diff --git a/Conf/lang.yaml b/Conf/lang.yaml index 1c581ea6ab..3a55cedcb2 100644 --- a/Conf/lang.yaml +++ b/Conf/lang.yaml @@ -23,6 +23,7 @@ ALGOL 68: ext: alg ALGOL W: ext: alg +ALGOL-M: AMPL: ANT: ANTLR: @@ -66,6 +67,7 @@ AspectC++: AspectJ: Assembly: ext: .as +Astro: Asymptote: AutoHotkey: ext: ahk @@ -81,6 +83,7 @@ BASIC256: BBC BASIC: BCPL: BML: +BaCon: Babel: ext: pb Batch File: @@ -126,6 +129,7 @@ Caché ObjectScript: CafeOBJ: Caml: Cat: +Category SETL4: Cduce: Cecil: Ceylon: @@ -148,6 +152,7 @@ CoffeeScript: ColdFusion: ext: cfm Comal: +Comefrom0x10: Commodore BASIC: Common Lisp: ext: lisp @@ -161,8 +166,11 @@ D: DCL: DDNC: DIV Games Studio: +DM: DMS: +DUP: DWScript: +Dafny: Dao: Dart: Datalog: @@ -260,6 +268,7 @@ GML: GUISS: GW-BASIC: Gambas: +Gastona: Gdl: Gecho: Gema: @@ -280,6 +289,7 @@ HLA: HPPPL: HQ9+: Hack: +Halon: Harbour: Haskell: ext: hs @@ -294,6 +304,7 @@ HyperTalk: ext: ht I: IDL: +IWBASIC: Icon: Idris: Inform 6: @@ -323,7 +334,7 @@ JavaScript: Jcon: JoCaml: Joy: -jq: +Jq: JudoScript: Julia: K: @@ -353,6 +364,7 @@ LaTeX: ext: tex LabVIEW: Lambda Prolog: +Lambdatalk: Lang5: Lasso: Leon: @@ -406,6 +418,7 @@ MS SQL: MSSQL: ext: sql MSX BASIC: +MSX Basic: MUF: MUMPS: Make: @@ -428,6 +441,7 @@ Modula-3: ext: mod3 Mond: Monicelli: +Monkey: Monte: MoonScript: Moonscript: @@ -438,6 +452,7 @@ MyrtleScript: Mython: Mythryl: N/t/roff: +NASL: NESL: NGS: NQP: @@ -457,6 +472,8 @@ Nimrod: Nit: Niue: Nix: +OASYS: +OASYS Assembler: OCaml: OOC: OOCalc: @@ -492,6 +509,7 @@ PASM: PDP-11 Assembly: PHL: PHP: +PILOT: PIR: PL/I: ext: pli @@ -528,6 +546,7 @@ Piet: Pike: PlainTeX: ext: tex +Plan: Pony: Pop11: PostScript: @@ -604,6 +623,7 @@ SNUSP: SPAD: SPARC Assembly: SPARK: +SPL: SQL: SSEM: Sage: @@ -624,17 +644,20 @@ Seed7: Self: SequenceL: Set lang: +Setl4: SheerPower 4GL: ext: 4gl Shen: Shiny: Sidef: Simula: +Sinclair ZX81 BASIC: Sisal: SkookumScript: Slate: Smalltalk: ext: st +Smart BASIC: SmileBASIC: Snobol: ext: sno @@ -647,6 +670,7 @@ Squirrel: Standard ML: ext: ml Star: +Stata: StreamIt: Suneido: SuperCollider: @@ -668,6 +692,7 @@ TXR: Tcl: run: tclsh %f TeLa: +TechBASIC: Teco: Terra: TestML: @@ -676,6 +701,7 @@ Thyrd: ToffeeScript: Toka: TorqueScript: +TransFORTH: Transact-SQL: ext: sql Trith: @@ -716,10 +742,12 @@ Visual Objects: ext: vobj Visual Prolog: ext: pro +Viua VM assembly: Vorpal: Vox: WML: Wart: +WebAssembly: Whenever: Whitespace: ext: ws diff --git a/Lang/0815/99-Bottles-of-Beer b/Lang/0815/99-Bottles-of-Beer deleted file mode 120000 index a429d71bfe..0000000000 --- a/Lang/0815/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/0815 \ No newline at end of file diff --git a/Lang/360-Assembly/ABC-Problem b/Lang/360-Assembly/ABC-Problem new file mode 120000 index 0000000000..8599877991 --- /dev/null +++ b/Lang/360-Assembly/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Binary-search b/Lang/360-Assembly/Binary-search new file mode 120000 index 0000000000..c3ea817d07 --- /dev/null +++ b/Lang/360-Assembly/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Bitwise-operations b/Lang/360-Assembly/Bitwise-operations new file mode 120000 index 0000000000..962dd20103 --- /dev/null +++ b/Lang/360-Assembly/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Calendar---for-REAL-programmers b/Lang/360-Assembly/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..98444f9de6 --- /dev/null +++ b/Lang/360-Assembly/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Call-a-function b/Lang/360-Assembly/Call-a-function new file mode 120000 index 0000000000..54b542d4fe --- /dev/null +++ b/Lang/360-Assembly/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Casting-out-nines b/Lang/360-Assembly/Casting-out-nines new file mode 120000 index 0000000000..b1218c77c6 --- /dev/null +++ b/Lang/360-Assembly/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Character-codes b/Lang/360-Assembly/Character-codes new file mode 120000 index 0000000000..983477960b --- /dev/null +++ b/Lang/360-Assembly/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Closest-pair-problem b/Lang/360-Assembly/Closest-pair-problem new file mode 120000 index 0000000000..098620188c --- /dev/null +++ b/Lang/360-Assembly/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Comma-quibbling b/Lang/360-Assembly/Comma-quibbling new file mode 120000 index 0000000000..880ece4b5b --- /dev/null +++ b/Lang/360-Assembly/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Compile-time-calculation b/Lang/360-Assembly/Compile-time-calculation new file mode 120000 index 0000000000..09ff80434c --- /dev/null +++ b/Lang/360-Assembly/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Copy-a-string b/Lang/360-Assembly/Copy-a-string new file mode 120000 index 0000000000..144f1c2d46 --- /dev/null +++ b/Lang/360-Assembly/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Count-in-factors b/Lang/360-Assembly/Count-in-factors new file mode 120000 index 0000000000..e09a7f6137 --- /dev/null +++ b/Lang/360-Assembly/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Create-an-HTML-table b/Lang/360-Assembly/Create-an-HTML-table new file mode 120000 index 0000000000..d97f2c2ec3 --- /dev/null +++ b/Lang/360-Assembly/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Digital-root b/Lang/360-Assembly/Digital-root new file mode 120000 index 0000000000..cf3d4c8cd5 --- /dev/null +++ b/Lang/360-Assembly/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Find-the-last-Sunday-of-each-month b/Lang/360-Assembly/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..f2c2f73fd4 --- /dev/null +++ b/Lang/360-Assembly/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/FizzBuzz b/Lang/360-Assembly/FizzBuzz deleted file mode 120000 index 264736e4d3..0000000000 --- a/Lang/360-Assembly/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Hamming-numbers b/Lang/360-Assembly/Hamming-numbers new file mode 120000 index 0000000000..f1733e53a3 --- /dev/null +++ b/Lang/360-Assembly/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Identity-matrix b/Lang/360-Assembly/Identity-matrix new file mode 120000 index 0000000000..af13f681a4 --- /dev/null +++ b/Lang/360-Assembly/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Integer-overflow b/Lang/360-Assembly/Integer-overflow new file mode 120000 index 0000000000..3afbf63c7a --- /dev/null +++ b/Lang/360-Assembly/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Josephus-problem b/Lang/360-Assembly/Josephus-problem new file mode 120000 index 0000000000..06e8e28269 --- /dev/null +++ b/Lang/360-Assembly/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Kaprekar-numbers b/Lang/360-Assembly/Kaprekar-numbers new file mode 120000 index 0000000000..730d694374 --- /dev/null +++ b/Lang/360-Assembly/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Knapsack-problem-0-1 b/Lang/360-Assembly/Knapsack-problem-0-1 new file mode 120000 index 0000000000..34d7cd5470 --- /dev/null +++ b/Lang/360-Assembly/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Knapsack-problem-Unbounded b/Lang/360-Assembly/Knapsack-problem-Unbounded new file mode 120000 index 0000000000..fa558813ee --- /dev/null +++ b/Lang/360-Assembly/Knapsack-problem-Unbounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Unbounded/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Knights-tour b/Lang/360-Assembly/Knights-tour new file mode 120000 index 0000000000..11f80b8f8a --- /dev/null +++ b/Lang/360-Assembly/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Last-Friday-of-each-month b/Lang/360-Assembly/Last-Friday-of-each-month new file mode 120000 index 0000000000..fd8ad324f2 --- /dev/null +++ b/Lang/360-Assembly/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Linear-congruential-generator b/Lang/360-Assembly/Linear-congruential-generator new file mode 120000 index 0000000000..622017c0e5 --- /dev/null +++ b/Lang/360-Assembly/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Logical-operations b/Lang/360-Assembly/Logical-operations new file mode 120000 index 0000000000..9e939ec3d6 --- /dev/null +++ b/Lang/360-Assembly/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Longest-increasing-subsequence b/Lang/360-Assembly/Longest-increasing-subsequence new file mode 120000 index 0000000000..9b29b328ec --- /dev/null +++ b/Lang/360-Assembly/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Loop-over-multiple-arrays-simultaneously b/Lang/360-Assembly/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..78dcc0738c --- /dev/null +++ b/Lang/360-Assembly/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Loops-Break b/Lang/360-Assembly/Loops-Break new file mode 120000 index 0000000000..87235e765b --- /dev/null +++ b/Lang/360-Assembly/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Monte-Carlo-methods b/Lang/360-Assembly/Monte-Carlo-methods new file mode 120000 index 0000000000..b1dac2b557 --- /dev/null +++ b/Lang/360-Assembly/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Number-names b/Lang/360-Assembly/Number-names new file mode 120000 index 0000000000..d2d3358a8c --- /dev/null +++ b/Lang/360-Assembly/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Permutations-Derangements b/Lang/360-Assembly/Permutations-Derangements new file mode 120000 index 0000000000..afba0e1db0 --- /dev/null +++ b/Lang/360-Assembly/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Primality-by-trial-division b/Lang/360-Assembly/Primality-by-trial-division new file mode 120000 index 0000000000..6d3b7b3d03 --- /dev/null +++ b/Lang/360-Assembly/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Semiprime b/Lang/360-Assembly/Semiprime new file mode 120000 index 0000000000..c7b741504d --- /dev/null +++ b/Lang/360-Assembly/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Singly-linked-list-Element-definition b/Lang/360-Assembly/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..d0343d77ac --- /dev/null +++ b/Lang/360-Assembly/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Singly-linked-list-Element-insertion b/Lang/360-Assembly/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..8a3ae0df8f --- /dev/null +++ b/Lang/360-Assembly/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Soundex b/Lang/360-Assembly/Soundex new file mode 120000 index 0000000000..35ccf979d6 --- /dev/null +++ b/Lang/360-Assembly/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Standard-deviation b/Lang/360-Assembly/Standard-deviation deleted file mode 120000 index 6a3f3c840c..0000000000 --- a/Lang/360-Assembly/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/String-matching b/Lang/360-Assembly/String-matching new file mode 120000 index 0000000000..5655637f2f --- /dev/null +++ b/Lang/360-Assembly/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Substring-Top-and-tail b/Lang/360-Assembly/Substring-Top-and-tail new file mode 120000 index 0000000000..e3ddda9392 --- /dev/null +++ b/Lang/360-Assembly/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Sum-and-product-of-an-array b/Lang/360-Assembly/Sum-and-product-of-an-array new file mode 120000 index 0000000000..42262d0547 --- /dev/null +++ b/Lang/360-Assembly/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Sum-of-a-series b/Lang/360-Assembly/Sum-of-a-series new file mode 120000 index 0000000000..42a4d62d19 --- /dev/null +++ b/Lang/360-Assembly/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Van-der-Corput-sequence b/Lang/360-Assembly/Van-der-Corput-sequence new file mode 120000 index 0000000000..52d4e47360 --- /dev/null +++ b/Lang/360-Assembly/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Word-wrap b/Lang/360-Assembly/Word-wrap new file mode 120000 index 0000000000..4f169eb98a --- /dev/null +++ b/Lang/360-Assembly/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Zeckendorf-number-representation b/Lang/360-Assembly/Zeckendorf-number-representation new file mode 120000 index 0000000000..aa3cd0c9ad --- /dev/null +++ b/Lang/360-Assembly/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/360-Assembly \ No newline at end of file diff --git a/Lang/6502-Assembly/99-Bottles-of-Beer b/Lang/6502-Assembly/99-Bottles-of-Beer deleted file mode 120000 index 84b3c4532d..0000000000 --- a/Lang/6502-Assembly/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/6502-Assembly \ No newline at end of file diff --git a/Lang/6502-Assembly/Binary-digits b/Lang/6502-Assembly/Binary-digits new file mode 120000 index 0000000000..34335be109 --- /dev/null +++ b/Lang/6502-Assembly/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/6502-Assembly \ No newline at end of file diff --git a/Lang/6502-Assembly/FizzBuzz b/Lang/6502-Assembly/FizzBuzz deleted file mode 120000 index 18a406b701..0000000000 --- a/Lang/6502-Assembly/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/6502-Assembly \ No newline at end of file diff --git a/Lang/6502-Assembly/Terminal-control-Clear-the-screen b/Lang/6502-Assembly/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..1edd77c498 --- /dev/null +++ b/Lang/6502-Assembly/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/6502-Assembly \ No newline at end of file diff --git a/Lang/6502-Assembly/Terminal-control-Inverse-video b/Lang/6502-Assembly/Terminal-control-Inverse-video new file mode 120000 index 0000000000..987d274b05 --- /dev/null +++ b/Lang/6502-Assembly/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/6502-Assembly \ No newline at end of file diff --git a/Lang/6800-Assembly/99-Bottles-of-Beer b/Lang/6800-Assembly/99-Bottles-of-Beer deleted file mode 120000 index 3bcad38294..0000000000 --- a/Lang/6800-Assembly/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/6800-Assembly \ No newline at end of file diff --git a/Lang/68000-Assembly/Execute-Brain---- b/Lang/68000-Assembly/Execute-Brain---- new file mode 120000 index 0000000000..d5efeaee0b --- /dev/null +++ b/Lang/68000-Assembly/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/68000-Assembly \ No newline at end of file diff --git a/Lang/8086-Assembly/FizzBuzz b/Lang/8086-Assembly/FizzBuzz deleted file mode 120000 index 38c9a8868b..0000000000 --- a/Lang/8086-Assembly/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/8086-Assembly \ No newline at end of file diff --git a/Lang/8th/00DESCRIPTION b/Lang/8th/00DESCRIPTION index 5000115cc8..84b050f8a0 100644 --- a/Lang/8th/00DESCRIPTION +++ b/Lang/8th/00DESCRIPTION @@ -1,6 +1,6 @@ {{language|8th -|site=http://8th-dev.com +|site=https://8th-dev.com |untyped=no |exec=both |gc=yes @@ -23,4 +23,5 @@ Some of its features include: * Easy cross-platform GUI * FFI (call native libraries) * Built-in networking (sockets, http etc) +* Built-in high-end encryption * Lots of other things... [http://8th-dev.com see the website] for more information. \ No newline at end of file diff --git a/Lang/8th/ABC-Problem b/Lang/8th/ABC-Problem new file mode 120000 index 0000000000..3eea47ee63 --- /dev/null +++ b/Lang/8th/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/8th \ No newline at end of file diff --git a/Lang/8th/Anagrams b/Lang/8th/Anagrams new file mode 120000 index 0000000000..9571dd7242 --- /dev/null +++ b/Lang/8th/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/8th \ No newline at end of file diff --git a/Lang/8th/Benfords-law b/Lang/8th/Benfords-law new file mode 120000 index 0000000000..63b8647396 --- /dev/null +++ b/Lang/8th/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/8th \ No newline at end of file diff --git a/Lang/8th/Caesar-cipher b/Lang/8th/Caesar-cipher new file mode 120000 index 0000000000..996ad189f9 --- /dev/null +++ b/Lang/8th/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/8th \ No newline at end of file diff --git a/Lang/8th/Happy-numbers b/Lang/8th/Happy-numbers new file mode 120000 index 0000000000..b081d67d19 --- /dev/null +++ b/Lang/8th/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/8th \ No newline at end of file diff --git a/Lang/ABAP/Fibonacci-sequence b/Lang/ABAP/Fibonacci-sequence new file mode 120000 index 0000000000..53db1753a5 --- /dev/null +++ b/Lang/ABAP/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/ABAP \ No newline at end of file diff --git a/Lang/ACL2/99-Bottles-of-Beer b/Lang/ACL2/99-Bottles-of-Beer deleted file mode 120000 index c798847c1a..0000000000 --- a/Lang/ACL2/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/File-IO b/Lang/ACL2/File-IO deleted file mode 120000 index da5caed497..0000000000 --- a/Lang/ACL2/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/ACL2 \ No newline at end of file diff --git a/Lang/ALGOL-68/Benfords-law b/Lang/ALGOL-68/Benfords-law new file mode 120000 index 0000000000..b724e5529f --- /dev/null +++ b/Lang/ALGOL-68/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Bernoulli-numbers b/Lang/ALGOL-68/Bernoulli-numbers new file mode 120000 index 0000000000..e32a379ca7 --- /dev/null +++ b/Lang/ALGOL-68/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Calendar---for-real-programmers b/Lang/ALGOL-68/Calendar---for-real-programmers deleted file mode 120000 index 58b7604557..0000000000 --- a/Lang/ALGOL-68/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Character-matching b/Lang/ALGOL-68/Character-matching deleted file mode 120000 index 1e794d2bb2..0000000000 --- a/Lang/ALGOL-68/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/File-IO b/Lang/ALGOL-68/File-IO deleted file mode 120000 index 25da6d4ee9..0000000000 --- a/Lang/ALGOL-68/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Guess-the-number-With-feedback--player- b/Lang/ALGOL-68/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..33489bae28 --- /dev/null +++ b/Lang/ALGOL-68/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Langtons-ant b/Lang/ALGOL-68/Langtons-ant new file mode 120000 index 0000000000..d0f764aace --- /dev/null +++ b/Lang/ALGOL-68/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Largest-int-from-concatenated-ints b/Lang/ALGOL-68/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..2c0e4e307b --- /dev/null +++ b/Lang/ALGOL-68/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Left-factorials b/Lang/ALGOL-68/Left-factorials new file mode 120000 index 0000000000..dc69888dbb --- /dev/null +++ b/Lang/ALGOL-68/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/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/Multisplit b/Lang/ALGOL-68/Multisplit new file mode 120000 index 0000000000..216f713ce7 --- /dev/null +++ b/Lang/ALGOL-68/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Parsing-Shunting-yard-algorithm b/Lang/ALGOL-68/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..e7afecfd74 --- /dev/null +++ b/Lang/ALGOL-68/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Quickselect-algorithm b/Lang/ALGOL-68/Quickselect-algorithm new file mode 120000 index 0000000000..52c8b33904 --- /dev/null +++ b/Lang/ALGOL-68/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Remove-lines-from-a-file b/Lang/ALGOL-68/Remove-lines-from-a-file new file mode 120000 index 0000000000..b3a066524e --- /dev/null +++ b/Lang/ALGOL-68/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Rosetta-Code-Rank-languages-by-popularity b/Lang/ALGOL-68/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 65acf74bf3..0000000000 --- a/Lang/ALGOL-68/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Standard-deviation b/Lang/ALGOL-68/Standard-deviation deleted file mode 120000 index e1f4b79efc..0000000000 --- a/Lang/ALGOL-68/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Trabb-Pardo-Knuth-algorithm b/Lang/ALGOL-68/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..f90900a9ec --- /dev/null +++ b/Lang/ALGOL-68/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-M/00DESCRIPTION b/Lang/ALGOL-M/00DESCRIPTION new file mode 100644 index 0000000000..542aac3a94 --- /dev/null +++ b/Lang/ALGOL-M/00DESCRIPTION @@ -0,0 +1,2 @@ +{{stub}}{{language|ALGOL-M}} +[[ALGOL]] for microcomputers (specifically the 8080), developed in 1976-77 by John P. Flynn and Mark S. Moranville. Based on [[ALGOL 60]]. It was the first structured programming language for a microcomputer. Compiled to virtual machine code. \ No newline at end of file diff --git a/Lang/ALGOL-M/Factorial b/Lang/ALGOL-M/Factorial new file mode 120000 index 0000000000..c866c1b715 --- /dev/null +++ b/Lang/ALGOL-M/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/ALGOL-M \ No newline at end of file diff --git a/Lang/ALGOL-M/Fibonacci-sequence b/Lang/ALGOL-M/Fibonacci-sequence new file mode 120000 index 0000000000..761f9540db --- /dev/null +++ b/Lang/ALGOL-M/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/ALGOL-M \ No newline at end of file diff --git a/Lang/ALGOL-M/Function-definition b/Lang/ALGOL-M/Function-definition new file mode 120000 index 0000000000..bfeab4c3a0 --- /dev/null +++ b/Lang/ALGOL-M/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/ALGOL-M \ No newline at end of file diff --git a/Lang/ALGOL-M/Hello-world-Text b/Lang/ALGOL-M/Hello-world-Text new file mode 120000 index 0000000000..cc7cc68d26 --- /dev/null +++ b/Lang/ALGOL-M/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/ALGOL-M \ No newline at end of file diff --git a/Lang/ALGOL-M/Loops-For b/Lang/ALGOL-M/Loops-For new file mode 120000 index 0000000000..916e2e1970 --- /dev/null +++ b/Lang/ALGOL-M/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/ALGOL-M \ No newline at end of file diff --git a/Lang/ALGOL-M/Loops-For-with-a-specified-step b/Lang/ALGOL-M/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..5780fadad9 --- /dev/null +++ b/Lang/ALGOL-M/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/ALGOL-M \ No newline at end of file diff --git a/Lang/ALGOL-M/Loops-While b/Lang/ALGOL-M/Loops-While new file mode 120000 index 0000000000..46943d79de --- /dev/null +++ b/Lang/ALGOL-M/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/ALGOL-M \ No newline at end of file diff --git a/Lang/ALGOL-M/README b/Lang/ALGOL-M/README new file mode 100644 index 0000000000..a25c1a76af --- /dev/null +++ b/Lang/ALGOL-M/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:ALGOL-M diff --git a/Lang/ALGOL-M/Temperature-conversion b/Lang/ALGOL-M/Temperature-conversion new file mode 120000 index 0000000000..cfd04ccd8b --- /dev/null +++ b/Lang/ALGOL-M/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/ALGOL-M \ No newline at end of file diff --git a/Lang/ALGOL-W/00DESCRIPTION b/Lang/ALGOL-W/00DESCRIPTION index c03423d718..c3aa2a2bbe 100644 --- a/Lang/ALGOL-W/00DESCRIPTION +++ b/Lang/ALGOL-W/00DESCRIPTION @@ -30,6 +30,5 @@ and Hendrik Boom's [http://mtn-host.prjek.net/projects/a68h/ A68H] ==See also== *[[ALGOL 60]] *[[ALGOL 68]] -== Code Specimen == {{language programming paradigm|Concurrent}} {{stub}} \ No newline at end of file diff --git a/Lang/ALGOL-W/Arithmetic-Integer b/Lang/ALGOL-W/Arithmetic-Integer new file mode 120000 index 0000000000..de259d015a --- /dev/null +++ b/Lang/ALGOL-W/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Array-concatenation b/Lang/ALGOL-W/Array-concatenation new file mode 120000 index 0000000000..fa2355aa8f --- /dev/null +++ b/Lang/ALGOL-W/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Arrays b/Lang/ALGOL-W/Arrays new file mode 120000 index 0000000000..b028f1f91f --- /dev/null +++ b/Lang/ALGOL-W/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Averages-Pythagorean-means b/Lang/ALGOL-W/Averages-Pythagorean-means new file mode 120000 index 0000000000..12790d9d43 --- /dev/null +++ b/Lang/ALGOL-W/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Bitwise-operations b/Lang/ALGOL-W/Bitwise-operations new file mode 120000 index 0000000000..2d3662d7d6 --- /dev/null +++ b/Lang/ALGOL-W/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Call-a-function b/Lang/ALGOL-W/Call-a-function new file mode 120000 index 0000000000..363499e24d --- /dev/null +++ b/Lang/ALGOL-W/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Catalan-numbers b/Lang/ALGOL-W/Catalan-numbers new file mode 120000 index 0000000000..58f13c18d0 --- /dev/null +++ b/Lang/ALGOL-W/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Catalan-numbers-Pascals-triangle b/Lang/ALGOL-W/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..36343bd443 --- /dev/null +++ b/Lang/ALGOL-W/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Compound-data-type b/Lang/ALGOL-W/Compound-data-type new file mode 120000 index 0000000000..9bf600bb82 --- /dev/null +++ b/Lang/ALGOL-W/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Count-in-octal b/Lang/ALGOL-W/Count-in-octal new file mode 120000 index 0000000000..e8cb3c7723 --- /dev/null +++ b/Lang/ALGOL-W/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Detect-division-by-zero b/Lang/ALGOL-W/Detect-division-by-zero new file mode 120000 index 0000000000..0ac0278a32 --- /dev/null +++ b/Lang/ALGOL-W/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Digital-root-Multiplicative-digital-root b/Lang/ALGOL-W/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..29583e8637 --- /dev/null +++ b/Lang/ALGOL-W/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Ethiopian-multiplication b/Lang/ALGOL-W/Ethiopian-multiplication new file mode 120000 index 0000000000..83572bba24 --- /dev/null +++ b/Lang/ALGOL-W/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Flow-control-structures b/Lang/ALGOL-W/Flow-control-structures new file mode 120000 index 0000000000..cdb0e32495 --- /dev/null +++ b/Lang/ALGOL-W/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Floyds-triangle b/Lang/ALGOL-W/Floyds-triangle new file mode 120000 index 0000000000..17580de300 --- /dev/null +++ b/Lang/ALGOL-W/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Hamming-numbers b/Lang/ALGOL-W/Hamming-numbers new file mode 120000 index 0000000000..7f7451592d --- /dev/null +++ b/Lang/ALGOL-W/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Input-loop b/Lang/ALGOL-W/Input-loop new file mode 120000 index 0000000000..3f0d16f208 --- /dev/null +++ b/Lang/ALGOL-W/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Leap-year b/Lang/ALGOL-W/Leap-year new file mode 120000 index 0000000000..0cfeec7aa5 --- /dev/null +++ b/Lang/ALGOL-W/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Literals-Integer b/Lang/ALGOL-W/Literals-Integer new file mode 120000 index 0000000000..83fb93d36e --- /dev/null +++ b/Lang/ALGOL-W/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Loops-Continue b/Lang/ALGOL-W/Loops-Continue new file mode 120000 index 0000000000..c7bb0e158c --- /dev/null +++ b/Lang/ALGOL-W/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Luhn-test-of-credit-card-numbers b/Lang/ALGOL-W/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..cc0b88854e --- /dev/null +++ b/Lang/ALGOL-W/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Memory-allocation b/Lang/ALGOL-W/Memory-allocation new file mode 120000 index 0000000000..cdbdac504e --- /dev/null +++ b/Lang/ALGOL-W/Memory-allocation @@ -0,0 +1 @@ +../../Task/Memory-allocation/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Middle-three-digits b/Lang/ALGOL-W/Middle-three-digits new file mode 120000 index 0000000000..9b3b7ff083 --- /dev/null +++ b/Lang/ALGOL-W/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Multifactorial b/Lang/ALGOL-W/Multifactorial new file mode 120000 index 0000000000..63078a3431 --- /dev/null +++ b/Lang/ALGOL-W/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Narcissistic-decimal-number b/Lang/ALGOL-W/Narcissistic-decimal-number new file mode 120000 index 0000000000..4f9f9aca50 --- /dev/null +++ b/Lang/ALGOL-W/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Non-decimal-radices-Output b/Lang/ALGOL-W/Non-decimal-radices-Output new file mode 120000 index 0000000000..6ea2380849 --- /dev/null +++ b/Lang/ALGOL-W/Non-decimal-radices-Output @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Output/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/One-dimensional-cellular-automata b/Lang/ALGOL-W/One-dimensional-cellular-automata new file mode 120000 index 0000000000..3b2d5deb3f --- /dev/null +++ b/Lang/ALGOL-W/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Pascals-triangle b/Lang/ALGOL-W/Pascals-triangle new file mode 120000 index 0000000000..4ffa9e9665 --- /dev/null +++ b/Lang/ALGOL-W/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Primality-by-trial-division b/Lang/ALGOL-W/Primality-by-trial-division new file mode 120000 index 0000000000..fe8b7baed4 --- /dev/null +++ b/Lang/ALGOL-W/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Program-termination b/Lang/ALGOL-W/Program-termination new file mode 120000 index 0000000000..317415be09 --- /dev/null +++ b/Lang/ALGOL-W/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Queue-Definition b/Lang/ALGOL-W/Queue-Definition new file mode 120000 index 0000000000..d8a0c44e36 --- /dev/null +++ b/Lang/ALGOL-W/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Real-constants-and-functions b/Lang/ALGOL-W/Real-constants-and-functions new file mode 120000 index 0000000000..be1c421def --- /dev/null +++ b/Lang/ALGOL-W/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/SEDOLs b/Lang/ALGOL-W/SEDOLs new file mode 120000 index 0000000000..50f856b16b --- /dev/null +++ b/Lang/ALGOL-W/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Sequence-of-primes-by-Trial-Division b/Lang/ALGOL-W/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..f7ceef6fe9 --- /dev/null +++ b/Lang/ALGOL-W/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Sorting-algorithms-Quicksort b/Lang/ALGOL-W/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..39e586afa2 --- /dev/null +++ b/Lang/ALGOL-W/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Special-variables b/Lang/ALGOL-W/Special-variables new file mode 120000 index 0000000000..fb74bb43d6 --- /dev/null +++ b/Lang/ALGOL-W/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Stack b/Lang/ALGOL-W/Stack new file mode 120000 index 0000000000..35f016945e --- /dev/null +++ b/Lang/ALGOL-W/Stack @@ -0,0 +1 @@ +../../Task/Stack/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Standard-deviation b/Lang/ALGOL-W/Standard-deviation deleted file mode 120000 index 745c6dedc7..0000000000 --- a/Lang/ALGOL-W/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/User-input-Text b/Lang/ALGOL-W/User-input-Text new file mode 120000 index 0000000000..ac031c566d --- /dev/null +++ b/Lang/ALGOL-W/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL/00DESCRIPTION b/Lang/ALGOL/00DESCRIPTION index a332fceac0..bd10ee70ac 100644 --- a/Lang/ALGOL/00DESCRIPTION +++ b/Lang/ALGOL/00DESCRIPTION @@ -2,6 +2,7 @@ ==See Also== * [[ALGOL 60]] * [[ALGOL 68]] +* [[ALGOL-M]] * [[ALGOL W]]
* [[JOVIAL]] diff --git a/Lang/ANTLR/A+B b/Lang/ANTLR/A+B deleted file mode 120000 index d8dee80ad6..0000000000 --- a/Lang/ANTLR/A+B +++ /dev/null @@ -1 +0,0 @@ -../../Task/A+B/ANTLR \ No newline at end of file diff --git a/Lang/APL/24-game b/Lang/APL/24-game new file mode 120000 index 0000000000..86e47d3e7f --- /dev/null +++ b/Lang/APL/24-game @@ -0,0 +1 @@ +../../Task/24-game/APL \ No newline at end of file diff --git a/Lang/APL/A+B b/Lang/APL/A+B new file mode 120000 index 0000000000..4528ae7e18 --- /dev/null +++ b/Lang/APL/A+B @@ -0,0 +1 @@ +../../Task/A+B/APL \ No newline at end of file diff --git a/Lang/APL/ABC-Problem b/Lang/APL/ABC-Problem new file mode 120000 index 0000000000..b786d24409 --- /dev/null +++ b/Lang/APL/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/APL \ No newline at end of file diff --git a/Lang/APL/Arithmetic-geometric-mean b/Lang/APL/Arithmetic-geometric-mean new file mode 120000 index 0000000000..e315137ff2 --- /dev/null +++ b/Lang/APL/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/APL \ No newline at end of file diff --git a/Lang/APL/Filter b/Lang/APL/Filter new file mode 120000 index 0000000000..f1b91d4dec --- /dev/null +++ b/Lang/APL/Filter @@ -0,0 +1 @@ +../../Task/Filter/APL \ No newline at end of file diff --git a/Lang/APL/Leap-year b/Lang/APL/Leap-year new file mode 120000 index 0000000000..0ef471c3ed --- /dev/null +++ b/Lang/APL/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/APL \ No newline at end of file diff --git a/Lang/APL/Tree-traversal b/Lang/APL/Tree-traversal new file mode 120000 index 0000000000..62c075c6db --- /dev/null +++ b/Lang/APL/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/APL \ No newline at end of file diff --git a/Lang/ATS/Amicable-pairs b/Lang/ATS/Amicable-pairs new file mode 120000 index 0000000000..447814deb0 --- /dev/null +++ b/Lang/ATS/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/ATS \ No newline at end of file diff --git a/Lang/ATS/Middle-three-digits b/Lang/ATS/Middle-three-digits new file mode 120000 index 0000000000..b0317d4f43 --- /dev/null +++ b/Lang/ATS/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/ATS \ No newline at end of file diff --git a/Lang/ATS/Pangram-checker b/Lang/ATS/Pangram-checker new file mode 120000 index 0000000000..6019e3fb63 --- /dev/null +++ b/Lang/ATS/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/ATS \ No newline at end of file diff --git a/Lang/ATS/Playing-cards b/Lang/ATS/Playing-cards new file mode 120000 index 0000000000..57b047ce56 --- /dev/null +++ b/Lang/ATS/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/ATS \ No newline at end of file diff --git a/Lang/ATS/Primality-by-trial-division b/Lang/ATS/Primality-by-trial-division new file mode 120000 index 0000000000..fbef08b183 --- /dev/null +++ b/Lang/ATS/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/ATS \ No newline at end of file diff --git a/Lang/ATS/Y-combinator b/Lang/ATS/Y-combinator new file mode 120000 index 0000000000..56f957758c --- /dev/null +++ b/Lang/ATS/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/ATS \ No newline at end of file diff --git a/Lang/AWK/Assertions b/Lang/AWK/Assertions new file mode 120000 index 0000000000..6348e55972 --- /dev/null +++ b/Lang/AWK/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/AWK \ No newline at end of file diff --git a/Lang/AWK/Dinesmans-multiple-dwelling-problem b/Lang/AWK/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..7a0d42344c --- /dev/null +++ b/Lang/AWK/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/AWK \ No newline at end of file diff --git a/Lang/AWK/Empty-directory b/Lang/AWK/Empty-directory new file mode 120000 index 0000000000..3a71cabbba --- /dev/null +++ b/Lang/AWK/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/AWK \ No newline at end of file diff --git a/Lang/AWK/Evaluate-binomial-coefficients b/Lang/AWK/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..24f8ca83bf --- /dev/null +++ b/Lang/AWK/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/AWK \ No newline at end of file diff --git a/Lang/AWK/File-IO b/Lang/AWK/File-IO deleted file mode 120000 index f969ee76a9..0000000000 --- a/Lang/AWK/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/AWK \ No newline at end of file diff --git a/Lang/AWK/FizzBuzz b/Lang/AWK/FizzBuzz deleted file mode 120000 index bc077ca36a..0000000000 --- a/Lang/AWK/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/AWK \ No newline at end of file diff --git a/Lang/AWK/Hash-join b/Lang/AWK/Hash-join new file mode 120000 index 0000000000..3325911eb8 --- /dev/null +++ b/Lang/AWK/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/AWK \ No newline at end of file diff --git a/Lang/AWK/Hofstadter-Figure-Figure-sequences b/Lang/AWK/Hofstadter-Figure-Figure-sequences new file mode 120000 index 0000000000..0c212a8b38 --- /dev/null +++ b/Lang/AWK/Hofstadter-Figure-Figure-sequences @@ -0,0 +1 @@ +../../Task/Hofstadter-Figure-Figure-sequences/AWK \ No newline at end of file diff --git a/Lang/AWK/Interactive-programming b/Lang/AWK/Interactive-programming new file mode 120000 index 0000000000..21d2462980 --- /dev/null +++ b/Lang/AWK/Interactive-programming @@ -0,0 +1 @@ +../../Task/Interactive-programming/AWK \ No newline at end of file diff --git a/Lang/AWK/Knapsack-problem-0-1 b/Lang/AWK/Knapsack-problem-0-1 new file mode 120000 index 0000000000..ede2a5b771 --- /dev/null +++ b/Lang/AWK/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/AWK \ No newline at end of file diff --git a/Lang/AWK/Knapsack-problem-Continuous b/Lang/AWK/Knapsack-problem-Continuous new file mode 120000 index 0000000000..5dad7b9026 --- /dev/null +++ b/Lang/AWK/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/AWK \ No newline at end of file diff --git a/Lang/AWK/Program-name b/Lang/AWK/Program-name new file mode 120000 index 0000000000..ccb3f40308 --- /dev/null +++ b/Lang/AWK/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/AWK \ No newline at end of file diff --git a/Lang/AWK/Rosetta-Code-Rank-languages-by-popularity b/Lang/AWK/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index c0bfd6a30c..0000000000 --- a/Lang/AWK/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/AWK \ No newline at end of file diff --git a/Lang/AWK/Stair-climbing-puzzle b/Lang/AWK/Stair-climbing-puzzle new file mode 120000 index 0000000000..20936bd3e7 --- /dev/null +++ b/Lang/AWK/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/AWK \ No newline at end of file diff --git a/Lang/AWK/Standard-deviation b/Lang/AWK/Standard-deviation deleted file mode 120000 index 1588b4214c..0000000000 --- a/Lang/AWK/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/AWK \ No newline at end of file diff --git a/Lang/AWK/Truncate-a-file b/Lang/AWK/Truncate-a-file new file mode 120000 index 0000000000..186c208d06 --- /dev/null +++ b/Lang/AWK/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/AWK \ No newline at end of file diff --git a/Lang/ActionScript/Sieve-of-Eratosthenes b/Lang/ActionScript/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..48f30a1eec --- /dev/null +++ b/Lang/ActionScript/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/ActionScript \ No newline at end of file diff --git a/Lang/Ada/Calendar---for-real-programmers b/Lang/Ada/Calendar---for-real-programmers deleted file mode 120000 index 61ff6f00d1..0000000000 --- a/Lang/Ada/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/Ada \ No newline at end of file diff --git a/Lang/Ada/Character-matching b/Lang/Ada/Character-matching deleted file mode 120000 index e7b13e9087..0000000000 --- a/Lang/Ada/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Ada \ No newline at end of file diff --git a/Lang/Ada/File-IO b/Lang/Ada/File-IO deleted file mode 120000 index a1bb43fdee..0000000000 --- a/Lang/Ada/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/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/Mutex b/Lang/Ada/Mutex deleted file mode 120000 index e421aae300..0000000000 --- a/Lang/Ada/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Ada \ No newline at end of file diff --git a/Lang/Ada/Rosetta-Code-Count-examples b/Lang/Ada/Rosetta-Code-Count-examples deleted file mode 120000 index a912071c5c..0000000000 --- a/Lang/Ada/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Ada \ No newline at end of file diff --git a/Lang/Ada/Rosetta-Code-Find-unimplemented-tasks b/Lang/Ada/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index 8441e9c78f..0000000000 --- a/Lang/Ada/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/Ada \ No newline at end of file diff --git a/Lang/Ada/Rosetta-Code-Rank-languages-by-popularity b/Lang/Ada/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 14bfc6c8b8..0000000000 --- a/Lang/Ada/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Ada \ No newline at end of file diff --git a/Lang/Ada/Standard-deviation b/Lang/Ada/Standard-deviation deleted file mode 120000 index b42c70390d..0000000000 --- a/Lang/Ada/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Ada \ No newline at end of file diff --git a/Lang/Agda/Ackermann-function b/Lang/Agda/Ackermann-function new file mode 120000 index 0000000000..a451f0cde4 --- /dev/null +++ b/Lang/Agda/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Agda \ No newline at end of file diff --git a/Lang/Agda2/Reverse-a-string b/Lang/Agda2/Reverse-a-string deleted file mode 120000 index 07d789c153..0000000000 --- a/Lang/Agda2/Reverse-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Reverse-a-string/Agda2 \ No newline at end of file diff --git a/Lang/Agena/A+B b/Lang/Agena/A+B new file mode 120000 index 0000000000..a8d2c3bbac --- /dev/null +++ b/Lang/Agena/A+B @@ -0,0 +1 @@ +../../Task/A+B/Agena \ No newline at end of file diff --git a/Lang/Agena/Execute-Brain---- b/Lang/Agena/Execute-Brain---- new file mode 120000 index 0000000000..122c83afbf --- /dev/null +++ b/Lang/Agena/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Agena \ No newline at end of file diff --git a/Lang/Agena/Hello-world-Newline-omission b/Lang/Agena/Hello-world-Newline-omission new file mode 120000 index 0000000000..0012d16bc0 --- /dev/null +++ b/Lang/Agena/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Agena \ No newline at end of file diff --git a/Lang/Agena/Hello-world-Standard-error b/Lang/Agena/Hello-world-Standard-error new file mode 120000 index 0000000000..34e774621f --- /dev/null +++ b/Lang/Agena/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Agena \ No newline at end of file diff --git a/Lang/Agena/Hello-world-Text b/Lang/Agena/Hello-world-Text new file mode 120000 index 0000000000..255022ba06 --- /dev/null +++ b/Lang/Agena/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Agena \ No newline at end of file diff --git a/Lang/Agena/Loops-Continue b/Lang/Agena/Loops-Continue new file mode 120000 index 0000000000..a80869d082 --- /dev/null +++ b/Lang/Agena/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Agena \ No newline at end of file diff --git a/Lang/Agena/Loops-Do-while b/Lang/Agena/Loops-Do-while new file mode 120000 index 0000000000..eafbb948fc --- /dev/null +++ b/Lang/Agena/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Agena \ No newline at end of file diff --git a/Lang/Agena/Loops-Downward-for b/Lang/Agena/Loops-Downward-for new file mode 120000 index 0000000000..01af21f50c --- /dev/null +++ b/Lang/Agena/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Agena \ No newline at end of file diff --git a/Lang/Agena/Loops-For b/Lang/Agena/Loops-For new file mode 120000 index 0000000000..0ae3c8bdd3 --- /dev/null +++ b/Lang/Agena/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Agena \ No newline at end of file diff --git a/Lang/Agena/Loops-For-with-a-specified-step b/Lang/Agena/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..bd6e988c45 --- /dev/null +++ b/Lang/Agena/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Agena \ No newline at end of file diff --git a/Lang/Agena/Loops-Infinite b/Lang/Agena/Loops-Infinite new file mode 120000 index 0000000000..0dc979e287 --- /dev/null +++ b/Lang/Agena/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Agena \ No newline at end of file diff --git a/Lang/Agena/Loops-While b/Lang/Agena/Loops-While new file mode 120000 index 0000000000..e53c2f45b7 --- /dev/null +++ b/Lang/Agena/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Agena \ No newline at end of file diff --git a/Lang/Agena/Multiplication-tables b/Lang/Agena/Multiplication-tables new file mode 120000 index 0000000000..02baa9f50b --- /dev/null +++ b/Lang/Agena/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Agena \ No newline at end of file diff --git a/Lang/Agena/Narcissistic-decimal-number b/Lang/Agena/Narcissistic-decimal-number new file mode 120000 index 0000000000..4d8f324709 --- /dev/null +++ b/Lang/Agena/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Agena \ No newline at end of file diff --git a/Lang/Agena/Return-multiple-values b/Lang/Agena/Return-multiple-values new file mode 120000 index 0000000000..7b33982845 --- /dev/null +++ b/Lang/Agena/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Agena \ No newline at end of file diff --git a/Lang/Agena/Trabb-Pardo-Knuth-algorithm b/Lang/Agena/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..6b2edf8ffd --- /dev/null +++ b/Lang/Agena/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Agena \ No newline at end of file diff --git a/Lang/Aime/Array-concatenation b/Lang/Aime/Array-concatenation new file mode 120000 index 0000000000..dca0f85b8e --- /dev/null +++ b/Lang/Aime/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Aime \ No newline at end of file diff --git a/Lang/Aime/Averages-Arithmetic-mean b/Lang/Aime/Averages-Arithmetic-mean new file mode 120000 index 0000000000..7f2f73f061 --- /dev/null +++ b/Lang/Aime/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Aime \ No newline at end of file diff --git a/Lang/Aime/CSV-data-manipulation b/Lang/Aime/CSV-data-manipulation new file mode 120000 index 0000000000..938d8790ed --- /dev/null +++ b/Lang/Aime/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Aime \ No newline at end of file diff --git a/Lang/Aime/Case-sensitivity-of-identifiers b/Lang/Aime/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..0af2aa867d --- /dev/null +++ b/Lang/Aime/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Aime \ No newline at end of file diff --git a/Lang/Aime/Dot-product b/Lang/Aime/Dot-product new file mode 120000 index 0000000000..56b456cfc7 --- /dev/null +++ b/Lang/Aime/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Aime \ No newline at end of file diff --git a/Lang/Aime/Echo-server b/Lang/Aime/Echo-server new file mode 120000 index 0000000000..f1629bc140 --- /dev/null +++ b/Lang/Aime/Echo-server @@ -0,0 +1 @@ +../../Task/Echo-server/Aime \ No newline at end of file diff --git a/Lang/Aime/Fibonacci-word b/Lang/Aime/Fibonacci-word new file mode 120000 index 0000000000..68b9df78f4 --- /dev/null +++ b/Lang/Aime/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Aime \ No newline at end of file diff --git a/Lang/Aime/File-IO b/Lang/Aime/File-IO deleted file mode 120000 index 757f42f07e..0000000000 --- a/Lang/Aime/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Aime \ No newline at end of file diff --git a/Lang/Aime/Find-the-missing-permutation b/Lang/Aime/Find-the-missing-permutation new file mode 120000 index 0000000000..2e13e96c79 --- /dev/null +++ b/Lang/Aime/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Aime \ No newline at end of file diff --git a/Lang/Aime/Hello-world-Web-server b/Lang/Aime/Hello-world-Web-server new file mode 120000 index 0000000000..03fdf3b45b --- /dev/null +++ b/Lang/Aime/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Aime \ No newline at end of file diff --git a/Lang/Aime/Largest-int-from-concatenated-ints b/Lang/Aime/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..b0a222dc98 --- /dev/null +++ b/Lang/Aime/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Aime \ No newline at end of file diff --git a/Lang/Aime/Long-multiplication b/Lang/Aime/Long-multiplication new file mode 120000 index 0000000000..bdcd997dd5 --- /dev/null +++ b/Lang/Aime/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/Aime \ No newline at end of file diff --git a/Lang/Aime/Order-disjoint-list-items b/Lang/Aime/Order-disjoint-list-items new file mode 120000 index 0000000000..bbedc0d3ec --- /dev/null +++ b/Lang/Aime/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Aime \ No newline at end of file diff --git a/Lang/Aime/Read-a-configuration-file b/Lang/Aime/Read-a-configuration-file new file mode 120000 index 0000000000..c5d27c6b3c --- /dev/null +++ b/Lang/Aime/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Aime \ No newline at end of file diff --git a/Lang/Aime/Repeat-a-string b/Lang/Aime/Repeat-a-string new file mode 120000 index 0000000000..6bc5c05e6f --- /dev/null +++ b/Lang/Aime/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Aime \ No newline at end of file diff --git a/Lang/Aime/Set b/Lang/Aime/Set new file mode 120000 index 0000000000..a0ff07a5ee --- /dev/null +++ b/Lang/Aime/Set @@ -0,0 +1 @@ +../../Task/Set/Aime \ No newline at end of file diff --git a/Lang/Algae/99-Bottles-of-Beer b/Lang/Algae/99-Bottles-of-Beer new file mode 120000 index 0000000000..d9b41f1b2d --- /dev/null +++ b/Lang/Algae/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Algae \ No newline at end of file diff --git a/Lang/Apex/FizzBuzz b/Lang/Apex/FizzBuzz new file mode 120000 index 0000000000..9db4b8a370 --- /dev/null +++ b/Lang/Apex/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Apex \ No newline at end of file diff --git a/Lang/AppleScript/Averages-Root-mean-square b/Lang/AppleScript/Averages-Root-mean-square new file mode 120000 index 0000000000..4aadd784e6 --- /dev/null +++ b/Lang/AppleScript/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Check-that-file-exists b/Lang/AppleScript/Check-that-file-exists new file mode 120000 index 0000000000..752edaf89a --- /dev/null +++ b/Lang/AppleScript/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Comma-quibbling b/Lang/AppleScript/Comma-quibbling new file mode 120000 index 0000000000..f2daa4ebb6 --- /dev/null +++ b/Lang/AppleScript/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Equilibrium-index b/Lang/AppleScript/Equilibrium-index new file mode 120000 index 0000000000..3766656233 --- /dev/null +++ b/Lang/AppleScript/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/File-IO b/Lang/AppleScript/File-IO deleted file mode 120000 index e760928a7d..0000000000 --- a/Lang/AppleScript/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Floyds-triangle b/Lang/AppleScript/Floyds-triangle new file mode 120000 index 0000000000..54cc2b117b --- /dev/null +++ b/Lang/AppleScript/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Forward-difference b/Lang/AppleScript/Forward-difference new file mode 120000 index 0000000000..95f31b13d3 --- /dev/null +++ b/Lang/AppleScript/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Maximum-triangle-path-sum b/Lang/AppleScript/Maximum-triangle-path-sum new file mode 120000 index 0000000000..6b63a149f4 --- /dev/null +++ b/Lang/AppleScript/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Narcissistic-decimal-number b/Lang/AppleScript/Narcissistic-decimal-number new file mode 120000 index 0000000000..b678937901 --- /dev/null +++ b/Lang/AppleScript/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Non-decimal-radices-Convert b/Lang/AppleScript/Non-decimal-radices-Convert new file mode 120000 index 0000000000..c621d35654 --- /dev/null +++ b/Lang/AppleScript/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Partial-function-application b/Lang/AppleScript/Partial-function-application new file mode 120000 index 0000000000..cb89d8bf82 --- /dev/null +++ b/Lang/AppleScript/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Rep-string b/Lang/AppleScript/Rep-string new file mode 120000 index 0000000000..ae7f581857 --- /dev/null +++ b/Lang/AppleScript/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Sort-an-array-of-composite-structures b/Lang/AppleScript/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..3aabe6e739 --- /dev/null +++ b/Lang/AppleScript/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Sort-using-a-custom-comparator b/Lang/AppleScript/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..c3d69d9968 --- /dev/null +++ b/Lang/AppleScript/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Sum-of-squares b/Lang/AppleScript/Sum-of-squares new file mode 120000 index 0000000000..109934b20f --- /dev/null +++ b/Lang/AppleScript/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Topic-variable b/Lang/AppleScript/Topic-variable new file mode 120000 index 0000000000..b9d5dd762d --- /dev/null +++ b/Lang/AppleScript/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/AppleScript \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/99-Bottles-of-Beer b/Lang/Applesoft-BASIC/99-Bottles-of-Beer deleted file mode 120000 index cb96e37c7a..0000000000 --- a/Lang/Applesoft-BASIC/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Binary-digits b/Lang/Applesoft-BASIC/Binary-digits deleted file mode 120000 index cf5fd530fa..0000000000 --- a/Lang/Applesoft-BASIC/Binary-digits +++ /dev/null @@ -1 +0,0 @@ -../../Task/Binary-digits/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Detect-division-by-zero b/Lang/Applesoft-BASIC/Detect-division-by-zero deleted file mode 120000 index 09ac14a83a..0000000000 --- a/Lang/Applesoft-BASIC/Detect-division-by-zero +++ /dev/null @@ -1 +0,0 @@ -../../Task/Detect-division-by-zero/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Jump-anywhere b/Lang/Applesoft-BASIC/Jump-anywhere deleted file mode 120000 index 8b0e2c46be..0000000000 --- a/Lang/Applesoft-BASIC/Jump-anywhere +++ /dev/null @@ -1 +0,0 @@ -../../Task/Jump-anywhere/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Loops-Continue b/Lang/Applesoft-BASIC/Loops-Continue deleted file mode 120000 index 03727e8d35..0000000000 --- a/Lang/Applesoft-BASIC/Loops-Continue +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Continue/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Arc/Loops-Break b/Lang/Arc/Loops-Break new file mode 120000 index 0000000000..c5ae940657 --- /dev/null +++ b/Lang/Arc/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Arc \ No newline at end of file diff --git a/Lang/Astro/00DESCRIPTION b/Lang/Astro/00DESCRIPTION new file mode 100644 index 0000000000..86ec27c6f4 --- /dev/null +++ b/Lang/Astro/00DESCRIPTION @@ -0,0 +1,4 @@ +{{stub}}{{language|Astro}} +Astro is a high-performance statically-typed programming language that compiles to [[WebAssembly]], with syntax similar to [[Python]] and numerical-computing orientation similar to [[Julia]]. +Astro provides a sophisticated compiler with full type inference, compile-time garbage collection, and an extensive mathematical function library. +It pushes multiple dispatch as its primary paradigm but borrows from several other paradigms as well. It supports first-class types, functions and hygenic macros. \ No newline at end of file diff --git a/Lang/Astro/100-doors b/Lang/Astro/100-doors new file mode 120000 index 0000000000..e1e2bc8c1b --- /dev/null +++ b/Lang/Astro/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Astro \ No newline at end of file diff --git a/Lang/Astro/99-Bottles-of-Beer b/Lang/Astro/99-Bottles-of-Beer new file mode 120000 index 0000000000..95b586753d --- /dev/null +++ b/Lang/Astro/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Astro \ No newline at end of file diff --git a/Lang/Astro/ABC-Problem b/Lang/Astro/ABC-Problem new file mode 120000 index 0000000000..0c81476152 --- /dev/null +++ b/Lang/Astro/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Astro \ No newline at end of file diff --git a/Lang/Astro/Accumulator-factory b/Lang/Astro/Accumulator-factory new file mode 120000 index 0000000000..41129d79df --- /dev/null +++ b/Lang/Astro/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Astro \ No newline at end of file diff --git a/Lang/Astro/Address-of-a-variable b/Lang/Astro/Address-of-a-variable new file mode 120000 index 0000000000..fb40162901 --- /dev/null +++ b/Lang/Astro/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Astro \ No newline at end of file diff --git a/Lang/Astro/Averages-Arithmetic-mean b/Lang/Astro/Averages-Arithmetic-mean new file mode 120000 index 0000000000..0642abdc0d --- /dev/null +++ b/Lang/Astro/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Astro \ No newline at end of file diff --git a/Lang/Astro/Averages-Root-mean-square b/Lang/Astro/Averages-Root-mean-square new file mode 120000 index 0000000000..eedf0b8b84 --- /dev/null +++ b/Lang/Astro/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Astro \ No newline at end of file diff --git a/Lang/Astro/Caesar-cipher b/Lang/Astro/Caesar-cipher new file mode 120000 index 0000000000..9ab9493765 --- /dev/null +++ b/Lang/Astro/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Astro \ No newline at end of file diff --git a/Lang/Astro/Comma-quibbling b/Lang/Astro/Comma-quibbling new file mode 120000 index 0000000000..8f5e8d41ec --- /dev/null +++ b/Lang/Astro/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Astro \ No newline at end of file diff --git a/Lang/Astro/Concurrent-computing b/Lang/Astro/Concurrent-computing new file mode 120000 index 0000000000..2b759b5d30 --- /dev/null +++ b/Lang/Astro/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/Astro \ No newline at end of file diff --git a/Lang/Astro/Conditional-structures b/Lang/Astro/Conditional-structures new file mode 120000 index 0000000000..0ba21da1ee --- /dev/null +++ b/Lang/Astro/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Astro \ No newline at end of file diff --git a/Lang/Astro/Hello-world-Text b/Lang/Astro/Hello-world-Text new file mode 120000 index 0000000000..95aa60c8d4 --- /dev/null +++ b/Lang/Astro/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Astro \ No newline at end of file diff --git a/Lang/Astro/Integer-comparison b/Lang/Astro/Integer-comparison new file mode 120000 index 0000000000..523be70135 --- /dev/null +++ b/Lang/Astro/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Astro \ No newline at end of file diff --git a/Lang/Astro/Maximum-triangle-path-sum b/Lang/Astro/Maximum-triangle-path-sum new file mode 120000 index 0000000000..9c7ae1f401 --- /dev/null +++ b/Lang/Astro/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Astro \ No newline at end of file diff --git a/Lang/Astro/Number-reversal-game b/Lang/Astro/Number-reversal-game new file mode 120000 index 0000000000..6e9cd6d5f5 --- /dev/null +++ b/Lang/Astro/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Astro \ No newline at end of file diff --git a/Lang/Astro/Queue-Usage b/Lang/Astro/Queue-Usage new file mode 120000 index 0000000000..9378b95404 --- /dev/null +++ b/Lang/Astro/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/Astro \ No newline at end of file diff --git a/Lang/Astro/README b/Lang/Astro/README new file mode 100644 index 0000000000..5925a7f5e3 --- /dev/null +++ b/Lang/Astro/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Astro diff --git a/Lang/Astro/Read-a-file-line-by-line b/Lang/Astro/Read-a-file-line-by-line new file mode 120000 index 0000000000..8306c654e1 --- /dev/null +++ b/Lang/Astro/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Astro \ No newline at end of file diff --git a/Lang/Astro/SHA-1 b/Lang/Astro/SHA-1 new file mode 120000 index 0000000000..8193b2abd5 --- /dev/null +++ b/Lang/Astro/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Astro \ No newline at end of file diff --git a/Lang/Astro/Sorting-algorithms-Merge-sort b/Lang/Astro/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..c7a89d0977 --- /dev/null +++ b/Lang/Astro/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Astro \ No newline at end of file diff --git a/Lang/Astro/String-comparison b/Lang/Astro/String-comparison new file mode 120000 index 0000000000..7f53fd8dae --- /dev/null +++ b/Lang/Astro/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Astro \ No newline at end of file diff --git a/Lang/Astro/Tokenize-a-string b/Lang/Astro/Tokenize-a-string new file mode 120000 index 0000000000..f4d2f8ce23 --- /dev/null +++ b/Lang/Astro/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Astro \ No newline at end of file diff --git a/Lang/AutoHotkey/99-Bottles-of-Beer b/Lang/AutoHotkey/99-Bottles-of-Beer deleted file mode 120000 index d611bb82f4..0000000000 --- a/Lang/AutoHotkey/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Calendar---for-real-programmers b/Lang/AutoHotkey/Calendar---for-real-programmers deleted file mode 120000 index f36b0f14e6..0000000000 --- a/Lang/AutoHotkey/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Character-matching b/Lang/AutoHotkey/Character-matching deleted file mode 120000 index 8c9c3fdc94..0000000000 --- a/Lang/AutoHotkey/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/File-IO b/Lang/AutoHotkey/File-IO deleted file mode 120000 index f32410efe5..0000000000 --- a/Lang/AutoHotkey/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Maze-solving b/Lang/AutoHotkey/Maze-solving new file mode 120000 index 0000000000..4d082f7c23 --- /dev/null +++ b/Lang/AutoHotkey/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/AutoHotkey \ 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/Rosetta-Code-Count-examples b/Lang/AutoHotkey/Rosetta-Code-Count-examples deleted file mode 120000 index 0b1de8c223..0000000000 --- a/Lang/AutoHotkey/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Rosetta-Code-Find-bare-lang-tags b/Lang/AutoHotkey/Rosetta-Code-Find-bare-lang-tags deleted file mode 120000 index 7617e8307d..0000000000 --- a/Lang/AutoHotkey/Rosetta-Code-Find-bare-lang-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-bare-lang-tags/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Rosetta-Code-Find-unimplemented-tasks b/Lang/AutoHotkey/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index 2c382bcd56..0000000000 --- a/Lang/AutoHotkey/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Rosetta-Code-Fix-code-tags b/Lang/AutoHotkey/Rosetta-Code-Fix-code-tags deleted file mode 120000 index f8b80906f9..0000000000 --- a/Lang/AutoHotkey/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Rosetta-Code-Rank-languages-by-popularity b/Lang/AutoHotkey/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index d43899a9ae..0000000000 --- a/Lang/AutoHotkey/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Solve-the-no-connection-puzzle b/Lang/AutoHotkey/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..4c4063be0c --- /dev/null +++ b/Lang/AutoHotkey/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Standard-deviation b/Lang/AutoHotkey/Standard-deviation deleted file mode 120000 index c5aaf10e72..0000000000 --- a/Lang/AutoHotkey/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoIt/99-Bottles-of-Beer b/Lang/AutoIt/99-Bottles-of-Beer deleted file mode 120000 index cdfbe2b20a..0000000000 --- a/Lang/AutoIt/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Character-matching b/Lang/AutoIt/Character-matching deleted file mode 120000 index d22ba39a43..0000000000 --- a/Lang/AutoIt/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/AutoIt \ No newline at end of file diff --git a/Lang/Axiom/Standard-deviation b/Lang/Axiom/Standard-deviation deleted file mode 120000 index c8209d2dc3..0000000000 --- a/Lang/Axiom/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Axiom \ No newline at end of file diff --git a/Lang/BASIC/00DESCRIPTION b/Lang/BASIC/00DESCRIPTION index 10d54e7703..1a7340ea5a 100644 --- a/Lang/BASIC/00DESCRIPTION +++ b/Lang/BASIC/00DESCRIPTION @@ -1,5 +1,6 @@ {{language -|tags=qbasic, freebasic, thinbasic +|exec=interpreted +|tags=basic, qbasic, freebasic, thinbasic |hopl id=176 |LCT=yes }} @@ -12,5 +13,9 @@ BASIC became popular, with many different implementations for various computers. ==Links== *[[wp:BASIC|Wikipedia:BASIC]] **[[wp:Rocky Mountain BASIC]] +**[[wp:True BASIC]] +**[[wp:Chipmunk Basic]] +**[[wp:PureBasic]] +**[[wp:PowerBASIC]] {{language programming paradigm|Procedural}} \ No newline at end of file diff --git a/Lang/BASIC/99-Bottles-of-Beer b/Lang/BASIC/99-Bottles-of-Beer deleted file mode 120000 index b2e57f0408..0000000000 --- a/Lang/BASIC/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Align-columns b/Lang/BASIC/Align-columns new file mode 120000 index 0000000000..e0f8ddfa93 --- /dev/null +++ b/Lang/BASIC/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Array-concatenation b/Lang/BASIC/Array-concatenation new file mode 120000 index 0000000000..9f756fd3a0 --- /dev/null +++ b/Lang/BASIC/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Binary-digits b/Lang/BASIC/Binary-digits new file mode 120000 index 0000000000..29d1edba78 --- /dev/null +++ b/Lang/BASIC/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Character-matching b/Lang/BASIC/Character-matching deleted file mode 120000 index c685afa92d..0000000000 --- a/Lang/BASIC/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/BASIC \ No newline at end of file diff --git a/Lang/BASIC/File-IO b/Lang/BASIC/File-IO deleted file mode 120000 index ab5bd448f1..0000000000 --- a/Lang/BASIC/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/BASIC \ No newline at end of file diff --git a/Lang/BASIC/FizzBuzz b/Lang/BASIC/FizzBuzz deleted file mode 120000 index 306c9d57c0..0000000000 --- a/Lang/BASIC/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Generate-lower-case-ASCII-alphabet b/Lang/BASIC/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..a6e35bfaa2 --- /dev/null +++ b/Lang/BASIC/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Loops-Continue b/Lang/BASIC/Loops-Continue new file mode 120000 index 0000000000..b2746b5c24 --- /dev/null +++ b/Lang/BASIC/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Loops-Foreach b/Lang/BASIC/Loops-Foreach new file mode 120000 index 0000000000..7359a5e5dc --- /dev/null +++ b/Lang/BASIC/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Map-range b/Lang/BASIC/Map-range new file mode 120000 index 0000000000..7922452b20 --- /dev/null +++ b/Lang/BASIC/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Penneys-game b/Lang/BASIC/Penneys-game new file mode 120000 index 0000000000..0421a26b5f --- /dev/null +++ b/Lang/BASIC/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Return-multiple-values b/Lang/BASIC/Return-multiple-values new file mode 120000 index 0000000000..1a9098e43c --- /dev/null +++ b/Lang/BASIC/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Universal-Turing-machine b/Lang/BASIC/Universal-Turing-machine new file mode 120000 index 0000000000..d53e4e2018 --- /dev/null +++ b/Lang/BASIC/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/BASIC \ No newline at end of file diff --git a/Lang/BASIC256/100-doors b/Lang/BASIC256/100-doors deleted file mode 120000 index 1df0602bc1..0000000000 --- a/Lang/BASIC256/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/99-Bottles-of-Beer b/Lang/BASIC256/99-Bottles-of-Beer deleted file mode 120000 index bd398f73ed..0000000000 --- a/Lang/BASIC256/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/A+B b/Lang/BASIC256/A+B deleted file mode 120000 index e70ccb0534..0000000000 --- a/Lang/BASIC256/A+B +++ /dev/null @@ -1 +0,0 @@ -../../Task/A+B/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Conways-Game-of-Life b/Lang/BASIC256/Conways-Game-of-Life deleted file mode 120000 index eb5e0bfb2a..0000000000 --- a/Lang/BASIC256/Conways-Game-of-Life +++ /dev/null @@ -1 +0,0 @@ -../../Task/Conways-Game-of-Life/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Forest-fire b/Lang/BASIC256/Forest-fire deleted file mode 120000 index e8ccdf840a..0000000000 --- a/Lang/BASIC256/Forest-fire +++ /dev/null @@ -1 +0,0 @@ -../../Task/Forest-fire/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Logical-operations b/Lang/BASIC256/Logical-operations deleted file mode 120000 index d5d5041322..0000000000 --- a/Lang/BASIC256/Logical-operations +++ /dev/null @@ -1 +0,0 @@ -../../Task/Logical-operations/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Loops-Foreach b/Lang/BASIC256/Loops-Foreach deleted file mode 120000 index cc72787530..0000000000 --- a/Lang/BASIC256/Loops-Foreach +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Foreach/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Mandelbrot-set b/Lang/BASIC256/Mandelbrot-set deleted file mode 120000 index b7754d3683..0000000000 --- a/Lang/BASIC256/Mandelbrot-set +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mandelbrot-set/BASIC256 \ No newline at end of file diff --git a/Lang/BBC-BASIC/99-Bottles-of-Beer b/Lang/BBC-BASIC/99-Bottles-of-Beer deleted file mode 120000 index 4a85de4aaa..0000000000 --- a/Lang/BBC-BASIC/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/A+B b/Lang/BBC-BASIC/A+B deleted file mode 120000 index 7385341f41..0000000000 --- a/Lang/BBC-BASIC/A+B +++ /dev/null @@ -1 +0,0 @@ -../../Task/A+B/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Align-columns b/Lang/BBC-BASIC/Align-columns deleted file mode 120000 index ce45a0825b..0000000000 --- a/Lang/BBC-BASIC/Align-columns +++ /dev/null @@ -1 +0,0 @@ -../../Task/Align-columns/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Array-concatenation b/Lang/BBC-BASIC/Array-concatenation deleted file mode 120000 index c5df8c5df6..0000000000 --- a/Lang/BBC-BASIC/Array-concatenation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Array-concatenation/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Binary-digits b/Lang/BBC-BASIC/Binary-digits deleted file mode 120000 index 767a5ed929..0000000000 --- a/Lang/BBC-BASIC/Binary-digits +++ /dev/null @@ -1 +0,0 @@ -../../Task/Binary-digits/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Calendar---for-real-programmers b/Lang/BBC-BASIC/Calendar---for-real-programmers deleted file mode 120000 index 501af7834b..0000000000 --- a/Lang/BBC-BASIC/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Character-matching b/Lang/BBC-BASIC/Character-matching deleted file mode 120000 index c281710c7f..0000000000 --- a/Lang/BBC-BASIC/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Colour-bars-Display b/Lang/BBC-BASIC/Colour-bars-Display deleted file mode 120000 index 2bab2092e9..0000000000 --- a/Lang/BBC-BASIC/Colour-bars-Display +++ /dev/null @@ -1 +0,0 @@ -../../Task/Colour-bars-Display/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Constrained-random-points-on-a-circle b/Lang/BBC-BASIC/Constrained-random-points-on-a-circle deleted file mode 120000 index 8a32de444b..0000000000 --- a/Lang/BBC-BASIC/Constrained-random-points-on-a-circle +++ /dev/null @@ -1 +0,0 @@ -../../Task/Constrained-random-points-on-a-circle/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Conways-Game-of-Life b/Lang/BBC-BASIC/Conways-Game-of-Life deleted file mode 120000 index c1a3803646..0000000000 --- a/Lang/BBC-BASIC/Conways-Game-of-Life +++ /dev/null @@ -1 +0,0 @@ -../../Task/Conways-Game-of-Life/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Detect-division-by-zero b/Lang/BBC-BASIC/Detect-division-by-zero deleted file mode 120000 index 2241d2b34c..0000000000 --- a/Lang/BBC-BASIC/Detect-division-by-zero +++ /dev/null @@ -1 +0,0 @@ -../../Task/Detect-division-by-zero/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Draw-a-sphere b/Lang/BBC-BASIC/Draw-a-sphere deleted file mode 120000 index 9b98fd11f1..0000000000 --- a/Lang/BBC-BASIC/Draw-a-sphere +++ /dev/null @@ -1 +0,0 @@ -../../Task/Draw-a-sphere/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Ethiopian-multiplication b/Lang/BBC-BASIC/Ethiopian-multiplication deleted file mode 120000 index 4c8585062b..0000000000 --- a/Lang/BBC-BASIC/Ethiopian-multiplication +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ethiopian-multiplication/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Euler-method b/Lang/BBC-BASIC/Euler-method deleted file mode 120000 index 955665ab10..0000000000 --- a/Lang/BBC-BASIC/Euler-method +++ /dev/null @@ -1 +0,0 @@ -../../Task/Euler-method/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/File-IO b/Lang/BBC-BASIC/File-IO deleted file mode 120000 index 3d789ec845..0000000000 --- a/Lang/BBC-BASIC/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/FizzBuzz b/Lang/BBC-BASIC/FizzBuzz deleted file mode 120000 index 45e69c96cb..0000000000 --- a/Lang/BBC-BASIC/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Forest-fire b/Lang/BBC-BASIC/Forest-fire deleted file mode 120000 index c37228b302..0000000000 --- a/Lang/BBC-BASIC/Forest-fire +++ /dev/null @@ -1 +0,0 @@ -../../Task/Forest-fire/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Generate-lower-case-ASCII-alphabet b/Lang/BBC-BASIC/Generate-lower-case-ASCII-alphabet deleted file mode 120000 index 19bbed8353..0000000000 --- a/Lang/BBC-BASIC/Generate-lower-case-ASCII-alphabet +++ /dev/null @@ -1 +0,0 @@ -../../Task/Generate-lower-case-ASCII-alphabet/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Hailstone-sequence b/Lang/BBC-BASIC/Hailstone-sequence deleted file mode 120000 index b25c2438d2..0000000000 --- a/Lang/BBC-BASIC/Hailstone-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hailstone-sequence/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Input-loop b/Lang/BBC-BASIC/Input-loop deleted file mode 120000 index 82a543578c..0000000000 --- a/Lang/BBC-BASIC/Input-loop +++ /dev/null @@ -1 +0,0 @@ -../../Task/Input-loop/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Least-common-multiple b/Lang/BBC-BASIC/Least-common-multiple deleted file mode 120000 index 4fdd4d0d18..0000000000 --- a/Lang/BBC-BASIC/Least-common-multiple +++ /dev/null @@ -1 +0,0 @@ -../../Task/Least-common-multiple/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Logical-operations b/Lang/BBC-BASIC/Logical-operations deleted file mode 120000 index 21853a5e44..0000000000 --- a/Lang/BBC-BASIC/Logical-operations +++ /dev/null @@ -1 +0,0 @@ -../../Task/Logical-operations/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Loops-Continue b/Lang/BBC-BASIC/Loops-Continue deleted file mode 120000 index aaf229e600..0000000000 --- a/Lang/BBC-BASIC/Loops-Continue +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Continue/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Loops-For b/Lang/BBC-BASIC/Loops-For deleted file mode 120000 index 4dba4d4cb0..0000000000 --- a/Lang/BBC-BASIC/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Loops-Foreach b/Lang/BBC-BASIC/Loops-Foreach deleted file mode 120000 index 534b69b51c..0000000000 --- a/Lang/BBC-BASIC/Loops-Foreach +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Foreach/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Loops-N-plus-one-half b/Lang/BBC-BASIC/Loops-N-plus-one-half deleted file mode 120000 index 308d2eb72e..0000000000 --- a/Lang/BBC-BASIC/Loops-N-plus-one-half +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-N-plus-one-half/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Mandelbrot-set b/Lang/BBC-BASIC/Mandelbrot-set deleted file mode 120000 index 4a47d7d008..0000000000 --- a/Lang/BBC-BASIC/Mandelbrot-set +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mandelbrot-set/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Map-range b/Lang/BBC-BASIC/Map-range deleted file mode 120000 index e034afee6e..0000000000 --- a/Lang/BBC-BASIC/Map-range +++ /dev/null @@ -1 +0,0 @@ -../../Task/Map-range/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Mutex b/Lang/BBC-BASIC/Mutex deleted file mode 120000 index 2a321a371d..0000000000 --- a/Lang/BBC-BASIC/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Null-object b/Lang/BBC-BASIC/Null-object deleted file mode 120000 index 7327acb9d3..0000000000 --- a/Lang/BBC-BASIC/Null-object +++ /dev/null @@ -1 +0,0 @@ -../../Task/Null-object/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Rosetta-Code-Count-examples b/Lang/BBC-BASIC/Rosetta-Code-Count-examples deleted file mode 120000 index db9da8adf4..0000000000 --- a/Lang/BBC-BASIC/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Rosetta-Code-Rank-languages-by-popularity b/Lang/BBC-BASIC/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index fe97f2d5e6..0000000000 --- a/Lang/BBC-BASIC/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Scope-modifiers b/Lang/BBC-BASIC/Scope-modifiers deleted file mode 120000 index 1147492904..0000000000 --- a/Lang/BBC-BASIC/Scope-modifiers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Scope-modifiers/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Standard-deviation b/Lang/BBC-BASIC/Standard-deviation deleted file mode 120000 index 688d2647a5..0000000000 --- a/Lang/BBC-BASIC/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/String-case b/Lang/BBC-BASIC/String-case deleted file mode 120000 index 20f92949a8..0000000000 --- a/Lang/BBC-BASIC/String-case +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-case/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/String-concatenation b/Lang/BBC-BASIC/String-concatenation deleted file mode 120000 index 5378d96200..0000000000 --- a/Lang/BBC-BASIC/String-concatenation +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-concatenation/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Clear-the-screen b/Lang/BBC-BASIC/Terminal-control-Clear-the-screen deleted file mode 120000 index b912b9f8ee..0000000000 --- a/Lang/BBC-BASIC/Terminal-control-Clear-the-screen +++ /dev/null @@ -1 +0,0 @@ -../../Task/Terminal-control-Clear-the-screen/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Cursor-positioning b/Lang/BBC-BASIC/Terminal-control-Cursor-positioning deleted file mode 120000 index 2c8b634b75..0000000000 --- a/Lang/BBC-BASIC/Terminal-control-Cursor-positioning +++ /dev/null @@ -1 +0,0 @@ -../../Task/Terminal-control-Cursor-positioning/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Inverse-video b/Lang/BBC-BASIC/Terminal-control-Inverse-video deleted file mode 120000 index 88bc50404a..0000000000 --- a/Lang/BBC-BASIC/Terminal-control-Inverse-video +++ /dev/null @@ -1 +0,0 @@ -../../Task/Terminal-control-Inverse-video/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Tokenize-a-string b/Lang/BBC-BASIC/Tokenize-a-string deleted file mode 120000 index d5a8e0be54..0000000000 --- a/Lang/BBC-BASIC/Tokenize-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Tokenize-a-string/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Write-language-name-in-3D-ASCII b/Lang/BBC-BASIC/Write-language-name-in-3D-ASCII deleted file mode 120000 index 1a033b1706..0000000000 --- a/Lang/BBC-BASIC/Write-language-name-in-3D-ASCII +++ /dev/null @@ -1 +0,0 @@ -../../Task/Write-language-name-in-3D-ASCII/BBC-BASIC \ No newline at end of file diff --git a/Lang/BaCon/00DESCRIPTION b/Lang/BaCon/00DESCRIPTION new file mode 100644 index 0000000000..4dfa92e58e --- /dev/null +++ b/Lang/BaCon/00DESCRIPTION @@ -0,0 +1,27 @@ +{{language|BaCon +|site=http://basic-converter.org/ +|exec=machine +|gc=yes +|parampass=both +|express=both +|checking=both +|strength=weak +|safety=unsafe +|compat=structural +|hopl=no +|tags=bacon}} +{{implementation|BASIC}} + +'''BaCon''', the [[BASIC]] Converter, by Peter van Eerten. + +BaCon is a free BASIC to C translator for Unix-based systems, which runs on most Unix/Linux/BSD platforms, including MacOSX. It intends to be a programming aid in creating tools which can be compiled on different platforms (including 64bit environments), while trying to revive the days of the good old BASIC. + +BaCon can be described as a translator, a converter, a source-to-source compiler, a transcompiler or a transpiler. It also can be described as a very elaborate preprocessor to C. BaCon is implemented in generic shell script and in itself. Therefore, to start using Bacon, the target system must have either Korn Shell, or ZShell, or Bourne Again Shell (BASH) available. If none of these shells are available, then the free Public Domain Korn Shell can be installed, which can execute BaCon also. Furthermore, BaCon also works with a newer Kornshell implementation like the MirBSD Korn Shell. + +The shell script implementation can convert and compile the BaCon version of BaCon. This will deliver the binary version of BaCon which has an extremely high conversion performance. On newer systems, the average conversion rate usually lies above 10.000 lines per second. + +Code converted by BaCon can be compiled by GCC, the Compaq C Compiler, TCC, the clang/LLVM compiler and possibly also by other C compilers. + +==See Also== +* http://basic-converter.org/ +* http://basic-converter.proboards.com \ No newline at end of file diff --git a/Lang/BaCon/100-doors b/Lang/BaCon/100-doors new file mode 120000 index 0000000000..97e6bd22b3 --- /dev/null +++ b/Lang/BaCon/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/BaCon \ No newline at end of file diff --git a/Lang/BaCon/ABC-Problem b/Lang/BaCon/ABC-Problem new file mode 120000 index 0000000000..65915a647f --- /dev/null +++ b/Lang/BaCon/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Assertions b/Lang/BaCon/Assertions new file mode 120000 index 0000000000..65cd66cd4c --- /dev/null +++ b/Lang/BaCon/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Associative-array-Creation b/Lang/BaCon/Associative-array-Creation new file mode 120000 index 0000000000..ab9fb4ae61 --- /dev/null +++ b/Lang/BaCon/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Associative-array-Iteration b/Lang/BaCon/Associative-array-Iteration new file mode 120000 index 0000000000..1da49f08fa --- /dev/null +++ b/Lang/BaCon/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Binary-digits b/Lang/BaCon/Binary-digits new file mode 120000 index 0000000000..c4498846cd --- /dev/null +++ b/Lang/BaCon/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Caesar-cipher b/Lang/BaCon/Caesar-cipher new file mode 120000 index 0000000000..3cbf9a6094 --- /dev/null +++ b/Lang/BaCon/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Call-a-function-in-a-shared-library b/Lang/BaCon/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..cc49f9c3e1 --- /dev/null +++ b/Lang/BaCon/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Concurrent-computing b/Lang/BaCon/Concurrent-computing new file mode 120000 index 0000000000..e6ef51ee38 --- /dev/null +++ b/Lang/BaCon/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Count-occurrences-of-a-substring b/Lang/BaCon/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..64339362b9 --- /dev/null +++ b/Lang/BaCon/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Date-format b/Lang/BaCon/Date-format new file mode 120000 index 0000000000..aeb6829898 --- /dev/null +++ b/Lang/BaCon/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Determine-if-a-string-is-numeric b/Lang/BaCon/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..c1efde5876 --- /dev/null +++ b/Lang/BaCon/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Dutch-national-flag-problem b/Lang/BaCon/Dutch-national-flag-problem new file mode 120000 index 0000000000..e0c0c6cabd --- /dev/null +++ b/Lang/BaCon/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Empty-directory b/Lang/BaCon/Empty-directory new file mode 120000 index 0000000000..f5c9ebc32e --- /dev/null +++ b/Lang/BaCon/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Even-or-odd b/Lang/BaCon/Even-or-odd new file mode 120000 index 0000000000..a1f2e71d46 --- /dev/null +++ b/Lang/BaCon/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Factorial b/Lang/BaCon/Factorial new file mode 120000 index 0000000000..9e019b82fb --- /dev/null +++ b/Lang/BaCon/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/BaCon \ No newline at end of file diff --git a/Lang/BaCon/File-size b/Lang/BaCon/File-size new file mode 120000 index 0000000000..16db69f53f --- /dev/null +++ b/Lang/BaCon/File-size @@ -0,0 +1 @@ +../../Task/File-size/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Flatten-a-list b/Lang/BaCon/Flatten-a-list new file mode 120000 index 0000000000..659c71847c --- /dev/null +++ b/Lang/BaCon/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Fork b/Lang/BaCon/Fork new file mode 120000 index 0000000000..9fb5aab0f5 --- /dev/null +++ b/Lang/BaCon/Fork @@ -0,0 +1 @@ +../../Task/Fork/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Formatted-numeric-output b/Lang/BaCon/Formatted-numeric-output new file mode 120000 index 0000000000..d03dbec297 --- /dev/null +++ b/Lang/BaCon/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/BaCon \ No newline at end of file diff --git a/Lang/BaCon/HTTP b/Lang/BaCon/HTTP new file mode 120000 index 0000000000..33d1f9e8dc --- /dev/null +++ b/Lang/BaCon/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Handle-a-signal b/Lang/BaCon/Handle-a-signal new file mode 120000 index 0000000000..9dc8f3860d --- /dev/null +++ b/Lang/BaCon/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Hello-world-Graphical b/Lang/BaCon/Hello-world-Graphical new file mode 120000 index 0000000000..06de1014d4 --- /dev/null +++ b/Lang/BaCon/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Hello-world-Web-server b/Lang/BaCon/Hello-world-Web-server new file mode 120000 index 0000000000..ff04aed934 --- /dev/null +++ b/Lang/BaCon/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Hostname b/Lang/BaCon/Hostname new file mode 120000 index 0000000000..54238ebe23 --- /dev/null +++ b/Lang/BaCon/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Include-a-file b/Lang/BaCon/Include-a-file new file mode 120000 index 0000000000..dfcfdb1bd7 --- /dev/null +++ b/Lang/BaCon/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/BaCon \ No newline at end of file diff --git a/Lang/BaCon/MD5 b/Lang/BaCon/MD5 new file mode 120000 index 0000000000..a36115f8b7 --- /dev/null +++ b/Lang/BaCon/MD5 @@ -0,0 +1 @@ +../../Task/MD5/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Mutual-recursion b/Lang/BaCon/Mutual-recursion new file mode 120000 index 0000000000..0ad361fc31 --- /dev/null +++ b/Lang/BaCon/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Nth b/Lang/BaCon/Nth new file mode 120000 index 0000000000..79e4f52e5f --- /dev/null +++ b/Lang/BaCon/Nth @@ -0,0 +1 @@ +../../Task/Nth/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Odd-word-problem b/Lang/BaCon/Odd-word-problem new file mode 120000 index 0000000000..2bda07ea4a --- /dev/null +++ b/Lang/BaCon/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Ordered-words b/Lang/BaCon/Ordered-words new file mode 120000 index 0000000000..25a1fc9713 --- /dev/null +++ b/Lang/BaCon/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Palindrome-detection b/Lang/BaCon/Palindrome-detection new file mode 120000 index 0000000000..38cdb09c9d --- /dev/null +++ b/Lang/BaCon/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Phrase-reversals b/Lang/BaCon/Phrase-reversals new file mode 120000 index 0000000000..286b8dca17 --- /dev/null +++ b/Lang/BaCon/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Pick-random-element b/Lang/BaCon/Pick-random-element new file mode 120000 index 0000000000..26aac211dc --- /dev/null +++ b/Lang/BaCon/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/BaCon \ No newline at end of file diff --git a/Lang/BaCon/README b/Lang/BaCon/README new file mode 100644 index 0000000000..ad53c811cf --- /dev/null +++ b/Lang/BaCon/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:BaCon diff --git a/Lang/BaCon/Rate-counter b/Lang/BaCon/Rate-counter new file mode 120000 index 0000000000..573bee12b4 --- /dev/null +++ b/Lang/BaCon/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Read-entire-file b/Lang/BaCon/Read-entire-file new file mode 120000 index 0000000000..9674c0f96a --- /dev/null +++ b/Lang/BaCon/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Reverse-a-string b/Lang/BaCon/Reverse-a-string new file mode 120000 index 0000000000..4f0f4eda85 --- /dev/null +++ b/Lang/BaCon/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Reverse-words-in-a-string b/Lang/BaCon/Reverse-words-in-a-string new file mode 120000 index 0000000000..f3b86d9ad1 --- /dev/null +++ b/Lang/BaCon/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Rot-13 b/Lang/BaCon/Rot-13 new file mode 120000 index 0000000000..4fa2b5c05b --- /dev/null +++ b/Lang/BaCon/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/BaCon \ No newline at end of file diff --git a/Lang/BaCon/SHA-256 b/Lang/BaCon/SHA-256 new file mode 120000 index 0000000000..ddf4f0ee5c --- /dev/null +++ b/Lang/BaCon/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Short-circuit-evaluation b/Lang/BaCon/Short-circuit-evaluation new file mode 120000 index 0000000000..bab34d5094 --- /dev/null +++ b/Lang/BaCon/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Sort-an-integer-array b/Lang/BaCon/Sort-an-integer-array new file mode 120000 index 0000000000..9255c3a580 --- /dev/null +++ b/Lang/BaCon/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/BaCon \ No newline at end of file diff --git a/Lang/BaCon/System-time b/Lang/BaCon/System-time new file mode 120000 index 0000000000..1bc11b72cb --- /dev/null +++ b/Lang/BaCon/System-time @@ -0,0 +1 @@ +../../Task/System-time/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Time-a-function b/Lang/BaCon/Time-a-function new file mode 120000 index 0000000000..c20d3362c1 --- /dev/null +++ b/Lang/BaCon/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Trigonometric-functions b/Lang/BaCon/Trigonometric-functions new file mode 120000 index 0000000000..90481a2796 --- /dev/null +++ b/Lang/BaCon/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Unix-ls b/Lang/BaCon/Unix-ls new file mode 120000 index 0000000000..0bb02dbc93 --- /dev/null +++ b/Lang/BaCon/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Variadic-function b/Lang/BaCon/Variadic-function new file mode 120000 index 0000000000..18614d1a44 --- /dev/null +++ b/Lang/BaCon/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Window-creation b/Lang/BaCon/Window-creation new file mode 120000 index 0000000000..abe872ab48 --- /dev/null +++ b/Lang/BaCon/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Word-wrap b/Lang/BaCon/Word-wrap new file mode 120000 index 0000000000..b07bab5d61 --- /dev/null +++ b/Lang/BaCon/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Zero-to-the-zero-power b/Lang/BaCon/Zero-to-the-zero-power new file mode 120000 index 0000000000..fa45c6480d --- /dev/null +++ b/Lang/BaCon/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/BaCon \ No newline at end of file diff --git a/Lang/Babel/File-IO b/Lang/Babel/File-IO deleted file mode 120000 index b6fdd56a9c..0000000000 --- a/Lang/Babel/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Babel \ No newline at end of file diff --git a/Lang/Batch-File/24-game b/Lang/Batch-File/24-game deleted file mode 120000 index 9485b23e72..0000000000 --- a/Lang/Batch-File/24-game +++ /dev/null @@ -1 +0,0 @@ -../../Task/24-game/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/99-Bottles-of-Beer b/Lang/Batch-File/99-Bottles-of-Beer deleted file mode 120000 index a6102c729d..0000000000 --- a/Lang/Batch-File/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Abundant,-deficient-and-perfect-number-classifications b/Lang/Batch-File/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..6552a5555e --- /dev/null +++ b/Lang/Batch-File/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Append-a-record-to-the-end-of-a-text-file b/Lang/Batch-File/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..228743713b --- /dev/null +++ b/Lang/Batch-File/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Binary-search b/Lang/Batch-File/Binary-search new file mode 120000 index 0000000000..954929633a --- /dev/null +++ b/Lang/Batch-File/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Case-sensitivity-of-identifiers b/Lang/Batch-File/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..c6fb4873db --- /dev/null +++ b/Lang/Batch-File/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Character-codes b/Lang/Batch-File/Character-codes new file mode 120000 index 0000000000..6879165288 --- /dev/null +++ b/Lang/Batch-File/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Conways-Game-of-Life b/Lang/Batch-File/Conways-Game-of-Life new file mode 120000 index 0000000000..f3e4870d06 --- /dev/null +++ b/Lang/Batch-File/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Count-in-octal b/Lang/Batch-File/Count-in-octal new file mode 120000 index 0000000000..6d73a50ae0 --- /dev/null +++ b/Lang/Batch-File/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Create-an-HTML-table b/Lang/Batch-File/Create-an-HTML-table new file mode 120000 index 0000000000..f295fe20b6 --- /dev/null +++ b/Lang/Batch-File/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Date-format b/Lang/Batch-File/Date-format new file mode 120000 index 0000000000..838163648d --- /dev/null +++ b/Lang/Batch-File/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Date-manipulation b/Lang/Batch-File/Date-manipulation new file mode 120000 index 0000000000..d5c5745558 --- /dev/null +++ b/Lang/Batch-File/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Ethiopian-multiplication b/Lang/Batch-File/Ethiopian-multiplication new file mode 120000 index 0000000000..d281e146c7 --- /dev/null +++ b/Lang/Batch-File/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Evolutionary-algorithm b/Lang/Batch-File/Evolutionary-algorithm new file mode 120000 index 0000000000..25ba1494d1 --- /dev/null +++ b/Lang/Batch-File/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Fibonacci-n-step-number-sequences b/Lang/Batch-File/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..c8ed48bd32 --- /dev/null +++ b/Lang/Batch-File/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/File-IO b/Lang/Batch-File/File-IO deleted file mode 120000 index 15d020f16e..0000000000 --- a/Lang/Batch-File/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Filter b/Lang/Batch-File/Filter new file mode 120000 index 0000000000..16f969021f --- /dev/null +++ b/Lang/Batch-File/Filter @@ -0,0 +1 @@ +../../Task/Filter/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Find-common-directory-path b/Lang/Batch-File/Find-common-directory-path new file mode 120000 index 0000000000..bdfe9af035 --- /dev/null +++ b/Lang/Batch-File/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Floyds-triangle b/Lang/Batch-File/Floyds-triangle new file mode 120000 index 0000000000..cf3bc6ee72 --- /dev/null +++ b/Lang/Batch-File/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Forest-fire b/Lang/Batch-File/Forest-fire new file mode 120000 index 0000000000..833e8eaea5 --- /dev/null +++ b/Lang/Batch-File/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Four-bit-adder b/Lang/Batch-File/Four-bit-adder new file mode 120000 index 0000000000..3c5304a87e --- /dev/null +++ b/Lang/Batch-File/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Generate-lower-case-ASCII-alphabet b/Lang/Batch-File/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..669d84942b --- /dev/null +++ b/Lang/Batch-File/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Guess-the-number-With-feedback--player- b/Lang/Batch-File/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..528dd5c541 --- /dev/null +++ b/Lang/Batch-File/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Harshad-or-Niven-series b/Lang/Batch-File/Harshad-or-Niven-series new file mode 120000 index 0000000000..c970666879 --- /dev/null +++ b/Lang/Batch-File/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Horners-rule-for-polynomial-evaluation b/Lang/Batch-File/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..abf4929c92 --- /dev/null +++ b/Lang/Batch-File/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Integer-sequence b/Lang/Batch-File/Integer-sequence new file mode 120000 index 0000000000..1bed650bc8 --- /dev/null +++ b/Lang/Batch-File/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Kaprekar-numbers b/Lang/Batch-File/Kaprekar-numbers new file mode 120000 index 0000000000..02d9105b1b --- /dev/null +++ b/Lang/Batch-File/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Knapsack-problem-0-1 b/Lang/Batch-File/Knapsack-problem-0-1 new file mode 120000 index 0000000000..af9891bb93 --- /dev/null +++ b/Lang/Batch-File/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Mad-Libs b/Lang/Batch-File/Mad-Libs deleted file mode 120000 index ad2a45b666..0000000000 --- a/Lang/Batch-File/Mad-Libs +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mad-Libs/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Prime-decomposition b/Lang/Batch-File/Prime-decomposition new file mode 120000 index 0000000000..fe58c44eab --- /dev/null +++ b/Lang/Batch-File/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Random-number-generator--device- b/Lang/Batch-File/Random-number-generator--device- new file mode 120000 index 0000000000..1cff460783 --- /dev/null +++ b/Lang/Batch-File/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Read-a-specific-line-from-a-file b/Lang/Batch-File/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..e05cea42bf --- /dev/null +++ b/Lang/Batch-File/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Rock-paper-scissors b/Lang/Batch-File/Rock-paper-scissors new file mode 120000 index 0000000000..1371633691 --- /dev/null +++ b/Lang/Batch-File/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Rot-13 b/Lang/Batch-File/Rot-13 new file mode 120000 index 0000000000..400235252e --- /dev/null +++ b/Lang/Batch-File/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Sorting-algorithms-Pancake-sort b/Lang/Batch-File/Sorting-algorithms-Pancake-sort deleted file mode 120000 index 89658edde2..0000000000 --- a/Lang/Batch-File/Sorting-algorithms-Pancake-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Pancake-sort/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/The-Twelve-Days-of-Christmas b/Lang/Batch-File/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..be4d5d8fac --- /dev/null +++ b/Lang/Batch-File/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Word-wrap b/Lang/Batch-File/Word-wrap new file mode 120000 index 0000000000..336007093b --- /dev/null +++ b/Lang/Batch-File/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Yin-and-yang b/Lang/Batch-File/Yin-and-yang deleted file mode 120000 index 35acc29cb6..0000000000 --- a/Lang/Batch-File/Yin-and-yang +++ /dev/null @@ -1 +0,0 @@ -../../Task/Yin-and-yang/Batch-File \ No newline at end of file diff --git a/Lang/Bc/100-doors b/Lang/Bc/100-doors new file mode 120000 index 0000000000..783dc8bf9b --- /dev/null +++ b/Lang/Bc/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Bc \ No newline at end of file diff --git a/Lang/Bc/A+B b/Lang/Bc/A+B new file mode 120000 index 0000000000..83a3655127 --- /dev/null +++ b/Lang/Bc/A+B @@ -0,0 +1 @@ +../../Task/A+B/Bc \ No newline at end of file diff --git a/Lang/Bc/Ackermann-function b/Lang/Bc/Ackermann-function new file mode 120000 index 0000000000..b73fbba0d9 --- /dev/null +++ b/Lang/Bc/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Bc \ No newline at end of file diff --git a/Lang/Bc/Arbitrary-precision-integers--included- b/Lang/Bc/Arbitrary-precision-integers--included- new file mode 120000 index 0000000000..9b496c2cd5 --- /dev/null +++ b/Lang/Bc/Arbitrary-precision-integers--included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers--included-/Bc \ No newline at end of file diff --git a/Lang/Bc/Arithmetic-Integer b/Lang/Bc/Arithmetic-Integer new file mode 120000 index 0000000000..2a27c47b8c --- /dev/null +++ b/Lang/Bc/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Bc \ No newline at end of file diff --git a/Lang/Bc/Arithmetic-geometric-mean b/Lang/Bc/Arithmetic-geometric-mean new file mode 120000 index 0000000000..8ecd7c97f1 --- /dev/null +++ b/Lang/Bc/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Bc \ No newline at end of file diff --git a/Lang/Bc/Arrays b/Lang/Bc/Arrays new file mode 120000 index 0000000000..2a41bba00f --- /dev/null +++ b/Lang/Bc/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Bc \ No newline at end of file diff --git a/Lang/Bc/Averages-Arithmetic-mean b/Lang/Bc/Averages-Arithmetic-mean new file mode 120000 index 0000000000..622b7e3044 --- /dev/null +++ b/Lang/Bc/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Bc \ No newline at end of file diff --git a/Lang/Bc/Binary-digits b/Lang/Bc/Binary-digits new file mode 120000 index 0000000000..51a51c4a4b --- /dev/null +++ b/Lang/Bc/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Bc \ No newline at end of file diff --git a/Lang/Bc/Case-sensitivity-of-identifiers b/Lang/Bc/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..221e7e3e39 --- /dev/null +++ b/Lang/Bc/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Bc \ No newline at end of file diff --git a/Lang/Bc/Comments b/Lang/Bc/Comments new file mode 120000 index 0000000000..2d11f7d871 --- /dev/null +++ b/Lang/Bc/Comments @@ -0,0 +1 @@ +../../Task/Comments/Bc \ No newline at end of file diff --git a/Lang/Bc/Count-in-octal b/Lang/Bc/Count-in-octal new file mode 120000 index 0000000000..3e974c92d1 --- /dev/null +++ b/Lang/Bc/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Bc \ No newline at end of file diff --git a/Lang/Bc/Day-of-the-week b/Lang/Bc/Day-of-the-week new file mode 120000 index 0000000000..3f1e95dd55 --- /dev/null +++ b/Lang/Bc/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Bc \ No newline at end of file diff --git a/Lang/Bc/Dot-product b/Lang/Bc/Dot-product new file mode 120000 index 0000000000..91e373a9e4 --- /dev/null +++ b/Lang/Bc/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Bc \ No newline at end of file diff --git a/Lang/Bc/Even-or-odd b/Lang/Bc/Even-or-odd new file mode 120000 index 0000000000..6237ad734a --- /dev/null +++ b/Lang/Bc/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Bc \ No newline at end of file diff --git a/Lang/Bc/Factorial b/Lang/Bc/Factorial new file mode 120000 index 0000000000..9532b583a9 --- /dev/null +++ b/Lang/Bc/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Bc \ No newline at end of file diff --git a/Lang/Bc/Factors-of-an-integer b/Lang/Bc/Factors-of-an-integer new file mode 120000 index 0000000000..4f60b56ffe --- /dev/null +++ b/Lang/Bc/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Bc \ No newline at end of file diff --git a/Lang/Bc/Fibonacci-sequence b/Lang/Bc/Fibonacci-sequence new file mode 120000 index 0000000000..30a06ad138 --- /dev/null +++ b/Lang/Bc/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Bc \ No newline at end of file diff --git a/Lang/Bc/FizzBuzz b/Lang/Bc/FizzBuzz new file mode 120000 index 0000000000..88b03cc371 --- /dev/null +++ b/Lang/Bc/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Bc \ No newline at end of file diff --git a/Lang/Bc/Formatted-numeric-output b/Lang/Bc/Formatted-numeric-output new file mode 120000 index 0000000000..d38f1568b3 --- /dev/null +++ b/Lang/Bc/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Bc \ No newline at end of file diff --git a/Lang/Bc/Function-definition b/Lang/Bc/Function-definition new file mode 120000 index 0000000000..5a590311ce --- /dev/null +++ b/Lang/Bc/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Bc \ No newline at end of file diff --git a/Lang/Bc/Gray-code b/Lang/Bc/Gray-code new file mode 120000 index 0000000000..ee0ab3f136 --- /dev/null +++ b/Lang/Bc/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Bc \ No newline at end of file diff --git a/Lang/Bc/Greatest-element-of-a-list b/Lang/Bc/Greatest-element-of-a-list new file mode 120000 index 0000000000..c086134a41 --- /dev/null +++ b/Lang/Bc/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Bc \ No newline at end of file diff --git a/Lang/Bc/Hamming-numbers b/Lang/Bc/Hamming-numbers new file mode 120000 index 0000000000..057fc980e7 --- /dev/null +++ b/Lang/Bc/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/Bc \ No newline at end of file diff --git a/Lang/Bc/Hello-world-Text b/Lang/Bc/Hello-world-Text new file mode 120000 index 0000000000..99b878d375 --- /dev/null +++ b/Lang/Bc/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Bc \ No newline at end of file diff --git a/Lang/Bc/Holidays-related-to-Easter b/Lang/Bc/Holidays-related-to-Easter new file mode 120000 index 0000000000..6a7294acff --- /dev/null +++ b/Lang/Bc/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/Bc \ No newline at end of file diff --git a/Lang/Bc/Integer-comparison b/Lang/Bc/Integer-comparison new file mode 120000 index 0000000000..37f15d5287 --- /dev/null +++ b/Lang/Bc/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Bc \ No newline at end of file diff --git a/Lang/Bc/Integer-sequence b/Lang/Bc/Integer-sequence new file mode 120000 index 0000000000..9a381aa7ab --- /dev/null +++ b/Lang/Bc/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Bc \ No newline at end of file diff --git a/Lang/Bc/Langtons-ant b/Lang/Bc/Langtons-ant new file mode 120000 index 0000000000..69cd0ebc2b --- /dev/null +++ b/Lang/Bc/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Bc \ No newline at end of file diff --git a/Lang/Bc/Least-common-multiple b/Lang/Bc/Least-common-multiple new file mode 120000 index 0000000000..1d29ff9c4f --- /dev/null +++ b/Lang/Bc/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Bc \ No newline at end of file diff --git a/Lang/Bc/Linear-congruential-generator b/Lang/Bc/Linear-congruential-generator new file mode 120000 index 0000000000..ebccdf976b --- /dev/null +++ b/Lang/Bc/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/Bc \ No newline at end of file diff --git a/Lang/Bc/Literals-Integer b/Lang/Bc/Literals-Integer new file mode 120000 index 0000000000..9b8e2a1a27 --- /dev/null +++ b/Lang/Bc/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Bc \ No newline at end of file diff --git a/Lang/Bc/Logical-operations b/Lang/Bc/Logical-operations new file mode 120000 index 0000000000..45731a694a --- /dev/null +++ b/Lang/Bc/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Bc \ No newline at end of file diff --git a/Lang/Bc/Loops-Break b/Lang/Bc/Loops-Break new file mode 120000 index 0000000000..012c0b03b3 --- /dev/null +++ b/Lang/Bc/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Bc \ No newline at end of file diff --git a/Lang/Bc/Loops-Continue b/Lang/Bc/Loops-Continue new file mode 120000 index 0000000000..a00be0dd1f --- /dev/null +++ b/Lang/Bc/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Bc \ No newline at end of file diff --git a/Lang/Bc/Loops-Do-while b/Lang/Bc/Loops-Do-while new file mode 120000 index 0000000000..0a842ccdb9 --- /dev/null +++ b/Lang/Bc/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Bc \ No newline at end of file diff --git a/Lang/Bc/Loops-Downward-for b/Lang/Bc/Loops-Downward-for new file mode 120000 index 0000000000..d8ad9aa91e --- /dev/null +++ b/Lang/Bc/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Bc \ No newline at end of file diff --git a/Lang/Bc/Loops-For b/Lang/Bc/Loops-For new file mode 120000 index 0000000000..5c9d8f215b --- /dev/null +++ b/Lang/Bc/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Bc \ No newline at end of file diff --git a/Lang/Bc/Loops-For-with-a-specified-step b/Lang/Bc/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..aa8a727d8d --- /dev/null +++ b/Lang/Bc/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Bc \ No newline at end of file diff --git a/Lang/Bc/Loops-Foreach b/Lang/Bc/Loops-Foreach new file mode 120000 index 0000000000..660448e4b4 --- /dev/null +++ b/Lang/Bc/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Bc \ No newline at end of file diff --git a/Lang/Bc/Loops-Infinite b/Lang/Bc/Loops-Infinite new file mode 120000 index 0000000000..e7d277c08d --- /dev/null +++ b/Lang/Bc/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Bc \ No newline at end of file diff --git a/Lang/Bc/Loops-N-plus-one-half b/Lang/Bc/Loops-N-plus-one-half new file mode 120000 index 0000000000..e1f9d13c7b --- /dev/null +++ b/Lang/Bc/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Bc \ No newline at end of file diff --git a/Lang/Bc/Loops-Nested b/Lang/Bc/Loops-Nested new file mode 120000 index 0000000000..e1193a28bb --- /dev/null +++ b/Lang/Bc/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Bc \ No newline at end of file diff --git a/Lang/Bc/Loops-While b/Lang/Bc/Loops-While new file mode 120000 index 0000000000..a437a4064d --- /dev/null +++ b/Lang/Bc/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Bc \ No newline at end of file diff --git a/Lang/Bc/Luhn-test-of-credit-card-numbers b/Lang/Bc/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..e476adf5af --- /dev/null +++ b/Lang/Bc/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Bc \ No newline at end of file diff --git a/Lang/Bc/Magic-squares-of-odd-order b/Lang/Bc/Magic-squares-of-odd-order new file mode 120000 index 0000000000..8501d04145 --- /dev/null +++ b/Lang/Bc/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Bc \ No newline at end of file diff --git a/Lang/Bc/Map-range b/Lang/Bc/Map-range new file mode 120000 index 0000000000..eae4e547f9 --- /dev/null +++ b/Lang/Bc/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Bc \ No newline at end of file diff --git a/Lang/Bc/Nth-root b/Lang/Bc/Nth-root new file mode 120000 index 0000000000..54496c244d --- /dev/null +++ b/Lang/Bc/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/Bc \ No newline at end of file diff --git a/Lang/Bc/Pi b/Lang/Bc/Pi new file mode 120000 index 0000000000..00871c2a0c --- /dev/null +++ b/Lang/Bc/Pi @@ -0,0 +1 @@ +../../Task/Pi/Bc \ No newline at end of file diff --git a/Lang/Bc/Primality-by-trial-division b/Lang/Bc/Primality-by-trial-division new file mode 120000 index 0000000000..bb3b13e30c --- /dev/null +++ b/Lang/Bc/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Bc \ No newline at end of file diff --git a/Lang/Bc/Real-constants-and-functions b/Lang/Bc/Real-constants-and-functions new file mode 120000 index 0000000000..a39285883a --- /dev/null +++ b/Lang/Bc/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Bc \ No newline at end of file diff --git a/Lang/Bc/Scope-Function-names-and-labels b/Lang/Bc/Scope-Function-names-and-labels new file mode 120000 index 0000000000..834abbaf39 --- /dev/null +++ b/Lang/Bc/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/Bc \ No newline at end of file diff --git a/Lang/Bc/Scope-modifiers b/Lang/Bc/Scope-modifiers new file mode 120000 index 0000000000..d20be4ae81 --- /dev/null +++ b/Lang/Bc/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/Bc \ No newline at end of file diff --git a/Lang/Bc/Sum-and-product-of-an-array b/Lang/Bc/Sum-and-product-of-an-array new file mode 120000 index 0000000000..8c05a67faa --- /dev/null +++ b/Lang/Bc/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Bc \ No newline at end of file diff --git a/Lang/Bc/Sum-digits-of-an-integer b/Lang/Bc/Sum-digits-of-an-integer new file mode 120000 index 0000000000..3d9a8a82a1 --- /dev/null +++ b/Lang/Bc/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Bc \ No newline at end of file diff --git a/Lang/Bc/Sum-multiples-of-3-and-5 b/Lang/Bc/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..477e0b50da --- /dev/null +++ b/Lang/Bc/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Bc \ No newline at end of file diff --git a/Lang/Bc/Sum-of-a-series b/Lang/Bc/Sum-of-a-series new file mode 120000 index 0000000000..4fe4ac8b79 --- /dev/null +++ b/Lang/Bc/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Bc \ No newline at end of file diff --git a/Lang/Bc/Sum-of-squares b/Lang/Bc/Sum-of-squares new file mode 120000 index 0000000000..92749e4a91 --- /dev/null +++ b/Lang/Bc/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Bc \ No newline at end of file diff --git a/Lang/Bc/Terminal-control-Display-an-extended-character b/Lang/Bc/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..71e6377103 --- /dev/null +++ b/Lang/Bc/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Bc \ No newline at end of file diff --git a/Lang/Bc/Trigonometric-functions b/Lang/Bc/Trigonometric-functions new file mode 120000 index 0000000000..1e2552050c --- /dev/null +++ b/Lang/Bc/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Bc \ No newline at end of file diff --git a/Lang/Bc/Van-der-Corput-sequence b/Lang/Bc/Van-der-Corput-sequence new file mode 120000 index 0000000000..381627ca95 --- /dev/null +++ b/Lang/Bc/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Bc \ No newline at end of file diff --git a/Lang/Bc/Variadic-function b/Lang/Bc/Variadic-function new file mode 120000 index 0000000000..4b4e1876e7 --- /dev/null +++ b/Lang/Bc/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Bc \ No newline at end of file diff --git a/Lang/Beeswax/99-Bottles-of-Beer b/Lang/Beeswax/99-Bottles-of-Beer new file mode 120000 index 0000000000..72c69b0cbb --- /dev/null +++ b/Lang/Beeswax/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Ackermann-function b/Lang/Beeswax/Ackermann-function new file mode 120000 index 0000000000..d1e8697f5e --- /dev/null +++ b/Lang/Beeswax/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Bitwise-operations b/Lang/Beeswax/Bitwise-operations new file mode 120000 index 0000000000..be566637bd --- /dev/null +++ b/Lang/Beeswax/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Conditional-structures b/Lang/Beeswax/Conditional-structures new file mode 120000 index 0000000000..36383e9e40 --- /dev/null +++ b/Lang/Beeswax/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Factorial b/Lang/Beeswax/Factorial new file mode 120000 index 0000000000..9ddec32198 --- /dev/null +++ b/Lang/Beeswax/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Fibonacci-sequence b/Lang/Beeswax/Fibonacci-sequence new file mode 120000 index 0000000000..a3144145af --- /dev/null +++ b/Lang/Beeswax/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/FizzBuzz b/Lang/Beeswax/FizzBuzz new file mode 120000 index 0000000000..d21e139e2e --- /dev/null +++ b/Lang/Beeswax/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Hailstone-sequence b/Lang/Beeswax/Hailstone-sequence new file mode 120000 index 0000000000..8a8cdf8677 --- /dev/null +++ b/Lang/Beeswax/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Hello-world-Newline-omission b/Lang/Beeswax/Hello-world-Newline-omission new file mode 120000 index 0000000000..a211be0d76 --- /dev/null +++ b/Lang/Beeswax/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Hello-world-Text b/Lang/Beeswax/Hello-world-Text new file mode 120000 index 0000000000..68ffcf7961 --- /dev/null +++ b/Lang/Beeswax/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Integer-sequence b/Lang/Beeswax/Integer-sequence new file mode 120000 index 0000000000..3ab2d03e93 --- /dev/null +++ b/Lang/Beeswax/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Loops-Infinite b/Lang/Beeswax/Loops-Infinite new file mode 120000 index 0000000000..0f22c4355e --- /dev/null +++ b/Lang/Beeswax/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Quine b/Lang/Beeswax/Quine new file mode 120000 index 0000000000..8b218cc92d --- /dev/null +++ b/Lang/Beeswax/Quine @@ -0,0 +1 @@ +../../Task/Quine/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Repeat-a-string b/Lang/Beeswax/Repeat-a-string new file mode 120000 index 0000000000..793cee6e09 --- /dev/null +++ b/Lang/Beeswax/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Terminal-control-Clear-the-screen b/Lang/Beeswax/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..cb1fe85c39 --- /dev/null +++ b/Lang/Beeswax/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Terminal-control-Display-an-extended-character b/Lang/Beeswax/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..b40767ffe7 --- /dev/null +++ b/Lang/Beeswax/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Beeswax \ No newline at end of file diff --git a/Lang/Beeswax/Terminal-control-Ringing-the-terminal-bell b/Lang/Beeswax/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..20c37fefe5 --- /dev/null +++ b/Lang/Beeswax/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Beeswax \ No newline at end of file diff --git a/Lang/Befunge/99-Bottles-of-Beer b/Lang/Befunge/99-Bottles-of-Beer deleted file mode 120000 index e9cdb8cbe4..0000000000 --- a/Lang/Befunge/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Befunge \ No newline at end of file diff --git a/Lang/Befunge/File-IO b/Lang/Befunge/File-IO deleted file mode 120000 index 60bcbfd2af..0000000000 --- a/Lang/Befunge/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Befunge \ No newline at end of file diff --git a/Lang/Befunge/FizzBuzz b/Lang/Befunge/FizzBuzz deleted file mode 120000 index 766937e42e..0000000000 --- a/Lang/Befunge/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Befunge \ No newline at end of file diff --git a/Lang/Bracmat/Character-matching b/Lang/Bracmat/Character-matching deleted file mode 120000 index 2dd0079e40..0000000000 --- a/Lang/Bracmat/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Doubly-linked-list-Element-definition b/Lang/Bracmat/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..945ef66541 --- /dev/null +++ b/Lang/Bracmat/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/File-IO b/Lang/Bracmat/File-IO deleted file mode 120000 index 67fec306c8..0000000000 --- a/Lang/Bracmat/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Loops-Continue b/Lang/Bracmat/Loops-Continue new file mode 120000 index 0000000000..ad61641a0b --- /dev/null +++ b/Lang/Bracmat/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Bracmat \ 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/Bracmat/Quine b/Lang/Bracmat/Quine deleted file mode 120000 index 406793e6de..0000000000 --- a/Lang/Bracmat/Quine +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quine/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Rosetta-Code-Count-examples b/Lang/Bracmat/Rosetta-Code-Count-examples deleted file mode 120000 index 1c8b3ee689..0000000000 --- a/Lang/Bracmat/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Rosetta-Code-Rank-languages-by-popularity b/Lang/Bracmat/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index df80f1b8cb..0000000000 --- a/Lang/Bracmat/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Bracmat \ No newline at end of file diff --git a/Lang/Brainf---/99-Bottles-of-Beer b/Lang/Brainf---/99-Bottles-of-Beer deleted file mode 120000 index 2ae380be76..0000000000 --- a/Lang/Brainf---/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Brainf--- \ No newline at end of file diff --git a/Lang/Brainf---/Averages-Arithmetic-mean b/Lang/Brainf---/Averages-Arithmetic-mean deleted file mode 120000 index cb841c05d8..0000000000 --- a/Lang/Brainf---/Averages-Arithmetic-mean +++ /dev/null @@ -1 +0,0 @@ -../../Task/Averages-Arithmetic-mean/Brainf--- \ No newline at end of file diff --git a/Lang/Brainf---/FizzBuzz b/Lang/Brainf---/FizzBuzz deleted file mode 120000 index a916b13259..0000000000 --- a/Lang/Brainf---/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Brainf--- \ No newline at end of file diff --git a/Lang/Brat/Conways-Game-of-Life b/Lang/Brat/Conways-Game-of-Life new file mode 120000 index 0000000000..96e736ad19 --- /dev/null +++ b/Lang/Brat/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Brat \ No newline at end of file diff --git a/Lang/C++/00DESCRIPTION b/Lang/C++/00DESCRIPTION index cf522cf3f3..ee87626e06 100644 --- a/Lang/C++/00DESCRIPTION +++ b/Lang/C++/00DESCRIPTION @@ -24,7 +24,8 @@ If you can't find an implementation for your task in the C++ category below, ple * '''TR1''' (Technical Report 1) is a proposal for extensions to the C++ standard library. It was published in 2007. Many of its proposals made it into C++11. Many compilers support it, but put its headers in a different directory. * '''C++11''' (formerly called '''C++0x''' and sometimes '''C++1x''') is a significant improvement, adding many new language features and libraries. It was standardized by ISO in 2011. Most of its features are available in [[GCC]] [http://gcc.gnu.org/projects/cxx0x.html] and [[Clang]] [http://clang.llvm.org/cxx_status.html]. * '''C++14''' (formerly called '''C++1y''') is a minor improvement to C++11, standardized by ISO in 2014. Most of its features are available in [[Clang]] [http://clang.llvm.org/cxx_status.html] and [[GCC]] [http://gcc.gnu.org/projects/cxx1y.html]. -* '''C++17''' (or '''C++1z''') is informal name of future standard which will become in 2017, but many of its features are already published and supported by several compilers. +* '''C++17''' (still currently called '''C++1z''') is a minor improvement to C++14 that has reached ''Draft International Standard'' [https://en.wikipedia.org/wiki/C++17] in March 2017, meaning publication is due very soon. Most of its features are already available in [[Clang]] [http://clang.llvm.org/cxx_status.html] and [[GCC]] [https://gcc.gnu.org/projects/cxx-status.html#cxx14]. +* '''C++2a''' ('''C++20 ''' unofficially) is a major upcoming improvement to C++17 first drafted in July 2017. What proposed features it will have is currently partially implemented by [[Clang]] [http://clang.llvm.org/cxx_status.html] and [[GCC]] [https://gcc.gnu.org/projects/cxx-status.html#tses] {{language programming paradigm|Imperative}} {{language programming paradigm|Object-oriented}} diff --git a/Lang/C++/Character-matching b/Lang/C++/Character-matching deleted file mode 120000 index 3c821871c8..0000000000 --- a/Lang/C++/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/C++ \ No newline at end of file diff --git a/Lang/C++/Combinations-with-repetitions b/Lang/C++/Combinations-with-repetitions new file mode 120000 index 0000000000..276f4c77a3 --- /dev/null +++ b/Lang/C++/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/C++ \ No newline at end of file diff --git a/Lang/C++/File-IO b/Lang/C++/File-IO deleted file mode 120000 index 4c9a81c000..0000000000 --- a/Lang/C++/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/C++ \ No newline at end of file diff --git a/Lang/C++/Find-limit-of-recursion b/Lang/C++/Find-limit-of-recursion new file mode 120000 index 0000000000..cb34cbcef7 --- /dev/null +++ b/Lang/C++/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/C++ \ No newline at end of file diff --git a/Lang/C++/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/C++/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..2a821f87e4 --- /dev/null +++ b/Lang/C++/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/C++ \ No newline at end of file diff --git a/Lang/C++/Pi b/Lang/C++/Pi deleted file mode 120000 index 1d87dd0375..0000000000 --- a/Lang/C++/Pi +++ /dev/null @@ -1 +0,0 @@ -../../Task/Pi/C++ \ No newline at end of file diff --git a/Lang/C++/QR-decomposition b/Lang/C++/QR-decomposition new file mode 120000 index 0000000000..57940a4067 --- /dev/null +++ b/Lang/C++/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/C++ \ No newline at end of file diff --git a/Lang/C++/Rosetta-Code-Rank-languages-by-popularity b/Lang/C++/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 2989c4c31e..0000000000 --- a/Lang/C++/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/C++ \ No newline at end of file diff --git a/Lang/C++/SHA-256 b/Lang/C++/SHA-256 new file mode 120000 index 0000000000..a85a596522 --- /dev/null +++ b/Lang/C++/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/C++ \ No newline at end of file diff --git a/Lang/C++/Standard-deviation b/Lang/C++/Standard-deviation deleted file mode 120000 index ee435d2ebd..0000000000 --- a/Lang/C++/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/C++ \ No newline at end of file diff --git a/Lang/C++/Truncate-a-file b/Lang/C++/Truncate-a-file new file mode 120000 index 0000000000..c214068e6a --- /dev/null +++ b/Lang/C++/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/C++ \ No newline at end of file diff --git a/Lang/C++/Use-another-language-to-call-a-function b/Lang/C++/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..6a6334f1ed --- /dev/null +++ b/Lang/C++/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/C++ \ No newline at end of file diff --git a/Lang/C-sharp/99-Bottles-of-Beer b/Lang/C-sharp/99-Bottles-of-Beer deleted file mode 120000 index 2338fb9478..0000000000 --- a/Lang/C-sharp/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/AKS-test-for-primes b/Lang/C-sharp/AKS-test-for-primes deleted file mode 120000 index 59eb71bffa..0000000000 --- a/Lang/C-sharp/AKS-test-for-primes +++ /dev/null @@ -1 +0,0 @@ -../../Task/AKS-test-for-primes/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Call-a-function b/Lang/C-sharp/Call-a-function new file mode 120000 index 0000000000..3360b61ad2 --- /dev/null +++ b/Lang/C-sharp/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Catalan-numbers-Pascals-triangle b/Lang/C-sharp/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..f2098849fe --- /dev/null +++ b/Lang/C-sharp/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Conways-Game-of-Life b/Lang/C-sharp/Conways-Game-of-Life deleted file mode 120000 index a85a094b2b..0000000000 --- a/Lang/C-sharp/Conways-Game-of-Life +++ /dev/null @@ -1 +0,0 @@ -../../Task/Conways-Game-of-Life/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Forest-fire b/Lang/C-sharp/Forest-fire deleted file mode 120000 index 836abe8c21..0000000000 --- a/Lang/C-sharp/Forest-fire +++ /dev/null @@ -1 +0,0 @@ -../../Task/Forest-fire/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Function-prototype b/Lang/C-sharp/Function-prototype new file mode 120000 index 0000000000..a04a4e0838 --- /dev/null +++ b/Lang/C-sharp/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Literals-Floating-point b/Lang/C-sharp/Literals-Floating-point new file mode 120000 index 0000000000..653b338bea --- /dev/null +++ b/Lang/C-sharp/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Parsing-Shunting-yard-algorithm b/Lang/C-sharp/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..a8dee5580d --- /dev/null +++ b/Lang/C-sharp/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Scope-modifiers b/Lang/C-sharp/Scope-modifiers new file mode 120000 index 0000000000..0cf4a3d3a9 --- /dev/null +++ b/Lang/C-sharp/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Sequence-of-primes-by-Trial-Division b/Lang/C-sharp/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..10138af881 --- /dev/null +++ b/Lang/C-sharp/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Sort-disjoint-sublist b/Lang/C-sharp/Sort-disjoint-sublist new file mode 120000 index 0000000000..5cc6d1fd86 --- /dev/null +++ b/Lang/C-sharp/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/C-sharp \ No newline at end of file diff --git a/Lang/C/Character-matching b/Lang/C/Character-matching deleted file mode 120000 index f7db89c9cd..0000000000 --- a/Lang/C/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/C \ No newline at end of file diff --git a/Lang/C/File-IO b/Lang/C/File-IO deleted file mode 120000 index 9281bf6c1e..0000000000 --- a/Lang/C/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/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/Mutex b/Lang/C/Mutex deleted file mode 120000 index 84410fc327..0000000000 --- a/Lang/C/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/C \ No newline at end of file diff --git a/Lang/C/Nautical-bell b/Lang/C/Nautical-bell new file mode 120000 index 0000000000..25f6b0bb36 --- /dev/null +++ b/Lang/C/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/C \ No newline at end of file diff --git a/Lang/C/Parametrized-SQL-statement b/Lang/C/Parametrized-SQL-statement new file mode 120000 index 0000000000..ff2c9604e8 --- /dev/null +++ b/Lang/C/Parametrized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parametrized-SQL-statement/C \ No newline at end of file diff --git a/Lang/C/Rosetta-Code-Find-bare-lang-tags b/Lang/C/Rosetta-Code-Find-bare-lang-tags deleted file mode 120000 index e0bc95da7b..0000000000 --- a/Lang/C/Rosetta-Code-Find-bare-lang-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-bare-lang-tags/C \ No newline at end of file diff --git a/Lang/C/Rosetta-Code-Rank-languages-by-popularity b/Lang/C/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 51e3f632cf..0000000000 --- a/Lang/C/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/C \ No newline at end of file diff --git a/Lang/C/Sequence-of-primes-by-Trial-Division b/Lang/C/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..f9a39a4fd2 --- /dev/null +++ b/Lang/C/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/C \ No newline at end of file diff --git a/Lang/C/Special-variables b/Lang/C/Special-variables deleted file mode 120000 index ca3623a056..0000000000 --- a/Lang/C/Special-variables +++ /dev/null @@ -1 +0,0 @@ -../../Task/Special-variables/C \ No newline at end of file diff --git a/Lang/C/Standard-deviation b/Lang/C/Standard-deviation deleted file mode 120000 index dacbf5a039..0000000000 --- a/Lang/C/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/C \ No newline at end of file diff --git a/Lang/COBOL/File-IO b/Lang/COBOL/File-IO deleted file mode 120000 index 60c249abbc..0000000000 --- a/Lang/COBOL/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Hostname b/Lang/COBOL/Hostname new file mode 120000 index 0000000000..e9d8bbfbb1 --- /dev/null +++ b/Lang/COBOL/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Standard-deviation b/Lang/COBOL/Standard-deviation deleted file mode 120000 index 9f8fa60e84..0000000000 --- a/Lang/COBOL/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/COBOL \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/Rosetta-Code-Rank-languages-by-popularity b/Lang/Cache-ObjectScript/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 06bfcd3121..0000000000 --- a/Lang/Cache-ObjectScript/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/SEDOLs b/Lang/Cache-ObjectScript/SEDOLs new file mode 120000 index 0000000000..9e221ece35 --- /dev/null +++ b/Lang/Cache-ObjectScript/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/Cache-ObjectScript \ No newline at end of file diff --git a/Task/FizzBuzz/Whitespace/fizzbuzz-1.ws b/Lang/Category-SETL4/00DESCRIPTION similarity index 100% rename from Task/FizzBuzz/Whitespace/fizzbuzz-1.ws rename to Lang/Category-SETL4/00DESCRIPTION diff --git a/Lang/Category-SETL4/README b/Lang/Category-SETL4/README new file mode 100644 index 0000000000..e6990279cb --- /dev/null +++ b/Lang/Category-SETL4/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Category_SETL4 diff --git a/Lang/Ceylon/Polymorphism b/Lang/Ceylon/Polymorphism new file mode 120000 index 0000000000..a520da17c6 --- /dev/null +++ b/Lang/Ceylon/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Set b/Lang/Ceylon/Set new file mode 120000 index 0000000000..846557cffd --- /dev/null +++ b/Lang/Ceylon/Set @@ -0,0 +1 @@ +../../Task/Set/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Set-puzzle b/Lang/Ceylon/Set-puzzle new file mode 120000 index 0000000000..6811bb777e --- /dev/null +++ b/Lang/Ceylon/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Wireworld b/Lang/Ceylon/Wireworld new file mode 120000 index 0000000000..0982c84c6f --- /dev/null +++ b/Lang/Ceylon/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Ceylon \ No newline at end of file diff --git a/Lang/Chef/99-Bottles-of-Beer b/Lang/Chef/99-Bottles-of-Beer deleted file mode 120000 index 0a81826598..0000000000 --- a/Lang/Chef/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Chef \ No newline at end of file diff --git a/Lang/Chef/FizzBuzz b/Lang/Chef/FizzBuzz deleted file mode 120000 index c94a46f378..0000000000 --- a/Lang/Chef/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Chef \ No newline at end of file diff --git a/Lang/Clean/File-IO b/Lang/Clean/File-IO deleted file mode 120000 index b87dc87656..0000000000 --- a/Lang/Clean/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Clean \ No newline at end of file diff --git a/Lang/Clean/Sorting-algorithms-Bubble-sort b/Lang/Clean/Sorting-algorithms-Bubble-sort deleted file mode 120000 index 4c0ff252fa..0000000000 --- a/Lang/Clean/Sorting-algorithms-Bubble-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Bubble-sort/Clean \ No newline at end of file diff --git a/Lang/Clojure/Amicable-pairs b/Lang/Clojure/Amicable-pairs new file mode 120000 index 0000000000..83b94c88f6 --- /dev/null +++ b/Lang/Clojure/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Benfords-law b/Lang/Clojure/Benfords-law new file mode 120000 index 0000000000..b3f07c12af --- /dev/null +++ b/Lang/Clojure/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Carmichael-3-strong-pseudoprimes b/Lang/Clojure/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..fbcbbcfbe9 --- /dev/null +++ b/Lang/Clojure/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Character-matching b/Lang/Clojure/Character-matching deleted file mode 120000 index ca5eff8664..0000000000 --- a/Lang/Clojure/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/Clojure/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..beca97d6ab --- /dev/null +++ b/Lang/Clojure/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Clojure \ No newline at end of file diff --git a/Lang/Clojure/File-IO b/Lang/Clojure/File-IO deleted file mode 120000 index aaeac25989..0000000000 --- a/Lang/Clojure/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Floyds-triangle b/Lang/Clojure/Floyds-triangle new file mode 120000 index 0000000000..7857cd3638 --- /dev/null +++ b/Lang/Clojure/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Knights-tour b/Lang/Clojure/Knights-tour new file mode 120000 index 0000000000..9b1a98151d --- /dev/null +++ b/Lang/Clojure/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Maze-generation b/Lang/Clojure/Maze-generation new file mode 120000 index 0000000000..0d2061cc7b --- /dev/null +++ b/Lang/Clojure/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Maze-solving b/Lang/Clojure/Maze-solving new file mode 120000 index 0000000000..f6791d9e11 --- /dev/null +++ b/Lang/Clojure/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Move-to-front-algorithm b/Lang/Clojure/Move-to-front-algorithm new file mode 120000 index 0000000000..be7f81d733 --- /dev/null +++ b/Lang/Clojure/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Narcissistic-decimal-number b/Lang/Clojure/Narcissistic-decimal-number new file mode 120000 index 0000000000..27d8af1f8e --- /dev/null +++ b/Lang/Clojure/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Order-two-numerical-lists b/Lang/Clojure/Order-two-numerical-lists new file mode 120000 index 0000000000..5e007bd00b --- /dev/null +++ b/Lang/Clojure/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Penneys-game b/Lang/Clojure/Penneys-game new file mode 120000 index 0000000000..86be7b9d21 --- /dev/null +++ b/Lang/Clojure/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Pig-the-dice-game b/Lang/Clojure/Pig-the-dice-game new file mode 120000 index 0000000000..20afc2e5ef --- /dev/null +++ b/Lang/Clojure/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Rosetta-Code-Count-examples b/Lang/Clojure/Rosetta-Code-Count-examples deleted file mode 120000 index cad7ce809d..0000000000 --- a/Lang/Clojure/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Semiprime b/Lang/Clojure/Semiprime new file mode 120000 index 0000000000..d0894bab74 --- /dev/null +++ b/Lang/Clojure/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Standard-deviation b/Lang/Clojure/Standard-deviation deleted file mode 120000 index b55f0b897e..0000000000 --- a/Lang/Clojure/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Text-processing-Max-licenses-in-use b/Lang/Clojure/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..8a44b9372e --- /dev/null +++ b/Lang/Clojure/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Walk-a-directory-Non-recursively b/Lang/Clojure/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..4283139515 --- /dev/null +++ b/Lang/Clojure/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Clojure \ No newline at end of file diff --git a/Lang/CoffeeScript/Character-matching b/Lang/CoffeeScript/Character-matching deleted file mode 120000 index cb8521a139..0000000000 --- a/Lang/CoffeeScript/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/One-dimensional-cellular-automata b/Lang/CoffeeScript/One-dimensional-cellular-automata deleted file mode 120000 index 87a40b2f39..0000000000 --- a/Lang/CoffeeScript/One-dimensional-cellular-automata +++ /dev/null @@ -1 +0,0 @@ -../../Task/One-dimensional-cellular-automata/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Standard-deviation b/Lang/CoffeeScript/Standard-deviation deleted file mode 120000 index a0512f9794..0000000000 --- a/Lang/CoffeeScript/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/CoffeeScript \ No newline at end of file diff --git a/Lang/ColdFusion/File-IO b/Lang/ColdFusion/File-IO deleted file mode 120000 index 5c79c3cb9b..0000000000 --- a/Lang/ColdFusion/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/String-prepend b/Lang/ColdFusion/String-prepend new file mode 120000 index 0000000000..db820018bd --- /dev/null +++ b/Lang/ColdFusion/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Substring b/Lang/ColdFusion/Substring new file mode 120000 index 0000000000..a8560440e7 --- /dev/null +++ b/Lang/ColdFusion/Substring @@ -0,0 +1 @@ +../../Task/Substring/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/System-time b/Lang/ColdFusion/System-time new file mode 120000 index 0000000000..3a18c0acda --- /dev/null +++ b/Lang/ColdFusion/System-time @@ -0,0 +1 @@ +../../Task/System-time/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Tokenize-a-string b/Lang/ColdFusion/Tokenize-a-string new file mode 120000 index 0000000000..6a47382437 --- /dev/null +++ b/Lang/ColdFusion/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Zero-to-the-zero-power b/Lang/ColdFusion/Zero-to-the-zero-power new file mode 120000 index 0000000000..b6ab2282d9 --- /dev/null +++ b/Lang/ColdFusion/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/ColdFusion \ No newline at end of file diff --git a/Lang/Comefrom0x10/00DESCRIPTION b/Lang/Comefrom0x10/00DESCRIPTION new file mode 100644 index 0000000000..a8dfa82043 --- /dev/null +++ b/Lang/Comefrom0x10/00DESCRIPTION @@ -0,0 +1,19 @@ +{{language +|exec=interpreted +|site=https://comefrom0x10.readthedocs.io/en/latest/ +|gc=yes +|checking=dynamic +|hopl=no +|bnf=https://bitbucket.org/julfers/comefrom0x10/src/tip/cf0x10/parser.py}} + +'''Comefrom0x10''' (pronounced "come from sixteen" and abbreviated "cf0x10") is a high-level language that has only one control flow statement: comefrom. Several other languages support comefrom statements and some, like Cf0x10, support no other control flow statements. Cf0x10 is unique in that it is higher level than others of this nature. + +Comefrom0x10 features lexical scope, based on block-level indentation, named identifiers and other hallmarks of structured programming. + +==See also== + +* [https://comefrom0x10.readthedocs.io/en/latest/tutorial/index.html Tutorial] +* [http://www.fortran.com/come_from.html COME FROM statement introduced in DATAMATION] +* [https://esolangs.org/wiki/Comefrom0x10 on Esolangs] + +[[Category:Esoteric Languages]] \ No newline at end of file diff --git a/Lang/Comefrom0x10/99-Bottles-of-Beer b/Lang/Comefrom0x10/99-Bottles-of-Beer new file mode 120000 index 0000000000..c8dbaffbe7 --- /dev/null +++ b/Lang/Comefrom0x10/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Comefrom0x10 \ No newline at end of file diff --git a/Lang/Comefrom0x10/Execute-Brain---- b/Lang/Comefrom0x10/Execute-Brain---- new file mode 120000 index 0000000000..ea987dddd5 --- /dev/null +++ b/Lang/Comefrom0x10/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Comefrom0x10 \ No newline at end of file diff --git a/Lang/Comefrom0x10/Factorial b/Lang/Comefrom0x10/Factorial new file mode 120000 index 0000000000..1feb0a48f4 --- /dev/null +++ b/Lang/Comefrom0x10/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Comefrom0x10 \ No newline at end of file diff --git a/Lang/Comefrom0x10/Fibonacci-sequence b/Lang/Comefrom0x10/Fibonacci-sequence new file mode 120000 index 0000000000..eef44989eb --- /dev/null +++ b/Lang/Comefrom0x10/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Comefrom0x10 \ No newline at end of file diff --git a/Lang/Comefrom0x10/FizzBuzz b/Lang/Comefrom0x10/FizzBuzz new file mode 120000 index 0000000000..5b90dd8ab4 --- /dev/null +++ b/Lang/Comefrom0x10/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Comefrom0x10 \ No newline at end of file diff --git a/Lang/Comefrom0x10/Hello-world-Text b/Lang/Comefrom0x10/Hello-world-Text new file mode 120000 index 0000000000..34650cf9bf --- /dev/null +++ b/Lang/Comefrom0x10/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Comefrom0x10 \ No newline at end of file diff --git a/Lang/Comefrom0x10/README b/Lang/Comefrom0x10/README new file mode 100644 index 0000000000..da949493b3 --- /dev/null +++ b/Lang/Comefrom0x10/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Comefrom0x10 diff --git a/Lang/Commodore-BASIC/00DESCRIPTION b/Lang/Commodore-BASIC/00DESCRIPTION index e6e7a3d3a2..f0149d0a1a 100644 --- a/Lang/Commodore-BASIC/00DESCRIPTION +++ b/Lang/Commodore-BASIC/00DESCRIPTION @@ -1,4 +1,9 @@ -{{language|Commodore BASIC}}{{Implementation|BASIC}} +{{language|Commodore BASIC + |exec=interpreted + |tags=basic,commodorebasic + |gc=yes + }} +{{Implementation|BASIC}} '''Commodore BASIC''' is the collective name for the various versions of [[:Category:BASIC|BASIC]] developed by [[Microsoft]] for [[Commodore]] 8-bit computers, starting with the [[wp:Commodore PET|PET]] in 1977. There were several versions; see [[wp:Commodore BASIC|Wikipedia's Commodore BASIC page]] for details. Commodore BASIC is notable for its lack of integer arithmetic; all operations were carried out in floating-point, which made the interpreter slower than some of its peers. diff --git a/Lang/Common-Lisp/99-Bottles-of-Beer b/Lang/Common-Lisp/99-Bottles-of-Beer deleted file mode 120000 index ff0505e107..0000000000 --- a/Lang/Common-Lisp/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Amicable-pairs b/Lang/Common-Lisp/Amicable-pairs new file mode 120000 index 0000000000..848553719d --- /dev/null +++ b/Lang/Common-Lisp/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Append-a-record-to-the-end-of-a-text-file b/Lang/Common-Lisp/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..09a2f8167f --- /dev/null +++ b/Lang/Common-Lisp/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Bitmap-Histogram b/Lang/Common-Lisp/Bitmap-Histogram new file mode 120000 index 0000000000..acb1408a71 --- /dev/null +++ b/Lang/Common-Lisp/Bitmap-Histogram @@ -0,0 +1 @@ +../../Task/Bitmap-Histogram/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Bitwise-IO b/Lang/Common-Lisp/Bitwise-IO new file mode 120000 index 0000000000..5af861d507 --- /dev/null +++ b/Lang/Common-Lisp/Bitwise-IO @@ -0,0 +1 @@ +../../Task/Bitwise-IO/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Call-an-object-method b/Lang/Common-Lisp/Call-an-object-method new file mode 120000 index 0000000000..e80aeeef33 --- /dev/null +++ b/Lang/Common-Lisp/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Color-quantization b/Lang/Common-Lisp/Color-quantization new file mode 120000 index 0000000000..e9e7f2d676 --- /dev/null +++ b/Lang/Common-Lisp/Color-quantization @@ -0,0 +1 @@ +../../Task/Color-quantization/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/File-IO b/Lang/Common-Lisp/File-IO deleted file mode 120000 index 1ebbe1cc50..0000000000 --- a/Lang/Common-Lisp/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Find-the-last-Sunday-of-each-month b/Lang/Common-Lisp/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..222c36d119 --- /dev/null +++ b/Lang/Common-Lisp/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Four-bit-adder b/Lang/Common-Lisp/Four-bit-adder new file mode 120000 index 0000000000..bedb7eea5a --- /dev/null +++ b/Lang/Common-Lisp/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Hello-world-Line-printer b/Lang/Common-Lisp/Hello-world-Line-printer new file mode 120000 index 0000000000..3779e7410d --- /dev/null +++ b/Lang/Common-Lisp/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/K-d-tree b/Lang/Common-Lisp/K-d-tree new file mode 120000 index 0000000000..0ecd16caac --- /dev/null +++ b/Lang/Common-Lisp/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Knapsack-problem-Continuous b/Lang/Common-Lisp/Knapsack-problem-Continuous new file mode 120000 index 0000000000..ac2cd8f8c2 --- /dev/null +++ b/Lang/Common-Lisp/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Ludic-numbers b/Lang/Common-Lisp/Ludic-numbers new file mode 120000 index 0000000000..85263ee1c1 --- /dev/null +++ b/Lang/Common-Lisp/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/MD5-Implementation b/Lang/Common-Lisp/MD5-Implementation new file mode 120000 index 0000000000..798dee14d4 --- /dev/null +++ b/Lang/Common-Lisp/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Mandelbrot-set b/Lang/Common-Lisp/Mandelbrot-set new file mode 120000 index 0000000000..9d3ab7d84d --- /dev/null +++ b/Lang/Common-Lisp/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/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/Numeric-error-propagation b/Lang/Common-Lisp/Numeric-error-propagation new file mode 120000 index 0000000000..fffb36cae1 --- /dev/null +++ b/Lang/Common-Lisp/Numeric-error-propagation @@ -0,0 +1 @@ +../../Task/Numeric-error-propagation/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Permutations-by-swapping b/Lang/Common-Lisp/Permutations-by-swapping new file mode 120000 index 0000000000..b79cc448cc --- /dev/null +++ b/Lang/Common-Lisp/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Price-fraction b/Lang/Common-Lisp/Price-fraction new file mode 120000 index 0000000000..e20f5488db --- /dev/null +++ b/Lang/Common-Lisp/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Random-number-generator--device- b/Lang/Common-Lisp/Random-number-generator--device- new file mode 120000 index 0000000000..4be5f63d63 --- /dev/null +++ b/Lang/Common-Lisp/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Random-number-generator--included- b/Lang/Common-Lisp/Random-number-generator--included- new file mode 120000 index 0000000000..790fc52575 --- /dev/null +++ b/Lang/Common-Lisp/Random-number-generator--included- @@ -0,0 +1 @@ +../../Task/Random-number-generator--included-/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Set-of-real-numbers b/Lang/Common-Lisp/Set-of-real-numbers new file mode 120000 index 0000000000..8dd1ad6293 --- /dev/null +++ b/Lang/Common-Lisp/Set-of-real-numbers @@ -0,0 +1 @@ +../../Task/Set-of-real-numbers/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Comb-sort b/Lang/Common-Lisp/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..c289f11548 --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Stooge-sort b/Lang/Common-Lisp/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..ce743a2715 --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sparkline-in-unicode b/Lang/Common-Lisp/Sparkline-in-unicode new file mode 120000 index 0000000000..363a2791ae --- /dev/null +++ b/Lang/Common-Lisp/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Standard-deviation b/Lang/Common-Lisp/Standard-deviation deleted file mode 120000 index d902bbccab..0000000000 --- a/Lang/Common-Lisp/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Stern-Brocot-sequence b/Lang/Common-Lisp/Stern-Brocot-sequence new file mode 120000 index 0000000000..1c2ceeec4b --- /dev/null +++ b/Lang/Common-Lisp/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Take-notes-on-the-command-line b/Lang/Common-Lisp/Take-notes-on-the-command-line new file mode 120000 index 0000000000..6fede35af1 --- /dev/null +++ b/Lang/Common-Lisp/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/URL-decoding b/Lang/Common-Lisp/URL-decoding new file mode 120000 index 0000000000..41443b1a96 --- /dev/null +++ b/Lang/Common-Lisp/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/URL-encoding b/Lang/Common-Lisp/URL-encoding new file mode 120000 index 0000000000..6c9e0d1d54 --- /dev/null +++ b/Lang/Common-Lisp/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Common-Lisp \ No newline at end of file diff --git a/Lang/Component-Pascal/99-Bottles-of-Beer b/Lang/Component-Pascal/99-Bottles-of-Beer deleted file mode 120000 index a28c34ddb9..0000000000 --- a/Lang/Component-Pascal/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/ABC-Problem b/Lang/Component-Pascal/ABC-Problem new file mode 120000 index 0000000000..1262f181d6 --- /dev/null +++ b/Lang/Component-Pascal/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Create-a-file b/Lang/Component-Pascal/Create-a-file new file mode 120000 index 0000000000..7a1b586863 --- /dev/null +++ b/Lang/Component-Pascal/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Day-of-the-week b/Lang/Component-Pascal/Day-of-the-week new file mode 120000 index 0000000000..6af6977626 --- /dev/null +++ b/Lang/Component-Pascal/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Delete-a-file b/Lang/Component-Pascal/Delete-a-file new file mode 120000 index 0000000000..329604385f --- /dev/null +++ b/Lang/Component-Pascal/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Digital-root b/Lang/Component-Pascal/Digital-root new file mode 120000 index 0000000000..04c07701ef --- /dev/null +++ b/Lang/Component-Pascal/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Digital-root-Multiplicative-digital-root b/Lang/Component-Pascal/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..6bb92cb5ba --- /dev/null +++ b/Lang/Component-Pascal/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Dot-product b/Lang/Component-Pascal/Dot-product new file mode 120000 index 0000000000..a04cf36e63 --- /dev/null +++ b/Lang/Component-Pascal/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Pascals-triangle b/Lang/Component-Pascal/Pascals-triangle new file mode 120000 index 0000000000..a5bffd107d --- /dev/null +++ b/Lang/Component-Pascal/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Standard-deviation b/Lang/Component-Pascal/Standard-deviation deleted file mode 120000 index d173a69ccb..0000000000 --- a/Lang/Component-Pascal/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Component-Pascal \ No newline at end of file diff --git a/Lang/Coq/Tree-traversal b/Lang/Coq/Tree-traversal new file mode 120000 index 0000000000..e38e9a0bdd --- /dev/null +++ b/Lang/Coq/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Coq \ No newline at end of file diff --git a/Lang/Crystal/Accumulator-factory b/Lang/Crystal/Accumulator-factory new file mode 120000 index 0000000000..1727bd7d2a --- /dev/null +++ b/Lang/Crystal/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Averages-Arithmetic-mean b/Lang/Crystal/Averages-Arithmetic-mean new file mode 120000 index 0000000000..09df65399b --- /dev/null +++ b/Lang/Crystal/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Bitmap b/Lang/Crystal/Bitmap new file mode 120000 index 0000000000..319f8c8a59 --- /dev/null +++ b/Lang/Crystal/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Classes b/Lang/Crystal/Classes new file mode 120000 index 0000000000..bf604d8b56 --- /dev/null +++ b/Lang/Crystal/Classes @@ -0,0 +1 @@ +../../Task/Classes/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Count-in-octal b/Lang/Crystal/Count-in-octal new file mode 120000 index 0000000000..e172fb06a3 --- /dev/null +++ b/Lang/Crystal/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Gray-code b/Lang/Crystal/Gray-code new file mode 120000 index 0000000000..0b4d145d77 --- /dev/null +++ b/Lang/Crystal/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Levenshtein-distance b/Lang/Crystal/Levenshtein-distance new file mode 120000 index 0000000000..fdb0d0d792 --- /dev/null +++ b/Lang/Crystal/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Pi b/Lang/Crystal/Pi new file mode 120000 index 0000000000..6587b54cbf --- /dev/null +++ b/Lang/Crystal/Pi @@ -0,0 +1 @@ +../../Task/Pi/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Reverse-a-string b/Lang/Crystal/Reverse-a-string new file mode 120000 index 0000000000..e43583dd82 --- /dev/null +++ b/Lang/Crystal/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Soundex b/Lang/Crystal/Soundex new file mode 120000 index 0000000000..8ce5e117ce --- /dev/null +++ b/Lang/Crystal/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Crystal \ No newline at end of file diff --git a/Lang/D/Calendar---for-real-programmers b/Lang/D/Calendar---for-real-programmers deleted file mode 120000 index ad4ff5ef7a..0000000000 --- a/Lang/D/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/D \ No newline at end of file diff --git a/Lang/D/Character-matching b/Lang/D/Character-matching deleted file mode 120000 index a177ce7f32..0000000000 --- a/Lang/D/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/D \ No newline at end of file diff --git a/Lang/D/File-IO b/Lang/D/File-IO deleted file mode 120000 index fd653d7b4c..0000000000 --- a/Lang/D/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/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/Mutex b/Lang/D/Mutex deleted file mode 120000 index c782bbc880..0000000000 --- a/Lang/D/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/D \ No newline at end of file diff --git a/Lang/D/Rosetta-Code-Count-examples b/Lang/D/Rosetta-Code-Count-examples deleted file mode 120000 index 978bf02a59..0000000000 --- a/Lang/D/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/D \ No newline at end of file diff --git a/Lang/D/Rosetta-Code-Fix-code-tags b/Lang/D/Rosetta-Code-Fix-code-tags deleted file mode 120000 index 5663332dd6..0000000000 --- a/Lang/D/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/D \ No newline at end of file diff --git a/Lang/D/Rosetta-Code-Rank-languages-by-popularity b/Lang/D/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index cf792155f1..0000000000 --- a/Lang/D/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/D \ No newline at end of file diff --git a/Lang/D/Standard-deviation b/Lang/D/Standard-deviation deleted file mode 120000 index d3a2132ae9..0000000000 --- a/Lang/D/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/D \ No newline at end of file diff --git a/Lang/DCL/Loops-While b/Lang/DCL/Loops-While new file mode 120000 index 0000000000..947c9756af --- /dev/null +++ b/Lang/DCL/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/DCL \ No newline at end of file diff --git a/Lang/DM/00DESCRIPTION b/Lang/DM/00DESCRIPTION new file mode 100644 index 0000000000..0fb43fe3b2 --- /dev/null +++ b/Lang/DM/00DESCRIPTION @@ -0,0 +1,3 @@ +'''DM''' (short for '''Dream Maker''') is a programming language built for the [http://www.byond.com/ BYOND game engine.] + +The official language guide can be found [http://www.byond.com/docs/guide/ here], and the language reference can be found [http://www.byond.com/docs/ref/index.html here]. {{language|DM|exec=bytecode|site=http://www.byond.com/|gc=yes|checking=static}} \ No newline at end of file diff --git a/Lang/DM/Classes b/Lang/DM/Classes new file mode 120000 index 0000000000..88c7a06b53 --- /dev/null +++ b/Lang/DM/Classes @@ -0,0 +1 @@ +../../Task/Classes/DM \ No newline at end of file diff --git a/Lang/DM/Conditional-structures b/Lang/DM/Conditional-structures new file mode 120000 index 0000000000..7bcd267717 --- /dev/null +++ b/Lang/DM/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/DM \ No newline at end of file diff --git a/Lang/DM/Hello-world-Text b/Lang/DM/Hello-world-Text new file mode 120000 index 0000000000..52c0c26f8f --- /dev/null +++ b/Lang/DM/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/DM \ No newline at end of file diff --git a/Lang/DM/README b/Lang/DM/README new file mode 100644 index 0000000000..40e9eff680 --- /dev/null +++ b/Lang/DM/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:DM diff --git a/Lang/DM/Variables b/Lang/DM/Variables new file mode 120000 index 0000000000..9cd3913a61 --- /dev/null +++ b/Lang/DM/Variables @@ -0,0 +1 @@ +../../Task/Variables/DM \ No newline at end of file diff --git a/Lang/DUP/00DESCRIPTION b/Lang/DUP/00DESCRIPTION new file mode 100644 index 0000000000..e5cfd2eee7 --- /dev/null +++ b/Lang/DUP/00DESCRIPTION @@ -0,0 +1,17 @@ +{{language|DUP +|site=http://strlen.com/false-language}} +'''DUP''' is a [[Forth]]-like esoteric programming language invented by Ian Osgood. DUP is a variant/enhancement of Wouter van Oortmerssen’s FALSE language. + +Changes from FALSE include: + +* Change of operators: DIV (integer division) changed to Forth-like MOD/DIV, new OVER operator etc. +* String output changed to string definition. Output has to be handled separately. +* Return stack is fully accessible and can be manipulated. +* Operator definition and override is possible. Access to full Unicode array of symbols for operator names. + + + +* [[eso:DUP|DUP on Esolangs]] +* [http://www.quirkster.com/iano/js/dup.html| Osgood’s online Javascript DUP interpreter] + +[[Category:Esoteric Languages]] \ No newline at end of file diff --git a/Lang/DUP/100-doors b/Lang/DUP/100-doors new file mode 120000 index 0000000000..498bc9eaa9 --- /dev/null +++ b/Lang/DUP/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/DUP \ No newline at end of file diff --git a/Lang/DUP/FizzBuzz b/Lang/DUP/FizzBuzz new file mode 120000 index 0000000000..d481f5fc84 --- /dev/null +++ b/Lang/DUP/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/DUP \ No newline at end of file diff --git a/Lang/DUP/Loops-Do-while b/Lang/DUP/Loops-Do-while new file mode 120000 index 0000000000..d288724fc1 --- /dev/null +++ b/Lang/DUP/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/DUP \ No newline at end of file diff --git a/Lang/DUP/Loops-While b/Lang/DUP/Loops-While new file mode 120000 index 0000000000..29414065ee --- /dev/null +++ b/Lang/DUP/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/DUP \ No newline at end of file diff --git a/Lang/DUP/README b/Lang/DUP/README new file mode 100644 index 0000000000..87c39bfc4a --- /dev/null +++ b/Lang/DUP/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:DUP diff --git a/Lang/Dafny/00DESCRIPTION b/Lang/Dafny/00DESCRIPTION new file mode 100644 index 0000000000..86ff546452 --- /dev/null +++ b/Lang/Dafny/00DESCRIPTION @@ -0,0 +1,11 @@ +{{stub}} +{{language|Daftny}} + +'''Dafny''' is a programming language developed and maintained by Microsoft. It includes built-in specification constructs which can be used to verify the functional correctness of programs. + +The Dafny programming language is designed to support the static verification of programs. It is imperative, sequential, supports generic classes, dynamic allocation, and inductive datatypes, and builds in specification constructs. The specifications include pre- and postconditions, invariants, frame specifications (read and write sets), and termination metrics. + +==Citations== +*[http://stackoverflow.com/tags/dafny/info Stack Overflow:Dafny] +*[https://www.microsoft.com/en-us/research/project/dafny-a-language-and-program-verifier-for-functional-correctness/ Dafny: A language and program verifier for functional correctness] at Microsoft +*[https://github.com/Microsoft/dafny Dafny at GitHub] \ No newline at end of file diff --git a/Lang/Dafny/100-doors b/Lang/Dafny/100-doors new file mode 120000 index 0000000000..e7eb6b79fb --- /dev/null +++ b/Lang/Dafny/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Dafny \ No newline at end of file diff --git a/Lang/Dafny/Hello-world-Text b/Lang/Dafny/Hello-world-Text new file mode 120000 index 0000000000..5e7d04fc28 --- /dev/null +++ b/Lang/Dafny/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Dafny \ No newline at end of file diff --git a/Lang/Dafny/README b/Lang/Dafny/README new file mode 100644 index 0000000000..5ea92509d0 --- /dev/null +++ b/Lang/Dafny/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Dafny diff --git a/Lang/Dart/Count-the-coins b/Lang/Dart/Count-the-coins new file mode 120000 index 0000000000..7255439a8c --- /dev/null +++ b/Lang/Dart/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Dart \ No newline at end of file diff --git a/Lang/Dart/Guess-the-number b/Lang/Dart/Guess-the-number new file mode 120000 index 0000000000..4d97abc17f --- /dev/null +++ b/Lang/Dart/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Dart \ No newline at end of file diff --git a/Lang/Dart/Kaprekar-numbers b/Lang/Dart/Kaprekar-numbers new file mode 120000 index 0000000000..0c08c26c91 --- /dev/null +++ b/Lang/Dart/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Dart \ No newline at end of file diff --git a/Lang/Dart/Least-common-multiple b/Lang/Dart/Least-common-multiple new file mode 120000 index 0000000000..b729d47e3d --- /dev/null +++ b/Lang/Dart/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Dart \ No newline at end of file diff --git a/Lang/Dart/Loops-Infinite b/Lang/Dart/Loops-Infinite new file mode 120000 index 0000000000..889b3fd4a0 --- /dev/null +++ b/Lang/Dart/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Dart \ No newline at end of file diff --git a/Lang/Dart/Middle-three-digits b/Lang/Dart/Middle-three-digits new file mode 120000 index 0000000000..6670c122c4 --- /dev/null +++ b/Lang/Dart/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Dart \ No newline at end of file diff --git a/Lang/Dart/Monte-Carlo-methods b/Lang/Dart/Monte-Carlo-methods new file mode 120000 index 0000000000..3cf690f1a7 --- /dev/null +++ b/Lang/Dart/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/Dart \ No newline at end of file diff --git a/Lang/Dart/Multifactorial b/Lang/Dart/Multifactorial new file mode 120000 index 0000000000..4cd2f20f47 --- /dev/null +++ b/Lang/Dart/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Dart \ No newline at end of file diff --git a/Lang/Dart/Pascals-triangle b/Lang/Dart/Pascals-triangle new file mode 120000 index 0000000000..bf6530f7ab --- /dev/null +++ b/Lang/Dart/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Dart \ No newline at end of file diff --git a/Lang/Dart/Write-language-name-in-3D-ASCII b/Lang/Dart/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..d4e4ba9a1c --- /dev/null +++ b/Lang/Dart/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Dart \ No newline at end of file diff --git a/Lang/Dc/A+B b/Lang/Dc/A+B new file mode 120000 index 0000000000..6ca11185d6 --- /dev/null +++ b/Lang/Dc/A+B @@ -0,0 +1 @@ +../../Task/A+B/Dc \ No newline at end of file diff --git a/Lang/Dc/Arbitrary-precision-integers--included- b/Lang/Dc/Arbitrary-precision-integers--included- new file mode 120000 index 0000000000..9fef36f785 --- /dev/null +++ b/Lang/Dc/Arbitrary-precision-integers--included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers--included-/Dc \ No newline at end of file diff --git a/Lang/Dc/Arithmetic-Integer b/Lang/Dc/Arithmetic-Integer new file mode 120000 index 0000000000..d38bdb9bec --- /dev/null +++ b/Lang/Dc/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Dc \ No newline at end of file diff --git a/Lang/Dc/Averages-Arithmetic-mean b/Lang/Dc/Averages-Arithmetic-mean new file mode 120000 index 0000000000..834c274bfa --- /dev/null +++ b/Lang/Dc/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Dc \ No newline at end of file diff --git a/Lang/Dc/Binary-digits b/Lang/Dc/Binary-digits new file mode 120000 index 0000000000..2101612aa3 --- /dev/null +++ b/Lang/Dc/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Dc \ No newline at end of file diff --git a/Lang/Dc/Case-sensitivity-of-identifiers b/Lang/Dc/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..a80e247eff --- /dev/null +++ b/Lang/Dc/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Dc \ No newline at end of file diff --git a/Lang/Dc/Comments b/Lang/Dc/Comments new file mode 120000 index 0000000000..ec18ce2ddb --- /dev/null +++ b/Lang/Dc/Comments @@ -0,0 +1 @@ +../../Task/Comments/Dc \ No newline at end of file diff --git a/Lang/Dc/Copy-a-string b/Lang/Dc/Copy-a-string new file mode 120000 index 0000000000..9b2de6a6c8 --- /dev/null +++ b/Lang/Dc/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Dc \ No newline at end of file diff --git a/Lang/Dc/Ethiopian-multiplication b/Lang/Dc/Ethiopian-multiplication new file mode 120000 index 0000000000..ef3c20c39e --- /dev/null +++ b/Lang/Dc/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Dc \ No newline at end of file diff --git a/Lang/Dc/Evaluate-binomial-coefficients b/Lang/Dc/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..6d910df309 --- /dev/null +++ b/Lang/Dc/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Dc \ No newline at end of file diff --git a/Lang/Dc/Execute-a-system-command b/Lang/Dc/Execute-a-system-command new file mode 120000 index 0000000000..1f0393e988 --- /dev/null +++ b/Lang/Dc/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Dc \ No newline at end of file diff --git a/Lang/Dc/Factorial b/Lang/Dc/Factorial new file mode 120000 index 0000000000..6a23d7b4f8 --- /dev/null +++ b/Lang/Dc/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Dc \ No newline at end of file diff --git a/Lang/Dc/FizzBuzz b/Lang/Dc/FizzBuzz new file mode 120000 index 0000000000..19f0ce2622 --- /dev/null +++ b/Lang/Dc/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Dc \ No newline at end of file diff --git a/Lang/Dc/Formatted-numeric-output b/Lang/Dc/Formatted-numeric-output new file mode 120000 index 0000000000..6606d802b8 --- /dev/null +++ b/Lang/Dc/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Dc \ No newline at end of file diff --git a/Lang/Dc/Function-definition b/Lang/Dc/Function-definition new file mode 120000 index 0000000000..d5256e7205 --- /dev/null +++ b/Lang/Dc/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Dc \ No newline at end of file diff --git a/Lang/Dc/Generic-swap b/Lang/Dc/Generic-swap new file mode 120000 index 0000000000..80965b4e85 --- /dev/null +++ b/Lang/Dc/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Dc \ No newline at end of file diff --git a/Lang/Dc/Greatest-element-of-a-list b/Lang/Dc/Greatest-element-of-a-list new file mode 120000 index 0000000000..42093b0262 --- /dev/null +++ b/Lang/Dc/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Dc \ No newline at end of file diff --git a/Lang/Dc/Happy-numbers b/Lang/Dc/Happy-numbers new file mode 120000 index 0000000000..a79d3ee933 --- /dev/null +++ b/Lang/Dc/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Dc \ No newline at end of file diff --git a/Lang/Dc/Hello-world-Text b/Lang/Dc/Hello-world-Text new file mode 120000 index 0000000000..f9e0cd21bb --- /dev/null +++ b/Lang/Dc/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Dc \ No newline at end of file diff --git a/Lang/Dc/Linear-congruential-generator b/Lang/Dc/Linear-congruential-generator new file mode 120000 index 0000000000..0a5cb2efad --- /dev/null +++ b/Lang/Dc/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/Dc \ No newline at end of file diff --git a/Lang/Dc/Loops-Break b/Lang/Dc/Loops-Break new file mode 120000 index 0000000000..8fb37e73ec --- /dev/null +++ b/Lang/Dc/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Dc \ No newline at end of file diff --git a/Lang/Dc/Loops-Continue b/Lang/Dc/Loops-Continue new file mode 120000 index 0000000000..74738c7dc6 --- /dev/null +++ b/Lang/Dc/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Dc \ No newline at end of file diff --git a/Lang/Dc/Loops-Do-while b/Lang/Dc/Loops-Do-while new file mode 120000 index 0000000000..ac3b8744b4 --- /dev/null +++ b/Lang/Dc/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Dc \ No newline at end of file diff --git a/Lang/Dc/Loops-Downward-for b/Lang/Dc/Loops-Downward-for new file mode 120000 index 0000000000..f9f320d319 --- /dev/null +++ b/Lang/Dc/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Dc \ No newline at end of file diff --git a/Lang/Dc/Loops-For b/Lang/Dc/Loops-For new file mode 120000 index 0000000000..27f6328195 --- /dev/null +++ b/Lang/Dc/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Dc \ No newline at end of file diff --git a/Lang/Dc/Loops-Infinite b/Lang/Dc/Loops-Infinite new file mode 120000 index 0000000000..b44466bd3a --- /dev/null +++ b/Lang/Dc/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Dc \ No newline at end of file diff --git a/Lang/Dc/Loops-Nested b/Lang/Dc/Loops-Nested new file mode 120000 index 0000000000..ae2c415882 --- /dev/null +++ b/Lang/Dc/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Dc \ No newline at end of file diff --git a/Lang/Dc/Quine b/Lang/Dc/Quine new file mode 120000 index 0000000000..9f114cd2bc --- /dev/null +++ b/Lang/Dc/Quine @@ -0,0 +1 @@ +../../Task/Quine/Dc \ No newline at end of file diff --git a/Lang/Dc/Subtractive-generator b/Lang/Dc/Subtractive-generator new file mode 120000 index 0000000000..cc4e266a21 --- /dev/null +++ b/Lang/Dc/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Dc \ No newline at end of file diff --git a/Lang/Dc/Sum-and-product-of-an-array b/Lang/Dc/Sum-and-product-of-an-array new file mode 120000 index 0000000000..92d80476ce --- /dev/null +++ b/Lang/Dc/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Dc \ No newline at end of file diff --git a/Lang/Dc/The-Twelve-Days-of-Christmas b/Lang/Dc/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..b04bc554f1 --- /dev/null +++ b/Lang/Dc/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Dc \ No newline at end of file diff --git a/Lang/Delphi/99-Bottles-of-Beer b/Lang/Delphi/99-Bottles-of-Beer deleted file mode 120000 index 1712f9b8e3..0000000000 --- a/Lang/Delphi/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Character-matching b/Lang/Delphi/Character-matching deleted file mode 120000 index 0db34575de..0000000000 --- a/Lang/Delphi/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Delphi \ No newline at end of file diff --git a/Lang/Delphi/File-IO b/Lang/Delphi/File-IO deleted file mode 120000 index 959676f5cc..0000000000 --- a/Lang/Delphi/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Standard-deviation b/Lang/Delphi/Standard-deviation deleted file mode 120000 index e4c6be14a1..0000000000 --- a/Lang/Delphi/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Delphi \ No newline at end of file diff --git a/Lang/Dodo0/Concurrent-computing b/Lang/Dodo0/Concurrent-computing new file mode 120000 index 0000000000..97bf05dd79 --- /dev/null +++ b/Lang/Dodo0/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/Dodo0 \ No newline at end of file diff --git a/Lang/Dodo0/Execute-Brain---- b/Lang/Dodo0/Execute-Brain---- new file mode 120000 index 0000000000..41601dbfb5 --- /dev/null +++ b/Lang/Dodo0/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Dodo0 \ No newline at end of file diff --git a/Lang/Dodo0/Loops-For b/Lang/Dodo0/Loops-For new file mode 120000 index 0000000000..b71e6943c5 --- /dev/null +++ b/Lang/Dodo0/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Dodo0 \ No newline at end of file diff --git a/Lang/E/Character-matching b/Lang/E/Character-matching deleted file mode 120000 index b0aea42ad3..0000000000 --- a/Lang/E/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/E \ No newline at end of file diff --git a/Lang/E/File-IO b/Lang/E/File-IO deleted file mode 120000 index 7176049a46..0000000000 --- a/Lang/E/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/E \ 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/Mutex b/Lang/E/Mutex deleted file mode 120000 index b93f8c50c9..0000000000 --- a/Lang/E/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/E \ No newline at end of file diff --git a/Lang/E/Standard-deviation b/Lang/E/Standard-deviation deleted file mode 120000 index 606d9f7d55..0000000000 --- a/Lang/E/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/E \ No newline at end of file diff --git a/Lang/EC/Conways-Game-of-Life b/Lang/EC/Conways-Game-of-Life new file mode 120000 index 0000000000..f16413ca73 --- /dev/null +++ b/Lang/EC/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/EC \ No newline at end of file diff --git a/Lang/EC/Empty-program b/Lang/EC/Empty-program new file mode 120000 index 0000000000..50170b4d9c --- /dev/null +++ b/Lang/EC/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/EC \ No newline at end of file diff --git a/Lang/EC/Hello-world-Graphical b/Lang/EC/Hello-world-Graphical new file mode 120000 index 0000000000..e92e6ccd84 --- /dev/null +++ b/Lang/EC/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/EC \ No newline at end of file diff --git a/Lang/EC/Hello-world-Text b/Lang/EC/Hello-world-Text new file mode 120000 index 0000000000..77efcfb5de --- /dev/null +++ b/Lang/EC/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/EC \ No newline at end of file diff --git a/Lang/EC/Mandelbrot-set b/Lang/EC/Mandelbrot-set new file mode 120000 index 0000000000..82312e6f62 --- /dev/null +++ b/Lang/EC/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/EC \ No newline at end of file diff --git a/Lang/EC/OpenGL b/Lang/EC/OpenGL new file mode 120000 index 0000000000..93bcd6cd1e --- /dev/null +++ b/Lang/EC/OpenGL @@ -0,0 +1 @@ +../../Task/OpenGL/EC \ No newline at end of file diff --git a/Lang/EC/Sieve-of-Eratosthenes b/Lang/EC/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..e1c1ba26da --- /dev/null +++ b/Lang/EC/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/EC \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Copy-a-string b/Lang/EDSAC-order-code/Copy-a-string new file mode 120000 index 0000000000..77e6032ede --- /dev/null +++ b/Lang/EDSAC-order-code/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Even-or-odd b/Lang/EDSAC-order-code/Even-or-odd new file mode 120000 index 0000000000..3837a8052f --- /dev/null +++ b/Lang/EDSAC-order-code/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Hello-world-Line-printer b/Lang/EDSAC-order-code/Hello-world-Line-printer new file mode 120000 index 0000000000..2205ba03d4 --- /dev/null +++ b/Lang/EDSAC-order-code/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Loops-Downward-for b/Lang/EDSAC-order-code/Loops-Downward-for new file mode 120000 index 0000000000..d3bd2e4a70 --- /dev/null +++ b/Lang/EDSAC-order-code/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Loops-Infinite b/Lang/EDSAC-order-code/Loops-Infinite new file mode 120000 index 0000000000..4dd9fe60fd --- /dev/null +++ b/Lang/EDSAC-order-code/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Loops-N-plus-one-half b/Lang/EDSAC-order-code/Loops-N-plus-one-half new file mode 120000 index 0000000000..a8e20b3eb9 --- /dev/null +++ b/Lang/EDSAC-order-code/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EGL/Rosetta-Code-Count-examples b/Lang/EGL/Rosetta-Code-Count-examples deleted file mode 120000 index 03b7618460..0000000000 --- a/Lang/EGL/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/EGL \ No newline at end of file diff --git a/Lang/ERRE/Conways-Game-of-Life b/Lang/ERRE/Conways-Game-of-Life new file mode 120000 index 0000000000..3c6ff33ad6 --- /dev/null +++ b/Lang/ERRE/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/ERRE \ No newline at end of file diff --git a/Lang/ERRE/Determine-if-a-string-is-numeric b/Lang/ERRE/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..ac8dac2199 --- /dev/null +++ b/Lang/ERRE/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/ERRE \ No newline at end of file diff --git a/Lang/ESQL/Empty-program b/Lang/ESQL/Empty-program new file mode 120000 index 0000000000..0cae37fb52 --- /dev/null +++ b/Lang/ESQL/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/ESQL \ No newline at end of file diff --git a/Lang/EchoLisp/GUI-component-interaction b/Lang/EchoLisp/GUI-component-interaction new file mode 120000 index 0000000000..ed8c5b6e9a --- /dev/null +++ b/Lang/EchoLisp/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/EchoLisp \ No newline at end of file diff --git a/Lang/Eiffel/File-IO b/Lang/Eiffel/File-IO deleted file mode 120000 index 675eaf7662..0000000000 --- a/Lang/Eiffel/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Eiffel \ No newline at end of file diff --git a/Lang/ElastiC/Hello-world-Text b/Lang/ElastiC/Hello-world-Text new file mode 120000 index 0000000000..207cd606aa --- /dev/null +++ b/Lang/ElastiC/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/ElastiC \ No newline at end of file diff --git a/Lang/Elena/00DESCRIPTION b/Lang/Elena/00DESCRIPTION index c737720fc5..b909c1eb0a 100644 --- a/Lang/Elena/00DESCRIPTION +++ b/Lang/Elena/00DESCRIPTION @@ -56,9 +56,7 @@ Note: In most cases "<<" is a synonym to "write" and "+" to "add". Several parameters can be passed in the message as well: - control foreach: (1,2,3) &do:printingLn. - -Ampersand is used to indicate that the signature has several arguments (subjects). The actual message name is eval&foreach&do(2). + control foreach: (1,2,3) do:printingLn. The generic message can have several parameters as well: @@ -76,66 +74,65 @@ To work with the class we have to create its instance with the help of the speci Classes form the inheritance tree. There is the common super class - system'Object. ELENA does not support multiple inheritance, though it is possible to inherit the code using redirect handler (so called "horizontal inheritance"). When the parent is not provided the class inherits directly system'Object (the super class). - #class BaseClass + class BaseClass { - #field theField1. - #field theField2. + object theField1. + object theField2. - #method field1 = theField1. - - #method field2 = theField. + field1 = theField1. + field2 = theField. } - #class DerivedClass : BaseClass + class DerivedClass :: BaseClass { - #constructor new &field1:aField2 &field2:aField2 + constructor new field1:aField2 field2:aField2 [ theField1 := aField1. theField2 := aField2. ] - #method add &field1:aField2 &field2:aField2 - = MyClass new &Field1:(theField1 + aField1) &Field2:(theField2 + aField2). + add field1:aField2 field2:aField2 + = MyClass new Field1:(theField1 + aField1) Field2:(theField2 + aField2). } To create a class instance we have to send a message (usually new) to its symbol (a class symbol is declared implicitly for every class and can be used as a normal one) - #var anObject := DerivedClass new &field1:1 &field2:1. // DerivedClass is a symbol + var anObject := DerivedClass new field1:1 field2:1. // DerivedClass is a symbol -Roles cannot have constructors and their symbols can be used directly +Singletons cannot have constructors and their symbols can be used directly - #class(role)ClassHelper + class ClassHelper = { - #method sumOf:anObject1:anObject2 - = anObject1 add &field1::anObject2 &field2::anObject1. + sumOf:a:b + = a add field1:b field2:a. } ... - #var aSum := ClassHelper sumOf:anObject1:anObject2. + var aSum := ClassHelper sumOf:1:2. In general the symbol is a named expression and can be used to declare initialized objects, constants, reusable expressions and so on. - #symbol ZeroClass = DerivedClass new &field:0 &field:0. + symbol ZeroClass = DerivedClass new field:0 field:0. A static symbol is the class instance which state is preserved. There could be only one instance of static symbol. - #static SingletonClass = DerivedClass new &field:0 &field:0. + static SingletonClass = DerivedClass new field:0 field:0. == Code blocks == ELENA code block consists of a sequence of statements. The block is enclosed in square brackets and may contain nested sub code blocks (which in fact are inline action classes). The statement terminator is a dot. - #method printAckermann &n:n &m:m + printAckermann n:n m:m [ - control forrange &int:0 &int:n &do: (&int:i) + control forrange int:0 int:n do: (&int:i) [ - control forrange &int:0 &int:m &do: (&int:j) + control forrange int:0 int:m do: (&int:j) [ ... - console writeLine. + console writeLine ]. ]. ] @@ -145,49 +142,42 @@ When a method should return a result (other than self) return statement is used. [ ... - ^ aRetVal / anArray length. + ^ aRetVal / anArray length ] If the code block contains only return statement the simplified syntax can be used: - #method Number = convertor toReal:theValue. - -or there is an alternative block expression - - [ convertor toReal:theValue ] - -Note: it should not end with the terminator symbol + Number = convertor toReal:theValue. It is possible to declare the block variable and assigns the value to it. The variable name must be unique within the code block scope. - #var aRetVal := Integer new:0. + var aRetVal := Integer new:0. == Conditional branching == ELENA like Smalltalk does not support any special language constructs to implement the conditional branching. Instead special Boolean symbols (system’true and system’false) are used. All conditional operations should return these symbols as a result. -There are three branching methods : then[1] , then&else[2], else[1] +There are three branching methods : if[1] , if[2], else[1] - (m == 0) then: + (m == 0) if: [ n + 1 ] - &else: [ + : [ m + n ]. Note that code in square brackets are in fact nested action classes ( an action class is a class supporting evaluate message). So this code is can be written in this form: - (m == 0) then: + (m == 0) if: { eval [ ^ n + 1. ] } - &else: - { + : { eval [ ^ m + n. @@ -197,46 +187,54 @@ Note that code in square brackets are in fact nested action classes ( an action This expression can be written using special operators (m == 0) - ? [ n + 1 ] - ! [ m + n ]. + ? [ ^n + 1 ] + ! [ ^m + n ]. Note: the main difference between using explicit messages and conditional operators is that the compiler may optimize the resulting code in the later case. We could omit true or else part (m == 0) - ! [ m / n ]. + ! [ ^m / n ]. + +It is possible to use *if* template code : + + if (m == 0) + [ n := n + 1. ]; + [ n := m + n. ]. + +In this case the compiler always use optimized code for branching Boolean symbols supports basic logical operations (AND, OR, XOR and NOT), so several conditions can be checked - (aChar >= 48) and:(aChar < 58) - ? [ - theToken += aChar. - ] - ! [ - #throw Exception new:"Invalid expression". + if (aChar >= 48) and:(aChar < 58) + [ + theToken append:aChar. + ]; + [ + Exception new:"Invalid expression"; raise. ] Note that in this case both condition will be evaluated even if the first one is false If we want to use short-circuit evaluation expression brackets should be used - (x >= 0)and:[ array@x != 0] ? + if ((x >= 0)and:$(array@x != 0)) [ ... ] A switch statement can be implemented using => operator - ^ aBulls => - -1 ? [ consoleEx writeLine:"Not a valid guess.". ^ true. ] - 4 ? [ + aBulls => + -1 [ consoleEx writeLine:"Not a valid guess.". ^ true ]; + 4 [ consoleEx writeLine:"Congratulations! You have won!". - ^ false. - ] + ^ false + ]; ! [ - theAttempt += 1. + theAttempt append:1. consoleEx writeLine: "Your Score is " : aBulls : " bulls and " : aCows : " cows". - ^ true. + ^ true ]. \ No newline at end of file diff --git a/Lang/Elena/Calendar---for-real-programmers b/Lang/Elena/Calendar---for-real-programmers deleted file mode 120000 index fdf584337b..0000000000 --- a/Lang/Elena/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/Elena \ No newline at end of file diff --git a/Lang/Elena/Case-sensitivity-of-identifiers b/Lang/Elena/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..7de31acf17 --- /dev/null +++ b/Lang/Elena/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Elena \ No newline at end of file diff --git a/Lang/Elena/Character-matching b/Lang/Elena/Character-matching deleted file mode 120000 index 842017d3ac..0000000000 --- a/Lang/Elena/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Elena \ No newline at end of file diff --git a/Lang/Elena/Conways-Game-of-Life b/Lang/Elena/Conways-Game-of-Life new file mode 120000 index 0000000000..d33f63a782 --- /dev/null +++ b/Lang/Elena/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Elena \ No newline at end of file diff --git a/Lang/Elena/Define-a-primitive-data-type b/Lang/Elena/Define-a-primitive-data-type new file mode 120000 index 0000000000..75d10fde95 --- /dev/null +++ b/Lang/Elena/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/Elena \ No newline at end of file diff --git a/Lang/Elena/Entropy b/Lang/Elena/Entropy new file mode 120000 index 0000000000..ccfebd5e71 --- /dev/null +++ b/Lang/Elena/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Elena \ No newline at end of file diff --git a/Lang/Elena/Exceptions b/Lang/Elena/Exceptions new file mode 120000 index 0000000000..158aa29769 --- /dev/null +++ b/Lang/Elena/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Elena \ No newline at end of file diff --git a/Lang/Elena/Execute-Brain---- b/Lang/Elena/Execute-Brain---- deleted file mode 120000 index 93f688098a..0000000000 --- a/Lang/Elena/Execute-Brain---- +++ /dev/null @@ -1 +0,0 @@ -../../Task/Execute-Brain----/Elena \ No newline at end of file diff --git a/Lang/Elena/First-class-functions-Use-numbers-analogously b/Lang/Elena/First-class-functions-Use-numbers-analogously new file mode 120000 index 0000000000..a406be790a --- /dev/null +++ b/Lang/Elena/First-class-functions-Use-numbers-analogously @@ -0,0 +1 @@ +../../Task/First-class-functions-Use-numbers-analogously/Elena \ No newline at end of file diff --git a/Lang/Elena/Function-composition b/Lang/Elena/Function-composition new file mode 120000 index 0000000000..92fa8b3a5c --- /dev/null +++ b/Lang/Elena/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Elena \ No newline at end of file diff --git a/Lang/Elena/Function-definition b/Lang/Elena/Function-definition new file mode 120000 index 0000000000..5fd4eae1dd --- /dev/null +++ b/Lang/Elena/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Elena \ No newline at end of file diff --git a/Lang/Elena/Generic-swap b/Lang/Elena/Generic-swap new file mode 120000 index 0000000000..2473568934 --- /dev/null +++ b/Lang/Elena/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Elena \ No newline at end of file diff --git a/Lang/Elena/Greatest-element-of-a-list b/Lang/Elena/Greatest-element-of-a-list new file mode 120000 index 0000000000..d1cfa8fd84 --- /dev/null +++ b/Lang/Elena/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Elena \ No newline at end of file diff --git a/Lang/Elena/Partial-function-application b/Lang/Elena/Partial-function-application new file mode 120000 index 0000000000..02a69602b5 --- /dev/null +++ b/Lang/Elena/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Elena \ No newline at end of file diff --git a/Lang/Elena/Real-constants-and-functions b/Lang/Elena/Real-constants-and-functions new file mode 120000 index 0000000000..2f11a4cb71 --- /dev/null +++ b/Lang/Elena/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Elena \ No newline at end of file diff --git a/Lang/Elena/Respond-to-an-unknown-method-call b/Lang/Elena/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..2e55abfdb5 --- /dev/null +++ b/Lang/Elena/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/Elena \ No newline at end of file diff --git a/Lang/Elena/Return-multiple-values b/Lang/Elena/Return-multiple-values new file mode 120000 index 0000000000..a89fa4b88c --- /dev/null +++ b/Lang/Elena/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Elena \ No newline at end of file diff --git a/Lang/Elena/Sorting-algorithms-Bubble-sort b/Lang/Elena/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..5090fa82fb --- /dev/null +++ b/Lang/Elena/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Elena \ No newline at end of file diff --git a/Lang/Elena/Stack-traces b/Lang/Elena/Stack-traces new file mode 120000 index 0000000000..fd63b6499e --- /dev/null +++ b/Lang/Elena/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Elena \ No newline at end of file diff --git a/Lang/Elena/Sum-of-a-series b/Lang/Elena/Sum-of-a-series new file mode 120000 index 0000000000..36292a1353 --- /dev/null +++ b/Lang/Elena/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Elena \ No newline at end of file diff --git a/Lang/Elena/Sum-of-squares b/Lang/Elena/Sum-of-squares new file mode 120000 index 0000000000..16ed44e00c --- /dev/null +++ b/Lang/Elena/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Elena \ No newline at end of file diff --git a/Lang/Elena/Variadic-function b/Lang/Elena/Variadic-function new file mode 120000 index 0000000000..8e5f5b795e --- /dev/null +++ b/Lang/Elena/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Elena \ No newline at end of file diff --git a/Lang/Elena/Word-wrap b/Lang/Elena/Word-wrap new file mode 120000 index 0000000000..8123bebbf2 --- /dev/null +++ b/Lang/Elena/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Elena \ No newline at end of file diff --git a/Lang/Elena/Y-combinator b/Lang/Elena/Y-combinator new file mode 120000 index 0000000000..c0e398151e --- /dev/null +++ b/Lang/Elena/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Elena \ No newline at end of file diff --git a/Lang/Elena/Zeckendorf-arithmetic b/Lang/Elena/Zeckendorf-arithmetic new file mode 120000 index 0000000000..2c644481a7 --- /dev/null +++ b/Lang/Elena/Zeckendorf-arithmetic @@ -0,0 +1 @@ +../../Task/Zeckendorf-arithmetic/Elena \ No newline at end of file diff --git a/Lang/Elena/Zeckendorf-number-representation b/Lang/Elena/Zeckendorf-number-representation new file mode 120000 index 0000000000..260cbfa19b --- /dev/null +++ b/Lang/Elena/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Elena \ No newline at end of file diff --git a/Lang/Elena/Zero-to-the-zero-power b/Lang/Elena/Zero-to-the-zero-power new file mode 120000 index 0000000000..c6ab9a541b --- /dev/null +++ b/Lang/Elena/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Elena \ No newline at end of file diff --git a/Lang/Elena/Zhang-Suen-thinning-algorithm b/Lang/Elena/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..f618b8cd73 --- /dev/null +++ b/Lang/Elena/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Elena \ No newline at end of file diff --git a/Lang/Elena/Zig-zag-matrix b/Lang/Elena/Zig-zag-matrix new file mode 120000 index 0000000000..08b9d269a2 --- /dev/null +++ b/Lang/Elena/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Elena \ No newline at end of file diff --git a/Lang/Elixir/Binary-strings b/Lang/Elixir/Binary-strings new file mode 120000 index 0000000000..db8a2f7bad --- /dev/null +++ b/Lang/Elixir/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Create-an-HTML-table b/Lang/Elixir/Create-an-HTML-table new file mode 120000 index 0000000000..8e46f44614 --- /dev/null +++ b/Lang/Elixir/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Deal-cards-for-FreeCell b/Lang/Elixir/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..5d49a80104 --- /dev/null +++ b/Lang/Elixir/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Factors-of-a-Mersenne-number b/Lang/Elixir/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..be26cb580a --- /dev/null +++ b/Lang/Elixir/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Knapsack-problem-0-1 b/Lang/Elixir/Knapsack-problem-0-1 new file mode 120000 index 0000000000..c80a754a76 --- /dev/null +++ b/Lang/Elixir/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Knapsack-problem-Unbounded b/Lang/Elixir/Knapsack-problem-Unbounded new file mode 120000 index 0000000000..8e9825c7d9 --- /dev/null +++ b/Lang/Elixir/Knapsack-problem-Unbounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Unbounded/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Number-names b/Lang/Elixir/Number-names new file mode 120000 index 0000000000..5ed93718eb --- /dev/null +++ b/Lang/Elixir/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Queue-Usage b/Lang/Elixir/Queue-Usage new file mode 120000 index 0000000000..14e7008c1d --- /dev/null +++ b/Lang/Elixir/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/Elixir \ No newline at end of file diff --git a/Lang/Elm/100-doors b/Lang/Elm/100-doors new file mode 120000 index 0000000000..59b669bd71 --- /dev/null +++ b/Lang/Elm/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Elm \ No newline at end of file diff --git a/Lang/Elm/A+B b/Lang/Elm/A+B new file mode 120000 index 0000000000..45c5b4fc99 --- /dev/null +++ b/Lang/Elm/A+B @@ -0,0 +1 @@ +../../Task/A+B/Elm \ No newline at end of file diff --git a/Lang/Elm/Bitmap-Bresenhams-line-algorithm b/Lang/Elm/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..8af3ba721d --- /dev/null +++ b/Lang/Elm/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/Elm \ No newline at end of file diff --git a/Lang/Elm/Boolean-values b/Lang/Elm/Boolean-values new file mode 120000 index 0000000000..a82ab629c7 --- /dev/null +++ b/Lang/Elm/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Elm \ No newline at end of file diff --git a/Lang/Elm/Compound-data-type b/Lang/Elm/Compound-data-type new file mode 120000 index 0000000000..9d7ae93fd6 --- /dev/null +++ b/Lang/Elm/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/Elm \ No newline at end of file diff --git a/Lang/Elm/Empty-program b/Lang/Elm/Empty-program new file mode 120000 index 0000000000..e45072ad70 --- /dev/null +++ b/Lang/Elm/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Elm \ No newline at end of file diff --git a/Lang/Elm/Function-definition b/Lang/Elm/Function-definition new file mode 120000 index 0000000000..0800e61aba --- /dev/null +++ b/Lang/Elm/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Elm \ No newline at end of file diff --git a/Lang/Elm/Haversine-formula b/Lang/Elm/Haversine-formula new file mode 120000 index 0000000000..beb8f50bd1 --- /dev/null +++ b/Lang/Elm/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Elm \ No newline at end of file diff --git a/Lang/Elm/Logical-operations b/Lang/Elm/Logical-operations new file mode 120000 index 0000000000..bfa78d00cf --- /dev/null +++ b/Lang/Elm/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Elm \ No newline at end of file diff --git a/Lang/Emacs-Lisp/A+B b/Lang/Emacs-Lisp/A+B new file mode 120000 index 0000000000..80d22dec7a --- /dev/null +++ b/Lang/Emacs-Lisp/A+B @@ -0,0 +1 @@ +../../Task/A+B/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Standard-deviation b/Lang/Emacs-Lisp/Standard-deviation deleted file mode 120000 index 5fe66f8f9a..0000000000 --- a/Lang/Emacs-Lisp/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Erlang/Catalan-numbers-Pascals-triangle b/Lang/Erlang/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..30b533f30e --- /dev/null +++ b/Lang/Erlang/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Character-matching b/Lang/Erlang/Character-matching deleted file mode 120000 index bccd441830..0000000000 --- a/Lang/Erlang/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Erlang \ No newline at end of file diff --git a/Lang/Erlang/DNS-query b/Lang/Erlang/DNS-query new file mode 120000 index 0000000000..381baa2e41 --- /dev/null +++ b/Lang/Erlang/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Erlang \ No newline at end of file diff --git a/Lang/Erlang/File-IO b/Lang/Erlang/File-IO deleted file mode 120000 index 3030796e13..0000000000 --- a/Lang/Erlang/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/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/Mutex b/Lang/Erlang/Mutex deleted file mode 120000 index 0ca8d2bcf3..0000000000 --- a/Lang/Erlang/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Rosetta-Code-Count-examples b/Lang/Erlang/Rosetta-Code-Count-examples deleted file mode 120000 index 7b2911eb3e..0000000000 --- a/Lang/Erlang/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Rosetta-Code-Find-unimplemented-tasks b/Lang/Erlang/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index d80226c73e..0000000000 --- a/Lang/Erlang/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Rosetta-Code-Fix-code-tags b/Lang/Erlang/Rosetta-Code-Fix-code-tags deleted file mode 120000 index 249da695f1..0000000000 --- a/Lang/Erlang/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Rosetta-Code-Rank-languages-by-popularity b/Lang/Erlang/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 2f795051dc..0000000000 --- a/Lang/Erlang/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sorting-algorithms-Selection-sort b/Lang/Erlang/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..df37e9545b --- /dev/null +++ b/Lang/Erlang/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Standard-deviation b/Lang/Erlang/Standard-deviation deleted file mode 120000 index f18386b727..0000000000 --- a/Lang/Erlang/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Vector-products b/Lang/Erlang/Vector-products new file mode 120000 index 0000000000..c4f8de58af --- /dev/null +++ b/Lang/Erlang/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Erlang \ No newline at end of file diff --git a/Lang/Euphoria/Character-matching b/Lang/Euphoria/Character-matching deleted file mode 120000 index 14fdab0dd4..0000000000 --- a/Lang/Euphoria/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/File-IO b/Lang/Euphoria/File-IO deleted file mode 120000 index c64f9ffb27..0000000000 --- a/Lang/Euphoria/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Hello-world-Text b/Lang/Euphoria/Hello-world-Text deleted file mode 120000 index a9e631687a..0000000000 --- a/Lang/Euphoria/Hello-world-Text +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Text/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Towers-of-Hanoi b/Lang/Euphoria/Towers-of-Hanoi deleted file mode 120000 index 52f6dc5a6d..0000000000 --- a/Lang/Euphoria/Towers-of-Hanoi +++ /dev/null @@ -1 +0,0 @@ -../../Task/Towers-of-Hanoi/Euphoria \ No newline at end of file diff --git a/Lang/F-Sharp/Kaprekar-numbers b/Lang/F-Sharp/Kaprekar-numbers new file mode 120000 index 0000000000..ea70e78b91 --- /dev/null +++ b/Lang/F-Sharp/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Monte-Carlo-methods b/Lang/F-Sharp/Monte-Carlo-methods new file mode 120000 index 0000000000..d9ae98e16b --- /dev/null +++ b/Lang/F-Sharp/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/N-queens-problem b/Lang/F-Sharp/N-queens-problem new file mode 120000 index 0000000000..3e8f3d1540 --- /dev/null +++ b/Lang/F-Sharp/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Sequence-of-primes-by-Trial-Division b/Lang/F-Sharp/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..b4d52e4c6d --- /dev/null +++ b/Lang/F-Sharp/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/F-Sharp \ No newline at end of file diff --git a/Lang/FALSE/100-doors b/Lang/FALSE/100-doors new file mode 120000 index 0000000000..88b9f1ef8c --- /dev/null +++ b/Lang/FALSE/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/FALSE \ No newline at end of file diff --git a/Lang/FALSE/99-Bottles-of-Beer b/Lang/FALSE/99-Bottles-of-Beer deleted file mode 120000 index 167e034e74..0000000000 --- a/Lang/FALSE/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/FALSE \ No newline at end of file diff --git a/Lang/FALSE/FizzBuzz b/Lang/FALSE/FizzBuzz deleted file mode 120000 index 49383bbfd7..0000000000 --- a/Lang/FALSE/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/FALSE \ No newline at end of file diff --git a/Lang/FBSL/99-Bottles-of-Beer b/Lang/FBSL/99-Bottles-of-Beer deleted file mode 120000 index 94e389590c..0000000000 --- a/Lang/FBSL/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Arrays b/Lang/FBSL/Arrays deleted file mode 120000 index d20fd16eea..0000000000 --- a/Lang/FBSL/Arrays +++ /dev/null @@ -1 +0,0 @@ -../../Task/Arrays/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Character-matching b/Lang/FBSL/Character-matching deleted file mode 120000 index 96ef0d1b65..0000000000 --- a/Lang/FBSL/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Loops-For b/Lang/FBSL/Loops-For deleted file mode 120000 index dd8d8414c2..0000000000 --- a/Lang/FBSL/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Middle-three-digits b/Lang/FBSL/Middle-three-digits deleted file mode 120000 index fd841f1f79..0000000000 --- a/Lang/FBSL/Middle-three-digits +++ /dev/null @@ -1 +0,0 @@ -../../Task/Middle-three-digits/FBSL \ No newline at end of file diff --git a/Lang/FUZE-BASIC/A+B b/Lang/FUZE-BASIC/A+B deleted file mode 120000 index 9dfcff73b7..0000000000 --- a/Lang/FUZE-BASIC/A+B +++ /dev/null @@ -1 +0,0 @@ -../../Task/A+B/FUZE-BASIC \ No newline at end of file diff --git a/Lang/Factor/Bernoulli-numbers b/Lang/Factor/Bernoulli-numbers new file mode 120000 index 0000000000..4ea30435df --- /dev/null +++ b/Lang/Factor/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Factor \ No newline at end of file diff --git a/Lang/Factor/Bitcoin-address-validation b/Lang/Factor/Bitcoin-address-validation new file mode 120000 index 0000000000..1b3321061e --- /dev/null +++ b/Lang/Factor/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Factor \ No newline at end of file diff --git a/Lang/Factor/Bitcoin-public-point-to-address b/Lang/Factor/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..4d9a67ba5e --- /dev/null +++ b/Lang/Factor/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/Factor \ No newline at end of file diff --git a/Lang/Factor/File-IO b/Lang/Factor/File-IO deleted file mode 120000 index 345143b246..0000000000 --- a/Lang/Factor/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Factor \ No newline at end of file diff --git a/Lang/Factor/Include-a-file b/Lang/Factor/Include-a-file new file mode 120000 index 0000000000..45e2729a42 --- /dev/null +++ b/Lang/Factor/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Factor \ No newline at end of file diff --git a/Lang/Factor/Mandelbrot-set b/Lang/Factor/Mandelbrot-set new file mode 120000 index 0000000000..5d9e5d6468 --- /dev/null +++ b/Lang/Factor/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Factor \ No newline at end of file diff --git a/Lang/Factor/Modular-exponentiation b/Lang/Factor/Modular-exponentiation new file mode 120000 index 0000000000..c066c8f708 --- /dev/null +++ b/Lang/Factor/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Factor \ No newline at end of file diff --git a/Lang/Factor/Named-parameters b/Lang/Factor/Named-parameters new file mode 120000 index 0000000000..26afb71de2 --- /dev/null +++ b/Lang/Factor/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/Factor \ No newline at end of file diff --git a/Lang/Factor/Rosetta-Code-Count-examples b/Lang/Factor/Rosetta-Code-Count-examples deleted file mode 120000 index bbe79fc0c9..0000000000 --- a/Lang/Factor/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Factor \ No newline at end of file diff --git a/Lang/Factor/Sorting-algorithms-Sleep-sort b/Lang/Factor/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..fc774d847b --- /dev/null +++ b/Lang/Factor/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Factor \ No newline at end of file diff --git a/Lang/Factor/Standard-deviation b/Lang/Factor/Standard-deviation deleted file mode 120000 index 0e8782d458..0000000000 --- a/Lang/Factor/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Factor \ No newline at end of file diff --git a/Lang/Falcon/Loops-N-plus-one-half b/Lang/Falcon/Loops-N-plus-one-half new file mode 120000 index 0000000000..67db5444fd --- /dev/null +++ b/Lang/Falcon/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Falcon \ No newline at end of file diff --git a/Lang/Fantom/Character-matching b/Lang/Fantom/Character-matching deleted file mode 120000 index 9196d744a7..0000000000 --- a/Lang/Fantom/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Fantom \ No newline at end of file diff --git a/Lang/Ferite/99-Bottles-of-Beer b/Lang/Ferite/99-Bottles-of-Beer new file mode 120000 index 0000000000..39bc3ed869 --- /dev/null +++ b/Lang/Ferite/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Ferite \ No newline at end of file diff --git a/Lang/Ferite/Hello-world-Text b/Lang/Ferite/Hello-world-Text new file mode 120000 index 0000000000..b837f73e4e --- /dev/null +++ b/Lang/Ferite/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Ferite \ No newline at end of file diff --git a/Lang/Forth/Abundant,-deficient-and-perfect-number-classifications b/Lang/Forth/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..fc5347deb6 --- /dev/null +++ b/Lang/Forth/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Forth \ No newline at end of file diff --git a/Lang/Forth/Character-matching b/Lang/Forth/Character-matching deleted file mode 120000 index 67aa24411a..0000000000 --- a/Lang/Forth/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Forth \ No newline at end of file diff --git a/Lang/Forth/File-IO b/Lang/Forth/File-IO deleted file mode 120000 index b284707897..0000000000 --- a/Lang/Forth/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Forth \ No newline at end of file diff --git a/Lang/Forth/Find-the-missing-permutation b/Lang/Forth/Find-the-missing-permutation new file mode 120000 index 0000000000..a357cbfa30 --- /dev/null +++ b/Lang/Forth/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Forth \ No newline at end of file diff --git a/Lang/Forth/Identity-matrix b/Lang/Forth/Identity-matrix new file mode 120000 index 0000000000..7fdeeb05ae --- /dev/null +++ b/Lang/Forth/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Forth \ No newline at end of file diff --git a/Lang/Forth/Inheritance-Multiple b/Lang/Forth/Inheritance-Multiple deleted file mode 120000 index 24ec79d711..0000000000 --- a/Lang/Forth/Inheritance-Multiple +++ /dev/null @@ -1 +0,0 @@ -../../Task/Inheritance-Multiple/Forth \ No newline at end of file diff --git a/Lang/Forth/Matrix-arithmetic b/Lang/Forth/Matrix-arithmetic new file mode 120000 index 0000000000..c2d5c6edc4 --- /dev/null +++ b/Lang/Forth/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Forth \ No newline at end of file diff --git a/Lang/Forth/Matrix-transposition b/Lang/Forth/Matrix-transposition new file mode 120000 index 0000000000..e1bbb56759 --- /dev/null +++ b/Lang/Forth/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/Forth \ No newline at end of file diff --git a/Lang/Forth/Permutations-by-swapping b/Lang/Forth/Permutations-by-swapping new file mode 120000 index 0000000000..b328103c37 --- /dev/null +++ b/Lang/Forth/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Forth \ No newline at end of file diff --git a/Lang/Forth/Standard-deviation b/Lang/Forth/Standard-deviation deleted file mode 120000 index 9dad1468f4..0000000000 --- a/Lang/Forth/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Forth \ No newline at end of file diff --git a/Lang/Fortran/Boolean-values b/Lang/Fortran/Boolean-values new file mode 120000 index 0000000000..52b789ded0 --- /dev/null +++ b/Lang/Fortran/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Collections b/Lang/Fortran/Collections new file mode 120000 index 0000000000..85b85e9672 --- /dev/null +++ b/Lang/Fortran/Collections @@ -0,0 +1 @@ +../../Task/Collections/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Doubly-linked-list-Traversal b/Lang/Fortran/Doubly-linked-list-Traversal deleted file mode 120000 index 1053e2832b..0000000000 --- a/Lang/Fortran/Doubly-linked-list-Traversal +++ /dev/null @@ -1 +0,0 @@ -../../Task/Doubly-linked-list-Traversal/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Execute-HQ9+ b/Lang/Fortran/Execute-HQ9+ new file mode 120000 index 0000000000..77ec4f10de --- /dev/null +++ b/Lang/Fortran/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/Fortran \ No newline at end of file diff --git a/Lang/Fortran/File-IO b/Lang/Fortran/File-IO deleted file mode 120000 index d77546cac9..0000000000 --- a/Lang/Fortran/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/Fortran/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..134a01963f --- /dev/null +++ b/Lang/Fortran/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran \ No newline at end of file diff --git a/Lang/Fortran/K-means++-clustering b/Lang/Fortran/K-means++-clustering new file mode 120000 index 0000000000..37974632f7 --- /dev/null +++ b/Lang/Fortran/K-means++-clustering @@ -0,0 +1 @@ +../../Task/K-means++-clustering/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Left-factorials b/Lang/Fortran/Left-factorials new file mode 120000 index 0000000000..dbebe72bef --- /dev/null +++ b/Lang/Fortran/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/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/Multiple-regression b/Lang/Fortran/Multiple-regression new file mode 120000 index 0000000000..e4ab198471 --- /dev/null +++ b/Lang/Fortran/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Parallel-calculations b/Lang/Fortran/Parallel-calculations new file mode 120000 index 0000000000..9b72079632 --- /dev/null +++ b/Lang/Fortran/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Parametric-polymorphism b/Lang/Fortran/Parametric-polymorphism new file mode 120000 index 0000000000..769e7668b7 --- /dev/null +++ b/Lang/Fortran/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Rate-counter b/Lang/Fortran/Rate-counter new file mode 120000 index 0000000000..3a40e2dd64 --- /dev/null +++ b/Lang/Fortran/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Radix-sort b/Lang/Fortran/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..2d1b19d3f7 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Sleep-sort b/Lang/Fortran/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..16cb22f539 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Special-variables b/Lang/Fortran/Special-variables new file mode 120000 index 0000000000..883356adfc --- /dev/null +++ b/Lang/Fortran/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Standard-deviation b/Lang/Fortran/Standard-deviation deleted file mode 120000 index 45df64cb97..0000000000 --- a/Lang/Fortran/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Fortran \ No newline at end of file diff --git a/Lang/Fortran/String-comparison b/Lang/Fortran/String-comparison new file mode 120000 index 0000000000..30fb2169a3 --- /dev/null +++ b/Lang/Fortran/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Top-rank-per-group b/Lang/Fortran/Top-rank-per-group new file mode 120000 index 0000000000..8e14f13ee5 --- /dev/null +++ b/Lang/Fortran/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Van-der-Corput-sequence b/Lang/Fortran/Van-der-Corput-sequence new file mode 120000 index 0000000000..c7ec084a34 --- /dev/null +++ b/Lang/Fortran/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Zeckendorf-number-representation b/Lang/Fortran/Zeckendorf-number-representation new file mode 120000 index 0000000000..2ac92139df --- /dev/null +++ b/Lang/Fortran/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Zhang-Suen-thinning-algorithm b/Lang/Fortran/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..d3fda29266 --- /dev/null +++ b/Lang/Fortran/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Fortran \ No newline at end of file diff --git a/Lang/Free-Pascal/Old-lady-swallowed-a-fly b/Lang/Free-Pascal/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..339fa3f6ad --- /dev/null +++ b/Lang/Free-Pascal/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Free-Pascal \ No newline at end of file diff --git a/Lang/FreeBASIC/00DESCRIPTION b/Lang/FreeBASIC/00DESCRIPTION index 86a1580ece..06e2813a95 100644 --- a/Lang/FreeBASIC/00DESCRIPTION +++ b/Lang/FreeBASIC/00DESCRIPTION @@ -3,10 +3,10 @@ |gc=yes |checking=static |site=http://www.freebasic.net/}} -{{implementation|BASIC}}'''FreeBASIC''' is a free/[[open source]] ([[GPL]]), 32-bit [[BASIC]] compiler for [[Microsoft]] [[Windows]], protected-mode [[DOS]] (via a [[wp:DOS extender|DOS extender]]), [[Linux]], [[BSD|FreeBSD]], and the [[wp:Xbox|Xbox]]. The [[wp:Xbox|Xbox]] version is no longer maintained. +{{implementation|BASIC}}'''FreeBASIC''' is a free/[[open source]] ([[GPL]]), 32-bit [[BASIC]] compiler for [[Microsoft]] [[Windows]], protected-mode [[DOS]] (via a [[wp:DOS extender|DOS extender]]), and [[Linux]], with unofficial ports to [[Mac OS]] and [[BSD|FreeBSD]]. An experimental [[wp:Xbox|Xbox]] version is no longer maintained. -It makes use of the [[wp:GNU Binutils|GNU Binutils]] programming tools as backends, and can produce console, [[QuickBASIC]]-compatible graphical and [[GUI]] executables, along with dynamic and static libraries. A [[GCC]] frontend is under development, which will enable compilation for many more operating systems than currently supported. +FreeBASIC makes use of the [[wp:GNU Binutils|GNU Binutils]] programming tools as backends, and can produce console, [[QuickBASIC]]-compatible graphical and [[GUI]] executables, along with dynamic and static libraries. A [[GCC]] frontend is under development, which will enable compilation for many more operating systems than currently supported. Currently, software libraries like [[GTK+]], [[wp:GNU Scientific Library|GSL]], [[:Category:SDL|SDL]], [[wp:Allegro library|Allegro]], [[Lua]] and [[OpenGL]] can be used directly (no wrappers, only function and structure prototypes), and more are being added on every new release. A complete set of the Windows [[API]] headers is also included. diff --git a/Lang/FreeBASIC/A+B b/Lang/FreeBASIC/A+B deleted file mode 120000 index c053bd49db..0000000000 --- a/Lang/FreeBASIC/A+B +++ /dev/null @@ -1 +0,0 @@ -../../Task/A+B/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Bitcoin-address-validation b/Lang/FreeBASIC/Bitcoin-address-validation new file mode 120000 index 0000000000..ed2e7b6a32 --- /dev/null +++ b/Lang/FreeBASIC/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Break-OO-privacy b/Lang/FreeBASIC/Break-OO-privacy new file mode 120000 index 0000000000..45cbfe7be4 --- /dev/null +++ b/Lang/FreeBASIC/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Brownian-tree b/Lang/FreeBASIC/Brownian-tree new file mode 120000 index 0000000000..ae129337a1 --- /dev/null +++ b/Lang/FreeBASIC/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/CRC-32 b/Lang/FreeBASIC/CRC-32 new file mode 120000 index 0000000000..233ac10c14 --- /dev/null +++ b/Lang/FreeBASIC/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Cholesky-decomposition b/Lang/FreeBASIC/Cholesky-decomposition new file mode 120000 index 0000000000..012ebd94e9 --- /dev/null +++ b/Lang/FreeBASIC/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Colour-pinstripe-Display b/Lang/FreeBASIC/Colour-pinstripe-Display new file mode 120000 index 0000000000..aac7159b0b --- /dev/null +++ b/Lang/FreeBASIC/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Digital-root-Multiplicative-digital-root b/Lang/FreeBASIC/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..199ca69850 --- /dev/null +++ b/Lang/FreeBASIC/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Draw-a-clock b/Lang/FreeBASIC/Draw-a-clock new file mode 120000 index 0000000000..8e2d94a2e8 --- /dev/null +++ b/Lang/FreeBASIC/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Find-the-missing-permutation b/Lang/FreeBASIC/Find-the-missing-permutation new file mode 120000 index 0000000000..ba9fd46aed --- /dev/null +++ b/Lang/FreeBASIC/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/First-class-functions b/Lang/FreeBASIC/First-class-functions new file mode 120000 index 0000000000..27dc12c869 --- /dev/null +++ b/Lang/FreeBASIC/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Fractal-tree b/Lang/FreeBASIC/Fractal-tree new file mode 120000 index 0000000000..a80549eebb --- /dev/null +++ b/Lang/FreeBASIC/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/GUI-enabling-disabling-of-controls b/Lang/FreeBASIC/GUI-enabling-disabling-of-controls new file mode 120000 index 0000000000..026eb83596 --- /dev/null +++ b/Lang/FreeBASIC/GUI-enabling-disabling-of-controls @@ -0,0 +1 @@ +../../Task/GUI-enabling-disabling-of-controls/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Generate-lower-case-ASCII-alphabet b/Lang/FreeBASIC/Generate-lower-case-ASCII-alphabet deleted file mode 120000 index 52a073acbf..0000000000 --- a/Lang/FreeBASIC/Generate-lower-case-ASCII-alphabet +++ /dev/null @@ -1 +0,0 @@ -../../Task/Generate-lower-case-ASCII-alphabet/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Gray-code b/Lang/FreeBASIC/Gray-code new file mode 120000 index 0000000000..ec71f0f8f5 --- /dev/null +++ b/Lang/FreeBASIC/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Greyscale-bars-Display b/Lang/FreeBASIC/Greyscale-bars-Display new file mode 120000 index 0000000000..ef7309123b --- /dev/null +++ b/Lang/FreeBASIC/Greyscale-bars-Display @@ -0,0 +1 @@ +../../Task/Greyscale-bars-Display/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Horizontal-sundial-calculations b/Lang/FreeBASIC/Horizontal-sundial-calculations new file mode 120000 index 0000000000..975c6ebe27 --- /dev/null +++ b/Lang/FreeBASIC/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Introspection b/Lang/FreeBASIC/Introspection new file mode 120000 index 0000000000..bc6c984a2e --- /dev/null +++ b/Lang/FreeBASIC/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Largest-int-from-concatenated-ints b/Lang/FreeBASIC/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..dda165aefb --- /dev/null +++ b/Lang/FreeBASIC/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Left-factorials b/Lang/FreeBASIC/Left-factorials new file mode 120000 index 0000000000..aec8e68d77 --- /dev/null +++ b/Lang/FreeBASIC/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Logical-operations b/Lang/FreeBASIC/Logical-operations deleted file mode 120000 index c33bc3af60..0000000000 --- a/Lang/FreeBASIC/Logical-operations +++ /dev/null @@ -1 +0,0 @@ -../../Task/Logical-operations/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Long-multiplication b/Lang/FreeBASIC/Long-multiplication new file mode 120000 index 0000000000..e9d2c5c7e8 --- /dev/null +++ b/Lang/FreeBASIC/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Loops-Continue b/Lang/FreeBASIC/Loops-Continue deleted file mode 120000 index 84b964a752..0000000000 --- a/Lang/FreeBASIC/Loops-Continue +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Continue/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Loops-Foreach b/Lang/FreeBASIC/Loops-Foreach deleted file mode 120000 index 0260d67ece..0000000000 --- a/Lang/FreeBASIC/Loops-Foreach +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Foreach/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/N-queens-problem b/Lang/FreeBASIC/N-queens-problem new file mode 120000 index 0000000000..29c4644f8a --- /dev/null +++ b/Lang/FreeBASIC/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Paraffins b/Lang/FreeBASIC/Paraffins new file mode 120000 index 0000000000..ce811540df --- /dev/null +++ b/Lang/FreeBASIC/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Permutations b/Lang/FreeBASIC/Permutations new file mode 120000 index 0000000000..33af6e2b62 --- /dev/null +++ b/Lang/FreeBASIC/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Permutations-Derangements b/Lang/FreeBASIC/Permutations-Derangements new file mode 120000 index 0000000000..9ee2bb1de8 --- /dev/null +++ b/Lang/FreeBASIC/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Permutations-Rank-of-a-permutation b/Lang/FreeBASIC/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..63a66dde93 --- /dev/null +++ b/Lang/FreeBASIC/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Permutations-by-swapping b/Lang/FreeBASIC/Permutations-by-swapping new file mode 120000 index 0000000000..926ad9f710 --- /dev/null +++ b/Lang/FreeBASIC/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Pinstripe-Display b/Lang/FreeBASIC/Pinstripe-Display new file mode 120000 index 0000000000..9db24659a6 --- /dev/null +++ b/Lang/FreeBASIC/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Queue-Definition b/Lang/FreeBASIC/Queue-Definition new file mode 120000 index 0000000000..13d0819ba3 --- /dev/null +++ b/Lang/FreeBASIC/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Queue-Usage b/Lang/FreeBASIC/Queue-Usage new file mode 120000 index 0000000000..4780427fce --- /dev/null +++ b/Lang/FreeBASIC/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/RSA-code b/Lang/FreeBASIC/RSA-code new file mode 120000 index 0000000000..5ece754a25 --- /dev/null +++ b/Lang/FreeBASIC/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Search-a-list b/Lang/FreeBASIC/Search-a-list new file mode 120000 index 0000000000..c9bcee23f4 --- /dev/null +++ b/Lang/FreeBASIC/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sort-an-array-of-composite-structures b/Lang/FreeBASIC/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..a44117ebac --- /dev/null +++ b/Lang/FreeBASIC/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sorting-algorithms-Merge-sort b/Lang/FreeBASIC/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..e63b3c9b15 --- /dev/null +++ b/Lang/FreeBASIC/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sorting-algorithms-Pancake-sort b/Lang/FreeBASIC/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..efac0f8043 --- /dev/null +++ b/Lang/FreeBASIC/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sorting-algorithms-Permutation-sort b/Lang/FreeBASIC/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..53a3911be1 --- /dev/null +++ b/Lang/FreeBASIC/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Stack b/Lang/FreeBASIC/Stack new file mode 120000 index 0000000000..4e83468299 --- /dev/null +++ b/Lang/FreeBASIC/Stack @@ -0,0 +1 @@ +../../Task/Stack/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Truncatable-primes b/Lang/FreeBASIC/Truncatable-primes new file mode 120000 index 0000000000..bd97c768b1 --- /dev/null +++ b/Lang/FreeBASIC/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/FreeBASIC \ No newline at end of file diff --git a/Lang/Friendly-interactive-shell/100-doors b/Lang/Friendly-interactive-shell/100-doors new file mode 120000 index 0000000000..eb82caaecd --- /dev/null +++ b/Lang/Friendly-interactive-shell/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Friendly-interactive-shell \ No newline at end of file diff --git a/Lang/Friendly-interactive-shell/Arithmetic-Integer b/Lang/Friendly-interactive-shell/Arithmetic-Integer new file mode 120000 index 0000000000..5433436a67 --- /dev/null +++ b/Lang/Friendly-interactive-shell/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Friendly-interactive-shell \ No newline at end of file diff --git a/Lang/Friendly-interactive-shell/Conditional-structures b/Lang/Friendly-interactive-shell/Conditional-structures new file mode 120000 index 0000000000..464734134d --- /dev/null +++ b/Lang/Friendly-interactive-shell/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Friendly-interactive-shell \ No newline at end of file diff --git a/Lang/Friendly-interactive-shell/Create-a-file b/Lang/Friendly-interactive-shell/Create-a-file new file mode 120000 index 0000000000..c02be9acc5 --- /dev/null +++ b/Lang/Friendly-interactive-shell/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Friendly-interactive-shell \ No newline at end of file diff --git a/Lang/Friendly-interactive-shell/Empty-program b/Lang/Friendly-interactive-shell/Empty-program new file mode 120000 index 0000000000..d786666373 --- /dev/null +++ b/Lang/Friendly-interactive-shell/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Friendly-interactive-shell \ No newline at end of file diff --git a/Lang/Friendly-interactive-shell/Entropy b/Lang/Friendly-interactive-shell/Entropy new file mode 120000 index 0000000000..b3e9637309 --- /dev/null +++ b/Lang/Friendly-interactive-shell/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Friendly-interactive-shell \ No newline at end of file diff --git a/Lang/Friendly-interactive-shell/Factorial b/Lang/Friendly-interactive-shell/Factorial new file mode 120000 index 0000000000..e7ab450836 --- /dev/null +++ b/Lang/Friendly-interactive-shell/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Friendly-interactive-shell \ No newline at end of file diff --git a/Lang/Friendly-interactive-shell/HTTP b/Lang/Friendly-interactive-shell/HTTP new file mode 120000 index 0000000000..216b917400 --- /dev/null +++ b/Lang/Friendly-interactive-shell/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Friendly-interactive-shell \ No newline at end of file diff --git a/Lang/Friendly-interactive-shell/Hello-world-Text b/Lang/Friendly-interactive-shell/Hello-world-Text new file mode 120000 index 0000000000..327fca886b --- /dev/null +++ b/Lang/Friendly-interactive-shell/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Friendly-interactive-shell \ No newline at end of file diff --git a/Lang/Friendly-interactive-shell/Hostname b/Lang/Friendly-interactive-shell/Hostname new file mode 120000 index 0000000000..0ad086dd9f --- /dev/null +++ b/Lang/Friendly-interactive-shell/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Friendly-interactive-shell \ No newline at end of file diff --git a/Lang/Friendly-interactive-shell/Integer-comparison b/Lang/Friendly-interactive-shell/Integer-comparison new file mode 120000 index 0000000000..5baeabfc5e --- /dev/null +++ b/Lang/Friendly-interactive-shell/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Friendly-interactive-shell \ No newline at end of file diff --git a/Lang/Friendly-interactive-shell/Josephus-problem b/Lang/Friendly-interactive-shell/Josephus-problem new file mode 120000 index 0000000000..a11c685312 --- /dev/null +++ b/Lang/Friendly-interactive-shell/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Friendly-interactive-shell \ No newline at end of file diff --git a/Lang/Friendly-interactive-shell/Literals-String b/Lang/Friendly-interactive-shell/Literals-String new file mode 120000 index 0000000000..f7d0ca1fb8 --- /dev/null +++ b/Lang/Friendly-interactive-shell/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/Friendly-interactive-shell \ No newline at end of file diff --git a/Lang/Friendly-interactive-shell/Loops-Foreach b/Lang/Friendly-interactive-shell/Loops-Foreach new file mode 120000 index 0000000000..d5b2de2050 --- /dev/null +++ b/Lang/Friendly-interactive-shell/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Friendly-interactive-shell \ No newline at end of file diff --git a/Lang/Frink/Anagrams b/Lang/Frink/Anagrams new file mode 120000 index 0000000000..43b3173944 --- /dev/null +++ b/Lang/Frink/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Frink \ No newline at end of file diff --git a/Lang/Frink/Count-in-factors b/Lang/Frink/Count-in-factors new file mode 120000 index 0000000000..c7e6c3527d --- /dev/null +++ b/Lang/Frink/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/Frink \ No newline at end of file diff --git a/Lang/Frink/File-IO b/Lang/Frink/File-IO deleted file mode 120000 index e537c87d39..0000000000 --- a/Lang/Frink/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Frink \ No newline at end of file diff --git a/Lang/Frink/Unicode-variable-names b/Lang/Frink/Unicode-variable-names new file mode 120000 index 0000000000..0ead66bd60 --- /dev/null +++ b/Lang/Frink/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Frink \ No newline at end of file diff --git a/Lang/Futhark/Reverse-a-string b/Lang/Futhark/Reverse-a-string new file mode 120000 index 0000000000..415455d556 --- /dev/null +++ b/Lang/Futhark/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Futhark \ No newline at end of file diff --git a/Lang/GAP/Accumulator-factory b/Lang/GAP/Accumulator-factory deleted file mode 120000 index 9d39b78368..0000000000 --- a/Lang/GAP/Accumulator-factory +++ /dev/null @@ -1 +0,0 @@ -../../Task/Accumulator-factory/GAP \ No newline at end of file diff --git a/Lang/GAP/File-IO b/Lang/GAP/File-IO deleted file mode 120000 index b4ed31b3c9..0000000000 --- a/Lang/GAP/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/GAP \ No newline at end of file diff --git a/Lang/GML/Character-matching b/Lang/GML/Character-matching deleted file mode 120000 index 1d66029918..0000000000 --- a/Lang/GML/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/GML \ No newline at end of file diff --git a/Lang/GML/File-IO b/Lang/GML/File-IO deleted file mode 120000 index fc44b342bd..0000000000 --- a/Lang/GML/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/GML \ No newline at end of file diff --git a/Lang/GUISS/Calendar---for-real-programmers b/Lang/GUISS/Calendar---for-real-programmers deleted file mode 120000 index 77e9bfb78a..0000000000 --- a/Lang/GUISS/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/GUISS \ No newline at end of file diff --git a/Lang/GUISS/File-IO b/Lang/GUISS/File-IO deleted file mode 120000 index 153d444a46..0000000000 --- a/Lang/GUISS/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/GUISS \ No newline at end of file diff --git a/Lang/GUISS/Minesweeper-game b/Lang/GUISS/Minesweeper-game deleted file mode 120000 index fc8449a28d..0000000000 --- a/Lang/GUISS/Minesweeper-game +++ /dev/null @@ -1 +0,0 @@ -../../Task/Minesweeper-game/GUISS \ No newline at end of file diff --git a/Lang/GW-BASIC/Ethiopian-multiplication b/Lang/GW-BASIC/Ethiopian-multiplication deleted file mode 120000 index 3bfccbddc4..0000000000 --- a/Lang/GW-BASIC/Ethiopian-multiplication +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ethiopian-multiplication/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Loops-For b/Lang/GW-BASIC/Loops-For deleted file mode 120000 index 5767da5545..0000000000 --- a/Lang/GW-BASIC/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Narcissistic-decimal-number b/Lang/GW-BASIC/Narcissistic-decimal-number new file mode 120000 index 0000000000..84f5ae005a --- /dev/null +++ b/Lang/GW-BASIC/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Terminal-control-Clear-the-screen b/Lang/GW-BASIC/Terminal-control-Clear-the-screen deleted file mode 120000 index 9061eea49a..0000000000 --- a/Lang/GW-BASIC/Terminal-control-Clear-the-screen +++ /dev/null @@ -1 +0,0 @@ -../../Task/Terminal-control-Clear-the-screen/GW-BASIC \ No newline at end of file diff --git a/Lang/Gambas/100-doors b/Lang/Gambas/100-doors new file mode 120000 index 0000000000..37536c8bca --- /dev/null +++ b/Lang/Gambas/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Gambas \ No newline at end of file diff --git a/Lang/Gambas/A+B b/Lang/Gambas/A+B new file mode 120000 index 0000000000..3229c1709c --- /dev/null +++ b/Lang/Gambas/A+B @@ -0,0 +1 @@ +../../Task/A+B/Gambas \ No newline at end of file diff --git a/Lang/Gambas/ABC-Problem b/Lang/Gambas/ABC-Problem new file mode 120000 index 0000000000..b7848abc2a --- /dev/null +++ b/Lang/Gambas/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Align-columns b/Lang/Gambas/Align-columns new file mode 120000 index 0000000000..66171242db --- /dev/null +++ b/Lang/Gambas/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Animation b/Lang/Gambas/Animation new file mode 120000 index 0000000000..99a58a5e63 --- /dev/null +++ b/Lang/Gambas/Animation @@ -0,0 +1 @@ +../../Task/Animation/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Array-concatenation b/Lang/Gambas/Array-concatenation new file mode 120000 index 0000000000..a8a654bb0e --- /dev/null +++ b/Lang/Gambas/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Associative-array-Iteration b/Lang/Gambas/Associative-array-Iteration new file mode 120000 index 0000000000..3ecdad5670 --- /dev/null +++ b/Lang/Gambas/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Balanced-brackets b/Lang/Gambas/Balanced-brackets new file mode 120000 index 0000000000..297beb6d00 --- /dev/null +++ b/Lang/Gambas/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Binary-digits b/Lang/Gambas/Binary-digits new file mode 120000 index 0000000000..8f48ce8833 --- /dev/null +++ b/Lang/Gambas/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Boolean-values b/Lang/Gambas/Boolean-values new file mode 120000 index 0000000000..c17696f033 --- /dev/null +++ b/Lang/Gambas/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Box-the-compass b/Lang/Gambas/Box-the-compass new file mode 120000 index 0000000000..2e51fdac52 --- /dev/null +++ b/Lang/Gambas/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/Gambas \ No newline at end of file diff --git a/Lang/Gambas/CSV-data-manipulation b/Lang/Gambas/CSV-data-manipulation new file mode 120000 index 0000000000..2389bc0c7d --- /dev/null +++ b/Lang/Gambas/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Caesar-cipher b/Lang/Gambas/Caesar-cipher new file mode 120000 index 0000000000..d770cc7acb --- /dev/null +++ b/Lang/Gambas/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Calendar b/Lang/Gambas/Calendar new file mode 120000 index 0000000000..f21ce3ad55 --- /dev/null +++ b/Lang/Gambas/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Call-a-function b/Lang/Gambas/Call-a-function new file mode 120000 index 0000000000..92b4138bc3 --- /dev/null +++ b/Lang/Gambas/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Case-sensitivity-of-identifiers b/Lang/Gambas/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..4defae8eb1 --- /dev/null +++ b/Lang/Gambas/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Character-codes b/Lang/Gambas/Character-codes new file mode 120000 index 0000000000..0fc2b27b46 --- /dev/null +++ b/Lang/Gambas/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Check-that-file-exists b/Lang/Gambas/Check-that-file-exists new file mode 120000 index 0000000000..95ffbe52cd --- /dev/null +++ b/Lang/Gambas/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Colour-bars-Display b/Lang/Gambas/Colour-bars-Display new file mode 120000 index 0000000000..697ad21627 --- /dev/null +++ b/Lang/Gambas/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Colour-pinstripe-Display b/Lang/Gambas/Colour-pinstripe-Display new file mode 120000 index 0000000000..4cecd9dfc0 --- /dev/null +++ b/Lang/Gambas/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Comma-quibbling b/Lang/Gambas/Comma-quibbling new file mode 120000 index 0000000000..59ac42a57a --- /dev/null +++ b/Lang/Gambas/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Create-a-file b/Lang/Gambas/Create-a-file new file mode 120000 index 0000000000..c247653ba7 --- /dev/null +++ b/Lang/Gambas/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Date-format b/Lang/Gambas/Date-format new file mode 120000 index 0000000000..12a2952ba0 --- /dev/null +++ b/Lang/Gambas/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Day-of-the-week b/Lang/Gambas/Day-of-the-week new file mode 120000 index 0000000000..3f0903fd61 --- /dev/null +++ b/Lang/Gambas/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Delete-a-file b/Lang/Gambas/Delete-a-file new file mode 120000 index 0000000000..c8b1106191 --- /dev/null +++ b/Lang/Gambas/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Detect-division-by-zero b/Lang/Gambas/Detect-division-by-zero new file mode 120000 index 0000000000..2209f0680c --- /dev/null +++ b/Lang/Gambas/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Determine-if-a-string-is-numeric b/Lang/Gambas/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..154707c519 --- /dev/null +++ b/Lang/Gambas/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Dutch-national-flag-problem b/Lang/Gambas/Dutch-national-flag-problem new file mode 120000 index 0000000000..33b84bd553 --- /dev/null +++ b/Lang/Gambas/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Empty-directory b/Lang/Gambas/Empty-directory new file mode 120000 index 0000000000..410cc41928 --- /dev/null +++ b/Lang/Gambas/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Empty-string b/Lang/Gambas/Empty-string new file mode 120000 index 0000000000..9a5f9ce3c7 --- /dev/null +++ b/Lang/Gambas/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Even-or-odd b/Lang/Gambas/Even-or-odd new file mode 120000 index 0000000000..c9b1d9c7de --- /dev/null +++ b/Lang/Gambas/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Events b/Lang/Gambas/Events new file mode 120000 index 0000000000..cf6853677f --- /dev/null +++ b/Lang/Gambas/Events @@ -0,0 +1 @@ +../../Task/Events/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Exceptions b/Lang/Gambas/Exceptions new file mode 120000 index 0000000000..50f6d20bdc --- /dev/null +++ b/Lang/Gambas/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Execute-a-system-command b/Lang/Gambas/Execute-a-system-command new file mode 120000 index 0000000000..596b23908d --- /dev/null +++ b/Lang/Gambas/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Gambas \ No newline at end of file diff --git a/Lang/Gambas/File-input-output b/Lang/Gambas/File-input-output new file mode 120000 index 0000000000..4df752a55c --- /dev/null +++ b/Lang/Gambas/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Gambas \ No newline at end of file diff --git a/Lang/Gambas/File-modification-time b/Lang/Gambas/File-modification-time new file mode 120000 index 0000000000..733e72bb84 --- /dev/null +++ b/Lang/Gambas/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/Gambas \ No newline at end of file diff --git a/Lang/Gambas/File-size b/Lang/Gambas/File-size new file mode 120000 index 0000000000..fc1ed13fdd --- /dev/null +++ b/Lang/Gambas/File-size @@ -0,0 +1 @@ +../../Task/File-size/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Filter b/Lang/Gambas/Filter new file mode 120000 index 0000000000..75e0204830 --- /dev/null +++ b/Lang/Gambas/Filter @@ -0,0 +1 @@ +../../Task/Filter/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Find-common-directory-path b/Lang/Gambas/Find-common-directory-path new file mode 120000 index 0000000000..de9f41ab55 --- /dev/null +++ b/Lang/Gambas/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Find-the-last-Sunday-of-each-month b/Lang/Gambas/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..31229bf8c9 --- /dev/null +++ b/Lang/Gambas/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Five-weekends b/Lang/Gambas/Five-weekends new file mode 120000 index 0000000000..a47c9a261e --- /dev/null +++ b/Lang/Gambas/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Gambas \ No newline at end of file diff --git a/Lang/Gambas/FizzBuzz b/Lang/Gambas/FizzBuzz new file mode 120000 index 0000000000..7734861e5c --- /dev/null +++ b/Lang/Gambas/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Flatten-a-list b/Lang/Gambas/Flatten-a-list new file mode 120000 index 0000000000..6dd5fd1c4d --- /dev/null +++ b/Lang/Gambas/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Flow-control-structures b/Lang/Gambas/Flow-control-structures new file mode 120000 index 0000000000..c9a6877184 --- /dev/null +++ b/Lang/Gambas/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Floyds-triangle b/Lang/Gambas/Floyds-triangle new file mode 120000 index 0000000000..91f4698738 --- /dev/null +++ b/Lang/Gambas/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Formatted-numeric-output b/Lang/Gambas/Formatted-numeric-output new file mode 120000 index 0000000000..7e2f5397f7 --- /dev/null +++ b/Lang/Gambas/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Function-definition b/Lang/Gambas/Function-definition new file mode 120000 index 0000000000..98361bace8 --- /dev/null +++ b/Lang/Gambas/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Gambas \ No newline at end of file diff --git a/Lang/Gambas/GUI-Maximum-window-dimensions b/Lang/Gambas/GUI-Maximum-window-dimensions new file mode 120000 index 0000000000..4fb84b8738 --- /dev/null +++ b/Lang/Gambas/GUI-Maximum-window-dimensions @@ -0,0 +1 @@ +../../Task/GUI-Maximum-window-dimensions/Gambas \ No newline at end of file diff --git a/Lang/Gambas/GUI-component-interaction b/Lang/Gambas/GUI-component-interaction new file mode 120000 index 0000000000..b0f0803b14 --- /dev/null +++ b/Lang/Gambas/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/Gambas \ No newline at end of file diff --git a/Lang/Gambas/GUI-enabling-disabling-of-controls b/Lang/Gambas/GUI-enabling-disabling-of-controls new file mode 120000 index 0000000000..61ff795ea8 --- /dev/null +++ b/Lang/Gambas/GUI-enabling-disabling-of-controls @@ -0,0 +1 @@ +../../Task/GUI-enabling-disabling-of-controls/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Generate-lower-case-ASCII-alphabet b/Lang/Gambas/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..22897ce191 --- /dev/null +++ b/Lang/Gambas/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Generic-swap b/Lang/Gambas/Generic-swap new file mode 120000 index 0000000000..ab34a15436 --- /dev/null +++ b/Lang/Gambas/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Greyscale-bars-Display b/Lang/Gambas/Greyscale-bars-Display new file mode 120000 index 0000000000..a70d01c486 --- /dev/null +++ b/Lang/Gambas/Greyscale-bars-Display @@ -0,0 +1 @@ +../../Task/Greyscale-bars-Display/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Guess-the-number b/Lang/Gambas/Guess-the-number new file mode 120000 index 0000000000..9663713184 --- /dev/null +++ b/Lang/Gambas/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Handle-a-signal b/Lang/Gambas/Handle-a-signal new file mode 120000 index 0000000000..e09b29c93e --- /dev/null +++ b/Lang/Gambas/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Harshad-or-Niven-series b/Lang/Gambas/Harshad-or-Niven-series new file mode 120000 index 0000000000..9859b05194 --- /dev/null +++ b/Lang/Gambas/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Hash-from-two-arrays b/Lang/Gambas/Hash-from-two-arrays new file mode 120000 index 0000000000..495c5c49a5 --- /dev/null +++ b/Lang/Gambas/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Hostname b/Lang/Gambas/Hostname new file mode 120000 index 0000000000..4381b91f3d --- /dev/null +++ b/Lang/Gambas/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Include-a-file b/Lang/Gambas/Include-a-file new file mode 120000 index 0000000000..7d80486ef2 --- /dev/null +++ b/Lang/Gambas/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Increment-a-numerical-string b/Lang/Gambas/Increment-a-numerical-string new file mode 120000 index 0000000000..c15efcc405 --- /dev/null +++ b/Lang/Gambas/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Integer-comparison b/Lang/Gambas/Integer-comparison new file mode 120000 index 0000000000..0d3f68c04f --- /dev/null +++ b/Lang/Gambas/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Keyboard-input-Keypress-check b/Lang/Gambas/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..2f7cc77bd2 --- /dev/null +++ b/Lang/Gambas/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Knuth-shuffle b/Lang/Gambas/Knuth-shuffle new file mode 120000 index 0000000000..40efe219ec --- /dev/null +++ b/Lang/Gambas/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Langtons-ant b/Lang/Gambas/Langtons-ant new file mode 120000 index 0000000000..8d4934c980 --- /dev/null +++ b/Lang/Gambas/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Largest-int-from-concatenated-ints b/Lang/Gambas/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..3316ada346 --- /dev/null +++ b/Lang/Gambas/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Last-Friday-of-each-month b/Lang/Gambas/Last-Friday-of-each-month new file mode 120000 index 0000000000..533c56a297 --- /dev/null +++ b/Lang/Gambas/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Leap-year b/Lang/Gambas/Leap-year new file mode 120000 index 0000000000..77f4032a29 --- /dev/null +++ b/Lang/Gambas/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Letter-frequency b/Lang/Gambas/Letter-frequency new file mode 120000 index 0000000000..be2d7f5d9b --- /dev/null +++ b/Lang/Gambas/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Look-and-say-sequence b/Lang/Gambas/Look-and-say-sequence new file mode 120000 index 0000000000..37c0e302bc --- /dev/null +++ b/Lang/Gambas/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Loop-over-multiple-arrays-simultaneously b/Lang/Gambas/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..07a414b556 --- /dev/null +++ b/Lang/Gambas/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Loops-Break b/Lang/Gambas/Loops-Break new file mode 120000 index 0000000000..421e24080f --- /dev/null +++ b/Lang/Gambas/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Loops-Continue b/Lang/Gambas/Loops-Continue new file mode 120000 index 0000000000..3676d06f54 --- /dev/null +++ b/Lang/Gambas/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Loops-Do-while b/Lang/Gambas/Loops-Do-while new file mode 120000 index 0000000000..3d2dd5e6f7 --- /dev/null +++ b/Lang/Gambas/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Loops-Downward-for b/Lang/Gambas/Loops-Downward-for new file mode 120000 index 0000000000..df6f510022 --- /dev/null +++ b/Lang/Gambas/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Loops-For-with-a-specified-step b/Lang/Gambas/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..5c451a5816 --- /dev/null +++ b/Lang/Gambas/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Loops-Foreach b/Lang/Gambas/Loops-Foreach new file mode 120000 index 0000000000..e4d331fbac --- /dev/null +++ b/Lang/Gambas/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Loops-Infinite b/Lang/Gambas/Loops-Infinite new file mode 120000 index 0000000000..42f40c18d5 --- /dev/null +++ b/Lang/Gambas/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Loops-N-plus-one-half b/Lang/Gambas/Loops-N-plus-one-half new file mode 120000 index 0000000000..2b503ed1dc --- /dev/null +++ b/Lang/Gambas/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Loops-Nested b/Lang/Gambas/Loops-Nested new file mode 120000 index 0000000000..c50f0b06ad --- /dev/null +++ b/Lang/Gambas/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Loops-While b/Lang/Gambas/Loops-While new file mode 120000 index 0000000000..2d53a13c24 --- /dev/null +++ b/Lang/Gambas/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Luhn-test-of-credit-card-numbers b/Lang/Gambas/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..5ca605a07e --- /dev/null +++ b/Lang/Gambas/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Make-directory-path b/Lang/Gambas/Make-directory-path new file mode 120000 index 0000000000..3caacbab03 --- /dev/null +++ b/Lang/Gambas/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Menu b/Lang/Gambas/Menu new file mode 120000 index 0000000000..54d48fefc0 --- /dev/null +++ b/Lang/Gambas/Menu @@ -0,0 +1 @@ +../../Task/Menu/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Middle-three-digits b/Lang/Gambas/Middle-three-digits new file mode 120000 index 0000000000..f9fe59f237 --- /dev/null +++ b/Lang/Gambas/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Morse-code b/Lang/Gambas/Morse-code new file mode 120000 index 0000000000..4c6d7743e2 --- /dev/null +++ b/Lang/Gambas/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Move-to-front-algorithm b/Lang/Gambas/Move-to-front-algorithm new file mode 120000 index 0000000000..237dae01d8 --- /dev/null +++ b/Lang/Gambas/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Multiplication-tables b/Lang/Gambas/Multiplication-tables new file mode 120000 index 0000000000..f0e1b28a40 --- /dev/null +++ b/Lang/Gambas/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Nth b/Lang/Gambas/Nth new file mode 120000 index 0000000000..8d2982b1d4 --- /dev/null +++ b/Lang/Gambas/Nth @@ -0,0 +1 @@ +../../Task/Nth/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Ordered-words b/Lang/Gambas/Ordered-words new file mode 120000 index 0000000000..46354802cf --- /dev/null +++ b/Lang/Gambas/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Phrase-reversals b/Lang/Gambas/Phrase-reversals new file mode 120000 index 0000000000..10d6da304d --- /dev/null +++ b/Lang/Gambas/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Pick-random-element b/Lang/Gambas/Pick-random-element new file mode 120000 index 0000000000..6689e53123 --- /dev/null +++ b/Lang/Gambas/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Pinstripe-Display b/Lang/Gambas/Pinstripe-Display new file mode 120000 index 0000000000..2485908bab --- /dev/null +++ b/Lang/Gambas/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Primality-by-trial-division b/Lang/Gambas/Primality-by-trial-division new file mode 120000 index 0000000000..0635a711ee --- /dev/null +++ b/Lang/Gambas/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Program-name b/Lang/Gambas/Program-name new file mode 120000 index 0000000000..f8d92e02c8 --- /dev/null +++ b/Lang/Gambas/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Program-termination b/Lang/Gambas/Program-termination new file mode 120000 index 0000000000..f17e7b8434 --- /dev/null +++ b/Lang/Gambas/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Range-extraction b/Lang/Gambas/Range-extraction new file mode 120000 index 0000000000..c5397a8777 --- /dev/null +++ b/Lang/Gambas/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Read-a-configuration-file b/Lang/Gambas/Read-a-configuration-file new file mode 120000 index 0000000000..35a69eaaab --- /dev/null +++ b/Lang/Gambas/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Read-a-file-line-by-line b/Lang/Gambas/Read-a-file-line-by-line new file mode 120000 index 0000000000..2ab206e0d2 --- /dev/null +++ b/Lang/Gambas/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Read-entire-file b/Lang/Gambas/Read-entire-file new file mode 120000 index 0000000000..4bc840a4dd --- /dev/null +++ b/Lang/Gambas/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Regular-expressions b/Lang/Gambas/Regular-expressions new file mode 120000 index 0000000000..8123e8e290 --- /dev/null +++ b/Lang/Gambas/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Remove-lines-from-a-file b/Lang/Gambas/Remove-lines-from-a-file new file mode 120000 index 0000000000..42781edaf1 --- /dev/null +++ b/Lang/Gambas/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Repeat-a-string b/Lang/Gambas/Repeat-a-string new file mode 120000 index 0000000000..15bd6a0674 --- /dev/null +++ b/Lang/Gambas/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Reverse-a-string b/Lang/Gambas/Reverse-a-string new file mode 120000 index 0000000000..46324cae8f --- /dev/null +++ b/Lang/Gambas/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Reverse-words-in-a-string b/Lang/Gambas/Reverse-words-in-a-string new file mode 120000 index 0000000000..e0b857f935 --- /dev/null +++ b/Lang/Gambas/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Roman-numerals-Decode b/Lang/Gambas/Roman-numerals-Decode new file mode 120000 index 0000000000..97affac4e6 --- /dev/null +++ b/Lang/Gambas/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Run-length-encoding b/Lang/Gambas/Run-length-encoding new file mode 120000 index 0000000000..235b157379 --- /dev/null +++ b/Lang/Gambas/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Search-a-list b/Lang/Gambas/Search-a-list new file mode 120000 index 0000000000..a17a1a0444 --- /dev/null +++ b/Lang/Gambas/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Shell-one-liner b/Lang/Gambas/Shell-one-liner new file mode 120000 index 0000000000..937d28dc2b --- /dev/null +++ b/Lang/Gambas/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Simple-windowed-application b/Lang/Gambas/Simple-windowed-application new file mode 120000 index 0000000000..db6ca82417 --- /dev/null +++ b/Lang/Gambas/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Sort-an-integer-array b/Lang/Gambas/Sort-an-integer-array new file mode 120000 index 0000000000..8aac6dd404 --- /dev/null +++ b/Lang/Gambas/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Gambas \ No newline at end of file diff --git a/Lang/Gambas/String-append b/Lang/Gambas/String-append new file mode 120000 index 0000000000..bfff34003b --- /dev/null +++ b/Lang/Gambas/String-append @@ -0,0 +1 @@ +../../Task/String-append/Gambas \ No newline at end of file diff --git a/Lang/Gambas/String-case b/Lang/Gambas/String-case new file mode 120000 index 0000000000..d80e47521c --- /dev/null +++ b/Lang/Gambas/String-case @@ -0,0 +1 @@ +../../Task/String-case/Gambas \ No newline at end of file diff --git a/Lang/Gambas/String-interpolation--included- b/Lang/Gambas/String-interpolation--included- new file mode 120000 index 0000000000..600a4af212 --- /dev/null +++ b/Lang/Gambas/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Gambas \ No newline at end of file diff --git a/Lang/Gambas/String-matching b/Lang/Gambas/String-matching new file mode 120000 index 0000000000..5896ef71d5 --- /dev/null +++ b/Lang/Gambas/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Gambas \ No newline at end of file diff --git a/Lang/Gambas/String-prepend b/Lang/Gambas/String-prepend new file mode 120000 index 0000000000..af41b6528b --- /dev/null +++ b/Lang/Gambas/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Strip-a-set-of-characters-from-a-string b/Lang/Gambas/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..4b6c4fd8c4 --- /dev/null +++ b/Lang/Gambas/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Gambas/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..1cc5eb7bab --- /dev/null +++ b/Lang/Gambas/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Gambas/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..9a6fa87af4 --- /dev/null +++ b/Lang/Gambas/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Substring b/Lang/Gambas/Substring new file mode 120000 index 0000000000..b16f4a4b04 --- /dev/null +++ b/Lang/Gambas/Substring @@ -0,0 +1 @@ +../../Task/Substring/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Sum-and-product-of-an-array b/Lang/Gambas/Sum-and-product-of-an-array new file mode 120000 index 0000000000..932d5399c7 --- /dev/null +++ b/Lang/Gambas/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Gambas \ No newline at end of file diff --git a/Lang/Gambas/System-time b/Lang/Gambas/System-time new file mode 120000 index 0000000000..0116b1e3d1 --- /dev/null +++ b/Lang/Gambas/System-time @@ -0,0 +1 @@ +../../Task/System-time/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Take-notes-on-the-command-line b/Lang/Gambas/Take-notes-on-the-command-line new file mode 120000 index 0000000000..147e839a7e --- /dev/null +++ b/Lang/Gambas/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Temperature-conversion b/Lang/Gambas/Temperature-conversion new file mode 120000 index 0000000000..3ed4e6b7d6 --- /dev/null +++ b/Lang/Gambas/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Unix-ls b/Lang/Gambas/Unix-ls new file mode 120000 index 0000000000..318ff16d6c --- /dev/null +++ b/Lang/Gambas/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Gambas \ No newline at end of file diff --git a/Lang/Gambas/User-input-Graphical b/Lang/Gambas/User-input-Graphical new file mode 120000 index 0000000000..35f4a3b50f --- /dev/null +++ b/Lang/Gambas/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Variable-size-Get b/Lang/Gambas/Variable-size-Get new file mode 120000 index 0000000000..0921222218 --- /dev/null +++ b/Lang/Gambas/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Walk-a-directory-Non-recursively b/Lang/Gambas/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..f188c7e259 --- /dev/null +++ b/Lang/Gambas/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Walk-a-directory-Recursively b/Lang/Gambas/Walk-a-directory-Recursively new file mode 120000 index 0000000000..ff3daf2a50 --- /dev/null +++ b/Lang/Gambas/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Web-scraping b/Lang/Gambas/Web-scraping new file mode 120000 index 0000000000..a1ddcaf0b8 --- /dev/null +++ b/Lang/Gambas/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Window-creation b/Lang/Gambas/Window-creation new file mode 120000 index 0000000000..70ee811b3c --- /dev/null +++ b/Lang/Gambas/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Yahoo--search-interface b/Lang/Gambas/Yahoo--search-interface new file mode 120000 index 0000000000..2e07f6ed91 --- /dev/null +++ b/Lang/Gambas/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Yin-and-yang b/Lang/Gambas/Yin-and-yang new file mode 120000 index 0000000000..67750daacf --- /dev/null +++ b/Lang/Gambas/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Zero-to-the-zero-power b/Lang/Gambas/Zero-to-the-zero-power new file mode 120000 index 0000000000..40d8d9766d --- /dev/null +++ b/Lang/Gambas/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Gambas \ No newline at end of file diff --git a/Lang/Gastona/00DESCRIPTION b/Lang/Gastona/00DESCRIPTION new file mode 100644 index 0000000000..707e68aef3 --- /dev/null +++ b/Lang/Gastona/00DESCRIPTION @@ -0,0 +1,10 @@ +{{language|Gastona +|site=https://github.com/wakeupthecat/gastona github.com/wakeupthecat/gastona}} + +'''Gastona''' is an interpreted language which main goal is to build applications with or +without Graphical User Interface with the less programming effort possible. Although it has variables, loops, +conditionals and other programming language characteristics, it can be considered more close to be +a "smart" configuration system. + +Current implementations are based on java and the code is open source that can be found at +[https://github.com/wakeupthecat/gastona github.com/wakeupthecat/gastoAna]. Binaries for Windows, Linux and also Android can be found at [https://sourceforge.net/projects/gastona/ sourceforge.net/projects/gastona]. \ No newline at end of file diff --git a/Lang/Gastona/A+B b/Lang/Gastona/A+B new file mode 120000 index 0000000000..e2564c85b0 --- /dev/null +++ b/Lang/Gastona/A+B @@ -0,0 +1 @@ +../../Task/A+B/Gastona \ No newline at end of file diff --git a/Lang/Gastona/HTTP b/Lang/Gastona/HTTP new file mode 120000 index 0000000000..83eec3089c --- /dev/null +++ b/Lang/Gastona/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Gastona \ No newline at end of file diff --git a/Lang/Gastona/Hello-world-Web-server b/Lang/Gastona/Hello-world-Web-server new file mode 120000 index 0000000000..be50ff6e37 --- /dev/null +++ b/Lang/Gastona/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Gastona \ No newline at end of file diff --git a/Lang/Gastona/README b/Lang/Gastona/README new file mode 100644 index 0000000000..b0975070b9 --- /dev/null +++ b/Lang/Gastona/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Gastona diff --git a/Lang/Gastona/Simple-windowed-application b/Lang/Gastona/Simple-windowed-application new file mode 120000 index 0000000000..6e8a87916a --- /dev/null +++ b/Lang/Gastona/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Gastona \ No newline at end of file diff --git a/Lang/Gastona/String-interpolation--included- b/Lang/Gastona/String-interpolation--included- new file mode 120000 index 0000000000..c58e10318a --- /dev/null +++ b/Lang/Gastona/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Gastona \ No newline at end of file diff --git a/Lang/Gastona/XML-XPath b/Lang/Gastona/XML-XPath new file mode 120000 index 0000000000..a7734ae1e4 --- /dev/null +++ b/Lang/Gastona/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Gastona \ No newline at end of file diff --git a/Lang/Gdl/Median-filter b/Lang/Gdl/Median-filter new file mode 120000 index 0000000000..0b9836cb84 --- /dev/null +++ b/Lang/Gdl/Median-filter @@ -0,0 +1 @@ +../../Task/Median-filter/Gdl \ No newline at end of file diff --git a/Lang/Gecho/Hello-world-Newline-omission b/Lang/Gecho/Hello-world-Newline-omission new file mode 120000 index 0000000000..d74bba7247 --- /dev/null +++ b/Lang/Gecho/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Gecho \ No newline at end of file diff --git a/Lang/Gecho/Hello-world-Text b/Lang/Gecho/Hello-world-Text new file mode 120000 index 0000000000..354a7e25ee --- /dev/null +++ b/Lang/Gecho/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Gecho \ No newline at end of file diff --git a/Lang/Gecho/Literals-Floating-point b/Lang/Gecho/Literals-Floating-point new file mode 120000 index 0000000000..703e486349 --- /dev/null +++ b/Lang/Gecho/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Gecho \ No newline at end of file diff --git a/Lang/Gecho/Literals-String b/Lang/Gecho/Literals-String new file mode 120000 index 0000000000..78619944e0 --- /dev/null +++ b/Lang/Gecho/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/Gecho \ No newline at end of file diff --git a/Lang/Gecho/Logical-operations b/Lang/Gecho/Logical-operations new file mode 120000 index 0000000000..22a477d4d9 --- /dev/null +++ b/Lang/Gecho/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Gecho \ No newline at end of file diff --git a/Lang/Genyris/00DESCRIPTION b/Lang/Genyris/00DESCRIPTION index cfa8c135f6..2acf649c80 100644 --- a/Lang/Genyris/00DESCRIPTION +++ b/Lang/Genyris/00DESCRIPTION @@ -1,8 +1,7 @@ {{language|Genyris |site=http://sourceforge.net/projects/genyris/}} -A new language inspired by the Semantic Web. Based on [[Scheme]], different because it is -* Fully [[Object-oriented]] +A language inspired by the Semantic Web. Based on [[Scheme]], different because * Objects may be members of multiple classes -* Classes are assigned and re-assigned to objects after construction +* Classes are assigned and re-assigned to objects _after_ construction * Indentation syntax reduces parentheses. {{language programming paradigm|object-oriented}} \ No newline at end of file diff --git a/Lang/Genyris/FizzBuzz b/Lang/Genyris/FizzBuzz new file mode 120000 index 0000000000..35ea174738 --- /dev/null +++ b/Lang/Genyris/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Genyris \ No newline at end of file diff --git a/Lang/Glee/100-doors b/Lang/Glee/100-doors new file mode 120000 index 0000000000..19a8955df9 --- /dev/null +++ b/Lang/Glee/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Glee \ No newline at end of file diff --git a/Lang/Glee/Permutations b/Lang/Glee/Permutations new file mode 120000 index 0000000000..01caa341b0 --- /dev/null +++ b/Lang/Glee/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Glee \ No newline at end of file diff --git a/Lang/Gnuplot/99-Bottles-of-Beer b/Lang/Gnuplot/99-Bottles-of-Beer new file mode 120000 index 0000000000..2cbcb04b27 --- /dev/null +++ b/Lang/Gnuplot/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Ackermann-function b/Lang/Gnuplot/Ackermann-function new file mode 120000 index 0000000000..34d78e1e5a --- /dev/null +++ b/Lang/Gnuplot/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Brownian-tree b/Lang/Gnuplot/Brownian-tree new file mode 120000 index 0000000000..8d80fe959c --- /dev/null +++ b/Lang/Gnuplot/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Comments b/Lang/Gnuplot/Comments new file mode 120000 index 0000000000..ffd60d6da6 --- /dev/null +++ b/Lang/Gnuplot/Comments @@ -0,0 +1 @@ +../../Task/Comments/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Constrained-random-points-on-a-circle b/Lang/Gnuplot/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..1404d4abad --- /dev/null +++ b/Lang/Gnuplot/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Dragon-curve b/Lang/Gnuplot/Dragon-curve new file mode 120000 index 0000000000..42beb72638 --- /dev/null +++ b/Lang/Gnuplot/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Execute-a-system-command b/Lang/Gnuplot/Execute-a-system-command new file mode 120000 index 0000000000..4dc2a1c6d0 --- /dev/null +++ b/Lang/Gnuplot/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Factorial b/Lang/Gnuplot/Factorial new file mode 120000 index 0000000000..b806b0c421 --- /dev/null +++ b/Lang/Gnuplot/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Find-limit-of-recursion b/Lang/Gnuplot/Find-limit-of-recursion new file mode 120000 index 0000000000..c061ddc133 --- /dev/null +++ b/Lang/Gnuplot/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Formatted-numeric-output b/Lang/Gnuplot/Formatted-numeric-output new file mode 120000 index 0000000000..90bbea891a --- /dev/null +++ b/Lang/Gnuplot/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Greatest-common-divisor b/Lang/Gnuplot/Greatest-common-divisor new file mode 120000 index 0000000000..3337a95ddd --- /dev/null +++ b/Lang/Gnuplot/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Input-loop b/Lang/Gnuplot/Input-loop new file mode 120000 index 0000000000..d740dc7465 --- /dev/null +++ b/Lang/Gnuplot/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Mandelbrot-set b/Lang/Gnuplot/Mandelbrot-set new file mode 120000 index 0000000000..ba538311ae --- /dev/null +++ b/Lang/Gnuplot/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Modular-exponentiation b/Lang/Gnuplot/Modular-exponentiation new file mode 120000 index 0000000000..ae2e4eaf08 --- /dev/null +++ b/Lang/Gnuplot/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Plot-coordinate-pairs b/Lang/Gnuplot/Plot-coordinate-pairs new file mode 120000 index 0000000000..024c646829 --- /dev/null +++ b/Lang/Gnuplot/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Polynomial-regression b/Lang/Gnuplot/Polynomial-regression new file mode 120000 index 0000000000..d047800a58 --- /dev/null +++ b/Lang/Gnuplot/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Sierpinski-carpet b/Lang/Gnuplot/Sierpinski-carpet new file mode 120000 index 0000000000..e2432d2bba --- /dev/null +++ b/Lang/Gnuplot/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Sierpinski-triangle b/Lang/Gnuplot/Sierpinski-triangle new file mode 120000 index 0000000000..c874484934 --- /dev/null +++ b/Lang/Gnuplot/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Sierpinski-triangle-Graphical b/Lang/Gnuplot/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..e9bfdbfd61 --- /dev/null +++ b/Lang/Gnuplot/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Terminal-control-Ringing-the-terminal-bell b/Lang/Gnuplot/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..c8d014c1fa --- /dev/null +++ b/Lang/Gnuplot/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Gnuplot \ No newline at end of file diff --git a/Lang/Go/Abundant,-deficient-and-perfect-number-classifications b/Lang/Go/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..3a5e6fe79e --- /dev/null +++ b/Lang/Go/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Go \ No newline at end of file diff --git a/Lang/Go/Amicable-pairs b/Lang/Go/Amicable-pairs new file mode 120000 index 0000000000..53d138fa07 --- /dev/null +++ b/Lang/Go/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Go \ No newline at end of file diff --git a/Lang/Go/Character-matching b/Lang/Go/Character-matching deleted file mode 120000 index 52bbff82cc..0000000000 --- a/Lang/Go/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Go \ No newline at end of file diff --git a/Lang/Go/File-IO b/Lang/Go/File-IO deleted file mode 120000 index d8c3c8d610..0000000000 --- a/Lang/Go/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/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/Mutex b/Lang/Go/Mutex deleted file mode 120000 index ae1d58ef7b..0000000000 --- a/Lang/Go/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Go \ No newline at end of file diff --git a/Lang/Go/Penneys-game b/Lang/Go/Penneys-game new file mode 120000 index 0000000000..da70526b59 --- /dev/null +++ b/Lang/Go/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Go \ No newline at end of file diff --git a/Lang/Go/Rosetta-Code-Count-examples b/Lang/Go/Rosetta-Code-Count-examples deleted file mode 120000 index 12d28e0862..0000000000 --- a/Lang/Go/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Go \ No newline at end of file diff --git a/Lang/Go/Rosetta-Code-Find-unimplemented-tasks b/Lang/Go/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index aa0888ccb8..0000000000 --- a/Lang/Go/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/Go \ No newline at end of file diff --git a/Lang/Go/Rosetta-Code-Fix-code-tags b/Lang/Go/Rosetta-Code-Fix-code-tags deleted file mode 120000 index 327886fb15..0000000000 --- a/Lang/Go/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/Go \ No newline at end of file diff --git a/Lang/Go/Rosetta-Code-Rank-languages-by-popularity b/Lang/Go/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 44340b6f37..0000000000 --- a/Lang/Go/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Go \ No newline at end of file diff --git a/Lang/Go/Standard-deviation b/Lang/Go/Standard-deviation deleted file mode 120000 index cbb11e110b..0000000000 --- a/Lang/Go/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Go \ No newline at end of file diff --git a/Lang/Golo/Accumulator-factory b/Lang/Golo/Accumulator-factory new file mode 120000 index 0000000000..fc6aa58c29 --- /dev/null +++ b/Lang/Golo/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Golo \ No newline at end of file diff --git a/Lang/Golo/Execute-HQ9+ b/Lang/Golo/Execute-HQ9+ new file mode 120000 index 0000000000..538b793c67 --- /dev/null +++ b/Lang/Golo/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/Golo \ No newline at end of file diff --git a/Lang/Golo/FizzBuzz b/Lang/Golo/FizzBuzz new file mode 120000 index 0000000000..588bd4aeff --- /dev/null +++ b/Lang/Golo/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Golo \ No newline at end of file diff --git a/Lang/Gosu/00DESCRIPTION b/Lang/Gosu/00DESCRIPTION index 95b39e193f..05ee1895c9 100644 --- a/Lang/Gosu/00DESCRIPTION +++ b/Lang/Gosu/00DESCRIPTION @@ -3,7 +3,8 @@ |checking=static}} {{Language programming paradigm|imperative}} {{Language programming paradigm|object-oriented}} -'''Gosu''' is [[runs on vm::JVM]]-based an imperative statically-typed object-oriented programming language that is designed to be expressive, easy-to-read, and reasonably fast. It started in 2002 in company called [http://guidewire.com/ Guidewire] as a internal language and was released in 2010 to the opensource world. +'''Gosu''' is a statically-typed [[runs on vm::JVM]]-based general purpose programming language that is designed to be expressive, easy-to-read, and high performing. Gosu is uniquely both a high-functioning general purpose language as well as a powerful and concise scripting language. In addition Gosu's type system defines an open API for domain-specific *types* as opposed to grammar e.g., XSD/XML is type-safe and modeled directly from XML schema files, without intermediate code generation. Gosu began in 2002 from [http://guidewire.com/ Guidewire Software] as an internal language and was released in 2010 to the opensource world. Scott McKinney is the creator and principle developer of the language. +* [https://gosu-lang.github.io/ Gosu Home Page] * [http://lazygosu.github.io/ LazyGosu - nice community tutorial] * [http://developers.slashdot.org/story/10/11/09/0510258/Gosu-Programming-Language-Released-To-Public Slashdot finds Gosu] \ No newline at end of file diff --git a/Lang/Gosu/Associative-array-Creation b/Lang/Gosu/Associative-array-Creation new file mode 120000 index 0000000000..db61cfa7e3 --- /dev/null +++ b/Lang/Gosu/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Gosu \ No newline at end of file diff --git a/Lang/Gosu/Factors-of-an-integer b/Lang/Gosu/Factors-of-an-integer new file mode 120000 index 0000000000..88a6cb8c28 --- /dev/null +++ b/Lang/Gosu/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Gosu \ No newline at end of file diff --git a/Lang/Gosu/JSON b/Lang/Gosu/JSON new file mode 120000 index 0000000000..c886ad5d46 --- /dev/null +++ b/Lang/Gosu/JSON @@ -0,0 +1 @@ +../../Task/JSON/Gosu \ No newline at end of file diff --git a/Lang/Gosu/Loops-N-plus-one-half b/Lang/Gosu/Loops-N-plus-one-half new file mode 120000 index 0000000000..4e965162e4 --- /dev/null +++ b/Lang/Gosu/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Gosu \ No newline at end of file diff --git a/Lang/Gosu/Middle-three-digits b/Lang/Gosu/Middle-three-digits new file mode 120000 index 0000000000..23cb9e4a1a --- /dev/null +++ b/Lang/Gosu/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Gosu \ No newline at end of file diff --git a/Lang/Gosu/String-append b/Lang/Gosu/String-append new file mode 120000 index 0000000000..8e676ebd0a --- /dev/null +++ b/Lang/Gosu/String-append @@ -0,0 +1 @@ +../../Task/String-append/Gosu \ No newline at end of file diff --git a/Lang/Groovy/9-billion-names-of-God-the-integer b/Lang/Groovy/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..26ead67724 --- /dev/null +++ b/Lang/Groovy/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Almost-prime b/Lang/Groovy/Almost-prime new file mode 120000 index 0000000000..1b4d8750d3 --- /dev/null +++ b/Lang/Groovy/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Catalan-numbers b/Lang/Groovy/Catalan-numbers new file mode 120000 index 0000000000..44a4959109 --- /dev/null +++ b/Lang/Groovy/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Catalan-numbers-Pascals-triangle b/Lang/Groovy/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..d0aac85a51 --- /dev/null +++ b/Lang/Groovy/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Groovy \ No newline at end of file diff --git a/Lang/Groovy/File-IO b/Lang/Groovy/File-IO deleted file mode 120000 index 1947155e88..0000000000 --- a/Lang/Groovy/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Harshad-or-Niven-series b/Lang/Groovy/Harshad-or-Niven-series new file mode 120000 index 0000000000..e5ef7e20fc --- /dev/null +++ b/Lang/Groovy/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Integer-sequence b/Lang/Groovy/Integer-sequence deleted file mode 120000 index 84cfa7f843..0000000000 --- a/Lang/Groovy/Integer-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Integer-sequence/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Long-multiplication b/Lang/Groovy/Long-multiplication deleted file mode 120000 index 77c4e16299..0000000000 --- a/Lang/Groovy/Long-multiplication +++ /dev/null @@ -1 +0,0 @@ -../../Task/Long-multiplication/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Pernicious-numbers b/Lang/Groovy/Pernicious-numbers new file mode 120000 index 0000000000..ca31c26b55 --- /dev/null +++ b/Lang/Groovy/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Rosetta-Code-Rank-languages-by-popularity b/Lang/Groovy/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 53bac431a5..0000000000 --- a/Lang/Groovy/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Runge-Kutta-method b/Lang/Groovy/Runge-Kutta-method new file mode 120000 index 0000000000..db8182b329 --- /dev/null +++ b/Lang/Groovy/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Stair-climbing-puzzle b/Lang/Groovy/Stair-climbing-puzzle new file mode 120000 index 0000000000..6d39569c18 --- /dev/null +++ b/Lang/Groovy/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Standard-deviation b/Lang/Groovy/Standard-deviation deleted file mode 120000 index 32c4cffe09..0000000000 --- a/Lang/Groovy/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Groovy \ No newline at end of file diff --git a/Lang/Groovy/String-append b/Lang/Groovy/String-append new file mode 120000 index 0000000000..4e76ffe8a6 --- /dev/null +++ b/Lang/Groovy/String-append @@ -0,0 +1 @@ +../../Task/String-append/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Temperature-conversion b/Lang/Groovy/Temperature-conversion new file mode 120000 index 0000000000..345155f365 --- /dev/null +++ b/Lang/Groovy/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Groovy \ No newline at end of file diff --git a/Lang/HQ9+/99-Bottles-of-Beer b/Lang/HQ9+/99-Bottles-of-Beer deleted file mode 120000 index af94471f5e..0000000000 --- a/Lang/HQ9+/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/HQ9+ \ No newline at end of file diff --git a/Lang/Halon/00DESCRIPTION b/Lang/Halon/00DESCRIPTION new file mode 100644 index 0000000000..734c0644be --- /dev/null +++ b/Lang/Halon/00DESCRIPTION @@ -0,0 +1,4 @@ +{{language|Halon +|parampass=value +|site=http://docs.halon.se/hsl/}} +'''HSL''' (Halon Scripting Language) is a domain-specific scripting language originally designed for processing SMTP transaction and email parsing in the Halon SMTP server. A SMTP software for highly dynamic email environment (hosting and telecom) where customer, settings and routing information needs to be handled dynamically (hence the need for a dynamic scripting language). HSL is currently only available in the Halon software engine, but can be used from a command line interface (REPL). The language support basic classes, has first-class functions and modules, and lot of it's features are borrowed from [[PHP]], [[Python]], [[Javascript]] and [[Perl]]. \ No newline at end of file diff --git a/Lang/Halon/99-Bottles-of-Beer b/Lang/Halon/99-Bottles-of-Beer new file mode 120000 index 0000000000..ed46013d1a --- /dev/null +++ b/Lang/Halon/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Halon \ No newline at end of file diff --git a/Lang/Halon/Arrays b/Lang/Halon/Arrays new file mode 120000 index 0000000000..6076f80e1e --- /dev/null +++ b/Lang/Halon/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Halon \ No newline at end of file diff --git a/Lang/Halon/Function-definition b/Lang/Halon/Function-definition new file mode 120000 index 0000000000..a4fd82341b --- /dev/null +++ b/Lang/Halon/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Halon \ No newline at end of file diff --git a/Lang/Halon/HTTP b/Lang/Halon/HTTP new file mode 120000 index 0000000000..a5793ec2aa --- /dev/null +++ b/Lang/Halon/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Halon \ No newline at end of file diff --git a/Lang/Halon/Hello-world-Text b/Lang/Halon/Hello-world-Text new file mode 120000 index 0000000000..ac3635884b --- /dev/null +++ b/Lang/Halon/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Halon \ No newline at end of file diff --git a/Lang/Halon/JSON b/Lang/Halon/JSON new file mode 120000 index 0000000000..adbd00688e --- /dev/null +++ b/Lang/Halon/JSON @@ -0,0 +1 @@ +../../Task/JSON/Halon \ No newline at end of file diff --git a/Lang/Halon/Loops-Foreach b/Lang/Halon/Loops-Foreach new file mode 120000 index 0000000000..b4f2374011 --- /dev/null +++ b/Lang/Halon/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Halon \ No newline at end of file diff --git a/Lang/Halon/Loops-Infinite b/Lang/Halon/Loops-Infinite new file mode 120000 index 0000000000..8347ad23ba --- /dev/null +++ b/Lang/Halon/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Halon \ No newline at end of file diff --git a/Lang/Halon/README b/Lang/Halon/README new file mode 100644 index 0000000000..c9af7435f1 --- /dev/null +++ b/Lang/Halon/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Halon diff --git a/Lang/Halon/SHA-1 b/Lang/Halon/SHA-1 new file mode 120000 index 0000000000..b32ebb3c33 --- /dev/null +++ b/Lang/Halon/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Halon \ No newline at end of file diff --git a/Lang/Halon/SHA-256 b/Lang/Halon/SHA-256 new file mode 120000 index 0000000000..e6788b5dd6 --- /dev/null +++ b/Lang/Halon/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Halon \ No newline at end of file diff --git a/Lang/Halon/String-concatenation b/Lang/Halon/String-concatenation new file mode 120000 index 0000000000..8b6615a5ba --- /dev/null +++ b/Lang/Halon/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Halon \ No newline at end of file diff --git a/Lang/Halon/Time-a-function b/Lang/Halon/Time-a-function new file mode 120000 index 0000000000..6e4a860769 --- /dev/null +++ b/Lang/Halon/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Halon \ No newline at end of file diff --git a/Lang/Haskell/Call-a-function-in-a-shared-library b/Lang/Haskell/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..783af9a000 --- /dev/null +++ b/Lang/Haskell/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Character-matching b/Lang/Haskell/Character-matching deleted file mode 120000 index e322b4e9f9..0000000000 --- a/Lang/Haskell/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Extreme-floating-point-values b/Lang/Haskell/Extreme-floating-point-values new file mode 120000 index 0000000000..0f63c02684 --- /dev/null +++ b/Lang/Haskell/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Haskell \ No newline at end of file diff --git a/Lang/Haskell/File-IO b/Lang/Haskell/File-IO deleted file mode 120000 index 081caec161..0000000000 --- a/Lang/Haskell/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Find-limit-of-recursion b/Lang/Haskell/Find-limit-of-recursion new file mode 120000 index 0000000000..b4fe0f70f1 --- /dev/null +++ b/Lang/Haskell/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/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/Mutex b/Lang/Haskell/Mutex deleted file mode 120000 index da903a20b5..0000000000 --- a/Lang/Haskell/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Percolation-Bond-percolation b/Lang/Haskell/Percolation-Bond-percolation new file mode 120000 index 0000000000..354fefb3eb --- /dev/null +++ b/Lang/Haskell/Percolation-Bond-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Bond-percolation/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Rosetta-Code-Count-examples b/Lang/Haskell/Rosetta-Code-Count-examples deleted file mode 120000 index e848948d8d..0000000000 --- a/Lang/Haskell/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Rosetta-Code-Find-unimplemented-tasks b/Lang/Haskell/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index 150cbab4dd..0000000000 --- a/Lang/Haskell/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Rosetta-Code-Rank-languages-by-popularity b/Lang/Haskell/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 3768cd4a16..0000000000 --- a/Lang/Haskell/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Scope-Function-names-and-labels b/Lang/Haskell/Scope-Function-names-and-labels new file mode 120000 index 0000000000..7b05fb3ab0 --- /dev/null +++ b/Lang/Haskell/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Standard-deviation b/Lang/Haskell/Standard-deviation deleted file mode 120000 index e19450d67c..0000000000 --- a/Lang/Haskell/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Topic-variable b/Lang/Haskell/Topic-variable new file mode 120000 index 0000000000..1e15ae6bb0 --- /dev/null +++ b/Lang/Haskell/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Vigen-re-cipher-Cryptanalysis b/Lang/Haskell/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..35b5f514cf --- /dev/null +++ b/Lang/Haskell/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Haskell \ No newline at end of file diff --git a/Lang/Haxe/Determine-if-a-string-is-numeric b/Lang/Haxe/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..2c9554887c --- /dev/null +++ b/Lang/Haxe/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Standard-deviation b/Lang/Haxe/Standard-deviation deleted file mode 120000 index 01324a2bdc..0000000000 --- a/Lang/Haxe/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Haxe \ No newline at end of file diff --git a/Lang/HicEst/File-IO b/Lang/HicEst/File-IO deleted file mode 120000 index 15ffb36980..0000000000 --- a/Lang/HicEst/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Rosetta-Code-Rank-languages-by-popularity b/Lang/HicEst/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 457f520540..0000000000 --- a/Lang/HicEst/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Standard-deviation b/Lang/HicEst/Standard-deviation deleted file mode 120000 index a8bfa138bf..0000000000 --- a/Lang/HicEst/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/HicEst \ No newline at end of file diff --git a/Lang/HolyC/FizzBuzz b/Lang/HolyC/FizzBuzz new file mode 120000 index 0000000000..779c2f200d --- /dev/null +++ b/Lang/HolyC/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Integer-sequence b/Lang/HolyC/Integer-sequence new file mode 120000 index 0000000000..4a51935d9e --- /dev/null +++ b/Lang/HolyC/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Loops-Break b/Lang/HolyC/Loops-Break new file mode 120000 index 0000000000..309aeef0b4 --- /dev/null +++ b/Lang/HolyC/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Loops-Do-while b/Lang/HolyC/Loops-Do-while new file mode 120000 index 0000000000..2d765f09cd --- /dev/null +++ b/Lang/HolyC/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Loops-Downward-for b/Lang/HolyC/Loops-Downward-for new file mode 120000 index 0000000000..464c77dd6a --- /dev/null +++ b/Lang/HolyC/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Loops-For b/Lang/HolyC/Loops-For new file mode 120000 index 0000000000..8955c5f681 --- /dev/null +++ b/Lang/HolyC/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Loops-For-with-a-specified-step b/Lang/HolyC/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..e0c8e424fd --- /dev/null +++ b/Lang/HolyC/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Loops-Infinite b/Lang/HolyC/Loops-Infinite new file mode 120000 index 0000000000..c40fcc2335 --- /dev/null +++ b/Lang/HolyC/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Loops-N-plus-one-half b/Lang/HolyC/Loops-N-plus-one-half new file mode 120000 index 0000000000..b95d780aac --- /dev/null +++ b/Lang/HolyC/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Loops-While b/Lang/HolyC/Loops-While new file mode 120000 index 0000000000..844f171859 --- /dev/null +++ b/Lang/HolyC/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/HolyC \ No newline at end of file diff --git a/Lang/Hy/A+B b/Lang/Hy/A+B new file mode 120000 index 0000000000..ca1e79c70f --- /dev/null +++ b/Lang/Hy/A+B @@ -0,0 +1 @@ +../../Task/A+B/Hy \ No newline at end of file diff --git a/Lang/Hy/Array-concatenation b/Lang/Hy/Array-concatenation new file mode 120000 index 0000000000..0f6f45bab6 --- /dev/null +++ b/Lang/Hy/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Hy \ No newline at end of file diff --git a/Lang/Hy/Currying b/Lang/Hy/Currying new file mode 120000 index 0000000000..c650f7c30c --- /dev/null +++ b/Lang/Hy/Currying @@ -0,0 +1 @@ +../../Task/Currying/Hy \ No newline at end of file diff --git a/Lang/Hy/Dot-product b/Lang/Hy/Dot-product new file mode 120000 index 0000000000..88fa05e4ab --- /dev/null +++ b/Lang/Hy/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Hy \ No newline at end of file diff --git a/Lang/Hy/Factorial b/Lang/Hy/Factorial new file mode 120000 index 0000000000..5e0d293fde --- /dev/null +++ b/Lang/Hy/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Hy \ No newline at end of file diff --git a/Lang/Hy/Flatten-a-list b/Lang/Hy/Flatten-a-list new file mode 120000 index 0000000000..aa03ce7fa9 --- /dev/null +++ b/Lang/Hy/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Hy \ No newline at end of file diff --git a/Lang/Hy/Function-composition b/Lang/Hy/Function-composition new file mode 120000 index 0000000000..142c7643ae --- /dev/null +++ b/Lang/Hy/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Hy \ No newline at end of file diff --git a/Lang/Hy/Function-definition b/Lang/Hy/Function-definition new file mode 120000 index 0000000000..8705cc1e32 --- /dev/null +++ b/Lang/Hy/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Hy \ No newline at end of file diff --git a/Lang/Hy/Increment-a-numerical-string b/Lang/Hy/Increment-a-numerical-string new file mode 120000 index 0000000000..0312504bb1 --- /dev/null +++ b/Lang/Hy/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Hy \ No newline at end of file diff --git a/Lang/Hy/Integer-comparison b/Lang/Hy/Integer-comparison new file mode 120000 index 0000000000..369423e15d --- /dev/null +++ b/Lang/Hy/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Hy \ No newline at end of file diff --git a/Lang/Hy/List-comprehensions b/Lang/Hy/List-comprehensions new file mode 120000 index 0000000000..5096d41f26 --- /dev/null +++ b/Lang/Hy/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Hy \ No newline at end of file diff --git a/Lang/Hy/Logical-operations b/Lang/Hy/Logical-operations new file mode 120000 index 0000000000..b2fc7ca4f0 --- /dev/null +++ b/Lang/Hy/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Hy \ No newline at end of file diff --git a/Lang/Hy/Loops-Foreach b/Lang/Hy/Loops-Foreach new file mode 120000 index 0000000000..308da66549 --- /dev/null +++ b/Lang/Hy/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Hy \ No newline at end of file diff --git a/Lang/IDL/File-IO b/Lang/IDL/File-IO deleted file mode 120000 index 1b19879ca3..0000000000 --- a/Lang/IDL/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/IDL \ No newline at end of file diff --git a/Lang/IWBASIC/00DESCRIPTION b/Lang/IWBASIC/00DESCRIPTION new file mode 100644 index 0000000000..dfaba2554e --- /dev/null +++ b/Lang/IWBASIC/00DESCRIPTION @@ -0,0 +1,6 @@ +{{stub}} +{{language|IWBASIC +|site=http://www.ionicwind.com/ +|tags=IWBASIC}} + +IWBasic is a 32-bit BASIC compiler from Ionic Wind Software featuring an integrated development environment with syntax similar to the BASIC programming language. \ No newline at end of file diff --git a/Lang/IWBASIC/Function-definition b/Lang/IWBASIC/Function-definition new file mode 120000 index 0000000000..acbbacee71 --- /dev/null +++ b/Lang/IWBASIC/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/IWBASIC \ No newline at end of file diff --git a/Lang/IWBASIC/GUI-Maximum-window-dimensions b/Lang/IWBASIC/GUI-Maximum-window-dimensions new file mode 120000 index 0000000000..fa2da92d88 --- /dev/null +++ b/Lang/IWBASIC/GUI-Maximum-window-dimensions @@ -0,0 +1 @@ +../../Task/GUI-Maximum-window-dimensions/IWBASIC \ No newline at end of file diff --git a/Lang/IWBASIC/Hello-world-Graphical b/Lang/IWBASIC/Hello-world-Graphical new file mode 120000 index 0000000000..3d737f3301 --- /dev/null +++ b/Lang/IWBASIC/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/IWBASIC \ No newline at end of file diff --git a/Lang/IWBASIC/Hello-world-Newline-omission b/Lang/IWBASIC/Hello-world-Newline-omission new file mode 120000 index 0000000000..00d74a428d --- /dev/null +++ b/Lang/IWBASIC/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/IWBASIC \ No newline at end of file diff --git a/Lang/IWBASIC/Hello-world-Text b/Lang/IWBASIC/Hello-world-Text new file mode 120000 index 0000000000..44995083a9 --- /dev/null +++ b/Lang/IWBASIC/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/IWBASIC \ No newline at end of file diff --git a/Lang/IWBASIC/Include-a-file b/Lang/IWBASIC/Include-a-file new file mode 120000 index 0000000000..f587c9f892 --- /dev/null +++ b/Lang/IWBASIC/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/IWBASIC \ No newline at end of file diff --git a/Lang/IWBASIC/Loops-While b/Lang/IWBASIC/Loops-While new file mode 120000 index 0000000000..e1ce39e615 --- /dev/null +++ b/Lang/IWBASIC/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/IWBASIC \ No newline at end of file diff --git a/Lang/IWBASIC/README b/Lang/IWBASIC/README new file mode 100644 index 0000000000..3778b98791 --- /dev/null +++ b/Lang/IWBASIC/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:IWBASIC diff --git a/Lang/Icon/Calendar---for-real-programmers b/Lang/Icon/Calendar---for-real-programmers deleted file mode 120000 index f87a3bab2a..0000000000 --- a/Lang/Icon/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/Icon \ No newline at end of file diff --git a/Lang/Icon/File-IO b/Lang/Icon/File-IO deleted file mode 120000 index a383c301d6..0000000000 --- a/Lang/Icon/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Icon \ No newline at end of file diff --git a/Lang/Icon/Four-bit-adder b/Lang/Icon/Four-bit-adder new file mode 120000 index 0000000000..6542f4d133 --- /dev/null +++ b/Lang/Icon/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/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/Rosetta-Code-Find-unimplemented-tasks b/Lang/Icon/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index 1e7b892393..0000000000 --- a/Lang/Icon/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/Icon \ No newline at end of file diff --git a/Lang/Icon/Rosetta-Code-Rank-languages-by-popularity b/Lang/Icon/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 442c3df12c..0000000000 --- a/Lang/Icon/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Icon \ No newline at end of file diff --git a/Lang/Icon/Standard-deviation b/Lang/Icon/Standard-deviation deleted file mode 120000 index ca6327a6d5..0000000000 --- a/Lang/Icon/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Icon \ No newline at end of file diff --git a/Lang/Inform-7/Empty-program b/Lang/Inform-7/Empty-program new file mode 120000 index 0000000000..0f56365c64 --- /dev/null +++ b/Lang/Inform-7/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Inform-7 \ No newline at end of file diff --git a/Lang/Integer-BASIC/99-Bottles-of-Beer b/Lang/Integer-BASIC/99-Bottles-of-Beer deleted file mode 120000 index 707b176715..0000000000 --- a/Lang/Integer-BASIC/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Integer-BASIC \ No newline at end of file diff --git a/Lang/Io/File-IO b/Lang/Io/File-IO deleted file mode 120000 index b3b0e02224..0000000000 --- a/Lang/Io/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Io \ No newline at end of file diff --git a/Lang/Io/Mutual-recursion b/Lang/Io/Mutual-recursion new file mode 120000 index 0000000000..f9a78fb578 --- /dev/null +++ b/Lang/Io/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Io \ No newline at end of file diff --git a/Lang/J/Calendar---for-real-programmers b/Lang/J/Calendar---for-real-programmers deleted file mode 120000 index a2d759cdf1..0000000000 --- a/Lang/J/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/J \ No newline at end of file diff --git a/Lang/J/Character-matching b/Lang/J/Character-matching deleted file mode 120000 index 602547d09b..0000000000 --- a/Lang/J/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/J \ No newline at end of file diff --git a/Lang/J/File-IO b/Lang/J/File-IO deleted file mode 120000 index 602773ed27..0000000000 --- a/Lang/J/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/J \ No newline at end of file diff --git a/Lang/J/MD4 b/Lang/J/MD4 new file mode 120000 index 0000000000..acf1dae62d --- /dev/null +++ b/Lang/J/MD4 @@ -0,0 +1 @@ +../../Task/MD4/J \ No newline at end of file diff --git a/Lang/J/Rosetta-Code-Count-examples b/Lang/J/Rosetta-Code-Count-examples deleted file mode 120000 index bf0f74d897..0000000000 --- a/Lang/J/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/J \ No newline at end of file diff --git a/Lang/J/Rosetta-Code-Find-unimplemented-tasks b/Lang/J/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index d69b65cbde..0000000000 --- a/Lang/J/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/J \ No newline at end of file diff --git a/Lang/J/Rosetta-Code-Fix-code-tags b/Lang/J/Rosetta-Code-Fix-code-tags deleted file mode 120000 index ac294949d3..0000000000 --- a/Lang/J/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/J \ No newline at end of file diff --git a/Lang/J/Standard-deviation b/Lang/J/Standard-deviation deleted file mode 120000 index 49ea3ab5d4..0000000000 --- a/Lang/J/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/J \ No newline at end of file diff --git a/Lang/Java/Active-object b/Lang/Java/Active-object new file mode 120000 index 0000000000..aa9be431a7 --- /dev/null +++ b/Lang/Java/Active-object @@ -0,0 +1 @@ +../../Task/Active-object/Java \ No newline at end of file diff --git a/Lang/Java/Character-matching b/Lang/Java/Character-matching deleted file mode 120000 index 6c0faea249..0000000000 --- a/Lang/Java/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Java \ No newline at end of file diff --git a/Lang/Java/File-IO b/Lang/Java/File-IO deleted file mode 120000 index 5f5de7b3e6..0000000000 --- a/Lang/Java/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Java \ No newline at end of file diff --git a/Lang/Java/FizzBuzz b/Lang/Java/FizzBuzz deleted file mode 120000 index b7e778d9be..0000000000 --- a/Lang/Java/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Java \ No newline at end of file diff --git a/Lang/Java/Hello-world-Newbie b/Lang/Java/Hello-world-Newbie new file mode 120000 index 0000000000..da2bbc6974 --- /dev/null +++ b/Lang/Java/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/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/Mutex b/Lang/Java/Mutex deleted file mode 120000 index 5c0eaa6809..0000000000 --- a/Lang/Java/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Java \ No newline at end of file diff --git a/Lang/Java/Permutations-by-swapping b/Lang/Java/Permutations-by-swapping new file mode 120000 index 0000000000..5be047ee56 --- /dev/null +++ b/Lang/Java/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Java \ No newline at end of file diff --git a/Lang/Java/Rosetta-Code-Count-examples b/Lang/Java/Rosetta-Code-Count-examples deleted file mode 120000 index 94544023c4..0000000000 --- a/Lang/Java/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Java \ No newline at end of file diff --git a/Lang/Java/Rosetta-Code-Fix-code-tags b/Lang/Java/Rosetta-Code-Fix-code-tags deleted file mode 120000 index 42e08f2326..0000000000 --- a/Lang/Java/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/Java \ No newline at end of file diff --git a/Lang/Java/Standard-deviation b/Lang/Java/Standard-deviation deleted file mode 120000 index 7e52652d25..0000000000 --- a/Lang/Java/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Java \ No newline at end of file diff --git a/Lang/Java/Unix-ls b/Lang/Java/Unix-ls new file mode 120000 index 0000000000..c9a33da43e --- /dev/null +++ b/Lang/Java/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Java \ No newline at end of file diff --git a/Lang/Java/Use-another-language-to-call-a-function b/Lang/Java/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..5fb758ec55 --- /dev/null +++ b/Lang/Java/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Java \ No newline at end of file diff --git a/Lang/JavaScript/Almost-prime b/Lang/JavaScript/Almost-prime new file mode 120000 index 0000000000..0f6180227c --- /dev/null +++ b/Lang/JavaScript/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Averages-Mean-time-of-day b/Lang/JavaScript/Averages-Mean-time-of-day new file mode 120000 index 0000000000..c1d3ae882d --- /dev/null +++ b/Lang/JavaScript/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Character-matching b/Lang/JavaScript/Character-matching deleted file mode 120000 index ffe8cb3d81..0000000000 --- a/Lang/JavaScript/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Circles-of-given-radius-through-two-points b/Lang/JavaScript/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..4d4dfd8134 --- /dev/null +++ b/Lang/JavaScript/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Draw-a-cuboid b/Lang/JavaScript/Draw-a-cuboid new file mode 120000 index 0000000000..44fc7b9f3d --- /dev/null +++ b/Lang/JavaScript/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Dutch-national-flag-problem b/Lang/JavaScript/Dutch-national-flag-problem new file mode 120000 index 0000000000..888be7c782 --- /dev/null +++ b/Lang/JavaScript/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/File-IO b/Lang/JavaScript/File-IO deleted file mode 120000 index 69bc1dbc43..0000000000 --- a/Lang/JavaScript/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Forward-difference b/Lang/JavaScript/Forward-difference new file mode 120000 index 0000000000..4f9c69e91d --- /dev/null +++ b/Lang/JavaScript/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Ludic-numbers b/Lang/JavaScript/Ludic-numbers new file mode 120000 index 0000000000..412cac2906 --- /dev/null +++ b/Lang/JavaScript/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Maximum-triangle-path-sum b/Lang/JavaScript/Maximum-triangle-path-sum new file mode 120000 index 0000000000..4c277120e8 --- /dev/null +++ b/Lang/JavaScript/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Maze-solving b/Lang/JavaScript/Maze-solving new file mode 120000 index 0000000000..238a20d3f7 --- /dev/null +++ b/Lang/JavaScript/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/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/N-queens-problem b/Lang/JavaScript/N-queens-problem new file mode 120000 index 0000000000..21956cdc97 --- /dev/null +++ b/Lang/JavaScript/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Pythagorean-triples b/Lang/JavaScript/Pythagorean-triples new file mode 120000 index 0000000000..9078717c46 --- /dev/null +++ b/Lang/JavaScript/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Quickselect-algorithm b/Lang/JavaScript/Quickselect-algorithm new file mode 120000 index 0000000000..d88f8453c4 --- /dev/null +++ b/Lang/JavaScript/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Ray-casting-algorithm b/Lang/JavaScript/Ray-casting-algorithm new file mode 120000 index 0000000000..028c970a5f --- /dev/null +++ b/Lang/JavaScript/Ray-casting-algorithm @@ -0,0 +1 @@ +../../Task/Ray-casting-algorithm/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Rep-string b/Lang/JavaScript/Rep-string new file mode 120000 index 0000000000..59fcfa5702 --- /dev/null +++ b/Lang/JavaScript/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Rosetta-Code-Fix-code-tags b/Lang/JavaScript/Rosetta-Code-Fix-code-tags deleted file mode 120000 index 3933b339df..0000000000 --- a/Lang/JavaScript/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sierpinski-triangle-Graphical b/Lang/JavaScript/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..3d6e799008 --- /dev/null +++ b/Lang/JavaScript/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Solve-a-Holy-Knights-tour b/Lang/JavaScript/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..a0b5b666d1 --- /dev/null +++ b/Lang/JavaScript/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Solve-the-no-connection-puzzle b/Lang/JavaScript/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..c377f38b33 --- /dev/null +++ b/Lang/JavaScript/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sorting-algorithms-Heapsort b/Lang/JavaScript/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..07c6964002 --- /dev/null +++ b/Lang/JavaScript/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Standard-deviation b/Lang/JavaScript/Standard-deviation deleted file mode 120000 index 6c2653a133..0000000000 --- a/Lang/JavaScript/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/String-prepend b/Lang/JavaScript/String-prepend new file mode 120000 index 0000000000..b7d164ddee --- /dev/null +++ b/Lang/JavaScript/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Strip-whitespace-from-a-string-Top-and-tail b/Lang/JavaScript/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..aa7eccbad0 --- /dev/null +++ b/Lang/JavaScript/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sudoku b/Lang/JavaScript/Sudoku new file mode 120000 index 0000000000..c039df021f --- /dev/null +++ b/Lang/JavaScript/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Topological-sort b/Lang/JavaScript/Topological-sort new file mode 120000 index 0000000000..b6ca15b0fb --- /dev/null +++ b/Lang/JavaScript/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Unix-ls b/Lang/JavaScript/Unix-ls new file mode 120000 index 0000000000..26594a2260 --- /dev/null +++ b/Lang/JavaScript/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Voronoi-diagram b/Lang/JavaScript/Voronoi-diagram new file mode 120000 index 0000000000..4c5ca15863 --- /dev/null +++ b/Lang/JavaScript/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Wireworld b/Lang/JavaScript/Wireworld new file mode 120000 index 0000000000..d108018184 --- /dev/null +++ b/Lang/JavaScript/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Zhang-Suen-thinning-algorithm b/Lang/JavaScript/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..3d1bcc4045 --- /dev/null +++ b/Lang/JavaScript/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/JavaScript \ No newline at end of file diff --git a/Lang/jq/00DESCRIPTION b/Lang/Jq/00DESCRIPTION similarity index 100% rename from Lang/jq/00DESCRIPTION rename to Lang/Jq/00DESCRIPTION diff --git a/Lang/Jq/100-doors b/Lang/Jq/100-doors new file mode 120000 index 0000000000..b2a5ce969b --- /dev/null +++ b/Lang/Jq/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Jq \ No newline at end of file diff --git a/Lang/Jq/24-game-Solve b/Lang/Jq/24-game-Solve new file mode 120000 index 0000000000..619d90924b --- /dev/null +++ b/Lang/Jq/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Jq \ No newline at end of file diff --git a/Lang/Jq/99-Bottles-of-Beer b/Lang/Jq/99-Bottles-of-Beer new file mode 120000 index 0000000000..af67e172f7 --- /dev/null +++ b/Lang/Jq/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Jq \ No newline at end of file diff --git a/Lang/Jq/A+B b/Lang/Jq/A+B new file mode 120000 index 0000000000..0b80348471 --- /dev/null +++ b/Lang/Jq/A+B @@ -0,0 +1 @@ +../../Task/A+B/Jq \ No newline at end of file diff --git a/Lang/Jq/ABC-Problem b/Lang/Jq/ABC-Problem new file mode 120000 index 0000000000..a487a70221 --- /dev/null +++ b/Lang/Jq/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Jq \ No newline at end of file diff --git a/Lang/Jq/AKS-test-for-primes b/Lang/Jq/AKS-test-for-primes new file mode 120000 index 0000000000..e37fac44e6 --- /dev/null +++ b/Lang/Jq/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Jq \ No newline at end of file diff --git a/Lang/Jq/Abundant,-deficient-and-perfect-number-classifications b/Lang/Jq/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..18dfc0a338 --- /dev/null +++ b/Lang/Jq/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Jq \ No newline at end of file diff --git a/Lang/Jq/Ackermann-function b/Lang/Jq/Ackermann-function new file mode 120000 index 0000000000..4bd13b7a01 --- /dev/null +++ b/Lang/Jq/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Jq \ No newline at end of file diff --git a/Lang/Jq/Add-a-variable-to-a-class-instance-at-runtime b/Lang/Jq/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..a69df9b8eb --- /dev/null +++ b/Lang/Jq/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/Jq \ No newline at end of file diff --git a/Lang/Jq/Align-columns b/Lang/Jq/Align-columns new file mode 120000 index 0000000000..3b390fa27e --- /dev/null +++ b/Lang/Jq/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Jq \ No newline at end of file diff --git a/Lang/Jq/Aliquot-sequence-classifications b/Lang/Jq/Aliquot-sequence-classifications new file mode 120000 index 0000000000..918be37093 --- /dev/null +++ b/Lang/Jq/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Jq \ No newline at end of file diff --git a/Lang/Jq/Almost-prime b/Lang/Jq/Almost-prime new file mode 120000 index 0000000000..ecadfd4dac --- /dev/null +++ b/Lang/Jq/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Jq \ No newline at end of file diff --git a/Lang/Jq/Amb b/Lang/Jq/Amb new file mode 120000 index 0000000000..8f31330f75 --- /dev/null +++ b/Lang/Jq/Amb @@ -0,0 +1 @@ +../../Task/Amb/Jq \ No newline at end of file diff --git a/Lang/Jq/Amicable-pairs b/Lang/Jq/Amicable-pairs new file mode 120000 index 0000000000..9b82a0c171 --- /dev/null +++ b/Lang/Jq/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Jq \ No newline at end of file diff --git a/Lang/Jq/Anagrams b/Lang/Jq/Anagrams new file mode 120000 index 0000000000..bc4729c039 --- /dev/null +++ b/Lang/Jq/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Jq \ No newline at end of file diff --git a/Lang/Jq/Anagrams-Deranged-anagrams b/Lang/Jq/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..e6620451c2 --- /dev/null +++ b/Lang/Jq/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/Jq \ No newline at end of file diff --git a/Lang/Jq/Anonymous-recursion b/Lang/Jq/Anonymous-recursion new file mode 120000 index 0000000000..2b49c12ad7 --- /dev/null +++ b/Lang/Jq/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Jq \ No newline at end of file diff --git a/Lang/Jq/Apply-a-callback-to-an-array b/Lang/Jq/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..b069c0cdd6 --- /dev/null +++ b/Lang/Jq/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Jq \ No newline at end of file diff --git a/Lang/Jq/Arithmetic-Complex b/Lang/Jq/Arithmetic-Complex new file mode 120000 index 0000000000..596942b03c --- /dev/null +++ b/Lang/Jq/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Jq \ No newline at end of file diff --git a/Lang/Jq/Arithmetic-Integer b/Lang/Jq/Arithmetic-Integer new file mode 120000 index 0000000000..a9fa2cf742 --- /dev/null +++ b/Lang/Jq/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Jq \ No newline at end of file diff --git a/Lang/Jq/Arithmetic-geometric-mean b/Lang/Jq/Arithmetic-geometric-mean new file mode 120000 index 0000000000..a3963771a0 --- /dev/null +++ b/Lang/Jq/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Jq \ No newline at end of file diff --git a/Lang/Jq/Array-concatenation b/Lang/Jq/Array-concatenation new file mode 120000 index 0000000000..d6c201beff --- /dev/null +++ b/Lang/Jq/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Jq \ No newline at end of file diff --git a/Lang/Jq/Arrays b/Lang/Jq/Arrays new file mode 120000 index 0000000000..86f65c0238 --- /dev/null +++ b/Lang/Jq/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Jq \ No newline at end of file diff --git a/Lang/Jq/Associative-array-Creation b/Lang/Jq/Associative-array-Creation new file mode 120000 index 0000000000..9d5e512d7f --- /dev/null +++ b/Lang/Jq/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Jq \ No newline at end of file diff --git a/Lang/Jq/Associative-array-Iteration b/Lang/Jq/Associative-array-Iteration new file mode 120000 index 0000000000..9e717f0afa --- /dev/null +++ b/Lang/Jq/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Jq \ No newline at end of file diff --git a/Lang/Jq/Averages-Arithmetic-mean b/Lang/Jq/Averages-Arithmetic-mean new file mode 120000 index 0000000000..87da14aadd --- /dev/null +++ b/Lang/Jq/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Jq \ No newline at end of file diff --git a/Lang/Jq/Averages-Mean-angle b/Lang/Jq/Averages-Mean-angle new file mode 120000 index 0000000000..95e92ec287 --- /dev/null +++ b/Lang/Jq/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Jq \ No newline at end of file diff --git a/Lang/Jq/Averages-Mean-time-of-day b/Lang/Jq/Averages-Mean-time-of-day new file mode 120000 index 0000000000..3738cf1f7c --- /dev/null +++ b/Lang/Jq/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Jq \ No newline at end of file diff --git a/Lang/Jq/Averages-Median b/Lang/Jq/Averages-Median new file mode 120000 index 0000000000..03c8c4539b --- /dev/null +++ b/Lang/Jq/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Jq \ No newline at end of file diff --git a/Lang/Jq/Averages-Mode b/Lang/Jq/Averages-Mode new file mode 120000 index 0000000000..67247ebdfd --- /dev/null +++ b/Lang/Jq/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Jq \ No newline at end of file diff --git a/Lang/Jq/Averages-Pythagorean-means b/Lang/Jq/Averages-Pythagorean-means new file mode 120000 index 0000000000..1fce8b61f2 --- /dev/null +++ b/Lang/Jq/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Jq \ No newline at end of file diff --git a/Lang/Jq/Averages-Root-mean-square b/Lang/Jq/Averages-Root-mean-square new file mode 120000 index 0000000000..b8999bcf79 --- /dev/null +++ b/Lang/Jq/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Jq \ No newline at end of file diff --git a/Lang/Jq/Benfords-law b/Lang/Jq/Benfords-law new file mode 120000 index 0000000000..3e280c3a88 --- /dev/null +++ b/Lang/Jq/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Jq \ No newline at end of file diff --git a/Lang/Jq/Bernoulli-numbers b/Lang/Jq/Bernoulli-numbers new file mode 120000 index 0000000000..869bf26d7d --- /dev/null +++ b/Lang/Jq/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Best-shuffle b/Lang/Jq/Best-shuffle new file mode 120000 index 0000000000..152b3b7828 --- /dev/null +++ b/Lang/Jq/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/Jq \ No newline at end of file diff --git a/Lang/Jq/Binary-digits b/Lang/Jq/Binary-digits new file mode 120000 index 0000000000..09f97a62ff --- /dev/null +++ b/Lang/Jq/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Jq \ No newline at end of file diff --git a/Lang/Jq/Binary-search b/Lang/Jq/Binary-search new file mode 120000 index 0000000000..62138548e1 --- /dev/null +++ b/Lang/Jq/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/Jq \ No newline at end of file diff --git a/Lang/Jq/Binary-strings b/Lang/Jq/Binary-strings new file mode 120000 index 0000000000..dc695fe771 --- /dev/null +++ b/Lang/Jq/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Jq \ No newline at end of file diff --git a/Lang/Jq/CSV-data-manipulation b/Lang/Jq/CSV-data-manipulation new file mode 120000 index 0000000000..dc6c7286d1 --- /dev/null +++ b/Lang/Jq/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Jq \ No newline at end of file diff --git a/Lang/Jq/CSV-to-HTML-translation b/Lang/Jq/CSV-to-HTML-translation new file mode 120000 index 0000000000..820444f9c3 --- /dev/null +++ b/Lang/Jq/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Jq \ No newline at end of file diff --git a/Lang/Jq/Case-sensitivity-of-identifiers b/Lang/Jq/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..840ed3b8ca --- /dev/null +++ b/Lang/Jq/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Jq \ No newline at end of file diff --git a/Lang/Jq/Casting-out-nines b/Lang/Jq/Casting-out-nines new file mode 120000 index 0000000000..d5df5d1d48 --- /dev/null +++ b/Lang/Jq/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Jq \ No newline at end of file diff --git a/Lang/Jq/Catalan-numbers b/Lang/Jq/Catalan-numbers new file mode 120000 index 0000000000..f9c9cad3b6 --- /dev/null +++ b/Lang/Jq/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Catalan-numbers-Pascals-triangle b/Lang/Jq/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..0e434f5382 --- /dev/null +++ b/Lang/Jq/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Jq \ No newline at end of file diff --git a/Lang/Jq/Character-codes b/Lang/Jq/Character-codes new file mode 120000 index 0000000000..626edd421e --- /dev/null +++ b/Lang/Jq/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Jq \ No newline at end of file diff --git a/Lang/Jq/Chinese-remainder-theorem b/Lang/Jq/Chinese-remainder-theorem new file mode 120000 index 0000000000..ea0c535a82 --- /dev/null +++ b/Lang/Jq/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Jq \ No newline at end of file diff --git a/Lang/Jq/Cholesky-decomposition b/Lang/Jq/Cholesky-decomposition new file mode 120000 index 0000000000..1cb759d0fa --- /dev/null +++ b/Lang/Jq/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Jq \ No newline at end of file diff --git a/Lang/Jq/Circles-of-given-radius-through-two-points b/Lang/Jq/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..fde8d89bf9 --- /dev/null +++ b/Lang/Jq/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Jq \ No newline at end of file diff --git a/Lang/Jq/Closest-pair-problem b/Lang/Jq/Closest-pair-problem new file mode 120000 index 0000000000..64fa9bc89b --- /dev/null +++ b/Lang/Jq/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/Jq \ No newline at end of file diff --git a/Lang/Jq/Collections b/Lang/Jq/Collections new file mode 120000 index 0000000000..bcc26fac25 --- /dev/null +++ b/Lang/Jq/Collections @@ -0,0 +1 @@ +../../Task/Collections/Jq \ No newline at end of file diff --git a/Lang/Jq/Combinations b/Lang/Jq/Combinations new file mode 120000 index 0000000000..010e37d766 --- /dev/null +++ b/Lang/Jq/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Jq \ No newline at end of file diff --git a/Lang/Jq/Combinations-and-permutations b/Lang/Jq/Combinations-and-permutations new file mode 120000 index 0000000000..5545d88c14 --- /dev/null +++ b/Lang/Jq/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Jq \ No newline at end of file diff --git a/Lang/Jq/Combinations-with-repetitions b/Lang/Jq/Combinations-with-repetitions new file mode 120000 index 0000000000..c1bd215a11 --- /dev/null +++ b/Lang/Jq/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Jq \ No newline at end of file diff --git a/Lang/Jq/Comma-quibbling b/Lang/Jq/Comma-quibbling new file mode 120000 index 0000000000..a18b7a0584 --- /dev/null +++ b/Lang/Jq/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Jq \ No newline at end of file diff --git a/Lang/Jq/Command-line-arguments b/Lang/Jq/Command-line-arguments new file mode 120000 index 0000000000..66eba61756 --- /dev/null +++ b/Lang/Jq/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/Jq \ No newline at end of file diff --git a/Lang/Jq/Comments b/Lang/Jq/Comments new file mode 120000 index 0000000000..51325fbd61 --- /dev/null +++ b/Lang/Jq/Comments @@ -0,0 +1 @@ +../../Task/Comments/Jq \ No newline at end of file diff --git a/Lang/Jq/Compound-data-type b/Lang/Jq/Compound-data-type new file mode 120000 index 0000000000..21c97dde37 --- /dev/null +++ b/Lang/Jq/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/Jq \ No newline at end of file diff --git a/Lang/Jq/Conditional-structures b/Lang/Jq/Conditional-structures new file mode 120000 index 0000000000..e7df927769 --- /dev/null +++ b/Lang/Jq/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Jq \ No newline at end of file diff --git a/Lang/Jq/Conjugate-transpose b/Lang/Jq/Conjugate-transpose new file mode 120000 index 0000000000..faa83c6043 --- /dev/null +++ b/Lang/Jq/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Jq \ No newline at end of file diff --git a/Lang/Jq/Continued-fraction b/Lang/Jq/Continued-fraction new file mode 120000 index 0000000000..11fc80c2bd --- /dev/null +++ b/Lang/Jq/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Jq \ No newline at end of file diff --git a/Lang/Jq/Conways-Game-of-Life b/Lang/Jq/Conways-Game-of-Life new file mode 120000 index 0000000000..b2d4020616 --- /dev/null +++ b/Lang/Jq/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Jq \ No newline at end of file diff --git a/Lang/Jq/Copy-a-string b/Lang/Jq/Copy-a-string new file mode 120000 index 0000000000..e86c3b5327 --- /dev/null +++ b/Lang/Jq/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Jq \ No newline at end of file diff --git a/Lang/Jq/Count-occurrences-of-a-substring b/Lang/Jq/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..966f90ce1f --- /dev/null +++ b/Lang/Jq/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Jq \ No newline at end of file diff --git a/Lang/Jq/Count-the-coins b/Lang/Jq/Count-the-coins new file mode 120000 index 0000000000..62ca850deb --- /dev/null +++ b/Lang/Jq/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Jq \ No newline at end of file diff --git a/Lang/Jq/Create-a-two-dimensional-array-at-runtime b/Lang/Jq/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..7649689579 --- /dev/null +++ b/Lang/Jq/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Jq \ No newline at end of file diff --git a/Lang/Jq/Create-an-HTML-table b/Lang/Jq/Create-an-HTML-table new file mode 120000 index 0000000000..0ddd8b497f --- /dev/null +++ b/Lang/Jq/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Jq \ No newline at end of file diff --git a/Lang/Jq/Currying b/Lang/Jq/Currying new file mode 120000 index 0000000000..3950af9533 --- /dev/null +++ b/Lang/Jq/Currying @@ -0,0 +1 @@ +../../Task/Currying/Jq \ No newline at end of file diff --git a/Lang/Jq/Date-format b/Lang/Jq/Date-format new file mode 120000 index 0000000000..b3afa1eb83 --- /dev/null +++ b/Lang/Jq/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Jq \ No newline at end of file diff --git a/Lang/Jq/Date-manipulation b/Lang/Jq/Date-manipulation new file mode 120000 index 0000000000..6365972920 --- /dev/null +++ b/Lang/Jq/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Jq \ No newline at end of file diff --git a/Lang/Jq/Day-of-the-week b/Lang/Jq/Day-of-the-week new file mode 120000 index 0000000000..5f5d0f15f2 --- /dev/null +++ b/Lang/Jq/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Jq \ No newline at end of file diff --git a/Lang/Jq/Define-a-primitive-data-type b/Lang/Jq/Define-a-primitive-data-type new file mode 120000 index 0000000000..67d6b9257a --- /dev/null +++ b/Lang/Jq/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/Jq \ No newline at end of file diff --git a/Lang/Jq/Detect-division-by-zero b/Lang/Jq/Detect-division-by-zero new file mode 120000 index 0000000000..89423cc892 --- /dev/null +++ b/Lang/Jq/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Jq \ No newline at end of file diff --git a/Lang/Jq/Determine-if-a-string-is-numeric b/Lang/Jq/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..2856ee9463 --- /dev/null +++ b/Lang/Jq/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Jq \ No newline at end of file diff --git a/Lang/Jq/Digital-root b/Lang/Jq/Digital-root new file mode 120000 index 0000000000..47053a5bc8 --- /dev/null +++ b/Lang/Jq/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Jq \ No newline at end of file diff --git a/Lang/Jq/Digital-root-Multiplicative-digital-root b/Lang/Jq/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..d588bcde90 --- /dev/null +++ b/Lang/Jq/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Jq \ No newline at end of file diff --git a/Lang/Jq/Dinesmans-multiple-dwelling-problem b/Lang/Jq/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..d1192829e0 --- /dev/null +++ b/Lang/Jq/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Jq \ No newline at end of file diff --git a/Lang/Jq/Dot-product b/Lang/Jq/Dot-product new file mode 120000 index 0000000000..fe697a9da1 --- /dev/null +++ b/Lang/Jq/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Jq \ No newline at end of file diff --git a/Lang/Jq/Dragon-curve b/Lang/Jq/Dragon-curve new file mode 120000 index 0000000000..b50eacce5d --- /dev/null +++ b/Lang/Jq/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Jq \ No newline at end of file diff --git a/Lang/Jq/Draw-a-sphere b/Lang/Jq/Draw-a-sphere new file mode 120000 index 0000000000..e3b66e24b4 --- /dev/null +++ b/Lang/Jq/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/Jq \ No newline at end of file diff --git a/Lang/Jq/Dynamic-variable-names b/Lang/Jq/Dynamic-variable-names new file mode 120000 index 0000000000..915fc27834 --- /dev/null +++ b/Lang/Jq/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Jq \ No newline at end of file diff --git a/Lang/Jq/Element-wise-operations b/Lang/Jq/Element-wise-operations new file mode 120000 index 0000000000..0f07f3a7a3 --- /dev/null +++ b/Lang/Jq/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Jq \ No newline at end of file diff --git a/Lang/Jq/Empty-program b/Lang/Jq/Empty-program new file mode 120000 index 0000000000..ae9682c4b5 --- /dev/null +++ b/Lang/Jq/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Jq \ No newline at end of file diff --git a/Lang/Jq/Empty-string b/Lang/Jq/Empty-string new file mode 120000 index 0000000000..11ebcea485 --- /dev/null +++ b/Lang/Jq/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Jq \ No newline at end of file diff --git a/Lang/Jq/Enforced-immutability b/Lang/Jq/Enforced-immutability new file mode 120000 index 0000000000..72ea5b112c --- /dev/null +++ b/Lang/Jq/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/Jq \ No newline at end of file diff --git a/Lang/Jq/Entropy b/Lang/Jq/Entropy new file mode 120000 index 0000000000..3915f25afa --- /dev/null +++ b/Lang/Jq/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Jq \ No newline at end of file diff --git a/Lang/Jq/Environment-variables b/Lang/Jq/Environment-variables new file mode 120000 index 0000000000..a61915323d --- /dev/null +++ b/Lang/Jq/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Jq \ No newline at end of file diff --git a/Lang/Jq/Equilibrium-index b/Lang/Jq/Equilibrium-index new file mode 120000 index 0000000000..b27855531f --- /dev/null +++ b/Lang/Jq/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Jq \ No newline at end of file diff --git a/Lang/Jq/Euler-method b/Lang/Jq/Euler-method new file mode 120000 index 0000000000..1c4fa6856d --- /dev/null +++ b/Lang/Jq/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Jq \ No newline at end of file diff --git a/Lang/Jq/Evaluate-binomial-coefficients b/Lang/Jq/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..4592dfdff7 --- /dev/null +++ b/Lang/Jq/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Jq \ No newline at end of file diff --git a/Lang/Jq/Even-or-odd b/Lang/Jq/Even-or-odd new file mode 120000 index 0000000000..60191c336b --- /dev/null +++ b/Lang/Jq/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Jq \ No newline at end of file diff --git a/Lang/Jq/Exceptions b/Lang/Jq/Exceptions new file mode 120000 index 0000000000..10ad5274ed --- /dev/null +++ b/Lang/Jq/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Jq \ No newline at end of file diff --git a/Lang/Jq/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Jq/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..c130077d8a --- /dev/null +++ b/Lang/Jq/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Jq \ No newline at end of file diff --git a/Lang/Jq/Exponentiation-operator b/Lang/Jq/Exponentiation-operator new file mode 120000 index 0000000000..964dc893e1 --- /dev/null +++ b/Lang/Jq/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Jq \ No newline at end of file diff --git a/Lang/Jq/Extensible-prime-generator b/Lang/Jq/Extensible-prime-generator new file mode 120000 index 0000000000..5830fee3bb --- /dev/null +++ b/Lang/Jq/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Jq \ No newline at end of file diff --git a/Lang/Jq/Extreme-floating-point-values b/Lang/Jq/Extreme-floating-point-values new file mode 120000 index 0000000000..782f2c759e --- /dev/null +++ b/Lang/Jq/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Jq \ No newline at end of file diff --git a/Lang/Jq/Factorial b/Lang/Jq/Factorial new file mode 120000 index 0000000000..147f222b20 --- /dev/null +++ b/Lang/Jq/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Jq \ No newline at end of file diff --git a/Lang/Jq/Factors-of-an-integer b/Lang/Jq/Factors-of-an-integer new file mode 120000 index 0000000000..aa40faa1f0 --- /dev/null +++ b/Lang/Jq/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Jq \ No newline at end of file diff --git a/Lang/Jq/Fast-Fourier-transform b/Lang/Jq/Fast-Fourier-transform new file mode 120000 index 0000000000..001ab63f24 --- /dev/null +++ b/Lang/Jq/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Jq \ No newline at end of file diff --git a/Lang/Jq/Fibonacci-n-step-number-sequences b/Lang/Jq/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..593043db0b --- /dev/null +++ b/Lang/Jq/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Jq \ No newline at end of file diff --git a/Lang/Jq/Fibonacci-sequence b/Lang/Jq/Fibonacci-sequence new file mode 120000 index 0000000000..d995423095 --- /dev/null +++ b/Lang/Jq/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Jq \ No newline at end of file diff --git a/Lang/Jq/Fibonacci-word b/Lang/Jq/Fibonacci-word new file mode 120000 index 0000000000..fa1a16e54f --- /dev/null +++ b/Lang/Jq/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Jq \ No newline at end of file diff --git a/Lang/Jq/File-input-output b/Lang/Jq/File-input-output new file mode 120000 index 0000000000..a616f0d2b9 --- /dev/null +++ b/Lang/Jq/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Jq \ No newline at end of file diff --git a/Lang/Jq/File-size b/Lang/Jq/File-size new file mode 120000 index 0000000000..b0f6a134b3 --- /dev/null +++ b/Lang/Jq/File-size @@ -0,0 +1 @@ +../../Task/File-size/Jq \ No newline at end of file diff --git a/Lang/Jq/Filter b/Lang/Jq/Filter new file mode 120000 index 0000000000..798139f569 --- /dev/null +++ b/Lang/Jq/Filter @@ -0,0 +1 @@ +../../Task/Filter/Jq \ No newline at end of file diff --git a/Lang/Jq/Find-common-directory-path b/Lang/Jq/Find-common-directory-path new file mode 120000 index 0000000000..a2fbbcc56b --- /dev/null +++ b/Lang/Jq/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Jq \ No newline at end of file diff --git a/Lang/Jq/Find-limit-of-recursion b/Lang/Jq/Find-limit-of-recursion new file mode 120000 index 0000000000..1844852374 --- /dev/null +++ b/Lang/Jq/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/Jq \ No newline at end of file diff --git a/Lang/Jq/Find-the-last-Sunday-of-each-month b/Lang/Jq/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..0d6524ad5d --- /dev/null +++ b/Lang/Jq/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Jq \ No newline at end of file diff --git a/Lang/Jq/Find-the-missing-permutation b/Lang/Jq/Find-the-missing-permutation new file mode 120000 index 0000000000..3fec087563 --- /dev/null +++ b/Lang/Jq/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Jq \ No newline at end of file diff --git a/Lang/Jq/First-class-environments b/Lang/Jq/First-class-environments new file mode 120000 index 0000000000..925c044c37 --- /dev/null +++ b/Lang/Jq/First-class-environments @@ -0,0 +1 @@ +../../Task/First-class-environments/Jq \ No newline at end of file diff --git a/Lang/Jq/First-class-functions-Use-numbers-analogously b/Lang/Jq/First-class-functions-Use-numbers-analogously new file mode 120000 index 0000000000..67d2b28a09 --- /dev/null +++ b/Lang/Jq/First-class-functions-Use-numbers-analogously @@ -0,0 +1 @@ +../../Task/First-class-functions-Use-numbers-analogously/Jq \ No newline at end of file diff --git a/Lang/Jq/Five-weekends b/Lang/Jq/Five-weekends new file mode 120000 index 0000000000..40063f96e7 --- /dev/null +++ b/Lang/Jq/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Jq \ No newline at end of file diff --git a/Lang/Jq/FizzBuzz b/Lang/Jq/FizzBuzz new file mode 120000 index 0000000000..f9649a7f20 --- /dev/null +++ b/Lang/Jq/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Jq \ No newline at end of file diff --git a/Lang/Jq/Flatten-a-list b/Lang/Jq/Flatten-a-list new file mode 120000 index 0000000000..4de116062d --- /dev/null +++ b/Lang/Jq/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Jq \ No newline at end of file diff --git a/Lang/Jq/Flow-control-structures b/Lang/Jq/Flow-control-structures new file mode 120000 index 0000000000..fab4aa7956 --- /dev/null +++ b/Lang/Jq/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/Jq \ No newline at end of file diff --git a/Lang/Jq/Floyds-triangle b/Lang/Jq/Floyds-triangle new file mode 120000 index 0000000000..9d0ec0d659 --- /dev/null +++ b/Lang/Jq/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Jq \ No newline at end of file diff --git a/Lang/Jq/Formal-power-series b/Lang/Jq/Formal-power-series new file mode 120000 index 0000000000..792cf40d8e --- /dev/null +++ b/Lang/Jq/Formal-power-series @@ -0,0 +1 @@ +../../Task/Formal-power-series/Jq \ No newline at end of file diff --git a/Lang/Jq/Formatted-numeric-output b/Lang/Jq/Formatted-numeric-output new file mode 120000 index 0000000000..26c77e45fe --- /dev/null +++ b/Lang/Jq/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Jq \ No newline at end of file diff --git a/Lang/Jq/Forward-difference b/Lang/Jq/Forward-difference new file mode 120000 index 0000000000..7de1721f4b --- /dev/null +++ b/Lang/Jq/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/Jq \ No newline at end of file diff --git a/Lang/Jq/Four-bit-adder b/Lang/Jq/Four-bit-adder new file mode 120000 index 0000000000..ebf6404011 --- /dev/null +++ b/Lang/Jq/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Jq \ No newline at end of file diff --git a/Lang/Jq/Fractal-tree b/Lang/Jq/Fractal-tree new file mode 120000 index 0000000000..c7722abbd9 --- /dev/null +++ b/Lang/Jq/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Jq \ No newline at end of file diff --git a/Lang/Jq/Function-composition b/Lang/Jq/Function-composition new file mode 120000 index 0000000000..5b5f5e61f3 --- /dev/null +++ b/Lang/Jq/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Jq \ No newline at end of file diff --git a/Lang/Jq/Function-definition b/Lang/Jq/Function-definition new file mode 120000 index 0000000000..fef92b8afb --- /dev/null +++ b/Lang/Jq/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Jq \ No newline at end of file diff --git a/Lang/Jq/Gamma-function b/Lang/Jq/Gamma-function new file mode 120000 index 0000000000..a57806b8f5 --- /dev/null +++ b/Lang/Jq/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Jq \ No newline at end of file diff --git a/Lang/Jq/Generate-lower-case-ASCII-alphabet b/Lang/Jq/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..5210c6874b --- /dev/null +++ b/Lang/Jq/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Jq \ No newline at end of file diff --git a/Lang/Jq/Generator-Exponential b/Lang/Jq/Generator-Exponential new file mode 120000 index 0000000000..d8ce6f89de --- /dev/null +++ b/Lang/Jq/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/Jq \ No newline at end of file diff --git a/Lang/Jq/Generic-swap b/Lang/Jq/Generic-swap new file mode 120000 index 0000000000..b9ab5ddf4a --- /dev/null +++ b/Lang/Jq/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Jq \ No newline at end of file diff --git a/Lang/Jq/Globally-replace-text-in-several-files b/Lang/Jq/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..c3c584ec0b --- /dev/null +++ b/Lang/Jq/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Jq \ No newline at end of file diff --git a/Lang/Jq/Greatest-common-divisor b/Lang/Jq/Greatest-common-divisor new file mode 120000 index 0000000000..5db0ee2e5b --- /dev/null +++ b/Lang/Jq/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Jq \ No newline at end of file diff --git a/Lang/Jq/Greatest-element-of-a-list b/Lang/Jq/Greatest-element-of-a-list new file mode 120000 index 0000000000..92fcb62dcd --- /dev/null +++ b/Lang/Jq/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Jq \ No newline at end of file diff --git a/Lang/Jq/Greatest-subsequential-sum b/Lang/Jq/Greatest-subsequential-sum new file mode 120000 index 0000000000..23d67be9d6 --- /dev/null +++ b/Lang/Jq/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/Jq \ No newline at end of file diff --git a/Lang/Jq/Guess-the-number b/Lang/Jq/Guess-the-number new file mode 120000 index 0000000000..2366b11c69 --- /dev/null +++ b/Lang/Jq/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Jq \ No newline at end of file diff --git a/Lang/Jq/Hailstone-sequence b/Lang/Jq/Hailstone-sequence new file mode 120000 index 0000000000..d8cdf3fa91 --- /dev/null +++ b/Lang/Jq/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Jq \ No newline at end of file diff --git a/Lang/Jq/Hamming-numbers b/Lang/Jq/Hamming-numbers new file mode 120000 index 0000000000..2367dee31c --- /dev/null +++ b/Lang/Jq/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Happy-numbers b/Lang/Jq/Happy-numbers new file mode 120000 index 0000000000..367beb80ea --- /dev/null +++ b/Lang/Jq/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Harshad-or-Niven-series b/Lang/Jq/Harshad-or-Niven-series new file mode 120000 index 0000000000..604e22e0b2 --- /dev/null +++ b/Lang/Jq/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Jq \ No newline at end of file diff --git a/Lang/Jq/Hash-from-two-arrays b/Lang/Jq/Hash-from-two-arrays new file mode 120000 index 0000000000..cbaab6ea86 --- /dev/null +++ b/Lang/Jq/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Jq \ No newline at end of file diff --git a/Lang/Jq/Hash-join b/Lang/Jq/Hash-join new file mode 120000 index 0000000000..3d788cbb56 --- /dev/null +++ b/Lang/Jq/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Jq \ No newline at end of file diff --git a/Lang/Jq/Haversine-formula b/Lang/Jq/Haversine-formula new file mode 120000 index 0000000000..fe36130515 --- /dev/null +++ b/Lang/Jq/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Jq \ No newline at end of file diff --git a/Lang/Jq/Hello-world-Graphical b/Lang/Jq/Hello-world-Graphical new file mode 120000 index 0000000000..72c1bbe8af --- /dev/null +++ b/Lang/Jq/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Jq \ No newline at end of file diff --git a/Lang/Jq/Hello-world-Newbie b/Lang/Jq/Hello-world-Newbie new file mode 120000 index 0000000000..404cd7db2b --- /dev/null +++ b/Lang/Jq/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Jq \ No newline at end of file diff --git a/Lang/Jq/Hello-world-Newline-omission b/Lang/Jq/Hello-world-Newline-omission new file mode 120000 index 0000000000..40f9fc3d1b --- /dev/null +++ b/Lang/Jq/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Jq \ No newline at end of file diff --git a/Lang/Jq/Hello-world-Standard-error b/Lang/Jq/Hello-world-Standard-error new file mode 120000 index 0000000000..7449dcac57 --- /dev/null +++ b/Lang/Jq/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Jq \ No newline at end of file diff --git a/Lang/Jq/Hello-world-Text b/Lang/Jq/Hello-world-Text new file mode 120000 index 0000000000..57a770fcce --- /dev/null +++ b/Lang/Jq/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Jq \ No newline at end of file diff --git a/Lang/Jq/Here-document b/Lang/Jq/Here-document new file mode 120000 index 0000000000..932786b547 --- /dev/null +++ b/Lang/Jq/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Jq \ No newline at end of file diff --git a/Lang/Jq/Heronian-triangles b/Lang/Jq/Heronian-triangles new file mode 120000 index 0000000000..c73dec6b74 --- /dev/null +++ b/Lang/Jq/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/Jq \ No newline at end of file diff --git a/Lang/Jq/Hickerson-series-of-almost-integers b/Lang/Jq/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..455a3b9e43 --- /dev/null +++ b/Lang/Jq/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Jq \ No newline at end of file diff --git a/Lang/Jq/Higher-order-functions b/Lang/Jq/Higher-order-functions new file mode 120000 index 0000000000..e334438034 --- /dev/null +++ b/Lang/Jq/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Jq \ No newline at end of file diff --git a/Lang/Jq/Hofstadter-Q-sequence b/Lang/Jq/Hofstadter-Q-sequence new file mode 120000 index 0000000000..83e48c6909 --- /dev/null +++ b/Lang/Jq/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/Jq \ No newline at end of file diff --git a/Lang/Jq/I-before-E-except-after-C b/Lang/Jq/I-before-E-except-after-C new file mode 120000 index 0000000000..fb635996c9 --- /dev/null +++ b/Lang/Jq/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Jq \ No newline at end of file diff --git a/Lang/Jq/IBAN b/Lang/Jq/IBAN new file mode 120000 index 0000000000..f56e135507 --- /dev/null +++ b/Lang/Jq/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Jq \ No newline at end of file diff --git a/Lang/Jq/Identity-matrix b/Lang/Jq/Identity-matrix new file mode 120000 index 0000000000..2226e17e6d --- /dev/null +++ b/Lang/Jq/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Jq \ No newline at end of file diff --git a/Lang/Jq/Include-a-file b/Lang/Jq/Include-a-file new file mode 120000 index 0000000000..f23b009570 --- /dev/null +++ b/Lang/Jq/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Jq \ No newline at end of file diff --git a/Lang/Jq/Increment-a-numerical-string b/Lang/Jq/Increment-a-numerical-string new file mode 120000 index 0000000000..bd2a1d851f --- /dev/null +++ b/Lang/Jq/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Jq \ No newline at end of file diff --git a/Lang/Jq/Infinity b/Lang/Jq/Infinity new file mode 120000 index 0000000000..3929b9cd11 --- /dev/null +++ b/Lang/Jq/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/Jq \ No newline at end of file diff --git a/Lang/Jq/Input-loop b/Lang/Jq/Input-loop new file mode 120000 index 0000000000..fcfdd911e8 --- /dev/null +++ b/Lang/Jq/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Jq \ No newline at end of file diff --git a/Lang/Jq/Integer-comparison b/Lang/Jq/Integer-comparison new file mode 120000 index 0000000000..6b04913a0b --- /dev/null +++ b/Lang/Jq/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Jq \ No newline at end of file diff --git a/Lang/Jq/Integer-sequence b/Lang/Jq/Integer-sequence new file mode 120000 index 0000000000..277eb1aee3 --- /dev/null +++ b/Lang/Jq/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Jq \ No newline at end of file diff --git a/Lang/Jq/Inverted-index b/Lang/Jq/Inverted-index new file mode 120000 index 0000000000..be8e76dbee --- /dev/null +++ b/Lang/Jq/Inverted-index @@ -0,0 +1 @@ +../../Task/Inverted-index/Jq \ No newline at end of file diff --git a/Lang/Jq/Inverted-syntax b/Lang/Jq/Inverted-syntax new file mode 120000 index 0000000000..2e2e531bfd --- /dev/null +++ b/Lang/Jq/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/Jq \ No newline at end of file diff --git a/Lang/Jq/Iterated-digits-squaring b/Lang/Jq/Iterated-digits-squaring new file mode 120000 index 0000000000..432637ce15 --- /dev/null +++ b/Lang/Jq/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Jq \ No newline at end of file diff --git a/Lang/Jq/JSON b/Lang/Jq/JSON new file mode 120000 index 0000000000..9fd596a434 --- /dev/null +++ b/Lang/Jq/JSON @@ -0,0 +1 @@ +../../Task/JSON/Jq \ No newline at end of file diff --git a/Lang/Jq/Jensens-Device b/Lang/Jq/Jensens-Device new file mode 120000 index 0000000000..9e069cd2b4 --- /dev/null +++ b/Lang/Jq/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Jq \ No newline at end of file diff --git a/Lang/Jq/Josephus-problem b/Lang/Jq/Josephus-problem new file mode 120000 index 0000000000..d7773f4794 --- /dev/null +++ b/Lang/Jq/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Jq \ No newline at end of file diff --git a/Lang/Jq/Jump-anywhere b/Lang/Jq/Jump-anywhere new file mode 120000 index 0000000000..334698f9b0 --- /dev/null +++ b/Lang/Jq/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/Jq \ No newline at end of file diff --git a/Lang/Jq/Kaprekar-numbers b/Lang/Jq/Kaprekar-numbers new file mode 120000 index 0000000000..dd40c00c61 --- /dev/null +++ b/Lang/Jq/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Knapsack-problem-0-1 b/Lang/Jq/Knapsack-problem-0-1 new file mode 120000 index 0000000000..ff2be1c3de --- /dev/null +++ b/Lang/Jq/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Jq \ No newline at end of file diff --git a/Lang/Jq/Knapsack-problem-Continuous b/Lang/Jq/Knapsack-problem-Continuous new file mode 120000 index 0000000000..1cb50e1fd5 --- /dev/null +++ b/Lang/Jq/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Jq \ No newline at end of file diff --git a/Lang/Jq/LU-decomposition b/Lang/Jq/LU-decomposition new file mode 120000 index 0000000000..2383b691f8 --- /dev/null +++ b/Lang/Jq/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/Jq \ No newline at end of file diff --git a/Lang/Jq/LZW-compression b/Lang/Jq/LZW-compression new file mode 120000 index 0000000000..6fb0d6e618 --- /dev/null +++ b/Lang/Jq/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Jq \ No newline at end of file diff --git a/Lang/Jq/Langtons-ant b/Lang/Jq/Langtons-ant new file mode 120000 index 0000000000..2f5084ca80 --- /dev/null +++ b/Lang/Jq/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Jq \ No newline at end of file diff --git a/Lang/Jq/Largest-int-from-concatenated-ints b/Lang/Jq/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..2b1029d221 --- /dev/null +++ b/Lang/Jq/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Jq \ No newline at end of file diff --git a/Lang/Jq/Last-Friday-of-each-month b/Lang/Jq/Last-Friday-of-each-month new file mode 120000 index 0000000000..6c58484f41 --- /dev/null +++ b/Lang/Jq/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Jq \ No newline at end of file diff --git a/Lang/Jq/Last-letter-first-letter b/Lang/Jq/Last-letter-first-letter new file mode 120000 index 0000000000..74a39b0bb6 --- /dev/null +++ b/Lang/Jq/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Jq \ No newline at end of file diff --git a/Lang/Jq/Leap-year b/Lang/Jq/Leap-year new file mode 120000 index 0000000000..bd63828168 --- /dev/null +++ b/Lang/Jq/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Jq \ No newline at end of file diff --git a/Lang/Jq/Least-common-multiple b/Lang/Jq/Least-common-multiple new file mode 120000 index 0000000000..eb9120a113 --- /dev/null +++ b/Lang/Jq/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Jq \ No newline at end of file diff --git a/Lang/Jq/Left-factorials b/Lang/Jq/Left-factorials new file mode 120000 index 0000000000..eaab974428 --- /dev/null +++ b/Lang/Jq/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Jq \ No newline at end of file diff --git a/Lang/Jq/Letter-frequency b/Lang/Jq/Letter-frequency new file mode 120000 index 0000000000..5e7281b589 --- /dev/null +++ b/Lang/Jq/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Jq \ No newline at end of file diff --git a/Lang/Jq/Levenshtein-distance b/Lang/Jq/Levenshtein-distance new file mode 120000 index 0000000000..d81589338c --- /dev/null +++ b/Lang/Jq/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Jq \ No newline at end of file diff --git a/Lang/Jq/Linear-congruential-generator b/Lang/Jq/Linear-congruential-generator new file mode 120000 index 0000000000..50df968d41 --- /dev/null +++ b/Lang/Jq/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/Jq \ No newline at end of file diff --git a/Lang/Jq/List-comprehensions b/Lang/Jq/List-comprehensions new file mode 120000 index 0000000000..e30b52ee11 --- /dev/null +++ b/Lang/Jq/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Jq \ No newline at end of file diff --git a/Lang/Jq/Literals-Floating-point b/Lang/Jq/Literals-Floating-point new file mode 120000 index 0000000000..8a398f8188 --- /dev/null +++ b/Lang/Jq/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Jq \ No newline at end of file diff --git a/Lang/Jq/Logical-operations b/Lang/Jq/Logical-operations new file mode 120000 index 0000000000..475b0a2e22 --- /dev/null +++ b/Lang/Jq/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Jq \ No newline at end of file diff --git a/Lang/Jq/Long-multiplication b/Lang/Jq/Long-multiplication new file mode 120000 index 0000000000..c3aecdf799 --- /dev/null +++ b/Lang/Jq/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/Jq \ No newline at end of file diff --git a/Lang/Jq/Longest-common-subsequence b/Lang/Jq/Longest-common-subsequence new file mode 120000 index 0000000000..39fab837b1 --- /dev/null +++ b/Lang/Jq/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/Jq \ No newline at end of file diff --git a/Lang/Jq/Longest-increasing-subsequence b/Lang/Jq/Longest-increasing-subsequence new file mode 120000 index 0000000000..6b6eebcf96 --- /dev/null +++ b/Lang/Jq/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Jq \ No newline at end of file diff --git a/Lang/Jq/Look-and-say-sequence b/Lang/Jq/Look-and-say-sequence new file mode 120000 index 0000000000..ca24e16a58 --- /dev/null +++ b/Lang/Jq/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Jq \ No newline at end of file diff --git a/Lang/Jq/Loop-over-multiple-arrays-simultaneously b/Lang/Jq/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..d6c4c22d50 --- /dev/null +++ b/Lang/Jq/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Jq \ No newline at end of file diff --git a/Lang/Jq/Loops-Break b/Lang/Jq/Loops-Break new file mode 120000 index 0000000000..9f3d608b1b --- /dev/null +++ b/Lang/Jq/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Jq \ No newline at end of file diff --git a/Lang/Jq/Loops-Continue b/Lang/Jq/Loops-Continue new file mode 120000 index 0000000000..e321c7ca1e --- /dev/null +++ b/Lang/Jq/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Jq \ No newline at end of file diff --git a/Lang/Jq/Loops-Do-while b/Lang/Jq/Loops-Do-while new file mode 120000 index 0000000000..70d71bf202 --- /dev/null +++ b/Lang/Jq/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Jq \ No newline at end of file diff --git a/Lang/Jq/Loops-Downward-for b/Lang/Jq/Loops-Downward-for new file mode 120000 index 0000000000..264f57c2a1 --- /dev/null +++ b/Lang/Jq/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Jq \ No newline at end of file diff --git a/Lang/Jq/Loops-For b/Lang/Jq/Loops-For new file mode 120000 index 0000000000..c58c2f7dcb --- /dev/null +++ b/Lang/Jq/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Jq \ No newline at end of file diff --git a/Lang/Jq/Loops-For-with-a-specified-step b/Lang/Jq/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..55cda6dc06 --- /dev/null +++ b/Lang/Jq/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Jq \ No newline at end of file diff --git a/Lang/Jq/Loops-Foreach b/Lang/Jq/Loops-Foreach new file mode 120000 index 0000000000..d267b32f53 --- /dev/null +++ b/Lang/Jq/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Jq \ No newline at end of file diff --git a/Lang/Jq/Loops-Infinite b/Lang/Jq/Loops-Infinite new file mode 120000 index 0000000000..62c2c5f44a --- /dev/null +++ b/Lang/Jq/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Jq \ No newline at end of file diff --git a/Lang/Jq/Loops-N-plus-one-half b/Lang/Jq/Loops-N-plus-one-half new file mode 120000 index 0000000000..c3ac2c23d7 --- /dev/null +++ b/Lang/Jq/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Jq \ No newline at end of file diff --git a/Lang/Jq/Loops-Nested b/Lang/Jq/Loops-Nested new file mode 120000 index 0000000000..848bef00c1 --- /dev/null +++ b/Lang/Jq/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Jq \ No newline at end of file diff --git a/Lang/Jq/Loops-While b/Lang/Jq/Loops-While new file mode 120000 index 0000000000..61fe26990b --- /dev/null +++ b/Lang/Jq/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Jq \ No newline at end of file diff --git a/Lang/Jq/Luhn-test-of-credit-card-numbers b/Lang/Jq/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..6aa250bba8 --- /dev/null +++ b/Lang/Jq/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Magic-squares-of-odd-order b/Lang/Jq/Magic-squares-of-odd-order new file mode 120000 index 0000000000..74238b96db --- /dev/null +++ b/Lang/Jq/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Jq \ No newline at end of file diff --git a/Lang/Jq/Mandelbrot-set b/Lang/Jq/Mandelbrot-set new file mode 120000 index 0000000000..6628584904 --- /dev/null +++ b/Lang/Jq/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Jq \ No newline at end of file diff --git a/Lang/Jq/Map-range b/Lang/Jq/Map-range new file mode 120000 index 0000000000..9a77934731 --- /dev/null +++ b/Lang/Jq/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Jq \ No newline at end of file diff --git a/Lang/Jq/Matrix-arithmetic b/Lang/Jq/Matrix-arithmetic new file mode 120000 index 0000000000..841fc8ffaa --- /dev/null +++ b/Lang/Jq/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Jq \ No newline at end of file diff --git a/Lang/Jq/Matrix-exponentiation-operator b/Lang/Jq/Matrix-exponentiation-operator new file mode 120000 index 0000000000..bfbeb5b80e --- /dev/null +++ b/Lang/Jq/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/Jq \ No newline at end of file diff --git a/Lang/Jq/Matrix-multiplication b/Lang/Jq/Matrix-multiplication new file mode 120000 index 0000000000..7c02478b35 --- /dev/null +++ b/Lang/Jq/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Jq \ No newline at end of file diff --git a/Lang/Jq/Matrix-transposition b/Lang/Jq/Matrix-transposition new file mode 120000 index 0000000000..0d641bebdc --- /dev/null +++ b/Lang/Jq/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/Jq \ No newline at end of file diff --git a/Lang/Jq/Maximum-triangle-path-sum b/Lang/Jq/Maximum-triangle-path-sum new file mode 120000 index 0000000000..a1d7313fee --- /dev/null +++ b/Lang/Jq/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Jq \ No newline at end of file diff --git a/Lang/Jq/Menu b/Lang/Jq/Menu new file mode 120000 index 0000000000..c531c4e4f3 --- /dev/null +++ b/Lang/Jq/Menu @@ -0,0 +1 @@ +../../Task/Menu/Jq \ No newline at end of file diff --git a/Lang/Jq/Middle-three-digits b/Lang/Jq/Middle-three-digits new file mode 120000 index 0000000000..c88c725d5e --- /dev/null +++ b/Lang/Jq/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Jq \ No newline at end of file diff --git a/Lang/Jq/Move-to-front-algorithm b/Lang/Jq/Move-to-front-algorithm new file mode 120000 index 0000000000..ceb64c1ab8 --- /dev/null +++ b/Lang/Jq/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Jq \ No newline at end of file diff --git a/Lang/Jq/Multifactorial b/Lang/Jq/Multifactorial new file mode 120000 index 0000000000..f42881bb2a --- /dev/null +++ b/Lang/Jq/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Jq \ No newline at end of file diff --git a/Lang/Jq/Multiple-distinct-objects b/Lang/Jq/Multiple-distinct-objects new file mode 120000 index 0000000000..79c81c7c7a --- /dev/null +++ b/Lang/Jq/Multiple-distinct-objects @@ -0,0 +1 @@ +../../Task/Multiple-distinct-objects/Jq \ No newline at end of file diff --git a/Lang/Jq/Multisplit b/Lang/Jq/Multisplit new file mode 120000 index 0000000000..9cad10370f --- /dev/null +++ b/Lang/Jq/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/Jq \ No newline at end of file diff --git a/Lang/Jq/Munching-squares b/Lang/Jq/Munching-squares new file mode 120000 index 0000000000..2e7ff129a6 --- /dev/null +++ b/Lang/Jq/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Jq \ No newline at end of file diff --git a/Lang/Jq/Mutual-recursion b/Lang/Jq/Mutual-recursion new file mode 120000 index 0000000000..8c5ddfbf2f --- /dev/null +++ b/Lang/Jq/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Jq \ No newline at end of file diff --git a/Lang/Jq/N-queens-problem b/Lang/Jq/N-queens-problem new file mode 120000 index 0000000000..e46089ab54 --- /dev/null +++ b/Lang/Jq/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Jq \ No newline at end of file diff --git a/Lang/Jq/Named-parameters b/Lang/Jq/Named-parameters new file mode 120000 index 0000000000..5ee5e27d3d --- /dev/null +++ b/Lang/Jq/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/Jq \ No newline at end of file diff --git a/Lang/Jq/Narcissistic-decimal-number b/Lang/Jq/Narcissistic-decimal-number new file mode 120000 index 0000000000..74d65c6963 --- /dev/null +++ b/Lang/Jq/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Jq \ No newline at end of file diff --git a/Lang/Jq/Natural-sorting b/Lang/Jq/Natural-sorting new file mode 120000 index 0000000000..b043c8aa86 --- /dev/null +++ b/Lang/Jq/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Jq \ No newline at end of file diff --git a/Lang/Jq/Non-continuous-subsequences b/Lang/Jq/Non-continuous-subsequences new file mode 120000 index 0000000000..96a410c77a --- /dev/null +++ b/Lang/Jq/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/Jq \ No newline at end of file diff --git a/Lang/Jq/Non-decimal-radices-Convert b/Lang/Jq/Non-decimal-radices-Convert new file mode 120000 index 0000000000..eed2254c48 --- /dev/null +++ b/Lang/Jq/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Jq \ No newline at end of file diff --git a/Lang/Jq/Nth b/Lang/Jq/Nth new file mode 120000 index 0000000000..1a74ef6562 --- /dev/null +++ b/Lang/Jq/Nth @@ -0,0 +1 @@ +../../Task/Nth/Jq \ No newline at end of file diff --git a/Lang/Jq/Nth-root b/Lang/Jq/Nth-root new file mode 120000 index 0000000000..9301cc9437 --- /dev/null +++ b/Lang/Jq/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/Jq \ No newline at end of file diff --git a/Lang/Jq/Null-object b/Lang/Jq/Null-object new file mode 120000 index 0000000000..e75fa9ade7 --- /dev/null +++ b/Lang/Jq/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/Jq \ No newline at end of file diff --git a/Lang/Jq/Number-names b/Lang/Jq/Number-names new file mode 120000 index 0000000000..cdd0719c75 --- /dev/null +++ b/Lang/Jq/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Jq \ No newline at end of file diff --git a/Lang/Jq/Number-reversal-game b/Lang/Jq/Number-reversal-game new file mode 120000 index 0000000000..6b38c519c4 --- /dev/null +++ b/Lang/Jq/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Jq \ No newline at end of file diff --git a/Lang/Jq/One-dimensional-cellular-automata b/Lang/Jq/One-dimensional-cellular-automata new file mode 120000 index 0000000000..b6376160d2 --- /dev/null +++ b/Lang/Jq/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Jq \ No newline at end of file diff --git a/Lang/Jq/Optional-parameters b/Lang/Jq/Optional-parameters new file mode 120000 index 0000000000..16c46c7c56 --- /dev/null +++ b/Lang/Jq/Optional-parameters @@ -0,0 +1 @@ +../../Task/Optional-parameters/Jq \ No newline at end of file diff --git a/Lang/Jq/Order-disjoint-list-items b/Lang/Jq/Order-disjoint-list-items new file mode 120000 index 0000000000..f0feec01ab --- /dev/null +++ b/Lang/Jq/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Jq \ No newline at end of file diff --git a/Lang/Jq/Order-two-numerical-lists b/Lang/Jq/Order-two-numerical-lists new file mode 120000 index 0000000000..70990a51e3 --- /dev/null +++ b/Lang/Jq/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Jq \ No newline at end of file diff --git a/Lang/Jq/Ordered-Partitions b/Lang/Jq/Ordered-Partitions new file mode 120000 index 0000000000..8b96a8f67c --- /dev/null +++ b/Lang/Jq/Ordered-Partitions @@ -0,0 +1 @@ +../../Task/Ordered-Partitions/Jq \ No newline at end of file diff --git a/Lang/Jq/Ordered-words b/Lang/Jq/Ordered-words new file mode 120000 index 0000000000..e34e68a98e --- /dev/null +++ b/Lang/Jq/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Jq \ No newline at end of file diff --git a/Lang/Jq/Palindrome-detection b/Lang/Jq/Palindrome-detection new file mode 120000 index 0000000000..b12fff2cca --- /dev/null +++ b/Lang/Jq/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Jq \ No newline at end of file diff --git a/Lang/Jq/Pangram-checker b/Lang/Jq/Pangram-checker new file mode 120000 index 0000000000..ea878628b9 --- /dev/null +++ b/Lang/Jq/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/Jq \ No newline at end of file diff --git a/Lang/Jq/Paraffins b/Lang/Jq/Paraffins new file mode 120000 index 0000000000..08409543a6 --- /dev/null +++ b/Lang/Jq/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Jq \ No newline at end of file diff --git a/Lang/Jq/Pascals-triangle b/Lang/Jq/Pascals-triangle new file mode 120000 index 0000000000..514e44bcad --- /dev/null +++ b/Lang/Jq/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Jq \ No newline at end of file diff --git a/Lang/Jq/Perfect-numbers b/Lang/Jq/Perfect-numbers new file mode 120000 index 0000000000..a6575a8140 --- /dev/null +++ b/Lang/Jq/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Permutation-test b/Lang/Jq/Permutation-test new file mode 120000 index 0000000000..ead7c86ca4 --- /dev/null +++ b/Lang/Jq/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Jq \ No newline at end of file diff --git a/Lang/Jq/Permutations b/Lang/Jq/Permutations new file mode 120000 index 0000000000..6a500bcc6a --- /dev/null +++ b/Lang/Jq/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Jq \ No newline at end of file diff --git a/Lang/Jq/Permutations-Derangements b/Lang/Jq/Permutations-Derangements new file mode 120000 index 0000000000..4a2ccf9209 --- /dev/null +++ b/Lang/Jq/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/Jq \ No newline at end of file diff --git a/Lang/Jq/Permutations-by-swapping b/Lang/Jq/Permutations-by-swapping new file mode 120000 index 0000000000..b2f7aa17e5 --- /dev/null +++ b/Lang/Jq/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Jq \ No newline at end of file diff --git a/Lang/Jq/Pernicious-numbers b/Lang/Jq/Pernicious-numbers new file mode 120000 index 0000000000..71cf4d1257 --- /dev/null +++ b/Lang/Jq/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Phrase-reversals b/Lang/Jq/Phrase-reversals new file mode 120000 index 0000000000..9406272e4e --- /dev/null +++ b/Lang/Jq/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Jq \ No newline at end of file diff --git a/Lang/Jq/Pi b/Lang/Jq/Pi new file mode 120000 index 0000000000..49b7dcf21d --- /dev/null +++ b/Lang/Jq/Pi @@ -0,0 +1 @@ +../../Task/Pi/Jq \ No newline at end of file diff --git a/Lang/Jq/Plot-coordinate-pairs b/Lang/Jq/Plot-coordinate-pairs new file mode 120000 index 0000000000..9a62eeeabb --- /dev/null +++ b/Lang/Jq/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Jq \ No newline at end of file diff --git a/Lang/Jq/Polymorphism b/Lang/Jq/Polymorphism new file mode 120000 index 0000000000..599fec1630 --- /dev/null +++ b/Lang/Jq/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/Jq \ No newline at end of file diff --git a/Lang/Jq/Power-set b/Lang/Jq/Power-set new file mode 120000 index 0000000000..4208b571a5 --- /dev/null +++ b/Lang/Jq/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Jq \ No newline at end of file diff --git a/Lang/Jq/Price-fraction b/Lang/Jq/Price-fraction new file mode 120000 index 0000000000..3c025e3bec --- /dev/null +++ b/Lang/Jq/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Jq \ No newline at end of file diff --git a/Lang/Jq/Prime-decomposition b/Lang/Jq/Prime-decomposition new file mode 120000 index 0000000000..44ff0e2de6 --- /dev/null +++ b/Lang/Jq/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Jq \ No newline at end of file diff --git a/Lang/Jq/Priority-queue b/Lang/Jq/Priority-queue new file mode 120000 index 0000000000..f108d42c33 --- /dev/null +++ b/Lang/Jq/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Jq \ No newline at end of file diff --git a/Lang/Jq/Problem-of-Apollonius b/Lang/Jq/Problem-of-Apollonius new file mode 120000 index 0000000000..6ecd692cb7 --- /dev/null +++ b/Lang/Jq/Problem-of-Apollonius @@ -0,0 +1 @@ +../../Task/Problem-of-Apollonius/Jq \ No newline at end of file diff --git a/Lang/Jq/Program-termination b/Lang/Jq/Program-termination new file mode 120000 index 0000000000..7a2db91e17 --- /dev/null +++ b/Lang/Jq/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Jq \ No newline at end of file diff --git a/Lang/Jq/Pythagorean-triples b/Lang/Jq/Pythagorean-triples new file mode 120000 index 0000000000..2f4bd6f731 --- /dev/null +++ b/Lang/Jq/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Jq \ No newline at end of file diff --git a/Lang/Jq/Quaternion-type b/Lang/Jq/Quaternion-type new file mode 120000 index 0000000000..36df977f17 --- /dev/null +++ b/Lang/Jq/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Jq \ No newline at end of file diff --git a/Lang/Jq/Queue-Definition b/Lang/Jq/Queue-Definition new file mode 120000 index 0000000000..c69441e36a --- /dev/null +++ b/Lang/Jq/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Jq \ No newline at end of file diff --git a/Lang/Jq/Quickselect-algorithm b/Lang/Jq/Quickselect-algorithm new file mode 120000 index 0000000000..f55d9d0497 --- /dev/null +++ b/Lang/Jq/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Jq \ No newline at end of file diff --git a/Lang/Jq/README b/Lang/Jq/README new file mode 100644 index 0000000000..e770026dd2 --- /dev/null +++ b/Lang/Jq/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Jq diff --git a/Lang/Jq/Random-number-generator--device- b/Lang/Jq/Random-number-generator--device- new file mode 120000 index 0000000000..1330c42016 --- /dev/null +++ b/Lang/Jq/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/Jq \ No newline at end of file diff --git a/Lang/Jq/Random-numbers b/Lang/Jq/Random-numbers new file mode 120000 index 0000000000..a1accc1c6c --- /dev/null +++ b/Lang/Jq/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Range-expansion b/Lang/Jq/Range-expansion new file mode 120000 index 0000000000..36536bbbfb --- /dev/null +++ b/Lang/Jq/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/Jq \ No newline at end of file diff --git a/Lang/Jq/Range-extraction b/Lang/Jq/Range-extraction new file mode 120000 index 0000000000..1ff557fac7 --- /dev/null +++ b/Lang/Jq/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Jq \ No newline at end of file diff --git a/Lang/Jq/Ranking-methods b/Lang/Jq/Ranking-methods new file mode 120000 index 0000000000..29edf581f6 --- /dev/null +++ b/Lang/Jq/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Jq \ No newline at end of file diff --git a/Lang/Jq/Read-a-configuration-file b/Lang/Jq/Read-a-configuration-file new file mode 120000 index 0000000000..1fa3c04f90 --- /dev/null +++ b/Lang/Jq/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Jq \ No newline at end of file diff --git a/Lang/Jq/Read-a-file-line-by-line b/Lang/Jq/Read-a-file-line-by-line new file mode 120000 index 0000000000..ba19b1aae9 --- /dev/null +++ b/Lang/Jq/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Jq \ No newline at end of file diff --git a/Lang/Jq/Read-a-specific-line-from-a-file b/Lang/Jq/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..4a59f7b5d0 --- /dev/null +++ b/Lang/Jq/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Jq \ No newline at end of file diff --git a/Lang/Jq/Read-entire-file b/Lang/Jq/Read-entire-file new file mode 120000 index 0000000000..e72ad594b7 --- /dev/null +++ b/Lang/Jq/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Jq \ No newline at end of file diff --git a/Lang/Jq/Real-constants-and-functions b/Lang/Jq/Real-constants-and-functions new file mode 120000 index 0000000000..368530288a --- /dev/null +++ b/Lang/Jq/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Jq \ No newline at end of file diff --git a/Lang/Jq/Regular-expressions b/Lang/Jq/Regular-expressions new file mode 120000 index 0000000000..21f7eae87f --- /dev/null +++ b/Lang/Jq/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Jq \ No newline at end of file diff --git a/Lang/Jq/Remove-duplicate-elements b/Lang/Jq/Remove-duplicate-elements new file mode 120000 index 0000000000..290d0a568d --- /dev/null +++ b/Lang/Jq/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Jq \ No newline at end of file diff --git a/Lang/Jq/Remove-lines-from-a-file b/Lang/Jq/Remove-lines-from-a-file new file mode 120000 index 0000000000..ed15e9015c --- /dev/null +++ b/Lang/Jq/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Jq \ No newline at end of file diff --git a/Lang/Jq/Rep-string b/Lang/Jq/Rep-string new file mode 120000 index 0000000000..3e8464f2e9 --- /dev/null +++ b/Lang/Jq/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Jq \ No newline at end of file diff --git a/Lang/Jq/Repeat-a-string b/Lang/Jq/Repeat-a-string new file mode 120000 index 0000000000..8e31c7bebc --- /dev/null +++ b/Lang/Jq/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Jq \ No newline at end of file diff --git a/Lang/Jq/Return-multiple-values b/Lang/Jq/Return-multiple-values new file mode 120000 index 0000000000..eeace31aa1 --- /dev/null +++ b/Lang/Jq/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Jq \ No newline at end of file diff --git a/Lang/Jq/Reverse-a-string b/Lang/Jq/Reverse-a-string new file mode 120000 index 0000000000..58ad216ac6 --- /dev/null +++ b/Lang/Jq/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Jq \ No newline at end of file diff --git a/Lang/Jq/Reverse-words-in-a-string b/Lang/Jq/Reverse-words-in-a-string new file mode 120000 index 0000000000..442e6c0691 --- /dev/null +++ b/Lang/Jq/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Jq \ No newline at end of file diff --git a/Lang/Jq/Roman-numerals-Decode b/Lang/Jq/Roman-numerals-Decode new file mode 120000 index 0000000000..953cd16c31 --- /dev/null +++ b/Lang/Jq/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Jq \ No newline at end of file diff --git a/Lang/Jq/Roots-of-a-function b/Lang/Jq/Roots-of-a-function new file mode 120000 index 0000000000..39d15eb65a --- /dev/null +++ b/Lang/Jq/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/Jq \ No newline at end of file diff --git a/Lang/Jq/Roots-of-a-quadratic-function b/Lang/Jq/Roots-of-a-quadratic-function new file mode 120000 index 0000000000..65ad6ed325 --- /dev/null +++ b/Lang/Jq/Roots-of-a-quadratic-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-quadratic-function/Jq \ No newline at end of file diff --git a/Lang/Jq/Roots-of-unity b/Lang/Jq/Roots-of-unity new file mode 120000 index 0000000000..3c909bdb82 --- /dev/null +++ b/Lang/Jq/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/Jq \ No newline at end of file diff --git a/Lang/Jq/Rot-13 b/Lang/Jq/Rot-13 new file mode 120000 index 0000000000..75996f7608 --- /dev/null +++ b/Lang/Jq/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Jq \ No newline at end of file diff --git a/Lang/Jq/Run-length-encoding b/Lang/Jq/Run-length-encoding new file mode 120000 index 0000000000..bdb9caace2 --- /dev/null +++ b/Lang/Jq/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Jq \ No newline at end of file diff --git a/Lang/Jq/Runge-Kutta-method b/Lang/Jq/Runge-Kutta-method new file mode 120000 index 0000000000..62544848ed --- /dev/null +++ b/Lang/Jq/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Jq \ No newline at end of file diff --git a/Lang/Jq/SEDOLs b/Lang/Jq/SEDOLs new file mode 120000 index 0000000000..1e9052ff34 --- /dev/null +++ b/Lang/Jq/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/Jq \ No newline at end of file diff --git a/Lang/Jq/Same-Fringe b/Lang/Jq/Same-Fringe new file mode 120000 index 0000000000..4d775f729d --- /dev/null +++ b/Lang/Jq/Same-Fringe @@ -0,0 +1 @@ +../../Task/Same-Fringe/Jq \ No newline at end of file diff --git a/Lang/Jq/Scope-Function-names-and-labels b/Lang/Jq/Scope-Function-names-and-labels new file mode 120000 index 0000000000..c0967cc240 --- /dev/null +++ b/Lang/Jq/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/Jq \ No newline at end of file diff --git a/Lang/Jq/Search-a-list b/Lang/Jq/Search-a-list new file mode 120000 index 0000000000..dd103f5b9c --- /dev/null +++ b/Lang/Jq/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Jq \ No newline at end of file diff --git a/Lang/Jq/Self-describing-numbers b/Lang/Jq/Self-describing-numbers new file mode 120000 index 0000000000..db67937927 --- /dev/null +++ b/Lang/Jq/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Self-referential-sequence b/Lang/Jq/Self-referential-sequence new file mode 120000 index 0000000000..a3370d0a8e --- /dev/null +++ b/Lang/Jq/Self-referential-sequence @@ -0,0 +1 @@ +../../Task/Self-referential-sequence/Jq \ No newline at end of file diff --git a/Lang/Jq/Semordnilap b/Lang/Jq/Semordnilap new file mode 120000 index 0000000000..a3416c07d2 --- /dev/null +++ b/Lang/Jq/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Jq \ No newline at end of file diff --git a/Lang/Jq/Sequence-of-non-squares b/Lang/Jq/Sequence-of-non-squares new file mode 120000 index 0000000000..4e90196774 --- /dev/null +++ b/Lang/Jq/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/Jq \ No newline at end of file diff --git a/Lang/Jq/Sequence-of-primes-by-Trial-Division b/Lang/Jq/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..8bc0d9896a --- /dev/null +++ b/Lang/Jq/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Jq \ No newline at end of file diff --git a/Lang/Jq/Set b/Lang/Jq/Set new file mode 120000 index 0000000000..dedd85a54c --- /dev/null +++ b/Lang/Jq/Set @@ -0,0 +1 @@ +../../Task/Set/Jq \ No newline at end of file diff --git a/Lang/Jq/Set-consolidation b/Lang/Jq/Set-consolidation new file mode 120000 index 0000000000..b791cdcb2a --- /dev/null +++ b/Lang/Jq/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/Jq \ No newline at end of file diff --git a/Lang/Jq/Shell-one-liner b/Lang/Jq/Shell-one-liner new file mode 120000 index 0000000000..f6a5ce1c3a --- /dev/null +++ b/Lang/Jq/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Jq \ No newline at end of file diff --git a/Lang/Jq/Short-circuit-evaluation b/Lang/Jq/Short-circuit-evaluation new file mode 120000 index 0000000000..fea255dd30 --- /dev/null +++ b/Lang/Jq/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Jq \ No newline at end of file diff --git a/Lang/Jq/Show-the-epoch b/Lang/Jq/Show-the-epoch new file mode 120000 index 0000000000..71bc79eca3 --- /dev/null +++ b/Lang/Jq/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Jq \ No newline at end of file diff --git a/Lang/Jq/Sierpinski-carpet b/Lang/Jq/Sierpinski-carpet new file mode 120000 index 0000000000..135a5ab6f1 --- /dev/null +++ b/Lang/Jq/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Jq \ No newline at end of file diff --git a/Lang/Jq/Sieve-of-Eratosthenes b/Lang/Jq/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..08c5dabd9f --- /dev/null +++ b/Lang/Jq/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Jq \ No newline at end of file diff --git a/Lang/Jq/Singly-linked-list-Traversal b/Lang/Jq/Singly-linked-list-Traversal new file mode 120000 index 0000000000..bdaf581e0a --- /dev/null +++ b/Lang/Jq/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Jq \ No newline at end of file diff --git a/Lang/Jq/Solve-the-no-connection-puzzle b/Lang/Jq/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..ce7ec451f8 --- /dev/null +++ b/Lang/Jq/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Jq \ No newline at end of file diff --git a/Lang/Jq/Sort-an-array-of-composite-structures b/Lang/Jq/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..d55df3ad83 --- /dev/null +++ b/Lang/Jq/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Jq \ No newline at end of file diff --git a/Lang/Jq/Sort-an-integer-array b/Lang/Jq/Sort-an-integer-array new file mode 120000 index 0000000000..bc36db4e98 --- /dev/null +++ b/Lang/Jq/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Jq \ No newline at end of file diff --git a/Lang/Jq/Sort-disjoint-sublist b/Lang/Jq/Sort-disjoint-sublist new file mode 120000 index 0000000000..dc5372b1ca --- /dev/null +++ b/Lang/Jq/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Jq \ No newline at end of file diff --git a/Lang/Jq/Sort-stability b/Lang/Jq/Sort-stability new file mode 120000 index 0000000000..f4957a7bd6 --- /dev/null +++ b/Lang/Jq/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Jq \ No newline at end of file diff --git a/Lang/Jq/Sort-using-a-custom-comparator b/Lang/Jq/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..2ca883b834 --- /dev/null +++ b/Lang/Jq/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Bead-sort b/Lang/Jq/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..5be65fb273 --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Bubble-sort b/Lang/Jq/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..08ce74ea42 --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Cocktail-sort b/Lang/Jq/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..278f7648d2 --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Comb-sort b/Lang/Jq/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..e3d8601686 --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Counting-sort b/Lang/Jq/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..ebde2f6f5a --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Gnome-sort b/Lang/Jq/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..ac505c4e62 --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Insertion-sort b/Lang/Jq/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..cc881ea2a1 --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Merge-sort b/Lang/Jq/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..6be36c7cb8 --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Pancake-sort b/Lang/Jq/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..d41253787c --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Permutation-sort b/Lang/Jq/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..d6a5125082 --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Quicksort b/Lang/Jq/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..33cf339cff --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Radix-sort b/Lang/Jq/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..df31194aa1 --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Selection-sort b/Lang/Jq/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..c1c6467151 --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Shell-sort b/Lang/Jq/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..6c743eef57 --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Sleep-sort b/Lang/Jq/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..5b17c85518 --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Stooge-sort b/Lang/Jq/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..6e60a8f05e --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-algorithms-Strand-sort b/Lang/Jq/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..1bd3f6ae21 --- /dev/null +++ b/Lang/Jq/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Sparkline-in-unicode b/Lang/Jq/Sparkline-in-unicode new file mode 120000 index 0000000000..625a476802 --- /dev/null +++ b/Lang/Jq/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Jq \ No newline at end of file diff --git a/Lang/Jq/Special-characters b/Lang/Jq/Special-characters new file mode 120000 index 0000000000..bd24b3785b --- /dev/null +++ b/Lang/Jq/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/Jq \ No newline at end of file diff --git a/Lang/Jq/Special-variables b/Lang/Jq/Special-variables new file mode 120000 index 0000000000..83a886ce9c --- /dev/null +++ b/Lang/Jq/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Jq \ No newline at end of file diff --git a/Lang/Jq/Spiral-matrix b/Lang/Jq/Spiral-matrix new file mode 120000 index 0000000000..031165c016 --- /dev/null +++ b/Lang/Jq/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Jq \ No newline at end of file diff --git a/Lang/Jq/Stair-climbing-puzzle b/Lang/Jq/Stair-climbing-puzzle new file mode 120000 index 0000000000..4b700315b7 --- /dev/null +++ b/Lang/Jq/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Jq \ No newline at end of file diff --git a/Lang/Jq/State-name-puzzle b/Lang/Jq/State-name-puzzle new file mode 120000 index 0000000000..03fde53cfc --- /dev/null +++ b/Lang/Jq/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Jq \ No newline at end of file diff --git a/Lang/Jq/Stem-and-leaf-plot b/Lang/Jq/Stem-and-leaf-plot new file mode 120000 index 0000000000..3d36cff720 --- /dev/null +++ b/Lang/Jq/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Jq \ No newline at end of file diff --git a/Lang/Jq/Stern-Brocot-sequence b/Lang/Jq/Stern-Brocot-sequence new file mode 120000 index 0000000000..09c5a01b06 --- /dev/null +++ b/Lang/Jq/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Jq \ No newline at end of file diff --git a/Lang/Jq/String-append b/Lang/Jq/String-append new file mode 120000 index 0000000000..7099122cb6 --- /dev/null +++ b/Lang/Jq/String-append @@ -0,0 +1 @@ +../../Task/String-append/Jq \ No newline at end of file diff --git a/Lang/Jq/String-case b/Lang/Jq/String-case new file mode 120000 index 0000000000..3cd15a65df --- /dev/null +++ b/Lang/Jq/String-case @@ -0,0 +1 @@ +../../Task/String-case/Jq \ No newline at end of file diff --git a/Lang/Jq/String-comparison b/Lang/Jq/String-comparison new file mode 120000 index 0000000000..032b23c76f --- /dev/null +++ b/Lang/Jq/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Jq \ No newline at end of file diff --git a/Lang/Jq/String-concatenation b/Lang/Jq/String-concatenation new file mode 120000 index 0000000000..5a53728e50 --- /dev/null +++ b/Lang/Jq/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Jq \ No newline at end of file diff --git a/Lang/Jq/String-interpolation--included- b/Lang/Jq/String-interpolation--included- new file mode 120000 index 0000000000..d3bf788c8c --- /dev/null +++ b/Lang/Jq/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Jq \ No newline at end of file diff --git a/Lang/Jq/String-length b/Lang/Jq/String-length new file mode 120000 index 0000000000..374b358a18 --- /dev/null +++ b/Lang/Jq/String-length @@ -0,0 +1 @@ +../../Task/String-length/Jq \ No newline at end of file diff --git a/Lang/Jq/String-matching b/Lang/Jq/String-matching new file mode 120000 index 0000000000..433dcc979b --- /dev/null +++ b/Lang/Jq/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Jq \ No newline at end of file diff --git a/Lang/Jq/String-prepend b/Lang/Jq/String-prepend new file mode 120000 index 0000000000..8dd1e024ec --- /dev/null +++ b/Lang/Jq/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Jq \ No newline at end of file diff --git a/Lang/Jq/Strip-a-set-of-characters-from-a-string b/Lang/Jq/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..52b668b150 --- /dev/null +++ b/Lang/Jq/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Jq \ No newline at end of file diff --git a/Lang/Jq/Strip-block-comments b/Lang/Jq/Strip-block-comments new file mode 120000 index 0000000000..62a566da82 --- /dev/null +++ b/Lang/Jq/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Jq \ No newline at end of file diff --git a/Lang/Jq/Strip-comments-from-a-string b/Lang/Jq/Strip-comments-from-a-string new file mode 120000 index 0000000000..12668c2beb --- /dev/null +++ b/Lang/Jq/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Jq \ No newline at end of file diff --git a/Lang/Jq/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Jq/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..1883fac8d7 --- /dev/null +++ b/Lang/Jq/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Jq \ No newline at end of file diff --git a/Lang/Jq/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Jq/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..64a136b00f --- /dev/null +++ b/Lang/Jq/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Jq \ No newline at end of file diff --git a/Lang/Jq/Substring b/Lang/Jq/Substring new file mode 120000 index 0000000000..457c2f2fb2 --- /dev/null +++ b/Lang/Jq/Substring @@ -0,0 +1 @@ +../../Task/Substring/Jq \ No newline at end of file diff --git a/Lang/Jq/Substring-Top-and-tail b/Lang/Jq/Substring-Top-and-tail new file mode 120000 index 0000000000..042eda9a8e --- /dev/null +++ b/Lang/Jq/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Jq \ No newline at end of file diff --git a/Lang/Jq/Sum-and-product-of-an-array b/Lang/Jq/Sum-and-product-of-an-array new file mode 120000 index 0000000000..b380d587f1 --- /dev/null +++ b/Lang/Jq/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Jq \ No newline at end of file diff --git a/Lang/Jq/Sum-digits-of-an-integer b/Lang/Jq/Sum-digits-of-an-integer new file mode 120000 index 0000000000..a4ba15d14f --- /dev/null +++ b/Lang/Jq/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Jq \ No newline at end of file diff --git a/Lang/Jq/Sum-multiples-of-3-and-5 b/Lang/Jq/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..f036a14dc7 --- /dev/null +++ b/Lang/Jq/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Jq \ No newline at end of file diff --git a/Lang/Jq/Sum-of-a-series b/Lang/Jq/Sum-of-a-series new file mode 120000 index 0000000000..42f04379a4 --- /dev/null +++ b/Lang/Jq/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Jq \ No newline at end of file diff --git a/Lang/Jq/Sum-of-squares b/Lang/Jq/Sum-of-squares new file mode 120000 index 0000000000..a76b1d6a93 --- /dev/null +++ b/Lang/Jq/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Jq \ No newline at end of file diff --git a/Lang/Jq/Symmetric-difference b/Lang/Jq/Symmetric-difference new file mode 120000 index 0000000000..583499b93d --- /dev/null +++ b/Lang/Jq/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Jq \ No newline at end of file diff --git a/Lang/Jq/System-time b/Lang/Jq/System-time new file mode 120000 index 0000000000..7a2c473331 --- /dev/null +++ b/Lang/Jq/System-time @@ -0,0 +1 @@ +../../Task/System-time/Jq \ No newline at end of file diff --git a/Lang/Jq/Temperature-conversion b/Lang/Jq/Temperature-conversion new file mode 120000 index 0000000000..137a5b87b8 --- /dev/null +++ b/Lang/Jq/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Jq \ No newline at end of file diff --git a/Lang/Jq/Terminal-control-Clear-the-screen b/Lang/Jq/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..b8754bab1a --- /dev/null +++ b/Lang/Jq/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Jq \ No newline at end of file diff --git a/Lang/Jq/Terminal-control-Unicode-output b/Lang/Jq/Terminal-control-Unicode-output new file mode 120000 index 0000000000..7958c49025 --- /dev/null +++ b/Lang/Jq/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Jq \ No newline at end of file diff --git a/Lang/Jq/Ternary-logic b/Lang/Jq/Ternary-logic new file mode 120000 index 0000000000..2ad131f519 --- /dev/null +++ b/Lang/Jq/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Jq \ No newline at end of file diff --git a/Lang/Jq/Test-a-function b/Lang/Jq/Test-a-function new file mode 120000 index 0000000000..d11057eaa9 --- /dev/null +++ b/Lang/Jq/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Jq \ No newline at end of file diff --git a/Lang/Jq/Text-processing-1 b/Lang/Jq/Text-processing-1 new file mode 120000 index 0000000000..9b81d84e08 --- /dev/null +++ b/Lang/Jq/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Jq \ No newline at end of file diff --git a/Lang/Jq/Text-processing-2 b/Lang/Jq/Text-processing-2 new file mode 120000 index 0000000000..cea49839fc --- /dev/null +++ b/Lang/Jq/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Jq \ No newline at end of file diff --git a/Lang/Jq/Text-processing-Max-licenses-in-use b/Lang/Jq/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..6f66813e7e --- /dev/null +++ b/Lang/Jq/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Jq \ No newline at end of file diff --git a/Lang/Jq/Textonyms b/Lang/Jq/Textonyms new file mode 120000 index 0000000000..70d870880f --- /dev/null +++ b/Lang/Jq/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Jq \ No newline at end of file diff --git a/Lang/Jq/Tokenize-a-string b/Lang/Jq/Tokenize-a-string new file mode 120000 index 0000000000..78dd967abb --- /dev/null +++ b/Lang/Jq/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Jq \ No newline at end of file diff --git a/Lang/Jq/Top-rank-per-group b/Lang/Jq/Top-rank-per-group new file mode 120000 index 0000000000..16fe966e6a --- /dev/null +++ b/Lang/Jq/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Jq \ No newline at end of file diff --git a/Lang/Jq/Topological-sort b/Lang/Jq/Topological-sort new file mode 120000 index 0000000000..d70812df18 --- /dev/null +++ b/Lang/Jq/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Topswops b/Lang/Jq/Topswops new file mode 120000 index 0000000000..693422e40b --- /dev/null +++ b/Lang/Jq/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Jq \ No newline at end of file diff --git a/Lang/Jq/Towers-of-Hanoi b/Lang/Jq/Towers-of-Hanoi new file mode 120000 index 0000000000..122161f2fd --- /dev/null +++ b/Lang/Jq/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Jq \ No newline at end of file diff --git a/Lang/Jq/Trabb-Pardo-Knuth-algorithm b/Lang/Jq/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..af3188ac24 --- /dev/null +++ b/Lang/Jq/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Jq \ No newline at end of file diff --git a/Lang/Jq/Tree-traversal b/Lang/Jq/Tree-traversal new file mode 120000 index 0000000000..8c3da1d2c9 --- /dev/null +++ b/Lang/Jq/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Jq \ No newline at end of file diff --git a/Lang/Jq/Trigonometric-functions b/Lang/Jq/Trigonometric-functions new file mode 120000 index 0000000000..b18f66a889 --- /dev/null +++ b/Lang/Jq/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Jq \ No newline at end of file diff --git a/Lang/Jq/Twelve-statements b/Lang/Jq/Twelve-statements new file mode 120000 index 0000000000..b5f90c2bcb --- /dev/null +++ b/Lang/Jq/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Jq \ No newline at end of file diff --git a/Lang/Jq/URL-decoding b/Lang/Jq/URL-decoding new file mode 120000 index 0000000000..f57f56ae20 --- /dev/null +++ b/Lang/Jq/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Jq \ No newline at end of file diff --git a/Lang/Jq/URL-encoding b/Lang/Jq/URL-encoding new file mode 120000 index 0000000000..6daa2e2265 --- /dev/null +++ b/Lang/Jq/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Jq \ No newline at end of file diff --git a/Lang/Jq/Undefined-values b/Lang/Jq/Undefined-values new file mode 120000 index 0000000000..cffdd5c9b0 --- /dev/null +++ b/Lang/Jq/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Jq \ No newline at end of file diff --git a/Lang/Jq/Unicode-variable-names b/Lang/Jq/Unicode-variable-names new file mode 120000 index 0000000000..d5588349d0 --- /dev/null +++ b/Lang/Jq/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Jq \ No newline at end of file diff --git a/Lang/Jq/User-input-Text b/Lang/Jq/User-input-Text new file mode 120000 index 0000000000..c1d1faf27c --- /dev/null +++ b/Lang/Jq/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Jq \ No newline at end of file diff --git a/Lang/Jq/Van-der-Corput-sequence b/Lang/Jq/Van-der-Corput-sequence new file mode 120000 index 0000000000..c5a0bddf77 --- /dev/null +++ b/Lang/Jq/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Jq \ No newline at end of file diff --git a/Lang/Jq/Variables b/Lang/Jq/Variables new file mode 120000 index 0000000000..d7d4d90f35 --- /dev/null +++ b/Lang/Jq/Variables @@ -0,0 +1 @@ +../../Task/Variables/Jq \ No newline at end of file diff --git a/Lang/Jq/Variadic-function b/Lang/Jq/Variadic-function new file mode 120000 index 0000000000..45540ff487 --- /dev/null +++ b/Lang/Jq/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Jq \ No newline at end of file diff --git a/Lang/Jq/Vector-products b/Lang/Jq/Vector-products new file mode 120000 index 0000000000..2b34eb5023 --- /dev/null +++ b/Lang/Jq/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Jq \ No newline at end of file diff --git a/Lang/Jq/Web-scraping b/Lang/Jq/Web-scraping new file mode 120000 index 0000000000..8699747cc8 --- /dev/null +++ b/Lang/Jq/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Jq \ No newline at end of file diff --git a/Lang/Jq/Wireworld b/Lang/Jq/Wireworld new file mode 120000 index 0000000000..917a5e6fdb --- /dev/null +++ b/Lang/Jq/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Jq \ No newline at end of file diff --git a/Lang/Jq/Word-wrap b/Lang/Jq/Word-wrap new file mode 120000 index 0000000000..534a87f903 --- /dev/null +++ b/Lang/Jq/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Jq \ No newline at end of file diff --git a/Lang/Jq/Write-float-arrays-to-a-text-file b/Lang/Jq/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..acab88953c --- /dev/null +++ b/Lang/Jq/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Jq \ No newline at end of file diff --git a/Lang/Jq/Yin-and-yang b/Lang/Jq/Yin-and-yang new file mode 120000 index 0000000000..28f3ac48c3 --- /dev/null +++ b/Lang/Jq/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Jq \ No newline at end of file diff --git a/Lang/Jq/Zebra-puzzle b/Lang/Jq/Zebra-puzzle new file mode 120000 index 0000000000..7ba9c4a884 --- /dev/null +++ b/Lang/Jq/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Jq \ No newline at end of file diff --git a/Lang/Jq/Zeckendorf-number-representation b/Lang/Jq/Zeckendorf-number-representation new file mode 120000 index 0000000000..6a121895b9 --- /dev/null +++ b/Lang/Jq/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Jq \ No newline at end of file diff --git a/Lang/Jq/Zero-to-the-zero-power b/Lang/Jq/Zero-to-the-zero-power new file mode 120000 index 0000000000..e383ad9e41 --- /dev/null +++ b/Lang/Jq/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Jq \ No newline at end of file diff --git a/Lang/Jq/Zig-zag-matrix b/Lang/Jq/Zig-zag-matrix new file mode 120000 index 0000000000..9e7105bbe4 --- /dev/null +++ b/Lang/Jq/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Jq \ No newline at end of file diff --git a/Lang/Julia/00DESCRIPTION b/Lang/Julia/00DESCRIPTION index dbe90a1fb2..a8e9b8a3ac 100644 --- a/Lang/Julia/00DESCRIPTION +++ b/Lang/Julia/00DESCRIPTION @@ -1,5 +1,14 @@ {{stub}} -{{language | Julia | site=http://julialang.org/ }} +{{language +|Julia +|exec=byte +|site=http://julialang.org/ +|gc=yes +|parampass=both +|safety=both +|checking=both +|strength=strong +}} Julia is a high-level, high-performance dynamic programming language for technical computing, with syntax silimar to [[MATLAB]]'s. It provides a sophisticated compiler, distributed parallel execution, numerical accuracy, and an extensive mathematical function library. diff --git a/Lang/Julia/Average-loop-length b/Lang/Julia/Average-loop-length new file mode 120000 index 0000000000..760069b4d0 --- /dev/null +++ b/Lang/Julia/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Julia \ No newline at end of file diff --git a/Lang/Julia/Best-shuffle b/Lang/Julia/Best-shuffle new file mode 120000 index 0000000000..3c7e618a65 --- /dev/null +++ b/Lang/Julia/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/Julia \ No newline at end of file diff --git a/Lang/Julia/Bitwise-operations b/Lang/Julia/Bitwise-operations new file mode 120000 index 0000000000..2276b30a68 --- /dev/null +++ b/Lang/Julia/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Julia \ No newline at end of file diff --git a/Lang/Julia/Box-the-compass b/Lang/Julia/Box-the-compass new file mode 120000 index 0000000000..ef264155a3 --- /dev/null +++ b/Lang/Julia/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/Julia \ No newline at end of file diff --git a/Lang/Julia/Catalan-numbers-Pascals-triangle b/Lang/Julia/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..dae57159b9 --- /dev/null +++ b/Lang/Julia/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Julia \ No newline at end of file diff --git a/Lang/Julia/Character-matching b/Lang/Julia/Character-matching deleted file mode 120000 index 5fd1bd4f85..0000000000 --- a/Lang/Julia/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Julia \ No newline at end of file diff --git a/Lang/Julia/Closest-pair-problem b/Lang/Julia/Closest-pair-problem new file mode 120000 index 0000000000..05cc981b64 --- /dev/null +++ b/Lang/Julia/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/Julia \ No newline at end of file diff --git a/Lang/Julia/Count-the-coins b/Lang/Julia/Count-the-coins new file mode 120000 index 0000000000..56c0aa09ac --- /dev/null +++ b/Lang/Julia/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Julia \ No newline at end of file diff --git a/Lang/Julia/Currying b/Lang/Julia/Currying new file mode 120000 index 0000000000..c3db29810b --- /dev/null +++ b/Lang/Julia/Currying @@ -0,0 +1 @@ +../../Task/Currying/Julia \ No newline at end of file diff --git a/Lang/Julia/Deepcopy b/Lang/Julia/Deepcopy new file mode 120000 index 0000000000..8424ec6ee8 --- /dev/null +++ b/Lang/Julia/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/Julia \ No newline at end of file diff --git a/Lang/Julia/Delete-a-file b/Lang/Julia/Delete-a-file new file mode 120000 index 0000000000..14900e3fc3 --- /dev/null +++ b/Lang/Julia/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Julia \ No newline at end of file diff --git a/Lang/Julia/Discordian-date b/Lang/Julia/Discordian-date new file mode 120000 index 0000000000..3e87765483 --- /dev/null +++ b/Lang/Julia/Discordian-date @@ -0,0 +1 @@ +../../Task/Discordian-date/Julia \ No newline at end of file diff --git a/Lang/Julia/Draw-a-sphere b/Lang/Julia/Draw-a-sphere new file mode 120000 index 0000000000..257ced7181 --- /dev/null +++ b/Lang/Julia/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/Julia \ No newline at end of file diff --git a/Lang/Julia/Element-wise-operations b/Lang/Julia/Element-wise-operations new file mode 120000 index 0000000000..9b66241dbf --- /dev/null +++ b/Lang/Julia/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Julia \ No newline at end of file diff --git a/Lang/Julia/Empty-directory b/Lang/Julia/Empty-directory new file mode 120000 index 0000000000..3e4634a96f --- /dev/null +++ b/Lang/Julia/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Julia \ No newline at end of file diff --git a/Lang/Julia/Enumerations b/Lang/Julia/Enumerations new file mode 120000 index 0000000000..6ec3746ab2 --- /dev/null +++ b/Lang/Julia/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Julia \ No newline at end of file diff --git a/Lang/Julia/Equilibrium-index b/Lang/Julia/Equilibrium-index new file mode 120000 index 0000000000..80040539ad --- /dev/null +++ b/Lang/Julia/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Julia \ No newline at end of file diff --git a/Lang/Julia/Exponentiation-operator b/Lang/Julia/Exponentiation-operator new file mode 120000 index 0000000000..cbe75f5d45 --- /dev/null +++ b/Lang/Julia/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Julia \ No newline at end of file diff --git a/Lang/Julia/Extreme-floating-point-values b/Lang/Julia/Extreme-floating-point-values new file mode 120000 index 0000000000..a350267c36 --- /dev/null +++ b/Lang/Julia/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Julia \ No newline at end of file diff --git a/Lang/Julia/Factors-of-a-Mersenne-number b/Lang/Julia/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..77c0a7ee0d --- /dev/null +++ b/Lang/Julia/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Julia \ No newline at end of file diff --git a/Lang/Julia/Fibonacci-word b/Lang/Julia/Fibonacci-word new file mode 120000 index 0000000000..29d3887e7d --- /dev/null +++ b/Lang/Julia/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Julia \ No newline at end of file diff --git a/Lang/Julia/Forest-fire b/Lang/Julia/Forest-fire new file mode 120000 index 0000000000..192f3ac3fa --- /dev/null +++ b/Lang/Julia/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/Julia \ No newline at end of file diff --git a/Lang/Julia/HTTPS b/Lang/Julia/HTTPS new file mode 120000 index 0000000000..14d7b6abe9 --- /dev/null +++ b/Lang/Julia/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Julia \ No newline at end of file diff --git a/Lang/Julia/Hash-join b/Lang/Julia/Hash-join new file mode 120000 index 0000000000..56f93251a1 --- /dev/null +++ b/Lang/Julia/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Julia \ No newline at end of file diff --git a/Lang/Julia/Hello-world-Web-server b/Lang/Julia/Hello-world-Web-server new file mode 120000 index 0000000000..1521b248e0 --- /dev/null +++ b/Lang/Julia/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Julia \ No newline at end of file diff --git a/Lang/Julia/Hofstadter-Conway-$10,000-sequence b/Lang/Julia/Hofstadter-Conway-$10,000-sequence new file mode 120000 index 0000000000..06041f975b --- /dev/null +++ b/Lang/Julia/Hofstadter-Conway-$10,000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10,000-sequence/Julia \ No newline at end of file diff --git a/Lang/Julia/Holidays-related-to-Easter b/Lang/Julia/Holidays-related-to-Easter new file mode 120000 index 0000000000..2d4329d2e9 --- /dev/null +++ b/Lang/Julia/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/Julia \ No newline at end of file diff --git a/Lang/Julia/Horizontal-sundial-calculations b/Lang/Julia/Horizontal-sundial-calculations new file mode 120000 index 0000000000..ef5bda81b1 --- /dev/null +++ b/Lang/Julia/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/Julia \ No newline at end of file diff --git a/Lang/Julia/I-before-E-except-after-C b/Lang/Julia/I-before-E-except-after-C new file mode 120000 index 0000000000..79d35b2082 --- /dev/null +++ b/Lang/Julia/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Julia \ No newline at end of file diff --git a/Lang/Julia/IBAN b/Lang/Julia/IBAN new file mode 120000 index 0000000000..0c589f5e47 --- /dev/null +++ b/Lang/Julia/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Julia \ No newline at end of file diff --git a/Lang/Julia/Longest-common-subsequence b/Lang/Julia/Longest-common-subsequence new file mode 120000 index 0000000000..0b096d352d --- /dev/null +++ b/Lang/Julia/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/Julia \ No newline at end of file diff --git a/Lang/Julia/Look-and-say-sequence b/Lang/Julia/Look-and-say-sequence new file mode 120000 index 0000000000..ccd13123d7 --- /dev/null +++ b/Lang/Julia/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Julia \ No newline at end of file diff --git a/Lang/Julia/Magic-squares-of-odd-order b/Lang/Julia/Magic-squares-of-odd-order new file mode 120000 index 0000000000..542c583847 --- /dev/null +++ b/Lang/Julia/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/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/Non-decimal-radices-Convert b/Lang/Julia/Non-decimal-radices-Convert new file mode 120000 index 0000000000..9ee28f6a36 --- /dev/null +++ b/Lang/Julia/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Julia \ No newline at end of file diff --git a/Lang/Julia/Non-decimal-radices-Input b/Lang/Julia/Non-decimal-radices-Input new file mode 120000 index 0000000000..f538896c63 --- /dev/null +++ b/Lang/Julia/Non-decimal-radices-Input @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Input/Julia \ No newline at end of file diff --git a/Lang/Julia/Number-reversal-game b/Lang/Julia/Number-reversal-game new file mode 120000 index 0000000000..52052ff354 --- /dev/null +++ b/Lang/Julia/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Julia \ No newline at end of file diff --git a/Lang/Julia/Numeric-error-propagation b/Lang/Julia/Numeric-error-propagation new file mode 120000 index 0000000000..5f4fa1360c --- /dev/null +++ b/Lang/Julia/Numeric-error-propagation @@ -0,0 +1 @@ +../../Task/Numeric-error-propagation/Julia \ No newline at end of file diff --git a/Lang/Julia/Pascals-triangle b/Lang/Julia/Pascals-triangle new file mode 120000 index 0000000000..859a4fa1bd --- /dev/null +++ b/Lang/Julia/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Julia \ No newline at end of file diff --git a/Lang/Julia/Permutations-Derangements b/Lang/Julia/Permutations-Derangements new file mode 120000 index 0000000000..60b9dd81bf --- /dev/null +++ b/Lang/Julia/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/Julia \ No newline at end of file diff --git a/Lang/Julia/Reduced-row-echelon-form b/Lang/Julia/Reduced-row-echelon-form deleted file mode 120000 index f1579dab3a..0000000000 --- a/Lang/Julia/Reduced-row-echelon-form +++ /dev/null @@ -1 +0,0 @@ -../../Task/Reduced-row-echelon-form/Julia \ No newline at end of file diff --git a/Lang/Julia/Simulate-input-Mouse b/Lang/Julia/Simulate-input-Mouse new file mode 120000 index 0000000000..a2703f3f65 --- /dev/null +++ b/Lang/Julia/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Comb-sort b/Lang/Julia/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..c7c6959a56 --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Insertion-sort b/Lang/Julia/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..20e1590f45 --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Permutation-sort b/Lang/Julia/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..8e9503d5ec --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Shell-sort b/Lang/Julia/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..0fee54cd9e --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Stooge-sort b/Lang/Julia/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..23c9f57eb7 --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Standard-deviation b/Lang/Julia/Standard-deviation deleted file mode 120000 index 7f2281f0b6..0000000000 --- a/Lang/Julia/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Julia \ No newline at end of file diff --git a/Lang/Julia/Stern-Brocot-sequence b/Lang/Julia/Stern-Brocot-sequence new file mode 120000 index 0000000000..fd889f9310 --- /dev/null +++ b/Lang/Julia/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Julia \ No newline at end of file diff --git a/Lang/Julia/String-comparison b/Lang/Julia/String-comparison new file mode 120000 index 0000000000..0bd893b960 --- /dev/null +++ b/Lang/Julia/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Julia \ No newline at end of file diff --git a/Lang/Julia/Strip-block-comments b/Lang/Julia/Strip-block-comments new file mode 120000 index 0000000000..bd757e5c64 --- /dev/null +++ b/Lang/Julia/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Julia \ No newline at end of file diff --git a/Lang/Julia/Sudoku b/Lang/Julia/Sudoku new file mode 120000 index 0000000000..225864970d --- /dev/null +++ b/Lang/Julia/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Julia \ No newline at end of file diff --git a/Lang/Julia/Terminal-control-Clear-the-screen b/Lang/Julia/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..e1c4b74aab --- /dev/null +++ b/Lang/Julia/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Julia \ No newline at end of file diff --git a/Lang/Julia/The-Twelve-Days-of-Christmas b/Lang/Julia/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..33f68e0e71 --- /dev/null +++ b/Lang/Julia/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Julia \ No newline at end of file diff --git a/Lang/Julia/Time-a-function b/Lang/Julia/Time-a-function new file mode 120000 index 0000000000..f61753752f --- /dev/null +++ b/Lang/Julia/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Julia \ No newline at end of file diff --git a/Lang/Julia/Top-rank-per-group b/Lang/Julia/Top-rank-per-group new file mode 120000 index 0000000000..aaa09cce7d --- /dev/null +++ b/Lang/Julia/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Julia \ No newline at end of file diff --git a/Lang/Julia/Topic-variable b/Lang/Julia/Topic-variable new file mode 120000 index 0000000000..53722c3de4 --- /dev/null +++ b/Lang/Julia/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Julia \ No newline at end of file diff --git a/Lang/Julia/Towers-of-Hanoi b/Lang/Julia/Towers-of-Hanoi new file mode 120000 index 0000000000..0b46ade7fc --- /dev/null +++ b/Lang/Julia/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Julia \ No newline at end of file diff --git a/Lang/Julia/Trigonometric-functions b/Lang/Julia/Trigonometric-functions new file mode 120000 index 0000000000..20207f98f2 --- /dev/null +++ b/Lang/Julia/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Julia \ No newline at end of file diff --git a/Lang/Julia/Unix-ls b/Lang/Julia/Unix-ls new file mode 120000 index 0000000000..269ba06fad --- /dev/null +++ b/Lang/Julia/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Julia \ No newline at end of file diff --git a/Lang/Julia/Verify-distribution-uniformity-Chi-squared-test b/Lang/Julia/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..2b5f4764cb --- /dev/null +++ b/Lang/Julia/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/Julia \ No newline at end of file diff --git a/Lang/Julia/Window-creation b/Lang/Julia/Window-creation new file mode 120000 index 0000000000..78452c25c2 --- /dev/null +++ b/Lang/Julia/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Julia \ No newline at end of file diff --git a/Lang/K/Character-matching b/Lang/K/Character-matching deleted file mode 120000 index c87d021c77..0000000000 --- a/Lang/K/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/K \ No newline at end of file diff --git a/Lang/K/File-IO b/Lang/K/File-IO deleted file mode 120000 index c6b944d183..0000000000 --- a/Lang/K/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/K \ No newline at end of file diff --git a/Lang/K/Five-weekends b/Lang/K/Five-weekends new file mode 120000 index 0000000000..88fb70d33d --- /dev/null +++ b/Lang/K/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/K \ No newline at end of file diff --git a/Lang/K/Identity-matrix b/Lang/K/Identity-matrix new file mode 120000 index 0000000000..05caf69843 --- /dev/null +++ b/Lang/K/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/K \ No newline at end of file diff --git a/Lang/K/Palindrome-detection b/Lang/K/Palindrome-detection new file mode 120000 index 0000000000..6d7629eb00 --- /dev/null +++ b/Lang/K/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/K \ No newline at end of file diff --git a/Lang/Klong/A+B b/Lang/Klong/A+B new file mode 120000 index 0000000000..3bb7eee1b4 --- /dev/null +++ b/Lang/Klong/A+B @@ -0,0 +1 @@ +../../Task/A+B/Klong \ No newline at end of file diff --git a/Lang/Klong/Continued-fraction b/Lang/Klong/Continued-fraction new file mode 120000 index 0000000000..aea21d3f22 --- /dev/null +++ b/Lang/Klong/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Klong \ No newline at end of file diff --git a/Lang/Klong/Matrix-transposition b/Lang/Klong/Matrix-transposition new file mode 120000 index 0000000000..2656175562 --- /dev/null +++ b/Lang/Klong/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/Klong \ No newline at end of file diff --git a/Lang/Kotlin/00DESCRIPTION b/Lang/Kotlin/00DESCRIPTION index 9031d39e4d..fa4b4c3306 100644 --- a/Lang/Kotlin/00DESCRIPTION +++ b/Lang/Kotlin/00DESCRIPTION @@ -1,3 +1,8 @@ {{language |checking=static -|site=http://kotlinlang.org}}Kotlin is the codename for a statically-typed [[JVM]]-targeted programming language developed by JetBrains and intended for industrial use. \ No newline at end of file +|site=http://kotlinlang.org}}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. + + +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. + +Kotlin has become a popular language for developing Android applications and, in May 2017, Google announced official support for it alongside Java and C++. \ No newline at end of file diff --git a/Lang/Kotlin/24-game-Solve b/Lang/Kotlin/24-game-Solve new file mode 120000 index 0000000000..81ea07a65a --- /dev/null +++ b/Lang/Kotlin/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/A+B b/Lang/Kotlin/A+B new file mode 120000 index 0000000000..2244695f62 --- /dev/null +++ b/Lang/Kotlin/A+B @@ -0,0 +1 @@ +../../Task/A+B/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/AKS-test-for-primes b/Lang/Kotlin/AKS-test-for-primes new file mode 120000 index 0000000000..9bd91a1f3a --- /dev/null +++ b/Lang/Kotlin/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Abstract-type b/Lang/Kotlin/Abstract-type new file mode 120000 index 0000000000..5a23762fef --- /dev/null +++ b/Lang/Kotlin/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Abundant,-deficient-and-perfect-number-classifications b/Lang/Kotlin/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..e624b2df9a --- /dev/null +++ b/Lang/Kotlin/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Accumulator-factory b/Lang/Kotlin/Accumulator-factory new file mode 120000 index 0000000000..3b86675a99 --- /dev/null +++ b/Lang/Kotlin/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Add-a-variable-to-a-class-instance-at-runtime b/Lang/Kotlin/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..a4e6577168 --- /dev/null +++ b/Lang/Kotlin/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Address-of-a-variable b/Lang/Kotlin/Address-of-a-variable new file mode 120000 index 0000000000..b025e9dc49 --- /dev/null +++ b/Lang/Kotlin/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Aliquot-sequence-classifications b/Lang/Kotlin/Aliquot-sequence-classifications new file mode 120000 index 0000000000..494cd648db --- /dev/null +++ b/Lang/Kotlin/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Amb b/Lang/Kotlin/Amb new file mode 120000 index 0000000000..0cde92df51 --- /dev/null +++ b/Lang/Kotlin/Amb @@ -0,0 +1 @@ +../../Task/Amb/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Amicable-pairs b/Lang/Kotlin/Amicable-pairs new file mode 120000 index 0000000000..0b48ca64a0 --- /dev/null +++ b/Lang/Kotlin/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Anagrams b/Lang/Kotlin/Anagrams new file mode 120000 index 0000000000..c51eab6b32 --- /dev/null +++ b/Lang/Kotlin/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Anagrams-Deranged-anagrams b/Lang/Kotlin/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..83cddf011f --- /dev/null +++ b/Lang/Kotlin/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Animation b/Lang/Kotlin/Animation new file mode 120000 index 0000000000..aa81b6526a --- /dev/null +++ b/Lang/Kotlin/Animation @@ -0,0 +1 @@ +../../Task/Animation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Anonymous-recursion b/Lang/Kotlin/Anonymous-recursion new file mode 120000 index 0000000000..4023d442c2 --- /dev/null +++ b/Lang/Kotlin/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Arbitrary-precision-integers--included- b/Lang/Kotlin/Arbitrary-precision-integers--included- new file mode 120000 index 0000000000..18c90c1229 --- /dev/null +++ b/Lang/Kotlin/Arbitrary-precision-integers--included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers--included-/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Arena-storage-pool b/Lang/Kotlin/Arena-storage-pool new file mode 120000 index 0000000000..5442239bde --- /dev/null +++ b/Lang/Kotlin/Arena-storage-pool @@ -0,0 +1 @@ +../../Task/Arena-storage-pool/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Arithmetic-Complex b/Lang/Kotlin/Arithmetic-Complex new file mode 120000 index 0000000000..e6e764ab18 --- /dev/null +++ b/Lang/Kotlin/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Arithmetic-Integer b/Lang/Kotlin/Arithmetic-Integer new file mode 120000 index 0000000000..7f4f675d5f --- /dev/null +++ b/Lang/Kotlin/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Arithmetic-Rational b/Lang/Kotlin/Arithmetic-Rational new file mode 120000 index 0000000000..30244c5e6d --- /dev/null +++ b/Lang/Kotlin/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Arithmetic-geometric-mean b/Lang/Kotlin/Arithmetic-geometric-mean new file mode 120000 index 0000000000..9857f986ec --- /dev/null +++ b/Lang/Kotlin/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Kotlin/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..a83547dd2a --- /dev/null +++ b/Lang/Kotlin/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Assertions b/Lang/Kotlin/Assertions new file mode 120000 index 0000000000..f697a1dc7c --- /dev/null +++ b/Lang/Kotlin/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Average-loop-length b/Lang/Kotlin/Average-loop-length new file mode 120000 index 0000000000..208aecbca0 --- /dev/null +++ b/Lang/Kotlin/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Averages-Mean-angle b/Lang/Kotlin/Averages-Mean-angle new file mode 120000 index 0000000000..07b72971b6 --- /dev/null +++ b/Lang/Kotlin/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Averages-Mean-time-of-day b/Lang/Kotlin/Averages-Mean-time-of-day new file mode 120000 index 0000000000..0e3474b4a0 --- /dev/null +++ b/Lang/Kotlin/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Averages-Mode b/Lang/Kotlin/Averages-Mode new file mode 120000 index 0000000000..48d98abf13 --- /dev/null +++ b/Lang/Kotlin/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Averages-Root-mean-square b/Lang/Kotlin/Averages-Root-mean-square new file mode 120000 index 0000000000..f6ac45be67 --- /dev/null +++ b/Lang/Kotlin/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Averages-Simple-moving-average b/Lang/Kotlin/Averages-Simple-moving-average new file mode 120000 index 0000000000..72bc259061 --- /dev/null +++ b/Lang/Kotlin/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Balanced-brackets b/Lang/Kotlin/Balanced-brackets new file mode 120000 index 0000000000..389d5ca795 --- /dev/null +++ b/Lang/Kotlin/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Balanced-ternary b/Lang/Kotlin/Balanced-ternary new file mode 120000 index 0000000000..4c514071d2 --- /dev/null +++ b/Lang/Kotlin/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Binary-digits b/Lang/Kotlin/Binary-digits new file mode 120000 index 0000000000..8917a33e10 --- /dev/null +++ b/Lang/Kotlin/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Binary-strings b/Lang/Kotlin/Binary-strings new file mode 120000 index 0000000000..184805db15 --- /dev/null +++ b/Lang/Kotlin/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bitcoin-address-validation b/Lang/Kotlin/Bitcoin-address-validation new file mode 120000 index 0000000000..a6b5ccab39 --- /dev/null +++ b/Lang/Kotlin/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bitmap b/Lang/Kotlin/Bitmap new file mode 120000 index 0000000000..f47b647fb4 --- /dev/null +++ b/Lang/Kotlin/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bitmap-Bresenhams-line-algorithm b/Lang/Kotlin/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..713e4c846b --- /dev/null +++ b/Lang/Kotlin/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bitmap-Flood-fill b/Lang/Kotlin/Bitmap-Flood-fill new file mode 120000 index 0000000000..bbef5df2c3 --- /dev/null +++ b/Lang/Kotlin/Bitmap-Flood-fill @@ -0,0 +1 @@ +../../Task/Bitmap-Flood-fill/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bitmap-Midpoint-circle-algorithm b/Lang/Kotlin/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..5aac5f97d1 --- /dev/null +++ b/Lang/Kotlin/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bitwise-operations b/Lang/Kotlin/Bitwise-operations new file mode 120000 index 0000000000..f49344d4a3 --- /dev/null +++ b/Lang/Kotlin/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Box-the-compass b/Lang/Kotlin/Box-the-compass new file mode 120000 index 0000000000..a51dc11aff --- /dev/null +++ b/Lang/Kotlin/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Break-OO-privacy b/Lang/Kotlin/Break-OO-privacy new file mode 120000 index 0000000000..4d8392523e --- /dev/null +++ b/Lang/Kotlin/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Brownian-tree b/Lang/Kotlin/Brownian-tree new file mode 120000 index 0000000000..e2030dd3d6 --- /dev/null +++ b/Lang/Kotlin/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bulls-and-cows b/Lang/Kotlin/Bulls-and-cows new file mode 120000 index 0000000000..8c0fe0b545 --- /dev/null +++ b/Lang/Kotlin/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bulls-and-cows-Player b/Lang/Kotlin/Bulls-and-cows-Player new file mode 120000 index 0000000000..d9c925db50 --- /dev/null +++ b/Lang/Kotlin/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/CRC-32 b/Lang/Kotlin/CRC-32 new file mode 120000 index 0000000000..994c9d1268 --- /dev/null +++ b/Lang/Kotlin/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/CSV-data-manipulation b/Lang/Kotlin/CSV-data-manipulation new file mode 120000 index 0000000000..66ef287daf --- /dev/null +++ b/Lang/Kotlin/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/CSV-to-HTML-translation b/Lang/Kotlin/CSV-to-HTML-translation new file mode 120000 index 0000000000..959b7df138 --- /dev/null +++ b/Lang/Kotlin/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Caesar-cipher b/Lang/Kotlin/Caesar-cipher new file mode 120000 index 0000000000..a11121c793 --- /dev/null +++ b/Lang/Kotlin/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Calendar---for-REAL-programmers b/Lang/Kotlin/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..cfdc3d5ba5 --- /dev/null +++ b/Lang/Kotlin/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Call-a-foreign-language-function b/Lang/Kotlin/Call-a-foreign-language-function new file mode 120000 index 0000000000..37d69b93bc --- /dev/null +++ b/Lang/Kotlin/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Call-a-function b/Lang/Kotlin/Call-a-function new file mode 120000 index 0000000000..2a12383b51 --- /dev/null +++ b/Lang/Kotlin/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Call-an-object-method b/Lang/Kotlin/Call-an-object-method new file mode 120000 index 0000000000..c023e1e5f4 --- /dev/null +++ b/Lang/Kotlin/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Case-sensitivity-of-identifiers b/Lang/Kotlin/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..f87b62fa7f --- /dev/null +++ b/Lang/Kotlin/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Casting-out-nines b/Lang/Kotlin/Casting-out-nines new file mode 120000 index 0000000000..2bc7ccc450 --- /dev/null +++ b/Lang/Kotlin/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Catalan-numbers-Pascals-triangle b/Lang/Kotlin/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..aacdbcbff7 --- /dev/null +++ b/Lang/Kotlin/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Catamorphism b/Lang/Kotlin/Catamorphism new file mode 120000 index 0000000000..35e318574a --- /dev/null +++ b/Lang/Kotlin/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Character-codes b/Lang/Kotlin/Character-codes new file mode 120000 index 0000000000..6e3ab479dd --- /dev/null +++ b/Lang/Kotlin/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Check-Machin-like-formulas b/Lang/Kotlin/Check-Machin-like-formulas new file mode 120000 index 0000000000..b68bc0be68 --- /dev/null +++ b/Lang/Kotlin/Check-Machin-like-formulas @@ -0,0 +1 @@ +../../Task/Check-Machin-like-formulas/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Check-that-file-exists b/Lang/Kotlin/Check-that-file-exists new file mode 120000 index 0000000000..dd935ce10a --- /dev/null +++ b/Lang/Kotlin/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Chinese-remainder-theorem b/Lang/Kotlin/Chinese-remainder-theorem new file mode 120000 index 0000000000..2eab5d9f73 --- /dev/null +++ b/Lang/Kotlin/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Cholesky-decomposition b/Lang/Kotlin/Cholesky-decomposition new file mode 120000 index 0000000000..a6da7b331a --- /dev/null +++ b/Lang/Kotlin/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Classes b/Lang/Kotlin/Classes new file mode 120000 index 0000000000..c5087152fc --- /dev/null +++ b/Lang/Kotlin/Classes @@ -0,0 +1 @@ +../../Task/Classes/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Closest-pair-problem b/Lang/Kotlin/Closest-pair-problem new file mode 120000 index 0000000000..0aab8009c6 --- /dev/null +++ b/Lang/Kotlin/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Closures-Value-capture b/Lang/Kotlin/Closures-Value-capture new file mode 120000 index 0000000000..556f8c23ef --- /dev/null +++ b/Lang/Kotlin/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Collections b/Lang/Kotlin/Collections new file mode 120000 index 0000000000..312fc8e29d --- /dev/null +++ b/Lang/Kotlin/Collections @@ -0,0 +1 @@ +../../Task/Collections/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Colour-bars-Display b/Lang/Kotlin/Colour-bars-Display new file mode 120000 index 0000000000..62c46796bc --- /dev/null +++ b/Lang/Kotlin/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Colour-pinstripe-Display b/Lang/Kotlin/Colour-pinstripe-Display new file mode 120000 index 0000000000..9813204c6c --- /dev/null +++ b/Lang/Kotlin/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Combinations b/Lang/Kotlin/Combinations new file mode 120000 index 0000000000..c11b389838 --- /dev/null +++ b/Lang/Kotlin/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Combinations-and-permutations b/Lang/Kotlin/Combinations-and-permutations new file mode 120000 index 0000000000..9b0fae8e83 --- /dev/null +++ b/Lang/Kotlin/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Combinations-with-repetitions b/Lang/Kotlin/Combinations-with-repetitions new file mode 120000 index 0000000000..535f9885e4 --- /dev/null +++ b/Lang/Kotlin/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Comma-quibbling b/Lang/Kotlin/Comma-quibbling new file mode 120000 index 0000000000..e1277f5a73 --- /dev/null +++ b/Lang/Kotlin/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Comments b/Lang/Kotlin/Comments new file mode 120000 index 0000000000..e0f051927d --- /dev/null +++ b/Lang/Kotlin/Comments @@ -0,0 +1 @@ +../../Task/Comments/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Compile-time-calculation b/Lang/Kotlin/Compile-time-calculation new file mode 120000 index 0000000000..b41774c8ac --- /dev/null +++ b/Lang/Kotlin/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Compound-data-type b/Lang/Kotlin/Compound-data-type new file mode 120000 index 0000000000..03097fd74c --- /dev/null +++ b/Lang/Kotlin/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Concurrent-computing b/Lang/Kotlin/Concurrent-computing new file mode 120000 index 0000000000..90742dfc73 --- /dev/null +++ b/Lang/Kotlin/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Conditional-structures b/Lang/Kotlin/Conditional-structures new file mode 120000 index 0000000000..29cc1b3e48 --- /dev/null +++ b/Lang/Kotlin/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Conjugate-transpose b/Lang/Kotlin/Conjugate-transpose new file mode 120000 index 0000000000..e1572392b0 --- /dev/null +++ b/Lang/Kotlin/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Constrained-genericity b/Lang/Kotlin/Constrained-genericity new file mode 120000 index 0000000000..d76fa305cb --- /dev/null +++ b/Lang/Kotlin/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Constrained-random-points-on-a-circle b/Lang/Kotlin/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..5ed8f6aa61 --- /dev/null +++ b/Lang/Kotlin/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Continued-fraction b/Lang/Kotlin/Continued-fraction new file mode 120000 index 0000000000..7b51078d22 --- /dev/null +++ b/Lang/Kotlin/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/Kotlin/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..2dedc047b7 --- /dev/null +++ b/Lang/Kotlin/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- b/Lang/Kotlin/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- new file mode 120000 index 0000000000..8c55b80c1c --- /dev/null +++ b/Lang/Kotlin/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Convert-decimal-number-to-rational b/Lang/Kotlin/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..62153dff18 --- /dev/null +++ b/Lang/Kotlin/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Count-in-factors b/Lang/Kotlin/Count-in-factors new file mode 120000 index 0000000000..b9e704c1b3 --- /dev/null +++ b/Lang/Kotlin/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Count-in-octal b/Lang/Kotlin/Count-in-octal new file mode 120000 index 0000000000..260d10020e --- /dev/null +++ b/Lang/Kotlin/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Count-occurrences-of-a-substring b/Lang/Kotlin/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..66e66ee198 --- /dev/null +++ b/Lang/Kotlin/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Count-the-coins b/Lang/Kotlin/Count-the-coins new file mode 120000 index 0000000000..1b98962dda --- /dev/null +++ b/Lang/Kotlin/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Create-a-file b/Lang/Kotlin/Create-a-file new file mode 120000 index 0000000000..ec699bc15d --- /dev/null +++ b/Lang/Kotlin/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Create-a-file-on-magnetic-tape b/Lang/Kotlin/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..71434732f5 --- /dev/null +++ b/Lang/Kotlin/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Create-an-HTML-table b/Lang/Kotlin/Create-an-HTML-table new file mode 120000 index 0000000000..df383a21d5 --- /dev/null +++ b/Lang/Kotlin/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Create-an-object-at-a-given-address b/Lang/Kotlin/Create-an-object-at-a-given-address new file mode 120000 index 0000000000..692b82eeda --- /dev/null +++ b/Lang/Kotlin/Create-an-object-at-a-given-address @@ -0,0 +1 @@ +../../Task/Create-an-object-at-a-given-address/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Currying b/Lang/Kotlin/Currying new file mode 120000 index 0000000000..8324378c01 --- /dev/null +++ b/Lang/Kotlin/Currying @@ -0,0 +1 @@ +../../Task/Currying/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Cut-a-rectangle b/Lang/Kotlin/Cut-a-rectangle new file mode 120000 index 0000000000..452e123954 --- /dev/null +++ b/Lang/Kotlin/Cut-a-rectangle @@ -0,0 +1 @@ +../../Task/Cut-a-rectangle/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/DNS-query b/Lang/Kotlin/DNS-query new file mode 120000 index 0000000000..d724dcc53f --- /dev/null +++ b/Lang/Kotlin/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Date-format b/Lang/Kotlin/Date-format new file mode 120000 index 0000000000..665436aac4 --- /dev/null +++ b/Lang/Kotlin/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Date-manipulation b/Lang/Kotlin/Date-manipulation new file mode 120000 index 0000000000..9049e4cdce --- /dev/null +++ b/Lang/Kotlin/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Day-of-the-week b/Lang/Kotlin/Day-of-the-week new file mode 120000 index 0000000000..8e8acb174b --- /dev/null +++ b/Lang/Kotlin/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Deal-cards-for-FreeCell b/Lang/Kotlin/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..68e71a0869 --- /dev/null +++ b/Lang/Kotlin/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Deconvolution-1D b/Lang/Kotlin/Deconvolution-1D new file mode 120000 index 0000000000..0dfd40f5ec --- /dev/null +++ b/Lang/Kotlin/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Define-a-primitive-data-type b/Lang/Kotlin/Define-a-primitive-data-type new file mode 120000 index 0000000000..6e19385457 --- /dev/null +++ b/Lang/Kotlin/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Delete-a-file b/Lang/Kotlin/Delete-a-file new file mode 120000 index 0000000000..c2cef7ecc5 --- /dev/null +++ b/Lang/Kotlin/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Detect-division-by-zero b/Lang/Kotlin/Detect-division-by-zero new file mode 120000 index 0000000000..8c62988646 --- /dev/null +++ b/Lang/Kotlin/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Determine-if-a-string-is-numeric b/Lang/Kotlin/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..cf49c189ea --- /dev/null +++ b/Lang/Kotlin/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Determine-if-only-one-instance-is-running b/Lang/Kotlin/Determine-if-only-one-instance-is-running new file mode 120000 index 0000000000..ff56785ddf --- /dev/null +++ b/Lang/Kotlin/Determine-if-only-one-instance-is-running @@ -0,0 +1 @@ +../../Task/Determine-if-only-one-instance-is-running/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Digital-root b/Lang/Kotlin/Digital-root new file mode 120000 index 0000000000..4e8612c1be --- /dev/null +++ b/Lang/Kotlin/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Digital-root-Multiplicative-digital-root b/Lang/Kotlin/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..000b1fc482 --- /dev/null +++ b/Lang/Kotlin/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Dinesmans-multiple-dwelling-problem b/Lang/Kotlin/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..f91c445da9 --- /dev/null +++ b/Lang/Kotlin/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Doubly-linked-list-Definition b/Lang/Kotlin/Doubly-linked-list-Definition new file mode 120000 index 0000000000..59b467ef13 --- /dev/null +++ b/Lang/Kotlin/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Doubly-linked-list-Element-definition b/Lang/Kotlin/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..5d77dc6312 --- /dev/null +++ b/Lang/Kotlin/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Doubly-linked-list-Element-insertion b/Lang/Kotlin/Doubly-linked-list-Element-insertion new file mode 120000 index 0000000000..8a49253662 --- /dev/null +++ b/Lang/Kotlin/Doubly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-insertion/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Doubly-linked-list-Traversal b/Lang/Kotlin/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..ea06bc1ae2 --- /dev/null +++ b/Lang/Kotlin/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Dragon-curve b/Lang/Kotlin/Dragon-curve new file mode 120000 index 0000000000..b71f79f8f1 --- /dev/null +++ b/Lang/Kotlin/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Draw-a-clock b/Lang/Kotlin/Draw-a-clock new file mode 120000 index 0000000000..da4512c08a --- /dev/null +++ b/Lang/Kotlin/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Draw-a-cuboid b/Lang/Kotlin/Draw-a-cuboid new file mode 120000 index 0000000000..d033ac9b92 --- /dev/null +++ b/Lang/Kotlin/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Draw-a-sphere b/Lang/Kotlin/Draw-a-sphere new file mode 120000 index 0000000000..bcdc5f3147 --- /dev/null +++ b/Lang/Kotlin/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Dutch-national-flag-problem b/Lang/Kotlin/Dutch-national-flag-problem new file mode 120000 index 0000000000..43a6df6953 --- /dev/null +++ b/Lang/Kotlin/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Dynamic-variable-names b/Lang/Kotlin/Dynamic-variable-names new file mode 120000 index 0000000000..46b57248be --- /dev/null +++ b/Lang/Kotlin/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Echo-server b/Lang/Kotlin/Echo-server new file mode 120000 index 0000000000..16f879224e --- /dev/null +++ b/Lang/Kotlin/Echo-server @@ -0,0 +1 @@ +../../Task/Echo-server/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Empty-directory b/Lang/Kotlin/Empty-directory new file mode 120000 index 0000000000..9ef95cd143 --- /dev/null +++ b/Lang/Kotlin/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Enforced-immutability b/Lang/Kotlin/Enforced-immutability new file mode 120000 index 0000000000..9d68289d63 --- /dev/null +++ b/Lang/Kotlin/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Entropy b/Lang/Kotlin/Entropy new file mode 120000 index 0000000000..89030facf9 --- /dev/null +++ b/Lang/Kotlin/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Enumerations b/Lang/Kotlin/Enumerations new file mode 120000 index 0000000000..026890a8aa --- /dev/null +++ b/Lang/Kotlin/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Environment-variables b/Lang/Kotlin/Environment-variables new file mode 120000 index 0000000000..9aac759215 --- /dev/null +++ b/Lang/Kotlin/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Equilibrium-index b/Lang/Kotlin/Equilibrium-index new file mode 120000 index 0000000000..73639768a3 --- /dev/null +++ b/Lang/Kotlin/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Ethiopian-multiplication b/Lang/Kotlin/Ethiopian-multiplication new file mode 120000 index 0000000000..e4d12df402 --- /dev/null +++ b/Lang/Kotlin/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Euler-method b/Lang/Kotlin/Euler-method new file mode 120000 index 0000000000..ecac8c2a90 --- /dev/null +++ b/Lang/Kotlin/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Evaluate-binomial-coefficients b/Lang/Kotlin/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..bdd2becb49 --- /dev/null +++ b/Lang/Kotlin/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Even-or-odd b/Lang/Kotlin/Even-or-odd new file mode 120000 index 0000000000..0b54f6af8c --- /dev/null +++ b/Lang/Kotlin/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Evolutionary-algorithm b/Lang/Kotlin/Evolutionary-algorithm new file mode 120000 index 0000000000..e1e1509215 --- /dev/null +++ b/Lang/Kotlin/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Exceptions b/Lang/Kotlin/Exceptions new file mode 120000 index 0000000000..118ee6078f --- /dev/null +++ b/Lang/Kotlin/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Kotlin/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..238c9b3648 --- /dev/null +++ b/Lang/Kotlin/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Execute-Brain---- b/Lang/Kotlin/Execute-Brain---- new file mode 120000 index 0000000000..a06553b87e --- /dev/null +++ b/Lang/Kotlin/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Execute-HQ9+ b/Lang/Kotlin/Execute-HQ9+ new file mode 120000 index 0000000000..5d9fbab37f --- /dev/null +++ b/Lang/Kotlin/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Execute-SNUSP b/Lang/Kotlin/Execute-SNUSP new file mode 120000 index 0000000000..34dc68dd56 --- /dev/null +++ b/Lang/Kotlin/Execute-SNUSP @@ -0,0 +1 @@ +../../Task/Execute-SNUSP/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Execute-a-system-command b/Lang/Kotlin/Execute-a-system-command new file mode 120000 index 0000000000..a22bbc3e69 --- /dev/null +++ b/Lang/Kotlin/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Exponentiation-operator b/Lang/Kotlin/Exponentiation-operator new file mode 120000 index 0000000000..d73be59de3 --- /dev/null +++ b/Lang/Kotlin/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Extend-your-language b/Lang/Kotlin/Extend-your-language new file mode 120000 index 0000000000..d2ba4c7a81 --- /dev/null +++ b/Lang/Kotlin/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Extensible-prime-generator b/Lang/Kotlin/Extensible-prime-generator new file mode 120000 index 0000000000..fb4d4d73fd --- /dev/null +++ b/Lang/Kotlin/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Extreme-floating-point-values b/Lang/Kotlin/Extreme-floating-point-values new file mode 120000 index 0000000000..0c2ca30dae --- /dev/null +++ b/Lang/Kotlin/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Factors-of-a-Mersenne-number b/Lang/Kotlin/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..19ed37036c --- /dev/null +++ b/Lang/Kotlin/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Factors-of-an-integer b/Lang/Kotlin/Factors-of-an-integer new file mode 120000 index 0000000000..9aafbd9627 --- /dev/null +++ b/Lang/Kotlin/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Fibonacci-n-step-number-sequences b/Lang/Kotlin/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..d24977933d --- /dev/null +++ b/Lang/Kotlin/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Fibonacci-word b/Lang/Kotlin/Fibonacci-word new file mode 120000 index 0000000000..f326178816 --- /dev/null +++ b/Lang/Kotlin/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Fibonacci-word-fractal b/Lang/Kotlin/Fibonacci-word-fractal new file mode 120000 index 0000000000..173e5ef76a --- /dev/null +++ b/Lang/Kotlin/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/File-input-output b/Lang/Kotlin/File-input-output new file mode 120000 index 0000000000..07a9938e42 --- /dev/null +++ b/Lang/Kotlin/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/File-modification-time b/Lang/Kotlin/File-modification-time new file mode 120000 index 0000000000..b9f70ebb9c --- /dev/null +++ b/Lang/Kotlin/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/File-size b/Lang/Kotlin/File-size new file mode 120000 index 0000000000..0de46e6ecb --- /dev/null +++ b/Lang/Kotlin/File-size @@ -0,0 +1 @@ +../../Task/File-size/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Filter b/Lang/Kotlin/Filter new file mode 120000 index 0000000000..5b6a792d68 --- /dev/null +++ b/Lang/Kotlin/Filter @@ -0,0 +1 @@ +../../Task/Filter/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/Kotlin/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..08d48cb2bc --- /dev/null +++ b/Lang/Kotlin/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Find-limit-of-recursion b/Lang/Kotlin/Find-limit-of-recursion new file mode 120000 index 0000000000..514ad7ec47 --- /dev/null +++ b/Lang/Kotlin/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Find-the-last-Sunday-of-each-month b/Lang/Kotlin/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..ec02de73b7 --- /dev/null +++ b/Lang/Kotlin/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Find-the-missing-permutation b/Lang/Kotlin/Find-the-missing-permutation new file mode 120000 index 0000000000..a4531e6b67 --- /dev/null +++ b/Lang/Kotlin/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/First-class-environments b/Lang/Kotlin/First-class-environments new file mode 120000 index 0000000000..f5fe406cf8 --- /dev/null +++ b/Lang/Kotlin/First-class-environments @@ -0,0 +1 @@ +../../Task/First-class-environments/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/First-class-functions b/Lang/Kotlin/First-class-functions new file mode 120000 index 0000000000..70bbaa1597 --- /dev/null +++ b/Lang/Kotlin/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/First-class-functions-Use-numbers-analogously b/Lang/Kotlin/First-class-functions-Use-numbers-analogously new file mode 120000 index 0000000000..2d7705817e --- /dev/null +++ b/Lang/Kotlin/First-class-functions-Use-numbers-analogously @@ -0,0 +1 @@ +../../Task/First-class-functions-Use-numbers-analogously/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Five-weekends b/Lang/Kotlin/Five-weekends new file mode 120000 index 0000000000..69cb5d8453 --- /dev/null +++ b/Lang/Kotlin/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Flatten-a-list b/Lang/Kotlin/Flatten-a-list new file mode 120000 index 0000000000..f0dd2e856c --- /dev/null +++ b/Lang/Kotlin/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Flipping-bits-game b/Lang/Kotlin/Flipping-bits-game new file mode 120000 index 0000000000..add796778c --- /dev/null +++ b/Lang/Kotlin/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Flow-control-structures b/Lang/Kotlin/Flow-control-structures new file mode 120000 index 0000000000..8630d2941a --- /dev/null +++ b/Lang/Kotlin/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Formatted-numeric-output b/Lang/Kotlin/Formatted-numeric-output new file mode 120000 index 0000000000..0448ca980d --- /dev/null +++ b/Lang/Kotlin/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Forward-difference b/Lang/Kotlin/Forward-difference new file mode 120000 index 0000000000..07b32ed732 --- /dev/null +++ b/Lang/Kotlin/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Fractal-tree b/Lang/Kotlin/Fractal-tree new file mode 120000 index 0000000000..f83eb29edc --- /dev/null +++ b/Lang/Kotlin/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Fractran b/Lang/Kotlin/Fractran new file mode 120000 index 0000000000..a68d5869c6 --- /dev/null +++ b/Lang/Kotlin/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Function-composition b/Lang/Kotlin/Function-composition new file mode 120000 index 0000000000..cb820d47c9 --- /dev/null +++ b/Lang/Kotlin/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Function-prototype b/Lang/Kotlin/Function-prototype new file mode 120000 index 0000000000..5294474eaa --- /dev/null +++ b/Lang/Kotlin/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/GUI-Maximum-window-dimensions b/Lang/Kotlin/GUI-Maximum-window-dimensions new file mode 120000 index 0000000000..f923e20300 --- /dev/null +++ b/Lang/Kotlin/GUI-Maximum-window-dimensions @@ -0,0 +1 @@ +../../Task/GUI-Maximum-window-dimensions/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Gamma-function b/Lang/Kotlin/Gamma-function new file mode 120000 index 0000000000..2a14f5df86 --- /dev/null +++ b/Lang/Kotlin/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Generate-lower-case-ASCII-alphabet b/Lang/Kotlin/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..cb73296470 --- /dev/null +++ b/Lang/Kotlin/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Generator-Exponential b/Lang/Kotlin/Generator-Exponential new file mode 120000 index 0000000000..5ac0a60119 --- /dev/null +++ b/Lang/Kotlin/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Generic-swap b/Lang/Kotlin/Generic-swap new file mode 120000 index 0000000000..05f5bd6fb0 --- /dev/null +++ b/Lang/Kotlin/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Gray-code b/Lang/Kotlin/Gray-code new file mode 120000 index 0000000000..2b1bd5cae1 --- /dev/null +++ b/Lang/Kotlin/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Greatest-element-of-a-list b/Lang/Kotlin/Greatest-element-of-a-list new file mode 120000 index 0000000000..e70af142b2 --- /dev/null +++ b/Lang/Kotlin/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Greatest-subsequential-sum b/Lang/Kotlin/Greatest-subsequential-sum new file mode 120000 index 0000000000..5a943f9315 --- /dev/null +++ b/Lang/Kotlin/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Greyscale-bars-Display b/Lang/Kotlin/Greyscale-bars-Display new file mode 120000 index 0000000000..07d19b4ce9 --- /dev/null +++ b/Lang/Kotlin/Greyscale-bars-Display @@ -0,0 +1 @@ +../../Task/Greyscale-bars-Display/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Guess-the-number b/Lang/Kotlin/Guess-the-number new file mode 120000 index 0000000000..848c8b355c --- /dev/null +++ b/Lang/Kotlin/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Guess-the-number-With-feedback b/Lang/Kotlin/Guess-the-number-With-feedback new file mode 120000 index 0000000000..4382986fe1 --- /dev/null +++ b/Lang/Kotlin/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Guess-the-number-With-feedback--player- b/Lang/Kotlin/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..ef314ac6f0 --- /dev/null +++ b/Lang/Kotlin/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/HTTP b/Lang/Kotlin/HTTP new file mode 120000 index 0000000000..c258788088 --- /dev/null +++ b/Lang/Kotlin/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/HTTPS b/Lang/Kotlin/HTTPS new file mode 120000 index 0000000000..193c814e6e --- /dev/null +++ b/Lang/Kotlin/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Handle-a-signal b/Lang/Kotlin/Handle-a-signal new file mode 120000 index 0000000000..6fcfd577f0 --- /dev/null +++ b/Lang/Kotlin/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Happy-numbers b/Lang/Kotlin/Happy-numbers new file mode 120000 index 0000000000..6631fe29bc --- /dev/null +++ b/Lang/Kotlin/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Harshad-or-Niven-series b/Lang/Kotlin/Harshad-or-Niven-series new file mode 120000 index 0000000000..228781ce8c --- /dev/null +++ b/Lang/Kotlin/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Hash-from-two-arrays b/Lang/Kotlin/Hash-from-two-arrays new file mode 120000 index 0000000000..bf9ac26b4a --- /dev/null +++ b/Lang/Kotlin/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Hash-join b/Lang/Kotlin/Hash-join new file mode 120000 index 0000000000..021b2963f0 --- /dev/null +++ b/Lang/Kotlin/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Hello-world-Line-printer b/Lang/Kotlin/Hello-world-Line-printer new file mode 120000 index 0000000000..8c36bb76b9 --- /dev/null +++ b/Lang/Kotlin/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Hello-world-Newbie b/Lang/Kotlin/Hello-world-Newbie new file mode 120000 index 0000000000..cb07d23370 --- /dev/null +++ b/Lang/Kotlin/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Hello-world-Standard-error b/Lang/Kotlin/Hello-world-Standard-error new file mode 120000 index 0000000000..f0c0b3701b --- /dev/null +++ b/Lang/Kotlin/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Hello-world-Web-server b/Lang/Kotlin/Hello-world-Web-server new file mode 120000 index 0000000000..8030a5e936 --- /dev/null +++ b/Lang/Kotlin/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Here-document b/Lang/Kotlin/Here-document new file mode 120000 index 0000000000..d1fc71fbad --- /dev/null +++ b/Lang/Kotlin/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Hickerson-series-of-almost-integers b/Lang/Kotlin/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..814f617b4f --- /dev/null +++ b/Lang/Kotlin/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/History-variables b/Lang/Kotlin/History-variables new file mode 120000 index 0000000000..06b4e8c0b2 --- /dev/null +++ b/Lang/Kotlin/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Hofstadter-Conway-$10,000-sequence b/Lang/Kotlin/Hofstadter-Conway-$10,000-sequence new file mode 120000 index 0000000000..ac521c1cfd --- /dev/null +++ b/Lang/Kotlin/Hofstadter-Conway-$10,000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10,000-sequence/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Hofstadter-Q-sequence b/Lang/Kotlin/Hofstadter-Q-sequence new file mode 120000 index 0000000000..8a6d7d658b --- /dev/null +++ b/Lang/Kotlin/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Holidays-related-to-Easter b/Lang/Kotlin/Holidays-related-to-Easter new file mode 120000 index 0000000000..9bd2f40c82 --- /dev/null +++ b/Lang/Kotlin/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Honeycombs b/Lang/Kotlin/Honeycombs new file mode 120000 index 0000000000..cef309bece --- /dev/null +++ b/Lang/Kotlin/Honeycombs @@ -0,0 +1 @@ +../../Task/Honeycombs/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Horizontal-sundial-calculations b/Lang/Kotlin/Horizontal-sundial-calculations new file mode 120000 index 0000000000..9982440a6b --- /dev/null +++ b/Lang/Kotlin/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Horners-rule-for-polynomial-evaluation b/Lang/Kotlin/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..42873901c2 --- /dev/null +++ b/Lang/Kotlin/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Host-introspection b/Lang/Kotlin/Host-introspection new file mode 120000 index 0000000000..cae3e9db28 --- /dev/null +++ b/Lang/Kotlin/Host-introspection @@ -0,0 +1 @@ +../../Task/Host-introspection/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Hostname b/Lang/Kotlin/Hostname new file mode 120000 index 0000000000..5dc05b179c --- /dev/null +++ b/Lang/Kotlin/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/I-before-E-except-after-C b/Lang/Kotlin/I-before-E-except-after-C new file mode 120000 index 0000000000..1d6c669422 --- /dev/null +++ b/Lang/Kotlin/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/IBAN b/Lang/Kotlin/IBAN new file mode 120000 index 0000000000..c154d96274 --- /dev/null +++ b/Lang/Kotlin/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Identity-matrix b/Lang/Kotlin/Identity-matrix new file mode 120000 index 0000000000..362306fde4 --- /dev/null +++ b/Lang/Kotlin/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Include-a-file b/Lang/Kotlin/Include-a-file new file mode 120000 index 0000000000..80c4806fb7 --- /dev/null +++ b/Lang/Kotlin/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Increment-a-numerical-string b/Lang/Kotlin/Increment-a-numerical-string new file mode 120000 index 0000000000..bf44df7e95 --- /dev/null +++ b/Lang/Kotlin/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Inheritance-Single b/Lang/Kotlin/Inheritance-Single new file mode 120000 index 0000000000..8166e54ea7 --- /dev/null +++ b/Lang/Kotlin/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Input-loop b/Lang/Kotlin/Input-loop new file mode 120000 index 0000000000..59db30bb7e --- /dev/null +++ b/Lang/Kotlin/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Integer-overflow b/Lang/Kotlin/Integer-overflow new file mode 120000 index 0000000000..4b48fc2baa --- /dev/null +++ b/Lang/Kotlin/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Integer-sequence b/Lang/Kotlin/Integer-sequence new file mode 120000 index 0000000000..0fa7c2b164 --- /dev/null +++ b/Lang/Kotlin/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Interactive-programming b/Lang/Kotlin/Interactive-programming new file mode 120000 index 0000000000..f0164dfcd3 --- /dev/null +++ b/Lang/Kotlin/Interactive-programming @@ -0,0 +1 @@ +../../Task/Interactive-programming/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Introspection b/Lang/Kotlin/Introspection new file mode 120000 index 0000000000..c1a8ad7f78 --- /dev/null +++ b/Lang/Kotlin/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Inverted-syntax b/Lang/Kotlin/Inverted-syntax new file mode 120000 index 0000000000..69223bc01d --- /dev/null +++ b/Lang/Kotlin/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Iterated-digits-squaring b/Lang/Kotlin/Iterated-digits-squaring new file mode 120000 index 0000000000..676793b04b --- /dev/null +++ b/Lang/Kotlin/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Josephus-problem b/Lang/Kotlin/Josephus-problem new file mode 120000 index 0000000000..d5a1e2c11d --- /dev/null +++ b/Lang/Kotlin/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Jump-anywhere b/Lang/Kotlin/Jump-anywhere new file mode 120000 index 0000000000..74a75506ab --- /dev/null +++ b/Lang/Kotlin/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Keyboard-input-Flush-the-keyboard-buffer b/Lang/Kotlin/Keyboard-input-Flush-the-keyboard-buffer new file mode 120000 index 0000000000..ed31241f7f --- /dev/null +++ b/Lang/Kotlin/Keyboard-input-Flush-the-keyboard-buffer @@ -0,0 +1 @@ +../../Task/Keyboard-input-Flush-the-keyboard-buffer/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Keyboard-input-Keypress-check b/Lang/Kotlin/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..a667a95aad --- /dev/null +++ b/Lang/Kotlin/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/Kotlin/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..a66fc73c8b --- /dev/null +++ b/Lang/Kotlin/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Knapsack-problem-0-1 b/Lang/Kotlin/Knapsack-problem-0-1 new file mode 120000 index 0000000000..13d7b6a8de --- /dev/null +++ b/Lang/Kotlin/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Knapsack-problem-Bounded b/Lang/Kotlin/Knapsack-problem-Bounded new file mode 120000 index 0000000000..eeed6db4fc --- /dev/null +++ b/Lang/Kotlin/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Knapsack-problem-Continuous b/Lang/Kotlin/Knapsack-problem-Continuous new file mode 120000 index 0000000000..7f048aa6c4 --- /dev/null +++ b/Lang/Kotlin/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Knapsack-problem-Unbounded b/Lang/Kotlin/Knapsack-problem-Unbounded new file mode 120000 index 0000000000..6052136ef7 --- /dev/null +++ b/Lang/Kotlin/Knapsack-problem-Unbounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Unbounded/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Knuths-algorithm-S b/Lang/Kotlin/Knuths-algorithm-S new file mode 120000 index 0000000000..9ca9f1f9c3 --- /dev/null +++ b/Lang/Kotlin/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/LZW-compression b/Lang/Kotlin/LZW-compression new file mode 120000 index 0000000000..b3214e1550 --- /dev/null +++ b/Lang/Kotlin/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Last-Friday-of-each-month b/Lang/Kotlin/Last-Friday-of-each-month new file mode 120000 index 0000000000..906c941606 --- /dev/null +++ b/Lang/Kotlin/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Last-letter-first-letter b/Lang/Kotlin/Last-letter-first-letter new file mode 120000 index 0000000000..d5fb99e117 --- /dev/null +++ b/Lang/Kotlin/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Left-factorials b/Lang/Kotlin/Left-factorials new file mode 120000 index 0000000000..fdab28b23c --- /dev/null +++ b/Lang/Kotlin/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Letter-frequency b/Lang/Kotlin/Letter-frequency new file mode 120000 index 0000000000..90211fc39f --- /dev/null +++ b/Lang/Kotlin/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Levenshtein-distance b/Lang/Kotlin/Levenshtein-distance new file mode 120000 index 0000000000..875e8c5ba0 --- /dev/null +++ b/Lang/Kotlin/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Linear-congruential-generator b/Lang/Kotlin/Linear-congruential-generator new file mode 120000 index 0000000000..702abe2892 --- /dev/null +++ b/Lang/Kotlin/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/List-comprehensions b/Lang/Kotlin/List-comprehensions new file mode 120000 index 0000000000..28370ffc34 --- /dev/null +++ b/Lang/Kotlin/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Literals-Integer b/Lang/Kotlin/Literals-Integer new file mode 120000 index 0000000000..818bb74432 --- /dev/null +++ b/Lang/Kotlin/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Literals-String b/Lang/Kotlin/Literals-String new file mode 120000 index 0000000000..aa1390c7b6 --- /dev/null +++ b/Lang/Kotlin/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Logical-operations b/Lang/Kotlin/Logical-operations new file mode 120000 index 0000000000..de20fabaaa --- /dev/null +++ b/Lang/Kotlin/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Longest-common-subsequence b/Lang/Kotlin/Longest-common-subsequence new file mode 120000 index 0000000000..11bc911acb --- /dev/null +++ b/Lang/Kotlin/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Longest-increasing-subsequence b/Lang/Kotlin/Longest-increasing-subsequence new file mode 120000 index 0000000000..ced037a007 --- /dev/null +++ b/Lang/Kotlin/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Longest-string-challenge b/Lang/Kotlin/Longest-string-challenge new file mode 120000 index 0000000000..04984b72a3 --- /dev/null +++ b/Lang/Kotlin/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Look-and-say-sequence b/Lang/Kotlin/Look-and-say-sequence new file mode 120000 index 0000000000..efc8a7672e --- /dev/null +++ b/Lang/Kotlin/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Loop-over-multiple-arrays-simultaneously b/Lang/Kotlin/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..250934d3ed --- /dev/null +++ b/Lang/Kotlin/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Loops-Continue b/Lang/Kotlin/Loops-Continue new file mode 120000 index 0000000000..124575c0eb --- /dev/null +++ b/Lang/Kotlin/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Loops-Do-while b/Lang/Kotlin/Loops-Do-while new file mode 120000 index 0000000000..fc5bb9a331 --- /dev/null +++ b/Lang/Kotlin/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Loops-Downward-for b/Lang/Kotlin/Loops-Downward-for new file mode 120000 index 0000000000..aae73a5182 --- /dev/null +++ b/Lang/Kotlin/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Loops-For-with-a-specified-step b/Lang/Kotlin/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..b7fffcafe4 --- /dev/null +++ b/Lang/Kotlin/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Loops-Foreach b/Lang/Kotlin/Loops-Foreach new file mode 120000 index 0000000000..3befe0dbb6 --- /dev/null +++ b/Lang/Kotlin/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Loops-Infinite b/Lang/Kotlin/Loops-Infinite new file mode 120000 index 0000000000..faf31c374b --- /dev/null +++ b/Lang/Kotlin/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Loops-N-plus-one-half b/Lang/Kotlin/Loops-N-plus-one-half new file mode 120000 index 0000000000..311c557755 --- /dev/null +++ b/Lang/Kotlin/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Loops-While b/Lang/Kotlin/Loops-While new file mode 120000 index 0000000000..cb528d24e9 --- /dev/null +++ b/Lang/Kotlin/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Lucas-Lehmer-test b/Lang/Kotlin/Lucas-Lehmer-test new file mode 120000 index 0000000000..35ed938a22 --- /dev/null +++ b/Lang/Kotlin/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Ludic-numbers b/Lang/Kotlin/Ludic-numbers new file mode 120000 index 0000000000..0a573a5c2f --- /dev/null +++ b/Lang/Kotlin/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Luhn-test-of-credit-card-numbers b/Lang/Kotlin/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..69341462b2 --- /dev/null +++ b/Lang/Kotlin/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/MD4 b/Lang/Kotlin/MD4 new file mode 120000 index 0000000000..51e04db4c0 --- /dev/null +++ b/Lang/Kotlin/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/MD5 b/Lang/Kotlin/MD5 new file mode 120000 index 0000000000..4cdce91e34 --- /dev/null +++ b/Lang/Kotlin/MD5 @@ -0,0 +1 @@ +../../Task/MD5/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/MD5-Implementation b/Lang/Kotlin/MD5-Implementation new file mode 120000 index 0000000000..d45c5a4d94 --- /dev/null +++ b/Lang/Kotlin/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Machine-code b/Lang/Kotlin/Machine-code new file mode 120000 index 0000000000..a31e5fea30 --- /dev/null +++ b/Lang/Kotlin/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Mad-Libs b/Lang/Kotlin/Mad-Libs new file mode 120000 index 0000000000..7dab1ddd0c --- /dev/null +++ b/Lang/Kotlin/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Magic-squares-of-odd-order b/Lang/Kotlin/Magic-squares-of-odd-order new file mode 120000 index 0000000000..dd50d1ecf5 --- /dev/null +++ b/Lang/Kotlin/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Make-directory-path b/Lang/Kotlin/Make-directory-path new file mode 120000 index 0000000000..67ee089d07 --- /dev/null +++ b/Lang/Kotlin/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Man-or-boy-test b/Lang/Kotlin/Man-or-boy-test new file mode 120000 index 0000000000..56a9331633 --- /dev/null +++ b/Lang/Kotlin/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Mandelbrot-set b/Lang/Kotlin/Mandelbrot-set new file mode 120000 index 0000000000..c3397a2262 --- /dev/null +++ b/Lang/Kotlin/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Map-range b/Lang/Kotlin/Map-range new file mode 120000 index 0000000000..d8074bd024 --- /dev/null +++ b/Lang/Kotlin/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Matrix-arithmetic b/Lang/Kotlin/Matrix-arithmetic new file mode 120000 index 0000000000..b53a643566 --- /dev/null +++ b/Lang/Kotlin/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Matrix-exponentiation-operator b/Lang/Kotlin/Matrix-exponentiation-operator new file mode 120000 index 0000000000..868feba271 --- /dev/null +++ b/Lang/Kotlin/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Matrix-multiplication b/Lang/Kotlin/Matrix-multiplication new file mode 120000 index 0000000000..a0d4b5ea61 --- /dev/null +++ b/Lang/Kotlin/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Matrix-transposition b/Lang/Kotlin/Matrix-transposition new file mode 120000 index 0000000000..965207e793 --- /dev/null +++ b/Lang/Kotlin/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Maximum-triangle-path-sum b/Lang/Kotlin/Maximum-triangle-path-sum new file mode 120000 index 0000000000..3b497395d0 --- /dev/null +++ b/Lang/Kotlin/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Memory-allocation b/Lang/Kotlin/Memory-allocation new file mode 120000 index 0000000000..c5cbc841f4 --- /dev/null +++ b/Lang/Kotlin/Memory-allocation @@ -0,0 +1 @@ +../../Task/Memory-allocation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Memory-layout-of-a-data-structure b/Lang/Kotlin/Memory-layout-of-a-data-structure new file mode 120000 index 0000000000..001dba3c2b --- /dev/null +++ b/Lang/Kotlin/Memory-layout-of-a-data-structure @@ -0,0 +1 @@ +../../Task/Memory-layout-of-a-data-structure/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Menu b/Lang/Kotlin/Menu new file mode 120000 index 0000000000..3b751993cb --- /dev/null +++ b/Lang/Kotlin/Menu @@ -0,0 +1 @@ +../../Task/Menu/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Metaprogramming b/Lang/Kotlin/Metaprogramming new file mode 120000 index 0000000000..ae5a298fee --- /dev/null +++ b/Lang/Kotlin/Metaprogramming @@ -0,0 +1 @@ +../../Task/Metaprogramming/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Metronome b/Lang/Kotlin/Metronome new file mode 120000 index 0000000000..213e02f151 --- /dev/null +++ b/Lang/Kotlin/Metronome @@ -0,0 +1 @@ +../../Task/Metronome/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Modular-exponentiation b/Lang/Kotlin/Modular-exponentiation new file mode 120000 index 0000000000..56adb9fad3 --- /dev/null +++ b/Lang/Kotlin/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Modular-inverse b/Lang/Kotlin/Modular-inverse new file mode 120000 index 0000000000..adc30300a1 --- /dev/null +++ b/Lang/Kotlin/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Monte-Carlo-methods b/Lang/Kotlin/Monte-Carlo-methods new file mode 120000 index 0000000000..38e13d5089 --- /dev/null +++ b/Lang/Kotlin/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Monty-Hall-problem b/Lang/Kotlin/Monty-Hall-problem new file mode 120000 index 0000000000..2e46ffb5a7 --- /dev/null +++ b/Lang/Kotlin/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Mouse-position b/Lang/Kotlin/Mouse-position new file mode 120000 index 0000000000..2bc59fab96 --- /dev/null +++ b/Lang/Kotlin/Mouse-position @@ -0,0 +1 @@ +../../Task/Mouse-position/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Move-to-front-algorithm b/Lang/Kotlin/Move-to-front-algorithm new file mode 120000 index 0000000000..372c289577 --- /dev/null +++ b/Lang/Kotlin/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Multiple-distinct-objects b/Lang/Kotlin/Multiple-distinct-objects new file mode 120000 index 0000000000..69d39e4e33 --- /dev/null +++ b/Lang/Kotlin/Multiple-distinct-objects @@ -0,0 +1 @@ +../../Task/Multiple-distinct-objects/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Multiplication-tables b/Lang/Kotlin/Multiplication-tables new file mode 120000 index 0000000000..2311826d66 --- /dev/null +++ b/Lang/Kotlin/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Multisplit b/Lang/Kotlin/Multisplit new file mode 120000 index 0000000000..aaede459f5 --- /dev/null +++ b/Lang/Kotlin/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Mutual-recursion b/Lang/Kotlin/Mutual-recursion new file mode 120000 index 0000000000..4341d6c1c6 --- /dev/null +++ b/Lang/Kotlin/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/N-queens-problem b/Lang/Kotlin/N-queens-problem new file mode 120000 index 0000000000..4adc2887dc --- /dev/null +++ b/Lang/Kotlin/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Named-parameters b/Lang/Kotlin/Named-parameters new file mode 120000 index 0000000000..3dcb1ad9cb --- /dev/null +++ b/Lang/Kotlin/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Narcissist b/Lang/Kotlin/Narcissist new file mode 120000 index 0000000000..d1dc37a74c --- /dev/null +++ b/Lang/Kotlin/Narcissist @@ -0,0 +1 @@ +../../Task/Narcissist/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Narcissistic-decimal-number b/Lang/Kotlin/Narcissistic-decimal-number new file mode 120000 index 0000000000..44518dd5e6 --- /dev/null +++ b/Lang/Kotlin/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Natural-sorting b/Lang/Kotlin/Natural-sorting new file mode 120000 index 0000000000..f53bb6a384 --- /dev/null +++ b/Lang/Kotlin/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Nautical-bell b/Lang/Kotlin/Nautical-bell new file mode 120000 index 0000000000..4224ed94b2 --- /dev/null +++ b/Lang/Kotlin/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Non-continuous-subsequences b/Lang/Kotlin/Non-continuous-subsequences new file mode 120000 index 0000000000..dce8e9e486 --- /dev/null +++ b/Lang/Kotlin/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Non-decimal-radices-Convert b/Lang/Kotlin/Non-decimal-radices-Convert new file mode 120000 index 0000000000..710e536fe1 --- /dev/null +++ b/Lang/Kotlin/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Non-decimal-radices-Input b/Lang/Kotlin/Non-decimal-radices-Input new file mode 120000 index 0000000000..9b57c37792 --- /dev/null +++ b/Lang/Kotlin/Non-decimal-radices-Input @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Input/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Non-decimal-radices-Output b/Lang/Kotlin/Non-decimal-radices-Output new file mode 120000 index 0000000000..ec60c7d1db --- /dev/null +++ b/Lang/Kotlin/Non-decimal-radices-Output @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Output/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Nth-root b/Lang/Kotlin/Nth-root new file mode 120000 index 0000000000..7e5e1475c8 --- /dev/null +++ b/Lang/Kotlin/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Null-object b/Lang/Kotlin/Null-object new file mode 120000 index 0000000000..3391bf7cb1 --- /dev/null +++ b/Lang/Kotlin/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Number-names b/Lang/Kotlin/Number-names new file mode 120000 index 0000000000..e3cd4c9a95 --- /dev/null +++ b/Lang/Kotlin/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Number-reversal-game b/Lang/Kotlin/Number-reversal-game new file mode 120000 index 0000000000..995e9ea78e --- /dev/null +++ b/Lang/Kotlin/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Numerical-integration b/Lang/Kotlin/Numerical-integration new file mode 120000 index 0000000000..aafa422cda --- /dev/null +++ b/Lang/Kotlin/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Odd-word-problem b/Lang/Kotlin/Odd-word-problem new file mode 120000 index 0000000000..605721a5d1 --- /dev/null +++ b/Lang/Kotlin/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Old-lady-swallowed-a-fly b/Lang/Kotlin/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..da5744ea3f --- /dev/null +++ b/Lang/Kotlin/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/OpenGL b/Lang/Kotlin/OpenGL new file mode 120000 index 0000000000..7f52a34786 --- /dev/null +++ b/Lang/Kotlin/OpenGL @@ -0,0 +1 @@ +../../Task/OpenGL/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Order-disjoint-list-items b/Lang/Kotlin/Order-disjoint-list-items new file mode 120000 index 0000000000..ded1a58835 --- /dev/null +++ b/Lang/Kotlin/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Order-two-numerical-lists b/Lang/Kotlin/Order-two-numerical-lists new file mode 120000 index 0000000000..5615a559ec --- /dev/null +++ b/Lang/Kotlin/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Ordered-Partitions b/Lang/Kotlin/Ordered-Partitions new file mode 120000 index 0000000000..c3aafcb944 --- /dev/null +++ b/Lang/Kotlin/Ordered-Partitions @@ -0,0 +1 @@ +../../Task/Ordered-Partitions/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Palindrome-detection b/Lang/Kotlin/Palindrome-detection new file mode 120000 index 0000000000..820a7e5e7c --- /dev/null +++ b/Lang/Kotlin/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Pangram-checker b/Lang/Kotlin/Pangram-checker new file mode 120000 index 0000000000..6181a5baa3 --- /dev/null +++ b/Lang/Kotlin/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Paraffins b/Lang/Kotlin/Paraffins new file mode 120000 index 0000000000..467088f129 --- /dev/null +++ b/Lang/Kotlin/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Parametric-polymorphism b/Lang/Kotlin/Parametric-polymorphism new file mode 120000 index 0000000000..727b3cdbd6 --- /dev/null +++ b/Lang/Kotlin/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Parse-an-IP-Address b/Lang/Kotlin/Parse-an-IP-Address new file mode 120000 index 0000000000..c8e4ef0b2b --- /dev/null +++ b/Lang/Kotlin/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Parsing-RPN-calculator-algorithm b/Lang/Kotlin/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..0b3811e8cc --- /dev/null +++ b/Lang/Kotlin/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Partial-function-application b/Lang/Kotlin/Partial-function-application new file mode 120000 index 0000000000..6cd0cf3a44 --- /dev/null +++ b/Lang/Kotlin/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Pascals-triangle-Puzzle b/Lang/Kotlin/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..d87f62e9f8 --- /dev/null +++ b/Lang/Kotlin/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Perfect-numbers b/Lang/Kotlin/Perfect-numbers new file mode 120000 index 0000000000..53ce1986dd --- /dev/null +++ b/Lang/Kotlin/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Permutation-test b/Lang/Kotlin/Permutation-test new file mode 120000 index 0000000000..60f07e260b --- /dev/null +++ b/Lang/Kotlin/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Permutations b/Lang/Kotlin/Permutations new file mode 120000 index 0000000000..0a1381e3f6 --- /dev/null +++ b/Lang/Kotlin/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Permutations-Derangements b/Lang/Kotlin/Permutations-Derangements new file mode 120000 index 0000000000..5aa59d8b34 --- /dev/null +++ b/Lang/Kotlin/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Permutations-Rank-of-a-permutation b/Lang/Kotlin/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..b475476a2e --- /dev/null +++ b/Lang/Kotlin/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Permutations-by-swapping b/Lang/Kotlin/Permutations-by-swapping new file mode 120000 index 0000000000..34452278ea --- /dev/null +++ b/Lang/Kotlin/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Pernicious-numbers b/Lang/Kotlin/Pernicious-numbers new file mode 120000 index 0000000000..66cf1515a3 --- /dev/null +++ b/Lang/Kotlin/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Phrase-reversals b/Lang/Kotlin/Phrase-reversals new file mode 120000 index 0000000000..9e9bbe74ff --- /dev/null +++ b/Lang/Kotlin/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Pi b/Lang/Kotlin/Pi new file mode 120000 index 0000000000..f415a50ae0 --- /dev/null +++ b/Lang/Kotlin/Pi @@ -0,0 +1 @@ +../../Task/Pi/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Pick-random-element b/Lang/Kotlin/Pick-random-element new file mode 120000 index 0000000000..b8c0ee55a7 --- /dev/null +++ b/Lang/Kotlin/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Pig-the-dice-game b/Lang/Kotlin/Pig-the-dice-game new file mode 120000 index 0000000000..1ce1d7eaa1 --- /dev/null +++ b/Lang/Kotlin/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Pinstripe-Display b/Lang/Kotlin/Pinstripe-Display new file mode 120000 index 0000000000..acf0a25d8c --- /dev/null +++ b/Lang/Kotlin/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Playing-cards b/Lang/Kotlin/Playing-cards new file mode 120000 index 0000000000..9fe1fad64d --- /dev/null +++ b/Lang/Kotlin/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Pointers-and-references b/Lang/Kotlin/Pointers-and-references new file mode 120000 index 0000000000..e1e2c03b6a --- /dev/null +++ b/Lang/Kotlin/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Polymorphic-copy b/Lang/Kotlin/Polymorphic-copy new file mode 120000 index 0000000000..1b5b9cada6 --- /dev/null +++ b/Lang/Kotlin/Polymorphic-copy @@ -0,0 +1 @@ +../../Task/Polymorphic-copy/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Polymorphism b/Lang/Kotlin/Polymorphism new file mode 120000 index 0000000000..1038fe0562 --- /dev/null +++ b/Lang/Kotlin/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Power-set b/Lang/Kotlin/Power-set new file mode 120000 index 0000000000..cb9bbc9aa1 --- /dev/null +++ b/Lang/Kotlin/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Pragmatic-directives b/Lang/Kotlin/Pragmatic-directives new file mode 120000 index 0000000000..99d7b2485d --- /dev/null +++ b/Lang/Kotlin/Pragmatic-directives @@ -0,0 +1 @@ +../../Task/Pragmatic-directives/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Price-fraction b/Lang/Kotlin/Price-fraction new file mode 120000 index 0000000000..147750c43d --- /dev/null +++ b/Lang/Kotlin/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Primality-by-trial-division b/Lang/Kotlin/Primality-by-trial-division new file mode 120000 index 0000000000..a913bf7430 --- /dev/null +++ b/Lang/Kotlin/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Prime-decomposition b/Lang/Kotlin/Prime-decomposition new file mode 120000 index 0000000000..90762e2064 --- /dev/null +++ b/Lang/Kotlin/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Probabilistic-choice b/Lang/Kotlin/Probabilistic-choice new file mode 120000 index 0000000000..aff5f5396e --- /dev/null +++ b/Lang/Kotlin/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Problem-of-Apollonius b/Lang/Kotlin/Problem-of-Apollonius new file mode 120000 index 0000000000..e336cf41a7 --- /dev/null +++ b/Lang/Kotlin/Problem-of-Apollonius @@ -0,0 +1 @@ +../../Task/Problem-of-Apollonius/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Program-name b/Lang/Kotlin/Program-name new file mode 120000 index 0000000000..6b142cda57 --- /dev/null +++ b/Lang/Kotlin/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Program-termination b/Lang/Kotlin/Program-termination new file mode 120000 index 0000000000..e53fdc6df7 --- /dev/null +++ b/Lang/Kotlin/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Pythagorean-triples b/Lang/Kotlin/Pythagorean-triples new file mode 120000 index 0000000000..819d1945f1 --- /dev/null +++ b/Lang/Kotlin/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Quaternion-type b/Lang/Kotlin/Quaternion-type new file mode 120000 index 0000000000..a85b316d4c --- /dev/null +++ b/Lang/Kotlin/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Queue-Definition b/Lang/Kotlin/Queue-Definition new file mode 120000 index 0000000000..c8a5ce6041 --- /dev/null +++ b/Lang/Kotlin/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Queue-Usage b/Lang/Kotlin/Queue-Usage new file mode 120000 index 0000000000..533e502ee8 --- /dev/null +++ b/Lang/Kotlin/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Quickselect-algorithm b/Lang/Kotlin/Quickselect-algorithm new file mode 120000 index 0000000000..1f0ce00017 --- /dev/null +++ b/Lang/Kotlin/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Quine b/Lang/Kotlin/Quine new file mode 120000 index 0000000000..490b46cda9 --- /dev/null +++ b/Lang/Kotlin/Quine @@ -0,0 +1 @@ +../../Task/Quine/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/RSA-code b/Lang/Kotlin/RSA-code new file mode 120000 index 0000000000..82699241ac --- /dev/null +++ b/Lang/Kotlin/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Random-number-generator--device- b/Lang/Kotlin/Random-number-generator--device- new file mode 120000 index 0000000000..613594d3ca --- /dev/null +++ b/Lang/Kotlin/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Random-numbers b/Lang/Kotlin/Random-numbers new file mode 120000 index 0000000000..4e71d1c01c --- /dev/null +++ b/Lang/Kotlin/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Range-expansion b/Lang/Kotlin/Range-expansion new file mode 120000 index 0000000000..ac0c6af54b --- /dev/null +++ b/Lang/Kotlin/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Range-extraction b/Lang/Kotlin/Range-extraction new file mode 120000 index 0000000000..594db8ad96 --- /dev/null +++ b/Lang/Kotlin/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Ranking-methods b/Lang/Kotlin/Ranking-methods new file mode 120000 index 0000000000..fc34e9bf9c --- /dev/null +++ b/Lang/Kotlin/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Rate-counter b/Lang/Kotlin/Rate-counter new file mode 120000 index 0000000000..f106c498eb --- /dev/null +++ b/Lang/Kotlin/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Read-a-file-line-by-line b/Lang/Kotlin/Read-a-file-line-by-line new file mode 120000 index 0000000000..d6b0807645 --- /dev/null +++ b/Lang/Kotlin/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Read-a-specific-line-from-a-file b/Lang/Kotlin/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..bc0de1bc22 --- /dev/null +++ b/Lang/Kotlin/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Real-constants-and-functions b/Lang/Kotlin/Real-constants-and-functions new file mode 120000 index 0000000000..3319e7feea --- /dev/null +++ b/Lang/Kotlin/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Record-sound b/Lang/Kotlin/Record-sound new file mode 120000 index 0000000000..2c57b6c041 --- /dev/null +++ b/Lang/Kotlin/Record-sound @@ -0,0 +1 @@ +../../Task/Record-sound/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Regular-expressions b/Lang/Kotlin/Regular-expressions new file mode 120000 index 0000000000..cdacb6a22e --- /dev/null +++ b/Lang/Kotlin/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Remove-lines-from-a-file b/Lang/Kotlin/Remove-lines-from-a-file new file mode 120000 index 0000000000..b9ca8e9333 --- /dev/null +++ b/Lang/Kotlin/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Rename-a-file b/Lang/Kotlin/Rename-a-file new file mode 120000 index 0000000000..b630256cd5 --- /dev/null +++ b/Lang/Kotlin/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Rep-string b/Lang/Kotlin/Rep-string new file mode 120000 index 0000000000..52b4abbb24 --- /dev/null +++ b/Lang/Kotlin/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Resistor-mesh b/Lang/Kotlin/Resistor-mesh new file mode 120000 index 0000000000..e6cd844aa2 --- /dev/null +++ b/Lang/Kotlin/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Respond-to-an-unknown-method-call b/Lang/Kotlin/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..e93aa2225e --- /dev/null +++ b/Lang/Kotlin/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Return-multiple-values b/Lang/Kotlin/Return-multiple-values new file mode 120000 index 0000000000..55f3b4a021 --- /dev/null +++ b/Lang/Kotlin/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Reverse-words-in-a-string b/Lang/Kotlin/Reverse-words-in-a-string new file mode 120000 index 0000000000..2bb97b151b --- /dev/null +++ b/Lang/Kotlin/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Roman-numerals-Decode b/Lang/Kotlin/Roman-numerals-Decode new file mode 120000 index 0000000000..924921f113 --- /dev/null +++ b/Lang/Kotlin/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Roots-of-a-function b/Lang/Kotlin/Roots-of-a-function new file mode 120000 index 0000000000..2ee2fb00ce --- /dev/null +++ b/Lang/Kotlin/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Run-length-encoding b/Lang/Kotlin/Run-length-encoding new file mode 120000 index 0000000000..58e28744b1 --- /dev/null +++ b/Lang/Kotlin/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Runge-Kutta-method b/Lang/Kotlin/Runge-Kutta-method new file mode 120000 index 0000000000..9b89d14943 --- /dev/null +++ b/Lang/Kotlin/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Runtime-evaluation-In-an-environment b/Lang/Kotlin/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..16b1da87c1 --- /dev/null +++ b/Lang/Kotlin/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/SEDOLs b/Lang/Kotlin/SEDOLs new file mode 120000 index 0000000000..e59c61fa52 --- /dev/null +++ b/Lang/Kotlin/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/SHA-1 b/Lang/Kotlin/SHA-1 new file mode 120000 index 0000000000..ded9a4039b --- /dev/null +++ b/Lang/Kotlin/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/SHA-256 b/Lang/Kotlin/SHA-256 new file mode 120000 index 0000000000..0730c5d3e5 --- /dev/null +++ b/Lang/Kotlin/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Safe-addition b/Lang/Kotlin/Safe-addition new file mode 120000 index 0000000000..60b1076fe0 --- /dev/null +++ b/Lang/Kotlin/Safe-addition @@ -0,0 +1 @@ +../../Task/Safe-addition/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Scope-Function-names-and-labels b/Lang/Kotlin/Scope-Function-names-and-labels new file mode 120000 index 0000000000..6131866825 --- /dev/null +++ b/Lang/Kotlin/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Scope-modifiers b/Lang/Kotlin/Scope-modifiers new file mode 120000 index 0000000000..9e51bbf60f --- /dev/null +++ b/Lang/Kotlin/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Search-a-list b/Lang/Kotlin/Search-a-list new file mode 120000 index 0000000000..603041af5f --- /dev/null +++ b/Lang/Kotlin/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Secure-temporary-file b/Lang/Kotlin/Secure-temporary-file new file mode 120000 index 0000000000..86e6f5bcf2 --- /dev/null +++ b/Lang/Kotlin/Secure-temporary-file @@ -0,0 +1 @@ +../../Task/Secure-temporary-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Self-describing-numbers b/Lang/Kotlin/Self-describing-numbers new file mode 120000 index 0000000000..1a18b507ad --- /dev/null +++ b/Lang/Kotlin/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Self-referential-sequence b/Lang/Kotlin/Self-referential-sequence new file mode 120000 index 0000000000..2b6fc007d8 --- /dev/null +++ b/Lang/Kotlin/Self-referential-sequence @@ -0,0 +1 @@ +../../Task/Self-referential-sequence/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Semiprime b/Lang/Kotlin/Semiprime new file mode 120000 index 0000000000..ef2c1c7533 --- /dev/null +++ b/Lang/Kotlin/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Send-an-unknown-method-call b/Lang/Kotlin/Send-an-unknown-method-call new file mode 120000 index 0000000000..7753dba648 --- /dev/null +++ b/Lang/Kotlin/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Send-email b/Lang/Kotlin/Send-email new file mode 120000 index 0000000000..979741f75a --- /dev/null +++ b/Lang/Kotlin/Send-email @@ -0,0 +1 @@ +../../Task/Send-email/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sequence-of-non-squares b/Lang/Kotlin/Sequence-of-non-squares new file mode 120000 index 0000000000..bc7fae947d --- /dev/null +++ b/Lang/Kotlin/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sequence-of-primes-by-Trial-Division b/Lang/Kotlin/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..dca8ecb968 --- /dev/null +++ b/Lang/Kotlin/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Set b/Lang/Kotlin/Set new file mode 120000 index 0000000000..05b37a768b --- /dev/null +++ b/Lang/Kotlin/Set @@ -0,0 +1 @@ +../../Task/Set/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Set-consolidation b/Lang/Kotlin/Set-consolidation new file mode 120000 index 0000000000..96b7733866 --- /dev/null +++ b/Lang/Kotlin/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Set-of-real-numbers b/Lang/Kotlin/Set-of-real-numbers new file mode 120000 index 0000000000..ad3c0252d8 --- /dev/null +++ b/Lang/Kotlin/Set-of-real-numbers @@ -0,0 +1 @@ +../../Task/Set-of-real-numbers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Set-puzzle b/Lang/Kotlin/Set-puzzle new file mode 120000 index 0000000000..402cea0b9e --- /dev/null +++ b/Lang/Kotlin/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Seven-sided-dice-from-five-sided-dice b/Lang/Kotlin/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..14b79706db --- /dev/null +++ b/Lang/Kotlin/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Short-circuit-evaluation b/Lang/Kotlin/Short-circuit-evaluation new file mode 120000 index 0000000000..df5e28bbb0 --- /dev/null +++ b/Lang/Kotlin/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Show-the-epoch b/Lang/Kotlin/Show-the-epoch new file mode 120000 index 0000000000..314893d57e --- /dev/null +++ b/Lang/Kotlin/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sierpinski-carpet b/Lang/Kotlin/Sierpinski-carpet new file mode 120000 index 0000000000..4030f10946 --- /dev/null +++ b/Lang/Kotlin/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sierpinski-triangle b/Lang/Kotlin/Sierpinski-triangle new file mode 120000 index 0000000000..d35dd93c8e --- /dev/null +++ b/Lang/Kotlin/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Simple-windowed-application b/Lang/Kotlin/Simple-windowed-application new file mode 120000 index 0000000000..3088aa9d22 --- /dev/null +++ b/Lang/Kotlin/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Simulate-input-Keyboard b/Lang/Kotlin/Simulate-input-Keyboard new file mode 120000 index 0000000000..116d87145c --- /dev/null +++ b/Lang/Kotlin/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Simulate-input-Mouse b/Lang/Kotlin/Simulate-input-Mouse new file mode 120000 index 0000000000..b69e9d1b2c --- /dev/null +++ b/Lang/Kotlin/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Singleton b/Lang/Kotlin/Singleton new file mode 120000 index 0000000000..e7259cc144 --- /dev/null +++ b/Lang/Kotlin/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Singly-linked-list-Element-definition b/Lang/Kotlin/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..4a27d863a2 --- /dev/null +++ b/Lang/Kotlin/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Singly-linked-list-Element-insertion b/Lang/Kotlin/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..2b88afdc9b --- /dev/null +++ b/Lang/Kotlin/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sleep b/Lang/Kotlin/Sleep new file mode 120000 index 0000000000..ebbeca5fde --- /dev/null +++ b/Lang/Kotlin/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Solve-a-Holy-Knights-tour b/Lang/Kotlin/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..d7c267f683 --- /dev/null +++ b/Lang/Kotlin/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sort-an-array-of-composite-structures b/Lang/Kotlin/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..cf5e1fe141 --- /dev/null +++ b/Lang/Kotlin/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sort-an-integer-array b/Lang/Kotlin/Sort-an-integer-array new file mode 120000 index 0000000000..037641bf78 --- /dev/null +++ b/Lang/Kotlin/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Bead-sort b/Lang/Kotlin/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..6e4a76ddc5 --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Bogosort b/Lang/Kotlin/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..7a053a3b65 --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Cocktail-sort b/Lang/Kotlin/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..05a34d05d7 --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Comb-sort b/Lang/Kotlin/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..6be16fb765 --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Counting-sort b/Lang/Kotlin/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..80125b2479 --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Gnome-sort b/Lang/Kotlin/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..fd177b18bc --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Heapsort b/Lang/Kotlin/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..ce852feef3 --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Pancake-sort b/Lang/Kotlin/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..7ec0b59985 --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Permutation-sort b/Lang/Kotlin/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..0a99a8b057 --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Radix-sort b/Lang/Kotlin/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..f059258043 --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Shell-sort b/Lang/Kotlin/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..9db851a56e --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Stooge-sort b/Lang/Kotlin/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..8855c29425 --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Strand-sort b/Lang/Kotlin/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..4c9be90ed3 --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Soundex b/Lang/Kotlin/Soundex new file mode 120000 index 0000000000..abad95449f --- /dev/null +++ b/Lang/Kotlin/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Special-variables b/Lang/Kotlin/Special-variables new file mode 120000 index 0000000000..071194a5f0 --- /dev/null +++ b/Lang/Kotlin/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Spiral-matrix b/Lang/Kotlin/Spiral-matrix new file mode 120000 index 0000000000..8a5fcca143 --- /dev/null +++ b/Lang/Kotlin/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Stack b/Lang/Kotlin/Stack new file mode 120000 index 0000000000..12472a5bae --- /dev/null +++ b/Lang/Kotlin/Stack @@ -0,0 +1 @@ +../../Task/Stack/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Stack-traces b/Lang/Kotlin/Stack-traces new file mode 120000 index 0000000000..a65f48df7f --- /dev/null +++ b/Lang/Kotlin/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Statistics-Basic b/Lang/Kotlin/Statistics-Basic new file mode 120000 index 0000000000..8184020d0e --- /dev/null +++ b/Lang/Kotlin/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Stem-and-leaf-plot b/Lang/Kotlin/Stem-and-leaf-plot new file mode 120000 index 0000000000..b87298d07b --- /dev/null +++ b/Lang/Kotlin/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Stern-Brocot-sequence b/Lang/Kotlin/Stern-Brocot-sequence new file mode 120000 index 0000000000..6360f0d5d7 --- /dev/null +++ b/Lang/Kotlin/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/String-case b/Lang/Kotlin/String-case new file mode 120000 index 0000000000..b9703c1df3 --- /dev/null +++ b/Lang/Kotlin/String-case @@ -0,0 +1 @@ +../../Task/String-case/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/String-comparison b/Lang/Kotlin/String-comparison new file mode 120000 index 0000000000..138cf750a4 --- /dev/null +++ b/Lang/Kotlin/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/String-interpolation--included- b/Lang/Kotlin/String-interpolation--included- new file mode 120000 index 0000000000..fd032545e9 --- /dev/null +++ b/Lang/Kotlin/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/String-length b/Lang/Kotlin/String-length new file mode 120000 index 0000000000..797219217d --- /dev/null +++ b/Lang/Kotlin/String-length @@ -0,0 +1 @@ +../../Task/String-length/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/String-matching b/Lang/Kotlin/String-matching new file mode 120000 index 0000000000..a9f9519c92 --- /dev/null +++ b/Lang/Kotlin/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/String-prepend b/Lang/Kotlin/String-prepend new file mode 120000 index 0000000000..9aa92aa725 --- /dev/null +++ b/Lang/Kotlin/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Strip-a-set-of-characters-from-a-string b/Lang/Kotlin/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..297e8e23c1 --- /dev/null +++ b/Lang/Kotlin/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Strip-block-comments b/Lang/Kotlin/Strip-block-comments new file mode 120000 index 0000000000..ad345d18cc --- /dev/null +++ b/Lang/Kotlin/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Strip-comments-from-a-string b/Lang/Kotlin/Strip-comments-from-a-string new file mode 120000 index 0000000000..c9d8261145 --- /dev/null +++ b/Lang/Kotlin/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Kotlin/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..0af03a7227 --- /dev/null +++ b/Lang/Kotlin/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Kotlin/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..176d8b1164 --- /dev/null +++ b/Lang/Kotlin/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Substring b/Lang/Kotlin/Substring new file mode 120000 index 0000000000..2421a903b2 --- /dev/null +++ b/Lang/Kotlin/Substring @@ -0,0 +1 @@ +../../Task/Substring/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Substring-Top-and-tail b/Lang/Kotlin/Substring-Top-and-tail new file mode 120000 index 0000000000..18a022b2be --- /dev/null +++ b/Lang/Kotlin/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sum-and-product-of-an-array b/Lang/Kotlin/Sum-and-product-of-an-array new file mode 120000 index 0000000000..0cb51b7422 --- /dev/null +++ b/Lang/Kotlin/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sum-digits-of-an-integer b/Lang/Kotlin/Sum-digits-of-an-integer new file mode 120000 index 0000000000..9851957c7b --- /dev/null +++ b/Lang/Kotlin/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sum-multiples-of-3-and-5 b/Lang/Kotlin/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..5321a6a752 --- /dev/null +++ b/Lang/Kotlin/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sum-of-a-series b/Lang/Kotlin/Sum-of-a-series new file mode 120000 index 0000000000..fa37d8ad41 --- /dev/null +++ b/Lang/Kotlin/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sum-of-squares b/Lang/Kotlin/Sum-of-squares new file mode 120000 index 0000000000..a52ea2affb --- /dev/null +++ b/Lang/Kotlin/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sutherland-Hodgman-polygon-clipping b/Lang/Kotlin/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..caa0d48c1a --- /dev/null +++ b/Lang/Kotlin/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Symmetric-difference b/Lang/Kotlin/Symmetric-difference new file mode 120000 index 0000000000..fe50c90845 --- /dev/null +++ b/Lang/Kotlin/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/System-time b/Lang/Kotlin/System-time new file mode 120000 index 0000000000..7a5e25de39 --- /dev/null +++ b/Lang/Kotlin/System-time @@ -0,0 +1 @@ +../../Task/System-time/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Temperature-conversion b/Lang/Kotlin/Temperature-conversion new file mode 120000 index 0000000000..7ac421b6b0 --- /dev/null +++ b/Lang/Kotlin/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Terminal-control-Clear-the-screen b/Lang/Kotlin/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..6c5760733a --- /dev/null +++ b/Lang/Kotlin/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Terminal-control-Coloured-text b/Lang/Kotlin/Terminal-control-Coloured-text new file mode 120000 index 0000000000..b6c72d533f --- /dev/null +++ b/Lang/Kotlin/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Terminal-control-Cursor-movement b/Lang/Kotlin/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..fe0b5aa7f0 --- /dev/null +++ b/Lang/Kotlin/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Terminal-control-Cursor-positioning b/Lang/Kotlin/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..55975a48e2 --- /dev/null +++ b/Lang/Kotlin/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Terminal-control-Dimensions b/Lang/Kotlin/Terminal-control-Dimensions new file mode 120000 index 0000000000..414f45e9ad --- /dev/null +++ b/Lang/Kotlin/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Terminal-control-Display-an-extended-character b/Lang/Kotlin/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..791d1fcf06 --- /dev/null +++ b/Lang/Kotlin/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Terminal-control-Hiding-the-cursor b/Lang/Kotlin/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..7d039b2e07 --- /dev/null +++ b/Lang/Kotlin/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Terminal-control-Inverse-video b/Lang/Kotlin/Terminal-control-Inverse-video new file mode 120000 index 0000000000..c8bc91f911 --- /dev/null +++ b/Lang/Kotlin/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Terminal-control-Positional-read b/Lang/Kotlin/Terminal-control-Positional-read new file mode 120000 index 0000000000..e2f5b91281 --- /dev/null +++ b/Lang/Kotlin/Terminal-control-Positional-read @@ -0,0 +1 @@ +../../Task/Terminal-control-Positional-read/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Terminal-control-Preserve-screen b/Lang/Kotlin/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..46e1da82c8 --- /dev/null +++ b/Lang/Kotlin/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Terminal-control-Ringing-the-terminal-bell b/Lang/Kotlin/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..14c74d6a1a --- /dev/null +++ b/Lang/Kotlin/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Terminal-control-Unicode-output b/Lang/Kotlin/Terminal-control-Unicode-output new file mode 120000 index 0000000000..65392e1173 --- /dev/null +++ b/Lang/Kotlin/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Ternary-logic b/Lang/Kotlin/Ternary-logic new file mode 120000 index 0000000000..6f70d3cdb6 --- /dev/null +++ b/Lang/Kotlin/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Test-a-function b/Lang/Kotlin/Test-a-function new file mode 120000 index 0000000000..4dd879f151 --- /dev/null +++ b/Lang/Kotlin/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Textonyms b/Lang/Kotlin/Textonyms new file mode 120000 index 0000000000..cc5971bf5c --- /dev/null +++ b/Lang/Kotlin/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/The-ISAAC-Cipher b/Lang/Kotlin/The-ISAAC-Cipher new file mode 120000 index 0000000000..2a38981597 --- /dev/null +++ b/Lang/Kotlin/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Thieles-interpolation-formula b/Lang/Kotlin/Thieles-interpolation-formula new file mode 120000 index 0000000000..025c34f78b --- /dev/null +++ b/Lang/Kotlin/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Time-a-function b/Lang/Kotlin/Time-a-function new file mode 120000 index 0000000000..2c4338b0ed --- /dev/null +++ b/Lang/Kotlin/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Top-rank-per-group b/Lang/Kotlin/Top-rank-per-group new file mode 120000 index 0000000000..5257c8c5e0 --- /dev/null +++ b/Lang/Kotlin/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Topic-variable b/Lang/Kotlin/Topic-variable new file mode 120000 index 0000000000..75b9dc4e98 --- /dev/null +++ b/Lang/Kotlin/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Topswops b/Lang/Kotlin/Topswops new file mode 120000 index 0000000000..498ea4019d --- /dev/null +++ b/Lang/Kotlin/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Total-circles-area b/Lang/Kotlin/Total-circles-area new file mode 120000 index 0000000000..239662a3bd --- /dev/null +++ b/Lang/Kotlin/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Towers-of-Hanoi b/Lang/Kotlin/Towers-of-Hanoi new file mode 120000 index 0000000000..deb8f5225f --- /dev/null +++ b/Lang/Kotlin/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Trabb-Pardo-Knuth-algorithm b/Lang/Kotlin/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..7c57536999 --- /dev/null +++ b/Lang/Kotlin/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Trigonometric-functions b/Lang/Kotlin/Trigonometric-functions new file mode 120000 index 0000000000..064f7c9760 --- /dev/null +++ b/Lang/Kotlin/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Truncatable-primes b/Lang/Kotlin/Truncatable-primes new file mode 120000 index 0000000000..a2fe32c468 --- /dev/null +++ b/Lang/Kotlin/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Truncate-a-file b/Lang/Kotlin/Truncate-a-file new file mode 120000 index 0000000000..0b1fdc937d --- /dev/null +++ b/Lang/Kotlin/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Twelve-statements b/Lang/Kotlin/Twelve-statements new file mode 120000 index 0000000000..7bbf4e361e --- /dev/null +++ b/Lang/Kotlin/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/URL-decoding b/Lang/Kotlin/URL-decoding new file mode 120000 index 0000000000..9b56e0d95b --- /dev/null +++ b/Lang/Kotlin/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/URL-encoding b/Lang/Kotlin/URL-encoding new file mode 120000 index 0000000000..c6add267bb --- /dev/null +++ b/Lang/Kotlin/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Unbias-a-random-generator b/Lang/Kotlin/Unbias-a-random-generator new file mode 120000 index 0000000000..44f81da4e0 --- /dev/null +++ b/Lang/Kotlin/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Undefined-values b/Lang/Kotlin/Undefined-values new file mode 120000 index 0000000000..a9d8e57b5b --- /dev/null +++ b/Lang/Kotlin/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Unicode-strings b/Lang/Kotlin/Unicode-strings new file mode 120000 index 0000000000..22fc73bc3f --- /dev/null +++ b/Lang/Kotlin/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Unicode-variable-names b/Lang/Kotlin/Unicode-variable-names new file mode 120000 index 0000000000..9fa77a40e9 --- /dev/null +++ b/Lang/Kotlin/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/User-input-Graphical b/Lang/Kotlin/User-input-Graphical new file mode 120000 index 0000000000..8684f61f9b --- /dev/null +++ b/Lang/Kotlin/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/User-input-Text b/Lang/Kotlin/User-input-Text new file mode 120000 index 0000000000..79876a0118 --- /dev/null +++ b/Lang/Kotlin/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Vampire-number b/Lang/Kotlin/Vampire-number new file mode 120000 index 0000000000..99f7919c59 --- /dev/null +++ b/Lang/Kotlin/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Van-der-Corput-sequence b/Lang/Kotlin/Van-der-Corput-sequence new file mode 120000 index 0000000000..8bb623f36b --- /dev/null +++ b/Lang/Kotlin/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Variable-length-quantity b/Lang/Kotlin/Variable-length-quantity new file mode 120000 index 0000000000..642884814a --- /dev/null +++ b/Lang/Kotlin/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Variable-size-Get b/Lang/Kotlin/Variable-size-Get new file mode 120000 index 0000000000..e010595519 --- /dev/null +++ b/Lang/Kotlin/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Variable-size-Set b/Lang/Kotlin/Variable-size-Set new file mode 120000 index 0000000000..73452d3dd3 --- /dev/null +++ b/Lang/Kotlin/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Variables b/Lang/Kotlin/Variables new file mode 120000 index 0000000000..5101fd528b --- /dev/null +++ b/Lang/Kotlin/Variables @@ -0,0 +1 @@ +../../Task/Variables/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Variadic-function b/Lang/Kotlin/Variadic-function new file mode 120000 index 0000000000..f54800ba50 --- /dev/null +++ b/Lang/Kotlin/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Vector-products b/Lang/Kotlin/Vector-products new file mode 120000 index 0000000000..ef36c5ee62 --- /dev/null +++ b/Lang/Kotlin/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Verify-distribution-uniformity-Naive b/Lang/Kotlin/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..8f6ab64aa2 --- /dev/null +++ b/Lang/Kotlin/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Vigen-re-cipher b/Lang/Kotlin/Vigen-re-cipher new file mode 120000 index 0000000000..3a20fe8b1a --- /dev/null +++ b/Lang/Kotlin/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Vigen-re-cipher-Cryptanalysis b/Lang/Kotlin/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..236a67c75b --- /dev/null +++ b/Lang/Kotlin/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Vogels-approximation-method b/Lang/Kotlin/Vogels-approximation-method new file mode 120000 index 0000000000..370f210760 --- /dev/null +++ b/Lang/Kotlin/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Voronoi-diagram b/Lang/Kotlin/Voronoi-diagram new file mode 120000 index 0000000000..c792c52bdc --- /dev/null +++ b/Lang/Kotlin/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Walk-a-directory-Non-recursively b/Lang/Kotlin/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..b7f40ff95d --- /dev/null +++ b/Lang/Kotlin/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Web-scraping b/Lang/Kotlin/Web-scraping new file mode 120000 index 0000000000..a61ff547fe --- /dev/null +++ b/Lang/Kotlin/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Window-creation-X11 b/Lang/Kotlin/Window-creation-X11 new file mode 120000 index 0000000000..46ab53748c --- /dev/null +++ b/Lang/Kotlin/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Word-wrap b/Lang/Kotlin/Word-wrap new file mode 120000 index 0000000000..d353fbae0e --- /dev/null +++ b/Lang/Kotlin/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/World-Cup-group-stage b/Lang/Kotlin/World-Cup-group-stage new file mode 120000 index 0000000000..47aa6d18bb --- /dev/null +++ b/Lang/Kotlin/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Write-float-arrays-to-a-text-file b/Lang/Kotlin/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..7375a76ad4 --- /dev/null +++ b/Lang/Kotlin/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Write-language-name-in-3D-ASCII b/Lang/Kotlin/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..3579ea909f --- /dev/null +++ b/Lang/Kotlin/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Write-to-Windows-event-log b/Lang/Kotlin/Write-to-Windows-event-log new file mode 120000 index 0000000000..43c27dc18f --- /dev/null +++ b/Lang/Kotlin/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/XML-DOM-serialization b/Lang/Kotlin/XML-DOM-serialization new file mode 120000 index 0000000000..54dbfba9fc --- /dev/null +++ b/Lang/Kotlin/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/XML-Input b/Lang/Kotlin/XML-Input new file mode 120000 index 0000000000..3c2a556501 --- /dev/null +++ b/Lang/Kotlin/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/XML-Output b/Lang/Kotlin/XML-Output new file mode 120000 index 0000000000..80e9526e5b --- /dev/null +++ b/Lang/Kotlin/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/XML-XPath b/Lang/Kotlin/XML-XPath new file mode 120000 index 0000000000..9e7d6c8842 --- /dev/null +++ b/Lang/Kotlin/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Xiaolin-Wus-line-algorithm b/Lang/Kotlin/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..9595621731 --- /dev/null +++ b/Lang/Kotlin/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Y-combinator b/Lang/Kotlin/Y-combinator new file mode 120000 index 0000000000..038ec5e988 --- /dev/null +++ b/Lang/Kotlin/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Yin-and-yang b/Lang/Kotlin/Yin-and-yang new file mode 120000 index 0000000000..b4523787f6 --- /dev/null +++ b/Lang/Kotlin/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Zebra-puzzle b/Lang/Kotlin/Zebra-puzzle new file mode 120000 index 0000000000..7ca5a43ab8 --- /dev/null +++ b/Lang/Kotlin/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Zeckendorf-number-representation b/Lang/Kotlin/Zeckendorf-number-representation new file mode 120000 index 0000000000..d797a807b6 --- /dev/null +++ b/Lang/Kotlin/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Zero-to-the-zero-power b/Lang/Kotlin/Zero-to-the-zero-power new file mode 120000 index 0000000000..c61d9eff08 --- /dev/null +++ b/Lang/Kotlin/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Zhang-Suen-thinning-algorithm b/Lang/Kotlin/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..acaf77a789 --- /dev/null +++ b/Lang/Kotlin/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Zig-zag-matrix b/Lang/Kotlin/Zig-zag-matrix new file mode 120000 index 0000000000..ce1547f399 --- /dev/null +++ b/Lang/Kotlin/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Kotlin \ No newline at end of file diff --git a/Lang/LLVM/99-Bottles-of-Beer b/Lang/LLVM/99-Bottles-of-Beer deleted file mode 120000 index 99d7ba0e35..0000000000 --- a/Lang/LLVM/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/LLVM \ No newline at end of file diff --git a/Lang/LOLCODE/99-Bottles-of-Beer b/Lang/LOLCODE/99-Bottles-of-Beer deleted file mode 120000 index 51a01cce6f..0000000000 --- a/Lang/LOLCODE/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Fibonacci-sequence b/Lang/LOLCODE/Fibonacci-sequence new file mode 120000 index 0000000000..0033c3675f --- /dev/null +++ b/Lang/LOLCODE/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/FizzBuzz b/Lang/LOLCODE/FizzBuzz deleted file mode 120000 index f80c1cd2ee..0000000000 --- a/Lang/LOLCODE/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/LOLCODE \ No newline at end of file diff --git a/Lang/LaTeX/00DESCRIPTION b/Lang/LaTeX/00DESCRIPTION index e31cedce57..0094110f9e 100644 --- a/Lang/LaTeX/00DESCRIPTION +++ b/Lang/LaTeX/00DESCRIPTION @@ -1,6 +1,6 @@ {{language|LaTeX |site=http://latex-project.org/}} -'''LaTeX''' is a document preparation language (markup language) written by Lamport (1985, 1994) to allow authors to create documents to be typeset using the [[TeX]] typesetting language (Knuth: 1978, 1982), without having to know the internal details of TeX. For further details please see the links below. +'''{{LaTeX}}''' is a document preparation language (markup language) written by Lamport (1985, 1994) to allow authors to create documents to be typeset using the [[TeX|{{TeX}}]] typesetting language (Knuth: 1978, 1982), without having to know the internal details of {{TeX}}. For further details please see the links below. ==See Also== -* [http://www.tug.org TeX Users Group] \ No newline at end of file +* [http://www.tug.org {{TeX}} Users Group] \ No newline at end of file diff --git a/Lang/LabVIEW/00DESCRIPTION b/Lang/LabVIEW/00DESCRIPTION index 3f26cc9159..3fa7b8f465 100644 --- a/Lang/LabVIEW/00DESCRIPTION +++ b/Lang/LabVIEW/00DESCRIPTION @@ -1,6 +1,6 @@ {{language |site=http://www.ni.com/labview/}}LabVIEW is a proprietary graphical programming language produced by National Instruments that is used mainly for data acquisition, instrument control, test automation and industrial control. -The basic building block of a LabVIEW application is a VI(virtual instrument), which consists of a front panel, where you design a user interface, and a block diagram, where you create graphical code. +The basic building block of a LabVIEW application is a VI (virtual instrument), which consists of a front panel, where you design a user interface, and a block diagram, where you create graphical code. ==See also== * [[wp:Labview|Wikipedia article]] \ No newline at end of file diff --git a/Lang/Lambdatalk/00DESCRIPTION b/Lang/Lambdatalk/00DESCRIPTION new file mode 100644 index 0000000000..4d7c3f8c89 --- /dev/null +++ b/Lang/Lambdatalk/00DESCRIPTION @@ -0,0 +1,176 @@ +{{language|Lamdatalk}} + + +The {lambda way} project is a web application built on two engines: + +1) {lambda tank}, a tiny wiki built as a thin overlay on top of any web browser, + +2) {lambda talk}, a purely functional language unifying authoring, styling and scripting in a single and coherent s-expression based syntax. + +=={lambda talk} in a few words== + +1) Expressions are written in a prefix notation using curly braces. + +2) Away from curly braces words are just words. + + 2+3 is equal to {+ 2 3} + -> 2+3 is equal to 5 + +3) Functions are created with '''lambda''' and named with '''def'''. + + {def foo + {lambda {:a :b} + :a+:b is equal to {+ :a :b}}} + -> foo + {foo 2 3} + -> 2+3 is equal to 5 + +==more about {lambda talk}== + +{lambda talk} is freely inspired by the '''λ-calculus'''. At the lowest level a {lambda talk} expression is exclusively made of words, abstractions and applications: + +===structure & evaluation=== + + expression is [word|abstraction|application]* + where + 1) word is [^\s{}]* -> word + 2) abstraction is {lambda {words} expression} -> word + 3) application is {expression expression} -> words + +1) a word is any character except spaces and curly braces, and is not evaluated out of curly braces, + +2) an abstraction is a '''special form''' (called a function) selecting words (called arguments) in an expression (called the body), and is evaluated to a word referencing an anonymous function added to a single dictionary, initially empty, + +3) an application is a '''simple form''' calling an abstraction to replace selected words by some other words (called values), and is evaluated to words. + +The evaluation stops when all expressions have been replaced by words. + +In order to make code easier to write and read, we define a second special form: + + {def word expression} + +allowing to create constants added to the dictionary and to give names to anonymous functions. + +What can be done with so little? + +===Examples=== + +Out of curly braces words are not evaluated: + + Hello World + -> Hello World + +Sequences of words can be given a name: + + {def HI Hello World} + -> HI + HI, I just say {HI} + -> HI, I just say Hello World + +Abstractions can be defined and immediately called: + + {{lambda {o a} oh happy day!} oOOOo aaAAaa} + -> oOOOoh haaAAaappy daaAAaay! + +The abstraction is first evaluated, the application gets the awaited values oOOOo and aaAAaa, calls the abstraction which makes the substitution and returns the result, oOOOoh haaAAaappy daaAAaay!. + +Abstractions can be given a name and then called easily several times: + + {def GOOD_DAY {lambda {o a} oh happy day!}} + -> GOOD_DAY + {GOOD_DAY oOOOo aaAaa} + -> oOOOoh haaAaappy daaAaay! + {GOOD_DAY ♠ ♥} + -> ♠h h♥ppy d♥y! + +Most of the time expressions are nested. The expression below returns the first word of Hello World: + + {{lambda {z} + {z {lambda {x y} x}}} + {{lambda {x y z} + {z x y}} Hello World}} + -> Hello + +Using names helps to recognize a data structure and its accessors: + + {def CONS {lambda {:x :y :z} {:z :x :y}}} -> CONS + {def CAR {lambda {:z} {:z {lambda {:x :y} :x}}}} -> CAR + {def CDR {lambda {:z} {:z {lambda {:x :y} :y}}}} -> CDR + {CAR {CONS Hello World}} -> Hello + {CDR {CONS Hello World}} -> World + +===about the implementation=== + +{lambda talk} is not implemented following the standard process, code -> tokens -> tree -> eval. '''The code is a string from beginning to end'''. At each keyboard input, the code is processed by a single function, do_eval(), which returns words sent to the browser for the final evaluation and display: + + var do_eval = function( code ) { + code = pre_processing( code ); + code = eval_lambdas( code ); // {lambda {args} body} + code = eval_defs( code ); // {def name body} + code = eval_forms( code ); // {a {b {c ...}}} + code = post_processing( code ); + return code + }; + +'''1) eval_forms()''': Using a single '''regular expression''' the eval_forms() function loops over the code string, skips the words out of curly braces, matches nested forms {first rest} from inside out, and replaces them by words. The repeated substitutions inside the code string overcomes limitations of regular language. It's a kind of Turing machine. + +'''2) eval_lambdas()''': this function uses arguments as '''regular expressions''' to successively replace occurrences found in the function's body by the given values. Lambdas have the following properties: + +- lambdas are '''first class functions''', they can be called as functions' arguments and returned from functions, + +- lambdas are pure black boxes, they '''don't create closures''' and are context free, inner lambdas don't see outer functions' arguments, there are no lexical scoping, no free variables, + +- lambdas accept de facto '''partial function application''': called with a number of values lesser than its arity, a lambda memorizes the given values and returns a new lambda waiting for the rest. + +'''Note:''': This is what Ward Cunningham wrote about such an iconoclastic implementation: ''« I was surprised that the technique worked so well in so many cases. I knew that regex are highly optimized and the cpus themselves optimize sequential access to memory which the regex must have at its core. [..] Yes, this has at its heart the repeated application of a text transformation. The fact that it is repeated application of the same transformation makes it exceptional. [..] Repeated application of Regular Expressions can perform Touring Complete computations. This works because the needed "state" is in the partially evaluated text itself. »'' All is said! + +===and?=== + +Upon these foundations, after '''Alonzo Church''', we could define the set of natural numbers [ZERO, ONE, TWO, ...] and their associate operators, [SUCC, ADD, MUL, POWER, PRED, ...] allowing to build '''iterative''' and '''recursive''' processes. For instance, computing factorials: + + {CHURCH + {{lambda {:n} + {{lambda {:g :n} {:g :g :n}} + {lambda {:g :n} + {{{ISZERO :n} + {CONS {lambda {:g :n} ONE} + {lambda {:g :n} + {MUL :n {:g :g {PRED :n}}}} + }} :g :n}} :n}} FIVE}} + -> 120 + +=={lambda talk} full== + +In fact, {lambda talk} takes benefit from the extraordinary power of modern web browsers and simply adds a coherent and unique language on existing tools. + +In its complete state, {lambda talk} comes with a more complete set of special forms, [lambda, def, if, let, quote, macro, require, script, style], and a dictionary containing about 200 primitive functions built on the Javascript Math Object, HTML tags, CSS rules, SVG, the DOM and more, pairs, lists, arrays, light-show, spreadsheet, splines, turtle graphics, big numbers, ... and some other specific to the wiki context. Example: + + {def ! {lambda {:a :b} + {if {< :b 2} + then :a + else {! {* :a :b} {- :b 1}}}}} + -> ! + {! 1 6} + -> 720 + +What for? Well, you could compute the famous Euler's number: + + {def euler {lambda {:n} + {+ {map {lambda {:n} {/ 1 {! 1 :n}}} {serie 0 :n}}}}} + -> euler + {euler 17} + -> 2.7182818284590455 + +Web design is not forgotten and examples can be seen in the workshop's website. Thanks to the language's unicity, authors, web-designers and coders can share their experiences to build rich web pages. + +The {lambda way} project adds on browsers a thin overlay, {lambda tank}, giving to {lambda talk} a small ''Interactive Development Environment'' without any external dependencies and thereby easy to download (50kb) and install on any web account provider running PHP. From any web browser, on any system, complex and dynamic web pages can be created, enriched, structured and tested in real time on the web. + +A full presentation of the {lambda way} project can be seen in: + + - http://lambdaway.free.fr/ + - http://lambdaway.free.fr/workshop/?view=about + - http://lambdaway.free.fr/workshop/?view=foundations + - http://lambdaway.free.fr/workshop/?view=oxford_slides + - and several other pages of the workshop. + +Your opinion is welcome. Alain Marty \ No newline at end of file diff --git a/Lang/Lambdatalk/Anonymous-recursion b/Lang/Lambdatalk/Anonymous-recursion new file mode 120000 index 0000000000..a8972e40aa --- /dev/null +++ b/Lang/Lambdatalk/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Lambdatalk \ No newline at end of file diff --git a/Lang/Lambdatalk/Binary-search b/Lang/Lambdatalk/Binary-search new file mode 120000 index 0000000000..82ae3dc3d5 --- /dev/null +++ b/Lang/Lambdatalk/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/Lambdatalk \ No newline at end of file diff --git a/Lang/Lambdatalk/First-class-functions b/Lang/Lambdatalk/First-class-functions new file mode 120000 index 0000000000..7f616e9169 --- /dev/null +++ b/Lang/Lambdatalk/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/Lambdatalk \ No newline at end of file diff --git a/Lang/Lambdatalk/Long-multiplication b/Lang/Lambdatalk/Long-multiplication new file mode 120000 index 0000000000..25f677a50e --- /dev/null +++ b/Lang/Lambdatalk/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/Lambdatalk \ No newline at end of file diff --git a/Lang/Lambdatalk/Partial-function-application b/Lang/Lambdatalk/Partial-function-application new file mode 120000 index 0000000000..1fe0967c08 --- /dev/null +++ b/Lang/Lambdatalk/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Lambdatalk \ No newline at end of file diff --git a/Lang/Lambdatalk/README b/Lang/Lambdatalk/README new file mode 100644 index 0000000000..739e8b5891 --- /dev/null +++ b/Lang/Lambdatalk/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Lambdatalk diff --git a/Lang/Lambdatalk/Sequence-of-primes-by-Trial-Division b/Lang/Lambdatalk/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..1042cf8bee --- /dev/null +++ b/Lang/Lambdatalk/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Lambdatalk \ No newline at end of file diff --git a/Lang/Lambdatalk/Simple-windowed-application b/Lang/Lambdatalk/Simple-windowed-application new file mode 120000 index 0000000000..d6d143dc24 --- /dev/null +++ b/Lang/Lambdatalk/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Lambdatalk \ No newline at end of file diff --git a/Lang/Lambdatalk/Towers-of-Hanoi b/Lang/Lambdatalk/Towers-of-Hanoi new file mode 120000 index 0000000000..d433100791 --- /dev/null +++ b/Lang/Lambdatalk/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Lambdatalk \ No newline at end of file diff --git a/Lang/Lambdatalk/Y-combinator b/Lang/Lambdatalk/Y-combinator new file mode 120000 index 0000000000..5781207fc3 --- /dev/null +++ b/Lang/Lambdatalk/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Lambdatalk \ No newline at end of file diff --git a/Lang/Lang5/99-Bottles-of-Beer b/Lang/Lang5/99-Bottles-of-Beer new file mode 120000 index 0000000000..e48b3acddf --- /dev/null +++ b/Lang/Lang5/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Lang5 \ No newline at end of file diff --git a/Lang/Lang5/Arrays b/Lang/Lang5/Arrays new file mode 120000 index 0000000000..01a8ffb0fb --- /dev/null +++ b/Lang/Lang5/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Lang5 \ No newline at end of file diff --git a/Lang/Lang5/Character-matching b/Lang/Lang5/Character-matching deleted file mode 120000 index 3afce4254a..0000000000 --- a/Lang/Lang5/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Lang5 \ No newline at end of file diff --git a/Lang/Lang5/File-IO b/Lang/Lang5/File-IO deleted file mode 120000 index 160dec5803..0000000000 --- a/Lang/Lang5/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Lang5 \ No newline at end of file diff --git a/Lang/Lang5/Stack b/Lang/Lang5/Stack new file mode 120000 index 0000000000..17776493b0 --- /dev/null +++ b/Lang/Lang5/Stack @@ -0,0 +1 @@ +../../Task/Stack/Lang5 \ No newline at end of file diff --git a/Lang/Liberty-BASIC/99-Bottles-of-Beer b/Lang/Liberty-BASIC/99-Bottles-of-Beer deleted file mode 120000 index f6b7c0c518..0000000000 --- a/Lang/Liberty-BASIC/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/A+B b/Lang/Liberty-BASIC/A+B deleted file mode 120000 index c921701f1e..0000000000 --- a/Lang/Liberty-BASIC/A+B +++ /dev/null @@ -1 +0,0 @@ -../../Task/A+B/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Character-matching b/Lang/Liberty-BASIC/Character-matching deleted file mode 120000 index befb5ee97f..0000000000 --- a/Lang/Liberty-BASIC/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Colour-bars-Display b/Lang/Liberty-BASIC/Colour-bars-Display deleted file mode 120000 index 7edc974d47..0000000000 --- a/Lang/Liberty-BASIC/Colour-bars-Display +++ /dev/null @@ -1 +0,0 @@ -../../Task/Colour-bars-Display/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Conways-Game-of-Life b/Lang/Liberty-BASIC/Conways-Game-of-Life deleted file mode 120000 index 32522deed2..0000000000 --- a/Lang/Liberty-BASIC/Conways-Game-of-Life +++ /dev/null @@ -1 +0,0 @@ -../../Task/Conways-Game-of-Life/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Detect-division-by-zero b/Lang/Liberty-BASIC/Detect-division-by-zero deleted file mode 120000 index 2ea9f120df..0000000000 --- a/Lang/Liberty-BASIC/Detect-division-by-zero +++ /dev/null @@ -1 +0,0 @@ -../../Task/Detect-division-by-zero/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Draw-a-sphere b/Lang/Liberty-BASIC/Draw-a-sphere deleted file mode 120000 index a68e88e8e3..0000000000 --- a/Lang/Liberty-BASIC/Draw-a-sphere +++ /dev/null @@ -1 +0,0 @@ -../../Task/Draw-a-sphere/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Ethiopian-multiplication b/Lang/Liberty-BASIC/Ethiopian-multiplication deleted file mode 120000 index b75f5ee193..0000000000 --- a/Lang/Liberty-BASIC/Ethiopian-multiplication +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ethiopian-multiplication/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/File-IO b/Lang/Liberty-BASIC/File-IO deleted file mode 120000 index 6ecdf5c8df..0000000000 --- a/Lang/Liberty-BASIC/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/FizzBuzz b/Lang/Liberty-BASIC/FizzBuzz deleted file mode 120000 index faba02a746..0000000000 --- a/Lang/Liberty-BASIC/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Forest-fire b/Lang/Liberty-BASIC/Forest-fire deleted file mode 120000 index e001ce5626..0000000000 --- a/Lang/Liberty-BASIC/Forest-fire +++ /dev/null @@ -1 +0,0 @@ -../../Task/Forest-fire/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Hailstone-sequence b/Lang/Liberty-BASIC/Hailstone-sequence deleted file mode 120000 index e510bfe068..0000000000 --- a/Lang/Liberty-BASIC/Hailstone-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hailstone-sequence/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Loops-Continue b/Lang/Liberty-BASIC/Loops-Continue deleted file mode 120000 index 290bbeca43..0000000000 --- a/Lang/Liberty-BASIC/Loops-Continue +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Continue/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Loops-For b/Lang/Liberty-BASIC/Loops-For deleted file mode 120000 index abe2a517a2..0000000000 --- a/Lang/Liberty-BASIC/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Loops-Foreach b/Lang/Liberty-BASIC/Loops-Foreach deleted file mode 120000 index 3a170b605d..0000000000 --- a/Lang/Liberty-BASIC/Loops-Foreach +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Foreach/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Mandelbrot-set b/Lang/Liberty-BASIC/Mandelbrot-set deleted file mode 120000 index 0c87cd4c2d..0000000000 --- a/Lang/Liberty-BASIC/Mandelbrot-set +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mandelbrot-set/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/Standard-deviation b/Lang/Liberty-BASIC/Standard-deviation deleted file mode 120000 index b06b9cf188..0000000000 --- a/Lang/Liberty-BASIC/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/String-case b/Lang/Liberty-BASIC/String-case deleted file mode 120000 index 597afb5d79..0000000000 --- a/Lang/Liberty-BASIC/String-case +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-case/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Tokenize-a-string b/Lang/Liberty-BASIC/Tokenize-a-string deleted file mode 120000 index 59a66cdddd..0000000000 --- a/Lang/Liberty-BASIC/Tokenize-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Tokenize-a-string/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Lilypond/Hello-world-Text b/Lang/Lilypond/Hello-world-Text new file mode 120000 index 0000000000..d678a845d2 --- /dev/null +++ b/Lang/Lilypond/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Lilypond \ No newline at end of file diff --git a/Lang/Lisaac/File-IO b/Lang/Lisaac/File-IO deleted file mode 120000 index 157d6f4d92..0000000000 --- a/Lang/Lisaac/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Lisaac \ No newline at end of file diff --git a/Lang/Lisp/99-Bottles-of-Beer b/Lang/Lisp/99-Bottles-of-Beer deleted file mode 120000 index e8c8282a9e..0000000000 --- a/Lang/Lisp/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Lisp \ No newline at end of file diff --git a/Lang/LiveCode/Levenshtein-distance b/Lang/LiveCode/Levenshtein-distance new file mode 120000 index 0000000000..a2249b323b --- /dev/null +++ b/Lang/LiveCode/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/LiveCode \ No newline at end of file diff --git a/Lang/Locomotive-Basic/00DESCRIPTION b/Lang/Locomotive-Basic/00DESCRIPTION index 69a68e9534..a1e3a8cca5 100644 --- a/Lang/Locomotive-Basic/00DESCRIPTION +++ b/Lang/Locomotive-Basic/00DESCRIPTION @@ -3,7 +3,8 @@ |site=http://www.grimware.org/doku.php/documentations/software/locomotive.basic/}} {{implementation|BASIC}} -'''Locomotive BASIC''' is a variant of BASIC that is built into the ROM of the [[wp:Amstrad CPC|Amstrad CPC]] series of Z80-based home computers introduced in 1984. In the 1980s, CPCs were a popular, slightly more expensive alternative to the Commodore C64/C128 and were not just suited for games but also office work because of their high resolution displays and [[wp:CP/M|CP/M]] support. They came with a built-in cassette deck (CPC 464 and 664) or 3" disk drive (CPC 6128) as storage devices and a "green screen" or color monitor which also housed the power supply. Sales were particularly strong in the UK, Germany, France, and Spain. Today, Locomotive BASIC can be used via CPC emulators such as [http://www.winape.net/ WinAPE] or [http://sourceforge.net/projects/javacpc/ JavaCPC]—which is perfectly legal because Amstrad has given their permission for distributing CPC ROM images with emulators. +'''Locomotive BASIC''' is a variant of BASIC that is built into the ROM of the [[wp:Amstrad CPC|Amstrad CPC]] series of Z80-based home computers introduced in 1984. In the 1980s, CPCs were a popular, slightly more expensive alternative to the Commodore C64/C128 and were not just suited for games but also office work because of their high resolution displays and [[wp:CP/M|CP/M]] support. They came with a built-in cassette deck (CPC 464) or 3" disk drive (CPC 664 and +6128) as storage devices and a "green screen" or color monitor which also housed the power supply. Sales were particularly strong in the UK, Germany, France, and Spain. Today, Locomotive BASIC can be used via CPC emulators such as [http://www.winape.net/ WinAPE] or [http://sourceforge.net/projects/javacpc/ JavaCPC]—which is perfectly legal because Amstrad has given their permission for distributing CPC ROM images with emulators. ==Features== diff --git a/Lang/Locomotive-Basic/Colour-bars-Display b/Lang/Locomotive-Basic/Colour-bars-Display deleted file mode 120000 index defbfc4e84..0000000000 --- a/Lang/Locomotive-Basic/Colour-bars-Display +++ /dev/null @@ -1 +0,0 @@ -../../Task/Colour-bars-Display/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Detect-division-by-zero b/Lang/Locomotive-Basic/Detect-division-by-zero deleted file mode 120000 index 9b5c8050a9..0000000000 --- a/Lang/Locomotive-Basic/Detect-division-by-zero +++ /dev/null @@ -1 +0,0 @@ -../../Task/Detect-division-by-zero/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Write-language-name-in-3D-ASCII b/Lang/Locomotive-Basic/Write-language-name-in-3D-ASCII deleted file mode 120000 index 58732a90ca..0000000000 --- a/Lang/Locomotive-Basic/Write-language-name-in-3D-ASCII +++ /dev/null @@ -1 +0,0 @@ -../../Task/Write-language-name-in-3D-ASCII/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Logo/Character-matching b/Lang/Logo/Character-matching deleted file mode 120000 index 08ecf5beb6..0000000000 --- a/Lang/Logo/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Logo \ No newline at end of file diff --git a/Lang/Logo/Deal-cards-for-FreeCell b/Lang/Logo/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..04572904e3 --- /dev/null +++ b/Lang/Logo/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Logo \ No newline at end of file diff --git a/Lang/Logo/File-IO b/Lang/Logo/File-IO deleted file mode 120000 index 45d94372d1..0000000000 --- a/Lang/Logo/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Logo \ No newline at end of file diff --git a/Lang/Logtalk/Environment-variables b/Lang/Logtalk/Environment-variables new file mode 120000 index 0000000000..3d46ef5ac0 --- /dev/null +++ b/Lang/Logtalk/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Execute-a-system-command b/Lang/Logtalk/Execute-a-system-command new file mode 120000 index 0000000000..7dba6b3f98 --- /dev/null +++ b/Lang/Logtalk/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Mutex b/Lang/Logtalk/Mutex deleted file mode 120000 index 47f82f6def..0000000000 --- a/Lang/Logtalk/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Logtalk \ No newline at end of file diff --git a/Lang/Lua/Animate-a-pendulum b/Lang/Lua/Animate-a-pendulum new file mode 120000 index 0000000000..3fc5d075e1 --- /dev/null +++ b/Lang/Lua/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Lua \ No newline at end of file diff --git a/Lang/Lua/Character-matching b/Lang/Lua/Character-matching deleted file mode 120000 index b6e2b08ca5..0000000000 --- a/Lang/Lua/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Lua \ No newline at end of file diff --git a/Lang/Lua/Execute-HQ9+ b/Lang/Lua/Execute-HQ9+ new file mode 120000 index 0000000000..fa84144ed1 --- /dev/null +++ b/Lang/Lua/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/Lua \ No newline at end of file diff --git a/Lang/Lua/Extreme-floating-point-values b/Lang/Lua/Extreme-floating-point-values new file mode 120000 index 0000000000..f48fb8c5b2 --- /dev/null +++ b/Lang/Lua/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Lua \ No newline at end of file diff --git a/Lang/Lua/Fibonacci-word-fractal b/Lang/Lua/Fibonacci-word-fractal new file mode 120000 index 0000000000..44f84e893b --- /dev/null +++ b/Lang/Lua/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Lua \ No newline at end of file diff --git a/Lang/Lua/File-IO b/Lang/Lua/File-IO deleted file mode 120000 index d516c392aa..0000000000 --- a/Lang/Lua/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Lua \ No newline at end of file diff --git a/Lang/Lua/Flipping-bits-game b/Lang/Lua/Flipping-bits-game new file mode 120000 index 0000000000..b997ffb0bb --- /dev/null +++ b/Lang/Lua/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Lua \ No newline at end of file diff --git a/Lang/Lua/Fractal-tree b/Lang/Lua/Fractal-tree new file mode 120000 index 0000000000..faa6019e6e --- /dev/null +++ b/Lang/Lua/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Lua \ No newline at end of file diff --git a/Lang/Lua/Mandelbrot-set b/Lang/Lua/Mandelbrot-set new file mode 120000 index 0000000000..75c8621a49 --- /dev/null +++ b/Lang/Lua/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Lua \ No newline at end of file diff --git a/Lang/Lua/Munching-squares b/Lang/Lua/Munching-squares new file mode 120000 index 0000000000..96a890f8a9 --- /dev/null +++ b/Lang/Lua/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Lua \ No newline at end of file diff --git a/Lang/Lua/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/Lua/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..661384bcc5 --- /dev/null +++ b/Lang/Lua/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/Lua \ No newline at end of file diff --git a/Lang/Lua/Parsing-RPN-calculator-algorithm b/Lang/Lua/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..397c1ccfd1 --- /dev/null +++ b/Lang/Lua/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Lua \ No newline at end of file diff --git a/Lang/Lua/Penneys-game b/Lang/Lua/Penneys-game new file mode 120000 index 0000000000..4106e13764 --- /dev/null +++ b/Lang/Lua/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Lua \ No newline at end of file diff --git a/Lang/Lua/Pointers-and-references b/Lang/Lua/Pointers-and-references new file mode 120000 index 0000000000..ffb4c54182 --- /dev/null +++ b/Lang/Lua/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/Lua \ No newline at end of file diff --git a/Lang/Lua/Random-numbers b/Lang/Lua/Random-numbers new file mode 120000 index 0000000000..d1617541d2 --- /dev/null +++ b/Lang/Lua/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Lua \ No newline at end of file diff --git a/Lang/Lua/Rosetta-Code-Fix-code-tags b/Lang/Lua/Rosetta-Code-Fix-code-tags deleted file mode 120000 index e7c76ee04a..0000000000 --- a/Lang/Lua/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/Lua \ No newline at end of file diff --git a/Lang/Lua/Solve-a-Holy-Knights-tour b/Lang/Lua/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..0ef1bcee80 --- /dev/null +++ b/Lang/Lua/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-algorithms-Permutation-sort b/Lang/Lua/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..8a30ab8e19 --- /dev/null +++ b/Lang/Lua/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Lua \ No newline at end of file diff --git a/Lang/Lua/Standard-deviation b/Lang/Lua/Standard-deviation deleted file mode 120000 index f40b48ac97..0000000000 --- a/Lang/Lua/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Lua \ No newline at end of file diff --git a/Lang/Lua/URL-decoding b/Lang/Lua/URL-decoding new file mode 120000 index 0000000000..5dbd7a10b8 --- /dev/null +++ b/Lang/Lua/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Lua \ No newline at end of file diff --git a/Lang/Lua/URL-encoding b/Lang/Lua/URL-encoding new file mode 120000 index 0000000000..6e3c8220e4 --- /dev/null +++ b/Lang/Lua/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Lua \ No newline at end of file diff --git a/Lang/Lua/Wireworld b/Lang/Lua/Wireworld new file mode 120000 index 0000000000..2a7c069527 --- /dev/null +++ b/Lang/Lua/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Lua \ No newline at end of file diff --git a/Lang/M4/Compile-time-calculation b/Lang/M4/Compile-time-calculation new file mode 120000 index 0000000000..54e9867d0c --- /dev/null +++ b/Lang/M4/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/M4 \ No newline at end of file diff --git a/Lang/M4/Hello-world-Newline-omission b/Lang/M4/Hello-world-Newline-omission new file mode 120000 index 0000000000..145cd0f2ee --- /dev/null +++ b/Lang/M4/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/M4 \ No newline at end of file diff --git a/Lang/M4/Hello-world-Standard-error b/Lang/M4/Hello-world-Standard-error new file mode 120000 index 0000000000..e80eae41d6 --- /dev/null +++ b/Lang/M4/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/M4 \ No newline at end of file diff --git a/Lang/M4/Include-a-file b/Lang/M4/Include-a-file new file mode 120000 index 0000000000..a3e742f765 --- /dev/null +++ b/Lang/M4/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/M4 \ No newline at end of file diff --git a/Lang/M4/Inverted-syntax b/Lang/M4/Inverted-syntax new file mode 120000 index 0000000000..32755b16d0 --- /dev/null +++ b/Lang/M4/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/M4 \ No newline at end of file diff --git a/Lang/MATLAB/Abstract-type b/Lang/MATLAB/Abstract-type new file mode 120000 index 0000000000..a38c08d064 --- /dev/null +++ b/Lang/MATLAB/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Character-matching b/Lang/MATLAB/Character-matching deleted file mode 120000 index aacc0c8fa7..0000000000 --- a/Lang/MATLAB/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Chinese-remainder-theorem b/Lang/MATLAB/Chinese-remainder-theorem new file mode 120000 index 0000000000..5a31c32609 --- /dev/null +++ b/Lang/MATLAB/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Function-definition b/Lang/MATLAB/Function-definition deleted file mode 120000 index 007258e587..0000000000 --- a/Lang/MATLAB/Function-definition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Function-definition/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/JSON b/Lang/MATLAB/JSON new file mode 120000 index 0000000000..34213f4b9d --- /dev/null +++ b/Lang/MATLAB/JSON @@ -0,0 +1 @@ +../../Task/JSON/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Rosetta-Code-Count-examples b/Lang/MATLAB/Rosetta-Code-Count-examples deleted file mode 120000 index 68b7269d68..0000000000 --- a/Lang/MATLAB/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sierpinski-carpet b/Lang/MATLAB/Sierpinski-carpet new file mode 120000 index 0000000000..72ff6bd205 --- /dev/null +++ b/Lang/MATLAB/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sierpinski-triangle b/Lang/MATLAB/Sierpinski-triangle new file mode 120000 index 0000000000..9f48edb951 --- /dev/null +++ b/Lang/MATLAB/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sierpinski-triangle-Graphical b/Lang/MATLAB/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..020cc7da15 --- /dev/null +++ b/Lang/MATLAB/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Standard-deviation b/Lang/MATLAB/Standard-deviation deleted file mode 120000 index 6f5d2fe983..0000000000 --- a/Lang/MATLAB/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/MATLAB \ No newline at end of file diff --git a/Lang/MAXScript/File-IO b/Lang/MAXScript/File-IO deleted file mode 120000 index ba70cd75eb..0000000000 --- a/Lang/MAXScript/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Primality-by-trial-division b/Lang/MAXScript/Primality-by-trial-division deleted file mode 120000 index 46e46141e7..0000000000 --- a/Lang/MAXScript/Primality-by-trial-division +++ /dev/null @@ -1 +0,0 @@ -../../Task/Primality-by-trial-division/MAXScript \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/100-doors b/Lang/MIRC-Scripting-Language/100-doors new file mode 120000 index 0000000000..cdcc202fec --- /dev/null +++ b/Lang/MIRC-Scripting-Language/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/24-game b/Lang/MIRC-Scripting-Language/24-game new file mode 120000 index 0000000000..1efeade83c --- /dev/null +++ b/Lang/MIRC-Scripting-Language/24-game @@ -0,0 +1 @@ +../../Task/24-game/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/99-Bottles-of-Beer b/Lang/MIRC-Scripting-Language/99-Bottles-of-Beer new file mode 120000 index 0000000000..0bfce7b23b --- /dev/null +++ b/Lang/MIRC-Scripting-Language/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/A+B b/Lang/MIRC-Scripting-Language/A+B new file mode 120000 index 0000000000..a0bcb24363 --- /dev/null +++ b/Lang/MIRC-Scripting-Language/A+B @@ -0,0 +1 @@ +../../Task/A+B/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/Comments b/Lang/MIRC-Scripting-Language/Comments new file mode 120000 index 0000000000..8c258c843b --- /dev/null +++ b/Lang/MIRC-Scripting-Language/Comments @@ -0,0 +1 @@ +../../Task/Comments/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/Date-format b/Lang/MIRC-Scripting-Language/Date-format new file mode 120000 index 0000000000..6fc268b474 --- /dev/null +++ b/Lang/MIRC-Scripting-Language/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/Date-manipulation b/Lang/MIRC-Scripting-Language/Date-manipulation new file mode 120000 index 0000000000..9146027083 --- /dev/null +++ b/Lang/MIRC-Scripting-Language/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/Detect-division-by-zero b/Lang/MIRC-Scripting-Language/Detect-division-by-zero new file mode 120000 index 0000000000..4235d03904 --- /dev/null +++ b/Lang/MIRC-Scripting-Language/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/Determine-if-a-string-is-numeric b/Lang/MIRC-Scripting-Language/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..75b3745487 --- /dev/null +++ b/Lang/MIRC-Scripting-Language/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/File-input-output b/Lang/MIRC-Scripting-Language/File-input-output new file mode 120000 index 0000000000..6cb7e01df1 --- /dev/null +++ b/Lang/MIRC-Scripting-Language/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/File-size b/Lang/MIRC-Scripting-Language/File-size new file mode 120000 index 0000000000..b0f9ff7efd --- /dev/null +++ b/Lang/MIRC-Scripting-Language/File-size @@ -0,0 +1 @@ +../../Task/File-size/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/Hello-world-Graphical b/Lang/MIRC-Scripting-Language/Hello-world-Graphical new file mode 120000 index 0000000000..e25dc1db74 --- /dev/null +++ b/Lang/MIRC-Scripting-Language/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/Hello-world-Newline-omission b/Lang/MIRC-Scripting-Language/Hello-world-Newline-omission new file mode 120000 index 0000000000..01cbccfcdc --- /dev/null +++ b/Lang/MIRC-Scripting-Language/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/Hello-world-Text b/Lang/MIRC-Scripting-Language/Hello-world-Text new file mode 120000 index 0000000000..36bee18847 --- /dev/null +++ b/Lang/MIRC-Scripting-Language/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/Hostname b/Lang/MIRC-Scripting-Language/Hostname new file mode 120000 index 0000000000..c76c854311 --- /dev/null +++ b/Lang/MIRC-Scripting-Language/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/Increment-a-numerical-string b/Lang/MIRC-Scripting-Language/Increment-a-numerical-string new file mode 120000 index 0000000000..147981ab5a --- /dev/null +++ b/Lang/MIRC-Scripting-Language/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/Input-loop b/Lang/MIRC-Scripting-Language/Input-loop new file mode 120000 index 0000000000..7fff541615 --- /dev/null +++ b/Lang/MIRC-Scripting-Language/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/String-case b/Lang/MIRC-Scripting-Language/String-case new file mode 120000 index 0000000000..214d9a5abb --- /dev/null +++ b/Lang/MIRC-Scripting-Language/String-case @@ -0,0 +1 @@ +../../Task/String-case/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/String-length b/Lang/MIRC-Scripting-Language/String-length new file mode 120000 index 0000000000..6aca44f6d5 --- /dev/null +++ b/Lang/MIRC-Scripting-Language/String-length @@ -0,0 +1 @@ +../../Task/String-length/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/Tic-tac-toe b/Lang/MIRC-Scripting-Language/Tic-tac-toe new file mode 120000 index 0000000000..eaac4012a2 --- /dev/null +++ b/Lang/MIRC-Scripting-Language/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/User-input-Text b/Lang/MIRC-Scripting-Language/User-input-Text new file mode 120000 index 0000000000..0ca5d38fa0 --- /dev/null +++ b/Lang/MIRC-Scripting-Language/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MIRC-Scripting-Language/Web-scraping b/Lang/MIRC-Scripting-Language/Web-scraping new file mode 120000 index 0000000000..c649afcd4f --- /dev/null +++ b/Lang/MIRC-Scripting-Language/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/MIRC-Scripting-Language \ No newline at end of file diff --git a/Lang/MLite/99-Bottles-of-Beer b/Lang/MLite/99-Bottles-of-Beer new file mode 120000 index 0000000000..76b68b04dd --- /dev/null +++ b/Lang/MLite/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/MLite \ No newline at end of file diff --git a/Lang/MLite/Ackermann-function b/Lang/MLite/Ackermann-function new file mode 120000 index 0000000000..c9f4136674 --- /dev/null +++ b/Lang/MLite/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/MLite \ No newline at end of file diff --git a/Lang/MLite/Binary-digits b/Lang/MLite/Binary-digits new file mode 120000 index 0000000000..3d808a1c26 --- /dev/null +++ b/Lang/MLite/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/MLite \ No newline at end of file diff --git a/Lang/MPIF90/99-Bottles-of-Beer b/Lang/MPIF90/99-Bottles-of-Beer deleted file mode 120000 index c6f1a276d8..0000000000 --- a/Lang/MPIF90/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/MPIF90 \ No newline at end of file diff --git a/Lang/MSX-Basic/00DESCRIPTION b/Lang/MSX-Basic/00DESCRIPTION new file mode 100644 index 0000000000..b32f20e269 --- /dev/null +++ b/Lang/MSX-Basic/00DESCRIPTION @@ -0,0 +1,25 @@ +{{stub}}{{language|MSX Basic}} + + +{{language|MSX Basic +|exec=interpreted +|site=https://www.webmsx.org/ +|parampass=both +|tags=MSXBasic}} +{{language programming paradigm|procedural}} +{{implementation|BASIC}} + + +MSX Basic is the BASIC built into the ROM of the MSX compatible computers. + +MSX BASIC is a dialect of the BASIC programming language. It is an extended version of Microsoft Standard BASIC Version 4.5, and includes support for graphic, music, and various peripherals attached to MSX Personal Computers. Generally, MSX-BASIC is designed to follow GW-BASIC + + +=={{header|MSX Basic}}== +10 Rem Count 1 to 10 and print! +20 for a=1 to 10 +20 Print a +30 Next a + + +
'''MSX Basic''' initially introduced to Rosetta Code on July 10, 2016 by [http://rosettacode.org/wiki/User:Kaizen Paulo Almeida]
MSX Basic and the MSX logo are registered trademarks of MSX Japan
\ No newline at end of file diff --git a/Lang/MSX-Basic/README b/Lang/MSX-Basic/README new file mode 100644 index 0000000000..b60dd918d6 --- /dev/null +++ b/Lang/MSX-Basic/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:MSX_Basic diff --git a/Lang/MUMPS/24-game b/Lang/MUMPS/24-game new file mode 120000 index 0000000000..39da2f5d5f --- /dev/null +++ b/Lang/MUMPS/24-game @@ -0,0 +1 @@ +../../Task/24-game/MUMPS \ No newline at end of file diff --git a/Lang/Make/99-Bottles-of-Beer b/Lang/Make/99-Bottles-of-Beer new file mode 120000 index 0000000000..f2db2ad9fd --- /dev/null +++ b/Lang/Make/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Make \ No newline at end of file diff --git a/Lang/Make/FizzBuzz b/Lang/Make/FizzBuzz new file mode 120000 index 0000000000..ba43ac7f85 --- /dev/null +++ b/Lang/Make/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Make \ No newline at end of file diff --git a/Lang/Make/Hello-world-Text b/Lang/Make/Hello-world-Text new file mode 120000 index 0000000000..ef4e2d1dad --- /dev/null +++ b/Lang/Make/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Make \ No newline at end of file diff --git a/Lang/Make/Loops-For b/Lang/Make/Loops-For new file mode 120000 index 0000000000..82cf29ebe7 --- /dev/null +++ b/Lang/Make/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Make \ No newline at end of file diff --git a/Lang/Maple/Amicable-pairs b/Lang/Maple/Amicable-pairs new file mode 120000 index 0000000000..73457146b5 --- /dev/null +++ b/Lang/Maple/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Maple \ No newline at end of file diff --git a/Lang/Maple/Bitwise-operations b/Lang/Maple/Bitwise-operations new file mode 120000 index 0000000000..b2c5572f27 --- /dev/null +++ b/Lang/Maple/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Maple \ No newline at end of file diff --git a/Lang/Maple/Character-matching b/Lang/Maple/Character-matching deleted file mode 120000 index a64bf87ae2..0000000000 --- a/Lang/Maple/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Maple \ No newline at end of file diff --git a/Lang/Maple/Colour-bars-Display b/Lang/Maple/Colour-bars-Display new file mode 120000 index 0000000000..fdf833dece --- /dev/null +++ b/Lang/Maple/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/Maple \ No newline at end of file diff --git a/Lang/Maple/Colour-pinstripe-Display b/Lang/Maple/Colour-pinstripe-Display new file mode 120000 index 0000000000..82d4ce1dc1 --- /dev/null +++ b/Lang/Maple/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Maple \ No newline at end of file diff --git a/Lang/Maple/Combinations-and-permutations b/Lang/Maple/Combinations-and-permutations new file mode 120000 index 0000000000..addc288581 --- /dev/null +++ b/Lang/Maple/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Maple \ No newline at end of file diff --git a/Lang/Maple/Continued-fraction b/Lang/Maple/Continued-fraction new file mode 120000 index 0000000000..015384cc38 --- /dev/null +++ b/Lang/Maple/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Maple \ No newline at end of file diff --git a/Lang/Maple/Count-in-octal b/Lang/Maple/Count-in-octal new file mode 120000 index 0000000000..0c01382295 --- /dev/null +++ b/Lang/Maple/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Maple \ No newline at end of file diff --git a/Lang/Maple/Date-format b/Lang/Maple/Date-format new file mode 120000 index 0000000000..0fed85ea78 --- /dev/null +++ b/Lang/Maple/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Maple \ No newline at end of file diff --git a/Lang/Maple/Empty-directory b/Lang/Maple/Empty-directory new file mode 120000 index 0000000000..a1f6729d07 --- /dev/null +++ b/Lang/Maple/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Maple \ No newline at end of file diff --git a/Lang/Maple/Exceptions b/Lang/Maple/Exceptions new file mode 120000 index 0000000000..0d00f32abf --- /dev/null +++ b/Lang/Maple/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Maple \ No newline at end of file diff --git a/Lang/Maple/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Maple/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..112f7458d1 --- /dev/null +++ b/Lang/Maple/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Maple \ No newline at end of file diff --git a/Lang/Maple/File-input-output b/Lang/Maple/File-input-output new file mode 120000 index 0000000000..8f855d7ae8 --- /dev/null +++ b/Lang/Maple/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Maple \ No newline at end of file diff --git a/Lang/Maple/Filter b/Lang/Maple/Filter new file mode 120000 index 0000000000..c1abb017ab --- /dev/null +++ b/Lang/Maple/Filter @@ -0,0 +1 @@ +../../Task/Filter/Maple \ No newline at end of file diff --git a/Lang/Maple/Find-common-directory-path b/Lang/Maple/Find-common-directory-path new file mode 120000 index 0000000000..fb876a88ec --- /dev/null +++ b/Lang/Maple/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Maple \ No newline at end of file diff --git a/Lang/Maple/Hello-world-Newbie b/Lang/Maple/Hello-world-Newbie new file mode 120000 index 0000000000..6cf95f1064 --- /dev/null +++ b/Lang/Maple/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Maple \ No newline at end of file diff --git a/Lang/Maple/Hello-world-Standard-error b/Lang/Maple/Hello-world-Standard-error new file mode 120000 index 0000000000..2857c06b52 --- /dev/null +++ b/Lang/Maple/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Maple \ No newline at end of file diff --git a/Lang/Maple/Image-noise b/Lang/Maple/Image-noise new file mode 120000 index 0000000000..4a0aef10ea --- /dev/null +++ b/Lang/Maple/Image-noise @@ -0,0 +1 @@ +../../Task/Image-noise/Maple \ No newline at end of file diff --git a/Lang/Maple/Input-loop b/Lang/Maple/Input-loop new file mode 120000 index 0000000000..ec02a23ee4 --- /dev/null +++ b/Lang/Maple/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Maple \ No newline at end of file diff --git a/Lang/Mathematica/Casting-out-nines b/Lang/Mathematica/Casting-out-nines new file mode 120000 index 0000000000..82beb7df72 --- /dev/null +++ b/Lang/Mathematica/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Character-matching b/Lang/Mathematica/Character-matching deleted file mode 120000 index 7e5b6b44bc..0000000000 --- a/Lang/Mathematica/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/File-IO b/Lang/Mathematica/File-IO deleted file mode 120000 index 166d039ba5..0000000000 --- a/Lang/Mathematica/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/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/Rosetta-Code-Count-examples b/Lang/Mathematica/Rosetta-Code-Count-examples deleted file mode 120000 index bb39583e78..0000000000 --- a/Lang/Mathematica/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Rosetta-Code-Find-unimplemented-tasks b/Lang/Mathematica/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index 5204326bff..0000000000 --- a/Lang/Mathematica/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Rosetta-Code-Fix-code-tags b/Lang/Mathematica/Rosetta-Code-Fix-code-tags deleted file mode 120000 index 8f79e5aa46..0000000000 --- a/Lang/Mathematica/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Rosetta-Code-Rank-languages-by-popularity b/Lang/Mathematica/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index ccc906ba1a..0000000000 --- a/Lang/Mathematica/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Standard-deviation b/Lang/Mathematica/Standard-deviation deleted file mode 120000 index cfa5a9d5a1..0000000000 --- a/Lang/Mathematica/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Mathematica \ 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/Mercury/File-IO b/Lang/Mercury/File-IO deleted file mode 120000 index c5d0f8ecdd..0000000000 --- a/Lang/Mercury/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Mercury \ 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/Modula-3/File-IO b/Lang/Modula-3/File-IO deleted file mode 120000 index c976bb8e68..0000000000 --- a/Lang/Modula-3/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Modula-3 \ No newline at end of file diff --git a/Lang/Monkey/00DESCRIPTION b/Lang/Monkey/00DESCRIPTION new file mode 100644 index 0000000000..1c0beb36a5 --- /dev/null +++ b/Lang/Monkey/00DESCRIPTION @@ -0,0 +1,4 @@ +{{stub}} +{{language|Monkey}} + +Monkey is a BASIC dialect programming language designed for video game development for many different platforms, including desktop and laptop computers, mobile phones, tablets, and video game consoles. \ No newline at end of file diff --git a/Lang/Monkey/99-Bottles-of-Beer b/Lang/Monkey/99-Bottles-of-Beer new file mode 120000 index 0000000000..d8a4b1bd2b --- /dev/null +++ b/Lang/Monkey/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Monkey \ No newline at end of file diff --git a/Lang/Monkey/README b/Lang/Monkey/README new file mode 100644 index 0000000000..dbda25f906 --- /dev/null +++ b/Lang/Monkey/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Monkey diff --git a/Lang/Moonscript/100-doors b/Lang/Moonscript/100-doors new file mode 120000 index 0000000000..9b0ea6cf57 --- /dev/null +++ b/Lang/Moonscript/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Moonscript \ No newline at end of file diff --git a/Lang/Moonscript/99-Bottles-of-Beer b/Lang/Moonscript/99-Bottles-of-Beer new file mode 120000 index 0000000000..afc5fefad3 --- /dev/null +++ b/Lang/Moonscript/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Moonscript \ No newline at end of file diff --git a/Lang/Moonscript/A+B b/Lang/Moonscript/A+B new file mode 120000 index 0000000000..2176335a17 --- /dev/null +++ b/Lang/Moonscript/A+B @@ -0,0 +1 @@ +../../Task/A+B/Moonscript \ No newline at end of file diff --git a/Lang/Moonscript/FizzBuzz b/Lang/Moonscript/FizzBuzz new file mode 120000 index 0000000000..3dc4c3abc8 --- /dev/null +++ b/Lang/Moonscript/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Moonscript \ No newline at end of file diff --git a/Lang/Moonscript/Read-a-specific-line-from-a-file b/Lang/Moonscript/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..b7d5ce34b4 --- /dev/null +++ b/Lang/Moonscript/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Moonscript \ No newline at end of file diff --git a/Lang/MySQL/100-doors b/Lang/MySQL/100-doors new file mode 120000 index 0000000000..c066aea315 --- /dev/null +++ b/Lang/MySQL/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/MySQL \ No newline at end of file diff --git a/Lang/MySQL/Haversine-formula b/Lang/MySQL/Haversine-formula new file mode 120000 index 0000000000..0effe039c9 --- /dev/null +++ b/Lang/MySQL/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/MySQL \ No newline at end of file diff --git a/Lang/NASL/00DESCRIPTION b/Lang/NASL/00DESCRIPTION new file mode 100644 index 0000000000..6e485df799 --- /dev/null +++ b/Lang/NASL/00DESCRIPTION @@ -0,0 +1,4 @@ +{{stub}} +{{language|NASL}} + +NASL(Nessus Attack Scripting Language), a scripting language for the Nessus Vulnerability Scanner. \ No newline at end of file diff --git a/Lang/NASL/99-Bottles-of-Beer b/Lang/NASL/99-Bottles-of-Beer new file mode 120000 index 0000000000..b9194180fa --- /dev/null +++ b/Lang/NASL/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/NASL \ No newline at end of file diff --git a/Lang/NASL/README b/Lang/NASL/README new file mode 100644 index 0000000000..8d45a996b1 --- /dev/null +++ b/Lang/NASL/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:NASL diff --git a/Lang/NetRexx/Character-matching b/Lang/NetRexx/Character-matching deleted file mode 120000 index 07bd655daf..0000000000 --- a/Lang/NetRexx/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/File-IO b/Lang/NetRexx/File-IO deleted file mode 120000 index d6e591455f..0000000000 --- a/Lang/NetRexx/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/NetRexx \ No newline at end of file diff --git a/Lang/NewLISP/99-Bottles-of-Beer b/Lang/NewLISP/99-Bottles-of-Beer deleted file mode 120000 index 78662ef30b..0000000000 --- a/Lang/NewLISP/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/A+B b/Lang/NewLISP/A+B new file mode 120000 index 0000000000..5e6798efbe --- /dev/null +++ b/Lang/NewLISP/A+B @@ -0,0 +1 @@ +../../Task/A+B/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Accumulator-factory b/Lang/NewLISP/Accumulator-factory new file mode 120000 index 0000000000..ec8cbb6576 --- /dev/null +++ b/Lang/NewLISP/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Conditional-structures b/Lang/NewLISP/Conditional-structures new file mode 120000 index 0000000000..31763787cf --- /dev/null +++ b/Lang/NewLISP/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Dot-product b/Lang/NewLISP/Dot-product new file mode 120000 index 0000000000..7fae5d69d5 --- /dev/null +++ b/Lang/NewLISP/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Factorial b/Lang/NewLISP/Factorial new file mode 120000 index 0000000000..cdfffaf4cf --- /dev/null +++ b/Lang/NewLISP/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/First-class-functions b/Lang/NewLISP/First-class-functions new file mode 120000 index 0000000000..71dcb9a750 --- /dev/null +++ b/Lang/NewLISP/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/HTTP b/Lang/NewLISP/HTTP new file mode 120000 index 0000000000..381adae4ba --- /dev/null +++ b/Lang/NewLISP/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Hello-world-Graphical b/Lang/NewLISP/Hello-world-Graphical new file mode 120000 index 0000000000..032d48ff98 --- /dev/null +++ b/Lang/NewLISP/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Hello-world-Text b/Lang/NewLISP/Hello-world-Text new file mode 120000 index 0000000000..1ef107de57 --- /dev/null +++ b/Lang/NewLISP/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Program-name b/Lang/NewLISP/Program-name new file mode 120000 index 0000000000..ee4bd04a8e --- /dev/null +++ b/Lang/NewLISP/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Substring b/Lang/NewLISP/Substring new file mode 120000 index 0000000000..8bcef5da02 --- /dev/null +++ b/Lang/NewLISP/Substring @@ -0,0 +1 @@ +../../Task/Substring/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/User-input-Text b/Lang/NewLISP/User-input-Text new file mode 120000 index 0000000000..f1ea61f382 --- /dev/null +++ b/Lang/NewLISP/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/XML-Input b/Lang/NewLISP/XML-Input new file mode 120000 index 0000000000..6c6014186a --- /dev/null +++ b/Lang/NewLISP/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/NewLISP \ No newline at end of file diff --git a/Lang/Nim/Almost-prime b/Lang/Nim/Almost-prime new file mode 120000 index 0000000000..26eaebbc33 --- /dev/null +++ b/Lang/Nim/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Nim \ No newline at end of file diff --git a/Lang/Nim/Bitwise-IO b/Lang/Nim/Bitwise-IO new file mode 120000 index 0000000000..14124d6c1b --- /dev/null +++ b/Lang/Nim/Bitwise-IO @@ -0,0 +1 @@ +../../Task/Bitwise-IO/Nim \ No newline at end of file diff --git a/Lang/Nim/Dynamic-variable-names b/Lang/Nim/Dynamic-variable-names new file mode 120000 index 0000000000..ddc5c0ed84 --- /dev/null +++ b/Lang/Nim/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Nim \ No newline at end of file diff --git a/Lang/Nim/Hello-world-Newbie b/Lang/Nim/Hello-world-Newbie new file mode 120000 index 0000000000..f7eff5bced --- /dev/null +++ b/Lang/Nim/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Nim \ No newline at end of file diff --git a/Lang/Nim/Integer-overflow b/Lang/Nim/Integer-overflow new file mode 120000 index 0000000000..3595d8bf8b --- /dev/null +++ b/Lang/Nim/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Nim \ No newline at end of file diff --git a/Lang/Nim/MD5-Implementation b/Lang/Nim/MD5-Implementation new file mode 120000 index 0000000000..4708c6d5ae --- /dev/null +++ b/Lang/Nim/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/Nim \ No newline at end of file diff --git a/Lang/Nim/Semiprime b/Lang/Nim/Semiprime new file mode 120000 index 0000000000..7602cf04d0 --- /dev/null +++ b/Lang/Nim/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Nim \ No newline at end of file diff --git a/Lang/Nim/Synchronous-concurrency b/Lang/Nim/Synchronous-concurrency new file mode 120000 index 0000000000..96c1e717c2 --- /dev/null +++ b/Lang/Nim/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Nim \ No newline at end of file diff --git a/Lang/Nimrod/100-doors b/Lang/Nimrod/100-doors deleted file mode 120000 index 7babab5486..0000000000 --- a/Lang/Nimrod/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/99-Bottles-of-Beer b/Lang/Nimrod/99-Bottles-of-Beer deleted file mode 120000 index 532af5ed6a..0000000000 --- a/Lang/Nimrod/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/A+B b/Lang/Nimrod/A+B deleted file mode 120000 index 1dd0c233cb..0000000000 --- a/Lang/Nimrod/A+B +++ /dev/null @@ -1 +0,0 @@ -../../Task/A+B/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Ackermann-function b/Lang/Nimrod/Ackermann-function deleted file mode 120000 index 966d9b221d..0000000000 --- a/Lang/Nimrod/Ackermann-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ackermann-function/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Anagrams b/Lang/Nimrod/Anagrams deleted file mode 120000 index 6821bfaabf..0000000000 --- a/Lang/Nimrod/Anagrams +++ /dev/null @@ -1 +0,0 @@ -../../Task/Anagrams/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Apply-a-callback-to-an-array b/Lang/Nimrod/Apply-a-callback-to-an-array deleted file mode 120000 index 9f5ea5074a..0000000000 --- a/Lang/Nimrod/Apply-a-callback-to-an-array +++ /dev/null @@ -1 +0,0 @@ -../../Task/Apply-a-callback-to-an-array/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Arithmetic-Complex b/Lang/Nimrod/Arithmetic-Complex deleted file mode 120000 index c6cc45fdd3..0000000000 --- a/Lang/Nimrod/Arithmetic-Complex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Arithmetic-Complex/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Arithmetic-Integer b/Lang/Nimrod/Arithmetic-Integer deleted file mode 120000 index d5748fc3cf..0000000000 --- a/Lang/Nimrod/Arithmetic-Integer +++ /dev/null @@ -1 +0,0 @@ -../../Task/Arithmetic-Integer/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Arithmetic-geometric-mean b/Lang/Nimrod/Arithmetic-geometric-mean deleted file mode 120000 index 98559aa412..0000000000 --- a/Lang/Nimrod/Arithmetic-geometric-mean +++ /dev/null @@ -1 +0,0 @@ -../../Task/Arithmetic-geometric-mean/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Assertions b/Lang/Nimrod/Assertions deleted file mode 120000 index 6e0978fc00..0000000000 --- a/Lang/Nimrod/Assertions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Assertions/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Associative-array-Creation b/Lang/Nimrod/Associative-array-Creation deleted file mode 120000 index 93e293cf72..0000000000 --- a/Lang/Nimrod/Associative-array-Creation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Associative-array-Creation/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Associative-array-Iteration b/Lang/Nimrod/Associative-array-Iteration deleted file mode 120000 index 6677fa138d..0000000000 --- a/Lang/Nimrod/Associative-array-Iteration +++ /dev/null @@ -1 +0,0 @@ -../../Task/Associative-array-Iteration/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Call-a-foreign-language-function b/Lang/Nimrod/Call-a-foreign-language-function deleted file mode 120000 index d11c415cc4..0000000000 --- a/Lang/Nimrod/Call-a-foreign-language-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Call-a-foreign-language-function/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Case-sensitivity-of-identifiers b/Lang/Nimrod/Case-sensitivity-of-identifiers deleted file mode 120000 index c06f362dc0..0000000000 --- a/Lang/Nimrod/Case-sensitivity-of-identifiers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Case-sensitivity-of-identifiers/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Comments b/Lang/Nimrod/Comments deleted file mode 120000 index 726f4bdbf9..0000000000 --- a/Lang/Nimrod/Comments +++ /dev/null @@ -1 +0,0 @@ -../../Task/Comments/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Compile-time-calculation b/Lang/Nimrod/Compile-time-calculation deleted file mode 120000 index 3d86637c69..0000000000 --- a/Lang/Nimrod/Compile-time-calculation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Compile-time-calculation/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Date-format b/Lang/Nimrod/Date-format deleted file mode 120000 index 5b4bb217b9..0000000000 --- a/Lang/Nimrod/Date-format +++ /dev/null @@ -1 +0,0 @@ -../../Task/Date-format/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Delete-a-file b/Lang/Nimrod/Delete-a-file deleted file mode 120000 index c8e62b09b2..0000000000 --- a/Lang/Nimrod/Delete-a-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Delete-a-file/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Execute-Brain---- b/Lang/Nimrod/Execute-Brain---- deleted file mode 120000 index ef0fe3f5eb..0000000000 --- a/Lang/Nimrod/Execute-Brain---- +++ /dev/null @@ -1 +0,0 @@ -../../Task/Execute-Brain----/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Execute-HQ9+ b/Lang/Nimrod/Execute-HQ9+ deleted file mode 120000 index cf2e6e898a..0000000000 --- a/Lang/Nimrod/Execute-HQ9+ +++ /dev/null @@ -1 +0,0 @@ -../../Task/Execute-HQ9+/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Fibonacci-sequence b/Lang/Nimrod/Fibonacci-sequence deleted file mode 120000 index 4d0121d690..0000000000 --- a/Lang/Nimrod/Fibonacci-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Fibonacci-sequence/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/FizzBuzz b/Lang/Nimrod/FizzBuzz deleted file mode 120000 index bf51671747..0000000000 --- a/Lang/Nimrod/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Fork b/Lang/Nimrod/Fork deleted file mode 120000 index 20ce113a50..0000000000 --- a/Lang/Nimrod/Fork +++ /dev/null @@ -1 +0,0 @@ -../../Task/Fork/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Function-definition b/Lang/Nimrod/Function-definition deleted file mode 120000 index 511b8eb7b3..0000000000 --- a/Lang/Nimrod/Function-definition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Function-definition/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/GUI-Maximum-window-dimensions b/Lang/Nimrod/GUI-Maximum-window-dimensions deleted file mode 120000 index a92c706e9e..0000000000 --- a/Lang/Nimrod/GUI-Maximum-window-dimensions +++ /dev/null @@ -1 +0,0 @@ -../../Task/GUI-Maximum-window-dimensions/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/GUI-component-interaction b/Lang/Nimrod/GUI-component-interaction deleted file mode 120000 index 28ebd48db7..0000000000 --- a/Lang/Nimrod/GUI-component-interaction +++ /dev/null @@ -1 +0,0 @@ -../../Task/GUI-component-interaction/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/GUI-enabling-disabling-of-controls b/Lang/Nimrod/GUI-enabling-disabling-of-controls deleted file mode 120000 index 97065feb78..0000000000 --- a/Lang/Nimrod/GUI-enabling-disabling-of-controls +++ /dev/null @@ -1 +0,0 @@ -../../Task/GUI-enabling-disabling-of-controls/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Generic-swap b/Lang/Nimrod/Generic-swap deleted file mode 120000 index c2fadbeddf..0000000000 --- a/Lang/Nimrod/Generic-swap +++ /dev/null @@ -1 +0,0 @@ -../../Task/Generic-swap/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Greatest-common-divisor b/Lang/Nimrod/Greatest-common-divisor deleted file mode 120000 index eae079a612..0000000000 --- a/Lang/Nimrod/Greatest-common-divisor +++ /dev/null @@ -1 +0,0 @@ -../../Task/Greatest-common-divisor/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Greatest-element-of-a-list b/Lang/Nimrod/Greatest-element-of-a-list deleted file mode 120000 index 2637ddf4ef..0000000000 --- a/Lang/Nimrod/Greatest-element-of-a-list +++ /dev/null @@ -1 +0,0 @@ -../../Task/Greatest-element-of-a-list/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Guess-the-number b/Lang/Nimrod/Guess-the-number deleted file mode 120000 index 00b179b288..0000000000 --- a/Lang/Nimrod/Guess-the-number +++ /dev/null @@ -1 +0,0 @@ -../../Task/Guess-the-number/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Hello-world-Text b/Lang/Nimrod/Hello-world-Text deleted file mode 120000 index 7a1c38b68e..0000000000 --- a/Lang/Nimrod/Hello-world-Text +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Text/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Integer-sequence b/Lang/Nimrod/Integer-sequence deleted file mode 120000 index 017167a65b..0000000000 --- a/Lang/Nimrod/Integer-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Integer-sequence/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Loops-Downward-for b/Lang/Nimrod/Loops-Downward-for deleted file mode 120000 index 3de09308a4..0000000000 --- a/Lang/Nimrod/Loops-Downward-for +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Downward-for/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Loops-For b/Lang/Nimrod/Loops-For deleted file mode 120000 index fdf0bc3379..0000000000 --- a/Lang/Nimrod/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Loops-For-with-a-specified-step b/Lang/Nimrod/Loops-For-with-a-specified-step deleted file mode 120000 index 6c1de334d7..0000000000 --- a/Lang/Nimrod/Loops-For-with-a-specified-step +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For-with-a-specified-step/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Loops-Foreach b/Lang/Nimrod/Loops-Foreach deleted file mode 120000 index 741d3f218b..0000000000 --- a/Lang/Nimrod/Loops-Foreach +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Foreach/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Loops-Nested b/Lang/Nimrod/Loops-Nested deleted file mode 120000 index c1983d776d..0000000000 --- a/Lang/Nimrod/Loops-Nested +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Nested/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Loops-While b/Lang/Nimrod/Loops-While deleted file mode 120000 index 6329b3ab8c..0000000000 --- a/Lang/Nimrod/Loops-While +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-While/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/One-dimensional-cellular-automata b/Lang/Nimrod/One-dimensional-cellular-automata deleted file mode 120000 index f5badb8b18..0000000000 --- a/Lang/Nimrod/One-dimensional-cellular-automata +++ /dev/null @@ -1 +0,0 @@ -../../Task/One-dimensional-cellular-automata/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Pascals-triangle-Puzzle b/Lang/Nimrod/Pascals-triangle-Puzzle deleted file mode 120000 index 322268d569..0000000000 --- a/Lang/Nimrod/Pascals-triangle-Puzzle +++ /dev/null @@ -1 +0,0 @@ -../../Task/Pascals-triangle-Puzzle/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Perfect-numbers b/Lang/Nimrod/Perfect-numbers deleted file mode 120000 index deed8bc14c..0000000000 --- a/Lang/Nimrod/Perfect-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Perfect-numbers/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Price-fraction b/Lang/Nimrod/Price-fraction deleted file mode 120000 index 3554aba03b..0000000000 --- a/Lang/Nimrod/Price-fraction +++ /dev/null @@ -1 +0,0 @@ -../../Task/Price-fraction/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Prime-decomposition b/Lang/Nimrod/Prime-decomposition deleted file mode 120000 index a9610bcf46..0000000000 --- a/Lang/Nimrod/Prime-decomposition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Prime-decomposition/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Probabilistic-choice b/Lang/Nimrod/Probabilistic-choice deleted file mode 120000 index 9cfae6f545..0000000000 --- a/Lang/Nimrod/Probabilistic-choice +++ /dev/null @@ -1 +0,0 @@ -../../Task/Probabilistic-choice/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Program-termination b/Lang/Nimrod/Program-termination deleted file mode 120000 index 03aaf2377c..0000000000 --- a/Lang/Nimrod/Program-termination +++ /dev/null @@ -1 +0,0 @@ -../../Task/Program-termination/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Queue-Definition b/Lang/Nimrod/Queue-Definition deleted file mode 120000 index 518190987a..0000000000 --- a/Lang/Nimrod/Queue-Definition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Queue-Definition/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Queue-Usage b/Lang/Nimrod/Queue-Usage deleted file mode 120000 index cc94319545..0000000000 --- a/Lang/Nimrod/Queue-Usage +++ /dev/null @@ -1 +0,0 @@ -../../Task/Queue-Usage/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Random-numbers b/Lang/Nimrod/Random-numbers deleted file mode 120000 index 06065934af..0000000000 --- a/Lang/Nimrod/Random-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Random-numbers/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Range-expansion b/Lang/Nimrod/Range-expansion deleted file mode 120000 index 5fb0094a2d..0000000000 --- a/Lang/Nimrod/Range-expansion +++ /dev/null @@ -1 +0,0 @@ -../../Task/Range-expansion/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Range-extraction b/Lang/Nimrod/Range-extraction deleted file mode 120000 index 0bf5dcc076..0000000000 --- a/Lang/Nimrod/Range-extraction +++ /dev/null @@ -1 +0,0 @@ -../../Task/Range-extraction/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Read-entire-file b/Lang/Nimrod/Read-entire-file deleted file mode 120000 index ddeee23dfb..0000000000 --- a/Lang/Nimrod/Read-entire-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Read-entire-file/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Repeat-a-string b/Lang/Nimrod/Repeat-a-string deleted file mode 120000 index 61b3b9a2d8..0000000000 --- a/Lang/Nimrod/Repeat-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Repeat-a-string/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Reverse-a-string b/Lang/Nimrod/Reverse-a-string deleted file mode 120000 index 6f7db44df6..0000000000 --- a/Lang/Nimrod/Reverse-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Reverse-a-string/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Sieve-of-Eratosthenes b/Lang/Nimrod/Sieve-of-Eratosthenes deleted file mode 120000 index 1297795e4f..0000000000 --- a/Lang/Nimrod/Sieve-of-Eratosthenes +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sieve-of-Eratosthenes/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Sleep b/Lang/Nimrod/Sleep deleted file mode 120000 index 66956689ed..0000000000 --- a/Lang/Nimrod/Sleep +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sleep/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Solve-a-Hidato-puzzle b/Lang/Nimrod/Solve-a-Hidato-puzzle deleted file mode 120000 index d61aa04fa9..0000000000 --- a/Lang/Nimrod/Solve-a-Hidato-puzzle +++ /dev/null @@ -1 +0,0 @@ -../../Task/Solve-a-Hidato-puzzle/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Sort-an-integer-array b/Lang/Nimrod/Sort-an-integer-array deleted file mode 120000 index 42bb935745..0000000000 --- a/Lang/Nimrod/Sort-an-integer-array +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sort-an-integer-array/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Sorting-algorithms-Quicksort b/Lang/Nimrod/Sorting-algorithms-Quicksort deleted file mode 120000 index abe9c784fe..0000000000 --- a/Lang/Nimrod/Sorting-algorithms-Quicksort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Quicksort/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Stack b/Lang/Nimrod/Stack deleted file mode 120000 index 31ade3675a..0000000000 --- a/Lang/Nimrod/Stack +++ /dev/null @@ -1 +0,0 @@ -../../Task/Stack/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/String-case b/Lang/Nimrod/String-case deleted file mode 120000 index fece91f339..0000000000 --- a/Lang/Nimrod/String-case +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-case/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/String-comparison b/Lang/Nimrod/String-comparison deleted file mode 120000 index 4c24a06e67..0000000000 --- a/Lang/Nimrod/String-comparison +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-comparison/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/String-concatenation b/Lang/Nimrod/String-concatenation deleted file mode 120000 index 228a56b383..0000000000 --- a/Lang/Nimrod/String-concatenation +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-concatenation/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/String-interpolation--included- b/Lang/Nimrod/String-interpolation--included- deleted file mode 120000 index b743264085..0000000000 --- a/Lang/Nimrod/String-interpolation--included- +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-interpolation--included-/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/String-length b/Lang/Nimrod/String-length deleted file mode 120000 index 0f5b919049..0000000000 --- a/Lang/Nimrod/String-length +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-length/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Strip-a-set-of-characters-from-a-string b/Lang/Nimrod/Strip-a-set-of-characters-from-a-string deleted file mode 120000 index 9d96b47c83..0000000000 --- a/Lang/Nimrod/Strip-a-set-of-characters-from-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Strip-a-set-of-characters-from-a-string/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Substring-Top-and-tail b/Lang/Nimrod/Substring-Top-and-tail deleted file mode 120000 index d68fc8afd3..0000000000 --- a/Lang/Nimrod/Substring-Top-and-tail +++ /dev/null @@ -1 +0,0 @@ -../../Task/Substring-Top-and-tail/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/System-time b/Lang/Nimrod/System-time deleted file mode 120000 index 0728bd97dd..0000000000 --- a/Lang/Nimrod/System-time +++ /dev/null @@ -1 +0,0 @@ -../../Task/System-time/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Towers-of-Hanoi b/Lang/Nimrod/Towers-of-Hanoi deleted file mode 120000 index 8bbb6dc0ee..0000000000 --- a/Lang/Nimrod/Towers-of-Hanoi +++ /dev/null @@ -1 +0,0 @@ -../../Task/Towers-of-Hanoi/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Unicode-variable-names b/Lang/Nimrod/Unicode-variable-names deleted file mode 120000 index ba8d276e84..0000000000 --- a/Lang/Nimrod/Unicode-variable-names +++ /dev/null @@ -1 +0,0 @@ -../../Task/Unicode-variable-names/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Window-creation b/Lang/Nimrod/Window-creation deleted file mode 120000 index e14412a69c..0000000000 --- a/Lang/Nimrod/Window-creation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Window-creation/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Window-management b/Lang/Nimrod/Window-management deleted file mode 120000 index 6489526dad..0000000000 --- a/Lang/Nimrod/Window-management +++ /dev/null @@ -1 +0,0 @@ -../../Task/Window-management/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Write-float-arrays-to-a-text-file b/Lang/Nimrod/Write-float-arrays-to-a-text-file deleted file mode 120000 index 5abd0f821c..0000000000 --- a/Lang/Nimrod/Write-float-arrays-to-a-text-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Write-float-arrays-to-a-text-file/Nimrod \ No newline at end of file diff --git a/Lang/Nit/24-game b/Lang/Nit/24-game new file mode 120000 index 0000000000..8078924625 --- /dev/null +++ b/Lang/Nit/24-game @@ -0,0 +1 @@ +../../Task/24-game/Nit \ No newline at end of file diff --git a/Lang/Nit/Accumulator-factory b/Lang/Nit/Accumulator-factory new file mode 120000 index 0000000000..924a639af9 --- /dev/null +++ b/Lang/Nit/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Nit \ No newline at end of file diff --git a/Lang/Nit/Ackermann-function b/Lang/Nit/Ackermann-function new file mode 120000 index 0000000000..a1ddca72cc --- /dev/null +++ b/Lang/Nit/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Nit \ No newline at end of file diff --git a/Lang/Nit/Align-columns b/Lang/Nit/Align-columns new file mode 120000 index 0000000000..5df08f91d6 --- /dev/null +++ b/Lang/Nit/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Nit \ No newline at end of file diff --git a/Lang/OASYS-Assembler/00DESCRIPTION b/Lang/OASYS-Assembler/00DESCRIPTION new file mode 100644 index 0000000000..825c66397d --- /dev/null +++ b/Lang/OASYS-Assembler/00DESCRIPTION @@ -0,0 +1,5 @@ +{{stub}} +{{language|OASYS Assembler +|tags=oasys)oaa}} + +OASYS is an old system for text adventure games. OASYS VM actually has two different programming languages, OAC (OASYS C; the original one) and OAA (OASYS Assembler) \ No newline at end of file diff --git a/Lang/OASYS-Assembler/Call-an-object-method b/Lang/OASYS-Assembler/Call-an-object-method new file mode 120000 index 0000000000..9614777c0e --- /dev/null +++ b/Lang/OASYS-Assembler/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/OASYS-Assembler \ No newline at end of file diff --git a/Lang/OASYS-Assembler/Function-definition b/Lang/OASYS-Assembler/Function-definition new file mode 120000 index 0000000000..0d88d70d2a --- /dev/null +++ b/Lang/OASYS-Assembler/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/OASYS-Assembler \ No newline at end of file diff --git a/Lang/OASYS-Assembler/Generic-swap b/Lang/OASYS-Assembler/Generic-swap new file mode 120000 index 0000000000..468827d85d --- /dev/null +++ b/Lang/OASYS-Assembler/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/OASYS-Assembler \ No newline at end of file diff --git a/Lang/OASYS-Assembler/README b/Lang/OASYS-Assembler/README new file mode 100644 index 0000000000..fa71c841e3 --- /dev/null +++ b/Lang/OASYS-Assembler/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:OASYS_Assembler diff --git a/Lang/OASYS/00DESCRIPTION b/Lang/OASYS/00DESCRIPTION new file mode 100644 index 0000000000..42d9ed85f0 --- /dev/null +++ b/Lang/OASYS/00DESCRIPTION @@ -0,0 +1,5 @@ +{{stub}} +{{language|OASYS +|tags=oasys}} + +OASYS is an old system for text adventure games. OASYS VM actually has two different programming languages, OAC (OASYS C; the original one) and OAA (OASYS Assembler) \ No newline at end of file diff --git a/Lang/OASYS/99-Bottles-of-Beer b/Lang/OASYS/99-Bottles-of-Beer new file mode 120000 index 0000000000..11cedc4c51 --- /dev/null +++ b/Lang/OASYS/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/OASYS \ No newline at end of file diff --git a/Lang/OASYS/Function-definition b/Lang/OASYS/Function-definition new file mode 120000 index 0000000000..81c70f82a2 --- /dev/null +++ b/Lang/OASYS/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/OASYS \ No newline at end of file diff --git a/Lang/OASYS/README b/Lang/OASYS/README new file mode 100644 index 0000000000..05068fd92e --- /dev/null +++ b/Lang/OASYS/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:OASYS diff --git a/Lang/OCaml/Arithmetic-geometric-mean-Calculate-Pi b/Lang/OCaml/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..0764266615 --- /dev/null +++ b/Lang/OCaml/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Catalan-numbers b/Lang/OCaml/Catalan-numbers new file mode 120000 index 0000000000..17de4dacf3 --- /dev/null +++ b/Lang/OCaml/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Character-matching b/Lang/OCaml/Character-matching deleted file mode 120000 index 1b9d904b68..0000000000 --- a/Lang/OCaml/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/OCaml \ No newline at end of file diff --git a/Lang/OCaml/File-IO b/Lang/OCaml/File-IO deleted file mode 120000 index 8557844849..0000000000 --- a/Lang/OCaml/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/OCaml \ No newline at end of file diff --git a/Lang/OCaml/History-variables b/Lang/OCaml/History-variables new file mode 120000 index 0000000000..7f40f08823 --- /dev/null +++ b/Lang/OCaml/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Mutex b/Lang/OCaml/Mutex deleted file mode 120000 index c020f85a23..0000000000 --- a/Lang/OCaml/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Nth b/Lang/OCaml/Nth new file mode 120000 index 0000000000..f77f00fb18 --- /dev/null +++ b/Lang/OCaml/Nth @@ -0,0 +1 @@ +../../Task/Nth/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Parsing-Shunting-yard-algorithm b/Lang/OCaml/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..1124113433 --- /dev/null +++ b/Lang/OCaml/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Rosetta-Code-Count-examples b/Lang/OCaml/Rosetta-Code-Count-examples deleted file mode 120000 index 2873044c05..0000000000 --- a/Lang/OCaml/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Rosetta-Code-Fix-code-tags b/Lang/OCaml/Rosetta-Code-Fix-code-tags deleted file mode 120000 index 8991da0ace..0000000000 --- a/Lang/OCaml/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Standard-deviation b/Lang/OCaml/Standard-deviation deleted file mode 120000 index bc81d222ec..0000000000 --- a/Lang/OCaml/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Write-language-name-in-3D-ASCII b/Lang/OCaml/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..a32f413700 --- /dev/null +++ b/Lang/OCaml/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/OCaml \ No newline at end of file diff --git a/Lang/Oberon-2/Compound-data-type b/Lang/Oberon-2/Compound-data-type new file mode 120000 index 0000000000..914cd5b5bc --- /dev/null +++ b/Lang/Oberon-2/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Doubly-linked-list-Definition b/Lang/Oberon-2/Doubly-linked-list-Definition new file mode 120000 index 0000000000..80a71832d0 --- /dev/null +++ b/Lang/Oberon-2/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Doubly-linked-list-Element-definition b/Lang/Oberon-2/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..542d6515dc --- /dev/null +++ b/Lang/Oberon-2/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Doubly-linked-list-Element-insertion b/Lang/Oberon-2/Doubly-linked-list-Element-insertion new file mode 120000 index 0000000000..e075d2babc --- /dev/null +++ b/Lang/Oberon-2/Doubly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-insertion/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Doubly-linked-list-Traversal b/Lang/Oberon-2/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..e0c859e730 --- /dev/null +++ b/Lang/Oberon-2/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Empty-string b/Lang/Oberon-2/Empty-string new file mode 120000 index 0000000000..23e4dae404 --- /dev/null +++ b/Lang/Oberon-2/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Oberon-2 \ No newline at end of file diff --git a/Lang/Objeck/00DESCRIPTION b/Lang/Objeck/00DESCRIPTION index 6bed07cf68..2aacf5a086 100644 --- a/Lang/Objeck/00DESCRIPTION +++ b/Lang/Objeck/00DESCRIPTION @@ -13,4 +13,4 @@ The '''Objeck Programming Language''' is an [[object-oriented]] computing langua The programming environment consists of an optimizing compiler, command-line debugger and virtual machine with associated [[Garbage collection|garbage collector]] and [[JIT]] compiler. The compiler emits binary [[bytecode]] that is executed by the runtime system. The runtime system has the ability to translate the bytecode into AMD64 or IA-32 executable machine code on the fly. -For more information check out the [http://www.objeck.org/docs/objeck_lang.pdf Programmer's Guide] or this YouTube [https://www.youtube.com/watch?v=IUaQYdw02TU video]. The language can be [http://sourceforge.net/projects/objeck-lang/files/ obtained] from the main project homepage. Also, check out the IRC channel #objeck on freenode.net. \ No newline at end of file +For more information check out the [http://www.objeck.org/docs/objeck_lang.pdf Programmer's Guide] or this YouTube [https://www.youtube.com/watch?v=IUaQYdw02TU video]. The language can be [http://www.objeck.org obtained] from the main project homepage. \ No newline at end of file diff --git a/Lang/Objeck/Character-matching b/Lang/Objeck/Character-matching deleted file mode 120000 index d06b853385..0000000000 --- a/Lang/Objeck/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Doubly-linked-list-Definition b/Lang/Objeck/Doubly-linked-list-Definition new file mode 120000 index 0000000000..aef2ce6ba3 --- /dev/null +++ b/Lang/Objeck/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Execute-Brain---- b/Lang/Objeck/Execute-Brain---- new file mode 120000 index 0000000000..a4c9356ab4 --- /dev/null +++ b/Lang/Objeck/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Objeck \ No newline at end of file diff --git a/Lang/Objeck/File-IO b/Lang/Objeck/File-IO deleted file mode 120000 index 1382ae77bc..0000000000 --- a/Lang/Objeck/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Objeck \ No newline at end of file diff --git a/Lang/Objeck/File-modification-time b/Lang/Objeck/File-modification-time new file mode 120000 index 0000000000..8c56e93e27 --- /dev/null +++ b/Lang/Objeck/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Mutex b/Lang/Objeck/Mutex deleted file mode 120000 index d21333276c..0000000000 --- a/Lang/Objeck/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Quine b/Lang/Objeck/Quine new file mode 120000 index 0000000000..469a22a709 --- /dev/null +++ b/Lang/Objeck/Quine @@ -0,0 +1 @@ +../../Task/Quine/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Rosetta-Code-Count-examples b/Lang/Objeck/Rosetta-Code-Count-examples deleted file mode 120000 index 2ab7a0001b..0000000000 --- a/Lang/Objeck/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Rosetta-Code-Rank-languages-by-popularity b/Lang/Objeck/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index da151e30b0..0000000000 --- a/Lang/Objeck/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sort-using-a-custom-comparator b/Lang/Objeck/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..34a8e41ae4 --- /dev/null +++ b/Lang/Objeck/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Standard-deviation b/Lang/Objeck/Standard-deviation deleted file mode 120000 index edfd5e9636..0000000000 --- a/Lang/Objeck/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Objeck \ No newline at end of file diff --git a/Lang/Objeck/String-prepend b/Lang/Objeck/String-prepend new file mode 120000 index 0000000000..45a1d2899c --- /dev/null +++ b/Lang/Objeck/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Objeck \ No newline at end of file diff --git a/Lang/Object-Pascal/File-IO b/Lang/Object-Pascal/File-IO deleted file mode 120000 index f5635ded4a..0000000000 --- a/Lang/Object-Pascal/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Object-Pascal \ No newline at end of file diff --git a/Lang/Objective-C/Character-matching b/Lang/Objective-C/Character-matching deleted file mode 120000 index b8714f4e95..0000000000 --- a/Lang/Objective-C/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/File-IO b/Lang/Objective-C/File-IO deleted file mode 120000 index 9d37d889c2..0000000000 --- a/Lang/Objective-C/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Mutex b/Lang/Objective-C/Mutex deleted file mode 120000 index 543a721133..0000000000 --- a/Lang/Objective-C/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Standard-deviation b/Lang/Objective-C/Standard-deviation deleted file mode 120000 index 6c35bd9b48..0000000000 --- a/Lang/Objective-C/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Objective-C \ No newline at end of file diff --git a/Lang/Octave/Runtime-evaluation-In-an-environment b/Lang/Octave/Runtime-evaluation-In-an-environment deleted file mode 120000 index f6e9b92036..0000000000 --- a/Lang/Octave/Runtime-evaluation-In-an-environment +++ /dev/null @@ -1 +0,0 @@ -../../Task/Runtime-evaluation-In-an-environment/Octave \ No newline at end of file diff --git a/Lang/Ol/00DESCRIPTION b/Lang/Ol/00DESCRIPTION index 5d57b6433f..cc4d77196d 100644 --- a/Lang/Ol/00DESCRIPTION +++ b/Lang/Ol/00DESCRIPTION @@ -1,14 +1,22 @@ -{{language -|exec=interpreted +{{language|Ol (Otus Lisp) +|exec=both +|parampass=both +|safety=safe +|strength=strong +|express=implicit |checking=dynamic |gc=yes -|site=http://yuriy-chumak.github.io/OL/}} -{{implementation|Lisp}} +|LCT=no +|site=http://yuriy-chumak.github.io/ol/}} [[Category:Lisp Implementations]] +[[Category:Scheme Implementations]] -'''OL (Owl Lisp)''' is a purely (mostly) functional dialect of Lisp. It implements an extended subset of R5RS Scheme. +{{language programming paradigm|functional}} +Ol (Otus Lisp) is a purely* functional dialect of [[derived from::Lisp]]. It implements an extended subset of [http://www.schemers.org/Documents/Standards/R5RS/ R5RS] Scheme including, but not limited to, some of the [http://srfi.schemers.org/ SRFI], open source / free software, with a permissive license. -You can try RosettaCode tasks directly in the project page. +It is small, embeddable and crossplatform. -==See Also== -* [https://github.com/yuriy-chumak/OL Github project page] \ No newline at end of file +Builds and source codes can be found at project [https://yuriy-chumak.github.io/ol/ home page] or [https://github.com/yuriy-chumak/ol Github]. + +{{implementation|Lisp}} +{{implementation|Scheme}} \ No newline at end of file diff --git a/Lang/Ol/A+B b/Lang/Ol/A+B new file mode 120000 index 0000000000..804e417976 --- /dev/null +++ b/Lang/Ol/A+B @@ -0,0 +1 @@ +../../Task/A+B/Ol \ No newline at end of file diff --git a/Lang/Ol/Apply-a-callback-to-an-array b/Lang/Ol/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..1476f179a0 --- /dev/null +++ b/Lang/Ol/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Ol \ No newline at end of file diff --git a/Lang/Ol/Arithmetic-Complex b/Lang/Ol/Arithmetic-Complex new file mode 120000 index 0000000000..fb31feaeb4 --- /dev/null +++ b/Lang/Ol/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Ol \ No newline at end of file diff --git a/Lang/Ol/Arithmetic-Integer b/Lang/Ol/Arithmetic-Integer new file mode 120000 index 0000000000..01286663bf --- /dev/null +++ b/Lang/Ol/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Ol \ No newline at end of file diff --git a/Lang/Ol/Associative-array-Creation b/Lang/Ol/Associative-array-Creation new file mode 120000 index 0000000000..ab13f49af9 --- /dev/null +++ b/Lang/Ol/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Ol \ No newline at end of file diff --git a/Lang/Ol/Associative-array-Iteration b/Lang/Ol/Associative-array-Iteration new file mode 120000 index 0000000000..1514955086 --- /dev/null +++ b/Lang/Ol/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Ol \ No newline at end of file diff --git a/Lang/Ol/Call-a-function b/Lang/Ol/Call-a-function new file mode 120000 index 0000000000..a02763fcd7 --- /dev/null +++ b/Lang/Ol/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Ol \ No newline at end of file diff --git a/Lang/Ol/Empty-string b/Lang/Ol/Empty-string new file mode 120000 index 0000000000..c5321f3747 --- /dev/null +++ b/Lang/Ol/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Ol \ No newline at end of file diff --git a/Lang/Ol/Ethiopian-multiplication b/Lang/Ol/Ethiopian-multiplication new file mode 120000 index 0000000000..958db4b586 --- /dev/null +++ b/Lang/Ol/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Ol \ No newline at end of file diff --git a/Lang/Ol/Execute-Brain---- b/Lang/Ol/Execute-Brain---- new file mode 120000 index 0000000000..2400aa3a32 --- /dev/null +++ b/Lang/Ol/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Ol \ No newline at end of file diff --git a/Lang/Ol/Greatest-element-of-a-list b/Lang/Ol/Greatest-element-of-a-list new file mode 120000 index 0000000000..b504ec04f8 --- /dev/null +++ b/Lang/Ol/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Ol \ No newline at end of file diff --git a/Lang/Ol/Guess-the-number b/Lang/Ol/Guess-the-number new file mode 120000 index 0000000000..4e75aa2be4 --- /dev/null +++ b/Lang/Ol/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Ol \ No newline at end of file diff --git a/Lang/Ol/Guess-the-number-With-feedback b/Lang/Ol/Guess-the-number-With-feedback new file mode 120000 index 0000000000..69dc033b36 --- /dev/null +++ b/Lang/Ol/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Ol \ No newline at end of file diff --git a/Lang/Ol/Hello-world-Web-server b/Lang/Ol/Hello-world-Web-server new file mode 120000 index 0000000000..5698f58a34 --- /dev/null +++ b/Lang/Ol/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Ol \ No newline at end of file diff --git a/Lang/Ol/Morse-code b/Lang/Ol/Morse-code new file mode 120000 index 0000000000..84a53bc911 --- /dev/null +++ b/Lang/Ol/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Ol \ No newline at end of file diff --git a/Lang/Ol/Quine b/Lang/Ol/Quine new file mode 120000 index 0000000000..6e1c4fa65c --- /dev/null +++ b/Lang/Ol/Quine @@ -0,0 +1 @@ +../../Task/Quine/Ol \ No newline at end of file diff --git a/Lang/Ol/Special-characters b/Lang/Ol/Special-characters new file mode 120000 index 0000000000..233068d3de --- /dev/null +++ b/Lang/Ol/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/Ol \ No newline at end of file diff --git a/Lang/Ol/String-length b/Lang/Ol/String-length new file mode 120000 index 0000000000..a3ab6aca16 --- /dev/null +++ b/Lang/Ol/String-length @@ -0,0 +1 @@ +../../Task/String-length/Ol \ No newline at end of file diff --git a/Lang/Ol/Word-wrap b/Lang/Ol/Word-wrap new file mode 120000 index 0000000000..928a3bf73b --- /dev/null +++ b/Lang/Ol/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Ol \ No newline at end of file diff --git a/Lang/OoRexx/100-doors b/Lang/OoRexx/100-doors new file mode 120000 index 0000000000..2ce8117c0b --- /dev/null +++ b/Lang/OoRexx/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/A+B b/Lang/OoRexx/A+B new file mode 120000 index 0000000000..b1078fe078 --- /dev/null +++ b/Lang/OoRexx/A+B @@ -0,0 +1 @@ +../../Task/A+B/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Abstract-type b/Lang/OoRexx/Abstract-type new file mode 120000 index 0000000000..5520700968 --- /dev/null +++ b/Lang/OoRexx/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Accumulator-factory b/Lang/OoRexx/Accumulator-factory new file mode 120000 index 0000000000..ab8ac5de22 --- /dev/null +++ b/Lang/OoRexx/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Ackermann-function b/Lang/OoRexx/Ackermann-function new file mode 120000 index 0000000000..fb841c3723 --- /dev/null +++ b/Lang/OoRexx/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Active-Directory-Search-for-a-user b/Lang/OoRexx/Active-Directory-Search-for-a-user new file mode 120000 index 0000000000..ee29e92cb0 --- /dev/null +++ b/Lang/OoRexx/Active-Directory-Search-for-a-user @@ -0,0 +1 @@ +../../Task/Active-Directory-Search-for-a-user/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Active-object b/Lang/OoRexx/Active-object new file mode 120000 index 0000000000..ad1bb6df56 --- /dev/null +++ b/Lang/OoRexx/Active-object @@ -0,0 +1 @@ +../../Task/Active-object/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Add-a-variable-to-a-class-instance-at-runtime b/Lang/OoRexx/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..33184e4809 --- /dev/null +++ b/Lang/OoRexx/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Align-columns b/Lang/OoRexx/Align-columns new file mode 120000 index 0000000000..4e986e22dd --- /dev/null +++ b/Lang/OoRexx/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Anagrams b/Lang/OoRexx/Anagrams new file mode 120000 index 0000000000..7114d8e6d4 --- /dev/null +++ b/Lang/OoRexx/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Anagrams-Deranged-anagrams b/Lang/OoRexx/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..8ca73570da --- /dev/null +++ b/Lang/OoRexx/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Animate-a-pendulum b/Lang/OoRexx/Animate-a-pendulum new file mode 120000 index 0000000000..9d72886c76 --- /dev/null +++ b/Lang/OoRexx/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Apply-a-callback-to-an-array b/Lang/OoRexx/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..975da41360 --- /dev/null +++ b/Lang/OoRexx/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Arbitrary-precision-integers--included- b/Lang/OoRexx/Arbitrary-precision-integers--included- new file mode 120000 index 0000000000..09c028191f --- /dev/null +++ b/Lang/OoRexx/Arbitrary-precision-integers--included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers--included-/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Arithmetic-Complex b/Lang/OoRexx/Arithmetic-Complex new file mode 120000 index 0000000000..12e9daf498 --- /dev/null +++ b/Lang/OoRexx/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Arithmetic-Rational b/Lang/OoRexx/Arithmetic-Rational new file mode 120000 index 0000000000..5dd10089b1 --- /dev/null +++ b/Lang/OoRexx/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Arithmetic-evaluation b/Lang/OoRexx/Arithmetic-evaluation new file mode 120000 index 0000000000..67f54c0886 --- /dev/null +++ b/Lang/OoRexx/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Arithmetic-geometric-mean b/Lang/OoRexx/Arithmetic-geometric-mean new file mode 120000 index 0000000000..9d64e655e8 --- /dev/null +++ b/Lang/OoRexx/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Array-concatenation b/Lang/OoRexx/Array-concatenation new file mode 120000 index 0000000000..545634d06f --- /dev/null +++ b/Lang/OoRexx/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Arrays b/Lang/OoRexx/Arrays new file mode 120000 index 0000000000..67cebeacf8 --- /dev/null +++ b/Lang/OoRexx/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Associative-array-Creation b/Lang/OoRexx/Associative-array-Creation new file mode 120000 index 0000000000..4e0fc46a6e --- /dev/null +++ b/Lang/OoRexx/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Associative-array-Iteration b/Lang/OoRexx/Associative-array-Iteration new file mode 120000 index 0000000000..3e15940fe1 --- /dev/null +++ b/Lang/OoRexx/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Averages-Arithmetic-mean b/Lang/OoRexx/Averages-Arithmetic-mean new file mode 120000 index 0000000000..5d0ddc8328 --- /dev/null +++ b/Lang/OoRexx/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Averages-Mean-angle b/Lang/OoRexx/Averages-Mean-angle new file mode 120000 index 0000000000..0d324659f9 --- /dev/null +++ b/Lang/OoRexx/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Averages-Mean-time-of-day b/Lang/OoRexx/Averages-Mean-time-of-day new file mode 120000 index 0000000000..045f719143 --- /dev/null +++ b/Lang/OoRexx/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Averages-Median b/Lang/OoRexx/Averages-Median new file mode 120000 index 0000000000..c07160c711 --- /dev/null +++ b/Lang/OoRexx/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Averages-Mode b/Lang/OoRexx/Averages-Mode new file mode 120000 index 0000000000..65c9a86295 --- /dev/null +++ b/Lang/OoRexx/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Averages-Pythagorean-means b/Lang/OoRexx/Averages-Pythagorean-means new file mode 120000 index 0000000000..6108bdf915 --- /dev/null +++ b/Lang/OoRexx/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Averages-Root-mean-square b/Lang/OoRexx/Averages-Root-mean-square new file mode 120000 index 0000000000..7ba8b172df --- /dev/null +++ b/Lang/OoRexx/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Averages-Simple-moving-average b/Lang/OoRexx/Averages-Simple-moving-average new file mode 120000 index 0000000000..d5713ac47b --- /dev/null +++ b/Lang/OoRexx/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Balanced-brackets b/Lang/OoRexx/Balanced-brackets new file mode 120000 index 0000000000..e433107f3f --- /dev/null +++ b/Lang/OoRexx/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Binary-search b/Lang/OoRexx/Binary-search new file mode 120000 index 0000000000..0c88520573 --- /dev/null +++ b/Lang/OoRexx/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Bitwise-operations b/Lang/OoRexx/Bitwise-operations new file mode 120000 index 0000000000..5838b245ea --- /dev/null +++ b/Lang/OoRexx/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/CRC-32 b/Lang/OoRexx/CRC-32 new file mode 120000 index 0000000000..5b5e8429b7 --- /dev/null +++ b/Lang/OoRexx/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Call-an-object-method b/Lang/OoRexx/Call-an-object-method new file mode 120000 index 0000000000..87bc14f93f --- /dev/null +++ b/Lang/OoRexx/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Catalan-numbers b/Lang/OoRexx/Catalan-numbers new file mode 120000 index 0000000000..43fffd6e61 --- /dev/null +++ b/Lang/OoRexx/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Check-Machin-like-formulas b/Lang/OoRexx/Check-Machin-like-formulas new file mode 120000 index 0000000000..f59223b75c --- /dev/null +++ b/Lang/OoRexx/Check-Machin-like-formulas @@ -0,0 +1 @@ +../../Task/Check-Machin-like-formulas/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Check-that-file-exists b/Lang/OoRexx/Check-that-file-exists new file mode 120000 index 0000000000..8f3900990e --- /dev/null +++ b/Lang/OoRexx/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Cholesky-decomposition b/Lang/OoRexx/Cholesky-decomposition new file mode 120000 index 0000000000..b942b1119d --- /dev/null +++ b/Lang/OoRexx/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Circles-of-given-radius-through-two-points b/Lang/OoRexx/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..6b4dd333d3 --- /dev/null +++ b/Lang/OoRexx/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Classes b/Lang/OoRexx/Classes new file mode 120000 index 0000000000..981219b49c --- /dev/null +++ b/Lang/OoRexx/Classes @@ -0,0 +1 @@ +../../Task/Classes/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Collections b/Lang/OoRexx/Collections new file mode 120000 index 0000000000..5b0b75e6b0 --- /dev/null +++ b/Lang/OoRexx/Collections @@ -0,0 +1 @@ +../../Task/Collections/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Comments b/Lang/OoRexx/Comments new file mode 120000 index 0000000000..0bfb69f325 --- /dev/null +++ b/Lang/OoRexx/Comments @@ -0,0 +1 @@ +../../Task/Comments/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Compound-data-type b/Lang/OoRexx/Compound-data-type new file mode 120000 index 0000000000..1c56afc3f7 --- /dev/null +++ b/Lang/OoRexx/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Concurrent-computing b/Lang/OoRexx/Concurrent-computing new file mode 120000 index 0000000000..b63082dcd3 --- /dev/null +++ b/Lang/OoRexx/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Conditional-structures b/Lang/OoRexx/Conditional-structures new file mode 120000 index 0000000000..e8b2d32b79 --- /dev/null +++ b/Lang/OoRexx/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Constrained-genericity b/Lang/OoRexx/Constrained-genericity new file mode 120000 index 0000000000..32516d44c8 --- /dev/null +++ b/Lang/OoRexx/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Conways-Game-of-Life b/Lang/OoRexx/Conways-Game-of-Life new file mode 120000 index 0000000000..b6ae71dca5 --- /dev/null +++ b/Lang/OoRexx/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Copy-a-string b/Lang/OoRexx/Copy-a-string new file mode 120000 index 0000000000..96929dd36b --- /dev/null +++ b/Lang/OoRexx/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Count-occurrences-of-a-substring b/Lang/OoRexx/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..bb48b0749b --- /dev/null +++ b/Lang/OoRexx/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Create-a-two-dimensional-array-at-runtime b/Lang/OoRexx/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..9af8cdffe9 --- /dev/null +++ b/Lang/OoRexx/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Date-manipulation b/Lang/OoRexx/Date-manipulation new file mode 120000 index 0000000000..d99d00f944 --- /dev/null +++ b/Lang/OoRexx/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Day-of-the-week b/Lang/OoRexx/Day-of-the-week new file mode 120000 index 0000000000..40a2d31662 --- /dev/null +++ b/Lang/OoRexx/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Define-a-primitive-data-type b/Lang/OoRexx/Define-a-primitive-data-type new file mode 120000 index 0000000000..ad2d3839fb --- /dev/null +++ b/Lang/OoRexx/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Delegates b/Lang/OoRexx/Delegates new file mode 120000 index 0000000000..0b1460fdfe --- /dev/null +++ b/Lang/OoRexx/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Delete-a-file b/Lang/OoRexx/Delete-a-file new file mode 120000 index 0000000000..c5c4e5131c --- /dev/null +++ b/Lang/OoRexx/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Detect-division-by-zero b/Lang/OoRexx/Detect-division-by-zero new file mode 120000 index 0000000000..a263ae1a21 --- /dev/null +++ b/Lang/OoRexx/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Draw-a-clock b/Lang/OoRexx/Draw-a-clock new file mode 120000 index 0000000000..c466c814d7 --- /dev/null +++ b/Lang/OoRexx/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Empty-directory b/Lang/OoRexx/Empty-directory new file mode 120000 index 0000000000..a55b0351dc --- /dev/null +++ b/Lang/OoRexx/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Empty-string b/Lang/OoRexx/Empty-string new file mode 120000 index 0000000000..b61852bb35 --- /dev/null +++ b/Lang/OoRexx/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Fast-Fourier-transform b/Lang/OoRexx/Fast-Fourier-transform new file mode 120000 index 0000000000..12bb64c40d --- /dev/null +++ b/Lang/OoRexx/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Fibonacci-word b/Lang/OoRexx/Fibonacci-word new file mode 120000 index 0000000000..553d3433cd --- /dev/null +++ b/Lang/OoRexx/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/File-size b/Lang/OoRexx/File-size new file mode 120000 index 0000000000..5d39592d3a --- /dev/null +++ b/Lang/OoRexx/File-size @@ -0,0 +1 @@ +../../Task/File-size/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Filter b/Lang/OoRexx/Filter new file mode 120000 index 0000000000..412b98cc4c --- /dev/null +++ b/Lang/OoRexx/Filter @@ -0,0 +1 @@ +../../Task/Filter/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Flatten-a-list b/Lang/OoRexx/Flatten-a-list new file mode 120000 index 0000000000..dc6dbe016e --- /dev/null +++ b/Lang/OoRexx/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Fork b/Lang/OoRexx/Fork new file mode 120000 index 0000000000..58658bae4d --- /dev/null +++ b/Lang/OoRexx/Fork @@ -0,0 +1 @@ +../../Task/Fork/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Function-definition b/Lang/OoRexx/Function-definition new file mode 120000 index 0000000000..5194721333 --- /dev/null +++ b/Lang/OoRexx/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Greatest-element-of-a-list b/Lang/OoRexx/Greatest-element-of-a-list new file mode 120000 index 0000000000..947bb47c1f --- /dev/null +++ b/Lang/OoRexx/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Guess-the-number-With-feedback b/Lang/OoRexx/Guess-the-number-With-feedback new file mode 120000 index 0000000000..612368ed61 --- /dev/null +++ b/Lang/OoRexx/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/HTTP b/Lang/OoRexx/HTTP new file mode 120000 index 0000000000..84798f47bd --- /dev/null +++ b/Lang/OoRexx/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Hailstone-sequence b/Lang/OoRexx/Hailstone-sequence new file mode 120000 index 0000000000..ea5f8d48f8 --- /dev/null +++ b/Lang/OoRexx/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Happy-numbers b/Lang/OoRexx/Happy-numbers new file mode 120000 index 0000000000..44d744406a --- /dev/null +++ b/Lang/OoRexx/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Harshad-or-Niven-series b/Lang/OoRexx/Harshad-or-Niven-series new file mode 120000 index 0000000000..69e61ba904 --- /dev/null +++ b/Lang/OoRexx/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Hash-from-two-arrays b/Lang/OoRexx/Hash-from-two-arrays new file mode 120000 index 0000000000..b64cf712d5 --- /dev/null +++ b/Lang/OoRexx/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Haversine-formula b/Lang/OoRexx/Haversine-formula new file mode 120000 index 0000000000..e984ef278f --- /dev/null +++ b/Lang/OoRexx/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Hello-world-Standard-error b/Lang/OoRexx/Hello-world-Standard-error new file mode 120000 index 0000000000..2b4e0c2788 --- /dev/null +++ b/Lang/OoRexx/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Hello-world-Text b/Lang/OoRexx/Hello-world-Text new file mode 120000 index 0000000000..0fab43aec1 --- /dev/null +++ b/Lang/OoRexx/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Heronian-triangles b/Lang/OoRexx/Heronian-triangles new file mode 120000 index 0000000000..99de2315be --- /dev/null +++ b/Lang/OoRexx/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Higher-order-functions b/Lang/OoRexx/Higher-order-functions new file mode 120000 index 0000000000..3bab5b97b6 --- /dev/null +++ b/Lang/OoRexx/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Horners-rule-for-polynomial-evaluation b/Lang/OoRexx/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..630a41b8ec --- /dev/null +++ b/Lang/OoRexx/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Hostname b/Lang/OoRexx/Hostname new file mode 120000 index 0000000000..7f378aa8ce --- /dev/null +++ b/Lang/OoRexx/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Identity-matrix b/Lang/OoRexx/Identity-matrix new file mode 120000 index 0000000000..8b47bf65e9 --- /dev/null +++ b/Lang/OoRexx/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Include-a-file b/Lang/OoRexx/Include-a-file new file mode 120000 index 0000000000..126c3b048d --- /dev/null +++ b/Lang/OoRexx/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Inheritance-Multiple b/Lang/OoRexx/Inheritance-Multiple new file mode 120000 index 0000000000..d6b0ed59a0 --- /dev/null +++ b/Lang/OoRexx/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Inheritance-Single b/Lang/OoRexx/Inheritance-Single new file mode 120000 index 0000000000..97611f1af7 --- /dev/null +++ b/Lang/OoRexx/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Knapsack-problem-Continuous b/Lang/OoRexx/Knapsack-problem-Continuous new file mode 120000 index 0000000000..9eb3e9763f --- /dev/null +++ b/Lang/OoRexx/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Last-letter-first-letter b/Lang/OoRexx/Last-letter-first-letter new file mode 120000 index 0000000000..3323303edb --- /dev/null +++ b/Lang/OoRexx/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Leap-year b/Lang/OoRexx/Leap-year new file mode 120000 index 0000000000..d55569532a --- /dev/null +++ b/Lang/OoRexx/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Least-common-multiple b/Lang/OoRexx/Least-common-multiple new file mode 120000 index 0000000000..57f2f54f15 --- /dev/null +++ b/Lang/OoRexx/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Levenshtein-distance b/Lang/OoRexx/Levenshtein-distance new file mode 120000 index 0000000000..e3e364002d --- /dev/null +++ b/Lang/OoRexx/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Loop-over-multiple-arrays-simultaneously b/Lang/OoRexx/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..0643edce88 --- /dev/null +++ b/Lang/OoRexx/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Loops-Break b/Lang/OoRexx/Loops-Break new file mode 120000 index 0000000000..3ee14b0702 --- /dev/null +++ b/Lang/OoRexx/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Loops-Foreach b/Lang/OoRexx/Loops-Foreach new file mode 120000 index 0000000000..a4173f07b0 --- /dev/null +++ b/Lang/OoRexx/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/MD5-Implementation b/Lang/OoRexx/MD5-Implementation new file mode 120000 index 0000000000..e8dd307797 --- /dev/null +++ b/Lang/OoRexx/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Modular-exponentiation b/Lang/OoRexx/Modular-exponentiation new file mode 120000 index 0000000000..6d013310a4 --- /dev/null +++ b/Lang/OoRexx/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Multiple-distinct-objects b/Lang/OoRexx/Multiple-distinct-objects new file mode 120000 index 0000000000..999a6214c3 --- /dev/null +++ b/Lang/OoRexx/Multiple-distinct-objects @@ -0,0 +1 @@ +../../Task/Multiple-distinct-objects/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Null-object b/Lang/OoRexx/Null-object new file mode 120000 index 0000000000..316b8544f3 --- /dev/null +++ b/Lang/OoRexx/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/OoRexx/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..b4c7806eb2 --- /dev/null +++ b/Lang/OoRexx/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Ordered-words b/Lang/OoRexx/Ordered-words new file mode 120000 index 0000000000..bb228c48a2 --- /dev/null +++ b/Lang/OoRexx/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Parallel-calculations b/Lang/OoRexx/Parallel-calculations new file mode 120000 index 0000000000..0d32cc0ddb --- /dev/null +++ b/Lang/OoRexx/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Parsing-RPN-calculator-algorithm b/Lang/OoRexx/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..c03d0045f0 --- /dev/null +++ b/Lang/OoRexx/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Perfect-numbers b/Lang/OoRexx/Perfect-numbers new file mode 120000 index 0000000000..020850285b --- /dev/null +++ b/Lang/OoRexx/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Pointers-and-references b/Lang/OoRexx/Pointers-and-references new file mode 120000 index 0000000000..a3b6d067a3 --- /dev/null +++ b/Lang/OoRexx/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Polymorphic-copy b/Lang/OoRexx/Polymorphic-copy new file mode 120000 index 0000000000..6b8fd40bc7 --- /dev/null +++ b/Lang/OoRexx/Polymorphic-copy @@ -0,0 +1 @@ +../../Task/Polymorphic-copy/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Polymorphism b/Lang/OoRexx/Polymorphism new file mode 120000 index 0000000000..974f98c53e --- /dev/null +++ b/Lang/OoRexx/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Quaternion-type b/Lang/OoRexx/Quaternion-type new file mode 120000 index 0000000000..be3652b55d --- /dev/null +++ b/Lang/OoRexx/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Queue-Usage b/Lang/OoRexx/Queue-Usage new file mode 120000 index 0000000000..fbb06812d6 --- /dev/null +++ b/Lang/OoRexx/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Quine b/Lang/OoRexx/Quine new file mode 120000 index 0000000000..6a8b184fa2 --- /dev/null +++ b/Lang/OoRexx/Quine @@ -0,0 +1 @@ +../../Task/Quine/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Random-numbers b/Lang/OoRexx/Random-numbers new file mode 120000 index 0000000000..e7a18661a7 --- /dev/null +++ b/Lang/OoRexx/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Range-expansion b/Lang/OoRexx/Range-expansion new file mode 120000 index 0000000000..216bfdcbbe --- /dev/null +++ b/Lang/OoRexx/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Range-extraction b/Lang/OoRexx/Range-extraction new file mode 120000 index 0000000000..93cfa2dd99 --- /dev/null +++ b/Lang/OoRexx/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Read-a-configuration-file b/Lang/OoRexx/Read-a-configuration-file new file mode 120000 index 0000000000..5b60e3d58a --- /dev/null +++ b/Lang/OoRexx/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Read-entire-file b/Lang/OoRexx/Read-entire-file new file mode 120000 index 0000000000..dcf2672e13 --- /dev/null +++ b/Lang/OoRexx/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Real-constants-and-functions b/Lang/OoRexx/Real-constants-and-functions new file mode 120000 index 0000000000..0b233a500d --- /dev/null +++ b/Lang/OoRexx/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Regular-expressions b/Lang/OoRexx/Regular-expressions new file mode 120000 index 0000000000..406920891e --- /dev/null +++ b/Lang/OoRexx/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Remove-duplicate-elements b/Lang/OoRexx/Remove-duplicate-elements new file mode 120000 index 0000000000..0ec204c3d1 --- /dev/null +++ b/Lang/OoRexx/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Respond-to-an-unknown-method-call b/Lang/OoRexx/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..9f22b12610 --- /dev/null +++ b/Lang/OoRexx/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Return-multiple-values b/Lang/OoRexx/Return-multiple-values new file mode 120000 index 0000000000..092a8cbcc5 --- /dev/null +++ b/Lang/OoRexx/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Runtime-evaluation b/Lang/OoRexx/Runtime-evaluation new file mode 120000 index 0000000000..fb61ee0bfa --- /dev/null +++ b/Lang/OoRexx/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Runtime-evaluation-In-an-environment b/Lang/OoRexx/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..24cc922654 --- /dev/null +++ b/Lang/OoRexx/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Search-a-list b/Lang/OoRexx/Search-a-list new file mode 120000 index 0000000000..b20c4466fa --- /dev/null +++ b/Lang/OoRexx/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Self-describing-numbers b/Lang/OoRexx/Self-describing-numbers new file mode 120000 index 0000000000..abd3d9052b --- /dev/null +++ b/Lang/OoRexx/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Set b/Lang/OoRexx/Set new file mode 120000 index 0000000000..125d0c7575 --- /dev/null +++ b/Lang/OoRexx/Set @@ -0,0 +1 @@ +../../Task/Set/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Set-consolidation b/Lang/OoRexx/Set-consolidation new file mode 120000 index 0000000000..361ee2dde6 --- /dev/null +++ b/Lang/OoRexx/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Shell-one-liner b/Lang/OoRexx/Shell-one-liner new file mode 120000 index 0000000000..8ca7780abb --- /dev/null +++ b/Lang/OoRexx/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Short-circuit-evaluation b/Lang/OoRexx/Short-circuit-evaluation new file mode 120000 index 0000000000..c1b5c75d8f --- /dev/null +++ b/Lang/OoRexx/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Simple-windowed-application b/Lang/OoRexx/Simple-windowed-application new file mode 120000 index 0000000000..885494c87c --- /dev/null +++ b/Lang/OoRexx/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Singleton b/Lang/OoRexx/Singleton new file mode 120000 index 0000000000..21cbbdcf52 --- /dev/null +++ b/Lang/OoRexx/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Singly-linked-list-Element-definition b/Lang/OoRexx/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..261bff6541 --- /dev/null +++ b/Lang/OoRexx/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Singly-linked-list-Element-insertion b/Lang/OoRexx/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..5dfec8cebf --- /dev/null +++ b/Lang/OoRexx/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Singly-linked-list-Traversal b/Lang/OoRexx/Singly-linked-list-Traversal new file mode 120000 index 0000000000..d120a5c2a9 --- /dev/null +++ b/Lang/OoRexx/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sleep b/Lang/OoRexx/Sleep new file mode 120000 index 0000000000..5ac99a7535 --- /dev/null +++ b/Lang/OoRexx/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sort-an-array-of-composite-structures b/Lang/OoRexx/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..51138602c3 --- /dev/null +++ b/Lang/OoRexx/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sort-an-integer-array b/Lang/OoRexx/Sort-an-integer-array new file mode 120000 index 0000000000..fc9ebd402d --- /dev/null +++ b/Lang/OoRexx/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sort-disjoint-sublist b/Lang/OoRexx/Sort-disjoint-sublist new file mode 120000 index 0000000000..e871f8b14a --- /dev/null +++ b/Lang/OoRexx/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sort-stability b/Lang/OoRexx/Sort-stability new file mode 120000 index 0000000000..407b2646fb --- /dev/null +++ b/Lang/OoRexx/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sort-using-a-custom-comparator b/Lang/OoRexx/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..c40f2150dc --- /dev/null +++ b/Lang/OoRexx/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sorting-algorithms-Bead-sort b/Lang/OoRexx/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..01f6d3ac0e --- /dev/null +++ b/Lang/OoRexx/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sorting-algorithms-Bubble-sort b/Lang/OoRexx/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..2b6f7d562e --- /dev/null +++ b/Lang/OoRexx/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sorting-algorithms-Cocktail-sort b/Lang/OoRexx/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..f5eebbe57f --- /dev/null +++ b/Lang/OoRexx/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sorting-algorithms-Gnome-sort b/Lang/OoRexx/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..ecdee4eb3e --- /dev/null +++ b/Lang/OoRexx/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sorting-algorithms-Insertion-sort b/Lang/OoRexx/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..b292e6fb9e --- /dev/null +++ b/Lang/OoRexx/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sorting-algorithms-Quicksort b/Lang/OoRexx/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..07437f2d55 --- /dev/null +++ b/Lang/OoRexx/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sorting-algorithms-Selection-sort b/Lang/OoRexx/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..016d1552dd --- /dev/null +++ b/Lang/OoRexx/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sorting-algorithms-Shell-sort b/Lang/OoRexx/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..73baf08326 --- /dev/null +++ b/Lang/OoRexx/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sorting-algorithms-Stooge-sort b/Lang/OoRexx/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..950d4759b1 --- /dev/null +++ b/Lang/OoRexx/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Spiral-matrix b/Lang/OoRexx/Spiral-matrix new file mode 120000 index 0000000000..ea1e5c6b48 --- /dev/null +++ b/Lang/OoRexx/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Stack b/Lang/OoRexx/Stack new file mode 120000 index 0000000000..c0a4406043 --- /dev/null +++ b/Lang/OoRexx/Stack @@ -0,0 +1 @@ +../../Task/Stack/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/String-comparison b/Lang/OoRexx/String-comparison new file mode 120000 index 0000000000..ccc6a62702 --- /dev/null +++ b/Lang/OoRexx/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sum-and-product-of-an-array b/Lang/OoRexx/Sum-and-product-of-an-array new file mode 120000 index 0000000000..51cc712ed5 --- /dev/null +++ b/Lang/OoRexx/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Symmetric-difference b/Lang/OoRexx/Symmetric-difference new file mode 120000 index 0000000000..97317a5ec0 --- /dev/null +++ b/Lang/OoRexx/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Synchronous-concurrency b/Lang/OoRexx/Synchronous-concurrency new file mode 120000 index 0000000000..a22482e6ca --- /dev/null +++ b/Lang/OoRexx/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Table-creation-Postal-addresses b/Lang/OoRexx/Table-creation-Postal-addresses new file mode 120000 index 0000000000..48c11d1313 --- /dev/null +++ b/Lang/OoRexx/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Terminal-control-Coloured-text b/Lang/OoRexx/Terminal-control-Coloured-text new file mode 120000 index 0000000000..47ea78260b --- /dev/null +++ b/Lang/OoRexx/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Ternary-logic b/Lang/OoRexx/Ternary-logic new file mode 120000 index 0000000000..cf014bb045 --- /dev/null +++ b/Lang/OoRexx/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Tokenize-a-string b/Lang/OoRexx/Tokenize-a-string new file mode 120000 index 0000000000..a26b12b785 --- /dev/null +++ b/Lang/OoRexx/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Tree-traversal b/Lang/OoRexx/Tree-traversal new file mode 120000 index 0000000000..2cd163f7a7 --- /dev/null +++ b/Lang/OoRexx/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Trigonometric-functions b/Lang/OoRexx/Trigonometric-functions new file mode 120000 index 0000000000..802fabdfad --- /dev/null +++ b/Lang/OoRexx/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Truncatable-primes b/Lang/OoRexx/Truncatable-primes new file mode 120000 index 0000000000..28de0493fa --- /dev/null +++ b/Lang/OoRexx/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Variables b/Lang/OoRexx/Variables new file mode 120000 index 0000000000..f6dc3ccf0f --- /dev/null +++ b/Lang/OoRexx/Variables @@ -0,0 +1 @@ +../../Task/Variables/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Vector-products b/Lang/OoRexx/Vector-products new file mode 120000 index 0000000000..19cf010cac --- /dev/null +++ b/Lang/OoRexx/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Vigen-re-cipher b/Lang/OoRexx/Vigen-re-cipher new file mode 120000 index 0000000000..8f6040fa12 --- /dev/null +++ b/Lang/OoRexx/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Walk-a-directory-Recursively b/Lang/OoRexx/Walk-a-directory-Recursively new file mode 120000 index 0000000000..e7637db81f --- /dev/null +++ b/Lang/OoRexx/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Web-scraping b/Lang/OoRexx/Web-scraping new file mode 120000 index 0000000000..dc85ca5f6c --- /dev/null +++ b/Lang/OoRexx/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Zero-to-the-zero-power b/Lang/OoRexx/Zero-to-the-zero-power new file mode 120000 index 0000000000..8d2f389052 --- /dev/null +++ b/Lang/OoRexx/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Zig-zag-matrix b/Lang/OoRexx/Zig-zag-matrix new file mode 120000 index 0000000000..b44c31225f --- /dev/null +++ b/Lang/OoRexx/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/OoRexx \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/File-IO b/Lang/OpenEdge-Progress/File-IO deleted file mode 120000 index cc32274cf0..0000000000 --- a/Lang/OpenEdge-Progress/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/OxygenBasic/Character-matching b/Lang/OxygenBasic/Character-matching deleted file mode 120000 index 6112e773dc..0000000000 --- a/Lang/OxygenBasic/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Hailstone-sequence b/Lang/OxygenBasic/Hailstone-sequence deleted file mode 120000 index d594331289..0000000000 --- a/Lang/OxygenBasic/Hailstone-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hailstone-sequence/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/String-case b/Lang/OxygenBasic/String-case deleted file mode 120000 index 9cf48e027a..0000000000 --- a/Lang/OxygenBasic/String-case +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-case/OxygenBasic \ No newline at end of file diff --git a/Lang/Oz/File-IO b/Lang/Oz/File-IO deleted file mode 120000 index c6515fdd2e..0000000000 --- a/Lang/Oz/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/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/Oz/Mutex b/Lang/Oz/Mutex deleted file mode 120000 index 93e8c309e5..0000000000 --- a/Lang/Oz/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Oz \ No newline at end of file diff --git a/Lang/Oz/Rosetta-Code-Count-examples b/Lang/Oz/Rosetta-Code-Count-examples deleted file mode 120000 index 777776db5b..0000000000 --- a/Lang/Oz/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Oz \ No newline at end of file diff --git a/Lang/Oz/Rosetta-Code-Find-unimplemented-tasks b/Lang/Oz/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index 0f47412111..0000000000 --- a/Lang/Oz/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/Oz \ No newline at end of file diff --git a/Lang/Oz/Rosetta-Code-Rank-languages-by-popularity b/Lang/Oz/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index e6024d2faa..0000000000 --- a/Lang/Oz/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Oz \ No newline at end of file diff --git a/Lang/PARI-GP/Accumulator-factory b/Lang/PARI-GP/Accumulator-factory new file mode 120000 index 0000000000..5274d6b0a7 --- /dev/null +++ b/Lang/PARI-GP/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Aliquot-sequence-classifications b/Lang/PARI-GP/Aliquot-sequence-classifications new file mode 120000 index 0000000000..ec1c1769a8 --- /dev/null +++ b/Lang/PARI-GP/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Character-matching b/Lang/PARI-GP/Character-matching deleted file mode 120000 index 790ecc1dc4..0000000000 --- a/Lang/PARI-GP/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/File-IO b/Lang/PARI-GP/File-IO deleted file mode 120000 index 002ac9a7d8..0000000000 --- a/Lang/PARI-GP/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Generate-Chess960-starting-position b/Lang/PARI-GP/Generate-Chess960-starting-position new file mode 120000 index 0000000000..cc0654892b --- /dev/null +++ b/Lang/PARI-GP/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Generator-Exponential b/Lang/PARI-GP/Generator-Exponential new file mode 120000 index 0000000000..ce2e56eefb --- /dev/null +++ b/Lang/PARI-GP/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Mandelbrot-set b/Lang/PARI-GP/Mandelbrot-set new file mode 120000 index 0000000000..bada75b940 --- /dev/null +++ b/Lang/PARI-GP/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/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/Paraffins b/Lang/PARI-GP/Paraffins new file mode 120000 index 0000000000..397b151de6 --- /dev/null +++ b/Lang/PARI-GP/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Set-of-real-numbers b/Lang/PARI-GP/Set-of-real-numbers new file mode 120000 index 0000000000..be46ab4497 --- /dev/null +++ b/Lang/PARI-GP/Set-of-real-numbers @@ -0,0 +1 @@ +../../Task/Set-of-real-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Standard-deviation b/Lang/PARI-GP/Standard-deviation deleted file mode 120000 index 4369e11be2..0000000000 --- a/Lang/PARI-GP/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/PARI-GP \ No newline at end of file diff --git a/Lang/PHP/Calendar---for-real-programmers b/Lang/PHP/Calendar---for-real-programmers deleted file mode 120000 index 9f00b3c5e5..0000000000 --- a/Lang/PHP/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/PHP \ No newline at end of file diff --git a/Lang/PHP/Character-matching b/Lang/PHP/Character-matching deleted file mode 120000 index 8298cc63af..0000000000 --- a/Lang/PHP/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/PHP \ No newline at end of file diff --git a/Lang/PHP/File-IO b/Lang/PHP/File-IO deleted file mode 120000 index 76eb48478c..0000000000 --- a/Lang/PHP/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/PHP \ No newline at end of file diff --git a/Lang/PHP/Forest-fire b/Lang/PHP/Forest-fire new file mode 120000 index 0000000000..a5b15ecca3 --- /dev/null +++ b/Lang/PHP/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/PHP \ No newline at end of file diff --git a/Lang/PHP/Maze-generation b/Lang/PHP/Maze-generation deleted file mode 120000 index 5e26d65e31..0000000000 --- a/Lang/PHP/Maze-generation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Maze-generation/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/Standard-deviation b/Lang/PHP/Standard-deviation deleted file mode 120000 index d3369f76f4..0000000000 --- a/Lang/PHP/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/PHP \ No newline at end of file diff --git a/Lang/PILOT/00DESCRIPTION b/Lang/PILOT/00DESCRIPTION new file mode 100644 index 0000000000..742582e7c0 --- /dev/null +++ b/Lang/PILOT/00DESCRIPTION @@ -0,0 +1,12 @@ +{{stub}}{{language|PILOT}} +'Programmed Instruction, Learning Or Teaching' is an imperative educational language developed in the 1960s by John A. Starkweather at the University of California, San Francisco. It is designed to make it very easy to write interactive classroom tests or quizzes: +COMPUTE:year = 1804 +TYPE:Who became French Emperor in #year? +ACCEPT: +MATCH:Napoleon,Bonaparte +YES:Correct! +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 diff --git a/Lang/PILOT/Factors-of-an-integer b/Lang/PILOT/Factors-of-an-integer new file mode 120000 index 0000000000..8c995386f4 --- /dev/null +++ b/Lang/PILOT/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/PILOT \ No newline at end of file diff --git a/Lang/PILOT/FizzBuzz b/Lang/PILOT/FizzBuzz new file mode 120000 index 0000000000..85fef4e69f --- /dev/null +++ b/Lang/PILOT/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/PILOT \ No newline at end of file diff --git a/Lang/PILOT/Hello-world-Text b/Lang/PILOT/Hello-world-Text new file mode 120000 index 0000000000..fad5fc0f09 --- /dev/null +++ b/Lang/PILOT/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/PILOT \ No newline at end of file diff --git a/Lang/PILOT/Integer-sequence b/Lang/PILOT/Integer-sequence new file mode 120000 index 0000000000..f9c7779473 --- /dev/null +++ b/Lang/PILOT/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/PILOT \ No newline at end of file diff --git a/Lang/PILOT/Loops-For b/Lang/PILOT/Loops-For new file mode 120000 index 0000000000..dc26684e2d --- /dev/null +++ b/Lang/PILOT/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/PILOT \ No newline at end of file diff --git a/Lang/PILOT/Loops-For-with-a-specified-step b/Lang/PILOT/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..da3604abaa --- /dev/null +++ b/Lang/PILOT/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/PILOT \ No newline at end of file diff --git a/Lang/PILOT/Loops-Infinite b/Lang/PILOT/Loops-Infinite new file mode 120000 index 0000000000..1c723a4d88 --- /dev/null +++ b/Lang/PILOT/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/PILOT \ No newline at end of file diff --git a/Lang/PILOT/README b/Lang/PILOT/README new file mode 100644 index 0000000000..2dde20cdf2 --- /dev/null +++ b/Lang/PILOT/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:PILOT diff --git a/Lang/PL-I/Calendar---for-real-programmers b/Lang/PL-I/Calendar---for-real-programmers deleted file mode 120000 index 0aaf0bb2f6..0000000000 --- a/Lang/PL-I/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Character-matching b/Lang/PL-I/Character-matching deleted file mode 120000 index 5d164a3541..0000000000 --- a/Lang/PL-I/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/PL-I \ No newline at end of file diff --git a/Lang/PL-I/File-IO b/Lang/PL-I/File-IO deleted file mode 120000 index b7f65e9299..0000000000 --- a/Lang/PL-I/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Pointers-and-references b/Lang/PL-I/Pointers-and-references new file mode 120000 index 0000000000..568b2f6038 --- /dev/null +++ b/Lang/PL-I/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Standard-deviation b/Lang/PL-I/Standard-deviation deleted file mode 120000 index a7ef1c963b..0000000000 --- a/Lang/PL-I/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/PL-I \ No newline at end of file diff --git a/Lang/PL-M/00DESCRIPTION b/Lang/PL-M/00DESCRIPTION index f66cf163bf..842acda5a5 100644 --- a/Lang/PL-M/00DESCRIPTION +++ b/Lang/PL-M/00DESCRIPTION @@ -1 +1,35 @@ -{{language}}{{stub}} \ No newline at end of file +{{stub}}{{language}} + +PL/M (Programming Language for Microcomputers) is (as the name suggests) a language designed for microcomputer software, particularly system software. +
+
+It is approximately a very small subset of PL/1 (though not a strict subset). +
+The following statements were available: +* assignment +* CALL +* DECLARE +* DO-END +* IF-THEN-ELSE +* GOTO +* PROCEDURE-END +* RETURN +Additionally a number of compiler directive statements existed. There are no built-in I/O statements - calls to appropriate routines would be made instead. +

+Unlike PL1, PL/M keywords are reserved and so cannot be used as identifiers. +
+Available datatypes (BYTE, WORD, etc.) reflected the available types of the microprocessors. +

+The declaration of structures in PL/M does not use level-numbers, instead a syntax more like C structs is used, e.g.: +DECLARE A STRUCTURE ( B BYTE, C WORD ); +declares a structure A with two members, B and C. +
+
+PL/M was used in the development of the CP/M operating system and associated applications. +
+Compilers were available for a number of microprocessors including the 8080 Z80. +
+
+==See Also== +* [[wp:PL/M|Wikipedia page on PL/M]]: [https://en.wikipedia.org/wiki/PL/M] +* [[PL/1]] \ No newline at end of file diff --git a/Lang/PL-SQL/00DESCRIPTION b/Lang/PL-SQL/00DESCRIPTION index 81d408ebd7..f26936308b 100644 --- a/Lang/PL-SQL/00DESCRIPTION +++ b/Lang/PL-SQL/00DESCRIPTION @@ -1,3 +1,4 @@ {{language|PL/SQL}}{{implementation|SQL}}'''PL/SQL''' (Procedural Language/Structured Query Language) is Oracle Corporation's proprietary server-based procedural extension to the [[SQL]] database language. (Some other SQL database management systems offer languages similar to PL/SQL.) Its syntax strongly resembles that of [[Ada]]. ==Citations== -* [http://en.wikipedia.org/wiki/PL/SQL Wikipedia:PL/SQL] \ No newline at end of file +* [http://en.wikipedia.org/wiki/PL/SQL Wikipedia:PL/SQL] +* [http://docs.oracle.com/database/122/LNPLS/toc.htm Oracle 12.2 PL/SQL Manual] \ No newline at end of file diff --git a/Lang/PL-SQL/Hello-world-Text b/Lang/PL-SQL/Hello-world-Text new file mode 120000 index 0000000000..d0136abeb7 --- /dev/null +++ b/Lang/PL-SQL/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/PL-SQL \ No newline at end of file diff --git a/Lang/Pascal/99-Bottles-of-Beer b/Lang/Pascal/99-Bottles-of-Beer deleted file mode 120000 index a4fece1da2..0000000000 --- a/Lang/Pascal/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Bernoulli-numbers b/Lang/Pascal/Bernoulli-numbers new file mode 120000 index 0000000000..17b1884e34 --- /dev/null +++ b/Lang/Pascal/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Pascal \ No newline at end of file diff --git a/Lang/Pascal/CSV-data-manipulation b/Lang/Pascal/CSV-data-manipulation new file mode 120000 index 0000000000..a004708625 --- /dev/null +++ b/Lang/Pascal/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Comma-quibbling b/Lang/Pascal/Comma-quibbling new file mode 120000 index 0000000000..a17a66651c --- /dev/null +++ b/Lang/Pascal/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Discordian-date b/Lang/Pascal/Discordian-date new file mode 120000 index 0000000000..436abd0085 --- /dev/null +++ b/Lang/Pascal/Discordian-date @@ -0,0 +1 @@ +../../Task/Discordian-date/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Execute-Brain---- b/Lang/Pascal/Execute-Brain---- new file mode 120000 index 0000000000..aed19296fa --- /dev/null +++ b/Lang/Pascal/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Knapsack-problem-0-1 b/Lang/Pascal/Knapsack-problem-0-1 new file mode 120000 index 0000000000..7fc0c365fc --- /dev/null +++ b/Lang/Pascal/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Menu b/Lang/Pascal/Menu new file mode 120000 index 0000000000..55830fd65a --- /dev/null +++ b/Lang/Pascal/Menu @@ -0,0 +1 @@ +../../Task/Menu/Pascal \ No newline at end of file diff --git a/Lang/Pascal/One-dimensional-cellular-automata b/Lang/Pascal/One-dimensional-cellular-automata new file mode 120000 index 0000000000..ad7b19acfd --- /dev/null +++ b/Lang/Pascal/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Parametrized-SQL-statement b/Lang/Pascal/Parametrized-SQL-statement new file mode 120000 index 0000000000..621285d4cc --- /dev/null +++ b/Lang/Pascal/Parametrized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parametrized-SQL-statement/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Standard-deviation b/Lang/Pascal/Standard-deviation deleted file mode 120000 index 045fd07fd2..0000000000 --- a/Lang/Pascal/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Symmetric-difference b/Lang/Pascal/Symmetric-difference new file mode 120000 index 0000000000..74889cca69 --- /dev/null +++ b/Lang/Pascal/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Terminal-control-Inverse-video b/Lang/Pascal/Terminal-control-Inverse-video new file mode 120000 index 0000000000..eadbaa85db --- /dev/null +++ b/Lang/Pascal/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Pascal \ No newline at end of file diff --git a/Lang/Perl-6/Bitmap-Midpoint-circle-algorithm b/Lang/Perl-6/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..2c96501957 --- /dev/null +++ b/Lang/Perl-6/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Calendar---for-real-programmers b/Lang/Perl-6/Calendar---for-real-programmers deleted file mode 120000 index 9f1aa1011f..0000000000 --- a/Lang/Perl-6/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Character-matching b/Lang/Perl-6/Character-matching deleted file mode 120000 index 60d1c21291..0000000000 --- a/Lang/Perl-6/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/DNS-query b/Lang/Perl-6/DNS-query new file mode 120000 index 0000000000..cc415493a4 --- /dev/null +++ b/Lang/Perl-6/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Execute-SNUSP b/Lang/Perl-6/Execute-SNUSP new file mode 120000 index 0000000000..4ecbc5c674 --- /dev/null +++ b/Lang/Perl-6/Execute-SNUSP @@ -0,0 +1 @@ +../../Task/Execute-SNUSP/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/File-IO b/Lang/Perl-6/File-IO deleted file mode 120000 index 31a7e6cf7b..0000000000 --- a/Lang/Perl-6/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Magic-squares-of-odd-order b/Lang/Perl-6/Magic-squares-of-odd-order deleted file mode 120000 index 2bd7fc43b6..0000000000 --- a/Lang/Perl-6/Magic-squares-of-odd-order +++ /dev/null @@ -1 +0,0 @@ -../../Task/Magic-squares-of-odd-order/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Miller-Rabin-primality-test b/Lang/Perl-6/Miller-Rabin-primality-test deleted file mode 120000 index 24b8ad3c0b..0000000000 --- a/Lang/Perl-6/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Mutex b/Lang/Perl-6/Mutex deleted file mode 120000 index 151b588311..0000000000 --- a/Lang/Perl-6/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Percolation-Bond-percolation b/Lang/Perl-6/Percolation-Bond-percolation new file mode 120000 index 0000000000..d9d9ba1bbe --- /dev/null +++ b/Lang/Perl-6/Percolation-Bond-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Bond-percolation/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Percolation-Mean-cluster-density b/Lang/Perl-6/Percolation-Mean-cluster-density new file mode 120000 index 0000000000..e9e4ee72d7 --- /dev/null +++ b/Lang/Perl-6/Percolation-Mean-cluster-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-cluster-density/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Percolation-Site-percolation b/Lang/Perl-6/Percolation-Site-percolation new file mode 120000 index 0000000000..e21c473e28 --- /dev/null +++ b/Lang/Perl-6/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Rosetta-Code-Count-examples b/Lang/Perl-6/Rosetta-Code-Count-examples deleted file mode 120000 index 4bff3c0bda..0000000000 --- a/Lang/Perl-6/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Rosetta-Code-Find-unimplemented-tasks b/Lang/Perl-6/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index fe10280bde..0000000000 --- a/Lang/Perl-6/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Rosetta-Code-Fix-code-tags b/Lang/Perl-6/Rosetta-Code-Fix-code-tags deleted file mode 120000 index 7386f1eb5e..0000000000 --- a/Lang/Perl-6/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Rosetta-Code-Rank-languages-by-popularity b/Lang/Perl-6/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index d84ceb645d..0000000000 --- a/Lang/Perl-6/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Standard-deviation b/Lang/Perl-6/Standard-deviation deleted file mode 120000 index fd7b9fde9f..0000000000 --- a/Lang/Perl-6/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Perl-6 \ No newline at end of file diff --git a/Lang/Perl/Averages-Mean-time-of-day b/Lang/Perl/Averages-Mean-time-of-day new file mode 120000 index 0000000000..9e2d66605a --- /dev/null +++ b/Lang/Perl/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Perl \ No newline at end of file diff --git a/Lang/Perl/Calendar---for-real-programmers b/Lang/Perl/Calendar---for-real-programmers deleted file mode 120000 index 85c695f20e..0000000000 --- a/Lang/Perl/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/Perl \ No newline at end of file diff --git a/Lang/Perl/Character-matching b/Lang/Perl/Character-matching deleted file mode 120000 index d16ad0cf7a..0000000000 --- a/Lang/Perl/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Perl \ No newline at end of file diff --git a/Lang/Perl/Circles-of-given-radius-through-two-points b/Lang/Perl/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..e0634ef19f --- /dev/null +++ b/Lang/Perl/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Perl \ No newline at end of file diff --git a/Lang/Perl/File-IO b/Lang/Perl/File-IO deleted file mode 120000 index 3f7e0d3a6c..0000000000 --- a/Lang/Perl/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Perl \ No newline at end of file diff --git a/Lang/Perl/HTTPS-Client-authenticated b/Lang/Perl/HTTPS-Client-authenticated new file mode 120000 index 0000000000..b3902ec74a --- /dev/null +++ b/Lang/Perl/HTTPS-Client-authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Client-authenticated/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/Mutex b/Lang/Perl/Mutex deleted file mode 120000 index 37318a2941..0000000000 --- a/Lang/Perl/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Perl \ No newline at end of file diff --git a/Lang/Perl/Rosetta-Code-Count-examples b/Lang/Perl/Rosetta-Code-Count-examples deleted file mode 120000 index 7b3ef57551..0000000000 --- a/Lang/Perl/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Perl \ No newline at end of file diff --git a/Lang/Perl/Rosetta-Code-Find-bare-lang-tags b/Lang/Perl/Rosetta-Code-Find-bare-lang-tags deleted file mode 120000 index c5d8ab2076..0000000000 --- a/Lang/Perl/Rosetta-Code-Find-bare-lang-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-bare-lang-tags/Perl \ No newline at end of file diff --git a/Lang/Perl/Rosetta-Code-Find-unimplemented-tasks b/Lang/Perl/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index 0e72c4d01e..0000000000 --- a/Lang/Perl/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/Perl \ No newline at end of file diff --git a/Lang/Perl/Rosetta-Code-Fix-code-tags b/Lang/Perl/Rosetta-Code-Fix-code-tags deleted file mode 120000 index 9cc24cd62d..0000000000 --- a/Lang/Perl/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/Perl \ No newline at end of file diff --git a/Lang/Perl/Rosetta-Code-Rank-languages-by-popularity b/Lang/Perl/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index d1749cec95..0000000000 --- a/Lang/Perl/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Perl \ No newline at end of file diff --git a/Lang/Perl/Standard-deviation b/Lang/Perl/Standard-deviation deleted file mode 120000 index 1cc6321764..0000000000 --- a/Lang/Perl/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Perl \ No newline at end of file diff --git a/Lang/Perl5i/00DESCRIPTION b/Lang/Perl5i/00DESCRIPTION index b2ab4c8edf..2b872b43d9 100644 --- a/Lang/Perl5i/00DESCRIPTION +++ b/Lang/Perl5i/00DESCRIPTION @@ -4,4 +4,4 @@ While the Perl examples on Rosetta Code are correct, some of them reflect an old Object-Oriented Perl has been transformed by the development of Moose and its lightweight cousins, Mouse, Moo, etc. -A number of modules encourage good non-OO style and simplify the boilerplate involved, such as Modern::Perl. I've decided to treat one of those modules, perl5i, as if it were a language on its own. While the existing code focuses on the use of Perl as a quick and easy scripting language, I want to emphasize its use for more engineered situations. Were I use OO, I've gone for a minimal style. As well, I've avoided POD and used minimal per-routine documentation. \ No newline at end of file +A number of modules encourage good non-OO style and simplify the boilerplate involved, such as Modern::Perl. I've decided to treat one of those modules, perl5i, as if it were a language on its own. While the existing code focuses on the use of Perl as a quick and easy scripting language, I want to emphasize its use for more engineered situations. Where I use OO, I've gone for a minimal style. As well, I've avoided POD and used minimal per-routine documentation. \ No newline at end of file diff --git a/Lang/Phix/00DESCRIPTION b/Lang/Phix/00DESCRIPTION index 2fa7a1f02b..424a53e08f 100644 --- a/Lang/Phix/00DESCRIPTION +++ b/Lang/Phix/00DESCRIPTION @@ -1,6 +1,6 @@ {{language |exec=both -|site=http://phix.is-great.org +|site=http://phix.x10.mx |gc=Reference Counting |parampass=copy-on-write |express=explicit @@ -9,18 +9,27 @@ |altexec=compiled |hopl=no |LCT=yes -|bnf=http://phix.is-great.org/bnf.php +|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 Euphoria. -A single 6MB download contains a precompiled executable, all the sources, and'' '''everything''' ''needed to recompile them, in about 15 seconds. The download also contains a full-featured programmer's editor and 130+ demo programs. +A single 16MB download contains a pre-compiled executable, all the sources, and'' '''everything''' ''needed to recompile them, in about 15 seconds. The download also contains a full-featured programmer's editor and 130+ demo programs. -Phix applies the principle of least surprise, for instance in some languages myproc(list) or res = myfunc(list) can mangle list, whereas in Phix if you actually want that to happen you would code list = myproc(list) (and myproc would need to become a function) or {res,list} = myfunc(list). A core tenet is that for any line of code there is one and only one possible interpretation of it, and said meaning is utterly intuitive. +Perhaps the most striking feature of Phix is that it has just five builtin data types: +
+        <-------- object --------->
+        |                |
+        +-atom           +-sequence
+          |                |
+          +-integer        +-string
+
+Despite such apparent simplicity, or perhaps precisely because of it, Phix programs are pretty fast - not quite achieving the runtime performance of C or assembly, but making up for it with a very fast edit/run cycle and proper human-readable messages should anything go wrong (even in shipped pre-compiled executables). Sequences are the real powerhouse of Phix. The one type covers lists, queues, tables, trees, and arrays, with strings being the subset that is array of character. They can grow and shrink automatically without any memory management overhead. For example if s="food" then s[2..3]="e" makes s "fed", and then s[2..1]="east" makes s "feasted". -sequences (the one type covers lists/queues/tables/trees/arrays etc) and strings can grow and shrink automatically without any memory management overhead. For example if s="food" then s[2..3]="e" makes s "fed", and then s[2..1]="east" makes s "feasted". +Phix applies the principle of least surprise, for instance in some languages myproc(list) or res = myfunc(list) can mangle list, whereas in Phix if you actually want that to happen you would code list = myproc(list) (and myproc would need to become a function) or {res,list} = myfunc(list). Likewise 1/2 is 0.5 (not 0, unless you explicitly ask for the floor()) and 0-1 is -1 (not +MAXINT). A core tenet is that for any line of code there is one and only one possible interpretation of it, and said meaning is utterly intuitive. -My goal on rosettacode is to show that Phix is easy to understand (succinct but not terse), and easy to debug. +The principle goal of Phix is to make debugging easier, a whole subject area that does not seem to get the attention it deserves. Not entirely sure I am succeeding, yet. ==See also== -* [http://phix.is-great.org Phix site] -* [https://bitbucket.org/petelomax/phix/src bitbucket] \ No newline at end of file +* [http://phix.x10.mx Phix site] +* [https://bitbucket.org/petelomax/phix/src bitbucket] +* [[Reports:Tasks_not_implemented_in_Phix|Wishlist]] \ No newline at end of file diff --git a/Lang/Phix/Append-a-record-to-the-end-of-a-text-file b/Lang/Phix/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..0dad391d52 --- /dev/null +++ b/Lang/Phix/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Phix \ No newline at end of file diff --git a/Lang/Phix/Arena-storage-pool b/Lang/Phix/Arena-storage-pool new file mode 120000 index 0000000000..9938050b32 --- /dev/null +++ b/Lang/Phix/Arena-storage-pool @@ -0,0 +1 @@ +../../Task/Arena-storage-pool/Phix \ No newline at end of file diff --git a/Lang/Phix/CSV-data-manipulation b/Lang/Phix/CSV-data-manipulation new file mode 120000 index 0000000000..19e68023ae --- /dev/null +++ b/Lang/Phix/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Phix \ No newline at end of file diff --git a/Lang/Phix/Call-a-function-in-a-shared-library b/Lang/Phix/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..f4ade52567 --- /dev/null +++ b/Lang/Phix/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/Phix \ No newline at end of file diff --git a/Lang/Phix/Casting-out-nines b/Lang/Phix/Casting-out-nines new file mode 120000 index 0000000000..7d650f1fed --- /dev/null +++ b/Lang/Phix/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Phix \ No newline at end of file diff --git a/Lang/Phix/Catamorphism b/Lang/Phix/Catamorphism new file mode 120000 index 0000000000..c965e127cc --- /dev/null +++ b/Lang/Phix/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Phix \ No newline at end of file diff --git a/Lang/Phix/Cholesky-decomposition b/Lang/Phix/Cholesky-decomposition new file mode 120000 index 0000000000..80207c4080 --- /dev/null +++ b/Lang/Phix/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Phix \ No newline at end of file diff --git a/Lang/Phix/Closures-Value-capture b/Lang/Phix/Closures-Value-capture new file mode 120000 index 0000000000..7a01e209f0 --- /dev/null +++ b/Lang/Phix/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Phix \ No newline at end of file diff --git a/Lang/Phix/Color-of-a-screen-pixel b/Lang/Phix/Color-of-a-screen-pixel new file mode 120000 index 0000000000..2a77d77d03 --- /dev/null +++ b/Lang/Phix/Color-of-a-screen-pixel @@ -0,0 +1 @@ +../../Task/Color-of-a-screen-pixel/Phix \ No newline at end of file diff --git a/Lang/Phix/Colour-bars-Display b/Lang/Phix/Colour-bars-Display new file mode 120000 index 0000000000..91a1cafff1 --- /dev/null +++ b/Lang/Phix/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/Phix \ No newline at end of file diff --git a/Lang/Phix/Colour-pinstripe-Display b/Lang/Phix/Colour-pinstripe-Display new file mode 120000 index 0000000000..b4a776b8b5 --- /dev/null +++ b/Lang/Phix/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Phix \ No newline at end of file diff --git a/Lang/Phix/Comma-quibbling b/Lang/Phix/Comma-quibbling new file mode 120000 index 0000000000..d367bd1190 --- /dev/null +++ b/Lang/Phix/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Phix \ No newline at end of file diff --git a/Lang/Phix/Compare-sorting-algorithms-performance b/Lang/Phix/Compare-sorting-algorithms-performance new file mode 120000 index 0000000000..7b25fe8c3a --- /dev/null +++ b/Lang/Phix/Compare-sorting-algorithms-performance @@ -0,0 +1 @@ +../../Task/Compare-sorting-algorithms-performance/Phix \ No newline at end of file diff --git a/Lang/Phix/Conditional-structures b/Lang/Phix/Conditional-structures new file mode 120000 index 0000000000..8009fbcf5d --- /dev/null +++ b/Lang/Phix/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Phix \ No newline at end of file diff --git a/Lang/Phix/Conjugate-transpose b/Lang/Phix/Conjugate-transpose new file mode 120000 index 0000000000..c48680f104 --- /dev/null +++ b/Lang/Phix/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Phix \ No newline at end of file diff --git a/Lang/Phix/Continued-fraction b/Lang/Phix/Continued-fraction new file mode 120000 index 0000000000..d168987be1 --- /dev/null +++ b/Lang/Phix/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Phix \ No newline at end of file diff --git a/Lang/Phix/Conways-Game-of-Life b/Lang/Phix/Conways-Game-of-Life new file mode 120000 index 0000000000..de6985984d --- /dev/null +++ b/Lang/Phix/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Phix \ No newline at end of file diff --git a/Lang/Phix/Count-the-coins b/Lang/Phix/Count-the-coins new file mode 120000 index 0000000000..469c36a649 --- /dev/null +++ b/Lang/Phix/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Phix \ No newline at end of file diff --git a/Lang/Phix/Currying b/Lang/Phix/Currying new file mode 120000 index 0000000000..a05067f97f --- /dev/null +++ b/Lang/Phix/Currying @@ -0,0 +1 @@ +../../Task/Currying/Phix \ No newline at end of file diff --git a/Lang/Phix/Deal-cards-for-FreeCell b/Lang/Phix/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..d59b6bd561 --- /dev/null +++ b/Lang/Phix/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Phix \ No newline at end of file diff --git a/Lang/Phix/Death-Star b/Lang/Phix/Death-Star new file mode 120000 index 0000000000..1eae3e3adc --- /dev/null +++ b/Lang/Phix/Death-Star @@ -0,0 +1 @@ +../../Task/Death-Star/Phix \ No newline at end of file diff --git a/Lang/Phix/Deconvolution-1D b/Lang/Phix/Deconvolution-1D new file mode 120000 index 0000000000..6d9f54b9af --- /dev/null +++ b/Lang/Phix/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/Phix \ No newline at end of file diff --git a/Lang/Phix/Deepcopy b/Lang/Phix/Deepcopy new file mode 120000 index 0000000000..03364b5f6d --- /dev/null +++ b/Lang/Phix/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/Phix \ No newline at end of file diff --git a/Lang/Phix/Delete-a-file b/Lang/Phix/Delete-a-file new file mode 120000 index 0000000000..ba6d1b522e --- /dev/null +++ b/Lang/Phix/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Phix \ No newline at end of file diff --git a/Lang/Phix/Detect-division-by-zero b/Lang/Phix/Detect-division-by-zero new file mode 120000 index 0000000000..8ca42b9e83 --- /dev/null +++ b/Lang/Phix/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Phix \ No newline at end of file diff --git a/Lang/Phix/Digital-root b/Lang/Phix/Digital-root new file mode 120000 index 0000000000..d8e98e6f56 --- /dev/null +++ b/Lang/Phix/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Phix \ No newline at end of file diff --git a/Lang/Phix/Dinesmans-multiple-dwelling-problem b/Lang/Phix/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..8df975f600 --- /dev/null +++ b/Lang/Phix/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Phix \ No newline at end of file diff --git a/Lang/Phix/Doubly-linked-list-Element-definition b/Lang/Phix/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..ef34ef4d0c --- /dev/null +++ b/Lang/Phix/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/Phix \ No newline at end of file diff --git a/Lang/Phix/Doubly-linked-list-Element-insertion b/Lang/Phix/Doubly-linked-list-Element-insertion new file mode 120000 index 0000000000..c03e3b9424 --- /dev/null +++ b/Lang/Phix/Doubly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-insertion/Phix \ No newline at end of file diff --git a/Lang/Phix/Doubly-linked-list-Traversal b/Lang/Phix/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..ac5c9509b8 --- /dev/null +++ b/Lang/Phix/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/Phix \ No newline at end of file diff --git a/Lang/Phix/Dragon-curve b/Lang/Phix/Dragon-curve new file mode 120000 index 0000000000..8fde30f858 --- /dev/null +++ b/Lang/Phix/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Phix \ No newline at end of file diff --git a/Lang/Phix/Draw-a-clock b/Lang/Phix/Draw-a-clock new file mode 120000 index 0000000000..c479c77a6c --- /dev/null +++ b/Lang/Phix/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Phix \ No newline at end of file diff --git a/Lang/Phix/Draw-a-sphere b/Lang/Phix/Draw-a-sphere new file mode 120000 index 0000000000..6401f2581b --- /dev/null +++ b/Lang/Phix/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/Phix \ No newline at end of file diff --git a/Lang/Phix/Dutch-national-flag-problem b/Lang/Phix/Dutch-national-flag-problem new file mode 120000 index 0000000000..06cce5c39f --- /dev/null +++ b/Lang/Phix/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Phix \ No newline at end of file diff --git a/Lang/Phix/Dynamic-variable-names b/Lang/Phix/Dynamic-variable-names new file mode 120000 index 0000000000..5c440a8bd0 --- /dev/null +++ b/Lang/Phix/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Phix \ No newline at end of file diff --git a/Lang/Phix/Empty-directory b/Lang/Phix/Empty-directory new file mode 120000 index 0000000000..8a28474306 --- /dev/null +++ b/Lang/Phix/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Phix \ No newline at end of file diff --git a/Lang/Phix/Entropy b/Lang/Phix/Entropy new file mode 120000 index 0000000000..9555ce7675 --- /dev/null +++ b/Lang/Phix/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Phix \ No newline at end of file diff --git a/Lang/Phix/Evaluate-binomial-coefficients b/Lang/Phix/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..e095fe2ea8 --- /dev/null +++ b/Lang/Phix/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Phix \ No newline at end of file diff --git a/Lang/Phix/Exceptions b/Lang/Phix/Exceptions new file mode 120000 index 0000000000..da7753f499 --- /dev/null +++ b/Lang/Phix/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Phix \ No newline at end of file diff --git a/Lang/Phix/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Phix/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..6c2f6d7b09 --- /dev/null +++ b/Lang/Phix/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Phix \ No newline at end of file diff --git a/Lang/Phix/Executable-library b/Lang/Phix/Executable-library new file mode 120000 index 0000000000..a565bfd753 --- /dev/null +++ b/Lang/Phix/Executable-library @@ -0,0 +1 @@ +../../Task/Executable-library/Phix \ No newline at end of file diff --git a/Lang/Phix/Execute-SNUSP b/Lang/Phix/Execute-SNUSP new file mode 120000 index 0000000000..1793312fe9 --- /dev/null +++ b/Lang/Phix/Execute-SNUSP @@ -0,0 +1 @@ +../../Task/Execute-SNUSP/Phix \ No newline at end of file diff --git a/Lang/Phix/Execute-a-Markov-algorithm b/Lang/Phix/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..c2a713197d --- /dev/null +++ b/Lang/Phix/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/Phix \ No newline at end of file diff --git a/Lang/Phix/Extend-your-language b/Lang/Phix/Extend-your-language new file mode 120000 index 0000000000..0afbad34d0 --- /dev/null +++ b/Lang/Phix/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/Phix \ No newline at end of file diff --git a/Lang/Phix/Extensible-prime-generator b/Lang/Phix/Extensible-prime-generator new file mode 120000 index 0000000000..a420fdc678 --- /dev/null +++ b/Lang/Phix/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Phix \ No newline at end of file diff --git a/Lang/Phix/Factors-of-a-Mersenne-number b/Lang/Phix/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..b4b8f4a390 --- /dev/null +++ b/Lang/Phix/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Phix \ No newline at end of file diff --git a/Lang/Phix/Fast-Fourier-transform b/Lang/Phix/Fast-Fourier-transform new file mode 120000 index 0000000000..f7dc5d0f4d --- /dev/null +++ b/Lang/Phix/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Phix \ No newline at end of file diff --git a/Lang/Phix/Fibonacci-n-step-number-sequences b/Lang/Phix/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..2242ea7fe5 --- /dev/null +++ b/Lang/Phix/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Phix \ No newline at end of file diff --git a/Lang/Phix/Fibonacci-word b/Lang/Phix/Fibonacci-word new file mode 120000 index 0000000000..0a81739891 --- /dev/null +++ b/Lang/Phix/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Phix \ No newline at end of file diff --git a/Lang/Phix/Fibonacci-word-fractal b/Lang/Phix/Fibonacci-word-fractal new file mode 120000 index 0000000000..752acc78ae --- /dev/null +++ b/Lang/Phix/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Phix \ No newline at end of file diff --git a/Lang/Phix/Find-common-directory-path b/Lang/Phix/Find-common-directory-path new file mode 120000 index 0000000000..a35a69326d --- /dev/null +++ b/Lang/Phix/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Phix \ No newline at end of file diff --git a/Lang/Phix/First-class-environments b/Lang/Phix/First-class-environments new file mode 120000 index 0000000000..e6e93858fc --- /dev/null +++ b/Lang/Phix/First-class-environments @@ -0,0 +1 @@ +../../Task/First-class-environments/Phix \ No newline at end of file diff --git a/Lang/Phix/Floyds-triangle b/Lang/Phix/Floyds-triangle new file mode 120000 index 0000000000..e4b26c7fb3 --- /dev/null +++ b/Lang/Phix/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Phix \ No newline at end of file diff --git a/Lang/Phix/Forest-fire b/Lang/Phix/Forest-fire new file mode 120000 index 0000000000..3568536a59 --- /dev/null +++ b/Lang/Phix/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/Phix \ No newline at end of file diff --git a/Lang/Phix/Forward-difference b/Lang/Phix/Forward-difference new file mode 120000 index 0000000000..436436e86f --- /dev/null +++ b/Lang/Phix/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/Phix \ No newline at end of file diff --git a/Lang/Phix/Four-bit-adder b/Lang/Phix/Four-bit-adder new file mode 120000 index 0000000000..0de84961c6 --- /dev/null +++ b/Lang/Phix/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Phix \ No newline at end of file diff --git a/Lang/Phix/Function-prototype b/Lang/Phix/Function-prototype new file mode 120000 index 0000000000..a94b536a46 --- /dev/null +++ b/Lang/Phix/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/Phix \ No newline at end of file diff --git a/Lang/Phix/GUI-Maximum-window-dimensions b/Lang/Phix/GUI-Maximum-window-dimensions new file mode 120000 index 0000000000..91a4fb165f --- /dev/null +++ b/Lang/Phix/GUI-Maximum-window-dimensions @@ -0,0 +1 @@ +../../Task/GUI-Maximum-window-dimensions/Phix \ No newline at end of file diff --git a/Lang/Phix/Galton-box-animation b/Lang/Phix/Galton-box-animation new file mode 120000 index 0000000000..2f5619ea38 --- /dev/null +++ b/Lang/Phix/Galton-box-animation @@ -0,0 +1 @@ +../../Task/Galton-box-animation/Phix \ No newline at end of file diff --git a/Lang/Phix/Gamma-function b/Lang/Phix/Gamma-function new file mode 120000 index 0000000000..bcf18bdb8b --- /dev/null +++ b/Lang/Phix/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Phix \ No newline at end of file diff --git a/Lang/Phix/Generate-Chess960-starting-position b/Lang/Phix/Generate-Chess960-starting-position new file mode 120000 index 0000000000..dfe8826494 --- /dev/null +++ b/Lang/Phix/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Phix \ No newline at end of file diff --git a/Lang/Phix/Generator-Exponential b/Lang/Phix/Generator-Exponential new file mode 120000 index 0000000000..89334f7406 --- /dev/null +++ b/Lang/Phix/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/Phix \ No newline at end of file diff --git a/Lang/Phix/Globally-replace-text-in-several-files b/Lang/Phix/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..a0783b85df --- /dev/null +++ b/Lang/Phix/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Phix \ No newline at end of file diff --git a/Lang/Phix/Greyscale-bars-Display b/Lang/Phix/Greyscale-bars-Display new file mode 120000 index 0000000000..949e639f69 --- /dev/null +++ b/Lang/Phix/Greyscale-bars-Display @@ -0,0 +1 @@ +../../Task/Greyscale-bars-Display/Phix \ No newline at end of file diff --git a/Lang/Phix/Hamming-numbers b/Lang/Phix/Hamming-numbers new file mode 120000 index 0000000000..9e99a0f4d5 --- /dev/null +++ b/Lang/Phix/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/Phix \ No newline at end of file diff --git a/Lang/Phix/Harshad-or-Niven-series b/Lang/Phix/Harshad-or-Niven-series new file mode 120000 index 0000000000..5e73925a30 --- /dev/null +++ b/Lang/Phix/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Phix \ No newline at end of file diff --git a/Lang/Phix/Hash-from-two-arrays b/Lang/Phix/Hash-from-two-arrays new file mode 120000 index 0000000000..7c82126813 --- /dev/null +++ b/Lang/Phix/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Phix \ No newline at end of file diff --git a/Lang/Phix/Hash-join b/Lang/Phix/Hash-join new file mode 120000 index 0000000000..7206f9d327 --- /dev/null +++ b/Lang/Phix/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Phix \ No newline at end of file diff --git a/Lang/Phix/Haversine-formula b/Lang/Phix/Haversine-formula new file mode 120000 index 0000000000..9c85b40a95 --- /dev/null +++ b/Lang/Phix/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Phix \ No newline at end of file diff --git a/Lang/Phix/Hello-world-Newbie b/Lang/Phix/Hello-world-Newbie new file mode 120000 index 0000000000..2d3fb2af43 --- /dev/null +++ b/Lang/Phix/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Phix \ No newline at end of file diff --git a/Lang/Phix/Holidays-related-to-Easter b/Lang/Phix/Holidays-related-to-Easter new file mode 120000 index 0000000000..b4e324c851 --- /dev/null +++ b/Lang/Phix/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/Phix \ No newline at end of file diff --git a/Lang/Phix/Horners-rule-for-polynomial-evaluation b/Lang/Phix/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..8c6e48b9e9 --- /dev/null +++ b/Lang/Phix/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Phix \ No newline at end of file diff --git a/Lang/Phix/Host-introspection b/Lang/Phix/Host-introspection new file mode 120000 index 0000000000..8c8cb9affb --- /dev/null +++ b/Lang/Phix/Host-introspection @@ -0,0 +1 @@ +../../Task/Host-introspection/Phix \ No newline at end of file diff --git a/Lang/Phix/I-before-E-except-after-C b/Lang/Phix/I-before-E-except-after-C new file mode 120000 index 0000000000..c435201cc9 --- /dev/null +++ b/Lang/Phix/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Phix \ No newline at end of file diff --git a/Lang/Phix/IBAN b/Lang/Phix/IBAN new file mode 120000 index 0000000000..172dd27769 --- /dev/null +++ b/Lang/Phix/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Phix \ No newline at end of file diff --git a/Lang/Phix/Identity-matrix b/Lang/Phix/Identity-matrix new file mode 120000 index 0000000000..89eccbb0d1 --- /dev/null +++ b/Lang/Phix/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Phix \ No newline at end of file diff --git a/Lang/Phix/Input-loop b/Lang/Phix/Input-loop new file mode 120000 index 0000000000..99e27c499a --- /dev/null +++ b/Lang/Phix/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Phix \ No newline at end of file diff --git a/Lang/Phix/Iterated-digits-squaring b/Lang/Phix/Iterated-digits-squaring new file mode 120000 index 0000000000..876336fa3b --- /dev/null +++ b/Lang/Phix/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Phix \ No newline at end of file diff --git a/Lang/Phix/JSON b/Lang/Phix/JSON new file mode 120000 index 0000000000..552f236874 --- /dev/null +++ b/Lang/Phix/JSON @@ -0,0 +1 @@ +../../Task/JSON/Phix \ No newline at end of file diff --git a/Lang/Phix/Jensens-Device b/Lang/Phix/Jensens-Device new file mode 120000 index 0000000000..3a50dda7ba --- /dev/null +++ b/Lang/Phix/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Phix \ No newline at end of file diff --git a/Lang/Phix/Josephus-problem b/Lang/Phix/Josephus-problem new file mode 120000 index 0000000000..eaf470e41e --- /dev/null +++ b/Lang/Phix/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Phix \ No newline at end of file diff --git a/Lang/Phix/Kaprekar-numbers b/Lang/Phix/Kaprekar-numbers new file mode 120000 index 0000000000..6dd6588473 --- /dev/null +++ b/Lang/Phix/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Phix \ No newline at end of file diff --git a/Lang/Phix/Knapsack-problem-0-1 b/Lang/Phix/Knapsack-problem-0-1 new file mode 120000 index 0000000000..b7de898389 --- /dev/null +++ b/Lang/Phix/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Phix \ No newline at end of file diff --git a/Lang/Phix/Knapsack-problem-Bounded b/Lang/Phix/Knapsack-problem-Bounded new file mode 120000 index 0000000000..f56b14ad0c --- /dev/null +++ b/Lang/Phix/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Phix \ No newline at end of file diff --git a/Lang/Phix/Knapsack-problem-Continuous b/Lang/Phix/Knapsack-problem-Continuous new file mode 120000 index 0000000000..dbb8215805 --- /dev/null +++ b/Lang/Phix/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Phix \ No newline at end of file diff --git a/Lang/Phix/Knapsack-problem-Unbounded b/Lang/Phix/Knapsack-problem-Unbounded new file mode 120000 index 0000000000..10ac9be06e --- /dev/null +++ b/Lang/Phix/Knapsack-problem-Unbounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Unbounded/Phix \ No newline at end of file diff --git a/Lang/Phix/LZW-compression b/Lang/Phix/LZW-compression new file mode 120000 index 0000000000..25ce9650a5 --- /dev/null +++ b/Lang/Phix/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Phix \ No newline at end of file diff --git a/Lang/Phix/Left-factorials b/Lang/Phix/Left-factorials new file mode 120000 index 0000000000..9db5f8d8c1 --- /dev/null +++ b/Lang/Phix/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Phix \ No newline at end of file diff --git a/Lang/Phix/Linear-congruential-generator b/Lang/Phix/Linear-congruential-generator new file mode 120000 index 0000000000..44bfc6ff1e --- /dev/null +++ b/Lang/Phix/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/Phix \ No newline at end of file diff --git a/Lang/Phix/List-comprehensions b/Lang/Phix/List-comprehensions new file mode 120000 index 0000000000..859af1ac52 --- /dev/null +++ b/Lang/Phix/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Phix \ No newline at end of file diff --git a/Lang/Phix/Longest-common-subsequence b/Lang/Phix/Longest-common-subsequence new file mode 120000 index 0000000000..0cfa682b86 --- /dev/null +++ b/Lang/Phix/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/Phix \ No newline at end of file diff --git a/Lang/Phix/Longest-increasing-subsequence b/Lang/Phix/Longest-increasing-subsequence new file mode 120000 index 0000000000..642dc7497a --- /dev/null +++ b/Lang/Phix/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Phix \ No newline at end of file diff --git a/Lang/Phix/Look-and-say-sequence b/Lang/Phix/Look-and-say-sequence new file mode 120000 index 0000000000..d5b65ce442 --- /dev/null +++ b/Lang/Phix/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Phix \ No newline at end of file diff --git a/Lang/Phix/Lucas-Lehmer-test b/Lang/Phix/Lucas-Lehmer-test new file mode 120000 index 0000000000..513d01a234 --- /dev/null +++ b/Lang/Phix/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/Phix \ No newline at end of file diff --git a/Lang/Phix/Ludic-numbers b/Lang/Phix/Ludic-numbers new file mode 120000 index 0000000000..d8d5606534 --- /dev/null +++ b/Lang/Phix/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Phix \ No newline at end of file diff --git a/Lang/Phix/Make-directory-path b/Lang/Phix/Make-directory-path new file mode 120000 index 0000000000..13635c080c --- /dev/null +++ b/Lang/Phix/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Phix \ No newline at end of file diff --git a/Lang/Phix/Man-or-boy-test b/Lang/Phix/Man-or-boy-test new file mode 120000 index 0000000000..abe4ba2608 --- /dev/null +++ b/Lang/Phix/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Phix \ No newline at end of file diff --git a/Lang/Phix/Matrix-arithmetic b/Lang/Phix/Matrix-arithmetic new file mode 120000 index 0000000000..19a3b3b9db --- /dev/null +++ b/Lang/Phix/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Phix \ No newline at end of file diff --git a/Lang/Phix/Matrix-exponentiation-operator b/Lang/Phix/Matrix-exponentiation-operator new file mode 120000 index 0000000000..fd9592a56f --- /dev/null +++ b/Lang/Phix/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/Phix \ No newline at end of file diff --git a/Lang/Phix/Maximum-triangle-path-sum b/Lang/Phix/Maximum-triangle-path-sum new file mode 120000 index 0000000000..6a7c0a1ae6 --- /dev/null +++ b/Lang/Phix/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Phix \ No newline at end of file diff --git a/Lang/Phix/Maze-generation b/Lang/Phix/Maze-generation new file mode 120000 index 0000000000..582ae4c715 --- /dev/null +++ b/Lang/Phix/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Phix \ No newline at end of file diff --git a/Lang/Phix/Maze-solving b/Lang/Phix/Maze-solving new file mode 120000 index 0000000000..dc87c48f99 --- /dev/null +++ b/Lang/Phix/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/Phix \ No newline at end of file diff --git a/Lang/Phix/Memory-layout-of-a-data-structure b/Lang/Phix/Memory-layout-of-a-data-structure new file mode 120000 index 0000000000..21635aa55c --- /dev/null +++ b/Lang/Phix/Memory-layout-of-a-data-structure @@ -0,0 +1 @@ +../../Task/Memory-layout-of-a-data-structure/Phix \ No newline at end of file diff --git a/Lang/Phix/Metered-concurrency b/Lang/Phix/Metered-concurrency new file mode 120000 index 0000000000..e5d78dba8c --- /dev/null +++ b/Lang/Phix/Metered-concurrency @@ -0,0 +1 @@ +../../Task/Metered-concurrency/Phix \ No newline at end of file diff --git a/Lang/Phix/Middle-three-digits b/Lang/Phix/Middle-three-digits new file mode 120000 index 0000000000..f95a879140 --- /dev/null +++ b/Lang/Phix/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Phix \ No newline at end of file diff --git a/Lang/Phix/Monte-Carlo-methods b/Lang/Phix/Monte-Carlo-methods new file mode 120000 index 0000000000..c5088dfb7a --- /dev/null +++ b/Lang/Phix/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/Phix \ No newline at end of file diff --git a/Lang/Phix/Mouse-position b/Lang/Phix/Mouse-position new file mode 120000 index 0000000000..488a313cca --- /dev/null +++ b/Lang/Phix/Mouse-position @@ -0,0 +1 @@ +../../Task/Mouse-position/Phix \ No newline at end of file diff --git a/Lang/Phix/Move-to-front-algorithm b/Lang/Phix/Move-to-front-algorithm new file mode 120000 index 0000000000..d2e03a752e --- /dev/null +++ b/Lang/Phix/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Phix \ No newline at end of file diff --git a/Lang/Phix/Multifactorial b/Lang/Phix/Multifactorial new file mode 120000 index 0000000000..555c9ff69c --- /dev/null +++ b/Lang/Phix/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Phix \ No newline at end of file diff --git a/Lang/Phix/Multiple-distinct-objects b/Lang/Phix/Multiple-distinct-objects new file mode 120000 index 0000000000..6b0b5a2aba --- /dev/null +++ b/Lang/Phix/Multiple-distinct-objects @@ -0,0 +1 @@ +../../Task/Multiple-distinct-objects/Phix \ No newline at end of file diff --git a/Lang/Phix/Multisplit b/Lang/Phix/Multisplit new file mode 120000 index 0000000000..7570dd19a9 --- /dev/null +++ b/Lang/Phix/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/Phix \ No newline at end of file diff --git a/Lang/Phix/N-queens-problem b/Lang/Phix/N-queens-problem new file mode 120000 index 0000000000..3a06609449 --- /dev/null +++ b/Lang/Phix/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Phix \ No newline at end of file diff --git a/Lang/Phix/Narcissistic-decimal-number b/Lang/Phix/Narcissistic-decimal-number new file mode 120000 index 0000000000..fc6312c53a --- /dev/null +++ b/Lang/Phix/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Phix \ No newline at end of file diff --git a/Lang/Phix/Natural-sorting b/Lang/Phix/Natural-sorting new file mode 120000 index 0000000000..13760a488d --- /dev/null +++ b/Lang/Phix/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Phix \ No newline at end of file diff --git a/Lang/Phix/Non-continuous-subsequences b/Lang/Phix/Non-continuous-subsequences new file mode 120000 index 0000000000..e2eeebaf86 --- /dev/null +++ b/Lang/Phix/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/Phix \ No newline at end of file diff --git a/Lang/Phix/Nth b/Lang/Phix/Nth new file mode 120000 index 0000000000..4fd8c71e74 --- /dev/null +++ b/Lang/Phix/Nth @@ -0,0 +1 @@ +../../Task/Nth/Phix \ No newline at end of file diff --git a/Lang/Phix/Nth-root b/Lang/Phix/Nth-root new file mode 120000 index 0000000000..96649cf421 --- /dev/null +++ b/Lang/Phix/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/Phix \ No newline at end of file diff --git a/Lang/Phix/Odd-word-problem b/Lang/Phix/Odd-word-problem new file mode 120000 index 0000000000..acca77721a --- /dev/null +++ b/Lang/Phix/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Phix \ No newline at end of file diff --git a/Lang/Phix/Order-two-numerical-lists b/Lang/Phix/Order-two-numerical-lists new file mode 120000 index 0000000000..c58dd7d102 --- /dev/null +++ b/Lang/Phix/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Phix \ No newline at end of file diff --git a/Lang/Phix/Ordered-Partitions b/Lang/Phix/Ordered-Partitions new file mode 120000 index 0000000000..d2086ca9cd --- /dev/null +++ b/Lang/Phix/Ordered-Partitions @@ -0,0 +1 @@ +../../Task/Ordered-Partitions/Phix \ No newline at end of file diff --git a/Lang/Phix/Pangram-checker b/Lang/Phix/Pangram-checker new file mode 120000 index 0000000000..19e5ba2fbe --- /dev/null +++ b/Lang/Phix/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/Phix \ No newline at end of file diff --git a/Lang/Phix/Parametric-polymorphism b/Lang/Phix/Parametric-polymorphism new file mode 120000 index 0000000000..5641d2183c --- /dev/null +++ b/Lang/Phix/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/Phix \ No newline at end of file diff --git a/Lang/Phix/Partial-function-application b/Lang/Phix/Partial-function-application new file mode 120000 index 0000000000..3755ad9f07 --- /dev/null +++ b/Lang/Phix/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Phix \ No newline at end of file diff --git a/Lang/Phix/Permutation-test b/Lang/Phix/Permutation-test new file mode 120000 index 0000000000..cba3df507f --- /dev/null +++ b/Lang/Phix/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Phix \ No newline at end of file diff --git a/Lang/Phix/Permutations-Derangements b/Lang/Phix/Permutations-Derangements new file mode 120000 index 0000000000..2e6e9dbd2c --- /dev/null +++ b/Lang/Phix/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/Phix \ No newline at end of file diff --git a/Lang/Phix/Permutations-by-swapping b/Lang/Phix/Permutations-by-swapping new file mode 120000 index 0000000000..6d99ef65e9 --- /dev/null +++ b/Lang/Phix/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Phix \ No newline at end of file diff --git a/Lang/Phix/Pernicious-numbers b/Lang/Phix/Pernicious-numbers new file mode 120000 index 0000000000..a4c57808f0 --- /dev/null +++ b/Lang/Phix/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Phix \ No newline at end of file diff --git a/Lang/Phix/Playing-cards b/Lang/Phix/Playing-cards new file mode 120000 index 0000000000..d936ea7d99 --- /dev/null +++ b/Lang/Phix/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/Phix \ No newline at end of file diff --git a/Lang/Phix/Plot-coordinate-pairs b/Lang/Phix/Plot-coordinate-pairs new file mode 120000 index 0000000000..03581f83e4 --- /dev/null +++ b/Lang/Phix/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Phix \ No newline at end of file diff --git a/Lang/Phix/Pointers-and-references b/Lang/Phix/Pointers-and-references new file mode 120000 index 0000000000..ebed745f2e --- /dev/null +++ b/Lang/Phix/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/Phix \ No newline at end of file diff --git a/Lang/Phix/Polymorphic-copy b/Lang/Phix/Polymorphic-copy new file mode 120000 index 0000000000..0febee2513 --- /dev/null +++ b/Lang/Phix/Polymorphic-copy @@ -0,0 +1 @@ +../../Task/Polymorphic-copy/Phix \ No newline at end of file diff --git a/Lang/Phix/Polynomial-regression b/Lang/Phix/Polynomial-regression new file mode 120000 index 0000000000..1350104c6c --- /dev/null +++ b/Lang/Phix/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Phix \ No newline at end of file diff --git a/Lang/Phix/Power-set b/Lang/Phix/Power-set new file mode 120000 index 0000000000..e1bb42856f --- /dev/null +++ b/Lang/Phix/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Phix \ No newline at end of file diff --git a/Lang/Phix/Prime-decomposition b/Lang/Phix/Prime-decomposition new file mode 120000 index 0000000000..e33b15ecbe --- /dev/null +++ b/Lang/Phix/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Phix \ No newline at end of file diff --git a/Lang/Phix/Priority-queue b/Lang/Phix/Priority-queue new file mode 120000 index 0000000000..20be63060b --- /dev/null +++ b/Lang/Phix/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Phix \ No newline at end of file diff --git a/Lang/Phix/Range-expansion b/Lang/Phix/Range-expansion new file mode 120000 index 0000000000..ae3b1b2005 --- /dev/null +++ b/Lang/Phix/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/Phix \ No newline at end of file diff --git a/Lang/Phix/Read-a-configuration-file b/Lang/Phix/Read-a-configuration-file new file mode 120000 index 0000000000..f2c4a13fb5 --- /dev/null +++ b/Lang/Phix/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Phix \ No newline at end of file diff --git a/Lang/Phix/Read-a-specific-line-from-a-file b/Lang/Phix/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..c39a117da6 --- /dev/null +++ b/Lang/Phix/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Phix \ No newline at end of file diff --git a/Lang/Phix/Regular-expressions b/Lang/Phix/Regular-expressions new file mode 120000 index 0000000000..430f903fad --- /dev/null +++ b/Lang/Phix/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Phix \ No newline at end of file diff --git a/Lang/Phix/Remove-lines-from-a-file b/Lang/Phix/Remove-lines-from-a-file new file mode 120000 index 0000000000..6c69a59858 --- /dev/null +++ b/Lang/Phix/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Phix \ No newline at end of file diff --git a/Lang/Phix/Rename-a-file b/Lang/Phix/Rename-a-file new file mode 120000 index 0000000000..eb20902940 --- /dev/null +++ b/Lang/Phix/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/Phix \ No newline at end of file diff --git a/Lang/Phix/Rep-string b/Lang/Phix/Rep-string new file mode 120000 index 0000000000..cef6d6a202 --- /dev/null +++ b/Lang/Phix/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Phix \ No newline at end of file diff --git a/Lang/Phix/Roots-of-a-function b/Lang/Phix/Roots-of-a-function new file mode 120000 index 0000000000..1681882217 --- /dev/null +++ b/Lang/Phix/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/Phix \ No newline at end of file diff --git a/Lang/Phix/Roots-of-a-quadratic-function b/Lang/Phix/Roots-of-a-quadratic-function new file mode 120000 index 0000000000..d3f65e1350 --- /dev/null +++ b/Lang/Phix/Roots-of-a-quadratic-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-quadratic-function/Phix \ No newline at end of file diff --git a/Lang/Phix/Roots-of-unity b/Lang/Phix/Roots-of-unity new file mode 120000 index 0000000000..aa836bbff6 --- /dev/null +++ b/Lang/Phix/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/Phix \ No newline at end of file diff --git a/Lang/Phix/Runge-Kutta-method b/Lang/Phix/Runge-Kutta-method new file mode 120000 index 0000000000..9f0aefa2c9 --- /dev/null +++ b/Lang/Phix/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Phix \ No newline at end of file diff --git a/Lang/Phix/Same-Fringe b/Lang/Phix/Same-Fringe new file mode 120000 index 0000000000..0b589e163d --- /dev/null +++ b/Lang/Phix/Same-Fringe @@ -0,0 +1 @@ +../../Task/Same-Fringe/Phix \ No newline at end of file diff --git a/Lang/Phix/Scope-modifiers b/Lang/Phix/Scope-modifiers new file mode 120000 index 0000000000..7b4425ed54 --- /dev/null +++ b/Lang/Phix/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/Phix \ No newline at end of file diff --git a/Lang/Phix/Self-referential-sequence b/Lang/Phix/Self-referential-sequence new file mode 120000 index 0000000000..d7f8449ea2 --- /dev/null +++ b/Lang/Phix/Self-referential-sequence @@ -0,0 +1 @@ +../../Task/Self-referential-sequence/Phix \ No newline at end of file diff --git a/Lang/Phix/Semiprime b/Lang/Phix/Semiprime new file mode 120000 index 0000000000..fb9894b68f --- /dev/null +++ b/Lang/Phix/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Phix \ No newline at end of file diff --git a/Lang/Phix/Send-an-unknown-method-call b/Lang/Phix/Send-an-unknown-method-call new file mode 120000 index 0000000000..d4d8d7a31f --- /dev/null +++ b/Lang/Phix/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Phix \ No newline at end of file diff --git a/Lang/Phix/Sequence-of-primes-by-Trial-Division b/Lang/Phix/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..bab8ac08da --- /dev/null +++ b/Lang/Phix/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Phix \ No newline at end of file diff --git a/Lang/Phix/Set b/Lang/Phix/Set new file mode 120000 index 0000000000..d6b60617cb --- /dev/null +++ b/Lang/Phix/Set @@ -0,0 +1 @@ +../../Task/Set/Phix \ No newline at end of file diff --git a/Lang/Phix/Set-puzzle b/Lang/Phix/Set-puzzle new file mode 120000 index 0000000000..3e1f954285 --- /dev/null +++ b/Lang/Phix/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Phix \ No newline at end of file diff --git a/Lang/Phix/Show-the-epoch b/Lang/Phix/Show-the-epoch new file mode 120000 index 0000000000..20dc0318f3 --- /dev/null +++ b/Lang/Phix/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Phix \ No newline at end of file diff --git a/Lang/Phix/Sierpinski-triangle-Graphical b/Lang/Phix/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..5bb0d78678 --- /dev/null +++ b/Lang/Phix/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Phix \ No newline at end of file diff --git a/Lang/Phix/Singly-linked-list-Element-definition b/Lang/Phix/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..588c48e534 --- /dev/null +++ b/Lang/Phix/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Phix \ No newline at end of file diff --git a/Lang/Phix/Singly-linked-list-Element-insertion b/Lang/Phix/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..336a60103d --- /dev/null +++ b/Lang/Phix/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Phix \ No newline at end of file diff --git a/Lang/Phix/Singly-linked-list-Traversal b/Lang/Phix/Singly-linked-list-Traversal new file mode 120000 index 0000000000..f55264ae0e --- /dev/null +++ b/Lang/Phix/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Phix \ No newline at end of file diff --git a/Lang/Phix/Sort-stability b/Lang/Phix/Sort-stability new file mode 120000 index 0000000000..8bc3bd093d --- /dev/null +++ b/Lang/Phix/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Phix \ No newline at end of file diff --git a/Lang/Phix/Stable-marriage-problem b/Lang/Phix/Stable-marriage-problem new file mode 120000 index 0000000000..b7f6c52891 --- /dev/null +++ b/Lang/Phix/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Phix \ No newline at end of file diff --git a/Lang/Phix/Stack-traces b/Lang/Phix/Stack-traces new file mode 120000 index 0000000000..2f896032d6 --- /dev/null +++ b/Lang/Phix/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Phix \ No newline at end of file diff --git a/Lang/Phix/State-name-puzzle b/Lang/Phix/State-name-puzzle new file mode 120000 index 0000000000..8877102364 --- /dev/null +++ b/Lang/Phix/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Phix \ No newline at end of file diff --git a/Lang/Phix/Statistics-Basic b/Lang/Phix/Statistics-Basic new file mode 120000 index 0000000000..6281a14daa --- /dev/null +++ b/Lang/Phix/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Phix \ No newline at end of file diff --git a/Lang/Phix/Stern-Brocot-sequence b/Lang/Phix/Stern-Brocot-sequence new file mode 120000 index 0000000000..846d4c7e1f --- /dev/null +++ b/Lang/Phix/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Phix \ No newline at end of file diff --git a/Lang/Phix/Sum-multiples-of-3-and-5 b/Lang/Phix/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..c4f4f9c628 --- /dev/null +++ b/Lang/Phix/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Phix \ No newline at end of file diff --git a/Lang/Phix/Sutherland-Hodgman-polygon-clipping b/Lang/Phix/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..bab79d011b --- /dev/null +++ b/Lang/Phix/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Phix \ No newline at end of file diff --git a/Lang/Phix/Symmetric-difference b/Lang/Phix/Symmetric-difference new file mode 120000 index 0000000000..d5cfbb65ae --- /dev/null +++ b/Lang/Phix/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Phix \ No newline at end of file diff --git a/Lang/Phix/Terminal-control-Coloured-text b/Lang/Phix/Terminal-control-Coloured-text new file mode 120000 index 0000000000..1b552439b9 --- /dev/null +++ b/Lang/Phix/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Phix \ No newline at end of file diff --git a/Lang/Phix/Terminal-control-Cursor-movement b/Lang/Phix/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..288ce95c12 --- /dev/null +++ b/Lang/Phix/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/Phix \ No newline at end of file diff --git a/Lang/Phix/Terminal-control-Inverse-video b/Lang/Phix/Terminal-control-Inverse-video new file mode 120000 index 0000000000..a06d12a9cc --- /dev/null +++ b/Lang/Phix/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Phix \ No newline at end of file diff --git a/Lang/Phix/Terminal-control-Positional-read b/Lang/Phix/Terminal-control-Positional-read new file mode 120000 index 0000000000..19cda12049 --- /dev/null +++ b/Lang/Phix/Terminal-control-Positional-read @@ -0,0 +1 @@ +../../Task/Terminal-control-Positional-read/Phix \ No newline at end of file diff --git a/Lang/Phix/Terminal-control-Ringing-the-terminal-bell b/Lang/Phix/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..fd416d799c --- /dev/null +++ b/Lang/Phix/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Phix \ No newline at end of file diff --git a/Lang/Phix/Textonyms b/Lang/Phix/Textonyms new file mode 120000 index 0000000000..2eb93c655c --- /dev/null +++ b/Lang/Phix/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Phix \ No newline at end of file diff --git a/Lang/Phix/The-Twelve-Days-of-Christmas b/Lang/Phix/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..57157deef6 --- /dev/null +++ b/Lang/Phix/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Phix \ No newline at end of file diff --git a/Lang/Phix/Top-rank-per-group b/Lang/Phix/Top-rank-per-group new file mode 120000 index 0000000000..68b8a78e49 --- /dev/null +++ b/Lang/Phix/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Phix \ No newline at end of file diff --git a/Lang/Phix/Towers-of-Hanoi b/Lang/Phix/Towers-of-Hanoi new file mode 120000 index 0000000000..3cd1c6df8d --- /dev/null +++ b/Lang/Phix/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Phix \ No newline at end of file diff --git a/Lang/Phix/Trabb-Pardo-Knuth-algorithm b/Lang/Phix/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..5df5e5170b --- /dev/null +++ b/Lang/Phix/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Phix \ No newline at end of file diff --git a/Lang/Phix/Truncatable-primes b/Lang/Phix/Truncatable-primes new file mode 120000 index 0000000000..681dea2513 --- /dev/null +++ b/Lang/Phix/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Phix \ No newline at end of file diff --git a/Lang/Phix/URL-decoding b/Lang/Phix/URL-decoding new file mode 120000 index 0000000000..b7a3e492a6 --- /dev/null +++ b/Lang/Phix/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Phix \ No newline at end of file diff --git a/Lang/Phix/URL-encoding b/Lang/Phix/URL-encoding new file mode 120000 index 0000000000..34ea6bb762 --- /dev/null +++ b/Lang/Phix/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Phix \ No newline at end of file diff --git a/Lang/Phix/Universal-Turing-machine b/Lang/Phix/Universal-Turing-machine new file mode 120000 index 0000000000..e7815773a7 --- /dev/null +++ b/Lang/Phix/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Phix \ No newline at end of file diff --git a/Lang/Phix/Unix-ls b/Lang/Phix/Unix-ls new file mode 120000 index 0000000000..735513f365 --- /dev/null +++ b/Lang/Phix/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Phix \ No newline at end of file diff --git a/Lang/Phix/Update-a-configuration-file b/Lang/Phix/Update-a-configuration-file new file mode 120000 index 0000000000..338c3edd1a --- /dev/null +++ b/Lang/Phix/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/Phix \ No newline at end of file diff --git a/Lang/Phix/Variable-size-Get b/Lang/Phix/Variable-size-Get new file mode 120000 index 0000000000..7c02115752 --- /dev/null +++ b/Lang/Phix/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Phix \ No newline at end of file diff --git a/Lang/Phix/Vigen-re-cipher b/Lang/Phix/Vigen-re-cipher new file mode 120000 index 0000000000..9bc2854ec7 --- /dev/null +++ b/Lang/Phix/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Phix \ No newline at end of file diff --git a/Lang/Phix/Vigen-re-cipher-Cryptanalysis b/Lang/Phix/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..a9af087de2 --- /dev/null +++ b/Lang/Phix/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Phix \ No newline at end of file diff --git a/Lang/Phix/Voronoi-diagram b/Lang/Phix/Voronoi-diagram new file mode 120000 index 0000000000..29ad1a8296 --- /dev/null +++ b/Lang/Phix/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Phix \ No newline at end of file diff --git a/Lang/Phix/Wireworld b/Lang/Phix/Wireworld new file mode 120000 index 0000000000..458a55aa49 --- /dev/null +++ b/Lang/Phix/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Phix \ No newline at end of file diff --git a/Lang/Phix/Word-wrap b/Lang/Phix/Word-wrap new file mode 120000 index 0000000000..f39bb86b7a --- /dev/null +++ b/Lang/Phix/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Phix \ No newline at end of file diff --git a/Lang/Phix/Xiaolin-Wus-line-algorithm b/Lang/Phix/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..f06a5f7c8e --- /dev/null +++ b/Lang/Phix/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Phix \ No newline at end of file diff --git a/Lang/Phix/Yin-and-yang b/Lang/Phix/Yin-and-yang new file mode 120000 index 0000000000..f859492e20 --- /dev/null +++ b/Lang/Phix/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Phix \ No newline at end of file diff --git a/Lang/Phix/Zeckendorf-number-representation b/Lang/Phix/Zeckendorf-number-representation new file mode 120000 index 0000000000..3ad11c11f7 --- /dev/null +++ b/Lang/Phix/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Phix \ No newline at end of file diff --git a/Lang/PicoLisp/99-Bottles-of-Beer b/Lang/PicoLisp/99-Bottles-of-Beer deleted file mode 120000 index 7c5b47876e..0000000000 --- a/Lang/PicoLisp/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Bitcoin-public-point-to-address b/Lang/PicoLisp/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..3ff2212a1e --- /dev/null +++ b/Lang/PicoLisp/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Calendar---for-real-programmers b/Lang/PicoLisp/Calendar---for-real-programmers deleted file mode 120000 index c49ce49cbc..0000000000 --- a/Lang/PicoLisp/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Character-matching b/Lang/PicoLisp/Character-matching deleted file mode 120000 index 0c515809a4..0000000000 --- a/Lang/PicoLisp/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/File-IO b/Lang/PicoLisp/File-IO deleted file mode 120000 index e04416c8f8..0000000000 --- a/Lang/PicoLisp/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/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/Quickselect-algorithm b/Lang/PicoLisp/Quickselect-algorithm new file mode 120000 index 0000000000..b0a6e7e7d5 --- /dev/null +++ b/Lang/PicoLisp/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Rosetta-Code-Count-examples b/Lang/PicoLisp/Rosetta-Code-Count-examples deleted file mode 120000 index ed1164c47b..0000000000 --- a/Lang/PicoLisp/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Rosetta-Code-Find-unimplemented-tasks b/Lang/PicoLisp/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index bb0e9205ed..0000000000 --- a/Lang/PicoLisp/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Rosetta-Code-Fix-code-tags b/Lang/PicoLisp/Rosetta-Code-Fix-code-tags deleted file mode 120000 index 835c48277c..0000000000 --- a/Lang/PicoLisp/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Rosetta-Code-Rank-languages-by-popularity b/Lang/PicoLisp/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 67fe9faec9..0000000000 --- a/Lang/PicoLisp/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Standard-deviation b/Lang/PicoLisp/Standard-deviation deleted file mode 120000 index fd6c328ad7..0000000000 --- a/Lang/PicoLisp/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/PicoLisp \ No newline at end of file diff --git a/Lang/Pike/DNS-query b/Lang/Pike/DNS-query new file mode 120000 index 0000000000..e86ac931bc --- /dev/null +++ b/Lang/Pike/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Pike \ No newline at end of file diff --git a/Lang/PlainTeX/00DESCRIPTION b/Lang/PlainTeX/00DESCRIPTION index 7cd3f31b56..24b1cd5531 100644 --- a/Lang/PlainTeX/00DESCRIPTION +++ b/Lang/PlainTeX/00DESCRIPTION @@ -1,7 +1,7 @@ {{language|plainTeX}} -plainTeX is the name used to refer to the default set of ''macros'' which are always present on all [[TeX]] systems -(and it is the default preloaded format for tex executable). They were written by Knuth himself, and provide the basic to start using [[TeX]] (since "raw" [[TeX]] is not ready-to-use for documents creation). Often when one says simply "TeX document", s/he means s/he is using the plainTeX macros, even though nowadays the success of the complex feature-full [[LaTeX]] macros package creates a little bit of confusion and a lot of people, ignoring that LaTeX is just one of possible macro packages for TeX, think that LaTeX is TeX and viceversa. +{{PlainTeX}} is the name used to refer to the default set of ''macros'' which are always present on all [[TeX|{{TeX}}]] systems +(and it is the default preloaded format for tex executable). They were written by Knuth himself, and provide the basic to start using [[TeX|{{TeX}}]] (since "raw" [[TeX|{{TeX}}]] is not ready-to-use for documents creation). Often when one says simply "{{TeX}} document", s/he means s/he is using the {{PlainTeX}} macros, even though nowadays the success of the complex feature-full [[LaTeX|{{LaTeX}}]] macros package creates a little bit of confusion and a lot of people, ignoring that {{LaTeX}} is just one of possible macro packages for {{TeX}}, think that {{LaTeX}} is {{TeX}} and viceversa. -Extension to the plainTeX exists, like eplain(TeX). +Extension to the {{PlainTeX}} exists, like eplain({{TeX}}). -Even though [[LaTeX]] is nowadays almost a typesetting "standard" when using a [[TeX]] system, plainTeX is still usable and used. \ No newline at end of file +Even though [[LaTeX|{{LaTeX}}]] is nowadays almost a typesetting "standard" when using a [[TeX|{{TeX}}]] system, {{PlainTeX}} is still usable and used. \ No newline at end of file diff --git a/Lang/PlainTeX/Comments b/Lang/PlainTeX/Comments new file mode 120000 index 0000000000..ed0eaf8498 --- /dev/null +++ b/Lang/PlainTeX/Comments @@ -0,0 +1 @@ +../../Task/Comments/PlainTeX \ No newline at end of file diff --git a/Lang/PlainTeX/Empty-program b/Lang/PlainTeX/Empty-program new file mode 120000 index 0000000000..68ef701dad --- /dev/null +++ b/Lang/PlainTeX/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/PlainTeX \ No newline at end of file diff --git a/Lang/PlainTeX/Hailstone-sequence b/Lang/PlainTeX/Hailstone-sequence new file mode 120000 index 0000000000..8cd301ff64 --- /dev/null +++ b/Lang/PlainTeX/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/PlainTeX \ No newline at end of file diff --git a/Lang/PlainTeX/Hash-join b/Lang/PlainTeX/Hash-join new file mode 120000 index 0000000000..bd47b2dca5 --- /dev/null +++ b/Lang/PlainTeX/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/PlainTeX \ No newline at end of file diff --git a/Lang/PlainTeX/Increment-a-numerical-string b/Lang/PlainTeX/Increment-a-numerical-string new file mode 120000 index 0000000000..785bd18c4a --- /dev/null +++ b/Lang/PlainTeX/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/PlainTeX \ No newline at end of file diff --git a/Lang/PlainTeX/Loops-Infinite b/Lang/PlainTeX/Loops-Infinite new file mode 120000 index 0000000000..6345b4bd20 --- /dev/null +++ b/Lang/PlainTeX/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/PlainTeX \ No newline at end of file diff --git a/Lang/PlainTeX/Multifactorial b/Lang/PlainTeX/Multifactorial new file mode 120000 index 0000000000..baf5c525f7 --- /dev/null +++ b/Lang/PlainTeX/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/PlainTeX \ No newline at end of file diff --git a/Lang/PlainTeX/Phrase-reversals b/Lang/PlainTeX/Phrase-reversals new file mode 120000 index 0000000000..054ff13452 --- /dev/null +++ b/Lang/PlainTeX/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/PlainTeX \ No newline at end of file diff --git a/Lang/PlainTeX/Reverse-a-string b/Lang/PlainTeX/Reverse-a-string new file mode 120000 index 0000000000..c1064d758e --- /dev/null +++ b/Lang/PlainTeX/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/PlainTeX \ No newline at end of file diff --git a/Lang/PlainTeX/Roman-numerals-Encode b/Lang/PlainTeX/Roman-numerals-Encode new file mode 120000 index 0000000000..7775c74477 --- /dev/null +++ b/Lang/PlainTeX/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/PlainTeX \ No newline at end of file diff --git a/Lang/PlainTeX/String-append b/Lang/PlainTeX/String-append new file mode 120000 index 0000000000..bfded6c3c9 --- /dev/null +++ b/Lang/PlainTeX/String-append @@ -0,0 +1 @@ +../../Task/String-append/PlainTeX \ No newline at end of file diff --git a/Lang/PlainTeX/Zeckendorf-number-representation b/Lang/PlainTeX/Zeckendorf-number-representation new file mode 120000 index 0000000000..c38b70a034 --- /dev/null +++ b/Lang/PlainTeX/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/PlainTeX \ No newline at end of file diff --git a/Lang/Plan/00DESCRIPTION b/Lang/Plan/00DESCRIPTION new file mode 100644 index 0000000000..0ba98e3de2 --- /dev/null +++ b/Lang/Plan/00DESCRIPTION @@ -0,0 +1,2 @@ +Plan was the assemble language used on the old 1900 ICL mainframe machines. This can be used by Emulation software now +{{stub}}{{language|Plan}} \ No newline at end of file diff --git a/Lang/Plan/README b/Lang/Plan/README new file mode 100644 index 0000000000..494ce72db0 --- /dev/null +++ b/Lang/Plan/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Plan diff --git a/Lang/Pop11/File-IO b/Lang/Pop11/File-IO deleted file mode 120000 index 71262c1417..0000000000 --- a/Lang/Pop11/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Pop11 \ No newline at end of file diff --git a/Lang/PostScript/First-class-functions b/Lang/PostScript/First-class-functions new file mode 120000 index 0000000000..a8f1c90586 --- /dev/null +++ b/Lang/PostScript/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/PostScript \ No newline at end of file diff --git a/Lang/PowerBASIC/Tokenize-a-string b/Lang/PowerBASIC/Tokenize-a-string deleted file mode 120000 index c877112582..0000000000 --- a/Lang/PowerBASIC/Tokenize-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Tokenize-a-string/PowerBASIC \ No newline at end of file diff --git a/Lang/PowerShell/99-Bottles-of-Beer b/Lang/PowerShell/99-Bottles-of-Beer deleted file mode 120000 index 87efcf6679..0000000000 --- a/Lang/PowerShell/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Anagrams-Deranged-anagrams b/Lang/PowerShell/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..33184c8bf5 --- /dev/null +++ b/Lang/PowerShell/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Averages-Mean-angle b/Lang/PowerShell/Averages-Mean-angle new file mode 120000 index 0000000000..b7d7ae950d --- /dev/null +++ b/Lang/PowerShell/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Binary-search b/Lang/PowerShell/Binary-search new file mode 120000 index 0000000000..81ecd3a5b9 --- /dev/null +++ b/Lang/PowerShell/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Character-matching b/Lang/PowerShell/Character-matching deleted file mode 120000 index 9abb929c9a..0000000000 --- a/Lang/PowerShell/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Collections b/Lang/PowerShell/Collections new file mode 120000 index 0000000000..fbbe02d9ce --- /dev/null +++ b/Lang/PowerShell/Collections @@ -0,0 +1 @@ +../../Task/Collections/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/DNS-query b/Lang/PowerShell/DNS-query new file mode 120000 index 0000000000..6e8195e2b6 --- /dev/null +++ b/Lang/PowerShell/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Events b/Lang/PowerShell/Events new file mode 120000 index 0000000000..c2dfddb801 --- /dev/null +++ b/Lang/PowerShell/Events @@ -0,0 +1 @@ +../../Task/Events/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Exceptions b/Lang/PowerShell/Exceptions new file mode 120000 index 0000000000..a19cad8fa0 --- /dev/null +++ b/Lang/PowerShell/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Fibonacci-n-step-number-sequences b/Lang/PowerShell/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..9b5b82a69b --- /dev/null +++ b/Lang/PowerShell/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/File-IO b/Lang/PowerShell/File-IO deleted file mode 120000 index 8ea671e0cd..0000000000 --- a/Lang/PowerShell/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Map-range b/Lang/PowerShell/Map-range new file mode 120000 index 0000000000..3e1e4e43b5 --- /dev/null +++ b/Lang/PowerShell/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Non-decimal-radices-Input b/Lang/PowerShell/Non-decimal-radices-Input new file mode 120000 index 0000000000..ad92c5a2c3 --- /dev/null +++ b/Lang/PowerShell/Non-decimal-radices-Input @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Input/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Pi b/Lang/PowerShell/Pi new file mode 120000 index 0000000000..730e93d1e1 --- /dev/null +++ b/Lang/PowerShell/Pi @@ -0,0 +1 @@ +../../Task/Pi/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Pick-random-element b/Lang/PowerShell/Pick-random-element new file mode 120000 index 0000000000..3836399895 --- /dev/null +++ b/Lang/PowerShell/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Price-fraction b/Lang/PowerShell/Price-fraction new file mode 120000 index 0000000000..aae3972884 --- /dev/null +++ b/Lang/PowerShell/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Probabilistic-choice b/Lang/PowerShell/Probabilistic-choice new file mode 120000 index 0000000000..19532b8bcf --- /dev/null +++ b/Lang/PowerShell/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/RIPEMD-160 b/Lang/PowerShell/RIPEMD-160 new file mode 120000 index 0000000000..effbdb7c77 --- /dev/null +++ b/Lang/PowerShell/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Random-number-generator--device- b/Lang/PowerShell/Random-number-generator--device- new file mode 120000 index 0000000000..1a8eceaa3b --- /dev/null +++ b/Lang/PowerShell/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Runtime-evaluation b/Lang/PowerShell/Runtime-evaluation new file mode 120000 index 0000000000..e961ae8216 --- /dev/null +++ b/Lang/PowerShell/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/SHA-256 b/Lang/PowerShell/SHA-256 new file mode 120000 index 0000000000..c8750a02b5 --- /dev/null +++ b/Lang/PowerShell/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Send-an-unknown-method-call b/Lang/PowerShell/Send-an-unknown-method-call new file mode 120000 index 0000000000..2b76bf145d --- /dev/null +++ b/Lang/PowerShell/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Set b/Lang/PowerShell/Set new file mode 120000 index 0000000000..08887c029c --- /dev/null +++ b/Lang/PowerShell/Set @@ -0,0 +1 @@ +../../Task/Set/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Soundex b/Lang/PowerShell/Soundex new file mode 120000 index 0000000000..da9ed67a08 --- /dev/null +++ b/Lang/PowerShell/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Standard-deviation b/Lang/PowerShell/Standard-deviation deleted file mode 120000 index dd2b2e384d..0000000000 --- a/Lang/PowerShell/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Strip-a-set-of-characters-from-a-string b/Lang/PowerShell/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..75a24cadbf --- /dev/null +++ b/Lang/PowerShell/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Strip-control-codes-and-extended-characters-from-a-string b/Lang/PowerShell/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..a8d82dd602 --- /dev/null +++ b/Lang/PowerShell/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Trabb-Pardo-Knuth-algorithm b/Lang/PowerShell/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..e60b59e13c --- /dev/null +++ b/Lang/PowerShell/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Truncate-a-file b/Lang/PowerShell/Truncate-a-file new file mode 120000 index 0000000000..fde0bffdb5 --- /dev/null +++ b/Lang/PowerShell/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/URL-encoding b/Lang/PowerShell/URL-encoding new file mode 120000 index 0000000000..624b9c0ed5 --- /dev/null +++ b/Lang/PowerShell/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/PowerShell \ No newline at end of file diff --git a/Lang/ProDOS/99-Bottles-of-Beer b/Lang/ProDOS/99-Bottles-of-Beer deleted file mode 120000 index fe2e9d444b..0000000000 --- a/Lang/ProDOS/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/ProDOS \ No newline at end of file diff --git a/Lang/Processing/Even-or-odd b/Lang/Processing/Even-or-odd new file mode 120000 index 0000000000..ff1a02d071 --- /dev/null +++ b/Lang/Processing/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Processing \ No newline at end of file diff --git a/Lang/Processing/Loops-For b/Lang/Processing/Loops-For new file mode 120000 index 0000000000..a8eaca7143 --- /dev/null +++ b/Lang/Processing/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Processing \ No newline at end of file diff --git a/Lang/Prolog/99-Bottles-of-Beer b/Lang/Prolog/99-Bottles-of-Beer deleted file mode 120000 index 6fc27c5350..0000000000 --- a/Lang/Prolog/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/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/Protium/Comments b/Lang/Protium/Comments deleted file mode 120000 index 00b35f60b4..0000000000 --- a/Lang/Protium/Comments +++ /dev/null @@ -1 +0,0 @@ -../../Task/Comments/Protium \ No newline at end of file diff --git a/Lang/Protium/Create-an-HTML-table b/Lang/Protium/Create-an-HTML-table deleted file mode 120000 index 2ca41736a9..0000000000 --- a/Lang/Protium/Create-an-HTML-table +++ /dev/null @@ -1 +0,0 @@ -../../Task/Create-an-HTML-table/Protium \ No newline at end of file diff --git a/Lang/Protium/Day-of-the-week b/Lang/Protium/Day-of-the-week deleted file mode 120000 index 9ab0611728..0000000000 --- a/Lang/Protium/Day-of-the-week +++ /dev/null @@ -1 +0,0 @@ -../../Task/Day-of-the-week/Protium \ No newline at end of file diff --git a/Lang/Protium/Factorial b/Lang/Protium/Factorial deleted file mode 120000 index 60cfeea912..0000000000 --- a/Lang/Protium/Factorial +++ /dev/null @@ -1 +0,0 @@ -../../Task/Factorial/Protium \ No newline at end of file diff --git a/Lang/Protium/Filter b/Lang/Protium/Filter deleted file mode 120000 index 40889c8904..0000000000 --- a/Lang/Protium/Filter +++ /dev/null @@ -1 +0,0 @@ -../../Task/Filter/Protium \ No newline at end of file diff --git a/Lang/Protium/FizzBuzz b/Lang/Protium/FizzBuzz deleted file mode 120000 index 26be33a1e8..0000000000 --- a/Lang/Protium/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Protium \ No newline at end of file diff --git a/Lang/Protium/HTTP b/Lang/Protium/HTTP deleted file mode 120000 index fd487b07e4..0000000000 --- a/Lang/Protium/HTTP +++ /dev/null @@ -1 +0,0 @@ -../../Task/HTTP/Protium \ No newline at end of file diff --git a/Lang/Protium/History-variables b/Lang/Protium/History-variables deleted file mode 120000 index 435783db23..0000000000 --- a/Lang/Protium/History-variables +++ /dev/null @@ -1 +0,0 @@ -../../Task/History-variables/Protium \ No newline at end of file diff --git a/Lang/Protium/Loops-Downward-for b/Lang/Protium/Loops-Downward-for deleted file mode 120000 index 0495237e33..0000000000 --- a/Lang/Protium/Loops-Downward-for +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Downward-for/Protium \ No newline at end of file diff --git a/Lang/Protium/Loops-N-plus-one-half b/Lang/Protium/Loops-N-plus-one-half deleted file mode 120000 index ccf5e85e7c..0000000000 --- a/Lang/Protium/Loops-N-plus-one-half +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-N-plus-one-half/Protium \ No newline at end of file diff --git a/Lang/Protium/Read-a-configuration-file b/Lang/Protium/Read-a-configuration-file deleted file mode 120000 index 730de14d65..0000000000 --- a/Lang/Protium/Read-a-configuration-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Read-a-configuration-file/Protium \ No newline at end of file diff --git a/Lang/Protium/Reverse-a-string b/Lang/Protium/Reverse-a-string deleted file mode 120000 index d345e34882..0000000000 --- a/Lang/Protium/Reverse-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Reverse-a-string/Protium \ No newline at end of file diff --git a/Lang/Protium/Roman-numerals-Encode b/Lang/Protium/Roman-numerals-Encode deleted file mode 120000 index 2dd886ad2f..0000000000 --- a/Lang/Protium/Roman-numerals-Encode +++ /dev/null @@ -1 +0,0 @@ -../../Task/Roman-numerals-Encode/Protium \ No newline at end of file diff --git a/Lang/Protium/Singly-linked-list-Traversal b/Lang/Protium/Singly-linked-list-Traversal deleted file mode 120000 index 9a9187cee8..0000000000 --- a/Lang/Protium/Singly-linked-list-Traversal +++ /dev/null @@ -1 +0,0 @@ -../../Task/Singly-linked-list-Traversal/Protium \ No newline at end of file diff --git a/Lang/Protium/Sleep b/Lang/Protium/Sleep deleted file mode 120000 index 87cc3d33b8..0000000000 --- a/Lang/Protium/Sleep +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sleep/Protium \ No newline at end of file diff --git a/Lang/Protium/Sort-an-integer-array b/Lang/Protium/Sort-an-integer-array deleted file mode 120000 index 5712474a41..0000000000 --- a/Lang/Protium/Sort-an-integer-array +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sort-an-integer-array/Protium \ No newline at end of file diff --git a/Lang/Protium/String-case b/Lang/Protium/String-case deleted file mode 120000 index 9d5ea1e0e4..0000000000 --- a/Lang/Protium/String-case +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-case/Protium \ No newline at end of file diff --git a/Lang/Protium/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Protium/Strip-control-codes-and-extended-characters-from-a-string deleted file mode 120000 index 96aefd6590..0000000000 --- a/Lang/Protium/Strip-control-codes-and-extended-characters-from-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Strip-control-codes-and-extended-characters-from-a-string/Protium \ No newline at end of file diff --git a/Lang/Protium/Unicode-variable-names b/Lang/Protium/Unicode-variable-names deleted file mode 120000 index 67d1b95832..0000000000 --- a/Lang/Protium/Unicode-variable-names +++ /dev/null @@ -1 +0,0 @@ -../../Task/Unicode-variable-names/Protium \ No newline at end of file diff --git a/Lang/Protium/Web-scraping b/Lang/Protium/Web-scraping deleted file mode 120000 index 6613ad1328..0000000000 --- a/Lang/Protium/Web-scraping +++ /dev/null @@ -1 +0,0 @@ -../../Task/Web-scraping/Protium \ No newline at end of file diff --git a/Lang/Pure/100-doors b/Lang/Pure/100-doors new file mode 120000 index 0000000000..c7799f545b --- /dev/null +++ b/Lang/Pure/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Pure \ No newline at end of file diff --git a/Lang/Pure/N-queens-problem b/Lang/Pure/N-queens-problem new file mode 120000 index 0000000000..3f4691dfbf --- /dev/null +++ b/Lang/Pure/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Pure \ No newline at end of file diff --git a/Lang/PureBasic/99-Bottles-of-Beer b/Lang/PureBasic/99-Bottles-of-Beer deleted file mode 120000 index 9502083317..0000000000 --- a/Lang/PureBasic/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Benfords-law b/Lang/PureBasic/Benfords-law new file mode 120000 index 0000000000..02553be96a --- /dev/null +++ b/Lang/PureBasic/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Catalan-numbers-Pascals-triangle b/Lang/PureBasic/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..6f7b6ef315 --- /dev/null +++ b/Lang/PureBasic/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Character-matching b/Lang/PureBasic/Character-matching deleted file mode 120000 index e99f64e1a9..0000000000 --- a/Lang/PureBasic/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Chinese-remainder-theorem b/Lang/PureBasic/Chinese-remainder-theorem new file mode 120000 index 0000000000..81d76b3400 --- /dev/null +++ b/Lang/PureBasic/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Colour-bars-Display b/Lang/PureBasic/Colour-bars-Display deleted file mode 120000 index c734bc3566..0000000000 --- a/Lang/PureBasic/Colour-bars-Display +++ /dev/null @@ -1 +0,0 @@ -../../Task/Colour-bars-Display/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Conways-Game-of-Life b/Lang/PureBasic/Conways-Game-of-Life deleted file mode 120000 index 05347f3c59..0000000000 --- a/Lang/PureBasic/Conways-Game-of-Life +++ /dev/null @@ -1 +0,0 @@ -../../Task/Conways-Game-of-Life/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Detect-division-by-zero b/Lang/PureBasic/Detect-division-by-zero deleted file mode 120000 index 6a32f8cde3..0000000000 --- a/Lang/PureBasic/Detect-division-by-zero +++ /dev/null @@ -1 +0,0 @@ -../../Task/Detect-division-by-zero/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Draw-a-sphere b/Lang/PureBasic/Draw-a-sphere deleted file mode 120000 index 7d51f87b9d..0000000000 --- a/Lang/PureBasic/Draw-a-sphere +++ /dev/null @@ -1 +0,0 @@ -../../Task/Draw-a-sphere/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Ethiopian-multiplication b/Lang/PureBasic/Ethiopian-multiplication deleted file mode 120000 index e72cb68d85..0000000000 --- a/Lang/PureBasic/Ethiopian-multiplication +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ethiopian-multiplication/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Extensible-prime-generator b/Lang/PureBasic/Extensible-prime-generator new file mode 120000 index 0000000000..1c65a13eef --- /dev/null +++ b/Lang/PureBasic/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/File-IO b/Lang/PureBasic/File-IO deleted file mode 120000 index b566c9f77a..0000000000 --- a/Lang/PureBasic/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Find-the-last-Sunday-of-each-month b/Lang/PureBasic/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..14ebb0abe5 --- /dev/null +++ b/Lang/PureBasic/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/FizzBuzz b/Lang/PureBasic/FizzBuzz deleted file mode 120000 index b02d41c08c..0000000000 --- a/Lang/PureBasic/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Forest-fire b/Lang/PureBasic/Forest-fire deleted file mode 120000 index 17b815da23..0000000000 --- a/Lang/PureBasic/Forest-fire +++ /dev/null @@ -1 +0,0 @@ -../../Task/Forest-fire/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Generate-lower-case-ASCII-alphabet b/Lang/PureBasic/Generate-lower-case-ASCII-alphabet deleted file mode 120000 index 6e3c824ec8..0000000000 --- a/Lang/PureBasic/Generate-lower-case-ASCII-alphabet +++ /dev/null @@ -1 +0,0 @@ -../../Task/Generate-lower-case-ASCII-alphabet/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Hailstone-sequence b/Lang/PureBasic/Hailstone-sequence deleted file mode 120000 index dd23191669..0000000000 --- a/Lang/PureBasic/Hailstone-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hailstone-sequence/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Hamming-numbers b/Lang/PureBasic/Hamming-numbers new file mode 120000 index 0000000000..bf726f1413 --- /dev/null +++ b/Lang/PureBasic/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Hash-join b/Lang/PureBasic/Hash-join new file mode 120000 index 0000000000..6828c268ab --- /dev/null +++ b/Lang/PureBasic/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Haversine-formula b/Lang/PureBasic/Haversine-formula new file mode 120000 index 0000000000..f06cdb3fa2 --- /dev/null +++ b/Lang/PureBasic/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Last-Friday-of-each-month b/Lang/PureBasic/Last-Friday-of-each-month new file mode 120000 index 0000000000..ddde218e3e --- /dev/null +++ b/Lang/PureBasic/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Loops-Continue b/Lang/PureBasic/Loops-Continue deleted file mode 120000 index ab2ff10d05..0000000000 --- a/Lang/PureBasic/Loops-Continue +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Continue/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Loops-For b/Lang/PureBasic/Loops-For deleted file mode 120000 index 6227e7c2f8..0000000000 --- a/Lang/PureBasic/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Loops-Foreach b/Lang/PureBasic/Loops-Foreach deleted file mode 120000 index 5c8c42f63d..0000000000 --- a/Lang/PureBasic/Loops-Foreach +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Foreach/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Middle-three-digits b/Lang/PureBasic/Middle-three-digits deleted file mode 120000 index 0bed3b1b8a..0000000000 --- a/Lang/PureBasic/Middle-three-digits +++ /dev/null @@ -1 +0,0 @@ -../../Task/Middle-three-digits/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/Mutex b/Lang/PureBasic/Mutex deleted file mode 120000 index fb6c8e3de7..0000000000 --- a/Lang/PureBasic/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Phrase-reversals b/Lang/PureBasic/Phrase-reversals new file mode 120000 index 0000000000..e241e1638d --- /dev/null +++ b/Lang/PureBasic/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Rosetta-Code-Count-examples b/Lang/PureBasic/Rosetta-Code-Count-examples deleted file mode 120000 index 36eb6d77bc..0000000000 --- a/Lang/PureBasic/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Rosetta-Code-Fix-code-tags b/Lang/PureBasic/Rosetta-Code-Fix-code-tags deleted file mode 120000 index be0183b9a5..0000000000 --- a/Lang/PureBasic/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Rosetta-Code-Rank-languages-by-popularity b/Lang/PureBasic/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 2b3a6ed635..0000000000 --- a/Lang/PureBasic/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sequence-of-primes-by-Trial-Division b/Lang/PureBasic/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..111c7f0436 --- /dev/null +++ b/Lang/PureBasic/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Standard-deviation b/Lang/PureBasic/Standard-deviation deleted file mode 120000 index 12936a6821..0000000000 --- a/Lang/PureBasic/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/String-case b/Lang/PureBasic/String-case deleted file mode 120000 index 3d3675da1e..0000000000 --- a/Lang/PureBasic/String-case +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-case/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Terminal-control-Clear-the-screen b/Lang/PureBasic/Terminal-control-Clear-the-screen deleted file mode 120000 index 8a716535d2..0000000000 --- a/Lang/PureBasic/Terminal-control-Clear-the-screen +++ /dev/null @@ -1 +0,0 @@ -../../Task/Terminal-control-Clear-the-screen/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Terminal-control-Inverse-video b/Lang/PureBasic/Terminal-control-Inverse-video deleted file mode 120000 index 474d2fc099..0000000000 --- a/Lang/PureBasic/Terminal-control-Inverse-video +++ /dev/null @@ -1 +0,0 @@ -../../Task/Terminal-control-Inverse-video/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Tokenize-a-string b/Lang/PureBasic/Tokenize-a-string deleted file mode 120000 index fe3ee4378e..0000000000 --- a/Lang/PureBasic/Tokenize-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Tokenize-a-string/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Vampire-number b/Lang/PureBasic/Vampire-number new file mode 120000 index 0000000000..955c1b3b51 --- /dev/null +++ b/Lang/PureBasic/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Van-der-Corput-sequence b/Lang/PureBasic/Van-der-Corput-sequence new file mode 120000 index 0000000000..cf8f01e9a3 --- /dev/null +++ b/Lang/PureBasic/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Zeckendorf-number-representation b/Lang/PureBasic/Zeckendorf-number-representation new file mode 120000 index 0000000000..e9048f2616 --- /dev/null +++ b/Lang/PureBasic/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/PureBasic \ No newline at end of file diff --git a/Lang/Python/99-Bottles-of-Beer b/Lang/Python/99-Bottles-of-Beer deleted file mode 120000 index 7f8b6fa2de..0000000000 --- a/Lang/Python/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Python \ No newline at end of file diff --git a/Lang/Python/Canny-edge-detector b/Lang/Python/Canny-edge-detector new file mode 120000 index 0000000000..3bc1b8c2b3 --- /dev/null +++ b/Lang/Python/Canny-edge-detector @@ -0,0 +1 @@ +../../Task/Canny-edge-detector/Python \ No newline at end of file diff --git a/Lang/Python/Character-matching b/Lang/Python/Character-matching deleted file mode 120000 index e05232ed0b..0000000000 --- a/Lang/Python/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Python \ No newline at end of file diff --git a/Lang/Python/Color-quantization b/Lang/Python/Color-quantization new file mode 120000 index 0000000000..b6bc8ee535 --- /dev/null +++ b/Lang/Python/Color-quantization @@ -0,0 +1 @@ +../../Task/Color-quantization/Python \ No newline at end of file diff --git a/Lang/Python/File-IO b/Lang/Python/File-IO deleted file mode 120000 index 5e68fa1bf3..0000000000 --- a/Lang/Python/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Python \ No newline at end of file diff --git a/Lang/Python/GUI-Maximum-window-dimensions b/Lang/Python/GUI-Maximum-window-dimensions new file mode 120000 index 0000000000..fc34ab901f --- /dev/null +++ b/Lang/Python/GUI-Maximum-window-dimensions @@ -0,0 +1 @@ +../../Task/GUI-Maximum-window-dimensions/Python \ No newline at end of file diff --git a/Lang/Python/GUI-enabling-disabling-of-controls b/Lang/Python/GUI-enabling-disabling-of-controls new file mode 120000 index 0000000000..ccd2687a38 --- /dev/null +++ b/Lang/Python/GUI-enabling-disabling-of-controls @@ -0,0 +1 @@ +../../Task/GUI-enabling-disabling-of-controls/Python \ No newline at end of file diff --git a/Lang/Python/Galton-box-animation b/Lang/Python/Galton-box-animation new file mode 120000 index 0000000000..239a1abe4c --- /dev/null +++ b/Lang/Python/Galton-box-animation @@ -0,0 +1 @@ +../../Task/Galton-box-animation/Python \ No newline at end of file diff --git a/Lang/Python/Image-convolution b/Lang/Python/Image-convolution new file mode 120000 index 0000000000..8aa9d5fff3 --- /dev/null +++ b/Lang/Python/Image-convolution @@ -0,0 +1 @@ +../../Task/Image-convolution/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/Mutex b/Lang/Python/Mutex deleted file mode 120000 index 70d0a13dac..0000000000 --- a/Lang/Python/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Python \ No newline at end of file diff --git a/Lang/Python/Rosetta-Code-Count-examples b/Lang/Python/Rosetta-Code-Count-examples deleted file mode 120000 index 96ad5ae313..0000000000 --- a/Lang/Python/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Python \ No newline at end of file diff --git a/Lang/Python/Rosetta-Code-Fix-code-tags b/Lang/Python/Rosetta-Code-Fix-code-tags deleted file mode 120000 index f942dbff1e..0000000000 --- a/Lang/Python/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/Python \ No newline at end of file diff --git a/Lang/Python/Rosetta-Code-Rank-languages-by-popularity b/Lang/Python/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 1b575573fe..0000000000 --- a/Lang/Python/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Python \ No newline at end of file diff --git a/Lang/Python/Solve-a-Holy-Knights-tour b/Lang/Python/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..b2c632abe6 --- /dev/null +++ b/Lang/Python/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Python \ No newline at end of file diff --git a/Lang/Python/Solve-a-Hopido-puzzle b/Lang/Python/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..0af3bdf546 --- /dev/null +++ b/Lang/Python/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/Python \ No newline at end of file diff --git a/Lang/Python/Solve-a-Numbrix-puzzle b/Lang/Python/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..d31f43a6c5 --- /dev/null +++ b/Lang/Python/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Python \ No newline at end of file diff --git a/Lang/Python/Standard-deviation b/Lang/Python/Standard-deviation deleted file mode 120000 index 468a855a6b..0000000000 --- a/Lang/Python/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Python \ No newline at end of file diff --git a/Lang/Python/Word-wrap b/Lang/Python/Word-wrap new file mode 120000 index 0000000000..cd4f5ce1db --- /dev/null +++ b/Lang/Python/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Python \ No newline at end of file diff --git a/Lang/Q/Cholesky-decomposition b/Lang/Q/Cholesky-decomposition new file mode 120000 index 0000000000..83fd91438f --- /dev/null +++ b/Lang/Q/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Q \ No newline at end of file diff --git a/Lang/Q/Pascals-triangle b/Lang/Q/Pascals-triangle new file mode 120000 index 0000000000..39849bd532 --- /dev/null +++ b/Lang/Q/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Q \ No newline at end of file diff --git a/Lang/R/Abundant,-deficient-and-perfect-number-classifications b/Lang/R/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..1634c742fd --- /dev/null +++ b/Lang/R/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/R \ No newline at end of file diff --git a/Lang/R/Bernoulli-numbers b/Lang/R/Bernoulli-numbers new file mode 120000 index 0000000000..c87a14d735 --- /dev/null +++ b/Lang/R/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/R \ No newline at end of file diff --git a/Lang/R/Bitmap-Flood-fill b/Lang/R/Bitmap-Flood-fill new file mode 120000 index 0000000000..fa0003e965 --- /dev/null +++ b/Lang/R/Bitmap-Flood-fill @@ -0,0 +1 @@ +../../Task/Bitmap-Flood-fill/R \ No newline at end of file diff --git a/Lang/R/Brownian-tree b/Lang/R/Brownian-tree new file mode 120000 index 0000000000..c0f5231d79 --- /dev/null +++ b/Lang/R/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/R \ No newline at end of file diff --git a/Lang/R/Conditional-structures b/Lang/R/Conditional-structures deleted file mode 120000 index 093bde197a..0000000000 --- a/Lang/R/Conditional-structures +++ /dev/null @@ -1 +0,0 @@ -../../Task/Conditional-structures/R \ No newline at end of file diff --git a/Lang/R/Fibonacci-word-fractal b/Lang/R/Fibonacci-word-fractal new file mode 120000 index 0000000000..e5b8c4c14c --- /dev/null +++ b/Lang/R/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/R \ No newline at end of file diff --git a/Lang/R/File-IO b/Lang/R/File-IO deleted file mode 120000 index cdd069101e..0000000000 --- a/Lang/R/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/R \ No newline at end of file diff --git a/Lang/R/Fractal-tree b/Lang/R/Fractal-tree new file mode 120000 index 0000000000..eaf5d9bede --- /dev/null +++ b/Lang/R/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/R \ No newline at end of file diff --git a/Lang/R/Rosetta-Code-Count-examples b/Lang/R/Rosetta-Code-Count-examples deleted file mode 120000 index d6d6b87161..0000000000 --- a/Lang/R/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/R \ No newline at end of file diff --git a/Lang/R/Rosetta-Code-Find-unimplemented-tasks b/Lang/R/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index 712b1b6e80..0000000000 --- a/Lang/R/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/R \ No newline at end of file diff --git a/Lang/R/Rosetta-Code-Fix-code-tags b/Lang/R/Rosetta-Code-Fix-code-tags deleted file mode 120000 index d83d287f10..0000000000 --- a/Lang/R/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/R \ No newline at end of file diff --git a/Lang/R/Rosetta-Code-Rank-languages-by-popularity b/Lang/R/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 7477d0e199..0000000000 --- a/Lang/R/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/R \ No newline at end of file diff --git a/Lang/R/Sierpinski-carpet b/Lang/R/Sierpinski-carpet new file mode 120000 index 0000000000..75614206d4 --- /dev/null +++ b/Lang/R/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/R \ No newline at end of file diff --git a/Lang/R/Sierpinski-triangle-Graphical b/Lang/R/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..9da311ff39 --- /dev/null +++ b/Lang/R/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/R \ No newline at end of file diff --git a/Lang/R/Standard-deviation b/Lang/R/Standard-deviation deleted file mode 120000 index 791f5b6130..0000000000 --- a/Lang/R/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/R \ No newline at end of file diff --git a/Lang/R/Stern-Brocot-sequence b/Lang/R/Stern-Brocot-sequence new file mode 120000 index 0000000000..5cae64ae51 --- /dev/null +++ b/Lang/R/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/R \ No newline at end of file diff --git a/Lang/R/Ulam-spiral--for-primes- b/Lang/R/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..8e1dbbfa24 --- /dev/null +++ b/Lang/R/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/R \ No newline at end of file diff --git a/Lang/R/Voronoi-diagram b/Lang/R/Voronoi-diagram new file mode 120000 index 0000000000..29ca927864 --- /dev/null +++ b/Lang/R/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/R \ No newline at end of file diff --git a/Lang/REALbasic/99-Bottles-of-Beer b/Lang/REALbasic/99-Bottles-of-Beer deleted file mode 120000 index 9b93d03776..0000000000 --- a/Lang/REALbasic/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/REALbasic \ No newline at end of file diff --git a/Lang/REALbasic/File-IO b/Lang/REALbasic/File-IO deleted file mode 120000 index 3b6884bf31..0000000000 --- a/Lang/REALbasic/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/REALbasic \ No newline at end of file diff --git a/Lang/REALbasic/FizzBuzz b/Lang/REALbasic/FizzBuzz deleted file mode 120000 index 49ed3cf68e..0000000000 --- a/Lang/REALbasic/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/REALbasic \ No newline at end of file diff --git a/Lang/REALbasic/Forest-fire b/Lang/REALbasic/Forest-fire deleted file mode 120000 index df5171cf6f..0000000000 --- a/Lang/REALbasic/Forest-fire +++ /dev/null @@ -1 +0,0 @@ -../../Task/Forest-fire/REALbasic \ No newline at end of file diff --git a/Lang/REALbasic/LZW-compression b/Lang/REALbasic/LZW-compression new file mode 120000 index 0000000000..cf4f163040 --- /dev/null +++ b/Lang/REALbasic/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/REALbasic \ No newline at end of file diff --git a/Lang/REBOL/Calendar b/Lang/REBOL/Calendar new file mode 120000 index 0000000000..f396941538 --- /dev/null +++ b/Lang/REBOL/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/REBOL \ No newline at end of file diff --git a/Lang/REBOL/File-IO b/Lang/REBOL/File-IO deleted file mode 120000 index 91195054f9..0000000000 --- a/Lang/REBOL/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/REBOL \ No newline at end of file diff --git a/Lang/REXX/Calendar---for-real-programmers b/Lang/REXX/Calendar---for-real-programmers deleted file mode 120000 index 2c110329c1..0000000000 --- a/Lang/REXX/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/REXX \ No newline at end of file diff --git a/Lang/REXX/Character-matching b/Lang/REXX/Character-matching deleted file mode 120000 index 5803a04a0f..0000000000 --- a/Lang/REXX/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/REXX \ No newline at end of file diff --git a/Lang/REXX/File-IO b/Lang/REXX/File-IO deleted file mode 120000 index 3903999609..0000000000 --- a/Lang/REXX/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/REXX \ No newline at end of file diff --git a/Lang/REXX/Hello-world-Web-server b/Lang/REXX/Hello-world-Web-server new file mode 120000 index 0000000000..8add562a4e --- /dev/null +++ b/Lang/REXX/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/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/Multiplicative-order b/Lang/REXX/Multiplicative-order new file mode 120000 index 0000000000..6aac4e0064 --- /dev/null +++ b/Lang/REXX/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/REXX \ No newline at end of file diff --git a/Lang/REXX/Operator-precedence b/Lang/REXX/Operator-precedence deleted file mode 120000 index 91c8a67272..0000000000 --- a/Lang/REXX/Operator-precedence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Operator-precedence/REXX \ No newline at end of file diff --git a/Lang/REXX/Polynomial-regression b/Lang/REXX/Polynomial-regression new file mode 120000 index 0000000000..d3474e08a4 --- /dev/null +++ b/Lang/REXX/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/REXX \ No newline at end of file diff --git a/Lang/REXX/Rosetta-Code-Fix-code-tags b/Lang/REXX/Rosetta-Code-Fix-code-tags deleted file mode 120000 index e17cd45332..0000000000 --- a/Lang/REXX/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/REXX \ No newline at end of file diff --git a/Lang/REXX/Rosetta-Code-Rank-languages-by-popularity b/Lang/REXX/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 0a03be6588..0000000000 --- a/Lang/REXX/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/REXX \ No newline at end of file diff --git a/Lang/REXX/Stack-traces b/Lang/REXX/Stack-traces new file mode 120000 index 0000000000..ca4b2b4c5c --- /dev/null +++ b/Lang/REXX/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/REXX \ No newline at end of file diff --git a/Lang/REXX/Standard-deviation b/Lang/REXX/Standard-deviation deleted file mode 120000 index 40eb7a6df1..0000000000 --- a/Lang/REXX/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/REXX \ No newline at end of file diff --git a/Lang/Racket/Calendar---for-real-programmers b/Lang/Racket/Calendar---for-real-programmers deleted file mode 120000 index 652953a553..0000000000 --- a/Lang/Racket/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/Racket \ No newline at end of file diff --git a/Lang/Racket/Character-matching b/Lang/Racket/Character-matching deleted file mode 120000 index 6aa960b01e..0000000000 --- a/Lang/Racket/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Racket \ No newline at end of file diff --git a/Lang/Racket/File-IO b/Lang/Racket/File-IO deleted file mode 120000 index 36bf4089f3..0000000000 --- a/Lang/Racket/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Racket \ No newline at end of file diff --git a/Lang/Racket/Metaprogramming b/Lang/Racket/Metaprogramming new file mode 120000 index 0000000000..7518773cb5 --- /dev/null +++ b/Lang/Racket/Metaprogramming @@ -0,0 +1 @@ +../../Task/Metaprogramming/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/Mutex b/Lang/Racket/Mutex deleted file mode 120000 index 61c87915d1..0000000000 --- a/Lang/Racket/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Racket \ No newline at end of file diff --git a/Lang/Racket/Rosetta-Code-Count-examples b/Lang/Racket/Rosetta-Code-Count-examples deleted file mode 120000 index b9d3365fda..0000000000 --- a/Lang/Racket/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Racket \ No newline at end of file diff --git a/Lang/Racket/Rosetta-Code-Find-unimplemented-tasks b/Lang/Racket/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index 82f76d4f9e..0000000000 --- a/Lang/Racket/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/Racket \ No newline at end of file diff --git a/Lang/Racket/Rosetta-Code-Fix-code-tags b/Lang/Racket/Rosetta-Code-Fix-code-tags deleted file mode 120000 index b44514c3fb..0000000000 --- a/Lang/Racket/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/Racket \ No newline at end of file diff --git a/Lang/Racket/Rosetta-Code-Rank-languages-by-popularity b/Lang/Racket/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index aeb304d9d7..0000000000 --- a/Lang/Racket/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Racket \ No newline at end of file diff --git a/Lang/Racket/Standard-deviation b/Lang/Racket/Standard-deviation deleted file mode 120000 index b548b53cd2..0000000000 --- a/Lang/Racket/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Racket \ No newline at end of file diff --git a/Lang/RapidQ/File-IO b/Lang/RapidQ/File-IO deleted file mode 120000 index 9051de57d7..0000000000 --- a/Lang/RapidQ/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/RapidQ \ No newline at end of file diff --git a/Lang/Raven/File-IO b/Lang/Raven/File-IO deleted file mode 120000 index 97a4398831..0000000000 --- a/Lang/Raven/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Raven \ No newline at end of file diff --git a/Lang/Red/Hello-world-Text b/Lang/Red/Hello-world-Text new file mode 120000 index 0000000000..47b5215ee5 --- /dev/null +++ b/Lang/Red/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Red \ No newline at end of file diff --git a/Lang/Retro/Character-matching b/Lang/Retro/Character-matching deleted file mode 120000 index e2512dbd24..0000000000 --- a/Lang/Retro/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Retro \ No newline at end of file diff --git a/Lang/Retro/File-IO b/Lang/Retro/File-IO deleted file mode 120000 index b4466fa9c1..0000000000 --- a/Lang/Retro/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Retro \ No newline at end of file diff --git a/Lang/Revolution/Anagrams b/Lang/Revolution/Anagrams deleted file mode 120000 index 0601ef93de..0000000000 --- a/Lang/Revolution/Anagrams +++ /dev/null @@ -1 +0,0 @@ -../../Task/Anagrams/Revolution \ No newline at end of file diff --git a/Lang/Ring/Collections b/Lang/Ring/Collections new file mode 120000 index 0000000000..e08e007d17 --- /dev/null +++ b/Lang/Ring/Collections @@ -0,0 +1 @@ +../../Task/Collections/Ring \ No newline at end of file diff --git a/Lang/Ring/Count-the-coins b/Lang/Ring/Count-the-coins new file mode 120000 index 0000000000..f766bbe2c2 --- /dev/null +++ b/Lang/Ring/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Ring \ No newline at end of file diff --git a/Lang/Ring/Entropy b/Lang/Ring/Entropy new file mode 120000 index 0000000000..1b7620c93d --- /dev/null +++ b/Lang/Ring/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Ring \ No newline at end of file diff --git a/Lang/Ring/Execute-HQ9+ b/Lang/Ring/Execute-HQ9+ new file mode 120000 index 0000000000..2a8ac1d9f1 --- /dev/null +++ b/Lang/Ring/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/Ring \ No newline at end of file diff --git a/Lang/Ring/File-modification-time b/Lang/Ring/File-modification-time new file mode 120000 index 0000000000..137acb1c58 --- /dev/null +++ b/Lang/Ring/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/Ring \ No newline at end of file diff --git a/Lang/Ring/Find-common-directory-path b/Lang/Ring/Find-common-directory-path new file mode 120000 index 0000000000..8165accd10 --- /dev/null +++ b/Lang/Ring/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Ring \ No newline at end of file diff --git a/Lang/Ring/Heronian-triangles b/Lang/Ring/Heronian-triangles deleted file mode 120000 index 1c13dd5c7a..0000000000 --- a/Lang/Ring/Heronian-triangles +++ /dev/null @@ -1 +0,0 @@ -../../Task/Heronian-triangles/Ring \ No newline at end of file diff --git a/Lang/Ring/Josephus-problem b/Lang/Ring/Josephus-problem new file mode 120000 index 0000000000..bad6f35bc2 --- /dev/null +++ b/Lang/Ring/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Ring \ No newline at end of file diff --git a/Lang/Ring/Keyboard-macros b/Lang/Ring/Keyboard-macros new file mode 120000 index 0000000000..ca5ebb3c64 --- /dev/null +++ b/Lang/Ring/Keyboard-macros @@ -0,0 +1 @@ +../../Task/Keyboard-macros/Ring \ No newline at end of file diff --git a/Lang/Ring/Literals-Integer b/Lang/Ring/Literals-Integer new file mode 120000 index 0000000000..415c2360ce --- /dev/null +++ b/Lang/Ring/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Ring \ No newline at end of file diff --git a/Lang/Ring/Map-range b/Lang/Ring/Map-range new file mode 120000 index 0000000000..9ff1b5b02f --- /dev/null +++ b/Lang/Ring/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Ring \ No newline at end of file diff --git a/Lang/Ring/Monty-Hall-problem b/Lang/Ring/Monty-Hall-problem new file mode 120000 index 0000000000..47ebc35b89 --- /dev/null +++ b/Lang/Ring/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Ring \ No newline at end of file diff --git a/Lang/Ring/Non-decimal-radices-Output b/Lang/Ring/Non-decimal-radices-Output new file mode 120000 index 0000000000..9bcbf2aea6 --- /dev/null +++ b/Lang/Ring/Non-decimal-radices-Output @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Output/Ring \ No newline at end of file diff --git a/Lang/Ring/Rate-counter b/Lang/Ring/Rate-counter new file mode 120000 index 0000000000..7409099ede --- /dev/null +++ b/Lang/Ring/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/Ring \ No newline at end of file diff --git a/Lang/Ring/Sierpinski-triangle b/Lang/Ring/Sierpinski-triangle new file mode 120000 index 0000000000..be95a4859a --- /dev/null +++ b/Lang/Ring/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Ring \ No newline at end of file diff --git a/Lang/Ring/Sort-using-a-custom-comparator b/Lang/Ring/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..5b67145d84 --- /dev/null +++ b/Lang/Ring/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Ring \ No newline at end of file diff --git a/Lang/Ring/Start-from-a-main-routine b/Lang/Ring/Start-from-a-main-routine new file mode 120000 index 0000000000..b413bc3521 --- /dev/null +++ b/Lang/Ring/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Ring \ No newline at end of file diff --git a/Lang/Ring/Topic-variable b/Lang/Ring/Topic-variable new file mode 120000 index 0000000000..c50d37a367 --- /dev/null +++ b/Lang/Ring/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Ring \ No newline at end of file diff --git a/Lang/Ring/Unicode-variable-names b/Lang/Ring/Unicode-variable-names new file mode 120000 index 0000000000..095ad1c52a --- /dev/null +++ b/Lang/Ring/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Ring \ No newline at end of file diff --git a/Lang/Ring/Vector-products b/Lang/Ring/Vector-products new file mode 120000 index 0000000000..678e082424 --- /dev/null +++ b/Lang/Ring/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Ring \ No newline at end of file diff --git a/Lang/Ring/Verify-distribution-uniformity-Naive b/Lang/Ring/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..80fd9cc44e --- /dev/null +++ b/Lang/Ring/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Ring \ No newline at end of file diff --git a/Lang/Ring/Video-display-modes b/Lang/Ring/Video-display-modes new file mode 120000 index 0000000000..a2e9645f27 --- /dev/null +++ b/Lang/Ring/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/Ring \ No newline at end of file diff --git a/Lang/Ring/Walk-a-directory-Non-recursively b/Lang/Ring/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..9a02915cee --- /dev/null +++ b/Lang/Ring/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Ring \ No newline at end of file diff --git a/Lang/Ruby/Calendar---for-real-programmers b/Lang/Ruby/Calendar---for-real-programmers deleted file mode 120000 index 15df2b5f1b..0000000000 --- a/Lang/Ruby/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Character-matching b/Lang/Ruby/Character-matching deleted file mode 120000 index 34ddb8d8a7..0000000000 --- a/Lang/Ruby/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Ruby \ No newline at end of file diff --git a/Lang/Ruby/File-IO b/Lang/Ruby/File-IO deleted file mode 120000 index cbe2085f9f..0000000000 --- a/Lang/Ruby/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Hello-world-Newbie b/Lang/Ruby/Hello-world-Newbie new file mode 120000 index 0000000000..00534d075f --- /dev/null +++ b/Lang/Ruby/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Knapsack-problem-Bounded b/Lang/Ruby/Knapsack-problem-Bounded new file mode 120000 index 0000000000..216ddbed87 --- /dev/null +++ b/Lang/Ruby/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Metered-concurrency b/Lang/Ruby/Metered-concurrency new file mode 120000 index 0000000000..4851240f63 --- /dev/null +++ b/Lang/Ruby/Metered-concurrency @@ -0,0 +1 @@ +../../Task/Metered-concurrency/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Metronome b/Lang/Ruby/Metronome new file mode 120000 index 0000000000..c26a5515d6 --- /dev/null +++ b/Lang/Ruby/Metronome @@ -0,0 +1 @@ +../../Task/Metronome/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/Mutex b/Lang/Ruby/Mutex deleted file mode 120000 index 1de5f8656e..0000000000 --- a/Lang/Ruby/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Pig-the-dice-game-Player b/Lang/Ruby/Pig-the-dice-game-Player new file mode 120000 index 0000000000..dfd543f915 --- /dev/null +++ b/Lang/Ruby/Pig-the-dice-game-Player @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game-Player/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Rosetta-Code-Count-examples b/Lang/Ruby/Rosetta-Code-Count-examples deleted file mode 120000 index 642419c6b7..0000000000 --- a/Lang/Ruby/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Rosetta-Code-Find-unimplemented-tasks b/Lang/Ruby/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index 88d0272e54..0000000000 --- a/Lang/Ruby/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Rosetta-Code-Fix-code-tags b/Lang/Ruby/Rosetta-Code-Fix-code-tags deleted file mode 120000 index 6864bf1ad2..0000000000 --- a/Lang/Ruby/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Rosetta-Code-Rank-languages-by-popularity b/Lang/Ruby/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 500910a8f3..0000000000 --- a/Lang/Ruby/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Scope-Function-names-and-labels b/Lang/Ruby/Scope-Function-names-and-labels new file mode 120000 index 0000000000..f57ffd6c81 --- /dev/null +++ b/Lang/Ruby/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Standard-deviation b/Lang/Ruby/Standard-deviation deleted file mode 120000 index b5b555580b..0000000000 --- a/Lang/Ruby/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Use-another-language-to-call-a-function b/Lang/Ruby/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..5663718ee0 --- /dev/null +++ b/Lang/Ruby/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Ruby \ No newline at end of file diff --git a/Lang/Run-BASIC/99-Bottles-of-Beer b/Lang/Run-BASIC/99-Bottles-of-Beer deleted file mode 120000 index cf56317fda..0000000000 --- a/Lang/Run-BASIC/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Averages-Simple-moving-average b/Lang/Run-BASIC/Averages-Simple-moving-average new file mode 120000 index 0000000000..2ea230532a --- /dev/null +++ b/Lang/Run-BASIC/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Calendar b/Lang/Run-BASIC/Calendar deleted file mode 120000 index 378fbefc0f..0000000000 --- a/Lang/Run-BASIC/Calendar +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Character-matching b/Lang/Run-BASIC/Character-matching deleted file mode 120000 index cfdca3503b..0000000000 --- a/Lang/Run-BASIC/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Colour-bars-Display b/Lang/Run-BASIC/Colour-bars-Display deleted file mode 120000 index 8597b7a389..0000000000 --- a/Lang/Run-BASIC/Colour-bars-Display +++ /dev/null @@ -1 +0,0 @@ -../../Task/Colour-bars-Display/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Detect-division-by-zero b/Lang/Run-BASIC/Detect-division-by-zero deleted file mode 120000 index 8822b84d8c..0000000000 --- a/Lang/Run-BASIC/Detect-division-by-zero +++ /dev/null @@ -1 +0,0 @@ -../../Task/Detect-division-by-zero/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Draw-a-sphere b/Lang/Run-BASIC/Draw-a-sphere deleted file mode 120000 index d5f8d62c21..0000000000 --- a/Lang/Run-BASIC/Draw-a-sphere +++ /dev/null @@ -1 +0,0 @@ -../../Task/Draw-a-sphere/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Euler-method b/Lang/Run-BASIC/Euler-method deleted file mode 120000 index 6e89af9943..0000000000 --- a/Lang/Run-BASIC/Euler-method +++ /dev/null @@ -1 +0,0 @@ -../../Task/Euler-method/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/File-IO b/Lang/Run-BASIC/File-IO deleted file mode 120000 index 6e45dc07fd..0000000000 --- a/Lang/Run-BASIC/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/FizzBuzz b/Lang/Run-BASIC/FizzBuzz deleted file mode 120000 index 42435f2d57..0000000000 --- a/Lang/Run-BASIC/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Forest-fire b/Lang/Run-BASIC/Forest-fire deleted file mode 120000 index f76dbb908c..0000000000 --- a/Lang/Run-BASIC/Forest-fire +++ /dev/null @@ -1 +0,0 @@ -../../Task/Forest-fire/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Generate-lower-case-ASCII-alphabet b/Lang/Run-BASIC/Generate-lower-case-ASCII-alphabet deleted file mode 120000 index 1bbf772a9e..0000000000 --- a/Lang/Run-BASIC/Generate-lower-case-ASCII-alphabet +++ /dev/null @@ -1 +0,0 @@ -../../Task/Generate-lower-case-ASCII-alphabet/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/HTTPS-Client-authenticated b/Lang/Run-BASIC/HTTPS-Client-authenticated deleted file mode 120000 index 5626762629..0000000000 --- a/Lang/Run-BASIC/HTTPS-Client-authenticated +++ /dev/null @@ -1 +0,0 @@ -../../Task/HTTPS-Client-authenticated/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Hailstone-sequence b/Lang/Run-BASIC/Hailstone-sequence deleted file mode 120000 index 5a75245ea8..0000000000 --- a/Lang/Run-BASIC/Hailstone-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hailstone-sequence/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Long-multiplication b/Lang/Run-BASIC/Long-multiplication deleted file mode 120000 index 2985d7ba61..0000000000 --- a/Lang/Run-BASIC/Long-multiplication +++ /dev/null @@ -1 +0,0 @@ -../../Task/Long-multiplication/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Loops-Continue b/Lang/Run-BASIC/Loops-Continue deleted file mode 120000 index a1fabfaed1..0000000000 --- a/Lang/Run-BASIC/Loops-Continue +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Continue/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Loops-For b/Lang/Run-BASIC/Loops-For deleted file mode 120000 index c7f7e0840a..0000000000 --- a/Lang/Run-BASIC/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Loops-Foreach b/Lang/Run-BASIC/Loops-Foreach deleted file mode 120000 index e239698800..0000000000 --- a/Lang/Run-BASIC/Loops-Foreach +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Foreach/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Middle-three-digits b/Lang/Run-BASIC/Middle-three-digits deleted file mode 120000 index 213f96d558..0000000000 --- a/Lang/Run-BASIC/Middle-three-digits +++ /dev/null @@ -1 +0,0 @@ -../../Task/Middle-three-digits/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/Rosetta-Code-Count-examples b/Lang/Run-BASIC/Rosetta-Code-Count-examples deleted file mode 120000 index 7d3f78c25d..0000000000 --- a/Lang/Run-BASIC/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Rosetta-Code-Find-unimplemented-tasks b/Lang/Run-BASIC/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index 9a5cded71d..0000000000 --- a/Lang/Run-BASIC/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Rosetta-Code-Rank-languages-by-popularity b/Lang/Run-BASIC/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index f635ee846d..0000000000 --- a/Lang/Run-BASIC/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sierpinski-carpet b/Lang/Run-BASIC/Sierpinski-carpet deleted file mode 120000 index 81deaccd00..0000000000 --- a/Lang/Run-BASIC/Sierpinski-carpet +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sierpinski-carpet/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Standard-deviation b/Lang/Run-BASIC/Standard-deviation deleted file mode 120000 index 9d615fc9cc..0000000000 --- a/Lang/Run-BASIC/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/String-case b/Lang/Run-BASIC/String-case deleted file mode 120000 index e649a56195..0000000000 --- a/Lang/Run-BASIC/String-case +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-case/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sum-digits-of-an-integer b/Lang/Run-BASIC/Sum-digits-of-an-integer deleted file mode 120000 index 41c990fac8..0000000000 --- a/Lang/Run-BASIC/Sum-digits-of-an-integer +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sum-digits-of-an-integer/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Terminal-control-Inverse-video b/Lang/Run-BASIC/Terminal-control-Inverse-video deleted file mode 120000 index 92c96c0f48..0000000000 --- a/Lang/Run-BASIC/Terminal-control-Inverse-video +++ /dev/null @@ -1 +0,0 @@ -../../Task/Terminal-control-Inverse-video/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Tokenize-a-string b/Lang/Run-BASIC/Tokenize-a-string deleted file mode 120000 index 8f73f67ff1..0000000000 --- a/Lang/Run-BASIC/Tokenize-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Tokenize-a-string/Run-BASIC \ No newline at end of file diff --git a/Lang/Rust/00DESCRIPTION b/Lang/Rust/00DESCRIPTION index e0a3dbfff0..3c0e2daca7 100644 --- a/Lang/Rust/00DESCRIPTION +++ b/Lang/Rust/00DESCRIPTION @@ -1,3 +1,4 @@ +{{implementation|Rust}} {{language |site=http://www.rust-lang.org |exec=machine diff --git a/Lang/Rust/24-game-Solve b/Lang/Rust/24-game-Solve new file mode 120000 index 0000000000..46e91c7e1a --- /dev/null +++ b/Lang/Rust/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Rust \ No newline at end of file diff --git a/Lang/Rust/Abundant,-deficient-and-perfect-number-classifications b/Lang/Rust/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..26736703e5 --- /dev/null +++ b/Lang/Rust/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Rust \ No newline at end of file diff --git a/Lang/Rust/Animation b/Lang/Rust/Animation new file mode 120000 index 0000000000..3a15d04ce7 --- /dev/null +++ b/Lang/Rust/Animation @@ -0,0 +1 @@ +../../Task/Animation/Rust \ No newline at end of file diff --git a/Lang/Rust/Arbitrary-precision-integers--included- b/Lang/Rust/Arbitrary-precision-integers--included- new file mode 120000 index 0000000000..25cae8d970 --- /dev/null +++ b/Lang/Rust/Arbitrary-precision-integers--included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers--included-/Rust \ No newline at end of file diff --git a/Lang/Rust/Bitcoin-address-validation b/Lang/Rust/Bitcoin-address-validation new file mode 120000 index 0000000000..a4124109b8 --- /dev/null +++ b/Lang/Rust/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Rust \ No newline at end of file diff --git a/Lang/Rust/Call-a-function-in-a-shared-library b/Lang/Rust/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..d07fbe31d5 --- /dev/null +++ b/Lang/Rust/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/Rust \ No newline at end of file diff --git a/Lang/Rust/Catalan-numbers-Pascals-triangle b/Lang/Rust/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..f2c71d98a7 --- /dev/null +++ b/Lang/Rust/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Rust \ No newline at end of file diff --git a/Lang/Rust/Catamorphism b/Lang/Rust/Catamorphism new file mode 120000 index 0000000000..d31431b503 --- /dev/null +++ b/Lang/Rust/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Rust \ No newline at end of file diff --git a/Lang/Rust/Chinese-remainder-theorem b/Lang/Rust/Chinese-remainder-theorem new file mode 120000 index 0000000000..ffc2cd2135 --- /dev/null +++ b/Lang/Rust/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Rust \ No newline at end of file diff --git a/Lang/Rust/Cholesky-decomposition b/Lang/Rust/Cholesky-decomposition new file mode 120000 index 0000000000..53cecf4a71 --- /dev/null +++ b/Lang/Rust/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Rust \ No newline at end of file diff --git a/Lang/Rust/Classes b/Lang/Rust/Classes new file mode 120000 index 0000000000..0602857845 --- /dev/null +++ b/Lang/Rust/Classes @@ -0,0 +1 @@ +../../Task/Classes/Rust \ No newline at end of file diff --git a/Lang/Rust/Compile-time-calculation b/Lang/Rust/Compile-time-calculation new file mode 120000 index 0000000000..b64b2bc16b --- /dev/null +++ b/Lang/Rust/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/Rust \ No newline at end of file diff --git a/Lang/Rust/Conditional-structures b/Lang/Rust/Conditional-structures new file mode 120000 index 0000000000..9fb4ca592a --- /dev/null +++ b/Lang/Rust/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Rust \ No newline at end of file diff --git a/Lang/Rust/Constrained-genericity b/Lang/Rust/Constrained-genericity new file mode 120000 index 0000000000..3496ea6ec7 --- /dev/null +++ b/Lang/Rust/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/Rust \ No newline at end of file diff --git a/Lang/Rust/Count-the-coins b/Lang/Rust/Count-the-coins new file mode 120000 index 0000000000..ea68515a4a --- /dev/null +++ b/Lang/Rust/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Rust \ No newline at end of file diff --git a/Lang/Rust/Create-a-file b/Lang/Rust/Create-a-file new file mode 120000 index 0000000000..671ef7e384 --- /dev/null +++ b/Lang/Rust/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Rust \ No newline at end of file diff --git a/Lang/Rust/Create-a-two-dimensional-array-at-runtime b/Lang/Rust/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..581fca7107 --- /dev/null +++ b/Lang/Rust/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Rust \ No newline at end of file diff --git a/Lang/Rust/Create-an-HTML-table b/Lang/Rust/Create-an-HTML-table new file mode 120000 index 0000000000..b1ddd78693 --- /dev/null +++ b/Lang/Rust/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Rust \ No newline at end of file diff --git a/Lang/Rust/Create-an-object-at-a-given-address b/Lang/Rust/Create-an-object-at-a-given-address new file mode 120000 index 0000000000..3235509b25 --- /dev/null +++ b/Lang/Rust/Create-an-object-at-a-given-address @@ -0,0 +1 @@ +../../Task/Create-an-object-at-a-given-address/Rust \ No newline at end of file diff --git a/Lang/Rust/Cut-a-rectangle b/Lang/Rust/Cut-a-rectangle new file mode 120000 index 0000000000..10e4f85c5d --- /dev/null +++ b/Lang/Rust/Cut-a-rectangle @@ -0,0 +1 @@ +../../Task/Cut-a-rectangle/Rust \ No newline at end of file diff --git a/Lang/Rust/DNS-query b/Lang/Rust/DNS-query new file mode 120000 index 0000000000..f432a5fb8b --- /dev/null +++ b/Lang/Rust/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Rust \ No newline at end of file diff --git a/Lang/Rust/Deepcopy b/Lang/Rust/Deepcopy new file mode 120000 index 0000000000..a39e96415b --- /dev/null +++ b/Lang/Rust/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/Rust \ No newline at end of file diff --git a/Lang/Rust/Delete-a-file b/Lang/Rust/Delete-a-file new file mode 120000 index 0000000000..dd6df1387e --- /dev/null +++ b/Lang/Rust/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Rust \ No newline at end of file diff --git a/Lang/Rust/Determine-if-a-string-is-numeric b/Lang/Rust/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..6b17f0e6f8 --- /dev/null +++ b/Lang/Rust/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Rust \ No newline at end of file diff --git a/Lang/Rust/Draw-a-clock b/Lang/Rust/Draw-a-clock new file mode 120000 index 0000000000..e89471ba19 --- /dev/null +++ b/Lang/Rust/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Rust \ No newline at end of file diff --git a/Lang/Rust/Dutch-national-flag-problem b/Lang/Rust/Dutch-national-flag-problem new file mode 120000 index 0000000000..8e83a10942 --- /dev/null +++ b/Lang/Rust/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Rust \ No newline at end of file diff --git a/Lang/Rust/Element-wise-operations b/Lang/Rust/Element-wise-operations new file mode 120000 index 0000000000..b1cd3a9950 --- /dev/null +++ b/Lang/Rust/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Rust \ No newline at end of file diff --git a/Lang/Rust/Exponentiation-operator b/Lang/Rust/Exponentiation-operator new file mode 120000 index 0000000000..305b28ecbd --- /dev/null +++ b/Lang/Rust/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Rust \ No newline at end of file diff --git a/Lang/Rust/Extend-your-language b/Lang/Rust/Extend-your-language new file mode 120000 index 0000000000..dd3c99c3c0 --- /dev/null +++ b/Lang/Rust/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/Rust \ No newline at end of file diff --git a/Lang/Rust/Extensible-prime-generator b/Lang/Rust/Extensible-prime-generator new file mode 120000 index 0000000000..83a54643fd --- /dev/null +++ b/Lang/Rust/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Rust \ No newline at end of file diff --git a/Lang/Rust/Extreme-floating-point-values b/Lang/Rust/Extreme-floating-point-values new file mode 120000 index 0000000000..9f3515be52 --- /dev/null +++ b/Lang/Rust/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Rust \ No newline at end of file diff --git a/Lang/Rust/File-IO b/Lang/Rust/File-IO deleted file mode 120000 index bf0d436165..0000000000 --- a/Lang/Rust/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Rust \ No newline at end of file diff --git a/Lang/Rust/Flatten-a-list b/Lang/Rust/Flatten-a-list new file mode 120000 index 0000000000..f7451057cd --- /dev/null +++ b/Lang/Rust/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Rust \ No newline at end of file diff --git a/Lang/Rust/Function-composition b/Lang/Rust/Function-composition new file mode 120000 index 0000000000..70394738fb --- /dev/null +++ b/Lang/Rust/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Rust \ No newline at end of file diff --git a/Lang/Rust/Huffman-coding b/Lang/Rust/Huffman-coding new file mode 120000 index 0000000000..085ec9e0ee --- /dev/null +++ b/Lang/Rust/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Rust \ No newline at end of file diff --git a/Lang/Rust/IBAN b/Lang/Rust/IBAN new file mode 120000 index 0000000000..0e8f509dbf --- /dev/null +++ b/Lang/Rust/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Rust \ No newline at end of file diff --git a/Lang/Rust/Input-loop b/Lang/Rust/Input-loop new file mode 120000 index 0000000000..2e38305e41 --- /dev/null +++ b/Lang/Rust/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Rust \ No newline at end of file diff --git a/Lang/Rust/Least-common-multiple b/Lang/Rust/Least-common-multiple new file mode 120000 index 0000000000..f1fe1c3725 --- /dev/null +++ b/Lang/Rust/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Rust \ No newline at end of file diff --git a/Lang/Rust/Literals-Floating-point b/Lang/Rust/Literals-Floating-point new file mode 120000 index 0000000000..2104f0f850 --- /dev/null +++ b/Lang/Rust/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Rust \ No newline at end of file diff --git a/Lang/Rust/Literals-Integer b/Lang/Rust/Literals-Integer new file mode 120000 index 0000000000..1562de9d46 --- /dev/null +++ b/Lang/Rust/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Rust \ No newline at end of file diff --git a/Lang/Rust/Longest-common-subsequence b/Lang/Rust/Longest-common-subsequence new file mode 120000 index 0000000000..8bae234a6a --- /dev/null +++ b/Lang/Rust/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/Rust \ No newline at end of file diff --git a/Lang/Rust/Loops-N-plus-one-half b/Lang/Rust/Loops-N-plus-one-half new file mode 120000 index 0000000000..68d9921c81 --- /dev/null +++ b/Lang/Rust/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Rust \ No newline at end of file diff --git a/Lang/Rust/Make-directory-path b/Lang/Rust/Make-directory-path new file mode 120000 index 0000000000..32dfe91730 --- /dev/null +++ b/Lang/Rust/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Rust \ No newline at end of file diff --git a/Lang/Rust/Matrix-multiplication b/Lang/Rust/Matrix-multiplication new file mode 120000 index 0000000000..e6ace9917e --- /dev/null +++ b/Lang/Rust/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Rust \ No newline at end of file diff --git a/Lang/Rust/Matrix-transposition b/Lang/Rust/Matrix-transposition new file mode 120000 index 0000000000..75af6d02f5 --- /dev/null +++ b/Lang/Rust/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/Rust \ No newline at end of file diff --git a/Lang/Rust/Monty-Hall-problem b/Lang/Rust/Monty-Hall-problem new file mode 120000 index 0000000000..794d694d3d --- /dev/null +++ b/Lang/Rust/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Rust \ No newline at end of file diff --git a/Lang/Rust/Munching-squares b/Lang/Rust/Munching-squares new file mode 120000 index 0000000000..11a73784f1 --- /dev/null +++ b/Lang/Rust/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Rust \ No newline at end of file diff --git a/Lang/Rust/Old-lady-swallowed-a-fly b/Lang/Rust/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..e0f9d4556e --- /dev/null +++ b/Lang/Rust/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Rust \ No newline at end of file diff --git a/Lang/Rust/Pattern-matching b/Lang/Rust/Pattern-matching new file mode 120000 index 0000000000..702681852e --- /dev/null +++ b/Lang/Rust/Pattern-matching @@ -0,0 +1 @@ +../../Task/Pattern-matching/Rust \ No newline at end of file diff --git a/Lang/Rust/Perfect-numbers b/Lang/Rust/Perfect-numbers new file mode 120000 index 0000000000..0e2c24adf3 --- /dev/null +++ b/Lang/Rust/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Permutations b/Lang/Rust/Permutations new file mode 120000 index 0000000000..52b97edc63 --- /dev/null +++ b/Lang/Rust/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Rust \ No newline at end of file diff --git a/Lang/Rust/Pick-random-element b/Lang/Rust/Pick-random-element new file mode 120000 index 0000000000..0dc65d5061 --- /dev/null +++ b/Lang/Rust/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Rust \ No newline at end of file diff --git a/Lang/Rust/Ray-casting-algorithm b/Lang/Rust/Ray-casting-algorithm new file mode 120000 index 0000000000..37df4c23f6 --- /dev/null +++ b/Lang/Rust/Ray-casting-algorithm @@ -0,0 +1 @@ +../../Task/Ray-casting-algorithm/Rust \ No newline at end of file diff --git a/Lang/Rust/Runge-Kutta-method b/Lang/Rust/Runge-Kutta-method new file mode 120000 index 0000000000..f67c070a94 --- /dev/null +++ b/Lang/Rust/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Rust \ No newline at end of file diff --git a/Lang/Rust/Sleep b/Lang/Rust/Sleep new file mode 120000 index 0000000000..739be5d3f9 --- /dev/null +++ b/Lang/Rust/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Rust \ No newline at end of file diff --git a/Lang/Rust/Sort-stability b/Lang/Rust/Sort-stability new file mode 120000 index 0000000000..e03d517574 --- /dev/null +++ b/Lang/Rust/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Rust \ No newline at end of file diff --git a/Lang/Rust/Sort-using-a-custom-comparator b/Lang/Rust/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..b4a90736f4 --- /dev/null +++ b/Lang/Rust/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-algorithms-Heapsort b/Lang/Rust/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..04b85ecc34 --- /dev/null +++ b/Lang/Rust/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-algorithms-Selection-sort b/Lang/Rust/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..271c9deeb8 --- /dev/null +++ b/Lang/Rust/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Rust \ No newline at end of file diff --git a/Lang/Rust/Sparkline-in-unicode b/Lang/Rust/Sparkline-in-unicode new file mode 120000 index 0000000000..bb1d3cbf3c --- /dev/null +++ b/Lang/Rust/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Rust \ No newline at end of file diff --git a/Lang/Rust/String-append b/Lang/Rust/String-append new file mode 120000 index 0000000000..ab7bf71188 --- /dev/null +++ b/Lang/Rust/String-append @@ -0,0 +1 @@ +../../Task/String-append/Rust \ No newline at end of file diff --git a/Lang/Rust/String-length b/Lang/Rust/String-length new file mode 120000 index 0000000000..c6faf500cc --- /dev/null +++ b/Lang/Rust/String-length @@ -0,0 +1 @@ +../../Task/String-length/Rust \ No newline at end of file diff --git a/Lang/Rust/Sum-digits-of-an-integer b/Lang/Rust/Sum-digits-of-an-integer new file mode 120000 index 0000000000..6b0615510d --- /dev/null +++ b/Lang/Rust/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Rust \ No newline at end of file diff --git a/Lang/Rust/Sutherland-Hodgman-polygon-clipping b/Lang/Rust/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..a9d1dbf8cb --- /dev/null +++ b/Lang/Rust/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Rust \ No newline at end of file diff --git a/Lang/Rust/Vector-products b/Lang/Rust/Vector-products new file mode 120000 index 0000000000..781a799574 --- /dev/null +++ b/Lang/Rust/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Rust \ No newline at end of file diff --git a/Lang/S-lang/Command-line-arguments b/Lang/S-lang/Command-line-arguments new file mode 120000 index 0000000000..974f4c101f --- /dev/null +++ b/Lang/S-lang/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/S-lang \ No newline at end of file diff --git a/Lang/S-lang/Extreme-floating-point-values b/Lang/S-lang/Extreme-floating-point-values new file mode 120000 index 0000000000..5719e0d64d --- /dev/null +++ b/Lang/S-lang/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/S-lang \ No newline at end of file diff --git a/Lang/S-lang/Largest-int-from-concatenated-ints b/Lang/S-lang/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..fcbeb93ec4 --- /dev/null +++ b/Lang/S-lang/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/S-lang \ No newline at end of file diff --git a/Lang/S-lang/Middle-three-digits b/Lang/S-lang/Middle-three-digits new file mode 120000 index 0000000000..fc07d2453d --- /dev/null +++ b/Lang/S-lang/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/S-lang \ No newline at end of file diff --git a/Lang/S-lang/Null-object b/Lang/S-lang/Null-object new file mode 120000 index 0000000000..5810818fb5 --- /dev/null +++ b/Lang/S-lang/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/S-lang \ No newline at end of file diff --git a/Lang/S-lang/Pernicious-numbers b/Lang/S-lang/Pernicious-numbers new file mode 120000 index 0000000000..7e14b7bdd6 --- /dev/null +++ b/Lang/S-lang/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/S-lang \ No newline at end of file diff --git a/Lang/S-lang/Primality-by-trial-division b/Lang/S-lang/Primality-by-trial-division new file mode 120000 index 0000000000..c75d3e13a7 --- /dev/null +++ b/Lang/S-lang/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/S-lang \ No newline at end of file diff --git a/Lang/S-lang/Search-a-list b/Lang/S-lang/Search-a-list new file mode 120000 index 0000000000..04d51dc2eb --- /dev/null +++ b/Lang/S-lang/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/S-lang \ No newline at end of file diff --git a/Lang/S-lang/Sparkline-in-unicode b/Lang/S-lang/Sparkline-in-unicode new file mode 120000 index 0000000000..d3b9c8ff98 --- /dev/null +++ b/Lang/S-lang/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/S-lang \ No newline at end of file diff --git a/Lang/S-lang/Unicode-variable-names b/Lang/S-lang/Unicode-variable-names new file mode 120000 index 0000000000..b2d4f9b0d9 --- /dev/null +++ b/Lang/S-lang/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/S-lang \ No newline at end of file diff --git a/Lang/SAS/Standard-deviation b/Lang/SAS/Standard-deviation deleted file mode 120000 index be23e46c07..0000000000 --- a/Lang/SAS/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/SAS \ No newline at end of file diff --git a/Lang/SETL/Assertions b/Lang/SETL/Assertions new file mode 120000 index 0000000000..dadc1d3a21 --- /dev/null +++ b/Lang/SETL/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/SETL \ No newline at end of file diff --git a/Lang/SETL/Loops-While b/Lang/SETL/Loops-While new file mode 120000 index 0000000000..d871872d87 --- /dev/null +++ b/Lang/SETL/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/SETL \ No newline at end of file diff --git a/Lang/SNOBOL4/File-IO b/Lang/SNOBOL4/File-IO deleted file mode 120000 index b4358a349a..0000000000 --- a/Lang/SNOBOL4/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Function-prototype b/Lang/SNOBOL4/Function-prototype new file mode 120000 index 0000000000..d191906750 --- /dev/null +++ b/Lang/SNOBOL4/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNUSP/99-Bottles-of-Beer b/Lang/SNUSP/99-Bottles-of-Beer deleted file mode 120000 index 6a9767c2f6..0000000000 --- a/Lang/SNUSP/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/SNUSP \ No newline at end of file diff --git a/Lang/SNUSP/FizzBuzz b/Lang/SNUSP/FizzBuzz deleted file mode 120000 index fd33a28a02..0000000000 --- a/Lang/SNUSP/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/SNUSP \ No newline at end of file diff --git a/Lang/SPAD/Polynomial-long-division b/Lang/SPAD/Polynomial-long-division new file mode 120000 index 0000000000..3011801dad --- /dev/null +++ b/Lang/SPAD/Polynomial-long-division @@ -0,0 +1 @@ +../../Task/Polynomial-long-division/SPAD \ No newline at end of file diff --git a/Lang/SPL/00DESCRIPTION b/Lang/SPL/00DESCRIPTION new file mode 100644 index 0000000000..4b711cb2e1 --- /dev/null +++ b/Lang/SPL/00DESCRIPTION @@ -0,0 +1,20 @@ +=={{header|SPL}}== +{{language|SPL +|site=http://kibernetik.pro/spl/ +}} + +SPL (Smart Programming Language) is an easy to use programming language. SPL suits very well for everyday programming tasks and for hobbyist programming. SPL does not require hard learning or high user qualification to use. + +SPL is designed and developed by Mr.Kibernetik. + +=== Documentation === +Documentation is available [http://kibernetik.pro/spl_manual/default_en.html > here <]. + +=== SPL SDK === +SPL programs can be converted to UWP applications using [http://kibernetik.pro/spl_sdk.zip SPL SDK]. + +=== Download === +You can download SPL for Windows [https://www.microsoft.com/store/apps/9nf9tncg82p1 > here <]. + +=== Support === +SPL Support forum is available [http://kibernetik.pro > here <]. \ No newline at end of file diff --git a/Lang/SPL/9-billion-names-of-God-the-integer b/Lang/SPL/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..f304e048df --- /dev/null +++ b/Lang/SPL/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/SPL \ No newline at end of file diff --git a/Lang/SPL/A+B b/Lang/SPL/A+B new file mode 120000 index 0000000000..bc6e893221 --- /dev/null +++ b/Lang/SPL/A+B @@ -0,0 +1 @@ +../../Task/A+B/SPL \ No newline at end of file diff --git a/Lang/SPL/Arbitrary-precision-integers--included- b/Lang/SPL/Arbitrary-precision-integers--included- new file mode 120000 index 0000000000..fe6dffbfd0 --- /dev/null +++ b/Lang/SPL/Arbitrary-precision-integers--included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers--included-/SPL \ No newline at end of file diff --git a/Lang/SPL/Arrays b/Lang/SPL/Arrays new file mode 120000 index 0000000000..3196f2e285 --- /dev/null +++ b/Lang/SPL/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/SPL \ No newline at end of file diff --git a/Lang/SPL/Calendar b/Lang/SPL/Calendar new file mode 120000 index 0000000000..6dc88c346b --- /dev/null +++ b/Lang/SPL/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/SPL \ No newline at end of file diff --git a/Lang/SPL/Character-codes b/Lang/SPL/Character-codes new file mode 120000 index 0000000000..b583991004 --- /dev/null +++ b/Lang/SPL/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/SPL \ No newline at end of file diff --git a/Lang/SPL/Comments b/Lang/SPL/Comments new file mode 120000 index 0000000000..55ee5c94ea --- /dev/null +++ b/Lang/SPL/Comments @@ -0,0 +1 @@ +../../Task/Comments/SPL \ No newline at end of file diff --git a/Lang/SPL/Dragon-curve b/Lang/SPL/Dragon-curve new file mode 120000 index 0000000000..a6c565ffd5 --- /dev/null +++ b/Lang/SPL/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/SPL \ No newline at end of file diff --git a/Lang/SPL/Even-or-odd b/Lang/SPL/Even-or-odd new file mode 120000 index 0000000000..4d056944d1 --- /dev/null +++ b/Lang/SPL/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/SPL \ No newline at end of file diff --git a/Lang/SPL/Factorial b/Lang/SPL/Factorial new file mode 120000 index 0000000000..e07bfde303 --- /dev/null +++ b/Lang/SPL/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/SPL \ No newline at end of file diff --git a/Lang/SPL/Fibonacci-sequence b/Lang/SPL/Fibonacci-sequence new file mode 120000 index 0000000000..1d79d50575 --- /dev/null +++ b/Lang/SPL/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/SPL \ No newline at end of file diff --git a/Lang/SPL/Floyds-triangle b/Lang/SPL/Floyds-triangle new file mode 120000 index 0000000000..999864fd26 --- /dev/null +++ b/Lang/SPL/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/SPL \ No newline at end of file diff --git a/Lang/SPL/Function-definition b/Lang/SPL/Function-definition new file mode 120000 index 0000000000..70f2cd4db7 --- /dev/null +++ b/Lang/SPL/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/SPL \ No newline at end of file diff --git a/Lang/SPL/Generate-lower-case-ASCII-alphabet b/Lang/SPL/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..5c191f8d7f --- /dev/null +++ b/Lang/SPL/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/SPL \ No newline at end of file diff --git a/Lang/SPL/Hello-world-Text b/Lang/SPL/Hello-world-Text new file mode 120000 index 0000000000..3d35597fca --- /dev/null +++ b/Lang/SPL/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/SPL \ No newline at end of file diff --git a/Lang/SPL/Heronian-triangles b/Lang/SPL/Heronian-triangles new file mode 120000 index 0000000000..40f65f031d --- /dev/null +++ b/Lang/SPL/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/SPL \ No newline at end of file diff --git a/Lang/SPL/Include-a-file b/Lang/SPL/Include-a-file new file mode 120000 index 0000000000..1c6560847a --- /dev/null +++ b/Lang/SPL/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/SPL \ No newline at end of file diff --git a/Lang/SPL/Jump-anywhere b/Lang/SPL/Jump-anywhere new file mode 120000 index 0000000000..8bf4656671 --- /dev/null +++ b/Lang/SPL/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/SPL \ No newline at end of file diff --git a/Lang/SPL/Kaprekar-numbers b/Lang/SPL/Kaprekar-numbers new file mode 120000 index 0000000000..c4ae7998db --- /dev/null +++ b/Lang/SPL/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/SPL \ No newline at end of file diff --git a/Lang/SPL/Loops-Break b/Lang/SPL/Loops-Break new file mode 120000 index 0000000000..5a90c514a6 --- /dev/null +++ b/Lang/SPL/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/SPL \ No newline at end of file diff --git a/Lang/SPL/Loops-Continue b/Lang/SPL/Loops-Continue new file mode 120000 index 0000000000..4c28467596 --- /dev/null +++ b/Lang/SPL/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/SPL \ No newline at end of file diff --git a/Lang/SPL/Loops-Do-while b/Lang/SPL/Loops-Do-while new file mode 120000 index 0000000000..f225c8640a --- /dev/null +++ b/Lang/SPL/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/SPL \ No newline at end of file diff --git a/Lang/SPL/Loops-Downward-for b/Lang/SPL/Loops-Downward-for new file mode 120000 index 0000000000..76497fc51b --- /dev/null +++ b/Lang/SPL/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/SPL \ No newline at end of file diff --git a/Lang/SPL/Loops-For b/Lang/SPL/Loops-For new file mode 120000 index 0000000000..341f289900 --- /dev/null +++ b/Lang/SPL/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/SPL \ No newline at end of file diff --git a/Lang/SPL/Loops-For-with-a-specified-step b/Lang/SPL/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..106da3901a --- /dev/null +++ b/Lang/SPL/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/SPL \ No newline at end of file diff --git a/Lang/SPL/Loops-Infinite b/Lang/SPL/Loops-Infinite new file mode 120000 index 0000000000..32349b3030 --- /dev/null +++ b/Lang/SPL/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/SPL \ No newline at end of file diff --git a/Lang/SPL/Loops-Nested b/Lang/SPL/Loops-Nested new file mode 120000 index 0000000000..14690a87d4 --- /dev/null +++ b/Lang/SPL/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/SPL \ No newline at end of file diff --git a/Lang/SPL/Loops-While b/Lang/SPL/Loops-While new file mode 120000 index 0000000000..974fb35893 --- /dev/null +++ b/Lang/SPL/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/SPL \ No newline at end of file diff --git a/Lang/SPL/Mandelbrot-set b/Lang/SPL/Mandelbrot-set new file mode 120000 index 0000000000..66850546d1 --- /dev/null +++ b/Lang/SPL/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/SPL \ No newline at end of file diff --git a/Lang/SPL/Mutual-recursion b/Lang/SPL/Mutual-recursion new file mode 120000 index 0000000000..32ceeda943 --- /dev/null +++ b/Lang/SPL/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/SPL \ No newline at end of file diff --git a/Lang/SPL/Nth-root b/Lang/SPL/Nth-root new file mode 120000 index 0000000000..1014e2e935 --- /dev/null +++ b/Lang/SPL/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/SPL \ No newline at end of file diff --git a/Lang/SPL/Ordered-words b/Lang/SPL/Ordered-words new file mode 120000 index 0000000000..d53db8fb6a --- /dev/null +++ b/Lang/SPL/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/SPL \ No newline at end of file diff --git a/Lang/SPL/README b/Lang/SPL/README new file mode 100644 index 0000000000..32569ea999 --- /dev/null +++ b/Lang/SPL/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:SPL diff --git a/Lang/SPL/Read-a-file-line-by-line b/Lang/SPL/Read-a-file-line-by-line new file mode 120000 index 0000000000..694d933cf2 --- /dev/null +++ b/Lang/SPL/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/SPL \ No newline at end of file diff --git a/Lang/SPL/Read-a-specific-line-from-a-file b/Lang/SPL/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..20cb3f6441 --- /dev/null +++ b/Lang/SPL/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/SPL \ No newline at end of file diff --git a/Lang/SPL/Read-entire-file b/Lang/SPL/Read-entire-file new file mode 120000 index 0000000000..bf214afe35 --- /dev/null +++ b/Lang/SPL/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/SPL \ No newline at end of file diff --git a/Lang/SPL/Roman-numerals-Decode b/Lang/SPL/Roman-numerals-Decode new file mode 120000 index 0000000000..5b942a0d8d --- /dev/null +++ b/Lang/SPL/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/SPL \ No newline at end of file diff --git a/Lang/SPL/Roman-numerals-Encode b/Lang/SPL/Roman-numerals-Encode new file mode 120000 index 0000000000..883032651c --- /dev/null +++ b/Lang/SPL/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/SPL \ No newline at end of file diff --git a/Lang/SPL/String-length b/Lang/SPL/String-length new file mode 120000 index 0000000000..65dc6d9dd4 --- /dev/null +++ b/Lang/SPL/String-length @@ -0,0 +1 @@ +../../Task/String-length/SPL \ No newline at end of file diff --git a/Lang/SPL/System-time b/Lang/SPL/System-time new file mode 120000 index 0000000000..97c4a4d8fe --- /dev/null +++ b/Lang/SPL/System-time @@ -0,0 +1 @@ +../../Task/System-time/SPL \ No newline at end of file diff --git a/Lang/SPL/Terminal-control-Clear-the-screen b/Lang/SPL/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..ca30039aa4 --- /dev/null +++ b/Lang/SPL/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/SPL \ No newline at end of file diff --git a/Lang/SPL/User-input-Text b/Lang/SPL/User-input-Text new file mode 120000 index 0000000000..e1c86f2f9a --- /dev/null +++ b/Lang/SPL/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/SPL \ No newline at end of file diff --git a/Lang/SPL/Variables b/Lang/SPL/Variables new file mode 120000 index 0000000000..c49ea51ec6 --- /dev/null +++ b/Lang/SPL/Variables @@ -0,0 +1 @@ +../../Task/Variables/SPL \ No newline at end of file diff --git a/Lang/SPL/Write-float-arrays-to-a-text-file b/Lang/SPL/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..575c7a94b9 --- /dev/null +++ b/Lang/SPL/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/SPL \ No newline at end of file diff --git a/Lang/SQL/Arithmetic-Integer b/Lang/SQL/Arithmetic-Integer new file mode 120000 index 0000000000..631015c204 --- /dev/null +++ b/Lang/SQL/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/SQL \ No newline at end of file diff --git a/Lang/SQL/Averages-Mean-time-of-day b/Lang/SQL/Averages-Mean-time-of-day new file mode 120000 index 0000000000..c1e515e4ab --- /dev/null +++ b/Lang/SQL/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/SQL \ No newline at end of file diff --git a/Lang/SQL/Date-format b/Lang/SQL/Date-format new file mode 120000 index 0000000000..5b797c6976 --- /dev/null +++ b/Lang/SQL/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/SQL \ No newline at end of file diff --git a/Lang/SQL/Date-manipulation b/Lang/SQL/Date-manipulation new file mode 120000 index 0000000000..9096331568 --- /dev/null +++ b/Lang/SQL/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/SQL \ No newline at end of file diff --git a/Lang/SQL/Hello-world-Text b/Lang/SQL/Hello-world-Text new file mode 120000 index 0000000000..0f4a6581fe --- /dev/null +++ b/Lang/SQL/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/SQL \ No newline at end of file diff --git a/Lang/SQL/Hostname b/Lang/SQL/Hostname new file mode 120000 index 0000000000..4ba98afb1c --- /dev/null +++ b/Lang/SQL/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/SQL \ No newline at end of file diff --git a/Lang/SQL/Integer-comparison b/Lang/SQL/Integer-comparison new file mode 120000 index 0000000000..b1645c638f --- /dev/null +++ b/Lang/SQL/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/SQL \ No newline at end of file diff --git a/Lang/SQL/Parametrized-SQL-statement b/Lang/SQL/Parametrized-SQL-statement new file mode 120000 index 0000000000..5b0651a277 --- /dev/null +++ b/Lang/SQL/Parametrized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parametrized-SQL-statement/SQL \ No newline at end of file diff --git a/Lang/SQL/Set b/Lang/SQL/Set new file mode 120000 index 0000000000..8eacb54c87 --- /dev/null +++ b/Lang/SQL/Set @@ -0,0 +1 @@ +../../Task/Set/SQL \ No newline at end of file diff --git a/Lang/SQL/Standard-deviation b/Lang/SQL/Standard-deviation deleted file mode 120000 index acd1ea1bbd..0000000000 --- a/Lang/SQL/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/SQL \ No newline at end of file diff --git a/Lang/Scala/Casting-out-nines b/Lang/Scala/Casting-out-nines new file mode 120000 index 0000000000..ab4ab43131 --- /dev/null +++ b/Lang/Scala/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Scala \ No newline at end of file diff --git a/Lang/Scala/Character-matching b/Lang/Scala/Character-matching deleted file mode 120000 index 05767cdec2..0000000000 --- a/Lang/Scala/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Scala \ No newline at end of file diff --git a/Lang/Scala/File-IO b/Lang/Scala/File-IO deleted file mode 120000 index 644d1c03e8..0000000000 --- a/Lang/Scala/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Scala \ No newline at end of file diff --git a/Lang/Scala/Knights-tour b/Lang/Scala/Knights-tour new file mode 120000 index 0000000000..55b2da89ff --- /dev/null +++ b/Lang/Scala/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/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/Multiplication-tables b/Lang/Scala/Multiplication-tables new file mode 120000 index 0000000000..5158acb14a --- /dev/null +++ b/Lang/Scala/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Scala \ No newline at end of file diff --git a/Lang/Scala/Phrase-reversals b/Lang/Scala/Phrase-reversals new file mode 120000 index 0000000000..b24aa0eb45 --- /dev/null +++ b/Lang/Scala/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Scala \ No newline at end of file diff --git a/Lang/Scala/RSA-code b/Lang/Scala/RSA-code new file mode 120000 index 0000000000..f08fba15b2 --- /dev/null +++ b/Lang/Scala/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Scala \ No newline at end of file diff --git a/Lang/Scala/Rosetta-Code-Count-examples b/Lang/Scala/Rosetta-Code-Count-examples deleted file mode 120000 index 0afd632de1..0000000000 --- a/Lang/Scala/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Scala \ No newline at end of file diff --git a/Lang/Scala/Rosetta-Code-Rank-languages-by-popularity b/Lang/Scala/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index c2db137221..0000000000 --- a/Lang/Scala/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Scala \ No newline at end of file diff --git a/Lang/Scala/Standard-deviation b/Lang/Scala/Standard-deviation deleted file mode 120000 index f03fff484b..0000000000 --- a/Lang/Scala/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Scala \ No newline at end of file diff --git a/Lang/Scala/Van-der-Corput-sequence b/Lang/Scala/Van-der-Corput-sequence new file mode 120000 index 0000000000..342c3fe59e --- /dev/null +++ b/Lang/Scala/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Scala \ No newline at end of file diff --git a/Lang/Scheme/00DESCRIPTION b/Lang/Scheme/00DESCRIPTION index f549eef576..9c7c3e03bd 100644 --- a/Lang/Scheme/00DESCRIPTION +++ b/Lang/Scheme/00DESCRIPTION @@ -9,13 +9,30 @@ |bnf=http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-7.html#node_chap_4}} {{codepad}} {{language programming paradigm|functional}} -'''Scheme''' is a multi-[[:Category:Programming Paradigms|paradigm]] programming language. It is one of the two main dialects of [[derived from::Lisp]] and supports a number of programming paradigms but is best known for its support of [[functional programming]]. It was developed by Guy L. Steele and Gerald Jay Sussman in the 1970s. Scheme was introduced to the academic world via a series of papers now referred to as Sussman and Steele's Lambda Papers. There are two standards that define the Scheme language: the official [[IEEE]] standard, and a de facto standard called the ''Revisedn Report on the Algorithmic Language Scheme'', nearly always abbreviated R''n''RS, where ''n'' is the number of the revision. The current standard is '''R6RS''', and '''R7RS''' is in development. +'''Scheme''' is a multi-[[:Category:Programming Paradigms|paradigm]] programming language. It is one of the two main dialects of [[derived from::Lisp]] and supports a number of programming paradigms; however it is best known for its support of [[functional programming]]. It was developed by Guy L. Steele and Gerald Jay Sussman in the 1970s. Scheme was introduced to the academic world via a series of papers, now referred to as Sussman and Steele's Lambda Papers. There are two standards that define the Scheme language: the official [[IEEE]] standard, and a de facto standard called the ''Revisedn Report on the Algorithmic Language Scheme'', nearly always abbreviated R''n''RS, where ''n'' is the number of the revision. The current standard is '''R7RS''', with '''R5RS''' and, less common, '''R6RS''' still in use. Scheme's philosophy is minimalist. Scheme provides as few primitive notions as possible, and, where practical, lets everything else be provided by programming libraries. Scheme was the first dialect of Lisp to choose static (a.k.a. lexical) over dynamic variable scope. It was also one of the first programming languages to support first-class continuations. +==Running Examples== + +Some examples from this site require particular versions of Scheme, or libraries, to run. + +* R7RS programs typically begin with a line such as (import (scheme base) ...) +* R6RS programs with a line such as (import (rnrs) ...) +* R5RS programs don't require any preamble. + + +A semi-standard set of libraries for Scheme is the collection [[:Category:Scheme/SRFIs|SRFIs]] (from Scheme Requests For Implementation). These libraries provide additional functions operating on core data structures, such as SRFI-1 for lists and SRFI-13 for strings; additional data structures, such as SRFI-69 or SRFI-125 for hash tables; or additional functionality, such as SRFI-42 providing eager comprehensions. Example programs which require one or more SRFIs must be run on implementations which support that SRFI. + +Scheme does not directly support a GUI library: some examples use [[:Category:Scheme/PsTk|PsTk]]. + ==Citations== + * [[wp:Scheme_%28programming_language%29|Wikipedia:Scheme (programming language)]] +* [http://trac.sacrideo.us/wg/wiki/R7RSHomePage R7RS Scheme home page] +* [http://www.r6rs.org/ R6RS Scheme home page] +* [http://www.schemers.org/Documents/Standards/R5RS/ R5RS Scheme documentation] {{implementation|Lisp}} \ No newline at end of file diff --git a/Lang/Scheme/9-billion-names-of-God-the-integer b/Lang/Scheme/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..4c2087c7dc --- /dev/null +++ b/Lang/Scheme/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Align-columns b/Lang/Scheme/Align-columns new file mode 120000 index 0000000000..2168ff77c5 --- /dev/null +++ b/Lang/Scheme/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Amicable-pairs b/Lang/Scheme/Amicable-pairs new file mode 120000 index 0000000000..cc474aad8a --- /dev/null +++ b/Lang/Scheme/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Anagrams b/Lang/Scheme/Anagrams new file mode 120000 index 0000000000..0879bdbd6b --- /dev/null +++ b/Lang/Scheme/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Anagrams-Deranged-anagrams b/Lang/Scheme/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..9e93e3bb97 --- /dev/null +++ b/Lang/Scheme/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Arithmetic-evaluation b/Lang/Scheme/Arithmetic-evaluation new file mode 120000 index 0000000000..f251563046 --- /dev/null +++ b/Lang/Scheme/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Arithmetic-geometric-mean b/Lang/Scheme/Arithmetic-geometric-mean new file mode 120000 index 0000000000..30b1de7b87 --- /dev/null +++ b/Lang/Scheme/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Average-loop-length b/Lang/Scheme/Average-loop-length new file mode 120000 index 0000000000..3380657d18 --- /dev/null +++ b/Lang/Scheme/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Averages-Mean-angle b/Lang/Scheme/Averages-Mean-angle new file mode 120000 index 0000000000..c88ff1effe --- /dev/null +++ b/Lang/Scheme/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Averages-Mean-time-of-day b/Lang/Scheme/Averages-Mean-time-of-day new file mode 120000 index 0000000000..b57f4f0af7 --- /dev/null +++ b/Lang/Scheme/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Catamorphism b/Lang/Scheme/Catamorphism new file mode 120000 index 0000000000..0f64b7e042 --- /dev/null +++ b/Lang/Scheme/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Circles-of-given-radius-through-two-points b/Lang/Scheme/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..37529db383 --- /dev/null +++ b/Lang/Scheme/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Combinations-and-permutations b/Lang/Scheme/Combinations-and-permutations new file mode 120000 index 0000000000..fc0a34998c --- /dev/null +++ b/Lang/Scheme/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Comma-quibbling b/Lang/Scheme/Comma-quibbling new file mode 120000 index 0000000000..a837f80b25 --- /dev/null +++ b/Lang/Scheme/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Create-a-two-dimensional-array-at-runtime b/Lang/Scheme/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..9e8bacdcb8 --- /dev/null +++ b/Lang/Scheme/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Date-format b/Lang/Scheme/Date-format new file mode 120000 index 0000000000..d8c4d35b40 --- /dev/null +++ b/Lang/Scheme/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Draw-a-clock b/Lang/Scheme/Draw-a-clock new file mode 120000 index 0000000000..dea438eab5 --- /dev/null +++ b/Lang/Scheme/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Entropy b/Lang/Scheme/Entropy new file mode 120000 index 0000000000..9a336abba3 --- /dev/null +++ b/Lang/Scheme/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Evolutionary-algorithm b/Lang/Scheme/Evolutionary-algorithm new file mode 120000 index 0000000000..1c67e4fdce --- /dev/null +++ b/Lang/Scheme/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Fibonacci-n-step-number-sequences b/Lang/Scheme/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..9be0e34365 --- /dev/null +++ b/Lang/Scheme/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Fibonacci-word b/Lang/Scheme/Fibonacci-word new file mode 120000 index 0000000000..bf58117859 --- /dev/null +++ b/Lang/Scheme/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Scheme \ No newline at end of file diff --git a/Lang/Scheme/File-IO b/Lang/Scheme/File-IO deleted file mode 120000 index 7c63da792c..0000000000 --- a/Lang/Scheme/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Four-bit-adder b/Lang/Scheme/Four-bit-adder new file mode 120000 index 0000000000..53e17be9a4 --- /dev/null +++ b/Lang/Scheme/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Fractal-tree b/Lang/Scheme/Fractal-tree new file mode 120000 index 0000000000..6d5419d5f1 --- /dev/null +++ b/Lang/Scheme/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Fractran b/Lang/Scheme/Fractran new file mode 120000 index 0000000000..c1c909c28c --- /dev/null +++ b/Lang/Scheme/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Gamma-function b/Lang/Scheme/Gamma-function new file mode 120000 index 0000000000..68188578d7 --- /dev/null +++ b/Lang/Scheme/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Generate-Chess960-starting-position b/Lang/Scheme/Generate-Chess960-starting-position new file mode 120000 index 0000000000..1c9fbdca65 --- /dev/null +++ b/Lang/Scheme/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Hofstadter-Conway-$10,000-sequence b/Lang/Scheme/Hofstadter-Conway-$10,000-sequence new file mode 120000 index 0000000000..f0c6e26b9a --- /dev/null +++ b/Lang/Scheme/Hofstadter-Conway-$10,000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10,000-sequence/Scheme \ No newline at end of file diff --git a/Lang/Scheme/K-means++-clustering b/Lang/Scheme/K-means++-clustering new file mode 120000 index 0000000000..0fa6a3bcc2 --- /dev/null +++ b/Lang/Scheme/K-means++-clustering @@ -0,0 +1 @@ +../../Task/K-means++-clustering/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Left-factorials b/Lang/Scheme/Left-factorials new file mode 120000 index 0000000000..f720d23c97 --- /dev/null +++ b/Lang/Scheme/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Multifactorial b/Lang/Scheme/Multifactorial new file mode 120000 index 0000000000..8a1026125b --- /dev/null +++ b/Lang/Scheme/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Scheme \ No newline at end of file diff --git a/Lang/Scheme/N-queens-problem b/Lang/Scheme/N-queens-problem new file mode 120000 index 0000000000..982faec85b --- /dev/null +++ b/Lang/Scheme/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Natural-sorting b/Lang/Scheme/Natural-sorting new file mode 120000 index 0000000000..7c710985e2 --- /dev/null +++ b/Lang/Scheme/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Number-reversal-game b/Lang/Scheme/Number-reversal-game new file mode 120000 index 0000000000..2b71dab78c --- /dev/null +++ b/Lang/Scheme/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Standard-deviation b/Lang/Scheme/Standard-deviation deleted file mode 120000 index 914d7b76d9..0000000000 --- a/Lang/Scheme/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Strip-a-set-of-characters-from-a-string b/Lang/Scheme/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..d2345f0f40 --- /dev/null +++ b/Lang/Scheme/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sum-digits-of-an-integer b/Lang/Scheme/Sum-digits-of-an-integer new file mode 120000 index 0000000000..c6c0e2bcf3 --- /dev/null +++ b/Lang/Scheme/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Symmetric-difference b/Lang/Scheme/Symmetric-difference new file mode 120000 index 0000000000..9d53444185 --- /dev/null +++ b/Lang/Scheme/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Temperature-conversion b/Lang/Scheme/Temperature-conversion new file mode 120000 index 0000000000..0715d3a0e9 --- /dev/null +++ b/Lang/Scheme/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Test-a-function b/Lang/Scheme/Test-a-function new file mode 120000 index 0000000000..f88532688b --- /dev/null +++ b/Lang/Scheme/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Word-wrap b/Lang/Scheme/Word-wrap new file mode 120000 index 0000000000..81868d8a1f --- /dev/null +++ b/Lang/Scheme/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Scheme \ No newline at end of file diff --git a/Lang/Scilab/100-doors b/Lang/Scilab/100-doors new file mode 120000 index 0000000000..30e0bcea90 --- /dev/null +++ b/Lang/Scilab/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Animate-a-pendulum b/Lang/Scilab/Animate-a-pendulum new file mode 120000 index 0000000000..10b6aa8a99 --- /dev/null +++ b/Lang/Scilab/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Balanced-brackets b/Lang/Scilab/Balanced-brackets new file mode 120000 index 0000000000..d466baf7b0 --- /dev/null +++ b/Lang/Scilab/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Conways-Game-of-Life b/Lang/Scilab/Conways-Game-of-Life new file mode 120000 index 0000000000..6a0befda62 --- /dev/null +++ b/Lang/Scilab/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Count-the-coins b/Lang/Scilab/Count-the-coins new file mode 120000 index 0000000000..686975b3c6 --- /dev/null +++ b/Lang/Scilab/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Dragon-curve b/Lang/Scilab/Dragon-curve new file mode 120000 index 0000000000..a4f4668d34 --- /dev/null +++ b/Lang/Scilab/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Entropy b/Lang/Scilab/Entropy new file mode 120000 index 0000000000..0ca7581cf5 --- /dev/null +++ b/Lang/Scilab/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Fibonacci-word b/Lang/Scilab/Fibonacci-word new file mode 120000 index 0000000000..7ab95d8c2f --- /dev/null +++ b/Lang/Scilab/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Fibonacci-word-fractal b/Lang/Scilab/Fibonacci-word-fractal new file mode 120000 index 0000000000..871f7de52a --- /dev/null +++ b/Lang/Scilab/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Fractal-tree b/Lang/Scilab/Fractal-tree new file mode 120000 index 0000000000..8089e21dfd --- /dev/null +++ b/Lang/Scilab/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Hello-world-Graphical b/Lang/Scilab/Hello-world-Graphical new file mode 120000 index 0000000000..78a1a1eb8b --- /dev/null +++ b/Lang/Scilab/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Hello-world-Newline-omission b/Lang/Scilab/Hello-world-Newline-omission new file mode 120000 index 0000000000..a3cf7a3359 --- /dev/null +++ b/Lang/Scilab/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Hello-world-Standard-error b/Lang/Scilab/Hello-world-Standard-error new file mode 120000 index 0000000000..073174025a --- /dev/null +++ b/Lang/Scilab/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Langtons-ant b/Lang/Scilab/Langtons-ant new file mode 120000 index 0000000000..e22b6938b6 --- /dev/null +++ b/Lang/Scilab/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Scilab \ No newline at end of file diff --git a/Lang/Scilab/N-queens-problem b/Lang/Scilab/N-queens-problem new file mode 120000 index 0000000000..7fcd3b6796 --- /dev/null +++ b/Lang/Scilab/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Plot-coordinate-pairs b/Lang/Scilab/Plot-coordinate-pairs new file mode 120000 index 0000000000..e90baf2002 --- /dev/null +++ b/Lang/Scilab/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Sorting-algorithms-Cocktail-sort b/Lang/Scilab/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..64f067630e --- /dev/null +++ b/Lang/Scilab/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Standard-deviation b/Lang/Scilab/Standard-deviation deleted file mode 120000 index c7e14f9fc7..0000000000 --- a/Lang/Scilab/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Sudoku b/Lang/Scilab/Sudoku new file mode 120000 index 0000000000..9283403bce --- /dev/null +++ b/Lang/Scilab/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Tic-tac-toe b/Lang/Scilab/Tic-tac-toe new file mode 120000 index 0000000000..2a01af6b19 --- /dev/null +++ b/Lang/Scilab/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Yin-and-yang b/Lang/Scilab/Yin-and-yang new file mode 120000 index 0000000000..41ae420a81 --- /dev/null +++ b/Lang/Scilab/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Scilab \ No newline at end of file diff --git a/Lang/Sed/99-Bottles-of-Beer b/Lang/Sed/99-Bottles-of-Beer new file mode 120000 index 0000000000..019be1e903 --- /dev/null +++ b/Lang/Sed/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Sed \ No newline at end of file diff --git a/Lang/Sed/A+B b/Lang/Sed/A+B new file mode 120000 index 0000000000..54974969d8 --- /dev/null +++ b/Lang/Sed/A+B @@ -0,0 +1 @@ +../../Task/A+B/Sed \ No newline at end of file diff --git a/Lang/Sed/Align-columns b/Lang/Sed/Align-columns new file mode 120000 index 0000000000..386f9870c9 --- /dev/null +++ b/Lang/Sed/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Sed \ No newline at end of file diff --git a/Lang/Sed/Caesar-cipher b/Lang/Sed/Caesar-cipher new file mode 120000 index 0000000000..33a2aa5998 --- /dev/null +++ b/Lang/Sed/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Sed \ No newline at end of file diff --git a/Lang/Sed/Comments b/Lang/Sed/Comments new file mode 120000 index 0000000000..c07f3667b4 --- /dev/null +++ b/Lang/Sed/Comments @@ -0,0 +1 @@ +../../Task/Comments/Sed \ No newline at end of file diff --git a/Lang/Sed/Fibonacci-sequence b/Lang/Sed/Fibonacci-sequence new file mode 120000 index 0000000000..9ee1f24de7 --- /dev/null +++ b/Lang/Sed/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Sed \ No newline at end of file diff --git a/Lang/Sed/Hello-world-Standard-error b/Lang/Sed/Hello-world-Standard-error new file mode 120000 index 0000000000..15d939ef5d --- /dev/null +++ b/Lang/Sed/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Sed \ No newline at end of file diff --git a/Lang/Sed/Hello-world-Text b/Lang/Sed/Hello-world-Text new file mode 120000 index 0000000000..60c7357e1a --- /dev/null +++ b/Lang/Sed/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Sed \ No newline at end of file diff --git a/Lang/Sed/Loops-Infinite b/Lang/Sed/Loops-Infinite new file mode 120000 index 0000000000..eb5b545cff --- /dev/null +++ b/Lang/Sed/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Sed \ No newline at end of file diff --git a/Lang/Sed/Luhn-test-of-credit-card-numbers b/Lang/Sed/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..ec1f10f425 --- /dev/null +++ b/Lang/Sed/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Sed \ No newline at end of file diff --git a/Lang/Sed/Morse-code b/Lang/Sed/Morse-code new file mode 120000 index 0000000000..5505bcdc72 --- /dev/null +++ b/Lang/Sed/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Sed \ No newline at end of file diff --git a/Lang/Sed/Read-a-specific-line-from-a-file b/Lang/Sed/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..2adc2b3da4 --- /dev/null +++ b/Lang/Sed/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Sed \ No newline at end of file diff --git a/Lang/Sed/Repeat-a-string b/Lang/Sed/Repeat-a-string new file mode 120000 index 0000000000..a30ebcc9bf --- /dev/null +++ b/Lang/Sed/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Sed \ No newline at end of file diff --git a/Lang/Sed/Rot-13 b/Lang/Sed/Rot-13 new file mode 120000 index 0000000000..781684887b --- /dev/null +++ b/Lang/Sed/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Sed \ No newline at end of file diff --git a/Lang/Sed/Run-length-encoding b/Lang/Sed/Run-length-encoding new file mode 120000 index 0000000000..4f5835b2ee --- /dev/null +++ b/Lang/Sed/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Sed \ No newline at end of file diff --git a/Lang/Sed/Start-from-a-main-routine b/Lang/Sed/Start-from-a-main-routine new file mode 120000 index 0000000000..00cedcc3b3 --- /dev/null +++ b/Lang/Sed/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Sed \ No newline at end of file diff --git a/Lang/Sed/Strip-comments-from-a-string b/Lang/Sed/Strip-comments-from-a-string new file mode 120000 index 0000000000..830473b01b --- /dev/null +++ b/Lang/Sed/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Sed \ No newline at end of file diff --git a/Lang/Seed7/Character-matching b/Lang/Seed7/Character-matching deleted file mode 120000 index f9193ddbd8..0000000000 --- a/Lang/Seed7/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/File-IO b/Lang/Seed7/File-IO deleted file mode 120000 index 8327757aa5..0000000000 --- a/Lang/Seed7/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Seed7 \ 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/Rosetta-Code-Rank-languages-by-popularity b/Lang/Seed7/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index ef18e8acbd..0000000000 --- a/Lang/Seed7/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Seed7 \ No newline at end of file diff --git a/Lang/Self/00DESCRIPTION b/Lang/Self/00DESCRIPTION index 856070bf64..dd6e89e237 100644 --- a/Lang/Self/00DESCRIPTION +++ b/Lang/Self/00DESCRIPTION @@ -3,7 +3,7 @@ |LCT=no }} -'''Self''' is an [[object-oriented]] programming language based on the concept of prototypes. It was used primarily as an experimental test system for language design in the 1980s and 1990s; however, as of May 2015, Self is still being developed and maintained as an open source project. The latest major version is 4.5.0, which was released in January 2014. +'''Self''' is an [[object-oriented]] programming language based on the concept of prototypes. It was used primarily as an experimental test system for language design in the 1980s and 1990s; however, as of May 2015, Self is still being developed and maintained as an open source project. The latest major version is 2017.1, which was released in May 2017. ==Citations== * [[wp:Self_%28programming_language%29|Wikipedia:Self (programming language)]] \ No newline at end of file diff --git a/Lang/SequenceL/Arithmetic-geometric-mean b/Lang/SequenceL/Arithmetic-geometric-mean new file mode 120000 index 0000000000..1c49b42948 --- /dev/null +++ b/Lang/SequenceL/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Brownian-tree b/Lang/SequenceL/Brownian-tree new file mode 120000 index 0000000000..2964193aa1 --- /dev/null +++ b/Lang/SequenceL/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Evaluate-binomial-coefficients b/Lang/SequenceL/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..76de778ed0 --- /dev/null +++ b/Lang/SequenceL/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Execute-a-Markov-algorithm b/Lang/SequenceL/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..2a06172a3c --- /dev/null +++ b/Lang/SequenceL/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Forward-difference b/Lang/SequenceL/Forward-difference new file mode 120000 index 0000000000..7a4bdccb24 --- /dev/null +++ b/Lang/SequenceL/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Increment-a-numerical-string b/Lang/SequenceL/Increment-a-numerical-string new file mode 120000 index 0000000000..e4e390f136 --- /dev/null +++ b/Lang/SequenceL/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Josephus-problem b/Lang/SequenceL/Josephus-problem new file mode 120000 index 0000000000..3c0050d4b5 --- /dev/null +++ b/Lang/SequenceL/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/K-means++-clustering b/Lang/SequenceL/K-means++-clustering new file mode 120000 index 0000000000..0fac75728a --- /dev/null +++ b/Lang/SequenceL/K-means++-clustering @@ -0,0 +1 @@ +../../Task/K-means++-clustering/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Knights-tour b/Lang/SequenceL/Knights-tour new file mode 120000 index 0000000000..aa2d233758 --- /dev/null +++ b/Lang/SequenceL/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Levenshtein-distance b/Lang/SequenceL/Levenshtein-distance new file mode 120000 index 0000000000..04fd0d3881 --- /dev/null +++ b/Lang/SequenceL/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Linear-congruential-generator b/Lang/SequenceL/Linear-congruential-generator new file mode 120000 index 0000000000..62000b214b --- /dev/null +++ b/Lang/SequenceL/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Longest-common-subsequence b/Lang/SequenceL/Longest-common-subsequence new file mode 120000 index 0000000000..64eb8a5752 --- /dev/null +++ b/Lang/SequenceL/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Ludic-numbers b/Lang/SequenceL/Ludic-numbers new file mode 120000 index 0000000000..30e6b03de1 --- /dev/null +++ b/Lang/SequenceL/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Luhn-test-of-credit-card-numbers b/Lang/SequenceL/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..53357361ce --- /dev/null +++ b/Lang/SequenceL/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Monte-Carlo-methods b/Lang/SequenceL/Monte-Carlo-methods new file mode 120000 index 0000000000..bc26187c6b --- /dev/null +++ b/Lang/SequenceL/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/One-dimensional-cellular-automata b/Lang/SequenceL/One-dimensional-cellular-automata new file mode 120000 index 0000000000..8ac2abd1c0 --- /dev/null +++ b/Lang/SequenceL/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/QR-decomposition b/Lang/SequenceL/QR-decomposition new file mode 120000 index 0000000000..292e216b3f --- /dev/null +++ b/Lang/SequenceL/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Sorting-algorithms-Heapsort b/Lang/SequenceL/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..ec7d5fd4ac --- /dev/null +++ b/Lang/SequenceL/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/SequenceL \ No newline at end of file diff --git a/Lang/SequenceL/Tree-traversal b/Lang/SequenceL/Tree-traversal new file mode 120000 index 0000000000..0d214d56e1 --- /dev/null +++ b/Lang/SequenceL/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/SequenceL \ No newline at end of file diff --git a/Lang/Setl4/00DESCRIPTION b/Lang/Setl4/00DESCRIPTION new file mode 100644 index 0000000000..376f310f3a --- /dev/null +++ b/Lang/Setl4/00DESCRIPTION @@ -0,0 +1,11 @@ +{{stub}}{{language|Setl4}} + +SETL4 is a new implementation of Setl that brings the raw power and speed of SPITBOL to non-numeric computation using set-theoretic constructs + +It was designed and created by Dave Shields, the author of the first implementation of Setl, written in 1970-1971, using as ASR 33 Teletype. + +Setl4 is written in SPITBOL, a very efficient implementation of Snobol4. + +Source and binaries can be found at http://github.com/setl4. + +Setl4 is licensed under the MIT License, SPITBOL under GPLv2 (or later) \ No newline at end of file diff --git a/Lang/Setl4/Associative-array-Creation b/Lang/Setl4/Associative-array-Creation new file mode 120000 index 0000000000..63208f7a13 --- /dev/null +++ b/Lang/Setl4/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Setl4 \ No newline at end of file diff --git a/Lang/Setl4/Collections b/Lang/Setl4/Collections new file mode 120000 index 0000000000..d3e5b7a7d6 --- /dev/null +++ b/Lang/Setl4/Collections @@ -0,0 +1 @@ +../../Task/Collections/Setl4 \ No newline at end of file diff --git a/Lang/Setl4/Hello-world-Text b/Lang/Setl4/Hello-world-Text new file mode 120000 index 0000000000..479837413f --- /dev/null +++ b/Lang/Setl4/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Setl4 \ No newline at end of file diff --git a/Lang/Setl4/README b/Lang/Setl4/README new file mode 100644 index 0000000000..cee15e2ec1 --- /dev/null +++ b/Lang/Setl4/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Setl4 diff --git a/Lang/Setl4/Remove-duplicate-elements b/Lang/Setl4/Remove-duplicate-elements new file mode 120000 index 0000000000..c87f6e42d0 --- /dev/null +++ b/Lang/Setl4/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Setl4 \ No newline at end of file diff --git a/Lang/Shen/00DESCRIPTION b/Lang/Shen/00DESCRIPTION index 1739f7401e..c38ac7934f 100644 --- a/Lang/Shen/00DESCRIPTION +++ b/Lang/Shen/00DESCRIPTION @@ -1,4 +1,22 @@ {{stub}} {{language |site=http://www.shenlanguage.org/}} -{{implementation|Lisp}} \ No newline at end of file +{{implementation|Lisp}} + +http://www.shenlanguage.org/ + +Shen is a portable functional programming language that offers + +* pattern matching, +* lambda calculus consistency, +* macros for defining domain specific languages, +* optional lazy evaluation, +* static type checking based on sequent calculus, one of the most powerful systems for typing in functional programming +* portability over many languages, +* an integrated fully functional Prolog, +* an inbuilt compiler-compiler. +* runs under CLisp, SBCL, Clozure CL, Clojure, F#, Scheme, Wasp, Emacs Lisp, Ruby, Python, the JVM, the CLR, Haskell and Javascript +* has a BSD kernel + + +The word ‘Shen’ is Chinese for 'spirit' and our motto reflects our desire to liberate our work to live under many platforms. \ No newline at end of file diff --git a/Lang/Shen/Even-or-odd b/Lang/Shen/Even-or-odd new file mode 120000 index 0000000000..dc506b0e22 --- /dev/null +++ b/Lang/Shen/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Shen \ No newline at end of file diff --git a/Lang/Shen/Y-combinator b/Lang/Shen/Y-combinator new file mode 120000 index 0000000000..5e5b295771 --- /dev/null +++ b/Lang/Shen/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Shen \ No newline at end of file diff --git a/Lang/Sidef/Conjugate-transpose b/Lang/Sidef/Conjugate-transpose new file mode 120000 index 0000000000..320dbe7b5e --- /dev/null +++ b/Lang/Sidef/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Last-letter-first-letter b/Lang/Sidef/Last-letter-first-letter new file mode 120000 index 0000000000..ebe2eff25e --- /dev/null +++ b/Lang/Sidef/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Monte-Carlo-methods b/Lang/Sidef/Monte-Carlo-methods new file mode 120000 index 0000000000..1902f31c30 --- /dev/null +++ b/Lang/Sidef/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Twelve-statements b/Lang/Sidef/Twelve-statements new file mode 120000 index 0000000000..c379e20d59 --- /dev/null +++ b/Lang/Sidef/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Variable-length-quantity b/Lang/Sidef/Variable-length-quantity new file mode 120000 index 0000000000..c39602871a --- /dev/null +++ b/Lang/Sidef/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Sidef \ No newline at end of file diff --git a/Lang/Simula/100-doors b/Lang/Simula/100-doors new file mode 120000 index 0000000000..84a8605131 --- /dev/null +++ b/Lang/Simula/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Simula \ No newline at end of file diff --git a/Lang/Simula/24-game b/Lang/Simula/24-game new file mode 120000 index 0000000000..46e5a2b792 --- /dev/null +++ b/Lang/Simula/24-game @@ -0,0 +1 @@ +../../Task/24-game/Simula \ No newline at end of file diff --git a/Lang/Simula/24-game-Solve b/Lang/Simula/24-game-Solve new file mode 120000 index 0000000000..7ddca23f00 --- /dev/null +++ b/Lang/Simula/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Simula \ No newline at end of file diff --git a/Lang/Simula/99-Bottles-of-Beer b/Lang/Simula/99-Bottles-of-Beer new file mode 120000 index 0000000000..d3040af3f1 --- /dev/null +++ b/Lang/Simula/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Simula \ No newline at end of file diff --git a/Lang/Simula/A+B b/Lang/Simula/A+B new file mode 120000 index 0000000000..6b160a7322 --- /dev/null +++ b/Lang/Simula/A+B @@ -0,0 +1 @@ +../../Task/A+B/Simula \ No newline at end of file diff --git a/Lang/Simula/ABC-Problem b/Lang/Simula/ABC-Problem new file mode 120000 index 0000000000..4525fba483 --- /dev/null +++ b/Lang/Simula/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Simula \ No newline at end of file diff --git a/Lang/Simula/Abstract-type b/Lang/Simula/Abstract-type new file mode 120000 index 0000000000..1848e4c58f --- /dev/null +++ b/Lang/Simula/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Simula \ No newline at end of file diff --git a/Lang/Simula/Accumulator-factory b/Lang/Simula/Accumulator-factory new file mode 120000 index 0000000000..18a652d5d1 --- /dev/null +++ b/Lang/Simula/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Simula \ No newline at end of file diff --git a/Lang/Simula/Anagrams b/Lang/Simula/Anagrams new file mode 120000 index 0000000000..393f182ace --- /dev/null +++ b/Lang/Simula/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Simula \ No newline at end of file diff --git a/Lang/Simula/Apply-a-callback-to-an-array b/Lang/Simula/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..b76c0fcbd2 --- /dev/null +++ b/Lang/Simula/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Simula \ No newline at end of file diff --git a/Lang/Simula/Array-concatenation b/Lang/Simula/Array-concatenation new file mode 120000 index 0000000000..bfdd0832b3 --- /dev/null +++ b/Lang/Simula/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Simula \ No newline at end of file diff --git a/Lang/Simula/Arrays b/Lang/Simula/Arrays new file mode 120000 index 0000000000..caf96c559b --- /dev/null +++ b/Lang/Simula/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Simula \ No newline at end of file diff --git a/Lang/Simula/Conways-Game-of-Life b/Lang/Simula/Conways-Game-of-Life new file mode 120000 index 0000000000..8beca158bb --- /dev/null +++ b/Lang/Simula/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Simula \ No newline at end of file diff --git a/Lang/Simula/Determine-if-a-string-is-numeric b/Lang/Simula/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..f64cdd7410 --- /dev/null +++ b/Lang/Simula/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Simula \ No newline at end of file diff --git a/Lang/Simula/Five-weekends b/Lang/Simula/Five-weekends new file mode 120000 index 0000000000..57114acd12 --- /dev/null +++ b/Lang/Simula/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Simula \ No newline at end of file diff --git a/Lang/Simula/Jensens-Device b/Lang/Simula/Jensens-Device new file mode 120000 index 0000000000..b6530a48a3 --- /dev/null +++ b/Lang/Simula/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Simula \ No newline at end of file diff --git a/Lang/Simula/Levenshtein-distance b/Lang/Simula/Levenshtein-distance new file mode 120000 index 0000000000..3b80c4c39f --- /dev/null +++ b/Lang/Simula/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Simula \ No newline at end of file diff --git a/Lang/Simula/Loops-Break b/Lang/Simula/Loops-Break new file mode 120000 index 0000000000..6c770ed52c --- /dev/null +++ b/Lang/Simula/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Simula \ No newline at end of file diff --git a/Lang/Simula/Loops-Continue b/Lang/Simula/Loops-Continue new file mode 120000 index 0000000000..3331990f23 --- /dev/null +++ b/Lang/Simula/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Simula \ No newline at end of file diff --git a/Lang/Simula/Loops-While b/Lang/Simula/Loops-While new file mode 120000 index 0000000000..e3b4d3cf36 --- /dev/null +++ b/Lang/Simula/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Simula \ No newline at end of file diff --git a/Lang/Simula/Matrix-arithmetic b/Lang/Simula/Matrix-arithmetic new file mode 120000 index 0000000000..1cffeecd51 --- /dev/null +++ b/Lang/Simula/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Simula \ No newline at end of file diff --git a/Lang/Simula/Ordered-words b/Lang/Simula/Ordered-words new file mode 120000 index 0000000000..0be5bb5f1b --- /dev/null +++ b/Lang/Simula/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Simula \ No newline at end of file diff --git a/Lang/Simula/Palindrome-detection b/Lang/Simula/Palindrome-detection new file mode 120000 index 0000000000..333797ee2a --- /dev/null +++ b/Lang/Simula/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Simula \ No newline at end of file diff --git a/Lang/Simula/Power-set b/Lang/Simula/Power-set new file mode 120000 index 0000000000..48a818c50b --- /dev/null +++ b/Lang/Simula/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Simula \ No newline at end of file diff --git a/Lang/Simula/Roman-numerals-Decode b/Lang/Simula/Roman-numerals-Decode new file mode 120000 index 0000000000..d10e053233 --- /dev/null +++ b/Lang/Simula/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Simula \ No newline at end of file diff --git a/Lang/Simula/Roman-numerals-Encode b/Lang/Simula/Roman-numerals-Encode new file mode 120000 index 0000000000..7b6127dc39 --- /dev/null +++ b/Lang/Simula/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Simula \ No newline at end of file diff --git a/Lang/Simula/Runtime-evaluation-In-an-environment b/Lang/Simula/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..9f781a3e7c --- /dev/null +++ b/Lang/Simula/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/Simula \ No newline at end of file diff --git a/Lang/Simula/Set b/Lang/Simula/Set new file mode 120000 index 0000000000..6a45ed4b22 --- /dev/null +++ b/Lang/Simula/Set @@ -0,0 +1 @@ +../../Task/Set/Simula \ No newline at end of file diff --git a/Lang/Simula/Short-circuit-evaluation b/Lang/Simula/Short-circuit-evaluation new file mode 120000 index 0000000000..36720986ef --- /dev/null +++ b/Lang/Simula/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Simula \ No newline at end of file diff --git a/Lang/Simula/Sort-an-array-of-composite-structures b/Lang/Simula/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..2b4a0cf5e6 --- /dev/null +++ b/Lang/Simula/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Simula \ No newline at end of file diff --git a/Lang/Simula/Sorting-algorithms-Bubble-sort b/Lang/Simula/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..b03509d8cc --- /dev/null +++ b/Lang/Simula/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Simula \ No newline at end of file diff --git a/Lang/Simula/Sorting-algorithms-Quicksort b/Lang/Simula/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..db2e7bace7 --- /dev/null +++ b/Lang/Simula/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Simula \ No newline at end of file diff --git a/Lang/Simula/Sorting-algorithms-Sleep-sort b/Lang/Simula/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..15a60bcf7f --- /dev/null +++ b/Lang/Simula/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Simula \ No newline at end of file diff --git a/Lang/Simula/String-length b/Lang/Simula/String-length new file mode 120000 index 0000000000..f8d353f8c5 --- /dev/null +++ b/Lang/Simula/String-length @@ -0,0 +1 @@ +../../Task/String-length/Simula \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/00DESCRIPTION b/Lang/Sinclair-ZX81-BASIC/00DESCRIPTION new file mode 100644 index 0000000000..f60b6b4138 --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/00DESCRIPTION @@ -0,0 +1,14 @@ +{{language|Sinclair ZX81 BASIC}} +{{implementation|BASIC}} + +Sinclair ZX81 BASIC is the dialect of BASIC resident in ROM on the ZX81 home computer (1981) and compatibles (Timex Sinclair 1000, Lambda 8300, and many others). It was developed by John Grant and Steve Vickers. Today, ZX81 emulators exist for a wide range of platforms and operating systems. + +ZX81 BASIC is almost a subset of [[ZX Spectrum Basic]], but not quite: the exponentiation operator is spelled ** rather than (mapped to ASCII ^), the jump and subroutine call keywords are spelled GOTO and GOSUB rather than GO TO and GO SUB, etc. Note also that the ZX81 uses an idiosyncratic (non-ASCII) character set, so that the CODE and CHR$ functions do not return the same values as they would on the Spectrum. Floating point operations, some string handling, and low-resolution graphics are supported; colour, sound, user-defined functions, the READ, DATA, and RESTORE keywords, and assorted other features are not. + +The ZX81 has no moving parts and only four microchips: the 3.25MHz Z80 CPU, an 8k ROM chip containing the operating system and BASIC, a 1k RAM chip, and an uncommitted logic array. Since there is no separate video chip, the CPU spends about 75% of its time driving the display and only 25% doing everything else. This can, however, be controlled under BASIC using the FAST and SLOW commands: FAST blanks the screen and allows the processor to operate at full speed, and SLOW reverts to the default behaviour. Even FAST mode can be slower than some other BASIC dialects running on comparable hardware, because ZX81 BASIC has no integer type: all numeric operations have to be done on 40-bit floats using software floating-point routines. + +The original machine's 1k of RAM was shared between the display, the system variables and stack, and the user's program and variables. The Timex-branded model marketed in the United States had a minimum of 2k, as did many clones; an expansion pack was available from Sinclair to increase the RAM to 16k, and expansions of other sizes were produced by third parties. Most ZX81 BASIC programs on Rosetta Code will work with the 1k configuration, but unfortunately some of them require 2k. The minimum RAM requirement is usually stated in a note to the program: where it is omitted, it can be assumed to be 1k. + +A PDF version of the manual, ZX81 BASIC Programming by Steve Vickers, is available [http://zxnext.narod.ru/manuals/ZX81_Manual.pdf here]. + +If you do not have a ZX81 emulator installed on your computer, and your computer is not itself a ZX81 or ZX81 compatible, you can type any of these programs into the [http://www.zx81stuff.org.uk/zx81/jtyone.html JtyOne online ZX81 emulator] and see what they do. \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Arithmetic-geometric-mean b/Lang/Sinclair-ZX81-BASIC/Arithmetic-geometric-mean new file mode 120000 index 0000000000..5fb705fa47 --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Brownian-tree b/Lang/Sinclair-ZX81-BASIC/Brownian-tree new file mode 120000 index 0000000000..634fea02a7 --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Caesar-cipher b/Lang/Sinclair-ZX81-BASIC/Caesar-cipher new file mode 120000 index 0000000000..b9c5fe721f --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Evolutionary-algorithm b/Lang/Sinclair-ZX81-BASIC/Evolutionary-algorithm new file mode 120000 index 0000000000..6771739dc3 --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Harshad-or-Niven-series b/Lang/Sinclair-ZX81-BASIC/Harshad-or-Niven-series new file mode 120000 index 0000000000..36ac5db852 --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Identity-matrix b/Lang/Sinclair-ZX81-BASIC/Identity-matrix new file mode 120000 index 0000000000..598898f684 --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Loops-While b/Lang/Sinclair-ZX81-BASIC/Loops-While new file mode 120000 index 0000000000..a59fde3db2 --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Memory-allocation b/Lang/Sinclair-ZX81-BASIC/Memory-allocation new file mode 120000 index 0000000000..84dd2f8936 --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Memory-allocation @@ -0,0 +1 @@ +../../Task/Memory-allocation/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Nth b/Lang/Sinclair-ZX81-BASIC/Nth new file mode 120000 index 0000000000..fd7fbac806 --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Nth @@ -0,0 +1 @@ +../../Task/Nth/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Parsing-RPN-calculator-algorithm b/Lang/Sinclair-ZX81-BASIC/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..8fbfeb644e --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/README b/Lang/Sinclair-ZX81-BASIC/README new file mode 100644 index 0000000000..72bc00e996 --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Sinclair_ZX81_BASIC diff --git a/Lang/Sinclair-ZX81-BASIC/Repeat-a-string b/Lang/Sinclair-ZX81-BASIC/Repeat-a-string new file mode 120000 index 0000000000..fc238c2c7f --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Sierpinski-carpet b/Lang/Sinclair-ZX81-BASIC/Sierpinski-carpet new file mode 120000 index 0000000000..e5fe034166 --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Trabb-Pardo-Knuth-algorithm b/Lang/Sinclair-ZX81-BASIC/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..14f6e4ad20 --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Zeckendorf-number-representation b/Lang/Sinclair-ZX81-BASIC/Zeckendorf-number-representation new file mode 120000 index 0000000000..a734b4e65d --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Zero-to-the-zero-power b/Lang/Sinclair-ZX81-BASIC/Zero-to-the-zero-power new file mode 120000 index 0000000000..4e444ab58e --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/SkookumScript/00DESCRIPTION b/Lang/SkookumScript/00DESCRIPTION index fb028795d6..fb99f654f9 100644 --- a/Lang/SkookumScript/00DESCRIPTION +++ b/Lang/SkookumScript/00DESCRIPTION @@ -1,5 +1,5 @@ {{language|SkookumScript -|exec=compiled +|exec=machine |parampass=reference |gc=yes |safety=safe @@ -7,6 +7,7 @@ |express=Partially implicit |checking=static |compat=nominative +|tags=sk |site=http://skookumscript.com/ |LCT=yes |bnf=http://skookumscript.com/docs/v3.0/lang/syntax/}} diff --git a/Lang/Slate/File-IO b/Lang/Slate/File-IO deleted file mode 120000 index cebb12c3ea..0000000000 --- a/Lang/Slate/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Slate \ No newline at end of file diff --git a/Lang/Smalltalk/Character-matching b/Lang/Smalltalk/Character-matching deleted file mode 120000 index 9b9ab21c46..0000000000 --- a/Lang/Smalltalk/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/File-IO b/Lang/Smalltalk/File-IO deleted file mode 120000 index ca4b4b1c77..0000000000 --- a/Lang/Smalltalk/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Loops-N-plus-one-half b/Lang/Smalltalk/Loops-N-plus-one-half new file mode 120000 index 0000000000..e9dfc088b0 --- /dev/null +++ b/Lang/Smalltalk/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Smalltalk \ 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/Smalltalk/Primality-by-trial-division b/Lang/Smalltalk/Primality-by-trial-division new file mode 120000 index 0000000000..bbf1153a13 --- /dev/null +++ b/Lang/Smalltalk/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sequence-of-non-squares b/Lang/Smalltalk/Sequence-of-non-squares new file mode 120000 index 0000000000..78d9784e23 --- /dev/null +++ b/Lang/Smalltalk/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sieve-of-Eratosthenes b/Lang/Smalltalk/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..f5e7085d7b --- /dev/null +++ b/Lang/Smalltalk/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Standard-deviation b/Lang/Smalltalk/Standard-deviation deleted file mode 120000 index c8f148c743..0000000000 --- a/Lang/Smalltalk/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Smalltalk \ No newline at end of file diff --git a/Lang/Smart-BASIC/00DESCRIPTION b/Lang/Smart-BASIC/00DESCRIPTION new file mode 100644 index 0000000000..084b6a561d --- /dev/null +++ b/Lang/Smart-BASIC/00DESCRIPTION @@ -0,0 +1,33 @@ +=={{header|smart BASIC}}== +{{language|smart BASIC +|exec=interpreted/compiled +|site=https://itunes.apple.com/us/app/smart-basic-programming-language/id541447413?mt=8 +|parampass=both}} +{{language programming paradigm|procedural}} +{{implementation|BASIC}} + +smart BASIC is an extension of the very popular BASIC programming language originally developed by Dartmouth College way back in 1964. With Smart BASIC you can write BASIC programs directly on iOS devices. + +Using Apple's Xcode platform along with the freely provided smart BASIC SDK, you can actually program in BASIC within Xcode, test your code in iOS simulators or your own iOS device, and even build stand-alone apps for submission to the App Store to sell, with no royalty issues. All for just $4.99! + +smart BASIC is very powerful. Some of its features include: + +*Genuine BASIC commands +*Graphics +*Standard interface objects +*Music +*Video +*Hardware support (GPS, accelerometer, cameras, multitouch) +*Networking +*File and directory functions +*Skinnable interface +*Fully documented +*Sample programs +*Active online support forum ([http://kibernetik.pro/forum/viewforum.php?f=2 Mr. Kibernetik]) + +The smart BASIC support forum is regularly administered by Mr. Kibernetik, who provides timely, professional support in addition to a lively group of forum members from around the world. + +
'''smart BASIC''' initially introduced to Rosetta Code on December 16, 2016 by [http://rosettacode.org/wiki/User:Sarossell Scott A. Rossell]
smart BASIC and the smart BASIC logo are owned by Mr. Kibernetik. +---- +
+ \ No newline at end of file diff --git a/Lang/Smart-BASIC/100-doors b/Lang/Smart-BASIC/100-doors new file mode 120000 index 0000000000..90d5884dab --- /dev/null +++ b/Lang/Smart-BASIC/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/A+B b/Lang/Smart-BASIC/A+B new file mode 120000 index 0000000000..701c6f4708 --- /dev/null +++ b/Lang/Smart-BASIC/A+B @@ -0,0 +1 @@ +../../Task/A+B/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Active-Directory-Connect b/Lang/Smart-BASIC/Active-Directory-Connect new file mode 120000 index 0000000000..3077cd1d69 --- /dev/null +++ b/Lang/Smart-BASIC/Active-Directory-Connect @@ -0,0 +1 @@ +../../Task/Active-Directory-Connect/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Animate-a-pendulum b/Lang/Smart-BASIC/Animate-a-pendulum new file mode 120000 index 0000000000..c7929250ec --- /dev/null +++ b/Lang/Smart-BASIC/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Animation b/Lang/Smart-BASIC/Animation new file mode 120000 index 0000000000..2e0edcb6e7 --- /dev/null +++ b/Lang/Smart-BASIC/Animation @@ -0,0 +1 @@ +../../Task/Animation/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Arithmetic-Complex b/Lang/Smart-BASIC/Arithmetic-Complex new file mode 120000 index 0000000000..c2f3fd9096 --- /dev/null +++ b/Lang/Smart-BASIC/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Arithmetic-Integer b/Lang/Smart-BASIC/Arithmetic-Integer new file mode 120000 index 0000000000..263dcb4908 --- /dev/null +++ b/Lang/Smart-BASIC/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Box-the-compass b/Lang/Smart-BASIC/Box-the-compass new file mode 120000 index 0000000000..96abd7a441 --- /dev/null +++ b/Lang/Smart-BASIC/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Bulls-and-cows b/Lang/Smart-BASIC/Bulls-and-cows new file mode 120000 index 0000000000..c50924f246 --- /dev/null +++ b/Lang/Smart-BASIC/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Catalan-numbers b/Lang/Smart-BASIC/Catalan-numbers new file mode 120000 index 0000000000..969b4b4987 --- /dev/null +++ b/Lang/Smart-BASIC/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Catalan-numbers-Pascals-triangle b/Lang/Smart-BASIC/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..4cf7e3f72a --- /dev/null +++ b/Lang/Smart-BASIC/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Comments b/Lang/Smart-BASIC/Comments new file mode 120000 index 0000000000..79d8267d4a --- /dev/null +++ b/Lang/Smart-BASIC/Comments @@ -0,0 +1 @@ +../../Task/Comments/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Fibonacci-sequence b/Lang/Smart-BASIC/Fibonacci-sequence new file mode 120000 index 0000000000..fac20e16e4 --- /dev/null +++ b/Lang/Smart-BASIC/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Hello-world-Text b/Lang/Smart-BASIC/Hello-world-Text new file mode 120000 index 0000000000..fcfb11aec4 --- /dev/null +++ b/Lang/Smart-BASIC/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/README b/Lang/Smart-BASIC/README new file mode 100644 index 0000000000..2e257e4595 --- /dev/null +++ b/Lang/Smart-BASIC/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Smart_BASIC diff --git a/Lang/Smart-BASIC/The-Twelve-Days-of-Christmas b/Lang/Smart-BASIC/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..4c07bf8cbf --- /dev/null +++ b/Lang/Smart-BASIC/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/User-input-Text b/Lang/Smart-BASIC/User-input-Text new file mode 120000 index 0000000000..b8a64f7b24 --- /dev/null +++ b/Lang/Smart-BASIC/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Variables b/Lang/Smart-BASIC/Variables new file mode 120000 index 0000000000..e8c840e9d5 --- /dev/null +++ b/Lang/Smart-BASIC/Variables @@ -0,0 +1 @@ +../../Task/Variables/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Video-display-modes b/Lang/Smart-BASIC/Video-display-modes new file mode 120000 index 0000000000..8e7f7af599 --- /dev/null +++ b/Lang/Smart-BASIC/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/Smart-BASIC \ No newline at end of file diff --git a/Lang/Smart-BASIC/Zero-to-the-zero-power b/Lang/Smart-BASIC/Zero-to-the-zero-power new file mode 120000 index 0000000000..d78e6d5105 --- /dev/null +++ b/Lang/Smart-BASIC/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Smart-BASIC \ No newline at end of file diff --git a/Lang/Snobol/Generate-lower-case-ASCII-alphabet b/Lang/Snobol/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..fe9525242e --- /dev/null +++ b/Lang/Snobol/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Snobol \ No newline at end of file diff --git a/Lang/Standard-ML/100-doors b/Lang/Standard-ML/100-doors new file mode 120000 index 0000000000..3ec35bac33 --- /dev/null +++ b/Lang/Standard-ML/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Character-matching b/Lang/Standard-ML/Character-matching deleted file mode 120000 index 3c55279b79..0000000000 --- a/Lang/Standard-ML/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Fibonacci-sequence b/Lang/Standard-ML/Fibonacci-sequence deleted file mode 120000 index 500cf5d82e..0000000000 --- a/Lang/Standard-ML/Fibonacci-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Fibonacci-sequence/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/File-IO b/Lang/Standard-ML/File-IO deleted file mode 120000 index 3f4f253fca..0000000000 --- a/Lang/Standard-ML/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Filter b/Lang/Standard-ML/Filter deleted file mode 120000 index 67251d6a40..0000000000 --- a/Lang/Standard-ML/Filter +++ /dev/null @@ -1 +0,0 @@ -../../Task/Filter/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/FizzBuzz b/Lang/Standard-ML/FizzBuzz deleted file mode 120000 index a297dedd92..0000000000 --- a/Lang/Standard-ML/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Greatest-common-divisor b/Lang/Standard-ML/Greatest-common-divisor deleted file mode 120000 index 019dbbd5a2..0000000000 --- a/Lang/Standard-ML/Greatest-common-divisor +++ /dev/null @@ -1 +0,0 @@ -../../Task/Greatest-common-divisor/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/IBAN b/Lang/Standard-ML/IBAN new file mode 120000 index 0000000000..c4828b7723 --- /dev/null +++ b/Lang/Standard-ML/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Increment-a-numerical-string b/Lang/Standard-ML/Increment-a-numerical-string deleted file mode 120000 index 1db6c8f2a2..0000000000 --- a/Lang/Standard-ML/Increment-a-numerical-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Increment-a-numerical-string/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/Palindrome-detection b/Lang/Standard-ML/Palindrome-detection deleted file mode 120000 index 6b8476e1ce..0000000000 --- a/Lang/Standard-ML/Palindrome-detection +++ /dev/null @@ -1 +0,0 @@ -../../Task/Palindrome-detection/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Rot-13 b/Lang/Standard-ML/Rot-13 deleted file mode 120000 index 8dd80a3357..0000000000 --- a/Lang/Standard-ML/Rot-13 +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rot-13/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sorting-algorithms-Insertion-sort b/Lang/Standard-ML/Sorting-algorithms-Insertion-sort deleted file mode 120000 index 4d9b5a0868..0000000000 --- a/Lang/Standard-ML/Sorting-algorithms-Insertion-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Insertion-sort/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sum-of-a-series b/Lang/Standard-ML/Sum-of-a-series deleted file mode 120000 index f86ffa2a3c..0000000000 --- a/Lang/Standard-ML/Sum-of-a-series +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sum-of-a-series/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Universal-Turing-machine b/Lang/Standard-ML/Universal-Turing-machine new file mode 120000 index 0000000000..7b25ce082c --- /dev/null +++ b/Lang/Standard-ML/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Standard-ML \ No newline at end of file diff --git a/Lang/Stata/00DESCRIPTION b/Lang/Stata/00DESCRIPTION new file mode 100644 index 0000000000..d96c2c6e51 --- /dev/null +++ b/Lang/Stata/00DESCRIPTION @@ -0,0 +1,3 @@ +{{stub}}{{language|Stata|site=http://www.stata.com/}} + +Stata is a statistical software package created in 1985. It includes a macro language and a matrix language called Mata. \ No newline at end of file diff --git a/Lang/Stata/100-doors b/Lang/Stata/100-doors new file mode 120000 index 0000000000..bb8d3542d2 --- /dev/null +++ b/Lang/Stata/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Stata \ No newline at end of file diff --git a/Lang/Stata/99-Bottles-of-Beer b/Lang/Stata/99-Bottles-of-Beer new file mode 120000 index 0000000000..1f3d2ca4ac --- /dev/null +++ b/Lang/Stata/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Stata \ No newline at end of file diff --git a/Lang/Stata/AKS-test-for-primes b/Lang/Stata/AKS-test-for-primes new file mode 120000 index 0000000000..77047527a8 --- /dev/null +++ b/Lang/Stata/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Stata \ No newline at end of file diff --git a/Lang/Stata/Ackermann-function b/Lang/Stata/Ackermann-function new file mode 120000 index 0000000000..55290b540f --- /dev/null +++ b/Lang/Stata/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Stata \ No newline at end of file diff --git a/Lang/Stata/Arithmetic-Complex b/Lang/Stata/Arithmetic-Complex new file mode 120000 index 0000000000..75da39cb71 --- /dev/null +++ b/Lang/Stata/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Stata \ No newline at end of file diff --git a/Lang/Stata/Arithmetic-geometric-mean b/Lang/Stata/Arithmetic-geometric-mean new file mode 120000 index 0000000000..509008da8d --- /dev/null +++ b/Lang/Stata/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Stata \ No newline at end of file diff --git a/Lang/Stata/Array-concatenation b/Lang/Stata/Array-concatenation new file mode 120000 index 0000000000..00fdd90f67 --- /dev/null +++ b/Lang/Stata/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Stata \ No newline at end of file diff --git a/Lang/Stata/Arrays b/Lang/Stata/Arrays new file mode 120000 index 0000000000..b191c09f13 --- /dev/null +++ b/Lang/Stata/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Stata \ No newline at end of file diff --git a/Lang/Stata/Assertions b/Lang/Stata/Assertions new file mode 120000 index 0000000000..7f61671e3a --- /dev/null +++ b/Lang/Stata/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Stata \ No newline at end of file diff --git a/Lang/Stata/Associative-array-Creation b/Lang/Stata/Associative-array-Creation new file mode 120000 index 0000000000..f8d55d41b5 --- /dev/null +++ b/Lang/Stata/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Stata \ No newline at end of file diff --git a/Lang/Stata/Associative-array-Iteration b/Lang/Stata/Associative-array-Iteration new file mode 120000 index 0000000000..b2e6c5c049 --- /dev/null +++ b/Lang/Stata/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Stata \ No newline at end of file diff --git a/Lang/Stata/Averages-Arithmetic-mean b/Lang/Stata/Averages-Arithmetic-mean new file mode 120000 index 0000000000..be8e345ed9 --- /dev/null +++ b/Lang/Stata/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Stata \ No newline at end of file diff --git a/Lang/Stata/Averages-Mean-angle b/Lang/Stata/Averages-Mean-angle new file mode 120000 index 0000000000..eaa0666145 --- /dev/null +++ b/Lang/Stata/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Stata \ No newline at end of file diff --git a/Lang/Stata/Averages-Median b/Lang/Stata/Averages-Median new file mode 120000 index 0000000000..6c00cae77e --- /dev/null +++ b/Lang/Stata/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Stata \ No newline at end of file diff --git a/Lang/Stata/Averages-Pythagorean-means b/Lang/Stata/Averages-Pythagorean-means new file mode 120000 index 0000000000..95f475352e --- /dev/null +++ b/Lang/Stata/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Stata \ No newline at end of file diff --git a/Lang/Stata/Benfords-law b/Lang/Stata/Benfords-law new file mode 120000 index 0000000000..58c433d52f --- /dev/null +++ b/Lang/Stata/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Stata \ No newline at end of file diff --git a/Lang/Stata/CSV-data-manipulation b/Lang/Stata/CSV-data-manipulation new file mode 120000 index 0000000000..86ef11f3de --- /dev/null +++ b/Lang/Stata/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Stata \ No newline at end of file diff --git a/Lang/Stata/Call-a-foreign-language-function b/Lang/Stata/Call-a-foreign-language-function new file mode 120000 index 0000000000..2c201b308d --- /dev/null +++ b/Lang/Stata/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Stata \ No newline at end of file diff --git a/Lang/Stata/Case-sensitivity-of-identifiers b/Lang/Stata/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..04e2ad0b58 --- /dev/null +++ b/Lang/Stata/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Stata \ No newline at end of file diff --git a/Lang/Stata/Check-that-file-exists b/Lang/Stata/Check-that-file-exists new file mode 120000 index 0000000000..648d509fed --- /dev/null +++ b/Lang/Stata/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Stata \ No newline at end of file diff --git a/Lang/Stata/Cholesky-decomposition b/Lang/Stata/Cholesky-decomposition new file mode 120000 index 0000000000..ac32d727af --- /dev/null +++ b/Lang/Stata/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Stata \ No newline at end of file diff --git a/Lang/Stata/Combinations b/Lang/Stata/Combinations new file mode 120000 index 0000000000..7e98230537 --- /dev/null +++ b/Lang/Stata/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Stata \ No newline at end of file diff --git a/Lang/Stata/Comments b/Lang/Stata/Comments new file mode 120000 index 0000000000..44a0a3f6b1 --- /dev/null +++ b/Lang/Stata/Comments @@ -0,0 +1 @@ +../../Task/Comments/Stata \ No newline at end of file diff --git a/Lang/Stata/Compound-data-type b/Lang/Stata/Compound-data-type new file mode 120000 index 0000000000..1c54375be4 --- /dev/null +++ b/Lang/Stata/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/Stata \ No newline at end of file diff --git a/Lang/Stata/Create-a-file b/Lang/Stata/Create-a-file new file mode 120000 index 0000000000..c0c9ae0f5d --- /dev/null +++ b/Lang/Stata/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Stata \ No newline at end of file diff --git a/Lang/Stata/Create-a-two-dimensional-array-at-runtime b/Lang/Stata/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..1fcbd529e9 --- /dev/null +++ b/Lang/Stata/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Stata \ No newline at end of file diff --git a/Lang/Stata/Create-an-HTML-table b/Lang/Stata/Create-an-HTML-table new file mode 120000 index 0000000000..4a17fd6dc3 --- /dev/null +++ b/Lang/Stata/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Stata \ No newline at end of file diff --git a/Lang/Stata/Date-format b/Lang/Stata/Date-format new file mode 120000 index 0000000000..643ab63a04 --- /dev/null +++ b/Lang/Stata/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Stata \ No newline at end of file diff --git a/Lang/Stata/Day-of-the-week b/Lang/Stata/Day-of-the-week new file mode 120000 index 0000000000..b68cf1871e --- /dev/null +++ b/Lang/Stata/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Stata \ No newline at end of file diff --git a/Lang/Stata/Delete-a-file b/Lang/Stata/Delete-a-file new file mode 120000 index 0000000000..7cfcd9b9a6 --- /dev/null +++ b/Lang/Stata/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Stata \ No newline at end of file diff --git a/Lang/Stata/Dot-product b/Lang/Stata/Dot-product new file mode 120000 index 0000000000..7bdd7d93ea --- /dev/null +++ b/Lang/Stata/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Stata \ No newline at end of file diff --git a/Lang/Stata/Dynamic-variable-names b/Lang/Stata/Dynamic-variable-names new file mode 120000 index 0000000000..308d9989b9 --- /dev/null +++ b/Lang/Stata/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Stata \ No newline at end of file diff --git a/Lang/Stata/Empty-program b/Lang/Stata/Empty-program new file mode 120000 index 0000000000..1ce360f788 --- /dev/null +++ b/Lang/Stata/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Stata \ No newline at end of file diff --git a/Lang/Stata/Empty-string b/Lang/Stata/Empty-string new file mode 120000 index 0000000000..a6c416f687 --- /dev/null +++ b/Lang/Stata/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Stata \ No newline at end of file diff --git a/Lang/Stata/Environment-variables b/Lang/Stata/Environment-variables new file mode 120000 index 0000000000..a51358e781 --- /dev/null +++ b/Lang/Stata/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Stata \ No newline at end of file diff --git a/Lang/Stata/Evaluate-binomial-coefficients b/Lang/Stata/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..6ccb3d4ab7 --- /dev/null +++ b/Lang/Stata/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Stata \ No newline at end of file diff --git a/Lang/Stata/Exceptions b/Lang/Stata/Exceptions new file mode 120000 index 0000000000..e49f29fafa --- /dev/null +++ b/Lang/Stata/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Stata \ No newline at end of file diff --git a/Lang/Stata/Execute-a-system-command b/Lang/Stata/Execute-a-system-command new file mode 120000 index 0000000000..85bfd3b2b4 --- /dev/null +++ b/Lang/Stata/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Stata \ No newline at end of file diff --git a/Lang/Stata/Extreme-floating-point-values b/Lang/Stata/Extreme-floating-point-values new file mode 120000 index 0000000000..08013eedcb --- /dev/null +++ b/Lang/Stata/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Stata \ No newline at end of file diff --git a/Lang/Stata/Factorial b/Lang/Stata/Factorial new file mode 120000 index 0000000000..4ba1a6a025 --- /dev/null +++ b/Lang/Stata/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Stata \ No newline at end of file diff --git a/Lang/Stata/Fast-Fourier-transform b/Lang/Stata/Fast-Fourier-transform new file mode 120000 index 0000000000..1eb37940e5 --- /dev/null +++ b/Lang/Stata/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Stata \ No newline at end of file diff --git a/Lang/Stata/Fibonacci-sequence b/Lang/Stata/Fibonacci-sequence new file mode 120000 index 0000000000..11ee7d8364 --- /dev/null +++ b/Lang/Stata/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Stata \ No newline at end of file diff --git a/Lang/Stata/File-input-output b/Lang/Stata/File-input-output new file mode 120000 index 0000000000..3890ea4bea --- /dev/null +++ b/Lang/Stata/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Stata \ No newline at end of file diff --git a/Lang/Stata/File-size b/Lang/Stata/File-size new file mode 120000 index 0000000000..03a8f527ac --- /dev/null +++ b/Lang/Stata/File-size @@ -0,0 +1 @@ +../../Task/File-size/Stata \ No newline at end of file diff --git a/Lang/Stata/Filter b/Lang/Stata/Filter new file mode 120000 index 0000000000..1c92bd67d1 --- /dev/null +++ b/Lang/Stata/Filter @@ -0,0 +1 @@ +../../Task/Filter/Stata \ No newline at end of file diff --git a/Lang/Stata/Flow-control-structures b/Lang/Stata/Flow-control-structures new file mode 120000 index 0000000000..0cefe065ca --- /dev/null +++ b/Lang/Stata/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/Stata \ No newline at end of file diff --git a/Lang/Stata/Formatted-numeric-output b/Lang/Stata/Formatted-numeric-output new file mode 120000 index 0000000000..62d6a089a4 --- /dev/null +++ b/Lang/Stata/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Stata \ No newline at end of file diff --git a/Lang/Stata/Forward-difference b/Lang/Stata/Forward-difference new file mode 120000 index 0000000000..258e844f70 --- /dev/null +++ b/Lang/Stata/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/Stata \ No newline at end of file diff --git a/Lang/Stata/Generate-lower-case-ASCII-alphabet b/Lang/Stata/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..0337270859 --- /dev/null +++ b/Lang/Stata/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Stata \ No newline at end of file diff --git a/Lang/Stata/Generic-swap b/Lang/Stata/Generic-swap new file mode 120000 index 0000000000..b6201498e7 --- /dev/null +++ b/Lang/Stata/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Stata \ No newline at end of file diff --git a/Lang/Stata/Haversine-formula b/Lang/Stata/Haversine-formula new file mode 120000 index 0000000000..5bfeef992c --- /dev/null +++ b/Lang/Stata/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Stata \ No newline at end of file diff --git a/Lang/Stata/Hello-world-Graphical b/Lang/Stata/Hello-world-Graphical new file mode 120000 index 0000000000..4af76ac97f --- /dev/null +++ b/Lang/Stata/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Stata \ No newline at end of file diff --git a/Lang/Stata/Hello-world-Text b/Lang/Stata/Hello-world-Text new file mode 120000 index 0000000000..94edb1145b --- /dev/null +++ b/Lang/Stata/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Stata \ No newline at end of file diff --git a/Lang/Stata/LU-decomposition b/Lang/Stata/LU-decomposition new file mode 120000 index 0000000000..3b1235c5d6 --- /dev/null +++ b/Lang/Stata/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/Stata \ No newline at end of file diff --git a/Lang/Stata/Leap-year b/Lang/Stata/Leap-year new file mode 120000 index 0000000000..7ab2a949bf --- /dev/null +++ b/Lang/Stata/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Stata \ No newline at end of file diff --git a/Lang/Stata/Loop-over-multiple-arrays-simultaneously b/Lang/Stata/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..058e2da010 --- /dev/null +++ b/Lang/Stata/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Stata \ No newline at end of file diff --git a/Lang/Stata/Loops-Break b/Lang/Stata/Loops-Break new file mode 120000 index 0000000000..8443f63a26 --- /dev/null +++ b/Lang/Stata/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Stata \ No newline at end of file diff --git a/Lang/Stata/Loops-Continue b/Lang/Stata/Loops-Continue new file mode 120000 index 0000000000..2e2cd69f7d --- /dev/null +++ b/Lang/Stata/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Stata \ No newline at end of file diff --git a/Lang/Stata/Loops-Do-while b/Lang/Stata/Loops-Do-while new file mode 120000 index 0000000000..b2aa57606e --- /dev/null +++ b/Lang/Stata/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Stata \ No newline at end of file diff --git a/Lang/Stata/Loops-Downward-for b/Lang/Stata/Loops-Downward-for new file mode 120000 index 0000000000..821a5737b2 --- /dev/null +++ b/Lang/Stata/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Stata \ No newline at end of file diff --git a/Lang/Stata/Loops-For b/Lang/Stata/Loops-For new file mode 120000 index 0000000000..65f4b23470 --- /dev/null +++ b/Lang/Stata/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Stata \ No newline at end of file diff --git a/Lang/Stata/Loops-For-with-a-specified-step b/Lang/Stata/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..687f7c935f --- /dev/null +++ b/Lang/Stata/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Stata \ No newline at end of file diff --git a/Lang/Stata/Loops-Foreach b/Lang/Stata/Loops-Foreach new file mode 120000 index 0000000000..2e3424fbdb --- /dev/null +++ b/Lang/Stata/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Stata \ No newline at end of file diff --git a/Lang/Stata/Loops-Infinite b/Lang/Stata/Loops-Infinite new file mode 120000 index 0000000000..3b2e2e7745 --- /dev/null +++ b/Lang/Stata/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Stata \ No newline at end of file diff --git a/Lang/Stata/Loops-N-plus-one-half b/Lang/Stata/Loops-N-plus-one-half new file mode 120000 index 0000000000..3f58d7bb03 --- /dev/null +++ b/Lang/Stata/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Stata \ No newline at end of file diff --git a/Lang/Stata/Loops-Nested b/Lang/Stata/Loops-Nested new file mode 120000 index 0000000000..a0c322845e --- /dev/null +++ b/Lang/Stata/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Stata \ No newline at end of file diff --git a/Lang/Stata/Loops-While b/Lang/Stata/Loops-While new file mode 120000 index 0000000000..2308b40866 --- /dev/null +++ b/Lang/Stata/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Stata \ No newline at end of file diff --git a/Lang/Stata/Monte-Carlo-methods b/Lang/Stata/Monte-Carlo-methods new file mode 120000 index 0000000000..3b064f8422 --- /dev/null +++ b/Lang/Stata/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/Stata \ No newline at end of file diff --git a/Lang/Stata/N-queens-problem b/Lang/Stata/N-queens-problem new file mode 120000 index 0000000000..845e04efa0 --- /dev/null +++ b/Lang/Stata/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Stata \ No newline at end of file diff --git a/Lang/Stata/Permutations b/Lang/Stata/Permutations new file mode 120000 index 0000000000..757eb2034a --- /dev/null +++ b/Lang/Stata/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Stata \ No newline at end of file diff --git a/Lang/Stata/Plot-coordinate-pairs b/Lang/Stata/Plot-coordinate-pairs new file mode 120000 index 0000000000..fdc9de3264 --- /dev/null +++ b/Lang/Stata/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Stata \ No newline at end of file diff --git a/Lang/Stata/Polynomial-regression b/Lang/Stata/Polynomial-regression new file mode 120000 index 0000000000..031633de7c --- /dev/null +++ b/Lang/Stata/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Stata \ No newline at end of file diff --git a/Lang/Stata/QR-decomposition b/Lang/Stata/QR-decomposition new file mode 120000 index 0000000000..2c243948a4 --- /dev/null +++ b/Lang/Stata/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/Stata \ No newline at end of file diff --git a/Lang/Stata/README b/Lang/Stata/README new file mode 100644 index 0000000000..252b52cb55 --- /dev/null +++ b/Lang/Stata/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Stata diff --git a/Lang/Stata/Random-numbers b/Lang/Stata/Random-numbers new file mode 120000 index 0000000000..0d332cce9f --- /dev/null +++ b/Lang/Stata/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Stata \ No newline at end of file diff --git a/Lang/Stata/Read-a-specific-line-from-a-file b/Lang/Stata/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..3ce6dcb6dd --- /dev/null +++ b/Lang/Stata/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Stata \ No newline at end of file diff --git a/Lang/Stata/Read-entire-file b/Lang/Stata/Read-entire-file new file mode 120000 index 0000000000..65946918f0 --- /dev/null +++ b/Lang/Stata/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Stata \ No newline at end of file diff --git a/Lang/Stata/Real-constants-and-functions b/Lang/Stata/Real-constants-and-functions new file mode 120000 index 0000000000..b34598da26 --- /dev/null +++ b/Lang/Stata/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Stata \ No newline at end of file diff --git a/Lang/Stata/Regular-expressions b/Lang/Stata/Regular-expressions new file mode 120000 index 0000000000..58d52f0874 --- /dev/null +++ b/Lang/Stata/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Stata \ No newline at end of file diff --git a/Lang/Stata/Remove-duplicate-elements b/Lang/Stata/Remove-duplicate-elements new file mode 120000 index 0000000000..414d4ea152 --- /dev/null +++ b/Lang/Stata/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Stata \ No newline at end of file diff --git a/Lang/Stata/Remove-lines-from-a-file b/Lang/Stata/Remove-lines-from-a-file new file mode 120000 index 0000000000..633397f16e --- /dev/null +++ b/Lang/Stata/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Stata \ No newline at end of file diff --git a/Lang/Stata/Rename-a-file b/Lang/Stata/Rename-a-file new file mode 120000 index 0000000000..49e55740af --- /dev/null +++ b/Lang/Stata/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/Stata \ No newline at end of file diff --git a/Lang/Stata/Repeat-a-string b/Lang/Stata/Repeat-a-string new file mode 120000 index 0000000000..c136e3c995 --- /dev/null +++ b/Lang/Stata/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Stata \ No newline at end of file diff --git a/Lang/Stata/Reverse-a-string b/Lang/Stata/Reverse-a-string new file mode 120000 index 0000000000..407f019e4e --- /dev/null +++ b/Lang/Stata/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Stata \ No newline at end of file diff --git a/Lang/Stata/Roots-of-a-quadratic-function b/Lang/Stata/Roots-of-a-quadratic-function new file mode 120000 index 0000000000..b0147f8388 --- /dev/null +++ b/Lang/Stata/Roots-of-a-quadratic-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-quadratic-function/Stata \ No newline at end of file diff --git a/Lang/Stata/Sieve-of-Eratosthenes b/Lang/Stata/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..53c8c8a2c9 --- /dev/null +++ b/Lang/Stata/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Stata \ No newline at end of file diff --git a/Lang/Stata/Sleep b/Lang/Stata/Sleep new file mode 120000 index 0000000000..2a797f797c --- /dev/null +++ b/Lang/Stata/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Stata \ No newline at end of file diff --git a/Lang/Stata/Sort-an-integer-array b/Lang/Stata/Sort-an-integer-array new file mode 120000 index 0000000000..5ae7c5616c --- /dev/null +++ b/Lang/Stata/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Stata \ No newline at end of file diff --git a/Lang/Stata/Soundex b/Lang/Stata/Soundex new file mode 120000 index 0000000000..a3e71f261f --- /dev/null +++ b/Lang/Stata/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Stata \ No newline at end of file diff --git a/Lang/Stata/Statistics-Basic b/Lang/Stata/Statistics-Basic new file mode 120000 index 0000000000..c9f422c418 --- /dev/null +++ b/Lang/Stata/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Stata \ No newline at end of file diff --git a/Lang/Stata/Stem-and-leaf-plot b/Lang/Stata/Stem-and-leaf-plot new file mode 120000 index 0000000000..ffa212c381 --- /dev/null +++ b/Lang/Stata/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Stata \ No newline at end of file diff --git a/Lang/Stata/String-case b/Lang/Stata/String-case new file mode 120000 index 0000000000..971d60af58 --- /dev/null +++ b/Lang/Stata/String-case @@ -0,0 +1 @@ +../../Task/String-case/Stata \ No newline at end of file diff --git a/Lang/Stata/String-length b/Lang/Stata/String-length new file mode 120000 index 0000000000..2e9a8c9ee7 --- /dev/null +++ b/Lang/Stata/String-length @@ -0,0 +1 @@ +../../Task/String-length/Stata \ No newline at end of file diff --git a/Lang/Stata/Sum-multiples-of-3-and-5 b/Lang/Stata/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..5aea12a670 --- /dev/null +++ b/Lang/Stata/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Stata \ No newline at end of file diff --git a/Lang/Stata/Time-a-function b/Lang/Stata/Time-a-function new file mode 120000 index 0000000000..63bd29606b --- /dev/null +++ b/Lang/Stata/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Stata \ No newline at end of file diff --git a/Lang/Stata/Top-rank-per-group b/Lang/Stata/Top-rank-per-group new file mode 120000 index 0000000000..db33d36c78 --- /dev/null +++ b/Lang/Stata/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Stata \ No newline at end of file diff --git a/Lang/Stata/Trigonometric-functions b/Lang/Stata/Trigonometric-functions new file mode 120000 index 0000000000..3c0c113f0a --- /dev/null +++ b/Lang/Stata/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Stata \ No newline at end of file diff --git a/Lang/Stata/Unix-ls b/Lang/Stata/Unix-ls new file mode 120000 index 0000000000..f7be0af373 --- /dev/null +++ b/Lang/Stata/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Stata \ No newline at end of file diff --git a/Lang/Stata/Van-der-Corput-sequence b/Lang/Stata/Van-der-Corput-sequence new file mode 120000 index 0000000000..9c5197c864 --- /dev/null +++ b/Lang/Stata/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Stata \ No newline at end of file diff --git a/Lang/Stata/Vector-products b/Lang/Stata/Vector-products new file mode 120000 index 0000000000..70a16aed82 --- /dev/null +++ b/Lang/Stata/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Stata \ No newline at end of file diff --git a/Lang/Stata/Zero-to-the-zero-power b/Lang/Stata/Zero-to-the-zero-power new file mode 120000 index 0000000000..086177695b --- /dev/null +++ b/Lang/Stata/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Stata \ No newline at end of file diff --git a/Lang/SuperCollider/Enforced-immutability b/Lang/SuperCollider/Enforced-immutability new file mode 120000 index 0000000000..53588f99d2 --- /dev/null +++ b/Lang/SuperCollider/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/SuperCollider \ No newline at end of file diff --git a/Lang/SuperCollider/Pick-random-element b/Lang/SuperCollider/Pick-random-element new file mode 120000 index 0000000000..516d9920dd --- /dev/null +++ b/Lang/SuperCollider/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/SuperCollider \ No newline at end of file diff --git a/Lang/SuperCollider/Variables b/Lang/SuperCollider/Variables new file mode 120000 index 0000000000..12806325ed --- /dev/null +++ b/Lang/SuperCollider/Variables @@ -0,0 +1 @@ +../../Task/Variables/SuperCollider \ No newline at end of file diff --git a/Lang/SuperCollider/Y-combinator b/Lang/SuperCollider/Y-combinator new file mode 120000 index 0000000000..8ea4b3514b --- /dev/null +++ b/Lang/SuperCollider/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/SuperCollider \ No newline at end of file diff --git a/Lang/Swift/Arithmetic-Integer b/Lang/Swift/Arithmetic-Integer new file mode 120000 index 0000000000..fbe1bcc57e --- /dev/null +++ b/Lang/Swift/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Swift \ No newline at end of file diff --git a/Lang/Swift/Arithmetic-geometric-mean b/Lang/Swift/Arithmetic-geometric-mean new file mode 120000 index 0000000000..4df6b02f39 --- /dev/null +++ b/Lang/Swift/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Swift \ No newline at end of file diff --git a/Lang/Swift/Benfords-law b/Lang/Swift/Benfords-law new file mode 120000 index 0000000000..0afee02a32 --- /dev/null +++ b/Lang/Swift/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Swift \ No newline at end of file diff --git a/Lang/Swift/Caesar-cipher b/Lang/Swift/Caesar-cipher new file mode 120000 index 0000000000..b2a4e250a7 --- /dev/null +++ b/Lang/Swift/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Swift \ No newline at end of file diff --git a/Lang/Swift/Chinese-remainder-theorem b/Lang/Swift/Chinese-remainder-theorem new file mode 120000 index 0000000000..3b97b21a7d --- /dev/null +++ b/Lang/Swift/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Swift \ No newline at end of file diff --git a/Lang/Swift/Find-common-directory-path b/Lang/Swift/Find-common-directory-path new file mode 120000 index 0000000000..2303e70009 --- /dev/null +++ b/Lang/Swift/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Swift \ No newline at end of file diff --git a/Lang/Swift/Find-the-last-Sunday-of-each-month b/Lang/Swift/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..9f9bae1f3d --- /dev/null +++ b/Lang/Swift/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Swift \ No newline at end of file diff --git a/Lang/Swift/Last-Friday-of-each-month b/Lang/Swift/Last-Friday-of-each-month new file mode 120000 index 0000000000..3985a258f4 --- /dev/null +++ b/Lang/Swift/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Swift \ No newline at end of file diff --git a/Lang/Swift/Middle-three-digits b/Lang/Swift/Middle-three-digits new file mode 120000 index 0000000000..dcc29413ba --- /dev/null +++ b/Lang/Swift/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Swift \ No newline at end of file diff --git a/Lang/Swift/Move-to-front-algorithm b/Lang/Swift/Move-to-front-algorithm new file mode 120000 index 0000000000..597aa2e919 --- /dev/null +++ b/Lang/Swift/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Swift \ No newline at end of file diff --git a/Lang/Swift/Narcissist b/Lang/Swift/Narcissist new file mode 120000 index 0000000000..9ed1a821de --- /dev/null +++ b/Lang/Swift/Narcissist @@ -0,0 +1 @@ +../../Task/Narcissist/Swift \ No newline at end of file diff --git a/Lang/Swift/Pascals-triangle b/Lang/Swift/Pascals-triangle new file mode 120000 index 0000000000..108cc10598 --- /dev/null +++ b/Lang/Swift/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Swift \ No newline at end of file diff --git a/Lang/Swift/Percentage-difference-between-images b/Lang/Swift/Percentage-difference-between-images new file mode 120000 index 0000000000..b7bf1021bf --- /dev/null +++ b/Lang/Swift/Percentage-difference-between-images @@ -0,0 +1 @@ +../../Task/Percentage-difference-between-images/Swift \ No newline at end of file diff --git a/Lang/Swift/Phrase-reversals b/Lang/Swift/Phrase-reversals new file mode 120000 index 0000000000..789955af09 --- /dev/null +++ b/Lang/Swift/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Swift \ No newline at end of file diff --git a/Lang/Swift/Singleton b/Lang/Swift/Singleton new file mode 120000 index 0000000000..5f1ce38cd9 --- /dev/null +++ b/Lang/Swift/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Swift \ No newline at end of file diff --git a/Lang/Swift/Singly-linked-list-Element-definition b/Lang/Swift/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..e1468e7cf8 --- /dev/null +++ b/Lang/Swift/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Swift \ No newline at end of file diff --git a/Lang/Swift/Sum-multiples-of-3-and-5 b/Lang/Swift/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..73d4c0ef2a --- /dev/null +++ b/Lang/Swift/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Swift \ No newline at end of file diff --git a/Lang/Swift/Temperature-conversion b/Lang/Swift/Temperature-conversion new file mode 120000 index 0000000000..19ae2f48cf --- /dev/null +++ b/Lang/Swift/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Swift \ No newline at end of file diff --git a/Lang/Swift/Tic-tac-toe b/Lang/Swift/Tic-tac-toe new file mode 120000 index 0000000000..12c0af1f11 --- /dev/null +++ b/Lang/Swift/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Swift \ No newline at end of file diff --git a/Lang/Swift/Xiaolin-Wus-line-algorithm b/Lang/Swift/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..a2945f9667 --- /dev/null +++ b/Lang/Swift/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Swift \ No newline at end of file diff --git a/Lang/SystemVerilog/Solve-a-Numbrix-puzzle b/Lang/SystemVerilog/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..e955d41920 --- /dev/null +++ b/Lang/SystemVerilog/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/SystemVerilog \ No newline at end of file diff --git a/Lang/SystemVerilog/Sudoku b/Lang/SystemVerilog/Sudoku new file mode 120000 index 0000000000..d71b47ff30 --- /dev/null +++ b/Lang/SystemVerilog/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/SystemVerilog \ No newline at end of file diff --git a/Lang/TI-83-BASIC/100-doors b/Lang/TI-83-BASIC/100-doors deleted file mode 120000 index 75b0e897b8..0000000000 --- a/Lang/TI-83-BASIC/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/99-Bottles-of-Beer b/Lang/TI-83-BASIC/99-Bottles-of-Beer deleted file mode 120000 index cb89e8fc7e..0000000000 --- a/Lang/TI-83-BASIC/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Ackermann-function b/Lang/TI-83-BASIC/Ackermann-function new file mode 120000 index 0000000000..d6099a65ff --- /dev/null +++ b/Lang/TI-83-BASIC/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Conways-Game-of-Life b/Lang/TI-83-BASIC/Conways-Game-of-Life deleted file mode 120000 index bd16eb3489..0000000000 --- a/Lang/TI-83-BASIC/Conways-Game-of-Life +++ /dev/null @@ -1 +0,0 @@ -../../Task/Conways-Game-of-Life/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/FizzBuzz b/Lang/TI-83-BASIC/FizzBuzz deleted file mode 120000 index 48a9806259..0000000000 --- a/Lang/TI-83-BASIC/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Loops-For b/Lang/TI-83-BASIC/Loops-For deleted file mode 120000 index 06f21585d2..0000000000 --- a/Lang/TI-83-BASIC/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Program-termination b/Lang/TI-83-BASIC/Program-termination deleted file mode 120000 index 21f7ae3833..0000000000 --- a/Lang/TI-83-BASIC/Program-termination +++ /dev/null @@ -1 +0,0 @@ -../../Task/Program-termination/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/String-case b/Lang/TI-83-BASIC/String-case deleted file mode 120000 index b15fafd207..0000000000 --- a/Lang/TI-83-BASIC/String-case +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-case/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Sum-and-product-of-an-array b/Lang/TI-83-BASIC/Sum-and-product-of-an-array new file mode 120000 index 0000000000..45a2ec1b9d --- /dev/null +++ b/Lang/TI-83-BASIC/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Sum-of-a-series b/Lang/TI-83-BASIC/Sum-of-a-series new file mode 120000 index 0000000000..341a2af929 --- /dev/null +++ b/Lang/TI-83-BASIC/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/99-Bottles-of-Beer b/Lang/TI-89-BASIC/99-Bottles-of-Beer deleted file mode 120000 index 2707cf1558..0000000000 --- a/Lang/TI-89-BASIC/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/Conways-Game-of-Life b/Lang/TI-89-BASIC/Conways-Game-of-Life deleted file mode 120000 index 8133d9e29c..0000000000 --- a/Lang/TI-89-BASIC/Conways-Game-of-Life +++ /dev/null @@ -1 +0,0 @@ -../../Task/Conways-Game-of-Life/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/Loops-Continue b/Lang/TI-89-BASIC/Loops-Continue deleted file mode 120000 index 5f2ea091fd..0000000000 --- a/Lang/TI-89-BASIC/Loops-Continue +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Continue/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/Loops-Foreach b/Lang/TI-89-BASIC/Loops-Foreach deleted file mode 120000 index 134cd738e4..0000000000 --- a/Lang/TI-89-BASIC/Loops-Foreach +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Foreach/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TUSCRIPT/Character-matching b/Lang/TUSCRIPT/Character-matching deleted file mode 120000 index 1097158f35..0000000000 --- a/Lang/TUSCRIPT/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/File-input-output b/Lang/TUSCRIPT/File-input-output new file mode 120000 index 0000000000..79c9a3cfcf --- /dev/null +++ b/Lang/TUSCRIPT/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/I-before-E-except-after-C b/Lang/TUSCRIPT/I-before-E-except-after-C new file mode 120000 index 0000000000..0797d34238 --- /dev/null +++ b/Lang/TUSCRIPT/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Levenshtein-distance b/Lang/TUSCRIPT/Levenshtein-distance new file mode 120000 index 0000000000..5671b787d9 --- /dev/null +++ b/Lang/TUSCRIPT/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Rosetta-Code-Count-examples b/Lang/TUSCRIPT/Rosetta-Code-Count-examples deleted file mode 120000 index 593f1db983..0000000000 --- a/Lang/TUSCRIPT/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Rosetta-Code-Rank-languages-by-popularity b/Lang/TUSCRIPT/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 5c73e329b6..0000000000 --- a/Lang/TUSCRIPT/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/TUSCRIPT \ No newline at end of file diff --git a/Lang/TXR/A+B b/Lang/TXR/A+B deleted file mode 120000 index 65cb47f747..0000000000 --- a/Lang/TXR/A+B +++ /dev/null @@ -1 +0,0 @@ -../../Task/A+B/TXR \ No newline at end of file diff --git a/Lang/TXR/Character-matching b/Lang/TXR/Character-matching deleted file mode 120000 index f705e73ba6..0000000000 --- a/Lang/TXR/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/TXR \ No newline at end of file diff --git a/Lang/TXR/Comma-quibbling b/Lang/TXR/Comma-quibbling new file mode 120000 index 0000000000..03c46d0d54 --- /dev/null +++ b/Lang/TXR/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/TXR \ No newline at end of file diff --git a/Lang/TXR/Determine-if-only-one-instance-is-running b/Lang/TXR/Determine-if-only-one-instance-is-running new file mode 120000 index 0000000000..3474787cbf --- /dev/null +++ b/Lang/TXR/Determine-if-only-one-instance-is-running @@ -0,0 +1 @@ +../../Task/Determine-if-only-one-instance-is-running/TXR \ No newline at end of file diff --git a/Lang/TXR/File-input-output b/Lang/TXR/File-input-output new file mode 120000 index 0000000000..f6d024097b --- /dev/null +++ b/Lang/TXR/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/TXR \ No newline at end of file diff --git a/Lang/TXR/Hello-world-Graphical b/Lang/TXR/Hello-world-Graphical new file mode 120000 index 0000000000..6e3ab65699 --- /dev/null +++ b/Lang/TXR/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/TXR \ No newline at end of file diff --git a/Lang/TXR/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/TXR/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..b29db509c7 --- /dev/null +++ b/Lang/TXR/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/TXR \ No newline at end of file diff --git a/Lang/TXR/Least-common-multiple b/Lang/TXR/Least-common-multiple new file mode 120000 index 0000000000..42eff7a8a8 --- /dev/null +++ b/Lang/TXR/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/TXR \ No newline at end of file diff --git a/Lang/TXR/Terminal-control-Positional-read b/Lang/TXR/Terminal-control-Positional-read new file mode 120000 index 0000000000..855cc8ce4c --- /dev/null +++ b/Lang/TXR/Terminal-control-Positional-read @@ -0,0 +1 @@ +../../Task/Terminal-control-Positional-read/TXR \ No newline at end of file diff --git a/Lang/TXR/Use-another-language-to-call-a-function b/Lang/TXR/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..e43dc5bc15 --- /dev/null +++ b/Lang/TXR/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/TXR \ No newline at end of file diff --git a/Lang/TXR/Variable-length-quantity b/Lang/TXR/Variable-length-quantity deleted file mode 120000 index df05f2260c..0000000000 --- a/Lang/TXR/Variable-length-quantity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Variable-length-quantity/TXR \ No newline at end of file diff --git a/Lang/TXR/Variable-size-Get b/Lang/TXR/Variable-size-Get new file mode 120000 index 0000000000..d58fa448c2 --- /dev/null +++ b/Lang/TXR/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/TXR \ No newline at end of file diff --git a/Lang/TXR/Variable-size-Set b/Lang/TXR/Variable-size-Set new file mode 120000 index 0000000000..51bd673b70 --- /dev/null +++ b/Lang/TXR/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/TXR \ No newline at end of file diff --git a/Lang/TXR/Walk-a-directory-Non-recursively b/Lang/TXR/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..03ee61ab8a --- /dev/null +++ b/Lang/TXR/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/TXR \ No newline at end of file diff --git a/Lang/TXR/Walk-a-directory-Recursively b/Lang/TXR/Walk-a-directory-Recursively new file mode 120000 index 0000000000..7c342253f3 --- /dev/null +++ b/Lang/TXR/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/TXR \ No newline at end of file diff --git a/Lang/TXR/Window-creation b/Lang/TXR/Window-creation new file mode 120000 index 0000000000..a6df3e2d63 --- /dev/null +++ b/Lang/TXR/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/TXR \ No newline at end of file diff --git a/Lang/Tcl/99-Bottles-of-Beer b/Lang/Tcl/99-Bottles-of-Beer deleted file mode 120000 index e5219c564e..0000000000 --- a/Lang/Tcl/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Calendar---for-real-programmers b/Lang/Tcl/Calendar---for-real-programmers deleted file mode 120000 index d49bf551a1..0000000000 --- a/Lang/Tcl/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Character-matching b/Lang/Tcl/Character-matching deleted file mode 120000 index 6b64a025e3..0000000000 --- a/Lang/Tcl/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/Tcl \ No newline at end of file diff --git a/Lang/Tcl/File-IO b/Lang/Tcl/File-IO deleted file mode 120000 index 0f1da9084e..0000000000 --- a/Lang/Tcl/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/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/Mutex b/Lang/Tcl/Mutex deleted file mode 120000 index cacc864612..0000000000 --- a/Lang/Tcl/Mutex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutex/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Rosetta-Code-Count-examples b/Lang/Tcl/Rosetta-Code-Count-examples deleted file mode 120000 index 36cc31efcb..0000000000 --- a/Lang/Tcl/Rosetta-Code-Count-examples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Count-examples/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Rosetta-Code-Find-unimplemented-tasks b/Lang/Tcl/Rosetta-Code-Find-unimplemented-tasks deleted file mode 120000 index 22fbcdfd56..0000000000 --- a/Lang/Tcl/Rosetta-Code-Find-unimplemented-tasks +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Find-unimplemented-tasks/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Rosetta-Code-Fix-code-tags b/Lang/Tcl/Rosetta-Code-Fix-code-tags deleted file mode 120000 index 6ad7902ad5..0000000000 --- a/Lang/Tcl/Rosetta-Code-Fix-code-tags +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Fix-code-tags/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Rosetta-Code-Rank-languages-by-popularity b/Lang/Tcl/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index 134eb7c0c3..0000000000 --- a/Lang/Tcl/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Special-variables b/Lang/Tcl/Special-variables deleted file mode 120000 index 7a1c2350c6..0000000000 --- a/Lang/Tcl/Special-variables +++ /dev/null @@ -1 +0,0 @@ -../../Task/Special-variables/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Standard-deviation b/Lang/Tcl/Standard-deviation deleted file mode 120000 index 32fdc71153..0000000000 --- a/Lang/Tcl/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Tcl \ No newline at end of file diff --git a/Lang/TechBASIC/00DESCRIPTION b/Lang/TechBASIC/00DESCRIPTION new file mode 100644 index 0000000000..9783def5cf --- /dev/null +++ b/Lang/TechBASIC/00DESCRIPTION @@ -0,0 +1,107 @@ +=={{header|TechBASIC}}== +{{language|TechBASIC +|exec=interpreted/compiled +|site=http://www.byteworks.us/Byte_Works/techBASIC.html +|parampass=both +|tags=techBASIC}} +{{language programming paradigm|Procedural}} +{{language programming paradigm|Event-driven}} +{{language programming paradigm|Object-oriented}} +{{implementation|BASIC}} + +

Write Scientific and Educational Programs on the iPhone/iPad

+ +== '''Overview''' == + +techBASIC has been around since 2011 and is a comprehensive software development and technical computing environment for programming, data collection, displaying sophisticated interactive graphics and analyzing data. + +techBASIC is a powerful matrix-rich version of the famously easy to use BASIC programming language. Their built-in help system, reference manual and web-based tutorials make it easy to start using techBASIC for real problems in programming, education and in the professional lab right away. + +And once you finish your app in techBASIC, compile it with techBASIC App Builder and XCode on your Macintosh to create a stand-alone app. You can share that app with others using Ad Hoc distribution or publish it on Apple’s App Store. + + +== '''Building iPhone & iPad Electronic Projects''' == + +Buy ready-built or DIY electronic kits, design, invent your own sensors, data collectors, a comprehensive scientific development environment right on your mobile device. Connect to internal and external sensors using techBASIC’s built-in commands. + +techBASIC brings the power of a desktop computer to your iPhone/iPad for programming, collecting and analyzing data, and visualizing and manipulating stunning 3D graphics. It’s a robust implementation of the famously easy to use BASIC Programming Language with specialized array and matrix commands. + +Scientists and engineers can collect and analyze complex data easily and accurately with techBASIC. The built-in floating-point libraries insure calculations are precise. Special classes make it easy to perform complex array and matrix calculations. The graphing capabilities allow you to display and interact with your data in new and amazing ways. And, data can be moved easily to and from your desktop computer. + +A new book from O’Reilly features techBASIC, showing how to access real-world Arduino, sensor and Bluetooth Low Energy apps in techBASIC. The book is available in print and ebook format.
 +Key Features: + + +== Collecting/Analyzing Data == +
    +
  • Send and receive data from Bluetooth LE devices (only on hardware that supports Bluetooth LE)--control the Internet of Things right from your iPhone or iPadCollect, analyze and display data right on your iPhone/iPad
    +
  • Use Bluetooth LE or WiFi to connect to Arduino using the Red Bear Arduino BLE Bridge or Roving Networks WiFly
    +
  • Collect data from outside sensors using HiJack
    +
  • Access to the accelerometer, magnetometer and gyroscope
    +
  • Get the current location and heading
    +
  • Analyze photos and images pixel-by-pixel
    +
  • Supports TCP/IP, HTTP and FTP for accessing information via WiFi connections

    +
  • Numeric integration for calculus
    +
  • Fit curves to data with polynomial and linear regression
    +
  • Solve simultaneous equations with matrix operations like LU decomposition
    +
  • Special functions for statistics +
+

+ +== BASIC Programming == +
    +
  • Array and matrix commands like matrix inversion, determinants, matrix arithmetic and more.
    +
  • Step and trace debugger
    +
  • Set breakpoints with a tap
    +
  • See current variables, both local and global
    +
  • See everything in a variable, even large matrices
    +
  • 43 statements, 41 functions
    +
  • 35 classes with 362 methods, including GUI, graphics, sensor data collection and matrices +
+

+ +== Create Stunning GUIs and Use all standard iOS controls == +
    +
  • Activity indicators
    +
  • Buttons
    +
  • Date pickers
    +
  • Images
    +
  • Labels
    +
  • Map views
    +
  • Pickers
    +
  • Progress bars
    +
  • Segmented controls
    +
  • Sliders
    +
  • Steppers
    +
  • Switches
    +
  • Tables
    +
  • Text fields
    +
  • Text views
    +
  • Web pages
    +
  • Add alerts
    +
  • Send emails
    +
  • Take photos or grab pictures from the photo library
 +
+

+ +== Graphing/Plotting Capabilities == +
    +
  • Create a plot with only a few lines of code
    +
  • Pan and zoom plots with swipes and pinches
    +
  • Rotate 3D plots along an arbitrary axis
    +
  • Supports 2D or 3D Cartesian axis
    +
  • Polar, spherical and cylindrical axis
    +
  • Plot general surfaces
    +
  • Create error bars in 2 or 3 dimensions
    +
  • 2D and 3D vector plots
    +
  • Add custom callouts
 +
+

+ +Apps for people who think.™ +

+
'''techBASIC''' initially introduced to Rosetta Code on January 29, 2017 by [http://rosettacode.org/wiki/User:George_McGinn]
techBASIC and the techBASIC logo are owned by Byte Works, Inc. +Text owned and copyrighted ©2017 by Byte Works, Inc. All Rights Reserved +---- +
+ \ No newline at end of file diff --git a/Lang/TechBASIC/Haversine-formula b/Lang/TechBASIC/Haversine-formula new file mode 120000 index 0000000000..86735dfd0f --- /dev/null +++ b/Lang/TechBASIC/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/TechBASIC \ No newline at end of file diff --git a/Lang/TechBASIC/README b/Lang/TechBASIC/README new file mode 100644 index 0000000000..af984ad717 --- /dev/null +++ b/Lang/TechBASIC/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:TechBASIC diff --git a/Lang/TechBASIC/Roman-numerals-Decode b/Lang/TechBASIC/Roman-numerals-Decode new file mode 120000 index 0000000000..7ee6864c79 --- /dev/null +++ b/Lang/TechBASIC/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/TechBASIC \ No newline at end of file diff --git a/Lang/Toka/File-IO b/Lang/Toka/File-IO deleted file mode 120000 index 561e4f453f..0000000000 --- a/Lang/Toka/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Toka \ No newline at end of file diff --git a/Lang/TransFORTH/00DESCRIPTION b/Lang/TransFORTH/00DESCRIPTION new file mode 100644 index 0000000000..ce530078cb --- /dev/null +++ b/Lang/TransFORTH/00DESCRIPTION @@ -0,0 +1,2 @@ +{{stub}}{{language|TransFORTH}} +TransFORTH (or TransFORTH ][) is a compiled language and interactive programming environment for the Apple II computer, developed by Paul Lutus and released in 1981. It may be regarded either as a somewhat divergent dialect of Forth or as a separate language with clear Forth ancestry. \ No newline at end of file diff --git a/Lang/TransFORTH/Factorial b/Lang/TransFORTH/Factorial new file mode 120000 index 0000000000..022978d093 --- /dev/null +++ b/Lang/TransFORTH/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/TransFORTH \ No newline at end of file diff --git a/Lang/TransFORTH/FizzBuzz b/Lang/TransFORTH/FizzBuzz new file mode 120000 index 0000000000..d6698a44f4 --- /dev/null +++ b/Lang/TransFORTH/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/TransFORTH \ No newline at end of file diff --git a/Lang/TransFORTH/Hello-world-Text b/Lang/TransFORTH/Hello-world-Text new file mode 120000 index 0000000000..fd34390df5 --- /dev/null +++ b/Lang/TransFORTH/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/TransFORTH \ No newline at end of file diff --git a/Lang/TransFORTH/Loops-For b/Lang/TransFORTH/Loops-For new file mode 120000 index 0000000000..d5ebce80f1 --- /dev/null +++ b/Lang/TransFORTH/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/TransFORTH \ No newline at end of file diff --git a/Lang/TransFORTH/README b/Lang/TransFORTH/README new file mode 100644 index 0000000000..7eff73d0db --- /dev/null +++ b/Lang/TransFORTH/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:TransFORTH diff --git a/Lang/Transact-SQL/Loops-Break b/Lang/Transact-SQL/Loops-Break new file mode 120000 index 0000000000..2e057cc2b9 --- /dev/null +++ b/Lang/Transact-SQL/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Transact-SQL \ No newline at end of file diff --git a/Lang/Transact-SQL/Loops-Continue b/Lang/Transact-SQL/Loops-Continue new file mode 120000 index 0000000000..45f5190279 --- /dev/null +++ b/Lang/Transact-SQL/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Transact-SQL \ No newline at end of file diff --git a/Lang/Transact-SQL/Loops-While b/Lang/Transact-SQL/Loops-While new file mode 120000 index 0000000000..73ca1a087f --- /dev/null +++ b/Lang/Transact-SQL/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Transact-SQL \ No newline at end of file diff --git a/Lang/Transact-SQL/Luhn-test-of-credit-card-numbers b/Lang/Transact-SQL/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..4a93546bdb --- /dev/null +++ b/Lang/Transact-SQL/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Transact-SQL \ No newline at end of file diff --git a/Lang/True-BASIC/00DESCRIPTION b/Lang/True-BASIC/00DESCRIPTION index 5e988b9b09..765d6ad0cc 100644 --- a/Lang/True-BASIC/00DESCRIPTION +++ b/Lang/True-BASIC/00DESCRIPTION @@ -1,3 +1,9 @@ -{{stub}} {{language -|site=http://www.truebasic.com/}} \ No newline at end of file +|exec=interpreted +|tags=basic,TrueBasic +|site=http://www.truebasic.com/}} +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. + +[[:Category:BASIC Implementations]] lists the many implementations of BASIC in Rosetta Code. \ No newline at end of file diff --git a/Lang/True-BASIC/100-doors b/Lang/True-BASIC/100-doors new file mode 120000 index 0000000000..0f58c3a043 --- /dev/null +++ b/Lang/True-BASIC/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Hello-world-Text b/Lang/True-BASIC/Hello-world-Text new file mode 120000 index 0000000000..b185af5f1b --- /dev/null +++ b/Lang/True-BASIC/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/True-BASIC \ No newline at end of file diff --git a/Lang/TypeScript/Averages-Arithmetic-mean b/Lang/TypeScript/Averages-Arithmetic-mean new file mode 120000 index 0000000000..609de44364 --- /dev/null +++ b/Lang/TypeScript/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/TypeScript \ No newline at end of file diff --git a/Lang/TypeScript/Identity-matrix b/Lang/TypeScript/Identity-matrix new file mode 120000 index 0000000000..05452f1bb1 --- /dev/null +++ b/Lang/TypeScript/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/TypeScript \ No newline at end of file diff --git a/Lang/UNIX-Shell/00DESCRIPTION b/Lang/UNIX-Shell/00DESCRIPTION index 82111d1836..6d96656780 100644 --- a/Lang/UNIX-Shell/00DESCRIPTION +++ b/Lang/UNIX-Shell/00DESCRIPTION @@ -6,7 +6,7 @@ =Implementation= -There are many UNIX Shells and most of them can be categorized into two families. For purposes of the Rosetta Code, all examples are in Bourne-compatible syntax. The other family of shells, with a markedly different syntax, are ''csh'' ([[:Category:C Shell|C Shell]]) and it's ''tcsh'' (Tenex C Shell) "clone." Common Bourne compatible shells include the original [[Bourne Shell]] (''/bin/sh'' on most versions of UNIX), the GNU [[Bourne Again SHell]] (''bash'' --- which is linked to ''/bin/sh'' on many distributions of [[Linux]], making it their default shell), the [[Korn Shell]] (''ksh''), the [[Public Domain Korn SHell]] (''pdksh''), the [[Almquist SHell]] (''ash'') and the [[Debian Almquist SHell]] (''dash'') and the [[Z SHell]] (''zsh''). +There are many UNIX Shells and most of them can be categorized into two families. For purposes of the Rosetta Code, all examples are in Bourne-compatible syntax. The other family of shells, with a markedly different syntax, are ''csh'' ([[:Category:C Shell|C Shell]]) and its ''tcsh'' (Tenex C Shell) "clone." Common Bourne compatible shells include the original [[Bourne Shell]] (''/bin/sh'' on most versions of UNIX), the GNU [[Bourne Again SHell]] (''bash'' --- which is linked to ''/bin/sh'' on many distributions of [[Linux]], making it their default shell), the [[Korn Shell]] (''ksh''), the [[Public Domain Korn SHell]] (''pdksh''), the [[Almquist SHell]] (''ash'') and the [[Debian Almquist SHell]] (''dash'') and the [[Z SHell]] (''zsh''). ''Main article: [[UNIX Shell Implementations]]'' diff --git a/Lang/UNIX-Shell/99-Bottles-of-Beer b/Lang/UNIX-Shell/99-Bottles-of-Beer deleted file mode 120000 index e4c308f51c..0000000000 --- a/Lang/UNIX-Shell/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Combinations-with-repetitions b/Lang/UNIX-Shell/Combinations-with-repetitions deleted file mode 120000 index 1264fc2473..0000000000 --- a/Lang/UNIX-Shell/Combinations-with-repetitions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Combinations-with-repetitions/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/File-IO b/Lang/UNIX-Shell/File-IO deleted file mode 120000 index 0bbda5fd6e..0000000000 --- a/Lang/UNIX-Shell/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Write-language-name-in-3D-ASCII b/Lang/UNIX-Shell/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..95a5cfddc4 --- /dev/null +++ b/Lang/UNIX-Shell/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/UNIX-Shell \ No newline at end of file diff --git a/Lang/Unicon/Arrays b/Lang/Unicon/Arrays new file mode 120000 index 0000000000..627f65d340 --- /dev/null +++ b/Lang/Unicon/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Unicon \ No newline at end of file diff --git a/Lang/Unicon/HTTPS b/Lang/Unicon/HTTPS deleted file mode 120000 index 149450f34c..0000000000 --- a/Lang/Unicon/HTTPS +++ /dev/null @@ -1 +0,0 @@ -../../Task/HTTPS/Unicon \ No newline at end of file diff --git a/Lang/Unicon/Identity-matrix b/Lang/Unicon/Identity-matrix deleted file mode 120000 index cad86066a9..0000000000 --- a/Lang/Unicon/Identity-matrix +++ /dev/null @@ -1 +0,0 @@ -../../Task/Identity-matrix/Unicon \ No newline at end of file diff --git a/Lang/UnixPipes/99-Bottles-of-Beer b/Lang/UnixPipes/99-Bottles-of-Beer deleted file mode 120000 index 80b56cba90..0000000000 --- a/Lang/UnixPipes/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/UnixPipes \ No newline at end of file diff --git a/Lang/UnixPipes/Rosetta-Code-Rank-languages-by-popularity b/Lang/UnixPipes/Rosetta-Code-Rank-languages-by-popularity deleted file mode 120000 index dd8942e0ea..0000000000 --- a/Lang/UnixPipes/Rosetta-Code-Rank-languages-by-popularity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rosetta-Code-Rank-languages-by-popularity/UnixPipes \ No newline at end of file diff --git a/Lang/Ursala/File-IO b/Lang/Ursala/File-IO deleted file mode 120000 index 2b92bf6303..0000000000 --- a/Lang/Ursala/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Ursala \ No newline at end of file diff --git a/Lang/VBA/99-Bottles-of-Beer b/Lang/VBA/99-Bottles-of-Beer deleted file mode 120000 index c0a74a2d47..0000000000 --- a/Lang/VBA/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/VBA \ No newline at end of file diff --git a/Lang/VBA/Bitwise-operations b/Lang/VBA/Bitwise-operations new file mode 120000 index 0000000000..1472f9f8de --- /dev/null +++ b/Lang/VBA/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/VBA \ No newline at end of file diff --git a/Lang/VBA/Collections b/Lang/VBA/Collections new file mode 120000 index 0000000000..5ea2d062aa --- /dev/null +++ b/Lang/VBA/Collections @@ -0,0 +1 @@ +../../Task/Collections/VBA \ No newline at end of file diff --git a/Lang/VBA/Floyds-triangle b/Lang/VBA/Floyds-triangle new file mode 120000 index 0000000000..df1c0d94f8 --- /dev/null +++ b/Lang/VBA/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/VBA \ No newline at end of file diff --git a/Lang/VBA/Higher-order-functions b/Lang/VBA/Higher-order-functions new file mode 120000 index 0000000000..f99d1ba943 --- /dev/null +++ b/Lang/VBA/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/VBA \ No newline at end of file diff --git a/Lang/VBA/Knapsack-problem-0-1 b/Lang/VBA/Knapsack-problem-0-1 new file mode 120000 index 0000000000..9cc3bad810 --- /dev/null +++ b/Lang/VBA/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/VBA \ No newline at end of file diff --git a/Lang/VBA/N-queens-problem b/Lang/VBA/N-queens-problem new file mode 120000 index 0000000000..9ffb9f0493 --- /dev/null +++ b/Lang/VBA/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/VBA \ No newline at end of file diff --git a/Lang/VBA/Sorting-algorithms-Heapsort b/Lang/VBA/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..65de07b90d --- /dev/null +++ b/Lang/VBA/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/VBA \ No newline at end of file diff --git a/Lang/VBScript/99-Bottles-of-Beer b/Lang/VBScript/99-Bottles-of-Beer deleted file mode 120000 index ecb0b93135..0000000000 --- a/Lang/VBScript/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Caesar-cipher b/Lang/VBScript/Caesar-cipher new file mode 120000 index 0000000000..58c1ea5b06 --- /dev/null +++ b/Lang/VBScript/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Combinations-and-permutations b/Lang/VBScript/Combinations-and-permutations new file mode 120000 index 0000000000..d8b55b08cf --- /dev/null +++ b/Lang/VBScript/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Evolutionary-algorithm b/Lang/VBScript/Evolutionary-algorithm new file mode 120000 index 0000000000..b5759a294f --- /dev/null +++ b/Lang/VBScript/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Execute-Brain---- b/Lang/VBScript/Execute-Brain---- new file mode 120000 index 0000000000..7dbace070e --- /dev/null +++ b/Lang/VBScript/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/VBScript \ No newline at end of file diff --git a/Lang/VBScript/File-IO b/Lang/VBScript/File-IO deleted file mode 120000 index 37fb43544b..0000000000 --- a/Lang/VBScript/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Hello-world-Standard-error b/Lang/VBScript/Hello-world-Standard-error new file mode 120000 index 0000000000..2340e4a210 --- /dev/null +++ b/Lang/VBScript/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Include-a-file b/Lang/VBScript/Include-a-file new file mode 120000 index 0000000000..23c1c96de5 --- /dev/null +++ b/Lang/VBScript/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Integer-overflow b/Lang/VBScript/Integer-overflow new file mode 120000 index 0000000000..be1fbed180 --- /dev/null +++ b/Lang/VBScript/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Knapsack-problem-0-1 b/Lang/VBScript/Knapsack-problem-0-1 new file mode 120000 index 0000000000..bec87d012a --- /dev/null +++ b/Lang/VBScript/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/VBScript \ No newline at end of file diff --git a/Lang/VBScript/N-queens-problem b/Lang/VBScript/N-queens-problem new file mode 120000 index 0000000000..bcf652d2a9 --- /dev/null +++ b/Lang/VBScript/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Program-name b/Lang/VBScript/Program-name new file mode 120000 index 0000000000..0576b71e99 --- /dev/null +++ b/Lang/VBScript/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Standard-deviation b/Lang/VBScript/Standard-deviation deleted file mode 120000 index dcb31fb0c1..0000000000 --- a/Lang/VBScript/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sum-of-a-series b/Lang/VBScript/Sum-of-a-series new file mode 120000 index 0000000000..0cac57e5b3 --- /dev/null +++ b/Lang/VBScript/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/VBScript \ No newline at end of file diff --git a/Lang/VBScript/System-time b/Lang/VBScript/System-time new file mode 120000 index 0000000000..9d74acb7fe --- /dev/null +++ b/Lang/VBScript/System-time @@ -0,0 +1 @@ +../../Task/System-time/VBScript \ No newline at end of file diff --git a/Lang/Vala/Caesar-cipher b/Lang/Vala/Caesar-cipher new file mode 120000 index 0000000000..cde198322e --- /dev/null +++ b/Lang/Vala/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Vala \ No newline at end of file diff --git a/Lang/Vala/Levenshtein-distance b/Lang/Vala/Levenshtein-distance new file mode 120000 index 0000000000..df35bb1912 --- /dev/null +++ b/Lang/Vala/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Vala \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Calendar---for-real-programmers b/Lang/Vedit-macro-language/Calendar---for-real-programmers deleted file mode 120000 index 5e7c6a018c..0000000000 --- a/Lang/Vedit-macro-language/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/File-IO b/Lang/Vedit-macro-language/File-IO deleted file mode 120000 index f0d25b682f..0000000000 --- a/Lang/Vedit-macro-language/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Verilog/Seven-sided-dice-from-five-sided-dice b/Lang/Verilog/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..922f7f227b --- /dev/null +++ b/Lang/Verilog/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Verilog \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/99-Bottles-of-Beer b/Lang/Visual-Basic-.NET/99-Bottles-of-Beer deleted file mode 120000 index 0dbef891ac..0000000000 --- a/Lang/Visual-Basic-.NET/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Bernoulli-numbers b/Lang/Visual-Basic-.NET/Bernoulli-numbers new file mode 120000 index 0000000000..408be59833 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/CRC-32 b/Lang/Visual-Basic-.NET/CRC-32 new file mode 120000 index 0000000000..8429ebe3ca --- /dev/null +++ b/Lang/Visual-Basic-.NET/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Colour-pinstripe-Display b/Lang/Visual-Basic-.NET/Colour-pinstripe-Display new file mode 120000 index 0000000000..72d47c5bb4 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Combinations-and-permutations b/Lang/Visual-Basic-.NET/Combinations-and-permutations new file mode 120000 index 0000000000..7ff593b194 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/File-IO b/Lang/Visual-Basic-.NET/File-IO deleted file mode 120000 index 6fad58e731..0000000000 --- a/Lang/Visual-Basic-.NET/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/FizzBuzz b/Lang/Visual-Basic-.NET/FizzBuzz deleted file mode 120000 index ae9b27ad3f..0000000000 --- a/Lang/Visual-Basic-.NET/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Forest-fire b/Lang/Visual-Basic-.NET/Forest-fire deleted file mode 120000 index e203b939b1..0000000000 --- a/Lang/Visual-Basic-.NET/Forest-fire +++ /dev/null @@ -1 +0,0 @@ -../../Task/Forest-fire/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Integer-overflow b/Lang/Visual-Basic-.NET/Integer-overflow new file mode 120000 index 0000000000..b7ffa63262 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Knapsack-problem-0-1 b/Lang/Visual-Basic-.NET/Knapsack-problem-0-1 new file mode 120000 index 0000000000..1d3affa62f --- /dev/null +++ b/Lang/Visual-Basic-.NET/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Loops-Continue b/Lang/Visual-Basic-.NET/Loops-Continue deleted file mode 120000 index 62ad6183ad..0000000000 --- a/Lang/Visual-Basic-.NET/Loops-Continue +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Continue/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Loops-For b/Lang/Visual-Basic-.NET/Loops-For deleted file mode 120000 index 7bc86b9c4f..0000000000 --- a/Lang/Visual-Basic-.NET/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Loops-Foreach b/Lang/Visual-Basic-.NET/Loops-Foreach deleted file mode 120000 index 50ce52ca41..0000000000 --- a/Lang/Visual-Basic-.NET/Loops-Foreach +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Foreach/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/N-queens-problem b/Lang/Visual-Basic-.NET/N-queens-problem new file mode 120000 index 0000000000..186d46b4c0 --- /dev/null +++ b/Lang/Visual-Basic-.NET/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/String-case b/Lang/Visual-Basic-.NET/String-case deleted file mode 120000 index a71ca0ff4f..0000000000 --- a/Lang/Visual-Basic-.NET/String-case +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-case/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Sum-of-a-series b/Lang/Visual-Basic-.NET/Sum-of-a-series new file mode 120000 index 0000000000..dfc5f9152b --- /dev/null +++ b/Lang/Visual-Basic-.NET/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic/99-Bottles-of-Beer b/Lang/Visual-Basic/99-Bottles-of-Beer deleted file mode 120000 index de46cd0324..0000000000 --- a/Lang/Visual-Basic/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Integer-overflow b/Lang/Visual-Basic/Integer-overflow new file mode 120000 index 0000000000..4496ce3883 --- /dev/null +++ b/Lang/Visual-Basic/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Knapsack-problem-0-1 b/Lang/Visual-Basic/Knapsack-problem-0-1 new file mode 120000 index 0000000000..e9daa68a8d --- /dev/null +++ b/Lang/Visual-Basic/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Loops-For b/Lang/Visual-Basic/Loops-For deleted file mode 120000 index 4e36a09dd8..0000000000 --- a/Lang/Visual-Basic/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/N-queens-problem b/Lang/Visual-Basic/N-queens-problem new file mode 120000 index 0000000000..f9257c174a --- /dev/null +++ b/Lang/Visual-Basic/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Standard-deviation b/Lang/Visual-Basic/Standard-deviation deleted file mode 120000 index 4d4adecb37..0000000000 --- a/Lang/Visual-Basic/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Tokenize-a-string b/Lang/Visual-Basic/Tokenize-a-string deleted file mode 120000 index 7d3c8071a0..0000000000 --- a/Lang/Visual-Basic/Tokenize-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Tokenize-a-string/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Prolog/99-Bottles-of-Beer b/Lang/Visual-Prolog/99-Bottles-of-Beer deleted file mode 120000 index 2538580fd2..0000000000 --- a/Lang/Visual-Prolog/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Visual-Prolog \ No newline at end of file diff --git a/Lang/Viua-VM-assembly/00DESCRIPTION b/Lang/Viua-VM-assembly/00DESCRIPTION new file mode 100644 index 0000000000..791795758d --- /dev/null +++ b/Lang/Viua-VM-assembly/00DESCRIPTION @@ -0,0 +1,24 @@ +{{stub}} + +{{language|Viua VM assembly +|site=http://viuavm.org/ +|exec=bytecode +|safety=safe +|strength=strong +|checking=dynamic +|parampass=both +|gc=allowed +|express=implicit +|LCT=yes +}} +{{Language programming paradigm|Concurrent}} +{{Language programming paradigm|Imperative}} + +Viua VM assembly is the language that is used to program Viua virtual machine. + +Programs in written in Viua VM assembly are composed of isolated, lightweight processes running in parallel and communicating via message passing (compare with [[Erlang]]). +Inside every process programs are executed sequentially. + +The programming arsenal provided by Viua VM assembly language includes first-class functions, move- and copy-semantics for value movement (inside a single call frame, and for parameter passing), exceptions, deferred calls, safe pointers, and more. + +Documentation can be found at http://docs.viuavm.org/ \ No newline at end of file diff --git a/Lang/Viua-VM-assembly/99-Bottles-of-Beer b/Lang/Viua-VM-assembly/99-Bottles-of-Beer new file mode 120000 index 0000000000..4c4803d5c4 --- /dev/null +++ b/Lang/Viua-VM-assembly/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Viua-VM-assembly \ No newline at end of file diff --git a/Lang/Viua-VM-assembly/Hello-world-Text b/Lang/Viua-VM-assembly/Hello-world-Text new file mode 120000 index 0000000000..978d54e9ea --- /dev/null +++ b/Lang/Viua-VM-assembly/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Viua-VM-assembly \ No newline at end of file diff --git a/Lang/Viua-VM-assembly/README b/Lang/Viua-VM-assembly/README new file mode 100644 index 0000000000..926433d257 --- /dev/null +++ b/Lang/Viua-VM-assembly/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:Viua_VM_assembly diff --git a/Lang/Wart/00DESCRIPTION b/Lang/Wart/00DESCRIPTION index af54cfbb2b..3150915b1b 100644 --- a/Lang/Wart/00DESCRIPTION +++ b/Lang/Wart/00DESCRIPTION @@ -1,9 +1,22 @@ -{{language}} -[http://github.com/akkartik/wart#readme Wart] is an experimental, dynamic, [http://plus.google.com/110981030061712822816/posts/KaSKeg4vQtz batshit-liberal] language designed for small teams of [http://en.wikipedia.org/wiki/Motivation#Intrinsic_and_extrinsic_motivation intrinsically-motivated] programmers. Wart is based on [http://paulgraham.com/lispfaq1.html lisp], but with a cleaner syntax and more powerful primitives to help non-lispers appreciate the power of lisp. Wart was designed with several questions in mind: +{{language|Wart +|exec=interpreted +|site=https://github.com/akkartik/wart +|gc=yes +|parampass=value +|strength=strong +|checking=dynamic +|hopl=no +|LCT=no +|tags=lisp, c +}} +{{language programming paradigm|Dynamic}} +{{language programming paradigm|Functional}} +{{language programming paradigm|Procedural}} +[http://github.com/akkartik/wart#readme Wart] is an experimental, dynamic, [http://plus.google.com/110981030061712822816/posts/KaSKeg4vQtz batshit-liberal] language designed to eventually be used by small teams of [http://en.wikipedia.org/wiki/Motivation#Intrinsic_and_extrinsic_motivation intrinsically-motivated] programmers. Wart is based on [http://paulgraham.com/lispfaq1.html Lisp], but with a cleaner syntax and more powerful primitives to help non-lispers appreciate the power of Lisp. Wart was designed with several questions in mind: -* How far can we change the syntax of lisp without compromising the power of lisp macros? Wart has several features to help make codebases more pleasurable to read and easier to ramp up on. -*# While lispers can continue to write fully-parenthesized lisp, wart provides a whitespace-sensitive syntax that is easy to get used to and eliminates most parentheses for the convenience of non-lisp readers.
if (odd 3) "odd"
-*# Wart provides infix operators in an elegant way without compromising homoiconicity or macros. Infix operations provide only one precedence rule: operators without whitespace are evaluated before operators with whitespace.
(n * n-1)  # does what you think
The catch: infix characters like dashes can't be used in names, unlike traditional lisps. +* How far can we change the syntax of Lisp without compromising the power of Lisp macros? Wart has several features to help make codebases more pleasurable to read and easier to ramp up on. +*# While lispers can continue to write fully-parenthesized Lisp, Wart provides a whitespace-sensitive syntax that is easy to get used to and eliminates most parentheses for the convenience of non-lisp readers.
if (odd 3) "odd"
+*# Wart provides infix operators in an elegant way without compromising homoiconicity or macros. Infix operations provide only one precedence rule: operators without whitespace are evaluated before operators with whitespace.
(n * n-1)  # does what you think
The catch: infix characters like dashes can't be used in names, unlike traditional Lisps. *# All functions can be called with keyword arguments as needed, using ''aliases'' so both caller and callee can use the right name for them.
 def (subtract a|from b)
@@ -16,7 +29,7 @@ subtract 3 :from 4
 => 1
 
-* What would a language ecosystem be like without any backwards-compatibility guarantees, super easy to change and fork promiscuously? Wart has no version numbers, and new versions and forks are free to change all semantics to their hearts' desire. Instead of a spec or frozen interfaces, we rely on automated tests. Wart is thoroughly tested, and wart programs are expected to be thoroughly tested as well, and to buy in to the investment of needing to make changes during upgrades. The hope is that upgrade effort might be higher than the best-case scenario in other languages, but the worst-case time will remain tightly bounded because clients of libraries will be more likely to understand how they're implemented, and so be more empowered. (More info: http://akkartik.name/blog/libraries2) +* What would a language ecosystem be like without any backwards-compatibility guarantees, super easy to change and fork promiscuously? Wart has no version numbers, and new versions and forks are free to change all semantics to their hearts' desire. Instead of a spec or frozen interfaces, we rely on automated tests. Wart is thoroughly tested, and Wart programs are expected to be thoroughly tested as well, and to buy in to the investment of needing to make changes during upgrades. The hope is that upgrade effort might be higher than the best-case scenario in other languages, but the worst-case time will remain tightly bounded because clients of libraries will be more likely to understand how they're implemented, and so be more empowered. (More info: http://akkartik.name/blog/libraries2) * What would a language look like with an emphasis on a parsimonious and harmonious system of names? This is only possible if the language has no reserved words, and even primitives can be overloaded in arbitrary ways. So you never end up with constructions like 'my_if' or 'append2' or 'queue_length'. (More info: http://akkartik.name/blog/readable-bad) diff --git a/Lang/WebAssembly/00DESCRIPTION b/Lang/WebAssembly/00DESCRIPTION new file mode 100644 index 0000000000..f787117c47 --- /dev/null +++ b/Lang/WebAssembly/00DESCRIPTION @@ -0,0 +1,4 @@ +{{stub}}{{language|WebAssembly}} +WebAssembly or wasm is a low-level bytecode format for in-browser client-side scripting that is more efficient than JavaScript, from which it evolved. +WebAssembly is a portable stack machine which is designed to be faster to parse than JavaScript, as well as faster to execute. +Its initial aim is to support compilation from C and C++, though other source languages such as Rust are also supported. \ No newline at end of file diff --git a/Lang/WebAssembly/README b/Lang/WebAssembly/README new file mode 100644 index 0000000000..16c74ab2b1 --- /dev/null +++ b/Lang/WebAssembly/README @@ -0,0 +1 @@ +Data source: http://rosettacode.org/wiki/Category:WebAssembly diff --git a/Lang/Whenever/99-Bottles-of-Beer b/Lang/Whenever/99-Bottles-of-Beer deleted file mode 120000 index 7d47743918..0000000000 --- a/Lang/Whenever/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Whenever \ No newline at end of file diff --git a/Lang/Whitespace/FizzBuzz b/Lang/Whitespace/FizzBuzz deleted file mode 120000 index 03bdfd6026..0000000000 --- a/Lang/Whitespace/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Whitespace \ No newline at end of file diff --git a/Lang/Wollok/00DESCRIPTION b/Lang/Wollok/00DESCRIPTION index 1846dc32e5..3b040f5c76 100644 --- a/Lang/Wollok/00DESCRIPTION +++ b/Lang/Wollok/00DESCRIPTION @@ -6,7 +6,10 @@ It is currently under active development. It takes away syntax complexity and focus on objects, messages and polymorphism. It features objects as first class citizens in order to start programming OOP without the need of classes (and its complexity). -But it also supports classes and simple inheritance. +But it also supports classes, simple inheritance and mixins (multiple inheritance by linearization). +Wollok also has an optional type-system with type inference, aiming to be as much implicit as one can :) -For more information visit https://github.com/uqbar-project/wollok \ No newline at end of file +Although Wollok can be used from a command line, the full experience to teach and learn OOP is based on an IDE with: tests cases support, autocomplete, syntax-highlight and many static code checks (plus quick fixes) + +For more information visit https://github.com/uqbar-project/wollok and http://www.wollok.org/ \ No newline at end of file diff --git a/Lang/X86-Assembly/00DESCRIPTION b/Lang/X86-Assembly/00DESCRIPTION index c9b9f3b5fe..eb9b1b61c7 100644 --- a/Lang/X86-Assembly/00DESCRIPTION +++ b/Lang/X86-Assembly/00DESCRIPTION @@ -1,3 +1,33 @@ -{{stub}}{{language}}{{assembler language}} +{{language}}{{assembler language}} -[[Category:Assembly]] \ No newline at end of file +[[Category:Assembly]] + +Quote from Wikipedia article: + +x86 assembly language is a family of backward-compatible assembly languages, which provide some level of compatibility all the way back to the Intel 8008 introduced in April 1972. x86 assembly languages are used to produce object code for the x86 class of processors. Like all assembly languages, it uses short mnemonics to represent the fundamental instructions that the CPU in a computer can understand and follow. Compilers sometimes produce assembly code as an intermediate step when translating a high level program into machine code. Regarded as a programming language, assembly coding is machine-specific and low level. Assembly languages are more typically used for detailed and time critical applications such as small real-time embedded systems or operating system kernels and device drivers. +==See also== +Wikipedia Article: https://en.wikipedia.org/wiki/X86_assembly_language + +Intel manuals: https://software.intel.com/en-us/articles/intel-sdm + +Brief introduction: http://cs.lmu.edu/~ray/notes/x86assembly/ + +GNU assembler: https://sourceware.org/binutils/docs/as/ + +SSE: https://en.wikibooks.org/wiki/X86_Assembly/SSE + +64 bit Linux assembly: http://rayseyfarth.com/asm/ + +Linux system calls: http://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/ + +YASM manual: http://www.tortall.net/projects/yasm/manual/html/index.html + +NASM manual: http://www.nasm.us/xdoc/2.12.02/html/nasmdoc0.html + +8086 assembly: http://www.stevemorse.org/8086/ + +32 bit: http://pacman128.github.io/pcasm/ + +64 bit: https://www.cs.cmu.edu/~fp/courses/15213-s07/misc/asm64-handout.pdf + +Linux procedure calls: https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-r252.pdf \ No newline at end of file diff --git a/Lang/X86-Assembly/100-doors b/Lang/X86-Assembly/100-doors new file mode 120000 index 0000000000..888ed9c37e --- /dev/null +++ b/Lang/X86-Assembly/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/99-Bottles-of-Beer b/Lang/X86-Assembly/99-Bottles-of-Beer deleted file mode 120000 index 41d51d1a5f..0000000000 --- a/Lang/X86-Assembly/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Arithmetic-Integer b/Lang/X86-Assembly/Arithmetic-Integer new file mode 120000 index 0000000000..26ab1db42d --- /dev/null +++ b/Lang/X86-Assembly/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Bitwise-operations b/Lang/X86-Assembly/Bitwise-operations new file mode 120000 index 0000000000..77ab7c4cc4 --- /dev/null +++ b/Lang/X86-Assembly/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Calendar---for-real-programmers b/Lang/X86-Assembly/Calendar---for-real-programmers deleted file mode 120000 index 6f502b97ec..0000000000 --- a/Lang/X86-Assembly/Calendar---for-real-programmers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar---for-real-programmers/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Ethiopian-multiplication b/Lang/X86-Assembly/Ethiopian-multiplication new file mode 120000 index 0000000000..39d76b2cb1 --- /dev/null +++ b/Lang/X86-Assembly/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Execute-HQ9+ b/Lang/X86-Assembly/Execute-HQ9+ new file mode 120000 index 0000000000..fbb07e9e05 --- /dev/null +++ b/Lang/X86-Assembly/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Factorial b/Lang/X86-Assembly/Factorial new file mode 120000 index 0000000000..24b6113d73 --- /dev/null +++ b/Lang/X86-Assembly/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Fibonacci-sequence b/Lang/X86-Assembly/Fibonacci-sequence new file mode 120000 index 0000000000..861c4f65fb --- /dev/null +++ b/Lang/X86-Assembly/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/File-size b/Lang/X86-Assembly/File-size new file mode 120000 index 0000000000..648883641d --- /dev/null +++ b/Lang/X86-Assembly/File-size @@ -0,0 +1 @@ +../../Task/File-size/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Find-limit-of-recursion b/Lang/X86-Assembly/Find-limit-of-recursion new file mode 120000 index 0000000000..9f5e35c9b9 --- /dev/null +++ b/Lang/X86-Assembly/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Greatest-common-divisor b/Lang/X86-Assembly/Greatest-common-divisor new file mode 120000 index 0000000000..b9437857d2 --- /dev/null +++ b/Lang/X86-Assembly/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Horizontal-sundial-calculations b/Lang/X86-Assembly/Horizontal-sundial-calculations new file mode 120000 index 0000000000..70c605bcef --- /dev/null +++ b/Lang/X86-Assembly/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Include-a-file b/Lang/X86-Assembly/Include-a-file new file mode 120000 index 0000000000..fbe6b856f2 --- /dev/null +++ b/Lang/X86-Assembly/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Input-loop b/Lang/X86-Assembly/Input-loop new file mode 120000 index 0000000000..2a9a149642 --- /dev/null +++ b/Lang/X86-Assembly/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Loops-For b/Lang/X86-Assembly/Loops-For new file mode 120000 index 0000000000..133925c27d --- /dev/null +++ b/Lang/X86-Assembly/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/MD5-Implementation b/Lang/X86-Assembly/MD5-Implementation new file mode 120000 index 0000000000..3169a5f74e --- /dev/null +++ b/Lang/X86-Assembly/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Memory-allocation b/Lang/X86-Assembly/Memory-allocation new file mode 120000 index 0000000000..646af14e19 --- /dev/null +++ b/Lang/X86-Assembly/Memory-allocation @@ -0,0 +1 @@ +../../Task/Memory-allocation/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Mutual-recursion b/Lang/X86-Assembly/Mutual-recursion new file mode 120000 index 0000000000..8a153eef5b --- /dev/null +++ b/Lang/X86-Assembly/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Palindrome-detection b/Lang/X86-Assembly/Palindrome-detection new file mode 120000 index 0000000000..75e046f39d --- /dev/null +++ b/Lang/X86-Assembly/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Program-name b/Lang/X86-Assembly/Program-name new file mode 120000 index 0000000000..303a47b117 --- /dev/null +++ b/Lang/X86-Assembly/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Quine b/Lang/X86-Assembly/Quine new file mode 120000 index 0000000000..c896a39753 --- /dev/null +++ b/Lang/X86-Assembly/Quine @@ -0,0 +1 @@ +../../Task/Quine/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Random-number-generator--device- b/Lang/X86-Assembly/Random-number-generator--device- new file mode 120000 index 0000000000..3f2125d5c6 --- /dev/null +++ b/Lang/X86-Assembly/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Singly-linked-list-Element-insertion b/Lang/X86-Assembly/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..82a9bbf1cb --- /dev/null +++ b/Lang/X86-Assembly/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Sleep b/Lang/X86-Assembly/Sleep new file mode 120000 index 0000000000..0d8646d143 --- /dev/null +++ b/Lang/X86-Assembly/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Stack b/Lang/X86-Assembly/Stack new file mode 120000 index 0000000000..c0f7dc8fa0 --- /dev/null +++ b/Lang/X86-Assembly/Stack @@ -0,0 +1 @@ +../../Task/Stack/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/String-length b/Lang/X86-Assembly/String-length new file mode 120000 index 0000000000..2f38ea95f7 --- /dev/null +++ b/Lang/X86-Assembly/String-length @@ -0,0 +1 @@ +../../Task/String-length/X86-Assembly \ No newline at end of file diff --git a/Lang/XEec/A+B b/Lang/XEec/A+B new file mode 120000 index 0000000000..8161d08976 --- /dev/null +++ b/Lang/XEec/A+B @@ -0,0 +1 @@ +../../Task/A+B/XEec \ No newline at end of file diff --git a/Lang/XEec/Even-or-odd b/Lang/XEec/Even-or-odd new file mode 120000 index 0000000000..2053f1c03c --- /dev/null +++ b/Lang/XEec/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/XEec \ No newline at end of file diff --git a/Lang/XEec/Fibonacci-sequence b/Lang/XEec/Fibonacci-sequence new file mode 120000 index 0000000000..285701e956 --- /dev/null +++ b/Lang/XEec/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/XEec \ No newline at end of file diff --git a/Lang/XEec/Generate-lower-case-ASCII-alphabet b/Lang/XEec/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..f0f1a1e9a6 --- /dev/null +++ b/Lang/XEec/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/XEec \ No newline at end of file diff --git a/Lang/XEec/Hello-world-Text b/Lang/XEec/Hello-world-Text new file mode 120000 index 0000000000..2c9ccc0ca5 --- /dev/null +++ b/Lang/XEec/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/XEec \ No newline at end of file diff --git a/Lang/XLISP/00DESCRIPTION b/Lang/XLISP/00DESCRIPTION index 3d65edc294..137eb4ad3f 100644 --- a/Lang/XLISP/00DESCRIPTION +++ b/Lang/XLISP/00DESCRIPTION @@ -1,2 +1,4 @@ {{stub}}{{language|XLISP}} +{{implementation|Lisp}} +{{implementation|Scheme}} XLISP, created by David Betz and first released in 1984, is a Lisp dialect with support for simple object-oriented programming using classes. Since 1997 it has been based on Scheme, with some extensions resembling Common Lisp. \ No newline at end of file diff --git a/Lang/XLISP/Bitwise-operations b/Lang/XLISP/Bitwise-operations new file mode 120000 index 0000000000..670ec8870f --- /dev/null +++ b/Lang/XLISP/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/XLISP \ No newline at end of file diff --git a/Lang/XLISP/Catalan-numbers b/Lang/XLISP/Catalan-numbers new file mode 120000 index 0000000000..79cc02fa0b --- /dev/null +++ b/Lang/XLISP/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/XLISP \ No newline at end of file diff --git a/Lang/XLISP/Conditional-structures b/Lang/XLISP/Conditional-structures new file mode 120000 index 0000000000..1ef68a16e1 --- /dev/null +++ b/Lang/XLISP/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/XLISP \ No newline at end of file diff --git a/Lang/XLISP/Empty-string b/Lang/XLISP/Empty-string new file mode 120000 index 0000000000..511f423653 --- /dev/null +++ b/Lang/XLISP/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/XLISP \ No newline at end of file diff --git a/Lang/XLISP/Even-or-odd b/Lang/XLISP/Even-or-odd new file mode 120000 index 0000000000..3cad86feda --- /dev/null +++ b/Lang/XLISP/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/XLISP \ No newline at end of file diff --git a/Lang/XLISP/Factorial b/Lang/XLISP/Factorial new file mode 120000 index 0000000000..d86246ef81 --- /dev/null +++ b/Lang/XLISP/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/XLISP \ No newline at end of file diff --git a/Lang/XLISP/Integer-sequence b/Lang/XLISP/Integer-sequence new file mode 120000 index 0000000000..501d830fd1 --- /dev/null +++ b/Lang/XLISP/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/XLISP \ No newline at end of file diff --git a/Lang/XLISP/Loops-Infinite b/Lang/XLISP/Loops-Infinite new file mode 120000 index 0000000000..cb01185725 --- /dev/null +++ b/Lang/XLISP/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/XLISP \ No newline at end of file diff --git a/Lang/XLISP/User-input-Text b/Lang/XLISP/User-input-Text new file mode 120000 index 0000000000..9ed2a8f94d --- /dev/null +++ b/Lang/XLISP/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/XLISP \ No newline at end of file diff --git a/Lang/XPL0/Character-matching b/Lang/XPL0/Character-matching deleted file mode 120000 index f68cd568c7..0000000000 --- a/Lang/XPL0/Character-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-matching/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/File-IO b/Lang/XPL0/File-IO deleted file mode 120000 index fd7191d7a6..0000000000 --- a/Lang/XPL0/File-IO +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-IO/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Standard-deviation b/Lang/XPL0/Standard-deviation deleted file mode 120000 index 03d1b156f7..0000000000 --- a/Lang/XPL0/Standard-deviation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Standard-deviation/XPL0 \ No newline at end of file diff --git a/Lang/XSLT-1.0/FizzBuzz b/Lang/XSLT-1.0/FizzBuzz deleted file mode 120000 index af823b9f55..0000000000 --- a/Lang/XSLT-1.0/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/XSLT-1.0 \ No newline at end of file diff --git a/Lang/XSLT-2.0/FizzBuzz b/Lang/XSLT-2.0/FizzBuzz deleted file mode 120000 index 8e6093bf6f..0000000000 --- a/Lang/XSLT-2.0/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/XSLT-2.0 \ No newline at end of file diff --git a/Lang/XTalk/String-length b/Lang/XTalk/String-length new file mode 120000 index 0000000000..915c88ab60 --- /dev/null +++ b/Lang/XTalk/String-length @@ -0,0 +1 @@ +../../Task/String-length/XTalk \ No newline at end of file diff --git a/Lang/Xojo/Parsing-RPN-calculator-algorithm b/Lang/Xojo/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..ab5bb88c07 --- /dev/null +++ b/Lang/Xojo/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Xojo \ No newline at end of file diff --git a/Lang/Xojo/Parsing-Shunting-yard-algorithm b/Lang/Xojo/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..974b493156 --- /dev/null +++ b/Lang/Xojo/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Xojo \ No newline at end of file diff --git a/Lang/Z80-Assembly/99-Bottles-of-Beer b/Lang/Z80-Assembly/99-Bottles-of-Beer deleted file mode 120000 index e13024bbe5..0000000000 --- a/Lang/Z80-Assembly/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/Z80-Assembly \ No newline at end of file diff --git a/Lang/ZED/100-doors b/Lang/ZED/100-doors deleted file mode 120000 index 2d81560a37..0000000000 --- a/Lang/ZED/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/ZED \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Generate-lower-case-ASCII-alphabet b/Lang/ZX-Spectrum-Basic/Generate-lower-case-ASCII-alphabet deleted file mode 120000 index dd6309b8a5..0000000000 --- a/Lang/ZX-Spectrum-Basic/Generate-lower-case-ASCII-alphabet +++ /dev/null @@ -1 +0,0 @@ -../../Task/Generate-lower-case-ASCII-alphabet/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/IBAN b/Lang/ZX-Spectrum-Basic/IBAN new file mode 120000 index 0000000000..e61d9d7e3c --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Identity-matrix b/Lang/ZX-Spectrum-Basic/Identity-matrix new file mode 120000 index 0000000000..f2358bd2dc --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Integer-comparison b/Lang/ZX-Spectrum-Basic/Integer-comparison new file mode 120000 index 0000000000..ae92a9e920 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Iterated-digits-squaring b/Lang/ZX-Spectrum-Basic/Iterated-digits-squaring new file mode 120000 index 0000000000..0393e9edee --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Narcissistic-decimal-number b/Lang/ZX-Spectrum-Basic/Narcissistic-decimal-number new file mode 120000 index 0000000000..1f05f88cdf --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Nth b/Lang/ZX-Spectrum-Basic/Nth new file mode 120000 index 0000000000..f5abbfadd2 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Nth @@ -0,0 +1 @@ +../../Task/Nth/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/String-concatenation b/Lang/ZX-Spectrum-Basic/String-concatenation deleted file mode 120000 index c9090d6c07..0000000000 --- a/Lang/ZX-Spectrum-Basic/String-concatenation +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-concatenation/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Write-language-name-in-3D-ASCII b/Lang/ZX-Spectrum-Basic/Write-language-name-in-3D-ASCII deleted file mode 120000 index 56aa7a4390..0000000000 --- a/Lang/ZX-Spectrum-Basic/Write-language-name-in-3D-ASCII +++ /dev/null @@ -1 +0,0 @@ -../../Task/Write-language-name-in-3D-ASCII/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/Zkl/100-doors b/Lang/Zkl/100-doors new file mode 120000 index 0000000000..8b7b4d433f --- /dev/null +++ b/Lang/Zkl/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Zkl \ No newline at end of file diff --git a/Lang/Zkl/24-game b/Lang/Zkl/24-game new file mode 120000 index 0000000000..aacc900825 --- /dev/null +++ b/Lang/Zkl/24-game @@ -0,0 +1 @@ +../../Task/24-game/Zkl \ No newline at end of file diff --git a/Lang/Zkl/24-game-Solve b/Lang/Zkl/24-game-Solve new file mode 120000 index 0000000000..5bbc351de5 --- /dev/null +++ b/Lang/Zkl/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Zkl \ No newline at end of file diff --git a/Lang/Zkl/9-billion-names-of-God-the-integer b/Lang/Zkl/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..12c28d1c2b --- /dev/null +++ b/Lang/Zkl/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Zkl \ No newline at end of file diff --git a/Lang/Zkl/99-Bottles-of-Beer b/Lang/Zkl/99-Bottles-of-Beer new file mode 120000 index 0000000000..d5aee54b13 --- /dev/null +++ b/Lang/Zkl/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Zkl \ No newline at end of file diff --git a/Lang/Zkl/A+B b/Lang/Zkl/A+B new file mode 120000 index 0000000000..3a70bda0eb --- /dev/null +++ b/Lang/Zkl/A+B @@ -0,0 +1 @@ +../../Task/A+B/Zkl \ No newline at end of file diff --git a/Lang/Zkl/ABC-Problem b/Lang/Zkl/ABC-Problem new file mode 120000 index 0000000000..519d54b622 --- /dev/null +++ b/Lang/Zkl/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Zkl \ No newline at end of file diff --git a/Lang/Zkl/AKS-test-for-primes b/Lang/Zkl/AKS-test-for-primes new file mode 120000 index 0000000000..722cd75f05 --- /dev/null +++ b/Lang/Zkl/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Abstract-type b/Lang/Zkl/Abstract-type new file mode 120000 index 0000000000..2bbf6deacf --- /dev/null +++ b/Lang/Zkl/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Abundant,-deficient-and-perfect-number-classifications b/Lang/Zkl/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..0c89b7ecae --- /dev/null +++ b/Lang/Zkl/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Accumulator-factory b/Lang/Zkl/Accumulator-factory new file mode 120000 index 0000000000..9ce1d0d5f3 --- /dev/null +++ b/Lang/Zkl/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Active-object b/Lang/Zkl/Active-object new file mode 120000 index 0000000000..9f2bf4a03e --- /dev/null +++ b/Lang/Zkl/Active-object @@ -0,0 +1 @@ +../../Task/Active-object/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Align-columns b/Lang/Zkl/Align-columns new file mode 120000 index 0000000000..fb38b4d930 --- /dev/null +++ b/Lang/Zkl/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Aliquot-sequence-classifications b/Lang/Zkl/Aliquot-sequence-classifications new file mode 120000 index 0000000000..9d85457dd4 --- /dev/null +++ b/Lang/Zkl/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Almost-prime b/Lang/Zkl/Almost-prime new file mode 120000 index 0000000000..f35705fa33 --- /dev/null +++ b/Lang/Zkl/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Amb b/Lang/Zkl/Amb new file mode 120000 index 0000000000..365d8e1750 --- /dev/null +++ b/Lang/Zkl/Amb @@ -0,0 +1 @@ +../../Task/Amb/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Amicable-pairs b/Lang/Zkl/Amicable-pairs new file mode 120000 index 0000000000..1b085871de --- /dev/null +++ b/Lang/Zkl/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Anagrams b/Lang/Zkl/Anagrams new file mode 120000 index 0000000000..382713367a --- /dev/null +++ b/Lang/Zkl/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Anagrams-Deranged-anagrams b/Lang/Zkl/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..f6c4a9aaff --- /dev/null +++ b/Lang/Zkl/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Anonymous-recursion b/Lang/Zkl/Anonymous-recursion new file mode 120000 index 0000000000..4b804359cf --- /dev/null +++ b/Lang/Zkl/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Append-a-record-to-the-end-of-a-text-file b/Lang/Zkl/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..3ca19c0136 --- /dev/null +++ b/Lang/Zkl/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Apply-a-callback-to-an-array b/Lang/Zkl/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..d4c9712bc8 --- /dev/null +++ b/Lang/Zkl/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Arbitrary-precision-integers--included- b/Lang/Zkl/Arbitrary-precision-integers--included- new file mode 120000 index 0000000000..3080661d13 --- /dev/null +++ b/Lang/Zkl/Arbitrary-precision-integers--included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers--included-/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Arena-storage-pool b/Lang/Zkl/Arena-storage-pool new file mode 120000 index 0000000000..a09c9c6b22 --- /dev/null +++ b/Lang/Zkl/Arena-storage-pool @@ -0,0 +1 @@ +../../Task/Arena-storage-pool/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Arithmetic-Complex b/Lang/Zkl/Arithmetic-Complex new file mode 120000 index 0000000000..f319fe9077 --- /dev/null +++ b/Lang/Zkl/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Arithmetic-Integer b/Lang/Zkl/Arithmetic-Integer new file mode 120000 index 0000000000..9912440415 --- /dev/null +++ b/Lang/Zkl/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Arithmetic-Rational b/Lang/Zkl/Arithmetic-Rational new file mode 120000 index 0000000000..5b9ed4c555 --- /dev/null +++ b/Lang/Zkl/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Arithmetic-evaluation b/Lang/Zkl/Arithmetic-evaluation new file mode 120000 index 0000000000..6423d5228a --- /dev/null +++ b/Lang/Zkl/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Arithmetic-geometric-mean b/Lang/Zkl/Arithmetic-geometric-mean new file mode 120000 index 0000000000..615674d013 --- /dev/null +++ b/Lang/Zkl/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Array-concatenation b/Lang/Zkl/Array-concatenation new file mode 120000 index 0000000000..3cc0b5a179 --- /dev/null +++ b/Lang/Zkl/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Arrays b/Lang/Zkl/Arrays new file mode 120000 index 0000000000..011b48cf25 --- /dev/null +++ b/Lang/Zkl/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Assertions b/Lang/Zkl/Assertions new file mode 120000 index 0000000000..7f928f4392 --- /dev/null +++ b/Lang/Zkl/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Associative-array-Creation b/Lang/Zkl/Associative-array-Creation new file mode 120000 index 0000000000..e82781a3cf --- /dev/null +++ b/Lang/Zkl/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Associative-array-Iteration b/Lang/Zkl/Associative-array-Iteration new file mode 120000 index 0000000000..c6815ada83 --- /dev/null +++ b/Lang/Zkl/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Atomic-updates b/Lang/Zkl/Atomic-updates new file mode 120000 index 0000000000..f63440c4d6 --- /dev/null +++ b/Lang/Zkl/Atomic-updates @@ -0,0 +1 @@ +../../Task/Atomic-updates/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Average-loop-length b/Lang/Zkl/Average-loop-length new file mode 120000 index 0000000000..85fea5cfc3 --- /dev/null +++ b/Lang/Zkl/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Averages-Arithmetic-mean b/Lang/Zkl/Averages-Arithmetic-mean new file mode 120000 index 0000000000..1012c7d655 --- /dev/null +++ b/Lang/Zkl/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Averages-Mean-angle b/Lang/Zkl/Averages-Mean-angle new file mode 120000 index 0000000000..7e01fdd4d1 --- /dev/null +++ b/Lang/Zkl/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Averages-Mean-time-of-day b/Lang/Zkl/Averages-Mean-time-of-day new file mode 120000 index 0000000000..dcced07b50 --- /dev/null +++ b/Lang/Zkl/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Averages-Median b/Lang/Zkl/Averages-Median new file mode 120000 index 0000000000..1db9021a57 --- /dev/null +++ b/Lang/Zkl/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Averages-Mode b/Lang/Zkl/Averages-Mode new file mode 120000 index 0000000000..df07ee050f --- /dev/null +++ b/Lang/Zkl/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Averages-Pythagorean-means b/Lang/Zkl/Averages-Pythagorean-means new file mode 120000 index 0000000000..24a61d51c2 --- /dev/null +++ b/Lang/Zkl/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Averages-Root-mean-square b/Lang/Zkl/Averages-Root-mean-square new file mode 120000 index 0000000000..45d894e2ed --- /dev/null +++ b/Lang/Zkl/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Averages-Simple-moving-average b/Lang/Zkl/Averages-Simple-moving-average new file mode 120000 index 0000000000..c7f40a799c --- /dev/null +++ b/Lang/Zkl/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Balanced-brackets b/Lang/Zkl/Balanced-brackets new file mode 120000 index 0000000000..b9b97d4476 --- /dev/null +++ b/Lang/Zkl/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Benfords-law b/Lang/Zkl/Benfords-law new file mode 120000 index 0000000000..62a5b3d304 --- /dev/null +++ b/Lang/Zkl/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bernoulli-numbers b/Lang/Zkl/Bernoulli-numbers new file mode 120000 index 0000000000..23dc28eb5a --- /dev/null +++ b/Lang/Zkl/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Best-shuffle b/Lang/Zkl/Best-shuffle new file mode 120000 index 0000000000..61d0aecfca --- /dev/null +++ b/Lang/Zkl/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Binary-digits b/Lang/Zkl/Binary-digits new file mode 120000 index 0000000000..3bcbc93ada --- /dev/null +++ b/Lang/Zkl/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Binary-search b/Lang/Zkl/Binary-search new file mode 120000 index 0000000000..6fa141eb5b --- /dev/null +++ b/Lang/Zkl/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Binary-strings b/Lang/Zkl/Binary-strings new file mode 120000 index 0000000000..26134b16c4 --- /dev/null +++ b/Lang/Zkl/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitcoin-address-validation b/Lang/Zkl/Bitcoin-address-validation new file mode 120000 index 0000000000..1ad1d4561b --- /dev/null +++ b/Lang/Zkl/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitcoin-public-point-to-address b/Lang/Zkl/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..923da687e1 --- /dev/null +++ b/Lang/Zkl/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitmap b/Lang/Zkl/Bitmap new file mode 120000 index 0000000000..040993ede0 --- /dev/null +++ b/Lang/Zkl/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitmap-B-zier-curves-Cubic b/Lang/Zkl/Bitmap-B-zier-curves-Cubic new file mode 120000 index 0000000000..22a8137c2d --- /dev/null +++ b/Lang/Zkl/Bitmap-B-zier-curves-Cubic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Cubic/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitmap-B-zier-curves-Quadratic b/Lang/Zkl/Bitmap-B-zier-curves-Quadratic new file mode 120000 index 0000000000..36a83c0032 --- /dev/null +++ b/Lang/Zkl/Bitmap-B-zier-curves-Quadratic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Quadratic/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitmap-Bresenhams-line-algorithm b/Lang/Zkl/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..667ff37be2 --- /dev/null +++ b/Lang/Zkl/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitmap-Flood-fill b/Lang/Zkl/Bitmap-Flood-fill new file mode 120000 index 0000000000..edda4f1768 --- /dev/null +++ b/Lang/Zkl/Bitmap-Flood-fill @@ -0,0 +1 @@ +../../Task/Bitmap-Flood-fill/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitmap-Histogram b/Lang/Zkl/Bitmap-Histogram new file mode 120000 index 0000000000..0be317942b --- /dev/null +++ b/Lang/Zkl/Bitmap-Histogram @@ -0,0 +1 @@ +../../Task/Bitmap-Histogram/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitmap-Midpoint-circle-algorithm b/Lang/Zkl/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..718ec7d72c --- /dev/null +++ b/Lang/Zkl/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitmap-PPM-conversion-through-a-pipe b/Lang/Zkl/Bitmap-PPM-conversion-through-a-pipe new file mode 120000 index 0000000000..d9765f22b8 --- /dev/null +++ b/Lang/Zkl/Bitmap-PPM-conversion-through-a-pipe @@ -0,0 +1 @@ +../../Task/Bitmap-PPM-conversion-through-a-pipe/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitmap-Read-a-PPM-file b/Lang/Zkl/Bitmap-Read-a-PPM-file new file mode 120000 index 0000000000..285cb33e29 --- /dev/null +++ b/Lang/Zkl/Bitmap-Read-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Read-a-PPM-file/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitmap-Read-an-image-through-a-pipe b/Lang/Zkl/Bitmap-Read-an-image-through-a-pipe new file mode 120000 index 0000000000..7b311ef59c --- /dev/null +++ b/Lang/Zkl/Bitmap-Read-an-image-through-a-pipe @@ -0,0 +1 @@ +../../Task/Bitmap-Read-an-image-through-a-pipe/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitmap-Write-a-PPM-file b/Lang/Zkl/Bitmap-Write-a-PPM-file new file mode 120000 index 0000000000..11c9d8f225 --- /dev/null +++ b/Lang/Zkl/Bitmap-Write-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Write-a-PPM-file/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitwise-IO b/Lang/Zkl/Bitwise-IO new file mode 120000 index 0000000000..70a498ff48 --- /dev/null +++ b/Lang/Zkl/Bitwise-IO @@ -0,0 +1 @@ +../../Task/Bitwise-IO/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bitwise-operations b/Lang/Zkl/Bitwise-operations new file mode 120000 index 0000000000..f711957a54 --- /dev/null +++ b/Lang/Zkl/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Boolean-values b/Lang/Zkl/Boolean-values new file mode 120000 index 0000000000..d1b12cf3c5 --- /dev/null +++ b/Lang/Zkl/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Box-the-compass b/Lang/Zkl/Box-the-compass new file mode 120000 index 0000000000..b84b78f9b9 --- /dev/null +++ b/Lang/Zkl/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Break-OO-privacy b/Lang/Zkl/Break-OO-privacy new file mode 120000 index 0000000000..7ce7a489ea --- /dev/null +++ b/Lang/Zkl/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Brownian-tree b/Lang/Zkl/Brownian-tree new file mode 120000 index 0000000000..28acfa05c0 --- /dev/null +++ b/Lang/Zkl/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bulls-and-cows b/Lang/Zkl/Bulls-and-cows new file mode 120000 index 0000000000..b0d0f50461 --- /dev/null +++ b/Lang/Zkl/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Bulls-and-cows-Player b/Lang/Zkl/Bulls-and-cows-Player new file mode 120000 index 0000000000..4ea0805855 --- /dev/null +++ b/Lang/Zkl/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/Zkl \ No newline at end of file diff --git a/Lang/Zkl/CRC-32 b/Lang/Zkl/CRC-32 new file mode 120000 index 0000000000..3cb2d07762 --- /dev/null +++ b/Lang/Zkl/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Zkl \ No newline at end of file diff --git a/Lang/Zkl/CSV-data-manipulation b/Lang/Zkl/CSV-data-manipulation new file mode 120000 index 0000000000..d1a7afc122 --- /dev/null +++ b/Lang/Zkl/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/CSV-to-HTML-translation b/Lang/Zkl/CSV-to-HTML-translation new file mode 120000 index 0000000000..c35fa5e9eb --- /dev/null +++ b/Lang/Zkl/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Caesar-cipher b/Lang/Zkl/Caesar-cipher new file mode 120000 index 0000000000..74190a3b39 --- /dev/null +++ b/Lang/Zkl/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Calendar b/Lang/Zkl/Calendar new file mode 120000 index 0000000000..bd880a6524 --- /dev/null +++ b/Lang/Zkl/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Calendar---for-REAL-programmers b/Lang/Zkl/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..c1f688903f --- /dev/null +++ b/Lang/Zkl/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Call-a-foreign-language-function b/Lang/Zkl/Call-a-foreign-language-function new file mode 120000 index 0000000000..177cd7d379 --- /dev/null +++ b/Lang/Zkl/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Call-a-function b/Lang/Zkl/Call-a-function new file mode 120000 index 0000000000..332b549afc --- /dev/null +++ b/Lang/Zkl/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Call-a-function-in-a-shared-library b/Lang/Zkl/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..bbf5339b90 --- /dev/null +++ b/Lang/Zkl/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Call-an-object-method b/Lang/Zkl/Call-an-object-method new file mode 120000 index 0000000000..2f855a0333 --- /dev/null +++ b/Lang/Zkl/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Carmichael-3-strong-pseudoprimes b/Lang/Zkl/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..4ba8922528 --- /dev/null +++ b/Lang/Zkl/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Case-sensitivity-of-identifiers b/Lang/Zkl/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..1122d39ceb --- /dev/null +++ b/Lang/Zkl/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Casting-out-nines b/Lang/Zkl/Casting-out-nines new file mode 120000 index 0000000000..f29308587d --- /dev/null +++ b/Lang/Zkl/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Catalan-numbers b/Lang/Zkl/Catalan-numbers new file mode 120000 index 0000000000..89d4a889e3 --- /dev/null +++ b/Lang/Zkl/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Catalan-numbers-Pascals-triangle b/Lang/Zkl/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..da88d26013 --- /dev/null +++ b/Lang/Zkl/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Catamorphism b/Lang/Zkl/Catamorphism new file mode 120000 index 0000000000..d8bf093186 --- /dev/null +++ b/Lang/Zkl/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Character-codes b/Lang/Zkl/Character-codes new file mode 120000 index 0000000000..fa7b6ed656 --- /dev/null +++ b/Lang/Zkl/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Chat-server b/Lang/Zkl/Chat-server new file mode 120000 index 0000000000..67bf679cb0 --- /dev/null +++ b/Lang/Zkl/Chat-server @@ -0,0 +1 @@ +../../Task/Chat-server/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Check-that-file-exists b/Lang/Zkl/Check-that-file-exists new file mode 120000 index 0000000000..761e7a2bdf --- /dev/null +++ b/Lang/Zkl/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Checkpoint-synchronization b/Lang/Zkl/Checkpoint-synchronization new file mode 120000 index 0000000000..e4d914bd80 --- /dev/null +++ b/Lang/Zkl/Checkpoint-synchronization @@ -0,0 +1 @@ +../../Task/Checkpoint-synchronization/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Chinese-remainder-theorem b/Lang/Zkl/Chinese-remainder-theorem new file mode 120000 index 0000000000..4b3e3f92f8 --- /dev/null +++ b/Lang/Zkl/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Cholesky-decomposition b/Lang/Zkl/Cholesky-decomposition new file mode 120000 index 0000000000..fd9d721ac0 --- /dev/null +++ b/Lang/Zkl/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Circles-of-given-radius-through-two-points b/Lang/Zkl/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..00df276ae4 --- /dev/null +++ b/Lang/Zkl/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Classes b/Lang/Zkl/Classes new file mode 120000 index 0000000000..679e1523fc --- /dev/null +++ b/Lang/Zkl/Classes @@ -0,0 +1 @@ +../../Task/Classes/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Closest-pair-problem b/Lang/Zkl/Closest-pair-problem new file mode 120000 index 0000000000..4897e44d4e --- /dev/null +++ b/Lang/Zkl/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Closures-Value-capture b/Lang/Zkl/Closures-Value-capture new file mode 120000 index 0000000000..0b83681046 --- /dev/null +++ b/Lang/Zkl/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Collections b/Lang/Zkl/Collections new file mode 120000 index 0000000000..dd6421bb0f --- /dev/null +++ b/Lang/Zkl/Collections @@ -0,0 +1 @@ +../../Task/Collections/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Combinations b/Lang/Zkl/Combinations new file mode 120000 index 0000000000..d9a5d02305 --- /dev/null +++ b/Lang/Zkl/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Combinations-with-repetitions b/Lang/Zkl/Combinations-with-repetitions new file mode 120000 index 0000000000..c93f82e66a --- /dev/null +++ b/Lang/Zkl/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Comma-quibbling b/Lang/Zkl/Comma-quibbling new file mode 120000 index 0000000000..2b6a9569f6 --- /dev/null +++ b/Lang/Zkl/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Command-line-arguments b/Lang/Zkl/Command-line-arguments new file mode 120000 index 0000000000..c3cc535043 --- /dev/null +++ b/Lang/Zkl/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Comments b/Lang/Zkl/Comments new file mode 120000 index 0000000000..bd7c9619cf --- /dev/null +++ b/Lang/Zkl/Comments @@ -0,0 +1 @@ +../../Task/Comments/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Compile-time-calculation b/Lang/Zkl/Compile-time-calculation new file mode 120000 index 0000000000..382d8e09f4 --- /dev/null +++ b/Lang/Zkl/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Compound-data-type b/Lang/Zkl/Compound-data-type new file mode 120000 index 0000000000..e120550bc2 --- /dev/null +++ b/Lang/Zkl/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Concurrent-computing b/Lang/Zkl/Concurrent-computing new file mode 120000 index 0000000000..e53cd3441e --- /dev/null +++ b/Lang/Zkl/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Conditional-structures b/Lang/Zkl/Conditional-structures new file mode 120000 index 0000000000..3a836ac158 --- /dev/null +++ b/Lang/Zkl/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Constrained-genericity b/Lang/Zkl/Constrained-genericity new file mode 120000 index 0000000000..27f90c8d20 --- /dev/null +++ b/Lang/Zkl/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Constrained-random-points-on-a-circle b/Lang/Zkl/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..1662be3623 --- /dev/null +++ b/Lang/Zkl/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Continued-fraction b/Lang/Zkl/Continued-fraction new file mode 120000 index 0000000000..63f26ca3ad --- /dev/null +++ b/Lang/Zkl/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/Zkl/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..abdf5005cb --- /dev/null +++ b/Lang/Zkl/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- b/Lang/Zkl/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- new file mode 120000 index 0000000000..98e9863c16 --- /dev/null +++ b/Lang/Zkl/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Convert-decimal-number-to-rational b/Lang/Zkl/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..11f781ecb9 --- /dev/null +++ b/Lang/Zkl/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Conways-Game-of-Life b/Lang/Zkl/Conways-Game-of-Life new file mode 120000 index 0000000000..19898f012e --- /dev/null +++ b/Lang/Zkl/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Copy-a-string b/Lang/Zkl/Copy-a-string new file mode 120000 index 0000000000..5e9f82f92b --- /dev/null +++ b/Lang/Zkl/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Count-in-factors b/Lang/Zkl/Count-in-factors new file mode 120000 index 0000000000..a8c40fbf98 --- /dev/null +++ b/Lang/Zkl/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Count-in-octal b/Lang/Zkl/Count-in-octal new file mode 120000 index 0000000000..289a5b9cf2 --- /dev/null +++ b/Lang/Zkl/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Count-occurrences-of-a-substring b/Lang/Zkl/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..2d5dabacd5 --- /dev/null +++ b/Lang/Zkl/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Count-the-coins b/Lang/Zkl/Count-the-coins new file mode 120000 index 0000000000..772dcb00fa --- /dev/null +++ b/Lang/Zkl/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Create-a-file b/Lang/Zkl/Create-a-file new file mode 120000 index 0000000000..a3a5623492 --- /dev/null +++ b/Lang/Zkl/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Create-a-two-dimensional-array-at-runtime b/Lang/Zkl/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..5e0ec2d144 --- /dev/null +++ b/Lang/Zkl/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Create-an-HTML-table b/Lang/Zkl/Create-an-HTML-table new file mode 120000 index 0000000000..af1bca2a34 --- /dev/null +++ b/Lang/Zkl/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Currying b/Lang/Zkl/Currying new file mode 120000 index 0000000000..2f64d7ceb2 --- /dev/null +++ b/Lang/Zkl/Currying @@ -0,0 +1 @@ +../../Task/Currying/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Cut-a-rectangle b/Lang/Zkl/Cut-a-rectangle new file mode 120000 index 0000000000..769b5abc01 --- /dev/null +++ b/Lang/Zkl/Cut-a-rectangle @@ -0,0 +1 @@ +../../Task/Cut-a-rectangle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/DNS-query b/Lang/Zkl/DNS-query new file mode 120000 index 0000000000..8f056771b4 --- /dev/null +++ b/Lang/Zkl/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Date-format b/Lang/Zkl/Date-format new file mode 120000 index 0000000000..dd8e0e56fd --- /dev/null +++ b/Lang/Zkl/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Date-manipulation b/Lang/Zkl/Date-manipulation new file mode 120000 index 0000000000..0d0ed905fd --- /dev/null +++ b/Lang/Zkl/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Day-of-the-week b/Lang/Zkl/Day-of-the-week new file mode 120000 index 0000000000..f637126c9f --- /dev/null +++ b/Lang/Zkl/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Deal-cards-for-FreeCell b/Lang/Zkl/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..f2ebe132aa --- /dev/null +++ b/Lang/Zkl/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Deconvolution-1D b/Lang/Zkl/Deconvolution-1D new file mode 120000 index 0000000000..950ecced96 --- /dev/null +++ b/Lang/Zkl/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Delegates b/Lang/Zkl/Delegates new file mode 120000 index 0000000000..95ba92787c --- /dev/null +++ b/Lang/Zkl/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Delete-a-file b/Lang/Zkl/Delete-a-file new file mode 120000 index 0000000000..9d4a11382c --- /dev/null +++ b/Lang/Zkl/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Detect-division-by-zero b/Lang/Zkl/Detect-division-by-zero new file mode 120000 index 0000000000..574e2e871f --- /dev/null +++ b/Lang/Zkl/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Determine-if-a-string-is-numeric b/Lang/Zkl/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..6a0c097eae --- /dev/null +++ b/Lang/Zkl/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Digital-root b/Lang/Zkl/Digital-root new file mode 120000 index 0000000000..0734cb9f9e --- /dev/null +++ b/Lang/Zkl/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Digital-root-Multiplicative-digital-root b/Lang/Zkl/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..f3da0c0139 --- /dev/null +++ b/Lang/Zkl/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Dinesmans-multiple-dwelling-problem b/Lang/Zkl/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..4517fd1d5b --- /dev/null +++ b/Lang/Zkl/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Dining-philosophers b/Lang/Zkl/Dining-philosophers new file mode 120000 index 0000000000..f588023c8a --- /dev/null +++ b/Lang/Zkl/Dining-philosophers @@ -0,0 +1 @@ +../../Task/Dining-philosophers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Discordian-date b/Lang/Zkl/Discordian-date new file mode 120000 index 0000000000..d0c9f74097 --- /dev/null +++ b/Lang/Zkl/Discordian-date @@ -0,0 +1 @@ +../../Task/Discordian-date/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Dot-product b/Lang/Zkl/Dot-product new file mode 120000 index 0000000000..6b1b5a09cd --- /dev/null +++ b/Lang/Zkl/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Doubly-linked-list-Definition b/Lang/Zkl/Doubly-linked-list-Definition new file mode 120000 index 0000000000..ceb962bfae --- /dev/null +++ b/Lang/Zkl/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Doubly-linked-list-Element-definition b/Lang/Zkl/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..7287a852a8 --- /dev/null +++ b/Lang/Zkl/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Doubly-linked-list-Element-insertion b/Lang/Zkl/Doubly-linked-list-Element-insertion new file mode 120000 index 0000000000..e2e19c66b8 --- /dev/null +++ b/Lang/Zkl/Doubly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-insertion/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Doubly-linked-list-Traversal b/Lang/Zkl/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..8dc1ed9d9c --- /dev/null +++ b/Lang/Zkl/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Dragon-curve b/Lang/Zkl/Dragon-curve new file mode 120000 index 0000000000..55b2ce0a0e --- /dev/null +++ b/Lang/Zkl/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Draw-a-clock b/Lang/Zkl/Draw-a-clock new file mode 120000 index 0000000000..7e34ffe188 --- /dev/null +++ b/Lang/Zkl/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Draw-a-cuboid b/Lang/Zkl/Draw-a-cuboid new file mode 120000 index 0000000000..c7c82880f7 --- /dev/null +++ b/Lang/Zkl/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Draw-a-sphere b/Lang/Zkl/Draw-a-sphere new file mode 120000 index 0000000000..bf3760329b --- /dev/null +++ b/Lang/Zkl/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Dutch-national-flag-problem b/Lang/Zkl/Dutch-national-flag-problem new file mode 120000 index 0000000000..c6a20a039d --- /dev/null +++ b/Lang/Zkl/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Dynamic-variable-names b/Lang/Zkl/Dynamic-variable-names new file mode 120000 index 0000000000..593c261cbb --- /dev/null +++ b/Lang/Zkl/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Echo-server b/Lang/Zkl/Echo-server new file mode 120000 index 0000000000..7069ef0037 --- /dev/null +++ b/Lang/Zkl/Echo-server @@ -0,0 +1 @@ +../../Task/Echo-server/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Element-wise-operations b/Lang/Zkl/Element-wise-operations new file mode 120000 index 0000000000..06685a7dee --- /dev/null +++ b/Lang/Zkl/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Empty-directory b/Lang/Zkl/Empty-directory new file mode 120000 index 0000000000..851959afa4 --- /dev/null +++ b/Lang/Zkl/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Empty-program b/Lang/Zkl/Empty-program new file mode 120000 index 0000000000..e43395dd63 --- /dev/null +++ b/Lang/Zkl/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Empty-string b/Lang/Zkl/Empty-string new file mode 120000 index 0000000000..3fcbb7eaaa --- /dev/null +++ b/Lang/Zkl/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Enforced-immutability b/Lang/Zkl/Enforced-immutability new file mode 120000 index 0000000000..b19dc245be --- /dev/null +++ b/Lang/Zkl/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Entropy b/Lang/Zkl/Entropy new file mode 120000 index 0000000000..9c5d06c512 --- /dev/null +++ b/Lang/Zkl/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Enumerations b/Lang/Zkl/Enumerations new file mode 120000 index 0000000000..43ccb8ea27 --- /dev/null +++ b/Lang/Zkl/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Environment-variables b/Lang/Zkl/Environment-variables new file mode 120000 index 0000000000..e05257d3f2 --- /dev/null +++ b/Lang/Zkl/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Equilibrium-index b/Lang/Zkl/Equilibrium-index new file mode 120000 index 0000000000..62cbfa3e74 --- /dev/null +++ b/Lang/Zkl/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Ethiopian-multiplication b/Lang/Zkl/Ethiopian-multiplication new file mode 120000 index 0000000000..af91b2acf7 --- /dev/null +++ b/Lang/Zkl/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Euler-method b/Lang/Zkl/Euler-method new file mode 120000 index 0000000000..58607bb395 --- /dev/null +++ b/Lang/Zkl/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Evaluate-binomial-coefficients b/Lang/Zkl/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..3e42037a52 --- /dev/null +++ b/Lang/Zkl/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Even-or-odd b/Lang/Zkl/Even-or-odd new file mode 120000 index 0000000000..313ce50b7a --- /dev/null +++ b/Lang/Zkl/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Events b/Lang/Zkl/Events new file mode 120000 index 0000000000..e2fb7e747c --- /dev/null +++ b/Lang/Zkl/Events @@ -0,0 +1 @@ +../../Task/Events/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Evolutionary-algorithm b/Lang/Zkl/Evolutionary-algorithm new file mode 120000 index 0000000000..c8faacd9d3 --- /dev/null +++ b/Lang/Zkl/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Exceptions b/Lang/Zkl/Exceptions new file mode 120000 index 0000000000..65273aad85 --- /dev/null +++ b/Lang/Zkl/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Zkl/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..8b74fe5c58 --- /dev/null +++ b/Lang/Zkl/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Executable-library b/Lang/Zkl/Executable-library new file mode 120000 index 0000000000..e8cc097d66 --- /dev/null +++ b/Lang/Zkl/Executable-library @@ -0,0 +1 @@ +../../Task/Executable-library/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Execute-Brain---- b/Lang/Zkl/Execute-Brain---- new file mode 120000 index 0000000000..12e5d3cac8 --- /dev/null +++ b/Lang/Zkl/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Execute-HQ9+ b/Lang/Zkl/Execute-HQ9+ new file mode 120000 index 0000000000..e1ea88c660 --- /dev/null +++ b/Lang/Zkl/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Execute-a-Markov-algorithm b/Lang/Zkl/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..7af93b664f --- /dev/null +++ b/Lang/Zkl/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Execute-a-system-command b/Lang/Zkl/Execute-a-system-command new file mode 120000 index 0000000000..ba56da7ecc --- /dev/null +++ b/Lang/Zkl/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Exponentiation-operator b/Lang/Zkl/Exponentiation-operator new file mode 120000 index 0000000000..b921cd8bfa --- /dev/null +++ b/Lang/Zkl/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Extensible-prime-generator b/Lang/Zkl/Extensible-prime-generator new file mode 120000 index 0000000000..ffb7ee698b --- /dev/null +++ b/Lang/Zkl/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Factorial b/Lang/Zkl/Factorial new file mode 120000 index 0000000000..0b155a0043 --- /dev/null +++ b/Lang/Zkl/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Factors-of-a-Mersenne-number b/Lang/Zkl/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..f80356ecc9 --- /dev/null +++ b/Lang/Zkl/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Factors-of-an-integer b/Lang/Zkl/Factors-of-an-integer new file mode 120000 index 0000000000..2d4f3c19a7 --- /dev/null +++ b/Lang/Zkl/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Fast-Fourier-transform b/Lang/Zkl/Fast-Fourier-transform new file mode 120000 index 0000000000..2455d8f180 --- /dev/null +++ b/Lang/Zkl/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Fibonacci-n-step-number-sequences b/Lang/Zkl/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..dd9fd3e962 --- /dev/null +++ b/Lang/Zkl/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Fibonacci-sequence b/Lang/Zkl/Fibonacci-sequence new file mode 120000 index 0000000000..71a9327e39 --- /dev/null +++ b/Lang/Zkl/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Fibonacci-word b/Lang/Zkl/Fibonacci-word new file mode 120000 index 0000000000..81d83bedfa --- /dev/null +++ b/Lang/Zkl/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Fibonacci-word-fractal b/Lang/Zkl/Fibonacci-word-fractal new file mode 120000 index 0000000000..136944e095 --- /dev/null +++ b/Lang/Zkl/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Zkl \ No newline at end of file diff --git a/Lang/Zkl/File-input-output b/Lang/Zkl/File-input-output new file mode 120000 index 0000000000..6012449504 --- /dev/null +++ b/Lang/Zkl/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Zkl \ No newline at end of file diff --git a/Lang/Zkl/File-modification-time b/Lang/Zkl/File-modification-time new file mode 120000 index 0000000000..e6872db5ad --- /dev/null +++ b/Lang/Zkl/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/Zkl \ No newline at end of file diff --git a/Lang/Zkl/File-size b/Lang/Zkl/File-size new file mode 120000 index 0000000000..0ef8866528 --- /dev/null +++ b/Lang/Zkl/File-size @@ -0,0 +1 @@ +../../Task/File-size/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Filter b/Lang/Zkl/Filter new file mode 120000 index 0000000000..e9f3be37a3 --- /dev/null +++ b/Lang/Zkl/Filter @@ -0,0 +1 @@ +../../Task/Filter/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Find-common-directory-path b/Lang/Zkl/Find-common-directory-path new file mode 120000 index 0000000000..2c4e19b182 --- /dev/null +++ b/Lang/Zkl/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/Zkl/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..7342b2d3f5 --- /dev/null +++ b/Lang/Zkl/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Find-limit-of-recursion b/Lang/Zkl/Find-limit-of-recursion new file mode 120000 index 0000000000..85d3ce7ade --- /dev/null +++ b/Lang/Zkl/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Find-the-missing-permutation b/Lang/Zkl/Find-the-missing-permutation new file mode 120000 index 0000000000..c538225161 --- /dev/null +++ b/Lang/Zkl/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/First-class-environments b/Lang/Zkl/First-class-environments new file mode 120000 index 0000000000..c8392167c3 --- /dev/null +++ b/Lang/Zkl/First-class-environments @@ -0,0 +1 @@ +../../Task/First-class-environments/Zkl \ No newline at end of file diff --git a/Lang/Zkl/First-class-functions b/Lang/Zkl/First-class-functions new file mode 120000 index 0000000000..98f301a6e4 --- /dev/null +++ b/Lang/Zkl/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/Zkl \ No newline at end of file diff --git a/Lang/Zkl/First-class-functions-Use-numbers-analogously b/Lang/Zkl/First-class-functions-Use-numbers-analogously new file mode 120000 index 0000000000..73963dbed9 --- /dev/null +++ b/Lang/Zkl/First-class-functions-Use-numbers-analogously @@ -0,0 +1 @@ +../../Task/First-class-functions-Use-numbers-analogously/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Five-weekends b/Lang/Zkl/Five-weekends new file mode 120000 index 0000000000..eb03cff6f2 --- /dev/null +++ b/Lang/Zkl/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Zkl \ No newline at end of file diff --git a/Lang/Zkl/FizzBuzz b/Lang/Zkl/FizzBuzz new file mode 120000 index 0000000000..a6a033a886 --- /dev/null +++ b/Lang/Zkl/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Flatten-a-list b/Lang/Zkl/Flatten-a-list new file mode 120000 index 0000000000..6be311b82f --- /dev/null +++ b/Lang/Zkl/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Flow-control-structures b/Lang/Zkl/Flow-control-structures new file mode 120000 index 0000000000..503ab72c70 --- /dev/null +++ b/Lang/Zkl/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Floyds-triangle b/Lang/Zkl/Floyds-triangle new file mode 120000 index 0000000000..97d3c607a3 --- /dev/null +++ b/Lang/Zkl/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Fork b/Lang/Zkl/Fork new file mode 120000 index 0000000000..4e52f67bac --- /dev/null +++ b/Lang/Zkl/Fork @@ -0,0 +1 @@ +../../Task/Fork/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Formal-power-series b/Lang/Zkl/Formal-power-series new file mode 120000 index 0000000000..6c7d591133 --- /dev/null +++ b/Lang/Zkl/Formal-power-series @@ -0,0 +1 @@ +../../Task/Formal-power-series/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Formatted-numeric-output b/Lang/Zkl/Formatted-numeric-output new file mode 120000 index 0000000000..2bce25c0fd --- /dev/null +++ b/Lang/Zkl/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Forward-difference b/Lang/Zkl/Forward-difference new file mode 120000 index 0000000000..973c19ea94 --- /dev/null +++ b/Lang/Zkl/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Four-bit-adder b/Lang/Zkl/Four-bit-adder new file mode 120000 index 0000000000..71f523402e --- /dev/null +++ b/Lang/Zkl/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Fractal-tree b/Lang/Zkl/Fractal-tree new file mode 120000 index 0000000000..f937ba3ca5 --- /dev/null +++ b/Lang/Zkl/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Fractran b/Lang/Zkl/Fractran new file mode 120000 index 0000000000..b099ed551a --- /dev/null +++ b/Lang/Zkl/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Function-composition b/Lang/Zkl/Function-composition new file mode 120000 index 0000000000..1e213ba02c --- /dev/null +++ b/Lang/Zkl/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Function-definition b/Lang/Zkl/Function-definition new file mode 120000 index 0000000000..856160cd78 --- /dev/null +++ b/Lang/Zkl/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Function-prototype b/Lang/Zkl/Function-prototype new file mode 120000 index 0000000000..75d447b489 --- /dev/null +++ b/Lang/Zkl/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Gamma-function b/Lang/Zkl/Gamma-function new file mode 120000 index 0000000000..d83b6efaa2 --- /dev/null +++ b/Lang/Zkl/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Gaussian-elimination b/Lang/Zkl/Gaussian-elimination new file mode 120000 index 0000000000..dffb66d924 --- /dev/null +++ b/Lang/Zkl/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Generate-Chess960-starting-position b/Lang/Zkl/Generate-Chess960-starting-position new file mode 120000 index 0000000000..330d8bba0d --- /dev/null +++ b/Lang/Zkl/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Generate-lower-case-ASCII-alphabet b/Lang/Zkl/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..32d0bda766 --- /dev/null +++ b/Lang/Zkl/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Generator-Exponential b/Lang/Zkl/Generator-Exponential new file mode 120000 index 0000000000..8eae93c1d4 --- /dev/null +++ b/Lang/Zkl/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Generic-swap b/Lang/Zkl/Generic-swap new file mode 120000 index 0000000000..9234cac612 --- /dev/null +++ b/Lang/Zkl/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Globally-replace-text-in-several-files b/Lang/Zkl/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..368052c7c2 --- /dev/null +++ b/Lang/Zkl/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Gray-code b/Lang/Zkl/Gray-code new file mode 120000 index 0000000000..b54385e1eb --- /dev/null +++ b/Lang/Zkl/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Grayscale-image b/Lang/Zkl/Grayscale-image new file mode 120000 index 0000000000..3541322810 --- /dev/null +++ b/Lang/Zkl/Grayscale-image @@ -0,0 +1 @@ +../../Task/Grayscale-image/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Greatest-common-divisor b/Lang/Zkl/Greatest-common-divisor new file mode 120000 index 0000000000..9ccbe15727 --- /dev/null +++ b/Lang/Zkl/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Greatest-element-of-a-list b/Lang/Zkl/Greatest-element-of-a-list new file mode 120000 index 0000000000..790ef60c27 --- /dev/null +++ b/Lang/Zkl/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Greatest-subsequential-sum b/Lang/Zkl/Greatest-subsequential-sum new file mode 120000 index 0000000000..14011c22e4 --- /dev/null +++ b/Lang/Zkl/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Greyscale-bars-Display b/Lang/Zkl/Greyscale-bars-Display new file mode 120000 index 0000000000..46ebe1c5de --- /dev/null +++ b/Lang/Zkl/Greyscale-bars-Display @@ -0,0 +1 @@ +../../Task/Greyscale-bars-Display/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Guess-the-number b/Lang/Zkl/Guess-the-number new file mode 120000 index 0000000000..9c1c1dee07 --- /dev/null +++ b/Lang/Zkl/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Guess-the-number-With-feedback b/Lang/Zkl/Guess-the-number-With-feedback new file mode 120000 index 0000000000..dbcafd895e --- /dev/null +++ b/Lang/Zkl/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Guess-the-number-With-feedback--player- b/Lang/Zkl/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..bba338b3d7 --- /dev/null +++ b/Lang/Zkl/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/Zkl \ No newline at end of file diff --git a/Lang/Zkl/HTTP b/Lang/Zkl/HTTP new file mode 120000 index 0000000000..5c26c31b36 --- /dev/null +++ b/Lang/Zkl/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Zkl \ No newline at end of file diff --git a/Lang/Zkl/HTTPS b/Lang/Zkl/HTTPS new file mode 120000 index 0000000000..0b4183c994 --- /dev/null +++ b/Lang/Zkl/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Zkl \ No newline at end of file diff --git a/Lang/Zkl/HTTPS-Authenticated b/Lang/Zkl/HTTPS-Authenticated new file mode 120000 index 0000000000..3d60ebb1a0 --- /dev/null +++ b/Lang/Zkl/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/Zkl \ No newline at end of file diff --git a/Lang/Zkl/HTTPS-Client-authenticated b/Lang/Zkl/HTTPS-Client-authenticated new file mode 120000 index 0000000000..876772b552 --- /dev/null +++ b/Lang/Zkl/HTTPS-Client-authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Client-authenticated/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hailstone-sequence b/Lang/Zkl/Hailstone-sequence new file mode 120000 index 0000000000..70b1eb45d8 --- /dev/null +++ b/Lang/Zkl/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hamming-numbers b/Lang/Zkl/Hamming-numbers new file mode 120000 index 0000000000..cf2a649cd9 --- /dev/null +++ b/Lang/Zkl/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Handle-a-signal b/Lang/Zkl/Handle-a-signal new file mode 120000 index 0000000000..7ebdd0527b --- /dev/null +++ b/Lang/Zkl/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Happy-numbers b/Lang/Zkl/Happy-numbers new file mode 120000 index 0000000000..58257e2ab6 --- /dev/null +++ b/Lang/Zkl/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Harshad-or-Niven-series b/Lang/Zkl/Harshad-or-Niven-series new file mode 120000 index 0000000000..6d32174b77 --- /dev/null +++ b/Lang/Zkl/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hash-from-two-arrays b/Lang/Zkl/Hash-from-two-arrays new file mode 120000 index 0000000000..d5dd6ca1f8 --- /dev/null +++ b/Lang/Zkl/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hash-join b/Lang/Zkl/Hash-join new file mode 120000 index 0000000000..2b2a41d623 --- /dev/null +++ b/Lang/Zkl/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Haversine-formula b/Lang/Zkl/Haversine-formula new file mode 120000 index 0000000000..5cc345f145 --- /dev/null +++ b/Lang/Zkl/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hello-world-Graphical b/Lang/Zkl/Hello-world-Graphical new file mode 120000 index 0000000000..b37475aa58 --- /dev/null +++ b/Lang/Zkl/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hello-world-Newline-omission b/Lang/Zkl/Hello-world-Newline-omission new file mode 120000 index 0000000000..48dab76c28 --- /dev/null +++ b/Lang/Zkl/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hello-world-Standard-error b/Lang/Zkl/Hello-world-Standard-error new file mode 120000 index 0000000000..e758da0628 --- /dev/null +++ b/Lang/Zkl/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hello-world-Text b/Lang/Zkl/Hello-world-Text new file mode 120000 index 0000000000..ec090c7cf5 --- /dev/null +++ b/Lang/Zkl/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hello-world-Web-server b/Lang/Zkl/Hello-world-Web-server new file mode 120000 index 0000000000..c801bb45ad --- /dev/null +++ b/Lang/Zkl/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Here-document b/Lang/Zkl/Here-document new file mode 120000 index 0000000000..361ca21fae --- /dev/null +++ b/Lang/Zkl/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Heronian-triangles b/Lang/Zkl/Heronian-triangles new file mode 120000 index 0000000000..e17fa05917 --- /dev/null +++ b/Lang/Zkl/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hickerson-series-of-almost-integers b/Lang/Zkl/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..0924ab9154 --- /dev/null +++ b/Lang/Zkl/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Higher-order-functions b/Lang/Zkl/Higher-order-functions new file mode 120000 index 0000000000..a6599cc3b8 --- /dev/null +++ b/Lang/Zkl/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Zkl \ No newline at end of file diff --git a/Lang/Zkl/History-variables b/Lang/Zkl/History-variables new file mode 120000 index 0000000000..da2a9f2c46 --- /dev/null +++ b/Lang/Zkl/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hofstadter-Conway-$10,000-sequence b/Lang/Zkl/Hofstadter-Conway-$10,000-sequence new file mode 120000 index 0000000000..e2c5574303 --- /dev/null +++ b/Lang/Zkl/Hofstadter-Conway-$10,000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10,000-sequence/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hofstadter-Figure-Figure-sequences b/Lang/Zkl/Hofstadter-Figure-Figure-sequences new file mode 120000 index 0000000000..3e3228df6d --- /dev/null +++ b/Lang/Zkl/Hofstadter-Figure-Figure-sequences @@ -0,0 +1 @@ +../../Task/Hofstadter-Figure-Figure-sequences/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hofstadter-Q-sequence b/Lang/Zkl/Hofstadter-Q-sequence new file mode 120000 index 0000000000..fbd5f583be --- /dev/null +++ b/Lang/Zkl/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Horizontal-sundial-calculations b/Lang/Zkl/Horizontal-sundial-calculations new file mode 120000 index 0000000000..3a9c663c85 --- /dev/null +++ b/Lang/Zkl/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Horners-rule-for-polynomial-evaluation b/Lang/Zkl/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..368c203951 --- /dev/null +++ b/Lang/Zkl/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hostname b/Lang/Zkl/Hostname new file mode 120000 index 0000000000..23071d3735 --- /dev/null +++ b/Lang/Zkl/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Hough-transform b/Lang/Zkl/Hough-transform new file mode 120000 index 0000000000..ad231867bd --- /dev/null +++ b/Lang/Zkl/Hough-transform @@ -0,0 +1 @@ +../../Task/Hough-transform/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Huffman-coding b/Lang/Zkl/Huffman-coding new file mode 120000 index 0000000000..89e7750c55 --- /dev/null +++ b/Lang/Zkl/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Zkl \ No newline at end of file diff --git a/Lang/Zkl/I-before-E-except-after-C b/Lang/Zkl/I-before-E-except-after-C new file mode 120000 index 0000000000..7276ba4f88 --- /dev/null +++ b/Lang/Zkl/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Zkl \ No newline at end of file diff --git a/Lang/Zkl/IBAN b/Lang/Zkl/IBAN new file mode 120000 index 0000000000..42b99892a0 --- /dev/null +++ b/Lang/Zkl/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Identity-matrix b/Lang/Zkl/Identity-matrix new file mode 120000 index 0000000000..478ddf9db0 --- /dev/null +++ b/Lang/Zkl/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Include-a-file b/Lang/Zkl/Include-a-file new file mode 120000 index 0000000000..de8713054a --- /dev/null +++ b/Lang/Zkl/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Increment-a-numerical-string b/Lang/Zkl/Increment-a-numerical-string new file mode 120000 index 0000000000..463351f623 --- /dev/null +++ b/Lang/Zkl/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Infinity b/Lang/Zkl/Infinity new file mode 120000 index 0000000000..c1fc28608c --- /dev/null +++ b/Lang/Zkl/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Inheritance-Multiple b/Lang/Zkl/Inheritance-Multiple new file mode 120000 index 0000000000..b1b63619ca --- /dev/null +++ b/Lang/Zkl/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Inheritance-Single b/Lang/Zkl/Inheritance-Single new file mode 120000 index 0000000000..822effc844 --- /dev/null +++ b/Lang/Zkl/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Input-loop b/Lang/Zkl/Input-loop new file mode 120000 index 0000000000..02e7550d34 --- /dev/null +++ b/Lang/Zkl/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Integer-comparison b/Lang/Zkl/Integer-comparison new file mode 120000 index 0000000000..a7b19dae3c --- /dev/null +++ b/Lang/Zkl/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Integer-overflow b/Lang/Zkl/Integer-overflow new file mode 120000 index 0000000000..d7ac548fca --- /dev/null +++ b/Lang/Zkl/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Integer-sequence b/Lang/Zkl/Integer-sequence new file mode 120000 index 0000000000..2022cc758a --- /dev/null +++ b/Lang/Zkl/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Introspection b/Lang/Zkl/Introspection new file mode 120000 index 0000000000..4a1cc16759 --- /dev/null +++ b/Lang/Zkl/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Inverted-syntax b/Lang/Zkl/Inverted-syntax new file mode 120000 index 0000000000..f4f21bb69c --- /dev/null +++ b/Lang/Zkl/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Iterated-digits-squaring b/Lang/Zkl/Iterated-digits-squaring new file mode 120000 index 0000000000..38fc04a6b6 --- /dev/null +++ b/Lang/Zkl/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Zkl \ No newline at end of file diff --git a/Lang/Zkl/JSON b/Lang/Zkl/JSON new file mode 120000 index 0000000000..9eb1402ebf --- /dev/null +++ b/Lang/Zkl/JSON @@ -0,0 +1 @@ +../../Task/JSON/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Jensens-Device b/Lang/Zkl/Jensens-Device new file mode 120000 index 0000000000..4fff202653 --- /dev/null +++ b/Lang/Zkl/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Josephus-problem b/Lang/Zkl/Josephus-problem new file mode 120000 index 0000000000..d93b6c41e8 --- /dev/null +++ b/Lang/Zkl/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Zkl \ No newline at end of file diff --git a/Lang/Zkl/K-d-tree b/Lang/Zkl/K-d-tree new file mode 120000 index 0000000000..2167e4da29 --- /dev/null +++ b/Lang/Zkl/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Kaprekar-numbers b/Lang/Zkl/Kaprekar-numbers new file mode 120000 index 0000000000..57550b56f1 --- /dev/null +++ b/Lang/Zkl/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Knapsack-problem-0-1 b/Lang/Zkl/Knapsack-problem-0-1 new file mode 120000 index 0000000000..413f9f67ba --- /dev/null +++ b/Lang/Zkl/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Knapsack-problem-Bounded b/Lang/Zkl/Knapsack-problem-Bounded new file mode 120000 index 0000000000..827077cd4a --- /dev/null +++ b/Lang/Zkl/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Knapsack-problem-Continuous b/Lang/Zkl/Knapsack-problem-Continuous new file mode 120000 index 0000000000..1ae43ad946 --- /dev/null +++ b/Lang/Zkl/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Knapsack-problem-Unbounded b/Lang/Zkl/Knapsack-problem-Unbounded new file mode 120000 index 0000000000..c384326633 --- /dev/null +++ b/Lang/Zkl/Knapsack-problem-Unbounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Unbounded/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Knights-tour b/Lang/Zkl/Knights-tour new file mode 120000 index 0000000000..890e5135e1 --- /dev/null +++ b/Lang/Zkl/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Knuth-shuffle b/Lang/Zkl/Knuth-shuffle new file mode 120000 index 0000000000..edd58d775b --- /dev/null +++ b/Lang/Zkl/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Knuths-algorithm-S b/Lang/Zkl/Knuths-algorithm-S new file mode 120000 index 0000000000..e2cb0cfe67 --- /dev/null +++ b/Lang/Zkl/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/Zkl \ No newline at end of file diff --git a/Lang/Zkl/LU-decomposition b/Lang/Zkl/LU-decomposition new file mode 120000 index 0000000000..88e9e92422 --- /dev/null +++ b/Lang/Zkl/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/Zkl \ No newline at end of file diff --git a/Lang/Zkl/LZW-compression b/Lang/Zkl/LZW-compression new file mode 120000 index 0000000000..35892dffd8 --- /dev/null +++ b/Lang/Zkl/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Langtons-ant b/Lang/Zkl/Langtons-ant new file mode 120000 index 0000000000..02e539b77f --- /dev/null +++ b/Lang/Zkl/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Largest-int-from-concatenated-ints b/Lang/Zkl/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..705f865d36 --- /dev/null +++ b/Lang/Zkl/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Last-Friday-of-each-month b/Lang/Zkl/Last-Friday-of-each-month new file mode 120000 index 0000000000..c27a48c78f --- /dev/null +++ b/Lang/Zkl/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Last-letter-first-letter b/Lang/Zkl/Last-letter-first-letter new file mode 120000 index 0000000000..c085c2b435 --- /dev/null +++ b/Lang/Zkl/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Leap-year b/Lang/Zkl/Leap-year new file mode 120000 index 0000000000..ab047c1d39 --- /dev/null +++ b/Lang/Zkl/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Least-common-multiple b/Lang/Zkl/Least-common-multiple new file mode 120000 index 0000000000..5d8aea6869 --- /dev/null +++ b/Lang/Zkl/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Left-factorials b/Lang/Zkl/Left-factorials new file mode 120000 index 0000000000..e8e47ee5fe --- /dev/null +++ b/Lang/Zkl/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Letter-frequency b/Lang/Zkl/Letter-frequency new file mode 120000 index 0000000000..acdc48f4dd --- /dev/null +++ b/Lang/Zkl/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Levenshtein-distance b/Lang/Zkl/Levenshtein-distance new file mode 120000 index 0000000000..2d0f6c0c5d --- /dev/null +++ b/Lang/Zkl/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Linear-congruential-generator b/Lang/Zkl/Linear-congruential-generator new file mode 120000 index 0000000000..d04dfa1733 --- /dev/null +++ b/Lang/Zkl/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/Zkl \ No newline at end of file diff --git a/Lang/Zkl/List-comprehensions b/Lang/Zkl/List-comprehensions new file mode 120000 index 0000000000..0949f4c374 --- /dev/null +++ b/Lang/Zkl/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Literals-Floating-point b/Lang/Zkl/Literals-Floating-point new file mode 120000 index 0000000000..60a2026de6 --- /dev/null +++ b/Lang/Zkl/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Literals-Integer b/Lang/Zkl/Literals-Integer new file mode 120000 index 0000000000..fce4b2924c --- /dev/null +++ b/Lang/Zkl/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Literals-String b/Lang/Zkl/Literals-String new file mode 120000 index 0000000000..68ce1b3d03 --- /dev/null +++ b/Lang/Zkl/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Logical-operations b/Lang/Zkl/Logical-operations new file mode 120000 index 0000000000..d332a8ef7c --- /dev/null +++ b/Lang/Zkl/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Long-multiplication b/Lang/Zkl/Long-multiplication new file mode 120000 index 0000000000..94d166c5c2 --- /dev/null +++ b/Lang/Zkl/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Longest-common-subsequence b/Lang/Zkl/Longest-common-subsequence new file mode 120000 index 0000000000..a9c7f12751 --- /dev/null +++ b/Lang/Zkl/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Longest-increasing-subsequence b/Lang/Zkl/Longest-increasing-subsequence new file mode 120000 index 0000000000..e4bcbdf78f --- /dev/null +++ b/Lang/Zkl/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Longest-string-challenge b/Lang/Zkl/Longest-string-challenge new file mode 120000 index 0000000000..3f196bfd9a --- /dev/null +++ b/Lang/Zkl/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Look-and-say-sequence b/Lang/Zkl/Look-and-say-sequence new file mode 120000 index 0000000000..c0bb10391c --- /dev/null +++ b/Lang/Zkl/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Loop-over-multiple-arrays-simultaneously b/Lang/Zkl/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..542b2d63b6 --- /dev/null +++ b/Lang/Zkl/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Loops-Break b/Lang/Zkl/Loops-Break new file mode 120000 index 0000000000..21dddca885 --- /dev/null +++ b/Lang/Zkl/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Loops-Continue b/Lang/Zkl/Loops-Continue new file mode 120000 index 0000000000..89ed2ddd12 --- /dev/null +++ b/Lang/Zkl/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Loops-Do-while b/Lang/Zkl/Loops-Do-while new file mode 120000 index 0000000000..ea89d6869c --- /dev/null +++ b/Lang/Zkl/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Loops-Downward-for b/Lang/Zkl/Loops-Downward-for new file mode 120000 index 0000000000..7c7eef1391 --- /dev/null +++ b/Lang/Zkl/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Loops-For b/Lang/Zkl/Loops-For new file mode 120000 index 0000000000..9b977bef78 --- /dev/null +++ b/Lang/Zkl/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Loops-For-with-a-specified-step b/Lang/Zkl/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..afb2b44fa5 --- /dev/null +++ b/Lang/Zkl/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Loops-Foreach b/Lang/Zkl/Loops-Foreach new file mode 120000 index 0000000000..57dff8206b --- /dev/null +++ b/Lang/Zkl/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Loops-Infinite b/Lang/Zkl/Loops-Infinite new file mode 120000 index 0000000000..0f27b3ad97 --- /dev/null +++ b/Lang/Zkl/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Loops-N-plus-one-half b/Lang/Zkl/Loops-N-plus-one-half new file mode 120000 index 0000000000..a0a1bfc324 --- /dev/null +++ b/Lang/Zkl/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Loops-Nested b/Lang/Zkl/Loops-Nested new file mode 120000 index 0000000000..737a9cb941 --- /dev/null +++ b/Lang/Zkl/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Loops-While b/Lang/Zkl/Loops-While new file mode 120000 index 0000000000..b11a2158bd --- /dev/null +++ b/Lang/Zkl/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Lucas-Lehmer-test b/Lang/Zkl/Lucas-Lehmer-test new file mode 120000 index 0000000000..e7b6a9f395 --- /dev/null +++ b/Lang/Zkl/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Ludic-numbers b/Lang/Zkl/Ludic-numbers new file mode 120000 index 0000000000..550bc8559a --- /dev/null +++ b/Lang/Zkl/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Luhn-test-of-credit-card-numbers b/Lang/Zkl/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..f55b81b70c --- /dev/null +++ b/Lang/Zkl/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/MD5 b/Lang/Zkl/MD5 new file mode 120000 index 0000000000..e8f5697241 --- /dev/null +++ b/Lang/Zkl/MD5 @@ -0,0 +1 @@ +../../Task/MD5/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Mad-Libs b/Lang/Zkl/Mad-Libs new file mode 120000 index 0000000000..f0f38aa72f --- /dev/null +++ b/Lang/Zkl/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Magic-squares-of-odd-order b/Lang/Zkl/Magic-squares-of-odd-order new file mode 120000 index 0000000000..672146f310 --- /dev/null +++ b/Lang/Zkl/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Main-step-of-GOST-28147-89 b/Lang/Zkl/Main-step-of-GOST-28147-89 new file mode 120000 index 0000000000..f338dd6c2a --- /dev/null +++ b/Lang/Zkl/Main-step-of-GOST-28147-89 @@ -0,0 +1 @@ +../../Task/Main-step-of-GOST-28147-89/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Make-directory-path b/Lang/Zkl/Make-directory-path new file mode 120000 index 0000000000..c16e3165a5 --- /dev/null +++ b/Lang/Zkl/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Man-or-boy-test b/Lang/Zkl/Man-or-boy-test new file mode 120000 index 0000000000..636d5619a9 --- /dev/null +++ b/Lang/Zkl/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Mandelbrot-set b/Lang/Zkl/Mandelbrot-set new file mode 120000 index 0000000000..6a74e2b927 --- /dev/null +++ b/Lang/Zkl/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Map-range b/Lang/Zkl/Map-range new file mode 120000 index 0000000000..5b0a3255e4 --- /dev/null +++ b/Lang/Zkl/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Matrix-arithmetic b/Lang/Zkl/Matrix-arithmetic new file mode 120000 index 0000000000..f52362743e --- /dev/null +++ b/Lang/Zkl/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Matrix-multiplication b/Lang/Zkl/Matrix-multiplication new file mode 120000 index 0000000000..7b326b0fc4 --- /dev/null +++ b/Lang/Zkl/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Matrix-transposition b/Lang/Zkl/Matrix-transposition new file mode 120000 index 0000000000..a5a4c570a5 --- /dev/null +++ b/Lang/Zkl/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Maximum-triangle-path-sum b/Lang/Zkl/Maximum-triangle-path-sum new file mode 120000 index 0000000000..8a374e344f --- /dev/null +++ b/Lang/Zkl/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Maze-generation b/Lang/Zkl/Maze-generation new file mode 120000 index 0000000000..76429e4803 --- /dev/null +++ b/Lang/Zkl/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Maze-solving b/Lang/Zkl/Maze-solving new file mode 120000 index 0000000000..c6dcd289a2 --- /dev/null +++ b/Lang/Zkl/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Median-filter b/Lang/Zkl/Median-filter new file mode 120000 index 0000000000..d9c3f27aa8 --- /dev/null +++ b/Lang/Zkl/Median-filter @@ -0,0 +1 @@ +../../Task/Median-filter/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Memory-allocation b/Lang/Zkl/Memory-allocation new file mode 120000 index 0000000000..a9e5e1654b --- /dev/null +++ b/Lang/Zkl/Memory-allocation @@ -0,0 +1 @@ +../../Task/Memory-allocation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Menu b/Lang/Zkl/Menu new file mode 120000 index 0000000000..f83c9df596 --- /dev/null +++ b/Lang/Zkl/Menu @@ -0,0 +1 @@ +../../Task/Menu/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Metaprogramming b/Lang/Zkl/Metaprogramming new file mode 120000 index 0000000000..dc78c4d26d --- /dev/null +++ b/Lang/Zkl/Metaprogramming @@ -0,0 +1 @@ +../../Task/Metaprogramming/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Metered-concurrency b/Lang/Zkl/Metered-concurrency new file mode 120000 index 0000000000..b73a3b3f11 --- /dev/null +++ b/Lang/Zkl/Metered-concurrency @@ -0,0 +1 @@ +../../Task/Metered-concurrency/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Middle-three-digits b/Lang/Zkl/Middle-three-digits new file mode 120000 index 0000000000..75153b9bea --- /dev/null +++ b/Lang/Zkl/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Modular-exponentiation b/Lang/Zkl/Modular-exponentiation new file mode 120000 index 0000000000..f08464f500 --- /dev/null +++ b/Lang/Zkl/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Modular-inverse b/Lang/Zkl/Modular-inverse new file mode 120000 index 0000000000..1c7fc94451 --- /dev/null +++ b/Lang/Zkl/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Monte-Carlo-methods b/Lang/Zkl/Monte-Carlo-methods new file mode 120000 index 0000000000..677d0e9ef6 --- /dev/null +++ b/Lang/Zkl/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Monty-Hall-problem b/Lang/Zkl/Monty-Hall-problem new file mode 120000 index 0000000000..1bf912d2ef --- /dev/null +++ b/Lang/Zkl/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Move-to-front-algorithm b/Lang/Zkl/Move-to-front-algorithm new file mode 120000 index 0000000000..931d3fbac2 --- /dev/null +++ b/Lang/Zkl/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Multifactorial b/Lang/Zkl/Multifactorial new file mode 120000 index 0000000000..8d8ef2b1b8 --- /dev/null +++ b/Lang/Zkl/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Multiple-distinct-objects b/Lang/Zkl/Multiple-distinct-objects new file mode 120000 index 0000000000..4e119c3a8f --- /dev/null +++ b/Lang/Zkl/Multiple-distinct-objects @@ -0,0 +1 @@ +../../Task/Multiple-distinct-objects/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Multiple-regression b/Lang/Zkl/Multiple-regression new file mode 120000 index 0000000000..710df0964b --- /dev/null +++ b/Lang/Zkl/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Multiplication-tables b/Lang/Zkl/Multiplication-tables new file mode 120000 index 0000000000..1cdc00d58f --- /dev/null +++ b/Lang/Zkl/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Multiplicative-order b/Lang/Zkl/Multiplicative-order new file mode 120000 index 0000000000..d46c2f136e --- /dev/null +++ b/Lang/Zkl/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Multisplit b/Lang/Zkl/Multisplit new file mode 120000 index 0000000000..27621d85b6 --- /dev/null +++ b/Lang/Zkl/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Munching-squares b/Lang/Zkl/Munching-squares new file mode 120000 index 0000000000..39ac4ffc16 --- /dev/null +++ b/Lang/Zkl/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Mutual-recursion b/Lang/Zkl/Mutual-recursion new file mode 120000 index 0000000000..4309f27e14 --- /dev/null +++ b/Lang/Zkl/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Zkl \ No newline at end of file diff --git a/Lang/Zkl/N-queens-problem b/Lang/Zkl/N-queens-problem new file mode 120000 index 0000000000..6228495f1c --- /dev/null +++ b/Lang/Zkl/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Narcissist b/Lang/Zkl/Narcissist new file mode 120000 index 0000000000..ebf9a7052e --- /dev/null +++ b/Lang/Zkl/Narcissist @@ -0,0 +1 @@ +../../Task/Narcissist/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Narcissistic-decimal-number b/Lang/Zkl/Narcissistic-decimal-number new file mode 120000 index 0000000000..64dbf22de2 --- /dev/null +++ b/Lang/Zkl/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Natural-sorting b/Lang/Zkl/Natural-sorting new file mode 120000 index 0000000000..a73886ecbe --- /dev/null +++ b/Lang/Zkl/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Non-continuous-subsequences b/Lang/Zkl/Non-continuous-subsequences new file mode 120000 index 0000000000..f08958e889 --- /dev/null +++ b/Lang/Zkl/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Non-decimal-radices-Convert b/Lang/Zkl/Non-decimal-radices-Convert new file mode 120000 index 0000000000..a216252a2f --- /dev/null +++ b/Lang/Zkl/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Non-decimal-radices-Input b/Lang/Zkl/Non-decimal-radices-Input new file mode 120000 index 0000000000..65a531106b --- /dev/null +++ b/Lang/Zkl/Non-decimal-radices-Input @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Input/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Non-decimal-radices-Output b/Lang/Zkl/Non-decimal-radices-Output new file mode 120000 index 0000000000..a7089215ff --- /dev/null +++ b/Lang/Zkl/Non-decimal-radices-Output @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Output/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Nth b/Lang/Zkl/Nth new file mode 120000 index 0000000000..9be54ff8ea --- /dev/null +++ b/Lang/Zkl/Nth @@ -0,0 +1 @@ +../../Task/Nth/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Nth-root b/Lang/Zkl/Nth-root new file mode 120000 index 0000000000..b8e1719e06 --- /dev/null +++ b/Lang/Zkl/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Null-object b/Lang/Zkl/Null-object new file mode 120000 index 0000000000..afbe1dfc29 --- /dev/null +++ b/Lang/Zkl/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Number-names b/Lang/Zkl/Number-names new file mode 120000 index 0000000000..e58afea125 --- /dev/null +++ b/Lang/Zkl/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Number-reversal-game b/Lang/Zkl/Number-reversal-game new file mode 120000 index 0000000000..14093aa911 --- /dev/null +++ b/Lang/Zkl/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Numerical-integration b/Lang/Zkl/Numerical-integration new file mode 120000 index 0000000000..68998dcdb7 --- /dev/null +++ b/Lang/Zkl/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/Zkl/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..ee482b6f3b --- /dev/null +++ b/Lang/Zkl/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Object-serialization b/Lang/Zkl/Object-serialization new file mode 120000 index 0000000000..fa448fddf0 --- /dev/null +++ b/Lang/Zkl/Object-serialization @@ -0,0 +1 @@ +../../Task/Object-serialization/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Odd-word-problem b/Lang/Zkl/Odd-word-problem new file mode 120000 index 0000000000..d46e8a3b1b --- /dev/null +++ b/Lang/Zkl/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Old-lady-swallowed-a-fly b/Lang/Zkl/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..1cff1c25de --- /dev/null +++ b/Lang/Zkl/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Zkl \ No newline at end of file diff --git a/Lang/Zkl/One-dimensional-cellular-automata b/Lang/Zkl/One-dimensional-cellular-automata new file mode 120000 index 0000000000..533cab4632 --- /dev/null +++ b/Lang/Zkl/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Zkl \ No newline at end of file diff --git a/Lang/Zkl/One-of-n-lines-in-a-file b/Lang/Zkl/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..b4b62f7c96 --- /dev/null +++ b/Lang/Zkl/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Optional-parameters b/Lang/Zkl/Optional-parameters new file mode 120000 index 0000000000..ba9b41c219 --- /dev/null +++ b/Lang/Zkl/Optional-parameters @@ -0,0 +1 @@ +../../Task/Optional-parameters/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Order-disjoint-list-items b/Lang/Zkl/Order-disjoint-list-items new file mode 120000 index 0000000000..908bf372ee --- /dev/null +++ b/Lang/Zkl/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Order-two-numerical-lists b/Lang/Zkl/Order-two-numerical-lists new file mode 120000 index 0000000000..e431348536 --- /dev/null +++ b/Lang/Zkl/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Ordered-Partitions b/Lang/Zkl/Ordered-Partitions new file mode 120000 index 0000000000..a67ffb5698 --- /dev/null +++ b/Lang/Zkl/Ordered-Partitions @@ -0,0 +1 @@ +../../Task/Ordered-Partitions/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Ordered-words b/Lang/Zkl/Ordered-words new file mode 120000 index 0000000000..1b62184eba --- /dev/null +++ b/Lang/Zkl/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Palindrome-detection b/Lang/Zkl/Palindrome-detection new file mode 120000 index 0000000000..31cf7137d5 --- /dev/null +++ b/Lang/Zkl/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Pangram-checker b/Lang/Zkl/Pangram-checker new file mode 120000 index 0000000000..1bc8b0e3a2 --- /dev/null +++ b/Lang/Zkl/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Paraffins b/Lang/Zkl/Paraffins new file mode 120000 index 0000000000..22b710b3e8 --- /dev/null +++ b/Lang/Zkl/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Parallel-calculations b/Lang/Zkl/Parallel-calculations new file mode 120000 index 0000000000..d0c6f69f85 --- /dev/null +++ b/Lang/Zkl/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Parsing-RPN-calculator-algorithm b/Lang/Zkl/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..7c2e9e5b17 --- /dev/null +++ b/Lang/Zkl/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Parsing-RPN-to-infix-conversion b/Lang/Zkl/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..dd1a4ebf47 --- /dev/null +++ b/Lang/Zkl/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Parsing-Shunting-yard-algorithm b/Lang/Zkl/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..82f51872d8 --- /dev/null +++ b/Lang/Zkl/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Partial-function-application b/Lang/Zkl/Partial-function-application new file mode 120000 index 0000000000..cf28323208 --- /dev/null +++ b/Lang/Zkl/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Pascals-triangle b/Lang/Zkl/Pascals-triangle new file mode 120000 index 0000000000..ecb624ba8e --- /dev/null +++ b/Lang/Zkl/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Pascals-triangle-Puzzle b/Lang/Zkl/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..29ee5fa299 --- /dev/null +++ b/Lang/Zkl/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Penneys-game b/Lang/Zkl/Penneys-game new file mode 120000 index 0000000000..6e13d224be --- /dev/null +++ b/Lang/Zkl/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Percentage-difference-between-images b/Lang/Zkl/Percentage-difference-between-images new file mode 120000 index 0000000000..04a4cdb046 --- /dev/null +++ b/Lang/Zkl/Percentage-difference-between-images @@ -0,0 +1 @@ +../../Task/Percentage-difference-between-images/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Percolation-Bond-percolation b/Lang/Zkl/Percolation-Bond-percolation new file mode 120000 index 0000000000..c3f841a171 --- /dev/null +++ b/Lang/Zkl/Percolation-Bond-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Bond-percolation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Percolation-Mean-cluster-density b/Lang/Zkl/Percolation-Mean-cluster-density new file mode 120000 index 0000000000..a8842bbeb5 --- /dev/null +++ b/Lang/Zkl/Percolation-Mean-cluster-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-cluster-density/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Percolation-Mean-run-density b/Lang/Zkl/Percolation-Mean-run-density new file mode 120000 index 0000000000..98a1347694 --- /dev/null +++ b/Lang/Zkl/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Percolation-Site-percolation b/Lang/Zkl/Percolation-Site-percolation new file mode 120000 index 0000000000..d08fbde208 --- /dev/null +++ b/Lang/Zkl/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Perfect-numbers b/Lang/Zkl/Perfect-numbers new file mode 120000 index 0000000000..a862e734b9 --- /dev/null +++ b/Lang/Zkl/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Permutation-test b/Lang/Zkl/Permutation-test new file mode 120000 index 0000000000..f43e645408 --- /dev/null +++ b/Lang/Zkl/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Permutations b/Lang/Zkl/Permutations new file mode 120000 index 0000000000..d52449fecb --- /dev/null +++ b/Lang/Zkl/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Permutations-Derangements b/Lang/Zkl/Permutations-Derangements new file mode 120000 index 0000000000..167f4b3234 --- /dev/null +++ b/Lang/Zkl/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Permutations-Rank-of-a-permutation b/Lang/Zkl/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..f8c44fcca1 --- /dev/null +++ b/Lang/Zkl/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Permutations-by-swapping b/Lang/Zkl/Permutations-by-swapping new file mode 120000 index 0000000000..969746ec1c --- /dev/null +++ b/Lang/Zkl/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Pernicious-numbers b/Lang/Zkl/Pernicious-numbers new file mode 120000 index 0000000000..55096684e3 --- /dev/null +++ b/Lang/Zkl/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Phrase-reversals b/Lang/Zkl/Phrase-reversals new file mode 120000 index 0000000000..345ae0c720 --- /dev/null +++ b/Lang/Zkl/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Pi b/Lang/Zkl/Pi new file mode 120000 index 0000000000..6d4eb270fa --- /dev/null +++ b/Lang/Zkl/Pi @@ -0,0 +1 @@ +../../Task/Pi/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Pick-random-element b/Lang/Zkl/Pick-random-element new file mode 120000 index 0000000000..86eb1f38ec --- /dev/null +++ b/Lang/Zkl/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Pig-the-dice-game b/Lang/Zkl/Pig-the-dice-game new file mode 120000 index 0000000000..96c3a6ee1e --- /dev/null +++ b/Lang/Zkl/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Playing-cards b/Lang/Zkl/Playing-cards new file mode 120000 index 0000000000..0a6b313154 --- /dev/null +++ b/Lang/Zkl/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Plot-coordinate-pairs b/Lang/Zkl/Plot-coordinate-pairs new file mode 120000 index 0000000000..87a3fc3564 --- /dev/null +++ b/Lang/Zkl/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Pointers-and-references b/Lang/Zkl/Pointers-and-references new file mode 120000 index 0000000000..9aa19cbdae --- /dev/null +++ b/Lang/Zkl/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Polymorphism b/Lang/Zkl/Polymorphism new file mode 120000 index 0000000000..65f3ff11f0 --- /dev/null +++ b/Lang/Zkl/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Polynomial-long-division b/Lang/Zkl/Polynomial-long-division new file mode 120000 index 0000000000..6033ce7984 --- /dev/null +++ b/Lang/Zkl/Polynomial-long-division @@ -0,0 +1 @@ +../../Task/Polynomial-long-division/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Polynomial-regression b/Lang/Zkl/Polynomial-regression new file mode 120000 index 0000000000..e538550b6b --- /dev/null +++ b/Lang/Zkl/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Power-set b/Lang/Zkl/Power-set new file mode 120000 index 0000000000..4bea9ffa2c --- /dev/null +++ b/Lang/Zkl/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Price-fraction b/Lang/Zkl/Price-fraction new file mode 120000 index 0000000000..c5017257a4 --- /dev/null +++ b/Lang/Zkl/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Primality-by-trial-division b/Lang/Zkl/Primality-by-trial-division new file mode 120000 index 0000000000..f18e2c9269 --- /dev/null +++ b/Lang/Zkl/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Prime-decomposition b/Lang/Zkl/Prime-decomposition new file mode 120000 index 0000000000..202fc7f0d8 --- /dev/null +++ b/Lang/Zkl/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Priority-queue b/Lang/Zkl/Priority-queue new file mode 120000 index 0000000000..49a519405d --- /dev/null +++ b/Lang/Zkl/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Probabilistic-choice b/Lang/Zkl/Probabilistic-choice new file mode 120000 index 0000000000..35229db076 --- /dev/null +++ b/Lang/Zkl/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Problem-of-Apollonius b/Lang/Zkl/Problem-of-Apollonius new file mode 120000 index 0000000000..2befbe30f5 --- /dev/null +++ b/Lang/Zkl/Problem-of-Apollonius @@ -0,0 +1 @@ +../../Task/Problem-of-Apollonius/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Program-name b/Lang/Zkl/Program-name new file mode 120000 index 0000000000..ea730c476c --- /dev/null +++ b/Lang/Zkl/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Program-termination b/Lang/Zkl/Program-termination new file mode 120000 index 0000000000..6a1e0f06bb --- /dev/null +++ b/Lang/Zkl/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Pythagorean-triples b/Lang/Zkl/Pythagorean-triples new file mode 120000 index 0000000000..c520cf6411 --- /dev/null +++ b/Lang/Zkl/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Zkl \ No newline at end of file diff --git a/Lang/Zkl/QR-decomposition b/Lang/Zkl/QR-decomposition new file mode 120000 index 0000000000..727240d268 --- /dev/null +++ b/Lang/Zkl/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Quaternion-type b/Lang/Zkl/Quaternion-type new file mode 120000 index 0000000000..d36f19dd00 --- /dev/null +++ b/Lang/Zkl/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Queue-Definition b/Lang/Zkl/Queue-Definition new file mode 120000 index 0000000000..c71a1499b3 --- /dev/null +++ b/Lang/Zkl/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Quickselect-algorithm b/Lang/Zkl/Quickselect-algorithm new file mode 120000 index 0000000000..6ab9d67674 --- /dev/null +++ b/Lang/Zkl/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Quine b/Lang/Zkl/Quine new file mode 120000 index 0000000000..402fb94097 --- /dev/null +++ b/Lang/Zkl/Quine @@ -0,0 +1 @@ +../../Task/Quine/Zkl \ No newline at end of file diff --git a/Lang/Zkl/RIPEMD-160 b/Lang/Zkl/RIPEMD-160 new file mode 120000 index 0000000000..07761db89f --- /dev/null +++ b/Lang/Zkl/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/Zkl \ No newline at end of file diff --git a/Lang/Zkl/RSA-code b/Lang/Zkl/RSA-code new file mode 120000 index 0000000000..1b0a95fd0a --- /dev/null +++ b/Lang/Zkl/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Random-number-generator--device- b/Lang/Zkl/Random-number-generator--device- new file mode 120000 index 0000000000..cbc2e0fde4 --- /dev/null +++ b/Lang/Zkl/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Random-numbers b/Lang/Zkl/Random-numbers new file mode 120000 index 0000000000..1a05658e22 --- /dev/null +++ b/Lang/Zkl/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Range-expansion b/Lang/Zkl/Range-expansion new file mode 120000 index 0000000000..a330e658f6 --- /dev/null +++ b/Lang/Zkl/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Range-extraction b/Lang/Zkl/Range-extraction new file mode 120000 index 0000000000..ae7f8e1dba --- /dev/null +++ b/Lang/Zkl/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Ranking-methods b/Lang/Zkl/Ranking-methods new file mode 120000 index 0000000000..342169871a --- /dev/null +++ b/Lang/Zkl/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Rate-counter b/Lang/Zkl/Rate-counter new file mode 120000 index 0000000000..2dc1026794 --- /dev/null +++ b/Lang/Zkl/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Ray-casting-algorithm b/Lang/Zkl/Ray-casting-algorithm new file mode 120000 index 0000000000..056e0038ad --- /dev/null +++ b/Lang/Zkl/Ray-casting-algorithm @@ -0,0 +1 @@ +../../Task/Ray-casting-algorithm/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Read-a-configuration-file b/Lang/Zkl/Read-a-configuration-file new file mode 120000 index 0000000000..5d5e3ed514 --- /dev/null +++ b/Lang/Zkl/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Read-a-file-line-by-line b/Lang/Zkl/Read-a-file-line-by-line new file mode 120000 index 0000000000..4a88311fec --- /dev/null +++ b/Lang/Zkl/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Read-a-specific-line-from-a-file b/Lang/Zkl/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..7138944f6f --- /dev/null +++ b/Lang/Zkl/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Read-entire-file b/Lang/Zkl/Read-entire-file new file mode 120000 index 0000000000..ac37a3dc7f --- /dev/null +++ b/Lang/Zkl/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Real-constants-and-functions b/Lang/Zkl/Real-constants-and-functions new file mode 120000 index 0000000000..b6dbaa08fb --- /dev/null +++ b/Lang/Zkl/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Reduced-row-echelon-form b/Lang/Zkl/Reduced-row-echelon-form new file mode 120000 index 0000000000..23f2f14952 --- /dev/null +++ b/Lang/Zkl/Reduced-row-echelon-form @@ -0,0 +1 @@ +../../Task/Reduced-row-echelon-form/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Regular-expressions b/Lang/Zkl/Regular-expressions new file mode 120000 index 0000000000..9f3c042122 --- /dev/null +++ b/Lang/Zkl/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Remove-duplicate-elements b/Lang/Zkl/Remove-duplicate-elements new file mode 120000 index 0000000000..50ccf0918d --- /dev/null +++ b/Lang/Zkl/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Remove-lines-from-a-file b/Lang/Zkl/Remove-lines-from-a-file new file mode 120000 index 0000000000..bddd91a6d7 --- /dev/null +++ b/Lang/Zkl/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Rendezvous b/Lang/Zkl/Rendezvous new file mode 120000 index 0000000000..05abb24c49 --- /dev/null +++ b/Lang/Zkl/Rendezvous @@ -0,0 +1 @@ +../../Task/Rendezvous/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Rep-string b/Lang/Zkl/Rep-string new file mode 120000 index 0000000000..a2b1a1a5fa --- /dev/null +++ b/Lang/Zkl/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Repeat-a-string b/Lang/Zkl/Repeat-a-string new file mode 120000 index 0000000000..c32c8ca4f9 --- /dev/null +++ b/Lang/Zkl/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Resistor-mesh b/Lang/Zkl/Resistor-mesh new file mode 120000 index 0000000000..73473fbbc1 --- /dev/null +++ b/Lang/Zkl/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Respond-to-an-unknown-method-call b/Lang/Zkl/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..9831446802 --- /dev/null +++ b/Lang/Zkl/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Return-multiple-values b/Lang/Zkl/Return-multiple-values new file mode 120000 index 0000000000..3b43cd5630 --- /dev/null +++ b/Lang/Zkl/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Reverse-words-in-a-string b/Lang/Zkl/Reverse-words-in-a-string new file mode 120000 index 0000000000..597e2dca48 --- /dev/null +++ b/Lang/Zkl/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Roman-numerals-Decode b/Lang/Zkl/Roman-numerals-Decode new file mode 120000 index 0000000000..0158b5f51f --- /dev/null +++ b/Lang/Zkl/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Roman-numerals-Encode b/Lang/Zkl/Roman-numerals-Encode new file mode 120000 index 0000000000..e72721d80c --- /dev/null +++ b/Lang/Zkl/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Roots-of-a-function b/Lang/Zkl/Roots-of-a-function new file mode 120000 index 0000000000..06b49d8f2f --- /dev/null +++ b/Lang/Zkl/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Roots-of-a-quadratic-function b/Lang/Zkl/Roots-of-a-quadratic-function new file mode 120000 index 0000000000..14ed9f7db0 --- /dev/null +++ b/Lang/Zkl/Roots-of-a-quadratic-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-quadratic-function/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Roots-of-unity b/Lang/Zkl/Roots-of-unity new file mode 120000 index 0000000000..7d73386442 --- /dev/null +++ b/Lang/Zkl/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Rot-13 b/Lang/Zkl/Rot-13 new file mode 120000 index 0000000000..9b3d3998a6 --- /dev/null +++ b/Lang/Zkl/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Run-length-encoding b/Lang/Zkl/Run-length-encoding new file mode 120000 index 0000000000..82d6488da4 --- /dev/null +++ b/Lang/Zkl/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Runge-Kutta-method b/Lang/Zkl/Runge-Kutta-method new file mode 120000 index 0000000000..7336f4a0d8 --- /dev/null +++ b/Lang/Zkl/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Runtime-evaluation b/Lang/Zkl/Runtime-evaluation new file mode 120000 index 0000000000..7329636ba6 --- /dev/null +++ b/Lang/Zkl/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Runtime-evaluation-In-an-environment b/Lang/Zkl/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..a77c9b3fe2 --- /dev/null +++ b/Lang/Zkl/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/Zkl \ No newline at end of file diff --git a/Lang/Zkl/SEDOLs b/Lang/Zkl/SEDOLs new file mode 120000 index 0000000000..9f0872ecc6 --- /dev/null +++ b/Lang/Zkl/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/Zkl \ No newline at end of file diff --git a/Lang/Zkl/SHA-1 b/Lang/Zkl/SHA-1 new file mode 120000 index 0000000000..f70f7cf9b1 --- /dev/null +++ b/Lang/Zkl/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Zkl \ No newline at end of file diff --git a/Lang/Zkl/SHA-256 b/Lang/Zkl/SHA-256 new file mode 120000 index 0000000000..558befe6cc --- /dev/null +++ b/Lang/Zkl/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Same-Fringe b/Lang/Zkl/Same-Fringe new file mode 120000 index 0000000000..113f2c8d96 --- /dev/null +++ b/Lang/Zkl/Same-Fringe @@ -0,0 +1 @@ +../../Task/Same-Fringe/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Scope-Function-names-and-labels b/Lang/Zkl/Scope-Function-names-and-labels new file mode 120000 index 0000000000..077783d11b --- /dev/null +++ b/Lang/Zkl/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Search-a-list b/Lang/Zkl/Search-a-list new file mode 120000 index 0000000000..1416ace429 --- /dev/null +++ b/Lang/Zkl/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Self-describing-numbers b/Lang/Zkl/Self-describing-numbers new file mode 120000 index 0000000000..d61818a3db --- /dev/null +++ b/Lang/Zkl/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Self-referential-sequence b/Lang/Zkl/Self-referential-sequence new file mode 120000 index 0000000000..6bcab2ffff --- /dev/null +++ b/Lang/Zkl/Self-referential-sequence @@ -0,0 +1 @@ +../../Task/Self-referential-sequence/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Semiprime b/Lang/Zkl/Semiprime new file mode 120000 index 0000000000..9c54628b9b --- /dev/null +++ b/Lang/Zkl/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Semordnilap b/Lang/Zkl/Semordnilap new file mode 120000 index 0000000000..6c115734c7 --- /dev/null +++ b/Lang/Zkl/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Send-an-unknown-method-call b/Lang/Zkl/Send-an-unknown-method-call new file mode 120000 index 0000000000..b58fa6f906 --- /dev/null +++ b/Lang/Zkl/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sequence-of-non-squares b/Lang/Zkl/Sequence-of-non-squares new file mode 120000 index 0000000000..47c3a5b36f --- /dev/null +++ b/Lang/Zkl/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sequence-of-primes-by-Trial-Division b/Lang/Zkl/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..5661c2de08 --- /dev/null +++ b/Lang/Zkl/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Set b/Lang/Zkl/Set new file mode 120000 index 0000000000..ef3c7d51dd --- /dev/null +++ b/Lang/Zkl/Set @@ -0,0 +1 @@ +../../Task/Set/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Set-consolidation b/Lang/Zkl/Set-consolidation new file mode 120000 index 0000000000..cfef1f1809 --- /dev/null +++ b/Lang/Zkl/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Set-of-real-numbers b/Lang/Zkl/Set-of-real-numbers new file mode 120000 index 0000000000..f524cef1ce --- /dev/null +++ b/Lang/Zkl/Set-of-real-numbers @@ -0,0 +1 @@ +../../Task/Set-of-real-numbers/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Set-puzzle b/Lang/Zkl/Set-puzzle new file mode 120000 index 0000000000..c3444a093e --- /dev/null +++ b/Lang/Zkl/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Seven-sided-dice-from-five-sided-dice b/Lang/Zkl/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..8ba34212d1 --- /dev/null +++ b/Lang/Zkl/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Shell-one-liner b/Lang/Zkl/Shell-one-liner new file mode 120000 index 0000000000..2843a9d560 --- /dev/null +++ b/Lang/Zkl/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Short-circuit-evaluation b/Lang/Zkl/Short-circuit-evaluation new file mode 120000 index 0000000000..b47726e8db --- /dev/null +++ b/Lang/Zkl/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Show-the-epoch b/Lang/Zkl/Show-the-epoch new file mode 120000 index 0000000000..6cee87650c --- /dev/null +++ b/Lang/Zkl/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sierpinski-carpet b/Lang/Zkl/Sierpinski-carpet new file mode 120000 index 0000000000..f5821abcac --- /dev/null +++ b/Lang/Zkl/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sierpinski-triangle b/Lang/Zkl/Sierpinski-triangle new file mode 120000 index 0000000000..109d3c99bb --- /dev/null +++ b/Lang/Zkl/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sierpinski-triangle-Graphical b/Lang/Zkl/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..1d39d9a13a --- /dev/null +++ b/Lang/Zkl/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sieve-of-Eratosthenes b/Lang/Zkl/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..fcfab34d35 --- /dev/null +++ b/Lang/Zkl/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Singleton b/Lang/Zkl/Singleton new file mode 120000 index 0000000000..fc02e24c78 --- /dev/null +++ b/Lang/Zkl/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Singly-linked-list-Element-definition b/Lang/Zkl/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..13573d430e --- /dev/null +++ b/Lang/Zkl/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Singly-linked-list-Element-insertion b/Lang/Zkl/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..163c09515d --- /dev/null +++ b/Lang/Zkl/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Singly-linked-list-Traversal b/Lang/Zkl/Singly-linked-list-Traversal new file mode 120000 index 0000000000..860c8ba85b --- /dev/null +++ b/Lang/Zkl/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sleep b/Lang/Zkl/Sleep new file mode 120000 index 0000000000..94aa210faa --- /dev/null +++ b/Lang/Zkl/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sockets b/Lang/Zkl/Sockets new file mode 120000 index 0000000000..d5bc90b2a1 --- /dev/null +++ b/Lang/Zkl/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Solve-a-Hidato-puzzle b/Lang/Zkl/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..de7ff1f065 --- /dev/null +++ b/Lang/Zkl/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Solve-a-Hopido-puzzle b/Lang/Zkl/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..614b539543 --- /dev/null +++ b/Lang/Zkl/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Solve-a-Numbrix-puzzle b/Lang/Zkl/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..3b07d6cfd2 --- /dev/null +++ b/Lang/Zkl/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Solve-the-no-connection-puzzle b/Lang/Zkl/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..3170687d08 --- /dev/null +++ b/Lang/Zkl/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sort-an-array-of-composite-structures b/Lang/Zkl/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..c06c944a4c --- /dev/null +++ b/Lang/Zkl/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sort-an-integer-array b/Lang/Zkl/Sort-an-integer-array new file mode 120000 index 0000000000..ce2755c8a3 --- /dev/null +++ b/Lang/Zkl/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sort-disjoint-sublist b/Lang/Zkl/Sort-disjoint-sublist new file mode 120000 index 0000000000..72ff3eaebe --- /dev/null +++ b/Lang/Zkl/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sort-stability b/Lang/Zkl/Sort-stability new file mode 120000 index 0000000000..d018e581b7 --- /dev/null +++ b/Lang/Zkl/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sort-using-a-custom-comparator b/Lang/Zkl/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..45f7c0faa4 --- /dev/null +++ b/Lang/Zkl/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Bead-sort b/Lang/Zkl/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..1776609b79 --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Bogosort b/Lang/Zkl/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..0f3eb9f311 --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Bubble-sort b/Lang/Zkl/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..6cc0332fdc --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Cocktail-sort b/Lang/Zkl/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..fb7c2ec4d4 --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Comb-sort b/Lang/Zkl/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..d5471d6b8d --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Counting-sort b/Lang/Zkl/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..421815c46d --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Gnome-sort b/Lang/Zkl/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..0bb0f6bc39 --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Heapsort b/Lang/Zkl/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..e7e1cb2bbd --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Insertion-sort b/Lang/Zkl/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..6de395359e --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Merge-sort b/Lang/Zkl/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..ab55f030ce --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Pancake-sort b/Lang/Zkl/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..4d8c7c629b --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Permutation-sort b/Lang/Zkl/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..fadb75867a --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Quicksort b/Lang/Zkl/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..cdca163f66 --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Radix-sort b/Lang/Zkl/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..1433e958bc --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Selection-sort b/Lang/Zkl/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..ade3f334ff --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Shell-sort b/Lang/Zkl/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..9a80fafe78 --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Sleep-sort b/Lang/Zkl/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..ff7b73066a --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Stooge-sort b/Lang/Zkl/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..ed0c9823b2 --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-algorithms-Strand-sort b/Lang/Zkl/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..269e493c2c --- /dev/null +++ b/Lang/Zkl/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sparkline-in-unicode b/Lang/Zkl/Sparkline-in-unicode new file mode 120000 index 0000000000..9c44d3df90 --- /dev/null +++ b/Lang/Zkl/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Spiral-matrix b/Lang/Zkl/Spiral-matrix new file mode 120000 index 0000000000..1fa83a5499 --- /dev/null +++ b/Lang/Zkl/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Stable-marriage-problem b/Lang/Zkl/Stable-marriage-problem new file mode 120000 index 0000000000..71ffd8d5d0 --- /dev/null +++ b/Lang/Zkl/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Stack b/Lang/Zkl/Stack new file mode 120000 index 0000000000..2b3a41ab41 --- /dev/null +++ b/Lang/Zkl/Stack @@ -0,0 +1 @@ +../../Task/Stack/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Stack-traces b/Lang/Zkl/Stack-traces new file mode 120000 index 0000000000..8fefaac55d --- /dev/null +++ b/Lang/Zkl/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Stair-climbing-puzzle b/Lang/Zkl/Stair-climbing-puzzle new file mode 120000 index 0000000000..a8058b1c59 --- /dev/null +++ b/Lang/Zkl/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Start-from-a-main-routine b/Lang/Zkl/Start-from-a-main-routine new file mode 120000 index 0000000000..6977fe5261 --- /dev/null +++ b/Lang/Zkl/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Zkl \ No newline at end of file diff --git a/Lang/Zkl/State-name-puzzle b/Lang/Zkl/State-name-puzzle new file mode 120000 index 0000000000..406524388c --- /dev/null +++ b/Lang/Zkl/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Statistics-Basic b/Lang/Zkl/Statistics-Basic new file mode 120000 index 0000000000..74b494aecc --- /dev/null +++ b/Lang/Zkl/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Stem-and-leaf-plot b/Lang/Zkl/Stem-and-leaf-plot new file mode 120000 index 0000000000..255b48105f --- /dev/null +++ b/Lang/Zkl/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Stern-Brocot-sequence b/Lang/Zkl/Stern-Brocot-sequence new file mode 120000 index 0000000000..091706fd03 --- /dev/null +++ b/Lang/Zkl/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Zkl \ No newline at end of file diff --git a/Lang/Zkl/String-append b/Lang/Zkl/String-append new file mode 120000 index 0000000000..372933ba29 --- /dev/null +++ b/Lang/Zkl/String-append @@ -0,0 +1 @@ +../../Task/String-append/Zkl \ No newline at end of file diff --git a/Lang/Zkl/String-case b/Lang/Zkl/String-case new file mode 120000 index 0000000000..39f1ce994c --- /dev/null +++ b/Lang/Zkl/String-case @@ -0,0 +1 @@ +../../Task/String-case/Zkl \ No newline at end of file diff --git a/Lang/Zkl/String-comparison b/Lang/Zkl/String-comparison new file mode 120000 index 0000000000..9e1e7dd4b5 --- /dev/null +++ b/Lang/Zkl/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Zkl \ No newline at end of file diff --git a/Lang/Zkl/String-concatenation b/Lang/Zkl/String-concatenation new file mode 120000 index 0000000000..52c352ce29 --- /dev/null +++ b/Lang/Zkl/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/String-interpolation--included- b/Lang/Zkl/String-interpolation--included- new file mode 120000 index 0000000000..c1b836bc29 --- /dev/null +++ b/Lang/Zkl/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Zkl \ No newline at end of file diff --git a/Lang/Zkl/String-length b/Lang/Zkl/String-length new file mode 120000 index 0000000000..fe6b26c384 --- /dev/null +++ b/Lang/Zkl/String-length @@ -0,0 +1 @@ +../../Task/String-length/Zkl \ No newline at end of file diff --git a/Lang/Zkl/String-matching b/Lang/Zkl/String-matching new file mode 120000 index 0000000000..da53b00937 --- /dev/null +++ b/Lang/Zkl/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Zkl \ No newline at end of file diff --git a/Lang/Zkl/String-prepend b/Lang/Zkl/String-prepend new file mode 120000 index 0000000000..f1ef3b720c --- /dev/null +++ b/Lang/Zkl/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Strip-a-set-of-characters-from-a-string b/Lang/Zkl/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..3794b70e30 --- /dev/null +++ b/Lang/Zkl/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Strip-block-comments b/Lang/Zkl/Strip-block-comments new file mode 120000 index 0000000000..23189957de --- /dev/null +++ b/Lang/Zkl/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Strip-comments-from-a-string b/Lang/Zkl/Strip-comments-from-a-string new file mode 120000 index 0000000000..09a48cc888 --- /dev/null +++ b/Lang/Zkl/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Zkl/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..c164d7fb47 --- /dev/null +++ b/Lang/Zkl/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Zkl/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..461ac043b6 --- /dev/null +++ b/Lang/Zkl/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Substring b/Lang/Zkl/Substring new file mode 120000 index 0000000000..ae01e48be6 --- /dev/null +++ b/Lang/Zkl/Substring @@ -0,0 +1 @@ +../../Task/Substring/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Substring-Top-and-tail b/Lang/Zkl/Substring-Top-and-tail new file mode 120000 index 0000000000..b87614921b --- /dev/null +++ b/Lang/Zkl/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Subtractive-generator b/Lang/Zkl/Subtractive-generator new file mode 120000 index 0000000000..1ed4af66cc --- /dev/null +++ b/Lang/Zkl/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sudoku b/Lang/Zkl/Sudoku new file mode 120000 index 0000000000..d7767f407a --- /dev/null +++ b/Lang/Zkl/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sum-and-product-of-an-array b/Lang/Zkl/Sum-and-product-of-an-array new file mode 120000 index 0000000000..2c8d91cda3 --- /dev/null +++ b/Lang/Zkl/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sum-digits-of-an-integer b/Lang/Zkl/Sum-digits-of-an-integer new file mode 120000 index 0000000000..4e1f1b23a0 --- /dev/null +++ b/Lang/Zkl/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sum-multiples-of-3-and-5 b/Lang/Zkl/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..fb7c228497 --- /dev/null +++ b/Lang/Zkl/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sum-of-a-series b/Lang/Zkl/Sum-of-a-series new file mode 120000 index 0000000000..bbae23506f --- /dev/null +++ b/Lang/Zkl/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sum-of-squares b/Lang/Zkl/Sum-of-squares new file mode 120000 index 0000000000..a460cc23c8 --- /dev/null +++ b/Lang/Zkl/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sutherland-Hodgman-polygon-clipping b/Lang/Zkl/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..73c90b429d --- /dev/null +++ b/Lang/Zkl/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Symmetric-difference b/Lang/Zkl/Symmetric-difference new file mode 120000 index 0000000000..fa58401f23 --- /dev/null +++ b/Lang/Zkl/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Synchronous-concurrency b/Lang/Zkl/Synchronous-concurrency new file mode 120000 index 0000000000..d1e5001bc8 --- /dev/null +++ b/Lang/Zkl/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Zkl \ No newline at end of file diff --git a/Lang/Zkl/System-time b/Lang/Zkl/System-time new file mode 120000 index 0000000000..1f83d7827c --- /dev/null +++ b/Lang/Zkl/System-time @@ -0,0 +1 @@ +../../Task/System-time/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Table-creation-Postal-addresses b/Lang/Zkl/Table-creation-Postal-addresses new file mode 120000 index 0000000000..c8698a1abc --- /dev/null +++ b/Lang/Zkl/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Take-notes-on-the-command-line b/Lang/Zkl/Take-notes-on-the-command-line new file mode 120000 index 0000000000..fd7dcfe4fd --- /dev/null +++ b/Lang/Zkl/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Temperature-conversion b/Lang/Zkl/Temperature-conversion new file mode 120000 index 0000000000..526dea364d --- /dev/null +++ b/Lang/Zkl/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Terminal-control-Clear-the-screen b/Lang/Zkl/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..fcb60b0fca --- /dev/null +++ b/Lang/Zkl/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Terminal-control-Coloured-text b/Lang/Zkl/Terminal-control-Coloured-text new file mode 120000 index 0000000000..6866879ab9 --- /dev/null +++ b/Lang/Zkl/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Terminal-control-Cursor-movement b/Lang/Zkl/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..684c1a2c9f --- /dev/null +++ b/Lang/Zkl/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Terminal-control-Cursor-positioning b/Lang/Zkl/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..52348f377a --- /dev/null +++ b/Lang/Zkl/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Terminal-control-Dimensions b/Lang/Zkl/Terminal-control-Dimensions new file mode 120000 index 0000000000..1e59a38c17 --- /dev/null +++ b/Lang/Zkl/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Terminal-control-Display-an-extended-character b/Lang/Zkl/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..d8dd9134be --- /dev/null +++ b/Lang/Zkl/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Terminal-control-Hiding-the-cursor b/Lang/Zkl/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..c598d2dc1b --- /dev/null +++ b/Lang/Zkl/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Terminal-control-Inverse-video b/Lang/Zkl/Terminal-control-Inverse-video new file mode 120000 index 0000000000..ab3bc42830 --- /dev/null +++ b/Lang/Zkl/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Terminal-control-Preserve-screen b/Lang/Zkl/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..994ca2d6b2 --- /dev/null +++ b/Lang/Zkl/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Terminal-control-Ringing-the-terminal-bell b/Lang/Zkl/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..2a8b5f3529 --- /dev/null +++ b/Lang/Zkl/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Terminal-control-Unicode-output b/Lang/Zkl/Terminal-control-Unicode-output new file mode 120000 index 0000000000..10ae44fc87 --- /dev/null +++ b/Lang/Zkl/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Test-a-function b/Lang/Zkl/Test-a-function new file mode 120000 index 0000000000..b65fae10cd --- /dev/null +++ b/Lang/Zkl/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Text-processing-2 b/Lang/Zkl/Text-processing-2 new file mode 120000 index 0000000000..fc92d0b86e --- /dev/null +++ b/Lang/Zkl/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Text-processing-Max-licenses-in-use b/Lang/Zkl/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..f13e79b48b --- /dev/null +++ b/Lang/Zkl/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Textonyms b/Lang/Zkl/Textonyms new file mode 120000 index 0000000000..8387dd1c25 --- /dev/null +++ b/Lang/Zkl/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Zkl \ No newline at end of file diff --git a/Lang/Zkl/The-Twelve-Days-of-Christmas b/Lang/Zkl/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..f35cfc489a --- /dev/null +++ b/Lang/Zkl/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Thieles-interpolation-formula b/Lang/Zkl/Thieles-interpolation-formula new file mode 120000 index 0000000000..92c466d7c7 --- /dev/null +++ b/Lang/Zkl/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Time-a-function b/Lang/Zkl/Time-a-function new file mode 120000 index 0000000000..7fd0d63102 --- /dev/null +++ b/Lang/Zkl/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Tokenize-a-string b/Lang/Zkl/Tokenize-a-string new file mode 120000 index 0000000000..64d50904b9 --- /dev/null +++ b/Lang/Zkl/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Top-rank-per-group b/Lang/Zkl/Top-rank-per-group new file mode 120000 index 0000000000..1360237ae4 --- /dev/null +++ b/Lang/Zkl/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Topic-variable b/Lang/Zkl/Topic-variable new file mode 120000 index 0000000000..676f58f37d --- /dev/null +++ b/Lang/Zkl/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Topological-sort b/Lang/Zkl/Topological-sort new file mode 120000 index 0000000000..cc010de7a3 --- /dev/null +++ b/Lang/Zkl/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Topswops b/Lang/Zkl/Topswops new file mode 120000 index 0000000000..823ac4fe4b --- /dev/null +++ b/Lang/Zkl/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Total-circles-area b/Lang/Zkl/Total-circles-area new file mode 120000 index 0000000000..1cd9fdd7bb --- /dev/null +++ b/Lang/Zkl/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Towers-of-Hanoi b/Lang/Zkl/Towers-of-Hanoi new file mode 120000 index 0000000000..414ede41bf --- /dev/null +++ b/Lang/Zkl/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Trabb-Pardo-Knuth-algorithm b/Lang/Zkl/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..d8b3ddce3f --- /dev/null +++ b/Lang/Zkl/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Tree-traversal b/Lang/Zkl/Tree-traversal new file mode 120000 index 0000000000..f588eb4907 --- /dev/null +++ b/Lang/Zkl/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Trigonometric-functions b/Lang/Zkl/Trigonometric-functions new file mode 120000 index 0000000000..dab5597828 --- /dev/null +++ b/Lang/Zkl/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Truncatable-primes b/Lang/Zkl/Truncatable-primes new file mode 120000 index 0000000000..f033e16270 --- /dev/null +++ b/Lang/Zkl/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Twelve-statements b/Lang/Zkl/Twelve-statements new file mode 120000 index 0000000000..2129f956ef --- /dev/null +++ b/Lang/Zkl/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Zkl \ No newline at end of file diff --git a/Lang/Zkl/URL-decoding b/Lang/Zkl/URL-decoding new file mode 120000 index 0000000000..cd4a7904e8 --- /dev/null +++ b/Lang/Zkl/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Zkl \ No newline at end of file diff --git a/Lang/Zkl/URL-encoding b/Lang/Zkl/URL-encoding new file mode 120000 index 0000000000..f156244689 --- /dev/null +++ b/Lang/Zkl/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Ulam-spiral--for-primes- b/Lang/Zkl/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..26e9c0bd16 --- /dev/null +++ b/Lang/Zkl/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Unbias-a-random-generator b/Lang/Zkl/Unbias-a-random-generator new file mode 120000 index 0000000000..aece871654 --- /dev/null +++ b/Lang/Zkl/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Undefined-values b/Lang/Zkl/Undefined-values new file mode 120000 index 0000000000..70f315315a --- /dev/null +++ b/Lang/Zkl/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Unicode-variable-names b/Lang/Zkl/Unicode-variable-names new file mode 120000 index 0000000000..e40a3ebf72 --- /dev/null +++ b/Lang/Zkl/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Universal-Turing-machine b/Lang/Zkl/Universal-Turing-machine new file mode 120000 index 0000000000..819b0af3d3 --- /dev/null +++ b/Lang/Zkl/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Unix-ls b/Lang/Zkl/Unix-ls new file mode 120000 index 0000000000..ec9bda4d66 --- /dev/null +++ b/Lang/Zkl/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Use-another-language-to-call-a-function b/Lang/Zkl/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..d40981e737 --- /dev/null +++ b/Lang/Zkl/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Zkl \ No newline at end of file diff --git a/Lang/Zkl/User-input-Text b/Lang/Zkl/User-input-Text new file mode 120000 index 0000000000..aa243a289d --- /dev/null +++ b/Lang/Zkl/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Vampire-number b/Lang/Zkl/Vampire-number new file mode 120000 index 0000000000..d7e3dd0ea5 --- /dev/null +++ b/Lang/Zkl/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Van-der-Corput-sequence b/Lang/Zkl/Van-der-Corput-sequence new file mode 120000 index 0000000000..fae505c6de --- /dev/null +++ b/Lang/Zkl/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Variable-length-quantity b/Lang/Zkl/Variable-length-quantity new file mode 120000 index 0000000000..f903cb676b --- /dev/null +++ b/Lang/Zkl/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Variable-size-Get b/Lang/Zkl/Variable-size-Get new file mode 120000 index 0000000000..97b9933c3a --- /dev/null +++ b/Lang/Zkl/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Variables b/Lang/Zkl/Variables new file mode 120000 index 0000000000..a4880dfc0d --- /dev/null +++ b/Lang/Zkl/Variables @@ -0,0 +1 @@ +../../Task/Variables/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Variadic-function b/Lang/Zkl/Variadic-function new file mode 120000 index 0000000000..fd5ab0cac6 --- /dev/null +++ b/Lang/Zkl/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Vector-products b/Lang/Zkl/Vector-products new file mode 120000 index 0000000000..8e2abb2f02 --- /dev/null +++ b/Lang/Zkl/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Verify-distribution-uniformity-Chi-squared-test b/Lang/Zkl/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..e0fb2c354c --- /dev/null +++ b/Lang/Zkl/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Verify-distribution-uniformity-Naive b/Lang/Zkl/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..ff0dd46d9d --- /dev/null +++ b/Lang/Zkl/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Vigen-re-cipher b/Lang/Zkl/Vigen-re-cipher new file mode 120000 index 0000000000..0caeb61a31 --- /dev/null +++ b/Lang/Zkl/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Vigen-re-cipher-Cryptanalysis b/Lang/Zkl/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..308e6c1d64 --- /dev/null +++ b/Lang/Zkl/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Visualize-a-tree b/Lang/Zkl/Visualize-a-tree new file mode 120000 index 0000000000..36f355c645 --- /dev/null +++ b/Lang/Zkl/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Vogels-approximation-method b/Lang/Zkl/Vogels-approximation-method new file mode 120000 index 0000000000..c1843f411d --- /dev/null +++ b/Lang/Zkl/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Voronoi-diagram b/Lang/Zkl/Voronoi-diagram new file mode 120000 index 0000000000..8d8a902536 --- /dev/null +++ b/Lang/Zkl/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Walk-a-directory-Non-recursively b/Lang/Zkl/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..f9c7b4b9b5 --- /dev/null +++ b/Lang/Zkl/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Walk-a-directory-Recursively b/Lang/Zkl/Walk-a-directory-Recursively new file mode 120000 index 0000000000..5fc8f2637a --- /dev/null +++ b/Lang/Zkl/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Web-scraping b/Lang/Zkl/Web-scraping new file mode 120000 index 0000000000..4ad4f78e9e --- /dev/null +++ b/Lang/Zkl/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Word-wrap b/Lang/Zkl/Word-wrap new file mode 120000 index 0000000000..da760d322b --- /dev/null +++ b/Lang/Zkl/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Zkl \ No newline at end of file diff --git a/Lang/Zkl/World-Cup-group-stage b/Lang/Zkl/World-Cup-group-stage new file mode 120000 index 0000000000..ce3a94b4c2 --- /dev/null +++ b/Lang/Zkl/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Write-float-arrays-to-a-text-file b/Lang/Zkl/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..662dd496ac --- /dev/null +++ b/Lang/Zkl/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Write-language-name-in-3D-ASCII b/Lang/Zkl/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..a0c7ff9283 --- /dev/null +++ b/Lang/Zkl/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Write-to-Windows-event-log b/Lang/Zkl/Write-to-Windows-event-log new file mode 120000 index 0000000000..dde2b9c15c --- /dev/null +++ b/Lang/Zkl/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/Zkl \ No newline at end of file diff --git a/Lang/Zkl/XML-Input b/Lang/Zkl/XML-Input new file mode 120000 index 0000000000..595a6f26b5 --- /dev/null +++ b/Lang/Zkl/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Zkl \ No newline at end of file diff --git a/Lang/Zkl/XML-Output b/Lang/Zkl/XML-Output new file mode 120000 index 0000000000..1a9187f824 --- /dev/null +++ b/Lang/Zkl/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Y-combinator b/Lang/Zkl/Y-combinator new file mode 120000 index 0000000000..98b702f7ef --- /dev/null +++ b/Lang/Zkl/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Yin-and-yang b/Lang/Zkl/Yin-and-yang new file mode 120000 index 0000000000..68e9601479 --- /dev/null +++ b/Lang/Zkl/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Zebra-puzzle b/Lang/Zkl/Zebra-puzzle new file mode 120000 index 0000000000..bd2638ad61 --- /dev/null +++ b/Lang/Zkl/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Zeckendorf-number-representation b/Lang/Zkl/Zeckendorf-number-representation new file mode 120000 index 0000000000..2323ba1277 --- /dev/null +++ b/Lang/Zkl/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Zero-to-the-zero-power b/Lang/Zkl/Zero-to-the-zero-power new file mode 120000 index 0000000000..8aa6e1c1d8 --- /dev/null +++ b/Lang/Zkl/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Zig-zag-matrix b/Lang/Zkl/Zig-zag-matrix new file mode 120000 index 0000000000..57e7c94f6e --- /dev/null +++ b/Lang/Zkl/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Zkl \ No newline at end of file diff --git a/Lang/jq/100-doors b/Lang/jq/100-doors deleted file mode 120000 index 64620c24ef..0000000000 --- a/Lang/jq/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/jq \ No newline at end of file diff --git a/Lang/jq/24-game-Solve b/Lang/jq/24-game-Solve deleted file mode 120000 index c90a118112..0000000000 --- a/Lang/jq/24-game-Solve +++ /dev/null @@ -1 +0,0 @@ -../../Task/24-game-Solve/jq \ No newline at end of file diff --git a/Lang/jq/99-Bottles-of-Beer b/Lang/jq/99-Bottles-of-Beer deleted file mode 120000 index fd06f971ca..0000000000 --- a/Lang/jq/99-Bottles-of-Beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-Bottles-of-Beer/jq \ No newline at end of file diff --git a/Lang/jq/A+B b/Lang/jq/A+B deleted file mode 120000 index 6361cd7926..0000000000 --- a/Lang/jq/A+B +++ /dev/null @@ -1 +0,0 @@ -../../Task/A+B/jq \ No newline at end of file diff --git a/Lang/jq/ABC-Problem b/Lang/jq/ABC-Problem deleted file mode 120000 index 9dbe42d1f2..0000000000 --- a/Lang/jq/ABC-Problem +++ /dev/null @@ -1 +0,0 @@ -../../Task/ABC-Problem/jq \ No newline at end of file diff --git a/Lang/jq/AKS-test-for-primes b/Lang/jq/AKS-test-for-primes deleted file mode 120000 index 1d445baabf..0000000000 --- a/Lang/jq/AKS-test-for-primes +++ /dev/null @@ -1 +0,0 @@ -../../Task/AKS-test-for-primes/jq \ No newline at end of file diff --git a/Lang/jq/Abundant,-deficient-and-perfect-number-classifications b/Lang/jq/Abundant,-deficient-and-perfect-number-classifications deleted file mode 120000 index 8700f2750b..0000000000 --- a/Lang/jq/Abundant,-deficient-and-perfect-number-classifications +++ /dev/null @@ -1 +0,0 @@ -../../Task/Abundant,-deficient-and-perfect-number-classifications/jq \ No newline at end of file diff --git a/Lang/jq/Ackermann-function b/Lang/jq/Ackermann-function deleted file mode 120000 index 5f15421b94..0000000000 --- a/Lang/jq/Ackermann-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ackermann-function/jq \ No newline at end of file diff --git a/Lang/jq/Add-a-variable-to-a-class-instance-at-runtime b/Lang/jq/Add-a-variable-to-a-class-instance-at-runtime deleted file mode 120000 index e5a02b3885..0000000000 --- a/Lang/jq/Add-a-variable-to-a-class-instance-at-runtime +++ /dev/null @@ -1 +0,0 @@ -../../Task/Add-a-variable-to-a-class-instance-at-runtime/jq \ No newline at end of file diff --git a/Lang/jq/Align-columns b/Lang/jq/Align-columns deleted file mode 120000 index 4f5471e554..0000000000 --- a/Lang/jq/Align-columns +++ /dev/null @@ -1 +0,0 @@ -../../Task/Align-columns/jq \ No newline at end of file diff --git a/Lang/jq/Aliquot-sequence-classifications b/Lang/jq/Aliquot-sequence-classifications deleted file mode 120000 index 2b48aff453..0000000000 --- a/Lang/jq/Aliquot-sequence-classifications +++ /dev/null @@ -1 +0,0 @@ -../../Task/Aliquot-sequence-classifications/jq \ No newline at end of file diff --git a/Lang/jq/Almost-prime b/Lang/jq/Almost-prime deleted file mode 120000 index ce12bdb414..0000000000 --- a/Lang/jq/Almost-prime +++ /dev/null @@ -1 +0,0 @@ -../../Task/Almost-prime/jq \ No newline at end of file diff --git a/Lang/jq/Amb b/Lang/jq/Amb deleted file mode 120000 index 4e0cd6e134..0000000000 --- a/Lang/jq/Amb +++ /dev/null @@ -1 +0,0 @@ -../../Task/Amb/jq \ No newline at end of file diff --git a/Lang/jq/Amicable-pairs b/Lang/jq/Amicable-pairs deleted file mode 120000 index 0e2e48e729..0000000000 --- a/Lang/jq/Amicable-pairs +++ /dev/null @@ -1 +0,0 @@ -../../Task/Amicable-pairs/jq \ No newline at end of file diff --git a/Lang/jq/Anagrams b/Lang/jq/Anagrams deleted file mode 120000 index 9f636a01bd..0000000000 --- a/Lang/jq/Anagrams +++ /dev/null @@ -1 +0,0 @@ -../../Task/Anagrams/jq \ No newline at end of file diff --git a/Lang/jq/Anonymous-recursion b/Lang/jq/Anonymous-recursion deleted file mode 120000 index 9455fcd8fd..0000000000 --- a/Lang/jq/Anonymous-recursion +++ /dev/null @@ -1 +0,0 @@ -../../Task/Anonymous-recursion/jq \ No newline at end of file diff --git a/Lang/jq/Apply-a-callback-to-an-array b/Lang/jq/Apply-a-callback-to-an-array deleted file mode 120000 index 0baca02d61..0000000000 --- a/Lang/jq/Apply-a-callback-to-an-array +++ /dev/null @@ -1 +0,0 @@ -../../Task/Apply-a-callback-to-an-array/jq \ No newline at end of file diff --git a/Lang/jq/Arithmetic-Complex b/Lang/jq/Arithmetic-Complex deleted file mode 120000 index db7763bb31..0000000000 --- a/Lang/jq/Arithmetic-Complex +++ /dev/null @@ -1 +0,0 @@ -../../Task/Arithmetic-Complex/jq \ No newline at end of file diff --git a/Lang/jq/Arithmetic-Integer b/Lang/jq/Arithmetic-Integer deleted file mode 120000 index ad19e7ca66..0000000000 --- a/Lang/jq/Arithmetic-Integer +++ /dev/null @@ -1 +0,0 @@ -../../Task/Arithmetic-Integer/jq \ No newline at end of file diff --git a/Lang/jq/Arithmetic-geometric-mean b/Lang/jq/Arithmetic-geometric-mean deleted file mode 120000 index ca9b6deb24..0000000000 --- a/Lang/jq/Arithmetic-geometric-mean +++ /dev/null @@ -1 +0,0 @@ -../../Task/Arithmetic-geometric-mean/jq \ No newline at end of file diff --git a/Lang/jq/Array-concatenation b/Lang/jq/Array-concatenation deleted file mode 120000 index f027bac8cb..0000000000 --- a/Lang/jq/Array-concatenation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Array-concatenation/jq \ No newline at end of file diff --git a/Lang/jq/Arrays b/Lang/jq/Arrays deleted file mode 120000 index ba381d3771..0000000000 --- a/Lang/jq/Arrays +++ /dev/null @@ -1 +0,0 @@ -../../Task/Arrays/jq \ No newline at end of file diff --git a/Lang/jq/Associative-array-Creation b/Lang/jq/Associative-array-Creation deleted file mode 120000 index 8cf173c3f5..0000000000 --- a/Lang/jq/Associative-array-Creation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Associative-array-Creation/jq \ No newline at end of file diff --git a/Lang/jq/Averages-Arithmetic-mean b/Lang/jq/Averages-Arithmetic-mean deleted file mode 120000 index 0c9b68267a..0000000000 --- a/Lang/jq/Averages-Arithmetic-mean +++ /dev/null @@ -1 +0,0 @@ -../../Task/Averages-Arithmetic-mean/jq \ No newline at end of file diff --git a/Lang/jq/Averages-Mean-angle b/Lang/jq/Averages-Mean-angle deleted file mode 120000 index f55f649ff4..0000000000 --- a/Lang/jq/Averages-Mean-angle +++ /dev/null @@ -1 +0,0 @@ -../../Task/Averages-Mean-angle/jq \ No newline at end of file diff --git a/Lang/jq/Averages-Mean-time-of-day b/Lang/jq/Averages-Mean-time-of-day deleted file mode 120000 index 66e9750781..0000000000 --- a/Lang/jq/Averages-Mean-time-of-day +++ /dev/null @@ -1 +0,0 @@ -../../Task/Averages-Mean-time-of-day/jq \ No newline at end of file diff --git a/Lang/jq/Averages-Median b/Lang/jq/Averages-Median deleted file mode 120000 index 44b59e8aa9..0000000000 --- a/Lang/jq/Averages-Median +++ /dev/null @@ -1 +0,0 @@ -../../Task/Averages-Median/jq \ No newline at end of file diff --git a/Lang/jq/Averages-Mode b/Lang/jq/Averages-Mode deleted file mode 120000 index e454ba61ad..0000000000 --- a/Lang/jq/Averages-Mode +++ /dev/null @@ -1 +0,0 @@ -../../Task/Averages-Mode/jq \ No newline at end of file diff --git a/Lang/jq/Averages-Pythagorean-means b/Lang/jq/Averages-Pythagorean-means deleted file mode 120000 index 54687ab122..0000000000 --- a/Lang/jq/Averages-Pythagorean-means +++ /dev/null @@ -1 +0,0 @@ -../../Task/Averages-Pythagorean-means/jq \ No newline at end of file diff --git a/Lang/jq/Averages-Root-mean-square b/Lang/jq/Averages-Root-mean-square deleted file mode 120000 index f2aed7d862..0000000000 --- a/Lang/jq/Averages-Root-mean-square +++ /dev/null @@ -1 +0,0 @@ -../../Task/Averages-Root-mean-square/jq \ No newline at end of file diff --git a/Lang/jq/Benfords-law b/Lang/jq/Benfords-law deleted file mode 120000 index 8911fc1a34..0000000000 --- a/Lang/jq/Benfords-law +++ /dev/null @@ -1 +0,0 @@ -../../Task/Benfords-law/jq \ No newline at end of file diff --git a/Lang/jq/Bernoulli-numbers b/Lang/jq/Bernoulli-numbers deleted file mode 120000 index a997f43128..0000000000 --- a/Lang/jq/Bernoulli-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bernoulli-numbers/jq \ No newline at end of file diff --git a/Lang/jq/Binary-digits b/Lang/jq/Binary-digits deleted file mode 120000 index 75fc620e9c..0000000000 --- a/Lang/jq/Binary-digits +++ /dev/null @@ -1 +0,0 @@ -../../Task/Binary-digits/jq \ No newline at end of file diff --git a/Lang/jq/Binary-search b/Lang/jq/Binary-search deleted file mode 120000 index 4d9c9511f1..0000000000 --- a/Lang/jq/Binary-search +++ /dev/null @@ -1 +0,0 @@ -../../Task/Binary-search/jq \ No newline at end of file diff --git a/Lang/jq/Binary-strings b/Lang/jq/Binary-strings deleted file mode 120000 index b148f22acb..0000000000 --- a/Lang/jq/Binary-strings +++ /dev/null @@ -1 +0,0 @@ -../../Task/Binary-strings/jq \ No newline at end of file diff --git a/Lang/jq/CSV-data-manipulation b/Lang/jq/CSV-data-manipulation deleted file mode 120000 index c0ad56b70e..0000000000 --- a/Lang/jq/CSV-data-manipulation +++ /dev/null @@ -1 +0,0 @@ -../../Task/CSV-data-manipulation/jq \ No newline at end of file diff --git a/Lang/jq/CSV-to-HTML-translation b/Lang/jq/CSV-to-HTML-translation deleted file mode 120000 index 46cccba951..0000000000 --- a/Lang/jq/CSV-to-HTML-translation +++ /dev/null @@ -1 +0,0 @@ -../../Task/CSV-to-HTML-translation/jq \ No newline at end of file diff --git a/Lang/jq/Case-sensitivity-of-identifiers b/Lang/jq/Case-sensitivity-of-identifiers deleted file mode 120000 index 915d942945..0000000000 --- a/Lang/jq/Case-sensitivity-of-identifiers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Case-sensitivity-of-identifiers/jq \ No newline at end of file diff --git a/Lang/jq/Casting-out-nines b/Lang/jq/Casting-out-nines deleted file mode 120000 index fb944eaf04..0000000000 --- a/Lang/jq/Casting-out-nines +++ /dev/null @@ -1 +0,0 @@ -../../Task/Casting-out-nines/jq \ No newline at end of file diff --git a/Lang/jq/Catalan-numbers b/Lang/jq/Catalan-numbers deleted file mode 120000 index e3f6e86128..0000000000 --- a/Lang/jq/Catalan-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Catalan-numbers/jq \ No newline at end of file diff --git a/Lang/jq/Catalan-numbers-Pascals-triangle b/Lang/jq/Catalan-numbers-Pascals-triangle deleted file mode 120000 index b25f0007ca..0000000000 --- a/Lang/jq/Catalan-numbers-Pascals-triangle +++ /dev/null @@ -1 +0,0 @@ -../../Task/Catalan-numbers-Pascals-triangle/jq \ No newline at end of file diff --git a/Lang/jq/Character-codes b/Lang/jq/Character-codes deleted file mode 120000 index 3beaf03f67..0000000000 --- a/Lang/jq/Character-codes +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-codes/jq \ No newline at end of file diff --git a/Lang/jq/Chinese-remainder-theorem b/Lang/jq/Chinese-remainder-theorem deleted file mode 120000 index 0d73598544..0000000000 --- a/Lang/jq/Chinese-remainder-theorem +++ /dev/null @@ -1 +0,0 @@ -../../Task/Chinese-remainder-theorem/jq \ No newline at end of file diff --git a/Lang/jq/Cholesky-decomposition b/Lang/jq/Cholesky-decomposition deleted file mode 120000 index 6c068aaea2..0000000000 --- a/Lang/jq/Cholesky-decomposition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Cholesky-decomposition/jq \ No newline at end of file diff --git a/Lang/jq/Circles-of-given-radius-through-two-points b/Lang/jq/Circles-of-given-radius-through-two-points deleted file mode 120000 index 39b6dd572d..0000000000 --- a/Lang/jq/Circles-of-given-radius-through-two-points +++ /dev/null @@ -1 +0,0 @@ -../../Task/Circles-of-given-radius-through-two-points/jq \ No newline at end of file diff --git a/Lang/jq/Closest-pair-problem b/Lang/jq/Closest-pair-problem deleted file mode 120000 index eb8d48b547..0000000000 --- a/Lang/jq/Closest-pair-problem +++ /dev/null @@ -1 +0,0 @@ -../../Task/Closest-pair-problem/jq \ No newline at end of file diff --git a/Lang/jq/Collections b/Lang/jq/Collections deleted file mode 120000 index 8492e6ab97..0000000000 --- a/Lang/jq/Collections +++ /dev/null @@ -1 +0,0 @@ -../../Task/Collections/jq \ No newline at end of file diff --git a/Lang/jq/Combinations b/Lang/jq/Combinations deleted file mode 120000 index c6012ce04b..0000000000 --- a/Lang/jq/Combinations +++ /dev/null @@ -1 +0,0 @@ -../../Task/Combinations/jq \ No newline at end of file diff --git a/Lang/jq/Combinations-and-permutations b/Lang/jq/Combinations-and-permutations deleted file mode 120000 index b1fa8a8b7b..0000000000 --- a/Lang/jq/Combinations-and-permutations +++ /dev/null @@ -1 +0,0 @@ -../../Task/Combinations-and-permutations/jq \ No newline at end of file diff --git a/Lang/jq/Combinations-with-repetitions b/Lang/jq/Combinations-with-repetitions deleted file mode 120000 index 00ec71621e..0000000000 --- a/Lang/jq/Combinations-with-repetitions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Combinations-with-repetitions/jq \ No newline at end of file diff --git a/Lang/jq/Comma-quibbling b/Lang/jq/Comma-quibbling deleted file mode 120000 index b4ffffba2f..0000000000 --- a/Lang/jq/Comma-quibbling +++ /dev/null @@ -1 +0,0 @@ -../../Task/Comma-quibbling/jq \ No newline at end of file diff --git a/Lang/jq/Comments b/Lang/jq/Comments deleted file mode 120000 index fc994d7ff2..0000000000 --- a/Lang/jq/Comments +++ /dev/null @@ -1 +0,0 @@ -../../Task/Comments/jq \ No newline at end of file diff --git a/Lang/jq/Compound-data-type b/Lang/jq/Compound-data-type deleted file mode 120000 index b0f540a6a0..0000000000 --- a/Lang/jq/Compound-data-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Compound-data-type/jq \ No newline at end of file diff --git a/Lang/jq/Conditional-structures b/Lang/jq/Conditional-structures deleted file mode 120000 index 1ec37e927b..0000000000 --- a/Lang/jq/Conditional-structures +++ /dev/null @@ -1 +0,0 @@ -../../Task/Conditional-structures/jq \ No newline at end of file diff --git a/Lang/jq/Conjugate-transpose b/Lang/jq/Conjugate-transpose deleted file mode 120000 index c3ddd7b7c9..0000000000 --- a/Lang/jq/Conjugate-transpose +++ /dev/null @@ -1 +0,0 @@ -../../Task/Conjugate-transpose/jq \ No newline at end of file diff --git a/Lang/jq/Continued-fraction b/Lang/jq/Continued-fraction deleted file mode 120000 index 502e963312..0000000000 --- a/Lang/jq/Continued-fraction +++ /dev/null @@ -1 +0,0 @@ -../../Task/Continued-fraction/jq \ No newline at end of file diff --git a/Lang/jq/Conways-Game-of-Life b/Lang/jq/Conways-Game-of-Life deleted file mode 120000 index d6960290f8..0000000000 --- a/Lang/jq/Conways-Game-of-Life +++ /dev/null @@ -1 +0,0 @@ -../../Task/Conways-Game-of-Life/jq \ No newline at end of file diff --git a/Lang/jq/Copy-a-string b/Lang/jq/Copy-a-string deleted file mode 120000 index c7574393ef..0000000000 --- a/Lang/jq/Copy-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Copy-a-string/jq \ No newline at end of file diff --git a/Lang/jq/Count-occurrences-of-a-substring b/Lang/jq/Count-occurrences-of-a-substring deleted file mode 120000 index d2aac595aa..0000000000 --- a/Lang/jq/Count-occurrences-of-a-substring +++ /dev/null @@ -1 +0,0 @@ -../../Task/Count-occurrences-of-a-substring/jq \ No newline at end of file diff --git a/Lang/jq/Count-the-coins b/Lang/jq/Count-the-coins deleted file mode 120000 index 3f202f31bc..0000000000 --- a/Lang/jq/Count-the-coins +++ /dev/null @@ -1 +0,0 @@ -../../Task/Count-the-coins/jq \ No newline at end of file diff --git a/Lang/jq/Create-a-two-dimensional-array-at-runtime b/Lang/jq/Create-a-two-dimensional-array-at-runtime deleted file mode 120000 index 2b956d97e5..0000000000 --- a/Lang/jq/Create-a-two-dimensional-array-at-runtime +++ /dev/null @@ -1 +0,0 @@ -../../Task/Create-a-two-dimensional-array-at-runtime/jq \ No newline at end of file diff --git a/Lang/jq/Create-an-HTML-table b/Lang/jq/Create-an-HTML-table deleted file mode 120000 index 3ae0044846..0000000000 --- a/Lang/jq/Create-an-HTML-table +++ /dev/null @@ -1 +0,0 @@ -../../Task/Create-an-HTML-table/jq \ No newline at end of file diff --git a/Lang/jq/Currying b/Lang/jq/Currying deleted file mode 120000 index cab9263491..0000000000 --- a/Lang/jq/Currying +++ /dev/null @@ -1 +0,0 @@ -../../Task/Currying/jq \ No newline at end of file diff --git a/Lang/jq/Date-format b/Lang/jq/Date-format deleted file mode 120000 index 72829a1392..0000000000 --- a/Lang/jq/Date-format +++ /dev/null @@ -1 +0,0 @@ -../../Task/Date-format/jq \ No newline at end of file diff --git a/Lang/jq/Date-manipulation b/Lang/jq/Date-manipulation deleted file mode 120000 index 17cbf7da3e..0000000000 --- a/Lang/jq/Date-manipulation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Date-manipulation/jq \ No newline at end of file diff --git a/Lang/jq/Day-of-the-week b/Lang/jq/Day-of-the-week deleted file mode 120000 index c061bc1c35..0000000000 --- a/Lang/jq/Day-of-the-week +++ /dev/null @@ -1 +0,0 @@ -../../Task/Day-of-the-week/jq \ No newline at end of file diff --git a/Lang/jq/Define-a-primitive-data-type b/Lang/jq/Define-a-primitive-data-type deleted file mode 120000 index dc95ff836a..0000000000 --- a/Lang/jq/Define-a-primitive-data-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Define-a-primitive-data-type/jq \ No newline at end of file diff --git a/Lang/jq/Detect-division-by-zero b/Lang/jq/Detect-division-by-zero deleted file mode 120000 index 3c1b98ee62..0000000000 --- a/Lang/jq/Detect-division-by-zero +++ /dev/null @@ -1 +0,0 @@ -../../Task/Detect-division-by-zero/jq \ No newline at end of file diff --git a/Lang/jq/Determine-if-a-string-is-numeric b/Lang/jq/Determine-if-a-string-is-numeric deleted file mode 120000 index c27a82cd1b..0000000000 --- a/Lang/jq/Determine-if-a-string-is-numeric +++ /dev/null @@ -1 +0,0 @@ -../../Task/Determine-if-a-string-is-numeric/jq \ No newline at end of file diff --git a/Lang/jq/Digital-root b/Lang/jq/Digital-root deleted file mode 120000 index c63c2a55a5..0000000000 --- a/Lang/jq/Digital-root +++ /dev/null @@ -1 +0,0 @@ -../../Task/Digital-root/jq \ No newline at end of file diff --git a/Lang/jq/Digital-root-Multiplicative-digital-root b/Lang/jq/Digital-root-Multiplicative-digital-root deleted file mode 120000 index b5c7415db1..0000000000 --- a/Lang/jq/Digital-root-Multiplicative-digital-root +++ /dev/null @@ -1 +0,0 @@ -../../Task/Digital-root-Multiplicative-digital-root/jq \ No newline at end of file diff --git a/Lang/jq/Dinesmans-multiple-dwelling-problem b/Lang/jq/Dinesmans-multiple-dwelling-problem deleted file mode 120000 index eadad000fe..0000000000 --- a/Lang/jq/Dinesmans-multiple-dwelling-problem +++ /dev/null @@ -1 +0,0 @@ -../../Task/Dinesmans-multiple-dwelling-problem/jq \ No newline at end of file diff --git a/Lang/jq/Dot-product b/Lang/jq/Dot-product deleted file mode 120000 index a65f918946..0000000000 --- a/Lang/jq/Dot-product +++ /dev/null @@ -1 +0,0 @@ -../../Task/Dot-product/jq \ No newline at end of file diff --git a/Lang/jq/Dragon-curve b/Lang/jq/Dragon-curve deleted file mode 120000 index 62f7cafec1..0000000000 --- a/Lang/jq/Dragon-curve +++ /dev/null @@ -1 +0,0 @@ -../../Task/Dragon-curve/jq \ No newline at end of file diff --git a/Lang/jq/Draw-a-sphere b/Lang/jq/Draw-a-sphere deleted file mode 120000 index 1246656fef..0000000000 --- a/Lang/jq/Draw-a-sphere +++ /dev/null @@ -1 +0,0 @@ -../../Task/Draw-a-sphere/jq \ No newline at end of file diff --git a/Lang/jq/Element-wise-operations b/Lang/jq/Element-wise-operations deleted file mode 120000 index ed3f1bc8e4..0000000000 --- a/Lang/jq/Element-wise-operations +++ /dev/null @@ -1 +0,0 @@ -../../Task/Element-wise-operations/jq \ No newline at end of file diff --git a/Lang/jq/Empty-string b/Lang/jq/Empty-string deleted file mode 120000 index 51f274698d..0000000000 --- a/Lang/jq/Empty-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-string/jq \ No newline at end of file diff --git a/Lang/jq/Enforced-immutability b/Lang/jq/Enforced-immutability deleted file mode 120000 index 68c05481df..0000000000 --- a/Lang/jq/Enforced-immutability +++ /dev/null @@ -1 +0,0 @@ -../../Task/Enforced-immutability/jq \ No newline at end of file diff --git a/Lang/jq/Entropy b/Lang/jq/Entropy deleted file mode 120000 index c93f61f414..0000000000 --- a/Lang/jq/Entropy +++ /dev/null @@ -1 +0,0 @@ -../../Task/Entropy/jq \ No newline at end of file diff --git a/Lang/jq/Enumerations b/Lang/jq/Enumerations deleted file mode 120000 index 593efca591..0000000000 --- a/Lang/jq/Enumerations +++ /dev/null @@ -1 +0,0 @@ -../../Task/Enumerations/jq \ No newline at end of file diff --git a/Lang/jq/Environment-variables b/Lang/jq/Environment-variables deleted file mode 120000 index 004aa3b98b..0000000000 --- a/Lang/jq/Environment-variables +++ /dev/null @@ -1 +0,0 @@ -../../Task/Environment-variables/jq \ No newline at end of file diff --git a/Lang/jq/Equilibrium-index b/Lang/jq/Equilibrium-index deleted file mode 120000 index f494d635e4..0000000000 --- a/Lang/jq/Equilibrium-index +++ /dev/null @@ -1 +0,0 @@ -../../Task/Equilibrium-index/jq \ No newline at end of file diff --git a/Lang/jq/Euler-method b/Lang/jq/Euler-method deleted file mode 120000 index aa62ee130c..0000000000 --- a/Lang/jq/Euler-method +++ /dev/null @@ -1 +0,0 @@ -../../Task/Euler-method/jq \ No newline at end of file diff --git a/Lang/jq/Evaluate-binomial-coefficients b/Lang/jq/Evaluate-binomial-coefficients deleted file mode 120000 index 238f725fec..0000000000 --- a/Lang/jq/Evaluate-binomial-coefficients +++ /dev/null @@ -1 +0,0 @@ -../../Task/Evaluate-binomial-coefficients/jq \ No newline at end of file diff --git a/Lang/jq/Even-or-odd b/Lang/jq/Even-or-odd deleted file mode 120000 index 0b205d47ab..0000000000 --- a/Lang/jq/Even-or-odd +++ /dev/null @@ -1 +0,0 @@ -../../Task/Even-or-odd/jq \ No newline at end of file diff --git a/Lang/jq/Exceptions b/Lang/jq/Exceptions deleted file mode 120000 index b7def3ddba..0000000000 --- a/Lang/jq/Exceptions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Exceptions/jq \ No newline at end of file diff --git a/Lang/jq/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/jq/Exceptions-Catch-an-exception-thrown-in-a-nested-call deleted file mode 120000 index 563618c174..0000000000 --- a/Lang/jq/Exceptions-Catch-an-exception-thrown-in-a-nested-call +++ /dev/null @@ -1 +0,0 @@ -../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/jq \ No newline at end of file diff --git a/Lang/jq/Exponentiation-operator b/Lang/jq/Exponentiation-operator deleted file mode 120000 index c4e0cc03e1..0000000000 --- a/Lang/jq/Exponentiation-operator +++ /dev/null @@ -1 +0,0 @@ -../../Task/Exponentiation-operator/jq \ No newline at end of file diff --git a/Lang/jq/Extensible-prime-generator b/Lang/jq/Extensible-prime-generator deleted file mode 120000 index c63a971559..0000000000 --- a/Lang/jq/Extensible-prime-generator +++ /dev/null @@ -1 +0,0 @@ -../../Task/Extensible-prime-generator/jq \ No newline at end of file diff --git a/Lang/jq/Extreme-floating-point-values b/Lang/jq/Extreme-floating-point-values deleted file mode 120000 index 542d124028..0000000000 --- a/Lang/jq/Extreme-floating-point-values +++ /dev/null @@ -1 +0,0 @@ -../../Task/Extreme-floating-point-values/jq \ No newline at end of file diff --git a/Lang/jq/Factorial b/Lang/jq/Factorial deleted file mode 120000 index dcc5573f66..0000000000 --- a/Lang/jq/Factorial +++ /dev/null @@ -1 +0,0 @@ -../../Task/Factorial/jq \ No newline at end of file diff --git a/Lang/jq/Factors-of-an-integer b/Lang/jq/Factors-of-an-integer deleted file mode 120000 index 04ea6d9645..0000000000 --- a/Lang/jq/Factors-of-an-integer +++ /dev/null @@ -1 +0,0 @@ -../../Task/Factors-of-an-integer/jq \ No newline at end of file diff --git a/Lang/jq/Fast-Fourier-transform b/Lang/jq/Fast-Fourier-transform deleted file mode 120000 index 3f07990b2a..0000000000 --- a/Lang/jq/Fast-Fourier-transform +++ /dev/null @@ -1 +0,0 @@ -../../Task/Fast-Fourier-transform/jq \ No newline at end of file diff --git a/Lang/jq/Fibonacci-n-step-number-sequences b/Lang/jq/Fibonacci-n-step-number-sequences deleted file mode 120000 index fb36031b57..0000000000 --- a/Lang/jq/Fibonacci-n-step-number-sequences +++ /dev/null @@ -1 +0,0 @@ -../../Task/Fibonacci-n-step-number-sequences/jq \ No newline at end of file diff --git a/Lang/jq/Fibonacci-sequence b/Lang/jq/Fibonacci-sequence deleted file mode 120000 index be17810558..0000000000 --- a/Lang/jq/Fibonacci-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Fibonacci-sequence/jq \ No newline at end of file diff --git a/Lang/jq/Fibonacci-word b/Lang/jq/Fibonacci-word deleted file mode 120000 index 8e839a910d..0000000000 --- a/Lang/jq/Fibonacci-word +++ /dev/null @@ -1 +0,0 @@ -../../Task/Fibonacci-word/jq \ No newline at end of file diff --git a/Lang/jq/File-input-output b/Lang/jq/File-input-output deleted file mode 120000 index 0238b84121..0000000000 --- a/Lang/jq/File-input-output +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-input-output/jq \ No newline at end of file diff --git a/Lang/jq/File-size b/Lang/jq/File-size deleted file mode 120000 index 38d2e5ad66..0000000000 --- a/Lang/jq/File-size +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-size/jq \ No newline at end of file diff --git a/Lang/jq/Filter b/Lang/jq/Filter deleted file mode 120000 index d720eff4cd..0000000000 --- a/Lang/jq/Filter +++ /dev/null @@ -1 +0,0 @@ -../../Task/Filter/jq \ No newline at end of file diff --git a/Lang/jq/Find-common-directory-path b/Lang/jq/Find-common-directory-path deleted file mode 120000 index c2afe1e03c..0000000000 --- a/Lang/jq/Find-common-directory-path +++ /dev/null @@ -1 +0,0 @@ -../../Task/Find-common-directory-path/jq \ No newline at end of file diff --git a/Lang/jq/Find-limit-of-recursion b/Lang/jq/Find-limit-of-recursion deleted file mode 120000 index 207fe5532a..0000000000 --- a/Lang/jq/Find-limit-of-recursion +++ /dev/null @@ -1 +0,0 @@ -../../Task/Find-limit-of-recursion/jq \ No newline at end of file diff --git a/Lang/jq/Find-the-last-Sunday-of-each-month b/Lang/jq/Find-the-last-Sunday-of-each-month deleted file mode 120000 index 32cc04d83f..0000000000 --- a/Lang/jq/Find-the-last-Sunday-of-each-month +++ /dev/null @@ -1 +0,0 @@ -../../Task/Find-the-last-Sunday-of-each-month/jq \ No newline at end of file diff --git a/Lang/jq/Find-the-missing-permutation b/Lang/jq/Find-the-missing-permutation deleted file mode 120000 index e6135c39b9..0000000000 --- a/Lang/jq/Find-the-missing-permutation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Find-the-missing-permutation/jq \ No newline at end of file diff --git a/Lang/jq/First-class-functions-Use-numbers-analogously b/Lang/jq/First-class-functions-Use-numbers-analogously deleted file mode 120000 index 4b6ebaee94..0000000000 --- a/Lang/jq/First-class-functions-Use-numbers-analogously +++ /dev/null @@ -1 +0,0 @@ -../../Task/First-class-functions-Use-numbers-analogously/jq \ No newline at end of file diff --git a/Lang/jq/Five-weekends b/Lang/jq/Five-weekends deleted file mode 120000 index 618c750622..0000000000 --- a/Lang/jq/Five-weekends +++ /dev/null @@ -1 +0,0 @@ -../../Task/Five-weekends/jq \ No newline at end of file diff --git a/Lang/jq/FizzBuzz b/Lang/jq/FizzBuzz deleted file mode 120000 index 1ffda480cd..0000000000 --- a/Lang/jq/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/jq \ No newline at end of file diff --git a/Lang/jq/Flatten-a-list b/Lang/jq/Flatten-a-list deleted file mode 120000 index 8d8d5d0011..0000000000 --- a/Lang/jq/Flatten-a-list +++ /dev/null @@ -1 +0,0 @@ -../../Task/Flatten-a-list/jq \ No newline at end of file diff --git a/Lang/jq/Floyds-triangle b/Lang/jq/Floyds-triangle deleted file mode 120000 index feca7b37ba..0000000000 --- a/Lang/jq/Floyds-triangle +++ /dev/null @@ -1 +0,0 @@ -../../Task/Floyds-triangle/jq \ No newline at end of file diff --git a/Lang/jq/Formal-power-series b/Lang/jq/Formal-power-series deleted file mode 120000 index f3237a2ec3..0000000000 --- a/Lang/jq/Formal-power-series +++ /dev/null @@ -1 +0,0 @@ -../../Task/Formal-power-series/jq \ No newline at end of file diff --git a/Lang/jq/Formatted-numeric-output b/Lang/jq/Formatted-numeric-output deleted file mode 120000 index 0d016e90d9..0000000000 --- a/Lang/jq/Formatted-numeric-output +++ /dev/null @@ -1 +0,0 @@ -../../Task/Formatted-numeric-output/jq \ No newline at end of file diff --git a/Lang/jq/Forward-difference b/Lang/jq/Forward-difference deleted file mode 120000 index 6ef6d304dd..0000000000 --- a/Lang/jq/Forward-difference +++ /dev/null @@ -1 +0,0 @@ -../../Task/Forward-difference/jq \ No newline at end of file diff --git a/Lang/jq/Four-bit-adder b/Lang/jq/Four-bit-adder deleted file mode 120000 index 7b9d205879..0000000000 --- a/Lang/jq/Four-bit-adder +++ /dev/null @@ -1 +0,0 @@ -../../Task/Four-bit-adder/jq \ No newline at end of file diff --git a/Lang/jq/Fractal-tree b/Lang/jq/Fractal-tree deleted file mode 120000 index 5fc5742c6a..0000000000 --- a/Lang/jq/Fractal-tree +++ /dev/null @@ -1 +0,0 @@ -../../Task/Fractal-tree/jq \ No newline at end of file diff --git a/Lang/jq/Function-composition b/Lang/jq/Function-composition deleted file mode 120000 index 5d68b294a4..0000000000 --- a/Lang/jq/Function-composition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Function-composition/jq \ No newline at end of file diff --git a/Lang/jq/Function-definition b/Lang/jq/Function-definition deleted file mode 120000 index fb88f4218a..0000000000 --- a/Lang/jq/Function-definition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Function-definition/jq \ No newline at end of file diff --git a/Lang/jq/Gamma-function b/Lang/jq/Gamma-function deleted file mode 120000 index e98ab4bbc0..0000000000 --- a/Lang/jq/Gamma-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Gamma-function/jq \ No newline at end of file diff --git a/Lang/jq/Generate-lower-case-ASCII-alphabet b/Lang/jq/Generate-lower-case-ASCII-alphabet deleted file mode 120000 index 00511b6172..0000000000 --- a/Lang/jq/Generate-lower-case-ASCII-alphabet +++ /dev/null @@ -1 +0,0 @@ -../../Task/Generate-lower-case-ASCII-alphabet/jq \ No newline at end of file diff --git a/Lang/jq/Generator-Exponential b/Lang/jq/Generator-Exponential deleted file mode 120000 index 5dc816f45f..0000000000 --- a/Lang/jq/Generator-Exponential +++ /dev/null @@ -1 +0,0 @@ -../../Task/Generator-Exponential/jq \ No newline at end of file diff --git a/Lang/jq/Generic-swap b/Lang/jq/Generic-swap deleted file mode 120000 index 9b3b623e9e..0000000000 --- a/Lang/jq/Generic-swap +++ /dev/null @@ -1 +0,0 @@ -../../Task/Generic-swap/jq \ No newline at end of file diff --git a/Lang/jq/Greatest-common-divisor b/Lang/jq/Greatest-common-divisor deleted file mode 120000 index 458e3d1487..0000000000 --- a/Lang/jq/Greatest-common-divisor +++ /dev/null @@ -1 +0,0 @@ -../../Task/Greatest-common-divisor/jq \ No newline at end of file diff --git a/Lang/jq/Greatest-element-of-a-list b/Lang/jq/Greatest-element-of-a-list deleted file mode 120000 index 8e7c217278..0000000000 --- a/Lang/jq/Greatest-element-of-a-list +++ /dev/null @@ -1 +0,0 @@ -../../Task/Greatest-element-of-a-list/jq \ No newline at end of file diff --git a/Lang/jq/Greatest-subsequential-sum b/Lang/jq/Greatest-subsequential-sum deleted file mode 120000 index d16c4ff425..0000000000 --- a/Lang/jq/Greatest-subsequential-sum +++ /dev/null @@ -1 +0,0 @@ -../../Task/Greatest-subsequential-sum/jq \ No newline at end of file diff --git a/Lang/jq/Hailstone-sequence b/Lang/jq/Hailstone-sequence deleted file mode 120000 index 531c842938..0000000000 --- a/Lang/jq/Hailstone-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hailstone-sequence/jq \ No newline at end of file diff --git a/Lang/jq/Hamming-numbers b/Lang/jq/Hamming-numbers deleted file mode 120000 index ffbca6177b..0000000000 --- a/Lang/jq/Hamming-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hamming-numbers/jq \ No newline at end of file diff --git a/Lang/jq/Happy-numbers b/Lang/jq/Happy-numbers deleted file mode 120000 index f0daba2747..0000000000 --- a/Lang/jq/Happy-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Happy-numbers/jq \ No newline at end of file diff --git a/Lang/jq/Harshad-or-Niven-series b/Lang/jq/Harshad-or-Niven-series deleted file mode 120000 index aae4606e1b..0000000000 --- a/Lang/jq/Harshad-or-Niven-series +++ /dev/null @@ -1 +0,0 @@ -../../Task/Harshad-or-Niven-series/jq \ No newline at end of file diff --git a/Lang/jq/Hash-from-two-arrays b/Lang/jq/Hash-from-two-arrays deleted file mode 120000 index 05834b8d3e..0000000000 --- a/Lang/jq/Hash-from-two-arrays +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hash-from-two-arrays/jq \ No newline at end of file diff --git a/Lang/jq/Hash-join b/Lang/jq/Hash-join deleted file mode 120000 index 89b30387b6..0000000000 --- a/Lang/jq/Hash-join +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hash-join/jq \ No newline at end of file diff --git a/Lang/jq/Haversine-formula b/Lang/jq/Haversine-formula deleted file mode 120000 index 45605bf44e..0000000000 --- a/Lang/jq/Haversine-formula +++ /dev/null @@ -1 +0,0 @@ -../../Task/Haversine-formula/jq \ No newline at end of file diff --git a/Lang/jq/Hello-world-Graphical b/Lang/jq/Hello-world-Graphical deleted file mode 120000 index 86ef90b894..0000000000 --- a/Lang/jq/Hello-world-Graphical +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Graphical/jq \ No newline at end of file diff --git a/Lang/jq/Hello-world-Newbie b/Lang/jq/Hello-world-Newbie deleted file mode 120000 index 3739263b20..0000000000 --- a/Lang/jq/Hello-world-Newbie +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Newbie/jq \ No newline at end of file diff --git a/Lang/jq/Hello-world-Newline-omission b/Lang/jq/Hello-world-Newline-omission deleted file mode 120000 index 79184d07a0..0000000000 --- a/Lang/jq/Hello-world-Newline-omission +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Newline-omission/jq \ No newline at end of file diff --git a/Lang/jq/Hello-world-Standard-error b/Lang/jq/Hello-world-Standard-error deleted file mode 120000 index 4ef9ce9225..0000000000 --- a/Lang/jq/Hello-world-Standard-error +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Standard-error/jq \ No newline at end of file diff --git a/Lang/jq/Hello-world-Text b/Lang/jq/Hello-world-Text deleted file mode 120000 index fd30d28d8b..0000000000 --- a/Lang/jq/Hello-world-Text +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Text/jq \ No newline at end of file diff --git a/Lang/jq/Here-document b/Lang/jq/Here-document deleted file mode 120000 index e5a693fc0e..0000000000 --- a/Lang/jq/Here-document +++ /dev/null @@ -1 +0,0 @@ -../../Task/Here-document/jq \ No newline at end of file diff --git a/Lang/jq/Heronian-triangles b/Lang/jq/Heronian-triangles deleted file mode 120000 index 62d6773394..0000000000 --- a/Lang/jq/Heronian-triangles +++ /dev/null @@ -1 +0,0 @@ -../../Task/Heronian-triangles/jq \ No newline at end of file diff --git a/Lang/jq/Hickerson-series-of-almost-integers b/Lang/jq/Hickerson-series-of-almost-integers deleted file mode 120000 index 9f135439e9..0000000000 --- a/Lang/jq/Hickerson-series-of-almost-integers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hickerson-series-of-almost-integers/jq \ No newline at end of file diff --git a/Lang/jq/Higher-order-functions b/Lang/jq/Higher-order-functions deleted file mode 120000 index 039ab453b1..0000000000 --- a/Lang/jq/Higher-order-functions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Higher-order-functions/jq \ No newline at end of file diff --git a/Lang/jq/Hofstadter-Q-sequence b/Lang/jq/Hofstadter-Q-sequence deleted file mode 120000 index ea0068c389..0000000000 --- a/Lang/jq/Hofstadter-Q-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hofstadter-Q-sequence/jq \ No newline at end of file diff --git a/Lang/jq/I-before-E-except-after-C b/Lang/jq/I-before-E-except-after-C deleted file mode 120000 index 8677e5a0c0..0000000000 --- a/Lang/jq/I-before-E-except-after-C +++ /dev/null @@ -1 +0,0 @@ -../../Task/I-before-E-except-after-C/jq \ No newline at end of file diff --git a/Lang/jq/IBAN b/Lang/jq/IBAN deleted file mode 120000 index a0af10f6de..0000000000 --- a/Lang/jq/IBAN +++ /dev/null @@ -1 +0,0 @@ -../../Task/IBAN/jq \ No newline at end of file diff --git a/Lang/jq/Identity-matrix b/Lang/jq/Identity-matrix deleted file mode 120000 index 050df62dfd..0000000000 --- a/Lang/jq/Identity-matrix +++ /dev/null @@ -1 +0,0 @@ -../../Task/Identity-matrix/jq \ No newline at end of file diff --git a/Lang/jq/Include-a-file b/Lang/jq/Include-a-file deleted file mode 120000 index f3950cfe6d..0000000000 --- a/Lang/jq/Include-a-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Include-a-file/jq \ No newline at end of file diff --git a/Lang/jq/Increment-a-numerical-string b/Lang/jq/Increment-a-numerical-string deleted file mode 120000 index 65e61ac457..0000000000 --- a/Lang/jq/Increment-a-numerical-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Increment-a-numerical-string/jq \ No newline at end of file diff --git a/Lang/jq/Infinity b/Lang/jq/Infinity deleted file mode 120000 index 1eae182da0..0000000000 --- a/Lang/jq/Infinity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Infinity/jq \ No newline at end of file diff --git a/Lang/jq/Input-loop b/Lang/jq/Input-loop deleted file mode 120000 index 087b2f007f..0000000000 --- a/Lang/jq/Input-loop +++ /dev/null @@ -1 +0,0 @@ -../../Task/Input-loop/jq \ No newline at end of file diff --git a/Lang/jq/Integer-comparison b/Lang/jq/Integer-comparison deleted file mode 120000 index b3a0c6689e..0000000000 --- a/Lang/jq/Integer-comparison +++ /dev/null @@ -1 +0,0 @@ -../../Task/Integer-comparison/jq \ No newline at end of file diff --git a/Lang/jq/Integer-sequence b/Lang/jq/Integer-sequence deleted file mode 120000 index 7bd6e7d13d..0000000000 --- a/Lang/jq/Integer-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Integer-sequence/jq \ No newline at end of file diff --git a/Lang/jq/Inverted-index b/Lang/jq/Inverted-index deleted file mode 120000 index d589eb77ac..0000000000 --- a/Lang/jq/Inverted-index +++ /dev/null @@ -1 +0,0 @@ -../../Task/Inverted-index/jq \ No newline at end of file diff --git a/Lang/jq/Inverted-syntax b/Lang/jq/Inverted-syntax deleted file mode 120000 index 74b8d52f4a..0000000000 --- a/Lang/jq/Inverted-syntax +++ /dev/null @@ -1 +0,0 @@ -../../Task/Inverted-syntax/jq \ No newline at end of file diff --git a/Lang/jq/Iterated-digits-squaring b/Lang/jq/Iterated-digits-squaring deleted file mode 120000 index 155dbe5090..0000000000 --- a/Lang/jq/Iterated-digits-squaring +++ /dev/null @@ -1 +0,0 @@ -../../Task/Iterated-digits-squaring/jq \ No newline at end of file diff --git a/Lang/jq/JSON b/Lang/jq/JSON deleted file mode 120000 index 77a3e298e4..0000000000 --- a/Lang/jq/JSON +++ /dev/null @@ -1 +0,0 @@ -../../Task/JSON/jq \ No newline at end of file diff --git a/Lang/jq/Jensens-Device b/Lang/jq/Jensens-Device deleted file mode 120000 index c6703d83bc..0000000000 --- a/Lang/jq/Jensens-Device +++ /dev/null @@ -1 +0,0 @@ -../../Task/Jensens-Device/jq \ No newline at end of file diff --git a/Lang/jq/Josephus-problem b/Lang/jq/Josephus-problem deleted file mode 120000 index ee00505f82..0000000000 --- a/Lang/jq/Josephus-problem +++ /dev/null @@ -1 +0,0 @@ -../../Task/Josephus-problem/jq \ No newline at end of file diff --git a/Lang/jq/Jump-anywhere b/Lang/jq/Jump-anywhere deleted file mode 120000 index c9c37ea35f..0000000000 --- a/Lang/jq/Jump-anywhere +++ /dev/null @@ -1 +0,0 @@ -../../Task/Jump-anywhere/jq \ No newline at end of file diff --git a/Lang/jq/Kaprekar-numbers b/Lang/jq/Kaprekar-numbers deleted file mode 120000 index cb34e2a076..0000000000 --- a/Lang/jq/Kaprekar-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Kaprekar-numbers/jq \ No newline at end of file diff --git a/Lang/jq/Knapsack-problem-0-1 b/Lang/jq/Knapsack-problem-0-1 deleted file mode 120000 index c5a9085dcc..0000000000 --- a/Lang/jq/Knapsack-problem-0-1 +++ /dev/null @@ -1 +0,0 @@ -../../Task/Knapsack-problem-0-1/jq \ No newline at end of file diff --git a/Lang/jq/Knapsack-problem-Continuous b/Lang/jq/Knapsack-problem-Continuous deleted file mode 120000 index 6cdb0bad20..0000000000 --- a/Lang/jq/Knapsack-problem-Continuous +++ /dev/null @@ -1 +0,0 @@ -../../Task/Knapsack-problem-Continuous/jq \ No newline at end of file diff --git a/Lang/jq/LU-decomposition b/Lang/jq/LU-decomposition deleted file mode 120000 index 65231474ef..0000000000 --- a/Lang/jq/LU-decomposition +++ /dev/null @@ -1 +0,0 @@ -../../Task/LU-decomposition/jq \ No newline at end of file diff --git a/Lang/jq/LZW-compression b/Lang/jq/LZW-compression deleted file mode 120000 index 31d6658418..0000000000 --- a/Lang/jq/LZW-compression +++ /dev/null @@ -1 +0,0 @@ -../../Task/LZW-compression/jq \ No newline at end of file diff --git a/Lang/jq/Langtons-ant b/Lang/jq/Langtons-ant deleted file mode 120000 index 2765fc5d09..0000000000 --- a/Lang/jq/Langtons-ant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Langtons-ant/jq \ No newline at end of file diff --git a/Lang/jq/Largest-int-from-concatenated-ints b/Lang/jq/Largest-int-from-concatenated-ints deleted file mode 120000 index 1a4e31a859..0000000000 --- a/Lang/jq/Largest-int-from-concatenated-ints +++ /dev/null @@ -1 +0,0 @@ -../../Task/Largest-int-from-concatenated-ints/jq \ No newline at end of file diff --git a/Lang/jq/Last-Friday-of-each-month b/Lang/jq/Last-Friday-of-each-month deleted file mode 120000 index f5af02bf27..0000000000 --- a/Lang/jq/Last-Friday-of-each-month +++ /dev/null @@ -1 +0,0 @@ -../../Task/Last-Friday-of-each-month/jq \ No newline at end of file diff --git a/Lang/jq/Last-letter-first-letter b/Lang/jq/Last-letter-first-letter deleted file mode 120000 index 4e30a86949..0000000000 --- a/Lang/jq/Last-letter-first-letter +++ /dev/null @@ -1 +0,0 @@ -../../Task/Last-letter-first-letter/jq \ No newline at end of file diff --git a/Lang/jq/Leap-year b/Lang/jq/Leap-year deleted file mode 120000 index 06f5b5f3a2..0000000000 --- a/Lang/jq/Leap-year +++ /dev/null @@ -1 +0,0 @@ -../../Task/Leap-year/jq \ No newline at end of file diff --git a/Lang/jq/Least-common-multiple b/Lang/jq/Least-common-multiple deleted file mode 120000 index e28bff4b1c..0000000000 --- a/Lang/jq/Least-common-multiple +++ /dev/null @@ -1 +0,0 @@ -../../Task/Least-common-multiple/jq \ No newline at end of file diff --git a/Lang/jq/Left-factorials b/Lang/jq/Left-factorials deleted file mode 120000 index 74a810951f..0000000000 --- a/Lang/jq/Left-factorials +++ /dev/null @@ -1 +0,0 @@ -../../Task/Left-factorials/jq \ No newline at end of file diff --git a/Lang/jq/Letter-frequency b/Lang/jq/Letter-frequency deleted file mode 120000 index 68fca3d40a..0000000000 --- a/Lang/jq/Letter-frequency +++ /dev/null @@ -1 +0,0 @@ -../../Task/Letter-frequency/jq \ No newline at end of file diff --git a/Lang/jq/Levenshtein-distance b/Lang/jq/Levenshtein-distance deleted file mode 120000 index 28121fc841..0000000000 --- a/Lang/jq/Levenshtein-distance +++ /dev/null @@ -1 +0,0 @@ -../../Task/Levenshtein-distance/jq \ No newline at end of file diff --git a/Lang/jq/Linear-congruential-generator b/Lang/jq/Linear-congruential-generator deleted file mode 120000 index 60dfe034dc..0000000000 --- a/Lang/jq/Linear-congruential-generator +++ /dev/null @@ -1 +0,0 @@ -../../Task/Linear-congruential-generator/jq \ No newline at end of file diff --git a/Lang/jq/List-comprehensions b/Lang/jq/List-comprehensions deleted file mode 120000 index 9a93ffd2d2..0000000000 --- a/Lang/jq/List-comprehensions +++ /dev/null @@ -1 +0,0 @@ -../../Task/List-comprehensions/jq \ No newline at end of file diff --git a/Lang/jq/Literals-Floating-point b/Lang/jq/Literals-Floating-point deleted file mode 120000 index edd07c4b1e..0000000000 --- a/Lang/jq/Literals-Floating-point +++ /dev/null @@ -1 +0,0 @@ -../../Task/Literals-Floating-point/jq \ No newline at end of file diff --git a/Lang/jq/Logical-operations b/Lang/jq/Logical-operations deleted file mode 120000 index 95ff723fd1..0000000000 --- a/Lang/jq/Logical-operations +++ /dev/null @@ -1 +0,0 @@ -../../Task/Logical-operations/jq \ No newline at end of file diff --git a/Lang/jq/Long-multiplication b/Lang/jq/Long-multiplication deleted file mode 120000 index 5b95ab175f..0000000000 --- a/Lang/jq/Long-multiplication +++ /dev/null @@ -1 +0,0 @@ -../../Task/Long-multiplication/jq \ No newline at end of file diff --git a/Lang/jq/Longest-common-subsequence b/Lang/jq/Longest-common-subsequence deleted file mode 120000 index 5ce4aedc1e..0000000000 --- a/Lang/jq/Longest-common-subsequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Longest-common-subsequence/jq \ No newline at end of file diff --git a/Lang/jq/Longest-increasing-subsequence b/Lang/jq/Longest-increasing-subsequence deleted file mode 120000 index cf75b768be..0000000000 --- a/Lang/jq/Longest-increasing-subsequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Longest-increasing-subsequence/jq \ No newline at end of file diff --git a/Lang/jq/Look-and-say-sequence b/Lang/jq/Look-and-say-sequence deleted file mode 120000 index 55e24d4596..0000000000 --- a/Lang/jq/Look-and-say-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Look-and-say-sequence/jq \ No newline at end of file diff --git a/Lang/jq/Loop-over-multiple-arrays-simultaneously b/Lang/jq/Loop-over-multiple-arrays-simultaneously deleted file mode 120000 index 0103d65f43..0000000000 --- a/Lang/jq/Loop-over-multiple-arrays-simultaneously +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loop-over-multiple-arrays-simultaneously/jq \ No newline at end of file diff --git a/Lang/jq/Loops-Continue b/Lang/jq/Loops-Continue deleted file mode 120000 index e6bd8fa39a..0000000000 --- a/Lang/jq/Loops-Continue +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Continue/jq \ No newline at end of file diff --git a/Lang/jq/Loops-Do-while b/Lang/jq/Loops-Do-while deleted file mode 120000 index 5a9c41e0a5..0000000000 --- a/Lang/jq/Loops-Do-while +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Do-while/jq \ No newline at end of file diff --git a/Lang/jq/Loops-Downward-for b/Lang/jq/Loops-Downward-for deleted file mode 120000 index b8f7c3f61f..0000000000 --- a/Lang/jq/Loops-Downward-for +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Downward-for/jq \ No newline at end of file diff --git a/Lang/jq/Loops-For b/Lang/jq/Loops-For deleted file mode 120000 index 64f2246b7e..0000000000 --- a/Lang/jq/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/jq \ No newline at end of file diff --git a/Lang/jq/Loops-For-with-a-specified-step b/Lang/jq/Loops-For-with-a-specified-step deleted file mode 120000 index cf3c63285c..0000000000 --- a/Lang/jq/Loops-For-with-a-specified-step +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For-with-a-specified-step/jq \ No newline at end of file diff --git a/Lang/jq/Loops-Foreach b/Lang/jq/Loops-Foreach deleted file mode 120000 index a12051ada1..0000000000 --- a/Lang/jq/Loops-Foreach +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Foreach/jq \ No newline at end of file diff --git a/Lang/jq/Loops-Infinite b/Lang/jq/Loops-Infinite deleted file mode 120000 index 5ad8e6cc2e..0000000000 --- a/Lang/jq/Loops-Infinite +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Infinite/jq \ No newline at end of file diff --git a/Lang/jq/Loops-N-plus-one-half b/Lang/jq/Loops-N-plus-one-half deleted file mode 120000 index a103981177..0000000000 --- a/Lang/jq/Loops-N-plus-one-half +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-N-plus-one-half/jq \ No newline at end of file diff --git a/Lang/jq/Loops-While b/Lang/jq/Loops-While deleted file mode 120000 index 8db73e32d6..0000000000 --- a/Lang/jq/Loops-While +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-While/jq \ No newline at end of file diff --git a/Lang/jq/Luhn-test-of-credit-card-numbers b/Lang/jq/Luhn-test-of-credit-card-numbers deleted file mode 120000 index 01dc7c1efb..0000000000 --- a/Lang/jq/Luhn-test-of-credit-card-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Luhn-test-of-credit-card-numbers/jq \ No newline at end of file diff --git a/Lang/jq/Magic-squares-of-odd-order b/Lang/jq/Magic-squares-of-odd-order deleted file mode 120000 index eac823e88f..0000000000 --- a/Lang/jq/Magic-squares-of-odd-order +++ /dev/null @@ -1 +0,0 @@ -../../Task/Magic-squares-of-odd-order/jq \ No newline at end of file diff --git a/Lang/jq/Mandelbrot-set b/Lang/jq/Mandelbrot-set deleted file mode 120000 index 26b0c4d984..0000000000 --- a/Lang/jq/Mandelbrot-set +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mandelbrot-set/jq \ No newline at end of file diff --git a/Lang/jq/Map-range b/Lang/jq/Map-range deleted file mode 120000 index 177b47215e..0000000000 --- a/Lang/jq/Map-range +++ /dev/null @@ -1 +0,0 @@ -../../Task/Map-range/jq \ No newline at end of file diff --git a/Lang/jq/Matrix-arithmetic b/Lang/jq/Matrix-arithmetic deleted file mode 120000 index dab94d242d..0000000000 --- a/Lang/jq/Matrix-arithmetic +++ /dev/null @@ -1 +0,0 @@ -../../Task/Matrix-arithmetic/jq \ No newline at end of file diff --git a/Lang/jq/Matrix-exponentiation-operator b/Lang/jq/Matrix-exponentiation-operator deleted file mode 120000 index 126393f6f4..0000000000 --- a/Lang/jq/Matrix-exponentiation-operator +++ /dev/null @@ -1 +0,0 @@ -../../Task/Matrix-exponentiation-operator/jq \ No newline at end of file diff --git a/Lang/jq/Matrix-multiplication b/Lang/jq/Matrix-multiplication deleted file mode 120000 index 966ca1487a..0000000000 --- a/Lang/jq/Matrix-multiplication +++ /dev/null @@ -1 +0,0 @@ -../../Task/Matrix-multiplication/jq \ No newline at end of file diff --git a/Lang/jq/Matrix-transposition b/Lang/jq/Matrix-transposition deleted file mode 120000 index edacbd31f4..0000000000 --- a/Lang/jq/Matrix-transposition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Matrix-transposition/jq \ No newline at end of file diff --git a/Lang/jq/Maximum-triangle-path-sum b/Lang/jq/Maximum-triangle-path-sum deleted file mode 120000 index d5c87fdf6e..0000000000 --- a/Lang/jq/Maximum-triangle-path-sum +++ /dev/null @@ -1 +0,0 @@ -../../Task/Maximum-triangle-path-sum/jq \ No newline at end of file diff --git a/Lang/jq/Menu b/Lang/jq/Menu deleted file mode 120000 index afb7510e54..0000000000 --- a/Lang/jq/Menu +++ /dev/null @@ -1 +0,0 @@ -../../Task/Menu/jq \ No newline at end of file diff --git a/Lang/jq/Middle-three-digits b/Lang/jq/Middle-three-digits deleted file mode 120000 index 755f8144b9..0000000000 --- a/Lang/jq/Middle-three-digits +++ /dev/null @@ -1 +0,0 @@ -../../Task/Middle-three-digits/jq \ No newline at end of file diff --git a/Lang/jq/Move-to-front-algorithm b/Lang/jq/Move-to-front-algorithm deleted file mode 120000 index 831f5b4af8..0000000000 --- a/Lang/jq/Move-to-front-algorithm +++ /dev/null @@ -1 +0,0 @@ -../../Task/Move-to-front-algorithm/jq \ No newline at end of file diff --git a/Lang/jq/Multifactorial b/Lang/jq/Multifactorial deleted file mode 120000 index 720c39d429..0000000000 --- a/Lang/jq/Multifactorial +++ /dev/null @@ -1 +0,0 @@ -../../Task/Multifactorial/jq \ No newline at end of file diff --git a/Lang/jq/Multiple-distinct-objects b/Lang/jq/Multiple-distinct-objects deleted file mode 120000 index 1845b7dd46..0000000000 --- a/Lang/jq/Multiple-distinct-objects +++ /dev/null @@ -1 +0,0 @@ -../../Task/Multiple-distinct-objects/jq \ No newline at end of file diff --git a/Lang/jq/Multisplit b/Lang/jq/Multisplit deleted file mode 120000 index 117c105741..0000000000 --- a/Lang/jq/Multisplit +++ /dev/null @@ -1 +0,0 @@ -../../Task/Multisplit/jq \ No newline at end of file diff --git a/Lang/jq/Munching-squares b/Lang/jq/Munching-squares deleted file mode 120000 index 9ad05e5792..0000000000 --- a/Lang/jq/Munching-squares +++ /dev/null @@ -1 +0,0 @@ -../../Task/Munching-squares/jq \ No newline at end of file diff --git a/Lang/jq/Mutual-recursion b/Lang/jq/Mutual-recursion deleted file mode 120000 index 10e27ca341..0000000000 --- a/Lang/jq/Mutual-recursion +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutual-recursion/jq \ No newline at end of file diff --git a/Lang/jq/N-queens-problem b/Lang/jq/N-queens-problem deleted file mode 120000 index 2f185da6e8..0000000000 --- a/Lang/jq/N-queens-problem +++ /dev/null @@ -1 +0,0 @@ -../../Task/N-queens-problem/jq \ No newline at end of file diff --git a/Lang/jq/Named-parameters b/Lang/jq/Named-parameters deleted file mode 120000 index 467073a675..0000000000 --- a/Lang/jq/Named-parameters +++ /dev/null @@ -1 +0,0 @@ -../../Task/Named-parameters/jq \ No newline at end of file diff --git a/Lang/jq/Narcissistic-decimal-number b/Lang/jq/Narcissistic-decimal-number deleted file mode 120000 index 8d9dd3f2c3..0000000000 --- a/Lang/jq/Narcissistic-decimal-number +++ /dev/null @@ -1 +0,0 @@ -../../Task/Narcissistic-decimal-number/jq \ No newline at end of file diff --git a/Lang/jq/Natural-sorting b/Lang/jq/Natural-sorting deleted file mode 120000 index 90b3c8c6f6..0000000000 --- a/Lang/jq/Natural-sorting +++ /dev/null @@ -1 +0,0 @@ -../../Task/Natural-sorting/jq \ No newline at end of file diff --git a/Lang/jq/Non-continuous-subsequences b/Lang/jq/Non-continuous-subsequences deleted file mode 120000 index 1eee870240..0000000000 --- a/Lang/jq/Non-continuous-subsequences +++ /dev/null @@ -1 +0,0 @@ -../../Task/Non-continuous-subsequences/jq \ No newline at end of file diff --git a/Lang/jq/Non-decimal-radices-Convert b/Lang/jq/Non-decimal-radices-Convert deleted file mode 120000 index 510cd0a48e..0000000000 --- a/Lang/jq/Non-decimal-radices-Convert +++ /dev/null @@ -1 +0,0 @@ -../../Task/Non-decimal-radices-Convert/jq \ No newline at end of file diff --git a/Lang/jq/Nth b/Lang/jq/Nth deleted file mode 120000 index 27e77b9610..0000000000 --- a/Lang/jq/Nth +++ /dev/null @@ -1 +0,0 @@ -../../Task/Nth/jq \ No newline at end of file diff --git a/Lang/jq/Nth-root b/Lang/jq/Nth-root deleted file mode 120000 index 466ab46741..0000000000 --- a/Lang/jq/Nth-root +++ /dev/null @@ -1 +0,0 @@ -../../Task/Nth-root/jq \ No newline at end of file diff --git a/Lang/jq/Null-object b/Lang/jq/Null-object deleted file mode 120000 index 65ecb9bf9e..0000000000 --- a/Lang/jq/Null-object +++ /dev/null @@ -1 +0,0 @@ -../../Task/Null-object/jq \ No newline at end of file diff --git a/Lang/jq/Number-names b/Lang/jq/Number-names deleted file mode 120000 index 222d8bbbe6..0000000000 --- a/Lang/jq/Number-names +++ /dev/null @@ -1 +0,0 @@ -../../Task/Number-names/jq \ No newline at end of file diff --git a/Lang/jq/One-dimensional-cellular-automata b/Lang/jq/One-dimensional-cellular-automata deleted file mode 120000 index 6ddf378c3d..0000000000 --- a/Lang/jq/One-dimensional-cellular-automata +++ /dev/null @@ -1 +0,0 @@ -../../Task/One-dimensional-cellular-automata/jq \ No newline at end of file diff --git a/Lang/jq/Optional-parameters b/Lang/jq/Optional-parameters deleted file mode 120000 index 220ff8eaac..0000000000 --- a/Lang/jq/Optional-parameters +++ /dev/null @@ -1 +0,0 @@ -../../Task/Optional-parameters/jq \ No newline at end of file diff --git a/Lang/jq/Order-disjoint-list-items b/Lang/jq/Order-disjoint-list-items deleted file mode 120000 index 1e6b3145a5..0000000000 --- a/Lang/jq/Order-disjoint-list-items +++ /dev/null @@ -1 +0,0 @@ -../../Task/Order-disjoint-list-items/jq \ No newline at end of file diff --git a/Lang/jq/Order-two-numerical-lists b/Lang/jq/Order-two-numerical-lists deleted file mode 120000 index 0cea96e323..0000000000 --- a/Lang/jq/Order-two-numerical-lists +++ /dev/null @@ -1 +0,0 @@ -../../Task/Order-two-numerical-lists/jq \ No newline at end of file diff --git a/Lang/jq/Ordered-Partitions b/Lang/jq/Ordered-Partitions deleted file mode 120000 index 9e5b4c3a90..0000000000 --- a/Lang/jq/Ordered-Partitions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ordered-Partitions/jq \ No newline at end of file diff --git a/Lang/jq/Ordered-words b/Lang/jq/Ordered-words deleted file mode 120000 index 59b3880dd1..0000000000 --- a/Lang/jq/Ordered-words +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ordered-words/jq \ No newline at end of file diff --git a/Lang/jq/Palindrome-detection b/Lang/jq/Palindrome-detection deleted file mode 120000 index 1c9e94b134..0000000000 --- a/Lang/jq/Palindrome-detection +++ /dev/null @@ -1 +0,0 @@ -../../Task/Palindrome-detection/jq \ No newline at end of file diff --git a/Lang/jq/Pangram-checker b/Lang/jq/Pangram-checker deleted file mode 120000 index d60ef3dbf4..0000000000 --- a/Lang/jq/Pangram-checker +++ /dev/null @@ -1 +0,0 @@ -../../Task/Pangram-checker/jq \ No newline at end of file diff --git a/Lang/jq/Paraffins b/Lang/jq/Paraffins deleted file mode 120000 index 73cba13b96..0000000000 --- a/Lang/jq/Paraffins +++ /dev/null @@ -1 +0,0 @@ -../../Task/Paraffins/jq \ No newline at end of file diff --git a/Lang/jq/Pascals-triangle b/Lang/jq/Pascals-triangle deleted file mode 120000 index 56fae8663c..0000000000 --- a/Lang/jq/Pascals-triangle +++ /dev/null @@ -1 +0,0 @@ -../../Task/Pascals-triangle/jq \ No newline at end of file diff --git a/Lang/jq/Perfect-numbers b/Lang/jq/Perfect-numbers deleted file mode 120000 index 6088ecf85d..0000000000 --- a/Lang/jq/Perfect-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Perfect-numbers/jq \ No newline at end of file diff --git a/Lang/jq/Permutation-test b/Lang/jq/Permutation-test deleted file mode 120000 index 8bc91beafb..0000000000 --- a/Lang/jq/Permutation-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Permutation-test/jq \ No newline at end of file diff --git a/Lang/jq/Permutations b/Lang/jq/Permutations deleted file mode 120000 index 99f3a3311c..0000000000 --- a/Lang/jq/Permutations +++ /dev/null @@ -1 +0,0 @@ -../../Task/Permutations/jq \ No newline at end of file diff --git a/Lang/jq/Permutations-Derangements b/Lang/jq/Permutations-Derangements deleted file mode 120000 index e67767a37d..0000000000 --- a/Lang/jq/Permutations-Derangements +++ /dev/null @@ -1 +0,0 @@ -../../Task/Permutations-Derangements/jq \ No newline at end of file diff --git a/Lang/jq/Permutations-by-swapping b/Lang/jq/Permutations-by-swapping deleted file mode 120000 index 2a983dd029..0000000000 --- a/Lang/jq/Permutations-by-swapping +++ /dev/null @@ -1 +0,0 @@ -../../Task/Permutations-by-swapping/jq \ No newline at end of file diff --git a/Lang/jq/Pernicious-numbers b/Lang/jq/Pernicious-numbers deleted file mode 120000 index e119be00b3..0000000000 --- a/Lang/jq/Pernicious-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Pernicious-numbers/jq \ No newline at end of file diff --git a/Lang/jq/Phrase-reversals b/Lang/jq/Phrase-reversals deleted file mode 120000 index 21a929b605..0000000000 --- a/Lang/jq/Phrase-reversals +++ /dev/null @@ -1 +0,0 @@ -../../Task/Phrase-reversals/jq \ No newline at end of file diff --git a/Lang/jq/Pi b/Lang/jq/Pi deleted file mode 120000 index 43e516f667..0000000000 --- a/Lang/jq/Pi +++ /dev/null @@ -1 +0,0 @@ -../../Task/Pi/jq \ No newline at end of file diff --git a/Lang/jq/Plot-coordinate-pairs b/Lang/jq/Plot-coordinate-pairs deleted file mode 120000 index 42672a5592..0000000000 --- a/Lang/jq/Plot-coordinate-pairs +++ /dev/null @@ -1 +0,0 @@ -../../Task/Plot-coordinate-pairs/jq \ No newline at end of file diff --git a/Lang/jq/Power-set b/Lang/jq/Power-set deleted file mode 120000 index c5a2556b1e..0000000000 --- a/Lang/jq/Power-set +++ /dev/null @@ -1 +0,0 @@ -../../Task/Power-set/jq \ No newline at end of file diff --git a/Lang/jq/Price-fraction b/Lang/jq/Price-fraction deleted file mode 120000 index b540e6c2fd..0000000000 --- a/Lang/jq/Price-fraction +++ /dev/null @@ -1 +0,0 @@ -../../Task/Price-fraction/jq \ No newline at end of file diff --git a/Lang/jq/Prime-decomposition b/Lang/jq/Prime-decomposition deleted file mode 120000 index f4227c02ff..0000000000 --- a/Lang/jq/Prime-decomposition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Prime-decomposition/jq \ No newline at end of file diff --git a/Lang/jq/Priority-queue b/Lang/jq/Priority-queue deleted file mode 120000 index 28de1716dd..0000000000 --- a/Lang/jq/Priority-queue +++ /dev/null @@ -1 +0,0 @@ -../../Task/Priority-queue/jq \ No newline at end of file diff --git a/Lang/jq/Problem-of-Apollonius b/Lang/jq/Problem-of-Apollonius deleted file mode 120000 index 0a953668a7..0000000000 --- a/Lang/jq/Problem-of-Apollonius +++ /dev/null @@ -1 +0,0 @@ -../../Task/Problem-of-Apollonius/jq \ No newline at end of file diff --git a/Lang/jq/Program-termination b/Lang/jq/Program-termination deleted file mode 120000 index b10fef1a76..0000000000 --- a/Lang/jq/Program-termination +++ /dev/null @@ -1 +0,0 @@ -../../Task/Program-termination/jq \ No newline at end of file diff --git a/Lang/jq/Pythagorean-triples b/Lang/jq/Pythagorean-triples deleted file mode 120000 index f866b4dce7..0000000000 --- a/Lang/jq/Pythagorean-triples +++ /dev/null @@ -1 +0,0 @@ -../../Task/Pythagorean-triples/jq \ No newline at end of file diff --git a/Lang/jq/Quaternion-type b/Lang/jq/Quaternion-type deleted file mode 120000 index 2dc96e6e0b..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/Queue-Definition b/Lang/jq/Queue-Definition deleted file mode 120000 index bce75a40b9..0000000000 --- a/Lang/jq/Queue-Definition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Queue-Definition/jq \ No newline at end of file diff --git a/Lang/jq/Quickselect-algorithm b/Lang/jq/Quickselect-algorithm deleted file mode 120000 index e597b8ada9..0000000000 --- a/Lang/jq/Quickselect-algorithm +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quickselect-algorithm/jq \ No newline at end of file diff --git a/Lang/jq/README b/Lang/jq/README deleted file mode 100644 index 50c6497a74..0000000000 --- a/Lang/jq/README +++ /dev/null @@ -1 +0,0 @@ -Data source: http://rosettacode.org/wiki/Category:jq diff --git a/Lang/jq/Random-numbers b/Lang/jq/Random-numbers deleted file mode 120000 index f68fa5ce2f..0000000000 --- a/Lang/jq/Random-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Random-numbers/jq \ No newline at end of file diff --git a/Lang/jq/Range-expansion b/Lang/jq/Range-expansion deleted file mode 120000 index e2f4bc5b32..0000000000 --- a/Lang/jq/Range-expansion +++ /dev/null @@ -1 +0,0 @@ -../../Task/Range-expansion/jq \ No newline at end of file diff --git a/Lang/jq/Range-extraction b/Lang/jq/Range-extraction deleted file mode 120000 index 1c985adf8b..0000000000 --- a/Lang/jq/Range-extraction +++ /dev/null @@ -1 +0,0 @@ -../../Task/Range-extraction/jq \ No newline at end of file diff --git a/Lang/jq/Ranking-methods b/Lang/jq/Ranking-methods deleted file mode 120000 index c2d2760578..0000000000 --- a/Lang/jq/Ranking-methods +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ranking-methods/jq \ No newline at end of file diff --git a/Lang/jq/Read-a-file-line-by-line b/Lang/jq/Read-a-file-line-by-line deleted file mode 120000 index 7cbe91eb10..0000000000 --- a/Lang/jq/Read-a-file-line-by-line +++ /dev/null @@ -1 +0,0 @@ -../../Task/Read-a-file-line-by-line/jq \ No newline at end of file diff --git a/Lang/jq/Read-a-specific-line-from-a-file b/Lang/jq/Read-a-specific-line-from-a-file deleted file mode 120000 index 9e11c6474b..0000000000 --- a/Lang/jq/Read-a-specific-line-from-a-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Read-a-specific-line-from-a-file/jq \ No newline at end of file diff --git a/Lang/jq/Read-entire-file b/Lang/jq/Read-entire-file deleted file mode 120000 index 2506b1c8d7..0000000000 --- a/Lang/jq/Read-entire-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Read-entire-file/jq \ No newline at end of file diff --git a/Lang/jq/Real-constants-and-functions b/Lang/jq/Real-constants-and-functions deleted file mode 120000 index e234ea60b1..0000000000 --- a/Lang/jq/Real-constants-and-functions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Real-constants-and-functions/jq \ No newline at end of file diff --git a/Lang/jq/Regular-expressions b/Lang/jq/Regular-expressions deleted file mode 120000 index 47b2212198..0000000000 --- a/Lang/jq/Regular-expressions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Regular-expressions/jq \ No newline at end of file diff --git a/Lang/jq/Remove-duplicate-elements b/Lang/jq/Remove-duplicate-elements deleted file mode 120000 index 43c62d7c60..0000000000 --- a/Lang/jq/Remove-duplicate-elements +++ /dev/null @@ -1 +0,0 @@ -../../Task/Remove-duplicate-elements/jq \ No newline at end of file diff --git a/Lang/jq/Remove-lines-from-a-file b/Lang/jq/Remove-lines-from-a-file deleted file mode 120000 index c1086e79d3..0000000000 --- a/Lang/jq/Remove-lines-from-a-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Remove-lines-from-a-file/jq \ No newline at end of file diff --git a/Lang/jq/Rep-string b/Lang/jq/Rep-string deleted file mode 120000 index da208ba1a3..0000000000 --- a/Lang/jq/Rep-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rep-string/jq \ No newline at end of file diff --git a/Lang/jq/Repeat-a-string b/Lang/jq/Repeat-a-string deleted file mode 120000 index c89321c0c8..0000000000 --- a/Lang/jq/Repeat-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Repeat-a-string/jq \ No newline at end of file diff --git a/Lang/jq/Return-multiple-values b/Lang/jq/Return-multiple-values deleted file mode 120000 index de2dbd8f1d..0000000000 --- a/Lang/jq/Return-multiple-values +++ /dev/null @@ -1 +0,0 @@ -../../Task/Return-multiple-values/jq \ No newline at end of file diff --git a/Lang/jq/Reverse-a-string b/Lang/jq/Reverse-a-string deleted file mode 120000 index e1c723ce82..0000000000 --- a/Lang/jq/Reverse-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Reverse-a-string/jq \ No newline at end of file diff --git a/Lang/jq/Reverse-words-in-a-string b/Lang/jq/Reverse-words-in-a-string deleted file mode 120000 index 5998372f95..0000000000 --- a/Lang/jq/Reverse-words-in-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Reverse-words-in-a-string/jq \ No newline at end of file diff --git a/Lang/jq/Roman-numerals-Decode b/Lang/jq/Roman-numerals-Decode deleted file mode 120000 index 7cea44a0a6..0000000000 --- a/Lang/jq/Roman-numerals-Decode +++ /dev/null @@ -1 +0,0 @@ -../../Task/Roman-numerals-Decode/jq \ No newline at end of file diff --git a/Lang/jq/Roots-of-a-function b/Lang/jq/Roots-of-a-function deleted file mode 120000 index 44c0ca6870..0000000000 --- a/Lang/jq/Roots-of-a-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Roots-of-a-function/jq \ No newline at end of file diff --git a/Lang/jq/Roots-of-a-quadratic-function b/Lang/jq/Roots-of-a-quadratic-function deleted file mode 120000 index 7973a6b551..0000000000 --- a/Lang/jq/Roots-of-a-quadratic-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Roots-of-a-quadratic-function/jq \ No newline at end of file diff --git a/Lang/jq/Roots-of-unity b/Lang/jq/Roots-of-unity deleted file mode 120000 index 6e0084fb35..0000000000 --- a/Lang/jq/Roots-of-unity +++ /dev/null @@ -1 +0,0 @@ -../../Task/Roots-of-unity/jq \ No newline at end of file diff --git a/Lang/jq/Rot-13 b/Lang/jq/Rot-13 deleted file mode 120000 index 5d55e3e6f7..0000000000 --- a/Lang/jq/Rot-13 +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rot-13/jq \ No newline at end of file diff --git a/Lang/jq/Run-length-encoding b/Lang/jq/Run-length-encoding deleted file mode 120000 index a1e01d72b8..0000000000 --- a/Lang/jq/Run-length-encoding +++ /dev/null @@ -1 +0,0 @@ -../../Task/Run-length-encoding/jq \ No newline at end of file diff --git a/Lang/jq/Runge-Kutta-method b/Lang/jq/Runge-Kutta-method deleted file mode 120000 index a3f07a6b01..0000000000 --- a/Lang/jq/Runge-Kutta-method +++ /dev/null @@ -1 +0,0 @@ -../../Task/Runge-Kutta-method/jq \ No newline at end of file diff --git a/Lang/jq/SEDOLs b/Lang/jq/SEDOLs deleted file mode 120000 index ac26655cb3..0000000000 --- a/Lang/jq/SEDOLs +++ /dev/null @@ -1 +0,0 @@ -../../Task/SEDOLs/jq \ No newline at end of file diff --git a/Lang/jq/Same-Fringe b/Lang/jq/Same-Fringe deleted file mode 120000 index 62e5474996..0000000000 --- a/Lang/jq/Same-Fringe +++ /dev/null @@ -1 +0,0 @@ -../../Task/Same-Fringe/jq \ No newline at end of file diff --git a/Lang/jq/Scope-Function-names-and-labels b/Lang/jq/Scope-Function-names-and-labels deleted file mode 120000 index 021c5767a4..0000000000 --- a/Lang/jq/Scope-Function-names-and-labels +++ /dev/null @@ -1 +0,0 @@ -../../Task/Scope-Function-names-and-labels/jq \ No newline at end of file diff --git a/Lang/jq/Search-a-list b/Lang/jq/Search-a-list deleted file mode 120000 index a27836f5cf..0000000000 --- a/Lang/jq/Search-a-list +++ /dev/null @@ -1 +0,0 @@ -../../Task/Search-a-list/jq \ No newline at end of file diff --git a/Lang/jq/Self-describing-numbers b/Lang/jq/Self-describing-numbers deleted file mode 120000 index 129e1a77f5..0000000000 --- a/Lang/jq/Self-describing-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Self-describing-numbers/jq \ No newline at end of file diff --git a/Lang/jq/Self-referential-sequence b/Lang/jq/Self-referential-sequence deleted file mode 120000 index 124129a36b..0000000000 --- a/Lang/jq/Self-referential-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Self-referential-sequence/jq \ No newline at end of file diff --git a/Lang/jq/Semordnilap b/Lang/jq/Semordnilap deleted file mode 120000 index 2993c47e97..0000000000 --- a/Lang/jq/Semordnilap +++ /dev/null @@ -1 +0,0 @@ -../../Task/Semordnilap/jq \ No newline at end of file diff --git a/Lang/jq/Sequence-of-non-squares b/Lang/jq/Sequence-of-non-squares deleted file mode 120000 index a0d478b1a4..0000000000 --- a/Lang/jq/Sequence-of-non-squares +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sequence-of-non-squares/jq \ No newline at end of file diff --git a/Lang/jq/Sequence-of-primes-by-Trial-Division b/Lang/jq/Sequence-of-primes-by-Trial-Division deleted file mode 120000 index e0bdc3d074..0000000000 --- a/Lang/jq/Sequence-of-primes-by-Trial-Division +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sequence-of-primes-by-Trial-Division/jq \ No newline at end of file diff --git a/Lang/jq/Set b/Lang/jq/Set deleted file mode 120000 index e23e4f0705..0000000000 --- a/Lang/jq/Set +++ /dev/null @@ -1 +0,0 @@ -../../Task/Set/jq \ No newline at end of file diff --git a/Lang/jq/Set-consolidation b/Lang/jq/Set-consolidation deleted file mode 120000 index 953e3cb130..0000000000 --- a/Lang/jq/Set-consolidation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Set-consolidation/jq \ No newline at end of file diff --git a/Lang/jq/Shell-one-liner b/Lang/jq/Shell-one-liner deleted file mode 120000 index 7389e9117d..0000000000 --- a/Lang/jq/Shell-one-liner +++ /dev/null @@ -1 +0,0 @@ -../../Task/Shell-one-liner/jq \ No newline at end of file diff --git a/Lang/jq/Short-circuit-evaluation b/Lang/jq/Short-circuit-evaluation deleted file mode 120000 index d182ba1ef4..0000000000 --- a/Lang/jq/Short-circuit-evaluation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Short-circuit-evaluation/jq \ No newline at end of file diff --git a/Lang/jq/Show-the-epoch b/Lang/jq/Show-the-epoch deleted file mode 120000 index 5658c2c7dd..0000000000 --- a/Lang/jq/Show-the-epoch +++ /dev/null @@ -1 +0,0 @@ -../../Task/Show-the-epoch/jq \ No newline at end of file diff --git a/Lang/jq/Sierpinski-carpet b/Lang/jq/Sierpinski-carpet deleted file mode 120000 index 4ae292ba8f..0000000000 --- a/Lang/jq/Sierpinski-carpet +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sierpinski-carpet/jq \ No newline at end of file diff --git a/Lang/jq/Sieve-of-Eratosthenes b/Lang/jq/Sieve-of-Eratosthenes deleted file mode 120000 index 743ce5c4c0..0000000000 --- a/Lang/jq/Sieve-of-Eratosthenes +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sieve-of-Eratosthenes/jq \ No newline at end of file diff --git a/Lang/jq/Singly-linked-list-Traversal b/Lang/jq/Singly-linked-list-Traversal deleted file mode 120000 index 52a1fbba76..0000000000 --- a/Lang/jq/Singly-linked-list-Traversal +++ /dev/null @@ -1 +0,0 @@ -../../Task/Singly-linked-list-Traversal/jq \ No newline at end of file diff --git a/Lang/jq/Solve-the-no-connection-puzzle b/Lang/jq/Solve-the-no-connection-puzzle deleted file mode 120000 index 035b893b36..0000000000 --- a/Lang/jq/Solve-the-no-connection-puzzle +++ /dev/null @@ -1 +0,0 @@ -../../Task/Solve-the-no-connection-puzzle/jq \ No newline at end of file diff --git a/Lang/jq/Sort-an-array-of-composite-structures b/Lang/jq/Sort-an-array-of-composite-structures deleted file mode 120000 index 0d743b8a3c..0000000000 --- a/Lang/jq/Sort-an-array-of-composite-structures +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sort-an-array-of-composite-structures/jq \ No newline at end of file diff --git a/Lang/jq/Sort-an-integer-array b/Lang/jq/Sort-an-integer-array deleted file mode 120000 index 7c88949063..0000000000 --- a/Lang/jq/Sort-an-integer-array +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sort-an-integer-array/jq \ No newline at end of file diff --git a/Lang/jq/Sort-disjoint-sublist b/Lang/jq/Sort-disjoint-sublist deleted file mode 120000 index 10a763fd6c..0000000000 --- a/Lang/jq/Sort-disjoint-sublist +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sort-disjoint-sublist/jq \ No newline at end of file diff --git a/Lang/jq/Sort-using-a-custom-comparator b/Lang/jq/Sort-using-a-custom-comparator deleted file mode 120000 index bc1818ca5e..0000000000 --- a/Lang/jq/Sort-using-a-custom-comparator +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sort-using-a-custom-comparator/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Bead-sort b/Lang/jq/Sorting-algorithms-Bead-sort deleted file mode 120000 index d400bd9a6e..0000000000 --- a/Lang/jq/Sorting-algorithms-Bead-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Bead-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Bubble-sort b/Lang/jq/Sorting-algorithms-Bubble-sort deleted file mode 120000 index 292f1c2e61..0000000000 --- a/Lang/jq/Sorting-algorithms-Bubble-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Bubble-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Cocktail-sort b/Lang/jq/Sorting-algorithms-Cocktail-sort deleted file mode 120000 index da4a852235..0000000000 --- a/Lang/jq/Sorting-algorithms-Cocktail-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Cocktail-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Comb-sort b/Lang/jq/Sorting-algorithms-Comb-sort deleted file mode 120000 index ad11942ee0..0000000000 --- a/Lang/jq/Sorting-algorithms-Comb-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Comb-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Counting-sort b/Lang/jq/Sorting-algorithms-Counting-sort deleted file mode 120000 index f3c096680f..0000000000 --- a/Lang/jq/Sorting-algorithms-Counting-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Counting-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Gnome-sort b/Lang/jq/Sorting-algorithms-Gnome-sort deleted file mode 120000 index 6ace37f6c8..0000000000 --- a/Lang/jq/Sorting-algorithms-Gnome-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Gnome-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Insertion-sort b/Lang/jq/Sorting-algorithms-Insertion-sort deleted file mode 120000 index 1bf0689053..0000000000 --- a/Lang/jq/Sorting-algorithms-Insertion-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Insertion-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Merge-sort b/Lang/jq/Sorting-algorithms-Merge-sort deleted file mode 120000 index b79f579b4f..0000000000 --- a/Lang/jq/Sorting-algorithms-Merge-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Merge-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Pancake-sort b/Lang/jq/Sorting-algorithms-Pancake-sort deleted file mode 120000 index 8834489380..0000000000 --- a/Lang/jq/Sorting-algorithms-Pancake-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Pancake-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Permutation-sort b/Lang/jq/Sorting-algorithms-Permutation-sort deleted file mode 120000 index 208aeeac7b..0000000000 --- a/Lang/jq/Sorting-algorithms-Permutation-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Permutation-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Quicksort b/Lang/jq/Sorting-algorithms-Quicksort deleted file mode 120000 index ce8b37cc43..0000000000 --- a/Lang/jq/Sorting-algorithms-Quicksort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Quicksort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Radix-sort b/Lang/jq/Sorting-algorithms-Radix-sort deleted file mode 120000 index 824eb9aafd..0000000000 --- a/Lang/jq/Sorting-algorithms-Radix-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Radix-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Selection-sort b/Lang/jq/Sorting-algorithms-Selection-sort deleted file mode 120000 index 9f2e1fd6c3..0000000000 --- a/Lang/jq/Sorting-algorithms-Selection-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Selection-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Shell-sort b/Lang/jq/Sorting-algorithms-Shell-sort deleted file mode 120000 index 4cc63e4524..0000000000 --- a/Lang/jq/Sorting-algorithms-Shell-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Shell-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Sleep-sort b/Lang/jq/Sorting-algorithms-Sleep-sort deleted file mode 120000 index 78ef28618e..0000000000 --- a/Lang/jq/Sorting-algorithms-Sleep-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Sleep-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Stooge-sort b/Lang/jq/Sorting-algorithms-Stooge-sort deleted file mode 120000 index cdac9a092f..0000000000 --- a/Lang/jq/Sorting-algorithms-Stooge-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Stooge-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sorting-algorithms-Strand-sort b/Lang/jq/Sorting-algorithms-Strand-sort deleted file mode 120000 index 6698f286b4..0000000000 --- a/Lang/jq/Sorting-algorithms-Strand-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Strand-sort/jq \ No newline at end of file diff --git a/Lang/jq/Sparkline-in-unicode b/Lang/jq/Sparkline-in-unicode deleted file mode 120000 index 95b041634f..0000000000 --- a/Lang/jq/Sparkline-in-unicode +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sparkline-in-unicode/jq \ No newline at end of file diff --git a/Lang/jq/Special-characters b/Lang/jq/Special-characters deleted file mode 120000 index ebae3996af..0000000000 --- a/Lang/jq/Special-characters +++ /dev/null @@ -1 +0,0 @@ -../../Task/Special-characters/jq \ No newline at end of file diff --git a/Lang/jq/Special-variables b/Lang/jq/Special-variables deleted file mode 120000 index 069535d958..0000000000 --- a/Lang/jq/Special-variables +++ /dev/null @@ -1 +0,0 @@ -../../Task/Special-variables/jq \ No newline at end of file diff --git a/Lang/jq/Spiral-matrix b/Lang/jq/Spiral-matrix deleted file mode 120000 index a22ff50613..0000000000 --- a/Lang/jq/Spiral-matrix +++ /dev/null @@ -1 +0,0 @@ -../../Task/Spiral-matrix/jq \ No newline at end of file diff --git a/Lang/jq/Stair-climbing-puzzle b/Lang/jq/Stair-climbing-puzzle deleted file mode 120000 index 742761de1f..0000000000 --- a/Lang/jq/Stair-climbing-puzzle +++ /dev/null @@ -1 +0,0 @@ -../../Task/Stair-climbing-puzzle/jq \ No newline at end of file diff --git a/Lang/jq/State-name-puzzle b/Lang/jq/State-name-puzzle deleted file mode 120000 index 4883f2bdf8..0000000000 --- a/Lang/jq/State-name-puzzle +++ /dev/null @@ -1 +0,0 @@ -../../Task/State-name-puzzle/jq \ No newline at end of file diff --git a/Lang/jq/Stem-and-leaf-plot b/Lang/jq/Stem-and-leaf-plot deleted file mode 120000 index c080f9f998..0000000000 --- a/Lang/jq/Stem-and-leaf-plot +++ /dev/null @@ -1 +0,0 @@ -../../Task/Stem-and-leaf-plot/jq \ No newline at end of file diff --git a/Lang/jq/Stern-Brocot-sequence b/Lang/jq/Stern-Brocot-sequence deleted file mode 120000 index 5f7cfd7283..0000000000 --- a/Lang/jq/Stern-Brocot-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Stern-Brocot-sequence/jq \ No newline at end of file diff --git a/Lang/jq/String-append b/Lang/jq/String-append deleted file mode 120000 index 582a64a5bb..0000000000 --- a/Lang/jq/String-append +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-append/jq \ No newline at end of file diff --git a/Lang/jq/String-case b/Lang/jq/String-case deleted file mode 120000 index 0cd6afcfa3..0000000000 --- a/Lang/jq/String-case +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-case/jq \ No newline at end of file diff --git a/Lang/jq/String-comparison b/Lang/jq/String-comparison deleted file mode 120000 index 6a1dd5e26a..0000000000 --- a/Lang/jq/String-comparison +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-comparison/jq \ No newline at end of file diff --git a/Lang/jq/String-concatenation b/Lang/jq/String-concatenation deleted file mode 120000 index fa23f5442d..0000000000 --- a/Lang/jq/String-concatenation +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-concatenation/jq \ No newline at end of file diff --git a/Lang/jq/String-interpolation--included- b/Lang/jq/String-interpolation--included- deleted file mode 120000 index a3a6fd6c34..0000000000 --- a/Lang/jq/String-interpolation--included- +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-interpolation--included-/jq \ No newline at end of file diff --git a/Lang/jq/String-length b/Lang/jq/String-length deleted file mode 120000 index 4479772647..0000000000 --- a/Lang/jq/String-length +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-length/jq \ No newline at end of file diff --git a/Lang/jq/String-matching b/Lang/jq/String-matching deleted file mode 120000 index 246ce28073..0000000000 --- a/Lang/jq/String-matching +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-matching/jq \ No newline at end of file diff --git a/Lang/jq/String-prepend b/Lang/jq/String-prepend deleted file mode 120000 index edf9e7a1b6..0000000000 --- a/Lang/jq/String-prepend +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-prepend/jq \ No newline at end of file diff --git a/Lang/jq/Strip-a-set-of-characters-from-a-string b/Lang/jq/Strip-a-set-of-characters-from-a-string deleted file mode 120000 index c8ebb83f38..0000000000 --- a/Lang/jq/Strip-a-set-of-characters-from-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Strip-a-set-of-characters-from-a-string/jq \ No newline at end of file diff --git a/Lang/jq/Strip-block-comments b/Lang/jq/Strip-block-comments deleted file mode 120000 index 683d8e8bc9..0000000000 --- a/Lang/jq/Strip-block-comments +++ /dev/null @@ -1 +0,0 @@ -../../Task/Strip-block-comments/jq \ No newline at end of file diff --git a/Lang/jq/Strip-comments-from-a-string b/Lang/jq/Strip-comments-from-a-string deleted file mode 120000 index e401e6e704..0000000000 --- a/Lang/jq/Strip-comments-from-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Strip-comments-from-a-string/jq \ No newline at end of file diff --git a/Lang/jq/Strip-control-codes-and-extended-characters-from-a-string b/Lang/jq/Strip-control-codes-and-extended-characters-from-a-string deleted file mode 120000 index d641a32f13..0000000000 --- a/Lang/jq/Strip-control-codes-and-extended-characters-from-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Strip-control-codes-and-extended-characters-from-a-string/jq \ No newline at end of file diff --git a/Lang/jq/Strip-whitespace-from-a-string-Top-and-tail b/Lang/jq/Strip-whitespace-from-a-string-Top-and-tail deleted file mode 120000 index 41a5799b1a..0000000000 --- a/Lang/jq/Strip-whitespace-from-a-string-Top-and-tail +++ /dev/null @@ -1 +0,0 @@ -../../Task/Strip-whitespace-from-a-string-Top-and-tail/jq \ No newline at end of file diff --git a/Lang/jq/Substring b/Lang/jq/Substring deleted file mode 120000 index 28fb6d4429..0000000000 --- a/Lang/jq/Substring +++ /dev/null @@ -1 +0,0 @@ -../../Task/Substring/jq \ No newline at end of file diff --git a/Lang/jq/Substring-Top-and-tail b/Lang/jq/Substring-Top-and-tail deleted file mode 120000 index 0b8db46deb..0000000000 --- a/Lang/jq/Substring-Top-and-tail +++ /dev/null @@ -1 +0,0 @@ -../../Task/Substring-Top-and-tail/jq \ No newline at end of file diff --git a/Lang/jq/Sum-and-product-of-an-array b/Lang/jq/Sum-and-product-of-an-array deleted file mode 120000 index 0e0f713900..0000000000 --- a/Lang/jq/Sum-and-product-of-an-array +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sum-and-product-of-an-array/jq \ No newline at end of file diff --git a/Lang/jq/Sum-digits-of-an-integer b/Lang/jq/Sum-digits-of-an-integer deleted file mode 120000 index 10ac4f4a1d..0000000000 --- a/Lang/jq/Sum-digits-of-an-integer +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sum-digits-of-an-integer/jq \ No newline at end of file diff --git a/Lang/jq/Sum-multiples-of-3-and-5 b/Lang/jq/Sum-multiples-of-3-and-5 deleted file mode 120000 index b0aaec49b9..0000000000 --- a/Lang/jq/Sum-multiples-of-3-and-5 +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sum-multiples-of-3-and-5/jq \ No newline at end of file diff --git a/Lang/jq/Sum-of-a-series b/Lang/jq/Sum-of-a-series deleted file mode 120000 index a20ef46ff7..0000000000 --- a/Lang/jq/Sum-of-a-series +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sum-of-a-series/jq \ No newline at end of file diff --git a/Lang/jq/Sum-of-squares b/Lang/jq/Sum-of-squares deleted file mode 120000 index a9b2ebd898..0000000000 --- a/Lang/jq/Sum-of-squares +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sum-of-squares/jq \ No newline at end of file diff --git a/Lang/jq/Symmetric-difference b/Lang/jq/Symmetric-difference deleted file mode 120000 index 606f196876..0000000000 --- a/Lang/jq/Symmetric-difference +++ /dev/null @@ -1 +0,0 @@ -../../Task/Symmetric-difference/jq \ No newline at end of file diff --git a/Lang/jq/System-time b/Lang/jq/System-time deleted file mode 120000 index f3877f16a2..0000000000 --- a/Lang/jq/System-time +++ /dev/null @@ -1 +0,0 @@ -../../Task/System-time/jq \ No newline at end of file diff --git a/Lang/jq/Temperature-conversion b/Lang/jq/Temperature-conversion deleted file mode 120000 index 269edf9aa9..0000000000 --- a/Lang/jq/Temperature-conversion +++ /dev/null @@ -1 +0,0 @@ -../../Task/Temperature-conversion/jq \ No newline at end of file diff --git a/Lang/jq/Terminal-control-Clear-the-screen b/Lang/jq/Terminal-control-Clear-the-screen deleted file mode 120000 index ebd0f09b48..0000000000 --- a/Lang/jq/Terminal-control-Clear-the-screen +++ /dev/null @@ -1 +0,0 @@ -../../Task/Terminal-control-Clear-the-screen/jq \ No newline at end of file diff --git a/Lang/jq/Terminal-control-Unicode-output b/Lang/jq/Terminal-control-Unicode-output deleted file mode 120000 index 86f2fa2c65..0000000000 --- a/Lang/jq/Terminal-control-Unicode-output +++ /dev/null @@ -1 +0,0 @@ -../../Task/Terminal-control-Unicode-output/jq \ No newline at end of file diff --git a/Lang/jq/Ternary-logic b/Lang/jq/Ternary-logic deleted file mode 120000 index 4c48247f66..0000000000 --- a/Lang/jq/Ternary-logic +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ternary-logic/jq \ No newline at end of file diff --git a/Lang/jq/Test-a-function b/Lang/jq/Test-a-function deleted file mode 120000 index f8b7aafb81..0000000000 --- a/Lang/jq/Test-a-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Test-a-function/jq \ No newline at end of file diff --git a/Lang/jq/Text-processing-1 b/Lang/jq/Text-processing-1 deleted file mode 120000 index d3f7c5d91a..0000000000 --- a/Lang/jq/Text-processing-1 +++ /dev/null @@ -1 +0,0 @@ -../../Task/Text-processing-1/jq \ No newline at end of file diff --git a/Lang/jq/Text-processing-2 b/Lang/jq/Text-processing-2 deleted file mode 120000 index e2fc79d8f2..0000000000 --- a/Lang/jq/Text-processing-2 +++ /dev/null @@ -1 +0,0 @@ -../../Task/Text-processing-2/jq \ No newline at end of file diff --git a/Lang/jq/Text-processing-Max-licenses-in-use b/Lang/jq/Text-processing-Max-licenses-in-use deleted file mode 120000 index 96c9e5b2cf..0000000000 --- a/Lang/jq/Text-processing-Max-licenses-in-use +++ /dev/null @@ -1 +0,0 @@ -../../Task/Text-processing-Max-licenses-in-use/jq \ No newline at end of file diff --git a/Lang/jq/Textonyms b/Lang/jq/Textonyms deleted file mode 120000 index 6d9acf6952..0000000000 --- a/Lang/jq/Textonyms +++ /dev/null @@ -1 +0,0 @@ -../../Task/Textonyms/jq \ No newline at end of file diff --git a/Lang/jq/Tokenize-a-string b/Lang/jq/Tokenize-a-string deleted file mode 120000 index 119878379b..0000000000 --- a/Lang/jq/Tokenize-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Tokenize-a-string/jq \ No newline at end of file diff --git a/Lang/jq/Top-rank-per-group b/Lang/jq/Top-rank-per-group deleted file mode 120000 index ec19fec1c7..0000000000 --- a/Lang/jq/Top-rank-per-group +++ /dev/null @@ -1 +0,0 @@ -../../Task/Top-rank-per-group/jq \ No newline at end of file diff --git a/Lang/jq/Topological-sort b/Lang/jq/Topological-sort deleted file mode 120000 index f9a70e2dbc..0000000000 --- a/Lang/jq/Topological-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Topological-sort/jq \ No newline at end of file diff --git a/Lang/jq/Topswops b/Lang/jq/Topswops deleted file mode 120000 index 5150fd859b..0000000000 --- a/Lang/jq/Topswops +++ /dev/null @@ -1 +0,0 @@ -../../Task/Topswops/jq \ No newline at end of file diff --git a/Lang/jq/Towers-of-Hanoi b/Lang/jq/Towers-of-Hanoi deleted file mode 120000 index 1e867f3f65..0000000000 --- a/Lang/jq/Towers-of-Hanoi +++ /dev/null @@ -1 +0,0 @@ -../../Task/Towers-of-Hanoi/jq \ No newline at end of file diff --git a/Lang/jq/Trabb-Pardo-Knuth-algorithm b/Lang/jq/Trabb-Pardo-Knuth-algorithm deleted file mode 120000 index c5aa935547..0000000000 --- a/Lang/jq/Trabb-Pardo-Knuth-algorithm +++ /dev/null @@ -1 +0,0 @@ -../../Task/Trabb-Pardo-Knuth-algorithm/jq \ No newline at end of file diff --git a/Lang/jq/Tree-traversal b/Lang/jq/Tree-traversal deleted file mode 120000 index c59a763bf5..0000000000 --- a/Lang/jq/Tree-traversal +++ /dev/null @@ -1 +0,0 @@ -../../Task/Tree-traversal/jq \ No newline at end of file diff --git a/Lang/jq/Trigonometric-functions b/Lang/jq/Trigonometric-functions deleted file mode 120000 index c1de7e3f6e..0000000000 --- a/Lang/jq/Trigonometric-functions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Trigonometric-functions/jq \ No newline at end of file diff --git a/Lang/jq/Twelve-statements b/Lang/jq/Twelve-statements deleted file mode 120000 index 00e5b95a35..0000000000 --- a/Lang/jq/Twelve-statements +++ /dev/null @@ -1 +0,0 @@ -../../Task/Twelve-statements/jq \ No newline at end of file diff --git a/Lang/jq/URL-decoding b/Lang/jq/URL-decoding deleted file mode 120000 index c131226015..0000000000 --- a/Lang/jq/URL-decoding +++ /dev/null @@ -1 +0,0 @@ -../../Task/URL-decoding/jq \ No newline at end of file diff --git a/Lang/jq/URL-encoding b/Lang/jq/URL-encoding deleted file mode 120000 index ebdbac90c2..0000000000 --- a/Lang/jq/URL-encoding +++ /dev/null @@ -1 +0,0 @@ -../../Task/URL-encoding/jq \ No newline at end of file diff --git a/Lang/jq/Undefined-values b/Lang/jq/Undefined-values deleted file mode 120000 index bd98db8a00..0000000000 --- a/Lang/jq/Undefined-values +++ /dev/null @@ -1 +0,0 @@ -../../Task/Undefined-values/jq \ No newline at end of file diff --git a/Lang/jq/User-input-Text b/Lang/jq/User-input-Text deleted file mode 120000 index 0831b549fc..0000000000 --- a/Lang/jq/User-input-Text +++ /dev/null @@ -1 +0,0 @@ -../../Task/User-input-Text/jq \ No newline at end of file diff --git a/Lang/jq/Van-der-Corput-sequence b/Lang/jq/Van-der-Corput-sequence deleted file mode 120000 index 11908cf2c6..0000000000 --- a/Lang/jq/Van-der-Corput-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Van-der-Corput-sequence/jq \ No newline at end of file diff --git a/Lang/jq/Variables b/Lang/jq/Variables deleted file mode 120000 index ee4a7e5976..0000000000 --- a/Lang/jq/Variables +++ /dev/null @@ -1 +0,0 @@ -../../Task/Variables/jq \ No newline at end of file diff --git a/Lang/jq/Variadic-function b/Lang/jq/Variadic-function deleted file mode 120000 index 74c9a0051c..0000000000 --- a/Lang/jq/Variadic-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Variadic-function/jq \ No newline at end of file diff --git a/Lang/jq/Vector-products b/Lang/jq/Vector-products deleted file mode 120000 index 1489030b13..0000000000 --- a/Lang/jq/Vector-products +++ /dev/null @@ -1 +0,0 @@ -../../Task/Vector-products/jq \ No newline at end of file diff --git a/Lang/jq/Web-scraping b/Lang/jq/Web-scraping deleted file mode 120000 index a5ee6db52b..0000000000 --- a/Lang/jq/Web-scraping +++ /dev/null @@ -1 +0,0 @@ -../../Task/Web-scraping/jq \ No newline at end of file diff --git a/Lang/jq/Wireworld b/Lang/jq/Wireworld deleted file mode 120000 index 61dff942e6..0000000000 --- a/Lang/jq/Wireworld +++ /dev/null @@ -1 +0,0 @@ -../../Task/Wireworld/jq \ No newline at end of file diff --git a/Lang/jq/Word-wrap b/Lang/jq/Word-wrap deleted file mode 120000 index 0cec64a4cb..0000000000 --- a/Lang/jq/Word-wrap +++ /dev/null @@ -1 +0,0 @@ -../../Task/Word-wrap/jq \ No newline at end of file diff --git a/Lang/jq/Write-float-arrays-to-a-text-file b/Lang/jq/Write-float-arrays-to-a-text-file deleted file mode 120000 index 3bf983eaa3..0000000000 --- a/Lang/jq/Write-float-arrays-to-a-text-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Write-float-arrays-to-a-text-file/jq \ No newline at end of file diff --git a/Lang/jq/Yin-and-yang b/Lang/jq/Yin-and-yang deleted file mode 120000 index 44c616aab4..0000000000 --- a/Lang/jq/Yin-and-yang +++ /dev/null @@ -1 +0,0 @@ -../../Task/Yin-and-yang/jq \ No newline at end of file diff --git a/Lang/jq/Zebra-puzzle b/Lang/jq/Zebra-puzzle deleted file mode 120000 index 337008ab04..0000000000 --- a/Lang/jq/Zebra-puzzle +++ /dev/null @@ -1 +0,0 @@ -../../Task/Zebra-puzzle/jq \ No newline at end of file diff --git a/Lang/jq/Zeckendorf-number-representation b/Lang/jq/Zeckendorf-number-representation deleted file mode 120000 index 2b9524c79b..0000000000 --- a/Lang/jq/Zeckendorf-number-representation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Zeckendorf-number-representation/jq \ No newline at end of file diff --git a/Lang/jq/Zero-to-the-zero-power b/Lang/jq/Zero-to-the-zero-power deleted file mode 120000 index 643a7470db..0000000000 --- a/Lang/jq/Zero-to-the-zero-power +++ /dev/null @@ -1 +0,0 @@ -../../Task/Zero-to-the-zero-power/jq \ No newline at end of file diff --git a/Lang/jq/Zig-zag-matrix b/Lang/jq/Zig-zag-matrix deleted file mode 120000 index 72f067914b..0000000000 --- a/Lang/jq/Zig-zag-matrix +++ /dev/null @@ -1 +0,0 @@ -../../Task/Zig-zag-matrix/jq \ No newline at end of file diff --git a/Meta/Lang.yaml b/Meta/Lang.yaml index abbb9245a1..0a11c8f03e 100644 --- a/Meta/Lang.yaml +++ b/Meta/Lang.yaml @@ -99,6 +99,11 @@ ALGOL W: name: ALGOL W path: ALGOL-W url: ALGOL_W +ALGOL-M: + ext: algol-m + name: ALGOL-M + path: ALGOL-M + url: ALGOL-M AMPL: ext: ampl name: AMPL @@ -279,6 +284,11 @@ Assembly: name: Assembly path: Assembly url: Assembly +Astro: + ext: astro + name: Astro + path: Astro + url: Astro Asymptote: ext: asymptote name: Asymptote @@ -349,6 +359,11 @@ BML: name: BML path: BML url: BML +BaCon: + ext: bacon + name: BaCon + path: BaCon + url: BaCon Babel: ext: pb name: Babel @@ -524,6 +539,11 @@ Cat: name: Cat path: Cat url: Cat +Category SETL4: + ext: category + name: Category SETL4 + path: Category-SETL4 + url: Category_SETL4 Cduce: ext: cduce name: Cduce @@ -620,6 +640,11 @@ Comal: name: Comal path: Comal url: Comal +Comefrom0x10: + ext: comefrom0x10 + name: Comefrom0x10 + path: Comefrom0x10 + url: Comefrom0x10 Commodore BASIC: ext: commodore name: Commodore BASIC @@ -680,16 +705,31 @@ DIV Games Studio: name: DIV Games Studio path: DIV-Games-Studio url: DIV_Games_Studio +DM: + ext: dm + name: DM + path: DM + url: DM DMS: ext: dms name: DMS path: DMS url: DMS +DUP: + ext: dup + name: DUP + path: DUP + url: DUP DWScript: ext: dw name: DWScript path: DWScript url: DWScript +Dafny: + ext: dafny + name: Dafny + path: Dafny + url: Dafny Dao: ext: dao name: Dao @@ -1120,6 +1160,11 @@ Gambas: name: Gambas path: Gambas url: Gambas +Gastona: + ext: gastona + name: Gastona + path: Gastona + url: Gastona Gdl: ext: gdl name: Gdl @@ -1216,6 +1261,11 @@ Hack: name: Hack path: Hack url: Hack +Halon: + ext: halon + name: Halon + path: Halon + url: Halon Harbour: ext: harbour name: Harbour @@ -1276,6 +1326,11 @@ IDL: name: IDL path: IDL url: IDL +IWBASIC: + ext: iwbasic + name: IWBASIC + path: IWBASIC + url: IWBASIC Icon: ext: icon name: Icon @@ -1396,6 +1451,11 @@ Joy: name: Joy path: Joy url: Joy +Jq: + ext: jq + name: Jq + path: Jq + url: Jq JudoScript: ext: judo name: JudoScript @@ -1521,6 +1581,11 @@ Lambda Prolog: name: Lambda Prolog path: Lambda-Prolog url: Lambda_Prolog +Lambdatalk: + ext: lambdatalk + name: Lambdatalk + path: Lambdatalk + url: Lambdatalk Lang5: ext: lang5 name: Lang5 @@ -1761,6 +1826,11 @@ MSX BASIC: name: MSX BASIC path: MSX-BASIC url: MSX_BASIC +MSX Basic: + ext: msx + name: MSX Basic + path: MSX-Basic + url: MSX_Basic MUF: ext: muf name: MUF @@ -1851,6 +1921,11 @@ Monicelli: name: Monicelli path: Monicelli url: Monicelli +Monkey: + ext: monkey + name: Monkey + path: Monkey + url: Monkey Monte: ext: monte name: Monte @@ -1896,6 +1971,11 @@ N/t/roff: name: N/t/roff path: N-t-roff url: N/t/roff +NASL: + ext: nasl + name: NASL + path: NASL + url: NASL NESL: ext: nesl name: NESL @@ -1991,6 +2071,16 @@ Nix: name: Nix path: Nix url: Nix +OASYS: + ext: oasys + name: OASYS + path: OASYS + url: OASYS +OASYS Assembler: + ext: oasys + name: OASYS Assembler + path: OASYS-Assembler + url: OASYS_Assembler OCaml: ext: ocaml name: OCaml @@ -2141,6 +2231,11 @@ PHP: name: PHP path: PHP url: PHP +PILOT: + ext: pilot + name: PILOT + path: PILOT + url: PILOT PIR: ext: pir name: PIR @@ -2277,6 +2372,11 @@ PlainTeX: name: PlainTeX path: PlainTeX url: PlainTeX +Plan: + ext: plan + name: Plan + path: Plan + url: Plan Pony: ext: pony name: Pony @@ -2589,6 +2689,11 @@ SPARK: name: SPARK path: SPARK url: SPARK +SPL: + ext: spl + name: SPL + path: SPL + url: SPL SQL: ext: sql name: SQL @@ -2674,6 +2779,11 @@ Set lang: name: Set lang path: Set-lang url: Set_lang +Setl4: + ext: setl4 + name: Setl4 + path: Setl4 + url: Setl4 SheerPower 4GL: ext: 4gl name: SheerPower 4GL @@ -2699,6 +2809,11 @@ Simula: name: Simula path: Simula url: Simula +Sinclair ZX81 BASIC: + ext: sinclair + name: Sinclair ZX81 BASIC + path: Sinclair-ZX81-BASIC + url: Sinclair_ZX81_BASIC Sisal: ext: sisal name: Sisal @@ -2719,6 +2834,11 @@ Smalltalk: name: Smalltalk path: Smalltalk url: Smalltalk +Smart BASIC: + ext: smart + name: Smart BASIC + path: Smart-BASIC + url: Smart_BASIC SmileBASIC: ext: smilebasic name: SmileBASIC @@ -2764,6 +2884,11 @@ Star: name: Star path: Star url: Star +Stata: + ext: stata + name: Stata + path: Stata + url: Stata StreamIt: ext: streamit name: StreamIt @@ -2860,6 +2985,11 @@ TeLa: name: TeLa path: TeLa url: TeLa +TechBASIC: + ext: techbasic + name: TechBASIC + path: TechBASIC + url: TechBASIC Teco: ext: teco name: Teco @@ -2900,6 +3030,11 @@ TorqueScript: name: TorqueScript path: TorqueScript url: TorqueScript +TransFORTH: + ext: transforth + name: TransFORTH + path: TransFORTH + url: TransFORTH Transact-SQL: ext: sql name: Transact-SQL @@ -3065,6 +3200,11 @@ Visual Prolog: name: Visual Prolog path: Visual-Prolog url: Visual_Prolog +Viua VM assembly: + ext: viua + name: Viua VM assembly + path: Viua-VM-assembly + url: Viua_VM_assembly Vorpal: ext: vorpal name: Vorpal @@ -3085,6 +3225,11 @@ Wart: name: Wart path: Wart url: Wart +WebAssembly: + ext: webassembly + name: WebAssembly + path: WebAssembly + url: WebAssembly Whenever: ext: whenever name: Whenever @@ -3255,8 +3400,3 @@ Zonnon: name: Zonnon path: Zonnon url: Zonnon -jq: - ext: jq - name: jq - path: jq - url: jq diff --git a/Task/100-doors/00DESCRIPTION b/Task/100-doors/00DESCRIPTION index 1db5397c00..2e5c77cea8 100644 --- a/Task/100-doors/00DESCRIPTION +++ b/Task/100-doors/00DESCRIPTION @@ -2,7 +2,7 @@ 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. diff --git a/Task/100-doors/ABAP/100-doors-2.abap b/Task/100-doors/ABAP/100-doors-2.abap index 9a68228308..ce085c1102 100644 --- a/Task/100-doors/ABAP/100-doors-2.abap +++ b/Task/100-doors/ABAP/100-doors-2.abap @@ -1,14 +1,9 @@ -form open_doors_opt. - data: lv_square type i value 1, - lv_inc type i value 3. - data: lt_doors type standard table of c initial size 100. - field-symbols: type c. - do 100 times. - append initial line to lt_doors assigning . - if sy-index = lv_square. - = 'X'. - add: lv_inc to lv_square, 2 to lv_inc. - write : / 'Door', (4) sy-index right-justified, 'is open' no-gap. - endif. - enddo. -endform. +cl_demo_output=>display( REDUCE stringtab( INIT list TYPE stringtab + aux TYPE i + FOR door = 1 WHILE door <= 100 + FOR pass = 1 WHILE pass <= 100 + NEXT aux = COND #( WHEN pass = 1 THEN 1 + WHEN door MOD pass = 0 THEN aux + 1 ELSE aux ) + list = COND #( WHEN pass = 100 + THEN COND #( WHEN aux MOD 2 <> 0 THEN VALUE #( BASE list ( CONV #( door ) ) ) + ELSE list ) ELSE list ) ) ). diff --git a/Task/100-doors/ABAP/100-doors-3.abap b/Task/100-doors/ABAP/100-doors-3.abap new file mode 100644 index 0000000000..9a68228308 --- /dev/null +++ b/Task/100-doors/ABAP/100-doors-3.abap @@ -0,0 +1,14 @@ +form open_doors_opt. + data: lv_square type i value 1, + lv_inc type i value 3. + data: lt_doors type standard table of c initial size 100. + field-symbols: type c. + do 100 times. + append initial line to lt_doors assigning . + if sy-index = lv_square. + = 'X'. + add: lv_inc to lv_square, 2 to lv_inc. + write : / 'Door', (4) sy-index right-justified, 'is open' no-gap. + endif. + enddo. +endform. diff --git a/Task/100-doors/ABAP/100-doors-4.abap b/Task/100-doors/ABAP/100-doors-4.abap new file mode 100644 index 0000000000..53a2381a53 --- /dev/null +++ b/Task/100-doors/ABAP/100-doors-4.abap @@ -0,0 +1,4 @@ +DO 10 TIMES. + DATA(val) = sy-index * sy-index. + WRITE: / val. +ENDDO. diff --git a/Task/100-doors/ABAP/100-doors-5.abap b/Task/100-doors/ABAP/100-doors-5.abap new file mode 100644 index 0000000000..4148036cc1 --- /dev/null +++ b/Task/100-doors/ABAP/100-doors-5.abap @@ -0,0 +1,3 @@ +cl_demo_output=>display( REDUCE stringtab( INIT list TYPE stringtab + FOR i = 1 WHILE i <= 10 + NEXT list = VALUE #( BASE list ( i * i ) ) ) ). diff --git a/Task/100-doors/APL/100-doors-1.apl b/Task/100-doors/APL/100-doors-1.apl deleted file mode 100644 index 8390a1b5b0..0000000000 --- a/Task/100-doors/APL/100-doors-1.apl +++ /dev/null @@ -1,11 +0,0 @@ -out?doors num -? Simulates the 100 doors problem for any number of doors -? Returns a boolean vector with 1 being open - -out??num ? num steps -out??¨out ? Count out the spacing for each step -out?1=out ? Make that into a boolean vector -out??¨out ? Flip each vector around -out?(num°?)¨out ? Copy each out to the right size -out??/out ? XOR each vector, toggling each marked door -out??out ? Disclose the results to get a vector diff --git a/Task/100-doors/APL/100-doors-2.apl b/Task/100-doors/APL/100-doors-2.apl deleted file mode 100644 index 7d8ad58785..0000000000 --- a/Task/100-doors/APL/100-doors-2.apl +++ /dev/null @@ -1,7 +0,0 @@ -out?doorsOptimized num;marks -? Returns a boolean vector of the doors that would be left open - -marks??num*0.5 ? Take the square root of the size, floored -marks?(?marks)*2 ? Get each door to be opened -out?num?0 ? Make a vector of 0s -out[marks]?1 ? Set the marked doors to 1 diff --git a/Task/100-doors/AppleScript/100-doors-2.applescript b/Task/100-doors/AppleScript/100-doors-2.applescript index 382a73ed29..477c5419af 100644 --- a/Task/100-doors/AppleScript/100-doors-2.applescript +++ b/Task/100-doors/AppleScript/100-doors-2.applescript @@ -1,45 +1,47 @@ +-- FINAL DOOR STATES --------------------------------------------------------- + -- finalDoors :: Int -> [(Int, Bool)] on finalDoors(n) -- toggledCorridor :: [(Int, Bool)] -> (Int, Bool) -> Int -> [(Int, Bool)] script toggledCorridor - on lambda(a, _, k) + on |λ|(a, _, k) -- perhapsToggled :: Bool -> Int -> Bool script perhapsToggled - on lambda(x, i) + on |λ|(x, i) if i mod k = 0 then {i, not item 2 of x} else {i, item 2 of x} end if - end lambda + end |λ| end script map(perhapsToggled, a) - end lambda + end |λ| end script - set lstRange to range(1, n) + set xs to enumFromTo(1, n) foldl(toggledCorridor, ¬ - zip(lstRange, replicate(n, {false})), lstRange) + zip(xs, replicate(n, {false})), xs) end finalDoors --- TEST +-- TEST ---------------------------------------------------------------------- on run -- isOpenAtEnd :: (Int, Bool) -> Bool script isOpenAtEnd - on lambda(door) + on |λ|(door) (item 2 of door) - end lambda + end |λ| end script -- doorNumber :: (Int, Bool) -> Int script doorNumber - on lambda(door) + on |λ|(door) (item 1 of door) - end lambda + end |λ| end script map(doorNumber, filter(isOpenAtEnd, finalDoors(100))) @@ -48,8 +50,21 @@ on run end run +-- GENERIC FUNCTIONS --------------------------------------------------------- --- GENERIC FUNCTIONS +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if n < m then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) @@ -58,7 +73,7 @@ on filter(f, xs) set lng to length of xs repeat with i from 1 to lng set v to item i of xs - if lambda(v, i, xs) then set end of lst to v + if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell @@ -70,7 +85,7 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -82,40 +97,38 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map --- zip :: [a] -> [b] -> [(a, b)] -on zip(xs, ys) - script pair - on lambda(x, i) - [x, item i of ys] - end lambda - end script - - if length of xs = length of ys then - map(pair, xs) +-- min :: Ord a => a -> a -> a +on min(x, y) + if y < x then + y else - missing value + x end if -end zip +end min --- Egyptian multiplication - progressively doubling a list, appending --- stages of doubling to an accumulator where needed for binary --- assembly of a target length +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn -- replicate :: Int -> a -> [a] on replicate(n, a) - if class of a is list then - set out to {} - else - set out to "" - end if + set out to {} if n < 1 then return out - set dbl to a + set dbl to {a} repeat while (n > 1) if (n mod 2) > 0 then set out to out & dbl @@ -125,25 +138,12 @@ on replicate(n, a) return out & dbl end replicate --- range :: Int -> Int -> [Int] -on range(m, n) - set d to 1 - if n < m then set d to -1 +-- zip :: [a] -> [b] -> [(a, b)] +on zip(xs, ys) + set lng to min(length of xs, length of ys) set lst to {} - repeat with i from m to n by d - set end of lst to i + repeat with i from 1 to lng + set end of lst to {item i of xs, item i of ys} end repeat return lst -end range - --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn +end zip diff --git a/Task/100-doors/AppleScript/100-doors-4.applescript b/Task/100-doors/AppleScript/100-doors-4.applescript index efe91e4d16..3cd54f4bf1 100644 --- a/Task/100-doors/AppleScript/100-doors-4.applescript +++ b/Task/100-doors/AppleScript/100-doors-4.applescript @@ -1,4 +1,4 @@ -map(factorCountMod2, range(1, 100)) +map(factorCountMod2, enumFromTo(1, 100)) on factorCountMod2(n) {n, (length of integerFactors(n)) mod 2 = 1} diff --git a/Task/100-doors/AppleScript/100-doors-5.applescript b/Task/100-doors/AppleScript/100-doors-5.applescript index a0f2e17b5d..6db0536276 100644 --- a/Task/100-doors/AppleScript/100-doors-5.applescript +++ b/Task/100-doors/AppleScript/100-doors-5.applescript @@ -2,16 +2,16 @@ on perfectSquaresUpTo(n) script squared -- (Int -> Int) - on lambda(x) + on |λ|(x) x * x - end lambda + end |λ| end script set realRoot to n ^ (1 / 2) set intRoot to realRoot as integer set blnNotPerfectSquare to not (intRoot = realRoot) - map(squared, range(1, intRoot - (blnNotPerfectSquare as integer))) + map(squared, enumFromTo(1, intRoot - (blnNotPerfectSquare as integer))) end perfectSquaresUpTo on run diff --git a/Task/100-doors/Astro/100-doors.astro b/Task/100-doors/Astro/100-doors.astro new file mode 100644 index 0000000000..fd1782d362 --- /dev/null +++ b/Task/100-doors/Astro/100-doors.astro @@ -0,0 +1,4 @@ +var doors = falses 100 +for a in [:101]: + for b in [a:a:101]: doors[b] = !doors[b] + print "Door $a is $('open.' if doors[a] else 'closed.')" diff --git a/Task/100-doors/BASIC/100-doors-5.basic b/Task/100-doors/BASIC/100-doors-5.basic new file mode 100644 index 0000000000..4229d9c86a --- /dev/null +++ b/Task/100-doors/BASIC/100-doors-5.basic @@ -0,0 +1,9 @@ +10 DIM D(100) +20 FOR I=1 TO 100 +30 FOR J=I TO 100 STEP I +40 LET D(J)=NOT D(J) +50 NEXT J +60 NEXT I +70 FOR I=1 TO 100 +80 IF D(I) THEN PRINT I, +90 NEXT I diff --git a/Task/100-doors/BASIC256/100-doors.basic256 b/Task/100-doors/BASIC/100-doors-6.basic similarity index 100% rename from Task/100-doors/BASIC256/100-doors.basic256 rename to Task/100-doors/BASIC/100-doors-6.basic diff --git a/Task/100-doors/BASIC/100-doors-7.basic b/Task/100-doors/BASIC/100-doors-7.basic new file mode 100644 index 0000000000..4aa6f409d4 --- /dev/null +++ b/Task/100-doors/BASIC/100-doors-7.basic @@ -0,0 +1,9 @@ +10 DIM D(100) +20 FOR I=1 TO 100 +30 FOR J=I TO 100 STEP I +40 D(J) = NOT D(J) +50 NEXT J +60 NEXT I +70 FOR I=1 TO 100 +80 IF D(I) THEN PRINT I, +90 NEXT I diff --git a/Task/100-doors/BaCon/100-doors.bacon b/Task/100-doors/BaCon/100-doors.bacon new file mode 100644 index 0000000000..cc0e283593 --- /dev/null +++ b/Task/100-doors/BaCon/100-doors.bacon @@ -0,0 +1,13 @@ +OPTION BASE 1 + +DECLARE doors[100] + +FOR size = 1 TO 100 + FOR pass = 0 TO 100 STEP size + doors[pass] = NOT(doors[pass]) + NEXT +NEXT + +FOR which = 1 TO 100 + IF doors[which] THEN PRINT which +NEXT diff --git a/Task/100-doors/Bc/100-doors.bc b/Task/100-doors/Bc/100-doors.bc new file mode 100644 index 0000000000..af02fe475a --- /dev/null +++ b/Task/100-doors/Bc/100-doors.bc @@ -0,0 +1,12 @@ +/* 0 means door is closed, 1 means door is open */ +for (i = 0; i < 100; i++) { + for (j = i; j < 100; j += (i + 1)) { + d[j] = 1 - d[j] /* Toggle door */ + } +} + +"Open doors: +" +for (i = 0; i < 100; i++) { + if (d[i] == 1) (i + 1) +} diff --git a/Task/100-doors/ColdFusion/100-doors-3.cfm b/Task/100-doors/ColdFusion/100-doors-3.cfm index b622ac1256..c5f0db0c70 100644 --- a/Task/100-doors/ColdFusion/100-doors-3.cfm +++ b/Task/100-doors/ColdFusion/100-doors-3.cfm @@ -1,11 +1,11 @@ - // Display all doors - - Door #x# Open: #YesNoFormat(ListGetAt(doorList,x))#
-
+// Display all doors + + Door #x# Open: #YesNoFormat(ListGetAt(doorList,x))#
+
- // Output only open doors - - - #x#
-
-
+// Output only open doors + + + #x#
+
+
diff --git a/Task/100-doors/ColdFusion/100-doors-4.cfm b/Task/100-doors/ColdFusion/100-doors-4.cfm index 2c24d60b80..0f9932d00d 100644 --- a/Task/100-doors/ColdFusion/100-doors-4.cfm +++ b/Task/100-doors/ColdFusion/100-doors-4.cfm @@ -1,14 +1,14 @@ - + - - - + + + - + - + #doorlist# diff --git a/Task/100-doors/D/100-doors-1.d b/Task/100-doors/D/100-doors-1.d index 65e8f69802..383f1d0dc4 100644 --- a/Task/100-doors/D/100-doors-1.d +++ b/Task/100-doors/D/100-doors-1.d @@ -7,7 +7,7 @@ Doors flipUnoptimized(Doors doors) pure nothrow { doors[] = DoorState.closed; foreach (immutable i; 0 .. doors.length) - for (int j = i; j < doors.length; j += i + 1) + for (ulong j = i; j < doors.length; j += i + 1) if (doors[j] == DoorState.open) doors[j] = DoorState.closed; else diff --git a/Task/100-doors/DUP/100-doors-1.dup b/Task/100-doors/DUP/100-doors-1.dup new file mode 100644 index 0000000000..12392653b6 --- /dev/null +++ b/Task/100-doors/DUP/100-doors-1.dup @@ -0,0 +1,5 @@ +100[$][0^:1-]# {initialize doors} +% +[s;[$101<][$$;~\:s;+]#%]d: {function d, switch door state function} +1s:[s;101<][d;!s;1+s:]# {increment step width from 1 to 100, execute function d each time} +1[$101<][$$.' ,;['o,'p,'e,'n,10,]['c,'l,'o,'s,'e,'d,10,]?1+]# {loop through doors, print door number and state} diff --git a/Task/100-doors/DUP/100-doors-2.dup b/Task/100-doors/DUP/100-doors-2.dup new file mode 100644 index 0000000000..df2a916b08 --- /dev/null +++ b/Task/100-doors/DUP/100-doors-2.dup @@ -0,0 +1,20 @@ +1 open +2 closed +3 closed +4 open +5 closed +6 closed +7 closed +8 closed +9 open +10 closed +11 closed +12 closed +... +94 closed +95 closed +96 closed +97 closed +98 closed +99 closed +100 open diff --git a/Task/100-doors/Dafny/100-doors.dafny b/Task/100-doors/Dafny/100-doors.dafny new file mode 100644 index 0000000000..af720e8612 --- /dev/null +++ b/Task/100-doors/Dafny/100-doors.dafny @@ -0,0 +1,48 @@ +datatype Door = Closed | Open + +method InitializeDoors(n:int) returns (doors:array) + // Precondition: n must be a valid array size. + requires n >= 0 + // Postcondition: doors is an array, which is not an alias for any other + // object, with a length of n, all of whose elements are Closed. The "fresh" + // (non-alias) condition is needed to allow doors to be modified by the + // remaining code. + ensures doors != null && fresh(doors) && doors.Length == n + ensures forall j :: 0 <= j < doors.Length ==> doors[j] == Closed; +{ + doors := new Door[n]; + var i := 0; + // Invariant: i is always a valid index inside the loop, and all doors less + // than i are Closed. These invariants are needed to ensure the second + // postcondition. + while i < doors.Length + invariant i <= doors.Length + invariant forall j :: 0 <= j < i ==> doors[j] == Closed; + { + doors[i] := Closed; + i := i + 1; + } +} + +method Main () +{ + var doors := InitializeDoors(100); + + var pass := 1; + while pass <= doors.Length + { + var door := pass; + while door < doors.Length + { + doors[door] := if doors[door] == Closed then Open else Closed; + door := door + pass; + } + pass := pass + 1; + } + var i := 0; + while i < doors.Length + { + print i, " is ", if doors[i] == Closed then "closed\n" else "open\n"; + i := i + 1; + } +} diff --git a/Task/100-doors/Elena/100-doors.elena b/Task/100-doors/Elena/100-doors.elena index 5fc7093148..5b19be4a90 100644 --- a/Task/100-doors/Elena/100-doors.elena +++ b/Task/100-doors/Elena/100-doors.elena @@ -1,21 +1,22 @@ -#import system. -#import system'routines. -#import extensions. +import system'routines. +import extensions. -#symbol program= +program = [ - #var Doors := Array new:100 set &every: (&index:n) [ false ]. + var Doors := Array new:100; populate(:n)( false ). - 0 till:100 &doEach: i + 0 till:100 do(:i) [ - i till:100 &by:(i + 1) &doEach: j + i till:100 by(i + 1) do(:j) [ - Doors@j := Doors@j not. - ]. + Doors[j] := Doors[j] not + ] ]. - 0 till:100 &doEach: i + 0 till:100 do(:i) [ - console writeLine:"Door #":(i + 1):" :":(Doors@i iif:"Open":"Closed"). + console printLine("Door #",i + 1," :",Doors[i] iif("Open","Closed")) ]. + + console readChar. ]. diff --git a/Task/100-doors/Elm/100-doors.elm b/Task/100-doors/Elm/100-doors.elm new file mode 100644 index 0000000000..d271fc95f6 --- /dev/null +++ b/Task/100-doors/Elm/100-doors.elm @@ -0,0 +1,17 @@ +-- Unoptimized +import List exposing (indexedMap, foldl, repeat, range) +import Html exposing (text) + +type Door = Open | Closed + +toggle d = if d == Open then Closed else Open + +toggleEvery : Int -> List Door -> List Door +toggleEvery k doors = indexedMap + (\i door -> if i % k == 0 then toggle door else door) + doors + +n = 100 + +main = + text (toString (foldl toggleEvery (repeat n Closed) (range 1 n))) diff --git a/Task/100-doors/FALSE/100-doors-1.false b/Task/100-doors/FALSE/100-doors-1.false new file mode 100644 index 0000000000..55eb16004c --- /dev/null +++ b/Task/100-doors/FALSE/100-doors-1.false @@ -0,0 +1,7 @@ +100[$][0 1ø:1-]# {initialize doors} +% +[s;[$101\>][$$;~\:s;+]#%]d: {function d, switch door state function} +1s:[s;101\>][d;!s;1+s:]# {increment step width from 1 to 100, execute function d each time} +1[$101\>][$$." ";$["open +"]?~["closed +"]?1+]# {loop through doors, print door number and state} diff --git a/Task/100-doors/FALSE/100-doors-2.false b/Task/100-doors/FALSE/100-doors-2.false new file mode 100644 index 0000000000..ddad52d564 --- /dev/null +++ b/Task/100-doors/FALSE/100-doors-2.false @@ -0,0 +1,14 @@ +1 open +2 closed +3 closed +4 open +5 closed +6 closed +7 closed +8 closed +9 open +10 closed +... +98 closed +99 closed +100 open diff --git a/Task/100-doors/Friendly-interactive-shell/100-doors-1.fish b/Task/100-doors/Friendly-interactive-shell/100-doors-1.fish new file mode 100644 index 0000000000..d90baa8e29 --- /dev/null +++ b/Task/100-doors/Friendly-interactive-shell/100-doors-1.fish @@ -0,0 +1,26 @@ +# Set doors to empty list +set doors + +# Initialize doors arrays +for i in (seq 100) + set doors[$i] 0 +end + +for i in (seq 100) + set j $i + while test $j -le 100 + # Logical not on doors + set doors[$j] (math !$doors[$j]) + set j (math $j + $i) + end +end + +# Print every door +for i in (seq (count $doors)) + echo -n "$i " + if test $doors[$i] -eq 0 + echo closed + else + echo open + end +end diff --git a/Task/100-doors/Friendly-interactive-shell/100-doors-2.fish b/Task/100-doors/Friendly-interactive-shell/100-doors-2.fish new file mode 100644 index 0000000000..7dc7567221 --- /dev/null +++ b/Task/100-doors/Friendly-interactive-shell/100-doors-2.fish @@ -0,0 +1,12 @@ +# Set doors to empty list +set doors + +for i in (seq 100) + set doors[(math "$i * $i")] 1 + echo -n "$i " + if test $doors[$i] -eq 1 + echo open + else + echo closed + end +end diff --git a/Task/100-doors/Gambas/100-doors.gambas b/Task/100-doors/Gambas/100-doors.gambas new file mode 100644 index 0000000000..9a6dd6fb88 --- /dev/null +++ b/Task/100-doors/Gambas/100-doors.gambas @@ -0,0 +1,16 @@ +Public Sub Main() +Dim bDoor As New Boolean[101] +Dim siCount1, siCount2, siStart As Short + +For siCount1 = 1 To 100 + Inc siStart + For siCount2 = siStart To 100 Step siCount1 + bDoor[siCount2] = Not bDoor[siCount2] + Next +Next + +For siCount1 = 1 To 100 + If bDoor[siCount1] Then Print siCount1;; +Next + +End diff --git a/Task/100-doors/Glee/100-doors-1.glee b/Task/100-doors/Glee/100-doors-1.glee new file mode 100644 index 0000000000..3d95b4241c --- /dev/null +++ b/Task/100-doors/Glee/100-doors-1.glee @@ -0,0 +1,4 @@ +100` *=0=>d $$ create vector 1..100, create bit pattern d, marking all equal to 0 +:for (1..100[.s]){ $$ loop s from 1 to 100 + d^(100` %s *=0 )=>d;} $$ d = d xor (bit pattern of vector 1..100 % s) +d $$ output d diff --git a/Task/100-doors/Glee/100-doors-2.glee b/Task/100-doors/Glee/100-doors-2.glee new file mode 100644 index 0000000000..0c00c77d25 --- /dev/null +++ b/Task/100-doors/Glee/100-doors-2.glee @@ -0,0 +1,2 @@ +Result: +10010000 10000001 00000000 10000000 00010000 00000000 10000000 00000001 00000000 00000000 10000000 00000000 0001 diff --git a/Task/100-doors/Haskell/100-doors-1.hs b/Task/100-doors/Haskell/100-doors-1.hs index b82123a8e8..328636686f 100644 --- a/Task/100-doors/Haskell/100-doors-1.hs +++ b/Task/100-doors/Haskell/100-doors-1.hs @@ -1,10 +1,21 @@ -data Door = Open | Closed deriving Show +data Door + = Open + | Closed + deriving (Eq, Show) -toggle Open = Closed +toggle :: Door -> Door +toggle Open = Closed toggle Closed = Open -toggleEvery :: [Door] -> Int -> [Door] -toggleEvery xs k = zipWith ($) fs xs - where fs = cycle $ (replicate (k-1) id) ++ [toggle] +toggleEvery :: Int -> [Door] -> [Door] +toggleEvery k = zipWith toggleK [1 ..] + where + toggleK n door + | n `mod` k == 0 = toggle door + | otherwise = door -run n = foldl toggleEvery (replicate n Closed) [1..n] +run :: Int -> [Door] +run n = foldr toggleEvery (replicate n Closed) [1 .. n] + +main :: IO () +main = print $ filter ((== Open) . snd) $ zip [1 ..] (run 100) diff --git a/Task/100-doors/Haskell/100-doors-2.hs b/Task/100-doors/Haskell/100-doors-2.hs index e89bb4fea7..2cea247dfd 100644 --- a/Task/100-doors/Haskell/100-doors-2.hs +++ b/Task/100-doors/Haskell/100-doors-2.hs @@ -1,12 +1,6 @@ -data Door = Open | Closed deriving Show +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 [] _ = [] -toggle Open = Closed -toggle Closed = Open - -toggleEvery :: Int -> [Door] -> [Door] -toggleEvery k = zipWith toggleK [1..] - where - toggleK n door | n `mod` k == 0 = toggle door - | otherwise = door - -run n = foldr toggleEvery (replicate n Closed) [1..n] +run n = gate [1..n] [k*k | k <- [1..]] diff --git a/Task/100-doors/Haskell/100-doors-3.hs b/Task/100-doors/Haskell/100-doors-3.hs index 2cea247dfd..44f44aa391 100644 --- a/Task/100-doors/Haskell/100-doors-3.hs +++ b/Task/100-doors/Haskell/100-doors-3.hs @@ -1,6 +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..]] +run n = takeWhile (< n) [k*k | k <- [1..]] diff --git a/Task/100-doors/Haskell/100-doors-4.hs b/Task/100-doors/Haskell/100-doors-4.hs deleted file mode 100644 index 44f44aa391..0000000000 --- a/Task/100-doors/Haskell/100-doors-4.hs +++ /dev/null @@ -1 +0,0 @@ -run n = takeWhile (< n) [k*k | k <- [1..]] diff --git a/Task/100-doors/Java/100-doors-1.java b/Task/100-doors/Java/100-doors-1.java index df5e0aee5c..3ef72743d9 100644 --- a/Task/100-doors/Java/100-doors-1.java +++ b/Task/100-doors/Java/100-doors-1.java @@ -1 +1,17 @@ -N.println(IntStream.rangeClosed(1, 100).filter(i -> Math.pow((int) Math.sqrt(i), 2) == i).boxed().join(", ", "Open Doors: ", "")); +class HundredDoors { + public static void main(String[] args) { + boolean[] doors = new boolean[101]; + + for (int i = 1; i < doors.length; i++) { + for (int j = i; j < doors.length; j += i) { + doors[j] = !doors[j]; + } + } + + for (int i = 1; i < doors.length; i++) { + if (doors[i]) { + System.out.printf("Door %d is open.%n", i); + } + } + } +} diff --git a/Task/100-doors/Java/100-doors-2.java b/Task/100-doors/Java/100-doors-2.java index e215518087..8faa42f92b 100644 --- a/Task/100-doors/Java/100-doors-2.java +++ b/Task/100-doors/Java/100-doors-2.java @@ -1,13 +1,6 @@ -public class HundredDoors { +class HundredDoors { public static void main(String[] args) { - boolean[] doors = new boolean[101]; - for (int i = 1; i <= 100; i++) { - for (int j = i; j <= 100; j++) { - if(j % i == 0) doors[j] = !doors[j]; - } - } - for (int i = 1; i <= 100; i++) { - System.out.printf("Door %d: %s%n", i, doors[i] ? "open" : "closed"); - } + for (int i = 1; i <= 10; i++) + System.out.printf("Door %d is open.%n", i * i); } } diff --git a/Task/100-doors/Java/100-doors-3.java b/Task/100-doors/Java/100-doors-3.java index fbc73e7d13..8d9ada9050 100644 --- a/Task/100-doors/Java/100-doors-3.java +++ b/Task/100-doors/Java/100-doors-3.java @@ -1,11 +1,12 @@ -public class Doors -{ - public static void main(String[] args) - { - boolean[] doors=new boolean[100]; - for(int i=0;i<10;i++) - doors[i*(i+2)]=true; - for(int i=0;i<100;i++) - System.out.println("Door #"+(i+1)+" is"+(doors[i]?"open.":" closed.")); - } +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +class HundredDoors { + public static void main(String args[]) { + String openDoors = IntStream.rangeClosed(1, 100) + .filter(i -> Math.pow((int) Math.sqrt(i), 2) == i) + .mapToObj(Integer::toString) + .collect(Collectors.joining(", ")); + System.out.printf("Open doors: %s%n", openDoors); + } } diff --git a/Task/100-doors/Java/100-doors-4.java b/Task/100-doors/Java/100-doors-4.java deleted file mode 100644 index 7722346acf..0000000000 --- a/Task/100-doors/Java/100-doors-4.java +++ /dev/null @@ -1,8 +0,0 @@ -public class Doors -{ - public static void main(String[] args) - { - for(int i=0;i<10;i++) - System.out.println("Door #"+(i*(i+2)+1)+" is open."); - } -} diff --git a/Task/100-doors/Java/100-doors-5.java b/Task/100-doors/Java/100-doors-5.java deleted file mode 100644 index 318cd39a24..0000000000 --- a/Task/100-doors/Java/100-doors-5.java +++ /dev/null @@ -1,13 +0,0 @@ -public class Doors -{ - public static void main(final String[] args) - { - boolean[] doors = new boolean[100]; - - for (int pass = 0; pass < 10; pass++) - doors[(pass + 1) * (pass + 1) - 1] = true; - - for(int i = 0; i < 100; i++) - System.out.println("Door #" + (i + 1) + " is " + (doors[i] ? "open." : "closed.")); - } -} diff --git a/Task/100-doors/Java/100-doors-6.java b/Task/100-doors/Java/100-doors-6.java deleted file mode 100644 index 2d89ca9dc4..0000000000 --- a/Task/100-doors/Java/100-doors-6.java +++ /dev/null @@ -1,12 +0,0 @@ -public class Doors -{ - public static void main(final String[] args) - { - StringBuilder sb = new StringBuilder(); - - for (int i = 1; i <= 10; i++) - sb.append("Door #").append(i*i).append(" is open\n"); - - System.out.println(sb.toString()); - } -} diff --git a/Task/100-doors/Java/100-doors-7.java b/Task/100-doors/Java/100-doors-7.java deleted file mode 100644 index 4d4b8e884c..0000000000 --- a/Task/100-doors/Java/100-doors-7.java +++ /dev/null @@ -1,13 +0,0 @@ -public class Doors{ - public static void main(String[] args){ - int i; - for(i = 1; i < 101; i++){ - double sqrt = Math.sqrt(i); - if(sqrt != (int)sqrt){ - System.out.println("Door " + i + " is closed"); - }else{ - System.out.println("Door " + i + " is open"); - } - } - } -} diff --git a/Task/100-doors/JavaScript/100-doors-13.js b/Task/100-doors/JavaScript/100-doors-13.js deleted file mode 100644 index 7378d4bae5..0000000000 --- a/Task/100-doors/JavaScript/100-doors-13.js +++ /dev/null @@ -1,9 +0,0 @@ -// Array comprehension style -[ for (i of Array.apply(null, { length: 100 })) i ].forEach((_, i) => { - var door = i + 1 - var sqrt = Math.sqrt(door); - - if (sqrt === (sqrt | 0)) { - console.log("Door %d is open", door); - } -}); diff --git a/Task/100-doors/jq/100-doors-1.jq b/Task/100-doors/Jq/100-doors-1.jq similarity index 90% rename from Task/100-doors/jq/100-doors-1.jq rename to Task/100-doors/Jq/100-doors-1.jq index b3cbb11c94..04a0b86e8b 100644 --- a/Task/100-doors/jq/100-doors-1.jq +++ b/Task/100-doors/Jq/100-doors-1.jq @@ -6,7 +6,7 @@ def doors(n): | range(1; length+1) | if $doors[.] then "Door \(.) is open" else empty end; - ([][n+1] = null) as $doors + [range(n+1)|null] as $doors | reduce range(1; n+1) as $run ( $doors; reduce range($run; n+1; $run ) as $door ( .; .[$door] = (.[$door] | not) ) ) diff --git a/Task/100-doors/jq/100-doors-2.jq b/Task/100-doors/Jq/100-doors-2.jq similarity index 100% rename from Task/100-doors/jq/100-doors-2.jq rename to Task/100-doors/Jq/100-doors-2.jq diff --git a/Task/100-doors/Kotlin/100-doors.kotlin b/Task/100-doors/Kotlin/100-doors.kotlin index a7a693598e..852ff6fb27 100644 --- a/Task/100-doors/Kotlin/100-doors.kotlin +++ b/Task/100-doors/Kotlin/100-doors.kotlin @@ -1,10 +1,12 @@ fun oneHundredDoors(): List { val doors = BooleanArray(100, { false }) - - for (i in 0..99) - for (j in i..99 step (i + 1)) + for (i in 0..99) { + for (j in i..99 step (i + 1)) { doors[j] = !doors[j] - - return doors.asSequence().mapIndexed { i, b -> i to b }.filter { it.second } - .map { it.first + 1 }.toList() + } + } + return doors + .mapIndexed { i, b -> i to b } + .filter { it.second } + .map { it.first + 1 } } diff --git a/Task/100-doors/MATLAB/100-doors-1.m b/Task/100-doors/MATLAB/100-doors-1.m index 3e87d2a41f..e43885890e 100644 --- a/Task/100-doors/MATLAB/100-doors-1.m +++ b/Task/100-doors/MATLAB/100-doors-1.m @@ -1,11 +1,7 @@ -a=zeros(1,100); -for b=1:100; -for i=b:b:100; - if a(i)==1 - a(i)=0; - else - a(i)=1; - end -end +a = false(1,100); +for b=1:100 + for i = b:b:100 + a(i) = ~a(i); + end end a diff --git a/Task/100-doors/MIRC-Scripting-Language/100-doors.mirc b/Task/100-doors/MIRC-Scripting-Language/100-doors.mirc new file mode 100644 index 0000000000..cd8cc4f021 --- /dev/null +++ b/Task/100-doors/MIRC-Scripting-Language/100-doors.mirc @@ -0,0 +1,16 @@ +var %d = $str(0 $+ $chr(32),100), %m = 1 +while (%m <= 100) { + var %n = 1 + while ($calc(%n * %m) <= 100) { + var %d = $puttok(%d,$iif($gettok(%d,$calc(%n * %m),32),0,1),$calc(%n * %m),32) + inc %n + } + inc %m +} +echo -ag All Doors (Boolean): %d +var %n = 1 +while (%n <= $findtok(%d,1,0,32)) { + var %t = %t $findtok(%d,1,%n,32) + inc %n +} +echo -ag Open Door Numbers: %t diff --git a/Task/100-doors/Moonscript/100-doors.moon b/Task/100-doors/Moonscript/100-doors.moon new file mode 100644 index 0000000000..72b750ef40 --- /dev/null +++ b/Task/100-doors/Moonscript/100-doors.moon @@ -0,0 +1,8 @@ +is_open = [false for door = 1,100] + +for pass = 1,100 + for door = pass,100,pass + is_open[door] = not is_open[door] + +for i,v in ipairs is_open + print "Door #{i}: " .. if v then 'open' else 'closed' diff --git a/Task/100-doors/MySQL/100-doors.sql b/Task/100-doors/MySQL/100-doors.sql new file mode 100644 index 0000000000..59c0d3cebc --- /dev/null +++ b/Task/100-doors/MySQL/100-doors.sql @@ -0,0 +1,37 @@ +DROP PROCEDURE IF EXISTS one_hundred_doors; + +DELIMITER | + +CREATE PROCEDURE one_hundred_doors (n INT) +BEGIN + DROP TEMPORARY TABLE IF EXISTS doors; + CREATE TEMPORARY TABLE doors ( + id INTEGER NOT NULL, + open BOOLEAN DEFAULT FALSE, + PRIMARY KEY (id) + ); + + SET @i = 1; + create_doors: LOOP + INSERT INTO doors (id, open) values (@i, FALSE); + SET @i = @i + 1; + IF @i > n THEN + LEAVE create_doors; + END IF; + END LOOP create_doors; + + SET @i = 1; + toggle_doors: LOOP + UPDATE doors SET open = NOT open WHERE MOD(id, @i) = 0; + SET @i = @i + 1; + IF @i > n THEN + LEAVE toggle_doors; + END IF; + END LOOP toggle_doors; + + SELECT id FROM doors WHERE open; +END| + +DELIMITER ; + +CALL one_hundred_doors(100); diff --git a/Task/100-doors/Nimrod/100-doors.nimrod b/Task/100-doors/Nimrod/100-doors.nimrod deleted file mode 100644 index 8b914ad3d1..0000000000 --- a/Task/100-doors/Nimrod/100-doors.nimrod +++ /dev/null @@ -1,16 +0,0 @@ -from strutils import format - -proc check_doors() = - const n = 100 - var is_open : array[1..n, bool] # auto-initialized to false - # pass over the doors n times - for pass in 1..n: - var i = pass - while i <= n: - is_open[i] = not is_open[i] - i += pass - # print the result - for door in 1..n: - echo format("door $1 is $2.", door, (if is_open[door]: "open" else: "closed")) - -check_doors() diff --git a/Task/100-doors/OoRexx/100-doors.rexx b/Task/100-doors/OoRexx/100-doors.rexx new file mode 100644 index 0000000000..6fad29ae7f --- /dev/null +++ b/Task/100-doors/OoRexx/100-doors.rexx @@ -0,0 +1,38 @@ +doors = .array~new(100) -- array containing all of the doors +do i = 1 to doors~size -- initialize with a collection of closed doors + doors[i] = .door~new(i) +end + +do inc = 1 to doors~size + do d = inc to doors~size by inc + doors[d]~toggle + end +end +say "The open doors after 100 passes:" +do door over doors + if door~isopen then say door +end + +::class door -- simple class to represent a door +::method init -- initialize an instance of a door + expose id state -- instance variables of a door + use strict arg id -- set the id + state = .false -- initial state is closed + +::method toggle -- toggle the state of the door + expose state + state = \state + +::method isopen -- test if the door is open + expose state + return state + +::method string -- return a string value for a door + expose state id + if state then return "Door" id "is open" + else return "Door" id "is closed" + +::method state -- return door state as a descriptive string + expose state + if state then return "open" + else return "closed" diff --git a/Task/100-doors/PHP/100-doors-2.php b/Task/100-doors/PHP/100-doors-2.php index 8f598ce832..7ead2a5c49 100644 --- a/Task/100-doors/PHP/100-doors-2.php +++ b/Task/100-doors/PHP/100-doors-2.php @@ -1,13 +1,12 @@ 'closed', 'closed' => 'open'); -$doors = array_fill(1, 100, 'closed'); +$doors = array_fill(1, 100, false); for ($pass = 1; $pass <= 100; ++$pass) { for ($nr = 1; $nr <= 100; ++$nr) { if ($nr % $pass == 0) { - $doors[$nr] = $toggleState[$doors[$nr]]; + $doors[$nr] = !$doors[$nr]; } } } for ($nr = 1; $nr <= 100; ++$nr) - printf("Door %d is %s\n", $nr, $doors[$nr]); + printf("Door %d: %s\n", $nr, ($doors[$nr])?'open':'closed'); ?> diff --git a/Task/100-doors/Prolog/100-doors-1.pro b/Task/100-doors/Prolog/100-doors-1.pro index eaac239216..5a5d94d937 100644 --- a/Task/100-doors/Prolog/100-doors-1.pro +++ b/Task/100-doors/Prolog/100-doors-1.pro @@ -1,34 +1,21 @@ -doors_unoptimized(N) :- - length(L, N), - maplist(init, L), - doors(N, N, L, L1), - affiche(N, L1). +main :- + forall(between(1,100,Door), ignore(display(Door))). -init(close). +% show output if door is open after the 100th pass +display(Door) :- + status(Door, 100, open), + format("Door ~d is open~n", [Door]). -doors(Max, 1, L, L1) :- - !, - inverse(1, 1, Max, L, L1). +% true if Door has Status after Pass is done +status(Door, Pass, Status) :- + Pass > 0, + Remainder is Door mod Pass, + toggle(Remainder, OldStatus, Status), + OldPass is Pass - 1, + status(Door, OldPass, OldStatus). +status(_Door, 0, closed). -doors(Max, N, L, L1) :- - N1 is N - 1, - doors(Max, N1, L, L2), - inverse(N, 1, Max, L2, L1). - - -inverse(N, Max, Max, [V], [V1]) :- - !, - 0 =:= Max mod N -> inverse(V, V1); V1 = V. - -inverse(N, M, Max, [V|T], [V1|T1]) :- - M1 is M+1, - inverse(N, M1, Max, T, T1), - ( 0 =:= M mod N -> inverse(V, V1); V1 = V). - - -inverse(open, close). -inverse(close, open). - -affiche(N, L) :- - forall(between(1, N, I), - ( nth1(I, L, open) -> format('Door ~w is open.~n', [I]); true)). +toggle(Remainder, Status, Status) :- + Remainder > 0. +toggle(0, open, closed). +toggle(0, closed, open). diff --git a/Task/100-doors/Prolog/100-doors-2.pro b/Task/100-doors/Prolog/100-doors-2.pro index ec41cb4af2..eaac239216 100644 --- a/Task/100-doors/Prolog/100-doors-2.pro +++ b/Task/100-doors/Prolog/100-doors-2.pro @@ -1,31 +1,34 @@ -doors(Num, Passes) :- - forall(( everyNth(1,Passes,1,Pass) - , forall((everyNth(Pass,Num,Pass,Door), toggle(Door))) - )) - , show(Num) - . +doors_unoptimized(N) :- + length(L, N), + maplist(init, L), + doors(N, N, L, L1), + affiche(N, L1). + +init(close). + +doors(Max, 1, L, L1) :- + !, + inverse(1, 1, Max, L, L1). + +doors(Max, N, L, L1) :- + N1 is N - 1, + doors(Max, N1, L, L2), + inverse(N, 1, Max, L2, L1). -toggle(Door) :- - Opened = opened(Door) - , ( clause(Opened,_) -> retract(Opened) - ; asserta(Opened) - ). +inverse(N, Max, Max, [V], [V1]) :- + !, + 0 =:= Max mod N -> inverse(V, V1); V1 = V. + +inverse(N, M, Max, [V|T], [V1|T1]) :- + M1 is M+1, + inverse(N, M1, Max, T, T1), + ( 0 =:= M mod N -> inverse(V, V1); V1 = V). -show(Num) :- - forall(( between(1,Num,Door) - , (opened(Door) -> State = opened ; State = closed) - , write(Door), write(' '), write(State), nl - )). +inverse(open, close). +inverse(close, open). - -% utils -forall(X) :- findall(_, X, _). - -everyNth(From,To,Step,X) :- - From =< To - , ( X = From ; From1 is From + Step, everyNth(From1,To,Step,X) ) - . - -main :- doors(100,100), halt. +affiche(N, L) :- + forall(between(1, N, I), + ( nth1(I, L, open) -> format('Door ~w is open.~n', [I]); true)). diff --git a/Task/100-doors/Prolog/100-doors-3.pro b/Task/100-doors/Prolog/100-doors-3.pro index 04252bdc72..ec41cb4af2 100644 --- a/Task/100-doors/Prolog/100-doors-3.pro +++ b/Task/100-doors/Prolog/100-doors-3.pro @@ -1,4 +1,31 @@ -doors_optimized(N) :- - Max is floor(sqrt(N)), - forall(between(1, Max, I), - ( J is I*I,format('Door ~w is open.~n',[J]))). +doors(Num, Passes) :- + forall(( everyNth(1,Passes,1,Pass) + , forall((everyNth(Pass,Num,Pass,Door), toggle(Door))) + )) + , show(Num) + . + + +toggle(Door) :- + Opened = opened(Door) + , ( clause(Opened,_) -> retract(Opened) + ; asserta(Opened) + ). + + +show(Num) :- + forall(( between(1,Num,Door) + , (opened(Door) -> State = opened ; State = closed) + , write(Door), write(' '), write(State), nl + )). + + +% utils +forall(X) :- findall(_, X, _). + +everyNth(From,To,Step,X) :- + From =< To + , ( X = From ; From1 is From + Step, everyNth(From1,To,Step,X) ) + . + +main :- doors(100,100), halt. diff --git a/Task/100-doors/Prolog/100-doors-4.pro b/Task/100-doors/Prolog/100-doors-4.pro new file mode 100644 index 0000000000..04252bdc72 --- /dev/null +++ b/Task/100-doors/Prolog/100-doors-4.pro @@ -0,0 +1,4 @@ +doors_optimized(N) :- + Max is floor(sqrt(N)), + forall(between(1, Max, I), + ( J is I*I,format('Door ~w is open.~n',[J]))). diff --git a/Task/100-doors/Pure/100-doors.pure b/Task/100-doors/Pure/100-doors.pure new file mode 100644 index 0000000000..3df83126df --- /dev/null +++ b/Task/100-doors/Pure/100-doors.pure @@ -0,0 +1,23 @@ +using system; + +// initialize doors as pairs: number, status where 0 means open +let doors = zip (1..100) (repeat 1); + +toogle (x,y) = x,~y; + +toogleEvery n d = map (tooglep n) d with + tooglep n d@((x,_)) = toogle d if ~(x mod n); + = d otherwise; end; + +// show description of given doors +status (n,x) = (str n) + (case x of + 1 = " close"; + 0 = " open"; end); + +let result = foldl (\a n -> toogleEvery n a) doors (1..100); + +// pretty print the result (only open doors) +showResult = do (puts.status) final when + final = filter open result with + open (_,x) = ~x; + end; end; diff --git a/Task/100-doors/REXX/100-doors-3.rexx b/Task/100-doors/REXX/100-doors-3.rexx deleted file mode 100644 index 2fccfc835e..0000000000 --- a/Task/100-doors/REXX/100-doors-3.rexx +++ /dev/null @@ -1,14 +0,0 @@ -/*REXX program to solve the 100 door puzzle, the easy-way version. */ -parse arg doors . /*get the first argument (# of doors.) */ -if doors=='' then doors=100 /*not specified? Then assume 100 doors*/ - /* 0 = closed. */ - /* 1 = open. */ -door.=0 /*assume all that all doors are closed.*/ -say -say 'For the' doors "doors problem, the following doors are open:" -say - do j=1 for doors /*process an easy pass-through. */ - p=j**2 /*square the door number. */ - if p>doors then leave /*if too large, we're done. */ - say right(p,20) - end /*j*/ diff --git a/Task/100-doors/REXX/100-doors-4.rexx b/Task/100-doors/REXX/100-doors-4.rexx deleted file mode 100644 index e4c9141b9a..0000000000 --- a/Task/100-doors/REXX/100-doors-4.rexx +++ /dev/null @@ -1,12 +0,0 @@ -/*REXX program to solve the 100 door puzzle, the easy-way version 2.*/ -parse arg doors . /*get the first argument (# of doors.) */ -if doors=='' then doors=1000 /*not specified? Then assume 1000 doors*/ - /* 0 = closed. */ - /* 1 = open. */ -door.=0 /*assume all that all doors are closed.*/ -say -say 'For the' doors "doors problem, the open doors are:" -say - do j=1 for doors while j**2<=doors /*limit pass-throughs.*/ - say right(j**2,20) - end /*j*/ diff --git a/Task/100-doors/Rust/100-doors-1.rust b/Task/100-doors/Rust/100-doors-1.rust index 64414e1adc..b224a24b57 100644 --- a/Task/100-doors/Rust/100-doors-1.rust +++ b/Task/100-doors/Rust/100-doors-1.rust @@ -1,6 +1,8 @@ +#![feature(inclusive_range_syntax)] + fn main() { let mut door_open = [false; 100]; - for pass in (1..101) { + for pass in 1...100 { let mut door = pass; while door <= 100 { door_open[door - 1] = !door_open[door - 1]; diff --git a/Task/100-doors/Rust/100-doors-2.rust b/Task/100-doors/Rust/100-doors-2.rust index 1a5371ce3a..fe4d9e1f42 100644 --- a/Task/100-doors/Rust/100-doors-2.rust +++ b/Task/100-doors/Rust/100-doors-2.rust @@ -1,9 +1,11 @@ -fn main() { - let squares: Vec<_> = (1..10+1).map(|n| n*n).collect(); - let is_square = |num| squares.binary_search(&num).is_ok(); +#![feature(inclusive_range_syntax)] - for i in 1..100+1 { - let state = if is_square(i) {"open"} else {"closed"}; - println!("Door {} is {}", i, state); - } +fn main() { + let doors = vec![false; 100].iter_mut().enumerate() + .map(|(door, door_state)| (1...100).into_iter() + .filter(|pass| door % pass == 0) + .map(|_| { *door_state = !*door_state; *door_state }) + .last().unwrap()).collect::>(); + + println!("{:?}", doors); } diff --git a/Task/100-doors/Rust/100-doors-3.rust b/Task/100-doors/Rust/100-doors-3.rust index e263967d6f..25610e11b3 100644 --- a/Task/100-doors/Rust/100-doors-3.rust +++ b/Task/100-doors/Rust/100-doors-3.rust @@ -1,5 +1,11 @@ +#![feature(inclusive_range_syntax)] + fn main() { - for i in 1u32..11u32{ - println!("Door {} is open", i.pow(2)); + let squares: Vec<_> = (1...10).map(|n| n*n).collect(); + let is_square = |num| squares.binary_search(&num).is_ok(); + + for i in 1...100 { + let state = if is_square(i) {"open"} else {"closed"}; + println!("Door {} is {}", i, state); } } diff --git a/Task/100-doors/Rust/100-doors-4.rust b/Task/100-doors/Rust/100-doors-4.rust new file mode 100644 index 0000000000..6ae27a5ded --- /dev/null +++ b/Task/100-doors/Rust/100-doors-4.rust @@ -0,0 +1,7 @@ +#![feature(inclusive_range_syntax)] + +fn main() { + for i in 1u32...10u32{ + println!("Door {} is open", i.pow(2)); + } +} diff --git a/Task/100-doors/Scilab/100-doors.scilab b/Task/100-doors/Scilab/100-doors.scilab new file mode 100644 index 0000000000..85f218cb86 --- /dev/null +++ b/Task/100-doors/Scilab/100-doors.scilab @@ -0,0 +1,14 @@ +doors=zeros(1,100); +for i = 1:100 + for j = i:i:100 + doors(j) = ~doors(j); + end +end +for i = 1:100 + if ( doors(i) ) + s = "open"; + else + s = "closed"; + end + printf("%d %s\n", i, s); +end diff --git a/Task/100-doors/Sidef/100-doors-1.sidef b/Task/100-doors/Sidef/100-doors-1.sidef index 249d06af23..5a27a2963d 100644 --- a/Task/100-doors/Sidef/100-doors-1.sidef +++ b/Task/100-doors/Sidef/100-doors-1.sidef @@ -1,13 +1,13 @@ var doors = [] -100.times { |pass| - 100.times { |i| - if (i % pass == 0) { +{ |pass| + { |i| + if (pass `divides` i) { doors[i] := false -> not! } - } -} + } << 1..100 +} << 1..100 -100.times { |i| - "Door %3d is %s\n".printf(i, doors[i] ? 'open' : 'closed') -} +{ |i| + say ("Door %3d is %s" % (i, doors[i] ? 'open' : 'closed')) +} << 1..100 diff --git a/Task/100-doors/Sidef/100-doors-2.sidef b/Task/100-doors/Sidef/100-doors-2.sidef index 34ece006fa..7661db4e6a 100644 --- a/Task/100-doors/Sidef/100-doors-2.sidef +++ b/Task/100-doors/Sidef/100-doors-2.sidef @@ -1,3 +1,3 @@ { |i| - "Door %3d is %s\n".printf(i, ["closed", "open"][i.is_sqr]) -} * 100 + "Door %3d is %s\n".printf(i, [i.is_sqr]) +} << 1..100 diff --git a/Task/100-doors/Simula/100-doors.simula b/Task/100-doors/Simula/100-doors.simula new file mode 100644 index 0000000000..d10c6d58f2 --- /dev/null +++ b/Task/100-doors/Simula/100-doors.simula @@ -0,0 +1,16 @@ +BEGIN + INTEGER I, PASS; + BOOLEAN ARRAY DOORS(1:100); + + FOR I := 1 STEP 1 UNTIL 100 DO + DOORS(I) := FALSE; + + FOR PASS := 1 STEP 1 UNTIL 100 DO + FOR I := PASS STEP PASS UNTIL 100 DO + DOORS(I) := NOT DOORS(I); + + FOR I := 1 STEP 1 UNTIL 100 DO + IF DOORS(I) + THEN BEGIN OUTTEXT("DOOR "); OUTINT(I,0); OUTTEXT(" IS OPEN"); OUTIMAGE END + +END. diff --git a/Task/100-doors/Smart-BASIC/100-doors.smart b/Task/100-doors/Smart-BASIC/100-doors.smart new file mode 100644 index 0000000000..4b54075202 --- /dev/null +++ b/Task/100-doors/Smart-BASIC/100-doors.smart @@ -0,0 +1,9 @@ +x=1!y=3!z=0 +PRINT "Open doors: ";x;" "; +DO + z=x+y + PRINT z;" "; + x=z + y=y+2 +UNTIL z>=100 +END diff --git a/Task/100-doors/Standard-ML/100-doors.ml b/Task/100-doors/Standard-ML/100-doors.ml new file mode 100644 index 0000000000..55f1a75b6b --- /dev/null +++ b/Task/100-doors/Standard-ML/100-doors.ml @@ -0,0 +1,19 @@ +datatype Door = Closed | Opened + +fun toggle Closed = Opened + | toggle Opened = Closed + +fun pass (steps, doors) = List.mapi (fn (k, door) => if (k+1) mod steps = 0 then toggle door else door) doors + +(* [1..n] *) +fun runs n = List.tabulate (n, fn k => k+1) + +fun run n = + let + val initialdoors = List.tabulate (n, fn _ => Closed) + val runs = runs n + in + foldl pass initialdoors runs + end + +fun opened_doors n = List.mapPartiali (fn (k, Closed) => NONE | (k, Opened) => SOME (k+1)) (run n) diff --git a/Task/100-doors/Stata/100-doors.stata b/Task/100-doors/Stata/100-doors.stata new file mode 100644 index 0000000000..05f4aeb261 --- /dev/null +++ b/Task/100-doors/Stata/100-doors.stata @@ -0,0 +1,24 @@ +clear all +set obs 100 +gen doors=0 +gen index=_n +forvalues i=1/100 { + quietly replace doors=1-doors if mod(_n,`i')==0 +} +list index if doors + + +-------+ + | index | + |-------| + 1. | 1 | + 4. | 4 | + 9. | 9 | + 16. | 16 | + 25. | 25 | + |-------| + 36. | 36 | + 49. | 49 | + 64. | 64 | + 81. | 81 | +100. | 100 | + +-------+ diff --git a/Task/100-doors/TI-83-BASIC/100-doors-1.ti-83 b/Task/100-doors/TI-83-BASIC/100-doors-1.ti-83 deleted file mode 100644 index 9fb8669fce..0000000000 --- a/Task/100-doors/TI-83-BASIC/100-doors-1.ti-83 +++ /dev/null @@ -1,16 +0,0 @@ -PROGRAM:DOORS100 -:ClrHome -:Disp "SETTING UP LIST" -:Disp "PLEASE WAIT..." -:For(I,1,100,1) -:0?L1(I) -:End -:ClrHome -:Disp "Pass" -:For(I,1,100,1) -:For(J,I,100,I) -:Output(2,1,I) -:not(L1(J))?L1(J) -:End -:End -:ClrHome diff --git a/Task/100-doors/TI-83-BASIC/100-doors-2.ti-83 b/Task/100-doors/TI-83-BASIC/100-doors-2.ti-83 deleted file mode 100644 index 18f28256a3..0000000000 --- a/Task/100-doors/TI-83-BASIC/100-doors-2.ti-83 +++ /dev/null @@ -1,4 +0,0 @@ -PROGRAM:DOORSOPT -:For(I,1,100,1) -:not(fPart(v(I)))?L1(I) -:End diff --git a/Task/100-doors/True-BASIC/100-doors.true b/Task/100-doors/True-BASIC/100-doors.true new file mode 100644 index 0000000000..2887a09f7d --- /dev/null +++ b/Task/100-doors/True-BASIC/100-doors.true @@ -0,0 +1,15 @@ +! Optimized solution with True BASIC + +OPTION NOLET +x = 1 +y = 3 +z = 0 +PRINT STR$(x) & " Open" +DO UNTIL z >= 100 +z = x + y +PRINT STR$(z) & " Open" +x = z +y = y + 2 +LOOP + +END diff --git a/Task/100-doors/X86-Assembly/100-doors.x86 b/Task/100-doors/X86-Assembly/100-doors.x86 new file mode 100644 index 0000000000..77879352e3 --- /dev/null +++ b/Task/100-doors/X86-Assembly/100-doors.x86 @@ -0,0 +1,66 @@ +; linux x86_64 + +section .data +open: db "open", 10 +closed: db "closed", 10 + +section .bss +doors resb 101 + +section .text + +global _start + +_start: +mov rax, 1 + mov bl, 0 + zeroset_door: + mov [doors + rax], bl + inc rax + cmp rax, 101 + jl zeroset_door + + mov rax, 0 + set_doors: + inc rax + cmp rax, 101 + je display_result + mov rbx, 0 + + make_pass: + add rbx, rax + cmp rbx, 101 + jge set_doors + not byte [doors + rbx] + jmp make_pass + + display_result: + mov rbx, 0 + display_door: + inc rbx + cmp rbx, 101 + je exit + cmp byte [doors + rbx], 0 + je print_closed + jmp print_open + + print_open: + mov rax, 1 + mov rdi, 1 + mov rsi, open + mov rdx, 5 + syscall + jmp display_door + + print_closed: + mov rax, 1 + mov rdi, 1 + mov rsi, closed + mov rdx, 7 + syscall + jmp display_door + + exit: + mov rax, 60 + mov rdi, 0 + syscall diff --git a/Task/100-doors/ZED/100-doors.zed b/Task/100-doors/ZED/100-doors.zed deleted file mode 100644 index 1304aceb45..0000000000 --- a/Task/100-doors/ZED/100-doors.zed +++ /dev/null @@ -1,47 +0,0 @@ -(100doors) -comment: returns the first 100 doors after making 100 passes -(always) -(pr) (first) 100 (passes) 1 (doors) - -(doors) -comment: start with an infinite list of closed doors -(always) -(c) "'closed" (doors) - -(passes) count doors -comment: count is greater than 100 -> make 100 passes -(>) count 100 -doors - -(passes) count doors -comment: count is not greater than 100 -> make 100 passes -(always) -(passes) (add1) count - (pass) count doors - -(pass) count doors -comment: takes a count and a list of doors -> makes a pass over the doors -(always) -(ZEDpass) count count doors - -(ZEDpass) count1 count2 doors -comment: count2 is one -> completes a pass over the doors -(=) count2 1 -(c) (toggle) (1) doors - (pass) count1 (!) doors - -(ZEDpass) count1 count2 doors -comment: count2 is greater than one -> completes a pass over the doors -(>) count2 1 -(c) (1) doors - (ZEDpass) count1 (sub1) count2 (!) doors - -(toggle) door -comment: door is closed -> toggles it -(=) door "'closed" -"'open" - -(toggle) door -comment: door is open -> toggles it -(=) door "'open" -"'closed" diff --git a/Task/100-doors/Zkl/100-doors.zkl b/Task/100-doors/Zkl/100-doors.zkl new file mode 100644 index 0000000000..a1099a639a --- /dev/null +++ b/Task/100-doors/Zkl/100-doors.zkl @@ -0,0 +1,3 @@ +doors:=List.createLong(100,False); // list of 100 Falses +foreach n,m in (100,[n..99,n+1]){ doors[m]=(not doors[m]); } //foreach{ foreach{} } +doors.filterNs().apply('+(1)).println(); diff --git a/Task/24-game-Solve/CoffeeScript/24-game-solve-1.coffee b/Task/24-game-Solve/CoffeeScript/24-game-solve-1.coffee deleted file mode 100644 index ca775d9813..0000000000 --- a/Task/24-game-Solve/CoffeeScript/24-game-solve-1.coffee +++ /dev/null @@ -1,87 +0,0 @@ -# This program tries to find some way to turn four digits into an arithmetic -# expression that adds up to 24. -# -# Example solution for 5, 7, 8, 8: -# (((8 + 7) * 8) / 5) - - -solve_24_game = (digits...) -> - # Create an array of objects for our helper functions - arr = for digit in digits - { - val: digit - expr: digit - } - combo4 arr... - -combo4 = (a, b, c, d) -> - arr = [a, b, c, d] - # Reduce this to a three-node problem by combining two - # nodes from the array. - permutations = [ - [0, 1, 2, 3] - [0, 2, 1, 3] - [0, 3, 1, 2] - [1, 2, 0, 3] - [1, 3, 0, 2] - [2, 3, 0, 1] - ] - for permutation in permutations - [i, j, k, m] = permutation - for combo in combos arr[i], arr[j] - answer = combo3 combo, arr[k], arr[m] - return answer if answer - null - -combo3 = (a, b, c) -> - arr = [a, b, c] - permutations = [ - [0, 1, 2] - [0, 2, 1] - [1, 2, 0] - ] - for permutation in permutations - [i, j, k] = permutation - for combo in combos arr[i], arr[j] - answer = combo2 combo, arr[k] - return answer if answer - null - -combo2 = (a, b) -> - for combo in combos a, b - return combo.expr if combo.val == 24 - null - -combos = (a, b) -> - [ - val: a.val + b.val - expr: "(#{a.expr} + #{b.expr})" - , - val: a.val * b.val - expr: "(#{a.expr} * #{b.expr})" - , - val: a.val - b.val - expr: "(#{a.expr} - #{b.expr})" - , - val: b.val - a.val - expr: "(#{b.expr} - #{a.expr})" - , - val: a.val / b.val - expr: "(#{a.expr} / #{b.expr})" - , - val: b.val / a.val - expr: "(#{b.expr} / #{a.expr})" - , - ] - -# test -do -> - rand_digit = -> 1 + Math.floor (9 * Math.random()) - - for i in [1..15] - a = rand_digit() - b = rand_digit() - c = rand_digit() - d = rand_digit() - solution = solve_24_game a, b, c, d - console.log "Solution for #{[a,b,c,d]}: #{solution ? 'no solution'}" diff --git a/Task/24-game-Solve/CoffeeScript/24-game-solve-2.coffee b/Task/24-game-Solve/CoffeeScript/24-game-solve-2.coffee deleted file mode 100644 index c0b84511eb..0000000000 --- a/Task/24-game-Solve/CoffeeScript/24-game-solve-2.coffee +++ /dev/null @@ -1,16 +0,0 @@ -> coffee 24_game.coffee -Solution for 8,3,1,8: ((1 + 8) * (8 / 3)) -Solution for 6,9,5,7: (6 - ((5 - 7) * 9)) -Solution for 4,2,1,1: no solution -Solution for 3,5,1,3: (((3 + 5) * 1) * 3) -Solution for 6,4,1,7: ((7 - (4 - 1)) * 6) -Solution for 8,1,3,1: (((8 + 1) - 1) * 3) -Solution for 6,1,3,3: (((6 + 1) * 3) + 3) -Solution for 7,1,5,6: (((7 - 1) * 5) - 6) -Solution for 4,2,3,1: ((3 + 1) * (4 + 2)) -Solution for 8,8,5,8: ((5 * 8) - (8 + 8)) -Solution for 3,8,4,1: ((1 - (3 - 8)) * 4) -Solution for 6,4,3,8: ((8 - (6 / 3)) * 4) -Solution for 2,1,8,7: (((2 * 8) + 1) + 7) -Solution for 5,2,7,5: ((2 * 7) + (5 + 5)) -Solution for 2,4,8,9: ((9 - (2 + 4)) * 8) diff --git a/Task/24-game-Solve/jq/24-game-solve-1.jq b/Task/24-game-Solve/Jq/24-game-solve-1.jq similarity index 100% rename from Task/24-game-Solve/jq/24-game-solve-1.jq rename to Task/24-game-Solve/Jq/24-game-solve-1.jq diff --git a/Task/24-game-Solve/jq/24-game-solve-2.jq b/Task/24-game-Solve/Jq/24-game-solve-2.jq similarity index 100% rename from Task/24-game-Solve/jq/24-game-solve-2.jq rename to Task/24-game-Solve/Jq/24-game-solve-2.jq diff --git a/Task/24-game-Solve/jq/24-game-solve-3.jq b/Task/24-game-Solve/Jq/24-game-solve-3.jq similarity index 100% rename from Task/24-game-Solve/jq/24-game-solve-3.jq rename to Task/24-game-Solve/Jq/24-game-solve-3.jq diff --git a/Task/24-game-Solve/jq/24-game-solve-4.jq b/Task/24-game-Solve/Jq/24-game-solve-4.jq similarity index 100% rename from Task/24-game-Solve/jq/24-game-solve-4.jq rename to Task/24-game-Solve/Jq/24-game-solve-4.jq diff --git a/Task/24-game-Solve/Kotlin/24-game-solve.kotlin b/Task/24-game-Solve/Kotlin/24-game-solve.kotlin new file mode 100644 index 0000000000..6e440c9537 --- /dev/null +++ b/Task/24-game-Solve/Kotlin/24-game-solve.kotlin @@ -0,0 +1,99 @@ +// version 1.1.3 + +import java.util.Random + +const val N_CARDS = 4 +const val SOLVE_GOAL = 24 +const val MAX_DIGIT = 9 + +class Frac(val num: Int, val den: Int) + +enum class OpType { NUM, ADD, SUB, MUL, DIV } + +class Expr( + var op: OpType = OpType.NUM, + var left: Expr? = null, + var right: Expr? = null, + var value: Int = 0 +) + +fun showExpr(e: Expr?, prec: OpType, isRight: Boolean) { + if (e == null) return + val op = when (e.op) { + OpType.NUM -> { print(e.value); return } + OpType.ADD -> " + " + OpType.SUB -> " - " + OpType.MUL -> " x " + OpType.DIV -> " / " + } + + if ((e.op == prec && isRight) || e.op < prec) print("(") + showExpr(e.left, e.op, false) + print(op) + showExpr(e.right, e.op, true) + if ((e.op == prec && isRight) || e.op < prec) print(")") +} + +fun evalExpr(e: Expr?): Frac { + if (e == null) return Frac(0, 1) + if (e.op == OpType.NUM) return Frac(e.value, 1) + val l = evalExpr(e.left) + val r = evalExpr(e.right) + return when (e.op) { + OpType.ADD -> Frac(l.num * r.den + l.den * r.num, l.den * r.den) + OpType.SUB -> Frac(l.num * r.den - l.den * r.num, l.den * r.den) + OpType.MUL -> Frac(l.num * r.num, l.den * r.den) + OpType.DIV -> Frac(l.num * r.den, l.den * r.num) + else -> throw IllegalArgumentException("Unknown op: ${e.op}") + } +} + +fun solve(ea: Array, len: Int): Boolean { + if (len == 1) { + val final = evalExpr(ea[0]) + if (final.num == final.den * SOLVE_GOAL && final.den != 0) { + showExpr(ea[0], OpType.NUM, false) + return true + } + } + + val ex = arrayOfNulls(N_CARDS) + for (i in 0 until len - 1) { + for (j in i + 1 until len) ex[j - 1] = ea[j] + val node = Expr() + ex[i] = node + for (j in i + 1 until len) { + node.left = ea[i] + node.right = ea[j] + for (k in OpType.values().drop(1)) { + node.op = k + if (solve(ex, len - 1)) return true + } + node.left = ea[j] + node.right = ea[i] + node.op = OpType.SUB + if (solve(ex, len - 1)) return true + node.op = OpType.DIV + if (solve(ex, len - 1)) return true + ex[j] = ea[j] + } + ex[i] = ea[i] + } + return false +} + +fun solve24(n: IntArray) = + solve (Array(N_CARDS) { Expr(value = n[it]) }, N_CARDS) + +fun main(args: Array) { + val r = Random() + val n = IntArray(N_CARDS) + for (j in 0..9) { + for (i in 0 until N_CARDS) { + n[i] = 1 + r.nextInt(MAX_DIGIT) + print(" ${n[i]}") + } + print(": ") + println(if (solve24(n)) "" else "No solution") + } +} diff --git a/Task/24-game-Solve/ProDOS/24-game-solve-1.dos b/Task/24-game-Solve/ProDOS/24-game-solve-1.dos deleted file mode 100644 index 4da948715f..0000000000 --- a/Task/24-game-Solve/ProDOS/24-game-solve-1.dos +++ /dev/null @@ -1,35 +0,0 @@ -editvar /modify -random- = <10 -:a -editvar /newvar /withothervar /value=-random- /title=1 -editvar /newvar /withothervar /value=-random- /title=2 -editvar /newvar /withothervar /value=-random- /title=3 -editvar /newvar /withothervar /value=-random- /title=4 -printline These are your four digits: -1- -2- -3- -4- -printline Use an algorithm to make the number 24. -editvar /newvar /value=a /userinput=1 /title=Algorithm: -do -a- -if -a- /hasvalue 24 printline Your algorithm worked! & goto :b ( -) else printline Your algorithm did not work. -editvar /newvar /value=b /userinput=1 /title=Do you want to see how you could have done it? -if -b- /hasvalue y goto :c else goto :b -:b -editvar /newvar /value=c /userinput=1 /title=Do you want to play again? -if -c- /hasvalue y goto :a else exitcurrentprogram -:c -editvar /newvar /value=do -1- + -2- + -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve -editvar /newvar /value=do -1- - -2- + -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve -editvar /newvar /value=do -1- / -2- + -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve -editvar /newvar /value=do -1- * -2- + -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve -editvar /newvar /value=do -1- + -2- - -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve -editvar /newvar /value=do -1- + -2- / -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve -editvar /newvar /value=do -1- + -2- * -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve -editvar /newvar /value=do -1- + -2- + -3- - -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve -editvar /newvar /value=do -1- + -2- + -3- / -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve -editvar /newvar /value=do -1- + -2- + -3- * -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve -editvar /newvar /value=do -1- - -2- - -3- - -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve -editvar /newvar /value=do -1- / -2- / -3- / -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve -editvar /newvar /value=do -1- * -2- * -3- * -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve -:solve -printline you could have done it by doing -c- -stoptask -goto :b diff --git a/Task/24-game-Solve/ProDOS/24-game-solve-2.dos b/Task/24-game-Solve/ProDOS/24-game-solve-2.dos deleted file mode 100644 index 69d8b8a977..0000000000 --- a/Task/24-game-Solve/ProDOS/24-game-solve-2.dos +++ /dev/null @@ -1,11 +0,0 @@ -These are your four digits: 1 4 5 2 -Use an algorithm to make the number 24. -Algorithm: 4 + 2 - 5 + 1 -Your algorithm did not work. -Do you want to play again? y - -These are your four digits: 1 8 9 6 -Use an algorithm to make the number 24. -Algorithm: 1 + 8 + 9 + 6 -Your algorithm worked! -Do you want to play again? n diff --git a/Task/24-game-Solve/Rust/24-game-solve.rust b/Task/24-game-Solve/Rust/24-game-solve.rust new file mode 100644 index 0000000000..39fb5c606b --- /dev/null +++ b/Task/24-game-Solve/Rust/24-game-solve.rust @@ -0,0 +1,165 @@ +#[derive(Clone, Copy, Debug)] +enum Operator { + Sub, + Plus, + Mul, + Div, +} + +#[derive(Clone, Debug)] +struct Factor { + content: String, + value: i32, +} + +fn apply(op: Operator, left: &[Factor], right: &[Factor]) -> Vec { + let mut ret = Vec::new(); + for l in left.iter() { + for r in right.iter() { + use Operator::*; + ret.push(match op { + Sub if l.value > r.value => Factor { + content: format!("({} - {})", l.content, r.content), + value: l.value - r.value, + }, + Plus => Factor { + content: format!("({} + {})", l.content, r.content), + value: l.value + r.value, + }, + Mul => Factor { + content: format!("({} x {})", l.content, r.content), + value: l.value * r.value, + }, + Div if l.value >= r.value && r.value > 0 && l.value % r.value == 0 => Factor { + content: format!("({} / {})", l.content, r.content), + value: l.value / r.value, + }, + _ => continue, + }) + } + } + ret +} + +fn calc(op: [Operator; 3], numbers: [i32; 4]) -> Vec { + fn calc(op: &[Operator], numbers: &[i32], acc: &[Factor]) -> Vec { + use Operator::*; + if op.is_empty() { + return Vec::from(acc) + } + let mut ret = Vec::new(); + let mono_factor = [Factor { + content: numbers[0].to_string(), + value: numbers[0], + }]; + match op[0] { + Mul => ret.extend_from_slice(&apply(op[0], acc, &mono_factor)), + Div => { + ret.extend_from_slice(&apply(op[0], acc, &mono_factor)); + ret.extend_from_slice(&apply(op[0], &mono_factor, acc)); + }, + Sub => { + ret.extend_from_slice(&apply(op[0], acc, &mono_factor)); + ret.extend_from_slice(&apply(op[0], &mono_factor, acc)); + }, + Plus => ret.extend_from_slice(&apply(op[0], acc, &mono_factor)), + } + calc(&op[1..], &numbers[1..], &ret) + } + calc(&op, &numbers[1..], &[Factor { content: numbers[0].to_string(), value: numbers[0] }]) +} + +fn solutions(numbers: [i32; 4]) -> Vec { + use std::collections::hash_set::HashSet; + let mut ret = Vec::new(); + let mut hash_set = HashSet::new(); + + for ops in OpIter(0) { + for o in orders().iter() { + let numbers = apply_order(numbers, o); + let r = calc(ops, numbers); + ret.extend(r.into_iter().filter(|&Factor { value, ref content }| value == 24 && hash_set.insert(content.to_owned()))) + } + } + ret +} + +fn main() { + let mut numbers = Vec::new(); + if let Some(input) = std::env::args().skip(1).next() { + for c in input.chars() { + if let Ok(n) = c.to_string().parse() { + numbers.push(n) + } + if numbers.len() == 4 { + let numbers = [numbers[0], numbers[1], numbers[2], numbers[3]]; + let solutions = solutions(numbers); + let len = solutions.len(); + if len == 0 { + println!("no solution for {}, {}, {}, {}", numbers[0], numbers[1], numbers[2], numbers[3]); + return + } + println!("solutions for {}, {}, {}, {}", numbers[0], numbers[1], numbers[2], numbers[3]); + for s in solutions { + println!("{}", s.content) + } + println!("{} solutions found", len); + return + } + } + } else { + println!("empty input") + } +} + + +struct OpIter (usize); + +impl Iterator for OpIter { + type Item = [Operator; 3]; + fn next(&mut self) -> Option<[Operator; 3]> { + use Operator::*; + const OPTIONS: [Operator; 4] = [Mul, Sub, Plus, Div]; + if self.0 >= 1 << 6 { + return None + } + let f1 = OPTIONS[(self.0 & (3 << 4)) >> 4]; + let f2 = OPTIONS[(self.0 & (3 << 2)) >> 2]; + let f3 = OPTIONS[(self.0 & (3 << 0)) >> 0]; + self.0 += 1; + Some([f1, f2, f3]) + } +} + +fn orders() -> [[usize; 4]; 24] { + [ + [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] + ] +} + +fn apply_order(numbers: [i32; 4], order: &[usize; 4]) -> [i32; 4] { + [numbers[order[0]], numbers[order[1]], numbers[order[2]], numbers[order[3]]] +} diff --git a/Task/24-game-Solve/Sidef/24-game-solve-1.sidef b/Task/24-game-Solve/Sidef/24-game-solve-1.sidef index 724691c463..0ed8ccd5a4 100644 --- a/Task/24-game-Solve/Sidef/24-game-solve-1.sidef +++ b/Task/24-game-Solve/Sidef/24-game-solve-1.sidef @@ -4,28 +4,29 @@ var formats = [ '(%d %s %d) %s (%d %s %d)', '%d %s ((%d %s %d) %s %d)', '%d %s (%d %s (%d %s %d))', -]; +] -var op = %w( + - * / ); -var operators = op.map { |a| op.map {|b| op.map {|c| "#{a} #{b} #{c}" } } }.flatten; +var op = %w( + - * / ) +var operators = op.map { |a| op.map {|b| op.map {|c| "#{a} #{b} #{c}" } } }.flat loop { - var input = Sys.scanln("Enter four integers or 'q' to exit: "); - input == 'q' && break; + var input = read("Enter four integers or 'q' to exit: ", String) + input == 'q' && break - input ~~ /^\h*[1-9]\h+[1-9]\h+[1-9]\h+[1-9]\h*$/ || ( - say "Invalid input!"; next; - ); + if (input !~ /^\h*[1-9]\h+[1-9]\h+[1-9]\h+[1-9]\h*$/) { + say "Invalid input!" + next + } - var n = input.split.map{.to_i}; - var numbers = n.permute; + var n = input.split.map{.to_n} + var numbers = n.permutations formats.each { |format| numbers.each { |n| operators.each { |operator| var o = operator.split; - var str = (format % (n[0],o[0],n[1],o[1],n[2],o[2],n[3])); - eval(str) == 24 && say str; + var str = (format % (n[0],o[0],n[1],o[1],n[2],o[2],n[3])) + eval(str) == 24 && say str } } } diff --git a/Task/24-game-Solve/Sidef/24-game-solve-2.sidef b/Task/24-game-Solve/Sidef/24-game-solve-2.sidef index c5290c51a3..141ff693d3 100644 --- a/Task/24-game-Solve/Sidef/24-game-solve-2.sidef +++ b/Task/24-game-Solve/Sidef/24-game-solve-2.sidef @@ -1,56 +1,57 @@ var formats = [ {|a,b,c| - Hash.new( + Hash( func => {|d,e,f,g| ((d.$a(e)).$b(f)).$c(g) }, format => "((%d #{a} %d) #{b} %d) #{c} %d" ) }, {|a,b,c| - Hash.new( + Hash( func => {|d,e,f,g| (d.$a((e.$b(f)))).$c(g) }, format => "(%d #{a} (%d #{b} %d)) #{c} %d", ) }, {|a,b,c| - Hash.new( + Hash( func => {|d,e,f,g| (d.$a(e)).$b(f.$c(g)) }, format => "(%d #{a} %d) #{b} (%d #{c} %d)", ) }, {|a,b,c| - Hash.new( + Hash( func => {|d,e,f,g| (d.$a(e)).$b(f.$c(g)) }, format => "(%d #{a} %d) #{b} (%d #{c} %d)", ) }, {|a,b,c| - Hash.new( + Hash( func => {|d,e,f,g| d.$a(e.$b(f.$c(g))) }, format => "%d #{a} (%d #{b} (%d #{c} %d))", ) }, ]; -var op = %w( + - * / ); +var op = %w( + - * / ) var blocks = op.map { |a| op.map { |b| op.map { |c| formats.map { |format| format(a,b,c) -}}}}.flatten; +}}}}.flat loop { var input = Sys.scanln("Enter four integers or 'q' to exit: "); input == 'q' && break; - input ~~ /^\h*[1-9]\h+[1-9]\h+[1-9]\h+[1-9]\h*$/ || ( - say "Invalid input!"; next; - ); + if (input !~ /^\h*[1-9]\h+[1-9]\h+[1-9]\h+[1-9]\h*$/) { + say "Invalid input!" + next + } - var n = input.split.map{.to_num}; - var numbers = n.permute; + var n = input.split.map{.to_n} + var numbers = n.permutations blocks.each { |block| numbers.each { |n| if (block{:func}.call(n...) == 24) { - say (block{:format} % (n...)); + say (block{:format} % (n...)) } } } diff --git a/Task/24-game-Solve/Simula/24-game-solve.simula b/Task/24-game-Solve/Simula/24-game-solve.simula new file mode 100644 index 0000000000..197e2c7c66 --- /dev/null +++ b/Task/24-game-Solve/Simula/24-game-solve.simula @@ -0,0 +1,297 @@ +BEGIN + + + + CLASS EXPR; + BEGIN + + + REAL PROCEDURE POP; + BEGIN + IF STACKPOS > 0 THEN + BEGIN STACKPOS := STACKPOS - 1; POP := STACK(STACKPOS); END; + END POP; + + + PROCEDURE PUSH(NEWTOP); REAL NEWTOP; + BEGIN + STACK(STACKPOS) := NEWTOP; + STACKPOS := STACKPOS + 1; + END PUSH; + + + REAL PROCEDURE CALC(OPERATOR, ERR); CHARACTER OPERATOR; LABEL ERR; + BEGIN + REAL X, Y; X := POP; Y := POP; + IF OPERATOR = '+' THEN PUSH(Y + X) + ELSE IF OPERATOR = '-' THEN PUSH(Y - X) + ELSE IF OPERATOR = '*' THEN PUSH(Y * X) + ELSE IF OPERATOR = '/' THEN BEGIN + IF X = 0 THEN + BEGIN + EVALUATEDERR :- "DIV BY ZERO"; + GOTO ERR; + END; + PUSH(Y / X); + END + ELSE + BEGIN + EVALUATEDERR :- "UNKNOWN OPERATOR"; + GOTO ERR; + END + END CALC; + + + PROCEDURE READCHAR(CH); NAME CH; CHARACTER CH; + BEGIN + IF T.MORE THEN CH := T.GETCHAR ELSE CH := EOT; + END READCHAR; + + + PROCEDURE SKIPWHITESPACE(CH); NAME CH; CHARACTER CH; + BEGIN + WHILE (CH = SPACE) OR (CH = TAB) OR (CH = CR) OR (CH = LF) DO + READCHAR(CH); + END SKIPWHITESPACE; + + + PROCEDURE BUSYBOX(OP, ERR); INTEGER OP; LABEL ERR; + BEGIN + CHARACTER OPERATOR; + REAL NUMBR; + BOOLEAN NEGATIVE; + + SKIPWHITESPACE(CH); + + IF OP = EXPRESSION THEN + BEGIN + + NEGATIVE := FALSE; + WHILE (CH = '+') OR (CH = '-') DO + BEGIN + IF CH = '-' THEN NEGATIVE := NOT NEGATIVE; + READCHAR(CH); + END; + + BUSYBOX(TERM, ERR); + + IF NEGATIVE THEN + BEGIN + NUMBR := POP; PUSH(0 - NUMBR); + END; + + WHILE (CH = '+') OR (CH = '-') DO + BEGIN + OPERATOR := CH; READCHAR(CH); + BUSYBOX(TERM, ERR); CALC(OPERATOR, ERR); + END; + + END + ELSE IF OP = TERM THEN + BEGIN + + BUSYBOX(FACTOR, ERR); + WHILE (CH = '*') OR (CH = '/') DO + BEGIN + OPERATOR := CH; READCHAR(CH); + BUSYBOX(FACTOR, ERR); CALC(OPERATOR, ERR) + END + + END + ELSE IF OP = FACTOR THEN + BEGIN + + IF (CH = '+') OR (CH = '-') THEN + BUSYBOX(EXPRESSION, ERR) + ELSE IF (CH >= '0') AND (CH <= '9') THEN + BUSYBOX(NUMBER, ERR) + ELSE IF CH = '(' THEN + BEGIN + READCHAR(CH); + BUSYBOX(EXPRESSION, ERR); + IF CH = ')' THEN READCHAR(CH) ELSE GOTO ERR; + END + ELSE GOTO ERR; + + END + ELSE IF OP = NUMBER THEN + BEGIN + + NUMBR := 0; + WHILE (CH >= '0') AND (CH <= '9') DO + BEGIN + NUMBR := 10 * NUMBR + RANK(CH) - RANK('0'); READCHAR(CH); + END; + IF CH = '.' THEN + BEGIN + REAL FAKTOR; + READCHAR(CH); + FAKTOR := 10; + WHILE (CH >= '0') AND (CH <= '9') DO + BEGIN + NUMBR := NUMBR + (RANK(CH) - RANK('0')) / FAKTOR; + FAKTOR := 10 * FAKTOR; + READCHAR(CH); + END; + END; + PUSH(NUMBR); + + END; + + SKIPWHITESPACE(CH); + + END BUSYBOX; + + + BOOLEAN PROCEDURE EVAL(INP); TEXT INP; + BEGIN + EVALUATEDERR :- NOTEXT; + STACKPOS := 0; + T :- COPY(INP.STRIP); + READCHAR(CH); + BUSYBOX(EXPRESSION, ERRORLABEL); + IF NOT T.MORE AND STACKPOS = 1 AND CH = EOT THEN + BEGIN + EVALUATED := POP; + EVAL := TRUE; + GOTO NOERRORLABEL; + END; + ERRORLABEL: + EVAL := FALSE; + IF EVALUATEDERR = NOTEXT THEN + EVALUATEDERR :- "INVALID EXPRESSION: " & INP; + NOERRORLABEL: + END EVAL; + + + REAL PROCEDURE RESULT; + RESULT := EVALUATED; + + TEXT PROCEDURE ERR; + ERR :- EVALUATEDERR; + + TEXT T; + + INTEGER EXPRESSION; + INTEGER TERM; + INTEGER FACTOR; + INTEGER NUMBER; + + CHARACTER TAB; + CHARACTER LF; + CHARACTER CR; + CHARACTER SPACE; + CHARACTER EOT; + + CHARACTER CH; + REAL ARRAY STACK(0:31); + INTEGER STACKPOS; + + REAL EVALUATED; + TEXT EVALUATEDERR; + + EXPRESSION := 1; + TERM := 2; + FACTOR := 3; + NUMBER := 4; + + TAB := CHAR(9); + LF := CHAR(10); + CR := CHAR(13); + SPACE := CHAR(32); + EOT := CHAR(0); + + END EXPR; + + + INTEGER ARRAY DIGITS(1:4); + INTEGER SEED, I; + REF(EXPR) E; + + INTEGER SOLUTION; + INTEGER D1,D2,D3,D4; + INTEGER O1,O2,O3; + TEXT OPS; + + OPS :- "+-*/"; + + E :- NEW EXPR; + OUTTEXT("ENTER FOUR INTEGERS: "); + OUTIMAGE; + FOR I := 1 STEP 1 UNTIL 4 DO DIGITS(I) := ININT; !RANDINT(0, 9, SEED); + + ! DIGITS ; + FOR D1 := 1 STEP 1 UNTIL 4 DO + FOR D2 := 1 STEP 1 UNTIL 4 DO IF D2 <> D1 THEN + FOR D3 := 1 STEP 1 UNTIL 4 DO IF D3 <> D2 AND + D3 <> D1 THEN + FOR D4 := 1 STEP 1 UNTIL 4 DO IF D4 <> D3 AND + D4 <> D2 AND + D4 <> D1 THEN + ! OPERATORS ; + FOR O1 := 1 STEP 1 UNTIL 4 DO + FOR O2 := 1 STEP 1 UNTIL 4 DO + FOR O3 := 1 STEP 1 UNTIL 4 DO + BEGIN + PROCEDURE P(FMT); TEXT FMT; + BEGIN + INTEGER PLUS; + TRY.SETPOS(1); + WHILE FMT.MORE DO + BEGIN + CHARACTER C; + C := FMT.GETCHAR; + IF (C >= '1') AND (C <= '4') THEN + BEGIN + INTEGER DIG; CHARACTER NCH; + DIG := IF C = '1' THEN DIGITS(D1) + ELSE IF C = '2' THEN DIGITS(D2) + ELSE IF C = '3' THEN DIGITS(D3) + ELSE DIGITS(D4); + NCH := CHAR( DIG + RANK('0') ); + TRY.PUTCHAR(NCH); + END + ELSE IF C = '+' THEN + BEGIN + PLUS := PLUS + 1; + OPS.SETPOS(IF PLUS = 1 THEN O1 ELSE + IF PLUS = 2 THEN O2 + ELSE O3); + TRY.PUTCHAR(OPS.GETCHAR); + END + ELSE IF (C = '(') OR (C = ')') OR (C = ' ') THEN + TRY.PUTCHAR(C) + ELSE + ERROR("ILLEGAL EXPRESSION"); + END; + IF E.EVAL(TRY) THEN + BEGIN + IF ABS(E.RESULT - 24) < 0.001 THEN + BEGIN + SOLUTION := SOLUTION + 1; + OUTTEXT(TRY); OUTTEXT(" = "); + OUTFIX(E.RESULT, 4, 10); + OUTIMAGE; + END; + END + ELSE + BEGIN + IF E.ERR <> "DIV BY ZERO" THEN + BEGIN + OUTTEXT(TRY); OUTIMAGE; + OUTTEXT(E.ERR); OUTIMAGE; + END; + END; + END P; + TEXT TRY; + TRY :- BLANKS(17); + P("(1 + 2) + (3 + 4)"); + P("(1 + (2 + 3)) + 4"); + P("((1 + 2) + 3) + 4"); + P("1 + ((2 + 3) + 4)"); + P("1 + (2 + (3 + 4))"); + END; + OUTINT(SOLUTION, 0); + OUTTEXT(" SOLUTIONS FOUND"); + OUTIMAGE; +END. diff --git a/Task/24-game-Solve/Zkl/24-game-solve-1.zkl b/Task/24-game-Solve/Zkl/24-game-solve-1.zkl new file mode 100644 index 0000000000..1e789250a3 --- /dev/null +++ b/Task/24-game-Solve/Zkl/24-game-solve-1.zkl @@ -0,0 +1,26 @@ +var [const] H=Utils.Helpers; +fcn u(xs){ xs.reduce(fcn(us,s){us.holds(s) and us or us.append(s) },L()) } +var ops=u(H.combosK(3,"+-*/".split("")).apply(H.permute).flatten()); +var fs=T( + fcn f0(a,b,c,d,x,y,z){ Op(z)(Op(y)(Op(x)(a,b),c),d) }, // ((AxB)yC)zD + fcn f1(a,b,c,d,x,y,z){ Op(y)(Op(x)(a,b),Op(z)(c,d)) }, // (AxB)y(CzD) + fcn f2(a,b,c,d,x,y,z){ Op(z)(Op(x)(a,Op(y)(b,c)),d) }, // (Ax(ByC))zD + fcn f3(a,b,c,d,x,y,z){ Op(x)(a,Op(z)(Op(y)(b,c),d)) }, // Ax((ByC)zD) + fcn f4(a,b,c,d,x,y,z){ Op(x)(a,Op(y)(b,Op(z)(c,d))) }, // Ax(By(CzD)) +); + +var fts= // format strings for human readable formulas + T("((d.d).d).d", "(d.d).(d.d)", "(d.(d.d)).d", "d.((d.d).d)", "d.(d.(d.d))") + .pump(List,T("replace","d","%d"),T("replace",".","%s")); + +fcn f2s(digits,ops,f){ + fts[f.name[1].toInt()].fmt(digits.zip(ops).flatten().xplode(),digits[3]); +} + +fcn game24Solver(digitsString){ + digits:=digitsString.split("").apply("toFloat"); + [[(digits4,ops3,f); H.permute(digits); ops; // list comprehension + fs,{ try{f(digits4.xplode(),ops3.xplode()).closeTo(24,0.001) } + catch(MathError){ False } }; + { f2s(digits4,ops3,f) }]]; +} diff --git a/Task/24-game-Solve/Zkl/24-game-solve-2.zkl b/Task/24-game-Solve/Zkl/24-game-solve-2.zkl new file mode 100644 index 0000000000..756c4bf0f3 --- /dev/null +++ b/Task/24-game-Solve/Zkl/24-game-solve-2.zkl @@ -0,0 +1,3 @@ +solutions:=u(game24Solver(ask(0,"digits: "))); +println(solutions.len()," solutions:"); +solutions.apply2(Console.println); diff --git a/Task/24-game/APL/24-game.apl b/Task/24-game/APL/24-game.apl new file mode 100644 index 0000000000..6c0d56c936 --- /dev/null +++ b/Task/24-game/APL/24-game.apl @@ -0,0 +1,8 @@ +tfgame←{⎕IO←1 + ⎕←d←?⍵⍴9 + i←⍞ + u[⍋u←{⍎¨⍣(0≠≢⍵)⊢⍵}(i∊'1234567890')⊆i]≢d[⍋d]:'nope' + ~∧/((~b←i∊'1234567890')/i)∊'+-×÷()':'nope' + 24≠⍎i:'nope' + 'Yeah!' +} diff --git a/Task/24-game/Batch-File/24-game.bat b/Task/24-game/Batch-File/24-game.bat deleted file mode 100644 index 41dad929ea..0000000000 --- a/Task/24-game/Batch-File/24-game.bat +++ /dev/null @@ -1,150 +0,0 @@ -@set @dummy=0 /* - -::24.bat -:: -::Batch file implemetnation of the 24 Game where a player is given four random -::digits n, where 1 <= n <= 9, and needs to provide a simple arithmetic -::operation that does evaluate to 24. -:: -::Please open the Batch File Directly to play... - -@echo off -setlocal enabledelayedexpansion -title The 24 Game Batch File -cls -echo. -echo The 24 Game -echo. -echo Given four digits, provide a simple arithmetic expression -echo that evaluates to 24 using +,-,*,/. -echo. -echo Reminders (Please read): -echo. -echo 1. Type 'new' (NO quotes) - Fresh digits -echo 2. Type 'show' (NO quotes) - Show digits -echo 3. Type 'exit' (NO quotes) - Quit game -echo 4. Combining two digits as one number is NOT allowed. -echo 5. Use each digit only ONCE in expressions. -echo 6. Use ONLY the Parentheses as the groupting symbols. -echo 7. Do not make any digit Negative. -echo. -echo Why do someone wants to not follow the reminders? To trick me, right? ;) -echo. -pause - -:NEW -set TRY=0 - -::Get four random digits -set /a "DIGIT_1=%RANDOM%%%9+1" -set /a "DIGIT_2=%RANDOM%%%9+1" -set /a "DIGIT_3=%RANDOM%%%9+1" -set /a "DIGIT_4=%RANDOM%%%9+1" - -cls -echo. -echo The 24 Game -echo. -goto SHOW - -::Main Program Loop -:MAIN -set /a TRY+=1 -set ANSWER= -set "TMP_DIGIT_1=%DIGIT_1%" -set "TMP_DIGIT_2=%DIGIT_2%" -set "TMP_DIGIT_3=%DIGIT_3%" -set "TMP_DIGIT_4=%DIGIT_4%" - -::Prompt for an answer -echo. -set /p ANSWER="Try %TRY%: " - -::Determine if the player inputs a "good" try (input validation...) -if /i "!ANSWER!"=="NEW" goto NEW -if /i "!ANSWER!"=="SHOW" goto SHOW -if /i "!ANSWER!"=="EXIT" goto ABORT - -set ANSWER=!ANSWER: =! -set DIGITS_USED=0&set COUNTER=0 - -:LOOP -set CURR_DIGIT=!ANSWER:~%COUNTER%,1! -if "!CURR_DIGIT!"=="%TMP_DIGIT_1%" (set "TMP_DIGIT_1=X"&goto NEXTCHARSCAN1) -if "!CURR_DIGIT!"=="%TMP_DIGIT_2%" (set "TMP_DIGIT_2=X"&goto NEXTCHARSCAN1) -if "!CURR_DIGIT!"=="%TMP_DIGIT_3%" (set "TMP_DIGIT_3=X"&goto NEXTCHARSCAN1) -if "!CURR_DIGIT!"=="%TMP_DIGIT_4%" (set "TMP_DIGIT_4=X"&goto NEXTCHARSCAN1) -if "!CURR_DIGIT!"=="" goto ALMOST -if "!CURR_DIGIT!"==")" goto SCANMORE -if "!CURR_DIGIT!"=="(" goto SCANMORE -if "!CURR_DIGIT!"=="+" goto NEXTCHARSCAN2 -if "!CURR_DIGIT!"=="-" goto DONTALLOWNEGATIVES -if "!CURR_DIGIT!"=="*" goto NEXTCHARSCAN2 -if "!CURR_DIGIT!"=="/" goto NEXTCHARSCAN2 -goto ERROR_ICHAR_FOUND - -:NEXTCHARSCAN1 -set /a NEXT=%COUNTER%+1 -set NEXT_CHAR=!ANSWER:~%NEXT%,1! -for /l %%w in (1,1,9) do ( -if "!NEXT_CHAR!"=="%%w" goto ERROR_POSITION -) -goto :SCANMORE -:DONTALLOWNEGATIVES -set /a NEXT=%COUNTER%-1 -if "%NEXT%"=="-1" goto ERROR_NEGA -set NEXT_CHAR=!ANSWER:~%NEXT%,1! -for /l %%z in (1,1,9) do ( -if "!NEXT_CHAR!"=="%%z" goto NEXTCHARSCAN2 -) -if "!NEXT_CHAR!"=="(" goto ERROR_NEGA -if "!NEXT_CHAR!"==")" goto NEXTCHARSCAN2 -goto ERROR_NEGA -:NEXTCHARSCAN2 -set /a NEXT=%COUNTER%+1 -set NEXT_CHAR=!ANSWER:~%NEXT%,1! -for %%y in (+,-,/) do ( -if "!NEXT_CHAR!"=="%%y" goto ERROR_TRICK -) -:SCANMORE -set /a "COUNTER+=1"&goto LOOP - -:ALMOST -if not "%TMP_DIGIT_1%%TMP_DIGIT_2%%TMP_DIGIT_3%%TMP_DIGIT_4%"=="XXXX" goto ERROR_CHARS -::(SIGH) Input passed... Now, calculate and evaluate result -set "RESULT=" -for /f "usebackq delims=" %%x in (`cscript //nologo //e:jscript "%~f0" "%ANSWER%" 2^>nul`) do set RESULT=%%x -::Wait... Input is STILL erroneous??? -if "%RESULT%"=="" goto ERROR_SYNTAX -::YES!!! Correct Expression??? -if "%RESULT%"=="24" goto END - -::The Outputs - -echo Wrong Answer [%RESULT% is not equal to 24.]&goto MAIN -:ERROR_CHARS -echo Invalid input [Please use all the digits above ONCE.]&goto MAIN -:ERROR_ICHAR_FOUND -echo Invalid input [An invalid character is found... C'mon...]&goto MAIN -:ERROR_SYNTAX -echo Invalid input [Syntax Error... Please answer seriously... I'm begging you...]&goto MAIN -:ERROR_POSITION -echo Invalid input [Sorry, digit concatenation is not allowed.]&goto MAIN -:ERROR_TRICK -echo Invalid input [Are you Playing the Game Seriously?]&goto MAIN -:ERROR_NEGA -echo Invalid input [Do not Make any Digit Negative.]&goto MAIN -:SHOW -echo Given digits: %DIGIT_1% %DIGIT_2% %DIGIT_3% %DIGIT_4%&goto MAIN -:END -echo Correct Input [Congratulations^^!] -echo. -echo Press any char key for a new game, or close this window to exit... -pause>nul -goto NEW -:ABORT -echo. -exit -::*/ - -WScript.echo(eval(WScript.arguments(0))); diff --git a/Task/24-game/Elena/24-game.elena b/Task/24-game/Elena/24-game.elena index 8c436af44c..4a5af756b7 100644 --- a/Task/24-game/Elena/24-game.elena +++ b/Task/24-game/Elena/24-game.elena @@ -1,96 +1,95 @@ -#define system. -#define system'routines. -#define system'collections. -#define system'dynamic. -#define extensions. +import system'routines. +import system'collections. +import system'dynamic. +import extensions. -#class ExpressionTree +class ExpressionTree { - #field theTree. + object theTree. - #constructor new : aLiteral + constructor new : aLiteral [ - #var aLevel := Integer new:0. + var aLevel := Integer new:0. - aLiteral run &each: ch + aLiteral forEach(:ch) [ - #var node := Dynamic new. + var node := DynamicStruct new. ch => - #43 ? [ node set &level:(aLevel + 1) set &operation:%add. ] // + - #45 ? [ node set &level:(aLevel + 1) set &operation:%subtract. ] // - - #42 ? [ node set &level:(aLevel + 2) set &operation:%multiply. ] // * - #47 ? [ node set &level:(aLevel + 2) set &operation:%divide. ] // / - #40 ? [ aLevel += 10. ^ $self. ] // ( - #41 ? [ aLevel -= 10. ^ $self. ] // ) + $43 [ node set level(aLevel + 1); set operation:%add ]; // + + $45 [ node set level(aLevel + 1); set operation:%subtract ]; // - + $42 [ node set level(aLevel + 2); set operation:%multiply ]; // * + $47 [ node set level(aLevel + 2); set operation:%divide ]; // / + $40 [ aLevel append int:10. ^ $self ]; // ( + $41 [ aLevel reduce int:10. ^ $self ]; // ) ! [ - node set &leaf:(ch literal toReal) set &level:((aLevel + 3)). + node set leaf(ch literal; toReal); set level(aLevel + 3). ]. - ($nil == theTree) - ? [ theTree := node. ] - ! [ - (theTree level >= node level) - ? [ - node set &left:theTree set &right:$nil. + if ($nil == theTree) + [ theTree := node ]; + [ + if (theTree level >= node level) + [ + node set left:theTree; set right:$nil. - theTree := node. + theTree := node + ]; + [ + var aTop := theTree. + while (($nil != aTop right)and:$(aTop right; level < node level)) + [ aTop := aTop right ]. + + node set left(aTop right); set right:$nil. + + aTop set right:node ] - ! [ - #var aTop := theTree. - #loop (($nil != aTop right)and:[aTop right level < node level] ) - ? [ aTop := aTop right. ]. - - node set &left:(aTop right) set &right:$nil. - - aTop set &right:node. - ]. - ]. - ]. + ] + ] ] - #method eval : aNode + eval : aNode [ - (aNode if &leaf) - ? [ ^ aNode leaf. ] - ! [ - #var aLeft := $self eval:(aNode left). - #var aRight := $self eval:(aNode right). + if (aNode containsProperty:%leaf) + [ ^ aNode leaf ]; + [ + var aLeft := $self eval:(aNode left). + var aRight := $self eval:(aNode right). - ^ aLeft::(aNode operation) eval:aRight. + ^ aLeft~(aNode operation) eval:aRight ] ] - #method value + value <= eval:theTree. - #method readLeaves : aList &at:aNode + readLeaves : aList at:aNode [ - ($nil == aNode) - ? [ #throw InvalidArgumentException new. ]. + if ($nil == aNode) + [ InvalidArgumentException new; raise ]. - (aNode if &leaf) - ? [ aList += aNode leaf. ] - ! [ - $self readLeaves:aList &at:(aNode left). - $self readLeaves:aList &at:(aNode right). + if (aNode containsProperty:%leaf) + [ aList append(aNode leaf) ]; + [ + $self readLeaves:aList at(aNode left). + $self readLeaves:aList at(aNode right). ]. ] - #method readLeaves : aList - <= readLeaves:aList &at:theTree. + readLeaves : aList + <= readLeaves:aList at:theTree. } -#class TwentyFourGame +class TwentyFourGame { - #field theNumbers. + object theNumbers. - #constructor new + constructor new [ $self newPuzzle. ] - #method newPuzzle + newPuzzle [ theNumbers := ( 1 + randomGenerator eval:9, @@ -99,75 +98,76 @@ 1 + randomGenerator eval:9). ] - #method help + help [ console - writeLine:"------------------------------- Instructions ------------------------------" - writeLine:"Four digits will be displayed." - writeLine:"Enter an equation using all of those four digits that evaluates to 24" - writeLine:"Only * / + - operators and () are allowed" - writeLine:"Digits can only be used once, but in any order you need." - writeLine:"Digits cannot be combined - i.e.: 12 + 12 when given 1,2,2,1 is not allowed" - writeLine:"Submit a blank line to skip the current puzzle." - writeLine:"Type 'q' to quit" - writeLine - writeLine:"Example: given 2 3 8 2, answer should resemble 8*3-(2-2)" - writeLine:"------------------------------- --------------------------------------------". + printLine:"------------------------------- Instructions ------------------------------"; + printLine:"Four digits will be displayed."; + printLine:"Enter an equation using all of those four digits that evaluates to 24"; + printLine:"Only * / + - operators and () are allowed"; + printLine:"Digits can only be used once, but in any order you need."; + printLine:"Digits cannot be combined - i.e.: 12 + 12 when given 1,2,2,1 is not allowed"; + printLine:"Submit a blank line to skip the current puzzle."; + printLine:"Type 'q' to quit"; + writeLine; + printLine:"Example: given 2 3 8 2, answer should resemble 8*3-(2-2)"; + printLine:"------------------------------- --------------------------------------------". ] - #method prompt + prompt [ - theNumbers run &each: n [ console writeLiteral:n:" ". ]. + theNumbers forEach(:n) [ console print(n," ") ]. - console write:": ". + console print:": " ] - #method resolve : aLine + resolve : aLine [ - #var exp := ExpressionTree new:aLine. + var exp := ExpressionTree new:aLine. - #var Leaves := ArrayList new. + var Leaves := ArrayList new. exp readLeaves:Leaves. - (Leaves ascendant equal &indexable:(theNumbers ascendant)) - ! [ console writeLine:"Invalid input. Enter an equation using all of those four digits. Try again.". ^ $self. ]. + ifnot (Leaves ascendant; sequenceEqual(theNumbers ascendant)) + [ console printLine:"Invalid input. Enter an equation using all of those four digits. Try again.". ^ $self ]. - #var aResult := exp value. - (aResult == 24) - ? [ - console writeLine:"Good work. ":aLine:"=":aResult. + var aResult := exp value. + if (aResult == 24) + [ + console printLine("Good work. ",aLine,"=",aResult). $self newPuzzle. - ] - ! [ console writeLine:"Incorrect. ":aLine:"=":aResult. ]. + ]; + [ console printLine("Incorrect. ",aLine,"=",aResult) ] ] } -#class(extension) gameOp +extension gameOp { - #method playRound : aLine + playRound : aLine [ - (aLine == "q") - ? [ ^ false. ] - ! [ - (aLine == "") - ? [ console writeLine:"Skipping this puzzle". self newPuzzle. ] - ! [ - self resolve:aLine - | if &Error: e - [ - console writeLine:"An error occurred. Check your input and try again.". - ]. + if (aLine == "q") + [ ^ false ]; + [ + if (aLine == "") + [ console printLine:"Skipping this puzzle". self newPuzzle. ]; + [ + try(self resolve:aLine) + { + on(Exception e) [ + console writeLine:"An error occurred. Check your input and try again." + ] + } ]. - ^ true. + ^ true ]. ] } -#symbol program = +program = [ - #var aGame := TwentyFourGame new help. + var aGame := TwentyFourGame new; help. - #loop (aGame prompt playRound:(console readLine)) ? []. + while (aGame prompt; playRound(console readLine)) []. ]. diff --git a/Task/24-game/Haskell/24-game.hs b/Task/24-game/Haskell/24-game.hs index e53c48e3e3..ccec90a8b0 100644 --- a/Task/24-game/Haskell/24-game.hs +++ b/Task/24-game/Haskell/24-game.hs @@ -1,43 +1,53 @@ -import Char -import Control.Monad.Error -import Data.List -import IO -import Maybe -import Random +import Data.List (sort) +import Data.Char (isDigit) +import Data.Maybe (fromJust) +import Control.Monad (foldM) +import System.Random (randomRs, getStdGen) +import System.IO (hSetBuffering, stdout, BufferMode(NoBuffering)) main = do - hSetBuffering stdout NoBuffering - mapM_ putStrLn - [ "THE 24 GAME\n" - , "Given four digits in the range 1 to 9" - , "Use the +, -, *, and / operators in reverse polish notation" - , "To show how to make an answer of 24.\n" - ] - digits <- liftM (sort . take 4 . randomRs (1,9)) getStdGen :: IO [Int] - putStrLn ("Your digits: " ++ intercalate " " (map show digits)) - guessLoop digits - where guessLoop digits = - putStr "Your expression: " >> - liftM (processGuess digits . words) getLine >>= - either (\m -> putStrLn m >> guessLoop digits) putStrLn + hSetBuffering stdout NoBuffering + mapM_ + putStrLn + [ "THE 24 GAME\n" + , "Given four digits in the range 1 to 9" + , "Use the +, -, *, and / operators in reverse polish notation" + , "To show how to make an answer of 24.\n" + ] + digits <- fmap (sort . take 4 . randomRs (1, 9)) getStdGen :: IO [Int] + putStrLn ("Your digits: " ++ unwords (fmap show digits)) + guessLoop digits + where + guessLoop digits = + putStr "Your expression: " >> fmap (processGuess digits . words) getLine >>= + either (\m -> putStrLn m >> guessLoop digits) putStrLn -processGuess _ [] = Right "" -processGuess digits xs | not $ matches = Left "Wrong digits used" - where matches = digits == (sort . map read $ filter (all isDigit) xs) +processGuess _ [] = Right "" +processGuess digits xs + | not matches = Left "Wrong digits used" + where + matches = digits == (sort . fmap read $ filter (all isDigit) xs) processGuess digits xs = calc xs >>= check - where check 24 = Right "Correct" - check x = Left (show (fromRational (x :: Rational)) ++ " is wrong") + where + check 24 = Right "Correct" + check x = Left (show (fromRational (x :: Rational)) ++ " is wrong") -- A Reverse Polish Notation calculator with full error handling -calc xs = foldM simplify [] xs >>= \ns -> (case ns of - [n] -> Right n - _ -> Left "Too few operators") +calc xs = + foldM simplify [] xs >>= + \ns -> + (case ns of + [n] -> Right n + _ -> Left "Too few operators") -simplify (a:b:ns) s | isOp s = Right ((fromJust $ lookup s ops) b a : ns) -simplify _ s | isOp s = Left ("Too few values before " ++ s) -simplify ns s | all isDigit s = Right (fromIntegral (read s) : ns) -simplify _ s = Left ("Unrecognized symbol: " ++ s) +simplify (a:b:ns) s + | isOp s = Right ((fromJust $ lookup s ops) b a : ns) +simplify _ s + | isOp s = Left ("Too few values before " ++ s) +simplify ns s + | all isDigit s = Right (fromIntegral (read s) : ns) +simplify _ s = Left ("Unrecognized symbol: " ++ s) -isOp v = elem v $ map fst ops +isOp v = elem v $ fmap fst ops -ops = [("+",(+)), ("-",(-)), ("*",(*)), ("/",(/))] +ops = [("+", (+)), ("-", (-)), ("*", (*)), ("/", (/))] diff --git a/Task/24-game/Kotlin/24-game.kotlin b/Task/24-game/Kotlin/24-game.kotlin index 588784aac2..b7ae354ce0 100644 --- a/Task/24-game/Kotlin/24-game.kotlin +++ b/Task/24-game/Kotlin/24-game.kotlin @@ -1,6 +1,6 @@ -package game24 - -import java.util.* +import java.util.Random +import java.util.Scanner +import java.util.Stack internal object Game24 { fun run() { @@ -10,9 +10,9 @@ internal object Game24 { print("> ") val s = Stack() - var total: Long = 0 + var total = 0L val cin = Scanner(System.`in`) - for (c in cin.nextLine()) + for (c in cin.nextLine()) { when (c) { in '0'..'9' -> { val d = c - '0' @@ -20,9 +20,11 @@ internal object Game24 { s += d.toFloat() } else -> - if ("+/-*".indexOf(c) != -1) + if ("+/-*".indexOf(c) != -1) { s += c.applyOperator(s.pop(), s.pop()) + } } + } when { tally(digits) != total -> @@ -34,7 +36,7 @@ internal object Game24 { } } - fun Char.applyOperator(a: Float, b: Float) = when (this) { + private fun Char.applyOperator(a: Float, b: Float) = when (this) { '+' -> a + b '-' -> b - a '*' -> a * b @@ -42,7 +44,7 @@ internal object Game24 { else -> Float.NaN } - fun tally(a: List): Long = a.reduce({ t, i -> t + (1 shl (i * 5)) }).toLong() + private fun tally(a: List): Long = a.reduce({ t, i -> t + (1 shl (i * 5)) }).toLong() private val target = 24 } diff --git a/Task/24-game/MIRC-Scripting-Language/24-game.mirc b/Task/24-game/MIRC-Scripting-Language/24-game.mirc new file mode 100644 index 0000000000..49f07663d5 --- /dev/null +++ b/Task/24-game/MIRC-Scripting-Language/24-game.mirc @@ -0,0 +1,33 @@ +alias 24 { + dialog -m 24-Game 24-Game +} + +dialog 24-Game { + title "24-Game" + size -1 -1 100 70 + option dbu + text "", 1, 29 7 42 8 + text "Equation", 2, 20 21 21 8 + edit "", 3, 45 20 40 10 + text "Status", 4, 10 34 80 8, center + button "Calculate", 5, 5 45 40 20 + button "New", 6, 57 47 35 15 +} + +on *:DIALOG:24-Game:init:*: { + did -o 24-Game 1 1 Numbers: $rand(1,9) $rand(1,9) $rand(1,9) $rand(1,9) +} + +on *:DIALOG:24-Game:sclick:*: { + if ($did == 5) { + if ($regex($did(3),/^[ (]*\d *[-+*/][ (]*\d[ ()]*[-+*/][ ()]*\d[ )]*[-+*/] *\d[ )]*$/)) && ($sorttok($regsubex($did(3),/[^\d]+/g,$chr(32)),32) == $sorttok($remove($did(1),Numbers:),32)) { + did -o 24-Game 4 1 $iif($calc($did(3)) == 24,Correct,Wrong) + } + else { + did -o 24-Game 4 1 Wrong Numbers or Syntax + } + } + elseif ($did == 6) { + did -o 24-Game 1 1 Numbers: $rand(1,9) $rand(1,9) $rand(1,9) $rand(1,9) + } +} diff --git a/Task/24-game/MUMPS/24-game.mumps b/Task/24-game/MUMPS/24-game.mumps new file mode 100644 index 0000000000..7e6bde9d8d --- /dev/null +++ b/Task/24-game/MUMPS/24-game.mumps @@ -0,0 +1,80 @@ +24Game + k number, operator, bracket + ; generate 4 random numbers each between 1 & 9 + ; duplicates allowed! + s n1=$r(9)+1, n2=$r(9)+1, n3=$r(9)+1, n4=$r(9)+1 + ; save a copy of them so that we can keep restarting + ; if the user gets it wrong + s s1=n1,s2=n2,s3=n3,s4=n4 +Question + s (numcount,opcount,lbrackcount,rbrackcount)=0 + ; restart with the random numbers already found + s n1=s1,n2=s2,n3=s3,n4=s4 + w !,"Enter an arithmetic expression that evaluates to 24 using (", + n1," ",n2," ",n3," ",n4,"): " + r !,expr + q:expr="" + ; validate numbers and operators + s error="" + f n=1:1:$l(expr) { + s char=$e(expr,n) + if char?1n { + s number($i(numcount))=char + w ! + zw char + } + elseif char?1(1"*",1"/",1"+",1"-") { + s operator($i(opcount))=char + } + elseif char?1"(" { + s bracket($i(lbrackcount))=char + } + elseif char?1")" { + s bracket($i(rbrackcount))=char + } + else { + s error="That ain't no character I wanted to see" + q + } + } + if error'="" w error g Question + if numcount'=4 { + w "Does not have 4 numbers, do it again." + g Question + } + s error="" + f n=1:1:4 { + if number(n)=n1 { + s n1="dont use again" continue + } + if number(n)=n2 { + s n2="dont use again" continue + } + if number(n)=n3 { + s n3="dont use again" continue + } + if number(n)=n4 { + s n4="dont use again" continue + } + s error="Numbers entered do not match all of the randomly generated numbers." + q + } + if error'="" { + w error + g Question + } + if opcount'=3 { + w "Does not have 3 operators." + g Question + } + if lbrackcount'=rbrackcount { + w "brackets must be in pairs." + g Question + } + x "s x="_expr + if x'=24 { + w !,"Answer does not = 24" + g Question + } + w x + q diff --git a/Task/24-game/Nim/24-game.nim b/Task/24-game/Nim/24-game.nim index 92c8a0e884..78abbac79c 100644 --- a/Task/24-game/Nim/24-game.nim +++ b/Task/24-game/Nim/24-game.nim @@ -1,8 +1,11 @@ -import math, strutils, algorithm, sequtils +from random import randomize, random +from strutils import Whitespace +from algorithm import sort +from sequtils import deduplicate randomize() -template newSeqWith(len: int, init: expr): expr = - var result {.gensym.} = newSeq[type(init)](len) +template newSeqWith(len: int, init: untyped): untyped = + var result = newSeq[type(init)](len) for i in 0 .. 1 do + var operand = operands.shift + var a = temp_numbers.shift + var b = temp_numbers.shift + + if operand == '+' then number = a + b + if operand == '-' then number = a - b + if operand == '*' then number = a * b + if operand == '/' then number = a / b + + temp_numbers.unshift(number) + end + if number != 0 then random_numbers.add(number) +end + +# Check if used `numbers` exist in the `random_numbers` created +fun numbers_exists(random_numbers, numbers: Array[Int]): Bool do + for number in numbers do + if not random_numbers.count(number) >= numbers.count(number) then return false + end + return true +end + +# Remove `numbers` when they are used +fun remove_numbers(random_numbers, numbers: Array[Int]) do + for number in numbers do random_numbers.remove(number) +end + +# Check if the mathematical `operation` is valid +fun check(operation: String): Bool do + var previous_char: nullable Char = null + var next_char: nullable Char = null + var next_1_char: nullable Char = null + + for i in operation.length.times do + var current_char = operation[i] + + if i + 1 < operation.length then + next_char = operation[i + 1] + if i + 2 < operation.length then + next_1_char = operation[i + 2] + else + next_1_char = null + end + else + next_char = null + end + + if not current_char.is_op and not current_char.is_digit then return false + if next_char == null and current_char.is_op then return false + + if previous_char == null then + if next_char == null or next_1_char == null then return false + if current_char == '-' and not next_char.is_digit then return false + if current_char != '-' and not current_char.is_digit then return false + else + if next_char != null then + if previous_char.is_digit and current_char.is_op and + not (next_char == '-' and next_1_char != null and + next_1_char.is_digit or next_char.is_digit) then + return false + end + end + end + previous_char = current_char + end + return true +end + +var random_numbers = new Array[Int] +var operation = "" + +random_numbers = random +while not random_numbers.has(24) and random_numbers.length > 1 do + var numbers = new Array[Int] + var operands = new Array[Char] + + print "numbers: " + random_numbers.join(", ") + operation = gets + if check(operation) then + exportation(operation, numbers, operands) + if numbers_exists(random_numbers, numbers) then + calculation(random_numbers, numbers, operands) + remove_numbers(random_numbers, numbers) + else + print "NUMBERS ERROR!" + end + else + print "STRING ERROR!" + end +end + +if random_numbers.has(24) then print "CONGRATULATIONS" else print "YOU LOSE" diff --git a/Task/24-game/Python/24-game.py b/Task/24-game/Python/24-game-1.py similarity index 100% rename from Task/24-game/Python/24-game.py rename to Task/24-game/Python/24-game-1.py diff --git a/Task/24-game/Python/24-game-2.py b/Task/24-game/Python/24-game-2.py new file mode 100644 index 0000000000..232551bcd6 --- /dev/null +++ b/Task/24-game/Python/24-game-2.py @@ -0,0 +1,33 @@ +import random, re +chars = ["(",")","/","+","-","*"] +while True: + charsandints, ints = [], [] + for x in range(4): + ints.append(str(random.randrange(1,10))) + charsandints = chars + ints + print "Numbers are:", ints + guess = raw_input("Enter your guess:") + if guess.lower() == "q": + break + elif guess.lower() == "|": + pass + else: + flag = True + for a in guess: + if a not in charsandints or guess.count(a) > charsandints.count(a): + flag = False + if re.search("\d\d", guess): + print "You cannot combine digits." + break + if flag: + print "Your result is: ", eval(guess) + if eval(guess) == 24: + print "You won" + break + else: + print "You lost" + break + else: + print "You cannot use anthing other than", charsandints + break +print "Thanks for playing" diff --git a/Task/24-game/REXX/24-game-1.rexx b/Task/24-game/REXX/24-game-1.rexx index 9709af0e5e..c5666bd51e 100644 --- a/Task/24-game/REXX/24-game-1.rexx +++ b/Task/24-game/REXX/24-game-1.rexx @@ -1,17 +1,14 @@ /*REXX program supports a human to play the game of 24 (twenty-four) with error checking*/ -numeric digits 15 /*allow more leeway when computing #s. */ -parse arg yyy /*get the optional arguments from C.L. */ - yyy = space(yyy, 0) /*remove extraneous blanks from YYY. */ +parse arg yyy; yyy=space(yyy, 0) /*get optional CL args; elide blanks. */ parse var yyy start '-' fin /*get the START and FINish (maybe). */ - fin = word(fin start, 1) /*if no FINish specified, use START.*/ - ops = '+-*/' ; Lops = length(0ps) /*define the legal arithmetic operators*/ -groupSym = '()[]{}' /*legal grouping symbols for this game.*/ - indent = left('', 30) /*used to indent display of solutions. */ - Lpar = '(' ; Rpar = ')' /*strings to make the output prettier.*/ - digs = 123456789 /*numerals (digits) that can be used. */ - show = 1 /*flag used show solutions (0 = not). */ - do j=1 for Lops; @.j=substr(ops,j,1) /*define a version for fast execution. */ - end /*j*/ + fin= word(fin start, 1) /*if no FINish specified, use START.*/ + ops= '+-*/' ; Lops= length(0ps) /*define the legal arithmetic operators*/ +groupSym= '()[]{}' /*legal grouping symbols for this game.*/ + pad= left('', 30) /*used to indent display of solutions. */ + Lpar= '(' ; Rpar= ')' /*strings to make the output prettier.*/ + digs= 123456789 /*numerals (digits) that can be used. */ + show= 1 /*flag used show solutions (0 = not). */ + do j=1 for Lops; @.j=substr(ops,j,1); end /*for fast execution. */ signal on syntax /*enable program to trap syntax errors.*/ if yyy\=='' then do; sols=solve(start, fin) /*solve from START ───► FINish. */ if sols <0 then exit 13 /*Was there a problem with the input? */ @@ -30,11 +27,10 @@ $.=0 do j=1 for Lrrrr; _=substr(rrrr,j,1) /*digit count for each digit in RRRR. */ $._= countDigs(rrrr, _) /*define the count for this digit. */ end /*j*/ /* [↑] counts duplicates twice, no harm*/ - -__ = copies('─', 9) /*used for output highlighting. */ + __ = copies('─', 9) /*used for output highlighting. */ prompt= 'Using the digits ' rrrr", enter an expression that equals 24 (or QUIT):" /* [↓] ITERATE needs a variable name.*/ - do prompter=0; say; say __ prompt /*display blank line and the prompt (P)*/ + do prompter=0 by 0; say; say __ prompt /*display blank line and the prompt (P)*/ pull y; y=space(y, 0) /*get Y from CL, then remove all blanks*/ if abbrev('QUIT', y, 1) then exit 0 /*Does the user want to quit this game?*/ _v=verify(y, digs || ops || groupSym); a=substr(y, max(1,_v), 1) @@ -43,33 +39,29 @@ prompt= 'Using the digits ' rrrr", enter an expression that equals 24 (or if pos('//', y) then do; call ger "invalid // operator"; iterate; end Ly=length(y) if y=='' then do; call validate y; iterate; end - - do j=1 for Ly-1; if \datatype(substr(y, j , 1), 'W') then iterate - if \datatype(substr(y, j+1, 1), 'W') then iterate - call ger 'invalid use of "digit abuttal".' - iterate prompter - end /*j*/ - - yd=countDigs(y, digs) /*count of the digits 1──►9 (123456789)*/ + do j=1 for Ly-1; if \datatype(substr(y,j ,1), 'W') then iterate + if \datatype(substr(y,j+1,1), 'W') then iterate + call ger 'invalid use of "digit abuttal".' + iterate prompter + end /*j*/ + yd=countDigs(y,digs) /*count of the digits 1──►9 (123456789)*/ if yd<4 then do; call ger 'not enough digits entered.'; iterate /*prompter*/; end if yd>4 then do; call ger 'too many digits entered.' ; iterate /*prompter*/; end - - do j=1 for 9; if $.j==0 then iterate - _d=countDigs(y, j); if $.j==_d then iterate - if _d<$.j then call ger 'not enough' j "digits, must be" $.j - else call ger 'too many' j "digits, must be" $.j - iterate prompter - end /*j*/ - + do j=1 for 9; if $.j==0 then iterate + _d=countDigs(y, j); if $.j==_d then iterate + if _d<$.j then call ger 'not enough' j "digits, must be" $.j + else call ger 'too many' j "digits, must be" $.j + iterate prompter + end /*j*/ interpret 'ans=' translate(y, '()()', "[]{}"); ans=ans/1 if ans==24 then leave prompter; say 'incorrect, ' y"="ans end /*prompter*/ -say; say center('┌─────────────────────┐', 79) - say center('│ │', 79) - say center('│ congratulations ! │', 79) - say center('│ │', 79) - say center('└─────────────────────┘', 79) +say; say center('┌─────────────────────┐', 79) + say center('│ │', 79) + say center('│ congratulations ! │', 79) + say center('│ │', 79) + say center('└─────────────────────┘', 79) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ countDigs: arg ?; return length(?) - length(space(translate(?, , arg(2)), 0)) @@ -79,18 +71,12 @@ s: if arg(1)==1 then return ''; return "s" /*a simple plu syntax: call ger 'illegal syntax in' y; exit /*──────────────────────────────────────────────────────────────────────────────────────*/ solve: parse arg ssss, ffff /*parse the argument passed to SOLVE. */ - if ffff=='' then ffff=ssss /*create a FFFF if necessary. */ - if \validate(ssss) then return -1 /*validate the SSSS field. */ - if \validate(ffff) then return -1 /* " " FFFF " */ - #=0 /*number of found solutions (so far). */ - !.=0 /*a method to hold unique expressions. */ - /*alternative: indent=copies(' ',30) */ + if ffff=='' then ffff=ssss /*create a FFFF if necessary. */ + if \validate(ssss) | \validate(ffff) then return -1 /*validate SSSS & FFFF*/ + !.=0; #=0 /*holds unique expressions; # solutions*/ do g=ssss to ffff /*process a (possible) range of values.*/ if pos(0, g)\==0 then iterate /*ignore values with zero in them. */ - - do j=1 for 4; g.j=substr(g, j, 1) /*define a version for fast execution. */ - end /*j*/ - + do j=1 for 4; g.j=substr(g,j,1); end /*for fast execution.*/ do i =1 for Lops /*insert an operator after 1st number. */ do j =1 for Lops /* " " " " 2nd " */ do k =1 for Lops /* " " " " 3rd " */ @@ -108,14 +94,13 @@ solve: parse arg ssss, ffff /*parse the argument passed to interpret 'x=' e /*have REXX do all the heavy lifting */ if x\=24 then iterate /*Is the result incorrect? Try again. */ #=#+1 /*bump number of found solutions. */ - if show then say indent 'a solution:' translate(yyyE, '][', ")(") + if show then say pad 'a solution for' g": " translate(yyyE,'][',")(") end /*n*/ /* [↑] display a (single) solution. */ end /*m*/ end /*k*/ end /*j*/ end /*i*/ end /*g*/ - return # /*──────────────────────────────────────────────────────────────────────────────────────*/ sort: procedure; parse arg #; L=length(#); !.= /*this is a modified bin sort.*/ @@ -130,5 +115,4 @@ validate: parse arg y; OK=1; _v=verify(y,digs); DE='digits entered, there must when pos(0,y)\==0 then call ger "can't use the digit 0 (zero)." when _v\==0 then call ger "illegal character: " substr(y, _v, 1) otherwise nop - end /*select*/ - return OK + end /*select*/; return OK diff --git a/Task/24-game/REXX/24-game-3.rexx b/Task/24-game/REXX/24-game-3.rexx deleted file mode 100644 index 79165ca303..0000000000 --- a/Task/24-game/REXX/24-game-3.rexx +++ /dev/null @@ -1,25 +0,0 @@ -changestr: Procedure -/* change needle to newneedle in haystack (as often as specified */ -/* or all of them if count is omitted */ - Parse Arg needle,haystack,newneedle,count - If count>'' Then Do - If count=0 Then Do - Say 'chstr count must be > 0' - Signal Syntax - End - End - res="" - changes=0 - px=1 - do Until py=0 - py=pos(needle,haystack,px) - if py>0 then Do - res=res||substr(haystack,px,py-px)||newneedle - px=py+length(needle) - changes=changes+1 - If count>'' Then - If changes=count Then Leave - End - end - res=res||substr(haystack,px) - Return res diff --git a/Task/24-game/Sidef/24-game.sidef b/Task/24-game/Sidef/24-game.sidef index f1a3063ce9..a07c0e423e 100644 --- a/Task/24-game/Sidef/24-game.sidef +++ b/Task/24-game/Sidef/24-game.sidef @@ -1,34 +1,34 @@ -const digits = (1..9 -> pick(4)); -const grammar = Regex.new( +const digits = (1..9 -> pick(4)) +const grammar = Regex( '^ (?&exp) \z (?(DEFINE) (? ( (?&term) (?&op) (?&term) )+ ) (? \( (?&exp) \) | [' + digits.join + ']) - (? [-+*/] ) + (? [\-+*/] ) )', 'x' -); -  -say "Here are your digits: #{digits.join(' ')}"; -  +) + +say "Here are your digits: #{digits.join(' ')}" + loop { - var input = Sys.scanln("Expression: "); -  - var expr = input; - expr -= /\s+/g; # remove all whitespace -  - input == 'q' && ( - say "Goodbye. Sorry you couldn't win."; - break; - ); -  - var given_digits = digits.map{.to_s}.sort.join; - var entry_digits = input.scan(/\d/).sort.join; -  - if ((given_digits != entry_digits) || (expr !~ grammar)) { - say "That's not valid"; - next; + var input = read("Expression: ", String) + + var expr = input + expr -= /\s+/g # remove all whitespace + + if (input == 'q') { + say "Goodbye. Sorry you couldn't win." + break } -  + + var given_digits = digits.map{.to_s}.sort.join + var entry_digits = input.scan(/\d/).sort.join + + if ((given_digits != entry_digits) || (expr !~ grammar)) { + say "That's not valid" + next + } + given(var n = eval(input)) { when (24) { say "You win!"; break } default { say "Sorry, your expression is #{n}, not 24" } diff --git a/Task/24-game/Simula/24-game.simula b/Task/24-game/Simula/24-game.simula new file mode 100644 index 0000000000..394d522b42 --- /dev/null +++ b/Task/24-game/Simula/24-game.simula @@ -0,0 +1,296 @@ +BEGIN + + CLASS EXPR; + BEGIN + + + REAL PROCEDURE POP; + BEGIN + IF STACKPOS > 0 THEN + BEGIN STACKPOS := STACKPOS - 1; POP := STACK(STACKPOS); END; + END POP; + + + PROCEDURE PUSH(NEWTOP); REAL NEWTOP; + BEGIN + STACK(STACKPOS) := NEWTOP; + STACKPOS := STACKPOS + 1; + END PUSH; + + + REAL PROCEDURE CALC(OPERATOR, ERR); CHARACTER OPERATOR; LABEL ERR; + BEGIN + REAL X, Y; X := POP; Y := POP; + IF OPERATOR = '+' THEN PUSH(Y + X) + ELSE IF OPERATOR = '-' THEN PUSH(Y - X) + ELSE IF OPERATOR = '*' THEN PUSH(Y * X) + ELSE IF OPERATOR = '/' THEN BEGIN + IF X = 0 THEN + BEGIN + EVALUATEDERR :- "DIV BY ZERO"; + GOTO ERR; + END; + PUSH(Y / X); + END + ELSE + BEGIN + EVALUATEDERR :- "UNKNOWN OPERATOR"; + GOTO ERR; + END + END CALC; + + + PROCEDURE READCHAR(CH); NAME CH; CHARACTER CH; + BEGIN + IF T.MORE THEN CH := T.GETCHAR ELSE CH := EOT; + END READCHAR; + + + PROCEDURE SKIPWHITESPACE(CH); NAME CH; CHARACTER CH; + BEGIN + WHILE (CH = SPACE) OR (CH = TAB) OR (CH = CR) OR (CH = LF) DO + READCHAR(CH); + END SKIPWHITESPACE; + + + PROCEDURE BUSYBOX(OP, ERR); INTEGER OP; LABEL ERR; + BEGIN + CHARACTER OPERATOR; + REAL NUMBR; + BOOLEAN NEGATIVE; + + SKIPWHITESPACE(CH); + + IF OP = EXPRESSION THEN + BEGIN + + NEGATIVE := FALSE; + WHILE (CH = '+') OR (CH = '-') DO + BEGIN + IF CH = '-' THEN NEGATIVE := NOT NEGATIVE; + READCHAR(CH); + END; + + BUSYBOX(TERM, ERR); + + IF NEGATIVE THEN + BEGIN + NUMBR := POP; PUSH(0 - NUMBR); + END; + + WHILE (CH = '+') OR (CH = '-') DO + BEGIN + OPERATOR := CH; READCHAR(CH); + BUSYBOX(TERM, ERR); CALC(OPERATOR, ERR); + END; + + END + ELSE IF OP = TERM THEN + BEGIN + + BUSYBOX(FACTOR, ERR); + WHILE (CH = '*') OR (CH = '/') DO + BEGIN + OPERATOR := CH; READCHAR(CH); + BUSYBOX(FACTOR, ERR); CALC(OPERATOR, ERR) + END + + END + ELSE IF OP = FACTOR THEN + BEGIN + + IF (CH = '+') OR (CH = '-') THEN + BUSYBOX(EXPRESSION, ERR) + ELSE IF (CH >= '0') AND (CH <= '9') THEN + BUSYBOX(NUMBER, ERR) + ELSE IF CH = '(' THEN + BEGIN + READCHAR(CH); + BUSYBOX(EXPRESSION, ERR); + IF CH = ')' THEN READCHAR(CH) ELSE GOTO ERR; + END + ELSE GOTO ERR; + + END + ELSE IF OP = NUMBER THEN + BEGIN + + NUMBR := 0; + WHILE (CH >= '0') AND (CH <= '9') DO + BEGIN + NUMBR := 10 * NUMBR + RANK(CH) - RANK('0'); READCHAR(CH); + END; + IF CH = '.' THEN + BEGIN + REAL FAKTOR; + READCHAR(CH); + FAKTOR := 10; + WHILE (CH >= '0') AND (CH <= '9') DO + BEGIN + NUMBR := NUMBR + (RANK(CH) - RANK('0')) / FAKTOR; + FAKTOR := 10 * FAKTOR; + READCHAR(CH); + END; + END; + PUSH(NUMBR); + + END; + + SKIPWHITESPACE(CH); + + END BUSYBOX; + + + BOOLEAN PROCEDURE EVAL(INP); TEXT INP; + BEGIN + EVALUATEDERR :- NOTEXT; + STACKPOS := 0; + T :- COPY(INP.STRIP); + READCHAR(CH); + BUSYBOX(EXPRESSION, ERRORLABEL); + ! OUTTEXT("T = '"); + ! OUTTEXT(T); + ! OUTTEXT("'"); + ! OUTTEXT(", T.POS = "); + ! OUTINT(T.POS, 0); + ! OUTTEXT(", STACKPOS = "); + ! OUTINT(STACKPOS, 0); + ! OUTTEXT(", T.MORE = "); + ! OUTCHAR(IF T.MORE THEN 'T' ELSE 'F'); + ! OUTTEXT(", CH = "); + ! OUTCHAR(CH); + ! OUTIMAGE; + IF NOT T.MORE AND STACKPOS = 1 AND CH = EOT THEN + BEGIN + EVALUATED := POP; + EVAL := TRUE; + GOTO NOERRORLABEL; + END; + ERRORLABEL: + EVAL := FALSE; + IF EVALUATEDERR = NOTEXT THEN + EVALUATEDERR :- "INVALID EXPRESSION: " & INP; + NOERRORLABEL: + END EVAL; + + + REAL PROCEDURE RESULT; + RESULT := EVALUATED; + + TEXT PROCEDURE ERR; + ERR :- EVALUATEDERR; + + TEXT T; + + INTEGER EXPRESSION; + INTEGER TERM; + INTEGER FACTOR; + INTEGER NUMBER; + + CHARACTER TAB; + CHARACTER LF; + CHARACTER CR; + CHARACTER SPACE; + CHARACTER EOT; + + CHARACTER CH; + REAL ARRAY STACK(0:31); + INTEGER STACKPOS; + + REAL EVALUATED; + TEXT EVALUATEDERR; + + EXPRESSION := 1; + TERM := 2; + FACTOR := 3; + NUMBER := 4; + + TAB := CHAR(9); + LF := CHAR(10); + CR := CHAR(13); + SPACE := CHAR(32); + EOT := CHAR(0); + + END EXPR; + + INTEGER ARRAY DIGITS(1:4); + INTEGER SEED, I; + REF(EXPR) E; + + E :- NEW EXPR; + OUTTEXT("ENTER RANDOM SEED: "); + OUTIMAGE; + SEED := ININT; + FOR I := 1 STEP 1 UNTIL 4 DO DIGITS(I) := RANDINT(0, 9, SEED); + +L: BEGIN + INTEGER ARRAY DIGITSUSED(0:9); + INTEGER ARRAY DIGITSTAKEN(0:9); + CHARACTER C, LASTC; + TEXT INP; + + LASTC := CHAR(0); + OUTTEXT("MAKE 24 USING THESE DIGITS: "); + FOR I := 1 STEP 1 UNTIL 4 DO + BEGIN + OUTINT(DIGITS(I), 2); + DIGITSUSED( DIGITS(I) ) := DIGITSUSED( DIGITS(I) ) + 1; + END; + OUTIMAGE; + INIMAGE; + INP :- COPY(SYSIN.IMAGE.STRIP); + OUTIMAGE; + WHILE INP.MORE DO + BEGIN + C := INP.GETCHAR; + IF (C >= '0') AND (C <= '9') THEN + BEGIN + INTEGER D; + IF (LASTC >= '0') AND (LASTC <= '9') THEN + BEGIN + OUTTEXT("NUMBER HAS TOO MANY DIGITS: "); + OUTCHAR(LASTC); + OUTCHAR(C); + OUTIMAGE; + GOTO L; + END; + D := RANK(C) - RANK('0'); + DIGITSTAKEN(D) := DIGITSTAKEN(D) + 1; + END + ELSE IF NOT ((C = '+') OR (C = '-') OR (C = '/') OR (C = '*') OR + (C = ' ') OR (C = '(') OR (C = ')')) THEN + BEGIN + OUTTEXT("ILLEGAL INPUT CHARACTER: "); + OUTCHAR(C); + OUTIMAGE; + GOTO L; + END; + LASTC := C; + END; + FOR I := 0 STEP 1 UNTIL 9 DO + BEGIN + IF DIGITSUSED(I) <> DIGITSTAKEN(I) THEN + BEGIN + OUTTEXT("NOT THE SAME DIGITS."); + OUTIMAGE; + GOTO L; + END; + END; + IF E.EVAL(INP) THEN + BEGIN + OUTTEXT("RESULT IS "); + OUTFIX(E.RESULT, 4, 10); + OUTIMAGE; + OUTTEXT(IF ABS(E.RESULT - 24) < 0.001 + THEN "YOU WIN" + ELSE "YOU LOOSE"); + OUTIMAGE; + END + ELSE + BEGIN + OUTTEXT(E.ERR); + OUTIMAGE; + END; + END; + +END. diff --git a/Task/24-game/Zkl/24-game.zkl b/Task/24-game/Zkl/24-game.zkl new file mode 100644 index 0000000000..89d61ce963 --- /dev/null +++ b/Task/24-game/Zkl/24-game.zkl @@ -0,0 +1,19 @@ +while(1){ + digits := [1..4].pump(String,(0).random.fpM("11-",1,9)); + exp := ask("Enter an expression using the digits ",digits, + " that evals to 24: ") - " \n"; + expf:=exp.apply(fcn(c){if ("1"<=c<="9") "(%s).toFloat()".fmt(c) else c}); + reg r; + try { Compiler.Compiler.compileText(expf).__constructor(); r=vm.regX } + catch { println("bad expression"); continue; } + else{ + extra := (exp - "+-/*()" - digits); + if (extra) { println("Extra goodies in expression: ",extra); continue; } + (digits.split("").sort() != (exp - "+-/*()").split("").sort()) : + if(_) { println("You can only use the digits ",digits," once each"); continue; }; + if (exp.matches("*[1-9][1-9]*")) + { println("no repeated digits"); continue; } + if (r.closeTo(24,0.001)) "nice!".println(); + else println("That evaled to ",r,", not 24"); + } +} 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 new file mode 100644 index 0000000000..fed2cfdfba --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Groovy/9-billion-names-of-god-the-integer.groovy @@ -0,0 +1,41 @@ +def partitions(c) +{ + + def p=[]; + int k = 0; + p[k] = c; + int counter=0; + def counts=[]; + for (i in 0..c-1) + {counts[i]=0;} + while (true) + { + + counter++; + counts[p[0]-1]=counts[p[0]-1]+1; + int rem_val = 0; + while (k >= 0 && p[k] == 1) + { rem_val += p[k]; + k--;} + if (k < 0) { break;} + p[k]--; + rem_val++; + while (rem_val > p[k]) + { + p[k+1] = p[k]; + rem_val = rem_val - p[k]; + k++; + } + p[k+1] = rem_val; + k++; + } + println counts; + return counter; +} + + +static void main(String[] args) +{ +for( i in 1..25 ) +{partitions(i);} +} 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.kotlin index 063ee350cd..a04bec4fd8 100644 --- 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.kotlin @@ -1,5 +1,9 @@ -fun namesOfGod(n: Int): List { +import java.lang.Math.min +import java.math.BigInteger +import java.util.ArrayList +import java.util.Arrays.asList +fun namesOfGod(n: Int): List { val cache = ArrayList>() cache.add(asList(BigInteger.ONE)) @@ -15,15 +19,17 @@ fun namesOfGod(n: Int): List { return cache[n] } -fun row(n: Int) = namesOfGod(n).let { r -> (0..n-1).map { r[it + 1] - r[it] } } +fun row(n: Int) = namesOfGod(n).let { r -> (0 until n).map { r[it + 1] - r[it] } } -println("Rows:") -(1..25).forEach { - System.out.printf("%2d: %s%n", it, row(it)) -} +fun main(args: Array) { + println("Rows:") + (1..25).forEach { + System.out.printf("%2d: %s%n", it, row(it)) + } -println("\nSums:") -intArrayOf(23, 123, 1234, 1234).forEach { - val c = namesOfGod(it) - System.out.printf("%s %s%n", it, c[c.size - 1]) + println("\nSums:") + intArrayOf(23, 123, 1234, 1234).forEach { + val c = namesOfGod(it) + System.out.printf("%s %s%n", it, c[c.size - 1]) + } } diff --git a/Task/9-billion-names-of-God-the-integer/Nim/9-billion-names-of-god-the-integer-1.nim b/Task/9-billion-names-of-God-the-integer/Nim/9-billion-names-of-god-the-integer-1.nim index 34a1d0bf09..c06a89c8ca 100644 --- a/Task/9-billion-names-of-God-the-integer/Nim/9-billion-names-of-god-the-integer-1.nim +++ b/Task/9-billion-names-of-God-the-integer/Nim/9-billion-names-of-god-the-integer-1.nim @@ -2,15 +2,15 @@ import bigints var cache = @[@[1.initBigInt]] -proc cumu(n): seq[BigInt] = - for l in cache.len .. n: +proc cumu(n: int): seq[BigInt] = + for m in cache.len .. n: var r = @[0.initBigInt] - for x in 1..l: - r.add r[r.high] + cache[l-x][min(x, l-x)] + for x in 1..m: + r.add r[r.high] + cache[m-x][min(x, m-x)] cache.add r result = cache[n] -proc row(n): seq[BigInt] = +proc row(n: int): seq[BigInt] = let r = cumu n result = @[] for i in 0 .. Len(sums))+Len(sums)*Bool(Len(sums)>=Len(s)) v1=Val(Mid(s,i,1)) @@ -21,8 +21,8 @@ Procedure.i Adr(row.i,col.i) EndProcedure Procedure Triangle(row.i,Array pfx.s(1)) - Define.i n,k - Define.s zs + Define n.i,k.i + Define zs.s nMax=row ReDim pfx(Adr(nMax,nMax)) For n=1 To nMax @@ -42,7 +42,7 @@ Procedure Triangle(row.i,Array pfx.s(1)) EndProcedure Procedure.s sum(row.i, Array pfx.s(1)) - Define.s s + Define s.s Triangle(row, pfx()) For n=1 To row s=Sigma(pfx(Adr(row,n)),s) diff --git a/Task/9-billion-names-of-God-the-integer/SPL/9-billion-names-of-god-the-integer.spl b/Task/9-billion-names-of-God-the-integer/SPL/9-billion-names-of-god-the-integer.spl new file mode 100644 index 0000000000..fdc7ec574b --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/SPL/9-billion-names-of-god-the-integer.spl @@ -0,0 +1,38 @@ +'print triangle +> n, 1..25 + k = 50-n*2 + #.output(#.str("","<"+k+"<"),#.rs) + > k, 1..n + i = p(n,k) + s = #.str(i,">3<") + ? kn, <= 0 + ? k=n, <= 1 + <= p(n-1,k-1)+p(n-k,k) +. + +'calculate partition function +#.output() +#.output("G(23) = ",g(23)) +#.output("G(123) = ",g(123)) +#.output("G(1234) = ",g(1234)) +#.output("G(12345) = ",g(12345)) +g(n)= + p[1] = 1 + > i, 2..n+1 + j = 2 + k,p[i] = 0 + > j>1 + k += 1 + j = i-#.lower((3*k*k+k)/2) + ? j!<1, p[i] -= (-1)^k*p[j] + j = i-#.lower((3*k*k-k)/2) + ? j!<1, p[i] -= (-1)^k*p[j] + < + < + <= p[n+1] +. 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.ss new file mode 100644 index 0000000000..38dbe6834d --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Scheme/9-billion-names-of-god-the-integer.ss @@ -0,0 +1,20 @@ +(define (f m n) + (define (sigma g x y) + (define (sum i) + (if (< i 0) 0 (+ (f x (- y i) ) (sum (- i 1))))) + (sum y)) + (cond ((eq? m n) 1) + ((eq? n 1) 1) + ((eq? n 0) 0) + ((< m n) (f m m)) + ((< (/ m 2) n) (sigma f (- m n) (- m n))) + (else (sigma f (- m n) n)))) +(define (line m) + (define (connect i) + (if (> i m) '() (cons (f m i) (connect (+ i 1))))) + (connect 1)) +(define (print x) + (define (print-loop i) + (cond ((< i x) (begin (display (line i)) (display "\n") (print-loop (+ i 1)) )))) + (print-loop 1)) +(print 25) diff --git a/Task/9-billion-names-of-God-the-integer/Sidef/9-billion-names-of-god-the-integer.sidef b/Task/9-billion-names-of-God-the-integer/Sidef/9-billion-names-of-god-the-integer.sidef index f8e920de33..597bd65fd4 100644 --- a/Task/9-billion-names-of-God-the-integer/Sidef/9-billion-names-of-god-the-integer.sidef +++ b/Task/9-billion-names-of-God-the-integer/Sidef/9-billion-names-of-god-the-integer.sidef @@ -1,28 +1,28 @@ var cache = [[1]] -  + func cumu (n) { - for l in range(cache.len, n) { + for l (cache.len .. n) { var r = [0] - l.times { |i| + for i (1..l) { r << (r[-1] + cache[l-i][min(i, l-i)]) } cache << r } cache[n] } -  + func row (n) { var r = cumu(n) - n.of {|i| r[i] - r[i-1] } + n.of {|i| r[i+1] - r[i] } } -  + say "rows:" -15.times { |i| - "%2s: %s\n".printf(i, row(i)) +for i (1..15) { + "%2s: %s\n".printf(i, row(i)) } -  + say "\nsums:" -  + for i in [23, 123, 1234, 12345] { - "%2s : %4s\n".printf(i, cumu(i)[-1]) + "%2s : %4s\n".printf(i, cumu(i)[-1]) } diff --git a/Task/9-billion-names-of-God-the-integer/Zkl/9-billion-names-of-god-the-integer-1.zkl b/Task/9-billion-names-of-God-the-integer/Zkl/9-billion-names-of-god-the-integer-1.zkl new file mode 100644 index 0000000000..7cd04834e1 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Zkl/9-billion-names-of-god-the-integer-1.zkl @@ -0,0 +1,17 @@ +var [const] BN=Import.lib("zklBigNum"); + +const N=0d100_000; +p:=List.createLong(N+1,BN.fp(0),True); // (0,0,...) all different + +fcn calc(n,p){ + p[n].set(0); // reset array for each run + foreach k in ([1..n]){ + d:=n - k *(3*k - 1)/2; + do(2){ + if (d<0) break(2); + if (k.isOdd) p[n].add(p[d]); + else p[n].sub(p[d]); + d-=k; + } + } +} diff --git a/Task/9-billion-names-of-God-the-integer/Zkl/9-billion-names-of-god-the-integer-2.zkl b/Task/9-billion-names-of-God-the-integer/Zkl/9-billion-names-of-god-the-integer-2.zkl new file mode 100644 index 0000000000..fece2a975c --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Zkl/9-billion-names-of-god-the-integer-2.zkl @@ -0,0 +1,7 @@ +idx:=T(23, 123, 1234, 12345, 20000, 30000, 40000, 50000, N); +p[0].set(1); + +foreach i in (idx){ + (1).pump(i,Void,calc.fp1(p)); // for n in [1..i] do calc(n,p) + "%2d:\t%d".fmt(i,p[i]).println(); +} diff --git a/Task/99-Bottles-of-Beer/00DESCRIPTION b/Task/99-Bottles-of-Beer/00DESCRIPTION index 429e8fe81f..238e9d0278 100644 --- a/Task/99-Bottles-of-Beer/00DESCRIPTION +++ b/Task/99-Bottles-of-Beer/00DESCRIPTION @@ -4,23 +4,26 @@ Display the complete lyrics for the song:     '''99 bottles of beer on ;The beersong: The lyrics follow this form: - X bottles of beer on the wall - X bottles of beer - Take one down, pass it around - X-1 bottles of beer on the wall - X-1 bottles of beer on the wall - ... - Take one down, pass it around - 0 bottles of beer on the wall -Where X and X-1 are replaced by numbers of course. +
+ 99 bottles of beer on the wall
+ 99 bottles of beer
+ Take one down, pass it around
+ 98 bottles of beer on the wall

+ + 98 bottles of beer on the wall
+ 98 bottles of beer
+ Take one down, pass it around
+ 97 bottles of beer on the wall +
+ +... and so on, until reaching 0. Grammatical support for "1 bottle of beer" is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). - ;See also: * http://99-bottles-of-beer.net/ * [[:Category:99_Bottles_of_Beer]] diff --git a/Task/99-Bottles-of-Beer/0815/99-bottles-of-beer.0815 b/Task/99-Bottles-of-Beer/0815/99-bottles-of-beer.0815 deleted file mode 100644 index 350b8fdf26..0000000000 --- a/Task/99-Bottles-of-Beer/0815/99-bottles-of-beer.0815 +++ /dev/null @@ -1,25 +0,0 @@ -<:63:x<:20:=<:62:>=>=><:6F:x<:74:=<:6C:>=>>=><:65:x<:73:=<:20:>=>=><:6F:x<:66:=<:20:>=>=> -<:62:x<:65:=<:72:>=>>=><:20:x<:6F:=<:6E:>=>=><:20:x<:74:=<:68:>=>=><:65:x<:20:=<:77:>=>=> -<:61:x<:6C:=>=>><:54:x<:61:=<:6B:>=>=><:65:x<:20:=<:6F:>=>=><:6E:x<:65:=<:20:>=>=><:64:x -<:6F:=<:77:>=>=><:6E:x<:20:=<:61:>=>=><:6E:x<:64:=<:20:>=>=><:70:x<:61:=<:73:>=>=>><:20:x -<:69:=<:74:>=>=><:20:x<:61:=<:72:>=>=><:6F:x<:75:=<:6E:>=>=><:64:~>}:_start:{~%><:1c:~ -}:_99:~{~$>=<:01:x-^:_99:<:0D:~$@:20:{~%><:10:~}:_98:~{~$>=<:01:x-^:_98:<:0D:~$@:c:<:20:~ -}:_97:~{~$>=<:01:x-^:_97:<:0D:~${x<:01:x->&==<:01:-#:_322:{~%><:1c:~}:_96:~{~$>=<:01:x- -^:_96:<:d:~$$@:20:{~>&^:_start:}:_90:?<:4E:x<:6F:=<:20:>=>=><:6D:x<:6F:=<:72:>=>=><:65:x -<:20:=<:62:>=>=><:6F:x<:74:=<:6C:>=>>=><:65:x<:73:=<:20:>=>=><:6F:x<:66:=<:20:>=>=><:62:x -<:65:=<:72:>=>>=><:20:x<:6F:=<:6E:>=>=><:20:x<:74:=<:68:>=>=><:65:x<:20:=<:77:>=>=><:61:x -<:6C:=>=>><:02:~}:_70:><:23:~}:_80:~{~$>=<:01:x-^:_80:{~<:01:=-#:_60:<:0D:~$$=^:_70:}:_60: -<:0D:~$<:17:~}:_81:~{~$=<:01:x-^:_81:<:0D:~$?<:47:x<:6F:=<:20:>=>=><:74:x<:6F:=<:20:>=>=> -<:74:x<:68:=<:65:>=>=><:20:x<:73:=<:74:>=>=><:6F:x<:72:=<:65:>=>=><:20:x<:61:=<:6E:>=>=> -<:64:x<:20:=<:62:>=>=><:75:x<:79:=<:20:>=>=><:73:x<:6F:=<:6D:>=>=><:65:x<:20:=<:6D:>=>=> -<:6F:x<:72:=<:65:>=>=><:21:~}:_18:~{~$=<:01:x-^:_18:<:0D:~$<:63:x<:20:=<:62:>=>=><:6F:x -<:74:=<:6C:>=>>=><:65:x<:73:=<:20:>=>=><:6F:x<:66:=<:20:>=>=><:62:x<:65:=<:72:>=>>=><:20: -x<:6F:=<:6E:>=>=><:20:x<:74:=<:68:>=>=><:65:x<:20:=<:77:>=>=><:61:x<:6C:=>=>>{~%<:1c:~ -}:_21:~{~$=<:01:x-^:_21:<:0D:~$^:end:}:_322:?<:01:x<:20:=<:62:>=>=><:6F:x<:74:=<:6C:>=>>= -><:65:x<:20:=<:6F:>=>=><:66:x<:20:=>=><:62:x<:65:=<:72:>=>>=><:20:x<:6F:=<:6E:>=>=><:20:x -<:74:=<:68:>=>=><:65:x<:20:=<:77:>=>=><:61:x<:6C:=>=>><:54:x<:61:=<:6B:>=>=><:65:x<:20:= -<:6F:>=>=><:6E:x<:65:=<:20:>=>=><:64:x<:6F:=<:77:>=>=><:6E:x<:20:=<:61:>=>=><:6E:x<:64:= -<:20:>=>=><:70:x<:61:=<:73:>=>=>><:20:x<:69:=<:74:>=>=><:20:x<:61:=<:72:>=>=><:6F:x<:75:= -<:6E:>=>=><:64:~>{~%><:1b:~}:_299:~{~$>=<:01:x-^:_299:<:0D:~$$@:20:{~%><:1b:~}:_298:~{~$> -=<:01:x-^:_298:<:0D:~$@:20:{~%<:f:~}:_297:~{~$>=<:01:x-^:_297:<:0D:~$@:c:<:20:~}:_296:~{~ -$>=<:01:x-^:_296:<:0D:~${x<:01:x->&==<:01:-^:_90: diff --git a/Task/99-Bottles-of-Beer/6502-Assembly/99-bottles-of-beer.6502 b/Task/99-Bottles-of-Beer/6502-Assembly/99-bottles-of-beer.6502 deleted file mode 100644 index 671af377de..0000000000 --- a/Task/99-Bottles-of-Beer/6502-Assembly/99-bottles-of-beer.6502 +++ /dev/null @@ -1,157 +0,0 @@ - .CR 6502 - .TF AP1BEER.O,AP1 - .LF AP1BEER.LST - .OR $0BEE -;-------------------------------------; -; BEER SONG IN 6502 ASSEMBLY LANGUAGE ; -; BY BARRYM 2010-05-30 ; -; THANKS TO SBPROJECTS.COM FOR LOTS ; -; OF VALUABLE INFORMATION AND A ; -; VERY NICE ASSEMBLER! ; -;-------------------------------------; -; THE TARGET MACHINE FOR THIS PROGRAM ; -; IS THE APPLE 1, BUT IT WOULD BE ; -; EASY TO MAKE IT RUN ON OTHER 65XX ; -; MACHINES BY CHANGING THE NEXT TWO ; -; EQUATES. SOME MACHINE-TESTED ; -; EXAMPLES: ; -; APPLE II, +, E, C: $FDED, $80 ; -; COMMODORE 64: $FFD2, $00 ; -;-------------------------------------; -ECHO = $FFEF ;EMIT A REG AS ASCII -ORMASK = $80 ;($00 FOR + ASCII) -; -MAXBEER = 99 ;INITIAL BEER COUNT -;-------------------------------------; -; X REG. IS THE BOTTLE COUNTER. ; -; Y REG. IS THE STRING INDEX POINTER, ; -; AND THE TENS DIGIT IN THE BINARY- ; -; TO-ASCII CONVERSION ROUTINE. ; -; A REG. HANDLES EVERYTHING ELSE WITH ; -; A LITTLE HELP FROM THE STACK. ; -; ZERO PAGE ISN'T DIRECTLY DISTURBED. ; -;-------------------------------------; -; EMIT COMPLETE CORRECT SONG ADJUSTED ; -; FOR UPPER-CASE 40-COLUMN DISPLAY. ; -;-------------------------------------; - LDX #MAXBEER ;X=MAXBEER - BNE PRSONG ;SING THE SONG & RTS -;-------------------------------------; -; EMIT WHOLE SONG UP TO LAST SENTENCE.; -;-------------------------------------; -BEERME: - LDY #TAKE1-TXT ;? "TAKE ... AROUND," - JSR PRBOB ;? X;" BOT ... WALL." -PRSONG: ; ;? - LDY #CR-TXT ;? X;" BOT ... WALL," - JSR PRBOB ;? X;" BOT ... BEER." - DEX ;X=X-1 - BPL BEERME ;IF X>=0 THEN BEERME -;-------------------------------------; -; EMIT LAST SENTENCE AND FALL THROUGH.; -;-------------------------------------; - LDX #MAXBEER X=MAXBEER: -; ? "GO TO ... MORE," -;-------------------------------------; -; PRINT A PROPERLY PUNCTUATED "BOTTLE ; -; OF BEER" SENTENCE. ; -;-------------------------------------; -PRBOB: - TYA - PHA ;SAVE THE PRE$ PTR - JSR PUTS ;? PRE$; - TXA ;IF X=0 THEN - BEQ PRBOTT ; ? "NO MORE"; - LDY #"0"-1 ;ELSE - SEC ;( -DIV10: - SBC #10 ; Y=INT(X/10) - INY - BCS DIV10 - ADC #10+'0' - CPY #"0" - BEQ ONEDIG - PHA ; IF Y>0 THEN - TYA ? Y; - JSR PUTCH - PLA ; ? X MOD 10; -ONEDIG: - LDY #BOTTL-TXT ;) -PRBOTT: - JSR PUTCH ;? " BOTTLE"; - CPX #1 - BNE PLURAL - INY ;IF X<>1 THEN ? "S"; -PLURAL: - JSR PUTS ;? " OF BEER"; - PLA ;RECALL THE PRE$ PTR - CMP #COMCR-TXT - BEQ PRDOT - PHA ;IF APPROPRIATE THEN - JSR PUTS ; ? " ON THE WALL"; - PLA - LDY #COMCR-TXT ;IF APPROPRIATE THEN - CMP #CR-TXT ; ? ",": - BEQ PRBOB ; ? X;" ... BEER"; -PRDOT: - LDY #DOTCR-TXT ;? "." -;-------------------------------------; -; EMIT A HI-BIT-SET TERMINATED STRING ; -; @ OFFSET Y AND EXIT WITH Y @ THE ; -; BEGINNING OF THE NEXT STRING. ; -;-------------------------------------; -PUTS: - LDA TXT,Y ;GRAB A STRING CHAR - INY ;ADVANCE STRING PTR -PUTCH: - PHA - ORA #ORMASK - AND #ORMASK+127 ;FORMAT CHAR FOR ECHO - JSR ECHO ;SHOOT IT TO CONSOLE - PLA - BPL PUTS ;LOOP IF APPROPRIATE - RTS -;-------------------------------------; -; OPTIMIZED SONG LYRIC STRINGS. ; -;-------------------------------------; -TXT: -TAKE1: - .AS "TAKE ONE DOWN AND" - .AS " PASS IT AROUND" -COMCR: - .AS "," -CR: - .AT #13 - .AS "NO MORE" -BOTTL: - .AT " BOTTLE" - .AT "S OF BEER" - .AT " ON THE WALL" -DOTCR: - .AT ".",#13 - .AS "GO TO THE STORE AND" - .AT " BUY SOME MORE,",#13 - .EN -;-------------------------------------; -; APPLE 1 MONITOR HEX DUMP FOLLOWS. ; -; ENTER AS SHOWN INTO THE MONITOR, ; -; AND LET THE BEER FLOW!! ; -;-------------------------------------; -0BEE -:A2 63 D0 05 A0 00 20 01 0C A0 21 20 01 -:0C CA 10 F3 A2 63 98 48 20 3C 0C 8A F0 -:16 A0 AF 38 E9 0A C8 B0 FB 69 3A C0 B0 -:F0 06 48 98 20 40 0C 68 A0 29 20 40 0C -:E0 01 D0 01 C8 20 3C 0C 68 C9 20 F0 0B -:48 20 3C 0C 68 A0 20 C9 21 F0 C7 A0 45 -:B9 4C 0C C8 48 09 80 29 FF 20 EF FF 68 -:10 F1 60 54 41 4B 45 20 4F 4E 45 20 44 -:4F 57 4E 20 41 4E 44 20 50 41 53 53 20 -:49 54 20 41 52 4F 55 4E 44 2C 8D 4E 4F -:20 4D 4F 52 45 20 42 4F 54 54 4C C5 53 -:20 4F 46 20 42 45 45 D2 20 4F 4E 20 54 -:48 45 20 57 41 4C CC 2E 8D 47 4F 20 54 -:4F 20 54 48 45 20 53 54 4F 52 45 20 41 -:4E 44 20 42 55 59 20 53 4F 4D 45 20 4D -:4F 52 45 2C 8D -BEER diff --git a/Task/99-Bottles-of-Beer/6800-Assembly/99-bottles-of-beer.6800 b/Task/99-Bottles-of-Beer/6800-Assembly/99-bottles-of-beer.6800 deleted file mode 100644 index 3eb5df26b2..0000000000 --- a/Task/99-Bottles-of-Beer/6800-Assembly/99-bottles-of-beer.6800 +++ /dev/null @@ -1,157 +0,0 @@ - .cr 6800 - .tf beer6800.obj,AP1 - .lf beer6800 -;=====================================================; -; Beer Song for the Motorola 6800 microprocessor ; -; by barrym 2011-04-19 ; -;-----------------------------------------------------; -; Prints the correct, complete song lyrics to a full ; -; ascii terminal (console) connected to a 1970s ; -; vintage SWTPC 6800 system, which is the target ; -; device for this assembly. ; -; Many thanks to: ; -; swtpc.com for hosting Michael Holley's documents! ; -; sbprojects.com for a very nice assembler! ; -; swtpcemu.com for a very capable emulator! ; -; The 6800 microprocessor is the slightly older, less ; -; popular, and more expensive step-brother of the ; -; 6502. Numerous similarities exist between the ; -; assembly languages of the two, but the 6800 has ; -; its own distinct flavor, which is (judging by how ; -; compact the code ended up) well suited to this ; -; type of small program. I am especially impressed ; -; with the two-byte 'bsr' instruction, and I make ; -; extensive use of it here. ; -; Effort was made to keep the code footprint as small ; -; as possible by re-using substrings and code in a ; -; hacker-like style that makes the program flow a ; -; bit strange to the human eye (the 6800 gobbles it ; -; up without complaint). The final tally: 97 bytes ; -; of instructions, 108 bytes of text, and about 11 ; -; bytes of stack. This includes integer-to-ascii ; -; conversion, blank line between verses, removal of ; -; "s" from "1 bottles", substitution of "no more" ; -; for "0", and proper capitalization of "No more". ; -; reg b is the beer counter ; -; reg x is the string pointer ; -; reg a handles everything else (with a little help ; -; from the system stack) ; -;-----------------------------------------------------; -outeee = $e1d1 ;ROM: console putchar routine -stbeer = 99 ;Must be in the range [0..99] - .or $0f00 -;=====================================================; -; Initialize, sing the song, and exit ; -;-----------------------------------------------------; -main ldab #stbeer ;Beer count = stbeer - bsr prsong ;Sing the entire song - swi ;Return to the monitor. -;=====================================================; -; Emit the entire song up to the last sentence ; -;-----------------------------------------------------; -beerme bsr prbob2 ;Emit second sentence of verse -prsong ldx #nline ;Blank line between verses - ldaa #'N' ;First sentence type = 'N' - bsr prbob ;Emit 1st sentence of verse - decb ;Beer count -= 1 - bpl beerme ;If beer count >= 0 then beerme -;=====================================================; -; Set up the last sentence and fall through to prbob2 ; -;-----------------------------------------------------; - ldab #stbeer ;Beer count = stbeer - ldx #store ;x$ = "Go to the store ..." -;=====================================================; -; Emit a properly punctuated bottle-of-beer sentence, ; -; using beer counter in reg b, pre-string pointer ; -; in reg x, and the sentence type in reg a ('N' = ; -; sentence 1, 'o' = sentence 1.5, 'n' = sentence 2) ; -;-----------------------------------------------------; -prbob2 ldaa #'n' ;Second sentence type = 'n' -prbob psha ;Stack sentence type for later - bsr puts ;Emit pre-string - pula ;Check sentence type and use - psha ; it to prepare the upper- or - anda #'n' ; lower-case of "no more" - ldx #omore ;x$ = "o more bottle" - tstb ;If beer count = 0 then - beq prbott ; skip over the i-to-a - ldx #bottl ;x$ = " bottle" -;=====================================================; -; I-to-A (inline): convert int in b to ascii and emit ; -; with leading zero suppression (0 <= # <= 99)! ; -;-----------------------------------------------------; - pshb ;Stack beer count - ldaa #-1 ; (divten trashes it) -divten subb #10 ;b = ones digit - 10 - inca ;a = tens digit - bcc divten ;If a = 0 then - beq onedig ; suppress leading zero - adda #"0" ;else translate tens digit to - bsr putch ; shifted ascii and emit -onedig addb #'0'+10 ;Translate ones digit to ascii - tba ; and leave it in a for putch - pulb ;Restore beer count -;-----------------------------------------------------; -prbott bsr putch ;Emit a;x$; - cmpb #1 ;If beer count = 1 - bne plural ;then - inx ; skip over the "s" -plural bsr puts ;Emit " ... beer"; - pula ;Restore sentence type - cmpa #'o' ;If type <> 'o' - beq putdot ;then - psha ; emit " on the wall"; - bsr puts ; if type = 'N' then loop - pula ; back to finish the - adda #33 ; first sentence with - bpl prbob ; type = 'o', x$ = ", " -putdot ldx #dotnl ;x$ = ".\n" -;=====================================================; -; Emit string @ x and leave x @ start of next string ; -;-----------------------------------------------------; -puts ldaa 0,x ;a = raw character removed - inx ; from the beginning of x$ -;=====================================================; -; Emit a as ascii and loop into x$ if hi-bit is clear ; -;-----------------------------------------------------; -putch psha ;Stack raw char - anda #$7f ;Mask off the hi-bit - jsr outeee ;Emit a as 7-bit ascii - pula ;Restore raw char - tsta ;If hi-bit is clear then - bpl puts ; loop back into x$ - rts ;All 8 'bsr's use this 'rts'! -;=====================================================; -; Optimized song lyric strings, carefully arranged to ; -; allow the prbob subroutine to take full advantage ; -; of the x register side-effects of puts ; -;-----------------------------------------------------; -omore .as "o more" -bottl .at " bottle" - .at "s of beer" - .at " on the wall" - .at ", " -dotnl .as "." -nline .at #13,#10 - .at "Take one down and pass it around, " -store .at "Go to the store and buy some more, " - .en -;=====================================================; -; The following is a hex dump of the object file, ; -; suitable for copying and pasting into the 6800 ; -; emulator available at swtpcemu.com! ; -;-----------------------------------------------------; -e0F00 C6 63 8D 03 3F 8D 0F CE 0F 86 86 4E 8D 0A 5A 2A -e0F10 F4 C6 63 CE 0F AA 86 6E 36 8D 38 32 36 84 6E CE -e0F20 0F 61 5D 27 15 CE 0F 67 37 86 FF C0 0A 4C 24 FB -e0F30 27 04 8B B0 8D 20 17 8B 3A 33 8D 1A C1 01 26 01 -e0F40 08 8D 10 32 81 6F 27 08 36 8D 08 32 8B 21 2A C8 -e0F50 CE 0F 85 A6 00 08 36 84 7F BD E1 D1 32 4D 2A F3 -e0F60 39 6F 20 6D 6F 72 65 20 62 6F 74 74 6C E5 73 20 -e0F70 6F 66 20 62 65 65 F2 20 6F 6E 20 74 68 65 20 77 -e0F80 61 6C EC 2C A0 2E 0D 8A 54 61 6B 65 20 6F 6E 65 -e0F90 20 64 6F 77 6E 20 61 6E 64 20 70 61 73 73 20 69 -e0FA0 74 20 61 72 6F 75 6E 64 2C A0 47 6F 20 74 6F 20 -e0FB0 74 68 65 20 73 74 6F 72 65 20 61 6E 64 20 62 75 -e0FC0 79 20 73 6F 6D 65 20 6D 6F 72 65 2C A0 -j0F00 diff --git a/Task/99-Bottles-of-Beer/ABAP/99-bottles-of-beer.abap b/Task/99-Bottles-of-Beer/ABAP/99-bottles-of-beer-1.abap similarity index 100% rename from Task/99-Bottles-of-Beer/ABAP/99-bottles-of-beer.abap rename to Task/99-Bottles-of-Beer/ABAP/99-bottles-of-beer-1.abap diff --git a/Task/99-Bottles-of-Beer/ABAP/99-bottles-of-beer-2.abap b/Task/99-Bottles-of-Beer/ABAP/99-bottles-of-beer-2.abap new file mode 100644 index 0000000000..275146818f --- /dev/null +++ b/Task/99-Bottles-of-Beer/ABAP/99-bottles-of-beer-2.abap @@ -0,0 +1,18 @@ +REPORT YCL_99_BOTTLES. + +DATA it_99_bottles TYPE TABLE OF string WITH EMPTY KEY. +DATA(cr_lf) = cl_abap_char_utilities=>cr_lf. +it_99_bottles = VALUE #( + FOR i = 99 THEN i - 1 UNTIL i = 0 ( COND string( LET lv = ( i - 1 ) + lr = i && | bottles of beer on the wall| + && cr_lf + && i && | bottles of beer| + && cr_lf + && |Take one down, pass it around| + && cr_lf + && lv && | bottles of beer on the wall| + && cr_lf IN WHEN 1 = 1 THEN lr ) + ) + ). +cl_demo_output=>write( it_99_bottles ). +cl_demo_output=>display( ). diff --git a/Task/99-Bottles-of-Beer/ACL2/99-bottles-of-beer.acl2 b/Task/99-Bottles-of-Beer/ACL2/99-bottles-of-beer.acl2 deleted file mode 100644 index f5630f373d..0000000000 --- a/Task/99-Bottles-of-Beer/ACL2/99-bottles-of-beer.acl2 +++ /dev/null @@ -1,14 +0,0 @@ -(defun bottles-of-beer (n) - (if (zp n) - nil - (prog2$ (cw (concatenate 'string - "~%" - "~N0 bottle~#1~[~/s~] of beer on the wall,~%" - "~n0 bottle~#1~[~/s~] of beer.~%" - "Take one down, pass it around,~%" - "~n2 bottle~#3~[~/s~] of beer on the wall.~%") - n - (if (= n 1) 0 1) - (1- n) - (if (= n 2) 0 1)) - (bottles-of-beer (- n 1))))) diff --git a/Task/99-Bottles-of-Beer/Aime/99-bottles-of-beer.aime b/Task/99-Bottles-of-Beer/Aime/99-bottles-of-beer.aime index 47a0733c16..ea345b0b86 100644 --- a/Task/99-Bottles-of-Beer/Aime/99-bottles-of-beer.aime +++ b/Task/99-Bottles-of-Beer/Aime/99-bottles-of-beer.aime @@ -1,20 +1,10 @@ -integer -main(void) -{ - cardinal bottles; +integer bottles; - bottles = 99; +bottles = 99; - do { - o_cardinal(bottles); - o_text(" bottles of beer on the wall\n"); - o_cardinal(bottles); - o_text(" bottles of beer\n"); - o_text("Take one down, pass it around\n"); - bottles -= 1; - o_cardinal(bottles); - o_text(" bottles of beer on the wall\n\n"); - } while (bottles); - - return 0; -} +do { + o_(bottles, " bottles of beer on the wall\n"); + o_(bottles, " bottles of beer\n"); + o_("Take one down, pass it around\n"); + o_(bottles -= 1, " bottles of beer on the wall\n\n"); +} while (bottles); diff --git a/Task/99-Bottles-of-Beer/Algae/99-bottles-of-beer.algae b/Task/99-Bottles-of-Beer/Algae/99-bottles-of-beer.algae new file mode 100644 index 0000000000..359d33fcf3 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Algae/99-bottles-of-beer.algae @@ -0,0 +1,20 @@ +# 99 Bottles of Beer on the Wall +# in Algae +# bottles.A +for (i in 99:1:1) { + if (i != 1) { + printf("%d bottles of beer on the wall\n";i); + printf("%d bottles of beer...\n";i); + printf("you take on down and pass it around...\n"); + if ( i == 2) { + printf("%d bottles of beer on the wall\n\n";i-1); + else + printf("%d bottles of beer on the wall\n\n";i-1); + } + else + printf("1 bottle of beer on the wall\n"); + printf("1 bottle of beer...\n"); + printf("you take on down and pass it around..\n"); + printf("no more bottles of beer on the wall!\n\n"); + } +} diff --git a/Task/99-Bottles-of-Beer/AppleScript/99-bottles-of-beer-2.applescript b/Task/99-Bottles-of-Beer/AppleScript/99-bottles-of-beer-2.applescript index 064bf47b16..40e29995d8 100644 --- a/Task/99-Bottles-of-Beer/AppleScript/99-bottles-of-beer-2.applescript +++ b/Task/99-Bottles-of-Beer/AppleScript/99-bottles-of-beer-2.applescript @@ -1,64 +1,67 @@ --- BRIEF - +-- BRIEF ----------------------------------------------------------------------- on run + set localisations to ¬ + {"on the wall", ¬ + "Take one down, pass it around", ¬ + "Better go to the store to buy some more", "bottle"} intercalate("\n\n", ¬ - map(recitation, range(99, 0))) - + (map(curry(incantation)'s |λ|(localisations), enumFromTo(99, 0)))) end run --- DECLARATIVE +-- DECLARATIVE ----------------------------------------------------------------- -script recitation - property coordinates : " on the wall" - property redistribution : "Take one down, pass it around" - property resort : "Better go to the store to buy some more" - property unit : "bottle" +-- incantation :: [String] -> Int -> String +on incantation(xs, n) + script asset + on |λ|(n) + unwords({(n as string), item -1 of xs & cond(n ≠ 1, "s", "")}) + end |λ| + end script - -- Int -> String - on lambda(n) - if n > 0 then - set reserve to resourceDescriptor(n) - set residue to resourceDescriptor(n - 1) + script store + on |λ|(n) + unwords({asset's |λ|(n), item 1 of xs}) + end |λ| + end script - intercalate(linefeed, ¬ - {reserve & coordinates, reserve, ¬ - redistribution, residue & coordinates}) - else - resort - end if - end lambda - - -- resourceDescriptor :: Int -> String - on resourceDescriptor(n) - if n ≠ 1 then - (n as string) & space & unit & "s" - else - "1 " & unit - end if - end resourceDescriptor -end script + set {distribute, solve} to items 2 thru 3 of xs + if n > 0 then + unlines({store's |λ|(n), asset's |λ|(n), distribute, store's |λ|(n - 1)}) + else + solve + end if +end incantation +-- GENERICALLY DYSFUNCTIONAL --------------------------------------------------- --- DYSFUNCTIONAL +-- cond :: Bool -> a -> a -> a +on cond(bln, f, g) + if bln then + f + else + g + end if +end cond --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map +-- curry :: (Script|Handler) -> Script +on curry(f) + script + on |λ|(a) + script + on |λ|(b) + |λ|(a, b) of mReturn(f) + end |λ| + end script + end |λ| + end script +end curry --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then set d to -1 else set d to 1 @@ -68,7 +71,7 @@ on range(m, n) set end of lst to i end repeat return lst -end range +end enumFromTo -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) @@ -78,6 +81,18 @@ on intercalate(strText, lstText) return strJoined end intercalate +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) @@ -85,7 +100,17 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn + +-- unlines :: [String] -> String +on unlines(xs) + intercalate(linefeed, xs) +end unlines + +-- unwords :: [String] -> String +on unwords(xs) + intercalate(space, xs) +end unwords diff --git a/Task/99-Bottles-of-Beer/Applesoft-BASIC/99-bottles-of-beer.applesoft b/Task/99-Bottles-of-Beer/Applesoft-BASIC/99-bottles-of-beer.applesoft deleted file mode 100644 index 431466059b..0000000000 --- a/Task/99-Bottles-of-Beer/Applesoft-BASIC/99-bottles-of-beer.applesoft +++ /dev/null @@ -1,7 +0,0 @@ -10 HOME -20 FOR B=99 TO 1 STEP -1 -30 PRINT B;" BOTTLE OF BEER ON THE WALL" -40 PRINT B;" BOTTLE OF BEER ON THE WALL" -50 PRINT "TAKE ONE DOWN, PASS IT AROUND" -60 PRINT B-1;" BOTTLE OF BEER ON THE WALL" -70 NEXT B diff --git a/Task/99-Bottles-of-Beer/Astro/99-bottles-of-beer.astro b/Task/99-Bottles-of-Beer/Astro/99-bottles-of-beer.astro new file mode 100644 index 0000000000..13dcf7a1b7 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Astro/99-bottles-of-beer.astro @@ -0,0 +1,12 @@ +fun bottles(n): + | 0 -> "No more bottles" + | 1 -> "1 bottle" + | _ -> "$n bottles" + +for n in [100:1]: + print """ + $(bottles n) of beer on the wall + $(bottles n) of beer + Take one down, pass it around + $(bottles n-1) of beer on the wall\n + """ diff --git a/Task/99-Bottles-of-Beer/AutoHotkey/99-bottles-of-beer-1.ahk b/Task/99-Bottles-of-Beer/AutoHotkey/99-bottles-of-beer-1.ahk deleted file mode 100644 index de2110d039..0000000000 --- a/Task/99-Bottles-of-Beer/AutoHotkey/99-bottles-of-beer-1.ahk +++ /dev/null @@ -1,15 +0,0 @@ -; RC: 99 bottles of beer - b = 99 - Loop, %b% { - s .= b . " bottles of beer on the wall,`n" - . b . " bottles of beer.`nTake one down, pass it around,`n" - . b-1 . " bottles of beer on the wall.`n`n" - b-- - } - Gui, Add, Edit, w200 h200, %s% - Gui, Show, , 99 bottles of beer -Return ; end of auto-execute section - -GuiClose: - ExitApp -Return diff --git a/Task/99-Bottles-of-Beer/AutoHotkey/99-bottles-of-beer-2.ahk b/Task/99-Bottles-of-Beer/AutoHotkey/99-bottles-of-beer-2.ahk deleted file mode 100644 index f87c7cd935..0000000000 --- a/Task/99-Bottles-of-Beer/AutoHotkey/99-bottles-of-beer-2.ahk +++ /dev/null @@ -1,17 +0,0 @@ -n=99 -Gui, Font, s20 cMaroon, Comic Sans MS -Gui, Add, Text, w500 vLyrics, %n% bottles of beer on the wall... -Gui, Show -Loop { - Sleep, 2000 - GuiControl,,Lyrics,% n!=1 ? n " bottles of beer.":n " bottle of beer." - Sleep, 2000 - GuiControl,,Lyrics,% n ? "Take one down, pass it around...":"Go to the store, buy some more..." - Sleep, 2000 - n := n ? --n:99 - GuiControl,,Lyrics,% n!=1 ? n " bottles of beer on the wall.":n " bottle of beer on the wall." - Sleep, 2000 - GuiControl,,Lyrics,% n!=1 ? n " bottles of beer on the wall...":n " bottle of beer on the wall..." -} -GuiClose: -ExitApp diff --git a/Task/99-Bottles-of-Beer/AutoHotkey/99-bottles-of-beer-3.ahk b/Task/99-Bottles-of-Beer/AutoHotkey/99-bottles-of-beer-3.ahk deleted file mode 100644 index 7e0b0fc58a..0000000000 --- a/Task/99-Bottles-of-Beer/AutoHotkey/99-bottles-of-beer-3.ahk +++ /dev/null @@ -1,7 +0,0 @@ -b=99 -Loop, %b% { -s := b " bottles of beer on the wall, " b " bottles of beer, Take one down, pass it around " b-1 " bottles of beer on the wall" -b-- -TrayTip,,%s% -sleep, 40 -} diff --git a/Task/99-Bottles-of-Beer/AutoHotkey/99-bottles-of-beer-4.ahk b/Task/99-Bottles-of-Beer/AutoHotkey/99-bottles-of-beer-4.ahk deleted file mode 100644 index 24ecb70ff7..0000000000 --- a/Task/99-Bottles-of-Beer/AutoHotkey/99-bottles-of-beer-4.ahk +++ /dev/null @@ -1,10 +0,0 @@ -N=o more -Z=99 -L:=Z M:=(B:=" bottle")"s" -Loop 99 -V.=L (W:=(O:=" of beer")" on the wall")",`n"L O ",`nTake one down and pass it around,`n"(L:=(--Z ? Z:"N"N)(Z=1 ? B:M))W ".`n`n" -Gui,Add,Edit,w600 h250,% V L W ", n"N M O ".`nGo to the store and buy some more, 99"M W "." -Gui,Show -Return -GuiClose: -ExitApp diff --git a/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-1.autoit b/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-1.autoit deleted file mode 100644 index 2d8243ba91..0000000000 --- a/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-1.autoit +++ /dev/null @@ -1,21 +0,0 @@ -local $bottleNo=99 -local $lyrics=" " - -While $bottleNo<>0 - If $bottleNo=1 Then - $lyrics&=$bottleNo & " bottles of beer on the wall" & @CRLF - $lyrics&=$bottleNo & " bottles of beer" & @CRLF - $lyrics&="Take one down, pass it around" & @CRLF - Else - $lyrics&=$bottleNo & " bottles of beer on the wall" & @CRLF - $lyrics&=$bottleNo & " bottles of beer" & @CRLF - $lyrics&="Take one down, pass it around" & @CRLF - EndIf - If $bottleNo=1 Then - $lyrics&=$bottleNo-1 & " bottle of beer" & @CRLF - Else - $lyrics&=$bottleNo-1 & " bottles of beer" & @CRLF - EndIf - $bottleNo-=1 -WEnd -MsgBox(1,"99",$lyrics) diff --git a/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-2.autoit b/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-2.autoit deleted file mode 100644 index cab0ffcb62..0000000000 --- a/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-2.autoit +++ /dev/null @@ -1,15 +0,0 @@ -$bottles = 99 -$lyrics1 = " bottles of beer on the wall. " -$lyrics2 = " bottles of beer. Take one down and pass it around. " - - For $i = $bottles To 1 Step -1 - If $i = 1 Then - $lyrics1 = " bottle of beer on the wall. " - $lyrics2 = " bottle of beer. Take one down and pass it around. " - $lyrics3 = " Go to the store and get some more! No bottles of beer on the wall!" - ConsoleWrite($bottles & $lyrics1 & $bottles & $lyrics2 & $lyrics3 & @CRLF) - Else - ConsoleWrite($bottles & $lyrics1 & $bottles & $lyrics2 & $bottles - 1 & $lyrics1 & @CRLF) - $bottles -= 1 - EndIf - Next diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-1.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-1.basic deleted file mode 100644 index cefa889e54..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-1.basic +++ /dev/null @@ -1,12 +0,0 @@ -PLAY "<" -FOR x = 99 TO 0 STEP -1 - PRINT x; "bottles of beer on the wall" - PRINT x; "bottles of beer" - PRINT "Take one down, pass it around" - PRINT x-1; "bottles of beer on the wall" - PRINT - PLAY "e-8e-8e-8e-8e-8e-8e-4"'X bottles of beer on the wall - PLAY "f8f8f8c8c8c8f4"'X bottles of beer - PLAY "d4d8d8 N0 d8d8d8d4"'take one down, pass it around - PLAY "c8c8d8d+8d+8d+8d+4"'X-1 bottles of beer on the wall -NEXT x diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-10.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-10.basic deleted file mode 100644 index 5dffeed1a5..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-10.basic +++ /dev/null @@ -1,13 +0,0 @@ -For bottles = 99 To 1 Step -1 - song$ = song$ + str$(bottles) + " bottle" - If (bottles > 1) Then song$ = song$ + "s" - song$ = song$ + " of beer on the wall, " + str$(bottles) + " bottle" - If (bottles > 1) Then song$ = song$ + "s" - song$ = song$ + " of beer," + chr$(13) + chr$(10) + "Take one down, pass it around, " + str$(bottles - 1) + " bottle" - If (bottles > 2) Or (bottles = 1) Then song$ = song$ + "s" - song$ = song$ + " of beer on the wall." + chr$(13) + chr$(10) -Next bottles -song$ = song$ + "No more bottles of beer on the wall, no more bottles of beer." _ - + chr$(13) + chr$(10) + "Go to the store and buy some more, 99 bottles of beer on the wall." - -Print song$ diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-11.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-11.basic deleted file mode 100644 index b1c205e835..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-11.basic +++ /dev/null @@ -1,13 +0,0 @@ -If OpenConsole() - Define Bottles=99 - While Bottles - PrintN(Str(Bottles)+" bottles of beer on the wall") - PrintN(Str(Bottles)+" bottles of beer") - PrintN("Take one down, pass it around") - Bottles-1 - PrintN(Str(Bottles)+" bottles of beer on the wall"+#CRLF$) - Wend - - PrintN(#CRLF$+#CRLF$+"Press ENTER to exit"):Input() - CloseConsole() -EndIf diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-12.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-12.basic deleted file mode 100644 index 3e437bb017..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-12.basic +++ /dev/null @@ -1,59 +0,0 @@ -Prototype Wall_Action(*Self, Number.i) - -Structure WallClass - Inventory.i - AddBottle.Wall_Action - DrinkAndSing.Wall_Action -EndStructure - -Procedure.s _B(n, Short=#False) - Select n - Case 0 : result$="No more bottles " - Case 1 : result$=Str(n)+" bottle of beer" - Default: result$=Str(n)+" bottles of beer" - EndSelect - If Not Short: result$+" on the wall": EndIf - ProcedureReturn result$+#CRLF$ -EndProcedure - -Procedure PrintBottles(*Self.WallClass, n) - Bottles$=" bottles of beer " - Bottle$ =" bottle of beer " - txt$ = _B(*Self\Inventory) - txt$ + _B(*Self\Inventory, #True) - txt$ + "Take one down, pass it around"+#CRLF$ - *Self\AddBottle(*Self, -1) - txt$ + _B(*self\Inventory) - PrintN(txt$) - ProcedureReturn *Self\Inventory -EndProcedure - -Procedure AddBottle(*Self.WallClass, n) - i=*Self\Inventory+n - If i>=0 - *Self\Inventory=i - EndIf -EndProcedure - -Procedure InitClass() - *class.WallClass=AllocateMemory(SizeOf(WallClass)) - If *class - InitializeStructure(*class, WallClass) - With *class - \AddBottle =@AddBottle() - \DrinkAndSing =@PrintBottles() - EndWith - EndIf - ProcedureReturn *class -EndProcedure - -If OpenConsole() - *MyWall.WallClass=InitClass() - If *MyWall - *MyWall\AddBottle(*MyWall, 99) - While *MyWall\DrinkAndSing(*MyWall, #True): Wend - ; - PrintN(#CRLF$+#CRLF$+"Press ENTER to exit"):Input() - CloseConsole() - EndIf -EndIf diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-13.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-13.basic deleted file mode 100644 index 97a23b973b..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-13.basic +++ /dev/null @@ -1,8 +0,0 @@ -dim bottles as Integer = 99 -While bottles > 0 - Print(str(bottles) + " bottles of beer on the wall") - Print(str(bottles) + " bottles of beer") - Print("Take one down, pass it around") - bottles = bottles - 1 - Print(str(bottles) + " bottles of beer on the wall") -Wend diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-14.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-14.basic deleted file mode 100644 index fdbfabe74e..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-14.basic +++ /dev/null @@ -1,12 +0,0 @@ -b$ = " bottles" -for bottles = 99 To 1 Step -1 - If (bottles = 1) then b$ = " bottle" - print bottles;b$;" of beer on the wall, " - print bottles ;b$;" of beer" - print "Take one down, pass it around, " - if bottles = 1 then - print "No bottles of beer on the wall" - else - print bottles - 1;b$;" of beer on the wall.";chr$(10) - end if -next bottles diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-15.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-15.basic deleted file mode 100644 index cca30e2823..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-15.basic +++ /dev/null @@ -1,13 +0,0 @@ -PROGRAM:BEER -:For(I,99,1,-1) -:Disp I -:Disp "BOTTLES OF BEER" -:Disp "ON THE WALL," -:Disp I -:Pause "BOTTLES OF BEER," -:Disp "TAKE ONE DOWN," -:Disp "PASS IT AROUND," -:Disp I-1 -:Disp "BOTTLES OF BEER" -:Disp "ON THE WALL." -:End diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-16.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-16.basic deleted file mode 100644 index be967a6f9c..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-16.basic +++ /dev/null @@ -1,47 +0,0 @@ -Prgm - Local i,plural,clockWas,t,k,wait - "s" → plural - 0 → k - isClkOn() → clockWas - - Define wait() = Prgm - EndPrgm - - ClockOn - - For i,99,0,–1 - Disp "" - Disp string(i) & " bottle" & plural & " of beer on the" - Disp "wall, " & string(i) & " bottle" & plural & " of beer." - - getTime()[3]→t - While getTime()[3] = t and k = 0 : getKey() → k : EndWhile - If k ≠ 0 Then : Exit : EndIf - - Disp "Take one down, pass it" - Disp "around." - - getTime()[3]→t - While getTime()[3] = t and k = 0 : getKey() → k : EndWhile - If k ≠ 0 Then : Exit : EndIf - - If i - 1 = 1 Then - "" → plural - EndIf - If i > 1 Then - Disp string(i-1) & " bottle" & plural & " of beer on the" - Disp "wall." - Else - Disp "No more bottles of beer on" - Disp "the wall." - EndIf - - getTime()[3]→t - While abs(getTime()[3] - t)<2 and k = 0 : getKey() → k : EndWhile - If k ≠ 0 Then : Exit : EndIf - - EndFor - If not clockWas Then - ClockOff - ENdIf -EndPrgm diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-17.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-17.basic deleted file mode 100644 index 65e32dce45..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-17.basic +++ /dev/null @@ -1,33 +0,0 @@ -Sub Main() - Const bottlesofbeer As String = " bottles of beer" - Const onthewall As String = " on the wall" - Const takeonedown As String = "Take one down, pass it around" - Const onebeer As String = "1 bottle of beer" - - Dim bottles As Long - - For bottles = 99 To 3 Step -1 - Debug.Print CStr(bottles) & bottlesofbeer & onthewall - Debug.Print CStr(bottles) & bottlesofbeer - Debug.Print takeonedown - Debug.Print CStr(bottles - 1) & bottlesofbeer & onthewall - Debug.Print - Next - - Debug.Print "2" & bottlesofbeer & onthewall - Debug.Print "2" & bottlesofbeer - Debug.Print takeonedown - Debug.Print onebeer & onthewall - Debug.Print - - Debug.Print onebeer & onthewall - Debug.Print onebeer - Debug.Print takeonedown - Debug.Print "No more" & bottlesofbeer & onthewall - Debug.Print - - Debug.Print "No" & bottlesofbeer & onthewall - Debug.Print "No" & bottlesofbeer - Debug.Print "Go to the store, buy some more" - Debug.Print "99" & bottlesofbeer & onthewall -End Sub diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-18.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-18.basic deleted file mode 100644 index e1b3ae76fe..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-18.basic +++ /dev/null @@ -1,20 +0,0 @@ -Module Module1 - Sub Main() - Dim Bottles As Integer - For Bottles = 99 To 0 Step -1 - If Bottles = 0 Then - Console.WriteLine("No more bottles of beer on the wall, no more bottles of beer.") - Console.WriteLine("Go to the store and buy some more, 99 bottles of beer on the wall.") - Console.ReadLine() - ElseIf Bottles = 1 Then - Console.WriteLine(Bottles & " bottle of beer on the wall, " & Bottles & " bottle of beer.") - Console.WriteLine("Take one down and pass it around, no more bottles of beer on the wall.") - Console.ReadLine() - Else - Console.WriteLine(Bottles & " bottles of beer on the wall, " & Bottles & " bottles of beer.") - Console.WriteLine("Take one down and pass it around, " & (Bottles - 1) & " bottles of beer on the wall.") - Console.ReadLine() - End If - Next - End Sub -End Module diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-2.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-2.basic deleted file mode 100644 index 3dd875c8d6..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-2.basic +++ /dev/null @@ -1,7 +0,0 @@ -FOR x = 99 TO 1 STEP -1 - PRINT x; "bottles of beer on the wall" - PRINT x; "bottles of beer" - PRINT "Take one down, pass it around" - PRINT x-1; "bottles of beer on the wall" - PRINT -NEXT x diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-3.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-3.basic deleted file mode 100644 index 431466059b..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-3.basic +++ /dev/null @@ -1,7 +0,0 @@ -10 HOME -20 FOR B=99 TO 1 STEP -1 -30 PRINT B;" BOTTLE OF BEER ON THE WALL" -40 PRINT B;" BOTTLE OF BEER ON THE WALL" -50 PRINT "TAKE ONE DOWN, PASS IT AROUND" -60 PRINT B-1;" BOTTLE OF BEER ON THE WALL" -70 NEXT B diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-4.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-4.basic deleted file mode 100644 index 795e9dcabd..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-4.basic +++ /dev/null @@ -1,33 +0,0 @@ -#length of querter and eight note in ms -n4 = 1000 * 60 / 80 / 4 -n8 = n4 / 2 - -#frequency of musical notes in hz -e = 330 -ef = 311 -b = 247 -bf = 233 -f = 349 -c = 262 -d = 294 -ds = 311 -a = 220 - -dim notes(1) -dim lengs(1) - -# redim is automatic when using a {} list to assign an array -notes = {ef, ef, ef, bf, bf, bf, ef, ef, ef, ef, f , f , f , c , c , c , f , d , d , d , d , d , d , d , bf, bf, bf, c , c , ef, ef, ef, ef, ef} -lengs = {n8, n8, n8, n8, n8, n8, n8, n8, n8, n4, n8, n8, n8, n8, n8, n8, n4, n4, n8, n8, n8, n8, n8, n4, n8, n8, n8, n8, n8, n8, n8, n8, n8, n4 } - -for x = 99 to 1 step -1 - for t = 0 to notes[?]-1 - if t = 0 then print x + " bottles of beer on the wall" - if t = 11 then print x + " bottles of beer" - if t = 18 then print "Take one down, pass it around" - if t = 25 then print(x-1) + " bottles of beer on the wall" - sound notes[t], lengs[t] - pause .002 - next t - print -next x diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-5.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-5.basic deleted file mode 100644 index f55119ce84..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-5.basic +++ /dev/null @@ -1,32 +0,0 @@ - N_Bottles = 99 - - beer$ = " of beer" - wall$ = " on the wall" - unit$ = "99 bottles" - - WHILE N_Bottles >= 0 - - IF N_Bottles=0 THEN - PRINT '"No more bottles" beer$ wall$ ", " unit$ beer$ "." - PRINT "Go to the store and buy some more, "; - ELSE - PRINT 'unit$ beer$ wall$ ", " unit$ beer$ "." - PRINT "Take one down and pass it around, "; - ENDIF - - N_Bottles -= 1 - - CASE N_Bottles OF - WHEN 0: - unit$ = "no more bottles" - WHEN 1: - unit$ = "1 bottle" - OTHERWISE: - unit$ = STR$((N_Bottles + 100) MOD 100) + " bottles" - ENDCASE - - PRINT unit$ beer$ wall$ "." - - ENDWHILE - - END diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-6.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-6.basic deleted file mode 100644 index e0e0202adf..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-6.basic +++ /dev/null @@ -1,142 +0,0 @@ -DEF Win:WINDOW -DEF Close:CHAR -DEF ScreenSizeX,ScreenSizeY:INT - -DECLARE VSpace(Number:UINT) -DECLARE CLR() - -DEF TheLine$[4],Number$,Erase:STRING -DEF TheLine,TextHeight,TextWidth:INT -DEF TextX,TextY:UINT - -TheLine$[0]="bottles" -TheLine$[1]="of beer on the wall." -TheLine$[2]="of beer." -TheLine$[3]="Take one down, pass it around." - -BottlesOfBeer=99 -TheLine=1 - -GETSCREENSIZE(ScreenSizeX,ScreenSizeY) - -WINDOW Win,0,0,ScreenSizeX,ScreenSizeY,@MINBOX|@MAXBOX|@SIZE,0,"99 Bottles Of Beer",MainHandler - -GETTEXTSIZE(Win,TheLine$[3],TextWidth,TextHeight) - -Erase$=STRING$(TextWidth," ") - -PRINT Win,"Let's sing a song." - -VSpace(2) - -'1.2 seconds. -STARTTIMER Win,1200 - -GOSUB Sing - -WAITUNTIL Close=1 - -CLOSEWINDOW Win - -END - -SUB MainHandler - - SELECT @CLASS - - CASE @IDCLOSEWINDOW - - Close=1 - - CASE @IDTIMER - - GOSUB Sing - - ENDSELECT - -RETURN - -SUB Sing - - DEF Sing:INT - - Sing=TheLine - - MOVE Win,TextX,TextY - - Number$=STR$(BottlesOfBeer) - - IF BottlesOfBeer=0 - - Number$="No more" - TheLine$[0]="bottles" - TheLine$[3]="Go to the store and buy some more." - - ENDIF - - IF BottlesOfBeer=1 - - TheLine$[0]="bottle" - TheLine$[3]="Take it down, pass it around." - - ENDIF - - IF TheLine=4 THEN Sing=1 - - IF (TheLine=1)|(TheLine=2)|(TheLine=4) - - IF BottlesOfBeer>-1 THEN PRINT Win,Number$+" "+TheLine$[0]+" "+TheLine$[Sing] ELSE GOSUB TheEnd - - ELSE - - PRINT Win,TheLine$[3] - - BottlesOfBeer=BottlesOfBeer-1 - - ENDIF - - TheLine=TheLine+1 - - VSpace(1) - - IF TheLine>4 - - TheLine=1 - - VSpace(1) - - ENDIF - -RETURN - -SUB TheEnd - - PRINT Win,"What's the problem, offishur?" - - STOPTIMER Win - - VSpace(2) - - MOVE Win,TextX,TextY:PRINT Win,"That's all." - -RETURN - -SUB VSpace(Number:UINT) - - TextY=TextY+(TextHeight*Number) - - IF TextY+(TextHeight*8)>ScreenSizeY THEN CLR() - -RETURN - -SUB CLR() - - FOR X=0 TO ScreenSizeY - - MOVE Win,0,X:PRINT Win,Erase$ - - TextY=8 - - NEXT X - -RETURN diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-7.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-7.basic deleted file mode 100644 index f0cead4e91..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-7.basic +++ /dev/null @@ -1,111 +0,0 @@ -REM Using the ESC key to exit will not work in console programs under Windows 95/98 or ME. - -DECLARE SingWallLn() -DECLARE Delay1() -DECLARE Delay2() -'To use ESC Key to exit. -DECLARE Quit() -DECLARE TheEnd() - -DEF Bottles:UINT -DEF Number$,Again$:STRING - -OPENCONSOLE - -PRINT"I'm going to sing a song.":PRINT - -Delay1() - -LABEL StartSong - -Bottles=99 - -DO - Quit() - - SingWallLn():Delay1() - - PRINT LTRIM$(STR$(Bottles))+Number$+" of beer.":Delay1() - - IF Bottles>0 THEN PRINT"Take one down, pass it around." ELSE PRINT"Take it down, pass it around.":Delay1() - - Bottles=Bottles-1 - - SingWallLn() - - Delay2() - -PRINT:PRINT - -UNTIL Bottles=0 - -Delay2() - -ClS - -LABEL Question - -INPUT"Sing it again (y or n)?",Again$ - -SELECT Again$ - - CASE("y") - CASE("Y") - - CLS - - GOTO StartSong - - CASE "n" - CASE "N" - - CLS - - PRINT"Fine, be that way.":Delay2() - - TheEnd() - -ENDSELECT - -PRINT"Sorry, I didn't understand.":PRINT - -GOTO Question - -'Keep from running into subroutines. -END - -SUB SingWallLn() - - IF Bottles=1 THEN Number$=" bottle" ELSE Number$=" bottles" - - PRINT LTRIM$(STR$(Bottles))+Number$+" of beer on the wall." - -RETURN - -SUB Delay1() - - FOR X=1 TO 7000:NEXT X - -RETURN - -SUB Delay2() - - FOR X=1 TO 1750000:NEXT X - -RETURN - -SUB Quit() - - 'Close program by pressing the ESC key. - 'Will not work in console under Windows 95/98 or ME. - IF GETKEYSTATE(0x1B) THEN TheEnd() - -RETURN - -SUB TheEnd() - - CLOSECONSOLE - - END - -RETURN diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-8.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-8.basic deleted file mode 100644 index 3cefee652c..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-8.basic +++ /dev/null @@ -1,60 +0,0 @@ -#AppType Console - -Class Wall - bottles - - Sub Initialize(%n = 99) - bottles = n - End Sub - - Method Denom() - if bottles+1 > 1 then - return "one" - elseif bottles+1 = 1 then - return "it" - end if - End Method - - Method StockUp( %n = 99 ) - bottles = n - End Method - - Method TakeOneDown() - bottles = bottles - 1 - end Method - - Method Pluraliser() - if bottles > 1 then - return "s" - else - return "" - end if - end method - - Method Sing() - print bottles, " bottle", Pluraliser(), " of beer on the wall" - print bottles, " bottle", Pluraliser(), " of beer" - TakeOneDown() - print "take ", Denom(), " down and pass it round" - if bottles > 0 then - print bottles, " bottle", Pluraliser(), " of beer on the wall" - print - else - print "no more bottles of beer on the wall" - print - print "no more bottles of beer on the wall" - print "no more bottles of beer on the wall" - print "go to the store and buy some more" - StockUp(99) - print bottles, " bottle", Pluraliser(), " of beer on the wall" - print - end if - return bottles - End Method - -End Class - -Dim BeerSong as new Wall(99) - -while BeerSong.Sing() <> 99 -end while diff --git a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-9.basic b/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-9.basic deleted file mode 100644 index 2e743c2ed3..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC/99-bottles-of-beer-9.basic +++ /dev/null @@ -1,28 +0,0 @@ -E000G (APPLE II) -E000R (APPLE I) -10 REM ------------------------- -11 REM BEERSONG IN APPLE INTEGER -12 REM BASIC BY BARRYM 2011-8-21 -13 REM THANKS : APPLEWIN1.17.2.0 -14 REM THANKS ALSO : POM1 0.7B -15 REM ------------------------- -16 REM PRINTS THE COMPLETE UPPER -17 REM CASE LYRICS ON AN APPLE I -18 REM OR AN 'ORIGINAL' APPLE II -19 REM WITH WOZ'S INTEGER BASIC. -20 REM ------------------------- -21 REM THIS BASIC HAS AN UNUSUAL -22 REM 'THEN', WHICH EXECUTES OR -23 REM SKIPS ONE (AND ONLY ONE!) -24 REM STATEMENT. THIS CONFUSED -25 REM US KIDS REGULARLY WHEN WE -26 REM TRIED TRANSLATING INTEGER -27 REM BASIC GAMES TO APPLE$OFT! -30 REM ------------------------- -40 FOR B=99 TO 98 STEP 0: PRINT : FOR W=0 TO 2: IF W<2 THEN 70 -50 IF B THEN PRINT "TAKE ONE DOWN AND PASS IT AROUND";:B=B-1 -60 IF B+1 THEN 70:B=99: PRINT "GO TO THE STORE AND BUY SOME MORE"; -70 IF W THEN PRINT ",": IF B THEN PRINT B;: IF B=0 THEN PRINT "NO MORE"; -80 PRINT " BOTTLE";: IF B#1 THEN PRINT "S";: PRINT " OF BEER"; -90 IF W#1 THEN PRINT " ON THE WALL";: IF W THEN PRINT ".": NEXT W,B: END -RUN diff --git a/Task/99-Bottles-of-Beer/BASIC256/99-bottles-of-beer.basic256 b/Task/99-Bottles-of-Beer/BASIC256/99-bottles-of-beer.basic256 deleted file mode 100644 index 795e9dcabd..0000000000 --- a/Task/99-Bottles-of-Beer/BASIC256/99-bottles-of-beer.basic256 +++ /dev/null @@ -1,33 +0,0 @@ -#length of querter and eight note in ms -n4 = 1000 * 60 / 80 / 4 -n8 = n4 / 2 - -#frequency of musical notes in hz -e = 330 -ef = 311 -b = 247 -bf = 233 -f = 349 -c = 262 -d = 294 -ds = 311 -a = 220 - -dim notes(1) -dim lengs(1) - -# redim is automatic when using a {} list to assign an array -notes = {ef, ef, ef, bf, bf, bf, ef, ef, ef, ef, f , f , f , c , c , c , f , d , d , d , d , d , d , d , bf, bf, bf, c , c , ef, ef, ef, ef, ef} -lengs = {n8, n8, n8, n8, n8, n8, n8, n8, n8, n4, n8, n8, n8, n8, n8, n8, n4, n4, n8, n8, n8, n8, n8, n4, n8, n8, n8, n8, n8, n8, n8, n8, n8, n4 } - -for x = 99 to 1 step -1 - for t = 0 to notes[?]-1 - if t = 0 then print x + " bottles of beer on the wall" - if t = 11 then print x + " bottles of beer" - if t = 18 then print "Take one down, pass it around" - if t = 25 then print(x-1) + " bottles of beer on the wall" - sound notes[t], lengs[t] - pause .002 - next t - print -next x diff --git a/Task/99-Bottles-of-Beer/BBC-BASIC/99-bottles-of-beer.bbc b/Task/99-Bottles-of-Beer/BBC-BASIC/99-bottles-of-beer.bbc deleted file mode 100644 index f55119ce84..0000000000 --- a/Task/99-Bottles-of-Beer/BBC-BASIC/99-bottles-of-beer.bbc +++ /dev/null @@ -1,32 +0,0 @@ - N_Bottles = 99 - - beer$ = " of beer" - wall$ = " on the wall" - unit$ = "99 bottles" - - WHILE N_Bottles >= 0 - - IF N_Bottles=0 THEN - PRINT '"No more bottles" beer$ wall$ ", " unit$ beer$ "." - PRINT "Go to the store and buy some more, "; - ELSE - PRINT 'unit$ beer$ wall$ ", " unit$ beer$ "." - PRINT "Take one down and pass it around, "; - ENDIF - - N_Bottles -= 1 - - CASE N_Bottles OF - WHEN 0: - unit$ = "no more bottles" - WHEN 1: - unit$ = "1 bottle" - OTHERWISE: - unit$ = STR$((N_Bottles + 100) MOD 100) + " bottles" - ENDCASE - - PRINT unit$ beer$ wall$ "." - - ENDWHILE - - END diff --git a/Task/99-Bottles-of-Beer/Batch-File/99-bottles-of-beer.bat b/Task/99-Bottles-of-Beer/Batch-File/99-bottles-of-beer.bat deleted file mode 100644 index a9ff3467ac..0000000000 --- a/Task/99-Bottles-of-Beer/Batch-File/99-bottles-of-beer.bat +++ /dev/null @@ -1,47 +0,0 @@ -@echo off -setlocal -:main -for /L %%i in (99,-1,1) do ( - call :verse %%i -) -echo no bottles of beer on the wall -echo no bottles of beer -echo go to the store and buy some more -echo 99 bottles of beer on the wall -echo. -set /p q="Keep drinking? " -if %q% == y goto main -if %q% == Y goto main -goto :eof - -:verse -call :plural %1 res -echo %res% of beer on the wall -echo %res% of beer -call :oneit %1 res -echo take %res% down and pass it round -set /a c=%1-1 -call :plural %c% res -echo %res% of beer on the wall -echo. -goto :eof - -:plural -if %1 gtr 1 goto :gtr -if %1 equ 1 goto :equ -set %2=no bottles -goto :eof -:gtr -set %2=%1 bottles -goto :eof -:equ -set %2=1 bottle -goto :eof - -:oneit -if %1 equ 1 ( - set %2=it -) else ( - set %2=one -) -goto :eof diff --git a/Task/99-Bottles-of-Beer/Battlestar/99-bottles-of-beer.battlestar b/Task/99-Bottles-of-Beer/Battlestar/99-bottles-of-beer.battlestar index 031a606634..d2fd41c62a 100644 --- a/Task/99-Bottles-of-Beer/Battlestar/99-bottles-of-beer.battlestar +++ b/Task/99-Bottles-of-Beer/Battlestar/99-bottles-of-beer.battlestar @@ -11,17 +11,18 @@ const store = "Go to the store and buy some more, " const dotnl = ".\n" const nl = "\n" -// Print two digits, use the value in a +// Reserve 1024 bytes in the .bss section +var x 1024 + +// Write two digits, based on the value in a fun printnum b = a - loop - break (a < 10) + a >= 10 a /= 10 // modulo is in the d register after idiv b = d a += 48 // ASCII value for '0' print(chr(a)) - break end a = b a += 48 // ASCII value for '0' @@ -39,45 +40,48 @@ fun main printnum() // N, "bottles of beer on the wall, " - print(bottle) - print(plural) - print(ofbeer) - print(wall) - print(sep) + x = bottle + x += plural + x += ofbeer + x += wall + x += sep + print(x) // Retrieve and print the number stack -> a printnum() - // N, "bottles of beer." - print(bottle) - print(plural) - print(ofbeer) - print(dotnl) - - // "Take one down and pass it around," - print(takedown) + // N, "bottles of beer.\nTake one down and pass it around," + x = bottle + x += plural + x += ofbeer + x += dotnl + x += takedown + print(x) // N-1, "bottles of beer on the wall." stack -> a a-- + // Store N-1, used just a few lines down a -> stack printnum() print(bottle) + // Retrieve N-1 stack -> a + // Write an "s" if the count is not 1 a != 1 print(plural) end - // Write the rest - print(ofbeer) - print(wall) - print(dotnl) - // Blank line - print(nl) + // Write the rest + a blank line + x = ofbeer + x += wall + x += dotnl + x += nl + print(x) // Skip to the top of the loop while the counter is >= 2 continue (c >= 2) @@ -87,52 +91,52 @@ fun main // "1 bottle of beer on the wall," a = 1 printnum() - print(bottle) - print(ofbeer) - print(wall) - print(sep) + x = bottle + x += ofbeer + x += wall + x += sep + print(x) - // "1 bottle of beer." + // "1" a = 1 printnum() - print(bottle) - print(ofbeer) - print(dotnl) - - // "Take one down and pass it around," - print(takedown) + // "bottle of beer. Take one down and pass it around," // "no more bottles of beer on the wall." - print(l_no) - print(more) - print(wall) - print(dotnl) - // Blank line - print(nl) - // "No more bottles of beer on the wall," - print(u_no) - print(more) - print(wall) - print(sep) - // "no more bottles of beer." - print(l_no) - print(more) - print(dotnl) - // "Go to the store and buy some more," - print(store) + x = bottle + x += ofbeer + x += dotnl + x += takedown + x += l_no + x += more + x += wall + x += dotnl + x += nl + x += u_no + x += more + x += wall + x += sep + x += l_no + x += more + x += dotnl + x += store + print(x) - // "99 bottles of beer on the wall." + // "99" a = 99 printnum() - print(bottle) - print(plural) - print(ofbeer) - print(wall) - print(dotnl) + + // "bottles of beer on the wall." + x = bottle + x += plural + x += ofbeer + x += wall + x += dotnl + print(x) end end diff --git a/Task/99-Bottles-of-Beer/Beeswax/99-bottles-of-beer-1.beeswax b/Task/99-Bottles-of-Beer/Beeswax/99-bottles-of-beer-1.beeswax new file mode 100644 index 0000000000..95ba5a0790 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Beeswax/99-bottles-of-beer-1.beeswax @@ -0,0 +1,8 @@ + > NN p +> d#_8~2~(P~3~.~1~>{` bottles of beer on the wall, `{` bottles of beer.`q +d`.llaw eht no reeb fo selttob `{pLM` ,dnuora ti ssap dna nwod eno ekaT`N< +q`.llaw eht no reeb fo elttob ` {< + > NN >{` bottle of beer on the wall, `{` bottle of beer.`N q +pN `.llaw eht no reeb fo selttob erom on ,dnuora ti ssap dna nwod eno ekaT`< +>N`No more bottles of beer on the wall, no more bottles of beer.`N q +;`.llaw eht no reeb fo selttob 99 ,erom emos yub dna erots eht ot oG`< diff --git a/Task/99-Bottles-of-Beer/Beeswax/99-bottles-of-beer-2.beeswax b/Task/99-Bottles-of-Beer/Beeswax/99-bottles-of-beer-2.beeswax new file mode 100644 index 0000000000..6624561815 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Beeswax/99-bottles-of-beer-2.beeswax @@ -0,0 +1,10 @@ +#D@.9~2~@M.7~P9zE `N`p +DMM@.9@.~2~.++~5zE `n`>`o`p +>0f1ff# q `erom `< #h3~1z< #h3~1z< #h3~1z< +d_8~2~(P~3~. ~1~>"b{>X^^^` bottle` ` of beer`@g"pX` on the wall`g"pX `, ` @p # + > d <#XL#^^^^^`s`# # ## # > `.`NN@ X# + b < < < + >~L#^^^^`s`# #h3~1zX #h3~1z<# # # # # + d #h3~1z<# #> `.` g"pXN @"p `Take one down and `p +>^^^^^^^^^; .# b XgNN < bM` ,dnuora ti ssap`< +d^^^^^^^^^^^^^^^^X~3~P(~2~8` ,erom emos yub dna erots eht ot`` oG`< diff --git a/Task/99-Bottles-of-Beer/Befunge/99-bottles-of-beer.bf b/Task/99-Bottles-of-Beer/Befunge/99-bottles-of-beer.bf deleted file mode 100644 index 9366f05bfa..0000000000 --- a/Task/99-Bottles-of-Beer/Befunge/99-bottles-of-beer.bf +++ /dev/null @@ -1,11 +0,0 @@ -:,| - :,| - :,| - >01g1-:01p v -v <.g10" bottles of beer on the wall"+*4310< ->:,| - >134*+0` | - @ diff --git a/Task/99-Bottles-of-Beer/Brainf---/99-bottles-of-beer.bf b/Task/99-Bottles-of-Beer/Brainf---/99-bottles-of-beer.bf deleted file mode 100644 index 74cb56e92c..0000000000 --- a/Task/99-Bottles-of-Beer/Brainf---/99-bottles-of-beer.bf +++ /dev/null @@ -1,44 +0,0 @@ ->+++++++++[<+++++++++++>-]<[>[-]>[-]<<[>+>+<<-]>>[<<+>>-]>>> -[-]<<<+++++++++<[>>>+<<[>+>[-]<<-]>[<+>-]>[<<++++++++++>>>+< --]<<-<-]+++++++++>[<->-]>>+>[<[-]<<+>>>-]>[-]+<<[>+>-<<-]<<< -[>>+>+<<<-]>>>[<<<+>>>-]>[<+>-]<<-[>[-]<[-]]>>+<[>[-]<-]<+++ -+++++[<++++++<++++++>>-]>>>[>+>+<<-]>>[<<+>>-]<[<<<<<.>>>>>- -]<<<<<<.>>[-]>[-]++++[<++++++++>-]<.>++++[<++++++++>-]<++.>+ -++++[<+++++++++>-]<.><+++++..--------.-------.>>[>>+>+<<<-]> ->>[<<<+>>>-]<[<<<<++++++++++++++.>>>>-]<<<<[-]>++++[<+++++++ -+>-]<.>+++++++++[<+++++++++>-]<--.---------.>+++++++[<------ ----->-]<.>++++++[<+++++++++++>-]<.+++..+++++++++++++.>++++++ -++[<---------->-]<--.>+++++++++[<+++++++++>-]<--.-.>++++++++ -[<---------->-]<++.>++++++++[<++++++++++>-]<++++.----------- --.---.>+++++++[<---------->-]<+.>++++++++[<+++++++++++>-]<-. ->++[<----------->-]<.+++++++++++..>+++++++++[<---------->-]< ------.---.>>>[>+>+<<-]>>[<<+>>-]<[<<<<<.>>>>>-]<<<<<<.>>>+++ -+[<++++++>-]<--.>++++[<++++++++>-]<++.>+++++[<+++++++++>-]<. -><+++++..--------.-------.>>[>>+>+<<<-]>>>[<<<+>>>-]<[<<<<++ -++++++++++++.>>>>-]<<<<[-]>++++[<++++++++>-]<.>+++++++++[<++ -+++++++>-]<--.---------.>+++++++[<---------->-]<.>++++++[<++ -+++++++++>-]<.+++..+++++++++++++.>++++++++++[<---------->-]< --.---.>+++++++[<++++++++++>-]<++++.+++++++++++++.++++++++++. -------.>+++++++[<---------->-]<+.>++++++++[<++++++++++>-]<-. --.---------.>+++++++[<---------->-]<+.>+++++++[<++++++++++>- -]<--.+++++++++++.++++++++.---------.>++++++++[<---------->-] -<++.>+++++[<+++++++++++++>-]<.+++++++++++++.----------.>++++ -+++[<---------->-]<++.>++++++++[<++++++++++>-]<.>+++[<-----> --]<.>+++[<++++++>-]<..>+++++++++[<--------->-]<--.>+++++++[< -++++++++++>-]<+++.+++++++++++.>++++++++[<----------->-]<++++ -.>+++++[<+++++++++++++>-]<.>+++[<++++++>-]<-.---.++++++.---- ----.----------.>++++++++[<----------->-]<+.---.[-]<<<->[-]>[ --]<<[>+>+<<-]>>[<<+>>-]>>>[-]<<<+++++++++<[>>>+<<[>+>[-]<<-] ->[<+>-]>[<<++++++++++>>>+<-]<<-<-]+++++++++>[<->-]>>+>[<[-]< -<+>>>-]>[-]+<<[>+>-<<-]<<<[>>+>+<<<-]>>>[<<<+>>>-]<>>[<+>-]< -<-[>[-]<[-]]>>+<[>[-]<-]<++++++++[<++++++<++++++>>-]>>>[>+>+ -<<-]>>[<<+>>-]<[<<<<<.>>>>>-]<<<<<<.>>[-]>[-]++++[<++++++++> --]<.>++++[<++++++++>-]<++.>+++++[<+++++++++>-]<.><+++++..--- ------.-------.>>[>>+>+<<<-]>>>[<<<+>>>-]<[<<<<++++++++++++++ -.>>>>-]<<<<[-]>++++[<++++++++>-]<.>+++++++++[<+++++++++>-]<- --.---------.>+++++++[<---------->-]<.>++++++[<+++++++++++>-] -<.+++..+++++++++++++.>++++++++[<---------->-]<--.>+++++++++[ -<+++++++++>-]<--.-.>++++++++[<---------->-]<++.>++++++++[<++ -++++++++>-]<++++.------------.---.>+++++++[<---------->-]<+. ->++++++++[<+++++++++++>-]<-.>++[<----------->-]<.+++++++++++ -..>+++++++++[<---------->-]<-----.---.+++.---.[-]<<<] diff --git a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-1.cs b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-1.cs deleted file mode 100644 index 5b8c096f4a..0000000000 --- a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-1.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; - -class Program -{ - static void Main(string[] args) - { - for (int i = 99; i > -1; i--) - { - if (i == 0) - { - Console.WriteLine("No more bottles of beer on the wall, no more bottles of beer."); - Console.WriteLine("Go to the store and buy some more, 99 bottles of beer on the wall."); - break; - } - if (i == 1) - { - Console.WriteLine("1 bottle of beer on the wall, 1 bottle of beer."); - Console.WriteLine("Take one down and pass it around, no more bottles of beer on the wall."); - Console.WriteLine(); - } - else - { - Console.WriteLine("{0} bottles of beer on the wall, {0} bottles of beer.", i); - Console.WriteLine("Take one down and pass it around, {0} bottles of beer on the wall.", i - 1); - Console.WriteLine(); - } - } - } -} diff --git a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-2.cs b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-2.cs deleted file mode 100644 index 0c8b560b4e..0000000000 --- a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-2.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Linq; - -class Program -{ - static void Main() - { - var query = from total in Enumerable.Range(0,100).Reverse() - select (total > 0) - ? string.Format("{0} bottles of beer on the wall\n{0} bottles of beer\nTake one down, pass it around", total) - : string.Format("{0} bottles left", total); - - foreach (var item in query) - { - Console.WriteLine(item); - } - } -} diff --git a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-3.cs b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-3.cs deleted file mode 100644 index 47b6a7bc2d..0000000000 --- a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-3.cs +++ /dev/null @@ -1,39 +0,0 @@ - class Program - { - const string Vessel = "bottle"; - const string Beverage = "beer"; - const string Location = "on the wall"; - - private static string DefaultAction(ref int bottles) - { - bottles--; - return "take one down, pass it around,"; - } - - private static string FallbackAction(ref int bottles) - { - bottles += 99; - return "go to the store, buy some more,"; - } - - private static string Act(ref int bottles) - { - return bottles > 0 ? DefaultAction(ref bottles) : FallbackAction(ref bottles); - } - - static void Main() - { - Func plural = b => b == 1 ? "" : "s"; - Func describeCount = b => b == 0 ? "no more" : b.ToString(); - Func describeBottles = b => string.Format("{0} {1}{2} of {3}", describeCount(b), Vessel, plural(b), Beverage); - Action write = s => Console.WriteLine(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s)); - int bottles = 99; - while (true) - { - write(string.Format("{0} {1}, {0},", describeBottles(bottles), Location)); - write(Act(ref bottles)); - write(string.Format("{0} {1}.", describeBottles(bottles), Location)); - write(string.Empty); - } - } - } diff --git a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-4.cs b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-4.cs deleted file mode 100644 index df76d8ce8e..0000000000 --- a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-4.cs +++ /dev/null @@ -1,28 +0,0 @@ -class songs -{ - static void Main(string[] args) - { - beer(5); - } - - private static void beer(int bottles) - { - for (int i = bottles; i > 0; i--) - { - if (i > 1) - { - Console.Write("{0}\n{1}\n{2}\n{3}\n\n", - i + " bottles of beer on the wall", - i + " bottles of beer", - "Take one down, pass it around", - (i - 1) + " bottles of beer on the wall"); - } - else - Console.Write("{0}\n{1}\n{2}\n{3}\n\n", - i + " bottle of beer on the wall", - i + " bottle of beer", - "Take one down, pass it around", - (i - 1) + " bottles of beer on the wall...."); - } - } -} diff --git a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-5.cs b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-5.cs deleted file mode 100644 index 87df3fd53e..0000000000 --- a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-5.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Linq; - -class Program -{ - static void Main() - { - BeerBottles().Take(99).ToList().ForEach(Console.WriteLine); - } - - static IEnumerable BeerBottles() - { - int i = 100; - String f = "{0}, {1}. Take one down, pass it around, {2}"; - Func booze = (c , b) => - String.Format("{0} bottle{1} of beer{2}", c > 0 ? c.ToString() : "no more", (c == 1 ? "" : "s"), b ? " on the wall" : ""); - - while (--i >= 1) - yield return String.Format(f, booze(i, true), booze(i, false), booze(i - 1, true)); - } -} diff --git a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-6.cs b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-6.cs deleted file mode 100644 index f087b131bd..0000000000 --- a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-6.cs +++ /dev/null @@ -1,131 +0,0 @@ -string[] bottles = { "80 Shilling", - "Abita Amber", - "Adams Broadside Ale", - "Altenmünster Premium", - "August Schell's SnowStorm", - "Bah Humbug! Christmas Ale", - "Beck's Oktoberfest", - "Belhaven Wee Heavy", - "Bison Chocolate Stout", - "Blue Star Wheat Beer", - "Bridgeport Black Strap Stout", - "Brother Thelonius Belgian-Style Abbey Ale", - "Capital Blonde Doppelbock", - "Carta Blanca", - "Celis Raspberry Wheat", - "Christian Moerlein Select Lager", - "Corona", - "Czechvar", - "Delirium Tremens", - "Diamond Bear Southern Blonde", - "Don De Dieu", - "Eastside Dark", - "Eliot Ness", - "Flying Dog K-9 Cruiser Altitude Ale", - "Fuller's London Porter", - "Gaffel Kölsch", - "Golden Horseshoe", - "Guinness Pub Draught", - "Hacker-Pschorr Weisse", - "Hereford & Hops Black Spring Double Stout", - "Highland Oatmeal Porter", - "Ipswich Ale", - "Iron City", - "Jack Daniel's Amber Lager", - "Jamaica Sunset India Pale Ale", - "Killian's Red", - "König Ludwig Weiss", - "Kronenbourg 1664", - "Lagunitas Hairy Eyball Ale", - "Left Hand Juju Ginger", - "Locktender Lager", - "Magic Hat Blind Faith", - "Missing Elf Double Bock", - "Muskoka Cream Ale ", - "New Glarus Cherry Stout", - "Nostradamus Bruin", - "Old Devil", - "Ommegang Three Philosophers", - "Paulaner Hefe-Weizen Dunkel", - "Perla Chmielowa Pils", - "Pete's Wicked Springfest", - "Point White Biere", - "Prostel Alkoholfrei", - "Quilmes", - "Rahr's Red", - "Rebel Garnet", - "Rickard's Red", - "Rio Grande Elfego Bock", - "Rogue Brutal Bitter", - "Roswell Alien Amber Ale", - "Russian River Pliny The Elder", - "Samuel Adams Blackberry Witbier", - "Samuel Smith's Taddy Porter", - "Schlafly Pilsner", - "Sea Dog Wild Blueberry Wheat Ale", - "Sharp's", - "Shiner 99", - "Sierra Dorada", - "Skullsplitter Orkney Ale", - "Snake Chaser Irish Style Stout", - "St. Arnold Bock", - "St. Peter's Cream Stout", - "Stag", - "Stella Artois", - "Stone Russian Imperial Stout", - "Sweetwater Happy Ending Imperial Stout", - "Taiwan Gold Medal", - "Terrapin Big Hoppy Monster", - "Thomas Hooker American Pale Ale", - "Tie Die Red Ale", - "Toohey's Premium", - "Tsingtao", - "Ugly Pug Black Lager", - "Unibroue Qatre-Centieme", - "Victoria Bitter", - "Voll-Damm Doble Malta", - "Wailing Wench Ale", - "Warsteiner Dunkel", - "Wellhead Crude Oil Stout", - "Weyerbacher Blithering Idiot Barley-Wine Style Ale", - "Wild Boar Amber", - "Würzburger Oktoberfest", - "Xingu Black Beer", - "Yanjing", - "Younger's Tartan Special", - "Yuengling Black & Tan", - "Zagorka Special", - "Zig Zag River Lager", - "Zywiec" }; - - -int bottlesLeft = 99; -const int FIRST_LINE_SINGULAR = 98; -const int FINAL_LINE_SINGULAR = 97; -string firstLine = ""; -string finalLine = ""; - - -for (int i = 0; i < 99; i++) -{ - firstLine = bottlesLeft.ToString() + " bottle"; - if (i != FIRST_LINE_SINGULAR) - firstLine += "s"; - firstLine += " of beer on the wall, " + bottlesLeft.ToString() + " bottle"; - if (i != FIRST_LINE_SINGULAR) - firstLine += "s"; - firstLine += " of beer"; - - Console.WriteLine(firstLine); - Console.WriteLine("Take the " + bottles[i] + " down, pass it around,"); - bottlesLeft--; - - finalLine = bottlesLeft.ToString() + " bottle"; - if (i != FINAL_LINE_SINGULAR) - finalLine += "s"; - finalLine += " of beer on the wall!"; - - Console.WriteLine(finalLine); - Console.WriteLine(); - Console.ReadLine(); -} diff --git a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-7.cs b/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-7.cs deleted file mode 100644 index 151cb4c0a5..0000000000 --- a/Task/99-Bottles-of-Beer/C-sharp/99-bottles-of-beer-7.cs +++ /dev/null @@ -1,12 +0,0 @@ - public static void BottlesSong(int numberOfBottles) - { - if (numberOfBottles > 0) - { - Console.WriteLine("{0} bottles of beer on the wall", numberOfBottles); - Console.WriteLine("{0} bottles of beer ", numberOfBottles); - Console.WriteLine("Take one down, pass it around"); - Console.WriteLine("{0} bottles of beer ", numberOfBottles - 1); - Console.WriteLine(); - BottlesSong(--numberOfBottles); - } - } diff --git a/Task/99-Bottles-of-Beer/Chef/99-bottles-of-beer.chef b/Task/99-Bottles-of-Beer/Chef/99-bottles-of-beer.chef deleted file mode 100644 index 6e4597b805..0000000000 --- a/Task/99-Bottles-of-Beer/Chef/99-bottles-of-beer.chef +++ /dev/null @@ -1,225 +0,0 @@ -99 Bottles Of Beer. - -Ingredients. -99 bottles - -Method. -Loop the bottles. - Put bottles into 1st mixing bowl. - Serve with bottles of beer on the wall. - Clean 1st mixing bowl. - Put bottles into 1st mixing bowl. - Serve with bottles of beer. - Clean 1st mixing bowl. - Serve with Take one down and pass it around. - Clean 1st mixing bowl. -Loop the bottles until looped. -Serve with No more bottles of beer. -Clean 1st mixing bowl. -Pour contents of the 3rd mixing bowl into the 1st baking dish. - -Serves 1. - -bottles of beer on the wall. - -Prints out "n" bottles of beer on the wall. - -Ingredients. -108 g lime -97 cups asparagus -119 pinches watercress -32 tablespoons pickles -101 pinches eggplant -104 g huckleberry -116 teaspoons turnip -110 tablespoons nannyberry -111 tablespoons onion -114 tablespoons raspberry -98 g broccoli -102 g feijoa -115 teaspoons squach -10 ml new line - -Method. -Put new line into 1st mixing bowl. -Put lime into 2nd mixing bowl. -Put lime into 2nd mixing bowl. -Put asparagus into 2nd mixing bowl. -Put watercress into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put eggplant into 2nd mixing bowl. -Put huckleberry into 2nd mixing bowl. -Put turnip into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put nannyberry into 2nd mixing bowl. -Put onion into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put raspberry into 2nd mixing bowl. -Put eggplant into 2nd mixing bowl. -Put eggplant into 2nd mixing bowl. -Put broccoli into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put feijoa into 2nd mixing bowl. -Put onion into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put squach into 2nd mixing bowl. -Put eggplant into 2nd mixing bowl. -Put lime into 2nd mixing bowl. -Put turnip into 2nd mixing bowl. -Put turnip into 2nd mixing bowl. -Put onion into 2nd mixing bowl. -Put broccoli into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Liquify contents of the 2nd mixing bowl. -Pour contents of the 2nd mixing bowl into the baking dish. -Pour contents of the mixing bowl into the baking dish. -Refrigerate for 1 hour. - -bottles of beer. - -Prints out "n" bottles of beer. - -Ingredients. -114 tablespoons raspberry -101 pinches eggplant -98 teaspoons broccoli -32 pinches pickles -102 tablespoons feijoa -111 teaspoons onion -115 cups squach -108 cups lime -116 teaspoons turnip -10 ml new line - -Method. -Put new line into 1st mixing bowl. -Put raspberry into 2nd mixing bowl. -Put eggplant into 2nd mixing bowl. -Put eggplant into 2nd mixing bowl. -Put broccoli into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put feijoa into 2nd mixing bowl. -Put onion into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put squach into 2nd mixing bowl. -Put eggplant into 2nd mixing bowl. -Put lime into 2nd mixing bowl. -Put turnip into 2nd mixing bowl. -Put turnip into 2nd mixing bowl. -Put onion into 2nd mixing bowl. -Put broccoli into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Liquify contents of the 2nd mixing bowl. -Pour contents of the 2nd mixing bowl into the baking dish. -Pour contents of the mixing bowl into the baking dish. -Refrigerate for 1 hour. - -Take one down and pass it around. - -Prints out "Take one down and pass it around". - -Ingredients. -100 cups dandelion -110 g nannyberry -117 pinches cucumber -111 pinches onion -114 pinches raspberry -97 g asparagus -32 tablespoons pickles -116 pinches turnip -105 g chestnut -115 g squach -112 g pumpkin -119 cups watercress -101 g eggplant -107 g kale -84 cups tomatoe -10 ml new line - -Method. -Put new line into 3rd mixing bowl. -Put dandelion into 2nd mixing bowl. -Put nannyberry into 2nd mixing bowl. -Put cucumber into 2nd mixing bowl. -Put onion into 2nd mixing bowl. -Put raspberry into 2nd mixing bowl. -Put asparagus into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put turnip into 2nd mixing bowl. -Put chestnut into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put squach into 2nd mixing bowl. -Put squach into 2nd mixing bowl. -Put asparagus into 2nd mixing bowl. -Put pumpkin into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put dandelion into 2nd mixing bowl. -Put nannyberry into 2nd mixing bowl. -Put asparagus into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put nannyberry into 2nd mixing bowl. -Put watercress into 2nd mixing bowl. -Put onion into 2nd mixing bowl. -Put dandelion into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put eggplant into 2nd mixing bowl. -Put nannyberry into 2nd mixing bowl. -Put onion into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put eggplant into 2nd mixing bowl. -Put kale into 2nd mixing bowl. -Put asparagus into 2nd mixing bowl. -Put tomatoe into 2nd mixing bowl. -Liquify contents of the 2nd mixing bowl. -Pour contents of the 2nd mixing bowl into the baking dish. -Pour contents of the 3rd mixing bowl into the baking dish. -Refrigerate for 1 hour. - -No more bottles of beer. - -Prints out "No more bottles of beer". - -Ingredients. -114 pinches raspberry -101 teaspoons eggplant -98 cups broccoli -32 tablespoons pickles -102 pinches feijoa -111 cups onion -115 tablespoons squach -108 tablespoons lime -116 pinches turnip -109 cups mushrooms -78 g nectarine -10 ml new line - -Method. -Put new line into 3rd mixing bowl. -Put new line into 2nd mixing bowl. -Put raspberry into 2nd mixing bowl. -Put eggplant into 2nd mixing bowl. -Put eggplant into 2nd mixing bowl. -Put broccoli into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put feijoa into 2nd mixing bowl. -Put onion into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put squach into 2nd mixing bowl. -Put eggplant into 2nd mixing bowl. -Put lime into 2nd mixing bowl. -Put turnip into 2nd mixing bowl. -Put turnip into 2nd mixing bowl. -Put onion into 2nd mixing bowl. -Put broccoli into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put eggplant into 2nd mixing bowl. -Put raspberry into 2nd mixing bowl. -Put onion into 2nd mixing bowl. -Put mushrooms into 2nd mixing bowl. -Put pickles into 2nd mixing bowl. -Put onion into 2nd mixing bowl. -Put nectarine into 2nd mixing bowl. -Liquify contents of the 2nd mixing bowl. -Pour contents of the 2nd mixing bowl into the baking dish. -Pour contents of the 3rd mixing bowl into the baking dish. -Refrigerate for 1 hour. diff --git a/Task/99-Bottles-of-Beer/Comefrom0x10/99-bottles-of-beer.comefrom0x10 b/Task/99-Bottles-of-Beer/Comefrom0x10/99-bottles-of-beer.comefrom0x10 new file mode 100644 index 0000000000..e4a43cbf8d --- /dev/null +++ b/Task/99-Bottles-of-Beer/Comefrom0x10/99-bottles-of-beer.comefrom0x10 @@ -0,0 +1,18 @@ +bottles = ' bottles ' +remaining = 99 +one_less_bottle = remaining +depluralize + comefrom drinking if one_less_bottle is 1 + bottles = ' bottle ' + +drinking + comefrom if remaining is one_less_bottle + remaining bottles 'of beer on the wall' + remaining bottles 'of beer' + 'Take one down, pass it around' + one_less_bottle = remaining - 1 + one_less_bottle bottles 'of beer on the wall`n' + remaining = remaining - 1 + + comefrom if one_less_bottle is 0 + 'No more bottles of beer on the wall' diff --git a/Task/99-Bottles-of-Beer/Common-Lisp/99-bottles-of-beer-1.lisp b/Task/99-Bottles-of-Beer/Common-Lisp/99-bottles-of-beer-1.lisp deleted file mode 100644 index eaed32bce3..0000000000 --- a/Task/99-Bottles-of-Beer/Common-Lisp/99-bottles-of-beer-1.lisp +++ /dev/null @@ -1,6 +0,0 @@ -(defun bottles (x) - (loop for bottles from x downto 1 - do (format t "~a bottle~:p of beer on the wall -~:*~a bottle~:p of beer -Take one down, pass it around -~a bottle~:p of beer on the wall~2%" bottles (1- bottles)))) diff --git a/Task/99-Bottles-of-Beer/Common-Lisp/99-bottles-of-beer-2.lisp b/Task/99-Bottles-of-Beer/Common-Lisp/99-bottles-of-beer-2.lisp deleted file mode 100644 index f70ed72c5d..0000000000 --- a/Task/99-Bottles-of-Beer/Common-Lisp/99-bottles-of-beer-2.lisp +++ /dev/null @@ -1 +0,0 @@ -(bottles 99) diff --git a/Task/99-Bottles-of-Beer/Common-Lisp/99-bottles-of-beer-3.lisp b/Task/99-Bottles-of-Beer/Common-Lisp/99-bottles-of-beer-3.lisp deleted file mode 100644 index 804f496105..0000000000 --- a/Task/99-Bottles-of-Beer/Common-Lisp/99-bottles-of-beer-3.lisp +++ /dev/null @@ -1,2 +0,0 @@ -(format t "~{~[~^~]~:*~D bottle~:P of beer on the wall~%~:*~D bottle~:P of beer~%Take one down, pass it around~%~D bottle~:P~:* of beer on the wall~2%~}" - (loop :for n :from 99 :downto 0 :collect n)) diff --git a/Task/99-Bottles-of-Beer/Component-Pascal/99-bottles-of-beer.component b/Task/99-Bottles-of-Beer/Component-Pascal/99-bottles-of-beer.component deleted file mode 100644 index 61f6910bc2..0000000000 --- a/Task/99-Bottles-of-Beer/Component-Pascal/99-bottles-of-beer.component +++ /dev/null @@ -1,22 +0,0 @@ -MODULE BottlesOfBeer; -IMPORT StdLog; -CONST bottles = 99; - -PROCEDURE Part(i: INTEGER); -BEGIN - StdLog.Int(i);StdLog.String(" bottles of beer on the wall");StdLog.Ln; - StdLog.Int(i);StdLog.String(" bottles of beer");StdLog.Ln; - StdLog.String("Take one down, pass it around");StdLog.Ln; - StdLog.Int(i - 1);StdLog.String(" bottles of beer on the wall.");StdLog.Ln; - StdLog.Ln -END Part; - -PROCEDURE Sing*; -VAR - i: INTEGER; -BEGIN - FOR i := bottles TO 1 BY -1 DO - Part(i) - END -END Sing; -END BottlesOfBeer. diff --git a/Task/99-Bottles-of-Beer/Delphi/99-bottles-of-beer.delphi b/Task/99-Bottles-of-Beer/Delphi/99-bottles-of-beer.delphi deleted file mode 100644 index 011054cf5e..0000000000 --- a/Task/99-Bottles-of-Beer/Delphi/99-bottles-of-beer.delphi +++ /dev/null @@ -1,27 +0,0 @@ -program Hundred_Bottles; - -{$APPTYPE CONSOLE} - -uses SysUtils; - -const C_1_Down = 'Take one down, pass it around' ; - -Var i : Integer ; - -// As requested, some fun : examples of Delphi basic techniques. Just to make it a bit complex - -procedure WriteABottle( BottleNr : Integer ) ; -begin - Writeln(BottleNr, ' bottles of beer on the wall' ) ; -end ; - -begin - for i := 99 Downto 1 do begin - WriteABottle(i); - Writeln( Format('%d bottles of beer' , [i] ) ) ; - Writeln( C_1_Down ) ; - WriteABottle(i-1); - Writeln ; -End ; - -end. 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 84959b3420..301a6bee0e 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 @@ -1,33 +1,32 @@ -#import system. -#import system'dynamic. -#import system'routines. -#import extensions. -#import extensions'routines. -#import extensions'text. +import system'dynamic. +import system'routines. +import extensions. +import extensions'routines. +import extensions'text. -#class(extension)bottleOp +extension bottleOp { - #method bottleDescription - = self literal + (self != 1) iif:" bottles":" bottle". + bottleDescription + = self literal + (self != 1) iif(" bottles"," bottle"). - #method bottleEnumerator = Variable new:self eval &with:target + bottleEnumerator = Variable new:self; doWith(:target) [ - Enumerator + ^ Enumerator:: { next = target > 0. - get = StringWriter new - writeLine:(target bottleDescription):" of beer on the wall" - writeLine:(target bottleDescription):" of beer" - writeLine:"Take one down, pass it around" - writeLine:((target -= 1) bottleDescription):" of beer on the wall". + get = StringWriter new; + printLine(target bottleDescription," of beer on the wall"); + printLine(target bottleDescription," of beer"); + printLine("Take one down, pass it around"); + printLine((target reduce:1) bottleDescription," of beer on the wall"). } ]. } -#symbol program = +program = [ - #var bottles := 99. + var bottles := 99. - bottles bottleEnumerator run &each:printingLn. + bottles bottleEnumerator; forEach:printingLn. ]. diff --git a/Task/99-Bottles-of-Beer/Euphoria/99-bottles-of-beer.euphoria b/Task/99-Bottles-of-Beer/Euphoria/99-bottles-of-beer.euphoria index 2d227e0434..1a39847370 100644 --- a/Task/99-Bottles-of-Beer/Euphoria/99-bottles-of-beer.euphoria +++ b/Task/99-Bottles-of-Beer/Euphoria/99-bottles-of-beer.euphoria @@ -1,50 +1,28 @@ -include std/console.e -include std/search.e +constant + bottles = "bottles", + bottle = "bottle" -function one_or_it( atom n ) - if n = 1 then - return "it" - else - return "one" - end if -end function +procedure beers (integer how_much) + sequence word1 = bottles, word2 = bottles + switch how_much do + case 2 then + word2 = bottle + case 1 then + word1 = bottle + word2 = bottle + end switch -function numberable( atom n ) - if n = 0 then - return "no" - else - return sprintf( "%d", n ) - end if -end function + printf (1, + "%d %s of beer on the wall \n" & + "%d %s of beer \n" & + "Take one down, and pass it around \n" & + "%d %s of beer on the wall \n\n", + { how_much, word1, + how_much, word1, + how_much-1, word2 } + ) +end procedure -function plural( atom n ) - if n != 1 then - return "s" - else - return "" - end if -end function - -atom stillDrinking = 1 - -sequence yn -sequence plurality -sequence numerality - -while stillDrinking do - for bottle = 99 to 1 by -1 do - plurality = plural( bottle ) - numerality = numberable( bottle ) - printf( 1, "%s bottle%s of beer on the wall\n%s bottle%s of beer\n", - { numerality, plurality, numerality, plurality } ) - printf( 1, "Take %s down and pass it round\n", { one_or_it( bottle ) } ) - printf( 1, "%s bottle%s of beer on the wall\n\n", - { numberable( bottle - 1 ), plural( bottle - 1 ) } ) - end for - puts( 1, "No more bottles of beer on the wall\nNo more bottles of beer\n" ) - puts( 1, "Go to the store and buy some more\n99 bottles of beer on the wall\n" ) - puts( 1, "\nKeep drinking? " ) - yn = gets(0) - stillDrinking = find_any( "yY", yn ) - puts( 1, "\n" ) -end while +for a = 99 to 1 by -1 do + beers (a) +end for diff --git a/Task/99-Bottles-of-Beer/FALSE/99-bottles-of-beer.false b/Task/99-Bottles-of-Beer/FALSE/99-bottles-of-beer.false deleted file mode 100644 index 083dac697c..0000000000 --- a/Task/99-Bottles-of-Beer/FALSE/99-bottles-of-beer.false +++ /dev/null @@ -1,7 +0,0 @@ -[$." bottle"$1-["s"]?" of beer"]b: -99 -[$][b;!" on the wall -"b;!" -Take one down and pass it around -"1-b;!" on the wall -"]#% diff --git a/Task/99-Bottles-of-Beer/FBSL/99-bottles-of-beer.fbsl b/Task/99-Bottles-of-Beer/FBSL/99-bottles-of-beer.fbsl deleted file mode 100644 index 3cefee652c..0000000000 --- a/Task/99-Bottles-of-Beer/FBSL/99-bottles-of-beer.fbsl +++ /dev/null @@ -1,60 +0,0 @@ -#AppType Console - -Class Wall - bottles - - Sub Initialize(%n = 99) - bottles = n - End Sub - - Method Denom() - if bottles+1 > 1 then - return "one" - elseif bottles+1 = 1 then - return "it" - end if - End Method - - Method StockUp( %n = 99 ) - bottles = n - End Method - - Method TakeOneDown() - bottles = bottles - 1 - end Method - - Method Pluraliser() - if bottles > 1 then - return "s" - else - return "" - end if - end method - - Method Sing() - print bottles, " bottle", Pluraliser(), " of beer on the wall" - print bottles, " bottle", Pluraliser(), " of beer" - TakeOneDown() - print "take ", Denom(), " down and pass it round" - if bottles > 0 then - print bottles, " bottle", Pluraliser(), " of beer on the wall" - print - else - print "no more bottles of beer on the wall" - print - print "no more bottles of beer on the wall" - print "no more bottles of beer on the wall" - print "go to the store and buy some more" - StockUp(99) - print bottles, " bottle", Pluraliser(), " of beer on the wall" - print - end if - return bottles - End Method - -End Class - -Dim BeerSong as new Wall(99) - -while BeerSong.Sing() <> 99 -end while diff --git a/Task/99-Bottles-of-Beer/Ferite/99-bottles-of-beer.ferite b/Task/99-Bottles-of-Beer/Ferite/99-bottles-of-beer.ferite new file mode 100644 index 0000000000..8747d648a2 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Ferite/99-bottles-of-beer.ferite @@ -0,0 +1,20 @@ +uses "console"; + +number bottles = 99; +boolean looping = true; +object counter = closure { + if (--bottles > 0) { + return true; + } else { + return false; + } +}; + +while (looping) { + Console.println("${bottles} bottles of beer on the wall,"); + Console.println("${bottles} bottles of beer,"); + Console.println("Take one down, pass it around,"); + + looping = counter.invoke(); + + Console.println("${bottles} bottles of beer on the wall."); diff --git a/Task/99-Bottles-of-Beer/Gnuplot/99-bottles-of-beer.gnuplot b/Task/99-Bottles-of-Beer/Gnuplot/99-bottles-of-beer.gnuplot new file mode 100644 index 0000000000..5f0c661bcb --- /dev/null +++ b/Task/99-Bottles-of-Beer/Gnuplot/99-bottles-of-beer.gnuplot @@ -0,0 +1,8 @@ +if (!exists("bottles")) bottles = 99 +print sprintf("%i bottles of beer on the wall", bottles) +print sprintf("%i bottles of beer", bottles) +print "Take one down, pass it around" +bottles = bottles - 1 +print sprintf("%i bottles of beer on the wall", bottles) +print "" +if (bottles > 0) reread diff --git a/Task/99-Bottles-of-Beer/HQ9+/99-bottles-of-beer.hq9p b/Task/99-Bottles-of-Beer/HQ9+/99-bottles-of-beer.hq9p deleted file mode 100644 index ec635144f6..0000000000 --- a/Task/99-Bottles-of-Beer/HQ9+/99-bottles-of-beer.hq9p +++ /dev/null @@ -1 +0,0 @@ -9 diff --git a/Task/99-Bottles-of-Beer/Halon/99-bottles-of-beer.halon b/Task/99-Bottles-of-Beer/Halon/99-bottles-of-beer.halon new file mode 100644 index 0000000000..a8caa7aa35 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Halon/99-bottles-of-beer.halon @@ -0,0 +1,14 @@ +$plural = "s"; +$x = 99; +while ($x > 0) { + echo "$x bottle$plural of beer on the wall"; + echo "$x bottle$plural of beer"; + echo "Take one down, pass it around"; + $x -= 1; + if ($x == 1) + $plural = ""; + if ($x > 0) + echo "$x bottle$plural of beer on the wall\n"; + else + echo "No more bottles of beer on the wall!"; +} diff --git a/Task/99-Bottles-of-Beer/Haskell/99-bottles-of-beer-4.hs b/Task/99-Bottles-of-Beer/Haskell/99-bottles-of-beer-4.hs new file mode 100644 index 0000000000..5e59f70915 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Haskell/99-bottles-of-beer-4.hs @@ -0,0 +1,27 @@ +incant :: Int -> String +incant n = + let inventory = unwords . (: [locate]) . asset + in case n of + 0 -> solve + _ -> unlines [inventory n, asset n, distribute, inventory (n - 1)] + +asset :: Int -> String +asset n = + unwords + [ show n + , (reverse . concat) $ + (case n of + 1 -> [] + _ -> ['s']) : + [drink] + ] + +[locate, distribute, solve, drink] = + [ "on the wall" + , "Take one down, pass it around" + , "Better go to the store to buy some more" + , "elttob" + ] + +main :: IO () +main = putStrLn $ unlines (incant <$> [99,98 .. 0]) diff --git a/Task/99-Bottles-of-Beer/Integer-BASIC/99-bottles-of-beer.integer b/Task/99-Bottles-of-Beer/Integer-BASIC/99-bottles-of-beer.integer deleted file mode 100644 index 2e743c2ed3..0000000000 --- a/Task/99-Bottles-of-Beer/Integer-BASIC/99-bottles-of-beer.integer +++ /dev/null @@ -1,28 +0,0 @@ -E000G (APPLE II) -E000R (APPLE I) -10 REM ------------------------- -11 REM BEERSONG IN APPLE INTEGER -12 REM BASIC BY BARRYM 2011-8-21 -13 REM THANKS : APPLEWIN1.17.2.0 -14 REM THANKS ALSO : POM1 0.7B -15 REM ------------------------- -16 REM PRINTS THE COMPLETE UPPER -17 REM CASE LYRICS ON AN APPLE I -18 REM OR AN 'ORIGINAL' APPLE II -19 REM WITH WOZ'S INTEGER BASIC. -20 REM ------------------------- -21 REM THIS BASIC HAS AN UNUSUAL -22 REM 'THEN', WHICH EXECUTES OR -23 REM SKIPS ONE (AND ONLY ONE!) -24 REM STATEMENT. THIS CONFUSED -25 REM US KIDS REGULARLY WHEN WE -26 REM TRIED TRANSLATING INTEGER -27 REM BASIC GAMES TO APPLE$OFT! -30 REM ------------------------- -40 FOR B=99 TO 98 STEP 0: PRINT : FOR W=0 TO 2: IF W<2 THEN 70 -50 IF B THEN PRINT "TAKE ONE DOWN AND PASS IT AROUND";:B=B-1 -60 IF B+1 THEN 70:B=99: PRINT "GO TO THE STORE AND BUY SOME MORE"; -70 IF W THEN PRINT ",": IF B THEN PRINT B;: IF B=0 THEN PRINT "NO MORE"; -80 PRINT " BOTTLE";: IF B#1 THEN PRINT "S";: PRINT " OF BEER"; -90 IF W#1 THEN PRINT " ON THE WALL";: IF W THEN PRINT ".": NEXT W,B: END -RUN diff --git a/Task/99-Bottles-of-Beer/J/99-bottles-of-beer-1.j b/Task/99-Bottles-of-Beer/J/99-bottles-of-beer-1.j deleted file mode 100644 index 09f09cd83e..0000000000 --- a/Task/99-Bottles-of-Beer/J/99-bottles-of-beer-1.j +++ /dev/null @@ -1,4 +0,0 @@ -bob =: ": , ' bottle' , (1 = ]) }. 's of beer'"_ -bobw=: bob , ' on the wall'"_ -beer=: bobw , ', ' , bob , '; take one down and pass it around, ' , bobw@<: -beer"0 >:i.-99 diff --git a/Task/99-Bottles-of-Beer/J/99-bottles-of-beer-2.j b/Task/99-Bottles-of-Beer/J/99-bottles-of-beer-2.j deleted file mode 100644 index 328f6c0640..0000000000 --- a/Task/99-Bottles-of-Beer/J/99-bottles-of-beer-2.j +++ /dev/null @@ -1,6 +0,0 @@ -99 bottles of beer on the wall, 99 bottles of beer; take one down and pass it around, 98 bottles of beer on the wall -98 bottles of beer on the wall, 98 bottles of beer; take one down and pass it around, 97 bottles of beer on the wall -... -3 bottles of beer on the wall, 3 bottles of beer; take one down and pass it around, 2 bottles of beer on the wall -2 bottles of beer on the wall, 2 bottles of beer; take one down and pass it around, 1 bottle of beer on the wall -1 bottle of beer on the wall, 1 bottle of beer; take one down and pass it around, 0 bottles of beer on the wall diff --git a/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-1.java b/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-1.java index 805e0b3e6c..85cb41f0e4 100644 --- a/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-1.java +++ b/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-1.java @@ -1,20 +1,19 @@ import java.text.MessageFormat; -public class Beer -{ - static String bottles(final int n) - { - return MessageFormat.format("{0,choice,0#No more bottles|1#One bottle|2#{0} bottles} of beer", n); - } - public static void main(final String[] args) - { - String byob = bottles(99); - for (int x = 99; x > 0;) - { - System.out.println(byob + " on the wall"); - System.out.println(byob); - System.out.println("Take one down, pass it around"); - byob = bottles(--x); - System.out.println(byob + " on the wall\n"); - } - } + +public class Beer { + static String bottles(int n) { + return MessageFormat.format("{0,choice,0#No more bottles|1#One bottle|2#{0} bottles} of beer", n); + } + + public static void main(String[] args) { + String bottles = bottles(99); + for (int n = 99; n > 0; ) { + System.out.println(bottles + " on the wall"); + System.out.println(bottles); + System.out.println("Take one down, pass it around"); + bottles = bottles(--n); + System.out.println(bottles + " on the wall"); + System.out.println(); + } + } } diff --git a/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-2.java b/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-2.java index b89dcc149f..6ea053e672 100644 --- a/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-2.java +++ b/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-2.java @@ -1,16 +1,14 @@ -public class Beer -{ - public static void main(final String[] args) - { - int beer = 99; - StringBuilder sb = new StringBuilder(); - String data[] = new String[] { " bottles of beer on the wall\n", - " bottles of beer.\nTake one down, pass it around,\n", - "Better go to the store and buy some more." }; +public class Beer { + public static void main(String[] args) { + int bottles = 99; + StringBuilder sb = new StringBuilder(); + String verse1 = " bottles of beer on the wall\n"; + String verse2 = " bottles of beer.\nTake one down, pass it around,\n"; + String verse3 = "Better go to the store and buy some more."; - while (beer > 0) - sb.append(beer).append(data[0]).append(beer).append(data[1]).append(--beer).append(data[0]).append("\n"); + while (bottles > 0) + sb.append(bottles).append(verse1).append(bottles).append(verse2).append(--bottles).append(verse1).append("\n"); - System.out.println(sb.append(data[2]).toString()); - } + System.out.println(sb.append(verse3)); + } } diff --git a/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-3.java b/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-3.java index f9d8e17684..6cf8caa9a5 100644 --- a/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-3.java +++ b/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-3.java @@ -1,21 +1,17 @@ -public class Beer -{ - public static void main(String args[]) - { - song(99); - } - - public static void song(int b) - { - if(b>=0) - { - if(b>1) - System.out.println(b+" bottles of beer on the wall\n"+b+" bottles of beer\nTake one down, pass it around\n"+(b-1)+" bottles of beer on the wall.\n"); - else if(b==1) - System.out.println(b+" bottle of beer on the wall\n"+b+" bottle of beer\nTake one down, pass it around\n"+(b-1)+" bottles of beer on the wall.\n"); - else - System.out.println(b+" bottles of beer on the wall\n"+b+" bottles of beer\nBetter go to the store and buy some more!"); - song(b-1); - } - } +public class Beer { + public static void main(String args[]) { + song(99); + } + + public static void song(int bottles) { + if (bottles >= 0) { + if (bottles > 1) + System.out.println(bottles + " bottles of beer on the wall\n" + bottles + " bottles of beer\nTake one down, pass it around\n" + (bottles - 1) + " bottles of beer on the wall.\n"); + else if (bottles == 1) + System.out.println(bottles + " bottle of beer on the wall\n" + bottles + " bottle of beer\nTake one down, pass it around\n" + (bottles - 1) + " bottles of beer on the wall.\n"); + else + System.out.println(bottles + " bottles of beer on the wall\n" + bottles + " bottles of beer\nBetter go to the store and buy some more!"); + song(bottles - 1); + } + } } diff --git a/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-4.java b/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-4.java index ca5c43b61a..1fb5e9c375 100644 --- a/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-4.java +++ b/Task/99-Bottles-of-Beer/Java/99-bottles-of-beer-4.java @@ -1,40 +1,41 @@ import java.awt.BorderLayout; import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTextArea; -public class Beer extends JFrame implements ActionListener{ - private int x; - private JButton take; - private JTextArea text; - public static void main(String[] args){ - new Beer();//build and show the GUI - } - public Beer(){ - x= 99; - take= new JButton("Take one down, pass it around"); - text= new JTextArea(4,30);//size the area to 4 lines, 30 chars each - text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer"); - text.setEditable(false);//so they can't change the text after it's displayed - take.addActionListener(this);//listen to the button - setLayout(new BorderLayout());//handle placement of components - add(text, BorderLayout.CENTER);//put the text area in the largest section - add(take, BorderLayout.SOUTH);//put the button underneath it - pack();//auto-size the window - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit on "X" (I hate System.exit...) - setVisible(true);//show it - } +public class Beer extends JFrame { + private int x; + private JTextArea text; - public void actionPerformed(ActionEvent arg0){ - if(arg0.getSource() == take){//if they clicked the button - JOptionPane.showMessageDialog(null, --x + " bottles of beer on the wall");//show a popup message - text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer");//change the text - } - if(x == 0){//if it's the end - dispose();//end - } + public static void main(String[] args) { + new Beer().setVisible(true); + } + + public Beer() { + x = 99; + + JButton take = new JButton("Take one down, pass it around"); + take.addActionListener(this::onTakeClick); + + text = new JTextArea(4, 30); + text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer"); + text.setEditable(false); + + setLayout(new BorderLayout()); + add(text, BorderLayout.CENTER); + add(take, BorderLayout.PAGE_END); + pack(); + setLocationRelativeTo(null); + setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + } + + private void onTakeClick(ActionEvent event) { + JOptionPane.showMessageDialog(null, --x + " bottles of beer on the wall"); + text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer"); + if (x == 0) { + dispose(); } + } } diff --git a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-5.js b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-5.js index f24a6c991d..be031385b4 100644 --- a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-5.js +++ b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-5.js @@ -1,25 +1 @@ -function Bottles(count) { - this.count = count || 99; -} - -Bottles.prototype.take = function() { - var verse = [ - this.count + " bottles of beer on the wall,", - this.count + " bottles of beer!", - "Take one down, pass it around", - (this.count - 1) + " bottles of beer on the wall!" - ].join("\n"); - - console.log(verse); - - this.count--; -}; - -Bottles.prototype.sing = function() { - while (this.count) { - this.take(); - } -}; - -var bar = new Bottles(99); -bar.sing(); +Array.from(Array(100).keys()).splice(1).reverse().forEach(n => console.log(`${n} bottle${n !== 1 ? 's' : ''} of beer on the wall\n${n} bottle${n !== 1 ? 's' : ''} of beer\nTake one down, pass it around\n${n - 1} bottle${n - 1 !== 1 ? 's' : ''} of beer on the wall\n\n`)); diff --git a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-6.js b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-6.js index 036d7f4de0..f24a6c991d 100644 --- a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-6.js +++ b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-6.js @@ -1,18 +1,25 @@ -function bottleSong(n) { - if (!isFinite(Number(n)) || n == 0) n = 100; - var a = '%% bottles of beer', - b = ' on the wall', - c = 'Take one down, pass it around', - r = '
' - p = document.createElement('p'), - s = [], - re = /%%/g; - - while(n) { - s.push((a+b+r+a+r+c+r).replace(re, n) + (a+b).replace(re, --n)); - } - p.innerHTML = s.join(r+r); - document.body.appendChild(p); +function Bottles(count) { + this.count = count || 99; } -window.onload = bottleSong; +Bottles.prototype.take = function() { + var verse = [ + this.count + " bottles of beer on the wall,", + this.count + " bottles of beer!", + "Take one down, pass it around", + (this.count - 1) + " bottles of beer on the wall!" + ].join("\n"); + + console.log(verse); + + this.count--; +}; + +Bottles.prototype.sing = function() { + while (this.count) { + this.take(); + } +}; + +var bar = new Bottles(99); +bar.sing(); diff --git a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-7.js b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-7.js new file mode 100644 index 0000000000..036d7f4de0 --- /dev/null +++ b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-7.js @@ -0,0 +1,18 @@ +function bottleSong(n) { + if (!isFinite(Number(n)) || n == 0) n = 100; + var a = '%% bottles of beer', + b = ' on the wall', + c = 'Take one down, pass it around', + r = '
' + p = document.createElement('p'), + s = [], + re = /%%/g; + + while(n) { + s.push((a+b+r+a+r+c+r).replace(re, n) + (a+b).replace(re, --n)); + } + p.innerHTML = s.join(r+r); + document.body.appendChild(p); +} + +window.onload = bottleSong; diff --git a/Task/99-Bottles-of-Beer/jq/99-bottles-of-beer-1.jq b/Task/99-Bottles-of-Beer/Jq/99-bottles-of-beer-1.jq similarity index 100% rename from Task/99-Bottles-of-Beer/jq/99-bottles-of-beer-1.jq rename to Task/99-Bottles-of-Beer/Jq/99-bottles-of-beer-1.jq diff --git a/Task/99-Bottles-of-Beer/jq/99-bottles-of-beer-2.jq b/Task/99-Bottles-of-Beer/Jq/99-bottles-of-beer-2.jq similarity index 100% rename from Task/99-Bottles-of-Beer/jq/99-bottles-of-beer-2.jq rename to Task/99-Bottles-of-Beer/Jq/99-bottles-of-beer-2.jq diff --git a/Task/99-Bottles-of-Beer/jq/99-bottles-of-beer-3.jq b/Task/99-Bottles-of-Beer/Jq/99-bottles-of-beer-3.jq similarity index 100% rename from Task/99-Bottles-of-Beer/jq/99-bottles-of-beer-3.jq rename to Task/99-Bottles-of-Beer/Jq/99-bottles-of-beer-3.jq diff --git a/Task/99-Bottles-of-Beer/jq/99-bottles-of-beer-4.jq b/Task/99-Bottles-of-Beer/Jq/99-bottles-of-beer-4.jq similarity index 100% rename from Task/99-Bottles-of-Beer/jq/99-bottles-of-beer-4.jq rename to Task/99-Bottles-of-Beer/Jq/99-bottles-of-beer-4.jq diff --git a/Task/99-Bottles-of-Beer/Kotlin/99-bottles-of-beer.kotlin b/Task/99-Bottles-of-Beer/Kotlin/99-bottles-of-beer.kotlin index 612c8220d4..208848f9c1 100644 --- a/Task/99-Bottles-of-Beer/Kotlin/99-bottles-of-beer.kotlin +++ b/Task/99-Bottles-of-Beer/Kotlin/99-bottles-of-beer.kotlin @@ -1,7 +1,7 @@ fun main(args: Array) { for (i in 99.downTo(1)) { - println("${i} bottles of beer on the wall") - println("${i} bottles of beer") + println("$i bottles of beer on the wall") + println("$i bottles of beer") println("Take one down, pass it around") } println("No more bottles of beer on the wall!") diff --git a/Task/99-Bottles-of-Beer/LLVM/99-bottles-of-beer.llvm b/Task/99-Bottles-of-Beer/LLVM/99-bottles-of-beer.llvm deleted file mode 100644 index e60b4f47d3..0000000000 --- a/Task/99-Bottles-of-Beer/LLVM/99-bottles-of-beer.llvm +++ /dev/null @@ -1,70 +0,0 @@ -; "99 Bottles of Beer on the Wall" in LLVM Assembly - -; This is not strictly LLVM, as it uses the C library function "printf". -; LLVM does not provide a way to print values, so the alternative would be -; to just load the string into memory, and that would be boring. - -; The song lyrics are global constants. -; Lyrics for plural verses: -@pluralVerse = private constant [120 x i8] -c"%d bottles of beer on the wall, %d bottles of beer.\0ATake one down and pass it around, %d bottles of beer on the wall.\0A\0A\00" -; Lyrics for the singular verse: -@singularVerse = private constant [121 x i8] - c"1 bottle of beer on the wall, 1 bottle of beer.\0ATake one down and pass it around, no more bottles of beer on the wall.\0A\0A\00" -; Lyrics for the final verse: -@finalVerse = private constant [130 x i8] - c"No more bottles of beer on the wall, no more bottles of beer.\0AGo to the store and buy some more, %d bottles of beer on the wall.\0A\00" - -; Initial number of bottles of beer. -; This must be a natural number. -@initialVerseNumber = private constant i32 99 - -; The declaration for the external C printf function. -declare i32 @printf(i8*, ...) - -; Prints a verse, with %numberOfBottles being the initial number of bottles -; in that verse. -define fastcc void @printVerse(i32 %numberOfBottles) { - switch i32 %numberOfBottles, - label %pluralVerse - [ i32 1, label %singularVerse - i32 0, label %finalVerse ] - -pluralVerse: - %pluralVersePointer = getelementptr [120 x i8]* @pluralVerse, i64 0, i64 0 - %newNumberOfBottles = sub i32 %numberOfBottles, 1 - call i32(i8*, ...)* @printf( - i8* %pluralVersePointer, - i32 %numberOfBottles, - i32 %numberOfBottles, - i32 %newNumberOfBottles) - ret void - -singularVerse: - %singularVersePointer = getelementptr [121 x i8]* @singularVerse,i64 0,i64 0 - call i32(i8*, ...)* @printf(i8* %singularVersePointer) - ret void - -finalVerse: - %finalVersePointer = getelementptr [130 x i8]* @finalVerse, i64 0, i64 0 - %initialVerseNumberL = load i32* @initialVerseNumber - call i32(i8*, ...)* @printf(i8* %finalVersePointer,i32 %initialVerseNumberL) - ret void -} - -define i32 @main() { -loopHeader: - %initialVerseNumberL = load i32* @initialVerseNumber - br label %loop ; This br terminates the first basic block. -loop: - %verseNumber = - phi i32 [%initialVerseNumberL, %loopHeader], [%nextVerseNumber, %do] - %cond = icmp eq i32 -1, %verseNumber - br i1 %cond, label %break, label %do -do: - call fastcc void @printVerse(i32 %verseNumber) - %nextVerseNumber = sub i32 %verseNumber, 1 - br label %loop -break: - ret i32 0 -} diff --git a/Task/99-Bottles-of-Beer/LOLCODE/99-bottles-of-beer.lol b/Task/99-Bottles-of-Beer/LOLCODE/99-bottles-of-beer.lol deleted file mode 100644 index 1fec3e9577..0000000000 --- a/Task/99-Bottles-of-Beer/LOLCODE/99-bottles-of-beer.lol +++ /dev/null @@ -1,24 +0,0 @@ -HAI 1.3 - -I HAS A bottles ITZ 99 -I HAS A plural ITZ "Z" -I HAS A lyric ITZ "99 BOTTLZ OV BEER" - -IM IN YR song - VISIBLE lyric " ON TEH WALL" - VISIBLE lyric - VISIBLE "TAEK 1 DOWN, PAZ IT AROUN" - - bottles R DIFF OF bottles AN 1 - NOT bottles, O RLY? - YA RLY, VISIBLE "NO MOAR BOTTLZ OV BEER ON TEH WALL", GTFO - OIC - BOTH SAEM bottles AN 1, O RLY? - YA RLY, plural R "" - OIC - - lyric R SMOOSH bottles " BOTTL" plural " OV BEER" MKAY - VISIBLE lyric " ON TEH WALL:)" -IM OUTTA YR song - -KTHXBYE diff --git a/Task/99-Bottles-of-Beer/Lang5/99-bottles-of-beer.lang5 b/Task/99-Bottles-of-Beer/Lang5/99-bottles-of-beer.lang5 new file mode 100644 index 0000000000..1f7103dea3 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Lang5/99-bottles-of-beer.lang5 @@ -0,0 +1,9 @@ +: ~ 2 compress "" join ; +: verses(*) + dup " bottles of beer on the wall\n" ~ . + dup " bottles of beer\n" ~ . + "Take one down, pass it around\n" . + 1 - " bottles of beer on the wall\n\n" ~ . + ; + +99 iota 1 + reverse verses diff --git a/Task/99-Bottles-of-Beer/Liberty-BASIC/99-bottles-of-beer.liberty b/Task/99-Bottles-of-Beer/Liberty-BASIC/99-bottles-of-beer.liberty deleted file mode 100644 index 5dffeed1a5..0000000000 --- a/Task/99-Bottles-of-Beer/Liberty-BASIC/99-bottles-of-beer.liberty +++ /dev/null @@ -1,13 +0,0 @@ -For bottles = 99 To 1 Step -1 - song$ = song$ + str$(bottles) + " bottle" - If (bottles > 1) Then song$ = song$ + "s" - song$ = song$ + " of beer on the wall, " + str$(bottles) + " bottle" - If (bottles > 1) Then song$ = song$ + "s" - song$ = song$ + " of beer," + chr$(13) + chr$(10) + "Take one down, pass it around, " + str$(bottles - 1) + " bottle" - If (bottles > 2) Or (bottles = 1) Then song$ = song$ + "s" - song$ = song$ + " of beer on the wall." + chr$(13) + chr$(10) -Next bottles -song$ = song$ + "No more bottles of beer on the wall, no more bottles of beer." _ - + chr$(13) + chr$(10) + "Go to the store and buy some more, 99 bottles of beer on the wall." - -Print song$ diff --git a/Task/99-Bottles-of-Beer/Lisp/99-bottles-of-beer.l b/Task/99-Bottles-of-Beer/Lisp/99-bottles-of-beer.l deleted file mode 100644 index 79ae8ef054..0000000000 --- a/Task/99-Bottles-of-Beer/Lisp/99-bottles-of-beer.l +++ /dev/null @@ -1,19 +0,0 @@ -(defun beer-verse (count) - "Recurses the verses" - (format t "~A bottle~A of beer on the wall~%" - count - (if (/= count 1) "s" "")) - (format t "~A bottle~A of beer~%" - count - (if (/= count 1) "s" "")) - (format t "Take one down, pass it round~%") - (format t "~A bottle~A of beer on the wall~%~%" - (if (= count 1) - "No" - (- count 1)) - (if (/= count 2) - "s" - "")) - (if (> count 1) - (beer-verse (- count 1)))) -(beer-verse 99) diff --git a/Task/99-Bottles-of-Beer/MIRC-Scripting-Language/99-bottles-of-beer.mirc b/Task/99-Bottles-of-Beer/MIRC-Scripting-Language/99-bottles-of-beer.mirc new file mode 100644 index 0000000000..fd3dd1af7d --- /dev/null +++ b/Task/99-Bottles-of-Beer/MIRC-Scripting-Language/99-bottles-of-beer.mirc @@ -0,0 +1,8 @@ +var %x = 99 +while (%x) { + echo -ag %x bottles of beer on the wall + echo -ag %x bottles of beer + echo -ag Take one down, pass it around + dec %x + echo -ag %x bottles of beer on the wall +} diff --git a/Task/99-Bottles-of-Beer/MLite/99-bottles-of-beer.mlite b/Task/99-Bottles-of-Beer/MLite/99-bottles-of-beer.mlite new file mode 100644 index 0000000000..ed735f588a --- /dev/null +++ b/Task/99-Bottles-of-Beer/MLite/99-bottles-of-beer.mlite @@ -0,0 +1,24 @@ +val NL = implode [#"newline"] + +fun itone 1 = "it" + | n = "one" + +fun plural (s, 0) = ("no " @ s @ "s") + | (s, 1) = ("1 " @ s) + | (s, n) = (ntos n @ " " @ s @ "s") + +fun verse 0 = "no bottles of beer on the wall" @ NL @ + "no bottles of beer" @ NL @ + "go to the store and buy some more" @ NL @ + "99 bottles of beer on the wall" @ NL @ NL + | x = plural ("bottle",x) @ " of beer on the wall" @ NL @ + plural ("bottle",x) @ " of beer" @ NL @ + "take " @ (itone x) @ " down and pass it round" @ NL @ + plural ("bottle", (x-1)) @ " of beer on the wall" @ NL @ NL + +fun bottles x = map (print o verse) (rev (0 :: iota (1, x))) + +fun default (false, y) = y | (x, _) = x + +; +bottles ` ston ` default (argv 0, "99") diff --git a/Task/99-Bottles-of-Beer/MPIF90/99-bottles-of-beer.mpif90 b/Task/99-Bottles-of-Beer/MPIF90/99-bottles-of-beer.mpif90 deleted file mode 100644 index 7037ec367a..0000000000 --- a/Task/99-Bottles-of-Beer/MPIF90/99-bottles-of-beer.mpif90 +++ /dev/null @@ -1,28 +0,0 @@ -program bottlesMPI - - implicit none - - integer :: ierr,rank,nproc - - character(len=*), parameter :: bwall = " on the wall", & - bottles = "bottles of beer", & - bottle = "bottle of beer", & - take = "Take one down, pass it around", & - form = "(I0, ' ', A)" - - call mpi_init(ierr) - call mpi_comm_size(MPI_COMM_WORLD,nproc, ierr) - call mpi_comm_rank(MPI_COMM_WORLD,rank,ierr) - - if ( rank /= 1 ) then - write (*,form) rank, bottles // bwall - if ( rank > 0 ) write (*,form) rank, bottles - else - write (*,form) rank, bottle // bwall - write (*,form) rank, bottle - end if - if ( rank > 0 ) write (*,*) take - - call mpi_finalize(ierr) - -end program bottlesMPI diff --git a/Task/99-Bottles-of-Beer/Make/99-bottles-of-beer-1.make b/Task/99-Bottles-of-Beer/Make/99-bottles-of-beer-1.make new file mode 100644 index 0000000000..d73e658dbf --- /dev/null +++ b/Task/99-Bottles-of-Beer/Make/99-bottles-of-beer-1.make @@ -0,0 +1,27 @@ +START = 99 +UP != jot - 2 `expr $(START) - 1` 1 + +0-bottles-of-beer: 1-bottle-of-beer + @echo No more bottles of beer on the wall! + +1-bottle-of-beer: 2-bottles-of-beer + @echo One last bottle of beer on the wall! + @echo + @echo One last bottle of beer on the wall, + @echo One last bottle of beer, + @echo Take it down, pass it around. + +.for COUNT in $(UP) +ONE_MORE != expr 1 + $(COUNT) +$(COUNT)-bottles-of-beer: $(ONE_MORE)-bottles-of-beer + @echo $(COUNT) bottles of beer on the wall! + @echo + @echo $(COUNT) bottles of beer on the wall, + @echo $(COUNT) bottles of beer, + @echo Take one down, pass it around. +.endfor + +$(START)-bottles-of-beer: + @echo $(START) bottles of beer on the wall, + @echo $(START) bottles of beer. + @echo Take one down, pass it around. diff --git a/Task/99-Bottles-of-Beer/Make/99-bottles-of-beer-2.make b/Task/99-Bottles-of-Beer/Make/99-bottles-of-beer-2.make new file mode 100644 index 0000000000..3a5961365f --- /dev/null +++ b/Task/99-Bottles-of-Beer/Make/99-bottles-of-beer-2.make @@ -0,0 +1,17 @@ +PRED=`expr $* - 1` + +1-bottles: 1-beer pass + @echo "No more bottles of beer on the wall" + +%-bottles: %-beer pass + @echo "$(PRED) bottles of beer on the wall\n" + @-$(MAKE) $(PRED)-bottles + +1-beer: + @echo "One bottle of beer on the wall, One bottle of beer" + +%-beer: + @echo "$* bottles of beer on the wall, $* bottles of beer" + +pass: + @echo "Take one down and pass it around," diff --git a/Task/99-Bottles-of-Beer/Make/99-bottles-of-beer-3.make b/Task/99-Bottles-of-Beer/Make/99-bottles-of-beer-3.make new file mode 100644 index 0000000000..6089f84836 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Make/99-bottles-of-beer-3.make @@ -0,0 +1,53 @@ +digits:=9 8 7 6 5 4 3 2 1 0 +numbers:=$(foreach x,$(filter-out 0,$(digits)),$(foreach y,$(digits),$x$y)) +numbers+=$(digits) + +bottles=bottle$(if $(findstring /1/,$@),,s) +num=$(if $(findstring /0/,$@),$(empty),$(@F)) +action=$(if $(findstring /0/,$@),$(buy),$(pass)) + +beer:=of beer +wall:=on the wall +empty:=No more +pass:=Take one down and pass it around. +buy:=Go to the store and buy some more. + +# Function to generate targets for each verse of the song. +define verse +.PHONY: $1 +$1: verse/$1/$1 prelude/$2/$2 $2 + +.PHONY: $1-bottles +$1-bottles: $1 + +most?=$1 +endef + +# Recursive function that loops through the 100 numbers. +define verses +$$(eval $$(call verse,$$(word 1,$1),$$(word 2,$1))) +$$(if $$(word 2,$1),$$(eval $$(call verses,$$(filter-out $$(word 1,$1),$1)))) +endef + +# Generate the targets for the 100 numbers. +$(eval $(call verses,$(numbers))) + + +# Main lines in the verse. +.PHONY: verse/% +verse/%: + @echo "$(num) $(bottles) $(beer) $(wall)." + @echo "$(num) $(bottles) $(beer)." + @echo "$(action)" + +# Last line of a verse, which is a prelude to the next verse. +.PHONY: prelude/% +prelude/%: + @echo "$(num) $(bottles) $(beer) $(wall)." + @echo "" + +# Special target for the last line of the song. +.PHONY: prelude/ +prelude/: + @echo "$(most) $(bottles) $(beer) $(wall)!" + @echo "" diff --git a/Task/99-Bottles-of-Beer/Monkey/99-bottles-of-beer.monkey b/Task/99-Bottles-of-Beer/Monkey/99-bottles-of-beer.monkey new file mode 100644 index 0000000000..3cac705191 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Monkey/99-bottles-of-beer.monkey @@ -0,0 +1,75 @@ +Import mojo + +Function Main () + New NintyNineBottles +End + + +Class NintyNineBottles Extends App + + Field _bottles:Int = 99 + Field _y:Int=640 + Field tic:Int + Field duration:Int = 1500 + Field lyric:Int = 1 + Method OnCreate () + SetUpdateRate 60 + End + + ' Stuff to do while running... + Method OnUpdate () + If Millisecs()-Self.tic > Self.duration + Self.tic=Millisecs() + If Self.lyric= 4 Then Self._bottles-=1 + Self.lyric+=1 + + + End If + End + + ' Drawing code... + + Method OnRender () + Cls + + Select Self.lyric + Case 1 + DrawText(_bottles+" bottles of beer on the wall",10,10) + Case 2 + DrawText(_bottles+" bottles of beer",10,10) + Case 3 + If Self._bottles > 1 + DrawText("take one down",10,10) + Else + DrawText("take it down",10,10) + End If + Case 4 + DrawText("Pass it around",10,10) + Case 5 + If Self._bottles>0 + DrawText(Self._bottles+" bottles of beer on the wall",10,10) + Else + DrawText("no more bottles of beer on the wall",10,10) + End If + Case 6 + If Self._bottles>0 + Self.lyric=1'DrawText(Self._bottles+" bottles of beer on the wall",10,10) + Else + DrawText("no more bottles of beer",10,10) + End if + Case 7 + DrawText("go to the store",10,10) + + Case 8 + DrawText("and buy some more",10,10) + Case 9 + Self._bottles=99 + DrawText(_bottles+" more bottles of beer on the wall",10,10) + Case 10 + Self.lyric=1 + End Select + + End + + +End diff --git a/Task/99-Bottles-of-Beer/Moonscript/99-bottles-of-beer.moon b/Task/99-Bottles-of-Beer/Moonscript/99-bottles-of-beer.moon new file mode 100644 index 0000000000..a2af06ba68 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Moonscript/99-bottles-of-beer.moon @@ -0,0 +1,13 @@ +p = (i) -> + i != 1 and 's' or '' + +for b = 99,1,-1 + for i = 1,4 + print if i == 3 + 'Take one down, pass it around' + else + string.format '%s bottle%s of beer%s', + i < 4 and b or b-1, + i < 4 and (p b) or (p b-1), + i%3 == 1 and ' on the wall' or '' + io.write '\n' diff --git a/Task/99-Bottles-of-Beer/NASL/99-bottles-of-beer.nasl b/Task/99-Bottles-of-Beer/NASL/99-bottles-of-beer.nasl new file mode 100644 index 0000000000..ce9942d2ff --- /dev/null +++ b/Task/99-Bottles-of-Beer/NASL/99-bottles-of-beer.nasl @@ -0,0 +1,7 @@ +bottles = 99; +repeat { + display(bottles, ' bottles of beer on the wall\n'); + display(bottles, ' bottles of beer\n'); + display('Take one down, pass it around\n'); + display(--bottles, ' bottles of beer on the wall\n\n'); +} until bottles < 1; diff --git a/Task/99-Bottles-of-Beer/NewLISP/99-bottles-of-beer.newlisp b/Task/99-Bottles-of-Beer/NewLISP/99-bottles-of-beer.newlisp deleted file mode 100644 index 040b39b0b4..0000000000 --- a/Task/99-Bottles-of-Beer/NewLISP/99-bottles-of-beer.newlisp +++ /dev/null @@ -1,12 +0,0 @@ -(for (n 99 1) -(println n " bottles of beer on the wall," n " bottles of beer. Take one down, pass it around. ") -(println (- n 1) "bottles of beer on the wall!")) - -;;recursive -;;also shows list afterword -(define (rec bottles) - (if (!= 0 bottles) (print "/n" bottles " bottles of beer on the wall" bottles " bottles of beer. -\nTake one down, pass it around, " (- bottles 1) -" bottles of beer on the wall" (rec ( - bottles 1))))(list bottles)) - -(rec 99) diff --git a/Task/99-Bottles-of-Beer/Nimrod/99-bottles-of-beer.nimrod b/Task/99-Bottles-of-Beer/Nimrod/99-bottles-of-beer.nimrod deleted file mode 100644 index c7c4ad6527..0000000000 --- a/Task/99-Bottles-of-Beer/Nimrod/99-bottles-of-beer.nimrod +++ /dev/null @@ -1,17 +0,0 @@ -proc GetBottleNumber(n: int): string = - var bs: string - if n == 0: - bs = "No more bottles" - elif n == 1: - bs = "1 bottle" - else: - bs = $n & " bottles" - return bs & " of beer" - -for bn in countdown(99, 1): - var cur = GetBottleNumber(bn) - echo(cur, " on the wall, ", cur, ".") - echo("Take one down and pass it around, ", GetBottleNumber(bn-1), " on the wall.\n") - -echo "No more bottles of beer on the wall, no more bottles of beer." -echo "Go to the store and buy some more, 99 bottles of beer on the wall." diff --git a/Task/99-Bottles-of-Beer/OASYS/99-bottles-of-beer.oasys b/Task/99-Bottles-of-Beer/OASYS/99-bottles-of-beer.oasys new file mode 100644 index 0000000000..1963b379da --- /dev/null +++ b/Task/99-Bottles-of-Beer/OASYS/99-bottles-of-beer.oasys @@ -0,0 +1,30 @@ +class player {} + +int count + +property int dummy + +method quit verbs {{quit}} { + quit +} + +method beer verbs {{beer}} { + count = 99 + while count { + print count + print " bottles of beer on the wall.\n" + print count + print " bottles of beer.\nTake one down and pass it around,\n" + count = count - 1 + if count { + print count + print " bottles of beer on the wall.\n\n" + } + } + print "No more bottles of beer on the wall.\n" +} + +method init { + player = create player + print "Type 'beer' for beer.\nType 'quit' to quit.\n" +} diff --git a/Task/99-Bottles-of-Beer/Pascal/99-bottles-of-beer.pascal b/Task/99-Bottles-of-Beer/Pascal/99-bottles-of-beer.pascal deleted file mode 100644 index bcb5d4cdb3..0000000000 --- a/Task/99-Bottles-of-Beer/Pascal/99-bottles-of-beer.pascal +++ /dev/null @@ -1,21 +0,0 @@ -procedure BottlesOfBeer; -var - i: Integer; -begin - for i := 99 downto 1 do - begin - if i = 1 then - begin - WriteLn('1 bottle of beer on the wall'); - WriteLn('1 bottle of beer'); - WriteLn('Take one down, pass it around'); - WriteLn('No more bottles of beer on the wall'); - Exit; - end; - WriteLn(Format('%d bottles of beer on the wall', [i])); - WriteLn(Format('%d bottles of beer', [i])); - WriteLn('Take one down, pass it around'); - WriteLn(Format('%d bottles of beer on the wall', [Pred(i)])); - WriteLn(''); - end; -end; diff --git a/Task/99-Bottles-of-Beer/PicoLisp/99-bottles-of-beer.l b/Task/99-Bottles-of-Beer/PicoLisp/99-bottles-of-beer.l deleted file mode 100644 index 3c1a50cec9..0000000000 --- a/Task/99-Bottles-of-Beer/PicoLisp/99-bottles-of-beer.l +++ /dev/null @@ -1,12 +0,0 @@ -(de bottles (N) - (case N - (0 "No more beer") - (1 "One bottle of beer") - (T (cons N " bottles of beer")) ) ) - -(for (N 99 (gt0 N)) - (prinl (bottles N) " on the wall,") - (prinl (bottles N) ".") - (prinl "Take one down, pass it around,") - (prinl (bottles (dec 'N)) " on the wall.") - (prinl) ) diff --git a/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-1.psh b/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-1.psh deleted file mode 100644 index 645f527544..0000000000 --- a/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-1.psh +++ /dev/null @@ -1,7 +0,0 @@ -for($n=99; $n -gt 0; $n--) { - "$n bottles of beer on the wall" - "$n bottles of beer" - "Take one down, pass it around" - [string]($n-1) + " bottles of beer on the wall" - "" -} diff --git a/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-2.psh b/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-2.psh deleted file mode 100644 index 4e1af6aa09..0000000000 --- a/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-2.psh +++ /dev/null @@ -1,8 +0,0 @@ -[int]$i = 99; -for($i=99; $i -gt 0; $i--) { - write-host $i " bottles of beer on the wall"; - write-host $i " bottles of beer"; - write-host "Take one down, pass it around" - write-host ($i-1) " bottles of beer on the wall" - write-host "" -} diff --git a/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-3.psh b/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-3.psh deleted file mode 100644 index fc1e3107e4..0000000000 --- a/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-3.psh +++ /dev/null @@ -1,4 +0,0 @@ -$n=99 -do { - "{0} bottles of beer on the wall`n{0} bottles of beer`nTake one down, pass it around`n{1} bottles of beer on the wall`n" -f $n, --$n -} while ($n -gt 0) diff --git a/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-4.psh b/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-4.psh deleted file mode 100644 index 95e2390b59..0000000000 --- a/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-4.psh +++ /dev/null @@ -1,4 +0,0 @@ -$n=99 -do { - "{0} bottles of beer on the wall`n{0} bottles of beer`nTake one down, pass it around`n{1} bottles of beer on the wall`n" -f $n, --$n -} until ($n -eq 0) diff --git a/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-5.psh b/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-5.psh deleted file mode 100644 index 0f25d69385..0000000000 --- a/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-5.psh +++ /dev/null @@ -1,3 +0,0 @@ -$s = "{0} bottles of beer on the wall`n{0} bottles of beer`nTake one down, pass it around`n{1} bottles of beer on the wall`n" -$n=99 -do { $s -f $n, --$n } while ($n -gt 0) diff --git a/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-6.psh b/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-6.psh deleted file mode 100644 index 8eaaa70185..0000000000 --- a/Task/99-Bottles-of-Beer/PowerShell/99-bottles-of-beer-6.psh +++ /dev/null @@ -1,4 +0,0 @@ -99..1 | ForEach-Object { - $s=$( if( $_ -ne 1 ) { 's' } else { '' } ) - $s2=$( if( $_ -ne 2 ) { 's' } else { '' } ) - "$_ bottle$s of beer on the wall`n$_ bottle$s of beer`nTake one down`npass it around`n$( $_ - 1 ) bottle$s2 of beer on the wall`n"} diff --git a/Task/99-Bottles-of-Beer/ProDOS/99-bottles-of-beer.dos b/Task/99-Bottles-of-Beer/ProDOS/99-bottles-of-beer.dos deleted file mode 100644 index 2e923239d6..0000000000 --- a/Task/99-Bottles-of-Beer/ProDOS/99-bottles-of-beer.dos +++ /dev/null @@ -1,16 +0,0 @@ -editvar /newvar /value=a=99 -:a -printline -a- bottles of beer on the wall -printline -a- bottles of beer -printline Take one down, pass it round -editvar /newvar /value=a=-a-1 -if -a- /hasvalue 1 goto :1 -printline -a- bottles of beer on the wall. -goto :a -:1 -printline 1 bottle of beer on the wall -printline 1 bottle of beer -printline take it down, pass it round -printline no bottles of beer on the wall. -editvar /newvar /value=b /userinput=1 /title=Keep drinking? -if -b- /hasvalue yes goto :a else exitprogram diff --git a/Task/99-Bottles-of-Beer/Prolog/99-bottles-of-beer-1.pro b/Task/99-Bottles-of-Beer/Prolog/99-bottles-of-beer-1.pro deleted file mode 100644 index 2160c6cb06..0000000000 --- a/Task/99-Bottles-of-Beer/Prolog/99-bottles-of-beer-1.pro +++ /dev/null @@ -1,10 +0,0 @@ -bottles(0):-!. -bottles(X):- - writef('%t bottles of beer on the wall \n',[X]), - writef('%t bottles of beer\n',[X]), - write('Take one down, pass it around\n'), - succ(XN,X), - writef('%t bottles of beer on the wall \n\n',[XN]), - bottles(XN). - -:- bottles(99). diff --git a/Task/99-Bottles-of-Beer/Prolog/99-bottles-of-beer-2.pro b/Task/99-Bottles-of-Beer/Prolog/99-bottles-of-beer-2.pro deleted file mode 100644 index 996a5d7fbf..0000000000 --- a/Task/99-Bottles-of-Beer/Prolog/99-bottles-of-beer-2.pro +++ /dev/null @@ -1,19 +0,0 @@ -line1(X):- line2(X),write(' on the wall'). -line2(0):- write('no more bottles of beer'). -line2(1):- write('1 bottle of beer'). -line2(X):- writef('%t bottles of beer',[X]). -line3(1):- write('Take it down, pass it around'). -line3(X):- write('Take one down, pass it around'). -line4(X):- line1(X). - -bottles(0):-!. -bottles(X):- - succ(XN,X), - line1(X),nl, - line2(X),nl, - line3(X),nl, - line4(XN),nl,nl, - !, - bottles(XN). - -:- bottles(99). diff --git a/Task/99-Bottles-of-Beer/PureBasic/99-bottles-of-beer-1.purebasic b/Task/99-Bottles-of-Beer/PureBasic/99-bottles-of-beer-1.purebasic deleted file mode 100644 index b1c205e835..0000000000 --- a/Task/99-Bottles-of-Beer/PureBasic/99-bottles-of-beer-1.purebasic +++ /dev/null @@ -1,13 +0,0 @@ -If OpenConsole() - Define Bottles=99 - While Bottles - PrintN(Str(Bottles)+" bottles of beer on the wall") - PrintN(Str(Bottles)+" bottles of beer") - PrintN("Take one down, pass it around") - Bottles-1 - PrintN(Str(Bottles)+" bottles of beer on the wall"+#CRLF$) - Wend - - PrintN(#CRLF$+#CRLF$+"Press ENTER to exit"):Input() - CloseConsole() -EndIf diff --git a/Task/99-Bottles-of-Beer/PureBasic/99-bottles-of-beer-2.purebasic b/Task/99-Bottles-of-Beer/PureBasic/99-bottles-of-beer-2.purebasic deleted file mode 100644 index 3e437bb017..0000000000 --- a/Task/99-Bottles-of-Beer/PureBasic/99-bottles-of-beer-2.purebasic +++ /dev/null @@ -1,59 +0,0 @@ -Prototype Wall_Action(*Self, Number.i) - -Structure WallClass - Inventory.i - AddBottle.Wall_Action - DrinkAndSing.Wall_Action -EndStructure - -Procedure.s _B(n, Short=#False) - Select n - Case 0 : result$="No more bottles " - Case 1 : result$=Str(n)+" bottle of beer" - Default: result$=Str(n)+" bottles of beer" - EndSelect - If Not Short: result$+" on the wall": EndIf - ProcedureReturn result$+#CRLF$ -EndProcedure - -Procedure PrintBottles(*Self.WallClass, n) - Bottles$=" bottles of beer " - Bottle$ =" bottle of beer " - txt$ = _B(*Self\Inventory) - txt$ + _B(*Self\Inventory, #True) - txt$ + "Take one down, pass it around"+#CRLF$ - *Self\AddBottle(*Self, -1) - txt$ + _B(*self\Inventory) - PrintN(txt$) - ProcedureReturn *Self\Inventory -EndProcedure - -Procedure AddBottle(*Self.WallClass, n) - i=*Self\Inventory+n - If i>=0 - *Self\Inventory=i - EndIf -EndProcedure - -Procedure InitClass() - *class.WallClass=AllocateMemory(SizeOf(WallClass)) - If *class - InitializeStructure(*class, WallClass) - With *class - \AddBottle =@AddBottle() - \DrinkAndSing =@PrintBottles() - EndWith - EndIf - ProcedureReturn *class -EndProcedure - -If OpenConsole() - *MyWall.WallClass=InitClass() - If *MyWall - *MyWall\AddBottle(*MyWall, 99) - While *MyWall\DrinkAndSing(*MyWall, #True): Wend - ; - PrintN(#CRLF$+#CRLF$+"Press ENTER to exit"):Input() - CloseConsole() - EndIf -EndIf diff --git a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-1.py b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-1.py deleted file mode 100644 index de0103c5aa..0000000000 --- a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-1.py +++ /dev/null @@ -1,14 +0,0 @@ -def plural(word, amount): # Correctly pluralize a word. - if amount == 1: - return word - else: - return word + 's' - -def sing(b, end): # Sing a phrase of the song, for b bottles, ending in end - print b or 'No more', plural('bottle', b), end - -for i in range(99, 0, -1): - sing(i, 'of beer on the wall,') - sing(i, 'of beer,') - print 'Take one down, pass it around,' - sing(i-1, 'of beer on the wall.\n') diff --git a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-2.py b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-2.py deleted file mode 100644 index 0b8ed8e4c9..0000000000 --- a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-2.py +++ /dev/null @@ -1,9 +0,0 @@ -verse = '''\ -%i bottles of beer on the wall -%i bottles of beer -Take one down, pass it around -%i bottles of beer on the wall -''' - -for bottles in range(99,0,-1): - print verse % (bottles, bottles, bottles-1) diff --git a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-3.py b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-3.py deleted file mode 100644 index e3844fad8d..0000000000 --- a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-3.py +++ /dev/null @@ -1,9 +0,0 @@ -verse = '''\ -{some} bottles of beer on the wall -{some} bottles of beer -Take one down, pass it around -{less} bottles of beer on the wall -''' - -for bottles in range(99,0,-1): - print verse.format(some=bottles, less=bottles-1) diff --git a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-4.py b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-4.py deleted file mode 100644 index 7d5e47be3f..0000000000 --- a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-4.py +++ /dev/null @@ -1,2 +0,0 @@ -a, b, c, s = " bottles of beer", " on the wall\n", "Take one down, pass it around\n", str -print "\n".join(s(x)+a+b+s(x)+a+"\n"+c+s(x-1)+a+b for x in xrange(99, 0, -1)) diff --git a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-5.py b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-5.py deleted file mode 100644 index 8324e1645a..0000000000 --- a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-5.py +++ /dev/null @@ -1,2 +0,0 @@ -a = lambda n: "%u bottle%s of beer on the wall\n" % (n, "s"[n==1:]) -print "\n".join(a(x)+a(x)[:-13]+"\nTake one down, pass it around\n"+a(x-1) for x in xrange(99, 0, -1)) diff --git a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-6.py b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-6.py deleted file mode 100644 index 3cd3b209d1..0000000000 --- a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-6.py +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env python3 -"""\ -{0} {2} of beer on the wall -{0} {2} of beer -Take one down, pass it around -{1} {3} of beer on the wall -""" -print("\n".join( - __doc__.format( - i, i - 1, - "bottle" if i == 1 else "bottles", - "bottle" if i - 1 == 1 else "bottles" - ) for i in range(99, 0, -1) -), end="") diff --git a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-7.py b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-7.py deleted file mode 100644 index 614f67c2e8..0000000000 --- a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-7.py +++ /dev/null @@ -1,39 +0,0 @@ -ones = ( -'', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine' -) -prefixes = ('thir', 'four', 'fif', 'six', 'seven', 'eigh', 'nine') -tens = ['', '', 'twenty' ] -teens = ['ten', 'eleven', 'twelve'] -for prefix in prefixes: - tens.append(prefix + 'ty') - teens.append(prefix +'teen') -tens[4] = 'forty' - -def number(num): - "get the wordy version of a number" - ten, one = divmod(num, 10) - if ten == 0 and one == 0: - return 'no' - elif ten == 0: - return ones[one] - elif ten == 1: - return teens[one] - elif one == 0: - return tens[ten] - else: - return "%s-%s" % (tens[ten], ones[one]) - -def bottles(beer): - "our rephrase" - return "%s bottle%s of beer" % ( - number(beer).capitalize(), 's' if beer > 1 else '' - ) - -onthewall = 'on the wall' -takeonedown = 'Take one down, pass it around' -for beer in range(99, 0, -1): - print bottles(beer), onthewall - print bottles(beer) - print takeonedown - print bottles(beer-1), onthewall - print diff --git a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-8.py b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-8.py deleted file mode 100644 index 930169b060..0000000000 --- a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-8.py +++ /dev/null @@ -1,7 +0,0 @@ -for n in xrange(99, 0, -1): - ## The formatting performs a conditional check on the variable. - ## If it formats the first open for False, and the second for True - print n, 'bottle%s of beer on the the wall.' % ('s', '')[n == 1] - print n, 'bottle%s of beer.' % ('s', '')[n == 1] - print 'Take one down, pass it around.' - print n - 1, 'bottle%s of beer on the wall.\n' % ('s', '')[n - 1 == 1] diff --git a/Task/99-Bottles-of-Beer/REALbasic/99-bottles-of-beer.realbasic b/Task/99-Bottles-of-Beer/REALbasic/99-bottles-of-beer.realbasic deleted file mode 100644 index 97a23b973b..0000000000 --- a/Task/99-Bottles-of-Beer/REALbasic/99-bottles-of-beer.realbasic +++ /dev/null @@ -1,8 +0,0 @@ -dim bottles as Integer = 99 -While bottles > 0 - Print(str(bottles) + " bottles of beer on the wall") - Print(str(bottles) + " bottles of beer") - Print("Take one down, pass it around") - bottles = bottles - 1 - Print(str(bottles) + " bottles of beer on the wall") -Wend diff --git a/Task/99-Bottles-of-Beer/Racket/99-bottles-of-beer.rkt b/Task/99-Bottles-of-Beer/Racket/99-bottles-of-beer.rkt index d10a60c1f2..f513fe0eec 100644 --- a/Task/99-Bottles-of-Beer/Racket/99-bottles-of-beer.rkt +++ b/Task/99-Bottles-of-Beer/Racket/99-bottles-of-beer.rkt @@ -5,4 +5,4 @@ Take one down, pass it around\n~a of beer on the wall\n\n" (plural bottles) (plural bottles) (plural (sub1 bottles))) (unless (= 1 bottles) (sing (sub1 bottles)))) -(sing 100) +(sing 99) diff --git a/Task/99-Bottles-of-Beer/Run-BASIC/99-bottles-of-beer.run b/Task/99-Bottles-of-Beer/Run-BASIC/99-bottles-of-beer.run deleted file mode 100644 index fdbfabe74e..0000000000 --- a/Task/99-Bottles-of-Beer/Run-BASIC/99-bottles-of-beer.run +++ /dev/null @@ -1,12 +0,0 @@ -b$ = " bottles" -for bottles = 99 To 1 Step -1 - If (bottles = 1) then b$ = " bottle" - print bottles;b$;" of beer on the wall, " - print bottles ;b$;" of beer" - print "Take one down, pass it around, " - if bottles = 1 then - print "No bottles of beer on the wall" - else - print bottles - 1;b$;" of beer on the wall.";chr$(10) - end if -next bottles 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.rust deleted file mode 100644 index 31c96e952b..0000000000 --- a/Task/99-Bottles-of-Beer/Rust/99-bottles-of-beer-2.rust +++ /dev/null @@ -1,16 +0,0 @@ -use std::borrow::Cow; - -fn main() { - for i in (0..100).rev().map(|x| beer(x)) { - println!("{}", i) - } -} -fn beer(num: u32) -> Cow<'static, str> { - match num { - 1=> "1 bottle of beer on the wall\n1 bottle of beer\nTake one down, pass it around".into(), - 0 => "better go to the store and buy some more.".into(), - _ => (num.to_string() + " bottles of beer on the wall\n" + - &num.to_string() +" bottles of beer\nTake one down, pass it around\n" + - beer(num - 1).lines().nth(0).unwrap() + "\n").into(), - } -} 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.rust 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.rust diff --git a/Task/99-Bottles-of-Beer/SNUSP/99-bottles-of-beer.snusp b/Task/99-Bottles-of-Beer/SNUSP/99-bottles-of-beer.snusp deleted file mode 100644 index 67356a27ff..0000000000 --- a/Task/99-Bottles-of-Beer/SNUSP/99-bottles-of-beer.snusp +++ /dev/null @@ -1,19 +0,0 @@ - /=!/===========!/==+++++++++# +9 - | | /=!/=====@/==@@@+@+++++# +48 (itoa) - | | | | /==!/==@@@@=++++# +32 (space) - | | | | | \==@@++\!+++++++++++++\!+++++\ - 9 9 '9 9' space 'b' 'o' 't' - $@/>@/>@/>@/>@/>========@/>============@/>====@/>++++++++++ \n setup -/====================================loop=====>\!=>\!<<<<<<<< / -\@\@\>cr.@\< ?\<->+++++++++>->+++++++++\ | | - ! | | \===-========>=>-==BCD==!\< @\< ?/< ?/# no more beer! - /=|=====|================================/ - | | \<++t.<<----a.>----k.<++++e.<_.>>++++o.-n.< e.<_.>-d.>+o.>+++w.<-n.<<_.\ - | | / / - | | \>---a.>n.<+++d.<_.>>++p.<---a.>>----s.s.<<<_.>>-------i.>+t.<<<_.\ - | | / / - | | \>a.>>--r.<++++++o.>+++u.<-n.<+++d.>>>cr.<-T<+O<--B<<<# - | ! - \@\<<<_.>>o.-n.<<_.>>>++t.<<+++h.---e.<_.>>>+++w.<<----a.>--l.l.>>CR.<---T<+++O<+B<<<# - | - \9.>9.>_.>B.>O.>T.t.<---l.<+++e.>>-s.<<<_.>>+++O.<+f.<_.>----b.+++e.E.>>-R.# diff --git a/Task/99-Bottles-of-Beer/Sed/99-bottles-of-beer.sed b/Task/99-Bottles-of-Beer/Sed/99-bottles-of-beer.sed new file mode 100644 index 0000000000..62ab197639 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Sed/99-bottles-of-beer.sed @@ -0,0 +1,26 @@ +s/.*/99 bottles of beer on the wall/ +h +: b +s/^0// +/^0/q +s/^1 bottles/1 bottle/ +p +s/on.*// +p +s/.*/Take one down, pass it around/ +p +g +/^.[1-9]/{ +h +s/^.// +y/123456789/012345678/ +x +s/^\(.\).*$/\1/ +G +s/\n// +h +bb +} +y/0123456789/9012345678/ +h +bb diff --git a/Task/99-Bottles-of-Beer/Simula/99-bottles-of-beer-1.simula b/Task/99-Bottles-of-Beer/Simula/99-bottles-of-beer-1.simula new file mode 100644 index 0000000000..7ede693f13 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Simula/99-bottles-of-beer-1.simula @@ -0,0 +1,36 @@ +COMMENT HTTP://99-BOTTLES-OF-BEER.NET ; +COMMENT AUTHOR: TIM GOODWIN ; +COMMENT DATE: 04/20/05 ; +BEGIN + + PROCEDURE BOTTLES(N); INTEGER N; + BEGIN + IF N = 0 THEN OUTTEXT("NO MORE BOTTLES") ELSE + IF N = 1 THEN OUTTEXT("ONE BOTTLE") ELSE + BEGIN + OUTINT(N, 0); + OUTTEXT(" BOTTLES"); + END; + OUTTEXT(" OF BEER"); + END OF BOTTLES; + + PROCEDURE BEER(N); INTEGER N; + BEGIN + WHILE N > 0 DO BEGIN + BOTTLES(N); + OUTTEXT(" ON THE WALL"); + OUTIMAGE; + BOTTLES(N); + OUTIMAGE; + OUTTEXT( "TAKE ONE DOWN, PASS IT AROUND"); + OUTIMAGE; + BOTTLES(N - 1); + OUTTEXT( " ON THE WALL"); + OUTIMAGE; + OUTIMAGE; + N := N - 1; + END; + END OF BEER; + + BEER(99); +END; diff --git a/Task/99-Bottles-of-Beer/Simula/99-bottles-of-beer-2.simula b/Task/99-Bottles-of-Beer/Simula/99-bottles-of-beer-2.simula new file mode 100644 index 0000000000..ad9afb3e4a --- /dev/null +++ b/Task/99-Bottles-of-Beer/Simula/99-bottles-of-beer-2.simula @@ -0,0 +1,29 @@ +COMMENT http://99-bottles-of-beer.net + author: Jack Leunissen + date: 03/10/07; +BEGIN + INTEGER BOTTLES; + INTEGER NUM; + + NUM := 2; + FOR BOTTLES := 99 STEP -1 UNTIL 1 DO + BEGIN + IF BOTTLES < 10 THEN + NUM := 1; + OUTINT(BOTTLES, NUM); + OUTTEXT(" BOTTLE(S) OF BEER ON THE WALL, "); + OUTINT(BOTTLES, NUM); + OUTTEXT(" BOTTLE(S) OF BEER"); + OUTIMAGE; + OUTTEXT("TAKE ONE DOWN, PASS IT AROUND, "); + OUTINT(BOTTLES - 1, NUM); + OUTTEXT(" BOTTLE(S) OF BEER ON THE WALL."); + OUTIMAGE; + OUTIMAGE; + END; + OUTTEXT("1 BOTTLE OF BEER ON THE WALL, ONE BOTTLE OF BEER."); + OUTIMAGE; + OUTTEXT("TAKE ONE DOWN, PASS IT AROUND, "); + OUTTEXT("NO MORE BOTTLES OF BEER ON THE WALL."); + OUTIMAGE; +END; diff --git a/Task/99-Bottles-of-Beer/Stata/99-bottles-of-beer.stata b/Task/99-Bottles-of-Beer/Stata/99-bottles-of-beer.stata new file mode 100644 index 0000000000..6f26594ca3 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Stata/99-bottles-of-beer.stata @@ -0,0 +1,42 @@ +program drink + local s s + forvalues i=`1'(-1)0 { + if `i'>0 { + display "`i' bottle`s' of beer on the wall" + display "`i' bottle`s' of beer" + display "Take one down, pass it around" + if `i'==2 { + local s "" + } + if `i'>1 { + display "`=`i'-1' bottle`s' of beer on the wall..." + } + else { + display "No more bottles of beer on the wall" + } + display + } + else { + display "No more bottles of beer on the wall" + display "No more bottles of beer" + display "Go to the store and buy some more" + display "`1' bottles of beer on the wall..." + } + } +end + +drink 2 +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 more bottles of beer on the wall + +No more bottles of beer on the wall +No more bottles of beer +Go to the store and buy some more +2 bottles of beer on the wall... diff --git a/Task/99-Bottles-of-Beer/Swift/99-bottles-of-beer.swift b/Task/99-Bottles-of-Beer/Swift/99-bottles-of-beer.swift index b47b0f166e..4a9f0f6571 100644 --- a/Task/99-Bottles-of-Beer/Swift/99-bottles-of-beer.swift +++ b/Task/99-Bottles-of-Beer/Swift/99-bottles-of-beer.swift @@ -1,6 +1,5 @@ -for i in reverse(1...99) { - - println("\(i) bottles of beer on the wall, \(i) bottles of beer.") - let next = i == 1 ? "no" : i.description - println("Take one down and pass it around, \(next) bottles of beer on the wall.") -} +for i in (1...99).reversed() { + print("\(i) bottles of beer on the wall, \(i) bottles of beer.") + let next = i == 1 ? "no" : i.description + print("Take one down and pass it around, \(next) bottles of beer on the wall.") + } diff --git a/Task/99-Bottles-of-Beer/TI-83-BASIC/99-bottles-of-beer.ti-83 b/Task/99-Bottles-of-Beer/TI-83-BASIC/99-bottles-of-beer.ti-83 deleted file mode 100644 index cca30e2823..0000000000 --- a/Task/99-Bottles-of-Beer/TI-83-BASIC/99-bottles-of-beer.ti-83 +++ /dev/null @@ -1,13 +0,0 @@ -PROGRAM:BEER -:For(I,99,1,-1) -:Disp I -:Disp "BOTTLES OF BEER" -:Disp "ON THE WALL," -:Disp I -:Pause "BOTTLES OF BEER," -:Disp "TAKE ONE DOWN," -:Disp "PASS IT AROUND," -:Disp I-1 -:Disp "BOTTLES OF BEER" -:Disp "ON THE WALL." -:End diff --git a/Task/99-Bottles-of-Beer/TI-89-BASIC/99-bottles-of-beer.ti-89 b/Task/99-Bottles-of-Beer/TI-89-BASIC/99-bottles-of-beer.ti-89 deleted file mode 100644 index be967a6f9c..0000000000 --- a/Task/99-Bottles-of-Beer/TI-89-BASIC/99-bottles-of-beer.ti-89 +++ /dev/null @@ -1,47 +0,0 @@ -Prgm - Local i,plural,clockWas,t,k,wait - "s" → plural - 0 → k - isClkOn() → clockWas - - Define wait() = Prgm - EndPrgm - - ClockOn - - For i,99,0,–1 - Disp "" - Disp string(i) & " bottle" & plural & " of beer on the" - Disp "wall, " & string(i) & " bottle" & plural & " of beer." - - getTime()[3]→t - While getTime()[3] = t and k = 0 : getKey() → k : EndWhile - If k ≠ 0 Then : Exit : EndIf - - Disp "Take one down, pass it" - Disp "around." - - getTime()[3]→t - While getTime()[3] = t and k = 0 : getKey() → k : EndWhile - If k ≠ 0 Then : Exit : EndIf - - If i - 1 = 1 Then - "" → plural - EndIf - If i > 1 Then - Disp string(i-1) & " bottle" & plural & " of beer on the" - Disp "wall." - Else - Disp "No more bottles of beer on" - Disp "the wall." - EndIf - - getTime()[3]→t - While abs(getTime()[3] - t)<2 and k = 0 : getKey() → k : EndWhile - If k ≠ 0 Then : Exit : EndIf - - EndFor - If not clockWas Then - ClockOff - ENdIf -EndPrgm diff --git a/Task/99-Bottles-of-Beer/Tcl/99-bottles-of-beer-1.tcl b/Task/99-Bottles-of-Beer/Tcl/99-bottles-of-beer-1.tcl deleted file mode 100644 index f6ccf91bd9..0000000000 --- a/Task/99-Bottles-of-Beer/Tcl/99-bottles-of-beer-1.tcl +++ /dev/null @@ -1,10 +0,0 @@ -set s "s"; set ob "of beer"; set otw "on the wall"; set more "Take one down and pass it around" -for {set n 100} {$n ne "No more"} {} { - switch -- [incr n -1] { - 1 {set s ""} - 0 {set s "s"; set n "No more"; set more "Go to the store and buy some more"} - } - lappend verse ". $n bottle$s $ob $otw.\n" - lappend verse "\n$n bottle$s $ob $otw, [string tolower $n] bottle$s $ob.\n$more" -} -puts -nonewline [join [lreplace $verse 0 0] ""][lindex $verse 0] diff --git a/Task/99-Bottles-of-Beer/Tcl/99-bottles-of-beer-2.tcl b/Task/99-Bottles-of-Beer/Tcl/99-bottles-of-beer-2.tcl deleted file mode 100644 index 1bf1a247c2..0000000000 --- a/Task/99-Bottles-of-Beer/Tcl/99-bottles-of-beer-2.tcl +++ /dev/null @@ -1,28 +0,0 @@ -proc 0-19 {n} { - lindex {"no more" one two three four five six seven eight nine ten eleven - twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen} $n -} - -proc TENS {n} { - lindex {twenty thirty fourty fifty sixty seventy eighty ninety} [expr {$n - 2}] -} - -proc num2words {n} { - if {$n < 20} {return [0-19 $n]} - set tens [expr {$n / 10}] - set ones [expr {$n % 10}] - if {$ones == 0} {return [TENS $tens]} - return "[TENS $tens]-[0-19 $ones]" -} - -proc get_words {n} { - return "[num2words $n] bottle[expr {$n != 1 ? "s" : ""}] of beer" -} - -for {set i 99} {$i > 0} {incr i -1} { - puts [string totitle "[get_words $i] on the wall, [get_words $i]."] - puts "Take one down and pass it around, [get_words [expr {$i - 1}]] on the wall.\n" -} - -puts "No more bottles of beer on the wall, no more bottles of beer." -puts "Go to the store and buy some more, 99 bottles of beer on the wall." diff --git a/Task/99-Bottles-of-Beer/UNIX-Shell/99-bottles-of-beer-1.sh b/Task/99-Bottles-of-Beer/UNIX-Shell/99-bottles-of-beer-1.sh deleted file mode 100644 index 3e44f9aaa1..0000000000 --- a/Task/99-Bottles-of-Beer/UNIX-Shell/99-bottles-of-beer-1.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh - -i=99 s=s - -while [ $i -gt 0 ]; do - echo "$i bottle$s of beer on the wall" - echo "$i bottle$s of beer -Take one down, pass it around" - # POSIX allows for $(( i - 1 )) but some older Unices didn't have that - i=`expr $i - 1` - [ $i -eq 1 ] && s= || s=s - echo "$i bottle$s of beer on the wall -" -done diff --git a/Task/99-Bottles-of-Beer/UNIX-Shell/99-bottles-of-beer-2.sh b/Task/99-Bottles-of-Beer/UNIX-Shell/99-bottles-of-beer-2.sh deleted file mode 100644 index a2d3635e6a..0000000000 --- a/Task/99-Bottles-of-Beer/UNIX-Shell/99-bottles-of-beer-2.sh +++ /dev/null @@ -1,22 +0,0 @@ -bottles() { - beer=$1 - [ $((beer)) -gt 0 ] && echo -n $beer || echo -n "No more" - echo -n " bottle" - [ $((beer)) -ne 1 ] && echo -n "s" - echo -n " of beer" -} - -for ((i=99;i>=0;i--)); do - ((remaining=i)) - echo "$(bottles $remaining) on the wall" - echo "$(bottles $remaining)" - if [ $((remaining)) -eq 0 ]; then - echo "Go to the store and buy some more" - ((remaining+=99)) - else - echo "Take one down, pass it around" - ((remaining--)) - fi - echo "$(bottles $remaining) on the wall" - echo -done diff --git a/Task/99-Bottles-of-Beer/UNIX-Shell/99-bottles-of-beer-3.sh b/Task/99-Bottles-of-Beer/UNIX-Shell/99-bottles-of-beer-3.sh deleted file mode 100644 index efc12cb2d5..0000000000 --- a/Task/99-Bottles-of-Beer/UNIX-Shell/99-bottles-of-beer-3.sh +++ /dev/null @@ -1,15 +0,0 @@ -@ i=99 -set s=s -while ($i > 0) - echo "$i bottle$s of beer on the wall" - echo "$i bottle$s of beer" - echo "Take one down, pass it around" - @ i = $i - 1 - if ($i == 1) then - set s= - else - set s=s - endif - echo "$i bottle$s of beer on the wall" - echo "" -end diff --git a/Task/99-Bottles-of-Beer/UNIX-Shell/99-bottles-of-beer-4.sh b/Task/99-Bottles-of-Beer/UNIX-Shell/99-bottles-of-beer-4.sh deleted file mode 100644 index e481629d4e..0000000000 --- a/Task/99-Bottles-of-Beer/UNIX-Shell/99-bottles-of-beer-4.sh +++ /dev/null @@ -1,11 +0,0 @@ -i = 99 -s = s -while {test $i -gt 0} { - echo $i bottle$s of beer on the wall - echo $i bottle$s of beer - echo Take one down, pass it around - i = `{expr $i - 1} - if {test $i -eq 1} {s = ''} {s = s} - echo $i bottle$s of beer on the wall - echo -} diff --git a/Task/99-Bottles-of-Beer/UnixPipes/99-bottles-of-beer.unixpipes b/Task/99-Bottles-of-Beer/UnixPipes/99-bottles-of-beer.unixpipes deleted file mode 100644 index 6e1783b4b0..0000000000 --- a/Task/99-Bottles-of-Beer/UnixPipes/99-bottles-of-beer.unixpipes +++ /dev/null @@ -1,15 +0,0 @@ -# Unix Pipes, avoiding all the turing complete sub programs like sed, awk,dc etc. -mkdir 99 || exit 1 -trap "rm -rf 99" 1 2 3 4 5 6 7 8 - -(cd 99 - mkfifo p.b1 p.b2 p.verse1 p.wall p.take - yes "on the wall" > p.wall & - yes "Take one down and pass it around, " > p.take & - (yes "bottles of beer" | nl -s\ | head -n 99 | tac | head -n 98 ; - echo "One bottle of beer"; - echo "No more bottles of beer") | tee p.b1 p.b2 | - paste -d"\ " - p.wall p.b1 p.take | head -n 99 > p.verse1 & - cat p.b2 | tail -99 | paste -d"\ " p.verse1 - p.wall | head -n 99 -) -rm -rf 99 diff --git a/Task/99-Bottles-of-Beer/VBA/99-bottles-of-beer.vba b/Task/99-Bottles-of-Beer/VBA/99-bottles-of-beer.vba deleted file mode 100644 index 687958411a..0000000000 --- a/Task/99-Bottles-of-Beer/VBA/99-bottles-of-beer.vba +++ /dev/null @@ -1,22 +0,0 @@ -Public Function countbottles(n As Integer, liquid As String) As String - countbottles = IIf(n > 1, Format$(n), IIf(n = 0, "no more", "one")) & " bottle" & IIf(n = 1, "", "s") & " of " & liquid -End Function - -Public Sub drink(fullbottles As Integer, Optional liquid As String = "beer") -Static emptybottles As Integer - - Debug.Print countbottles(fullbottles, liquid) & " on the wall" - Debug.Print countbottles(fullbottles, liquid) - - If fullbottles > 0 Then - Debug.Print "take " & IIf(fullbottles > 1, "one", "it") & " down, pass it around" - Debug.Print countbottles(fullbottles - 1, liquid) & " on the wall" - Debug.Print - emptybottles = emptybottles + 1 - drink fullbottles - 1, liquid - Else - Debug.Print "go to the store and buy some more" - Debug.Print countbottles(emptybottles, liquid) & " on the wall" - End If - -End Sub diff --git a/Task/99-Bottles-of-Beer/VBScript/99-bottles-of-beer-1.vb b/Task/99-Bottles-of-Beer/VBScript/99-bottles-of-beer-1.vb deleted file mode 100644 index cb388bce53..0000000000 --- a/Task/99-Bottles-of-Beer/VBScript/99-bottles-of-beer-1.vb +++ /dev/null @@ -1,37 +0,0 @@ -sub song( numBottles ) - dim i - for i = numBottles to 0 step -1 - if i > 0 then - wscript.echo pluralBottles(i) & " of beer on the wall" - wscript.echo pluralBottles(i) & " of beer" - if i = 1 then - wscript.echo "take it down" - else - wscript.echo "take one down" - end if - wscript.echo "and pass it round" - wscript.echo pluralBottles(i-1) & " of beer on the wall" - wscript.echo - else - wscript.echo "no more bottles of beer on the wall" - wscript.echo "no more bottles of beer" - wscript.echo "go to the store" - wscript.echo "and buy some more" - wscript.echo pluralBottles(numBottles) & " of beer on the wall" - wscript.echo - end if - next -end sub - -function pluralBottles( n ) - select case n - case 1 - pluralBottles = "one bottle" - case 0 - pluralBottles = "no more bottles" - case else - pluralBottles = n & " bottles" - end select -end function - -song 3 diff --git a/Task/99-Bottles-of-Beer/VBScript/99-bottles-of-beer-2.vb b/Task/99-Bottles-of-Beer/VBScript/99-bottles-of-beer-2.vb deleted file mode 100644 index 6d6436a1dc..0000000000 --- a/Task/99-Bottles-of-Beer/VBScript/99-bottles-of-beer-2.vb +++ /dev/null @@ -1,23 +0,0 @@ -3 bottles of beer on the wall -3 bottles of beer -take one down -and pass it round -2 bottles of beer on the wall - -2 bottles of beer on the wall -2 bottles of beer -take one down -and pass it round -one bottle of beer on the wall - -one bottle of beer on the wall -one bottle of beer -take it down -and pass it round -no more bottles of beer on the wall - -no more bottles of beer on the wall -no more bottles of beer -go to the store -and buy some more -3 bottles of beer on the wall diff --git a/Task/99-Bottles-of-Beer/VBScript/99-bottles-of-beer-3.vb b/Task/99-Bottles-of-Beer/VBScript/99-bottles-of-beer-3.vb deleted file mode 100644 index 0ab6d268fe..0000000000 --- a/Task/99-Bottles-of-Beer/VBScript/99-bottles-of-beer-3.vb +++ /dev/null @@ -1,58 +0,0 @@ -function pluralBottles( n ) - select case n - case 1 - pluralBottles = "one bottle" - case 0 - pluralBottles = "no more bottles" - case else - pluralBottles = n & " bottles" - end select -end function - -function eef( b, r1, r2 ) - if b then - eef = r1 - else - eef = r2 - end if -end function - -Function evalEmbedded(sInput, sP1) - dim oRe, oMatch, oMatches - dim sExpr, sResult - Set oRe = New RegExp - 'Look for expressions as enclosed in braces - oRe.Pattern = "{(.+?)}" - sResult = sInput - do - Set oMatches = oRe.Execute(sResult) - if oMatches.count = 0 then exit do - for each oMatch in oMatches - '~ wscript.echo oMatch.Value - for j = 0 to omatch.submatches.count - 1 - sExpr = omatch.submatches(j) - sResult = Replace( sResult, "{" & sExpr & "}", eval(sExpr) ) - next - next - loop - evalEmbedded = sResult -End Function - -sub sing( numBottles ) - dim i - for i = numBottles to 0 step -1 - if i = 0 then - wscript.echo evalEmbedded("no more bottles of beer on the wall" & vbNewline & _ - "no more bottles of beer" & vbNewline & _ - "go to the store and buy some more" & vbNewline & _ - "{pluralBottles(sP1)} of beer on the wall" & vbNewline, numBottles) - else - wscript.echo evalEmbedded("{pluralBottles(sP1)} of beer on the wall" & vbNewline & _ - "{pluralBottles(sP1)} of beer" & vbNewline & _ - "take {eef(sP1=1,""it"",""one"")} down and pass it round" & vbNewline & _ - "{pluralBottles(sP1-1)} of beer on the wall" & vbNewline, i) - end if - next -end sub - -sing 3 diff --git a/Task/99-Bottles-of-Beer/Visual-Basic-.NET/99-bottles-of-beer.visual b/Task/99-Bottles-of-Beer/Visual-Basic-.NET/99-bottles-of-beer.visual deleted file mode 100644 index e1b3ae76fe..0000000000 --- a/Task/99-Bottles-of-Beer/Visual-Basic-.NET/99-bottles-of-beer.visual +++ /dev/null @@ -1,20 +0,0 @@ -Module Module1 - Sub Main() - Dim Bottles As Integer - For Bottles = 99 To 0 Step -1 - If Bottles = 0 Then - Console.WriteLine("No more bottles of beer on the wall, no more bottles of beer.") - Console.WriteLine("Go to the store and buy some more, 99 bottles of beer on the wall.") - Console.ReadLine() - ElseIf Bottles = 1 Then - Console.WriteLine(Bottles & " bottle of beer on the wall, " & Bottles & " bottle of beer.") - Console.WriteLine("Take one down and pass it around, no more bottles of beer on the wall.") - Console.ReadLine() - Else - Console.WriteLine(Bottles & " bottles of beer on the wall, " & Bottles & " bottles of beer.") - Console.WriteLine("Take one down and pass it around, " & (Bottles - 1) & " bottles of beer on the wall.") - Console.ReadLine() - End If - Next - End Sub -End Module diff --git a/Task/99-Bottles-of-Beer/Visual-Basic/99-bottles-of-beer.vb b/Task/99-Bottles-of-Beer/Visual-Basic/99-bottles-of-beer.vb deleted file mode 100644 index 65e32dce45..0000000000 --- a/Task/99-Bottles-of-Beer/Visual-Basic/99-bottles-of-beer.vb +++ /dev/null @@ -1,33 +0,0 @@ -Sub Main() - Const bottlesofbeer As String = " bottles of beer" - Const onthewall As String = " on the wall" - Const takeonedown As String = "Take one down, pass it around" - Const onebeer As String = "1 bottle of beer" - - Dim bottles As Long - - For bottles = 99 To 3 Step -1 - Debug.Print CStr(bottles) & bottlesofbeer & onthewall - Debug.Print CStr(bottles) & bottlesofbeer - Debug.Print takeonedown - Debug.Print CStr(bottles - 1) & bottlesofbeer & onthewall - Debug.Print - Next - - Debug.Print "2" & bottlesofbeer & onthewall - Debug.Print "2" & bottlesofbeer - Debug.Print takeonedown - Debug.Print onebeer & onthewall - Debug.Print - - Debug.Print onebeer & onthewall - Debug.Print onebeer - Debug.Print takeonedown - Debug.Print "No more" & bottlesofbeer & onthewall - Debug.Print - - Debug.Print "No" & bottlesofbeer & onthewall - Debug.Print "No" & bottlesofbeer - Debug.Print "Go to the store, buy some more" - Debug.Print "99" & bottlesofbeer & onthewall -End Sub diff --git a/Task/99-Bottles-of-Beer/Visual-Prolog/99-bottles-of-beer.pro b/Task/99-Bottles-of-Beer/Visual-Prolog/99-bottles-of-beer.pro deleted file mode 100644 index c74f83a75e..0000000000 --- a/Task/99-Bottles-of-Beer/Visual-Prolog/99-bottles-of-beer.pro +++ /dev/null @@ -1,24 +0,0 @@ -implement main - open core, std, console - -class predicates - bottles : (integer) -> string procedure (i). - -clauses - bottles(1) = "bottle" :- !. - bottles(_) = "bottles". - - run():- - init(), - foreach B = downTo(99,1) do - write(B," ",bottles(B), " of beer on the wall,\n"), - write(B," ",bottles(B), " of beer,\n"), - write("Take one down, pass it around,\n"), - write(B-1," ",bottles(B-1)," of beer on the wall.\n\n") - end foreach, - - succeed(). -end implement main - -goal - mainExe::run(main::run). diff --git a/Task/99-Bottles-of-Beer/Viua-VM-assembly/99-bottles-of-beer.viua b/Task/99-Bottles-of-Beer/Viua-VM-assembly/99-bottles-of-beer.viua new file mode 100644 index 0000000000..793d60412e --- /dev/null +++ b/Task/99-Bottles-of-Beer/Viua-VM-assembly/99-bottles-of-beer.viua @@ -0,0 +1,107 @@ +.function: bottles_of_beer_text/1 + .name: %iota number_of_bottles + arg %number_of_bottles %0 + + .name: %iota bottles_of_beer + ; support for "1 bottle of beer" and "N bottles of beer" + if (eq %iota %number_of_bottles (istore %iota 1)) +1 +3 + text %bottles_of_beer " bottle of beer" + jump +2 + text %bottles_of_beer " bottles of beer" + + move %0 %bottles_of_beer + return +.end + +.function: first_print/1 + ; this function prints the + ; + ; N bottles of beer on the wall + ; N bottles of beer + ; Take one down, pass it around + ; + .name: %iota number_of_bottles + arg %number_of_bottles %0 + + .name: %iota bottles_of_beer + frame ^[(param %0 %number_of_bottles)] + call %bottles_of_beer bottles_of_beer_text/1 + + echo %number_of_bottles + echo %bottles_of_beer + print (text %iota " on the wall") + echo %number_of_bottles + print %bottles_of_beer + print (text %iota "Take one down, pass it around") + + return +.end + +.function: second_print/1 + ; this function prints the + ; + ; No more bottles of beer on the wall / + ; N bottles of beer on the wall + ; + ; i.e. the last line of a paragraph + .name: %iota number_of_bottles + arg %number_of_bottles %0 + + .name: %iota bottles_of_beer + frame ^[(param %0 %number_of_bottles)] + call %bottles_of_beer bottles_of_beer_text/1 + + .name: %iota on_the_wall + text %on_the_wall " on the wall" + + ; say "No more" instead of "0 bottles" + if %number_of_bottles +1 +3 + echo %number_of_bottles + jump +3 + echo (text %iota "No more") + + echo %bottles_of_beer + print %on_the_wall + + if %number_of_bottles +1 +3 + print (text %iota "") + + return +.end + +.function: bottles_of_beer/1 + .name: %iota total_number_of_bottles + arg %total_number_of_bottles %0 + + ; display first three lines of a paragraph + frame ^[(param %0 %total_number_of_bottles)] + call void first_print/1 + + ; decrement the number of bottles + idec %total_number_of_bottles + + ; display last line of a paragraph + frame ^[(param %0 %total_number_of_bottles)] + call void second_print/1 + + ; immediately return if there are no more bottles + if %total_number_of_bottles theres_more +1 + return + + .mark: theres_more + ; if there are more bottles + ; call the function once more + frame ^[(pamv %0 %total_number_of_bottles)] + tailcall bottles_of_beer/1 +.end + +.function: main/0 + .name: %iota total_number_of_bottles + istore %total_number_of_bottles 9 + + frame ^[(pamv %0 %total_number_of_bottles)] + call void bottles_of_beer/1 + + izero %0 local + return +.end diff --git a/Task/99-Bottles-of-Beer/Whenever/99-bottles-of-beer.whenever b/Task/99-Bottles-of-Beer/Whenever/99-bottles-of-beer.whenever deleted file mode 100644 index 279781eb11..0000000000 --- a/Task/99-Bottles-of-Beer/Whenever/99-bottles-of-beer.whenever +++ /dev/null @@ -1,4 +0,0 @@ -1 defer (4 || N(1)" " AND I + "@ + @ = " + =, p1 + p2 diff --git a/Task/A+B/Gastona/a+b-2.gastona b/Task/A+B/Gastona/a+b-2.gastona new file mode 100644 index 0000000000..1b8a352c6d --- /dev/null +++ b/Task/A+B/Gastona/a+b-2.gastona @@ -0,0 +1,15 @@ +#javaj# + + + EVALAYOUT, 6, 6, 3, + , A , A + , lA , eA + , lB , eB + , bSum, eRes + +#listix# + + <-- bSum> + MSG, eRes data!,, @ + + =, eA + eB diff --git a/Task/A+B/Hy/a+b-1.hy b/Task/A+B/Hy/a+b-1.hy new file mode 100644 index 0000000000..31da952851 --- /dev/null +++ b/Task/A+B/Hy/a+b-1.hy @@ -0,0 +1 @@ +(print (sum (map int (.split (input))))) diff --git a/Task/A+B/Hy/a+b-2.hy b/Task/A+B/Hy/a+b-2.hy new file mode 100644 index 0000000000..42f5442442 --- /dev/null +++ b/Task/A+B/Hy/a+b-2.hy @@ -0,0 +1 @@ +(->> (input) (.split) (map int) (sum) (print)) diff --git a/Task/A+B/Java/a+b-1.java b/Task/A+B/Java/a+b-1.java index 61762511c2..052d8ee196 100644 --- a/Task/A+B/Java/a+b-1.java +++ b/Task/A+B/Java/a+b-1.java @@ -1,8 +1,8 @@ import java.util.*; public class Sum2 { - public static void main(String[] args) { - Scanner in = new Scanner(System.in); // Standard input - System.out.println(in.nextInt() + in.nextInt()); // Standard output - } + public static void main(String[] args) { + Scanner in = new Scanner(System.in); // Standard input + System.out.println(in.nextInt() + in.nextInt()); // Standard output + } } diff --git a/Task/A+B/Java/a+b-3.java b/Task/A+B/Java/a+b-3.java index 546ca2d56f..c8ed02fc85 100644 --- a/Task/A+B/Java/a+b-3.java +++ b/Task/A+B/Java/a+b-3.java @@ -1,19 +1,16 @@ import java.io.*; +import java.nio.charset.Charset; public class AplusB { - public static void main(String[] args) { - try { - StreamTokenizer in = new StreamTokenizer(new FileReader("input.txt")); - in.nextToken(); - int a = (int) in.nval; - in.nextToken(); - int b = (int) in.nval; - FileWriter outFile = new FileWriter("output.txt"); - outFile.write(Integer.toString(a + b)); - outFile.close(); - } - catch (IOException e) { - System.out.println("IO error"); - } - } + public static void main(String[] args) throws IOException { + StreamTokenizer in = new StreamTokenizer(new InputStreamReader(System.in, Charset.defaultCharset())); + in.nextToken(); + int a = (int) in.nval; + in.nextToken(); + int b = (int) in.nval; + + try (Writer out = new OutputStreamWriter(System.out, Charset.defaultCharset())) { + out.write(Integer.toString(a + b)); + } + } } diff --git a/Task/A+B/JavaScript/a+b-4.js b/Task/A+B/JavaScript/a+b-4.js new file mode 100644 index 0000000000..2aa8b71269 --- /dev/null +++ b/Task/A+B/JavaScript/a+b-4.js @@ -0,0 +1,3 @@ +var a = WScript.StdIn.ReadLine(); +var b = WScript.StdIn.ReadLine(); +WSH.echo(a, " + " , b , " = " , Number(a)+Number(b)); diff --git a/Task/A+B/jq/a+b-1.jq b/Task/A+B/Jq/a+b-1.jq similarity index 100% rename from Task/A+B/jq/a+b-1.jq rename to Task/A+B/Jq/a+b-1.jq diff --git a/Task/A+B/jq/a+b-2.jq b/Task/A+B/Jq/a+b-2.jq similarity index 100% rename from Task/A+B/jq/a+b-2.jq rename to Task/A+B/Jq/a+b-2.jq diff --git a/Task/A+B/jq/a+b-3.jq b/Task/A+B/Jq/a+b-3.jq similarity index 100% rename from Task/A+B/jq/a+b-3.jq rename to Task/A+B/Jq/a+b-3.jq diff --git a/Task/A+B/Kite/a+b-1.kite b/Task/A+B/Kite/a+b-1.kite deleted file mode 100644 index a3a3e3d14d..0000000000 --- a/Task/A+B/Kite/a+b-1.kite +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/kite - -import "System.file"; - -in = System.file.stdin; -line = in|readline; -while(not (line is null)) [ - arry = line|split(" "); - result = (arry[0])|int + (arry[1])|int; - result|print; - - line = in|readline; -]; diff --git a/Task/A+B/Kite/a+b-2.kite b/Task/A+B/Kite/a+b-2.kite deleted file mode 100644 index ce039f95fb..0000000000 --- a/Task/A+B/Kite/a+b-2.kite +++ /dev/null @@ -1,5 +0,0 @@ -$ kite a_plus_b.kt <) { + val r = Regex("""-?\d+[ ]+-?\d+""") + while(true) { + print("Enter two integers separated by space(s) or q to quit: ") + val input: String = readLine()!!.trim() + if (input == "q" || input == "Q") break + if (!input.matches(r)) { + println("Invalid input, try again") + continue + } + val index = input.lastIndexOf(' ') + val a = input.substring(0, index).trimEnd().toInt() + val b = input.substring(index + 1).toInt() + if (Math.abs(a) > 1000 || Math.abs(b) > 1000) { + println("Both numbers must be in the interval [-1000, 1000] - try again") + } + else { + println("Their sum is ${a + b}\n") + } + } +} diff --git a/Task/A+B/MIRC-Scripting-Language/a+b.mirc b/Task/A+B/MIRC-Scripting-Language/a+b.mirc new file mode 100644 index 0000000000..5182435e3a --- /dev/null +++ b/Task/A+B/MIRC-Scripting-Language/a+b.mirc @@ -0,0 +1,3 @@ +alias a+b { + echo -ag $calc($1 + $2) +} diff --git a/Task/A+B/Moonscript/a+b.moon b/Task/A+B/Moonscript/a+b.moon new file mode 100644 index 0000000000..07629881b5 --- /dev/null +++ b/Task/A+B/Moonscript/a+b.moon @@ -0,0 +1,2 @@ +a,b = io.read '*number','*number' +print a + b diff --git a/Task/A+B/NewLISP/a+b.newlisp b/Task/A+B/NewLISP/a+b.newlisp new file mode 100644 index 0000000000..b24480d267 --- /dev/null +++ b/Task/A+B/NewLISP/a+b.newlisp @@ -0,0 +1 @@ +(println (apply + (map int (parse (read-line))))) diff --git a/Task/A+B/Nim/a+b-3.nim b/Task/A+B/Nim/a+b-3.nim index 9782c6d193..f5a324e86c 100644 --- a/Task/A+B/Nim/a+b-3.nim +++ b/Task/A+B/Nim/a+b-3.nim @@ -6,7 +6,7 @@ proc aplusb(a,b: float): float = proc getnumber(): float = try: parseFloat(readLine(stdin)) - except EInvalidValue: + except ValueError: echo("Please enter a number: ") getnumber() diff --git a/Task/A+B/Nimrod/a+b-1.nimrod b/Task/A+B/Nimrod/a+b-1.nimrod deleted file mode 100644 index b0365dd189..0000000000 --- a/Task/A+B/Nimrod/a+b-1.nimrod +++ /dev/null @@ -1,3 +0,0 @@ -import strutils, os - -echo parseInt(paramStr(1)) + parseInt(paramStr(2)) diff --git a/Task/A+B/Nimrod/a+b-2.nimrod b/Task/A+B/Nimrod/a+b-2.nimrod deleted file mode 100644 index 848c54d708..0000000000 --- a/Task/A+B/Nimrod/a+b-2.nimrod +++ /dev/null @@ -1,5 +0,0 @@ -import strutils, os -var sum = 0 -for i in countup(1, paramCount()): - sum = sum + parseInt(paramStr(i)) -echo sum diff --git a/Task/A+B/Nit/a+b.nit b/Task/A+B/Nit/a+b.nit index 34b4c22a06..8a81dcedd4 100644 --- a/Task/A+B/Nit/a+b.nit +++ b/Task/A+B/Nit/a+b.nit @@ -1,4 +1,8 @@ module ab var words = gets.split(" ") +if words.length != 2 then + print "Expected two numbers" + return +end print words[0].to_i + words[1].to_i diff --git a/Task/A+B/Ol/a+b.ol b/Task/A+B/Ol/a+b.ol new file mode 100644 index 0000000000..7ef083b10a --- /dev/null +++ b/Task/A+B/Ol/a+b.ol @@ -0,0 +1,12 @@ +; simplest +(+ (read) (read)) + +; safe +(let ((a (read)) + (b (read))) + (if (not (number? a)) + (runtime-error "a is not a number! got:" a)) + (if (not (number? b)) + (runtime-error "b is not a number! got:" b)) + + (print a " + " b " = " (+ a b))) diff --git a/Task/A+B/OoRexx/a+b-1.rexx b/Task/A+B/OoRexx/a+b-1.rexx new file mode 100644 index 0000000000..6ea95731af --- /dev/null +++ b/Task/A+B/OoRexx/a+b-1.rexx @@ -0,0 +1,19 @@ +Numeric digits 1000 /*just in case the user gets ka-razy. */ +Say 'enter some numbers to be summed:' +parse pull y +yplus=add_plus(y) +sum=0 +Do While y<>'' + Parse Var y n y + If datatype(n)<>'NUM' Then Do + Say 'you entered something that is not recognized to be a number:' n + Exit + End + sum+=n + End +Say yplus '=' sum/1 +Exit +add_plus: +Parse arg list +list=space(list) +return translate(list,'+',' ') diff --git a/Task/A+B/OoRexx/a+b-2.rexx b/Task/A+B/OoRexx/a+b-2.rexx new file mode 100644 index 0000000000..27163f9bc4 --- /dev/null +++ b/Task/A+B/OoRexx/a+b-2.rexx @@ -0,0 +1,21 @@ +Numeric digits 1000 +Say 'enter some numbers to be summed:' +parse pull y +sum=0 +yplus='' +Do i=1 By 1 While y<>'' + Parse Var y n y + If datatype(n)<>'NUM' Then Do + Say 'you entered something that is not recognized to be a number:' n + Exit + End + Select + When i=1 Then + yplus=n + When n>0 Then yplus||='+'abs(n) + Otherwise yplus||=n + End + sum+=n + End +Say yplus '=' sum/1 +Exit diff --git a/Task/A+B/Perl/a+b.pl b/Task/A+B/Perl/a+b-1.pl similarity index 100% rename from Task/A+B/Perl/a+b.pl rename to Task/A+B/Perl/a+b-1.pl diff --git a/Task/A+B/Perl/a+b-2.pl b/Task/A+B/Perl/a+b-2.pl new file mode 100644 index 0000000000..692faf3034 --- /dev/null +++ b/Task/A+B/Perl/a+b-2.pl @@ -0,0 +1 @@ +say sum split /\s+/, scalar ; diff --git a/Task/A+B/Red/a+b-1.red b/Task/A+B/Red/a+b-1.red new file mode 100644 index 0000000000..11c00cfcaa --- /dev/null +++ b/Task/A+B/Red/a+b-1.red @@ -0,0 +1 @@ +x: load input print x/1 + x/2 diff --git a/Task/A+B/Red/a+b-2.red b/Task/A+B/Red/a+b-2.red new file mode 100644 index 0000000000..e133b90ed4 --- /dev/null +++ b/Task/A+B/Red/a+b-2.red @@ -0,0 +1 @@ +print (first x: load input) + x/2 diff --git a/Task/A+B/Red/a+b-3.red b/Task/A+B/Red/a+b-3.red new file mode 100644 index 0000000000..c533e60aaa --- /dev/null +++ b/Task/A+B/Red/a+b-3.red @@ -0,0 +1 @@ +print head insert load input 'add diff --git a/Task/A+B/Red/a+b-4.red b/Task/A+B/Red/a+b-4.red new file mode 100644 index 0000000000..3e9e4480bc --- /dev/null +++ b/Task/A+B/Red/a+b-4.red @@ -0,0 +1 @@ +print load replace input " " " + " diff --git a/Task/A+B/Red/a+b.red b/Task/A+B/Red/a+b.red deleted file mode 100644 index 003613d500..0000000000 --- a/Task/A+B/Red/a+b.red +++ /dev/null @@ -1 +0,0 @@ -forever [x: load input print x/1 + x/2] diff --git a/Task/A+B/Ruby/a+b-1.rb b/Task/A+B/Ruby/a+b-1.rb deleted file mode 100644 index 019307f1ca..0000000000 --- a/Task/A+B/Ruby/a+b-1.rb +++ /dev/null @@ -1 +0,0 @@ -puts gets.split.map{|x| x.to_i}.inject{|sum, x| sum + x} diff --git a/Task/A+B/Ruby/a+b-2.rb b/Task/A+B/Ruby/a+b-2.rb deleted file mode 100644 index afdd82e3f8..0000000000 --- a/Task/A+B/Ruby/a+b-2.rb +++ /dev/null @@ -1 +0,0 @@ -puts gets.split.map(&:to_i).inject(&:+) diff --git a/Task/A+B/Rust/a+b-2.rust b/Task/A+B/Rust/a+b-2.rust index 7ae5c6b2c3..abdf167839 100644 --- a/Task/A+B/Rust/a+b-2.rust +++ b/Task/A+B/Rust/a+b-2.rust @@ -1,11 +1,11 @@ -#![feature(iter_arith)] use std::io; fn main() { - let mut a = String::new(); - io::stdin().read_line(&mut a).expect("reading stdin"); - println!("{}", - a.split_whitespace() - .map(|x| x.parse::().expect("these better be numbers")) - .sum::()); + let mut line = String::new(); + io::stdin().read_line(&mut line).expect("reading stdin"); + + let sum: i64 = line.split_whitespace() + .map(|x| x.parse::().expect("Not an integer")) + .sum(); + println!("{}", sum); } diff --git a/Task/A+B/SPL/a+b.spl b/Task/A+B/SPL/a+b.spl new file mode 100644 index 0000000000..1435861ff6 --- /dev/null +++ b/Task/A+B/SPL/a+b.spl @@ -0,0 +1,2 @@ +n = #.split(#.input("Input two numbers, separated by space:")," ") +#.output(n[1],"+",n[2],"=",#.val(n[1])+#.val(n[2])) diff --git a/Task/A+B/Sed/a+b-1.sed b/Task/A+B/Sed/a+b-1.sed new file mode 100644 index 0000000000..28c17878de --- /dev/null +++ b/Task/A+B/Sed/a+b-1.sed @@ -0,0 +1,26 @@ +: Loop +# All done +/^-*00* /s/// +/ -*00*$/s/// +t + +# Negative Check +/^\(-*\)[0-9].* \1[0-9]/!b Negative + +# Create magic lookup table +s/\(.[0-9]*\) \(.[0-9]*\)/\1;987654321000009999000999009909 \2;012345678999990000999000990090/ +s/ \(-\)*\(9*;\)/ \10\2/ +# Decrement 1st number +s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).* \(.*\)/\3\4 \5/ +# Increment 2nd +s/\([^9]\)\(9*\);[^9]*\1\(.\).*\2\(0*\).*/\3\4/ +t Loop + +: Negative +# Create magic lookup table +s/\(.[0-9]*\) \(.[0-9]*\)/\1;987654321000009999000999009909 \2;987654321000009999000999009909/ +# Decrement 1st number +s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).* \(.*\)/\3\4 \5/ +# Decrement 2nd +s/\([^0]\)\(0*\);[^0]*\1\(.\).*\2\(9*\).*/\3\4/ +t Loop diff --git a/Task/A+B/Sed/a+b-2.sed b/Task/A+B/Sed/a+b-2.sed new file mode 100644 index 0000000000..7f99bd8cc8 --- /dev/null +++ b/Task/A+B/Sed/a+b-2.sed @@ -0,0 +1,39 @@ +#!/bin/sed -f + +# Add a marker in front of each digit, for tracking tens, hundreds, etc. +s/[0-9]/<&/g +# Convert numbers to, in essence, tally marks +s/0//g; s/1/|/g; s/2/||/g; s/3/|||/g; s/4/||||/g; s/5/|||||/g +s/6/||||||/g; s/7/|||||||/g; s/8/||||||||/g; s/9/|||||||||/g + +# Multiply by ten for each digit from the back they were. +:tens +s/| + LR R13,R15 " addressability + LA R8,1 l=1 +LOOPL C R8,=A(NN) do l=1 to hbound(words) + BH ELOOPL + LR R1,R8 l + MH R1,=H'20' *20 + LA R10,WORDS-20(R1) @words(l) + MVC STATUS,=CL5'true' cflag='true' + MVC TBLOCKS,BLOCKS tblocks=blocks + MVC CC(1),0(R10) cc=substr(words(l),1,1) + LA R6,1 i=1 +LOOPI CLI CC,C' ' do while cc<>' ' + BE ELOOPI + SR R7,R7 k=0 + LH R0,=H'1' m=1 +LOOPM CH R0,=AL2(L'TBLOCKS) do m=1 to length(tblocks) + BH ELOOPM + LA R5,TBLOCKS-1 @tblocks[0] + AR R5,R0 @tblocks[m] + CLC 0(1,R5),CC if substr(tblocks,m,1)=cc + BNE INDEXM + LR R7,R0 k=m=index(tblocks,cc) + B ELOOPM +INDEXM AH R0,=H'1' m=m+1 + B LOOPM +ELOOPM LTR R7,R7 if k=0 + BNZ OKK + MVC STATUS,=CL5'false' cflag='false' + B EIFK0 +OKK LA R4,TBLOCKS-2 @tblocks[-1] + AR R4,R7 +k + CLI 0(R4),C'(' if substr(tblocks,k-1,1)='(' + BNE SECOND + LA R0,1 j=1 + B EIFBLOCK +SECOND LA R0,3 j=3 +EIFBLOCK LR R2,R7 k + SR R2,R0 k-j + LA R4,TBLOCKS-1 @tblocks[0] + AR R4,R2 @tblocks[k-j] + MVC 0(5,R4),=CL5' ' substr(tblocks,k-j,5)=' ' +EIFK0 LA R6,1(R6) i=i+1 + LR R4,R10 @words + AR R4,R6 +i + BCTR R4,0 -1 + MVC CC,0(R4) cc=substr(words,i,1) + B LOOPI +ELOOPI MVC PG(20),0(R10) tabword(l) + MVC PG+20(5),STATUS status + XPRNT PG,80 print buffer + LA R8,1(R8) l=l+1 + B LOOPL +ELOOPL L R13,4(0,R13) epilog + LM R14,R12,12(R13) " restore + XR R15,R15 " rc=0 + BR R14 exit +WORDS DC CL20'A',CL20'BARK',CL20'BOOK',CL20'TREAT',CL20'COMMON' + DC CL20'SQUAD',CL20'CONFUSE' +BLOCKS DS 0CL122 + DC CL61'((B O) (X K) (D Q) (C P) (N A) (G T) (R E) (T G) (Q D) (F S) ' + DC CL61'(J W) (H U) (V I) (A N) (O B) (E R) (F S) (L Y) (P C) (Z M)) ' +TBLOCKS DS CL(L'BLOCKS) work blocks +CC DS CL1 letter to find +STATUS DS CL5 true/false +PG DC CL80' ' buffer + YREGS +NN EQU (BLOCKS-WORDS)/L'WORDS number of words + END ABC diff --git a/Task/ABC-Problem/8th/abc-problem.8th b/Task/ABC-Problem/8th/abc-problem.8th new file mode 100644 index 0000000000..f5b7f80c51 --- /dev/null +++ b/Task/ABC-Problem/8th/abc-problem.8th @@ -0,0 +1,198 @@ +\ ======================================================================================== +\ You are given a collection of ABC blocks +\ There are twenty blocks with two letters on each block. +\ A complete alphabet is guaranteed amongst all sides of the blocks. +\ +\ Write a function that takes a string (word) and determines whether +\ the word can be spelled with the given collection of blocks. +\ +\ Rules: +\ 1. Once a letter on a block is used that block cannot be used again +\ 2. The function should be case-insensitive +\ 3. Show the output on this page for the following 7 words in the following example +\ can_make_word(???) where ??? is resp.: +\ "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE" +\ +\ NOTE: +\ to make the program readable for even n00bs, I have a comment at the end of each line. +\ The comments take the form of: +\ \ | +\ in order to be able to follow exactly what the program does. +\ ======================================================================================== + +["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"] var, blks +["a", "AbBa", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"] var, chkwrds + +needs stack/rstack + +a:new var, paths \ Keeps the combinatory explosion of letter paths +var wrd +var success +var ix + +: uni2char "" swap s:+ ; + +: char2uni 0 s:@ nip ; + +: rreset rstack st:clear drop ; + +: addoneletter \ ix path -- \ ix path | letter + r@ \ ix path letter | letter + s:+ \ ix newpath | letter + paths @ \ ix newpath paths | letter + -rot \ paths ix newval | letter + a:! \ paths | letter + drop \ | letter + ; + +: oneletter \ letter -- \ letter + >r \ | letter + paths @ ' addoneletter a:each drop \ | letter + ; + +: addtwoletters \ ix path -- \ ix path | letter1 letter2 halflen + swap \ path ix | letter1 letter2 halflen + dup \ path ix ix | letter1 letter2 halflen + r@ \ path ix ix halflen | letter1 letter2 halflen + n:< \ path ix bool | letter1 letter2 halflen + if \ path ix | letter1 letter2 halflen + swap \ ix path | letter1 letter2 halflen + 1 rpick \ ix path letter | letter1 letter2 halflen + else + swap \ ix path | letter1 letter2 halflen + 2 rpick \ ix path letter | letter1 letter2 halflen + then + s:+ \ ix newpath | letter1 letter2 halflen + paths @ \ ix newpath paths | letter1 letter2 halflen + -rot \ paths ix newpath | letter1 letter2 halflen + a:! \ paths | letter1 letter2 halflen + drop \ | letter1 letter2 halflen + ; + +: twoletters \ letters -- \ letters + \ fetch the 2 letters + dup \ letters letters + 1 s:lsub \ letters letter1 + >r \ letters | letter1 + 1 s:rsub \ letter2 | letter1 + >r \ | letter1 letter2 + \ duplicate paths in itself + paths @ dup a:+ \ paths | letter1 letter2 + \ halfway length of array + a:len \ paths len | letter1 letter2 + 2 / \ paths halflen | letter1 letter2 + >r \ paths | letter1 letter2 halflen + \ add letters to paths + ' addtwoletters a:each drop \ | letter1 letter2 halflen + rreset \ + ; + +: chkletter \ letter -- letter \ letter + dup \ letter letter + wrd @ \ letter letter word + swap uni2char \ letter word letter + s:search \ letter word index + null? \ letter word index bool + nip \ letter word bool + if \ letter word + 2drop \ + "" \ letter + else \ letter word + drop \ letter + then \ + ; + +: buildpaths \ ix blk -- \ ix blk + nip \ blk + ' chkletter s:map \ resultletters + s:len \ resultletters len + dup \ resultletters len len + 0 \ resultletters len len 0 + n:= \ resultletters len bool + if \ resultletters len + \ This block contains no letters of current word + 2drop \ + ;; \ exit word + then \ resultletters len + 1 \ resultletters len 1 + n:= \ resultletters bool + if \ resultletters + oneletter \ + else \ resultletters + twoletters \ + then + ; + +: chkokpath \ ix wrdch -- \ ix wrdch | path + swap \ wrdch ix | path + ix ! \ wrdch | path + r@ \ wrdch path | path + dup \ wrdch path path | path + "" \ wrdch path path "" | path + s:= \ wrdch path bool | path + if \ wrdch path | path + \ Path is empty - no match + 2drop \ | path + break \ | path + ;; \ | path + then + swap \ path wrdch | path + uni2char \ path wrdch | path + s:search \ path pos | path + null? \ path pos bool | path + if \ path pos | path + \ Letter not found in path - no match + 2drop \ | path + break \ | path + else \ path pos | path + wrd @ \ path pos wrd | path + s:len \ path pos wrd len | path + nip \ path pos len | path + n:1- \ path pos cix | path + ix @ \ path pos cix ix | path + n:= \ path pos bool | path + if \ path pos | path + \ We have a match! + true success ! \ path pos | path + 2drop \ | path + break \ | path + else \ path pos | path + 1 \ path pos len | path + s:- \ restpath | path + rdrop >r \ | restpath + then + then + ; + +: chkpath \ ix path -- \ ix path + nip \ path + >r \ | path + wrd @ \ wrd | path + ' chkokpath s:each \ | path + rdrop \ + success @ \ success + if \ + break \ + then + ; + +: chkwrd \ ix wrd -- \ ix wrd + nip \ wrd + s:uc \ wrdupper + "Word=" . dup . \ wrdupper + wrd ! \ + \ other word - clear paths + paths @ a:clear "" a:push drop \ + \ create path tree for this word + blks @ ' buildpaths a:each drop \ + \ check if word can be made from a path + false success ! \ + paths @ ' chkpath a:each drop \ + success @ \ success + "\t\t" . . cr \ + ; + +: app:main + chkwrds @ ' chkwrd a:each drop \ check if word can be made + bye + ; diff --git a/Task/ABC-Problem/APL/abc-problem.apl b/Task/ABC-Problem/APL/abc-problem.apl new file mode 100644 index 0000000000..e54bdd7296 --- /dev/null +++ b/Task/ABC-Problem/APL/abc-problem.apl @@ -0,0 +1 @@ +abc←{{0=⍴⍵:1 ⋄ 0=⍴h←⊃⍵:0 ⋄ ∇(t←1↓⍵)~¨⊃h:1 ⋄ ∇(⊂1↓h),t}⍸¨↓⍵∘.∊⍺} diff --git a/Task/ABC-Problem/AppleScript/abc-problem-1.applescript b/Task/ABC-Problem/AppleScript/abc-problem-1.applescript new file mode 100644 index 0000000000..efcbc606dc --- /dev/null +++ b/Task/ABC-Problem/AppleScript/abc-problem-1.applescript @@ -0,0 +1,28 @@ +set blocks to {"bo", "xk", "dq", "cp", "na", "gt", "re", "tg", "qd", "fs", ¬ + "jw", "hu", "vi", "an", "ob", "er", "fs", "ly", "pc", "zm"} + +canMakeWordWithBlocks("a", blocks) +canMakeWordWithBlocks("bark", blocks) +canMakeWordWithBlocks("book", blocks) +canMakeWordWithBlocks("treat", blocks) +canMakeWordWithBlocks("common", blocks) +canMakeWordWithBlocks("squad", blocks) +canMakeWordWithBlocks("confuse", blocks) + +on canMakeWordWithBlocks(theString, constBlocks) + copy constBlocks to theBlocks + if theString = "" then return true + set i to 1 + repeat + if i > (count theBlocks) then exit repeat + if character 1 of theString is in item i of theBlocks then + set item i of theBlocks to missing value + set theBlocks to strings of theBlocks + if canMakeWordWithBlocks(rest of characters of theString as string, theBlocks) then + return true + end if + end if + set i to i + 1 + end repeat + return false +end canMakeWordWithBlocks diff --git a/Task/ABC-Problem/AppleScript/abc-problem-2.applescript b/Task/ABC-Problem/AppleScript/abc-problem-2.applescript new file mode 100644 index 0000000000..1c22c533dd --- /dev/null +++ b/Task/ABC-Problem/AppleScript/abc-problem-2.applescript @@ -0,0 +1,242 @@ +use framework "Foundation" + +-- SPELLING BY BLOCK ---------------------------------------------------------- +on run + set blocks to map(chars, ¬ + |words|("BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM")) + + script blockSpelled + on |λ|(s) + intercalate(" -> ", ¬ + ap({my |quote|, compose({my |not|, my |null|, ¬ + curry(my spellWith)'s |λ|(blocks), my toUpper})}, {s})) + end |λ| + end script + + unlines(map(blockSpelled, ¬ + {"", "A", "BARK", "BoOK", "TrEAT", "COmMoN", "SQUAD", "conFUsE"})) +end run + +-- spellWith :: [(Char, Char)] -> String -> [[(Char, Char)]] +on spellWith(blocks, ccs) + if |null|(ccs) then + {{}} + else + set {c, cs} to uncons(ccs) + + script matchSequence + on |λ|(pair) + if elem(c, pair) then + + script pairUsed + on |λ|(xs) + {{pair} & xs} + end |λ| + end script + + concatMap(pairUsed, spellWith(|delete|(pair, blocks), cs)) + else + {} + end if + end |λ| + end script + + concatMap(matchSequence, blocks) + end if +end spellWith + + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- A list of functions applied to a list of arguments +-- (<*> | ap) :: [(a -> b)] -> [a] -> [b] +on ap(fs, xs) + set lngFs to length of fs + set lngXs to length of xs + set lst to {} + repeat with i from 1 to lngFs + tell mReturn(item i of fs) + repeat with j from 1 to lngXs + set end of lst to |λ|(contents of (item j of xs)) + end repeat + end tell + end repeat + return lst +end ap + +-- chars :: String -> [Char] +on chars(s) + characters of s +end chars + +-- compose :: [(a -> a)] -> (a -> a) +on compose(fs) + script + on |λ|(x) + script + on |λ|(a, f) + mReturn(f)'s |λ|(a) + end |λ| + end script + + foldr(result, x, fs) + end |λ| + end script +end compose + +-- concatMap :: (a -> [b]) -> [a] -> [b] +on concatMap(f, xs) + set lst to {} + set lng to length of xs + tell mReturn(f) + repeat with i from 1 to lng + set lst to (lst & |λ|(contents of item i of xs, i, xs)) + end repeat + end tell + return lst +end concatMap + +-- curry :: (Script|Handler) -> Script +on curry(f) + script + on |λ|(a) + script + on |λ|(b) + |λ|(a, b) of mReturn(f) + end |λ| + end script + end |λ| + end script +end curry + +-- delete :: Eq a => a -> [a] -> [a] +on |delete|(x, xs) + set mbIndex to elemIndex(x, xs) + set lng to length of xs + + if mbIndex is not missing value then + if lng > 1 then + if mbIndex = 1 then + items 2 thru -1 of xs + else if mbIndex = lng then + items 1 thru -2 of xs + else + tell xs to items 1 thru (mbIndex - 1) & ¬ + items (mbIndex + 1) thru -1 + end if + else + {} + end if + else + xs + end if +end |delete| + +-- elem :: Eq a => a -> [a] -> Bool +on elem(x, xs) + xs contains x +end elem + +-- elemIndex :: a -> [a] -> Maybe Int +on elemIndex(x, xs) + set lng to length of xs + repeat with i from 1 to lng + if x = (item i of xs) then return i + end repeat + return missing value +end elemIndex + +-- foldr :: (a -> b -> a) -> a -> [b] -> a +on foldr(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from lng to 1 by -1 + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldr + +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- null:: [a] -> Bool +on |null|(xs) + if class of xs is string then + xs = "" + else + xs = {} + end if +end |null| + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- not :: Bool -> Bool +on |not|(x) + not x +end |not| + +-- quote :: String -> String +on |quote|(x) + quoted form of x +end |quote| + +-- toUpper :: String -> String +on toUpper(str) + set ca to current application + ((ca's NSString's stringWithString:(str))'s ¬ + uppercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text +end toUpper + +-- uncons :: [a] -> Maybe (a, [a]) +on uncons(xs) + set lng to length of xs + if lng > 0 then + if class of xs is string then + set cs to text items of xs + {item 1 of cs, rest of cs} + else + {item 1 of xs, rest of xs} + end if + else + missing value + end if +end uncons + +-- unlines :: [String] -> String +on unlines(xs) + intercalate(linefeed, xs) +end unlines + +-- words :: String -> [String] +on |words|(s) + words of s +end |words| diff --git a/Task/ABC-Problem/AppleScript/abc-problem.applescript b/Task/ABC-Problem/AppleScript/abc-problem.applescript deleted file mode 100644 index 1c6047df28..0000000000 --- a/Task/ABC-Problem/AppleScript/abc-problem.applescript +++ /dev/null @@ -1,27 +0,0 @@ -set blocks to {"bo", "xk", "dq", "cp", "na", "gt", "re", "tg", "qd", "fs", "jw", "hu", "vi", "an", "ob", "er", "fs", "ly", "pc", "zm"} - -canMakeWordWithBlocks("a", blocks) -canMakeWordWithBlocks("bark", blocks) -canMakeWordWithBlocks("book", blocks) -canMakeWordWithBlocks("treat", blocks) -canMakeWordWithBlocks("common", blocks) -canMakeWordWithBlocks("squad", blocks) -canMakeWordWithBlocks("confuse", blocks) - -on canMakeWordWithBlocks(theString, constBlocks) - copy constBlocks to theBlocks - if theString = "" then return true - set i to 1 - repeat - if i > (count theBlocks) then exit repeat - if character 1 of theString is in item i of theBlocks then - set item i of theBlocks to missing value - set theBlocks to strings of theBlocks - if canMakeWordWithBlocks(rest of characters of theString as string, theBlocks) then - return true - end if - end if - set i to i + 1 - end repeat - return false -end canMakeWordWithBlocks diff --git a/Task/ABC-Problem/Astro/abc-problem.astro b/Task/ABC-Problem/Astro/abc-problem.astro new file mode 100644 index 0000000000..9844a0f97a --- /dev/null +++ b/Task/ABC-Problem/Astro/abc-problem.astro @@ -0,0 +1,12 @@ +fun abc(s, list): + return true if s.empty + for i in [:list.size]: + return any([abc(s[:!1], delete(val list, i))]) ... + if s[!0] in list[i] else true + false + +let test = ["A", "BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"] +let list = ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW", +"HU","VI","AN","OB","ER","FS","LY","PC","ZM"] +for s in test: + print "$:.-8(s) | $(abc(s, list))" diff --git a/Task/ABC-Problem/BASIC/abc-problem.basic b/Task/ABC-Problem/BASIC/abc-problem-1.basic similarity index 100% rename from Task/ABC-Problem/BASIC/abc-problem.basic rename to Task/ABC-Problem/BASIC/abc-problem-1.basic diff --git a/Task/ABC-Problem/BASIC/abc-problem-2.basic b/Task/ABC-Problem/BASIC/abc-problem-2.basic new file mode 100644 index 0000000000..4564eeafae --- /dev/null +++ b/Task/ABC-Problem/BASIC/abc-problem-2.basic @@ -0,0 +1,25 @@ +10 W$ = "A" : GOSUB 100 +20 W$ = "BARK" : GOSUB 100 +30 W$ = "BOOK" : GOSUB 100 +40 W$ = "TREAT" : GOSUB 100 +50 W$ = "COMMON" : GOSUB 100 +60 W$ = "SQUAD" : GOSUB 100 +70 W$ = "CONFUSE" : GOSUB 100 +80 END +90 REM ******************************** +100 B$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM" +110 FOR I=1 TO LEN(W$) +120 BL = LEN(B$) +130 FOR J=1 TO BL STEP 2 +140 C$=MID$(B$,J,1): D$=MID$(B$,J+1,1) +150 X$=MID$(W$,I,1) +160 IF C$<>X$ AND D$<>X$ THEN GOTO 190 +170 B$ = LEFT$(B$,J-1)+RIGHT$(B$,BL-J-1) +180 GOTO 210 +190 NEXT J +200 IF J>BL-1 THEN GOTO 240 +210 NEXT I +220 PRINT W$" -> YES" +230 RETURN +240 PRINT W$" -> NO" +250 RETURN diff --git a/Task/ABC-Problem/BASIC/abc-problem-3.basic b/Task/ABC-Problem/BASIC/abc-problem-3.basic new file mode 100644 index 0000000000..b76ddfbd9e --- /dev/null +++ b/Task/ABC-Problem/BASIC/abc-problem-3.basic @@ -0,0 +1,11 @@ + 10 LET B$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM" + 20 INPUT W$ + 30 FOR I=1 TO LEN W$ + 40 FOR J=1 TO LEN B$ STEP 2 + 50 IF B$(J)<>W$(I) AND B$(J+1)<>W$(I) THEN GOTO 100 + 60 LET B$=B$( TO J-1)+B$(J+2 TO ) + 70 NEXT I + 80 PRINT "YES" + 90 STOP +100 NEXT J +110 PRINT "NO" diff --git a/Task/ABC-Problem/BaCon/abc-problem.bacon b/Task/ABC-Problem/BaCon/abc-problem.bacon new file mode 100644 index 0000000000..b9fc9feee5 --- /dev/null +++ b/Task/ABC-Problem/BaCon/abc-problem.bacon @@ -0,0 +1,24 @@ +CONST info$ = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" + +DATA "A", "BARK", "BOOK", "TREAT", "Common", "Squad", "Confuse" + +WHILE TRUE + READ word$ + + IF NOT(LEN(word$)) THEN BREAK + + block$ = info$ + + count = AMOUNT(block$) + + FOR y = 1 TO LEN(word$) + FOR x = 1 TO AMOUNT(block$) + IF TALLY(TOKEN$(block$, x), MID$(UCASE$(word$), y, 1)) THEN + block$ = DEL$(block$, x) + BREAK + END IF + NEXT + NEXT + + PRINT word$, IIF$(LEN(word$) = count-AMOUNT(block$), "True", "False") FORMAT "%-10s: %s\n" +WEND diff --git a/Task/ABC-Problem/Clojure/abc-problem.clj b/Task/ABC-Problem/Clojure/abc-problem.clj index 00b43386e8..8f0146704c 100644 --- a/Task/ABC-Problem/Clojure/abc-problem.clj +++ b/Task/ABC-Problem/Clojure/abc-problem.clj @@ -10,7 +10,7 @@ (defn abc "return lazy sequence of solutions (i.e. block lists)" [blocks [c & cs]] - (if-some c + (if (some? c) (for [b blocks :when (some #(= c %) b) bs (abc (omit blocks b) cs)] (cons b bs)) diff --git a/Task/ABC-Problem/Component-Pascal/abc-problem.component b/Task/ABC-Problem/Component-Pascal/abc-problem.component new file mode 100644 index 0000000000..1f278709b7 --- /dev/null +++ b/Task/ABC-Problem/Component-Pascal/abc-problem.component @@ -0,0 +1,84 @@ +MODULE ABCProblem; +IMPORT + StdLog, DevCommanders, TextMappers; +CONST + notfound = -1; +TYPE + String = ARRAY 3 OF CHAR; +VAR + 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; + +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; + +PROCEDURE CanMakeWord*; +VAR + 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 +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"; + +END ABCProblem. diff --git a/Task/ABC-Problem/Elena/abc-problem.elena b/Task/ABC-Problem/Elena/abc-problem.elena index c44f073afd..d23e1ea99a 100644 --- a/Task/ABC-Problem/Elena/abc-problem.elena +++ b/Task/ABC-Problem/Elena/abc-problem.elena @@ -1,37 +1,37 @@ -#import system. -#import system'routines. -#import system'collections. -#import extensions. -#import extensions'routines. +import system'routines. +import system'collections. +import extensions. +import extensions'routines. -#class(extension)op +extension op { - #method canMakeWord &from:blocks + canMakeWordFrom:blocks [ - #var list := ArrayList new:blocks. + var list := ArrayList new:blocks. - ^ $nil == self literal upperCase seek &each:ch + ^ $nil == self literal; upperCase; seekEach(:ch) [ - #var index := list indexOf:(word [ word indexOf:ch &at:0 != -1 ] asComparer). + var index := list indexOfElement + ((:word)(word indexOf:ch at:0 != -1) asComparator). - (index>=0) - ? [ list remove &at:index. ^ false. ] - ! [ ^ true. ]. - ]. + if (index>=0) + [ list remove at:index. ^ false ]; + [ ^ true ] + ] ] } -#symbol program = +program = [ - #var blocks := ("BO", "XK", "DQ", "CP", "NA", + var blocks := ("BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"). - #var words := ("", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse"). + var words := ("", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse"). - words run &each:word + words forEach(:word) [ - console writeLine:"can make '":word:"' : ":(word canMakeWord &from: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.elixir index 0d6c15c7bf..8cea29bada 100644 --- a/Task/ABC-Problem/Elixir/abc-problem.elixir +++ b/Task/ABC-Problem/Elixir/abc-problem.elixir @@ -1,12 +1,12 @@ defmodule ABC do def can_make_word(word, avail) do - can_make_word(String.upcase(word) |> to_char_list, avail, []) + can_make_word(String.upcase(word) |> to_charlist, avail, []) end defp can_make_word([], _, _), do: true defp can_make_word(_, [], _), do: false defp can_make_word([l|tail], [b|rest], tried) do - (Enum.member?(b,l) and can_make_word(tail, rest++tried, [])) + (l in b and can_make_word(tail, rest++tried, [])) or can_make_word([l|tail], rest, [b|tried]) end end diff --git a/Task/ABC-Problem/Gambas/abc-problem.gambas b/Task/ABC-Problem/Gambas/abc-problem.gambas new file mode 100644 index 0000000000..194e524e13 --- /dev/null +++ b/Task/ABC-Problem/Gambas/abc-problem.gambas @@ -0,0 +1,28 @@ +Public Sub Main() +Dim sCheck As String[] = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"] +Dim sBlock As String[] = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"] +Dim sList As New String[] +Dim siCount, siLoop As Short +Dim sTemp, sAnswer As String + +For Each sTemp In sCheck + sAnswer = "" + sList = sBlock.Copy() + For siCount = 1 To Len(sTemp) + For siLoop = 0 To sList.Max + If InStr(sList[siLoop], Mid(sTemp, siCount, 1)) Then + sList.Extract(siLoop, 1) + sAnswer &= Mid(sTemp, siCount, 1) + Break + Endif + Next + Next + + If sAnswer = sTemp Then + Print sTemp & " - True" + Else + Print sTemp & " - False" + End If +Next + +End diff --git a/Task/ABC-Problem/Haskell/abc-problem.hs b/Task/ABC-Problem/Haskell/abc-problem-1.hs similarity index 100% rename from Task/ABC-Problem/Haskell/abc-problem.hs rename to Task/ABC-Problem/Haskell/abc-problem-1.hs diff --git a/Task/ABC-Problem/Haskell/abc-problem-2.hs b/Task/ABC-Problem/Haskell/abc-problem-2.hs new file mode 100644 index 0000000000..a7c5dd40c0 --- /dev/null +++ b/Task/ABC-Problem/Haskell/abc-problem-2.hs @@ -0,0 +1,22 @@ +import Data.List (delete) +import Data.Char (toUpper) + +-- Any block sequences found +spellWith :: [String] -> String -> [[String]] +spellWith _ [] = [[]] +spellWith blocks (x:xs) = + foldMap + (\b -> + if x `elem` b + then foldMap (return . (b :)) (spellWith (delete b blocks) xs) + else []) + blocks + +blocks :: [String] +blocks = words "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" + +main :: IO () +main = + mapM_ + (print . ((,) <*>) (not . null . spellWith blocks . (toUpper <$>))) + ["", "A", "BARK", "BoOK", "TrEAT", "COmMoN", "SQUAD", "conFUsE"] diff --git a/Task/ABC-Problem/Java/abc-problem.java b/Task/ABC-Problem/Java/abc-problem.java index 8cd74ed0ba..c8c35a042b 100644 --- a/Task/ABC-Problem/Java/abc-problem.java +++ b/Task/ABC-Problem/Java/abc-problem.java @@ -1,44 +1,36 @@ import java.util.Arrays; +import java.util.Collections; +import java.util.List; -public class ABC{ - private static void swap(int i, int j, Object... arr){ - Object tmp = arr[i]; - arr[i] = arr[j]; - arr[j] = tmp; - } - - public static boolean canMakeWord(String word, String... blocks) { - if(word.length() == 0) - return true; - - char c = Character.toUpperCase(word.charAt(0)); - for(int i = 0; i < blocks.length; i++) { - String b = blocks[i]; - if(Character.toUpperCase(b.charAt(0)) != c && Character.toUpperCase(b.charAt(1)) != c) - continue; - swap(0, i, blocks); - if(canMakeWord(word.substring(1), Arrays.copyOfRange(blocks, 1, blocks.length))) - return true; - swap(0, i, blocks); - } - - return false; - } - - public static void main(String[] args){ - String[] blocks = {"BO", "XK", "DQ", "CP", "NA", - "GT", "RE", "TG", "QD", "FS", - "JW", "HU", "VI", "AN", "OB", - "ER", "FS", "LY", "PC", "ZM"}; +public class ABC { - System.out.println("\"\": " + canMakeWord("", blocks)); - System.out.println("A: " + canMakeWord("A", blocks)); - System.out.println("BARK: " + canMakeWord("BARK", blocks)); - System.out.println("book: " + canMakeWord("book", blocks)); - System.out.println("treat: " + canMakeWord("treat", blocks)); - System.out.println("COMMON: " + canMakeWord("COMMON", blocks)); - System.out.println("SQuAd: " + canMakeWord("SQuAd", blocks)); - System.out.println("CONFUSE: " + canMakeWord("CONFUSE", blocks)); - - } + public static void main(String[] args) { + List blocks = Arrays.asList( + "BO", "XK", "DQ", "CP", "NA", + "GT", "RE", "TG", "QD", "FS", + "JW", "HU", "VI", "AN", "OB", + "ER", "FS", "LY", "PC", "ZM"); + + for (String word : Arrays.asList("", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE")) { + System.out.printf("%s: %s%n", word.isEmpty() ? "\"\"" : word, canMakeWord(word, blocks)); + } + } + + public static boolean canMakeWord(String word, List blocks) { + if (word.isEmpty()) + return true; + + char c = word.charAt(0); + for (int i = 0; i < blocks.size(); i++) { + String b = blocks.get(i); + if (b.charAt(0) != c && b.charAt(1) != c) + continue; + Collections.swap(blocks, 0, i); + if (canMakeWord(word.substring(1), blocks.subList(1, blocks.size()))) + return true; + Collections.swap(blocks, 0, i); + } + + return false; + } } diff --git a/Task/ABC-Problem/JavaScript/abc-problem-5.js b/Task/ABC-Problem/JavaScript/abc-problem-5.js new file mode 100644 index 0000000000..1c1ad7afcc --- /dev/null +++ b/Task/ABC-Problem/JavaScript/abc-problem-5.js @@ -0,0 +1,97 @@ +(() => { + 'use strict'; + + // ABC BLOCKS ------------------------------------------------------------- + + // spellWith :: [(Char, Char)] -> [Char] -> [[(Char, Char)]] + const spellWith = (blocks, wordChars) => + (isNull(wordChars)) ? [ + [] + ] : + (() => { + const [x, xs] = uncons(wordChars); + return concatMap( + b => elem(x, b) ? concatMap( + bs => [cons(b, bs)], + spellWith( + deleteBy( + (p, q) => (p[0] === q[0]) && (p[1] === q[1]), + b, blocks + ), + xs + ) + ) : [], + blocks + ); + })(); + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // compose :: [(a -> a)] -> (a -> a) + const compose = fs => x => fs.reduceRight((a, f) => f(a), x); + + // concatMap :: (a -> [b]) -> [a] -> [b] + const concatMap = (f, xs) => [].concat.apply([], xs.map(f)); + + // cons :: a -> [a] -> [a] + const cons = (x, xs) => [x].concat(xs); + + // curry :: Function -> Function + const curry = (f, ...args) => { + const go = xs => xs.length >= f.length ? (f.apply(null, xs)) : + function () { + return go(xs.concat([].slice.apply(arguments))); + }; + return go([].slice.call(args, 1)); + }; + + // deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a] + const deleteBy = (f, x, xs) => + xs.length > 0 ? ( + f(x, xs[0]) ? ( + xs.slice(1) + ) : [xs[0]].concat(deleteBy(f, x, xs.slice(1))) + ) : []; + + // elem :: Eq a => a -> [a] -> Bool + const elem = (x, xs) => xs.indexOf(x) !== -1; + + // isNull :: [a] -> Bool + const isNull = xs => (xs instanceof Array) ? xs.length < 1 : undefined; + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // not :: Bool -> Bool + const not = b => !b; + + // show :: a -> String + const show = x => JSON.stringify(x); //, null, 2); + + // stringChars :: String -> [Char] + const stringChars = s => s.split(''); + + // toUpper :: Text -> Text + const toUpper = s => s.toUpperCase(); + + // uncons :: [a] -> Maybe (a, [a]) + const uncons = xs => xs.length ? [xs[0], xs.slice(1)] : undefined; + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + // words :: String -> [String] + const words = s => s.split(/\s+/); + + // TEST ------------------------------------------------------------------- + // blocks :: [(Char, Char)] + const blocks = words( + "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" + ); + + return unlines(map( + x => show([x, compose( + [not, isNull, curry(spellWith)(blocks), stringChars, toUpper] + )(x)]), ["", "A", "BARK", "BoOK", "TrEAT", "COmMoN", "SQUAD", "conFUsE"] + )); +})(); diff --git a/Task/ABC-Problem/jq/abc-problem-1.jq b/Task/ABC-Problem/Jq/abc-problem-1.jq similarity index 100% rename from Task/ABC-Problem/jq/abc-problem-1.jq rename to Task/ABC-Problem/Jq/abc-problem-1.jq diff --git a/Task/ABC-Problem/jq/abc-problem-2.jq b/Task/ABC-Problem/Jq/abc-problem-2.jq similarity index 100% rename from Task/ABC-Problem/jq/abc-problem-2.jq rename to Task/ABC-Problem/Jq/abc-problem-2.jq diff --git a/Task/ABC-Problem/Kotlin/abc-problem.kotlin b/Task/ABC-Problem/Kotlin/abc-problem.kotlin index d33d1e9ee6..9a20aca7a5 100644 --- a/Task/ABC-Problem/Kotlin/abc-problem.kotlin +++ b/Task/ABC-Problem/Kotlin/abc-problem.kotlin @@ -1,5 +1,3 @@ -package abc - object ABC_block_checker { fun run() { val blocks = arrayOf("BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", @@ -17,7 +15,7 @@ object ABC_block_checker { } private fun Array.canMakeWord(word: String): Boolean { - if (word.length == 0) + if (word.isEmpty()) return true val c = Character.toUpperCase(word.first()) diff --git a/Task/ABC-Problem/Nim/abc-problem.nim b/Task/ABC-Problem/Nim/abc-problem.nim index 7fbc590119..f9dd2b907e 100644 --- a/Task/ABC-Problem/Nim/abc-problem.nim +++ b/Task/ABC-Problem/Nim/abc-problem.nim @@ -1,33 +1,24 @@ -from strutils import contains, format, toUpper +from strutils import toUpperAscii, contains, format from sequtils import delete -proc canMakeWord(s: string): bool = +proc makeWord(s: string): bool = var abcs = @["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"] - matched = newSeq[string]() if s.len > abcs.len: return false - for i in 0 .. s.len - 1: - var - letter = s[i].toUpper - n = 0 - for abc in abcs: - if contains(abc, letter): - delete(abcs, n, n) - matched = matched & abc - break - else: - inc(n) + for ch in s.toUpperAscii.items: + block outer: + for i, abc in abcs.pairs: + if abc.contains(ch): + abcs.delete(i) + break outer + return false + return true - if matched.len == s.len: - return true - else: - return false - -var words = @["A", "bArK", "BOOK", "treat", "common", "sQuAd", "CONFUSE"] +let words = @["A", "bArK", "BOOK", "treat", "common", "sQuAd", "CONFUSE"] for word in words: - echo format("Can the blocks make the word \"$1\"? $2", word, - (if canMakeWord(word): "yes" else: "no")) + echo format("""Can the blocks make the word "$1"? $2 """, word, + if makeWord(word): "yes" else: "no") diff --git a/Task/ABC-Problem/PL-I/abc-problem-1.pli b/Task/ABC-Problem/PL-I/abc-problem-1.pli index 3592b2aec8..28025005d5 100644 --- a/Task/ABC-Problem/PL-I/abc-problem-1.pli +++ b/Task/ABC-Problem/PL-I/abc-problem-1.pli @@ -11,7 +11,8 @@ ABC: procedure options (main); /* 12 January 2014 */ do word = 'A', 'BARK', 'BOOK', 'TREAT', 'COMMON', 'SQuAd', 'CONFUSE'; flag = true; tblocks = blocks; - do i = 1 to length(word); + do i = 1 to length(word) + while(flag = true); ch = substr(word, i, 1); k = index(tblocks, uppercase(ch)); if k = 0 then diff --git a/Task/ABC-Problem/PureBasic/abc-problem-1.purebasic b/Task/ABC-Problem/PureBasic/abc-problem-1.purebasic index e05892c1a0..640f6e1149 100644 --- a/Task/ABC-Problem/PureBasic/abc-problem-1.purebasic +++ b/Task/ABC-Problem/PureBasic/abc-problem-1.purebasic @@ -2,9 +2,9 @@ EnableExplicit #LETTERS = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM " Procedure.s can_make_word(word.s) - Define.s letters = #LETTERS, buffer - Define.i index1, index2 - Define.b match + Define letters.s = #LETTERS, buffer.s + Define index1.i, index2.i + Define match.b For index1=1 To Len(word) index2=1 : match=#False Repeat diff --git a/Task/ABC-Problem/PureBasic/abc-problem-2.purebasic b/Task/ABC-Problem/PureBasic/abc-problem-2.purebasic index cdda3b84bb..5cfb7569f2 100644 --- a/Task/ABC-Problem/PureBasic/abc-problem-2.purebasic +++ b/Task/ABC-Problem/PureBasic/abc-problem-2.purebasic @@ -1,4 +1,3 @@ -Define.i #LETTERS = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM " Macro test(t) diff --git a/Task/ABC-Problem/Python/abc-problem-1.py b/Task/ABC-Problem/Python/abc-problem-1.py index 355da9cc93..6490b5fa75 100644 --- a/Task/ABC-Problem/Python/abc-problem-1.py +++ b/Task/ABC-Problem/Python/abc-problem-1.py @@ -1,3 +1,8 @@ +''' +Note that this code is broken, e.g., it won't work when +blocks = [("A", "B"), ("A","C")] and the word is "AB", where the answer +should be True, but the code returns False. +''' blocks = [("B", "O"), ("X", "K"), ("D", "Q"), diff --git a/Task/ABC-Problem/REXX/abc-problem-1.rexx b/Task/ABC-Problem/REXX/abc-problem-1.rexx index b5152e475b..b6ff22c338 100644 --- a/Task/ABC-Problem/REXX/abc-problem-1.rexx +++ b/Task/ABC-Problem/REXX/abc-problem-1.rexx @@ -1,24 +1,21 @@ -/*REXX program determines if words can be spelt from a pool of toy blocks. */ -list= 'A bark bOOk treat common squaD conFuse' /*words can be in any case. */ -blocks= 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM' - do k=1 for words(list) /*traipse through a list of seven words*/ - call spell word(list,k) /*display if word can be spelt (or not)*/ - end /*k*/ /* [↑] tests each word in the list. */ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -spell: procedure expose blocks; arg x; p.=0 /*uppercase word to be spelt. */ -parse upper var blocks theBlocks; L=length(x) /*uppercase the block letters.*/ - /* [↓] try to spell the word.*/ - do try=1 for L; z=theBlocks /*use a fresh copy of Z blocks*/ - do n=1 for L; y=substr(x,n,1) /*attempt another block letter*/ - p.n=pos(y,z,1+p.n); if p.n==0 then iterate try /*not found? Try again.*/ - z=overlay(' ',z,p.n) /*mutate block ───► a onesy.*/ - do k=1 for words(blocks) /*scrub block pool (not 1s). */ - if length(word(z,k))==1 then z=delword(z,k,1) /*single char? Delete.*/ - end /*k*/ /* [↑] elide any onesy block.*/ - if n==L then leave try /*was the last letter spelt? */ - end /*n*/ /* [↑] end of a block attempt*/ - end /*try*/ /* [↑] end of "TRY" permute. */ - -say right(arg(1),30) right(word("can't can", (n==L)+1), 6) 'be spelt.' -return +/*REXX pgm finds if words can be spelt from a pool of toy blocks (each having 2 letters)*/ +list= 'A bark bOOk treat common squaD conFuse' /*words can be: upper/lower/mixed case*/ +blocks= 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM' + do k=1 for words(list) /*traipse through a list of some words.*/ + call spell word(list, k) /*display if word can be spelt (or not)*/ + end /*k*/ /* [↑] tests each word in the list. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +spell: procedure expose blocks; arg x /*ARG uppercases the word to be spelt.*/ + L=length(x); @.=0 /*get length of the word to be spelt. */ + do try=1 for L; z=blocks; upper z /*use a fresh copy of the "Z" blocks.*/ + do n=1 for L; y=substr(x, n, 1) /*attempt another letter in the word. */ + @.n=pos(y, z, 1 + @.n); if @.n==0 then leave /*not found? Try again*/ + z=overlay(' ', z, @.n) /*mutate the toy block ───► a onesy. */ + do q=1 for words(z); if length(word(z, q))==1 then z=delword(z, q, 1) + end /*q*/ /* [↑] elide any existing onesy block.*/ + if n==L then leave try /*was last letter used in the spelling?*/ + end /*n*/ /* [↑] end of a toy block usage. */ + end /*try*/ /* [↑] end of a "TRY" permute. */ + say right(arg(1), 30) right( word( "can't can", (n==L) +1), 6) 'be spelt.' + return diff --git a/Task/ABC-Problem/Simula/abc-problem.simula b/Task/ABC-Problem/Simula/abc-problem.simula new file mode 100644 index 0000000000..a633b223b6 --- /dev/null +++ b/Task/ABC-Problem/Simula/abc-problem.simula @@ -0,0 +1,96 @@ +COMMENT ABC PROBLEM; +BEGIN + + CLASS BLOCK(CH1, CH2); CHARACTER CH1, CH2; + BEGIN + BOOLEAN USED; + END; + + CLASS GAME(WORD, POSSIBLE); TEXT WORD; BOOLEAN POSSIBLE;; + + BOOLEAN PROCEDURE CANMAKEWORD(WORD); TEXT WORD; + BEGIN + INTEGER I, NUMBLOCKS; + BOOLEAN ALLPOSSIBLE, FOUND; + NUMBLOCKS := UPPERBOUND(BLOCKS, 1); + FOR I := 1 STEP 1 UNTIL NUMBLOCKS DO + BLOCKS(I).USED := FALSE; + ALLPOSSIBLE := TRUE; + + WORD.SETPOS(1); + WHILE ALLPOSSIBLE AND WORD.MORE DO + BEGIN + CHARACTER WORDCHAR; + WORDCHAR := WORD.GETCHAR; + FOUND := FALSE; + FOR I := 1 STEP 1 UNTIL NUMBLOCKS DO + BEGIN + INSPECT BLOCKS(I) DO + BEGIN + IF (WORDCHAR = CH1 OR WORDCHAR = CH2) AND NOT USED THEN + BEGIN + USED := FOUND := TRUE; + GOTO L; + END; + END; + END; + L: + IF NOT FOUND THEN + ALLPOSSIBLE := FALSE; + END; + CANMAKEWORD := ALLPOSSIBLE; + END CANMAKEWORD; + + REF(BLOCK) ARRAY BLOCKS(1:20); + REF(GAME) ARRAY GAMES(1:7); + TEXT WORD; + BEGIN + INTEGER I; + I := I+1; BLOCKS(I) :- NEW BLOCK('B', 'O'); + I := I+1; BLOCKS(I) :- NEW BLOCK('X', 'K'); + I := I+1; BLOCKS(I) :- NEW BLOCK('D', 'Q'); + I := I+1; BLOCKS(I) :- NEW BLOCK('C', 'P'); + I := I+1; BLOCKS(I) :- NEW BLOCK('N', 'A'); + I := I+1; BLOCKS(I) :- NEW BLOCK('G', 'T'); + I := I+1; BLOCKS(I) :- NEW BLOCK('R', 'E'); + I := I+1; BLOCKS(I) :- NEW BLOCK('T', 'G'); + I := I+1; BLOCKS(I) :- NEW BLOCK('Q', 'D'); + I := I+1; BLOCKS(I) :- NEW BLOCK('F', 'S'); + I := I+1; BLOCKS(I) :- NEW BLOCK('J', 'W'); + I := I+1; BLOCKS(I) :- NEW BLOCK('H', 'U'); + I := I+1; BLOCKS(I) :- NEW BLOCK('V', 'I'); + I := I+1; BLOCKS(I) :- NEW BLOCK('A', 'N'); + I := I+1; BLOCKS(I) :- NEW BLOCK('O', 'B'); + I := I+1; BLOCKS(I) :- NEW BLOCK('E', 'R'); + I := I+1; BLOCKS(I) :- NEW BLOCK('F', 'S'); + I := I+1; BLOCKS(I) :- NEW BLOCK('L', 'Y'); + I := I+1; BLOCKS(I) :- NEW BLOCK('P', 'C'); + I := I+1; BLOCKS(I) :- NEW BLOCK('Z', 'M'); + END; + BEGIN + INTEGER N, I; BOOLEAN ANSWER; + N := N+1; GAMES(N) :- NEW GAME("A", TRUE); + N := N+1; GAMES(N) :- NEW GAME("BARK", TRUE); + N := N+1; GAMES(N) :- NEW GAME("BOOK", FALSE); + N := N+1; GAMES(N) :- NEW GAME("TREAT", TRUE); + N := N+1; GAMES(N) :- NEW GAME("COMMON", FALSE); + N := N+1; GAMES(N) :- NEW GAME("SQUAD", TRUE); + N := N+1; GAMES(N) :- NEW GAME("CONFUSE", TRUE); + FOR I := 1 STEP 1 UNTIL N DO + BEGIN + INSPECT GAMES(I) DO + BEGIN + OUTTEXT(WORD); + OUTTEXT(" => "); + ANSWER := CANMAKEWORD(WORD); + OUTCHAR(IF ANSWER THEN 'T' ELSE 'F'); + IF ANSWER EQV POSSIBLE + THEN OUTTEXT(" OK") + ELSE OUTTEXT(" ------------- WRONG!"); + OUTIMAGE; + END; + END; + END; + + +END. diff --git a/Task/ABC-Problem/Swift/abc-problem.swift b/Task/ABC-Problem/Swift/abc-problem-1.swift similarity index 100% rename from Task/ABC-Problem/Swift/abc-problem.swift rename to Task/ABC-Problem/Swift/abc-problem-1.swift diff --git a/Task/ABC-Problem/Swift/abc-problem-2.swift b/Task/ABC-Problem/Swift/abc-problem-2.swift new file mode 100644 index 0000000000..026a22d936 --- /dev/null +++ b/Task/ABC-Problem/Swift/abc-problem-2.swift @@ -0,0 +1,22 @@ +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 +} + +let words = ["a", "bARK", "boOK", "TreAt", "CoMmon", "SquAd", "CONFUse"] + +words.forEach { print($0, canMake(word: $0)) } diff --git a/Task/ABC-Problem/Zkl/abc-problem.zkl b/Task/ABC-Problem/Zkl/abc-problem.zkl new file mode 100644 index 0000000000..66da4854fc --- /dev/null +++ b/Task/ABC-Problem/Zkl/abc-problem.zkl @@ -0,0 +1,19 @@ +var blocks=T("BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", + "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 + } + False; // out of blocks but not out of word + }(blocks.copy(),word.toUpper()) +} + +foreach word in (T("","A","BarK","BOOK","TREAT","COMMON","SQUAD","Confuse","abba")){ + can_make_word(word).println(": ",word); +} diff --git a/Task/AKS-test-for-primes/C-sharp/aks-test-for-primes.cs b/Task/AKS-test-for-primes/C-sharp/aks-test-for-primes.cs deleted file mode 100644 index 80b0711b7c..0000000000 --- a/Task/AKS-test-for-primes/C-sharp/aks-test-for-primes.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; - public class AksTest - { - static long[] c = new long[100]; - - static void Main(string[] args) - { - for (int n = 0; n < 10; n++) { - coef(n); - Console.Write("(x-1)^" + n + " = "); - show(n); - Console.WriteLine(""); - } - Console.Write("Primes:"); - for (int n = 1; n <= 63; n++) - if (is_prime(n)) - Console.Write(n + " "); - - Console.WriteLine('\n'); - Console.ReadLine(); - } - - static void coef(int n) - { - int i, j; - - if (n < 0 || n > 63) System.Environment.Exit(0);// gracefully deal with range issue - - for (c[i = 0] = 1L; i < n; c[0] = -c[0], i++) - for (c[1 + (j = i)] = 1L; j > 0; j--) - c[j] = c[j - 1] - c[j]; - } - - static bool is_prime(int n) - { - int i; - - coef(n); - c[0] += 1; - c[i = n] -= 1; - - while (i-- != 0 && (c[i] % n) == 0) ; - - return i < 0; - } - - static void show(int n) - { - do { - Console.Write("+" + c[n] + "x^" + n); - }while (n-- != 0); - } - } diff --git a/Task/AKS-test-for-primes/Java/aks-test-for-primes.java b/Task/AKS-test-for-primes/Java/aks-test-for-primes.java index b7ea1a286b..4676f0db8f 100644 --- a/Task/AKS-test-for-primes/Java/aks-test-for-primes.java +++ b/Task/AKS-test-for-primes/Java/aks-test-for-primes.java @@ -1,52 +1,45 @@ -public class AksTest -{ - static Long[] c = new Long[100]; - - public static void main(String[] args) - { - for (int n = 0; n < 10; n++) { - coef(n); - System.out.print("(x-1)^" + n + " = "); - show(n); - System.out.println(""); - } - - System.out.print("Primes:"); - for (int n = 1; n <= 63; n++) - if (is_prime(n)) - System.out.printf(" %d", n); - - System.out.println('\n'); - } - - static void coef(int n) - { - int i, j; - - if (n < 0 || n > 63) System.exit(0); // gracefully deal with range issue - - for (c[i=0] = 1l; i < n; c[0] = -c[0], i++) - for (c[1 + (j=i)] = 1l; j > 0; j--) - c[j] = c[j-1] - c[j]; - } - - static boolean is_prime(int n) - { - int i; - - coef(n); - c[0] += 1; - c[i=n] -= 1; - - while (i-- != 0 && (c[i] % n) == 0); - - return i < 0; - } - - static void show(int n) - { - do { - System.out.print("+" + c[n] + "x^"+ n); - }while (n-- != 0); - } +public class AksTest { + private static final long[] c = new long[64]; + + public static void main(String[] args) { + for (int n = 0; n < 10; n++) { + coeff(n); + show(n); + } + + System.out.print("Primes:"); + for (int n = 1; n < c.length; n++) + if (isPrime(n)) + System.out.printf(" %d", n); + + System.out.println(); + } + + static void coeff(int n) { + c[0] = 1; + for (int i = 0; i < n; c[0] = -c[0], i++) { + c[1 + i] = 1; + for (int j = i; j > 0; j--) + c[j] = c[j - 1] - c[j]; + } + } + + static boolean isPrime(int n) { + coeff(n); + c[0]++; + c[n]--; + + int i = n; + while (i-- != 0 && c[i] % n == 0) + continue; + return i < 0; + } + + static void show(int n) { + System.out.print("(x-1)^" + n + " ="); + for (int i = n; i >= 0; i--) { + System.out.print(" + " + c[i] + "x^" + i); + } + System.out.println(); + } } diff --git a/Task/AKS-test-for-primes/jq/aks-test-for-primes-1.jq b/Task/AKS-test-for-primes/Jq/aks-test-for-primes-1.jq similarity index 100% rename from Task/AKS-test-for-primes/jq/aks-test-for-primes-1.jq rename to Task/AKS-test-for-primes/Jq/aks-test-for-primes-1.jq diff --git a/Task/AKS-test-for-primes/jq/aks-test-for-primes-2.jq b/Task/AKS-test-for-primes/Jq/aks-test-for-primes-2.jq similarity index 100% rename from Task/AKS-test-for-primes/jq/aks-test-for-primes-2.jq rename to Task/AKS-test-for-primes/Jq/aks-test-for-primes-2.jq diff --git a/Task/AKS-test-for-primes/jq/aks-test-for-primes-3.jq b/Task/AKS-test-for-primes/Jq/aks-test-for-primes-3.jq similarity index 100% rename from Task/AKS-test-for-primes/jq/aks-test-for-primes-3.jq rename to Task/AKS-test-for-primes/Jq/aks-test-for-primes-3.jq diff --git a/Task/AKS-test-for-primes/jq/aks-test-for-primes-4.jq b/Task/AKS-test-for-primes/Jq/aks-test-for-primes-4.jq similarity index 100% rename from Task/AKS-test-for-primes/jq/aks-test-for-primes-4.jq rename to Task/AKS-test-for-primes/Jq/aks-test-for-primes-4.jq diff --git a/Task/AKS-test-for-primes/jq/aks-test-for-primes-5.jq b/Task/AKS-test-for-primes/Jq/aks-test-for-primes-5.jq similarity index 100% rename from Task/AKS-test-for-primes/jq/aks-test-for-primes-5.jq rename to Task/AKS-test-for-primes/Jq/aks-test-for-primes-5.jq diff --git a/Task/AKS-test-for-primes/jq/aks-test-for-primes-6.jq b/Task/AKS-test-for-primes/Jq/aks-test-for-primes-6.jq similarity index 100% rename from Task/AKS-test-for-primes/jq/aks-test-for-primes-6.jq rename to Task/AKS-test-for-primes/Jq/aks-test-for-primes-6.jq diff --git a/Task/AKS-test-for-primes/jq/aks-test-for-primes-7.jq b/Task/AKS-test-for-primes/Jq/aks-test-for-primes-7.jq similarity index 100% rename from Task/AKS-test-for-primes/jq/aks-test-for-primes-7.jq rename to Task/AKS-test-for-primes/Jq/aks-test-for-primes-7.jq diff --git a/Task/AKS-test-for-primes/jq/aks-test-for-primes-8.jq b/Task/AKS-test-for-primes/Jq/aks-test-for-primes-8.jq similarity index 100% rename from Task/AKS-test-for-primes/jq/aks-test-for-primes-8.jq rename to Task/AKS-test-for-primes/Jq/aks-test-for-primes-8.jq diff --git a/Task/AKS-test-for-primes/jq/aks-test-for-primes-9.jq b/Task/AKS-test-for-primes/Jq/aks-test-for-primes-9.jq similarity index 100% rename from Task/AKS-test-for-primes/jq/aks-test-for-primes-9.jq rename to Task/AKS-test-for-primes/Jq/aks-test-for-primes-9.jq 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.kotlin new file mode 100644 index 0000000000..541af7f852 --- /dev/null +++ b/Task/AKS-test-for-primes/Kotlin/aks-test-for-primes.kotlin @@ -0,0 +1,56 @@ +// version 1.1 + +fun binomial(n: Int, k: Int): Long = when { + n < 0 || k < 0 -> throw IllegalArgumentException("negative numbers not allowed") + k == 0 -> 1L + k == n -> 1L + else -> { + var prod = 1L + var div = 1L + for (i in 1..k) { + prod *= (n + 1 - i) + div *= i + if (prod % div == 0L) { + prod /= div + div = 1L + } + } + prod + } +} + +fun isPrime(n: Int): Boolean { + if (n < 2) return false + return (1 until n).none { binomial(n, it) % n.toLong() != 0L } +} + +fun main(args: Array) { + var coeff: Long + var sign: Int + var op: String + for (n in 0..9) { + print("(x - 1)^$n = ") + sign = 1 + for (k in n downTo 0) { + coeff = binomial(n, k) + op = if (sign == 1) " + " else " - " + when (k) { + n -> print("x^$n") + 0 -> println("${op}1") + else -> print("$op${coeff}x^$k") + } + if (n == 0) println() + sign *= -1 + } + } + // generate primes under 62 + var p = 2 + val primes = mutableListOf() + do { + if (isPrime(p)) primes.add(p) + if (p != 2) p += 2 else p = 3 + } + while (p < 62) + println("\nThe prime numbers under 62 are:") + println(primes) +} diff --git a/Task/AKS-test-for-primes/PureBasic/aks-test-for-primes.purebasic b/Task/AKS-test-for-primes/PureBasic/aks-test-for-primes.purebasic index 0908f0ee06..9a075b7084 100644 --- a/Task/AKS-test-for-primes/PureBasic/aks-test-for-primes.purebasic +++ b/Task/AKS-test-for-primes/PureBasic/aks-test-for-primes.purebasic @@ -1,8 +1,8 @@ EnableExplicit -Define vzr.b = -1, vzc.b = ~vzr, nMAX.i = 10, n , k +Define vzr.b = -1, vzc.b = ~vzr, nMAX.i = 10, n.i , k.i Procedure coeff(nRow.i, Array pd.i(2)) - Define.i n, k + Define n.i, k.i For n=1 To nRow For k=0 To n If k=0 Or k=n : pd(n,k)=1 : Continue : EndIf @@ -12,7 +12,7 @@ Procedure coeff(nRow.i, Array pd.i(2)) EndProcedure Procedure.b isPrime(n.i, Array pd.i(2)) - Define.i m + Define m.i For m=1 To n-1 If Not pd(n,m) % n = 0 : ProcedureReturn #False : EndIf Next diff --git a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx index 75fa6d9b5a..2371997158 100644 --- a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx +++ b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx @@ -1,15 +1,15 @@ /*REXX program calculates primes via the Agrawal─Kayal─Saxena (AKS) primality test.*/ -parse arg Z .; if Z=='' | Z=="," then Z=200 /*Z not specified? Then use default.*/ -OZ=Z; tell=Z<0; Z=abs(Z) /*Is Z negative? Then show expression.*/ -numeric digits max(9,Z%3) /*define a dynamic # of decimal digits.*/ +parse arg Z .; if Z=='' then Z=200 /*Z not specified? Then use default.*/ +OZ=Z; tell= Z<0; Z=abs(Z) /*Is Z negative? Then show expression.*/ +numeric digits max(9, Z%3) /*define a dynamic # of decimal digits.*/ $.0='-'; $.1="+"; @.=1 /*$.x: sign char; default coefficients.*/ #= /*define list of prime numbers (so far)*/ - do p=3 for Z; pm=p-1; pp=p+1 /*PM & PP: used as a coding convenience*/ - do m=2 for pp%2-1; mm=m-1 /*calculate coefficients for a power. */ - @.p.m=@.pm.mm + @.pm.m; h=pp-m /*calculate left side of coefficients*/ - @.p.h=@.p.m /* " right " " " */ - end /*m*/ /* [↑] The M DO loop creates both */ - end /*p*/ /* sides in the same loop, saving */ + do p=3 for Z; pm=p-1; pp=p+1 /*PM & PP: used as a coding convenience*/ + do m=2 for pp%2-1; mm=m-1 /*calculate coefficients for a power. */ + @.p.m=@.pm.mm + @.pm.m; h=pp-m /*calculate left side of coefficients*/ + @.p.h=@.p.m /* " right " " " */ + end /*m*/ /* [↑] The M DO loop creates both */ + end /*p*/ /* sides in the same loop, saving */ /* a bunch of execution time. */ if tell then say '(x-1)^0: 1' /*possibly display the first expression*/ /* [↓] test for primality by division.*/ @@ -17,25 +17,25 @@ if tell then say '(x-1)^0: 1' /*possibly display the first ex do k=3 to nh while @.n.k//d==0 /*are coefficients divisible by N-1 ? */ end /*k*/ /* [↑] skip the 1st & 2nd coefficients*/ /* [↓] multiple THEN─IF faster than &s*/ - if d\==1 then if d\==4 then if k>nh then #=# d /*add a number to prime list.*/ + if k>nh then if d\==1 then if d\==4 then #=# d /*add a number to prime list.*/ if \tell then iterate /*Don't tell? Don't show expressions.*/ y='(x-1)^'d": " /*define the 1st part of the expression*/ s=1 /*S: is the sign indicator (-1│+1).*/ - do j=n to 2 by -1 /*create the higher powers first. */ + do j=n for n-1 by -1; jm=j-1 /*create the higher powers first. */ if j==2 then xp='x' /*if power=1, then don't show the power*/ - else xp='x^' || (j-1) /* ··· else show power with ^ */ + else xp='x^'jm /* ··· else show power with ^ */ if j==n then y=y xp /*no sign (+│-) for the 1st expression.*/ - else y=y $.s @.n.j'∙'xp /*build the expression with sign (+|-).*/ + else y=y $.s || @.n.j'∙'xp /*build the expression with sign (+|-).*/ s=\s /*flip the sign for the next expression*/ end /*j*/ /* [↑] the sign (now) is either 0 │ 1,*/ /* and is displayed either - │ + */ - say y $.s 1 /*just show the first N expressions, */ + say y $.s || 1 /*just show the first N expressions, */ end /*n*/ /* [↑] ··· but only for negative Z. */ say /* [↓] Has Z a leading + ? Then show.*/ -if Z==word(. #,words(#)+1) then is='is' /*the number is a prime. */ - else is="isn't" /* " " ain't " " */ -if left(OZ,1)=='+' then say Z is 'prime.' /*show if OZ has a + (plus sign). */ - else say 'primes:' # /*display the prime number list. */ +if Z==word(. #, words(#)+1) then is= 'is' /*the number is a prime. */ + else is= "isn't" /* " " isn't " " */ +if left(OZ, 1)=='+' then say Z is 'prime.' /*display if OZ has a + (plus sign).*/ + else say 'primes:' # /*display the prime number list. */ say /* [↓] the digit length of a big coef.*/ say 'Found ' words(#) " primes and the largest coefficient has " length(@.pm.h), - " decimal digits." /*stick a fork in it, we're all done. */ + " decimal digits." /*stick a fork in it, we're all done. */ diff --git a/Task/AKS-test-for-primes/Stata/aks-test-for-primes.stata b/Task/AKS-test-for-primes/Stata/aks-test-for-primes.stata new file mode 100644 index 0000000000..993f54cd64 --- /dev/null +++ b/Task/AKS-test-for-primes/Stata/aks-test-for-primes.stata @@ -0,0 +1,63 @@ +mata +function pol(n) { + a=J(1,n+1,1) + r=1 + s=1 + for (k=0; k) { + val d = Dog("Fido") + with(d) { + makeNoise() + announceType() // inherits Animal's implementation + announceName() + } + println() + val c = Cat() + with(c) { + makeNoise() + announceType() + announceName() // inherits Announcer's implementation + } +} diff --git a/Task/Abstract-type/MATLAB/abstract-type-1.m b/Task/Abstract-type/MATLAB/abstract-type-1.m new file mode 100644 index 0000000000..cd9af1d233 --- /dev/null +++ b/Task/Abstract-type/MATLAB/abstract-type-1.m @@ -0,0 +1,3 @@ +classdef (Abstract) AbsClass + ... +end diff --git a/Task/Abstract-type/MATLAB/abstract-type-2.m b/Task/Abstract-type/MATLAB/abstract-type-2.m new file mode 100644 index 0000000000..23f06db91f --- /dev/null +++ b/Task/Abstract-type/MATLAB/abstract-type-2.m @@ -0,0 +1,3 @@ +methods (Abstract) + abstMethod(obj) +end diff --git a/Task/Abstract-type/MATLAB/abstract-type-3.m b/Task/Abstract-type/MATLAB/abstract-type-3.m new file mode 100644 index 0000000000..8450408541 --- /dev/null +++ b/Task/Abstract-type/MATLAB/abstract-type-3.m @@ -0,0 +1,3 @@ +properties (Abstract) + AbsProp +end diff --git a/Task/Abstract-type/Nim/abstract-type.nim b/Task/Abstract-type/Nim/abstract-type.nim index eefb4189e9..502a939685 100644 --- a/Task/Abstract-type/Nim/abstract-type.nim +++ b/Task/Abstract-type/Nim/abstract-type.nim @@ -1,9 +1,12 @@ type - Comparable = generic x, y + Comparable = concept x, y (x < y) is bool - Container[T] = generic c - c.len is ordinal - items(c) is iterator - for value in c: - type(value) is T + Stack[T] = concept s, var v + s.pop() is T + v.push(T) + + s.len is Ordinal + + for value in s: + value is T diff --git a/Task/Abstract-type/OoRexx/abstract-type-1.rexx b/Task/Abstract-type/OoRexx/abstract-type-1.rexx new file mode 100644 index 0000000000..18b9ec7ba3 --- /dev/null +++ b/Task/Abstract-type/OoRexx/abstract-type-1.rexx @@ -0,0 +1,60 @@ + -- Example showing a class that defines an interface in ooRexx + -- shape is the interface class that defines the methods a shape instance + -- is expected to implement as abstract methods. Instances of the shape + -- class need not directly subclass the interface, but can use multiple + -- inheritance to mark itself as implementing the interface. + + r=.rectangle~new(5,2) + say r + -- check for instance of + if r~isa(.shape) then say "a" r~name "is a shape" + say "r~area:" r~area + say + + c=.circle~new(2) + say c + -- check for instance of shape works even if inherited + if c~isa(.shape) then say "a" c~name "is a shape" + say "c~area:" c~area + say + + -- a mixin is still a class and can be instantiated. The abstract methods + -- will give an error if invoked + g=.shape~new + say g + say g~name + say "g~area:" g~area -- invoking abstract method results in a runtime error. + + -- the "MIXINCLASS" tag makes this avaiable for multiple inhertance + ::class shape MIXINCLASS Object + ::method area abstract + ::method name abstract + + -- directly subclassing the the interface + ::class rectangle subclass shape + + ::method init + expose length width + use strict arg length=0, width=0 + + ::method area + expose length width + return length*width + + ::method name + return "Rectangle" + + -- inherits the shape methods + ::class circle subclass object inherit shape + + ::method init + expose radius + use strict arg radius=0 + + ::method area + expose radius + numeric digits 20 + return radius*radius*3.14159265358979323846 + + ::method name + return "Circle" diff --git a/Task/Abstract-type/OoRexx/abstract-type-2.rexx b/Task/Abstract-type/OoRexx/abstract-type-2.rexx new file mode 100644 index 0000000000..3da157e618 --- /dev/null +++ b/Task/Abstract-type/OoRexx/abstract-type-2.rexx @@ -0,0 +1,51 @@ + -- Example showing an abstract type in ooRexx + -- shape is the abstract class that defines the abstract method area + -- which is then implemented by its two subclasses, rectangle and circle + -- name is the method inherited by the subclasses. + -- author: Rony G. Flatscher, 2012-05-26 + -- changed/edited: Walter Pachl, 2012-05-28 28 + -- highlighting: to come + + r=.rectangle~new(5,2) + say r + say r~name + say "r~area:" r~area + say + + c=.circle~new(2) + say c + say c~name + say "c~area:" c~area + say + + g=.shape~new + say g + say g~name + say "g~area:" g~area -- invoking abstract method results in a runtime error. + + ::class shape + ::method area abstract + ::method name + return "self~class~id:" self~class~id + + + ::class rectangle subclass shape + + ::method init + expose length width + use strict arg length=0, width=0 + + ::method area + expose length width + return length*width + + ::class circle subclass shape + + ::method init + expose radius + use strict arg radius=0 + + ::method area + expose radius + numeric digits 20 + return radius*radius*3.14159265358979323846 diff --git a/Task/Abstract-type/Simula/abstract-type-1.simula b/Task/Abstract-type/Simula/abstract-type-1.simula new file mode 100644 index 0000000000..ecf8191d00 --- /dev/null +++ b/Task/Abstract-type/Simula/abstract-type-1.simula @@ -0,0 +1,9 @@ + ! ABSTRACT HASH KEY TYPE ; + LISTVAL CLASS HASHKEY; + VIRTUAL: + PROCEDURE HASH IS + INTEGER PROCEDURE HASH;; + PROCEDURE EQUALTO IS + BOOLEAN PROCEDURE EQUALTO(K); REF(HASHKEY) K;; + BEGIN + END HASHKEY; diff --git a/Task/Abstract-type/Simula/abstract-type-2.simula b/Task/Abstract-type/Simula/abstract-type-2.simula new file mode 100644 index 0000000000..dffcb17a69 --- /dev/null +++ b/Task/Abstract-type/Simula/abstract-type-2.simula @@ -0,0 +1,20 @@ + ! COMMON HASH KEY TYPE IS TEXT ; + HASHKEY CLASS TEXTHASHKEY(T); VALUE T; TEXT T; + BEGIN + INTEGER PROCEDURE HASH; + BEGIN + INTEGER I; + T.SETPOS(1); + WHILE T.MORE DO + I := 31*I+RANK(T.GETCHAR); + IF DEBUG THEN BEGIN + OUTIMAGE; + OUTTEXT("HASHMAPS.TEXTHASHKEY.HASH="); + OUTINT(I,0); + OUTIMAGE; + END; + HASH := I; + END HASH; + BOOLEAN PROCEDURE EQUALTO(K); REF(HASHKEY) K; + EQUALTO := T = K QUA TEXTHASHKEY.T; + END TEXTHASHKEY; diff --git a/Task/Abstract-type/Zkl/abstract-type-1.zkl b/Task/Abstract-type/Zkl/abstract-type-1.zkl new file mode 100644 index 0000000000..11418bf671 --- /dev/null +++ b/Task/Abstract-type/Zkl/abstract-type-1.zkl @@ -0,0 +1,21 @@ +class Stream{ // Mostly virtural base class + var [proxy protected] + isBroken = fcn { _broken.isSet() }, + isClosed = fcn { return(_closed.isSet() or _broken.isSet()); }; + fcn init{ + var [protected] + _closed = Atomic.Bool(True), + _broken = Atomic.Bool(False), + whyBroken = Void; + } + fcn clear { _closed.clear(); _broken.clear(); return(self.topdog); } + fcn open { return(topdog.init(vm.pasteArgs())); } + fcn toStream { return(self); } + fcn close { _closed.set(); return(self.topdog); } + fcn flush { return(self.topdog); } + fcn read { throw(Exception.TheEnd); } // destructive or advance + fcn readln { throw(Exception.TheEnd); } + fcn write(x) { return(self.topdog); } + fcn writeln(x) { return(self.topdog); } + fcn walker { return((0).walker(*,wap((self.topdog.read.fpM(""))))); } +} diff --git a/Task/Abstract-type/Zkl/abstract-type-2.zkl b/Task/Abstract-type/Zkl/abstract-type-2.zkl new file mode 100644 index 0000000000..8de1aa75b5 --- /dev/null +++ b/Task/Abstract-type/Zkl/abstract-type-2.zkl @@ -0,0 +1,5 @@ +class DevNull(Stream){ + var [const] fileName = "DevNull"; // compatibility with File + fcn init { Stream.init() } + fcn write(x) { return(0); } +} diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Batch-File/abundant,-deficient-and-perfect-number-classifications.bat b/Task/Abundant,-deficient-and-perfect-number-classifications/Batch-File/abundant,-deficient-and-perfect-number-classifications.bat new file mode 100644 index 0000000000..f4a8dcf80a --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Batch-File/abundant,-deficient-and-perfect-number-classifications.bat @@ -0,0 +1,33 @@ +@echo off +setlocal enabledelayedexpansion + +:_main + +for /l %%i in (1,1,20000) do ( + + echo Processing %%i + + call:_P %%i + set Pn=!errorlevel! + if !Pn! lss %%i set /a deficient+=1 + if !Pn!==%%i set /a perfect+=1 + if !Pn! gtr %%i set /a abundant+=1 + cls +) + +echo Deficient - %deficient% ^| Perfect - %perfect% ^| Abundant - %abundant% +pause>nul + + +:_P +setlocal enabledelayedexpansion +set sumdivisers=0 + +set /a upperlimit=%1-1 + +for /l %%i in (1,1,%upperlimit%) do ( + set /a isdiviser=%1 %% %%i + if !isdiviser!==0 set /a sumdivisers+=%%i +) + +exit /b %sumdivisers% diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/C/abundant,-deficient-and-perfect-number-classifications.c b/Task/Abundant,-deficient-and-perfect-number-classifications/C/abundant,-deficient-and-perfect-number-classifications.c index 869c90661e..0a303342da 100644 --- a/Task/Abundant,-deficient-and-perfect-number-classifications/C/abundant,-deficient-and-perfect-number-classifications.c +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/C/abundant,-deficient-and-perfect-number-classifications.c @@ -1,41 +1,42 @@ #include -#define d 0 -#define p 1 -#define a 2 +#define de 0 +#define pe 1 +#define ab 2 + int main(){ - int sum_pd=0,i,j; - int try_max=0; + int sum = 0, i, j; + int try_max = 0; //1 is deficient by default and can add it deficient list - int count_list[3]={1,0,0}; - for(i=2;i<=20000;i++){ + int count_list[3] = {1,0,0}; + for(i=2; i <= 20000; i++){ //Set maximum to check for proper division - try_max=i/2; + try_max = i/2; //1 is in all proper division number - sum_pd=1; - for(j=2;ji){ - count_list[a]++; + if (sum > i){ + count_list[ab]++; continue; } - count_list[p]++; + count_list[pe]++; } - printf("\nThere are %d deficient,",count_list[d]); - printf(" %d perfect,",count_list[p]); - printf(" %d abundant numbers between 1 and 20000.\n",count_list[a]); + printf("\nThere are %d deficient," ,count_list[de]); + printf(" %d perfect," ,count_list[pe]); + printf(" %d abundant numbers between 1 and 20000.\n" ,count_list[ab]); return 0; } diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Forth/abundant,-deficient-and-perfect-number-classifications.fth b/Task/Abundant,-deficient-and-perfect-number-classifications/Forth/abundant,-deficient-and-perfect-number-classifications.fth new file mode 100644 index 0000000000..1ba9147fd9 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Forth/abundant,-deficient-and-perfect-number-classifications.fth @@ -0,0 +1,26 @@ +CREATE A 0 , +: SLOT ( x y -- 0|1|2) OVER OVER < -ROT > - 1+ ; +: CLASSIFY ( n -- n') \ 0 == deficient, 1 == perfect, 2 == abundant + DUP A ! \ we'll be accessing this often, so save somewhere convenient + 2 / >R \ upper bound + 1 \ starting sum, 1 is always a divisor + 2 \ current check + BEGIN DUP R@ < WHILE + A @ OVER /MOD SWAP ( s c d m) + IF DROP ELSE + R> DROP DUP >R ( R: d n) + OVER TUCK OVER <> * - ( s c c+?d) + ROT + SWAP ( s' c) + THEN 1+ + REPEAT DROP R> DROP A @ ( sum n) SLOT ; +CREATE COUNTS 0 , 0 , 0 , +: INIT COUNTS 3 CELLS ERASE 1 COUNTS ! ; +: CLASSIFY-NUMBERS ( n --) INIT + BEGIN DUP WHILE + 1 OVER CLASSIFY CELLS COUNTS + +! 1- + REPEAT DROP ; +: .COUNTS + ." Deficient : " [ COUNTS ]L @ . CR + ." Perfect : " [ COUNTS 1 CELLS + ]L @ . CR + ." Abundant : " [ COUNTS 2 CELLS + ]L @ . CR ; +20000 CLASSIFY-NUMBERS .COUNTS BYE diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Go/abundant,-deficient-and-perfect-number-classifications.go b/Task/Abundant,-deficient-and-perfect-number-classifications/Go/abundant,-deficient-and-perfect-number-classifications.go new file mode 100644 index 0000000000..c99712033c --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Go/abundant,-deficient-and-perfect-number-classifications.go @@ -0,0 +1,39 @@ +package main + +import "fmt" + +import "math" + +func main() { + +var d,a,p,i=0,0,0,1 + +for i=1;i<=20000;i++{ + +if pfac_sum(i) n % i == 0 && n != i).sum(); + public static long properDivsSum(long n) { + return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n != i && n % i == 0).sum(); } } diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-1.js b/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-1.js index edeeb32f9b..7b9825ea0c 100644 --- a/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-1.js +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-1.js @@ -1,5 +1,5 @@ for (var dpa=[1,0,0], n=2; n<=20000; n+=1) { - for (var ds=0, d=1, e=n/2+1; d' ) diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-2.js b/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-2.js index d3dba24cc9..08b3d078a0 100644 --- a/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-2.js +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-2.js @@ -1,6 +1,6 @@ for (var dpa=[1,0,0], n=2; n<=20000; n+=1) { - for (var ds=1, d=2, e=Math.sqrt(n); d' ) diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-3.js b/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-3.js index 8fb7d53ff2..b80b4bf2c6 100644 --- a/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-3.js +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-3.js @@ -1,48 +1,48 @@ function primes(t) { - var ps = {2:true, 3:true} - next: for (var n=5, i=2; n<=t; n+=i, i=6-i) { - var s = Math.sqrt( n ) - for ( var p in ps ) { - if ( p > s ) break - if ( n % p ) continue - continue next - } - ps[n] = true - } - return ps + var ps = {2:true, 3:true} + next: for (var n=5, i=2; n<=t; n+=i, i=6-i) { + var s = Math.sqrt( n ) + for ( var p in ps ) { + if ( p > s ) break + if ( n % p ) continue + continue next + } + ps[n] = true + } + return ps } function factorize(f, t) { - var cs = {}, ps = primes(t) - for (var n=f; n<=t; n++) if (!ps[n]) cs[n] = factors(n) - return cs - function factors(n) { - for ( var p in ps ) if ( n % p == 0 ) break - var ts = {} - ts[p] = 1 - if ( ps[n /= p] ) { - if ( !ts[n]++ ) ts[n]=1 - } - else { - var fs = cs[n] - if ( !fs ) fs = cs[n] = factors(n) - for ( var e in fs ) ts[e] = fs[e] + (e==p) - } - return ts - } + var cs = {}, ps = primes(t) + for (var n=f; n<=t; n++) if (!ps[n]) cs[n] = factors(n) + return cs + function factors(n) { + for ( var p in ps ) if ( n % p == 0 ) break + var ts = {} + ts[p] = 1 + if ( ps[n /= p] ) { + if ( !ts[n]++ ) ts[n]=1 + } + else { + var fs = cs[n] + if ( !fs ) fs = cs[n] = factors(n) + for ( var e in fs ) ts[e] = fs[e] + (e==p) + } + return ts + } } function pContrib(p, e) { - for (var pc=1, n=1, i=1; i<=e; i+=1) pc+=n*=p; - return pc + for (var pc=1, n=1, i=1; i<=e; i+=1) pc+=n*=p; + return pc } for (var dpa=[1,0,0], t=20000, cs=factorize(2,t), n=2; n<=t; n+=1) { - var ds=1, fs=cs[n] - if (fs) { - for (var p in fs) ds *= pContrib(p, fs[p]) - ds -= n - } - dpa[ds' ) diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-4.js b/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-4.js new file mode 100644 index 0000000000..bbc4f9d79b --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-4.js @@ -0,0 +1,42 @@ +(() => { + 'use strict'; + + const + // divisors :: (Integral a) => a -> [a] + divisors = n => range(1, Math.floor(n / 2)) + .filter(x => n % x === 0), + + // classOf :: (Integral a) => a -> Ordering + classOf = n => compare(divisors(n) + .reduce((a, b) => a + b, 0), n), + + classTypes = { + deficient: -1, + perfect: 0, + abundant: 1 + }; + + // GENERIC FUNCTIONS + const + // compare :: Ord a => a -> a -> Ordering + compare = (a, b) => + a < b ? -1 : (a > b ? 1 : 0), + + // range :: Int -> Int -> [Int] + range = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // TEST + + // classes :: [Ordering] + const classes = range(1, 20000) + .map(classOf); + + return Object.keys(classTypes) + .map(k => k + ": " + classes + .filter(x => x === classTypes[k]) + .length.toString()) + .join('\n'); +})(); diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/jq/abundant,-deficient-and-perfect-number-classifications-1.jq b/Task/Abundant,-deficient-and-perfect-number-classifications/Jq/abundant,-deficient-and-perfect-number-classifications-1.jq similarity index 100% rename from Task/Abundant,-deficient-and-perfect-number-classifications/jq/abundant,-deficient-and-perfect-number-classifications-1.jq rename to Task/Abundant,-deficient-and-perfect-number-classifications/Jq/abundant,-deficient-and-perfect-number-classifications-1.jq diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/jq/abundant,-deficient-and-perfect-number-classifications-2.jq b/Task/Abundant,-deficient-and-perfect-number-classifications/Jq/abundant,-deficient-and-perfect-number-classifications-2.jq similarity index 100% rename from Task/Abundant,-deficient-and-perfect-number-classifications/jq/abundant,-deficient-and-perfect-number-classifications-2.jq rename to Task/Abundant,-deficient-and-perfect-number-classifications/Jq/abundant,-deficient-and-perfect-number-classifications-2.jq diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/jq/abundant,-deficient-and-perfect-number-classifications-3.jq b/Task/Abundant,-deficient-and-perfect-number-classifications/Jq/abundant,-deficient-and-perfect-number-classifications-3.jq similarity index 100% rename from Task/Abundant,-deficient-and-perfect-number-classifications/jq/abundant,-deficient-and-perfect-number-classifications-3.jq rename to Task/Abundant,-deficient-and-perfect-number-classifications/Jq/abundant,-deficient-and-perfect-number-classifications-3.jq diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Kotlin/abundant,-deficient-and-perfect-number-classifications.kotlin b/Task/Abundant,-deficient-and-perfect-number-classifications/Kotlin/abundant,-deficient-and-perfect-number-classifications.kotlin new file mode 100644 index 0000000000..79da5c71d5 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Kotlin/abundant,-deficient-and-perfect-number-classifications.kotlin @@ -0,0 +1,25 @@ +// version 1.1 + +fun sumProperDivisors(n: Int) = + if (n < 2) 0 else (1..n / 2).filter { (n % it) == 0 }.sum() + +fun main(args: Array) { + var sum: Int + var deficient = 0 + var perfect = 0 + var abundant = 0 + + for (n in 1..20000) { + sum = sumProperDivisors(n) + when { + sum < n -> deficient++ + sum == n -> perfect++ + sum > n -> abundant++ + } + } + + println("The classification of the numbers from 1 to 20,000 is as follows:\n") + println("Deficient = $deficient") + println("Perfect = $perfect") + println("Abundant = $abundant") +} diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/PowerShell/abundant,-deficient-and-perfect-number-classifications.psh b/Task/Abundant,-deficient-and-perfect-number-classifications/PowerShell/abundant,-deficient-and-perfect-number-classifications-1.psh similarity index 100% rename from Task/Abundant,-deficient-and-perfect-number-classifications/PowerShell/abundant,-deficient-and-perfect-number-classifications.psh rename to Task/Abundant,-deficient-and-perfect-number-classifications/PowerShell/abundant,-deficient-and-perfect-number-classifications-1.psh diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/PowerShell/abundant,-deficient-and-perfect-number-classifications-2.psh b/Task/Abundant,-deficient-and-perfect-number-classifications/PowerShell/abundant,-deficient-and-perfect-number-classifications-2.psh new file mode 100644 index 0000000000..74593a216c --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/PowerShell/abundant,-deficient-and-perfect-number-classifications-2.psh @@ -0,0 +1,56 @@ +function Get-NumberClassification +{ + [CmdletBinding()] + [OutputType([PSCustomObject])] + Param + ( + [Parameter(Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true, + Position=0)] + [int] + $Number + ) + + Begin + { + function Get-ProperDivisorSum ([int]$Number) + { + if ($Number -lt 2) {return 0} + + $sum = 1 + + if ($Number -gt 3) + { + $sqrtNumber = [Math]::Sqrt($Number) + + foreach ($divisor in 2..$sqrtNumber) + { + if ($Number % $divisor -eq 0) {$sum += $divisor + $Number / $divisor} + } + + if ($Number % $sqrtNumber -eq 0) {$sum -= $sqrtNumber} + } + + $sum + } + + [System.Collections.ArrayList]$numbers = @() + } + Process + { + switch ([Math]::Sign((Get-ProperDivisorSum $Number) - $Number)) + { + -1 { [void]$numbers.Add([PSCustomObject]@{Class="Deficient"; Number=$Number}) } + 0 { [void]$numbers.Add([PSCustomObject]@{Class="Perfect" ; Number=$Number}) } + 1 { [void]$numbers.Add([PSCustomObject]@{Class="Abundant" ; Number=$Number}) } + } + } + End + { + $numbers | Group-Object -Property Class | + Select-Object -Property Count, + @{Name='Class' ; Expression={$_.Name}}, + @{Name='Number'; Expression={$_.Group.Number}} + } +} diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/PowerShell/abundant,-deficient-and-perfect-number-classifications-3.psh b/Task/Abundant,-deficient-and-perfect-number-classifications/PowerShell/abundant,-deficient-and-perfect-number-classifications-3.psh new file mode 100644 index 0000000000..fd9ab5621c --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/PowerShell/abundant,-deficient-and-perfect-number-classifications-3.psh @@ -0,0 +1 @@ +1..20000 | Get-NumberClassification diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-1.py b/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-1.py deleted file mode 100644 index fef62aaa57..0000000000 --- a/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-1.py +++ /dev/null @@ -1,15 +0,0 @@ ->>> from proper_divisors import proper_divs ->>> from collections import Counter ->>> ->>> rangemax = 20000 ->>> ->>> def pdsum(n): -... return sum(proper_divs(n)) -... ->>> def classify(n, p): -... return 'perfect' if n == p else 'abundant' if p > n else 'deficient' -... ->>> classes = Counter(classify(n, pdsum(n)) for n in range(1, 1 + rangemax)) ->>> classes.most_common() -[('deficient', 15043), ('abundant', 4953), ('perfect', 4)] ->>> diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-2.py b/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-2.py deleted file mode 100644 index bf3832ad49..0000000000 --- a/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-2.py +++ /dev/null @@ -1,26 +0,0 @@ -#lang racket -(require "proper-divisors.rkt") -(define SCOPE 20000) - -(define P - (let ((P-v (vector))) - (λ (n) - (set! P-v (fold-divisors P-v n 0 +)) - (vector-ref P-v n)))) - -(define-values - (a d p) - (for/fold ((a 0) (d 0) (p 0)) - ((n (in-range SCOPE 0 -1))) ; doing this backwards initialises the memo - (match (- (P n) n) - [0 (values a d (add1 p))] ; perfect - [(? negative?) (values a (add1 d) p)] ; deficient - [(? positive?) (values (add1 a) d p)]))) ; abundant - -(printf #<1; q=q%4; _=z-r-q; r=r%2; if _>=0 then do; z=_; r=r+q; end - end /*while*/ /*upon completion, R is the sqrt of Z*/ - s=1 /* [↓] only use EVEN | ODD ints. ___*/ - do j=2+odd by 1+odd to r /*divide by all integers up to √ x */ + q=1; do while q<=z; q=q*4; end /* ◄──↓ compute integer sqrt of Z (=R)*/ + r=0; do while q>1; q=q%4; _=z-r-q; r=r%2; if _>=0 then do; z=_; r=r+q; end; end + /* [↓] only use EVEN | ODD ints. ___*/ + s=1; do j=2+odd by 1+odd to r /*divide by all integers up to √ x */ if x//j==0 then s=s+j+ x%j /*add the two divisors to (sigma) sum. */ end /*j*/ /* [↑] % is the REXX integer division*/ /* [↓] adjust for a square. ___*/ diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Rust/abundant,-deficient-and-perfect-number-classifications.rust b/Task/Abundant,-deficient-and-perfect-number-classifications/Rust/abundant,-deficient-and-perfect-number-classifications.rust new file mode 100644 index 0000000000..844ad9eef8 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Rust/abundant,-deficient-and-perfect-number-classifications.rust @@ -0,0 +1,19 @@ +fn main() { + // deficient starts at 1 because 1 is deficient but proper_divisors returns + // and empty Vec + let (mut abundant, mut deficient, mut perfect) = (0u32, 1u32, 0u32); + for i in 1..20_001 { + if let Some(divisors) = i.proper_divisors() { + let sum: u64 = divisors.iter().sum(); + if sum < i { + deficient += 1 + } else if sum > i { + abundant += 1 + } else { + perfect += 1 + } + } + } + println!("deficient:\t{:5}\nperfect:\t{:5}\nabundant:\t{:5}", + deficient, perfect, abundant); +} diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Sidef/abundant,-deficient-and-perfect-number-classifications.sidef b/Task/Abundant,-deficient-and-perfect-number-classifications/Sidef/abundant,-deficient-and-perfect-number-classifications.sidef index 9f1dd6cbb3..371eac9a23 100644 --- a/Task/Abundant,-deficient-and-perfect-number-classifications/Sidef/abundant,-deficient-and-perfect-number-classifications.sidef +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Sidef/abundant,-deficient-and-perfect-number-classifications.sidef @@ -1,11 +1,11 @@ func propdivsum(x) { gather { for d in (2 .. x.isqrt) { - take(d, x/d) if d.divides(x) + take(d, x/d) if (d `divides` x) } - }.uniq.sum(x > 1 ? 1 : 0) + }.uniq.sum(x > 1 ? 1 : 0) } - +  var h = Hash() -20000.times { |i| ++(h{propdivsum(i) <=> i} := 0) } +{|i| ++(h{propdivsum(i) <=> i} := 0) } << 1..20000 say "Perfect: #{h{0}} Deficient: #{h{-1}} Abundant: #{h{1}}" diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Zkl/abundant,-deficient-and-perfect-number-classifications.zkl b/Task/Abundant,-deficient-and-perfect-number-classifications/Zkl/abundant,-deficient-and-perfect-number-classifications.zkl new file mode 100644 index 0000000000..3218443bf9 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Zkl/abundant,-deficient-and-perfect-number-classifications.zkl @@ -0,0 +1,13 @@ +fcn properDivs(n){ [1.. (n + 1)/2 + 1].filter('wrap(x){ n%x==0 and n!=x }) } + +fcn classify(n){ + p:=properDivs(n).sum(); + return(if(p Script on foo(sum) script - on lambda(n) + on |λ|(n) set sum to sum + n - end lambda + end |λ| end script end foo diff --git a/Task/Accumulator-factory/Astro/accumulator-factory.astro b/Task/Accumulator-factory/Astro/accumulator-factory.astro new file mode 100644 index 0000000000..15b7d041e9 --- /dev/null +++ b/Task/Accumulator-factory/Astro/accumulator-factory.astro @@ -0,0 +1,5 @@ +fun accumulator(sum): |n| -> sum += n +let f = accumulator(5) +print f(5) # 10 +print f(10) # 20 +print f(2.4) # 22.4 diff --git a/Task/Accumulator-factory/Crystal/accumulator-factory.crystal b/Task/Accumulator-factory/Crystal/accumulator-factory.crystal new file mode 100644 index 0000000000..59c9ae4a13 --- /dev/null +++ b/Task/Accumulator-factory/Crystal/accumulator-factory.crystal @@ -0,0 +1,12 @@ +# Make types a bit easier with an alias +alias Num = Int32 | Int64 | Float32 | Float64 + +def accumulator(sum : Num) + # This proc is very similar to a Ruby lambda + ->(n : Num){ sum += n } +end + +x = accumulator(5) +puts x.call(5) #=> 10 +puts x.call(10) #=> 20 +puts x.call(2.4) #=> 22.4 diff --git a/Task/Accumulator-factory/Elena/accumulator-factory.elena b/Task/Accumulator-factory/Elena/accumulator-factory.elena index 43975bcceb..79b8cb52a4 100644 --- a/Task/Accumulator-factory/Elena/accumulator-factory.elena +++ b/Task/Accumulator-factory/Elena/accumulator-factory.elena @@ -1,22 +1,21 @@ -#import system. -#import system'dynamic. +import system'dynamic. -#symbol Function = - (:x) [ this append:x ]. +Function = + (:x)(closure append:x). -#class(extension)op +extension op { - #method accumulator &of:func - = Variable new:self mix &into:func. + accumulatorOf:func + = Variable new(self); mixInto(func). } -#symbol program = +program = [ - #var x := 1 accumulator &of:Function. + var x := 1 accumulatorOf(Function). - x eval:5. + x eval(5). - #var y := 3 accumulator &of:Function. + var y := 3 accumulatorOf(Function). - console write:(x eval:2.3r). + console write(x eval(2.3r)). ]. diff --git a/Task/Accumulator-factory/Elixir/accumulator-factory-2.elixir b/Task/Accumulator-factory/Elixir/accumulator-factory-2.elixir index 5c0d7c2c0b..1b558ebf33 100644 --- a/Task/Accumulator-factory/Elixir/accumulator-factory-2.elixir +++ b/Task/Accumulator-factory/Elixir/accumulator-factory-2.elixir @@ -1,3 +1,5 @@ +ExUnit.start + defmodule AccumulatorFactoryTest do use ExUnit.Case diff --git a/Task/Accumulator-factory/Forth/accumulator-factory.fth b/Task/Accumulator-factory/Forth/accumulator-factory-1.fth similarity index 100% rename from Task/Accumulator-factory/Forth/accumulator-factory.fth rename to Task/Accumulator-factory/Forth/accumulator-factory-1.fth diff --git a/Task/Accumulator-factory/Forth/accumulator-factory-2.fth b/Task/Accumulator-factory/Forth/accumulator-factory-2.fth new file mode 100644 index 0000000000..3a88c20e79 --- /dev/null +++ b/Task/Accumulator-factory/Forth/accumulator-factory-2.fth @@ -0,0 +1,9 @@ +: faccumulator ( r "name" -- ) + create falign f, +does> ( r1 -- r2 ) + faligned dup f@ f+ fdup f! ; + +1 s>f faccumulator x +5 s>f x fdrop +3 s>f faccumulator y \ unused +2.3e x f. diff --git a/Task/Accumulator-factory/GAP/accumulator-factory.gap b/Task/Accumulator-factory/GAP/accumulator-factory.gap deleted file mode 100644 index 777986bdd7..0000000000 --- a/Task/Accumulator-factory/GAP/accumulator-factory.gap +++ /dev/null @@ -1,29 +0,0 @@ -accu := function(n) - local f, v; - v := n; - f := function(a) - v := v + a; - return v; - end; - return f; -end; - -a := accu(0); -# function( a ) ... end -b := accu(100); -# function( a ) ... end -a(6); -# 6 -b(6); -# 106 -a(1); -# 7 -b(1); -# 107 -# These functions also accept other types, as long as addition is meaningful -b(1/FLOAT_INT(3)) -# 107.333 -a(2/3); -# 23/3 -a([1, 2, 3]); -# [ 26/3, 29/3, 32/3 ] diff --git a/Task/Accumulator-factory/Golo/accumulator-factory.golo b/Task/Accumulator-factory/Golo/accumulator-factory.golo new file mode 100644 index 0000000000..be83ad3f91 --- /dev/null +++ b/Task/Accumulator-factory/Golo/accumulator-factory.golo @@ -0,0 +1,16 @@ +module accumulatorfactory + +function accumulator = |n| { + let number = DynamicVariable(n) + return |i| { + number: value(number: value() + i) + return number: value() + } +} + +function main = |args| { + let x = accumulator(1) + x(5) + accumulator(3) + println(x(2.3)) +} diff --git a/Task/Accumulator-factory/Java/accumulator-factory-2.java b/Task/Accumulator-factory/Java/accumulator-factory-2.java index 5831d32b7d..408e9f5b40 100644 --- a/Task/Accumulator-factory/Java/accumulator-factory-2.java +++ b/Task/Accumulator-factory/Java/accumulator-factory-2.java @@ -1,19 +1,16 @@ -import com.google.common.base.Function; +public class Accumulator { + private double sum; + public Accumulator(double sum0) { + sum = sum0; + } + public double call(double n) { + return sum += n; + } -public class AccumulatorFactory { - private static Function accumulator(final Double elem) { - return new Function() { - Double sum = elem; - @Override public Double apply(Double val) { - return sum += val; - } - }; - } - - public static void main(String[] args) { - Function x = accumulator(1d); - x.apply(5d); - System.out.println(accumulator(3d)); - System.out.println(x.apply(2.3)); - } + public static void main(String[] args) { + Accumulator x = new Accumulator(1); + x.call(5); + System.out.println(new Accumulator(3)); + System.out.println(x.call(2.3)); + } } diff --git a/Task/Accumulator-factory/Java/accumulator-factory-3.java b/Task/Accumulator-factory/Java/accumulator-factory-3.java index 614eb8cd68..f38f83029c 100644 --- a/Task/Accumulator-factory/Java/accumulator-factory-3.java +++ b/Task/Accumulator-factory/Java/accumulator-factory-3.java @@ -1,15 +1,24 @@ -import java.util.function.DoubleUnaryOperator; +public class AccumulatorFactory { -public interface AccumulatorFactory { - public static DoubleUnaryOperator accumulator(double element) { - double[] sum = new double[] { element }; - return value -> sum[0] += value; - } + public interface Accumulator { + double add(double x); + } - public static void main(String... arguments) { - DoubleUnaryOperator x = accumulator(1d); - x.applyAsDouble(5d); - System.out.println(accumulator(3d)); - System.out.println(x.applyAsDouble(2.3)); - } + private static Accumulator accumulator(final double initial) { + return new Accumulator() { + private double sum = initial; + + @Override + public double add(double x) { + return sum += x; + } + }; + } + + public static void main(String[] args) { + Accumulator x = accumulator(1.0); + x.add(5.0); + System.out.println(accumulator(3.0)); + System.out.println(x.add(2.3)); + } } diff --git a/Task/Accumulator-factory/Java/accumulator-factory-4.java b/Task/Accumulator-factory/Java/accumulator-factory-4.java index 99c7f67e49..e6f219571a 100644 --- a/Task/Accumulator-factory/Java/accumulator-factory-4.java +++ b/Task/Accumulator-factory/Java/accumulator-factory-4.java @@ -1,30 +1,15 @@ -public class Accumulator { - private Long sumA; // non-null if we're working in the integer domain - private double sumB; - public Accumulator(Number sum0) { - if (sum0 instanceof Double) { - sumB = sum0.doubleValue(); - } else { - sumA = sum0.longValue(); - } - } - public Number call(Number n) { - if (sumA != null) { - if (n instanceof Double) { - sumB = n.doubleValue() + sumA; - sumA = null; - return sumB; - } - return sumA += n.longValue(); - } - return sumB += n.doubleValue(); - } +import java.util.function.DoubleUnaryOperator; - public static void main(String[] args) { - Accumulator x = new Accumulator(1); - x.call(5); - Accumulator y = new Accumulator(3); - System.out.println(y+" has value "+y.call(0)); - System.out.println(x.call(2.3)); - } +public interface AccumulatorFactory { + public static DoubleUnaryOperator accumulator(double element) { + double[] sum = { element }; + return value -> sum[0] += value; + } + + public static void main(String... arguments) { + DoubleUnaryOperator x = accumulator(1.0); + x.applyAsDouble(5.0); + System.out.println(accumulator(3.0)); + System.out.println(x.applyAsDouble(2.3)); + } } diff --git a/Task/Accumulator-factory/Java/accumulator-factory-5.java b/Task/Accumulator-factory/Java/accumulator-factory-5.java new file mode 100644 index 0000000000..99c7f67e49 --- /dev/null +++ b/Task/Accumulator-factory/Java/accumulator-factory-5.java @@ -0,0 +1,30 @@ +public class Accumulator { + private Long sumA; // non-null if we're working in the integer domain + private double sumB; + public Accumulator(Number sum0) { + if (sum0 instanceof Double) { + sumB = sum0.doubleValue(); + } else { + sumA = sum0.longValue(); + } + } + public Number call(Number n) { + if (sumA != null) { + if (n instanceof Double) { + sumB = n.doubleValue() + sumA; + sumA = null; + return sumB; + } + return sumA += n.longValue(); + } + return sumB += n.doubleValue(); + } + + public static void main(String[] args) { + Accumulator x = new Accumulator(1); + x.call(5); + Accumulator y = new Accumulator(3); + System.out.println(y+" has value "+y.call(0)); + System.out.println(x.call(2.3)); + } +} diff --git a/Task/Accumulator-factory/Kotlin/accumulator-factory.kotlin b/Task/Accumulator-factory/Kotlin/accumulator-factory.kotlin new file mode 100644 index 0000000000..ed3969a8e9 --- /dev/null +++ b/Task/Accumulator-factory/Kotlin/accumulator-factory.kotlin @@ -0,0 +1,22 @@ +// version 1.1 + +fun foo(n: Double): (d: Double) -> Double { + var nn = n + return { nn += it; nn } +} + +fun foo(n: Int): (i: Int) -> Int { + var nn = n + return { nn += it; nn } +} + +fun main(args: Array) { + val x = foo(1.0) // calls 'Double' overload + x(5.0) + foo(3.0) + println(x(2.3)) + val y = foo(1) // calls 'Int' overload + y(5) + foo(5) + println(y(2)) +} diff --git a/Task/Accumulator-factory/NewLISP/accumulator-factory.newlisp b/Task/Accumulator-factory/NewLISP/accumulator-factory.newlisp new file mode 100644 index 0000000000..10348d8877 --- /dev/null +++ b/Task/Accumulator-factory/NewLISP/accumulator-factory.newlisp @@ -0,0 +1 @@ +(define (sum (x 0)) (inc 0 x)) diff --git a/Task/Accumulator-factory/Nit/accumulator-factory.nit b/Task/Accumulator-factory/Nit/accumulator-factory.nit new file mode 100644 index 0000000000..f9b97090f7 --- /dev/null +++ b/Task/Accumulator-factory/Nit/accumulator-factory.nit @@ -0,0 +1,22 @@ +# The `accumulator factory` task. +# +# Nit has no first-class function. +# A class is used to store the state. +module accumulator_factory + +class Accumulator + # The accumulated sum + # Numeric is used, so Int and Float are accepted + private var sum: Numeric + fun call(n: Numeric): Numeric + do + # `add` is the safe `+` method on Numeric + sum = sum.add(n) + return sum + end +end + +var x = new Accumulator(1) +x.call(5) +var y = new Accumulator(3) +print x.call(2.3) diff --git a/Task/Accumulator-factory/OoRexx/accumulator-factory.rexx b/Task/Accumulator-factory/OoRexx/accumulator-factory.rexx new file mode 100644 index 0000000000..9da011f121 --- /dev/null +++ b/Task/Accumulator-factory/OoRexx/accumulator-factory.rexx @@ -0,0 +1,23 @@ +x = .accumulator~new(1) -- new accumulator with initial value of "1" +x~call(5) +x~call(2.3) +say "Accumulator value is now" x -- displays current value + +-- an accumulator class instance can be instantiated and +-- used to sum up a series of numbers +::class accumulator +::method init -- instance initializer...sets the accumulator initial value + expose sum + use strict arg sum = 0 -- sets default sum value if not specified + +-- perform the accumulator function +::method call + expose sum + use strict arg n + sum += n -- bump the accumulator + return sum -- return the new value + +-- extra credit...display the current accumulator value +::method string + expose sum + return sum diff --git a/Task/Accumulator-factory/PARI-GP/accumulator-factory.pari b/Task/Accumulator-factory/PARI-GP/accumulator-factory.pari new file mode 100644 index 0000000000..d70bbe3bfc --- /dev/null +++ b/Task/Accumulator-factory/PARI-GP/accumulator-factory.pari @@ -0,0 +1,4 @@ +stack = List([1]); +factory(b,c=0) = my(a=stack[1]++);listput(stack,c);(b)->stack[a]+=b; + +foo(f) = factory(0, f); \\ initialize the factory diff --git a/Task/Accumulator-factory/Simula/accumulator-factory.simula b/Task/Accumulator-factory/Simula/accumulator-factory.simula new file mode 100644 index 0000000000..e86b395dfb --- /dev/null +++ b/Task/Accumulator-factory/Simula/accumulator-factory.simula @@ -0,0 +1,69 @@ +BEGIN + + ! ABSTRACTION FOR SIMULA'S TWO NUMERIC TYPES ; + CLASS NUMBER; + VIRTUAL: + PROCEDURE OUT IS PROCEDURE OUT;; + BEGIN + END NUMBER; + + NUMBER CLASS INTEGERNUMBER(INTVAL); INTEGER INTVAL; + BEGIN + PROCEDURE OUT; OUTINT(INTVAL, 10); + END INTEGERNUMBER; + + NUMBER CLASS REALNUMBER(REALVAL); REAL REALVAL; + BEGIN + PROCEDURE OUT; OUTFIX(REALVAL, 4, 10); + END REALNUMBER; + + + ! SIMULA CANNOT RETURN FUNCTIONS - SIMULATE FUNCTIONS WITH CLASSES ; + CLASS ACCUMULATOR(ACC); REF(NUMBER) ACC; + BEGIN + + PROCEDURE SWITCHTOREAL(Y); REAL Y; + BEGIN + REF(REALNUMBER) NEWACC; + NEWACC :- NEW REALNUMBER(ACC QUA INTEGERNUMBER.INTVAL); + NEWACC.REALVAL:= NEWACC.REALVAL + Y; + ACC :- NEWACC; + END SWITCHTOREAL; + + REF(NUMBER) PROCEDURE ACCUMULATE(OTHERNUM); REF(NUMBER) OTHERNUM; + BEGIN + INSPECT ACC + WHEN INTEGERNUMBER DO + BEGIN + INSPECT OTHERNUM + WHEN INTEGERNUMBER DO + ACC QUA INTEGERNUMBER.INTVAL + := ACC QUA INTEGERNUMBER.INTVAL + INTVAL + WHEN REALNUMBER DO + SWITCHTOREAL(REALVAL) + END + WHEN REALNUMBER DO + BEGIN + INSPECT OTHERNUM + WHEN INTEGERNUMBER DO + ACC QUA REALNUMBER.REALVAL + := ACC QUA REALNUMBER.REALVAL + INTVAL + WHEN REALNUMBER DO + ACC QUA REALNUMBER.REALVAL + := ACC QUA REALNUMBER.REALVAL + REALVAL + END; + ACCUMULATE :- ACC; + END ACCUMULATE; + + PROCEDURE OUT; ACC.OUT; + + END FOO; + + + REF(ACCUMULATOR) FOO; + FOO :- NEW ACCUMULATOR(NEW INTEGERNUMBER(1)); FOO.OUT; OUTIMAGE; + FOO.ACCUMULATE(NEW INTEGERNUMBER(5)); FOO.OUT; OUTIMAGE; + NEW ACCUMULATOR(NEW INTEGERNUMBER(3)); + FOO.ACCUMULATE(NEW REALNUMBER(2.3)); FOO.OUT; OUTIMAGE; + +END. diff --git a/Task/Accumulator-factory/Zkl/accumulator-factory.zkl b/Task/Accumulator-factory/Zkl/accumulator-factory.zkl new file mode 100644 index 0000000000..a1b9ee5b46 --- /dev/null +++ b/Task/Accumulator-factory/Zkl/accumulator-factory.zkl @@ -0,0 +1 @@ +fcn foo(n){ fcn(n,acc){ acc.set(n+acc.value).value }.fp1(Ref(n)) } diff --git a/Task/Ackermann-function/Agda/ackermann-function-1.agda b/Task/Ackermann-function/Agda/ackermann-function-1.agda new file mode 100644 index 0000000000..1528a75ff4 --- /dev/null +++ b/Task/Ackermann-function/Agda/ackermann-function-1.agda @@ -0,0 +1,12 @@ +open import Data.Nat +open import Data.Nat.Show +open import IO + +module Ackermann where + +ack : ℕ -> ℕ -> ℕ +ack zero n = n + 1 +ack (suc m) zero = ack m 1 +ack (suc m) (suc n) = ack m (ack (suc m) n) + +main = run (putStrLn (show (ack 3 9))) diff --git a/Task/Ackermann-function/Agda/ackermann-function-2.agda b/Task/Ackermann-function/Agda/ackermann-function-2.agda new file mode 100644 index 0000000000..32b6b4af20 --- /dev/null +++ b/Task/Ackermann-function/Agda/ackermann-function-2.agda @@ -0,0 +1,2 @@ +agda --compile Ackermann.agda +./Ackermann diff --git a/Task/Ackermann-function/Bc/ackermann-function.bc b/Task/Ackermann-function/Bc/ackermann-function.bc new file mode 100644 index 0000000000..4f2ebf3f33 --- /dev/null +++ b/Task/Ackermann-function/Bc/ackermann-function.bc @@ -0,0 +1,12 @@ +define ack(m, n) { + if ( m == 0 ) return (n+1); + if ( n == 0 ) return (ack(m-1, 1)); + return (ack(m-1, ack(m, n-1))); +} + +for (n=0; n<7; n++) { + for (m=0; m<4; m++) { + print "A(", m, ",", n, ") = ", ack(m,n), "\n"; + } +} +quit diff --git a/Task/Ackermann-function/Beeswax/ackermann-function-1.beeswax b/Task/Ackermann-function/Beeswax/ackermann-function-1.beeswax new file mode 100644 index 0000000000..144e52e397 --- /dev/null +++ b/Task/Ackermann-function/Beeswax/ackermann-function-1.beeswax @@ -0,0 +1,5 @@ + >M?f@h@gMf@h3yzp if m>0 and n>0 => replace m,n with m-1,m,n-1 + >@h@g'b?1f@h@gM?f@hzp if m>0 and n=0 => replace m,n with m-1,1 +_ii>Ag~1?~Lpz1~2h@g'd?g?Pfzp if m=0 => replace m,n with n+1 + >I; + b < < diff --git a/Task/Ackermann-function/Beeswax/ackermann-function-2.beeswax b/Task/Ackermann-function/Beeswax/ackermann-function-2.beeswax new file mode 100644 index 0000000000..bedf0b3dc2 --- /dev/null +++ b/Task/Ackermann-function/Beeswax/ackermann-function-2.beeswax @@ -0,0 +1,10 @@ + >Mf@Ph?@g@2h@Mf@Php if m>4 and n>0 => replace m,n with m-1,m,n-1 + >~4~L#1~2hg'd?1f@hgM?f2h p if m>4 and n=0 => replace m,n with m-1,1 + # q < /n+3 times \ + #X~4K#?2Fg?PPP>@B@M"pb if m=4 => replace m,n with 2^(2^(....)))-3 + # >~3K#?g?PPP~2BMMp>@MMMp if m=3 => replace m,n with 2^(n+3)-3 +_ii>Ag~1?~Lpz1~2h@gX'#?g?P p M if m=0 => replace m,n with n+1 + z I ~>~1K#?g?PP p if m=1 => replace m,n with n+2 + f ; >2K#?g?~2.PPPp if m=2 => replace m,n with 2n+3 + z b < < < + d < diff --git a/Task/Ackermann-function/C-sharp/ackermann-function.cs b/Task/Ackermann-function/C-sharp/ackermann-function.cs index 4b6effdb54..597561c067 100644 --- a/Task/Ackermann-function/C-sharp/ackermann-function.cs +++ b/Task/Ackermann-function/C-sharp/ackermann-function.cs @@ -1,32 +1,127 @@ using System; -class Program +using System.Numerics; +using System.IO; +using System.Diagnostics; + +namespace Ackermann_Function { - public static long Ackermann(long m, long n) + class Program { - if(m > 0) + static void Main(string[] args) { - if (n > 0) - return Ackermann(m - 1, Ackermann(m, n - 1)); - else if (n == 0) - return Ackermann(m - 1, 1); - } - else if(m == 0) - { - if(n >= 0) - return n + 1; - } - - throw new System.ArgumentOutOfRangeException(); - } - - static void Main() - { - for (long m = 0; m <= 3; ++m) - { - for (long n = 0; n <= 4; ++n) + int _m = 0; + int _n = 0; + Console.Write("m = "); + try { - Console.WriteLine("Ackermann({0}, {1}) = {2}", m, n, Ackermann(m, n)); + _m = Convert.ToInt32(Console.ReadLine()); } + catch (Exception) + { + Console.WriteLine("Please enter a number."); + } + Console.Write("n = "); + try + { + _n = Convert.ToInt32(Console.ReadLine()); + } + catch (Exception) + { + Console.WriteLine("Please enter a number."); + } + //for (long m = 0; m <= 10; ++m) + //{ + // for (long n = 0; n <= 10; ++n) + // { + // DateTime now = DateTime.Now; + // Console.WriteLine("Ackermann({0}, {1}) = {2}", m, n, Ackermann(m, n)); + // Console.WriteLine("Time taken:{0}", DateTime.Now - now); + // } + //} + + DateTime now = DateTime.Now; + Console.WriteLine("Ackermann({0}, {1}) = {2}", _m, _n, Ackermann(_m, _n)); + Console.WriteLine("Time taken:{0}", DateTime.Now - now); + File.WriteAllText("number.txt", Ackermann(_m, _n).ToString()); + Process.Start("number.txt"); + Console.ReadKey(); + } + public class OverflowlessStack + { + internal sealed class SinglyLinkedNode + { + private const int ArraySize = 2048; + T[] _array; + int _size; + public SinglyLinkedNode Next; + public SinglyLinkedNode() + { + _array = new T[ArraySize]; + } + public bool IsEmpty { get { return _size == 0; } } + public SinglyLinkedNode Push(T item) + { + if (_size == ArraySize - 1) + { + SinglyLinkedNode n = new SinglyLinkedNode(); + n.Next = this; + n.Push(item); + return n; + } + _array[_size++] = item; + return this; + } + public T Pop() + { + return _array[--_size]; + } + } + private SinglyLinkedNode _head = new SinglyLinkedNode(); + + public T Pop() + { + T ret = _head.Pop(); + if (_head.IsEmpty && _head.Next != null) + _head = _head.Next; + return ret; + } + public void Push(T item) + { + _head = _head.Push(item); + } + public bool IsEmpty + { + get { return _head.Next == null && _head.IsEmpty; } + } + } + public static BigInteger Ackermann(BigInteger m, BigInteger n) + { + var stack = new OverflowlessStack(); + stack.Push(m); + while (!stack.IsEmpty) + { + m = stack.Pop(); + skipStack: + if (m == 0) + n = n + 1; + else if (m == 1) + n = n + 2; + else if (m == 2) + n = n * 2 + 3; + else if (n == 0) + { + --m; + n = 1; + goto skipStack; + } + else + { + stack.Push(m - 1); + --n; + goto skipStack; + } + } + return n; } } } diff --git a/Task/Ackermann-function/Elena/ackermann-function.elena b/Task/Ackermann-function/Elena/ackermann-function.elena index 7c06aeb159..def9390a83 100644 --- a/Task/Ackermann-function/Elena/ackermann-function.elena +++ b/Task/Ackermann-function/Elena/ackermann-function.elena @@ -1,26 +1,29 @@ -#define system. -#define extensions. +import extensions. -// --- Ackermann function --- - -#symbol ackermann = (:m:n) +ackermann = (:m:n) [ + if((n < 0)||(m < 0)) + [ + InvalidArgumentException new; raise + ]. + m => - 0 ? [ n + 1 ] - > 0 ? [ - n => 0 ? [ ackermann eval:(m - 1):1 ] - > 0 ? [ ackermann eval:(m - 1):(ackermann eval:m:(n-1)) ] + 0 [ ^n + 1 ]; + ! [ + n => + 0 [ ^ackermann eval(m - 1,1) ]; + ! [ ^ackermann eval(m - 1,ackermann eval(m,n-1)) ] ] ]. -#symbol program = +program = [ - 0 to:3 &doEach: (:i) + 0 to:3 do(:i) [ - 0 to:5 &doEach: (:j) + 0 to:5 do(:j) [ - console writeLine:"A(":i:",":j:")=":(ackermann eval:i:j). - ]. + console printLine("A(",i,",",j,")=",ackermann eval(i,j)) + ] ]. console readChar. diff --git a/Task/Ackermann-function/Gnuplot/ackermann-function.gnuplot b/Task/Ackermann-function/Gnuplot/ackermann-function.gnuplot new file mode 100644 index 0000000000..ca84f37f12 --- /dev/null +++ b/Task/Ackermann-function/Gnuplot/ackermann-function.gnuplot @@ -0,0 +1,5 @@ +A (m, n) = m == 0 ? n + 1 : n == 0 ? A (m - 1, 1) : A (m - 1, A (m, n - 1)) +print A (0, 4) +print A (1, 4) +print A (2, 4) +print A (3, 4) diff --git a/Task/Ackermann-function/Haskell/ackermann-function-1.hs b/Task/Ackermann-function/Haskell/ackermann-function-1.hs index 53f36fffb1..8208fa996b 100644 --- a/Task/Ackermann-function/Haskell/ackermann-function-1.hs +++ b/Task/Ackermann-function/Haskell/ackermann-function-1.hs @@ -1,3 +1,7 @@ -ack 0 n = n + 1 -ack m 0 = ack (m-1) 1 -ack m n = ack (m-1) (ack m (n-1)) +ack :: Int -> Int -> Int +ack 0 n = succ n +ack m 0 = ack (pred m) 1 +ack m n = ack (pred m) (ack m (pred n)) + +main :: IO () +main = mapM_ print $ uncurry ack <$> [(0, 0), (3, 4)] diff --git a/Task/Ackermann-function/jq/ackermann-function-1.jq b/Task/Ackermann-function/Jq/ackermann-function-1.jq similarity index 100% rename from Task/Ackermann-function/jq/ackermann-function-1.jq rename to Task/Ackermann-function/Jq/ackermann-function-1.jq diff --git a/Task/Ackermann-function/jq/ackermann-function-2.jq b/Task/Ackermann-function/Jq/ackermann-function-2.jq similarity index 100% rename from Task/Ackermann-function/jq/ackermann-function-2.jq rename to Task/Ackermann-function/Jq/ackermann-function-2.jq diff --git a/Task/Ackermann-function/jq/ackermann-function-3.jq b/Task/Ackermann-function/Jq/ackermann-function-3.jq similarity index 100% rename from Task/Ackermann-function/jq/ackermann-function-3.jq rename to Task/Ackermann-function/Jq/ackermann-function-3.jq diff --git a/Task/Ackermann-function/jq/ackermann-function-4.jq b/Task/Ackermann-function/Jq/ackermann-function-4.jq similarity index 100% rename from Task/Ackermann-function/jq/ackermann-function-4.jq rename to Task/Ackermann-function/Jq/ackermann-function-4.jq diff --git a/Task/Ackermann-function/jq/ackermann-function-5.jq b/Task/Ackermann-function/Jq/ackermann-function-5.jq similarity index 100% rename from Task/Ackermann-function/jq/ackermann-function-5.jq rename to Task/Ackermann-function/Jq/ackermann-function-5.jq diff --git a/Task/Ackermann-function/jq/ackermann-function-6.jq b/Task/Ackermann-function/Jq/ackermann-function-6.jq similarity index 100% rename from Task/Ackermann-function/jq/ackermann-function-6.jq rename to Task/Ackermann-function/Jq/ackermann-function-6.jq diff --git a/Task/Ackermann-function/Kotlin/ackermann-function.kotlin b/Task/Ackermann-function/Kotlin/ackermann-function.kotlin index 77317662c4..489397d280 100644 --- a/Task/Ackermann-function/Kotlin/ackermann-function.kotlin +++ b/Task/Ackermann-function/Kotlin/ackermann-function.kotlin @@ -1,5 +1,3 @@ -package ackermann - fun A(m: Long, n: Long): Long = when { m == 0L -> n + 1 m > 0L -> when { diff --git a/Task/Ackermann-function/MLite/ackermann-function-1.mlite b/Task/Ackermann-function/MLite/ackermann-function-1.mlite new file mode 100644 index 0000000000..baa15fac0a --- /dev/null +++ b/Task/Ackermann-function/MLite/ackermann-function-1.mlite @@ -0,0 +1,3 @@ +fun ackermann( 0, n ) = n + 1 + | ( m, 0 ) = ackermann( m - 1, 1 ) + | ( m, n ) = ackermann( m - 1, ackermann(m, n - 1) ) diff --git a/Task/Ackermann-function/MLite/ackermann-function-2.mlite b/Task/Ackermann-function/MLite/ackermann-function-2.mlite new file mode 100644 index 0000000000..cb0da1fd1b --- /dev/null +++ b/Task/Ackermann-function/MLite/ackermann-function-2.mlite @@ -0,0 +1,5 @@ +fun jota x = map (fn x = x-1) ` iota x + +fun test_tuples (x, y) = append_map (fn a = map (fn b = (b, a)) ` jota x) ` jota y + +map ackermann (test_tuples(4,9)) diff --git a/Task/Ackermann-function/Nim/ackermann-function-1.nim b/Task/Ackermann-function/Nim/ackermann-function-1.nim deleted file mode 100644 index a9bf77abe2..0000000000 --- a/Task/Ackermann-function/Nim/ackermann-function-1.nim +++ /dev/null @@ -1,7 +0,0 @@ -proc Ackermann(m, n: int64): int64 = - if m == 0: - result = n + 1 - elif n == 0: - result = Ackermann(m - 1, 1) - else: - result = Ackermann(m - 1, Ackermann(m, n - 1)) diff --git a/Task/Ackermann-function/Nim/ackermann-function-2.nim b/Task/Ackermann-function/Nim/ackermann-function-2.nim deleted file mode 100644 index 8f68f25d51..0000000000 --- a/Task/Ackermann-function/Nim/ackermann-function-2.nim +++ /dev/null @@ -1,32 +0,0 @@ -from strutils import parseInt - -proc ackermann(m,n: int): int = - var res: int - if m == 0: - res += n + 1 - elif m > 0 and n == 0: - res += ackermann(m-1, 1) - elif m > 0 and n > 0: - res += ackermann(m-1, ackermann(m, n-1)) - return res - -proc getnumber(): int = - try: - parseInt(readLine(stdin)) - except EInvalidValue: - echo("Please enter an integer: ") - getnumber() - -echo("First number please: ") -var first: int = getnumber() -while first < 0: - echo("Please enter a non-negative integer value.") - first = getnumber() - -echo("Second number please: ") -var second: int = getnumber() -while second < 0: - echo("Please enter a non-negative integer value.") - second = getnumber() - -echo("Result: " & $ackermann(first, second)) diff --git a/Task/Ackermann-function/Nim/ackermann-function.nim b/Task/Ackermann-function/Nim/ackermann-function.nim new file mode 100644 index 0000000000..e751f92918 --- /dev/null +++ b/Task/Ackermann-function/Nim/ackermann-function.nim @@ -0,0 +1,25 @@ +from strutils import parseInt + +proc ackermann(m, n: int64): int64 = + if m == 0: + result = n + 1 + elif n == 0: + result = ackermann(m - 1, 1) + else: + result = ackermann(m - 1, ackermann(m, n - 1)) + +proc getNumber(): int = + try: + result = stdin.readLine.parseInt + except ValueError: + echo "An integer, please!" + result = getNumber() + if result < 0: + echo "Please Enter a non-negative Integer: " + result = getNumber() + +echo "First non-negative Integer please: " +let first = getNumber() +echo "Second non-negative Integer please: " +let second = getNumber() +echo "Reslut: ", $ackermann(first, second) diff --git a/Task/Ackermann-function/Nimrod/ackermann-function.nimrod b/Task/Ackermann-function/Nimrod/ackermann-function.nimrod deleted file mode 100644 index a9bf77abe2..0000000000 --- a/Task/Ackermann-function/Nimrod/ackermann-function.nimrod +++ /dev/null @@ -1,7 +0,0 @@ -proc Ackermann(m, n: int64): int64 = - if m == 0: - result = n + 1 - elif n == 0: - result = Ackermann(m - 1, 1) - else: - result = Ackermann(m - 1, Ackermann(m, n - 1)) diff --git a/Task/Ackermann-function/Nit/ackermann-function.nit b/Task/Ackermann-function/Nit/ackermann-function.nit new file mode 100644 index 0000000000..4a41dea12c --- /dev/null +++ b/Task/Ackermann-function/Nit/ackermann-function.nit @@ -0,0 +1,18 @@ +# Task: Ackermann function +# +# A simple straightforward recursive implementation. +module ackermann_function + +fun ack(m, n: Int): Int +do + if m == 0 then return n + 1 + if n == 0 then return ack(m-1,1) + return ack(m-1, ack(m, n-1)) +end + +for m in [0..3] do + for n in [0..6] do + print ack(m,n) + end + print "" +end diff --git a/Task/Ackermann-function/OoRexx/ackermann-function.rexx b/Task/Ackermann-function/OoRexx/ackermann-function.rexx new file mode 100644 index 0000000000..469b51506a --- /dev/null +++ b/Task/Ackermann-function/OoRexx/ackermann-function.rexx @@ -0,0 +1,13 @@ +loop m = 0 to 3 + loop n = 0 to 6 + say "Ackermann("m", "n") =" ackermann(m, n) + end +end + +::routine ackermann + use strict arg m, n + -- give us some precision room + numeric digits 10000 + if m = 0 then return n + 1 + else if n = 0 then return ackermann(m - 1, 1) + else return ackermann(m - 1, ackermann(m, n - 1)) diff --git a/Task/Ackermann-function/Stata/ackermann-function.stata b/Task/Ackermann-function/Stata/ackermann-function.stata new file mode 100644 index 0000000000..128275973f --- /dev/null +++ b/Task/Ackermann-function/Stata/ackermann-function.stata @@ -0,0 +1,17 @@ +mata +function ackermann(m,n) { + if (m==0) { + return(n+1) + } else if (n==0) { + return(ackermann(m-1,1)) + } else { + return(ackermann(m-1,ackermann(m,n-1))) + } +} + +for (i=0; i<=3; i++) printf("%f\n",ackermann(i,4)) +5 +6 +11 +125 +end diff --git a/Task/Ackermann-function/TI-83-BASIC/ackermann-function-1.ti-83 b/Task/Ackermann-function/TI-83-BASIC/ackermann-function-1.ti-83 new file mode 100644 index 0000000000..a3b0c7c372 --- /dev/null +++ b/Task/Ackermann-function/TI-83-BASIC/ackermann-function-1.ti-83 @@ -0,0 +1,21 @@ +PROGRAM:ACKERMAN +:If not(M +:Then +:N+1→N +:Return +:Else +:If not(N +:Then +:1→N +:M-1→M +:prgmACKERMAN +:Else +:N-1→N +:M→L1(1+dim(L1 +:prgmACKERMAN +:Ans→N +:L1(dim(L1))-1→M +:dim(L1)-1→dim(L1 +:prgmACKERMAN +:End +:End diff --git a/Task/Ackermann-function/TI-83-BASIC/ackermann-function-2.ti-83 b/Task/Ackermann-function/TI-83-BASIC/ackermann-function-2.ti-83 new file mode 100644 index 0000000000..6bfb47aefc --- /dev/null +++ b/Task/Ackermann-function/TI-83-BASIC/ackermann-function-2.ti-83 @@ -0,0 +1,6 @@ +PROGRAM:AHANDLER +:0→dim(L1 +:Prompt M +:Prompt N +:prgmACKERMAN +:Disp Ans diff --git a/Task/Active-Directory-Connect/Java/active-directory-connect.java b/Task/Active-Directory-Connect/Java/active-directory-connect.java index 64f3b0bea7..8ac8dd8669 100644 --- a/Task/Active-Directory-Connect/Java/active-directory-connect.java +++ b/Task/Active-Directory-Connect/Java/active-directory-connect.java @@ -1,59 +1,14 @@ import java.io.IOException; - +import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; -import org.apache.directory.shared.ldap.model.cursor.EntryCursor; -import org.apache.directory.shared.ldap.model.entry.Entry; -import org.apache.directory.shared.ldap.model.exception.LdapException; -import org.apache.directory.shared.ldap.model.message.SearchScope; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -public class RDirectoryLDAP { +public class LdapConnectionDemo { - static final Logger log_; - private static final String ldapHostName; - private static final int ldapPort; - private static LdapConnection connection; - - static { - log_ = LoggerFactory.getLogger(RDirectoryLDAP.class); - connection = null; - ldapHostName = "localhost"; - ldapPort = 10389; - } - - public static void main(String[] args) { - try { - if (log_.isInfoEnabled()) { log_.info("LDAP Connection to " + ldapHostName + " on port " + ldapPort); } - connection = new LdapNetworkConnection(ldapHostName, ldapPort); - - try { - if (log_.isTraceEnabled()) { log_.trace("LDAP bind"); } - connection.bind(); - - if (log_.isTraceEnabled()) { log_.trace("LDAP unbind"); } - connection.unBind(); - } - catch (LdapException lex) { - log_.error("LDAP Error", lex); - } - catch (IOException ex) { - log_.error("I/O Error", ex); - } - } - finally { - if (log_.isTraceEnabled()) { log_.trace("LDAP close connection"); } - try { - if (connection != null) { - connection.close(); + public static void main(String[] args) throws LdapException, IOException { + try (LdapConnection connection = new LdapNetworkConnection("localhost", 10389)) { + connection.bind(); + connection.unBind(); } - } - catch (IOException ex) { - log_.error("I/O Error on connection.close()", ex); - } } - - return; - } } diff --git a/Task/Active-Directory-Connect/Kotlin/active-directory-connect.kotlin b/Task/Active-Directory-Connect/Kotlin/active-directory-connect.kotlin index 9c1ee985b1..35718bb661 100644 --- a/Task/Active-Directory-Connect/Kotlin/active-directory-connect.kotlin +++ b/Task/Active-Directory-Connect/Kotlin/active-directory-connect.kotlin @@ -1,41 +1,32 @@ -package directory - -import kotlin.properties.get - +import org.apache.directory.api.ldap.model.exception.LdapException +import org.apache.directory.ldap.client.api.LdapNetworkConnection import java.io.IOException import java.util.logging.Level import java.util.logging.Logger -import org.apache.directory.api.ldap.model.exception.LdapException -import org.apache.directory.ldap.client.api.LdapNetworkConnection - -class LDAP(val map: Map) { +class LDAP(map: Map) { fun run() { var connection: LdapNetworkConnection? = null try { - if (info) - log.info("LDAP Connection to $hostname on port $port") + if (info) log.info("LDAP Connection to $hostname on port $port") connection = LdapNetworkConnection(hostname, port.toInt()) try { - if (info) - log.info("LDAP bind") + if (info) log.info("LDAP bind") connection.bind() } catch (e: LdapException) { log.severe(e.toString()) } try { - if (info) - log.info("LDAP unbind") + if (info) log.info("LDAP unbind") connection.unBind() } catch (e: LdapException) { log.severe(e.toString()) } } finally { try { - if (info) - log.info("LDAP close connection") + if (info) log.info("LDAP close connection") connection!!.close() } catch (e: IOException) { log.severe(e.toString()) diff --git a/Task/Active-Directory-Connect/Smart-BASIC/active-directory-connect.smart b/Task/Active-Directory-Connect/Smart-BASIC/active-directory-connect.smart new file mode 100644 index 0000000000..e2339b1a3b --- /dev/null +++ b/Task/Active-Directory-Connect/Smart-BASIC/active-directory-connect.smart @@ -0,0 +1,15 @@ +PRINT "Current directory: ";CURRENT_DIR$() +PRINT +PRINT "Folders:" +PRINT +DIR "/" LIST DIRS a$,c +FOR n = 0 TO c-1 +PRINT ,a$(n) +NEXT n +PRINT +PRINT "Files:" +PRINT +DIR "/" LIST FILES a$,c +FOR n = 0 TO c-1 +PRINT ,a$(n) +NEXT n diff --git a/Task/Active-Directory-Search-for-a-user/Java/active-directory-search-for-a-user.java b/Task/Active-Directory-Search-for-a-user/Java/active-directory-search-for-a-user.java index 42097890fe..1fed41b9fe 100644 --- a/Task/Active-Directory-Search-for-a-user/Java/active-directory-search-for-a-user.java +++ b/Task/Active-Directory-Search-for-a-user/Java/active-directory-search-for-a-user.java @@ -1,153 +1,38 @@ import java.io.IOException; -import java.util.Arrays; - +import org.apache.directory.api.ldap.model.cursor.CursorException; +import org.apache.directory.api.ldap.model.cursor.EntryCursor; +import org.apache.directory.api.ldap.model.entry.Entry; +import org.apache.directory.api.ldap.model.exception.LdapException; +import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; -import org.apache.directory.shared.ldap.model.cursor.EntryCursor; -import org.apache.directory.shared.ldap.model.entry.Entry; -import org.apache.directory.shared.ldap.model.exception.LdapException; -import org.apache.directory.shared.ldap.model.message.SearchScope; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +public class LdapSearchDemo { -public class RDirectorySearchLDAP { - - protected static final Logger log_; - private static LdapConnection connection; - private static final String ldapHostName; - private static final int ldapPort; - private static final String ldapDnStr; - private static final String ldapCreds; - - static { - - log_ = LoggerFactory.getLogger(RDirectorySearchLDAP.class); - - ldapHostName = "localhost"; - ldapPort = 11389; - ldapDnStr="uid=admin,ou=system"; - ldapCreds="********"; - } - - public static void main(String[] args) { - - boolean connected = false; - - try { - connected = setUp(); - if (connected) { - search("*mil*"); - } - } - finally { - if (connected) { - tearDown(); - } + public static void main(String[] args) throws IOException, LdapException, CursorException { + new LdapSearchDemo().demonstrateSearch(); } - return; - } - - private static boolean search(String uid) { - - boolean state; - EntryCursor cursor; - Entry ev; - String baseDn; - String filter; - SearchScope scope; - String attributes[]; - int ksearch = 0; - - state = true; - - baseDn = "ou=users,o=mojo"; - filter = "(&(objectClass=person)(&(uid=" + uid + ")))"; - scope = SearchScope.SUBTREE; - attributes = new java.lang.String[] { "dn", "cn", "sn", "uid" }; - - try { - if (log_.isTraceEnabled()) { log_.trace("LDAP search"); } - if (log_.isInfoEnabled()) { - log_.info("Begin search"); - log_.info(" search base distinguished name: " + baseDn); - log_.info(" search filter: " + filter); - log_.info(" search attributes: " + (Arrays.asList(attributes).toString())); - } - cursor = connection.search(baseDn, filter, scope, attributes); - while (cursor.next()) { - ksearch++; - ev = cursor.get(); - if (log_.isInfoEnabled()) { log_.info("Search cursor entry count: " + ksearch); } - if (log_.isInfoEnabled()) { log_.info(ev.toString()); } - } - } - catch (LdapException lex) { - state = false; - log_.error("LDAP Error in cursor loop: Iteration " + ksearch, lex); - } - catch (Exception ex) { - state = false; - log_.error("I/O Error in cursor loop: Iteration " + ksearch, ex); + private void demonstrateSearch() throws IOException, LdapException, CursorException { + try (LdapConnection conn = new LdapNetworkConnection("localhost", 11389)) { + conn.bind("uid=admin,ou=system", "********"); + search(conn, "*mil*"); + conn.unBind(); + } } - return state; - } + private void search(LdapConnection connection, String uid) throws LdapException, CursorException { + String baseDn = "ou=users,o=mojo"; + String filter = "(&(objectClass=person)(&(uid=" + uid + ")))"; + SearchScope scope = SearchScope.SUBTREE; + String[] attributes = {"dn", "cn", "sn", "uid"}; + int ksearch = 0; - private static boolean search() { - - return search("*"); - } - - private static boolean setUp() { - - boolean state = false; - - try { - if (log_.isInfoEnabled()) { log_.info("LDAP Connection to " + ldapHostName + " on port " + ldapPort); } - connection = new LdapNetworkConnection(ldapHostName, ldapPort); - - if (log_.isTraceEnabled()) { log_.trace("LDAP bind"); } - connection.bind(ldapDnStr, ldapCreds); - - state = true; + EntryCursor cursor = connection.search(baseDn, filter, scope, attributes); + while (cursor.next()) { + ksearch++; + Entry entry = cursor.get(); + System.out.printf("Search entry %d = %s%n", ksearch, entry); + } } - catch (LdapException lex) { - state = false; - log_.error("LDAP Error", lex); - } - catch (IOException iox) { - state = false; - log_.error("I/O Error", iox); - } - - return state; - } - - private static boolean tearDown() { - - boolean state = false; - - try { - if (log_.isTraceEnabled()) { log_.trace("LDAP unbind"); } - connection.unBind(); - state = true; - } - catch (LdapException lex) { - state = false; - log_.error("LDAP Error", lex); - } - finally { - try { - connection.close(); - } - catch (IOException iox) { - state = false; - log_.error("I/O Error on connection.close()", iox); - } - } - - return state; - } } diff --git a/Task/Active-Directory-Search-for-a-user/OoRexx/active-directory-search-for-a-user.rexx b/Task/Active-Directory-Search-for-a-user/OoRexx/active-directory-search-for-a-user.rexx new file mode 100644 index 0000000000..ff3f4debbe --- /dev/null +++ b/Task/Active-Directory-Search-for-a-user/OoRexx/active-directory-search-for-a-user.rexx @@ -0,0 +1,60 @@ +/* Rexx */ +do + LDAP_URL = 'ldap://localhost:11389' + LDAP_DN_STR = 'uid=admin,ou=system' + LDAP_CREDS = '********' + LDAP_BASE_DN = 'ou=users,o=mojo' + LDAP_SCOPE = 'sub' + LDAP_FILTER = '"(&(objectClass=person)(&(uid=*mil*)))"' + LDAP_ATTRIBUTES = '"dn" "cn" "sn" "uid"' + + ldapCommand = , + 'ldapsearch' , + '-s base' , + '-H' LDAP_URL , + '-LLL' , + '-x' , + '-v' , + '-s' LDAP_SCOPE , + '-D' LDAP_DN_STR , + '-w' LDAP_CREDS , + '-b' LDAP_BASE_DN , + LDAP_FILTER , + LDAP_ATTRIBUTES , + '2>&1' , + '|' , + 'rxqueue' , + '' + + address command, + ldapCommand + + ldapResult. = '' + loop ln = 1 to queued() + parse pull line + ldapResult.0 = ln + ldapResult.ln = line + end ln + + loop ln = 1 to ldapResult.0 + parse var ldapResult.ln 'dn:' dn_ , + 0 'uid:' uid_ , + 0 'sn:' sn_ , + 0 'cn:' cn_ + select + when length(strip(dn_, 'b')) > 0 then dn = dn_ + when length(strip(uid_, 'b')) > 0 then uid = uid_ + when length(strip(sn_, 'b')) > 0 then sn = sn_ + when length(strip(cn_, 'b')) > 0 then cn = cn_ + otherwise nop + end + end ln + + say 'Distiguished Name:' dn + say ' Common Name:' cn + say ' Surname:' sn + say ' userID:' uid + + return +end +exit diff --git a/Task/Active-object/Java/active-object.java b/Task/Active-object/Java/active-object.java new file mode 100644 index 0000000000..26ef36427d --- /dev/null +++ b/Task/Active-object/Java/active-object.java @@ -0,0 +1,70 @@ +/** + * Integrates input function K over time + * S + (t1 - t0) * (K(t1) + K(t0)) / 2 + */ +public class Integrator { + + public interface Function { + double apply(double timeSinceStartInSeconds); + } + + private final long start; + private volatile boolean running; + + private Function func; + private double t0; + private double v0; + private double sum; + + public Integrator(Function func) { + this.start = System.nanoTime(); + setFunc(func); + new Thread(this::integrate).start(); + } + + public void setFunc(Function func) { + this.func = func; + v0 = func.apply(0.0); + t0 = 0; + } + + public double getOutput() { + return sum; + } + + public void stop() { + running = false; + } + + private void integrate() { + running = true; + while (running) { + try { + Thread.sleep(1); + update(); + } catch (InterruptedException e) { + return; + } + } + } + + private void update() { + double t1 = (System.nanoTime() - start) / 1.0e9; + double v1 = func.apply(t1); + double rect = (t1 - t0) * (v0 + v1) / 2; + this.sum += rect; + t0 = t1; + v0 = v1; + } + + public static void main(String[] args) throws InterruptedException { + Integrator integrator = new Integrator(t -> Math.sin(Math.PI * t)); + Thread.sleep(2000); + + integrator.setFunc(t -> 0.0); + Thread.sleep(500); + + integrator.stop(); + System.out.println(integrator.getOutput()); + } +} diff --git a/Task/Active-object/OoRexx/active-object.rexx b/Task/Active-object/OoRexx/active-object.rexx new file mode 100644 index 0000000000..3eba7f4df1 --- /dev/null +++ b/Task/Active-object/OoRexx/active-object.rexx @@ -0,0 +1,74 @@ +integrater = .integrater~new(.routines~sine) -- start the integrater function +call syssleep 2 +integrater~input = .routines~zero -- update the integrater function +call syssleep .5 + +say integrater~output +integrater~stop -- terminate the updater thread + +::class integrater +::method init + expose stopped start v last_v last_t k + use strict arg k + stopped = .false + start = .datetime~new -- initial time stamp + v = 0 + last_v = 0 + last_t = 0 + self~input = k + self~start + +-- spin off a new thread and start updating. Note, this method is unguarded +-- to allow other threads to make calls +::method start unguarded + expose stopped + + reply -- this spins this method invocation off onto a new thread + + do while \stopped + call sysSleep .1 + self~update -- perform the update operation + end + +-- turn off the thread. Since this is unguarded, +-- it can be called any time, any where +::method stop unguarded + expose stopped + stopped = .true + +-- perform the update. Since this is a guarded method, the object +-- start is protected. +::method update + expose start v last_v t last_t k + + numeric digits 20 -- give a lot of precision + + current = .datetime~new + t = (current - start)~microseconds + new_v = k~call(t) -- call the input function + v += (last_v + new_v) * (t - last_t) / 2 + last_t = t + last_v = new_v + say new value is v + +-- a write-only attribute setter (this is GUARDED) +::attribute input SET + expose k last_t last_v + self~update -- update current values + use strict arg k -- update the call function to the provided value + last_t = 0 + last_v = k~call(0) -- and update to the zero value + +-- the output function...returns current calculated value +::attribute output GET + expose v + return v + +::routine zero + return 0 + +::routine sine + use arg t + return rxcalcsin(rxcalcpi() * t) + +::requires rxmath library diff --git a/Task/Active-object/Zkl/active-object-1.zkl b/Task/Active-object/Zkl/active-object-1.zkl new file mode 100644 index 0000000000..60a5d6d937 --- /dev/null +++ b/Task/Active-object/Zkl/active-object-1.zkl @@ -0,0 +1,19 @@ +class Integrator{ + // continuously integrate a function `K`, at each `interval` seconds' + fcn init(f,interval=1e-4){ + var _interval=interval, K=Ref(f), S=Ref(0.0), run=True; + self.launch(); // start me as a thread + } + fcn liftoff{ // entry point for the thread + start:=Time.Clock.timef; // floating point seconds since Epoch + t0,k0,s:=0,K.value(0),S.value; + while(run){ + Atomic.sleep(_interval); + t1,k1:=Time.Clock.timef - start, K.value(t1); + s+=(k1 + k0)*(t1 - t0)/2.0; S.set(s); + t0,k0=t1,k1; + } + } + fcn sample { S.value } + fcn setF(f) { K.set(f) } +} diff --git a/Task/Active-object/Zkl/active-object-2.zkl b/Task/Active-object/Zkl/active-object-2.zkl new file mode 100644 index 0000000000..47a3ff2090 --- /dev/null +++ b/Task/Active-object/Zkl/active-object-2.zkl @@ -0,0 +1,7 @@ +ai:=Integrator(fcn(t){ ((0.0).pi*t).sin() }); +Atomic.sleep(2); +ai.sample().println(); + +ai.setF(fcn{ 0 }); +Atomic.sleep(0.5); +ai.sample().println(); diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/00DESCRIPTION b/Task/Add-a-variable-to-a-class-instance-at-runtime/00DESCRIPTION index 9bf8e67c64..eb4dcaedfe 100644 --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/00DESCRIPTION +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/00DESCRIPTION @@ -1,3 +1,4 @@ +{{omit from|Rust}} Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at [http://www.devsource.com/article2/0,1759,1928562,00.asp An Exercise in Metaprogramming with Ruby]. This is referred to as "monkeypatching" by Pythonistas and some others. 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 0109cb4cfe..120f27657f 100644 --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena @@ -1,33 +1,25 @@ -#define system. -#define extensions. +import extensions. -#class Extender :: BaseExtender +class Extender :: BaseExtender { - #field theField. + object prop foo :: theField. - #constructor new : anObject + constructor new : anObject [ theObject := anObject. ] - - #method foo = theField. - - #method set &foo : aValue - [ - theField := aValue. - ] } -#symbol program = +program = [ - #var anObject := 234. + var anObject := 234. // extending an object with a field - anObject := Extender new:anObject. + anObject := Extender new(anObject). - anObject set &foo:"bar". + anObject foo := "bar". - console writeLine:anObject:".foo=":(anObject foo). + console printLine(anObject,".foo=",anObject foo). console readChar. ]. diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Forth/add-a-variable-to-a-class-instance-at-runtime.fth b/Task/Add-a-variable-to-a-class-instance-at-runtime/Forth/add-a-variable-to-a-class-instance-at-runtime.fth index 6804a35c5a..920a7ebc1b 100644 --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/Forth/add-a-variable-to-a-class-instance-at-runtime.fth +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Forth/add-a-variable-to-a-class-instance-at-runtime.fth @@ -9,6 +9,7 @@ include FMS-SILib.f :class foo object-list inst-objects \ a dynamically growable object container + :m init: inst-objects init: ;m :m add: ( obj -- ) inst-objects add: ;m :m at: ( idx -- obj ) inst-objects at: ;m ;class diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/jq/add-a-variable-to-a-class-instance-at-runtime-1.jq b/Task/Add-a-variable-to-a-class-instance-at-runtime/Jq/add-a-variable-to-a-class-instance-at-runtime-1.jq similarity index 100% rename from Task/Add-a-variable-to-a-class-instance-at-runtime/jq/add-a-variable-to-a-class-instance-at-runtime-1.jq rename to Task/Add-a-variable-to-a-class-instance-at-runtime/Jq/add-a-variable-to-a-class-instance-at-runtime-1.jq diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/jq/add-a-variable-to-a-class-instance-at-runtime-2.jq b/Task/Add-a-variable-to-a-class-instance-at-runtime/Jq/add-a-variable-to-a-class-instance-at-runtime-2.jq similarity index 100% rename from Task/Add-a-variable-to-a-class-instance-at-runtime/jq/add-a-variable-to-a-class-instance-at-runtime-2.jq rename to Task/Add-a-variable-to-a-class-instance-at-runtime/Jq/add-a-variable-to-a-class-instance-at-runtime-2.jq 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.kotlin new file mode 100644 index 0000000000..6e9c52a98e --- /dev/null +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Kotlin/add-a-variable-to-a-class-instance-at-runtime.kotlin @@ -0,0 +1,30 @@ +// version 1.1.2 + +class SomeClass { + val runtimeVariables = mutableMapOf() +} + +fun main(args: Array) { + val sc = SomeClass() + println("Create two variables at runtime: ") + for (i in 1..2) { + println(" Variable #$i:") + print(" Enter name : ") + val name = readLine()!! + print(" Enter value : ") + val value = readLine()!! + sc.runtimeVariables.put(name, value) + println() + } + while (true) { + print("Which variable do you want to inspect ? ") + val name = readLine()!! + val value = sc.runtimeVariables[name] + if (value == null) { + println("There is no variable of that name, try again") + } else { + println("Its value is '${sc.runtimeVariables[name]}'") + return + } + } +} diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/OoRexx/add-a-variable-to-a-class-instance-at-runtime-1.rexx b/Task/Add-a-variable-to-a-class-instance-at-runtime/OoRexx/add-a-variable-to-a-class-instance-at-runtime-1.rexx new file mode 100644 index 0000000000..1fd032b43e --- /dev/null +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/OoRexx/add-a-variable-to-a-class-instance-at-runtime-1.rexx @@ -0,0 +1,37 @@ +d = .dynamicvar~new +d~foo = 123 +say d~foo + +d2 = .dynamicvar2~new +d~bar = "Fred" +say d~bar + +-- a class that allows dynamic variables. Since this is a mixin, this +-- capability can be added to any class using multiple inheritance +::class dynamicvar MIXINCLASS object +::method init + expose variables + variables = .directory~new + +-- the UNKNOWN method is invoked for all unknown messages. We turn this +-- into either an assignment or a retrieval for the desired item +::method unknown + expose variables + use strict arg messageName, arguments + + -- assignment messages end with '=', which tells us what to do + if messageName~right(1) == '=' then do + variables[messageName~left(messageName~length - 1)] = arguments[1] + end + else do + return variables[messageName] + end + + +-- this class is not a direct subclass of dynamicvar, but mixes in the +-- functionality using multiple inheritance +::class dynamicvar2 inherit dynamicvar +::method init + -- mixin init methods are not automatically invoked, so we must + -- explicitly invoke this + self~init:.dynamicvar diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/OoRexx/add-a-variable-to-a-class-instance-at-runtime-2.rexx b/Task/Add-a-variable-to-a-class-instance-at-runtime/OoRexx/add-a-variable-to-a-class-instance-at-runtime-2.rexx new file mode 100644 index 0000000000..f25c452394 --- /dev/null +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/OoRexx/add-a-variable-to-a-class-instance-at-runtime-2.rexx @@ -0,0 +1,35 @@ +d = .dynamicvar~new +d~foo = 123 +say d~foo + +-- a class that allows dynamic variables. Since this is a mixin, this +-- capability can be added to any class using multiple inheritance +::class dynamicvar MIXINCLASS object +::method init + expose variables + variables = .directory~new + +-- the unknown method will get invoked any time an unknown method is +-- used. This UNKNOWN method will add attribute methods for the given +-- name that will be available on all subsequent uses. +::method unknown + expose variables + use strict arg messageName, arguments + + -- check for an assignment or fetch, and get the proper + -- method name + if messageName~right(1) == '=' then do + variableName = messageName~left(messageName~length - 1) + end + else do + variableName = messageName + end + + -- define a pair of methods to set and retrieve the instance variable. These are + -- created at the object scope + self~setMethod(variableName, 'expose' variableName'; return' variableName) + self~setMethod(variableName'=', 'expose' variableName'; use strict arg value;' variableName '= value' ) + + -- reinvoke the original message. This will now go to the dynamically added + methods + forward to(self) message(messageName) arguments(arguments) diff --git a/Task/Address-of-a-variable/Astro/address-of-a-variable.astro b/Task/Address-of-a-variable/Astro/address-of-a-variable.astro new file mode 100644 index 0000000000..9c2eaee744 --- /dev/null +++ b/Task/Address-of-a-variable/Astro/address-of-a-variable.astro @@ -0,0 +1,4 @@ +var x = 12 +var pointer = ptr(x) # get pointer +print pointer # print address +pointer.set 0xFFFE # set the address diff --git a/Task/Address-of-a-variable/D/address-of-a-variable-3.d b/Task/Address-of-a-variable/D/address-of-a-variable-3.d index 65c2a04524..16cc75b13a 100644 --- a/Task/Address-of-a-variable/D/address-of-a-variable-3.d +++ b/Task/Address-of-a-variable/D/address-of-a-variable-3.d @@ -1,5 +1,6 @@ void test(ref int i) { - writefln(&i); + import std.stdio; + writeln(&i); } void main() { diff --git a/Task/Address-of-a-variable/Kotlin/address-of-a-variable.kotlin b/Task/Address-of-a-variable/Kotlin/address-of-a-variable.kotlin new file mode 100644 index 0000000000..99aebba67a --- /dev/null +++ b/Task/Address-of-a-variable/Kotlin/address-of-a-variable.kotlin @@ -0,0 +1,10 @@ +// Kotlin/Native Technology Preview + +import kotlinx.cinterop.* + +fun main(args: Array) { + val intVar = nativeHeap.alloc() + intVar.value = 42 + with(intVar) { println("Value is $value, address is $rawPtr") } + nativeHeap.free(intVar) +} diff --git a/Task/Address-of-a-variable/PL-I/address-of-a-variable.pli b/Task/Address-of-a-variable/PL-I/address-of-a-variable.pli index c346686e30..3786c7a23f 100644 --- a/Task/Address-of-a-variable/PL-I/address-of-a-variable.pli +++ b/Task/Address-of-a-variable/PL-I/address-of-a-variable.pli @@ -1,3 +1,33 @@ +declare addr builtin; /* retrieve address of a variable */ +declare ptradd builtin; /* pointer addition */ +declare cstg builtin; /* retrieve length of the storage of a variable */ +declare hbound builtin; /* retrieve the number of elements in an array */ + declare p pointer; -k = addr(b); /* Obtain address of variable, stored in integer variable k */ -p = addr(q); /* assigns address to pointer variable p. */ +declare i bin fixed(31) init(42); +p = addr(i); /* Obtain address of variable, stored in integer variable k */ + +/* how to read a string bit by bit - example for pointerAdd */ +/* we built a pointer (movingPointer), which will move through the */ +/* storage of a variable (exampleTxt). attached to the pointer is */ +/* an array of bits (movingBit) - this means wherever the pointer */ +/* is pointing to, this will also be the position of the array. */ +/* only whole bytes can be addressed. to get down to the single bits, */ +/* an array of 8 bits is used. */ + +declare exampleTxt char(16) init('Hello MainFrame!); +declare movingPointer pointer; +declare movingBit(8) bit(01) based(movingPointer); + +declare walkOffset bin fixed(31); +declare walkBit bin fixed(31); + +do walkOffset = 0 to cstg(exampleTxt)-1; + movingPointer = ptradd(addr(exampleTxt, walkOffset); + + do walkBit = 1 to hbound(movingBit); + put skip list( 'bit at Byte ' !!walkOffset + !!' and position '!!walkBit + !!' is ' !!movingBit(walkBit)); + end; +end; diff --git a/Task/Address-of-a-variable/Rust/address-of-a-variable-1.rust b/Task/Address-of-a-variable/Rust/address-of-a-variable-1.rust index 5eaa1241d9..128957ad54 100644 --- a/Task/Address-of-a-variable/Rust/address-of-a-variable-1.rust +++ b/Task/Address-of-a-variable/Rust/address-of-a-variable-1.rust @@ -1,2 +1,11 @@ -let var = 1; -println!("address of var: {:p}", &var); +let v1 = vec![vec![1,2,3]; 10]; +println!("Original address: {:p}", &v1); +let mut v2; +// Override rust protections on reading from uninitialized memory +unsafe {v2 = mem::uninitialized();} +let addr = &mut v2 as *mut _; + +// ptr::write() though it takes v1 by value, v1s destructor is not run when it goes out of +// scope, which is good since then we'd have a vector of free'd vectors +unsafe {ptr::write(addr, v1)} +println!("New address: {:p}", &v2); diff --git a/Task/Address-of-a-variable/Rust/address-of-a-variable-2.rust b/Task/Address-of-a-variable/Rust/address-of-a-variable-2.rust index 9b1bed0267..5eaa1241d9 100644 --- a/Task/Address-of-a-variable/Rust/address-of-a-variable-2.rust +++ b/Task/Address-of-a-variable/Rust/address-of-a-variable-2.rust @@ -1,5 +1,2 @@ -let address: usize = 0x7ffc8f303130; -unsafe { - let val = *(address as *const usize); - println!("value at {}: {:?}", address, val); -} +let var = 1; +println!("address of var: {:p}", &var); diff --git a/Task/Address-of-a-variable/Rust/address-of-a-variable-3.rust b/Task/Address-of-a-variable/Rust/address-of-a-variable-3.rust index 78261501f5..9b1bed0267 100644 --- a/Task/Address-of-a-variable/Rust/address-of-a-variable-3.rust +++ b/Task/Address-of-a-variable/Rust/address-of-a-variable-3.rust @@ -1,3 +1,5 @@ +let address: usize = 0x7ffc8f303130; unsafe { - *(0x7ffc8f303130 as *mut usize) = 1; + let val = *(address as *const usize); + println!("value at {}: {:?}", address, val); } diff --git a/Task/Address-of-a-variable/Rust/address-of-a-variable-4.rust b/Task/Address-of-a-variable/Rust/address-of-a-variable-4.rust new file mode 100644 index 0000000000..b28ebf7809 --- /dev/null +++ b/Task/Address-of-a-variable/Rust/address-of-a-variable-4.rust @@ -0,0 +1,5 @@ +unsafe { + *(0x7ffc8f303130 as *mut usize) = 1; + // Note that this invokes undefined behavior if 0x7ffc8f303130 is uninitialized. In that case, std::ptr::write should be used. + std::ptr::write(0x7ffc8f303130 as *mut usize, 1); +} diff --git a/Task/Address-of-a-variable/Swift/address-of-a-variable.swift b/Task/Address-of-a-variable/Swift/address-of-a-variable.swift index 99aa87aae4..7ad5ffe7e1 100644 --- a/Task/Address-of-a-variable/Swift/address-of-a-variable.swift +++ b/Task/Address-of-a-variable/Swift/address-of-a-variable.swift @@ -1,31 +1,29 @@ -class MyClass { -} +class MyClass { } -func printPointer(ptr: UnsafePointer) { - println(ptr) +func printAddress(of pointer: UnsafePointer) { + print(pointer) } func test() { - var x = 42 - var y = 3.14 - var z = "foo" - var obj = MyClass() + var x = 42 + var y = 3.14 + var z = "foo" + var obj = MyClass() - // Use a pointer to a variable on the stack and print its address - withUnsafePointer(&x) { ptr in println(ptr) } - withUnsafePointer(&y) { ptr in println(ptr) } - withUnsafePointer(&z) { ptr in println(ptr) } - withUnsafePointer(&obj) { ptr in println(ptr) } + // Use a pointer to a variable on the stack and print its address. + withUnsafePointer(to: &x) { print($0) } + withUnsafePointer(to: &y) { print($0) } + withUnsafePointer(to: &z) { print($0) } + withUnsafePointer(to: &obj) { print($0) } - // Alternately: - printPointer(&x) - printPointer(&y) - printPointer(&z) - printPointer(&obj) + // Alternately: + printAddress(of: &x) + printAddress(of: &y) + printAddress(of: &z) + printAddress(of: &obj) - // Printing the address of an object that an object reference points to - // In Swift 3, unsafeAddress is removed - println(Unmanaged.passUnretained(obj).toOpaque()) + // Printing the address of an object that an object reference points to. + print(Unmanaged.passUnretained(obj).toOpaque()) } test() diff --git a/Task/Align-columns/00DESCRIPTION b/Task/Align-columns/00DESCRIPTION index 9fb3f5a107..3be0adace9 100644 --- a/Task/Align-columns/00DESCRIPTION +++ b/Task/Align-columns/00DESCRIPTION @@ -20,3 +20,4 @@ Note that: # Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal. # The minimum space between columns should be computed from the text and not hard-coded. # It is ''not'' a requirement to add separating characters between or around columns. +

diff --git a/Task/Align-columns/AppleScript/align-columns.applescript b/Task/Align-columns/AppleScript/align-columns.applescript index 4b9c3d3d06..54f9e402b6 100644 --- a/Task/Align-columns/AppleScript/align-columns.applescript +++ b/Task/Align-columns/AppleScript/align-columns.applescript @@ -1,3 +1,5 @@ +-- COLUMN ALIGNMENTS --------------------------------------------------------- + property pstrLines : ¬ "Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" & ¬ "are$delineated$by$a$single$'dollar'$character,$write$a$program\n" & ¬ @@ -10,29 +12,15 @@ property eLeft : -1 property eCenter : 0 property eRight : 1 -on run - set lstCols to lineColumns("$", pstrLines) - - script testAlignment - on lambda(eAlign) - columnsAligned(eAlign, lstCols) - end lambda - end script - - intercalate(return & return, ¬ - map(testAlignment, {eLeft, eRight, eCenter})) -end run - - -- columnsAligned :: EnumValue -> [[String]] -> String on columnsAligned(eAlign, lstCols) -- padwords :: Int -> [String] -> [[String]] script padwords - on lambda(n, lstWords) + on |λ|(n, lstWords) -- pad :: String -> String script pad - on lambda(str) + on |λ|(str) set lngPad to n - (length of str) if eAlign = my eCenter then set lngHalf to lngPad div 2 @@ -45,11 +33,11 @@ on columnsAligned(eAlign, lstCols) {replicate(lngPad, space), str, ""} end if end if - end lambda + end |λ| end script map(pad, lstWords) - end lambda + end |λ| end script unlines(map(my unwords, ¬ @@ -61,9 +49,9 @@ end columnsAligned on lineColumns(strColDelim, strText) -- _words :: Text -> [Text] script _words - on lambda(str) + on |λ|(str) splitOn(strColDelim, str) - end lambda + end |λ| end script set lstRows to map(_words, splitOn(linefeed, pstrLines)) @@ -71,9 +59,9 @@ on lineColumns(strColDelim, strText) -- fullRow :: [[a]] -> [[a]] script fullRow - on lambda(lst) + on |λ|(lst) lst & replicate(nCols - (length of lst), {""}) - end lambda + end |λ| end script transpose(map(fullRow, lstRows)) @@ -81,19 +69,56 @@ end lineColumns -- widest [a] -> Int on widest(xs) - script maxLen - on lambda(a, x) - set lng to length of x - cond(lng > a, lng, a) - end lambda - end script - - foldl(maxLen, 0, xs) + |length|(maximumBy(comparing(my |length|), xs)) end widest +-- TEST ---------------------------------------------------------------------- +on run + set lstCols to lineColumns("$", pstrLines) + script testAlignment + on |λ|(eAlign) + columnsAligned(eAlign, lstCols) + end |λ| + end script --- GENERIC LIBRARY FUNCTIONS + intercalate(return & return, ¬ + map(testAlignment, {eLeft, eRight, eCenter})) +end run + +-- GENERIC FUNCTIONS --------------------------------------------------------- + +-- comparing :: (a -> b) -> (a -> a -> Ordering) +on comparing(f) + set mf to mReturn(f) + script + on |λ|(a, b) + set x to mf's |λ|(a) + set y to mf's |λ|(b) + if x < y then + -1 + else + if x > y then + 1 + else + 0 + end if + end if + end |λ| + end script +end comparing + +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl -- Text -> [Text] -> Text on intercalate(strText, lstText) @@ -103,52 +128,22 @@ on intercalate(strText, lstText) return strJoined end intercalate --- Text -> Text -> [Text] -on splitOn(strDelim, strMain) - set {dlm, my text item delimiters} to {my text item delimiters, strDelim} - set lstParts to text items of strMain - set my text item delimiters to dlm - return lstParts -end splitOn +-- length :: [a] -> Int +on |length|(xs) + length of xs +end |length| --- [Text] -> Text -on unlines(lstLines) - intercalate(linefeed, lstLines) -end unlines - --- [Text] -> Text -on unwords(lstWords) - intercalate(" ", lstWords) -end unwords - --- transpose :: [[a]] -> [[a]] -on transpose(xss) - script column - on lambda(_, iCol) - script row - on lambda(xs) - item iCol of xs - end lambda - end script - - map(row, xss) - end lambda - end script - - map(column, item 1 of xss) -end transpose - --- foldl :: (a -> b -> a) -> a -> [b] -> a -on foldl(f, startValue, xs) - tell mReturn(f) - set v to startValue - set lng to length of xs - repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) - end repeat - return v - end tell -end foldl +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn -- map :: (a -> b) -> [a] -> [b] on map(f, xs) @@ -156,34 +151,36 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map --- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -on zipWith(f, xs, ys) - set lng to length of xs - if lng is not length of ys then return missing value +-- maximumBy :: (a -> a -> Ordering) -> [a] -> a +on maximumBy(f, xs) + set cmp to mReturn(f) + script max + on |λ|(a, b) + if a is missing value or cmp's |λ|(a, b) < 0 then + b + else + a + end if + end |λ| + end script - tell mReturn(f) - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, item i of ys) - end repeat - return lst - end tell -end zipWith + foldl(max, missing value, xs) +end maximumBy --- cond :: Bool -> a -> a -> a -on cond(bool, f, g) - if bool then - f +-- min :: Ord a => a -> a -> a +on min(x, y) + if y < x then + y else - g + x end if -end cond +end min -- Egyptian multiplication - progressively doubling a list, appending -- stages of doubling to an accumulator where needed for binary @@ -191,7 +188,11 @@ end cond -- replicate :: Int -> a -> [a] on replicate(n, a) - set out to cond(class of a is string, "", {}) + if class of a is string then + set out to "" + else + set out to {} + end if if n < 1 then return out set dbl to a @@ -203,14 +204,49 @@ on replicate(n, a) return out & dbl end replicate --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn +-- Text -> Text -> [Text] +on splitOn(strDelim, strMain) + set {dlm, my text item delimiters} to {my text item delimiters, strDelim} + set lstParts to text items of strMain + set my text item delimiters to dlm + return lstParts +end splitOn + +-- transpose :: [[a]] -> [[a]] +on transpose(xss) + script column + on |λ|(_, iCol) + script row + on |λ|(xs) + item iCol of xs + end |λ| + end script + + map(row, xss) + end |λ| + end script + + map(column, item 1 of xss) +end transpose + +-- [Text] -> Text +on unlines(lstLines) + intercalate(linefeed, lstLines) +end unlines + +-- [Text] -> Text +on unwords(lstWords) + intercalate(" ", lstWords) +end unwords + +-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] +on zipWith(f, xs, ys) + set lng to min(length of xs, length of ys) + set lst to {} + tell mReturn(f) + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, item i of ys) + end repeat + return lst + end tell +end zipWith diff --git a/Task/Align-columns/BBC-BASIC/align-columns.bbc b/Task/Align-columns/BASIC/align-columns-1.basic similarity index 100% rename from Task/Align-columns/BBC-BASIC/align-columns.bbc rename to Task/Align-columns/BASIC/align-columns-1.basic diff --git a/Task/Align-columns/BASIC/align-columns-2.basic b/Task/Align-columns/BASIC/align-columns-2.basic new file mode 100644 index 0000000000..dc332f08cc --- /dev/null +++ b/Task/Align-columns/BASIC/align-columns-2.basic @@ -0,0 +1,66 @@ +10 rem ******************************** +20 rem print words in columns +30 rem commodore basic 2.0 +40 rem ******************************** +50 print chr$(14) : rem change to upper/lower case set +60 gosub 140 : rem find length of longest word +70 algn$ = "left" +80 gosub 260 : rem print aligned text +90 algn$ = "center" +100 gosub 260 +110 algn$ = "right" +120 gosub 260 +130 end +140 rem *** find length of longest word +150 mx=0 +160 for i=1 to 6 +170 read a$ +180 n=1 +190 for j=1 to len(a$) +200 if mid$(a$,j,1)<>"$" then n=n+1: goto 230 +210 if mx"$" then n=n+1 : goto 380 +360 gosub 440 : rem print word +370 n=1 +380 next +390 if n>1 then gosub 440 +400 next +410 print +420 return +430 rem ********* print word ********** +440 b$ = mid$(a$,j-n+1,n-1) +450 b = len(b$) +460 if algn$ = "center" then 520 +470 if algn$ = "right" then 570 +480 if c+b<40 and c+mx>40 then print b$: c=1: return +490 if c+mx>40 then print : c=1 +500 print b$;left$(s$,mx-b);: c=c+mx +510 return +520 if c+mx>40 then print : c=1 +530 bb=(mx-b)/2 : ba=bb +540 if bb>1 and int(bb)=bb then ba=bb-1 +550 print left$(s$,ba);b$;left$(s$,bb);: c=c+mx +560 return +570 if c+mx>40 then print : c=1 +580 print left$(s$,mx-b);b$;: c=c+mx +590 return +600 rem *********** the words ********* +610 data "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" +620 data "are$delineated$by$a$single$'dollar'$character,$write$a$program" +630 data "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" +640 data "column$are$separated$by$at$least$one$space." +650 data "Further,$allow$for$each$word$in$a$column$to$be$either$left$" +660 data "justified,$right$justified,$or$center$justified$within$its$column" diff --git a/Task/Align-columns/Elixir/align-columns.elixir b/Task/Align-columns/Elixir/align-columns.elixir index fb4f2508d6..5ccfa41418 100644 --- a/Task/Align-columns/Elixir/align-columns.elixir +++ b/Task/Align-columns/Elixir/align-columns.elixir @@ -1,7 +1,7 @@ defmodule Align do def columns(text, alignment) do fieldsbyrow = String.split(text, "\n", trim: true) - |> Enum.map(fn line -> String.split(line, "$", trim: true) end) + |> Enum.map(fn row -> String.split(row, "$", trim: true) end) maxfields = Enum.map(fieldsbyrow, fn field -> length(field) end) |> Enum.max colwidths = Enum.map(fieldsbyrow, fn field -> field ++ List.duplicate("", maxfields - length(field)) end) |> List.zip @@ -15,9 +15,9 @@ defmodule Align do end) end - defp adjust(field, width, :Left), do: String.ljust(field, width) - defp adjust(field, width, :Right), do: String.rjust(field, width) - defp adjust(field, width, _), do: :string.centre(String.to_char_list(field), width) + defp adjust(field, width, :Left), do: String.pad_trailing(field, width) + defp adjust(field, width, :Right), do: String.pad_leading(field, width) + defp adjust(field, width, _), do: :string.centre(String.to_charlist(field), width) end text = """ diff --git a/Task/Align-columns/Gambas/align-columns.gambas b/Task/Align-columns/Gambas/align-columns.gambas new file mode 100644 index 0000000000..2cc2c69177 --- /dev/null +++ b/Task/Align-columns/Gambas/align-columns.gambas @@ -0,0 +1,44 @@ +Public Sub Main() 'Written in Gambas 3.9.2 as a Command line Application - 15/03/2017 +Dim siCount, siCounter, siLength As Short 'Counters +Dim siLongest As Short = -1 'To store the longest 'Word' +Dim sLine, sRows As New String[] 'Arrays +Dim sTemp, sAlign As String 'Temp strings +Dim sInput As String = "Given$a$text$file$of$many$lines, $where$fields$within$a$line$" & "\n" +"are$delineated$by$a$single$ 'dollar'$character,$write$a$program" & "\n" +"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" & "\n" +"column$are$separated$by$at$least$one$space." & "\n" +"Further, $allow$for$each$word$in$a$column$to$be$either$left$" & "\n" +"justified, $right$justified, $or$center$justified$within$its$column." 'Main string (with End Of Line characters added) + +For Each sTemp In Split(sInput, "\n") 'For each Line (split by End of Line character).. + sLine.add(sTemp) 'Add the Line to sLine array +Next + +For siCount = 0 To sLine.Max 'For each of Lines in the array.. + For Each sTemp In Split(sLine[siCount], "$") 'For each 'Word' in the Line (Split by the '$') + siLength = Len(sTemp) 'Store the length of the current 'Word' + If siLength > siLongest Then siLongest = siLength 'Make sure siLength has the length of the longest 'Word' + sRows.add(Trim(sTemp)) 'Create an array of the 'Words' + Next + sRows.add("\n") 'Add a End Of Line character to the sRows array +Next + +For siCounter = 0 To 2 'For each alignment (Left, Right and Centre) + For Each sTemp In sRows 'For each 'Word' in the sRows array.. + If sTemp = "\n" Then 'If it's a End Of Line character then.. + Print 'Print + Continue 'Jump to the next iteration of the For Next Loop + Endif + If siCounter = 0 Then Print sTemp & Space(siLongest - Len(sTemp)); 'Print control for Left align + If siCounter = 1 Then Print Space(siLongest - Len(sTemp)) & sTemp; 'Print control for Right align + If siCounter = 2 Then 'Print control for Centre align + siCount = (siLongest - Len(sTemp)) / 2 'Difference between the length of the longest 'Word' and the current 'Word' / 2 + sAlign = Space(siCount) & sTemp & Space(siCount) 'Put the string together for printing + If Len(sAlign) < siLongest Then sAlign &= " " 'Check it's the correct length if not add a space on the end + Print sAlign; 'Print the 'Word' + Endif + Next + Print 'Print an empty line between each alignment list +Next + +End diff --git a/Task/Align-columns/Haskell/align-columns-1.hs b/Task/Align-columns/Haskell/align-columns-1.hs new file mode 100644 index 0000000000..c1a7b15212 --- /dev/null +++ b/Task/Align-columns/Haskell/align-columns-1.hs @@ -0,0 +1,26 @@ +import Data.List (unfoldr, transpose) +import Control.Arrow (second) + +dat = + "Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" ++ + "are$delineated$by$a$single$'dollar'$character,$write$a$program\n" ++ + "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n" ++ + "column$are$separated$by$at$least$one$space.\n" ++ + "Further,$allow$for$each$word$in$a$column$to$be$either$left$\n" ++ + "justified,$right$justified,$or$center$justified$within$its$column.\n" + +brkdwn = + takeWhile (not . null) . unfoldr (Just . second (drop 1) . span ('$' /=)) + +format j ls = map (unwords . zipWith align colw) rows + where + rows = map brkdwn $ lines ls + colw = map (maximum . map length) . transpose $ rows + align cw w = + case j of + 'c' -> replicate l ' ' ++ w ++ replicate r ' ' + 'r' -> replicate dl ' ' ++ w + 'l' -> w ++ replicate dl ' ' + where + dl = cw - length w + (l, r) = (dl `div` 2, dl - l) diff --git a/Task/Align-columns/Haskell/align-columns-2.hs b/Task/Align-columns/Haskell/align-columns-2.hs new file mode 100644 index 0000000000..ba3bbc37c1 --- /dev/null +++ b/Task/Align-columns/Haskell/align-columns-2.hs @@ -0,0 +1,35 @@ +import Prelude as P +import Data.Text as T + (Text, pack, unpack, splitOn, unlines, unwords, length, + justifyLeft, justifyRight, center) +import Data.List (transpose, zip, maximumBy) +import Data.Ord (comparing) + +rows :: [[Text]] +rows = + (splitOn (pack "$") . pack) <$> + [ "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" + , "are$delineated$by$a$single$'dollar'$character,$write$a$program" + , "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" + , "column$are$separated$by$at$least$one$space." + , "Further,$allow$for$each$word$in$a$column$to$be$either$left$" + , "justified,$right$justified,$or$center$justified$within$its$column." + ] + +cols :: [[Text]] +cols = + transpose $ + ((++) <*> + (flip P.replicate (pack []) . + (-) (maximum (P.length <$> rows)) . P.length)) <$> + rows + +main :: IO () +main = + mapM_ putStrLn $ + [ (\cols f -> + (unpack . T.unlines) $ + T.unwords <$> transpose ((\(xs, n) -> f (n + 1) ' ' <$> xs) <$> cols)) + (zip cols ((T.length . maximumBy (comparing T.length)) <$> cols)) + ] <*> + [justifyLeft, justifyRight, center] diff --git a/Task/Align-columns/Haskell/align-columns.hs b/Task/Align-columns/Haskell/align-columns.hs deleted file mode 100644 index b57888c269..0000000000 --- a/Task/Align-columns/Haskell/align-columns.hs +++ /dev/null @@ -1,25 +0,0 @@ -import Data.List -import Control.Monad -import Control.Arrow - -dat = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" ++ - "are$delineated$by$a$single$'dollar'$character,$write$a$program\n" ++ - "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n" ++ - "column$are$separated$by$at$least$one$space.\n" ++ - "Further,$allow$for$each$word$in$a$column$to$be$either$left$\n" ++ - "justified,$right$justified,$or$center$justified$within$its$column.\n" - -brkdwn = takeWhile (not.null) . unfoldr (Just . second (drop 1) . span ('$'/=)) - -format j ls = map (unwords. zipWith align colw) rows - where - rows = map brkdwn $ lines ls - colw = map (maximum. map length) . transpose $ rows - align cw w = - case j of - 'c' -> (replicate l ' ') ++ w ++ (replicate r ' ') - 'r' -> (replicate dl ' ') ++ w - 'l' -> w ++ (replicate dl ' ') - where - dl = cw-length w - (l,r) = (dl `div` 2, dl-l) diff --git a/Task/Align-columns/jq/align-columns-1.jq b/Task/Align-columns/Jq/align-columns-1.jq similarity index 100% rename from Task/Align-columns/jq/align-columns-1.jq rename to Task/Align-columns/Jq/align-columns-1.jq diff --git a/Task/Align-columns/jq/align-columns-2.jq b/Task/Align-columns/Jq/align-columns-2.jq similarity index 100% rename from Task/Align-columns/jq/align-columns-2.jq rename to Task/Align-columns/Jq/align-columns-2.jq diff --git a/Task/Align-columns/jq/align-columns-3.jq b/Task/Align-columns/Jq/align-columns-3.jq similarity index 100% rename from Task/Align-columns/jq/align-columns-3.jq rename to Task/Align-columns/Jq/align-columns-3.jq diff --git a/Task/Align-columns/Kotlin/align-columns.kotlin b/Task/Align-columns/Kotlin/align-columns.kotlin index a02f891b04..abf2c69f81 100644 --- a/Task/Align-columns/Kotlin/align-columns.kotlin +++ b/Task/Align-columns/Kotlin/align-columns.kotlin @@ -1,10 +1,8 @@ -package column_alignment - import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Paths -enum class Align_function { +enum class AlignFunction { LEFT { override fun invoke(s: String, l: Int) = ("%-" + l + 's').format(("%" + s.length + 's').format(s)) }, RIGHT { override fun invoke(s: String, l: Int) = ("%-" + l + 's').format(("%" + l + 's').format(s)) }, CENTER { override fun invoke(s: String, l: Int) = ("%-" + l + 's').format(("%" + ((l + s.length) / 2) + 's').format(s)) }; @@ -16,8 +14,8 @@ enum class Align_function { * @constructor Initializes columns aligner from lines in a list of strings. * @property lines Lines in a single string. Empty string does form a column. */ -class Column_aligner(val lines: List) { - operator fun invoke(a: Align_function) : String { +class ColumnAligner(val lines: List) { + operator fun invoke(a: AlignFunction) : String { var result = "" for (lineWords in words) { for (i in lineWords.indices) { @@ -38,26 +36,28 @@ class Column_aligner(val lines: List) { lines.forEach { val lineWords = java.lang.String(it).split("\\$") words += lineWords - for (i in lineWords.indices) - if (i >= column_widths.size) + for (i in lineWords.indices) { + if (i >= column_widths.size) { column_widths += lineWords[i].length - else + } else { column_widths[i] = Math.max(column_widths[i], lineWords[i].length) + } + } } } } fun main(args: Array) { - if (args.size < 1) + if (args.isEmpty()) { println("Usage: ColumnAligner file [L|R|C]") - else { - val ca = Column_aligner(Files.readAllLines(Paths.get(args[0]), StandardCharsets.UTF_8)) - val alignment = if (args.size >= 2) args[1] else "L" - when (alignment) { - "L" -> print(ca(Align_function.LEFT)) - "R" -> print(ca(Align_function.RIGHT)) - "C" -> print(ca(Align_function.CENTER)) - else -> System.err.println("Error! Unknown alignment: " + alignment) - } + return + } + val ca = ColumnAligner(Files.readAllLines(Paths.get(args[0]), StandardCharsets.UTF_8)) + val alignment = if (args.size >= 2) args[1] else "L" + when (alignment) { + "L" -> print(ca(AlignFunction.LEFT)) + "R" -> print(ca(AlignFunction.RIGHT)) + "C" -> print(ca(AlignFunction.CENTER)) + else -> System.err.println("Error! Unknown alignment: " + alignment) } } diff --git a/Task/Align-columns/Nim/align-columns.nim b/Task/Align-columns/Nim/align-columns.nim index 02ee86e0e9..fe2cec8821 100644 --- a/Task/Align-columns/Nim/align-columns.nim +++ b/Task/Align-columns/Nim/align-columns.nim @@ -1,4 +1,6 @@ -import strutils, sequtils, strfmt +from strutils import splitLines, split +from sequtils import mapIt +from strfmt import format, write let textinfile = """Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program @@ -7,16 +9,17 @@ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.""" -var words = textinfile.splitLines.mapIt(seq[string], it.split '$') -var maxs = newSeq[int](max words.mapIt(int, it.len)) +var words = textinfile.splitLines.mapIt(it.split '$') +var maxs = newSeq[int](max words.mapIt(it.len)) -for l in words: - for j,w in l: +for line in words: + for j,w in line: maxs[j] = max(maxs[j], w.len+1) for i, align in ["<",">","^"]: echo(["Left", "Right", "Center"][i], " column-aligned output:") - for l in words: - for j,w in l: - stdout.write w.format align & $maxs[j] + for line in words: + for j,w in line: + stdout.write(w.format align & $maxs[j]) stdout.write "\n" + stdout.write "\n" diff --git a/Task/Align-columns/Nit/align-columns.nit b/Task/Align-columns/Nit/align-columns.nit new file mode 100644 index 0000000000..a7df4d8a17 --- /dev/null +++ b/Task/Align-columns/Nit/align-columns.nit @@ -0,0 +1,49 @@ +# Task: Align columns +# +# Uses `Text::justify` from the standard library. +module align_columns + +fun aligner(text: String, left: Float) +do + # Each row is a sequence of fields + var rows = new Array[Array[String]] + for line in text.split('\n') do + rows.add line.split("$") + end + + # Compute the final length of each column + var lengths = new Array[Int] + for fields in rows do + var i = 0 + for field in fields do + var fl = field.length + if lengths.length <= i or fl > lengths[i] then + lengths[i] = fl + end + i += 1 + end + end + + # Process each line and align each field + for fields in rows do + var line = new Array[String] + var i = 0 + for field in fields do + line.add field.justify(lengths[i], left) + i += 1 + end + print line.join(" ") + end +end + +var text = """ +Given$a$text$file$of$many$lines,$where$fields$within$a$line$ +are$delineated$by$a$single$'dollar'$character,$write$a$program +that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ +column$are$separated$by$at$least$one$space. +Further,$allow$for$each$word$in$a$column$to$be$either$left$ +justified,$right$justified,$or$center$justified$within$its$column.""" + +aligner(text, 0.0) +aligner(text, 1.0) +aligner(text, 0.5) diff --git a/Task/Align-columns/OoRexx/align-columns.rexx b/Task/Align-columns/OoRexx/align-columns.rexx new file mode 100644 index 0000000000..4b5cc88331 --- /dev/null +++ b/Task/Align-columns/OoRexx/align-columns.rexx @@ -0,0 +1,74 @@ +text = .array~of("Given$a$text$file$of$many$lines,$where$fields$within$a$line$", - + "are$delineated$by$a$single$'dollar'$character,$write$a$program", - + "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$", - + "column$are$separated$by$at$least$one$space.", - + "Further,$allow$for$each$word$in$a$column$to$be$either$left$", - + "justified,$right$justified,$or$center$justified$within$its$column.") + +columns = 0 +parsedText = .array~new +-- split each line of text into words and figure out how many columns we need +loop line over text + parsedLine = line~makearray("$") + parsedText~append(parsedLine) + columns = max(columns, parsedLine~items) +end + +-- now figure out how wide we need to make each column +columnWidths = .array~new(columns) +linelength = 0 +loop i = 1 to columns + width = 0 + loop line over parsedText + word = line[i] + if word \= .nil then width = max(width, word~length) + end + columnWidths[i] = width + -- keep track of the total width, including space for a separator + linelength += width + 1 +end + +say "align left:" +say +out = .mutableBuffer~new(linelength) +loop line over parsedText + -- mutable buffers are more efficient than repeated string concats + -- reset the working buffer to zero + out~setbuffersize(0) + loop col = 1 to line~items + word = line[col] + if word == .nil then word = '' + out~append(word~left(columnwidths[col] + 1)) + end + say out~string +end +say +say "align right:" +say + +loop line over parsedText + -- mutable buffers are more efficient than repeated string concats + -- reset the working buffer to zero + out~setbuffersize(0) + loop col = 1 to line~items + word = line[col] + if word == .nil then word = '' + out~append(word~right(columnwidths[col] + 1)) + end + say out~string +end +say +say "align center:" +say + +loop line over parsedText + -- mutable buffers are more efficient than repeated string concats + -- reset the working buffer to zero + out~setbuffersize(0) + loop col = 1 to line~items + word = line[col] + if word == .nil then word = '' + out~append(word~center(columnwidths[col] + 1)) + end + say out~string +end diff --git a/Task/Align-columns/REXX/align-columns-2.rexx b/Task/Align-columns/REXX/align-columns-2.rexx index 2acf00cc06..a7ce885e5d 100644 --- a/Task/Align-columns/REXX/align-columns-2.rexx +++ b/Task/Align-columns/REXX/align-columns-2.rexx @@ -1,34 +1,32 @@ -/*REXX program displays various alignments for words in a text string.*/ -cols=0; size=0; wid.=0; t.=; @.= /*zero|nullify some variables*/ - /* [↓] some "text" lines. */ +/*REXX program displays various alignments for words in an array of text strings. */ +cols=0; size=0; wid.=0; t.=; @.= /*zero or nullify some variables. */ + /* [↓] some "text" lines. */ t.1 = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" t.2 = "are$delineated$by$a$single$'dollar'$character,$write$a$program" t.3 = "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" t.4 = "column$are$separated$by$at$least$one$space." t.5 = "Further,$allow$for$each$word$in$a$column$to$be$either$left$" t.6 = "justified,$right$justified,$or$center$justified$within$its$column." - /* [↑] a null line is the end*/ - do r=1 while t.r\=='' /* [↓] process all text lines*/ - _=strip(t.r,,'$') /*strip leading & trailing $.*/ - do c=1 until _=='' /* [↓] process each word. */ - parse var _ @.r.c '$' _ - wid.c=max(wid.c, length(@.r.c)) /*max word width.*/ + /* [↑] a null line is the end of text.*/ + do r=1 while t.r\=='' /* [↓] process all the text lines. */ + _=strip(t.r,,'$') /*strip leading & trailing dollar signs*/ + do c=1 until _=='' /* [↓] process each of the words. */ + parse var _ @.r.c '$' _ + wid.c=max(wid.c, length(@.r.c)) /*find the maximum word width. */ end /*c*/ - cols=max(cols,c) /*use the maximum COLS found.*/ + cols=max(cols,c) /*use the maximum COLS found. */ end /*r*/ - do k=1 for cols; size=size+wid.k; end /*find width of biggest line.*/ -rows=r-1 /*adjust ROWS because of DO.*/ - do j=1 for 3; say; say /*show 2 blank lines for sep.*/ - say center(word('left right center', j) "aligned", size+cols-1, "═") - - do r=1 for rows; _= /*build row by row*/ - do c=1 for cols; x=@.r.c /* " col " col*/ - if j==1 then _=_ left(x, wid.c) /*justified left.*/ - if j==2 then _=_ right(x, wid.c) /* " right.*/ - if j==3 then _=_ centre(x, wid.c) /* " center.*/ + do k=1 for cols; size=size+wid.k; end /*find the width of the biggest line. */ +rows=r-1 /*adjust ROWS because of the DO loop.*/ + do j=1 for 3; say; say /*show two blank lines for a separator.*/ + say center(word('left right center', j) "aligned", size+cols-1, "═") /*show title*/ + do r=1 for rows; _= /*construct row by row. */ + do c=1 for cols; x=@.r.c /* " col " col. */ + if j==1 then _=_ left(x, wid.c) /*justified left. */ + if j==2 then _=_ right(x, wid.c) /* " right. */ + if j==3 then _=_ centre(x, wid.c) /* " center. */ end /*c*/ - say substr(_,2) /*ignore the leading extra blank.*/ + say substr(_, 2) /*ignore the leading extra blank. */ end /*r*/ - end /*j*/ - /*stick a fork in it, we're done.*/ + end /*j*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Align-columns/REXX/align-columns-3.rexx b/Task/Align-columns/REXX/align-columns-3.rexx index 4069842473..d83fbdce3c 100644 --- a/Task/Align-columns/REXX/align-columns-3.rexx +++ b/Task/Align-columns/REXX/align-columns-3.rexx @@ -1,40 +1,39 @@ -/*REXX program displays various alignments for words in a text string.*/ -cols=0; size=0; wid.=0; t.=; @.= /*zero|nullify some variables*/ - /* [↓] some "text" lines. */ +/*REXX pgm displays various (boxed) alignments for words in an array of text strings. */ +cols=0; size=0; wid.=0; t.=; @.= /*zero or nullify some variables. */ + /* [↓] some "text" lines. */ t.1 = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" t.2 = "are$delineated$by$a$single$'dollar'$character,$write$a$program" t.3 = "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" t.4 = "column$are$separated$by$at$least$one$space." t.5 = "Further,$allow$for$each$word$in$a$column$to$be$either$left$" t.6 = "justified,$right$justified,$or$center$justified$within$its$column." - /* [↑] a null line is the end*/ - do r=1 while t.r\=='' /* [↓] process all text lines*/ - _=strip(t.r,,'$') /*strip leading & trailing $.*/ - do c=1 until _=='' /* [↓] process each word. */ - parse var _ @.r.c '$' _ - wid.c=max(wid.c, length(@.r.c)) /*max word width.*/ + /* [↑] a null line is the end of text.*/ + do r=1 while t.r\=='' /* [↓] process all the text lines. */ + _=strip(t.r,,'$') /*strip leading & trailing dollar signs*/ + do c=1 until _=='' /* [↓] process each of the words. */ + parse var _ @.r.c '$' _ + wid.c=max(wid.c, length(@.r.c)) /*find the maximum word width. */ end /*c*/ - cols=max(cols,c) /*use the maximum COLS found.*/ + cols=max(cols,c) /*use the maximum COLS found. */ end /*r*/ - do k=1 for cols; size=size+wid.k; end /*find width of biggest line.*/ -rows=r-1 /*adjust ROWS because of DO.*/ - do j=1 for 3; say; say /*show 2 blank lines for sep.*/ - say center(word('left right center', j) "aligned", size+cols+1, "═") + do k=1 for cols; size=size+wid.k; end /*find the width of the biggest line. */ +rows=r-1 /*adjust ROWS because of the DO loop.*/ + do j=1 for 3; say; say /*show two blank lines for a separator.*/ + say center(word('left right center', j) "aligned", size+cols+1, "═") /*show title*/ - do r=0 to rows; _=; !='│'; if r==0 then !='┬' - do c=1 for cols; x=@.r.c - if r==0 then x=copies("─",wid.c+1) - if j==1 then _=_ || ! || left(x,wid.c) - if j==2 then _=_ || ! || right(x,wid.c) - if j==3 then _=_ || ! || centre(x,wid.c) + do r=0 to rows; _=; !='│'; if r==0 then !='┬' + do c=1 for cols; x=@.r.c + if r==0 then x=copies("─", wid.c +1) + if j==1 then _=_ || ! || left(x, wid.c) + if j==2 then _=_ || ! || right(x, wid.c) + if j==3 then _=_ || ! || centre(x, wid.c) end /*c*/ - if r==0 then do; _= '┌'substr(_,2,length(_)-1)"┐" - bot= '└'substr(_,2,length(_)-2)"┘" - end - else _=_ || ! + if r==0 then do; _= '┌'substr(_, 2, length(_) -1)"┐" + bot= '└'substr(_, 2, length(_) -2)"┘" + end + else _=_ || ! say _ - end /*r*/ - /* [↑] shows words in boxes.*/ - say translate(bot,'┴',"┬") - end /*j*/ + end /*r*/ /* [↑] shows words in boxes. */ + say translate(bot, '┴', "┬") + end /*j*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Align-columns/Scheme/align-columns.ss b/Task/Align-columns/Scheme/align-columns.ss new file mode 100644 index 0000000000..a43f49f35e --- /dev/null +++ b/Task/Align-columns/Scheme/align-columns.ss @@ -0,0 +1,53 @@ +(import (scheme base) + (scheme write) + (srfi 1) + (except (srfi 13) string-for-each string-map) + (srfi 14)) + +;; text is a list of lines, alignment is left/right/center +;; displays the aligned text in columns with a single space gap +(define (align-columns text alignment) + (define (split line) ; splits string on $ into list of strings + (string-tokenize line (char-set-complement (->char-set "$")))) + (define (extend lst n) ; extends list to length n, by adding "" to end + (append lst (make-list (- n (length lst)) ""))) + (define (align-word word width) ; align single word to fit width + (case alignment + ((left) (string-pad-right word width)) + ((right) (string-pad word width)) + ((center) (let ((rem (- width (string-length word)))) + (string-pad-right (string-pad word (- width (truncate (/ rem 2)))) + width))))) + ; + (display alignment) (newline) + (let* ((text-list (map split text)) + (max-line-len (fold (lambda (text val) (max (length text) val)) 0 text-list)) + (text-lines (map (lambda (line) (extend line max-line-len)) text-list)) + (min-col-widths (map (lambda (col) + (fold (lambda (line val) + (max (string-length (list-ref line col)) + val)) + 0 + text-lines)) + (iota max-line-len)))) + (map (lambda (line) + (map (lambda (word width) + (display (string-append (align-word word width) + " "))) + line min-col-widths) + (newline)) + text-lines)) + (newline)) + +;; show example +(define *example* + '("Given$a$text$file$of$many$lines,$where$fields$within$a$line$" + "are$delineated$by$a$single$'dollar'$character,$write$a$program" + "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" + "column$are$separated$by$at$least$one$space." + "Further,$allow$for$each$word$in$a$column$to$be$either$left$" + "justified,$right$justified,$or$center$justified$within$its$column.")) + +(align-columns *example* 'left) +(align-columns *example* 'center) +(align-columns *example* 'right) diff --git a/Task/Align-columns/Sed/align-columns.sed b/Task/Align-columns/Sed/align-columns.sed new file mode 100644 index 0000000000..f551707844 --- /dev/null +++ b/Task/Align-columns/Sed/align-columns.sed @@ -0,0 +1,75 @@ +#!/bin/sed -nrf +# Format: \n\n\n\n... +# After reading whole file contains max number of fields of max width each. + +# If no $ at start or end of a line -- add them +/^\$/! s/^/$/ +/\$$/! s/$/$/ + +# First line saved as three lines in hold space: +# \n\n +1{ + h + s/[^$]/ /g + H + G + x + # Restart -- go to next line + b +} + +# For lines 2,3,... +H +# Current line -> pattern +# (each character replaced by constant symbol (e.g. space) so that we can count them) +s/[^$]/ /g +H +G +# Add two markers +s/\$/1$/ +s/(\n[^$]*)\$/\12$/ + +# Compare patterns +:cmp + s/(1\$([^$\n]*)([^$\n]*)[^2]*2\$\2)/\1\3/ + /1\$\n/ bout + # Advance markers + s/1(\$[^12$\n]*)/\11/ + s/2(\$[^12$\n]*)/\12/ + # Add one more field + /^[^2]*2\$\n/{ s/^([^2]*)2\$\n/\12$$\n/; } +bcmp +:out +# Remove first line +s/[^\n]*\n// +# Remove 2$-marker +s/2\$/$/ +x + +${ +# We are on the last line -- start printing + x; + # Add a line for aligned string + s/^/\n/ + :nextline + # Add marker again (only one this time) + s/\$/1$/ + :align + # 1. look up missing spaces, + # 2. put first word of 2nd line before first newline adding missing spaces + # 3. cut first word of 2nd and 3rd lines. + # Replace \5\3 by \3\5 for RIGHT ALIGNMENT + s/(\n[^\n]*)1\$([^$\n]*)([^$\n]*)\$([^\n]*\n)\$([^$\n]*)([^\n]*\n)\$\2\$/\5\3 \1$\2\31$\4\6$/ + talign + # We ate 2nd and 3rd lines completely, except newlines -- remove them + s/\$\n\$\n\$\n/$\n/ + # Print the first line in pattern space + P + # ... and remove it + s/^[^\n]*// + # Remove marker + s/1\$/$/ + # If no more lines -- exit + /\$\n\$$/q + bnextline +} diff --git a/Task/Align-columns/Zkl/align-columns-1.zkl b/Task/Align-columns/Zkl/align-columns-1.zkl new file mode 100644 index 0000000000..bbcd65f8e7 --- /dev/null +++ b/Task/Align-columns/Zkl/align-columns-1.zkl @@ -0,0 +1,16 @@ +fcn format(text,how){ + words:=text.split("$").apply("split").flatten(); + max:=words.reduce(fcn(p,n){ n=n.len(); n>p and n or p },0); + wordsPerCol:=80/(max+1); + fmt:=(switch(how){ + case(-1){ "%%-%ds ".fmt(max).fmt } + case(0) { fcn(max,w){ + a:=(max-w.len())/2; b:=max-w.len() - a; String(" "*a,w," "*b); + }.fp(max) + } + case(1){ "%%%ds ".fmt(max).fmt } + }); + w:=words.walker(); d:=Data(0,Int); + do{ w.pump(wordsPerCol,d,fmt).append("\n") } while(not w.atEnd); + d.text; +} diff --git a/Task/Align-columns/Zkl/align-columns-2.zkl b/Task/Align-columns/Zkl/align-columns-2.zkl new file mode 100644 index 0000000000..3c0a76847e --- /dev/null +++ b/Task/Align-columns/Zkl/align-columns-2.zkl @@ -0,0 +1,11 @@ +text:= +"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" +"are$delineated$by$a$single$'dollar'$character,$write$a$program\n" +"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n" +"column$are$separated$by$at$least$one$space.\n" +"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n" +"justified,$right$justified,$or$center$justified$within$its$column.\n"; + +format(text,-1).print(); +format(text, 0).print(); +format(text, 1).print(); diff --git a/Task/Aliquot-sequence-classifications/00DESCRIPTION b/Task/Aliquot-sequence-classifications/00DESCRIPTION index 9b9729b67a..252d10bd93 100644 --- a/Task/Aliquot-sequence-classifications/00DESCRIPTION +++ b/Task/Aliquot-sequence-classifications/00DESCRIPTION @@ -6,13 +6,13 @@ being K and subsequent members being the sum of the [[Proper divisors]] of the p :
There are several classifications for non termination: :* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''. :* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''. -:* If the N'th term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''. +:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''. :
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... :* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''. :* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''. :
And finally: -:* Some K form aliquot sequences that are not known to be either terminating or periodic. these K are to be called '''non-terminating'''.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140737488355328. +:* Some K form aliquot sequences that are not known to be either terminating or periodic. these K are to be called '''non-terminating'''.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. ;Task: @@ -23,7 +23,9 @@ being K and subsequent members being the sum of the [[Proper divisors]] of the p Show all output on this page. + ;Cf. * [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence). * [[Proper divisors]] * [[Amicable pairs]] +

diff --git a/Task/Aliquot-sequence-classifications/Java/aliquot-sequence-classifications.java b/Task/Aliquot-sequence-classifications/Java/aliquot-sequence-classifications.java index e4de90244e..b13fbac684 100644 --- a/Task/Aliquot-sequence-classifications/Java/aliquot-sequence-classifications.java +++ b/Task/Aliquot-sequence-classifications/Java/aliquot-sequence-classifications.java @@ -1,11 +1,12 @@ -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import java.util.stream.LongStream; -import static java.util.stream.LongStream.rangeClosed; public class AliquotSequenceClassifications { - public static Long properDivsSum(long n) { - return rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); + private static Long properDivsSum(long n) { + return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); } static boolean aliquot(long n, int maxLen, long maxTerm) { @@ -52,8 +53,9 @@ public class AliquotSequenceClassifications { } public static void main(String[] args) { - long[] arr = {11L, 12, 28, 496, 220, 1184, 12496, 1264460, - 790, 909, 562, 1064, 1488}; + long[] arr = { + 11, 12, 28, 496, 220, 1184, 12496, 1264460, + 790, 909, 562, 1064, 1488}; LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47)); System.out.println(); diff --git a/Task/Aliquot-sequence-classifications/jq/aliquot-sequence-classifications-1.jq b/Task/Aliquot-sequence-classifications/Jq/aliquot-sequence-classifications-1.jq similarity index 100% rename from Task/Aliquot-sequence-classifications/jq/aliquot-sequence-classifications-1.jq rename to Task/Aliquot-sequence-classifications/Jq/aliquot-sequence-classifications-1.jq diff --git a/Task/Aliquot-sequence-classifications/jq/aliquot-sequence-classifications-2.jq b/Task/Aliquot-sequence-classifications/Jq/aliquot-sequence-classifications-2.jq similarity index 100% rename from Task/Aliquot-sequence-classifications/jq/aliquot-sequence-classifications-2.jq rename to Task/Aliquot-sequence-classifications/Jq/aliquot-sequence-classifications-2.jq diff --git a/Task/Aliquot-sequence-classifications/Kotlin/aliquot-sequence-classifications.kotlin b/Task/Aliquot-sequence-classifications/Kotlin/aliquot-sequence-classifications.kotlin new file mode 100644 index 0000000000..d81c2e360e --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Kotlin/aliquot-sequence-classifications.kotlin @@ -0,0 +1,62 @@ +// version 1.1.3 + +data class Classification(val sequence: List, val aliquot: String) + +const val THRESHOLD = 1L shl 47 + +fun sumProperDivisors(n: Long): Long { + if (n < 2L) return 0L + val sqrt = Math.sqrt(n.toDouble()).toLong() + var sum = 1L + (2L..sqrt) + .filter { n % it == 0L } + .map { it + n / it } + .sum() + if (sqrt * sqrt == n) sum -= sqrt + return sum +} + +fun classifySequence(k: Long): Classification { + require(k > 0) + var last = k + val seq = mutableListOf(k) + while (true) { + last = sumProperDivisors(last) + seq.add(last) + val n = seq.size + val aliquot = when { + last == 0L -> "Terminating" + n == 2 && last == k -> "Perfect" + n == 3 && last == k -> "Amicable" + n >= 4 && last == k -> "Sociable[${n - 1}]" + last == seq[n - 2] -> "Aspiring" + last in seq.slice(1..n - 3) -> "Cyclic[${n - 1 - seq.indexOf(last)}]" + n == 16 || last > THRESHOLD -> "Non-Terminating" + else -> "" + } + if (aliquot != "") return Classification(seq, aliquot) + } +} + +fun main(args: Array) { + println("Aliqot classifications - periods for Sociable/Cyclic in square brackets:\n") + for (k in 1L..10) { + val (seq, aliquot) = classifySequence(k) + println("${"%2d".format(k)}: ${aliquot.padEnd(15)} $seq") + } + + val la = longArrayOf( + 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488 + ) + println() + + for (k in la) { + val (seq, aliquot) = classifySequence(k) + println("${"%7d".format(k)}: ${aliquot.padEnd(15)} $seq") + } + + println() + + val k = 15355717786080L + val (seq, aliquot) = classifySequence(k) + println("$k: ${aliquot.padEnd(15)} $seq") +} diff --git a/Task/Aliquot-sequence-classifications/PARI-GP/aliquot-sequence-classifications.pari b/Task/Aliquot-sequence-classifications/PARI-GP/aliquot-sequence-classifications.pari new file mode 100644 index 0000000000..1b0f46c55b --- /dev/null +++ b/Task/Aliquot-sequence-classifications/PARI-GP/aliquot-sequence-classifications.pari @@ -0,0 +1,18 @@ +aliquot(x) = +{ + my (L = List(x), M = Map(Mat([x,1])), k, m = "non-term.", n = x); + + for (i = 2, 16, n = vecsum(divisors(n)) - n; + if (n > 2^47, break, + n == 0, m = "terminates"; break, + mapisdefined(M, n, &k), + m = if (k == 1, + if (i == 2, "perfect", + i == 3, "amicable", + i > 3, concat("sociable-",i-1)), + k < i-1, concat("cyclic-",i-k), + "aspiring"); break, + mapput(M, n, i); listput(L, n)); + ); + printf("%16d: %10s, %s\n", x, m, Vec(L)); +} diff --git a/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-3.psh b/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-3.psh new file mode 100644 index 0000000000..9999c547fc --- /dev/null +++ b/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-3.psh @@ -0,0 +1,90 @@ +function Get-Aliquot +{ + [CmdletBinding()] + [OutputType([PScustomObject])] + Param + ( + [Parameter(Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true)] + [int] + $InputObject + ) + + Begin + { + function Get-NextAliquot ([int]$X) + { + if ($X -gt 1) + { + $nextAliquot = 1 + + if ($X -gt 2) + { + $xSquareRoot = [Math]::Sqrt($X) + + 2..$xSquareRoot | Where-Object {$X % $_ -eq 0} | ForEach-Object {$nextAliquot += $_ + $x / $_} + + if ($xSquareRoot % 1 -eq 0) {$nextAliquot -= $xSquareRoot} + } + + $nextAliquot + } + } + + function Get-AliquotSequence ([int]$K, [int]$N) + { + $X = $K + $X + $i = 1 + + while ($X -and $i -lt $N) + { + $i++ + $next = Get-NextAliquot $X + + if ($next) + { + if ($X -eq $next) + { + $i..$N | ForEach-Object {$X} + $i = $N + } + else + { + $X = $next + $X + } + } + else + { + $i = $N + } + } + } + + function Classify-AlliquotSequence ([int[]]$Sequence) + { + $k = $Sequence[0] + + if ($Sequence[-1] -eq 0) {return "terminating"} + if ($Sequence[-1] -eq 1) {return "terminating"} + if ($Sequence[1] -eq $k) {return "perfect" } + if ($Sequence[2] -eq $k) {return "amicable" } + if ($Sequence[3..($Sequence.Count-1)] -contains $k) {return "sociable" } + if ($Sequence[-1] -eq $Sequence[-2] ) {return "aspiring" } + if ($Sequence.Count -gt ($Sequence | Select -Unique).Count ) {return "cyclic" } + + return "non-terminating and non-repeating through N = $($Sequence.Count)" + } + } + Process + { + $_ | ForEach-Object { + [PSCustomObject]@{ + Number = $_ + Classification = (Classify-AlliquotSequence -Sequence (Get-AliquotSequence -K $_ -N 16)) + } + } + } +} diff --git a/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-4.psh b/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-4.psh new file mode 100644 index 0000000000..d6e159aeda --- /dev/null +++ b/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-4.psh @@ -0,0 +1,5 @@ +$oneToTen = 1..10 | Get-Aliquot +$selected = 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488 | Get-Aliquot + +$numbers = $oneToTen, $selected +$numbers diff --git a/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx b/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx index c9f0587483..29da9a563e 100644 --- a/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx +++ b/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx @@ -1,45 +1,44 @@ /*REXX program classifies various positive integers for types of aliquot sequences. */ parse arg low high L /*obtain optional arguments from the CL*/ high=word(high low 10,1); low=word(low 1,1) /*obtain the LOW and HIGH (range). */ -if L='' then L=11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080 -big=2**47; NTlimit=16+1 /*limit for a non─terminating sequence.*/ -numeric digits max(9, 1+length(big)) /*be able to handle big numbers for // */ -#.=.; #.0=0; #.1=0 /*#. are the proper divisor sums. */ -say center('numbers from ' low " to " high, 79, "═") - - do n=low to high /*process (probably) some low numbers. */ - call classify n /*call a subroutine to classify number.*/ +if L='' then L=11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080 +numeric digits 20 /*be able to handle the number: BIG */ +big=2**47; NTlimit=16+1 /*limits for a non─terminating sequence*/ +numeric digits max(9, 1 + length(big) ) /*be able to handle big numbers for // */ +#.=.; #.0=0; #.1=0 /*#. are the proper divisor sums. */ +say center('numbers from ' low " to " high, 79, "═") + do n=low to high; call classify n /*call a subroutine to classify number.*/ end /*n*/ /* [↑] process a range of integers. */ say say center('first numbers for each classification', 79, "═") class.=0 /* [↓] ensure one number of each class*/ do q=1 until class.sociable\==0 /*the only one that has to be counted. */ - call classify -q /*the minus (-) sign indicates ¬ tell. */ + call classify -q /*minus (-) sign indicates don't tell. */ _=what; upper _; class._=class._+1 /*bump counter for this class sequence.*/ - if class._==1 then call show_class q,$ /*only display the first occurrence. */ - end /*q*/ /* [↑] process until all classes found*/ -say + if class._==1 then say right(q, digits()) 'is' center(what, 15) $ + end /*q*/ /* [↑] only display the 1st occurrence*/ +say /* [↑] process until all classes found*/ say center('classifications for specific numbers', 79, "═") - do i=1 for words(L) /*L: is a list of "special numbers".*/ call classify word(L,i) /*call a subroutine to classify number.*/ end /*i*/ /* [↑] process a list of integers. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -classify: parse arg a 1 aa; a=abs(a) /*obtain number that's to be classified*/ - if #.a\==. then s=#.a /*Was this number been summed before?*/ - else s=sigma(a) /*No, then classify number the hard way*/ +classify: parse arg a 1 aa; a=abs(a) /*obtain number that's to be classified*/ + if #.a\==. then s=#.a /*Was this number been summed before?*/ + else s=sigma(a) /*No, then classify number the hard way*/ #.a=s; $=s /*define sum of the proper divisors. */ what='terminating' /*assume this kind of classification. */ c.=0; c.s=1 /*clear all cyclic sequences; set 1st.*/ if $==a then what='perfect' /*check for a "perfect" number. */ else do t=1 while s\==0 /*loop until sum isn't 0 or > big.*/ - m=word($, words($)) /*obtain the last number in sequence. */ + m=s /*obtain the last number in sequence. */ if #.m==. then s=sigma(m) /*Not defined? Then sum proper divisors*/ else s=#.m /*use the previously found integer. */ if m==s & m\==0 then do; what='aspiring' ; leave; end - if word($,2)==a then do; what='amicable' ; leave; end - $=$ s /*append a sum to the integer sequence.*/ + parse var $ . word2 . /* " " 2nd " " " */ + if word2==a then do; what='amicable' ; leave; end + $=$ s /*append a sum to the integer sequence.*/ if s==a & t>3 then do; what='sociable' ; leave; end if c.s & m\==0 then do; what='cyclic' ; leave; end c.s=1 /*assign another possible cyclic number*/ @@ -47,17 +46,14 @@ classify: parse arg a 1 aa; a=abs(a) /*obtain number that's to be cl if t>NTlimit then do; what='non-terminating'; leave; end if s>big then do; what='NON-TERMINATING'; leave; end end /*t*/ /* [↑] only permit within reason. */ - if aa>0 then call show_class a,$ /*only display if A is positive. */ - return + if aa>0 then say right(a, digits() ) 'is' center(what, 15) $ + return /* [↑] only display if A is positive.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ -show_class: say right(arg(1),digits()) 'is' center(what,15) arg(2); return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sigma: procedure expose #.; parse arg x; if x<2 then return 0; odd=x//2 +sigma: procedure expose #.; parse arg x; if x<2 then return 0; odd=x//2 s=1 /* [↓] use only EVEN | ODD ints. ___*/ do j=2+odd by 1+odd while j*jWalker + Walker(fcn(rk){ k:=rk.value; if(k)rk.set(properDivs(k).sum()); k }.fp(Ref(k))) +}(10).walk(15).println(); diff --git a/Task/Aliquot-sequence-classifications/Zkl/aliquot-sequence-classifications-2.zkl b/Task/Aliquot-sequence-classifications/Zkl/aliquot-sequence-classifications-2.zkl new file mode 100644 index 0000000000..57c1019049 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Zkl/aliquot-sequence-classifications-2.zkl @@ -0,0 +1,9 @@ +fcn aliquot(k){ //-->Walker + Walker(fcn(rk){ + k:=rk.value; + rk.set((1).reduce((k + 1)/2, fcn(s,n,k){ + s + (k%n==0 and k!=n and n) // s + False == s + 0 + },0,k)); + k + }.fp(Ref(k))) +}(10).walk(15).println(); diff --git a/Task/Aliquot-sequence-classifications/Zkl/aliquot-sequence-classifications-3.zkl b/Task/Aliquot-sequence-classifications/Zkl/aliquot-sequence-classifications-3.zkl new file mode 100644 index 0000000000..21d26551a9 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Zkl/aliquot-sequence-classifications-3.zkl @@ -0,0 +1,22 @@ +fcn classify(k){ + const MAX=(2).pow(47); // 140737488355328 + ak,aks:=aliquot(k), ak.walk(16); + _,a2,a3:=aks; + if(a2==k) return("perfect"); + if(a3==k) return("amicable"); + aspiring:='wrap(){ + foreach n in (aks.len()-1){ if(aks[n]==aks[n+1]) return(True) } + False + }; + cyclic:='wrap(){ + foreach n in (aks.len()-1){ if(aks[n+1,*].holds(aks[n])) return(aks[n]) } + False + }; + (if(aks.filter1('==(0))!=False) "terminating" + else if(n:=aks[1,*].filter1n('==(k))) "sociable of length " + (n+1) + else if(aks.filter1('>(MAX))) "non-terminating" + else if(aspiring()) "aspiring" + else if((c:=cyclic())!=False) "cyclic on " + c + else "non-terminating" ) + + " " + aks.filter(); +} diff --git a/Task/Aliquot-sequence-classifications/Zkl/aliquot-sequence-classifications-4.zkl b/Task/Aliquot-sequence-classifications/Zkl/aliquot-sequence-classifications-4.zkl new file mode 100644 index 0000000000..09cf61878b --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Zkl/aliquot-sequence-classifications-4.zkl @@ -0,0 +1,3 @@ +[1..10].pump(fcn(k){ "%6d is %s".fmt(k,classify(k)).println() }); +T(11,12,28,496,220,1184,12496,1264460,790,909,562,1064,1488) + .pump(fcn(k){ "%6d is %s".fmt(k,classify(k)).println() }); diff --git a/Task/Almost-prime/Groovy/almost-prime.groovy b/Task/Almost-prime/Groovy/almost-prime.groovy new file mode 100644 index 0000000000..1ee69bcdf7 --- /dev/null +++ b/Task/Almost-prime/Groovy/almost-prime.groovy @@ -0,0 +1,34 @@ + public class almostprime +{ +public static boolean kprime(int n,int k) + { + int i,div=0; + for(i=2;(i*i <= n) && (div 1)?1:0) == k; + } + public static void main(String[] args) + { + int i,l,k; + for(k=1;k<=5;k++) + { + println("k = " + k + ":"); + l = 0; + for(i=2;l<10;i++) + { + if(kprime(i,k)) + { + print(i + " "); + l++; + } + } + println(); + } + } +}​ diff --git a/Task/Almost-prime/Java/almost-prime.java b/Task/Almost-prime/Java/almost-prime.java index 46460dcedf..5523a1a87d 100644 --- a/Task/Almost-prime/Java/almost-prime.java +++ b/Task/Almost-prime/Java/almost-prime.java @@ -1,28 +1,27 @@ -public class AlmostPrime -{ - public static void main(String args[]) - { +public class AlmostPrime { + public static void main(String[] args) { for (int k = 1; k <= 5; k++) { System.out.print("k = " + k + ":"); - for (int i = 2, c = 0; c < 10; i++) + for (int i = 2, c = 0; c < 10; i++) { if (kprime(i, k)) { System.out.print(" " + i); c++; } + } System.out.println(""); } } - public static boolean kprime(int n, int k) - { + public static boolean kprime(int n, int k) { int f = 0; - for (int p = 2; f < k && p*p <= n; p++) - while (0 == n % p){ - n /= p; - f++; + for (int p = 2; f < k && p * p <= n; p++) { + while (n % p == 0) { + n /= p; + f++; } - return f + ((n > 1)?1:0) == k; + } + return f + ((n > 1) ? 1 : 0) == k; } } diff --git a/Task/Almost-prime/JavaScript/almost-prime.js b/Task/Almost-prime/JavaScript/almost-prime.js new file mode 100644 index 0000000000..f20a65a07d --- /dev/null +++ b/Task/Almost-prime/JavaScript/almost-prime.js @@ -0,0 +1,24 @@ +function almostPrime (n, k) { + var divisor = 2, count = 0 + while(count < k + 1 && n != 1) { + if (n % divisor == 0) { + n = n / divisor + count = count + 1 + } else { + divisor++ + } + } + return count == k +} + +for (var k = 1; k <= 5; k++) { + document.write("
k=", k, ": ") + var count = 0, n = 0 + while (count <= 10) { + n++ + if (almostPrime(n, k)) { + document.write(n, " ") + count++ + } + } +} diff --git a/Task/Almost-prime/jq/almost-prime-1.jq b/Task/Almost-prime/Jq/almost-prime-1.jq similarity index 100% rename from Task/Almost-prime/jq/almost-prime-1.jq rename to Task/Almost-prime/Jq/almost-prime-1.jq diff --git a/Task/Almost-prime/jq/almost-prime-2.jq b/Task/Almost-prime/Jq/almost-prime-2.jq similarity index 100% rename from Task/Almost-prime/jq/almost-prime-2.jq rename to Task/Almost-prime/Jq/almost-prime-2.jq diff --git a/Task/Almost-prime/jq/almost-prime-3.jq b/Task/Almost-prime/Jq/almost-prime-3.jq similarity index 100% rename from Task/Almost-prime/jq/almost-prime-3.jq rename to Task/Almost-prime/Jq/almost-prime-3.jq diff --git a/Task/Almost-prime/jq/almost-prime-4.jq b/Task/Almost-prime/Jq/almost-prime-4.jq similarity index 100% rename from Task/Almost-prime/jq/almost-prime-4.jq rename to Task/Almost-prime/Jq/almost-prime-4.jq diff --git a/Task/Almost-prime/Nim/almost-prime.nim b/Task/Almost-prime/Nim/almost-prime.nim new file mode 100644 index 0000000000..84b0d78aea --- /dev/null +++ b/Task/Almost-prime/Nim/almost-prime.nim @@ -0,0 +1,23 @@ +proc prime(k: int, listLen: int): seq[int] = + result = @[] + var + test: int = 2 + curseur: int = 0 + while curseur < listLen: + var + i: int = 2 + compte = 0 + n = test + while i <= n: + if (n mod i)==0: + n = n div i + compte += 1 + else: + i += 1 + if compte == k: + result.add(test) + curseur += 1 + test += 1 + +for k in 1..5: + echo "k = ",k," : ",prime(k,10) diff --git a/Task/Almost-prime/REXX/almost-prime-1.rexx b/Task/Almost-prime/REXX/almost-prime-1.rexx index 90f5629f0e..e5652afb7c 100644 --- a/Task/Almost-prime/REXX/almost-prime-1.rexx +++ b/Task/Almost-prime/REXX/almost-prime-1.rexx @@ -1,33 +1,35 @@ -/*REXX program displays the N numbers of the first K k-almost primes*/ -parse arg N K . /*get the arguments from the C.L.*/ -if N=='' then N=10 /*No N? Then use the default.*/ -if K=='' then K=5 /* " K? " " " " */ - /* [↓] display one line per K.*/ - do m=1 for K; $=2**m; fir=$ /*generate the 1st k_almost prime*/ - #=1; if #==N then leave /*# k-almost primes; 'nuff found?*/ - sec=3*(2**(m-1)); $=$ sec; #=2 /*generate the 2nd k-almost prime*/ - do j=fir+fir+1 until #==N /*process an almost-prime N times*/ - if #factr(j)\==m then iterate /*not the correct k-almost prime?*/ - #=#+1 /*bump the k-almost prime counter*/ - $=$ j /*append k-almost prime to list. */ - end /*j*/ /* [↑] gen N k-almost primes.*/ - say N right(m,4)"-almost primes:" $ /*display the k-almost primes.*/ - end /*m*/ /* [↑] display a line for each K*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────#FACTR subroutine───────────────────*/ -#factr: procedure;parse arg x 1 z; f=0 /*defines X and Z to the arg.*/ -if x<2 then return 0 /*invalid number? Then return 0.*/ - do j=2 to 5; if j\==4 then call .#factr; end /*fast factoring.*/ -j=5 /*start were we left off (J=5). */ - do y=0 by 2; j=j+2 + y//4 /*insure it's not divisible by 3.*/ - if right(j,1)==5 then iterate /*fast check for divisible by 5.*/ - if j>z then leave /*number reduced to a wee number?*/ - call .#factr /*go add other factors to count. */ - end /*y*/ /* [↑] find all factors in X. */ -return max(f,1) /*if prime (f==0), then return 1.*/ -/*──────────────────────────────────.#FACTR subroutine──────────────────*/ -.#factr: do f=f+1 while z//j==0 /*keep dividing until we can't. */ - z=z%j /*perform an (%) integer divide.*/ - end /*while*/ /* [↑] whittle down the Z num.*/ -f=f-1 /*adjust the count of factors. */ -return +/*REXX program computes and displays the first N K─almost primes from 1 ──► K. */ +parse arg N K . /*get optional arguments from the C.L. */ +if N=='' | N=="," then N=10 /*N not specified? Then use default.*/ +if K=='' | K=="," then K= 5 /*K " " " " " */ + /*W: is the width of K, used for output*/ + do m=1 for K; $=2**m; fir=$ /*generate & assign 1st K─almost prime.*/ + #=1; if #==N then leave /*#: K─almost primes; Enough are found?*/ + #=2; $=$ 3*(2**(m-1)) /*generate & append 2nd K─almost prime.*/ + if #==N then leave /*#: K─almost primes; Enough are found?*/ + if m==1 then _=fir + fir /* [↓] gen & append 3rd K─almost prime*/ + else do; _=9 * (2**(m-2)); #=3; $=$ _; end + do j=_ + m - 1 until #==N /*process an K─almost prime N times.*/ + if factr()\==m then iterate /*not the correct K─almost prime? */ + #=# + 1; $=$ j /*bump K─almost counter; append it to $*/ + end /*j*/ /* [↑] generate N K─almost primes.*/ + say right(m, length(K))"─almost ("N') primes:' $ + end /*m*/ /* [↑] display a line for each K─prime*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +factr: z=j; do f=0 while z// 2==0; z=z% 2; end /*divisible by 2.*/ + do f=f while z// 3==0; z=z% 3; end /*divisible " 3.*/ + do f=f while z// 5==0; z=z% 5; end /*divisible " 5.*/ + do f=f while z// 7==0; z=z% 7; end /*divisible " 7.*/ + do f=f while z//11==0; z=z%11; end /*divisible " 11.*/ + do f=f while z//13==0; z=z%13; end /*divisible " 13.*/ + do p=17 by 6 while p<=z /*insure P isn't divisible by three. */ + parse var p '' -1 _ /*obtain the right─most decimal digit. */ + /* [↓] fast check for divisible by 5. */ + if _\==5 then do; do f=f+1 while z//p==0; z=z%p; end; f=f-1; end /*÷ by P? */ + if _ ==3 then iterate /*fast check for X divisible by five.*/ + x=p+2; do f=f+1 while z//x==0; z=z%x; end; f=f-1 /*÷ by X? */ + end /*i*/ /* [↑] find all the factors in Z. */ + + if f==0 then return 1 /*if prime (f==0), then return unity.*/ + return f /*return to invoker the number of divs.*/ diff --git a/Task/Almost-prime/REXX/almost-prime-2.rexx b/Task/Almost-prime/REXX/almost-prime-2.rexx index 1673079e3f..d0dbbe54d6 100644 --- a/Task/Almost-prime/REXX/almost-prime-2.rexx +++ b/Task/Almost-prime/REXX/almost-prime-2.rexx @@ -1,35 +1,66 @@ -/*REXX program displays the N numbers of the first K k-almost primes*/ -parse arg N K . /*get the arguments from the C.L.*/ -if N=='' then N=10 /*No N? Then use the default.*/ -if K=='' then K=5 /* " K? " " " " */ - /* [↓] display one line per K.*/ - do m=1 for K; $=2**m; fir=$ /*generate the 1st k_almost prime*/ - #=1; if #==N then leave /*# k-almost primes; 'nuff found?*/ - sec=3*(2**(m-1)); $=$ sec; #=2 /*generate the 2nd k-almost prime*/ - do j=fir+fir+1 until #==N /*process an almost-prime N times*/ - if #factL(j,m)\==m then iterate /*not the correct k-almost prime?*/ - #=#+1 /*bump the k-almost prime counter*/ - $=$ j /*append k-almost prime to list. */ - end /*j*/ /* [↑] gen N k-almost primes.*/ - say N right(m,4)"-almost primes:" $ /*display the k-almost primes.*/ - end /*m*/ /* [↑] display a line for each K*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────#FACTL subroutine───────────────────*/ -#factL: procedure; parse arg x 1 z,L /*defines X and Z to the arg.*/ -f=0; if x<2 then return 0 /*invalid number? Then return 0.*/ - do j=2 to 5; if j\==4 then call .#factL; end /*fast factoring.*/ -if f>L then return f /*#factors > L ? Then too many.*/ -j=5 /*start were we left off (J=5). */ - do y=0 by 2; j=j+2 + y//4 /*insure it's not divisible by 3.*/ - if right(j,1)==5 then iterate /*fast check for divisible by 5.*/ - if j>z then leave /*number reduced to a wee number?*/ - call .#factL /*go add other factors to count. */ - if f>L then return f /*#factors > L ? Then too many.*/ - end /*y*/ /* [↑] find all factors in X. */ -return max(f,1) /*if prime (f==0), then return 1.*/ -/*──────────────────────────────────.#FACTL subroutine──────────────────*/ -.#factL: do f=f+1 while z//j==0 /*keep dividing until we can't. */ - z=z%j /*perform an (%) integer divide.*/ - end /*while*/ /* [↑] whittle down the Z num.*/ -f=f-1 /*adjust the count of factors. */ -return +/*REXX program computes and displays the first N K─almost primes from 1 ──► K. */ +parse arg N K . /*obtain optional arguments from the CL*/ +if N=='' | N==',' then N=10 /*N not specified? Then use default.*/ +if K=='' | K==',' then K= 5 /*K " " " " " */ +nn=N; N=abs(N); w=length(K) /*N positive? Then show K─almost primes*/ +limit= (2**K) * N / 2 /*this is the limit for most K-primes. */ +if N==1 then limit=limit * 2 /* " " " " " a N of 1.*/ +if K==1 then limit=limit * 4 /* " " " " " a K─prime " 2.*/ +if K==2 then limit=limit * 2 /* " " " " " " " " 4.*/ +if K==3 then limit=limit * 3 % 2 /* " " " " " " " " 8.*/ +call genPrimes limit + 1 /*generate primes up to the LIMIT + 1.*/ +say 'The highest prime computed: ' @.# " (under the limit of " limit').' +say /* [↓] define where 1st K─prime is odd*/ +d.=0; d.2= 2; d.3 = 4; d.4 = 7; d.5 = 13; d.6 = 22; d.7 = 38; d.8=63 + d.9=102; d.10=168; d.11=268; d.12=426; d.13=673; d.14=1064 +d!=0 + do m=1 for K; d!=max(d!,d.m) /*generate & assign 1st K─almost prime.*/ + mr=right(m,w); mm=m-1 + + $=; do #=1 to min(N, d!) /*assign some doubled K─almost primes. */ + $=$ d.mm.# * 2 + end /*#*/ + #=#-1 + if m==1 then from=2 + else from=1 + word($, words($) ) + + do j=from until #==N /*process an K─almost prime N times.*/ + if factr()\==m then iterate /*not the correct K─almost prime? */ + #=#+1; $=$ j /*bump K─almost counter; append it to $*/ + end /*j*/ /* [↑] generate N K─almost primes.*/ + + if nn>0 then say mr"─almost ("N') primes:' $ + else say ' the last' mr "K─almost prime: " word($, words($)) + /* [↓] assign K─almost primes.*/ + do q=1 for #; d.m.q=word($,q) ; end /*q*/ + do q=1 for #; if d.m.q\==d.mm.q*2 then leave; end /*q*/ + /* [↑] count doubly-duplicates*/ +/*──── say copies('─',40) 'for ' m", " q-1 'numbers were doubly─duplicated.' ────*/ +/*──── say ────*/ + end /*m*/ /* [↑] display a line for each K─prime*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +factr: if #.j\==. then return #.j + z=j; do f=0 while z// 2==0; z=z% 2; end /*÷ by 2*/ + do f=f while z// 3==0; z=z% 3; end /*÷ " 3*/ + do f=f while z// 5==0; z=z% 5; end /*÷ " 5*/ + do f=f while z// 7==0; z=z% 7; end /*÷ " 7*/ + do f=f while z//11==0; z=z%11; end /*÷ " 11*/ + do f=f while z//13==0; z=z%13; end /*÷ " 13*/ + do f=f while z//17==0; z=z%17; end /*÷ " 17*/ + do f=f while z//19==0; z=z%19; end /*÷ " 19*/ + + do i=9 while @.i<=z; d=@.i /*divide by some higher primes. */ + do f=f while z//d==0; z=z%d; end /*is Z divisible by the prime D ? */ + end /*i*/ /* [↑] find all factors in Z. */ + + if f==0 then f=1; #.j=f; return f /*Is prime (f≡0)? Then return unity. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +genPrimes: arg x; @.=; @.1=2; @.2=3; #.=.; #=2; s.#=@.#**2 + do j=@.# +2 by 2 to x /*only find odd primes from here on. */ + do p=2 while s.p<=j /*divide by some known low odd primes. */ + if j//@.p==0 then iterate j /*Is J divisible by X? Then ¬ prime.*/ + end /*p*/ /* [↓] a prime (J) has been found. */ + #=#+1; @.#=j; #.j=1; s.#=j*j /*bump prime count, and also assign ···*/ + end /*j*/ /* ··· the # of factors, prime, prime².*/ + return /* [↑] not an optimal prime generator.*/ diff --git a/Task/Almost-prime/REXX/almost-prime.rexx b/Task/Almost-prime/REXX/almost-prime.rexx deleted file mode 100644 index 92dc76fe97..0000000000 --- a/Task/Almost-prime/REXX/almost-prime.rexx +++ /dev/null @@ -1,32 +0,0 @@ -/*REXX program computes and displays the first N K─almost primes from 1 ── ►K. */ -parse arg N K . /*get optional arguments from the C.L. */ -if N=='' | N=="," then N=10 /*N not specified? Then use default.*/ -if K=='' | K=="," then K= 5 /*K " " " " " */ - /*W: is the width of K, used for output*/ - do m=1 for K; $=2**m; fir=$ /*generate & assign 1st K─almost prime.*/ - #=1; if #==N then leave /*#: K─almost primes; Enough are found?*/ - #=2; $=$ 3*(2**(m-1)) /*generate & append 2nd K─almost prime.*/ - if #==N then leave /*#: K─almost primes; Enough are found?*/ - if m==1 then _=fir+fir /* [↓] gen & append 3rd K─almost prime*/ - else do; _=9*(2**(m-2)); #=3; $=$ _; end - do j=_+m-1 until #==N /*process an K─almost prime N times.*/ - if #factr()\==m then iterate /*not the correct K─almost prime? */ - #=#+1; $=$ j /*bump K─almost counter; append it to $*/ - end /*j*/ /* [↑] generate N K─almost primes.*/ - say right(m, length(K))"─almost ("N') primes:' $ - end /*m*/ /* [↑] display a line for each K─prime*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -#factr: z=j; do f=0 while z//2==0; z=z%2; end /*divisible by 2. */ - do f=f while z//3==0; z=z%3; end /*divisible " 3. */ - do f=f while z//5==0; z=z%5; end /*divisible " 5. */ - do f=f while z//7==0; z=z%7; end /*divisible " 7. */ - do i=11 by 6 while i<=z /*insure I isn't divisible by three. */ - parse var i '' -1 _ /*obtain the right─most decimal digit. */ - /* [↓] fast check for divisible by 5. */ - if _\==5 then do; do f=f+1 while z//i==0; z=z%i; end; f=f-1; end /*divisible by I. */ - if _==3 then iterate /*fast check for X divisible by five.*/ - x=i+2; do f=f+1 while z//x==0; z=z%x; end; f=f-1 /*divisible by X. */ - end /*i*/ /* [↑] find all the factors in Z. */ - -return max(f, 1) /*if prime (f==0), then return unity.*/ diff --git a/Task/Almost-prime/Sidef/almost-prime.sidef b/Task/Almost-prime/Sidef/almost-prime.sidef index 941dd2d248..015cf5ce1e 100644 --- a/Task/Almost-prime/Sidef/almost-prime.sidef +++ b/Task/Almost-prime/Sidef/almost-prime.sidef @@ -1,17 +1,18 @@ func is_k_almost_prime(n, k) { for (var (p, f) = (2, 0); (f < k) && (p*p <= n); ++p) { - (n /= p; ++f) while p.divides(n); + (n /= p; ++f) while (p `divides` n) } n > 1 ? (f.inc == k) : (f == k) } -5.times { |k| +{ |k| var x = 10 say gather { - Math.inf.times { |i| + { |i| if (is_k_almost_prime(i, k)) { - take(i); (--x).is_zero && break; + take(i) + --x == 0 && break } - } + } << 1..Inf } -} +} << 1..5 diff --git a/Task/Almost-prime/Zkl/almost-prime.zkl b/Task/Almost-prime/Zkl/almost-prime.zkl new file mode 100644 index 0000000000..f629ce9665 --- /dev/null +++ b/Task/Almost-prime/Zkl/almost-prime.zkl @@ -0,0 +1,5 @@ +primes:=Utils.Generator(Import("sieve").postponed_sieve); +(p10:=ar:=primes.walk(10)).println(); +do(4){ + (ar=([[(x,y);ar;p10;'*]] : Utils.Helpers.listUnique(_).sort()[0,10])).println(); +} diff --git a/Task/Amb/Elena/amb.elena b/Task/Amb/Elena/amb.elena index e1f0736977..c2760ef490 100644 --- a/Task/Amb/Elena/amb.elena +++ b/Task/Amb/Elena/amb.elena @@ -1,74 +1,76 @@ -#define system. -#define system'routines. -#define extensions. -#define extensions'routines. +import system'routines. +import extensions. +import extensions'routines. -#symbol joinable = (:aFormer:aLater) - [ (aFormer@(aFormer length - 1)) == (aLater@0) ]. +joinable = (:aFormer:aLater)(aFormer[aFormer length - 1] == aLater[0]). -#symbol dispatcher = +dispatcher = { - eval : anArray &func2:aFunction + eval object:anArray func2:aFunction [ - ^ aFunction eval:(anArray@0):(anArray@1). + ^ aFunction eval(anArray[0],anArray[1]). ] - eval : anArray &func3:aFunction + eval object:anArray func3:aFunction [ - ^ aFunction eval:(anArray@0):(anArray@1):(anArray@2). + ^ aFunction eval(anArray[0], anArray[1],anArray[2]). ] - eval : anArray &func4:aFunction + eval object:anArray func4:aFunction [ - ^ aFunction eval:(anArray@0):(anArray@1):(anArray@2):(anArray@3). + ^ aFunction eval(anArray[0],anArray[1],anArray[2],anArray[3]). ] - eval : anArray &func5:aFunction + eval object:anArray func5:aFunction [ - ^ aFunction eval:(anArray@0):(anArray@1):(anArray@2):(anArray@3):(anArray@4). + ^ aFunction eval(anArray[0],anArray[1],anArray[2],anArray[3],anArray[4]). ] }. -#class AmbValueCollection +class AmbValueCollection { - #field theCombinator. + object theCombinator. - #constructor new &args:Arguments + constructor new args:Arguments [ - theCombinator := SequentialEnumerator new &args:Arguments. + theCombinator := SequentialEnumerator new args:Arguments. ] - #method seek : aCondition + seek : aCondition [ theCombinator reset. - theCombinator seek &each: v - [ - ^ aCondition cast:%eval &to:dispatcher &with:v. - ]. + theCombinator seekEach(:v)(dispatcher eval(v,aCondition)) ] - #method do : aFunction + do : aFunction [ - #var aResult := theCombinator get. - (nil != aResult) - ? [ aFunction cast:%eval &to:dispatcher &with:aResult. ] - ! [ #throw InvalidArgumentException new. ]. + var aResult := theCombinator get. + if (nil != aResult) + [ dispatcher eval(aResult,aFunction) ]; + [ InvalidArgumentException new; raise ] ] } -#symbol ambOperator = +ambOperator = { - for &args:Arguments - = AmbValueCollection new &args:Arguments. + generic for args:Arguments + = AmbValueCollection new args:Arguments. }. -#symbol program = +program = [ - ambOperator - for &args:("the","that","a"):("frog", "elephant", "thing"):("walked", "treaded", "grows"):("slowly", "quickly") - seek: (:a:b:c:d) [ (joinable:a:b) and:(joinable:b:c) and:(joinable:c:d) ] - do: (:a:b:c:d) [ console writeLine:a:" ":b:" ":c:" ":d. ] - | if &InvalidArgumentError: e [ console writeLine:"AMB is angry". ]. + try(ambOperator + for(("the","that","a"),("frog", "elephant", "thing"),("walked", "treaded", "grows"),("slowly", "quickly")); + seek(:a:b:c:d) ( joinable eval(a,b) && joinable eval(b,c) && joinable eval(c,d) ); + do(:a:b:c:d) [ console printLine(a," ",b," ",c," ",d) ]) + { + on(Exception e) + [ + console printLine:"AMB is angry" + ] + }. + + console readChar. ]. diff --git a/Task/Amb/jq/amb-1.jq b/Task/Amb/Jq/amb-1.jq similarity index 100% rename from Task/Amb/jq/amb-1.jq rename to Task/Amb/Jq/amb-1.jq diff --git a/Task/Amb/jq/amb-2.jq b/Task/Amb/Jq/amb-2.jq similarity index 100% rename from Task/Amb/jq/amb-2.jq rename to Task/Amb/Jq/amb-2.jq diff --git a/Task/Amb/jq/amb-3.jq b/Task/Amb/Jq/amb-3.jq similarity index 100% rename from Task/Amb/jq/amb-3.jq rename to Task/Amb/Jq/amb-3.jq diff --git a/Task/Amb/jq/amb-4.jq b/Task/Amb/Jq/amb-4.jq similarity index 100% rename from Task/Amb/jq/amb-4.jq rename to Task/Amb/Jq/amb-4.jq diff --git a/Task/Amb/jq/amb-5.jq b/Task/Amb/Jq/amb-5.jq similarity index 100% rename from Task/Amb/jq/amb-5.jq rename to Task/Amb/Jq/amb-5.jq diff --git a/Task/Amb/Kotlin/amb.kotlin b/Task/Amb/Kotlin/amb.kotlin new file mode 100644 index 0000000000..a28a6adcd7 --- /dev/null +++ b/Task/Amb/Kotlin/amb.kotlin @@ -0,0 +1,41 @@ +// version 1.1.3 + +typealias Constraint = (T, T) -> Boolean + +fun amb(lists: List>, res: MutableList, cons: Constraint): Boolean { + if (lists.isEmpty()) return true + if (lists[0].isEmpty()) return false + val z = res.size + for ((i, el) in lists[0].withIndex()) { + if (i == 0) res.add(el) else res[z] = el + if (z > 0 && !cons(res[z - 1], res[z])) continue + if (amb(lists.drop(1), res, cons)) return true + } + res.removeAt(z) + return false +} + +fun main(args: Array) { + val wordLists = listOf( + listOf("the", "that", "a"), + listOf("frog", "elephant", "thing"), + listOf("walked", "treaded", "grows"), + listOf("slowly", "quickly") + ) + val res = mutableListOf() + val cons: Constraint = { x, y -> x.last() == y.first() } + if (amb(wordLists, res, cons)) + println(res) + else + println("No solution found") + val numLists = listOf( + listOf(1, 2, 3), + listOf(7, 6, 4, 5) + ) + val res2 = mutableListOf() + val cons2: Constraint = { x, y -> x * y == 8 } + if (amb(numLists, res2, cons2)) + println(res2) + else + println("No solution found") +} diff --git a/Task/Amb/REXX/amb-1.rexx b/Task/Amb/REXX/amb-1.rexx index fe05d4379e..3de6b6c7fa 100644 --- a/Task/Amb/REXX/amb-1.rexx +++ b/Task/Amb/REXX/amb-1.rexx @@ -1,20 +1,22 @@ -/*REXX program demonstrates the Amd operator, choosing a word from each set.*/ -@.=; @.1 = "the that a" - @.2 = "frog elephant thing" - @.3 = "walked treaded grows" - @.4 = "slowly quickly" - do j=1 until @.j==''; end; @.0=j-1 /*define @.0 as the number of sets.*/ -call Amb 1 /*find all word combinations that works*/ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -Amb: procedure expose @.; parse arg # _; arg . u /*2nd parse uppercases U*/ - if #>@.0 then do; w=word(u,1) /*W: is a uppercased U*/ - do n=2 to words(u); ?=word(u,n) - if left(?,1)\==right(w,1) then return; w=? - end /*n*/ - say space(_) - end - do k=1 for words(@.#) /*process words in sets.*/ - call Amb #+1 _ word(@.#,k) /*generate combinations,*/ - end /*k*/ /* [↑] (recursively).*/ - return +/*REXX program demonstrates the Amd operator, choosing a word from each set. */ +@.=; @.1 = "the that a" + @.2 = "frog elephant thing" + @.3 = "walked treaded grows" + @.4 = "slowly quickly" +call Amb 1 /*find all word combinations that works*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +Amb: procedure expose @.; parse arg # x; arg . u /*2nd parse uppercases U*/ + do j=1 until @.j==''; end /*locate a null string. */ + t=j-1 /*define number of sets.*/ + if #>t then do; w=word(u,1) /*W: is a uppercased U*/ + do n=2 to words(u); ?=word(u, n) + if left(?, 1) \== right(w, 1) then return; w=? + end /*n*/ + say space(x) + end + + do k=1 for words(@.#) /*process words in sets.*/ + call Amb #+1 x word(@.#, k) /*generate combinations,*/ + end /*k*/ /* [↑] (recursively).*/ + return diff --git a/Task/Amb/Zkl/amb-1.zkl b/Task/Amb/Zkl/amb-1.zkl new file mode 100644 index 0000000000..34c390e7f1 --- /dev/null +++ b/Task/Amb/Zkl/amb-1.zkl @@ -0,0 +1 @@ +fcn joins(a,b){ a[-1]==b[0] } // the constraint diff --git a/Task/Amb/Zkl/amb-2.zkl b/Task/Amb/Zkl/amb-2.zkl new file mode 100644 index 0000000000..d27c49169c --- /dev/null +++ b/Task/Amb/Zkl/amb-2.zkl @@ -0,0 +1,6 @@ +amb(joins, + T("the","that","a"), + T("frog","elephant","thing"), + T("walked","treaded","grows"), + T("slowly","quickly") +).println(); diff --git a/Task/Amb/Zkl/amb-3.zkl b/Task/Amb/Zkl/amb-3.zkl new file mode 100644 index 0000000000..3834a066d1 --- /dev/null +++ b/Task/Amb/Zkl/amb-3.zkl @@ -0,0 +1,6 @@ +a:=amb.future(joins,T("the","that","a"),T("frog","elephant","thing")); +b:=amb.future(joins,T("walked","treaded","grows"),T("slowly","squacking")); +c:=amb.future(joins,a,b); // a future of futures +println(a,b,c); +c=c.noop(); // trigger the landslide, referencing c forces a result for a,b,c +println(a.noop(),b.noop(),c); // even though a has a result, it doesn't know it until we force it diff --git a/Task/Amb/Zkl/amb-4.zkl b/Task/Amb/Zkl/amb-4.zkl new file mode 100644 index 0000000000..f6c1d4b6bd --- /dev/null +++ b/Task/Amb/Zkl/amb-4.zkl @@ -0,0 +1,10 @@ +fcn amb(f,a,b,etc){ + fcn(sink,f,a,b,etc){ + abc:=vm.arglist[2,*]; // ((the,that),(frog,elephant)) + if(abc.len()<2) return(sink.write(abc[0][0])); // back out of recursion + foreach a,b in (abc[0],abc[1]){ // Cartesian product + if(f(a,b)) self.fcn(sink,f,T(String(a," ",b)),abc[2,*].xplode()); + } + }(s:=List(),vm.pasteArgs()); + s +} diff --git a/Task/Amb/Zkl/amb-5.zkl b/Task/Amb/Zkl/amb-5.zkl new file mode 100644 index 0000000000..a6562de534 --- /dev/null +++ b/Task/Amb/Zkl/amb-5.zkl @@ -0,0 +1 @@ +fcn amb(f,a,b,c,etc){ Walker.cproduct(vm.pasteArgs(1)).filter1(f) } diff --git a/Task/Amb/Zkl/amb-6.zkl b/Task/Amb/Zkl/amb-6.zkl new file mode 100644 index 0000000000..f255fdbdda --- /dev/null +++ b/Task/Amb/Zkl/amb-6.zkl @@ -0,0 +1,5 @@ + // [()] notation unpacks parameter list: f((1,2,3))-->a=1,b=2,c=3 +fcn f([(a,b,c,d)]){ joins(a,b) and joins(b,c) and joins(c,d) } +amb(f, T("the","that","a"), T("frog","elephant","thing"), + T("walked","treaded","grows"), T("slowly","quickly") +).println(); diff --git a/Task/Amb/Zkl/amb-7.zkl b/Task/Amb/Zkl/amb-7.zkl new file mode 100644 index 0000000000..3be96bee10 --- /dev/null +++ b/Task/Amb/Zkl/amb-7.zkl @@ -0,0 +1 @@ +amb(fcn([(x,y,z)]){ x*x + y*y == z*z },[1..],[1..10],[1..10]).println(); diff --git a/Task/Amicable-pairs/ATS/amicable-pairs.ats b/Task/Amicable-pairs/ATS/amicable-pairs.ats new file mode 100644 index 0000000000..7aef83f826 --- /dev/null +++ b/Task/Amicable-pairs/ATS/amicable-pairs.ats @@ -0,0 +1,104 @@ +(* ****** ****** *) +// +#include +"share/atspre_staload.hats" +#include +"share/HATS/atspre_staload_libats_ML.hats" +// +(* ****** ****** *) +// +fun +sum_list_vt + (xs: List_vt(int)): int = +( + case+ xs of + | ~list_vt_nil() => 0 + | ~list_vt_cons(x, xs) => x + sum_list_vt(xs) +) +// +(* ****** ****** *) + +fun +propDivs +( + x0: int +) : List0_vt(int) = + loop(x0, 2, list_vt_sing(1)) where +{ +// +fun +loop +( +x0: int, i: int, res: List0_vt(int) +) : List0_vt(int) = +( +if +(i * i) > x0 +then list_vt_reverse(res) +else +( + if x0 % i != 0 + then + loop(x0, i+1, res) + // end of [then] + else let + val res = + cons_vt(i, res) + // end of [val] + val res = + ( + if i * i = x0 then res else cons_vt(x0 / i, res) + ) : List0_vt(int) // end of [val] + in + loop(x0, i+1, res) + end // end of [else] + // end of [if] +) +) (* end of [loop] *) +// +} // end of [propDivs] + +(* ****** ****** *) + +fun +sum_propDivs(x: int): int = sum_list_vt(propDivs(x)) + +(* ****** ****** *) + +val +theNat2 = auxmain(2) where +{ +fun +auxmain +( + n: int +) : stream_vt(int) = $ldelay(stream_vt_cons(n, auxmain(n+1))) +} + +(* ****** ****** *) +// +val +theAmicable = +( +stream_vt_takeLte(theNat2, 20000) +).filter() +( +lam x => +let + val x2 = sum_propDivs(x) +in x < x2 && x = sum_propDivs(x2) end +) +// +(* ****** ****** *) + +val () = +theAmicable.foreach() +( + lam x => println! ("(", x, ", ", sum_propDivs(x), ")") +) + +(* ****** ****** *) + +implement main0 () = () + +(* ****** ****** *) diff --git a/Task/Amicable-pairs/Clojure/amicable-pairs.clj b/Task/Amicable-pairs/Clojure/amicable-pairs.clj new file mode 100644 index 0000000000..326520c137 --- /dev/null +++ b/Task/Amicable-pairs/Clojure/amicable-pairs.clj @@ -0,0 +1,23 @@ +(ns example + (:gen-class)) + +(defn factors [n] + " Find the proper factors of a number " + (into (sorted-set) + (mapcat (fn [x] (if (= x 1) [x] [x (/ n x)])) + (filter #(zero? (rem n %)) (range 1 (inc (Math/sqrt n)))) ))) + + +(def find-pairs (into #{} + (for [n (range 2 20000) + :let [f (factors n) ; Factors of n + M (apply + f) ; Sum of factors + g (factors M) ; Factors of sum + N (apply + g)] ; Sum of Factors of sum + :when (= n N) ; (sum(proDivs(N)) = M and sum(propDivs(M)) = N + :when (not= M N)] ; N not-equal M + (sorted-set n M)))) ; Found pair + +;; Output Results +(doseq [q find-pairs] + (println q)) diff --git a/Task/Amicable-pairs/Common-Lisp/amicable-pairs.lisp b/Task/Amicable-pairs/Common-Lisp/amicable-pairs.lisp new file mode 100644 index 0000000000..0a6538825f --- /dev/null +++ b/Task/Amicable-pairs/Common-Lisp/amicable-pairs.lisp @@ -0,0 +1,15 @@ +(let ((cache (make-hash-table))) + (defun sum-proper-divisors (n) + (or (gethash n cache) + (setf (gethash n cache) + (loop for x from 1 to (/ n 2) + when (zerop (rem n x)) + sum x))))) + +(defun amicable-pairs-up-to (n) + (loop for x from 1 to n + for sum-divs = (sum-proper-divisors x) + when (and (< x sum-divs) (= x (sum-proper-divisors sum-divs))) + collect (list x sum-divs))) + +(amicable-pairs-up-to 20000) diff --git a/Task/Amicable-pairs/Elixir/amicable-pairs.elixir b/Task/Amicable-pairs/Elixir/amicable-pairs.elixir index 2abea4c098..e63bdf5291 100644 --- a/Task/Amicable-pairs/Elixir/amicable-pairs.elixir +++ b/Task/Amicable-pairs/Elixir/amicable-pairs.elixir @@ -8,7 +8,7 @@ defmodule Proper do defp divisors(k,n,q) , do: [k,div(n,k) | divisors(k+1,n,q)] end -map = Enum.into(1..20000, %{}, fn n -> {n, Proper.divisors(n) |> Enum.sum} end) +map = Map.new(1..20000, fn n -> {n, Proper.divisors(n) |> Enum.sum} end) Enum.filter(map, fn {n,sum} -> map[sum] == n and n < sum end) |> Enum.sort |> Enum.each(fn {i,j} -> IO.puts "#{i} and #{j}" end) diff --git a/Task/Amicable-pairs/Futhark/amicable-pairs.futhark b/Task/Amicable-pairs/Futhark/amicable-pairs.futhark index 717a67bf12..f7b3b2681c 100644 --- a/Task/Amicable-pairs/Futhark/amicable-pairs.futhark +++ b/Task/Amicable-pairs/Futhark/amicable-pairs.futhark @@ -13,4 +13,4 @@ fun main(upper: int): [][2]int = let range = map (1+) (iota upper) let divs = zip range (map (fn n => reduce (+) 0 (divisors n)) range) let amicable = filter amicable (map (getPair divs) (iota (upper*upper))) - in map (fn (np,mp) => [np.0, mp.0]) amicable + in map (fn (np,mp) => [#1 np, #1 mp]) amicable diff --git a/Task/Amicable-pairs/Go/amicable-pairs.go b/Task/Amicable-pairs/Go/amicable-pairs.go new file mode 100644 index 0000000000..7419064202 --- /dev/null +++ b/Task/Amicable-pairs/Go/amicable-pairs.go @@ -0,0 +1,29 @@ +package main +import "fmt" +import "math" +func main() { +var i int +var a [200001]int +a[0]=0 +for i=1;i<=20000;i++{ +a[i]=pfac_sum(i) +} +fmt.Println("The amicable pairs are:") +for i=1;i<=20000;i++{ +if (i==a[a[i]])&&(i [(Int, Int)] +amicablePairsUpTo n = + foldl + (\a x -> + let y = sigma x + in if (x < y) && (sigma y == x) + then a ++ [(x, y)] + else a) + [] + [1 .. n] + +sigma :: Int -> Int +sigma = sum . propDivs + where + propDivs :: Int -> [Int] + propDivs n + | n < 2 = [] + | otherwise = + lows ++ + drop + (if isPerfect + then 1 + else 0) + (reverse (quot n <$> tail lows)) + where + iRoot = floor (sqrt $ fromIntegral n) + isPerfect = iRoot * iRoot == n + lows = filter ((== 0) . rem n) [1 .. iRoot] + +main :: IO () +main = mapM_ print $ amicablePairsUpTo 20000 diff --git a/Task/Amicable-pairs/Java/amicable-pairs.java b/Task/Amicable-pairs/Java/amicable-pairs.java index e20197426e..3a890a4085 100644 --- a/Task/Amicable-pairs/Java/amicable-pairs.java +++ b/Task/Amicable-pairs/Java/amicable-pairs.java @@ -1,19 +1,19 @@ import java.util.Map; -import static java.util.function.Function.*; -import static java.util.stream.Collectors.*; -import static java.util.stream.LongStream.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.LongStream; public class AmicablePairs { public static void main(String[] args) { - final int limit = 20_000; + int limit = 20_000; - Map map = rangeClosed(1, limit) + Map map = LongStream.rangeClosed(1, limit) .parallel() .boxed() - .collect(toMap(identity(), AmicablePairs::properDivsSum)); + .collect(Collectors.toMap(Function.identity(), AmicablePairs::properDivsSum)); - rangeClosed(1, limit) + LongStream.rangeClosed(1, limit) .forEach(n -> { long m = map.get(n); if (m > n && m <= limit && map.get(m) == n) @@ -22,6 +22,6 @@ public class AmicablePairs { } public static Long properDivsSum(long n) { - return rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0).sum(); + return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0).sum(); } } diff --git a/Task/Amicable-pairs/jq/amicable-pairs-1.jq b/Task/Amicable-pairs/Jq/amicable-pairs-1.jq similarity index 100% rename from Task/Amicable-pairs/jq/amicable-pairs-1.jq rename to Task/Amicable-pairs/Jq/amicable-pairs-1.jq diff --git a/Task/Amicable-pairs/jq/amicable-pairs-2.jq b/Task/Amicable-pairs/Jq/amicable-pairs-2.jq similarity index 100% rename from Task/Amicable-pairs/jq/amicable-pairs-2.jq rename to Task/Amicable-pairs/Jq/amicable-pairs-2.jq diff --git a/Task/Amicable-pairs/Kotlin/amicable-pairs.kotlin b/Task/Amicable-pairs/Kotlin/amicable-pairs.kotlin new file mode 100644 index 0000000000..d8e787c891 --- /dev/null +++ b/Task/Amicable-pairs/Kotlin/amicable-pairs.kotlin @@ -0,0 +1,17 @@ +// version 1.1 + +fun sumProperDivisors(n: Int): Int { + if (n < 2) return 0 + return (1..n / 2).filter{ (n % it) == 0 }.sum() +} + +fun main(args: Array) { + val sum = IntArray(20000, { sumProperDivisors(it) } ) + println("The pairs of amicable numbers below 20,000 are:\n") + for(n in 2..19998) { + val m = sum[n] + if (m > n && m < 20000 && n == sum[m]) { + println(n.toString().padStart(5) + " and " + m.toString().padStart(5)) + } + } +} diff --git a/Task/Amicable-pairs/Maple/amicable-pairs.maple b/Task/Amicable-pairs/Maple/amicable-pairs.maple new file mode 100644 index 0000000000..e25f933c5f --- /dev/null +++ b/Task/Amicable-pairs/Maple/amicable-pairs.maple @@ -0,0 +1,13 @@ +with(NumberTheory): +pairs:=[]; +for i from 1 to 20000 do + for j from i+1 to 20000 do + sum1:=SumOfDivisors(j)-j; + sum2:=SumOfDivisors(i)-i; + if sum1=i and sum2=j and i<>j then + pairs:=[op(pairs),[i,j]]; + printf("%a", pairs); + end if; + end do; +end do; +pairs; diff --git a/Task/Amicable-pairs/Scheme/amicable-pairs.ss b/Task/Amicable-pairs/Scheme/amicable-pairs.ss new file mode 100644 index 0000000000..d39eba7683 --- /dev/null +++ b/Task/Amicable-pairs/Scheme/amicable-pairs.ss @@ -0,0 +1,49 @@ +(import (scheme base) + (scheme inexact) + (scheme write) + (only (srfi 1) fold)) + +;; return a list of the proper-divisors of n +(define (proper-divisors n) + (let ((root (sqrt n))) + (let loop ((divisors (list 1)) + (i 2)) + (if (> i root) + divisors + (loop (if (zero? (modulo n i)) + (if (= (square i) n) + (cons i divisors) + (append (list i (quotient n i)) divisors)) + divisors) + (+ 1 i)))))) + +(define (sum-proper-divisors n) + (if (< n 2) + 0 + (fold + 0 (proper-divisors n)))) + +(define *max-n* 20000) + +;; hold sums of proper divisors in a cache, to avoid recalculating +(define *cache* (make-vector (+ 1 *max-n*))) +(for-each (lambda (i) (vector-set! *cache* i (sum-proper-divisors i))) + (iota *max-n* 1)) + +(define (amicable-pair? i j) + (and (not (= i j)) + (= i (vector-ref *cache* j)) + (= j (vector-ref *cache* i)))) + +;; double loop to *max-n*, displaying all amicable pairs +(let loop-i ((i 1)) + (when (<= i *max-n*) + (let loop-j ((j i)) + (when (<= j *max-n*) + (when (amicable-pair? i j) + (display (string-append "Amicable pair: " + (number->string i) + " " + (number->string j))) + (newline)) + (loop-j (+ 1 j)))) + (loop-i (+ 1 i)))) diff --git a/Task/Amicable-pairs/Sidef/amicable-pairs.sidef b/Task/Amicable-pairs/Sidef/amicable-pairs.sidef index 858becaaa7..06dc02f01c 100644 --- a/Task/Amicable-pairs/Sidef/amicable-pairs.sidef +++ b/Task/Amicable-pairs/Sidef/amicable-pairs.sidef @@ -1,15 +1,14 @@ func propdivsum(x) { gather { - 2.to(x.isqrt).each { |d| - if (x %% d) { - take(d) - take(x/d) if !x.is_sqr + for d in (2 .. x.isqrt) { + if (d.divides(x)) { + take(d, x/d) } } - }.sum(x > 0 ? 1 : 0) + }.uniq.sum(x > 0 ? 1 : 0) } -1.to(20000).each { |i| +for i (1..20000) { var j = propdivsum(i) say "#{i} #{j}" if (j>i && i==propdivsum(j)) } diff --git a/Task/Amicable-pairs/Zkl/amicable-pairs.zkl b/Task/Amicable-pairs/Zkl/amicable-pairs.zkl new file mode 100644 index 0000000000..1bbfd88e62 --- /dev/null +++ b/Task/Amicable-pairs/Zkl/amicable-pairs.zkl @@ -0,0 +1,4 @@ +fcn properDivs(n){ [1.. (n + 1)/2 + 1].filter('wrap(x){ n%x==0 and n!=x }) } +const N=20000; +sums:=[1..N].pump(T(-1),fcn(n){ properDivs(n).sum(0) }); +[0..].zip(sums).filter('wrap([(n,s)]){ (n String.split - |> Enum.group_by(fn word -> String.codepoints(word) |> Enum.sort end) + |> Enum.map(fn word -> to_charlist(word) end) + |> Enum.group_by(fn word -> Enum.sort(word) end) |> Enum.filter(fn {_,words} -> length(words) > 1 end) |> Enum.sort_by(fn {key,_} -> -length(key) end) |> Enum.find(fn {_,words} -> find_derangements(words) end) @@ -13,8 +14,7 @@ defmodule Anagrams do end defp deranged?(a,b) do - Enum.zip(String.codepoints(a), String.codepoints(b)) - |> Enum.all?(fn {chr_a,chr_b} -> chr_a != chr_b end) + Enum.zip(a, b) |> Enum.all?(fn {chr_a,chr_b} -> chr_a != chr_b end) end defp comb(_, 0), do: [[]] diff --git a/Task/Anagrams-Deranged-anagrams/Java/anagrams-deranged-anagrams.java b/Task/Anagrams-Deranged-anagrams/Java/anagrams-deranged-anagrams.java index 870a8ac461..7d7dcfbeb4 100644 --- a/Task/Anagrams-Deranged-anagrams/Java/anagrams-deranged-anagrams.java +++ b/Task/Anagrams-Deranged-anagrams/Java/anagrams-deranged-anagrams.java @@ -1,62 +1,47 @@ -import java.io.*; -import java.util.*; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class DerangedAnagrams { - public static void main(final String[] args) throws IOException { - if (!findAnagrams(readLines("unixdict.txt"))) - System.out.println("no result"); + public static void main(String[] args) throws IOException { + List words = Files.readAllLines(new File("unixdict.txt").toPath()); + printLongestDerangedAnagram(words); } - private static boolean isDeranged(final String w, final List lst) { - for (String w2 : lst) { - int k = w.length() - 1; - while (k >= 0 && w.charAt(k) != w2.charAt(k)) { - k--; - } - if (k == -1) { - System.out.println(w + ", " + w2); - return true; - } - } - return false; - } + private static void printLongestDerangedAnagram(List words) { + words.sort(Comparator.comparingInt(String::length).reversed().thenComparing(String::toString)); - private static boolean findAnagrams(final List words) { - Collections.sort(words, new Comparator() { - public int compare(String a, String b) { - return b.length() - a.length(); - } - }); Map> map = new HashMap<>(); - for (String w : words) { - char[] srt = w.toCharArray(); - Arrays.sort(srt); - String key = String.valueOf(srt); - ArrayList lst; - if (map.containsKey(key)) { - lst = map.get(key); - if (isDeranged(w, lst)) { - return true; + for (String word : words) { + char[] chars = word.toCharArray(); + Arrays.sort(chars); + String key = String.valueOf(chars); + + List anagrams = map.computeIfAbsent(key, k -> new ArrayList<>()); + for (String anagram : anagrams) { + if (isDeranged(word, anagram)) { + System.out.printf("%s %s%n", anagram, word); + return; } - lst.add(w); - } else { - lst = new ArrayList<>(); - lst.add(w); - map.put(key, lst); } + anagrams.add(word); } - return false; + System.out.println("no result"); } - private static List readLines(final String fn) throws IOException { - List lines; - try (BufferedReader br = new BufferedReader(new FileReader(fn))) { - lines = new ArrayList<>(); - String line = null; - while ((line = br.readLine()) != null) - lines.add(line); + private static boolean isDeranged(String word1, String word2) { + for (int i = 0; i < word1.length(); i++) { + if (word1.charAt(i) == word2.charAt(i)) { + return false; + } } - return lines; + return true; } } diff --git a/Task/Anagrams-Deranged-anagrams/Jq/anagrams-deranged-anagrams.jq b/Task/Anagrams-Deranged-anagrams/Jq/anagrams-deranged-anagrams.jq new file mode 100644 index 0000000000..c0637eace7 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/Jq/anagrams-deranged-anagrams.jq @@ -0,0 +1,32 @@ +# Input: an array of strings +# Output: a stream of arrays +def anagrams: + reduce .[] as $word ( + {table: {}, max: 0}; # state + ($word | explode | sort | implode) as $hash + | .table[$hash] += [ $word ] + | .max = ([ .max, ( .table[$hash] | length) ] | max ) ) + | .table | .[] | select(length>1); + +# Check whether the input and y are deranged, +# on the assumption that they are anagrams: +def deranged(y): + explode as $x # explode is fast + | (y | explode) as $y + | all( range(0;length); $x[.] != $y[.] ); + +# The task: loop through the anagrams, +# retaining only the best set of deranged anagrams so far. +split("\n") | select(length>0) # read all the words as an array +| reduce anagrams as $words ([]; # loop through all the anagrams + reduce $words[] as $v (.; + reduce ($words - [$v])[] as $w (.; # $v and $w are distinct members of $words + if $v|deranged($w) + then if length == 0 then [$v,$w] + elif ($v|length) == (.[0]|length) then . + [$v,$w] + elif ($v|length) > (.[0]|length) then [$v,$w] + else . + end + else . + end) ) ) +| unique diff --git a/Task/Anagrams-Deranged-anagrams/Kotlin/anagrams-deranged-anagrams.kotlin b/Task/Anagrams-Deranged-anagrams/Kotlin/anagrams-deranged-anagrams.kotlin new file mode 100644 index 0000000000..8ffd9ba3bf --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/Kotlin/anagrams-deranged-anagrams.kotlin @@ -0,0 +1,39 @@ +// version 1.0.6 + +import java.io.BufferedReader +import java.io.InputStreamReader +import java.net.URL + +fun isDeranged(s1: String, s2: String): Boolean { + return (0 until s1.length).none { s1[it] == s2[it] } +} + +fun main(args: Array) { + val url = URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt") + val isr = InputStreamReader(url.openStream()) + val reader = BufferedReader(isr) + val anagrams = mutableMapOf>() + var count = 0 + var word = reader.readLine() + while (word != null) { + val chars = word.toCharArray() + chars.sort() + val key = chars.joinToString("") + if (!anagrams.containsKey(key)) { + anagrams.put(key, mutableListOf()) + anagrams[key]!!.add(word) + } + else { + val deranged = anagrams[key]!!.any { isDeranged(it, word) } + if (deranged) { + anagrams[key]!!.add(word) + count = Math.max(count, word.length) + } + } + word = reader.readLine() + } + reader.close() + anagrams.values + .filter { it.size > 1 && it[0].length == count } + .forEach { println(it) } +} diff --git a/Task/Anagrams-Deranged-anagrams/OoRexx/anagrams-deranged-anagrams.rexx b/Task/Anagrams-Deranged-anagrams/OoRexx/anagrams-deranged-anagrams.rexx new file mode 100644 index 0000000000..8225fea97e --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/OoRexx/anagrams-deranged-anagrams.rexx @@ -0,0 +1,63 @@ +-- This assumes you've already downloaded the following file and placed it +-- in the current directory: http://www.puzzlers.org/pub/wordlists/unixdict.txt + +-- There are several different ways of reading the file. I chose the +-- supplier method just because I haven't used it yet in any other examples. +source = .stream~new('unixdict.txt')~supplier +-- this holds our mappings of the anagrams. This is good use for the +-- relation class +anagrams = .relation~new +count = 0 -- this is used to keep track of the maximums + +loop while source~available + word = source~item + -- this produces a string consisting of the characters in sorted order + -- Note: the ~~ used to invoke sort makes that message return value be + -- the target array. The sort method does not normally have a return value. + key = word~makearray('')~~sort~tostring("l", "") + -- add this to our mapping. This creates multiple entries for each + -- word that uses the same key + anagrams[key] = word + source~next +end + +-- now get the set of unique keys +keys = .set~new~~putall(anagrams~allIndexes) +-- the longest count tracker +longest = 0 +-- our list of the longest pairs +pairs = .array~new + +loop key over keys + -- don't even bother doing the deranged checks for any key + -- shorter than our current longest + if key~length < longest then iterate + + words = anagrams~allAt(key) + -- singletons aren't anagrams at all + newCount = words~items + loop i = 1 to newCount - 1 + word1 = words[i] + loop j = 1 to newCount + word2 = words[j] + -- bitxor will have '00'x in every position where these + -- strings match. If found, go around and check the + -- next one + if word1~bitxor(word2)~pos('00'x) > 0 then iterate + -- we have a match + else do + if word1~length > longest then do + -- throw away anything we've gathered so far + pairs~empty + longest = word1~length + end + pairs~append(.array~of(word1, word2)) + end + end + end +end + +say "The longest deranged anagrams we found are:" +loop pair over pairs + say pair[1] pair[2] +end diff --git a/Task/Anagrams-Deranged-anagrams/Perl-6/anagrams-deranged-anagrams-1.pl6 b/Task/Anagrams-Deranged-anagrams/Perl-6/anagrams-deranged-anagrams-1.pl6 deleted file mode 100644 index 461126470c..0000000000 --- a/Task/Anagrams-Deranged-anagrams/Perl-6/anagrams-deranged-anagrams-1.pl6 +++ /dev/null @@ -1 +0,0 @@ -grep '^[ie]' unixdict.txt > dict.ie diff --git a/Task/Anagrams-Deranged-anagrams/Perl-6/anagrams-deranged-anagrams-2.pl6 b/Task/Anagrams-Deranged-anagrams/Perl-6/anagrams-deranged-anagrams-2.pl6 deleted file mode 100644 index 73ae78c462..0000000000 --- a/Task/Anagrams-Deranged-anagrams/Perl-6/anagrams-deranged-anagrams-2.pl6 +++ /dev/null @@ -1,12 +0,0 @@ -my %anagram = slurp('dict.ie').words.map({[.comb]}).classify({ .sort.join }); - -for %anagram.values.sort({ -@($_[0]) }) -> @aset { - for 0 ..^ @aset.end -> $i { - for $i ^.. @aset.end -> $j { - if none( @aset[$i].list Zeq @aset[$j].list ) { - say "{@aset[$i].join} {@aset[$j].join}"; - exit; - } - } - } -} diff --git a/Task/Anagrams-Deranged-anagrams/PowerShell/anagrams-deranged-anagrams.psh b/Task/Anagrams-Deranged-anagrams/PowerShell/anagrams-deranged-anagrams.psh new file mode 100644 index 0000000000..9943253fa3 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/PowerShell/anagrams-deranged-anagrams.psh @@ -0,0 +1,33 @@ +function Test-Deranged ([string[]]$Strings) +{ + $array1 = $Strings[0].ToCharArray() + + for ($i = 1; $i -lt $Strings.Count; $i++) + { + $array2 = $Strings[$i].ToCharArray() + + for ($i = 0; $i -lt $array1.Count; $i++) + { + if ($array1[$i] -match $array2[$i]) + { + return $false + } + } + } + + return $true +} + + +$words = [System.Collections.ArrayList]@() + +Get-Content -Path ".\unixdict.txt" | + ForEach-Object { [void]$words.Add([PSCustomObject]@{Word=$_; SortedWord=(($_.ToCharArray() | Sort-Object) -join "")}) } + +[object[]]$anagrams = $words | Group-Object -Property SortedWord | Where-Object -Property Count -GT 1 | Sort-Object {$_.Name.Length} +[string[]]$deranged = ($anagrams | ForEach-Object { if ((Test-Deranged $_.Group.Word)) {$_} } | Select-Object -Last 1).Group.Word + +[PSCustomObject]@{ + Length = $deranged[0].Length + Words = $deranged +} diff --git a/Task/Anagrams-Deranged-anagrams/Scheme/anagrams-deranged-anagrams.ss b/Task/Anagrams-Deranged-anagrams/Scheme/anagrams-deranged-anagrams.ss new file mode 100644 index 0000000000..e06a2ef2b9 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/Scheme/anagrams-deranged-anagrams.ss @@ -0,0 +1,49 @@ +(import (scheme base) + (scheme char) + (scheme cxr) + (scheme file) + (scheme write) + (srfi 1) ; lists + (srfi 132)) ; sorting library + +;; read in word list, and sort into decreasing length +(define (read-ordered-words) + (with-input-from-file + "unixdict.txt" + (lambda () + (do ((line (read-line) (read-line)) + (words '() (cons line words))) + ((eof-object? line) + (list-sort (lambda (a b) (> (string-length a) (string-length b))) + words)))))) + +(define (find-deranged-words word-list) + (define (search words) + (let loop ((word-chars (let ((chars (map string->list words))) + (zip chars + (map (lambda (word) (list-sort charstring (list (caar word-chars) (car deranged-word))) + (loop (cdr word-chars))))))) + ; + (let loop ((rem word-list)) + (if (null? rem) + '() + (let* ((len (string-length (car rem))) + (deranged-words (search ; look through group of equal sized words + (take-while (lambda (word) (= len (string-length word))) + (cdr rem))))) + (if deranged-words + deranged-words + (loop (drop-while (lambda (word) (= len (string-length word))) + (cdr rem)))))))) + +(display (find-deranged-words (read-ordered-words))) (newline) diff --git a/Task/Anagrams-Deranged-anagrams/Sidef/anagrams-deranged-anagrams.sidef b/Task/Anagrams-Deranged-anagrams/Sidef/anagrams-deranged-anagrams.sidef index 805d3934cc..a055f83dfd 100644 --- a/Task/Anagrams-Deranged-anagrams/Sidef/anagrams-deranged-anagrams.sidef +++ b/Task/Anagrams-Deranged-anagrams/Sidef/anagrams-deranged-anagrams.sidef @@ -1,6 +1,6 @@ func find_deranged(Array a) { - for i in range(a) { - for j in range(i+1, a.end) { + for i in (^a) { + for j in (i+1 .. a.end) { overlaps(a[i], a[j]) || ( printf("length %d: %s => %s\n", a[i].len, a[i], a[j]) return true diff --git a/Task/Anagrams-Deranged-anagrams/Zkl/anagrams-deranged-anagrams-1.zkl b/Task/Anagrams-Deranged-anagrams/Zkl/anagrams-deranged-anagrams-1.zkl new file mode 100644 index 0000000000..f0cd2f3122 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/Zkl/anagrams-deranged-anagrams-1.zkl @@ -0,0 +1,22 @@ +words:=Dictionary(25000); //-->Dictionary(sorted word:all anagrams, ...) +File("unixdict.txt").read().pump(Void,'wrap(w){ + w=w.strip(); key:=w.sort(); words[key]=words.find(key,T).append(w); +}); + +nws:=words.values.pump(List,fcn(ws){ //-->( (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)); + } + } + if(r) return(r.insert(0,n)); + } + Void.Skip +}); + +nws.filter(fcn(nws,max){ nws[0]==max }, + nws.reduce(fcn(p,nws){ p.max(nws[0]) },0) ) +.println(); diff --git a/Task/Anagrams-Deranged-anagrams/Zkl/anagrams-deranged-anagrams-2.zkl b/Task/Anagrams-Deranged-anagrams/Zkl/anagrams-deranged-anagrams-2.zkl new file mode 100644 index 0000000000..ce697554b4 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/Zkl/anagrams-deranged-anagrams-2.zkl @@ -0,0 +1,10 @@ +nws:=words.values.pump(List,fcn(ws){ //-->( (len,words), ...) + if(ws.len()>1){ // two or more anagrams + 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/8th/anagrams.8th b/Task/Anagrams/8th/anagrams.8th new file mode 100644 index 0000000000..e9c07ba544 --- /dev/null +++ b/Task/Anagrams/8th/anagrams.8th @@ -0,0 +1,132 @@ +\ +\ anagrams.8th +\ Rosetta Code - Anagrams problem +\ Using the word list at: +\ http://www.puzzlers.org/pub/wordlists/unixdict.txt, +\ find the sets of words that share the same characters +\ that contain the most words in them. +\ + +ns: anagrams + +m:new var, anamap +a:new var, anaptr +0 var, analen + +\ sort a string +: s:sort \ s -- s \ + null s:/ \ a + ' s:cmpi a:sort \ a + "" a:join \ s + ; + +: process-words \ word -- \ word + s:lc \ word + dup \ word word + >r \ word | word + \ 1. we create a sorted version of the curret word (sword) + s:sort \ sword | word + \ We check if sword can be found in map anamap + anamap @ \ sword anamap | word + over \ sword anamap sword | word + m:exists? \ sword anamap boolean | word + if \ sword anamap | word + \ If sword already exists in anamap: + \ - get mapvalue, which is an array + \ - add the original word to that array + \ - store the array in the map with key sword + over \ sword anamap sword | word + m:@ \ sword anamap array | word + r> \ sword anamap array word + a:push \ sword anamap array + rot \ anamap array sword + swap \ anamap sword array + m:! \ anamap + else \ sword anamap | word + \ If sword does not yet exist in anamap: + \ - create empty array + \ - put the original word into that array + \ - store the array in the map with key sword + swap \ anamap sword | word + a:new \ anamap sword array | word + r> \ anamap sword array word + a:push \ anamap sword array + m:! \ anamap + then + drop \ + ; + +\ Read and check all words in array analist +: read-and-check-words \ -- \ + "analist.txt" \ fname + f:open-ro \ f + ' process-words f:eachline \ f + f:close \ + ; + +: len< \ key array arraylen -- \ key array arraylen + 2drop \ key + drop \ + ; + +: len= \ key array arraylen -- \ key array arraylen + 2drop \ key + anaptr @ \ key anaptr + swap \ anaptr key + a:push \ anaptr + drop \ + ; + +: len> \ key array arraylen -- \ key array arraylen + analen \ key array arraylen analen + ! \ key array + drop \ key + anaptr @ \ key anaptr + a:clear \ key anaptr + swap \ anaptr key + a:push \ anaptr + drop \ + ; + +: fetch-longest-list \ key array -- \ key array + a:len \ key array arraylen + analen @ \ key array arraylen analen + 2dup \ key array arraylen analen arraylen analen + n:cmp \ key array arraylen analen value + 1 n:+ \ key array arraylen analen value + nip \ key array arraylen value + [ ' len< , ' len= , ' len> ] \ key array arraylen value swarr + swap \ key array arraylen swarr value + caseof \ + ; + +: list-words-1 \ ix value -- \ ix value + nip \ value + "\t" . . \ + ; + +: list-words \ ix value -- \ ix value + nip \ value + anamap @ \ value anamap + swap \ anamap value + m:@ \ anamap array + nip \ array + ' list-words-1 a:each \ array + cr \ array + drop \ + ; + +: app:main + + \ Create a map, where the values are arrays, containing all words + \ which are the same when sorted (sword); sword is used as key + read-and-check-words + + \ Create an array that holds the keys for anamap, for which the value, + \ which is the array of anagrams, has the biggest length found. + anamap @ ' fetch-longest-list m:each + + \ Dump the resulting words to the console + anaptr @ ' list-words a:each drop + bye + ; diff --git a/Task/Anagrams/Clojure/anagrams.clj b/Task/Anagrams/Clojure/anagrams-1.clj similarity index 100% rename from Task/Anagrams/Clojure/anagrams.clj rename to Task/Anagrams/Clojure/anagrams-1.clj diff --git a/Task/Anagrams/Clojure/anagrams-2.clj b/Task/Anagrams/Clojure/anagrams-2.clj new file mode 100644 index 0000000000..65ae8078d5 --- /dev/null +++ b/Task/Anagrams/Clojure/anagrams-2.clj @@ -0,0 +1,15 @@ +(->> (slurp "http://www.puzzlers.org/pub/wordlists/unixdict.txt") + (apply str) + clojure.string/split-lines + (group-by sort) + vals + (sort-by count #(compare %2 %1)) ;; sort in reverse + (partition-by count) + first) + +;; (["caret" "carte" "cater" "crate" "trace"] +;; ["angel" "angle" "galen" "glean" "lange"] +;; ["elan" "lane" "lean" "lena" "neal"] +;; ["alger" "glare" "lager" "large" "regal"] +;; ["evil" "levi" "live" "veil" "vile"] +;; ["abel" "able" "bale" "bela" "elba"]) diff --git a/Task/Anagrams/Common-Lisp/anagrams-4.lisp b/Task/Anagrams/Common-Lisp/anagrams-4.lisp deleted file mode 100644 index 077815ca61..0000000000 --- a/Task/Anagrams/Common-Lisp/anagrams-4.lisp +++ /dev/null @@ -1,9 +0,0 @@ -import std.stdio, std.algorithm, std.range, std.string, std.exception; - -void main() { - string[][const ubyte[]] an; - foreach (w; "unixdict.txt".File.byLine(KeepTerminator.no)) - an[w.dup.representation.sort().release.assumeUnique] ~= w.idup; - immutable m = an.byValue.map!q{ a.length }.reduce!max; - writefln("%(%s\n%)", an.byValue.filter!(ws => ws.length == m)); -} diff --git a/Task/Anagrams/Common-Lisp/anagrams-5.lisp b/Task/Anagrams/Common-Lisp/anagrams-5.lisp deleted file mode 100644 index cd5cfc1fa8..0000000000 --- a/Task/Anagrams/Common-Lisp/anagrams-5.lisp +++ /dev/null @@ -1,13 +0,0 @@ -import std.stdio, std.algorithm, std.file, std.string; - -void main() { - char[] keys = cast(char[])"unixdict.txt".read; - immutable vals = keys.idup; - string[][string] anags; - foreach (w; keys.splitter) { - immutable k = cast(string)w.representation.sort().release; - anags[k] ~= vals[k.ptr-keys.ptr .. k.ptr-keys.ptr + k.length]; - } - immutable m = anags.byValue.map!q{ a.length }.reduce!max; - writefln("%(%s\n%)", anags.byValue.filter!(ws => ws.length == m)); -} diff --git a/Task/Anagrams/Common-Lisp/anagrams-6.lisp b/Task/Anagrams/Common-Lisp/anagrams-6.lisp deleted file mode 100644 index a653db655f..0000000000 --- a/Task/Anagrams/Common-Lisp/anagrams-6.lisp +++ /dev/null @@ -1,10 +0,0 @@ -import std.stdio, std.stream, tools.functional, tools.base; - -void main() { - ( (new BufferedFile("/usr/share/dict/cracklib-small")) - /map/ ex!("s -> s.dup") - /groupby/ ex!("s -> s.dup.sort") - /map/ (string key, string[] value) { return value; } - /qsort/ ex!("a, b -> a.length < b.length") - )[$-1].writefln(); -} diff --git a/Task/Anagrams/Elena/anagrams.elena b/Task/Anagrams/Elena/anagrams.elena index 2779c65908..6ee99abcd0 100644 --- a/Task/Anagrams/Elena/anagrams.elena +++ b/Task/Anagrams/Elena/anagrams.elena @@ -1,34 +1,37 @@ -#import system. -#import system'routines. -#import system'io. -#import system'collections. -#import extensions. -#import extensions'routines. +import system'routines. +import system'calendar. +import system'io. +import system'collections. +import extensions. +import extensions'routines. -#class(extension) op +extension op { - #method normalized - = self toArray ascendant summarize:(String new) literal. + normalized + = self toArray; ascendant; summarize(String new); literal. } -#symbol program = +symbol program = [ - #var aDictionary := Dictionary new. + var aDictionary := Dictionary new. - "unixdict.txt" file_path run &eachLine: aWord + File new("unixdict.txt"); forEachLine(:aWord) [ - #var aKey := aWord normalized. - #var anItem := aDictionary@aKey. - ($nil == anItem) ? + var s := aWord. + var aKey := aWord normalized. + var anItem := aDictionary[aKey]. + if ($nil == anItem) [ anItem := ArrayList new. - aDictionary@aKey := anItem. + aDictionary[aKey] := anItem. ]. - anItem += aWord. + anItem append:aWord. ]. - aDictionary array_list - sort: (:aFormer:aLater) [ aFormer length > aLater length ] - top:20 run &each: aPair [ console writeLine:aPair ]. + aDictionary array_list; + sort(:aFormer:aLater)( aFormer length > aLater length ); + top:20; forEach(:aPair)[ console printLine(aPair value) ]. + + console readChar. ]. diff --git a/Task/Anagrams/Frink/anagrams.frink b/Task/Anagrams/Frink/anagrams.frink new file mode 100644 index 0000000000..8ba2f436ae --- /dev/null +++ b/Task/Anagrams/Frink/anagrams.frink @@ -0,0 +1,20 @@ +d = new dict +for w = lines["http://www.puzzlers.org/pub/wordlists/unixdict.txt"] +{ + sorted = sort[charList[w]] + curr = d@sorted + if curr + d@sorted.push[w] + else + d@sorted = [w] +} + +most = sort[toArray[d], {|a,b| length[b@1] <=> length[a@1]}] +longest = length[most@0@1] + +i = 0 +while length[most@i@1] == longest +{ + println[most@i@1] + i = i + 1 +} diff --git a/Task/Anagrams/Go/anagrams-5.go b/Task/Anagrams/Go/anagrams-5.go new file mode 100644 index 0000000000..16be1e72aa --- /dev/null +++ b/Task/Anagrams/Go/anagrams-5.go @@ -0,0 +1,12 @@ +import Data.List (groupBy, maximumBy, sort) +import Data.Ord (comparing) +import Data.Function (on) +import Data.Text (pack) + +main :: IO () +main = do + f <- readFile "./unixdict.txt" + let ws = groupBy (on (==) fst) (sort (((,) =<< pack . sort) <$> lines f)) + mapM_ + (print . fmap snd) + (filter ((length (maximumBy (comparing length) ws) ==) . length) ws) diff --git a/Task/Anagrams/jq/anagrams-1.jq b/Task/Anagrams/Jq/anagrams-1.jq similarity index 80% rename from Task/Anagrams/jq/anagrams-1.jq rename to Task/Anagrams/Jq/anagrams-1.jq index 6365ca6cfa..888a949f94 100644 --- a/Task/Anagrams/jq/anagrams-1.jq +++ b/Task/Anagrams/Jq/anagrams-1.jq @@ -2,7 +2,7 @@ def anagrams: (reduce .[] as $word ( {table: {}, max: 0}; # state ($word | explode | sort | implode) as $hash - | .table = ( .table + { ($hash): ( .table[$hash] + [ $word ]) }) + | .table[$hash] += [ $word ] | .max = ([ .max, ( .table[$hash] | length) ] | max ) )) | .max as $max | .table | .[] | select(length == $max) ; diff --git a/Task/Anagrams/jq/anagrams-2.jq b/Task/Anagrams/Jq/anagrams-2.jq similarity index 100% rename from Task/Anagrams/jq/anagrams-2.jq rename to Task/Anagrams/Jq/anagrams-2.jq diff --git a/Task/Anagrams/Julia/anagrams.julia b/Task/Anagrams/Julia/anagrams.julia index 6f41b834ff..e5c7144a75 100644 --- a/Task/Anagrams/Julia/anagrams.julia +++ b/Task/Anagrams/Julia/anagrams.julia @@ -1,6 +1,6 @@ url = "http://www.puzzlers.org/pub/wordlists/unixdict.txt" -wordlist = map!(chomp,(open(readlines, download(url)))) +wordlist = open(readlines, download(url)) wsort(word) = join(sort(collect(word))) diff --git a/Task/Anagrams/Kotlin/anagrams.kotlin b/Task/Anagrams/Kotlin/anagrams.kotlin new file mode 100644 index 0000000000..ef6c63a1c4 --- /dev/null +++ b/Task/Anagrams/Kotlin/anagrams.kotlin @@ -0,0 +1,25 @@ +import java.io.BufferedReader +import java.io.InputStreamReader +import java.net.URL + +fun main(args: Array) { + val url = URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt") + val isr = InputStreamReader(url.openStream()) + val reader = BufferedReader(isr) + val anagrams = mutableMapOf>() + var count = 0 + var word = reader.readLine() + while (word != null) { + val chars = word.toCharArray() + chars.sort() + val key = chars.joinToString("") + if (!anagrams.containsKey(key)) anagrams.put(key, mutableListOf()) + anagrams[key]!!.add(word) + count = Math.max(count, anagrams[key]!!.size) + word = reader.readLine() + } + reader.close() + anagrams.values + .filter { it.size == count } + .forEach { println(it) } +} diff --git a/Task/Anagrams/Nim/anagrams.nim b/Task/Anagrams/Nim/anagrams.nim index ea90687abb..bfe3286c6c 100644 --- a/Task/Anagrams/Nim/anagrams.nim +++ b/Task/Anagrams/Nim/anagrams.nim @@ -11,8 +11,8 @@ proc main() = anagrams.mgetOrPut(key, newSeq[string]()).add(word) count = max(count, anagrams[key].len) - for k, v in anagrams: + for _, v in anagrams: if v.len == count: - v.join(", ").echo + v.join(" ").echo main() diff --git a/Task/Anagrams/Nimrod/anagrams.nimrod b/Task/Anagrams/Nimrod/anagrams.nimrod deleted file mode 100644 index 29650e835e..0000000000 --- a/Task/Anagrams/Nimrod/anagrams.nimrod +++ /dev/null @@ -1,52 +0,0 @@ -import tables - -proc sort(s: string): string = - var - i,j: int - t: char - - result = s - for i in 0 .. result.len - 1: - j = i - t = result[j] - while(j > 0) and (result[j - 1] > t): - result[j] = result[j - 1] - dec(j) - result[j] = t -# end sort - -proc maxCount(an: TTable[string,seq[string]]): int = - result = 0 - for v in an.values: - if v.len > result: - result = v.len -#end maxCount - -proc showAnagrams(s: seq[string]) = - for v in s: - write(stdout,v) - write(stdout," ") - writeln(stdout,"") -#end showAnagrams - -proc processFile: TTable[string,seq[string]] = - var - fd: TFile - sline,line: string - - result = initTable[string,seq[string]]() - if Open(fd,"unixdict.txt"): - while not EndOfFile(fd): - line = fd.readLine() - sline = sort(line) - if result.hasKey(sline): - result[sline] = result[sline] & line - else: - result[sline] = @[line] - -var - anagrams:TTable[string,seq[string]] = processFile() - max = anagrams.maxCount - -for v in anagrams.values: - if v.len == max: showAnagrams(v) diff --git a/Task/Anagrams/OoRexx/anagrams-1.rexx b/Task/Anagrams/OoRexx/anagrams-1.rexx new file mode 100644 index 0000000000..4f65d777df --- /dev/null +++ b/Task/Anagrams/OoRexx/anagrams-1.rexx @@ -0,0 +1,35 @@ +-- This assumes you've already downloaded the following file and placed it +-- in the current directory: http://www.puzzlers.org/pub/wordlists/unixdict.txt + +-- There are several different ways of reading the file. I chose the +-- supplier method just because I haven't used it yet in any other examples. +source = .stream~new('unixdict.txt')~supplier +-- this holds our mappings of the anagrams +anagrams = .directory~new +count = 0 -- this is used to keep track of the maximums + +loop while source~available + word = source~item + -- this produces a string consisting of the characters in sorted order + -- Note: the ~~ used to invoke sort makes that message return value be + -- the target array. The sort method does not normally have a return value. + key = word~makearray('')~~sort~tostring("l", "") + + -- make sure we have an accumulator collection for this key + list = anagrams[key] + if list == .nil then do + list = .array~new + anagrams[key] = list + end + -- this word is now associate with this key + list~append(word) + -- and see if this is a new highest count + count = max(count, list~items) + source~next +end + +loop letters over anagrams + list = anagrams[letters] + if list~items >= count then + say letters":" list~makestring("l", ", ") +end diff --git a/Task/Anagrams/OoRexx/anagrams-2.rexx b/Task/Anagrams/OoRexx/anagrams-2.rexx new file mode 100644 index 0000000000..bd6080e404 --- /dev/null +++ b/Task/Anagrams/OoRexx/anagrams-2.rexx @@ -0,0 +1,46 @@ +-- This assumes you've already downloaded the following file and placed it +-- in the current directory: http://www.puzzlers.org/pub/wordlists/unixdict.txt + +-- There are several different ways of reading the file. I chose the +-- supplier method just because I haven't used it yet in any other examples. +source = .stream~new('unixdict.txt')~supplier +-- this holds our mappings of the anagrams. This is good use for the +-- relation class +anagrams = .relation~new +count = 0 -- this is used to keep track of the maximums + +loop while source~available + word = source~item + -- this produces a string consisting of the characters in sorted order + -- Note: the ~~ used to invoke sort makes that message return value be + -- the target array. The sort method does not normally have a return value. + key = word~makearray('')~~sort~tostring("l", "") + -- add this to our mapping. This creates multiple entries for each + -- word that uses the same key + anagrams[key] = word + source~next +end + +-- now get the set of unique keys +keys = .set~new~~putall(anagrams~allIndexes) +count = 0 -- this is used to keep track of the maximums +most = .directory~new + +loop key over keys + words = anagrams~allAt(key) + newCount = words~items + if newCount > count then do + -- throw away our old set + most~empty + count = newCount + most[key] = words + end + -- matches our highest count, add it to the list + else if newCount == count then + most[key] = words +end + +loop letters over most + words = most[letters] + say letters":" words~makestring("l", ", ") +end diff --git a/Task/Anagrams/Python/anagrams-4.py b/Task/Anagrams/Python/anagrams-4.py deleted file mode 100644 index fc284a8617..0000000000 --- a/Task/Anagrams/Python/anagrams-4.py +++ /dev/null @@ -1,22 +0,0 @@ ->>> import urllib, itertools ->>> words = urllib.urlopen('http://www.puzzlers.org/pub/wordlists/unixdict.txt').read().split() ->>> len(words) -25104 ->>> anagrams = [list(g) for k,g in itertools.groupby(sorted(words, key=sorted), key=sorted)] - - ->>> count = max(len(ana) for ana in anagrams) ->>> for ana in anagrams: - if len(ana) >= count: - print ana - - -['abel', 'able', 'bale', 'bela', 'elba'] -['caret', 'carte', 'cater', 'crate', 'trace'] -['angel', 'angle', 'galen', 'glean', 'lange'] -['alger', 'glare', 'lager', 'large', 'regal'] -['elan', 'lane', 'lean', 'lena', 'neal'] -['evil', 'levi', 'live', 'veil', 'vile'] ->>> count -5 ->>> diff --git a/Task/Anagrams/Racket/anagrams-1.rkt b/Task/Anagrams/Racket/anagrams-1.rkt deleted file mode 100644 index b6a10447e4..0000000000 --- a/Task/Anagrams/Racket/anagrams-1.rkt +++ /dev/null @@ -1,21 +0,0 @@ -#lang racket - -(require net/url) - -(define (get-lines url-string) - (define port (get-pure-port (string->url url-string))) - (for/list ([l (in-lines port)]) l)) - -(define (hash-words words) - (for/fold ([ws-hash (hash)]) ([w words]) - (hash-update ws-hash - (list->string (sort (string->list w) < #:key (λ (c) (char->integer c)))) - (λ (ws) (cons w ws)) - (λ () '())))) - -(define (get-maxes h) - (define max-ws (apply max (map length (hash-values h)))) - (define max-keys (filter (λ (k) (= (length (hash-ref h k)) max-ws)) (hash-keys h))) - (map (λ (k) (hash-ref h k)) max-keys)) - -(get-maxes (hash-words (get-lines "http://www.puzzlers.org/pub/wordlists/unixdict.txt"))) diff --git a/Task/Anagrams/Racket/anagrams-2.rkt b/Task/Anagrams/Racket/anagrams-2.rkt deleted file mode 100644 index 2e7c60f396..0000000000 --- a/Task/Anagrams/Racket/anagrams-2.rkt +++ /dev/null @@ -1,6 +0,0 @@ -'(("neal" "lena" "lean" "lane" "elan") - ("trace" "crate" "cater" "carte" "caret") - ("regal" "large" "lager" "glare" "alger") - ("elba" "bela" "bale" "able" "abel") - ("lange" "glean" "galen" "angle" "angel") - ("vile" "veil" "live" "levi" "evil")) diff --git a/Task/Anagrams/Revolution/anagrams.rev b/Task/Anagrams/Revolution/anagrams.rev deleted file mode 100644 index 21e3f0e6d9..0000000000 --- a/Task/Anagrams/Revolution/anagrams.rev +++ /dev/null @@ -1,34 +0,0 @@ -on mouseUp - repeat for each word W in url "http://www.puzzlers.org/pub/wordlists/unixdict.txt" - put W & comma after A[sortChars(W)] - end repeat - put 0 into winningLength - repeat for each element E in A - get the number of items in E - if it < winningLength then next repeat - if it > winningLength then - put it into winningLength - put empty into winningList - end if - put (char 1 to -2 of E) & cr after winningList - end repeat - put winningList -end mouseUp - -function sortChars X - get charsToItems(X) - sort items of it - return itemsToChars(it) -end sortChars - -function charsToItems X - repeat for each char C in X - put C & comma after R - end repeat - return char 1 to -2 of R -end charsToItems - -function itemsToChars X - replace comma with empty in X - return X -end itemsToChars diff --git a/Task/Anagrams/Rust/anagrams-1.rust b/Task/Anagrams/Rust/anagrams-1.rust new file mode 100644 index 0000000000..f42d8a14ac --- /dev/null +++ b/Task/Anagrams/Rust/anagrams-1.rust @@ -0,0 +1,30 @@ +use std::collections::HashMap; +use std::fs::File; +use std::io::{BufRead,BufReader}; +use std::borrow::ToOwned; + +extern crate unicode_segmentation; +use unicode_segmentation::{UnicodeSegmentation}; + +fn main () { + let file = BufReader::new(File::open("unixdict.txt").unwrap()); + let mut map = HashMap::new(); + for line in file.lines() { + let s = line.unwrap(); + //Bytes: let mut sorted = s.trim().bytes().collect::>(); + //Codepoints: let mut sorted = s.trim().chars().collect::>(); + let mut sorted = s.trim().graphemes(true).map(ToOwned::to_owned).collect::>(); + sorted.sort(); + + map.entry(sorted).or_insert_with(Vec::new).push(s); + } + + if let Some(max_len) = map.values().map(|v| v.len()).max() { + for anagram in map.values().filter(|v| v.len() == max_len) { + for word in anagram { + print!("{} ", word); + } + println!(); + } + } +} diff --git a/Task/Anagrams/Rust/anagrams-2.rust b/Task/Anagrams/Rust/anagrams-2.rust new file mode 100644 index 0000000000..55a13587dd --- /dev/null +++ b/Task/Anagrams/Rust/anagrams-2.rust @@ -0,0 +1,42 @@ +use std::collections::HashMap; +use std::path::Path; +use std::io::{self, BufRead, BufReader}; +use std::fs::File; + +fn main() { + if let Ok(anagrams) = find_anagrams("unixdict.txt") { + for anagram in anagrams { + for word in anagram { + print!("{} ", word); + } + println!(); + } + } +} + +const PRIMES: [u64; 256] = [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,1019,1021,1031,1033 + ,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,1153,1163,1171 + ,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,1301 + ,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,1453 + ,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583 + ,1597,1601,1607,1609,1613,1619]; + +fn find_anagrams>(file: P) -> io::Result>> { + let file = BufReader::new(File::open(file)?); + let mut map = HashMap::new(); + for line in file.lines() { + let string = line?; + let mut num = 1; + for ch in string.trim().bytes() { + num *= PRIMES[ch as usize]; + } + map.entry(num).or_insert_with(Vec::new).push(string); + } + Ok(map.into_iter().map(|(_, entry)| entry).collect()) +} diff --git a/Task/Anagrams/Rust/anagrams.rust b/Task/Anagrams/Rust/anagrams.rust deleted file mode 100644 index 84faf495fc..0000000000 --- a/Task/Anagrams/Rust/anagrams.rust +++ /dev/null @@ -1,27 +0,0 @@ -use std::collections::HashMap; -use std::collections::hash_map::Entry::*; -use std::fs::File; -use std::io::{BufRead,BufReader}; -use std::cmp; - -fn sort_string(string: &str) -> String { - let mut chars = string.chars().collect::>(); - chars.sort(); - chars.into_iter().collect() -} - -fn main () { - let file = BufReader::new(File::open("unixdict.txt").unwrap()); - let mut map = HashMap::new(); - for line in file.lines() { - let s: String = line.unwrap().trim().into(); - match map.entry(sort_string(&s)) { - Vacant(entry) => { entry.insert(vec![s]); }, - Occupied(mut entry) => { entry.get_mut().push(s); } - } - } - let max_length = map.values().fold(0, |s, v| cmp::max(s, v.len())); - for v in map.values().filter(|&v| v.len() == max_length) { - println!("{}", v.join(" ")) - } -} diff --git a/Task/Anagrams/Scheme/anagrams.ss b/Task/Anagrams/Scheme/anagrams.ss new file mode 100644 index 0000000000..798a3fad48 --- /dev/null +++ b/Task/Anagrams/Scheme/anagrams.ss @@ -0,0 +1,41 @@ +(import (scheme base) + (scheme char) + (scheme file) + (scheme write) + (srfi 125) ; hash tables + (srfi 132)) ; sorting library + +;; read in the words +(define (read-groups) + (with-input-from-file + "unixdict.txt" + (lambda () + (let ((groups (hash-table string=?))) + (do ((line (read-line) (read-line))) + ((eof-object? line) groups) + (let* ((key (list->string (list-sort charlist line)))) + (val (hash-table-ref/default groups key '()))) + (hash-table-set! groups key (cons line val)))))))) + +;; extract the longest values from given hash-table of groups +(define (largest-groups groups) + (define (find-largest grps n sofar) + (cond ((null? grps) + sofar) + ((> (length (car grps)) n) + (find-largest (cdr grps) (length (car grps)) (list (car grps)))) + ((= (length (car grps)) n) + (find-largest (cdr grps) n (cons (car grps) sofar))) + (else + (find-largest (cdr grps) n sofar)))) + (find-largest (hash-table-values groups) 0 '())) + +;; print results +(for-each + (lambda (group) + (display "[ ") + (for-each (lambda (word) (display word) (display " ")) group) + (display "]\n")) + (list-sort (lambda (a b) (string= 0.75 * IMAP.N THEN + BEGIN + COMMENT RESIZE HASHMAP ; + REF(INNERHASHMAP) NEWIMAP; + REF(ITERATOR) IT; + NEWIMAP :- NEW INNERHASHMAP(2 * IMAP.N); + IT :- NEW ITERATOR(THIS HASHMAP); + WHILE IT.MORE DO + BEGIN + REF(HASHKEY) KEY; + KEY :- IT.NEXT; + NEWIMAP.PUT(KEY, IMAP.GET(KEY)); + END; + IMAP.CLEAR; + IMAP :- NEWIMAP; + END; + IMAP.PUT(K, V); + END; + + REF(HASHVAL) PROCEDURE GET(K); REF(HASHKEY) K; + GET :- IMAP.GET(K); + + PROCEDURE CLEAR; + IMAP.CLEAR; + + INTEGER PROCEDURE SIZE; + SIZE := IMAP.SIZE; + + REF(INNERHASHMAP) IMAP; + + IMAP :- NEW INNERHASHMAP(16); + END HASHMAP; + + CLASS ITERATOR(H); REF(HASHMAP) H; + BEGIN + INTEGER POS,KEYCOUNT; + + BOOLEAN PROCEDURE MORE; + MORE := KEYCOUNT < H.SIZE; + + REF(HASHKEY) PROCEDURE NEXT; + BEGIN + INSPECT H.IMAP DO + BEGIN + WHILE KEYTABLE(POS) == NONE DO + POS := POS+1; + NEXT :- KEYTABLE(POS); + KEYCOUNT := KEYCOUNT+1; + POS := POS+1; + END; + END NEXT; + + END ITERATOR; + + COMMENT ----- PROBLEM SPECIFIC CLASSES ; + + HASHKEY CLASS TEXTHASHKEY(T); VALUE T; TEXT T; + BEGIN + INTEGER PROCEDURE HASH; + BEGIN + INTEGER I; + T.SETPOS(1); + WHILE T.MORE DO + I := 31*I+RANK(T.GETCHAR); + HASH := I; + END HASH; + BOOLEAN PROCEDURE EQUALTO(K); REF(HASHKEY) K; + EQUALTO := T = K QUA TEXTHASHKEY.T; + END TEXTHASHKEY; + + HASHVAL CLASS TEXTVECTOR; + BEGIN + + CLASS ARRAYHOLDER(N); INTEGER N; + BEGIN + TEXT ARRAY DATA(1:N); + END ARRAYHOLDER; + + REF(ARRAYHOLDER) HOLDER; + INTEGER SIZE; + + PROCEDURE DOUBLESIZE; + BEGIN + REF(ARRAYHOLDER) NEWHOLDER; + INTEGER I; + NEWHOLDER :- NEW ARRAYHOLDER(2 * HOLDER.N); + FOR I := 1 STEP 1 UNTIL HOLDER.N DO + NEWHOLDER.DATA(I) :- HOLDER.DATA(I); + HOLDER :- NEWHOLDER; + END; + + PROCEDURE ADD(WORD); TEXT WORD; + BEGIN + SIZE := SIZE + 1; + IF SIZE > HOLDER.N THEN + DOUBLESIZE; + HOLDER.DATA(SIZE) :- WORD; + END; + + HOLDER :- NEW ARRAYHOLDER(16); + END TEXTVECTOR; + + TEXT PROCEDURE MAKEKEY(WORD); TEXT WORD; + BEGIN + TEXT KEY; + INTEGER I; + KEY :- BLANKS(WORD.LENGTH); + KEY.SETPOS(1); + FOR I := RANK('a') STEP 1 UNTIL RANK('z'), + RANK('0') STEP 1 UNTIL RANK('9') DO + BEGIN + WORD.SETPOS(1); + WHILE WORD.MORE DO + IF WORD.GETCHAR = CHAR(I) THEN + KEY.PUTCHAR(CHAR(I)); + END; + MAKEKEY :- KEY; + END MAKEKEY; + + REF(INFILE) INF; + REF(HASHMAP) MAP; + REF(HASHKEY) KEY; + REF(TEXTVECTOR) TVEC; + REF(ITERATOR) IT; + TEXT WORD; + INTEGER I, J, LONGEST; + + MAP :- NEW HASHMAP; + + INF :- NEW INFILE("unixdict.txt"); + INF.OPEN(BLANKS(132)); + WHILE NOT INF.LASTITEM DO + BEGIN + WORD :- COPY(INF.IMAGE).STRIP; INF.INIMAGE; + KEY :- NEW TEXTHASHKEY(MAKEKEY(WORD)); + TVEC :- MAP.GET(KEY); + IF TVEC == NONE THEN + BEGIN + TVEC :- NEW TEXTVECTOR; + MAP.PUT(KEY, TVEC); + END; + TVEC.ADD(WORD); + END; + INF.CLOSE; + + COMMENT FIND LONGEST ENTRIES ; + + IT :- NEW ITERATOR(MAP); + WHILE IT.MORE DO + BEGIN + TVEC :- MAP.GET(IT.NEXT); + IF TVEC.SIZE > LONGEST THEN + LONGEST := TVEC.SIZE; + END; + + COMMENT OUTPUT LONGEST ENTRIES ; + + IT :- NEW ITERATOR(MAP); + WHILE IT.MORE DO + BEGIN + KEY :- IT.NEXT; + TVEC :- MAP.GET(KEY); + IF TVEC.SIZE = LONGEST THEN + BEGIN + OUTTEXT(KEY QUA TEXTHASHKEY.T); + OUTTEXT(":"); + FOR J := 1 STEP 1 UNTIL TVEC.SIZE DO + INSPECT TVEC.HOLDER DO + BEGIN + OUTCHAR(' '); + OUTTEXT(DATA(J)); + END; + OUTIMAGE; + END; + END; + +END diff --git a/Task/Anagrams/Zkl/anagrams-1.zkl b/Task/Anagrams/Zkl/anagrams-1.zkl new file mode 100644 index 0000000000..aa0d6184f8 --- /dev/null +++ b/Task/Anagrams/Zkl/anagrams-1.zkl @@ -0,0 +1,13 @@ +File("unixdict.txt").read(*) // dictionary file to blob, copied from web + // blob to dictionary: key is word "fuzzed", values are anagram words + .pump(Void,T(fcn(w,d){ + key:=w.split("").sort().concat(); // fuzz word to key + d.appendV(key,w); // add or append w + },d:=Dictionary(0d60_000))); + +d.filter(fcn([(k,v)]){ v.len()>3 }) // prune to list of # words > 3 + .sort(fcn([(_,v1)],[(_,v2)]){ v1.len()>v2.len() }) // sort by word count + [0,10].pump(Console.println,'wrap([(zz,v)]){ // and print 10 biggest + "%d:%s: %s".fmt(v.len(),zz.strip(), + v.apply("strip").concat(",")) + }); diff --git a/Task/Anagrams/Zkl/anagrams-2.zkl b/Task/Anagrams/Zkl/anagrams-2.zkl new file mode 100644 index 0000000000..60908b94a4 --- /dev/null +++ b/Task/Anagrams/Zkl/anagrams-2.zkl @@ -0,0 +1,5 @@ +URL:="http://www.puzzlers.org/pub/wordlists/unixdict.txt"; +var ZC=Import("zklCurl"); +unixdict:=ZC().get(URL); //--> T(Data,bytes of header, bytes of trailer) +unixdict=unixdict[0].del(0,unixdict[1]); // remove HTTP header +File("unixdict.txt","w").write(unixdict); diff --git a/Task/Animate-a-pendulum/Haskell/animate-a-pendulum-1.hs b/Task/Animate-a-pendulum/Haskell/animate-a-pendulum-1.hs new file mode 100644 index 0000000000..156fab6ddc --- /dev/null +++ b/Task/Animate-a-pendulum/Haskell/animate-a-pendulum-1.hs @@ -0,0 +1,28 @@ +import Graphics.HGL.Draw.Monad (Graphic, ) +import Graphics.HGL.Draw.Picture +import Graphics.HGL.Utils +import Graphics.HGL.Window +import Graphics.HGL.Run + +import Control.Exception (bracket, ) +import Control.Arrow + +toInt = fromIntegral.round + +pendulum = runGraphics $ + bracket + (openWindowEx "Pendulum animation task" Nothing (600,400) DoubleBuffered (Just 30)) + closeWindow + (\w -> mapM_ ((\ g -> setGraphic w g >> getWindowTick w). + (\ (x, y) -> overGraphic (line (300, 0) (x, y)) + (ellipse (x - 12, y + 12) (x + 12, y - 12)) )) pts) + where + dt = 1/30 + t = - pi/4 + l = 1 + g = 9.812 + nextAVT (a,v,t) = (a', v', t + v' * dt) where + a' = - (g / l) * sin t + v' = v + a' * dt + pts = map (\(_,t,_) -> (toInt.(300+).(300*).cos &&& toInt. (300*).sin) (pi/2+0.6*t) ) + $ iterate nextAVT (- (g / l) * sin t, t, 0) diff --git a/Task/Animate-a-pendulum/Haskell/animate-a-pendulum-2.hs b/Task/Animate-a-pendulum/Haskell/animate-a-pendulum-2.hs new file mode 100644 index 0000000000..6229fc84b0 --- /dev/null +++ b/Task/Animate-a-pendulum/Haskell/animate-a-pendulum-2.hs @@ -0,0 +1,51 @@ +import Graphics.Gloss + +-- Initial conditions +g_ = (-9.8) :: Float --Gravity acceleration +v_0 = 0 :: Float --Initial tangential speed +a_0 = 0 / 180 * pi :: Float --Initial angle +dt = 0.01 :: Float --Time step +t_f = 15 :: Float --Final time for data logging +l_ = 200 :: Float --Rod length + +-- Define a type to represent the pendulum: +type Pendulum = (Float, Float, Float) -- (rod length, tangential speed, angle) + +-- Pendulum's initial state +initialstate :: Pendulum +initialstate = (l_, v_0, a_0) + +-- Step funtion: update pendulum to new position +movePendulum :: Float -> Pendulum -> Pendulum +movePendulum dt (l,v,a) = ( l , v_2 , a + v_2 / l * dt*10 ) + where v_2 = v + g_ * (cos a) * dt + +-- Convert from Pendulum to [Picture] for display +renderPendulum :: Pendulum -> [Picture] +renderPendulum (l,v,a) = map (uncurry Translate newOrigin) + [ Line [ ( 0 , 0 ) , ( l * (cos a), l * (sin a) ) ] + , polygon [ ( 0 , 0 ) , ( -5 , 8.66 ) , ( 5 , 8.66 ) ] + , Translate ( l * (cos a)) (l * (sin a)) (circleSolid (0.04*l_)) + , Translate (-1.1*l) (-1.3*l) (Scale 0.1 0.1 (Text currSpeed)) + , Translate (-1.1*l) (-1.3*l + 20) (Scale 0.1 0.1 (Text currAngle)) + ] + where currSpeed = "Speed (pixels/s) = " ++ (show v) + currAngle = "Angle (deg) = " ++ (show ( 90 + a / pi * 180 ) ) + +-- New origin to beter display the animation +newOrigin = (0, l_ / 2) + +-- Calcule a proper window size (for angles between 0 and -pi) +windowSize :: (Int, Int) +windowSize = ( 300 + 2 * round (snd newOrigin) + , 200 + 2 * round (snd newOrigin) ) + +-- Run simulation +main :: IO () +main = do --plotOnGNU + simulate window background fps initialstate render update + where window = InWindow "Animate a pendulum" windowSize (40, 40) + background = white + fps = round (1/dt) + render xs = pictures $ renderPendulum xs + update _ = movePendulum diff --git a/Task/Animate-a-pendulum/Haskell/animate-a-pendulum.hs b/Task/Animate-a-pendulum/Haskell/animate-a-pendulum.hs deleted file mode 100644 index 14b08cff1b..0000000000 --- a/Task/Animate-a-pendulum/Haskell/animate-a-pendulum.hs +++ /dev/null @@ -1,28 +0,0 @@ -import Graphics.HGL.Draw.Monad (Graphic, ) -import Graphics.HGL.Draw.Picture -import Graphics.HGL.Utils -import Graphics.HGL.Window -import Graphics.HGL.Run - -import Control.Exception (bracket, ) -import Control.Arrow - -toInt = fromIntegral.round - -pendulum = runGraphics $ - bracket - (openWindowEx "Pendulum animation task" Nothing (600,400) DoubleBuffered (Just 30)) - closeWindow - (\w -> mapM_ ((\ g -> setGraphic w g >> getWindowTick w). - (\ (x, y) -> overGraphic (line (300, 0) (x, y)) - (ellipse (x - 12, y + 12) (x + 12, y - 12)) )) pts) - where - dt = 1/30 - t = - pi/4 - l = 1 - g = 9.812 - nextAVT (a,v,t) = (a', v', t + v' * dt) where - a' = - (g / l) * sin t - v' = v + a' * dt - pts = map (\(_,t,_) -> (toInt.(300+).(300*).cos &&& toInt. (300*).sin) (pi/2+0.6*t) ) - $ iterate nextAVT (- (g / l) * sin t, t, 0) diff --git a/Task/Animate-a-pendulum/Lua/animate-a-pendulum.lua b/Task/Animate-a-pendulum/Lua/animate-a-pendulum.lua new file mode 100644 index 0000000000..a34a9a3762 --- /dev/null +++ b/Task/Animate-a-pendulum/Lua/animate-a-pendulum.lua @@ -0,0 +1,28 @@ +function degToRad( d ) + return d * 0.01745329251 +end + +function love.load() + g = love.graphics + rodLen, gravity, velocity, acceleration = 260, 3, 0, 0 + halfWid, damp = g.getWidth() / 2, .989 + posX, posY, angle = halfWid + TWO_PI, angle = math.pi * 2, degToRad( 90 ) +end + +function love.update( dt ) + acceleration = -gravity / rodLen * math.sin( angle ) + angle = angle + velocity; if angle > TWO_PI then angle = 0 end + velocity = velocity + acceleration + velocity = velocity * damp + posX = halfWid + math.sin( angle ) * rodLen + posY = math.cos( angle ) * rodLen +end + +function love.draw() + g.setColor( 250, 0, 250 ) + g.circle( "fill", halfWid, 0, 8 ) + g.line( halfWid, 4, posX, posY ) + g.setColor( 250, 100, 20 ) + g.circle( "fill", posX, posY, 20 ) +end diff --git a/Task/Animate-a-pendulum/OoRexx/animate-a-pendulum.rexx b/Task/Animate-a-pendulum/OoRexx/animate-a-pendulum.rexx new file mode 100644 index 0000000000..93309b4580 --- /dev/null +++ b/Task/Animate-a-pendulum/OoRexx/animate-a-pendulum.rexx @@ -0,0 +1,35 @@ +pendulum = .pendulum~new(10, 30) + +before = .datetime~new +do 100 -- somewhat arbitrary loop count + call syssleep .2 + now = .datetime~new + pendulum~update(now - before) + before = now + say " X:" pendulum~x " Y:" pendulum~y +end + +::class pendulum +::method init + expose length theta x y velocity + use arg length, theta + x = rxcalcsin(theta) * length + y = rxcalccos(theta) * length + velocity = 0 + +::attribute x GET +::attribute y GET + +::constant g -9.81 -- acceleration due to gravity + +::method update + expose length theta x y velocity + use arg duration + acceleration = self~g / length * rxcalcsin(theta) + durationSeconds = duration~microseconds / 1000000 + x = rxcalcsin(theta, length) + y = rxcalccos(theta, length) + velocity = velocity + acceleration * durationSeconds + theta = theta + velocity * durationSeconds + +::requires rxmath library diff --git a/Task/Animate-a-pendulum/Phix/animate-a-pendulum.phix b/Task/Animate-a-pendulum/Phix/animate-a-pendulum.phix index a74367eb7a..9c22c5e07d 100644 --- a/Task/Animate-a-pendulum/Phix/animate-a-pendulum.phix +++ b/Task/Animate-a-pendulum/Phix/animate-a-pendulum.phix @@ -1,68 +1,76 @@ -include ..\arwen\arwen.ew -include ..\arwen\axtra.ew +-- +-- demo\rosetta\animate_pendulum2.exw +-- ================================== +-- +include pGUI.e -constant main = create(Window, "Animated Pendulum", 0, 0, 20, 20, 625, 690, 0), - mainDC = getPrivateDC(main), - backDC = c_func(xCreateCompatibleDC, {NULL}), -- the background - viewDC = c_func(xCreateCompatibleDC, {NULL}), -- with animation - grey = #909090 +Ihandle dlg, canvas, timer +cdCanvas cddbuffer, cdcanvas -constant MainTimer = createTimer() - -integer dw = 0, dh = 0 -- client area width and height -atom bmBack, bmView -integer bmX = 0, bmY = 0 -- actual size of the bitmaps - -constant dt = 1E-3 constant g = 50 -integer sX = 0, sY = 0 -- suspension point of pendulum -integer len atom alpha = PI/2, - omega = 0, - epsilon + omega = 0 -function mainHandler(integer id, integer msg, atom wParam, object lParam) -integer eX, eY -- moving end of pendulum - if msg=WM_SIZE then - {{},{},dw,dh} = getClientRect(main) - if dw>bmX or dh>bmY then - -- we need bigger bitmaps - bmBack = c_func(xCreateCompatibleBitmap, {mainDC, dw, dh}) - {} = deleteObject(selectObject(backDC,bmBack)) - -- clear the background - setPenColor(grey) - drawRectangleh(backDC, True, 0, 0, dw, dh) - bmView = c_func(xCreateCompatibleBitmap, {mainDC, dw, dh}) - {} = deleteObject(selectObject(viewDC,bmView)) - {bmX,bmY} = {dw,dh} - end if - -- new suspension point and length - sX = floor(dw/2) - sY = floor(dh/8) - len = sX-20 - elsif msg=WM_PAINT then - -- start with a fresh copy of the background - void = c_func(xBitBlt,{viewDC,0,0,dw,dh,backDC,0,0,SRCCOPY}) - eX = floor(len*sin(alpha)+sX) - eY = floor(len*cos(alpha)+sY) - drawLinesh(viewDC,{Red,{sX,sY,eX,eY},Yellow}) - drawEllipseh(viewDC,eX-5,eY-5,eX+5,eY+5) - void = c_func(xBitBlt,{mainDC,0,0,dw,dh,viewDC,0,0,SRCCOPY}) - elsif msg=WM_TIMER then - epsilon = -len*sin(alpha)*g - omega += dt*epsilon - alpha += dt*omega - repaintWindow(main) - elsif msg=WM_SHOWWINDOW then - startTimer(MainTimer,main,33) - elsif msg=WM_CHAR - and wParam=VK_ESCAPE then - closeWindow(main) - if id or object(lParam) then end if -- suppress warnings - end if - return 0 +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) + integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE") + cdCanvasActivate(cddbuffer) + cdCanvasClear(cddbuffer) + -- new suspension point and length + integer sX = floor(w/2) + integer sY = floor(h/8) + integer len = sX-30 + atom dt = 1/w + -- move: + atom epsilon = -len*sin(alpha)*g + omega += dt*epsilon + alpha += dt*omega + -- repaint: + integer eX = floor(len*sin(alpha)+sX) + integer eY = floor(len*cos(alpha)+sY) + cdCanvasSetForeground(cddbuffer, CD_DARK_GREY) + cdCanvasLine(cddbuffer, sX, h-sY, eX, h-eY) + cdCanvasSetForeground(cddbuffer, CD_BLACK) + cdCanvasSector(cddbuffer, eX, h-eY, 35, 35, 0, 360) + cdCanvasFlush(cddbuffer) + return IUP_DEFAULT end function -setHandler({main},routine_id("mainHandler")) -WinMain(main, SW_NORMAL) +function timer_cb(Ihandle /*ih*/) + IupUpdate(canvas) + return IUP_IGNORE +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + cdCanvasSetBackground(cddbuffer, CD_GREY) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "640x380") + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + + timer = IupTimer(Icallback("timer_cb"), 20) + + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", "Animated Pendulum") + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + + IupShow(dlg) + IupSetAttribute(canvas, "RASTERSIZE", NULL) + IupMainLoop() + IupClose() +end procedure + +main() diff --git a/Task/Animate-a-pendulum/Scilab/animate-a-pendulum.scilab b/Task/Animate-a-pendulum/Scilab/animate-a-pendulum.scilab new file mode 100644 index 0000000000..ed71062f6c --- /dev/null +++ b/Task/Animate-a-pendulum/Scilab/animate-a-pendulum.scilab @@ -0,0 +1,85 @@ +//Input variables (Assumptions: massless pivot, no energy loss) +bob_mass=10; +g=-9.81; +L=2; +theta0=-%pi/6; +v0=0; +t0=0; + +//No. of steps +steps=300; + +//Setting deltaT or duration (comment either of the lines below) +//deltaT=0.1; t_max=t0+deltaT*steps; +t_max=5; deltaT=(t_max-t0)/steps; + +if t_max<=t0 then + error("Check duration (t0 and t_f), number of steps and deltaT."); +end + +//Initial position +not_a_pendulum=%F; +t=zeros(1,steps); t(1)=t0; //time +theta=zeros(1,steps); theta(1)=theta0; //angle +F=zeros(1,steps); F(1)=bob_mass*g*sin(theta0); //force +A=zeros(1,steps); A(1)=F(1)/bob_mass; //acceleration +V=zeros(1,steps); V(1)=v0; //linear speed +W=zeros(1,steps); W(1)=v0/L; //angular speed + +for i=2:steps + t(i)=t(i-1)+deltaT; + V(i)=A(i-1)*deltaT+V(i-1); + W(i)=V(i)/L; + theta(i)=theta(i-1)+W(i)*deltaT; + F(i)=bob_mass*g*sin(theta(i)); + A(i)=F(i)/bob_mass; + if (abs(theta(i))>=%pi | (abs(theta(i))==0 & V(i)==0)) & ~not_a_pendulum then + disp("Initial conditions do not describe a pendulum."); + not_a_pendulum = %T; + end +end +clear i + +//Ploting the pendulum +bob_r=0.08*L; +bob_shape=bob_r*exp(%i.*linspace(0,360,20)/180*%pi); + +bob_pos=zeros(20,steps); +rod_pos=zeros(1,steps); +for i=1:steps + rod_pos(i)=L*exp(%i*(-%pi/2+theta(i))); + bob_pos(:,i)=bob_shape'+rod_pos(i); +end +clear i + +scf(0); clf(); xname("Simple gravity pendulum"); +plot2d(real([0 rod_pos(1)]),imag([0 rod_pos(1)])); +axes=gca(); +axes.isoview="on"; +axes.children(1).children.mark_style=3; +axes.children(1).children.mark_size=1; +axes.children(1).children.thickness=3; + +plot2d(real(bob_pos(:,1)),imag(bob_pos(:,1))); +axes=gca(); +axes.children(1).children.fill_mode="on"; +axes.children(1).children.foreground=2; +axes.children(1).children.background=2; + +if max(imag(bob_pos))>0 then + axes.data_bounds=[-L-bob_r,-L-1.01*bob_r;L+bob_r,max(imag(bob_pos))]; +else + axes.data_bounds=[-L-bob_r,-L-1.01*bob_r;L+bob_r,bob_r]; +end + + + +//Animating the plot +disp("Duration: "+string(max(t)+deltaT-t0)+"s."); +sleep(850); +for i=2:steps + axes.children(1).children.data=[real(bob_pos(:,i)), imag(bob_pos(:,i))]; + axes.children(2).children.data=[0, 0; real(rod_pos(i)), imag(rod_pos(i))]; + sleep(deltaT*1000) +end +clear i diff --git a/Task/Animate-a-pendulum/Smart-BASIC/animate-a-pendulum.smart b/Task/Animate-a-pendulum/Smart-BASIC/animate-a-pendulum.smart new file mode 100644 index 0000000000..83bfed5a38 --- /dev/null +++ b/Task/Animate-a-pendulum/Smart-BASIC/animate-a-pendulum.smart @@ -0,0 +1,35 @@ +'Pendulum +'By Dutchman +' --- constants +g=9.81 ' accelleration of gravity +l=1 ' length of pendulum +GET SCREEN SIZE sw,sh +pivotx=sw/2 +pivoty=150 +' --- initialise graphics +GRAPHICS +DRAW COLOR 1,0,0 +FILL COLOR 0,0,1 +DRAW SIZE 2 +' --- initialise pendulum +theta=1 ' initial displacement in radians +speed=0 +' --- loop +DO + bobx=pivotx+100*l*SIN(theta) + boby=pivoty-100*l*COS(theta) + GOSUB Plot + PAUSE 0.01 + accel=g*SIN(theta)/l/100 + speed=speed+accel + theta=theta+speed +UNTIL 0 +END +' --- subroutine +Plot: +REFRESH OFF +GRAPHICS CLEAR 1,1,0.5 +DRAW LINE pivotx,pivoty TO bobx,boby +FILL CIRCLE bobx,boby SIZE 10 +REFRESH ON +RETURN diff --git a/Task/Animation/Gambas/animation.gambas b/Task/Animation/Gambas/animation.gambas new file mode 100644 index 0000000000..9dfe4136fb --- /dev/null +++ b/Task/Animation/Gambas/animation.gambas @@ -0,0 +1,66 @@ +'This code will create the necessary controls on a GUI Form + +hLabel As Label 'Label needed to display the 'Hello World! " message +hTimer As Timer 'Timer to rotate the display +bDirection As Boolean 'Used to control the direction of the text +'__________________________________________________ +Public Sub Form_Open() +Dim hPanel As Panel '2 Panels used to centre the Label vertically on the Form +Dim hHBox As HBox 'Box to hold the Label + +With Me 'Set the Form Properties + .Arrangement = Arrange.Vertical 'Arrange controls vertically + .Title = "Animation" 'Give the Form a Title + .Height = 75 'Set the Height of the Form + .Width = 225 'Set the Width of the Form +End With + +hPanel = New Panel(Me) 'Add a Panel to the Form +HPanel.Expand = True 'Expand the Panel + +hHBox = New HBox(Me) 'Add a HBox to the Form +hHBox.Height = 28 'Set the HBox Height + +hLabel = New Label(hHBox) As "LabelAnimation" 'Add new Lable with Event name + +With hLabel 'Change the hLabel properties + .Height = 35 'Set the Height of the Label + .Expand = True 'Expand the hLabel + .Font.Bold = True 'Set the Font to Bold + .Font.size = 20 'Set the Font Size + .Alignment = Align.Center 'Centre align the text + .Tooltip = "Click me to reverse direction" 'Add a Tooltip + .Border = Border.Plain 'Add a Border + .Text = "Hello World! " 'Add the Text +End With + +hPanel = New Panel(Me) 'Add another Panel +HPanel.Expand = True 'Expand the Panel + +hTimer = New Timer As "Timer1" 'Add a Timer +hTimer.delay = 500 'Set the Timer Delay +hTimer.Start 'Start the Timer + +End +'__________________________________________________ +Public Sub LabelAnimation_MouseDown() 'If the hLabel is clicked.. + +bDirection = Not bDirection 'Change the value of bDirection + +End +'__________________________________________________ +Public Sub Timer1_Timer() 'Timer +Dim sString As String = hLabel.Text 'To hold the text in the Label +Dim sTemp As String 'Temp string + +If bDirection Then 'If the text is to rotate left then.. + sTemp = Left(sString, 1) 'Get the first charater of the Label Text e.g 'H' + sString = Right(sString, -1) & sTemp 'Recreate sString with all the text less the 1st character e.g. 'ello World! ' and add the 1st character to the end e.g. 'ello World! H' +Else 'Else if text is to rotate right then.. + sTemp = Right(sString, 1) 'Get the last charater of the Label Text e.g '!' + sString = sTemp & Left(sString, -1) 'Recreate sString with all the text less the last character e.g. ' Hello World' and add the last character to the begining e.g. '! Hello World' +End If + +hLabel.text = sString 'Display the result + +End diff --git a/Task/Animation/HicEst/animation-1.hicest b/Task/Animation/HicEst/animation-1.hicest deleted file mode 100644 index a510f720fc..0000000000 --- a/Task/Animation/HicEst/animation-1.hicest +++ /dev/null @@ -1,18 +0,0 @@ -CHARACTER string="Hello World! " - - WINDOW(WINdowhandle=wh, Height=1, X=1, TItle="left/right click to rotate left/right, Y-click-position sets milliseconds period") - AXIS(WINdowhandle=wh, PoinT=20, X=2048, Y, Title='ms', MiN=0, MaX=400, MouSeY=msec, MouSeCall=Mouse_callback, MouSeButton=button_type) - direction = 4 - msec = 100 ! initial milliseconds - DO tic = 1, 1E20 - WRITE(WIN=wh, Align='Center Vertical') string - IF(direction == 4) string = string(LEN(string)) // string ! rotate left - IF(direction == 8) string = string(2:) // string(1) ! rotate right - WRITE(StatusBar, Name) tic, direction, msec - SYSTEM(WAIT=msec) - ENDDO - END - -SUBROUTINE Mouse_callback() - direction = button_type ! 4 == left button up, 8 == right button up - END diff --git a/Task/Animation/HicEst/animation-2.hicest b/Task/Animation/HicEst/animation-2.hicest deleted file mode 100644 index e0fad2322e..0000000000 --- a/Task/Animation/HicEst/animation-2.hicest +++ /dev/null @@ -1,44 +0,0 @@ -import gui -$include "guih.icn" - -class WindowApp : Dialog (label, direction) - - method rotate_left (msg) - return msg[2:0] || msg[1] - end - - method rotate_right (msg) - return msg[-1:0] || msg[1:-1] - end - - method reverse_direction () - direction := 1-direction - end - - # this method gets called by the ticker, and updates the label - method tick () - static msg := "Hello World! " - if direction = 0 - then msg := rotate_left (msg) - else msg := rotate_right (msg) - label.set_label(msg) - end - - method component_setup () - direction := 1 # start off rotating to the right - label := Label("label=Hello World! ", "pos=0,0") - # respond to a mouse click on the label - label.connect (self, "reverse_direction", MOUSE_RELEASE_EVENT) - add (label) - - connect (self, "dispose", CLOSE_BUTTON_EVENT) - # tick every 100ms - self.set_ticker (100) - end -end - -# create and show the window -procedure main () - w := WindowApp () - w.show_modal () -end diff --git a/Task/Animation/Java/animation.java b/Task/Animation/Java/animation.java index 23d0674a04..ff089f20a4 100644 --- a/Task/Animation/Java/animation.java +++ b/Task/Animation/Java/animation.java @@ -1,59 +1,61 @@ import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; import java.util.Timer; import java.util.TimerTask; import javax.swing.JFrame; import javax.swing.JLabel; +import javax.swing.WindowConstants; -public class Rotate extends JFrame { - String text = "Hello World! "; - JLabel label = new JLabel(text); - boolean rotRight = true; - int startIdx = 0; +public class Rotate { - public Rotate() { - label.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent evt) { - rotRight = !rotRight; - } - }); - add(label); - pack(); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - setVisible(true); - } + private static class State { + private final String text = "Hello World! "; + private int startIndex = 0; + private boolean rotateRight = true; + } - public static void main(String[] args) { - final Rotate rot = new Rotate(); - TimerTask task = new TimerTask() { - public void run() { - if (rot.rotRight) { - rot.startIdx++; - if (rot.startIdx >= rot.text.length()) { - rot.startIdx -= rot.text.length(); - } - } else { - rot.startIdx--; - if (rot.startIdx < 0) { - rot.startIdx += rot.text.length(); - } + public static void main(String[] args) { + State state = new State(); + + JLabel label = new JLabel(state.text); + label.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent event) { + state.rotateRight = !state.rotateRight; + } + }); + + TimerTask task = new TimerTask() { + public void run() { + int delta = state.rotateRight ? 1 : -1; + state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length(); + label.setText(rotate(state.text, state.startIndex)); + } + }; + Timer timer = new Timer(false); + timer.schedule(task, 0, 500); + + JFrame rot = new JFrame(); + rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + rot.add(label); + rot.pack(); + rot.setLocationRelativeTo(null); + rot.addWindowListener(new WindowAdapter() { + @Override + public void windowClosed(WindowEvent e) { + timer.cancel(); + } + }); + rot.setVisible(true); + } + + private static String rotate(String text, int startIdx) { + char[] rotated = new char[text.length()]; + for (int i = 0; i < text.length(); i++) { + rotated[i] = text.charAt((i + startIdx) % text.length()); } - rot.label.setText(getRotatedText(rot.text, rot.startIdx)); - } - }; - Timer timer = new Timer(false); - timer.schedule(task, 0, 500); - } - - public static String getRotatedText(String text, int startIdx) { - String ret = ""; - int i = startIdx; - do { - ret += text.charAt(i) + ""; - i++; - i = i % text.length(); - } while (i != startIdx); - return ret; - } + return String.valueOf(rotated); + } } diff --git a/Task/Animation/Kotlin/animation.kotlin b/Task/Animation/Kotlin/animation.kotlin new file mode 100644 index 0000000000..8cecef6a13 --- /dev/null +++ b/Task/Animation/Kotlin/animation.kotlin @@ -0,0 +1,55 @@ +// version 1.1.0 + +import java.awt.Dimension +import java.awt.event.MouseAdapter +import java.awt.event.MouseEvent +import java.util.* +import javax.swing.JFrame +import javax.swing.JLabel + +class Rotate : JFrame() { + val text = "Hello World! " + val label = JLabel(text) + var rotRight = true + var startIdx = 0 + + init { + preferredSize = Dimension(96, 64) + label.addMouseListener(object: MouseAdapter() { + override fun mouseClicked(evt: MouseEvent) { + rotRight = !rotRight + } + }) + add(label) + pack() + defaultCloseOperation = JFrame.EXIT_ON_CLOSE + isVisible = true + } +} + +fun getRotatedText(text: String, startIdx: Int): String { + val ret = StringBuilder() + var i = startIdx + do { + ret.append(text[i++]) + i %= text.length + } + while (i != startIdx) + return ret.toString() +} + +fun main(args: Array) { + val rot = Rotate() + val task = object : TimerTask() { + override fun run() { + if (rot.rotRight) { + if (--rot.startIdx < 0) rot.startIdx += rot.text.length + } + else { + if (++rot.startIdx >= rot.text.length) rot.startIdx -= rot.text.length + } + rot.label.text = getRotatedText(rot.text, rot.startIdx) + } + } + Timer(false).schedule(task, 0, 500) +} diff --git a/Task/Animation/Rust/animation.rust b/Task/Animation/Rust/animation.rust new file mode 100644 index 0000000000..a3d3327230 --- /dev/null +++ b/Task/Animation/Rust/animation.rust @@ -0,0 +1,60 @@ +#[cfg(feature = "gtk")] +mod graphical { + extern crate gtk; + + use self::gtk::traits::*; + use self::gtk::{Inhibit, Window, WindowType}; + use std::ops::Not; + use std::sync::{Arc, RwLock}; + + pub fn create_window() { + gtk::init().expect("Failed to initialize GTK"); + + let window = Window::new(WindowType::Toplevel); + window.connect_delete_event(|_, _| { + gtk::main_quit(); + Inhibit(false) + }); + let button = gtk::Button::new_with_label("Hello World! "); + window.add(&button); + + let lock = Arc::new(RwLock::new(false)); + + let lock_button = lock.clone(); + button.connect_clicked(move |_| { + let mut reverse = lock_button.write().unwrap(); + *reverse = reverse.not(); + }); + + let lock_thread = lock.clone(); + gtk::timeout_add(100, move || { + let reverse = lock_thread.read().unwrap(); + let mut text = button.get_label().unwrap(); + let len = &text.len(); + + if *reverse { + let begin = &text.split_off(1); + text.insert_str(0, begin); + } else { + let end = &text.split_off(len - 1); + text.insert_str(0, end); + } + + button.set_label(&text); + + gtk::Continue(true) + }); + + window.show_all(); + gtk::main(); + } +} + + +#[cfg(feature = "gtk")] +fn main() { + graphical::create_window(); +} + +#[cfg(not(feature = "gtk"))] +fn main() {} diff --git a/Task/Animation/Smart-BASIC/animation-1.smart b/Task/Animation/Smart-BASIC/animation-1.smart new file mode 100644 index 0000000000..6d151b716f --- /dev/null +++ b/Task/Animation/Smart-BASIC/animation-1.smart @@ -0,0 +1,17 @@ +'Animation, by rbytes and Dutchman +word$="Hello World! " +'use button window with text +SET BUTTONS CUSTOM +SET BUTTONS FONT SIZE 40 +DRAW COLOR 0,0,0 +DO 'the button is redrawn each loop +BUTTON "anim" TEXT word$ AT 130,100 +PAUSE .1 +'touching the button reverses the scrolling +IF BUTTON_PRESSED("anim") THEN flag=1-flag +IF flag THEN 'shift right + word$=RIGHT$(word$,1)&LEFT$(word$,LEN(word$)-1) +ELSE 'shift left + word$=RIGHT$(word$,LEN(word$)-1)&LEFT$(word$,1) +ENDIF +UNTIL 0 diff --git a/Task/Animation/Smart-BASIC/animation-2.smart b/Task/Animation/Smart-BASIC/animation-2.smart new file mode 100644 index 0000000000..13345e758c --- /dev/null +++ b/Task/Animation/Smart-BASIC/animation-2.smart @@ -0,0 +1,2 @@ +'by rbytes and Dutchman!word$="Hello World! "!'use button window with text! +SET BUTTONS CUSTOM!SET BUTTONS FONT SIZE 40!DRAW COLOR 0,0,0!DO!'the button is redrawn each loop!BUTTON "anim" TEXT word$ AT 130,100!PAUSE .1!'touching the button reverses the scrolling!IF BUTTON_PRESSED("anim") THEN flag=1-flag!IF flag THEN!'shift right!word$=RIGHT$(word$,1)&LEFT$(word$,LEN(word$)-1)!ELSE!'shift left!word$=RIGHT$(word$,LEN(word$)-1)&LEFT$(word$,1)!ENDIF!UNTIL 0 diff --git a/Task/Animation/Smart-BASIC/animation-3.smart b/Task/Animation/Smart-BASIC/animation-3.smart new file mode 100644 index 0000000000..d7e3a20b47 --- /dev/null +++ b/Task/Animation/Smart-BASIC/animation-3.smart @@ -0,0 +1 @@ +w$="Hello World! "!1 BUTTON 0 TEXT w$ AT 0,0!PAUSE .1!IF BUTTON_PRESSED("0") THEN f=1-f!IF f THEN w$=RIGHT$(w$,1)&LEFT$(w$,LEN(w$)-1) ELSE w$=RIGHT$(w$,LEN(w$)-1)&LEFT$(w$,1)!GOTO 1 diff --git a/Task/Animation/Smart-BASIC/animation-4.smart b/Task/Animation/Smart-BASIC/animation-4.smart new file mode 100644 index 0000000000..c2b46890fb --- /dev/null +++ b/Task/Animation/Smart-BASIC/animation-4.smart @@ -0,0 +1 @@ +w$="Hello World! "!1 BUTTON 0 TEXT w$ AT 0,0!PAUSE .1!IF BUTTON_PRESSED("0") THEN f=1-f!k=LEN(w$)-1!IF f THEN w$=RIGHT$(w$,1)&LEFT$(w$,k) ELSE w$=RIGHT$(w$,k)&LEFT$(w$,1)!GOTO 1 diff --git a/Task/Anonymous-recursion/AutoHotkey/anonymous-recursion-1.ahk b/Task/Anonymous-recursion/AutoHotkey/anonymous-recursion-1.ahk deleted file mode 100644 index 73afd29be2..0000000000 --- a/Task/Anonymous-recursion/AutoHotkey/anonymous-recursion-1.ahk +++ /dev/null @@ -1,8 +0,0 @@ -fib(n) -{ if(n < 0) - return error - else if(n < 2) - return 1 - else - return n * fib(n-1) -} diff --git a/Task/Anonymous-recursion/AutoHotkey/anonymous-recursion-2.ahk b/Task/Anonymous-recursion/AutoHotkey/anonymous-recursion-2.ahk deleted file mode 100644 index 83e3951faa..0000000000 --- a/Task/Anonymous-recursion/AutoHotkey/anonymous-recursion-2.ahk +++ /dev/null @@ -1,3 +0,0 @@ -fib(n) -{ return n < 0 ? "error" : n < 2 ? 1 : n * fib(n-1) -} diff --git a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena index d1f82c10b0..147dbe12f3 100644 --- a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena +++ b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena @@ -1,31 +1,35 @@ -#import system. -#import extensions. +import extensions. -#class(extension)mathOp +extension mathOp { - #method fib + fib [ - (self < 0) - ? [ #throw InvalidArgumentException new &message:"Must be non negative". ]. + if (self < 0) + [ InvalidArgumentException new:"Must be non negative"; raise ]. - ^ control eval:self &for: + ^ control do:self with (:n) [ - (n > 1) ? [ this eval:(n - 2) + this eval:(n - 1) ] ! [ n ] + if (n > 1) + [ ^ $closure eval(n - 2) + $closure eval(n - 1) ]; + [ ^ n ] ]. ] } -#symbol program = +program = [ - -1 to:10 &doEach: (:i) + -1 to:10 do(:i) [ - console writeLiteral:"fib(":i:")=". + console print("fib(",i,")="). - console writeLine:(i fib) | if &InvalidArgumentError: e + try (console printLine(i fib)) + { + on(Exception e) [ - console writeLine:"invalid". - ]. + console printLine:"invalid" + ] + }. ]. console readChar. diff --git a/Task/Anonymous-recursion/Java/anonymous-recursion-1.java b/Task/Anonymous-recursion/Java/anonymous-recursion-1.java index 6027c471bb..b4912dfcbd 100644 --- a/Task/Anonymous-recursion/Java/anonymous-recursion-1.java +++ b/Task/Anonymous-recursion/Java/anonymous-recursion-1.java @@ -1,9 +1,10 @@ -public static long fib(int n) -{ - if (n < 0) - throw new IllegalArgumentException("n can not be a negative number"); - return new Object() { - private long fibInner(int n) - { return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2)); } - }.fibInner(n); +public static long fib(int n) { + if (n < 0) + throw new IllegalArgumentException("n can not be a negative number"); + + return new Object() { + private long fibInner(int n) { + return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2)); + } + }.fibInner(n); } diff --git a/Task/Anonymous-recursion/Java/anonymous-recursion-2.java b/Task/Anonymous-recursion/Java/anonymous-recursion-2.java index d3a05115ac..b4a220e2d7 100644 --- a/Task/Anonymous-recursion/Java/anonymous-recursion-2.java +++ b/Task/Anonymous-recursion/Java/anonymous-recursion-2.java @@ -2,23 +2,24 @@ import java.util.function.Function; @FunctionalInterface interface SelfApplicable { - OUTPUT apply(SelfApplicable input); + OUTPUT apply(SelfApplicable input); } class Utils { - public static SelfApplicable, Function>, Function>> y() { - return y -> f -> x -> f.apply(y.apply(y).apply(f)).apply(x); - } + public static SelfApplicable, Function>, Function>> y() { + return y -> f -> x -> f.apply(y.apply(y).apply(f)).apply(x); + } - public static Function, Function>, Function> fix() { - return Utils.y().apply(Utils.y()); - } + public static Function, Function>, Function> fix() { + return Utils.y().apply(Utils.y()); + } - public static long fib(int m) { - if (m < 0) - throw new IllegalArgumentException("n can not be a negative number"); - return Utils.fix().apply( - f -> n -> (n < 2) ? n : (f.apply(n - 1) + f.apply(n - 2)) - ).apply(m); - } + public static long fib(int m) { + if (m < 0) + throw new IllegalArgumentException("n can not be a negative number"); + + return Utils.fix().apply( + f -> n -> (n < 2) ? n : (f.apply(n - 1) + f.apply(n - 2)) + ).apply(m); + } } diff --git a/Task/Anonymous-recursion/jq/anonymous-recursion-1.jq b/Task/Anonymous-recursion/Jq/anonymous-recursion-1.jq similarity index 100% rename from Task/Anonymous-recursion/jq/anonymous-recursion-1.jq rename to Task/Anonymous-recursion/Jq/anonymous-recursion-1.jq diff --git a/Task/Anonymous-recursion/jq/anonymous-recursion-2.jq b/Task/Anonymous-recursion/Jq/anonymous-recursion-2.jq similarity index 100% rename from Task/Anonymous-recursion/jq/anonymous-recursion-2.jq rename to Task/Anonymous-recursion/Jq/anonymous-recursion-2.jq diff --git a/Task/Anonymous-recursion/Kotlin/anonymous-recursion.kotlin b/Task/Anonymous-recursion/Kotlin/anonymous-recursion.kotlin new file mode 100644 index 0000000000..20d0604660 --- /dev/null +++ b/Task/Anonymous-recursion/Kotlin/anonymous-recursion.kotlin @@ -0,0 +1,11 @@ +fun fib(n: Int): Int { + require(n >= 0) + fun fib1(k: Int, a: Int, b: Int): Int = + if (k == 0) a else fib1(k - 1, b, a + b) + return fib1(n, 0, 1) +} + +fun main(args: Array) { + for (i in 0..20) print("${fib(i)} ") + println() +} diff --git a/Task/Anonymous-recursion/Lambdatalk/anonymous-recursion.lambdatalk b/Task/Anonymous-recursion/Lambdatalk/anonymous-recursion.lambdatalk new file mode 100644 index 0000000000..e53c52b79e --- /dev/null +++ b/Task/Anonymous-recursion/Lambdatalk/anonymous-recursion.lambdatalk @@ -0,0 +1,17 @@ +1) defining a tail-recursive function: +{def fibo {lambda {:n} + {{lambda {:f :n :a :b} {:f :f :n :a :b}} + {lambda {:f :n :a :b} + {if {< :n 0} + then the number must be positive! + else {if {< :n 1} + then :a + else {:f :f {- :n 1} {+ :a :b} :a}}}} :n 1 0}}} + +2) testing: +{fibo -1} -> the number must be positive! +{fibo 0} -> 1 +{fibo 8} -> 34 +{fibo 1000} -> 7.0330367711422765e+208 +{map fibo {serie 1 20}} +-> 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 diff --git a/Task/Anonymous-recursion/Nim/anonymous-recursion.nim b/Task/Anonymous-recursion/Nim/anonymous-recursion.nim index 7a9ae3bc94..2a89ef1d28 100644 --- a/Task/Anonymous-recursion/Nim/anonymous-recursion.nim +++ b/Task/Anonymous-recursion/Nim/anonymous-recursion.nim @@ -1,6 +1,6 @@ # Using scoped function fibI inside fib -proc fib(x): int = - proc fibI(n): int = +proc fib(x: int): int = + proc fibI(n: int): int = if n < 2: n else: fibI(n-2) + fibI(n-1) if x < 0: raise newException(ValueError, "Invalid argument") diff --git a/Task/Anonymous-recursion/REXX/anonymous-recursion-1.rexx b/Task/Anonymous-recursion/REXX/anonymous-recursion-1.rexx index 0052921a0d..65c908ada1 100644 --- a/Task/Anonymous-recursion/REXX/anonymous-recursion-1.rexx +++ b/Task/Anonymous-recursion/REXX/anonymous-recursion-1.rexx @@ -1,11 +1,11 @@ /*REXX program to show anonymous recursion (of a function or subroutine). */ -numeric digits 1e6 /*in case the user goes ka-razy. */ +numeric digits 1e6 /*in case the user goes ka-razy with X.*/ parse arg x . /*obtain the optional argument from CL.*/ if x=='' | x=="," then x=12 /*Not specified? Then use the default.*/ w=length(x) /*W: used for formatting the output. */ - do j=0 to x; jj=right(j, w) /*use the argument as an upper limit.*/ - say 'fibonacci('jj") =" fib(j) /*show the Fibonacci sequence: 0 ──► x */ - end /*j*/ + do j=0 for x+1 /*use the argument as an upper limit.*/ + say 'fibonacci('right(j, w)") =" fib(j) + end /*j*/ /* [↑] show Fibonacci sequence: 0 ──► X*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ fib: procedure; parse arg z; if z>=0 then return .(z) diff --git a/Task/Anonymous-recursion/REXX/anonymous-recursion-2.rexx b/Task/Anonymous-recursion/REXX/anonymous-recursion-2.rexx index dff9575bbe..b061be1f85 100644 --- a/Task/Anonymous-recursion/REXX/anonymous-recursion-2.rexx +++ b/Task/Anonymous-recursion/REXX/anonymous-recursion-2.rexx @@ -1,12 +1,12 @@ /*REXX program to show anonymous recursion of a function or subroutine with memoization.*/ -numeric digits 1e6 /*in case the user goes ka-razy. */ +numeric digits 1e6 /*in case the user goes ka-razy with X.*/ parse arg x . /*obtain the optional argument from CL.*/ if x=='' | x=="," then x=12 /*Not specified? Then use the default.*/ @.=.; @.0=0; @.1=1 /*used to implement memoization for FIB*/ w=length(x) /*W: used for formatting the output. */ - do j=0 to x; jj=right(j, w) /*use the argument as an upper limit.*/ - say 'fibonacci('jj") =" fib(j) /*show the Fibonacci sequence: 0 ──► x */ - end /*j*/ + do j=0 for x+1 /*use the argument as an upper limit.*/ + say 'fibonacci('right(j, w)") =" fib(j) + end /*j*/ /* [↑] show Fibonacci sequence: 0 ──► X*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ fib: procedure expose @.; arg z; if z>=0 then return .(z) diff --git a/Task/Anonymous-recursion/Sidef/anonymous-recursion-1.sidef b/Task/Anonymous-recursion/Sidef/anonymous-recursion-1.sidef index c1999f0317..d6182be3e9 100644 --- a/Task/Anonymous-recursion/Sidef/anonymous-recursion-1.sidef +++ b/Task/Anonymous-recursion/Sidef/anonymous-recursion-1.sidef @@ -1,7 +1,7 @@ { |i| func (n) { - if (n < 0) { return }; + if (n < 0) { return NaN } n < 2 ? n - : (__FUNC__(n-2) + __FUNC__(n-1)); - }(i).to_s.say; -} * 10; + : (__FUNC__(n-2) + __FUNC__(n-1)) + }(i).say +} * 10 diff --git a/Task/Anonymous-recursion/Sidef/anonymous-recursion-2.sidef b/Task/Anonymous-recursion/Sidef/anonymous-recursion-2.sidef index eac1be8569..099a9fa858 100644 --- a/Task/Anonymous-recursion/Sidef/anonymous-recursion-2.sidef +++ b/Task/Anonymous-recursion/Sidef/anonymous-recursion-2.sidef @@ -1,7 +1,7 @@ { |i| { |n| - if (n < 0) { return }; + if (n < 0) { return NaN } n < 2 ? n - : (__BLOCK__(n-2) + __BLOCK__(n-1)); - }(i).to_s.say; -} * 10; + : (__BLOCK__(n-2) + __BLOCK__(n-1)) + }(i).say +} * 10 diff --git a/Task/Anonymous-recursion/Zkl/anonymous-recursion.zkl b/Task/Anonymous-recursion/Zkl/anonymous-recursion.zkl new file mode 100644 index 0000000000..df25cdd67d --- /dev/null +++ b/Task/Anonymous-recursion/Zkl/anonymous-recursion.zkl @@ -0,0 +1,9 @@ +fcn fib(n){ + if (n<0) throw(Exception.ValueError); + fcn(n){ + if (n < 2) return(1); + else return(self.fcn(n-1) + self.fcn(n-2)); + }(n); +} +fib(8) .println(); +fib(-8).println(); diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Batch-File/append-a-record-to-the-end-of-a-text-file.bat b/Task/Append-a-record-to-the-end-of-a-text-file/Batch-File/append-a-record-to-the-end-of-a-text-file.bat new file mode 100644 index 0000000000..e31a341c26 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Batch-File/append-a-record-to-the-end-of-a-text-file.bat @@ -0,0 +1,16 @@ +@echo off + +( + echo jsmith:x:1001:1000:Joe Smith,Room 1007,^(234^)555-8917,^(234^)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash + echo jdoe:x:1002:1000:Jane Doe,Room 1004,^(234^)555-8914,^(234^)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash +) > append.txt + +echo Current contents of append.txt: +type append.txt +echo. + +echo xyz:x:1003:1000:X Yz,Room 1003,^(234^)555-8913,^(234^)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash >> append.txt + +echo New contents of append.txt: +type append.txt +pause>nul diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Common-Lisp/append-a-record-to-the-end-of-a-text-file.lisp b/Task/Append-a-record-to-the-end-of-a-text-file/Common-Lisp/append-a-record-to-the-end-of-a-text-file.lisp new file mode 100644 index 0000000000..9c27dc389c --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Common-Lisp/append-a-record-to-the-end-of-a-text-file.lisp @@ -0,0 +1,52 @@ +(defvar *initial_data* + (list + (list "jsmith" "x" 1001 1000 + (list "Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org") + "/home/jsmith" "/bin/bash") + (list "jdoe" "x" 1002 1000 + (list "Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org") + "/home/jdoe" "/bin/bash"))) + +(defvar *insert* + (list "xyz" "x" 1003 1000 + (list "X Yz" "Room 1003" "(234)555-8913" "(234)555-0033" "xyz@rosettacode.org") + "/home/xyz" "/bin/bash")) + + +(defun serialize (record delim) + (string-right-trim delim ;; Remove trailing delimiter + (reduce (lambda (a b) + (typecase b + (list (concatenate 'string a (serialize b ",") delim)) + (t (concatenate 'string a + (typecase b + (integer (write-to-string b)) + (t b)) + delim)))) + record :initial-value ""))) + + +(defun main () + ;; Write initial values to file + (with-open-file (stream "./passwd" + :direction :output + :if-exists :supersede + :if-does-not-exist :create) + (loop for x in *initial_data* do + (format stream (concatenate 'string (serialize x ":") "~%")))) + + ;; Reopen file, append insert value + (with-open-file (stream "./passwd" + :direction :output + :if-exists :append) + (format stream (concatenate 'string (serialize *insert* ":") "~%"))) + + ;; Reopen file, search for new record + (with-open-file (stream "./passwd") + (when stream + (loop for line = (read-line stream nil) + while line do + (if (search "xyz" line) + (format t "Appended record: ~a~%" line)))))) + +(main) 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.elixir index 3f49880c9a..8439d6ef05 100644 --- 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.elixir @@ -1,88 +1,86 @@ defmodule Gecos do - defstruct [:fullname, :office, :extension, :homephone, :email] + defstruct [:fullname, :office, :extension, :homephone, :email] + + defimpl String.Chars do + def to_string(gecos) do + [:fullname, :office, :extension, :homephone, :email] + |> Enum.map_join(",", &Map.get(gecos, &1)) + end + end end defmodule Passwd do - defstruct [:account, :password, :uid, :gid, :gecos, :directory, :shell] -end + defstruct [:account, :password, :uid, :gid, :gecos, :directory, :shell] -defimpl String.Chars, for: Gecos do - def to_string(gecos) do - [:fullname, :office, :extension, :homephone, :email] - |> Enum.map(&Map.get(gecos, &1)) - |> Enum.join(",") - end -end - -defimpl String.Chars, for: Passwd do - def to_string(passwd) do - [:account, :password, :uid, :gid, :gecos, :directory, :shell] - |> Enum.map(&String.Chars.to_string(Map.get(passwd, &1))) - |> Enum.join(":") - end + defimpl String.Chars do + def to_string(passwd) do + [:account, :password, :uid, :gid, :gecos, :directory, :shell] + |> Enum.map_join(":", &Map.get(passwd, &1)) + end + end end defmodule Appender do - def write(filename) do - jsmith = %Passwd{ - account: "jsmith", - password: "x", - uid: 1001, - gid: 1000, - gecos: %Gecos{ - fullname: "Joe Smith", - office: "Room 1007", - extension: "(234)555-8917", - homephone: "(234)555-0077", - email: "jsmith@rosettacode.org" - }, - directory: "/home/jsmith", - shell: "/bin/bash" - } + def write(filename) do + jsmith = %Passwd{ + account: "jsmith", + password: "x", + uid: 1001, + gid: 1000, + gecos: %Gecos{ + fullname: "Joe Smith", + office: "Room 1007", + extension: "(234)555-8917", + homephone: "(234)555-0077", + email: "jsmith@rosettacode.org" + }, + directory: "/home/jsmith", + shell: "/bin/bash" + } - jdoe = %Passwd{ - account: "jdoe", - password: "x", - uid: 1002, - gid: 1000, - gecos: %Gecos{ - fullname: "Jane Doe", - office: "Room 1004", - extension: "(234)555-8914", - homephone: "(234)555-0044", - email: "jdoe@rosettacode.org" - }, - directory: "/home/jdoe", - shell: "/bin/bash" - } + jdoe = %Passwd{ + account: "jdoe", + password: "x", + uid: 1002, + gid: 1000, + gecos: %Gecos{ + fullname: "Jane Doe", + office: "Room 1004", + extension: "(234)555-8914", + homephone: "(234)555-0044", + email: "jdoe@rosettacode.org" + }, + directory: "/home/jdoe", + shell: "/bin/bash" + } - xyz = %Passwd{ - account: "xyz", - password: "x", - uid: 1003, - gid: 1000, - gecos: %Gecos{ - fullname: "X Yz", - office: "Room 1003", - extension: "(234)555-8913", - homephone: "(234)555-0033", - email: "xyz@rosettacode.org" - }, - directory: "/home/xyz", - shell: "/bin/bash" - } + xyz = %Passwd{ + account: "xyz", + password: "x", + uid: 1003, + gid: 1000, + gecos: %Gecos{ + fullname: "X Yz", + office: "Room 1003", + extension: "(234)555-8913", + homephone: "(234)555-0033", + email: "xyz@rosettacode.org" + }, + directory: "/home/xyz", + shell: "/bin/bash" + } - {:ok, file} = File.open(filename, [:write]) - IO.puts(file, jsmith) - IO.puts(file, jdoe) - File.close(file) + File.open!(filename, [:write], fn file -> + IO.puts(file, jsmith) + IO.puts(file, jdoe) + end) - {:ok, file} = File.open(filename, [:append]) - IO.puts(file, xyz) - File.close(file) + File.open!(filename, [:append], fn file -> + IO.puts(file, xyz) + end) - IO.puts File.read!(filename) - end + IO.puts File.read!(filename) + end end Appender.write("passwd.txt") diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Fortran/append-a-record-to-the-end-of-a-text-file.f b/Task/Append-a-record-to-the-end-of-a-text-file/Fortran/append-a-record-to-the-end-of-a-text-file.f index f0042d9181..dc87b30b6f 100644 --- a/Task/Append-a-record-to-the-end-of-a-text-file/Fortran/append-a-record-to-the-end-of-a-text-file.f +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Fortran/append-a-record-to-the-end-of-a-text-file.f @@ -45,7 +45,7 @@ Choose the existing file, and append a further record to it. 1 DETAILS("X Yz","Room 1003","(234)555-8193", 2 "(234)555-033","xyz@rosettacode.org"), 3 "/home/xyz","/bin/bash") - WRITE (F,*) NOTE !Append it's content to the file. + WRITE (F,*) NOTE !Append its content to the file. CLOSE (F) Chase through the file, revealing what had been written.. diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Java/append-a-record-to-the-end-of-a-text-file.java b/Task/Append-a-record-to-the-end-of-a-text-file/Java/append-a-record-to-the-end-of-a-text-file.java index 25489e8a27..571277bb6c 100644 --- a/Task/Append-a-record-to-the-end-of-a-text-file/Java/append-a-record-to-the-end-of-a-text-file.java +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Java/append-a-record-to-the-end-of-a-text-file.java @@ -1,73 +1,71 @@ -import static java.lang.Integer.parseInt; -import static java.nio.file.StandardOpenOption.APPEND; -import static java.util.Arrays.asList; -import static java.util.Arrays.stream; import static java.util.Objects.requireNonNull; -import static java.util.stream.Collectors.joining; -import static java.util.stream.Collectors.toList; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.Arrays; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; import java.util.stream.Stream; public class RecordAppender { - static class Record { - private final String account; - private final String password; - private final int uid; - private final int gid; - private final List gecos; - private final String directory; - private final String shell; - - public Record(String account, String password, int uid, int gid, List gecos, String directory, String shell) { - this.account = requireNonNull(account); - this.password = requireNonNull(password); - this.uid = uid; - this.gid = gid; - this.gecos = requireNonNull(gecos); - this.directory = requireNonNull(directory); - this.shell = requireNonNull(shell); + static class Record { + private final String account; + private final String password; + private final int uid; + private final int gid; + private final List gecos; + private final String directory; + private final String shell; + + public Record(String account, String password, int uid, int gid, List gecos, String directory, String shell) { + this.account = requireNonNull(account); + this.password = requireNonNull(password); + this.uid = uid; + this.gid = gid; + this.gecos = requireNonNull(gecos); + this.directory = requireNonNull(directory); + this.shell = requireNonNull(shell); + } + + @Override + public String toString() { + return account + ':' + password + ':' + uid + ':' + gid + ':' + String.join(",", gecos) + ':' + directory + ':' + shell; + } + + public static Record parse(String text) { + String[] tokens = text.split(":"); + return new Record( + tokens[0], + tokens[1], + Integer.parseInt(tokens[2]), + Integer.parseInt(tokens[3]), + Arrays.asList(tokens[4].split(",")), + tokens[5], + tokens[6]); + } } - - @Override - public String toString() { - return account + ':' + password + ':' + uid + ':' + gid + ':' + gecos.stream().collect(joining(",")) + ':' + directory + ':' + shell; + + public static void main(String[] args) throws IOException { + List rawData = Arrays.asList( + "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", + "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", + "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" + ); + + List records = rawData.stream().map(Record::parse).collect(Collectors.toList()); + + Path tmp = Paths.get("_rosetta", ".passwd"); + Files.createDirectories(tmp.getParent()); + Files.write(tmp, (Iterable) records.stream().limit(2).map(Record::toString)::iterator); + + Files.write(tmp, Collections.singletonList(records.get(2).toString()), StandardOpenOption.APPEND); + + try (Stream lines = Files.lines(tmp)) { + lines.map(Record::parse).forEach(System.out::println); + } } - - public static Record parse(String text) { - String[] tokens = text.split(":"); - return new Record( - tokens[0], - tokens[1], - parseInt(tokens[2]), - parseInt(tokens[3]), - asList(tokens[4].split(",")), - tokens[5], - tokens[6]); - } - } - - public static void main(String[] args) throws IOException { - String[] rawData = { - "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", - "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", - "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" - }; - - List records = stream(rawData).map(Record::parse).collect(toList()); - - Path tmp = Paths.get("_rosetta", ".passwd"); - Files.createDirectories(tmp.getParent()); - Files.write(tmp, (Iterable)records.stream().limit(2).map(Record::toString)::iterator); - - Files.write(tmp, asList(records.get(2).toString()), APPEND); - - try(Stream lines = Files.lines(tmp)) { - lines.map(Record::parse).forEach(System.out::println); - } - } } diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Phix/append-a-record-to-the-end-of-a-text-file.phix b/Task/Append-a-record-to-the-end-of-a-text-file/Phix/append-a-record-to-the-end-of-a-text-file.phix new file mode 100644 index 0000000000..196345d3d5 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Phix/append-a-record-to-the-end-of-a-text-file.phix @@ -0,0 +1,61 @@ +constant filename = "passwd.txt" +integer fn + +constant + rec1 = {"jsmith","x",1001,1000,{"Joe Smith","Room 1007","(234)555-8917","(234)555-0077","jsmith@rosettacode.org"},"/home/jsmith","/bin/bash"}, + rec2 = {"jdoe","x",1002,1000,{"Jane Doe","Room 1004","(234)555-8914","(234)555-0044","jdoe@rosettacode.org"},"/home/jdoe","/bin/bash"}, + rec3 = {"xyz","x",1003,1000,{"X Yz","Room 1003","(234)555-8913","(234)555-0033","xyz@rosettacode.org"},"/home/xyz","/bin/bash"} + +function tostring(sequence record) + record[3] = sprintf("%d",{record[3]}) + record[4] = sprintf("%d",{record[4]}) + record[5] = join(record[5],",") + record = join(record,":") + return record +end function + +procedure wait(string what) + ?sprintf("wait (%s)",{what}) + sleep(1) + task_yield() +end procedure + + if not file_exists(filename) then + fn = open(filename,"w") + if fn!=-1 then -- (someone else just beat us to it?) + printf(fn,"account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell\n") + printf(fn,"%s\n",{tostring(rec1)}) + printf(fn,"%s\n",{tostring(rec2)}) + close(fn) + end if + end if + while 1 do + fn = open(filename,"a") + if fn!=-1 then exit end if + wait("append") + end while +-- ?"file open in append mode"; {} = wait_key() + while 1 do + if lock_file(fn,LOCK_EXCLUSIVE,{}) then exit end if + wait("lock") + end while +-- ?"file locked"; {} = wait_key() + printf(fn,"%s\n",{tostring(rec3)}) + unlock_file(fn,{}) + close(fn) + while 1 do + fn = open(filename,"r") + if fn!=-1 then exit end if + wait("read") + end while + + ?gets(fn) + while 1 do + object line = gets(fn) + if atom(line) then exit end if + ?line + {line} = scanf(line,"%s:%s:%d:%d:%s:%s:%s\n") + line[5] = split(line[5],',') + ?line + end while + close(fn) diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/REXX/append-a-record-to-the-end-of-a-text-file.rexx b/Task/Append-a-record-to-the-end-of-a-text-file/REXX/append-a-record-to-the-end-of-a-text-file.rexx index 2c4e553f25..463c835318 100644 --- a/Task/Append-a-record-to-the-end-of-a-text-file/REXX/append-a-record-to-the-end-of-a-text-file.rexx +++ b/Task/Append-a-record-to-the-end-of-a-text-file/REXX/append-a-record-to-the-end-of-a-text-file.rexx @@ -1,5 +1,4 @@ /*REXX program writes (appends) two records, closes the file, appends another record.*/ -signal on syntax; signal on noValue /*handle (if any) REXX program errors.*/ tFID= 'PASSWD.TXT' /*define the name of the output file.*/ call lineout tFID /*close the output file, just in case,*/ /* it could be open from calling pgm.*/ @@ -18,10 +17,7 @@ call writeRec tFID,, /*append the 3rd record to th call lineout fid /*"be safe" programming: close the file*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -err: say; say '***error***'; say; do j=1 for arg(); say arg(j); say; end; exit 13 s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) /*pluralizer*/ -/*──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ -noValue: syntax: call err 'REXX program' condition("C"), condition("D"), 'REXX source statement (line' sigl"):", sourceline(sigl) /*──────────────────────────────────────────────────────────────────────────────────────*/ writeRec: parse arg fid,_ /*get the fileID, and also the 1st arg.*/ sep=':' /*field delimiter used in file, it ··· */ @@ -35,5 +31,6 @@ writeRec: parse arg fid,_ /*get the fileID, and also the if r==0 then return /*Zero? Then record was written. */ call sleep tries /*Error? So try again after a delay. */ end /*tries*/ /*Note: not all REXXes have SLEEP. */ - call err r 'record's(r) "not written to file" fid; exit 13 + + say '***error***'; say r 'record's(r) "not written to file" fid; exit 13 /*some error causes: no write access, disk is full, file lockout, no authority*/ diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Zkl/append-a-record-to-the-end-of-a-text-file-1.zkl b/Task/Append-a-record-to-the-end-of-a-text-file/Zkl/append-a-record-to-the-end-of-a-text-file-1.zkl new file mode 100644 index 0000000000..32ba9bbe83 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Zkl/append-a-record-to-the-end-of-a-text-file-1.zkl @@ -0,0 +1,14 @@ +var [const] + gnames=T("fullname","office","extension","homephone","email"), + pnames=T("account","password","uid","gid","gecos","directory","shell"); + +class Gecos{ + var fullname, office, extension, homephone, email; + fcn init(str){ gnames.zipWith(setVar,vm.arglist) } + fcn toString { gnames.apply(setVar).concat(",") } +} +class Passwd{ + var account,password,uid,gid,gecos,directory,shell; + fcn init(str){ pnames.zipWith(setVar,vm.arglist) } + fcn toString { pnames.apply(setVar).concat(":") } +} diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Zkl/append-a-record-to-the-end-of-a-text-file-2.zkl b/Task/Append-a-record-to-the-end-of-a-text-file/Zkl/append-a-record-to-the-end-of-a-text-file-2.zkl new file mode 100644 index 0000000000..4c6e076c7f --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Zkl/append-a-record-to-the-end-of-a-text-file-2.zkl @@ -0,0 +1,5 @@ +fcn strToPasswd(str){ // blow apart file line to class + p:=str.strip().split(":"); + g:=Gecos(p[4].split(",").xplode()); + Passwd(p[0,4].xplode(),g,p[5,*].xplode()); +} diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Zkl/append-a-record-to-the-end-of-a-text-file-3.zkl b/Task/Append-a-record-to-the-end-of-a-text-file/Zkl/append-a-record-to-the-end-of-a-text-file-3.zkl new file mode 100644 index 0000000000..3d3c899abe --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Zkl/append-a-record-to-the-end-of-a-text-file-3.zkl @@ -0,0 +1,16 @@ +jsmith:=Passwd("jsmith","x",1001, 1000, + Gecos("Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"), + "/home/jsmith", "/bin/bash"); +jdoe:=strToPasswd("jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044," + "jdoe@rosettacode.org:/home/jdoe:/bin/bash"); +xyz:=strToPasswd("xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033," + "xyz@rosettacode.org:/home/xyz:/bin/bash"); + +filename:="append.records.test"; +f:=File(filename,"w"); // create file with 2 records +f.writeln(jsmith,"\n",jdoe); f.close(); + +f:=File(filename,"a+"); // append a third record +f.writeln(xyz); f.close(); + +File(filename).read().text.print(); // print file diff --git a/Task/Apply-a-callback-to-an-array/Aime/apply-a-callback-to-an-array.aime b/Task/Apply-a-callback-to-an-array/Aime/apply-a-callback-to-an-array.aime index 15f9021028..992104cdb6 100644 --- a/Task/Apply-a-callback-to-an-array/Aime/apply-a-callback-to-an-array.aime +++ b/Task/Apply-a-callback-to-an-array/Aime/apply-a-callback-to-an-array.aime @@ -1,35 +1,21 @@ void -map(list l, void (*fp) (object)) +map(list l, void (*fp)(object)) { - integer i; - - i = 0; - while (i < l_length(l)) { - fp(l[i]); - i += 1; - } + l_ucall(l, fp, 0); } void out(object o) { - o_integer(o); - o_byte(10); + o_(o, "\n"); } integer main(void) { - list l; - - l_append(l, 0); - l_append(l, 1); - l_append(l, 2); - l_append(l, 3); - - map(l, out); + map(l_effect(0, 1, 2, 3), out); return 0; } diff --git a/Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-3.pb b/Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-3.pb deleted file mode 100644 index 959e3fdc9c..0000000000 --- a/Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-3.pb +++ /dev/null @@ -1,9 +0,0 @@ -((main - { [val 1 1 2 3 5 8 13 21] - {double !} eachar - collect ! - {%d ' ' . <<} each}) - -(double { 2 * }) - -(collect { -1 take })) diff --git a/Task/Apply-a-callback-to-an-array/C-sharp/apply-a-callback-to-an-array-1.cs b/Task/Apply-a-callback-to-an-array/C-sharp/apply-a-callback-to-an-array-1.cs index 5732b940db..7f3d1f715d 100644 --- a/Task/Apply-a-callback-to-an-array/C-sharp/apply-a-callback-to-an-array-1.cs +++ b/Task/Apply-a-callback-to-an-array/C-sharp/apply-a-callback-to-an-array-1.cs @@ -1,34 +1,11 @@ -using System; +int[] intArray = { 1, 2, 3, 4, 5 }; +// Simplest method: LINQ, functional +int[] squares1 = intArray.Select(x => x * x).ToArray(); -static class Program -{ - // Purpose: Apply a callback (or anonymous method) to an Array - // Output: Prints the squares of an int array to the console. - // Compiler: Visual Studio 2005 - // Framework: .net 2 +// Slightly fancier: LINQ, query expression +int[] squares2 = (from x in intArray + select x * x).ToArray(); - [STAThread] - public static void Main() - { - int[] intArray = { 1, 2, 3, 4, 5 }; - - // Using a callback, - Console.WriteLine("Printing squares using a callback:"); - Array.ForEach(intArray, PrintSquare); - - // or using an anonymous method: - Console.WriteLine("Printing squares using an anonymous method:"); - Array.ForEach - ( - intArray, - delegate(int value) - { - Console.WriteLine(value * value); - }); - } - - public static void PrintSquare(int value) - { - Console.WriteLine(value * value); - } -} +// Or, if you only want to call a function on each element, just use foreach +foreach (var i in intArray) + Console.WriteLine(i * i); diff --git a/Task/Apply-a-callback-to-an-array/C-sharp/apply-a-callback-to-an-array-2.cs b/Task/Apply-a-callback-to-an-array/C-sharp/apply-a-callback-to-an-array-2.cs index e5bc00017c..5732b940db 100644 --- a/Task/Apply-a-callback-to-an-array/C-sharp/apply-a-callback-to-an-array-2.cs +++ b/Task/Apply-a-callback-to-an-array/C-sharp/apply-a-callback-to-an-array-2.cs @@ -1,2 +1,34 @@ -int[] intArray = { 1, 2, 3, 4, 5 }; -Array.ForEach(intArray, i => Console.WriteLine(i * i)); +using System; + +static class Program +{ + // Purpose: Apply a callback (or anonymous method) to an Array + // Output: Prints the squares of an int array to the console. + // Compiler: Visual Studio 2005 + // Framework: .net 2 + + [STAThread] + public static void Main() + { + int[] intArray = { 1, 2, 3, 4, 5 }; + + // Using a callback, + Console.WriteLine("Printing squares using a callback:"); + Array.ForEach(intArray, PrintSquare); + + // or using an anonymous method: + Console.WriteLine("Printing squares using an anonymous method:"); + Array.ForEach + ( + intArray, + delegate(int value) + { + Console.WriteLine(value * value); + }); + } + + public static void PrintSquare(int value) + { + Console.WriteLine(value * value); + } +} 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 40672f3f6d..3086e60e6d 100644 --- a/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena +++ b/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena @@ -1,10 +1,6 @@ -#define system. -#define system'routines. +import system'routines. -#symbol PrintSecondPower = - (:n) [ console writeLine:(n * n) ]. - -#symbol program = +program = [ - (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) run &each:PrintSecondPower. + (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) forEach(:n) [ console writeLine(n * n) ]. ]. 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.elixir index 84e62078e3..0c619f17d2 100644 --- 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.elixir @@ -1 +1,2 @@ Enum.map([1, 2, 3], fn(n) -> n * 2 end) +Enum.map [1, 2, 3], &(&1 * 2) diff --git a/Task/Apply-a-callback-to-an-array/Haskell/apply-a-callback-to-an-array-3.hs b/Task/Apply-a-callback-to-an-array/Haskell/apply-a-callback-to-an-array-3.hs index 2950d3f7ab..c94a4e2fb4 100644 --- a/Task/Apply-a-callback-to-an-array/Haskell/apply-a-callback-to-an-array-3.hs +++ b/Task/Apply-a-callback-to-an-array/Haskell/apply-a-callback-to-an-array-3.hs @@ -1,2 +1 @@ -let printSquares = mapM_ (print.square) -printSquares values +[1 .. 10] >>= pure . (^ 2) diff --git a/Task/Apply-a-callback-to-an-array/Haskell/apply-a-callback-to-an-array-4.hs b/Task/Apply-a-callback-to-an-array/Haskell/apply-a-callback-to-an-array-4.hs index e0cb25c5fc..d17f63dfce 100644 --- a/Task/Apply-a-callback-to-an-array/Haskell/apply-a-callback-to-an-array-4.hs +++ b/Task/Apply-a-callback-to-an-array/Haskell/apply-a-callback-to-an-array-4.hs @@ -1,4 +1 @@ -import Data.Array.IArray -let square x = x*x -let values = array (1,10) [(i,i)|i <- [1..10]] :: Array Int Int -amap square values +(^ 2) <$> [1..10] diff --git a/Task/Apply-a-callback-to-an-array/Haskell/apply-a-callback-to-an-array-5.hs b/Task/Apply-a-callback-to-an-array/Haskell/apply-a-callback-to-an-array-5.hs new file mode 100644 index 0000000000..2950d3f7ab --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Haskell/apply-a-callback-to-an-array-5.hs @@ -0,0 +1,2 @@ +let printSquares = mapM_ (print.square) +printSquares values diff --git a/Task/Apply-a-callback-to-an-array/Haskell/apply-a-callback-to-an-array-6.hs b/Task/Apply-a-callback-to-an-array/Haskell/apply-a-callback-to-an-array-6.hs new file mode 100644 index 0000000000..6a3db74f3c --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Haskell/apply-a-callback-to-an-array-6.hs @@ -0,0 +1,10 @@ +import Data.Array (Array, listArray) + +square :: Int -> Int +square x = x * x + +values :: Array Int Int +values = listArray (1, 10) [1 .. 10] + +main :: IO () +main = print $ fmap square values diff --git a/Task/Apply-a-callback-to-an-array/Java/apply-a-callback-to-an-array-1.java b/Task/Apply-a-callback-to-an-array/Java/apply-a-callback-to-an-array-1.java index d1689ff5b6..a958a0f8c8 100644 --- a/Task/Apply-a-callback-to-an-array/Java/apply-a-callback-to-an-array-1.java +++ b/Task/Apply-a-callback-to-an-array/Java/apply-a-callback-to-an-array-1.java @@ -1,11 +1,45 @@ -interface IntToVoid { - void run(int x); -} +public class ArrayCallback7 { -for (int z : myIntArray) { - new IntToVoid() { - public void run(int x) { - System.out.println(x); + interface IntConsumer { + void run(int x); + } + + interface IntToInt { + int run(int x); + } + + static void forEach(int[] arr, IntConsumer consumer) { + for (int i : arr) { + consumer.run(i); } - }.run(z); + } + + static void update(int[] arr, IntToInt mapper) { + for (int i = 0; i < arr.length; i++) { + arr[i] = mapper.run(arr[i]); + } + } + + public static void main(String[] args) { + int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + + forEach(numbers, new IntConsumer() { + public void run(int x) { + System.out.println(x); + } + }); + + update(numbers, new IntToInt() { + @Override + public int run(int x) { + return x * x; + } + }); + + forEach(numbers, new IntConsumer() { + public void run(int x) { + System.out.println(x); + } + }); + } } diff --git a/Task/Apply-a-callback-to-an-array/Java/apply-a-callback-to-an-array-2.java b/Task/Apply-a-callback-to-an-array/Java/apply-a-callback-to-an-array-2.java index 8e05ef64f0..71848e3af7 100644 --- a/Task/Apply-a-callback-to-an-array/Java/apply-a-callback-to-an-array-2.java +++ b/Task/Apply-a-callback-to-an-array/Java/apply-a-callback-to-an-array-2.java @@ -1,13 +1,17 @@ -interface IntToInt { - int run(int x); -} +import java.util.Arrays; -int[] result = new int[myIntArray.length]; -for (int i = 0; i < myIntArray.length; i++) { - result[i] = - new IntToInt() { - public int run(int x) { - return x * x; - } - }.run(myIntArray[i]); +public class ArrayCallback { + + public static void main(String[] args) { + int[] myIntArray = {1, 2, 3, 4, 5}; + + int sum = Arrays.stream(myIntArray) + .map(x -> { + int cube = x * x * x; + System.out.println(cube); + return cube; + }) + .reduce(0, (left, right) -> left + right); // <-- could substitute .sum() for .reduce(...) here. + System.out.println("sum: " + sum); + } } diff --git a/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-4.js b/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-4.js deleted file mode 100644 index b474d2b7e3..0000000000 --- a/Task/Apply-a-callback-to-an-array/JavaScript/apply-a-callback-to-an-array-4.js +++ /dev/null @@ -1 +0,0 @@ -Functional.map('x*x*x', [1,2,3,4,5]) diff --git a/Task/Apply-a-callback-to-an-array/jq/apply-a-callback-to-an-array-1.jq b/Task/Apply-a-callback-to-an-array/Jq/apply-a-callback-to-an-array-1.jq similarity index 100% rename from Task/Apply-a-callback-to-an-array/jq/apply-a-callback-to-an-array-1.jq rename to Task/Apply-a-callback-to-an-array/Jq/apply-a-callback-to-an-array-1.jq diff --git a/Task/Apply-a-callback-to-an-array/jq/apply-a-callback-to-an-array-2.jq b/Task/Apply-a-callback-to-an-array/Jq/apply-a-callback-to-an-array-2.jq similarity index 100% rename from Task/Apply-a-callback-to-an-array/jq/apply-a-callback-to-an-array-2.jq rename to Task/Apply-a-callback-to-an-array/Jq/apply-a-callback-to-an-array-2.jq diff --git a/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array-1.julia b/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array-1.julia deleted file mode 100644 index a80a7e58d2..0000000000 --- a/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array-1.julia +++ /dev/null @@ -1,8 +0,0 @@ -a = [1,2,3,4,5] -julia> map(x -> x*2,a) -5-element Int32 Array: - 2 - 4 - 6 - 8 - 10 diff --git a/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array-2.julia b/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array-2.julia deleted file mode 100644 index bf447939a3..0000000000 --- a/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array-2.julia +++ /dev/null @@ -1,7 +0,0 @@ -julia> a .* 2 -5-element Int32 Array: - 2 - 4 - 6 - 8 - 10 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.kotlin index d833e479fb..a7ac594cd8 100644 --- 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.kotlin @@ -1,5 +1,5 @@ fun main(args: Array) { - val array = arrayOf(1,2,3,4,5,6,7,8,9,10) // build + val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // build val function = { i: Int -> i * i } // function to apply val list = array.map { function(it) } // process each item println(list) // print results diff --git a/Task/Apply-a-callback-to-an-array/Nim/apply-a-callback-to-an-array.nim b/Task/Apply-a-callback-to-an-array/Nim/apply-a-callback-to-an-array.nim index 5a04ac5570..60d1dca090 100644 --- a/Task/Apply-a-callback-to-an-array/Nim/apply-a-callback-to-an-array.nim +++ b/Task/Apply-a-callback-to-an-array/Nim/apply-a-callback-to-an-array.nim @@ -1,2 +1,2 @@ -var arr = [1,2,3,4] -arr.map proc(some: var int) = echo(some, " squared = ", some*some) +var arr = @[1,2,3,4] +arr.apply proc(some: var int) = echo(some, " squared = ", some*some) diff --git a/Task/Apply-a-callback-to-an-array/Nimrod/apply-a-callback-to-an-array.nimrod b/Task/Apply-a-callback-to-an-array/Nimrod/apply-a-callback-to-an-array.nimrod deleted file mode 100644 index 5a04ac5570..0000000000 --- a/Task/Apply-a-callback-to-an-array/Nimrod/apply-a-callback-to-an-array.nimrod +++ /dev/null @@ -1,2 +0,0 @@ -var arr = [1,2,3,4] -arr.map proc(some: var int) = echo(some, " squared = ", some*some) diff --git a/Task/Apply-a-callback-to-an-array/Ol/apply-a-callback-to-an-array.ol b/Task/Apply-a-callback-to-an-array/Ol/apply-a-callback-to-an-array.ol new file mode 100644 index 0000000000..e754405709 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Ol/apply-a-callback-to-an-array.ol @@ -0,0 +1,5 @@ +(for-each + (lambda (element) + (display element)) + '(1 2 3 4 5)) +; ==> 12345 diff --git a/Task/Apply-a-callback-to-an-array/OoRexx/apply-a-callback-to-an-array.rexx b/Task/Apply-a-callback-to-an-array/OoRexx/apply-a-callback-to-an-array.rexx new file mode 100644 index 0000000000..04f1e64c6f --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/OoRexx/apply-a-callback-to-an-array.rexx @@ -0,0 +1,24 @@ +start = .array~of("Rick", "Mike", "David", "Mark") +new = map(start, .routines~reversit) +call map new, .routines~sayit + + +-- a function to perform an iterated callback over an array +-- using the provided function. Returns an array containing +-- each function result +::routine map + use strict arg array, function + resultArray = .array~new(array~items) + do item over array + resultArray~append(function~call(item)) + end + return resultArray + +::routine reversit + use arg string + return string~reverse + +::routine sayit + use arg string + say string + return .true -- called as a function, so a result is required diff --git a/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-1.sidef b/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-1.sidef index db7c7d81ea..4d154c101e 100644 --- a/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-1.sidef +++ b/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-1.sidef @@ -1 +1 @@ -func callback(i) { say i**2 }; +func callback(i) { say i**2 } diff --git a/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-2.sidef b/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-2.sidef index 584a90a056..912b8d7234 100644 --- a/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-2.sidef +++ b/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-2.sidef @@ -1 +1 @@ -[1,2,3,4].each(callback); +[1,2,3,4].each(callback) diff --git a/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-3.sidef b/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-3.sidef index d28f324d70..c85f1e49e0 100644 --- a/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-3.sidef +++ b/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-3.sidef @@ -1 +1 @@ -[1,2,3,4].each{|i| say i**2 }; +[1,2,3,4].each{|i| say i**2 } diff --git a/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-4.sidef b/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-4.sidef index 3d64c9e107..e0e07ad641 100644 --- a/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-4.sidef +++ b/Task/Apply-a-callback-to-an-array/Sidef/apply-a-callback-to-an-array-4.sidef @@ -1 +1 @@ -[1,2,3,4,5].map{|i| i**2 }; +[1,2,3,4,5].map{|i| i**2 } diff --git a/Task/Apply-a-callback-to-an-array/Simula/apply-a-callback-to-an-array.simula b/Task/Apply-a-callback-to-an-array/Simula/apply-a-callback-to-an-array.simula new file mode 100644 index 0000000000..adec6d9942 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Simula/apply-a-callback-to-an-array.simula @@ -0,0 +1,22 @@ +BEGIN + + ! APPLIES A CALLBACK FUNCTION TO AN ARRAY ; + PROCEDURE APPLY(ARR, FUN); + REAL ARRAY ARR; + PROCEDURE FUN IS REAL PROCEDURE FUN(X); REAL X;; + BEGIN + INTEGER I; + FOR I := LOWERBOUND(ARR, 1) STEP 1 UNTIL UPPERBOUND(ARR, 1) DO + ARR(I) := FUN(ARR(I)); + END APPLY; + + ! CALLBACK ; + REAL PROCEDURE SQUARE(X); REAL X; SQUARE := X * X; + + REAL ARRAY A(1:5); + INTEGER I; + FOR I := 1 STEP 1 UNTIL 5 DO A(I) := I; + APPLY(A, SQUARE); + FOR I := 1 STEP 1 UNTIL 5 DO OUTFIX(A(I), 2, 8); OUTIMAGE; + +END. diff --git a/Task/Apply-a-callback-to-an-array/SuperCollider/apply-a-callback-to-an-array-2.supercollider b/Task/Apply-a-callback-to-an-array/SuperCollider/apply-a-callback-to-an-array-2.supercollider index a3864475e7..09caf44a51 100644 --- a/Task/Apply-a-callback-to-an-array/SuperCollider/apply-a-callback-to-an-array-2.supercollider +++ b/Task/Apply-a-callback-to-an-array/SuperCollider/apply-a-callback-to-an-array-2.supercollider @@ -1 +1 @@ -[1, 2, 3].collect({ | x | x * x }) +[1, 2, 3].collect { |x| x * x } diff --git a/Task/Apply-a-callback-to-an-array/Zkl/apply-a-callback-to-an-array.zkl b/Task/Apply-a-callback-to-an-array/Zkl/apply-a-callback-to-an-array.zkl new file mode 100644 index 0000000000..99f4ec684c --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Zkl/apply-a-callback-to-an-array.zkl @@ -0,0 +1 @@ +L(1,2,3,4,5).apply('+(5)) diff --git a/Task/Arbitrary-precision-integers--included-/00DESCRIPTION b/Task/Arbitrary-precision-integers--included-/00DESCRIPTION index 32972c33c3..14ee5c0142 100644 --- a/Task/Arbitrary-precision-integers--included-/00DESCRIPTION +++ b/Task/Arbitrary-precision-integers--included-/00DESCRIPTION @@ -11,7 +11,7 @@ Using the in-built capabilities of your language, calculate the integer value of
  • Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the '''only''' recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
  • -;See also: -* [[Long multiplication]] -* [[Exponentiation order]] +;Related tasks: +*   [[Long multiplication]] +*   [[Exponentiation order]]

    diff --git a/Task/Arbitrary-precision-integers--included-/Bc/arbitrary-precision-integers--included-.bc b/Task/Arbitrary-precision-integers--included-/Bc/arbitrary-precision-integers--included-.bc new file mode 100644 index 0000000000..3d34e89375 --- /dev/null +++ b/Task/Arbitrary-precision-integers--included-/Bc/arbitrary-precision-integers--included-.bc @@ -0,0 +1,8 @@ +/* 5432.bc */ + +y = 5 ^ 4 ^ 3 ^ 2 +c = length(y) +" First 20 digits: "; y / (10 ^ (c - 20)) +" Last 20 digits: "; y % (10 ^ 20) +"Number of digits: "; c +quit diff --git a/Task/Arbitrary-precision-integers--included-/Dc/arbitrary-precision-integers--included-.dc b/Task/Arbitrary-precision-integers--included-/Dc/arbitrary-precision-integers--included-.dc new file mode 100644 index 0000000000..c7ac2b180c --- /dev/null +++ b/Task/Arbitrary-precision-integers--included-/Dc/arbitrary-precision-integers--included-.dc @@ -0,0 +1,7 @@ +[5432.dc]sz + +5 4 3 2 ^ ^ ^ sy [y = 5 ^ 4 ^ 3 ^ 2]sz +ly Z sc [c = length of y]sz +[ First 20 digits: ]P ly 10 lc 20 - ^ / p sz [y / (10 ^ (c - 20))]sz +[ Last 20 digits: ]P ly 10 20 ^ % p sz [y % (10 ^ 20)]sz +[Number of digits: ]P lc p sz diff --git a/Task/Arbitrary-precision-integers--included-/Java/arbitrary-precision-integers--included-.java b/Task/Arbitrary-precision-integers--included-/Java/arbitrary-precision-integers--included-.java index 6d9f1d5c70..948d2edd76 100644 --- a/Task/Arbitrary-precision-integers--included-/Java/arbitrary-precision-integers--included-.java +++ b/Task/Arbitrary-precision-integers--included-/Java/arbitrary-precision-integers--included-.java @@ -1,11 +1,11 @@ import java.math.BigInteger; -class Program { +class IntegerPower { public static void main(String[] args) { - BigInteger x = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValue()).intValue()); - String y = x.toString(); - int l = y.length(); - System.out.printf("5**4**3**2 = %s...%s and has %d digits\n", - y.substring(0,20), y.substring(l-20), l); + BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact()); + String str = power.toString(); + int len = str.length(); + System.out.printf("5**4**3**2 = %s...%s and has %d digits%n", + str.substring(0, 20), str.substring(len - 20), len); } } diff --git a/Task/Arbitrary-precision-integers--included-/Kotlin/arbitrary-precision-integers--included-.kotlin b/Task/Arbitrary-precision-integers--included-/Kotlin/arbitrary-precision-integers--included-.kotlin new file mode 100644 index 0000000000..159ace2809 --- /dev/null +++ b/Task/Arbitrary-precision-integers--included-/Kotlin/arbitrary-precision-integers--included-.kotlin @@ -0,0 +1,8 @@ +import java.math.BigInteger + +fun main(args: Array) { + val x = BigInteger.valueOf(5).pow(Math.pow(4.0, 3.0 * 3.0).toInt()) + val y = x.toString() + val len = y.length + println("5^4^3^2 = ${y.substring(0, 20)}...${y.substring(len - 20)} and has $len digits") +} diff --git a/Task/Arbitrary-precision-integers--included-/OoRexx/arbitrary-precision-integers--included-.rexx b/Task/Arbitrary-precision-integers--included-/OoRexx/arbitrary-precision-integers--included-.rexx new file mode 100644 index 0000000000..c7a92440f4 --- /dev/null +++ b/Task/Arbitrary-precision-integers--included-/OoRexx/arbitrary-precision-integers--included-.rexx @@ -0,0 +1,18 @@ +--REXX program to show arbitrary precision integers. +numeric digits 200000 +check = '62060698786608744707...92256259918212890625' + +start = .datetime~new +n = 5 ** (4 ** (3**2)) +time = .datetime~new - start +say 'elapsed time for the calculation:' time +say +sampl = left(n, 20)"..."right(n, 20) + +say ' check:' check +say 'Sample:' sampl +say 'digits:' length(n) +say + +if check=sampl then say 'passed!' + else say 'failed!' diff --git a/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--1.rexx b/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--1.rexx index 3d15ed71be..4fd5adf515 100644 --- a/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--1.rexx +++ b/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--1.rexx @@ -1,15 +1,15 @@ -/*REXX program calculates and demonstrates arbitrary precision numbers. */ -numeric digits 200000 /*two hundred thousand decimal digits. */ +/*REXX program calculates and demonstrates arbitrary precision numbers (using powers). */ +numeric digits 200000 /*two hundred thousand decimal digits. */ - n = 5 ** (4 ** (3 ** 2)) /*calculate multiple exponentiations. */ + n = 5 ** (4 ** (3 ** 2) ) /*calculate multiple exponentiations. */ -check = 62060698786608744707...92256259918212890625 -sampl = left(n, 20) || ... || right(n, 20) +true=62060698786608744707...92256259918212890625 /*what answer is supposed to look like.*/ +rexx= left(n, 20)'...'right(n, 20) /*the left and right 20 decimal digits.*/ -say ' check:' check -say 'sample:' sampl -say 'digits:' length(n) +say ' true:' true /*show what the "true" answer is. */ +say ' REXX:' rexx /* " " " REXX " " */ +say 'digits:' length(n) /* " " " length of answer is. */ say -if check==sampl then say 'passed!' - else say 'failed!' - /*stick a fork in it, we're all done. */ +if true == rexx then say 'passed!' /*either it passed, ··· */ + else say 'failed!' /* or it didn't. */ + /*stick a fork in it, we're all done. */ diff --git a/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--2.rexx b/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--2.rexx index c1694879b2..972913632a 100644 --- a/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--2.rexx +++ b/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--2.rexx @@ -1,22 +1,22 @@ -/*REXX program calculates and demonstrates arbitrary precision numbers. */ -numeric digits 5 + 1 /*6 is needed (not 5) for ooRexx. */ +/*REXX program calculates and demonstrates arbitrary precision numbers (using powers). */ +numeric digits 5 /*just use enough digits for 1st time. */ - n=5** (4** (3** 2)) /*calculate multiple exponentiations. */ + n=5** (4** (3** 2) ) /*calculate multiple exponentiations. */ -parse var n 'E' pow . /*POW might be null, so N is OK. */ +parse var n 'E' pow . /*POW might be null, so N is OK. */ -if pow\=='' then do /*general case: POW might be < zero.*/ - numeric digits abs(pow)+9 /*recalculate with more digits.*/ - n=5** (4** (3** 2)) /*calculate multiple exponentiations. */ - end +if pow\=='' then do /*general case: POW might be < zero.*/ + numeric digits abs(pow) + 9 /*recalculate with more decimal digits.*/ + n=5** (4** (3** 2) ) /*calculate multiple exponentiations. */ + end /* [↑] calculation is the real McCoy. */ -check = 62060698786608744707...92256259918212890625 -sampl = left(n, 20)'...'right(n, 20) +true=62060698786608744707...92256259918212890625 /*what answer is supposed to look like.*/ +rexx= left(n, 20)'...'right(n, 20) /*the left and right 20 decimal digits.*/ -say ' check:' check -say 'sample:' sampl -say 'digits:' length(n) +say ' true:' true /*show what the "true" answer is. */ +say ' REXX:' rexx /* " " " REXX " " */ +say 'digits:' length(n) /* " " " length of answer is. */ say -if check==sampl then say 'passed!' - else say 'failed!' - /*stick a fork in it, we're all done. */ +if true == rexx then say 'passed!' /*either it passed, ··· */ + else say 'failed!' /* or it didn't. */ + /*stick a fork in it, we're all done. */ diff --git a/Task/Arbitrary-precision-integers--included-/Rust/arbitrary-precision-integers--included-.rust b/Task/Arbitrary-precision-integers--included-/Rust/arbitrary-precision-integers--included-.rust new file mode 100644 index 0000000000..b906225cae --- /dev/null +++ b/Task/Arbitrary-precision-integers--included-/Rust/arbitrary-precision-integers--included-.rust @@ -0,0 +1,9 @@ +extern crate num; +use num::bigint::BigUint; +use num::FromPrimitive; +use num::pow::pow; + +fn main() { + let big = BigUint::from_u8(5).unwrap(); + println!("{}", pow(big,pow(4,pow(3,2)))); +} diff --git a/Task/Arbitrary-precision-integers--included-/SPL/arbitrary-precision-integers--included-.spl b/Task/Arbitrary-precision-integers--included-/SPL/arbitrary-precision-integers--included-.spl new file mode 100644 index 0000000000..5891773e73 --- /dev/null +++ b/Task/Arbitrary-precision-integers--included-/SPL/arbitrary-precision-integers--included-.spl @@ -0,0 +1,4 @@ +t = #.str(5^(4^(3^2))) +n = #.size(t) +#.output(n," digits") +#.output(#.mid(t,1,20),"...",#.mid(t,n-19,20)) diff --git a/Task/Arbitrary-precision-integers--included-/Zkl/arbitrary-precision-integers--included-.zkl b/Task/Arbitrary-precision-integers--included-/Zkl/arbitrary-precision-integers--included-.zkl new file mode 100644 index 0000000000..ca06b39fe0 --- /dev/null +++ b/Task/Arbitrary-precision-integers--included-/Zkl/arbitrary-precision-integers--included-.zkl @@ -0,0 +1,5 @@ +var BN=Import("zklBigNum"); +n:=BN(5).pow(BN(4).pow(BN(3).pow(2))); +s:=n.toString(); +"%,d".fmt(s.len()).println(); +println(s[0,20],"...",s[-20,*]); diff --git a/Task/Arena-storage-pool/Kotlin/arena-storage-pool.kotlin b/Task/Arena-storage-pool/Kotlin/arena-storage-pool.kotlin new file mode 100644 index 0000000000..d6431b8789 --- /dev/null +++ b/Task/Arena-storage-pool/Kotlin/arena-storage-pool.kotlin @@ -0,0 +1,14 @@ +// Kotlin Native v0.3 + +import kotlinx.cinterop.* + +fun main(args: Array) { + memScoped { + val intVar1 = alloc() + intVar1.value = 1 + val intVar2 = alloc() + intVar2.value = 2 + println("${intVar1.value} + ${intVar2.value} = ${intVar1.value + intVar2.value}") + } + // native memory used by intVar1 & intVar2 is automatically freed when memScoped block ends +} diff --git a/Task/Arena-storage-pool/Phix/arena-storage-pool-1.phix b/Task/Arena-storage-pool/Phix/arena-storage-pool-1.phix new file mode 100644 index 0000000000..9afcdbaf6d --- /dev/null +++ b/Task/Arena-storage-pool/Phix/arena-storage-pool-1.phix @@ -0,0 +1 @@ +atom mem = allocate(size,true) diff --git a/Task/Arena-storage-pool/Phix/arena-storage-pool-2.phix b/Task/Arena-storage-pool/Phix/arena-storage-pool-2.phix new file mode 100644 index 0000000000..d08dd826a2 --- /dev/null +++ b/Task/Arena-storage-pool/Phix/arena-storage-pool-2.phix @@ -0,0 +1,12 @@ +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 diff --git a/Task/Arena-storage-pool/Zkl/arena-storage-pool.zkl b/Task/Arena-storage-pool/Zkl/arena-storage-pool.zkl new file mode 100644 index 0000000000..e3b99feeb1 --- /dev/null +++ b/Task/Arena-storage-pool/Zkl/arena-storage-pool.zkl @@ -0,0 +1,3 @@ +var pool=List(); // pool could be any mutable container +pool.append(Data(0,1234)); // allocate mem blob and add to pool +pool=Void; // free the pool and everything in it. diff --git a/Task/Arithmetic-Complex/Clojure/arithmetic-complex-1.clj b/Task/Arithmetic-Complex/Clojure/arithmetic-complex-1.clj deleted file mode 100644 index 0d801ad855..0000000000 --- a/Task/Arithmetic-Complex/Clojure/arithmetic-complex-1.clj +++ /dev/null @@ -1,23 +0,0 @@ -(deftype Complex [real imag] - Object - (toString [this] (str real " " imag "j"))) - -(defn c-add [^Complex a ^Complex b] - (Complex. (+ (.real a) (.real b)) - (+ (.imag a) (.imag b)))) - -(defn c-mul [^Complex a ^Complex b] - (Complex. (- (* (.real a) (.real b)) (* (.imag a) (.imag b))) - (+ (* (.real a) (.imag b)) (* (.imag a) (.real b))))) - -(defn c-neg [^Complex a] - (Complex. (- (.real a)) (- (.imag a)))) - -(defn c-inv [^Complex a] - (let [r (.real a) - i (.imag a) - m (+ (* r r) (* i i))] - (Complex. (/ r m) (- (/ i m))))) - -(defn c-conj [^Complex a] - (Complex. (.real a) (- (.imag a)))) diff --git a/Task/Arithmetic-Complex/Clojure/arithmetic-complex-2.clj b/Task/Arithmetic-Complex/Clojure/arithmetic-complex-2.clj deleted file mode 100644 index 9067f4bde8..0000000000 --- a/Task/Arithmetic-Complex/Clojure/arithmetic-complex-2.clj +++ /dev/null @@ -1,17 +0,0 @@ -(Complex. 1 1) -# - -(c-add (Complex. 3.17 7) (Complex. 1 1.77)) -# - -(c-mul (Complex. 0 1) (Complex. 0 1)) -# - -(c-neg (Complex. 1 2)) -# - -(c-inv (Complex. 1 1)) -# - -(c-conj (Complex. 1 1)) -# diff --git a/Task/Arithmetic-Complex/CoffeeScript/arithmetic-complex-1.coffee b/Task/Arithmetic-Complex/CoffeeScript/arithmetic-complex-1.coffee deleted file mode 100644 index 66c7b3b817..0000000000 --- a/Task/Arithmetic-Complex/CoffeeScript/arithmetic-complex-1.coffee +++ /dev/null @@ -1,60 +0,0 @@ -# create an immutable Complex type -class Complex - constructor: (@r=0, @i=0) -> - @magnitude = @r*@r + @i*@i - - plus: (c2) -> - new Complex( - @r + c2.r, - @i + c2.i - ) - - times: (c2) -> - new Complex( - @r*c2.r - @i*c2.i, - @r*c2.i + @i*c2.r - ) - - negation: -> - new Complex( - -1 * @r, - -1 * @i - ) - - inverse: -> - throw Error "no inverse" if @magnitude is 0 - new Complex( - @r / @magnitude, - -1 * @i / @magnitude - ) - - toString: -> - return "#{@r}" if @i == 0 - return "#{@i}i" if @r == 0 - if @i > 0 - "#{@r} + #{@i}i" - else - "#{@r} - #{-1 * @i}i" - -# test -do -> - a = new Complex(5, 3) - b = new Complex(4, -3) - - sum = a.plus b - console.log "(#{a}) + (#{b}) = #{sum}" - - product = a.times b - console.log "(#{a}) * (#{b}) = #{product}" - - negation = b.negation() - console.log "-1 * (#{b}) = #{negation}" - - diff = a.plus negation - console.log "(#{a}) - (#{b}) = #{diff}" - - inverse = b.inverse() - console.log "1 / (#{b}) = #{inverse}" - - quotient = product.times inverse - console.log "(#{product}) / (#{b}) = #{quotient}" diff --git a/Task/Arithmetic-Complex/CoffeeScript/arithmetic-complex-2.coffee b/Task/Arithmetic-Complex/CoffeeScript/arithmetic-complex-2.coffee deleted file mode 100644 index 513321f60e..0000000000 --- a/Task/Arithmetic-Complex/CoffeeScript/arithmetic-complex-2.coffee +++ /dev/null @@ -1,7 +0,0 @@ -> coffee complex.coffee -(5 + 3i) + (4 - 3i) = 9 -(5 + 3i) * (4 - 3i) = 29 - 3i --1 * (4 - 3i) = -4 + 3i -(5 + 3i) - (4 - 3i) = 1 + 6i -1 / (4 - 3i) = 0.16 + 0.12i -(29 - 3i) / (4 - 3i) = 5 + 3i diff --git a/Task/Arithmetic-Complex/Forth/arithmetic-complex.fth b/Task/Arithmetic-Complex/Forth/arithmetic-complex.fth index b798ef6d83..847ab71f02 100644 --- a/Task/Arithmetic-Complex/Forth/arithmetic-complex.fth +++ b/Task/Arithmetic-Complex/Forth/arithmetic-complex.fth @@ -1,6 +1,5 @@ -include complex.seq - -: ZNEGATE ( r i -- -r -i ) fswap fnegate fswap fnegate ; +S" fsl-util.fs" REQUIRED +S" complex.fs" REQUIRED zvariable x zvariable y @@ -9,5 +8,6 @@ pi 1.2e y z! x z@ y z@ z+ z. x z@ y z@ z* z. +1e 0e zconstant 1+0i 1+0i x z@ z/ z. x z@ znegate z. diff --git a/Task/Arithmetic-Complex/Fortran/arithmetic-complex-2.f b/Task/Arithmetic-Complex/Fortran/arithmetic-complex-2.f index c4dd1a6208..f8a369ecda 100644 --- a/Task/Arithmetic-Complex/Fortran/arithmetic-complex-2.f +++ b/Task/Arithmetic-Complex/Fortran/arithmetic-complex-2.f @@ -12,7 +12,7 @@ program cdemo2 abquot = a / b abpow = a ** b areal = real(a) ! Real part - aimag = imag(a) ! Imaginary part + aimag = imag(a) ! Imaginary part. Function imag(a) is possibly not recognised. Use aimag(a) if so. newc = cmplx(x,y) ! Creating a complex on the fly from two reals intrinsically ! (initializer only works in declarations) newc = x + y*i ! Creating a complex on the fly from two reals arithmetically diff --git a/Task/Arithmetic-Complex/Haskell/arithmetic-complex-1.hs b/Task/Arithmetic-Complex/Haskell/arithmetic-complex-1.hs deleted file mode 100644 index 3bcc29321b..0000000000 --- a/Task/Arithmetic-Complex/Haskell/arithmetic-complex-1.hs +++ /dev/null @@ -1,14 +0,0 @@ -import Data.Complex - -main = do - let a = 1.0 :+ 2.0 -- complex number 1+2i - let b = 4 -- complex number 4+0i - -- 'b' is inferred to be complex because it's used in - -- arithmetic with 'a' below. - putStrLn $ "Add: " ++ show (a + b) - putStrLn $ "Subtract: " ++ show (a - b) - putStrLn $ "Multiply: " ++ show (a * b) - putStrLn $ "Divide: " ++ show (a / b) - putStrLn $ "Negate: " ++ show (-a) - putStrLn $ "Inverse: " ++ show (recip a) - putStrLn $ "Conjugate:" ++ show (conjugate a) diff --git a/Task/Arithmetic-Complex/Haskell/arithmetic-complex-2.hs b/Task/Arithmetic-Complex/Haskell/arithmetic-complex-2.hs deleted file mode 100644 index 5884ede83b..0000000000 --- a/Task/Arithmetic-Complex/Haskell/arithmetic-complex-2.hs +++ /dev/null @@ -1,8 +0,0 @@ -*Main> main -Add: 5.0 :+ 2.0 -Subtract: (-3.0) :+ 2.0 -Multiply: 4.0 :+ 8.0 -Divide: 0.25 :+ 0.5 -Negate: (-1.0) :+ (-2.0) -Inverse: 0.2 :+ (-0.4) -Conjugate:1.0 :+ (-2.0) diff --git a/Task/Arithmetic-Complex/jq/arithmetic-complex-1.jq b/Task/Arithmetic-Complex/Jq/arithmetic-complex-1.jq similarity index 100% rename from Task/Arithmetic-Complex/jq/arithmetic-complex-1.jq rename to Task/Arithmetic-Complex/Jq/arithmetic-complex-1.jq diff --git a/Task/Arithmetic-Complex/jq/arithmetic-complex-2.jq b/Task/Arithmetic-Complex/Jq/arithmetic-complex-2.jq similarity index 100% rename from Task/Arithmetic-Complex/jq/arithmetic-complex-2.jq rename to Task/Arithmetic-Complex/Jq/arithmetic-complex-2.jq diff --git a/Task/Arithmetic-Complex/Kotlin/arithmetic-complex.kotlin b/Task/Arithmetic-Complex/Kotlin/arithmetic-complex.kotlin new file mode 100644 index 0000000000..9f03399819 --- /dev/null +++ b/Task/Arithmetic-Complex/Kotlin/arithmetic-complex.kotlin @@ -0,0 +1,39 @@ +class Complex(private val real: Double, private val imag: Double) { + operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag) + + operator fun times(other: Complex) = Complex( + real * other.real - imag * other.imag, + real * other.imag + imag * other.real + ) + + fun inv(): Complex { + val denom = real * real + imag * imag + return Complex(real / denom, -imag / denom) + } + + operator fun unaryMinus() = Complex(-real, -imag) + + operator fun minus(other: Complex) = this + (-other) + + operator fun div(other: Complex) = this * other.inv() + + fun conj() = Complex(real, -imag) + + override fun toString() = + if (imag >= 0.0) "$real + ${imag}i" + else "$real - ${-imag}i" +} + +fun main(args: Array) { + val x = Complex(1.0, 3.0) + val y = Complex(5.0, 2.0) + println("x = $x") + println("y = $y") + println("x + y = ${x + y}") + println("x - y = ${x - y}") + println("x * y = ${x * y}") + println("x / y = ${x / y}") + println("-x = ${-x}") + println("1 / x = ${x.inv()}") + println("x* = ${x.conj()}") +} diff --git a/Task/Arithmetic-Complex/Nim/arithmetic-complex.nim b/Task/Arithmetic-Complex/Nim/arithmetic-complex.nim index 93a744022b..b80bc61326 100644 --- a/Task/Arithmetic-Complex/Nim/arithmetic-complex.nim +++ b/Task/Arithmetic-Complex/Nim/arithmetic-complex.nim @@ -1,10 +1,10 @@ import complex -var a: TComplex = (1.0,1.0) -var b: TComplex = (3.1415,1.2) +var a: Complex = (1.0,1.0) +var b: Complex = (3.1415,1.2) -echo ("a : " & $a) -echo ("b : " & $b) -echo ("a + b: " & $(a + b)) -echo ("a * b: " & $(a * b)) -echo ("1/a : " & $(1/a)) -echo ("-a : " & $(-a)) +echo("a : " & $a) +echo("b : " & $b) +echo("a + b: " & $(a + b)) +echo("a * b: " & $(a * b)) +echo("1/a : " & $(1/a)) +echo("-a : " & $(-a)) diff --git a/Task/Arithmetic-Complex/Nimrod/arithmetic-complex.nimrod b/Task/Arithmetic-Complex/Nimrod/arithmetic-complex.nimrod deleted file mode 100644 index 93a744022b..0000000000 --- a/Task/Arithmetic-Complex/Nimrod/arithmetic-complex.nimrod +++ /dev/null @@ -1,10 +0,0 @@ -import complex -var a: TComplex = (1.0,1.0) -var b: TComplex = (3.1415,1.2) - -echo ("a : " & $a) -echo ("b : " & $b) -echo ("a + b: " & $(a + b)) -echo ("a * b: " & $(a * b)) -echo ("1/a : " & $(1/a)) -echo ("-a : " & $(-a)) diff --git a/Task/Arithmetic-Complex/Ol/arithmetic-complex.ol b/Task/Arithmetic-Complex/Ol/arithmetic-complex.ol new file mode 100644 index 0000000000..195fe6de74 --- /dev/null +++ b/Task/Arithmetic-Complex/Ol/arithmetic-complex.ol @@ -0,0 +1,23 @@ +(define A 0+1i) +(define B 1+0i) + +(print (+ A B)) +; <== 1+i + +(print (- A B)) +; <== -1+i + +(print (* A B)) +; <== 0+i + +(print (/ A B)) +; <== 0+i + + +(define C 2/7-3i) + +(print "real part of " C " is " (car C)) +; <== real part of 2/7-3i is 2/7 + +(print "imaginary part of " C " is " (cdr C)) +; <== imaginary part of 2/7-3i is -3 diff --git a/Task/Arithmetic-Complex/OoRexx/arithmetic-complex.rexx b/Task/Arithmetic-Complex/OoRexx/arithmetic-complex.rexx new file mode 100644 index 0000000000..5dd47e3268 --- /dev/null +++ b/Task/Arithmetic-Complex/OoRexx/arithmetic-complex.rexx @@ -0,0 +1,137 @@ +c1 = .complex~new(1, 2) +c2 = .complex~new(3, 4) +r = 7 + +say "c1 =" c1 +say "c2 =" c2 +say "r =" r +say "-c1 =" (-c1) +say "c1 + r =" c1 + r +say "c1 + c2 =" c1 + c2 +say "c1 - r =" c1 - r +say "c1 - c2 =" c1 - c2 +say "c1 * r =" c1 * r +say "c1 * c2 =" c1 * c2 +say "inv(c1) =" c1~inv +say "conj(c1) =" c1~conjugate +say "c1 / r =" c1 / r +say "c1 / c2 =" c1 / c2 +say "c1 == c1 =" (c1 == c1) +say "c1 == c2 =" (c1 == c2) + + +::class complex +::method init + expose r i + use strict arg r, i = 0 + +-- complex instances are immutable, so these are +-- read only attributes +::attribute r GET +::attribute i GET + +::method negative + expose r i + return self~class~new(-r, -i) + +::method add + expose r i + use strict arg other + if other~isa(.complex) then + return self~class~new(r + other~r, i + other~i) + else return self~class~new(r + other, i) + +::method subtract + expose r i + use strict arg other + if other~isa(.complex) then + return self~class~new(r - other~r, i - other~i) + else return self~class~new(r - other, i) + +::method times + expose r i + use strict arg other + if other~isa(.complex) then + return self~class~new(r * other~r - i * other~i, r * other~i + i * other~r) + else return self~class~new(r * other, i * other) + +::method inv + expose r i + denom = r * r + i * i + return self~class~new(r/denom,-i/denom) + +::method conjugate + expose r i + return self~class~new(r, -i) + +::method divide + use strict arg other + -- this is easier if everything is a complex number + if \other~isA(.complex) then other = .complex~new(other) + -- division is multiplication with the inversion + return self * other~inv + +::method "==" + expose r i + use strict arg other + + if \other~isa(.complex) 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 + +::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 + return r self~formatnumber(i)"i" + +::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 + return r~hashcode~bitxor(i~hashcode) diff --git a/Task/Arithmetic-Complex/PowerShell/arithmetic-complex-2.psh b/Task/Arithmetic-Complex/PowerShell/arithmetic-complex-2.psh index 99e19293c2..d5779ffa82 100644 --- a/Task/Arithmetic-Complex/PowerShell/arithmetic-complex-2.psh +++ b/Task/Arithmetic-Complex/PowerShell/arithmetic-complex-2.psh @@ -1,5 +1,5 @@ function show([System.Numerics.Complex]$c) { - if(0 -ge $c.Imginary) { + if(0 -le $c.Imaginary) { return "$($c.Real)+$($c.Imaginary)i" } else { return "$($c.Real)$($c.Imaginary)i" diff --git a/Task/Arithmetic-Complex/Sidef/arithmetic-complex.sidef b/Task/Arithmetic-Complex/Sidef/arithmetic-complex.sidef index 830b1d93fe..37494606dc 100644 --- a/Task/Arithmetic-Complex/Sidef/arithmetic-complex.sidef +++ b/Task/Arithmetic-Complex/Sidef/arithmetic-complex.sidef @@ -1,11 +1,11 @@ -var a = 1:1; # Complex(1, 1) -var b = 3.14159:1.25; # Complex(3.14159, 1.25) +var a = 1:1 # Complex(1, 1) +var b = 3.14159:1.25 # Complex(3.14159, 1.25) [ a + b, # addition a * b, # multiplication -a, # negation - 1 / a, # multiplicative inverse - ~a, # complex conjugate + a.inv, # multiplicative inverse + a.conj, # complex conjugate a.abs, # abs a.sqrt, # sqrt b.re, # real diff --git a/Task/Arithmetic-Complex/Smart-BASIC/arithmetic-complex.smart b/Task/Arithmetic-Complex/Smart-BASIC/arithmetic-complex.smart new file mode 100644 index 0000000000..4fe1f76666 --- /dev/null +++ b/Task/Arithmetic-Complex/Smart-BASIC/arithmetic-complex.smart @@ -0,0 +1,17 @@ +' complex numbers are native for "smart BASIC" +A=1+2i +B=3-5i + +' all math operations and functions work with complex numbers +C=A*B +PRINT SQR(-4) + +' example of solving quadratic equation with complex roots +' x^2+2x+5=0 +a=1 ! b=2 ! c=5 +x1=(-b+sqr(b^2-4*a*c))/(2*a) +x2=(-b-sqr(b^2-4*a*c))/(2*a) +print x1,x2 + +' gives output +-1+2i -1-2i diff --git a/Task/Arithmetic-Complex/Stata/arithmetic-complex.stata b/Task/Arithmetic-Complex/Stata/arithmetic-complex.stata new file mode 100644 index 0000000000..1401894889 --- /dev/null +++ b/Task/Arithmetic-Complex/Stata/arithmetic-complex.stata @@ -0,0 +1,42 @@ +mata +C(2,3) +2 + 3i + +a=2+3i +b=1-2*i + + +a+b +-5 + 3i + +a-b +9 + 3i + +a*b +-14 - 21i + +a/b +-.285714286 - .428571429i + +-a +-2 - 3i + +1/a +.153846154 - .230769231i + +conj(a) +2 - 3i + +abs(a) +3.605551275 + +arg(a) +.9827937232 + +exp(a) +-7.31511009 + 1.04274366i + +log(a) +1.28247468 + .982793723i + +end diff --git a/Task/Arithmetic-Complex/Zkl/arithmetic-complex.zkl b/Task/Arithmetic-Complex/Zkl/arithmetic-complex.zkl new file mode 100644 index 0000000000..7480682ca9 --- /dev/null +++ b/Task/Arithmetic-Complex/Zkl/arithmetic-complex.zkl @@ -0,0 +1,8 @@ +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +(GSL.Z(3,4) + GSL.Z(1,2)).println(); // (4.00+6.00i) +(GSL.Z(3,4) - GSL.Z(1,2)).println(); // (2.00+2.00i) +(GSL.Z(3,4) * GSL.Z(1,2)).println(); // (-5.00+10.00i) +(GSL.Z(3,4) / GSL.Z(1,2)).println(); // (2.20-0.40i) +(GSL.Z(1,0) / GSL.Z(1,1)).println(); // (0.50-0.50i) // inversion +(-GSL.Z(3,4)).println(); // (-3.00-4.00i) +GSL.Z(3,4).conjugate().println(); // (3.00-4.00i) diff --git a/Task/Arithmetic-Integer/ALGOL-W/arithmetic-integer.alg b/Task/Arithmetic-Integer/ALGOL-W/arithmetic-integer.alg new file mode 100644 index 0000000000..35fcba70f9 --- /dev/null +++ b/Task/Arithmetic-Integer/ALGOL-W/arithmetic-integer.alg @@ -0,0 +1,14 @@ +begin + integer a, b; + write( "Enter 2 integers> " ); + read( a, b ); + write( "a + b: ", a + b ); % addition % + write( "a - b: ", a - b ); % subtraction % + write( "a * b: ", a * b ); % multiplication % + write( "a / b: ", a div b ); % integer division % + write( "a mod b: ", a rem b ); % modulo % + % the ** operator returns a real result even with integer operands % + % ( the right-hand operand must always be an integer, the left-hand % + % operand can be integer, real or complex ) % + write( "a ^ b: ", round( a ** b ) ) +end. diff --git a/Task/Arithmetic-Integer/BASIC/arithmetic-integer.basic b/Task/Arithmetic-Integer/BASIC/arithmetic-integer-1.basic similarity index 100% rename from Task/Arithmetic-Integer/BASIC/arithmetic-integer.basic rename to Task/Arithmetic-Integer/BASIC/arithmetic-integer-1.basic diff --git a/Task/Arithmetic-Integer/BASIC/arithmetic-integer-2.basic b/Task/Arithmetic-Integer/BASIC/arithmetic-integer-2.basic new file mode 100644 index 0000000000..b0a0961053 --- /dev/null +++ b/Task/Arithmetic-Integer/BASIC/arithmetic-integer-2.basic @@ -0,0 +1,12 @@ +' Arthimetic/Integer +DECLARE a%, b% +INPUT "Enter integer A: ", a% +INPUT "Enter integer B: ", b% +PRINT + +PRINT a%, " + ", b%, " is ", a% + b% +PRINT a%, " - ", b%, " is ", a% - b% +PRINT a%, " * ", b%, " is ", a% * b% +PRINT a%, " / ", b%, " is ", a% / b%, ", trucation toward zero" +PRINT "MOD(", a%, ", ", b%, ") is ", MOD(a%, b%), ", same sign as first operand" +PRINT "POW(", a%, ", ", b%, ") is ", INT(POW(a%, b%)) diff --git a/Task/Arithmetic-Integer/BASIC/arithmetic-integer-3.basic b/Task/Arithmetic-Integer/BASIC/arithmetic-integer-3.basic new file mode 100644 index 0000000000..74082cec7d --- /dev/null +++ b/Task/Arithmetic-Integer/BASIC/arithmetic-integer-3.basic @@ -0,0 +1,8 @@ +10 INPUT "ENTER A NUMBER"; A% +20 INPUT "ENTER ANOTHER NUMBER"; B% +30 PRINT "ADDITION:";A%;"+";B%;"=";A%+B% +40 PRINT "SUBTRACTION:";A%;"-";B%;"=";A%-B% +50 PRINT "MULTIPLICATION:";A%;"*";B%;"=";A%*B% +60 PRINT "INTEGER DIVISION:";A%;"/";B%;"=";INT(A%/B%) +70 PRINT "REMAINDER OR MODULO:";A%;"%";B%;"=";A%-INT(A%/B%)*B% +80 PRINT "POWER:";A%;"^";B%;"=";A%^B% diff --git a/Task/Arithmetic-Integer/BASIC/arithmetic-integer-4.basic b/Task/Arithmetic-Integer/BASIC/arithmetic-integer-4.basic new file mode 100644 index 0000000000..be8375f3cb --- /dev/null +++ b/Task/Arithmetic-Integer/BASIC/arithmetic-integer-4.basic @@ -0,0 +1,15 @@ +! RosettaCode: Integer Arithmetic +! True BASIC v6.007 +! Translated from BaCon example. +PROGRAM Integer_Arithmetic + INPUT PROMPT "Enter integer A: ": a + INPUT PROMPT "Enter integer B: ": b + PRINT + PRINT a;" + ";b;" is ";a+b + PRINT a;" - ";b;" is ";a-b + PRINT a;" * ";b;" is ";a*b + PRINT a;" / ";b;" is ";INT(a/b); + PRINT "MOD(";a;", ";b;") is "; MOD(a,b) + PRINT "POW(";a;", ";b;") is ";INT(a^b) + GET KEY done +END diff --git a/Task/Arithmetic-Integer/Bc/arithmetic-integer.bc b/Task/Arithmetic-Integer/Bc/arithmetic-integer.bc new file mode 100644 index 0000000000..474303d087 --- /dev/null +++ b/Task/Arithmetic-Integer/Bc/arithmetic-integer.bc @@ -0,0 +1,8 @@ +define f(a, b) { + "add: "; a + b + "sub: "; a - b + "mul: "; a * b + "div: "; a / b /* truncates toward zero */ + "mod: "; a % b /* same sign as first operand */ + "pow: "; a ^ b +} diff --git a/Task/Arithmetic-Integer/D/arithmetic-integer-2.d b/Task/Arithmetic-Integer/D/arithmetic-integer-2.d index a2615445c4..ae8f9ea691 100644 --- a/Task/Arithmetic-Integer/D/arithmetic-integer-2.d +++ b/Task/Arithmetic-Integer/D/arithmetic-integer-2.d @@ -1,4 +1,4 @@ -import std.stdio, std.string, std.conv, std.typetuple; +import std.stdio, std.string, std.conv, std.meta; void main() { int a = -16, b = 5; @@ -8,6 +8,6 @@ void main() { } catch (StdioException e) {} writeln("a = ", a, ", b = ", b); - foreach (op; TypeTuple!("+", "-", "*", "/", "%", "^^")) + foreach (op; AliasSeq!("+", "-", "*", "/", "%", "^^")) mixin(`writeln("a ` ~ op ~ ` b = ", a` ~ op ~ `b);`); } diff --git a/Task/Arithmetic-Integer/Dc/arithmetic-integer.dc b/Task/Arithmetic-Integer/Dc/arithmetic-integer.dc new file mode 100644 index 0000000000..bcb1bf3edb --- /dev/null +++ b/Task/Arithmetic-Integer/Dc/arithmetic-integer.dc @@ -0,0 +1,10 @@ +[Enter 2 integers on 1 line. + Use whitespace to separate. Example: 2 3 + Use underscore for negative integers. Example: _10 +]P ? sb sa +[add: ]P la lb + p sz +[sub: ]P la lb - p sz +[mul: ]P la lb * p sz +[div: ]P la lb / p sz [truncates toward zero]sz +[mod: ]P la lb % p sz [sign matches first operand]sz +[pow: ]P la lb ^ p sz diff --git a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena index 2212245642..c0f0fa3bb4 100644 --- a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena +++ b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena @@ -1,17 +1,14 @@ -#define system. -#define system'math. -#define extensions. +import system'math. +import extensions. -// --- Program --- - -#symbol program = +program = [ - #var a := console readLine:(Integer new). - #var b := console readLine:(Integer new). + var a := console readLineTo(Integer new). + var b := console readLineTo(Integer new). - console writeLine:a:" + ": b:" = ":(a + b). - console writeLine:a:" - ": b:" = ":(a - b). - console writeLine:a:" * ": b:" = ":(a * b). - console writeLine:a:" / ": b:" = ":(a / b). // truncates towards 0 - console writeLine:a:" % ":b:" = ":(a mod:b). // matches sign of first operand + console printLine(a," + ",b," = ",a + b). + console printLine(a," - ",b," = ",a - b). + console printLine(a," * ",b," = ",a * b). + console printLine(a," / ",b," = ",a / b). // truncates towards 0 + console printLine(a," % ",b," = ",a mod:b). // matches sign of first operand ]. diff --git a/Task/Arithmetic-Integer/Elixir/arithmetic-integer.elixir b/Task/Arithmetic-Integer/Elixir/arithmetic-integer.elixir index 3b402c361b..a3c1fb7855 100644 --- a/Task/Arithmetic-Integer/Elixir/arithmetic-integer.elixir +++ b/Task/Arithmetic-Integer/Elixir/arithmetic-integer.elixir @@ -1,15 +1,25 @@ -# Function to remove line breaks and convert string to int -get_int = fn msg -> IO.gets(msg) |> String.strip |> String.to_integer end +defmodule Arithmetic_Integer do + # Function to remove line breaks and convert string to int + defp get_int(msg) do + IO.gets(msg) |> String.strip |> String.to_integer + end -# Get user input -a = get_int.("Enter your first integer: ") -b = get_int.("Enter your second integer: ") + def task do + # Get user input + a = get_int("Enter your first integer: ") + b = get_int("Enter your second integer: ") -IO.puts "Elixir Integer Arithmetic:\n" -IO.puts "Sum: #{a + b}" -IO.puts "Difference: #{a - b}" -IO.puts "Product: #{a * b}" -IO.puts "True Division: #{a / b}" # Float -IO.puts "Division: #{div(a,b)}" # Truncated Towards 0 -IO.puts "Remainder: #{rem(a,b)}" # Sign from first digit -IO.puts "Exponent: #{:math.pow(a,b)}" # Float, using Erlang's :math + IO.puts "Elixir Integer Arithmetic:\n" + IO.puts "Sum: #{a + b}" + IO.puts "Difference: #{a - b}" + IO.puts "Product: #{a * b}" + IO.puts "True Division: #{a / b}" # Float + IO.puts "Division: #{div(a,b)}" # Truncated Towards 0 + IO.puts "Floor Division: #{Integer.floor_div(a,b)}" # floored integer division + IO.puts "Remainder: #{rem(a,b)}" # Sign from first digit + IO.puts "Modulo: #{Integer.mod(a,b)}" # modulo remainder (uses floored division) + IO.puts "Exponent: #{:math.pow(a,b)}" # Float, using Erlang's :math + end +end + +Arithmetic_Integer.task diff --git a/Task/Arithmetic-Integer/Factor/arithmetic-integer-1.factor b/Task/Arithmetic-Integer/Factor/arithmetic-integer-1.factor deleted file mode 100644 index b8f74e2c70..0000000000 --- a/Task/Arithmetic-Integer/Factor/arithmetic-integer-1.factor +++ /dev/null @@ -1,17 +0,0 @@ -USING: combinators io kernel math math.functions math.order -math.parser prettyprint ; - -"a=" "b=" [ write readln string>number ] bi@ -{ - [ + "sum: " write . ] - [ - "difference: " write . ] - [ * "product: " write . ] - [ / "quotient: " write . ] - [ /i "integer quotient: " write . ] - [ rem "remainder: " write . ] - [ mod "modulo: " write . ] - [ max "maximum: " write . ] - [ min "minimum: " write . ] - [ gcd "gcd: " write . drop ] - [ lcm "lcm: " write . ] -} 2cleave diff --git a/Task/Arithmetic-Integer/Factor/arithmetic-integer-2.factor b/Task/Arithmetic-Integer/Factor/arithmetic-integer-2.factor deleted file mode 100644 index 8cd761db5c..0000000000 --- a/Task/Arithmetic-Integer/Factor/arithmetic-integer-2.factor +++ /dev/null @@ -1,13 +0,0 @@ -a=8 -b=12 -sum: 20 -difference: -4 -product: 96 -quotient: 2/3 -integer quotient: 0 -remainder: 8 -modulo: 8 -maximum: 12 -minimum: 8 -gcd: 4 -lcm: 24 diff --git a/Task/Arithmetic-Integer/Friendly-interactive-shell/arithmetic-integer.fish b/Task/Arithmetic-Integer/Friendly-interactive-shell/arithmetic-integer.fish new file mode 100644 index 0000000000..354628d591 --- /dev/null +++ b/Task/Arithmetic-Integer/Friendly-interactive-shell/arithmetic-integer.fish @@ -0,0 +1,8 @@ +read a +read b +echo 'a + b =' (math "$a + $b") # Sum +echo 'a - b =' (math "$a - $b") # Difference +echo 'a * b =' (math "$a * $b") # Product +echo 'a / b =' (math "$a / $b") # Integer quotient +echo 'a % b =' (math "$a % $b") # Remainder +echo 'a ^ b =' (math "$a ^ $b") # Exponentation diff --git a/Task/Arithmetic-Integer/Java/arithmetic-integer.java b/Task/Arithmetic-Integer/Java/arithmetic-integer.java index 5be83bda97..9ecb561113 100644 --- a/Task/Arithmetic-Integer/Java/arithmetic-integer.java +++ b/Task/Arithmetic-Integer/Java/arithmetic-integer.java @@ -1,15 +1,16 @@ import java.util.Scanner; -public class Int{ - public static void main(String[] args){ - Scanner sc = new Scanner(System.in); - int a = sc.nextInt(); - int b = sc.nextInt(); - int sum = a + b;//integer addition is discouraged in print statements due to confusion with String concatenation - System.out.println("a + b = " + sum); - System.out.println("a - b = " + (a - b)); - System.out.println("a * b = " + (a * b)); - System.out.println("quotient of a / b = " + (a / b)); // truncates towards 0 - System.out.println("remainder of a / b = " + (a % b)); // same sign as first operand - } +public class IntegerArithmetic { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int a = sc.nextInt(); + int b = sc.nextInt(); + + int sum = a + b; // integer addition is discouraged in print statements due to confusion with string concatenation + System.out.println("a + b = " + sum); + System.out.println("a - b = " + (a - b)); + System.out.println("a * b = " + (a * b)); + System.out.println("quotient of a / b = " + (a / b)); // truncates towards 0 + System.out.println("remainder of a / b = " + (a % b)); // same sign as first operand + } } diff --git a/Task/Arithmetic-Integer/jq/arithmetic-integer.jq b/Task/Arithmetic-Integer/Jq/arithmetic-integer.jq similarity index 100% rename from Task/Arithmetic-Integer/jq/arithmetic-integer.jq rename to Task/Arithmetic-Integer/Jq/arithmetic-integer.jq diff --git a/Task/Arithmetic-Integer/Julia/arithmetic-integer.julia b/Task/Arithmetic-Integer/Julia/arithmetic-integer.julia index bd12750a36..f943ea5788 100644 --- a/Task/Arithmetic-Integer/Julia/arithmetic-integer.julia +++ b/Task/Arithmetic-Integer/Julia/arithmetic-integer.julia @@ -1,4 +1,4 @@ -function arithmetic (a = int(readline()), b = int(readline())) +function arithmetic (a = parse(Int, readline()), b = parse(Int, readline())) for op in [+,-,*,div,rem] println("a $op b = $(op(a,b))") end diff --git a/Task/Arithmetic-Integer/Kotlin/arithmetic-integer.kotlin b/Task/Arithmetic-Integer/Kotlin/arithmetic-integer.kotlin new file mode 100644 index 0000000000..0b314d57d7 --- /dev/null +++ b/Task/Arithmetic-Integer/Kotlin/arithmetic-integer.kotlin @@ -0,0 +1,41 @@ +// version 1.1 + +fun main(args: Array) { + val r = Regex("""-?\d+[ ]+-?\d+""") + while(true) { + print("Enter two integers separated by space(s) or q to quit: ") + val input: String = readLine()!!.trim() + if (input == "q" || input == "Q") break + if (!input.matches(r)) { + println("Invalid input, try again") + continue + } + val index = input.lastIndexOf(' ') + val a = input.substring(0, index).trimEnd().toLong() + val b = input.substring(index + 1).toLong() + println("$a + $b = ${a + b}") + println("$a - $b = ${a - b}") + println("$a * $b = ${a * b}") + if (b != 0L) { + println("$a / $b = ${a / b}") // rounds towards zero + println("$a % $b = ${a % b}") // if non-zero, matches sign of first operand + } + else { + println("$a / $b = undefined") + println("$a % $b = undefined") + } + val d = Math.pow(a.toDouble(), b.toDouble()) + print("$a ^ $b = ") + if (d % 1.0 == 0.0) { + if (d >= Long.MIN_VALUE.toDouble() && d <= Long.MAX_VALUE.toDouble()) + println("${d.toLong()}") + else + println("out of range") + } + else if (!d.isFinite()) + println("not finite") + else + println("not integral") + println() + } +} diff --git a/Task/Arithmetic-Integer/Nim/arithmetic-integer.nim b/Task/Arithmetic-Integer/Nim/arithmetic-integer.nim index 43a6b90847..7fbbd935c5 100644 --- a/Task/Arithmetic-Integer/Nim/arithmetic-integer.nim +++ b/Task/Arithmetic-Integer/Nim/arithmetic-integer.nim @@ -1,7 +1,7 @@ -import parseopt,strutils +import parseopt, strutils var - opt: TOptParser = initOptParser() + opt: OptParser = initOptParser() str = opt.cmdLineRest.split a: int = 0 b: int = 0 @@ -9,14 +9,14 @@ var try: a = parseInt(str[0]) b = parseInt(str[1]) -except EinvalidValue: +except ValueError: quit("Invalid params. Two integers are expected.") -echo ("a : " & $a) -echo ("b : " & $b) -echo ("a + b : " & $(a+b)) -echo ("a - b : " & $(a-b)) -echo ("a * b : " & $(a*b)) -echo ("a div b: " & $(a div b)) -echo ("a mod b: " & $(a mod b)) +echo("a : " & $a) +echo("b : " & $b) +echo("a + b : " & $(a+b)) +echo("a - b : " & $(a-b)) +echo("a * b : " & $(a*b)) +echo("a div b: " & $(a div b)) +echo("a mod b: " & $(a mod b)) diff --git a/Task/Arithmetic-Integer/Nimrod/arithmetic-integer.nimrod b/Task/Arithmetic-Integer/Nimrod/arithmetic-integer.nimrod deleted file mode 100644 index 43a6b90847..0000000000 --- a/Task/Arithmetic-Integer/Nimrod/arithmetic-integer.nimrod +++ /dev/null @@ -1,22 +0,0 @@ -import parseopt,strutils - -var - opt: TOptParser = initOptParser() - str = opt.cmdLineRest.split - a: int = 0 - b: int = 0 - -try: - a = parseInt(str[0]) - b = parseInt(str[1]) -except EinvalidValue: - quit("Invalid params. Two integers are expected.") - - -echo ("a : " & $a) -echo ("b : " & $b) -echo ("a + b : " & $(a+b)) -echo ("a - b : " & $(a-b)) -echo ("a * b : " & $(a*b)) -echo ("a div b: " & $(a div b)) -echo ("a mod b: " & $(a mod b)) diff --git a/Task/Arithmetic-Integer/Ol/arithmetic-integer-1.ol b/Task/Arithmetic-Integer/Ol/arithmetic-integer-1.ol new file mode 100644 index 0000000000..2a01a1edcd --- /dev/null +++ b/Task/Arithmetic-Integer/Ol/arithmetic-integer-1.ol @@ -0,0 +1,14 @@ +(define a 8) +(define b 12) + +(print "(+ " a " " b ") => " (+ a b)) +(print "(- " a " " b ") => " (- a b)) +(print "(* " a " " b ") => " (* a b)) +(print "(/ " a " " b ") => " (/ a b)) + +(print "(quotient " a " " b ") => " (quot a b)) ; same as (quotient a b) +(print "(remainder " a " " b ") => " (rem a b)) ; same as (remainder a b) +(print "(modulo " a " " b ") => " (mod a b)) ; same as (modulo a b) + +(import (owl math-extra)) +(print "(expt " a " " b ") => " (expt a b)) diff --git a/Task/Arithmetic-Integer/Ol/arithmetic-integer-2.ol b/Task/Arithmetic-Integer/Ol/arithmetic-integer-2.ol new file mode 100644 index 0000000000..f84700bf6a --- /dev/null +++ b/Task/Arithmetic-Integer/Ol/arithmetic-integer-2.ol @@ -0,0 +1,5 @@ +; you can use more than two arguments for +,-,*,/ functions +(print (+ 1 3 5 7 9)) ; ==> 25 +(print (- 1 3 5 7 9)) ; ==> -23 +(print (* 1 3 5 7 9)) ; ==> 945 - same as (1*3*5*7*9) +(print (/ 1 3 5 7 9)) ; ==> 1/945 - same as (((1/3)/5)/7)/9 diff --git a/Task/Arithmetic-Integer/SQL/arithmetic-integer.sql b/Task/Arithmetic-Integer/SQL/arithmetic-integer.sql new file mode 100644 index 0000000000..3329db385e --- /dev/null +++ b/Task/Arithmetic-Integer/SQL/arithmetic-integer.sql @@ -0,0 +1,20 @@ +-- test.sql +-- Tested in SQL*plus + +drop table test; + +create table test (a integer, b integer); + +insert into test values ('&&A','&&B'); + +commit; + +select a-b difference from test; + +select a*b product from test; + +select trunc(a/b) integer_quotient from test; + +select mod(a,b) remainder from test; + +select power(a,b) exponentiation from test; diff --git a/Task/Arithmetic-Integer/Smart-BASIC/arithmetic-integer.smart b/Task/Arithmetic-Integer/Smart-BASIC/arithmetic-integer.smart new file mode 100644 index 0000000000..c63583d14b --- /dev/null +++ b/Task/Arithmetic-Integer/Smart-BASIC/arithmetic-integer.smart @@ -0,0 +1,12 @@ +INPUT "Enter first number.":first +INPUT "Enter second number.":second +PRINT "The sum of";first;"and";second;"is ";first+second&"." +PRINT "The difference between";first;"and";second;"is ";ABS(first-second)&"." +PRINT "The product of";first;"and";second;"is ";first*second&"." +IF second THEN + PRINT "The integer quotient of";first;"and";second;"is ";INTEG(first/second)&"." +ELSE + PRINT "Division by zero not cool." +ENDIF +PRINT "The remainder being...";first%second&"." +PRINT STR$(first);"raised to the power of";second;"is ";first^second&"." diff --git a/Task/Arithmetic-Integer/Swift/arithmetic-integer.swift b/Task/Arithmetic-Integer/Swift/arithmetic-integer.swift new file mode 100644 index 0000000000..67dd7b89ce --- /dev/null +++ b/Task/Arithmetic-Integer/Swift/arithmetic-integer.swift @@ -0,0 +1,9 @@ +let a = 6 +let b = 4 + +print("sum =\(a+b)") +print("difference = \(a-b)") +print("product = \(a*b)") +print("Integer quotient = \(a/b)") +print("Remainder = (a%b)") +print("No operator for Exponential") diff --git a/Task/Arithmetic-Integer/X86-Assembly/arithmetic-integer.x86 b/Task/Arithmetic-Integer/X86-Assembly/arithmetic-integer.x86 new file mode 100644 index 0000000000..5b869c9609 --- /dev/null +++ b/Task/Arithmetic-Integer/X86-Assembly/arithmetic-integer.x86 @@ -0,0 +1,22 @@ +arithm: mov cx, a + mov bx, b + xor dx, dx + + mov ax, cx + add ax, bx + mov sum, ax + + mov ax, cx + imul bx + mov product, ax + + mov ax, cx + sub ax, bx + mov difference, ax + + mov ax, cx + idiv bx + mov quotient, ax + mov remainder, dx + + ret diff --git a/Task/Arithmetic-Integer/Zkl/arithmetic-integer.zkl b/Task/Arithmetic-Integer/Zkl/arithmetic-integer.zkl new file mode 100644 index 0000000000..339b894b2a --- /dev/null +++ b/Task/Arithmetic-Integer/Zkl/arithmetic-integer.zkl @@ -0,0 +1,7 @@ +x,y:=ask("Two ints: ").split(" ").apply("toInt"); +println("x+y = ",x + y); +println("x-y = ",x - y); +println("x*y = ",x * y); +println("x/y = ",x / y); // rounds toward zero +println("x%y = ",x % y); // remainder; matches sign of first operand when operands' signs differ +println("x.divr(y) = ",x.divr(y)); // (x/y,remainder); sign as above diff --git a/Task/Arithmetic-Rational/Java/arithmetic-rational.java b/Task/Arithmetic-Rational/Java/arithmetic-rational.java index 20d96a68a8..bf1e7b0cad 100644 --- a/Task/Arithmetic-Rational/Java/arithmetic-rational.java +++ b/Task/Arithmetic-Rational/Java/arithmetic-rational.java @@ -1,30 +1,27 @@ -class BigRationalFindPerfectNumbers { - public static void main(String[] args) { - System.out.println("Running BigRational built-in tests"); - if (BigRational.testFeatures()) { - int MAX_NUM = (1 << 19); - System.out.println(); - System.out.println("Searching for perfect numbers in the range [1, " + (MAX_NUM - 1) + "]"); - BigRational TWO = BigRational.valueOf(2); - for (int i = 1; i < MAX_NUM; i++) { - BigRational reciprocalSum = BigRational.ONE; - if (i > 1) - reciprocalSum = reciprocalSum.add(BigRational.valueOf(i).reciprocal()); - int maxDivisor = (int)Math.sqrt(i); - if (maxDivisor >= i) - maxDivisor--; - for (int divisor = 2; divisor <= maxDivisor; divisor++) { - if ((i % divisor) == 0) { - reciprocalSum = reciprocalSum.add(BigRational.valueOf(divisor).reciprocal()); - int dividend = i / divisor; - if (divisor != dividend) - reciprocalSum = reciprocalSum.add(BigRational.valueOf(dividend).reciprocal()); - } +public class BigRationalFindPerfectNumbers { + public static void main(String[] args) { + int MAX_NUM = 1 << 19; + System.out.println("Searching for perfect numbers in the range [1, " + (MAX_NUM - 1) + "]"); + + BigRational TWO = BigRational.valueOf(2); + for (int i = 1; i < MAX_NUM; i++) { + BigRational reciprocalSum = BigRational.ONE; + if (i > 1) + reciprocalSum = reciprocalSum.add(BigRational.valueOf(i).reciprocal()); + int maxDivisor = (int) Math.sqrt(i); + if (maxDivisor >= i) + maxDivisor--; + + for (int divisor = 2; divisor <= maxDivisor; divisor++) { + if (i % divisor == 0) { + reciprocalSum = reciprocalSum.add(BigRational.valueOf(divisor).reciprocal()); + int dividend = i / divisor; + if (divisor != dividend) + reciprocalSum = reciprocalSum.add(BigRational.valueOf(dividend).reciprocal()); + } + } + if (reciprocalSum.equals(TWO)) + System.out.println(String.valueOf(i) + " is a perfect number"); } - if (reciprocalSum.equals(TWO)) - System.out.println(String.valueOf(i) + " is a perfect number"); - } } - return; - } } diff --git a/Task/Arithmetic-Rational/Kotlin/arithmetic-rational.kotlin b/Task/Arithmetic-Rational/Kotlin/arithmetic-rational.kotlin new file mode 100644 index 0000000000..a017b2d8a2 --- /dev/null +++ b/Task/Arithmetic-Rational/Kotlin/arithmetic-rational.kotlin @@ -0,0 +1,127 @@ +// version 1.1.2 + +fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b) + +infix fun Long.ldiv(denom: Long) = Frac(this, denom) + +infix fun Int.idiv(denom: Int) = Frac(this.toLong(), denom.toLong()) + +fun Long.toFrac() = Frac(this, 1) + +fun Int.toFrac() = Frac(this.toLong(), 1) + +class Frac : Comparable { + val num: Long + val denom: Long + + companion object { + val ZERO = Frac(0, 1) + val ONE = Frac(1, 1) + } + + constructor(n: Long, d: Long) { + require(d != 0L) + var nn = n + var dd = d + if (nn == 0L) { + dd = 1 + } + else if (dd < 0) { + nn = -nn + dd = -dd + } + val g = Math.abs(gcd(nn, dd)) + if (g > 1) { + nn /= g + dd /= g + } + num = nn + denom = dd + } + + constructor(n: Int, d: Int) : this(n.toLong(), d.toLong()) + + operator fun plus(other: Frac) = + Frac(num * other.denom + denom * other.num, other.denom * denom) + + operator fun unaryPlus() = this + + operator fun unaryMinus() = Frac(-num, denom) + + operator fun minus(other: Frac) = this + (-other) + + operator fun times(other: Frac) = Frac(this.num * other.num, this.denom * other.denom) + + operator fun rem(other: Frac) = this - Frac((this / other).toLong(), 1) * other + + operator fun inc() = this + ONE + operator fun dec() = this - ONE + + fun inverse(): Frac { + require(num != 0L) + return Frac(denom, num) + } + + operator fun div(other: Frac) = this * other.inverse() + + fun abs() = if (num >= 0) this else -this + + override fun compareTo(other: Frac): Int { + val diff = this.toDouble() - other.toDouble() + return when { + diff < 0.0 -> -1 + diff > 0.0 -> +1 + else -> 0 + } + } + + override fun equals(other: Any?): Boolean { + if (other == null || other !is Frac) return false + return this.compareTo(other) == 0 + } + + override fun hashCode() = num.hashCode() xor denom.hashCode() + + override fun toString() = if (denom == 1L) "$num" else "$num/$denom" + + fun toDouble() = num.toDouble() / denom + + fun toLong() = num / denom +} + +fun isPerfect(n: Long): Boolean { + var sum = Frac(1, n) + val limit = Math.sqrt(n.toDouble()).toLong() + for (i in 2L..limit) { + if (n % i == 0L) sum += Frac(1, i) + Frac(1, n / i) + } + return sum == Frac.ONE +} + +fun main(args: Array) { + var frac1 = Frac(12, 3) + println ("frac1 = $frac1") + var frac2 = 15 idiv 2 + println("frac2 = $frac2") + println("frac1 <= frac2 is ${frac1 <= frac2}") + println("frac1 >= frac2 is ${frac1 >= frac2}") + println("frac1 == frac2 is ${frac1 == frac2}") + println("frac1 != frac2 is ${frac1 != frac2}") + println("frac1 + frac2 = ${frac1 + frac2}") + println("frac1 - frac2 = ${frac1 - frac2}") + println("frac1 * frac2 = ${frac1 * frac2}") + println("frac1 / frac2 = ${frac1 / frac2}") + println("frac1 % frac2 = ${frac1 % frac2}") + println("inv(frac1) = ${frac1.inverse()}") + println("abs(-frac1) = ${-frac1.abs()}") + println("inc(frac2) = ${++frac2}") + println("dec(frac2) = ${--frac2}") + println("dbl(frac2) = ${frac2.toDouble()}") + println("lng(frac2) = ${frac2.toLong()}") + println("\nThe Perfect numbers less than 2^19 are:") + // We can skip odd numbers as no known perfect numbers are odd + for (i in 2 until (1 shl 19) step 2) { + if (isPerfect(i.toLong())) print(" $i") + } + println() +} diff --git a/Task/Arithmetic-Rational/OoRexx/arithmetic-rational.rexx b/Task/Arithmetic-Rational/OoRexx/arithmetic-rational.rexx new file mode 100644 index 0000000000..a270c067f4 --- /dev/null +++ b/Task/Arithmetic-Rational/OoRexx/arithmetic-rational.rexx @@ -0,0 +1,163 @@ +loop candidate = 6 to 2**19 + sum = .fraction~new(1, candidate) + max2 = rxcalcsqrt(candidate)~trunc + + loop factor = 2 to max2 + if candidate // factor == 0 then do + sum += .fraction~new(1, factor) + sum += .fraction~new(1, candidate / factor) + end + end + if sum == 1 then say candidate "is a perfect number" +end + +::class fraction inherit orderable +::method init + expose numerator denominator + use strict arg numerator, denominator = 1 + + if denominator == 0 then raise syntax 98.900 array("Fraction denominator cannot be zero") + + -- if the denominator is negative, make the numerator carry the sign + if denominator < 0 then do + numerator = -numerator + denominator = - denominator + end + + + -- find the greatest common denominator and reduce to + -- the simplest form + gcd = self~gcd(numerator~abs, denominator~abs) + + numerator /= gcd + denominator /= gcd + +-- fraction instances are immutable, so these are +-- read only attributes +::attribute numerator GET +::attribute denominator GET + +-- calculate the greatest common denominator of a numerator/denominator pair +::method gcd private + use arg x, y + + loop while y \= 0 + -- check if they divide evenly + temp = x // y + x = y + y = temp + end + return x + +-- calculate the least common multiple of a numerator/denominator pair +::method lcm private + use arg x, y + return x / self~gcd(x, y) * y + +::method abs + expose numerator denominator + -- the denominator is always forced to be positive + return self~class~new(numerator~abs, denominator) + +::method reciprocal + expose numerator denominator + return self~class~new(denominator, numerator) + +-- convert a fraction to regular Rexx number +::method toNumber + expose numerator denominator + + if numerator == 0 then return 0 + return numerator/denominator + +::method negative + expose numerator denominator + return self~class~new(-numerator, denominator) + +::method add + expose numerator denominator + use strict arg other + -- convert to a fraction if a regular number + if \other~isa(.fraction) then other = self~class~new(other, 1) + + multiple = self~lcm(denominator, other~denominator) + newa = numerator * multiple / denominator + newb = other~numerator * multiple / other~denominator + return self~class~new(newa + newb, multiple) + +::method subtract + use strict arg other + return self + (-other) + +::method times + expose numerator denominator + use strict arg other + -- convert to a fraction if a regular number + if \other~isa(.fraction) then other = self~class~new(other, 1) + return self~class~new(numerator * other~numerator, denominator * other~denominator) + +::method divide + use strict arg other + -- convert to a fraction if a regular number + if \other~isa(.fraction) then other = self~class~new(other, 1) + -- and multiply by the reciprocal + return self * other~reciprocal + +-- compareTo method used by the orderable interface to implement +-- the operator methods +::method compareTo + expose numerator denominator + -- convert to a fraction if a regular number + if \other~isa(.fraction) then other = self~class~new(other, 1) + + return (numerator * other~denominator - denominator * other~numerator)~sign + +-- we still override "==" and "\==" because we want to bypass the +-- checks for not being an instance of the class +::method "==" + expose numerator denominator + use strict arg other + + -- convert to a fraction if a regular number + if \other~isa(.fraction) then other = self~class~new(other, 1) + -- Note: these are numeric comparisons, so we're using the "=" + -- method so those are handled correctly + return numerator = other~numerator & denominator = other~denominator + +::method "\==" + use strict arg other + return \self~"\=="(other) + +-- 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 imutable + else + forward message("ADD") + +::method string + expose numerator denominator + if denominator == 1 then return numerator + return numerator"/"denominator + +-- override hashcode for collection class hash uses +::method hashCode + expose numerator denominator + return numerator~hashcode~bitxor(numerator~hashcode) + +::requires rxmath library diff --git a/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx b/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx index 8fa2ac7b0e..4d17ceb166 100644 --- a/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx +++ b/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx @@ -1,92 +1,87 @@ -/*REXX pgm implements a reasonably complete rational arithmetic (fract.)*/ -L=length(2**19-1) /*saves time by checking even #s.*/ - do j=2 to 2**19-1 by 2 /*ignore unity (can't be perfect)*/ - $=divisors(j); s=0; @= /*get divisors, zero sum, null @.*/ - do k=2 to words($) /*ignore unity.*/ - r='1/'word($,k); @=@ r; s=fractFun(r,,s) - end /*k*/ - if s\==1 then iterate - say 'perfect number:' right(j,L) ' fractions:' @ +/*REXX program implements a reasonably complete rational arithmetic (using fractions).*/ +L=length(2**19 - 1) /*saves time by checking even numbers. */ + do j=2 by 2 to 2**19 - 1; s=0 /*ignore unity (which can't be perfect)*/ + mostDivs=eDivs(j); @= /*obtain divisors>1; zero sum; null @. */ + do k=1 for words(mostDivs) /*unity isn't return from eDivs here.*/ + r='1/'word(mostDivs, k); @=@ r; s=$fun(r, , s) + end /*k*/ + if s\==1 then iterate /*Is sum not equal to unity? Skip it.*/ + say 'perfect number:' right(j, L) " fractions:" @ end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────FRACTDIV subroutine─────────────────*/ -fractDiv: procedure; parse arg x; x=space(x,0); f='FractDiv' -parse var x n '/' d; d=p(d 1) -if d=0 then call err 'division by zero:' x -if \isNum(n) then call err 'a not numeric numerator:' x -if \isNum(d) then call err 'a not numeric denominator:' x -return n/d -/*──────────────────────────────────FRACTFUN subroutine─────────────────*/ -fractFun: procedure; parse arg z.1,,z.2 1 zz.2,f; arg ,op; op=p(op '+') -f='FractFun'; do j=1 for 2; z.j=translate(z.j,'/',"_"); end /*j*/ -if abbrev('ADD' ,op) then op='+' -if abbrev('DIVIDE' ,op) then op='/' -if abbrev('INTDIVIDE' ,op,4) then op='÷' -if abbrev('MODULO' ,op,3) | abbrev('MODULUS' ,op,3) then op='//' -if abbrev('MULTIPLY' ,op) then op='*' -if abbrev('POWER' ,op) then op='^' -if abbrev('SUBTRACT' ,op) then op='-' -if z.1=='' then z.1=(op\=="+" & op\=='-') /*unary +,-*/ -if z.2=='' then z.2=(op\=="+" & op\=='-') +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +$div: procedure; parse arg x; x=space(x,0); f= 'fractional division' + parse var x n '/' d; d=p(d 1) + if d=0 then call err 'division by zero:' x + if \datatype(n,'N') then call err 'a non─numeric numerator:' x + if \datatype(d,'N') then call err 'a non─numeric denominator:' x + return n/d +/*──────────────────────────────────────────────────────────────────────────────────────*/ +$fun: procedure; parse arg z.1,,z.2 1 zz.2; arg ,op; op=p(op '+') +F= 'fractionalFunction'; do j=1 for 2; z.j=translate(z.j, '/', "_"); end /*j*/ +if abbrev('ADD' , op) then op= "+" +if abbrev('DIVIDE' , op) then op= "/" +if abbrev('INTDIVIDE', op, 4) then op= "÷" +if abbrev('MODULUS' , op, 3) | abbrev('MODULO', op, 3) then op= "//" +if abbrev('MULTIPLY' , op) then op= "*" +if abbrev('POWER' , op) then op= "^" +if abbrev('SUBTRACT' , op) then op= "-" +if z.1=='' then z.1= (op\=="+" & op\=='-') +if z.2=='' then z.2= (op\=="+" & op\=='-') z_=z.2 - - do j=1 for 2 /*verification of both fractions.*/ - if pos('/',z.j)==0 then z.j=z.j"/1"; parse var z.j n.j '/' d.j - if \isNum(n.j) then call err 'a not numeric numerator:' n.j - if \isNum(d.j) then call err 'a not numeric denominator:' d.j - n.j=n.j/1; d.j=d.j/1 - do while \isInt(n.j); n.j=(n.j*10)/1; d.j=(d.j*10)/1 - end /*while*/ /* [↑] normalize both numbers. */ - if d.j=0 then call err 'a denominator of zero:' d.j - g=gcd(n.j,d.j); if g=0 then iterate; n.j=n.j/g; d.j=d.j/g + /* [↑] verification of both fractions.*/ + do j=1 for 2 + if pos('/', z.j)==0 then z.j=z.j"/1"; parse var z.j n.j '/' d.j + if \datatype(n.j,'N') then call err 'a non─numeric numerator:' n.j + if \datatype(d.j,'N') then call err 'a non─numeric denominator:' d.j + if d.j=0 then call err 'a denominator of zero:' d.j + n.j=n.j/1; d.j=d.j/1 + do while \datatype(n.j,'W'); n.j=(n.j*10)/1; d.j=(d.j*10)/1 + end /*while*/ /* [↑] {xxx/1} normalizes a number. */ + g=gcd(n.j, d.j); if g=0 then iterate; n.j=n.j/g; d.j=d.j/g end /*j*/ select + when op=='+' | op=='-' then do; l=lcm(d.1,d.2); do j=1 for 2; n.j=l*n.j/d.j; d.j=l + end /*j*/ + if op=='-' then n.2= -n.2; t=n.1 + n.2; u=l + end when op=='**' | op=='↑' |, - op=='^' then do; if \isInt(z_) then call err 'a not integer power:' z_ - t=1; u=1; do j=1 for abs(z_); t=t*n.1; u=u*d.1 - end /*j*/ - if z_<0 then parse value t u with u t - end - when op=='/' then do; if n.2=0 then call err 'a zero divisor:' zz.2 - t=n.1*d.2; u=n.2*d.1 - end - when op=='÷' then do; if n.2=0 then call err 'a zero divisor:' zz.2 - t=trunc(fractDiv(n.1 '/' d.1)); u=1 - end /* [↑] integer division. */ - when op=='//' then do; if n.2=0 then call err 'a zero divisor:' zz.2 - _=trunc(fractDiv(n.1 '/' d.1)); t=_-trunc(_)*d.1; u=1 - end /* [↑] modulus division. */ - when op=='+' |, - op=='-' then do; l=lcm(d.1 d.2); do j=1 for 2; n.j=l*n.j/d.j; d.j=l - end /*j*/ - if op=='-' then n.2=-n.2; t=n.1+n.2; u=l - end - when op=='ABS' then do; t=abs(n.1); u=abs(d.1); end - when op=='*' then do; t=n.1*n.2; u=d.1*d.2; end - when op=='EQ' |, - op=='=' then return fractDiv(n.1 '/' d.1) = fractDiv(n.2 '/' d.2) - when op=='NE' | op=='\=' | op=='╪' |, - op=='¬=' then return fractDiv(n.1 '/' d.1) \= fractDiv(n.2 '/' d.2) - when op=='GT' |, - op=='>' then return fractDiv(n.1 '/' d.1) > fractDiv(n.2 '/' d.2) - when op=='LT' |, - op=='<' then return fractDiv(n.1 '/' d.1) < fractDiv(n.2 '/' d.2) - when op=='GE' | op=='≥' |, - op=='>=' then return fractDiv(n.1 '/' d.1) >= fractDiv(n.2 '/' d.2) - when op=='LE' | op=='≤' |, - op=='<=' then return fractDiv(n.1 '/' d.1) <= fractDiv(n.2 '/' d.2) - otherwise call err 'an illegal function:' op + op=='^' then do; if \datatype(z_,'W') then call err 'a non─integer power:' z_ + t=1; u=1; do j=1 for abs(z_); t=t*n.1; u=u*d.1 + end /*j*/ + if z_<0 then parse value t u with u t /*swap U and T */ + end + when op=='/' then do; if n.2=0 then call err 'a zero divisor:' zz.2 + t=n.1*d.2; u=n.2*d.1 + end + when op=='÷' then do; if n.2=0 then call err 'a zero divisor:' zz.2 + t=trunc($div(n.1 '/' d.1)); u=1 + end /* [↑] this is integer division. */ + when op=='//' then do; if n.2=0 then call err 'a zero divisor:' zz.2 + _=trunc($div(n.1 '/' d.1)); t=_ - trunc(_) * d.1; u=1 + end /* [↑] modulus division. */ + when op=='ABS' then do; t=abs(n.1); u=abs(d.1); end + when op=='*' then do; t=n.1 * n.2; u=d.1 * d.2; end + when op=='EQ' | op=='=' then return $div(n.1 '/' d.1) = fDiv(n.2 '/' d.2) + when op=='NE' | op=='\=' | op=='╪' | , + op=='¬=' then return $div(n.1 '/' d.1) \= fDiv(n.2 '/' d.2) + when op=='GT' | op=='>' then return $div(n.1 '/' d.1) > fDiv(n.2 '/' d.2) + when op=='LT' | op=='<' then return $div(n.1 '/' d.1) < fDiv(n.2 '/' d.2) + when op=='GE' | op=='≥' | op=='>=' then return $div(n.1 '/' d.1) >= fDiv(n.2 '/' d.2) + when op=='LE' | op=='≤' | op=='<=' then return $div(n.1 '/' d.1) <= fDiv(n.2 '/' d.2) + otherwise call err 'an illegal function:' op end /*select*/ -if t==0 then return 0; g=gcd(t,u); t=t/g; u=u/g +if t==0 then return 0; g=gcd(t, u); t=t/g; u=u/g if u==1 then return t return t'/'u -/*─────────────────────────────general 1─line subs─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ -divisors: procedure; parse arg x 1 b; if x=1 then return 1; a=1; o=x//2; do j=2+o by 1+o while j*j 0 + self + } + fcn abs { a=a.abs(); self } + fcn __opNegate{ a=-a; self } // -Rat + fcn __opAdd(n){ + if(Rational.isChildOf(n)) self(a*n.b + b*n.a, b*n.b); // Rat + Rat + else self(b*n + a, b); // Rat + Int + } + fcn __opSub(n){ self(a*n.b - b*n.a, b*n.b) } // Rat - Rat + fcn __opMul(n){ + if(Rational.isChildOf(n)) self(a*n.a, b*n.b); // Rat * Rat + else self(a*n, b); // Rat * Int + } + fcn __opDiv(n){ self(a*n.b,b*n.a) } // Rat / Rat + fcn __opEQ(r){ // Rat==Rat, Rat==n + if(Rational.isChildOf(r)) a==r.a and b=r.b; + else b==1 and a==r; + } +} diff --git a/Task/Arithmetic-Rational/Zkl/arithmetic-rational-2.zkl b/Task/Arithmetic-Rational/Zkl/arithmetic-rational-2.zkl new file mode 100644 index 0000000000..4a2ffcec28 --- /dev/null +++ b/Task/Arithmetic-Rational/Zkl/arithmetic-rational-2.zkl @@ -0,0 +1,8 @@ +foreach p in ([2 .. (2).pow(19)]){ + sum,limit := Rational(1,p), p.toFloat().sqrt(); + foreach factor in ([2 .. limit]){ + if(p%factor == 0) sum+=Rational(1,factor) + Rational(factor,p); + } + if(sum.b==1) println("Sum of recipr. factors of %6s = %s exactly%s" + .fmt(p, sum, (sum==1) and ", perfect." or ".")); +} diff --git a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation-1.elena b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation-1.elena deleted file mode 100644 index 726a33956f..0000000000 --- a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation-1.elena +++ /dev/null @@ -1,302 +0,0 @@ -#define system. -#define extensions. - -// --- Token --- - -#class Token -{ - #field theValue. - - #constructor new - [ - theValue := String new. - ] - - #constructor new : aValue - [ - theValue := String new:aValue. - ] - - #method ParseOrder = 0. - - #method append : aChar - [ - theValue += aChar. - ] - - #method add : aNode - [ - ^ aNode += self. - ] - - #method Number = convertor toReal:(theValue value). -} - -// --- Node --- - -#class Node -{ - #field theLeft. - #field theRight. - #field theState. - - #method setRight : aNode - [ - theRight := aNode. - - theState := %appendRight. - ] - - #method setLeft : aNode - [ - theLeft := aNode. - - theState := %setRight. - ] - - #constructor new - [ - theState := %setLeft. - ] - - #method add : aNode - = (self ParseOrder > aNode ParseOrder) - ? [ - self += aNode. - - ^ self. - ] - ! [ - aNode += self. - - ^ aNode. - ]. - - #method appendRight : aNode - [ - (theRight ParseOrder > aNode ParseOrder) - ? [ - theRight += aNode. - ] - ! [ - theRight := aNode += theRight. - ]. - ] - - #method append : anObject - = $self~theState eval:anObject. - - #method => theState. -} - -// --- SummaryNode - -#class SummaryNode : Node -{ - #method ParseOrder = 2. - - #method Number = theLeft Number + theRight Number. -} - -// --- DifferenceNode --- - -#class DifferenceNode : Node -{ - #method ParseOrder = 2. - - #method Number = theLeft Number - theRight Number. -} - -// --- ProductNode --- - -#class ProductNode : Node -{ - #method ParseOrder = 1. - - #method Number = theLeft Number * theRight Number. -} - -// --- FractionNode --- - -#class FractionNode : Node -{ - #method ParseOrder = 1. - - #method Number = theLeft Number / theRight Number. -} - -// --- SubExpression --- - -#class SubExpression -{ - #field theParser. - #field theCounter. - - #constructor new - [ - theParser := arithmeval'Parser new. - theCounter := Integer new:1. - ] - - #method ParseOrder = 0. - - #method add : aNode - [ - ^ aNode += self. - ] - - #method validate - [ - (theCounter < 0) - ? [ #throw Exception new:"Invalid expression". ]. - - ^ (0 == theCounter). - ] - - #method append : aChar - [ - aChar => - 41 ? [ - theCounter -= 1. - ] - 40 ? [ theCounter += 1 ] - ! [ theParser evaluate:aChar ]. - ] - - #method Number - = $self validate - ? [ theParser Number ] - ! [ #throw Exception new:"Invalid expression". ]. -} - -// ---- Parser ---- - -#class Parser : system'routines'BasePattern -{ - #field theToken. - #field theTopNode. - #field theState. - - #method onBrackets : aChar - [ - theToken += aChar. - - (theToken validate) - ? [ - theState := %onDigit. - ]. - ] - - #method onStart : aChar - [ - aChar => - 40 ? [ // ( - theToken := SubExpression new. - theTopNode := theToken. - - theState := %onBrackets. - ] - 45 ? [ // - - theToken := DifferenceNode new add:(Token new:"0"). - - theTopNode := theToken. - - theState := %onOperator. - ] - ! [ - theToken := Token new. - theTopNode := theToken. - theState := %onDigit. - - $self appendDigit:aChar. - ]. - ] - - #method onOperator : aChar - [ - aChar => - 40 ? [ - theToken := SubExpression new. - theTopNode += theToken. - theState := %onBrackets. - ] - ! [ - theToken := Token new. - theTopNode += theToken. - theState := %onDigit. - - $self appendDigit:aChar. - ]. - ] - - #constructor new - [ - theState := %onStart. - ] - - #method Number = theTopNode Number. - - #method appendDigit : aChar - [ - (aChar >= 48) and:(aChar < 58) - ? [ - theToken += aChar. - ] - ! [ - #throw Exception new:"Invalid expression". - ] - - ] - - #method onDigit : aChar - [ - aChar => - 40 ? [ // ( - theToken := SubExpression new. - theTopNode := theToken. - theState := %onBrackets. - ] - 42 ? [ // * - theTopNode := theTopNode + ProductNode new. - - theState := %onOperator. - ] - 43 ? [ // + - theTopNode := theTopNode + SummaryNode new. - - theState := %onOperator. - ] - 45 ? [ // - - theTopNode := theTopNode + DifferenceNode new. - - theState := %onOperator. - ] - 47 ? // / - [ - theTopNode := theTopNode + FractionNode new. - - theState := %onOperator. - ] - ! [ - $self appendDigit:aChar. - ]. - ] - - #method eval : aChar = $self~theState eval:aChar. -} - -#symbol program = -[ - #var aText := String new. - - control while:(consoleEx readLine:aText length > 0) &do: - [ - #var aParser := Parser new. - - consoleEx writeLine:"=" :(aParser foreach:aText Number) - | if &e: - [ - consoleEx writeLine:"Invalid Expression". - ]. - ]. -]. diff --git a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation-2.elena b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation-2.elena deleted file mode 100644 index 7302c4fe7b..0000000000 --- a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation-2.elena +++ /dev/null @@ -1,30 +0,0 @@ -number ::= $numeric; -numeric ::= "(" sub_expr; -numeric ::= number; -factor ::= number factor_r; -factor ::= "(" sub_expr; -sum ::= "+" factor ; -difference ::= "-" factor ; -multiply ::= "*" numeric; -divide ::= "/" numeric; -factor_r ::= multiply factor_r; -factor_r ::= divide factor_r; -factor_r ::= $eps; -expr_r ::= sum expr_r; -expr_r ::= difference expr_r; -expr_r ::= $eps; -neg_r ::= factor_r expr_r; -sub_expr ::= expression sub_expr_r; -sub_expr_r ::= ")" factor_r; -neg_expression ::= $numeric neg_r; -expression ::= factor expr_r; -expression ::= "-" neg_expression; -print ::= "?" expression; -start ::= print; -print => &nil 'program'output $body ^write; -multiply => $body ^multiply; -divide => $body ^divide; -sum => $body ^add; -difference => $body ^subtract; -neg_expression => 0 $terminal ^subtract $body; -number => $terminal $body; diff --git a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena index 9eed08c46f..0d8390e410 100644 --- a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena +++ b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena @@ -1,331 +1,315 @@ -#import system. -#import system'routines. -#import extensions. -#import extensions'text. +import system'routines. +import extensions. +import extensions'text. -#class Token +class Token { - #field theValue. - #field theLevel. + object theValue. - #constructor new &level:aLevel + object rprop level :: theLevel. + + constructor new level:aLevel [ theValue := StringWriter new. theLevel := aLevel + 9. ] - #method level = theLevel. - - #method append : aChar + append : aChar [ theValue << aChar. ] - #method number = theValue get toReal. + number = theValue get; toReal. } -#class Node +class Node { - #field theLeft. - #field theRight. - #field theLevel. + object prop left :: theLeft. + object prop right :: theRight. + object rprop level :: theLevel. - #constructor new &level:aLevel + constructor new level:aLevel [ theLevel := aLevel. ] - - #method level = theLevel. - - #method left = theLeft. - - #method right = theRight. - - #method set &left:anObject [ theLeft := anObject. ] - - #method set &right:anObject [ theRight := anObject. ] } -#class SummaryNode :: Node +class SummaryNode :: Node { - #constructor new &level:aLevel - <= %new &level:(aLevel + 1). + constructor new level:aLevel + <= new level(aLevel + 1). - #method number = theLeft number + theRight number. + number = theLeft number + theRight number. } -#class DifferenceNode :: Node +class DifferenceNode :: Node { - #constructor new &level:aLevel - <= %new &level:(aLevel + 1). + constructor new level:aLevel + <= new level(aLevel + 1). - #method number = theLeft number - theRight number. + number = theLeft number - theRight number. } -#class ProductNode :: Node +class ProductNode :: Node { - #constructor new &level:aLevel - <= %new &level:(aLevel + 2). + constructor new level:aLevel + <= new level(aLevel + 2). - #method number = theLeft number * theRight number. + number = theLeft number * theRight number. } -#class FractionNode :: Node +class FractionNode :: Node { - #constructor new &level:aLevel - <= %new &level:(aLevel + 2). + constructor new level:aLevel + <= new level(aLevel + 2). - #method number = theLeft number / theRight number. + number = theLeft number / theRight number. } -#class Expression +class Expression { - #field theLevel. - #field theTop. + object rprop level :: theLevel. + object prop top :: theTop. - #constructor new &level:aLevel + constructor new level:aLevel [ - theLevel := aLevel. + theLevel := aLevel ] - #method top = theTop. + right = theTop. - #method set &top:aNode [ theTop := aNode. ] + set right:aNode [ theTop := aNode ] - #method right = theTop. - - #method set &right:aNode [ theTop := aNode. ] - - #method level = theLevel. - - #method number => theTop. + number => theTop. } -#symbol operatorState = (:ch) +operatorState = (:ch) [ ch => - #40 ? [ // ( - self new &bracket goto &start. - ] + $40 [ // ( + ^ closure newBracket; gotoStarting + ]; ! [ - self new &token append:ch goto &token. + ^ closure newToken; append:ch; gotoToken ]. ]. -#symbol tokenState = (:ch) +tokenState = (:ch) [ ch => - #41 ? [ // ) - self close &bracket goto &token. - ] - #42 ? [ // * - self new &product goto &operator. - ] - #43 ? [ // + - self new &summary goto &operator. - ] - #45 ? [ // - - self new &difference goto &operator. - ] - #47 ? // / - [ - self new &fraction goto &operator. - ] + $41 [ // ) + ^ closure closeBracket; gotoToken + ]; + $42 [ // * + ^ closure newProduct; gotoOperator + ]; + $43 [ // + + ^ closure newSummary; gotoOperator + ]; + $45 [ // - + ^ closure newDifference; gotoOperator + ]; + $47 [ // / + ^ closure newFraction; gotoOperator + ]; ! [ - self append:ch. + ^ closure append:ch ]. ]. -#symbol startState = (:ch) +startState = (:ch) [ ch => - #40 ? [ // ( - self new &bracket goto &start. - ] - #45 ? [ // - - self new &token append &literal:"0" new &difference goto &operator. - ] + $40 [ // ( + ^ closure newBracket; gotoStarting + ]; + $45 [ // - + ^ closure newToken; append literal:"0"; newDifference; gotoOperator + ]; ! [ - self new &token append:ch goto &token. + ^ closure newToken; append:ch; gotoToken ]. ]. -#class Scope +class Scope { - #field theState. - #field theLevel. - #field theParser. - #field theToken. - #field theExpression. + object theState. + object theLevel. + object theParser. + object theToken. + object theExpression. - #constructor new &parser:aParser + constructor new parser:aParser [ theState := startState. theLevel := 0. - theExpression := Expression new &level:0. + theExpression := Expression new level:0. theParser := aParser. ] - #method new &token + newToken [ - theToken := theParser append &token &expression:theExpression &level:theLevel. + theToken := theParser appendToken expression:theExpression level:theLevel. ] - #method new &summary + newSummary [ theToken := nil. - theParser append &summary &expression:theExpression &level:theLevel. + theParser appendSummary expression:theExpression level:theLevel. ] - #method new &difference + newDifference [ theToken := nil. - theParser append &difference &expression:theExpression &level:theLevel. + theParser appendDifference expression:theExpression level:theLevel ] - #method new &product + newProduct [ theToken := nil. - theParser append &product &expression:theExpression &level:theLevel. + theParser appendProduct expression:theExpression level:theLevel ] - #method new &fraction + newFraction [ theToken := nil. - theParser append &fraction &expression:theExpression &level:theLevel. + theParser appendFraction expression:theExpression level:theLevel ] - #method new &bracket + newBracket [ theToken := nil. theLevel := theLevel + 10. - theParser append &subexpression &expression:theExpression &level:theLevel. + theParser appendSubexpression expression:theExpression level:theLevel. ] - #method close &bracket + closeBracket [ - (theLevel < 10) - ? [ #throw InvalidArgumentException new &message:"Invalid expression". ]. + if (theLevel < 10) + [ InvalidArgumentException new:"Invalid expression"; raise ]. - theLevel := theLevel - 10. + theLevel := theLevel - 10 ] - #method append:ch + append:ch [ - ((ch >= #48) and:(ch < #58)) - ? [ theToken append:ch. ] - ! [ #throw InvalidArgumentException new &message:"Invalid expression". ]. + if((ch >= $48) && (ch < $58)) + [ theToken append:ch ]; + [ InvalidArgumentException new:"Invalid expression"; raise ] ] - #method append &literal:aLiteral + append literal:aLiteral [ - aLiteral run &each: ch [ self append:ch. ]. + aLiteral forEach(:ch)[ self append:ch ] ] - #method goto &start + gotoStarting [ - theState := startState. + theState := startState ] - #method goto &token + gotoToken [ - theState := tokenState. + theState := tokenState ] - #method goto &operator + gotoOperator [ - theState := operatorState. + theState := operatorState ] - #method number => theExpression. + number => theExpression. - #method => theState. + dispatch => theState. } -#class Parser +class Parser { - #method append &token &expression:anExpression &level:aLevel + appendToken expression:anExpression level:aLevel [ - #var aToken := Token new &level:aLevel. + var aToken := Token new level:aLevel. - anExpression set &top:($self append &last:(anExpression top) &new:aToken). + anExpression set top:($self append last(anExpression top) new:aToken). - ^ aToken. + ^ aToken ] - #method append &summary &expression:anExpression &level:aLevel + appendSummary expression:anExpression level:aLevel [ - anExpression set &top:($self append &last:(anExpression top) &new:(SummaryNode new &level:aLevel)). + anExpression set top($self append last(anExpression top) new(SummaryNode new level:aLevel)). ] - #method append &difference &expression:anExpression &level:aLevel + appendDifference expression:anExpression level:aLevel [ - anExpression set &top:($self append &last:(anExpression top) &new:(DifferenceNode new &level:aLevel)). + anExpression set top($self append last(anExpression top) new(DifferenceNode new level:aLevel)). ] - #method append &product &expression:anExpression &level:aLevel + appendProduct expression:anExpression level:aLevel [ - anExpression set &top:($self append &last:(anExpression top) &new:(ProductNode new &level:aLevel)). + anExpression set top($self append last(anExpression top) new(ProductNode new level:aLevel)). ] - #method append &fraction &expression:anExpression &level:aLevel + appendFraction expression:anExpression level:aLevel [ - anExpression set &top:($self append &last:(anExpression top) &new:(FractionNode new &level:aLevel)). + anExpression set top($self append last(anExpression top) new(FractionNode new level:aLevel)) ] - #method append &subexpression &expression:anExpression &level:aLevel + appendSubexpression expression:anExpression level:aLevel [ - anExpression set &top:($self append &last:(anExpression top) &new:(Expression new &level:aLevel)). + anExpression set top($self append last(anExpression top) new(Expression new level:aLevel)). ] - #method append &last:aLastNode &new:aNewNode + append last:aLastNode new:aNewNode [ - ($nil == aLastNode) - ? [ ^ aNewNode. ]. + if($nil == aLastNode) + [ ^ aNewNode ]. - (aNewNode level <= aLastNode level) - ? [ aNewNode set &left:aLastNode. ^ aNewNode. ]. + if (aNewNode level <= aLastNode level) + [ aNewNode set left:aLastNode. ^ aNewNode ]. - #var aParent := aLastNode. - #var aCurrent := aLastNode right. - #loop (($nil != aCurrent) and:[ aNewNode level > aCurrent level ]) ? + var aParent := aLastNode. + var aCurrent := aLastNode right. + while (($nil != aCurrent) && $(aNewNode level > aCurrent level)) [ aParent := aCurrent. aCurrent := aCurrent right. ]. - ($nil == aCurrent) - ? [ aParent set &right:aNewNode. ] - ! [ aNewNode set &left:aCurrent. aParent set &right:aNewNode. ]. + if ($nil == aCurrent) + [ aParent set right:aNewNode. ]; + [ aNewNode set left:aCurrent. aParent set right:aNewNode ]. - ^ aLastNode. + ^ aLastNode ] - #method run : aText + run : aText [ - #var aScope := Scope new &parser:$self. + var aScope := Scope new parser:$self. - aText run &each: ch [ aScope eval:ch. ]. + aText forEach(:ch)[ aScope eval:ch ]. - ^ aScope number. + ^ aScope number ] } -#symbol program = +program = [ - #var aText := String new. - #var aParser := Parser new. + var aText := String new. + var aParser := Parser new. - [ console readLine save &to:aText length > 0] doWhile: + $(console readLine; saveTo:aText; length > 0) doWhile: [ - console writeLine:"=" :(aParser run:aText) - | if &Error:e [ - console writeLine:"Invalid Expression". - ]. + try(console printLine("=",aParser run:aText)) + { + on(Exception e) + [ + console writeLine:"Invalid Expression" + ] + }. - aText clear. + aText clear ]. ]. diff --git a/Task/Arithmetic-evaluation/Haskell/arithmetic-evaluation.hs b/Task/Arithmetic-evaluation/Haskell/arithmetic-evaluation.hs index bc1030b4cd..864795fb84 100644 --- a/Task/Arithmetic-evaluation/Haskell/arithmetic-evaluation.hs +++ b/Task/Arithmetic-evaluation/Haskell/arithmetic-evaluation.hs @@ -1,28 +1,47 @@ +{-# LANGUAGE FlexibleContexts #-} + import Text.Parsec import Text.Parsec.Expr import Text.Parsec.Combinator import Data.Functor import Data.Function (on) -data Exp = Num Int - | Add Exp Exp - | Sub Exp Exp - | Mul Exp Exp - | Div Exp Exp +data Exp + = Num Int + | Add Exp + Exp + | Sub Exp + Exp + | Mul Exp + Exp + | Div Exp + Exp +expr + :: Stream s m Char + => ParsecT s u m Exp expr = buildExpressionParser table factor - where table = [[op "*" (Mul) AssocLeft, op "/" (Div) AssocLeft] - ,[op "+" (Add) AssocLeft, op "-" (Sub) AssocLeft]] - op s f assoc = Infix (f <$ string s) assoc - factor = (between `on` char) '(' ')' expr - <|> (Num . read <$> many1 digit) + where + table = + [ [op "*" Mul AssocLeft, op "/" Div AssocLeft] + , [op "+" Add AssocLeft, op "-" Sub AssocLeft] + ] + op s f = Infix (f <$ string s) + factor = (between `on` char) '(' ')' expr <|> (Num . read <$> many1 digit) -eval :: Num a => Exp -> a -eval (Num x) = fromIntegral x -eval (Add a b) = eval a + eval b -eval (Sub a b) = eval a - eval b -eval (Mul a b) = eval a * eval b +eval + :: Integral a + => Exp -> a +eval (Num x) = fromIntegral x +eval (Add a b) = eval a + eval b +eval (Sub a b) = eval a - eval b +eval (Mul a b) = eval a * eval b eval (Div a b) = eval a `div` eval b -solution :: Num a => String -> a +solution + :: Integral a + => String -> a solution = either (const (error "Did not parse")) eval . parse expr "" + +main :: IO () +main = print $ solution "(1+3)*7" diff --git a/Task/Arithmetic-evaluation/Java/arithmetic-evaluation.java b/Task/Arithmetic-evaluation/Java/arithmetic-evaluation.java index 59abc98a1e..4eba0f23f0 100644 --- a/Task/Arithmetic-evaluation/Java/arithmetic-evaluation.java +++ b/Task/Arithmetic-evaluation/Java/arithmetic-evaluation.java @@ -1,138 +1,165 @@ import java.util.Stack; -public class ArithmeticEvaluation -{ - public static enum Parentheses { LEFT, RIGHT } +public class ArithmeticEvaluation { - public static enum BinaryOperator - { - ADD('+', 1) { - public BigRational eval(BigRational leftValue, BigRational rightValue) { return leftValue.add(rightValue); } - }, - SUB('-', 1) { - public BigRational eval(BigRational leftValue, BigRational rightValue) { return leftValue.subtract(rightValue); } - }, - MUL('*', 2) { - public BigRational eval(BigRational leftValue, BigRational rightValue) { return leftValue.multiply(rightValue); } - }, - DIV('/', 2) { - public BigRational eval(BigRational leftValue, BigRational rightValue) { return leftValue.divide(rightValue); } - }; - - public final char symbol; - public final int precedence; - - BinaryOperator(char symbol, int precedence) - { - this.symbol = symbol; - this.precedence = precedence; + public interface Expression { + BigRational eval(); } - public abstract BigRational eval(BigRational leftValue, BigRational rightValue); - } + public enum Parentheses {LEFT} - public static class BinaryExpression - { - public Object leftOperand = null; - public BinaryOperator operator = null; - public Object rightOperand = null; + public enum BinaryOperator { + ADD('+', 1), + SUB('-', 1), + MUL('*', 2), + DIV('/', 2); - public BinaryExpression(Object leftOperand, BinaryOperator operator, Object rightOperand) - { - this.leftOperand = leftOperand; - this.operator = operator; - this.rightOperand = rightOperand; - } + public final char symbol; + public final int precedence; - public BigRational eval() - { - BigRational leftValue = (leftOperand instanceof BinaryExpression) ? ((BinaryExpression)leftOperand).eval() : (BigRational)leftOperand; - BigRational rightValue = (rightOperand instanceof BinaryExpression) ? ((BinaryExpression)rightOperand).eval() : (BigRational)rightOperand; - return operator.eval(leftValue, rightValue); - } - - public String toString() - { return "(" + leftOperand + " " + operator.symbol + " " + rightOperand + ")"; } - } - - public static void createNewOperand(BinaryOperator operator, Stack operands) - { - Object rightOperand = operands.pop(); - operands.push(new BinaryExpression(operands.pop(), operator, rightOperand)); - return; - } - - public static Object createExpression(String inputString) - { - int curIndex = 0; - boolean afterOperand = false; - Stack operands = new Stack(); - Stack operators = new Stack(); -inputStringLoop: - while (curIndex < inputString.length()) - { - int startIndex = curIndex; - char c = inputString.charAt(curIndex++); - if (Character.isWhitespace(c)) - continue; - if (afterOperand) - { - if (c == ')') - { - Object operator = null; - while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT)) - createNewOperand((BinaryOperator)operator, operands); - continue; + BinaryOperator(char symbol, int precedence) { + this.symbol = symbol; + this.precedence = precedence; } - afterOperand = false; - for (BinaryOperator operator : BinaryOperator.values()) - { - if (c == operator.symbol) - { - while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator)operators.peek()).precedence >= operator.precedence)) - createNewOperand((BinaryOperator)operators.pop(), operands); - operators.push(operator); - continue inputStringLoop; - } + + public BigRational eval(BigRational leftValue, BigRational rightValue) { + switch (this) { + case ADD: + return leftValue.add(rightValue); + case SUB: + return leftValue.subtract(rightValue); + case MUL: + return leftValue.multiply(rightValue); + case DIV: + return leftValue.divide(rightValue); + } + throw new IllegalStateException(); + } + + public static BinaryOperator forSymbol(char symbol) { + for (BinaryOperator operator : values()) { + if (operator.symbol == symbol) { + return operator; + } + } + throw new IllegalArgumentException(String.valueOf(symbol)); } - throw new IllegalArgumentException(); - } - if (c == '(') - { - operators.push(Parentheses.LEFT); - continue; - } - afterOperand = true; - while (curIndex < inputString.length()) - { - c = inputString.charAt(curIndex); - if (((c < '0') || (c > '9')) && (c != '.')) - break; - curIndex++; - } - operands.push(BigRational.valueOf(inputString.substring(startIndex, curIndex))); } - while (!operators.isEmpty()) - { - Object operator = operators.pop(); - if (operator == Parentheses.LEFT) - throw new IllegalArgumentException(); - createNewOperand((BinaryOperator)operator, operands); - } - Object expression = operands.pop(); - if (!operands.isEmpty()) - throw new IllegalArgumentException(); - return expression; - } + public static class Number implements Expression { + private final BigRational number; - public static void main(String[] args) - { - String[] testExpressions = { "2+3", "2+3/4", "2*3-4", "2*(3+4)+5/6", "2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10", "2*-3--4+-.25" }; - for (String testExpression : testExpressions) - { - Object expression = createExpression(testExpression); - System.out.println("Input: \"" + testExpression + "\", AST: \"" + expression + "\", eval=" + (expression instanceof BinaryExpression ? ((BinaryExpression)expression).eval() : expression)); + public Number(BigRational number) { + this.number = number; + } + + @Override + public BigRational eval() { + return number; + } + + @Override + public String toString() { + return number.toString(); + } + } + + public static class BinaryExpression implements Expression { + public final Expression leftOperand; + public final BinaryOperator operator; + public final Expression rightOperand; + + public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) { + this.leftOperand = leftOperand; + this.operator = operator; + this.rightOperand = rightOperand; + } + + @Override + public BigRational eval() { + BigRational leftValue = leftOperand.eval(); + BigRational rightValue = rightOperand.eval(); + return operator.eval(leftValue, rightValue); + } + + @Override + public String toString() { + return "(" + leftOperand + " " + operator.symbol + " " + rightOperand + ")"; + } + } + + private static void createNewOperand(BinaryOperator operator, Stack operands) { + Expression rightOperand = operands.pop(); + Expression leftOperand = operands.pop(); + operands.push(new BinaryExpression(leftOperand, operator, rightOperand)); + } + + public static Expression parse(String input) { + int curIndex = 0; + boolean afterOperand = false; + Stack operands = new Stack<>(); + Stack operators = new Stack<>(); + while (curIndex < input.length()) { + int startIndex = curIndex; + char c = input.charAt(curIndex++); + + if (Character.isWhitespace(c)) + continue; + + if (afterOperand) { + if (c == ')') { + Object operator; + while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT)) + createNewOperand((BinaryOperator) operator, operands); + continue; + } + afterOperand = false; + BinaryOperator operator = BinaryOperator.forSymbol(c); + while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence)) + createNewOperand((BinaryOperator) operators.pop(), operands); + operators.push(operator); + continue; + } + + if (c == '(') { + operators.push(Parentheses.LEFT); + continue; + } + + afterOperand = true; + while (curIndex < input.length()) { + c = input.charAt(curIndex); + if (((c < '0') || (c > '9')) && (c != '.')) + break; + curIndex++; + } + operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex)))); + } + + while (!operators.isEmpty()) { + Object operator = operators.pop(); + if (operator == Parentheses.LEFT) + throw new IllegalArgumentException(); + createNewOperand((BinaryOperator) operator, operands); + } + + Expression expression = operands.pop(); + if (!operands.isEmpty()) + throw new IllegalArgumentException(); + return expression; + } + + public static void main(String[] args) { + String[] testExpressions = { + "2+3", + "2+3/4", + "2*3-4", + "2*(3+4)+5/6", + "2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10", + "2*-3--4+-.25"}; + for (String testExpression : testExpressions) { + Expression expression = parse(testExpression); + System.out.printf("Input: \"%s\", AST: \"%s\", value=%s%n", testExpression, expression, expression.eval()); + } } - } } diff --git a/Task/Arithmetic-evaluation/OoRexx/arithmetic-evaluation.rexx b/Task/Arithmetic-evaluation/OoRexx/arithmetic-evaluation.rexx new file mode 100644 index 0000000000..4674dcb367 --- /dev/null +++ b/Task/Arithmetic-evaluation/OoRexx/arithmetic-evaluation.rexx @@ -0,0 +1,235 @@ +expressions = .array~of("2+3", "2+3/4", "2*3-4", "2*(3+4)+5/6", "2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10", "2*-3--4+-.25") +loop input over expressions + expression = createExpression(input) + if expression \= .nil then + say 'Expression "'input'" parses to "'expression~string'" and evaluates to "'expression~evaluate'"' +end + + +-- create an executable expression from the input, printing out any +-- errors if they are raised. +::routine createExpression + use arg inputString +-- signal on syntax + return .ExpressionParser~parseExpression(inputString) + +syntax: + condition = condition('o') + say condition~errorText + say condition~message + return .nil + + +-- a base class for tree nodes in the tree +-- all nodes return some sort of value. This can be constant, +-- or the result of additional evaluations +::class evaluatornode +-- all evaluation is done here +::method evaluate abstract + +-- node for numeric values in the tree +::class constant +::method init + expose value + use arg value + +::method evaluate + expose value + return value + +::method string + expose value + return value + +-- node for a parenthetical group on the tree +::class parens +::method init + expose subexpression + use arg subexpression + +::method evaluate + expose subexpression + return subexpression~evaluate + +::method string + expose subexpression + return "("subexpression~string")" + +-- base class for binary operators +::class binaryoperator +::method init + expose left right + -- the left and right sides are set after the left and right sides have + -- been resolved. + left = .nil + right = .nil + +-- base operation +::method evaluate + expose left right + return self~operation(left~evaluate, right~evaluate) + +-- the actual operation of the node +::method operation abstract +::method symbol abstract +::method precedence abstract + +-- display an operator as a string value +::method string + expose left right + return '('left~string self~symbol right~string')' + +::attribute left +::attribute right + +::class addoperator subclass binaryoperator +::method operation + use arg left, right + return left + right + +::method symbol + return "+" + +::method precedence + return 1 + +::class subtractoperator subclass binaryoperator +::method operation + use arg left, right + return left - right + +::method symbol + return "-" + +::method precedence + return 1 + +::class multiplyoperator subclass binaryoperator +::method operation + use arg left, right + return left * right + +::method symbol + return "*" + +::method precedence + return 2 + +::class divideoperator subclass binaryoperator +::method operation + use arg left, right + return left / right + +::method symbol + return "/" + +::method precedence + return 2 + +-- a class to parse the expression and build an evaluation tree +::class expressionParser +-- create a resolved operand from an operator instance and the top +-- two entries on the operand stack. +::method createNewOperand class + use strict arg operator, operands + -- the operands are a stack, so they are in inverse order current + operator~right = operands~pull + operator~left = operands~pull + -- this goes on the top of the stack now + operands~push(operator) + +::method parseExpression class + use strict arg inputString + -- stacks for managing the operands and pending operators + operands = .queue~new + operators = .queue~new + -- this flags what sort of item we expect to find at the current + -- location + afterOperand = .false + + loop currentIndex = 1 to inputString~length + char = inputString~subChar(currentIndex) + -- skip over whitespace + if char == ' ' then iterate currentIndex + -- If the last thing we parsed was an operand, then + -- we expect to see either a closing paren or an + -- operator to appear here + if afterOperand then do + if char == ')' then do + loop while \operators~isempty + operator = operators~pull + -- if we find the opening paren, replace the + -- top operand with a paren group wrapper + -- and stop popping items + if operator == '(' then do + operands~push(.parens~new(operands~pull)) + leave + end + -- collapse the operator stack a bit + self~createNewOperand(operator, operands) + end + -- done with this character + iterate currentIndex + end + afterOperand = .false + operator = .nil + if char == "+" then operator = .addoperator~new + else if char == "-" then operator = .subtractoperator~new + else if char == "*" then operator = .multiplyoperator~new + else if char == "/" then operator = .divideoperator~new + if operator \= .nil then do + loop while \operators~isEmpty + top = operators~peek + -- start of a paren group stops the popping + if top == '(' then leave + -- or the top operator has a lower precedence + if top~precedence < operator~precedence then leave + -- process this pending one + self~createNewOperand(operators~pull, operands) + end + -- this new operator is now top of the stack + operators~push(operator) + -- and back to the top + iterate currentIndex + end + raise syntax 98.900 array("Invalid expression character" char) + end + -- if we've hit an open paren, add this to the operator stack + -- as a phony operator + if char == '(' then do + operators~push('(') + iterate currentIndex + end + -- not an operator, so we have an operand of some type + afterOperand = .true + startindex = currentIndex + -- allow a leading minus sign on this + if inputString~subchar(currentIndex) == '-' then + currentIndex += 1 + -- now scan for the end of numbers + loop while currentIndex <= inputString~length + -- exit for any non-numeric value + if \inputString~matchChar(currentIndex, "0123456789.") then leave + currentIndex += 1 + end + -- extract the string value + operand = inputString~substr(startIndex, currentIndex - startIndex) + if \operand~datatype('Number') then + raise syntax 98.900 array("Invalid numeric operand '"operand"'") + -- back this up to the last valid character + currentIndex -= 1 + -- add this to the operand stack as a tree element that returns a constant + operands~push(.constant~new(operand)) + end + + loop while \operators~isEmpty + operator = operators~pull + if operator == '(' then + raise syntax 98.900 array("Missing closing ')' in expression") + self~createNewOperand(operator, operands) + end + -- our entire expression should be the top of the expression tree + expression = operands~pull + if \operands~isEmpty then + raise syntax 98.900 array("Invalid expression") + return expression diff --git a/Task/Arithmetic-evaluation/Racket/arithmetic-evaluation.rkt b/Task/Arithmetic-evaluation/Racket/arithmetic-evaluation.rkt index 64c2518055..c6ac224f44 100644 --- a/Task/Arithmetic-evaluation/Racket/arithmetic-evaluation.rkt +++ b/Task/Arithmetic-evaluation/Racket/arithmetic-evaluation.rkt @@ -12,7 +12,7 @@ [(~or "+" "-" "*" "/") (string->symbol lexeme)] ["(" 'OPEN] [")" 'CLOSE] - [(~: (~+ numeric) (~? #\. (~* numeric))) + [(~: (~+ numeric) (~? (~: #\. (~* numeric)))) (token-NUM (string->number lexeme))])) (define parse diff --git a/Task/Arithmetic-evaluation/Scheme/arithmetic-evaluation.ss b/Task/Arithmetic-evaluation/Scheme/arithmetic-evaluation.ss new file mode 100644 index 0000000000..22feced496 --- /dev/null +++ b/Task/Arithmetic-evaluation/Scheme/arithmetic-evaluation.ss @@ -0,0 +1,95 @@ +(import (scheme base) + (scheme char) + (scheme cxr) + (scheme write) + (srfi 1 lists)) + +;; convert a string into a list of tokens +(define (string->tokens str) + (define (next-token chars) + (cond ((member (car chars) (list #\+ #\- #\* #\/) char=?) + (values (cdr chars) + (cdr (assq (car chars) ; convert char for op into op procedure, using a look up list + (list (cons #\+ +) (cons #\- -) (cons #\* *) (cons #\/ /)))))) + ((member (car chars) (list #\( #\)) char=?) + (values (cdr chars) + (if (char=? (car chars) #\() + 'open + 'close))) + (else ; read a multi-digit positive integer + (let loop ((rem chars) + (res 0)) + (if (and (not (null? rem)) + (char-numeric? (car rem))) + (loop (cdr rem) + (+ (* res 10) + (- (char->integer (car rem)) + (char->integer #\0)))) + (values rem + res)))))) + ; + (let loop ((chars (remove char-whitespace? (string->list str))) + (tokens '())) + (if (null? chars) + (reverse tokens) + (let-values (((remaining-chars token) (next-token chars))) + (loop remaining-chars + (cons token tokens)))))) + +;; turn list of tokens into an AST +;; -- using recursive descent parsing to obey laws of precedence +(define (parse tokens) + (define (parse-factor tokens) + (if (number? (car tokens)) + (values (car tokens) (cdr tokens)) + (let-values (((expr rem) (parse-expr (cdr tokens)))) + (values expr (cdr rem))))) + (define (parse-term tokens) + (let-values (((left-expr rem) (parse-factor tokens))) + (if (and (not (null? rem)) + (member (car rem) (list * /))) + (let-values (((right-expr remr) (parse-term (cdr rem)))) + (values (list (car rem) left-expr right-expr) + remr)) + (values left-expr rem)))) + (define (parse-part tokens) + (let-values (((left-expr rem) (parse-term tokens))) + (if (and (not (null? rem)) + (member (car rem) (list + -))) + (let-values (((right-expr remr) (parse-part (cdr rem)))) + (values (list (car rem) left-expr right-expr) + remr)) + (values left-expr rem)))) + (define (parse-expr tokens) + (let-values (((expr rem) (parse-part tokens))) + (values expr rem))) + ; + (let-values (((expr rem) (parse-expr tokens))) + (if (null? rem) + expr + (error "Misformed expression")))) + +;; evaluate the AST, returning a number +(define (eval-expression ast) + (cond ((number? ast) + ast) + ((member (car ast) (list + - * /)) + ((car ast) + (eval-expression (cadr ast)) + (eval-expression (caddr ast)))) + (else + (error "Misformed expression")))) + +;; parse and evaluate the given string +(define (interpret str) + (eval-expression (parse (string->tokens str)))) + +;; running some examples +(for-each + (lambda (str) + (display + (string-append str + " => " + (number->string (interpret str)))) + (newline)) + '("1 + 2" "20+4*5" "1/2+5*(6-3)" "(1+3)/4-1" "(1 - 5) * 2 / (20 + 1)")) diff --git a/Task/Arithmetic-evaluation/Sidef/arithmetic-evaluation-1.sidef b/Task/Arithmetic-evaluation/Sidef/arithmetic-evaluation-1.sidef index 6869c00b4d..417221f6d0 100644 --- a/Task/Arithmetic-evaluation/Sidef/arithmetic-evaluation-1.sidef +++ b/Task/Arithmetic-evaluation/Sidef/arithmetic-evaluation-1.sidef @@ -3,54 +3,54 @@ func evalArithmeticExp(s) { func evalExp(s) { func operate(s, op) { - s.split(op).map{|c| c.to_num }.reduce(op); + s.split(op).map{|c| Number(c) }.reduce(op) } func add(s) { - operate(s.sub(/^\+/,'').sub(/\++/,'+'), '+'); + operate(s.sub(/^\+/,'').sub(/\++/,'+'), '+') } func subtract(s) { - s.gsub!(/(\+-|-\+)/,'-'); + s.gsub!(/(\+-|-\+)/,'-') if (s ~~ /--/) { - return(add(s.sub(/--/,'+'))); + return(add(s.sub(/--/,'+'))) } - var b = s.split('-'); - b.len == 3 ? (-1*b[1].to_num - b[2].to_num) - : operate(s, '-'); + var b = s.split('-') + b.len == 3 ? (-1*Number(b[1]) - Number(b[2])) + : operate(s, '-') } - s.gsub!(/[()]/,'').gsub!(/-\+/, '-'); + s.gsub!(/[()]/,'').gsub!(/-\+/, '-') - var reM = /\*/; - var reMD = %r"(\d+\.?\d*\s*[*/]\s*[+-]?\d+\.?\d*)"; + var reM = /\*/ + var reMD = %r"(\d+\.?\d*\s*[*/]\s*[+-]?\d+\.?\d*)" - var reA = /\d\+/; - var reAS = /(-?\d+\.?\d*\s*[+-]\s*[+-]?\d+\.?\d*)/; + var reA = /\d\+/ + var reAS = /(-?\d+\.?\d*\s*[+-]\s*[+-]?\d+\.?\d*)/ while (var match = reMD.match(s)) { match[0] ~~ reM ? s.sub!(reMD, operate(match[0], '*').to_s) - : s.sub!(reMD, operate(match[0], '/').to_s); + : s.sub!(reMD, operate(match[0], '/').to_s) } while (var match = reAS.match(s)) { match[0] ~~ reA ? s.sub!(reAS, add(match[0]).to_s) - : s.sub!(reAS, subtract(match[0]).to_s); + : s.sub!(reAS, subtract(match[0]).to_s) } - return s; + return s } - var rePara = /(\([^\(\)]*\))/; - s.split!.join!('').sub!(/^\+/,''); + var rePara = /(\([^\(\)]*\))/ + s.split!.join!('').sub!(/^\+/,'') while (var match = s.match(rePara)) { - s.sub!(rePara, evalExp(match[0])); + s.sub!(rePara, evalExp(match[0])) } - return evalExp(s).to_num; + return Number(evalExp(s)) } diff --git a/Task/Arithmetic-evaluation/Sidef/arithmetic-evaluation-2.sidef b/Task/Arithmetic-evaluation/Sidef/arithmetic-evaluation-2.sidef index 461bc6dddc..b959f5704a 100644 --- a/Task/Arithmetic-evaluation/Sidef/arithmetic-evaluation-2.sidef +++ b/Task/Arithmetic-evaluation/Sidef/arithmetic-evaluation-2.sidef @@ -7,7 +7,7 @@ for expr,res in [ ['2*-3--4+-0.25' => -2.25], ['2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10' => 7000], ] {  - var num = evalArithmeticExp(expr); - assert_eq(num, res); - "%-45s == %10g\n".printf(expr, num); + var num = evalArithmeticExp(expr) + assert_eq(num, res) + "%-45s == %10g\n".printf(expr, num) } diff --git a/Task/Arithmetic-evaluation/Zkl/arithmetic-evaluation-1.zkl b/Task/Arithmetic-evaluation/Zkl/arithmetic-evaluation-1.zkl new file mode 100644 index 0000000000..f9f7d745e6 --- /dev/null +++ b/Task/Arithmetic-evaluation/Zkl/arithmetic-evaluation-1.zkl @@ -0,0 +1,2 @@ +Compiler.Parser.parseText("(1+3)*7").dump(); +Compiler.Parser.parseText("1+3*7").dump(); diff --git a/Task/Arithmetic-evaluation/Zkl/arithmetic-evaluation-2.zkl b/Task/Arithmetic-evaluation/Zkl/arithmetic-evaluation-2.zkl new file mode 100644 index 0000000000..7b474ab9ed --- /dev/null +++ b/Task/Arithmetic-evaluation/Zkl/arithmetic-evaluation-2.zkl @@ -0,0 +1,2 @@ +Compiler.Compiler.compileText("(1+3)*7").__constructor(); vm.regX; +Compiler.Compiler.compileText("1+3*7").__constructor(); vm.regX; diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Kotlin/arithmetic-geometric-mean-calculate-pi.kotlin b/Task/Arithmetic-geometric-mean-Calculate-Pi/Kotlin/arithmetic-geometric-mean-calculate-pi.kotlin new file mode 100644 index 0000000000..44638cab07 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Kotlin/arithmetic-geometric-mean-calculate-pi.kotlin @@ -0,0 +1,33 @@ +import java.math.BigDecimal +import java.math.MathContext + +val con1024 = MathContext(1024) +val bigTwo = BigDecimal(2) +val bigFour = bigTwo * bigTwo + +fun bigSqrt(bd: BigDecimal, con: MathContext): BigDecimal { + var x0 = BigDecimal.ZERO + var x1 = BigDecimal.valueOf(Math.sqrt(bd.toDouble())) + while (x0 != x1) { + x0 = x1 + x1 = bd.divide(x0, con).add(x0).divide(bigTwo, con) + } + return x1 +} + +fun main(args: Array) { + var a = BigDecimal.ONE + var g = a.divide(bigSqrt(bigTwo, con1024), con1024) + var t : BigDecimal + var sum = BigDecimal.ZERO + var pow = bigTwo + while (a != g) { + t = (a + g).divide(bigTwo, con1024) + g = bigSqrt(a * g, con1024) + a = t + pow *= bigTwo + sum += (a * a - g * g) * pow + } + val pi = (bigFour * a * a).divide(BigDecimal.ONE - sum, con1024) + println(pi) +} diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/OCaml/arithmetic-geometric-mean-calculate-pi.ocaml b/Task/Arithmetic-geometric-mean-Calculate-Pi/OCaml/arithmetic-geometric-mean-calculate-pi.ocaml new file mode 100644 index 0000000000..615f99ade1 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/OCaml/arithmetic-geometric-mean-calculate-pi.ocaml @@ -0,0 +1,18 @@ +let limit = 10000 and n = 2800 +let x = Array.make (n+1) 2000 + +let rec g j sum = + if j < 1 then sum else + let sum = sum * j + limit * x.(j) in + x.(j) <- sum mod (j * 2 - 1); + g (j - 1) (sum / (j * 2 - 1)) + +let rec f i carry = + if i = 0 then () else + let sum = g i 0 in + Printf.printf "%04d" (carry + sum / limit); + f (i - 14) (sum mod limit) + +let () = + f n 0; + print_newline() diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-1.rexx b/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-1.rexx index d57f67151c..bfca3d64b3 100644 --- a/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-1.rexx +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-1.rexx @@ -1,21 +1,20 @@ -/*REXX program calculates the value of pi using the AGM algorithm. */ -parse arg d .; if d=='' then d=500 /*D not specified? Then use default. */ -numeric digits d+5 /*set the numeric decimal digits to D+5*/ -a=1; n=1; z=1/4; g=sqrt(1/2) /*calculate some initial values. */ +/*REXX program calculates the value of pi using the AGM algorithm. */ +parse arg d .; if d=='' | d=="," then d=500 /*D not specified? Then use default. */ +numeric digits d+5 /*set the numeric decimal digits to D+5*/ +z=1/4; a=1; g=sqrt(1/2) /*calculate some initial values. */ +n=1 + do j=1 until a==old; old=a /*keep calculating until no more noise.*/ + x=(a+g)*.5; g=sqrt(a*g) /*calculate the next set of terms. */ + z=z - n*(x-a)**2; n=n+n; a=x /*Z is used in the final calculation. */ + end /*j*/ /* [↑] stop if A equals OLD. */ - do j=1 until a==old; old=a /*keep calculating until no more noise.*/ - x=(a+g)*.5; g=sqrt(a*g) /*calculate the next set of terms. */ - z=z-n*(x-a)**2; n=n+n; a=x /*Z is used in the final calculation. */ - end /*j*/ /* [↑] stop if A equals OLD. */ - -pi=a**2/z /*display the computed value of pi. */ -numeric digits d /*set the numeric decimal digits to D.*/ -say pi/1 /*display the computed value of pi. */ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 - numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ - numeric digits d; return (g/1)i /*make complex if X < 0.*/ +pi=a**2 / z /*compute the finished value of pi. */ +numeric digits d /*set the numeric decimal digits to D.*/ +say pi / 1 /*display the computed value of pi. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h=d+6 + numeric form; m.=9; 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 diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-2.rexx b/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-2.rexx index 1fd1dc97ab..959df4faea 100644 --- a/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-2.rexx +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/REXX/arithmetic-geometric-mean-calculate-pi-2.rexx @@ -1,24 +1,24 @@ -/*REXX program calculates value of pi using the AGM algorithm (running digits)*/ -parse arg d .; if d=='' then d=500 /*D not specified? Then use default. */ -numeric digits d+5 /*set the numeric decimal digits to D+5*/ -a=1; n=1; z=1/4; g=sqrt(1/2) /*calculate some initial values. */ +/*REXX program calculates value of pi using the AGM algorithm (with running digits).*/ +parse arg d .; if d=='' | d=="," then d=500 /*D not specified? Then use default. */ +numeric digits d+5 /*set the numeric decimal digits to D+5*/ +z=1/4; a=1; g=sqrt(1/2) /*calculate some initial values. */ +n=1 - do j=1 until a==old; old=a /*keep calculating until no more noise.*/ - x=(a+g)*.5; g=sqrt(a*g) /*calculate the next set of terms. */ - z=z-n*(x-a)**2; n=n+n; a=x /*Z is used in the final calculation. */ - many=compare(a,old) /*how many accurate digits computed? */ - if many==0 then many=d /*adjust for the very last time. */ - say right('iteration' j,20) right(many,9) "digits" /*show digits.*/ - end /*j*/ /* [↑] stop if A equals OLD. */ -say /*display a blank line for a separator.*/ -pi=a**2/z /*display the computed value of pi. */ -numeric digits d /*set the numeric decimal digits to D.*/ -say pi/1 /*display the computed value of pi. */ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 - numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ - numeric digits d; return (g/1)i /*make complex if X < 0.*/ + do j=1 until a==old; old=a /*keep calculating until no more noise.*/ + x=(a+g)*.5; g=sqrt(a*g) /*calculate the next set of terms. */ + z=z-n*(x-a)**2; n=n+n; a=x /*Z is used in the final calculation. */ + many=compare(a,old) /*how many accurate digits computed? */ + if many==0 then many=d /*adjust for the very last time. */ + say right('iteration' j, 20) right(many, 9) "digits" /*show digits.*/ + end /*j*/ /* [↑] stop if A equals OLD. */ +say /*display a blank line for a separator.*/ +pi=a**2 / z /*compute the finished value of pi. */ +numeric digits d /*set the numeric decimal digits to D.*/ +say pi / 1 /*display the computed value of pi. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h=d+6 + numeric form; m.=9; 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 diff --git a/Task/Arithmetic-geometric-mean/APL/arithmetic-geometric-mean.apl b/Task/Arithmetic-geometric-mean/APL/arithmetic-geometric-mean.apl new file mode 100644 index 0000000000..4df6eb580f --- /dev/null +++ b/Task/Arithmetic-geometric-mean/APL/arithmetic-geometric-mean.apl @@ -0,0 +1,2 @@ +agd←{(⍺-⍵)<10*¯8:⍺⋄((⍺+⍵)÷2)∇(⍺×⍵)*÷2} +1 agd ÷2*÷2 diff --git a/Task/Arithmetic-geometric-mean/AppleScript/arithmetic-geometric-mean.applescript b/Task/Arithmetic-geometric-mean/AppleScript/arithmetic-geometric-mean.applescript index 193ec10bc0..6ce2c0d860 100644 --- a/Task/Arithmetic-geometric-mean/AppleScript/arithmetic-geometric-mean.applescript +++ b/Task/Arithmetic-geometric-mean/AppleScript/arithmetic-geometric-mean.applescript @@ -31,26 +31,19 @@ end run --- GENERIC +-- GENERIC FUNCTIONS -- until :: (a -> Bool) -> (a -> a) -> a -> a on |until|(p, f, x) set mp to mReturn(p) - set mf to mReturn(f) + set v to x - script - property p : mp's lambda - property f : mf's lambda - - on lambda(v) - repeat until p(v) - set v to f(v) - end repeat - return v - end lambda - end script - - result's lambda(x) + tell mReturn(f) + repeat until mp's lambda(v) + set v to lambda(v) + end repeat + end tell + return v end |until| -- Lift 2nd class handler function into 1st class script wrapper diff --git a/Task/Arithmetic-geometric-mean/Bc/arithmetic-geometric-mean.bc b/Task/Arithmetic-geometric-mean/Bc/arithmetic-geometric-mean.bc new file mode 100644 index 0000000000..c341acdb79 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Bc/arithmetic-geometric-mean.bc @@ -0,0 +1,25 @@ +/* Calculate the arithmethic-geometric mean of two positive + * numbers x and y. + * Result will have d digits after the decimal point. + */ +define m(x, y, d) { + auto a, g, o + + o = scale + scale = d + d = 1 / 10 ^ d + + a = (x + y) / 2 + g = sqrt(x * y) + while ((a - g) > d) { + x = (a + g) / 2 + g = sqrt(a * g) + a = x + } + + scale = o + return(a) +} + +scale = 20 +m(1, 1 / sqrt(2), 20) diff --git a/Task/Arithmetic-geometric-mean/D/arithmetic-geometric-mean.d b/Task/Arithmetic-geometric-mean/D/arithmetic-geometric-mean.d index 9d12ef84ee..689142bd2c 100644 --- a/Task/Arithmetic-geometric-mean/D/arithmetic-geometric-mean.d +++ b/Task/Arithmetic-geometric-mean/D/arithmetic-geometric-mean.d @@ -1,9 +1,9 @@ -import std.stdio, std.math, std.typecons, std.typetuple; +import std.stdio, std.math, std.meta, std.typecons; real agm(real a, real g, in int bitPrecision=60) pure nothrow @nogc @safe { do { //{a, g} = {(a + g) / 2.0, sqrt(a * g)}; - TypeTuple!(a, g) = tuple((a + g) / 2.0, sqrt(a * g)); + AliasSeq!(a, g) = tuple((a + g) / 2.0, sqrt(a * g)); } while (feqrel(a, g) < bitPrecision); return a; } diff --git a/Task/Arithmetic-geometric-mean/Futhark/arithmetic-geometric-mean.futhark b/Task/Arithmetic-geometric-mean/Futhark/arithmetic-geometric-mean.futhark index ccb89b197c..c11872e173 100644 --- a/Task/Arithmetic-geometric-mean/Futhark/arithmetic-geometric-mean.futhark +++ b/Task/Arithmetic-geometric-mean/Futhark/arithmetic-geometric-mean.futhark @@ -1,6 +1,11 @@ +import "futlib/math" + fun agm(a: f64, g: f64): f64 = let eps = 1.0E-16 - loop ((a,g)) = while abs(a-g) > eps do + loop ((a,g)) = while f64.abs(a-g) > eps do ((a+g) / 2.0, - sqrt64 (a*g)) + f64.sqrt (a*g)) in a + +fun main(x: f64, y: f64): f64 = + agm(x,y) diff --git a/Task/Arithmetic-geometric-mean/Go/arithmetic-geometric-mean-1.go b/Task/Arithmetic-geometric-mean/Go/arithmetic-geometric-mean-1.go deleted file mode 100644 index a5c08c09ef..0000000000 --- a/Task/Arithmetic-geometric-mean/Go/arithmetic-geometric-mean-1.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "fmt" - "math" -) - -const ε = 1e-14 - -func agm(a, g float64) float64 { - for math.Abs(a-g) > math.Abs(a)*ε { - a, g = (a+g)*.5, math.Sqrt(a*g) - } - return a -} - -func main() { - fmt.Println(agm(1, 1/math.Sqrt2)) -} diff --git a/Task/Arithmetic-geometric-mean/Go/arithmetic-geometric-mean-2.go b/Task/Arithmetic-geometric-mean/Go/arithmetic-geometric-mean-2.go deleted file mode 100644 index 278cd975a5..0000000000 --- a/Task/Arithmetic-geometric-mean/Go/arithmetic-geometric-mean-2.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "math" - "math/cmplx" -) - -const ε = 1e-14 - -func agm(a, g complex128) complex128 { - for cmplx.Abs(a-g) > cmplx.Abs(a)*ε { - a, g = (a+g)*.5, cmplx.Rect(math.Sqrt(cmplx.Abs(a)*cmplx.Abs(g)), - (cmplx.Phase(a)+cmplx.Phase(g))*.5) - } - return a -} - -func main() { - fmt.Println(agm(1, 1/math.Sqrt2)) -} diff --git a/Task/Arithmetic-geometric-mean/Java/arithmetic-geometric-mean.java b/Task/Arithmetic-geometric-mean/Java/arithmetic-geometric-mean.java index 936bf8f186..d9726be83a 100644 --- a/Task/Arithmetic-geometric-mean/Java/arithmetic-geometric-mean.java +++ b/Task/Arithmetic-geometric-mean/Java/arithmetic-geometric-mean.java @@ -1,25 +1,23 @@ /* + * Arithmetic-Geometric Mean of 1 & 1/sqrt(2) + * Brendan Shaklovitz + * 5/29/12 + */ +public class ArithmeticGeometricMean { - Arithmetic-Geometric Mean of 1 & 1/sqrt(2) - - Brendan Shaklovitz - 5/29/12 - -*/ - -public class ArithmeticMean { - public static void agm (double a, double g){ - double a1 = a; - double g1 = g; - while (Math.abs(a1-g1) >= Math.pow(10, -14)){ - double aTemp = (a1+g1)/2.0; - g1 = Math.sqrt(a1*g1); - a1 = aTemp; - } - System.out.println(a1); + public static double agm(double a, double g) { + double a1 = a; + double g1 = g; + while (Math.abs(a1 - g1) >= 1.0e-14) { + double arith = (a1 + g1) / 2.0; + double geom = Math.sqrt(a1 * g1); + a1 = arith; + g1 = geom; } + return a1; + } - public static void main(String[] args){ - agm(1,1/Math.sqrt(2)); - } + public static void main(String[] args) { + System.out.println(agm(1.0, 1.0 / Math.sqrt(2.0))); + } } diff --git a/Task/Arithmetic-geometric-mean/jq/arithmetic-geometric-mean-1.jq b/Task/Arithmetic-geometric-mean/Jq/arithmetic-geometric-mean-1.jq similarity index 100% rename from Task/Arithmetic-geometric-mean/jq/arithmetic-geometric-mean-1.jq rename to Task/Arithmetic-geometric-mean/Jq/arithmetic-geometric-mean-1.jq diff --git a/Task/Arithmetic-geometric-mean/jq/arithmetic-geometric-mean-2.jq b/Task/Arithmetic-geometric-mean/Jq/arithmetic-geometric-mean-2.jq similarity index 100% rename from Task/Arithmetic-geometric-mean/jq/arithmetic-geometric-mean-2.jq rename to Task/Arithmetic-geometric-mean/Jq/arithmetic-geometric-mean-2.jq diff --git a/Task/Arithmetic-geometric-mean/Kotlin/arithmetic-geometric-mean.kotlin b/Task/Arithmetic-geometric-mean/Kotlin/arithmetic-geometric-mean.kotlin new file mode 100644 index 0000000000..24004d272d --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Kotlin/arithmetic-geometric-mean.kotlin @@ -0,0 +1,19 @@ +// version 1.0.5-2 + +fun agm(a: Double, g: Double): Double { + var aa = a // mutable 'a' + var gg = g // mutable 'g' + var ta: Double // temporary variable to hold next iteration of 'aa' + val epsilon = 1.0e-16 // tolerance for checking if limit has been reached + + while (true) { + ta = (aa + gg) / 2.0 + if (Math.abs(aa - ta) <= epsilon) return ta + gg = Math.sqrt(aa * gg) + aa = ta + } +} + +fun main(args: Array) { + println(agm(1.0, 1.0 / Math.sqrt(2.0))) +} diff --git a/Task/Arithmetic-geometric-mean/Nim/arithmetic-geometric-mean-1.nim b/Task/Arithmetic-geometric-mean/Nim/arithmetic-geometric-mean-1.nim index dcc5f0f4ad..3b174afca9 100644 --- a/Task/Arithmetic-geometric-mean/Nim/arithmetic-geometric-mean-1.nim +++ b/Task/Arithmetic-geometric-mean/Nim/arithmetic-geometric-mean-1.nim @@ -11,4 +11,4 @@ proc agm(a, g: float,delta: float = 1.0e-15): float = aOld = aNew result = aOld -echo ($agm(1.0,1.0/sqrt(2))) +echo $agm(1.0,1.0/sqrt(2.0)) diff --git a/Task/Arithmetic-geometric-mean/Nim/arithmetic-geometric-mean-2.nim b/Task/Arithmetic-geometric-mean/Nim/arithmetic-geometric-mean-2.nim index 2f192cd8ca..01e35880f2 100644 --- a/Task/Arithmetic-geometric-mean/Nim/arithmetic-geometric-mean-2.nim +++ b/Task/Arithmetic-geometric-mean/Nim/arithmetic-geometric-mean-2.nim @@ -14,7 +14,7 @@ proc agm(x,y: float): tuple[resA,resG: float] = (a[23], g[23]) -var t = agm(1, 1/sqrt(2)) +var t = agm(1, 1/sqrt(2.0)) echo("Result A: " & formatFloat(t.resA, ffDecimal, 24)) echo("Result G: " & formatFloat(t.resG, ffDecimal, 24)) diff --git a/Task/Arithmetic-geometric-mean/Nimrod/arithmetic-geometric-mean.nimrod b/Task/Arithmetic-geometric-mean/Nimrod/arithmetic-geometric-mean.nimrod deleted file mode 100644 index dcc5f0f4ad..0000000000 --- a/Task/Arithmetic-geometric-mean/Nimrod/arithmetic-geometric-mean.nimrod +++ /dev/null @@ -1,14 +0,0 @@ -import math - -proc agm(a, g: float,delta: float = 1.0e-15): float = - var - aNew: float = 0 - aOld: float = a - gOld: float = g - while (abs(aOld - gOld) > delta): - aNew = 0.5 * (aOld + gOld) - gOld = sqrt(aOld * gOld) - aOld = aNew - result = aOld - -echo ($agm(1.0,1.0/sqrt(2))) diff --git a/Task/Arithmetic-geometric-mean/OoRexx/arithmetic-geometric-mean.rexx b/Task/Arithmetic-geometric-mean/OoRexx/arithmetic-geometric-mean.rexx new file mode 100644 index 0000000000..937ae0218e --- /dev/null +++ b/Task/Arithmetic-geometric-mean/OoRexx/arithmetic-geometric-mean.rexx @@ -0,0 +1,18 @@ +say agm(1, 1/rxcalcsqrt(2)) + +::routine agm + use strict arg a, g + numeric digits 20 + + a1 = a + g1 = g + + loop while abs(a1 - g1) >= 1e-14 + temp = (a1 + g1)/2 + g1 = rxcalcsqrt(a1 * g1) + a1 = temp + end + numeric digits 9 + return a1+0 + +::requires rxmath LIBRARY diff --git a/Task/Arithmetic-geometric-mean/Scheme/arithmetic-geometric-mean.ss b/Task/Arithmetic-geometric-mean/Scheme/arithmetic-geometric-mean.ss new file mode 100644 index 0000000000..de4db19700 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Scheme/arithmetic-geometric-mean.ss @@ -0,0 +1,10 @@ +(define agm + (case-lambda + ((a0 g0) ; call again with default value for tolerance + (agm a0 g0 1e-8)) + ((a0 g0 tolerance) ; called with three arguments + (do ((a a0 (* (+ a g) 1/2)) + (g g0 (sqrt (* a g)))) + ((< (abs (- a g)) tolerance) a))))) + +(display (agm 1 (/ 1 (sqrt 2)))) (newline) diff --git a/Task/Arithmetic-geometric-mean/SequenceL/arithmetic-geometric-mean.sequencel b/Task/Arithmetic-geometric-mean/SequenceL/arithmetic-geometric-mean.sequencel new file mode 100644 index 0000000000..57c272c0a7 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/SequenceL/arithmetic-geometric-mean.sequencel @@ -0,0 +1,13 @@ +import ; + +agm(a, g) := + let + iota := 1.0e-15; + arithmeticMean := 0.5 * (a + g); + geometricMean := sqrt(a * g); + in + a when abs(a-g) < iota + else + agm(arithmeticMean, geometricMean); + +main := agm(1.0, 1.0 / sqrt(2)); diff --git a/Task/Arithmetic-geometric-mean/Sidef/arithmetic-geometric-mean.sidef b/Task/Arithmetic-geometric-mean/Sidef/arithmetic-geometric-mean.sidef index da7db80329..4e39ef90dc 100644 --- a/Task/Arithmetic-geometric-mean/Sidef/arithmetic-geometric-mean.sidef +++ b/Task/Arithmetic-geometric-mean/Sidef/arithmetic-geometric-mean.sidef @@ -1,8 +1,8 @@ func agm(a, g) { loop { - var x = [float(a+g / 2), sqrt(a*g)] - x == [a, g] && return a - x >> \(a, g) + var (a1, g1) = ((a+g)/2, sqrt(a*g)) + [a1,g1] == [a,g] && return a + (a, g) = (a1, g1) } } diff --git a/Task/Arithmetic-geometric-mean/Sinclair-ZX81-BASIC/arithmetic-geometric-mean.sinclair b/Task/Arithmetic-geometric-mean/Sinclair-ZX81-BASIC/arithmetic-geometric-mean.sinclair new file mode 100644 index 0000000000..f303e9767b --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Sinclair-ZX81-BASIC/arithmetic-geometric-mean.sinclair @@ -0,0 +1,11 @@ + 10 LET A=1 + 20 LET G=1/SQR 2 + 30 GOSUB 100 + 40 PRINT AGM + 50 STOP +100 LET A0=A +110 LET A=(A+G)/2 +120 LET G=SQR (A0*G) +130 IF ABS(A-G)>.00000001 THEN GOTO 100 +140 LET AGM=A +150 RETURN diff --git a/Task/Arithmetic-geometric-mean/Stata/arithmetic-geometric-mean.stata b/Task/Arithmetic-geometric-mean/Stata/arithmetic-geometric-mean.stata new file mode 100644 index 0000000000..48e77f5b72 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Stata/arithmetic-geometric-mean.stata @@ -0,0 +1,14 @@ +mata + +real scalar agm(real scalar a, real scalar b) { + real scalar c + do { + c=0.5*(a+b) + b=sqrt(a*b) + a=c + } while (a-b>1e-15*a) + return(0.5*(a+b)) +} + +agm(1,1/sqrt(2)) +end diff --git a/Task/Arithmetic-geometric-mean/Swift/arithmetic-geometric-mean.swift b/Task/Arithmetic-geometric-mean/Swift/arithmetic-geometric-mean.swift new file mode 100644 index 0000000000..b427303a6b --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Swift/arithmetic-geometric-mean.swift @@ -0,0 +1,31 @@ +import Darwin + +enum AGRError : Error { + case undefined +} + +func agm(_ a: Double, _ g: Double, _ iota: Double = 1e-8) throws -> Double { + var a = a + var g = g + var a1: Double = 0 + var g1: Double = 0 + + guard a * g >= 0 else { + throw AGRError.undefined + } + + while abs(a - g) > iota { + a1 = (a + g) / 2 + g1 = sqrt(a * g) + a = a1 + g = g1 + } + + return a +} + +do { + try print(agm(1, 1 / sqrt(2))) +} catch { + print("agr is undefined when a * g < 0") +} diff --git a/Task/Arithmetic-geometric-mean/Zkl/arithmetic-geometric-mean-1.zkl b/Task/Arithmetic-geometric-mean/Zkl/arithmetic-geometric-mean-1.zkl new file mode 100644 index 0000000000..ab338d89cc --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Zkl/arithmetic-geometric-mean-1.zkl @@ -0,0 +1,5 @@ +a:=1.0; g:=1.0/(2.0).sqrt(); +while(not a.closeTo(g,1.0e-15)){ + a1:=(a+g)/2.0; g=(a*g).sqrt(); a=a1; + println(a," ",g," ",a-g); +} diff --git a/Task/Arithmetic-geometric-mean/Zkl/arithmetic-geometric-mean-2.zkl b/Task/Arithmetic-geometric-mean/Zkl/arithmetic-geometric-mean-2.zkl new file mode 100644 index 0000000000..0c2f15bf4b --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Zkl/arithmetic-geometric-mean-2.zkl @@ -0,0 +1,3 @@ +fcn(a=1.0, g=1.0/(2.0).sqrt()){ println(a," ",g," ",a-g); + if(a.closeTo(g,1.0e-15)) return(a) else return(self.fcn((a+g)/2.0, (a*g).sqrt())); +}() diff --git a/Task/Array-concatenation/ALGOL-W/array-concatenation.alg b/Task/Array-concatenation/ALGOL-W/array-concatenation.alg new file mode 100644 index 0000000000..c9e74abab2 --- /dev/null +++ b/Task/Array-concatenation/ALGOL-W/array-concatenation.alg @@ -0,0 +1,36 @@ +begin + integer array a ( 1 :: 5 ); + integer array b ( 2 :: 4 ); + integer array c ( 1 :: 8 ); + + % concatenates the arrays a and b into c % + % the lower and upper bounds of each array must be specified in % + % the corresponding *Lb and *Ub parameters % + procedure arrayConcatenate ( integer array a ( * ) + ; integer value aLb, aUb + ; integer array b ( * ) + ; integer value bLb, bUb + ; integer array c ( * ) + ; integer value cLb, cUb + ) ; + begin + integer cPos; + assert( ( cUb - cLb ) + 1 >= ( ( aUb + bUb ) - ( aLb + bLb ) ) - 2 ); + cPos := cLb; + for aPos := aLb until aUb do begin + c( cPos ) := a( aPos ); + cPos := cPos + 1 + end for_aPos ; + for bPos := bLb until bUb do begin + c( cPos ) := b( bPos ); + cPos := cPos + 1 + end for_bPos + end arrayConcatenate ; + + % test arrayConcatenate % + for aPos := 1 until 5 do a( aPos ) := aPos; + for bPos := 2 until 4 do b( bPos ) := - bPos; + arrayConcatenate( a, 1, 5, b, 2, 4, c, 1, 8 ); + for cPos := 1 until 8 do writeon( i_w := 1, s_w := 1, c( cPos ) ) + +end. diff --git a/Task/Array-concatenation/Aime/array-concatenation.aime b/Task/Array-concatenation/Aime/array-concatenation.aime new file mode 100644 index 0000000000..06b83614d4 --- /dev/null +++ b/Task/Array-concatenation/Aime/array-concatenation.aime @@ -0,0 +1,25 @@ +list +ac(list a, list b) +{ + list o; + + l_ucall(a, l_append, 1, o); + l_ucall(b, l_append, 1, o); + + return o; +} + +integer +main(void) +{ + list a, b, c; + + a = l_effect(1, 2, 3, 4); + b = l_effect(5, 6, 7, 8); + + c = ac(a, b); + + l_ucall(c, o_, 1, " "); + + return 0; +} diff --git a/Task/Array-concatenation/BASIC/array-concatenation-1.basic b/Task/Array-concatenation/BASIC/array-concatenation-1.basic new file mode 100644 index 0000000000..9de36e16de --- /dev/null +++ b/Task/Array-concatenation/BASIC/array-concatenation-1.basic @@ -0,0 +1,17 @@ +' Array concatenation +OPTION BASE 1 + +CONST asize = 2 +CONST bsize = 3 +DECLARE a[asize] TYPE NUMBER +DECLARE b[bsize] TYPE NUMBER + +' BaCon has no array concatenation builtin, it will need to be done by hand +LOCAL c TYPE NUMBER ARRAY asize + bsize +FOR i = 1 TO asize + c[i] = a[i] +NEXT + +FOR i = 1 TO bsize + c[asize + i] = b[i] +NEXT diff --git a/Task/Array-concatenation/BBC-BASIC/array-concatenation.bbc b/Task/Array-concatenation/BASIC/array-concatenation-2.basic similarity index 100% rename from Task/Array-concatenation/BBC-BASIC/array-concatenation.bbc rename to Task/Array-concatenation/BASIC/array-concatenation-2.basic diff --git a/Task/Array-concatenation/BASIC/array-concatenation-3.basic b/Task/Array-concatenation/BASIC/array-concatenation-3.basic new file mode 100644 index 0000000000..1e60291191 --- /dev/null +++ b/Task/Array-concatenation/BASIC/array-concatenation-3.basic @@ -0,0 +1,17 @@ +10 X=4 : Y=5 +20 DIM A(X) : DIM B(Y) : DIM C(X+Y) +30 FOR I=1 TO X +40 : A(I) = I +50 NEXT +60 FOR I=1 TO Y +70 : B(I) = I*10 +80 NEXT +90 FOR I=1 TO X +100 : C(I) = A(I) +110 NEXT +120 FOR I=1 TO Y +130 : C(X+I) = B(I) +140 NEXT +150 FOR I=1 TO X+Y +160 : PRINT C(I); +170 NEXT diff --git a/Task/Array-concatenation/C++/array-concatenation-3.cpp b/Task/Array-concatenation/C++/array-concatenation-3.cpp new file mode 100644 index 0000000000..58486246d0 --- /dev/null +++ b/Task/Array-concatenation/C++/array-concatenation-3.cpp @@ -0,0 +1,50 @@ +#include + +using namespace std; + +template +int* concatArrays( T1& array_1, T2& array_2) { + int arrayCount_1 = sizeof(array_1) / sizeof(array_1[0]); + int arrayCount_2 = sizeof(array_2) / sizeof(array_2[0]); + int newArraySize = arrayCount_1 + arrayCount_2; + + int *p = new int[newArraySize]; + + for (int i = 0; i < arrayCount_1; i++) { + p[i] = array_1[i]; + } + + for (int i = arrayCount_1; i < newArraySize; i++) { + int newIndex = i-arrayCount_2; + + if (newArraySize % 2 == 1) + newIndex--; + + p[i] = array_2[newIndex]; + cout << "i: " << i << endl; + cout << "array_2[i]: " << array_2[newIndex] << endl; + cout << endl; + } + + return p; +} + +int main() { + + int ary[4] = {1, 2, 3, 123}; + int anotherAry[3] = {4, 5, 6}; + + int *r = concatArrays(ary, anotherAry); + + cout << *(r + 0) << endl; + cout << *(r + 1) << endl; + cout << *(r + 2) << endl; + cout << *(r + 3) << endl; + cout << *(r + 4) << endl; + cout << *(r + 5) << endl; + cout << *(r + 6) << endl; + + delete r; + + return 0; +} diff --git a/Task/Array-concatenation/Elena/array-concatenation.elena b/Task/Array-concatenation/Elena/array-concatenation.elena index 81a9217c2e..759689788b 100644 --- a/Task/Array-concatenation/Elena/array-concatenation.elena +++ b/Task/Array-concatenation/Elena/array-concatenation.elena @@ -1,10 +1,9 @@ -#define system. -#define extensions. +import extensions. -#symbol program = +program = [ - #var a := (1,2,3). - #var b := (4,5). + var a := (1,2,3). + var b := (4,5). - console writeLine:"(":a:") + (":b:") = (":(a + b):")". + console printLine("(",a,") + (",b,") = (",a + b,")"); readChar. ]. diff --git a/Task/Array-concatenation/Gambas/array-concatenation.gambas b/Task/Array-concatenation/Gambas/array-concatenation.gambas new file mode 100644 index 0000000000..2d0e876112 --- /dev/null +++ b/Task/Array-concatenation/Gambas/array-concatenation.gambas @@ -0,0 +1,9 @@ +Public Sub Main() +Dim sString1 As String[] = ["The", "quick", "brown", "fox"] +Dim sString2 As String[] = ["jumped", "over", "the", "lazy", "dog"] + +sString1.Insert(sString2) + +Print sString1.Join(" ") + +End diff --git a/Task/Array-concatenation/Hy/array-concatenation.hy b/Task/Array-concatenation/Hy/array-concatenation.hy new file mode 100644 index 0000000000..9b852d7ce1 --- /dev/null +++ b/Task/Array-concatenation/Hy/array-concatenation.hy @@ -0,0 +1,15 @@ +=> (setv a [1 2 3]) +=> a +[1, 2, 3] + +=> (+ a [4 5 6]) ; returns the concatenation +[1, 2, 3, 4, 5, 6] +=> a +[1, 2, 3] + +=> (.extend a [7 8 9]) ; modifies the list in place +=> a +[1, 2, 3, 7, 8, 9] + +=> (+ [1 2] [3 4] [5 6]) ; can accept multiple arguments +[1, 2, 3, 4, 5, 6] diff --git a/Task/Array-concatenation/Java/array-concatenation-1.java b/Task/Array-concatenation/Java/array-concatenation-1.java deleted file mode 100644 index 4b3142be3f..0000000000 --- a/Task/Array-concatenation/Java/array-concatenation-1.java +++ /dev/null @@ -1,9 +0,0 @@ -public static Object[] objArrayConcat(Object[] o1, Object[] o2) -{ - Object[] ret = new Object[o1.length + o2.length]; - - System.arraycopy(o1, 0, ret, 0, o1.length); - System.arraycopy(o2, 0, ret, o1.length, o2.length); - - return ret; -} diff --git a/Task/Array-concatenation/Java/array-concatenation-2.java b/Task/Array-concatenation/Java/array-concatenation-2.java deleted file mode 100644 index 75354919cd..0000000000 --- a/Task/Array-concatenation/Java/array-concatenation-2.java +++ /dev/null @@ -1,4 +0,0 @@ -Collection list1, list2, list1And2; -//...list1 and list2 are instantiated... -list1And2 = new ArrayList(list1); //or any other Collection you want -list1And2.addAll(list2); diff --git a/Task/Array-concatenation/Java/array-concatenation.java b/Task/Array-concatenation/Java/array-concatenation.java new file mode 100644 index 0000000000..eb89cdf678 --- /dev/null +++ b/Task/Array-concatenation/Java/array-concatenation.java @@ -0,0 +1,8 @@ +public static Object[] concat(Object[] arr1, Object[] arr2) { + Object[] res = new Object[arr1.length + arr2.length]; + + System.arraycopy(arr1, 0, res, 0, arr1.length); + System.arraycopy(arr2, 0, res, arr1.length, arr2.length); + + return res; +} diff --git a/Task/Array-concatenation/jq/array-concatenation.jq b/Task/Array-concatenation/Jq/array-concatenation.jq similarity index 100% rename from Task/Array-concatenation/jq/array-concatenation.jq rename to Task/Array-concatenation/Jq/array-concatenation.jq diff --git a/Task/Array-concatenation/Julia/array-concatenation.julia b/Task/Array-concatenation/Julia/array-concatenation.julia index b7aa341da9..2221e3eb45 100644 --- a/Task/Array-concatenation/Julia/array-concatenation.julia +++ b/Task/Array-concatenation/Julia/array-concatenation.julia @@ -1,6 +1,6 @@ a = [1,2,3] b = [4,5,6] -ab = [a,b] +ab = [a;b] # the above bracket notation simply generates a call to vcat ab = vcat(a,b) # hcat is short for `horizontal concatenation` diff --git a/Task/Array-concatenation/Kotlin/array-concatenation-1.kotlin b/Task/Array-concatenation/Kotlin/array-concatenation-1.kotlin index 11765a0be6..c0164b628d 100644 --- a/Task/Array-concatenation/Kotlin/array-concatenation-1.kotlin +++ b/Task/Array-concatenation/Kotlin/array-concatenation-1.kotlin @@ -1,3 +1,6 @@ -val a : Array = // initialise a -val b : Array = // initialise b -val c = (a.toList() + b.toList()).copyToArray() +fun main(args: Array) { + val a: Array = arrayOf(1, 2, 3) // initialise a + val b: Array = arrayOf(4, 5, 6) // initialise b + val c: Array = (a.toList() + b.toList()).toTypedArray() + println(c) +} diff --git a/Task/Array-concatenation/Kotlin/array-concatenation-2.kotlin b/Task/Array-concatenation/Kotlin/array-concatenation-2.kotlin index db0f06a642..4ee0dd0a58 100644 --- a/Task/Array-concatenation/Kotlin/array-concatenation-2.kotlin +++ b/Task/Array-concatenation/Kotlin/array-concatenation-2.kotlin @@ -1,2 +1,3 @@ -fun arrayConcat(a : Array, b : Array) - = Array(a.size + b.size, {if (it in a.indices) a[it] else b[it - a.size]}) +fun arrayConcat(a: Array, b: Array): Array { + return Array(a.size + b.size, { if (it in a.indices) a[it] else b[it - a.size] }) +} diff --git a/Task/Array-concatenation/Kotlin/array-concatenation-3.kotlin b/Task/Array-concatenation/Kotlin/array-concatenation-3.kotlin index 95abc6a59b..9b60953853 100644 --- a/Task/Array-concatenation/Kotlin/array-concatenation-3.kotlin +++ b/Task/Array-concatenation/Kotlin/array-concatenation-3.kotlin @@ -1,3 +1,6 @@ -val a : Collection // initialise a -val b : Collection = // initialise b -val c : Collection = a + b +fun main(args: Array) { + val a: Collection = listOf(1, 2, 3) // initialise a + val b: Collection = listOf(4, 5, 6) // initialise b + val c: Collection = a + b + println(c) +} diff --git a/Task/Array-concatenation/OoRexx/array-concatenation.rexx b/Task/Array-concatenation/OoRexx/array-concatenation.rexx new file mode 100644 index 0000000000..fe97a5ca7a --- /dev/null +++ b/Task/Array-concatenation/OoRexx/array-concatenation.rexx @@ -0,0 +1,6 @@ +a = .array~of(1,2,3) +say "Array a has " a~items "items" +b = .array~of(4,5,6) +say "Array b has " b~items "items" +a~appendall(b) -- adds all items from b to a +say "Array a now has " a~items " diff --git a/Task/Array-concatenation/S-lang/array-concatenation-1.slang b/Task/Array-concatenation/S-lang/array-concatenation-1.slang index 105f2c29b2..b58f0b2bbf 100644 --- a/Task/Array-concatenation/S-lang/array-concatenation-1.slang +++ b/Task/Array-concatenation/S-lang/array-concatenation-1.slang @@ -1,2 +1,2 @@ variable a = [1, 2, 3]; -variable b = [4, 5, 6]; +variable b = [4, 5, 6], c; diff --git a/Task/Array-concatenation/S-lang/array-concatenation-2.slang b/Task/Array-concatenation/S-lang/array-concatenation-2.slang index b0087cb349..08f3d30a67 100644 --- a/Task/Array-concatenation/S-lang/array-concatenation-2.slang +++ b/Task/Array-concatenation/S-lang/array-concatenation-2.slang @@ -1,3 +1 @@ -variable la = length(a), c = _typeof(a)[la+length(b)]; -c[ [:la-1] ] = a; -c[ [la:] ] = b; +c = [a, b]; diff --git a/Task/Array-concatenation/S-lang/array-concatenation-3.slang b/Task/Array-concatenation/S-lang/array-concatenation-3.slang index 059d4ecdba..d5797b22d2 100644 --- a/Task/Array-concatenation/S-lang/array-concatenation-3.slang +++ b/Task/Array-concatenation/S-lang/array-concatenation-3.slang @@ -1,4 +1,3 @@ a = {1, 2, 3}; b = {4, 5, 6}; - -variable c = list_concat(a, b); +c = list_concat(a, b); diff --git a/Task/Array-concatenation/S-lang/array-concatenation-4.slang b/Task/Array-concatenation/S-lang/array-concatenation-4.slang index 4ac36280cd..cde255b214 100644 --- a/Task/Array-concatenation/S-lang/array-concatenation-4.slang +++ b/Task/Array-concatenation/S-lang/array-concatenation-4.slang @@ -1 +1 @@ -c = list_to_array(c); +list_join(a, b); diff --git a/Task/Array-concatenation/S-lang/array-concatenation-5.slang b/Task/Array-concatenation/S-lang/array-concatenation-5.slang deleted file mode 100644 index cde255b214..0000000000 --- a/Task/Array-concatenation/S-lang/array-concatenation-5.slang +++ /dev/null @@ -1 +0,0 @@ -list_join(a, b); diff --git a/Task/Array-concatenation/Simula/array-concatenation.simula b/Task/Array-concatenation/Simula/array-concatenation.simula new file mode 100644 index 0000000000..5b60f006e4 --- /dev/null +++ b/Task/Array-concatenation/Simula/array-concatenation.simula @@ -0,0 +1,50 @@ +BEGIN + + CLASS ARRAYHOLDER(N); INTEGER N; + BEGIN + REAL ARRAY DATA(1:N); + END; + + REF(ARRAYHOLDER) PROCEDURE CONCAT(A, B); REF(ARRAYHOLDER) A, B; + BEGIN + REF(ARRAYHOLDER) C; + INTEGER I, J; + + C :- NEW ARRAYHOLDER(A.N + B.N); + + FOR I := 1 STEP 1 UNTIL A.N DO + BEGIN + J := J+1; C.DATA(J) := A.DATA(I); + END; + + FOR I := 1 STEP 1 UNTIL B.N DO + BEGIN + J := J+1; C.DATA(J) := B.DATA(I); + END; + + CONCAT :- C; + END; + + REF(ARRAYHOLDER) X, Y, Z; + INTEGER I; + + X :- NEW ARRAYHOLDER(3); + Y :- NEW ARRAYHOLDER(4); + + I := 0; + I := I+1; X.DATA(I) := 2*I; + I := I+1; X.DATA(I) := 2*I; + I := I+1; X.DATA(I) := 2*I; + + I := 0; + I := I+1; Y.DATA(I) := -3*I; + I := I+1; Y.DATA(I) := -3*I; + I := I+1; Y.DATA(I) := -3*I; + I := I+1; Y.DATA(I) := -3*I; + + Z :- CONCAT(X, Y); + FOR I := 1 STEP 1 UNTIL Z.N DO + OUTFIX(Z.DATA(I), 2, 7); + OUTIMAGE; + +END. diff --git a/Task/Array-concatenation/Stata/array-concatenation-1.stata b/Task/Array-concatenation/Stata/array-concatenation-1.stata new file mode 100644 index 0000000000..8c99c94bbf --- /dev/null +++ b/Task/Array-concatenation/Stata/array-concatenation-1.stata @@ -0,0 +1,38 @@ +. matrix a=2,9,4\7,5,3\6,1,8 +. matrix list a + +a[3,3] + c1 c2 c3 +r1 2 9 4 +r2 7 5 3 +r3 6 1 8 + +. matrix b=I(3) +. matrix list b + +symmetric b[3,3] + c1 c2 c3 +r1 1 +r2 0 1 +r3 0 0 1 + +. matrix c=a,b +. matrix list c + +c[3,6] + c1 c2 c3 c1 c2 c3 +r1 2 9 4 1 0 0 +r2 7 5 3 0 1 0 +r3 6 1 8 0 0 1 + +. matrix c=a\b +. matrix list c + +c[6,3] + c1 c2 c3 +r1 2 9 4 +r2 7 5 3 +r3 6 1 8 +r1 1 0 0 +r2 0 1 0 +r3 0 0 1 diff --git a/Task/Array-concatenation/Stata/array-concatenation-2.stata b/Task/Array-concatenation/Stata/array-concatenation-2.stata new file mode 100644 index 0000000000..a7576287ee --- /dev/null +++ b/Task/Array-concatenation/Stata/array-concatenation-2.stata @@ -0,0 +1,25 @@ +. mata +: a=2,9,4\7,5,3\6,1,8 + +: b=I(3) + +: a,b + 1 2 3 4 5 6 + +-------------------------+ + 1 | 2 9 4 1 0 0 | + 2 | 7 5 3 0 1 0 | + 3 | 6 1 8 0 0 1 | + +-------------------------+ + +: a\b + 1 2 3 + +-------------+ + 1 | 2 9 4 | + 2 | 7 5 3 | + 3 | 6 1 8 | + 4 | 1 0 0 | + 5 | 0 1 0 | + 6 | 0 0 1 | + +-------------+ + +: end diff --git a/Task/Array-concatenation/Zkl/array-concatenation.zkl b/Task/Array-concatenation/Zkl/array-concatenation.zkl new file mode 100644 index 0000000000..9c8c00f97e --- /dev/null +++ b/Task/Array-concatenation/Zkl/array-concatenation.zkl @@ -0,0 +1,2 @@ +T(1,2).extend(T(4,5,6)) //-->L(1,2,4,5,6) +T(1,2).extend(4,5,6) //-->L(1,2,4,5,6) diff --git a/Task/Arrays/ALGOL-68/arrays-1.alg b/Task/Arrays/ALGOL-68/arrays-1.alg deleted file mode 100644 index 292c29921a..0000000000 --- a/Task/Arrays/ALGOL-68/arrays-1.alg +++ /dev/null @@ -1,20 +0,0 @@ -PROC array_test = VOID: -( - [1:20]INT a; - a := others; # assign whole array # - a[1] := -1; # assign individual element # - a[3:5] := (2, 4, -1); # assign a slice # - [1:3]INT slice = a[3:5]; # copy a slice # - - REF []INT rslice = a[3:5]; # create a reference to a slice # - print((LWB rslice, UPB slice)); # query the bounds of the slice # - rslice := (2, 4, -1); # assign to the slice, modifying original array # - - [1:3, 1:3]INT matrix; # create a two dimensional array # - REF []INT hvector = matrix[2,]; # create a reference to a row # - REF []INT vvector = matrix[,2]; # create a reference to a column # - REF [,]INT block = matrix[1:2, 1:2]; # create a reference to an area of the array # - - FLEX []CHAR string := "Hello, world!"; # create an array with variable bounds # - string := "shorter" # flexible arrays automatically resize themselves on assignment # -) diff --git a/Task/Arrays/ALGOL-68/arrays-2.alg b/Task/Arrays/ALGOL-68/arrays-2.alg deleted file mode 100644 index 439a7cb94a..0000000000 --- a/Task/Arrays/ALGOL-68/arrays-2.alg +++ /dev/null @@ -1,17 +0,0 @@ -DEF ai[100] : ARRAY OF CHAR, -> static - da: PTR TO CHAR, - la: PTR TO CHAR - -PROC main() - da := New(100) - -> or - NEW la[100] - IF da <> NIL - ai[0] := da[0] -> first is 0 - ai[99] := da[99] -> last is "size"-1 - Dispose(da) - ENDIF - -> using NEW, we must specify the size even when - -> "deallocating" the array - IF la <> NIL THEN END la[100] -ENDPROC diff --git a/Task/Arrays/ALGOL-68/arrays-3.alg b/Task/Arrays/ALGOL-68/arrays-3.alg deleted file mode 100644 index 0935326261..0000000000 --- a/Task/Arrays/ALGOL-68/arrays-3.alg +++ /dev/null @@ -1,2 +0,0 @@ - set empty to {} - set ints to {1, 2, 3} diff --git a/Task/Arrays/ALGOL-68/arrays-4.alg b/Task/Arrays/ALGOL-68/arrays-4.alg deleted file mode 100644 index da6037a43c..0000000000 --- a/Task/Arrays/ALGOL-68/arrays-4.alg +++ /dev/null @@ -1 +0,0 @@ - set any to {1, "foo", 2.57, missing value, ints} diff --git a/Task/Arrays/ALGOL-W/arrays.alg b/Task/Arrays/ALGOL-W/arrays.alg new file mode 100644 index 0000000000..86918a2cfe --- /dev/null +++ b/Task/Arrays/ALGOL-W/arrays.alg @@ -0,0 +1,18 @@ +begin + % declare an array % + integer array a ( 1 :: 10 ); + % set the values % + for i := 1 until 10 do a( i ) := i; + % change the 3rd element % + a( 3 ) := 27; + % display the 4th element % + write( a( 4 ) ); % would show 4 % + % arrays with sizes not known at compile-time must be created in inner-blocks or procedures % + begin + integer array b ( a( 3 ) - 2 :: a( 3 ) ); % b has bounds 25 :: 27 % + for i := a( 3 ) - 2 until a( 3 ) do b( i ) := i + end + % arrays cannot be part of records and cannot be returned by procecures though they can be passed % + % as parameters to procedures % + % multi-dimension arrays are supported % +end. diff --git a/Task/Arrays/BASIC/arrays-8.basic b/Task/Arrays/BASIC/arrays-8.basic index fe19328a03..2a7d10dfb9 100644 --- a/Task/Arrays/BASIC/arrays-8.basic +++ b/Task/Arrays/BASIC/arrays-8.basic @@ -1,9 +1,5 @@ -REDIM dynamicArray(10) AS INTEGER - -dynamicArray(0) = -1 -PRINT dynamicArray(0) - -REDIM dynamicArray(20) - -dynamicArray(20) = 1 -PRINT dynamicArray(0), dynamicArray(20) +10 DIM A%(11): REM ARRAY OF ELEVEN INTEGER ELEMENTS +20 LET A%(1) = -1 +30 LET A%(11) = 1 +40 PRINT A%(1), A%(11) +50 END diff --git a/Task/Arrays/BASIC/arrays-9.basic b/Task/Arrays/BASIC/arrays-9.basic new file mode 100644 index 0000000000..fe19328a03 --- /dev/null +++ b/Task/Arrays/BASIC/arrays-9.basic @@ -0,0 +1,9 @@ +REDIM dynamicArray(10) AS INTEGER + +dynamicArray(0) = -1 +PRINT dynamicArray(0) + +REDIM dynamicArray(20) + +dynamicArray(20) = 1 +PRINT dynamicArray(0), dynamicArray(20) diff --git a/Task/Arrays/Bc/arrays.bc b/Task/Arrays/Bc/arrays.bc new file mode 100644 index 0000000000..c234f42d09 --- /dev/null +++ b/Task/Arrays/Bc/arrays.bc @@ -0,0 +1,18 @@ +/* Put the value 42 into array g at index 3 */ +g[3] = 42 +/* Look at some other elements in g */ +g[2] +0 +g[4342] +0 +/* Look at the elements of another array */ +a[543] +0 +/* Array names don't conflict with names of ordinary (scalar) identifiers */ +g +0 +g = 123 +g +123 +g[3] +42 diff --git a/Task/Arrays/C++/arrays-1.cpp b/Task/Arrays/C++/arrays-1.cpp deleted file mode 100644 index 5170b61377..0000000000 --- a/Task/Arrays/C++/arrays-1.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include -#include -#include - -int main() { - std::array words = {"One", "Four", "Eight"}; - words[2] = "Three"; - words.at(1) = "Two"; - - std::reverse(words.begin(), words.end()); - - for(auto& word: words) std::cout << word << " "; - std::cout << std::endl; - - return 0; -} diff --git a/Task/Arrays/C++/arrays-2.cpp b/Task/Arrays/C++/arrays-2.cpp deleted file mode 100644 index daf8076357..0000000000 --- a/Task/Arrays/C++/arrays-2.cpp +++ /dev/null @@ -1,4 +0,0 @@ - // Qt - QVector myArray4(10); - myArray4.push_back(1); - myArray4.push_back(2); diff --git a/Task/Arrays/C++/arrays-3.cpp b/Task/Arrays/C++/arrays-3.cpp deleted file mode 100644 index 27f88be34e..0000000000 --- a/Task/Arrays/C++/arrays-3.cpp +++ /dev/null @@ -1,4 +0,0 @@ - // MFC - CArray myArray5(10); - myArray5.Add(1); - myArray5.Add(2); diff --git a/Task/Arrays/C++/arrays-4.cpp b/Task/Arrays/C++/arrays-4.cpp deleted file mode 100644 index 6c52abd0c0..0000000000 --- a/Task/Arrays/C++/arrays-4.cpp +++ /dev/null @@ -1,6 +0,0 @@ -int myArray[2]; - -myArray[0] = 1; -myArray[1] = 3; - -cout << myArray[1] << endl; diff --git a/Task/Arrays/C++/arrays-5.cpp b/Task/Arrays/C++/arrays-5.cpp deleted file mode 100644 index 41d3fd046a..0000000000 --- a/Task/Arrays/C++/arrays-5.cpp +++ /dev/null @@ -1,7 +0,0 @@ -int* myArray = new int[10]; - -myArray[0] = 1; -myArray[1] = 3; - -cout << myArray[1] << endl; -delete [] myArray; diff --git a/Task/Arrays/C++/arrays-6.cpp b/Task/Arrays/C++/arrays-6.cpp deleted file mode 100644 index b5119b9644..0000000000 --- a/Task/Arrays/C++/arrays-6.cpp +++ /dev/null @@ -1,8 +0,0 @@ -vector myArray2; - -myArray2.push_back(1); -myArray2.push_back(3); - -myArray2[0] = 2; - -cout << myArray2[0] << endl; diff --git a/Task/Arrays/C++/arrays-7.cpp b/Task/Arrays/C++/arrays-7.cpp deleted file mode 100644 index f753436759..0000000000 --- a/Task/Arrays/C++/arrays-7.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include -using std::cout; -using std::endl; - -#include -#include -#include - -int main() -{ - boost::array A; - A[0] = 5; // not bounds checked - A[1] = 2; - A.at(2) = 3; // this is bounds checked. - - cout << A[0] << endl; // not bounds checked - - for (int i =0; i < 3; ++i) { - cout << A.at(i) << endl; // this is bounds checked - } - - // use it as you would any STL ordered container. - std::reverse(A.begin(),A.end()); - BOOST_FOREACH(int i, A){cout << i << endl;} -} diff --git a/Task/Arrays/C-sharp/arrays-10.cs b/Task/Arrays/C-sharp/arrays-10.cs deleted file mode 100644 index ca083e8e46..0000000000 --- a/Task/Arrays/C-sharp/arrays-10.cs +++ /dev/null @@ -1,2 +0,0 @@ -array :: {Real} -array = createArray 10 3.1415 diff --git a/Task/Arrays/C-sharp/arrays-11.cs b/Task/Arrays/C-sharp/arrays-11.cs deleted file mode 100644 index 9795c01b26..0000000000 --- a/Task/Arrays/C-sharp/arrays-11.cs +++ /dev/null @@ -1,2 +0,0 @@ -array :: {Int} -array = {x \\ x <- [1 .. 10]} diff --git a/Task/Arrays/C-sharp/arrays-12.cs b/Task/Arrays/C-sharp/arrays-12.cs deleted file mode 100644 index 85a7bd4f92..0000000000 --- a/Task/Arrays/C-sharp/arrays-12.cs +++ /dev/null @@ -1,2 +0,0 @@ -array :: {!Int} -array = {x \\ x <- [1 .. 10]} diff --git a/Task/Arrays/C-sharp/arrays-13.cs b/Task/Arrays/C-sharp/arrays-13.cs deleted file mode 100644 index d4967f4131..0000000000 --- a/Task/Arrays/C-sharp/arrays-13.cs +++ /dev/null @@ -1,2 +0,0 @@ -array :: {#Char} -array = {x \\ x <- ['a' .. 'z']} diff --git a/Task/Arrays/C-sharp/arrays-9.cs b/Task/Arrays/C-sharp/arrays-9.cs deleted file mode 100644 index fac6242999..0000000000 --- a/Task/Arrays/C-sharp/arrays-9.cs +++ /dev/null @@ -1,2 +0,0 @@ -array :: {String} -array = {"Hello", "World"} diff --git a/Task/Arrays/CoffeeScript/arrays-1.coffee b/Task/Arrays/CoffeeScript/arrays-1.coffee deleted file mode 100644 index 6ab2780268..0000000000 --- a/Task/Arrays/CoffeeScript/arrays-1.coffee +++ /dev/null @@ -1,8 +0,0 @@ -array1 = [] -array1[0] = "Dillenidae" -array1[1] = "animus" -array1[2] = "Kona" -alert "Elements of array1: " + array1 # Dillenidae,animus,Kona - -array2 = ["Cepphus", "excreta", "Gansu"] -alert "Value of array2[1]: " + array2[1] # excreta diff --git a/Task/Arrays/CoffeeScript/arrays-2.coffee b/Task/Arrays/CoffeeScript/arrays-2.coffee deleted file mode 100644 index 3e5facdbce..0000000000 --- a/Task/Arrays/CoffeeScript/arrays-2.coffee +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Task/Arrays/CoffeeScript/arrays-3.coffee b/Task/Arrays/CoffeeScript/arrays-3.coffee deleted file mode 100644 index 6d9de17cfa..0000000000 --- a/Task/Arrays/CoffeeScript/arrays-3.coffee +++ /dev/null @@ -1,3 +0,0 @@ - - arr2 = ArrayNew(2); - diff --git a/Task/Arrays/Elena/arrays-1.elena b/Task/Arrays/Elena/arrays-1.elena index 2f60eb4e09..8bf308e65c 100644 --- a/Task/Arrays/Elena/arrays-1.elena +++ b/Task/Arrays/Elena/arrays-1.elena @@ -1 +1 @@ - #var aStaticArray := (1, 2, 3). + var aStaticArray := (1, 2, 3). diff --git a/Task/Arrays/Elena/arrays-2.elena b/Task/Arrays/Elena/arrays-2.elena index b69959e9cc..3b1e3b382c 100644 --- a/Task/Arrays/Elena/arrays-2.elena +++ b/Task/Arrays/Elena/arrays-2.elena @@ -1,4 +1,4 @@ - #var anArray := system'Array new &length:3. - anArray@0 := 1. - anArray@1 := 2. - anArray@2 := 3. + var anArray := system'Array new:3. + anArray[0] := 1. + anArray[1] := 2. + anArray[2] := 3. diff --git a/Task/Arrays/Elena/arrays-3.elena b/Task/Arrays/Elena/arrays-3.elena index ec27ea0589..6eb16c2699 100644 --- a/Task/Arrays/Elena/arrays-3.elena +++ b/Task/Arrays/Elena/arrays-3.elena @@ -1,4 +1,4 @@ - #var(int:3)aStackAllocatedArray. - aStackAllocatedArray@0 := 1. - aStackAllocatedArray@1 := 2. - aStackAllocatedArray@2 := 3. + int[] aStackAllocatedArray(3). + aStackAllocatedArray[0] := 1. + aStackAllocatedArray[1] := 2. + aStackAllocatedArray[2] := 3. diff --git a/Task/Arrays/Elena/arrays-4.elena b/Task/Arrays/Elena/arrays-4.elena index c95883669a..f2b5fd4874 100644 --- a/Task/Arrays/Elena/arrays-4.elena +++ b/Task/Arrays/Elena/arrays-4.elena @@ -1,6 +1,6 @@ - #var aDynamicArray := ArrayList new. + var aDynamicArray := ArrayList new. aDynamicArray += 1. aDynamicArray += 2. aDynamicArray += 4. - aDynamicArray@2 := 3. + aDynamicArray[2] := 3. diff --git a/Task/Arrays/Elena/arrays-5.elena b/Task/Arrays/Elena/arrays-5.elena index a7542b22a3..3068567ede 100644 --- a/Task/Arrays/Elena/arrays-5.elena +++ b/Task/Arrays/Elena/arrays-5.elena @@ -1,3 +1,3 @@ - system'console writeLine:(anArray@0). - system'console writeLine:(aStackAllocatedArray@1). - system'console writeLine:(aDynamicArray@2). + system'console writeLine(anArray[0]). + system'console writeLine(aStackAllocatedArray[1]). + system'console writeLine(aDynamicArray[2]). diff --git a/Task/Arrays/FBSL/arrays.fbsl b/Task/Arrays/FBSL/arrays.fbsl deleted file mode 100644 index 68a5fc3110..0000000000 --- a/Task/Arrays/FBSL/arrays.fbsl +++ /dev/null @@ -1,41 +0,0 @@ -#APPTYPE CONSOLE - -DIM v[-1 TO 1] ' static Variant -v[-1] = -1 -v[0] = "zero" -v[1] = !1.0 -FOREACH DIM e IN v - PRINT e, " "; -NEXT -PRINT - -DIM i[-1 TO 1] AS INTEGER ' static strong-type Integer/Single/Double/String -i[-1] = -1 -i[0] = "zero" -i[1] = !1 -FOREACH e IN i - PRINT e, " "; -NEXT -PRINT - -DIM d[] AS INTEGER ' dynamic strong-type Integer/Single/Double/String -d[] = -1 -d[] = "zero" -d[] = !1 -FOREACH e IN d - PRINT e, " "; -NEXT -PRINT - -DIM a[] = {-1, "zero", !1} ' dynamic Variant w/ anonymous array initialization -FOREACH e IN a - PRINT e, " "; -NEXT -PRINT - -FOREACH e IN {-1, "zero", !1} ' anonymous Variant - PRINT e, " "; -NEXT -PRINT - -PAUSE diff --git a/Task/Arrays/Gambas/arrays.gambas b/Task/Arrays/Gambas/arrays-1.gambas similarity index 100% rename from Task/Arrays/Gambas/arrays.gambas rename to Task/Arrays/Gambas/arrays-1.gambas diff --git a/Task/Arrays/Gambas/arrays-2.gambas b/Task/Arrays/Gambas/arrays-2.gambas new file mode 100644 index 0000000000..7efcd41855 --- /dev/null +++ b/Task/Arrays/Gambas/arrays-2.gambas @@ -0,0 +1,19 @@ +Public Sub Main() +Dim sFixedArray As String[] = ["Rosetta", "code", "is", "a", "programming", "chrestomathy", "site"] +Dim sFixedArray1 As New String[10] +Dim iDynamicArray As New Integer[] +Dim siCount As Short + +For siCount = 1 To 10 + iDynamicArray.Add(siCount) +Next + +sFixedArray1[5] = "Hello" +sFixedArray1[6] = " world!" + +Print sFixedArray.Join(" ") +Print iDynamicArray[5] + +Print sFixedArray1[5] & sFixedArray1[6] + +End diff --git a/Task/Arrays/Halon/arrays.halon b/Task/Arrays/Halon/arrays.halon new file mode 100644 index 0000000000..28a24570ee --- /dev/null +++ b/Task/Arrays/Halon/arrays.halon @@ -0,0 +1,9 @@ +$array = []; + +$array[] = 1; +$array["key"] = 3; + +$array[0] = 2; + +echo $array[0]; +echo $array["key"]; diff --git a/Task/Arrays/HicEst/arrays-1.hicest b/Task/Arrays/HicEst/arrays-1.hicest deleted file mode 100644 index 410727cc4f..0000000000 --- a/Task/Arrays/HicEst/arrays-1.hicest +++ /dev/null @@ -1,11 +0,0 @@ -REAL :: n = 3, Astat(n), Bdyn(1, 1) - -Astat(2) = 2.22222222 -WRITE(Messagebox, Name) Astat(2) - -ALLOCATE(Bdyn, 2*n, 3*n) -Bdyn(n-1, n) = -123 -WRITE(Row=27) Bdyn(n-1, n) - -ALIAS(Astat, n-1, last2ofAstat, 2) -WRITE(ClipBoard) last2ofAstat ! 2.22222222 0 diff --git a/Task/Arrays/HicEst/arrays-2.hicest b/Task/Arrays/HicEst/arrays-2.hicest deleted file mode 100644 index ae65dbdff8..0000000000 --- a/Task/Arrays/HicEst/arrays-2.hicest +++ /dev/null @@ -1,98 +0,0 @@ -record aThing(a, b, c) # arbitrary object (record or class) for illustration - -procedure main() - A0 := [] # empty list - A0 := list() # empty list (default size 0) - A0 := list(0) # empty list (literal size 0) - - A1 := list(10) # 10 elements, default initializer &null - A2 := list(10, 1) # 10 elements, initialized to 1 - - # literal array construction - arbitrary dynamically typed members - A3 := [1, 2, 3, ["foo", "bar", "baz"], aThing(1, 2, 3), "the end"] - - # left-end workers - # NOTE: get() is a synonym for pop() which allows nicely-worded use of put() and get() to implement queues - # - Q := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - x := pop(A0) # x is 1 - x := get(A0) # x is 2 - push(Q,0) - # Q is now [0,3, 4, 5, 6, 7, 8, 9, 10] - - # right-end workers - x := pull(Q) # x is 10 - put(Q, 100) # Q is now [0, 3, 4, 5, 6, 7, 8, 9, 100] - - # push and put return the list they are building - # they also can have multiple arguments which work like repeated calls - - Q2 := put([],1,2,3) # Q2 is [1,2,3] - Q3 := push([],1,2,3) # Q3 is [3,2,1] - Q4 := push(put(Q2),4),0] # Q4 is [0,1,2,3,4] and so is Q2 - - # array access follows with A as the sample array - A := [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] - - # get element indexed from left - x := A[1] # x is 10 - x := A[2] # x is 20 - x := A[10] # x is 100 - - # get element indexed from right - x := A[-1] # x is 100 - x := A[-2] # x is 90 - x := A[-10] # x is 10 - - # copy array to show assignment to elements - B := copy(A) - - # assign element indexed from left - B[1] := 11 - B[2] := 21 - B[10] := 101 - # B is now [11, 21, 30, 50, 60, 60, 70, 80, 90, 101] - - # assign element indexed from right - see below - B[-1] := 102 - B[-2] := 92 - B[-10] := 12 - # B is now [12, 21, 30, 50, 60, 60, 70, 80, 92, 102] - - # list slicing - # the unusual nature of the slice - returning 1 less element than might be expected - # in many languages - is best understood if you imagine indexes as pointing to BEFORE - # the item of interest. When a slice is made, the elements between the two points are - # collected. eg in the A[3 : 6] sample, it will get the elements between the [ ] marks - # - # sample list: 10 20 [30 40 50] 60 70 80 90 100 - # positive indexes: 1 2 3 4 5 6 7 8 9 10 11 - # non-positive indexes: -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 - # - # I have deliberately drawn the indexes between the positions of the values. - # The nature of this indexing brings simplicity to string operations - # - # list slicing can also use non-positive indexes to access values from the right. - # The final index of 0 shown above shows how the end of the list can be nominated - # without having to know it's length - # - # NOTE: list slices are distinct lists, so assigning to the slice - # or a member of the slice does not change the values in A - # - # Another key fact to understand: once the non-positive indexes and length-offsets are - # resolved to a simple positive index, the index pair (if two are given) are swapped - # if necessary to yield the elements between the two. - # - S := A[3 : 6] # S is [30, 40, 50] - S := A[6 : 3] # S is [30, 40, 50] not illegal or erroneous - S := A[-5 : -8] # S is [30, 40, 50] - S := A[-8 : -5] # S is [30, 40, 50] also legal and meaningful - - # list slicing with length request - S := A[3 +: 3] # S is [30, 40, 50] - S := A[6 -: 3] # S is [30, 40, 50] - S := A[-8 +: 3] # S is [30, 40, 50] - S := A[-5 -: 3] # S is [30, 40, 50] - S := A[-8 -: -3] # S is [30, 40, 50] - S := A[-5 +: -3] # S is [30, 40, 50] -end diff --git a/Task/Arrays/HicEst/arrays-3.hicest b/Task/Arrays/HicEst/arrays-3.hicest deleted file mode 100644 index a3a972a13f..0000000000 --- a/Task/Arrays/HicEst/arrays-3.hicest +++ /dev/null @@ -1,3 +0,0 @@ -# Unicon provides a number of extensions -# insert and delete work on lists allowing changes in the middle -# possibly others diff --git a/Task/Arrays/Java/arrays-2.java b/Task/Arrays/Java/arrays-2.java index af415acc40..d1e3a93a97 100644 --- a/Task/Arrays/Java/arrays-2.java +++ b/Task/Arrays/Java/arrays-2.java @@ -1,4 +1,4 @@ -ArrayList list = new ArrayList ();//optionally add an initial size as an argument -list.add(5);//appends to the end of the list -list.add(1, 6);//assigns the element at index 1 +List list = new ArrayList(); // optionally add an initial size as an argument +list.add(5); // appends to the end of the list +list.add(1, 6); // inserts an element at index 1 System.out.println(list.get(0)); diff --git a/Task/Arrays/jq/arrays.jq b/Task/Arrays/Jq/arrays.jq similarity index 100% rename from Task/Arrays/jq/arrays.jq rename to Task/Arrays/Jq/arrays.jq diff --git a/Task/Arrays/Lang5/arrays.lang5 b/Task/Arrays/Lang5/arrays.lang5 new file mode 100644 index 0000000000..0218f5abd4 --- /dev/null +++ b/Task/Arrays/Lang5/arrays.lang5 @@ -0,0 +1,5 @@ +[] +1 append +['foo 'bar] append +2 reshape +0 remove 2 swap 2 compress collapse . diff --git a/Task/Arrays/OoRexx/arrays.rexx b/Task/Arrays/OoRexx/arrays.rexx new file mode 100644 index 0000000000..03c9aa9922 --- /dev/null +++ b/Task/Arrays/OoRexx/arrays.rexx @@ -0,0 +1,6 @@ + a = .array~new -- create a zero element array + b = .array~new(10) -- create an array with initial size of 10 + c = .array~of(1, 2, 3) -- creates a 3 element array holding objects 1, 2, and 3 + a[3] = "Fred" -- assign an item + b[2] = a[3] -- retrieve an item from the array + c~append(4) -- adds to end. c[4] == 4 now diff --git a/Task/Arrays/SPL/arrays.spl b/Task/Arrays/SPL/arrays.spl new file mode 100644 index 0000000000..b2d7c8332f --- /dev/null +++ b/Task/Arrays/SPL/arrays.spl @@ -0,0 +1,4 @@ +a[1] = 2.5 +a[2] = 3 +a[3] = "Result is " +#.output(a[3],a[1]+a[2]) diff --git a/Task/Arrays/Simula/arrays-1.simula b/Task/Arrays/Simula/arrays-1.simula new file mode 100644 index 0000000000..7fe9a50ae4 --- /dev/null +++ b/Task/Arrays/Simula/arrays-1.simula @@ -0,0 +1,35 @@ +BEGIN + + PROCEDURE STATIC; + BEGIN + INTEGER ARRAY X(0:4); + + X(0) := 10; + X(1) := 11; + X(2) := 12; + X(3) := 13; + X(4) := X(0); + + OUTTEXT("STATIC AT 4: "); + OUTINT(X(4), 0); + OUTIMAGE + END STATIC; + + PROCEDURE DYNAMIC(N); INTEGER N; + BEGIN + INTEGER ARRAY X(0:N-1); + + X(0) := 10; + X(1) := 11; + X(2) := 12; + X(3) := 13; + X(4) := X(0); + + OUTTEXT("DYNAMIC AT 4: "); + OUTINT(X(4),0); + OUTIMAGE + END DYNAMIC; + + STATIC; + DYNAMIC(5) +END ARRAYS. diff --git a/Task/Arrays/Simula/arrays-2.simula b/Task/Arrays/Simula/arrays-2.simula new file mode 100644 index 0000000000..b4eb0fd0b7 --- /dev/null +++ b/Task/Arrays/Simula/arrays-2.simula @@ -0,0 +1,145 @@ +BEGIN + + CLASS ITEM;; + + CLASS ITEMARRAY(N); INTEGER N; + BEGIN + REF(ITEM) ARRAY DATA(1:N); + OUTTEXT("NEW ITEMARRAY WITH "); OUTINT(N, 0); OUTTEXT(" ELEMENTS"); + OUTIMAGE; + END; + + CLASS ARRAYLIST; + BEGIN + + PROCEDURE EXPAND(N); INTEGER N; + BEGIN + INTEGER I; + REF(ITEMARRAY) TEMP; + OUTTEXT("EXPAND TO CAPACITY "); OUTINT(N, 0); OUTIMAGE; + TEMP :- NEW ITEMARRAY(N); + FOR I := 1 STEP 1 UNTIL SIZE DO + TEMP.DATA(I) :- ITEMS.DATA(I); + ITEMS :- TEMP; + END; + + PROCEDURE ADD(T); REF(ITEM) T; + BEGIN + IF SIZE + 1 > CAPACITY THEN + BEGIN + CAPACITY := 2 * CAPACITY; + EXPAND(CAPACITY); + END; + SIZE := SIZE + 1; + ITEMS.DATA(SIZE) :- T; + OUTTEXT("SIZE IS "); OUTINT(SIZE, 0); OUTIMAGE; + END; + + PROCEDURE REMOVE(I); INTEGER I; + BEGIN + INTEGER J; + IF I < 1 OR I > SIZE THEN ERROR("REMOVE: INDEX OUT OF BOUNDS"); + FOR J := I STEP 1 UNTIL SIZE - 1 DO + ITEMS.DATA(J) :- ITEMS.DATA(J + 1); + ITEMS.DATA(SIZE) :- NONE; + SIZE := SIZE - 1; + END; + + REF(ITEM) PROCEDURE GET(I); INTEGER I; + BEGIN + IF I < 1 OR I > SIZE THEN ERROR("GET: INDEX OUT OF BOUNDS"); + GET :- ITEMS.DATA(I); + END; + + INTEGER CAPACITY; + INTEGER SIZE; + REF(ITEMARRAY) ITEMS; + + CAPACITY := 20; + SIZE := 0; + EXPAND(CAPACITY); + + END; + + + ITEM CLASS TEXTITEM(TXT); TEXT TXT;; + + ARRAYLIST CLASS TEXTARRAYLIST; + BEGIN + PROCEDURE ADD(T); TEXT T; + THIS TEXTARRAYLIST QUA ARRAYLIST.ADD(NEW TEXTITEM(T)); + TEXT PROCEDURE GET(I); INTEGER I; + GET :- THIS TEXTARRAYLIST QUA ARRAYLIST.GET(I) QUA TEXTITEM.TXT; + END; + + + ITEM CLASS REALITEM(X); REAL X;; + + ARRAYLIST CLASS REALARRAYLIST; + BEGIN + PROCEDURE ADD(X); REAL X; + THIS REALARRAYLIST QUA ARRAYLIST.ADD(NEW REALITEM(X)); + REAL PROCEDURE GET(I); INTEGER I; + GET := THIS REALARRAYLIST QUA ARRAYLIST.GET(I) QUA REALITEM.X; + END; + + + REF(TEXTARRAYLIST) LINES; + REF(REALARRAYLIST) REALS; + INTEGER I; + + LINES :- NEW TEXTARRAYLIST; + LINES.ADD("WE"); + LINES.ADD("HAVE"); + LINES.ADD("SEEN"); + LINES.ADD("THAT"); + LINES.ADD("ARRAYS"); + LINES.ADD("ARE"); + LINES.ADD("A"); + LINES.ADD("VERY"); + LINES.ADD("CONVENIENT"); + LINES.ADD("WAY"); + LINES.ADD("OF"); + LINES.ADD("STORING"); + LINES.ADD("SIMPLE"); + LINES.ADD("VALUES"); + LINES.ADD("AND"); + LINES.ADD("REFERENCES"); + LINES.ADD("TO"); + LINES.ADD("MORE"); + LINES.ADD("COMPLEX"); + LINES.ADD("CLASS"); + LINES.ADD("OBJECTS"); + LINES.ADD("IN"); + LINES.ADD("AN"); + LINES.ADD("ORDERED"); + LINES.ADD("LIST"); + LINES.ADD("."); + + FOR I := 1 STEP 1 UNTIL LINES.SIZE DO + BEGIN + OUTINT(I, 0); OUTTEXT(": "); + OUTTEXT(LINES.GET(I)); OUTIMAGE; + END; + + + REALS :- NEW REALARRAYLIST; + FOR I := 1 STEP 1 UNTIL 10 DO + REALS.ADD(I * I); + + FOR I := 1 STEP 1 UNTIL REALS.SIZE DO + BEGIN + OUTINT(I, 4); OUTTEXT(": "); + OUTFIX(REALS.GET(I),2,10); OUTIMAGE; + END; + + FOR I := REALS.SIZE STEP - 2 UNTIL 1 DO + REALS.REMOVE(I); + + FOR I := 1 STEP 1 UNTIL REALS.SIZE DO + BEGIN + OUTINT(I, 4); OUTTEXT(": "); + OUTFIX(REALS.GET(I),2,10); OUTIMAGE; + END; + +END; diff --git a/Task/Arrays/Stata/arrays-1.stata b/Task/Arrays/Stata/arrays-1.stata new file mode 100644 index 0000000000..5a117b6e2f --- /dev/null +++ b/Task/Arrays/Stata/arrays-1.stata @@ -0,0 +1,8 @@ +matrix a = 2,9,4\7,5,3\6,1,8 +display det(a) +matrix svd u d v = a +matrix b = u*diag(d)*v' +matrix list b +* store the u and v matrices in the current dataset +svmat u +svmat v diff --git a/Task/Arrays/Stata/arrays-2.stata b/Task/Arrays/Stata/arrays-2.stata new file mode 100644 index 0000000000..52fa35f145 --- /dev/null +++ b/Task/Arrays/Stata/arrays-2.stata @@ -0,0 +1,7 @@ +mata +a = 2,9,4\7,5,3\6,1,8 +det(a) +svd(a, u=., s=., v=.) +// Notice that to reconstruct the matrix, v is not transposed here, +// while it is with -matrix svd- in Stata. +u*diag(s)*v diff --git a/Task/Arrays/Swift/arrays.swift b/Task/Arrays/Swift/arrays.swift index a33940f0ac..d0fff3abd3 100644 --- a/Task/Arrays/Swift/arrays.swift +++ b/Task/Arrays/Swift/arrays.swift @@ -3,4 +3,4 @@ var anyArray = [Any]() anyArray.append("foo") // Adding to an Array anyArray.append(1) // ["foo", 1] anyArray.removeAtIndex(1) // Remove object -anyArray[0] = "bar" // ["bar"]] +anyArray[0] = "bar" // ["bar"] diff --git a/Task/Arrays/Unicon/arrays.unicon b/Task/Arrays/Unicon/arrays.unicon new file mode 100644 index 0000000000..78e40b9177 --- /dev/null +++ b/Task/Arrays/Unicon/arrays.unicon @@ -0,0 +1 @@ +L := list(100); L[12] := 7; a := array(100, 0.0); a[3] +:= a[1]+a[2] diff --git a/Task/Arrays/Zkl/arrays.zkl b/Task/Arrays/Zkl/arrays.zkl new file mode 100644 index 0000000000..95c2750394 --- /dev/null +++ b/Task/Arrays/Zkl/arrays.zkl @@ -0,0 +1,5 @@ +var array=List(); // array of size 0 +array=(0).pump(10,List().write,5).copy(); // [writable] array of size 10 filled with 5 +array[3]=4; +array[3] //-->4 +array+9; //append a 9 to the end, same as array.append(9) diff --git a/Task/Assertions/AWK/assertions.awk b/Task/Assertions/AWK/assertions.awk new file mode 100644 index 0000000000..2228c83d1f --- /dev/null +++ b/Task/Assertions/AWK/assertions.awk @@ -0,0 +1,21 @@ +BEGIN { + meaning = 6 * 7 + assert(meaning == 42, "Integer mathematics failed") + assert(meaning == 42) + meaning = strtonum("42 also known as forty-two") + assert(meaning == 42, "Built-in function failed") + meaning = "42" + assert(meaning == 42, "Dynamic type conversion failed") + meaning = 6 * 9 + assert(meaning == 42, "Ford Prefect's experiment failed") + print "That's all folks" + exit +} + +# Errormsg is optional, displayed if assertion fails +function assert(cond, errormsg){ + if (!cond) { + if (errormsg != "") print errormsg + exit 1 + } +} diff --git a/Task/Assertions/BaCon/assertions.bacon b/Task/Assertions/BaCon/assertions.bacon new file mode 100644 index 0000000000..4db89fb8bf --- /dev/null +++ b/Task/Assertions/BaCon/assertions.bacon @@ -0,0 +1,24 @@ +' Assertions +answer = assertion(42) +PRINT "The ultimate answer is indeed ", answer + +PRINT "Now, expect a failure, unless NDEBUG defined at compile time" +answer = assertion(41) +PRINT answer +END + +' Ensure the given number is the ultimate answer +FUNCTION assertion(NUMBER i) + + ' BaCon can easily be intimately integrated with C + USEH + #include + END USEH + + ' If the given expression is not true, abort the program + USEC + assert(i == 42); + END USEC + + RETURN i +END FUNCTION diff --git a/Task/Assertions/Java/assertions.java b/Task/Assertions/Java/assertions.java index 5c3fbfa951..097716babd 100644 --- a/Task/Assertions/Java/assertions.java +++ b/Task/Assertions/Java/assertions.java @@ -1,8 +1,16 @@ -public static void main(String[] args){ - int a; - //...input or change a here - assert a == 42;//throws an AssertionError when a is not 42 - assert a == 42 : "Error message"; //throws an AssertionError - //when a is not 42 with "Error message" for the message - //the error message can be any non-void expression +public class Assertions { + + public static void main(String[] args) { + int a = 13; + + // ... some real code here ... + + assert a == 42; + // Throws an AssertionError when a is not 42. + + assert a == 42 : "Error message"; + // Throws an AssertionError when a is not 42, + // with "Error message" for the message. + // The error message can be any non-void expression. + } } diff --git a/Task/Assertions/Kotlin/assertions.kotlin b/Task/Assertions/Kotlin/assertions.kotlin new file mode 100644 index 0000000000..f159452beb --- /dev/null +++ b/Task/Assertions/Kotlin/assertions.kotlin @@ -0,0 +1,6 @@ +// version 1.0.6 (assert.kt) + +fun main(args: Array) { + val a = 42 + assert(a == 43) +} diff --git a/Task/Assertions/Nim/assertions.nim b/Task/Assertions/Nim/assertions.nim index 541f20f9c9..ac39a9826c 100644 --- a/Task/Assertions/Nim/assertions.nim +++ b/Task/Assertions/Nim/assertions.nim @@ -1,2 +1,2 @@ var a = 42 -assert(a == 42) +assert(a == 42, "Not 42!") diff --git a/Task/Assertions/Nimrod/assertions.nimrod b/Task/Assertions/Nimrod/assertions.nimrod deleted file mode 100644 index 541f20f9c9..0000000000 --- a/Task/Assertions/Nimrod/assertions.nimrod +++ /dev/null @@ -1,2 +0,0 @@ -var a = 42 -assert(a == 42) diff --git a/Task/Assertions/SETL/assertions.setl b/Task/Assertions/SETL/assertions.setl new file mode 100644 index 0000000000..b53ba3bed8 --- /dev/null +++ b/Task/Assertions/SETL/assertions.setl @@ -0,0 +1 @@ +assert( n = 42 ); diff --git a/Task/Assertions/Stata/assertions-1.stata b/Task/Assertions/Stata/assertions-1.stata new file mode 100644 index 0000000000..5b2e576f2f --- /dev/null +++ b/Task/Assertions/Stata/assertions-1.stata @@ -0,0 +1 @@ +assert x0 diff --git a/Task/Assertions/Stata/assertions-2.stata b/Task/Assertions/Stata/assertions-2.stata new file mode 100644 index 0000000000..2b290a1e76 --- /dev/null +++ b/Task/Assertions/Stata/assertions-2.stata @@ -0,0 +1 @@ +confirm file titanium.dta diff --git a/Task/Assertions/Stata/assertions-3.stata b/Task/Assertions/Stata/assertions-3.stata new file mode 100644 index 0000000000..fa5d28c8dd --- /dev/null +++ b/Task/Assertions/Stata/assertions-3.stata @@ -0,0 +1,2 @@ +if (`n'==42) error 3 +* Will print "no dataset in use" diff --git a/Task/Assertions/Stata/assertions-4.stata b/Task/Assertions/Stata/assertions-4.stata new file mode 100644 index 0000000000..a2f6b38f8e --- /dev/null +++ b/Task/Assertions/Stata/assertions-4.stata @@ -0,0 +1,4 @@ +if (`n'==42) { + display as error "The correct answer is not 42." + exit 54 +} diff --git a/Task/Assertions/Zkl/assertions.zkl b/Task/Assertions/Zkl/assertions.zkl new file mode 100644 index 0000000000..1e84cc07ae --- /dev/null +++ b/Task/Assertions/Zkl/assertions.zkl @@ -0,0 +1,2 @@ +n:=42; (n==42) or throw(Exception.AssertionError); +n=41; (n==42) or throw(Exception.AssertionError("I wanted 42!")); diff --git a/Task/Associative-array-Creation/BaCon/associative-array-creation.bacon b/Task/Associative-array-Creation/BaCon/associative-array-creation.bacon new file mode 100644 index 0000000000..36a011e04b --- /dev/null +++ b/Task/Associative-array-Creation/BaCon/associative-array-creation.bacon @@ -0,0 +1,6 @@ +DECLARE associative ASSOC STRING + +associative("abc") = "first three" +associative("xyz") = "last three" + +PRINT associative("xyz") diff --git a/Task/Associative-array-Creation/Elena/associative-array-creation.elena b/Task/Associative-array-Creation/Elena/associative-array-creation.elena index 9505edb516..33a9699421 100644 --- a/Task/Associative-array-Creation/Elena/associative-array-creation.elena +++ b/Task/Associative-array-Creation/Elena/associative-array-creation.elena @@ -1,15 +1,12 @@ -#define system. -#define system'collections. +import system'collections. -// --- Program --- - -#symbol program = +program = [ // 1. Create - #var aMap := Dictionary new. - aMap@"key" := "foox". - aMap@"key" := "foo". - aMap@"key2":= "foo2". - aMap@"key3":= "foo3". - aMap@"key4":= "foo4". + var aMap := Dictionary new. + aMap["key"] := "foox". + aMap["key"] := "foo". + aMap["key2"]:= "foo2". + aMap["key3"]:= "foo3". + aMap["key4"]:= "foo4". ]. diff --git a/Task/Associative-array-Creation/Gosu/associative-array-creation.gosu b/Task/Associative-array-Creation/Gosu/associative-array-creation.gosu new file mode 100644 index 0000000000..caa8d64375 --- /dev/null +++ b/Task/Associative-array-Creation/Gosu/associative-array-creation.gosu @@ -0,0 +1,35 @@ +// empty map +var emptyMap = new HashMap() + +// map initialization +var map = {"Scott"->50, "Carson"->40, "Luca"->30, "Kyle"->38} + +// map key/value assignment +map["Scott"] = 51 + +// get a value +var x = map["Scott"] + +// remove an entry +map.remove("Scott") + +// loop and maps +for(entry in map.entrySet()) { + print("Key: ${entry.Key}, Value: ${entry.Value}") +} + +// functional iteration +map.eachKey(\ k ->print(map[k])) +map.eachValue(\ v ->print(v)) +map.eachKeyAndValue(\ k, v -> print("Key: ${v}, Value: ${v}")) +var filtered = map.filterByValues(\ v ->v < 50) + +// any object can be treated as an associative array +class Person { + var name: String + var age: int +} +// access properties on Person dynamically via associative array syntax +var scott = new Person() +scott["name"] = "Scott" +scott["age"] = 29 diff --git a/Task/Associative-array-Creation/JavaScript/associative-array-creation-3.js b/Task/Associative-array-Creation/JavaScript/associative-array-creation-3.js deleted file mode 100644 index 65996e6beb..0000000000 --- a/Task/Associative-array-Creation/JavaScript/associative-array-creation-3.js +++ /dev/null @@ -1 +0,0 @@ -'foo' in assoc // true diff --git a/Task/Associative-array-Creation/jq/associative-array-creation-1.jq b/Task/Associative-array-Creation/Jq/associative-array-creation-1.jq similarity index 100% rename from Task/Associative-array-Creation/jq/associative-array-creation-1.jq rename to Task/Associative-array-Creation/Jq/associative-array-creation-1.jq diff --git a/Task/Associative-array-Creation/jq/associative-array-creation-2.jq b/Task/Associative-array-Creation/Jq/associative-array-creation-2.jq similarity index 100% rename from Task/Associative-array-Creation/jq/associative-array-creation-2.jq rename to Task/Associative-array-Creation/Jq/associative-array-creation-2.jq diff --git a/Task/Associative-array-Creation/jq/associative-array-creation-3.jq b/Task/Associative-array-Creation/Jq/associative-array-creation-3.jq similarity index 100% rename from Task/Associative-array-Creation/jq/associative-array-creation-3.jq rename to Task/Associative-array-Creation/Jq/associative-array-creation-3.jq diff --git a/Task/Associative-array-Creation/jq/associative-array-creation-4.jq b/Task/Associative-array-Creation/Jq/associative-array-creation-4.jq similarity index 100% rename from Task/Associative-array-Creation/jq/associative-array-creation-4.jq rename to Task/Associative-array-Creation/Jq/associative-array-creation-4.jq diff --git a/Task/Associative-array-Creation/Nimrod/associative-array-creation.nimrod b/Task/Associative-array-Creation/Nimrod/associative-array-creation.nimrod deleted file mode 100644 index 052b5413d5..0000000000 --- a/Task/Associative-array-Creation/Nimrod/associative-array-creation.nimrod +++ /dev/null @@ -1,23 +0,0 @@ -import tables - -var t: TTable[int,string] = initTable[int,string]() - -t[1] = "one" -t[2] = "two" -t[3] = "three" -t.add(4,"four") - -echo "t has " & $t.len & " elements" - -echo "has t key 4? " & $t.hasKey(4) -echo "has t key 5? " & $t.hasKey(5) - -#iterate keys -echo "key iteration:" -for k in t.keys: - echo "at[" & $k & "]=" & t[k] - -#itetate pairs -echo "pair iteration:" -for k,v in t.pairs: - echo "at[" & $k & "]=" & v diff --git a/Task/Associative-array-Creation/Ol/associative-array-creation.ol b/Task/Associative-array-Creation/Ol/associative-array-creation.ol new file mode 100644 index 0000000000..afe32ee2fb --- /dev/null +++ b/Task/Associative-array-Creation/Ol/associative-array-creation.ol @@ -0,0 +1,23 @@ +; empty associative array has two names +#empty +#() + +; creating the new empty associative array +(define empty-map #empty) + +; creating associative array with values +(define my-map (list->ff '( + (1 . 100) + (2 . 200) + (7 . 777)))) + +; add new key-value pair to the existing associative array +(define my-new-map (put my-map 'the-key 'the-value)) + +; print our arrays +(print empty-map) +; ==> #() +(print my-map) +; ==> #((1 . 100) (2 . 200) (7 . 777)) +(print my-new-map) +; ==> #((1 . 100) (2 . 200) (7 . 777) (the-key . the-value)) diff --git a/Task/Associative-array-Creation/OoRexx/associative-array-creation-1.rexx b/Task/Associative-array-Creation/OoRexx/associative-array-creation-1.rexx new file mode 100644 index 0000000000..195d330e4a --- /dev/null +++ b/Task/Associative-array-Creation/OoRexx/associative-array-creation-1.rexx @@ -0,0 +1,5 @@ +map = .directory~new +map["foo"] = 5 +map["bar"] = 10 +map["baz"] = 15 +map["foo"] = 6 diff --git a/Task/Associative-array-Creation/OoRexx/associative-array-creation-2.rexx b/Task/Associative-array-Creation/OoRexx/associative-array-creation-2.rexx new file mode 100644 index 0000000000..b645d1157d --- /dev/null +++ b/Task/Associative-array-Creation/OoRexx/associative-array-creation-2.rexx @@ -0,0 +1,2 @@ +item = map["foo"] -- => 6 +item = map["invalid"] -- => .nil diff --git a/Task/Associative-array-Creation/OoRexx/associative-array-creation-3.rexx b/Task/Associative-array-Creation/OoRexx/associative-array-creation-3.rexx new file mode 100644 index 0000000000..7c7fd25670 --- /dev/null +++ b/Task/Associative-array-Creation/OoRexx/associative-array-creation-3.rexx @@ -0,0 +1,3 @@ +loop key over map + say key +end diff --git a/Task/Associative-array-Creation/OoRexx/associative-array-creation-4.rexx b/Task/Associative-array-Creation/OoRexx/associative-array-creation-4.rexx new file mode 100644 index 0000000000..efd0eed92f --- /dev/null +++ b/Task/Associative-array-Creation/OoRexx/associative-array-creation-4.rexx @@ -0,0 +1,3 @@ +loop value over map~allItems + say value +end diff --git a/Task/Associative-array-Creation/OoRexx/associative-array-creation-5.rexx b/Task/Associative-array-Creation/OoRexx/associative-array-creation-5.rexx new file mode 100644 index 0000000000..33cb44d4cf --- /dev/null +++ b/Task/Associative-array-Creation/OoRexx/associative-array-creation-5.rexx @@ -0,0 +1,5 @@ +s = map~supplier +loop while s~available + say s~index "=>" s~item + s~next +end diff --git a/Task/Associative-array-Creation/Setl4/associative-array-creation.setl4 b/Task/Associative-array-Creation/Setl4/associative-array-creation.setl4 new file mode 100644 index 0000000000..057fbfa330 --- /dev/null +++ b/Task/Associative-array-Creation/Setl4/associative-array-creation.setl4 @@ -0,0 +1,24 @@ +* Iterate over key-value pairs of a map + + map = new('map 1:one 2:two 3:three') + +visit(domain(map),'expr to evaluate for each member') + +visit(range(map),'expr to evaluate for each member') + + next + this = next(map) :f(done) + out(show(this) ':' show(get(map,this)) :next) + done + + loop(d = domain(map) + + next + out('next domain entry',next(d)) :s(next) + done + + loop(d = range(map) + + next + out('next domain entry',next(d)) :s(next) + done diff --git a/Task/Associative-array-Creation/Stata/associative-array-creation.stata b/Task/Associative-array-Creation/Stata/associative-array-creation.stata new file mode 100644 index 0000000000..a2ad3b5c5d --- /dev/null +++ b/Task/Associative-array-Creation/Stata/associative-array-creation.stata @@ -0,0 +1,18 @@ +mata +a=asarray_create() + +// Add entries +asarray(a,"one",1) +asarray(a,"two",2) + +// Check existence of key +asarray_contains(a,"two") + +// Get a vector of all keys +asarray_keys(a) + +// Number of entries +asarray_elements(a) + +// End Mata session +end diff --git a/Task/Associative-array-Creation/Zkl/associative-array-creation.zkl b/Task/Associative-array-Creation/Zkl/associative-array-creation.zkl new file mode 100644 index 0000000000..fdc23388a5 --- /dev/null +++ b/Task/Associative-array-Creation/Zkl/associative-array-creation.zkl @@ -0,0 +1,5 @@ +zkl: Dictionary("one",1, "two",2, "three",3) +D(two:2,three:3,one:1) + +zkl: T("one",1, "two",2, "three",3).toDictionary() +D(two:2,three:3,one:1) diff --git a/Task/Associative-array-Iteration/Aime/associative-array-iteration.aime b/Task/Associative-array-Iteration/Aime/associative-array-iteration.aime index 4b2aabd8a6..7039ea3556 100644 --- a/Task/Associative-array-Iteration/Aime/associative-array-iteration.aime +++ b/Task/Associative-array-Iteration/Aime/associative-array-iteration.aime @@ -8,5 +8,5 @@ r_put(r, "B", "associative"); # a string value if (r_first(r, s)) { do { o_form("key ~, value ~ (~)\n", s, r[s], r_type(r, s)); - } while (r_greater(r, s, s)); + } while (rsk_greater(r, s, s)); } diff --git a/Task/Associative-array-Iteration/BaCon/associative-array-iteration.bacon b/Task/Associative-array-Iteration/BaCon/associative-array-iteration.bacon new file mode 100644 index 0000000000..c43a9ee1c7 --- /dev/null +++ b/Task/Associative-array-Iteration/BaCon/associative-array-iteration.bacon @@ -0,0 +1,10 @@ +DECLARE associative ASSOC STRING + +associative("abc") = "first three" +associative("mn") = "middle two" +associative("xyz") = "last three" + +LOOKUP associative TO keys$ SIZE amount +FOR i = 0 TO amount - 1 + PRINT keys$[i], ":", associative(keys$[i]) +NEXT diff --git a/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena b/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena index 65dcb765ab..c0375f9fcd 100644 --- a/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena +++ b/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena @@ -1,20 +1,18 @@ -#define system. -#define system'collections. -#define system'routines. -#define extensions. +import system'collections. +import system'routines. +import extensions. -// --- Program --- - -#symbol program = +program = [ // 1. Create - #var aMap := Dictionary new. - aMap@"key" := "foox". - aMap@"key2":= "foo2". - aMap@"key3":= "foo3". - aMap@"key4":= "foo4". + var aMap := Dictionary new. + aMap["key"] := "foox". + aMap["key"] := "foo". + aMap["key2"]:= "foo2". + aMap["key3"]:= "foo3". + aMap["key4"]:= "foo4". // Enumerate - aMap run &each: aKeyValue - [ console writeLine:(aKeyValue key):" : ":aKeyValue ]. + aMap forEach + (:aKeyValue)[ console printLine(aKeyValue key," : ",aKeyValue) ]. ]. diff --git a/Task/Associative-array-Iteration/Gambas/associative-array-iteration.gambas b/Task/Associative-array-Iteration/Gambas/associative-array-iteration.gambas new file mode 100644 index 0000000000..30fade7825 --- /dev/null +++ b/Task/Associative-array-Iteration/Gambas/associative-array-iteration.gambas @@ -0,0 +1,16 @@ +Public Sub Main() +Dim cList As Collection = ["2": "quick", "4": "fox", "1": "The", "9": "dog", "7": "the", "5": "jumped", "3": "brown", "6": "over", "8": "lazy"] +Dim siCount As Short +Dim sTemp As String + +For Each sTemp In cList + Print cList.key & "=" & sTemp;; +Next + +Print + +For siCount = 1 To cList.Count + Print cList[Str(siCount)];; +Next + +End diff --git a/Task/Associative-array-Iteration/Go/associative-array-iteration.go b/Task/Associative-array-Iteration/Go/associative-array-iteration-1.go similarity index 100% rename from Task/Associative-array-Iteration/Go/associative-array-iteration.go rename to Task/Associative-array-Iteration/Go/associative-array-iteration-1.go diff --git a/Task/Associative-array-Iteration/Go/associative-array-iteration-2.go b/Task/Associative-array-Iteration/Go/associative-array-iteration-2.go new file mode 100644 index 0000000000..a94175294a --- /dev/null +++ b/Task/Associative-array-Iteration/Go/associative-array-iteration-2.go @@ -0,0 +1,35 @@ +package main + +import ( + "os" + "text/template" +) + +func main() { + m := map[string]int{ + "hello": 13, + "world": 31, + "!": 71, + } + + // iterating over key-value pairs: + template.Must(template.New("").Parse(` +{{- range $k, $v := . -}} +key = {{$k}}, value = {{$v}} +{{end -}} +`)).Execute(os.Stdout, m) + + // iterating over keys: + template.Must(template.New("").Parse(` +{{- range $k, $v := . -}} +key = {{$k}} +{{end -}} +`)).Execute(os.Stdout, m) + + // iterating over values: + template.Must(template.New("").Parse(` +{{- range . -}} +value = {{.}} +{{end -}} +`)).Execute(os.Stdout, m) +} diff --git a/Task/Associative-array-Iteration/Haskell/associative-array-iteration.hs b/Task/Associative-array-Iteration/Haskell/associative-array-iteration.hs index 0fcb893a72..cf4f2d6a47 100644 --- a/Task/Associative-array-Iteration/Haskell/associative-array-iteration.hs +++ b/Task/Associative-array-Iteration/Haskell/associative-array-iteration.hs @@ -1,10 +1,13 @@ import qualified Data.Map as M +myMap :: M.Map String Int myMap = M.fromList [("hello", 13), ("world", 31), ("!", 71)] -main = do -- pairs - print $ M.toList myMap - -- keys - print $ M.keys myMap - -- values - print $ M.elems myMap +main :: IO () +main = + (putStrLn . unlines) $ + [ show . M.toList -- Pairs + , show . M.keys -- Keys + , show . M.elems -- Values + ] <*> + pure myMap diff --git a/Task/Associative-array-Iteration/Java/associative-array-iteration-1.java b/Task/Associative-array-Iteration/Java/associative-array-iteration-1.java index f26d7ef0ce..caf52fb945 100644 --- a/Task/Associative-array-Iteration/Java/associative-array-iteration-1.java +++ b/Task/Associative-array-Iteration/Java/associative-array-iteration-1.java @@ -1,21 +1,21 @@ -Map myDict = new HashMap(); -myDict.put("hello", 1); -myDict.put("world", 2); -myDict.put("!", 3); +Map map = new HashMap(); +map.put("hello", 1); +map.put("world", 2); +map.put("!", 3); // iterating over key-value pairs: -for (Map.Entry e : myDict.entrySet()) { +for (Map.Entry e : map.entrySet()) { String key = e.getKey(); Integer value = e.getValue(); System.out.println("key = " + key + ", value = " + value); } // iterating over keys: -for (String key : myDict.keySet()) { +for (String key : map.keySet()) { System.out.println("key = " + key); } // iterating over values: -for (Integer value : myDict.values()) { +for (Integer value : map.values()) { System.out.println("value = " + value); } diff --git a/Task/Associative-array-Iteration/Java/associative-array-iteration-2.java b/Task/Associative-array-Iteration/Java/associative-array-iteration-2.java index 8c0bf2391c..2942a54d9c 100644 --- a/Task/Associative-array-Iteration/Java/associative-array-iteration-2.java +++ b/Task/Associative-array-Iteration/Java/associative-array-iteration-2.java @@ -1,15 +1,15 @@ -Map myDict = new HashMap<>(); -myDict.put("hello", 1); -myDict.put("world", 2); -myDict.put("!", 3); +Map map = new HashMap<>(); +map.put("hello", 1); +map.put("world", 2); +map.put("!", 3); // iterating over key-value pairs: -myDict.forEach((k, v) -> { +map.forEach((k, v) -> { System.out.printf("key = %s, value = %s%n", k, v); }); // iterating over keys: -myDict.keySet().forEach(k -> System.out.printf("key = %s%n", k)); +map.keySet().forEach(k -> System.out.printf("key = %s%n", k)); // iterating over values: -myDict.values().forEach(v -> System.out.printf("value = %s%n", v)); +map.values().forEach(v -> System.out.printf("value = %s%n", v)); diff --git a/Task/Associative-array-Iteration/JavaScript/associative-array-iteration-1.js b/Task/Associative-array-Iteration/JavaScript/associative-array-iteration-1.js deleted file mode 100644 index dde320f541..0000000000 --- a/Task/Associative-array-Iteration/JavaScript/associative-array-iteration-1.js +++ /dev/null @@ -1,15 +0,0 @@ -var myhash = {}; // a new, empty object -myhash["hello"] = 3; -myhash.world = 6; // obj.name is equivalent to obj["name"] for certain values of name -myhash["!"] = 9; - -var output = '', // initialise as string - key; -for (key in myhash) { - if (myhash.hasOwnProperty(key)) { - output += "key is: " + key; - output += " => "; - output += "value is: " + myhash[key]; // cannot use myhash.key, that would be myhash["key"] - output += "\n"; - } -} diff --git a/Task/Associative-array-Iteration/JavaScript/associative-array-iteration-2.js b/Task/Associative-array-Iteration/JavaScript/associative-array-iteration-2.js deleted file mode 100644 index 89939bf103..0000000000 --- a/Task/Associative-array-Iteration/JavaScript/associative-array-iteration-2.js +++ /dev/null @@ -1,13 +0,0 @@ -var myhash = {}; // a new, empty object -myhash["hello"] = 3; -myhash.world = 6; // obj.name is equivalent to obj["name"] for certain values of name -myhash["!"] = 9; - -var output = '', // initialise as string - val; -for (val in myhash) { - if (myhash.hasOwnProperty(val)) { - output += "myhash['" + val + "'] is: " + myhash[val]; - output += "\n"; - } -} diff --git a/Task/Associative-array-Iteration/Jq/associative-array-iteration.jq b/Task/Associative-array-Iteration/Jq/associative-array-iteration.jq new file mode 100644 index 0000000000..7594189587 --- /dev/null +++ b/Task/Associative-array-Iteration/Jq/associative-array-iteration.jq @@ -0,0 +1,31 @@ +def mydict: {"hello":13, "world": 31, "!": 71}; + +# Iterating over the keys +mydict | keys[] +# "!" +# "hello" +# "world" + +# Iterating over the values: +mydict[] +# 13 +# 31 +# 71 + +# Generating a stream of {"key": key, "value": value} objects: +mydict | to_entries[] +# {"key":"hello","value":13} +# {"key":"world","value":31} +# {"key":"!","value":71} + +# Generating a stream of [key,value] arrays: +mydict | . as $o | keys[] | [., $o[.]] +#["!",71] +#["hello",13] +#["world",31] + +# Generating a stream of [key,value] arrays, without sorting (jq > 1.4 required) +mydict | . as $o | keys_unsorted[] | [., $o[.]] +# ["hello",13] +# ["world",31] +# ["!",71] diff --git a/Task/Associative-array-Iteration/Kotlin/associative-array-iteration.kotlin b/Task/Associative-array-Iteration/Kotlin/associative-array-iteration.kotlin index f66cdf1f8c..94173d64a3 100644 --- a/Task/Associative-array-Iteration/Kotlin/associative-array-iteration.kotlin +++ b/Task/Associative-array-Iteration/Kotlin/associative-array-iteration.kotlin @@ -2,7 +2,7 @@ fun main(a: Array) { val map = mapOf("hello" to 1, "world" to 2, "!" to 3) with(map) { - forEach { println("key = ${it.key}, value = ${it.value}") } + entries.forEach { println("key = ${it.key}, value = ${it.value}") } keys.forEach { println("key = $it") } values.forEach { println("value = $it") } } diff --git a/Task/Associative-array-Iteration/Nim/associative-array-iteration.nim b/Task/Associative-array-Iteration/Nim/associative-array-iteration.nim index 052b5413d5..5339f02252 100644 --- a/Task/Associative-array-Iteration/Nim/associative-array-iteration.nim +++ b/Task/Associative-array-Iteration/Nim/associative-array-iteration.nim @@ -1,6 +1,6 @@ import tables -var t: TTable[int,string] = initTable[int,string]() +var t: Table[int,string] = initTable[int,string]() t[1] = "one" t[2] = "two" diff --git a/Task/Associative-array-Iteration/Nimrod/associative-array-iteration.nimrod b/Task/Associative-array-Iteration/Nimrod/associative-array-iteration.nimrod deleted file mode 100644 index 052b5413d5..0000000000 --- a/Task/Associative-array-Iteration/Nimrod/associative-array-iteration.nimrod +++ /dev/null @@ -1,23 +0,0 @@ -import tables - -var t: TTable[int,string] = initTable[int,string]() - -t[1] = "one" -t[2] = "two" -t[3] = "three" -t.add(4,"four") - -echo "t has " & $t.len & " elements" - -echo "has t key 4? " & $t.hasKey(4) -echo "has t key 5? " & $t.hasKey(5) - -#iterate keys -echo "key iteration:" -for k in t.keys: - echo "at[" & $k & "]=" & t[k] - -#itetate pairs -echo "pair iteration:" -for k,v in t.pairs: - echo "at[" & $k & "]=" & v diff --git a/Task/Associative-array-Iteration/Ol/associative-array-iteration.ol b/Task/Associative-array-Iteration/Ol/associative-array-iteration.ol new file mode 100644 index 0000000000..f41744b1c6 --- /dev/null +++ b/Task/Associative-array-Iteration/Ol/associative-array-iteration.ol @@ -0,0 +1,58 @@ +;;; create sample associative array +(define aa (list->ff '( + (hello . 1) + (world . 2) + (! . 3)))) + +(print aa) +; ==> #((! . 3) (hello . 1) (world . 2)) + +;;; simplest iteration over all associative array (using ff-iter, lazy iterator) +(let loop ((kv (ff-iter aa))) + (cond + ((null? kv) #true) + ((pair? kv) + (print (car kv)) + (loop (cdr kv))) + (else (loop (force kv))))) +; ==> (! . 3) +; ==> (hello . 1) +; ==> (world . 2) + +;;; iteration with returning value (using ff-fold) +(print + "folding result: " + (ff-fold + (lambda (result key value) + (print "key: " key ", value: " value) + (+ result 1)) + 0 + aa)) + +; ==> key: !, value: 3 +; ==> key: hello, value: 1 +; ==> key: world, value: 2 +; ==> folding result: 3 + +;;; same but right fold (using ff-foldr) +(print + "rfolding result: " + (ff-foldr + (lambda (result key value) + (print "key: " key ", value: " value) + (+ result 1)) + 0 + aa)) + +; ==> key: world, value: 2 +; ==> key: hello, value: 1 +; ==> key: !, value: 3 +; ==> rfolding result: 3 + +;;; at least create new array from existing (let's multiply every value by value) +(define bb (ff-map aa + (lambda (key value) + (* value value)))) +(print bb) + +; ==> #((! . 9) (hello . 1) (world . 4)) diff --git a/Task/Associative-array-Iteration/OoRexx/associative-array-iteration.rexx b/Task/Associative-array-Iteration/OoRexx/associative-array-iteration.rexx new file mode 100644 index 0000000000..950c6daa5c --- /dev/null +++ b/Task/Associative-array-Iteration/OoRexx/associative-array-iteration.rexx @@ -0,0 +1,21 @@ +d = .directory~new +d["hello"] = 1 +d["world"] = 2 +d["!"] = 3 + +-- iterating over keys: +loop key over d + say "key =" key +end + +-- iterating over values: +loop value over d~allitems + say "value =" value +end + +-- iterating over key-value pairs: +s = d~supplier +loop while s~available + say "key =" s~index", value =" s~item + s~next +end diff --git a/Task/Associative-array-Iteration/Stata/associative-array-iteration.stata b/Task/Associative-array-Iteration/Stata/associative-array-iteration.stata new file mode 100644 index 0000000000..4323c3b73d --- /dev/null +++ b/Task/Associative-array-Iteration/Stata/associative-array-iteration.stata @@ -0,0 +1,13 @@ +mata +// Create an associative array +a=asarray_create() +asarray(a,"one",1) +asarray(a,"two",2) + +// Loop over entries +loc=asarray_first(a) +do { + printf("%s %f\n",asarray_key(a,loc),asarray_contents(a,loc)) + loc=asarray_next(a,loc) +} while(loc!=NULL) +end diff --git a/Task/Associative-array-Iteration/Zkl/associative-array-iteration.zkl b/Task/Associative-array-Iteration/Zkl/associative-array-iteration.zkl new file mode 100644 index 0000000000..145005d236 --- /dev/null +++ b/Task/Associative-array-Iteration/Zkl/associative-array-iteration.zkl @@ -0,0 +1,5 @@ +var d=Dictionary("A","alpha","D","delta", "B","beta", "C", "gamma"); +d.keys.pump(Console.print,fcn(k){String(k,",")}) +d.values.apply("toUpper").println(); +d.makeReadOnly(); // can only iterate over k,v pairs if read only +foreach k,v in (d){print(k,":",v,"; ")} diff --git a/Task/Atomic-updates/D/atomic-updates.d b/Task/Atomic-updates/D/atomic-updates.d index 98b8b3faaf..cb33afd154 100644 --- a/Task/Atomic-updates/D/atomic-updates.d +++ b/Task/Atomic-updates/D/atomic-updates.d @@ -5,7 +5,7 @@ import std.algorithm: min, max; import std.parallelism: task; import core.thread: Thread; import core.sync.mutex: Mutex; -import core.time: dur; +import core.time: seconds; __gshared uint transfersCount; @@ -73,24 +73,22 @@ final class Buckets(size_t nBuckets) if (nBuckets > 0) { } void randomize(size_t N)(Buckets!N data) { - immutable maxi = data.length - 1; auto rng = Xorshift(1); while (data.running) { - immutable i = uniform(0, maxi, rng); - immutable j = uniform(0, maxi, rng); - immutable amount = uniform(0, 20, rng); + immutable i = uniform(0, data.length, rng); + immutable j = uniform(0, data.length, rng); + immutable amount = uniform!"[]"(0, 20, rng); data.transfer(i, j, amount); } } void equalize(size_t N)(Buckets!N data) { - immutable maxi = data.length - 1; auto rng = Xorshift(1); while (data.running) { - immutable i = uniform(0, maxi, rng); - immutable j = uniform(0, maxi, rng); + immutable i = uniform(0, data.length, rng); + immutable j = uniform(0, data.length, rng); immutable a = data[i]; immutable b = data[j]; if (a > b) @@ -104,7 +102,7 @@ void display(size_t N)(Buckets!N data) { foreach (immutable _; 0 .. 10) { writeln(transfersCount, " ", data); transfersCount = 0; - Thread.sleep(dur!"msecs"(1000)); + Thread.sleep(1.seconds); } data.running = false; } diff --git a/Task/Atomic-updates/Go/atomic-updates-1.go b/Task/Atomic-updates/Go/atomic-updates-1.go deleted file mode 100644 index 51fb590d98..0000000000 --- a/Task/Atomic-updates/Go/atomic-updates-1.go +++ /dev/null @@ -1,106 +0,0 @@ -package main - -import ( - "fmt" - "math/rand" - "time" -) - -// Data type required by task. -type bucketList interface { - // Two operations required by task. Updater parameter not specified - // by task, but useful for displaying update counts as an indication - // that transfer operations are happening "as often as possible." - bucketValue(bucket int) int - transfer(b1, b2, ammount, updater int) - - // Operation not specified by task, but needed for synchronization. - snapshot(bucketValues []int, transferCounts []int) - - // Operation not specified by task, but useful. - buckets() int // number of buckets -} - -// Total of all bucket values, declared as a const to demonstrate that -// it doesn't change. -const originalTotal = 1000 - -// Updater ids, used for maintaining transfer counts. -const ( - idOrder = iota - idChaos - nUpdaters -) - -func main() { - // Create a concrete object implementing the bucketList interface. - bl := newChList(10, originalTotal, nUpdaters) - - // Three concurrent tasks. - go order(bl) - go chaos(bl) - buddha(bl) -} - -// The concurrent tasks exercise the data operations by going through -// the bucketList interface. They do no explicit synchronization and -// are not responsible for maintaining invariants. - -// Exercise (1.) required by task: make values more equal. -func order(bl bucketList) { - r := rand.New(rand.NewSource(time.Now().UnixNano())) - nBuckets := bl.buckets() - for { - b1 := r.Intn(nBuckets) - b2 := r.Intn(nBuckets) - v1 := bl.bucketValue(b1) - v2 := bl.bucketValue(b2) - if v1 > v2 { - bl.transfer(b1, b2, (v1-v2)/2, idOrder) - } else { - bl.transfer(b2, b1, (v2-v1)/2, idOrder) - } - } -} - -// Exercise (2.) required by task: redistribute values. -func chaos(bl bucketList) { - r := rand.New(rand.NewSource(time.Now().UnixNano())) - nBuckets := bl.buckets() - for { - b1 := r.Intn(nBuckets) - b2 := r.Intn(nBuckets) - bl.transfer(b1, b2, r.Intn(bl.bucketValue(b1)+1), idChaos) - } -} - -// Exercise (3.) requred by task: display total. -func buddha(bl bucketList) { - nBuckets := bl.buckets() - s := make([]int, nBuckets) - tc := make([]int, nUpdaters) - var total, nTicks int - - fmt.Println("sum ---updates--- mean buckets") - tr := time.Tick(time.Second / 10) - for { - var sum int - <-tr - bl.snapshot(s, tc) - for _, l := range s { - if l < 0 { - panic("sob") // invariant not preserved - } - sum += l - } - // Output number of updates per tick and cummulative mean - // updates per tick to demonstrate "as often as possible" - // of task exercises 1 and 2. - total += tc[0] + tc[1] - nTicks++ - fmt.Printf("%d %6d %6d %7d %v\n", sum, tc[0], tc[1], total/nTicks, s) - if sum != originalTotal { - panic("weep") // invariant not preserved - } - } -} diff --git a/Task/Atomic-updates/Go/atomic-updates-2.go b/Task/Atomic-updates/Go/atomic-updates-2.go deleted file mode 100644 index d80d7558b1..0000000000 --- a/Task/Atomic-updates/Go/atomic-updates-2.go +++ /dev/null @@ -1,78 +0,0 @@ -// chList (ch for channel-synchronized) is a concrete type implementing -// the bucketList interface. The bucketList interface declared methods, -// the struct type here declares data. chList methods are repsonsible -// for synchronization so they are goroutine-safe. They are also -// responsible for maintaining the invariants that the sum of all buckets -// stays constant and that no bucket value goes negative. -type chList struct { - b []int // bucket data specified by task - s chan bool // syncronization object - tc []int // a transfer count for each updater -} - -// Constructor. -func newChList(nBuckets, initialSum, nUpdaters int) *chList { - bl := &chList{ - b: make([]int, nBuckets), - s: make(chan bool, 1), - tc: make([]int, nUpdaters), - } - // Distribute initialSum across buckets. - for i, dist := nBuckets, initialSum; i > 0; { - v := dist / i - i-- - bl.b[i] = v - dist -= v - } - // Synchronization is needed to maintain the invariant that the total - // of all bucket values stays the same. This is an implementation of - // the straightforward solution mentioned in the task description, - // ensuring that only one transfer happens at a time. Channel s - // holds a token. All methods must take the token from the channel - // before accessing data and then return the token when they are done. - // it is equivalent to a mutex. The constructor makes data available - // by initially dropping the token in the channel after all data is - // initialized. - bl.s <- true - return bl -} - -// Four methods implementing the bucketList interface. -func (bl *chList) bucketValue(b int) int { - <-bl.s // get token before accessing data - r := bl.b[b] - bl.s <- true // return token - return r -} - -func (bl *chList) transfer(b1, b2, a int, ux int) { - if b1 == b2 { // null operation - return - } - // Get access. - <-bl.s - // Clamping maintains invariant that bucket values remain nonnegative. - if a > bl.b[b1] { - a = bl.b[b1] - } - // Transfer. - bl.b[b1] -= a - bl.b[b2] += a - bl.tc[ux]++ // increment transfer count - // Release "lock". - bl.s <- true -} - -func (bl *chList) snapshot(s []int, tc []int) { - <-bl.s - copy(s, bl.b) - copy(tc, bl.tc) - for i := range bl.tc { - bl.tc[i] = 0 - } - bl.s <- true -} - -func (bl *chList) buckets() int { - return len(bl.b) -} diff --git a/Task/Atomic-updates/Go/atomic-updates-3.go b/Task/Atomic-updates/Go/atomic-updates-3.go deleted file mode 100644 index 43122a777d..0000000000 --- a/Task/Atomic-updates/Go/atomic-updates-3.go +++ /dev/null @@ -1,83 +0,0 @@ -// rwList, rw is for RWMutex-synchronized. -type rwList struct { - b []int // bucket data specified by task - - // Syncronization objects. - m []sync.Mutex // mutex for each bucket - all sync.RWMutex // mutex for entire list, for snapshot operation - - tc []int // a transfer count for each updater -} - -// Constructor. -func newRwList(nBuckets, initialSum, nUpdaters int) *rwList { - bl := &rwList{ - b: make([]int, nBuckets), - m: make([]sync.Mutex, nBuckets), - tc: make([]int, nUpdaters), - } - for i, dist := nBuckets, initialSum; i > 0; { - v := dist / i - i-- - bl.b[i] = v - dist -= v - } - return bl -} - -// Four methods implementing the bucketList interface. -func (bl *rwList) bucketValue(b int) int { - bl.m[b].Lock() // lock on bucket ensures read is atomic - r := bl.b[b] - bl.m[b].Unlock() - return r -} - -func (bl *rwList) transfer(b1, b2, a int, ux int) { - if b1 == b2 { // null operation - return - } - // RLock on list allows other simultaneous transfers. - bl.all.RLock() - // Locking lowest bucket first prevents deadlock - // with multiple tasks working at the same time. - if b1 < b2 { - bl.m[b1].Lock() - bl.m[b2].Lock() - } else { - bl.m[b2].Lock() - bl.m[b1].Lock() - } - // clamp - if a > bl.b[b1] { - a = bl.b[b1] - } - // transfer - bl.b[b1] -= a - bl.b[b2] += a - bl.tc[ux]++ // increment transfer count - // release - bl.m[b1].Unlock() - bl.m[b2].Unlock() - bl.all.RUnlock() - // With current Go, the program can hang without a call to gosched here. - // It seems that functions in the sync package don't touch the scheduler, - // (which is good) but we need to touch it here to give the channel - // operations in buddha a chance to run. (The current Go scheduler - // is basically cooperative rather than preemptive.) - runtime.Gosched() -} - -func (bl *rwList) snapshot(s []int, tc []int) { - bl.all.Lock() // RW lock on list prevents transfers during snap. - copy(s, bl.b) - copy(tc, bl.tc) - for i := range bl.tc { - bl.tc[i] = 0 - } - bl.all.Unlock() -} - -func (bl *rwList) buckets() int { - return len(bl.b) -} diff --git a/Task/Atomic-updates/Go/atomic-updates-4.go b/Task/Atomic-updates/Go/atomic-updates-4.go deleted file mode 100644 index 116370294f..0000000000 --- a/Task/Atomic-updates/Go/atomic-updates-4.go +++ /dev/null @@ -1,63 +0,0 @@ -// lf for lock-free -type lfList struct { - b []int32 - sync.RWMutex - tc []int -} - -// Constructor. -func newLfList(nBuckets, initialSum, nUpdaters int) *lfList { - bl := &lfList{ - b: make([]int32, nBuckets), - tc: make([]int, nUpdaters), - } - for i, dist := int32(nBuckets), int32(initialSum); i > 0; { - v := dist / i - i-- - bl.b[i] = v - dist -= v - } - return bl -} - -// Four methods implementing the bucketList interface. -func (bl *lfList) bucketValue(b int) int { - return int(atomic.LoadInt32(&bl.b[b])) -} - -func (bl *lfList) transfer(b1, b2, a int, ux int) { - if b1 == b2 { - return - } - bl.RLock() - for { - t := int32(a) - v1 := atomic.LoadInt32(&bl.b[b1]) - if t > v1 { - t = v1 - } - if atomic.CompareAndSwapInt32(&bl.b[b1], v1, v1-t) { - atomic.AddInt32(&bl.b[b2], t) - break - } - // else retry - } - bl.tc[ux]++ - bl.RUnlock() - runtime.Gosched() -} - -func (bl *lfList) snapshot(s []int, tc []int) { - bl.Lock() - for i, bv := range bl.b { - s[i] = int(bv) - } - for i := range bl.tc { - tc[i], bl.tc[i] = bl.tc[i], 0 - } - bl.Unlock() -} - -func (bl *lfList) buckets() int { - return len(bl.b) -} diff --git a/Task/Atomic-updates/Go/atomic-updates-5.go b/Task/Atomic-updates/Go/atomic-updates-5.go deleted file mode 100644 index b50439a4a0..0000000000 --- a/Task/Atomic-updates/Go/atomic-updates-5.go +++ /dev/null @@ -1,109 +0,0 @@ -// mnList (mn for monitor-synchronized) is a concrete type implementing -// the bucketList interface. The monitor is a goroutine, all communication -// with it is done through channels, which are the members of mnList. -// All data implementing the buckets is encapsulated in the monitor. -type mnList struct { - vrCh chan *valueReq - trCh chan *transferReq - srCh chan *snapReq - nbCh chan chan int -} - -// Constructor makes channels and starts monitor. -func newMnList(nBuckets, initialSum, nUpdaters int) *mnList { - mn := &mnList{ - make(chan *valueReq), - make(chan *transferReq), - make(chan *snapReq), - make(chan chan int), - } - go monitor(mn, nBuckets, initialSum, nUpdaters) - return mn -} - -// Monitor goroutine ecapsulates data and enters a loop to handle requests. -// The loop handles one request at a time, thus serializing all access. -func monitor(mn *mnList, nBuckets, initialSum, nUpdaters int) { - // bucket representation - b := make([]int, nBuckets) - for i, dist := nBuckets, initialSum; i > 0; { - v := dist / i - i-- - b[i] = v - dist -= v - } - // transfer count representation - count := make([]int, nUpdaters) - - // monitor loop - for { - select { - // value request operation - case vr := <-mn.vrCh: - vr.resp <- b[vr.bucket] - - // transfer operation - case tr := <-mn.trCh: - // clamp - if tr.amount > b[tr.from] { - tr.amount = b[tr.from] - } - // transfer - b[tr.from] -= tr.amount - b[tr.to] += tr.amount - count[tr.updaterId]++ - - // snap operation - case sr := <-mn.srCh: - copy(sr.bucketSnap, b) - copy(sr.countSnap, count) - for i := range count { - count[i] = 0 - } - sr.resp <- true - - // number of buckets - case nb := <-mn.nbCh: - nb <- nBuckets - } - } -} - -type valueReq struct { - bucket int - resp chan int -} - -func (mn *mnList) bucketValue(b int) int { - resp := make(chan int) - mn.vrCh <- &valueReq{b, resp} - return <-resp -} - -type transferReq struct { - from, to int - amount int - updaterId int -} - -func (mn *mnList) transfer(b1, b2, a, ux int) { - mn.trCh <- &transferReq{b1, b2, a, ux} -} - -type snapReq struct { - bucketSnap []int - countSnap []int - resp chan bool -} - -func (mn *mnList) snapshot(s []int, tc []int) { - resp := make(chan bool) - mn.srCh <- &snapReq{s, tc, resp} - <-resp -} - -func (mn *mnList) buckets() int { - resp := make(chan int) - mn.nbCh <- resp - return <-resp -} diff --git a/Task/Atomic-updates/Java/atomic-updates-1.java b/Task/Atomic-updates/Java/atomic-updates-1.java deleted file mode 100644 index 60b0c18c33..0000000000 --- a/Task/Atomic-updates/Java/atomic-updates-1.java +++ /dev/null @@ -1,119 +0,0 @@ -import java.util.Arrays; -import java.util.Random; - -public class AtomicUpdates -{ - public static class Buckets - { - private final int[] data; - - public Buckets(int[] data) - { - this.data = data.clone(); - } - - public int getBucket(int index) - { - synchronized (data) - { return data[index]; } - } - - public int transfer(int srcBucketIndex, int destBucketIndex, int amount) - { - if (amount == 0) - return 0; - // Negative transfers will happen in the opposite direction - if (amount < 0) - { - int tempIndex = srcBucketIndex; - srcBucketIndex = destBucketIndex; - destBucketIndex = tempIndex; - amount = -amount; - } - synchronized (data) - { - if (amount > data[srcBucketIndex]) - amount = data[srcBucketIndex]; - if (amount <= 0) - return 0; - data[srcBucketIndex] -= amount; - data[destBucketIndex] += amount; - return amount; - } - } - - public int[] getBuckets() - { - synchronized (data) - { return data.clone(); } - } - } - - public static int getTotal(int[] values) - { - int totalValue = 0; - for (int i = values.length - 1; i >= 0; i--) - totalValue += values[i]; - return totalValue; - } - - public static void main(String[] args) - { - final int NUM_BUCKETS = 10; - Random rnd = new Random(); - final int[] values = new int[NUM_BUCKETS]; - for (int i = 0; i < values.length; i++) - values[i] = rnd.nextInt(10); - System.out.println("Initial Array: " + getTotal(values) + " " + Arrays.toString(values)); - final Buckets buckets = new Buckets(values); - - new Thread(new Runnable() { - public void run() - { - Random r = new Random(); - while (true) - { - int srcBucketIndex = r.nextInt(NUM_BUCKETS); - int destBucketIndex = r.nextInt(NUM_BUCKETS); - int amount = (buckets.getBucket(srcBucketIndex) - buckets.getBucket(destBucketIndex)) >> 1; - if (amount != 0) - buckets.transfer(srcBucketIndex, destBucketIndex, amount); - } - } - } - ).start(); - - new Thread(new Runnable() { - public void run() - { - Random r = new Random(); - while (true) - { - int srcBucketIndex = r.nextInt(NUM_BUCKETS); - int destBucketIndex = r.nextInt(NUM_BUCKETS); - int srcBucketAmount = buckets.getBucket(srcBucketIndex); - int destBucketAmount = buckets.getBucket(destBucketIndex); - int amount = r.nextInt(srcBucketAmount + destBucketAmount + 1) - destBucketAmount; - if (amount != 0) - buckets.transfer(srcBucketIndex, destBucketIndex, amount); - } - } - } - ).start(); - - while (true) - { - long nextPrintTime = System.currentTimeMillis() + 3000; - long curTime; - while ((curTime = System.currentTimeMillis()) < nextPrintTime) - { - try - { Thread.sleep(nextPrintTime - curTime); } - catch (InterruptedException e) - { } - } - int[] bucketValues = buckets.getBuckets(); - System.out.println("Current values: " + getTotal(bucketValues) + " " + Arrays.toString(bucketValues)); - } - } -} diff --git a/Task/Atomic-updates/Java/atomic-updates-2.java b/Task/Atomic-updates/Java/atomic-updates-2.java deleted file mode 100644 index f25916a783..0000000000 --- a/Task/Atomic-updates/Java/atomic-updates-2.java +++ /dev/null @@ -1,186 +0,0 @@ -import java.util.Arrays; -import java.util.Optional; -import java.util.Random; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -public interface Buckets { - public static Buckets new_(int[] data) { - return $.new_(data); - } - public static void main(String... arguments) { - $.main(arguments); - } - public int[] getBuckets(); - - public int getBucket(int index); - - public int transfer(int srcBucketIndex, int destBucketIndex, int amount); - - public enum $ { - $$; - - private static Buckets new_(int[] data) { - return (FunctionalBuckets) function -> { - synchronized (data) { - return Optional.of(data) - .map(function) - .filter(output -> output != data) - .orElseGet(() -> data.clone()) - ; - } - }; - } - - private static void main(String... arguments) { - Stream.of(new Random()) - .parallel() - .map(r -> r.ints($.NUM_BUCKETS, 0, NUM_BUCKETS)) - .map(IntStream::toArray) - .peek(bucketValues -> Stream.of(bucketValues) - .map(values -> "Initial values: " + getTotal(values) + " " + Arrays.toString(values)) - .forEach(System.out::println) - ) - .map(Buckets::new_) - .forEach( - Stream.>of( - $::processBuckets, - $::displayBuckets - ).reduce($ -> {}, Consumer::andThen) - ) - ; - } - - @FunctionalInterface - private static interface FunctionalBuckets extends Buckets { - public Object untypedUseData(Function function); - - @SuppressWarnings("unchecked") - public default OUTPUT useData(Function function) { - return (OUTPUT) untypedUseData(function::apply); - } - - @Override - public default int[] getBuckets() { - return useData(Function.identity()); - } - - @Override - public default int getBucket(int index) { - return useData(data -> data[index]); - } - - @Override - public default int transfer(int originalSrcBucketIndex, int originalDestBucketIndex, int originalAmount) { - return useData(data -> { - int srcBucketIndex = originalSrcBucketIndex; - int destBucketIndex = originalDestBucketIndex; - int amount = originalAmount; - if (amount == 0) { - return 0; - } - // Negative transfers will happen in the opposite direction - if (amount < 0) { - int tempIndex = srcBucketIndex; - srcBucketIndex = destBucketIndex; - destBucketIndex = tempIndex; - amount = -amount; - } - if (amount > data[srcBucketIndex]) { - amount = data[srcBucketIndex]; - } - if (amount <= 0) { - return 0; - } - data[srcBucketIndex] -= amount; - data[destBucketIndex] += amount; - return amount; - }); - } - } - - private static final int NUM_BUCKETS = 10; - private static final int PRINT_DELAY = 3_000; - - private static int getTotal(int[] values) { - return Arrays.stream(values) - .parallel() - .sum() - ; - } - - private static void equalizeBuckets(Buckets buckets) { - Random r = new Random(); - while (true) { - int srcBucketIndex = r.nextInt($.NUM_BUCKETS); - int destBucketIndex = r.nextInt($.NUM_BUCKETS); - Stream.of(srcBucketIndex, destBucketIndex) - .map(buckets::getBucket) - .reduce((srcBucketAmount, destBucketAmount) -> - srcBucketAmount - destBucketAmount - ) - .map(amount -> amount >> 1) - .filter(amount -> amount != 0) - .ifPresent(amount -> - buckets.transfer(srcBucketIndex, destBucketIndex, amount) - ) - ; - } - } - - private static void randomizeBuckets (Buckets buckets) { - Random r = new Random(); - while (true) { - int srcBucketIndex = r.nextInt($.NUM_BUCKETS); - int destBucketIndex = r.nextInt($.NUM_BUCKETS); - Stream.of(srcBucketIndex, destBucketIndex) - .map(buckets::getBucket) - .reduce((srcBucketAmount, destBucketAmount) -> - r.nextInt(srcBucketAmount + destBucketAmount + 1) - destBucketAmount - ) - .filter(amount -> amount != 0) - .ifPresent(amount -> - buckets.transfer(srcBucketIndex, destBucketIndex, amount) - ) - ; - } - } - - private static Runnable run(Runnable runnable) { - return runnable; - } - - private static void processBuckets(Buckets buckets) { - Stream.>of( - $::equalizeBuckets, - $::randomizeBuckets - ) - .parallel() - .map(consumer -> run(() -> consumer.accept(buckets))) - .map(Thread::new) - .forEach(Thread::start) - ; - } - - private static void displayBuckets(Buckets buckets) { - while (true) { - long nextPrintTime = System.currentTimeMillis() + PRINT_DELAY; - long curTime; - while ((curTime = System.currentTimeMillis()) < nextPrintTime) { - try { - Thread.sleep(nextPrintTime - curTime); - } - catch (InterruptedException e) {} - } - Stream.of(buckets) - .parallel() - .map(Buckets::getBuckets) - .map(values -> "Current values: " + getTotal(values) + " " + Arrays.toString(values)) - .forEach(System.out::println) - ; - } - } - } -} diff --git a/Task/Atomic-updates/Java/atomic-updates.java b/Task/Atomic-updates/Java/atomic-updates.java new file mode 100644 index 0000000000..e82d77f488 --- /dev/null +++ b/Task/Atomic-updates/Java/atomic-updates.java @@ -0,0 +1,106 @@ +import java.util.Arrays; +import java.util.concurrent.ThreadLocalRandom; + +public class AtomicUpdates { + + private static final int NUM_BUCKETS = 10; + + public static class Buckets { + private final int[] data; + + public Buckets(int[] data) { + this.data = data.clone(); + } + + public int getBucket(int index) { + synchronized (data) { + return data[index]; + } + } + + public int transfer(int srcIndex, int dstIndex, int amount) { + if (amount < 0) + throw new IllegalArgumentException("negative amount: " + amount); + if (amount == 0) + return 0; + + synchronized (data) { + if (data[srcIndex] - amount < 0) + amount = data[srcIndex]; + if (data[dstIndex] + amount < 0) + amount = Integer.MAX_VALUE - data[dstIndex]; + if (amount < 0) + throw new IllegalStateException(); + data[srcIndex] -= amount; + data[dstIndex] += amount; + return amount; + } + } + + public int[] getBuckets() { + synchronized (data) { + return data.clone(); + } + } + } + + private static long getTotal(int[] values) { + long total = 0; + for (int value : values) { + total += value; + } + return total; + } + + public static void main(String[] args) { + ThreadLocalRandom rnd = ThreadLocalRandom.current(); + + int[] values = new int[NUM_BUCKETS]; + for (int i = 0; i < values.length; i++) + values[i] = rnd.nextInt() & Integer.MAX_VALUE; + System.out.println("Initial Array: " + getTotal(values) + " " + Arrays.toString(values)); + + Buckets buckets = new Buckets(values); + new Thread(() -> equalize(buckets), "equalizer").start(); + new Thread(() -> transferRandomAmount(buckets), "transferrer").start(); + new Thread(() -> print(buckets), "printer").start(); + } + + private static void transferRandomAmount(Buckets buckets) { + ThreadLocalRandom rnd = ThreadLocalRandom.current(); + while (true) { + int srcIndex = rnd.nextInt(NUM_BUCKETS); + int dstIndex = rnd.nextInt(NUM_BUCKETS); + int amount = rnd.nextInt() & Integer.MAX_VALUE; + buckets.transfer(srcIndex, dstIndex, amount); + } + } + + private static void equalize(Buckets buckets) { + ThreadLocalRandom rnd = ThreadLocalRandom.current(); + while (true) { + int srcIndex = rnd.nextInt(NUM_BUCKETS); + int dstIndex = rnd.nextInt(NUM_BUCKETS); + int amount = (buckets.getBucket(srcIndex) - buckets.getBucket(dstIndex)) / 2; + if (amount >= 0) + buckets.transfer(srcIndex, dstIndex, amount); + } + } + + private static void print(Buckets buckets) { + while (true) { + long nextPrintTime = System.currentTimeMillis() + 3000; + long now; + while ((now = System.currentTimeMillis()) < nextPrintTime) { + try { + Thread.sleep(nextPrintTime - now); + } catch (InterruptedException e) { + return; + } + } + + int[] bucketValues = buckets.getBuckets(); + System.out.println("Current values: " + getTotal(bucketValues) + " " + Arrays.toString(bucketValues)); + } + } +} diff --git a/Task/Atomic-updates/Zkl/atomic-updates-1.zkl b/Task/Atomic-updates/Zkl/atomic-updates-1.zkl new file mode 100644 index 0000000000..86332b4969 --- /dev/null +++ b/Task/Atomic-updates/Zkl/atomic-updates-1.zkl @@ -0,0 +1,29 @@ +class B{ + const N=10; + var [const] + buckets=(1).pump(N,List).copy(), //(1,2,3...) + lock=Atomic.Lock(), cnt=Atomic.Int(); + fcn init{ "Initial sum: ".println(values().sum()); } + fcn transferArb{ // transfer arbitary amount from 1 bucket to another + b1:=(0).random(N); b2:=(0).random(N); + critical(lock){ + t:=(0).random(buckets[b1]); + buckets[b1]=buckets[b1]-t; buckets[b2]=buckets[b2]+t; + } + cnt.inc(); + } + fcn transferEq{ // try to make two buckets equal + b1:=(0).random(N); b2:=(0).random(N); + critical(lock){ + v1:=buckets[b1]; v2:=buckets[b2]; + t:=(v1-v2).abs()/2; + if (v1",v.sum()," ", b.cnt.value," transfers ", + vm.numThreads," threads"); + Atomic.sleep(2.5); +} diff --git a/Task/Atomic-updates/Zkl/atomic-updates-3.zkl b/Task/Atomic-updates/Zkl/atomic-updates-3.zkl new file mode 100644 index 0000000000..741f226494 --- /dev/null +++ b/Task/Atomic-updates/Zkl/atomic-updates-3.zkl @@ -0,0 +1,30 @@ +class C{ + const N=10; + var [const] + buckets=(1).pump(N,List).copy(), //(1,2,3...) + pipe = Thread.Pipe(), cnt=Atomic.Int(); + fcn init{ + pipe.write(buckets); + "Initial sum: ".println(values().sum()); + } + fcn transferArb{ // transfer arbitary amount from 1 bucket to another + b1:=(0).random(N); b2:=(0).random(N); + v:=pipe.read(); + t:=(0).random(v[b1]); v[b1]=v[b1]-t; v[b2]=v[b2]+t; + pipe.write(v); + cnt.inc(); + } + fcn transferEq{ // try to make two buckets equal + b1:=(0).random(N); b2:=(0).random(N); + v:=pipe.read(); + v1:=v[b1]; v2:=v[b2]; t:=(v1-v2).abs()/2; + if (v1 seen = new ArrayList<>(n); - int current = 0; - int length = 0; - while(true){ - length++; - seen.add(current); - current = random[current]; - if(seen.contains(current)){ - break; - } - } - sum += length; - } - return sum/N; - } - public static void main(String args[]){ - System.out.println(" N average analytical (error)\n=== ========= ============ ========="); - for(int i=1;i<=20;i++){ - float avg = average(i); - float ana = analytical(i); - System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)",i,avg,ana,((ana-avg)/ana*100)));; - } - } + + private static final int N = 100000; + + //analytical(n) = sum_(i=1)^n (n!/(n-i)!/n**i) + private static double analytical(int n) { + double[] factorial = new double[n + 1]; + double[] powers = new double[n + 1]; + powers[0] = 1.0; + factorial[0] = 1.0; + for (int i = 1; i <= n; i++) { + factorial[i] = factorial[i - 1] * i; + powers[i] = powers[i - 1] * n; + } + double sum = 0; + //memoized factorial and powers + for (int i = 1; i <= n; i++) { + sum += factorial[n] / factorial[n - i] / powers[i]; + } + return sum; + } + + private static double average(int n) { + Random rnd = new Random(); + double sum = 0.0; + for (int a = 0; a < N; a++) { + int[] random = new int[n]; + for (int i = 0; i < n; i++) { + random[i] = rnd.nextInt(n); + } + Set seen = new HashSet<>(n); + int current = 0; + int length = 0; + while (seen.add(current)) { + length++; + current = random[current]; + } + sum += length; + } + return sum / N; + } + + public static void main(String[] args) { + System.out.println(" N average analytical (error)"); + System.out.println("=== ========= ============ ========="); + for (int i = 1; i <= 20; i++) { + double avg = average(i); + double ana = analytical(i); + System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100))); + } + } } diff --git a/Task/Average-loop-length/Julia/average-loop-length.julia b/Task/Average-loop-length/Julia/average-loop-length.julia new file mode 100644 index 0000000000..ea5a677bc5 --- /dev/null +++ b/Task/Average-loop-length/Julia/average-loop-length.julia @@ -0,0 +1,27 @@ +# Version 5.2 +analytical(n::Integer) = sum(factorial(n) / big(n) ^ i / factorial(n - i) for i = 1:n) + +function test(n::Integer, times::Integer = 1000000) + c = 0 + for i = range(0, times) + x, bits = 1, 0 + while (bits & x) == 0 + c += 1 + bits |= x + x = 1 << rand(0:(n - 1)) + end + end + return c / times +end + +function main(n::Integer) + println(" n\tavg\texp.\tdiff\n-------------------------------") + for n in 1:n + avg = test(n) + theory = analytical(n) + diff = (avg / theory - 1) * 100 + @printf(STDOUT, "%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff) + end +end + +main(20) diff --git a/Task/Average-loop-length/Kotlin/average-loop-length.kotlin b/Task/Average-loop-length/Kotlin/average-loop-length.kotlin new file mode 100644 index 0000000000..304eb4917b --- /dev/null +++ b/Task/Average-loop-length/Kotlin/average-loop-length.kotlin @@ -0,0 +1,38 @@ +const val NMAX = 20 +const val TESTS = 1000000 +val rand = java.util.Random() + +fun avg(n: Int): Double { + var sum = 0 + for (t in 0 until TESTS) { + val v = BooleanArray(NMAX) + var x = 0 + while (!v[x]) { + v[x] = true + sum++ + x = rand.nextInt(n) + } + } + return sum.toDouble() / TESTS +} + +fun ana(n: Int): Double { + val nn = n.toDouble() + var term = 1.0 + var sum = 1.0 + for (i in n - 1 downTo 1) { + term *= i / nn + sum += term + } + return sum +} + +fun main(args: Array) { + println(" N average analytical (error)") + println("=== ========= ============ =========") + for (n in 1..NMAX) { + val a = avg(n) + val b = ana(n) + println(String.format("%3d %6.4f %10.4f (%4.2f%%)", n, a, b, Math.abs(a - b) / b * 100.0)) + } +} diff --git a/Task/Average-loop-length/Nim/average-loop-length.nim b/Task/Average-loop-length/Nim/average-loop-length.nim index 0179fe9023..f383da4748 100644 --- a/Task/Average-loop-length/Nim/average-loop-length.nim +++ b/Task/Average-loop-length/Nim/average-loop-length.nim @@ -1,20 +1,20 @@ -import math, strfmt +import random, math, strfmt randomize() const maxN = 20 times = 1_000_000 -proc factorial(n): float = +proc factorial(n: int): float = result = 1 for i in 1 .. n: result *= i.float -proc expected(n): float = +proc expected(n: int): float = for i in 1 .. n: result += factorial(n) / pow(n.float, i.float) / factorial(n - i) -proc test(n, times): int = +proc test(n, times: int): int = for i in 1 .. times: var x = 1 diff --git a/Task/Average-loop-length/REXX/average-loop-length.rexx b/Task/Average-loop-length/REXX/average-loop-length.rexx index 579000f02c..12d8ff69e3 100644 --- a/Task/Average-loop-length/REXX/average-loop-length.rexx +++ b/Task/Average-loop-length/REXX/average-loop-length.rexx @@ -3,34 +3,34 @@ parse arg runs tests seed . /*obtain optional arguments fro if runs =='' | runs =="," then runs = 40 /*Not specified? Then use the default.*/ if tests =='' | tests =="," then tests= 1000000 /* " " " " " " */ if datatype(seed,'W') then call random ,, seed /*Is integer? For RAND repeatability.*/ -!.=0; !.0=1 /*used for factorial (!) memoization.*/ +!.=0; !.0=1 /*used for factorial (!) memoization.*/ numeric digits 100000 /*be able to calculate 25k! if need be.*/ numeric digits max(9, length( !(runs) ) ) /*set the NUMERIC DIGITS for !(runs). */ -say right( runs, 24) 'runs' /*display number of runs we're using.*/ -say right( tests, 24) 'tests' /* " " " tests " " */ -say right( digits(), 24) 'digits' /* " " " digits " " */ +say right( runs, 24) 'runs' /*display number of runs we're using.*/ +say right( tests, 24) 'tests' /* " " " tests " " */ +say right( digits(), 24) 'digits' /* " " " digits " " */ say say " N average exact % error " /* ◄─── title, header ►────────┐ */ hdr=" ═══ ═════════ ═════════ ═════════"; pad=left('',3) /* ◄────────┘ */ say hdr - do #=1 for runs; av=fmtD(exact(#)) /*use four digits past decimal point. */ - xa=fmtD(exper(#)) /* " " " " " " */ - say right(#,9) pad xa pad av pad fmtD(abs(xa-av)*100/av) /*display values.*/ + do #=1 for runs; av=fmtD( exact(#) ) /*use four digits past decimal point. */ + xa=fmtD( exper(#) ) /* " " " " " " */ + say right(#,9) pad xa pad av pad fmtD( abs(xa-av) * 100 / av) /*show values.*/ end /*#*/ say hdr /*display the final header (some bars).*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ !: procedure expose !.; parse arg z; if !.z\==0 then return !.z - !=1; do j=2 for z-1; !=!*j; !.j=!; end; /*factorial*/ return ! + !=1; do j=2 for z -1; !=!*j; !.j=!; end; /*compute factorial*/ return ! /*──────────────────────────────────────────────────────────────────────────────────────*/ -exact: parse arg x; s=0; do j=1 for x; s=s+!(x)/!(x-j)/x**j; end; return s +exact: parse arg x; s=0; do j=1 for x; s=s + !(x) / !(x-j) / x**j; end; return s /*──────────────────────────────────────────────────────────────────────────────────────*/ -exper: parse arg n; k=0; do tests; $.=0 /*do it TESTS times.*/ - do n; r=random(1,n); if $.r then leave - $.r=1; k=k+1 /*bump the counter. */ +exper: parse arg n; k=0; do tests; $.=0 /*do it TESTS times.*/ + do n; r=random(1, n); if $.r then leave + $.r=1; k=k + 1 /*bump the counter. */ end /*n*/ end /*tests*/ return k/tests /*──────────────────────────────────────────────────────────────────────────────────────*/ -fmtD: parse arg y,d; d=word(d 4,1); y=format(y,,d); parse var y w '.' f - if f=0 then return w || left('', d+1); return y +fmtD: parse arg y,d; d=word(d 4, 1); y=format(y, , d); parse var y w '.' f + if f=0 then return w || left('', d +1); return y diff --git a/Task/Average-loop-length/Scheme/average-loop-length.ss b/Task/Average-loop-length/Scheme/average-loop-length.ss new file mode 100644 index 0000000000..302238a700 --- /dev/null +++ b/Task/Average-loop-length/Scheme/average-loop-length.ss @@ -0,0 +1,56 @@ +(import (scheme base) + (scheme write) + (srfi 1 lists) + (only (srfi 13 strings) string-pad-right) + (srfi 27 random-bits)) + +(define (analytical-function n) + (define (factorial n) + (fold * 1 (iota n 1))) + ; + (fold (lambda (i sum) + (+ sum + (/ (factorial n) (expt n i) (factorial (- n i))))) + 0 + (iota n 1))) + +(define (simulation n runs) + (define (single-simulation) + (random-source-randomize! default-random-source) + (let ((vec (make-vector n #f))) + (let loop ((count 0) + (num (random-integer n))) + (if (vector-ref vec num) + count + (begin (vector-set! vec num #t) + (loop (+ 1 count) + (random-integer n))))))) + ;; + (let loop ((total 0) + (run runs)) + (if (zero? run) + (/ total runs) + (loop (+ total (single-simulation)) + (- run 1))))) + +(display " N average formula (error) \n") +(display "=== ========= ========= =========\n") +(for-each + (lambda (n) + (let ((simulation (inexact (simulation n 10000))) + (formula (inexact (analytical-function n)))) + (display + (string-append + " " + (string-pad-right (number->string n) 3) + " " + (string-pad-right (number->string simulation) 6) + " " + (string-pad-right (number->string formula) 6) + " (" + (string-pad-right + (number->string (* 100 (/ (- simulation formula) formula))) + 5) + "%)")) + (newline))) + (iota 20 1)) diff --git a/Task/Average-loop-length/Zkl/average-loop-length.zkl b/Task/Average-loop-length/Zkl/average-loop-length.zkl new file mode 100644 index 0000000000..b560a45847 --- /dev/null +++ b/Task/Average-loop-length/Zkl/average-loop-length.zkl @@ -0,0 +1,33 @@ +const N=20; + +(" N average analytical (error)").println(); +("=== ========= ============ =========").println(); +foreach n in ([1..N]){ + a := avg(n); + b := ana(n); + "%3d %9.4f %12.4f (%6.2f%%)".fmt( + n, a, b, ((a-b)/b*100)).println(); +} + +fcn f(n){ (0).random(n) } + +fcn avg(n){ + tests := 0d10_000; + sum := 0; + do(tests){ + v:=(0).pump(n,List,T(Void,False)).copy(); + while(1){ + z := f(n); + if(v[z]) break; + v[z] = True; + sum += 1; + } + } + return(sum.toFloat() / tests); +} + +fcn fact(n) { (1).reduce(n,fcn(N,n){N*n},1.0) } //-->Float +fcn ana(n){ + n=n.toFloat(); + (1).reduce(n,'wrap(sum,i){ sum+fact(n)/n.pow(i)/fact(n-i) },0.0); +} diff --git a/Task/Averages-Arithmetic-mean/Aime/averages-arithmetic-mean.aime b/Task/Averages-Arithmetic-mean/Aime/averages-arithmetic-mean.aime new file mode 100644 index 0000000000..d81327ad0d --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Aime/averages-arithmetic-mean.aime @@ -0,0 +1,21 @@ +real +mean(list l) +{ + integer i; + real sum, x; + + sum = 0; + for (i, x in l) { + sum += x; + } + + return sum / ~l; +} + +integer +main(void) +{ + o_form("%f\n", mean(l_effect(4.5, 7.25, 5r, 5.75))); + + return 0; +} diff --git a/Task/Averages-Arithmetic-mean/Astro/averages-arithmetic-mean.astro b/Task/Averages-Arithmetic-mean/Astro/averages-arithmetic-mean.astro new file mode 100644 index 0000000000..8e948d7c0a --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Astro/averages-arithmetic-mean.astro @@ -0,0 +1,3 @@ +mean([1, 2, 3]) +mean([1:10]) +mean([]) diff --git a/Task/Averages-Arithmetic-mean/Bc/averages-arithmetic-mean.bc b/Task/Averages-Arithmetic-mean/Bc/averages-arithmetic-mean.bc new file mode 100644 index 0000000000..1c8d38fca1 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Bc/averages-arithmetic-mean.bc @@ -0,0 +1,8 @@ +define m(a[], n) { + auto i, s + + for (i = 0; i < n; i++) { + s += a[i] + } + return(s / n) +} diff --git a/Task/Averages-Arithmetic-mean/Brainf---/averages-arithmetic-mean.bf b/Task/Averages-Arithmetic-mean/Brainf---/averages-arithmetic-mean.bf deleted file mode 100644 index 92dd39119f..0000000000 --- a/Task/Averages-Arithmetic-mean/Brainf---/averages-arithmetic-mean.bf +++ /dev/null @@ -1 +0,0 @@ ->,[-<+>>+<],<[->-<]>[-->+<]>. diff --git a/Task/Averages-Arithmetic-mean/Crystal/averages-arithmetic-mean.crystal b/Task/Averages-Arithmetic-mean/Crystal/averages-arithmetic-mean.crystal new file mode 100644 index 0000000000..bd91b82c02 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Crystal/averages-arithmetic-mean.crystal @@ -0,0 +1,4 @@ +# Crystal will return NaN if an empty array is passed +def mean(arr) : Float64 + arr.sum / arr.size.to_f +end diff --git a/Task/Averages-Arithmetic-mean/Dc/averages-arithmetic-mean-1.dc b/Task/Averages-Arithmetic-mean/Dc/averages-arithmetic-mean-1.dc new file mode 100644 index 0000000000..6585bda12c --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Dc/averages-arithmetic-mean-1.dc @@ -0,0 +1,2 @@ +1 2 3 5 7 zsn1k[+z1<+]ds+xln/p +3.6 diff --git a/Task/Averages-Arithmetic-mean/Dc/averages-arithmetic-mean-2.dc b/Task/Averages-Arithmetic-mean/Dc/averages-arithmetic-mean-2.dc new file mode 100644 index 0000000000..f7aba800e4 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Dc/averages-arithmetic-mean-2.dc @@ -0,0 +1,6 @@ +[[Nada Mean: ]Ppq]sq +zd0=qsn [stack length = n]sz +1k [precision can be altered]sz +[+z1<+]ds+x[Sum: ]Pp +ln/[Mean: ]Pp +[Sample size: ]Plnp diff --git a/Task/Averages-Arithmetic-mean/Dc/averages-arithmetic-mean-3.dc b/Task/Averages-Arithmetic-mean/Dc/averages-arithmetic-mean-3.dc new file mode 100644 index 0000000000..68f350140d --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Dc/averages-arithmetic-mean-3.dc @@ -0,0 +1,5 @@ +$ dc sample.dc amean.cd +Sum: 18 +Mean: 3.6 +Sample size: 5 +$ diff --git a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena index fe3354484a..11bbbe118e 100644 --- a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena +++ b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena @@ -1,27 +1,25 @@ -#define system. -#define extensions. +import extensions. -#class(extension)op +extension op { - #method average + average [ - #var aSum := Real new. - #var aCount := Integer new:0. + var aSum := Real new. + var aCount := Integer new:0. - #var anEnumerator := self enumerator. + var anEnumerator := self enumerator. - #loop (anEnumerator next)? + while (anEnumerator next) [ - aSum += anEnumerator get. - aCount += 1. + aSum append(anEnumerator get). + aCount append(1). ]. ^ aSum / aCount. ] } - -#symbol program = +program = [ - #var anArray := (1, 2, 3, 4, 5, 6, 7, 8). - console writeLine:"Arithmetic mean of {":anArray:"} is ":(anArray average). + var anArray := (1, 2, 3, 4, 5, 6, 7, 8). + console printLine("Arithmetic mean of {",anArray,"} is ",anArray average); readChar. ]. diff --git a/Task/Averages-Arithmetic-mean/Haskell/averages-arithmetic-mean-3.hs b/Task/Averages-Arithmetic-mean/Haskell/averages-arithmetic-mean-3.hs index d3bd10bf48..049b6b7479 100644 --- a/Task/Averages-Arithmetic-mean/Haskell/averages-arithmetic-mean-3.hs +++ b/Task/Averages-Arithmetic-mean/Haskell/averages-arithmetic-mean-3.hs @@ -1,5 +1,19 @@ {-# LANGUAGE BangPatterns #-} -import Data.List (foldl') -mean :: (Real n, Fractional m) => [n] -> m -mean xs = let (s,l) = foldl' f (0, 0) xs in realToFrac s / l - where f (!s,!l) x = (s+x,l+1) + +import Data.List (foldl') --' + +mean + :: (Real n, Fractional m) + => [n] -> m +mean xs = + let (s, l) = + foldl' --' + f + (0, 0) + xs + in realToFrac s / l + where + f (!s, !l) x = (s + x, l + 1) + +main :: IO () +main = print $ mean [1 .. 100] diff --git a/Task/Averages-Arithmetic-mean/Java/averages-arithmetic-mean.java b/Task/Averages-Arithmetic-mean/Java/averages-arithmetic-mean.java index 4eb4124892..c26919d67a 100644 --- a/Task/Averages-Arithmetic-mean/Java/averages-arithmetic-mean.java +++ b/Task/Averages-Arithmetic-mean/Java/averages-arithmetic-mean.java @@ -1,7 +1,7 @@ -... -double sum = 0; -for(double i : nums){ - sum += i; +public static double avg(double... arr) { + double sum = 0.0; + for (double x : arr) { + sum += x; + } + return sum / arr.length; } -System.out.println("The mean is: " + ((nums.length != 0) ? (sum / nums.length) : 0)); -... diff --git a/Task/Averages-Arithmetic-mean/jq/averages-arithmetic-mean-1.jq b/Task/Averages-Arithmetic-mean/Jq/averages-arithmetic-mean-1.jq similarity index 100% rename from Task/Averages-Arithmetic-mean/jq/averages-arithmetic-mean-1.jq rename to Task/Averages-Arithmetic-mean/Jq/averages-arithmetic-mean-1.jq diff --git a/Task/Averages-Arithmetic-mean/jq/averages-arithmetic-mean-2.jq b/Task/Averages-Arithmetic-mean/Jq/averages-arithmetic-mean-2.jq similarity index 100% rename from Task/Averages-Arithmetic-mean/jq/averages-arithmetic-mean-2.jq rename to Task/Averages-Arithmetic-mean/Jq/averages-arithmetic-mean-2.jq diff --git a/Task/Averages-Arithmetic-mean/Kotlin/averages-arithmetic-mean.kotlin b/Task/Averages-Arithmetic-mean/Kotlin/averages-arithmetic-mean.kotlin index 07b4122cea..58a2a4cf4a 100644 --- a/Task/Averages-Arithmetic-mean/Kotlin/averages-arithmetic-mean.kotlin +++ b/Task/Averages-Arithmetic-mean/Kotlin/averages-arithmetic-mean.kotlin @@ -1,2 +1,4 @@ -val nums = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) -println("average = %f".format(nums.average())) +fun main(args: Array) { + val nums = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) + println("average = %f".format(nums.average())) +} diff --git a/Task/Averages-Arithmetic-mean/Nim/averages-arithmetic-mean.nim b/Task/Averages-Arithmetic-mean/Nim/averages-arithmetic-mean.nim index 491cece56f..9179ce76d8 100644 --- a/Task/Averages-Arithmetic-mean/Nim/averages-arithmetic-mean.nim +++ b/Task/Averages-Arithmetic-mean/Nim/averages-arithmetic-mean.nim @@ -1,6 +1,6 @@ import strutils -proc mean(xs): float = +proc mean(xs: openArray[float]): float = for x in xs: result += x result = result / float(xs.len) @@ -8,4 +8,4 @@ proc mean(xs): float = var v = @[1.0, 2.0, 2.718, 3.0, 3.142] for i in 0..5: echo "mean of first ", v.len, " = ", formatFloat(mean(v), precision = 0) - v.setLen(v.high) + if v.len > 0: v.setLen(v.high) diff --git a/Task/Averages-Arithmetic-mean/OoRexx/averages-arithmetic-mean.rexx b/Task/Averages-Arithmetic-mean/OoRexx/averages-arithmetic-mean.rexx new file mode 100644 index 0000000000..9a58c7114c --- /dev/null +++ b/Task/Averages-Arithmetic-mean/OoRexx/averages-arithmetic-mean.rexx @@ -0,0 +1,21 @@ +call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) +call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11) +call testAverage .array~of(10, 20, 30, 40, 50, -100, 4.7, -11e2) +call testAverage .array~new + +::routine testAverage + use arg numbers + say "numbers =" numbers~toString("l", ", ") + say "average =" average(numbers) + say + +::routine average + use arg numbers + -- return zero for an empty list + if numbers~isempty then return 0 + + sum = 0 + do number over numbers + sum += number + end + return sum/numbers~items diff --git a/Task/Averages-Arithmetic-mean/Stata/averages-arithmetic-mean-1.stata b/Task/Averages-Arithmetic-mean/Stata/averages-arithmetic-mean-1.stata new file mode 100644 index 0000000000..6a99901c10 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Stata/averages-arithmetic-mean-1.stata @@ -0,0 +1,31 @@ +clear all +input str20 country population +Belgium 11311.1 +Bulgaria 7153.8 +"Czech Republic" 10553.8 +Denmark 5707.3 +Germany 82175.7 +Estonia 1315.9 +Ireland 4724.7 +Greece 10783.7 +end + +. mean population + +Mean estimation Number of obs = 8 + +-------------------------------------------------------------- + | Mean Std. Err. [95% Conf. Interval] +-------------+------------------------------------------------ + population | 16715.75 9431.077 -5585.203 39016.7 +-------------------------------------------------------------- + +. tabstat population, statistic(mean) + variable | mean +-------------+---------- + population | 16715.75 +------------------------ + +. quietly summarize population +. display r(mean) +16715.75 diff --git a/Task/Averages-Arithmetic-mean/Stata/averages-arithmetic-mean-2.stata b/Task/Averages-Arithmetic-mean/Stata/averages-arithmetic-mean-2.stata new file mode 100644 index 0000000000..472544b25e --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Stata/averages-arithmetic-mean-2.stata @@ -0,0 +1,6 @@ +mata +a=11311.1\7153.8\10553.8\5707.3\ +82175.7\1315.9\4724.7\10783.7 + +mean(a) +16715.75 diff --git a/Task/Averages-Arithmetic-mean/TypeScript/averages-arithmetic-mean.type b/Task/Averages-Arithmetic-mean/TypeScript/averages-arithmetic-mean.type new file mode 100644 index 0000000000..3b4689cbec --- /dev/null +++ b/Task/Averages-Arithmetic-mean/TypeScript/averages-arithmetic-mean.type @@ -0,0 +1,15 @@ +function mean(numbersArr) +{ + let arrLen = numbersArr.length; + if (arrLen > 0) { + let sum: number = 0; + for (let i of numbersArr) { + sum += i; + } + return sum/arrLen; + } + else return "Not defined"; +} + +alert( mean( [1,2,3,4,5] ) ); +alert( mean( [] ) ); diff --git a/Task/Averages-Arithmetic-mean/Zkl/averages-arithmetic-mean-1.zkl b/Task/Averages-Arithmetic-mean/Zkl/averages-arithmetic-mean-1.zkl new file mode 100644 index 0000000000..bb9cad72c6 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Zkl/averages-arithmetic-mean-1.zkl @@ -0,0 +1,3 @@ +fcn mean(a,b,c,etc){ z:=vm.arglist; z.reduce('+,0.0)/z.len() } +mean(3,1,4,1,5,9); //-->3.83333 +mean(); //-->Exception thrown: MathError(NaN (Not a number)) diff --git a/Task/Averages-Arithmetic-mean/Zkl/averages-arithmetic-mean-2.zkl b/Task/Averages-Arithmetic-mean/Zkl/averages-arithmetic-mean-2.zkl new file mode 100644 index 0000000000..43ed5ee2d5 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Zkl/averages-arithmetic-mean-2.zkl @@ -0,0 +1,2 @@ +fcn meanV(z){ z.reduce('+,0.0)/z.len() } +meanV(T(3,1,4,1,5,9)); // --> 3.83333 diff --git a/Task/Averages-Mean-angle/Haskell/averages-mean-angle-1.hs b/Task/Averages-Mean-angle/Haskell/averages-mean-angle-1.hs index c387b57855..8dec4a75cd 100644 --- a/Task/Averages-Mean-angle/Haskell/averages-mean-angle-1.hs +++ b/Task/Averages-Mean-angle/Haskell/averages-mean-angle-1.hs @@ -1,6 +1,15 @@ import Data.Complex (cis, phase) +meanAngle + :: RealFloat c + => [c] -> c meanAngle = (/ pi) . (* 180) . phase . sum . map (cis . (/ 180) . (* pi)) -main = mapM_ (\angles -> putStrLn $ "The mean angle of " ++ show angles ++ " is: " ++ show (meanAngle angles) ++ " degrees") - [[350, 10], [90, 180, 270, 360], [10, 20, 30]] +main :: IO () +main = + mapM_ + (\angles -> + putStrLn $ + "The mean angle of " ++ + show angles ++ " is: " ++ show (meanAngle angles) ++ " degrees") + [[350, 10], [90, 180, 270, 360], [10, 20, 30]] diff --git a/Task/Averages-Mean-angle/Java/averages-mean-angle.java b/Task/Averages-Mean-angle/Java/averages-mean-angle.java index 52c4abe02f..8c9b185361 100644 --- a/Task/Averages-Mean-angle/Java/averages-mean-angle.java +++ b/Task/Averages-Mean-angle/Java/averages-mean-angle.java @@ -1,60 +1,30 @@ -import java.util.ArrayList; import java.util.Arrays; -import java.util.List; -public class RAvgMeanAngle { +public class AverageMeanAngle { - private static final List> samples; - - static { - samples = new ArrayList<>(); - samples.add(Arrays.asList(350.0, 10.0)); - samples.add(Arrays.asList(90.0, 180.0, 270.0, 360.0)); - samples.add(Arrays.asList(10.0, 20.0, 30.0)); - samples.add(Arrays.asList(370.0)); - samples.add(Arrays.asList(180.0)); - } - - public RAvgMeanAngle() { - - return; - } - - public double getMeanAngle(List sample) { - - double x_component = 0.0; - double y_component = 0.0; - double avg_d, avg_r; - - for (double angle_d : sample) { - double angle_r; - angle_r = Math.toRadians(angle_d); - x_component += Math.cos(angle_r); - y_component += Math.sin(angle_r); - } - x_component /= sample.size(); - y_component /= sample.size(); - avg_r = Math.atan2(y_component, x_component); - avg_d = Math.toDegrees(avg_r); - - return avg_d; - } - - public static void main(String[] args) { - - runSample(args); - - return; - } - - public static void runSample(String[] args) { - - RAvgMeanAngle main = new RAvgMeanAngle(); - for (List sample : samples) { - double meanAngle = main.getMeanAngle(sample); - System.out.printf("The mean angle of %s is:%n%12.6f%n%n", sample, meanAngle); + public static void main(String[] args) { + printAverageAngle(350.0, 10.0); + printAverageAngle(90.0, 180.0, 270.0, 360.0); + printAverageAngle(10.0, 20.0, 30.0); + printAverageAngle(370.0); + printAverageAngle(180.0); } - return; - } + private static void printAverageAngle(double... sample) { + double meanAngle = getMeanAngle(sample); + System.out.printf("The mean angle of %s is %s%n", Arrays.toString(sample), meanAngle); + } + + public static double getMeanAngle(double... anglesDeg) { + double x = 0.0; + double y = 0.0; + + for (double angleD : anglesDeg) { + double angleR = Math.toRadians(angleD); + x += Math.cos(angleR); + y += Math.sin(angleR); + } + double avgR = Math.atan2(y / anglesDeg.length, x / anglesDeg.length); + return Math.toDegrees(avgR); + } } diff --git a/Task/Averages-Mean-angle/jq/averages-mean-angle-1.jq b/Task/Averages-Mean-angle/Jq/averages-mean-angle-1.jq similarity index 100% rename from Task/Averages-Mean-angle/jq/averages-mean-angle-1.jq rename to Task/Averages-Mean-angle/Jq/averages-mean-angle-1.jq diff --git a/Task/Averages-Mean-angle/jq/averages-mean-angle-2.jq b/Task/Averages-Mean-angle/Jq/averages-mean-angle-2.jq similarity index 100% rename from Task/Averages-Mean-angle/jq/averages-mean-angle-2.jq rename to Task/Averages-Mean-angle/Jq/averages-mean-angle-2.jq diff --git a/Task/Averages-Mean-angle/jq/averages-mean-angle-3.jq b/Task/Averages-Mean-angle/Jq/averages-mean-angle-3.jq similarity index 100% rename from Task/Averages-Mean-angle/jq/averages-mean-angle-3.jq rename to Task/Averages-Mean-angle/Jq/averages-mean-angle-3.jq diff --git a/Task/Averages-Mean-angle/jq/averages-mean-angle-4.jq b/Task/Averages-Mean-angle/Jq/averages-mean-angle-4.jq similarity index 100% rename from Task/Averages-Mean-angle/jq/averages-mean-angle-4.jq rename to Task/Averages-Mean-angle/Jq/averages-mean-angle-4.jq diff --git a/Task/Averages-Mean-angle/Kotlin/averages-mean-angle.kotlin b/Task/Averages-Mean-angle/Kotlin/averages-mean-angle.kotlin new file mode 100644 index 0000000000..8a803bbf26 --- /dev/null +++ b/Task/Averages-Mean-angle/Kotlin/averages-mean-angle.kotlin @@ -0,0 +1,17 @@ +// version 1.0.5-2 + +fun meanAngle(angles: DoubleArray): Double { + val sinSum = angles.sumByDouble { Math.sin(it * Math.PI / 180.0) } + val cosSum = angles.sumByDouble { Math.cos(it * Math.PI / 180.0) } + return Math.atan2(sinSum / angles.size, cosSum / angles.size) * 180.0 / Math.PI +} + +fun main(args: Array) { + val angles1 = doubleArrayOf(350.0, 10.0) + val angles2 = doubleArrayOf(90.0, 180.0, 270.0, 360.0) + val angles3 = doubleArrayOf(10.0, 20.0, 30.0) + val fmt = "%.2f degrees" // format results to 2 decimal places + println("Mean for angles 1 is ${fmt.format(meanAngle(angles1))}") + println("Mean for angles 2 is ${fmt.format(meanAngle(angles2))}") + println("Mean for angles 3 is ${fmt.format(meanAngle(angles3))}") +} diff --git a/Task/Averages-Mean-angle/Lua/averages-mean-angle.lua b/Task/Averages-Mean-angle/Lua/averages-mean-angle.lua index 933a26c4f4..472ee101e2 100644 --- a/Task/Averages-Mean-angle/Lua/averages-mean-angle.lua +++ b/Task/Averages-Mean-angle/Lua/averages-mean-angle.lua @@ -1,11 +1,11 @@ function meanAngle (angleList) - local sumSin, sumCos = 0, 0 - for i, angle in pairs(angleList) do - sumSin = sumSin + math.sin(math.rad(angle)) - sumCos = sumCos + math.cos(math.rad(angle)) - end - local result = math.deg(math.atan2(sumSin, sumCos)) - return string.format("%.2f", result) + local sumSin, sumCos = 0, 0 + for i, angle in pairs(angleList) do + sumSin = sumSin + math.sin(math.rad(angle)) + sumCos = sumCos + math.cos(math.rad(angle)) + end + local result = math.deg(math.atan2(sumSin, sumCos)) + return string.format("%.2f", result) end print(meanAngle({350, 10})) diff --git a/Task/Averages-Mean-angle/Nim/averages-mean-angle.nim b/Task/Averages-Mean-angle/Nim/averages-mean-angle.nim index 55635307b7..8bf6448305 100644 --- a/Task/Averages-Mean-angle/Nim/averages-mean-angle.nim +++ b/Task/Averages-Mean-angle/Nim/averages-mean-angle.nim @@ -1,12 +1,12 @@ import math, complex -proc rect(r, phi): Complex = (r * cos(phi), sin(phi)) -proc phase(c): float = arctan2(c.im, c.re) +proc rect(r, phi: float): Complex = (r * cos(phi), sin(phi)) +proc phase(c: Complex): float = arctan2(c.im, c.re) -proc radians(x): float = (x * Pi) / 180.0 -proc degrees(x): float = (x * 180.0) / Pi +proc radians(x: float): float = (x * Pi) / 180.0 +proc degrees(x: float): float = (x * 180.0) / Pi -proc meanAngle(deg): float = +proc meanAngle(deg: openArray[float]): float = var c: Complex for d in deg: c += rect(1.0, radians(d)) diff --git a/Task/Averages-Mean-angle/OoRexx/averages-mean-angle.rexx b/Task/Averages-Mean-angle/OoRexx/averages-mean-angle.rexx new file mode 100644 index 0000000000..9a6c8f6e83 --- /dev/null +++ b/Task/Averages-Mean-angle/OoRexx/averages-mean-angle.rexx @@ -0,0 +1,24 @@ +/*REXX program computes the mean angle (angles expressed in degrees). */ +numeric digits 50 /*use fifty digits of precision, */ + showDig=10 /*··· but only display 10 digits.*/ +xl = 350 10 ; say showit(xl, meanAngleD(xl) ) +xl = 90 180 270 360 ; say showit(xl, meanAngleD(xl) ) +xl = 10 20 30 ; say showit(xl, meanAngleD(xl) ) +exit /*stick a fork in it, we're done.*/ +/*----------------------------------MEANANGD subroutine-----------------*/ +meanAngleD: procedure; parse arg xl; numeric digits digits()+digits()%4 +sum.=0 +n=words(xl) +do j=1 to n + sum.0sin+=rxCalcSin(word(xl,j)) + sum.0cos+=rxCalcCos(word(xl,j)) + End +If sum.0cos=0 Then + Return sign(sum.0sin/n)*90 +Else + Return rxCalcArcTan((sum.0sin/n)/(sum.0cos/n)) + +showit: procedure expose showDig; numeric digits showDig; parse arg a,mA + return left('angles='a,30) 'mean angle=' format(mA,,showDig,0)/1 + +::requires rxMath library; diff --git a/Task/Averages-Mean-angle/PowerShell/averages-mean-angle-1.psh b/Task/Averages-Mean-angle/PowerShell/averages-mean-angle-1.psh new file mode 100644 index 0000000000..85708d1e36 --- /dev/null +++ b/Task/Averages-Mean-angle/PowerShell/averages-mean-angle-1.psh @@ -0,0 +1,7 @@ +function Get-MeanAngle ([double[]]$Angles) +{ + $x = ($Angles | ForEach-Object {[Math]::Cos($_ * [Math]::PI / 180)} | Measure-Object -Average).Average + $y = ($Angles | ForEach-Object {[Math]::Sin($_ * [Math]::PI / 180)} | Measure-Object -Average).Average + + [Math]::Atan2($y, $x) * 180 / [Math]::PI +} diff --git a/Task/Averages-Mean-angle/PowerShell/averages-mean-angle-2.psh b/Task/Averages-Mean-angle/PowerShell/averages-mean-angle-2.psh new file mode 100644 index 0000000000..10d8e76fc9 --- /dev/null +++ b/Task/Averages-Mean-angle/PowerShell/averages-mean-angle-2.psh @@ -0,0 +1 @@ +@(350, 10), @(90, 180, 270, 360), @(10, 20, 30) | ForEach-Object {Get-MeanAngle $_} diff --git a/Task/Averages-Mean-angle/Scheme/averages-mean-angle.ss b/Task/Averages-Mean-angle/Scheme/averages-mean-angle.ss new file mode 100644 index 0000000000..87cc164852 --- /dev/null +++ b/Task/Averages-Mean-angle/Scheme/averages-mean-angle.ss @@ -0,0 +1,23 @@ +(import (srfi 1 lists)) ;; use 'fold' from library + +(define (average l) + (/ (fold + 0 l) (length l))) + +(define pi 3.14159265358979323846264338327950288419716939937510582097) + +(define (radians a) + (* pi 1/180 a)) + +(define (degrees a) + (* 180 (/ 1 pi) a)) + +(define (mean-angle angles) + (let* ((angles (map radians angles)) + (cosines (map cos angles)) + (sines (map sin angles))) + (degrees (atan (average sines) (average cosines))))) + +(for-each (lambda (angles) + (display "The mean angle of ") (display angles) + (display " is ") (display (mean-angle angles)) (newline)) + '((350 10) (90 180 270 360) (10 20 30))) diff --git a/Task/Averages-Mean-angle/Sidef/averages-mean-angle.sidef b/Task/Averages-Mean-angle/Sidef/averages-mean-angle.sidef index e91d17e16d..e584131ef5 100644 --- a/Task/Averages-Mean-angle/Sidef/averages-mean-angle.sidef +++ b/Task/Averages-Mean-angle/Sidef/averages-mean-angle.sidef @@ -1,10 +1,10 @@ func mean_angle(angles) { - Math.atan2( + atan2( Math.avg(angles.map{ .deg2rad.sin }...), Math.avg(angles.map{ .deg2rad.cos }...), - ) -> rad2deg; + ) -> rad2deg } [[350,10], [90,180,270,360], [10,20,30]].each { |angles| - say "The mean angle of #{angles.dump} is: #{ '%.2f' % mean_angle(angles)} degrees"; + say "The mean angle of #{angles.dump} is: #{ '%.2f' % mean_angle(angles)} degrees" } diff --git a/Task/Averages-Mean-angle/Stata/averages-mean-angle.stata b/Task/Averages-Mean-angle/Stata/averages-mean-angle.stata new file mode 100644 index 0000000000..38b1682a99 --- /dev/null +++ b/Task/Averages-Mean-angle/Stata/averages-mean-angle.stata @@ -0,0 +1,14 @@ +mata +function meanangle(a) { +return(arg(sum(exp(C(0,a))))) +} + +deg=acos(-1)/180 + +meanangle((350,10)*deg)/deg + -1.61481e-15 +meanangle((90,180,270,360)*deg)/deg + 0 +meanangle((10,20,30)*deg)/deg + 20 +end diff --git a/Task/Averages-Mean-angle/Zkl/averages-mean-angle.zkl b/Task/Averages-Mean-angle/Zkl/averages-mean-angle.zkl new file mode 100644 index 0000000000..4e9c259f04 --- /dev/null +++ b/Task/Averages-Mean-angle/Zkl/averages-mean-angle.zkl @@ -0,0 +1,7 @@ +fcn meanA(a1,a2,etc){ + as:=vm.arglist.pump(List,"toFloat","toRad"); + n:=as.len(); + (as.apply("sin").sum(0.0)/n) + .atan2(as.apply("cos").sum(0.0)/n) + .toDeg() +} diff --git a/Task/Averages-Mean-time-of-day/JavaScript/averages-mean-time-of-day.js b/Task/Averages-Mean-time-of-day/JavaScript/averages-mean-time-of-day.js new file mode 100644 index 0000000000..fac143809c --- /dev/null +++ b/Task/Averages-Mean-time-of-day/JavaScript/averages-mean-time-of-day.js @@ -0,0 +1,37 @@ +var args = process.argv.slice(2); + +function time_to_seconds( hms ) { + var parts = hms.split(':'); + if ( parts[0] < 12 ) { + parts[0] = 24; + } + var seconds = parseInt(parts[0]) * 60 * 60 + parseInt(parts[1]) * 60 + parseInt(parts[2]); + return seconds; +} +function seconds_to_time( s ) { + var h = Math.floor( s/(60 * 60) ); + if ( h < 10 ) { + h = '0' + h; + } + s = s % (60 * 60); + + var m = Math.floor( s/60 ); + if ( m < 10 ) { + m = '0' + m; + } + s = s % 60 + if ( s < 10 ) { + s = '0' + s; + } + return h + ':' + m + ':' + s; +} + +var sum = 0, count = 0, idx; +for (idx in args) { + var seconds = time_to_seconds( args[idx] ); + sum += seconds; + count++; +} + +var seconds = Math.floor( sum / count ) +console.log( 'Mean time is ', seconds_to_time(seconds)); diff --git a/Task/Averages-Mean-time-of-day/jq/averages-mean-time-of-day-1.jq b/Task/Averages-Mean-time-of-day/Jq/averages-mean-time-of-day-1.jq similarity index 100% rename from Task/Averages-Mean-time-of-day/jq/averages-mean-time-of-day-1.jq rename to Task/Averages-Mean-time-of-day/Jq/averages-mean-time-of-day-1.jq diff --git a/Task/Averages-Mean-time-of-day/jq/averages-mean-time-of-day-2.jq b/Task/Averages-Mean-time-of-day/Jq/averages-mean-time-of-day-2.jq similarity index 100% rename from Task/Averages-Mean-time-of-day/jq/averages-mean-time-of-day-2.jq rename to Task/Averages-Mean-time-of-day/Jq/averages-mean-time-of-day-2.jq diff --git a/Task/Averages-Mean-time-of-day/jq/averages-mean-time-of-day-3.jq b/Task/Averages-Mean-time-of-day/Jq/averages-mean-time-of-day-3.jq similarity index 100% rename from Task/Averages-Mean-time-of-day/jq/averages-mean-time-of-day-3.jq rename to Task/Averages-Mean-time-of-day/Jq/averages-mean-time-of-day-3.jq diff --git a/Task/Averages-Mean-time-of-day/Kotlin/averages-mean-time-of-day.kotlin b/Task/Averages-Mean-time-of-day/Kotlin/averages-mean-time-of-day.kotlin new file mode 100644 index 0000000000..e7eebf7b98 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Kotlin/averages-mean-time-of-day.kotlin @@ -0,0 +1,36 @@ +// version 1.0.6 + +fun meanAngle(angles: DoubleArray): Double { + val sinSum = angles.sumByDouble { Math.sin(it * Math.PI / 180.0) } + val cosSum = angles.sumByDouble { Math.cos(it * Math.PI / 180.0) } + return Math.atan2(sinSum / angles.size, cosSum / angles.size) * 180.0 / Math.PI +} + +/* time string assumed to be in format "hh:mm:ss" */ +fun timeToSecs(t: String): Int { + val hours = t.slice(0..1).toInt() + val mins = t.slice(3..4).toInt() + val secs = t.slice(6..7).toInt() + return 3600 * hours + 60 * mins + secs +} + +/* 1 second of time = 360/(24 * 3600) = 1/240th degree */ +fun timeToDegrees(t: String): Double = timeToSecs(t) / 240.0 + +fun degreesToTime(d: Double): String { + var dd = d + if (dd < 0.0) dd += 360.0 + var secs = (dd * 240.0).toInt() + val hours = secs / 3600 + var mins = secs % 3600 + secs = mins % 60 + mins /= 60 + return String.format("%2d:%2d:%2d", hours, mins, secs) +} + +fun main(args: Array) { + val tm = arrayOf("23:00:17", "23:40:20", "00:12:45", "00:17:19") + val angles = DoubleArray(4) { timeToDegrees(tm[it]) } + val mean = meanAngle(angles) + println("Average time is : ${degreesToTime(mean)}") +} diff --git a/Task/Averages-Mean-time-of-day/Nim/averages-mean-time-of-day.nim b/Task/Averages-Mean-time-of-day/Nim/averages-mean-time-of-day.nim index 7ef8c37880..23faf610cc 100644 --- a/Task/Averages-Mean-time-of-day/Nim/averages-mean-time-of-day.nim +++ b/Task/Averages-Mean-time-of-day/Nim/averages-mean-time-of-day.nim @@ -1,18 +1,18 @@ -import math, complex, strutils +import math, complex, strutils, sequtils -proc rect(r, phi): Complex = (r * cos(phi), sin(phi)) -proc phase(c): float = arctan2(c.im, c.re) +proc rect(r, phi: float): Complex = (r * cos(phi), sin(phi)) +proc phase(c: Complex): float = arctan2(c.im, c.re) -proc radians(x): float = (x * Pi) / 180.0 -proc degrees(x): float = (x * 180.0) / Pi +proc radians(x: float): float = (x * Pi) / 180.0 +proc degrees(x: float): float = (x * 180.0) / Pi -proc meanAngle(deg): float = +proc meanAngle(deg: openArray[float]): float = var c: Complex for d in deg: c += rect(1.0, radians(d)) degrees(phase(c / float(deg.len))) -proc meanTime(times): string = +proc meanTime(times: openArray[string]): string = const day = 24 * 60 * 60 let angles = times.map(proc(time: string): float = @@ -21,6 +21,6 @@ proc meanTime(times): string = ms = (angles.meanAngle * day / 360 + day) mod day (h,m,s) = (ms.int div 3600, (ms.int mod 3600) div 60, ms.int mod 60) - align($h, 2, '0') &":"& align($m, 2, '0') &":"& align($s, 2, '0') + align($h, 2, '0') & ":" & align($m, 2, '0') & ":" & align($s, 2, '0') echo meanTime(["23:00:17", "23:40:20", "00:12:45", "00:17:19"]) diff --git a/Task/Averages-Mean-time-of-day/OoRexx/averages-mean-time-of-day.rexx b/Task/Averages-Mean-time-of-day/OoRexx/averages-mean-time-of-day.rexx new file mode 100644 index 0000000000..3b0f7eb68c --- /dev/null +++ b/Task/Averages-Mean-time-of-day/OoRexx/averages-mean-time-of-day.rexx @@ -0,0 +1,36 @@ +/* REXX --------------------------------------------------------------- +* 25.06.2014 Walter Pachl +*--------------------------------------------------------------------*/ +times='23:00:17 23:40:20 00:12:45 00:17:19' +sum=0 +day=86400 +x=0 +y=0 +Do i=1 To words(times) /* loop over times */ + time.i=word(times,i) /* pick a time */ + alpha.i=t2a(time.i) /* convert to angle (degrees) */ + /* Say time.i format(alpha.i,6,9) */ + x=x+rxcalcsin(alpha.i) /* accumulate sines */ + y=y+rxcalccos(alpha.i) /* accumulate cosines */ + End +ww=rxcalcarctan(x/y) /* compute average angle */ +ss=ww*86400/360 /* convert to seconds */ +If ss<0 Then ss=ss+day /* avoid negative value */ +m=ss%60 /* split into hh mm ss */ +s=ss-m*60 +h=m%60 +m=m-h*60 +Say f2(h)':'f2(m)':'f2(s) /* show the mean time */ +Exit + +t2a: Procedure Expose day /* convert time to angle */ + Parse Arg hh ':' mm ':' ss + sec=(hh*60+mm)*60+ss + If sec>(day/2) Then + sec=sec-day + a=360*sec/day + Return a + +f2: return right(format(arg(1),2,0),2,0) + +::requires rxmath library diff --git a/Task/Averages-Mean-time-of-day/Perl/averages-mean-time-of-day.pl b/Task/Averages-Mean-time-of-day/Perl/averages-mean-time-of-day.pl new file mode 100644 index 0000000000..5a994ab9d0 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Perl/averages-mean-time-of-day.pl @@ -0,0 +1,32 @@ +use Const::Fast; +const my $SECONDS_IN_HOUR => 60 * 60; +const my $SECONDS_IN_MINUTE => 60; + +sub hms_2_seconds { + my ( $hms ) = @_; + my ( $h, $m, $s ) = split /:/, $hms; + $h += 24 if $h < 12; + return $s + $m * $SECONDS_IN_MINUTE + $h * $SECONDS_IN_HOUR; +} +sub seconds_2_hms { + my ( $seconds ) = @_; + + my ( $h, $m ); + + $h = int( $seconds / $SECONDS_IN_HOUR ); + $seconds = $seconds % $SECONDS_IN_HOUR; + + $m = int( $seconds / $SECONDS_IN_MINUTE ); + $seconds = $seconds % $SECONDS_IN_MINUTE; + + return sprintf "%02s:%02s:%02s", $h, $m, $seconds; +} + +my @hms = split /,\s+/, scalar ; + +my ($sum, $count); +for my $time ( @hms) { + $sum += hms_2_seconds $time; + $count++; +} +say seconds_2_hms int( $sum / $count ); diff --git a/Task/Averages-Mean-time-of-day/SQL/averages-mean-time-of-day.sql b/Task/Averages-Mean-time-of-day/SQL/averages-mean-time-of-day.sql new file mode 100644 index 0000000000..14e8be95fb --- /dev/null +++ b/Task/Averages-Mean-time-of-day/SQL/averages-mean-time-of-day.sql @@ -0,0 +1,13 @@ +--Setup table for testing +CREATE TABLE time_table(times time); +INSERT INTO time_table values ('23:00:17'::time),('23:40:20'::time),('00:12:45'::time),('00:17:19'::time) + +--Compute mean time +SELECT to_timestamp((degrees(atan2(AVG(sin),AVG(cos))))* (24*60*60)/360)::time +FROM + (SELECT + cos(radians(t*360/(24*60*60))),sin(radians(t*360/(24*60*60))) + FROM + (SELECT EXTRACT(epoch from times) t + FROM time_table) T1 + )T2 diff --git a/Task/Averages-Mean-time-of-day/Scheme/averages-mean-time-of-day.ss b/Task/Averages-Mean-time-of-day/Scheme/averages-mean-time-of-day.ss new file mode 100644 index 0000000000..2ddb311da3 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Scheme/averages-mean-time-of-day.ss @@ -0,0 +1,52 @@ +(import (scheme base) + (scheme inexact) + (scheme read) + (scheme write) + (srfi 1)) ; for fold + +;; functions copied from "Averages/Mean angle" task +(define (average l) + (/ (fold + 0 l) (length l))) + +(define pi 3.14159265358979323846264338327950288419716939937510582097) + +(define (radians a) + (* pi 1/180 a)) + +(define (degrees a) + (* 180 (/ 1 pi) a)) + +(define (mean-angle angles) + (let* ((angles (map radians angles)) + (cosines (map cos angles)) + (sines (map sin angles))) + (degrees (atan (average sines) (average cosines))))) + +;; -- new functions for this task +(define (time->angle time) + (let* ((time2 ; replaces : with space in string + (string-map (lambda (c) (if (char=? c #\:) #\space c)) time)) + (string-port (open-input-string time2)) + (hour (read string-port)) + (minutes (read string-port)) + (seconds (read string-port))) + (/ (* 360 (+ (* hour 3600) (* minutes 60) seconds)) + (* 24 60 60)))) + +(define (angle->time angle) + (let* ((nom-angle (if (negative? angle) (+ 360 angle) angle)) + (time (/ (* nom-angle 24 60 60) 360)) + (hour (exact (floor (/ time 3600)))) + (minutes (exact (floor (/ (- time (* 3600 hour)) 60)))) + (seconds (exact (floor (- time (* 3600 hour) (* 60 minutes)))))) + (string-append (number->string hour) + ":" + (number->string minutes) + ":" + (number->string seconds)))) + +(define (mean-time-of-day times) + (angle->time (mean-angle (map time->angle times)))) + +(write (mean-time-of-day '("23:00:17" "23:40:20" "00:12:45" "00:17:19"))) +(newline) diff --git a/Task/Averages-Mean-time-of-day/Zkl/averages-mean-time-of-day.zkl b/Task/Averages-Mean-time-of-day/Zkl/averages-mean-time-of-day.zkl new file mode 100644 index 0000000000..e36a5b9aca --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Zkl/averages-mean-time-of-day.zkl @@ -0,0 +1,12 @@ +var D=Time.Date; +fcn meanT(t1,t2,etc){ + ts:=vm.arglist.apply(fcn(hms){ + (D.toFloat(hms.split(":").xplode())*15).toRad() + }); + n:=ts.len(); + mt:=(ts.apply("sin").sum(0.0)/n) + .atan2(ts.apply("cos").sum(0.0)/n) + .toDeg() /15; + if(mt<0) mt+=24; //-0.204622-->23.7954 + D.toHour(mt).concat(":") +} diff --git a/Task/Averages-Median/00DESCRIPTION b/Task/Averages-Median/00DESCRIPTION index 60c9239c48..7aef8979c6 100644 --- a/Task/Averages-Median/00DESCRIPTION +++ b/Task/Averages-Median/00DESCRIPTION @@ -9,7 +9,7 @@ There are several approaches to this.   One is to sort the elements, and th Sorting would take at least   O(''n'' log''n'').   Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s).   This would also take   O(''n'' log''n'').   The best solution is to use the   [[wp:Selection algorithm|selection algorithm]]   to find the median in   O(''n'')   time. {{task heading|See also}} - +[[Quickselect_algorithm]] {{Related tasks/Statistical measures}}
    diff --git a/Task/Averages-Median/AppleScript/averages-median-2.applescript b/Task/Averages-Median/AppleScript/averages-median-2.applescript index ddb5a66eb7..e2f4643a77 100644 --- a/Task/Averages-Median/AppleScript/averages-median-2.applescript +++ b/Task/Averages-Median/AppleScript/averages-median-2.applescript @@ -1,15 +1,17 @@ +-- MEDIAN --------------------------------------------------------------------- + -- median :: [Num] -> Num on median(xs) -- nth :: [Num] -> Int -> Maybe Num script nth - on lambda(xxs, n) + on |λ|(xxs, n) if length of xxs > 0 then set {x, xs} to uncons(xxs) script belowX - on lambda(y) + on |λ|(y) y < x - end lambda + end |λ| end script set {ys, zs} to partition(belowX, xs) @@ -18,24 +20,24 @@ on median(xs) x else if k > n then - lambda(ys, n) + |λ|(ys, n) else - lambda(zs, n - k - 1) + |λ|(zs, n - k - 1) end if end if else missing value end if - end lambda + end |λ| end script set n to length of xs if n > 0 then tell nth if n mod 2 = 0 then - (lambda(xs, n div 2) + lambda(xs, (n div 2) - 1)) / 2 + (|λ|(xs, n div 2) + |λ|(xs, (n div 2) - 1)) / 2 else - lambda(xs, n div 2) + |λ|(xs, n div 2) end if end tell else @@ -43,8 +45,7 @@ on median(xs) end if end median - --- TEST +-- TEST ----------------------------------------------------------------------- on run map(median, [¬ @@ -56,9 +57,31 @@ on run --> {missing value, 4, 3.5, 2.1} end run +-- GENERIC FUNCTIONS ---------------------------------------------------------- +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map --- GENERIC FUNCTIONS +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn -- partition :: predicate -> List -> (Matches, nonMatches) -- partition :: (a -> Bool) -> [a] -> ([a], [a]) @@ -67,7 +90,7 @@ on partition(f, xs) set lst to {{}, {}} repeat with x in xs set v to contents of x - set end of item ((lambda(v) as integer) + 1) of lst to v + set end of item ((|λ|(v) as integer) + 1) of lst to v end repeat end tell {item 2 of lst, item 1 of lst} @@ -81,27 +104,3 @@ on uncons(xs) missing value end if end uncons - --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map - --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn diff --git a/Task/Averages-Median/Elena/averages-median.elena b/Task/Averages-Median/Elena/averages-median.elena index 837821c0a2..7f1c9daec9 100644 --- a/Task/Averages-Median/Elena/averages-median.elena +++ b/Task/Averages-Median/Elena/averages-median.elena @@ -1,31 +1,32 @@ -#define system. -#define system'routines. -#define system'math. -#define extensions. +import system'routines. +import system'math. +import extensions. -#class(extension) op +extension op { - #method median + median [ - #var aSorted := self ascendant. + var aSorted := self ascendant. - #var aLen := aSorted length. - (aLen == 0) - ? [ ^ nil. ] - ! [ - #var aMiddleIndex := aLen / 2. - (aLen mod:2 == 0) - ? [ ^ (aSorted@(aMiddleIndex - 1) + aSorted@aMiddleIndex) / 2. ] - ! [ ^ aSorted@aMiddleIndex. ]. - ]. + var aLen := aSorted length. + if (aLen == 0) + [ ^ nil ]; + [ + var aMiddleIndex := aLen / 2. + if (aLen mod:2 == 0) + [ ^ (aSorted[aMiddleIndex - 1] + aSorted[aMiddleIndex]) / 2 ]; + [ ^ aSorted[aMiddleIndex] ] + ] ] } -#symbol program = +program = [ - #var a1 := (4.1r, 5.6r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r). - #var a2 := (4.1r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r). + var a1 := (4.1r, 5.6r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r). + var a2 := (4.1r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r). - console writeLine:"median of (":a1:") is ":(a1 median). - console writeLine:"median of (":a2:") is ":(a2 median). + console printLine("median of (",a1,") is ",a1 median). + console printLine("median of (",a2,") is ",a2 median). + + console readChar. ]. diff --git a/Task/Averages-Median/Fortran/averages-median.f b/Task/Averages-Median/Fortran/averages-median-1.f similarity index 100% rename from Task/Averages-Median/Fortran/averages-median.f rename to Task/Averages-Median/Fortran/averages-median-1.f diff --git a/Task/Averages-Median/Fortran/averages-median-2.f b/Task/Averages-Median/Fortran/averages-median-2.f new file mode 100644 index 0000000000..ee070ca3ad --- /dev/null +++ b/Task/Averages-Median/Fortran/averages-median-2.f @@ -0,0 +1,3 @@ + K = N/2 + MEDIAN = FINDELEMENT(K + 1,A,N) + IF (MOD(N,2).EQ.0) MEDIAN = (FINDELEMENT(K,A,N) + MEDIAN)/2 diff --git a/Task/Averages-Median/Haskell/averages-median-1.hs b/Task/Averages-Median/Haskell/averages-median-1.hs index 26464ab25d..b96477825c 100644 --- a/Task/Averages-Median/Haskell/averages-median-1.hs +++ b/Task/Averages-Median/Haskell/averages-median-1.hs @@ -1,11 +1,26 @@ -nth (x:xs) n - | k == n = x - | k > n = nth ys n - | otherwise = nth zs $ n - k - 1 - where (ys, zs) = partition (< x) xs - k = length ys +import Data.List (partition) -median xs | even n = (nth xs (div n 2) + nth xs (div n 2 - 1)) / 2.0 - | otherwise = nth xs (div n 2) +nth :: Ord t => [t] -> Int -> t +nth (x:xs) n + | k == n = x + | k > n = nth ys n + | otherwise = nth zs $ n - k - 1 where - n = length xs + (ys, zs) = partition (< x) xs + k = length ys + +medianMay :: (Fractional a, Ord a) => [a] -> Maybe a +medianMay xs + | n < 1 = Nothing + | even n = Just ((nth xs (div n 2) + nth xs (div n 2 - 1)) / 2.0) + | otherwise = Just (nth xs (div n 2)) + where + n = length xs + +main :: IO () +main = + mapM_ + (printMay . medianMay) + [[], [7], [5, 3, 4], [5, 4, 2, 3], [3, 4, 1, -8.4, 7.2, 4, 1, 1.2]] + where + printMay = maybe (putStrLn "(not defined)") print diff --git a/Task/Averages-Median/Java/averages-median-1.java b/Task/Averages-Median/Java/averages-median-1.java index ca3b0766f3..49f906edee 100644 --- a/Task/Averages-Median/Java/averages-median-1.java +++ b/Task/Averages-Median/Java/averages-median-1.java @@ -1,5 +1,5 @@ // Note: this function modifies the input list -public static double median(List list){ - Collections.sort(list); - return (list.get(list.size() / 2) + list.get((list.size() - 1) / 2)) / 2; +public static double median(List list) { + Collections.sort(list); + return (list.get(list.size() / 2) + list.get((list.size() - 1) / 2)) / 2; } diff --git a/Task/Averages-Median/Java/averages-median-2.java b/Task/Averages-Median/Java/averages-median-2.java index de43c4fc63..8270111996 100644 --- a/Task/Averages-Median/Java/averages-median-2.java +++ b/Task/Averages-Median/Java/averages-median-2.java @@ -1,10 +1,10 @@ -public static double median2(List list){ - PriorityQueue pq = new PriorityQueue(list); - int n = list.size(); - for (int i = 0; i < (n-1)/2; i++) - pq.poll(); // discard first half - if (n % 2 != 0) // odd length - return pq.poll(); - else - return (pq.poll() + pq.poll()) / 2.0; +public static double median2(List list) { + PriorityQueue pq = new PriorityQueue(list); + int n = list.size(); + for (int i = 0; i < (n - 1) / 2; i++) + pq.poll(); // discard first half + if (n % 2 != 0) // odd length + return pq.poll(); + else + return (pq.poll() + pq.poll()) / 2.0; } diff --git a/Task/Averages-Median/jq/averages-median-1.jq b/Task/Averages-Median/Jq/averages-median-1.jq similarity index 100% rename from Task/Averages-Median/jq/averages-median-1.jq rename to Task/Averages-Median/Jq/averages-median-1.jq diff --git a/Task/Averages-Median/jq/averages-median-2.jq b/Task/Averages-Median/Jq/averages-median-2.jq similarity index 100% rename from Task/Averages-Median/jq/averages-median-2.jq rename to Task/Averages-Median/Jq/averages-median-2.jq diff --git a/Task/Averages-Median/jq/averages-median-3.jq b/Task/Averages-Median/Jq/averages-median-3.jq similarity index 100% rename from Task/Averages-Median/jq/averages-median-3.jq rename to Task/Averages-Median/Jq/averages-median-3.jq diff --git a/Task/Averages-Median/Julia/averages-median.julia b/Task/Averages-Median/Julia/averages-median.julia index febfec9074..d6898cbd4f 100644 --- a/Task/Averages-Median/Julia/averages-median.julia +++ b/Task/Averages-Median/Julia/averages-median.julia @@ -1,10 +1,15 @@ +# Version 5.2 function median2(n) s = sort(n) len = length(n) - len%2 == 0 && return (s[ifloor(len/2)+1] + s[ifloor(len/2)])/2 - return s[ifloor(len/2)+1] + if len % 2 == 0 + return (s[floor(Int, len / 2) + 1] + s[floor(Int, len / 2)]) / 2 + else + return s[floor(Int, len / 2) + 1] + end end + a = [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2] b = [4.1, 7.2, 1.7, 9.3, 4.4, 3.2] -@assert median(a) == median2(a) -@assert median(b) == median2(b) + +@show a b median2(a) median(a) median2(b) median(b) diff --git a/Task/Averages-Median/Kotlin/averages-median.kotlin b/Task/Averages-Median/Kotlin/averages-median.kotlin index 4c195b2194..8812a644d9 100644 --- a/Task/Averages-Median/Kotlin/averages-median.kotlin +++ b/Task/Averages-Median/Kotlin/averages-median.kotlin @@ -1,5 +1,7 @@ fun median(l: List) = l.sorted().let { (it[it.size / 2] + it[(it.size - 1) / 2]) / 2 } -median(listOf(5.0, 3.0, 4.0)).let { println(it) } // 4 -median(listOf(5.0, 4.0, 2.0, 3.0)).let { println(it) } // 3.5 -median(listOf(3.0, 4.0, 1.0, -8.4, 7.2, 4.0, 1.0, 1.2)).let { println(it) } // 2.1 +fun main(args: Array) { + median(listOf(5.0, 3.0, 4.0)).let { println(it) } // 4 + median(listOf(5.0, 4.0, 2.0, 3.0)).let { println(it) } // 3.5 + median(listOf(3.0, 4.0, 1.0, -8.4, 7.2, 4.0, 1.0, 1.2)).let { println(it) } // 2.1 +} diff --git a/Task/Averages-Median/Nim/averages-median.nim b/Task/Averages-Median/Nim/averages-median.nim index a4162b6304..90863dd282 100644 --- a/Task/Averages-Median/Nim/averages-median.nim +++ b/Task/Averages-Median/Nim/averages-median.nim @@ -1,6 +1,6 @@ import algorithm, strutils -proc median(xs): float = +proc median(xs: seq[float]): float = var ys = xs sort(ys, system.cmp[float]) 0.5 * (ys[ys.high div 2] + ys[ys.len div 2]) diff --git a/Task/Averages-Median/OoRexx/averages-median.rexx b/Task/Averages-Median/OoRexx/averages-median.rexx new file mode 100644 index 0000000000..8e1d1068f6 --- /dev/null +++ b/Task/Averages-Median/OoRexx/averages-median.rexx @@ -0,0 +1,36 @@ +call testMedian .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) +call testMedian .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11) +call testMedian .array~of(10, 20, 30, 40, 50, -100, 4.7, -11e2) +call testMedian .array~new + +::routine testMedian + use arg numbers + say "numbers =" numbers~toString("l", ", ") + say "median =" median(numbers) + say + +::routine median + use arg numbers + + if numbers~isempty then return 0 + -- make a copy so the sort does not alter the + -- original set. This also means this will + -- work with lists and queues as well + numbers = numbers~makearray + + -- sort and return the middle element + numbers~sortWith(.numbercomparator~new) + size = numbers~items + -- this handles the odd value too + return numbers[size%2 + size//2] + + +-- a custom comparator that sorts strings as numeric values rather than +-- strings +::class numberComparator subclass comparator +::method compare + use strict arg left, right + -- perform the comparison on the names. By subtracting + -- the two and returning the sign, we give the expected + -- results for the compares + return (left - right)~sign diff --git a/Task/Averages-Median/Stata/averages-median-1.stata b/Task/Averages-Median/Stata/averages-median-1.stata new file mode 100644 index 0000000000..6b7049c6f1 --- /dev/null +++ b/Task/Averages-Median/Stata/averages-median-1.stata @@ -0,0 +1,4 @@ +set obs 100000 +gen x=rbeta(0.2,1.3) +quietly summarize x, detail +display r(p50) diff --git a/Task/Averages-Median/Stata/averages-median-2.stata b/Task/Averages-Median/Stata/averages-median-2.stata new file mode 100644 index 0000000000..962f616cfa --- /dev/null +++ b/Task/Averages-Median/Stata/averages-median-2.stata @@ -0,0 +1,12 @@ +program calcmedian, rclass sortpreserve +sort `1' +if mod(_N,2)==0 { + return scalar p50=(`1'[_N/2]+`1'[_N/2+1])/2 +} +else { + return scalar p50=`1'[(_N-1)/2] +} +end + +calcmedian x +display r(p50) diff --git a/Task/Averages-Median/Zkl/averages-median-1.zkl b/Task/Averages-Median/Zkl/averages-median-1.zkl new file mode 100644 index 0000000000..35d464ad0b --- /dev/null +++ b/Task/Averages-Median/Zkl/averages-median-1.zkl @@ -0,0 +1,7 @@ +var quickSelect=Import("quickSelect").qselect; + +fcn median(xs){ + n:=xs.len(); + if (n.isOdd) return(quickSelect(xs,n/2)); + ( quickSelect(xs,n/2-1) + quickSelect(xs,n/2) )/2; +} diff --git a/Task/Averages-Median/Zkl/averages-median-2.zkl b/Task/Averages-Median/Zkl/averages-median-2.zkl new file mode 100644 index 0000000000..0cfbf27f19 --- /dev/null +++ b/Task/Averages-Median/Zkl/averages-median-2.zkl @@ -0,0 +1,2 @@ +median(T( 5.1, 2.6, 6.2, 8.8, 4.6, 4.1 )); //-->4.85 +median(T( 5.1, 2.6, 8.8, 4.6, 4.1 )); //-->4.6 diff --git a/Task/Averages-Mode/Elena/averages-mode.elena b/Task/Averages-Mode/Elena/averages-mode.elena index 0b67b5178f..c79956657d 100644 --- a/Task/Averages-Mode/Elena/averages-mode.elena +++ b/Task/Averages-Mode/Elena/averages-mode.elena @@ -1,37 +1,37 @@ -#define system. -#define system'routines. -#define system'collections. -#define extensions. +import system'routines. +import system'collections. +import extensions. -#class(extension) op +extension op { - #method mode + mode [ - #var aCountMap := Dictionary new &default:0. - self run &each: anItem + var aCountMap := Dictionary new default:0. + self forEach(:anItem) [ - aCountMap@anItem := aCountMap@anItem + 1. + aCountMap[anItem] := aCountMap[anItem] + 1 ]. - aCountMap := aCountMap array_list sort:(:p:n) [ p > n ]. + aCountMap := aCountMap array_list; sort(:p:n)(p > n). - #var aMax := aCountMap firstMember. + var aMax := aCountMap firstMember. ^ aCountMap - filter &each:kv [ aMax safeEqual:kv ] - select &each:kv [ kv key ] + filterBy(:kv)(aMax equal:kv); + selectBy(:kv)(kv key); toArray. ] } -#symbol program = +program = [ - #var anArray1 := (1, 1, 2, 4, 4). - #var anArray2 := (1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17). - #var anArray3 := (1, "blue", 2, 7.5r, 5, "green", "red", 5, 2, "blue", "white"). + var anArray1 := (1, 1, 2, 4, 4). + var anArray2 := (1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17). + var anArray3 := (1, "blue", 2, 7.5r, 5, "green", "red", 5, 2, "blue", "white"). console - writeLine:"mode of (":anArray1:") is (":(anArray1 mode):")" - writeLine:"mode of (":anArray2:") is (":(anArray2 mode):")" - writeLine:"mode of (":anArray3:") is (":(anArray3 mode):")". + printLine("mode of (",anArray1,") is (",anArray1 mode,")"); + printLine("mode of (",anArray2,") is (",anArray2 mode,")"); + printLine("mode of (",anArray3,") is (",anArray3 mode,")"); + readChar. ]. diff --git a/Task/Averages-Mode/jq/averages-mode-1.jq b/Task/Averages-Mode/Jq/averages-mode-1.jq similarity index 100% rename from Task/Averages-Mode/jq/averages-mode-1.jq rename to Task/Averages-Mode/Jq/averages-mode-1.jq diff --git a/Task/Averages-Mode/jq/averages-mode-2.jq b/Task/Averages-Mode/Jq/averages-mode-2.jq similarity index 100% rename from Task/Averages-Mode/jq/averages-mode-2.jq rename to Task/Averages-Mode/Jq/averages-mode-2.jq diff --git a/Task/Averages-Mode/Kotlin/averages-mode.kotlin b/Task/Averages-Mode/Kotlin/averages-mode.kotlin new file mode 100644 index 0000000000..d81ee33e34 --- /dev/null +++ b/Task/Averages-Mode/Kotlin/averages-mode.kotlin @@ -0,0 +1,21 @@ +fun modeOf(a: Array) { + val sortedByFreq = a.groupBy { it }.entries.sortedByDescending { it.value.size } + val maxFreq = sortedByFreq.first().value.size + val modes = sortedByFreq.takeWhile { it.value.size == maxFreq } + if (modes.size == 1) + println("The mode of the collection is ${modes.first().key} which has a frequency of $maxFreq") + else { + print("There are ${modes.size} modes with a frequency of $maxFreq, namely : ") + println(modes.map { it.key }.joinToString(", ")) + } +} + +fun main(args: Array) { + val a = arrayOf(7, 1, 1, 6, 2, 4, 2, 4, 2, 1, 5) + println("[" + a.joinToString(", ") + "]") + modeOf(a) + println() + val b = arrayOf(true, false, true, false, true, true) + println("[" + b.joinToString(", ") + "]") + modeOf(b) +} diff --git a/Task/Averages-Mode/OoRexx/averages-mode.rexx b/Task/Averages-Mode/OoRexx/averages-mode.rexx new file mode 100644 index 0000000000..07798d05db --- /dev/null +++ b/Task/Averages-Mode/OoRexx/averages-mode.rexx @@ -0,0 +1,32 @@ +-- will work with just about any collection... +call testMode .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) +call testMode .list~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11) +call testMode .queue~of(30, 10, 20, 30, 40, 50, -100, 4.7, -11e2) + +::routine testMode + use arg list + say "list =" list~makearray~toString("l", ", ") + say "mode =" mode(list) + say + +::routine mode + use arg list + + -- this is a good application for a bag + -- add all of the items to the bag + collector = .bag~new + collector~putAll(list) + -- now get a list of unique items + indexes = .set~new~~putall(collector) + count = 0 -- this is used to keep track of the maximums + -- now see how many of each element we ended up with + loop index over indexes + items = collector~allat(index) + newCount = items~items + if newCount > count then do + mode = items[1] + count = newCount + end + end + + return mode diff --git a/Task/Averages-Mode/Zkl/averages-mode-1.zkl b/Task/Averages-Mode/Zkl/averages-mode-1.zkl new file mode 100644 index 0000000000..9d3e1be0ab --- /dev/null +++ b/Task/Averages-Mode/Zkl/averages-mode-1.zkl @@ -0,0 +1,5 @@ +fcn mode(items){ + d:=Dictionary(); foreach i in (items){ d.incV(i) } + m:=d.reduce(fcn(m,[(_,v)]){ v.max(m) },0); + d.filter('wrap([(_,v)]){ v==m }).apply("get",0); +} diff --git a/Task/Averages-Mode/Zkl/averages-mode-2.zkl b/Task/Averages-Mode/Zkl/averages-mode-2.zkl new file mode 100644 index 0000000000..d6d36eda0a --- /dev/null +++ b/Task/Averages-Mode/Zkl/averages-mode-2.zkl @@ -0,0 +1,4 @@ +data:=T(1, 2, 3, 1, 2, 4, 2, 5, 3, 3, 1, 3, 6); +println("Mode: ", mode(data)); +println("Mode: ", mode(data.append(2))); +println("Mode: ", mode("this is a test".split(""))); diff --git a/Task/Averages-Pythagorean-means/ALGOL-W/averages-pythagorean-means.alg b/Task/Averages-Pythagorean-means/ALGOL-W/averages-pythagorean-means.alg new file mode 100644 index 0000000000..dbce863369 --- /dev/null +++ b/Task/Averages-Pythagorean-means/ALGOL-W/averages-pythagorean-means.alg @@ -0,0 +1,36 @@ +begin + % returns the arithmetic mean of the elements of n from lo to hi % + real procedure arithmeticMean ( real array n ( * ); integer value lo, hi ) ; + begin + real sum; + sum := 0; + for i := lo until hi do sum := sum + n( i ); + sum / ( 1 + ( hi - lo ) ) + end arithmeticMean ; + % returns the geometric mean of the elements of n from lo to hi % + real procedure geometricMean ( real array n ( * ); integer value lo, hi ) ; + begin + real product; + product := 1; + for i := lo until hi do product := product * n( i ); + exp( ln( product ) / ( 1 + ( hi - lo ) ) ) + end geometricMean ; + % returns the harminic mean of the elements of n from lo to hi % + real procedure harmonicMean ( real array n ( * ); integer value lo, hi ) ; + begin + real sum; + sum := 0; + for i := lo until hi do sum := sum + ( 1 / n( i ) ); + ( 1 + ( hi - lo ) ) / sum + end harmonicMean ; + + real array v ( 1 :: 10 ); + for i := 1 until 10 do v( i ) := i; + + r_w := 10; r_d := 5; r_format := "A"; s_w := 0; % set output format % + + write( "Arithmetic mean: ", arithmeticMean( v, 1, 10 ) ); + write( "Geometric mean: ", geometricMean( v, 1, 10 ) ); + write( "Harmonic mean: ", harmonicMean( v, 1, 10 ) ) + +end. diff --git a/Task/Averages-Pythagorean-means/AppleScript/averages-pythagorean-means-1.applescript b/Task/Averages-Pythagorean-means/AppleScript/averages-pythagorean-means-1.applescript index 870071f3f7..97e7e68aef 100644 --- a/Task/Averages-Pythagorean-means/AppleScript/averages-pythagorean-means-1.applescript +++ b/Task/Averages-Pythagorean-means/AppleScript/averages-pythagorean-means-1.applescript @@ -3,63 +3,66 @@ on arithmetic_mean(xs) -- sum :: Number -> Number -> Number script sum - on lambda(accumulator, x) + on |λ|(accumulator, x) accumulator + x - end lambda + end |λ| end script foldl(sum, 0, xs) / (length of xs) end arithmetic_mean - -- geometric_mean :: [Number] -> Number on geometric_mean(xs) -- product :: Number -> Number -> Number script product - on lambda(accumulator, x) + on |λ|(accumulator, x) accumulator * x - end lambda + end |λ| end script foldl(product, 1, xs) ^ (1 / (length of xs)) end geometric_mean - -- harmonic_mean :: [Number] -> Number on harmonic_mean(xs) -- addInverse :: Number -> Number -> Number script addInverse - on lambda(accumulator, x) + on |λ|(accumulator, x) accumulator + (1 / x) - end lambda + end |λ| end script (length of xs) / (foldl(addInverse, 0, xs)) end harmonic_mean - --- TEST +-- TEST ----------------------------------------------------------------------- on run - - script test - on lambda(f) - mReturn(f)'s lambda({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) - end lambda - end script - - - set {A, G, H} to ¬ - map(test, {arithmetic_mean, geometric_mean, harmonic_mean}) + set {A, G, H} to ap({arithmetic_mean, geometric_mean, harmonic_mean}, ¬ + {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}) {values:{arithmetic:A, geometric:G, harmonic:H}, inequalities:¬ {|A >= G|:A ≥ G}, |G >= H|:G ≥ H} end run ---------------------------------------------------------------------------- --- GENERIC FUNCTIONS +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- A list of functions applied to a list of arguments +-- (<*> | ap) :: [(a -> b)] -> [a] -> [b] +on ap(fs, xs) + set {nf, nx} to {length of fs, length of xs} + set acc to {} + repeat with i from 1 to nf + tell mReturn(item i of fs) + repeat with j from 1 to nx + set end of acc to |λ|(contents of (item j of xs)) + end repeat + end tell + end repeat + return acc +end ap -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) @@ -67,7 +70,7 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -79,7 +82,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -92,7 +95,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Averages-Pythagorean-means/Erlang/averages-pythagorean-means-1.erl b/Task/Averages-Pythagorean-means/Erlang/averages-pythagorean-means-1.erl deleted file mode 100644 index 4e3dce6f9f..0000000000 --- a/Task/Averages-Pythagorean-means/Erlang/averages-pythagorean-means-1.erl +++ /dev/null @@ -1,35 +0,0 @@ -%% Author: Abhay Jain - --module(mean_calculator). --export([find_mean/0]). - -find_mean() -> -%% This is function calling. First argument is the the beginning number -%% and second argument is the initial value of sum for AM & HM and initial value of product for GM. - arithmetic_mean(1, 0), - geometric_mean(1, 1), - harmonic_mean(1, 0). - -%% Function to calculate Arithmetic Mean -arithmetic_mean(Number, Sum) when Number > 10 -> - AM = Sum / 10, - io:format("Arithmetic Mean ~p~n", [AM]); -arithmetic_mean(Number, Sum) -> - NewSum = Sum + Number, - arithmetic_mean(Number+1, NewSum). - -%% Function to calculate Geometric Mean -geometric_mean(Number, Product) when Number > 10 -> - GM = math:pow(Product, 0.1), - io:format("Geometric Mean ~p~n", [GM]); -geometric_mean(Number, Product) -> - NewProd = Product * Number, - geometric_mean(Number+1, NewProd). - -%% Function to calculate Harmonic Mean -harmonic_mean(Number, Sum) when Number > 10 -> - HM = 10 / Sum, - io:format("Harmonic Mean ~p~n", [HM]); -harmonic_mean(Number, Sum) -> - NewSum = Sum + (1/Number), - harmonic_mean(Number+1, NewSum). diff --git a/Task/Averages-Pythagorean-means/Erlang/averages-pythagorean-means-2.erl b/Task/Averages-Pythagorean-means/Erlang/averages-pythagorean-means-2.erl deleted file mode 100644 index b6eef6058c..0000000000 --- a/Task/Averages-Pythagorean-means/Erlang/averages-pythagorean-means-2.erl +++ /dev/null @@ -1,3 +0,0 @@ -Arithmetic Mean 5.5 -Geometric Mean 4.528728688116765 -Harmonic Mean 3.414171521474055 diff --git a/Task/Averages-Pythagorean-means/Haskell/averages-pythagorean-means.hs b/Task/Averages-Pythagorean-means/Haskell/averages-pythagorean-means-1.hs similarity index 100% rename from Task/Averages-Pythagorean-means/Haskell/averages-pythagorean-means.hs rename to Task/Averages-Pythagorean-means/Haskell/averages-pythagorean-means-1.hs diff --git a/Task/Averages-Pythagorean-means/Haskell/averages-pythagorean-means-2.hs b/Task/Averages-Pythagorean-means/Haskell/averages-pythagorean-means-2.hs new file mode 100644 index 0000000000..b10d256981 --- /dev/null +++ b/Task/Averages-Pythagorean-means/Haskell/averages-pythagorean-means-2.hs @@ -0,0 +1,24 @@ +import Data.List (genericLength) + +-- ARITHMETIC, GEOMETRIC AND HARMONIC MEANS ----------------------- +arithmetic, geometric, harmonic :: [Double] -> Double +arithmetic = liftM2 (/) sum genericLength + +geometric = liftM2 (**) product ((1 /) . genericLength) + +harmonic = liftM2 (/) genericLength (foldr ((+) . (1 /)) 0) + +-- GENERIC -------------------------------------------------------- +liftM2 f g h = pure f <*> g <*> h + +-- TEST ----------------------------------------------------------- +xs :: [Double] +xs = [arithmetic, geometric, harmonic] <*> [[1 .. 10]] + +main :: IO () +main = + (putStrLn . unlines) + [ zip ["Arithmetic", "Geometric", "Harmonic"] xs >>= show + , mappend "\n A >= G >= H is " $ -- + (show . and) $ zipWith (>=) xs (tail xs) + ] diff --git a/Task/Averages-Pythagorean-means/JavaScript/averages-pythagorean-means-3.js b/Task/Averages-Pythagorean-means/JavaScript/averages-pythagorean-means-3.js index dd6a78d198..eccdd32d69 100644 --- a/Task/Averages-Pythagorean-means/JavaScript/averages-pythagorean-means-3.js +++ b/Task/Averages-Pythagorean-means/JavaScript/averages-pythagorean-means-3.js @@ -2,31 +2,62 @@ // arithmeticMean :: [Number] -> Number const arithmeticMean = xs => - xs.reduce((sum, n) => sum + n, 0) / xs.length; + foldl((sum, n) => sum + n, 0, xs) / length(xs); // geometricMean :: [Number] -> Number const geometricMean = xs => - Math.pow(xs.reduce((product, x) => product * x, 1), 1 / xs.length); + raise(foldl((product, x) => product * x, 1, xs), 1 / length(xs)); // harmonicMean :: [Number] -> Number const harmonicMean = xs => - xs.length / xs.reduce((invSum, n) => invSum + (1 / n), 0); + length(xs) / foldl((invSum, n) => invSum + (1 / n), 0, xs); + // GENERIC FUNCTIONS ------------------------------------------------------ - // TEST - const values = [arithmeticMean, geometricMean, harmonicMean] - .map(f => f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])), + // A list of functions applied to a list of arguments + // <*> :: [(a -> b)] -> [a] -> [b] + const ap = (fs, xs) => // + [].concat.apply([], fs.map(f => // + [].concat.apply([], xs.map(x => [f(x)])))); - mean = { - Arithmetic: values[0], - Geometric: values[1], - Harmonic: values[2] - }; + // foldl :: (b -> a -> b) -> b -> [a] -> b + const foldl = (f, a, xs) => xs.reduce(f, a); - return JSON.stringify({ + // length :: [a] -> Int + const length = xs => xs.length; + + // mapFromList :: [(k, v)] -> Dictionary + const mapFromList = kvs => + foldl((a, [k, v]) => + (a[(typeof k === 'string' && k) || show(k)] = v, a), {}, kvs); + + // raise :: Num -> Int -> Num + const raise = (n, e) => Math.pow(n, e); + + // show :: a -> String + // show :: a -> Int -> String + const show = (...x) => + JSON.stringify.apply( + null, x.length > 1 ? [x[0], null, x[1]] : x + ); + + // zip :: [a] -> [b] -> [(a,b)] + const zip = (xs, ys) => + xs.slice(0, Math.min(xs.length, ys.length)) + .map((x, i) => [x, ys[i]]); + + // TEST ------------------------------------------------------------------- + // mean :: Dictionary + const mean = mapFromList(zip( + ['Arithmetic', 'Geometric', 'Harmonic'], + ap([arithmeticMean, geometricMean, harmonicMean], [ + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + ]) + )); + + return show({ values: mean, test: `is A >= G >= H ? ${mean.Arithmetic >= mean.Geometric && mean.Geometric >= mean.Harmonic ? "yes" : "no"}` - }, null, 2); - + }, 2); })(); diff --git a/Task/Averages-Pythagorean-means/jq/averages-pythagorean-means.jq b/Task/Averages-Pythagorean-means/Jq/averages-pythagorean-means.jq similarity index 100% rename from Task/Averages-Pythagorean-means/jq/averages-pythagorean-means.jq rename to Task/Averages-Pythagorean-means/Jq/averages-pythagorean-means.jq diff --git a/Task/Averages-Pythagorean-means/Kotlin/averages-pythagorean-means.kotlin b/Task/Averages-Pythagorean-means/Kotlin/averages-pythagorean-means.kotlin index 64d0cc7e16..5d16966632 100644 --- a/Task/Averages-Pythagorean-means/Kotlin/averages-pythagorean-means.kotlin +++ b/Task/Averages-Pythagorean-means/Kotlin/averages-pythagorean-means.kotlin @@ -1,13 +1,10 @@ fun Collection.geometricMean() = - if (isEmpty()) - Double.NaN - else Math.pow(reduce { n1, n2 -> n1 * n2 }, 1.0 / size) + if (isEmpty()) Double.NaN + else Math.pow(reduce { n1, n2 -> n1 * n2 }, 1.0 / size) fun Collection.harmonicMean() = - if (isEmpty() || contains(0.0)) - Double.NaN - else - size / reduce { n1, n2 -> n1 + 1.0 / n2 } + if (isEmpty() || contains(0.0)) Double.NaN + else size / reduce { n1, n2 -> n1 + 1.0 / n2 } fun main(args: Array) { val list = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) @@ -15,6 +12,6 @@ fun main(args: Array) { val g = list.geometricMean() val h = list.harmonicMean() println("A = %f G = %f H = %f".format(a, g, h)) - println("A >= G is %b, G >= H is %b".format( a >= g, g >= h)) - require(a >= g && g >= h) + println("A >= G is %b, G >= H is %b".format(a >= g, g >= h)) + require(g in h..a) } diff --git a/Task/Averages-Pythagorean-means/Nim/averages-pythagorean-means.nim b/Task/Averages-Pythagorean-means/Nim/averages-pythagorean-means.nim index b0f1278695..d5b18039a3 100644 --- a/Task/Averages-Pythagorean-means/Nim/averages-pythagorean-means.nim +++ b/Task/Averages-Pythagorean-means/Nim/averages-pythagorean-means.nim @@ -1,14 +1,14 @@ import math, sequtils, future -proc amean(num): float = +proc amean(num: seq[float]): float = sum(num) / float(len(num)) -proc gmean(num): float = +proc gmean(num: seq[float]): float = result = 1 for n in num: result *= n result = pow(result, 1.0 / float(num.len)) -proc hmean(num): float = +proc hmean(num: seq[float]): float = for n in num: result += 1.0 / n result = float(num.len) / result diff --git a/Task/Averages-Pythagorean-means/OCaml/averages-pythagorean-means-3.ocaml b/Task/Averages-Pythagorean-means/OCaml/averages-pythagorean-means-3.ocaml deleted file mode 100644 index 2c2707a557..0000000000 --- a/Task/Averages-Pythagorean-means/OCaml/averages-pythagorean-means-3.ocaml +++ /dev/null @@ -1,9 +0,0 @@ -let means v = - let (a, b, c) = - Array.fold_left - (fun (a, b, c) x -> (a+.x, b*.x, c+.1./.x)) - (0.,1.,0.) v - in - let n = float_of_int (Array.length v) in - (a /. n, b ** (1./.n), n /. c) -;; diff --git a/Task/Averages-Pythagorean-means/OoRexx/averages-pythagorean-means.rexx b/Task/Averages-Pythagorean-means/OoRexx/averages-pythagorean-means.rexx new file mode 100644 index 0000000000..95ef0f948e --- /dev/null +++ b/Task/Averages-Pythagorean-means/OoRexx/averages-pythagorean-means.rexx @@ -0,0 +1,41 @@ +a = .array~of(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) +say "Arithmetic =" arithmeticMean(a)", Geometric =" geometricMean(a)", Harmonic =" harmonicMean(a) + +::routine arithmeticMean + use arg numbers + -- somewhat arbitrary return for ooRexx + if numbers~isEmpty then return "NaN" + + mean = 0 + loop number over numbers + mean += number + end + return mean / numbers~items + +::routine geometricMean + use arg numbers + -- somewhat arbitrary return for ooRexx + if numbers~isEmpty then return "NaN" + + mean = 1 + loop number over numbers + mean *= number + end + + return rxcalcPower(mean, 1 / numbers~items) + +::routine harmonicMean + use arg numbers + -- somewhat arbitrary return for ooRexx + if numbers~isEmpty then return "NaN" + + mean = 0 + loop number over numbers + if number = 0 then return "Nan" + mean += 1 / number + end + + -- problem here.... + return numbers~items / mean + +::requires rxmath LIBRARY diff --git a/Task/Averages-Pythagorean-means/PostScript/averages-pythagorean-means-3.ps b/Task/Averages-Pythagorean-means/PostScript/averages-pythagorean-means-3.ps deleted file mode 100644 index 3bb75fdb94..0000000000 --- a/Task/Averages-Pythagorean-means/PostScript/averages-pythagorean-means-3.ps +++ /dev/null @@ -1,9 +0,0 @@ -/numbers {[1 10] 1 range}. -/recip {1 exch div}. - -% Arithmetic mean -numbers dup 0 {+} fold exch length div -% Geometric mean -numbers dup 1 {*} fold exch length recip exp -% Harmonic mean -numbers dup 0 {recip +} fold exch length exch div diff --git a/Task/Averages-Pythagorean-means/REXX/averages-pythagorean-means.rexx b/Task/Averages-Pythagorean-means/REXX/averages-pythagorean-means.rexx index 38f9492eb4..5efd8befae 100644 --- a/Task/Averages-Pythagorean-means/REXX/averages-pythagorean-means.rexx +++ b/Task/Averages-Pythagorean-means/REXX/averages-pythagorean-means.rexx @@ -1,55 +1,39 @@ /*REXX program computes and displays the Pythagorean means [Amean, Gmean, Hmean]. */ +numeric digits 20 /*use a little extra for the precision.*/ parse arg n . /*obtain the optional argument from CL.*/ -if n=='' then n=10 /*None specified? Then assume default.*/ -sum=0 /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ compute Arithmetic mean. ▒▒▒▒▒▒▒▒▒▒▒▒*/ - do a=1 for n; @.a=a /*populate the array and calculate sum.*/ - sum=sum + @.a /*compute the sum of all the elements. */ - end /*a*/ -Amean=sum/n /*calculate the arithmetic mean. */ -say 'Amean =' Amean /*display " " " */ -prod=1 /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ compute Geometric mean. ▒▒▒▒▒▒▒▒▒▒▒▒▒*/ - do g=1 for n - prod=prod * @.g /*compute the product of all elements. */ - end /*g*/ -Gmean=Iroot(prod,n) /*calculate the geometric mean. */ -say 'Gmean =' Gmean /*display " " " */ -rsum=0 /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ compute Harmonic mean. ▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ - do r=1 for n - rsum=rsum + 1/@.r /*compute the sum of the reciprocals. */ - end /*r*/ -Hmean=n/rsum /*calculate the harmonic mean. */ -say 'Hmean =' Hmean /*display " " " */ +if n=='' | n=="," then n=10 /*None specified? Then use the default*/ +sum=0; prod=1; rSum=0 /*initialize sum/product/reciprocal sum*/ +$=; do #=1 for n; $=$ # /*generate list by appending # to list.*/ + sum = sum + # /*compute the sum of all the elements. */ + prod= prod * # /*compute the product of all elements. */ + rSum= rSum + 1/# /*compute the sum of the reciprocals. */ + end /*#*/ +say ' list ='$ /*display the list of numbers used. */ +say 'Amean =' sum / n /*calculate & display arithmetic mean.*/ +say 'Gmean =' Iroot(prod, n) /* " " " geometric " */ +say 'Hmean =' n / rSum /* " " " harmonic " */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ Iroot: procedure; arg x 1 ox, y 1 oy /*get both args, and also a copy of X&Y*/ -if x=0 | x=1 then return x /*handle special case of zero and unity*/ -if y=0 then return 1 /* " " " " a zero root.*/ -if y=1 then return x /* " " " " a unity root.*/ -if x<0 & y//2==0 then do; say /*check for an illegal combination. */ - say '*** error *** (from Iroot):'; say - say 'root' y "can't be even if first argument is < 0."; say - return '[n/a]' /*return a "not applicable" string. */ - end /* [↑] Y<0 yields a complex number. */ -x=abs(x); y=abs(y); m=y-1 /*use the absolute value for X and Y. */ -digO=digits() /*save original accuracy (decimal digs)*/ -a=digO+5 /*use an extra five digs " " */ +if x=0 | x=1 | y=1 then return x /*handle special case of zero and unity*/ +if y=0 then return 1 /* " " " " a zero root.*/ +if x<0 & y//2==0 then return IrootErr() +x=abs(x); y=abs(y); m=y - 1 /*use the absolute value for X and Y. */ +oDigs=digits(); a=oDigs + 5 /*save original digits; add five digs.*/ g=(x+1) / y**y /*use this as the first guesstimate. */ -d=5 /*Start with 5 decimal digit accuracy. When the digits is large, */ - /*CPU time is wasted when the (1st) guess isn't close to the root.*/ +d=5 /*start with 5 dec digs, saves CPU time*/ + do until d==a /*keep going as digits are increased. */ + d=min(d+d, a); numeric digits d; f=d-2 /*limit digits to original digits + 5.*/ + og= /*use a non-guess for the old G (guess)*/ + do forever; gm=g**m /*keep computing at the Yth root. */ + _=format( (m*g*gm + x) / (y*gm), , f) /*this is the nitty─gritty calculation.*/ + if _=g | _=og then leave /*are we close enough yet? */ + og=g; g=_ /*save guess ──► OG; set the new guess.*/ + end /*forever*/ + end /*until */ - do forever /* ◄════════════════════════════╗ keep plugging as digits are increased. */ - d=min(d+d,a) /* ║ limit the digits to original digitss+5.*/ - numeric digits d /* ║ keep increasing the dec. digit accuracy*/ - old=. /* ║ define the old (value) for 1st compare.*/ - /* ║ */ - do forever /* ◄──────────────────────┐ ║ keep plugging at the Yth root. */ - _=format((m*g**y+x)/y/g**m,,d-2) /* │ ║ this is the nitty─gritty stuff. */ - if _=g | _=old then leave /* | ║ are we close enough yet? */ - old=g; g=_ /* │ ║ save guess to old); set the new guess.*/ - end /*forever ►──────────────────────┘ ║ */ - /* ║ */ - if d==a then leave /* ║ are we at desired dec. digit accuracy? */ - end /*forever ►══════════════════════════╝ */ - -_=g*sign(ox); if oy<0 then _=1/_ /*adjust for original X sign; neg. root*/ -numeric digits digO; return _/1 /*normalize to original decimal digits.*/ +if oy<0 then g=1/g /*use reciprocal when Y is negative. */ +numeric digits oDigs; return sign(ox)*g/1 /*normalize to original decimal digits.*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +IrootErr: say '***error*** (from Iroot): root' y "can't be even if 1st argument is < 0." + return '[n/a]' /*return a "not applicable" string. */ diff --git a/Task/Averages-Pythagorean-means/Stata/averages-pythagorean-means.stata b/Task/Averages-Pythagorean-means/Stata/averages-pythagorean-means.stata new file mode 100644 index 0000000000..39255d8c21 --- /dev/null +++ b/Task/Averages-Pythagorean-means/Stata/averages-pythagorean-means.stata @@ -0,0 +1,11 @@ +clear all +set obs 10 +gen x=_n +ameans x + + Variable | Type Obs Mean [95% Conf. Interval] +-------------+--------------------------------------------------------------- + x | Arithmetic 10 5.5 3.334149 7.665851 + | Geometric 10 4.528729 2.680672 7.650836 + | Harmonic 10 3.414172 2.035664 10.57602 +----------------------------------------------------------------------------- diff --git a/Task/Averages-Pythagorean-means/Zkl/averages-pythagorean-means.zkl b/Task/Averages-Pythagorean-means/Zkl/averages-pythagorean-means.zkl new file mode 100644 index 0000000000..b4b9935c69 --- /dev/null +++ b/Task/Averages-Pythagorean-means/Zkl/averages-pythagorean-means.zkl @@ -0,0 +1,4 @@ +ns:=T(1,2,3,4,5,6,7,8,9,10); +ns.sum(0.0)/ns.len(); // Arithmetic mean +ns.reduce('*,1.0).pow(1.0/ns.len()); // Geometric mean +ns.len().toFloat() / ns.reduce(fcn(p,n){ p + 1.0/n },0.0); // Harmonic mean diff --git a/Task/Averages-Root-mean-square/AppleScript/averages-root-mean-square.applescript b/Task/Averages-Root-mean-square/AppleScript/averages-root-mean-square.applescript new file mode 100644 index 0000000000..a2386131c0 --- /dev/null +++ b/Task/Averages-Root-mean-square/AppleScript/averages-root-mean-square.applescript @@ -0,0 +1,46 @@ +-- rootMeanSquare :: [Num] -> Real +on rootMeanSquare(xs) + script + on |λ|(a, x) + a + x * x + end |λ| + end script + + (foldl(result, 0, xs) / (length of xs)) ^ (1 / 2) +end rootMeanSquare + + +-- TEST ----------------------------------------------------------------------- +on run + + rootMeanSquare({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) + + -- > 6.204836822995 +end run + + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn diff --git a/Task/Averages-Root-mean-square/Astro/averages-root-mean-square.astro b/Task/Averages-Root-mean-square/Astro/averages-root-mean-square.astro new file mode 100644 index 0000000000..2e171c44c5 --- /dev/null +++ b/Task/Averages-Root-mean-square/Astro/averages-root-mean-square.astro @@ -0,0 +1 @@ +fun rootMeanSq(l): sqrt(mean(l²)) diff --git a/Task/Averages-Root-mean-square/BASIC/averages-root-mean-square-3.basic b/Task/Averages-Root-mean-square/BASIC/averages-root-mean-square-3.basic new file mode 100644 index 0000000000..d7550eaec3 --- /dev/null +++ b/Task/Averages-Root-mean-square/BASIC/averages-root-mean-square-3.basic @@ -0,0 +1,8 @@ +10 FAST +20 LET RMS=0 +30 FOR X=1 TO 10 +40 LET RMS=RMS+X**2 +50 NEXT X +60 LET RMS=SQR (RMS/10) +70 SLOW +80 PRINT RMS diff --git a/Task/Averages-Root-mean-square/Clojure/averages-root-mean-square.clj b/Task/Averages-Root-mean-square/Clojure/averages-root-mean-square.clj index f8ccf161df..c8e0d5e683 100644 --- a/Task/Averages-Root-mean-square/Clojure/averages-root-mean-square.clj +++ b/Task/Averages-Root-mean-square/Clojure/averages-root-mean-square.clj @@ -1,7 +1,5 @@ -(use '[clojure.contrib.math :only (sqrt)]) - (defn rms [xs] - (sqrt (/ (reduce + (map #(* % %) xs)) + (Math/sqrt (/ (reduce + (map #(* % %) xs)) (count xs)))) (println (rms (range 1 11))) diff --git a/Task/Averages-Root-mean-square/Futhark/averages-root-mean-square.futhark b/Task/Averages-Root-mean-square/Futhark/averages-root-mean-square.futhark index d1e296e87d..94aee5e751 100644 --- a/Task/Averages-Root-mean-square/Futhark/averages-root-mean-square.futhark +++ b/Task/Averages-Root-mean-square/Futhark/averages-root-mean-square.futhark @@ -1,2 +1,4 @@ +import "futlib/math" + fun main(as: [n]f64): f64 = - sqrt64 ((reduce (+) 0.0 (map (**2.0) as)) / f64(n)) + f64.sqrt ((reduce (+) 0.0 (map (**2.0) as)) / f64(n)) diff --git a/Task/Averages-Root-mean-square/Haskell/averages-root-mean-square.hs b/Task/Averages-Root-mean-square/Haskell/averages-root-mean-square-1.hs similarity index 100% rename from Task/Averages-Root-mean-square/Haskell/averages-root-mean-square.hs rename to Task/Averages-Root-mean-square/Haskell/averages-root-mean-square-1.hs diff --git a/Task/Averages-Root-mean-square/Haskell/averages-root-mean-square-2.hs b/Task/Averages-Root-mean-square/Haskell/averages-root-mean-square-2.hs new file mode 100644 index 0000000000..3822a2cb62 --- /dev/null +++ b/Task/Averages-Root-mean-square/Haskell/averages-root-mean-square-2.hs @@ -0,0 +1,7 @@ +import Data.List (genericLength) + +rootMeanSquare :: [Double] -> Double +rootMeanSquare = sqrt . (((/) . foldr ((+) . (^ 2)) 0) <*> genericLength) + +main :: IO () +main = print $ rootMeanSquare [1 .. 10] diff --git a/Task/Averages-Root-mean-square/Java/averages-root-mean-square.java b/Task/Averages-Root-mean-square/Java/averages-root-mean-square.java index 8bf65fce28..fac6e39460 100644 --- a/Task/Averages-Root-mean-square/Java/averages-root-mean-square.java +++ b/Task/Averages-Root-mean-square/Java/averages-root-mean-square.java @@ -1,14 +1,14 @@ -public class RMS { - public static double rms(double[] nums){ - double ms = 0; - for (int i = 0; i < nums.length; i++) - ms += nums[i] * nums[i]; - ms /= nums.length; - return Math.sqrt(ms); +public class RootMeanSquare { + + public static double rootMeanSquare(double... nums) { + double sum = 0.0; + for (double num : nums) + sum += num * num; + return Math.sqrt(sum / nums.length); } - public static void main(String[] args){ + public static void main(String[] args) { double[] nums = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}; - System.out.println("The RMS of the numbers from 1 to 10 is " + rms(nums)); + System.out.println("The RMS of the numbers from 1 to 10 is " + rootMeanSquare(nums)); } } diff --git a/Task/Averages-Root-mean-square/JavaScript/averages-root-mean-square-2.js b/Task/Averages-Root-mean-square/JavaScript/averages-root-mean-square-2.js index cc672c39de..a6cd80952d 100644 --- a/Task/Averages-Root-mean-square/JavaScript/averages-root-mean-square-2.js +++ b/Task/Averages-Root-mean-square/JavaScript/averages-root-mean-square-2.js @@ -1,18 +1,18 @@ -(lst => { +(() => { 'use strict'; // rootMeanSquare :: [Num] -> Real - let rootMeanSquare = lst => - Math.sqrt( - lst.reduce( + const rootMeanSquare = xs => + Math.sqrt( + xs.reduce( (a, x) => (a + x * x), 0 - ) / lst.length + ) / xs.length ); - return rootMeanSquare(lst); + return rootMeanSquare([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); - -})([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + // -> 6.2048368229954285 +})(); diff --git a/Task/Averages-Root-mean-square/jq/averages-root-mean-square-1.jq b/Task/Averages-Root-mean-square/Jq/averages-root-mean-square-1.jq similarity index 100% rename from Task/Averages-Root-mean-square/jq/averages-root-mean-square-1.jq rename to Task/Averages-Root-mean-square/Jq/averages-root-mean-square-1.jq diff --git a/Task/Averages-Root-mean-square/jq/averages-root-mean-square-2.jq b/Task/Averages-Root-mean-square/Jq/averages-root-mean-square-2.jq similarity index 100% rename from Task/Averages-Root-mean-square/jq/averages-root-mean-square-2.jq rename to Task/Averages-Root-mean-square/Jq/averages-root-mean-square-2.jq diff --git a/Task/Averages-Root-mean-square/Kotlin/averages-root-mean-square.kotlin b/Task/Averages-Root-mean-square/Kotlin/averages-root-mean-square.kotlin new file mode 100644 index 0000000000..7faec39916 --- /dev/null +++ b/Task/Averages-Root-mean-square/Kotlin/averages-root-mean-square.kotlin @@ -0,0 +1,11 @@ +// version 1.0.5-2 + +fun quadraticMean(vector: Array) : Double { + val sum = vector.sumByDouble { it * it } + return Math.sqrt(sum / vector.size) +} + +fun main(args: Array) { + val vector = Array(10, { (it + 1).toDouble() }) + print("Quadratic mean of numbers 1 to 10 is ${quadraticMean(vector)}") +} diff --git a/Task/Averages-Root-mean-square/Nim/averages-root-mean-square.nim b/Task/Averages-Root-mean-square/Nim/averages-root-mean-square.nim index 670470ffcb..b3087231dc 100644 --- a/Task/Averages-Root-mean-square/Nim/averages-root-mean-square.nim +++ b/Task/Averages-Root-mean-square/Nim/averages-root-mean-square.nim @@ -1,8 +1,8 @@ -import math +from math import sqrt, sum +from sequtils import mapIt -proc qmean(num): float = - for n in num: - result += n*n +proc qmean(num: seq[float]): float = + result = num.mapIt(it * it).sum result = sqrt(result / float(num.len)) -echo qmean([1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0]) +echo qmean(@[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0]) diff --git a/Task/Averages-Root-mean-square/OoRexx/averages-root-mean-square.rexx b/Task/Averages-Root-mean-square/OoRexx/averages-root-mean-square.rexx new file mode 100644 index 0000000000..2150d9be5a --- /dev/null +++ b/Task/Averages-Root-mean-square/OoRexx/averages-root-mean-square.rexx @@ -0,0 +1,22 @@ +call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) +call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11) +call testAverage .array~of(30, 10, 20, 30, 40, 50, -100, 4.7, -11e2) + +::routine testAverage + use arg list + say "list =" list~toString("l", ", ") + say "root mean square =" rootmeansquare(list) + say + +::routine rootmeansquare + use arg numbers + -- return zero for an empty list + if numbers~isempty then return 0 + + sum = 0 + do number over numbers + sum += number * number + end + return rxcalcsqrt(sum/numbers~items) + +::requires rxmath LIBRARY diff --git a/Task/Averages-Root-mean-square/Sidef/averages-root-mean-square.sidef b/Task/Averages-Root-mean-square/Sidef/averages-root-mean-square.sidef index bc1ce57f90..bfad571598 100644 --- a/Task/Averages-Root-mean-square/Sidef/averages-root-mean-square.sidef +++ b/Task/Averages-Root-mean-square/Sidef/averages-root-mean-square.sidef @@ -1,5 +1,5 @@ func rms(a) { - Math.sqrt(a.map{.**2}.sum / a.len); + sqrt(a.map{.**2}.sum / a.len) } -say rms(1..10); +say rms(1..10) diff --git a/Task/Averages-Root-mean-square/Zkl/averages-root-mean-square.zkl b/Task/Averages-Root-mean-square/Zkl/averages-root-mean-square.zkl new file mode 100644 index 0000000000..404e6634fd --- /dev/null +++ b/Task/Averages-Root-mean-square/Zkl/averages-root-mean-square.zkl @@ -0,0 +1 @@ +fcn rms(z){ ( z.reduce(fcn(p,n){ p + n*n },0.0) /z.len() ).sqrt() } diff --git a/Task/Averages-Simple-moving-average/CoffeeScript/averages-simple-moving-average-1.coffee b/Task/Averages-Simple-moving-average/CoffeeScript/averages-simple-moving-average-1.coffee deleted file mode 100644 index 14477dbd6d..0000000000 --- a/Task/Averages-Simple-moving-average/CoffeeScript/averages-simple-moving-average-1.coffee +++ /dev/null @@ -1,44 +0,0 @@ -I = (P) -> - # The cryptic name "I" follows the problem description; - # it returns a function that computes a moving average - # of successive values over the period P, using closure - # variables to maintain state. - cq = circular_queue(P) - num_elems = 0 - sum = 0 - - SMA = (n) -> - sum += n - if num_elems < P - cq.add(n) - num_elems += 1 - sum / num_elems - else - old = cq.replace(n) - sum -= old - sum / P - -circular_queue = (n) -> - # queue that only ever stores up to n values; - # Caller shouldn't call replace until n values - # have been added. - i = 0 - arr = [] - - add: (elem) -> - arr.push elem - replace: (elem) -> - # return value whose age is "n" - old_val = arr[i] - arr[i] = elem - i = (i + 1) % n - old_val - -# The output of the code below should convince you that -# calling I multiple times returns functions with independent -# state. -sma3 = I(3) -sma7 = I(7) -sma11 = I(11) -for i in [1..10] - console.log i, sma3(i), sma7(i), sma11(i) diff --git a/Task/Averages-Simple-moving-average/CoffeeScript/averages-simple-moving-average-2.coffee b/Task/Averages-Simple-moving-average/CoffeeScript/averages-simple-moving-average-2.coffee deleted file mode 100644 index 379c2bdcc9..0000000000 --- a/Task/Averages-Simple-moving-average/CoffeeScript/averages-simple-moving-average-2.coffee +++ /dev/null @@ -1,11 +0,0 @@ -> coffee moving_average.coffee -1 1 1 1 -2 1.5 1.5 1.5 -3 2 2 2 -4 3 2.5 2.5 -5 4 3 3 -6 5 3.5 3.5 -7 6 4 4 -8 7 5 4.5 -9 8 6 5 -10 9 7 5.5 diff --git a/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena b/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena index 9c5aa7267f..6d7f51d50d 100644 --- a/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena +++ b/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena @@ -1,55 +1,56 @@ -#define system. -#define system'routines. -#define system'collections. -#define extensions. +import system'routines. +import system'collections. +import extensions. -#class SMA +class SMA { - #field thePeriod. - #field theList. + object thePeriod. + object theList. - #constructor new : aPeriod + constructor new : aPeriod [ thePeriod := aPeriod. theList := List new. ] - #method append : aNumber + append : aNumber [ - theList += aNumber. + theList append:aNumber. - #var aCount := theList length. - ^ aCount => - 0 ? [ 0.0r ] + var aCount := theList length. + aCount => + 0 [ ^0.0r ]; ! [ - (aCount > thePeriod)? + if (aCount > thePeriod) [ - theList remove &index:0. + theList remove at:0. - aCount := thePeriod. + aCount := thePeriod ]. - #var aSum := theList summarize:(Real new &int:0). + var aSum := theList summarize(Real new int:0). - ^ aSum / aCount. - ]. + ^ aSum / aCount + ] ] } -#symbol program = +program = [ - #var SMA3 := SMA new:3. - #var SMA5 := SMA new:5. + var SMA3 := SMA new:3. + var SMA5 := SMA new:5. - 1 to:5 &doEach: (:i) + 1 to:5 do(:i) [ - console write:"sma3 + " :i :" = ": (SMA3 += i) &paddingRight:30 &with:#32. - console writeLine:"sma5 + " :i :" = ": (SMA5 += i). + console printPaddingRight(30, "sma3 + ", i, " = ", SMA3 append:i). + console printLine("sma5 + ", i, " = ", SMA5 append:i) ]. - 5 to:1 &doEach: (:i) + 5 to:1 do(:i) [ - console write:"sma3 + " :i :" = ": (SMA3 += i) &paddingRight:30 &with:#32. - console writeLine:"sma5 + " :i :" = ": (SMA5 += i). + console printPaddingRight(30, "sma3 + ", i, " = ", SMA3 append:i). + console printLine("sma5 + ", i, " = ", SMA5 append:i) ]. + + console readChar. ]. diff --git a/Task/Averages-Simple-moving-average/Java/averages-simple-moving-average.java b/Task/Averages-Simple-moving-average/Java/averages-simple-moving-average.java index 3a6ca14b80..0407f6cab5 100644 --- a/Task/Averages-Simple-moving-average/Java/averages-simple-moving-average.java +++ b/Task/Averages-Simple-moving-average/Java/averages-simple-moving-average.java @@ -1,5 +1,6 @@ import java.util.LinkedList; import java.util.Queue; + public class MovingAverage { private final Queue window = new LinkedList(); private final int period; @@ -19,13 +20,13 @@ public class MovingAverage { } public double getAvg() { - if (window.isEmpty()) return 0; // technically the average is undefined + if (window.isEmpty()) return 0.0; // technically the average is undefined return sum / window.size(); } public static void main(String[] args) { - double[] testData = {1,2,3,4,5,5,4,3,2,1}; - int[] windowSizes = {3,5}; + double[] testData = {1, 2, 3, 4, 5, 5, 4, 3, 2, 1}; + int[] windowSizes = {3, 5}; for (int windSize : windowSizes) { MovingAverage ma = new MovingAverage(windSize); for (double x : testData) { diff --git a/Task/Averages-Simple-moving-average/Kotlin/averages-simple-moving-average.kotlin b/Task/Averages-Simple-moving-average/Kotlin/averages-simple-moving-average.kotlin new file mode 100644 index 0000000000..dcc739d945 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Kotlin/averages-simple-moving-average.kotlin @@ -0,0 +1,19 @@ +// version 1.0.6 + +fun initMovingAverage(p: Int): (Double) -> Double { + if (p < 1) throw IllegalArgumentException("Period must be a positive integer") + val list = mutableListOf() + return { + list.add(it) + if (list.size > p) list.removeAt(0) + list.average() + } +} + +fun main(args: Array) { + val sma4 = initMovingAverage(4) + val sma5 = initMovingAverage(5) + val numbers = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 4.0, 3.0, 2.0, 1.0) + println("num\tsma4\tsma5\n") + for (number in numbers) println("${number}\t${sma4(number)}\t${sma5(number)}") +} diff --git a/Task/Averages-Simple-moving-average/Objective-C/averages-simple-moving-average-1.m b/Task/Averages-Simple-moving-average/Objective-C/averages-simple-moving-average-1.m deleted file mode 100644 index 52bcbd25f7..0000000000 --- a/Task/Averages-Simple-moving-average/Objective-C/averages-simple-moving-average-1.m +++ /dev/null @@ -1,83 +0,0 @@ -#import - -@interface MovingAverage : NSObject { - unsigned int period; - NSMutableArray *window; - double sum; -} -@end - -@implementation MovingAverage - -// init with default period -- (id)init { - self = [super init]; - if(self) { - period = 10; - window = [[NSMutableArray alloc] init]; - sum = 0.0; - } - return self; -} - -// init with specified period -- (id)initWithPeriod:(unsigned int)thePeriod { - self = [super init]; - if(self) { - period = thePeriod; - window = [[NSMutableArray alloc] init]; - sum = 0.0; - } - return self; -} - -// clear -- (void)dealloc { - [window release]; - [super dealloc]; -} - -// add a new number to the window -- (void)add:(double)val { - sum += val; - [window addObject:[NSNumber numberWithDouble:val]]; - if([window count] > period) { - NSNumber *n = [window objectAtIndex:0]; - sum -= [n doubleValue]; - [window removeObjectAtIndex:0]; - } -} - -// get the average value -- (double)avg { - if([window count] == 0) { - return 0; // technically the average is undefined - } - return sum / [window count]; -} - -// set the period, resizes current window -- (void)setPeriod:(unsigned int)thePeriod { - // make smaller? - if(thePeriod < [window count]) { - for(int i = 0; i < thePeriod; ++i) { - NSNumber *n = [window objectAtIndex:0]; - sum -= [n doubleValue]; - [window removeObjectAtIndex:0]; - } - } - period = thePeriod; -} - -// get the period (window size) -- (unsigned int)period { - return period; -} - -// clear the window and current sum -- (void)clear { - [window removeAllObjects]; - sum = 0; -} - -@end diff --git a/Task/Averages-Simple-moving-average/Objective-C/averages-simple-moving-average-2.m b/Task/Averages-Simple-moving-average/Objective-C/averages-simple-moving-average-2.m deleted file mode 100644 index de2ef66386..0000000000 --- a/Task/Averages-Simple-moving-average/Objective-C/averages-simple-moving-average-2.m +++ /dev/null @@ -1,11 +0,0 @@ -double testData[10] = {1,2,3,4,5,5,4,3,2,1}; -int periods[2] = {3,5}; -for(int i = 0; i < 2; ++i) { - MovingAverage *ma = [[MovingAverage alloc] initWithPeriod:periods[i]]; - for(int j = 0; j < 10; ++j) { - [ma add:testData[j]]; - NSLog(@"Next number = %f, SMA = %f", testData[j], [ma avg]); - } - [ma release]; - NSLog(@"\n"); -} diff --git a/Task/Averages-Simple-moving-average/OoRexx/averages-simple-moving-average.rexx b/Task/Averages-Simple-moving-average/OoRexx/averages-simple-moving-average.rexx new file mode 100644 index 0000000000..a9e412478d --- /dev/null +++ b/Task/Averages-Simple-moving-average/OoRexx/averages-simple-moving-average.rexx @@ -0,0 +1,42 @@ +testdata = .array~of(1, 2, 3, 4, 5, 5, 4, 3, 2, 1) + +-- run with different period sizes +loop period over .array~of(3, 5) + say "Period size =" period + say + movingaverage = .movingaverage~new(period) + loop number over testdata + average = movingaverage~addnumber(number) + say " Next number =" number", moving average =" average + end + say +end + +::class movingaverage +::method init + expose period queue sum + use strict arg period + sum = 0 + -- the circular queue makes this easy + queue = .circularqueue~new(period) + +-- add a number to the average set +::method addNumber + expose queue sum + use strict arg number + sum += number + -- add this to the queue + old = queue~queue(number) + -- if we pushed an element off the end of the queue, + -- subtract this from our sum + if old \= .nil then sum -= old + -- and return the current item + return sum / queue~items + +-- extra method to retrieve current average +::method average + expose queue sum + -- undefined really, but just return 0 + if queue~isempty then return 0 + -- return current queue + return sum / queue~items diff --git a/Task/Averages-Simple-moving-average/Run-BASIC/averages-simple-moving-average.run b/Task/Averages-Simple-moving-average/Run-BASIC/averages-simple-moving-average.run new file mode 100644 index 0000000000..28b1a33a7b --- /dev/null +++ b/Task/Averages-Simple-moving-average/Run-BASIC/averages-simple-moving-average.run @@ -0,0 +1,19 @@ +data 1,2,3,4,5,5,4,3,2,1 +dim sd(10) ' series data +global sd ' make it global so we all see it +for i = 1 to 10:read sd(i): next i + +x = sma(3) ' simple moving average for 3 periods +x = sma(5) ' simple moving average for 5 periods + +function sma(p) ' the simple moving average function +print "----- SMA:";p;" -----" + for i = 1 to 10 + sumSd = 0 + for j = max((i - p) + 1,1) to i + sumSd = sumSd + sd(j) ' sum series data for the period + next j + if p > i then p1 = i else p1 = p + print sd(i);" sma:";p;" ";sumSd / p1 + next i +end function diff --git a/Task/Averages-Simple-moving-average/Sidef/averages-simple-moving-average-1.sidef b/Task/Averages-Simple-moving-average/Sidef/averages-simple-moving-average-1.sidef index c0c2cee331..41d98345a6 100644 --- a/Task/Averages-Simple-moving-average/Sidef/averages-simple-moving-average-1.sidef +++ b/Task/Averages-Simple-moving-average/Sidef/averages-simple-moving-average-1.sidef @@ -13,10 +13,10 @@ func simple_moving_average(period) { } } -var ma3 = simple_moving_average(3); -var ma5 = simple_moving_average(5); +var ma3 = simple_moving_average(3) +var ma5 = simple_moving_average(5) -[1 ..^ 6, 6 ^.. 1].map{@|_} -> each {|num| - printf("Next number = %d, SMA_3 = %.3f, SMA_5 = %.1f\n", +for num (1..5, flip(1..5)) { + printf("Next number = %d, SMA_3 = %.3f, SMA_5 = %.1f\n", num, ma3.call(num), ma5.call(num)) } diff --git a/Task/Averages-Simple-moving-average/Sidef/averages-simple-moving-average-2.sidef b/Task/Averages-Simple-moving-average/Sidef/averages-simple-moving-average-2.sidef index 5d8393d679..23cbd1932c 100644 --- a/Task/Averages-Simple-moving-average/Sidef/averages-simple-moving-average-2.sidef +++ b/Task/Averages-Simple-moving-average/Sidef/averages-simple-moving-average-2.sidef @@ -13,7 +13,7 @@ class sma_generator(period, list=[], sum=0) { var ma3 = sma_generator(3) var ma5 = sma_generator(5) -for num in [@|(1..5), @|(1..5 -> flip)] { - printf("Next number = %d, SMA_3 = %.3f, SMA_5 = %.1f\n", +for num (1..5, flip(1..5)) { + printf("Next number = %d, SMA_3 = %.3f, SMA_5 = %.1f\n", num, ma3.SMA(num), ma5.SMA(num)) } diff --git a/Task/Averages-Simple-moving-average/Zkl/averages-simple-moving-average-1.zkl b/Task/Averages-Simple-moving-average/Zkl/averages-simple-moving-average-1.zkl new file mode 100644 index 0000000000..f39b91909d --- /dev/null +++ b/Task/Averages-Simple-moving-average/Zkl/averages-simple-moving-average-1.zkl @@ -0,0 +1,8 @@ +fcn SMA(P){ + fcn(n,ns,P){ + sz:=ns.append(n.toFloat()).len(); + if(P>sz) return(0.0); + if(P String -on brackets(n) +on randomBrackets(n) -- bracket :: () -> String script bracket - on lambda(_) + on |λ|(_) cond((random number) < 0.5, "[", "]") - end lambda + end |λ| end script - intercalate("", map(bracket, range(1, n))) -end brackets + intercalate("", map(bracket, enumFromTo(1, n))) +end randomBrackets on run set nPairs to 6 -- report :: Int -> String script report - property strPad : concatReplicate(nPairs * 2 + 4, space) + property strPad : concat(replicate(nPairs * 2 + 4, space)) - on lambda(n) + on |λ|(n) set w to n * 2 - set s to brackets(w) + set s to randomBrackets(w) set i to imbalance(s) set blnOK to (i = -1) @@ -62,19 +60,20 @@ on run set strLine to "'" & s & "'" & ¬ (items (w + 2) thru -1 of strPad) & strStatus - set strPointer to cond(blnOK, "", linefeed & concatReplicate(i + 1, space) & "^") + set strPointer to cond(blnOK, ¬ + "", linefeed & concat(replicate(i + 1, space)) & "^") intercalate("", {strLine, strPointer}) - end lambda + end |λ| end script linefeed & ¬ intercalate(linefeed, ¬ - map(report, range(0, nPairs))) & linefeed + map(report, enumFromTo(1, nPairs))) & linefeed end run --- GENERIC LIBRARY FUNCTIONS +-- GENERIC FUNCTIONS --------------------------------------------------------- -- map :: (a -> b) -> [a] -> [b] on map(f, xs) @@ -82,7 +81,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -94,7 +93,7 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -108,10 +107,21 @@ on intercalate(strText, lstText) return strJoined end intercalate --- concatReplicate :: Int -> String -> String -on concatReplicate(n, s) - concat(replicate(n, s)) -end concatReplicate +-- concat :: [[a]] -> [a] | [String] -> String +on concat(xs) + script append + on |λ|(a, b) + a & b + end |λ| + end script + + if length of xs > 0 and class of (item 1 of xs) is string then + set empty to "" + else + set empty to {} + end if + foldl(append, empty, xs) +end concat -- Egyptian multiplication - progressively doubling a list, appending -- stages of doubling to an accumulator where needed for binary @@ -131,21 +141,6 @@ on replicate(n, a) return out & dbl end replicate --- concat :: [[a]] -> [a] | [String] -> String -on concat(xs) - script append - on lambda(a, b) - a & b - end lambda - end script - - if length of xs > 0 and class of (item 1 of xs) is string then - foldl(append, "", xs) - else - foldl(append, {}, xs) - end if -end concat - -- Value of one of two expressions -- cond :: Bool -> a -> b -> c on cond(bln, f, g) @@ -155,15 +150,15 @@ on cond(bln, f, g) set e to g end if if class of e is handler then - mReturn(e)'s lambda() + mReturn(e)'s |λ|() else e end if end cond --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then set d to -1 else set d to 1 @@ -173,7 +168,7 @@ on range(m, n) set end of lst to i end repeat return lst -end range +end enumFromTo -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -182,7 +177,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Balanced-brackets/Elena/balanced-brackets.elena b/Task/Balanced-brackets/Elena/balanced-brackets.elena index 1e9b113859..8ad617b5d5 100644 --- a/Task/Balanced-brackets/Elena/balanced-brackets.elena +++ b/Task/Balanced-brackets/Elena/balanced-brackets.elena @@ -1,44 +1,45 @@ -#define system. -#define system'routines. -#define extensions. +import system'routines. +import extensions. -#symbol randomBrackets = +randomBrackets = { new : aLength - = (0 == aLength) - ? [ emptyLiteralValue ] - ! [ - #var aBrackets := - Array new &length:(aLength int) set &every: (&index:i) [ #91 ] + [ + if (0 == aLength) + [ ^emptyLiteralValue ]; + [ + var aBrackets := + Array new length:(aLength int); populate(:i)($91) + - Array new &length:(aLength int) set &every: (&index:i)[ #93 ]. + Array new length:(aLength int); populate(:i)($93). - aBrackets randomize:(aLength * 2). + aBrackets := aBrackets randomize:(aLength * 2). - ^ aBrackets summarize:(String new) literal. - ]. + ^ aBrackets summarize:(String new); literal + ] + ] }. -#class(extension)op +extension op { - #method isBalanced + isBalanced [ - #var aCounter := Integer new:0. + var aCounter := Integer new:0. - self seek &each:aChar [ (aCounter += (aChar => #91 ? [ 1 ] #93 ? [ -1 ])) < 0 ]. + self seekEach(:aChar)(aCounter append((aChar==$91)iif (1,-1)) < 0). - ^ (0 == aCounter). + ^ (0 == aCounter) ] } -#symbol program = +program = [ - 0 to:9 &doEach: (:aLength) + 0 to:9 do(:aLength) [ - #var anStr := randomBrackets new:aLength. + var anStr := randomBrackets new:aLength. - console writeLine:"""":anStr:"""":((anStr isBalanced) => true ? [ " is balanced" ] false ? [ " is not balanced" ]). + console printLine("""",anStr,"""",anStr isBalanced; iif(" is balanced"," is not balanced")) ]. - console readChar. + console readChar ]. diff --git a/Task/Balanced-brackets/Factor/balanced-brackets.factor b/Task/Balanced-brackets/Factor/balanced-brackets-1.factor similarity index 100% rename from Task/Balanced-brackets/Factor/balanced-brackets.factor rename to Task/Balanced-brackets/Factor/balanced-brackets-1.factor diff --git a/Task/Balanced-brackets/Factor/balanced-brackets-2.factor b/Task/Balanced-brackets/Factor/balanced-brackets-2.factor new file mode 100644 index 0000000000..5be66f2984 --- /dev/null +++ b/Task/Balanced-brackets/Factor/balanced-brackets-2.factor @@ -0,0 +1,20 @@ +USING: io formatting locals kernel math sequences unicode.case ; +IN: balanced-brackets + +: map-braces ( -- qout ) + [ + { + { "[" [ drop 1 ] } + { "]" [ drop -1 ] } + [ drop 0 ] + } case + ] +; + +: balanced? ( str -- ? ) + map-braces map sum 0 = +; + +"[1+2*[3+4*[5+6]-3]*4-[3*[3+3]]]" balanced? +-- Data stack: +t diff --git a/Task/Balanced-brackets/Gambas/balanced-brackets.gambas b/Task/Balanced-brackets/Gambas/balanced-brackets.gambas new file mode 100644 index 0000000000..ef5d4a5cd2 --- /dev/null +++ b/Task/Balanced-brackets/Gambas/balanced-brackets.gambas @@ -0,0 +1,73 @@ +'Altered to prevent lines starting with ']' or ending with '[' being generated as they can't work + +siNumberOfBrackets As Short = 20 'Maximum amount of brackets in a line +siNumberOfLines As Short = 20 'Amount of lines to test + +'---- + +Public Sub Main() +Dim sBrks As String[] = GenerateBrackets() 'Get random array to check +Dim sTemp, sHold, sWork As String 'Working variables +Dim siCount As Short 'Counter + +For Each sTemp In sBrks 'For each line in the sBrk array (e.g. '[][][][[[[]][]]]') + sWork = sTemp 'Make sWork = sTemp + Repeat 'Repeat + sHold = sWork 'Make sHold = sWork + sWork = Replace(sWork, "[]", "") 'Remove all brackets that match '[]' + Until sHold = sWork 'If sHold = sWork then there are no more '[]' matches + + If sWork = "" Then 'So if all the brackets 'Nested' correctly sWork will be empty + Print " OK "; 'Print 'OK' + Else 'Else they did not all match + Print "NOT OK "; 'So print 'NOT OK' + Endif + + For siCount = 1 To Len(sTemp) 'Loop through the line of brackets + Print Mid(sTemp, siCount, 1) & " "; 'Print each bracket + a space to make it easier to read + Next + Print 'Print a new line +Next + +End + +'---- + +Public Sub GenerateBrackets() As String[] 'Generates an array of random quantities of '[' and ']' +Dim siQty As New Short[] 'To store the random number (of brackets) to put in a line +Dim sBrk As New String[] 'To store the lines of brackets +Dim siNum, siEnd, siLoop As Short 'Various counters +Dim sTemp As String 'Temp string + +Repeat 'Repeat + siNum = Rand(0, siNumberOfBrackets) 'Pick a number between 0 and the total number of brackets requested + If Even(siNum) Then siQty.Add(siNum) 'If the number is even then add the number to siQty +Until siQty.Count = siNumberOfLines 'Keep going until we have the number of lines requested + +For Each siNum In siQty 'For each number in siQty..(e.g. 6) + Do + siEnd = Rand(0, 1) 'Generate a 0 or a 1 + If siEnd = 0 Then sTemp &= "[" 'If '0' then add a '[' bracket + If siEnd = 1 Then sTemp &= "]" 'If '1' then add a ']' bracket + + If siNum = 0 Then 'If siNum = 0 then.. + sBrk.Add("") 'Add '0' to the array + sTemp = "" 'Clear sTemp + Break 'Exit the Do Loop + Endif + + If Len(sTemp) = siNum Then 'If the length of sTemp = the required amount then.. + If sTemp Not Begins "]" And sTemp Not Ends "[" Then 'Check to see that sTemp does not start with "]" and does not end with a "[" + sBrk.Add(sTemp) 'Add it to the array + sTemp = "" 'Clear sTemp + Break 'Exit the Do Loop + Else 'Else + sTemp = "" 'Clear sTemp + End If 'Try again! + Endif + Loop +Next + +Return sBrk 'Return the sBrk array + +End diff --git a/Task/Balanced-brackets/Java/balanced-brackets.java b/Task/Balanced-brackets/Java/balanced-brackets.java index 66e53534f7..9754f34104 100644 --- a/Task/Balanced-brackets/Java/balanced-brackets.java +++ b/Task/Balanced-brackets/Java/balanced-brackets.java @@ -1,50 +1,49 @@ -public class Brackets { - public static boolean checkBrackets(String str){ - int mismatchedBrackets = 0; - for(char ch:str.toCharArray()){ - if(ch == '['){ - mismatchedBrackets++; - }else if(ch == ']'){ - mismatchedBrackets--; - }else{ - return false; //non-bracket chars +public class BalancedBrackets { + + public static boolean hasBalancedBrackets(String str) { + int brackets = 0; + for (char ch : str.toCharArray()) { + if (ch == '[') { + brackets++; + } else if (ch == ']') { + brackets--; + } else { + return false; // non-bracket chars } - if(mismatchedBrackets < 0){ //close bracket before open bracket + if (brackets < 0) { // closing bracket before opening bracket return false; } } - return mismatchedBrackets == 0; + return brackets == 0; } - public static String generate(int n){ - if(n % 2 == 1){ //if n is odd we can't match brackets - return null; - } - String ans = ""; + public static String generateBalancedBrackets(int n) { + assert n % 2 == 0; // if n is odd we can't match brackets + char[] ans = new char[n]; int openBracketsLeft = n / 2; int unclosed = 0; - while(ans.length() < n){ - if(Math.random() >= .5 && openBracketsLeft > 0 || unclosed == 0){ - ans += '['; + for (int i = 0; i < n; i++) { + if (Math.random() >= 0.5 && openBracketsLeft > 0 || unclosed == 0) { + ans[i] = '['; openBracketsLeft--; unclosed++; - }else{ - ans += ']'; + } else { + ans[i] = ']'; unclosed--; } } - return ans; + return String.valueOf(ans); } - public static void main(String[] args){ - String[] tests = {"", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"}; - for(int i = 0; i <= 16; i+=2){ - String bracks = generate(i); - System.out.println(bracks + ": " + checkBrackets(bracks)); + public static void main(String[] args) { + for (int i = 0; i <= 16; i += 2) { + String brackets = generateBalancedBrackets(i); + System.out.println(brackets + ": " + hasBalancedBrackets(brackets)); } - for(String test: tests){ - System.out.println(test + ": " + checkBrackets(test)); + String[] tests = {"", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"}; + for (String test : tests) { + System.out.println(test + ": " + hasBalancedBrackets(test)); } } } diff --git a/Task/Balanced-brackets/Kotlin/balanced-brackets.kotlin b/Task/Balanced-brackets/Kotlin/balanced-brackets.kotlin new file mode 100644 index 0000000000..87998056be --- /dev/null +++ b/Task/Balanced-brackets/Kotlin/balanced-brackets.kotlin @@ -0,0 +1,32 @@ +import java.util.Random + +fun isBalanced(s: String): Boolean { + if (s.isEmpty()) return true + var countLeft = 0 // number of left brackets so far unmatched + for (c in s) { + if (c == '[') countLeft++ + else if (countLeft > 0) countLeft-- + else return false + } + return countLeft == 0 +} + +fun main(args: Array) { + println("Checking examples in task description:") + val brackets = arrayOf("", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]") + for (b in brackets) { + print(if (b != "") b else "(empty)") + println("\t " + if (isBalanced(b)) "OK" else "NOT OK") + } + println() + + println("Checking 7 random strings of brackets of length 8:") + val r = Random() + (1..7).forEach { + var s = "" + for (j in 1..8) { + s += if (r.nextInt(2) == 0) '[' else ']' + } + println("$s " + if (isBalanced(s)) "OK" else "NOT OK") + } +} diff --git a/Task/Balanced-brackets/Nim/balanced-brackets.nim b/Task/Balanced-brackets/Nim/balanced-brackets.nim index 1d1f0c89e7..d5222bc0ed 100644 --- a/Task/Balanced-brackets/Nim/balanced-brackets.nim +++ b/Task/Balanced-brackets/Nim/balanced-brackets.nim @@ -1,16 +1,10 @@ -import random +from random import random, randomize, shuffle +from strutils import repeat + randomize() -proc shuffle(s: var string) = - for i in countdown(s.high, 0): - swap(s[i], s[random(s.len)]) - proc gen(n: int): string = - result = newString(2 * n) - for i in 0 .. 0 | unclosedBrackets == 0 then do + answer~append('[') + openBracketsNeeded -= 1 + unclosedBrackets += 1 + end + else do + answer~append(']') + unclosedBrackets -= 1 + end + end + return answer~string diff --git a/Task/Balanced-brackets/Scilab/balanced-brackets-1.scilab b/Task/Balanced-brackets/Scilab/balanced-brackets-1.scilab new file mode 100644 index 0000000000..f3670c6e4e --- /dev/null +++ b/Task/Balanced-brackets/Scilab/balanced-brackets-1.scilab @@ -0,0 +1,6 @@ +function varargout=isbb(s) + st=strsplit(s); + t=cumsum((st=='[')-(st==']')); + balanced=and(t>=0) & t(length(t))==0; + varargout=list(balanced) +endfunction diff --git a/Task/Balanced-brackets/Scilab/balanced-brackets-2.scilab b/Task/Balanced-brackets/Scilab/balanced-brackets-2.scilab new file mode 100644 index 0000000000..6cf842634b --- /dev/null +++ b/Task/Balanced-brackets/Scilab/balanced-brackets-2.scilab @@ -0,0 +1,14 @@ +for j=[5 16 22] + s=[]; + for i=1:j + p=rand(); + if p>0.5 then + s=s+"["; + else + s=s+"]"; + end + end + disp(s); + x=isbb(s); + disp(x); +end diff --git a/Task/Balanced-brackets/Sidef/balanced-brackets.sidef b/Task/Balanced-brackets/Sidef/balanced-brackets.sidef index 0b9a445d53..630ee735fc 100644 --- a/Task/Balanced-brackets/Sidef/balanced-brackets.sidef +++ b/Task/Balanced-brackets/Sidef/balanced-brackets.sidef @@ -1,14 +1,14 @@ func balanced (str) { - var depth = 0; + var depth = 0 str.each { |c| if(c=='['){ ++depth } elsif(c==']'){ --depth < 0 && return false } - }; + } - return !depth; + return !depth } -[']','[','[[]','][]','[[]]','[[]]]][][]]','x[ y [ [] z ]][ 1 ][]abcd'].each { |str| - printf("%sbalanced\t: %s\n", balanced(str) ? "" : "NOT ", str); -}; +for str [']','[','[[]','][]','[[]]','[[]]]][][]]','x[ y [ [] z ]][ 1 ][]abcd'] { + printf("%sbalanced\t: %s\n", balanced(str) ? "" : "NOT ", str) +} diff --git a/Task/Balanced-brackets/Zkl/balanced-brackets.zkl b/Task/Balanced-brackets/Zkl/balanced-brackets.zkl new file mode 100644 index 0000000000..690784ee06 --- /dev/null +++ b/Task/Balanced-brackets/Zkl/balanced-brackets.zkl @@ -0,0 +1 @@ +fcn bb(bs){ while(a:=bs.span("[","]")) {bs=bs[a[1],*]} (Void!=a) } diff --git a/Task/Balanced-ternary/Kotlin/balanced-ternary.kotlin b/Task/Balanced-ternary/Kotlin/balanced-ternary.kotlin new file mode 100644 index 0000000000..47fe065e10 --- /dev/null +++ b/Task/Balanced-ternary/Kotlin/balanced-ternary.kotlin @@ -0,0 +1,144 @@ +// version 1.1.3 + +import java.math.BigInteger + +val bigZero = BigInteger.ZERO +val bigOne = BigInteger.ONE +val bigThree = BigInteger.valueOf(3L) + +data class BTernary(private var value: String) : Comparable { + + init { + require(value.all { it in "0+-" }) + value = value.trimStart('0') + } + + constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) + + constructor(v: BigInteger) : this("") { + value = toBT(v) + } + + private fun toBT(v: BigInteger): String { + if (v < bigZero) return flip(toBT(-v)) + if (v == bigZero) return "" + val rem = mod3(v) + return when (rem) { + bigZero -> toBT(v / bigThree) + "0" + bigOne -> toBT(v / bigThree) + "+" + else -> toBT((v + bigOne) / bigThree) + "-" + } + } + + private fun flip(s: String): String { + val sb = StringBuilder() + for (c in s) { + sb.append(when (c) { + '+' -> "-" + '-' -> "+" + else -> "0" + }) + } + return sb.toString() + } + + private fun mod3(v: BigInteger): BigInteger { + if (v > bigZero) return v % bigThree + return ((v % bigThree) + bigThree) % bigThree + } + + fun toBigInteger(): BigInteger { + val len = value.length + var sum = bigZero + var pow = bigOne + for (i in 0 until len) { + val c = value[len - i - 1] + val dig = when (c) { + '+' -> bigOne + '-' -> -bigOne + else -> bigZero + } + if (dig != bigZero) sum += dig * pow + pow *= bigThree + } + return sum + } + + private fun addDigits(a: Char, b: Char, carry: Char): String { + val sum1 = addDigits(a, b) + val sum2 = addDigits(sum1.last(), carry) + return when { + sum1.length == 1 -> sum2 + sum2.length == 1 -> sum1.take(1) + sum2 + else -> sum1.take(1) + } + } + + private fun addDigits(a: Char, b: Char): String = + when { + a == '0' -> b.toString() + b == '0' -> a.toString() + a == '+' -> if (b == '+') "+-" else "0" + else -> if (b == '+') "0" else "-+" + } + + operator fun plus(other: BTernary): BTernary { + var a = this.value + var b = other.value + val longer = if (a.length > b.length) a else b + var shorter = if (a.length > b.length) b else a + while (shorter.length < longer.length) shorter = "0" + shorter + a = longer + b = shorter + var carry = '0' + var sum = "" + for (i in 0 until a.length) { + val place = a.length - i - 1 + val digisum = addDigits(a[place], b[place], carry) + carry = if (digisum.length != 1) digisum[0] else '0' + sum = digisum.takeLast(1) + sum + } + sum = carry.toString() + sum + return BTernary(sum) + } + + operator fun unaryMinus() = BTernary(flip(this.value)) + + operator fun minus(other: BTernary) = this + (-other) + + operator fun times(other: BTernary): BTernary { + var that = other + val one = BTernary(1) + val zero = BTernary(0) + var mul = zero + var flipFlag = false + if (that < zero) { + that = -that + flipFlag = true + } + var i = one + while (i <= that) { + mul += this + i += one + } + if (flipFlag) mul = -mul + return mul + } + + override operator fun compareTo(other: BTernary) = + this.toBigInteger().compareTo(other.toBigInteger()) + + override fun toString() = value +} + +fun main(args: Array) { + val a = BTernary("+-0++0+") + val b = BTernary(-436) + val c = BTernary("+-++-") + println("a = ${a.toBigInteger()}") + println("b = ${b.toBigInteger()}") + println("c = ${c.toBigInteger()}") + val bResult = a * (b - c) + val iResult = bResult.toBigInteger() + println("a * (b - c) = $bResult = $iResult") +} diff --git a/Task/Balanced-ternary/Perl-6/balanced-ternary.pl6 b/Task/Balanced-ternary/Perl-6/balanced-ternary.pl6 index cec0406c55..adaa32a5b2 100644 --- a/Task/Balanced-ternary/Perl-6/balanced-ternary.pl6 +++ b/Task/Balanced-ternary/Perl-6/balanced-ternary.pl6 @@ -34,7 +34,7 @@ sub carry (*@digits is copy) { multi prefix:<-> (BT $x) { $x.neg } multi infix:<+> (BT $x, BT $y) { - my ($b,$a) = sort +*.coeff, $x, $y; + my ($b,$a) = sort +*.coeff, ($x, $y); BT.new: coeff => carry ($a.coeff Z+ |$b.coeff, |(0 xx $a.coeff - $b.coeff)); } diff --git a/Task/Benfords-law/8th/benfords-law.8th b/Task/Benfords-law/8th/benfords-law.8th new file mode 100644 index 0000000000..d17bb3c0bb --- /dev/null +++ b/Task/Benfords-law/8th/benfords-law.8th @@ -0,0 +1,67 @@ +: n:log10e ` 1 10 ln / ` ; + +with: n + +: n:log10 \ n -- n + ln log10e * ; + +: benford \ x -- x + 1 swap / 1+ log10 ; + +: fibs \ xt n + swap >r + 0.0 1.0 rot + ( dup r@ w:exec tuck + ) swap times + 2drop rdrop ; + +var counts + +: init + a:new ( 0 a:push ) 9 times counts ! ; + +: leading \ n -- n + "%g" s:strfmt + 0 s:@ '0 - nip ; + +: bump-digit \ n -- + counts @ swap 1- dup >r a:@ + 1+ r> swap a:! drop ; + +: count-fibs \ -- + ( leading bump-digit ) 1000 fibs ; + +: adjust \ -- + counts @ ( 0.001 * ) a:map counts ! ; + +: spaces \ n -- + ' space swap times ; + +: .fw \ s n -- + >r s:len r> rot . swap - spaces ; + +: .header \ -- + "Digit" 8 .fw "Expected" 10 .fw "Actual" 10 .fw cr ; + +: .digit \ n -- + >s 8 .fw ; + +: .actual \ n -- + "%.3f" s:strfmt 10 .fw ; + +: .expected \ n -- + "%.4f" s:strfmt 10 .fw ; + +: report \ -- + .header + counts @ + ( swap 1+ dup benford swap + .digit .expected .actual cr ) + a:each drop ; + +: benford-test + init count-fibs adjust report ; + +;with + +benford-test +bye diff --git a/Task/Benfords-law/ALGOL-68/benfords-law.alg b/Task/Benfords-law/ALGOL-68/benfords-law.alg new file mode 100644 index 0000000000..89a5742fc8 --- /dev/null +++ b/Task/Benfords-law/ALGOL-68/benfords-law.alg @@ -0,0 +1,37 @@ +BEGIN + # set the number of digits for LONG LONG INT values # + PR precision 256 PR + # returns the probability of the first digit of each non-zero number in s # + PROC digit probability = ( []LONG LONG INT s )[]REAL: + BEGIN + [ 1 : 9 ]REAL result; + # count the number of times each digit is the first # + [ 1 : 9 ]INT count := ( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + FOR i FROM LWB s TO UPB s DO + LONG LONG INT v := ABS s[ i ]; + IF v /= 0 THEN + WHILE v > 9 DO v OVERAB 10 OD; + count[ SHORTEN SHORTEN v ] +:= 1 + FI + OD; + # calculate the probability of each digit # + INT number of elements = ( UPB s + 1 ) - LWB s; + FOR i TO 9 DO + result[ i ] := IF number of elements = 0 THEN 0 ELSE count[ i ] / number of elements FI + OD; + result + END # digit probability # ; + # outputs the digit probabilities of some numbers and those expected by Benford's law # + PROC compare to benford = ( []REAL actual )VOID: + FOR i TO 9 DO + print( ( "Benford: ", fixed( log( 1 + ( 1 / i ) ), -7, 3 ), " actual: ", fixed( actual[ i ], -7, 3 ), newline ) ) + OD # compare to benford # ; + # generate 1000 fibonacci numbers # + [ 0 : 1000 ]LONG LONG INT fn; + fn[ 0 ] := 0; + fn[ 1 ] := 1; + FOR i FROM 2 TO UPB fn DO fn[ i ] := fn[ i - 1 ] + fn[ i - 2 ] OD; + # get the probabilities of each first digit of the fibonacci numbers and # + # compare to the probabilities expected by Benford's law # + compare to benford( digit probability( fn ) ) +END diff --git a/Task/Benfords-law/Clojure/benfords-law.clj b/Task/Benfords-law/Clojure/benfords-law.clj new file mode 100644 index 0000000000..9df9f8ff92 --- /dev/null +++ b/Task/Benfords-law/Clojure/benfords-law.clj @@ -0,0 +1,73 @@ +(ns example + (:gen-class)) + +(defn abs [x] + (if (> x 0) + x + (- x))) + +(defn calc-benford-stats [digits] + " Frequencies of digits in data " + (let [y (frequencies digits) + tot (reduce + (vals y))] + [y tot])) + +(defn show-benford-stats [v] + " Prints in percent the actual, Benford expected, and difference" + (let [fd (map (comp first str) v)] ; first digit of each record + (doseq [q (range 1 10) + :let [[y tot] (calc-benford-stats fd) + d (first (str q)) ; reference digit + f (/ (get y d 0) tot 0.01) ; percent of occurence of digit + p (* (Math/log10 (/ (inc q) q)) 100) ; Benford expected percent + e (abs (- f p))]] ; error (difference) + (println (format "%3d %10.2f %10.2f %10.2f" + q + f + p + e))))) + +; Generate fibonacci results +(def fib (lazy-cat [0N 1N] (map + fib (rest fib)))) + +;(def fib-digits (map (comp first str) (take 10000 fib))) +(def fib-digits (take 10000 fib)) +(def header " found-% expected-% diff") + +(println "Fibonacci Results") +(println header) +(show-benford-stats fib-digits) +; +; Universal Constants from Physics (using first column of data) +(println "Universal Constants from Physics") +(println header) +(let [ + data-parser (fn [s] + (let [x (re-find #"\s{10}-?[0|/\.]*([1-9])" s)] + (if (not (nil? x)) ; Skips records without number + (second x) + x))) + + input (slurp "http://physics.nist.gov/cuu/Constants/Table/allascii.txt") + + y (for [line (line-seq (java.io.BufferedReader. + (java.io.StringReader. input)))] + (data-parser line)) + z (filter identity y)] + (show-benford-stats z)) + +; Sunspots +(println "Sunspots average count per month since 1749") +(println header) +(let [ + data-parser (fn [s] + (nth (re-find #"(.+?\s){3}([1-9])" s) 2)) + + ; Sunspot data loaded from file (saved from ;https://solarscience.msfc.nasa.gov/greenwch/SN_m_tot_V2.0.txt") + ; (note: attempting to load directly from url causes https Trust issues, so saved to file after loading to Browser) + input (slurp "SN_m_tot_V2.0.txt") + y (for [line (line-seq (java.io.BufferedReader. + (java.io.StringReader. input)))] + (data-parser line))] + + (show-benford-stats y)) diff --git a/Task/Benfords-law/Java/benfords-law.java b/Task/Benfords-law/Java/benfords-law.java index 904711c63c..9f7745f8e6 100644 --- a/Task/Benfords-law/Java/benfords-law.java +++ b/Task/Benfords-law/Java/benfords-law.java @@ -1,41 +1,29 @@ import java.math.BigInteger; +import java.util.Locale; -public class Benford { - private static interface NumberGenerator { - BigInteger[] getNumbers(); +public class BenfordsLaw { + + private static BigInteger[] generateFibonacci(int n) { + BigInteger[] fib = new BigInteger[n]; + fib[0] = BigInteger.ONE; + fib[1] = BigInteger.ONE; + for (int i = 2; i < fib.length; i++) { + fib[i] = fib[i - 2].add(fib[i - 1]); + } + return fib; } - private static class FibonacciGenerator implements NumberGenerator { - public BigInteger[] getNumbers() { - final BigInteger[] fib = new BigInteger[ 1000 ]; - fib[ 0 ] = fib[ 1 ] = BigInteger.ONE; - for ( int i = 2; i < fib.length; i++ ) - fib[ i ] = fib[ i - 2 ].add( fib[ i - 1 ] ); - return fib; + public static void main(String[] args) { + BigInteger[] numbers = generateFibonacci(1000); + + int[] firstDigits = new int[10]; + for (BigInteger number : numbers) { + firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++; + } + + for (int i = 1; i < firstDigits.length; i++) { + System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n", + i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i)); } } - - private final int[] firstDigits = new int[ 9 ]; - private final int count; - - private Benford( final NumberGenerator ng ) { - final BigInteger[] numbers = ng.getNumbers(); - count = numbers.length; - for ( final BigInteger number : numbers ) - firstDigits[ Integer.valueOf( number.toString().substring( 0, 1 ) ) - 1 ]++; - } - - public String toString() { - final StringBuilder result = new StringBuilder(); - for ( int i = 0; i < firstDigits.length; i++ ) - result.append( i + 1 ) - .append( '\t' ).append( firstDigits[ i ] / ( double )count ) - .append( '\t' ).append( Math.log10( 1 + 1d / ( i + 1 ) ) ) - .append( '\n' ); - return result.toString(); - } - - public static void main( final String[] args ) { - System.out.println( new Benford( new FibonacciGenerator() ) ); - } } diff --git a/Task/Benfords-law/jq/benfords-law.jq b/Task/Benfords-law/Jq/benfords-law.jq similarity index 100% rename from Task/Benfords-law/jq/benfords-law.jq rename to Task/Benfords-law/Jq/benfords-law.jq diff --git a/Task/Benfords-law/Kotlin/benfords-law.kotlin b/Task/Benfords-law/Kotlin/benfords-law.kotlin index 672999972e..a551ff221d 100644 --- a/Task/Benfords-law/Kotlin/benfords-law.kotlin +++ b/Task/Benfords-law/Kotlin/benfords-law.kotlin @@ -12,8 +12,9 @@ class Benford(ng: NumberGenerator) { private val str: String init { - for (n in ng.numbers) + for (n in ng.numbers) { firstDigits[n.toString().substring(0, 1).toInt() - 1]++ + } str = with(StringBuilder()) { for (i in firstDigits.indices) { @@ -29,7 +30,7 @@ class Benford(ng: NumberGenerator) { object FibonacciGenerator : NumberGenerator { override val numbers: Array by lazy { val fib = Array(1000, { BigInteger.ONE }) - for (i in 2..fib.size - 1) + for (i in 2 until fib.size) fib[i] = fib[i - 2].add(fib[i - 1]) fib } diff --git a/Task/Benfords-law/PureBasic/benfords-law.purebasic b/Task/Benfords-law/PureBasic/benfords-law.purebasic new file mode 100644 index 0000000000..324f50eaee --- /dev/null +++ b/Task/Benfords-law/PureBasic/benfords-law.purebasic @@ -0,0 +1,40 @@ +#MAX_N=1000 +NewMap d1.i() +Dim fi.s(#MAX_N) +fi(0)="0" : fi(1)="1" +Declare.s Sigma(sx.s,sy.s) + +For I=2 To #MAX_N + fi(I)=Sigma(fi(I-2),fi(I-1)) +Next + +For I=1 To #MAX_N + d1(Left(fi(I),1))+1 +Next + +Procedure.s Sigma(sx.s, sy.s) + Define i.i, v1.i, v2.i, r.i + Define s.s, sa.s + sy=ReverseString(sy) : s=ReverseString(sx) + For i=1 To Len(s)*Bool(Len(s)>Len(sy))+Len(sy)*Bool(Len(sy)>=Len(s)) + v1=Val(Mid(s,i,1)) + v2=Val(Mid(sy,i,1)) + r+v1+v2 + sa+Str(r%10) + r/10 + Next i + If r : sa+Str(r%10) : EndIf + ProcedureReturn ReverseString(sa) +EndProcedure + +OpenConsole("Benford's law: Fibonacci sequence 1.."+Str(#MAX_N)) + +Print(~"Dig.\t\tCnt."+~"\t\tExp.\t\tDif.\n\n") +ForEach d1() + Print(RSet(MapKey(d1()),4," ")+~"\t:\t"+RSet(Str(d1()),3," ")+~"\t\t") + ex=Int(#MAX_N*Log(1+1/Val(MapKey(d1())))/Log(10)) + PrintN(RSet(Str(ex),3," ")+~"\t\t"+RSet(StrF((ex-d1())*100/ex,5),8," ")+" %") +Next + +PrintN(~"\nPress Enter...") +Input() diff --git a/Task/Benfords-law/REXX/benfords-law.rexx b/Task/Benfords-law/REXX/benfords-law.rexx index 0599cf225f..165487bc19 100644 --- a/Task/Benfords-law/REXX/benfords-law.rexx +++ b/Task/Benfords-law/REXX/benfords-law.rexx @@ -2,33 +2,31 @@ numeric digits 50 /*use only 50 dec digits for LN & LOG.*/ parse arg N .; if N=='' | N=="," then N=1000 /*allow sample size to be specified. */ @benny= "Benford's law applied to" /*a handy-dandy literal for some SAYs. */ -w1= max( length('observed'), length(N-2) ); pad=" " /*used for aligning output.*/ -w2= max( length('expected'), length(N ) ) /* " " " " */ +w1= max(2+length('observed'), length(N-2) ); pad=" " /*used for aligning output.*/ +w2= max(2+length('expected'), length(N ) ) /* " " " " */ @.=1; do j=3 to N; jm1=j-1; jm2=j-2; @.j=@.jm2 + @.jm1; end /*j*/ call show @benny N 'Fibonacci numbers' -p=1; @.1=2 - do j=3 by 2 until p==N; if \isPrime(j) then iterate; p=p+1; @.p=j; end /*j*/ +p=1 +@.1=2; do j=3 by 2 until p==N; if \isPrime(j) then iterate; p=p+1; @.p=j; end /*j*/ call show @benny N 'prime numbers' - do j=1 for N; @.j=!(j); end /*j*/ +!=1; do j=1 for N; !=!*j; end /*j*/ call show @benny N 'factorial products' exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ -!: procedure; parse arg x; !=1; do j=2 to x; !=!*j; end /*j*/; return ! -e: return 2.7182818284590452353602874713526624977572470936999595749669676277240766303535 -isPrime: procedure; parse arg x; if wordpos(x,'2 3 5 7')\==0 then return 1; if x//2==0 then return 0; if x//3==0 then return 0; do j=5 by 6 until j*j>x; if x//j==0 then return 0; if x//(j+2)==0 then return 0; end; return 1 -ln10: return 2.30258509299404568401799145468436420760110148862877297603332790096757260967735248023599720508959829834196778404228624863340952546508280675666628736909878168948290720832555468084379989482623319852839350530896538 -ln: procedure; parse arg x,f; if x==10 then do; _=ln10(); y=format(_); if y\==_ then return y; end; call e; ig=(x>1.5); is=1 - 2*(ig\==1); ii=0; s=x; return .ln_comp() -.ln_comp: do while ig&s>1.5|\ig&s<.5;_=e();do k=-1;iz=s*_**-is;if k>=0&(ig&iz<1|\ig&iz>.5) then leave;_=_*_;izz=iz;end;s=izz;ii=ii+is*2**k;end;x=x*e()**-ii-1;z=0;_=-1;p=z;do k=1;_=-_*x;z=z+_/k;if z=p then leave;p=z;end;return z+ii -log: return ln( arg(1) ) / ln(10) +/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ +e: return 2.7182818284590452353602874713526624977572470936999595749669676277240766303535 +isPrime: procedure; parse arg x; if wordpos(x,'2 3 5 7')\==0 then return 1; if x//2==0 then return 0; if x//3==0 then return 0; do j=5 by 6 until j*j>x; if x//j==0 then return 0; if x//(j+2)==0 then return 0; end; return 1 +ln: procedure; parse arg x; _=e(); ig=(x>1.5); is=1 - 2 * (ig \== 1); ii=0; s=x; return .ln() +.ln: do while ig&s>1.5|\ig&s<.5;do k=-1;iz=s*_**-is;if k>=0&(ig&iz<1|\ig&iz>.5) then leave;_=_*_;izz=iz;end;s=izz;ii=ii+is*2**k;end;x=x*e()**-ii-1;z=0;_=-1;p=z;do k=1;_=-_*x;z=z+_/k;if z=p then leave;p=z;end;return z+ii +log: return ln( arg(1) ) / ln(10) /*──────────────────────────────────────────────────────────────────────────────────────*/ -show: say; say pad 'digit' pad center("observed",w1) pad center('expected',w2) - say pad '─────' pad center("",w1,'─') pad center("",w2,'─') pad arg(1) - !.=0; do j=1 for N; _=left(@.j,1); !._=!._+1; end /*get 1st digits.*/ +show: say; say pad ' digit ' pad center("observed",w1) pad center('expected',w2) + say pad '───────' pad center("",w1,'─') pad center("",w2,'─') pad arg(1) + !.=0; do j=1 for N; _=left(@.j,1); !._=!._+1; end /*get 1st digits.*/ - do k=1 for 9 /*show results for decimal digits*/ - say pad center(k,5) pad center(format(!.k /N , , length(N-2) ), w1), - pad center(format(log(1+1 /k) , , length(N)+2 ), w2) - end /*k*/ - return + do k=1 for 9 /*display results for decimal digits. */ + say pad center(k,7) pad center(format(!.k /N , , length(N-2) ), w1), + pad center(format(log(1+1 /k) , , length(N)+2 ), w2) + end /*k*/ + return diff --git a/Task/Benfords-law/Sidef/benfords-law.sidef b/Task/Benfords-law/Sidef/benfords-law.sidef index b88af815c0..ac2689ebf6 100644 --- a/Task/Benfords-law/Sidef/benfords-law.sidef +++ b/Task/Benfords-law/Sidef/benfords-law.sidef @@ -1,21 +1,16 @@ -var fibonacci = [0, 1] ; -{ - fibonacci.append(fibonacci[-1] + $fibonacci[-2]); -} * (1000 - fibonacci.len); +var (actuals, expected) = ([], []) +var fibonacci = 1000.of {|i| fib(i).digit(0) } -var (actuals, expected) = ([], []); +for i (1..9) { + var num = fibonacci.count_by {|j| j == i } + actuals.append(num / 1000) + expected.append(1 + (1/i) -> log10) +} -{ |i| - var num = 0; - fibonacci.each { |j| j.digit(-1) == i && (num++)}; - actuals.append(num / 1000); - expected.append(1 + (1/i) -> log10); -} * 9; - -"%17s%17s\n".printf("Observed","Expected"); -{ |i| +"%17s%17s\n".printf("Observed","Expected") +for i (1..9) { "%d : %11s %%%15s %%\n".printf( i, "%.2f".sprintf(100 * actuals[i - 1]), "%.2f".sprintf(100 * expected[i - 1]), - ); -} * 9; + ) +} diff --git a/Task/Benfords-law/Stata/benfords-law-1.stata b/Task/Benfords-law/Stata/benfords-law-1.stata new file mode 100644 index 0000000000..49fa3785a9 --- /dev/null +++ b/Task/Benfords-law/Stata/benfords-law-1.stata @@ -0,0 +1,25 @@ +clear +set obs 1000 +scalar phi=(1+sqrt(5))/2 +gen fib=(phi^_n-(-1/phi)^_n)/sqrt(5) +gen k=real(substr(string(fib),1,1)) +hist k, discrete // show a histogram +qui tabulate k, matcell(f) // compute frequencies + +mata +f=st_matrix("f") +p=log10(1:+1:/(1::9))*sum(f) +// print observed vs predicted probabilities +f,p + 1 2 + +-----------------------------+ + 1 | 297 301.0299957 | + 2 | 178 176.0912591 | + 3 | 127 124.9387366 | + 4 | 96 96.91001301 | + 5 | 80 79.18124605 | + 6 | 67 66.94678963 | + 7 | 57 57.99194698 | + 8 | 53 51.15252245 | + 9 | 45 45.75749056 | + +-----------------------------+ diff --git a/Task/Benfords-law/Stata/benfords-law-2.stata b/Task/Benfords-law/Stata/benfords-law-2.stata new file mode 100644 index 0000000000..83435b3e31 --- /dev/null +++ b/Task/Benfords-law/Stata/benfords-law-2.stata @@ -0,0 +1,8 @@ +// chi-square statistic +chisq=sum((f-p):^2:/p) +chisq + .2219340262 +// p-value +chi2tail(8,chisq) + .9999942179 +end diff --git a/Task/Benfords-law/Stata/benfords-law-3.stata b/Task/Benfords-law/Stata/benfords-law-3.stata new file mode 100644 index 0000000000..309f47506e --- /dev/null +++ b/Task/Benfords-law/Stata/benfords-law-3.stata @@ -0,0 +1,32 @@ +clear +set obs 500 +scalar s=2+sqrt(2) +gen a=s^_n +gen k=real(substr(string(a),1,1)) +hist k, discrete +qui tabulate k, matcell(f) + +mata +f=st_matrix("f") +p=log10(1:+1:/(1::9))*sum(f) +f,p + 1 2 + +-----------------------------+ + 1 | 134 150.5149978 | + 2 | 99 88.04562953 | + 3 | 68 62.4693683 | + 4 | 34 48.4550065 | + 5 | 33 39.59062302 | + 6 | 33 33.47339482 | + 7 | 33 28.99597349 | + 8 | 33 25.57626122 | + 9 | 33 22.87874528 | + +-----------------------------+ + +chisq=sum((f-p):^2:/p) +chisq + 16.26588528 + +chi2tail(8,chisq) + .0387287805 +end diff --git a/Task/Benfords-law/Swift/benfords-law.swift b/Task/Benfords-law/Swift/benfords-law.swift new file mode 100644 index 0000000000..a6b2af4cb2 --- /dev/null +++ b/Task/Benfords-law/Swift/benfords-law.swift @@ -0,0 +1,103 @@ +import Foundation + +/* Reads from a file and returns the content as a String */ +func readFromFile(fileName file:String) -> String{ + + var ret:String = "" + + let path = Foundation.URL(string: "file://"+file) + + do { + ret = try String(contentsOf: path!, encoding: String.Encoding.utf8) + } + catch { + print("Could not read from file!") + exit(-1) + } + + return ret +} + +/* Calculates the probability following Benford's law */ +func benford(digit z:Int) -> Double { + + if z<=0 || z>9 { + perror("Argument must be between 1 and 9.") + return 0 + } + + return log10(Double(1)+Double(1)/Double(z)) +} + +// get CLI input +if CommandLine.arguments.count < 2 { + print("Usage: Benford [FILE]") + exit(-1) +} + +let pathToFile = CommandLine.arguments[1] + +// Read from given file and parse into lines +let content = readFromFile(fileName: pathToFile) +let lines = content.components(separatedBy: "\n") + +var digitCount:UInt64 = 0 +var countDigit:[UInt64] = [0,0,0,0,0,0,0,0,0] + +// check digits line by line +for line in lines { + if line == "" { + continue + } + let charLine = Array(line.characters) + switch(charLine[0]){ + case "1": + countDigit[0] += 1 + digitCount += 1 + break + case "2": + countDigit[1] += 1 + digitCount += 1 + break + case "3": + countDigit[2] += 1 + digitCount += 1 + break + case "4": + countDigit[3] += 1 + digitCount += 1 + break + case "5": + countDigit[4] += 1 + digitCount += 1 + break + case "6": + countDigit[5] += 1 + digitCount += 1 + break + case "7": + countDigit[6] += 1 + digitCount += 1 + break + case "8": + countDigit[7] += 1 + digitCount += 1 + break + case "9": + countDigit[8] += 1 + digitCount += 1 + break + default: + break + } + +} + +// print result +print("Digit\tBenford [%]\tObserved [%]\tDeviation") +print("~~~~~\t~~~~~~~~~~~~\t~~~~~~~~~~~~\t~~~~~~~~~") +for i in 0..<9 { + let temp:Double = Double(countDigit[i])/Double(digitCount) + let ben = benford(digit: i+1) + print(String(format: "%d\t%.2f\t\t%.2f\t\t%.4f", i+1,ben*100,temp*100,ben-temp)) +} diff --git a/Task/Benfords-law/Zkl/benfords-law-1.zkl b/Task/Benfords-law/Zkl/benfords-law-1.zkl new file mode 100644 index 0000000000..3f0febd2f7 --- /dev/null +++ b/Task/Benfords-law/Zkl/benfords-law-1.zkl @@ -0,0 +1,15 @@ +show( // use list (fib(1)...fib(1000)) --> (1..4.34666e+208) + (0).pump(1000,List,fcn(ab){ab.append(ab.sum(0.0)).pop(0)}.fp(L(1,1))), + "First 1000 Fibonacci numbers"); + +fcn show(data,title){ + f:=(0).pump(9,List,Ref.fp(0)); // (Ref(0),Ref(0)... + foreach v in (data){ // eg 1.49707e+207 ("g" format) --> "1" (first digit) + f[v.toString()[0].toInt()-1].inc(); } + println(title); + println("Digit Observed Predicted"); + foreach i,n in ([1..].zip(f)){ // -->(1,Ref)...(9,Ref) + println(" %d %9.3f %8.3f".fmt(i,n.value.toFloat()/data.len(), + (1.0+1.0/i).log10())) + } +} diff --git a/Task/Benfords-law/Zkl/benfords-law-2.zkl b/Task/Benfords-law/Zkl/benfords-law-2.zkl new file mode 100644 index 0000000000..78bb1e517e --- /dev/null +++ b/Task/Benfords-law/Zkl/benfords-law-2.zkl @@ -0,0 +1,21 @@ +var BN=Import("zklBigNum"); + +fcn fibgen(a,b) { return(a,self.fcn.fp(b,a+b)) } //-->L(fib,fcn) + +benford := [0..9].pump(List,Ref.fp(0)).copy(); //L(Ref(0),...) + +const N=1000; + +[1..N].reduce('wrap(fiber,_){ + n,f:=fiber; + benford[n.toString()[0]].inc(); // first digit of fib + f() // next (fib,fcn) pair +},fibgen(BN(1),BN(1))); + + // de-ref Refs ie convert to int to float, divide by N +actual := benford.apply(T("value","toFloat",'/(N))); +expected := [1..9].apply(fcn(x){(1.0 + 1.0/x).log10()}); + +println("Leading digital distribution of the first 1,000 Fibonacci numbers"); +println("Digit\tActual\tExpected"); +foreach i in ([1..9]){ println("%d\t%.3f\t%.3f".fmt(i,actual[i], expected[i-1])); } diff --git a/Task/Bernoulli-numbers/00DESCRIPTION b/Task/Bernoulli-numbers/00DESCRIPTION index 04cc15473b..d5f8286fb3 100644 --- a/Task/Bernoulli-numbers/00DESCRIPTION +++ b/Task/Bernoulli-numbers/00DESCRIPTION @@ -11,7 +11,7 @@ The  nth  Bernoulli number is expressed as  '''B'''1 , all ''odd'' Bernoulli numbers have a value of zero.) :*   express the Bernoulli numbers as fractions  (most are improper fractions). :*   the fractions should be reduced. -:*   index each number in some way so that it can be discerned which number is being displayed. +:*   index each number in some way so that it can be discerned which Bernoulli number is being displayed. :*   align the solidi   (/)   if used (extra credit). diff --git a/Task/Bernoulli-numbers/ALGOL-68/bernoulli-numbers.alg b/Task/Bernoulli-numbers/ALGOL-68/bernoulli-numbers.alg new file mode 100644 index 0000000000..5e4716b6c0 --- /dev/null +++ b/Task/Bernoulli-numbers/ALGOL-68/bernoulli-numbers.alg @@ -0,0 +1,69 @@ +BEGIN + # Show the non-zero Bernoulli numbers B0 to B60 # + # as rational numbers # + # Uses code from the Arithmetic/Rational task modified to use # + # LONG LONG INT to allow for the large number of digits requried # + + PR precision 100 PR # sets the precision of LONG LONG INT # + + # Code from the Arithmetic/Rational task # + # ============================================================== # + MODE FRAC = STRUCT( LONG LONG INT num #erator#, den #ominator#); + PROC gcd = (LONG LONG INT a, b) LONG LONG INT: # greatest common divisor # + (a = 0 | b |: b = 0 | a |: ABS a > ABS b | gcd(b, a MOD b) | gcd(a, b MOD a)); + PROC lcm = (LONG LONG INT a, b)LONG LONG INT: # least common multiple # + a OVER gcd(a, b) * b; + PRIO // = 9; # higher then the ** operator # + OP // = (LONG LONG INT num, den)FRAC: ( # initialise and normalise # + LONG LONG INT common = gcd(num, den); + IF den < 0 THEN + ( -num OVER common, -den OVER common) + ELSE + ( num OVER common, den OVER common) + FI + ); + OP + = (FRAC a, b)FRAC: ( + LONG LONG INT common = lcm(den OF a, den OF b); + FRAC result := ( common OVER den OF a * num OF a + common OVER den OF b * num OF b, common ); + num OF result//den OF result + ); + OP - = (FRAC a, b)FRAC: a + -b, + * = (FRAC a, b)FRAC: ( + 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 frac)FRAC: (-num OF frac, den OF frac); + # ============================================================== # + # end code from the Arithmetic/Rational task # + + # Additional FRACrelated operators # + OP * = ( INT a, FRAC b )FRAC: ( num OF b * a ) // den OF b; + OP // = ( INT a, INT b )FRAC: LONG LONG INT( a ) // LONG LONG INT( b ); + + # returns the nth Bernoulli number, n must be >= 0 # + # Uses the algorithm suggested by the task, so B(1) is +1/2 # + PROC bernoulli = ( INT n )FRAC: + IF n < 0 + THEN # n is out of range # 0 // 1 + ELSE # n is valid # + [ 0 : n ]FRAC a; + FOR i FROM LWB a TO UPB a DO a[ i ] := 0 // 1 OD; + FOR m FROM 0 TO n DO + a[ m ] := 1 // ( m + 1 ); + FOR j FROM m BY -1 TO 1 DO + a[ j - 1 ] := j * ( a[ j - 1 ] - a[ j ] ) + OD + OD; + a[ 0 ] + FI # bernoulli # ; + + FOR n FROM 0 TO 60 DO + 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 ) ) + FI + OD +END diff --git a/Task/Bernoulli-numbers/Factor/bernoulli-numbers-1.factor b/Task/Bernoulli-numbers/Factor/bernoulli-numbers-1.factor new file mode 100644 index 0000000000..ae3fab7b5e --- /dev/null +++ b/Task/Bernoulli-numbers/Factor/bernoulli-numbers-1.factor @@ -0,0 +1,42 @@ +IN: scratchpad + [ + 0 1 1 "%2d : %d / %d\n" printf + 1 -1 2 "%2d : %d / %d\n" printf + 30 iota [ + 1 + 2 * dup bernoulli [ numerator ] [ denominator ] bi + "%2d : %d / %d\n" printf + ] each + ] time + 0 : 1 / 1 + 1 : -1 / 2 + 2 : 1 / 6 + 4 : -1 / 30 + 6 : 1 / 42 + 8 : -1 / 30 +10 : 5 / 66 +12 : -691 / 2730 +14 : 7 / 6 +16 : -3617 / 510 +18 : 43867 / 798 +20 : -174611 / 330 +22 : 854513 / 138 +24 : -236364091 / 2730 +26 : 8553103 / 6 +28 : -23749461029 / 870 +30 : 8615841276005 / 14322 +32 : -7709321041217 / 510 +34 : 2577687858367 / 6 +36 : -26315271553053477373 / 1919190 +38 : 2929993913841559 / 6 +40 : -261082718496449122051 / 13530 +42 : 1520097643918070802691 / 1806 +44 : -27833269579301024235023 / 690 +46 : 596451111593912163277961 / 282 +48 : -5609403368997817686249127547 / 46410 +50 : 495057205241079648212477525 / 66 +52 : -801165718135489957347924991853 / 1590 +54 : 29149963634884862421418123812691 / 798 +56 : -2479392929313226753685415739663229 / 870 +58 : 84483613348880041862046775994036021 / 354 +60 : -1215233140483755572040304994079820246041491 / 56786730 +Running time: 0.00489444 seconds diff --git a/Task/Bernoulli-numbers/Factor/bernoulli-numbers-2.factor b/Task/Bernoulli-numbers/Factor/bernoulli-numbers-2.factor new file mode 100644 index 0000000000..1ecfadc0d5 --- /dev/null +++ b/Task/Bernoulli-numbers/Factor/bernoulli-numbers-2.factor @@ -0,0 +1,35 @@ +:: bernoulli-numbers ( n -- ) + n 1 + 0 :> tab + 1 1 tab set-nth + 2 n [a,b] [| k | + k 1 - dup + tab nth * + k tab set-nth + ] each + 2 n [a,b] [| k | + k n [a,b] [| j | + j tab nth + j k - 2 + * + j 1 - tab nth + j k - * + + j tab set-nth + ] each + ] each + 1 :> s! + 1 n [a,b] [| k | + k 2 * dup + 2^ dup 1 - * + k tab nth + swap / * + s * k tab set-nth + s -1 * s! + ] each + + 0 1 1 "%2d : %d / %d\n" printf + 1 -1 2 "%2d : %d / %d\n" printf + 1 n [a,b] [| k | + k 2 * k tab nth + [ numerator ] [ denominator ] bi + "%2d : %d / %d\n" printf + ] each +; diff --git a/Task/Bernoulli-numbers/Factor/bernoulli-numbers-3.factor b/Task/Bernoulli-numbers/Factor/bernoulli-numbers-3.factor new file mode 100644 index 0000000000..fd4b64c99f --- /dev/null +++ b/Task/Bernoulli-numbers/Factor/bernoulli-numbers-3.factor @@ -0,0 +1,3 @@ +[ 30 bernoulli-numbers ] time +... +Running time: 0.004331652 seconds diff --git a/Task/Bernoulli-numbers/Haskell/bernoulli-numbers-1.hs b/Task/Bernoulli-numbers/Haskell/bernoulli-numbers-1.hs new file mode 100644 index 0000000000..d7e74ef0c8 --- /dev/null +++ b/Task/Bernoulli-numbers/Haskell/bernoulli-numbers-1.hs @@ -0,0 +1,23 @@ +import Data.Ratio +import System.Environment + +main = getArgs >>= printM . defaultArg + where + defaultArg as = + if null as + then 60 + else read (head as) + +printM m = + mapM_ (putStrLn . printP) . + takeWhile ((<= m) . fst) . filter (\(_, b) -> b /= 0 % 1) . zip [0 ..] $ + bernoullis + +printP (i, r) = + "B(" ++ show i ++ ") = " ++ show (numerator r) ++ "/" ++ show (denominator r) + +bernoullis = map head . iterate (ulli 1) . map berno $ enumFrom 0 + where + berno i = 1 % (i + 1) + ulli _ [_] = [] + ulli i (x:y:xs) = (i % 1) * (x - y) : ulli (i + 1) (y : xs) diff --git a/Task/Bernoulli-numbers/Haskell/bernoulli-numbers-2.hs b/Task/Bernoulli-numbers/Haskell/bernoulli-numbers-2.hs new file mode 100644 index 0000000000..1c4d5c3285 --- /dev/null +++ b/Task/Bernoulli-numbers/Haskell/bernoulli-numbers-2.hs @@ -0,0 +1,17 @@ +import Data.Ratio (numerator, denominator, (%)) + +bernouillis :: Integer -> [Rational] +bernouillis = + let faulhaber rs n = (:) =<< (-) 1 . sum $ zipWith ((*) . (n %)) [2 ..] rs + in fmap head . tail . scanl faulhaber [] . enumFromTo 0 + +bernouilliTable :: Integer -> String +bernouilliTable = + let row i x = + [ concat ["B(", show i, ") = ", show n, "/", show (denominator x)] + | let n = numerator x + , n /= 0 ] + in unlines . concat . zipWith row [0 ..] . bernouillis + +main :: IO () +main = putStrLn (bernouilliTable 60) diff --git a/Task/Bernoulli-numbers/Haskell/bernoulli-numbers.hs b/Task/Bernoulli-numbers/Haskell/bernoulli-numbers.hs deleted file mode 100644 index a5f7b2ae56..0000000000 --- a/Task/Bernoulli-numbers/Haskell/bernoulli-numbers.hs +++ /dev/null @@ -1,17 +0,0 @@ -module Main where - -import Data.Ratio -import System.Environment - -main = getArgs >>= printM . defaultArg where - defaultArg as = if null as then 60 else read (head as) - -printM m = mapM_ (putStrLn . printP) . takeWhile ((<= m).fst) - . filter (\(_,b) -> b /= 0%1) . zip [0..] $ bernoullis - -printP (i,r) = "B(" ++ show i ++ ")=" ++ show (numerator r) ++ "/" ++ show (denominator r) - -bernoullis = map head . iterate (ulli 1) . map berno $ enumFrom 0 where - berno i = 1 % (i+1) - ulli _ [_] = [] - ulli i (x:y:xs) = (i%1)*(x-y) : ulli (i+1) (y:xs) diff --git a/Task/Bernoulli-numbers/jq/bernoulli-numbers-1.jq b/Task/Bernoulli-numbers/Jq/bernoulli-numbers-1.jq similarity index 100% rename from Task/Bernoulli-numbers/jq/bernoulli-numbers-1.jq rename to Task/Bernoulli-numbers/Jq/bernoulli-numbers-1.jq diff --git a/Task/Bernoulli-numbers/jq/bernoulli-numbers-2.jq b/Task/Bernoulli-numbers/Jq/bernoulli-numbers-2.jq similarity index 100% rename from Task/Bernoulli-numbers/jq/bernoulli-numbers-2.jq rename to Task/Bernoulli-numbers/Jq/bernoulli-numbers-2.jq diff --git a/Task/Bernoulli-numbers/jq/bernoulli-numbers-3.jq b/Task/Bernoulli-numbers/Jq/bernoulli-numbers-3.jq similarity index 100% rename from Task/Bernoulli-numbers/jq/bernoulli-numbers-3.jq rename to Task/Bernoulli-numbers/Jq/bernoulli-numbers-3.jq diff --git a/Task/Bernoulli-numbers/jq/bernoulli-numbers-4.jq b/Task/Bernoulli-numbers/Jq/bernoulli-numbers-4.jq similarity index 100% rename from Task/Bernoulli-numbers/jq/bernoulli-numbers-4.jq rename to Task/Bernoulli-numbers/Jq/bernoulli-numbers-4.jq diff --git a/Task/Bernoulli-numbers/jq/bernoulli-numbers-5.jq b/Task/Bernoulli-numbers/Jq/bernoulli-numbers-5.jq similarity index 100% rename from Task/Bernoulli-numbers/jq/bernoulli-numbers-5.jq rename to Task/Bernoulli-numbers/Jq/bernoulli-numbers-5.jq diff --git a/Task/Bernoulli-numbers/Kotlin/bernoulli-numbers-2.kotlin b/Task/Bernoulli-numbers/Kotlin/bernoulli-numbers-2.kotlin deleted file mode 100644 index 46d0e7c171..0000000000 --- a/Task/Bernoulli-numbers/Kotlin/bernoulli-numbers-2.kotlin +++ /dev/null @@ -1 +0,0 @@ -System.out.printf("B(%-2d) = %-1s%n", n, Bernoulli(n)) diff --git a/Task/Bernoulli-numbers/Kotlin/bernoulli-numbers-1.kotlin b/Task/Bernoulli-numbers/Kotlin/bernoulli-numbers.kotlin similarity index 100% rename from Task/Bernoulli-numbers/Kotlin/bernoulli-numbers-1.kotlin rename to Task/Bernoulli-numbers/Kotlin/bernoulli-numbers.kotlin diff --git a/Task/Bernoulli-numbers/Pascal/bernoulli-numbers.pascal b/Task/Bernoulli-numbers/Pascal/bernoulli-numbers.pascal new file mode 100644 index 0000000000..16d01cd05f --- /dev/null +++ b/Task/Bernoulli-numbers/Pascal/bernoulli-numbers.pascal @@ -0,0 +1,115 @@ +(* Taken from the 'Ada 99' project, https://marquisdegeek.com/code_ada99 *) + +program BernoulliForAda99; + + +type + Fraction = object + private + numerator, denominator: Int64; + + public + procedure assign(n, d: Int64); + procedure subtract(rhs: Fraction); + procedure multiply(value: Int64); + procedure reduce(); + procedure writeOutput(); +end; + + +function gcd(a, b: Int64):Int64; +begin + if (b = 0) then + gcd := a + else + gcd := gcd(b, a mod b) +end; + + +procedure Fraction.writeOutput(); +begin + write(numerator); + if (numerator <> 0) then + begin + write('/'); + write(denominator); + end; +end; + + +procedure Fraction.assign(n, d: Int64); +begin + numerator := n; + denominator := d; +end; + + +procedure Fraction.subtract(rhs: Fraction); +begin + numerator := numerator * rhs.denominator; + numerator := numerator - (rhs.numerator * denominator); + denominator := denominator * rhs.denominator; +end; + + +procedure Fraction.multiply(value: Int64); +begin + numerator := numerator * value; +end; + + +procedure Fraction.reduce(); +var gcdResult: Int64; +begin + gcdResult := gcd(numerator, denominator); + + begin + numerator := numerator div gcdResult; (* div is Int64 division *) + denominator := denominator div gcdResult; (* could also use round(d/r) *) + end; +end; + + +function calculateBernoulli(n: Int64) : Fraction; +var + m, j: Int64; + results: array of Fraction; + + begin + setlength(results, n); + + for m:= 0 to n do + begin + results[m].assign(1, m+1); + + for j:= m downto 1 do + begin + results[j-1].subtract(results[j]); + results[j-1].multiply(j); + results[j-1].reduce(); + end; + end; + + calculateBernoulli := results[0]; +end; + + +(* Main program starts here *) + +var + b: Int64; + result: Fraction; + +begin + writeln('Calculating Bernoulli numbers...'); + + for b:= 1 to 25 do + begin + write(b); + write(' : '); + result := calculateBernoulli(b); + result.writeOutput(); + writeln; + end; + +end. diff --git a/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-3.pl6 b/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-3.pl6 index 55223d6e18..eb2c94c4cf 100644 --- a/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-3.pl6 +++ b/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-3.pl6 @@ -1,7 +1,16 @@ -my sub infix:(\prev,\this) { this.key => this.key * (this.value - prev.value) } +sub infix:(\prev, \this) { + this.key => this.key * (this.value - prev.value) +} -constant bernoulli = grep *.value, map { (.key => .value.[*-1]) }, do - 0 => [FatRat.new(1,1)], - -> (:key($pm),:value(@pa)) { - $pm + 1 => [ map *.value, [\bop] ($pm + 2 ... 1) Z=> FatRat.new(1, $pm + 2), @pa ]; - } ... *; +sub next-bernoulli ( (:key($pm), :value(@pa)) ) { + $pm + 1 => [ + map *.value, + [\bop] ($pm + 2 ... 1) Z=> FatRat.new(1, $pm + 2), |@pa + ] +} + +constant bernoulli = + grep *.value, + map { .key => .value[*-1] }, + (0 => [FatRat.new(1,1)], &next-bernoulli ... *) +; diff --git a/Task/Bernoulli-numbers/R/bernoulli-numbers.r b/Task/Bernoulli-numbers/R/bernoulli-numbers.r new file mode 100644 index 0000000000..210b361f64 --- /dev/null +++ b/Task/Bernoulli-numbers/R/bernoulli-numbers.r @@ -0,0 +1,3 @@ +# Bernoulli numbers. 12/8/16 aev +require(pracma) +bernoulli(60) diff --git a/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx b/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx index 0c37af6742..bae83df81a 100644 --- a/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx +++ b/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx @@ -1,6 +1,6 @@ /*REXX program calculates N number of Bernoulli numbers expressed as fractions. */ parse arg N .; if N=='' then N=60 /*Not specified? Then use the default.*/ -!.=0; w=max(length(N),4); Nw=N+N%5 /*used for aligning (output) fractions.*/ +!.=0; w=max(length(N), 4); Nw=N + w + N % 4 /*used for aligning (output) fractions.*/ say 'B(n)' center("Bernoulli number expressed as a fraction", max(78-w, Nw)) /*title*/ 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. */ @@ -10,43 +10,39 @@ say copies('─',w) copies("─",max(78-w,Nw+2*w)) /*display 2nd line of title end /*#*/ /* [↑] align the Bernoulli fractions. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -bern: parse arg x /*obtain the subroutine argument. */ - if x==0 then return '1/1' /*handle the special case of zero. */ - if x==1 then return '-1/2' /* " " " " " one. */ - if x//2 then return 0 /* " " " " " odds. */ - /* [↓] process all numbers up to X, */ - do j=2 to x by 2; jp=j+1; d=j+j /* ··· and set some shortcut vars.*/ +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. */ + do j=2 to x by 2; jp=j+1; d=j+j /*process the positive integers up to X*/ if d>digits() then numeric digits d /*increase the decimal digits if needed*/ - sn=1-j /*set the numerator. */ - sd=2 /* " " denominator. */ + 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; ad=$lcm /* " " next " */ + an=comb(jp, k) * bn /*use COMBination for the next term. */ + $lcm=lcm(sd, ad) /*use Least Common Denominator function*/ + sn=$lcm % sd * sn; sd=$lcm /*calculate the current numerator. */ + an=$lcm % ad * an; ad=$lcm /* " " next " */ sn=sn+an /* " " current " */ end /*k*/ /* [↑] calculate the SN/SD sequence.*/ sn=-sn /*adjust the sign for the numerator. */ sd=sd*jp /*calculate the denominator. */ if sn\==1 then do; _=gcd(sn, sd) /*get the Greatest Common Denominator.*/ - sn=sn%_; sd=sd%_ /*reduce the numerator and denominator.*/ + 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.*/ - + @.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\==0 then return !.!c.x.y /*combination computed before?*/ - if x-y 0 ? bern_diff(n - 1, 0, 1) : 1; + n > 0 ? bern_diff(n - 1, 0, 1) : 1 } -range(0, 60).each { |i| - var num = bernoulli_number(i) || next; - printf("B(%2d) = %44s / %s\n", i, num.parts); +for i (0..60) { + var num = bernoulli_number(i) || next + printf("B(%2d) = %44s / %s\n", i, num.nude) } diff --git a/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-2.sidef b/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-2.sidef index c7eb730784..6f9cf93bfe 100644 --- a/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-2.sidef +++ b/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-2.sidef @@ -1,13 +1,13 @@ func bernoulli_print { var a = [] - range(0, 60).each { |m| - a << (m+1 -> inv) - m.downto(1).each { |j| + for m (0..60) { + a.append(1/(m+1)) + for j (flip(1..m)) { (a[j-1] -= a[j]) *= j } a[0] || next - printf("B(%2d) = %44s / %s\n", m, a[0].parts) + printf("B(%2d) = %44s / %s\n", m, a[0].nude) } } - +  bernoulli_print() diff --git a/Task/Bernoulli-numbers/Visual-Basic-.NET/bernoulli-numbers.visual b/Task/Bernoulli-numbers/Visual-Basic-.NET/bernoulli-numbers.visual new file mode 100644 index 0000000000..c98a15b19a --- /dev/null +++ b/Task/Bernoulli-numbers/Visual-Basic-.NET/bernoulli-numbers.visual @@ -0,0 +1,50 @@ +' Bernoulli numbers - vb.net - 06/03/2017 +Imports System.Numerics 'BinInteger + +Module Bernoulli_numbers + + Function gcd_BigInt(ByVal x As BigInteger, ByVal y As BigInteger) As BigInteger + Dim y2 As BigInteger + x = BigInteger.Abs(x) + Do + y2 = BigInteger.Remainder(x, y) + x = y + y = y2 + Loop Until y = 0 + Return x + End Function 'gcd_BigInt + + Sub bernoul_BigInt(n As Integer, ByRef bnum As BigInteger, ByRef bden As BigInteger) + Dim j, m As Integer + Dim f As BigInteger + Dim anum(), aden() As BigInteger + ReDim anum(n + 1), aden(n + 1) + For m = 0 To n + anum(m + 1) = 1 + aden(m + 1) = m + 1 + For j = m To 1 Step -1 + anum(j) = j * (aden(j + 1) * anum(j) - aden(j) * anum(j + 1)) + aden(j) = aden(j) * aden(j + 1) + f = gcd_BigInt(BigInteger.Abs(anum(j)), BigInteger.Abs(aden(j))) + If f <> 1 Then + anum(j) = anum(j) / f + aden(j) = aden(j) / f + End If + Next + Next + bnum = anum(1) : bden = aden(1) + End Sub 'bernoul_BigInt + + Sub bernoulli_BigInt() + Dim i As Integer + Dim bnum, bden As BigInteger + bnum = 0 : bden = 0 + For i = 0 To 60 + bernoul_BigInt(i, bnum, bden) + If bnum <> 0 Then + Console.WriteLine("B(" & i & ")=" & bnum.ToString("D") & "/" & bden.ToString("D")) + End If + Next i + End Sub 'bernoulli_BigInt + +End Module 'Bernoulli_numbers diff --git a/Task/Bernoulli-numbers/Zkl/bernoulli-numbers-1.zkl b/Task/Bernoulli-numbers/Zkl/bernoulli-numbers-1.zkl new file mode 100644 index 0000000000..8657abc81f --- /dev/null +++ b/Task/Bernoulli-numbers/Zkl/bernoulli-numbers-1.zkl @@ -0,0 +1,20 @@ +class Rational{ // Weenie Rational class, can handle BigInts + fcn init(_a,_b){ var a=_a, b=_b; normalize(); } + fcn toString{ "%50d / %d".fmt(a,b) } + fcn normalize{ // divide a and b by gcd + g:= a.gcd(b); + a/=g; b/=g; + if(b<0){ a=-a; b=-b; } // denominator > 0 + self + } + fcn __opAdd(n){ + if(Rational.isChildOf(n)) self(a*n.b + b*n.a, b*n.b); // Rat + Rat + else self(b*n + a, b); // Rat + Int + } + fcn __opSub(n){ self(a*n.b - b*n.a, b*n.b) } // Rat - Rat + fcn __opMul(n){ + if(Rational.isChildOf(n)) self(a*n.a, b*n.b); // Rat * Rat + else self(a*n, b); // Rat * Int + } + fcn __opDiv(n){ self(a*n.b,b*n.a) } // Rat / Rat +} diff --git a/Task/Bernoulli-numbers/Zkl/bernoulli-numbers-2.zkl b/Task/Bernoulli-numbers/Zkl/bernoulli-numbers-2.zkl new file mode 100644 index 0000000000..ffc2737c7f --- /dev/null +++ b/Task/Bernoulli-numbers/Zkl/bernoulli-numbers-2.zkl @@ -0,0 +1,9 @@ +var [const] BN=Import.lib("zklBigNum"); // libGMP (GNU MP Bignum Library) +fcn B(N){ // calculate Bernoulli(n) + var A=List.createLong(100,0); // aka static aka not thread safe + foreach m in (N+1){ + A[m]=Rational(BN(1),BN(m+1)); + foreach j in ([m..1, -1]){ A[j-1]= (A[j-1] - A[j])*j; } + } + A[0] +} diff --git a/Task/Bernoulli-numbers/Zkl/bernoulli-numbers-3.zkl b/Task/Bernoulli-numbers/Zkl/bernoulli-numbers-3.zkl new file mode 100644 index 0000000000..964a79a6e2 --- /dev/null +++ b/Task/Bernoulli-numbers/Zkl/bernoulli-numbers-3.zkl @@ -0,0 +1 @@ +foreach b in ([0..1].chain([2..60,2])){ println("B(%2d)%s".fmt(b,B(b))) } diff --git a/Task/Best-shuffle/Elena/best-shuffle.elena b/Task/Best-shuffle/Elena/best-shuffle.elena index 086b29ebec..fa8eaa65fd 100644 --- a/Task/Best-shuffle/Elena/best-shuffle.elena +++ b/Task/Best-shuffle/Elena/best-shuffle.elena @@ -1,48 +1,47 @@ -#define system. -#define system'routines. -#define extensions. +import system'routines. +import extensions. -#class(extension)op +extension op { - #method shuffled + shuffled [ - #var anOriginal := self toArray. - #var aShuffled := self toArray. + var anOriginal := self toArray. + var aShuffled := self toArray. - 0 to:(anOriginal length - 1) &doEach: (:i) + 0 to(anOriginal length - 1) do(:i) [ - 0 to:(anOriginal length - 1) &doEach: (:j) + 0 to(anOriginal length - 1) do(:j) [ - ((i != j)and:[anOriginal@i != (aShuffled@j)]and:[anOriginal@j != (aShuffled@i)]) ? + if ((i != j) && $(anOriginal[i] != aShuffled[j]) && $(anOriginal[j] != aShuffled[i])) [ - aShuffled exchange:i:j. + aShuffled exchange(i,j) ]. ]. ]. - ^ aShuffled summarize:(String new) literal. + ^ aShuffled summarize(String new); literal ] - #method score : anOriginalText + score : anOriginalText [ - #var aShuffled := self toArray. - #var anOriginal := anOriginalText toArray. - #var aScore := Integer new. + var aShuffled := self toArray. + var anOriginal := anOriginalText toArray. + var aScore := Integer new. - 0 to:(anOriginal length - 1) &doEach: (:i) - [ ((anOriginal @ i) == (aShuffled @ i)) ? [ aScore += 1. ]. ]. + 0 to(anOriginal length - 1) do(:i) + [ if (anOriginal[i] == aShuffled[i]) [ aScore append:1 ] ]. ^ aScore value. ] } -#symbol program = +program = [ - ("abracadabra", "seesaw", "grrrrrr", "pop", "up", "a") run &each: aWord + ("abracadabra", "seesaw", "grrrrrr", "pop", "up", "a") forEach(:aWord) [ - #var aShuffled := aWord shuffled. + var aShuffled := aWord shuffled. - console writeLine:"The best shuffle of ":aWord:" is ":aShuffled:"(":(aShuffled score:aWord):")". + console printLine("The best shuffle of ",aWord," is ",aShuffled,"(",aShuffled score:aWord,")"). ]. console readChar. diff --git a/Task/Best-shuffle/JavaScript/best-shuffle-3.js b/Task/Best-shuffle/JavaScript/best-shuffle-3.js deleted file mode 100644 index ddcdbcc7c2..0000000000 --- a/Task/Best-shuffle/JavaScript/best-shuffle-3.js +++ /dev/null @@ -1,6 +0,0 @@ -abracadabra, raababacdar, (0) -seesaw, ewaess, (0) -elk, lke, (0) -grrrrrr, rrrrrgr, (5) -up, pu, (0) -a, a, (1) diff --git a/Task/Best-shuffle/Jq/best-shuffle-1.jq b/Task/Best-shuffle/Jq/best-shuffle-1.jq new file mode 100644 index 0000000000..01f379e115 --- /dev/null +++ b/Task/Best-shuffle/Jq/best-shuffle-1.jq @@ -0,0 +1,34 @@ +def count(s): reduce s as $i (0;.+1); + +def swap($i;$j): + .[$i] as $x | .[$i] = .[$j] | .[$j] = $x; + +# Input: an array +# Output: a best shuffle +def bestShuffleArray: + . as $s + | reduce range(0; length) as $i (.; + . as $t + | (first(range(0; length) + | select( $i != . and + $t[$i] != $s[.] and + $s[$i] != $t[.] and + $t[$i] != $t[.])) as $j + | swap($i;$j)) + // $t # fallback + ); + +# Award 1 for every spot which changed: +def score($base): + . as $in + | count( range(0;length) + | select($base[.] != $in[.]) ); + +# Input: a string +# Output: INPUT, BESTSHUFFLE, (NUMBER) +def bestShuffle: + . as $in + | explode + | . as $s + | bestShuffleArray + | "\($in), \(implode), (\( length - score($s) ))" ; diff --git a/Task/Best-shuffle/Jq/best-shuffle-2.jq b/Task/Best-shuffle/Jq/best-shuffle-2.jq new file mode 100644 index 0000000000..e39bf43100 --- /dev/null +++ b/Task/Best-shuffle/Jq/best-shuffle-2.jq @@ -0,0 +1,2 @@ +"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a", "antidisestablishmentarianism" +| bestShuffle diff --git a/Task/Best-shuffle/Julia/best-shuffle.julia b/Task/Best-shuffle/Julia/best-shuffle.julia new file mode 100644 index 0000000000..f45f59a335 --- /dev/null +++ b/Task/Best-shuffle/Julia/best-shuffle.julia @@ -0,0 +1,52 @@ +# v0.6 + +function bestshuffle(str::String)::Tuple{String,Int} + s = Vector{Char}(str) + + # Count the supply of characters. + cnt = Dict{Char,Int}(c => 0 for c in s) + for c in s; cnt[c] += 1 end + + # Allocate the result + r = similar(s) + for (i, x) in enumerate(s) + # Find the best character to replace x. + best = x + rankb = -2 + for (c, rankc) in cnt + # Prefer characters with more supply. + # (Save characters with less supply.) + # Avoid identical characters. + if c == x; rankc = -1 end + if rankc > rankb + best = c + rankb = rankc + end + end + + # Add character to list. Remove it from supply. + r[i] = best + cnt[best] -= 1 + if cnt[best] == 0; delete!(cnt, best) end + end + + # If the final letter became stuck (as "ababcd" became "bacabd", + # and the final "d" became stuck), then fix it. + i = length(s) + if r[i] == s[i] + for j in 1:i + if r[i] != s[j] && r[j] != s[i] + r[i], r[j] = r[j], r[i] + break + end + end + end + + score = sum(x == y for (x, y) in zip(r, s)) + return r, score +end + +for word in ("abracadabra", "seesaw", "elk", "grrrrrr", "up", "a") + shuffled, score = bestshuffle(word) + println("$word: $shuffled ($score)") +end diff --git a/Task/Best-shuffle/Kotlin/best-shuffle.kotlin b/Task/Best-shuffle/Kotlin/best-shuffle.kotlin index c7418307d8..66e8a947b6 100644 --- a/Task/Best-shuffle/Kotlin/best-shuffle.kotlin +++ b/Task/Best-shuffle/Kotlin/best-shuffle.kotlin @@ -1,5 +1,3 @@ -package shuffle - import java.util.Random object BestShuffle { diff --git a/Task/Best-shuffle/Sidef/best-shuffle.sidef b/Task/Best-shuffle/Sidef/best-shuffle.sidef index 2782238e66..02fbc79575 100644 --- a/Task/Best-shuffle/Sidef/best-shuffle.sidef +++ b/Task/Best-shuffle/Sidef/best-shuffle.sidef @@ -3,20 +3,19 @@ func best_shuffle(String orig) -> (String, Number) { var s = orig.chars var t = s.shuffle - s.range.each { |i| - s.range.each { |j| + for i (^s) { + for j (^s) { if (i!=j && t[i]!=s[j] && t[j]!=s[i]) { - t[i, j] = t[j, i]; - break; + t[i, j] = t[j, i] + break } } } - var word = t.join; - (word, orig ^ word -> count("\0")); + (t.join, s ~Z== t -> count(true)) } -.each { |word| +for word () { var (sword, score) = best_shuffle(word) "%-12s %12s: %d\n".printf(word, sword, score) } diff --git a/Task/Best-shuffle/VBScript/best-shuffle.vb b/Task/Best-shuffle/VBScript/best-shuffle.vb index 22ed8feb23..8d21c6236c 100644 --- a/Task/Best-shuffle/VBScript/best-shuffle.vb +++ b/Task/Best-shuffle/VBScript/best-shuffle.vb @@ -1,29 +1,52 @@ -Function shuffle(s) - Dim arr() - ReDim arr(Len(s)-1) - Set objrandom = CreateObject("System.Random") - For i = 1 To Len(s) - l = Mid(s,i,1) - Do - n = objrandom.Next_2(0,Len(s)) - If arr(n) = "" Then - arr(n) = l - Exit Do - End If - Loop - Next - shuffled_word = Join(arr,"") - score = 0 - For j = 1 To Len(s) - If Mid(s,j,1) = Mid(shuffled_word,j,1) Then - score = score + 1 - End If - Next - shuffle = shuffled_word & ",(" & score & ")" +'Best Shuffle Task +'VBScript Implementation + +Function bestshuffle(s) + Dim arr:Redim arr(Len(s)-1) + + 'The Following Does the toCharArray() Functionality + For i = 0 To Len(s)-1 + arr(i) = Mid(s, i + 1, 1) + Next + + arr = shuffler(arr) 'Make this line a comment for deterministic solution + For i = 0 To UBound(arr):Do + If arr(i) <> Mid(s, i + 1, 1) Then Exit Do + For j = 0 To UBound(arr) + If arr(i) <> arr(j) And arr(i) <> Mid(s, j + 1, 1) And arr(j) <> Mid(s, i + 1, 1) Then + tmp = arr(i) + arr(i) = arr(j) + arr(j) = tmp + End If + Next + Loop While False:Next + + shuffled_word = Join(arr,"") + + 'This section is the scorer + score = 0 + For k = 1 To Len(s) + If Mid(s,k,1) = Mid(shuffled_word,k,1) Then + score = score + 1 + End If + Next + + bestshuffle = shuffled_word & ",(" & score & ")" +End Function + +Function shuffler(array) + Set rand = CreateObject("System.Random") + For i = UBound(array) to 0 Step -1 + r = rand.next_2(0, i + 1) + tmp = array(i) + array(i) = array(r) + array(r) = tmp + Next + shuffler = array End Function 'Testing the function word_list = Array("abracadabra","seesaw","elk","grrrrrr","up","a") For Each word In word_list - WScript.StdOut.WriteLine word & "," & shuffle(word) + WScript.StdOut.WriteLine word & "," & bestshuffle(word) Next diff --git a/Task/Best-shuffle/Zkl/best-shuffle-1.zkl b/Task/Best-shuffle/Zkl/best-shuffle-1.zkl new file mode 100644 index 0000000000..c231de52ad --- /dev/null +++ b/Task/Best-shuffle/Zkl/best-shuffle-1.zkl @@ -0,0 +1,15 @@ +fcn bestShuffle(str){ + s:=str.split("").shuffle(); // -->List + if(not s) return(str,str.len()); // can't shuffle "" or "a" + + n:=str.len(); + foreach i in (n){ + foreach j in (n){ + if (i!=j and s[i]!=str[j] and s[j]!=str[i]){ + s.swap(i,j); + break; + } + } + } + return(s.concat(), s.zipWith('==,str).sum(0)); +} diff --git a/Task/Best-shuffle/Zkl/best-shuffle-2.zkl b/Task/Best-shuffle/Zkl/best-shuffle-2.zkl new file mode 100644 index 0000000000..2f6e94d1f7 --- /dev/null +++ b/Task/Best-shuffle/Zkl/best-shuffle-2.zkl @@ -0,0 +1,5 @@ +ss:=T("abracadabra","immediately","grrrrrr","seesaw","pop","up","a",""); +foreach s in (ss){ + ns,cnt:=bestShuffle(s); + println("%s --> %s (%d)".fmt(s,ns,cnt)); +} diff --git a/Task/Binary-digits/6502-Assembly/binary-digits.6502 b/Task/Binary-digits/6502-Assembly/binary-digits.6502 new file mode 100644 index 0000000000..91a54b3df1 --- /dev/null +++ b/Task/Binary-digits/6502-Assembly/binary-digits.6502 @@ -0,0 +1,90 @@ +; C64 - Binary digits +; http://rosettacode.org/wiki/Binary_digits + +; *** labels *** + +declow = $fb +dechigh = $fc +binstrptr = $fd ; $fe is used for the high byte of the address +chkcom = $aefd +frmnum = $ad8a +getadr = $b7f7 +strout = $ab1e + +; *** main *** + + *=$033c ; sys828 tbuffer ($033c-$03fb) + + jsr chkcom ; check for and skip comma + jsr frmnum ; evaluate numeric expression + jsr getadr ; convert floating point number to two-byte int + jsr dec2bin ; convert two-byte int to binary string + lda #binstr ; high byte + jsr skiplz ; skip leading zeros, return an address in a/y + ; that points to the first "1" + jsr strout ; print the result + rts + +; *** subroutines **** + +; Converts a 16 bit integer to a binary string. +; Input: y - low byte of the integer +; a - high byte of the integer +; Output: a 16 byte string stored at 'binstr' +dec2bin sty declow ; store the two-byte integer + sta dechigh + lda #binstr + sta binstrptr+1 + ldx #$01 ; start conversion with the high byte +wordloop ldy #$00 ; bit counter +byteloop asl declow,x ; shift left, bit 7 is shifted into carry + bcs one ; carry set? jump + lda #"0" ; a="0" + bne writebit +one lda #"1" ; a="1" +writebit sta (binstrptr),y ; write the digit to the string + iny ; y++ + cpy #$08 ; y==8 all bits converted? + bne byteloop ; no -> convert next bit + clc ; clear carry + lda #$08 ; a=8 + adc binstrptr ; add 8 to the string address pointer + sta binstrptr + bcc nooverflow ; address low byte did overflow? + inc binstrptr+1 ; yes -> increase the high byte +nooverflow dex ; x-- + bpl wordloop ; x<0? no -> convert the low byte + rts ; yes -> conversion finished, return + +; Skip leading zeros. +; Input: a - low byte of the byte string address +; y - high byte -"- +; Output: a - low byte of string start address without leading zeros +; y - high byte -"- +skiplz sta binstrptr ; store the binary string address on the zero page + sty binstrptr+1 + ldy #$00 ; byte counter +skiploop lda (binstrptr),y ; load a byte from the string + iny ; y++ + cpy #$11 ; y==17 + beq endreached ; yes -> end of string reached without a "1" + cmp #"1" ; a=="1" + bne skiploop ; no -> take the next byte + beq add2ptr ; yes -> jump +endreached dey ; move the pointer to the last 0 +add2ptr clc + dey + tya ; a=y + adc binstrptr ; move the pointer to the first "1" in the string + bcc loadhigh ; overflow? + inc binstrptr+1 ; yes -> increase high byte +loadhigh ldy binstrptr+1 + rts + +; *** data *** + +binstr .repeat 16, $00 ; reserve 16 bytes for the binary digits + .byte $0d, $00 ; newline + null terminator diff --git a/Task/Binary-digits/Ada/binary-digits.ada b/Task/Binary-digits/Ada/binary-digits.ada index 0fefbc2dc8..405f14bb78 100644 --- a/Task/Binary-digits/Ada/binary-digits.ada +++ b/Task/Binary-digits/Ada/binary-digits.ada @@ -1,28 +1,11 @@ -with Ada.Text_IO; - -procedure Binary_Output is - - package IIO is new Ada.Text_IO.Integer_IO(Integer); - - function To_Binary(N: Natural) return String is - S: String(1 .. 1000); -- more than plenty! - Left: Positive := S'First; - Right: Positive := S'Last; - begin - IIO.Put(To => S, Item => N, Base => 2); -- This is the conversion! - -- Now S is a String with many spaces and some "2#...#" somewhere. - -- We only need the "..." part without spaces or base markers. - while S(Left) /= '#' loop - Left := Left + 1; - end loop; - while S(Right) /= '#' loop - Right := Right - 1; - end loop; - return S(Left+1 .. Right-1); - end To_Binary; - +with ada.text_io;use ada.text_io; +procedure binary is +-- the digits in base 2 + bit : array (0..1) of string (1..1) := ("0","1"); +-- the conversion function itself + function bin_image (n : Natural) return string is (if n<2 then bit (n) else bin_image (n/2)&bit(n mod 2)); +-- the values we want to test + test_values : array (1..3) of Natural := (5,50,9000); begin - Ada.Text_IO.Put_Line(To_Binary(5)); -- 101 - Ada.Text_IO.Put_Line(To_Binary(50)); -- 110010 - Ada.Text_IO.Put_Line(To_Binary(9000)); -- 10001100101000 -end Binary_Output; + for test of test_values loop put_line ("Output for"&test'img&" is "&bin_image (test)); end loop; +end binary; diff --git a/Task/Binary-digits/AppleScript/binary-digits-1.applescript b/Task/Binary-digits/AppleScript/binary-digits-1.applescript new file mode 100644 index 0000000000..43161f639a --- /dev/null +++ b/Task/Binary-digits/AppleScript/binary-digits-1.applescript @@ -0,0 +1,90 @@ +-- showBin :: Int -> String +on showBin(n) + script binaryChar + on |λ|(n) + text item (n + 1) of "01" + end |λ| + end script + showIntAtBase(2, binaryChar, n, "") +end showBin + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- showIntAtBase :: Int -> (Int -> Char) -> Int -> String -> String +on showIntAtBase(base, toChr, n, rs) + script showIt + on |λ|(nd_, r) + set {n, d} to nd_ + set r_ to toChr's |λ|(d) & r + if n > 0 then + |λ|(quotRem(n, base), r_) + else + r_ + end if + end |λ| + end script + + if base ≤ 1 then + "error: showIntAtBase applied to unsupported base: " & base as string + else if n < 0 then + "error: showIntAtBase applied to negative number: " & base as string + else + showIt's |λ|(quotRem(n, base), rs) + end if +end showIntAtBase + +-- quotRem :: Integral a => a -> a -> (a, a) +on quotRem(m, n) + {m div n, m mod n} +end quotRem + +-- TEST ----------------------------------------------------------------------- +on run + script + on |λ|(n) + intercalate(" -> ", {n as string, showBin(n)}) + end |λ| + end script + + return unlines(map(result, {5, 50, 9000})) +end run + + +-- GENERIC FUNCTIONS FOR TEST ------------------------------------------------- + +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- unlines :: [String] -> String +on unlines(xs) + intercalate(linefeed, xs) +end unlines diff --git a/Task/Binary-digits/AppleScript/binary-digits-2.applescript b/Task/Binary-digits/AppleScript/binary-digits-2.applescript new file mode 100644 index 0000000000..71190e738c --- /dev/null +++ b/Task/Binary-digits/AppleScript/binary-digits-2.applescript @@ -0,0 +1,9 @@ +-- showBin :: Int -> String +on showBin(n) + script binaryChar + on |λ|(n) + text item (n + 1) of "〇一" + end |λ| + end script + showIntAtBase(2, binaryChar, n, "") +end showBin diff --git a/Task/Binary-digits/AppleScript/binary-digits.applescript b/Task/Binary-digits/AppleScript/binary-digits.applescript deleted file mode 100644 index fcf36e0668..0000000000 --- a/Task/Binary-digits/AppleScript/binary-digits.applescript +++ /dev/null @@ -1,80 +0,0 @@ --- binaryString :: Int -> String -on binaryString(n) - - showIntAtBase(2, n) - -end binaryString - - --- showIntAtBase :: Int -> Int -> String -on showIntAtBase(base, n) - if base > 1 then - if n > 0 then - set m to n mod base - set r to n - m - if r > 0 then - set prefix to showIntAtBase(base, r div base) - else - set prefix to "" - end if - - if m < 10 then - set baseCode to 48 -- "0" - else - set baseCode to 55 -- "A" - 10 - end if - - prefix & character id (baseCode + m) - else - "0" - end if - else - missing value - end if -end showIntAtBase - - --- TEST -on run - - intercalate(linefeed, ¬ - map(binaryString, [5, 50, 9000])) - -end run - - - - --- GENERIC FUNCTIONS FOR TESTING - --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map - --- intercalate :: Text -> [Text] -> Text -on intercalate(strText, lstText) - set {dlm, my text item delimiters} to {my text item delimiters, strText} - set strJoined to lstText as text - set my text item delimiters to dlm - return strJoined -end intercalate - --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn diff --git a/Task/Binary-digits/Applesoft-BASIC/binary-digits.applesoft b/Task/Binary-digits/BASIC/binary-digits-1.basic similarity index 100% rename from Task/Binary-digits/Applesoft-BASIC/binary-digits.applesoft rename to Task/Binary-digits/BASIC/binary-digits-1.basic diff --git a/Task/Binary-digits/BBC-BASIC/binary-digits-1.bbc b/Task/Binary-digits/BASIC/binary-digits-2.basic similarity index 100% rename from Task/Binary-digits/BBC-BASIC/binary-digits-1.bbc rename to Task/Binary-digits/BASIC/binary-digits-2.basic diff --git a/Task/Binary-digits/BBC-BASIC/binary-digits-2.bbc b/Task/Binary-digits/BASIC/binary-digits-3.basic similarity index 100% rename from Task/Binary-digits/BBC-BASIC/binary-digits-2.bbc rename to Task/Binary-digits/BASIC/binary-digits-3.basic diff --git a/Task/Binary-digits/BASIC/binary-digits-4.basic b/Task/Binary-digits/BASIC/binary-digits-4.basic new file mode 100644 index 0000000000..ff8524347c --- /dev/null +++ b/Task/Binary-digits/BASIC/binary-digits-4.basic @@ -0,0 +1,14 @@ +10 N = 5 : GOSUB 100 +20 N = 50 : GOSUB 100 +30 N = 9000 : GOSUB 100 +40 END +90 REM *** SUBROUTINE: CONVERT DECIMAL TO BINARY +100 N2 = ABS(INT(N)) +110 B$ = "" +120 FOR N1 = N2 TO 0 STEP 0 +130 : N2 = INT(N1 / 2) +140 : B$ = STR$(N1 - N2 * 2) + B$ +150 : N1 = N2 +160 NEXT N1 +170 PRINT B$ +180 RETURN diff --git a/Task/Binary-digits/BaCon/binary-digits.bacon b/Task/Binary-digits/BaCon/binary-digits.bacon new file mode 100644 index 0000000000..0089d7f770 --- /dev/null +++ b/Task/Binary-digits/BaCon/binary-digits.bacon @@ -0,0 +1,8 @@ +' Binary digits +OPTION MEMTYPE int +INPUT n$ +IF VAL(n$) = 0 THEN + PRINT "0" +ELSE + PRINT CHOP$(BIN$(VAL(n$)), "0", 1) +ENDIF diff --git a/Task/Binary-digits/Bc/binary-digits.bc b/Task/Binary-digits/Bc/binary-digits.bc new file mode 100644 index 0000000000..2bbc12309e --- /dev/null +++ b/Task/Binary-digits/Bc/binary-digits.bc @@ -0,0 +1,5 @@ +obase = 2 +5 +50 +9000 +quit diff --git a/Task/Binary-digits/C++/binary-digits-5.cpp b/Task/Binary-digits/C++/binary-digits-5.cpp new file mode 100644 index 0000000000..d50e44914c --- /dev/null +++ b/Task/Binary-digits/C++/binary-digits-5.cpp @@ -0,0 +1,11 @@ +#include + +std::string binary(int n) { + return n == 0 ? "" : binary(n >> 1) + std::to_string(n & 1); +} + +int main(int argc, char* argv[]) { + for (int i = 1; i < argc; ++i) { + std::cout << binary(std::stoi(argv[i])) << std::endl; + } +} diff --git a/Task/Binary-digits/C/binary-digits-1.c b/Task/Binary-digits/C/binary-digits-1.c deleted file mode 100644 index 08c7c0c86a..0000000000 --- a/Task/Binary-digits/C/binary-digits-1.c +++ /dev/null @@ -1,20 +0,0 @@ -#include - -void bin(int x, char *s) -{ - char*_(int x){ - *(s = x ? _(x >> 1) : s) = (x & 1) + '0'; - return ++s; - } - *_(x) = 0; -} - -int main() -{ - char a[100]; - int i; - for (i = 0; i <= 1984; i += 31) - bin(i, a), printf("%4d: %s\n", i, a); - - return 0; -} diff --git a/Task/Binary-digits/C/binary-digits-2.c b/Task/Binary-digits/C/binary-digits-2.c deleted file mode 100644 index 70aef3c276..0000000000 --- a/Task/Binary-digits/C/binary-digits-2.c +++ /dev/null @@ -1,30 +0,0 @@ -#include - -void IntToBitString(unsigned int number) -{ - int num_bits = sizeof(unsigned int) * 8; - - bool startPrinting = false; - for (int bit_pos=num_bits-1; bit_pos >= 0; bit_pos--) - { - bool isBitSet = (number & (1< { - [5, 50, 9000].map(function (n) { - return (n).toString(2); - }).join('\n') + // showIntAtBase_ :: // Int -> Int -> String + const showIntAtBase_ = (base, n) => (n) + .toString(base); -) + // showBin :: Int -> String + const showBin = n => showIntAtBase_(2, n); + + // GENERIC FUNCTIONS FOR TEST --------------------------------------------- + + // intercalate :: String -> [a] -> String + const intercalate = (s, xs) => xs.join(s); + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + // show :: a -> String + const show = x => JSON.stringify(x); + + // TEST ------------------------------------------------------------------- + + return unlines(map( + n => intercalate(' -> ', [show(n), showBin(n)]), + [5, 50, 9000] + )); +})(); diff --git a/Task/Binary-digits/JavaScript/binary-digits-3.js b/Task/Binary-digits/JavaScript/binary-digits-3.js new file mode 100644 index 0000000000..b4b04dacd0 --- /dev/null +++ b/Task/Binary-digits/JavaScript/binary-digits-3.js @@ -0,0 +1,47 @@ +(() => { + + // showBin :: Int -> String + const showBin = n => { + const binaryChar = n => n !== 0 ? '一' : '〇'; + + return showIntAtBase(2, binaryChar, n, ''); + }; + + // showIntAtBase :: Int -> (Int -> Char) -> Int -> String -> String + const showIntAtBase = (base, toChr, n, rs) => { + const showIt = ([n, d], r) => { + const r_ = toChr(d) + r; + return n !== 0 ? ( + showIt(quotRem(n, base), r_) + ) : r_; + }; + return base <= 1 ? ( + 'error: showIntAtBase applied to unsupported base' + ) : n < 0 ? ( + 'error: showIntAtBase applied to negative number' + ) : showIt(quotRem(n, base), rs); + }; + + // quotRem :: Integral a => a -> a -> (a, a) + const quotRem = (m, n) => [Math.floor(m / n), m % n]; + + // GENERIC FUNCTIONS FOR TEST --------------------------------------------- + + // intercalate :: String -> [a] -> String + const intercalate = (s, xs) => xs.join(s); + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + // show :: a -> String + const show = x => JSON.stringify(x); + + // TEST ------------------------------------------------------------------- + + return unlines(map( + n => intercalate(' -> ', [show(n), showBin(n)]), [5, 50, 9000] + )); +})(); diff --git a/Task/Binary-digits/jq/binary-digits.jq b/Task/Binary-digits/Jq/binary-digits.jq similarity index 100% rename from Task/Binary-digits/jq/binary-digits.jq rename to Task/Binary-digits/Jq/binary-digits.jq diff --git a/Task/Binary-digits/Kotlin/binary-digits.kotlin b/Task/Binary-digits/Kotlin/binary-digits.kotlin new file mode 100644 index 0000000000..959cec48ec --- /dev/null +++ b/Task/Binary-digits/Kotlin/binary-digits.kotlin @@ -0,0 +1,6 @@ +// version 1.0.5-2 + +fun main(args: Array) { + val numbers = intArrayOf(5, 50, 9000) + for (number in numbers) println("%4d".format(number) + " -> " + Integer.toBinaryString(number)) +} diff --git a/Task/Binary-digits/MLite/binary-digits.mlite b/Task/Binary-digits/MLite/binary-digits.mlite new file mode 100644 index 0000000000..e18233229f --- /dev/null +++ b/Task/Binary-digits/MLite/binary-digits.mlite @@ -0,0 +1,5 @@ +fun binary + (0, b) = implode ` map (fn x = if int x then chr (x + 48) else x) b + | (n, b) = binary (n div 2, n mod 2 :: b) + | n = binary (n, []) +; diff --git a/Task/Binary-digits/Objeck/binary-digits.objeck b/Task/Binary-digits/Objeck/binary-digits.objeck index 43577bbdd7..30d98f886a 100644 --- a/Task/Binary-digits/Objeck/binary-digits.objeck +++ b/Task/Binary-digits/Objeck/binary-digits.objeck @@ -1,9 +1,7 @@ -bundle Default { - class Binary { - function : Main(args : String[]) ~ Nil { - 5->ToBinaryString()->PrintLine(); - 50->ToBinaryString()->PrintLine(); - 9000->ToBinaryString()->PrintLine(); - } +class Binary { + function : Main(args : String[]) ~ Nil { + 5->ToBinaryString()->PrintLine(); + 50->ToBinaryString()->PrintLine(); + 9000->ToBinaryString()->PrintLine(); } } diff --git a/Task/Binary-digits/SkookumScript/binary-digits.skookum b/Task/Binary-digits/SkookumScript/binary-digits-1.skookum similarity index 100% rename from Task/Binary-digits/SkookumScript/binary-digits.skookum rename to Task/Binary-digits/SkookumScript/binary-digits-1.skookum diff --git a/Task/Binary-digits/SkookumScript/binary-digits-2.skookum b/Task/Binary-digits/SkookumScript/binary-digits-2.skookum new file mode 100644 index 0000000000..d9293b81aa --- /dev/null +++ b/Task/Binary-digits/SkookumScript/binary-digits-2.skookum @@ -0,0 +1 @@ +{5 50 9000}.do[println(item.binary)] diff --git a/Task/Binary-digits/Zkl/binary-digits-1.zkl b/Task/Binary-digits/Zkl/binary-digits-1.zkl new file mode 100644 index 0000000000..63ab008538 --- /dev/null +++ b/Task/Binary-digits/Zkl/binary-digits-1.zkl @@ -0,0 +1 @@ +(9000).toString(2) diff --git a/Task/Binary-digits/Zkl/binary-digits-2.zkl b/Task/Binary-digits/Zkl/binary-digits-2.zkl new file mode 100644 index 0000000000..011fe31ce6 --- /dev/null +++ b/Task/Binary-digits/Zkl/binary-digits-2.zkl @@ -0,0 +1 @@ +T(5,50,9000).apply("toString",2) //--> L("101","110010","10001100101000") diff --git a/Task/Binary-digits/Zkl/binary-digits-3.zkl b/Task/Binary-digits/Zkl/binary-digits-3.zkl new file mode 100644 index 0000000000..421ed1fb99 --- /dev/null +++ b/Task/Binary-digits/Zkl/binary-digits-3.zkl @@ -0,0 +1 @@ +"%.2B".fmt(9000) diff --git a/Task/Binary-search/00DESCRIPTION b/Task/Binary-search/00DESCRIPTION index 62772bf0a3..fd13cbf6ba 100644 --- a/Task/Binary-search/00DESCRIPTION +++ b/Task/Binary-search/00DESCRIPTION @@ -4,8 +4,8 @@ As an analogy, consider the children's game "[[Guess the number/With feedback|gu As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number. -'''The Task''' +;Task: Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also. There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them. @@ -16,7 +16,7 @@ All of the following code examples use an "inclusive" upper bound (i.e. hi * (for recursive algorithm) change if (high < low) to if (high <= low) * (for iterative algorithm) change while (low <= high) to while (low < high) -; Traditional algorithm +;Traditional algorithm The algorithms are as follows (from [[wp:Binary search|Wikipedia]]). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array). '''Recursive Pseudocode''': @@ -53,7 +53,7 @@ The algorithms are as follows (from [[wp:Binary search|Wikipedia]]). The algorit return not_found // value would be inserted at index "low" } -; Leftmost insertion point +;Leftmost insertion point The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. '''Recursive Pseudocode''': @@ -86,7 +86,7 @@ The following algorithms return the leftmost place where the given element can b return low } -; Rightmost insertion point +;Rightmost insertion point The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values. '''Recursive Pseudocode''': @@ -122,7 +122,7 @@ The following algorithms return the rightmost place where the given element can ;Extra credit Make sure it does not have overflow bugs. -The line in the pseudocode above to calculate the mean of two integers: +The line in the pseudo-code above to calculate the mean of two integers:
    mid = (low + high) / 2
    could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result. @@ -134,7 +134,12 @@ Another way for signed integers, possibly faster, is the following:
    mid = (low + high) >>> 1
    where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift. -'''References:'''
    -:* C.f: [[Guess the number/With Feedback (Player)]] + +;Related task: +:* [[Guess the number/With Feedback (Player)]] + + +;See also: :* [[wp:Binary search algorithm]] :* [http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken]. +

    diff --git a/Task/Binary-search/360-Assembly/binary-search.360 b/Task/Binary-search/360-Assembly/binary-search.360 new file mode 100644 index 0000000000..84cc2f8948 --- /dev/null +++ b/Task/Binary-search/360-Assembly/binary-search.360 @@ -0,0 +1,71 @@ +* Binary search 05/03/2017 +BINSEAR CSECT + USING BINSEAR,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + MVC LOW,=H'1' low=1 + MVC HIGH,=AL2((XVAL-T)/2) high=hbound(t) + SR R6,R6 i=0 + MVI F,X'00' f=false + LH R4,LOW low + DO WHILE=(CH,R4,LE,HIGH) do while low<=high + LA R6,1(R6) i=i+1 + LH R1,LOW low + AH R1,HIGH +high + SRA R1,1 /2 {by right shift} + STH R1,MID mid=(low+high)/2 + SLA R1,1 *2 + LH R7,T-2(R1) y=t(mid) + IF CH,R7,EQ,XVAL THEN if xval=y then + MVI F,X'01' f=true + B EXITDO leave + ENDIF , endif + IF CH,R7,GT,XVAL THEN if y>xval then + LH R2,MID mid + BCTR R2,0 -1 + STH R2,HIGH high=mid-1 + ELSE , else + LH R2,MID mid + LA R2,1(R2) +1 + STH R2,LOW low=mid+1 + ENDIF , endif + LH R4,LOW low + ENDDO , enddo +EXITDO EQU * exitdo: + XDECO R6,XDEC edit i + MVC PG(4),XDEC+8 output i + MVC PG+4(6),=C' loops' + XPRNT PG,L'PG print buffer + LH R1,XVAL xval + XDECO R1,XDEC edit xval + MVC PG(4),XDEC+8 output xval + IF CLI,F,EQ,X'01' THEN if f then + MVC PG+4(10),=C' found at ' + LH R1,MID mid + XDECO R1,XDEC edit mid + MVC PG+14(4),XDEC+8 output mid + ELSE , else + MVC PG+4(20),=C' is not in the list.' + ENDIF , endif + XPRNT PG,L'PG print buffer + L R13,4(0,R13) restore previous savearea pointer + LM R14,R12,12(R13) restore previous context + XR R15,R15 rc=0 + BR R14 exit +T DC H'3',H'7',H'13',H'19',H'23',H'31',H'43',H'47' + DC H'61',H'73',H'83',H'89',H'103',H'109',H'113',H'131' + DC H'139',H'151',H'167',H'181',H'193',H'199',H'229',H'233' + DC H'241',H'271',H'283',H'293',H'313',H'317',H'337',H'349' +XVAL DC H'229' <= search value +LOW DS H +HIGH DS H +MID DS H +F DS X flag +PG DC CL80' ' buffer +XDEC DS CL12 temp + YREGS + END BINSEAR diff --git a/Task/Binary-search/Batch-File/binary-search.bat b/Task/Binary-search/Batch-File/binary-search.bat new file mode 100644 index 0000000000..a475830cde --- /dev/null +++ b/Task/Binary-search/Batch-File/binary-search.bat @@ -0,0 +1,48 @@ +@echo off & setlocal enabledelayedexpansion + +:: Binary Chop Algorithm - Michael Sanders 2017 +:: +:: example output... +:: +:: binary chop algorithm vs. standard for loop +:: +:: number to find 941 +:: for loop required 941 iterations +:: binchop required 10 iterations + +:setup + + set x=1 + set y=999 + set /a z=(%random% * (%y% - 1) / 32768 + 1) + +:pseudoarray + + for /l %%q in (%x%,1,%y%) do set /a array[%%q]=%%q + +:std4loop + + for /l %%q in (%x%,1,%y%) do ( + if !array[%%q]!==%z% (set f=%%q& goto :binchop) + ) + +:binchop + + if !x! leq !y! ( + set /a i+=1 + set /a "p=(!x!+!y!)/2" + call set /a t=%%array[!p!]%% + if !t! equ !z! (set b=!i!& goto :done) + if !t! lss !z! (set /a x=!p!+1) else (set /a y=!p!-1) + goto :binchop + ) + +:done + + cls + echo binary chop algorithm vs. standard for loop... + echo. + echo . number to find !z! + echo . for loop required !f! iterations + echo . binchop required !b! iterations + endlocal & exit /b 0 diff --git a/Task/Binary-search/C/binary-search-1.c b/Task/Binary-search/C/binary-search-1.c deleted file mode 100644 index d68f733aaa..0000000000 --- a/Task/Binary-search/C/binary-search-1.c +++ /dev/null @@ -1,36 +0,0 @@ -/* http://www.solipsys.co.uk/b_search/spec.htm */ -typedef int Object; - -int cmpObject(Object* pa, Object *pb) -{ - Object a = *pa; - Object b = *pb; - if (a < b) return -1; - if (a == b) return 0; - if (a > b) return 1; - assert(0); -} - -int bsearch(Object Array[], int n, Object *KeyPtr, - int (*cmp)(Object *, Object *), - int NotFound) -{ - unsigned left = 1, right = n; /* `unsigned' to avoid overflow in `(left + right)/2' */ - - if ( ! (Array && n > 0 && KeyPtr && cmp)) - return NotFound; /* invalid input or empty array */ - - while (left < right) - { - /* invariant: a[left] <= *KeyPtr <= a[right] or *KeyPtr not in Array */ - unsigned m = (left + right) / 2; /*NOTE: *intentionally* truncate for odd sum */ - - if (cmp(Array + m, KeyPtr) < 0) - left = m + 1; /* a[m] < *KeyPtr <= a[right] or *KeyPtr not in Array */ - else - /* assert(right != m) or infinite loop possible */ - right = m; /* a[left] <= *KeyPtr <= a[m] or *KeyPtr not in Array */ - } - /* assert(left == right) */ - return (cmp(Array + right, KeyPtr) == 0) ? right : NotFound; -} diff --git a/Task/Binary-search/C/binary-search-2.c b/Task/Binary-search/C/binary-search-2.c deleted file mode 100644 index 0a92817172..0000000000 --- a/Task/Binary-search/C/binary-search-2.c +++ /dev/null @@ -1,38 +0,0 @@ -#define DUMMY -1 /* dummy element of array (to adjust indexing from 1..n) */ - -int main(void) -{ - Object a[] = {DUMMY, 0, 1, 1, 2, 5}; /* allowed indices from 1 to n including */ - int n = sizeof(a)/sizeof(*a) - 1; - const int NotFound = -1; - - /* key not in Array */ - Object key = 4; - assert(NotFound == bsearch(a, n, &key, cmpObject, NotFound)); - key = DUMMY; - assert(NotFound == bsearch(a, n, &key, cmpObject, NotFound)); - key = 7; - assert(NotFound == bsearch(a, n, &key, cmpObject, NotFound)); - - /* all possible `n' and `k' for `a' array */ - int k; - key = 10; /* not in `a` array */ - for (n = 0; n <= sizeof(a)/sizeof(*a) - 1; ++n) - for (k = n; k>=1; --k) { - int index = bsearch(a, n, &a[k], cmpObject, NotFound); - assert(index == k || (k==3 && index == 2) || n == 0); /* for equal `1's */ - assert(NotFound == bsearch(a, n, &key, cmpObject, NotFound)); - } - n = sizeof(a)/sizeof(*a) - 1; - - /* NULL array */ - assert(NotFound == bsearch(NULL, n, &key, cmpObject, NotFound)); - /* NULL &key */ - assert(NotFound == bsearch(a, n, NULL, cmpObject, NotFound)); - /* NULL cmpObject */ - assert(1 == bsearch(a, n, &a[1], cmpObject, NotFound)); - assert(NotFound == bsearch(a, n, &a[1], NULL, NotFound)); - - printf("OK\n"); - return 0; -} diff --git a/Task/Binary-search/C/binary-search-3.c b/Task/Binary-search/C/binary-search-3.c deleted file mode 100644 index 673888784a..0000000000 --- a/Task/Binary-search/C/binary-search-3.c +++ /dev/null @@ -1,21 +0,0 @@ -#include /* for bsearch */ -#include - -int intcmp(const void *a, const void *b) -{ - /* this is only correct if it doesn't overflow */ - return *(const int *)a - *(const int *)b; -} - -int main() -{ - int nums[5] = {2, 3, 5, 6, 8}; - int desired = 6; - int *ptr = bsearch(&desired, nums, 5, sizeof(int), intcmp); - if (ptr == NULL) - printf("not found\n"); - else - printf("index = %d\n", ptr - nums); - - return 0; -} diff --git a/Task/Binary-search/Groovy/binary-search-1.groovy b/Task/Binary-search/Groovy/binary-search-1.groovy index 18ef3aceb8..5a81df9415 100644 --- a/Task/Binary-search/Groovy/binary-search-1.groovy +++ b/Task/Binary-search/Groovy/binary-search-1.groovy @@ -1,12 +1,13 @@ def binSearchR -binSearchR = { a, target, offset=0 -> - def n = a.size() +//define binSearchR closure. +binSearchR = { a, key, offset=0 -> def m = n.intdiv(2) + def n = a.size() a.empty \ - ? ["insertion point": offset] \ - : a[m] > target \ - ? binSearchR(a[0.. key \ + ? binSearchR(a[0.. (a -> Ordering) -> (a, a) -> Maybe a -binarySearch p (low,high) - | high < low = Nothing - | otherwise = - let mid = (low + high) `div` 2 in - case p mid of - LT -> binarySearch p (low, mid-1) - GT -> binarySearch p (mid+1, high) - EQ -> Just mid diff --git a/Task/Binary-search/Haskell/binary-search-2.hs b/Task/Binary-search/Haskell/binary-search-2.hs deleted file mode 100644 index e94148580b..0000000000 --- a/Task/Binary-search/Haskell/binary-search-2.hs +++ /dev/null @@ -1,5 +0,0 @@ -import Data.Array - -binarySearchArray :: (Ix i, Integral i, Ord e) => Array i e -> e -> Maybe i -binarySearchArray a x = binarySearch p (bounds a) where - p m = x `compare` (a ! m) diff --git a/Task/Binary-search/Haskell/binary-search.hs b/Task/Binary-search/Haskell/binary-search.hs new file mode 100644 index 0000000000..076e1058f7 --- /dev/null +++ b/Task/Binary-search/Haskell/binary-search.hs @@ -0,0 +1,52 @@ +import Data.Array (Array, Ix, (!), listArray, bounds) + +-- BINARY SEARCH -------------------------------------------------------------- +bSearch + :: Integral a + => (a -> Ordering) -> (a, a) -> Maybe a +bSearch p (low, high) + | high < low = Nothing + | otherwise = + let mid = (low + high) `div` 2 + in case p mid of + LT -> bSearch p (low, mid - 1) + GT -> bSearch p (mid + 1, high) + EQ -> Just mid + +-- Application to an array: +bSearchArray + :: (Ix i, Integral i, Ord e) + => Array i e -> e -> Maybe i +bSearchArray a x = bSearch (compare x . (a !)) (bounds a) + +-- TEST ----------------------------------------------------------------------- +axs + :: (Num i, Ix i) + => Array i String +axs = + listArray + (0, 11) + [ "alpha" + , "beta" + , "delta" + , "epsilon" + , "eta" + , "gamma" + , "iota" + , "kappa" + , "lambda" + , "mu" + , "theta" + , "zeta" + ] + +main :: IO () +main = + let e = "mu" + found = bSearchArray axs e + in putStrLn $ + '\'' : + e ++ + case found of + Nothing -> "' Not found" + Just x -> "' found at index " ++ show x diff --git a/Task/Binary-search/Java/binary-search-1.java b/Task/Binary-search/Java/binary-search-1.java index 31cad26c88..a91bb39e82 100644 --- a/Task/Binary-search/Java/binary-search-1.java +++ b/Task/Binary-search/Java/binary-search-1.java @@ -1,27 +1,29 @@ -... -//check will be the number we are looking for -//nums will be the array we are searching through -public static int binarySearch(int[] nums, int check){ +public class BinarySearchIterative { + + public static int binarySearch(int[] nums, int check) { int hi = nums.length - 1; int lo = 0; - while(hi >= lo){ - int guess = lo + ((hi - lo) / 2); - if(nums[guess] > check){ - hi = guess - 1; - }else if(nums[guess] < check){ - lo = guess + 1; - }else{ - return guess; - } + while (hi >= lo) { + int guess = lo + ((hi - lo) / 2); + if (nums[guess] > check) { + hi = guess - 1; + } else if (nums[guess] < check) { + lo = guess + 1; + } else { + return guess; + } } return -1; -} + } -public static void main(String[] args){ - int[] searchMe; - int someNumber; - ... - int index = binarySearch(searchMe, someNumber); - System.out.println(someNumber + ((index == -1) ? " is not in the array" : (" is at index " + index))); - ... + public static void main(String[] args) { + int[] haystack = {1, 5, 6, 7, 8, 11}; + int needle = 5; + int index = binarySearch(haystack, needle); + if (index == -1) { + System.out.println(needle + " is not in the array"); + } else { + System.out.println(needle + " is at index " + index); + } + } } diff --git a/Task/Binary-search/Java/binary-search-2.java b/Task/Binary-search/Java/binary-search-2.java index 5cc5eb0dce..b0cdc26ed3 100644 --- a/Task/Binary-search/Java/binary-search-2.java +++ b/Task/Binary-search/Java/binary-search-2.java @@ -1,21 +1,28 @@ -public static void main(String[] args){ - int[] searchMe; - int someNumber; - ... - int index = binarySearch(searchMe, someNumber, 0, searchMe.length); - System.out.println(someNumber + ((index == -1) ? " is not in the array" : (" is at index " + index))); - ... -} +public class BinarySearchRecursive { -public static int binarySearch(int[] nums, int check, int lo, int hi){ - if(hi < lo){ - return -1; //impossible index for "not found" + public static int binarySearch(int[] haystack, int needle, int lo, int hi) { + if (hi < lo) { + return -1; } int guess = (hi + lo) / 2; - if(nums[guess] > check){ - return binarySearch(nums, check, lo, guess - 1); - }else if(nums[guess] needle) { + return binarySearch(haystack, needle, lo, guess - 1); + } else if (haystack[guess] < needle) { + return binarySearch(haystack, needle, guess + 1, hi); } return guess; + } + + public static void main(String[] args) { + int[] haystack = {1, 5, 6, 7, 8, 11}; + int needle = 5; + + int index = binarySearch(haystack, needle, 0, haystack.length); + + if (index == -1) { + System.out.println(needle + " is not in the array"); + } else { + System.out.println(needle + " is at index " + index); + } + } } diff --git a/Task/Binary-search/jq/binary-search-1.jq b/Task/Binary-search/Jq/binary-search-1.jq similarity index 100% rename from Task/Binary-search/jq/binary-search-1.jq rename to Task/Binary-search/Jq/binary-search-1.jq diff --git a/Task/Binary-search/jq/binary-search-2.jq b/Task/Binary-search/Jq/binary-search-2.jq similarity index 100% rename from Task/Binary-search/jq/binary-search-2.jq rename to Task/Binary-search/Jq/binary-search-2.jq diff --git a/Task/Binary-search/Kotlin/binary-search.kotlin b/Task/Binary-search/Kotlin/binary-search.kotlin index b8f7f6c7c8..abc63b6858 100644 --- a/Task/Binary-search/Kotlin/binary-search.kotlin +++ b/Task/Binary-search/Kotlin/binary-search.kotlin @@ -1,45 +1,38 @@ -// iterative search: -fun > Array.binarySearch(target: T): Int { +fun > Array.iterativeBinarySearch(target: T): Int { var hi = size - 1 var lo = 0 while (hi >= lo) { val guess = lo + (hi - lo) / 2 - if (this[guess] > target) - hi = guess - 1 - else if (this[guess] < target) - lo = guess + 1 - else - return guess + if (this[guess] > target) hi = guess - 1 + else if (this[guess] < target) lo = guess + 1 + else return guess } return -1 } -// recursive search: -fun > Array.binarySearch(target: T, lo: Int, hi: Int): Int { - if (hi < lo) - return -1 +fun > Array.recursiveBinarySearch(target: T, lo: Int, hi: Int): Int { + if (hi < lo) return -1 + val guess = (hi + lo) / 2 - return if (this[guess] > target) - binarySearch(target, lo, guess - 1) - else if (this[guess] < target) - binarySearch(target, guess + 1, hi) - else - guess + + return if (this[guess] > target) recursiveBinarySearch(target, lo, guess - 1) + else if (this[guess] < target) recursiveBinarySearch(target, guess + 1, hi) + else guess } fun main(args: Array) { - val a = intArrayOf(1, 3, 4, 5, 6, 7, 8, 9, 10) - var t = 6 // target - var r = a.binarySearch(t) - println(if (r < 0) "$t not found" else "$t found at index $r") - t = 250 - r = a.binarySearch(t) - println(if (r < 0) "$t not found" else "$t found at index $r") + val a = arrayOf(1, 3, 4, 5, 6, 7, 8, 9, 10) + var target = 6 + var r = a.iterativeBinarySearch(target) + println(if (r < 0) "$target not found" else "$target found at index $r") + target = 250 + r = a.iterativeBinarySearch(target) + println(if (r < 0) "$target not found" else "$target found at index $r") - t = 6 - r = a.binarySearch(t, 0, a.size) - println(if (r < 0) "$t not found" else "$t found at index $r") - t = 250 - r = a.binarySearch(t, 0, a.size) - println(if (r < 0) "$t not found" else "$t found at index $r") + target = 6 + r = a.recursiveBinarySearch(target, 0, a.size) + println(if (r < 0) "$target not found" else "$target found at index $r") + target = 250 + r = a.recursiveBinarySearch(target, 0, a.size) + println(if (r < 0) "$target not found" else "$target found at index $r") } diff --git a/Task/Binary-search/Lambdatalk/binary-search.lambdatalk b/Task/Binary-search/Lambdatalk/binary-search.lambdatalk new file mode 100644 index 0000000000..35868bd018 --- /dev/null +++ b/Task/Binary-search/Lambdatalk/binary-search.lambdatalk @@ -0,0 +1,28 @@ +{def BS + {def BS.r {lambda {:a :v :i0 :i1} + {let { {:a :a} {:v :v} {:i0 :i0} {:i1 :i1} + {:m {floor {* {+ :i0 :i1} 0.5}}} } + {if {< :i1 :i0} + then :v is not found + else {if {> {array.item :a :m} :v} + then {BS.r :a :v :i0 {- :m 1} } + else {if {< {array.item :a :m} :v} + then {BS.r :a :v {+ :m 1} :i1 } + else :v is at array[:m] }}}}} } + {lambda {:a :v} + {BS.r :a :v 0 {- {array.length :a} 1}} }} +-> BS + +{def A {array 12 14 16 18 20 22 25 27 30}} +-> A = [12,14,16,18,20,22,25,27,30] + +{BS {A} -1} -> -1 is not found +{BS {A} 24} -> 24 is not found +{BS {A} 25} -> 25 is at array[6] +{BS {A} 123} -> 123 is not found + +{def B {array {serie 1 100000 2}}} +-> B = [1,3,5,... 99997,99999] + +{BS {B} 100} -> 100 is not found +{BS {B} 12345} -> 12345 is at array[6172] diff --git a/Task/Binary-search/OoRexx/binary-search.rexx b/Task/Binary-search/OoRexx/binary-search.rexx new file mode 100644 index 0000000000..c284479f5d --- /dev/null +++ b/Task/Binary-search/OoRexx/binary-search.rexx @@ -0,0 +1,52 @@ +data = .array~of(1, 3, 5, 7, 9, 11) +-- search keys with a number of edge cases +searchkeys = .array~of(0, 1, 4, 7, 11, 12) +say "recursive binary search" +loop key over searchkeys + pos = recursiveBinarySearch(data, key) + if pos == 0 then say "Key" key "not found" + else say "Key" key "found at postion" pos +end +say +say "iterative binary search" +loop key over searchkeys + pos = iterativeBinarySearch(data, key) + if pos == 0 then say "Key" key "not found" + else say "Key" key "found at postion" pos +end + +::routine recursiveBinarySearch + -- NB: Rexx arrays are 1-based + use strict arg data, value, low = 1, high = (data~items) + + -- make sure we don't go beyond the bounds + high = min(high, data~items) + -- zero indicates not found + if high < low then return 0 + + mid = (low + high) % 2 + if data[mid] > value then + return recursiveBinarySearch(data, value, low, mid - 1) + else if data[mid] < value then + return recursiveBinarySearch(data, value, mid + 1, high) + -- got it! + return mid + +::routine iterativeBinarySearch + -- NB: Rexx arrays are 1-based + use strict arg data, value, low = 1, high = (data~items) + + -- make sure we don't go beyond the bounds + high = min(high, data~items) + -- zero indicates not found + if high < low then return 0 + loop while low <= high + mid = (low + high) % 2 + if data[mid] > value then + high = mid - 1 + else if data[mid] < value then + low = mid + 1 + else + return mid + end + return 0 diff --git a/Task/Binary-search/Phix/binary-search-1.phix b/Task/Binary-search/Phix/binary-search-1.phix index 6c8719c37a..2e188b0850 100644 --- a/Task/Binary-search/Phix/binary-search-1.phix +++ b/Task/Binary-search/Phix/binary-search-1.phix @@ -1,16 +1,20 @@ -function binary_search(sequence s, object val, integer low, integer high) - integer mid, cmp - if high < low then - return 0 -- not found - else - mid = floor( (low + high) / 2 ) - cmp = compare(s[mid], val) - if cmp > 0 then - return binary_search(s, val, low, mid-1) - elsif cmp < 0 then - return binary_search(s, val, mid+1, high) +global function binary_search(object needle, sequence haystack) +integer lo = 1, + hi = length(haystack), + mid = lo, + c = 0 + + while lo<=hi do + mid = floor((lo+hi)/2) + c = compare(needle, haystack[mid]) + if c<0 then + hi = mid-1 + elsif c>0 then + lo = mid+1 else - return mid + return mid -- found! end if - end if + end while + mid += c>0 + return -mid -- where it would go, if inserted now end function diff --git a/Task/Binary-search/Phix/binary-search-2.phix b/Task/Binary-search/Phix/binary-search-2.phix index 4ffa8d6cb3..a591005c3e 100644 --- a/Task/Binary-search/Phix/binary-search-2.phix +++ b/Task/Binary-search/Phix/binary-search-2.phix @@ -1,17 +1,7 @@ -function binary_search(sequence s, object val) - integer low, high, mid, cmp - low = 1 - high = length(s) - while low <= high do - mid = floor( (low + high) / 2 ) - cmp = compare(s[mid], val) - if cmp > 0 then - high = mid - 1 - elsif cmp < 0 then - low = mid + 1 - else - return mid - end if - end while - return 0 -- not found -end function +?binary_search(0,{1,3,5}) -- -1 +?binary_search(1,{1,3,5}) -- 1 +?binary_search(2,{1,3,5}) -- -2 +?binary_search(3,{1,3,5}) -- 2 +?binary_search(4,{1,3,5}) -- -3 +?binary_search(5,{1,3,5}) -- 3 +?binary_search(6,{1,3,5}) -- -4 diff --git a/Task/Binary-search/PowerShell/binary-search-1.psh b/Task/Binary-search/PowerShell/binary-search-1.psh new file mode 100644 index 0000000000..1e97404d8f --- /dev/null +++ b/Task/Binary-search/PowerShell/binary-search-1.psh @@ -0,0 +1,66 @@ +function BinarySearch-Iterative ([int[]]$Array, [int]$Value) +{ + [int]$low = 0 + [int]$high = $Array.Count - 1 + + while ($low -le $high) + { + [int]$mid = ($low + $high) / 2 + + if ($Array[$mid] -gt $Value) + { + $high = $mid - 1 + } + elseif ($Array[$mid] -lt $Value) + { + $low = $mid + 1 + } + else + { + return $mid + } + } + + return -1 +} + +function BinarySearch-Recursive ([int[]]$Array, [int]$Value, [int]$Low = 0, [int]$High = $Array.Count) +{ + if ($High -lt $Low) + { + return -1 + } + + [int]$mid = ($Low + $High) / 2 + + if ($Array[$mid] -gt $Value) + { + return BinarySearch $Array $Value $Low ($mid - 1) + } + elseif ($Array[$mid] -lt $Value) + { + return BinarySearch $Array $Value ($mid + 1) $High + } + else + { + return $mid + } +} + +function Show-SearchResult ([int[]]$Array, [int]$Search, [ValidateSet("Iterative", "Recursive")][string]$Function) +{ + switch ($Function) + { + "Iterative" {$index = BinarySearch-Iterative -Array $Array -Value $Search} + "Recursive" {$index = BinarySearch-Recursive -Array $Array -Value $Search} + } + + if ($index -ge 0) + { + Write-Host ("Using BinarySearch-{0}: {1} is at index {2}" -f $Function, $numbers[$index], $index) + } + else + { + Write-Host ("Using BinarySearch-{0}: {1} not found" -f $Function, $Search) -ForegroundColor Red + } +} diff --git a/Task/Binary-search/PowerShell/binary-search-2.psh b/Task/Binary-search/PowerShell/binary-search-2.psh new file mode 100644 index 0000000000..3b44875c6c --- /dev/null +++ b/Task/Binary-search/PowerShell/binary-search-2.psh @@ -0,0 +1,4 @@ +Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 41 -Function Iterative +Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 99 -Function Iterative +Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 86 -Function Recursive +Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 11 -Function Recursive diff --git a/Task/Binary-search/Scala/binary-search-2.scala b/Task/Binary-search/Scala/binary-search-2.scala index feee19e5b8..fc20a952b6 100644 --- a/Task/Binary-search/Scala/binary-search-2.scala +++ b/Task/Binary-search/Scala/binary-search-2.scala @@ -1,10 +1,12 @@ -def binarySearch[A <% Ordered[A]](xs: Seq[A], x: A): Option[Int] = { - var (low, high) = (0, xs.size - 1) - while (low <= high) - (low + high) / 2 match { - case mid if xs(mid) > x => high = mid - 1 - case mid if xs(mid) < x => low = mid + 1 - case mid => return Some(mid) - } - None -} +def binarySearch[T](xs: Seq[T], x: T)(implicit ordering: Ordering[T]): Option[Int] = { + var low: Int = 0 + var high: Int = xs.size - 1 + + while (low <= high) + low + high >>> 1 match { + case guess if ordering.gt(xs(guess), x) => high = guess - 1 //too high + case guess if ordering.lt(xs(guess), x) => low = guess + 1 // too low + case guess => return Some(guess) //found it + } + None //not found + } diff --git a/Task/Binary-search/Sidef/binary-search-1.sidef b/Task/Binary-search/Sidef/binary-search-1.sidef index 3d61581f48..d75d34972f 100644 --- a/Task/Binary-search/Sidef/binary-search-1.sidef +++ b/Task/Binary-search/Sidef/binary-search-1.sidef @@ -1,14 +1,14 @@ func binary_search(a, i) { - var l = 0; - var h = a.end; + var l = 0 + var h = a.end while (l <= h) { - var mid = (h+l / 2 -> int); - a[mid] > i && (h = mid-1; next); - a[mid] < i && (l = mid+1; next); - return mid; + var mid = (h+l / 2 -> int) + a[mid] > i && (h = mid-1; next) + a[mid] < i && (l = mid+1; next) + return mid } - return -1; + return -1 } diff --git a/Task/Binary-search/Sidef/binary-search-2.sidef b/Task/Binary-search/Sidef/binary-search-2.sidef index b85b85becc..b2a33e4ee1 100644 --- a/Task/Binary-search/Sidef/binary-search-2.sidef +++ b/Task/Binary-search/Sidef/binary-search-2.sidef @@ -1,13 +1,16 @@ func binary_search(arr, value, low=0, high=arr.end) { - high < low && return -1; - var middle = (high+low / 2 -> int); + high < low && return -1 + var middle = ((high+low) // 2) - if (value < arr[middle]) { - return binary_search(arr, value, low, middle-1); + given (arr[middle]) { |item| + case (value < item) { + binary_search(arr, value, low, middle-1) + } + case (value > item) { + binary_search(arr, value, middle+1, high) + } + case (value == item) { + middle + } } - elsif (value > arr[middle]) { - return binary_search(arr, value, middle+1, high); - } - - return middle; } diff --git a/Task/Binary-search/Zkl/binary-search-1.zkl b/Task/Binary-search/Zkl/binary-search-1.zkl new file mode 100644 index 0000000000..fed96a333f --- /dev/null +++ b/Task/Binary-search/Zkl/binary-search-1.zkl @@ -0,0 +1,9 @@ +fcn bsearch(list,value){ // list is sorted + fcn(list,value, low,high){ + if (high < low) return(Void); // not found + mid:=(low + high) / 2; + if (list[mid] > value) return(self.fcn(list,value, low, mid-1)); + if (list[mid] < value) return(self.fcn(list,value, mid+1, high)); + return(mid); // found + }(list,value,0,list.len()-1); +} diff --git a/Task/Binary-search/Zkl/binary-search-2.zkl b/Task/Binary-search/Zkl/binary-search-2.zkl new file mode 100644 index 0000000000..0220242db2 --- /dev/null +++ b/Task/Binary-search/Zkl/binary-search-2.zkl @@ -0,0 +1,6 @@ +list:=T(1,3,5,7,9,11); println("Sorted values: ",list); +foreach i in ([0..12]){ + n:=bsearch(list,i); + if (Void==n) println("Not found: ",i); + else println("found ",i," at index ",n); +} diff --git a/Task/Binary-strings/Elixir/binary-strings.elixir b/Task/Binary-strings/Elixir/binary-strings.elixir new file mode 100644 index 0000000000..17eac9cc1b --- /dev/null +++ b/Task/Binary-strings/Elixir/binary-strings.elixir @@ -0,0 +1,55 @@ +# String creation +x = "hello world" + +# String destruction +x = nil + +# String assignment with a null byte +x = "a\0b" +IO.inspect x #=> <<97, 0, 98>> +IO.puts String.length(x) #=> 3 + +# string comparison +if x == "hello" do + IO.puts "equal" +else + IO.puts "not equal" #=> not equal +end +y = "bc" +if x < y do + IO.puts "#{x} is lexicographically less than #{y}" #=> a b is lexicographically less than bc +end + +# string cloning +xx = x +IO.puts x == xx #=> true (same length and content) + +# check if empty +if x=="" do + IO.puts "is empty" +end +if String.length(x)==0 do + IO.puts "is empty" +end + +# append a byte +IO.puts x <> "\07" #=> a b 7 +IO.inspect x <> "\07" #=> <<97, 0, 98, 0, 55>> + +# substring +IO.puts String.slice("elixir", 1..3) #=> lix +IO.puts String.slice("elixir", 2, 3) #=> ixi + +# replace bytes +IO.puts String.replace("a,b,c", ",", "-") #=> a-b-c + +# string interpolation +a = "abc" +n = 100 +IO.puts "#{a} : #{n}" #=> abc : 100 + +# join strings +a = "hel" +b = "lo w" +c = "orld" +IO.puts a <> b <> c #=> hello world diff --git a/Task/Binary-strings/jq/binary-strings-1.jq b/Task/Binary-strings/Jq/binary-strings-1.jq similarity index 100% rename from Task/Binary-strings/jq/binary-strings-1.jq rename to Task/Binary-strings/Jq/binary-strings-1.jq diff --git a/Task/Binary-strings/jq/binary-strings-2.jq b/Task/Binary-strings/Jq/binary-strings-2.jq similarity index 100% rename from Task/Binary-strings/jq/binary-strings-2.jq rename to Task/Binary-strings/Jq/binary-strings-2.jq diff --git a/Task/Binary-strings/Kotlin/binary-strings.kotlin b/Task/Binary-strings/Kotlin/binary-strings.kotlin new file mode 100644 index 0000000000..17ce110dd1 --- /dev/null +++ b/Task/Binary-strings/Kotlin/binary-strings.kotlin @@ -0,0 +1,90 @@ +class ByteString(private val bytes: ByteArray) : Comparable { + val length get() = bytes.size + + fun isEmpty() = bytes.isEmpty() + + operator fun plus(other: ByteString): ByteString = ByteString(bytes + other.bytes) + + operator fun plus(byte: Byte) = ByteString(bytes + byte) + + operator fun get(index: Int): Byte { + require (index in 0 until length) + return bytes[index] + } + + fun toByteArray() = bytes + + fun copy() = ByteString(bytes.copyOf()) + + override fun compareTo(other: ByteString) = this.toString().compareTo(other.toString()) + + override fun equals(other: Any?): Boolean { + if (other == null || other !is ByteString) return false + return compareTo(other) == 0 + } + + override fun hashCode() = this.toString().hashCode() + + fun substring(startIndex: Int) = ByteString(bytes.sliceArray(startIndex until length)) + + fun substring(startIndex: Int, endIndex: Int) = + ByteString(bytes.sliceArray(startIndex until endIndex)) + + fun replace(oldByte: Byte, newByte: Byte): ByteString { + val ba = ByteArray(length) { if (bytes[it] == oldByte) newByte else bytes[it] } + return ByteString(ba) + } + + fun replace(oldValue: ByteString, newValue: ByteString) = + this.toString().replace(oldValue.toString(), newValue.toString()).toByteString() + + override fun toString(): String { + val chars = CharArray(length) + for (i in 0 until length) { + chars[i] = when (bytes[i]) { + in 0..127 -> bytes[i].toChar() + else -> (256 + bytes[i]).toChar() + } + } + return chars.joinToString("") + } +} + +fun String.toByteString(): ByteString { + val bytes = ByteArray(this.length) + for (i in 0 until this.length) { + bytes[i] = when (this[i].toInt()) { + in 0..127 -> this[i].toByte() + in 128..255 -> (this[i] - 256).toByte() + else -> '?'.toByte() // say + } + } + return ByteString(bytes) +} + +/* property to be used as an abbreviation for String.toByteString() */ +val String.bs get() = this.toByteString() + +fun main(args: Array) { + val ba = byteArrayOf(65, 66, 67) + val ba2 = byteArrayOf(68, 69, 70) + val bs = ByteString(ba) + val bs2 = ByteString(ba2) + val bs3 = bs + bs2 + val bs4 = "GHI£€".toByteString() + println("The length of $bs is ${bs.length}") + println("$bs + $bs2 = $bs3") + println("$bs + D = ${bs + 68}") + println("$bs == ABC is ${bs == bs.copy()}") + println("$bs != ABC is ${bs != bs.copy()}") + println("$bs >= $bs2 is ${bs > bs2}") + println("$bs <= $bs2 is ${bs < bs2}") + println("$bs is ${if (bs.isEmpty()) "empty" else "not empty"}") + println("ABC[1] = ${bs[1].toChar()}") + println("ABC as a byte array is ${bs.toByteArray().contentToString()}") + println("ABCDEF(1..5) = ${bs3.substring(1)}") + println("ABCDEF(2..4) = ${bs3.substring(2,5)}") + println("ABCDEF with C replaced by G is ${bs3.replace(67, 71)}") + println("ABCDEF with CD replaced by GH is ${bs3.replace("CD".bs, "GH".bs)}") + println("GHI£€ as a ByteString is $bs4") +} diff --git a/Task/Binary-strings/Perl-6/binary-strings.pl6 b/Task/Binary-strings/Perl-6/binary-strings.pl6 index 3fee0cf4c9..f0170d1a94 100644 --- a/Task/Binary-strings/Perl-6/binary-strings.pl6 +++ b/Task/Binary-strings/Perl-6/binary-strings.pl6 @@ -1,5 +1,4 @@ # Perl 6 is perfectly fine with NUL *characters* in strings: - my Str $s = 'nema' ~ 0.chr ~ 'problema!'; say $s; @@ -10,9 +9,9 @@ my Str $str = "My God, it's full of chars!"; my Buf $buf = Buf.new(255, 0, 1, 2, 3); say $buf; -# Strs can be encoded into Bufs … -my Buf $this = 'foo'.encode('ascii'); -# … and Bufs can be decoded into Strs … +# Strs can be encoded into Blobs … +my Blob $this = 'round-trip'.encode('ascii'); +# … and Blobs can be decoded into Strs … my Str $that = $this.decode('ascii'); # So it's all there. Nevertheless, let's solve this task explicitly @@ -23,7 +22,7 @@ class ByteStr { # … that keeps an array of bytes, and we delegate some # straight-forward stuff directly to this attribute: # (Note: "has byte @.bytes" would be nicer, but that is - # not yet implemented in rakudo or niecza.) + # not yet implemented in Rakudo.) has Int @.bytes handles(< Bool elems gist push >); # A handful of methods … @@ -43,11 +42,11 @@ class ByteStr { # A couple of operators for our new type: multi infix:(ByteStr $x, ByteStr $y) { $x.bytes cmp $y.bytes } -multi infix:<~> (ByteStr $x, ByteStr $y) { ByteStr.new(:bytes($x.bytes, $y.bytes)) } +multi infix:<~> (ByteStr $x, ByteStr $y) { ByteStr.new(:bytes(|$x.bytes, |$y.bytes)) } # create some byte strings (destruction not needed due to garbage collection) my ByteStr $b0 = ByteStr.new; -my ByteStr $b1 = ByteStr.new(:bytes( 'foo'.ords, 0, 10, 'bar'.ords )); +my ByteStr $b1 = ByteStr.new(:bytes( |'foo'.ords, 0, 10, |'bar'.ords )); # assignment ($b1 and $b2 contain the same ByteStr object afterwards): my ByteStr $b2 = $b1; @@ -69,14 +68,15 @@ say 'b1 is ', $b1 ?? 'not empty' !! 'empty'; # appending a byte: $b1.push: 123; +say 'appended = ', $b1; # extracting a substring: my $sub = $b1.substr(2, 4); -say 'sub = ', $sub; +say 'substr = ', $sub; # replacing a byte: $b2.replace(102 => 103); -say $b2; +say 'replaced = ', $b2; # joining: my ByteStr $b3 = $b1 ~ $sub; diff --git a/Task/Binary-strings/Zkl/binary-strings.zkl b/Task/Binary-strings/Zkl/binary-strings.zkl new file mode 100644 index 0000000000..8137fb8cb5 --- /dev/null +++ b/Task/Binary-strings/Zkl/binary-strings.zkl @@ -0,0 +1,21 @@ +Data(0,.Int,1,2,3) // bytes +Data(0,String,1,2,3) // same +Data(0,Int,"foo","bar") //-->foobar\0 +d:=Data(0,String,"foo","bar") //-->foo\0bar\0\0 +d==d // -->True: byte by byte comparison +d.copy() //-->clone +d.len() //-->8, 0 if empty + +d.append("1").len(); //-->10 // or d+"1" +Data(0,Int,"foo","bar").len() //-->6 +Data(0,Int,"foo","bar").append("1").len() //-->7 + +d.readString(4) //-->"bar" +d.readNthString(2) //-->"1" +d[2,4] //-->"o", really "o\0ba" but String sees the null + +while(Void!=(n:=d.findString("bar"))){ d[n,4]="hoho" } +d.bytes() //-->L(102,111,111,0,104,111,104,111,0,49,0) + +d2:=Data(0,Int,"sam"); +d.append(d2).text // or d+d2 diff --git a/Task/Bitcoin-address-validation/Factor/bitcoin-address-validation.factor b/Task/Bitcoin-address-validation/Factor/bitcoin-address-validation.factor new file mode 100644 index 0000000000..2b0498e371 --- /dev/null +++ b/Task/Bitcoin-address-validation/Factor/bitcoin-address-validation.factor @@ -0,0 +1,16 @@ +USING: byte-arrays checksums checksums.sha io.binary kernel math +math.parser sequences ; +IN: rosetta-code.bitcoin.validation + +CONSTANT: ALPHABET "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + +: base58>bigint ( str -- n ) + [ ALPHABET index ] + [ [ 58 * ] [ + ] bi* ] map-reduce ; + +: base58> ( str -- bytes ) base58>bigint 25 >be ; + +: btc-checksum ( bytes -- checksum-bytes ) + 21 head 2 [ sha-256 checksum-bytes ] times 4 head ; + +: btc-valid? ( str -- ? ) base58> [ btc-checksum ] [ 4 tail* ] bi = ; diff --git a/Task/Bitcoin-address-validation/FreeBASIC/bitcoin-address-validation.freebasic b/Task/Bitcoin-address-validation/FreeBASIC/bitcoin-address-validation.freebasic new file mode 100644 index 0000000000..24bc3ce9c0 --- /dev/null +++ b/Task/Bitcoin-address-validation/FreeBASIC/bitcoin-address-validation.freebasic @@ -0,0 +1,206 @@ +' version 05-04-2017 +' compile with: fbc -s console + +' function adapted from the SHA-256 task +Function SHA_256(test_str As String, bitcoin As ULong = 0) As String + + #Macro Ch (x, y, z) + (((x) And (y)) Xor ((Not (x)) And z)) + #EndMacro + + #Macro Maj (x, y, z) + (((x) And (y)) Xor ((x) And (z)) Xor ((y) And (z))) + #EndMacro + + #Macro sigma0 (x) + (((x) Shr 2 Or (x) Shl 30) Xor ((x) Shr 13 Or (x) Shl 19) Xor ((x) Shr 22 Or (x) Shl 10)) + #EndMacro + + #Macro sigma1 (x) + (((x) Shr 6 Or (x) Shl 26) Xor ((x) Shr 11 Or (x) Shl 21) Xor ((x) Shr 25 Or (x) Shl 7)) + #EndMacro + + #Macro sigma2 (x) + (((x) Shr 7 Or (x) Shl 25) Xor ((x) Shr 18 Or (x) Shl 14) Xor ((x) Shr 3)) + #EndMacro + + #Macro sigma3 (x) + (((x) Shr 17 Or (x) Shl 15) Xor ((x) Shr 19 Or (x) Shl 13) Xor ((x) Shr 10)) + #EndMacro + + Dim As String message = test_str ' strings are passed as ByRef's + + Dim As Long i, j + Dim As UByte Ptr ww1 + Dim As UInteger<32> Ptr ww4 + + Do + Dim As ULongInt l = Len(message) + ' set the first bit after the message to 1 + message = message + Chr(1 Shl 7) + ' add one char to the length + Dim As ULong padding = 64 - ((l +1) Mod (512 \ 8)) ' 512 \ 8 = 64 char. + + ' check if we have enough room for inserting the length + If padding < 8 Then padding = padding + 64 + + message = message + String(padding, Chr(0)) ' adjust length + Dim As ULong l1 = Len(message) ' new length + + l = l * 8 ' orignal length in bits + ' create ubyte ptr to point to l ( = length in bits) + Dim As UByte Ptr ub_ptr = Cast(UByte Ptr, @l) + + For i = 0 To 7 'copy length of message to the last 8 bytes + message[l1 -1 - i] = ub_ptr[i] + Next + + 'table of constants + Dim As UInteger<32> K(0 To ...) = _ + { &H428a2f98, &H71374491, &Hb5c0fbcf, &He9b5dba5, &H3956c25b, &H59f111f1, _ + &H923f82a4, &Hab1c5ed5, &Hd807aa98, &H12835b01, &H243185be, &H550c7dc3, _ + &H72be5d74, &H80deb1fe, &H9bdc06a7, &Hc19bf174, &He49b69c1, &Hefbe4786, _ + &H0fc19dc6, &H240ca1cc, &H2de92c6f, &H4a7484aa, &H5cb0a9dc, &H76f988da, _ + &H983e5152, &Ha831c66d, &Hb00327c8, &Hbf597fc7, &Hc6e00bf3, &Hd5a79147, _ + &H06ca6351, &H14292967, &H27b70a85, &H2e1b2138, &H4d2c6dfc, &H53380d13, _ + &H650a7354, &H766a0abb, &H81c2c92e, &H92722c85, &Ha2bfe8a1, &Ha81a664b, _ + &Hc24b8b70, &Hc76c51a3, &Hd192e819, &Hd6990624, &Hf40e3585, &H106aa070, _ + &H19a4c116, &H1e376c08, &H2748774c, &H34b0bcb5, &H391c0cb3, &H4ed8aa4a, _ + &H5b9cca4f, &H682e6ff3, &H748f82ee, &H78a5636f, &H84c87814, &H8cc70208, _ + &H90befffa, &Ha4506ceb, &Hbef9a3f7, &Hc67178f2 } + + Dim As UInteger<32> h0 = &H6a09e667 + Dim As UInteger<32> h1 = &Hbb67ae85 + Dim As UInteger<32> h2 = &H3c6ef372 + Dim As UInteger<32> h3 = &Ha54ff53a + Dim As UInteger<32> h4 = &H510e527f + Dim As UInteger<32> h5 = &H9b05688c + Dim As UInteger<32> h6 = &H1f83d9ab + Dim As UInteger<32> h7 = &H5be0cd19 + Dim As UInteger<32> a, b, c, d, e, f, g, h + Dim As UInteger<32> t1, t2, w(0 To 63) + + For j = 0 To (l1 -1) \ 64 ' split into block of 64 bytes + ww1 = Cast(UByte Ptr, @message[j * 64]) + ww4 = Cast(UInteger<32> Ptr, @message[j * 64]) + + For i = 0 To 60 Step 4 'little endian -> big endian + Swap ww1[i ], ww1[i +3] + Swap ww1[i +1], ww1[i +2] + Next + + For i = 0 To 15 ' copy the 16 32bit block into the array + W(i) = ww4[i] + Next + + For i = 16 To 63 ' fill the rest of the array + w(i) = sigma3(W(i -2)) + W(i -7) + sigma2(W(i -15)) + W(i -16) + Next + + a = h0 : b = h1 : c = h2 : d = h3 : e = h4 : f = h5 : g = h6 : h = h7 + + For i = 0 To 63 + t1 = h + sigma1(e) + Ch(e, f, g) + K(i) + W(i) + t2 = sigma0(a) + Maj(a, b, c) + h = g : g = f : f = e + e = d + t1 + d = c : c = b : b = a + a = t1 + t2 + Next + + h0 += a : h1 += b : h2 += c : h3 += d + h4 += e : h5 += f : h6 += g : h7 += h + + Next j + + Dim As String answer = Hex(h0, 8) + Hex(h1, 8) + Hex(h2, 8) + Hex(h3, 8) _ + + Hex(h4, 8) + Hex(h5, 8) + Hex(h6, 8) + Hex(h7, 8) + + If bitcoin = 0 Then + Return LCase(answer) + Else 'conver hex value's to integer value's + message = String(32,0) + For i = 0 To 31 + message[i] = Val("&h" + Mid(answer, i * 2 + 1, 2)) + Next + bitcoin = 0 + End If + + Loop + +End Function + +Function conv_base58(bitcoin_address As String) As String + + Dim As String base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + Dim As String tmp = String(24, 0) + Dim As Long x, y, z + + For x = 1 To Len(bitcoin_address) -1 + z = InStr(base58, Chr(bitcoin_address[x])) -1 + If z = -1 Then + Print " bitcoin address contains illegal character" + Return "" + End If + For y = 23 To 0 Step -1 + z = z + tmp[y] * 58 + tmp[y] = z And 255 ' test_str[y] = z Mod 256 + z Shr= 8 ' z \= 256 + Next + If z <> 0 Then + Print " bitcoin address is to long" + Return "" + End If + Next + + z = InStr(base58, Chr(bitcoin_address[0])) -1 + Return Chr(z) + tmp + +End Function + +' ------=< MAIN >=------ + +Data "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" ' original +Data "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j" ' checksum changed +Data "1NAGa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" ' address changed +Data "0AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" ' only 1 or 3 as first char. allowed +Data "1AGNa15ZQXAZUgFlqJ2i7Z2DPU2J6hW62i" ' illegal character in address + +Dim As String tmp, result, checksum, bitcoin_address +Dim As Long i, j + +For i = 1 To 5 + + Read bitcoin_address + Print "Bitcoin address: "; bitcoin_address; + tmp = Left(bitcoin_address,1) + + If tmp <> "1" And tmp <> "3" Then + Print " first character is not 1 or 3" + Continue For + End If + + ' convert bitcoinaddress + tmp = conv_base58(bitcoin_address) + If tmp = "" Then Continue For + ' get the checksum, last 4 digits + For j As Long = 21 To 24 + checksum = checksum + LCase(Hex(tmp[j], 2)) + Next + + ' send the first 21 characters to the SHA 256 routine + result = SHA_256(Left(tmp, 21), 2) + result = Left(result, 8) ' get the checksum (the first 8 digits (hex)) + If checksum = result Then ' test the found checksum against + Print " is valid" ' the one from the address + Else + Print " is not valid, checksum fails" + End If + +Next + +' empty keyboard buffer +While InKey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Bitcoin-address-validation/Haskell/bitcoin-address-validation.hs b/Task/Bitcoin-address-validation/Haskell/bitcoin-address-validation.hs index 594a4d519f..ae360d10e9 100644 --- a/Task/Bitcoin-address-validation/Haskell/bitcoin-address-validation.hs +++ b/Task/Bitcoin-address-validation/Haskell/bitcoin-address-validation.hs @@ -22,7 +22,7 @@ validityCheck encodedAddress = Just ev -> let address = toBytes ev addressLength = length address - in if addressLength > 24 + in if addressLength > 25 then Left "Address length exceeds 25 bytes" else if addressLength < 4 diff --git a/Task/Bitcoin-address-validation/Java/bitcoin-address-validation.java b/Task/Bitcoin-address-validation/Java/bitcoin-address-validation.java index 2c9ad37557..90525a5f31 100644 --- a/Task/Bitcoin-address-validation/Java/bitcoin-address-validation.java +++ b/Task/Bitcoin-address-validation/Java/bitcoin-address-validation.java @@ -1,63 +1,71 @@ -private final static String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; -public static void main(String[] args) { - Assert("Test 01", ValidateBitcoinAddress("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i"), true); - Assert("Test 02", ValidateBitcoinAddress("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j"), false); - Assert("Test 03", ValidateBitcoinAddress("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9"), true); - Assert("Test 04", ValidateBitcoinAddress("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X"), false); - Assert("Test 05", ValidateBitcoinAddress("1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i"), false); - Assert("Test 06", ValidateBitcoinAddress("1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i"), false); - Assert("Test 07", ValidateBitcoinAddress("BZbvjr"), false); - Assert("Test 08", ValidateBitcoinAddress("i55j"), false); - Assert("Test 09", ValidateBitcoinAddress("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!"), false); - Assert("Test 10", ValidateBitcoinAddress("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz"), false); - Assert("Test 11", ValidateBitcoinAddress("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz"), false); - Assert("Test 12", ValidateBitcoinAddress("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9"), false); - Assert("Test 13", ValidateBitcoinAddress("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I"), false); -} +public class BitcoinAddressValidator { -public static boolean ValidateBitcoinAddress(String addr) { - if (addr.length() < 26 || addr.length() > 35) return false; - byte[] decoded = DecodeBase58(addr, 58, 25); - if (decoded == null) return false; + private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; - byte[] hash = Sha256(decoded, 0, 21, 2); + public static boolean validateBitcoinAddress(String addr) { + if (addr.length() < 26 || addr.length() > 35) + return false; + byte[] decoded = decodeBase58(addr, 25); + if (decoded == null) + return false; - return Arrays.equals(Arrays.copyOfRange(hash, 0, 4), Arrays.copyOfRange(decoded, 21, 25)); -} + byte[] hash1 = sha256(Arrays.copyOfRange(decoded, 0, 21)); + byte[] hash2 = sha256(hash1); -private static byte[] DecodeBase58(String input, int base, int len) { - byte[] output = new byte[len]; - for (int i = 0; i < input.length(); i++) { - char t = input.charAt(i); + return Arrays.equals(Arrays.copyOfRange(hash2, 0, 4), Arrays.copyOfRange(decoded, 21, 25)); + } - int p = ALPHABET.indexOf(t); - if (p == -1) return null; - for (int j = len - 1; j > 0; j--, p /= 256) { - p += base * (output[j] & 0xFF); - output[j] = (byte) (p % 256); + private static byte[] decodeBase58(String input, int len) { + byte[] output = new byte[len]; + for (char t : input.toCharArray()) { + int p = ALPHABET.indexOf(t); + if (p == -1) + return null; + for (int j = len - 1; j >= 0; j--) { + p += 58 * (output[j] & 0xFF); + output[j] = (byte) (p % 256); + p /= 256; + } + if (p != 0) + return null; } - if (p != 0) return null; + + return output; } - return output; -} + private static byte[] sha256(byte[] data) { + try { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(data); + return md.digest(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } -private static byte[] Sha256(byte[] data, int start, int len, int recursion) { - if (recursion == 0) return data; + public static void main(String[] args) { + assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", true); + assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j", false); + assertBitcoin("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", true); + assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X", false); + assertBitcoin("1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", false); + assertBitcoin("1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", false); + assertBitcoin("BZbvjr", false); + assertBitcoin("i55j", false); + assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!", false); + assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz", false); + assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz", false); + assertBitcoin("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9", false); + assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I", false); + } - try { - MessageDigest md = MessageDigest.getInstance("SHA-256"); - md.update(Arrays.copyOfRange(data, start, start + len)); - return Sha256(md.digest(), 0, 32, recursion - 1); - } catch (NoSuchAlgorithmException e) { - return null; + private static void assertBitcoin(String address, boolean expected) { + boolean actual = validateBitcoinAddress(address); + if (actual != expected) + throw new AssertionError(String.format("Expected %s for %s, but got %s.", expected, address, actual)); } } - -public static void Assert(String name, boolean value, boolean expected) { - if (value ^ expected) - throw new Error("Test " + name + " failed"); - else - System.out.println(name + " passed"); -} diff --git a/Task/Bitcoin-address-validation/Kotlin/bitcoin-address-validation.kotlin b/Task/Bitcoin-address-validation/Kotlin/bitcoin-address-validation.kotlin new file mode 100644 index 0000000000..4c466060dd --- /dev/null +++ b/Task/Bitcoin-address-validation/Kotlin/bitcoin-address-validation.kotlin @@ -0,0 +1,60 @@ +import java.security.MessageDigest + +object Bitcoin { + private const val ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + + private fun ByteArray.contentEquals(other: ByteArray): Boolean { + if (this.size != other.size) return false + return (0 until this.size).none { this[it] != other[it] } + } + + private fun decodeBase58(input: String): ByteArray? { + val output = ByteArray(25) + for (c in input) { + var p = ALPHABET.indexOf(c) + if (p == -1) return null + for (j in 24 downTo 1) { + p += 58 * (output[j].toInt() and 0xff) + output[j] = (p % 256).toByte() + p = p shr 8 + } + if (p != 0) return null + } + return output + } + + private fun sha256(data: ByteArray, start: Int, len: Int, recursion: Int): ByteArray { + if (recursion == 0) return data + val md = MessageDigest.getInstance("SHA-256") + md.update(data.sliceArray(start until start + len)) + return sha256(md.digest(), 0, 32, recursion - 1) + } + + fun validateAddress(address: String): Boolean { + if (address.length !in 26..35) return false + val decoded = decodeBase58(address) + if (decoded == null) return false + val hash = sha256(decoded, 0, 21, 2) + return hash.sliceArray(0..3).contentEquals(decoded.sliceArray(21..24)) + } +} + +fun main(args: Array) { + val addresses = arrayOf( + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j", + "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X", + "1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", + "1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", + "BZbvjr", + "i55j", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz", + "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I" + ) + for (address in addresses) + println("${address.padEnd(36)} -> ${if (Bitcoin.validateAddress(address)) "valid" else "invalid"}") +} diff --git a/Task/Bitcoin-address-validation/Rust/bitcoin-address-validation.rust b/Task/Bitcoin-address-validation/Rust/bitcoin-address-validation.rust new file mode 100644 index 0000000000..31bc29dcca --- /dev/null +++ b/Task/Bitcoin-address-validation/Rust/bitcoin-address-validation.rust @@ -0,0 +1,54 @@ +extern crate crypto; + +use crypto::digest::Digest; +use crypto::sha2::Sha256; + +const DIGITS58: [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 main() { + println!("{}", validate_address("1AGNa15ZQXAZUgFiqJ3i7Z2DPU2J6hW62i")); + println!("{}", validate_address("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i")); + println!("{}", validate_address("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j")); + println!("{}", validate_address("17NdbrSGoUotzeGCcMMC?nFkEvLymoou9j")); +} + +fn validate_address(address: &str) -> bool { + let decoded = match from_base58(address, 25) { + Ok(x) => x, + Err(_) => return false + }; + if decoded[0] != 0 { + return false; + } + let mut sha = Sha256::new(); + sha.input(&decoded[0..21]); + let mut first_round = vec![0u8; sha.output_bytes()]; + sha.result(&mut first_round); + sha.reset(); + + sha.input(&first_round); + let mut second_round = vec![0u8; sha.output_bytes()]; + sha.result(&mut second_round); + if second_round[0..4] != decoded[21..25] { + return false + } + true +} + +fn from_base58(encoded: &str, size: usize) -> Result, String> { + let mut res: Vec = vec![0; size]; + for base58_value in encoded.chars() { + let mut value: u32 = match DIGITS58 + .iter() + .position(|x| *x == base58_value){ + Some(x) => x as u32, + None => return Err(String::from("Invalid character found in encoded string.")) + }; + for result_index in (0..size).rev() { + value += 58 * res[result_index] as u32; + res[result_index] = (value % 256) as u8; + value /= 256; + } + } + Ok(res) +} diff --git a/Task/Bitcoin-address-validation/Zkl/bitcoin-address-validation-1.zkl b/Task/Bitcoin-address-validation/Zkl/bitcoin-address-validation-1.zkl new file mode 100644 index 0000000000..5846f1040b --- /dev/null +++ b/Task/Bitcoin-address-validation/Zkl/bitcoin-address-validation-1.zkl @@ -0,0 +1,25 @@ +var [const] MsgHash=Import("zklMsgHash"); // SHA-256, etc +const symbols="123456789" // 58 characters: no cap i,o; ell, zero + "ABCDEFGHJKLMNPQRSTUVWXYZ" + "abcdefghijkmnopqrstuvwxyz"; + +fcn unbase58(str){ // --> Data (byte bucket) + out:=Data().fill(0,25); + str.pump(Void,symbols.index,'wrap(n){ // throws on out of range + [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 + },n) : if(_) throw(Exception.ValueError("address too long")); + }); + out; +} + +fcn coinValide(addr){ + reg dec,chkSum; + try{ dec=unbase58(addr) }catch{ return(False) } + chkSum=dec[-4,*]; dec.del(21,*); + // hash then hash the hash --> binary hash (instead of hex string) + (2).reduce(MsgHash.SHA256.fp1(1,dec),dec); // dec is i/o buffer + dec[0,4]==chkSum; +} diff --git a/Task/Bitcoin-address-validation/Zkl/bitcoin-address-validation-2.zkl b/Task/Bitcoin-address-validation/Zkl/bitcoin-address-validation-2.zkl new file mode 100644 index 0000000000..6766aefdf9 --- /dev/null +++ b/Task/Bitcoin-address-validation/Zkl/bitcoin-address-validation-2.zkl @@ -0,0 +1,6 @@ +T("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i","1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X", // checksum changed, original data. + "1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", // data changed, original checksum. + "1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", // invalid chars + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz", // too long +).apply(coinValide).println(); diff --git a/Task/Bitcoin-public-point-to-address/Factor/bitcoin-public-point-to-address.factor b/Task/Bitcoin-public-point-to-address/Factor/bitcoin-public-point-to-address.factor new file mode 100644 index 0000000000..eb127ea38a --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Factor/bitcoin-public-point-to-address.factor @@ -0,0 +1,22 @@ +USING: checksums checksums.ripemd checksums.sha io.binary kernel +math sequences ; +IN: rosetta-code.bitcoin.point-address + +CONSTANT: ALPHABET "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + +: btc-checksum ( bytes -- checksum-bytes ) + 2 [ sha-256 checksum-bytes ] times 4 head ; + +: bigint>base58 ( n -- str ) + 33 [ 58 /mod ALPHABET nth ] "" replicate-as reverse nip ; + +: >base58 ( bytes -- str ) + be> bigint>base58 ; + +: point>address ( X Y -- address ) + [ 32 >be ] bi@ append + 0x4 prefix + sha-256 checksum-bytes + ripemd-160 checksum-bytes + dup 0 prefix btc-checksum + append 0 prefix >base58 ; diff --git a/Task/Bitcoin-public-point-to-address/PicoLisp/bitcoin-public-point-to-address.l b/Task/Bitcoin-public-point-to-address/PicoLisp/bitcoin-public-point-to-address.l new file mode 100644 index 0000000000..4572e43b04 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/PicoLisp/bitcoin-public-point-to-address.l @@ -0,0 +1,39 @@ +(load "ripemd160.l") +(load "sha256.l") + +(setq *B58Alpha + (chop "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") ) +(de hex2L (H) + (make + (for (L (chop H) L (cddr L)) + (link (hex (pack (car L) (cadr L)))) ) ) ) +(de b58enc (Lst) + (let + (P 1 + Z 0 + A + (sum + '((X) + (* X (swap 'P (>> -8 P))) ) + (reverse Lst) ) ) + (for L Lst + (T (n0 L)) + (inc 'Z) ) + (pack + (need Z "1") + (make + (while (gt0 A) + (yoke + (prog1 + (get *B58Alpha (inc (% A 58))) + (setq A (/ A 58)) ) ) ) ) ) ) ) +(de point2address (X Y) + (let L (conc (cons 4) (hex2L X) (hex2L Y)) + (b58enc + (and + (conc (cons 0) (ripemd160 (sha256 L))) + (conc @ (head 4 (sha256 (sha256 @)))) ) ) ) ) +(println + (point2address + "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352" + "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6" ) ) diff --git a/Task/Bitcoin-public-point-to-address/Zkl/bitcoin-public-point-to-address-1.zkl b/Task/Bitcoin-public-point-to-address/Zkl/bitcoin-public-point-to-address-1.zkl new file mode 100644 index 0000000000..6fcd24c409 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Zkl/bitcoin-public-point-to-address-1.zkl @@ -0,0 +1,27 @@ +var [const] MsgHash=Import.lib("zklMsgHash"); // SHA-256, etc + +const symbols = "123456789" // 58 characters: no cap i,o; ell, zero + "ABCDEFGHJKLMNPQRSTUVWXYZ" + "abcdefghijkmnopqrstuvwxyz"; + +fcn base58Encode(bytes){ //Data-->String + bytes=bytes.copy(); sink:=Sink(String); + do(33){ + bytes.len().reduce('wrap(n,idx){ + n=n*256 + bytes[idx]; + bytes[idx]=(n/58); + n%58; + },0) : symbols[_] : sink.write(_) + } + sink.close().reverse(); +} + +const COIN_VER=0; + +fcn coinEncode(x,y){ // throws if x or y not hex or (x+y) not even length + bytes:=(x+y).pump(Data,Void.Read,fcn(a,b){ (a+b).toInt(16) }).insert(0,4); + (MsgHash.SHA256(bytes,1,bytes) : MsgHash.RIPEMD160(_,1,bytes)) + .insert(0,COIN_VER); // we are using bytes for in and out + d,chkSum := Data(), MsgHash.SHA256(bytes,1,d) : MsgHash.SHA256(_,1,d); + base58Encode(bytes.append(chkSum.del(4,*))); // first 4 bytes of hashed hash +} diff --git a/Task/Bitcoin-public-point-to-address/Zkl/bitcoin-public-point-to-address-2.zkl b/Task/Bitcoin-public-point-to-address/Zkl/bitcoin-public-point-to-address-2.zkl new file mode 100644 index 0000000000..1f6dc518e5 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Zkl/bitcoin-public-point-to-address-2.zkl @@ -0,0 +1,4 @@ +e:=coinEncode( + "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352", + "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6"); +(e=="16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM").println(); diff --git a/Task/Bitmap-B-zier-curves-Cubic/Zkl/bitmap-b-zier-curves-cubic-1.zkl b/Task/Bitmap-B-zier-curves-Cubic/Zkl/bitmap-b-zier-curves-cubic-1.zkl new file mode 100644 index 0000000000..329586251a --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Cubic/Zkl/bitmap-b-zier-curves-cubic-1.zkl @@ -0,0 +1,9 @@ + fcn cBezier(p0x,p0y, p1x,p1y, p2x,p2y, p3x,p3y, rgb, numPts=500){ + numPts.pump(Void,'wrap(t){ // B(t) + t=t.toFloat()/numPts; t1:=(1.0 - t); + a:=t1*t1*t1; b:=t*t1*t1*3; c:=t1*t*t*3; d:=t*t*t; + x:=a*p0x + b*p1x + c*p2x + d*p3x + 0.5; + y:=a*p0y + b*p1y + c*p2y + d*p3y + 0.5; + __sSet(rgb,x,y); + }); + } diff --git a/Task/Bitmap-B-zier-curves-Cubic/Zkl/bitmap-b-zier-curves-cubic-2.zkl b/Task/Bitmap-B-zier-curves-Cubic/Zkl/bitmap-b-zier-curves-cubic-2.zkl new file mode 100644 index 0000000000..56e466a3db --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Cubic/Zkl/bitmap-b-zier-curves-cubic-2.zkl @@ -0,0 +1,3 @@ +bitmap:=PPM(200,150,0xff|ff|ff); +bitmap.cBezier(0,149, 30,50, 120,130, 160,30, 0); +bitmap.write(File("foo.ppm","wb")); diff --git a/Task/Bitmap-B-zier-curves-Quadratic/Zkl/bitmap-b-zier-curves-quadratic-1.zkl b/Task/Bitmap-B-zier-curves-Quadratic/Zkl/bitmap-b-zier-curves-quadratic-1.zkl new file mode 100644 index 0000000000..576f4062e1 --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/Zkl/bitmap-b-zier-curves-quadratic-1.zkl @@ -0,0 +1,9 @@ + fcn qBezier(p0x,p0y, p1x,p1y, p2x,p2y, rgb, numPts=500){ + numPts.pump(Void,'wrap(t){ // B(t) + t=t.toFloat()/numPts; t1:=(1.0 - t); + a:=t1*t1; b:=t*t1*2; c:=t*t; + x:=a*p0x + b*p1x + c*p2x + 0.5; + y:=a*p0y + b*p1y + c*p2y + 0.5; + __sSet(rgb,x,y); + }); + } diff --git a/Task/Bitmap-B-zier-curves-Quadratic/Zkl/bitmap-b-zier-curves-quadratic-2.zkl b/Task/Bitmap-B-zier-curves-Quadratic/Zkl/bitmap-b-zier-curves-quadratic-2.zkl new file mode 100644 index 0000000000..ca59cdbc54 --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/Zkl/bitmap-b-zier-curves-quadratic-2.zkl @@ -0,0 +1,3 @@ +bitmap:=PPM(200,200,0xff|ff|ff); +bitmap.qBezier(10,100, 250,270, 150,20, 0); +bitmap.write(File("foo.ppm","wb")); diff --git a/Task/Bitmap-Bresenhams-line-algorithm/BBC-BASIC/bitmap-bresenhams-line-algorithm.bbc b/Task/Bitmap-Bresenhams-line-algorithm/BBC-BASIC/bitmap-bresenhams-line-algorithm.bbc index 762777c9ba..2e7c733b05 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/BBC-BASIC/bitmap-bresenhams-line-algorithm.bbc +++ b/Task/Bitmap-Bresenhams-line-algorithm/BBC-BASIC/bitmap-bresenhams-line-algorithm.bbc @@ -15,7 +15,7 @@ LOCAL dx%, dy%, sx%, sy%, e dx% = ABS(x2% - x1%) : sx% = SGN(x2% - x1%) dy% = ABS(y2% - y1%) : sy% = SGN(y2% - y1%) - IF dx% < dy% e = dx% / 2 ELSE e = dy% / 2 + IF dx% > dy% e = dx% / 2 ELSE e = dy% / 2 REPEAT PROCsetpixel(x1%,y1%,r%,g%,b%) IF x1% = x2% IF y1% = y2% EXIT REPEAT diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Elm/bitmap-bresenhams-line-algorithm.elm b/Task/Bitmap-Bresenhams-line-algorithm/Elm/bitmap-bresenhams-line-algorithm.elm new file mode 100644 index 0000000000..c32436db71 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Elm/bitmap-bresenhams-line-algorithm.elm @@ -0,0 +1,53 @@ +-- Brensenham Line Algorithm + +type alias Position = + {x: Int, y: Int} + +type alias BresenhamStatics = + { finish : Position + , sx : Int + , sy : Int + , dx : Float + , dy : Float + } + + +line : Position -> Position -> List Position +line p q = + let + dx = (toFloat << abs) (q.x - p.x) + dy = (toFloat << abs) (q.y - p.y) + + sx = if p.x < q.x then 1 else -1 + sy = if p.y < q.y then 1 else -1 + + error = + (if dx > dy then dx else -dy) / 2 + + statics = + BresenhamStatics q sx sy dx dy + in + bresenhamLineLoop statics error p [] + + +bresenhamLineLoop : BresenhamStatics -> Float -> Position -> List Position -> List Position +bresenhamLineLoop statics error p positions = + let + positions_ = p :: positions + {sx, sy, dx, dy, finish} = statics + in + if (p.x == finish.x) && (p.y == finish.y) then + positions_ + else + let + (dErrX, x) = + if error > -dx then (-dy, sx + p.x) + else (0, p.x) + + (dErrY, y) = + if error < dy then (dx, sy + p.y) + else (0, p.y) + + error_ = error + dErrX + dErrY + in + bresenhamLineLoop statics error_ (Position x y) positions_ diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Kotlin/bitmap-bresenhams-line-algorithm.kotlin b/Task/Bitmap-Bresenhams-line-algorithm/Kotlin/bitmap-bresenhams-line-algorithm.kotlin new file mode 100644 index 0000000000..7e3ad2953e --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Kotlin/bitmap-bresenhams-line-algorithm.kotlin @@ -0,0 +1,81 @@ +// version 1.1.2 + +import java.awt.* +import javax.swing.* + +class Bresenham(w: Int, h: Int) : JPanel() { + private val centerX = w / 2 + private val centerY = h / 2 + + init { + preferredSize = Dimension(w, h) + background = Color.blue + } + + override fun paintComponent(g: Graphics) { + super.paintComponent(g) + drawLine(g, 0, 0, 8, 19) // NNE + drawLine(g, 0, 0, 19, 8) // ENE + drawLine(g, 0, 0, 19, -8) // ESE + drawLine(g, 0, 0, 8, -19) // SSE + drawLine(g, 0, 0, -8, -19) // SSW + drawLine(g, 0, 0, -19, -8) // WSW + drawLine(g, 0, 0, -19, 8) // WNW + drawLine(g, 0, 0, -8, 19) // NNW + } + + private fun plot(g: Graphics, x: Int, y: Int) { + g.color = Color.white + g.drawOval(centerX + x * 10, centerY -y * 10, 10, 10) + } + + private fun drawLine(g: Graphics, x1: Int, y1: Int, x2: Int, y2: Int) { + var d = 0 + val dy = Math.abs(y2 - y1) + val dx = Math.abs(x2 - x1) + val dy2 = dy shl 1 + val dx2 = dx shl 1 + val ix = if (x1 < x2) 1 else -1 + val iy = if (y1 < y2) 1 else -1 + var xx = x1 + var yy = y1 + + if (dy <= dx) { + while (true) { + plot(g, xx, yy) + if (xx == x2) break + xx += ix + d += dy2 + if (d > dx) { + yy += iy + d -= dx2 + } + } + } + else { + while (true) { + plot(g, xx, yy) + if (yy == y2) break + yy += iy + d += dx2 + if (d > dy) { + xx += ix + d -= dy2 + } + } + } + } +} + +fun main(args: Array) { + SwingUtilities.invokeLater { + val f = JFrame() + f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE + f.isVisible = true + f.add(Bresenham(600, 500), BorderLayout.CENTER) + f.title = "Bresenham" + f.isResizable = false + f.pack() + f.setLocationRelativeTo(null) + } +} diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Zkl/bitmap-bresenhams-line-algorithm-1.zkl b/Task/Bitmap-Bresenhams-line-algorithm/Zkl/bitmap-bresenhams-line-algorithm-1.zkl new file mode 100644 index 0000000000..53e281ac00 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Zkl/bitmap-bresenhams-line-algorithm-1.zkl @@ -0,0 +1,7 @@ +ppm:=PPM(200,200,0xFF|FF|FF); +ppm.line(50,100, 100,190, 0); +ppm.line(100,190, 150,100, 0); +ppm.line(150,100, 100,10, 0); +ppm.line(100,10, 50,100, 0); + +ppm.writeJPGFile("line.jpg"); diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Zkl/bitmap-bresenhams-line-algorithm-2.zkl b/Task/Bitmap-Bresenhams-line-algorithm/Zkl/bitmap-bresenhams-line-algorithm-2.zkl new file mode 100644 index 0000000000..b90485397e --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Zkl/bitmap-bresenhams-line-algorithm-2.zkl @@ -0,0 +1,90 @@ +class PPM{ // (0,0) is logically bottom left + fcn init(width,height,rgb=0){ + sz:=width*height; + var [const] + data=Data(sz*3).fill(rgb.toBigEndian(3).toData()), // initialize to 24bit Black (RGB=000) + w=width, h=height; + } + fcn fill(rgb){ data.fill(rgb.toBigEndian(3).toData()) } + fcn __sGet(x,y) { data.toBigEndian(3*y*w + 3*x,3); } //ppm[x,y] + fcn __sSet(rgb,x,y){ data[3*y*w + x*3,3]=rgb.toBigEndian(3); rgb } //ppm[x,y]=rgb + fcn write(out,raw=False){ // write bottom to top to move (0,0) from top left to bottom left + out.write("P6\n#rosettacode PPM\n%d %d\n255\n".fmt(w,h)); + if(raw) out.write(data); + else [h-1..0, -1].pump(out,'wrap(h){ data.seek(3*h*w); data.read(3*w) }); + } + fcn writeJPGFile(fname){ // Linux, using imagemagick + System.popen(0'|convert ppm:- jpg:"%s"|.fmt(fname),"w") : + write(_,vm.pasteArgs(1)); + } + fcn readJPGFile(fileName){ // Linux, using imagemagick + p:=System.popen("convert \"%s\" ppm:-".fmt(fileName),"r"); + img:=PPM.readPPM(p); + p.close(); + img + } + fcn readPPMFile(fileName){ + f:=File(fileName,"rb"); ppm:=readPPM(f); f.close(); + ppm + } + fcn readPPM(image){ // image is a PPM byte stream + // header is "P6\n[#comment\n] \nmaxPixelValue\n + image.readln(); // "P6" + while("#"==(text:=image.readln().strip())[0]){} + w,h:=text.split().apply("toInt"); + image.readln(); // max pixel value + ppm,sz,buffer:=PPM(w,h), 3*w, Data(sz); + ppm.data.clear(); // gonna write file image data + // image is stored upside down in my data structure + do(h){ ppm.data.insert(0, image.read(sz,buffer)) } + ppm + } + fcn circle(x0,y0,r,rgb){ + 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); } + } + } + fcn cross(x,y,rgb=0xff|00,len=10){ + a:=len/2; b:=len-a; + line(x-a,y, x+b,y,rgb); line(x,y-a, x,y+b,rgb); + } + fcn line(x0,y0, x1,y1, rgb){ + dx:=(x1-x0).abs(); + dy:=(y1-y0).abs(); + if(x0 < x1) sx:=1 else sx:=-1; + if(y0 < y1) sy:=1 else sy:=-1; + err:=dx - dy; + while(1){ + __sSet(rgb,x0,y0); + if(x0==x1 and y0==y1) break; + e2:=2*err; + if(e2 > -dy){ err=err - dy; x0=x0 + sx; } + if(e2 < dx) { err=err + dx; y0=y0 + sy; } + } + } + fcn flood(x,y, repl){ // slow! + targ:=self[x,y]; + (stack:=List.createLong(10000)).append(T(x,y)); + while(stack){ + x,y:=stack.pop(); + if((0<=y +#include +#define MAXSIZE 2048 +#define BYTE unsigned char -int FillContour(int iXseed, int iYseed, unsigned char color, unsigned char _data[]) +static int width, height; +static BYTE bitmap[MAXSIZE][MAXSIZE]; +static BYTE oldColor; +static BYTE newColor; + +void floodFill(int i, int j) { - /* - fills contour with black border ( color = iJulia) using seed point inside contour - and horizontal lines - it starts from seed point, saves max right( iXmaxLocal) and max left ( iXminLocal) interior points of horizontal line, - in new line ( iY+1 or iY-1) it computes new interior point : iXmidLocal=iXminLocal + (iXmaxLocal-iXminLocal)/2; - result is stored in _data array : 1D array of 1-bit colors ( shades of gray) - it does not check if index of _data array is good so memory error is possible - */ - - - int iX, /* seed integer coordinate */ - iY=iYseed, - /* most interior point of line iY */ - iXmidLocal=iXseed, - /* min and max of interior points of horizontal line iY */ - iXminLocal, - iXmaxLocal; - int i ; /* index of _data array */; - - - /* --------- move up --------------- */ - do{ - iX=iXmidLocal; - i =f(iX,iY); /* index of _data array */; - - /* move to right */ - while (_data[i]==iInterior) - { _data[i]=color; - iX+=1; - i=f(iX,iY); - } - iXmaxLocal=iX-1; - - /* move to left */ - iX=iXmidLocal-1; - i=f(iX,iY); - while (_data[i]==iInterior) - { _data[i]=color; - iX-=1; - i=f(iX,iY); - } - iXminLocal=iX+1; - - - iY+=1; /* move up */ - iXmidLocal=iXminLocal + (iXmaxLocal-iXminLocal)/2; /* new iX inside contour */ - i=f(iXmidLocal,iY); /* index of _data array */; - if ( _data[i]==iJulia) break; /* it should not cross the border */ - - } while (iY */ -typedef struct { - color_component red, green, blue; -} rgb_color; -typedef rgb_color *rgb_color_p; +// http://commons.wikimedia.org/wiki/File:Julia_immediate_basin_1_3.png -void floodfill(image img, int px, int py, - rgb_color_p bankscolor, - rgb_color_p rcolor); +unsigned int f(unsigned int _iX, unsigned int _iY) +/* + gives position of point (iX,iY) in 1D array ; uses also global variables + it does not check if index is good so memory error is possible +*/ +{return (_iX + (iYmax-_iY-1)*iXmax );} + + +int FillContour(int iXseed, int iYseed, unsigned char color, unsigned char _data[]) +{ + /* + fills contour with black border ( color = iJulia) using seed point inside contour + and horizontal lines + it starts from seed point, saves max right( iXmaxLocal) and max left ( iXminLocal) interior points of horizontal line, + in new line ( iY+1 or iY-1) it computes new interior point : iXmidLocal=iXminLocal + (iXmaxLocal-iXminLocal)/2; + result is stored in _data array : 1D array of 1-bit colors ( shades of gray) + it does not check if index of _data array is good so memory error is possible + */ + + + int iX, /* seed integer coordinate */ + iY=iYseed, + /* most interior point of line iY */ + iXmidLocal=iXseed, + /* min and max of interior points of horizontal line iY */ + iXminLocal, + iXmaxLocal; + int i ; /* index of _data array */; + + + /* --------- move up --------------- */ + do{ + iX=iXmidLocal; + i =f(iX,iY); /* index of _data array */; + + /* move to right */ + while (_data[i]==iInterior) + { _data[i]=color; + iX+=1; + i=f(iX,iY); + } + iXmaxLocal=iX-1; + + /* move to left */ + iX=iXmidLocal-1; + i=f(iX,iY); + while (_data[i]==iInterior) + { _data[i]=color; + iX-=1; + i=f(iX,iY); + } + iXminLocal=iX+1; + + + iY+=1; /* move up */ + iXmidLocal=iXminLocal + (iXmaxLocal-iXminLocal)/2; /* new iX inside contour */ + i=f(iXmidLocal,iY); /* index of _data array */; + if ( _data[i]==iJulia) break; /* it should not cross the border */ + + } while (iY */ +typedef struct { + color_component red, green, blue; +} rgb_color; +typedef rgb_color *rgb_color_p; -typedef struct _ffill_node { - int px, py; - TAILQ_ENTRY(_ffill_node) nodes; -} _ffill_node_t; -TAILQ_HEAD(_ffill_queue_s, _ffill_node); -typedef struct _ffill_queue_s _ffill_queue; - -inline void _ffill_removehead(_ffill_queue *q) -{ - _ffill_node_t *n = q->tqh_first; - if ( n != NULL ) { - TAILQ_REMOVE(q, n, nodes); - free(n); - } -} - -inline void _ffill_enqueue(_ffill_queue *q, int px, int py) -{ - _ffill_node_t *node; - node = malloc(sizeof(_ffill_node_t)); - if ( node != NULL ) { - node->px = px; node->py = py; - TAILQ_INSERT_TAIL(q, node, nodes); - } -} - -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)); -} - -inline void _ffill_rgbcolor(image img, rgb_color_p tc, int px, int py) -{ - tc->red = GET_PIXEL(img, px, py)[0]; - tc->green = GET_PIXEL(img, px, py)[1]; - tc->blue = GET_PIXEL(img, px, py)[2]; -} - - -#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, +void floodfill(image img, int px, int py, rgb_color_p bankscolor, - rgb_color_p rcolor) -{ - _ffill_queue head; - rgb_color thisnode; - unsigned int pixelcount = 0; - double tolerance = 0.05; - - if ( (px < 0) || (py < 0) || (px >= img->width) || (py >= img->height) ) - return; - - TAILQ_INIT(&head); - - _ffill_rgbcolor(img, &thisnode, px, py); - if ( color_distance(&thisnode, bankscolor) <= tolerance ) return; - - _ffill_enqueue(&head, px, py); - while( head.tqh_first != NULL ) { - _ffill_node_t *n = head.tqh_first; - _ffill_rgbcolor(img, &thisnode, n->px, n->py); - if ( color_distance(&thisnode, bankscolor) > tolerance ) { - put_pixel_unsafe(img, n->px, n->py, rcolor->red, rcolor->green, rcolor->blue); - pixelcount++; - } - int tx = n->px, ty = n->py; - _ffill_removehead(&head); - NSOE(tx - 1, ty); - NSOE(tx + 1, ty); - NSOE(tx, ty - 1); - NSOE(tx, ty + 1); - } - return pixelcount; -} + 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 b41de6f1bd..8e9134edf6 100644 --- a/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-4.c +++ b/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-4.c @@ -1,27 +1,93 @@ -#include -#include #include "imglib.h" -int main(int argc, char **argv) -{ - image animage; - rgb_color ic; - rgb_color rc; +typedef struct _ffill_node { + int px, py; + TAILQ_ENTRY(_ffill_node) nodes; +} _ffill_node_t; +TAILQ_HEAD(_ffill_queue_s, _ffill_node); +typedef struct _ffill_queue_s _ffill_queue; - if ( argc > 1 ) { - animage = read_image(argv[1]); - if ( animage != NULL ) { - ic.red = 255; /* = 0; */ - ic.green = 255; /* = 0; */ - ic.blue = 255; /* = 0; */ - rc.red = 0; - rc.green = 255; - rc.blue = 0; - floodfill(animage, 100, 100, &ic, &rc); - /* 150, 150 */ - print_jpg(animage, 90); - free(animage); - } +inline void _ffill_removehead(_ffill_queue *q) +{ + _ffill_node_t *n = q->tqh_first; + if ( n != NULL ) { + TAILQ_REMOVE(q, n, nodes); + free(n); } - return 0; +} + +inline void _ffill_enqueue(_ffill_queue *q, int px, int py) +{ + _ffill_node_t *node; + node = malloc(sizeof(_ffill_node_t)); + if ( node != NULL ) { + node->px = px; node->py = py; + TAILQ_INSERT_TAIL(q, node, nodes); + } +} + +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)); +} + +inline void _ffill_rgbcolor(image img, rgb_color_p tc, int px, int py) +{ + tc->red = GET_PIXEL(img, px, py)[0]; + tc->green = GET_PIXEL(img, px, py)[1]; + tc->blue = GET_PIXEL(img, px, py)[2]; +} + + +#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) +{ + _ffill_queue head; + rgb_color thisnode; + unsigned int pixelcount = 0; + double tolerance = 0.05; + + if ( (px < 0) || (py < 0) || (px >= img->width) || (py >= img->height) ) + return; + + TAILQ_INIT(&head); + + _ffill_rgbcolor(img, &thisnode, px, py); + if ( color_distance(&thisnode, bankscolor) <= tolerance ) return; + + _ffill_enqueue(&head, px, py); + while( head.tqh_first != NULL ) { + _ffill_node_t *n = head.tqh_first; + _ffill_rgbcolor(img, &thisnode, n->px, n->py); + if ( color_distance(&thisnode, bankscolor) > tolerance ) { + put_pixel_unsafe(img, n->px, n->py, rcolor->red, rcolor->green, rcolor->blue); + pixelcount++; + } + int tx = n->px, ty = n->py; + _ffill_removehead(&head); + NSOE(tx - 1, ty); + NSOE(tx + 1, ty); + NSOE(tx, ty - 1); + NSOE(tx, ty + 1); + } + return pixelcount; } diff --git a/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-5.c b/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-5.c new file mode 100644 index 0000000000..b41de6f1bd --- /dev/null +++ b/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-5.c @@ -0,0 +1,27 @@ +#include +#include +#include "imglib.h" + +int main(int argc, char **argv) +{ + image animage; + rgb_color ic; + rgb_color rc; + + if ( argc > 1 ) { + animage = read_image(argv[1]); + if ( animage != NULL ) { + ic.red = 255; /* = 0; */ + ic.green = 255; /* = 0; */ + ic.blue = 255; /* = 0; */ + rc.red = 0; + rc.green = 255; + rc.blue = 0; + floodfill(animage, 100, 100, &ic, &rc); + /* 150, 150 */ + print_jpg(animage, 90); + free(animage); + } + } + return 0; +} diff --git a/Task/Bitmap-Flood-fill/Kotlin/bitmap-flood-fill.kotlin b/Task/Bitmap-Flood-fill/Kotlin/bitmap-flood-fill.kotlin new file mode 100644 index 0000000000..b369d4a034 --- /dev/null +++ b/Task/Bitmap-Flood-fill/Kotlin/bitmap-flood-fill.kotlin @@ -0,0 +1,60 @@ +// version 1.1.4-3 + +import java.awt.Color +import java.awt.Point +import java.awt.image.BufferedImage +import java.util.LinkedList +import java.io.File +import javax.imageio.ImageIO +import javax.swing.JOptionPane +import javax.swing.JLabel +import javax.swing.ImageIcon + +fun floodFill(image: BufferedImage, node: Point, targetColor: Color, replColor: Color) { + val target = targetColor.getRGB() + val replacement = replColor.getRGB() + if (target == replacement) return + val width = image.width + val height = image.height + val queue = LinkedList() + var nnode: Point? = node + + do { + var x = nnode!!.x + val y = nnode.y + while (x > 0 && image.getRGB(x - 1, y) == target) x-- + var spanUp = false + var spanDown = false + + while (x < width && image.getRGB(x, y) == target) { + image.setRGB(x, y, replacement) + + if (!spanUp && y > 0 && image.getRGB(x, y - 1) == target) { + queue.add(Point(x, y - 1)) + spanUp = true + } + else if (spanUp && y > 0 && image.getRGB(x, y - 1) != target) { + spanUp = false + } + + if (!spanDown && y < height - 1 && image.getRGB(x, y + 1) == target) { + queue.add(Point(x, y + 1)) + spanDown = true + } + else if (spanDown && y < height - 1 && image.getRGB(x, y + 1) != target) { + spanDown = false + } + x++ + } + nnode = queue.pollFirst() + } + while (nnode != null) +} + +fun main(args: Array) { + val image = ImageIO.read(File("Unfilledcirc.png")) + floodFill(image, Point(50, 50), Color.white, Color.yellow) + val title = "Floodfilledcirc.png" + ImageIO.write(image, "png", File(title)) + JOptionPane.showMessageDialog(null, JLabel(ImageIcon(image)), title, JOptionPane.PLAIN_MESSAGE) +} diff --git a/Task/Bitmap-Flood-fill/R/bitmap-flood-fill-1.r b/Task/Bitmap-Flood-fill/R/bitmap-flood-fill-1.r new file mode 100644 index 0000000000..4ddbad2f5b --- /dev/null +++ b/Task/Bitmap-Flood-fill/R/bitmap-flood-fill-1.r @@ -0,0 +1,23 @@ +library(png) +img <- readPNG("Unfilledcirc.png") +M <- img[ , , 1] +M <- ifelse(M < 0.5, 0, 1) +image(M, col = c(1, 0)) + +# https://en.wikipedia.org/wiki/Flood_fill +floodfill <- function(row, col, tcol, rcol) { + if (tcol == rcol) return() + if (M[row, col] != tcol) return() + M[row, col] <<- rcol + floodfill(row - 1, col , tcol, rcol) # south + floodfill(row + 1, col , tcol, rcol) # north + floodfill(row , col - 1, tcol, rcol) # west + floodfill(row , col + 1, tcol, rcol) # east + return("filling completed") +} + +options(expressions = 10000) +startrow <- 100; startcol <- 100 +floodfill(startrow, startcol, 0, 2) + +image(M, col = c(1, 0, 2)) diff --git a/Task/Bitmap-Flood-fill/R/bitmap-flood-fill-2.r b/Task/Bitmap-Flood-fill/R/bitmap-flood-fill-2.r new file mode 100644 index 0000000000..f3f5239dcc --- /dev/null +++ b/Task/Bitmap-Flood-fill/R/bitmap-flood-fill-2.r @@ -0,0 +1,37 @@ +library(png) +img <- readPNG("Unfilledcirc.png") +M <- img[ , , 1] +M <- ifelse(M < 0.5, 0, 1) +M <- rbind(M, 0) +M <- cbind(M, 0) +image(M, col = c(1, 0)) + +# https://en.wikipedia.org/wiki/Flood_fill +floodfill <- function(row, col, tcol, rcol) { + if (tcol == rcol) return() + if (M[row, col] != tcol) return() + Q <- matrix(c(row, col), 1, 2) + while (dim(Q)[1] > 0) { + n <- Q[1, , drop = FALSE] + west <- cbind(n[1] , n[2] - 1) + east <- cbind(n[1] , n[2] + 1) + north <- cbind(n[1] + 1, n[2] ) + south <- cbind(n[1] - 1, n[2] ) + Q <- Q[-1, , drop = FALSE] + if (M[n] == tcol) { + M[n] <<- rcol + if (M[west] == tcol) Q <- rbind(Q, west) + if (M[east] == tcol) Q <- rbind(Q, east) + if (M[north] == tcol) Q <- rbind(Q, north) + if (M[south] == tcol) Q <- rbind(Q, south) + } + } + return("filling completed") +} + +startrow <- 100; startcol <- 100 +floodfill(startrow, startcol, 0, 2) +startrow <- 50; startcol <- 50 +floodfill(startrow, startcol, 1, 3) + +image(M, col = c(1, 0, 2, 3)) diff --git a/Task/Bitmap-Flood-fill/REXX/bitmap-flood-fill.rexx b/Task/Bitmap-Flood-fill/REXX/bitmap-flood-fill.rexx index 1b8853e2e1..33cfd4d82f 100644 --- a/Task/Bitmap-Flood-fill/REXX/bitmap-flood-fill.rexx +++ b/Task/Bitmap-Flood-fill/REXX/bitmap-flood-fill.rexx @@ -4,14 +4,14 @@ red = '000000000000000011111111'b /* " " red " " green= '000000001111111100000000'b /* " " green " " " */ white= '111111111111111111111111'b /* " " white " " " */ /*image is defined to the test image. */ -hx=125; hy=125 /*define limits (x,Y) for the image. */ -area=white; call fill 125, 25, red /*fill the white area in red. */ -area=black; call fill 125, 125, green /*fill the center orb in green. */ +hx=125; hy=125 /*define limits (X,Y) for the image. */ +area=white; call fill 125, 25, red /*fill the white area in red. */ +area=black; call fill 125, 125, green /*fill the center orb in green. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ fill: procedure expose image. hx hy area; parse arg x,y,fill_color /*obtain the args.*/ if x<1 | x>hx | y<1 | y>hy then return /*X or Y are outside of the image area*/ - pixel=@(x, y) /*obtain the color of the X,Y pixel. */ + pixel=image.x.y /*obtain the color of the X,Y pixel. */ if pixel\==area then return /*the pixel has already been filled */ /*with the fill_color, or we are not */ /*within the area to be filled. */ diff --git a/Task/Bitmap-Flood-fill/Zkl/bitmap-flood-fill-1.zkl b/Task/Bitmap-Flood-fill/Zkl/bitmap-flood-fill-1.zkl new file mode 100644 index 0000000000..ccd3c7df5a --- /dev/null +++ b/Task/Bitmap-Flood-fill/Zkl/bitmap-flood-fill-1.zkl @@ -0,0 +1,14 @@ +fcn flood(pixmap, x,y, repl){ // slow! + targ,h,w:=pixmap[x,y], pixmap.h,pixmap.w; + stack:=List(T(x,y)); + while(stack){ + x,y:=stack.pop(); + if((0<=ygray-image (image) + (check-type image 8-bit-rgb-image) + (let ((gray-image (with-image-bounds (height width) image + (make-8-bit-gray-image height width :initial-element 0)))) + (do-pixels (i j) image + (multiple-value-bind (r g b) (pixel image i j) + (let ((gray (+ (* 0.2126 r) (* 0.7152 g) (* 0.0722 b)))) + (setf (pixel gray-image i j) (round gray))))) + gray-image)) + +(defun make-histogram (image) + (check-type image 8-bit-gray-image) + (let ((histogram (make-array 256 :element-type 'fixnum :initial-element 0))) + (do-pixels (i j) image + (incf (aref histogram (pixel image i j)))) + histogram)) + +(defun find-median (histogram) + (loop with num-pixels = (loop for count across histogram sum count) + with half = (/ num-pixels 2) + for count across histogram + for i from 0 + sum count into acc + when (>= acc half) + return i)) + +(defun gray->black&white-image (image) + (check-type image 8-bit-gray-image) + (let* ((histogram (make-histogram image)) + (median (find-median histogram)) + (bw-image (with-image-bounds (height width) image + (make-1-bit-gray-image height width :initial-element 0)))) + (do-pixels (i j) image + (setf (pixel bw-image i j) (if (<= (pixel image i j) median) 1 0))) + bw-image)) + +(defun main () + (let* ((image (read-jpeg-file "lenna.jpg")) + (bw-image (gray->black&white-image (color->gray-image image)))) + (write-pbm-file "lenna-bw.pbm" bw-image))) diff --git a/Task/Bitmap-Histogram/Zkl/bitmap-histogram-1.zkl b/Task/Bitmap-Histogram/Zkl/bitmap-histogram-1.zkl new file mode 100644 index 0000000000..5d99339833 --- /dev/null +++ b/Task/Bitmap-Histogram/Zkl/bitmap-histogram-1.zkl @@ -0,0 +1,14 @@ +fcn histogram(image){ + 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; +} +fcn histogramMedian(hist){ + from,to:=0,(2).pow(8) - 1; // 16 bits of luminance + left,right:=hist[from],hist[to]; + while(from!=to){ + if(leftmedian) 0xff else 0 }); + +bw.write(File("foo.ppm","wb")); 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.kotlin new file mode 100644 index 0000000000..f0bacc2a7d --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Kotlin/bitmap-midpoint-circle-algorithm.kotlin @@ -0,0 +1,60 @@ +// version 1.1.4-3 + +import java.awt.Color +import java.awt.Graphics +import java.awt.image.BufferedImage +import javax.swing.JOptionPane +import javax.swing.JLabel +import javax.swing.ImageIcon + +class BasicBitmapStorage(width: Int, height: Int) { + val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR) + + fun fill(c: Color) { + val g = image.graphics + g.color = c + g.fillRect(0, 0, image.width, image.height) + } + + fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB()) + + fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y)) +} + +fun drawCircle(bbs: BasicBitmapStorage, centerX: Int, centerY: Int, radius: Int, circleColor: Color) { + var d = (5 - radius * 4) / 4 + var x = 0 + var y = radius + + do { + with(bbs) { + setPixel(centerX + x, centerY + y, circleColor) + setPixel(centerX + x, centerY - y, circleColor) + setPixel(centerX - x, centerY + y, circleColor) + setPixel(centerX - x, centerY - y, circleColor) + setPixel(centerX + y, centerY + x, circleColor) + setPixel(centerX + y, centerY - x, circleColor) + setPixel(centerX - y, centerY + x, circleColor) + setPixel(centerX - y, centerY - x, circleColor) + } + if (d < 0) { + d += 2 * x + 1 + } + else { + d += 2 * (x - y) + 1 + y-- + } + x++ + } + while (x <= y) +} + +fun main(args: Array) { + val bbs = BasicBitmapStorage(400, 400) + bbs.fill(Color.pink) + drawCircle(bbs, 200, 200, 100, Color.black) + drawCircle(bbs, 200, 200, 50, Color.white) + val label = JLabel(ImageIcon(bbs.image)) + val title = "Bresenham's circle algorithm" + JOptionPane.showMessageDialog(null, label, title, JOptionPane.PLAIN_MESSAGE) +} diff --git a/Task/Bitmap-Midpoint-circle-algorithm/PL-I/bitmap-midpoint-circle-algorithm-1.pli b/Task/Bitmap-Midpoint-circle-algorithm/PL-I/bitmap-midpoint-circle-algorithm-1.pli deleted file mode 100644 index 53a26c45cf..0000000000 --- a/Task/Bitmap-Midpoint-circle-algorithm/PL-I/bitmap-midpoint-circle-algorithm-1.pli +++ /dev/null @@ -1,52 +0,0 @@ -/* Plot three circles. */ - -CIRCLE: PROCEDURE OPTIONS (MAIN); - declare image (-20:20, -20:20) character (1); - declare j fixed binary; - - image = '.'; - image(0,*) = '-'; - image(*,0) = '|'; - image(0,0) = '+'; - - CALL DRAW_CIRCLE (0, 0, 11); - CALL DRAW_CIRCLE (0, 0, 8); - CALL DRAW_CIRCLE (0, 0, 19); - - do j = hbound(image,1) to lbound(image,1) by -1; - put skip edit (image(j,*)) (a(1)); - end; - -draw_circle: procedure (x0, y0, radius); /* 14 May 2010. */ - declare ( x0, y0, radius ) fixed binary; - declare ( ddfx, ddfy, x, y, f ) fixed binary; - declare debug bit (1) aligned static initial ('0'b); - - f = 1-radius; - ddfx = 1; - ddfy = -2*radius; - x = 0; - y = radius; - image(x0, y0+radius) = '*'; /* Octet 0. */ - image(x0+radius, y0) = '*'; /* Octet 1. */ - image(x0, y0-radius) = '*'; /* Octet 2. */ - image(x0-radius, y0) = '*'; /* Octet 3. */ - - do while (x < y); - if f >= 0 then - do; y = y - 1; ddfy = ddfy +2; f = f + ddfy; end; - x = x + 1; - ddfx = ddfx + 2; - f = f + ddfx; - image(x0+x, y0+y) = '0'; /* Draws octant 0. */ - image(x0+y, y0+x) = '1'; /* Draws octant 1. */ - image(x0+y, y0-x) = '2'; /* Draws octant 2. */ - image(x0+x, y0-y) = '3'; /* Draws octant 3. */ - image(x0-x, y0-y) = '4'; /* Draws octant 4. */ - image(x0-y, y0-x) = '5'; /* Draws octant 5. */ - image(x0-y, y0+x) = '6'; /* Draws octant 6. */ - image(x0-x, y0+y) = '7'; /* Draws octant 7. */ - end; -end draw_circle; - -END CIRCLE; diff --git a/Task/Bitmap-Midpoint-circle-algorithm/PL-I/bitmap-midpoint-circle-algorithm-2.pli b/Task/Bitmap-Midpoint-circle-algorithm/PL-I/bitmap-midpoint-circle-algorithm-2.pli deleted file mode 100644 index aa545bca6f..0000000000 --- a/Task/Bitmap-Midpoint-circle-algorithm/PL-I/bitmap-midpoint-circle-algorithm-2.pli +++ /dev/null @@ -1,41 +0,0 @@ -....................|.................... -................2222*1111................ -.............222....|....111............. -...........22.......|.......11........... -..........2.........|.........1.......... -........22..........|..........11........ -.......3............|............0....... -......2.............|.............1...... -.....3..............|..............0..... -.....3...........222*111...........0..... -....3..........22...|...11..........0.... -...3..........2.....|.....1..........0... -...3........32....22*11....11........0... -..3.........3...22..|..11...0.........0.. -..3........3...3....|....0...0........0.. -..3.......3...2.....|.....1...0.......0.. -.3........3..3......|......0..0........0. -.3.......3...3......|......0...0.......0. -.3.......3..3.......|.......0..0.......0. -.3.......3..3.......|.......0..0.......0. --*-------*--*-------+-------*--*-------*- -.4.......4..4.......|.......7..7.......7. -.4.......4..4.......|.......7..7.......7. -.4.......4...4......|......7...7.......7. -.4........4..4......|......7..7........7. -..4.......4...5.....|.....6...7.......7.. -..4........4...4....|....7...7........7.. -..4.........4...55..|..66...7.........7.. -...4........55....55*66....67........7... -...4..........5.....|.....6..........7... -....4..........55...|...66..........7.... -.....4...........555*666...........7..... -.....4..............|..............7..... -......5.............|.............6...... -.......4............|............7....... -........55..........|..........66........ -..........5.........|.........6.......... -...........55.......|.......66........... -.............555....|....666............. -................5555*6666................ -....................|.................... diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Modula-3/bitmap-midpoint-circle-algorithm-4.mod3 b/Task/Bitmap-Midpoint-circle-algorithm/Perl-6/bitmap-midpoint-circle-algorithm-1.pl6 similarity index 100% rename from Task/Bitmap-Midpoint-circle-algorithm/Modula-3/bitmap-midpoint-circle-algorithm-4.mod3 rename to Task/Bitmap-Midpoint-circle-algorithm/Perl-6/bitmap-midpoint-circle-algorithm-1.pl6 diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Modula-3/bitmap-midpoint-circle-algorithm-5.mod3 b/Task/Bitmap-Midpoint-circle-algorithm/Perl-6/bitmap-midpoint-circle-algorithm-2.pl6 similarity index 100% rename from Task/Bitmap-Midpoint-circle-algorithm/Modula-3/bitmap-midpoint-circle-algorithm-5.mod3 rename to Task/Bitmap-Midpoint-circle-algorithm/Perl-6/bitmap-midpoint-circle-algorithm-2.pl6 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 new file mode 100644 index 0000000000..f651983a78 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Zkl/bitmap-midpoint-circle-algorithm-1.zkl @@ -0,0 +1,16 @@ + fcn circle(x0,y0,r,rgb){ + 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); } + } + } diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Zkl/bitmap-midpoint-circle-algorithm-2.zkl b/Task/Bitmap-Midpoint-circle-algorithm/Zkl/bitmap-midpoint-circle-algorithm-2.zkl new file mode 100644 index 0000000000..1d0060a65f --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Zkl/bitmap-midpoint-circle-algorithm-2.zkl @@ -0,0 +1,5 @@ +ppm:=PPM(200,200,0xFF|FF|FF); +ppm.circle(100,100,40,00); // black circle +ppm.circle(100,100,80,0xFF|00|00); // red circle + +ppm.write(File("foo.ppm","wb")); diff --git a/Task/Bitmap-PPM-conversion-through-a-pipe/Go/bitmap-ppm-conversion-through-a-pipe-1.go b/Task/Bitmap-PPM-conversion-through-a-pipe/Go/bitmap-ppm-conversion-through-a-pipe-1.go deleted file mode 100644 index 08a2664e3e..0000000000 --- a/Task/Bitmap-PPM-conversion-through-a-pipe/Go/bitmap-ppm-conversion-through-a-pipe-1.go +++ /dev/null @@ -1,59 +0,0 @@ -package main - -// Files required to build supporting package raster are found in: -// * Bitmap -// * Write a PPM file - -import ( - "fmt" - "math/rand" - "os/exec" - "raster" -) - -func main() { - b := raster.NewBitmap(400, 300) - // a little extravagant, this draws a design of dots and lines - b.FillRgb(0xc08040) - for i := 0; i < 2000; i++ { - b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020) - } - for x := 0; x < 400; x++ { - for y := 240; y < 245; y++ { - b.SetPxRgb(x, y, 0x804020) - } - for y := 260; y < 265; y++ { - b.SetPxRgb(x, y, 0x804020) - } - } - for y := 0; y < 300; y++ { - for x := 80; x < 85; x++ { - b.SetPxRgb(x, y, 0x804020) - } - for x := 95; x < 100; x++ { - b.SetPxRgb(x, y, 0x804020) - } - } - - // pipe logic - c := exec.Command("cjpeg", "-outfile", "pipeout.jpg") - pipe, err := c.StdinPipe() - if err != nil { - fmt.Println(err) - return - } - err = c.Start() - if err != nil { - fmt.Println(err) - return - } - err = b.WritePpmTo(pipe) - if err != nil { - fmt.Println(err) - return - } - err = pipe.Close() - if err != nil { - fmt.Println(err) - } -} diff --git a/Task/Bitmap-PPM-conversion-through-a-pipe/Go/bitmap-ppm-conversion-through-a-pipe-2.go b/Task/Bitmap-PPM-conversion-through-a-pipe/Go/bitmap-ppm-conversion-through-a-pipe-2.go deleted file mode 100644 index c4ad95af34..0000000000 --- a/Task/Bitmap-PPM-conversion-through-a-pipe/Go/bitmap-ppm-conversion-through-a-pipe-2.go +++ /dev/null @@ -1,15 +0,0 @@ -let print_jpeg ~img ?(quality=96) () = - let cmd = Printf.sprintf "cjpeg -quality %d" quality in - (* - let cmd = Printf.sprintf "ppmtojpeg -quality %d" quality in - let cmd = Printf.sprintf "convert ppm:- -quality %d jpg:-" quality in - *) - let ic, oc = Unix.open_process cmd in - output_ppm ~img ~oc; - try - while true do - let c = input_char ic in - print_char c - done - with End_of_file -> () -;; diff --git a/Task/Bitmap-PPM-conversion-through-a-pipe/Zkl/bitmap-ppm-conversion-through-a-pipe.zkl b/Task/Bitmap-PPM-conversion-through-a-pipe/Zkl/bitmap-ppm-conversion-through-a-pipe.zkl new file mode 100644 index 0000000000..9e4da3a628 --- /dev/null +++ b/Task/Bitmap-PPM-conversion-through-a-pipe/Zkl/bitmap-ppm-conversion-through-a-pipe.zkl @@ -0,0 +1,3 @@ +img:=PPM.readPPMFile("fractal.ppm"); +p:=System.popen(0'|convert ppm:- jpg:"fractal.jpg"|,"w"); +img.write(p); p.close(); diff --git a/Task/Bitmap-Read-a-PPM-file/Seed7/bitmap-read-a-ppm-file.seed7 b/Task/Bitmap-Read-a-PPM-file/Seed7/bitmap-read-a-ppm-file.seed7 index ce45e2ba68..d54e60d7fb 100644 --- a/Task/Bitmap-Read-a-PPM-file/Seed7/bitmap-read-a-ppm-file.seed7 +++ b/Task/Bitmap-Read-a-PPM-file/Seed7/bitmap-read-a-ppm-file.seed7 @@ -25,9 +25,9 @@ const func PRIMITIVE_WINDOW: getPPM (in string: fileName) is func aWindow := newPixmap(width, height); for y range 0 to pred(height) do for x range 0 to pred(width) do - pixColor.red_part := ord(getc(ppmFile)); - pixColor.green_part := ord(getc(ppmFile)); - pixColor.blue_part := ord(getc(ppmFile)); + pixColor.redLight := ord(getc(ppmFile)); + pixColor.greenLight := ord(getc(ppmFile)); + pixColor.blueLight := ord(getc(ppmFile)); end for; end for; end if; diff --git a/Task/Bitmap-Read-a-PPM-file/Zkl/bitmap-read-a-ppm-file.zkl b/Task/Bitmap-Read-a-PPM-file/Zkl/bitmap-read-a-ppm-file.zkl new file mode 100644 index 0000000000..4b536d6944 --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Zkl/bitmap-read-a-ppm-file.zkl @@ -0,0 +1,11 @@ +//24-bpp P6 PPM solution: +image:=File("lena.ppm","rb").read(); +start:=image.find("\n255\n")+5; // Get sizeof PPM header + +foreach n in ([start..image.len()-1,3]){ // Transform color triplets + r,g,b:=image[n,3]; // Read colors stored in RGB order + l:=(0.2126*r + 0.7152*g + 0.0722*b).toInt(); // Derive luminance + image[n,3]=T(l,l,l); +} + +File("lenaGrey.ppm","wb").write(image); diff --git a/Task/Bitmap-Read-an-image-through-a-pipe/Zkl/bitmap-read-an-image-through-a-pipe.zkl b/Task/Bitmap-Read-an-image-through-a-pipe/Zkl/bitmap-read-an-image-through-a-pipe.zkl new file mode 100644 index 0000000000..616ecded15 --- /dev/null +++ b/Task/Bitmap-Read-an-image-through-a-pipe/Zkl/bitmap-read-an-image-through-a-pipe.zkl @@ -0,0 +1,2 @@ +p:=System.popen(0'|convert "fractalTree.jpg" ppm:-|,"r"); +img:=PPM.readPPM(p); p.close(); diff --git a/Task/Bitmap-Write-a-PPM-file/Seed7/bitmap-write-a-ppm-file.seed7 b/Task/Bitmap-Write-a-PPM-file/Seed7/bitmap-write-a-ppm-file.seed7 index e0f06155eb..6078a634da 100644 --- a/Task/Bitmap-Write-a-PPM-file/Seed7/bitmap-write-a-ppm-file.seed7 +++ b/Task/Bitmap-Write-a-PPM-file/Seed7/bitmap-write-a-ppm-file.seed7 @@ -17,7 +17,7 @@ const proc: writePPM (in string: fileName, in PRIMITIVE_WINDOW: aWindow) is func for y range 0 to pred(height(aWindow)) do for x range 0 to pred(width(aWindow)) do pixColor := getPixelColor(aWindow, x, y); - write(ppmFile, str(chr(pixColor.red_part)) <& chr(pixColor.green_part) <& chr(pixColor.blue_part)); + write(ppmFile, str(chr(pixColor.redLight)) <& chr(pixColor.greenLight) <& chr(pixColor.blueLight)); end for; end for; close(ppmFile); diff --git a/Task/Bitmap-Write-a-PPM-file/Sidef/bitmap-write-a-ppm-file.sidef b/Task/Bitmap-Write-a-PPM-file/Sidef/bitmap-write-a-ppm-file.sidef index 57ba20217f..ffc55e9a48 100644 --- a/Task/Bitmap-Write-a-PPM-file/Sidef/bitmap-write-a-ppm-file.sidef +++ b/Task/Bitmap-Write-a-PPM-file/Sidef/bitmap-write-a-ppm-file.sidef @@ -1,24 +1,24 @@ subset Int < Number {|n| n.is_int } -subset Uint < Int {|n| n >= 0 } -subset Uint8 < Int {|n| n ~~ ^256 } +subset UInt < Int {|n| n >= 0 } +subset UInt8 < Int {|n| n ~~ ^256 } struct Pixel { - R < Uint8, - G < Uint8, - B < Uint8 + R < UInt8, + G < UInt8, + B < UInt8 } -class Bitmap(width < Uint, height < Uint) { +class Bitmap(width < UInt, height < UInt) { has data = [] method fill(Pixel p) { data = (width*height -> of { Pixel(p.R, p.G, p.B) }) } - method setpixel(i < Uint, j < Uint, Pixel p) { + method setpixel(i < UInt, j < UInt, Pixel p) { - subset WidthLimit < Uint { |n| n ~~ ^width } - subset HeightLimit < Uint { |n| n ~~ ^height } + subset WidthLimit < UInt { |n| n ~~ ^width } + subset HeightLimit < UInt { |n| n ~~ ^height } func (w < WidthLimit, h < HeightLimit) { data[w*height + h] = p @@ -26,8 +26,11 @@ class Bitmap(width < Uint, height < Uint) { } method p6 { - "P6\n#{width} #{height}\n255\n" + - data.map {|p| [p.R, p.G, p.B].pack('C3') }.join + <<-EOT + data.map {|p| [p.R, p.G, p.B].pack('C3') }.join + P6 + #{width} #{height} + 255 + EOT } } @@ -37,7 +40,4 @@ for i,j in (^b.height ~X ^b.width) { b.setpixel(i, j, Pixel(2*i, 2*j, 255 - 2*i)) } -var file = File("palette.ppm") -var fh = file.open('>:raw') -fh.print(b.p6) -fh.close +%f"palette.ppm".write(b.p6, :raw) diff --git a/Task/Bitmap-Write-a-PPM-file/Zkl/bitmap-write-a-ppm-file.zkl b/Task/Bitmap-Write-a-PPM-file/Zkl/bitmap-write-a-ppm-file.zkl new file mode 100644 index 0000000000..c02ab8d9d2 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Zkl/bitmap-write-a-ppm-file.zkl @@ -0,0 +1,17 @@ +// convert Windows BMP (bit map) image to PPM + + // Read BMP file +bmp:=File.stdin.read().howza(0); // BMP to memory (byte bucket), treat as bytes +_assert_(bmp[0]==0x42,"Stdin not a BMP file"); +width:=bmp.toLittleEndian(18,2,False); height:=bmp.toLittleEndian(22,2,False); // signed +println(width," x ",height); +bmp.del(0,14 + bmp.toLittleEndian(14,2)); // get rid of header + + // Write BMP to PPM image (in memory) +ppm:=Data(width*height*3 + 100); // sized byte bucket plus some header slop +ppm.write("P6\n#rosettacode BMP to PPM test\n%d %d\n255\n".fmt(width,height)); +foreach y in ([height - 1 .. 0,-1]){ // BGR 1 byte each, image is stored upside down + bmp[y*width*3,width*3].pump(ppm,T(Void.Read,2),fcn(b,g,r){ return(r,g,b) }); +} + +File("foo.ppm","wb").write(ppm); // File.stdout isn't binary, let GC close file diff --git a/Task/Bitmap/00DESCRIPTION b/Task/Bitmap/00DESCRIPTION index 882078c703..a179d8a7d1 100644 --- a/Task/Bitmap/00DESCRIPTION +++ b/Task/Bitmap/00DESCRIPTION @@ -1,4 +1,6 @@ +{{omit from|AWK}} {{omit from|PARI/GP}} + Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. diff --git a/Task/Bitmap/Ada/bitmap-1.ada b/Task/Bitmap/Ada/bitmap-1.ada index c6845cbb41..c239196025 100644 --- a/Task/Bitmap/Ada/bitmap-1.ada +++ b/Task/Bitmap/Ada/bitmap-1.ada @@ -1,10 +1,10 @@ package Bitmap_Store is type Luminance is mod 2**8; type Pixel is record - R, G, B : Luminance; + R, G, B : Luminance := Luminance'First; end record; - Black : constant Pixel := (others => 0); - White : constant Pixel := (others => 255); + Black : constant Pixel := (others => Luminance'First); + White : constant Pixel := (others => Luminance'Last); type Image is array (Positive range <>, Positive range <>) of Pixel; procedure Fill (Picture : in out Image; Color : Pixel); diff --git a/Task/Bitmap/Ada/bitmap-2.ada b/Task/Bitmap/Ada/bitmap-2.ada index d552d497d1..72c9941cf1 100644 --- a/Task/Bitmap/Ada/bitmap-2.ada +++ b/Task/Bitmap/Ada/bitmap-2.ada @@ -4,22 +4,14 @@ package body Bitmap_Store is procedure Fill (Picture : in out Image; Color : Pixel) is begin - for I in Picture'Range (1) loop - for J in Picture'Range (2) loop - Picture (I, J) := Color; - end loop; - end loop; + for p of Picture loop x:= Color;end loop; end Fill; procedure Print (Picture : Image) is begin for I in Picture'Range (1) loop for J in Picture'Range (2) loop - if Picture (I, J) = White then - Put (' '); - else - Put ('H'); - end if; + Put (if Picture (I, J) = White then ' ' else 'H'); end loop; New_Line; end loop; diff --git a/Task/Bitmap/Crystal/bitmap.crystal b/Task/Bitmap/Crystal/bitmap.crystal new file mode 100644 index 0000000000..fb4b8d9952 --- /dev/null +++ b/Task/Bitmap/Crystal/bitmap.crystal @@ -0,0 +1,36 @@ +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/Euphoria/bitmap.euphoria b/Task/Bitmap/Euphoria/bitmap.euphoria index 6a7738a031..e27c170c4e 100644 --- a/Task/Bitmap/Euphoria/bitmap.euphoria +++ b/Task/Bitmap/Euphoria/bitmap.euphoria @@ -19,5 +19,5 @@ image = new_image(800,600,black) image[400][300] = red -- Get pixel color -sequence color +atom color color = image[400][300] -- Now color is #FF0000 diff --git a/Task/Bitmap/Kotlin/bitmap.kotlin b/Task/Bitmap/Kotlin/bitmap.kotlin new file mode 100644 index 0000000000..a11112e9a7 --- /dev/null +++ b/Task/Bitmap/Kotlin/bitmap.kotlin @@ -0,0 +1,35 @@ +// version 1.1.4-3 + +import java.awt.Color +import java.awt.Graphics +import java.awt.image.BufferedImage + +class BasicBitmapStorage(width: Int, height: Int) { + val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR) + + fun fill(c: Color) { + val g = image.graphics + g.color = c + g.fillRect(0, 0, image.width, image.height) + } + + fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB()) + + fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y)) +} + +fun main(args: Array) { + val width = 640 + val height = 480 + val bbs = BasicBitmapStorage(width, height) + with (bbs) { + fill(Color.cyan) + setPixel(width / 2, height / 2, Color.black) + val c1 = getPixel(width / 2, height / 2) + val c2 = getPixel(20, 20) + print("The color of the pixel at (${width / 2}, ${height / 2}) is ") + println(if (c1 == Color.black) "black" else "unknown") + print("The color of the pixel at (120, 120) is ") + println(if (c2 == Color.cyan) "cyan" else "unknown") + } +} diff --git a/Task/Bitmap/REXX/bitmap-1.rexx b/Task/Bitmap/REXX/bitmap-1.rexx index f8bed61a30..826dc27c7f 100644 --- a/Task/Bitmap/REXX/bitmap-1.rexx +++ b/Task/Bitmap/REXX/bitmap-1.rexx @@ -1,37 +1,37 @@ -/*REXX pgm demonstrates how to handle a simple RGB raster graphics image*/ -red = '00000000 00000000 11111111'b /*define a red value. */ -blue = '11111111 00000000 00000000'b /*define a blue value. */ -blue = 'ff 00 00'x /*another way to define blue. */ -image.= /*"allocate" an "array" to nulls.*/ -call RGBfill red /*set the entire image to red. */ -call RGBset 10,40,blue /*set a pixel to blue. */ +/*REXX program demonstrates how to process/display a simple RGB raster graphics image.*/ +red = '00000000 00000000 11111111'b /*define a red value. */ +blue = '11111111 00000000 00000000'b /* " " blue " */ +blue = 'ff 00 00'x /*another way to define a blue value.*/ +image.= /*"allocate" an "array" to nulls. */ +call RGBfill red /*set the entire image to red. */ +call RGBset 10, 40, blue /*set a pixel to blue. */ -x=10; y=40; pix=RGBget(x,y) /*get the color of a pixel. */ -hexv = c2x(pix) /*get hex value of pix's color*/ -binv = x2b(hexv) /* " binary " " " " */ +x=10; y=40; pix=RGBget(x, y) /*get the color of a pixel. */ +hexv = c2x(pix) /*get hex value of pix's color. */ +binv = x2b(hexv) /* " binary " " " " */ -say 'pixel' x","y '=' binv /*show the binary value of 20,50 */ -bin3v = left(binv,8) substr(binv,9,8) right(binv,8) -say 'pixel' x","y '=' bin3v /*show again, but with spaces. */ -say /*show a blank between bin & hex.*/ -say 'pixel' x","y '=' hexv /*show again, but in hexadecimal.*/ -hex3v = left(hexv,2) substr(hexv,3,2) right(hexv,2) -say 'pixel' x","y '=' hex3v /*show again, but with spaces. */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────RGBFILL subroutine──────────────────*/ +say 'pixel' x","y '=' binv /*show the binary value of 20,50 */ +bin3v = left(binv, 8) substr(binv, 9, 8) right(binv, 8) +say 'pixel' x","y '=' bin3v /*show again, but with spaces. */ +say /*show a blank between binary and hex. */ +say 'pixel' x","y '=' hexv /*show again, but in hexadecimal. */ +hex3v = left(hexv, 2) substr(hexv, 3, 2) right(hexv, 2) +say 'pixel' x","y '=' hex3v /*show again, but with spaces. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ RGBfill: procedure expose image.; image.=arg(1); return -/*──────────────────────────────────RGBGET subroutine───────────────────*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ RGBget: procedure expose image.; parse arg Xpixel,Ypixel -return image.Xpixel.Ypixel /*get & return the pixel's color.*/ -/*──────────────────────────────────RGBRASTER subroutine────────────────*/ +return image.Xpixel.Ypixel /*obtain and return the pixel's color. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ RGBraster: procedure expose image.; parse arg Xsize,Ysize,color; RGB= - do x=1 to Xsize; _= /*build raster 1 line at a time. */ - do y=1 to Ysize /* " a line " pixel " " " */ - _=_ || image.x.y /*append single pixel to the line*/ - end /*y*/ /* [↑] all done building a line.*/ - RGB=RGB || _ /*append a single line to raster.*/ - end /*x*/ /* [↑] all done building raster.*/ -return RGB /*return RGB raster to invoker. */ -/*──────────────────────────────────RGBSET subroutine───────────────────*/ + do x=1 to Xsize; _= /*build raster one line at a time. */ + do y=1 to Ysize /* " a line " pixel " " " */ + _=_ || image.x.y /*append single pixel to the line. */ + end /*y*/ /* [↑] all done building a line. */ + RGB=RGB || _ /*append a single line to raster. */ + end /*x*/ /* [↑] all done building raster. */ +r return RGB /*return RGB raster to the invoker. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ RGBset: procedure expose image.; parse arg Xpixel,Ypixel,color -image.Xpixel.Ypixel=color; return /*define pixel, return to invoker*/ + image.Xpixel.Ypixel=color; return /*define pixel, return to the invoker. */ diff --git a/Task/Bitmap/Seed7/bitmap.seed7 b/Task/Bitmap/Seed7/bitmap.seed7 index b864bd532c..eef30cebcb 100644 --- a/Task/Bitmap/Seed7/bitmap.seed7 +++ b/Task/Bitmap/Seed7/bitmap.seed7 @@ -10,5 +10,5 @@ const proc: main is func clear(myPixmap, light_green); point(myPixmap, 20, 30, color(256, 512, 768)); myColor := getPixelColor(myPixmap, 20, 30); - writeln(myColor.red_part <& " " <& myColor.green_part <& " " <& myColor.blue_part); + writeln(myColor.redLight <& " " <& myColor.greenLight <& " " <& myColor.blueLight); end func; diff --git a/Task/Bitmap/Zkl/bitmap-1.zkl b/Task/Bitmap/Zkl/bitmap-1.zkl new file mode 100644 index 0000000000..b0784bda52 --- /dev/null +++ b/Task/Bitmap/Zkl/bitmap-1.zkl @@ -0,0 +1,19 @@ +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; + } + 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 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) }); + out.close(); + } +} diff --git a/Task/Bitmap/Zkl/bitmap-2.zkl b/Task/Bitmap/Zkl/bitmap-2.zkl new file mode 100644 index 0000000000..f415dbe889 --- /dev/null +++ b/Task/Bitmap/Zkl/bitmap-2.zkl @@ -0,0 +1,5 @@ +ppm:=PPM(256,256); +ppm.fill(0x00FF88); +foreach x in ([50..200]){ ppm[x,50]=0xff|00|00; } // horizontal red line + +ppm.write(File("foo.ppm","wb")); diff --git a/Task/Bitwise-IO/00DESCRIPTION b/Task/Bitwise-IO/00DESCRIPTION index 108c78afb7..a818f9b783 100644 --- a/Task/Bitwise-IO/00DESCRIPTION +++ b/Task/Bitwise-IO/00DESCRIPTION @@ -19,3 +19,4 @@ nine (or more) bits long. * Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. * Errors handling is not mandatory +

    diff --git a/Task/Bitwise-IO/Common-Lisp/bitwise-io-1.lisp b/Task/Bitwise-IO/Common-Lisp/bitwise-io-1.lisp new file mode 100644 index 0000000000..f64dc1fb22 --- /dev/null +++ b/Task/Bitwise-IO/Common-Lisp/bitwise-io-1.lisp @@ -0,0 +1,140 @@ +(defpackage :rosetta.bitwise-i/o + (:use :common-lisp) + (:export :bitwise-i/o-demo)) +(in-package :rosetta.bitwise-i/o) + +(defun byte->bit-vector (byte byte-bits) + "Convert one BYTE into a bit-vector of BYTE-BITS length." + (let ((vector (make-array byte-bits :element-type 'bit)) + (bit-value 1)) + (declare (optimize (speed 3))) + (dotimes (bit-index byte-bits vector) + (setf (aref vector bit-index) + (if (plusp (logand byte (the (unsigned-byte 8) bit-value))) + 1 0)) + (setq bit-value (ash bit-value 1))))) + +(defun bytes->bit-vector (byte-vector byte-bits) + "Convert a BYTE-VECTOR into a bit-vector, with each byte taking BYTE-BITS. + +For optimization's sake, I limit the size of the vector to (FLOOR +MOST-POSITIVE-FIXNUM BYTE-BITS), which is somewhat ridiculously long, +but allows the compiler to trust that indices will fit in a FIXNUM." + (reduce (lambda (a b) (concatenate 'bit-vector a b)) + (map 'list (lambda (byte) (byte->bit-vector byte byte-bits)) byte-vector))) + +(defun ascii-char-p (char) + "True if CHAR is an ASCII character" + (< (char-code char) #x80)) + +(defun assert-ascii-string (string) + "`ASSERT' that STRING is an ASCII string." + (assert (every #'ascii-char-p string) + (string) + "STRING must contain only ASCII (7-bit) characters;~%“~a” +…contains non-ASCII character~p~:*: ~{~% • ~c ~:*— ~@c ~}" + string (coerce (remove-duplicates (remove-if #'ascii-char-p string) + :test #'char=) + 'list))) + +(defun ascii-string->bit-vector (string) + "Convert a STRING consisting only of characters in the ASCII \(7-bit) +range into a bit-vector of 7 bits per character. + +This assumes \(as is now, in 2017, I believe universally the case) that +the local character code system \(as for `CHAR-CODE' and `CODE-CHAR') is +Unicode, or at least, a superset of ASCII \(eg: ISO-8859-*) +" + (check-type string simple-string) + (assert-ascii-string string) + (bytes->bit-vector (map 'vector #'char-code string) 7)) + +(defun pad-bit-vector-to-8 (vector) + "Ensure that VECTOR is a multiple of 8 bits in length." + (adjust-array vector (* 8 (ceiling (length vector) 8)))) + +(defun bit-vector->byte (vector) + "Convert VECTOR into a single byte." + (declare (optimize (speed 3))) + (check-type vector bit-vector) + (assert (<= (length vector) 8)) + (reduce (lambda (x y) + (logior (the (unsigned-byte 8) + (ash (the (unsigned-byte 8) x) 1)) + (the bit y))) + (reverse vector) :initial-value 0)) + +(defun bit-vector->bytes (vector byte-size &key (truncatep nil)) + "Convert a bit vector VECTOR into a vector of bytes of BYTE-SIZE bits each. + +If TRUNCATEP, then discard any trailing bits." + (let* ((out-length (funcall (if truncatep 'floor 'ceiling) + (length vector) + byte-size)) + (output (make-array out-length + :element-type (list 'unsigned-byte byte-size)))) + (loop for byte from 0 below out-length + for start-bit = 0 then end-bit + for end-bit = byte-size then (min (+ byte-size end-bit) + (length vector)) + do (setf (aref output byte) + (bit-vector->byte (subseq vector start-bit end-bit)))) + output)) + +(defun ascii-pack-to-8-bit (string) + "Pack an ASCII STRING into 8-bit bytes (7→8 bit packing)" + (bit-vector->bytes (ascii-string->bit-vector string) + 8)) + +(defun unpack-ascii-from-8-bits (byte-vector) + "Convert an 8-bit BYTE-VECTOR into an array of (unpacked) 7-bit bytes." + (map 'string #'code-char + (bit-vector->bytes + (pad-bit-vector-to-8 (bytes->bit-vector byte-vector 8)) + 7 + :truncatep t))) + +(defun write-7->8-bit-string-to-file (string pathname) + "Given a string of 7-bit character STRING, create a new file at PATHNAME +with the contents of that string packed into 8-bit bytes." + (format *trace-output* "~&Writing string to ~a in packed 7→8 bits…~%“~a”" + pathname string) + (assert-ascii-string string) + (with-open-file (output pathname + :direction :output + :if-exists :supersede + :element-type '(unsigned-byte 8)) + (write-sequence (ascii-pack-to-8-bit string) output) + (finish-output output) + (let ((expected-length (ceiling (* (length string) 7) 8))) + (assert (= (file-length output) expected-length) () + "The file written was ~:d byte~:p in length, ~ +but the string supplied should have written ~:d byte~:p." + (file-length output) expected-length)))) + +(defun read-file-into-byte-array (pathname) + "Read a binary file into a byte array" + (with-open-file (input pathname + :direction :input + :if-does-not-exist :error + :element-type '(unsigned-byte 8)) + (let ((buffer (make-array (file-length input) + :element-type '(unsigned-byte 8)))) + (read-sequence buffer input) + buffer))) + +(defun read-8->7-bit-string-from-file (pathname) + "Read 8-bit packed data from PATHNAME and return it as +a 7-bit string." + (unpack-ascii-from-8-bits (read-file-into-byte-array pathname))) + +(defun bitwise-i/o-demo (&key (string "Hello, World.") + (pathname #p"/tmp/demo.bin")) + "Writes STRING to PATHNAME after 7→8 bit packing, then reads it back +to validate." + (write-7->8-bit-string-to-file string pathname) + (let ((read-back (read-8->7-bit-string-from-file pathname))) + (assert (equal string read-back) () + "Reading back string got:~%“~a”~%…expected:~%“~a”" read-back string) + (format *trace-output* "~&String read back matches:~%“~a”" read-back)) + (finish-output *trace-output*)) diff --git a/Task/Bitwise-IO/Common-Lisp/bitwise-io-2.lisp b/Task/Bitwise-IO/Common-Lisp/bitwise-io-2.lisp new file mode 100644 index 0000000000..c3dc7ff2b3 --- /dev/null +++ b/Task/Bitwise-IO/Common-Lisp/bitwise-io-2.lisp @@ -0,0 +1,26 @@ +BITWISE-I/O> (bitwise-i/o-demo) + +Writing string to /tmp/demo.bin in packed 7→8 bits… +“Hello, World.” +String read back matches: +“Hello, World.” +NIL +BITWISE-I/O> (bitwise-i/o-demo :string "It doesn't, however, do UTF-7. So, no ☠ or 🙋") +Writing string to /tmp/demo.bin in packed 7→8 bits… +“It doesn't, however, do UTF-7. So, no ☠ or 🙋” + +STRING must contain only ASCII (7-bit) characters; +“It doesn't, however, do UTF-7. So, no ☠ or 🙋” +…contains non-ASCII characters: + • ☠ — #\SKULL_AND_CROSSBONES + • 🙋 — #\HAPPY_PERSON_RAISING_ONE_HAND + [Condition of type SIMPLE-ERROR] + + +Restarts: + 0: [CONTINUE] Retry assertion with new value for STRING. + 1: [RETRY] Retry SLIME REPL evaluation request. + 2: [*ABORT] Return to SLIME's top level. + 3: [ABORT] abort thread (#) + +⇒ ABORT diff --git a/Task/Bitwise-IO/Nim/bitwise-io.nim b/Task/Bitwise-IO/Nim/bitwise-io.nim new file mode 100644 index 0000000000..ccee665c9f --- /dev/null +++ b/Task/Bitwise-IO/Nim/bitwise-io.nim @@ -0,0 +1,94 @@ +type + BitWriter * = tuple + file: File + bits: uint8 + nRemain: int + + BitReader * = tuple + file: File + bits: uint8 + nRemain: int + nRead: int + +proc newBitWriter * (file: File) : ref BitWriter = + result = new BitWriter + result.file = file + result.bits = 0 + result.nRemain = 8 + +proc flushBits (stream : ref BitWriter) = + discard stream.file.writeBuffer(stream.bits.addr, 1) + stream.nRemain = 8 + stream.bits = 0 + +proc write * (stream: ref BitWriter, bits: uint8, nBits: int) = + assert(nBits <= 8) + + for ii in countdown((nBits - 1), 0) : + stream.bits = (stream.bits shl 1) or ((bits shr ii) and 1) + stream.nRemain.dec(1) + if stream.nRemain == 0: + stream.flushBits + +proc flush * (stream: ref BitWriter) = + if stream.nRemain < 8: + stream.bits = stream.bits shl stream.nRemain + stream.flushBits + +proc newBitReader * (file: File) : ref BitReader = + result = new BitReader + result.file = file + result.bits = 0 + result.nRemain = 0 + result.nRead = 0 + +proc read * (stream: ref BitReader, nBits: int) : uint8 = + assert(nBits <= 8) + + result = 0 + for ii in 0 .. < nBits : + if stream.nRemain == 0: + stream.nRead = stream.file.readBuffer(stream.bits.addr, 1) + if stream.nRead == 0: + break + stream.nRemain = 8 + + result = (result shl 1) or ((stream.bits shr 7) and 1) + + stream.bits = stream.bits shl 1 + stream.nRemain.dec(1) + + +when isMainModule: + var + file: File + writer: ref BitWriter + reader: ref BitReader + + file = open("testfile.dat", fmWrite) + writer = newBitWriter(file) + + for ii in 0 .. 255: + writer.write(ii.uint8, 7) + + writer.flush + file.close + + var dataCtr = 0 + + file = open("testfile.dat", fmRead) + reader = newBitReader(file) + + while true: + let aByte = reader.read(7) + + if reader.nRead == 0: + break + + assert((dataCtr and 0x7f).uint8 == aByte) + + assert(dataCtr == 256) + + file.close + + echo "OK" diff --git a/Task/Bitwise-IO/Perl-6/bitwise-io.pl6 b/Task/Bitwise-IO/Perl-6/bitwise-io.pl6 index ac1a1eeb11..84da19a2e2 100644 --- a/Task/Bitwise-IO/Perl-6/bitwise-io.pl6 +++ b/Task/Bitwise-IO/Perl-6/bitwise-io.pl6 @@ -1,11 +1,11 @@ sub encode-ascii(Str $s) { - my @b = $s.ords».fmt("%07b")».comb; + my @b = flat $s.ords».fmt("%07b")».comb; @b.push(0) until @b %% 8; # padding Buf.new: gather while @b { take reduce * *2+*, (@b.pop for ^8) } } sub decode-ascii(Buf $b) { - my @b = $b.list».fmt("%08b")».comb; + my @b = flat $b.list».fmt("%08b")».comb; @b.shift until @b %% 7; # remove padding @b = gather while @b { take reduce * *2+*, (@b.pop for ^7) } return [~] @b».chr; diff --git a/Task/Bitwise-IO/REXX/bitwise-io.rexx b/Task/Bitwise-IO/REXX/bitwise-io-1.rexx similarity index 100% rename from Task/Bitwise-IO/REXX/bitwise-io.rexx rename to Task/Bitwise-IO/REXX/bitwise-io-1.rexx diff --git a/Task/Bitwise-IO/REXX/bitwise-io-2.rexx b/Task/Bitwise-IO/REXX/bitwise-io-2.rexx new file mode 100644 index 0000000000..870a1f46ca --- /dev/null +++ b/Task/Bitwise-IO/REXX/bitwise-io-2.rexx @@ -0,0 +1,15 @@ +/*REXX pgm encodes/decodes/displays ASCII character strings as (7─bits) binary string.*/ +parse arg $; if $=='' then $='STRING' /*get optional argument; Use default ? */ +say ' input string=' $ /*display the input string to terminal.*/ +out=comp($); say ' encoded string=' out /*encode─► 7─bit binary string; display*/ +ori=dcomp(out); say ' decoded string=' ori /*decode─► 8─bit char " ; " */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +comp: parse arg x; z=; do j=1 for length(x) /*convert─►right-justified 7-bit binary*/ + z=z || right( x2b( c2x( substr(x, j, 1) )), 7) + end /*j*/; return left(z,length(z)+(8-length(z)//8)//8,0) +/*──────────────────────────────────────────────────────────────────────────────────────*/ +dcomp: parse arg x; z=; do k=1 by 7 to length(x); _=substr(x, k, 7) + if right(_, 1)==' ' then leave + z=z || x2c( b2x(0 || _) ) + end /*k*/; return z diff --git a/Task/Bitwise-IO/Zkl/bitwise-io-1.zkl b/Task/Bitwise-IO/Zkl/bitwise-io-1.zkl new file mode 100644 index 0000000000..157b160dd5 --- /dev/null +++ b/Task/Bitwise-IO/Zkl/bitwise-io-1.zkl @@ -0,0 +1,13 @@ + // stream of numBits sized ints to bytes, numBits<8 +fcn toBytes(n,[(numBits,acc,bitsSoFar)]state){ + acc=acc.shiftLeft(numBits) + n; bitsSoFar+=numBits; + reg r; + if(bitsSoFar>=8){ + bitsSoFar-=8; + r=acc.shiftRight(bitsSoFar); + acc=acc.bitAnd((-1).shiftLeft(bitsSoFar).bitNot()); + } + else r=Void.Skip; // need more bits to make a byte + state.clear(numBits,acc,bitsSoFar); + r +} diff --git a/Task/Bitwise-IO/Zkl/bitwise-io-2.zkl b/Task/Bitwise-IO/Zkl/bitwise-io-2.zkl new file mode 100644 index 0000000000..684f680ef7 --- /dev/null +++ b/Task/Bitwise-IO/Zkl/bitwise-io-2.zkl @@ -0,0 +1,7 @@ +ns:="THIS IS A TEST".pump(List,"toAsc",'-(0x20)); +ns.println(ns.len()); + +state:=L(6,0,0,L()); // input is six bits wide +cns:=ns.pump(List,toBytes.fp1(state)); // List could be a file or socket or ... +if(state[2]) cns+=toBytes(0,state); // flush +cns.println(cns.len()); diff --git a/Task/Bitwise-IO/Zkl/bitwise-io-3.zkl b/Task/Bitwise-IO/Zkl/bitwise-io-3.zkl new file mode 100644 index 0000000000..4a1b4fe95c --- /dev/null +++ b/Task/Bitwise-IO/Zkl/bitwise-io-3.zkl @@ -0,0 +1,12 @@ + // stream of bytes to numBits sized ints, 1=numBits){ + bitsSoFar-=numBits; + buf.append(acc.shiftRight(bitsSoFar)); + acc=acc.bitAnd((-1).shiftLeft(bitsSoFar).bitNot()); + } + state.clear(numBits,acc,bitsSoFar,buf); + return(Void.Write,Void.Write,buf); // append contents of buf to result +} diff --git a/Task/Bitwise-IO/Zkl/bitwise-io-4.zkl b/Task/Bitwise-IO/Zkl/bitwise-io-4.zkl new file mode 100644 index 0000000000..6fc9a813d1 --- /dev/null +++ b/Task/Bitwise-IO/Zkl/bitwise-io-4.zkl @@ -0,0 +1,4 @@ +state:=L(6,0,0,L()); // output is six bits wide +r:=cns.pump(List,fromBytes.fp1(state)); // cns could be a file or ... +r.println(r.len()); +r.pump(String,'+(0x20),"toChar").println(); diff --git a/Task/Bitwise-operations/360-Assembly/bitwise-operations.360 b/Task/Bitwise-operations/360-Assembly/bitwise-operations.360 new file mode 100644 index 0000000000..7253007bbf --- /dev/null +++ b/Task/Bitwise-operations/360-Assembly/bitwise-operations.360 @@ -0,0 +1,82 @@ +* Bitwise operations 15/02/2017 +BITWISE CSECT + USING BITWISE,R13 + B 72(R15) + DC 17F'0' + STM R14,R12,12(R13) + ST R13,4(R15) + ST R15,8(R13) + LR R13,R15 + L R1,A + XDECO R1,PG + MVC OP,=CL7'A=' + XPRNT OP,L'OP+L'PG + L R1,B + XDECO R1,PG + MVC OP,=CL7'B=' + XPRNT OP,L'OP+L'PG +* And + L R1,A + N R1,B + XDECO R1,PG + MVC OP,=C'A AND B' + XPRNT OP,L'OP+L'PG +* Or + L R1,A + O R1,B + XDECO R1,PG + MVC OP,=C'A OR B' + XPRNT OP,L'OP+L'PG +* Xor + L R1,A + X R1,B + XDECO R1,PG + MVC OP,=C'A XOR B' + XPRNT OP,L'OP+L'PG +* Not + L R1,A + X R1,=X'FFFFFFFF' not (by xor -1) + XDECO R1,PG + MVC OP,=CL7'NOT A' + XPRNT OP,L'OP+L'PG +* + MVC A,=X'80000008' a=-2147483640 (-2^31+8) + L R1,A + XDECO R1,PG + MVC OP,=CL7'A=' + XPRNT OP,L'OP+L'PG +* shift right arithmetic (on 31 bits) + L R1,A + SRA R1,3 + XDECO R1,PG + MVC OP,=C'A SRA 3' + XPRNT OP,L'OP+L'PG +* shift left arithmetic (on 31 bits) + L R1,A + SLA R1,3 + XDECO R1,PG + MVC OP,=C'A SLA 3' + XPRNT OP,L'OP+L'PG +* shift right logical (on 32 bits) + L R1,A + SRL R1,3 + XDECO R1,PG + MVC OP,=C'A SRL 3' + XPRNT OP,L'OP+L'PG +* shift left logical (on 32 bits) + L R1,A + SLL R1,3 + XDECO R1,PG + MVC OP,=C'A SLL 3' + XPRNT OP,L'OP+L'PG +* +RETURN L R13,4(0,R13) + LM R14,R12,12(R13) + XR R15,R15 + BR R14 +A DC F'21' +B DC F'3' +OP DS CL7 +PG DS CL12 + YREGS + END BITWISE diff --git a/Task/Bitwise-operations/ALGOL-W/bitwise-operations.alg b/Task/Bitwise-operations/ALGOL-W/bitwise-operations.alg new file mode 100644 index 0000000000..226a7dcdc5 --- /dev/null +++ b/Task/Bitwise-operations/ALGOL-W/bitwise-operations.alg @@ -0,0 +1,19 @@ +% performs bitwise and, or, not, left-shift and right shift on the integers n1 and n2 % +% Algol W does not have xor, arithmetic right shift, left rotate or right rotate % +procedure bitOperations ( integer value n1, n2 ) ; +begin + bits b1, b2; + % the Algol W bitwse operations operate on bits values, so we first convert the % + % integers to bits values using the builtin bitstring procedure % + % the results are converted back to integers using the builtin number procedure % + % all Algol W bits and integers are 32 bits quantities % + b1 := bitstring( n1 ); + b2 := bitstring( n2 ); + % perform the operaations and display the results as integers % + write( n1, " and ", n2, " = ", number( b1 and b2 ) ); + write( n1, " or ", n2, " = ", number( b1 or b2 ) ); + write( " " + , " not ", n1, " = ", number( not b1 ) ); + write( n1, " shl ", n2, " = ", number( b1 shl n2 ), " ( left-shift )" ); + write( n1, " shr ", n2, " = ", number( b1 shr n2 ), " ( right-shift )" ) +end bitOPerations ; diff --git a/Task/Bitwise-operations/BASIC/bitwise-operations-3.basic b/Task/Bitwise-operations/BASIC/bitwise-operations-3.basic new file mode 100644 index 0000000000..13dff32190 --- /dev/null +++ b/Task/Bitwise-operations/BASIC/bitwise-operations-3.basic @@ -0,0 +1,9 @@ + org 4084 +3a 83 40 ld a, (4083) +47 ld b, a +3a 82 40 ld a, (4082) +a0 and b +00 nop ; negate and shift instructions take 2 bytes +06 00 ld b, 0 +4f ld c, a ; value in BC reg pair is returned to BASIC +c9 ret diff --git a/Task/Bitwise-operations/BASIC/bitwise-operations-4.basic b/Task/Bitwise-operations/BASIC/bitwise-operations-4.basic new file mode 100644 index 0000000000..a6e00f56ab --- /dev/null +++ b/Task/Bitwise-operations/BASIC/bitwise-operations-4.basic @@ -0,0 +1,25 @@ + 10 REM ABCDEFGHIJKLMNO + 20 INPUT A + 30 INPUT B + 40 POKE 16514,A + 50 POKE 16515,B + 60 LET ADDR=16516 + 70 LET R$="3A8340473A8240A00006004FC9" + 80 POKE ADDR,CODE R$*16+CODE R$(2)-476 + 90 LET R$=R$(3 TO ) +100 LET ADDR=ADDR+1 +110 IF R$<>"" THEN GOTO 80 +120 PRINT A;" AND ";B;" = ";USR 16516 +130 POKE 16523,176 +140 PRINT A;" OR ";B;" = ";USR 16516 +150 POKE 16523,168 +160 PRINT A;" XOR ";B;" = ";USR 16516 +170 POKE 16523,237 +180 POKE 16524,68 +190 PRINT "NOT ";A;" = ";USR 16516 +200 POKE 16523,203 +210 POKE 16524,39 +220 FOR I=1 TO B +230 POKE 16514,USR 16516 +240 NEXT I +250 PRINT A;" << ";B;" = ";PEEK 16514 diff --git a/Task/Bitwise-operations/Beeswax/bitwise-operations-1.beeswax b/Task/Bitwise-operations/Beeswax/bitwise-operations-1.beeswax new file mode 100644 index 0000000000..26f9b5cd21 --- /dev/null +++ b/Task/Bitwise-operations/Beeswax/bitwise-operations-1.beeswax @@ -0,0 +1,25 @@ +#eX~T~T_# +###>N{` AND `~{~` = `&{Nz1~3J +UXe# +##>{` OR `~{~` = `|{Nz1~5J +UXe# +##>{` XOR `~{~` = `${Nz1~7J +UXe# +##>`NOT `{` = `!{Nz1~9J +UXe# +##>{` << `~{~` = `({Nz1~9PPJ +UXe# +##>{` >>> `~{~` = `){` (logical shift right)`N7F+M~1~J +UXe# +##>{` ROL `~{~` = `[{N7F+P~1~J +UXe# +##>{` ROR `~{~` = `]{NN8F+P~1~J +UXe# +##>`Arithmetic shift right is not originally implemented in beeswax.`N q + qN`,noitagen yb dezilaer eb nac srebmun evitagen rof RSA ,yllacinhcet tuB`N< +##>`logical shift right, and negating the result again:`NN7F++~1~J +UXe# #>e# + #>~1~[&'pUX{` >> `~{~` = `){` , interpreted as (positive) signed Int64 number (MSB=0), equivalent to >>>`NN; + ### + >UX`-`!P{M!` >> `~{~` = `!)!`-`M!{` , interpreted as (negative) signed Int64 number (MSB=1)`NN; + #>e# diff --git a/Task/Bitwise-operations/Beeswax/bitwise-operations-2.beeswax b/Task/Bitwise-operations/Beeswax/bitwise-operations-2.beeswax new file mode 100644 index 0000000000..38a701375b --- /dev/null +++ b/Task/Bitwise-operations/Beeswax/bitwise-operations-2.beeswax @@ -0,0 +1,19 @@ +julia> beeswax("Bitops.bswx",0,0.0,Int(20000)) +i9223653511831486512 +i48 + +9223653511831486512 AND 48 = 48 +9223653511831486512 OR 48 = 9223653511831486512 +9223653511831486512 XOR 48 = 9223653511831486464 +NOT 9223653511831486512 = 9223090561878065103 +9223653511831486512 << 48 = 13510798882111488 +9223653511831486512 >>> 48 = 32769 (logical shift right) +9223653511831486512 ROL 48 = 13651540665434112 +9223653511831486512 ROR 48 = 3178497 + +Arithmetic shift right is not originally implemented in beeswax. + +But technically, ASR for negative numbers can be realized by negation, +logical shift right, and negating the result again: + +-9223090561878065104 >> 48 = -32767 , interpreted as (negative) signed Int64 number (MSB=1) diff --git a/Task/Bitwise-operations/Beeswax/bitwise-operations-3.beeswax b/Task/Bitwise-operations/Beeswax/bitwise-operations-3.beeswax new file mode 100644 index 0000000000..91f733e890 --- /dev/null +++ b/Task/Bitwise-operations/Beeswax/bitwise-operations-3.beeswax @@ -0,0 +1 @@ +A>>B = NOT(NOT(A)>>>B) diff --git a/Task/Bitwise-operations/Beeswax/bitwise-operations-4.beeswax b/Task/Bitwise-operations/Beeswax/bitwise-operations-4.beeswax new file mode 100644 index 0000000000..8acaf88bcb --- /dev/null +++ b/Task/Bitwise-operations/Beeswax/bitwise-operations-4.beeswax @@ -0,0 +1,2 @@ +A ROL B = A<<(B%64)+A>>>(64-B%64) +A ROR B = A>>>(B%64)+A<<(64-B%64) diff --git a/Task/Bitwise-operations/Elena/bitwise-operations.elena b/Task/Bitwise-operations/Elena/bitwise-operations.elena index c6e8df547c..f32cfd3dde 100644 --- a/Task/Bitwise-operations/Elena/bitwise-operations.elena +++ b/Task/Bitwise-operations/Elena/bitwise-operations.elena @@ -1,20 +1,19 @@ -#import system. -#import extensions. +import extensions. -#class(extension) testOp +extension testOp { - #method bitwiseTest : y + bitwiseTest : y [ - console writeLine:self:" and ":y:" = ":(self and:y). - console writeLine:self:" or ":y:" = ":(self or:y). - console writeLine:self:" xor ":y:" = ":(self xor:y). - console writeLine:"not ":self:" = ":(self inverted). - console writeLine:self:" shr ":y:" = ":(self shift &index:y). - console writeLine:self:" shl ":y:" = ":(self shift &index:(y negative)). + console printLine(self," and ",y," = ",self and:y). + console printLine(self," or ",y," = ",self or:y). + console printLine(self," xor ",y," = ",self xor:y). + console printLine("not ",self," = ",self inverted). + console printLine(self," shr ",y," = ",self shiftRight:y). + console printLine(self," shl ",y," = ",self shiftLeft:y). ] } -#symbol program = +program = [ - console readLine:(Integer new) bitwiseTest:(console readLine:(Integer new)). + console readLineTo(Integer new); bitwiseTest(console readLineTo(Integer new)). ]. diff --git a/Task/Bitwise-operations/Haskell/bitwise-operations.hs b/Task/Bitwise-operations/Haskell/bitwise-operations.hs index 3e0939f3f3..1cdde7ddda 100644 --- a/Task/Bitwise-operations/Haskell/bitwise-operations.hs +++ b/Task/Bitwise-operations/Haskell/bitwise-operations.hs @@ -1,18 +1,24 @@ import Data.Bits bitwise :: Int -> Int -> IO () -bitwise a b = do - print $ a .&. b - print $ a .|. b - print $ a `xor` b - print $ complement a - print $ shiftL a b -- left shift - print $ shiftR a b -- arithmetic right shift - print $ shift a b -- You can also use the "unified" shift function; positive is for left shift, negative is for right shift - print $ shift a (-b) - print $ rotateL a b -- rotate left - print $ rotateR a b -- rotate right - print $ rotate a b -- You can also use the "unified" rotate function; positive is for left rotate, negative is for right rotate - print $ rotate a (-b) +bitwise a b = + mapM_ + print + [ a .&. b + , a .|. b + , a `xor` b + , complement a + , shiftL a b -- left shift + , shiftR a b -- arithmetic right shift + , shift a b -- You can also use the "unified" shift function; + -- positive is for left shift, negative is for right shift + , shift a (-b) + , rotateL a b -- rotate left + , rotateR a b -- rotate right + , rotate a b -- You can also use the "unified" rotate function; + -- positive is for left rotate, negative is for right rotate + , rotate a (-b) + ] +main :: IO () main = bitwise 255 170 diff --git a/Task/Bitwise-operations/Julia/bitwise-operations.julia b/Task/Bitwise-operations/Julia/bitwise-operations.julia new file mode 100644 index 0000000000..63de6eb100 --- /dev/null +++ b/Task/Bitwise-operations/Julia/bitwise-operations.julia @@ -0,0 +1,12 @@ +# Version 5.2 +@show 1 & 2 # AND +@show 1 | 2 # OR +@show 1 ^ 2 # XOR -- for Julia 6.0 the operator is `⊻` +@show ~1 # NOT +@show 1 >>> 2 # SHIFT RIGHT (LOGICAL) +@show 1 >> 2 # SHIFT RIGHT (ARITMETIC) +@show 1 << 2 # SHIFT LEFT (ARITMETIC/LOGICAL) + +A = BitArray([true, true, false, false, true]) +@show A ror(A,1) ror(A,2) ror(A,5) # ROTATION RIGHT +@show rol(A,1) rol(A,2) rol(A,5) # ROTATION LEFT diff --git a/Task/Bitwise-operations/Kotlin/bitwise-operations.kotlin b/Task/Bitwise-operations/Kotlin/bitwise-operations.kotlin new file mode 100644 index 0000000000..2b3f036cf1 --- /dev/null +++ b/Task/Bitwise-operations/Kotlin/bitwise-operations.kotlin @@ -0,0 +1,21 @@ +/* for symmetry with Kotlin's other binary bitwise operators + we wrap Java's 'rotate' methods as infix functions */ +infix fun Int.rol(distance: Int): Int = Integer.rotateLeft(this, distance) +infix fun Int.ror(distance: Int): Int = Integer.rotateRight(this, distance) + +fun main(args: Array) { + // inferred type of x and y is Int i.e. 32 bit signed integers + val x = 10 + val y = 2 + println("x = $x") + println("y = $y") + println("NOT x = ${x.inv()}") + println("x AND y = ${x and y}") + println("x OR y = ${x or y}") + println("x XOR y = ${x xor y}") + println("x SHL y = ${x shl y}") + println("x ASR y = ${x shr y}") // arithmetic shift right (sign bit filled) + println("x LSR y = ${x ushr y}") // logical shift right (zero filled) + println("x ROL y = ${x rol y}") + println("x ROR y = ${x ror y}") +} diff --git a/Task/Bitwise-operations/Maple/bitwise-operations.maple b/Task/Bitwise-operations/Maple/bitwise-operations.maple new file mode 100644 index 0000000000..9a34751959 --- /dev/null +++ b/Task/Bitwise-operations/Maple/bitwise-operations.maple @@ -0,0 +1,18 @@ +with(Bits): +bit:=proc(A,B) +local a,b,c,d,e,f,g,h,i,x,bitpow; +bitpow := 2^B: +a:=And(A,B); +b:=Not(A); +c:=Or(A,B); +d:=Xor(A,B); +#Left Shift +e:= irem(2*A,bitpow); +#Right Shift +f := iquo(A,2); +#Left Rotate +g:= irem(2*A,bitpow,'x')+x; +#Rightarithshift +i:= iquo(A,2)+bitpow/2*irem(A,bitpow/2); +return a,b,c,d,e,f,g,i; +end proc; diff --git a/Task/Bitwise-operations/OoRexx/bitwise-operations.rexx b/Task/Bitwise-operations/OoRexx/bitwise-operations.rexx new file mode 100644 index 0000000000..5fd0786ad8 --- /dev/null +++ b/Task/Bitwise-operations/OoRexx/bitwise-operations.rexx @@ -0,0 +1,20 @@ +/* ooRexx ************************************************************* +/ Bit Operations work as in Rexx (of course) +* Bit operations are performed up to the length of the shorter string. +* The rest of the longer string is copied to the result. +* ooRexx introduces the possibility to specify a padding character +* to be used for expanding the shorter string. +* 10.11.2012 Walter Pachl taken over from REXX and extended for ooRexx +**********************************************************************/ +a=21 +b=347 +Say ' a :'c2b(a) ' 'c2x(a) +Say ' b :'c2b(b) c2x(b) +Say 'bitand(a,b) :'c2b(bitand(a,b)) c2x(bitand(a,b)) +Say 'bitor(a,b) :'c2b(bitor(a,b)) c2x(bitor(a,b)) +Say 'bitxor(a,b) :'c2b(bitxor(a,b)) c2x(bitxor(a,b)) +p='11111111'B +Say 'ooRexx only:' +Say 'a~bitor(b,p):'c2b(a~bitor(b,p)) c2x(a~bitor(b,p)) +Exit +c2b: return x2b(c2x(arg(1))) diff --git a/Task/Bitwise-operations/Perl-6/bitwise-operations-1.pl6 b/Task/Bitwise-operations/Perl-6/bitwise-operations-1.pl6 deleted file mode 100644 index 2fb4be305e..0000000000 --- a/Task/Bitwise-operations/Perl-6/bitwise-operations-1.pl6 +++ /dev/null @@ -1,48 +0,0 @@ -sub bool ($a, $b) { - say 'Coerce to Boolean'; - say_bool_buff "$a and $b", $a ?& $b; - say_bool_buff "$a or $b", $a ?| $b; - say_bool_buff "$a xor $b", $a ?^ $b; - say_bool_buff "not $a", !$a; -} - -sub buf ($a, $b) { - say 'Coerce to Buffer'; - say_bool_buff "$a and $b", $a ~& $b; - say_bool_buff "$a or $b", $a ~| $b; - say_bool_buff "$a xor $b", $a ~^ $b; -# say_bool_buff "$a bit shift right $b", $a ~> $b; #NYI in Rakudo -# say_bool_buff "$a bit shift left $b", $a ~< $b; #NYI in Rakudo -} - -sub int ($a, $b) { - say 'Coerce to Int'; - say_bit "$a and $b", $a +& $b; - say_bit "$a or $b", $a +| $b; - say_bit "$a xor $b", $a +^ $b; - say_bit "$a signed bit shift right $b", $a +> $b; -# say_bit "$a unsigned bit shift right $b", $a +> $b :unsigned; #NYI in Rakudo -# say_bit "$a rotate right $b", $a +> $b :rotate; #NYI in Rakudo - say_bit "$a bit shift left $b", $a +< $b; -# say_bit "$a rotate shift left $b", $a +< $b :rotate; #NYI in Rakudo - say_bit "twos complement not $a", +^$a; - -} - -bool(7,2); -say '-' x 80; -buf(7,2); -say '-' x 80; -int(7,2); -say '-' x 80; - - -sub say_bit ($message, $value) { - my $INTSIZE = $*VM{'config'}{'intvalsize'} * 8; # hack to get native Int size - printf("%30s: %4d, %032b\n", $message, $value, $value) if $INTSIZE == 32; - printf("%30s: %4d, %064b\n", $message, $value, $value) if $INTSIZE == 64; -} - -sub say_bool_buff ($message, $value) { - printf("%30s: %4d, %s\n", $message, $value, $value); -} diff --git a/Task/Bitwise-operations/Perl-6/bitwise-operations-2.pl6 b/Task/Bitwise-operations/Perl-6/bitwise-operations-2.pl6 deleted file mode 100644 index a9598dd443..0000000000 --- a/Task/Bitwise-operations/Perl-6/bitwise-operations-2.pl6 +++ /dev/null @@ -1,30 +0,0 @@ -sub infix:( $a, $b, :$rotate, :$unsigned ) { - if $rotate { - my $INTSIZE = $*VM{'config'}{'intvalsize'} * 8; # hack to get native Int size - my $c = $b % $INTSIZE; - return pir::lsr__III($a, $c) +| pir::shl__III((2**$c-1) +& $a, $INTSIZE-$c); - } - if $unsigned { - return pir::lsr__III($a, $b); - } - pir::shr__III($a, $b); -} - -sub infix:( $a, $b, :$rotate, :$unsigned ) { - if $rotate { - my $INTSIZE = $*VM{'config'}{'intvalsize'} * 8; # hack to get native Int size - my $c = $b % $INTSIZE; - return pir::shl__III($a, $c) +| pir::lsr__III($a, $INTSIZE-$c); - } - pir::shl__III($a, $b); -} - -bs_int(7,2); - -sub bs_int ($a, $b) { - say_bit "$a Signed Bit shift right $b", $a bsr $b; - say_bit "$a Unsigned Bit shift right $b", infix:($a, $b, :unsigned); - say_bit "$a Rotate right $b", infix:($a, $b, :rotate); - say_bit "$a Bit shift left $b", $a bsl $b; - say_bit "$a Rotate left $b", infix:($a, $b, :rotate); -} diff --git a/Task/Bitwise-operations/Perl-6/bitwise-operations.pl6 b/Task/Bitwise-operations/Perl-6/bitwise-operations.pl6 index 0d6151252e..a7596faadb 100644 --- a/Task/Bitwise-operations/Perl-6/bitwise-operations.pl6 +++ b/Task/Bitwise-operations/Perl-6/bitwise-operations.pl6 @@ -3,7 +3,7 @@ constant BITS = MAXINT.base(2).chars; # define rotate ops for the fun of it multi sub infix:<⥁>(Int:D \a, Int:D \b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).list.rotate(b).reverse] } -multi sub infix:<⥀>(Int:D \a, Int:D \b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).reverse.rotate(b)] } +multi sub infix:<⥀>(Int:D \a, Int:D \b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).reverse.list.rotate(b)] } sub int-bits (Int $a, Int $b) { say ''; diff --git a/Task/Bitwise-operations/REXX/bitwise-operations.rexx b/Task/Bitwise-operations/REXX/bitwise-operations.rexx index ea27849cf6..e62e3ed38a 100644 --- a/Task/Bitwise-operations/REXX/bitwise-operations.rexx +++ b/Task/Bitwise-operations/REXX/bitwise-operations.rexx @@ -1,27 +1,23 @@ -/*REXX program performs bitwise operations on integers: & | && ¬ «L »R */ -numeric digits 1000 /*be able to handle some big integers. */ -say center('decimal', 9) center("value", 9) center('bits', 50) -say copies('─' , 9) copies("─" , 9) copies('─', 50) - -a = 21 ; call show a , 'A' /* show & tell A */ -b = 3 ; call show b , 'B' /* show & tell B */ - - call show bAnd(a,b) , 'A & B' /* and */ - call show bOr( a,b) , 'A | B' /* or */ - call show bXOr(a,b) , 'A && B' /* xor */ - call show bNot(a) , '¬ A' /* not */ - call show bShiftL(a,b) , 'A [«B]' /* shift left */ - call show bShiftR(a,b) , 'A [»B]' /* shirt right */ +/*REXX program performs bit─wise operations on integers: & | && ¬ «L »R */ +numeric digits 1000 /*be able to handle ginormous integers.*/ + say center('decimal', 9) center("value", 9) center('bits', 50) + say copies('─' , 9) copies("─" , 9) copies('─', 50) +a = 21 ; call show a , 'A' /* display A */ +b = 3 ; call show b , 'B' /* display B */ + call show bAnd(a, b) , 'A & B' /* and */ + call show bOr(a, b) , 'A | B' /* or */ + call show bXor(a, b) , 'A && B' /* xor */ + call show bNot(a) , '¬ A' /* not */ + call show bShiftL(a, b) , 'A [«B]' /* shift left */ + call show bShiftR(a, b) , 'A [»B]' /* shirt right */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -show: procedure; parse arg x,t; say right(x,9) center(t,9) right(d2b(x),50); return -d2b: return x2b(d2x(arg(1))) +0 /*some REXXes have the D2B BIF. */ -b2d: return x2d(b2x(arg(1))) /* " " " " B2D " */ -bNot: return b2d(translate(d2b(arg(1)), 10, 01)) +0 /*+0 ≡ normalizes the number*/ -bShiftL: return (b2d(d2b(arg(1)) || copies(0, arg(2)))) +0 /* " " " " " */ -bAnd: procedure; parse arg x,y; return c2d(bitand(d2c(x), d2c(y))) -bOr: procedure; parse arg x,y; return c2d(bitor( d2c(x), d2c(y))) -bXor: procedure; parse arg x,y; return c2d(bitxor(d2c(x), d2c(y))) -/*──────────────────────────────────────────────────────────────────────────────────────*/ -bShiftR: procedure; parse arg x,y; $=substr(reverse(d2b(x)), y+1) - if $=='' then $=0; return b2d(reverse($)) +show: say right( arg(1), 9) center( arg(2), 9) right( d2b( arg(1) ), 50); return +d2b: return x2b( d2x( arg(1) ) ) + 0 /*some REXXes have the D2B BIF. */ +b2d: return x2d( b2x( arg(1) ) ) /* " " " " B2D " */ +bNot: return b2d( translate( d2b( arg(1) ), 10, 01) ) +0 /*+0 ≡ normalizes a #.*/ +bShiftL: return b2d( d2b( arg(1) ) || copies(0, arg(2) ) ) +0 /* " " " " " */ +bAnd: return c2d( bitand( d2c( arg(1) ), d2c( arg(2) ) ) ) +bOr: return c2d( bitor( d2c( arg(1) ), d2c( arg(2) ) ) ) +bXor: return c2d( bitxor( d2c( arg(1) ), d2c( arg(2) ) ) ) +bShiftR: $=substr(reverse(d2b(arg(1))),arg(2)+1); if $='' then $=0; return b2d(reverse($)) diff --git a/Task/Bitwise-operations/Sidef/bitwise-operations.sidef b/Task/Bitwise-operations/Sidef/bitwise-operations.sidef index 4e17786922..f44685fc6c 100644 --- a/Task/Bitwise-operations/Sidef/bitwise-operations.sidef +++ b/Task/Bitwise-operations/Sidef/bitwise-operations.sidef @@ -1,15 +1,10 @@ func bitwise(a, b) { - - # Make sure they are integers - a.to_int!; - b.to_int!; - - say ('a and b : ', a & b); - say ('a or b : ', a | b); - say ('a xor b : ', a ^ b); - say ('not a : ', ~a); - say ('a << b : ', a << b); # left shift - say ('a >> b : ', a >> b); # arithmetic right shift + say ('a and b : ', a & b) + say ('a or b : ', a | b) + say ('a xor b : ', a ^ b) + say ('not a : ', ~a) + say ('a << b : ', a << b) # left shift + say ('a >> b : ', a >> b) # arithmetic right shift } bitwise(14,3) diff --git a/Task/Bitwise-operations/VBA/bitwise-operations-1.vba b/Task/Bitwise-operations/VBA/bitwise-operations-1.vba new file mode 100644 index 0000000000..8b61aca1e1 --- /dev/null +++ b/Task/Bitwise-operations/VBA/bitwise-operations-1.vba @@ -0,0 +1,6 @@ +Debug.Print Hex(&HF0F0 And &HFF00) 'F000 +Debug.Print Hex(&HF0F0 Or &HFF00) 'FFF0 +Debug.Print Hex(&HF0F0 Xor &HFF00) 'FF0 +Debug.Print Hex(Not &HF0F0) 'F0F +Debug.Print Hex(&HF0F0 Eqv &HFF00) 'F00F +Debug.Print Hex(&HF0F0 Imp &HFF00) 'FF0F diff --git a/Task/Bitwise-operations/VBA/bitwise-operations-2.vba b/Task/Bitwise-operations/VBA/bitwise-operations-2.vba new file mode 100644 index 0000000000..b8743b073d --- /dev/null +++ b/Task/Bitwise-operations/VBA/bitwise-operations-2.vba @@ -0,0 +1,79 @@ +Function MaskL(k As Integer) As Long + If k < 1 Then + MaskL = 0 + ElseIf k > 31 Then + MaskL = -1 + Else + MaskL = (-1) Xor (2 ^ (32 - k) - 1) + End If +End Function +Function MaskR(k As Integer) As Long + If k < 1 Then + MaskR = 0 + ElseIf k > 31 Then + MaskR = -1 + Else + MaskR = 2 ^ k - 1 + End If +End Function +Function Bit(k As Integer) As Long + If k < 0 Or k > 31 Then + Bit = 0 + ElseIf k = 31 Then + Bit = MaskL(1) + Else + Bit = 2 ^ k + End If +End Function +Function ShiftL(n As Long, k As Integer) As Long + If k = 0 Then + ShiftL = n + ElseIf k > 31 Then + ShiftL = 0 + ElseIf k < 0 Then + ShiftL = ShiftR(n, -k) + Else + ShiftL = (n And MaskR(31 - k)) * 2 ^ k + If (n And Bit(31 - k)) <> 0 Then ShiftL = ShiftL Or MaskL(1) + End If +End Function +Function ShiftR(n As Long, k As Integer) As Long + If k = 0 Then + ShiftR = n + ElseIf k > 31 Then + ShiftR = 0 + ElseIf k < 0 Then + ShiftR = ShiftL(n, -k) + Else + ShiftR = (n And MaskR(31)) \ 2 ^ k + If (n And MaskL(1)) <> 0 Then ShiftR = ShiftR Or Bit(31 - k) + End If +End Function +Function RotateL(n As Long, k As Integer) As Long + k = (32768 + k) Mod 32 + If k = 0 Then + RotateL = n + Else + RotateL = ShiftL(n, k) Or ShiftR(n, 32 - k) + End If +End Function +Function RotateR(n As Long, k As Integer) As Long + k = (32768 + k) Mod 32 + If k = 0 Then + RotateR = n + Else + RotateR = ShiftR(n, k) Or ShiftL(n, 32 - k) + End If +End Function +Function ClearBit(n As Long, k As Integer) As Long + ClearBit = n And Not Bit(k) +End Function +Function SetBit(n As Long, k As Integer) As Long + SetBit = n Or Bit(k) +End Function +Function SwitchBit(n As Long, k As Integer) As Long + SwitchBit = n Xor Bit(k) +End Function +Function TestBit(n As Long, k As Integer) As Boolean + TestBit = (n And Bit(k)) <> 0 +End Function diff --git a/Task/Bitwise-operations/VBA/bitwise-operations-3.vba b/Task/Bitwise-operations/VBA/bitwise-operations-3.vba new file mode 100644 index 0000000000..6d16faa33c --- /dev/null +++ b/Task/Bitwise-operations/VBA/bitwise-operations-3.vba @@ -0,0 +1,11 @@ +Debug.Print Hex(MaskL(8)) 'FF000000 +Debug.Print Hex(MaskR(8)) 'FF +Debug.Print Hex(Bit(7)) '80 +Debug.Print Hex(ShiftL(-1, 8)) 'FFFFFF00 +Debug.Print Hex(ShiftL(-1, -8)) 'FFFFFF +Debug.Print Hex(ShiftR(-1, 8)) 'FFFFFF +Debug.Print Hex(ShiftR(-1, -8)) 'FFFFFF00 +Debug.Print Hex(RotateL(65535, 8)) 'FFFF00 +Debug.Print Hex(RotateL(65535, -8)) 'FF0000FF +Debug.Print Hex(RotateR(65535, 8)) 'FF0000FF +Debug.Print Hex(RotateR(65535, -8)) 'FFFF00 diff --git a/Task/Bitwise-operations/X86-Assembly/bitwise-operations.x86 b/Task/Bitwise-operations/X86-Assembly/bitwise-operations.x86 new file mode 100644 index 0000000000..d37c92da00 --- /dev/null +++ b/Task/Bitwise-operations/X86-Assembly/bitwise-operations.x86 @@ -0,0 +1,104 @@ + extern printf + global main + + section .text +main + mov eax, dword [_a] + mov ecx, dword [_b] + push ecx + push eax + + and eax, ecx + mov ebx, _opand + call out_ops + + call get_nums + or eax, ecx + mov ebx, _opor + call out_ops + + call get_nums + xor eax, ecx + mov ebx, _opxor + call out_ops + + call get_nums + shr eax, cl + mov ebx, _opshr + call out_ops + + call get_nums + shl eax, cl + mov ebx, _opshl + call out_ops + + call get_nums + rol eax, cl + mov ebx, _oprol + call out_ops + + call get_nums + ror eax, cl + mov ebx, _opror + call out_ops + + call get_nums + sal eax, cl + mov ebx, _opsal + call out_ops + + call get_nums + sar eax, cl + mov ebx, _opsar + call out_ops + + mov eax, dword [esp+0] + not eax + push eax + not eax + push eax + push _opnot + push _null + push _testn + call printf + add esp, 20 + + add esp, 8 + ret + +out_ops + push eax + push ecx + push ebx + push dword [_a] + push _test + call printf + add esp, 20 + ret + +get_nums + mov eax, dword [esp+4] + mov ecx, dword [esp+8] + ret + + section .data + +_a dd 11 +_b dd 3 + + section .rodata +_test db '%08x %s %08x = %08x', 10, 0 +_testn db '%08s %s %08x = %08x', 10, 0 +_opand db 'and', 0 +_opor db 'or ', 0 +_opxor db 'xor', 0 +_opshl db 'shl', 0 +_opshr db 'shr', 0 +_opror db 'ror', 0 +_oprol db 'rol', 0 +_opnot db 'not', 0 +_opsal db 'sal', 0 +_opsar db 'sar', 0 +_null db 0 + + end diff --git a/Task/Bitwise-operations/XLISP/bitwise-operations.xlisp b/Task/Bitwise-operations/XLISP/bitwise-operations.xlisp new file mode 100644 index 0000000000..c76e22d837 --- /dev/null +++ b/Task/Bitwise-operations/XLISP/bitwise-operations.xlisp @@ -0,0 +1,8 @@ +(defun bitwise-operations (a b) + ; rotate operations are not supported + (print `(,a and ,b = ,(logand a b))) + (print `(,a or ,b = ,(logior a b))) + (print `(,a xor ,b = ,(logxor a b))) + (print `(,a left shift by ,b = ,(lsh a b))) + (print `(,a right shift by ,b = ,(lsh a (- b)))) ; negative second operand shifts right + (print `(,a arithmetic right shift by ,b = ,(ash a (- b)))) ) diff --git a/Task/Bitwise-operations/Zkl/bitwise-operations.zkl b/Task/Bitwise-operations/Zkl/bitwise-operations.zkl new file mode 100644 index 0000000000..877cbcc646 --- /dev/null +++ b/Task/Bitwise-operations/Zkl/bitwise-operations.zkl @@ -0,0 +1,8 @@ +(7).bitAnd(1) //-->1 +(8).bitOr(1) //-->9 +(7).bitXor(1) //-->6 +(1).bitNot() : "%,x".fmt(_) //-->ff|ff|ff|ff|ff|ff|ff|fe +(7).shiftRight(1) //-->3 +(7).shiftLeft(1) //-->0xe +(-1).toString(16) //-->ffffffffffffffff +(-1).shiftRight(1).toString(16) //-->7fffffffffffffff diff --git a/Task/Boolean-values/BASIC/boolean-values.basic b/Task/Boolean-values/BASIC/boolean-values-1.basic similarity index 100% rename from Task/Boolean-values/BASIC/boolean-values.basic rename to Task/Boolean-values/BASIC/boolean-values-1.basic diff --git a/Task/Boolean-values/BASIC/boolean-values-2.basic b/Task/Boolean-values/BASIC/boolean-values-2.basic new file mode 100644 index 0000000000..cb9d4e22b8 --- /dev/null +++ b/Task/Boolean-values/BASIC/boolean-values-2.basic @@ -0,0 +1,8 @@ +' Boolean TRUE and FALSE are non-zero and zero constants +a = TRUE +b = FALSE +PRINT a, ", ", b + +IF 0 THEN PRINT "TRUE" : ELSE PRINT "FALSE" +IF 1 THEN PRINT "TRUE" +IF 2 THEN PRINT "TRUE" diff --git a/Task/Boolean-values/Elm/boolean-values.elm b/Task/Boolean-values/Elm/boolean-values.elm new file mode 100644 index 0000000000..a755c9d8ad --- /dev/null +++ b/Task/Boolean-values/Elm/boolean-values.elm @@ -0,0 +1,44 @@ +--True and False directly represent Boolean values in Elm +--For eg to show yes for true and no for false +if True then "yes" else "no" + +--Same expression differently +if False then "no" else "yes" + +--This you can run as a program +--Elm allows you to take anything you want for representation +--In the program we take T for true F for false +import Html exposing(text,div,Html) +import Html.Attributes exposing(style) + +type Expr = T | F | And Expr Expr | Or Expr Expr | Not Expr + +evaluate : Expr->Bool +evaluate expression = + case expression of + T -> + True + + F -> + False + + And expr1 expr2 -> + evaluate expr1 && evaluate expr2 + + Or expr1 expr2 -> + evaluate expr1 || evaluate expr2 + + Not expr -> + not (evaluate expr) + +--CHECKING RANDOM LOGICAL EXPRESSIONS +ex1= Not F +ex2= And T F +ex3= And (Not(Or T F)) T + +main = + div [] (List.map display [ex1, ex2, ex3]) + +display expr= + div [] [ text ( toString expr ++ "-->" ++ toString(evaluate expr) ) ] +--END diff --git a/Task/Boolean-values/Fortran/boolean-values-1.f b/Task/Boolean-values/Fortran/boolean-values-1.f new file mode 100644 index 0000000000..1c94d0ae23 --- /dev/null +++ b/Task/Boolean-values/Fortran/boolean-values-1.f @@ -0,0 +1,5 @@ + TYPE MIXED + LOGICAL*1 LIVE + REAL*8 VALUE + END TYPE MIXED + TYPE(MIXED) STUFF(100) diff --git a/Task/Boolean-values/Fortran/boolean-values-2.f b/Task/Boolean-values/Fortran/boolean-values-2.f new file mode 100644 index 0000000000..5b79c4b80e --- /dev/null +++ b/Task/Boolean-values/Fortran/boolean-values-2.f @@ -0,0 +1,5 @@ + TYPE MIXED + LOGICAL*1 LIVE(100) + REAL*8 VALUE(100) + END TYPE MIXED + TYPE(MIXED) STUFF diff --git a/Task/Boolean-values/Gambas/boolean-values.gambas b/Task/Boolean-values/Gambas/boolean-values.gambas new file mode 100644 index 0000000000..64271f17f1 --- /dev/null +++ b/Task/Boolean-values/Gambas/boolean-values.gambas @@ -0,0 +1,8 @@ +Public Sub Main() +Dim bX As Boolean + +Print bX +bX = True +Print bX + +End diff --git a/Task/Boolean-values/Zkl/boolean-values.zkl b/Task/Boolean-values/Zkl/boolean-values.zkl new file mode 100644 index 0000000000..8bebdc5c8e --- /dev/null +++ b/Task/Boolean-values/Zkl/boolean-values.zkl @@ -0,0 +1,3 @@ +a:=True; +b:=False; +True.dir(); diff --git a/Task/Box-the-compass/AppleScript/box-the-compass.applescript b/Task/Box-the-compass/AppleScript/box-the-compass.applescript index b1378d5285..8bf743e8ee 100644 --- a/Task/Box-the-compass/AppleScript/box-the-compass.applescript +++ b/Task/Box-the-compass/AppleScript/box-the-compass.applescript @@ -1,6 +1,8 @@ use framework "Foundation" use scripting additions +-- BOXING THE COMPASS -------------------------------------------------------- + property plstLangs : [{|name|:"English"} & ¬ {expansions:{N:"north", S:"south", E:"east", W:"west", b:" by "}} & ¬ {|N|:"N", |NNNE|:"NbE", |NNE|:"N-NE", |NNENE|:"NEbN", |NE|:"NE", |NENEE|:"NEbE"} & ¬ @@ -34,14 +36,15 @@ on compassKeys(intDepth) -- Necessity drives recursive subdivision of broader directions, shrinking -- boxes down to a workable level of precision: script subdivision - on lambda(lstCompass, N) + on |λ|(lstCompass, N) if N ≤ 1 then lstCompass else script subKeys - on lambda(a, x, i, xs) + on |λ|(a, x, i, xs) -- Borders between N and S engender E and W. - -- further subdivisions (boxes) concatenate their two parent keys. + -- further subdivisions (boxes) + -- concatenate their two parent keys. if i > 1 then cond(N = intDepth, ¬ a & {cond(x = "N", "W", "E")} & x, ¬ @@ -49,21 +52,22 @@ on compassKeys(intDepth) else a & x end if - end lambda + end |λ| end script - lambda(foldl(subKeys, {}, lstCompass), N - 1) + |λ|(foldl(subKeys, {}, lstCompass), N - 1) end if - end lambda + end |λ| end script - tell subdivision to items 1 thru -2 of lambda(urCompass, intDepth) + tell subdivision to items 1 thru -2 of |λ|(urCompass, intDepth) end compassKeys -- pointIndex :: Int -> Num -> String on pointIndex(power, degrees) set nBoxes to 2 ^ power - set i to round (degrees + (360 / (nBoxes * 2))) mod 360 * nBoxes / 360 rounding up + set i to round (degrees + (360 / (nBoxes * 2))) ¬ + mod 360 * nBoxes / 360 rounding up cond(i > 0, i, 1) end pointIndex @@ -72,7 +76,7 @@ on pointNames(precision, iBox) set k to item iBox of compassKeys(precision) script translation - on lambda(recLang) + on |λ|(recLang) set maybeTrans to keyValue(recLang, k) set strBrief to cond(maybeTrans is missing value, k, maybeTrans) @@ -80,10 +84,10 @@ on pointNames(precision, iBox) if recExpand is not missing value then script expand - on lambda(c) + on |λ|(c) set t to keyValue(recExpand, c) cond(t is not missing value, t, c) - end lambda + end |λ| end script set strName to (intercalate(cond(precision > 5, " ", ""), ¬ map(expand, characters of strBrief))) @@ -91,7 +95,7 @@ on pointNames(precision, iBox) else strBrief end if - end lambda + end |λ| end script map(translation, plstLangs) @@ -99,15 +103,7 @@ end pointNames -- maxLen :: [String] -> Int on maxLen(xs) - -- compareByLength = (String, String) -> (-1 | 0 | 1) - script compareByLength - on lambda(a, b) - set {intA, intB} to {length of a, length of b} - cond(intA < intB, -1, cond(intA > intB, 1, 0)) - end lambda - end script - - length of maximumBy(compareByLength, xs) + length of maximumBy(comparing(my |length|), xs) end maxLen -- alignRight :: Int -> String -> String @@ -136,43 +132,43 @@ on compassTable(precision, xs) set join to curry(my intercalate) -- INDEX COLUMN - set lstIndex to map(lambda(precision) of curry(pointIndex), xs) + set lstIndex to map(|λ|(precision) of curry(pointIndex), xs) set lstStrIndex to map(show, lstIndex) set nIndexWidth to maxLen(lstStrIndex) - set colIndex to map(lambda(nIndexWidth + intPad) of rightAligned, lstStrIndex) + set colIndex to map(|λ|(nIndexWidth + intPad) of rightAligned, lstStrIndex) -- ANGLES COLUMN script degreeFormat - on lambda(x) + on |λ|(x) set {c, m} to splitOn(".", x as string) c & "." & (text 1 thru 2 of (m & "0")) & "°" - end lambda + end |λ| end script set lstAngles to map(degreeFormat, xs) set nAngleWidth to maxLen(lstAngles) + intPad - set colAngles to map(lambda(nAngleWidth) of rightAligned, lstAngles) + set colAngles to map(|λ|(nAngleWidth) of rightAligned, lstAngles) -- NAMES COLUMNS script precisionNames - on lambda(iBox) + on |λ|(iBox) pointNames(precision, iBox) - end lambda + end |λ| end script set lstTrans to transpose(map(precisionNames, lstIndex)) set lstTransWidths to map(maxLen, lstTrans) script spacedNames - on lambda(lstLang, i) - map(lambda((item i of lstTransWidths) + 2) of leftAligned, lstLang) - end lambda + on |λ|(lstLang, i) + map(|λ|((item i of lstTransWidths) + 2) of leftAligned, lstLang) + end |λ| end script set colsTrans to map(spacedNames, lstTrans) -- TABLE intercalate(linefeed, ¬ - map(lambda("") of join, ¬ + map(|λ|("") of join, ¬ transpose({colIndex} & {colAngles} & ¬ {replicate(length of lstIndex, " ")} & colsTrans))) end if @@ -180,9 +176,8 @@ end compassTable --- TEST +-- TEST ---------------------------------------------------------------------- on run - set xs to [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, ¬ @@ -196,23 +191,52 @@ on run -- to substitute for missing names for very finely divided boxes. compassTable(5, xs) -- // 2^5 -> 32 boxes - end run --- GENERIC FUNCTIONS +-- GENERIC FUNCTIONS --------------------------------------------------------- --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map +-- comparing :: (a -> b) -> (a -> a -> Ordering) +on comparing(f) + set mf to mReturn(f) + script + on |λ|(a, b) + set x to mf's |λ|(a) + set y to mf's |λ|(b) + if x < y then + -1 + else + if x > y then + 1 + else + 0 + end if + end if + end |λ| + end script +end comparing + +-- cond :: Bool -> a -> a -> a +on cond(bool, f, g) + if bool then + f + else + g + end if +end cond + +-- curry :: (Script|Handler) -> Script +on curry(f) + script + on |λ|(a) + script + on |λ|(b) + |λ|(a, b) of mReturn(f) + end |λ| + end script + end |λ| + end script +end curry -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) @@ -220,66 +244,12 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl --- curry :: (Script|Handler) -> Script -on curry(f) - script - on lambda(a) - script - on lambda(b) - lambda(a, b) of mReturn(f) - end lambda - end script - end lambda - end script -end curry - --- transpose :: [[a]] -> [[a]] -on transpose(xss) - script column - on lambda(_, iCol) - script row - on lambda(xs) - item iCol of xs - end lambda - end script - - map(row, xss) - end lambda - end script - - map(column, item 1 of xss) -end transpose - --- maximumBy :: (a -> a -> Ordering) -> [a] -> a -on maximumBy(f, xs) - set cmp to mReturn(f) - script max - on lambda(a, b) - if a is missing value or cmp's lambda(a, b) < 0 then - b - else - a - end if - end lambda - end script - - foldl(max, missing value, xs) -end maximumBy - --- splitOn :: Text -> Text -> [Text] -on splitOn(strDelim, strMain) - set {dlm, my text item delimiters} to {my text item delimiters, strDelim} - set xs to text items of strMain - set my text item delimiters to dlm - return xs -end splitOn - -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} @@ -288,39 +258,6 @@ on intercalate(strText, lstText) return strJoined end intercalate --- keyValue :: Record -> String -> Maybe String -on keyValue(rec, strKey) - set ca to current application - set v to (ca's NSDictionary's dictionaryWithDictionary:rec)'s objectForKey:strKey - if v is not missing value then - item 1 of ((ca's NSArray's arrayWithObject:v) as list) - else - missing value - end if -end keyValue - --- toLower :: String -> String -on toLower(str) - set ca to current application - ((ca's NSString's stringWithString:(str))'s ¬ - lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text -end toLower - --- toUpper :: String -> String -on toUpper(str) - set ca to current application - ((ca's NSString's stringWithString:(str))'s ¬ - uppercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text -end toUpper - --- toTitle :: String -> String -on toTitle(str) - set ca to current application - ((ca's NSString's stringWithString:(str))'s ¬ - capitalizedStringWithLocale:(ca's NSLocale's currentLocale())) as text -end toTitle - - -- justifyLeft :: Int -> Char -> Text -> Text on justifyLeft(N, cFiller, strText) if N > length of strText then @@ -339,6 +276,62 @@ on justifyRight(N, cFiller, strText) end if end justifyRight +-- keyValue :: Record -> String -> Maybe String +on keyValue(rec, strKey) + set ca to current application + set v to (ca's NSDictionary's dictionaryWithDictionary:rec)'s objectForKey:strKey + if v is not missing value then + item 1 of ((ca's NSArray's arrayWithObject:v) as list) + else + missing value + end if +end keyValue + +-- length :: [a] -> Int +on |length|(xs) + length of xs +end |length| + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- maximumBy :: (a -> a -> Ordering) -> [a] -> a +on maximumBy(f, xs) + set cmp to mReturn(f) + script max + on |λ|(a, b) + if a is missing value or cmp's |λ|(a, b) < 0 then + b + else + a + end if + end |λ| + end script + + foldl(max, missing value, xs) +end maximumBy + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + -- replicate :: Int -> a -> [a] on replicate(N, a) set out to {} @@ -353,23 +346,48 @@ on replicate(N, a) return out & dbl end replicate --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn +-- splitOn :: Text -> Text -> [Text] +on splitOn(strDelim, strMain) + set {dlm, my text item delimiters} to {my text item delimiters, strDelim} + set xs to text items of strMain + set my text item delimiters to dlm + return xs +end splitOn --- cond :: Bool -> a -> a -> a -on cond(bool, f, g) - if bool then - f - else - g - end if -end cond +-- transpose :: [[a]] -> [[a]] +on transpose(xss) + script column + on |λ|(_, iCol) + script row + on |λ|(xs) + item iCol of xs + end |λ| + end script + + map(row, xss) + end |λ| + end script + + map(column, item 1 of xss) +end transpose + +-- toLower :: String -> String +on toLower(str) + set ca to current application + ((ca's NSString's stringWithString:(str))'s ¬ + lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text +end toLower + +-- toTitle :: String -> String +on toTitle(str) + set ca to current application + ((ca's NSString's stringWithString:(str))'s ¬ + capitalizedStringWithLocale:(ca's NSLocale's currentLocale())) as text +end toTitle + +-- toUpper :: String -> String +on toUpper(str) + set ca to current application + ((ca's NSString's stringWithString:(str))'s ¬ + uppercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text +end toUpper diff --git a/Task/Box-the-compass/Elixir/box-the-compass.elixir b/Task/Box-the-compass/Elixir/box-the-compass.elixir index 7ef7588e1b..6323ed3f93 100644 --- a/Task/Box-the-compass/Elixir/box-the-compass.elixir +++ b/Task/Box-the-compass/Elixir/box-the-compass.elixir @@ -8,10 +8,11 @@ defmodule Box do end) |> Enum.with_index |> Enum.map(fn {s, i} -> {i+1, String.capitalize(s)} end) + |> Map.new end def compass do - header = Enum.into(head, Map.new) + header = head() angles = Enum.map(0..32, fn i -> i * 11.25 + elem({0, 5.62, -5.62}, rem(i, 3)) end) Enum.each(angles, fn degrees -> index = rem(round(32 * degrees / 360), 32) + 1 diff --git a/Task/Box-the-compass/Gambas/box-the-compass.gambas b/Task/Box-the-compass/Gambas/box-the-compass.gambas new file mode 100644 index 0000000000..a10ca7512f --- /dev/null +++ b/Task/Box-the-compass/Gambas/box-the-compass.gambas @@ -0,0 +1,19 @@ +Public Sub Main() +Dim fDeg As Float[] = [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] +Dim cHeading As Collection = ["N": "North", "S": "South", "W": "West", "E": "East", "b": "by"] +Dim sHeading As String[] = ["N", "NbE", "NNE", "NEbE", "NE", "NEbE", "ENE", "EbN", "E", "EbS", "ESE", "SEbE", "SE", "SEbS", "SSE", "SbE", "S", "SbW", "SSW", "SWbS", "SW", "SWbW", "WSW", "WbS", "W", "WbN", "WNW", "NWbW", "NW", "NWbN", "NNW", "NbW"] +Dim siLoop As Short +Dim sDirection As String +Dim fCount, fTemp As Float + +For Each fCount In fDeg + fTemp = Round(fCount / 11.25) + If fTemp = 32 Then fTemp = 0 + For siLoop = 0 To Len(sHeading[fTemp]) + sDirection &= cHeading[Mid(sHeading[fTemp], siLoop + 1, 1)] & " " + Next + Print "Index=" & Format(fTemp + 1, "#0") & " " & Format(Str(fCount), "##0.00") & " degrees = " & sDirection + sDirection = "" +Next + +End diff --git a/Task/Box-the-compass/Haskell/box-the-compass.hs b/Task/Box-the-compass/Haskell/box-the-compass.hs index 55dc5f70c6..7e16d0914e 100644 --- a/Task/Box-the-compass/Haskell/box-the-compass.hs +++ b/Task/Box-the-compass/Haskell/box-the-compass.hs @@ -1,25 +1,70 @@ -import Data.Char -import Data.Maybe -import Text.Printf +import Data.Char (toUpper) -dirs = ["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"] +import Data.Maybe (fromMaybe) --- Given an index between 0 and 31 return the corresponding compass point name. +import Text.Printf (PrintfType, printf) + +dirs :: [String] +dirs = + [ "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" + ] + +-- Index between 0 and 31 -> the corresponding compass point name. +pointName :: Int -> String pointName = capitalize . concatMap (fromMaybe "?" . fromChar) . (dirs !!) - where fromChar c = lookup c [('N', "north"), ('S', "south"), ('E', "east"), - ('W', "west"), ('b', " by "), ('-', "-")] - capitalize (c:cs) = toUpper c : cs + where + fromChar c = + lookup + c + [ ('N', "north") + , ('S', "south") + , ('E', "east") + , ('W', "west") + , ('b', " by ") + , ('-', "-") + ] + capitalize (c:cs) = toUpper c : cs --- Convert degrees to a compass point index between 0 and 31. -pointIndex d = (round (d*1000) + 5625) `mod` 360000 `div` 11250 +-- Degrees -> compass point index between 0 and 31. +pointIndex :: Double -> Int +pointIndex d = (round (d * 1000) + 5625) `mod` 360000 `div` 11250 -printPointName d = let deg = read d :: Double - idx = pointIndex deg - in printf "%2d %-18s %6.2f°\n" (idx+1) (pointName idx) deg +printPointName :: PrintfType t => String -> t +printPointName d = + let deg = read d :: Double + idx = pointIndex deg + in printf "%2d %-18s %6.2f°\n" (idx + 1) (pointName idx) deg -main = do - input <- getContents - mapM_ printPointName $ lines input +main :: IO () +main = mapM_ (printPointName . show) [0 .. 31] diff --git a/Task/Box-the-compass/Julia/box-the-compass.julia b/Task/Box-the-compass/Julia/box-the-compass.julia new file mode 100644 index 0000000000..b2fb2abce3 --- /dev/null +++ b/Task/Box-the-compass/Julia/box-the-compass.julia @@ -0,0 +1,26 @@ +# v0.6 + +function degree2compasspoint(d::Float64)::String + const MAJORS = ("north", "east", "south", "ovest", "north", "east", "south", "ovest") + const QUART1 = ("N", "N by E", "N-NE", "NE by N", "NE", "NE by E", "E-NE", "E by N") + const QUART2 = tuple((replace(p, "NE", "EN") for p in QUART1)...) + + d = (d % 360) + 360/64 + majorindex, minor = divrem(d, 90) + minorindex = div(minor * 4, 45) + majorindex += 1 + minorindex += 1 + p1, p2 = MAJORS[majorindex:majorindex+1] + if p1 in ("north", "south"); q = QUART1 + else q = QUART1 end + return titlecase(replace(replace(q[minorindex], 'N', p1), 'E', p2)) +end + +for i in 0:32 + d = i * 11.25 + m = i % 3 + if m == 1; d += 5.62 end + if m == 2; d -= 5.62 end + n = i % 32 + 1 + @printf("%2i %-17s %10.2f°\n", n, degree2compasspoint(d), d) +end diff --git a/Task/Box-the-compass/Kotlin/box-the-compass.kotlin b/Task/Box-the-compass/Kotlin/box-the-compass.kotlin new file mode 100644 index 0000000000..fa81c777ba --- /dev/null +++ b/Task/Box-the-compass/Kotlin/box-the-compass.kotlin @@ -0,0 +1,37 @@ +// version 1.1.2 + +fun expand(cp: String): String { + val sb = StringBuilder() + for (c in cp) { + sb.append(when (c) { + 'N' -> "north" + 'E' -> "east" + 'S' -> "south" + 'W' -> "west" + 'b' -> " by " + else -> "-" + }) + } + return sb.toString().capitalize() +} + +fun main(args: Array) { + val cp = arrayOf( + "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" + ) + println("Index Degrees Compass point") + println("----- ------- -------------") + val f = "%2d %6.2f %s" + for (i in 0..32) { + val index = i % 32 + var heading = i * 11.25 + when (i % 3) { + 1 -> heading += 5.62 + 2 -> heading -= 5.62 + } + println(f.format(index + 1, heading, expand(cp[index]))) + } +} diff --git a/Task/Box-the-compass/Smart-BASIC/box-the-compass.smart b/Task/Box-the-compass/Smart-BASIC/box-the-compass.smart new file mode 100644 index 0000000000..db6531dc09 --- /dev/null +++ b/Task/Box-the-compass/Smart-BASIC/box-the-compass.smart @@ -0,0 +1,36 @@ +/*Boxing The Compass by rbytes December 2017*/ +GET SCREEN SIZE sw,sh +OPTION BASE 1 +DIM point$(32,5) +FOR i=1 TO 32 +FOR j=1 TO 5 +READ point$(i,j) +NEXT j +NEXT i +html$= "" +html$&= "" +FOR i =1 TO 32 + html$&= "" +NEXT i +html$&= "
    Boxing The CompassAbbrMinMedMax
    "&i&""&point$(i,1)&""&point$(i,2)&""&point$(i,3)&""&point$(i,4)&""&point$(i,5)&"
    " +BROWSER "compass" AT 0,0 SIZE sw-20,sh-20 +BROWSER "compass" TEXT html$ +PAUSE 20 +END + +DATA "North", "N", "354.38", "0", "5.62", "North by east", "NbE", "5.63", "11.25", "16.87" +DATA "North-northeast", "NNE", "16.88", "22.50", "28.12", "Northeast by north", "NEbN", "28.13", "33.75", "39.37" +DATA "Northeast", "NE", "39.38", "45.00", "50.62", "Northeast by east", "NEbE", "50.63", "56.25", "61.87" +DATA "East-northeast", "ENE", "61.88", "67.50", "73.12", "East by north", "EbN", "73.13", "78.75", "84.37" +DATA "East", "E", "84.38", "90.00", "95.62", "East by south", "EbS", "95.63", "101.25", "106.87" +DATA "East-southeast", "ESE", "106.88", "112.50", "118.12", "Southeast by east", "SEbE", "118.13", "123.75", "129.37" +DATA "Southeast", "SE", "129.38", "135.00", "140.62", "Southeast by south", "SEbS", "140.63", "146.25", "151.87" +DATA "South-southeast", "SSE", "151.88", "157.50", "163.12", "South by east", "SbE", "163.13", "168.75", "174.37" +DATA "South", "S", "174.38", "180.00", "185.62", "South by west", "SbW", "185.63", "191.25", "196.87" +DATA "South-southwest", "SSW", "196.88", "202.50", "208.12", "Southwest by south", "SWbS", "208.13", "213.75", "219.37" +DATA "Southwest", "SW", "219.38", "225.00", "230.62", "Southwest by west", "SWbW", "230.63", "236.25", "241.87" +DATA "West-southwest", "WSW", "241.88", "247.50", "253.12", "West by south", "WbS", "253.13", "258.75", "264.37" +DATA "West", "W", "264.38", "270.00", "275.62", "West by north", "WbN", "275.63", "281.25", "286.87" +DATA "West-northwest", "WNW", "286.88", "292.50", "298.12", "Northwest by west", "NWbW", "298.13", "303.75", "309.37" +DATA "Northwest", "NW", "309.38", "315.00", "320.62", "Northwest by north", "NWbN", "320.63", "326.25", "331.87" +DATA "North-northwest", "NNW", "331.88", "337.50", "343.12", "North by west", "NbW", "343.13", "348.75", "354.37" diff --git a/Task/Box-the-compass/Zkl/box-the-compass.zkl b/Task/Box-the-compass/Zkl/box-the-compass.zkl new file mode 100644 index 0000000000..036256483c --- /dev/null +++ b/Task/Box-the-compass/Zkl/box-the-compass.zkl @@ -0,0 +1,17 @@ +A:=("X N NbE NNE NEbN NE NEbE ENE EbN E EbS ESE " // one based array + "SEbE SE SEbS SSE SbE S SbW SSW SWbS SW SWbW " + "WSW WbS W WbN WNW NWbW NW NWbN NNW NbW").split(" "); + +fcn compassBox(d){ + return(( ( (d + 360.0 / 64.0) % 360.0) * 32.0 / 360.0).ceil()); +} + +foreach i in ([0..32]){ + heading:=11.25*i; + switch(i%3){ // or heading+=5.62*((i+1).divr(3)[1]-1); + case(1){ heading+=5.62 } + case(2){ heading-=5.62 } + } + box:=compassBox(heading); + println("%6.2f\UB0; : %2d\t%s".fmt(heading,box,A[box])); +} diff --git a/Task/Break-OO-privacy/Factor/break-oo-privacy-3.factor b/Task/Break-OO-privacy/Factor/break-oo-privacy-3.factor deleted file mode 100644 index 1f5f38b3c2..0000000000 --- a/Task/Break-OO-privacy/Factor/break-oo-privacy-3.factor +++ /dev/null @@ -1,17 +0,0 @@ -link printf - -procedure main() - (x := foo(1,2,3)).print() # create and show a foo - printf("Fieldnames of foo x : ") # show fieldnames - every printf(" %i",fieldnames(x)) # __s (self), __m (methods), vars - printf("\n") - printf("var 1 of foo x = %i\n", x.var1) # read var1 from outside x - x.var1 := -1 # change var1 from outside x - x.print() # show we changed it -end - -class foo(var1,var2,var3) # class with no set/read methods - method print() - printf("foo var1=%i, var2=%i, var3=%i\n",var1,var2,var3) - end -end diff --git a/Task/Break-OO-privacy/FreeBASIC/break-oo-privacy.freebasic b/Task/Break-OO-privacy/FreeBASIC/break-oo-privacy.freebasic new file mode 100644 index 0000000000..2bd8b0985a --- /dev/null +++ b/Task/Break-OO-privacy/FreeBASIC/break-oo-privacy.freebasic @@ -0,0 +1,21 @@ +'FB 1.05.0 Win64 + +#Undef Private +#Undef Protected +#Define Private Public +#Define Protected Public + +Type MyType + Public : + x As Integer = 1 + Protected : + y As Integer = 2 + Private : + z As Integer = 3 +End Type + +Dim mt As MyType +Print mt.x, mt.y, mt.z +Print +Print "Press any key to quit" +Sleep diff --git a/Task/Break-OO-privacy/Kotlin/break-oo-privacy.kotlin b/Task/Break-OO-privacy/Kotlin/break-oo-privacy.kotlin new file mode 100644 index 0000000000..6c9ea0cafd --- /dev/null +++ b/Task/Break-OO-privacy/Kotlin/break-oo-privacy.kotlin @@ -0,0 +1,16 @@ +import kotlin.reflect.full.declaredMemberProperties +import kotlin.reflect.jvm.isAccessible + +class ToBeBroken { + @Suppress("unused") + private val secret: Int = 42 +} + +fun main(args: Array) { + val tbb = ToBeBroken() + val props = ToBeBroken::class.declaredMemberProperties + for (prop in props) { + prop.isAccessible = true // make private properties accessible + println("${prop.name} -> ${prop.get(tbb)}") + } +} diff --git a/Task/Break-OO-privacy/Zkl/break-oo-privacy.zkl b/Task/Break-OO-privacy/Zkl/break-oo-privacy.zkl new file mode 100644 index 0000000000..53753c433d --- /dev/null +++ b/Task/Break-OO-privacy/Zkl/break-oo-privacy.zkl @@ -0,0 +1,7 @@ +class C{var [private] v; fcn [private] f{123} class [private] D {}} +C.v; C.f; C.D; // all generate NotFoundError exceptions +However: +C.fcns //-->L(Fcn(nullFcn),Fcn(f)) +C.fcns[1]() //-->123 +C.classes //-->L(Class(D)) +C.vars //-->L(L("",Void)) (name,value) pairs diff --git a/Task/Brownian-tree/00DESCRIPTION b/Task/Brownian-tree/00DESCRIPTION index 0a9e3c8e7c..36b398d12f 100644 --- a/Task/Brownian-tree/00DESCRIPTION +++ b/Task/Brownian-tree/00DESCRIPTION @@ -1,4 +1,4 @@ -[[File:Brownian_tree.jpg|600px||right]] +[[File:Brownian_tree.jpg|240px||right]] ;Task: diff --git a/Task/Brownian-tree/FreeBASIC/brownian-tree.freebasic b/Task/Brownian-tree/FreeBASIC/brownian-tree.freebasic new file mode 100644 index 0000000000..7903a0af0c --- /dev/null +++ b/Task/Brownian-tree/FreeBASIC/brownian-tree.freebasic @@ -0,0 +1,60 @@ +' version 16-03-2017 +' compile with: fbc -s gui + +Const As ULong w = 400 +Const As ULong w1 = w -1 + +Dim As Long x, y, lastx, lasty +Dim As Long count, max = w * w \ 4 + +ScreenRes w, w, 8 ' windowsize 400 * 400, 8bit +' hit any key to stop or mouseclick on close window [X] +WindowTitle "hit any key to stop and close the window" + +Palette 0, 0 ' black +Palette 1, RGB( 1, 1, 1) ' almost black +Palette 2, RGB(255, 255, 255) ' white +Palette 3, RGB( 0, 255, 0) ' green + +Line (0, 0) - (w1, w1), 0, BF ' make field black +Line (0, 0) - (w1, w1), 1, B ' draw border in almost black color + +Randomize Timer +x = Int(Rnd * 11) - 5 +y = Int(Rnd * 11) - 5 + +PSet(w \ 2 + x, w \ 2 + y), 3 ' place seed near center + +Do + Do ' create new particle + x = Int(Rnd * w1) + 1 + y = Int(Rnd * w1) + 1 + Loop Until Point(x, y) = 0 ' black + PSet(x, y), 2 + + Do + lastx = x + lasty = y + Do + x = lastx + Int(Rnd * 3) -1 + y = lasty + Int(Rnd * 3) -1 + Loop Until Point(x, y) <> 1 + + If Point(x, y) = 3 Then + PSet(lastx, lasty), 3 + Exit Do ' exit do loop and create new particle + End If + + PSet(lastx, lasty), 0 + PSet(x,y), 2 + + If Inkey <> "" Or Inkey = Chr(255) + "k" Then + End + End If + Loop + + count += 1 +Loop Until count > max + +Beep : Sleep 5000 +End diff --git a/Task/Brownian-tree/Gnuplot/brownian-tree-1.gnuplot b/Task/Brownian-tree/Gnuplot/brownian-tree-1.gnuplot new file mode 100644 index 0000000000..e5b9600b91 --- /dev/null +++ b/Task/Brownian-tree/Gnuplot/brownian-tree-1.gnuplot @@ -0,0 +1,14 @@ +## plotff.gp 11/27/16 aev +## Plotting from any data-file with 2 columns (space delimited), and writing to png-file. +## Especially useful to plot colored fractals using points. +## Note: assign variables: clr, filename and ttl (before using load command). +reset +set terminal png font arial 12 size 640,640 +ofn=filename.".png" +set output ofn +unset border; unset xtics; unset ytics; unset key; +set size square +dfn=filename.".dat" +set title ttl font "Arial:Bold,12" +plot dfn using 1:2 with points pt 7 ps 0.5 lc @clr +set output diff --git a/Task/Brownian-tree/Gnuplot/brownian-tree-2.gnuplot b/Task/Brownian-tree/Gnuplot/brownian-tree-2.gnuplot new file mode 100644 index 0000000000..b20cc6e381 --- /dev/null +++ b/Task/Brownian-tree/Gnuplot/brownian-tree-2.gnuplot @@ -0,0 +1,41 @@ +## BTff.gp 11/27/16 aev +## Plotting 6 Brownian tree pictures. +## dat-files are PARI/GP generated output files: +## http://rosettacode.org/wiki/Brownian_tree#PARI.2FGP +#cd 'C:\gnupData' + +##BT1 +clr = '"dark-green"' +filename = "BTAH1" +ttl = "Brownian Tree v.#1" +load "plotff.gp" + +##BT2 +clr = '"brown"' +filename = "BTOC1" +ttl = "Brownian Tree v.#2" +load "plotff.gp" + +##BT3 +clr = '"navy"' +filename = "BTSE1" +ttl = "Brownian Tree v.#3" +load "plotff.gp" + +##BT41 +clr = '"red"' +filename = "BTPB1" +ttl = "Brownian Tree v.#4-1" +load "plotff.gp" + +##BT42 +clr = '"red"' +filename = "BTPB2" +ttl = "Brownian Tree v.#4-2" +load "plotff.gp" + +##BT43 +clr = '"red"' +filename = "BTPB3" +ttl = "Brownian Tree v.#4-3" +load "plotff.gp" diff --git a/Task/Brownian-tree/Kotlin/brownian-tree.kotlin b/Task/Brownian-tree/Kotlin/brownian-tree.kotlin new file mode 100644 index 0000000000..2984c0d51d --- /dev/null +++ b/Task/Brownian-tree/Kotlin/brownian-tree.kotlin @@ -0,0 +1,64 @@ +// version 1.1.2 + +import java.awt.Graphics +import java.awt.image.BufferedImage +import java.util.* +import javax.swing.JFrame + +class BrownianTree : JFrame("Brownian Tree"), Runnable { + private val img: BufferedImage + private val particles = LinkedList() + + private companion object { + val rand = Random() + } + + private inner class Particle { + private var x = rand.nextInt(img.width) + private var y = rand.nextInt(img.height) + + /* returns true if either out of bounds or collided with tree */ + fun move(): Boolean { + val dx = rand.nextInt(3) - 1 + val dy = rand.nextInt(3) - 1 + if ((x + dx < 0) || (y + dy < 0) || (y + dy >= img.height) || + (x + dx >= img.width)) return true + x += dx + y += dy + if ((img.getRGB(x, y) and 0xff00) == 0xff00) { + img.setRGB(x - dx, y - dy, 0xff00) + return true + } + return false + } + } + + init { + setBounds(100, 100, 400, 300) + defaultCloseOperation = EXIT_ON_CLOSE + img = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) + img.setRGB(img.width / 2, img.height / 2, 0xff00) + } + + override fun paint(g: Graphics) { + g.drawImage(img, 0, 0, this) + } + + override fun run() { + (0 until 20000).forEach { particles.add(Particle()) } + + while (!particles.isEmpty()) { + val iter = particles.iterator() + while (iter.hasNext()) { + if (iter.next().move()) iter.remove() + } + repaint() + } + } +} + +fun main(args: Array) { + val b = BrownianTree() + b.isVisible = true + Thread(b).start() +} diff --git a/Task/Brownian-tree/PARI-GP/brownian-tree-1.pari b/Task/Brownian-tree/PARI-GP/brownian-tree-1.pari index 2e40ef4b4f..0f25b66f6d 100644 --- a/Task/Brownian-tree/PARI-GP/brownian-tree-1.pari +++ b/Task/Brownian-tree/PARI-GP/brownian-tree-1.pari @@ -1,11 +1,28 @@ -\\ 2 plotting helper functions 3/2/16 aev -\\ insm(): x,y are inside matrix mat (+/- p deep). +\\ 2 old plotting helper functions 3/2/16 aev +\\ insm(): Check if x,y are inside matrix mat (+/- p deep). insm(mat,x,y,p=0)={my(xz=#mat[1,],yz=#mat[,1]); return(x+p>0 && x+p<=xz && y+p>0 && y+p<=yz && x-p>0 && x-p<=xz && y-p>0 && y-p<=yz)} -\\ plotmat(): Simple plotting using matrix mat (filled with 0/1). +\\ plotmat(): Simple plotting using a square matrix mat (filled with 0/1). plotmat(mat)={ -my(xz=#mat[1,],yz=#mat[,1],vx=List(),vy=vx,x,y); -for(i=1,yz, for(j=1,xz, if(mat[i,j]==0, next, listput(vx,i); listput(vy,j)))); -plothraw(Vec(vx),Vec(vy)); -print(" *** matrix(",xz,"x",yz,") ",#vy, " DOTS"); + my(xz=#mat[1,],yz=#mat[,1],vx=List(),vy=vx,x,y); + for(i=1,yz, for(j=1,xz, if(mat[i,j]==0, next, listput(vx,i); listput(vy,j)))); + print(" *** matrix(",xz,"x",yz,") ",#vy, " DOTS"); + plothraw(Vec(vx),Vec(vy)); +} +\\ 2 new plotting helper functions 11/27/16 aev +\\ wrtmat(): Writing file fn containing X,Y coordinates from matrix mat. +\\ Created primarily for using file in Gnuplot, also for re-plotting. +wrtmat(mat, fn)={ + my(xz=#mat[1,],yz=#mat[,1],ws,d=0); + for(i=1,yz, for(j=1,xz, if(mat[i,j]==0, next, d++; ws=Str(i," ",j); write(fn,ws)))); + print(" *** matrix(",xz,"x",yz,") ",d, " DOTS put in ",fn); +} +\\ plotff(): Plotting from a file written by the wrtmat(). +\\ Saving possibly huge generation time if re-plotting needed. +plotff(fn)={ + my(F,nf,vx=List(),vy=vx,Vr); + F=readstr(fn); nf=#F; + print(" *** Plotting from: ", fn, " - ", nf, " DOTS"); + for(i=1,nf, Vr=stok(F[i],","); listput(vx,eval(Vr[1])); listput(vy,eval(Vr[2]))); + plothraw(Vec(vx),Vec(vy)); } diff --git a/Task/Brownian-tree/PARI-GP/brownian-tree-2.pari b/Task/Brownian-tree/PARI-GP/brownian-tree-2.pari index 015ff3fa0d..f18e74cf25 100644 --- a/Task/Brownian-tree/PARI-GP/brownian-tree-2.pari +++ b/Task/Brownian-tree/PARI-GP/brownian-tree-2.pari @@ -1,20 +1,26 @@ -\\ 3/8/2016 -BrownianTree1(size,lim)={ -my(Myx=matrix(size,size),sz=size-1,sz2=sz\2,x,y,ox,oy); -x=sz2; y=sz2; Myx[y,x]=1; \\ seed in center -print(" *** START: ",x,"/",y); -for(i=1,lim, - x=random(sz)+1; y=random(sz)+1; - while(1, - ox=x; oy=y; - x+=random(3)-1; y+=random(3)-1; - if(insm(Myx,x,y)&&Myx[y,x], - if(insm(Myx,ox,oy), Myx[oy,ox]=1; break)); - if(!insm(Myx,x,y), break); - );\\wend -);\\ fend i -plotmat(Myx); -} -{\\ Executing: -BrownianTree1(400,15000); +\\ Brownian tree v.#1. Translated from AutoHotkey +\\ 3/8/2016, upgraded 11/27/16 aev +\\ Where: size - size of a square matrix; lim - limit of testing dots; +\\ fn - file name (fn=""-only plot, fn!=""-only writing file).. +BrownianTree1(size,lim, fn="")={ + my(Myx=matrix(size,size),sz=size-1,sz2=sz\2,x,y,ox,oy); + x=sz2; y=sz2; Myx[y,x]=1; \\ seed in center + print(" *** BT1 SEED: ",x,"/",y); + for(i=1,lim, + x=random(sz)+1; y=random(sz)+1; + while(1, + ox=x; oy=y; + x+=random(3)-1; y+=random(3)-1; + if(insm(Myx,x,y)&&Myx[y,x], + if(insm(Myx,ox,oy), Myx[oy,ox]=1; break)); + if(!insm(Myx,x,y), break); + );\\wend + );\\ fend i + if(fn=="", plotmat(Myx), wrtmat(Myx, fn)); } +\\ Executing 1 or 2 lines below: + +BrownianTree1(400,15000); \\BTAH1.png + +{BrownianTree1(400,15000,"c:\\pariData\\BTAH1.dat"); +plotff("c:\\pariData\\BTAH1.dat");} \\BTAH1.png diff --git a/Task/Brownian-tree/PARI-GP/brownian-tree-3.pari b/Task/Brownian-tree/PARI-GP/brownian-tree-3.pari index 818483400f..b9054a8f8d 100644 --- a/Task/Brownian-tree/PARI-GP/brownian-tree-3.pari +++ b/Task/Brownian-tree/PARI-GP/brownian-tree-3.pari @@ -1,18 +1,24 @@ -\\ 3/11/2016 -BrownianTree2(size,lim)={ -my(Myx=matrix(size,size),sz=size-1,dx,dy,x,y); -x=random(sz); y=random(sz); Myx[y,x]=1; \\ random seed -print(" *** START: ",x,"/",y); -for(i=1,lim, - x=random(sz)+1; y=random(sz)+1; - while(1, - dx=random(3)-1; dy=random(3)-1; - if(!insm(Myx,x+dx,y+dy), x=random(sz)+1; y=random(sz)+1, - if(Myx[y+dy,x+dx], Myx[y,x]=1; break, x+=dx; y+=dy)); - );\\wend -);\\fend i -plotmat(Myx); -} -{\\ Executing: -BrownianTree2(1000,3000); +\\ Brownian tree v.#2. Translated from Octave +\\ 3/8/2016, upgraded 11/27/16 aev +\\ Where: size - size of a square matrix; lim - limit of testing dots; +\\ fn - file name (fn=""-only plot, fn!=""-only writing file).. +BrownianTree2(size,lim, fn="")={ + my(Myx=matrix(size,size),sz=size-1,dx,dy,x,y); + x=random(sz); y=random(sz); Myx[y,x]=1; \\ random seed + print(" *** BT2 SEED: ",x,"/",y); + for(i=1,lim, + x=random(sz)+1; y=random(sz)+1; + while(1, + dx=random(3)-1; dy=random(3)-1; + if(!insm(Myx,x+dx,y+dy), x=random(sz)+1; y=random(sz)+1, + if(Myx[y+dy,x+dx], Myx[y,x]=1; break, x+=dx; y+=dy)); + );\\wend + );\\fend i + if(fn=="", plotmat(Myx), wrtmat(Myx, fn)); } +\\ Executing 1 or 2 lines below: + +BrownianTree2(1000,3000); \\BTOC1.png + +{BrownianTree2(1000,3000,"c:\\pariData\\BTOC1.dat"); +plotff("c:\\pariData\\BTOC1.dat");} \\BTOC1.png diff --git a/Task/Brownian-tree/PARI-GP/brownian-tree-4.pari b/Task/Brownian-tree/PARI-GP/brownian-tree-4.pari index bc1ecc6fb5..fbca4c33d0 100644 --- a/Task/Brownian-tree/PARI-GP/brownian-tree-4.pari +++ b/Task/Brownian-tree/PARI-GP/brownian-tree-4.pari @@ -1,9 +1,12 @@ -\\ 3/14/2016 -BrownianTree3(size,lim)={ -my(Myx=matrix(size,size),sz=size-2,x,y,dx,dy,b=0); -x=random(sz); y=random(sz); Myx[y,x]=1; \\ random seed -print("*** START: ", x,"/",y); -for(i=1,lim, +\\ Brownian tree v.#3. Translated from Seed7 +\\ 3/8/2016, upgraded 11/27/16 aev +\\ Where: size - size of a square matrix; lim - limit of testing dots; +\\ fn - file name (fn=""-only plot, fn!=""-only writing file).. +BrownianTree3(size,lim, fn="")={ + my(Myx=matrix(size,size),sz=size-2,x,y,dx,dy,b=0); + x=random(sz); y=random(sz); Myx[y,x]=1; \\ random seed + print("*** BT3 SEED: ", x,"/",y); + for(i=1,lim, x=random(sz); y=random(sz); b=0; \\ bumped not while(!b, @@ -12,9 +15,12 @@ for(i=1,lim, if(Myx[y+dy,x+dx]==1, Myx[y,x]=1; b=1, x+=dx; y+=dy); ); );\\wend -);\\fend i -plotmat(Myx); -} -{\\ Executing: -BrownianTree3(400,5000); + );\\fend i + if(fn=="", plotmat(Myx), wrtmat(Myx, fn)); } +\\ Executing 1 or 2 lines below: + +BrownianTree3(400,5000); \\BTSE1.png + +{BrownianTree3(400,5000,"c:\\pariData\\BTSE1.dat"); +plotff("c:\\pariData\\BTSE1.dat");} \\BTSE1.png diff --git a/Task/Brownian-tree/PARI-GP/brownian-tree-5.pari b/Task/Brownian-tree/PARI-GP/brownian-tree-5.pari index 11e837dff1..b92632e5e4 100644 --- a/Task/Brownian-tree/PARI-GP/brownian-tree-5.pari +++ b/Task/Brownian-tree/PARI-GP/brownian-tree-5.pari @@ -1,27 +1,39 @@ -\\ 3/17/2016 +\\ Brownian tree v.#4. Translated from PureBasic +\\ 3/8/2016, upgraded 11/27/16 aev +\\ Where: size - size of a square matrix; lim - limit of testing dots; +\\ fn - file name (fn=""-only plot, fn!=""-only writing file).. \\ s=1/2(random seed/seed in the center); p=0..n (level of the "deep" checking). -BrownianTree4(size,lim,s=1,p=0)={ -my(Myx=matrix(size,size),sz=size-3,x,y); -\\ seed s=1 for BTPB1, s=2 for BTPB2, BTPB3 -if(s==1,x=random(sz); y=random(sz), x=sz\2; y=sz\2); Myx[y,x]=1; -print(" *** START: ",x,"/",y); -for(i=1,lim, - if(!(i==1&&s==2), x=random(sz)+1; y=random(sz)+1); - while(insm(Myx,x,y,1)&& +BrownianTree4(size,lim, fn="",s=1,p=0)={ + my(Myx=matrix(size,size),sz=size-3,x,y); + \\ seed s=1 for BTPB1, s=2 for BTPB2, BTPB3 + if(s==1,x=random(sz); y=random(sz), x=sz\2; y=sz\2); Myx[y,x]=1; + print(" *** BT4 SEED: ",x,"/",y); + for(i=1,lim, + if(!(i==1&&s==2), x=random(sz)+1; y=random(sz)+1); + while(insm(Myx,x,y,1)&& (Myx[y+1,x+1]+Myx[y+1,x]+Myx[y+1,x-1]+Myx[y,x+1]+ Myx[y-1,x-1]+Myx[y,x-1]+Myx[y-1,x]+Myx[y-1,x+1])==0, - x+=random(3)-1; y+=random(3)-1; - \\ p=0 for BTPB1, BTPB2; p=5 for BTPB3 - if(!insm(Myx,x,y,p), x=random(sz)+1; y=random(sz)+1;); - );\\wend - Myx[y,x]=1; -);\\fend i -plotmat(Myx); + x+=random(3)-1; y+=random(3)-1; + \\ p=0 for BTPB1, BTPB2; p=5 for BTPB3 + if(!insm(Myx,x,y,p), x=random(sz)+1; y=random(sz)+1;); + );\\wend + Myx[y,x]=1; + );\\fend i + if(fn=="", plotmat(Myx), wrtmat(Myx, fn)); } +\\ Executing 1 or 2 lines below: -{ -\\ Executing: -BrownianTree4(200,4000); \\BTPB1.png -BrownianTree4(200,4000,2); \\BTPB2.png -BrownianTree4(200,4000,2,5); \\BTPB3.png -} +BrownianTree4(200,4000); \\BTPB1.png + +{BrownianTree4(200,4000,"c:\\pariData\\BTPB1.dat"); +plotff("c:\\pariData\\BTPB1.dat");} \\BTPB1.png + +BrownianTree4(200,4000,,2); \\BTPB2.png + +{BrownianTree4(200,4000,"c:\\pariData\\BTPB2.dat",2); +plotff("c:\\pariData\\BTPB2.dat");} \\BTPB2.png + +BrownianTree4(200,4000,,2,5); \\BTPB3.png + +{BrownianTree4(200,4000,"c:\\pariData\\BTPB3.dat",2,5); +plotff("c:\\pariData\\BTPB3.dat");} \\BTPB3.png diff --git a/Task/Brownian-tree/Phix/brownian-tree.phix b/Task/Brownian-tree/Phix/brownian-tree.phix index 5b338b9e68..83d305227f 100644 --- a/Task/Brownian-tree/Phix/brownian-tree.phix +++ b/Task/Brownian-tree/Phix/brownian-tree.phix @@ -1,4 +1,7 @@ -include ..\pGUI\pGUI.e +-- +-- demo\rosetta\BrownianTree.exw +-- +include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas @@ -50,7 +53,7 @@ function esc_close(Ihandle /*ih*/, atom c) end function procedure main() - IupOpen("..\\pGUI\\") + IupOpen() canvas = IupCanvas(NULL) IupSetAttribute(canvas, "RASTERSIZE", "200x200") -- fixed size diff --git a/Task/Brownian-tree/R/brownian-tree-1.r b/Task/Brownian-tree/R/brownian-tree-1.r new file mode 100644 index 0000000000..01f5d9f31c --- /dev/null +++ b/Task/Brownian-tree/R/brownian-tree-1.r @@ -0,0 +1,39 @@ +# plotmat(): Simple plotting using a square matrix mat (filled with 0/1). v. 8/31/16 +# Where: mat - matrix; fn - file name; clr - color; ttl - plot title; +# dflg - writing dump file flag (0-no/1-yes): psz - picture size. +plotmat <- function(mat, fn, clr, ttl, dflg=0, psz=600) { + m <- nrow(mat); d <- 0; + X=NULL; Y=NULL; + pf = paste0(fn, ".png"); df = paste0(fn, ".dmp"); + for (i in 1:m) { + for (j in 1:m) {if(mat[i,j]==0){next} else {d=d+1; X[d] <- i; Y[d] <- j;} } + }; + cat(" *** Matrix(", m,"x",m,")", d, "DOTS\n"); + # Dumping if requested (dflg=1). + if (dflg==1) {dump(c("X","Y"), df); cat(" *** Dump file:", df, "\n")}; + # Plotting + plot(X,Y, main=ttl, axes=FALSE, xlab="", ylab="", col=clr, pch=20); + dev.copy(png, filename=pf, width=psz, height=psz); + # Cleaning + dev.off(); graphics.off(); +} + +# plotv2(): Simple plotting using 2 vectors (dumped into ".dmp" file by plotmat()). +# Where: fn - file name; clr - color; ttl - plot title; psz - picture size. +# v. 8/31/16 +plotv2 <- function(fn, clr, ttl, psz=600) { + cat(" *** START:", date(), "clr=", clr, "psz=", psz, "\n"); + cat(" *** File name -", fn, "\n"); + pf = paste0(fn, ".png"); df = paste0(fn, ".dmp"); + source(df); + d <- length(X); + cat(" *** Source dump-file:", df, d, "DOTS\n"); + cat(" *** Plot file -", pf, "\n"); + # Plotting + plot(X, Y, main=ttl, axes=FALSE, xlab="", ylab="", col=clr, pch=20); + # Writing png-file + dev.copy(png, filename=pf, width=psz, height=psz); + # Cleaning + dev.off(); graphics.off(); + cat(" *** END:", date(), "\n"); +} diff --git a/Task/Brownian-tree/R/brownian-tree-2.r b/Task/Brownian-tree/R/brownian-tree-2.r new file mode 100644 index 0000000000..81dc30e191 --- /dev/null +++ b/Task/Brownian-tree/R/brownian-tree-2.r @@ -0,0 +1,33 @@ +# Generate and plot Brownian tree. Version #1. +# 7/27/16 aev +# gpBrownianTree1(m, n, clr, fn, ttl, dflg, psz) +# Where: m - defines matrix m x m; n - limit of the number of moves; +# fn - file name (.ext will be added); ttl - plot title; dflg - 0-no dump, +# 1-dump: psz - picture size. +gpBrownianTree1 <- function(m, n, clr, fn, ttl, dflg=0, psz=600) +{ + cat(" *** START:", date(), "m=",m, "n=",n, "clr=",clr, "psz=", psz, "\n"); + M <- matrix(c(0), ncol=m, nrow=m, byrow=TRUE); + # Seed in center + x <- m%/%2; y <- m%/%2; + M[x,y]=1; + pf=paste0(fn, ".png"); + cat(" *** Plot file -", pf, "\n"); + # Main loops + for (i in 1:n) { + if(i>1) { + x <- sample(1:m, 1, replace=FALSE) + y <- sample(1:m, 1, replace=FALSE)} + while(1) { + ox = x; oy = y; + x <- x + sample(-1:1, 1, replace=FALSE); + y <- y + sample(-1:1, 1, replace=FALSE); + if(x<=m && y<=m && x>0 && y>0 && M[x,y]) + {if(ox<=m && oy<=m && ox>0 && oy>0) {M[ox,oy]=1; break}} + if(!(x<=m && y<=m && x>0 && y>0)) {break} + } + } + plotmat(M, fn, clr, ttl, dflg, psz); + cat(" *** END:",date(),"\n"); +} +gpBrownianTree1(400,15000,"red", "BT1R", "Brownian Tree v.1", 1); diff --git a/Task/Brownian-tree/R/brownian-tree-3.r b/Task/Brownian-tree/R/brownian-tree-3.r new file mode 100644 index 0000000000..358c1d7e4b --- /dev/null +++ b/Task/Brownian-tree/R/brownian-tree-3.r @@ -0,0 +1,37 @@ +# Generate and plot Brownian tree. Version #2. +# 7/27/16 aev +# gpBrownianTree2(m, n, clr, fn, ttl, dflg, psz) +# Where: m - defines matrix m x m; n - limit of the number of moves; +# fn - file name (.ext will be added); ttl - plot title; dflg - 0-no dump, +# 1-dump; psz - picture size. +gpBrownianTree2 <- function(m, n, clr, fn, ttl, dflg=0, psz=600) +{ + cat(" *** START:", date(), "m=",m, "n=",n, "clr=",clr, "psz=", psz, "\n"); + M <- matrix(c(0), ncol=m, nrow=m, byrow=TRUE); + # Random seed always + x <- sample(1:m, 1, replace=FALSE); y <- sample(1:m, 1, replace=FALSE); + M[x,y]=1; + pf=paste0(fn,".png"); + cat(" *** Plot file -",pf,"Seed:",x,"/",y,"\n"); + # Main loops + for (i in 1:n) { + if(i>1) { + x <- sample(1:m, 1, replace=FALSE) + y <- sample(1:m, 1, replace=FALSE)} + while(1) { + dx <- sample(-1:1, 1, replace=FALSE); + dy <- sample(-1:1, 1, replace=FALSE); + nx=x+dx; ny=y+dy; + if(!(nx<=m && ny<=m && nx>0 && ny>0)) { + x <- sample(1:m, 1, replace=FALSE); y <- sample(1:m, 1, replace=FALSE)} + else {if(M[nx,ny]) {M[x,y]=1; break} + else{x=nx; y=ny;}} + } + } + plotmat(M, fn, clr, ttl, dflg, psz); + cat(" *** END:",date(),"\n"); +} +gpBrownianTree2(400,5000,"brown", "BT2R", "Brownian Tree v.2", 1); + +## Rename BT2R.dmp to BT2aR.dmp +plotv2("BT2aR", "orange", "Brownian Tree v.2a", 640) diff --git a/Task/Brownian-tree/R/brownian-tree-4.r b/Task/Brownian-tree/R/brownian-tree-4.r new file mode 100644 index 0000000000..d22621b8db --- /dev/null +++ b/Task/Brownian-tree/R/brownian-tree-4.r @@ -0,0 +1,39 @@ +# Generate and plot Brownian tree. Version #3. +# 7/27/16 aev +# gpBrownianTree3(m, n, clr, fn, ttl, dflg, seed, psz): +# Where: m - defines matrix m x m; n - limit of the number of moves; +# fn - file name (.ext will be added); ttl - plot title; dflg - 0-no dump, +# 1-dump; seed - 0-center, 1-random: psz - picture size. +gpBrownianTree3 <- function(m, n, clr, fn, ttl, dflg=0, seed=0, psz=600) +{ + cat(" *** START:", date(),"m=",m,"n=",n,"clr=",clr, "psz=",psz, "\n"); + M <- matrix(c(0), ncol=m, nrow=m, byrow=TRUE); + # Random seed + if(seed==1) + {x <- sample(1:m, 1, replace=FALSE);y <- sample(1:m, 1, replace=FALSE)} + # Seed in center + else {x <- m%/%2; y <- m%/%2} + M[x,y]=1; + pf=paste0(fn,". png"); + cat(" *** Plot file -", pf, "Seed:",x,"/",y, "\n"); + # Main loops + for (i in 1:n) { + if(i>1) { + x <- sample(1:m, 1, replace=FALSE) + y <- sample(1:m, 1, replace=FALSE)} + b <- 0; + while(b==0) { + dx <- sample(-1:1, 1, replace=FALSE) + dy <- sample(-1:1, 1, replace=FALSE) + if(!(x+dx<=m && y+dy<=m && x+dx>0 && y+dy>0)) + { x <- sample(1:m, 1, replace=FALSE) + y <- sample(1:m, 1, replace=FALSE) + } + else{if(M[x+dx,y+dy]==1) {M[x,y]=1; b=1} + else {x=x+dx; y=y+dy;} } + } + } + plotmat(M, fn, clr, ttl, dflg, psz); + cat(" *** END:", date(), "\n"); +} +gpBrownianTree3(400,5000,"dark green", "BT3R", "Brownian Tree v.3", 1); diff --git a/Task/Brownian-tree/R/brownian-tree-5.r b/Task/Brownian-tree/R/brownian-tree-5.r new file mode 100644 index 0000000000..61220c9fed --- /dev/null +++ b/Task/Brownian-tree/R/brownian-tree-5.r @@ -0,0 +1,41 @@ +# Generate and plot Brownian tree. Version #4. +# 7/27/16 aev +# gpBrownianTree4(m, n, clr, fn, ttl, dflg, seed, psz) +# Where: m - defines matrix m x m; n - limit of the number of moves; +# fn - file name (.ext will be added); ttl - plot title; dflg - 0-no dump, +# 1-dump; seed - 0-center, 1-random: psz - picture size. +gpBrownianTree4 <- function(m, n, clr, fn, ttl, dflg=0, seed=0, psz=600) +{ + cat(" *** START:", date(), "m=",m, "n=",n, "clr=",clr, "psz=",psz, "\n"); + M <- matrix(c(0), ncol=m, nrow=m, byrow=TRUE); + # Random seed + if(seed==1) + {x <- sample(1:m, 1, replace=FALSE);y <- sample(1:m, 1, replace=FALSE)} + # Seed in center + else {x <- m%/%2; y <- m%/%2} + M[x,y]=1; + pf=paste0(fn,".png"); + cat(" *** Plot file -",pf,"Seed:",x,"/",y,"\n"); + # Main loops + for (i in 1:n) { + if(i>1) { + x <- sample(1:m, 1, replace=FALSE) + y <- sample(1:m, 1, replace=FALSE)} + while((x<=m && y<=m && x>0 && y>0)) { + if(!(x+1<=m && y+1<=m && x-1>0 && y-1>0)) {break;} + b=M[x+1,y+1]+M[x,y+1]+M[x-1,y+1]+M[x+1,y]; + b=b+M[x-1,y-1]+M[x-1,y]+M[x,y-1]+M[x+1,y-1]; + if(b!=0) {break;} + x <- x + sample(-1:1, 1, replace=FALSE) + y <- y + sample(-1:1, 1, replace=FALSE) + if(!(x<=m && y<=m && x>0 && y>0)) + { x <- sample(1:m, 1, replace=FALSE) + y <- sample(1:m, 1, replace=FALSE) + } + } + M[x,y]=1; + } + plotmat(M, fn, clr, ttl, dflg, psz); + cat(" *** END:",date(),"\n"); +} +gpBrownianTree4(400,15000,"navy", "BT4R", "Brownian Tree v.4", 1); diff --git a/Task/Brownian-tree/REXX/brownian-tree.rexx b/Task/Brownian-tree/REXX/brownian-tree.rexx index 8461ed4b69..994170d411 100644 --- a/Task/Brownian-tree/REXX/brownian-tree.rexx +++ b/Task/Brownian-tree/REXX/brownian-tree.rexx @@ -1,37 +1,37 @@ /*REXX program animates and displays Brownian motion of dust in a field (with one seed).*/ -parse arg height width motes randSeed . /*get args from the C.L. */ -if height=='' | height=="," then height=0 /*Not specified? Then use the default.*/ -if width=='' | width=="," then width=0 /* " " " " " " */ -if motes=='' | motes=="," then motes='10%' /*The % dust motes in the field, */ - /* [↑] either a # -or- a # with a %.*/ -tree = '*' /*an affixed dust speck, start of tree.*/ mote = '·' /*character for a loose mote (of dust).*/ hole = ' ' /* " " an empty spot in field.*/ clearScr = 'CLS' /*(DOS) command to clear the screen. */ eons = 1000000 /*number cycles for Brownian movement.*/ snapshot = 0 /*every N winks, display a snapshot.*/ -snaptime = 1 /* " " secs, " " " */ +snaptime = 1 /* " " secs, " " " */ seedPos = 30 45 /*place a seed in this field position. */ seedPos = 0 /*if =0, then use middle of the field.*/ /* " -1, " " a random placement.*/ /*otherwise, place the seed at seedPos.*/ /*use RANDSEED for RANDOM repeatability*/ +parse arg height width motes tree randSeed . /*obtain optional arguments from the CL*/ +if height=='' | height=="," then height=0 /*Not specified? Then use the default.*/ +if width=='' | width=="," then width=0 /* " " " " " " */ +if motes=='' | motes=="," then motes='10%' /*The % dust motes in the field, */ + /* [↑] either a # -or- a # with a %.*/ +if tree=='' | tree==mote then tree='*' /*the character used to show the tree. */ +if length(tree)==2 then tree=x2c(tree) /*tree character was specified in hex. */ if datatype(randSeed,'W') then call random ,,randSeed /*if an integer, use the seed.*/ /* [↑] set the first random number. */ if height==0 | width==0 then _=scrsize() /*Note: not all REXXes have SCRSIZE BIF*/ -if height==0 then height=word(_,1)-3 /*adjust useable height for the border.*/ -if width==0 then width=word(_,2)-1 /* " " width " " " */ - +if height==0 then height=word(_, 1)-3 /*adjust useable height for the border.*/ +if width==0 then width=word(_, 2)-1 /* " " width " " " */ seedAt=seedPos if seedPos== 0 then seedAt=width%2 height%2 /*if it's a zero, start in the middle.*/ -if seedPos==-1 then seedAt=random(1,width) random(1,height) /*if negative, use random.*/ +if seedPos==-1 then seedAt=random(1, width) random(1,height) /*if negative, use random*/ parse var seedAt xs ys . /*obtain the X and Y seed coördinates*/ /* [↓] if right-most ≡ '%', then use %*/ -if right(motes,1)=='%' then motes=height * width * strip(motes,,'%') % 100 +if right(motes, 1) == '%' then motes=height * width * strip(motes, , '%') % 100 @.=hole /*create the Brownian field, all empty.*/ do j=1 for motes /*sprinkle a # of dust motes randomly.*/ - rx=random(1, width); ry=random(1,height); @.rx.ry=mote + rx=random(1, width); ry=random(1, height); @.rx.ry=mote end /*j*/ /* [↑] place a mote at random in field*/ /*plant the seed from which the tree */ /* will grow from dust motes that */ @@ -40,38 +40,36 @@ call show /*show field before we mess it tim=0 /*the time in seconds of last display. */ loX=1; hiX= width /*used to optimize the mote searching.*/ loY=1; hiY=height /* " " " " " " */ - - /*═══════════════════════════════════════ soooo, this is Brownian motion. */ - do winks=1 for eons until \motion /*EONs is used instead of ∞, close 'nuf*/ + /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ soooo, this is Brownian motion.*/ + do winks=1 for eons until \motion /*EONs is used instead of ∞; close 'nuf*/ motion=0 /*turn off the Brownian motion flag. */ - if snapshot\==0 then if winks//snapshot==0 then call show - if snaptime\==0 then do; t=time('S') - if t\==tim & t//snaptime==0 then do; tim=time('s') - call show - end + if snapshot\==0 then if winks//snapshot==0 then call show + if snaptime\==0 then do; t=time('S') + if t\==tim & t//snaptime==0 then do; tim=t; call show + end end - minX=loX; maxX=hiX /*as the tree grows, the search for */ - minY=loY; maxY=hiY /* dust motes gets faster. */ - loX= width; hiX=1 /*used to limit the mote searching. */ - loY=height; hiY=1 /* " " " " " " */ + minX=loX; maxX=hiX /*as the tree grows, the search for */ + minY=loY; maxY=hiY /* dust motes gets faster. */ + loX= width; hiX=1 /*used to limit the mote searching. */ + loY=height; hiY=1 /* " " " " " " */ - do x =minX to maxX; xm=x-1; xp=x+1 /*a couple handy-dandy values*/ + do x =minX to maxX; xm=x-1; xp=x+1 /*a couple handy-dandy values*/ do y=minY to maxY; if @.x.y\==mote then iterate /*Not a mote: keep looking. */ - if xhiX then hiX=x /*faster than: hiX=max(X hiX)*/ - if yhiY then hiY=y /*faster than: hiY=max(y hiY)*/ - if @.xm.y ==tree then do; @.x.y=tree; iterate; end /*neighbor?*/ - if @.xp.y ==tree then do; @.x.y=tree; iterate; end /*neighbor?*/ - ym=y-1 - if @.x.ym ==tree then do; @.x.y=tree; iterate; end /*neighbor?*/ - if @.xm.ym==tree then do; @.x.y=tree; iterate; end /*neighbor?*/ - if @.xp.ym==tree then do; @.x.y=tree; iterate; end /*neighbor?*/ - yp=y+1 - if @.x.yp ==tree then do; @.x.y=tree; iterate; end /*neighbor?*/ - if @.xm.yp==tree then do; @.x.y=tree; iterate; end /*neighbor?*/ - if @.xp.yp==tree then do; @.x.y=tree; iterate; end /*neighbor?*/ + if xhiX then hiX=x /*faster than: hiX=max(X,hiX)*/ + if yhiY then hiY=y /*faster than: hiY=max(y,hiY)*/ + if @.xm.y ==tree then do; @.x.y=tree; iterate; end /*there a neighbor of tree? */ + if @.xp.y ==tree then do; @.x.y=tree; iterate; end /*there a neighbor of tree? */ + ym=y-1 + if @.x.ym ==tree then do; @.x.y=tree; iterate; end /*there a neighbor of tree? */ + if @.xm.ym==tree then do; @.x.y=tree; iterate; end /*there a neighbor of tree? */ + if @.xp.ym==tree then do; @.x.y=tree; iterate; end /*there a neighbor of tree? */ + yp=y+1 + if @.x.yp ==tree then do; @.x.y=tree; iterate; end /*there a neighbor of tree? */ + if @.xm.yp==tree then do; @.x.y=tree; iterate; end /*there a neighbor of tree? */ + if @.xp.yp==tree then do; @.x.y=tree; iterate; end /*there a neighbor of tree? */ motion=1 /* [↓] Brownian motion is coming. */ - xb=x + random(1, 3) - 2 /* apply Brownian motion for X. */ - yb=y + random(1, 3) - 2 /* " " " " Y. */ + xb=x + random(1, 3) - 2 /* apply Brownian motion for X. */ + yb=y + random(1, 3) - 2 /* " " " " Y. */ if @.xb.yb\==hole then iterate /*can the mote actually move to there ?*/ @.x.y=hole /*"empty out" the old mote position. */ @.xb.yb=mote /*move the mote (or possibly not). */ @@ -81,7 +79,7 @@ loY=1; hiY=height /* " " " " " end /*x*/ call crop /*crops (or truncates) the mote field.*/ - end /*winks*/ + end /*winks*/ /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ call show exit /*stick a fork in it, we're all done. */ @@ -100,9 +98,9 @@ crop: if loX>1 & hiX1 & hiY; +import ; + +POINT ::= (X: int, Y: int); +RET_VAL ::= (World: int(2), Rand: RandomGenerator, Point: POINT); + +randomWalk(x, y, world(2), rand) := + let + randX := getRandom(rand); + randY := getRandom(randX.Generator); + nextX := x + (randX.Value mod 3) - 1; + nextY := y + (randY.Value mod 3) - 1; + newStartX := (randX.Value mod (size(world) - 2)) + 2; + newStartY := (randY.Value mod (size(world) - 2)) + 2; + + numNeighbors := world[y-1,x-1] + world[y-1,x] + world[y-1,x+1] + + world[y,x-1] + world[y,x+1] + + world[y+1,x-1] + world[y+1,x] + world[y+1,x+1]; + + outOfBounds := nextX <= 1 or nextY <= 1 or nextX >= size(world) or nextY >= size(world); + in + randomWalk(newStartX, newStartY, world, randY.Generator) when world[y,x] = 1 or outOfBounds + else + (X: x, Y: y) when numNeighbors > 0 + else + randomWalk(nextX, nextY, world, randY.Generator); + +step(rand, world(2)) := + let + walkSeed := getRandom(rand); + newParticle := randomWalk(size(world)/2,size(world)/2, world, seedRandom(walkSeed.Value)); + + newWorld[j] := + world[j] when j /= newParticle.Y + else + setElementAt(world[j], newParticle.X, 1); + in + (World: newWorld, Rand: walkSeed.Generator, Point: newParticle); + + +initialWorld(worldSize, seed) := + let + world[i,j] := 1 when i = worldSize / 2 and j = worldSize / 2 else 0 + foreach i within 1 ... worldSize, + j within 1 ... worldSize; + in + (World: world, Rand: seedRandom(seed), Point: (X: worldSize / 2, Y: worldSize / 2)); diff --git a/Task/Brownian-tree/SequenceL/brownian-tree-2.sequencel b/Task/Brownian-tree/SequenceL/brownian-tree-2.sequencel new file mode 100644 index 0000000000..8c72c0fac5 --- /dev/null +++ b/Task/Brownian-tree/SequenceL/brownian-tree-2.sequencel @@ -0,0 +1,44 @@ +#include +#include +#include "CImg.h" +#include "SL_Generated.h" + +using namespace std; +using namespace cimg_library; + +int main(int argc, char ** argv) +{ + int threads = 0; + int worldSize = 300; if(argc > 1) worldSize = atoi(argv[1]); + int seed = time(NULL); if(argc > 2) seed = atoi(argv[2]); + int scale = 2; if(argc > 3) scale = atoi(argv[3]); + + sl_init(threads); + + _sl_RET_VAL current; + _sl_RET_VAL result; + + const unsigned char black[] = {0}; + + CImg visu(worldSize * scale, worldSize * scale, 1, 1, 0); + CImgDisplay draw_disp(visu); + cout << "Brownian Tree in SequenceL" << endl << "Threads: " << threads << endl; + draw_disp.set_title("Brownian Tree in SequenceL: %d Threads", threads); + + visu.fill(255); + + sl_initialWorld(worldSize, seed, threads, current); + + while(!draw_disp.is_closed()) + { + visu.draw_circle((current.Point.val().Y - 1) * scale, (current.Point.val().X - 1) * scale, scale/2, black, 1); + visu.display(draw_disp); + sl_step(current.Rand.val(), current.World, threads, result); + current = result; + draw_disp.wait(1); + } + + sl_done(); + + return 0; +} diff --git a/Task/Brownian-tree/Sinclair-ZX81-BASIC/brownian-tree.sinclair b/Task/Brownian-tree/Sinclair-ZX81-BASIC/brownian-tree.sinclair new file mode 100644 index 0000000000..261cdb6370 --- /dev/null +++ b/Task/Brownian-tree/Sinclair-ZX81-BASIC/brownian-tree.sinclair @@ -0,0 +1,24 @@ + 10 DIM A$(20,20) + 20 LET A$(10,10)="1" + 30 FOR Y=42 TO 23 STEP -1 + 40 FOR X=0 TO 19 + 50 PLOT X,Y + 60 NEXT X + 70 NEXT Y + 80 UNPLOT 9,33 + 90 FOR I=1 TO 80 +100 LET X=INT (RND*18)+2 +110 LET Y=INT (RND*18)+2 +120 IF A$(X,Y)="1" THEN GOTO 100 +130 UNPLOT X-1,43-Y +140 IF A$(X+1,Y+1)="1" OR A$(X+1,Y)="1" OR A$(X+1,Y-1)="1" OR A$(X,Y+1)="1" OR A$(X,Y-1)="1" OR A$(X-1,Y+1)="1" OR A$(X-1,Y)="1" OR A$(X-1,Y-1)="1" THEN GOTO 230 +150 PLOT X-1,43-Y +160 LET X=X+INT (RND*3)-1 +170 LET Y=Y+INT (RND*3)-1 +180 IF X=1 THEN LET X=19 +190 IF X=20 THEN LET X=2 +200 IF Y=1 THEN LET Y=19 +210 IF Y=20 THEN LET Y=2 +220 GOTO 130 +230 LET A$(X,Y)="1" +240 NEXT I diff --git a/Task/Brownian-tree/Zkl/brownian-tree.zkl b/Task/Brownian-tree/Zkl/brownian-tree.zkl new file mode 100644 index 0000000000..0b969573a2 --- /dev/null +++ b/Task/Brownian-tree/Zkl/brownian-tree.zkl @@ -0,0 +1,33 @@ +w:=h:=400; numParticles:=20000; +bitmap:=PPM(w+2,h+2,0); // add borders as clip regions + +bitmap[w/2,h/2]=0xff|ff|ff; // plant seed +bitmap.circle(w/2,h/2,h/2,0x0f|0f|0f); // plant seeds + +fcn touching(x,y,bitmap){ // is (x,y) touching another pixel? + // (x,y) isn't on the border/edge of bitmap so no edge conditions + var [const] box=T(T(-1,-1),T(0,-1),T(1,-1), + T(-1, 0), T(1, 0), + T(-1, 1),T(0, 1),T(1, 1)); + box.filter1('wrap([(a,b)]){ bitmap[a+x,b+y] }); //-->False: not touching, (a,b) if is +} + +while(numParticles){ + c:=(0x1|00|00).random(0x1|00|00|00) + (0x1|00).random(0x1|00|00) + (0x1).random(0x1|00); + reg x,y; + do{ x=(1).random(w); y=(1).random(h); }while(bitmap[x,y]); // find empty spot + while(1){ // stagger around until bump into a particle, then attach barnicle + if(touching(x,y,bitmap)){ + bitmap[x,y]=c; + bitmap.write(f:=File("foo.ppm","wb")); // tell ImageViewer to update image + numParticles-=1; + break; + } + x+=(-1).random(2); y+=(-1).random(2); // [-1,0,1] + if( not ((0 color border + bitmap[x,y]=c; + break; + } + } +} +bitmap.write(File("foo.ppm","wb")); // the final image diff --git a/Task/Bulls-and-cows-Player/Elixir/bulls-and-cows-player.elixir b/Task/Bulls-and-cows-Player/Elixir/bulls-and-cows-player.elixir index 871fc9ca45..d61b0eb35e 100644 --- a/Task/Bulls-and-cows-Player/Elixir/bulls-and-cows-player.elixir +++ b/Task/Bulls-and-cows-Player/Elixir/bulls-and-cows-player.elixir @@ -10,11 +10,9 @@ defmodule Bulls_and_cows do case get_score(size) do {^size, 0} -> IO.puts "Solved!" score -> - selected = select(size, possibility, guess, score) - if selected==[] do - IO.puts "Sorry! I can't find a solution. Possible mistake in the scoring." - else - player(size, selected, i+1) + case select(size, possibility, guess, score) do + [] -> IO.puts "Sorry! I can't find a solution. Possible mistake in the scoring." + selected -> player(size, selected, i+1) end end end diff --git a/Task/Bulls-and-cows-Player/Kotlin/bulls-and-cows-player.kotlin b/Task/Bulls-and-cows-Player/Kotlin/bulls-and-cows-player.kotlin new file mode 100644 index 0000000000..1867e9463c --- /dev/null +++ b/Task/Bulls-and-cows-Player/Kotlin/bulls-and-cows-player.kotlin @@ -0,0 +1,52 @@ +// version 1.1.2 + +import java.util.Random + +fun countBullsAndCows(guess: IntArray, answer: IntArray): Pair { + var bulls = 0 + var cows = 0 + for ((i, d) in guess.withIndex()) { + if (answer[i] == d) bulls++ + else if (d in answer) cows++ + } + return bulls to cows +} + +fun main(args: Array) { + val r = Random() + val choices = mutableListOf() + // generate all possible distinct 4 digit (1 to 9) integer arrays + for (i in 1..9) { + for (j in 1..9) { + if (j == i) continue + for (k in 1..9) { + if (k == i || k == j) continue + for (l in 1..9) { + if (l == i || l == j || l == k) continue + choices.add(intArrayOf(i, j, k, l)) + } + } + } + } + + // pick one at random as the answer + val answer = choices[r.nextInt(choices.size)] + + // keep guessing, pruning the list as we go based on the score, until answer found + while (true) { + val guess = choices[r.nextInt(choices.size)] + val (bulls, cows) = countBullsAndCows(guess, answer) + println("Guess = ${guess.joinToString("")} Bulls = $bulls Cows = $cows") + if (bulls == 4) { + println("You've just found the answer!") + return + } + for (i in choices.size - 1 downTo 0) { + val (bulls2, cows2) = countBullsAndCows(choices[i], answer) + // if score is no better remove it from the list of choices + if (bulls2 <= bulls && cows2 <= cows) choices.removeAt(i) + } + if (choices.size == 0) + println("Something went wrong as no choices left! Aborting program") + } +} diff --git a/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx b/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx index 58f5340608..34482cd70c 100644 --- a/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx +++ b/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx @@ -1,60 +1,60 @@ -/*REXX program plays Bulls & Cows game with CBLFs (Carbon Based Life Forms).*/ -call gen@ /*generate all the possibilities. */ -call # /*get the first guess for the game. */ +/*REXX program plays the Bulls & Cows game with CBLFs (Carbon Based Life Forms). */ +call gen@ /*generate all the possibilities. */ +call # /*get the first guess for the game. */ do tries=1 until #()<2 | bull==4; say call prompter - do ?=L to H /*traipse through the whole list. */ - if @.?==. then iterate /*was this choice already eliminated ? */ - call bull# ?,g /*obtain the bulls and cows count. */ - if bull\==bulls | cow\==cows then @.?=. /*eliminate choice.*/ + do ?=L to H /*traipse through the whole list. */ + if @.?==. then iterate /*was this choice already eliminated ? */ + call bull# ?,g /*obtain the bulls and cows count. */ + if bull\==bulls | cow\==cows then @.?=. /*eliminate choice. */ end /*?*/ call # end /*tries*/ -if #==0 then do; call serr "At least one of your responses was invalid."; exit; end -say; say " ╔═════════════════════════════════════════════════╗" - say " ║ ║" - say " ║ Your secret Bulls and Cows number is: " g " ║" - say " ║ ║" - say " ╚═════════════════════════════════════════════════╝"; say +if #==0 then do; call serr "At least one of your responses was invalid."; exit; end +say; say " ╔═════════════════════════════════════════════════╗" + say " ║ ║" + say " ║ Your secret Bulls and Cows number is: " g " ║" + say " ║ ║" + say " ╚═════════════════════════════════════════════════╝"; say say tries 'tries.' -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────one─liner subroutines─────────────────────*/ -#: #=0; do k=L to H; if @.k==. then iterate; #=#+1; g=k; end; return # -gen@: @.=.; L=1234; H=9876; do j=L to H; if genOK() then @.j=j; end; return -genOK: if pos(0,j)\==0 then return 0; return \rep() -rep: do k=1 for 3; if pos(substr(j,k,1),j,k+1)\==0 then return 1; end; return 0 -serr: say; say pad '***error!*** ' ! arg(1); return -/*────────────────────────────────────────────────────────────────────────────*/ -bull#: parse arg n,q; L=length(n); bulls=0; cows=0 /*initialize some vars.*/ - do j=1 for L; if substr(n,j,1)\==substr(q,j,1) then iterate - bulls=bulls+1 /*bump the bull counter. */ - q=overlay(.,q,j) /*disallow this for a cow count.*/ - end /*j*/ /* [↑] bull count═══════════════*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +#: #=0; do k=L to H; if @.k==. then iterate; #=#+1; g=k; end; return # +gen@: @.=.; L=1234; H=9876; do j=L to H; if genOK() then @.j=j; end; return +genOK: if pos(0, j)\==0 then return 0; return \rep() +rep: do k=1 for 3; if pos(substr(j,k,1),j,k+1)\==0 then return 1; end; return 0 +serr: say; say pad '***error*** ' ! arg(1); return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +bull#: parse arg n,q; L=length(n); bulls=0; cows=0 /*initialize some vars.*/ + do j=1 for L; if substr(n,j,1) \== substr(q,j,1) then iterate + bulls=bulls+1 /*bump the bull counter. */ + q=overlay(.,q,j) /*disallow this for a cow count.*/ + end /*j*/ /* [↑] bull count═══════════════*/ - do k=1 for L; _=substr(n,k,1); if pos(_,q)==0 then iterate - cows=cows+1 /*bump the cow counter. */ - q=translate(q,,_) /*this allows for multiple digits*/ - end /*k*/ /* [↑] cow count═══════════════*/ + do k=1 for L; _=substr(n,k,1); if pos(_, q)==0 then iterate + cows=cows + 1 /*bump the cow counter. */ + q=translate(q, , _) /*this allows for multiple digits*/ + end /*k*/ /* [↑] cow count═══════════════*/ return -/*────────────────────────────────────────────────────────────────────────────*/ -prompter: pad='─────' /*define PAD characters for messages.*/ - do forever; say - say pad "How many bulls and cows were guessed with " g '? [─── or QUIT]' - pull x 1 bull cow _ . /*PULL capitalizes the arguments.*/ - if abbrev('QUIT',x,1) then exit /*the user wants to quit playing.*/ - select - when bull=='' then != "no numbers were entered." - when cow =='' then != "not enough numbers were entered." - when _\=='' then != "too many numbers entered: " x - when \datatype(bull,'W') then != "1st number (bulls) not an integer: " bull - when \datatype(cow ,'W') then != "2nd number (cows) not an integer: " cow - when bull <0 | bull >4 then != "1st number (bulls) not 0──►4: " bull - when cow <0 | cow >4 then != "2nd number (cows) not 0──►4: " cow - when bull + cow > 4 then != "sum of bulls and cows can't be > 4: " x - otherwise != - end /*select*/ - if !\=='' then do; call serr; iterate; end /*prompt the user again.*/ - bull=bull/1; cow=cow/1; return /*normalize 2 bulls & cows #s; return.*/ - end /*forever*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +prompter: pad= '─────' /*define PAD characters for msgs.*/ + do forever; say + say pad "How many bulls and cows were guessed with " g '? [─── or QUIT]' + pull x 1 bull cow _ . /*PULL capitalizes the arguments.*/ + if abbrev('QUIT', x, 1) then exit /*the user wants to quit playing.*/ + select + when bull=='' then != "no numbers were entered." + when cow =='' then != "not enough numbers were entered." + when _\=='' then != "too many numbers entered: " x + when \datatype(bull, 'W') then != "1st number (bulls) not an integer: " bull + when \datatype(cow , 'W') then != "2nd number (cows) not an integer: " cow + when bull <0 | bull >4 then != "1st number (bulls) not 0 ──► 4: " bull + when cow <0 | cow >4 then != "2nd number (cows) not 0 ──► 4: " cow + when bull + cow > 4 then != "sum of bulls and cows can't be > 4: " x + otherwise != + end /*select*/ + if !\=='' then do; call serr; iterate; end /*prompt the user and try again. */ + bull=bull/1; cow=cow/1; return /*normalize bulls & cows numbers.*/ + end /*forever*/ diff --git a/Task/Bulls-and-cows-Player/Zkl/bulls-and-cows-player.zkl b/Task/Bulls-and-cows-Player/Zkl/bulls-and-cows-player.zkl new file mode 100644 index 0000000000..0971d3379a --- /dev/null +++ b/Task/Bulls-and-cows-Player/Zkl/bulls-and-cows-player.zkl @@ -0,0 +1,15 @@ +d9:="123456789"; +choices:=Walker.cproduct(d9,d9,d9,d9).pump(List,// lazy,-->3024, order is important + fcn(list){ s:=list.concat(); (s.unique().len()==4) and s or Void.Skip }); +do{ + guess:=choices[(0).random(choices.len())]; + score:=ask("My guess is %s. How many bulls and cows? ".fmt(guess)).strip(); + bulls,cows:=score.split("").apply("toInt"); // "12"-->(1,2) + choices=choices.filter('wrap(c){ + bulls==c.zipWith('==,guess).sum(0) and // 0 + True == 1 + cows ==c.zipWith('wrap(a,b){ a!=b and guess.holds(a) },guess).sum(0) + }); +}while(choices.len()>1); + +if(not choices) "Nothing fits the scores you gave.".println(); +else "Solution found: ".println(choices[0]); diff --git a/Task/Bulls-and-cows/00DESCRIPTION b/Task/Bulls-and-cows/00DESCRIPTION index 0081809611..c51bdddcd8 100644 --- a/Task/Bulls-and-cows/00DESCRIPTION +++ b/Task/Bulls-and-cows/00DESCRIPTION @@ -20,4 +20,5 @@ The score is computed as: *   [[Bulls and cows/Player]] *   [[Guess the number]] *   [[Guess the number/With Feedback]] +*   [[Mastermind]]

    diff --git a/Task/Bulls-and-cows/00META.yaml b/Task/Bulls-and-cows/00META.yaml index a2413d963b..f7f95b3d15 100644 --- a/Task/Bulls-and-cows/00META.yaml +++ b/Task/Bulls-and-cows/00META.yaml @@ -1,2 +1,5 @@ --- +category: +- Puzzles +- Games note: Games diff --git a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena index 34a1ea299b..673fb94fb0 100644 --- a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena +++ b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena @@ -1,81 +1,84 @@ -#define system. -#define system'routines. -#define extensions. +import system'routines. +import extensions. -#class GameMaster +class GameMaster { - #field theNumbers. - #field theAttempt. + object theNumbers. + object theAttempt. - #constructor new + constructor new [ // generate secret number - #var aRandomNumbers := (1,2,3,4,5,6,7,8,9) randomize:9. + var aRandomNumbers := (1,2,3,4,5,6,7,8,9) randomize:9. - theNumbers := aRandomNumbers Subarray &index:0 &length:4. + theNumbers := aRandomNumbers Subarray:4 at:0. theAttempt := Integer new:1. ] - #method ask + ask [ - #var aRow := console writeLiteral:"Your Guess #":theAttempt:" ?" readLine. + var aRow := console print("Your Guess #",theAttempt," ?"); readLine. ^ aRow toArray. ] - #method proceed : aGuess + proceed : aGuess [ - #var aCows := Integer new:0. - #var aBulls := Integer new:0. + var aCows := Integer new:0. + var aBulls := Integer new:0. - (aGuess length != 4) - ? [ aBulls << -1. ] - ! [ - 0 to:3 &doEach: (:i) + if (aGuess length != 4) + [ aBulls append int:(-1). ]; + [ + try(0 to:3 do(:i) [ - #var ch := aGuess@i. - #var aNumber := ch literal toInt. + var ch := aGuess[i]. + var aNumber := ch literal; toInt. // check range - ((aNumber > 0)and:(aNumber < 10)) - ! [ #throw InvalidArgumentException new. ]. + ifnot ((aNumber > 0) && (aNumber < 10)) + [ InvalidArgumentException new; raise. ]. // check duplicates - #var duplicate := aGuess seek &each: x [ (x == ch)and:[ x equal &reference:ch not ] ]. - (nil != duplicate) ? + var duplicate := aGuess seekEach(:x)((x == ch)and:$(x equal reference:ch; not)). + if ($nil != duplicate) [ - #throw InvalidArgumentException new. + InvalidArgumentException new; raise. ]. - (aNumber == (theNumbers@i)) - ? [ aBulls += 1. ] - ! [ + if (aNumber == theNumbers[i]) + [ aBulls append int:1 ]; + [ (theNumbers ifExists:aNumber) - ? [ aCows += 1. ]. + ? [ aCows append int:1 ]. ]. - ] - | if &Error: e - [ - aBulls << -1. - ]. + ]) + { + on(Exception e) + [ + aBulls int := -1 + ] + }. ]. - ^ aBulls => - -1 ? [ console writeLine:"Not a valid guess.". ^ true. ] - 4 ? [ console writeLine:"Congratulations! You have won!". ^ false. ] + aBulls => + -1 [ console printLine:"Not a valid guess.". ^ true ]; + 4 [ console printLine:"Congratulations! You have won!". ^ false ]; ! [ - theAttempt += 1. + theAttempt append int:1. - console writeLine:"Your Score is " : aBulls : " bulls and " : aCows : " cows". + console printLine("Your Score is ",aBulls," bulls and ",aCows," cows"). - ^ true. + ^ true ]. ] } -#symbol program = +program = [ - #var aGameMaster := GameMaster new. + var aGameMaster := GameMaster new. - [ aGameMaster proceed:(aGameMaster ask) ] doWhile. + $(aGameMaster proceed:(aGameMaster ask)) doWhile. + + console readChar. ]. diff --git a/Task/Bulls-and-cows/Go/bulls-and-cows-1.go b/Task/Bulls-and-cows/Go/bulls-and-cows-1.go deleted file mode 100644 index a4b59f82ad..0000000000 --- a/Task/Bulls-and-cows/Go/bulls-and-cows-1.go +++ /dev/null @@ -1,68 +0,0 @@ -package main - -import ( - "bufio" - "bytes" - "fmt" - "math/rand" - "os" - "strings" - "time" -) - -func main() { - fmt.Println(`Cows and Bulls -Guess four digit number of unique digits in the range 1 to 9. -A correct digit but not in the correct place is a cow. -A correct digit in the correct place is a bull.`) - // generate pattern - pat := make([]byte, 4) - rand.Seed(time.Now().Unix()) - r := rand.Perm(9) - for i := range pat { - pat[i] = '1' + byte(r[i]) - } - - // accept and score guesses - valid := []byte("123456789") -guess: - for in := bufio.NewReader(os.Stdin); ; { - fmt.Print("Guess: ") - guess, err := in.ReadString('\n') - if err != nil { - fmt.Println("\nSo, bye.") - return - } - guess = strings.TrimSpace(guess) - if len(guess) != 4 { - // malformed: not four characters - fmt.Println("Please guess a four digit number.") - continue - } - var cows, bulls int - for ig, cg := range guess { - if strings.IndexRune(guess[:ig], cg) >= 0 { - // malformed: repeated digit - fmt.Printf("Repeated digit: %c\n", cg) - continue guess - } - switch bytes.IndexByte(pat, byte(cg)) { - case -1: - if bytes.IndexByte(valid, byte(cg)) == -1 { - // malformed: not a digit - fmt.Printf("Invalid digit: %c\n", cg) - continue guess - } - default: // I just think cows should go first - cows++ - case ig: - bulls++ - } - } - fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls) - if bulls == 4 { - fmt.Println("You got it.") - return - } - } -} diff --git a/Task/Bulls-and-cows/Go/bulls-and-cows-2.go b/Task/Bulls-and-cows/Go/bulls-and-cows-2.go deleted file mode 100644 index 7af3905e62..0000000000 --- a/Task/Bulls-and-cows/Go/bulls-and-cows-2.go +++ /dev/null @@ -1,117 +0,0 @@ -package main - -import ( - . "fmt" - "rand" - "time" - "os" - "bufio" - "strconv" - "strings" -) - -func generateTarget() int { - rand.Seed(time.Nanoseconds()) - // loop until we find a number that doesn't have dupes - for { - target := rand.Intn(9000) + 1000 - if !hasDupes(target) { - return target - } - } - panic("Crap.") -} - -func hasDupes(num int) bool { - digs := make([]bool, 10) - for num > 0 { - if digs[num%10] { - return true - } - digs[num%10] = true - num /= 10 - } - return false -} - -func askForNumber() (int, os.Error) { - in := bufio.NewReader(os.Stdin) - - for { - Print("Give me a number: ") - line, err := in.ReadString('\n') - - if err != nil { - return -1, err - } - - // Strip off the \n - line = line[0 : len(line)-1] - number, err := strconv.Atoi(line) - - switch { - case err != nil: - Println("Give me a number fule!") - case number < 1000: - Println("Number not long enough") - case number > 9999: - Println("Number is to big") - case hasDupes(number): - Println("I said no dupes!") - default: - return number, nil - } - // Keep Asking - } - panic("Crap.") -} - -func bullsAndCows(number int, guess int) (bulls int, cows int) { - bulls, cows = 0, 0 - numberstr := strconv.Itoa(number) - guessstr := strconv.Itoa(guess) - - for i := range guessstr { - s := string(guessstr[i]) - switch { - case guessstr[i] == numberstr[i]: - bulls++ - case strings.Index(numberstr, s) >= 0: - cows++ - } - } - return; -} - -func main() { - attempts := 0 - - Print("I choose a number made of 4 digits (from 1 to 9) without repetitions\n" - "You enter a number of 4 digits, and I say you how many of them are\n" - "in my secret number but in wrong position (cows or O), and how many\n" - "are in the right position (bulls or X)\n\n") - - target := generateTarget() - - for { - guess, err := askForNumber() - attempts++ - - // Handle err - if err != nil && err != os.EOF { - Print(err) - } else if err == os.EOF { - return - } - - // Check if target matches guess - if guess == target { - Printf("Congratulations you guessed correctly in %d attempts\n", attempts) - return - } - - bulls, cows := bullsAndCows(target, guess) - Printf("%d Bulls, %d Cows\n", bulls, cows) - } - -} diff --git a/Task/Bulls-and-cows/Kotlin/bulls-and-cows.kotlin b/Task/Bulls-and-cows/Kotlin/bulls-and-cows.kotlin new file mode 100644 index 0000000000..ce39836aa7 --- /dev/null +++ b/Task/Bulls-and-cows/Kotlin/bulls-and-cows.kotlin @@ -0,0 +1,49 @@ +// version 1.1.2 + +import java.util.Random + +const val MAX_GUESSES = 20 // say + +fun main(args: Array) { + val r = Random() + var num: String + // generate a 4 digit random number from 1234 to 9876 with no zeros or repeated digits + do { + num = (1234 + r.nextInt(8643)).toString() + } while ('0' in num || num.toSet().size < 4) + + println("All guesses should have exactly 4 distinct digits excluding zero.") + println("Keep guessing until you guess the chosen number (maximum $MAX_GUESSES valid guesses).\n") + var guesses = 0 + while (true) { + print("Enter your guess : ") + val guess = readLine()!! + if (guess == num) { + println("You've won with ${++guesses} valid guesses!") + return + } + val n = guess.toIntOrNull() + if (n == null) + println("Not a valid number") + else if ('-' in guess || '+' in guess) + println("Can't contain a sign") + else if ('0' in guess) + println("Can't contain zero") + else if (guess.length != 4) + println("Must have exactly 4 digits") + else if (guess.toSet().size < 4) + println("All digits must be distinct") + else { + var bulls = 0 + var cows = 0 + for ((i, c) in guess.withIndex()) { + if (num[i] == c) bulls++ + else if (c in num) cows++ + } + println("Your score for this guess: Bulls = $bulls Cows = $cows") + guesses++ + if (guesses == MAX_GUESSES) + println("You've now had $guesses valid guesses, the maximum allowed") + } + } +} diff --git a/Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx b/Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx index 54e65904ff..c6ba98c0e3 100644 --- a/Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx +++ b/Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx @@ -1,33 +1,31 @@ -/*REXX pgm scores Bulls & Cows game with CBLFs (Carbon Based Life Forms)*/ -?=; do until length(?)==4 /*generate unique 4-digit number.*/ - r=random(1,9) /*change 1──►0 to allow a 0 dig*/ - if pos(r,?)\==0 then iterate /*don't allow a repeated digit. */ - ?=? || r /*add random dig by concatenation*/ - end /*until length··· */ /* [↑] builds a unique 4-digit #*/ +/*REXX program scores the Bulls & Cows game with CBLFs (Carbon Based Life Forms). */ +?=; do until length(?)==4 /*generate a unique four-digit number. */ + r=random(1, 9) /*change 1──► 0 to allow a zero digit*/ + if pos(r, ?)\==0 then iterate /*don't allow a repeated digit/numeral.*/ + ?=? || r /*add random digit by concatenation. */ + end /*until length ···*/ /* [↑] builds a unique four-digit num.*/ +id= '──────── [Bulls & Cows] ' + do until bulls==4; say /*play until guessed or enters "QUIT".*/ + say id 'Please enter a 4-digit guess (with no zeroes) [or Quit]:' + pull n; n=space(n,0); if abbrev('QUIT',n,1) then exit /*wants to quit ? */ + q=?; L=length(n); bulls=0; cows=0 /*initialize some REXX variables. */ - do until bulls==4; say /*play until guessed |enters QUIT*/ - say '───── [Bulls & Cows] Please enter a 4-digit guess (with no zeroes) [or Quit]:' - pull n; n=space(n,0); if abbrev('QUIT',n,1) then exit /*Quit ?*/ - q=?; L=length(n); bulls=0; cows=0 /*initialize some REXX variables.*/ - - do j=1 for L; if substr(n,j,1)\==substr(q,j,1) then iterate - bulls=bulls+1 /*bump the bull count. */ - q=overlay(.,q,j) /*disallow this for a cow count. */ - end /*j*/ /* [↑] bull count───────────────*/ - - do k=1 for L; _=substr(n,k,1); if pos(_,q)==0 then iterate - cows=cows+1 /*bump the cow count. */ - q=translate(q,,_) /*this allows for multiple digits*/ - end /*k*/ /* [↑] cow count───────────────*/ - say - if L\==0 & bulls\==4 then say "───── You got" bulls 'bull's(bulls) "and" cows 'cow's(cows)"." - end /*until bulls···*/ - -say; say " ┌─────────────────────────────────────────┐" - say " │ │" - say " │ Congratulations, you've guessed it !! │" - say " │ │" - say " └─────────────────────────────────────────┘"; say -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────S subroutine────────────────────────*/ -s: if arg(1)==1 then return ''; return 's' /*handles plurals.*/ + do j=1 for L; if substr(n,j,1)\==substr(q, j, 1) then iterate /*bull? */ + bulls=bulls+1; q=overlay(.,q,j) /*bump bull count; disallow for cow*/ + end /*j*/ /* [↑] bull count─────────────────*/ + /*cow ? */ + do k=1 for L; _=substr(n,k,1); if pos(_,q)==0 then iterate + cows=cows+1 ; q=translate(q, , _) /*bump cow count; allow mult digits*/ + end /*k*/ /* [↑] cow count─────────────────*/ + say; @='You got' bulls + if L\==0 & bulls\==4 then say id @ 'bull's(bulls) "and" cows 'cow's(cows). + end /*until bulls==4*/ +say + say " ┌─────────────────────────────────────────┐" + say " │ │" + say " │ Congratulations, you've guessed it !! │" + say " │ │" + say " └─────────────────────────────────────────┘"; say +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +s: if arg(1)==1 then return ''; return 's' /*this function handles pluralization. */ diff --git a/Task/Bulls-and-cows/Sidef/bulls-and-cows.sidef b/Task/Bulls-and-cows/Sidef/bulls-and-cows.sidef index d91595cb79..d41e335c16 100644 --- a/Task/Bulls-and-cows/Sidef/bulls-and-cows.sidef +++ b/Task/Bulls-and-cows/Sidef/bulls-and-cows.sidef @@ -6,10 +6,11 @@ for (var guesses = 1; true; guesses++) { var bulls = 0 var cows = 0 - var input = Sys.scanln("Input: ").chars \ - .unique \ - .grep {.~~/^[1-9]$/} \ - .map {.to_i} + var input = + read("Input: ", String).chars \ + .uniq \ + .grep(/^[1-9]$/) \ + .map{.to_n} if (input.len != size) { warn "Invalid input!\n" @@ -22,7 +23,7 @@ for (var guesses = 1; true; guesses++) { break } - num.range.each { |i| + for i (^num) { if (num[i] == input[i]) { bulls++ } diff --git a/Task/Bulls-and-cows/Smart-BASIC/bulls-and-cows.smart b/Task/Bulls-and-cows/Smart-BASIC/bulls-and-cows.smart new file mode 100644 index 0000000000..bbce63b272 --- /dev/null +++ b/Task/Bulls-and-cows/Smart-BASIC/bulls-and-cows.smart @@ -0,0 +1,87 @@ +'by rbytes, January 2017 +OPTION BASE 1 +P(" B U L L S A N D C O W S")!l +P("A secret 4-digit number has been created, with") +P("no repeats and no zeros. You must guess the number.") +P("After each guess, you will be shown how many of your") +P("digits are correct and in the matching location (bulls),") +P("and how many are correct but in a different location (cows).") +p("See how many tries it takes you to get the right answer.") +' generate a 4-digit number with no repeats +guesses = 0 +1 WHILE LEN(sec$) <4 + c$ =CHR$( INTEG(RND(1) *9) +49) + IF INSTR(sec$, c$)=-1 THEN sec$&=c$ +ENDWHILE!l +2 PRINT "Your guess: " +INPUT "FOUR DIGITS": guess$!l +IF guess$="" THEN ' check if entry is null + P("Please enter something!")!l + GOTO 2 +ENDIF +P(guess$)!l +IF LEN(guess$)<>4 THEN ' check if entry is exactly 4 characters + P("Please enter exactly 4 digits.")!l + GOTO 2 +ENDIF +FOR t=1 TO 4 ' check if all characters are digits 1 - 9 + IF INSTR("123456789",MID$(guess$,t,1))=-1 THEN + P("You have entered at least one illegal character")!l + GOTO 2 + ENDIF +NEXT t +rep = check(guess$) ' check if any digits are repeated +IF check.chk THEN + P("Please enter a number with no repeated digits.")!l + GOTO 2 +ENDIF + +guesses+=1 +r$=score$(guess$,sec$) +P(r$)!l + +IF guess$=sec$ THEN + P("W I N N E R ! ! !")!l + IF guesses>1 THEN gs$="guesses!" ELSE gs$="guess!" + P("You won after "&guesses&" "&gs$) + P("Thanks for playing!")!l + PAUSE 2 + P("A G A I N with a new secret number")!l + guesses=0 +END IF +GOTO 1 +END ' _____________________________________________________________ + +DEF P(p$) ' function to print a string + PRINT p$ +END DEF + +DEF L() ' function to print an empty line + PRINT +END DEF + +DEF check(i$) ' check=0 if digit is not repeated, else=1 + chk=0 + FOR i =1 TO 3 + FOR j =i +1 TO 4 + IF MID$( i$, i, 1)=MID$( i$, j, 1) THEN chk =1 + NEXT j + NEXT i +END DEF + +DEF score$(a$,b$) ' calculate the numbers of bulls & cows. + bulls=0!cows=0 + FOR i = 1 TO 4 + c$ = MID$( a$, i, 1) + IF MID$( b$, i, 1)=c$ THEN + bulls+=1 + ELSE + IF INSTR( b$, c$) <>-1 AND INSTR( b$, c$) <>i THEN + cows+=1 + END IF + END IF + NEXT i + r$ ="Bulls: "&STR$( bulls)& ", "& "Cows: " &STR$( cows) + RETURN r$ +END DEF +END diff --git a/Task/Bulls-and-cows/Zkl/bulls-and-cows.zkl b/Task/Bulls-and-cows/Zkl/bulls-and-cows.zkl new file mode 100644 index 0000000000..d1f84e03d4 --- /dev/null +++ b/Task/Bulls-and-cows/Zkl/bulls-and-cows.zkl @@ -0,0 +1,12 @@ +d:=Dictionary(); do{ d[(1).random(10)]=True }while(d.len()<4); +abcd:=d.keys.shuffle(); +while(1){ + guess:=ask("4 digits: ")-" ,"; + if(guess.len()!=4 or guess.unique().len()!=4) continue; + bulls:=abcd.zipWith('==,guess).sum(0); + cows:=guess.split("").enumerate() + .reduce('wrap(s,[(n,c)]){ s + (d.find(c,False) and abcd[n]!=c) },0); + if(bulls==4) { println("You got it!"); break; } + "%d bull%s and %d cow%s".fmt(bulls,s(bulls),cows,s(cows)).println(); +} +fcn s(n){ (n!=1) and "s" or "" } diff --git a/Task/CRC-32/FreeBASIC/crc-32.freebasic b/Task/CRC-32/FreeBASIC/crc-32.freebasic new file mode 100644 index 0000000000..940e42e271 --- /dev/null +++ b/Task/CRC-32/FreeBASIC/crc-32.freebasic @@ -0,0 +1,50 @@ +' version 18-03-2017 +' compile with: fbc -s console + +Function crc32(buf As String) As UInteger<32> + + Static As UInteger<32> table(256) + Static As UInteger<32> have_table + Dim As UInteger<32> crc, k + Dim As ULong i, j + + If have_table = 0 Then + For i = 0 To 255 + k = i + For j = 0 To 7 + If (k And 1) Then + k Shr= 1 + k Xor= &Hedb88320 + Else + k Shr= 1 + End If + table(i) = k + Next + Next + have_table = 1 + End If + + crc = Not crc ' crc = &Hffffffff + + For i = 0 To Len(buf) -1 + crc = (crc Shr 8) Xor table((crc And &hff) Xor buf[i]) + Next + + Return Not crc + +End Function + +' ------=< MAIN >=------ + +Dim As String l = "The quick brown fox jumps over the lazy dog" +Dim As UInteger<32> crc + +Print "input = "; l +print +Print "The CRC-32 checksum = "; Hex(crc32(l), 8) + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/CRC-32/Kotlin/crc-32.kotlin b/Task/CRC-32/Kotlin/crc-32.kotlin new file mode 100644 index 0000000000..4896682de8 --- /dev/null +++ b/Task/CRC-32/Kotlin/crc-32.kotlin @@ -0,0 +1,12 @@ +// version 1.0.6 + +import java.util.zip.CRC32 + +fun main(args: Array) { + val text = "The quick brown fox jumps over the lazy dog" + val crc = CRC32() + with (crc) { + update(text.toByteArray()) + println("The CRC-32 checksum of '$text' = ${"%x".format(value)}") + } +} diff --git a/Task/CRC-32/OoRexx/crc-32.rexx b/Task/CRC-32/OoRexx/crc-32.rexx new file mode 100644 index 0000000000..99de0ee40a --- /dev/null +++ b/Task/CRC-32/OoRexx/crc-32.rexx @@ -0,0 +1,9 @@ +/* ooRexx */ +clzCRC32=bsf.importClass("java.util.zip.CRC32") +myCRC32 =clzCRC32~new +toBeEncoded="The quick brown fox jumps over the lazy dog" +myCRC32~update(BsfRawBytes(toBeEncoded)) +numeric digits 20 +say 'The CRC-32 value of "'toBeEncoded'" is:' myCRC32~getValue~d2x + +::requires "BSF.CLS" -- get Java bridge diff --git a/Task/CRC-32/Perl-6/crc-32-2.pl6 b/Task/CRC-32/Perl-6/crc-32-2.pl6 index 01c6ca7bb8..40c93e14b2 100644 --- a/Task/CRC-32/Perl-6/crc-32-2.pl6 +++ b/Task/CRC-32/Perl-6/crc-32-2.pl6 @@ -8,7 +8,7 @@ sub crc( :@bitorder = 0..7, # default: eat bytes LSB-first :@crcorder = 0..$n-1, # default: MSB of checksum is coefficient of x⁰ ) { - my @bit = flat ($buf.list X+& (1 X+< @bitorder).list)».so».Int, 0 xx $n; + my @bit = flat ($buf.list X+& (1 X+< @bitorder))».so».Int, 0 xx $n; @bit[0 .. $n-1] «+^=» @init; @bit[$_ ..$_+$n] «+^=» @poly if @bit[$_] for 0..@bit.end-$n; diff --git a/Task/CRC-32/Visual-Basic-.NET/crc-32-1.visual b/Task/CRC-32/Visual-Basic-.NET/crc-32-1.visual new file mode 100644 index 0000000000..1df0286865 --- /dev/null +++ b/Task/CRC-32/Visual-Basic-.NET/crc-32-1.visual @@ -0,0 +1,29 @@ +Public Class Crc32 + + ' Table for pre-calculated values. + Shared table(255) As UInteger + + ' Initialize table + Shared Sub New() + For i As UInteger = 0 To table.Length - 1 + Dim te As UInteger = i ' table entry + For j As Integer = 0 To 7 + If (te And 1) = 1 Then te = (te >> 1) Xor &HEDB88320UI Else te >>= 1 + Next + table(i) = te + Next + End Sub + + ' Return checksum calculation for Byte Array, + ' optionally resuming (used when breaking a large file into read-buffer-sized blocks). + ' Call with Init = False to continue calculation. + Public Shared Function cs(BA As Byte(), Optional Init As Boolean = True) As UInteger + Static crc As UInteger + If Init Then crc = UInteger.MaxValue + For Each b In BA + crc = (crc >> 8) Xor table((crc And &HFF) Xor b) + Next + Return Not crc + End Function + +End Class diff --git a/Task/CRC-32/Visual-Basic-.NET/crc-32-2.visual b/Task/CRC-32/Visual-Basic-.NET/crc-32-2.visual new file mode 100644 index 0000000000..5b7b566b13 --- /dev/null +++ b/Task/CRC-32/Visual-Basic-.NET/crc-32-2.visual @@ -0,0 +1,23 @@ + ' Returns a Byte Array from a string of ASCII characters. + Function Str2BA(Str As String) As Byte() + Return System.Text.Encoding.ASCII.GetBytes(Str) + End Function + + ' Returns a Hex string from an UInteger, formatted to a number of digits, + ' adding leading zeros If necessary. + Function HexF(Value As UInteger, Digits As Integer) As String + HexF = Hex(Value) + If Len(HexF) < Digits Then HexF = StrDup(Digits - Len(HexF), "0") & HexF + End Function + + ' Tests Crc32 class + Sub Test() + Dim Str As String = "The quick brown fox jumps over the lazy dog" + Debug.Print("Input = """ & Str & """") + ' Convert string to Byte Array, compute crc32, and display formatted result + Debug.Print("Crc32 = " & HexF(Crc32.cs(Str2BA(Str)), 8)) + ' This next code demonstrates continuing a crc32 calculation when breaking the input + ' into pieces, such as processing a large file by a series of buffer reads. + Crc32.cs(Str2BA(Mid(Str, 1, 20))) + Debug.Print("Crc32 = " & HexF(Crc32.cs(Str2BA(Mid(Str, 21)), False), 8)) + End Sub diff --git a/Task/CRC-32/Visual-Basic-.NET/crc-32-3.visual b/Task/CRC-32/Visual-Basic-.NET/crc-32-3.visual new file mode 100644 index 0000000000..f9e4962c96 --- /dev/null +++ b/Task/CRC-32/Visual-Basic-.NET/crc-32-3.visual @@ -0,0 +1,3 @@ +Input = "The quick brown fox jumps over the lazy dog" +Crc32 = 414FA339 +Crc32 = 414FA339 diff --git a/Task/CRC-32/Zkl/crc-32.zkl b/Task/CRC-32/Zkl/crc-32.zkl new file mode 100644 index 0000000000..47fe5c1c88 --- /dev/null +++ b/Task/CRC-32/Zkl/crc-32.zkl @@ -0,0 +1,3 @@ +var [const] ZLib=Import("zeelib"); +ZLib.calcCRC32(Data(Void,"The quick brown fox jumps over the lazy dog")); +//-->0x414fa339 diff --git a/Task/CSV-data-manipulation/Aime/csv-data-manipulation.aime b/Task/CSV-data-manipulation/Aime/csv-data-manipulation.aime new file mode 100644 index 0000000000..3eafdfdef1 --- /dev/null +++ b/Task/CSV-data-manipulation/Aime/csv-data-manipulation.aime @@ -0,0 +1,73 @@ +void +read_csv(list t, text path) +{ + file f; + list l; + + f_affix(f, path); + while (f_news(f, l, 0, 0, ",") ^ -1) { + l_append(t, l); + } +} + +list +sum_columns(list t) +{ + list c, l; + integer i; + + l_append(c, "SUM"); + for (i, l in t) { + if (i) { + integer j, sum; + text s; + + sum = 0; + for (j, s in l) { + sum += atoi(s); + } + + l_append(c, sum); + } + } + + return c; +} + +void +add_column(list t, list c) +{ + integer i; + list l; + + for (i, l in t) { + l_append(l, c[i]); + } +} + +void +write_csv(list t, text path) +{ + integer i; + file f; + list l; + + f_create(f, path, 00644); + for (i, l in t) { + f_(f, l[0]); + l_ocall(l, f_, 2, 1, -1, f, ","); + f_newline(f); + } +} + +integer +main(void) +{ + list t; + + read_csv(t, "tmp/CSV_data_manipulation.csv"); + add_column(t, sum_columns(t)); + write_csv(t, "tmp/CSV_data_manipulated.csv"); + + return 0; +} diff --git a/Task/CSV-data-manipulation/Gambas/csv-data-manipulation.gambas b/Task/CSV-data-manipulation/Gambas/csv-data-manipulation.gambas new file mode 100644 index 0000000000..868bb92165 --- /dev/null +++ b/Task/CSV-data-manipulation/Gambas/csv-data-manipulation.gambas @@ -0,0 +1,32 @@ +Public Sub Form_Open() +Dim sData As String = File.Load("data.csv") +Dim sLine, sTemp As String +Dim sOutput As New String[] +Dim siCount As Short +Dim bLine1 As Boolean + +For Each sLine In Split(sData, gb.NewLine) + If Not bLine1 Then + sLine &= ",SUM" + sOutput.Add(sLine) + bLine1 = True + Continue + End If + For Each sTemp In Split(sLine) + siCount += Val(sTemp) + Next + sOutput.Add(sLine & "," & Str(siCount)) + siCount = 0 +Next + +sData = "" + +For Each sTemp In sOutput + sData &= sTemp & gb.NewLine + Print sTemp; + Print +Next + +File.Save(User.home &/ "CSVData.csv", sData) + +End diff --git a/Task/CSV-data-manipulation/JavaScript/csv-data-manipulation.js b/Task/CSV-data-manipulation/JavaScript/csv-data-manipulation-1.js similarity index 100% rename from Task/CSV-data-manipulation/JavaScript/csv-data-manipulation.js rename to Task/CSV-data-manipulation/JavaScript/csv-data-manipulation-1.js diff --git a/Task/CSV-data-manipulation/JavaScript/csv-data-manipulation-2.js b/Task/CSV-data-manipulation/JavaScript/csv-data-manipulation-2.js new file mode 100644 index 0000000000..3358e9cdca --- /dev/null +++ b/Task/CSV-data-manipulation/JavaScript/csv-data-manipulation-2.js @@ -0,0 +1,41 @@ +const fs = require('fs'); + +// formats for the data parameter in the function below: {col1: array | function, col2: array | function} + +function addCols(path, data) { + let csv = fs.readFileSync(path, 'utf8'); + csv = csv.split('\n').map(line => line.trim()); + let colNames = Object.keys(data); + for (let i = 0; i < colNames.length; i++) { + let c = colNames[i]; + if (typeof data[c] === 'function') { + csv = csv.map((line, idx) => idx === 0 + ? line + ',' + c + : line + ',' + data[c](line, idx) + ); + } else if (Array.isArray(data[c])) { + csv = csv.map((line, idx) => idx === 0 + ? line + ',' + c + : line + ',' + data[c][idx - 1] + ); + } + } + fs.createWriteStream(path, { + flag: 'w', + defaultEncoding: 'utf8' + }).end(csv.join('\n')); +} + +addCols('test.csv', { + sum: function (line, idx) { + let s = 0; + line = line.split(',').map(d => +(d.trim())); + for (let i = 0; i < line.length; i++) { + s += line[i]; + } + return s; + }, + id: function(line, idx) { + return idx; + } + }); diff --git a/Task/CSV-data-manipulation/jq/csv-data-manipulation.jq b/Task/CSV-data-manipulation/Jq/csv-data-manipulation.jq similarity index 100% rename from Task/CSV-data-manipulation/jq/csv-data-manipulation.jq rename to Task/CSV-data-manipulation/Jq/csv-data-manipulation.jq diff --git a/Task/CSV-data-manipulation/Kotlin/csv-data-manipulation.kotlin b/Task/CSV-data-manipulation/Kotlin/csv-data-manipulation.kotlin new file mode 100644 index 0000000000..a48e254e76 --- /dev/null +++ b/Task/CSV-data-manipulation/Kotlin/csv-data-manipulation.kotlin @@ -0,0 +1,14 @@ +// version 1.1.3 + +import java.io.File + +fun main(args: Array) { + val lines = File("example.csv").readLines().toMutableList() + lines[0] += ",SUM" + for (i in 1 until lines.size) { + lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } + } + val text = lines.joinToString("\n") + File("example2.csv").writeText(text) // write to new file + println(text) // print to console +} diff --git a/Task/CSV-data-manipulation/Pascal/csv-data-manipulation.pascal b/Task/CSV-data-manipulation/Pascal/csv-data-manipulation.pascal new file mode 100644 index 0000000000..56853989ab --- /dev/null +++ b/Task/CSV-data-manipulation/Pascal/csv-data-manipulation.pascal @@ -0,0 +1,45 @@ +program CSV_Data_Manipulation; +uses Classes, SysUtils; + +var s: string; + ts: tStringList; + inFile, + outFile: Text; + Sum: integer; + Number: string; + +begin + + Assign(inFile,'input.csv'); + Reset(inFile); + + Assign(outFile,'result.csv'); + Rewrite(outFile); + + ts:=tStringList.Create; + ts.StrictDelimiter:=True; + + // Handle the header + ReadLn(inFile,s); // Read a line from input file + ts.CommaText:=s; // Split it to lines + ts.Add('SUM'); // Add a line + WriteLn(outFile,ts.CommaText); // Reassemble it with comma as delimiter + + // Handle the data + while not eof(inFile) do + begin + ReadLn(inFile,s); + ts.CommaText:=s; + + Sum:=0; + for Number in ts do + Sum+=StrToInt(Number); + + ts.Add('%D',[Sum]); + + writeln(outFile, ts.CommaText); + end; + Close(outFile); + Close(inFile); + ts.Free; +end. diff --git a/Task/CSV-data-manipulation/Phix/csv-data-manipulation.phix b/Task/CSV-data-manipulation/Phix/csv-data-manipulation.phix new file mode 100644 index 0000000000..8f8903e2ef --- /dev/null +++ b/Task/CSV-data-manipulation/Phix/csv-data-manipulation.phix @@ -0,0 +1,22 @@ +integer fn = open("test.csv","r") +sequence lines = {} + while 1 do + object line = gets(fn) + if atom(line) then exit end if + lines = append(lines,split(trim(line),',')) + end while + close(fn) + lines[1] = join(lines[1],',')&",SUM" + for i=2 to length(lines) do + sequence s = lines[i] + for j=1 to length(s) do + {{s[j]}} = scanf(s[j],"%d") + end for +-- s[rand(length(s))] = rand(100) -- (if you like) + lines[i] = sprintf("%d,%d,%d,%d,%d,%d",s&sum(s)) + end for + lines = join(lines,'\n') + fn = open("out.csv","w") + puts(fn,lines) + close(fn) + puts(1,lines) diff --git a/Task/CSV-data-manipulation/Stata/csv-data-manipulation.stata b/Task/CSV-data-manipulation/Stata/csv-data-manipulation.stata new file mode 100644 index 0000000000..3cac3dc728 --- /dev/null +++ b/Task/CSV-data-manipulation/Stata/csv-data-manipulation.stata @@ -0,0 +1,4 @@ +import delimited input.csv, clear +replace c5=c3+c4 +drop if mod(c3,3)==0 +export delimited using output.csv, replace diff --git a/Task/CSV-data-manipulation/Zkl/csv-data-manipulation.zkl b/Task/CSV-data-manipulation/Zkl/csv-data-manipulation.zkl new file mode 100644 index 0000000000..8303e4f0cd --- /dev/null +++ b/Task/CSV-data-manipulation/Zkl/csv-data-manipulation.zkl @@ -0,0 +1,8 @@ +csvFile:=File("test.csv"); +header:=csvFile.readln().strip(); // remove trailing "\n" and leading white space +listOfLines:=csvFile.pump(List,fcn(line){ line.strip().split(",").apply("toInt") }); + +newFile:=File("test2.csv","w"); +newFile.writeln(header + ",sum"); +listOfLines.pump(newFile.writeln,fcn(ns){ String(ns.concat(","),",",ns.sum()) }); +newFile.close(); diff --git a/Task/CSV-to-HTML-translation/jq/csv-to-html-translation-1.jq b/Task/CSV-to-HTML-translation/Jq/csv-to-html-translation-1.jq similarity index 100% rename from Task/CSV-to-HTML-translation/jq/csv-to-html-translation-1.jq rename to Task/CSV-to-HTML-translation/Jq/csv-to-html-translation-1.jq diff --git a/Task/CSV-to-HTML-translation/jq/csv-to-html-translation-2.jq b/Task/CSV-to-HTML-translation/Jq/csv-to-html-translation-2.jq similarity index 100% rename from Task/CSV-to-HTML-translation/jq/csv-to-html-translation-2.jq rename to Task/CSV-to-HTML-translation/Jq/csv-to-html-translation-2.jq diff --git a/Task/CSV-to-HTML-translation/jq/csv-to-html-translation-3.jq b/Task/CSV-to-HTML-translation/Jq/csv-to-html-translation-3.jq similarity index 100% rename from Task/CSV-to-HTML-translation/jq/csv-to-html-translation-3.jq rename to Task/CSV-to-HTML-translation/Jq/csv-to-html-translation-3.jq 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.kotlin new file mode 100644 index 0000000000..4cd74fd3b5 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Kotlin/csv-to-html-translation-1.kotlin @@ -0,0 +1,54 @@ +// version 1.1.3 + +val 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!" + +fun main(args: Array) { + val i = " " // indent + val sb = StringBuilder("\n$i\n$i$i\n$i\n$i\n$i$i\n$i$i\n$i\n
    ") + for (c in csv) { + sb.append( when (c) { + '\n' -> "
    " + ',' -> "" + '&' -> "&" + '\'' -> "'" + '<' -> "<" + '>' -> ">" + else -> c.toString() + }) + } + sb.append("
    ") + println(sb.toString()) + println() + + // now using first row as a table header + sb.setLength(0) + sb.append("\n$i\n$i$i\n$i$i$i\n$i$i\n$i\n$i\n$i$i\n$i$i$i\n$i$i$i\n$i$i\n$i$i\n$i$i$i\n$i$i$i\n$i$i\n$i\n
    ") + val hLength = csv.indexOf('\n') + 1 // find length of first row including CR + for (c in csv.take(hLength)) { + sb.append( when (c) { + '\n' -> "
    " + ',' -> "" + else -> c.toString() + }) + } + for (c in csv.drop(hLength)) { + sb.append( when (c) { + '\n' -> "
    " + ',' -> "" + '&' -> "&" + '\'' -> "'" + '<' -> "<" + '>' -> ">" + else -> c.toString() + }) + } + sb.append("
    ") + println(sb.toString()) +} 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.kotlin new file mode 100644 index 0000000000..93e6ee17d5 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Kotlin/csv-to-html-translation-2.kotlin @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + +
    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/REXX/csv-to-html-translation-1.rexx b/Task/CSV-to-HTML-translation/REXX/csv-to-html-translation-1.rexx deleted file mode 100644 index a51d3001ac..0000000000 --- a/Task/CSV-to-HTML-translation/REXX/csv-to-html-translation-1.rexx +++ /dev/null @@ -1,38 +0,0 @@ -/*REXX program to convert CSV ───> HTML table representing the CSV data.*/ -/*REXX program to convert CSV ───> HTML table representing the CSV data.*/ - -arg header_ . /*see if the user wants a header.*/ -wantsHdr= (header_=='HEADER') /*arg (low/upp/mix case)=HEADER ?*/ - - iFID='CSV_HTML.TXT' /*the input fileID. */ -if wantsHdr then oFID='OUTPUTH.HTML' /*output fileID with header, */ - else oFID='OUTPUT.HTML' /* " " without header. */ - - do rows=0 while lines(iFID)\==0 /*read the rows from a (txt) file*/ - row.rows=strip(linein(iFID)) - end /*rows*/ - -convFrom= '& < > "' /*special characters to convert. */ -convTo = '& < > "' /*what they are converted into. */ - -call write ,'' -call write ,'' - - do j=0 for rows; call write 5,'' - tx='td' - if wantsHdr & j==0 then tx='th' - - do while row.j\==''; parse var row.j yyy ',' row.j - do k=1 for words(convFrom) - yyy=changestr(word(convFrom,k),yyy,word(convTo,k)) - end /*k*/ - call write 10,'<'tx">"yyy'" - end /*forever*/ - end /*j*/ - -call write 5,'' -call write ,'
    ' -call write ,'' -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────WRITE subroutine────────────────────*/ -write: call lineout oFID,left('',0||arg(1))arg(2); return diff --git a/Task/CSV-to-HTML-translation/REXX/csv-to-html-translation-2.rexx b/Task/CSV-to-HTML-translation/REXX/csv-to-html-translation-2.rexx deleted file mode 100644 index f1e6eb5a74..0000000000 --- a/Task/CSV-to-HTML-translation/REXX/csv-to-html-translation-2.rexx +++ /dev/null @@ -1,26 +0,0 @@ -/*╔══════════════════════════════╗ CHANGESTR ╔═════════════════════════╗ -╔═╩══════════════════════════════╝ function ╚═════════════════════════╩═╗ -║ new string to be used──────────┐ ┌─────limit of # changes (times)║ -║ original string (haystack)────────┐ │ │ [default: ≈ one billian]║ -║ old string to be changed───┐ │ │ │ ┌───begin at this occurance #.║ -║ {O, H, and N can be null.} │ │ │ │ │ [default: 1st occurrance]║ -╚═╦════════════════════════════╗ │ │ │ │ │ ╔═══════════════════════╦═╝ - ╚════════════════════════════╝ ↓ ↓ ↓ ↓ ↓ ╚═══════════════════════╝*/ -changestr: procedure; parse arg o,h,n,t,b /* T and B are optional.*/ -$='' /*$: the returned string.*/ -t=word(t 999999999 , 1) /*maybe use the default? */ -b=word(b 1 , 1) /* " " " " */ -w=length(o) /*length of OLD string.*/ -if w==0 & t\=0 then return n || h /*changing a null char ? */ -#=0 /*# of changed occurances*/ - do j=1 until # >= t /*keep changing, T times.*/ - parse var h y (o) _ +(w) h /*parse the string ... */ - if _=='' then return $ || y /*no more left, return. */ - if j#{d}" } func csv2html(str) { - var template = <<'-EOT' + var template = <<-'EOT' Some Text diff --git a/Task/CSV-to-HTML-translation/Zkl/csv-to-html-translation-1.zkl b/Task/CSV-to-HTML-translation/Zkl/csv-to-html-translation-1.zkl new file mode 100644 index 0000000000..51b2f2833c --- /dev/null +++ b/Task/CSV-to-HTML-translation/Zkl/csv-to-html-translation-1.zkl @@ -0,0 +1,13 @@ +csvData:=Data(0,Int,"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!"); + +html:=csvData.pump("\n",fcn(line){ + line.replace("&","&").replace("<","<") // --> <angry/> + .split(",") + .pump("\n","strip",String.fpM("101"," \n"))+"\n" +}) + "
    ","
    "; +html.println(); diff --git a/Task/CSV-to-HTML-translation/Zkl/csv-to-html-translation-2.zkl b/Task/CSV-to-HTML-translation/Zkl/csv-to-html-translation-2.zkl new file mode 100644 index 0000000000..f34162b1e0 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Zkl/csv-to-html-translation-2.zkl @@ -0,0 +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!
    diff --git a/Task/Caesar-cipher/8th/caesar-cipher.8th b/Task/Caesar-cipher/8th/caesar-cipher.8th new file mode 100644 index 0000000000..25d3c44de4 --- /dev/null +++ b/Task/Caesar-cipher/8th/caesar-cipher.8th @@ -0,0 +1,23 @@ +\ Ensure the output char is in the correct range: +: modulate \ char base -- char + tuck n:- 26 n:+ 26 n:mod n:+ ; + +\ Symmetric Caesar cipher. Input is text and number of characters to advance +\ (or retreat, if negative). That value should be in the range 1..26 +: caesar \ intext key -- outext + >r + ( + \ Ignore anything below '.' as punctuation: + dup '. n:> if + \ Do the conversion + dup r@ n:+ swap + \ Wrap appropriately + 'A 'Z between if 'A else 'a then modulate + then + ) s:map rdrop ; + +"The five boxing wizards jump quickly!" +dup . cr +1 caesar dup . cr +-1 caesar . cr +bye diff --git a/Task/Caesar-cipher/Astro/caesar-cipher.astro b/Task/Caesar-cipher/Astro/caesar-cipher.astro new file mode 100644 index 0000000000..12a4706887 --- /dev/null +++ b/Task/Caesar-cipher/Astro/caesar-cipher.astro @@ -0,0 +1,8 @@ +fun caesar(s, k, decode: false): + if decode: k = 26 - k + join(char((ord(c) - 65 + k) % 26 + 65) | c in s.upper() where "a" <= c <= "A") + +let msg = "The quick brown fox jumped over the lazy dogs" +print msg +let enc = caesar(msg, 11) +print ..(enc) ..(caesar(enc, 11, decode: true)) diff --git a/Task/Caesar-cipher/BaCon/caesar-cipher.bacon b/Task/Caesar-cipher/BaCon/caesar-cipher.bacon new file mode 100644 index 0000000000..10b0e4e8dd --- /dev/null +++ b/Task/Caesar-cipher/BaCon/caesar-cipher.bacon @@ -0,0 +1,21 @@ +CONST lc$ = "abcdefghijklmnopqrstuvwxyz" +CONST uc$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + +CONST txt$ = "The quick brown fox jumps over the lazy dog." + +FUNCTION Ceasar$(t$, k) + + lk$ = MID$(lc$ & lc$, k+1, 26) + uk$ = MID$(uc$ & uc$, k+1, 26) + + RETURN REPLACE$(t$, lc$ & uc$, lk$ & uk$, 2) + +END FUNCTION + +tokey = RANDOM(25)+1 +PRINT "Encrypting text with key: ", tokey + +en$ = Ceasar$(txt$, tokey) + +PRINT "Encrypted: ", en$ +PRINT "Decrypted: ", Ceasar$(en$, 26-tokey) diff --git a/Task/Caesar-cipher/C++/caesar-cipher.cpp b/Task/Caesar-cipher/C++/caesar-cipher-1.cpp similarity index 100% rename from Task/Caesar-cipher/C++/caesar-cipher.cpp rename to Task/Caesar-cipher/C++/caesar-cipher-1.cpp diff --git a/Task/Caesar-cipher/C++/caesar-cipher-2.cpp b/Task/Caesar-cipher/C++/caesar-cipher-2.cpp new file mode 100644 index 0000000000..78252737ec --- /dev/null +++ b/Task/Caesar-cipher/C++/caesar-cipher-2.cpp @@ -0,0 +1,54 @@ +/* caesar cipher */ + +#include +#include +#include + +int main( ) { + + using namespace std; + + string input ; + int key = 0; + + // lambda functions + + auto encrypt = [&](char c, int key ) { + char A = ( islower(c) )? 'a': 'A'; + c = (isalpha(c))? (c - A + key) % 26 + A : c; + return (char) c; + }; + + auto decrypt = [&](char c, int key ) { + char A = ( islower(c) )? 'a': 'A'; + c = (isalpha(c))? (c - A + (26 - key) ) % 26 + A : c; + return (char) c; + }; + + + cout << "Enter a line of text.\n"; + getline( cin , input ); + + cout << "Enter an integer to shift text.\n"; + cin >> key; + + while ( (key < 1) || (key > 25) ) + { + cout << "must be an integer between 1 and 25 -->" << endl; + cin >> key; + } + + cout << "Plain: \t" << input << endl ; + + for ( auto & cp : input) // use & for mutability + cp = encrypt(cp, key); + + cout << "Encrypted:\t" << input << endl; + + for ( auto & cp : input) + cp = decrypt(cp, key); + + cout << "Decrypted:\t" << input << endl; + + return 0 ; +} diff --git a/Task/Caesar-cipher/Elena/caesar-cipher.elena b/Task/Caesar-cipher/Elena/caesar-cipher.elena index cc3b8381b7..f9fed07b5a 100644 --- a/Task/Caesar-cipher/Elena/caesar-cipher.elena +++ b/Task/Caesar-cipher/Elena/caesar-cipher.elena @@ -1,71 +1,70 @@ -#define system. -#define system'routines. -#define system'math. -#define extensions. +import system'routines. +import system'math. +import extensions. -#symbol Letters = "abcdefghijklmnopqrstuvwxyz". -#symbol BigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ". -#symbol TestText = "Pack my box with five dozen liquor jugs.". -#symbol Key = 12. +const Letters = "abcdefghijklmnopqrstuvwxyz". +const BigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ". +const TestText = "Pack my box with five dozen liquor jugs.". +const Key = 12. -#class Encrypting :: Enumerator +class Encrypting :: Enumerator { - #field theKey. - #field theEnumerator. + object theKey. + object theEnumerator. - #constructor new &key:aKey &text:aText + constructor new key:aKey text:aText [ theKey := aKey. theEnumerator := aText enumerator. ] - #method next => theEnumerator. + next => theEnumerator. - #method reset => theEnumerator. + reset => theEnumerator. - #method get + get [ - #var aChar := theEnumerator get. + var aChar := theEnumerator get. - #var anIndex := Letters indexOf:0:aChar. + var anIndex := Letters indexOf:aChar at:0. - (-1 < anIndex) - ? [ - ^ Letters @ ((theKey+anIndex) mod:26). - ] - ! [ - anIndex := BigLetters indexOf:0:aChar. - (-1 < anIndex) - ? [ - ^ BigLetters @ ((theKey+anIndex) mod:26). - ] - ! [ - ^ aChar. + if (-1 < anIndex) + [ + ^ Letters[(theKey+anIndex) mod:26] + ]; + [ + anIndex := BigLetters indexOf:aChar at:0. + if (-1 < anIndex) + [ + ^ BigLetters[(theKey+anIndex) mod:26] + ]; + [ + ^ aChar ]. ]. ] } -#class(extension)encryptOp +extension encryptOp { - #method encrypt : aKey - = Encrypting new &key:aKey &text:self summarize:(String new). + encrypt : aKey + = Encrypting new key:aKey text:self; summarize(String new). - #method decrypt :aKey - = Encrypting new &key:(26 - aKey) &text:self summarize:(String new). + decrypt :aKey + = Encrypting new key(26 - aKey) text:self; summarize(String new). } -#symbol program = +program = [ - console writeLine:"Original text :" :TestText. + console printLine("Original text :",TestText). - #var anEncryptedText := TestText encrypt:Key. + var anEncryptedText := TestText encrypt:Key. - console writeLine:"Encrypted text:" :anEncryptedText. + console printLine("Encrypted text:",anEncryptedText). - #var aDecryptedText := anEncryptedText decrypt:Key. + var aDecryptedText := anEncryptedText decrypt:Key. - console writeLine:"Decrypted text:" :aDecryptedText. + console printLine("Decrypted text:",aDecryptedText). console readChar. ]. diff --git a/Task/Caesar-cipher/Gambas/caesar-cipher.gambas b/Task/Caesar-cipher/Gambas/caesar-cipher.gambas new file mode 100644 index 0000000000..65f9c66848 --- /dev/null +++ b/Task/Caesar-cipher/Gambas/caesar-cipher.gambas @@ -0,0 +1,20 @@ +Public Sub Main() +Dim byKey As Byte = 3 'The key (Enter 26 to get the same output as input) +Dim byCount As Byte 'Counter +Dim sCeasar As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" 'Used to calculate the cipher +Dim sString As String = "The five boxing wizards jump quickly" 'Phrase to encrypt +Dim sCoded, sTemp As String 'Various strings + +For byCount = 1 To Len(sString) 'Count through each letter in the phrase + If Mid(sString, byCount, 1) = " " Then 'If it's a space.. + sCoded &= " " 'Keep it a space + Continue 'Jump to the next iteration of the loop + Endif + sTemp = Mid(sCeasar, InStr(sCeasar, Mid(UCase(sString), byCount, 1)) + byKey, 1) 'Get the new 'coded' letter + If Asc(Mid(sString, byCount, 1)) > 96 Then sTemp = Chr(Asc(sTemp) + 32) 'If the original was lower case then make the new 'coded' letter lower case + sCoded &= sTemp 'Add the result to the code string +Next + +Print sString & gb.NewLine & sCoded 'Print the result + +End diff --git a/Task/Caesar-cipher/Haskell/caesar-cipher-2.hs b/Task/Caesar-cipher/Haskell/caesar-cipher-2.hs index ea8e8e210f..d73ef8c74c 100644 --- a/Task/Caesar-cipher/Haskell/caesar-cipher-2.hs +++ b/Task/Caesar-cipher/Haskell/caesar-cipher-2.hs @@ -1,32 +1,23 @@ -{-# LANGUAGE LambdaCase #-} -module Main where +import Data.Char (ord, chr, isUpper, isAlpha) -import Control.Error (tryRead, tryAt) -import Control.Monad.Trans (liftIO) -import Control.Monad.Trans.Except (ExceptT, runExceptT) +caesar, uncaesar :: Int -> String -> String +caesar = (<$>) . tr -import Data.Char -import System.Exit (die) -import System.Environment (getArgs) +uncaesar = caesar . negate + +tr :: Int -> Char -> Char +tr offset c + | isAlpha c = chr $ intAlpha + mod ((ord c - intAlpha) + offset) 26 + | otherwise = c + where + intAlpha = + ord + (if isUpper c + then 'A' + else 'a') main :: IO () -main = runExceptT parseKey >>= \case - Left err -> die err - Right k -> interact $ caesar k - -parseKey :: (Read a, Integral a) => ExceptT String IO a -parseKey = liftIO getArgs >>= - flip (tryAt "Not enough arguments") 0 >>= - tryRead "Key is not a valid integer" - -caesar :: (Integral a) => a -> String -> String -caesar k = map f - where f c = case generalCategory c of - LowercaseLetter -> addChar 'a' k c - UppercaseLetter -> addChar 'A' k c - _ -> c - -addChar :: (Integral a) => Char -> a -> Char -> Char -addChar b o c = chr $ fromIntegral (b' + (c' - b' + o) `mod` 26) - where b' = fromIntegral $ ord b - c' = fromIntegral $ ord c +main = mapM_ print [encoded, decoded] + where + encoded = caesar (-114) "Curio, Cesare venne, e vide e vinse ? " + decoded = uncaesar (-114) encoded diff --git a/Task/Caesar-cipher/Haskell/caesar-cipher-3.hs b/Task/Caesar-cipher/Haskell/caesar-cipher-3.hs new file mode 100644 index 0000000000..ea8e8e210f --- /dev/null +++ b/Task/Caesar-cipher/Haskell/caesar-cipher-3.hs @@ -0,0 +1,32 @@ +{-# LANGUAGE LambdaCase #-} +module Main where + +import Control.Error (tryRead, tryAt) +import Control.Monad.Trans (liftIO) +import Control.Monad.Trans.Except (ExceptT, runExceptT) + +import Data.Char +import System.Exit (die) +import System.Environment (getArgs) + +main :: IO () +main = runExceptT parseKey >>= \case + Left err -> die err + Right k -> interact $ caesar k + +parseKey :: (Read a, Integral a) => ExceptT String IO a +parseKey = liftIO getArgs >>= + flip (tryAt "Not enough arguments") 0 >>= + tryRead "Key is not a valid integer" + +caesar :: (Integral a) => a -> String -> String +caesar k = map f + where f c = case generalCategory c of + LowercaseLetter -> addChar 'a' k c + UppercaseLetter -> addChar 'A' k c + _ -> c + +addChar :: (Integral a) => Char -> a -> Char -> Char +addChar b o c = chr $ fromIntegral (b' + (c' - b' + o) `mod` 26) + where b' = fromIntegral $ ord b + c' = fromIntegral $ ord c diff --git a/Task/Caesar-cipher/Kotlin/caesar-cipher.kotlin b/Task/Caesar-cipher/Kotlin/caesar-cipher.kotlin new file mode 100644 index 0000000000..dd6d981fa4 --- /dev/null +++ b/Task/Caesar-cipher/Kotlin/caesar-cipher.kotlin @@ -0,0 +1,35 @@ +// version 1.0.5-2 + +object Caesar { + fun encrypt(s: String, key: Int): String { + val offset = key % 26 + if (offset == 0) return s + var d: Char + val chars = CharArray(s.length) + for ((index, c) in s.withIndex()) { + if (c in 'A'..'Z') { + d = c + offset + if (d > 'Z') d -= 26 + } + else if (c in 'a'..'z') { + d = c + offset + if (d > 'z') d -= 26 + } + else + d = c + chars[index] = d + } + return chars.joinToString("") + } + + fun decrypt(s: String, key: Int): String { + return encrypt(s, 26 - key) + } +} + +fun main(args: Array) { + val encoded = Caesar.encrypt("Bright vixens jump; dozy fowl quack.", 8) + println(encoded) + val decoded = Caesar.decrypt(encoded, 8) + println(decoded) +} diff --git a/Task/Caesar-cipher/Racket/caesar-cipher-1.rkt b/Task/Caesar-cipher/Racket/caesar-cipher-1.rkt deleted file mode 100644 index a51e5c7c08..0000000000 --- a/Task/Caesar-cipher/Racket/caesar-cipher-1.rkt +++ /dev/null @@ -1,19 +0,0 @@ -#lang racket - -(define A (char->integer #\A)) -(define Z (char->integer #\Z)) -(define a (char->integer #\a)) -(define z (char->integer #\z)) - -(define (rotate c n) - (define cnum (char->integer c)) - (define (shift base) (integer->char (+ base (modulo (+ n (- cnum base)) 26)))) - (cond [(<= A cnum Z) (shift A)] - [(<= a cnum z) (shift a)] - [else c])) - -(define (caesar s n) - (list->string (for/list ([c (in-string s)]) (rotate c n)))) - -(define (encrypt s) (caesar s 1)) -(define (decrypt s) (caesar s -1)) diff --git a/Task/Caesar-cipher/Racket/caesar-cipher-2.rkt b/Task/Caesar-cipher/Racket/caesar-cipher-2.rkt deleted file mode 100644 index 3812b82940..0000000000 --- a/Task/Caesar-cipher/Racket/caesar-cipher-2.rkt +++ /dev/null @@ -1,5 +0,0 @@ -> (define s (encrypt "The five boxing wizards jump quickly.")) -> s -"Uif gjwf cpyjoh xjabset kvnq rvjdlmz." -> (decrypt s) -"The five boxing wizards jump quickly." diff --git a/Task/Caesar-cipher/Ruby/caesar-cipher.rb b/Task/Caesar-cipher/Ruby/caesar-cipher.rb index 3aa7441b61..6acff1cbdf 100644 --- a/Task/Caesar-cipher/Ruby/caesar-cipher.rb +++ b/Task/Caesar-cipher/Ruby/caesar-cipher.rb @@ -1,27 +1,12 @@ -module CaesarCipher - AtoZ = (0..25).each_with_object({}) do |key,h| - str = [*"A".."Z"].rotate(key).join - h[key] = str + str.downcase +class String + ALFABET = ("A".."Z").to_a + + def caesar_cipher(num) + self.tr(ALFABET.join, ALFABET.rotate(num).join) end - def encrypt(key, plaintext) - (1..25) === key or raise ArgumentError, "key not in 1..25" - plaintext.tr(AtoZ[0], AtoZ[key]) - end - - def decrypt(key, ciphertext) - (1..25) === key or raise ArgumentError, "key not in 1..25" - ciphertext.tr(AtoZ[key], AtoZ[0]) - end end -include CaesarCipher - -original = "THEYBROKEOURCIPHEREVERYONECANREADTHIS" -en = encrypt(3, original) -de = decrypt(3, en) - -[original, en, de].each {|e| puts e} - -puts 'OK' if - (1..25).all? {|k| original == decrypt(k, encrypt(k, original))} +#demo: +encypted = "THEYBROKEOURCIPHEREVERYONECANREADTHIS".caesar_cipher(3) +decrypted = encypted.caesar_cipher(-3) diff --git a/Task/Caesar-cipher/Sed/caesar-cipher.sed b/Task/Caesar-cipher/Sed/caesar-cipher.sed new file mode 100644 index 0000000000..a599313519 --- /dev/null +++ b/Task/Caesar-cipher/Sed/caesar-cipher.sed @@ -0,0 +1,37 @@ +#!/bin/sed -rf +# Input: \ntext to encode + +/^[0-9]+$/ { + # validate a number and translate it to analog form + s/$/;9876543210dddddddddd/ + s/([0-9]);.*\1.{10}(.?)/\2/ + s/2/11/ + s/1/dddddddddd/g + /[3-9]|d{25}d+/ { + s/.*/Error: Key must be <= 25/ + q + } + # append from-table + s/$/\nabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/ + # .. and to-table + s/$/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/ + # rotate to-table, lower and uppercase independently, removing one `d' at a time + : rotate + s/^d(.*\n[^Z]+Z)(.)(.{25})(.)(.{25})/\1\3\2\5\4/ + t rotate + s/\n// + h + d +} + +# use \n to mark character to convert +s/^/\n/ +# append conversion table to pattern space +G +: loop + # look up converted character and place it instead of old one + s/\n(.)(.*\n.*\1.{51}(.))/\n\3\2/ + # advance \n even if prev. command fails, thus skip non-alphabetical characters + /\n\n/! s/\n([^\n])/\1\n/ +t loop +s/\n\n.*// diff --git a/Task/Caesar-cipher/Sinclair-ZX81-BASIC/caesar-cipher.sinclair b/Task/Caesar-cipher/Sinclair-ZX81-BASIC/caesar-cipher.sinclair new file mode 100644 index 0000000000..5a7d8ee25f --- /dev/null +++ b/Task/Caesar-cipher/Sinclair-ZX81-BASIC/caesar-cipher.sinclair @@ -0,0 +1,12 @@ + 10 INPUT KEY + 20 INPUT T$ + 30 LET C$="" + 40 FOR I=1 TO LEN T$ + 50 LET L$=T$(I) + 60 IF L$<"A" OR L$>"Z" THEN GOTO 100 + 70 LET L$=CHR$ (CODE L$+KEY) + 80 IF L$>"Z" THEN LET L$=CHR$ (CODE L$-26) + 90 IF L$<"A" THEN LET L$=CHR$ (CODE L$+26) +100 LET C$=C$+L$ +110 NEXT I +120 PRINT C$ diff --git a/Task/Caesar-cipher/Swift/caesar-cipher.swift b/Task/Caesar-cipher/Swift/caesar-cipher.swift new file mode 100644 index 0000000000..e8502ca414 --- /dev/null +++ b/Task/Caesar-cipher/Swift/caesar-cipher.swift @@ -0,0 +1,65 @@ +var arr:[Character]=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] + +func res(st:String,ar:[Character],x:Int,ro:String)->String{ + + var str2:[Character]=[] + + for i in st.characters + { + + for j in 0...25 + { + + + if i==ar[j] + { + + switch ro + { + case "right": + + if(j+x<=25) + { + + str2.append(ar[j+x]) + break + + } + else + { + + str2.append(ar[j+x-26]) + break + } + + case "left": + + if(j-x>=0) + { + + str2.append(ar[j-x]) + break + } + else + { + + str2.append(ar[j-x+26]) + break + } + default: + print("incorrect input for rotation direction") + } + + + } + } + } + + return String(str2) +} + +var mssg:String="hi" +var x1:Int=5 +var rot:String="right" +var rotstr:String=res(st:mssg,ar:arr,x:x1,ro:rot) +print(rotstr) diff --git a/Task/Caesar-cipher/VBScript/caesar-cipher.vb b/Task/Caesar-cipher/VBScript/caesar-cipher.vb new file mode 100644 index 0000000000..80a55326d5 --- /dev/null +++ b/Task/Caesar-cipher/VBScript/caesar-cipher.vb @@ -0,0 +1,35 @@ + str = "IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES." + + Wscript.Echo str + Wscript.Echo Rotate(str,5) + Wscript.Echo Rotate(Rotate(str,5),-5) + + 'Rotate (Caesar encrypt/decrypt) test positions. + ' numpos < 0 - rotate left + ' numpos > 0 - rotate right + 'Left rotation is converted to equivalent right rotation + + Function Rotate (text, numpos) + + dim dic: set dic = CreateObject("Scripting.Dictionary") + dim ltr: ltr = Split("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z") + dim rot: rot = (26 + numpos Mod 26) Mod 26 'convert all to right rotation + dim ch + dim i + + for i = 0 to ubound(ltr) + dic(ltr(i)) = ltr((rot+i) Mod 26) + next + + Rotate = "" + + for i = 1 to Len(text) + ch = Mid(text,i,1) + if dic.Exists(ch) Then + Rotate = Rotate & dic(ch) + else + Rotate = Rotate & ch + end if + next + + End Function diff --git a/Task/Caesar-cipher/Vala/caesar-cipher.vala b/Task/Caesar-cipher/Vala/caesar-cipher.vala new file mode 100644 index 0000000000..09b27f1397 --- /dev/null +++ b/Task/Caesar-cipher/Vala/caesar-cipher.vala @@ -0,0 +1,33 @@ +static void println(string str) { + stdout.printf("%s\r\n", str); +} + +static unichar encrypt_char(unichar ch, int code) { + if (!ch.isalpha()) return ch; + + unichar offset = ch.isupper() ? 'A' : 'a'; + return (unichar)((ch + code - offset) % 26 + offset); +} + +static string encrypt(string input, int code) { + var builder = new StringBuilder(); + + unichar c; + for (int i = 0; input.get_next_char(ref i, out c);) { + builder.append_unichar(encrypt_char(c, code)); + } + + return builder.str; +} + +static string decrypt(string input, int code) { + return encrypt(input, 26 - code); +} + +const string test_case = "The quick brown fox jumped over the lazy dog"; + +void main() { + println(test_case); + println(encrypt(test_case, -1)); + println(decrypt(encrypt(test_case, -1), -1)); +} diff --git a/Task/Caesar-cipher/Zkl/caesar-cipher-1.zkl b/Task/Caesar-cipher/Zkl/caesar-cipher-1.zkl new file mode 100644 index 0000000000..653d5ea3e6 --- /dev/null +++ b/Task/Caesar-cipher/Zkl/caesar-cipher-1.zkl @@ -0,0 +1,7 @@ +fcn caesarCodec(str,n,encode=True){ + var [const] letters=["a".."z"].chain(["A".."Z"]).pump(String); // static + if(not encode) n=26 - n; + m,sz := n + 26, 26 - n; + ltrs:=String(letters[n,sz],letters[0,n],letters[m,sz],letters[26,n]); + str.translate(letters,ltrs) +} diff --git a/Task/Caesar-cipher/Zkl/caesar-cipher-2.zkl b/Task/Caesar-cipher/Zkl/caesar-cipher-2.zkl new file mode 100644 index 0000000000..095a5151da --- /dev/null +++ b/Task/Caesar-cipher/Zkl/caesar-cipher-2.zkl @@ -0,0 +1,6 @@ +text:="The five boxing wizards jump quickly"; +N:=3; +code:=caesarCodec(text,N); +println("text = ",text); +println("encoded(%d) = %s".fmt(N,code)); +println("decoded = ",caesarCodec(code,N,False)); diff --git a/Task/Calendar---for-REAL-programmers/360-Assembly/calendar---for-real-programmers.360 b/Task/Calendar---for-REAL-programmers/360-Assembly/calendar---for-real-programmers.360 new file mode 100644 index 0000000000..9ccd2dcd77 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/360-Assembly/calendar---for-real-programmers.360 @@ -0,0 +1,181 @@ +* CALENDAR FOR REAL PROGRAMMERS 05/03/2017 +CALENDAR CSECT + USING CALENDAR,R13 BASE REGISTER + B 72(R15) SKIP MY SAVEAREA + DC 17F'0' MY SAVEAREA + STM R14,R12,12(R13) SAVE CALLER'S REGISTERS + ST R13,4(R15) LINK BACKWARD + ST R15,8(R13) LINK FORWARD + LR R13,R15 SET ADDRESSABILITY + L R4,YEAR YEAR + SRDA R4,32 . + D R4,=F'4' YEAR//4 + LTR R4,R4 IF YEAR//4=0 + BNZ LYNOT + L R4,YEAR YEAR + SRDA R4,32 . + D R4,=F'100' YEAR//100 + LTR R4,R4 IF YEAR//100=0 + BNZ LY + L R4,YEAR YEAR + SRDA R4,32 . + D R4,=F'400' IF YEAR//400 + LTR R4,R4 IF YEAR//400=0 + BNZ LYNOT +LY MVC ML+2,=H'29' ML(2)=29 LEAPYEAR +LYNOT SR R10,R10 LTD1=0 + LA R6,1 I=1 +LOOPI1 C R6,=F'31' DO I=1 TO 31 + BH ELOOPI1 + XDECO R6,XDEC EDIT I + LA R14,TD1 TD1 + AR R14,R10 TD1+LTD1 + MVC 0(3,R14),XDEC+9 SUB(TD1,LTD1+1,3)=PIC(I,3) + LA R10,3(R10) LTD1+3 + LA R6,1(R6) I=I+1 + B LOOPI1 +ELOOPI1 LA R6,1 I=1 +LOOPI2 C R6,=F'12' DO I=1 TO 12 + BH ELOOPI2 + ST R6,M M=I + MVC D,=F'1' D=1 + MVC YY,YEAR YY=YEAR + L R4,M M + C R4,=F'3' IF M<3 + BNL GE3 + L R2,M M + LA R2,12(R2) M+12 + ST R2,M M=M+12 + L R2,YY YY + BCTR R2,0 YY-1 + ST R2,YY YY=YY-1 +GE3 L R2,YY YY + LR R1,R2 YY + SRA R1,2 YY/4 + AR R2,R1 YY+(YY/4) + L R4,YY YY + SRDA R4,32 . + D R4,=F'100' YY/100 + SR R2,R5 YY+(YY/4)-(YY/100) + L R4,YY YY + SRDA R4,32 . + D R4,=F'400' YY/400 + AR R2,R5 YY+(YY/4)-(YY/100)+(YY/400) + A R2,D R2=YY+(YY/4)-(YY/100)+(YY/400)+D + LA R5,153 153 + M R4,M 153*M + LA R5,8(R5) 153*M+8 + D R4,=F'5' (153*M+8)/5 + AR R5,R2 ((153*M+8)/5+R2 + LA R4,0 . + D R4,=F'7' R4=MOD(R5,7) 0=SUN 1=MON ... 6=SAT + LTR R4,R4 IF J=0 + BNZ JNE0 + LA R4,7 J=7 +JNE0 BCTR R4,0 J-1 + MH R4,=H'3' J*3 + LR R10,R4 J1=J*3 + LR R1,R6 I + SLA R1,1 *2 + LH R11,ML-2(R1) ML(I) + MH R11,=H'3' J2=ML(I)*3 + MVC TD2,BLANK TD2=' ' + LA R4,TD1 @TD1 + LR R5,R11 J2 + LA R2,TD2 @TD2 + AR R2,R10 @TD2+J1 + LR R3,R5 J2 + MVCL R2,R4 SUB(TD2,J1+1,J2)=SUB(TD1,1,J2) + LR R1,R6 I + MH R1,=H'144' *144 + LA R14,DA-144(R1) @DA(I) + MVC 0(144,R14),TD2 DA(I)=TD2 + LA R6,1(R6) I=I+1 + B LOOPI2 +ELOOPI2 XPRNT SNOOPY,132 PRINT SNOOPY + L R1,YEAR YEAR + XDECO R1,PG+56 EDIT YEAR + XPRNT PG,L'PG PRINT YEAR + MVC WDLINE,BLANK WDLINE=' ' + LA R10,1 LWDLINE=1 + LA R8,1 K=1 +LOOPK3 C R8,=F'6' DO K=1 TO 6 + BH ELOOPK3 + LA R4,WDLINE @WDLINE + AR R4,R10 +LWDLINE + MVC 0(20,R4),WDNA SUB(WDLINE,LWDLINE+1,20)=WDNA + LA R10,20(R10) LWDLINE=LWDLINE+20 + C R8,=F'6' IF K<6 + BNL ITERK3 + LA R10,2(R10) LWDLINE=LWDLINE+2 +ITERK3 LA R8,1(R8) K=K+1 + B LOOPK3 +ELOOPK3 LA R6,1 I=1 +LOOPI4 C R6,=F'12' DO I=1 TO 12 BY 6 + BH ELOOPI4 + MVC MOLINE,BLANK MOLINE=' ' + LA R10,6 LMOLINE=6 + LR R8,R6 K=I +LOOPK4 LA R2,5(R6) I+5 + CR R8,R2 DO K=I TO I+5 + BH ELOOPK4 + LR R1,R8 K + MH R1,=H'10' *10 + LA R3,MO-10(R1) MO(K) + LA R4,MOLINE @MOLINE + AR R4,R10 +LMOLINE + MVC 0(10,R4),0(R3) SUB(MOLINE,LMOLINE+1,10)=MO(K) + LA R10,22(R10) LMOLINE=LMOLINE+22 + LA R8,1(R8) K=K+1 + B LOOPK4 +ELOOPK4 XPRNT MOLINE,L'MOLINE PRINT MONTHS + XPRNT WDLINE,L'WDLINE PRINT DAYS OF WEEK + LA R7,1 J=1 +LOOPJ4 C R7,=F'106' DO J=1 TO 106 BY 21 + BH ELOOPJ4 + MVC PG,BLANK CLEAR BUFFER + LA R9,PG PGI=0 + LR R8,R6 K=I +LOOPK5 LA R2,5(R6) I+5 + CR R8,R2 DO K=I TO I+5 + BH ELOOPK5 + LR R1,R8 K + MH R1,=H'144' *144 + LA R4,DA-144(R1) DA(K) + BCTR R4,0 -1 + AR R4,R7 +J + MVC 0(21,R9),0(R4) SUBSTR(DA(K),J,21) + LA R9,22(R9) PGI=PGI+22 + LA R8,1(R8) K=K+1 + B LOOPK5 +ELOOPK5 XPRNT PG,L'PG PRINT BUFFER + LA R7,21(R7) J=J+21 + B LOOPJ4 +ELOOPJ4 LA R6,6(R6) I=I+6 + B LOOPI4 +ELOOPI4 L R13,4(0,R13) RESTORE PREVIOUS SAVEAREA POINTER + LM R14,R12,12(R13) RESTORE CALLER'S REGISTERS + XR R15,R15 SET RETURN CODE TO 0 + BR R14 RETURN TO CALLER +SNOOPY DC CL57' ',CL18'INSERT SNOOPY HERE',CL57' ' +YEAR DC F'1969' <== 1969 +MO DC CL10' JANUARY ',CL10' FEBRUARY ',CL10' MARCH ' + DC CL10' APRIL ',CL10' MAY ',CL10' JUNE ' + DC CL10' JULY ',CL10' AUGUST ',CL10'SEPTEMBER ' + DC CL10' OCTOBER ',CL10' NOVEMBER ',CL10' DECEMBER ' +ML DC H'31',H'28',H'31',H'30',H'31',H'30' + DC H'31',H'31',H'30',H'31',H'30',H'31' +WDNA DC CL20'MO TU WE TH FR SA SU' +M DS F +D DS F +YY DS F +TD1 DS CL93 +TD2 DS CL144 +MOLINE DS CL132 +WDLINE DS CL132 +PG DC CL132' ' BUFFER FOR THE LINE PRINTER +XDEC DS CL12 +BLANK DC CL144' ' +DA DS 12CL144 + YREGS + END CALENDAR diff --git a/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena b/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena index 1a8cf2cbd2..52f44c9773 100644 --- a/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena +++ b/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena @@ -1,138 +1,142 @@ -#import system. -#import system'text. -#import system'routines. -#import system'calendar. -#import extensions. -#import extensions'math. -#import extensions'routines. +import system'text. +import system'routines. +import system'calendar. +import extensions. +import extensions'routines. -#symbol MonthNames = ("JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"). -#symbol DayNames = ("MO", "TU", "WE", "TH", "FR", "SA", "SU"). +const MonthNames = ("JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"). +const DayNames = ("MO", "TU", "WE", "TH", "FR", "SA", "SU"). -#class CalendarMonthPrinter +class CalendarMonthPrinter { - #field theDate. - #field theLine. - #field theMonth. - #field theYear. - #field theRow. + object theDate. + object theLine. + object theMonth. + object theYear. + object theRow. - #constructor new &year:aYear &month:aMonth + constructor new year:aYear month:aMonth [ theMonth := aMonth. theYear := aYear. theLine := TextBuffer new. - theRow := Integer new &int:0. + theRow := Integer new int:0. ] - #method writeTitle + writeTitle [ - theRow << 0. - theDate := Date new &year:(theYear int) &month:(theMonth int) &day:1. - DayNames run &each: aName - [ theLine writeLiteral:" ":aName ]. + theRow set:0. + theDate := Date new year(theYear int) month(theMonth int) day:1. + DayNames forEach(:aName) + [ theLine print(" ",aName) ] ] - #method writeLine + writeLine [ theLine clear. - (theDate month == theMonth) - ? [ - theLine write:" " &length:(((theDate dayOfWeek) => 0 ? [ 7 ] ! [ theDate dayOfWeek ]) - 1). + if (theDate month == theMonth) + [ + theLine write:" " length((theDate dayOfWeek == 0)iif(7,theDate dayOfWeek) - 1). control do: [ - theLine write:(theDate day literal) &paddingLeft:3 &with:#32. - theDate := theDate add &days:1. + theLine write:(theDate day; literal) paddingLeft:3 with:$32. + + theDate := theDate add days:1. ] - &until:[(theDate month != theMonth)or:[theDate dayOfWeek == 1]]. + until:$((theDate month != theMonth)or:$(theDate dayOfWeek == 1)). ]. - #var(type:int) aLength := theLine length. - (aLength < 21) - ? [ theLine write:" " &length:(21 - aLength). ]. + int aLength := theLine length. + if (aLength < 21) + [ theLine write:" " length(21 - aLength). ]. - theRow += 1. + theRow append int:1. ] - #method iterator = Iterator + indexer = Indexer:: { available = theRow < 7. - readIndex &vint:anIndex [ anIndex << theRow int. ] + readIndexTo vint:anIndex [ anIndex int := theRow ] - write &index:anIndex + writeIndex int:anIndex [ - (anIndex <= theRow) - ? [ self writeTitle. ]. + if (anIndex <= theRow) + [ $owner writeTitle ]. - #loop (anIndex > theRow) ? - [ self writeLine. ]. + while (anIndex > theRow) + [ $owner writeLine ] ] - get = self. + + get = $owner. }. - #method printTitleTo : anOutput + printTitleTo : anOutput [ - anOutput write:(MonthNames @(theMonth - 1)) &padding:21 &with:#32. + anOutput write(MonthNames[theMonth - 1]) padding:21 with:$32. ] - #method printTo : anOutput + printTo : anOutput [ - anOutput write:(theLine literal). + anOutput write(theLine literal). ] } -#class Calendar +class Calendar { - #field(type:int) theYear. - #field(type:int) theRowLength. + int theYear. + int theRowLength. - #constructor new : aYear + constructor new : aYear [ theYear := aYear int. theRowLength := 3. ] - #method printTo:anOutput + printTo:anOutput [ - anOutput write:"[SNOOPY]" &padding:(theRowLength * 25) &with:#32. + anOutput write:"[SNOOPY]" padding:(theRowLength * 25) with:$32. anOutput writeLine. - anOutput write:(theYear literal) &padding:(theRowLength * 25) &with:#32. - anOutput writeLine writeLine. + anOutput write:(theYear literal) padding:(theRowLength * 25) with:$32. + anOutput writeLine; writeLine. - #var aRowCount := 12 / theRowLength. - #var Months := Array new &length:aRowCount set &every:(&index:i) - [ Array new &length:theRowLength set &every:(&index:j) - [ CalendarMonthPrinter new &year:(theYear int) &month:((i * theRowLength + j + 1) int) ]]. + var aRowCount := 12 / theRowLength. + var Months := Array new length:aRowCount; populate(:i) + (Array new length:theRowLength; + populate(:j) + ( CalendarMonthPrinter new year(theYear int) month(i * theRowLength + j + 1))). - Months run &each: aRow + Months forEach(:aRow) [ - aRow run &each: aMonth + aRow forEach(:aMonth) [ aMonth printTitleTo:anOutput. + anOutput write:" ". ]. anOutput writeLine. - ParallelEnumerator new:aRow run &each: aLine + ParallelEnumerator new:aRow; forEach(:aLine) [ - aLine run &each: aPrinter + aLine forEach(:aPrinter) [ aPrinter printTo:anOutput. - anOutput write:" ". + + anOutput write:" " ]. - anOutput writeLine. + + anOutput writeLine ]. ]. ] } -#symbol program = +program = [ - #var aCalender := Calendar new:(console write:"ENTER THE YEAR:" readLine:(Integer new)). + var aCalender := Calendar new(console write:"ENTER THE YEAR:"; readLineTo(Integer new)). aCalender printTo:console. diff --git a/Task/Calendar---for-REAL-programmers/Kotlin/calendar---for-real-programmers-1.kotlin b/Task/Calendar---for-REAL-programmers/Kotlin/calendar---for-real-programmers-1.kotlin new file mode 100644 index 0000000000..fbc59b3f4d --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Kotlin/calendar---for-real-programmers-1.kotlin @@ -0,0 +1,52 @@ +IMPORT JAVA.TEXT.* +IMPORT JAVA.UTIL.* +IMPORT JAVA.IO.PRINTSTREAM + +INTERNAL FUN PRINTSTREAM.PRINTCALENDAR(YEAR: INT, NCOLS: BYTE, LOCALE: LOCALE?) { + IF (NCOLS < 1 || NCOLS > 12) + THROW ILLEGALARGUMENTEXCEPTION("ILLEGAL COLUMN WIDTH.") + VAL W = NCOLS * 24 + VAL NROWS = MATH.CEIL(12.0 / NCOLS).TOINT() + + VAL DATE = GREGORIANCALENDAR(YEAR, 0, 1) + VAR OFFS = DATE.GET(CALENDAR.DAY_OF_WEEK) - 1 + + VAL DAYS = DATEFORMATSYMBOLS(LOCALE).SHORTWEEKDAYS.SLICE(1..7).MAP { IT.SLICE(0..1) }.JOINTOSTRING(" ", " ") + VAL MONS = ARRAY(12) { ARRAY(8) { "" } } + DATEFORMATSYMBOLS(LOCALE).MONTHS.SLICE(0..11).FOREACHINDEXED { M, NAME -> + VAL LEN = 11 + NAME.LENGTH / 2 + VAL FORMAT = MESSAGEFORMAT.FORMAT("%{0}S%{1}S", LEN, 21 - LEN) + MONS[M][0] = STRING.FORMAT(FORMAT, NAME, "") + MONS[M][1] = DAYS + VAL DIM = DATE.GETACTUALMAXIMUM(CALENDAR.DAY_OF_MONTH) + FOR (D IN 1..42) { + VAL ISDAY = D > OFFS && D <= OFFS + DIM + VAL ENTRY = IF (ISDAY) STRING.FORMAT(" %2S", D - OFFS) ELSE " " + IF (D % 7 == 1) + MONS[M][2 + (D - 1) / 7] = ENTRY + ELSE + MONS[M][2 + (D - 1) / 7] += ENTRY + } + OFFS = (OFFS + DIM) % 7 + DATE.ADD(CALENDAR.MONTH, 1) + } + + PRINTF("%" + (W / 2 + 10) + "S%N", "[SNOOPY PICTURE]") + PRINTF("%" + (W / 2 + 4) + "S%N%N", YEAR) + + FOR (R IN 0..NROWS - 1) { + FOR (I IN 0..7) { + VAR C = R * NCOLS + WHILE (C < (R + 1) * NCOLS && C < 12) { + PRINTF(" %S", MONS[C][I].TOUPPERCASE()) // ORIGINAL CHANGED TO PRINT IN UPPER CASE + C++ + } + PRINTLN() + } + PRINTLN() + } +} + +FUN MAIN(ARGS: ARRAY) { + SYSTEM.OUT.PRINTCALENDAR(1969, 3, LOCALE.US) +} diff --git a/Task/Calendar---for-REAL-programmers/Kotlin/calendar---for-real-programmers-2.kotlin b/Task/Calendar---for-REAL-programmers/Kotlin/calendar---for-real-programmers-2.kotlin new file mode 100644 index 0000000000..334729105a --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Kotlin/calendar---for-real-programmers-2.kotlin @@ -0,0 +1,84 @@ +// version 1.1.3 + +import java.io.File +import java.io.BufferedReader +import java.io.InputStreamReader + +fun main(args: Array) { + val keywords = listOf( + "import", "internal", "fun", "if", "throw", "val", "var", "for", "in", "while" + ) + + val singleCase = listOf( + "java.text", + "java.util", + "java.io", + "else", // really a keyword but doesn't have a following space here + "ceil", + "it", // really a keyword but doesn't have a following space here + "get(", // also included in GETACTUALMAXIMUM + "slice", + "map", + "months", + "length", + ".format", // also variable called FORMAT + "add", + "printf", + "println", + "out", + "main", + "args", + "s%{1}s", + "%2s", + "s%n%n", + "s%n", + "%s" + ) + + val mixedCase = listOf( + "PRINTSTREAM" to "PrintStream", + "INT," to "Int,", // also included in PRINTCALENDAR + "BYTE" to "Byte", + "LOCALE?" to "Locale?", // also variable called LOCALE + "LOCALE." to "Locale.", + "ILLEGALARGUMENTEXCEPTION" to "IllegalArgumentException", + "MATH" to "Math", + "GREGORIANCALENDAR" to "GregorianCalendar", + "DATEFORMATSYMBOLS" to "DateFormatSymbols", + "ARRAY" to "Array", + "MESSAGEFORMAT" to "MessageFormat", + "JOINTOSTRING" to "joinToString", + "STRING" to "String", + "CALENDAR." to "Calendar.", // also included in PRINTCALENDAR + "SYSTEM" to "System", + "TOINT" to "toInt", + "SHORTWEEKDAYS" to "shortWeekdays", + "FOREACHINDEXED" to "forEachIndexed", + "GETACTUALMAXIMUM" to "getActualMaximum", + "TOUPPERCASE" to "toUpperCase" + ) + + var text = File("calendar_UC.txt").readText() + for (k in keywords) text = text.replace("${k.toUpperCase()} ", "$k ") // add a following space to be on safe side + for (s in singleCase) text = text.replace(s.toUpperCase(), s) + for (m in mixedCase) text = text.replace(m.first, m.second) + File("calendar_NC.kt").writeText(text) + val commands = listOf("kotlinc", "calendar_NC.kt", "-include-runtime", "-d", "calendar_X.jar") + val pb = ProcessBuilder(commands) + pb.redirectErrorStream(true) + val process = pb.start() + process.waitFor() + val commands2 = listOf("java", "-jar", "calendar_NC.jar") + val pb2 = ProcessBuilder(commands2) + pb2.redirectErrorStream(true) + val process2 = pb2.start() + val out = StringBuilder() + val br = BufferedReader(InputStreamReader(process2.inputStream)) + while (true) { + val line = br.readLine() + if (line == null) break + out.append(line).append('\n') + } + br.close() + println(out.toString()) +} diff --git a/Task/Calendar---for-REAL-programmers/Kotlin/calendar---for-real-programmers-3.kotlin b/Task/Calendar---for-REAL-programmers/Kotlin/calendar---for-real-programmers-3.kotlin new file mode 100644 index 0000000000..2a8af8ac7c --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Kotlin/calendar---for-real-programmers-3.kotlin @@ -0,0 +1,52 @@ +import java.text.* +import java.util.* +import java.io.PrintStream + +internal fun PrintStream.PRINTCALENDAR(YEAR: Int, NCOLS: Byte, LOCALE: Locale?) { + if (NCOLS < 1 || NCOLS > 12) + throw IllegalArgumentException("ILLEGAL COLUMN WIDTH.") + val W = NCOLS * 24 + val NROWS = Math.ceil(12.0 / NCOLS).toInt() + + val DATE = GregorianCalendar(YEAR, 0, 1) + var OFFS = DATE.get(Calendar.DAY_OF_WEEK) - 1 + + val DAYS = DateFormatSymbols(LOCALE).shortWeekdays.slice(1..7).map { it.slice(0..1) }.joinToString(" ", " ") + val MONS = Array(12) { Array(8) { "" } } + DateFormatSymbols(LOCALE).months.slice(0..11).forEachIndexed { M, NAME -> + val LEN = 11 + NAME.length / 2 + val FORMAT = MessageFormat.format("%{0}s%{1}s", LEN, 21 - LEN) + MONS[M][0] = String.format(FORMAT, NAME, "") + MONS[M][1] = DAYS + val DIM = DATE.getActualMaximum(Calendar.DAY_OF_MONTH) + for (D in 1..42) { + val ISDAY = D > OFFS && D <= OFFS + DIM + val ENTRY = if (ISDAY) String.format(" %2s", D - OFFS) else " " + if (D % 7 == 1) + MONS[M][2 + (D - 1) / 7] = ENTRY + else + MONS[M][2 + (D - 1) / 7] += ENTRY + } + OFFS = (OFFS + DIM) % 7 + DATE.add(Calendar.MONTH, 1) + } + + printf("%" + (W / 2 + 10) + "s%n", "[SNOOPY PICTURE]") + printf("%" + (W / 2 + 4) + "s%n%n", YEAR) + + for (R in 0..NROWS - 1) { + for (I in 0..7) { + var C = R * NCOLS + while (C < (R + 1) * NCOLS && C < 12) { + printf(" %s", MONS[C][I].toUpperCase()) // ORIGINAL CHANGED TO PRINT in UPPER CASE + C++ + } + println() + } + println() + } +} + +fun main(args: Array) { + System.out.PRINTCALENDAR(1969, 3, Locale.US) +} diff --git a/Task/Calendar---for-REAL-programmers/Sidef/calendar---for-real-programmers.sidef b/Task/Calendar---for-REAL-programmers/Sidef/calendar---for-real-programmers.sidef index b2dbb5ef12..94a8470582 100644 --- a/Task/Calendar---for-REAL-programmers/Sidef/calendar---for-real-programmers.sidef +++ b/Task/Calendar---for-REAL-programmers/Sidef/calendar---for-real-programmers.sidef @@ -35,14 +35,14 @@ } -> FMT_YEAR (YEAR, STR="", MONTH_STRS=[]) { - MONTH_STRS = 12.("\LOF")({|I| FMT_MONTH(YEAR, I).("\LLINES") }) + MONTH_STRS = 12.("\LOF")({|I| FMT_MONTH(YEAR, I+1).("\LLINES") }) STR += (' '*(MONTHS_PER_COL()*10 + 2) + YEAR + "\12") (0..11 -> ("\LBY")(MONTHS_PER_COL())).("\LEACH")({ |MONTH| MONTH_STRS[MONTH] && ->() { { |I| - MONTH_STRS[MONTH + I - 1] && ( - STR += MONTH_STRS[MONTH + I - 1].("\LSHIFT") + MONTH_STRS[MONTH + I] && ( + STR += MONTH_STRS[MONTH + I].("\LSHIFT") STR += ' '*2 ) } * MONTHS_PER_COL() diff --git a/Task/Calendar---for-REAL-programmers/Zkl/calendar---for-real-programmers-1.zkl b/Task/Calendar---for-REAL-programmers/Zkl/calendar---for-real-programmers-1.zkl new file mode 100644 index 0000000000..b641ace09e --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Zkl/calendar---for-real-programmers-1.zkl @@ -0,0 +1,12 @@ +VAR [CONST] D=TIME.DATE, DAYS="SU MO TU WE TH FR SA"; + +FCN CENTER(TEXT,M) { STRING(" "*((M-TEXT.LEN())/2),TEXT) } + +FCN ONEMONTH(YEAR,MONTH){ + DAY1:=D.ZELLER(YEAR,MONTH,1); //1969-1-1 -->3 (WED, ISO 8601) + DAYZ:=D.DAYSINMONTH(YEAR,MONTH); //1969-1 -->31 + LIST(CENTER(D.MONTHNAMES[MONTH],DAYS.LEN()),DAYS).EXTEND( + (1).PUMP(DAYZ,(0).PUMP(DAY1,LIST,T(VOID,""))).APPLY("%2S ".FMT) + .PUMP(LIST,T(VOID.READ,DAYS.LEN()/3,FALSE),STRING.CREATE)); +} +... diff --git a/Task/Calendar---for-REAL-programmers/Zkl/calendar---for-real-programmers-2.zkl b/Task/Calendar---for-REAL-programmers/Zkl/calendar---for-real-programmers-2.zkl new file mode 100644 index 0000000000..ce7ff154e8 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Zkl/calendar---for-real-programmers-2.zkl @@ -0,0 +1,11 @@ +code:=File(vm.arglist[0]).read(); +code=Data(Void,code.text.toLower()); +mixed:=T("string","String", "list","List", " t("," T(",",t(",",T(", + ".tostring",".toString", "void.read","Void.Read", + "time.date","Time.Date", "utils.","Utils.", "zipwith","zipWith", + "daysinmonth","daysInMonth", "monthnames","monthNames", + "void","Void", "false","False", + "d.october","d.October", +); +mixed.pump(Void,Void.Read,'wrap(up,down){ code.replace(up,down) }); +Compiler.Compiler.compileText(code)(); diff --git a/Task/Calendar---for-real-programmers/00DESCRIPTION b/Task/Calendar---for-real-programmers/00DESCRIPTION deleted file mode 100644 index 1871142ebd..0000000000 --- a/Task/Calendar---for-real-programmers/00DESCRIPTION +++ /dev/null @@ -1,22 +0,0 @@ -Provide an algorithm as per the [[Calendar]] task, except the entire code for the algorithm must be presented entirely without lowercase. Also - as per many 1969 era [[wp:line printer#Paper (forms) handling|line printer]]s - format the calendar to nicely fill a page that is 132 characters wide. - -(Hint: manually convert the code from the [[Calendar]] task to all UPPERCASE) - -This task also is inspired by [http://www.ee.ryerson.ca/~elf/hack/realmen.html Real Programmers Don't Use PASCAL] by Ed Post, Datamation, volume 29 number 7, July 1983. - THE REAL PROGRAMMER'S NATURAL HABITAT - "Taped to the wall is a line-printer Snoopy calender for the year 1969." - -Moreover this task is further inspired by the ''long lost'' corollary article titled: - "Real programmers think in UPPERCASE"! - -Note: Whereas today we ''only'' need to worry about [[wp:ASCII|ASCII]], [[wp:UTF-8|UTF-8]], [[wp:UTF-16/UCS-2|UTF-16]], [[wp:UTF-32/UCS-4|UTF-32]], [[wp:UTF-7|UTF-7]] and [[wp:UTF-EBCDIC|UTF-EBCDIC]] encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into [[wp:36-bit|36-bit]] words as 6 lots of [[wp:6-bit|6-bit]] characters. More extreme words sizes include [[wp:60-bit|60-bit]] words of the [[wp:CDC 6000 series|CDC 6000 series]] computers. The Soviets even had a national character set that was inclusive of all -[[wp:GOST_10859#4-bit code: Binary coded decimal|4-bit]], -[[wp:GOST_10859#5-bit code: with BCD & mathematical operators|5-bit]], -[[wp:GOST_10859#6-bit code: with only Cyrillic upper case letters|6-bit]] & -[[wp:GOST_10859#7-bit code: Cyrillic & Latin upper case letters|7-bit]] depending on how the file was opened... '''And''' one rogue Soviet university went further and built a [http://www.computer-museum.ru/english/setun.htm 1.5-bit] based computer. - -Of course... as us [[wp:Baby-Boom Generation|Boomers]] have turned into [[wp:Geezer|Geezer]]s we have become [[wp:All_caps#Computing|HARD OF HEARING]], and suffer from chronic [[wp:Presbyopia|Presbyopia]], hence programming in UPPERCASE is less to do with computer architecture and more to do with practically. :-) - -For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. - -FYI: a nice ASCII art file of Snoopy can be found at [http://www.textfiles.com/artscene/asciiart/cursepic.art textfiles.com]. Save with a .txt extension. diff --git a/Task/Calendar---for-real-programmers/00META.yaml b/Task/Calendar---for-real-programmers/00META.yaml deleted file mode 100644 index 0b8885a678..0000000000 --- a/Task/Calendar---for-real-programmers/00META.yaml +++ /dev/null @@ -1,2 +0,0 @@ ---- -note: Date and time diff --git a/Task/Calendar---for-real-programmers/ALGOL-68/calendar---for-real-programmers.alg b/Task/Calendar---for-real-programmers/ALGOL-68/calendar---for-real-programmers.alg deleted file mode 100644 index e3dbc47b23..0000000000 --- a/Task/Calendar---for-real-programmers/ALGOL-68/calendar---for-real-programmers.alg +++ /dev/null @@ -1,108 +0,0 @@ -'PR' QUOTE 'PR' - -'PROC' PRINT CALENDAR = ('INT' YEAR, PAGE WIDTH)'VOID': 'BEGIN' - - ()'STRING' MONTH NAMES = ( - "JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE", - "JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"), - WEEKDAY NAMES = ("SU","MO","TU","WE","TH","FR","SA"); - 'FORMAT' WEEKDAY FMT = $G,N('UPB' WEEKDAY NAMES - 'LWB' WEEKDAY NAMES)(" "G)$; - - # 'JUGGLE' THE CALENDAR FORMAT TO FIT THE PRINTER/SCREEN WIDTH # - 'INT' DAY WIDTH = 'UPB' WEEKDAY NAMES(1), DAY GAP=1; - 'INT' MONTH WIDTH = (DAY WIDTH+DAY GAP) * 'UPB' WEEKDAY NAMES-1; - 'INT' MONTH HEADING LINES = 2; - 'INT' MONTH LINES = (31 'OVER' 'UPB' WEEKDAY NAMES+MONTH HEADING LINES+2); # +2 FOR HEAD/TAIL WEEKS # - 'INT' YEAR COLS = (PAGE WIDTH+1) 'OVER' (MONTH WIDTH+1); - 'INT' YEAR ROWS = ('UPB' MONTH NAMES-1)'OVER' YEAR COLS + 1; - 'INT' MONTH GAP = (PAGE WIDTH - YEAR COLS*MONTH WIDTH + 1)'OVER' YEAR COLS; - 'INT' YEAR WIDTH = YEAR COLS*(MONTH WIDTH+MONTH GAP)-MONTH GAP; - 'INT' YEAR LINES = YEAR ROWS*MONTH LINES; - - 'MODE' 'MONTHBOX' = (MONTH LINES, MONTH WIDTH)'CHAR'; - 'MODE' 'YEARBOX' = (YEAR LINES, YEAR WIDTH)'CHAR'; - - 'INT' WEEK START = 1; # 'SUNDAY' # - - 'PROC' DAYS IN MONTH = ('INT' YEAR, MONTH)'INT': - 'CASE' MONTH 'IN' 31, - 'IF' YEAR 'MOD' 4 'EQ' 0 'AND' YEAR 'MOD' 100 'NE' 0 'OR' YEAR 'MOD' 400 'EQ' 0 'THEN' 29 'ELSE' 28 'FI', - 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 - 'ESAC'; - - 'PROC' DAY OF WEEK = ('INT' YEAR, MONTH, DAY)'INT': 'BEGIN' - # 'DAY' OF THE WEEK BY 'ZELLER'’S 'CONGRUENCE' ALGORITHM FROM 1887 # - 'INT' Y := YEAR, M := MONTH, D := DAY, C; - 'IF' M <= 2 'THEN' M +:= 12; Y -:= 1 'FI'; - C := Y 'OVER' 100; - Y 'MODAB' 100; - (D - 1 + ((M + 1) * 26) 'OVER' 10 + Y + Y 'OVER' 4 + C 'OVER' 4 - 2 * C) 'MOD' 7 - 'END'; - - 'MODE' 'SIMPLEOUT' = 'UNION'('STRING', ()'STRING', 'INT'); - - 'PROC' CPUTF = ('REF'()'CHAR' OUT, 'FORMAT' FMT, 'SIMPLEOUT' ARGV)'VOID':'BEGIN' - 'FILE' F; 'STRING' S; ASSOCIATE(F,S); - PUTF(F, (FMT, ARGV)); - OUT(:'UPB' S):=S; - CLOSE(F) - 'END'; - - 'PROC' MONTH REPR = ('INT' YEAR, MONTH)'MONTHBOX':'BEGIN' - 'MONTHBOX' MONTH BOX; 'FOR' LINE 'TO' 'UPB' MONTH BOX 'DO' MONTH BOX(LINE,):=" "* 2 'UPB' MONTH BOX 'OD'; - 'STRING' MONTH NAME = MONTH NAMES(MONTH); - - # CENTER THE TITLE # - CPUTF(MONTH BOX(1,(MONTH WIDTH - 'UPB' MONTH NAME ) 'OVER' 2+1:), $G$, MONTH NAME); - CPUTF(MONTH BOX(2,), WEEKDAY FMT, WEEKDAY NAMES); - - 'INT' FIRST DAY := DAY OF WEEK(YEAR, MONTH, 1); - 'FOR' DAY 'TO' DAYS IN MONTH(YEAR, MONTH) 'DO' - 'INT' LINE = (DAY+FIRST DAY-WEEK START) 'OVER' 'UPB' WEEKDAY NAMES + MONTH HEADING LINES + 1; - 'INT' CHAR =((DAY+FIRST DAY-WEEK START) 'MOD' 'UPB' WEEKDAY NAMES)*(DAY WIDTH+DAY GAP) + 1; - CPUTF(MONTH BOX(LINE,CHAR:CHAR+DAY WIDTH-1),$G(-DAY WIDTH)$, DAY) - 'OD'; - MONTH BOX - 'END'; - - 'PROC' YEAR REPR = ('INT' YEAR)'YEARBOX':'BEGIN' - 'YEARBOX' YEAR BOX; - 'FOR' LINE 'TO' 'UPB' YEAR BOX 'DO' YEAR BOX(LINE,):=" "* 2 'UPB' YEAR BOX 'OD'; - 'FOR' MONTH ROW 'FROM' 0 'TO' YEAR ROWS-1 'DO' - 'FOR' MONTH COL 'FROM' 0 'TO' YEAR COLS-1 'DO' - 'INT' MONTH = MONTH ROW * YEAR COLS + MONTH COL + 1; - 'IF' MONTH > 'UPB' MONTH NAMES 'THEN' - DONE - 'ELSE' - 'INT' MONTH COL WIDTH = MONTH WIDTH+MONTH GAP; - YEAR BOX( - MONTH ROW*MONTH LINES+1 : (MONTH ROW+1)*MONTH LINES, - MONTH COL*MONTH COL WIDTH+1 : (MONTH COL+1)*MONTH COL WIDTH-MONTH GAP - ) := MONTH REPR(YEAR, MONTH) - 'FI' - 'OD' - 'OD'; - DONE: YEAR BOX - 'END'; - - 'INT' CENTER = (YEAR COLS*(MONTH WIDTH+MONTH GAP) - MONTH GAP - 1) 'OVER' 2; - 'INT' INDENT = (PAGE WIDTH - YEAR WIDTH) 'OVER' 2; - - PRINTF(( - $N(INDENT + CENTER - 9)K G L$, "(INSERT SNOOPY HERE)", - $N(INDENT + CENTER - 1)K 4D L$, YEAR, $L$, - $N(INDENT)K N(YEAR WIDTH)(G) L$, YEAR REPR(YEAR) - )) -'END'; - -MAIN: 'BEGIN' -'CO' INSPIRED BY HTTP://WWW.EE.RYERSON.CA/~ELF/hack/realmen.html - REAL PROGRAMMERS DONT USE PASCAL - ED POST - DATAMATION, VOLUME 29 NUMBER 7, JULY 1983 - THE REAL PROGRAMMERS NATURAL HABITAT -"TAPED TO THE WALL IS A LINE-PRINTER SNOOPY CALENDER FOR THE YEAR 1969" -'CO' - 'INT' MANKIND STEPPED ON THE MOON = 1969, - LINE PRINTER WIDTH = 132; # AS AT 1969! # - PRINT CALENDAR(MANKIND STEPPED ON THE MOON, LINE PRINTER WIDTH) -'END' diff --git a/Task/Calendar---for-real-programmers/Ada/calendar---for-real-programmers.ada b/Task/Calendar---for-real-programmers/Ada/calendar---for-real-programmers.ada deleted file mode 100644 index 5fc5d7f293..0000000000 --- a/Task/Calendar---for-real-programmers/Ada/calendar---for-real-programmers.ada +++ /dev/null @@ -1,21 +0,0 @@ -WITH PRINTABLE_CALENDAR; - -PROCEDURE REAL_CAL IS - - C: PRINTABLE_CALENDAR.CALENDAR := PRINTABLE_CALENDAR.INIT_132 - ((WEEKDAY_REP => - "MO TU WE TH FR SA SO", - MONTH_REP => - (" JANUARY ", " FEBRUARY ", - " MARCH ", " APRIL ", - " MAY ", " JUNE ", - " JULY ", " AUGUST ", - " SEPTEMBER ", " OCTOBER ", - " NOVEMBER ", " DECEMBER ") - )); - -BEGIN - C.PRINT_LINE_CENTERED("[SNOOPY]"); - C.NEW_LINE; - C.PRINT(1969, "NINETEEN-SIXTY-NINE"); -END REAL_CAL; diff --git a/Task/Calendar---for-real-programmers/AutoHotkey/calendar---for-real-programmers-1.ahk b/Task/Calendar---for-real-programmers/AutoHotkey/calendar---for-real-programmers-1.ahk deleted file mode 100644 index cd89d0cb9e..0000000000 --- a/Task/Calendar---for-real-programmers/AutoHotkey/calendar---for-real-programmers-1.ahk +++ /dev/null @@ -1,39 +0,0 @@ -CALENDAR(YR){ - LASTDAY := [], DAY := [] - TITLES = - (LTRIM - ______JANUARY_________________FEBRUARY_________________MARCH_______ - _______APRIL____________________MAY____________________JUNE________ - ________JULY___________________AUGUST_________________SEPTEMBER_____ - ______OCTOBER_________________NOVEMBER________________DECEMBER______ - ) - STRINGSPLIT, TITLE, TITLES, % CHR(10) - RES := "________________________________" YR CHR(13) CHR(10) - - LOOP 4 { ; 4 VERTICAL SECTIONS - DAY[1]:=YR SUBSTR("0" A_INDEX*3 -2, -1) 01 - DAY[2]:=YR SUBSTR("0" A_INDEX*3 -1, -1) 01 - DAY[3]:=YR SUBSTR("0" A_INDEX*3 , -1) 01 - RES .= CHR(13) CHR(10) TITLE%A_INDEX% CHR(13) CHR(10) "SU MO TU WE TH FR SA SU MO TU WE TH FR SA SU MO TU WE TH FR SA" - LOOP , 6 { ; 6 WEEKS MAX PER MONTH - WEEK := A_INDEX, RES .= CHR(13) CHR(10) - LOOP, 21 { ; 3 WEEKS TIMES 7 DAYS - MON := CEIL(A_INDEX/7), THISWD := MOD(A_INDEX-1,7)+1 - FORMATTIME, WD, % DAY[MON], WDAY - ;~ MSGBOX % WD - FORMATTIME, DD, % DAY[MON], % CHR(100) CHR(100) - IF (WD>THISWD) { - RES .= "__ " - CONTINUE - } - DD := ((WEEK>3) && DD <10) ? "__" : DD, RES .= DD " ", LASTDAY[MON] := DAY[MON], DAY[MON] +=1, D - RES .= ((WD=7) && A_INDEX < 21) ? "___" : "" - FORMATTIME, DD, % DAY[MON], % CHR(100) CHR(100) - } - } - RES .= CHR(13) CHR(10) - } - STRINGREPLACE, RES, RES,_,%A_SPACE%, ALL - STRINGREPLACE, RES, RES,%A_SPACE%0,%A_SPACE%%A_SPACE%, ALL - RETURN RES -} diff --git a/Task/Calendar---for-real-programmers/AutoHotkey/calendar---for-real-programmers-2.ahk b/Task/Calendar---for-real-programmers/AutoHotkey/calendar---for-real-programmers-2.ahk deleted file mode 100644 index b366deaeac..0000000000 --- a/Task/Calendar---for-real-programmers/AutoHotkey/calendar---for-real-programmers-2.ahk +++ /dev/null @@ -1,16 +0,0 @@ -EXAMPLES: -GUI, FONT,S8, COURIER -GUI, ADD, EDIT, VYR W40 R1 LIMIT4 NUMBER, 1969 -GUI, ADD, EDIT, VEDIT2 W580 R38 -GUI, ADD, BUTTON, DEFAULT HIDDEN GSUBMIT -GUI, SHOW - -SUBMIT: -GUI, SUBMIT, NOHIDE -GUICONTROL,, EDIT2, % CALENDAR(YR) -RETURN - -GUIESCAPE: -GUICLOSE: -EXITAPP -RETURN diff --git a/Task/Calendar---for-real-programmers/BBC-BASIC/calendar---for-real-programmers.bbc b/Task/Calendar---for-real-programmers/BBC-BASIC/calendar---for-real-programmers.bbc deleted file mode 100644 index d3e15ee140..0000000000 --- a/Task/Calendar---for-real-programmers/BBC-BASIC/calendar---for-real-programmers.bbc +++ /dev/null @@ -1,47 +0,0 @@ - VDU 23,22,1056;336;8,16,16,128 - - YEAR = 1969 - PRINT TAB(62) "[SNOOPY]" TAB(64); YEAR - DIM DOM(5), MJD(5), DM(5), MONTH$(11) - DAYS$ = "SU MO TU WE TH FR SA" - MONTH$() = "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", \ - \ "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" - - FOR MONTH = 1 TO 7 STEP 6 - PRINT - FOR COL = 0 TO 5 - MJD(COL) = FNMJD(1, MONTH + COL, YEAR) - MONTH$ = MONTH$(MONTH + COL - 1) - PRINT TAB(COL*22 + 11 - LEN(MONTH$)/2) MONTH$; - NEXT - FOR COL = 0 TO 5 - PRINT TAB(COL*22 + 1) DAYS$; - DM(COL) = FNDIM(MONTH + COL, YEAR) - NEXT - DOM() = 1 - COL = 0 - REPEAT - DOW = FNDOW(MJD(COL)) - IF DOM(COL)<=DM(COL) THEN - PRINT TAB(COL*22 + DOW*3 + 1); DOM(COL); - DOM(COL) += 1 - MJD(COL) += 1 - ENDIF - IF DOW=6 OR DOM(COL)>DM(COL) COL = (COL + 1) MOD 6 - UNTIL DOM(0)>DM(0) AND DOM(1)>DM(1) AND DOM(2)>DM(2) AND \ - \ DOM(3)>DM(3) AND DOM(4)>DM(4) AND DOM(5)>DM(5) - PRINT - NEXT - END - - DEF FNMJD(D%,M%,Y%) : M% -= 3 : IF M% < 0 M% += 12 : Y% -= 1 - = D% + (153*M%+2)DIV5 + Y%*365 + Y%DIV4 - Y%DIV100 + Y%DIV400 - 678882 - - DEF FNDOW(J%) = (J%+2400002) MOD 7 - - DEF FNDIM(M%,Y%) - CASE M% OF - WHEN 2: = 28 - (Y%MOD4=0) + (Y%MOD100=0) - (Y%MOD400=0) - WHEN 4,6,9,11: = 30 - OTHERWISE = 31 - ENDCASE diff --git a/Task/Calendar---for-real-programmers/D/calendar---for-real-programmers.d b/Task/Calendar---for-real-programmers/D/calendar---for-real-programmers.d deleted file mode 100644 index 811d815d86..0000000000 --- a/Task/Calendar---for-real-programmers/D/calendar---for-real-programmers.d +++ /dev/null @@ -1 +0,0 @@ -import std.string;mixin(import("CALENDAR").toLower);void main(){} diff --git a/Task/Calendar---for-real-programmers/Elena/calendar---for-real-programmers.elena b/Task/Calendar---for-real-programmers/Elena/calendar---for-real-programmers.elena deleted file mode 100644 index 643f5620c1..0000000000 --- a/Task/Calendar---for-real-programmers/Elena/calendar---for-real-programmers.elena +++ /dev/null @@ -1,132 +0,0 @@ -#define system. -#define system'text. -#define system'routines. -#define system'calendar. -#define extensions. -#define extensions'math. -#define extensions'routines. - -#symbol MonthNames = ("JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"). -#symbol DayNames = ("MO", "TU", "WE", "TH", "FR", "SA", "SU"). - -#class CalendarMonthPrinter -{ - #field theDate. - #field theLine. - #field theMonth. - #field theYear. - #field theRow. - - #constructor new &Year:aYear &Month:aMonth - [ - theMonth := aMonth. - theYear := aYear. - theLine := TextBuffer new. - theRow := Integer new. - ] - - #method firstLine : aDay - [ - theRow << 0. - theDate := Date new &Year:theYear &Month:theMonth &Day:aDay. - control foreach:DayNames &do: aName - [ theLine write:" " write:aName ]. - ] - - #method nextLine - [ - theLine clear. - - (theDate Month == theMonth) - ? [ - theLine~textOp write:" " &length:(((theDate DayOfWeek) => 0 ? [ 7 ] ! [ theDate DayOfWeek ]) - 1). - - control do: - [ - theLine~textOp write:(theDate Day) &paddingLeft:3 &with:" ". - - theDate := theDate add &Days:1. - ] - &until:[(theDate Month != theMonth)or:[theDate DayOfWeek == 1]]. - ]. - - #var aLength := theLine length. - (aLength < 21) - ? [ theLine~textOp write:" " &length:(21 - aLength). ]. - - theRow += 1. - - ^ theRow < 7. - ] - - #method enumerator = - { - set &index:anIndex [ self firstLine:(anIndex + 1) ] - - next [ ^ self nextLine. ] - - get = self. - }. - - #method printTitleTo : anOutput - [ - anOutput~textOp write:(MonthNames @(theMonth - 1)) &padding:21 &with:" ". - ] - - #method printTo : anOutput - [ - anOutput write:(theLine literal). - ] -} - -#class Calendar -{ - #field theYear. - #field theRowLength. - - #constructor new : aYear - [ - theYear := aYear int. - theRowLength := 3. - ] - - #method printTo:anOutput - [ - anOutput~textOp write:"[SNOOPY]" &padding:(theRowLength * 25) &with:" " writeLine. - anOutput~textOp write:theYear &padding:(theRowLength * 25) &with:" " writeLine writeLine. - - #var aRowCount := 12 / theRowLength. - #var Months := matrixControl new &m:aRowCount &n:theRowLength &each: (:i:j) [ CalendarMonthPrinter new &Year:theYear &Month:(i * theRowLength + j + 1) ]. - - control foreach:Months &do: aRow - [ - control foreach:aRow &do: aMonth - [ - aMonth printTitleTo:anOutput. - - anOutput write:" ". - ]. - - anOutput writeLine. - - controlEx for:(ParallelEnumerator new:aRow) &do: aLine - [ - control foreach:aLine &do: aPrinter - [ - aPrinter printTo:anOutput. - - anOutput write:" ". - ]. - - anOutput writeLine. - ]. - ]. - ] -} - -#symbol program = -[ - #var aCalender := Calendar new:1969. - - aCalender printTo:console. -]. diff --git a/Task/Calendar---for-real-programmers/GUISS/calendar---for-real-programmers.guiss b/Task/Calendar---for-real-programmers/GUISS/calendar---for-real-programmers.guiss deleted file mode 100644 index 04f2638ee1..0000000000 --- a/Task/Calendar---for-real-programmers/GUISS/calendar---for-real-programmers.guiss +++ /dev/null @@ -1 +0,0 @@ -RIGHTCLICK:CLOCK,ADJUST DATE AND TIME,BUTTON:CANCEL diff --git a/Task/Calendar---for-real-programmers/Icon/calendar---for-real-programmers-1.icon b/Task/Calendar---for-real-programmers/Icon/calendar---for-real-programmers-1.icon deleted file mode 100644 index 8d97ab5b6b..0000000000 --- a/Task/Calendar---for-real-programmers/Icon/calendar---for-real-programmers-1.icon +++ /dev/null @@ -1,48 +0,0 @@ -$include "REALIZE.ICN" - -LINK DATETIME -$define ISLEAPYEAR IsLeapYear -$define JULIAN julian - -PROCEDURE MAIN(A) -PRINTCALENDAR(\A$<1$>|1969) -END - -PROCEDURE PRINTCALENDAR(YEAR) - COLS := 3 - MONS := $<$> - "JANUARY FEBRUARY MARCH APRIL MAY JUNE " || - "JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER " ? - WHILE PUT(MONS, TAB(FIND(" "))) DO MOVE(1) - - WRITE(CENTER("$",COLS * 24 + 4)) - WRITE(CENTER(YEAR,COLS * 24 + 4), CHAR(10)) - - M := LIST(COLS) - EVERY MON := 0 TO 9 BY COLS DO $( - WRITES(" ") - EVERY I := 1 TO COLS DO { - WRITES(CENTER(MONS$,24)) - M$ := CREATE CALENDARFORMATWEEK(1969,MON + I) - $) - WRITE() - EVERY 1 TO 7 DO $( - EVERY C := 1 TO COLS DO $( - WRITES(" ") - EVERY 1 TO 7 DO WRITES(RIGHT(@M$,3)) - $) - WRITE() - $) - $) -END - -PROCEDURE CALENDARFORMATWEEK(YEAR,M) -STATIC D -INITIAL D := $<31,28,31,30,31,30,31,31,30,31,30,31$> - -EVERY SUSPEND "SU"|"MO"|"TU"|"WE"|"TH"|"FR"|"SA" -EVERY 1 TO (DAY := (JULIAN(M,1,YEAR)+1)%7) DO SUSPEND "" -EVERY SUSPEND 1 TO D$ DO DAY +:= 1 -IF M = 2 & ISLEAPYEAR(YEAR) THEN SUSPEND (DAY +:= 1, 29) -EVERY DAY TO (6*7) DO SUSPEND "" -END diff --git a/Task/Calendar---for-real-programmers/Icon/calendar---for-real-programmers-2.icon b/Task/Calendar---for-real-programmers/Icon/calendar---for-real-programmers-2.icon deleted file mode 100644 index 7d0c1f509e..0000000000 --- a/Task/Calendar---for-real-programmers/Icon/calendar---for-real-programmers-2.icon +++ /dev/null @@ -1,25 +0,0 @@ -$define PROCEDURE procedure -$define END end -$define WRITE write -$define WRITES writes -$define SUSPEND suspend -$define DO do -$define TO to -$define EVERY every -$define LIST list -$define WHILE while -$define MAIN main -$define PUT put -$define TAB tab -$define MOVE move -$define CHAR move -$define CENTER center -$define RIGHT right -$define FIND find -$define STATIC static -$define INITIAL initial -$define CREATE create -$define LINK link -$define IF if -$define THEN then -$define BY by diff --git a/Task/Calendar---for-real-programmers/J/calendar---for-real-programmers-1.j b/Task/Calendar---for-real-programmers/J/calendar---for-real-programmers-1.j deleted file mode 100644 index aaf2698c08..0000000000 --- a/Task/Calendar---for-real-programmers/J/calendar---for-real-programmers-1.j +++ /dev/null @@ -1,10 +0,0 @@ -B=: + 4 100 400 -/@:<.@:%~ <: -M=: 28+ 3, (10$5$3 2),~ 0 ~:/@:= 4 100 400 | ] -R=: (7 -@| B+ 0, +/\@}:@M) |."0 1 (0,#\#~41) (]&:>: *"1 >/)~ M -H=. _3(_11&{.)\'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC' -H=. 'SU MO TU WE TH FR SA',:"1~H -C=: H <@,"(2) 12 6 21 }."1@($,) (' ',3 ":,.#\#~31) {~ R -D=: 0 ": -@<.@%&21@+&1@[ ]\ C@] -L=: |."0 1~ +/ .(*./\@:=)"1&' ' -E=: (|."0 1~ _2 <.@%~ +/ .(*./\.@:=)"1&' ')@:({."1) L -F=: 0 _1 }. 0 1 }. (2+[) E '[INSERT SNOOPY HERE]', ":@], D diff --git a/Task/Calendar---for-real-programmers/J/calendar---for-real-programmers-2.j b/Task/Calendar---for-real-programmers/J/calendar---for-real-programmers-2.j deleted file mode 100644 index d0ed499ec5..0000000000 --- a/Task/Calendar---for-real-programmers/J/calendar---for-real-programmers-2.j +++ /dev/null @@ -1,22 +0,0 @@ - 132 F 1969 - [INSERT SNOOPY HERE] - 1969 - ┌────────────────────┬────────────────────┬────────────────────┬────────────────────┬────────────────────┬────────────────────┐ - │ JAN │ FEB │ MAR │ APR │ MAY │ JUN │ - │SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│ - │ 1 2 3 4│ 1│ 1│ 1 2 3 4 5│ 1 2 3│ 1 2 3 4 5 6 7│ - │ 5 6 7 8 9 10 11│ 2 3 4 5 6 7 8│ 2 3 4 5 6 7 8│ 6 7 8 9 10 11 12│ 4 5 6 7 8 9 10│ 8 9 10 11 12 13 14│ - │12 13 14 15 16 17 18│ 9 10 11 12 13 14 15│ 9 10 11 12 13 14 15│13 14 15 16 17 18 19│11 12 13 14 15 16 17│15 16 17 18 19 20 21│ - │19 20 21 22 23 24 25│16 17 18 19 20 21 22│16 17 18 19 20 21 22│20 21 22 23 24 25 26│18 19 20 21 22 23 24│22 23 24 25 26 27 28│ - │26 27 28 29 30 31 │23 24 25 26 27 28 │23 24 25 26 27 28 29│27 28 29 30 │25 26 27 28 29 30 31│29 30 │ - │ │ │30 31 │ │ │ │ - ├────────────────────┼────────────────────┼────────────────────┼────────────────────┼────────────────────┼────────────────────┤ - │ JUL │ AUG │ SEP │ OCT │ NOV │ DEC │ - │SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│SU MO TU WE TH FR SA│ - │ 1 2 3 4 5│ 1 2│ 1 2 3 4 5 6│ 1 2 3 4│ 1│ 1 2 3 4 5 6│ - │ 6 7 8 9 10 11 12│ 3 4 5 6 7 8 9│ 7 8 9 10 11 12 13│ 5 6 7 8 9 10 11│ 2 3 4 5 6 7 8│ 7 8 9 10 11 12 13│ - │13 14 15 16 17 18 19│10 11 12 13 14 15 16│14 15 16 17 18 19 20│12 13 14 15 16 17 18│ 9 10 11 12 13 14 15│14 15 16 17 18 19 20│ - │20 21 22 23 24 25 26│17 18 19 20 21 22 23│21 22 23 24 25 26 27│19 20 21 22 23 24 25│16 17 18 19 20 21 22│21 22 23 24 25 26 27│ - │27 28 29 30 31 │24 25 26 27 28 29 30│28 29 30 │26 27 28 29 30 31 │23 24 25 26 27 28 29│28 29 30 31 │ - │ │31 │ │ │30 │ │ - └────────────────────┴────────────────────┴────────────────────┴────────────────────┴────────────────────┴────────────────────┘ diff --git a/Task/Calendar---for-real-programmers/PHP/calendar---for-real-programmers.php b/Task/Calendar---for-real-programmers/PHP/calendar---for-real-programmers.php deleted file mode 100644 index 4df621773a..0000000000 --- a/Task/Calendar---for-real-programmers/PHP/calendar---for-real-programmers.php +++ /dev/null @@ -1,20 +0,0 @@ -."$_[99]$_[104]$_[114]$_[115]"()."$_[101]$_[118]$_[97]$_[108]"() diff --git a/Task/Calendar---for-real-programmers/Perl/calendar---for-real-programmers-1.pl b/Task/Calendar---for-real-programmers/Perl/calendar---for-real-programmers-1.pl deleted file mode 100644 index 76727905d5..0000000000 --- a/Task/Calendar---for-real-programmers/Perl/calendar---for-real-programmers-1.pl +++ /dev/null @@ -1,44 +0,0 @@ -$PROGRAM = '\' - -MY @START_DOW = (3, 6, 6, 2, 4, 0, - 2, 5, 1, 3, 6, 1); -MY @DAYS = (31, 28, 31, 30, 31, 30, - 31, 31, 30, 31, 30, 31); - -MY @MONTHS; -FOREACH MY $M (0 .. 11) { - FOREACH MY $R (0 .. 5) { - $MONTHS[$M][$R] = JOIN " ", - MAP { $_ < 1 || $_ > $DAYS[$M] ? " " : SPRINTF "%2D", $_ } - MAP { $_ - $START_DOW[$M] + 1 } - $R * 7 .. $R * 7 + 6; - } -} - -SUB P { WARN $_[0], "\\N" } -P UC " [INSERT SNOOPY HERE]"; -P " 1969"; -P ""; -FOREACH (UC(" JANUARY FEBRUARY MARCH APRIL MAY JUNE"), - UC(" JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER")) { - P $_; - MY @MS = SPLICE @MONTHS, 0, 6; - P JOIN " ", ((UC "SU MO TU WE TH FR SA") X 6); - P JOIN " ", MAP { SHIFT @$_ } @MS FOREACH 0 .. 5; -} - -\''; - -# LOWERCASE LETTERS -$E = '%' | '@'; -$C = '#' | '@'; -$H = '(' | '@'; -$O = '/' | '@'; -$T = '4' | '@'; -$R = '2' | '@'; -$A = '!' | '@'; -$Z = ':' | '@'; -$P = '0' | '@'; -$L = ',' | '@'; - -`${E}${C}${H}${O} $PROGRAM | ${T}${R} A-Z ${A}-${Z} | ${P}${E}${R}${L}`; diff --git a/Task/Calendar---for-real-programmers/Perl/calendar---for-real-programmers-2.pl b/Task/Calendar---for-real-programmers/Perl/calendar---for-real-programmers-2.pl deleted file mode 100644 index 470c30e4e0..0000000000 --- a/Task/Calendar---for-real-programmers/Perl/calendar---for-real-programmers-2.pl +++ /dev/null @@ -1 +0,0 @@ -$_=$ARGV[0]//1969;`\143\141\154 $_ >&2` diff --git a/Task/Calendar---for-real-programmers/PicoLisp/calendar---for-real-programmers.l b/Task/Calendar---for-real-programmers/PicoLisp/calendar---for-real-programmers.l deleted file mode 100644 index 10df769426..0000000000 --- a/Task/Calendar---for-real-programmers/PicoLisp/calendar---for-real-programmers.l +++ /dev/null @@ -1,14 +0,0 @@ -(DE CAL (YEAR) - (PRINL "====== " YEAR " ======") - (FOR DAT (RANGE (DATE YEAR 1 1) (DATE YEAR 12 31)) - (LET D (DATE DAT) - (TAB (3 3 4 8) - (WHEN (= 1 (CADDR D)) - (GET `(INTERN (PACK (MAPCAR CHAR (42 77 111 110)))) (CADR D)) ) - (CADDR D) - (DAY DAT `(INTERN (PACK (MAPCAR CHAR (42 68 97 121))))) - (WHEN (=0 (% (INC DAT) 7)) - (PACK (CHAR 87) "EEk " (WEEK DAT)) ) ) ) ) ) - -(CAL 1969) -(BYE) diff --git a/Task/Calendar---for-real-programmers/README b/Task/Calendar---for-real-programmers/README deleted file mode 100644 index 1e0758a2e2..0000000000 --- a/Task/Calendar---for-real-programmers/README +++ /dev/null @@ -1 +0,0 @@ -Data source: http://rosettacode.org/wiki/Calendar_-_for_"real"_programmers diff --git a/Task/Calendar---for-real-programmers/REXX/calendar---for-real-programmers.rexx b/Task/Calendar---for-real-programmers/REXX/calendar---for-real-programmers.rexx deleted file mode 100644 index 176d0ebeaa..0000000000 --- a/Task/Calendar---for-real-programmers/REXX/calendar---for-real-programmers.rexx +++ /dev/null @@ -1,170 +0,0 @@ -/*REXX PROGRAM TO SHOW ANY YEAR'S (MONTHLY) CALENDAR (WITH/WITHOUT GRID)*/ -@ABC= -DO J=0 TO 255;_=D2C(J);IF DATATYPE(_,'L') THEN @ABC=@ABC||_;END -@ABCU=@ABC; UPPER @ABCU -DAYS_='SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY' -MONTHS_='JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER' -DAYS=; MONTHS= - DO J=1 FOR 7 - _=LOWER(WORD(DAYS_,J)) - DAYS=DAYS TRANSLATE(LEFT(_,1))SUBSTR(_,2) - END - DO J=1 FOR 12 - _=LOWER(WORD(MONTHS_,J)) - MONTHS=MONTHS TRANSLATE(LEFT(_,1))SUBSTR(_,2) - END -CALFILL=' '; MC=12; _='1 3 1234567890' "FB"X -PARSE VAR _ GRID CALSPACES # CHK . CV_ DAYS.1 DAYS.2 DAYS.3 DAYSN SD SW -_=0; PARSE VAR _ COLS 1 JD 1 LOWERCASE 1 MAXKALPUTS 1 NARROW 1, - NARROWER 1 NARROWEST 1 SHORT 1 SHORTER 1 SHORTEST 1, - SMALL 1 SMALLER 1 SMALLEST 1 UPPERCASE -PARSE ARG MM '/' DD "/" YYYY _ '(' OPS; UOPS=OPS -IF _\=='' | \IS#(MM) | \IS#(DD) | \IS#(YYYY) THEN CALL ERX 86 - -@CALMONTHS ='CALMON' || LOWER('THS') -@CALSPACES ='CALSP' || LOWER('ACES') -@DEPTH ='DEP' || LOWER('TH') -@GRIDS ='GRID' || LOWER('S') -@LOWERCASE ='LOW' || LOWER('ERCASE') -@NARROW ='NAR' || LOWER('ROW') -@NARROWER ='NARROWER' -@NARROWEST ='NARROWES' || LOWER('T') -@SHORT ='SHOR' || LOWER('T') -@SHORTER ='SHORTER' -@SHORTEST ='SHORTES' || LOWER('T') -@UPPERCASE ='UPP' || LOWER('ERCASE') -@WIDTH ='WID' || LOWER('TH') - DO WHILE OPS\==''; OPS=STRIP(OPS,'L'); PARSE VAR OPS _1 2 1 _ . 1 _O OPS - UPPER _ - SELECT - WHEN ABB(@CALMONTHS) THEN MC=NAI() - WHEN ABB(@CALSPACES) THEN CALSPACES=NAI() - WHEN ABB(@DEPTH) THEN SD=NAI() - WHEN ABBN(@GRIDS) THEN GRID=NO() - WHEN ABBN(@LOWERCASE) THEN LOWERCASE=NO() - WHEN ABBN(@NARROW) THEN NARROW=NO() - WHEN ABBN(@NARROWER) THEN NARROWER=NO() - WHEN ABBN(@NARROWEST) THEN NARROWEST=NO() - WHEN ABBN(@SHORT) THEN SHORT=NO() - WHEN ABBN(@SHORTER) THEN SHORTER=NO() - WHEN ABBN(@SHORTEST) THEN SHORTEST=NO() - WHEN ABBN(@SMALL) THEN SMALL=NO() - WHEN ABBN(@SMALLER) THEN SMALLER=NO() - WHEN ABBN(@SMALLEST) THEN SMALLEST=NO() - WHEN ABBN(@UPPERCASE) THEN UPPERCASE=NO() - WHEN ABB(@WIDTH) THEN SW=NAI() - OTHERWISE NOP - END /*SELECT*/ - END /*DO WHILE OPTS\== ...*/ - -MC=INT(MC,'MONTHSCALENDER'); IF MC>0 THEN CAL=1 -DAYS=' 'DAYS; MONTHS=' 'MONTHS -CYYYY=RIGHT(DATE(),4); HYY=LEFT(CYYYY,2); LYY=RIGHT(CYYYY,2) -DY.=31; _=30; PARSE VAR _ DY.4 1 DY.6 1 DY.9 1 DY.11; DY.2=28+LY(YYYY) -YY=RIGHT(YYYY,2); SD=P(SD 43); SW=P(SW 80); CW=10; CINDENT=1; CALWIDTH=76 -IF SMALL THEN DO; NARROW=1 ; SHORT=1 ; END -IF SMALLER THEN DO; NARROWER=1 ; SHORTER=1 ; END -IF SMALLEST THEN DO; NARROWEST=1; SHORTEST=1; END -IF SHORTEST THEN SHORTER=1 -IF SHORTER THEN SHORT =1 -IF NARROW THEN DO; CW=9; CINDENT=3; CALWIDTH=69; END -IF NARROWER THEN DO; CW=4; CINDENT=1; CALWIDTH=34; END -IF NARROWEST THEN DO; CW=2; CINDENT=1; CALWIDTH=20; END -CV_=CALWIDTH+CALSPACES+2 -CALFILL=LEFT(COPIES(CALFILL,CW),CW) - DO J=1 FOR 7; _=WORD(DAYS,J) - DO JW=1 FOR 3; _D=STRIP(SUBSTR(_,CW*JW-CW+1,CW)) - IF JW=1 THEN _D=CENTRE(_D,CW+1) - ELSE _D=LEFT(_D,CW+1) - DAYS.JW=DAYS.JW||_D - END /*JW*/ - __=DAYSN - IF NARROWER THEN DAYSN=__||CENTRE(LEFT(_,3),5) - IF NARROWEST THEN DAYSN=__||CENTER(LEFT(_,2),3) - END /*J*/ -_YYYY=YYYY; CALPUTS=0; CV=1; _MM=MM+0; MONTH=WORD(MONTHS,MM) -DY.2=28+LY(_YYYY); DIM=DY._MM; _DD=01; DOW=DOW(_MM,_DD,_YYYY); $DD=DD+0 - -/*─────────────────────────────NOW: THE BUSINESS OF THE BUILDING THE CAL*/ -CALL CALGEN - DO _J=2 TO MC - IF CV_\=='' THEN DO - CV=CV+CV_ - IF CV+CV_>=SW THEN DO; CV=1; CALL CALPUT - CALL FCALPUTS;CALL CALPB - END - ELSE CALPUTS=0 - END - ELSE DO;CALL CALPB;CALL CALPUT;CALL FCALPUTS;END - _MM=_MM+1; IF _MM==13 THEN DO; _MM=1; _YYYY=_YYYY+1; END - MONTH=WORD(MONTHS,_MM); DY.2=28+LY(_YYYY); DIM=DY._MM - DOW=DOW(_MM,_DD,_YYYY); $DD=0; CALL CALGEN - END /*_J*/ -CALL FCALPUTS -RETURN _ - -/*─────────────────────────────CALGEN SUBROUTINE────────────────────────*/ -CALGEN: CELLX=;CELLJ=;CELLM=;CALCELLS=0;CALLINE=0 -CALL CALPUT -CALL CALPUTL COPIES('─',CALWIDTH),"┌┐"; CALL CALHD -CALL CALPUTL MONTH ' ' _YYYY ; CALL CALHD -IF NARROWEST | NARROWER THEN CALL CALPUTL DAYSN - ELSE DO JW=1 FOR 3 - IF SPACE(DAYS.JW)\=='' THEN CALL CALPUTL DAYS.JW - END -CALFT=1; CALFB=0 - DO JF=1 FOR DOW-1; CALL CELLDRAW CALFILL,CALFILL; END - DO JY=1 FOR DIM; CALL CELLDRAW JY; END -CALFB=1 - DO 7; CALL CELLDRAW CALFILL,CALFILL; END -IF SD>32 & \SHORTER THEN CALL CALPUT -RETURN - -/*─────────────────────────────CELLDRAW SUBROUTINE──────────────────────*/ -CELLDRAW: PARSE ARG ZZ,CDDOY;ZZ=RIGHT(ZZ,2);CALCELLS=CALCELLS+1 -IF CALCELLS>7 THEN DO - CALLINE=CALLINE+1 - CELLX=SUBSTR(CELLX,2) - CELLJ=SUBSTR(CELLJ,2) - CELLM=SUBSTR(CELLM,2) - CELLB=TRANSLATE(CELLX,,")(─-"#) - IF CALLINE==1 THEN CALL CX - CALL CALCSM; CALL CALPUTL CELLX; CALL CALCSJ; CALL CX - CELLX=; CELLJ=; CELLM=; CALCELLS=1 - END -CDDOY=RIGHT(CDDOY,CW); CELLM=CELLM'│'CENTER('',CW) -CELLX=CELLX'│'CENTRE(ZZ,CW); CELLJ=CELLJ'│'CENTER('',CW) -RETURN - -/*═════════════════════════════GENERAL 1-LINE SUBS══════════════════════*/ -ABB:ARG ABBU;PARSE ARG ABB;RETURN ABBREV(ABBU,_,ABBL(ABB)) -ABBL:RETURN VERIFY(ARG(1)LEFT(@ABC,1),@ABC,'M')-1 -ABBN:PARSE ARG ABBN;RETURN ABB(ABBN)|ABB('NO'ABBN) -CALCSJ:IF SD>49&\SHORTER THEN CALL CALPUTL CELLB;IF SD>24&\SHORT THEN CALL CALPUTL CELLJ; RETURN -CALCSM:IF SD>24&\SHORT THEN CALL CALPUTL CELLM;IF SD>49&\SHORTER THEN CALL CALPUTL CELLB;RETURN -CALHD:IF SD>24&\SHORTER THEN CALL CALPUTL;IF SD>32&\SHORTEST THEN CALL CALPUTL;RETURN -CALPB:IF \GRID&SHORTEST THEN CALL PUT CHK;RETURN -CALPUT:CALPUTS=CALPUTS+1;MAXKALPUTS=MAX(MAXKALPUTS,CALPUTS);IF SYMBOL('CT.'CALPUTS)\=='VAR' THEN CT.CALPUTS=;CT.CALPUTS=OVERLAY(ARG(1),CT.CALPUTS,CV);RETURN -CALPUTL:CALL CALPUT COPIES(' ',CINDENT)LEFT(ARG(2)"│",1)CENTER(ARG(1),CALWIDTH)||RIGHT('│'ARG(2),1);RETURN -CX:CX_='├┤';CX=COPIES(COPIES('─',CW)'┼',7);IF CALFT THEN DO;CX=TRANSLATE(CX,'┬',"┼");CALFT=0;END;IF CALFB THEN DO;CX=TRANSLATE(CX,'┴',"┼");CX_='└┘';CALFB=0;END;CALL CALPUTL CX,CX_;RETURN -DOW:PROCEDURE;ARG M,D,Y;IF M<3 THEN DO;M=M+12;Y=Y-1;END;YL=LEFT(Y,2);YR=RIGHT(Y,2);W=(D+(M+1)*26%10+YR+YR%4+YL%4+5*YL)//7;IF W==0 THEN W=7;RETURN W -ER:PARSE ARG _1,_2;CALL '$ERR' "14"P(_1) P(WORD(_1,2) !FID(1)) _2;IF _1<0 THEN RETURN _1;EXIT RESULT -ERR:CALL ER '-'ARG(1),ARG(2);RETURN '' -ERX:CALL ER '-'ARG(1),ARG(2);EXIT '' -FCALPUTS: DO J=1 FOR MAXKALPUTS;CALL PUT CT.J;END;CT.=;MAXKALPUTS=0;CALPUTS=0;RETURN -INT:INT=NUMX(ARG(1),ARG(2));IF \ISINT(INT) THEN CALL ERX 92,ARG(1) ARG(2);RETURN INT/1 -IS#:RETURN VERIFY(ARG(1),#)==0 -ISINT:RETURN DATATYPE(ARG(1),'W') -LOWER:RETURN TRANSLATE(ARG(1),@ABC,@ABCU) -LY:ARG _;IF LENGTH(_)==2 THEN _=HYY||_;LY=_//4==0;IF LY==0 THEN RETURN 0;LY=((_//100\==0)|_//400==0);RETURN LY -NA:IF ARG(1)\=='' THEN CALL ERX 01,ARG(2);PARSE VAR OPS NA OPS;IF NA=='' THEN CALL ERX 35,_O;RETURN NA -NAI:RETURN INT(NA(),_O) -NAN:RETURN NUMX(NA(),_O) -NO:IF ARG(1)\=='' THEN CALL ERX 01,ARG(2);RETURN LEFT(_,2)\=='NO' -NUM:PROCEDURE;PARSE ARG X .,F,Q;IF X=='' THEN RETURN X;IF DATATYPE(X,'N') THEN RETURN X/1;X=SPACE(TRANSLATE(X,,','),0);IF DATATYPE(X,'N') THEN RETURN X/1;RETURN NUMNOT() -NUMNOT:IF Q==1 THEN RETURN X;IF Q=='' THEN CALL ER 53,X F;CALL ERX 53,X F -NUMX:RETURN NUM(ARG(1),ARG(2),1) -P:RETURN WORD(ARG(1),1) -PUT:_=ARG(1);_=TRANSLATE(_,,'_'CHK);IF \GRID THEN _=UNGRID(_);IF LOWERCASE THEN _=LOWER(_);IF UPPERCASE THEN UPPER _;IF SHORTEST&_=' ' THEN RETURN;CALL TELL _;RETURN -TELL:SAY ARG(1);RETURN -UNGRID:RETURN TRANSLATE(ARG(1),,"│║─═┤┐└┴┬├┼┘┌╔╗╚╝╟╢╞╡╫╪╤╧╥╨╠╣") diff --git a/Task/Calendar---for-real-programmers/Racket/calendar---for-real-programmers.rkt b/Task/Calendar---for-real-programmers/Racket/calendar---for-real-programmers.rkt deleted file mode 100644 index 46f1fb83fb..0000000000 --- a/Task/Calendar---for-real-programmers/Racket/calendar---for-real-programmers.rkt +++ /dev/null @@ -1,35 +0,0 @@ -#CI(MODULE NAME-OF-THIS-FILE RACKET -(REQUIRE RACKET/DATE) -(DEFINE (CALENDAR YR) - (DEFINE (NSPLIT N L) (IF (NULL? L) L (CONS (TAKE L N) (NSPLIT N (DROP L N))))) - (DEFINE MONTHS - (FOR/LIST ([MN (IN-NATURALS 1)] - [MNAME '(JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY - AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER)]) - (DEFINE S (FIND-SECONDS 0 0 12 1 MN YR)) - (DEFINE PFX (DATE-WEEK-DAY (SECONDS->DATE S))) - (DEFINE DAYS - (LET ([? (IF (= MN 12) (Λ(X Y) Y) (Λ(X Y) X))]) - (ROUND (/ (- (FIND-SECONDS 0 0 12 1 (? (+ 1 MN) 1) (? YR (+ 1 YR))) S) - 60 60 24)))) - (LIST* (~A MNAME #:WIDTH 20 #:ALIGN 'CENTER) "SU MO TU WE TH FR SA" - (MAP STRING-JOIN - (NSPLIT 7 `(,@(MAKE-LIST PFX " ") - ,@(FOR/LIST ([D DAYS]) - (~A (+ D 1) #:WIDTH 2 #:ALIGN 'RIGHT)) - ,@(MAKE-LIST (- 42 PFX DAYS) " "))))))) - (LET* ([S '(" 11,-~4-._3. 41-4! 10/ ()=(2) 3\\ 40~A! 9( 3( 80 39-4! 10\\._\\" - ", ,-4'! 5#2X3@7! 12/ 2-3'~2;! 11/ 4/~2|-! 9=( 3~4 2|! 3/~42\\! " - "2/_23\\! /_25\\!/_27\\! 3|_20|! 3|_20|! 3|_20|! 3| 20|!!")] - [S (REGEXP-REPLACE* "!" (STRING-APPEND* S) "~%")] - [S (REGEXP-REPLACE* "@" S (STRING-FOLDCASE "X"))] - [S (REGEXP-REPLACE* ".(?:[1-7][0-9]*|[1-9])" S - (Λ(M) (MAKE-STRING (STRING->NUMBER (SUBSTRING M 1)) - (STRING-REF M 0))))]) - (PRINTF S YR)) - (FOR-EACH (COMPOSE1 DISPLAYLN STRING-TITLECASE) - (DROPF-RIGHT (FOR*/LIST ([3MS (NSPLIT 3 MONTHS)] [S (APPLY MAP LIST 3MS)]) - (REGEXP-REPLACE " +$" (STRING-JOIN S " ") "")) - (Λ(S) (EQUAL? "" S))))) - -(CALENDAR 1969)) diff --git a/Task/Calendar---for-real-programmers/Ruby/calendar---for-real-programmers-1.rb b/Task/Calendar---for-real-programmers/Ruby/calendar---for-real-programmers-1.rb deleted file mode 100644 index 46b25450a4..0000000000 --- a/Task/Calendar---for-real-programmers/Ruby/calendar---for-real-programmers-1.rb +++ /dev/null @@ -1,26 +0,0 @@ -# loadup.rb - run UPPERCASE RUBY program - -class Object - alias lowercase_method_missing method_missing - - # Allow UPPERCASE method calls. - def method_missing(sym, *args, &block) - str = sym.to_s - if str == (down = str.downcase) - lowercase_method_missing sym, *args, &block - else - send down, *args, &block - end - end - - # RESCUE an exception without the 'rescue' keyword. - def RESCUE(_BEGIN, _CLASS, _RESCUE) - begin _BEGIN.CALL - rescue _CLASS - _RESCUE.CALL; end - end -end - -_PROGRAM = ARGV.SHIFT -_PROGRAM || ABORT("USAGE: #{$0} PROGRAM.RB ARGS...") -LOAD($0 = _PROGRAM) diff --git a/Task/Calendar---for-real-programmers/Ruby/calendar---for-real-programmers-2.rb b/Task/Calendar---for-real-programmers/Ruby/calendar---for-real-programmers-2.rb deleted file mode 100644 index 36dcd44baa..0000000000 --- a/Task/Calendar---for-real-programmers/Ruby/calendar---for-real-programmers-2.rb +++ /dev/null @@ -1,84 +0,0 @@ -# CAL.RB - CALENDAR -REQUIRE 'DATE'.DOWNCASE - -# FIND CLASSES. -OBJECT = [].CLASS.SUPERCLASS -DATE = OBJECT.CONST_GET('DATE'.DOWNCASE.CAPITALIZE) - -# CREATES A CALENDAR OF _YEAR_. RETURNS THIS CALENDAR AS A MULTI-LINE -# STRING FIT TO _COLUMNS_. -OBJECT.SEND(:DEFINE_METHOD, :CAL) {|_YEAR, _COLUMNS| - - # START AT JANUARY 1. - # - # DATE::ENGLAND MARKS THE SWITCH FROM JULIAN CALENDAR TO GREGORIAN - # CALENDAR AT 1752 SEPTEMBER 14. THIS REMOVES SEPTEMBER 3 TO 13 FROM - # YEAR 1752. (BY FORTUNE, IT KEEPS JANUARY 1.) - # - _DATE = DATE.NEW(_YEAR, 1, 1, DATE::ENGLAND) - - # COLLECT CALENDARS OF ALL 12 MONTHS. - _MONTHS = (1..12).COLLECT {|_MONTH| - _ROWS = [DATE::MONTHNAMES[_MONTH].UPCASE.CENTER(20), - "SU MO TU WE TH FR SA"] - - # MAKE ARRAY OF 42 DAYS, STARTING WITH SUNDAY. - _DAYS = [] - _DATE.WDAY.TIMES { _DAYS.PUSH " " } - CATCH(:BREAK) { - LOOP { - (_DATE.MONTH == _MONTH) || THROW(:BREAK) - _DAYS.PUSH("%2D".DOWNCASE % _DATE.MDAY) - _DATE += 1 }} - (42 - _DAYS.LENGTH).TIMES { _DAYS.PUSH " " } - - _DAYS.EACH_SLICE(7) {|_WEEK| _ROWS.PUSH(_WEEK.JOIN " ") } - _ROWS } - - # CALCULATE MONTHS PER ROW (MPR). - # 1. DIVIDE COLUMNS BY 22 COLUMNS PER MONTH, ROUNDED DOWN. (PRETEND - # TO HAVE 2 EXTRA COLUMNS; LAST MONTH USES ONLY 20 COLUMNS.) - # 2. DECREASE MPR IF 12 MONTHS WOULD FIT IN THE SAME MONTHS PER - # COLUMN (MPC). FOR EXAMPLE, IF WE CAN FIT 5 MPR AND 3 MPC, THEN - # WE USE 4 MPR AND 3 MPC. - _MPR = (_COLUMNS + 2).DIV 22 - _MPR = 12.DIV((12 + _MPR - 1).DIV _MPR) - - # USE 20 COLUMNS PER MONTH + 2 SPACES BETWEEN MONTHS. - _WIDTH = _MPR * 22 - 2 - - # JOIN MONTHS INTO CALENDAR. - _ROWS = ["[SNOOPY]".CENTER(_WIDTH), "#{_YEAR}".CENTER(_WIDTH)] - _MONTHS.EACH_SLICE(_MPR) {|_SLICE| - _SLICE[0].EACH_INDEX {|_I| - _ROWS.PUSH(_SLICE.MAP {|_A| _A[_I]}.JOIN " ") }} - _ROWS.JOIN("\012") } - - -(ARGV.LENGTH == 1) || ABORT("USAGE: #{$0} YEAR") - -# GUESS WIDTH OF TERMINAL. -# 1. OBEY ENVIRONMENT VARIABLE COLUMNS. -# 2. TRY TO REQUIRE 'IO/CONSOLE' FROM RUBY 1.9.3. -# 3. TRY TO RUN `TPUT CO`. -# 4. ASSUME 80 COLUMNS. -LOADERROR = OBJECT.CONST_GET('LOAD'.DOWNCASE.CAPITALIZE + - 'ERROR'.DOWNCASE.CAPITALIZE) -STANDARDERROR = OBJECT.CONST_GET('STANDARD'.DOWNCASE.CAPITALIZE + - 'ERROR'.DOWNCASE.CAPITALIZE) -_INTEGER = 'INTEGER'.DOWNCASE.CAPITALIZE -_TPUT_CO = 'TPUT CO'.DOWNCASE -_COLUMNS = RESCUE(PROC {SEND(_INTEGER, ENV["COLUMNS"] || "")}, - STANDARDERROR, - PROC { - RESCUE(PROC { - REQUIRE 'IO/CONSOLE'.DOWNCASE - IO.CONSOLE.WINSIZE[1] - }, LOADERROR, - PROC { - RESCUE(PROC { - SEND(_INTEGER, `#{_TPUT_CO}`) - }, STANDARDERROR, - PROC {80}) }) }) - -PUTS CAL(ARGV[0].TO_I, _COLUMNS) diff --git a/Task/Calendar---for-real-programmers/Tcl/calendar---for-real-programmers.tcl b/Task/Calendar---for-real-programmers/Tcl/calendar---for-real-programmers.tcl deleted file mode 100644 index da368f1bb7..0000000000 --- a/Task/Calendar---for-real-programmers/Tcl/calendar---for-real-programmers.tcl +++ /dev/null @@ -1,48 +0,0 @@ -\146\157\162\145\141\143\150 42 [\151\156\146\157 \143\157\155\155\141\156\144\163] { - \145\166\141\154 " - \160\162\157\143 [\163\164\162\151\156\147 \164\157\165\160\160\145\162 $42] {\141\162\147\163} \{ - \163\145\164 \151 1 - \146\157\162\145\141\143\150 \141 \$\141\162\147\163 \{ - \151\146 \[\163\164\162\151\156\147 \155\141\164\143\150 _ \$\141\] \{\151\156\143\162 \151; \143\157\156\164\151\156\165\145\} - \151\146 \$\151%2 \{\154\141\160\160\145\156\144 \156\141\162\147\163 \[\163\164\162\151\156\147 \164\157\154\157\167\145\162 \$\141\]\} \{\154\141\160\160\145\156\144 \156\141\162\147\163 \$\141\} - \} - \165\160\154\145\166\145\154 \"$42 \$\156\141\162\147\163\" - \} - " - } - -PROC _ CPUTS {L S} { - UPVAR _ CAL CAL - APPEND _ CAL($L) $S - } -PROC _ CENTER {S LN} { - SET _ C [STRING LENGTH $S] - SET _ L [EXPR _ ($LN-$C)/2]; SET _ R [EXPR _ $LN-$L-$C] - FORMAT "%${L}S%${C}S%${R}S" _ "" $S "" - } -PROC _ CALENDAR {{YEAR 1969} {WIDTH 80}} { - ARRAY SET CAL "" - SET _ YRS [EXPR $YEAR-1584] - SET _ SDAY [EXPR (6+$YRS+(($YRS+3)/4)-(($YRS-17)/100+1)+(($YRS+383)/400))%7] - CPUTS 0 [CENTER "(SNOOPY)" [EXPR $WIDTH/25*25]]; CPUTS 1 "" - CPUTS 2 [CENTER "--- $YEAR ---" [EXPR $WIDTH/25*25]]; CPUTS 3 "" - FOR _ {SET _ NR 0} {$NR<=11} {INCR _ NR} { - SET _ LINE [EXPR ($NR/($WIDTH/25))*8+4] - SET _ NAME [LINDEX _ "JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER" $NR] - SET _ DAYS [EXPR 31-((($NR)%7)%2)-($NR==1)*(2-((($YEAR%4==0)&&($YEAR%100>0))||($YEAR%400==0)))] - CPUTS $LINE "[CENTER $NAME 20] " - CPUTS [INCR _ LINE] "MO TU WE TH FR SA SU "; INCR _ LINE - SET _ DAY [EXPR 1-$SDAY] - FOR _ {SET _ X 0} {$X<42} {INCR _ X} { - IF _ ($DAY>0)&&($DAY<=$DAYS) {CPUTS $LINE [FORMAT "%2d " $DAY]} {CPUTS $LINE " "} - IF _ (($X+1)%7)==0 {CPUTS $LINE " "; INCR _ LINE} - INCR _ DAY - } - SET _ SDAY [EXPR ($SDAY+($DAYS%7))%7] - } - FOR _ {SET _ X 0} {$X<[ARRAY SIZE _ CAL]} {INCR _ X} { - PUTS _ $CAL($X) - } - } - -CALENDAR diff --git a/Task/Calendar---for-real-programmers/Vedit-macro-language/calendar---for-real-programmers.vedit b/Task/Calendar---for-real-programmers/Vedit-macro-language/calendar---for-real-programmers.vedit deleted file mode 100644 index d621fe3a32..0000000000 --- a/Task/Calendar---for-real-programmers/Vedit-macro-language/calendar---for-real-programmers.vedit +++ /dev/null @@ -1,65 +0,0 @@ -BS(BF) -CFT(22) -#3 = 6 // NUMBER OF MONTHS PER LINE -#2 = 1969 // YEAR -#1 = 1 // STARTING MONTH -IC(' ', COUNT, #3*9) IT("[SNOOPY]") IN(2) -IC(' ', COUNT, #3*9+1) NI(#2) IN -REPEAT(12/#3) { - REPEAT (#3) { - BS(BF) - CALL("DRAW_CALENDAR") - RCB(10, 1, EOB_POS, COLSET, 1, 21) - BQ(OK) - #5 = CP - RI(10) - GP(#5) - EOL IC(9) - #1++ - } - EOF IN(2) -} -RETURN - -:DRAW_CALENDAR: -NUM_PUSH(4,20) -#20 = RF -BOF DC(ALL) - -NI(#1, LEFT+NOCR) IT("/1/") NI(#2, LEFT+NOCR) -RCB(#20, BOL_POS, EOL_POS, DELETE) -#10 = JDATE(@(#20)) - -#4 = #2+(#1==12) -NI(#1%12+1, LEFT+NOCR) IT("/1/") NI(#4, LEFT+NOCR) -RCB(#20, BOL_POS, CP, DELETE) -#11 = JDATE(@(#20)) - #10 -#7 = (#10-1) % 7 - -IF (#1==1) { RS(#20," JANUARY ") } -IF (#1==2) { RS(#20," FEBRUARY") } -IF (#1==3) { RS(#20," MARCH ") } -IF (#1==4) { RS(#20," APRIL ") } -IF (#1==5) { RS(#20," MAY ") } -IF (#1==6) { RS(#20," JUNE ") } -IF (#1==7) { RS(#20," JULY ") } -IF (#1==8) { RS(#20," AUGUST ") } -IF (#1==9) { RS(#20,"SEPTEMBER") } -IF (#1==10) { RS(#20," OCTOBER ") } -IF (#1==11) { RS(#20," NOVEMBER") } -IF (#1==12) { RS(#20," DECEMBER") } - -IT(" ") RI(#20) IN -IT(" MO TU WE TH FR SA SU") IN -IT(" --------------------") IN -IC(' ', COUNT, #7*3) -FOR (#8 = 1; #8 <= #11; #8++) { - NI(#8, COUNT, 3) - #5 = (#8+#10+5) % 7 - IF (#5 == 6) { IN } -} -IT(" ") - -REG_EMPTY(#20) -NUM_POP(4,20) -RETURN diff --git a/Task/Calendar---for-real-programmers/X86-Assembly/calendar---for-real-programmers.x86 b/Task/Calendar---for-real-programmers/X86-Assembly/calendar---for-real-programmers.x86 deleted file mode 100644 index b48eeae6ba..0000000000 --- a/Task/Calendar---for-real-programmers/X86-Assembly/calendar---for-real-programmers.x86 +++ /dev/null @@ -1,187 +0,0 @@ - .MODEL TINY - .CODE - .486 - ORG 100H ;.COM FILES START HERE -YEAR EQU 1969 ;DISPLAY CALENDAR FOR SPECIFIED YEAR -START: MOV CX, 61 ;SPACE(61); TEXT(0, "[SNOOPY]"); CRLF(0) - CALL SPACE - MOV DX, OFFSET SNOOPY - CALL TEXT - MOV CL, 63 ;SPACE(63); INTOUT(0, YEAR); CRLF(0); CRLF(0) - CALL SPACE - MOV AX, YEAR - CALL INTOUT - CALL CRLF - CALL CRLF - - MOV DI, 1 ;FOR MONTH:= 1 TO 12 DO DI=MONTH -L22: XOR SI, SI ; FOR COL:= 0 TO 6-1 DO SI=COL -L23: MOV CL, 5 ; SPACE(5) - CALL SPACE - MOV DX, DI ; TEXT(0, MONAME(MONTH+COL-1)); SPACE(7); - DEC DX ; DX:= (MONTH+COL-1)*10+MONAME - ADD DX, SI - IMUL DX, 10 - ADD DX, OFFSET MONAME - CALL TEXT - MOV CL, 7 - CALL SPACE - CMP SI, 5 ; IF COL<5 THEN SPACE(1); - JGE L24 - MOV CL, 1 - CALL SPACE - INC SI - JMP L23 -L24: CALL CRLF - - MOV SI, 6 ; FOR COL:= 0 TO 6-1 DO -L25: MOV DX, OFFSET SUMO ; TEXT(0, "SU MO TU WE TH FR SA"); - CALL TEXT - DEC SI ; IF COL<5 THEN SPACE(2); - JE L27 - MOV CL, 2 - CALL SPACE - JMP L25 -L27: CALL CRLF - - XOR SI, SI ;FOR COL:= 0 TO 6-1 DO -L28: MOV BX, DI ;DAY OF FIRST SUNDAY OF MONTH (CAN BE NEGATIVE) - ADD BX, SI ;DAY(COL):= 1 - WEEKDAY(YEAR, MONTH+COL, 1); - MOV BP, YEAR - -;DAY OF WEEK FOR FIRST DAY OF THE MONTH (0=SUN 1=MON..6=SAT) - CMP BL, 2 ;IF MONTH<=2 THEN - JG L3 - ADD BL, 12 ; MONTH:= MONTH+12; - DEC BP ; YEAR:= YEAR-1; -L3: -;REM((1-1 + (MONTH+1)*26/10 + YEAR + YEAR/4 + YEAR/100*6 + YEAR/400)/7) - INC BX ;MONTH - IMUL AX, BX, 26 - MOV CL, 10 - CWD - IDIV CX - MOV BX, AX - MOV AX, BP ;YEAR - ADD BX, AX - SHR AX, 2 - ADD BX, AX - MOV CL, 25 - CWD - IDIV CX - IMUL DX, AX, 6 ;YEAR/100*6 - ADD BX, DX - SHR AX, 2 ;YEAR/400 - ADD AX, BX - MOV CL, 7 - CWD - IDIV CX - NEG DX - INC DX - MOV [SI+DAY], DL ;COL+DAY - INC SI - CMP SI, 5 - JLE L28 - - MOV BP, 6 ;FOR LINE:= 0 TO 6-1 DO BP=LINE -L29: XOR SI, SI ; FOR COL:= 0 TO 6-1 DO SI=COL -L30: MOV BX, DI ; DAYMAX:= DAYS(MONTH+COL); - MOV BL, [BX+SI+DAYS] - -;IF MONTH+COL=2 & (REM(YEAR/4)=0 & REM(YEAR/100)#0 ! REM(YEAR/400)=0) THEN - MOV AX, DI ;MONTH - ADD AX, SI - CMP AL, 2 - JNE L32 - MOV AX, YEAR - TEST AL, 03H - JNE L32 - MOV CL,100 - CWD - IDIV CX - TEST DX, DX - JNE L31 - TEST AL, 03H - JNE L32 -L31: INC BX ;IF FEBRUARY AND LEAP YEAR THEN ADD A DAY -L32: - MOV DX, 7 ;FOR WEEKDAY:= 0 TO 7-1 DO -L33: MOVZX AX, [SI+DAY] ; IF DAY(COL)>=1 & DAY(COL)<=DAYMAX THEN - CMP AL, 1 - JL L34 - CMP AL, BL - JG L34 - CALL INTOUT ; INTOUT(0, DAY(COL)); - CMP AL, 10 ; IF DAY(COL)<10 THEN SPACE(1); LEFT JUSTIFY - JGE L36 - MOV CL, 1 - CALL SPACE - JMP L36 -L34: MOV CL, 2 ; ELSE SPACE(2); - CALL SPACE ; SUPPRESS OUT OF RANGE DAYS -L36: MOV CL, 1 ; SPACE(1); - CALL SPACE - INC BYTE PTR [SI+DAY] ; DAY(COL):= DAY(COL)+1; - DEC DX ;NEXT WEEKDAY - JNE L33 - - CMP SI, 5 ;IF COL<5 THEN SPACE(1); - JGE L37 - MOV CL, 1 - CALL SPACE - INC SI - JMP L30 -L37: CALL CRLF - - DEC BP ;NEXT LINE DOWN - JNE L29 - CALL CRLF - - ADD DI, 6 ;NEXT 6 MONTHS - CMP DI, 12 - JLE L22 - RET - -;DISPLAY POSITIVE INTEGER IN AX -INTOUT: PUSHA - MOV BX, 10 - XOR CX, CX -NO10: CWD - IDIV BX - PUSH DX - INC CX - TEST AX, AX - JNE NO10 -NO20: MOV AH, 02H - POP DX - ADD DL, '0' - INT 21H - LOOP NO20 - POPA - RET - -;DISPLAY CX SPACE CHARACTERS -SPACE: PUSHA -SP10: MOV AH, 02H - MOV DL, 20H - INT 21H - LOOP SP10 - POPA - RET - -;START A NEW LINE -CRLF: MOV DX, OFFSET LCRLF - -;DISPLAY STRING AT DX -TEXT: MOV AH, 09H - INT 21H - RET - -SNOOPY DB "[SNOOPY]" -LCRLF DB 0DH, 0AH, '$' -MONAME DB " JANUARY $ FEBRUARY$ MARCH $ APRIL $ MAY $ JUNE $" - DB " JULY $ AUGUST $SEPTEMBER$ OCTOBER$ NOVEMBER$ DECEMBER$" -SUMO DB "SU MO TU WE TH FR SA$" -DAYS DB 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 -DAY DB ?, ?, ?, ?, ?, ? - END START diff --git a/Task/Calendar/00DESCRIPTION b/Task/Calendar/00DESCRIPTION index 5dbca16812..d2722960ab 100644 --- a/Task/Calendar/00DESCRIPTION +++ b/Task/Calendar/00DESCRIPTION @@ -7,7 +7,7 @@ Choose one of the following devices: (Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.) -Kudos (κῦδος) for routines that also correctly transition from Julian to Gregorian calendar in September 1752. +Kudos (κῦδος) for routines that also transition from [https://en.wikipedia.org/wiki/Julian_calendar Julian] to [https://en.wikipedia.org/wiki/Gregorian_calendar Gregorian calendar]. This task is inspired by [http://www.ee.ryerson.ca/~elf/hack/realmen.html Real Programmers Don't Use PASCAL] by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT diff --git a/Task/Calendar/Gambas/calendar.gambas b/Task/Calendar/Gambas/calendar.gambas new file mode 100644 index 0000000000..650d6044c0 --- /dev/null +++ b/Task/Calendar/Gambas/calendar.gambas @@ -0,0 +1,5 @@ +Public Sub Main() + +Shell "cal 1969" + +End diff --git a/Task/Calendar/Kotlin/calendar.kotlin b/Task/Calendar/Kotlin/calendar.kotlin index 40e4f67d61..c147ae90b6 100644 --- a/Task/Calendar/Kotlin/calendar.kotlin +++ b/Task/Calendar/Kotlin/calendar.kotlin @@ -1,6 +1,9 @@ -import java.text.* -import java.util.* import java.io.PrintStream +import java.text.DateFormatSymbols +import java.text.MessageFormat +import java.util.Calendar +import java.util.GregorianCalendar +import java.util.Locale internal fun PrintStream.printCalendar(year: Int, nCols: Byte, locale: Locale?) { if (nCols < 1 || nCols > 12) @@ -34,7 +37,7 @@ internal fun PrintStream.printCalendar(year: Int, nCols: Byte, locale: Locale?) printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]") printf("%" + (w / 2 + 4) + "s%n%n", year) - for (r in 0..nRows - 1) { + for (r in 0 until nRows) { for (i in 0..7) { var c = r * nCols while (c < (r + 1) * nCols && c < 12) { diff --git a/Task/Calendar/Python/calendar.py b/Task/Calendar/Python/calendar.py index a302fade9d..46e1ea987f 100644 --- a/Task/Calendar/Python/calendar.py +++ b/Task/Calendar/Python/calendar.py @@ -41,7 +41,3 @@ Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31 - ->>> print('1234567890'*8) -12345678901234567890123456789012345678901234567890123456789012345678901234567890 ->>> diff --git a/Task/Calendar/REBOL/calendar.rebol b/Task/Calendar/REBOL/calendar.rebol new file mode 100644 index 0000000000..7b5c87f804 --- /dev/null +++ b/Task/Calendar/REBOL/calendar.rebol @@ -0,0 +1,12 @@ +do [if "" = y: ask "Year (ENTER for current):^/^/" [prin y: now/year] +foreach m system/locale/months [ + prin rejoin ["^/^/ " m "^/^/ "] + foreach day system/locale/days [prin join copy/part day 2 " "] + print "" f: to-date rejoin ["1-"m"-"y] loop f/weekday - 1 [prin " "] + repeat i 31 [ + if attempt [c: to-date rejoin [i"-"m"-"y]][ + prin join either 1 = length? form i [" "][" "] i + if c/weekday = 7 [print ""] + ] + ] +] ask "^/^/Press [ENTER] to Continue..."] diff --git a/Task/Calendar/Run-BASIC/calendar.run b/Task/Calendar/Run-BASIC/calendar.run deleted file mode 100644 index e97e7ff3d5..0000000000 --- a/Task/Calendar/Run-BASIC/calendar.run +++ /dev/null @@ -1,46 +0,0 @@ -input "Gimme a year";yr -cls ' clear screen -mths$ = "January,February,March,April,May,June,July,August,September,October,November,December" - -html "" -html "" - -for mm = 1 to 12 - gosub [getMonthInfo] - x = 0 - html "" - - if mm mod 4 = 0 then html "" ' 4 months across -next mm -html "

    Year:";yr;"

    " - html "" - - for i = 1 to mmDays + dow - if i > dow then x = x + 1 - if x = 0 then html "" else html "" - if (i mod 7) = 0 then html "" - next i - html "
    " - html " ";word$(mths$,mm,",") - html "
    SunMonTueWedThrFriSat
    ";x;"
    " -wait - -[getMonthInfo] -' ---------------------------------------- -' day of week when month begins. -' days in a month -' ---------------------------------------- -if yr < 100 then yr = val(date$("yy")) -if mm < 1 or mm > 12 then mm = val(date$("mm")) -dayOne$ = mm;"-01-";yr -n = date$(dayOne$) -dow = 1 + (n Mod 7) ' Day of Week month begins -m1 = mm -n1 = n + 27 -while m1 = mm - n1 = n1 + 1 - n$ = date$(n1) - m1 = val(left$(n$,2)) -wend -mmDays = n1 - n ' Days in Month -RETURN diff --git a/Task/Calendar/SPL/calendar.spl b/Task/Calendar/SPL/calendar.spl new file mode 100644 index 0000000000..271fd9d4c8 --- /dev/null +++ b/Task/Calendar/SPL/calendar.spl @@ -0,0 +1,37 @@ +year = 1969 +#.output(#.str(year,">68<")) +> row, 0..3 + > col, 1..3 + cal[col] = mcal(row*3+col,year) + size = #.size(cal[col],1) + < + > i, 1..8 + str = "" + > col, 1..3 + ? col>1, str += " " + line = "" + ? #.size(cal[col],1)!20<") + lines[2] = "Mo Tu We Th Fr Sa Su" + n = 3 + > i, 1..#.weekday(1,m,y)-1 + lines[n] += " " + < + > d, 1..days[m] + wd = #.weekday(d,m,y) + lines[n] += #.str(d,">2>") + ? wd<7, lines[n] += " " + ? wd=7, n += 1 + < + <= lines +. diff --git a/Task/Calendar/Sidef/calendar.sidef b/Task/Calendar/Sidef/calendar.sidef index 1445acdb80..a5f7cdfcea 100644 --- a/Task/Calendar/Sidef/calendar.sidef +++ b/Task/Calendar/Sidef/calendar.sidef @@ -8,16 +8,15 @@ func fmt_month (year, month) { var str = sprintf("%-20s\n", month_names[month-1]) str += week_day_names.join(' ')+"\n" - var dt = %s'DateTime' + var dt = %s var date = dt.new(year => year, month => month) var week_day = date.day_of_week - str += ([" "] * week_day-1 -> join(" ")) + str += (week_day-1 `of` " " -> join(" ")) var last_day = dt.last_day_of_month(year => year, month => month).day - for day in range(date.day, last_day) { + for day (date.day .. last_day) { date = dt.new(year => year, month => month, day => day) - - str += " " if (week_day ~~ range(2,7)) + str += " " if (week_day ~~ (2..7)) if (week_day == 8) { str += "\n" week_day = 1 @@ -26,17 +25,17 @@ func fmt_month (year, month) { ++week_day } str += " " if (week_day < 8) - str += ([" "] * 8-week_day -> join(" ")) + str += (8-week_day `of` " " -> join(" ")) str += "\n" } func fmt_year (year) { - var month_strs = 12.of { |i| fmt_month(year, i).lines } + var month_strs = 12.of {|i| fmt_month(year, i+1).lines } var str = (' '*30 + year + "\n") - for month in range(0, 11, months_per_col) { + for month (0..11 `by` months_per_col) { while (month_strs[month]) { - months_per_col.times { |i| + for i (1..months_per_col) { month_strs[month + i - 1] || next str += month_strs[month + i - 1].shift str += ' '*3 @@ -49,4 +48,4 @@ func fmt_year (year) { return str } -print fmt_year(ARGV.is_empty ? 1969 : ARGV[0].to_i) +print fmt_year(ARGV ? Number(ARGV[0]) : 1969) diff --git a/Task/Calendar/Zkl/calendar.zkl b/Task/Calendar/Zkl/calendar.zkl new file mode 100644 index 0000000000..6463ce1dd5 --- /dev/null +++ b/Task/Calendar/Zkl/calendar.zkl @@ -0,0 +1,26 @@ +var [const] D=Time.Date, days="Su Mo Tu We Th Fr Sa"; + +fcn center(text,m) { String(" "*((m-text.len())/2),text) } + +fcn oneMonth(year,month){ + day1:=D.zeller(year,month,1); //1969-1-1 -->3 (Wed, ISO 8601) + dayz:=D.daysInMonth(year,month); //1969-1 -->31 + List(center(D.monthNames[month],days.len()),days).extend( + (1).pump(dayz,(0).pump(day1,List,T(Void,""))).apply("%2s ".fmt) + .pump(List,T(Void.Read,days.len()/3,False),String.create)); +} + +const M=70; // mystery number +fcn oneYear(y=1969,title="3 Days of Peace & Music"){ + println(center(title,M),"\n",center(y.toString(),M),"\n"); + [1..12,3].pump(String,'wrap(m){ // 3 months per line + mmm:=(m).pump(3,List,oneMonth.fp(y)); //L(L(7-8 lines), L(...), L(...)) + if(mmm.apply("len").sum() % 3) // months have diff # of lines, pad + mmm=mmm.apply("append",""); + Utils.zipWith("%-25s%-25s%-25s\n".fmt, + mmm.xplode()).concat() + (if (m /* free() */ +#include /* strdup() */ +#include -module LibC - extend FFI::Library - ffi_lib FFI::Platform::LIBC +static VALUE +rc_strdup(VALUE obj, VALUE str_in) +{ + VALUE str_out; + char *c, *d; - attach_function :strdup, [:string], :pointer - attach_function :free, [:pointer], :void -end + /* + * Convert Ruby value to C string. May raise TypeError if the + * value isn't a string, or ArgumentError if it contains '\0'. + */ + c = StringValueCStr(str_in); -string = "Hello, World!" -duplicate = LibC.strdup(string) -puts duplicate.get_string(0) -LibC.free(duplicate) + /* Call strdup() and perhaps raise Errno::ENOMEM. */ + d = strdup(c); + if (d == NULL) + rb_sys_fail(NULL); + + /* Convert C string to Ruby string. */ + str_out = rb_str_new_cstr(d); + free(d); + return str_out; +} + +void +Init_rc_strdup(void) +{ + VALUE mRosettaCode = rb_define_module("RosettaCode"); + rb_define_module_function(mRosettaCode, "strdup", rc_strdup, 1); +} diff --git a/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-2.rb b/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-2.rb index 945e85b822..a898b24712 100644 --- a/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-2.rb +++ b/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-2.rb @@ -1,19 +1,3 @@ -require 'dl' -require 'fiddle' - -# Declare strdup(). -# * DL::Handle['strdup'] is the address of the function. -# * The function takes a pointer and returns a pointer. -strdup = Fiddle::Function.new(DL::Handle['strdup'], - [DL::TYPE_VOIDP], DL::TYPE_VOIDP) - -# Call strdup(). -# * Fiddle converts our Ruby string to a C string. -# * Fiddle returns a DL::CPtr. -duplicate = strdup.call("This is a string!") - -# DL::CPtr#to_s converts our C string to a Ruby string. -puts duplicate.to_s - -# We must call free(), because strdup() allocated memory. -DL.free duplicate +# extconf.rb +require 'mkmf' +create_makefile('rc_strdup') diff --git a/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-3.rb b/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-3.rb index 0ea7d3195e..5dbd9761a6 100644 --- a/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-3.rb +++ b/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-3.rb @@ -1,33 +1,3 @@ -require 'rubygems' -require 'inline' - -class InlineTester - def factorial_ruby(n) - (1..n).inject(1, :*) - end - - inline do |builder| - builder.c <<-'END_C' - long factorial_c(int max) { - long result = 1; - int i; - for (i = 1; i <= max; ++i) - result *= i; - return result; - } - END_C - end - - inline do |builder| - builder.include %q("math.h") - builder.c <<-'END_C' - int my_ilogb(double value) { - return ilogb(value); - } - END_C - end -end - -t = InlineTester.new -11.upto(14) {|n| p [n, t.factorial_ruby(n), t.factorial_c(n)]} -p t.my_ilogb(1000) +# demo.rb +require 'rc_strdup' +puts RosettaCode.strdup('This string gets duplicated.') diff --git a/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-4.rb b/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-4.rb new file mode 100644 index 0000000000..2f9d31de36 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-4.rb @@ -0,0 +1,14 @@ +require 'ffi' + +module LibC + extend FFI::Library + ffi_lib FFI::Platform::LIBC + + attach_function :strdup, [:string], :pointer + attach_function :free, [:pointer], :void +end + +string = "Hello, World!" +duplicate = LibC.strdup(string) +puts duplicate.get_string(0) +LibC.free(duplicate) diff --git a/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-5.rb b/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-5.rb new file mode 100644 index 0000000000..7d73f1fb8f --- /dev/null +++ b/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-5.rb @@ -0,0 +1,13 @@ +require 'fiddle' + +# Find strdup(). It takes a pointer and returns a pointer. +strdup = Fiddle::Function + .new(Fiddle::Handle['strdup'], + [Fiddle::TYPE_VOIDP], Fiddle::TYPE_VOIDP) + +# Call strdup(). +# - It converts our Ruby string to a C string. +# - It returns a Fiddle::Pointer. +duplicate = strdup.call("This is a string!") +puts duplicate.to_s # Convert the C string to a Ruby string. +Fiddle.free duplicate # free() the memory that strdup() allocated. diff --git a/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-6.rb b/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-6.rb new file mode 100644 index 0000000000..60101a145e --- /dev/null +++ b/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-6.rb @@ -0,0 +1,12 @@ +require 'fiddle' +require 'fiddle/import' + +module C + extend Fiddle::Importer + dlload Fiddle::Handle::DEFAULT + extern 'char *strdup(char *)' +end + +duplicate = C.strdup("This is a string!") +puts duplicate.to_s +Fiddle.free duplicate diff --git a/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-7.rb b/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-7.rb new file mode 100644 index 0000000000..0ea7d3195e --- /dev/null +++ b/Task/Call-a-foreign-language-function/Ruby/call-a-foreign-language-function-7.rb @@ -0,0 +1,33 @@ +require 'rubygems' +require 'inline' + +class InlineTester + def factorial_ruby(n) + (1..n).inject(1, :*) + end + + inline do |builder| + builder.c <<-'END_C' + long factorial_c(int max) { + long result = 1; + int i; + for (i = 1; i <= max; ++i) + result *= i; + return result; + } + END_C + end + + inline do |builder| + builder.include %q("math.h") + builder.c <<-'END_C' + int my_ilogb(double value) { + return ilogb(value); + } + END_C + end +end + +t = InlineTester.new +11.upto(14) {|n| p [n, t.factorial_ruby(n), t.factorial_c(n)]} +p t.my_ilogb(1000) diff --git a/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-1.stata b/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-1.stata new file mode 100644 index 0000000000..9f3b807cbd --- /dev/null +++ b/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-1.stata @@ -0,0 +1,14 @@ +#include +#include "stplugin.h" + +STDLL stata_call(int argc, char *argv[]) { + int i, j, n = strtol(argv[1], NULL, 0); + + for (i = 1; i <= n; i++) { + for (j = 1; j <= n; j++) { + // Don't forget array indices are 1-based in Stata. + SF_mat_store(argv[0], i, j, 1.0/(double)(i+j-1)); + } + } + return 0; +} diff --git a/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-2.stata b/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-2.stata new file mode 100644 index 0000000000..f2c5012148 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-2.stata @@ -0,0 +1,6 @@ +program hilbert + matrix define `1'=J(`2',`2',0) + plugin call hilbertmat, `1' `2' +end + +program hilbertmat, plugin diff --git a/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-3.stata b/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-3.stata new file mode 100644 index 0000000000..2a4218f12d --- /dev/null +++ b/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-3.stata @@ -0,0 +1,10 @@ +. hilbert mymat 4 + +. matrix list mymat + +symmetric mymat[4,4] + c1 c2 c3 c4 +r1 1 +r2 .5 .33333333 +r3 .33333333 .25 .2 +r4 .25 .2 .16666667 .14285714 diff --git a/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-4.stata b/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-4.stata new file mode 100644 index 0000000000..d42404376b --- /dev/null +++ b/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-4.stata @@ -0,0 +1,16 @@ +import com.stata.sfi.*; + +public class HilbertMatrix { + public static int run(String[] args) { + int n, i, j; + n = Integer.parseInt(args[1]); + Matrix.createMatrix(args[0], n, n, 0.0); + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + // Unlike Stata and the C API, indices are 0-based in the Java API. + Matrix.storeMatrixAt(args[0], i, j, 1.0/(double)(i+j+1)); + } + } + return 0; + } +} diff --git a/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-5.stata b/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-5.stata new file mode 100644 index 0000000000..0c860178d6 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-5.stata @@ -0,0 +1,10 @@ +. javacall HilbertMatrix run, classpath(K:\java) args(mymat 4) + +. matrix list mymat + +symmetric mymat[4,4] + c1 c2 c3 c4 +r1 1 +r2 .5 .33333333 +r3 .33333333 .25 .2 +r4 .25 .2 .16666667 .14285714 diff --git a/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-6.stata b/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-6.stata new file mode 100644 index 0000000000..17e1408e2e --- /dev/null +++ b/Task/Call-a-foreign-language-function/Stata/call-a-foreign-language-function-6.stata @@ -0,0 +1,9 @@ +. mata: Hilbert(4) +[symmetric] + 1 2 3 4 + +---------------------------------------------------------+ + 1 | 1 | + 2 | .5 .3333333333 | + 3 | .3333333333 .25 .2 | + 4 | .25 .2 .1666666667 .1428571429 | + +---------------------------------------------------------+ diff --git a/Task/Call-a-foreign-language-function/Zkl/call-a-foreign-language-function.zkl b/Task/Call-a-foreign-language-function/Zkl/call-a-foreign-language-function.zkl new file mode 100644 index 0000000000..54584b0e79 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Zkl/call-a-foreign-language-function.zkl @@ -0,0 +1,36 @@ +//-*-c-*- +// flf.c, Call a foreign-language function + +// export zklRoot=/home/ZKL +// clang -O -fPIC -I $zklRoot/VM -c -o flf.o flf.c +// clang flf.o -L$zklRoot/Lib -lzkl -shared -Wl,-soname,flf.so -o flf.so + +#include + +#include "zklObject.h" +#include "zklMethod.h" +#include "zklString.h" +#include "zklImports.h" + + // strlen(str) +static Instance *zkl_strlen(Instance *_,pArglist arglist,pVM vm) +{ + Instance *s = arglistGetString(arglist,0,"strlen",vm); + size_t sz = strlen(stringText(s)); + return intCreate(sz,vm); +} + +static int one; + +DllExport void *construct(void *vm) +{ + if (!vm) return (void *)ZKLX_PROTOCOL; // handshake + // If this is reloaded, nothing happens except + // construct() is called again so don't reinitialize + if (!one) // static items are zero + { + // do some one time initialization + one = 1; + } + return methodCreate(Void,0,zkl_strlen,vm); +} diff --git a/Task/Call-a-function-in-a-shared-library/00DESCRIPTION b/Task/Call-a-function-in-a-shared-library/00DESCRIPTION index d1064ca801..5db15f452d 100644 --- a/Task/Call-a-function-in-a-shared-library/00DESCRIPTION +++ b/Task/Call-a-function-in-a-shared-library/00DESCRIPTION @@ -2,5 +2,7 @@ Show how to call a function in a shared library (without dynamically linking to This is a special case of [[Call foreign language function|calling a foreign language function]] where the focus is close to the ABI level and not at the normal API level. -===Related tasks=== + +;Related task: * [[OpenGL]] -- OpenGL is usually maintained as a shared library. +

    diff --git a/Task/Call-a-function-in-a-shared-library/BaCon/call-a-function-in-a-shared-library.bacon b/Task/Call-a-function-in-a-shared-library/BaCon/call-a-function-in-a-shared-library.bacon new file mode 100644 index 0000000000..88f9710379 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/BaCon/call-a-function-in-a-shared-library.bacon @@ -0,0 +1,4 @@ +' Call a dynamic library function +PROTO j0 +bessel0 = j0(1.0) +PRINT bessel0 diff --git a/Task/Call-a-function-in-a-shared-library/Haskell/call-a-function-in-a-shared-library.hs b/Task/Call-a-function-in-a-shared-library/Haskell/call-a-function-in-a-shared-library.hs new file mode 100644 index 0000000000..38731878ac --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Haskell/call-a-function-in-a-shared-library.hs @@ -0,0 +1,41 @@ +#!/usr/bin/env stack +-- stack --resolver lts-6.33 --install-ghc runghc --package unix + +import Control.Exception ( try ) +import Foreign ( FunPtr, allocaBytes ) +import Foreign.C + ( CSize(..), CString, withCAStringLen, peekCAStringLen ) +import System.Info ( os ) +import System.IO.Error ( ioeGetErrorString ) +import System.IO.Unsafe ( unsafePerformIO ) +import System.Posix.DynamicLinker + ( RTLDFlags(RTLD_LAZY), dlsym, dlopen ) + +dlSuffix :: String +dlSuffix = if os == "darwin" then ".dylib" else ".so" + +type RevFun = CString -> CString -> CSize -> IO () + +foreign import ccall "dynamic" + mkFun :: FunPtr RevFun -> RevFun + +callRevFun :: RevFun -> String -> String +callRevFun f s = unsafePerformIO $ withCAStringLen s $ \(cs, len) -> do + allocaBytes len $ \buf -> do + f buf cs (fromIntegral len) + peekCAStringLen (buf, len) + +getReverse :: IO (String -> String) +getReverse = do + lib <- dlopen ("libcrypto" ++ dlSuffix) [RTLD_LAZY] + fun <- dlsym lib "BUF_reverse" + return $ callRevFun $ mkFun fun + +main = do + x <- try getReverse + let (msg, rev) = + case x of + Left e -> (ioeGetErrorString e ++ "; using fallback", reverse) + Right f -> ("Using BUF_reverse from OpenSSL", f) + putStrLn msg + putStrLn $ rev "a man a plan a canal panama" diff --git a/Task/Call-a-function-in-a-shared-library/Java/call-a-function-in-a-shared-library-1.java b/Task/Call-a-function-in-a-shared-library/Java/call-a-function-in-a-shared-library-1.java index 977e206151..288135925d 100644 --- a/Task/Call-a-function-in-a-shared-library/Java/call-a-function-in-a-shared-library-1.java +++ b/Task/Call-a-function-in-a-shared-library/Java/call-a-function-in-a-shared-library-1.java @@ -1,8 +1,71 @@ -public class LoadLib{ - private static native void functionInSharedLib(); //change return type or parameters as necessary +/* TrySort.java */ - public static void main(String[] args){ - System.loadLibrary("Path/to/library/here/lib.dll"); - functionInSharedLib(); - } +import java.util.Collections; +import java.util.Random; + +public class TrySort { + static boolean useC; + static { + try { + System.loadLibrary("TrySort"); + useC = true; + } catch(UnsatisfiedLinkError e) { + useC = false; + } + } + + static native void sortInC(int[] ary); + + static class IntList extends java.util.AbstractList { + int[] ary; + IntList(int[] ary) { this.ary = ary; } + public Integer get(int i) { return ary[i]; } + public Integer set(int i, Integer j) { + Integer o = ary[i]; ary[i] = j; return o; + } + public int size() { return ary.length; } + } + + static class ReverseAbsCmp + implements java.util.Comparator + { + public int compare(Integer pa, Integer pb) { + /* Order from highest to lowest absolute value. */ + int a = pa > 0 ? -pa : pa; + int b = pb > 0 ? -pb : pb; + return a < b ? -1 : a > b ? 1 : 0; + } + } + + static void sortInJava(int[] ary) { + Collections.sort(new IntList(ary), new ReverseAbsCmp()); + } + + public static void main(String[] args) { + /* Create an array of random integers. */ + int[] ary = new int[1000000]; + Random rng = new Random(); + for (int i = 0; i < ary.length; i++) + ary[i] = rng.nextInt(); + + /* Do the reverse sort. */ + if (useC) { + System.out.print("Sorting in C... "); + sortInC(ary); + } else { + System.out.print + ("Missing library for C! Sorting in Java... "); + sortInJava(ary); + } + + for (int i = 0; i < ary.length - 1; i++) { + int a = ary[i]; + int b = ary[i + 1]; + if ((a > 0 ? -a : a) > (b > 0 ? -b : b)) { + System.out.println("*BUG IN SORT*"); + System.exit(1); + } + } + System.out.println("ok"); + } } diff --git a/Task/Call-a-function-in-a-shared-library/Java/call-a-function-in-a-shared-library-2.java b/Task/Call-a-function-in-a-shared-library/Java/call-a-function-in-a-shared-library-2.java index c7f40b2785..a69b5bc017 100644 --- a/Task/Call-a-function-in-a-shared-library/Java/call-a-function-in-a-shared-library-2.java +++ b/Task/Call-a-function-in-a-shared-library/Java/call-a-function-in-a-shared-library-2.java @@ -1,15 +1,34 @@ -import com.sun.jna.Library; -import com.sun.jna.Native; +/* TrySort.c */ -public class LoadLibJNA{ - private interface YourSharedLibraryName extends Library{ - //put shared library functions here with no definition - public void sharedLibraryfunction(); - } +#include +#include "TrySort.h" - public static void main(String[] args){ - YourSharedLibraryName lib = (YourSharedLibraryName)Native.loadLibrary("sharedLibrary",//as in "sharedLibrary.dll" - YourSharedLibraryName.class); - lib.sharedLibraryFunction(); - } +static void fail(JNIEnv *jenv, const char *error_name) { + jclass error_class = (*jenv)->FindClass(jenv, error_name); + (*jenv)->ThrowNew(jenv, error_class, NULL); +} + +static int reverse_abs_cmp(const void *pa, const void *pb) { + jint a = *(jint *)pa; + jint b = *(jint *)pb; + a = a > 0 ? -a : a; + b = b > 0 ? -b : b; + return a < b ? -1 : a > b ? 1 : 0; +} + +void Java_TrySort_sortInC(JNIEnv *jenv, jclass obj, jintArray ary) { + jint *elem, length; + + if (ary == NULL) { + fail(jenv, "java/lang/NullPointerException"); + return; + } + length = (*jenv)->GetArrayLength(jenv, ary); + elem = (*jenv)->GetPrimitiveArrayCritical(jenv, ary, NULL); + if (elem == NULL) { + fail(jenv, "java/lang/OutOfMemoryError"); + return; + } + qsort(elem, length, sizeof(jint), reverse_abs_cmp); + (*jenv)->ReleasePrimitiveArrayCritical(jenv, ary, elem, 0); } diff --git a/Task/Call-a-function-in-a-shared-library/Java/call-a-function-in-a-shared-library-3.java b/Task/Call-a-function-in-a-shared-library/Java/call-a-function-in-a-shared-library-3.java new file mode 100644 index 0000000000..c25fd637f5 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Java/call-a-function-in-a-shared-library-3.java @@ -0,0 +1,27 @@ +# Makefile + +# Edit the next lines to match your JDK. +JAVA_HOME = /usr/local/jdk-1.8.0 +CPPFLAGS = -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/openbsd +JAVAC = $(JAVA_HOME)/bin/javac +JAVAH = $(JAVA_HOME)/bin/javah + +CC = cc +LDFLAGS = -shared -fPIC +LIB = libTrySort.so + +all: TrySort.class $(LIB) + +$(LIB): TrySort.c TrySort.h + $(CC) $(CPPFLAGS) $(LDFLAGS) -o $@ TrySort.c + +.SUFFIXES: .class .java .h +.class.h: + rm -f $@ + $(JAVAH) -jni -o $@ $(<:.class=) +.java.class: + $(JAVAC) $< + +clean: + rm -f TrySort.class TrySort?IntList.class \ + TrySort?ReverseAbsCmp.class TrySort.h $(LIB) diff --git a/Task/Call-a-function-in-a-shared-library/Java/call-a-function-in-a-shared-library-4.java b/Task/Call-a-function-in-a-shared-library/Java/call-a-function-in-a-shared-library-4.java new file mode 100644 index 0000000000..c7f40b2785 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Java/call-a-function-in-a-shared-library-4.java @@ -0,0 +1,15 @@ +import com.sun.jna.Library; +import com.sun.jna.Native; + +public class LoadLibJNA{ + private interface YourSharedLibraryName extends Library{ + //put shared library functions here with no definition + public void sharedLibraryfunction(); + } + + public static void main(String[] args){ + YourSharedLibraryName lib = (YourSharedLibraryName)Native.loadLibrary("sharedLibrary",//as in "sharedLibrary.dll" + YourSharedLibraryName.class); + lib.sharedLibraryFunction(); + } +} diff --git a/Task/Call-a-function-in-a-shared-library/Phix/call-a-function-in-a-shared-library.phix b/Task/Call-a-function-in-a-shared-library/Phix/call-a-function-in-a-shared-library.phix new file mode 100644 index 0000000000..70d04fd294 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Phix/call-a-function-in-a-shared-library.phix @@ -0,0 +1,8 @@ +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')}} +else + ?c_func(func,{'A'}) -- ('A'==65) +end if diff --git a/Task/Call-a-function-in-a-shared-library/Ruby/call-a-function-in-a-shared-library-1.rb b/Task/Call-a-function-in-a-shared-library/Ruby/call-a-function-in-a-shared-library-1.rb index f8fe6d9c5c..dd37ef681c 100644 --- a/Task/Call-a-function-in-a-shared-library/Ruby/call-a-function-in-a-shared-library-1.rb +++ b/Task/Call-a-function-in-a-shared-library/Ruby/call-a-function-in-a-shared-library-1.rb @@ -1,11 +1,20 @@ -require 'dl/import' +require 'fiddle/import' -FakeImgLib = DL.dlopen("/path/to/fakeimg.so") - -module FakeImage - def self.openimage filename - FakeImgLib["openimage", "IS"].call(filename)[0] +module FakeImgLib + extend Fiddle::Importer + begin + dlload './fakeimglib.so' + extern 'int openimage(const char *)' + rescue Fiddle::DLError + # Either fakeimglib or openimage() is missing. + @@handle = -1 + def openimage(path) + $stderr.puts "internal openimage opens #{path}\n" + @@handle += 1 + end + module_function :openimage end end -handle = FakeImage.openimage("path/to/image") +handle = FakeImgLib.openimage("path/to/image") +puts "opened with handle #{handle}" diff --git a/Task/Call-a-function-in-a-shared-library/Ruby/call-a-function-in-a-shared-library-2.rb b/Task/Call-a-function-in-a-shared-library/Ruby/call-a-function-in-a-shared-library-2.rb index 8e46956994..fa325300a4 100644 --- a/Task/Call-a-function-in-a-shared-library/Ruby/call-a-function-in-a-shared-library-2.rb +++ b/Task/Call-a-function-in-a-shared-library/Ruby/call-a-function-in-a-shared-library-2.rb @@ -1,8 +1,72 @@ -require 'ffi' -module FakeImgLib - extend FFI::Library - ffi_lib "path/to/fakeimglib.so" - attach_function :openimage, [:string], :int +# This script shows the width x height of some images. +# Example: +# $ ruby imsize.rb dwarf-vs-elf.png swedish-chef.jpg +# dwarf-vs-elf.png: 242x176 +# swedish-chef.jpg: 256x256 + +begin + require 'rmagick' + lib = :rmagick +rescue LoadError + # Missing rmagick. Try ffi. + begin + require 'ffi' + module F + extend FFI::Library + ffi_lib 'MagickWand-6.Q16' + attach_function :DestroyMagickWand, [:pointer], :pointer + attach_function :MagickGetImageHeight, [:pointer], :size_t + attach_function :MagickGetImageWidth, [:pointer], :size_t + attach_function :MagickPingImage, [:pointer, :string], :bool + attach_function :MagickWandGenesis, [], :void + attach_function :NewMagickWand, [], :pointer + end + lib = :ffi + rescue LoadError + # Missing ffi, MagickWand lib, or function in lib. + end end -handle = FakeImgLib.openimage("path/to/image") +case lib +when :rmagick + # Returns [width, height] of an image file. + def size(path) + img = Magick::Image.ping(path).first + [img.columns, img.rows] + end +when :ffi + F.MagickWandGenesis() + def size(path) + wand = F.NewMagickWand() + F.MagickPingImage(wand, path) or fail 'problem reading image' + [F.MagickGetImageWidth(wand), F.MagickGetImageHeight(wand)] + ensure + F.DestroyMagickWand(wand) if wand + end +else + PngSignature = "\x89PNG\r\n\x1A\n".force_encoding('binary') + def size(path) + File.open(path, 'rb') do |file| + # Only works with PNG: https://www.w3.org/TR/PNG/ + # Reads [width, height] from IDHR chunk. + # Checks height != nil, but doesn't check CRC of chunk. + sig, width, height = file.read(24).unpack('a8@16NN') + sig == PngSignature and height or fail 'not a PNG image' + [width, height] + end + end +end + +# Show the size of each image in ARGV. +status = true +ARGV.empty? and (warn "usage: $0 file..."; exit false) +ARGV.each do |path| + begin + r, c = size(path) + puts "#{path}: #{r}x#{c}" + rescue + status = false + puts "#{path}: #$!" + end +end +exit status diff --git a/Task/Call-a-function-in-a-shared-library/Rust/call-a-function-in-a-shared-library.rust b/Task/Call-a-function-in-a-shared-library/Rust/call-a-function-in-a-shared-library.rust new file mode 100644 index 0000000000..6e2157f5e8 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Rust/call-a-function-in-a-shared-library.rust @@ -0,0 +1,38 @@ +#![allow(unused_unsafe)] +extern crate libc; + +use std::io::{self,Write}; +use std::{mem,ffi,process}; + +use libc::{c_double, RTLD_NOW}; + +// Small macro which wraps turning a string-literal into a c-string. +// This is always safe to call, and the resulting pointer has 'static lifetime +macro_rules! to_cstr { + ($s:expr) => {unsafe {ffi::CStr::from_bytes_with_nul_unchecked(concat!($s, "\0").as_bytes()).as_ptr()}} +} + +macro_rules! from_cstr { + ($p:expr) => {ffi::CStr::from_ptr($p).to_string_lossy().as_ref() } +} + +fn main() { + unsafe { + let handle = libc::dlopen(to_cstr!("libm.so.6"), RTLD_NOW); + + if handle.is_null() { + writeln!(&mut io::stderr(), "{}", from_cstr!(libc::dlerror())).unwrap(); + process::exit(1); + } + + let extern_cos = libc::dlsym(handle, to_cstr!("cos")) + .as_ref() + .map(mem::transmute::<_,fn (c_double) -> c_double) + .unwrap_or(builtin_cos); + println!("{}", extern_cos(4.0)); + } +} + +fn builtin_cos(x: c_double) -> c_double { + x.cos() +} diff --git a/Task/Call-a-function-in-a-shared-library/Zkl/call-a-function-in-a-shared-library.zkl b/Task/Call-a-function-in-a-shared-library/Zkl/call-a-function-in-a-shared-library.zkl new file mode 100644 index 0000000000..71aae56d1a --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Zkl/call-a-function-in-a-shared-library.zkl @@ -0,0 +1,2 @@ +var BN=Import("zklBigNum"); +BN(1)+2 //--> BN(3) diff --git a/Task/Call-a-function/360-Assembly/call-a-function-1.360 b/Task/Call-a-function/360-Assembly/call-a-function-1.360 new file mode 100644 index 0000000000..e93e82d636 --- /dev/null +++ b/Task/Call-a-function/360-Assembly/call-a-function-1.360 @@ -0,0 +1,3 @@ +X DS F +Y DS F +Z DS F diff --git a/Task/Call-a-function/360-Assembly/call-a-function-2.360 b/Task/Call-a-function/360-Assembly/call-a-function-2.360 new file mode 100644 index 0000000000..a531b3f9b8 --- /dev/null +++ b/Task/Call-a-function/360-Assembly/call-a-function-2.360 @@ -0,0 +1,7 @@ + L R15,=V(MULTPLIC) + LA R1,PARMLIST address of the paramter list + BALR R14,R15 branch and link + ST R0,Z Z=MULTPLIC(X,Y) +* ... +PARMLIST DC A(X) + DC A(Y) diff --git a/Task/Call-a-function/360-Assembly/call-a-function-3.360 b/Task/Call-a-function/360-Assembly/call-a-function-3.360 new file mode 100644 index 0000000000..f7d52c3418 --- /dev/null +++ b/Task/Call-a-function/360-Assembly/call-a-function-3.360 @@ -0,0 +1,2 @@ + CALL MULTPLIC,(X,Y) call MULTPLIC(X,Y) + ST R0,Z Z=MULTPLIC(X,Y) diff --git a/Task/Call-a-function/360-Assembly/call-a-function-4.360 b/Task/Call-a-function/360-Assembly/call-a-function-4.360 new file mode 100644 index 0000000000..333bc1da59 --- /dev/null +++ b/Task/Call-a-function/360-Assembly/call-a-function-4.360 @@ -0,0 +1,4 @@ + LOAD EP=MULTPLIC load load-module + LR R15,R0 retrieve entry address + CALL (R15),(X,Y) call MULTPLIC(X,Y) + ST R0,Z Z=MULTPLIC(X,Y) diff --git a/Task/Call-a-function/ALGOL-68/call-a-function.alg b/Task/Call-a-function/ALGOL-68/call-a-function.alg index 7792840557..d8e1bcf479 100644 --- a/Task/Call-a-function/ALGOL-68/call-a-function.alg +++ b/Task/Call-a-function/ALGOL-68/call-a-function.alg @@ -1,21 +1,31 @@ -# A function without arguments: # -f(); -# or # +# Note functions and subroutines are called procedures (or PROCs) in Algol 68 # +# A function called without arguments: # f; - +# Algol 68 does not expect an empty parameter list for calls with no arguments, "f()" is a syntax error # # A function with a fixed number of arguments: # f(1, x); -# ALGOL 68 does not support optional arguments, variable numbers of arguments, or named -arguments. -However, some functions may take an argument "0" as an instruction to use the default value -(sort of a pseudo-optional argument). # +# variable number of arguments: # +# functions that accept an array as a parameter can effectively provide variable numbers of arguments # +# a "literal array" (called a row-display in Algol 68) can be passed, as is often the case for the I/O # +# functions - e.g.: # +print( ( "the result is: ", r, " after ", n, " iterations", newline ) ); +# the outer brackets indicate the parameters of print, the inner brackets indicates the contents are a "literal array" # + +# ALGOL 68 does not support optional arguments, though in some cases an empty array could be passed to a function # +# expecting an array, e.g.: # +f( () ); + +# named arguments - see the Algol 68 sample in: http://rosettacode.org/wiki/Named_parameters # # In "Talk:Call a function" a statement context is explained as "The function is used as an instruction (with a void context), -rather than used within an expression." Based on that, -both ALGOL examples above are already in a statement context. -For full ALGOL compatibility, though, they should be in the form "VOID (f ());" # +rather than used within an expression." +Based on that, the examples above are already in a statement context. +Technically, when a function that returns other than VOID (i.e. is not a subroutine) +is called in a statement context, the result of the call is "voided" i.e. discarded. +If desired, this can be made explicit using a cast, e.g.: # +VOID(f); # A function's return value being used: # x := f(y); @@ -26,3 +36,4 @@ x := f(y); # If the function is declared with argument(s) of mode REF MODE, then those arguments are being passed by reference. # +# Technically, all parameters are passed by value, however the value of a REF MODE is a reference... # diff --git a/Task/Call-a-function/ALGOL-W/call-a-function.alg b/Task/Call-a-function/ALGOL-W/call-a-function.alg new file mode 100644 index 0000000000..b07adf4632 --- /dev/null +++ b/Task/Call-a-function/ALGOL-W/call-a-function.alg @@ -0,0 +1,38 @@ +% Note, in Algol W, functions are called procedures % +% calling a function with no parameters: % +f; + +% calling a function with a fixed number of parameters % +g( 1, 2.3, "4" ); + +% Algol W does not support optional parameters in general, however constructors for records can % +% be called wither with parameters (one for each field in the record) or no parameters # + +% Algol W does not support variable numbers of parameters, except for the built-in I/O functions # +% Algol W does not support named arguments % + +% A function can be used in a statement context by calling it, as in the examples above % + +% First class context: A function can be passed as a parameter to another procedure, e.g.: % +v := integrate( sin, 0, 1 ) +% assuming a suitable definition of integrate % +% Algol W does not support functions returning functions % + +% obtaining the return value of a function: e.g.: % +v := g( x, y, z ); + +% There is no syntactic distinction between user-defined and built-in functions % + +% Subroutines and functions are both procedures, a subroutine is a procedure with no return type % +% (called a proper procedure in Algol W) % +% There is no syntactic distinction between a call to a function and a call to a subroutine % +% other than the context % + +% In Algol W, parameters are passed by value, result or value result. This must be stated in the % +% definition of the function/subroutine. Value parameters are passed by value, result and value result % +% are effectively passed by reference and assigned on function exit. Result parameters are "out" parameters % +% and value result parameters are "in out". % +% Algol W also has "name" parameters (not to be confused with named parameters). Functions with name % +% parameters are somewhat like macros % + +% Partial application is not possible in Algol W % diff --git a/Task/Call-a-function/C-sharp/call-a-function.cs b/Task/Call-a-function/C-sharp/call-a-function.cs new file mode 100644 index 0000000000..fedc3cd159 --- /dev/null +++ b/Task/Call-a-function/C-sharp/call-a-function.cs @@ -0,0 +1,30 @@ +/* a function that has no argument */ + public int MyFunction(); + + /* a function with a fixed number of arguments */ + FunctionWithArguments(4, 3, 2); + + /* a function with optional arguments */ + public void OptArg(); + + public static void Main() + { + OptArg(1); + OptArg(1, 2); + OptArg(1, 2, 3); + } + public void ExampleMethod(int required, + string optionalstr = "default string", + int optionalint = 10) + /* If you know the first and the last parameter */ + ExampleMethod(3, optionalint: 4); + + /* If you know all the parameter */ + ExampleMethod(3, "Hello World", 4); + + /* Variable number of arguments use array */ + public static void UseVariableParameters(params int[] list) + + /* Obtain return value from function */ + public internal MyFunction(); + int returnValue = MyFunction(); diff --git a/Task/Call-a-function/Gambas/call-a-function.gambas b/Task/Call-a-function/Gambas/call-a-function.gambas new file mode 100644 index 0000000000..3eed3cc0c9 --- /dev/null +++ b/Task/Call-a-function/Gambas/call-a-function.gambas @@ -0,0 +1,25 @@ +Public Sub Main() + +Hello +Print CopyIt("Hello ", 6) +Print CopyIt("Hello ", 3, "!!") + +End +'_____________________________________________________________________________________ +Public Sub CopyIt(sString As String, siNo As Short, Optional sEnd As String) As String +Dim siCount As Short +Dim sNewString As String + +For siCount = 1 To siNo + sNewString &= sString +Next + +Return Trim(sNewString) & sEnd + +End +'_____________________________________________________________________________________ +Public Sub Hello() + +Print "Hello world!" + +End diff --git a/Task/Call-a-function/Kotlin/call-a-function.kotlin b/Task/Call-a-function/Kotlin/call-a-function.kotlin new file mode 100644 index 0000000000..f33e1de745 --- /dev/null +++ b/Task/Call-a-function/Kotlin/call-a-function.kotlin @@ -0,0 +1,33 @@ +// version 1.0.6 + +fun fun1() = println("No arguments") + +fun fun2(i: Int) = println("One argument = $i") + +fun fun3(i: Int, j: Int = 0) = println("One required argument = $i, one optional argument = $j") + +fun fun4(vararg v: Int) = println("Variable number of arguments = ${v.asList()}") + +fun fun5(i: Int) = i * i + +fun fun6(i: Int, f: (Int) -> Int) = f(i) + +fun fun7(i: Int): Double = i / 2.0 + +fun fun8(x: String) = { y: String -> x + " " + y } + +fun main(args: Array) { + fun1() // no arguments + fun2(2) // fixed number of arguments, one here + fun3(3) // optional argument, default value used here + fun4(4, 5, 6) // variable number of arguments + fun3(j = 8, i = 7) // using named arguments, order unimportant + val b = false + if (b) fun1() else fun2(9) // statement context + println(1 + fun6(4, ::fun5) + 3) // first class context within an expression + println(fun5(5)) // obtaining return value + println(Math.round(2.5)) // no distinction between built-in and user-defined functions, though former usually have a receiver + fun1() // calling sub-routine which has a Unit return type by default + println(fun7(11)) // calling function with a return type of Double (here explicit but can be implicit) + println(fun8("Hello")("world")) // partial application isn't supported though you can do this +} diff --git a/Task/Call-a-function/Ol/call-a-function.ol b/Task/Call-a-function/Ol/call-a-function.ol new file mode 100644 index 0000000000..d90a250a11 --- /dev/null +++ b/Task/Call-a-function/Ol/call-a-function.ol @@ -0,0 +1,119 @@ +; note: sign "==>" indicates expected output + +;;; Calling a function that requires no arguments +(define (no-args-function) + (print "ok.")) +) + +(no-args-function) +; ==> ok. + + +;;; Calling a function with a fixed number of arguments +(define (two-args-function a b) + (print "a: " a) + (print "b: " b)) +) + +(two-args-function 8 13) +; ==> a: 8 +; ==> b: 13 + + +;;; Calling a function with optional arguments +(define (optional-args-function a . args) + (print "a: " a) + (if (null? args) + (print "no optional arguments")) + (if (less? 0 (length args)) + (print "b: " (car args))) + (if (less? 1 (length args)) + (print "c: " (cadr args))) + ; etc. +) + +(optional-args-function 3) +; ==> a: 3 +; ==> no optional arguments +(optional-args-function 3 8) +; ==> a: 3 +; ==> b: 8 +(optional-args-function 3 8 13) +; ==> a: 3 +; ==> b: 8 +; ==> c: 13 +(optional-args-function 3 8 13 77) +; ==> a: 3 +; ==> b: 8 +; ==> c: 13 + + +;;; Calling a function with a variable number of arguments +; /same as optional arguments + + +;;; Calling a function with named arguments +; /no named arguments "from the box" provided, but it can be simulated using builtin maps (named "ff") +(define (named-args-function args) + (print "a: " (get args 'a 8)) + (print "b: " (get args 'b 13)) +) + +(named-args-function #empty) +; ==> a: 8 +; ==> b: 13 +(named-args-function (list->ff '((a . 3)))) +; ==> a: 3 +; ==> b: 13 +(named-args-function (list->ff '((b . 7)))) +; ==> a: 8 +; ==> b: 7 +(named-args-function (list->ff '((a . 3) (b . 7)))) +; ==> a: 3 +; ==> b: 7 + + +;;; Using a function in first-class context within an expression +(define (first-class-arg-function arg a b) + (print (arg a b)) +) + +(first-class-arg-function + 2 3) +; ==> 5 +(first-class-arg-function - 2 3) +; ==> -1 + + +;;; Obtaining the return value of a function +(define (return-value-function) + (print "ok.") + 123) + +(let ((result (return-value-function))) + (print result)) +; ==> ok. +; ==> 123 +; actually + + +;;; Is partial application possible and how +(define (make-partial-function n) + (lambda (x y) + (print (n x y))) +) + +(define plus (make-partial-function +)) +(plus 2 3) +; ==> 5 +(define minus (make-partial-function -)) +(minus 2 3) +; ==> -1 + + +; TBD: +;;; Using a function in statement context +;;; Using a function in first-class context within an expression +;;; Obtaining the return value of a function +;;; Distinguishing built-in functions and user-defined functions +;;; Distinguishing subroutines and functions +;;; Stating whether arguments are passed by value or by reference diff --git a/Task/Call-a-function/Zkl/call-a-function-1.zkl b/Task/Call-a-function/Zkl/call-a-function-1.zkl new file mode 100644 index 0000000000..0884e5dd9f --- /dev/null +++ b/Task/Call-a-function/Zkl/call-a-function-1.zkl @@ -0,0 +1,10 @@ +f(); f(1,2,3,4); +fcn f(a=1){}() // define and call f, which gets a set to 1 +fcn{vm.arglist}(1,2,3,4) // arglist is L(1,2,3,4) +fcn{a1:=vm.nthArg(1)}(1,2,3) // a1 == 2 +(f() == True); (f() and 1 or 2) +if (f()) println() +f(f) // pass f to itself +s:=f() +fcn{}.isType(self.fcn) //True +fcn{}.len.isType(self.fcn) //False, len is a Method diff --git a/Task/Call-a-function/Zkl/call-a-function-2.zkl b/Task/Call-a-function/Zkl/call-a-function-2.zkl new file mode 100644 index 0000000000..042f4636f2 --- /dev/null +++ b/Task/Call-a-function/Zkl/call-a-function-2.zkl @@ -0,0 +1,10 @@ +fcn(a,b,c).fp(1)() // call function with a always set to 1 +fcn(a,b,c).fp1(2,3)() // call function with b & c always set to 2 & 3 +fcn(a,b,c,d).fpN(3,5)() // call function with d always set to 5 +fcn{vm.arglist}.fpN(3,66)(1,2,3,4,5) //-->L(1,2,3,66,4,5) +fcn{}.fpM("01-",5) // use a mask to select parameters + // 1 is supplied, 0 is get upon call, - is chop arglist +fcn{vm.arglist}.fpM("01-",66)(1,2,3,4) //-->L(1,66) + +a:=5; f('wrap(b){a+b}) // 'wrap is syntactic sugar for .fpN + // to create a lexical closure --> f(fcn(b,a){a+b}.fpN(1,a)) diff --git a/Task/Call-an-object-method/Common-Lisp/call-an-object-method.lisp b/Task/Call-an-object-method/Common-Lisp/call-an-object-method.lisp new file mode 100644 index 0000000000..fea7f21f7c --- /dev/null +++ b/Task/Call-an-object-method/Common-Lisp/call-an-object-method.lisp @@ -0,0 +1,17 @@ +(defclass my-class () + ((x + :accessor get-x ;; getter function + :initarg :x ;; arg name + :initform 0))) ;; initial value + +;; declaring a public class method +(defmethod square-x ((class-instance my-class)) + (* (get-x class-instance) (get-x class-instance))) + +;; create an instance of my-class +(defvar *instance* + (make-instance 'my-class :x 10)) + +(format t "Value of x: ~a~%" (get-x *instance*)) + +(format t "Value of x^2: ~a~%" (square-x *instance*)) diff --git a/Task/Call-an-object-method/Elena/call-an-object-method-1.elena b/Task/Call-an-object-method/Elena/call-an-object-method-1.elena index 97444b7886..9bf9c893a1 100644 --- a/Task/Call-an-object-method/Elena/call-an-object-method-1.elena +++ b/Task/Call-an-object-method/Elena/call-an-object-method-1.elena @@ -1 +1 @@ - instance message:param1:param2. + console printLine("Hello"," ","World!"). diff --git a/Task/Call-an-object-method/Elena/call-an-object-method-2.elena b/Task/Call-an-object-method/Elena/call-an-object-method-2.elena index 863f48823c..89960452a2 100644 --- a/Task/Call-an-object-method/Elena/call-an-object-method-2.elena +++ b/Task/Call-an-object-method/Elena/call-an-object-method-2.elena @@ -1 +1 @@ - instance message &subj1:param1 &subj2:param2. + console write literal:(console readLiteral). diff --git a/Task/Call-an-object-method/Elena/call-an-object-method-3.elena b/Task/Call-an-object-method/Elena/call-an-object-method-3.elena new file mode 100644 index 0000000000..4eb8814244 --- /dev/null +++ b/Task/Call-an-object-method/Elena/call-an-object-method-3.elena @@ -0,0 +1 @@ + console write literal(console readLiteral). diff --git a/Task/Call-an-object-method/Go/call-an-object-method-4.go b/Task/Call-an-object-method/Go/call-an-object-method-4.go index 4a825cfda1..a874f5c2b9 100644 --- a/Task/Call-an-object-method/Go/call-an-object-method-4.go +++ b/Task/Call-an-object-method/Go/call-an-object-method-4.go @@ -1,10 +1,10 @@ procedure main() - foo_m1() # equivalent of class method, not normally used bar := foo() # create instance - bar.m2() # call method m2 with self=bar -end + bar.m2() # call method m2 with self=bar, an implicit first parameter + foo_m1( , "param1", "param2") # equivalent of static class method, first (self) parameter is null +end class foo(cp1,cp2) method m1(m1p1,m1p2) diff --git a/Task/Call-an-object-method/Kotlin/call-an-object-method.kotlin b/Task/Call-an-object-method/Kotlin/call-an-object-method.kotlin new file mode 100644 index 0000000000..2802cc35d7 --- /dev/null +++ b/Task/Call-an-object-method/Kotlin/call-an-object-method.kotlin @@ -0,0 +1,13 @@ +class MyClass { + fun instanceMethod(s: String) = println(s) + + companion object { + fun staticMethod(s: String) = println(s) + } +} + +fun main(args: Array) { + val mc = MyClass() + mc.instanceMethod("Hello instance world!") + MyClass.staticMethod("Hello static world!") +} diff --git a/Task/Call-an-object-method/OASYS-Assembler/call-an-object-method.oasys b/Task/Call-an-object-method/OASYS-Assembler/call-an-object-method.oasys new file mode 100644 index 0000000000..510d48e63e --- /dev/null +++ b/Task/Call-an-object-method/OASYS-Assembler/call-an-object-method.oasys @@ -0,0 +1 @@ ++&GO diff --git a/Task/Call-an-object-method/OoRexx/call-an-object-method.rexx b/Task/Call-an-object-method/OoRexx/call-an-object-method.rexx new file mode 100644 index 0000000000..d8ac918ed5 --- /dev/null +++ b/Task/Call-an-object-method/OoRexx/call-an-object-method.rexx @@ -0,0 +1,30 @@ +say "pi:" .circle~pi +c=.circle~new(1) +say "c~area:" c~area +Do r=2 To 10 + c.r=.circle~new(r) + End +say .circle~instances('') 'circles were created' + +::class circle +::method pi class -- a class method + return 3.14159265358979323 + +::method instances class -- another class method + expose in + use arg a + If datatype(in)<>'NUM' Then in=0 + If a<>'' Then + in+=1 + Return in + +::method init + expose radius + use arg radius + self~class~instances('x') + +::method area -- an instance method + expose radius + Say self~class + Say self + return self~class~pi * radius * radius diff --git a/Task/Call-an-object-method/Zkl/call-an-object-method.zkl b/Task/Call-an-object-method/Zkl/call-an-object-method.zkl new file mode 100644 index 0000000000..dad0e59624 --- /dev/null +++ b/Task/Call-an-object-method/Zkl/call-an-object-method.zkl @@ -0,0 +1,11 @@ +class C{var v; fcn f{v}} +C.f() // call function f in class C +C.v=5; c2:=C(); // create new instance of C +println(C.f()," ",c2.f()) //-->5 Void +C.f.isStatic //--> False + +class [static] D{var v=123; fcn f{v}} +D.f(); D().f(); // both return 123 +D.f.isStatic //-->False + +class E{var v; fcn f{}} E.f.isStatic //-->True diff --git a/Task/Canny-edge-detector/Python/canny-edge-detector.py b/Task/Canny-edge-detector/Python/canny-edge-detector.py new file mode 100644 index 0000000000..e3c9a58861 --- /dev/null +++ b/Task/Canny-edge-detector/Python/canny-edge-detector.py @@ -0,0 +1,86 @@ +#!/bin/python +import numpy as np +from scipy.ndimage.filters import convolve, gaussian_filter +from scipy.misc import imread, imshow + +def CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31): + im = np.array(im, dtype=float) #Convert to float to prevent clipping values + + #Gaussian blur to reduce noise + im2 = gaussian_filter(im, blur) + + #Use sobel filters to get horizontal and vertical gradients + im3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]]) + im3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]]) + + #Get gradient and direction + grad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5) + theta = np.arctan2(im3v, im3h) + thetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 #Quantize direction + + #Non-maximum suppression + gradSup = grad.copy() + for r in range(im.shape[0]): + for c in range(im.shape[1]): + #Suppress pixels at the image edge + if r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1: + gradSup[r, c] = 0 + continue + tq = thetaQ[r, c] % 4 + + if tq == 0: #0 is E-W (horizontal) + if grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]: + gradSup[r, c] = 0 + if tq == 1: #1 is NE-SW + if grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]: + gradSup[r, c] = 0 + if tq == 2: #2 is N-S (vertical) + if grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]: + gradSup[r, c] = 0 + if tq == 3: #3 is NW-SE + if grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]: + gradSup[r, c] = 0 + + #Double threshold + strongEdges = (gradSup > highThreshold) + + #Strong has value 2, weak has value 1 + thresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold) + + #Tracing edges with hysteresis + #Find weak edge pixels near strong edge pixels + finalEdges = strongEdges.copy() + currentPixels = [] + for r in range(1, im.shape[0]-1): + for c in range(1, im.shape[1]-1): + if thresholdedEdges[r, c] != 1: + continue #Not a weak pixel + + #Get 3x3 patch + localPatch = thresholdedEdges[r-1:r+2,c-1:c+2] + patchMax = localPatch.max() + if patchMax == 2: + currentPixels.append((r, c)) + finalEdges[r, c] = 1 + + #Extend strong edges based on current pixels + while len(currentPixels) > 0: + newPix = [] + for r, c in currentPixels: + for dr in range(-1, 2): + for dc in range(-1, 2): + if dr == 0 and dc == 0: continue + r2 = r+dr + c2 = c+dc + if thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0: + #Copy this weak pixel to final result + newPix.append((r2, c2)) + finalEdges[r2, c2] = 1 + currentPixels = newPix + + return finalEdges + +if __name__=="__main__": + im = imread("test.jpg", mode="L") #Open image, convert to greyscale + finalEdges = CannyEdgeDetector(im) + imshow(finalEdges) diff --git a/Task/Carmichael-3-strong-pseudoprimes/Clojure/carmichael-3-strong-pseudoprimes.clj b/Task/Carmichael-3-strong-pseudoprimes/Clojure/carmichael-3-strong-pseudoprimes.clj new file mode 100644 index 0000000000..4e024b83e2 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Clojure/carmichael-3-strong-pseudoprimes.clj @@ -0,0 +1,27 @@ +(ns example + (:gen-class)) + +(defn prime? [n] + " Prime number test (using Java) " + (.isProbablePrime (biginteger n) 16)) + +(defn carmichael [p1] + " Triplets of Carmichael primes, with first element prime p1 " + (if (prime? p1) + (into [] (for [h3 (range 2 p1) + :let [g (+ h3 p1)] + d (range 1 g) + :when (and (= (mod (* g (dec p1)) d) 0) + (= (mod (- (* p1 p1)) h3) (mod d h3))) + :let [p2 (inc (quot (* (dec p1) g) d))] + :when (prime? p2) + :let [p3 (inc (quot (* p1 p2) h3))] + :when (prime? p3) + :when (= (mod (* p2 p3) (dec p1)) 1)] + [p1 p2 p3])))) + +; Generate Result +(def numbers (mapcat carmichael (range 2 62))) +(println (count numbers) "Carmichael numbers found:") +(doseq [t numbers] + (println (format "%5d x %5d x %5d = %10d" (first t) (second t) (last t) (apply * t)))) diff --git a/Task/Carmichael-3-strong-pseudoprimes/Kotlin/carmichael-3-strong-pseudoprimes.kotlin b/Task/Carmichael-3-strong-pseudoprimes/Kotlin/carmichael-3-strong-pseudoprimes.kotlin index be138b0952..40d59e6c43 100644 --- a/Task/Carmichael-3-strong-pseudoprimes/Kotlin/carmichael-3-strong-pseudoprimes.kotlin +++ b/Task/Carmichael-3-strong-pseudoprimes/Kotlin/carmichael-3-strong-pseudoprimes.kotlin @@ -1,12 +1,13 @@ fun Int.isPrime(): Boolean { - when { - this == 2 -> return true - this <= 1 || this % 2 == 0 -> return false + return when { + this == 2 -> true + this <= 1 || this % 2 == 0 -> false else -> { val max = Math.sqrt(toDouble()).toInt() - for (n in 3..max step 2) - if (this % n == 0) return false - return true + (3..max step 2) + .filter { this % it == 0 } + .forEach { return false } + true } } } @@ -14,18 +15,22 @@ fun Int.isPrime(): Boolean { fun mod(n: Int, m: Int) = ((n % m) + m) % m fun main(args: Array) { - for (p1 in 3..61) - if (p1.isPrime()) - for (h3 in 2..p1-1) { + for (p1 in 3..61) { + if (p1.isPrime()) { + for (h3 in 2 until p1) { val g = h3 + p1 - for (d in 1..g-1) + for (d in 1 until g) { if ((g * (p1 - 1)) % d == 0 && mod(-p1 * p1, h3) == d % h3) { val q = 1 + (p1 - 1) * g / d if (q.isPrime()) { val r = 1 + (p1 * q / h3) - if (r.isPrime() && (q * r) % (p1 - 1) == 1) + if (r.isPrime() && (q * r) % (p1 - 1) == 1) { println("$p1 x $q x $r") + } } } + } } + } + } } diff --git a/Task/Carmichael-3-strong-pseudoprimes/Sidef/carmichael-3-strong-pseudoprimes.sidef b/Task/Carmichael-3-strong-pseudoprimes/Sidef/carmichael-3-strong-pseudoprimes.sidef index 53a2160332..024f2a0966 100644 --- a/Task/Carmichael-3-strong-pseudoprimes/Sidef/carmichael-3-strong-pseudoprimes.sidef +++ b/Task/Carmichael-3-strong-pseudoprimes/Sidef/carmichael-3-strong-pseudoprimes.sidef @@ -5,9 +5,9 @@ func forprimes(a, b, callback) { } forprimes(3, 61, func(p) { - for h3 in (2 .. p-1) { + for h3 in (2 ..^ p) { var ph3 = (p + h3) - for d in (1 .. ph3-1) { + for d in (1 ..^ ph3) { ((-p * p) % h3) != (d % h3) && next ((p-1) * ph3) % d && next var q = 1+((p-1) * ph3 / d) diff --git a/Task/Carmichael-3-strong-pseudoprimes/Zkl/carmichael-3-strong-pseudoprimes-1.zkl b/Task/Carmichael-3-strong-pseudoprimes/Zkl/carmichael-3-strong-pseudoprimes-1.zkl new file mode 100644 index 0000000000..f27b8e7b75 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Zkl/carmichael-3-strong-pseudoprimes-1.zkl @@ -0,0 +1,12 @@ +var BN=Import("zklBigNum"), bi=BN(0); // gonna recycle bi +primes:=T(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61); +var p2,p3; +cs:=[[(p1,h3,d); primes; { [2..p1 - 1] }; // list comprehension + { [1..h3 + p1 - 1] }, + { ((h3 + p1)*(p1 - 1)%d == 0 and ((-p1*p1):mod(_,h3) == d%h3)) },//guard + { (p2=1 + (p1 - 1)*(h3 + p1)/d):bi.set(_).probablyPrime() },//guard + { (p3=1 + (p1*p2/h3)):bi.set(_).probablyPrime() }, //guard + { 1==(p2*p3)%(p1 - 1) }; //guard + { T(p1,p2,p3) } // return list of three primes in Carmichael number +]]; +fcn mod(a,b) { m:=a%b; if(m<0) m+b else m } diff --git a/Task/Carmichael-3-strong-pseudoprimes/Zkl/carmichael-3-strong-pseudoprimes-2.zkl b/Task/Carmichael-3-strong-pseudoprimes/Zkl/carmichael-3-strong-pseudoprimes-2.zkl new file mode 100644 index 0000000000..b9fb04cd05 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Zkl/carmichael-3-strong-pseudoprimes-2.zkl @@ -0,0 +1,3 @@ +cs.len().println(" Carmichael numbers found:"); +cs.pump(Console.println,fcn([(p1,p2,p3)]){ + "%2d * %4d * %5d = %d".fmt(p1,p2,p3,p1*p2*p3) }); diff --git a/Task/Case-sensitivity-of-identifiers/00DESCRIPTION b/Task/Case-sensitivity-of-identifiers/00DESCRIPTION index bd09c5a524..268b36ab7e 100644 --- a/Task/Case-sensitivity-of-identifiers/00DESCRIPTION +++ b/Task/Case-sensitivity-of-identifiers/00DESCRIPTION @@ -7,6 +7,7 @@ For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. -;Cf.: + +;Related task: * [[Unicode variable names]]

    diff --git a/Task/Case-sensitivity-of-identifiers/Aime/case-sensitivity-of-identifiers.aime b/Task/Case-sensitivity-of-identifiers/Aime/case-sensitivity-of-identifiers.aime new file mode 100644 index 0000000000..582eb956c5 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Aime/case-sensitivity-of-identifiers.aime @@ -0,0 +1,7 @@ +text dog, Dog, DOG; + +dog = "Benjamin"; +Dog = "Samba"; +DOG = "Bernie"; + +o_form("The three dogs are named ~, ~ and ~.\n", dog, Dog, DOG); diff --git a/Task/Case-sensitivity-of-identifiers/Batch-File/case-sensitivity-of-identifiers.bat b/Task/Case-sensitivity-of-identifiers/Batch-File/case-sensitivity-of-identifiers.bat new file mode 100644 index 0000000000..fc702eedbd --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Batch-File/case-sensitivity-of-identifiers.bat @@ -0,0 +1,8 @@ +@echo off + +set dog=Benjamin +set Dog=Samba +set DOG=Bernie + +echo There is just one dog named %dog%. +pause>nul diff --git a/Task/Case-sensitivity-of-identifiers/Bc/case-sensitivity-of-identifiers.bc b/Task/Case-sensitivity-of-identifiers/Bc/case-sensitivity-of-identifiers.bc new file mode 100644 index 0000000000..20d5047653 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Bc/case-sensitivity-of-identifiers.bc @@ -0,0 +1,10 @@ +obase = 16 +ibase = 16 + +/* + * Store the hexadecimal number 'BE27A312' + * in the variable 'd'. + */ +d = BE27A312 +"There is just one dog named "; d +quit diff --git a/Task/Case-sensitivity-of-identifiers/Dc/case-sensitivity-of-identifiers.dc b/Task/Case-sensitivity-of-identifiers/Dc/case-sensitivity-of-identifiers.dc new file mode 100644 index 0000000000..a0972a05e0 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Dc/case-sensitivity-of-identifiers.dc @@ -0,0 +1,4 @@ +[Benjamin]sd +[Samba]sD +[The two dogs are named ]P ldP [ and ]P lDP [. +]P 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 new file mode 100644 index 0000000000..0ba1066c14 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Elena/case-sensitivity-of-identifiers.elena @@ -0,0 +1,9 @@ +import extensions. + +program = +[ + var dog := "Benjamin". + var Dog := "Samba". + var DOG := "Bernie". + console printLineFormatted("The three dogs are named {0}, {1} and {2}", dog, Dog, DOG). +]. diff --git a/Task/Case-sensitivity-of-identifiers/Gambas/case-sensitivity-of-identifiers.gambas b/Task/Case-sensitivity-of-identifiers/Gambas/case-sensitivity-of-identifiers.gambas new file mode 100644 index 0000000000..1b0470c5ae --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Gambas/case-sensitivity-of-identifiers.gambas @@ -0,0 +1,9 @@ +Public Sub Main() +Dim dog As String + +Dog = "Benjamin" +DOG = "Samba" +dog = "Bernie" +Print "There is just one dog, named "; dog + +End diff --git a/Task/Case-sensitivity-of-identifiers/jq/case-sensitivity-of-identifiers-1.jq b/Task/Case-sensitivity-of-identifiers/Jq/case-sensitivity-of-identifiers-1.jq similarity index 100% rename from Task/Case-sensitivity-of-identifiers/jq/case-sensitivity-of-identifiers-1.jq rename to Task/Case-sensitivity-of-identifiers/Jq/case-sensitivity-of-identifiers-1.jq diff --git a/Task/Case-sensitivity-of-identifiers/jq/case-sensitivity-of-identifiers-2.jq b/Task/Case-sensitivity-of-identifiers/Jq/case-sensitivity-of-identifiers-2.jq similarity index 100% rename from Task/Case-sensitivity-of-identifiers/jq/case-sensitivity-of-identifiers-2.jq rename to Task/Case-sensitivity-of-identifiers/Jq/case-sensitivity-of-identifiers-2.jq 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.kotlin new file mode 100644 index 0000000000..2425bd7ea2 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Kotlin/case-sensitivity-of-identifiers.kotlin @@ -0,0 +1,6 @@ +fun main(args: Array) { + val dog = "Benjamin" + val Dog = "Samba" + val DOG = "Bernie" + println("The three dogs are named $dog, $Dog and $DOG") +} diff --git a/Task/Case-sensitivity-of-identifiers/Nimrod/case-sensitivity-of-identifiers.nimrod b/Task/Case-sensitivity-of-identifiers/Nimrod/case-sensitivity-of-identifiers.nimrod deleted file mode 100644 index 6ac96626fb..0000000000 --- a/Task/Case-sensitivity-of-identifiers/Nimrod/case-sensitivity-of-identifiers.nimrod +++ /dev/null @@ -1,4 +0,0 @@ -var dog = "Benjamin" -Dog = "Samba" -DOG = "Bernie" -echo("There is just one dog named " & doG) diff --git a/Task/Case-sensitivity-of-identifiers/Stata/case-sensitivity-of-identifiers.stata b/Task/Case-sensitivity-of-identifiers/Stata/case-sensitivity-of-identifiers.stata new file mode 100644 index 0000000000..ac926d4b94 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Stata/case-sensitivity-of-identifiers.stata @@ -0,0 +1,5 @@ +. local dog Benjamin +. local Dog Samba +. local DOG Bernie +. display "The three dogs are named $_dog, $_Dog, and $_DOG." +The three dogs are named Benjamin, Samba, and Bernie. diff --git a/Task/Case-sensitivity-of-identifiers/Zkl/case-sensitivity-of-identifiers.zkl b/Task/Case-sensitivity-of-identifiers/Zkl/case-sensitivity-of-identifiers.zkl new file mode 100644 index 0000000000..0cb635dd2d --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Zkl/case-sensitivity-of-identifiers.zkl @@ -0,0 +1 @@ +var dog = "Benjamin", Dog = "Samba", DOG = "Bernie"; diff --git a/Task/Casting-out-nines/360-Assembly/casting-out-nines.360 b/Task/Casting-out-nines/360-Assembly/casting-out-nines.360 new file mode 100644 index 0000000000..d2de49fcb7 --- /dev/null +++ b/Task/Casting-out-nines/360-Assembly/casting-out-nines.360 @@ -0,0 +1,64 @@ +* Casting out nines 08/02/2017 +CASTOUT CSECT + USING CASTOUT,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) prolog + ST R13,4(R15) " <- + ST R15,8(R13) " -> + LR R13,R15 " addressability + L R1,LOW low + XDECO R1,XDEC edit low + MVC PGT+4(4),XDEC+8 output low + L R1,HIGH high + XDECO R1,XDEC edit high + MVC PGT+12(4),XDEC+8 output low + L R1,BASE base + XDECO R1,XDEC edit base + MVC PGT+24(4),XDEC+8 output base + XPRNT PGT,L'PGT print buffer + L R2,BASE base + BCTR R2,0 -1 + ST R2,RM rm=base-1 + LA R8,PG ipg=0 + SR R7,R7 j=0 + L R6,LOW i=low + DO WHILE=(C,R6,LE,HIGH) do i=low to high + LR R5,R6 i + SR R4,R4 clear for div + D R4,RM /rm + LR R2,R4 r2=i mod rm + LR R5,R6 i + MR R4,R6 i*i + SR R4,R4 clear for div + D R4,RM /rm + IF CR,R2,EQ,R4 THEN if (i//rm)=(i*i//rm) then + LA R7,1(R7) j=j+1 + XDECO R6,XDEC edit i + MVC 0(4,R8),XDEC+8 output i + LA R8,4(R8) ipg=ipg+4 + IF C,R7,EQ,=F'20' THEN if j=20 then + XPRNT PG,L'PG print buffer + LA R8,PG ipg=0 + SR R7,R7 j=0 + MVC PG,=CL80' ' clear buffer + ENDIF , end if + ENDIF , end if + LA R6,1(R6) i=i+1 + ENDDO , end do i + IF LTR,R7,NE,R7 THEN if j<>0 then + XPRNT PG,L'PG print buffer + ENDIF , end if + L R13,4(0,R13) epilog + LM R14,R12,12(R13) " restore + XR R15,R15 " rc=0 + BR R14 exit +LOW DC F'1' low +HIGH DC F'500' high +BASE DC F'10' base +RM DS F rm +PGT DC CL80'for ... to ... base ...' buffer +PG DC CL80' ' buffer +XDEC DS CL12 temp for xdeco + YREGS + END CASTOUT diff --git a/Task/Casting-out-nines/Haskell/casting-out-nines-1.hs b/Task/Casting-out-nines/Haskell/casting-out-nines-1.hs new file mode 100644 index 0000000000..bf4635daa7 --- /dev/null +++ b/Task/Casting-out-nines/Haskell/casting-out-nines-1.hs @@ -0,0 +1,7 @@ +co9 n + | n <= 8 = n + | otherwise = co9 $ sum $ filter (/= 9) $ digits 10 n + +task2 = filter (\n -> co9 n == co9 (n ^ 2)) [1 .. 100] + +task3 k = filter (\n -> n `mod` k == n ^ 2 `mod` k) [1 .. 100] diff --git a/Task/Casting-out-nines/Haskell/casting-out-nines-2.hs b/Task/Casting-out-nines/Haskell/casting-out-nines-2.hs new file mode 100644 index 0000000000..e84e99ae88 --- /dev/null +++ b/Task/Casting-out-nines/Haskell/casting-out-nines-2.hs @@ -0,0 +1 @@ +digits base = map (`mod` base) . takeWhile (> 0) . iterate (`div` base) diff --git a/Task/Casting-out-nines/Haskell/casting-out-nines-3.hs b/Task/Casting-out-nines/Haskell/casting-out-nines-3.hs new file mode 100644 index 0000000000..d84b9ba128 --- /dev/null +++ b/Task/Casting-out-nines/Haskell/casting-out-nines-3.hs @@ -0,0 +1,3 @@ +digits base = Data.List.unfoldr modDiv + where modDiv 0 = Nothing + modDiv n = let (q, r) = (n `divMod` base) in Just (r, q) diff --git a/Task/Casting-out-nines/Haskell/casting-out-nines.hs b/Task/Casting-out-nines/Haskell/casting-out-nines.hs deleted file mode 100644 index 44d2a1855c..0000000000 --- a/Task/Casting-out-nines/Haskell/casting-out-nines.hs +++ /dev/null @@ -1,10 +0,0 @@ -digits base n - | n < m = [n] - | otherwise = r : digits base q where (q,r) = n `divMod` base - -co9 n - | n <= 8 = n - | otherwise = co9 $ sum $ filter (/= 9) $ digits 10 n - -task2 = filter (\n -> co9 n == co9 (n^2)) [1..100] -task3 k = filter (\n -> n `mod` k == n^2 `mod` k) [1..100] diff --git a/Task/Casting-out-nines/JavaScript/casting-out-nines-1.js b/Task/Casting-out-nines/JavaScript/casting-out-nines-1.js new file mode 100644 index 0000000000..bc44276602 --- /dev/null +++ b/Task/Casting-out-nines/JavaScript/casting-out-nines-1.js @@ -0,0 +1,47 @@ +function main(s, e, bs, pbs) { + bs = bs || 10; + pbs = pbs || 10 + document.write('start:', toString(s), ' end:', toString(e), + ' base:', bs, ' printBase:', pbs) + document.write('
    castOutNine: '); + castOutNine() + document.write('
    kaprekar: '); + kaprekar() + document.write('

    ') + + function castOutNine() { + for (var n = s, k = 0, bsm1 = bs - 1; n <= e; n += 1) + if (n % bsm1 == (n * n) % bsm1) k += 1, + document.write(toString(n), ' ') + document.write('
    trying ', k, ' numbers instead of ', n = e - s + 1, + ' numbers saves ', (100 - k / n * 100) + .toFixed(3), '%') + } + + function kaprekar() { + for (var n = s; n <= e; n += 1) + if (isKaprekar(n)) document.write(toString(n), ' ') + + function isKaprekar(n) { + if (n < 1) return false + if (n == 1) return true + var s = (n * n) + .toString(bs) + for (var i = 1, e = s.length; i < e; i += 1) { + var a = parseInt(s.substr(0, i), bs) + var b = parseInt(s.substr(i), bs) + if (b && a + b == n) return true + } + return false + } + } + + function toString(n) { + return n.toString(pbs) + .toUpperCase() + } +} +main(1, 10 * 10 - 1) +main(1, 16 * 16 - 1, 16) +main(1, 17 * 17 - 1, 17) +main(parseInt('10', 17), parseInt('gg', 17), 17, 17) diff --git a/Task/Casting-out-nines/JavaScript/casting-out-nines-2.js b/Task/Casting-out-nines/JavaScript/casting-out-nines-2.js new file mode 100644 index 0000000000..50859c6ecc --- /dev/null +++ b/Task/Casting-out-nines/JavaScript/casting-out-nines-2.js @@ -0,0 +1,46 @@ +(() => { + 'use strict'; + + // co9 :: Int -> Int + const co9 = n => + n <= 8 ? n : co9( + digits(10, n) + .reduce((a, x) => x !== 9 ? a + x : a, 0) + ); + + // GENERIC FUNCTIONS + + // digits :: Int -> Int -> [Int] + const digits = (base, n) => { + if (n < base) return [n]; + const [q, r] = quotRem(n, base); + return [r].concat(digits(base, q)); + }; + + // quotRem :: Integral a => a -> a -> (a, a) + const quotRem = (m, n) => [Math.floor(m / n), m % n]; + + // range :: Int -> Int -> [Int] + const range = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // squared :: Num a => a -> a + const squared = n => Math.pow(n, 2); + + // show :: a -> String + const show = x => JSON.stringify(x, null, 2); + + // TESTS + return show({ + test1: co9(232345), //-> 1 + test2: co9(34234234), //-> 7 + test3: co9(232345 + 34234234) === co9(232345) + co9(34234234), //-> true + test4: co9(232345 * 34234234) === co9(232345) * co9(34234234), //-> true, + task2: range(1, 100) + .filter(n => co9(n) === co9(squared(n))), + task3: (k => range(1, 100) + .filter(n => (n % k) === (squared(n) % k)))(16) + }); +})(); diff --git a/Task/Casting-out-nines/JavaScript/casting-out-nines.js b/Task/Casting-out-nines/JavaScript/casting-out-nines.js deleted file mode 100644 index 98237fd19b..0000000000 --- a/Task/Casting-out-nines/JavaScript/casting-out-nines.js +++ /dev/null @@ -1,32 +0,0 @@ -function main( s, e, bs, pbs ) { - bs = bs || 10; pbs = pbs || 10 - document.write('start:',toString(s), ' end:',toString(e), ' base:',bs, ' printBase:',pbs ) - document.write('
    castOutNine: '); castOutNine() - document.write('
    kaprekar: '); kaprekar() - document.write('

    ') - function castOutNine() { - for (var n=s, k=0, bsm1=bs-1; n<=e; n+=1) if (n%bsm1 == (n*n)%bsm1) k+=1, document.write(toString(n), ' ') - document.write('
    trying ', k, ' numbers instead of ', n=e-s+1, ' numbers saves ', (100-k/n*100).toFixed(3), '%') - } - function kaprekar() { - for (var n=s; n<=e; n+=1) if (isKaprekar(n)) document.write(toString(n), ' ') - function isKaprekar( n ) { - if ( n < 1 ) return false - if ( n == 1 ) return true - var s = (n * n).toString(bs) - for (var i=1, e=s.length; i { + val b = base - 1 + val ran = (0 until b).filter { it % b == (it * it) % b } + var x = start / b + val result = mutableListOf() + while (true) { + for (n in ran) { + val k = b * x + n + if (k < start) continue + if (k > end) return result + result.add(k) + } + x++ + } +} + +fun main(args: Array) { + println(castOut(16, 1, 255)) + println() + println(castOut(10, 1, 99)) + println() + println(castOut(17, 1, 288)) +} diff --git a/Task/Casting-out-nines/Mathematica/casting-out-nines-1.math b/Task/Casting-out-nines/Mathematica/casting-out-nines-1.math new file mode 100644 index 0000000000..233da95657 --- /dev/null +++ b/Task/Casting-out-nines/Mathematica/casting-out-nines-1.math @@ -0,0 +1,3 @@ +Co9[n_, b_: 10] := + With[{ans = FixedPoint[Total@IntegerDigits[#, b] &, n]}, + If[ans == b - 1, 0, ans]]; diff --git a/Task/Casting-out-nines/Mathematica/casting-out-nines-2.math b/Task/Casting-out-nines/Mathematica/casting-out-nines-2.math new file mode 100644 index 0000000000..b8c18c91f6 --- /dev/null +++ b/Task/Casting-out-nines/Mathematica/casting-out-nines-2.math @@ -0,0 +1,5 @@ +Co9 /@ (vals = {1235, 2345, 4753}) + {2, 5, 1} + +Total[Co9 /@ vals] == Co9[Total[vals]] + True diff --git a/Task/Casting-out-nines/Mathematica/casting-out-nines-3.math b/Task/Casting-out-nines/Mathematica/casting-out-nines-3.math new file mode 100644 index 0000000000..13dfd6a358 --- /dev/null +++ b/Task/Casting-out-nines/Mathematica/casting-out-nines-3.math @@ -0,0 +1 @@ +task2 = Select[Range@100, Co9[#] == Co9[#^2] &] diff --git a/Task/Casting-out-nines/Mathematica/casting-out-nines-4.math b/Task/Casting-out-nines/Mathematica/casting-out-nines-4.math new file mode 100644 index 0000000000..64d811d4e5 --- /dev/null +++ b/Task/Casting-out-nines/Mathematica/casting-out-nines-4.math @@ -0,0 +1 @@ +Co9eff[n_, b_: 10] := Mod[n, b - 1]; diff --git a/Task/Casting-out-nines/Mathematica/casting-out-nines-5.math b/Task/Casting-out-nines/Mathematica/casting-out-nines-5.math new file mode 100644 index 0000000000..2c95b38d65 --- /dev/null +++ b/Task/Casting-out-nines/Mathematica/casting-out-nines-5.math @@ -0,0 +1,5 @@ +task2 == Select[Range@100, Co9eff[#] == Co9eff[#^2] &] + True + +Select[Range@100, Co9eff[#, 17] == Co9eff[#^2, 17] &] + {1, 16, 17, 32, 33, 48, 49, 64, 65, 80, 81, 96, 97} diff --git a/Task/Casting-out-nines/Phix/casting-out-nines.phix b/Task/Casting-out-nines/Phix/casting-out-nines.phix new file mode 100644 index 0000000000..e675611c91 --- /dev/null +++ b/Task/Casting-out-nines/Phix/casting-out-nines.phix @@ -0,0 +1,29 @@ +procedure co9(integer start, integer base, integer lim, sequence kaprekars) +integer c1=0, + c2=0 +sequence s = {} + for k=start to lim do + c1 += 1 + if mod(k,base-1)=mod(k*k,base-1) then + c2 += 1 + s &= k + end if + end for + string msg = "Valid subset\n" + for i=1 to length(kaprekars) do + if not find(kaprekars[i],s) then + msg = "***INVALID***\n" + exit + end if + end for + if length(s)>40 then s[20..-20] = {"..."} end if + ?s + puts(1,"Kaprekar numbers:") + ?kaprekars + puts(1,msg) + printf(1,"Trying %d numbers instead of %d saves %3.2f%%\n\n",{c2,c1,100-(c2/c1)*100}) +end procedure + +co9(1, 10, 99, {1,9,45,55,99}) +co9(0(17)10, 17, 17*17, {0(17)3d,0(17)d4,0(17)gg}) +co9(1, 10, 1000, {1,9,45,55,99,297,703,999}) diff --git a/Task/Casting-out-nines/Scala/casting-out-nines.scala b/Task/Casting-out-nines/Scala/casting-out-nines.scala new file mode 100644 index 0000000000..ae04ac354b --- /dev/null +++ b/Task/Casting-out-nines/Scala/casting-out-nines.scala @@ -0,0 +1,16 @@ +object kaprekar{ + // PART 1 + val co_base = ((x:Int,base:Int) => (x%(base-1) == (x*x)%(base-1))) + //PART 2 + def get_cands(n:Int,base:Int):List[Int] = { + if(n==1) List[Int]() + else if (co_base(n,base)) n :: get_cands(n-1,base) + else get_cands(n-1,base) + } + def main(args:Array[String]) : Unit = { + //PART 3 + val base = 31 + println("Candidates for Kaprekar numbers found by casting out method with base %d:".format(base)) + println(get_cands(1000,base)) + } +} diff --git a/Task/Casting-out-nines/Zkl/casting-out-nines-1.zkl b/Task/Casting-out-nines/Zkl/casting-out-nines-1.zkl new file mode 100644 index 0000000000..58baf82e02 --- /dev/null +++ b/Task/Casting-out-nines/Zkl/casting-out-nines-1.zkl @@ -0,0 +1,12 @@ +fcn castOut(base=10, start=1, end=999999){ + base-=1; + ran:=(0).filter(base,'wrap(n){ n%base == (n*n)%base }); + result:=Sink(List); + foreach a,b in ([start/base ..],ran){ // foreach{ foreach {} } + k := base*a + b; + if (k < start) continue; + if (k > end) return(result.close()); + result.write(k); + } + // doesn't get here +} diff --git a/Task/Casting-out-nines/Zkl/casting-out-nines-2.zkl b/Task/Casting-out-nines/Zkl/casting-out-nines-2.zkl new file mode 100644 index 0000000000..2d13e385af --- /dev/null +++ b/Task/Casting-out-nines/Zkl/casting-out-nines-2.zkl @@ -0,0 +1,3 @@ +castOut(16, 1, 255).toString(*).println("\n-----"); +castOut(10, 1, 99).toString(*).println("\n-----"); +castOut(17, 1, 288).toString(*).println(); diff --git a/Task/Catalan-numbers-Pascals-triangle/00DESCRIPTION b/Task/Catalan-numbers-Pascals-triangle/00DESCRIPTION index 74024770df..c11c3855c6 100644 --- a/Task/Catalan-numbers-Pascals-triangle/00DESCRIPTION +++ b/Task/Catalan-numbers-Pascals-triangle/00DESCRIPTION @@ -3,7 +3,7 @@ Print out the first   '''15'''   Catalan numbers by extracting them fr ;See: -*   [http://milan.milanovic.org/math/english/fibo/fibo4.html Catalan Numbers and the Pascal Triangle].     This method enables calculation of Catalan Numbers using only addition and subtraction. +*   [http://milan.milanovic.org/math/english/fibo/fibo4.html Catalan Numbers and the Pascal Triangle].     This method enables calculation of Catalan Numbers using only addition and subtraction.
        '''The (above) link is broken.''' *   [http://mathworld.wolfram.com/CatalansTriangle.html Catalan's Triangle] for a Number Triangle that generates Catalan Numbers using only addition. diff --git a/Task/Catalan-numbers-Pascals-triangle/ALGOL-W/catalan-numbers-pascals-triangle.alg b/Task/Catalan-numbers-Pascals-triangle/ALGOL-W/catalan-numbers-pascals-triangle.alg new file mode 100644 index 0000000000..bdc0702ff4 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/ALGOL-W/catalan-numbers-pascals-triangle.alg @@ -0,0 +1,20 @@ +begin + % print the first 15 Catalan numbers from Pascal's triangle % + integer n; + n := 15; + begin + integer array pascalLine ( 1 :: n + 1 ); + % the Catalan numbers are the differences between the middle and middle - 1 numbers of the odd % + % lines of Pascal's triangle (lines with 3 or more numbers) % + % note - we only need to calculate the left side of the triangle % + pascalLine( 1 ) := 1; + for c := 2 until n + 1 do begin + % even line % + for i := c - 1 step -1 until 2 do pascalLine( i ) := pascalLine( i - 1 ) + pascalLine( i ); + pascalLine( c ) := pascalLine( c - 1 ); + % odd line % + for i := c step -1 until 2 do pascalLine( i ) := pascalLine( i - 1 ) + pascalLine( i ); + writeon( i_w := 1, s_w := 0, " ", pascalLine( c ) - pascalLine( c - 1 ) ) + end for_c + end +end. diff --git a/Task/Catalan-numbers-Pascals-triangle/C-sharp/catalan-numbers-pascals-triangle.cs b/Task/Catalan-numbers-Pascals-triangle/C-sharp/catalan-numbers-pascals-triangle.cs new file mode 100644 index 0000000000..88cc401b8d --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/C-sharp/catalan-numbers-pascals-triangle.cs @@ -0,0 +1,9 @@ +int n = 15; +List t = new List() { 0, 1 }; +for (int i = 1; i <= n; i++) +{ + for (var j = i; j > 1; j--) t[j] += t[j - 1]; + t.Add(t[i]); + for (var j = i + 1; j > 1; j--) t[j] += t[j - 1]; + Console.Write(((i == 1) ? "" : ", ") + (t[i + 1] - t[i])); +} diff --git a/Task/Catalan-numbers-Pascals-triangle/Erlang/catalan-numbers-pascals-triangle.erl b/Task/Catalan-numbers-Pascals-triangle/Erlang/catalan-numbers-pascals-triangle.erl new file mode 100644 index 0000000000..6d2e956134 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Erlang/catalan-numbers-pascals-triangle.erl @@ -0,0 +1,17 @@ +-module(catalin). +-compile(export_all). +mul(N,D,S,S)-> + 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). + +catl(Ans,16) -> Ans; +catl(D,S)-> + C=mul(1,1,S,2), + catl([D|C],S+1). +main()-> + Ans=catl(1,2). diff --git a/Task/Catalan-numbers-Pascals-triangle/Groovy/catalan-numbers-pascals-triangle.groovy b/Task/Catalan-numbers-Pascals-triangle/Groovy/catalan-numbers-pascals-triangle.groovy new file mode 100644 index 0000000000..6373ef6cb7 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Groovy/catalan-numbers-pascals-triangle.groovy @@ -0,0 +1,24 @@ +class Catalan +{ + public static void main(String[] args) + { + BigInteger N = 15; + BigInteger k,n,num,den; + BigInteger catalan; + print(1); + for(n=2;n<=N;n++) + { + num = 1; + den = 1; + for(k=2;k<=n;k++) + { + num = num*(n+k); + den = den*k; + catalan = num/den; + } + print(" " + catalan); + } + + } +} +​ diff --git a/Task/Catalan-numbers-Pascals-triangle/jq/catalan-numbers-pascals-triangle-1.jq b/Task/Catalan-numbers-Pascals-triangle/Jq/catalan-numbers-pascals-triangle-1.jq similarity index 100% rename from Task/Catalan-numbers-Pascals-triangle/jq/catalan-numbers-pascals-triangle-1.jq rename to Task/Catalan-numbers-Pascals-triangle/Jq/catalan-numbers-pascals-triangle-1.jq diff --git a/Task/Catalan-numbers-Pascals-triangle/jq/catalan-numbers-pascals-triangle-2.jq b/Task/Catalan-numbers-Pascals-triangle/Jq/catalan-numbers-pascals-triangle-2.jq similarity index 100% rename from Task/Catalan-numbers-Pascals-triangle/jq/catalan-numbers-pascals-triangle-2.jq rename to Task/Catalan-numbers-Pascals-triangle/Jq/catalan-numbers-pascals-triangle-2.jq 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.julia new file mode 100644 index 0000000000..17f033bb71 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Julia/catalan-numbers-pascals-triangle.julia @@ -0,0 +1,16 @@ +# v0.6 + +function pascal(n::Int) + r = ones(Int, n, n) + for i in 2:n, j in 2:n + r[i, j] = r[i-1, j] + r[i, j-1] + end + return r +end + +function catalan_num(n::Int) + p = pascal(n + 2) + p[n+4:n+3:end-1] - diag(p, 2) +end + +@show catalan_num(15) 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.kotlin new file mode 100644 index 0000000000..bfd894cf58 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Kotlin/catalan-numbers-pascals-triangle.kotlin @@ -0,0 +1,25 @@ +// version 1.1.2 + +import java.math.BigInteger + +val ONE = BigInteger.ONE + +fun pascal(n: Int, k: Int): BigInteger { + if (n == 0 || k == 0) return ONE + val num = (k + 1..n).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) } + val den = (2..n - k).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) } + return num / den +} + +fun catalanFromPascal(n: Int) { + for (i in 1 until n step 2) { + val mi = i / 2 + 1 + val catalan = pascal(i, mi) - pascal(i, mi - 2) + println("${"%2d".format(mi)} : $catalan") + } +} + +fun main(args: Array) { + val n = 15 + catalanFromPascal(n * 2) +} diff --git a/Task/Catalan-numbers-Pascals-triangle/MATLAB/catalan-numbers-pascals-triangle.m b/Task/Catalan-numbers-Pascals-triangle/MATLAB/catalan-numbers-pascals-triangle.m index 1b5fe4428b..541d996120 100644 --- a/Task/Catalan-numbers-Pascals-triangle/MATLAB/catalan-numbers-pascals-triangle.m +++ b/Task/Catalan-numbers-Pascals-triangle/MATLAB/catalan-numbers-pascals-triangle.m @@ -1,2 +1,3 @@ -p = pascal(17); -diag(p(2:end-1,2:end-1))-diag(p,2) +n = 15; +p = pascal(n + 2); +p(n + 4 : n + 3 : end - 1)' - diag(p, 2) diff --git a/Task/Catalan-numbers-Pascals-triangle/PureBasic/catalan-numbers-pascals-triangle.purebasic b/Task/Catalan-numbers-Pascals-triangle/PureBasic/catalan-numbers-pascals-triangle.purebasic new file mode 100644 index 0000000000..1125e82289 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/PureBasic/catalan-numbers-pascals-triangle.purebasic @@ -0,0 +1,26 @@ +#MAXNUM = 15 +Declare catalan() + +If OpenConsole("Catalan numbers") + catalan() + Input() + End 0 +Else + End -1 +EndIf + +Procedure catalan() + Define k.i, n.i, num.d, den.d, cat.d + + Print("1 ") + + For n=2 To #MAXNUM + num=1 : den =1 + For k=2 To n + num * (n+k) + den * k + cat = num / den + Next + Print(Str(cat)+" ") + Next +EndProcedure diff --git a/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-1.rexx b/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-1.rexx index 6a21491770..bc955d1b87 100644 --- a/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-1.rexx +++ b/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-1.rexx @@ -1,12 +1,11 @@ /*REXX program obtains and displays Catalan numbers from a Pascal's triangle. */ parse arg N . /*Obtain the optional argument from CL.*/ -if N=='' | N=="." then N=15 /*Not specified? Then use the default.*/ +if N=='' | N=="," then N=15 /*Not specified? Then use the default.*/ numeric digits max(9, N%2 + N%8) /*so we can handle huge Catalan numbers*/ @.=0; @.1=1 /*stem array default; define 1st value.*/ - do i=1 for N; ip=i+1 - do j=i by -1 for N; jm=j-1; @.j=@.j+@.jm; end /*j*/ - @.ip=@.i - do k=ip by -1 for N; km=k-1; @.k=@.k+@.km; end /*k*/ + do i=1 for N; ip=i+1 + do j=i by -1 for N; jm=j-1; @.j=@.j+@.jm; end /*j*/ + @.ip=@.i; do k=ip by -1 for N; km=k-1; @.k=@.k+@.km; end /*k*/ say @.ip - @.i /*display the Ith Catalan number. */ end /*i*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-2.rexx b/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-2.rexx index c82dbacad4..3658d16fa8 100644 --- a/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-2.rexx +++ b/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-2.rexx @@ -1,14 +1,13 @@ /*REXX program obtains and displays Catalan numbers from a Pascal's triangle. */ parse arg N . /*Obtain the optional argument from CL.*/ -if N=='' | N=="." then N=15 /*Not specified? Then use the default.*/ +if N=='' | N=="," then N=15 /*Not specified? Then use the default.*/ numeric digits max(9, N%2 + N%8) /*so we can handle huge Catalan numbers*/ @.=0; @.1=1 /*stem array default; define 1st value.*/ - - do i=1 for N; ip=i+1 - do j=i by -1 for N; @.j=@.j+@(j-1); end /*j*/ - @.ip=@.i; do k=ip by -1 for N; @.k=@.k+@(k-1); end /*k*/ - say @.ip - @.i /*display the Ith Catalan number. */ - end /*i*/ + do i=1 for N; ip=i+1 + do j=i by -1 for N; @.j=@.j+@(j-1); end /*j*/ + @.ip=@.i; do k=ip by -1 for N; @.k=@.k+@(k-1); end /*k*/ + say @.ip - @.i /*display the Ith Catalan number. */ + end /*i*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ @: parse arg !; return @.! /*return the value of @.[arg(1)] */ diff --git a/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-3.rexx b/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-3.rexx index bdf3f707a1..cfc2169690 100644 --- a/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-3.rexx +++ b/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-3.rexx @@ -1,11 +1,10 @@ /*REXX program obtains and displays Catalan numbers from a Pascal's triangle. */ parse arg N . /*Obtain the optional argument from CL.*/ -if N=='' | N=="." then N=15 /*Not specified? Then use the default.*/ +if N=='' | N=="," then N=15 /*Not specified? Then use the default.*/ numeric digits max(9, N%2 + N%8) /*so we can handle huge Catalan numbers*/ - - do j=1 for N /* [↓] display N Catalan numbers. */ - say comb(j+j,j) % (j+1) /*display the Jth Catalan number. */ - end /*j*/ + do j=1 for N /* [↓] display N Catalan numbers. */ + say comb(j+j, j) % (j+1) /*display the Jth Catalan number. */ + end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ !: procedure; parse arg z; _=1; do j=1 for arg(1); _=_*j; end; return _ diff --git a/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-4.rexx b/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-4.rexx index f02f923798..c4b42f7c6d 100644 --- a/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-4.rexx +++ b/Task/Catalan-numbers-Pascals-triangle/REXX/catalan-numbers-pascals-triangle-4.rexx @@ -1,11 +1,11 @@ /*REXX program obtains and displays Catalan numbers from a Pascal's triangle. */ parse arg N . /*Obtain the optional argument from CL.*/ -if N=='' | N=="." then N=15 /*Not specified? Then use the default.*/ +if N=='' | N=="," then N=15 /*Not specified? Then use the default.*/ numeric digits max(9, N%2 + N%8) /*so we can handle huge Catalan numbers*/ !.=. - do j=1 for N /* [↓] display N Catalan numbers. */ - say comb(j+j,j) % (j+1) /*display the Jth Catalan number. */ - end /*j*/ + do j=1 for N /* [↓] display N Catalan numbers. */ + say comb(j+j, j) % (j+1) /*display the Jth Catalan number. */ + end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ !: procedure expose !.; parse arg z; if !.z\==. then return !.z; _=1 diff --git a/Task/Catalan-numbers-Pascals-triangle/Rust/catalan-numbers-pascals-triangle.rust b/Task/Catalan-numbers-Pascals-triangle/Rust/catalan-numbers-pascals-triangle.rust new file mode 100644 index 0000000000..39701bbfcb --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Rust/catalan-numbers-pascals-triangle.rust @@ -0,0 +1,27 @@ +fn main() +{let n=15usize; + let mut t= [0; 17]; + t[1]=1; + let mut j:usize; + for i in 1..n+1 + { + j=i; + loop{ + if j==1{ + break; + } + t[j]=t[j] + t[j-1]; + j=j-1; + } + t[i+1]= t[i]; + j=i+1; + loop{ + if j==1{ + break; + } + t[j]=t[j] + t[j-1]; + j=j-1; + } + print!("{} ", t[i+1]-t[i]); + } +} diff --git a/Task/Catalan-numbers-Pascals-triangle/Sidef/catalan-numbers-pascals-triangle.sidef b/Task/Catalan-numbers-Pascals-triangle/Sidef/catalan-numbers-pascals-triangle.sidef index 23f5890926..5d61c4c3ba 100644 --- a/Task/Catalan-numbers-Pascals-triangle/Sidef/catalan-numbers-pascals-triangle.sidef +++ b/Task/Catalan-numbers-Pascals-triangle/Sidef/catalan-numbers-pascals-triangle.sidef @@ -1,11 +1,11 @@ func catalan(num) { - var t = [0, 1]; - range(1, num).map { |i| - range(i, 1, -1).each {|j| t[j] += t[j-1]}; - t[i+1] = t[i]; - range(i+1, 1, -1).each {|j| t[j] += t[j-1]}; - t[i+1] - t[i]; + var t = [0, 1] + (1..num).map { |i| + flip(^i ).each {|j| t[j+1] += t[j] } + t[i+1] = t[i] + flip(^i.inc).each {|j| t[j+1] += t[j] } + t[i+1] - t[i] } } -say catalan(15).join(' '); +say catalan(15).join(' ') diff --git a/Task/Catalan-numbers-Pascals-triangle/Smart-BASIC/catalan-numbers-pascals-triangle.smart b/Task/Catalan-numbers-Pascals-triangle/Smart-BASIC/catalan-numbers-pascals-triangle.smart new file mode 100644 index 0000000000..32738d4d95 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Smart-BASIC/catalan-numbers-pascals-triangle.smart @@ -0,0 +1,14 @@ +PRINT "Catalan Numbers from Pascal's Triangle"!PRINT +x = 15 +DIM t(x+2) +t(1) = 1 +FOR n = 1 TO x + FOR m = n TO 1 STEP -1 + t(m) = t(m) + t(m-1) + NEXT m + t(n+1) = t(n) + FOR m = n+1 TO 1 STEP -1 + t(m) = t(m) + t(m-1) + NEXT m +PRINT n,"#######":t(n+1) - t(n) +NEXT n diff --git a/Task/Catalan-numbers-Pascals-triangle/Zkl/catalan-numbers-pascals-triangle.zkl b/Task/Catalan-numbers-Pascals-triangle/Zkl/catalan-numbers-pascals-triangle.zkl new file mode 100644 index 0000000000..b1cb812bc3 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Zkl/catalan-numbers-pascals-triangle.zkl @@ -0,0 +1,2 @@ +fcn binomial(n,k){ (1).reduce(k,fcn(p,i,n){ p*(n-i+1)/i },1,n) } +(1).pump(15,List,fcn(n){ binomial(2*n,n)-binomial(2*n,n+1) }) diff --git a/Task/Catalan-numbers/ALGOL-W/catalan-numbers.alg b/Task/Catalan-numbers/ALGOL-W/catalan-numbers.alg new file mode 100644 index 0000000000..9b5d733cfb --- /dev/null +++ b/Task/Catalan-numbers/ALGOL-W/catalan-numbers.alg @@ -0,0 +1,10 @@ +begin + % print the catalan numbers up to C15 % + integer Cprev; + Cprev := 1; % C0 % + write( s_w := 0, i_w := 3, 0, ": ", i_w := 9, Cprev ); + for n := 1 until 15 do begin + Cprev := round( ( ( ( 4 * n ) - 2 ) / ( n + 1 ) ) * Cprev ); + write( s_w := 0, i_w := 3, n, ": ", i_w := 9, Cprev ); + end for_n +end. diff --git a/Task/Catalan-numbers/BASIC/catalan-numbers.basic b/Task/Catalan-numbers/BASIC/catalan-numbers-1.basic similarity index 100% rename from Task/Catalan-numbers/BASIC/catalan-numbers.basic rename to Task/Catalan-numbers/BASIC/catalan-numbers-1.basic diff --git a/Task/Catalan-numbers/BASIC/catalan-numbers-2.basic b/Task/Catalan-numbers/BASIC/catalan-numbers-2.basic new file mode 100644 index 0000000000..a1884c0065 --- /dev/null +++ b/Task/Catalan-numbers/BASIC/catalan-numbers-2.basic @@ -0,0 +1,17 @@ + 10 FOR N=0 TO 14 + 20 LET X=N + 30 GOSUB 130 + 40 LET A=FX + 50 LET X=N+1 + 60 GOSUB 130 + 70 LET B=FX + 80 LET X=2*N + 90 GOSUB 130 +100 PRINT N,FX/(B*A) +110 NEXT N +120 STOP +130 LET FX=1 +140 FOR I=1 TO X +150 LET FX=FX*I +160 NEXT I +170 RETURN diff --git a/Task/Catalan-numbers/C++/catalan-numbers-5.cpp b/Task/Catalan-numbers/C++/catalan-numbers-5.cpp deleted file mode 100644 index ebe93400fe..0000000000 --- a/Task/Catalan-numbers/C++/catalan-numbers-5.cpp +++ /dev/null @@ -1,16 +0,0 @@ -// Generate Catalan Numbers -// -// Nigel Galloway: June 9th., 2012 -// -#include -int main() { - const int N = 15; - int t[N+2] = {0,1}; - for(int i = 1; i<=N; i++){ - for(int j = i; j>1; j--) t[j] = t[j] + t[j-1]; - t[i+1] = t[i]; - for(int j = i+1; j>1; j--) t[j] = t[j] + t[j-1]; - std::cout << t[i+1] - t[i] << " "; - } - return 0; -} diff --git a/Task/Catalan-numbers/Eiffel/catalan-numbers-1.e b/Task/Catalan-numbers/Eiffel/catalan-numbers-1.e deleted file mode 100644 index 7715dd1ae4..0000000000 --- a/Task/Catalan-numbers/Eiffel/catalan-numbers-1.e +++ /dev/null @@ -1,19 +0,0 @@ -class - CATALAN_NUMBERS -feature - - cat_num(n:INTEGER): DOUBLE - require - n_not_negative:n>= 0 - local - s,t: DOUBLE - do - if n=0 then - Result:= 1.0 - else - t:= 4*n.to_double-2 - s:= n.to_double+1 - Result:= t/s*cat_num(n-1) - end - end -end diff --git a/Task/Catalan-numbers/Eiffel/catalan-numbers-2.e b/Task/Catalan-numbers/Eiffel/catalan-numbers-2.e deleted file mode 100644 index 3a7e4bbfed..0000000000 --- a/Task/Catalan-numbers/Eiffel/catalan-numbers-2.e +++ /dev/null @@ -1,24 +0,0 @@ -class - APPLICATION -inherit - ARGUMENTS -create - make -feature {NONE} -- Initialization - make - local - s: STRING - do - create cat - from - i:=0 - until - i>14 - loop - io.put_double (cat.cat_num (i)) - io.put_string ("%N") - i:= i+1 - end - end - cat: CATALAN_NUMBERS -end diff --git a/Task/Catalan-numbers/Groovy/catalan-numbers.groovy b/Task/Catalan-numbers/Groovy/catalan-numbers.groovy new file mode 100644 index 0000000000..3eea1b5b4f --- /dev/null +++ b/Task/Catalan-numbers/Groovy/catalan-numbers.groovy @@ -0,0 +1,23 @@ +class Catalan +{ + public static void main(String[] args) + { + BigInteger N = 15; + BigInteger k,n,num,den; + BigInteger catalan; + print(1); + for(n=2;n<=N;n++) + { + num = 1; + den = 1; + for(k=2;k<=n;k++) + { + num = num*(n+k); + den = den*k; + catalan = num/den; + } + println(catalan); + } + + } +} diff --git a/Task/Catalan-numbers/JavaScript/catalan-numbers-1.js b/Task/Catalan-numbers/JavaScript/catalan-numbers-1.js deleted file mode 100644 index ffea51d934..0000000000 --- a/Task/Catalan-numbers/JavaScript/catalan-numbers-1.js +++ /dev/null @@ -1,29 +0,0 @@ -Catalan -
    
    diff --git a/Task/Catalan-numbers/JavaScript/catalan-numbers-2.js b/Task/Catalan-numbers/JavaScript/catalan-numbers-2.js
    deleted file mode 100644
    index 2327812afd..0000000000
    --- a/Task/Catalan-numbers/JavaScript/catalan-numbers-2.js
    +++ /dev/null
    @@ -1,17 +0,0 @@
    -       meth1   meth2   meth3
    -0	1	1	1
    -1	1	1	1
    -2	2	2	2
    -3	5	5	5
    -4	14	14	14
    -5	42	42	42
    -6	132	132	132
    -7	429	429	429
    -8	1430	1430	1430
    -9	4862	4862	4862
    -10	16796	16796	16796
    -11	58786	58786	58786
    -12	208012	208012	208012
    -13	742900	742900	742900
    -14	2674440	2674440	2674440
    -15	9694845	9694845	9694845
    diff --git a/Task/Catalan-numbers/jq/catalan-numbers-1.jq b/Task/Catalan-numbers/Jq/catalan-numbers-1.jq
    similarity index 100%
    rename from Task/Catalan-numbers/jq/catalan-numbers-1.jq
    rename to Task/Catalan-numbers/Jq/catalan-numbers-1.jq
    diff --git a/Task/Catalan-numbers/jq/catalan-numbers-2.jq b/Task/Catalan-numbers/Jq/catalan-numbers-2.jq
    similarity index 100%
    rename from Task/Catalan-numbers/jq/catalan-numbers-2.jq
    rename to Task/Catalan-numbers/Jq/catalan-numbers-2.jq
    diff --git a/Task/Catalan-numbers/jq/catalan-numbers-3.jq b/Task/Catalan-numbers/Jq/catalan-numbers-3.jq
    similarity index 100%
    rename from Task/Catalan-numbers/jq/catalan-numbers-3.jq
    rename to Task/Catalan-numbers/Jq/catalan-numbers-3.jq
    diff --git a/Task/Catalan-numbers/jq/catalan-numbers-4.jq b/Task/Catalan-numbers/Jq/catalan-numbers-4.jq
    similarity index 100%
    rename from Task/Catalan-numbers/jq/catalan-numbers-4.jq
    rename to Task/Catalan-numbers/Jq/catalan-numbers-4.jq
    diff --git a/Task/Catalan-numbers/jq/catalan-numbers-5.jq b/Task/Catalan-numbers/Jq/catalan-numbers-5.jq
    similarity index 100%
    rename from Task/Catalan-numbers/jq/catalan-numbers-5.jq
    rename to Task/Catalan-numbers/Jq/catalan-numbers-5.jq
    diff --git a/Task/Catalan-numbers/jq/catalan-numbers-6.jq b/Task/Catalan-numbers/Jq/catalan-numbers-6.jq
    similarity index 100%
    rename from Task/Catalan-numbers/jq/catalan-numbers-6.jq
    rename to Task/Catalan-numbers/Jq/catalan-numbers-6.jq
    diff --git a/Task/Catalan-numbers/Kotlin/catalan-numbers.kotlin b/Task/Catalan-numbers/Kotlin/catalan-numbers.kotlin
    index d02b6ad9f9..b7dc850142 100644
    --- a/Task/Catalan-numbers/Kotlin/catalan-numbers.kotlin
    +++ b/Task/Catalan-numbers/Kotlin/catalan-numbers.kotlin
    @@ -1,33 +1,31 @@
    -import net.openhft.koloboke.collect.map.hash.HashIntDoubleMaps.*
    -
     abstract class Catalan {
         abstract operator fun invoke(n: Int) : Double
     
    -    protected val m = newUpdatableMapOf(0 , 1.0)
    +    protected val m = mutableMapOf(0 to 1.0)
     }
     
     object CatalanI : Catalan() {
         override fun invoke(n: Int): Double {
             if (n !in m)
                 m[n] = Math.round(fact(2 * n) / (fact(n + 1) * fact(n))).toDouble()
    -        return m[n]
    +        return m[n]!!
         }
     
         private fun fact(n: Int): Double {
             if (n in facts)
    -            return facts[n]
    -        var f = n * fact(n -1)
    +            return facts[n]!!
    +        val f = n * fact(n -1)
             facts[n] = f
             return f
         }
     
    -    private val facts = newUpdatableMapOf(0 , 1.0, 1 , 1.0, 2 , 2.0)
    +    private val facts = mutableMapOf(0 to 1.0, 1 to 1.0, 2 to 2.0)
     }
     
     object CatalanR1 : Catalan() {
         override fun invoke(n: Int): Double {
             if (n in m)
    -            return m[n]
    +            return m[n]!!
     
             var sum = 0.0
             for (i in 0..n - 1)
    @@ -42,7 +40,7 @@ object CatalanR2 : Catalan() {
         override fun invoke(n: Int): Double {
             if (n !in m)
                 m[n] = Math.round(2.0 * (2 * (n - 1) + 1) / (n + 1) * invoke(n - 1)).toDouble()
    -        return m[n]
    +        return m[n]!!
         }
     }
     
    diff --git a/Task/Catalan-numbers/MATLAB/catalan-numbers-2.m b/Task/Catalan-numbers/MATLAB/catalan-numbers-2.m
    index 37dcf3fb59..9315ee385e 100644
    --- a/Task/Catalan-numbers/MATLAB/catalan-numbers-2.m
    +++ b/Task/Catalan-numbers/MATLAB/catalan-numbers-2.m
    @@ -1,3 +1,3 @@
     function n = catalanNumbers(n)
    -    n = prod(n+1:2*n)/prod(1:n+1);
    +    n = arrayfun(@(n)prod(n+1:2*n)/prod(1:n+1), n);
     end
    diff --git a/Task/Catalan-numbers/OCaml/catalan-numbers.ocaml b/Task/Catalan-numbers/OCaml/catalan-numbers.ocaml
    new file mode 100644
    index 0000000000..1b195e4ee9
    --- /dev/null
    +++ b/Task/Catalan-numbers/OCaml/catalan-numbers.ocaml
    @@ -0,0 +1,12 @@
    +let catalan : int ref = ref 0 in
    +Printf.printf "%d ," 1 ;
    +for i = 2 to 9  do
    +let nm : int ref = ref 1 in
    +let den : int ref = ref 1 in
    +for k = 2 to i do
    +nm := (!nm)*(i+k);
    +den := (!den)*k;
    +catalan := (!nm)/(!den) ;
    +done;
    +print_int (!catalan); print_string "," ;
    +done;;
    diff --git a/Task/Catalan-numbers/OoRexx/catalan-numbers.rexx b/Task/Catalan-numbers/OoRexx/catalan-numbers.rexx
    new file mode 100644
    index 0000000000..7e6bfadf11
    --- /dev/null
    +++ b/Task/Catalan-numbers/OoRexx/catalan-numbers.rexx
    @@ -0,0 +1,81 @@
    +loop i = 0 to 15
    +    say "catI("i") =" .catalan~catI(i)
    +    say "catR1("i") =" .catalan~catR1(i)
    +    say "catR2("i") =" .catalan~catR2(i)
    +end
    +
    +-- This is implemented as static members on a class object
    +-- so that the code is able to keep state information between calls.  This
    +-- memoization will speed up things like factorial calls by remembering previous
    +-- results.
    +::class catalan
    +-- initialize the class object
    +::method init class
    +  expose facts catI catR1 catR2
    +         facts = .table~new
    +         catI = .table~new
    +         catR1 = .table~new
    +         catR2 = .table~new
    +         -- seed a few items
    +         facts[0] = 1
    +         facts[1] = 1
    +         facts[2] = 2
    +         catI[0] = 1
    +         catR1[0] = 1
    +         catR2[0] = 1
    +
    +-- private factorial method
    +::method fact private class
    +  expose facts
    +  use arg n
    +  -- see if we've calculated this before
    +  if facts~hasIndex(n) then return facts[n]
    +  numeric digits 120
    +
    +  fact = 1
    +  loop i = 2 to n
    +      fact *= i
    +  end
    +  -- save this result
    +  facts[n] = fact
    +  return fact
    +
    +::method catI class
    +  expose catI
    +  use arg n
    +  numeric digits 20
    +
    +  res = catI[n]
    +  if res == .nil then do
    +      -- dividing by 1 removes insignificant trailing 0s
    +      res = (self~fact(2 * n)/(self~fact(n + 1) * self~fact(n))) / 1
    +      catI[n] = res
    +  end
    +  return res
    +
    +::method catR1 class
    +  expose catR1
    +  use arg n
    +  numeric digits 20
    +
    +  if catR1~hasIndex(n) then return catR1[n]
    +  sum = 0
    +  loop i = 0 to n - 1
    +      sum += self~catR1(i) * self~catR1(n - 1 - i)
    +  end
    +  -- remove insignificant trailing 0s
    +  sum = sum / 1
    +  catR1[n] = sum
    +  return sum
    +
    +::method catR2 class
    +  expose catR2
    +  use arg n
    +  numeric digits 20
    +
    +  res = catR2[n]
    +  if res == .nil then do
    +     res = ((2 * (2 * n - 1) * self~catR2(n - 1)) /  (n + 1))
    +     catR2[n] = res
    +  end
    +  return res
    diff --git a/Task/Catalan-numbers/Perl-6/catalan-numbers-3.pl6 b/Task/Catalan-numbers/Perl-6/catalan-numbers-3.pl6
    index 65a32e0c03..db65ccb9c5 100644
    --- a/Task/Catalan-numbers/Perl-6/catalan-numbers-3.pl6
    +++ b/Task/Catalan-numbers/Perl-6/catalan-numbers-3.pl6
    @@ -1 +1 @@
    -.say for Catalan[^15];
    +.say for Catalan[^16];
    diff --git a/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx b/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx
    index f46a7d7ba9..64d93b2fb9 100644
    --- a/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx
    +++ b/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx
    @@ -10,7 +10,7 @@ call hdr 2 ;  do j=LO  to HI;  say '     Catalan'     right(j, w)": "      Cat2(
     call hdr 3 ;  do j=LO  to HI;  say '     Catalan'     right(j, w)": "      Cat3(j) ;   end
     exit                                             /*stick a fork in it,  we're all done. */
     /*──────────────────────────────────────────────────────────────────────────────────────*/
    -!:     arg z; if !.z\==. then return !.z; !=1;  do k=2 for z; !=!*k; end;  !.z=!; return !
    +!:     arg z; if !.z\==. then return !.z; !=1;  do k=2  to z; !=!*k; end;  !.z=!; return !
     Cat1A: procedure expose !.;  parse arg n;     return comb(n+n, n)    %  (n+1)
     Cat1B: procedure expose !.;  parse arg n;     return !(n+n) % ((n+1) * !(n)**2)
     Cat3:  procedure expose c.;  arg n; if c.n==. then c.n=(4*n-2)*cat3(n-1)%(n+1); return c.n
    @@ -18,6 +18,6 @@ comb:  procedure;            parse arg x,y;   return pFact(x-y+1, x) % pFact(2,
     hdr:   !.=.; c.=.; c.0=1; say; say center('Catalan numbers, method' arg(1),79,'─'); return
     pFact: procedure;            !=1;      do k=arg(1)  to arg(2);  !=!*k;  end;    return !
     /*──────────────────────────────────────────────────────────────────────────────────────*/
    -Cat2:  procedure expose c.;  parse arg n;  $=0;          if c.n\==.  then return c.n
    -                                       do k=0  to n-1;   $=$ + cat2(k) * cat2(n-k-1);  end
    +Cat2:  procedure expose c.;  parse arg n;  $=0;         if c.n\==.  then return c.n
    +                                       do k=0  for n;   $=$ + Cat2(k) * Cat2(n-k-1);   end
                                  c.n=$;           return $    /*use a memoization technique.*/
    diff --git a/Task/Catalan-numbers/Sidef/catalan-numbers-2.sidef b/Task/Catalan-numbers/Sidef/catalan-numbers-2.sidef
    index afaef00e98..c1d0174c46 100644
    --- a/Task/Catalan-numbers/Sidef/catalan-numbers-2.sidef
    +++ b/Task/Catalan-numbers/Sidef/catalan-numbers-2.sidef
    @@ -1,3 +1,3 @@
     func c(n) is cached {
    -    n == 0 ? 1 : (c(n-1) * (4 * n - 2) / (n + 1));
    +    n == 0 ? 1 : (c(n-1) * (4 * n - 2) / (n + 1))
     }
    diff --git a/Task/Catalan-numbers/Sidef/catalan-numbers-3.sidef b/Task/Catalan-numbers/Sidef/catalan-numbers-3.sidef
    index 442641a20c..9b35e748bf 100644
    --- a/Task/Catalan-numbers/Sidef/catalan-numbers-3.sidef
    +++ b/Task/Catalan-numbers/Sidef/catalan-numbers-3.sidef
    @@ -1,3 +1,3 @@
     15.times { |i|
    -    say "#{i-1}\t#{c(i-1)}";
    +    say "#{i}\t#{c(i)}"
     }
    diff --git a/Task/Catalan-numbers/Smart-BASIC/catalan-numbers.smart b/Task/Catalan-numbers/Smart-BASIC/catalan-numbers.smart
    new file mode 100644
    index 0000000000..e46c0a866e
    --- /dev/null
    +++ b/Task/Catalan-numbers/Smart-BASIC/catalan-numbers.smart
    @@ -0,0 +1,30 @@
    +PRINT "Recursive:"!PRINT
    +FOR n = 0 TO 15
    +    PRINT n,"#######":catrec(n)
    +NEXT n
    +PRINT!PRINT
    +
    +PRINT "Non-recursive:"!PRINT
    +FOR n = 0 TO 15
    +    PRINT n,"#######":catnonrec(n)
    +NEXT n
    +
    +END
    +
    +DEF catrec(x)
    +    IF x = 0 THEN
    +        temp = 1
    +    ELSE
    +        n = x
    +        temp = ((2*((2*n)-1))/(n+1))*catrec(n-1)
    +    END IF
    +    catrec = temp
    +END DEF
    +
    +DEF catnonrec(x)
    +    temp = 1
    +    FOR n = 1 TO x
    +         temp = (2*((2*n)-1))/(n+1)*temp
    +    NEXT n
    +    catnonrec = temp
    +END DEF
    diff --git a/Task/Catalan-numbers/XLISP/catalan-numbers.xlisp b/Task/Catalan-numbers/XLISP/catalan-numbers.xlisp
    new file mode 100644
    index 0000000000..45c4464433
    --- /dev/null
    +++ b/Task/Catalan-numbers/XLISP/catalan-numbers.xlisp
    @@ -0,0 +1,11 @@
    +(defun catalan (n)
    +	(if (= n 0)
    +		1
    +		(* (/ (* 2 (- (* 2 n) 1)) (+ n 1)) (catalan (- n 1))) ) )
    +
    +(defun range (x y)
    +	(cons x
    +		(if (< x y)
    +			(range (+ x 1) y) ) ) )
    +
    +(print (mapcar catalan (range 0 14)))
    diff --git a/Task/Catalan-numbers/Zkl/catalan-numbers-1.zkl b/Task/Catalan-numbers/Zkl/catalan-numbers-1.zkl
    new file mode 100644
    index 0000000000..ceb91a80ff
    --- /dev/null
    +++ b/Task/Catalan-numbers/Zkl/catalan-numbers-1.zkl
    @@ -0,0 +1,9 @@
    +var BN=Import("zklBigNum");
    +fcn catalan(n){
    +   BN(2*n).factorial() / BN(n+1).factorial() / BN(n).factorial();
    +}
    +
    +foreach n in (16){
    +   println("%2d --> %,d".fmt(n, catalan(n)));
    +}
    +println("%2d --> %,d".fmt(100, catalan(100)));
    diff --git a/Task/Catalan-numbers/Zkl/catalan-numbers-2.zkl b/Task/Catalan-numbers/Zkl/catalan-numbers-2.zkl
    new file mode 100644
    index 0000000000..49d4e9bff6
    --- /dev/null
    +++ b/Task/Catalan-numbers/Zkl/catalan-numbers-2.zkl
    @@ -0,0 +1 @@
    +fcn catalan(n){ (1).reduce(n,fcn(p,n){ 2*(2*n-1)*p/(n+1) },1) }
    diff --git a/Task/Catamorphism/00DESCRIPTION b/Task/Catamorphism/00DESCRIPTION
    index 0f07416896..001cf3a7d0 100644
    --- a/Task/Catamorphism/00DESCRIPTION
    +++ b/Task/Catamorphism/00DESCRIPTION
    @@ -5,7 +5,7 @@
     Show how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.
     
     
    -;Cf.
    -* [[wp:Fold (higher-order function)|Fold]]
    -* [[wp:Catamorphism|Catamorphism]]
    +;See also:
    +* Wikipedia article:   [[wp:Fold (higher-order function)|Fold]]
    +* Wikipedia article:   [[wp:Catamorphism|Catamorphism]]
     

    diff --git a/Task/Catamorphism/AppleScript/catamorphism.applescript b/Task/Catamorphism/AppleScript/catamorphism.applescript index 76bda1abfd..e8b7f2fa69 100644 --- a/Task/Catamorphism/AppleScript/catamorphism.applescript +++ b/Task/Catamorphism/AppleScript/catamorphism.applescript @@ -1,21 +1,22 @@ +-- CATAMORPHISMS -------------------------------------------------- + -- the arguments available to the called function f(a, x, i, l) are -- a: current accumulator value -- x: current item in list -- i: [ 1-based index in list ] optional -- l: [ a reference to the list itself ] optional --- reduce :: (a -> b -> a) -> a -> [b] -> a -on reduce(f, startValue, xs) +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell -end reduce - +end foldl -- the arguments available to the called function f(a, x, i, l) are -- a: current accumulator value @@ -23,45 +24,71 @@ end reduce -- i: [ 1-based index in list ] optional -- l: [ a reference to the list itself ] optional --- reduceRight :: (a -> b -> a) -> a -> [b] -> a -on reduceRight(f, startValue, xs) +-- foldr :: (a -> b -> a) -> a -> [b] -> a +on foldr(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell -end reduceRight +end foldr --- TEST +-- OTHER FUNCTIONS DEFINED IN TERMS OF FOLDL AND FOLDR ------------ + +-- concat :: [[a]] -> [a] | [String] -> String +on concat(xs) + script append + on |λ|(a, b) + a & b + end |λ| + end script + + if length of xs > 0 and class of (item 1 of xs) is string then + set unit to "" + else + set unit to {} + end if + foldl(append, unit, xs) +end concat + +-- product :: Num a => [a] -> a +on product(xs) + script + on |λ|(a, b) + a * b + end |λ| + end script + + foldr(result, 1, xs) +end product + +-- sum :: Num a => [a] -> a +on sum(xs) + script + on |λ|(a, b) + a + b + end |λ| + end script + + foldl(result, 0, xs) +end sum + + +-- TEST ----------------------------------------------------------- on run - set lst to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} + set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} - {reduce(sum_, 0, lst), ¬ - reduce(product_, 1, lst), ¬ - reduceRight(append_, "", lst)} + {sum(xs), product(xs), concat(xs)} --> {55, 3628800, "10987654321"} end run -on sum_(a, b) - a + b -end sum_ -on product_(a, b) - a * b -end product_ - -on append_(a, b) - a & b -end append_ - - - --- GENERIC +-- GENERIC FUNCTION ----------------------------------------------- -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -70,7 +97,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Catamorphism/D/catamorphism.d b/Task/Catamorphism/D/catamorphism.d index b3250b1344..b402a4ba99 100644 --- a/Task/Catamorphism/D/catamorphism.d +++ b/Task/Catamorphism/D/catamorphism.d @@ -1,9 +1,9 @@ void main() { - import std.stdio, std.algorithm, std.range, std.numeric, - std.conv, std.typecons, std.typetuple; + import std.stdio, std.algorithm, std.range, std.meta, std.numeric, + std.conv, std.typecons; auto list = iota(1, 11); - alias ops = TypeTuple!(q{a + b}, q{a * b}, min, max, gcd); + alias ops = AliasSeq!(q{a + b}, q{a * b}, min, max, gcd); foreach (op; ops) writeln(op.stringof, ": ", list.reduce!op); diff --git a/Task/Catamorphism/Elena/catamorphism.elena b/Task/Catamorphism/Elena/catamorphism.elena index eec0873a89..3dd9565c03 100644 --- a/Task/Catamorphism/Elena/catamorphism.elena +++ b/Task/Catamorphism/Elena/catamorphism.elena @@ -1,18 +1,17 @@ -#import system. -#import system'collections. -#import system'routines. -#import extensions. -#import extensions'text. +import system'collections. +import system'routines. +import extensions. +import extensions'text. -#symbol program = +program = [ - #var numbers := 1 repeat &till:10 &each:n [ n ] summarize:(ArrayList new). + var numbers := 1 repeat till:10 each(:n)( n ); summarize(ArrayList new). - #var summary := numbers accumulate:(Variable new:0) &with:(:a:b) [ a + b ]. + var summary := numbers accumulate(Variable new:0) with(:a:b)( a + b ). - #var product := numbers accumulate:(Variable new:1) &with:(:a:b) [ a * b ]. + var product := numbers accumulate(Variable new:1) with(:a:b)( a * b ). - #var concatenation := numbers accumulate:(String new) &with:(:a:b) [ a literal + b literal ]. + var concatenation := numbers accumulate(String new) with(:a:b)( a literal + b literal ). - console writeLine:summary:" ":product:" ":concatenation. + console printLine(summary," ",product," ",concatenation). ]. diff --git a/Task/Catamorphism/Haskell/catamorphism-1.hs b/Task/Catamorphism/Haskell/catamorphism-1.hs new file mode 100644 index 0000000000..d0c784e332 --- /dev/null +++ b/Task/Catamorphism/Haskell/catamorphism-1.hs @@ -0,0 +1,8 @@ +main :: IO () +main = + putStrLn . unlines $ + [ show . foldr (+) 0 -- sum + , show . foldr (*) 1 -- product + , foldr ((++) . show) "" -- concatenation + ] <*> + [[1 .. 10]] diff --git a/Task/Catamorphism/Haskell/catamorphism-2.hs b/Task/Catamorphism/Haskell/catamorphism-2.hs new file mode 100644 index 0000000000..f5f74fc0b1 --- /dev/null +++ b/Task/Catamorphism/Haskell/catamorphism-2.hs @@ -0,0 +1,12 @@ +import Data.Monoid + +main :: IO () +main = + let xs = [1 .. 10] + in (putStrLn . unlines) + [ (show . getSum . foldr (<>) mempty) (Sum <$> xs) + , (show . getProduct . foldr (<>) mempty) (Product <$> xs) + , (show . foldr (<>) mempty) (show <$> xs) + , (show . foldr (<>) mempty) (words + "Love is one damned thing after each other") + ] diff --git a/Task/Catamorphism/Haskell/catamorphism.hs b/Task/Catamorphism/Haskell/catamorphism.hs deleted file mode 100644 index ef45bac964..0000000000 --- a/Task/Catamorphism/Haskell/catamorphism.hs +++ /dev/null @@ -1,5 +0,0 @@ -nums = [1..10] - -summation = foldl (+) 0 nums -product = foldl (*) 1 nums -concatenation = foldr (\num s -> show num ++ s) "" nums diff --git a/Task/Catamorphism/Kotlin/catamorphism.kotlin b/Task/Catamorphism/Kotlin/catamorphism.kotlin new file mode 100644 index 0000000000..45ea9272ad --- /dev/null +++ b/Task/Catamorphism/Kotlin/catamorphism.kotlin @@ -0,0 +1,9 @@ +fun main(args: Array) { + val a = intArrayOf(1, 2, 3, 4, 5) + println("Array : ${a.joinToString(", ")}") + println("Sum : ${a.reduce { x, y -> x + y }}") + println("Difference : ${a.reduce { x, y -> x - y }}") + println("Product : ${a.reduce { x, y -> x * y }}") + println("Minimum : ${a.reduce { x, y -> if (x < y) x else y }}") + println("Maximum : ${a.reduce { x, y -> if (x > y) x else y }}") +} diff --git a/Task/Catamorphism/Phix/catamorphism.phix b/Task/Catamorphism/Phix/catamorphism.phix new file mode 100644 index 0000000000..f51b59c1f3 --- /dev/null +++ b/Task/Catamorphism/Phix/catamorphism.phix @@ -0,0 +1,23 @@ +function add(integer a, integer b) + return a + b +end function + +function sub(integer a, integer b) + return a - b +end function + +function mul(integer a, integer b) + return a * b +end function + +function reduce(integer rid, sequence s) +object res = s[1] + for i=2 to length(s) do + res = call_func(rid,{res,s[i]}) + end for + return res +end function + +?reduce(routine_id("add"),tagset(5)) +?reduce(routine_id("sub"),tagset(5)) +?reduce(routine_id("mul"),tagset(5)) diff --git a/Task/Catamorphism/Rust/catamorphism.rust b/Task/Catamorphism/Rust/catamorphism.rust new file mode 100644 index 0000000000..92348cba76 --- /dev/null +++ b/Task/Catamorphism/Rust/catamorphism.rust @@ -0,0 +1,7 @@ +fn main() { + println!("Sum: {}", (1..10).fold(0, |acc, n| acc + n)); + println!("Product: {}", (1..10).fold(1, |acc, n| acc * n)); + let chars = ['a', 'b', 'c', 'd', 'e']; + println!("Concatenation: {}", + chars.iter().map(|&c| (c as u8 + 1) as char).collect::()); +} diff --git a/Task/Catamorphism/Scheme/catamorphism.ss b/Task/Catamorphism/Scheme/catamorphism.ss new file mode 100644 index 0000000000..4deac3a119 --- /dev/null +++ b/Task/Catamorphism/Scheme/catamorphism.ss @@ -0,0 +1,7 @@ +(define (reduce fn init lst) + (do ((val init (fn (car rem) val)) ; accumulated value passed as second argument + (rem lst (cdr rem))) + ((null? rem) val))) + +(display (reduce + 0 '(1 2 3 4 5))) (newline) ; => 15 +(display (reduce expt 2 '(3 4))) (newline) ; => 262144 diff --git a/Task/Catamorphism/Zkl/catamorphism.zkl b/Task/Catamorphism/Zkl/catamorphism.zkl new file mode 100644 index 0000000000..f7cce4bd34 --- /dev/null +++ b/Task/Catamorphism/Zkl/catamorphism.zkl @@ -0,0 +1,3 @@ +T("foo","bar").reduce(fcn(p,n){p+n}) //--> "foobar" +"123four5".reduce(fcn(p,c){p+(c.matches("[0-9]") and c or 0)}, 0) //-->11 +File("foo.zkl").reduce('+(1).fpM("0-"),0) //->5 (lines in file) diff --git a/Task/Character-codes/360-Assembly/character-codes.360 b/Task/Character-codes/360-Assembly/character-codes.360 new file mode 100644 index 0000000000..1bd39c7182 --- /dev/null +++ b/Task/Character-codes/360-Assembly/character-codes.360 @@ -0,0 +1,34 @@ +* Character codes EBCDIC 15/02/2017 +CHARCODE CSECT + USING CHARCODE,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) prolog + ST R13,4(R15) " <- + ST R15,8(R13) " -> + LR R13,R15 " addressability +* Character to Decimal + SR R1,R1 r1=0 + IC R1,=C'a' insert character 'a' + XDECO R1,PG + XPRNT PG,L'PG print -> 129 +* Hexadecimal to character + SR R1,R1 r1=0 + IC R1,=X'81' insert character X'81' + STC R1,CHAR store character r1 + XPRNT CHAR,L'CHAR print -> 'a' +* Decimal to character + LH R1,=H'129' r1=129 + STC R1,CHAR store character r1 + XPRNT CHAR,L'CHAR print -> 'a' +* + XDUMP CHAR,L'CHAR dump -> X'81' +* +RETURN L R13,4(0,R13) epilog + LM R14,R12,12(R13) " restore + XR R15,R15 " rc=0 + BR R14 exit +PG DS CL12 +CHAR DS CL1 + YREGS + END CHARCODE diff --git a/Task/Character-codes/BASIC/character-codes-4.basic b/Task/Character-codes/BASIC/character-codes-4.basic new file mode 100644 index 0000000000..6b9314cce0 --- /dev/null +++ b/Task/Character-codes/BASIC/character-codes-4.basic @@ -0,0 +1,7 @@ +' ASCII +c$ = "$" +PRINT c$, ": ", ASC(c$) + +' UTF-8 +uc$ = "€" +PRINT uc$, ": ", UCS(uc$), ", ", UCS(c$) diff --git a/Task/Character-codes/Batch-File/character-codes.bat b/Task/Character-codes/Batch-File/character-codes.bat new file mode 100644 index 0000000000..7b218e460c --- /dev/null +++ b/Task/Character-codes/Batch-File/character-codes.bat @@ -0,0 +1,33 @@ +@echo off + +:: Supports all ASCII characters and codes from 34-126 with the exceptions of: +:: 38 & +:: 60 < +:: 62 > +:: 94 ^ +:: 124 | + +:_main +call:_toCode a +call:_toChar 97 +pause>nul +exit /b + +:_toCode +setlocal enabledelayedexpansion +set codecount=32 + +for /l %%i in (33,1,126) do ( + set /a codecount+=1 + cmd /c exit %%i + if %1==!=exitcodeAscii! ( + echo !codecount! + exit /b + ) +) + +:_toChar +setlocal +cmd /c exit %1 +echo %=exitcodeAscii% +exit /b diff --git a/Task/Character-codes/Elena/character-codes.elena b/Task/Character-codes/Elena/character-codes.elena index f804a38d85..70c73c48c8 100644 --- a/Task/Character-codes/Elena/character-codes.elena +++ b/Task/Character-codes/Elena/character-codes.elena @@ -1,9 +1,9 @@ -#define system. +import extensions. -#symbol program => +program = [ - #var ch := #97. + var ch := $97. console writeLine:ch. - console writeLine:(ch int). + console writeLine(ch toInt). ]. diff --git a/Task/Character-codes/Gambas/character-codes.gambas b/Task/Character-codes/Gambas/character-codes.gambas new file mode 100644 index 0000000000..4e9b68be5d --- /dev/null +++ b/Task/Character-codes/Gambas/character-codes.gambas @@ -0,0 +1,10 @@ +Public Sub Form_Open() +Dim sChar As String + +sChar = InputBox("Enter a character") +Print "Character " & sChar & " = ASCII " & Str(Asc(sChar)) + +sChar = InputBox("Enter a ASCII code") +Print "ASCII code " & sChar & " represents " & Chr(Val(sChar)) + +End diff --git a/Task/Character-codes/jq/character-codes-1.jq b/Task/Character-codes/Jq/character-codes-1.jq similarity index 100% rename from Task/Character-codes/jq/character-codes-1.jq rename to Task/Character-codes/Jq/character-codes-1.jq diff --git a/Task/Character-codes/jq/character-codes-2.jq b/Task/Character-codes/Jq/character-codes-2.jq similarity index 100% rename from Task/Character-codes/jq/character-codes-2.jq rename to Task/Character-codes/Jq/character-codes-2.jq diff --git a/Task/Character-codes/Kotlin/character-codes.kotlin b/Task/Character-codes/Kotlin/character-codes.kotlin new file mode 100644 index 0000000000..2163e06302 --- /dev/null +++ b/Task/Character-codes/Kotlin/character-codes.kotlin @@ -0,0 +1,8 @@ +fun main(args: Array) { + var c = 'a' + var i = c.toInt() + println("$c <-> $i") + i += 2 + c = i.toChar() + println("$i <-> $c") +} diff --git a/Task/Character-codes/Rust/character-codes.rust b/Task/Character-codes/Rust/character-codes.rust index f2bd461871..5616af64b1 100644 --- a/Task/Character-codes/Rust/character-codes.rust +++ b/Task/Character-codes/Rust/character-codes.rust @@ -7,5 +7,5 @@ fn main() { //unicode char println!("{}", 'π' as u32); - println!("{}", from_u32(960).unwrap(); + println!("{}", from_u32(960).unwrap()); } diff --git a/Task/Character-codes/SPL/character-codes.spl b/Task/Character-codes/SPL/character-codes.spl new file mode 100644 index 0000000000..3a330bbf20 --- /dev/null +++ b/Task/Character-codes/SPL/character-codes.spl @@ -0,0 +1,4 @@ +x = #.array("a") +#.output("a -> ",x[1]," ",x[2]) +x = [98,0] +#.output("98 0 -> ",#.str(x)) diff --git a/Task/Character-codes/Zkl/character-codes.zkl b/Task/Character-codes/Zkl/character-codes.zkl new file mode 100644 index 0000000000..951bfcd51f --- /dev/null +++ b/Task/Character-codes/Zkl/character-codes.zkl @@ -0,0 +1,2 @@ + "a".toAsc() //-->97 +(97).toChar() //-->"a" diff --git a/Task/Chat-server/Nim/chat-server.nim b/Task/Chat-server/Nim/chat-server.nim index b2f69ecc6b..e0afc28d69 100644 --- a/Task/Chat-server/Nim/chat-server.nim +++ b/Task/Chat-server/Nim/chat-server.nim @@ -1,40 +1,42 @@ import asyncnet, asyncdispatch -type TClient = tuple[socket: AsyncSocket, name: string] -var clients: seq[Client] = @[] +type + Client = tuple + socket: AsyncSocket + name: string + connected: bool + +var clients {.threadvar.}: seq[Client] proc sendOthers(client: Client, line: string) {.async.} = for c in clients: - if c != client: + if c != client and c.connected: await c.socket.send(line & "\c\L") proc processClient(socket: AsyncSocket) {.async.} = await socket.send("Please enter your name: ") - let client: Client = (socket, await socket.recvLine()) + var client: Client = (socket, await socket.recvLine(), true) - clients.add client - discard client.sendOthers "+++ " & client.name & " arrived +++" + clients.add(client) + asyncCheck client.sendOthers("+++ " & client.name & " arrived +++") while true: let line = await client.socket.recvLine() if line == "": - discard client.sendOthers "--- " & client.name & " leaves ---" - break - discard client.sendOthers client.name & "> " & line - - for i,c in clients: - if c == client: - clients.del i - break + asyncCheck client.sendOthers("--- " & client.name & " leaves ---") + client.connected = false + return + asyncCheck client.sendOthers(client.name & "> " & line) proc serve() {.async.} = + clients = @[] var server = newAsyncSocket() server.bindAddr(Port(4004)) server.listen() while true: let socket = await server.accept() - discard processClient socket + asyncCheck processClient(socket) -discard serve() +asyncCheck serve() runForever() diff --git a/Task/Chat-server/Zkl/chat-server.zkl b/Task/Chat-server/Zkl/chat-server.zkl new file mode 100644 index 0000000000..51e4d6593d --- /dev/null +++ b/Task/Chat-server/Zkl/chat-server.zkl @@ -0,0 +1,49 @@ +const PORT=23; + +var users=Dictionary(); // ( handle:socket, ...) +pipe:=Thread.Pipe(); // how server tells thread to connect to user + +fcn accept(pipe){ // a thread waiting for the server to send a socket + while(socket:=pipe.read()){ + println("Somebody is connecting ..."); + socket.read(); // telnet stuff + while(True){ // get credentials + reg name; + socket.write("Your handle: "); // bottle neck + try{ name = socket.read().text.strip() } catch(IOError){ continue } + if(users.holds(name)) socket.write("Handle is already in use.\n"); + else if(name){ + users[name] = socket; + chat.launch(name,socket); // thread + broadcast(name, "+++ %s arrived +++".fmt(name)); + break; // wait for next connection + } + }//while + }//while +}.launch(pipe); // thread + +fcn chat(name,socket){ // a thread, one per user + try{ + socket.write("^D to disconnect\n"); + while(True){ + message:=socket.read().text.strip(); + if(message=="\xff\xec") break; // ^D to disconnect. + broadcast(name, "%s> %s".fmt(name,message)); + } + }catch{} // eg socket pukes + users.del(name); socket.close(); + broadcast(name, "--- %s leaves ---".fmt(name)); +} + + // Send a message to all users from the given name. +fcn broadcast(name, message){ // called from user thread + println(message); // log message to server console + users.pump(Void,'wrap([(toName,socket)]){ + if(toName != name) try{ socket.write(message + "\n") } catch(IOError){} + }); +} + + // Set up the server socket. +server:=Network.TCPServerSocket.open(PORT); +println("Listening on %s:%s".fmt(server.hostname,server.port)); +server.listen(pipe); // Main event loop 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.kotlin new file mode 100644 index 0000000000..68d9cfa1e3 --- /dev/null +++ b/Task/Check-Machin-like-formulas/Kotlin/check-machin-like-formulas.kotlin @@ -0,0 +1,132 @@ +// version 1.1.3 + +import java.math.BigInteger + +val bigZero = BigInteger.ZERO +val bigOne = BigInteger.ONE + +class BigRational : Comparable { + + val num: BigInteger + val denom: BigInteger + + constructor(n: BigInteger, d: BigInteger) { + require(d != bigZero) + var nn = n + var dd = d + if (nn == bigZero) { + dd = bigOne + } + else if (dd < bigZero) { + nn = -nn + dd = -dd + } + val g = nn.gcd(dd) + if (g > bigOne) { + nn /= g + dd /= g + } + num = nn + denom = dd + } + + constructor(n: Long, d: Long) : this(BigInteger.valueOf(n), BigInteger.valueOf(d)) + + operator fun plus(other: BigRational) = + BigRational(num * other.denom + denom * other.num, other.denom * denom) + + operator fun unaryMinus() = BigRational(-num, denom) + + operator fun minus(other: BigRational) = this + (-other) + + operator fun times(other: BigRational) = BigRational(this.num * other.num, this.denom * other.denom) + + fun inverse(): BigRational { + require(num != bigZero) + return BigRational(denom, num) + } + + operator fun div(other: BigRational) = this * other.inverse() + + override fun compareTo(other: BigRational): Int { + val diff = this - other + return when { + diff.num < bigZero -> -1 + diff.num > bigZero -> +1 + else -> 0 + } + } + + override fun equals(other: Any?): Boolean { + if (other == null || other !is BigRational) return false + return this.compareTo(other) == 0 + } + + override fun toString() = if (denom == bigOne) "$num" else "$num/$denom" + + companion object { + val ZERO = BigRational(bigZero, bigOne) + val ONE = BigRational(bigOne, bigOne) + } +} + +/** represents a term of the form: c * atan(n / d) */ +class Term(val c: Long, val n: Long, val d: Long) { + + override fun toString() = when { + c == 1L -> " + " + c == -1L -> " - " + c < 0L -> " - ${-c}*" + else -> " + $c*" + } + "atan($n/$d)" +} + +val one = BigRational.ONE + +fun tanSum(terms: List): BigRational { + if (terms.size == 1) return tanEval(terms[0].c, BigRational(terms[0].n, terms[0].d)) + val half = terms.size / 2 + val a = tanSum(terms.take(half)) + val b = tanSum(terms.drop(half)) + return (a + b) / (one - (a * b)) +} + +fun tanEval(c: Long, f: BigRational): BigRational { + if (c == 1L) return f + if (c < 0L) return -tanEval(-c, f) + val ca = c / 2 + val cb = c - ca + val a = tanEval(ca, f) + val b = tanEval(cb, f) + return (a + b) / (one - (a * b)) +} + +fun main(args: Array) { + val termsList = listOf( + listOf(Term(1, 1, 2), Term(1, 1, 3)), + listOf(Term(2, 1, 3), Term(1, 1, 7)), + listOf(Term(4, 1, 5), Term(-1, 1, 239)), + listOf(Term(5, 1, 7), Term(2, 3, 79)), + listOf(Term(5, 29, 278), Term(7, 3, 79)), + listOf(Term(1, 1, 2), Term(1, 1, 5), Term(1, 1, 8)), + listOf(Term(4, 1, 5), Term(-1, 1, 70), Term(1, 1, 99)), + listOf(Term(5, 1, 7), Term(4, 1, 53), Term(2, 1, 4443)), + listOf(Term(6, 1, 8), Term(2, 1, 57), Term(1, 1, 239)), + listOf(Term(8, 1, 10), Term(-1, 1, 239), Term(-4, 1, 515)), + listOf(Term(12, 1, 18), Term(8, 1, 57), Term(-5, 1, 239)), + listOf(Term(16, 1, 21), Term(3, 1, 239), Term(4, 3, 1042)), + listOf(Term(22, 1, 28), Term(2, 1, 443), Term(-5, 1, 1393), Term(-10, 1, 11018)), + listOf(Term(22, 1, 38), Term(17, 7, 601), Term(10, 7, 8149)), + listOf(Term(44, 1, 57), Term(7, 1, 239), Term(-12, 1, 682), Term(24, 1, 12943)), + listOf(Term(88, 1, 172), Term(51, 1, 239), Term(32, 1, 682), Term(44, 1, 5357), Term(68, 1, 12943)), + listOf(Term(88, 1, 172), Term(51, 1, 239), Term(32, 1, 682), Term(44, 1, 5357), Term(68, 1, 12944)) + ) + + for (terms in termsList) { + val f = String.format("%-5s << 1 == tan(", tanSum(terms) == one) + print(f) + print(terms[0].toString().drop(3)) + for (i in 1 until terms.size) print(terms[i]) + println(")") + } +} diff --git a/Task/Check-Machin-like-formulas/OoRexx/check-machin-like-formulas.rexx b/Task/Check-Machin-like-formulas/OoRexx/check-machin-like-formulas.rexx new file mode 100644 index 0000000000..0d4c8ee969 --- /dev/null +++ b/Task/Check-Machin-like-formulas/OoRexx/check-machin-like-formulas.rexx @@ -0,0 +1,28 @@ +/*REXX ---------------------------------------------------------------- +* 09.04.2014 Walter Pachl the REXX solution adapted for ooRexx +* which provides a function package rxMath +*--------------------------------------------------------------------*/ +Numeric Digits 16 +Numeric Fuzz 3; pi=rxCalcpi(); a.='' + a.1 = 'pi/4 = rxCalcarctan(1/2,16,'R') + rxCalcarctan(1/3,16,'R')' + a.2 = 'pi/4 = 2*rxCalcarctan(1/3,16,'R') + rxCalcarctan(1/7,16,'R')' + a.3 = 'pi/4 = 4*rxCalcarctan(1/5,16,'R') - rxCalcarctan(1/239,16,'R')' + a.4 = 'pi/4 = 5*rxCalcarctan(1/7,16,'R') + 2*rxCalcarctan(3/79,16,'R')' + a.5 = 'pi/4 = 5*rxCalcarctan(29/278,16,'R') + 7*rxCalcarctan(3/79,16,'R')' + a.6 = 'pi/4 = rxCalcarctan(1/2,16,'R') + rxCalcarctan(1/5,16,'R') + rxCalcarctan(1/8,16,'R')' + a.7 = 'pi/4 = 4*rxCalcarctan(1/5,16,'R') - rxCalcarctan(1/70,16,'R') + rxCalcarctan(1/99,16,'R')' + a.8 = 'pi/4 = 5*rxCalcarctan(1/7,16,'R') + 4*rxCalcarctan(1/53,16,'R') + 2*rxCalcarctan(1/4443,16,'R')' + a.9 = 'pi/4 = 6*rxCalcarctan(1/8,16,'R') + 2*rxCalcarctan(1/57,16,'R') + rxCalcarctan(1/239,16,'R')' +a.10 = 'pi/4 = 8*rxCalcarctan(1/10,16,'R') - rxCalcarctan(1/239,16,'R') - 4*rxCalcarctan(1/515,16,'R')' +a.11 = 'pi/4 = 12*rxCalcarctan(1/18,16,'R') + 8*rxCalcarctan(1/57,16,'R') - 5*rxCalcarctan(1/239,16,'R')' +a.12 = 'pi/4 = 16*rxCalcarctan(1/21,16,'R') + 3*rxCalcarctan(1/239,16,'R') + 4*rxCalcarctan(3/1042,16,'R')' +a.13 = 'pi/4 = 22*rxCalcarctan(1/28,16,'R') + 2*rxCalcarctan(1/443,16,'R') - 5*rxCalcarctan(1/1393,16,'R') - 10*rxCalcarctan(1/11018,16,'R')' +a.14 = 'pi/4 = 22*rxCalcarctan(1/38,16,'R') + 17*rxCalcarctan(7/601,16,'R') + 10*rxCalcarctan(7/8149,16,'R')' +a.15 = 'pi/4 = 44*rxCalcarctan(1/57,16,'R') + 7*rxCalcarctan(1/239,16,'R') - 12*rxCalcarctan(1/682,16,'R') + 24*rxCalcarctan(1/12943,16,'R')' +a.16 = 'pi/4 = 88*rxCalcarctan(1/172,16,'R') + 51*rxCalcarctan(1/239,16,'R') + 32*rxCalcarctan(1/682,16,'R') + 44*rxCalcarctan(1/5357,16,'R') + 68*rxCalcarctan(1/12943,16,'R')' +a.17 = 'pi/4 = 88*rxCalcarctan(1/172,16,'R') + 51*rxCalcarctan(1/239,16,'R') + 32*rxCalcarctan(1/682,16,'R') + 44*rxCalcarctan(1/5357,16,'R') + 68*rxCalcarctan(1/12944,16,'R')' + do j=1 while a.j\=='' /*evaluate each of the formulas. */ + interpret 'answer=' "(" a.j ")" /*the heavy lifting.*/ + say right(word('bad OK',answer+1),3)": " space(a.j,0) + end /*j*/ /* [?] show OK | bad, formula. */ +::requires rxmath library diff --git a/Task/Check-that-file-exists/AppleScript/check-that-file-exists-1.applescript b/Task/Check-that-file-exists/AppleScript/check-that-file-exists-1.applescript new file mode 100644 index 0000000000..02a9655372 --- /dev/null +++ b/Task/Check-that-file-exists/AppleScript/check-that-file-exists-1.applescript @@ -0,0 +1,93 @@ +use framework "Foundation" -- YOSEMITE OS X onwards +use scripting additions + +on run + setCurrentDirectory("~/Desktop") + + ap({doesFileExist, doesDirectoryExist}, ¬ + {"input.txt", "/input.txt", "docs", "/docs"}) + + --> {true, true, true, true, false, false, true, true} + + -- The first four booleans are returned by `doesFileExist`. + + -- The last four are returned by `doesDirectoryExist`, + -- which yields false for simple files, and true for directories. +end run + +-- GENERIC SYSTEM DIRECTORY FUNCTIONS ----------------------------------------- + +-- doesDirectoryExist :: String -> Bool +on doesDirectoryExist(strPath) + set ca to current application + set oPath to (ca's NSString's stringWithString:strPath)'s ¬ + stringByStandardizingPath + set {bln, int} to (ca's NSFileManager's defaultManager()'s ¬ + fileExistsAtPath:oPath isDirectory:(reference)) + bln and (int = 1) +end doesDirectoryExist + +-- doesFileExist :: String -> Bool +on doesFileExist(strPath) + set ca to current application + set oPath to (ca's NSString's stringWithString:strPath)'s ¬ + stringByStandardizingPath + ca's NSFileManager's defaultManager()'s fileExistsAtPath:oPath +end doesFileExist + +-- getCurrentDirectory :: String +on getCurrentDirectory() + set ca to current application + ca's NSFileManager's defaultManager()'s currentDirectoryPath as string +end getCurrentDirectory + +-- getFinderDirectory :: String +on getFinderDirectory() + tell application "Finder" to POSIX path of (insertion location as alias) +end getFinderDirectory + +-- getHomeDirectory :: String +on getHomeDirectory() + (current application's NSHomeDirectory() as string) +end getHomeDirectory + +-- setCurrentDirectory :: String -> IO () +on setCurrentDirectory(strPath) + if doesDirectoryExist(strPath) then + set ca to current application + set oPath to (ca's NSString's stringWithString:strPath)'s ¬ + stringByStandardizingPath + ca's NSFileManager's defaultManager()'s ¬ + changeCurrentDirectoryPath:oPath + end if +end setCurrentDirectory + + +-- GENERIC HIGHER ORDER FUNCTIONS FOR THE TEST -------------------------------- + +-- A list of functions applied to a list of arguments +-- (<*> | ap) :: [(a -> b)] -> [a] -> [b] +on ap(fs, xs) + set {intFs, intXs} to {length of fs, length of xs} + set lst to {} + repeat with i from 1 to intFs + tell mReturn(item i of fs) + repeat with j from 1 to intXs + set end of lst to |λ|(contents of (item j of xs)) + end repeat + end tell + end repeat + return lst +end ap + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn diff --git a/Task/Check-that-file-exists/AppleScript/check-that-file-exists-2.applescript b/Task/Check-that-file-exists/AppleScript/check-that-file-exists-2.applescript new file mode 100644 index 0000000000..7380609da9 --- /dev/null +++ b/Task/Check-that-file-exists/AppleScript/check-that-file-exists-2.applescript @@ -0,0 +1 @@ +{true, true, true, true, false, false, true, true} diff --git a/Task/Check-that-file-exists/BASIC/check-that-file-exists-4.basic b/Task/Check-that-file-exists/BASIC/check-that-file-exists-4.basic new file mode 100644 index 0000000000..6bbc4d0522 --- /dev/null +++ b/Task/Check-that-file-exists/BASIC/check-that-file-exists-4.basic @@ -0,0 +1,16 @@ +' File exists +f$ = "input.txt" +d$ = "docs" +IF FILEEXISTS(f$) THEN PRINT f$, " exists" +IF FILEEXISTS(d$) AND FILETYPE(d$) = 2 THEN PRINT d$, " directory exists" + +f$ = "/" & f$ +d$ = "/" & d$ +PRINT f$, IIF$(FILEEXISTS(f$), " exists", " does not exist") +PRINT d$, IIF$(FILEEXISTS(d$) AND FILETYPE(d$) = 2, " is", " is not"), " a directory" + +f$ = "empty.bac" +PRINT f$, IIF$(FILEEXISTS(f$), " exists", " does not exist") + +f$ = "`Abdu'l-Bahá.txt" +PRINT f$, IIF$(FILEEXISTS(f$), " exists", " does not exist") diff --git a/Task/Check-that-file-exists/Elena/check-that-file-exists.elena b/Task/Check-that-file-exists/Elena/check-that-file-exists.elena index 0000d0376d..617a8503f7 100644 --- a/Task/Check-that-file-exists/Elena/check-that-file-exists.elena +++ b/Task/Check-that-file-exists/Elena/check-that-file-exists.elena @@ -1,14 +1,19 @@ -#import system. -#import system'io. -#import extensions. +import system'io. +import extensions. -#symbol program = +extension op +{ + validatePath + = self isAvailable; iif("exists","not found"). +} + +program = [ - console writeLine:"input.txt file ":("input.txt" file_path is &available iif:"exists":"not found"). + console printLine("input.txt file ",File new("input.txt"); validatePath). - console writeLine:"\input.txt file ":("\input.txt" file_path is &available iif:"exists":"not found"). + console printLine("\input.txt file ",File new("\input.txt"); validatePath). - console writeLine:"docs directory ":("docs" directory_path is &available iif:"exists":"not found"). + console printLine("docs directory ",Directory new("docs"); validatePath). - console writeLine:"\docs directory ":("\docs" directory_path is &available iif:"exists":"not found"). + console printLine("\docs directory ",Directory new("\docs"); validatePath). ]. diff --git a/Task/Check-that-file-exists/Gambas/check-that-file-exists.gambas b/Task/Check-that-file-exists/Gambas/check-that-file-exists.gambas new file mode 100644 index 0000000000..a740867fe9 --- /dev/null +++ b/Task/Check-that-file-exists/Gambas/check-that-file-exists.gambas @@ -0,0 +1,12 @@ +Public Sub Main() + +If Exist(User.Home &/ "input.txt") Then Print "'input.txt' does exist in the Home folder" +If Not Exist("/input.txt") Then Print "'input.txt' does NOT exist in Root" 'Not messing With my Root files + +If Exist(User.home &/ "docs/") Then Print "The folder '~/docs' does exist" +If Not Exist("/docs/") Then Print "The folder '/docs' does NOT exist" 'Not messing With my Root files + +File.Save(User.Home &/ "`Abdu'l-Bahá.txt", "") +If Exist(User.Home &/ "`Abdu'l-Bahá.txt") Then Print "'`Abdu'l-Bahá.txt' does exist (zero length and unusual name)" + +End diff --git a/Task/Check-that-file-exists/Haskell/check-that-file-exists.hs b/Task/Check-that-file-exists/Haskell/check-that-file-exists.hs index 83c6bf60c4..12d0cbff95 100644 --- a/Task/Check-that-file-exists/Haskell/check-that-file-exists.hs +++ b/Task/Check-that-file-exists/Haskell/check-that-file-exists.hs @@ -1,11 +1,15 @@ -import System.IO -import System.Directory +import System.Directory (doesFileExist, doesDirectoryExist) check :: (FilePath -> IO Bool) -> FilePath -> IO () check p s = do result <- p s - putStrLn $ s ++ if result then " does exist" else " does not exist" + putStrLn $ + s ++ + if result + then " does exist" + else " does not exist" +main :: IO () main = do check doesFileExist "input.txt" check doesDirectoryExist "docs" diff --git a/Task/Check-that-file-exists/JavaScript/check-that-file-exists.js b/Task/Check-that-file-exists/JavaScript/check-that-file-exists-1.js similarity index 100% rename from Task/Check-that-file-exists/JavaScript/check-that-file-exists.js rename to Task/Check-that-file-exists/JavaScript/check-that-file-exists-1.js diff --git a/Task/Check-that-file-exists/JavaScript/check-that-file-exists-2.js b/Task/Check-that-file-exists/JavaScript/check-that-file-exists-2.js new file mode 100644 index 0000000000..3c6a5f40c6 --- /dev/null +++ b/Task/Check-that-file-exists/JavaScript/check-that-file-exists-2.js @@ -0,0 +1,74 @@ +(() => { + + // SYSTEM DIRECTORY FUNCTIONS + // FOR MAC OS 'JAVASCRIPT FOR AUTOMATION' SCRIPTING ----------------------- + + // doesDirectoryExist :: String -> IO Bool + const doesDirectoryExist = strPath => { + const + dm = $.NSFileManager.defaultManager, + ref = Ref(); + return dm + .fileExistsAtPathIsDirectory( + $(strPath) + .stringByStandardizingPath, ref + ) && ref[0] === 1; + }; + + // doesFileExist :: String -> Bool + const doesFileExist = strPath => { + var error = $(); + return ( + $.NSFileManager.defaultManager + .attributesOfItemAtPathError( + $(strPath) + .stringByStandardizingPath, + error + ), + error.code === undefined + ); + }; + + // getCurrentDirectory :: String + const getCurrentDirectory = () => + ObjC.unwrap($.NSFileManager.defaultManager.currentDirectoryPath); + + // getFinderDirectory :: String + const getFinderDirectory = () => + Application('Finder') + .insertionLocation() + .url() + .slice(7); + + // getHomeDirectory :: String + const getHomeDirectory = () => + ObjC.unwrap($.NSHomeDirectory()); + + // setCurrentDirectory :: String -> IO () + const setCurrentDirectory = strPath => + $.NSFileManager.defaultManager + .changeCurrentDirectoryPath( + $(strPath) + .stringByStandardizingPath + ); + + // GENERIC FUNCTIONS FOR THE TEST ----------------------------------------- + + // A list of functions applied to a list of arguments + // <*> :: [(a -> b)] -> [a] -> [b] + const ap = (fs, xs) => // + [].concat.apply([], fs.map(f => // + [].concat.apply([], xs.map(x => [f(x)])))); + + // show :: a -> String + const show = x => JSON.stringify(x, null, 2); + + // TEST ------------------------------------------------------------------- + return ( + setCurrentDirectory('~/Desktop'), + show(ap( + [doesFileExist, doesDirectoryExist], + ['input.txt', '/input.txt', 'docs', '/docs'] + )) + ); +})(); diff --git a/Task/Check-that-file-exists/Kotlin/check-that-file-exists.kotlin b/Task/Check-that-file-exists/Kotlin/check-that-file-exists.kotlin new file mode 100644 index 0000000000..d91ff70a5d --- /dev/null +++ b/Task/Check-that-file-exists/Kotlin/check-that-file-exists.kotlin @@ -0,0 +1,16 @@ +// version 1.0.6 + +import java.io.File + +fun main(args: Array) { + val filePaths = arrayOf("input.txt", "c:\\input.txt", "zero_length.txt", "`Abdu'l-Bahá.txt") + val dirPaths = arrayOf("docs", "c:\\docs") + for (filePath in filePaths) { + val f = File(filePath) + println("$filePath ${if (f.exists() && !f.isDirectory) "exists" else "does not exist"}") + } + for (dirPath in dirPaths) { + val d = File(dirPath) + println("$dirPath ${if (d.exists() && d.isDirectory) "exists" else "does not exist"}") + } +} diff --git a/Task/Check-that-file-exists/OoRexx/check-that-file-exists.rexx b/Task/Check-that-file-exists/OoRexx/check-that-file-exists.rexx new file mode 100644 index 0000000000..dbacb1e481 --- /dev/null +++ b/Task/Check-that-file-exists/OoRexx/check-that-file-exists.rexx @@ -0,0 +1,20 @@ +/********************************************************************** +* exists(filespec) +* returns 1 if filespec identifies a file with size>0 +* (a file of size 0 is deemed not to exist.) +* or a directory +* 0 otherwise +* 09.06.2013 Walter Pachl (retrieved from my toolset) +**********************************************************************/ +exists: + parse arg spec + call sysfiletree spec, 'LIST', 'BL' + if list.0\=1 then return 0 -- does not exist + parse var list.1 . . size flags . + if size>0 then return 1 -- real file + If substr(flags,2,1)='D' Then Do + Say spec 'is a directory' + Return 1 + End + If size=0 Then Say spec 'is a zero-size file' + Return 0 diff --git a/Task/Check-that-file-exists/Stata/check-that-file-exists-1.stata b/Task/Check-that-file-exists/Stata/check-that-file-exists-1.stata new file mode 100644 index 0000000000..0c09f76e9b --- /dev/null +++ b/Task/Check-that-file-exists/Stata/check-that-file-exists-1.stata @@ -0,0 +1,4 @@ +mata +fileexists("input.txt") +direxists("docs") +end diff --git a/Task/Check-that-file-exists/Stata/check-that-file-exists-2.stata b/Task/Check-that-file-exists/Stata/check-that-file-exists-2.stata new file mode 100644 index 0000000000..752974682c --- /dev/null +++ b/Task/Check-that-file-exists/Stata/check-that-file-exists-2.stata @@ -0,0 +1,4 @@ +capture confirm file input.txt +if !_rc { + * do something if the file exists +} diff --git a/Task/Check-that-file-exists/Stata/check-that-file-exists-3.stata b/Task/Check-that-file-exists/Stata/check-that-file-exists-3.stata new file mode 100644 index 0000000000..ab89fe27d7 --- /dev/null +++ b/Task/Check-that-file-exists/Stata/check-that-file-exists-3.stata @@ -0,0 +1,4 @@ +confirmdir docs +if !r(confirmdir) { + * do something if the directory exists +} diff --git a/Task/Check-that-file-exists/Zkl/check-that-file-exists.zkl b/Task/Check-that-file-exists/Zkl/check-that-file-exists.zkl new file mode 100644 index 0000000000..4c83620caf --- /dev/null +++ b/Task/Check-that-file-exists/Zkl/check-that-file-exists.zkl @@ -0,0 +1,4 @@ +File.exists("input.txt") //--> True (in this case a sym link) +File.exists("/input.txt") //-->False +File.isDir("/") //-->True +File.isDir("docs") //-->False diff --git a/Task/Checkpoint-synchronization/Zkl/checkpoint-synchronization.zkl b/Task/Checkpoint-synchronization/Zkl/checkpoint-synchronization.zkl new file mode 100644 index 0000000000..c87c0f3a56 --- /dev/null +++ b/Task/Checkpoint-synchronization/Zkl/checkpoint-synchronization.zkl @@ -0,0 +1,26 @@ +const NUM_PARTS=5; // number of parts used to make the product +var requested=Atomic.Int(-1); // the id of the part the consumer needs +var pipe=Thread.Pipe(); // "conveyor belt" of parts to consumer + +fcn producer(id,pipe){ + while(True){ // make part forever + requested.waitFor(id); // wait for consumer to ask for my part + requested.set(-1); // I'm making the part + pipe.write(id); // ship my part + } + println(id," stopped"); +} + +foreach id in (NUM_PARTS){ producer.launch(id,pipe) } // start workers/threads + +product:=NUM_PARTS.pump(List(),0); // parts I have on hand +do(10){ // make 10 products + while(False!=(id:=product.filter1n('==(0)))){ // gather parts to make product + requested.set(id); + part:=pipe.read(); // get requested part + product[part]+=1; // assemble part into product + } + println("product made: ",product); + foreach n in (NUM_PARTS){ product[n]-=1 } // remove parts from bin +} +println("Done"); // but workers are still waiting diff --git a/Task/Chinese-remainder-theorem/jq/chinese-remainder-theorem.jq b/Task/Chinese-remainder-theorem/Jq/chinese-remainder-theorem.jq similarity index 100% rename from Task/Chinese-remainder-theorem/jq/chinese-remainder-theorem.jq rename to Task/Chinese-remainder-theorem/Jq/chinese-remainder-theorem.jq diff --git a/Task/Chinese-remainder-theorem/Kotlin/chinese-remainder-theorem.kotlin b/Task/Chinese-remainder-theorem/Kotlin/chinese-remainder-theorem.kotlin new file mode 100644 index 0000000000..2469b075d8 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Kotlin/chinese-remainder-theorem.kotlin @@ -0,0 +1,37 @@ +// version 1.1.2 + +/* returns x where (a * x) % b == 1 */ +fun multInv(a: Int, b: Int): Int { + if (b == 1) return 1 + var aa = a + var bb = b + var x0 = 0 + var x1 = 1 + while (aa > 1) { + val q = aa / bb + var t = bb + bb = aa % bb + aa = t + t = x0 + x0 = x1 - q * x0 + x1 = t + } + if (x1 < 0) x1 += b + return x1 +} + +fun chineseRemainder(n: IntArray, a: IntArray): Int { + val prod = n.fold(1) { acc, i -> acc * i } + var sum = 0 + for (i in 0 until n.size) { + val p = prod / n[i] + sum += a[i] * multInv(p, n[i]) * p + } + return sum % prod +} + +fun main(args: Array) { + val n = intArrayOf(3, 5, 7) + val a = intArrayOf(2, 3, 2) + println(chineseRemainder(n, a)) +} diff --git a/Task/Chinese-remainder-theorem/MATLAB/chinese-remainder-theorem-1.m b/Task/Chinese-remainder-theorem/MATLAB/chinese-remainder-theorem-1.m new file mode 100644 index 0000000000..dcec38bde7 --- /dev/null +++ b/Task/Chinese-remainder-theorem/MATLAB/chinese-remainder-theorem-1.m @@ -0,0 +1,4 @@ +function f = chineseRemainder(r, m) + s = prod(m) ./ m; + [~, t] = gcd(s, m); + f = s .* t * r'; diff --git a/Task/Chinese-remainder-theorem/MATLAB/chinese-remainder-theorem-2.m b/Task/Chinese-remainder-theorem/MATLAB/chinese-remainder-theorem-2.m new file mode 100644 index 0000000000..58f6566b25 --- /dev/null +++ b/Task/Chinese-remainder-theorem/MATLAB/chinese-remainder-theorem-2.m @@ -0,0 +1,2 @@ +>> chineseRemainder([2 3 2], [3 5 7]) + ans = 23 diff --git a/Task/Chinese-remainder-theorem/PureBasic/chinese-remainder-theorem.purebasic b/Task/Chinese-remainder-theorem/PureBasic/chinese-remainder-theorem.purebasic new file mode 100644 index 0000000000..0dc450cd55 --- /dev/null +++ b/Task/Chinese-remainder-theorem/PureBasic/chinese-remainder-theorem.purebasic @@ -0,0 +1,77 @@ +EnableExplicit +DisableDebugger +DataSection + LBL_n1: + Data.i 3,5,7 + LBL_a1: + Data.i 2,3,2 + LBL_n2: + Data.i 11,12,13 + LBL_a2: + Data.i 10,4,12 + LBL_n3: + Data.i 10,4,9 + LBL_a3: + Data.i 11,22,19 +EndDataSection + +Procedure ErrorHdl() + Print(ErrorMessage()) + Input() +EndProcedure + +Macro PrintData(n,a) + Define Idx.i=0 + Print("[") + While n+SizeOf(Integer)*Idx i32 + { let b0=b;let mut t;let mut q; + let mut x0=0;let mut x1=1; + if b==1 + {return 1; + } + while a>1 + { q=a/b; + t=b; + b=a%b; + a=t; + t=x0; + x0=x1-q*x0; + x1=t; + } + if x1<0 + {x1+=b0; + } + x1 + } + +fn chinese_remainder(n: &mut[i32],a: &mut[i32],len: usize)->i32 + { + let mut p=0;let mut prod=1;let mut sum=0; + for i in 0..len + { prod*=n[i]; + } + for i in 0..len + { p=prod/n[i]; + sum += a[i]*mul_inv(p, n[i])*p; + } + sum%prod + } + + +fn main() { + + let mut n = [3,5,7]; + let mut a = [2,3,2]; + let s = a.len(); + println!("{}",chinese_remainder(&mut n,&mut a,s)); + + +} diff --git a/Task/Chinese-remainder-theorem/Sidef/chinese-remainder-theorem.sidef b/Task/Chinese-remainder-theorem/Sidef/chinese-remainder-theorem.sidef index beb37cfc5f..7bd20060f0 100644 --- a/Task/Chinese-remainder-theorem/Sidef/chinese-remainder-theorem.sidef +++ b/Task/Chinese-remainder-theorem/Sidef/chinese-remainder-theorem.sidef @@ -16,5 +16,3 @@ func chinese_remainder(*n) { }.sum } } - -say chinese_remainder(3, 5, 7)(2, 3, 2); diff --git a/Task/Chinese-remainder-theorem/Swift/chinese-remainder-theorem.swift b/Task/Chinese-remainder-theorem/Swift/chinese-remainder-theorem.swift new file mode 100644 index 0000000000..f39362f22f --- /dev/null +++ b/Task/Chinese-remainder-theorem/Swift/chinese-remainder-theorem.swift @@ -0,0 +1,106 @@ +import Darwin + +/* + * Function: euclid + * Usage: (r,s) = euclid(m,n) + * -------------------------- + * The extended Euclidean algorithm subsequently performs + * Euclidean divisions till the remainder is zero and then + * returns the Bézout coefficients r and s. + */ + +func euclid(_ m:Int, _ n:Int) -> (Int,Int) { + if m % n == 0 { + return (0,1) + } else { + let rs = euclid(n % m, m) + let r = rs.1 - rs.0 * (n / m) + let s = rs.0 + + return (r,s) + } +} + +/* + * Function: gcd + * Usage: x = gcd(m,n) + * ------------------- + * The greatest common divisor of two numbers a and b + * is expressed by ax + by = gcd(a,b) where x and y are + * the Bézout coefficients as determined by the extended + * euclidean algorithm. + */ + +func gcd(_ m:Int, _ n:Int) -> Int { + let rs = euclid(m, n) + return m * rs.0 + n * rs.1 +} + +/* + * Function: coprime + * Usage: truth = coprime(m,n) + * --------------------------- + * If two values are coprime, their greatest common + * divisor is 1. + */ + +func coprime(_ m:Int, _ n:Int) -> Bool { + return gcd(m,n) == 1 ? true : false +} + +coprime(14,26) +//coprime(2,4) + +/* + * Function: crt + * Usage: x = crt(a,n) + * ------------------- + * The Chinese Remainder Theorem supposes that given the + * integers n_1...n_k that are pairwise co-prime, then for + * any sequence of integers a_1...a_k there exists an integer + * x that solves the system of linear congruences: + * + * x === a_1 (mod n_1) + * ... + * x === a_k (mod n_k) + */ + +func crt(_ a_i:[Int], _ n_i:[Int]) -> Int { + // There is no identity operator for elements of [Int]. + // The offset of the elements of an enumerated sequence + // can be used instead, to determine if two elements of the same + // array are the same. + let divs = n_i.enumerated() + + // Check if elements of n_i are pairwise coprime divs.filter{ $0.0 < n.0 } + divs.forEach{ + n in divs.filter{ $0.0 < n.0 }.forEach{ + assert(coprime(n.1, $0.1)) + } + } + + // Calculate factor N + let N = n_i.map{$0}.reduce(1, *) + + // Euclidean algorithm determines s_i (and r_i) + var s:[Int] = [] + + // Using euclidean algorithm to calculate r_i, s_i + n_i.forEach{ s += [euclid($0, N / $0).1] } + + // Solve for x + var x = 0 + a_i.enumerated().forEach{ + x += $0.1 * s[$0.0] * N / n_i[$0.0] + } + + // Return minimal solution + return x % N +} + +let a = [2,3,2] +let n = [3,5,7] + +let x = crt(a,n) + +print(x) diff --git a/Task/Chinese-remainder-theorem/Zkl/chinese-remainder-theorem-1.zkl b/Task/Chinese-remainder-theorem/Zkl/chinese-remainder-theorem-1.zkl new file mode 100644 index 0000000000..6bd361f74d --- /dev/null +++ b/Task/Chinese-remainder-theorem/Zkl/chinese-remainder-theorem-1.zkl @@ -0,0 +1,13 @@ +var BN=Import("zklBigNum"), one=BN(1); + +fcn crt(xs,ys){ + p:=xs.reduce('*,BN(1)); + X:=BN(0); + foreach x,y in (xs.zip(ys)){ + q:=p/x; + z,s,_:=q.gcdExt(x); + if(z!=one) throw(Exception.ValueError("%d not coprime".fmt(x))); + X+=y*s*q; + } + return(X % p); +} diff --git a/Task/Chinese-remainder-theorem/Zkl/chinese-remainder-theorem-2.zkl b/Task/Chinese-remainder-theorem/Zkl/chinese-remainder-theorem-2.zkl new file mode 100644 index 0000000000..028a5bc395 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Zkl/chinese-remainder-theorem-2.zkl @@ -0,0 +1,3 @@ +println(crt(T(3,5,7), T(2,3,2))); //-->23 +println(crt(T(11,12,13),T(10,4,12))); //-->1000 +println(crt(T(11,22,19), T(10,4,9))); //-->ValueError: 11 not coprime diff --git a/Task/Cholesky-decomposition/FreeBASIC/cholesky-decomposition.freebasic b/Task/Cholesky-decomposition/FreeBASIC/cholesky-decomposition.freebasic new file mode 100644 index 0000000000..438abb2511 --- /dev/null +++ b/Task/Cholesky-decomposition/FreeBASIC/cholesky-decomposition.freebasic @@ -0,0 +1,66 @@ +' version 18-01-2017 +' compile with: fbc -s console + +Sub Cholesky_decomp(array() As Double) + + Dim As Integer i, j, k + Dim As Double s, l(UBound(array), UBound(array, 2)) + + For i = 0 To UBound(array) + For j = 0 To i + s = 0 + For k = 0 To j -1 + s += l(i, k) * l(j, k) + Next + If i = j Then + l(i, j) = Sqr(array(i, i) - s) + Else + l(i, j) = (array(i, j) - s) / l(j, j) + End If + Next + Next + + For i = 0 To UBound(array) + For j = 0 To UBound(array, 2) + Swap array(i, j), l(i, j) + Next + Next + +End Sub + +Sub Print_(array() As Double) + + Dim As Integer i, j + + For i = 0 To UBound(array) + For j = 0 To UBound(array, 2) + Print Using "###.#####";array(i,j); + Next + Print + Next + +End Sub + +' ------=< MAIN >=------ + +Dim m1(2,2) As Double => {{25, 15, -5}, _ + {15, 18, 0}, _ + {-5, 0, 11}} + +Dim m2(3, 3) As Double => {{18, 22, 54, 42}, _ + {22, 70, 86, 62}, _ + {54, 86, 174, 134}, _ + {42, 62, 134, 106}} + +Cholesky_decomp(m1()) +Print_(m1()) + +Print +Cholesky_decomp(m2()) +Print_(m2()) + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Cholesky-decomposition/J/cholesky-decomposition-3.j b/Task/Cholesky-decomposition/J/cholesky-decomposition-3.j new file mode 100644 index 0000000000..9ab73645b5 --- /dev/null +++ b/Task/Cholesky-decomposition/J/cholesky-decomposition-3.j @@ -0,0 +1,11 @@ + load 'math/lapack' + load 'math/lapack/potrf' + potrf_jlapack_ eg1 + 5 0 0 + 3 3 0 +_1 1 3 + potrf_jlapack_ eg2 +4.24264 0 0 0 +5.18545 6.56591 0 0 +12.7279 3.04604 1.64974 0 +9.89949 1.62455 1.84971 1.39262 diff --git a/Task/Cholesky-decomposition/jq/cholesky-decomposition-1.jq b/Task/Cholesky-decomposition/Jq/cholesky-decomposition-1.jq similarity index 100% rename from Task/Cholesky-decomposition/jq/cholesky-decomposition-1.jq rename to Task/Cholesky-decomposition/Jq/cholesky-decomposition-1.jq diff --git a/Task/Cholesky-decomposition/jq/cholesky-decomposition-2.jq b/Task/Cholesky-decomposition/Jq/cholesky-decomposition-2.jq similarity index 100% rename from Task/Cholesky-decomposition/jq/cholesky-decomposition-2.jq rename to Task/Cholesky-decomposition/Jq/cholesky-decomposition-2.jq diff --git a/Task/Cholesky-decomposition/jq/cholesky-decomposition-3.jq b/Task/Cholesky-decomposition/Jq/cholesky-decomposition-3.jq similarity index 100% rename from Task/Cholesky-decomposition/jq/cholesky-decomposition-3.jq rename to Task/Cholesky-decomposition/Jq/cholesky-decomposition-3.jq diff --git a/Task/Cholesky-decomposition/Kotlin/cholesky-decomposition.kotlin b/Task/Cholesky-decomposition/Kotlin/cholesky-decomposition.kotlin new file mode 100644 index 0000000000..3a37d774d4 --- /dev/null +++ b/Task/Cholesky-decomposition/Kotlin/cholesky-decomposition.kotlin @@ -0,0 +1,40 @@ +// version 1.0.6 + +fun cholesky(a: DoubleArray): DoubleArray { + val n = Math.sqrt(a.size.toDouble()).toInt() + val l = DoubleArray(a.size) + var s: Double + for (i in 0 until n) + for (j in 0 .. i) { + s = 0.0 + for (k in 0 until j) s += l[i * n + k] * l[j * n + k] + l[i * n + j] = when { + (i == j) -> Math.sqrt(a[i * n + i] - s) + else -> 1.0 / l[j * n + j] * (a[i * n + j] - s) + } + } + return l +} + +fun showMatrix(a: DoubleArray) { + val n = Math.sqrt(a.size.toDouble()).toInt() + for (i in 0 until n) { + for (j in 0 until n) print("%8.5f ".format(a[i * n + j])) + println() + } +} + +fun main(args: Array) { + val m1 = doubleArrayOf(25.0, 15.0, -5.0, + 15.0, 18.0, 0.0, + -5.0, 0.0, 11.0) + val c1 = cholesky(m1) + showMatrix(c1) + println() + val m2 = doubleArrayOf(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) + val c2 = cholesky(m2) + showMatrix(c2) +} diff --git a/Task/Cholesky-decomposition/OoRexx/cholesky-decomposition.rexx b/Task/Cholesky-decomposition/OoRexx/cholesky-decomposition.rexx new file mode 100644 index 0000000000..80baca9971 --- /dev/null +++ b/Task/Cholesky-decomposition/OoRexx/cholesky-decomposition.rexx @@ -0,0 +1,51 @@ +/*REXX program performs the Cholesky decomposition on a square matrix. */ +niner = '25 15 -5' , /*define a 3x3 matrix. */ + '15 18 0' , + '-5 0 11' + call Cholesky niner +hexer = 18 22 54 42, /*define a 4x4 matrix. */ + 22 70 86 62, + 54 86 174 134, + 42 62 134 106 + call Cholesky hexer +exit /*stick a fork in it, we're all done. */ +/*----------------------------------------------------------------------------*/ +Cholesky: procedure; parse arg mat; say; say; call tell 'input matrix',mat + do r=1 for ord + do c=1 for r; d=0; do i=1 for c-1; d=d+!.r.i*!.c.i; end /*i*/ + if r=c then !.r.r=sqrt(!.r.r-d) + else !.r.c=1/!.c.c*(a.r.c-d) + end /*c*/ + end /*r*/ + call tell 'Cholesky factor',,!.,'-' + return +/*----------------------------------------------------------------------------*/ +err: say; say; say '***error***!'; say; say arg(1); say; say; exit 13 +/*----------------------------------------------------------------------------*/ +tell: parse arg hdr,x,y,sep; n=0; if sep=='' then sep='-' + dPlaces= 5 /*n decimal places past the decimal point*/ + width =10 /*width of field used to display elements*/ + if y=='' then !.=0 + else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end + w=words(x) + do ord=1 until ord**2>=w; end /*a fast way to find matrix's order*/ + say + if ord**2\==w then call err "matrix elements don't form a square matrix." + say center(hdr, ((width+1)*w)%ord, sep) + say + do row=1 for ord; z='' + do col=1 for ord; n=n+1 + a.row.col=word(x,n) + if col<=row then !.row.col=a.row.col + z=z right( format(a.row.col,, dPlaces) / 1, width) + end /*col*/ + say z + end /*row*/ + return +/*----------------------------------------------------------------------------*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=''; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Cholesky-decomposition/Phix/cholesky-decomposition.phix b/Task/Cholesky-decomposition/Phix/cholesky-decomposition.phix new file mode 100644 index 0000000000..3fb65ba60e --- /dev/null +++ b/Task/Cholesky-decomposition/Phix/cholesky-decomposition.phix @@ -0,0 +1,23 @@ +function cholesky(sequence matrix) +integer l = length(matrix) +sequence chol = repeat(repeat(0,l),l) + for row=1 to l do + for col=1 to row do + atom x = matrix[row][col] + for i=1 to col do + x -= chol[row][i] * chol[col][i] + end for + chol[row][col] = iff(row == col ? sqrt(x) : x/chol[col][col]) + end for + end for + return chol +end function + +ppOpt({pp_Nest,1}) +pp(cholesky({{ 25, 15, -5 }, + { 15, 18, 0 }, + { -5, 0, 11 }})) +pp(cholesky({{ 18, 22, 54, 42}, + { 22, 70, 86, 62}, + { 54, 86, 174, 134}, + { 42, 62, 134, 106}})) diff --git a/Task/Cholesky-decomposition/Q/cholesky-decomposition.q b/Task/Cholesky-decomposition/Q/cholesky-decomposition.q new file mode 100644 index 0000000000..f4294968fe --- /dev/null +++ b/Task/Cholesky-decomposition/Q/cholesky-decomposition.q @@ -0,0 +1,16 @@ +solve:{[A;B] $[0h>type A;B%A;inv[A] mmu B]} +ak:{[m;k] (),/:m[;k]til k:k-1} +akk:{[m;k] m[k;k:k-1]} +transpose:{$[0h=type x;flip x;enlist each x]} +mult:{[A;B]$[0h=type A;A mmu B;A*B]} +cholesky:{[A] + {[A;L;n] + l_k:solve[L;ak[A;n]]; + l_kk:first over sqrt[akk[A;n] - mult[transpose l_k;l_k]]; + ({$[0h, n: usize) -> Vec { + let mut res = vec![0.0; mat.len()]; + for i in 0..n { + for j in 0..(i+1){ + let mut s = 0.0; + for k in 0..j { + s += res[i * n + k] * res[j * n + k]; + } + res[i * n + j] = if i == j { (mat[i * n + i] - s).sqrt() } else { (1.0 / res[j * n + j] * (mat[i * n + j] - s)) }; + } + } + res +} + +fn show_matrix(matrix: Vec, n: usize){ + for i in 0..n { + for j in 0..n { + print!("{:.4}\t", matrix[i * n + j]); + } + println!(""); + } + println!(""); +} + +fn main(){ + let dimension = 3 as usize; + let m1 = vec![25.0, 15.0, -5.0, + 15.0, 18.0, 0.0, + -5.0, 0.0, 11.0]; + let res1 = cholesky(m1, dimension); + show_matrix(res1, dimension); + + let dimension = 4 as usize; + let m2 = vec![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]; + let res2 = cholesky(m2, dimension); + show_matrix(res2, dimension); +} diff --git a/Task/Cholesky-decomposition/Stata/cholesky-decomposition.stata b/Task/Cholesky-decomposition/Stata/cholesky-decomposition.stata new file mode 100644 index 0000000000..0d0e33daca --- /dev/null +++ b/Task/Cholesky-decomposition/Stata/cholesky-decomposition.stata @@ -0,0 +1,40 @@ +mata +: a=25,15,-5\15,18,0\-5,0,11 + +: a +[symmetric] + 1 2 3 + +----------------+ + 1 | 25 | + 2 | 15 18 | + 3 | -5 0 11 | + +----------------+ + +: cholesky(a) + 1 2 3 + +----------------+ + 1 | 5 0 0 | + 2 | 3 3 0 | + 3 | -1 1 3 | + +----------------+ + +: a=18,22,54,42\22,70,86,62\54,86,174,134\42,62,134,106 + +: a +[symmetric] + 1 2 3 4 + +-------------------------+ + 1 | 18 | + 2 | 22 70 | + 3 | 54 86 174 | + 4 | 42 62 134 106 | + +-------------------------+ + +: cholesky(a) + 1 2 3 4 + +---------------------------------------------------------+ + 1 | 4.242640687 0 0 0 | + 2 | 5.185449729 6.565905201 0 0 | + 3 | 12.72792206 3.046038495 1.649742248 0 | + 4 | 9.899494937 1.624553864 1.849711005 1.392621248 | + +---------------------------------------------------------+ diff --git a/Task/Cholesky-decomposition/Zkl/cholesky-decomposition-1.zkl b/Task/Cholesky-decomposition/Zkl/cholesky-decomposition-1.zkl new file mode 100644 index 0000000000..cc0309f957 --- /dev/null +++ b/Task/Cholesky-decomposition/Zkl/cholesky-decomposition-1.zkl @@ -0,0 +1,11 @@ +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +fcn lowerCholesky(m){ // trans: C + rows:=m.rows; + lcm:=GSL.Matrix(rows,rows); // zero filled + foreach i,j in (rows,i+1){ + s:=(0).reduce(j,'wrap(s,k){ s + lcm[i,k]*lcm[j,k] },0.0); + lcm[i,j]=( if(i==j)(m[i,i] - s).sqrt() + else 1.0/lcm[j,j]*(m[i,j] - s) ); + } + lcm +} diff --git a/Task/Cholesky-decomposition/Zkl/cholesky-decomposition-2.zkl b/Task/Cholesky-decomposition/Zkl/cholesky-decomposition-2.zkl new file mode 100644 index 0000000000..6254bbfac3 --- /dev/null +++ b/Task/Cholesky-decomposition/Zkl/cholesky-decomposition-2.zkl @@ -0,0 +1,10 @@ +fcn cholesky(mat){ + rows:=mat.len(); + r:=(0).pump(rows,List().write, (0).pump(rows,List,0.0).copy); // matrix of zeros + foreach i,j in (rows,i+1){ + s:=(0).reduce(j,'wrap(s,k){ s + r[i][k]*r[j][k] },0.0); + r[i][j]=( if(i==j)(mat[i][i] - s).sqrt() + else 1.0/r[j][j]*(mat[i][j] - s) ); + } + r +} diff --git a/Task/Cholesky-decomposition/Zkl/cholesky-decomposition-3.zkl b/Task/Cholesky-decomposition/Zkl/cholesky-decomposition-3.zkl new file mode 100644 index 0000000000..4f99eb028a --- /dev/null +++ b/Task/Cholesky-decomposition/Zkl/cholesky-decomposition-3.zkl @@ -0,0 +1,8 @@ +ex1:=L( L(25.0,15.0,-5.0), L(15.0,18.0,0.0), L(-5.0,0.0,11.0) ); +printM(cholesky(ex1)); +println("-----------------"); +ex2:=L( L(18.0, 22.0, 54.0, 42.0,), + L(22.0, 70.0, 86.0, 62.0,), + L(54.0, 86.0, 174.0, 134.0,), + L(42.0, 62.0, 134.0, 106.0,) ); +printM(cholesky(ex2)); diff --git a/Task/Cholesky-decomposition/Zkl/cholesky-decomposition-4.zkl b/Task/Cholesky-decomposition/Zkl/cholesky-decomposition-4.zkl new file mode 100644 index 0000000000..42bc456ccc --- /dev/null +++ b/Task/Cholesky-decomposition/Zkl/cholesky-decomposition-4.zkl @@ -0,0 +1,2 @@ +fcn printM(m){ m.pump(Console.println,rowFmt) } +fcn rowFmt(row){ ("%9.5f "*row.len()).fmt(row.xplode()) } diff --git a/Task/Circles-of-given-radius-through-two-points/JavaScript/circles-of-given-radius-through-two-points-1.js b/Task/Circles-of-given-radius-through-two-points/JavaScript/circles-of-given-radius-through-two-points-1.js new file mode 100644 index 0000000000..9d8e60bea1 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/JavaScript/circles-of-given-radius-through-two-points-1.js @@ -0,0 +1,42 @@ +const hDist = (p1, p2) => Math.hypot(...p1.map((e, i) => e - p2[i])) / 2; +const pAng = (p1, p2) => Math.atan(p1.map((e, i) => e - p2[i]).reduce((p, c) => c / p, 1)); +const solveF = (p, r) => t => [r*Math.cos(t) + p[0], r*Math.sin(t) + p[1]]; +const diamPoints = (p1, p2) => p1.map((e, i) => e + (p2[i] - e) / 2); + +const findC = (...args) => { + const [p1, p2, s] = args; + const solve = solveF(p1, s); + const halfDist = hDist(p1, p2); + + let msg = `p1: ${p1}, p2: ${p2}, r:${s} Result: `; + switch (Math.sign(s - halfDist)) { + case 0: + msg += s ? `Points on diameter. Circle at: ${diamPoints(p1, p2)}` : + 'Radius Zero'; + break; + case 1: + if (!halfDist) { + msg += 'Coincident point. Infinite solutions'; + } + else { + let theta = pAng(p1, p2); + let theta2 = Math.acos(halfDist / s); + [1, -1].map(e => solve(theta + e * theta2)).forEach( + e => msg += `Circle at ${e} `); + } + break; + case -1: + msg += 'No intersection. Points further apart than circle diameter'; + break; + } + return msg; +}; + + +[ + [[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] +].forEach((t,i) => console.log(`Test: ${i}: ${findC(...t)}`)); diff --git a/Task/Circles-of-given-radius-through-two-points/JavaScript/circles-of-given-radius-through-two-points-2.js b/Task/Circles-of-given-radius-through-two-points/JavaScript/circles-of-given-radius-through-two-points-2.js new file mode 100644 index 0000000000..70c6b65d68 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/JavaScript/circles-of-given-radius-through-two-points-2.js @@ -0,0 +1,5 @@ +Test: 0: p1: 0.1234,0.9876, p2: 0.8765,0.2345, r:2 Result: Circle at 1.8631118016581891,1.974211801658189 Circle at -0.863211801658189,-0.7521118016581889 +Test: 1: p1: 0,2, p2: 0,0, r:1 Result: Points on diameter. Circle at: 0,1 +Test: 2: p1: 0.1234,0.9876, p2: 0.1234,0.9876, r:2 Result: Coincident point. Infinite solutions +Test: 3: p1: 0.1234,0.9876, p2: 0.8765,0.2345, r:0.5 Result: No intersection. Points further apart than circle diameter +Test: 4: p1: 0.1234,0.9876, p2: 0.1234,0.9876, r:0 Result: Radius Zero diff --git a/Task/Circles-of-given-radius-through-two-points/jq/circles-of-given-radius-through-two-points-1.jq b/Task/Circles-of-given-radius-through-two-points/Jq/circles-of-given-radius-through-two-points-1.jq similarity index 100% rename from Task/Circles-of-given-radius-through-two-points/jq/circles-of-given-radius-through-two-points-1.jq rename to Task/Circles-of-given-radius-through-two-points/Jq/circles-of-given-radius-through-two-points-1.jq diff --git a/Task/Circles-of-given-radius-through-two-points/jq/circles-of-given-radius-through-two-points-2.jq b/Task/Circles-of-given-radius-through-two-points/Jq/circles-of-given-radius-through-two-points-2.jq similarity index 100% rename from Task/Circles-of-given-radius-through-two-points/jq/circles-of-given-radius-through-two-points-2.jq rename to Task/Circles-of-given-radius-through-two-points/Jq/circles-of-given-radius-through-two-points-2.jq diff --git a/Task/Circles-of-given-radius-through-two-points/jq/circles-of-given-radius-through-two-points-3.jq b/Task/Circles-of-given-radius-through-two-points/Jq/circles-of-given-radius-through-two-points-3.jq similarity index 100% rename from Task/Circles-of-given-radius-through-two-points/jq/circles-of-given-radius-through-two-points-3.jq rename to Task/Circles-of-given-radius-through-two-points/Jq/circles-of-given-radius-through-two-points-3.jq diff --git a/Task/Circles-of-given-radius-through-two-points/OoRexx/circles-of-given-radius-through-two-points.rexx b/Task/Circles-of-given-radius-through-two-points/OoRexx/circles-of-given-radius-through-two-points.rexx new file mode 100644 index 0000000000..361cc6032f --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/OoRexx/circles-of-given-radius-through-two-points.rexx @@ -0,0 +1,39 @@ +/*REXX pgm finds 2 circles with a specific radius given two (X,Y) points*/ + a.='' + a.1=0.1234 0.9876 0.8765 0.2345 2 + a.2=0.0000 2.0000 0.0000 0.0000 1 + a.3=0.1234 0.9876 0.1234 0.9876 2 + a.4=0.1234 0.9876 0.8765 0.2345 0.5 + a.5=0.1234 0.9876 0.1234 0.9876 0 + + Say ' x1 y1 x2 y2 radius cir1x cir1y cir2x cir2y' + Say ' ------ ------ ------ ------ ------ ------ ------ ------ ------' + Do j=1 By 1 While a.j<>'' + Do k=1 For 4 + w.k=f(word(a.j,k)) + End + Say w.1 w.2 w.3 w.4 format(word(a.j,5),5,1) twocircles(a.j) + End + Exit + +twocircles: Procedure + Parse Arg px py qx qy r . + If r=0 Then + Return ' radius of zero gives no circles.' + x=(qx-px)/2 + y=(qy-py)/2 + bx=px+x + by=py+y + pb=rxCalcsqrt(x**2+y**2) + If pb=0 Then + Return ' coincident points give infinite circles' + If pb>r Then + Return ' points are too far apart for the given radius' + cb=rxCalcsqrt(r**2-pb**2) + x1=y*cb/pb + y1=x*cb/pb + Return f(bx-x1) f(by+y1) f(bx+x1) f(by-y1) + +f: Return format(arg(1),2,4) /* format a number with 4 dec dig.*/ + +::requires 'rxMath' library diff --git a/Task/Circles-of-given-radius-through-two-points/Perl/circles-of-given-radius-through-two-points.pl b/Task/Circles-of-given-radius-through-two-points/Perl/circles-of-given-radius-through-two-points.pl new file mode 100644 index 0000000000..355021a77a --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Perl/circles-of-given-radius-through-two-points.pl @@ -0,0 +1,30 @@ +use feature 'say'; +sub circles_from_p1p2r { + my ($x1, $y1, $x2, $y2, $r) = @_; + die 'Radius is zero' if $r == 0.0; + die 'coincident points gives infinite number of Circles' if $x1 == $x2 && $y1 == $y2; + # delta x, delta y between points + my ($dx, $dy) = ($x2 - $x1, $y2 - $y1); + my $q = sqrt($dx**2 + $dy**2); + die 'separation of points > diameter' if $q > 2.0*$r; + # halfway point + my ($x3, $y3) = (($x1 + $x2) / 2, ($y1 + $y2) / 2); + # distance along the mirror line + my $d = sqrt($r**2-($q/2)**2); + # One answer + my @c1 = ($x3 - $d*$dy/$q, $y3 + $d*$dx/$q, $r); + # The other answer + my @c2 = ($x3 + $d*$dy/$q, $y3 - $d*$dx/$q, $r); + return (@c1, @c2); + } + +my @arr = ([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(@arr) { + my @res = circles_from_p1p2r @{$_}; + say "@res"; +} diff --git a/Task/Circles-of-given-radius-through-two-points/Scheme/circles-of-given-radius-through-two-points.ss b/Task/Circles-of-given-radius-through-two-points/Scheme/circles-of-given-radius-through-two-points.ss new file mode 100644 index 0000000000..6ab48c527c --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Scheme/circles-of-given-radius-through-two-points.ss @@ -0,0 +1,62 @@ +(import (scheme base) + (scheme inexact) + (scheme write)) + +;; c1 and c2 are pairs (x y), r a positive radius +(define (find-circles c1 c2 r) + (define x-coord car) ; for easier to read coordinate extraction from list + (define y-coord cadr) + (define (approx= a b) (< (- a b) 0.000001)) ; equal within tolerance + (define (avg a b) (/ (+ a b) 2)) + (define (distance pt1 pt2) + (sqrt (+ (square (- (x-coord pt1) (x-coord pt2))) + (square (- (y-coord pt1) (y-coord pt2)))))) + (define (equal-points? pt1 pt2) + (and (approx= (x-coord pt1) (x-coord pt2)) + (approx= (y-coord pt1) (y-coord pt2)))) + (define (delete-duplicate pts) ; assume no more than two points in list + (if (and (= 2 (length pts)) + (equal-points? (car pts) (cadr pts))) + (list (car pts)) ; keep the first only + pts)) + ; + (let ((d (distance c1 c2))) + (cond ((equal-points? c1 c2) ; coincident points + (if (> r 0) + 'infinite ; r > 0 + (list c1))) ; else r = 0 + ((< (* 2 r) d) + '()) ; circle cannot reach both points, as too far apart + ((approx= r 0.0) ; r = 0, no circles, as points differ + '()) + (else ; find up to two circles meeting c1 and c2 + (let* ((mid-pt (list (avg (x-coord c1) (x-coord c2)) + (avg (y-coord c1) (y-coord c2)))) + (offset (sqrt (- (square r) + (square (* 0.5 d))))) + (delta-cx (/ (- (x-coord c1) (x-coord c2)) d)) + (delta-cy (/ (- (y-coord c1) (y-coord c2)) d))) + (delete-duplicate + (list (list (- (x-coord mid-pt) (* offset delta-cx)) + (+ (y-coord mid-pt) (* offset delta-cy))) + (list (+ (x-coord mid-pt) (* offset delta-cx)) + (- (y-coord mid-pt) (* offset delta-cy)))))))))) + +;; work through the input examples, outputting results +(for-each + (lambda (c1 c2 r) + (let ((result (find-circles c1 c2 r))) + (display "p1: ") (display c1) + (display " p2: ") (display c2) + (display " r: ") (display (number->string r)) + (display " => ") + (cond ((eq? result 'infinite) + (display "Infinite number of circles")) + ((null? result) + (display "No circles")) + (else + (display result))) + (newline))) + '((0.1234 0.9876) (0.0000 2.0000) (0.1234 0.9876) (0.1234 0.9876) (0.1234 0.9876)) + '((0.8765 0.2345) (0.0000 0.0000) (0.1234 0.9876) (0.8765 0.2345) (0.1234 0.9876)) + '(2.0 1.0 2.0 0.5 0.0)) diff --git a/Task/Circles-of-given-radius-through-two-points/Zkl/circles-of-given-radius-through-two-points.zkl b/Task/Circles-of-given-radius-through-two-points/Zkl/circles-of-given-radius-through-two-points.zkl new file mode 100644 index 0000000000..398cc70035 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Zkl/circles-of-given-radius-through-two-points.zkl @@ -0,0 +1,35 @@ +fcn findCircles(a,b, c,d, r){ //-->T(T(x,y,r) [,T(x,y,r)])) + delta:=(a-c).hypot(b-d); + switch(delta){ // could just catch MathError + case(0.0){"singularity"} // should use epsilon test + case(r*2){T(T((a+c)/2,(b+d)/2,r))} + else{ + if(delta > 2*r) "Point delta > diameter"; + else{ + md:=(r.pow(2) - (delta/2).pow(2)).sqrt(); + T(T((a+c)/2 + md*(b-d)/delta,(b+d)/2 + md*(c-b)/delta,r), + T((a+c)/2 - md*(b-d)/delta,(b+d)/2 - md*(c-b)/delta,r)); + } + } + } +} + +data:=T( + T(0.1234, 0.9876, 0.8765, 0.2345, 2.0), + T(0.0000, 2.0000, 0.0000, 0.0000, 1.0), + T(0.1234, 0.9876, 0.1234, 0.9876, 2.0), + T(0.1234, 0.9876, 0.8765, 0.2345, 0.5), + T(0.1234, 0.9876, 0.1234, 0.9876, 0.0), +); + +ppFmt:="(%2.4f,%2.4f)"; +pprFmt:=ppFmt+" r=%2.1f"; +foreach a,b, c,d, r in (data){ + println("Points: ",ppFmt.fmt(a,b),", ",pprFmt.fmt(c,d,r)); + print(" Circles: "); + cs:=findCircles(a,b,c,d,r); + if(List.isType(cs)) + print(cs.pump(List,'wrap(c){pprFmt.fmt(c.xplode())}).concat(", ")); + else print(cs); + println(); +} diff --git a/Task/Classes/Crystal/classes.crystal b/Task/Classes/Crystal/classes.crystal new file mode 100644 index 0000000000..c94a793094 --- /dev/null +++ b/Task/Classes/Crystal/classes.crystal @@ -0,0 +1,13 @@ +class MyClass + + def initialize + @instance_var = 0 + end + + def add_1 + @instance_var += 1 + end + +end + +my_class = MyClass.new diff --git a/Task/Classes/DM/classes-1.dm b/Task/Classes/DM/classes-1.dm new file mode 100644 index 0000000000..b4785957bc --- /dev/null +++ b/Task/Classes/DM/classes-1.dm @@ -0,0 +1 @@ +s diff --git a/Task/Classes/DM/classes-2.dm b/Task/Classes/DM/classes-2.dm new file mode 100644 index 0000000000..6f7bfe5ce5 --- /dev/null +++ b/Task/Classes/DM/classes-2.dm @@ -0,0 +1,22 @@ +// Declare the class "/foo" +foo + // Everything inside the indented block is relative to the parent, "/foo" here. + // Instance variable "bar", with a default value of 0 + // Here, var/bar is relative to /foo, thus it becomes "/foo/var/bar" ultimately. + var/bar = 0 + + // The "New" proc is the constructor. + New() + // Constructor code. + + // Declares a proc called "Baz" on /foo + proc/baz() + // Do things. + +// Instantiation code. +// Overriding /client/New() means it is ran when a client connects. +/client/New() + ..() + var/foo/x = new /foo() + x.bar = 10 // Assign to the instance variable. + x.baz() // Call "baz" on our instance. diff --git a/Task/Classes/Elena/classes.elena b/Task/Classes/Elena/classes.elena index 7bc0015ae5..89d9b6fc99 100644 --- a/Task/Classes/Elena/classes.elena +++ b/Task/Classes/Elena/classes.elena @@ -1,30 +1,27 @@ -#import system. -#import extensions. +import extensions. -#class MyClass +class MyClass { - #field _variable. + object prop Variable :: _variable. - #method Variable = _variable. - - #method someMethod + someMethod [ _variable := 1. ] - #constructor new + constructor new [ ] } -#symbol program = +program = [ // instantiate the class - #var instance := MyClass new. + var instance := MyClass new. // invoke the method instance someMethod. // get the variable - console writeLine:"Variable=":(instance Variable). + console printLine("Variable=",instance Variable). ]. diff --git a/Task/Classes/Kotlin/classes.kotlin b/Task/Classes/Kotlin/classes.kotlin new file mode 100644 index 0000000000..b3e68e1e79 --- /dev/null +++ b/Task/Classes/Kotlin/classes.kotlin @@ -0,0 +1,8 @@ +class MyClass(val myInt: Int) { + fun treble(): Int = myInt * 3 +} + +fun main(args: Array) { + val mc = MyClass(24) + print("${mc.myInt}, ${mc.treble()}") +} diff --git a/Task/Classes/OoRexx/classes.rexx b/Task/Classes/OoRexx/classes.rexx new file mode 100644 index 0000000000..8b3ea48e4e --- /dev/null +++ b/Task/Classes/OoRexx/classes.rexx @@ -0,0 +1,29 @@ +p = .point~new +c = .circle~new + +p~print +c~print + +::class point +::method init + expose x y + use strict arg x = 0, y = 0 -- defaults to 0 for any non-specified coordinates + +::attribute x +::attribute y + +::method print + expose x y + say "A point at location ("||x","y")" + +::class circle subclass point +::method init + expose radius + use strict arg x = 0, y = 0, radius = 0 + self~init:super(x, y) -- call superclass constructor + +::attribute radius + +::method print + expose radius + say "A circle of radius" radius "centered at location ("||self~x","self~y")" diff --git a/Task/Classes/Rust/classes.rust b/Task/Classes/Rust/classes.rust new file mode 100644 index 0000000000..f64457b676 --- /dev/null +++ b/Task/Classes/Rust/classes.rust @@ -0,0 +1,30 @@ +struct MyClass { + variable: i32, // member variable = instance variable +} + +impl MyClass { + // member function = method, with its implementation + fn some_method(&mut self) { + self.variable = 1; + } + + // constructor, with its implementation + fn new() -> MyClass { + // Here could be more code. + MyClass { variable: 0 } + } +} + +fn main () { + // Create an instance in the stack. + let mut instance = MyClass::new(); + + // Create an instance in the heap. + let mut p_instance = Box::<_>::new(MyClass::new()); + + // Invoke method on both istances, + instance.some_method(); + p_instance.some_method(); + + // Both instances are automatically deleted when their scope ends. +} diff --git a/Task/Classes/Zkl/classes-1.zkl b/Task/Classes/Zkl/classes-1.zkl new file mode 100644 index 0000000000..f996c1e429 --- /dev/null +++ b/Task/Classes/Zkl/classes-1.zkl @@ -0,0 +1,10 @@ +class C{ // define class named "C", no parents or attributes + println("starting construction"); // all code outside functions is wrapped into the constructor + var v; // instance data for this class + fcn init(x) // initializer for this class, calls constructor + { v = x } + println("ending construction of ",self); +} +c1:=C(5); // create a new instance of C +c2:=c1("hoho"); // create another instance of C +println(C.v," ",c1.v," ",c2.v); diff --git a/Task/Classes/Zkl/classes-2.zkl b/Task/Classes/Zkl/classes-2.zkl new file mode 100644 index 0000000000..c5204d4488 --- /dev/null +++ b/Task/Classes/Zkl/classes-2.zkl @@ -0,0 +1,3 @@ +C.__constructor(); // run base class constructor for giggles +C.init(456); // initialize base class without creating instance +println(C.v," ",c1.v); diff --git a/Task/Closest-pair-problem/360-Assembly/closest-pair-problem.360 b/Task/Closest-pair-problem/360-Assembly/closest-pair-problem.360 new file mode 100644 index 0000000000..9932076a44 --- /dev/null +++ b/Task/Closest-pair-problem/360-Assembly/closest-pair-problem.360 @@ -0,0 +1,129 @@ +* Closest Pair Problem 10/03/2017 +CLOSEST CSECT + USING CLOSEST,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + LA R6,1 i=1 + LA R7,2 j=2 + BAL R14,DDCALC dd=(px(i)-px(j))^2+(py(i)-py(j))^2 + BAL R14,DDSTORE ddmin=dd; ii=i; jj=j + LA R6,1 i=1 + DO WHILE=(C,R6,LE,N) do i=1 to n + LA R7,1 j=1 + DO WHILE=(C,R7,LE,N) do j=1 to n + BAL R14,DDCALC dd=(px(i)-px(j))^2+(py(i)-py(j))^2 + IF CP,DD,GT,=P'0' THEN if dd>0 then + IF CP,DD,LT,DDMIN THEN if ddsqrt2 + ZAP SQRT1,SQRT2 sqrt1=sqrt2 + ZAP WPD,DDMIN ddmin + DP WPD,SQRT1 /sqrt1 + ZAP WP1,WPD(8) ddmin/sqrt1 + AP WP1,SQRT1 +sqrt1 + ZAP WPD,WP1 ~ + DP WPD,=PL8'2' /2 + ZAP SQRT2,WPD(8) sqrt2=(sqrt1+(ddmin/sqrt1))/2 + ENDDO , enddo while + MVC PG,=CL80'the minimum distance ' + ZAP WP1,SQRT2 sqrt2 + BAL R14,EDITPK edit + MVC PG+21(L'WC),WC output + XPRNT PG,L'PG print buffer + XPRNT =CL22'is between the points:',22 + MVC PG,PGP init buffer + L R1,II ii + SLA R1,4 *16 + LA R4,PXY-16(R1) @px(ii) + MVC WP1,0(R4) px(ii) + BAL R14,EDITPK edit + MVC PG+3(L'WC),WC output + MVC WP1,8(R4) py(ii) + BAL R14,EDITPK edit + MVC PG+21(L'WC),WC output + XPRNT PG,L'PG print buffer + MVC PG,PGP init buffer + L R1,JJ jj + SLA R1,4 *16 + LA R4,PXY-16(R1) @px(jj) + MVC WP1,0(R4) px(jj) + BAL R14,EDITPK edit + MVC PG+3(L'WC),WC output + MVC WP1,8(R4) py(jj) + BAL R14,EDITPK edit + MVC PG+21(L'WC),WC output + XPRNT PG,L'PG print buffer + L R13,4(0,R13) restore previous savearea pointer + LM R14,R12,12(R13) restore previous context + XR R15,R15 rc=0 + BR R14 exit +DDCALC EQU * ---- dd=(px(i)-px(j))^2+(py(i)-py(j))^2 + LR R1,R6 i + SLA R1,4 *16 + LA R4,PXY-16(R1) @px(i) + LR R1,R7 j + SLA R1,4 *16 + LA R5,PXY-16(R1) @px(j) + ZAP WP1,0(8,R4) px(i) + ZAP WP2,0(8,R5) px(j) + SP WP1,WP2 px(i)-px(j) + ZAP WPS,WP1 = + MP WP1,WPS (px(i)-px(j))*(px(i)-px(j)) + ZAP WP2,8(8,R4) py(i) + ZAP WP3,8(8,R5) py(j) + SP WP2,WP3 py(i)-py(j) + ZAP WPS,WP2 = + MP WP2,WPS (py(i)-py(j))*(py(i)-py(j)) + AP WP1,WP2 (px(i)-px(j))^2+(py(i)-py(j))^2 + ZAP DD,WP1 dd=(px(i)-px(j))^2+(py(i)-py(j))^2 + BR R14 ---- return +DDSTORE EQU * ---- ddmin=dd; ii=i; jj=j + ZAP DDMIN,DD ddmin=dd + ST R6,II ii=i + ST R7,JJ jj=j + BR R14 ---- return +EDITPK EQU * ---- + MVC WM,MASK set mask + EDMK WM,WP1 edit and mark + BCTR R1,0 -1 + MVC 0(1,R1),WM+17 set sign + MVC WC,WM len17<-len18 + BR R14 ---- return +N DC A((PGP-PXY)/16) +PXY DC PL8'0.654682',PL8'0.925557',PL8'0.409382',PL8'0.619391' + DC PL8'0.891663',PL8'0.888594',PL8'0.716629',PL8'0.996200' + DC PL8'0.477721',PL8'0.946355',PL8'0.925092',PL8'0.818220' + DC PL8'0.624291',PL8'0.142924',PL8'0.211332',PL8'0.221507' + DC PL8'0.293786',PL8'0.691701',PL8'0.839186',PL8'0.728260' +PGP DC CL80' [+xxxxxxxxx.xxxxxx,+xxxxxxxxx.xxxxxx]' +MASK DC C' ',7X'20',X'21',X'20',C'.',6X'20',C'-' CL18 15num +II DS F +JJ DS F +DD DS PL8 +DDMIN DS PL8 +SQRT1 DS PL8 +SQRT2 DS PL8 +WP1 DS PL8 +WP2 DS PL8 +WP3 DS PL8 +WPS DS PL8 +WPD DS PL16 +WM DS CL18 +WC DS CL17 +PG DS CL80 + YREGS + END CLOSEST diff --git a/Task/Closest-pair-problem/Haskell/closest-pair-problem-1.hs b/Task/Closest-pair-problem/Haskell/closest-pair-problem-1.hs index 5b9b891707..207202bde6 100644 --- a/Task/Closest-pair-problem/Haskell/closest-pair-problem-1.hs +++ b/Task/Closest-pair-problem/Haskell/closest-pair-problem-1.hs @@ -1,16 +1,23 @@ -import Data.List -import System.Random -import Control.Monad -import Control.Arrow -import Data.Ord +import Data.List (minimumBy, tails, unfoldr, foldl1') --' -vecLeng [[a,b],[p,q]] = sqrt $ (a-p)^2+(b-q)^2 +import System.Random (newStdGen, randomRs) -findClosestPair = foldl1' ((minimumBy (comparing vecLeng). ). (. return). (:)) . - concatMap (\(x:xs) -> map ((x:).return) xs) . init . tails +import Control.Arrow ((&&&)) + +import Data.Ord (comparing) + +vecLeng [[a, b], [p, q]] = sqrt $ (a - p) ^ 2 + (b - q) ^ 2 + +findClosestPair = + foldl1'' ((minimumBy (comparing vecLeng) .) . (. return) . (:)) . + concatMap (\(x:xs) -> map ((x :) . return) xs) . init . tails testCP = do - g <- newStdGen - let pts :: [[Double]] - pts = take 1000. unfoldr (Just. splitAt 2) $ randomRs(-1,1) g - print . (id &&& vecLeng ) . findClosestPair $ pts + g <- newStdGen + let pts :: [[Double]] + pts = take 1000 . unfoldr (Just . splitAt 2) $ randomRs (-1, 1) g + print . (id &&& vecLeng) . findClosestPair $ pts + +main = testCP + +foldl1'' = foldl1' diff --git a/Task/Closest-pair-problem/jq/closest-pair-problem-1.jq b/Task/Closest-pair-problem/Jq/closest-pair-problem-1.jq similarity index 100% rename from Task/Closest-pair-problem/jq/closest-pair-problem-1.jq rename to Task/Closest-pair-problem/Jq/closest-pair-problem-1.jq diff --git a/Task/Closest-pair-problem/jq/closest-pair-problem-2.jq b/Task/Closest-pair-problem/Jq/closest-pair-problem-2.jq similarity index 100% rename from Task/Closest-pair-problem/jq/closest-pair-problem-2.jq rename to Task/Closest-pair-problem/Jq/closest-pair-problem-2.jq diff --git a/Task/Closest-pair-problem/jq/closest-pair-problem-3.jq b/Task/Closest-pair-problem/Jq/closest-pair-problem-3.jq similarity index 100% rename from Task/Closest-pair-problem/jq/closest-pair-problem-3.jq rename to Task/Closest-pair-problem/Jq/closest-pair-problem-3.jq diff --git a/Task/Closest-pair-problem/Julia/closest-pair-problem.julia b/Task/Closest-pair-problem/Julia/closest-pair-problem.julia new file mode 100644 index 0000000000..32aa904e62 --- /dev/null +++ b/Task/Closest-pair-problem/Julia/closest-pair-problem.julia @@ -0,0 +1,16 @@ +function closestpair(P::Vector{Vector{T}}) where T <: Number + N = length(P) + if N < 2 return (Inf, ()) end + mindst = norm(P[1] - P[2]) + minpts = (P[1], P[2]) + for i in 1:N-1, j in i+1:N + tmpdst = norm(P[i] - P[j]) + if tmpdst < mindst + mindst = tmpdst + minpts = (P[i], P[j]) + end + end + return mindst, minpts +end + +closestpair([[0, -0.3], [1., 1.], [1.5, 2], [2, 2], [3, 3]]) diff --git a/Task/Closest-pair-problem/Kotlin/closest-pair-problem.kotlin b/Task/Closest-pair-problem/Kotlin/closest-pair-problem.kotlin new file mode 100644 index 0000000000..e2ddc9d0d9 --- /dev/null +++ b/Task/Closest-pair-problem/Kotlin/closest-pair-problem.kotlin @@ -0,0 +1,79 @@ +// version 1.1.2 + +typealias Point = Pair + +fun distance(p1: Point, p2: Point) = Math.hypot(p1.first- p2.first, p1.second - p2.second) + +fun bruteForceClosestPair(p: List): Pair> { + val n = p.size + if (n < 2) throw IllegalArgumentException("Must be at least two points") + var minPoints = p[0] to p[1] + var minDistance = distance(p[0], p[1]) + for (i in 0 until n - 1) + for (j in i + 1 until n) { + val dist = distance(p[i], p[j]) + if (dist < minDistance) { + minDistance = dist + minPoints = p[i] to p[j] + } + } + return minDistance to Pair(minPoints.first, minPoints.second) +} + +fun optimizedClosestPair(xP: List, yP: List): Pair> { + val n = xP.size + if (n <= 3) return bruteForceClosestPair(xP) + val xL = xP.take(n / 2) + val xR = xP.drop(n / 2) + val xm = xP[n / 2 - 1].first + val yL = yP.filter { it.first <= xm } + val yR = yP.filter { it.first > xm } + val (dL, pairL) = optimizedClosestPair(xL, yL) + val (dR, pairR) = optimizedClosestPair(xR, yR) + var dmin = dR + var pairMin = pairR + if (dL < dR) { + dmin = dL + pairMin = pairL + } + val yS = yP.filter { Math.abs(xm - it.first) < dmin } + val nS = yS.size + var closest = dmin + var closestPair = pairMin + for (i in 0 until nS - 1) { + var k = i + 1 + while (k < nS && (yS[k].second - yS[i].second < dmin)) { + val dist = distance(yS[k], yS[i]) + if (dist < closest) { + closest = dist + closestPair = Pair(yS[k], yS[i]) + } + k++ + } + } + return closest to closestPair +} + + +fun main(args: Array) { + val points = listOf( + listOf( + 5.0 to 9.0, 9.0 to 3.0, 2.0 to 0.0, 8.0 to 4.0, 7.0 to 4.0, + 9.0 to 10.0, 1.0 to 9.0, 8.0 to 2.0, 0.0 to 10.0, 9.0 to 6.0 + ), + listOf( + 0.654682 to 0.925557, 0.409382 to 0.619391, 0.891663 to 0.888594, + 0.716629 to 0.996200, 0.477721 to 0.946355, 0.925092 to 0.818220, + 0.624291 to 0.142924, 0.211332 to 0.221507, 0.293786 to 0.691701, + 0.839186 to 0.728260 + ) + ) + for (p in points) { + val (dist, pair) = bruteForceClosestPair(p) + println("Closest pair (brute force) is ${pair.first} and ${pair.second}, distance $dist") + val xP = p.sortedBy { it.first } + val yP = p.sortedBy { it.second } + val (dist2, pair2) = optimizedClosestPair(xP, yP) + println("Closest pair (optimized) is ${pair2.first} and ${pair2.second}, distance $dist2\n") + } +} diff --git a/Task/Closest-pair-problem/Zkl/closest-pair-problem-1.zkl b/Task/Closest-pair-problem/Zkl/closest-pair-problem-1.zkl new file mode 100644 index 0000000000..e689c4ea1c --- /dev/null +++ b/Task/Closest-pair-problem/Zkl/closest-pair-problem-1.zkl @@ -0,0 +1,15 @@ +class Point{ + fcn init(_x,_y){ var[const] x=_x, y=_y; } + fcn distance(p){ (p.x-x).hypot(p.y-y) } + fcn toString { String("Point(",x,",",y,")") } +} + + // find closest two points using brute ugly force: + // find all combinations of two points, measure distance, pick smallest +fcn closestPoints(points){ + pairs:=Utils.Helpers.pickNFrom(2,points); + triples:=pairs.apply(fcn([(p1,p2)]){ T(p1,p2,p1.distance(p2)) }); + triples.reduce(fcn([(_,_,d1)]p1,[(_,_,d2)]p2){ + if(d1 < d2) p1 else p2 + }); +} diff --git a/Task/Closest-pair-problem/Zkl/closest-pair-problem-2.zkl b/Task/Closest-pair-problem/Zkl/closest-pair-problem-2.zkl new file mode 100644 index 0000000000..dccd822a3f --- /dev/null +++ b/Task/Closest-pair-problem/Zkl/closest-pair-problem-2.zkl @@ -0,0 +1,15 @@ +points:=T( 5.0, 9.0, 9.0, 3.0, + 2.0, 0.0, 8.0, 4.0, + 7.0, 4.0, 9.0, 10.0, + 1.0, 9.0, 8.0, 2.0, + 0.0, 10.0, 9.0, 6.0 ).pump(List,Void.Read,Point); + +closestPoints(points).println(); //-->L(Point(8,4),Point(7,4),1) + +points:=T( 0.654682, 0.925557, 0.409382, 0.619391, + 0.891663, 0.888594, 0.716629, 0.9962, + 0.477721, 0.946355, 0.925092, 0.81822, + 0.624291, 0.142924, 0.211332, 0.221507, + 0.293786, 0.691701, 0.839186, 0.72826) + .pump(List,Void.Read,Point); +closestPoints(points).println(); diff --git a/Task/Closures-Value-capture/AppleScript/closures-value-capture-1.applescript b/Task/Closures-Value-capture/AppleScript/closures-value-capture-1.applescript index 31a69ece1a..646c0f9fbb 100644 --- a/Task/Closures-Value-capture/AppleScript/closures-value-capture-1.applescript +++ b/Task/Closures-Value-capture/AppleScript/closures-value-capture-1.applescript @@ -5,15 +5,13 @@ on run set end of fns to closure(i) end repeat - lambda() of item 3 of fns - + |λ|() of item 3 of fns end run - on closure(x) script - on lambda() - return x * x - end lambda + on |λ|() + x * x + end |λ| end script end closure diff --git a/Task/Closures-Value-capture/AppleScript/closures-value-capture-2.applescript b/Task/Closures-Value-capture/AppleScript/closures-value-capture-2.applescript index 4e30264da9..d1855b00fb 100644 --- a/Task/Closures-Value-capture/AppleScript/closures-value-capture-2.applescript +++ b/Task/Closures-Value-capture/AppleScript/closures-value-capture-2.applescript @@ -1,42 +1,54 @@ -on run +-- CLOSURE -------------------------------------------------------------------- - lambda() of (item 3 of (map(closure, range(1, 10)))) +script closure + on |λ|(x) + script + on |λ|() + x * x + end |λ| + end script + end |λ| +end script -end run - -on closure(x) - script - on lambda() - return x * x - end lambda - end script -end closure +|λ|() of (item 3 of (map(closure, enumFromTo(1, 10)))) +-- GENERIC FUNCTIONS ---------------------------------------------------------- --- GENERIC FUNCTIONS +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if n < m then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- map :: (a -> b) -> [a] -> [b] on map(f, xs) - script mf - property lambda : f - end script - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to mf's lambda(item i of xs, i, xs) - end repeat - return lst + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell end map - --- range :: Int -> Int -> Int -on range(m, n) - set lng to (n - m) + 1 - set base to m - 1 - set lst to {} - repeat with i from 1 to lng - set end of lst to i + base - end repeat - return lst -end range +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn diff --git a/Task/Closures-Value-capture/Elena/closures-value-capture.elena b/Task/Closures-Value-capture/Elena/closures-value-capture.elena index 8a5f0ec9b1..a56552550c 100644 --- a/Task/Closures-Value-capture/Elena/closures-value-capture.elena +++ b/Task/Closures-Value-capture/Elena/closures-value-capture.elena @@ -1,3 +1,8 @@ -#var list := Array new &length:10 set &every: (&index:i) [ [ ^ i * i. ] ]. +import system'routines. -console writeLine:(list@3 eval). +program = +[ + var functions := Array new length:10; populate(:i)( [ ^ i * i ] ). + + functions forEach(:func) [ console writeLine(func eval). ]. +]. diff --git a/Task/Closures-Value-capture/Kotlin/closures-value-capture.kotlin b/Task/Closures-Value-capture/Kotlin/closures-value-capture.kotlin new file mode 100644 index 0000000000..59ab82b0cf --- /dev/null +++ b/Task/Closures-Value-capture/Kotlin/closures-value-capture.kotlin @@ -0,0 +1,8 @@ +// version 1.0.6 + +fun main(args: Array) { + // create an array of 10 anonymous functions which return the square of their index + val funcs = Array(10){ fun(): Int = it * it } + // call all but the last + (0 .. 8).forEach { println(funcs[it]()) } +} diff --git a/Task/Closures-Value-capture/Phix/closures-value-capture-1.phix b/Task/Closures-Value-capture/Phix/closures-value-capture-1.phix new file mode 100644 index 0000000000..f9d1cbd506 --- /dev/null +++ b/Task/Closures-Value-capture/Phix/closures-value-capture-1.phix @@ -0,0 +1,35 @@ +-- First some generic handling stuff, handles partial_args +-- of any mixture of any length and element types. +sequence closures = {} +function add_closure(integer rid, sequence partial_args) + closures = append(closures,{rid,partial_args}) + return length(closures) -- (return an integer id) +end function + +function call_closure(integer id, sequence args) + {integer rid, sequence partial_args} = closures[id] + return call_func(rid,partial_args&args) +end function + +-- The test routine to be made into a closure, or ten +-- Note that all external references/captured variables must +-- be passed as arguments, and grouped together on the lhs +function square(integer i) + return i*i +end function + +-- Create the ten closures as asked for. +-- Here, cids is just {1,2,3,4,5,6,7,8,9,10}, however ids would be more +-- useful for a mixed bag of closures, possibly stored all over the shop. +-- Likewise add_closure could have been a procedure for this demo, but +-- you would probably want the function in a real-world application. +sequence cids = {} +for i=1 to 10 do +--for i=11 to 20 do -- alternative test + cids &= add_closure(routine_id("square"),{i}) +end for +-- And finally call em (this loop is blissfully unaware what function +-- it is actually calling, and what partial_arguments it is passing) +for i=1 to 10 do + printf(1," %d",call_closure(cids[i],{})) +end for diff --git a/Task/Closures-Value-capture/Phix/closures-value-capture-2.phix b/Task/Closures-Value-capture/Phix/closures-value-capture-2.phix new file mode 100644 index 0000000000..d07a073f0a --- /dev/null +++ b/Task/Closures-Value-capture/Phix/closures-value-capture-2.phix @@ -0,0 +1,13 @@ +function square(integer tid) + integer i = getd("i",tid) -- (setd valid here too) + return i*i +end function + +sequence tids = {} +for i=1 to 10 do +--for i=11 to 20 do + tids &= new_dict({{"i",i}}) +end for +for i=1 to 10 do + printf(1," %d",square(tids[i])) +end for diff --git a/Task/Closures-Value-capture/Ruby/closures-value-capture-1.rb b/Task/Closures-Value-capture/Ruby/closures-value-capture-1.rb deleted file mode 100644 index 5f5c50450b..0000000000 --- a/Task/Closures-Value-capture/Ruby/closures-value-capture-1.rb +++ /dev/null @@ -1,6 +0,0 @@ -list = {} -(1..10).each {|i| list[i] = proc {i * i}} -p list[3].call #=> 9 -p list[7][] #=> 49 -i = 5 -p list[3].call #=> 9 diff --git a/Task/Closures-Value-capture/Ruby/closures-value-capture-2.rb b/Task/Closures-Value-capture/Ruby/closures-value-capture-2.rb deleted file mode 100644 index 15500756e0..0000000000 --- a/Task/Closures-Value-capture/Ruby/closures-value-capture-2.rb +++ /dev/null @@ -1,5 +0,0 @@ -list = {} -for i in 1..10 do list[i] = proc {i * i} end -p list[3][] #=> 100 -i = 5 -p list[3][] #=> 25 diff --git a/Task/Closures-Value-capture/Sidef/closures-value-capture-1.sidef b/Task/Closures-Value-capture/Sidef/closures-value-capture-1.sidef index 415af77fda..17cd66da6b 100644 --- a/Task/Closures-Value-capture/Sidef/closures-value-capture-1.sidef +++ b/Task/Closures-Value-capture/Sidef/closures-value-capture-1.sidef @@ -1,7 +1,7 @@ var f = ( - 0 ..^ 9 -> map {|i| func(j){i * j} } -); + 10.of {|i| func(j){i * j} } +) -0 ..^ 8 -> each { |j| - say f[j](j); +9.times { |j| + say f[j](j) } diff --git a/Task/Closures-Value-capture/Sidef/closures-value-capture-2.sidef b/Task/Closures-Value-capture/Sidef/closures-value-capture-2.sidef index 6610323e34..69014ff377 100644 --- a/Task/Closures-Value-capture/Sidef/closures-value-capture-2.sidef +++ b/Task/Closures-Value-capture/Sidef/closures-value-capture-2.sidef @@ -1,7 +1,7 @@ -var f = 10.of { |i| +var f = (1..10).map { |i| func(j){i * j} } -9.times { |j| - say f[j-1](j); +for j (1..9) { + say f[j-1](j) } diff --git a/Task/Closures-Value-capture/Zkl/closures-value-capture.zkl b/Task/Closures-Value-capture/Zkl/closures-value-capture.zkl new file mode 100644 index 0000000000..8ef92baf86 --- /dev/null +++ b/Task/Closures-Value-capture/Zkl/closures-value-capture.zkl @@ -0,0 +1,4 @@ +(0).pump(10,List,fcn(i){i*i}.fp)[8]() //-->64 +list:=(0).pump(10,List,fcn(i){i*i}.fp); +foreach n in (list.len()-1) { list[n]().println() } +list.run(True).println() diff --git a/Task/Collections/Aime/collections-3.aime b/Task/Collections/Aime/collections-3.aime index 3f2486f91e..0b4660d806 100644 --- a/Task/Collections/Aime/collections-3.aime +++ b/Task/Collections/Aime/collections-3.aime @@ -1,3 +1,4 @@ -l_query(l, 2); -l_head(l); -l_q_text(l, 1); +l_query(l, 2) +l_head(l) +l_q_text(l, 1) +l[3] diff --git a/Task/Collections/Aime/collections-5.aime b/Task/Collections/Aime/collections-5.aime index 12b9dd2faa..ba14f62bdc 100644 --- a/Task/Collections/Aime/collections-5.aime +++ b/Task/Collections/Aime/collections-5.aime @@ -1,2 +1,3 @@ r_p_integer(r, "key1", 7); r_put(r, "key2", "a string"); +r["key3"] = .25; diff --git a/Task/Collections/Aime/collections-6.aime b/Task/Collections/Aime/collections-6.aime index 3a2750998f..ed9fa673fe 100644 --- a/Task/Collections/Aime/collections-6.aime +++ b/Task/Collections/Aime/collections-6.aime @@ -1,2 +1,3 @@ -r_query(r, "key1"); -r_tail(r); +r_query(r, "key1") +r_tail(r) +r["key2"] diff --git a/Task/Collections/Elena/collections-1.elena b/Task/Collections/Elena/collections-1.elena index 5fc0e307a6..dfa8f709f0 100644 --- a/Task/Collections/Elena/collections-1.elena +++ b/Task/Collections/Elena/collections-1.elena @@ -1,5 +1,5 @@ // Creates and initializes a new Array -#var intArray := (1, 2, 3, 4, 5). +var intArray := (1, 2, 3, 4, 5). -#var stringArr := Array new:5. -stringArr@0 := "string". +var stringArr := Array new:5. +stringArr[0] := "string". diff --git a/Task/Collections/Elena/collections-2.elena b/Task/Collections/Elena/collections-2.elena index a661e7e3e2..a4fa63743b 100644 --- a/Task/Collections/Elena/collections-2.elena +++ b/Task/Collections/Elena/collections-2.elena @@ -1,5 +1,5 @@ //Create and initialize ArrayList -#var myAl := ArrayList new += "Hello" += "World" += "!". +var myAl := ArrayList new; append:"Hello"; append:"World"; append:"!". //Create and initialize List -#var myList := List new += "Hello" += "World" += "!". +var myList := List new; append:"Hello"; append:"World"; append:"!". diff --git a/Task/Collections/Elena/collections-3.elena b/Task/Collections/Elena/collections-3.elena index 26e226b7c8..8f24be9874 100644 --- a/Task/Collections/Elena/collections-3.elena +++ b/Task/Collections/Elena/collections-3.elena @@ -1,4 +1,4 @@ //Create a dictionary -#var dict := Dictionary new. -dict@"Hello" := "World". -dict@"Key" := "Value". +var dict := Dictionary new. +dict["Hello"] := "World". +dict["Key"] := "Value". diff --git a/Task/Collections/Fortran/collections-1.f b/Task/Collections/Fortran/collections-1.f new file mode 100644 index 0000000000..a67914ed60 --- /dev/null +++ b/Task/Collections/Fortran/collections-1.f @@ -0,0 +1,3 @@ + REAL A(36) !Declares a one-dimensional array A(1), A(2), ... A(36) + A(1) = 1 !Assigns a value to the first element. + A(2) = 3*A(1) + 5 !The second element gets 8. diff --git a/Task/Collections/Fortran/collections-2.f b/Task/Collections/Fortran/collections-2.f new file mode 100644 index 0000000000..80a748e4ee --- /dev/null +++ b/Task/Collections/Fortran/collections-2.f @@ -0,0 +1,7 @@ + TYPE(MIXED) !Name the "type". + INTEGER COUNTER !Its content is listed. + REAL WEIGHT,DEPTH + CHARACTER*28 MARKNAME + COMPLEX PATH(6) !The mixed collection includes an array. + END TYPE MIXED + TYPE(MIXED) TEMP,A(6) !Declare some items of that type. diff --git a/Task/Collections/Haskell/collections-5.hs b/Task/Collections/Haskell/collections-5.hs new file mode 100644 index 0000000000..349d68f739 --- /dev/null +++ b/Task/Collections/Haskell/collections-5.hs @@ -0,0 +1,19 @@ +import Data.Array (Array, listArray, Ix, (!)) + +triples :: Array Int (Char, String, String) +triples = + listArray (0, 11) $ + zip3 + "鼠牛虎兔龍蛇馬羊猴鸡狗豬" -- 生肖 shengxiao – symbolic animals + (words "shǔ niú hǔ tù lóng shé mǎ yáng hóu jī gǒu zhū") + (words "rat ox tiger rabbit dragon snake horse goat monkey rooster dog pig") + +indexedItem + :: Ix i + => Array i (Char, String, String) -> i -> String +indexedItem a n = + let (c, w, w1) = a ! n + in c : unwords ["\t", w, w1] + +main :: IO () +main = (putStrLn . unlines) $ indexedItem triples <$> [2, 4, 6] diff --git a/Task/Collections/Haskell/collections-6.hs b/Task/Collections/Haskell/collections-6.hs new file mode 100644 index 0000000000..4dcef60658 --- /dev/null +++ b/Task/Collections/Haskell/collections-6.hs @@ -0,0 +1,20 @@ +import qualified Data.Map as M +import Data.Maybe (isJust) + +mapSample :: M.Map String Int +mapSample = + M.fromList + [ ("alpha", 1) + , ("beta", 2) + , ("gamma", 3) + , ("delta", 4) + , ("epsilon", 5) + , ("zeta", 6) + ] + +maybeValue :: String -> Maybe Int +maybeValue = flip M.lookup mapSample + +main :: IO () +main = + print $ sequence $ filter isJust (maybeValue <$> ["beta", "delta", "zeta"]) diff --git a/Task/Collections/Haskell/collections-7.hs b/Task/Collections/Haskell/collections-7.hs new file mode 100644 index 0000000000..d926ce74a5 --- /dev/null +++ b/Task/Collections/Haskell/collections-7.hs @@ -0,0 +1,10 @@ +import qualified Data.Set as S + +setA :: S.Set String +setA = S.fromList ["alpha", "beta", "gamma", "delta", "epsilon"] + +setB :: S.Set String +setB = S.fromList ["delta", "epsilon", "zeta", "eta", "theta"] + +main :: IO () +main = (print . S.toList) (S.intersection setA setB) diff --git a/Task/Collections/jq/collections-1.jq b/Task/Collections/Jq/collections-1.jq similarity index 100% rename from Task/Collections/jq/collections-1.jq rename to Task/Collections/Jq/collections-1.jq diff --git a/Task/Collections/jq/collections-2.jq b/Task/Collections/Jq/collections-2.jq similarity index 100% rename from Task/Collections/jq/collections-2.jq rename to Task/Collections/Jq/collections-2.jq diff --git a/Task/Collections/jq/collections-3.jq b/Task/Collections/Jq/collections-3.jq similarity index 100% rename from Task/Collections/jq/collections-3.jq rename to Task/Collections/Jq/collections-3.jq diff --git a/Task/Collections/Kotlin/collections.kotlin b/Task/Collections/Kotlin/collections.kotlin new file mode 100644 index 0000000000..eef42fe3ab --- /dev/null +++ b/Task/Collections/Kotlin/collections.kotlin @@ -0,0 +1,43 @@ +import java.util.PriorityQueue + +fun main(args: Array) { + // generic array + val ga = arrayOf(1, 2, 3) + println(ga.joinToString(prefix = "[", postfix = "]")) + + // specialized array (one for each primitive type) + val da = doubleArrayOf(4.0, 5.0, 6.0) + println(da.joinToString(prefix = "[", postfix = "]")) + + // immutable list + val li = listOf(7, 8, 9) + println(li) + + // mutable list + val ml = mutableListOf() + ml.add(10); ml.add(11); ml.add(12) + println(ml) + + // immutable map + val hm = mapOf('a' to 97, 'b' to 98, 'c' to 99) + println(hm) + + // mutable map + val mm = mutableMapOf() + mm.put('d', 100); mm.put('e', 101); mm.put('f', 102) + println(mm) + + // immutable set (duplicates not allowed) + val se = setOf(1, 2, 3) + println(se) + + // mutable set (duplicates not allowed) + val ms = mutableSetOf() + ms.add(4L); ms.add(5L); ms.add(6L) + println(ms) + + // priority queue (imported from Java) + val pq = PriorityQueue() + pq.add("First"); pq.add("Second"); pq.add("Third") + println(pq) +} diff --git a/Task/Collections/OoRexx/collections-1.rexx b/Task/Collections/OoRexx/collections-1.rexx new file mode 100644 index 0000000000..a75bfee9f1 --- /dev/null +++ b/Task/Collections/OoRexx/collections-1.rexx @@ -0,0 +1,5 @@ +a = .array~new(4) -- creates an array of 4 items, with all slots empty +say a~size a~items -- size is 4, but there are 0 items +a[1] = "Fred" -- assigns a value to the first item +a[5] = "Mike" -- assigns a value to the fifth slot, expanding the size +say a~size a~items -- size is now 5, with 2 items diff --git a/Task/Collections/OoRexx/collections-2.rexx b/Task/Collections/OoRexx/collections-2.rexx new file mode 100644 index 0000000000..d66f2c2dfa --- /dev/null +++ b/Task/Collections/OoRexx/collections-2.rexx @@ -0,0 +1,9 @@ +l = .list~new -- lists have no inherent size +index = l~insert('123') -- adds an item to this list, returning the index +l~insert('Fred', .nil) -- inserts this at the beginning +l~insert('Mike') -- adds this to the end +l~insert('Rick', index) -- inserts this after '123' +l[index] = l[index] + 1 -- the original item is now '124' +do item over l -- iterate over the items, displaying them in order + say item +end diff --git a/Task/Collections/OoRexx/collections-3.rexx b/Task/Collections/OoRexx/collections-3.rexx new file mode 100644 index 0000000000..74bae4baa6 --- /dev/null +++ b/Task/Collections/OoRexx/collections-3.rexx @@ -0,0 +1,7 @@ +q = .queue~of(2,4,6) -- creates a queue containing 3 items +say q[1] q[3] -- displays "2 6" +i = q~pull -- removes the first item +q~queue(i) -- adds it to the end +say q[1] q[3] -- displays "4 2" +q[1] = q[1] + 1 -- updates the first item +say q[1] q[3] -- displays "5 2" diff --git a/Task/Collections/OoRexx/collections-4.rexx b/Task/Collections/OoRexx/collections-4.rexx new file mode 100644 index 0000000000..d35e4eb1f5 --- /dev/null +++ b/Task/Collections/OoRexx/collections-4.rexx @@ -0,0 +1,4 @@ +t = .table~new +t['abc'] = 1 +t['def'] = 2 +say t['abc'] t['def'] -- displays "1 2" diff --git a/Task/Collections/OoRexx/collections-5.rexx b/Task/Collections/OoRexx/collections-5.rexx new file mode 100644 index 0000000000..35e4c7e01d --- /dev/null +++ b/Task/Collections/OoRexx/collections-5.rexx @@ -0,0 +1,12 @@ +t = .table~new -- a table example to demonstrate the difference +t['abc'] = 1 -- sets an item at index 'abc' +t['abc'] = 2 -- updates that item +say t~items t['abc'] -- displays "1 2" +r = .relation~new +r['abc'] = 1 -- sets an item at index 'abc' +r['abc'] = 2 -- adds an additional item at the same index +say r~items r['abc'] -- displays "2 2" this has two items in it now + +do item over r~allAt('abc') -- retrieves all items at the index 'abc' + say item +end diff --git a/Task/Collections/OoRexx/collections-6.rexx b/Task/Collections/OoRexx/collections-6.rexx new file mode 100644 index 0000000000..fba1bbd62c --- /dev/null +++ b/Task/Collections/OoRexx/collections-6.rexx @@ -0,0 +1,4 @@ +d = .directory~new +d['abc'] = 1 +d['def'] = 2 +say d['abc'] d['def'] -- displays "1 2" diff --git a/Task/Collections/OoRexx/collections-7.rexx b/Task/Collections/OoRexx/collections-7.rexx new file mode 100644 index 0000000000..7f00de885f --- /dev/null +++ b/Task/Collections/OoRexx/collections-7.rexx @@ -0,0 +1,4 @@ +d = .directory~new +d~abc = 1 +d~def = 2 +say d~abc d~def -- displays "1 2" diff --git a/Task/Collections/OoRexx/collections-8.rexx b/Task/Collections/OoRexx/collections-8.rexx new file mode 100644 index 0000000000..7869bb33b3 --- /dev/null +++ b/Task/Collections/OoRexx/collections-8.rexx @@ -0,0 +1,7 @@ +s = .set~new +text = "the quick brown fox jumped over the lazy dog" +do word over text~makearray(' ') + s~put(word) +end + +say "text has" text~words", but only" s~items "unique words" diff --git a/Task/Collections/Perl-6/collections-5.pl6 b/Task/Collections/Perl-6/collections-5.pl6 deleted file mode 100644 index 6cbaff4448..0000000000 --- a/Task/Collections/Perl-6/collections-5.pl6 +++ /dev/null @@ -1,2 +0,0 @@ -my $s = KeySet.new: ; -$s ∪= ; diff --git a/Task/Collections/Perl-6/collections-6.pl6 b/Task/Collections/Perl-6/collections-6.pl6 deleted file mode 100644 index 7aa1952364..0000000000 --- a/Task/Collections/Perl-6/collections-6.pl6 +++ /dev/null @@ -1,2 +0,0 @@ -my $bag = bag ; -my $newbag = $bag ∪ ; diff --git a/Task/Collections/Perl-6/collections-7.pl6 b/Task/Collections/Perl-6/collections-7.pl6 deleted file mode 100644 index fee571b488..0000000000 --- a/Task/Collections/Perl-6/collections-7.pl6 +++ /dev/null @@ -1,2 +0,0 @@ -my $b = KeySet.new: ; -$b ∪= ; diff --git a/Task/Collections/Perl-6/collections-8.pl6 b/Task/Collections/Perl-6/collections-8.pl6 deleted file mode 100644 index 5ee9da14e8..0000000000 --- a/Task/Collections/Perl-6/collections-8.pl6 +++ /dev/null @@ -1,2 +0,0 @@ -my $tail = d => e => f => Nil; -my $new = a => b => c => $tail; diff --git a/Task/Collections/Perl-6/collections-9.pl6 b/Task/Collections/Perl-6/collections-9.pl6 deleted file mode 100644 index 54e6ff9d1f..0000000000 --- a/Task/Collections/Perl-6/collections-9.pl6 +++ /dev/null @@ -1,2 +0,0 @@ -my $obj = Something.new: foo => 1, bar => 2; -my $newobj = $obj but role { has $.baz = 3 } # anonymous mixin diff --git a/Task/Collections/PowerShell/collections-1.psh b/Task/Collections/PowerShell/collections-1.psh new file mode 100644 index 0000000000..1df6d3796c --- /dev/null +++ b/Task/Collections/PowerShell/collections-1.psh @@ -0,0 +1,47 @@ +# Create an Array by separating the elements with commas: +$array = "one", 2, "three", 4 + +# Using explicit syntax: +$array = @("one", 2, "three", 4) + +# Send the values back into individual variables: +$var1, $var2, $var3, $var4 = $array + +# An array of several integer ([int]) values: +$array = 0, 1, 2, 3, 4, 5, 6, 7 + +# Using the range operator (..): +$array = 0..7 + +# Strongly typed: +[int[]] $stronglyTypedArray = 1, 2, 4, 8, 16, 32, 64, 128 + +# An empty array: +$array = @() + +# An array with a single element: +$array = @("one") + +# I suppose this would be a jagged array: +$jaggedArray = @((11, 12, 13), + (21, 22, 23), + (31, 32, 33)) + +$jaggedArray | Format-Wide {$_} -Column 3 -Force + +$jaggedArray[1][1] # returns 22 + +# A Multi-dimensional array: +$multiArray = New-Object -TypeName "System.Object[,]" -ArgumentList 6,6 + +for ($i = 0; $i -lt 6; $i++) +{ + for ($j = 0; $j -lt 6; $j++) + { + $multiArray[$i,$j] = ($i + 1) * 10 + ($j + 1) + } +} + +$multiArray | Format-Wide {$_} -Column 6 -Force + +$multiArray[2,2] # returns 33 diff --git a/Task/Collections/PowerShell/collections-2.psh b/Task/Collections/PowerShell/collections-2.psh new file mode 100644 index 0000000000..c565d63325 --- /dev/null +++ b/Task/Collections/PowerShell/collections-2.psh @@ -0,0 +1,46 @@ +# An empty Hash Table: +$hash = @{} + +# A Hash table populated with some values: +$nfcCentralDivision = @{ + Packers = "Green Bay" + Bears = "Chicago" + Lions = "Detroit" +} + +# Add items to a Hash Table: +$nfcCentralDivision.Add("Vikings","Minnesota") +$nfcCentralDivision.Add("Buccaneers","Tampa Bay") + +# Remove an item from a Hash Table: +$nfcCentralDivision.Remove("Buccaneers") + +# Searching for items +$nfcCentralDivision.ContainsKey("Packers") +$nfcCentralDivision.ContainsValue("Green Bay") + +# A bad value... +$hash1 = @{ + One = 1 + Two = 3 +} + +# Edit an item in a Hash Table: +$hash1.Set_Item("Two",2) + +# Combine Hash Tables: + +$hash2 = @{ + Three = 3 + Four = 4 +} + +$hash1 + $hash2 + +# Using the ([ordered]) accelerator the items in the Hash Table retain the order in which they were input: +$nfcCentralDivision = [ordered]@{ + Bears = "Chicago" + Lions = "Detroit" + Packers = "Green Bay" + Vikings = "Minnesota" +} diff --git a/Task/Collections/PowerShell/collections-3.psh b/Task/Collections/PowerShell/collections-3.psh new file mode 100644 index 0000000000..bd8157e756 --- /dev/null +++ b/Task/Collections/PowerShell/collections-3.psh @@ -0,0 +1,9 @@ +$list = New-Object -TypeName System.Collections.ArrayList -ArgumentList 1,2,3 + +# or... + +$list = [System.Collections.ArrayList]@(1,2,3) + + +$list.Add(4) | Out-Null +$list.RemoveAt(2) diff --git a/Task/Collections/Ring/collections.ring b/Task/Collections/Ring/collections.ring new file mode 100644 index 0000000000..ddeacd7d32 --- /dev/null +++ b/Task/Collections/Ring/collections.ring @@ -0,0 +1,4 @@ +text = list(2) +text[1] = "Hello " +text[2] = "world!" +see text[1] + text[2] + nl diff --git a/Task/Collections/Scheme/collections-7.ss b/Task/Collections/Scheme/collections-7.ss deleted file mode 100644 index 51b630f818..0000000000 --- a/Task/Collections/Scheme/collections-7.ss +++ /dev/null @@ -1 +0,0 @@ -(append lst ...) diff --git a/Task/Collections/Scheme/collections-8.ss b/Task/Collections/Scheme/collections-8.ss deleted file mode 100644 index 420c173fcc..0000000000 --- a/Task/Collections/Scheme/collections-8.ss +++ /dev/null @@ -1,2 +0,0 @@ -(display (append (list 1 2 3) (list 4 5 6))) -(newline) diff --git a/Task/Collections/Scheme/collections-9.ss b/Task/Collections/Scheme/collections-9.ss deleted file mode 100644 index c319ae6800..0000000000 --- a/Task/Collections/Scheme/collections-9.ss +++ /dev/null @@ -1 +0,0 @@ -(1 2 3 4 5 6) diff --git a/Task/Collections/Seed7/collections-3.seed7 b/Task/Collections/Seed7/collections-3.seed7 index ba69c66926..ab09f5949d 100644 --- a/Task/Collections/Seed7/collections-3.seed7 +++ b/Task/Collections/Seed7/collections-3.seed7 @@ -12,5 +12,5 @@ const proc: main is func aHash @:= ["helium"] "noble gas"; for aValue key aKey range aHash do writeln(aKey <& ": " <& aValue); - end for; + end for;a end func; diff --git a/Task/Collections/Setl4/collections-1.setl4 b/Task/Collections/Setl4/collections-1.setl4 new file mode 100644 index 0000000000..f007fe4125 --- /dev/null +++ b/Task/Collections/Setl4/collections-1.setl4 @@ -0,0 +1,9 @@ +set = new('set 5 10 15 20 25 25') +add(set,30) +show(set) + +show.eval('member(set,5)') +show.eval('member(set,6)') + +show.eval("exists(set,'eq(this,10)')") +show.eval("forall(set,'eq(this,40)')") diff --git a/Task/Collections/Setl4/collections-2.setl4 b/Task/Collections/Setl4/collections-2.setl4 new file mode 100644 index 0000000000..24bd07c467 --- /dev/null +++ b/Task/Collections/Setl4/collections-2.setl4 @@ -0,0 +1,4 @@ +iter = new('iter 1 10 2') +show(iter) +show.eval("eq(set.size(iter),5)") +show.eval('member(iter,5)') diff --git a/Task/Collections/Setl4/collections-3.setl4 b/Task/Collections/Setl4/collections-3.setl4 new file mode 100644 index 0000000000..3a3246aa55 --- /dev/null +++ b/Task/Collections/Setl4/collections-3.setl4 @@ -0,0 +1,7 @@ +map = new('map one:1 two:2 ten:10 forty:40 hundred:100 thousand:1000') +show(map) + +show.eval("eq(get(map,'one'),1)") +show.eval("eq(get(map,'one'),6)") +show.eval("exists(map,'eq(get(map,this),2)')") +show.eval("forall(map,'eq(get(map,this),2)')") diff --git a/Task/Collections/VBA/collections.vba b/Task/Collections/VBA/collections.vba new file mode 100644 index 0000000000..b871c63f6a --- /dev/null +++ b/Task/Collections/VBA/collections.vba @@ -0,0 +1,3 @@ +Dim coll As New Collection +coll.Add "apple" +coll.Add "banana" diff --git a/Task/Collections/Zkl/collections.zkl b/Task/Collections/Zkl/collections.zkl new file mode 100644 index 0000000000..2e492d1175 --- /dev/null +++ b/Task/Collections/Zkl/collections.zkl @@ -0,0 +1,10 @@ +Lists: L(1,2,3).append(4); //-->L(1,2,3,4), mutable list +Read only list: ROList(1,2,3).append(4); // creates two lists + +Bit bucket: Data(0,Int,1,2,3) // three bytes + The "Int" means treat contents as a byte stream +Data(0,Int,"foo ","bar") //-->7 bytes + Data(0,Int,"foo ").append("bar") //ditto + Data(0,Int,"foo\n","bar").readln() //-->"foo\n" +Data(0,String,"foo ","bar") //-->9 bytes (2 \0s) + Data(0,String,"foo ").append("bar").readln() //-->"foo " diff --git a/Task/Color-of-a-screen-pixel/00DESCRIPTION b/Task/Color-of-a-screen-pixel/00DESCRIPTION index 87d1c9bbc6..2351304009 100644 --- a/Task/Color-of-a-screen-pixel/00DESCRIPTION +++ b/Task/Color-of-a-screen-pixel/00DESCRIPTION @@ -1 +1,5 @@ -Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related. +;Task: +Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. + +The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related. +

    diff --git a/Task/Color-of-a-screen-pixel/Kotlin/color-of-a-screen-pixel.kotlin b/Task/Color-of-a-screen-pixel/Kotlin/color-of-a-screen-pixel.kotlin index bb2c27b458..9adecf951a 100644 --- a/Task/Color-of-a-screen-pixel/Kotlin/color-of-a-screen-pixel.kotlin +++ b/Task/Color-of-a-screen-pixel/Kotlin/color-of-a-screen-pixel.kotlin @@ -1,9 +1,7 @@ -import java.awt.Color -import java.awt.MouseInfo -import java.awt.Robot +import java.awt.* fun getMouseColor(): Color { - val location = MouseInfo.getPointerInfo().getLocation() + val location = MouseInfo.getPointerInfo().location return getColorAt(location.x, location.y) } diff --git a/Task/Color-of-a-screen-pixel/Phix/color-of-a-screen-pixel.phix b/Task/Color-of-a-screen-pixel/Phix/color-of-a-screen-pixel.phix new file mode 100644 index 0000000000..cd17bdeb1a --- /dev/null +++ b/Task/Color-of-a-screen-pixel/Phix/color-of-a-screen-pixel.phix @@ -0,0 +1 @@ +integer {r,g,b} = im_pixel(image, x, y) diff --git a/Task/Color-quantization/Common-Lisp/color-quantization.lisp b/Task/Color-quantization/Common-Lisp/color-quantization.lisp new file mode 100644 index 0000000000..1ac3ffde6a --- /dev/null +++ b/Task/Color-quantization/Common-Lisp/color-quantization.lisp @@ -0,0 +1,66 @@ +(defpackage #:quantize + (:use #:cl + #:opticl)) + +(in-package #:quantize) + +(defun image->pixels (image) + (check-type image 8-bit-rgb-image) + (let (pixels) + (do-pixels (y x) image + (push (pixel* image y x) pixels)) + pixels)) + +(defun greatest-color-range (pixels) + (loop for (r g b) in pixels + minimize r into r-min + minimize g into g-min + minimize b into b-min + maximize r into r-max + maximize g into g-max + maximize b into b-max + finally + (return (let* ((r-range (- r-max r-min)) + (g-range (- g-max g-min)) + (b-range (- b-max b-min)) + (max-range (max r-range g-range b-range))) + (cond ((= r-range max-range) 0) + ((= g-range max-range) 1) + (t 2)))))) + +(defun median-cut (pixels target-num-colors) + (assert (zerop (mod (log target-num-colors 2) 1))) + (if (or (= target-num-colors 1) (null (rest pixels))) + (list pixels) + (let* ((channel (greatest-color-range pixels)) + (sorted (sort pixels #'< :key (lambda (pixel) (nth channel pixel)))) + (half (floor (length sorted) 2)) + (next-target (/ target-num-colors 2))) + (nconc (median-cut (subseq sorted 0 half) next-target) + (median-cut (subseq sorted half) next-target))))) + +(defun quantize-colors (pixels target-num-colors) + (let ((color-map (make-hash-table :test #'equal))) + (dolist (bucket (median-cut pixels target-num-colors) color-map) + (loop for (r g b) in bucket + sum r into r-sum + sum g into g-sum + sum b into b-sum + count t into num-pixels + finally (let ((average (list (round r-sum num-pixels) + (round g-sum num-pixels) + (round b-sum num-pixels)))) + (dolist (pixel bucket) + (setf (gethash pixel color-map) average))))))) + +(defun quantize-image (input-file output-file target-num-colors) + (let* ((image (read-png-file input-file)) + (pixels (image->pixels image)) + (color-map (quantize-colors pixels target-num-colors)) + (result-image (with-image-bounds (height width) image + (make-8-bit-rgb-image height width :initial-element 0)))) + (set-pixels (y x) result-image + (let* ((original (multiple-value-list (pixel image y x))) + (quantized (gethash original color-map))) + (values-list quantized))) + (write-png-file output-file result-image))) diff --git a/Task/Color-quantization/Python/color-quantization.py b/Task/Color-quantization/Python/color-quantization.py new file mode 100644 index 0000000000..3a6a16736b --- /dev/null +++ b/Task/Color-quantization/Python/color-quantization.py @@ -0,0 +1,6 @@ +from PIL import Image + +if __name__=="__main__": + im = Image.open("frog.png") + im2 = im.quantize(16) + im2.show() diff --git a/Task/Colour-bars-Display/BBC-BASIC/colour-bars-display.bbc b/Task/Colour-bars-Display/BBC-BASIC/colour-bars-display.bbc deleted file mode 100644 index 41071ffd28..0000000000 --- a/Task/Colour-bars-Display/BBC-BASIC/colour-bars-display.bbc +++ /dev/null @@ -1,19 +0,0 @@ - SW_MAXIMIZE = 3 - SYS "ShowWindow", @hwnd%, SW_MAXIMIZE - VDU 26 - - W% = @vdu%!208 / 4 - H% = @vdu%!212 * 2 - - COLOUR 1,9 - COLOUR 2,10 - COLOUR 3,12 - COLOUR 4,13 - COLOUR 5,14 - COLOUR 6,11 - COLOUR 7,15 - - FOR C% = 0 TO 7 - GCOL C% - RECTANGLE FILL C%*W%, 0, W%, H% - NEXT diff --git a/Task/Colour-bars-Display/FreeBASIC/colour-bars-display.freebasic b/Task/Colour-bars-Display/FreeBASIC/colour-bars-display.freebasic index e504d88964..39683014b1 100644 --- a/Task/Colour-bars-Display/FreeBASIC/colour-bars-display.freebasic +++ b/Task/Colour-bars-Display/FreeBASIC/colour-bars-display.freebasic @@ -8,10 +8,8 @@ Locate ,, 0 '' turn cursor off For clr As UInteger = 0 To 15 Color 0, clr For row As Integer = 1 to 25 - For col As UInteger = 1 To 5 - Locate row, clr * 5 + 1 - Print Space(5); - Next col + Locate row, clr * 5 + 1 + Print Space(5); Next row Next clr diff --git a/Task/Colour-bars-Display/Gambas/colour-bars-display.gambas b/Task/Colour-bars-Display/Gambas/colour-bars-display.gambas new file mode 100644 index 0000000000..35ad124234 --- /dev/null +++ b/Task/Colour-bars-Display/Gambas/colour-bars-display.gambas @@ -0,0 +1,19 @@ +Public Sub Form_Open() +Dim iColour As Integer[] = [Color.Black, Color.red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.white] +Dim hPanel As Panel +Dim siCount As Short + +With Me + .Arrangement = Arrange.Horizontal + .Height = 300 + .Width = 400 +End With + +For siCount = 0 To 6 + hpanel = New Panel(Me) + hpanel.Expand = True + hpanel.H = 500 + HPanel.Background = iColour[siCount] +Next + +End diff --git a/Task/Colour-bars-Display/Kotlin/colour-bars-display.kotlin b/Task/Colour-bars-Display/Kotlin/colour-bars-display.kotlin new file mode 100644 index 0000000000..c185586deb --- /dev/null +++ b/Task/Colour-bars-Display/Kotlin/colour-bars-display.kotlin @@ -0,0 +1,25 @@ +import java.awt.Color +import java.awt.Graphics +import javax.swing.JFrame + +class ColorFrame(width: Int, height: Int): JFrame() { + init { + defaultCloseOperation = EXIT_ON_CLOSE + setSize(width, height) + isVisible = true + } + + override fun paint(g: Graphics) { + val colors = listOf(Color.black, Color.red, Color.green, Color.blue, + Color.pink, Color.cyan, Color.yellow, Color.white) + val size = colors.size + for (i in 0 until size) { + g.color = colors[i] + g.fillRect(width / size * i, 0, width / size, height) + } + } +} + +fun main(args: Array) { + ColorFrame(400, 400) +} diff --git a/Task/Colour-bars-Display/Liberty-BASIC/colour-bars-display.liberty b/Task/Colour-bars-Display/Liberty-BASIC/colour-bars-display.liberty deleted file mode 100644 index 528e576b26..0000000000 --- a/Task/Colour-bars-Display/Liberty-BASIC/colour-bars-display.liberty +++ /dev/null @@ -1,20 +0,0 @@ -nomainwin -colors$="black red green blue pink cyan yellow white" -WindowWidth=DisplayWidth:WindowHeight=DisplayHeight -UpperLeftX=1:UpperLeftY=1 -barWidth=DisplayWidth/8 -graphicbox #main.g, 0,0,DisplayWidth,DisplayHeight -open "" for window_popup as #main -#main "trapclose [quit]" -#main.g "down; setfocus; when characterInput [quit]" -#main.g "when leftButtonUp [quit]" -#main.g "size ";barWidth - -for x = barWidth/2 to DisplayWidth step barWidth - i=i+1 - if i>8 then i=1 - col$=word$(colors$,i) - #main.g "color ";col$;"; line ";x;" 0 ";x;" ";DisplayHeight -next -wait -[quit] close #main:end diff --git a/Task/Colour-bars-Display/Locomotive-Basic/colour-bars-display.locomotive b/Task/Colour-bars-Display/Locomotive-Basic/colour-bars-display.locomotive deleted file mode 100644 index 22c2f0c6e0..0000000000 --- a/Task/Colour-bars-Display/Locomotive-Basic/colour-bars-display.locomotive +++ /dev/null @@ -1,7 +0,0 @@ -10 MODE 0:BORDER 23 -20 FOR x=0 TO 15 -30 ORIGIN x*40,0 -40 GRAPHICS PEN x -50 FOR z=0 TO 39 STEP 4:MOVE z,0:DRAW z,400:NEXT -60 NEXT -70 CALL &bb06 ' wait for key press diff --git a/Task/Colour-bars-Display/Maple/colour-bars-display.maple b/Task/Colour-bars-Display/Maple/colour-bars-display.maple new file mode 100644 index 0000000000..3067970964 --- /dev/null +++ b/Task/Colour-bars-Display/Maple/colour-bars-display.maple @@ -0,0 +1,2 @@ +with(plottools): +plots:-display([rectangle([0, 0], [.3, 2.1], color = black), rectangle([.3, 0], [.6, 2.1], color = red), rectangle([.6, 0], [.9, 2.1], color = green), rectangle([.9, 0], [1.2, 2.1], color = magenta), rectangle([1.2, 0], [1.5, 2.1], color = cyan), rectangle([1.5, 0], [1.8, 2.1], color = white), rectangle([1.8, 0], [2.1, 2.1], color = yellow)]) diff --git a/Task/Colour-bars-Display/Perl-6/colour-bars-display.pl6 b/Task/Colour-bars-Display/Perl-6/colour-bars-display.pl6 index e26e3c5cb3..f4c0e63ba1 100644 --- a/Task/Colour-bars-Display/Perl-6/colour-bars-display.pl6 +++ b/Task/Colour-bars-Display/Perl-6/colour-bars-display.pl6 @@ -11,7 +11,7 @@ my @colors = map -> $r, $g, $b { Buf.new: |(($r, $g, $b) xx $HOR div 8) }, 255,255, 0, 255,255,255; -my $PPM = open "colorbars.ppm", :w, :bin or die "Can't create colorbars.ppm: $!"; +my $PPM = open "colorbars.ppm", :w or die "Can't create colorbars.ppm: $!"; $PPM.print: qq:to/EOH/; P6 diff --git a/Task/Colour-bars-Display/Phix/colour-bars-display.phix b/Task/Colour-bars-Display/Phix/colour-bars-display.phix new file mode 100644 index 0000000000..3a90972a84 --- /dev/null +++ b/Task/Colour-bars-Display/Phix/colour-bars-display.phix @@ -0,0 +1,66 @@ +-- +-- demo\rosetta\Colour_bars.exw +-- +include pGUI.e + +constant colours = {CD_BLACK, CD_RED, CD_GREEN, CD_MAGENTA, CD_CYAN, CD_YELLOW, CD_WHITE} + +Ihandle dlg, canvas +cdCanvas cddbuffer, cdcanvas + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) + cdCanvasActivate(cddbuffer) + integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") + integer x = 0, lc = length(colours) + for i=1 to lc do + integer w = floor((width-x)/(lc-i+1)) + cdCanvasSetForeground(cddbuffer, colours[i]) + cdCanvasBox(cddbuffer, x, x+w, 0, height) + x += w + end for + cdCanvasFlush(cddbuffer) + return IUP_DEFAULT +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + return IUP_DEFAULT +end function + +function unmap_cb(Ihandle /*ih*/) + cdKillCanvas(cddbuffer) + cdKillCanvas(cdcanvas) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "600x400") -- initial size + + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + IupSetCallback(canvas, "UNMAP_CB", Icallback("unmap_cb")) + + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", "Colour bars") + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + + IupMap(dlg) + IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation + + IupShowXY(dlg,IUP_CENTER,IUP_CENTER) + + IupMainLoop() + + IupClose() +end procedure + +main() diff --git a/Task/Colour-bars-Display/PureBasic/colour-bars-display-1.purebasic b/Task/Colour-bars-Display/PureBasic/colour-bars-display-1.purebasic deleted file mode 100644 index 9b35d9fe22..0000000000 --- a/Task/Colour-bars-Display/PureBasic/colour-bars-display-1.purebasic +++ /dev/null @@ -1,31 +0,0 @@ -Dim color(7) -color(0) = RGB($00, $00, $00) ;black -color(1) = RGB($FF, $00, $00) ;red -color(2) = RGB($00, $FF, $00) ;green -color(3) = RGB($00, $00, $FF) ;blue -color(4) = RGB($FF, $00, $FF) ;magenta -color(5) = RGB($00, $FF, $FF) ;cyan -color(6) = RGB($FF, $FF, $00) ;yellow -color(7) = RGB($FF, $FF, $FF) ;white - -If Not InitKeyboard(): End: EndIf ;can't init keyboard -If Not InitSprite(): End: EndIf ;can't init sprite/screen library -If Not ExamineDesktops(): End: EndIf ;can't retrieve information about desktop - -height = DesktopHeight(0) -width = DesktopWidth(0) -depth = DesktopDepth(0) -If OpenScreen(width, height, depth, "Press ENTER to exit") - StartDrawing(ScreenOutput()) - For c = 0 To 7 - Box((width * c) / 8, 0, width / 8, height, color(c)) - Next - StopDrawing() - FlipBuffers() - - Repeat - Delay(10) - ExamineKeyboard() - Until KeyboardPushed(#PB_Key_Escape) Or KeyboardPushed(#PB_Key_Return) - CloseScreen() -EndIf diff --git a/Task/Colour-bars-Display/PureBasic/colour-bars-display-2.purebasic b/Task/Colour-bars-Display/PureBasic/colour-bars-display-2.purebasic deleted file mode 100644 index e3cde4b7fd..0000000000 --- a/Task/Colour-bars-Display/PureBasic/colour-bars-display-2.purebasic +++ /dev/null @@ -1,24 +0,0 @@ -DataSection - ;Black, Red, Green, Blue, Magenta, Cyan, Yellow, White - Data.i 0, 12, 10, 9, 13, 11, 14, 15 -EndDataSection - -Dim colors(7) -For c = 0 To 7 - Read.i colors(c) -Next - -If OpenConsole() - ;The console display is 80 columns wide by 25 rows - For r = 0 To 24 - For c = 0 To 7 - ConsoleColor(colors(c), colors(c)) - Print(Space(80 / 8)) - Next - Next - EnableGraphicalConsole(1) - ConsoleLocate(0, 0) - - ConsoleTitle("Press ENTER to exit"): Input() - CloseConsole() -EndIf diff --git a/Task/Colour-bars-Display/Run-BASIC/colour-bars-display.run b/Task/Colour-bars-Display/Run-BASIC/colour-bars-display.run deleted file mode 100644 index 3e484752df..0000000000 --- a/Task/Colour-bars-Display/Run-BASIC/colour-bars-display.run +++ /dev/null @@ -1,6 +0,0 @@ -colors$ = "black,red,green,blue,magenta,cyan,yellow,white" -html "" -for i = 1 to 8 - html "
    " -next i -html "
    " diff --git a/Task/Colour-bars-Display/XPL0/colour-bars-display-1.xpl0 b/Task/Colour-bars-Display/XPL0/colour-bars-display-1.xpl0 deleted file mode 100644 index 2179c96410..0000000000 --- a/Task/Colour-bars-Display/XPL0/colour-bars-display-1.xpl0 +++ /dev/null @@ -1,12 +0,0 @@ -include c:\cxpl\codes; \intrinsic code declarations -int W, X0, X1, Y, C; -[SetVid($13); \320x200x8 graphics -W:= 320/8; \width of color bar (pixels) -for C:= 0 to 8-1 do - [X0:= W*C; X1:= X0+W-1; - for Y:= 0 to 200-1 do - [Move(X0, Y); Line(X1, Y, C)]; - ]; -C:= ChIn(1); \wait for keystroke -SetVid(3); \restore normal text mode -] diff --git a/Task/Colour-bars-Display/XPL0/colour-bars-display-2.xpl0 b/Task/Colour-bars-Display/XPL0/colour-bars-display-2.xpl0 deleted file mode 100644 index 3c8e3a3d25..0000000000 --- a/Task/Colour-bars-Display/XPL0/colour-bars-display-2.xpl0 +++ /dev/null @@ -1,8 +0,0 @@ -10 REM The ZX Spectrum display is 32 columns wide, so we have 8 columns of 4 spaces -20 FOR r=0 TO 20: REM There are 21 rows -30 FOR c=0 TO 7: REM We use the native colour sequence here -40 PAPER c: REM set the background colour for the spaces to be printed -50 PRINT " ";: REM four spaces, the semicolon prevents newline -60 NEXT c -70 REM at this point the cursor has wrapped, so we don't need a newline -80 NEXT r diff --git a/Task/Colour-pinstripe-Display/FreeBASIC/colour-pinstripe-display.freebasic b/Task/Colour-pinstripe-Display/FreeBASIC/colour-pinstripe-display.freebasic new file mode 100644 index 0000000000..83cc9e451a --- /dev/null +++ b/Task/Colour-pinstripe-Display/FreeBASIC/colour-pinstripe-display.freebasic @@ -0,0 +1,26 @@ +' version 14-03-2017 +' compile with: fbc -s console +' or compile with: fbc -s gui + +Dim As UInteger ps, col, h, w, x, y1, y2 +ScreenInfo w, h + +' create display size window, 8bit color (palette), no frame +ScreenRes w, h, 8,, 8 + +h = h \ 4 : y2 = h -1 + +For ps = 1 To 4 + col = 0 + For x = 0 To (w - ps -1) Step ps + Line (x, y1) - (x + ps -1, y2), col, bf + col = (col +1) And 255 + Next + y1 += h : y2 += h +Next + +' empty keyboard buffer +While Inkey <> "" : Wend +'Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Colour-pinstripe-Display/Gambas/colour-pinstripe-display.gambas b/Task/Colour-pinstripe-Display/Gambas/colour-pinstripe-display.gambas new file mode 100644 index 0000000000..e9e2ad772d --- /dev/null +++ b/Task/Colour-pinstripe-Display/Gambas/colour-pinstripe-display.gambas @@ -0,0 +1,27 @@ +'WARNING this takes a time to display + +Public Sub Form_Open() +Dim iColour As Integer[] = [Color.Black, Color.red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.white] +Dim hPanel As Panel +Dim siCount, siCounter, siSet As Short + +With Me + .Arrangement = Arrange.Row + .Border = False + .Height = 1080 + .Width = 400 + .Fullscreen = True +End With + +For siCounter = 1 To 4 + For siCount = 0 To Desktop.Width Step siCounter + hpanel = New Panel(Me) + hpanel.Width = siCounter + hpanel.Height = Desktop.Height / 4 + HPanel.Background = iColour[siSet] + Inc siSet + If siSet > 6 Then siSet = 0 + Next +Next + +End diff --git a/Task/Colour-pinstripe-Display/Kotlin/colour-pinstripe-display.kotlin b/Task/Colour-pinstripe-Display/Kotlin/colour-pinstripe-display.kotlin new file mode 100644 index 0000000000..ff5f828249 --- /dev/null +++ b/Task/Colour-pinstripe-Display/Kotlin/colour-pinstripe-display.kotlin @@ -0,0 +1,42 @@ +// version 1.1.0 + +import java.awt.* +import java.awt.Color.* +import javax.swing.* + +class ColourPinstripeDisplay : JPanel() { + private companion object { + val palette = arrayOf(black, red, green, blue, magenta, cyan, yellow, white) + } + + private val bands = 4 + + init { + preferredSize = Dimension(900, 600) + } + + override fun paintComponent(g: Graphics) { + super.paintComponent(g) + for (b in 1..bands) { + var colIndex = 0 + val h = height / bands + for (x in 0 until width step b) { + g.color = palette[colIndex % palette.size] + g.fillRect(x, (b - 1) * h, b, h) + colIndex++ + } + } + } +} + +fun main(args: Array) { + SwingUtilities.invokeLater { + val f = JFrame() + f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE + f.title = "ColourPinstripeDisplay" + f.add(ColourPinstripeDisplay(), BorderLayout.CENTER) + f.pack() + f.setLocationRelativeTo(null) + f.isVisible = true + } +} diff --git a/Task/Colour-pinstripe-Display/Maple/colour-pinstripe-display.maple b/Task/Colour-pinstripe-Display/Maple/colour-pinstripe-display.maple new file mode 100644 index 0000000000..ef51869002 --- /dev/null +++ b/Task/Colour-pinstripe-Display/Maple/colour-pinstripe-display.maple @@ -0,0 +1,5 @@ +colors := [yellow, black, red, green, magenta, cyan, white]: +plots:-display( [ + seq( plot([1+i/10,y,y=5..6], color=colors[i mod 7 + 1],thickness=1), i = 1..500), + seq( plot([1+i/10,y,y=4..5], color=colors[i mod 7 + 1],thickness=2), i = 1..500),seq( plot([1+i/10,y,y=3..4], color=colors[i mod 7 + 1],thickness=3), i = 1..500),seq( plot([1+i/10,y,y=2..3], color=colors[i mod 7 + 1],thickness=4,size=[interface(screenwidth)*20,interface(screenheight)*32]), i = 1..500)], +axes=none); diff --git a/Task/Colour-pinstripe-Display/Perl-6/colour-pinstripe-display.pl6 b/Task/Colour-pinstripe-Display/Perl-6/colour-pinstripe-display.pl6 index c0977ccada..d7550f3fae 100644 --- a/Task/Colour-pinstripe-Display/Perl-6/colour-pinstripe-display.pl6 +++ b/Task/Colour-pinstripe-Display/Perl-6/colour-pinstripe-display.pl6 @@ -11,7 +11,7 @@ my @colors = map -> $r, $g, $b { [$r, $g, $b] }, 255,255, 0, 255,255,255; -my $PPM = open "pinstripes.ppm", :w, :bin or die "Can't create pinstripes.ppm: $!"; +my $PPM = open "pinstripes.ppm", :w or die "Can't create pinstripes.ppm: $!"; $PPM.print: qq:to/EOH/; P3 diff --git a/Task/Colour-pinstripe-Display/Phix/colour-pinstripe-display.phix b/Task/Colour-pinstripe-Display/Phix/colour-pinstripe-display.phix new file mode 100644 index 0000000000..0aea751c48 --- /dev/null +++ b/Task/Colour-pinstripe-Display/Phix/colour-pinstripe-display.phix @@ -0,0 +1,70 @@ +-- +-- demo\rosetta\Colour_pinstripe.exw +-- ================================= +-- +include pGUI.e + +constant colours = {CD_BLACK, CD_RED, CD_GREEN, CD_MAGENTA, CD_CYAN, CD_YELLOW, CD_WHITE} + +Ihandle dlg, canvas +cdCanvas cddbuffer, cdcanvas + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) + cdCanvasActivate(cddbuffer) + integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") + for y=1 to 4 do + integer x = 0, c = 1, h = floor(height/(5-y)) + while x 0 && k >= 0) + return (n - k + 1 .. n).fold(BigInteger.ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) } +} + +fun comb(n: Int, k: Int): BigInteger { + require(n > 0 && k >= 0) + val fact = (2..k).fold(BigInteger.ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) } + return perm(n, k) / fact +} + +fun main(args: Array) { + println("A sample of permutations from 1 to 12:") + for (n in 1..12) System.out.printf("%2d P %-2d = %d\n", n, n / 3, perm(n, n / 3)) + + println("\nA sample of combinations from 10 to 60:") + for (n in 10..60 step 10) System.out.printf("%2d C %-2d = %d\n", n, n / 3, comb(n, n / 3)) + + println("\nA sample of permutations from 5 to 15000:") + val na = intArrayOf(5, 50, 500, 1000, 5000, 15000) + for (n in na) { + val k = n / 3 + val s = perm(n, k).toString() + val l = s.length + val e = if (l <= 40) "" else "... (${l - 40} more digits)" + System.out.printf("%5d P %-4d = %s%s\n", n, k, s.take(40), e) + } + + println("\nA sample of combinations from 100 to 1000:") + for (n in 100..1000 step 100) { + val k = n / 3 + val s = comb(n, k).toString() + val l = s.length + val e = if (l <= 40) "" else "... (${l - 40} more digits)" + System.out.printf("%4d C %-3d = %s%s\n", n, k, s.take(40), e) + } +} diff --git a/Task/Combinations-and-permutations/Maple/combinations-and-permutations.maple b/Task/Combinations-and-permutations/Maple/combinations-and-permutations.maple new file mode 100644 index 0000000000..ad6a42455a --- /dev/null +++ b/Task/Combinations-and-permutations/Maple/combinations-and-permutations.maple @@ -0,0 +1,6 @@ +comb := proc (n::integer, k::integer) + return factorial(n)/(factorial(k)*factorial(n-k)); +end proc; +perm := proc (n::integer, k::integer) + return factorial(n)/factorial(n-k); +end proc; diff --git a/Task/Combinations-and-permutations/Scheme/combinations-and-permutations.ss b/Task/Combinations-and-permutations/Scheme/combinations-and-permutations.ss new file mode 100644 index 0000000000..b3e60a88ea --- /dev/null +++ b/Task/Combinations-and-permutations/Scheme/combinations-and-permutations.ss @@ -0,0 +1,24 @@ +(define (combinations n k) + (do ((i 0 (+ 1 i)) + (res 1 (/ (* res (- n i)) + (- k i)))) + ((= i k) res))) + +(define (permutations n k) + (do ((i 0 (+ 1 i)) + (res 1 (* res (- n i)))) + ((= i k) res))) + +(display "P(4,2) = ") (display (permutations 4 2)) (newline) +(display "P(8,2) = ") (display (permutations 8 2)) (newline) +(display "P(10,8) = ") (display (permutations 10 8)) (newline) +(display "C(10,8) = ") (display (combinations 10 8)) (newline) +(display "C(20,8) = ") (display (combinations 20 8)) (newline) +(display "C(60,58) = ") (display (combinations 60 58)) (newline) +(display "P(1000,10) = ") (display (permutations 1000 10)) (newline) +(display "P(1000,20) = ") (display (permutations 1000 20)) (newline) +(display "P(15000,2) = ") (display (permutations 15000 3)) (newline) +(display "C(1000,10) = ") (display (combinations 1000 10)) (newline) +(display "C(1000,999) = ") (display (combinations 1000 999)) (newline) +(display "C(1000,1000) = ") (display (combinations 1000 1000)) (newline) +(display "C(15000,14998) = ") (display (combinations 15000 14998)) (newline) diff --git a/Task/Combinations-and-permutations/Sidef/combinations-and-permutations.sidef b/Task/Combinations-and-permutations/Sidef/combinations-and-permutations.sidef index 238eb4ac85..9a82837e6c 100644 --- a/Task/Combinations-and-permutations/Sidef/combinations-and-permutations.sidef +++ b/Task/Combinations-and-permutations/Sidef/combinations-and-permutations.sidef @@ -1,17 +1,16 @@ -func P(n, k) { n! / ((n-k)!) }; -func C(n, k) { binomial(n, k) }; +func P(n, k) { n! / ((n-k)!) } +func C(n, k) { binomial(n, k) } class Logarithm(value) { - method get_value { value }; method to_s { - var e = int(value/10.log); - "%.8fE%+d" % (exp(value - e*10.log), e); + var e = int(value/10.log) + "%.8fE%+d" % (exp(value - e*10.log), e) } } func lstirling(n) { - n < 10 ? (lstirling(n+1) - log(n+1)) - : (0.5*log(2*Number.pi*n) + n*log(n/Number.e + 1/(12*Number.e*n))); + n < 10 ? (lstirling(n+1) - log(n+1)) +  : (0.5*log(2*Num.pi*n) + n*log(n/Num.e + 1/(12*Num.e*n))) } func P_approx(n, k) { @@ -22,25 +21,25 @@ func C_approx(n, k) { Logarithm((lstirling(n) - lstirling(n -k) - lstirling(k))) } -say "=> Exact results:"; -range(1, 12).each { |n| - var p = int(n / 3); - say "P(#{n}, #{p}) = #{P(n, p)}"; +say "=> Exact results:" +for n (1..12) { + var p = n//3 + say "P(#{n}, #{p}) = #{P(n, p)}" } -range(10, 60, 10).each { |n| - var p = int(n / 3); - say "C(#{n}, #{p}) = #{C(n, p)}"; +for n (10..60 `by` 10) { + var p = n//3 + say "C(#{n}, #{p}) = #{C(n, p)}" } say ''; -say "=> Floating point approximations:"; -[5, 50, 500, 1000, 5000, 15000].each { |n| - var p = int(n / 3); - say "P(#{n}, #{p}) = #{P_approx(n, p)}"; +say "=> Floating point approximations:" +for n ([5, 50, 500, 1000, 5000, 15000]) { + var p = n//3 + say "P(#{n}, #{p}) = #{P_approx(n, p)}" } -range(100, 1000, 100).each { |n| - var p = int(n / 3); - say "C(#{n}, #{p}) = #{C_approx(n, p)}"; +for n (100..1000 `by` 100) { + var p = n//3 + say "C(#{n}, #{p}) = #{C_approx(n, p)}" } diff --git a/Task/Combinations-and-permutations/VBScript/combinations-and-permutations.vb b/Task/Combinations-and-permutations/VBScript/combinations-and-permutations.vb new file mode 100644 index 0000000000..423b6ef7c1 --- /dev/null +++ b/Task/Combinations-and-permutations/VBScript/combinations-and-permutations.vb @@ -0,0 +1,59 @@ +' Combinations and permutations - vbs - 10/04/2017 +dim i,j +Wscript.StdOut.WriteLine "-- Long Integer - Permutations - from 1 to 12" +for i=1 to 12 + for j=1 to i + Wscript.StdOut.Write "P(" & i & "," & j & ")=" & perm(i,j) & " " + next 'j + Wscript.StdOut.WriteLine "" +next 'i +Wscript.StdOut.WriteLine "-- Float integer - Combinations from 10 to 60" +for i=10 to 60 step 10 + for j=1 to i step i\5 + Wscript.StdOut.Write "C(" & i & "," & j & ")=" & comb(i,j) & " " + next 'j + Wscript.StdOut.WriteLine "" +next 'i +Wscript.StdOut.WriteLine "-- Float integer - Permutations from 5000 to 15000" +for i=5000 to 15000 step 5000 + for j=10 to 70 step 20 + Wscript.StdOut.Write "C(" & i & "," & j & ")=" & perm(i,j) & " " + next 'j + Wscript.StdOut.WriteLine "" +next 'i +Wscript.StdOut.WriteLine "-- Float integer - Combinations from 200 to 1000" +for i=200 to 1000 step 200 + for j=20 to 100 step 20 + Wscript.StdOut.Write "P(" & i & "," & j & ")=" & comb(i,j) & " " + next 'j + Wscript.StdOut.WriteLine "" +next 'i + +function perm(x,y) + dim i,z + z=1 + for i=x-y+1 to x + z=z*i + next 'i + perm=z +end function 'perm + +function fact(x) + dim i,z + z=1 + for i=2 to x + z=z*i + next 'i + fact=z +end function 'fact + +function comb(byval x,byval y) + if y>x then + comb=0 + elseif x=y then + comb=1 + else + if x-y v, int n, vector s){ + for (int i = 0; i < n; ++i) + printf("%s\t", s[v[i]].c_str()); + printf("\n"); +} + +int combination_with_repetiton(int sabores, int bolas, const vector& v_sabores){ + sabores--; + vector v; + for (int i = 0; i <= bolas; ++i) + v.push_back(0); + while (true){ + for (int i = 0; i < bolas; ++i){ //vai um + if (v[i] > sabores){ + v[i + 1] += 1; + for (int k = i; k >= 0; --k){ + v[k] = v[i + 1]; + } + //v[i] = v[i + 1]; + } + } + + if (v[bolas] > 0) + break; + print_vector(v, bolas, v_sabores); + v[0] += 1; + } + + return 1; +} + +int main(){ + combination_with_repetiton(3, 2, options); + return 0; +} diff --git a/Task/Combinations-with-repetitions/Clojure/combinations-with-repetitions-1.clj b/Task/Combinations-with-repetitions/Clojure/combinations-with-repetitions-1.clj deleted file mode 100644 index 34a0638d73..0000000000 --- a/Task/Combinations-with-repetitions/Clojure/combinations-with-repetitions-1.clj +++ /dev/null @@ -1,6 +0,0 @@ -(defn combinations [coll k] - (when-let [[x & xs] coll] - (if (= k 1) - (map list coll) - (concat (map (partial cons x) (combinations coll (dec k))) - (combinations xs k))))) diff --git a/Task/Combinations-with-repetitions/Clojure/combinations-with-repetitions-2.clj b/Task/Combinations-with-repetitions/Clojure/combinations-with-repetitions-2.clj deleted file mode 100644 index d19b60dd2e..0000000000 --- a/Task/Combinations-with-repetitions/Clojure/combinations-with-repetitions-2.clj +++ /dev/null @@ -1,2 +0,0 @@ -user> (combinations '[iced jam plain] 2) -((iced iced) (iced jam) (iced plain) (jam jam) (jam plain) (plain plain)) diff --git a/Task/Combinations-with-repetitions/CoffeeScript/combinations-with-repetitions-1.coffee b/Task/Combinations-with-repetitions/CoffeeScript/combinations-with-repetitions-1.coffee deleted file mode 100644 index 4ba3f5440a..0000000000 --- a/Task/Combinations-with-repetitions/CoffeeScript/combinations-with-repetitions-1.coffee +++ /dev/null @@ -1,12 +0,0 @@ -combos = (arr, k) -> - return [ [] ] if k == 0 - return [] if arr.length == 0 - - combos_with_head = ([arr[0]].concat combo for combo in combos arr, k-1) - combos_sans_head = combos arr[1...], k - combos_with_head.concat combos_sans_head - -arr = ['iced', 'jam', 'plain'] -console.log "valid pairs from #{arr.join ','}:" -console.log combos arr, 2 -console.log "#{combos([1..10], 3).length} ways to order 3 donuts given 10 types" diff --git a/Task/Combinations-with-repetitions/CoffeeScript/combinations-with-repetitions-2.coffee b/Task/Combinations-with-repetitions/CoffeeScript/combinations-with-repetitions-2.coffee deleted file mode 100644 index ef9701ffe7..0000000000 --- a/Task/Combinations-with-repetitions/CoffeeScript/combinations-with-repetitions-2.coffee +++ /dev/null @@ -1,8 +0,0 @@ -jam,plain: -[ [ 'iced', 'iced' ], - [ 'iced', 'jam' ], - [ 'iced', 'plain' ], - [ 'jam', 'jam' ], - [ 'jam', 'plain' ], - [ 'plain', 'plain' ] ] -220 ways to order 3 donuts given 10 types diff --git a/Task/Combinations-with-repetitions/Erlang/combinations-with-repetitions-1.erl b/Task/Combinations-with-repetitions/Erlang/combinations-with-repetitions-1.erl deleted file mode 100644 index 8a6ffeb70e..0000000000 --- a/Task/Combinations-with-repetitions/Erlang/combinations-with-repetitions-1.erl +++ /dev/null @@ -1,9 +0,0 @@ --module(comb). --compile(export_all). - -comb_rep(0,_) -> - [[]]; -comb_rep(_,[]) -> - []; -comb_rep(N,[H|T]=S) -> - [[H|L] || L <- comb_rep(N-1,S)]++comb_rep(N,T). diff --git a/Task/Combinations-with-repetitions/Erlang/combinations-with-repetitions-2.erl b/Task/Combinations-with-repetitions/Erlang/combinations-with-repetitions-2.erl deleted file mode 100644 index a6690ae775..0000000000 --- a/Task/Combinations-with-repetitions/Erlang/combinations-with-repetitions-2.erl +++ /dev/null @@ -1,9 +0,0 @@ -94> comb:comb_rep(2,[iced,jam,plain]). -[[iced,iced], - [iced,jam], - [iced,plain], - [jam,jam], - [jam,plain], - [plain,plain]] -95> length(comb:comb_rep(3,lists:seq(1,10))). -220 diff --git a/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-1.hs b/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-1.hs index 5d5e1a4945..8e90bab969 100644 --- a/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-1.hs +++ b/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-1.hs @@ -2,16 +2,23 @@ -- list. We ignore the case where k is greater than the length of -- the list. combsWithRep :: Int -> [a] -> [[a]] -combsWithRep 0 _ = [[]] +combsWithRep 0 _ = [[]] combsWithRep _ [] = [] -combsWithRep k xxs@(x:xs) = map (x:) (combsWithRep (k-1) xxs) ++ combsWithRep k xs +combsWithRep k xxs@(x:xs) = + (x :) <$> combsWithRep (k - 1) xxs ++ combsWithRep k xs -binomial n m = (f n) `div` (f (n - m)) `div` (f m) where - f n = if n == 0 then 1 else n * f (n - 1) +binomial n m = f n `div` f (n - m) `div` f m + where + f n = + if n == 0 + then 1 + else n * f (n - 1) +countCombsWithRep :: Int -> [a] -> Int countCombsWithRep k lst = binomial (k - 1 + length lst) k --- countCombsWithRep k = length . combsWithRep k +-- countCombsWithRep k = length . combsWithRep k +main :: IO () main = do - print $ combsWithRep 2 ["iced","jam","plain"] - print $ countCombsWithRep 3 [1..10] + print $ combsWithRep 2 ["iced", "jam", "plain"] + print $ countCombsWithRep 3 [1 .. 10] diff --git a/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-2.hs b/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-2.hs index ea90f6e3c9..2a2d3865ae 100644 --- a/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-2.hs +++ b/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-2.hs @@ -1,8 +1,8 @@ combsWithRep :: Int -> [a] -> [[a]] combsWithRep k xs = combsBySize xs !! k - where - combsBySize = foldr f ([[]] : repeat []) - f x next = scanl1 (\z n -> map (x:) z ++ n) next + where + combsBySize = foldr f ([[]] : repeat []) + f x = scanl1 $ (++) . map (x :) -main = do - print $ combsWithRep 2 ["iced","jam","plain"] +main :: IO () +main = print $ combsWithRep 2 ["iced", "jam", "plain"] diff --git a/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-3.hs b/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-3.hs new file mode 100644 index 0000000000..94b5f12090 --- /dev/null +++ b/Task/Combinations-with-repetitions/Haskell/combinations-with-repetitions-3.hs @@ -0,0 +1,15 @@ +combsWithRep + :: (Eq a) + => Int -> [a] -> [[a]] +combsWithRep k xs = comb k [] + where + comb 0 lst = lst + comb n [] = comb (n - 1) (pure <$> xs) + comb n peers = + let nextLayer ys@(h:_) = (: ys) <$> dropWhile (/= h) xs + in comb (n - 1) (foldMap nextLayer peers) + +main :: IO () +main = do + print $ combsWithRep 2 ["iced", "jam", "plain"] + print $ length $ combsWithRep 3 [0 .. 9] diff --git a/Task/Combinations-with-repetitions/JavaScript/combinations-with-repetitions-4.js b/Task/Combinations-with-repetitions/JavaScript/combinations-with-repetitions-4.js new file mode 100644 index 0000000000..68d078935e --- /dev/null +++ b/Task/Combinations-with-repetitions/JavaScript/combinations-with-repetitions-4.js @@ -0,0 +1,62 @@ +(() => { + 'use strict'; + + // COMBINATIONS WITH REPETITIONS ------------------------------------------- + + // combsWithRep :: Int -> [a] -> [[a]] + const combsWithRep = (k, xs) => { + const comb = (n, ys) => { + if (0 === n) return ys; + if (isNull(ys)) return comb(n - 1, map(pure, xs)); + + return comb(n - 1, concatMap(zs => { + const h = head(zs); + return map(x => [x].concat(zs), dropWhile(x => x !== h, xs)); + }, ys)); + }; + return comb(k, []); + }; + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // concatMap :: (a -> [b]) -> [a] -> [b] + const concatMap = (f, xs) => [].concat.apply([], xs.map(f)); + + // dropWhile :: (a -> Bool) -> [a] -> [a] + const dropWhile = (p, xs) => { + let i = 0; + for (let lng = xs.length; + (i < lng) && p(xs[i]); i++) {} + return xs.slice(i); + }; + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // head :: [a] -> Maybe a + const head = xs => xs.length ? xs[0] : undefined; + + // isNull :: [a] -> Bool + const isNull = xs => (xs instanceof Array) ? xs.length < 1 : undefined; + + // length :: [a] -> Int + const length = xs => xs.length; + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // pure :: a -> [a] + const pure = x => [x]; + + // show :: a -> String + const show = x => JSON.stringify(x, null, 2); + + // TEST ------------------------------------------------------------------- + return show({ + twoFromThree: combsWithRep(2, ['iced', 'jam', 'plain']), + threeFromTen: length(combsWithRep(3, enumFromTo(0, 9))) + }); +})(); diff --git a/Task/Combinations-with-repetitions/jq/combinations-with-repetitions-1.jq b/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-1.jq similarity index 100% rename from Task/Combinations-with-repetitions/jq/combinations-with-repetitions-1.jq rename to Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-1.jq diff --git a/Task/Combinations-with-repetitions/jq/combinations-with-repetitions-2.jq b/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-2.jq similarity index 100% rename from Task/Combinations-with-repetitions/jq/combinations-with-repetitions-2.jq rename to Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-2.jq diff --git a/Task/Combinations-with-repetitions/Kotlin/combinations-with-repetitions.kotlin b/Task/Combinations-with-repetitions/Kotlin/combinations-with-repetitions.kotlin new file mode 100644 index 0000000000..06b658a3fb --- /dev/null +++ b/Task/Combinations-with-repetitions/Kotlin/combinations-with-repetitions.kotlin @@ -0,0 +1,37 @@ +// version 1.0.6 + +class CombsWithReps(val m: Int, val n: Int, val items: List, val countOnly: Boolean = false) { + private val combination = IntArray(m) + private var count = 0 + + init { + generate(0) + if (!countOnly) println() + println("There are $count combinations of $n things taken $m at a time, with repetitions") + } + + private fun generate(k: Int) { + if (k >= m) { + if (!countOnly) { + for (i in 0 until m) print("${items[combination[i]]}\t") + println() + } + count++ + } + else { + for (j in 0 until n) + if (k == 0 || j >= combination[k - 1]) { + combination[k] = j + generate(k + 1) + } + } + } +} + +fun main(args: Array) { + val doughnuts = listOf("iced", "jam", "plain") + CombsWithReps(2, 3, doughnuts) + println() + val generic10 = "0123456789".split("") + CombsWithReps(3, 10, generic10, true) +} diff --git a/Task/Combinations-with-repetitions/PHP/combinations-with-repetitions-1.php b/Task/Combinations-with-repetitions/PHP/combinations-with-repetitions-1.php deleted file mode 100644 index c75762744b..0000000000 --- a/Task/Combinations-with-repetitions/PHP/combinations-with-repetitions-1.php +++ /dev/null @@ -1,32 +0,0 @@ -"; - } - $donuts = range(1, 10); - $num_donut_combos = count(combos($donuts, 3)); - echo "$num_donut_combos ways to order 3 donuts given 10 types"; -?> diff --git a/Task/Combinations-with-repetitions/PHP/combinations-with-repetitions-2.php b/Task/Combinations-with-repetitions/PHP/combinations-with-repetitions-2.php deleted file mode 100644 index d8ef0c4d5c..0000000000 --- a/Task/Combinations-with-repetitions/PHP/combinations-with-repetitions-2.php +++ /dev/null @@ -1,7 +0,0 @@ -iced iced -iced jam -iced plain -jam jam -jam plain -plain plain -220 ways to order 3 donuts given 10 types diff --git a/Task/Combinations-with-repetitions/Perl-6/combinations-with-repetitions-1.pl6 b/Task/Combinations-with-repetitions/Perl-6/combinations-with-repetitions-1.pl6 index 77ff7f90f4..20d2930cb0 100644 --- a/Task/Combinations-with-repetitions/Perl-6/combinations-with-repetitions-1.pl6 +++ b/Task/Combinations-with-repetitions/Perl-6/combinations-with-repetitions-1.pl6 @@ -1,4 +1,4 @@ my @S = ; my $k = 2; -.put for [X](@S xx $k).unique(as => *.sort, with => &[eqv]) +.put for [X](@S xx $k).unique(as => *.sort.cache, with => &[eqv]) diff --git a/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions-1.rexx b/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions-1.rexx index 162891ee9f..0f207aa6e7 100644 --- a/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions-1.rexx +++ b/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions-1.rexx @@ -1,23 +1,21 @@ -/*REXX program displays combination sets for X things taken Y at a time.*/ -call RcombN 3, 2, 'iced,jam,plain' /*The 1st part of Rosetta Code task. */ -call RcombN -10, 3, 'Iced,jam,plain' /* " 2nd " " " " " */ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -RcombN: procedure; parse arg x,y,syms; tell=x>0; x=abs(x); z=x+1 -syms=translate(syms,,',') /*separate symbols*/ -say "────────────" x 'doughnut selection taken' y "at a time:" - - do i=1 for words(syms); $.i=word(syms,i) /*assign symbols. */ - end /*i*/ -@.=1 /*assign @ default*/ - do #=1; if tell then call show /*display combos? */ - @.y=@.y+1; if @.y==z then if .(y-1) then leave /* ◄─── recursive.*/ - end /*#*/ - -say "────────────" # 'combinations.'; say; say; say -return -/*────────────────────────────────────────────────────────────────────────────*/ -.: procedure expose @. y z; parse arg ?; if ?==0 then return 1; p=@.?+1 - if p==z then return .(?-1); do i=? to y; @.i=p; end; return 0 -/*────────────────────────────────────────────────────────────────────────────*/ -show: L=; do c=1 for y; _=@.c; L=L $._; end; say L; return +/*REXX pgm displays combination sets (with repetitions) for X things taken Y at a time.*/ +call RcombN 3, 2, 'iced,jam,plain' /*The 1st part of Rosetta Code task. */ +call RcombN -10, 3, 'Iced,jam,plain' /* " 2nd " " " " " */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +RcombN: procedure; parse arg x,y,syms; tell= x>0; x=abs(x); z=x+1; pad=copies('─', 15) + syms=translate(syms, , ',') /*split symbols. */ + say pad x 'doughnut selection taken' y "at a time:" /*display title. */ + do i=1 for words(syms); $.i=word(syms, i) /*assign symbol. */ + end /*i*/ + @.=1 /*assign default.*/ + do #=1; if tell then call show /*display combos?*/ + @.y=@.y+1; if @.y==z then if .(y-1) then leave /* ◄─── recursive*/ + end /*#*/ + say pad # 'combinations.'; say; say; say /*display answer.*/ + return /* [↑] and blanks*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +.: procedure expose @. y z; parse arg ?; if ?==0 then return 1; p=@.?+1 + if p==z then return .(?-1); do i=? to y; @.i=p; end /*i*/; return 0 +/*──────────────────────────────────────────────────────────────────────────────────────*/ +show: L=; do c=1 for y; _=@.c; L=L $._; end /*c*/; say L; return diff --git a/Task/Combinations-with-repetitions/UNIX-Shell/combinations-with-repetitions.sh b/Task/Combinations-with-repetitions/UNIX-Shell/combinations-with-repetitions.sh deleted file mode 100644 index cebb3baa13..0000000000 --- a/Task/Combinations-with-repetitions/UNIX-Shell/combinations-with-repetitions.sh +++ /dev/null @@ -1,2 +0,0 @@ -$ echo {iced,jam,plain}-{iced,jam,plain} # trick question??? -iced-iced iced-jam iced-plain jam-iced jam-jam jam-plain plain-iced plain-jam plain-plain diff --git a/Task/Combinations-with-repetitions/Zkl/combinations-with-repetitions-1.zkl b/Task/Combinations-with-repetitions/Zkl/combinations-with-repetitions-1.zkl new file mode 100644 index 0000000000..625c99d821 --- /dev/null +++ b/Task/Combinations-with-repetitions/Zkl/combinations-with-repetitions-1.zkl @@ -0,0 +1,5 @@ +fcn combosK(k,seq){ // repeats, seq is finite + if (k==1) return(seq); + if (not seq) return(T); + self.fcn(k-1,seq).apply(T.extend.fp(seq[0])).extend(self.fcn(k,seq[1,*])); +} diff --git a/Task/Combinations-with-repetitions/Zkl/combinations-with-repetitions-2.zkl b/Task/Combinations-with-repetitions/Zkl/combinations-with-repetitions-2.zkl new file mode 100644 index 0000000000..ca6135412b --- /dev/null +++ b/Task/Combinations-with-repetitions/Zkl/combinations-with-repetitions-2.zkl @@ -0,0 +1,2 @@ +combosK(2,T("iced","jam","plain")).apply("concat",","); +combosK(3,T(0,1,2,3,4,5,6,7,8,9)).len(); diff --git a/Task/Combinations/AppleScript/combinations-3.applescript b/Task/Combinations/AppleScript/combinations-3.applescript index 0092d7b010..b3a2f0d872 100644 --- a/Task/Combinations/AppleScript/combinations-3.applescript +++ b/Task/Combinations/AppleScript/combinations-3.applescript @@ -1,43 +1,76 @@ -- comb :: Int -> [a] -> [[a]] on comb(n, lst) - set h to head(lst) - - script headPrepended - on lambda(t) - h & t - end lambda - end script - if n < 1 then - [[]] - else if length of lst = 0 then - [] + {{}} else - set xs to tail(lst) + if not isNull(lst) then + set {h, xs} to uncons(lst) - map(headPrepended, ¬ - comb(n - 1, xs)) & comb(n, xs) + map(curry(my cons)'s |λ|(h), comb(n - 1, xs)) & comb(n, xs) + else + {} + end if end if end comb - --- TEST - --- spaced :: [a] -> String -on spaced(lst) - intercalate(space, lst) -end spaced - +-- TEST ----------------------------------------------------------------------- on run intercalate(linefeed, ¬ - map(spaced, comb(3, range(0, 4)))) + map(unwords, comb(3, enumFromTo(0, 4)))) end run +-- GENERIC FUNCTIONS ---------------------------------------------------------- +-- cons :: a -> [a] -> [a] +on cons(x, xs) + {x} & xs +end cons --- GENERIC FUNCTIONS +-- curry :: (Script|Handler) -> Script +on curry(f) + script + on |λ|(a) + script + on |λ|(b) + |λ|(a, b) of mReturn(f) + end |λ| + end script + end |λ| + end script +end curry + +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if n < m then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo + +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + +-- isNull :: [a] -> Bool +on isNull(xs) + if class of xs is string then + xs = "" + else + xs = {} + end if +end isNull -- map :: (a -> b) -> [a] -> [b] on map(f, xs) @@ -45,7 +78,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -58,47 +91,27 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn --- intercalate :: Text -> [Text] -> Text -on intercalate(strText, lstText) - set {dlm, my text item delimiters} to {my text item delimiters, strText} - set strJoined to lstText as text - set my text item delimiters to dlm - return strJoined -end intercalate - --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then - set d to -1 - else - set d to 1 - end if - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range - --- head :: [a] -> a -on head(xs) - if length of xs > 0 then - item 1 of xs +-- uncons :: [a] -> Maybe (a, [a]) +on uncons(xs) + set lng to length of xs + if lng > 0 then + if class of xs is string then + set cs to text items of xs + {item 1 of cs, rest of cs} + else + {item 1 of xs, rest of xs} + end if else missing value end if -end head +end uncons --- tail :: [a] -> [a] -on tail(xs) - if length of xs > 1 then - items 2 thru -1 of xs - else - {} - end if -end tail +-- unwords :: [String] -> String +on unwords(xs) + intercalate(space, xs) +end unwords diff --git a/Task/Combinations/CoffeeScript/combinations-1.coffee b/Task/Combinations/CoffeeScript/combinations-1.coffee deleted file mode 100644 index 93cacf3d1b..0000000000 --- a/Task/Combinations/CoffeeScript/combinations-1.coffee +++ /dev/null @@ -1,25 +0,0 @@ -combinations = (n, p) -> - return [ [] ] if p == 0 - i = 0 - combos = [] - combo = [] - while combo.length < p - if i < n - combo.push i - i += 1 - else - break if combo.length == 0 - i = combo.pop() + 1 - - if combo.length == p - combos.push clone combo - i = combo.pop() + 1 - combos - -clone = (arr) -> (n for n in arr) - -N = 5 -for i in [0..N] - console.log "------ #{N} #{i}" - for combo in combinations N, i - console.log combo diff --git a/Task/Combinations/CoffeeScript/combinations-2.coffee b/Task/Combinations/CoffeeScript/combinations-2.coffee deleted file mode 100644 index 488d61813c..0000000000 --- a/Task/Combinations/CoffeeScript/combinations-2.coffee +++ /dev/null @@ -1,39 +0,0 @@ -> coffee combo.coffee ------- 5 0 -[] ------- 5 1 -[ 0 ] -[ 1 ] -[ 2 ] -[ 3 ] -[ 4 ] ------- 5 2 -[ 0, 1 ] -[ 0, 2 ] -[ 0, 3 ] -[ 0, 4 ] -[ 1, 2 ] -[ 1, 3 ] -[ 1, 4 ] -[ 2, 3 ] -[ 2, 4 ] -[ 3, 4 ] ------- 5 3 -[ 0, 1, 2 ] -[ 0, 1, 3 ] -[ 0, 1, 4 ] -[ 0, 2, 3 ] -[ 0, 2, 4 ] -[ 0, 3, 4 ] -[ 1, 2, 3 ] -[ 1, 2, 4 ] -[ 1, 3, 4 ] -[ 2, 3, 4 ] ------- 5 4 -[ 0, 1, 2, 3 ] -[ 0, 1, 2, 4 ] -[ 0, 1, 3, 4 ] -[ 0, 2, 3, 4 ] -[ 1, 2, 3, 4 ] ------- 5 5 -[ 0, 1, 2, 3, 4 ] diff --git a/Task/Combinations/Elena/combinations.elena b/Task/Combinations/Elena/combinations.elena index 035574691d..d86e19b8c8 100644 --- a/Task/Combinations/Elena/combinations.elena +++ b/Task/Combinations/Elena/combinations.elena @@ -1,25 +1,22 @@ -#define system. -#define system'routines. -#define extensions. -#define extensions'routines. +import system'routines. +import extensions. +import extensions'routines. -#symbol(const)M = 3. -#symbol(const)N = 5. +const int M = 3. +const int N = 5. -// --- Numbers --- - -#symbol numbers = (:anN) +numbers = (:anN) [ - Array new &length:(anN int) set &every: (&index:n) [ Integer new &int:n ] + ^ Array new length:anN; populate(:n)( n ) ]. -// --- Program --- - -#symbol program = +program = [ - #var aNumbers := numbers eval:N. - Combinator new:M &of:aNumbers run &each: aRow + var aNumbers := numbers eval:N. + Combinator new:M of:aNumbers; forEach(:aRow) [ - console writeLine:aRow. + console printLine:aRow ]. + + console readChar. ]. diff --git a/Task/Combinations/Fortran/combinations-3.f b/Task/Combinations/Fortran/combinations-3.f deleted file mode 100644 index 4c8a46967c..0000000000 --- a/Task/Combinations/Fortran/combinations-3.f +++ /dev/null @@ -1,10 +0,0 @@ -1 2 3 -1 2 4 -1 2 5 -1 3 4 -1 3 5 -1 4 5 -2 3 4 -2 3 5 -2 4 5 -3 4 5 diff --git a/Task/Combinations/JavaScript/combinations-6.js b/Task/Combinations/JavaScript/combinations-6.js index 99cce48212..c46a81e5a1 100644 --- a/Task/Combinations/JavaScript/combinations-6.js +++ b/Task/Combinations/JavaScript/combinations-6.js @@ -1,47 +1,65 @@ -(function (n) { - 'use strict'; +(() => { - - // n -> [a] -> [[a]] - let comb = (n, xs) => { - if (n < 1) return [[]]; + // combinations :: Int -> [a] -> [[a]] + const combinations = (n, xs) => { + const cmb_ = (n, xs) => { + if (n < 1) return [ + [] + ]; if (xs.length === 0) return []; - - let h = xs[0], + const h = xs[0], tail = xs.slice(1); + return cmb_(n - 1, tail) + .map(cons(h)) + .concat(cmb_(n, tail)); + }; + return memoized(cmb_)(n, xs); + } - return comb(n - 1, tail) - .map((t) => [h].concat(t)) - .concat(comb(n, tail)); - }, + // GENERIC FUNCTIONS ------------------------------------------------------ + // 2 or more arguments + // curry :: Function -> Function + const curry = (f, ...args) => { + const go = xs => xs.length >= f.length ? (f.apply(null, xs)) : + function () { + return go(xs.concat(Array.from(arguments))); + }; + return go([].slice.call(args, 1)); + }; + // cons :: a -> [a] -> [a] + const cons = curry((x, xs) => [x].concat(xs)); - // Derive a memoized version of a function - // Function -> Function - memoized = (f) => { - let m = {}; + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); - return function (x) { - let args = [].slice.call(arguments), - strKey = args.join('-'), - v = m[strKey]; + // Derive a memoized version of a function + // memoized :: Function -> Function + const memoized = f => { + let m = {}; + return function (x) { + let args = [].slice.call(arguments), + strKey = args.join('-'), + v = m[strKey]; + return ( + (v === undefined) && + (m[strKey] = v = f.apply(null, args)), + v + ); + } + }; - return ( - (v === undefined) && - (m[strKey] = v = f.apply(null, args)), - v - ); - } - }, + // show :: a -> String + const show = (...x) => + JSON.stringify.apply( + null, x.length > 1 ? [x[0], null, x[1]] : x + ); - range = (m, n) => - Array.from({ - length: (n - m) + 1 - }, (_, i) => m + i); - - - return memoized(comb)(n, range(0, 4)) - - -})(3); + return show( + memoized(combinations)(3, enumFromTo(0, 4)) + ); +})(); diff --git a/Task/Combinations/JavaScript/combinations-7.js b/Task/Combinations/JavaScript/combinations-7.js new file mode 100644 index 0000000000..bd1ec4e5a4 --- /dev/null +++ b/Task/Combinations/JavaScript/combinations-7.js @@ -0,0 +1,68 @@ +(() => { + 'use strict'; + + // COMBINATIONS ----------------------------------------------------------- + + // comb :: Int -> Int -> [[Int]] + const comb = (m, n) => combinations(m, enumFromTo(0, n - 1)); + + // combinations :: Int -> [a] -> [[a]] + const combinations = (k, xs) => + sort(filter(xs => k === xs.length, subsequences(xs))); + + + // GENERIC FUNCTIONS ----------------------------------------------------- + + // cons :: a -> [a] -> [a] + const cons = (x, xs) => [x].concat(xs); + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // filter :: (a -> Bool) -> [a] -> [a] + const filter = (f, xs) => xs.filter(f); + + // foldr (a -> b -> b) -> b -> [a] -> b + const foldr = (f, a, xs) => xs.reduceRight(f, a); + + // isNull :: [a] -> Bool + const isNull = xs => (xs instanceof Array) ? xs.length < 1 : undefined; + + // show :: a -> String + const show = x => JSON.stringify(x) //, null, 2); + + // sort :: Ord a => [a] -> [a] + const sort = xs => xs.sort(); + + // stringChars :: String -> [Char] + const stringChars = s => s.split(''); + + // subsequences :: [a] -> [[a]] + const subsequences = xs => { + + // nonEmptySubsequences :: [a] -> [[a]] + const nonEmptySubsequences = xxs => { + if (isNull(xxs)) return []; + const [x, xs] = uncons(xxs); + const f = (r, ys) => cons(ys, cons(cons(x, ys), r)); + + return cons([x], foldr(f, [], nonEmptySubsequences(xs))); + }; + + return nonEmptySubsequences( + (typeof xs === 'string' ? stringChars(xs) : xs) + ); + }; + + // uncons :: [a] -> Maybe (a, [a]) + const uncons = xs => xs.length ? [xs[0], xs.slice(1)] : undefined; + + + // TEST ------------------------------------------------------------------- + return show( + comb(3, 5) + ); +})(); diff --git a/Task/Combinations/jq/combinations.jq b/Task/Combinations/Jq/combinations.jq similarity index 100% rename from Task/Combinations/jq/combinations.jq rename to Task/Combinations/Jq/combinations.jq diff --git a/Task/Combinations/Julia/combinations.julia b/Task/Combinations/Julia/combinations.julia index 69daa9fd3b..3bffe97cdf 100644 --- a/Task/Combinations/Julia/combinations.julia +++ b/Task/Combinations/Julia/combinations.julia @@ -1,3 +1,4 @@ +using Combinatorics n = 4 m = 3 for i in combinations(0:n,m) diff --git a/Task/Combinations/Kotlin/combinations.kotlin b/Task/Combinations/Kotlin/combinations.kotlin new file mode 100644 index 0000000000..bb6efa51f0 --- /dev/null +++ b/Task/Combinations/Kotlin/combinations.kotlin @@ -0,0 +1,25 @@ +class Combinations(val m: Int, val n: Int) { + private val combination = IntArray(m) + + init { + generate(0) + } + + private fun generate(k: Int) { + if (k >= m) { + for (i in 0 until m) print("${combination[i]} ") + println() + } + else { + for (j in 0 until n) + if (k == 0 || j > combination[k - 1]) { + combination[k] = j + generate(k + 1) + } + } + } +} + +fun main(args: Array) { + Combinations(3, 5) +} diff --git a/Task/Combinations/OCaml/combinations-2.ocaml b/Task/Combinations/OCaml/combinations-2.ocaml index 3e2d015be3..0108b7c48d 100644 --- a/Task/Combinations/OCaml/combinations-2.ocaml +++ b/Task/Combinations/OCaml/combinations-2.ocaml @@ -1,16 +1,21 @@ let comb m xs = let xs = Array.of_list xs in + if m > Array.length xs then [] else begin + let arr = Array.make (m+1) [] in arr.(0) <- [[]]; + for j = 0 to Array.length xs - m do for i = 1 to m do - arr.(i) <- arr.(i) @ List.map (fun ys -> xs.(j+i-1)::ys) arr.(i-1) + arr.(i) <- arr.(i) @ List.map (fun ys -> xs.(j+i-1)::ys) arr.(i-1) done done; + arr.(m) + end ;; comb 3 [0;1;2;3;4];; diff --git a/Task/Combinations/PHP/combinations-1.php b/Task/Combinations/PHP/combinations-1.php new file mode 100644 index 0000000000..b16134bdd0 --- /dev/null +++ b/Task/Combinations/PHP/combinations-1.php @@ -0,0 +1,50 @@ + = 0) { + + if ($i == 0 && $b[$i] == $n-$k+1) break 2; + + $m=array_search($b[$i]+1,$c); + if ($m!==false) { + $c[$m]=$c[$m]-1; + $b[$i]=$b[$i]+1; + + $g=$i; + while ($g != $k-1) { + array_unshift ($c, $b[$g+1]); + $b[$g+1]=$b[$g]+1; + $g++; + } + $c=array_diff($c,$b); + print_r($b); + break; + } + $i--; + + } + + } + + +} + +?> diff --git a/Task/Combinations/PHP/combinations.php b/Task/Combinations/PHP/combinations-2.php similarity index 100% rename from Task/Combinations/PHP/combinations.php rename to Task/Combinations/PHP/combinations-2.php diff --git a/Task/Combinations/Perl-6/combinations-3.pl6 b/Task/Combinations/Perl-6/combinations-3.pl6 deleted file mode 100644 index a5fd07dc76..0000000000 --- a/Task/Combinations/Perl-6/combinations-3.pl6 +++ /dev/null @@ -1,10 +0,0 @@ -sub combinations(Int $n, Int $k) { - return [] if $k == 0; - return () if $k > $n; - gather { - take [0, (1..^$n)[@$_]] for combinations($n-1, $k-1); - take [(1..^$n)[@$_]] for combinations($n-1, $k ); - } -} - -.say for combinations(5, 3); diff --git a/Task/Combinations/Prolog/combinations-4.pro b/Task/Combinations/Prolog/combinations-4.pro deleted file mode 100644 index dd41062347..0000000000 --- a/Task/Combinations/Prolog/combinations-4.pro +++ /dev/null @@ -1,3 +0,0 @@ -:- use_module(library(clpfd)). -comb_lstcomp(N, M, V) :- - V <- {L & length(L, N), L ins 1..M & all_distinct(L), chain(L, #<), label(L)}. diff --git a/Task/Combinations/Sidef/combinations-1.sidef b/Task/Combinations/Sidef/combinations-1.sidef index 3b989fa581..adece9dd0c 100644 --- a/Task/Combinations/Sidef/combinations-1.sidef +++ b/Task/Combinations/Sidef/combinations-1.sidef @@ -1 +1 @@ -(@^5).combinations(3, {|c| say c }) +combinations(5, 3, {|*c| say c }) diff --git a/Task/Combinations/Stata/combinations-1.stata b/Task/Combinations/Stata/combinations-1.stata new file mode 100644 index 0000000000..b8a12866ed --- /dev/null +++ b/Task/Combinations/Stata/combinations-1.stata @@ -0,0 +1,13 @@ +program combin +tempfile cp +tempvar k +gen `k'=1 +quietly save "`cp'" +rename `1' `1'1 +forv i=2/`2' { + joinby `k' using "`cp'" + rename `1' `1'`i' + quietly drop if `1'`i'<=`1'`=`i'-1' +} +sort `1'* +end diff --git a/Task/Combinations/Stata/combinations-2.stata b/Task/Combinations/Stata/combinations-2.stata new file mode 100644 index 0000000000..c2f31b1b24 --- /dev/null +++ b/Task/Combinations/Stata/combinations-2.stata @@ -0,0 +1,20 @@ +. set obs 5 +. gen a=_n +. combin a 3 +. list + + +--------------+ + | a1 a2 a3 | + |--------------| + 1. | 1 2 3 | + 2. | 1 2 4 | + 3. | 1 2 5 | + 4. | 1 3 4 | + 5. | 1 3 5 | + |--------------| + 6. | 1 4 5 | + 7. | 2 3 4 | + 8. | 2 3 5 | + 9. | 2 4 5 | + 10. | 3 4 5 | + +--------------+ diff --git a/Task/Combinations/Zkl/combinations-1.zkl b/Task/Combinations/Zkl/combinations-1.zkl new file mode 100644 index 0000000000..aaf220f984 --- /dev/null +++ b/Task/Combinations/Zkl/combinations-1.zkl @@ -0,0 +1,9 @@ +fcn comb(k,seq){ // no repeats, seq is finite + seq=seq.makeReadOnly(); // because I append to parts of seq + fcn(k,seq){ + if(k<=0) return(T(T)); + if(not seq) return(T); + self.fcn(k-1,seq[1,*]).pump(List,seq[0,1].extend) + .extend(self.fcn(k,seq[1,*])); + }(k,seq); +} diff --git a/Task/Combinations/Zkl/combinations-2.zkl b/Task/Combinations/Zkl/combinations-2.zkl new file mode 100644 index 0000000000..b9282addd0 --- /dev/null +++ b/Task/Combinations/Zkl/combinations-2.zkl @@ -0,0 +1 @@ +comb(3,"abcde".split("")).apply("concat") diff --git a/Task/Comma-quibbling/360-Assembly/comma-quibbling.360 b/Task/Comma-quibbling/360-Assembly/comma-quibbling.360 new file mode 100644 index 0000000000..130fd3dc7c --- /dev/null +++ b/Task/Comma-quibbling/360-Assembly/comma-quibbling.360 @@ -0,0 +1,77 @@ +* Comma quibbling 13/03/2017 +COMMAQUI CSECT + USING COMMAQUI,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + LA R6,1 i=1 + DO WHILE=(C,R6,LE,=A(N)) do i=1 to hbound(t) + LR R1,R6 i + SLA R1,5 *32 + LA R2,T-32 @t(0) + AR R1,R2 @t(i) + MVC S1,0(R1) s1=t(i) + MVC S2,=CL32'{' s2='{' + LA R8,S2+1 s2ins=1 + MVC I2,=F'0' i2=0 + LA R7,1 j=1 + DO WHILE=(C,R7,LE,=A(L'T)) do j=1 to length(t) + LA R1,S1 @s1 + BCTR R1,0 @s1-1 + AR R1,R7 @s1-1+j + MVC CJ,0(R1) cj=mid(s1,j,1) + CLI CJ,C' ' if cj=' ' + BE EXITJ then goto exitj + IF CLI,CJ,EQ,C',' THEN if cj="," then + MVC 0(2,R8),=C', ' s2=s2||", " + LA R8,2(R8) s2ins=s2ins+2 + LR R0,R8 s2ins + LA R1,S2+1 @s2+1 + SR R0,R1 len(s2)-1 + ST R0,I2 i2=len(s2)-1 + ELSE , else + MVC 0(1,R8),CJ s2=s2||cj + LA R8,1(R8) s2ins=s2ins+1 + ENDIF , endif + LA R7,1(R7) j++ + ENDDO , enddo j +EXITJ MVI 0(R8),C'}' s2=s2||"}" + LA R8,1(R8) s2ins=s2ins+1 + L R0,I2 i2 + IF LTR,R0,NZ,R0 THEN if i2<>0 then + MVC S2B,S2 s2b=mid(s2,1,i2-1) + LA R1,S2B-1 @s2b-1 + A R1,I2 +i2 + MVC 0(5,R1),=C' and ' s2b||" and " + LA R1,5(R1) +5 + LA R2,S2+1 @s2+1 + A R2,I2 +i2 + LR R3,R8 s2ins + LA R0,S2+1 @s2+1 + SR R3,R0 s2ins-(@s2+1) + S R3,I2 -i2 + BCTR R3,0 -1 + EX R3,XMVC s2b||=mid(s2,i2+2) + MVC S2,S2B s2=mid(s2,1,i2-1)||" and "||mid(s2,i2+2) + ENDIF , endif + XPRNT S2,L'S2 print s2 + LA R6,1(R6) i++ + ENDDO , enddo i + L R13,4(0,R13) restore previous savearea pointer + LM R14,R12,12(R13) restore previous context + XR R15,R15 rc=0 + BR R14 exit +XMVC MVC 0(0,R1),0(R2) mvc @r1,@r2 +N EQU (TEND-T)/L'T items of t +T DC CL32' ',CL32'ABC',CL32'ABC,DEF',CL32'ABC,DEF,G,H' +TEND DS 0C +I2 DS F +S1 DS CL(L'T) +S2 DS CL(L'T) +S2B DS CL(L'T) +CJ DS CL1 + YREGS + END COMMAQUI diff --git a/Task/Comma-quibbling/AppleScript/comma-quibbling.applescript b/Task/Comma-quibbling/AppleScript/comma-quibbling.applescript new file mode 100644 index 0000000000..8f9067fd3b --- /dev/null +++ b/Task/Comma-quibbling/AppleScript/comma-quibbling.applescript @@ -0,0 +1,185 @@ +-- quibble :: [String] -> String +on quibble(xs) + if length of xs > 1 then + set applyCommas to ¬ + compose([curry(my intercalate)'s |λ|(", "), my |reverse|, my tail]) + + intercalate(" and ", ap({applyCommas, my head}, {|reverse|(xs)})) + else + concat(xs) + end if +end quibble + +-- TEST ----------------------------------------------------------------------- +on run + script braces + on |λ|(x) + "{" & x & "}" + end |λ| + end script + + unlines(map(compose({braces, quibble}), ¬ + append({{}, {"ABC"}, {"ABC", "DEF"}, {"ABC", "DEF", "G", "H"}}, ¬ + map(|words|, ¬ + {"One two three four", "Me myself I", "Jack Jill", "Loner"})))) +end run + + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- A list of functions applied to a list of arguments +-- (<*> | ap) :: [(a -> b)] -> [a] -> [b] +on ap(fs, xs) + set {intFs, intXs} to {length of fs, length of xs} + set lst to {} + repeat with i from 1 to intFs + tell mReturn(item i of fs) + repeat with j from 1 to intXs + set end of lst to |λ|(contents of (item j of xs)) + end repeat + end tell + end repeat + return lst +end ap + +-- (++) :: [a] -> [a] -> [a] +on append(xs, ys) + xs & ys +end append + +-- compose :: [(a -> a)] -> (a -> a) +on compose(fs) + script + on |λ|(x) + script + on |λ|(a, f) + mReturn(f)'s |λ|(a) + end |λ| + end script + + foldr(result, x, fs) + end |λ| + end script +end compose + +-- concat :: [[a]] -> [a] | [String] -> String +on concat(xs) + script append + on |λ|(a, b) + a & b + end |λ| + end script + + if length of xs > 0 and class of (item 1 of xs) is string then + set unit to "" + else + set unit to {} + end if + foldl(append, unit, xs) +end concat + +-- curry :: (Script|Handler) -> Script +on curry(f) + script + on |λ|(a) + script + on |λ|(b) + |λ|(a, b) of mReturn(f) + end |λ| + end script + end |λ| + end script +end curry + +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl + +-- foldr :: (a -> b -> a) -> a -> [b] -> a +on foldr(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from lng to 1 by -1 + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldr + +-- head :: [a] -> a +on head(xs) + if length of xs > 0 then + item 1 of xs + else + missing value + end if +end head + +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- |reverse| :: [a] -> [a] +on |reverse|(xs) + if class of xs is text then + (reverse of characters of xs) as text + else + reverse of xs + end if +end |reverse| + +-- tail :: [a] -> [a] +on tail(xs) + if length of xs > 1 then + items 2 thru -1 of xs + else + {} + end if +end tail + +-- unlines :: [String] -> String +on unlines(xs) + intercalate(linefeed, xs) +end unlines + +-- words :: String -> [String] +on |words|(s) + words of s +end |words| diff --git a/Task/Comma-quibbling/Astro/comma-quibbling.astro b/Task/Comma-quibbling/Astro/comma-quibbling.astro new file mode 100644 index 0000000000..6c2216ce1f --- /dev/null +++ b/Task/Comma-quibbling/Astro/comma-quibbling.astro @@ -0,0 +1,11 @@ +fun commaQuibble(s): + result = "" + for (i, c) in enumerate(s): + if i > 0: + result += ", " if i < s[!0] else "and " + result += c + result = "{ $result }" + +var s = [ [] ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] ] + +for i in s: print commaQuibble i diff --git a/Task/Comma-quibbling/Gambas/comma-quibbling.gambas b/Task/Comma-quibbling/Gambas/comma-quibbling.gambas new file mode 100644 index 0000000000..ee94990564 --- /dev/null +++ b/Task/Comma-quibbling/Gambas/comma-quibbling.gambas @@ -0,0 +1,15 @@ +Public Sub Main() +Dim sInput As String[] = ["", "ABC", "ABC DEF", "ABC DEF G H"] +Dim sTemp As String + +For Each sTemp In sInput + Print sTemp & " = "; + sTemp = Replace(sTemp, " ", ",") + If RInStr(sTemp, ",") > 0 Then + sTemp = Mid(sTemp, 1, RInStr(sTemp, ",") - 1) & " and " & Mid(sTemp, RInStr(sTemp, ",") + 1) + End If + sTemp = "{" & sTemp & "}" + Print sTemp +Next + +End diff --git a/Task/Comma-quibbling/Haskell/comma-quibbling.hs b/Task/Comma-quibbling/Haskell/comma-quibbling-1.hs similarity index 100% rename from Task/Comma-quibbling/Haskell/comma-quibbling.hs rename to Task/Comma-quibbling/Haskell/comma-quibbling-1.hs diff --git a/Task/Comma-quibbling/Haskell/comma-quibbling-2.hs b/Task/Comma-quibbling/Haskell/comma-quibbling-2.hs new file mode 100644 index 0000000000..de5525b228 --- /dev/null +++ b/Task/Comma-quibbling/Haskell/comma-quibbling-2.hs @@ -0,0 +1,15 @@ +import Data.List (intercalate) + +quibble :: [String] -> String +quibble ws + | length ws > 1 = + intercalate + " and " + ([intercalate ", " . reverse . tail, head] <*> [reverse ws]) + | otherwise = concat ws + +main :: IO () +main = + mapM_ (putStrLn . (`intercalate` ["{", "}"]) . quibble) $ + [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]] ++ + (words <$> ["One two three four", "Me myself I", "Jack Jill", "Loner"]) diff --git a/Task/Comma-quibbling/JavaScript/comma-quibbling.js b/Task/Comma-quibbling/JavaScript/comma-quibbling-1.js similarity index 100% rename from Task/Comma-quibbling/JavaScript/comma-quibbling.js rename to Task/Comma-quibbling/JavaScript/comma-quibbling-1.js diff --git a/Task/Comma-quibbling/JavaScript/comma-quibbling-2.js b/Task/Comma-quibbling/JavaScript/comma-quibbling-2.js new file mode 100644 index 0000000000..76d2561011 --- /dev/null +++ b/Task/Comma-quibbling/JavaScript/comma-quibbling-2.js @@ -0,0 +1,93 @@ +(() => { + 'use strict'; + + // COMMA QUIBBLING ------------------------------------------------------- + + // quibble :: [String] -> String + const quibble = xs => + (xs.length > 1) ? ( + intercalate( + " and ", + ap( + [compose([intercalate(", "), reverse, tail]), head], // + [reverse(xs)] + ) + ) + ) : concat(xs); + + + // GENERIC FUNCTIONS ----------------------------------------------------- + + // A list of functions applied to a list of arguments + // <*> :: [(a -> b)] -> [a] -> [b] + const ap = (fs, xs) => // + [].concat.apply([], fs.map(f => // + [].concat.apply([], xs.map(x => [f(x)])))); + + // curry :: Function -> Function + const curry = (f, ...args) => { + const go = xs => xs.length >= f.length ? (f.apply(null, xs)) : + function () { + return go(xs.concat([].slice.apply(arguments))); + }; + return go([].slice.call(args, 1)); + }; + + // intercalate :: String -> [a] -> String + const intercalate = curry((s, xs) => xs.join(s)); + + // concat :: [[a]] -> [a] | [String] -> String + const concat = xs => { + if (xs.length > 0) { + const unit = typeof xs[0] === 'string' ? '' : []; + return unit.concat.apply(unit, xs); + } else return []; + }; + + // compose :: [(a -> a)] -> (a -> a) + const compose = fs => x => fs.reduceRight((a, f) => f(a), x); + + // map :: (a -> b) -> [a] -> [b] + const map = curry((f, xs) => xs.map(f)); + + // reverse :: [a] -> [a] + const reverse = xs => + typeof xs === 'string' ? ( + xs.split('') + .reverse() + .join('') + ) : xs.slice(0) + .reverse(); + + // head :: [a] -> a + const head = xs => xs.length ? xs[0] : undefined; + + // tail :: [a] -> [a] + const tail = xs => xs.length ? xs.slice(1) : undefined; + + // (++) :: [a] -> [a] -> [a] + const append = (xs, ys) => xs.concat(ys); + + // words :: String -> [String] + const words = s => s.split(/\s+/); + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + + // TEST ------------------------------------------------------------------ + return unlines( + map( + compose([x => '{' + x + '}', quibble]), + append([ + [], + ["ABC"], + ["ABC", "DEF"], + ["ABC", "DEF", "G", "H"] + ], map( + words, [ + "One two three four", "Me myself I", "Jack Jill", "Loner" + ] + )) + )); +})(); diff --git a/Task/Comma-quibbling/jq/comma-quibbling-1.jq b/Task/Comma-quibbling/Jq/comma-quibbling-1.jq similarity index 100% rename from Task/Comma-quibbling/jq/comma-quibbling-1.jq rename to Task/Comma-quibbling/Jq/comma-quibbling-1.jq diff --git a/Task/Comma-quibbling/jq/comma-quibbling-2.jq b/Task/Comma-quibbling/Jq/comma-quibbling-2.jq similarity index 100% rename from Task/Comma-quibbling/jq/comma-quibbling-2.jq rename to Task/Comma-quibbling/Jq/comma-quibbling-2.jq diff --git a/Task/Comma-quibbling/jq/comma-quibbling-3.jq b/Task/Comma-quibbling/Jq/comma-quibbling-3.jq similarity index 100% rename from Task/Comma-quibbling/jq/comma-quibbling-3.jq rename to Task/Comma-quibbling/Jq/comma-quibbling-3.jq diff --git a/Task/Comma-quibbling/Kotlin/comma-quibbling.kotlin b/Task/Comma-quibbling/Kotlin/comma-quibbling.kotlin new file mode 100644 index 0000000000..743ef8e4f5 --- /dev/null +++ b/Task/Comma-quibbling/Kotlin/comma-quibbling.kotlin @@ -0,0 +1,26 @@ +// version 1.0.6 + +fun commaQuibble(s: String): String { + val t = s.trim('[', ']').replace(" ", "").replace("\"", "") + val words = t.split(',') + val sb = StringBuilder("{") + for (i in 0 until words.size) { + sb.append(when (i) { + 0 -> "" + words.lastIndex -> " and " + else -> ", " + }) + sb.append(words[i]) + } + return sb.append("}").toString() +} + +fun main(args: Array) { + val inputs = arrayOf( + """[]""", + """["ABC"]""", + """["ABC", "DEF"]""", + """["ABC", "DEF", "G", "H"]""" + ) + for (input in inputs) println("${input.padEnd(24)} -> ${commaQuibble(input)}") +} diff --git a/Task/Comma-quibbling/Pascal/comma-quibbling.pascal b/Task/Comma-quibbling/Pascal/comma-quibbling.pascal new file mode 100644 index 0000000000..acd7b7b663 --- /dev/null +++ b/Task/Comma-quibbling/Pascal/comma-quibbling.pascal @@ -0,0 +1,61 @@ +program CommaQuibbling; +uses Classes, StrUtils; + +const OuterBracket=['[',']']; + +type + + { TCommaQuibble } + + TCommaQuibble = class(TStringList) + private + function GetCommaquibble: string; + procedure SetCommaQuibble(AValue: string); + public + property CommaQuibble: string read GetCommaquibble write SetCommaQuibble; + end; + +{ TCommaQuibble } + +procedure TCommaQuibble.SetCommaQuibble(AValue: string); +begin + AValue:=ExtractWord(1,AValue,OuterBracket); + commatext:=Avalue; +end; + +function TCommaQuibble.GetCommaquibble: string; +var x: Integer; + Del: String; +begin + result:=''; + Del:=', '; + for x:=0 to Count-1 do + begin + result+=Strings[x]; + if x=Count-2 then Del:=' and ' + else if x=count-1 then Del:=''; + result+=del; + end; + result:='{'+result+'}'; +end; + +const TestData: array [0..7] of string=( '[]', + '["ABC"]', + '["ABC", "DEF"]', + '["ABC", "DEF", "G", "H"]', + '', + '"ABC"', + '"ABC", "DEF"', + '"ABC", "DEF", "G", "H"'); +var Quibble: TCommaQuibble; + TestString: String; +begin + Quibble:=TCommaQuibble.Create; + + for TestString in TestData do + begin + Quibble.CommaQuibble:=TestString; + writeln(Quibble.CommaQuibble); + end; + +end. diff --git a/Task/Comma-quibbling/Phix/comma-quibbling.phix b/Task/Comma-quibbling/Phix/comma-quibbling.phix new file mode 100644 index 0000000000..fc473e5064 --- /dev/null +++ b/Task/Comma-quibbling/Phix/comma-quibbling.phix @@ -0,0 +1,15 @@ +function quibble(sequence words) + if length(words)>=2 then + words[-2..-1] = {words[-2]&" and "&words[-1]} + end if + return "{"&join(words,", ")&"}" +end function + +constant tests = {{}, + {"ABC"}, + {"ABC","DEF"}, + {"ABC","DEF","G","H"}} + +for i=1 to length(tests) do + ?quibble(tests[i]) +end for diff --git a/Task/Comma-quibbling/Scheme/comma-quibbling.ss b/Task/Comma-quibbling/Scheme/comma-quibbling.ss new file mode 100644 index 0000000000..b5904f8b9e --- /dev/null +++ b/Task/Comma-quibbling/Scheme/comma-quibbling.ss @@ -0,0 +1,15 @@ +(define (quibble . args) + (display "{") + (do ((rem args (cdr rem))) + ((null? rem) (display "}\n")) + (display (car rem)) + (cond ((= 1 (length rem)) ) + ((= 2 (length rem)) + (display " and ")) + (else + (display ", "))))) + +(quibble) +(quibble "ABC") +(quibble "ABC" "DEF") +(quibble "ABC" "DEF" "G" "H") diff --git a/Task/Comma-quibbling/TXR/comma-quibbling.txr b/Task/Comma-quibbling/TXR/comma-quibbling.txr new file mode 100644 index 0000000000..d5d8ea2d8d --- /dev/null +++ b/Task/Comma-quibbling/TXR/comma-quibbling.txr @@ -0,0 +1,3 @@ +(defun quib (list) + (tree-bind (: last . lead) (reverse list) + `{@{(nreverse lead) ", "}@(if lead " and ")@last}`)) diff --git a/Task/Comma-quibbling/Zkl/comma-quibbling.zkl b/Task/Comma-quibbling/Zkl/comma-quibbling.zkl new file mode 100644 index 0000000000..c9fedf68f6 --- /dev/null +++ b/Task/Comma-quibbling/Zkl/comma-quibbling.zkl @@ -0,0 +1,7 @@ +fcn quib(list){ text:=("{"+list.toString(*)[2,-1]+"}").replace("\"",""); + if(list.len()<2) text; + else{ + z:=(text=text.replace(",",", ")).rfind(","); + String(text[0,z]," and ",text[z+2,*]) + } +} diff --git a/Task/Command-line-arguments/BASIC/command-line-arguments-3.basic b/Task/Command-line-arguments/BASIC/command-line-arguments-3.basic new file mode 100644 index 0000000000..ed5a174bdc --- /dev/null +++ b/Task/Command-line-arguments/BASIC/command-line-arguments-3.basic @@ -0,0 +1,9 @@ +' Command line arguments including program name +PRINT "Entire command line: ", ARGUMENT$ + +SPLIT ARGUMENT$ BY " " TO cli$ SIZE args +PRINT "Skip program name:"; +FOR i = 1 TO args - 1 + PRINT " " & cli$[i]; +NEXT +PRINT diff --git a/Task/Command-line-arguments/D/command-line-arguments-1.d b/Task/Command-line-arguments/D/command-line-arguments-1.d deleted file mode 100644 index 18aeaf3ebb..0000000000 --- a/Task/Command-line-arguments/D/command-line-arguments-1.d +++ /dev/null @@ -1,6 +0,0 @@ -import std.stdio ; - -void main(string[] args) { - foreach(i, e ; args[1..$]) - writefln("#%2d : %s", i + 1, e) ; -} diff --git a/Task/Command-line-arguments/D/command-line-arguments-2.d b/Task/Command-line-arguments/D/command-line-arguments-2.d deleted file mode 100644 index ef885e8a8a..0000000000 --- a/Task/Command-line-arguments/D/command-line-arguments-2.d +++ /dev/null @@ -1,18 +0,0 @@ -import tango.text.Arguments; -import tango.io.Stdout; - -void main(char[][] realArgs) -{ - auto args = new Arguments; - - args("hello").required.params(1).requires("world"); - args("world").params(1).aliased('w'); - - if (! args.parse(realArgs)) { - Stdout ("bad arguments"); - - } else { - Stdout("argument for --hello ") (args("hello").assigned).newline; - Stdout("argument for --world ") (args("world").assigned).newline; - } -} diff --git a/Task/Command-line-arguments/Elena/command-line-arguments.elena b/Task/Command-line-arguments/Elena/command-line-arguments.elena index 81e1cdfa3e..cce089875e 100644 --- a/Task/Command-line-arguments/Elena/command-line-arguments.elena +++ b/Task/Command-line-arguments/Elena/command-line-arguments.elena @@ -1,9 +1,8 @@ -#import system. -#import system'routines. -#import extensions. +import system'routines. +import extensions. -#symbol program = +program = [ - 'program'arguments run &every:(&index:i) - [ console writeLine:"Argument ":i:" is ":('program'arguments@i). ]. -] + 'program'arguments forEvery(:i) + [ console printLine("Argument ",i," is ",'program'arguments[i]) ] +]. diff --git a/Task/Command-line-arguments/Gambas/command-line-arguments.gambas b/Task/Command-line-arguments/Gambas/command-line-arguments.gambas index b460d3a57d..ce671a6228 100644 --- a/Task/Command-line-arguments/Gambas/command-line-arguments.gambas +++ b/Task/Command-line-arguments/Gambas/command-line-arguments.gambas @@ -7,4 +7,4 @@ PUBLIC SUB main() parm = Application.Args[l] PRINT l; " : "; parm NEXT -END SUB +END diff --git a/Task/Command-line-arguments/Go/command-line-arguments.go b/Task/Command-line-arguments/Go/command-line-arguments.go index e2d9506e38..8dd439b156 100644 --- a/Task/Command-line-arguments/Go/command-line-arguments.go +++ b/Task/Command-line-arguments/Go/command-line-arguments.go @@ -1,15 +1,11 @@ package main import ( - "fmt" - "os" + "fmt" + "os" ) func main() { - for i, x := range os.Args { - if i == 0 { - fmt.Printf("This program is named %s.\n", x) - } else { - fmt.Printf("the argument #%d is %s\n", i, x) - } - } + for i, x := range os.Args[1:] { + fmt.Printf("the argument #%d is %s\n", i, x) + } } diff --git a/Task/Command-line-arguments/Jq/command-line-arguments.jq b/Task/Command-line-arguments/Jq/command-line-arguments.jq new file mode 100644 index 0000000000..434230c84b --- /dev/null +++ b/Task/Command-line-arguments/Jq/command-line-arguments.jq @@ -0,0 +1,7 @@ +{ + "positional": [ + "a", + "b" + ], + "named": {} +} diff --git a/Task/Command-line-arguments/Nim/command-line-arguments.nim b/Task/Command-line-arguments/Nim/command-line-arguments.nim index ec403db4c5..dc8ca3faa7 100644 --- a/Task/Command-line-arguments/Nim/command-line-arguments.nim +++ b/Task/Command-line-arguments/Nim/command-line-arguments.nim @@ -1,3 +1,3 @@ import os -let programName = paramStr(0) +let programName = getAppFilename() let arguments = commandLineParams() diff --git a/Task/Command-line-arguments/S-lang/command-line-arguments.slang b/Task/Command-line-arguments/S-lang/command-line-arguments.slang new file mode 100644 index 0000000000..269b4abeeb --- /dev/null +++ b/Task/Command-line-arguments/S-lang/command-line-arguments.slang @@ -0,0 +1,3 @@ +variable a; +foreach a (__argv) + print(a); diff --git a/Task/Command-line-arguments/Zkl/command-line-arguments.zkl b/Task/Command-line-arguments/Zkl/command-line-arguments.zkl new file mode 100644 index 0000000000..040894ecd9 --- /dev/null +++ b/Task/Command-line-arguments/Zkl/command-line-arguments.zkl @@ -0,0 +1,2 @@ +System.argv.println(); +vm.arglist.println(); diff --git a/Task/Comments/Bc/comments-1.bc b/Task/Comments/Bc/comments-1.bc new file mode 100644 index 0000000000..6eaf14595b --- /dev/null +++ b/Task/Comments/Bc/comments-1.bc @@ -0,0 +1,11 @@ +/* This is a comment. */ + +2 + /* Comment between tokens. */ 3 + +"This is a string, /* NOT a comment */." + +/* + * A comment can have multiple lines. These asterisks in the middle + * of the comment are only for style. You must not nest a comment + * inside another comment; the first asterisk-slash ends the comment. + */ diff --git a/Task/Comments/Bc/comments-2.bc b/Task/Comments/Bc/comments-2.bc new file mode 100644 index 0000000000..e70f3a43db --- /dev/null +++ b/Task/Comments/Bc/comments-2.bc @@ -0,0 +1,11 @@ +#!/usr/bin/bc + +# This form of comment is an extension, not part of standard bc. + +# Your program must not have a #! shebang line +# unless your bc supports this form of comment. + +2 + 3 # It can be after a statement. + +a = 1 # The newline is not part of the comment. +b = 2 # So this line is a different statement. diff --git a/Task/Comments/D/comments-1.d b/Task/Comments/D/comments-1.d deleted file mode 100644 index ab92f3d454..0000000000 --- a/Task/Comments/D/comments-1.d +++ /dev/null @@ -1,3 +0,0 @@ -/* This is a simple -C-style comment */ -// this also is diff --git a/Task/Comments/D/comments-2.d b/Task/Comments/D/comments-2.d deleted file mode 100644 index 2ad750b7fc..0000000000 --- a/Task/Comments/D/comments-2.d +++ /dev/null @@ -1,5 +0,0 @@ -/+ Nestable comment - /+ See? - +/ -+/ -Yay! I'm code! diff --git a/Task/Comments/D/comments-3.d b/Task/Comments/D/comments-3.d deleted file mode 100644 index a97bb44829..0000000000 --- a/Task/Comments/D/comments-3.d +++ /dev/null @@ -1,5 +0,0 @@ -/// I'm documentation! -/** I'm multi- -line documentation. */ -/++ And I - /++ can be nested +/ +/ diff --git a/Task/Comments/D/comments-4.d b/Task/Comments/D/comments-4.d deleted file mode 100644 index 3c660331cd..0000000000 --- a/Task/Comments/D/comments-4.d +++ /dev/null @@ -1,11 +0,0 @@ -/***************************************** -* This function solves world hunger. -* Examples: -* ---------------------------------------- -* feed_world (earth); -* ---------------------------------------- -* Date: May 4, 2011 -* Bugs: Does not solve world thirst. -* See_Also: -* SoylentGreen -* Authors: J. Random Hacker. */ diff --git a/Task/Comments/Dc/comments-1.dc b/Task/Comments/Dc/comments-1.dc new file mode 100644 index 0000000000..4acb52ced6 --- /dev/null +++ b/Task/Comments/Dc/comments-1.dc @@ -0,0 +1 @@ +[Making and discarding a string acts like a comment] sz diff --git a/Task/Comments/Dc/comments-2.dc b/Task/Comments/Dc/comments-2.dc new file mode 100644 index 0000000000..3221c4a75b --- /dev/null +++ b/Task/Comments/Dc/comments-2.dc @@ -0,0 +1 @@ +# remainder of line is a comment diff --git a/Task/Comments/Gambas/comments.gambas b/Task/Comments/Gambas/comments.gambas index 4559cac6e7..9b0eda8063 100644 --- a/Task/Comments/Gambas/comments.gambas +++ b/Task/Comments/Gambas/comments.gambas @@ -1,2 +1,6 @@ ' This whole line is a comment and is ignored by the gambas interpreter print "Hello" ' Comments after an apostrophe are ignored + '' A bold-style comment + ' TODO: To Do comment will appear in Task Bar + ' FIXME: Fix Me comment will appear in Task Bar + ' NOTE: Note commnet will appear in Task Bar diff --git a/Task/Comments/Gnuplot/comments-1.gnuplot b/Task/Comments/Gnuplot/comments-1.gnuplot new file mode 100644 index 0000000000..c426fa8315 --- /dev/null +++ b/Task/Comments/Gnuplot/comments-1.gnuplot @@ -0,0 +1,5 @@ +# this is a comment + +# backslash continues \ +a comment to the next \ +line or lines diff --git a/Task/Comments/Gnuplot/comments-2.gnuplot b/Task/Comments/Gnuplot/comments-2.gnuplot new file mode 100644 index 0000000000..bc96be4aa7 --- /dev/null +++ b/Task/Comments/Gnuplot/comments-2.gnuplot @@ -0,0 +1,7 @@ +# this doesn't work +foo(n) = (n \ + + 2 # no good \ + + 3) + +# behaves as if you wrote merely +foo(n) = (n+2 diff --git a/Task/Comments/jq/comments.jq b/Task/Comments/Jq/comments.jq similarity index 100% rename from Task/Comments/jq/comments.jq rename to Task/Comments/Jq/comments.jq diff --git a/Task/Comments/Kotlin/comments.kotlin b/Task/Comments/Kotlin/comments.kotlin new file mode 100644 index 0000000000..d51968b373 --- /dev/null +++ b/Task/Comments/Kotlin/comments.kotlin @@ -0,0 +1,31 @@ +// This is a single line comment + +/* + This is a + multi-line + comment +*/ + +/* + Multi-line comments + /* + can also be nested + */ + like so +*/ + +const val CURRENT_VERSION = "1.0.5-2" // A comment can also be added at the end of a line +const val /* or even in the middle of a line */ NEXT_MAJOR_VERSION = "1.1" + +/** + * This is a documentation comment used by KDoc. + * + * It's documenting the main function which is the entry-point to a Kotlin executable. + * + * @param [args] A string array containing the command line arguments (if any) passed to the executable + * @return Implicit return value is Unit which signifies no meaningful return value (like 'void' in java) + */ +fun main(args: Array) { + println("Current stable version is $CURRENT_VERSION") + println("Next major version is $NEXT_MAJOR_VERSION") +} diff --git a/Task/Comments/LaTeX/comments-2.tex b/Task/Comments/LaTeX/comments-2.tex index f40cc029ae..affa4fca62 100644 --- a/Task/Comments/LaTeX/comments-2.tex +++ b/Task/Comments/LaTeX/comments-2.tex @@ -1,7 +1,7 @@ -\newcommand{\firstpart}{understand} +\newcommand{\firstpart}[1]{under#1} \newcommand{\secondpart}{able} \newcommand{\complete}{% -\firstpart% +\firstpart{stand}% \secondpart} \complete diff --git a/Task/Comments/MIRC-Scripting-Language/comments.mirc b/Task/Comments/MIRC-Scripting-Language/comments.mirc new file mode 100644 index 0000000000..a57fbdd433 --- /dev/null +++ b/Task/Comments/MIRC-Scripting-Language/comments.mirc @@ -0,0 +1,6 @@ +;Single Line Comment +/* +Multiple +Line +Comment +*/ diff --git a/Task/Comments/Nimrod/comments.nimrod b/Task/Comments/Nimrod/comments.nimrod deleted file mode 100644 index a1b99fe4cd..0000000000 --- a/Task/Comments/Nimrod/comments.nimrod +++ /dev/null @@ -1,14 +0,0 @@ -# Nimrod supports only single-line comments - -var x = 0 ## Documentation comments start with double hash characters. - -var y = 0 ## Comments are a proper part of the syntax and are indentation sensitive. - ## If the next line only consists of a comment piece, it must be aligned - ## either to the preceding one (documentation generator would merge these lines) -## or to the code block (starting a new comment piece). - - # any misaligned comment line (like this one) would trigger an "invalid indentation" error - -var z = 0 ## Alternatively you can end the preceding comment piece with a backslash \ - ## to reset alignment to any column you like. - ## See also http://nimrod-code.org/tut1.html#comments diff --git a/Task/Comments/OoRexx/comments.rexx b/Task/Comments/OoRexx/comments.rexx new file mode 100644 index 0000000000..70d77a97a8 --- /dev/null +++ b/Task/Comments/OoRexx/comments.rexx @@ -0,0 +1,9 @@ +/* + Multi-line comment block + */ + +-- this type of comment works in ooRexx, NetRexx and some of the more popular REXX implementations like Regina + +hour = 0 -- which is, like midnight, dude. + +hour = 12 /* time for lunch! works as well (and really everywhere) */ diff --git a/Task/Comments/PlainTeX/comments-1.tex b/Task/Comments/PlainTeX/comments-1.tex new file mode 100644 index 0000000000..961a6d6ac6 --- /dev/null +++ b/Task/Comments/PlainTeX/comments-1.tex @@ -0,0 +1,2 @@ +% this is a comment +This is not. diff --git a/Task/Comments/PlainTeX/comments-2.tex b/Task/Comments/PlainTeX/comments-2.tex new file mode 100644 index 0000000000..0f92c2301e --- /dev/null +++ b/Task/Comments/PlainTeX/comments-2.tex @@ -0,0 +1,6 @@ +\def\firstpart#1{under#1} +\def\secondpart{able} +\def\complete{\firstpart{stand}% +\secondpart} + +\complete diff --git a/Task/Comments/Protium/comments.protium b/Task/Comments/Protium/comments.protium deleted file mode 100644 index 5cee1c62b6..0000000000 --- a/Task/Comments/Protium/comments.protium +++ /dev/null @@ -1,3 +0,0 @@ -<@ OMT>This is a -multiline -comment diff --git a/Task/Comments/SPL/comments.spl b/Task/Comments/SPL/comments.spl new file mode 100644 index 0000000000..c9e690905e --- /dev/null +++ b/Task/Comments/SPL/comments.spl @@ -0,0 +1,4 @@ +'This is single-line comment + +''This is +multiline comment'' diff --git a/Task/Comments/Sed/comments.sed b/Task/Comments/Sed/comments.sed new file mode 100644 index 0000000000..6a197623e5 --- /dev/null +++ b/Task/Comments/Sed/comments.sed @@ -0,0 +1 @@ +# a single line comment diff --git a/Task/Comments/Smart-BASIC/comments.smart b/Task/Comments/Smart-BASIC/comments.smart new file mode 100644 index 0000000000..67b635cd09 --- /dev/null +++ b/Task/Comments/Smart-BASIC/comments.smart @@ -0,0 +1,20 @@ +'Single line comments are preceded by a single quote or the command REM + +PRINT "Hello" 'Single line comments may follow code + +PRINT "Hello" REM You can also use the command REM following code + +/* +Multi-line comments +are surrounded by +mirrored slash +and asterisk +*/ + +/*Multi-line comments do not have to actually have multiple lines*/ + +/* Spaces before or after comment bounds are optional.*/ + +/* A comment can also follow another comment */ 'Like this + +Some programmers like to do this to allow for /* Procedural comments */ followed by 'Programmer's notes. diff --git a/Task/Comments/Stata/comments.stata b/Task/Comments/Stata/comments.stata new file mode 100644 index 0000000000..d706a29ffe --- /dev/null +++ b/Task/Comments/Stata/comments.stata @@ -0,0 +1,7 @@ +* Line comment: must be used at the beginning of a line (does not work in Mata) + +// Line comment until the end of the line + +/* Multiline comment + +*/ diff --git a/Task/Comments/Wart/comments.wart b/Task/Comments/Wart/comments.wart index be697a0aa5..44d0be8cac 100644 --- a/Task/Comments/Wart/comments.wart +++ b/Task/Comments/Wart/comments.wart @@ -1 +1 @@ -# single line comment +# single-line comment diff --git a/Task/Comments/Zkl/comments.zkl b/Task/Comments/Zkl/comments.zkl new file mode 100644 index 0000000000..2ac4fec049 --- /dev/null +++ b/Task/Comments/Zkl/comments.zkl @@ -0,0 +1,10 @@ +x=1; // comment ala C++ +x=2; # ala scripts +/* ala C, these comments are parsed (also ala C) */ +/* can /* be */ nested */ +#if 0 + also ala C (and parsed) +#endif +#<<<# + "here" comment, unparsed +#<<<# diff --git a/Task/Compare-sorting-algorithms-performance/Phix/compare-sorting-algorithms-performance.phix b/Task/Compare-sorting-algorithms-performance/Phix/compare-sorting-algorithms-performance.phix new file mode 100644 index 0000000000..bd8f4dae6a --- /dev/null +++ b/Task/Compare-sorting-algorithms-performance/Phix/compare-sorting-algorithms-performance.phix @@ -0,0 +1,368 @@ +-- +-- demo\rosetta\Compare_sorting_algorithms.exw +-- +constant XQS = 01 -- (set to 1 to exclude quick_sort and shell_sort from ones) + +include pGUI.e + +Ihandle dlg, tabs, plot +Ihandles plots + +function quick_sort2(sequence x) +integer n = length(x), c, mid, midn +object xi, midval +sequence left = {}, right = {} + + if n<2 then + return x -- already sorted (trivial case) + end if + + mid = floor((n+1)/2) + midval = x[mid] + x[mid] = x[1] + midn = 1 + + for i=2 to n do + xi = x[i] + c = compare(xi,midval) + if c<0 then + left &= xi + elsif c>0 then + right &= xi + else + midn += 1 + end if + end for + + return quick_sort2(left) & repeat(midval,midn) & quick_sort2(right) +end function + +function quick_sort(sequence s) +sequence qstack +integer first, last, stackptr, I, J, tmp, pivot + + qstack = repeat(0,floor((length(s)/5)+10)) -- create a stack + + first = 1 + last = length(s) + stackptr = 0 + while 1 do + while firstpivot do + J -= 1 + end while + if I>J then exit end if + if IJ then exit end if + end while + if I0 do + for i=gap to length(s) do + temp = s[i] + j = i-gap + while j>=1 and temp<=s[j] do + s[j+gap] = s[j] + j -= gap + end while + s[j+gap] = temp + end for + gap = floor(gap/2) + end while + return s +end function + +function shell_sort2(sequence x) +integer gap, j, first, last +object xi, xj + + last = length(x) + gap = floor(last/10)+1 + while TRUE do + first = gap+1 + for i=first to last do + xi = x[i] + j = i-gap + while TRUE do + xj = x[j] + if xi>=xj then + j += gap + exit + end if + x[j+gap] = xj + if j<=gap then + exit + end if + j -= gap + end while + x[j] = xi + end for + if gap=1 then + return x + else + gap = floor(gap/3.5)+1 + end if + end while +end function + +function siftDown(sequence arr, integer s, integer last) +integer root = s + while root*2<=last do + integer child = root*2 + if child=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 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 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 + +include builtins/sort.e + +enum ONES = 1, SORTED = 2, RANDOM = 3, REVERSE = 4 + +constant tabtitles = {"ones","sorted","random","reverse"} +integer tabidx = 3 + +integer STEP + +function tr(sequence name, integer rid=routine_id(name)) + return {name,rid} +end function + +constant tests = {tr("quick_sort"), + tr("quick_sort2"), + tr("radix_sort"), + tr("shell_sort"), + tr("shell_sort2"), + tr("heap_sort"), + tr("sort"), -- builtin + } + +sequence results = repeat(repeat({}, length(tests)),length(tabtitles)) + +sequence dsdx = repeat(repeat(0,length(tests)),length(tabtitles)) + +integer ds_index + +function idle_action_cb() +atom best = -1, -- fastest last + besti = 0, -- 1..length(tests) + bestt = 0, -- 1..length(tabtitles) + len +sequence todo + -- + -- Search for something to do, active/visible tab first. + -- Any result set of length 0 -> just do one. + -- Of all result sets<8, pick the lowest [$]. + -- + todo = {tabidx} + for t=1 to length(tabtitles) do + if t!=tabidx then todo &= t end if + end for + + for t=1 to length(tabtitles) do + integer ti = todo[t] + for i=1 to length(results[ti]) do + len = length(results[ti][i]) + if len=0 then + best = 0 + besti = i + bestt = ti + exit + elsif len<8 then + if (best=-1) or (best>results[ti][i][$]) then + best = results[ti][i][$] + besti = i + bestt = ti + end if + end if + end for + if (t=1) and (besti!=0) then exit end if + end for + if best>10 then + -- cop out if it is getting too slow + besti = 0 + end if + if besti!=0 then + STEP = iff(not XQS and bestt=ONES?1000:100000) + len = (length(results[bestt][besti])+1)*STEP + sequence test = iff(bestt=ONES?repeat(1,len): + iff(bestt=SORTED?tagset(len): + iff(bestt=RANDOM?shuffle(tagset(len)): + iff(bestt=REVERSE?reverse(tagset(len)):9/0)))) + ds_index = dsdx[bestt][besti] + atom t0 = time() + sequence check = call_func(tests[besti][2],{test}) + t0 = time()-t0 +-- if check!=sort(test) then ?9/0 end if + plot = plots[bestt] + IupPlotInsert(plot, ds_index, -1, len, t0) + results[bestt][besti] = append(results[bestt][besti],t0) + IupSetAttribute(plot,"REDRAW",NULL) + sequence progress = {bestt} + for i=1 to length(results[bestt]) do + progress &= length(results[bestt][i]) + end for + IupSetStrAttribute(dlg,"TITLE","Compare sorting algorithms %s",{sprint(progress)}) + return IUP_CONTINUE + end if + IupSetAttribute(dlg,"TITLE","Compare sorting algorithms (all done, idle)") + return IUP_IGNORE -- all done, remove callback +end function +constant cb_idle_action = Icallback("idle_action_cb") + +function tabchange_cb(Ihandle /*self*/, Ihandle /*new_tab*/) + tabidx = IupGetInt(tabs,"VALUEPOS")+1 + plot = plots[tabidx] + return IUP_DEFAULT; +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + + plots = {} + for i=1 to length(tabtitles) do + if XQS then +-- results[ONES][1] = repeat(0,8) + results[ONES][4] = repeat(0,8) + end if + plot = IupPlot() + IupSetAttribute(plot,"MENUITEMPROPERTIES","YES") + IupSetAttribute(plot,"TABTITLE",tabtitles[i]) + IupSetAttribute(plot,"GRID","YES") + IupSetAttribute(plot,"MARGINLEFT","50") + IupSetAttribute(plot,"MARGINBOTTOM","40") + IupSetAttribute(plot,"LEGEND","YES") + IupSetAttribute(plot,"LEGENDPOS","TOPLEFT") +-- IupSetAttribute(plot,"AXS_YSCALE","LOG10") +-- IupSetAttribute(plot,"AXS_XSCALE","LOG10") + for j=1 to length(tests) do + IupPlotBegin(plot) + dsdx[i][j] = IupPlotEnd(plot) + IupSetAttribute(plot,"DS_NAME",tests[j][1]) + end for + plots = append(plots,plot) + end for + tabs = IupTabs(plots) + IupSetCallback(tabs, "TABCHANGE_CB", Icallback("tabchange_cb")) + dlg = IupDialog(tabs) + IupSetAttributes(dlg, "RASTERSIZE=%dx%d", {640, 480}) + IupSetAttribute(dlg, "TITLE", "Compare sorting algorithms") + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + IupShow(dlg) + IupSetInt(tabs, "VALUEPOS", tabidx-1) + IupSetGlobalFunction("IDLE_ACTION", cb_idle_action) + IupMainLoop() + IupClose() +end procedure + +main() diff --git a/Task/Compile-time-calculation/360-Assembly/compile-time-calculation-1.360 b/Task/Compile-time-calculation/360-Assembly/compile-time-calculation-1.360 new file mode 100644 index 0000000000..0d4fa2e0f9 --- /dev/null +++ b/Task/Compile-time-calculation/360-Assembly/compile-time-calculation-1.360 @@ -0,0 +1,7 @@ +COMPCALA CSECT + L R1,=A(FACT10) r1=10! + XDECO R1,PG + XPRNT PG,L'PG print buffer + BR R14 exit +FACT10 EQU 10*9*8*7*6*5*4*3*2*1 factorial computation +PG DS CL12 diff --git a/Task/Compile-time-calculation/360-Assembly/compile-time-calculation-2.360 b/Task/Compile-time-calculation/360-Assembly/compile-time-calculation-2.360 new file mode 100644 index 0000000000..833ac1b1ca --- /dev/null +++ b/Task/Compile-time-calculation/360-Assembly/compile-time-calculation-2.360 @@ -0,0 +1,22 @@ + MACRO +&LAB FACT ®,&N parameters +&F SETA 1 f=1 +&I SETA 1 i=1 +.EA AIF (&I GT &N).EB ea: if i>n then goto eb +&F SETA &F*&I f=f*i +&I SETA &I+1 i=i+1 + AGO .EA goto ea +.EB ANOP eb: + MNOTE 0,'Load ® with &N! = &F' macro note +&LAB L ®,=A(&F) load reg with factorial + MEND macro end +COMPCALB CSECT + USING COMPCALB,R12 base register + LR R12,R15 set base register + FACT R1,10 macro call + XDECO R1,PG + XPRNT PG,L'PG print buffer + BR R14 exit +PG DS CL12 + YREGS + END COMPCALB diff --git a/Task/Compile-time-calculation/Kotlin/compile-time-calculation.kotlin b/Task/Compile-time-calculation/Kotlin/compile-time-calculation.kotlin new file mode 100644 index 0000000000..3c87226067 --- /dev/null +++ b/Task/Compile-time-calculation/Kotlin/compile-time-calculation.kotlin @@ -0,0 +1,6 @@ +// version 1.0.6 +const val TEN_FACTORIAL = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 + +fun main(args: Array) { + println("10! = $TEN_FACTORIAL") +} diff --git a/Task/Compile-time-calculation/M4/compile-time-calculation-1.m4 b/Task/Compile-time-calculation/M4/compile-time-calculation-1.m4 new file mode 100644 index 0000000000..603612fecc --- /dev/null +++ b/Task/Compile-time-calculation/M4/compile-time-calculation-1.m4 @@ -0,0 +1,6 @@ +define(`factorial', +`ifelse($1, 0, 1, `eval($1 * factorial(eval($1 - 1)))')')dnl +dnl +BEGIN { + print "10! is factorial(10)" +} diff --git a/Task/Compile-time-calculation/M4/compile-time-calculation-2.m4 b/Task/Compile-time-calculation/M4/compile-time-calculation-2.m4 new file mode 100644 index 0000000000..dc1a061809 --- /dev/null +++ b/Task/Compile-time-calculation/M4/compile-time-calculation-2.m4 @@ -0,0 +1,3 @@ +BEGIN { + print "10! is 3628800" +} diff --git a/Task/Compile-time-calculation/Nimrod/compile-time-calculation-1.nimrod b/Task/Compile-time-calculation/Nimrod/compile-time-calculation-1.nimrod deleted file mode 100644 index 4fcde79ead..0000000000 --- a/Task/Compile-time-calculation/Nimrod/compile-time-calculation-1.nimrod +++ /dev/null @@ -1,7 +0,0 @@ -proc fact(x: int): int = - result = 1 - for i in 2..x: - result = result * i - -const fact10 = fact(10) -echo(fact10) diff --git a/Task/Compile-time-calculation/Nimrod/compile-time-calculation-2.nimrod b/Task/Compile-time-calculation/Nimrod/compile-time-calculation-2.nimrod deleted file mode 100644 index 20754dab1b..0000000000 --- a/Task/Compile-time-calculation/Nimrod/compile-time-calculation-2.nimrod +++ /dev/null @@ -1,3 +0,0 @@ -... -STRING_LITERAL(TMP122, "3628800", 7); -... diff --git a/Task/Compile-time-calculation/Rust/compile-time-calculation.rust b/Task/Compile-time-calculation/Rust/compile-time-calculation.rust new file mode 100644 index 0000000000..4262d7f2bd --- /dev/null +++ b/Task/Compile-time-calculation/Rust/compile-time-calculation.rust @@ -0,0 +1,11 @@ +fn factorial(n: i64) -> i64 { + let mut total = 1; + for i in 1..n+1 { + total *= i; + } + return total; +} + +fn main() { + println!("Factorial of 10 is {}.", factorial(10)); +} diff --git a/Task/Compile-time-calculation/Zkl/compile-time-calculation.zkl b/Task/Compile-time-calculation/Zkl/compile-time-calculation.zkl new file mode 100644 index 0000000000..7002b6ec2c --- /dev/null +++ b/Task/Compile-time-calculation/Zkl/compile-time-calculation.zkl @@ -0,0 +1,7 @@ +const { [1..10].reduce('*).println(" parse time") } + +#fcn fact(N) { [1..N].reduce('*).println(" tokenize time"); ""} + // paste output of fact into source +#tokenize fact(10) + +println("compiled program running."); diff --git a/Task/Compound-data-type/ALGOL-W/compound-data-type.alg b/Task/Compound-data-type/ALGOL-W/compound-data-type.alg new file mode 100644 index 0000000000..381dc23da1 --- /dev/null +++ b/Task/Compound-data-type/ALGOL-W/compound-data-type.alg @@ -0,0 +1,10 @@ +begin + % create the compound data type % + record Point( real x, y ); + % declare a Point variable % + reference(Point) p; + % assign a value to p % + p := Point( 1, 0.5 ); + % access the fields of p - note Algol W uses x(p) where many languages would use p.x % + write( x(p), y(p) ) +end. diff --git a/Task/Compound-data-type/Elm/compound-data-type.elm b/Task/Compound-data-type/Elm/compound-data-type.elm new file mode 100644 index 0000000000..76a36a0d03 --- /dev/null +++ b/Task/Compound-data-type/Elm/compound-data-type.elm @@ -0,0 +1,27 @@ +--Compound Data type can hold multiple independent values +--In Elm data can be compounded using List, Tuple, Record +--In a List +point = [2,5] +--This creates a list having x and y which are independent and can be accessed by List functions +--Note that x and y must be of same data type + +--Tuple is another useful data type that stores different independent values +point = (3,4) +--Here we can have multiple data types +point1 = ("x","y") +point2 = (3,4.5) +--The order of addressing matters +--Using a Record is the best option +point = {x=3,y=4} +--To access +point.x +point.y +--Or Use it as a function +.x point +.y point +--Also to alter the value +{point | x=7} +{point | y=2} +{point | x=3,y=4} +--Each time a new record is generated +--END diff --git a/Task/Compound-data-type/jq/compound-data-type-1.jq b/Task/Compound-data-type/Jq/compound-data-type-1.jq similarity index 100% rename from Task/Compound-data-type/jq/compound-data-type-1.jq rename to Task/Compound-data-type/Jq/compound-data-type-1.jq diff --git a/Task/Compound-data-type/jq/compound-data-type-2.jq b/Task/Compound-data-type/Jq/compound-data-type-2.jq similarity index 100% rename from Task/Compound-data-type/jq/compound-data-type-2.jq rename to Task/Compound-data-type/Jq/compound-data-type-2.jq diff --git a/Task/Compound-data-type/Kotlin/compound-data-type.kotlin b/Task/Compound-data-type/Kotlin/compound-data-type.kotlin new file mode 100644 index 0000000000..4c7d720819 --- /dev/null +++ b/Task/Compound-data-type/Kotlin/compound-data-type.kotlin @@ -0,0 +1,9 @@ +data class Point(var x: Int, var y: Int) + +fun main(args: Array) { + val p = Point(1, 2) + println(p) + p.x = 3 + p.y = 4 + println(p) +} diff --git a/Task/Compound-data-type/Oberon-2/compound-data-type.oberon-2 b/Task/Compound-data-type/Oberon-2/compound-data-type.oberon-2 new file mode 100644 index 0000000000..33465cd792 --- /dev/null +++ b/Task/Compound-data-type/Oberon-2/compound-data-type.oberon-2 @@ -0,0 +1,20 @@ +MODULE Point; +TYPE + Object* = POINTER TO ObjectDesc; + ObjectDesc* = RECORD + x-,y-: INTEGER; + END; + + PROCEDURE (p: Object) Init(x,y: INTEGER); + BEGIN + p.x := x; p.y := y + END Init; + + PROCEDURE New*(x,y: INTEGER): Object; + VAR + p: Object; + BEGIN + NEW(p);p.Init(x,y);RETURN p; + END New; + +END Point. diff --git a/Task/Compound-data-type/OoRexx/compound-data-type.rexx b/Task/Compound-data-type/OoRexx/compound-data-type.rexx new file mode 100644 index 0000000000..2ca4f62c4a --- /dev/null +++ b/Task/Compound-data-type/OoRexx/compound-data-type.rexx @@ -0,0 +1,11 @@ +p = .point~new(3,4) +say "x =" p~x +say "y =" p~y + +::class point +::method init + expose x y + use strict arg x = 0, y = 0 -- defaults to 0 for any non-specified coordinates + +::attribute x +::attribute y diff --git a/Task/Compound-data-type/Perl-6/compound-data-type-1.pl6 b/Task/Compound-data-type/Perl-6/compound-data-type-1.pl6 index 25c78fa45d..167f951997 100644 --- a/Task/Compound-data-type/Perl-6/compound-data-type-1.pl6 +++ b/Task/Compound-data-type/Perl-6/compound-data-type-1.pl6 @@ -1 +1,3 @@ my @point = 3, 8; + +my Int @point = 3, 8; # or constrain to integer elements diff --git a/Task/Compound-data-type/Perl-6/compound-data-type-2.pl6 b/Task/Compound-data-type/Perl-6/compound-data-type-2.pl6 index 369d4d6da6..2788554e47 100644 --- a/Task/Compound-data-type/Perl-6/compound-data-type-2.pl6 +++ b/Task/Compound-data-type/Perl-6/compound-data-type-2.pl6 @@ -1 +1,3 @@ my %point = x => 3, y => 8; + +my Int %point = x => 3, y => 8; # or constrain the hash to have integer values diff --git a/Task/Compound-data-type/PureBasic/compound-data-type-1.purebasic b/Task/Compound-data-type/PureBasic/compound-data-type-1.purebasic deleted file mode 100644 index 520001c3be..0000000000 --- a/Task/Compound-data-type/PureBasic/compound-data-type-1.purebasic +++ /dev/null @@ -1,4 +0,0 @@ -Structure MyPoint - X.i - Y.i -EndStructure diff --git a/Task/Compound-data-type/PureBasic/compound-data-type-2.purebasic b/Task/Compound-data-type/PureBasic/compound-data-type-2.purebasic deleted file mode 100644 index bd0023ed6b..0000000000 --- a/Task/Compound-data-type/PureBasic/compound-data-type-2.purebasic +++ /dev/null @@ -1,7 +0,0 @@ -Structure MyFileDate - name.s - StructureUnion - Date_as_txt.s - Date_in_Ticks.l - EndStructureUnion -EndStructure diff --git a/Task/Compound-data-type/Stata/compound-data-type.stata b/Task/Compound-data-type/Stata/compound-data-type.stata new file mode 100644 index 0000000000..9cb0197300 --- /dev/null +++ b/Task/Compound-data-type/Stata/compound-data-type.stata @@ -0,0 +1,16 @@ +mata +struct Point { + real scalar x, y +} + +// dumb example +function test() { + struct Point scalar a + a.x = 10 + a.y = 20 + printf("%f\n",a.x+a.y) +} + +test() +30 +end diff --git a/Task/Compound-data-type/Zkl/compound-data-type-1.zkl b/Task/Compound-data-type/Zkl/compound-data-type-1.zkl new file mode 100644 index 0000000000..b2d8a2ce67 --- /dev/null +++ b/Task/Compound-data-type/Zkl/compound-data-type-1.zkl @@ -0,0 +1,7 @@ +class Point{ var x,y; + fcn init(x,y){self.x=x.toFloat(); self.y=y.toFloat(); } + fcn toString{ "P(%f,%f)".fmt(x,y) } + fcn __opADD(P){} //+: add Point, constant or whatever + //... __opEQ == etc +} +Point(1,2).println() //-->P(1.000000,2.000000) diff --git a/Task/Compound-data-type/Zkl/compound-data-type-2.zkl b/Task/Compound-data-type/Zkl/compound-data-type-2.zkl new file mode 100644 index 0000000000..9b416e7c16 --- /dev/null +++ b/Task/Compound-data-type/Zkl/compound-data-type-2.zkl @@ -0,0 +1 @@ +point:=T(1,2); points:=T( T(1,2), L(3,4) ) diff --git a/Task/Concurrent-computing/Astro/concurrent-computing.astro b/Task/Concurrent-computing/Astro/concurrent-computing.astro new file mode 100644 index 0000000000..d050c0423b --- /dev/null +++ b/Task/Concurrent-computing/Astro/concurrent-computing.astro @@ -0,0 +1,12 @@ +fun main(): + let words = ['Enjoy', 'Rosetta', 'Code'] + random.seed(time.now()) + let q = Chan[Str]() + + for w in words: + run (w:) -> + time.sleep(random()) + q << w + + for i in [:words.size]: + print q diff --git a/Task/Concurrent-computing/BaCon/concurrent-computing.bacon b/Task/Concurrent-computing/BaCon/concurrent-computing.bacon new file mode 100644 index 0000000000..30aa515256 --- /dev/null +++ b/Task/Concurrent-computing/BaCon/concurrent-computing.bacon @@ -0,0 +1,18 @@ +' Concurrent computing using the OpenMP extension in GCC. Requires BaCon 3.6 or higher. + +' Specify compiler flag +PRAGMA OPTIONS -fopenmp + +' Sepcify linker flag +PRAGMA LDFLAGS -lgomp + +' Declare array with text +DECLARE str$[] = { "Enjoy", "Rosetta", "Code" } + +' Indicate MP optimization for FOR loop +PRAGMA omp parallel for num_threads(3) + +' The actual FOR loop +FOR i = 0 TO 2 + PRINT str$[i] +NEXT diff --git a/Task/Concurrent-computing/Dodo0/concurrent-computing.dodo0 b/Task/Concurrent-computing/Dodo0/concurrent-computing.dodo0 new file mode 100644 index 0000000000..e22abe0383 --- /dev/null +++ b/Task/Concurrent-computing/Dodo0/concurrent-computing.dodo0 @@ -0,0 +1,14 @@ +fun parprint -> text, return +( + fork() -> return, throw + println(text, return) + | x + return() +) +| parprint + +parprint("Enjoy") -> +parprint("Rosetta") -> +parprint("Code") -> + +exit() diff --git a/Task/Concurrent-computing/Elixir/concurrent-computing.elixir b/Task/Concurrent-computing/Elixir/concurrent-computing.elixir index 8d6a40e75b..b672df93d1 100644 --- a/Task/Concurrent-computing/Elixir/concurrent-computing.elixir +++ b/Task/Concurrent-computing/Elixir/concurrent-computing.elixir @@ -1,9 +1,13 @@ -defmodule ConcurrentComputing do - def print(xs) do - Enum.map(xs, fn x -> - spawn(fn -> IO.puts x end) +defmodule Concurrent do + def computing(xs) do + Enum.each(xs, fn x -> + spawn(fn -> + Process.sleep(:rand.uniform(1000)) + IO.puts x + end) end) + Process.sleep(1000) end end -ConcurrentComputing.print ["Enjoy", "Rosetta", "Code"] +Concurrent.computing ["Enjoy", "Rosetta", "Code"] diff --git a/Task/Concurrent-computing/Kotlin/concurrent-computing.kotlin b/Task/Concurrent-computing/Kotlin/concurrent-computing.kotlin new file mode 100644 index 0000000000..370bcb0e94 --- /dev/null +++ b/Task/Concurrent-computing/Kotlin/concurrent-computing.kotlin @@ -0,0 +1,16 @@ +// version 1.1.2 + +import java.util.concurrent.CyclicBarrier + +class DelayedMessagePrinter(val barrier: CyclicBarrier, val msg: String) : Runnable { + override fun run() { + barrier.await() + println(msg) + } +} + +fun main(args: Array) { + val msgs = listOf("Enjoy", "Rosetta", "Code") + val barrier = CyclicBarrier(msgs.size) + for (msg in msgs) Thread(DelayedMessagePrinter(barrier, msg)).start() +} diff --git a/Task/Concurrent-computing/Nim/concurrent-computing-1.nim b/Task/Concurrent-computing/Nim/concurrent-computing-1.nim index 466cc9b3b8..756eea19f9 100644 --- a/Task/Concurrent-computing/Nim/concurrent-computing-1.nim +++ b/Task/Concurrent-computing/Nim/concurrent-computing-1.nim @@ -1,8 +1,8 @@ const str = ["Enjoy", "Rosetta", "Code"] -var thr: array[3, TThread[int32]] +var thr: array[3, Thread[int32]] -proc f(i) {.thread.} = +proc f(i:int32) {.thread.} = echo str[i] for i in 0..thr.high: diff --git a/Task/Concurrent-computing/OoRexx/concurrent-computing.rexx b/Task/Concurrent-computing/OoRexx/concurrent-computing.rexx new file mode 100644 index 0000000000..c9cfc93dfe --- /dev/null +++ b/Task/Concurrent-computing/OoRexx/concurrent-computing.rexx @@ -0,0 +1,35 @@ +-- this will launch 3 threads, with each thread given a message to print out. +-- I've added a stoplight to make each thread wait until given a go signal, +-- plus some sleeps to give the threads a chance to randomize the execution +-- order a little. +launcher = .launcher~new +launcher~launch + +::class launcher +-- the launcher method. Guarded is the default, but let's make this +-- explicit here +::method launch guarded + + runner1 = .runner~new(self, "Enjoy") + runner2 = .runner~new(self, "Rosetta") + runner3 = .runner~new(self, "Code") + + -- let's give the threads a chance to settle in to the + -- starting line + call syssleep 1 + + guard off -- release the launcher lock. This is the starter's gun + +-- this is a guarded method that the runners will call. They +-- will block until the launch method releases the object guard +::method block guarded + +::class runner +::method init + use arg launcher, text + reply -- this creates the new thread + + call syssleep .5 -- try to mix things up by sleeping + launcher~block -- wait for the go signal + call syssleep .5 -- add another sleep here + say text diff --git a/Task/Concurrent-computing/Zkl/concurrent-computing.zkl b/Task/Concurrent-computing/Zkl/concurrent-computing.zkl new file mode 100644 index 0000000000..5c2d36f05e --- /dev/null +++ b/Task/Concurrent-computing/Zkl/concurrent-computing.zkl @@ -0,0 +1,3 @@ +fcn{println("Enjoy")}.launch(); // thread +fcn{println("Rosetta")}.strand(); // co-op thread +fcn{println("Code")}.future(); // another thread type diff --git a/Task/Conditional-structures/Astro/conditional-structures.astro b/Task/Conditional-structures/Astro/conditional-structures.astro new file mode 100644 index 0000000000..d2548d02a9 --- /dev/null +++ b/Task/Conditional-structures/Astro/conditional-structures.astro @@ -0,0 +1,14 @@ +if x == 0: + foo() +elif x == 1: + bar() +elif x == 2: + baz() +else: + qux() + +x +| 0 -> foo() +| 1 -> bar() +| 2 -> baz() +| _ -> qux() diff --git a/Task/Conditional-structures/Beeswax/conditional-structures-1.beeswax b/Task/Conditional-structures/Beeswax/conditional-structures-1.beeswax new file mode 100644 index 0000000000..0e973d3dd6 --- /dev/null +++ b/Task/Conditional-structures/Beeswax/conditional-structures-1.beeswax @@ -0,0 +1,4 @@ +' lstack top value == 0 ? skip next instruction : don’t skip next instruction. +" lstack top value > 0 ? skip next instruction : don’t skip next instruction. +K lstack top value == 2nd value ? skip next instruction : don’t skip next instruction. +L lstack top value > 2nd value ? skip next instruction : don’t skip next instruction. diff --git a/Task/Conditional-structures/Beeswax/conditional-structures-2.beeswax b/Task/Conditional-structures/Beeswax/conditional-structures-2.beeswax new file mode 100644 index 0000000000..0504f05557 --- /dev/null +++ b/Task/Conditional-structures/Beeswax/conditional-structures-2.beeswax @@ -0,0 +1,3 @@ +_`Enter integer n:`T'p`n = 0`>N`Enter integer m:`T'p`m = 0`>` and `Kp`m = n`; + >`n > 0`d >`m > 0`d >Lp`m > n`; + >`m < n`; diff --git a/Task/Conditional-structures/Beeswax/conditional-structures-3.beeswax b/Task/Conditional-structures/Beeswax/conditional-structures-3.beeswax new file mode 100644 index 0000000000..aa96219fa0 --- /dev/null +++ b/Task/Conditional-structures/Beeswax/conditional-structures-3.beeswax @@ -0,0 +1,6 @@ +Enter integer n: +i3 +n > 0 +Enter integer m: +i0 +m = 0 and m < n diff --git a/Task/Conditional-structures/D/conditional-structures-1.d b/Task/Conditional-structures/D/conditional-structures-1.d deleted file mode 100644 index 6cb58f4212..0000000000 --- a/Task/Conditional-structures/D/conditional-structures-1.d +++ /dev/null @@ -1 +0,0 @@ -const i = 5; static if (i == 7) { ... } else { ... } diff --git a/Task/Conditional-structures/D/conditional-structures-2.d b/Task/Conditional-structures/D/conditional-structures-2.d deleted file mode 100644 index 87486a535d..0000000000 --- a/Task/Conditional-structures/D/conditional-structures-2.d +++ /dev/null @@ -1,9 +0,0 @@ - auto i = 5; -// is(T: U) tests if T is implicitly castable to U. -// typeof(var) is the type of the variable. -// also: is(T==U) checks if T is U. -static if (is(typeof(i) : int)) { - ... -} else { - ... -} diff --git a/Task/Conditional-structures/DM/conditional-structures-1.dm b/Task/Conditional-structures/DM/conditional-structures-1.dm new file mode 100644 index 0000000000..1fec8f177f --- /dev/null +++ b/Task/Conditional-structures/DM/conditional-structures-1.dm @@ -0,0 +1,11 @@ +if (condition) + // Do thing, DM uses indentation for control flow. + +if (condition) + // Do thing + +else if (condition) + // Do thing + +else + // Do thing diff --git a/Task/Conditional-structures/DM/conditional-structures-2.dm b/Task/Conditional-structures/DM/conditional-structures-2.dm new file mode 100644 index 0000000000..84b7e6da46 --- /dev/null +++ b/Task/Conditional-structures/DM/conditional-structures-2.dm @@ -0,0 +1,2 @@ +// x will be 1 if condition is a true value, 2 otherwise. +var/x = condition ? 1 : 2 diff --git a/Task/Conditional-structures/DM/conditional-structures-3.dm b/Task/Conditional-structures/DM/conditional-structures-3.dm new file mode 100644 index 0000000000..97ba4a0b1d --- /dev/null +++ b/Task/Conditional-structures/DM/conditional-structures-3.dm @@ -0,0 +1,14 @@ +switch (value) + if (0) + // Do thing if zero + // DM does not have fall through of switch cases, so explicit break is not required. + if (1, 2, 3) + // Multiple values can be allowed by using commas + + if (10 to 20) + // Ranges are also allowed. + // Ranges include the bounds (10 and 20 here), + // and are checked in order if there is potential for overlap. + + else + // Fallback if nothing was matched. diff --git a/Task/Conditional-structures/Friendly-interactive-shell/conditional-structures-1.fish b/Task/Conditional-structures/Friendly-interactive-shell/conditional-structures-1.fish new file mode 100644 index 0000000000..ccf394d86d --- /dev/null +++ b/Task/Conditional-structures/Friendly-interactive-shell/conditional-structures-1.fish @@ -0,0 +1,8 @@ +set var 'Hello World' +if test $var = 'Hello World' + echo 'Welcome.' +else if test $var = 'Bye World' + echo 'Bye.' +else + echo 'Huh?' +end diff --git a/Task/Conditional-structures/Friendly-interactive-shell/conditional-structures-2.fish b/Task/Conditional-structures/Friendly-interactive-shell/conditional-structures-2.fish new file mode 100644 index 0000000000..cfc018d7bb --- /dev/null +++ b/Task/Conditional-structures/Friendly-interactive-shell/conditional-structures-2.fish @@ -0,0 +1,12 @@ +switch actually + case az + echo The word is "az". + case 'a*z' + echo Begins with a and ends with z. + case 'a*' + echo Begins with a. + case 'z*' + echo Ends with z. + case '*' + echo Neither begins with a or ends with z. +end diff --git a/Task/Conditional-structures/jq/conditional-structures-1.jq b/Task/Conditional-structures/Jq/conditional-structures-1.jq similarity index 100% rename from Task/Conditional-structures/jq/conditional-structures-1.jq rename to Task/Conditional-structures/Jq/conditional-structures-1.jq diff --git a/Task/Conditional-structures/jq/conditional-structures-2.jq b/Task/Conditional-structures/Jq/conditional-structures-2.jq similarity index 100% rename from Task/Conditional-structures/jq/conditional-structures-2.jq rename to Task/Conditional-structures/Jq/conditional-structures-2.jq diff --git a/Task/Conditional-structures/jq/conditional-structures-3.jq b/Task/Conditional-structures/Jq/conditional-structures-3.jq similarity index 100% rename from Task/Conditional-structures/jq/conditional-structures-3.jq rename to Task/Conditional-structures/Jq/conditional-structures-3.jq diff --git a/Task/Conditional-structures/jq/conditional-structures-4.jq b/Task/Conditional-structures/Jq/conditional-structures-4.jq similarity index 100% rename from Task/Conditional-structures/jq/conditional-structures-4.jq rename to Task/Conditional-structures/Jq/conditional-structures-4.jq diff --git a/Task/Conditional-structures/Kotlin/conditional-structures.kotlin b/Task/Conditional-structures/Kotlin/conditional-structures.kotlin new file mode 100644 index 0000000000..69b1177853 --- /dev/null +++ b/Task/Conditional-structures/Kotlin/conditional-structures.kotlin @@ -0,0 +1,28 @@ +// version 1.0.6 + +fun main(args: Array) { + // conventional 'if/else if/else' statement + if (args.isEmpty()) println("No arguments were supplied") + else if (args.size == 1) println("One argument was supplied") + else println("${args.size} arguments were supplied") + + print("Enter an integer : ") + val i = readLine()!!.toInt() + + // 'when' statement (similar to 'switch' in C family languages) + when (i) { + 0, 1 -> println("0 or 1") + in 2 .. 9 -> println("Between 2 and 9") + else -> println("Out of range") + } + + // both of these can be used as expressions as well as statements + val s = if (i < 0) "negative" else "non-negative" + println("$i is $s") + val t = when { + i > 0 -> "positive" + i == 0 -> "zero" + else -> "negative" + } + println("$i is $t") +} diff --git a/Task/Conditional-structures/NewLISP/conditional-structures-1.newlisp b/Task/Conditional-structures/NewLISP/conditional-structures-1.newlisp new file mode 100644 index 0000000000..2ded98377f --- /dev/null +++ b/Task/Conditional-structures/NewLISP/conditional-structures-1.newlisp @@ -0,0 +1,2 @@ +(set 'x 1) +(if (= x 1) (println "is 1")) diff --git a/Task/Conditional-structures/NewLISP/conditional-structures-2.newlisp b/Task/Conditional-structures/NewLISP/conditional-structures-2.newlisp new file mode 100644 index 0000000000..79a712286d --- /dev/null +++ b/Task/Conditional-structures/NewLISP/conditional-structures-2.newlisp @@ -0,0 +1,2 @@ +(set 'x 0) +(if (= x 1) (println "is 1") (println "not 1")) diff --git a/Task/Conditional-structures/OoRexx/conditional-structures-1.rexx b/Task/Conditional-structures/OoRexx/conditional-structures-1.rexx new file mode 100644 index 0000000000..f7ab6700b7 --- /dev/null +++ b/Task/Conditional-structures/OoRexx/conditional-structures-1.rexx @@ -0,0 +1 @@ +if arg~isa(.string) & arg~left(1) == "*" then call processArg arg diff --git a/Task/Conditional-structures/OoRexx/conditional-structures-2.rexx b/Task/Conditional-structures/OoRexx/conditional-structures-2.rexx new file mode 100644 index 0000000000..c9a6528898 --- /dev/null +++ b/Task/Conditional-structures/OoRexx/conditional-structures-2.rexx @@ -0,0 +1 @@ +if arg~isa(.string), arg~left(1) == "*" then call processArg arg diff --git a/Task/Conditional-structures/OoRexx/conditional-structures-3.rexx b/Task/Conditional-structures/OoRexx/conditional-structures-3.rexx new file mode 100644 index 0000000000..2eaacd92f7 --- /dev/null +++ b/Task/Conditional-structures/OoRexx/conditional-structures-3.rexx @@ -0,0 +1,25 @@ +if y then x=6 /* Y must be either 0 or 1 */ + + +if t**2>u then x=y + else x=-y + + + +if t**2>u then do j=1 to 10; say prime(j); end + else x=-y + + + +if z>w+4 then do + z=abs(z) + say 'z='z + end + else do; z=0; say 'failed.'; end + + + +if x>y & c*d0 then do + y=sqrt(z) + z=u**2 + end + + /*if control reaches this point and none of the WHENs */ + /*were satisfiied, a SYNTAX condition is raised (error).*/ + end diff --git a/Task/Conditional-structures/OoRexx/conditional-structures-5.rexx b/Task/Conditional-structures/OoRexx/conditional-structures-5.rexx new file mode 100644 index 0000000000..614dde3f8a --- /dev/null +++ b/Task/Conditional-structures/OoRexx/conditional-structures-5.rexx @@ -0,0 +1,14 @@ + select + when a=='angel' then many='host' + when a=='ass' | a=='donkey' then many='pace' + when a=='crocodile' then many='bask' + when a=='crow' then many='murder' + when a=='lark' then many='ascension' + when a=='quail' then many='bevy' + when a=='wolf' then many='pack' + otherwise say + say '*** error! ***' + say a "isn't one of the known thingys." + say + exit 13 + end diff --git a/Task/Conditional-structures/Phix/conditional-structures-1.phix b/Task/Conditional-structures/Phix/conditional-structures-1.phix new file mode 100644 index 0000000000..4e478117b7 --- /dev/null +++ b/Task/Conditional-structures/Phix/conditional-structures-1.phix @@ -0,0 +1,9 @@ +if name="Pete" then + -- do something +elsif age>50 then + -- do something +elsif age<20 then + -- do something +else + -- do something +end if diff --git a/Task/Conditional-structures/Phix/conditional-structures-2.phix b/Task/Conditional-structures/Phix/conditional-structures-2.phix new file mode 100644 index 0000000000..4f6047a885 --- /dev/null +++ b/Task/Conditional-structures/Phix/conditional-structures-2.phix @@ -0,0 +1 @@ +var = iff(flag?true_expr:false_expr) diff --git a/Task/Conditional-structures/Phix/conditional-structures-3.phix b/Task/Conditional-structures/Phix/conditional-structures-3.phix new file mode 100644 index 0000000000..6443e06599 --- /dev/null +++ b/Task/Conditional-structures/Phix/conditional-structures-3.phix @@ -0,0 +1,12 @@ +switch v [with fallthrough] do + case 1,2: + -- do something + case 3 then + -- do something + fallthrough + case 4: + -- do something + break + default: + -- do something +end switch diff --git a/Task/Conditional-structures/Phix/conditional-structures-4.phix b/Task/Conditional-structures/Phix/conditional-structures-4.phix new file mode 100644 index 0000000000..7cd88736e4 --- /dev/null +++ b/Task/Conditional-structures/Phix/conditional-structures-4.phix @@ -0,0 +1,22 @@ +#ilASM{ + [32] + mov eax,[var] + [64] + mov rax,[var] + [PE32] + push eax -- uExitCode + call "kernel32.dll","ExitProcess" + [PE64] + mov rcx,rax -- uExitCode + call "kernel32.dll","ExitProcess" + [ELF32] + mov ebx,eax -- error_code (p1) + mov eax,1 -- sys_exit(ebx=int error_code) + int 0x80 +-- xor ebx,ebx -- (common requirement after int 0x80) + [ELF64] + mov rdi,rax -- error_code (p1) + mov rax,60 -- sys_exit(rdi=int error_code) + syscall + [] + } diff --git a/Task/Conditional-structures/R/conditional-structures-1.r b/Task/Conditional-structures/R/conditional-structures-1.r deleted file mode 100644 index bef67ea1af..0000000000 --- a/Task/Conditional-structures/R/conditional-structures-1.r +++ /dev/null @@ -1,13 +0,0 @@ -#Single line example - #x is assumed to be scalar - if(x < 3) message("x is less than 3") else if(x < 5) message("x is greater than or equal to 3 but less than 5") else message("x is greater than or equal to 5") -#Block example - if(x < 3) - { - x <- 3 - warning("x has been increased to 3") - } else - { - y <- x^2 - } -#It is important that the else keyword appears on the same line as the closing '}' of the if block. diff --git a/Task/Conditional-structures/R/conditional-structures-2.r b/Task/Conditional-structures/R/conditional-structures-2.r deleted file mode 100644 index 4ad35586b6..0000000000 --- a/Task/Conditional-structures/R/conditional-structures-2.r +++ /dev/null @@ -1,3 +0,0 @@ -#ifelse is a vectorised version of the if/else flow controllers, similar to the C-style ternary operator. - x <- sample(1:10, 10) - ifelse(x > 5, x^2, 0) diff --git a/Task/Conditional-structures/R/conditional-structures-3.r b/Task/Conditional-structures/R/conditional-structures-3.r deleted file mode 100644 index 348713d55d..0000000000 --- a/Task/Conditional-structures/R/conditional-structures-3.r +++ /dev/null @@ -1,12 +0,0 @@ -# Character input - calories <- function(food) switch(food, apple=47, pizza=1500, stop("food not known")) - calories("apple") # 47 - calories("banana") # throws an error -# Numeric input - alphabet <- function(number) switch(number, "a", "ab", "abc") - alphabet(0) # null response - alphabet(1) # "a" - alphabet(2) # "ab" - alphabet(3) # "abc" - alphabet(4) # null response -# Note that no 'otherwise' option is allowed when the input is numeric. diff --git a/Task/Conditional-structures/Rust/conditional-structures-1.rust b/Task/Conditional-structures/Rust/conditional-structures-1.rust new file mode 100644 index 0000000000..2b1a7cc3a2 --- /dev/null +++ b/Task/Conditional-structures/Rust/conditional-structures-1.rust @@ -0,0 +1,21 @@ +// This function will only be compiled if we are compiling on Linux +#[cfg(target_os = "linux")] +fn running_linux() { + println!("This is linux"); +} +#[cfg(not(target_os = "linux"))] +fn running_linux() { + println!("This is not linux"); +} + +// If we are on linux, we must be using glibc +#[cfg_attr(target_os = "linux", target_env = "gnu")] +// We must either be compiling for ARM or on a little endian machine that doesn't have 32-bit pointers pointers, on a +// UNIX like OS and only if we are doing a test build +#[cfg(all( + any(target_arch = "arm", target_endian = "little"), + not(target_pointer_width = "32"), + unix, + test + ))] +fn highly_specific_function() {} diff --git a/Task/Conditional-structures/Rust/conditional-structures-2.rust b/Task/Conditional-structures/Rust/conditional-structures-2.rust new file mode 100644 index 0000000000..c1f9ee3628 --- /dev/null +++ b/Task/Conditional-structures/Rust/conditional-structures-2.rust @@ -0,0 +1,5 @@ +fn main() { + if cfg!(target_os = "linux") { + // Do something + } +} diff --git a/Task/Conditional-structures/Rust/conditional-structures-3.rust b/Task/Conditional-structures/Rust/conditional-structures-3.rust new file mode 100644 index 0000000000..3abd45f6cf --- /dev/null +++ b/Task/Conditional-structures/Rust/conditional-structures-3.rust @@ -0,0 +1,28 @@ +trait PrintType { + fn print_type(); +} + +impl PrintType for char { + fn print_type() { + println!("char"); + } +} + +impl PrintType for f64 { + fn print_type() { + println!("64-bit float"); + } +} + +fn prints_type_of_args(arg1: T, arg2: U) + where T: PrintType + U: PrintType +{ + arg1.print_type(); + arg2.print_type(); +} + +fn main() { + prints_type_of_args('a', 2.0); + prints_type_of_args('a', 'b'); +} diff --git a/Task/Conditional-structures/Rust/conditional-structures-4.rust b/Task/Conditional-structures/Rust/conditional-structures-4.rust new file mode 100644 index 0000000000..62e81ffc75 --- /dev/null +++ b/Task/Conditional-structures/Rust/conditional-structures-4.rust @@ -0,0 +1,21 @@ +if some_conditional { + do_stuff(); +} else if some_other_conditional + do_other_stuff(); +} else { + destroy_humanity(); +} + +// If statements are also expressions and will yield the value of the last expression in each block +let x = if y > z { y + 1 } else { z * 4 }; + +// Pattern matching may also be used +struct Point { + x: i32, + y: i32, +} +fn some_function(p: Option) { + if let Some(Point { x: x_coord, y: y_coord }) = p { + // Do something with x_coord and y_coord + } +} diff --git a/Task/Conditional-structures/Rust/conditional-structures-5.rust b/Task/Conditional-structures/Rust/conditional-structures-5.rust new file mode 100644 index 0000000000..94af31436c --- /dev/null +++ b/Task/Conditional-structures/Rust/conditional-structures-5.rust @@ -0,0 +1,10 @@ +fn some_other_function(p: Option) { + match p { + Some(Point { x: 0, y: 0 }) => println!("Point is on origin"), + Some(Point { x: 0, y: _ }) | Some(Point { x: _, y: 0 }) => println!("Point is on an axis"), + Some(Point {x: a, y: b}) if a == b println!("x and y are the same value"), + Some(Point {x: ref mut a, y: ref b}) if x > 4 && y < 2 => println!("we got a mutable reference to x-value and an immutable reference to y-value."), + op @ Some(p) => println!("op is the Option while p is the contained Point"), + None => println!("We didn't get a point"), + } +} diff --git a/Task/Conditional-structures/Rust/conditional-structures-6.rust b/Task/Conditional-structures/Rust/conditional-structures-6.rust new file mode 100644 index 0000000000..c83e358798 --- /dev/null +++ b/Task/Conditional-structures/Rust/conditional-structures-6.rust @@ -0,0 +1,8 @@ +fn prints_args_dynamic(arg1: &PrintType, arg2: &PrintType) { + arg1.print_type(); + arg2.print_type(); +} +fn main() { + prints_args_dynamic(&'a', &2.0); + prints_args_dynamic(&6.3,&'c'); +} diff --git a/Task/Conditional-structures/Scheme/conditional-structures-10.ss b/Task/Conditional-structures/Scheme/conditional-structures-10.ss deleted file mode 100644 index dff3aefd79..0000000000 --- a/Task/Conditional-structures/Scheme/conditional-structures-10.ss +++ /dev/null @@ -1,2 +0,0 @@ -composite -consonant diff --git a/Task/Conditional-structures/Scheme/conditional-structures-8.ss b/Task/Conditional-structures/Scheme/conditional-structures-8.ss deleted file mode 100644 index ae39fe7209..0000000000 --- a/Task/Conditional-structures/Scheme/conditional-structures-8.ss +++ /dev/null @@ -1 +0,0 @@ -(case ...) diff --git a/Task/Conditional-structures/Scheme/conditional-structures-9.ss b/Task/Conditional-structures/Scheme/conditional-structures-9.ss deleted file mode 100644 index affbd16181..0000000000 --- a/Task/Conditional-structures/Scheme/conditional-structures-9.ss +++ /dev/null @@ -1,11 +0,0 @@ -(display - (case (* 2 3) - ((2 3 5 7) "prime") - ((1 4 6 8 9) "composite"))) -(newline) -(display - (case (car (list c d)) - ((a e i o u) "vowel") - ((w y) "semivowel") - (else "consonant"))) -(newline) diff --git a/Task/Conditional-structures/XLISP/conditional-structures-1.xlisp b/Task/Conditional-structures/XLISP/conditional-structures-1.xlisp new file mode 100644 index 0000000000..bc5c80d2dd --- /dev/null +++ b/Task/Conditional-structures/XLISP/conditional-structures-1.xlisp @@ -0,0 +1,3 @@ +(if (eq s "Rosetta Code") + "The well-known programming chrestomathy site" + "Some other website, maybe, I dunno" ) diff --git a/Task/Conditional-structures/XLISP/conditional-structures-2.xlisp b/Task/Conditional-structures/XLISP/conditional-structures-2.xlisp new file mode 100644 index 0000000000..a3d1f05a8f --- /dev/null +++ b/Task/Conditional-structures/XLISP/conditional-structures-2.xlisp @@ -0,0 +1,5 @@ +(case s + ("Rosetta Code" "Ah yes, the chrestomathy site") + ("Stack Overflow" "Oh dear me, having problems are you?") + ("Github" "Say no more") + (else "Sorry, never heard of it") ) diff --git a/Task/Conditional-structures/XLISP/conditional-structures-3.xlisp b/Task/Conditional-structures/XLISP/conditional-structures-3.xlisp new file mode 100644 index 0000000000..7c389c9d60 --- /dev/null +++ b/Task/Conditional-structures/XLISP/conditional-structures-3.xlisp @@ -0,0 +1,4 @@ +(cond + ((eq s "Rosetta Code") "Chrestomathy site") + ((> n 37) "Some other appropriate value, presumably") + (t "If you're seeing me, s wasn't equal to Rosetta Code and n must have been 37 or below") ) diff --git a/Task/Conditional-structures/Zkl/conditional-structures.zkl b/Task/Conditional-structures/Zkl/conditional-structures.zkl new file mode 100644 index 0000000000..8137e71b6c --- /dev/null +++ b/Task/Conditional-structures/Zkl/conditional-structures.zkl @@ -0,0 +1,13 @@ +if (x) y else z; +if(a)b else if (c) else d; etc +x:=(if (a) b else c); + +a and b or c // usually the same as if(a) b else c, beware if b evals to False + +switch(x){ + case(1){...} + case("2"){...} // matches anything + case(a)[fallthrough]{...} // no break, no break has to be explicit + case(b){...} + else {...} // case a C's default, has to be at the end +} diff --git a/Task/Conjugate-transpose/jq/conjugate-transpose-1.jq b/Task/Conjugate-transpose/Jq/conjugate-transpose-1.jq similarity index 100% rename from Task/Conjugate-transpose/jq/conjugate-transpose-1.jq rename to Task/Conjugate-transpose/Jq/conjugate-transpose-1.jq diff --git a/Task/Conjugate-transpose/jq/conjugate-transpose-2.jq b/Task/Conjugate-transpose/Jq/conjugate-transpose-2.jq similarity index 100% rename from Task/Conjugate-transpose/jq/conjugate-transpose-2.jq rename to Task/Conjugate-transpose/Jq/conjugate-transpose-2.jq diff --git a/Task/Conjugate-transpose/jq/conjugate-transpose-3.jq b/Task/Conjugate-transpose/Jq/conjugate-transpose-3.jq similarity index 100% rename from Task/Conjugate-transpose/jq/conjugate-transpose-3.jq rename to Task/Conjugate-transpose/Jq/conjugate-transpose-3.jq diff --git a/Task/Conjugate-transpose/jq/conjugate-transpose-4.jq b/Task/Conjugate-transpose/Jq/conjugate-transpose-4.jq similarity index 100% rename from Task/Conjugate-transpose/jq/conjugate-transpose-4.jq rename to Task/Conjugate-transpose/Jq/conjugate-transpose-4.jq diff --git a/Task/Conjugate-transpose/jq/conjugate-transpose-5.jq b/Task/Conjugate-transpose/Jq/conjugate-transpose-5.jq similarity index 100% rename from Task/Conjugate-transpose/jq/conjugate-transpose-5.jq rename to Task/Conjugate-transpose/Jq/conjugate-transpose-5.jq diff --git a/Task/Conjugate-transpose/jq/conjugate-transpose-6.jq b/Task/Conjugate-transpose/Jq/conjugate-transpose-6.jq similarity index 100% rename from Task/Conjugate-transpose/jq/conjugate-transpose-6.jq rename to Task/Conjugate-transpose/Jq/conjugate-transpose-6.jq diff --git a/Task/Conjugate-transpose/jq/conjugate-transpose-7.jq b/Task/Conjugate-transpose/Jq/conjugate-transpose-7.jq similarity index 100% rename from Task/Conjugate-transpose/jq/conjugate-transpose-7.jq rename to Task/Conjugate-transpose/Jq/conjugate-transpose-7.jq diff --git a/Task/Conjugate-transpose/Kotlin/conjugate-transpose.kotlin b/Task/Conjugate-transpose/Kotlin/conjugate-transpose.kotlin new file mode 100644 index 0000000000..ba095c5742 --- /dev/null +++ b/Task/Conjugate-transpose/Kotlin/conjugate-transpose.kotlin @@ -0,0 +1,125 @@ +// version 1.1.3 + +typealias C = Complex +typealias Vector = Array +typealias Matrix = Array + +class Complex(val real: Double, val imag: Double) { + + operator fun plus(other: Complex) = + Complex(this.real + other.real, this.imag + other.imag) + + operator fun times(other: Complex) = + Complex(this.real * other.real - this.imag * other.imag, + this.real * other.imag + this.imag * other.real) + + fun conj() = Complex(this.real, -this.imag) + + /* tolerable equality allowing for rounding of Doubles */ + infix fun teq(other: Complex) = + Math.abs(this.real - other.real) <= 1e-14 && + Math.abs(this.imag - other.imag) <= 1e-14 + + override fun toString() = "${"%.3f".format(real)} " + when { + imag > 0.0 -> "+ ${"%.3f".format(imag)}i" + imag == 0.0 -> "+ 0.000i" + else -> "- ${"%.3f".format(-imag)}i" + } +} + +fun Matrix.conjTranspose(): Matrix { + val rows = this.size + val cols = this[0].size + return Matrix(cols) { i -> Vector(rows) { j -> this[j][i].conj() } } +} + +operator fun Matrix.times(other: Matrix): Matrix { + val rows1 = this.size + val cols1 = this[0].size + val rows2 = other.size + val cols2 = other[0].size + require(cols1 == rows2) + val result = Matrix(rows1) { Vector(cols2) { C(0.0, 0.0) } } + for (i in 0 until rows1) { + for (j in 0 until cols2) { + for (k in 0 until rows2) { + result[i][j] += this[i][k] * other[k][j] + } + } + } + return result +} + +/* tolerable matrix equality using the same concept as for complex numbers */ +infix fun Matrix.teq(other: Matrix): Boolean { + if (this.size != other.size || this[0].size != other[0].size) return false + for (i in 0 until this.size) { + for (j in 0 until this[0].size) if (!(this[i][j] teq other[i][j])) return false + } + return true +} + +fun Matrix.isHermitian() = this teq this.conjTranspose() + +fun Matrix.isNormal(): Boolean { + val ct = this.conjTranspose() + return (this * ct) teq (ct * this) +} + +fun Matrix.isUnitary(): Boolean { + val ct = this.conjTranspose() + val prod = this * ct + val ident = identityMatrix(prod.size) + val prod2 = ct * this + return (prod teq ident) && (prod2 teq ident) +} + +fun Matrix.print() { + val rows = this.size + val cols = this[0].size + for (i in 0 until rows) { + for (j in 0 until cols) { + print(this[i][j]) + print(if(j < cols - 1) ", " else "\n") + } + } + println() +} + +fun identityMatrix(n: Int): Matrix { + require(n >= 1) + val ident = Matrix(n) { Vector(n) { C(0.0, 0.0) } } + for (i in 0 until n) ident[i][i] = C(1.0, 0.0) + return ident +} + +fun main(args: Array) { + val x = Math.sqrt(2.0) / 2.0 + val matrices = arrayOf( + arrayOf( + arrayOf(C(3.0, 0.0), C(2.0, 1.0)), + arrayOf(C(2.0, -1.0), C(1.0, 0.0)) + ), + arrayOf( + arrayOf(C(1.0, 0.0), C(1.0, 0.0), C(0.0, 0.0)), + arrayOf(C(0.0, 0.0), C(1.0, 0.0), C(1.0, 0.0)), + arrayOf(C(1.0, 0.0), C(0.0, 0.0), C(1.0, 0.0)) + ), + arrayOf( + arrayOf(C(x, 0.0), C(x, 0.0), C(0.0, 0.0)), + arrayOf(C(0.0, -x), C(0.0, x), C(0.0, 0.0)), + arrayOf(C(0.0, 0.0), C(0.0, 0.0), C(0.0, 1.0)) + ) + ) + + for (m in matrices) { + println("Matrix:") + m.print() + val mct = m.conjTranspose() + println("Conjugate transpose:") + mct.print() + println("Hermitian? ${mct.isHermitian()}") + println("Normal? ${mct.isNormal()}") + println("Unitary? ${mct.isUnitary()}\n") + } +} diff --git a/Task/Conjugate-transpose/Phix/conjugate-transpose.phix b/Task/Conjugate-transpose/Phix/conjugate-transpose.phix new file mode 100644 index 0000000000..fd0db324fa --- /dev/null +++ b/Task/Conjugate-transpose/Phix/conjugate-transpose.phix @@ -0,0 +1,120 @@ +enum REAL, IMAG + +type complex(sequence s) + return length(s)=2 and atom(s[REAL]) and atom(s[IMAG]) +end type + +function c_add(complex a, complex b) + return sq_add(a,b) +end function + +function c_mul(complex a, complex b) + return {a[REAL] * b[REAL] - a[IMAG] * b[IMAG], + a[REAL] * b[IMAG] + a[IMAG] * b[REAL]} +end function + +function c_conj(complex a) + return {a[REAL],-a[IMAG]} +end function + +function c_print(complex a) + if a[IMAG]=0 then return sprintf("%g",a[REAL]) end if + return sprintf("%g%+gi",a) +end function + +procedure m_print(sequence a) + integer l = length(a) + for i=1 to l do + for j=1 to l do + a[i][j] = c_print(a[i][j]) + end for + a[i] = "["&join(a[i],",")&"]" + end for + puts(1,join(a,"\n")&"\n") +end procedure + + +function conjugate_transpose(sequence a) + sequence res = a + integer l = length(a) + for i=1 to l do + for j=1 to l do + res[i][j] = c_conj(a[j][i]) + end for + end for + return res +end function + +function m_unitary(sequence act) +-- note: a was normal and act = a*ct already + integer l = length(act) + for i=1 to l do + for j=1 to l do + atom {re,im} = act[i,j] + -- round to nearest billionth + -- (powers of 2 help the FPU out) + re = round(re,1024*1024*1024) + im = round(im,1024*1024*1024) + if im!=0 + or (i=j and re!=1) + or (i!=j and re!=0) then + return 0 + end if + end for + end for + return 1 +end function + +function m_mul(sequence a, sequence b) + sequence res = sq_mul(a,0) + integer l = length(a) + for i=1 to l do + for j=1 to l do + for k=1 to l do + res[i][j] = c_add(res[i][j],c_mul(a[i][k],b[k][j])) + end for + end for + end for + return res +end function + +procedure test(sequence a) +sequence ct = conjugate_transpose(a) + printf(1,"Original matrix:\n") + m_print(a) + printf(1,"Conjugate transpose:\n") + m_print(ct) + -- note: rounding similar to that in m_unitary may be rqd (in a similar + -- loop in a new m_equal function) on these two equality tests, + -- but as it is, all tests pass with the builtin = operator. + printf(1,"Hermitian?: %s\n",{iff(a=ct?"TRUE":"FALSE")}) -- (this one) + sequence act = m_mul(a,ct), cta = m_mul(ct,a) + bool normal = act=cta -- (&this one) + printf(1,"Normal?: %s\n",{iff(normal?"TRUE":"FALSE")}) + printf(1,"Unitary?: %s\n\n",{iff(normal and m_unitary(act)?"TRUE":"FALSE")}) +end procedure + +constant x = sqrt(2)/2 + +constant tests = {{{{3, 0},{2,1}}, + {{2,-1},{1,0}}}, + + {{{ 1, 0},{ 1, 1},{ 0, 2}}, + {{ 1,-1},{ 5, 0},{-3, 0}}, + {{ 0,-2},{-3, 0},{ 0, 0}}}, + + {{{0.5,+0.5},{0.5,-0.5}}, + {{0.5,-0.5},{0.5,+0.5}}}, + + {{{ 1, 0},{ 1, 0},{ 0, 0}}, + {{ 0, 0},{ 1, 0},{ 1, 0}}, + {{ 1, 0},{ 0, 0},{ 1, 0}}}, + + {{{x, 0},{x, 0},{0, 0}}, + {{0,-x},{0, x},{0, 0}}, + {{0, 0},{0, 0},{0, 1}}}, + + {{{2,7},{9,-5}}, + {{3,4},{8,-6}}}} + +for i=1 to length(tests) do test(tests[i]) end for diff --git a/Task/Conjugate-transpose/Sidef/conjugate-transpose.sidef b/Task/Conjugate-transpose/Sidef/conjugate-transpose.sidef new file mode 100644 index 0000000000..0a942fd2f7 --- /dev/null +++ b/Task/Conjugate-transpose/Sidef/conjugate-transpose.sidef @@ -0,0 +1,66 @@ +func is_Hermitian (Array m, Array t) -> Bool { m == t } + +func mat_mult (Array a, Array b, Number ε = -3) { + var p = [] + for r, c in (^a ~X ^b[0]) { + for k in (^b) { + p[r][c] := 0 += (a[r][k] * b[k][c]) -> round!(ε) + } + } + return p +} + +func mat_trans (Array m) { + var r = [] + for i,j in (^m ~X ^m[0]) { + r[j][i] = m[i][j] + } + return r +} + +func mat_ident (Number n) { + ^n -> map {|i| + [i.of(0)..., 1, (n - i - 1).of(0)...] + } +} + +func is_Normal (Array m, Array t) -> Bool { + mat_mult(m, t) == mat_mult(t, m) +} + +func is_Unitary (Array m, Array t) -> Bool { + mat_mult(m, t) == mat_ident(m.len) +} + +func say_it (Array a) { + a.each {|b| + b.map { "%9s" % _ }.join(' ').say + } +} + +[ + [ + [ 1, 1+1i, 2i], + [1-1i, 5, -3], + [0-2i, -3, 0] + ], + [ + [1, 1, 0], + [0, 1, 1], + [1, 0, 1] + ], + [ + [0.707 , 0.707, 0], + [0.707i, -0.707i, 0], + [0 , 0, 1i] + ] +].each { |m| + say "\nMatrix:" + say_it(m) + var t = mat_trans(m.map{.map{.conj}}) + say "\nTranspose:" + say_it(t) + say "Is Hermitian?\t#{is_Hermitian(m, t)}" + say "Is Normal?\t#{is_Normal(m, t)}" + say "Is Unitary?\t#{is_Unitary(m, t)}" +} diff --git a/Task/Constrained-genericity/Forth/constrained-genericity.fth b/Task/Constrained-genericity/Forth/constrained-genericity.fth index c33cc4ee7f..9a1d8cf26a 100644 --- a/Task/Constrained-genericity/Forth/constrained-genericity.fth +++ b/Task/Constrained-genericity/Forth/constrained-genericity.fth @@ -1,61 +1,39 @@ include FMS-SI.f include FMS-SILib.f - -: (where) ( class-xt where-dfa -- flag ) - swap >body { where-dfa class-dfa } - begin - class-dfa ['] object >body <> - while - class-dfa where-dfa = if true exit then - class-dfa sfa @ to class-dfa - repeat false ; - -: where ( class-xt "classname" -- flag ) - ' >body state @ - if postpone literal postpone (where) - else (where) - then ; immediate - :class Eatable - :m eat cr ." successful eat" ;m + :m eat ." successful eat " ;m ;class -\ FoodBox is defined without using eat in any way. +\ FoodBox is defined without inspecting for the eat message :class FoodBox object-list eatable-types - :m fill: { n class-xt -- } - class-xt where Eatable - if n 0 do class-xt eatable-types xtadd: loop - else ." not an eatable type " + :m init: eatable-types init: ;m + :m add: ( obj -- ) + dup is-kindOf Eatable + if eatable-types add: + else drop ." not an eatable type " then ;m - :m get ( -- obj ) eatable-types ;m + :m test + begin eatable-types each: + while eat + repeat ;m ;class -: test ( obj -- ) \ send the eat message to each object in the object-list - begin dup each: - while eat - repeat drop ; +FoodBox aFoodBox +Eatable aEatable +aEatable aFoodBox add: \ add the e1 object to the object-list +aFoodBox test \ => successful eat -FoodBox fb -3 ' Eatable fb fill: \ fill the object-list with 3 objects of class Eatable -fb get test -successful eat -successful eat -successful eat +:class brick + :m eat cr ." successful eat " ;m +;class -FoodBox fb1 -5 ' object fb1 fill: \ => not an eatable type +brick abrick \ create an object that is not eatable +abrick aFoodBox add: \ => not an eatable type :class apple successful eat successful eat diff --git a/Task/Constrained-genericity/Kotlin/constrained-genericity.kotlin b/Task/Constrained-genericity/Kotlin/constrained-genericity.kotlin new file mode 100644 index 0000000000..97adf71fc0 --- /dev/null +++ b/Task/Constrained-genericity/Kotlin/constrained-genericity.kotlin @@ -0,0 +1,51 @@ +// version 1.0.6 + +interface Eatable { + fun eat() +} + +class Cheese(val name: String) : Eatable { + override fun eat() { + println("Eating $name") + } + + override fun toString() = name +} + +class Meat(val name: String) : Eatable { + override fun eat() { + println("Eating $name") + } + + override fun toString() = name +} + +class FoodBox { + private val foodList = mutableListOf() + + fun add(food: T) { + foodList.add(food) + } + + override fun toString() = foodList.toString() +} + +fun main(args: Array) { + val cheddar = Cheese("cheddar") + val feta = Cheese("feta") + val cheeseBox = FoodBox() + cheeseBox.add(cheddar) + cheeseBox.add(feta) + println("CheeseBox contains : $cheeseBox") + + val beef = Meat("beef") + val ham = Meat("ham") + val meatBox = FoodBox() + meatBox.add(beef) + meatBox.add(ham) + println("MeatBox contains : $meatBox") + + cheddar.eat() + beef.eat() + println("Full now!") +} diff --git a/Task/Constrained-genericity/OoRexx/constrained-genericity.rexx b/Task/Constrained-genericity/OoRexx/constrained-genericity.rexx new file mode 100644 index 0000000000..095bc5ed45 --- /dev/null +++ b/Task/Constrained-genericity/OoRexx/constrained-genericity.rexx @@ -0,0 +1,29 @@ +call dinnerTime "yogurt" +call dinnerTime .pizza~new +call dinnerTime .broccoli~new + + +-- a mixin class that defines the interface for being "food", and +-- thus expected to implement an "eat" method +::class food mixinclass object +::method eat abstract + +::class pizza subclass food +::method eat + Say "mmmmmmmm, pizza". + +-- mixin classes can also be used for multiple inheritance +::class broccoli inherit food +::method eat + Say "ugh, do I have to?". + +::routine dinnerTime + use arg dish + -- ooRexx arguments are typeless, so tests for constrained + -- types must be peformed at run time. The isA method will + -- check if an object is of the required type + if \dish~isA(.food) then do + say "I can't eat that!" + return + end + else dish~eat diff --git a/Task/Constrained-genericity/Rust/constrained-genericity.rust b/Task/Constrained-genericity/Rust/constrained-genericity.rust new file mode 100644 index 0000000000..fe3ecdf649 --- /dev/null +++ b/Task/Constrained-genericity/Rust/constrained-genericity.rust @@ -0,0 +1,49 @@ +// This declares the "Eatable" constraint. It could contain no function. +trait Eatable { + fn eat(); +} + +// This declares the generic "FoodBox" type, +// whose parameter must satisfy the "Eatable" constraint. +// The objects of this type contain a vector of eatable objects. +struct FoodBox { + _data: Vec, +} + +// This implements the functions associated with the "FoodBox" type. +// This statement is not required, but here it is used +// to declare a handy "new" constructor. +impl FoodBox { + fn new() -> FoodBox { + FoodBox:: { _data: Vec::::new() } + } +} + +// This declares a simple type. +struct Banana {} + +// This makes the "Banana" type satisfy the "Eatable" constraint. +// For that, every declaration inside the declaration of "Eatable" +// must be implemented here. +impl Eatable for Banana { + fn eat() {} +} + +// This makes also the primitive "char" type satisfy the "Eatable" constraint. +impl Eatable for char { + fn eat() {} +} + +fn main() { + // This instantiate a "FoodBox" parameterized by the "Banana" type. + // It is allowed as "Banana" implements "Eatable". + let _fb1 = FoodBox::::new(); + + // This instantiate a "FoodBox" parameterized by the "char" type. + // It is allowed, as "char" implements "Eatable". + let _fb2 = FoodBox::::new(); + + // This instantiate a "FoodBox" parameterized by the "bool" type. + // It is NOT allowed, as "bool" does not implement "Eatable". + //let _fb3 = FoodBox::::new(); +} diff --git a/Task/Constrained-genericity/Zkl/constrained-genericity-1.zkl b/Task/Constrained-genericity/Zkl/constrained-genericity-1.zkl new file mode 100644 index 0000000000..a0608508ea --- /dev/null +++ b/Task/Constrained-genericity/Zkl/constrained-genericity-1.zkl @@ -0,0 +1,10 @@ +class Eatable{ var v; + fcn eat{ println("munching ",self.topdog.name); } +} +class FoodBox{ + fcn init(food1,food2,etc){ + editable,garbage:=vm.arglist.filter22("isChildOf",Eatable); + var contents=editable; + if(garbage) println("Rejecting: ",garbage); + } +} diff --git a/Task/Constrained-genericity/Zkl/constrained-genericity-2.zkl b/Task/Constrained-genericity/Zkl/constrained-genericity-2.zkl new file mode 100644 index 0000000000..fd78d60616 --- /dev/null +++ b/Task/Constrained-genericity/Zkl/constrained-genericity-2.zkl @@ -0,0 +1,2 @@ +class Apple(Eatable){} class Nuts(Eatable){} class Foo{} +FoodBox(Apple,"boogers",Nuts,Foo).contents.apply2("eat"); diff --git a/Task/Constrained-random-points-on-a-circle/BBC-BASIC/constrained-random-points-on-a-circle.bbc b/Task/Constrained-random-points-on-a-circle/BBC-BASIC/constrained-random-points-on-a-circle.bbc deleted file mode 100644 index 9196a187a8..0000000000 --- a/Task/Constrained-random-points-on-a-circle/BBC-BASIC/constrained-random-points-on-a-circle.bbc +++ /dev/null @@ -1,8 +0,0 @@ - MODE 8 - ORIGIN 640, 512 - FOR i% = 1 TO 1000 - x% = RND(31)-16 - y% = RND(31)-16 - r = SQR(x%^2 + y%^2) - IF r >= 10 IF r <= 15 PLOT x%*2, y%*2 - NEXT diff --git a/Task/Constrained-random-points-on-a-circle/Gnuplot/constrained-random-points-on-a-circle.gnuplot b/Task/Constrained-random-points-on-a-circle/Gnuplot/constrained-random-points-on-a-circle.gnuplot new file mode 100644 index 0000000000..4778678276 --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/Gnuplot/constrained-random-points-on-a-circle.gnuplot @@ -0,0 +1,27 @@ +## Ring of random points 2/18/17 aev +reset +fn="RingRandPntsGnu"; +ttl="Ring of random points" +ofn=fn.".png"; lim=1000; +randgp(top) = floor(rand(0)*top) +set terminal png font arial 12 size 640,640 +set output ofn +set title ttl font "Arial:Bold,12" +unset key; +set size square +set parametric +set xrange [-20:20]; set yrange [-20:20]; +set style line 1 lt rgb "red" +$rring << EOD +EOD +set print $rring append +do for [i=1:lim] { + x=randgp(30); y=randgp(30); + r=sqrt(x**2+y**2); + if (r>=10&&r<=15) \ + {print x," ",y; print -x," ",-y;print x," ",-y; print -x," ",y;} +} +plot [0:2*pi] sin(t)*10,cos(t)*10, sin(t)*15,cos(t)*15 ls 1,\ +$rring using 1:2 with points pt 7 ps 0.5 lc "black" +set output +unset print diff --git a/Task/Constrained-random-points-on-a-circle/Kotlin/constrained-random-points-on-a-circle.kotlin b/Task/Constrained-random-points-on-a-circle/Kotlin/constrained-random-points-on-a-circle.kotlin new file mode 100644 index 0000000000..e09eaa9030 --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/Kotlin/constrained-random-points-on-a-circle.kotlin @@ -0,0 +1,17 @@ +// version 1.1.3 + +fun main(args: Array) { + val r = java.util.Random() + val points = Array(31) { CharArray(31) { ' ' } } + var count = 0 + while (count < 100) { + val x = r.nextInt(31) - 15 + val y = r.nextInt(31) - 15 + val h = x * x + y * y + if (h in 100..225) { + points[x + 15][y + 15] = 'o' + count++ + } + } + for (i in 0..30) println(points[i].joinToString("")) +} diff --git a/Task/Constrained-random-points-on-a-circle/Zkl/constrained-random-points-on-a-circle.zkl b/Task/Constrained-random-points-on-a-circle/Zkl/constrained-random-points-on-a-circle.zkl new file mode 100644 index 0000000000..88f32fb738 --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/Zkl/constrained-random-points-on-a-circle.zkl @@ -0,0 +1,10 @@ +xy:=(0).walker(*).tweak(fcn{ // generate infinite random pairs (lazy) + x:=(-15).random(16); y:=(-15).random(16); + if(not (100<=(x*x + y*y)<=225)) Void.Skip else T(x,y) +}); + +const N=31; // [-15..15] includes 0 +array:=(" ,"*N*N).split(",").copy(); // bunch of spaces (list) + +xy.walk(100).apply2(fcn([(x,y)],array){array[x+15 + N*(y+15)]="*"},array); +foreach n in ([0..30]){ array[n*N,30].concat().println(); } diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Clojure/continued-fraction-arithmetic-construct-from-rational-number.clj b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Clojure/continued-fraction-arithmetic-construct-from-rational-number.clj new file mode 100644 index 0000000000..292007c867 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Clojure/continued-fraction-arithmetic-construct-from-rational-number.clj @@ -0,0 +1,27 @@ +(defn r2cf [n d] + (if-not (= d 0) (cons (quot n d) (lazy-seq (r2cf d (rem n d)))))) + +; Example usage +(def demo '((1 2) + (3 1) + (23 8) + (13 11) + (22 7) + (-151 77) + (14142 10000) + (141421 100000) + (1414214 1000000) + (14142136 10000000) + (31 10) + (314 100) + (3142 1000) + (31428 10000) + (314285 100000) + (3142857 1000000) + (31428571 10000000) + (314285714 100000000) + (3141592653589793 1000000000000000))) + +(doseq [inputs demo + :let [outputs (r2cf (first inputs) (last inputs))]] + (println inputs ";" outputs)) diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Haskell/continued-fraction-arithmetic-construct-from-rational-number.hs b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Haskell/continued-fraction-arithmetic-construct-from-rational-number.hs index 0a0dfb82d1..692245f950 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Haskell/continued-fraction-arithmetic-construct-from-rational-number.hs +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Haskell/continued-fraction-arithmetic-construct-from-rational-number.hs @@ -2,10 +2,16 @@ import Data.Ratio ((%)) real2cf :: (RealFrac a, Integral b) => a -> [b] real2cf x = - i : if f == 0 then [] else real2cf (1/f) - where (i, f) = properFraction x + let (i, f) = properFraction x + in i : + if f == 0 + then [] + else real2cf (1 / f) main :: IO () -main = do - print $ real2cf (13 % 11) -- => [1,5,2] - print $ take 20 $ real2cf (sqrt 2) -- => [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] +main = + mapM_ + print + [ real2cf (13 % 11) + , take 20 $ real2cf (sqrt 2) + ] diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Kotlin/continued-fraction-arithmetic-construct-from-rational-number.kotlin b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Kotlin/continued-fraction-arithmetic-construct-from-rational-number.kotlin new file mode 100644 index 0000000000..7e909c7d41 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Kotlin/continued-fraction-arithmetic-construct-from-rational-number.kotlin @@ -0,0 +1,45 @@ +// version 1.1.2 +// compile with -Xcoroutines=enable flag from command line + +import kotlin.coroutines.experimental.buildSequence + +fun r2cf(frac: Pair) = + buildSequence { + var num = frac.first + var den = frac.second + while (Math.abs(den) != 0) { + val div = num / den + val rem = num % den + num = den + den = rem + yield(div) + } + } + +fun iterate(seq: Sequence) { + for (i in seq) print("$i ") + println() +} + +fun main(args: Array) { + val fracs = arrayOf(1 to 2, 3 to 1, 23 to 8, 13 to 11, 22 to 7, -151 to 77) + for (frac in fracs) { + print("${"%4d".format(frac.first)} / ${"%-2d".format(frac.second)} = ") + iterate(r2cf(frac)) + } + val root2 = arrayOf(14142 to 10000, 141421 to 100000, + 1414214 to 1000000, 14142136 to 10000000) + println("\nSqrt(2) ->") + for (frac in root2) { + print("${"%8d".format(frac.first)} / ${"%-8d".format(frac.second)} = ") + iterate(r2cf(frac)) + } + val pi = arrayOf(31 to 10, 314 to 100, 3142 to 1000, 31428 to 10000, + 314285 to 100000, 3142857 to 1000000, + 31428571 to 10000000, 314285714 to 100000000) + println("\nPi ->") + for (frac in pi) { + print("${"%9d".format(frac.first)} / ${"%-9d".format(frac.second)} = ") + iterate(r2cf(frac)) + } +} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/REXX/continued-fraction-arithmetic-construct-from-rational-number.rexx b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/REXX/continued-fraction-arithmetic-construct-from-rational-number.rexx index 2ba9a0f02c..8c8ed43d93 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/REXX/continued-fraction-arithmetic-construct-from-rational-number.rexx +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/REXX/continued-fraction-arithmetic-construct-from-rational-number.rexx @@ -1,62 +1,58 @@ /*REXX program converts a decimal or rational fraction to a continued fraction. */ numeric digits 230 /*determines how many terms to be gened*/ -say ' 1/2 ──► CF: ' r2cf( '1/2' ) -say ' 3 ──► CF: ' r2cf( 3 ) -say ' 23/8 ──► CF: ' r2cf( '23/8' ) -say ' 13/11 ──► CF: ' r2cf( '13/11' ) -say ' 22/7 ──► CF: ' r2cf( '22/7 ' ) +say ' 1/2 ──► CF: ' r2cf( '1/2' ) +say ' 3 ──► CF: ' r2cf( 3 ) +say ' 23/8 ──► CF: ' r2cf( '23/8' ) +say ' 13/11 ──► CF: ' r2cf( '13/11' ) +say ' 22/7 ──► CF: ' r2cf( '22/7 ' ) say ' ___' say '───────── attempts at √ 2.' -say '14142/1e4 ──► CF: ' r2cf( '14142/1e4 ' ) -say '141421/1e5 ──► CF: ' r2cf( '141421/1e5 ' ) -say '1414214/1e6 ──► CF: ' r2cf( '1414214/1e6 ' ) -say '14142136/1e7 ──► CF: ' r2cf( '14142136/1e7 ' ) -say '141421356/1e8 ──► CF: ' r2cf( '141421356/1e8 ' ) -say '1414213562/1e9 ──► CF: ' r2cf( '1414213562/1e9 ' ) -say '14142135624/1e10 ──► CF: ' r2cf( '14142135624/1e10 ' ) -say '141421356237/1e11 ──► CF: ' r2cf( '141421356237/1e11 ' ) +say '14142/1e4 ──► CF: ' r2cf( '14142/1e4 ' ) +say '141421/1e5 ──► CF: ' r2cf( '141421/1e5 ' ) +say '1414214/1e6 ──► CF: ' r2cf( '1414214/1e6 ' ) +say '14142136/1e7 ──► CF: ' r2cf( '14142136/1e7 ' ) +say '141421356/1e8 ──► CF: ' r2cf( '141421356/1e8 ' ) +say '1414213562/1e9 ──► CF: ' r2cf( '1414213562/1e9 ' ) +say '14142135624/1e10 ──► CF: ' r2cf( '14142135624/1e10 ' ) +say '141421356237/1e11 ──► CF: ' r2cf( '141421356237/1e11 ' ) say '1414213562373/1e12 ──► CF: ' r2cf( '1414213562373/1e12 ' ) -say '√2 ──► CF: ' r2cf( sqrt(2) ) +say '√2 ──► CF: ' r2cf( sqrt(2) ) say say '───────── an attempt at pi' say 'pi ──► CF: ' r2cf( pi() ) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -r2cf: procedure; parse arg g 1 s 2; $=; if s=='-' then g = substr(g,2) - else s = - if pos('.',g)\==0 then do - if \datatype(g,'N') then call serr 'not numeric:' g - g = $maxfact(g) - end - if pos('/',g)==0 then g = g"/"1 - parse var g n '/' d - if \datatype(n,'W') then call serr "a numerator isn't an integer:" n - if \datatype(d,'W') then call serr "a denominator isn't an integer:" d - n = abs(n) /*ensure numerator is positive. */ - if d=0 then call serr 'a denominator is zero' - - do while d\==0 /*where the rubber meets the road*/ - $ = $ s || (n%d) /*append another number to list. */ - _ = d - d = n // d /* % is int div, // is modulus.*/ - n = _ - end /*while*/ - return strip($) +$maxFact: procedure; parse arg x 1 _x,y; y=10**(digits()-1); b=0; h=1; a=1; g=0 + do while a<=y & g<=y; n=trunc(_x); _=a; a=n*a+b; b=_; _=g; g=n*g+h; h=_ + if n=_x | a/g=x then do; if a>y | g>y then iterate; b=a; h=g; leave; end + _x=1/(_x-n); end; return b'/'h /*──────────────────────────────────────────────────────────────────────────────────────*/ pi: return 3.1415926535897932384626433832795028841971693993751058209749445923078164062862, || 089986280348253421170679821480865132823066470938446095505822317253594081284, || 811174502841027019385211055596446229489549303819644288109756659334461284756, - || 48233786783165271 /* ··· should ≥ NUMERIC DIGITS */ + || 48233786783165271 /* ··· should ≥ NUMERIC DIGITS */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -serr: say; say '***error!***'; say; say arg(1); say; exit 13 +r2cf: procedure; parse arg g 1 s 2; $=; if s=='-' then g=substr(g, 2) + else s= + if pos(., g)\==0 then do; if \datatype(g, 'N') then call serr 'not numeric:' g + g=$maxfact(g) + end + if pos('/', g)==0 then g=g"/"1 + parse var g n '/' d + if \datatype(n, 'W') then call serr "a numerator isn't an integer:" n + if \datatype(d, 'W') then call serr "a denominator isn't an integer:" d + if d=0 then call serr 'a denominator is zero' + n=abs(n) /*ensure numerator is positive. */ + do while d\==0; _=d /*where the rubber meets the road*/ + $=$ s || (n%d) /*append another number to list. */ + d=n // d; n=_ /* % is int div, // is modulus.*/ + end /*while*/ + return strip($) +/*──────────────────────────────────────────────────────────────────────────────────────*/ +serr: say; say '***error***'; say; say arg(1); say; exit 13 /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h=d+6; numeric form m.=9; 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*/ - numeric digits d; return g/1 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -$maxFact: procedure; parse arg x 1 _x,y; y=10**(digits()-1); b=0; h=1; a=1; g=0 - do while a<=y & g<=y; n=trunc(_x); _=a; a=n*a+b; b=_; _=g; g=n*g+h; h=_ - if n=_x | a/g=x then do; if a>y|g>y then iterate; b=a; h=g; leave; end - _x=1/(_x-n); end; return b'/'h + numeric digits d; return g/1 diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-10.rb b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-10.rb deleted file mode 100644 index d8ee9cf7c5..0000000000 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-10.rb +++ /dev/null @@ -1 +0,0 @@ -r2cf(14142136,10000000) {|n| print "#{n} "} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-5.rb b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-5.rb deleted file mode 100644 index 9ad87f479f..0000000000 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-5.rb +++ /dev/null @@ -1 +0,0 @@ -r2cf(13,11) {|n| print "#{n} "} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-6.rb b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-6.rb deleted file mode 100644 index de78f13b5a..0000000000 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-6.rb +++ /dev/null @@ -1 +0,0 @@ -r2cf(22,7) {|n| print "#{n} "} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-7.rb b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-7.rb deleted file mode 100644 index a24cf2f2de..0000000000 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-7.rb +++ /dev/null @@ -1 +0,0 @@ -r2cf(14142,10000) {|n| print "#{n} "} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-8.rb b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-8.rb deleted file mode 100644 index 540b71adad..0000000000 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-8.rb +++ /dev/null @@ -1 +0,0 @@ -r2cf(141421,100000) {|n| print "#{n} "} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-9.rb b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-9.rb deleted file mode 100644 index 0354322540..0000000000 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-9.rb +++ /dev/null @@ -1 +0,0 @@ -r2cf(1414214,1000000) {|n| print "#{n} "} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Sidef/continued-fraction-arithmetic-construct-from-rational-number.sidef b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Sidef/continued-fraction-arithmetic-construct-from-rational-number.sidef index 5cdc61beb9..d7c19eeb07 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Sidef/continued-fraction-arithmetic-construct-from-rational-number.sidef +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Sidef/continued-fraction-arithmetic-construct-from-rational-number.sidef @@ -1,7 +1,7 @@ func r2cf(num, den) { func() { - den.is_zero && return() - var q = int(num/den) + den || return nil + var q = num//den (num, den) = (den, num - q*den) return q } @@ -20,6 +20,6 @@ func showcf(f) { [14142/10000, 141421/100000, 1414214/1000000, 14142136/10000000], [314285714/100000000], ].each { |seq| - seq.each { |r| showcf(r2cf(r.parts)) } + seq.each { |r| showcf(r2cf(r.nude)) } print "\n" } diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Zkl/continued-fraction-arithmetic-construct-from-rational-number-1.zkl b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Zkl/continued-fraction-arithmetic-construct-from-rational-number-1.zkl new file mode 100644 index 0000000000..d3117e867c --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Zkl/continued-fraction-arithmetic-construct-from-rational-number-1.zkl @@ -0,0 +1,9 @@ +fcn r2cf(nom,dnom){ // -->Walker (iterator) + Walker.tweak(fcn(state){ + nom,dnom:=state; + if(dnom==0) return(Void.Stop); + n,d:=nom.divr(dnom); + state.clear(dnom,d); + n + }.fp(List(nom,dnom))) // partial application (light weight closure) +} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Zkl/continued-fraction-arithmetic-construct-from-rational-number-2.zkl b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Zkl/continued-fraction-arithmetic-construct-from-rational-number-2.zkl new file mode 100644 index 0000000000..1a4a182156 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Zkl/continued-fraction-arithmetic-construct-from-rational-number-2.zkl @@ -0,0 +1,9 @@ +fcn r2cf2(nom,dnom){ // -->Generator (heavy weight Walker) + Utils.Generator(fcn(nom,dnom){ + while(dnom){ + n,d:=nom.divr(dnom); nom,dnom=dnom,d; + vm.yield(n); + } + Void.Stop; + },nom,dnom) +} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Zkl/continued-fraction-arithmetic-construct-from-rational-number-3.zkl b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Zkl/continued-fraction-arithmetic-construct-from-rational-number-3.zkl new file mode 100644 index 0000000000..bc868edfc2 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Zkl/continued-fraction-arithmetic-construct-from-rational-number-3.zkl @@ -0,0 +1,5 @@ +foreach nom,dnom in (T(T(1,2), T(3,1), T(23,8), T(13,11), T(22,7), + T(14142,10000), T(141421,100000), T(1414214,1000000), + T(14142136,10000000))){ + r2cf(nom,dnom).walk(25).println(); // print up to 25 numbers +} diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Kotlin/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n-.kotlin b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Kotlin/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n-.kotlin new file mode 100644 index 0000000000..236529c9c7 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Kotlin/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n-.kotlin @@ -0,0 +1,124 @@ +// version 1.1.3 +// compile with -Xcoroutines=enable flag from command line + +import kotlin.coroutines.experimental.* + +typealias CFGenerator = (Pair) -> Sequence + +data class CFData( + val str: String, + val ng: IntArray, + val r: Pair, + val gen: CFGenerator +) + +fun r2cf(frac: Pair) = + buildSequence { + var num = frac.first + var den = frac.second + while (Math.abs(den) != 0) { + val div = num / den + val rem = num % den + num = den + den = rem + yield(div) + } + } + +fun d2cf(d: Double) = + buildSequence { + var dd = d + while (true) { + val div = Math.floor(dd) + val rem = dd - div + yield(div.toInt()) + if (rem == 0.0) break + dd = 1.0 / rem + } + } + +@Suppress("UNUSED_PARAMETER") +fun root2(dummy: Pair) = + buildSequence { + yield(1) + while (true) yield(2) + } + +@Suppress("UNUSED_PARAMETER") +fun recipRoot2(dummy: Pair) = + buildSequence { + yield(0) + yield(1) + while (true) yield(2) + } + +class NG(var a1: Int, var a: Int, var b1: Int, var b: Int) { + + fun ingress(n: Int) { + var t = a + a = a1 + a1 = t + a1 * n + t = b + b = b1 + b1 = t + b1 * n + } + + fun egress(): Int { + val n = a / b + var t = a + a = b + b = t - b * n + t = a1 + a1 = b1 + b1 = t - b1 * n + return n + } + + val needTerm get() = (b == 0 || b1 == 0) || ((a / b) != (a1 / b1)) + + val egressDone: Int + get() { + if (needTerm) { + a = a1 + b = b1 + } + return egress() + } + + val done get() = b == 0 && b1 == 0 +} + +fun main(args: Array) { + val data = listOf( + CFData("[1;5,2] + 1/2 ", intArrayOf(2, 1, 0, 2), 13 to 11, ::r2cf), + CFData("[3;7] + 1/2 ", intArrayOf(2, 1, 0, 2), 22 to 7, ::r2cf), + CFData("[3;7] divided by 4 ", intArrayOf(1, 0, 0, 4), 22 to 7, ::r2cf), + CFData("sqrt(2) ", intArrayOf(0, 1, 1, 0), 0 to 0, ::recipRoot2), + CFData("1 / sqrt(2) ", intArrayOf(0, 1, 1, 0), 0 to 0, ::root2), + CFData("(1 + sqrt(2)) / 2 ", intArrayOf(1, 1, 0, 2), 0 to 0, ::root2), + CFData("(1 + 1 / sqrt(2)) / 2", intArrayOf(1, 1, 0, 2), 0 to 0, ::recipRoot2) + ) + println("Produced by NG class:") + for ((str, ng, r, gen) in data) { + print("$str -> ") + val (a1, a, b1, b) = ng + val op = NG(a1, a, b1, b) + for (n in gen(r).take(20)) { + if (!op.needTerm) print(" ${op.egress()} ") + op.ingress(n) + } + while (true) { + print(" ${op.egressDone} ") + if (op.done) break + } + println() + } + println("\nProduced by direct calculation:") + val data2 = listOf( + Pair("(1 + sqrt(2)) / 2 ", (1 + Math.sqrt(2.0)) / 2), + Pair("(1 + 1 / sqrt(2)) / 2", (1 + 1 / Math.sqrt(2.0)) / 2) + ) + for ((str, d) in data2) { + println("$str -> ${d2cf(d).take(20).joinToString(" ")}") + } +} diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Ruby/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--3.rb b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Ruby/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--3.rb deleted file mode 100644 index 24ac7eb6c5..0000000000 --- a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Ruby/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--3.rb +++ /dev/null @@ -1,3 +0,0 @@ -op = NG.new(2,1,0,2) -r2cf(22,7) {|n| if op.needterm? then op.ingress(n) else print "#{op.egress} "; op.ingress(n) end} -while not op.done? do print "#{op.egress_done} " end diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Ruby/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--4.rb b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Ruby/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--4.rb deleted file mode 100644 index c6556761ea..0000000000 --- a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Ruby/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--4.rb +++ /dev/null @@ -1,3 +0,0 @@ -op = NG.new(1,0,0,4) -r2cf(22,7) {|n| if op.needterm? then op.ingress(n) else print "#{op.egress} "; op.ingress(n) end} -while not op.done? do print "#{op.egress_done} " end diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Zkl/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.zkl b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Zkl/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.zkl new file mode 100644 index 0000000000..a36b8a15dd --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Zkl/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.zkl @@ -0,0 +1,20 @@ +class NG{ + fcn init(_a1,_a, _b1,_b){ var a1=_a1,a=_a, b1=_b1,b=_b; } + var [proxy] done =fcn{ b==0 and b1==0 }; + var [proxy] needterm=fcn{ (b==0 or b1==0) or (a/b!=a1/b1) }; + fcn ingress(n){ + t:=self.copy(True); // tmp copy of vars for eager vs late evaluation + a,a1=t.a1, t.a + n*t.a1; + b,b1=t.b1, t.b + n*t.b1; + } + fcn egress{ + n,t:=a/b,self.copy(True); + a,b =t.b, t.a - n*t.b; + a1,b1=t.b1,t.a1 - n*t.b1; + n + } + fcn egress_done{ + if(needterm) a,b=a1,b1; + egress() + } +} diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Zkl/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.zkl b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Zkl/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.zkl new file mode 100644 index 0000000000..6869fef7ba --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Zkl/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.zkl @@ -0,0 +1,10 @@ + // from task: Continued fraction/Arithmetic/Construct from rational number +fcn r2cf(nom,dnom){ // -->Walker (iterator) + Walker.tweak(fcn(_,state){ + nom,dnom:=state; + if(dnom==0) return(Void.Stop); + n,d:=nom.divr(dnom); + state.clear(dnom,d); + n + }.fp1(List(nom,dnom))) +} diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Zkl/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--3.zkl b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Zkl/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--3.zkl new file mode 100644 index 0000000000..7a5e04d051 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Zkl/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--3.zkl @@ -0,0 +1,13 @@ +data:=T(T("[1;5,2] + 1/2", T(2,1,0,2), T(13,11)), + T("[3;7] + 1/2", T(2,1,0,2), T(22, 7)), + T("[3;7] divided by 4", T(1,0,0,4), T(22, 7))); +foreach string,ng,r in (data){ + print("%-20s-->".fmt(string)); + op:=NG(ng.xplode()); + foreach n in (r2cf(r.xplode())){ + if(not op.needterm) print(" %s".fmt(op.egress())); + op.ingress(n); + } + do{ print(" ",op.egress_done()) }while(not op.done); + println(); +} diff --git a/Task/Continued-fraction/jq/continued-fraction-1.jq b/Task/Continued-fraction/Jq/continued-fraction-1.jq similarity index 100% rename from Task/Continued-fraction/jq/continued-fraction-1.jq rename to Task/Continued-fraction/Jq/continued-fraction-1.jq diff --git a/Task/Continued-fraction/jq/continued-fraction-2.jq b/Task/Continued-fraction/Jq/continued-fraction-2.jq similarity index 100% rename from Task/Continued-fraction/jq/continued-fraction-2.jq rename to Task/Continued-fraction/Jq/continued-fraction-2.jq diff --git a/Task/Continued-fraction/jq/continued-fraction-3.jq b/Task/Continued-fraction/Jq/continued-fraction-3.jq similarity index 100% rename from Task/Continued-fraction/jq/continued-fraction-3.jq rename to Task/Continued-fraction/Jq/continued-fraction-3.jq diff --git a/Task/Continued-fraction/Klong/continued-fraction.klong b/Task/Continued-fraction/Klong/continued-fraction.klong new file mode 100644 index 0000000000..8dbe02abe9 --- /dev/null +++ b/Task/Continued-fraction/Klong/continued-fraction.klong @@ -0,0 +1,5 @@ +cf::{[f g i];f::x;g::y;i::z; + f(0)+z{i::i-1;g(i+1)%f(i+1)+x}:*0} +cf({:[0=x;1;2]};{x;1};1000) +cf({:[0=x;2;x]};{:[x>1;x-1;x]};1000) +cf({:[0=x;3;6]};{((2*x)-1)^2};1000) diff --git a/Task/Continued-fraction/Kotlin/continued-fraction.kotlin b/Task/Continued-fraction/Kotlin/continued-fraction.kotlin new file mode 100644 index 0000000000..d693f92254 --- /dev/null +++ b/Task/Continued-fraction/Kotlin/continued-fraction.kotlin @@ -0,0 +1,21 @@ +// version 1.1.2 + +typealias Func = (Int) -> IntArray + +fun calc(f: Func, n: Int): Double { + var temp = 0.0 + for (i in n downTo 1) { + val p = f(i) + temp = p[1] / (p[0] + temp) + } + return f(0)[0] + temp +} + +fun main(args: Array) { + val pList = listOf>( + "sqrt(2)" to { n -> intArrayOf(if (n > 0) 2 else 1, 1) }, + "e " to { n -> intArrayOf(if (n > 0) n else 2, if (n > 1) n - 1 else 1) }, + "pi " to { n -> intArrayOf(if (n > 0) 6 else 3, (2 * n - 1) * (2 * n - 1)) } + ) + for (pair in pList) println("${pair.first} = ${calc(pair.second, 200)}") +} diff --git a/Task/Continued-fraction/Maple/continued-fraction.maple b/Task/Continued-fraction/Maple/continued-fraction.maple new file mode 100644 index 0000000000..2dcc0331c0 --- /dev/null +++ b/Task/Continued-fraction/Maple/continued-fraction.maple @@ -0,0 +1,4 @@ +contfrac:=n->evalf(Value(NumberTheory:-ContinuedFraction(n))); +contfrac(2^(0.5)); +contfrac(Pi); +contfrac(exp(1)); diff --git a/Task/Continued-fraction/Phix/continued-fraction.phix b/Task/Continued-fraction/Phix/continued-fraction.phix new file mode 100644 index 0000000000..948776bbdd --- /dev/null +++ b/Task/Continued-fraction/Phix/continued-fraction.phix @@ -0,0 +1,23 @@ +function continued_fraction(integer steps, integer rid_a, integer rid_b) +atom res = 0 + for n=steps to 1 by -1 do + res := call_func(rid_b,{n}) / (call_func(rid_a,{n}) + res) + end for + return call_func(rid_a,{0}) + res +end function + +function sqr2_a(integer n) return iff(n=0?1:2) end function +function sqr2_b(integer n) return 1 end function + +function nap_a(integer n) return iff(n=0?2:n) end function +function nap_b(integer n) return iff(n=1?1:n-1) end function + +function pi_a(integer n) return iff(n=0?3:6) end function +function pi_b(integer n) return iff(n=1?1:power(2*n-1,2)) end function + +constant precision = 10000 + +printf(1,"Precision: %d\n", {precision}) +printf(1,"Sqr(2): %.10g\n", {continued_fraction(precision, routine_id("sqr2_a"), routine_id("sqr2_b"))}) +printf(1,"Napier: %.10g\n", {continued_fraction(precision, routine_id("nap_a"), routine_id("nap_b"))}) +printf(1,"Pi: %.10g\n", {continued_fraction(precision, routine_id("pi_a"), routine_id("pi_b"))}) diff --git a/Task/Continued-fraction/Zkl/continued-fraction-1.zkl b/Task/Continued-fraction/Zkl/continued-fraction-1.zkl new file mode 100644 index 0000000000..fbbc9a52d6 --- /dev/null +++ b/Task/Continued-fraction/Zkl/continued-fraction-1.zkl @@ -0,0 +1,4 @@ +fcn cf(fa,fb,a0){fcn(fa,fb,a0,n){ + a0 + [n..1,-1].reduce( + 'wrap(p,n){ fb(n)/(fa(n)+p) },0.0) }.fp(fa,fb,a0) +} diff --git a/Task/Continued-fraction/Zkl/continued-fraction-2.zkl b/Task/Continued-fraction/Zkl/continued-fraction-2.zkl new file mode 100644 index 0000000000..7a048476d4 --- /dev/null +++ b/Task/Continued-fraction/Zkl/continued-fraction-2.zkl @@ -0,0 +1,6 @@ +sqrt2:=cf((2.0).noop,(1.0).noop,1.0); + sqrt2(200) : "%.20e".fmt(_).println(); +nap:=cf((0.0).create,fcn(n){ (n==1) and 1.0 or (n-1).toFloat() },2.0); + println(nap(15) - (1.0).e); +pi:=cf((6.0).noop,fcn(n){ n=2*n-1; (n*n).toFloat() },3.0); + println(pi(1000) - (1.0).pi); diff --git a/Task/Convert-decimal-number-to-rational/Kotlin/convert-decimal-number-to-rational.kotlin b/Task/Convert-decimal-number-to-rational/Kotlin/convert-decimal-number-to-rational.kotlin new file mode 100644 index 0000000000..748d9fccce --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Kotlin/convert-decimal-number-to-rational.kotlin @@ -0,0 +1,29 @@ +// version 1.1.2 + +class Rational(val num: Long, val den: Long) { + override fun toString() = "$num/$den" +} + +fun decimalToRational(d: Double): Rational { + val ds = d.toString().trimEnd('0').trimEnd('.') + val index = ds.indexOf('.') + if (index == -1) return Rational(ds.toLong(), 1L) + var num = ds.replace(".", "").toLong() + var den = 1L + for (n in 1..(ds.length - index - 1)) den *= 10L + while (num % 2L == 0L && den % 2L == 0L) { + num /= 2L + den /= 2L + } + while (num % 5L == 0L && den % 5L == 0L) { + num /= 5L + den /= 5L + } + return Rational(num, den) +} + +fun main(args: Array) { + val decimals = doubleArrayOf(0.9054054, 0.518518, 2.405308, .75, 0.0, -0.64, 123.0, -14.6) + for (decimal in decimals) + println("${decimal.toString().padEnd(9)} = ${decimalToRational(decimal)}") +} diff --git a/Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-3.rexx b/Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-3.rexx index d68e447edc..66e9db5687 100644 --- a/Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-3.rexx +++ b/Task/Convert-decimal-number-to-rational/REXX/convert-decimal-number-to-rational-3.rexx @@ -50,8 +50,7 @@ test: Else tag='should be' soll say zin '=' fract tag - -- Say left(zz/nn,60) - Return + Return GCD: procedure /********************************************************************** diff --git a/Task/Convert-decimal-number-to-rational/Ruby/convert-decimal-number-to-rational-2.rb b/Task/Convert-decimal-number-to-rational/Ruby/convert-decimal-number-to-rational-2.rb index 3c2fdb7f55..281d7af286 100644 --- a/Task/Convert-decimal-number-to-rational/Ruby/convert-decimal-number-to-rational-2.rb +++ b/Task/Convert-decimal-number-to-rational/Ruby/convert-decimal-number-to-rational-2.rb @@ -1,5 +1,4 @@ -> [0.9054054, 0.518518, 0.75].each { |d| puts "%s %s" % [d, Rational(d).rationalize(0.0001)] } -0.9054054 67/74 -0.518518 14/27 -0.75 3/4 -=> [0.9054054, 0.518518, 0.75] +[0.9054054, 0.518518, 0.75].each { |f| puts "#{f} #{f.rationalize(0.0001)}" } +# =>0.9054054 67/74 +# =>0.518518 14/27 +# =>0.75 3/4 diff --git a/Task/Convert-decimal-number-to-rational/Zkl/convert-decimal-number-to-rational-1.zkl b/Task/Convert-decimal-number-to-rational/Zkl/convert-decimal-number-to-rational-1.zkl new file mode 100644 index 0000000000..4d1ba4a943 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Zkl/convert-decimal-number-to-rational-1.zkl @@ -0,0 +1,14 @@ +fcn real2Rational(r,bound){ + if (r == 0.0) return(0,1); + if (r < 0.0){ + result := real2Rational(-r, bound); + return(-result[0],result[1]); + } else { + best,bestError := 1,(1.0).MAX; + foreach i in ([1 .. bound + 1]){ + error := (r*i - (r*i).round()).abs(); + if (error < bestError) best,bestError = i,error; + } + return((r*best).round().toInt(),best); + } +} diff --git a/Task/Convert-decimal-number-to-rational/Zkl/convert-decimal-number-to-rational-2.zkl b/Task/Convert-decimal-number-to-rational/Zkl/convert-decimal-number-to-rational-2.zkl new file mode 100644 index 0000000000..fe9bc4cfe6 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Zkl/convert-decimal-number-to-rational-2.zkl @@ -0,0 +1,9 @@ +tests := T(0.750000000, 0.518518000, 0.905405400, + 0.142857143, 3.141592654, 2.718281828, + -0.423310825, 31.415926536); +foreach r in (tests) { + print("%8.9f ".fmt(r)); + foreach i in (6) + { print(" %d/%d".fmt(real2Rational(r,(10).pow(i)).xplode())) } + println(); +} diff --git a/Task/Conways-Game-of-Life/00DESCRIPTION b/Task/Conways-Game-of-Life/00DESCRIPTION index bb6995ecf4..61f1b60507 100644 --- a/Task/Conways-Game-of-Life/00DESCRIPTION +++ b/Task/Conways-Game-of-Life/00DESCRIPTION @@ -26,6 +26,6 @@ Although you should test your implementation on more complex examples such as th *   John Conway   [http://www.youtube.com/watch?v=R9Plq-D1gEk Inventing Game of Life]   - Numberphile video. -;See also: +;Related task: *   [[Langton's ant]]   - another well known cellular automaton.

    diff --git a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-10.basic b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-10.basic index 3e6839ffc6..a65257dee1 100644 --- a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-10.basic +++ b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-10.basic @@ -1,76 +1,7 @@ -Define life(pattern) = Prgm - Local x,y,nt,count,save,xl,yl,xh,yh - Define nt(y,x) = when(pxlTest(y,x), 1, 0) - - {}→save - setGraph("Axes", "Off")→save[1] - setGraph("Grid", "Off")→save[2] - setGraph("Labels", "Off")→save[3] - FnOff - PlotOff - ClrDraw - - If pattern = "blinker" Then - 36→yl - 40→yh - 78→xl - 82→xh - PxlOn 36,80 - PxlOn 38,80 - PxlOn 40,80 - ElseIf pattern = "glider" Then - 30→yl - 40→yh - 76→xl - 88→xh - PxlOn 38,76 - PxlOn 36,78 - PxlOn 36,80 - PxlOn 38,80 - PxlOn 40,80 - ElseIf pattern = "r" Then - 38-5*2→yl - 38+5*2→yh - 80-5*2→xl - 80+5*2→xh - PxlOn 38,78 - PxlOn 36,82 - PxlOn 36,80 - PxlOn 38,80 - PxlOn 40,80 - EndIf - - While getKey() = 0 - © Expand upper-left corner to whole cell - For y,yl,yh,2 - For x,xl,xh,2 - If pxlTest(y,x) Then - PxlOn y+1,x - PxlOn y+1,x+1 - PxlOn y, x+1 - Else - PxlOff y+1,x - PxlOff y+1,x+1 - PxlOff y, x+1 - EndIf - EndFor - EndFor - - © Compute next generation - For y,yl,yh,2 - For x,xl,xh,2 - nt(y-1,x-1) + nt(y-1,x) + nt(y-1,x+2) + nt(y,x-1) + nt(y+1,x+2) + nt(y+2,x-1) + nt(y+2,x+1) + nt(y+2,x+2) → count - If count = 3 Then - PxlOn y,x - ElseIf count ≠ 2 Then - PxlOff y,x - EndIf - EndFor - EndFor - EndWhile - - © Restore changed options - setGraph("Axes", save[1]) - setGraph("Grid", save[2]) - setGraph("Labels", save[3]) -EndPrgm +10 DIM L$(16,16) +20 FOR I=1 TO 16 +30 FOR J=1 TO 16 +40 LET L$(I,J)="0" +50 IF RND>=.7 THEN LET L$(I,J)="1" +60 NEXT J +70 NEXT I diff --git a/Task/Conways-Game-of-Life/TI-83-BASIC/conways-game-of-life-1.ti-83 b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-11.basic similarity index 100% rename from Task/Conways-Game-of-Life/TI-83-BASIC/conways-game-of-life-1.ti-83 rename to Task/Conways-Game-of-Life/BASIC/conways-game-of-life-11.basic diff --git a/Task/Conways-Game-of-Life/TI-83-BASIC/conways-game-of-life-2.ti-83 b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-12.basic similarity index 100% rename from Task/Conways-Game-of-Life/TI-83-BASIC/conways-game-of-life-2.ti-83 rename to Task/Conways-Game-of-Life/BASIC/conways-game-of-life-12.basic diff --git a/Task/Conways-Game-of-Life/TI-89-BASIC/conways-game-of-life.ti-89 b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-13.basic similarity index 100% rename from Task/Conways-Game-of-Life/TI-89-BASIC/conways-game-of-life.ti-89 rename to Task/Conways-Game-of-Life/BASIC/conways-game-of-life-13.basic diff --git a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-8.basic b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-8.basic index 00c941336f..3ad62cef3b 100644 --- a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-8.basic +++ b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-8.basic @@ -1,21 +1,37 @@ - PROGRAM:CONWAY -:While 1 -:For(X,2,9,1) -:For(Y,2,17,1) -:If [A](Y,X) -:Then -:Output(X-1,Y-1,"X") -:Else -:Output(X-1,Y-1," ") -:End -:[A](Y-1,X-1)+[A](Y,X-1)+[A](Y+1,X-1)+[A](Y-1,X)+[A](Y+1,X)+[A](Y-1,X+1)+[A](Y,X+1)+[A](Y+1,X+1)→N -:If ([A](Y,X) and (N=2 or N=3)) or (not([A](Y,X)) and N=3) -:Then -:1→[B](Y,X) -:Else -:0→[B](Y,X) -:End -:End -:End -:[B]→[A] -:End +1000 LET M=LEN L$(1) +1010 DIM N$(M,M) +1020 FOR I=0 TO M+1 +1030 PRINT AT I,0;"▩" +1040 PRINT AT I,M+1;"▩" +1050 PRINT AT 0,I;"▩" +1060 PRINT AT M+1,I;"▩" +1070 NEXT I +1080 LET G=0 +1090 PRINT AT 1,M+3;G +1100 FOR I=1 TO M +1110 FOR J=1 TO M +1120 IF L$(I,J)="0" THEN GOTO 1150 +1130 PRINT AT I,J;"■" +1140 GOTO 1160 +1150 PRINT AT I,J;" " +1160 NEXT J +1170 NEXT I +1180 FOR I=1 TO M +1190 FOR J=1 TO M +1200 LET N=0 +1210 FOR K=I-1 TO I+1 +1220 FOR L=J-1 TO J+1 +1230 IF K=0 OR K>M OR L=0 OR L>M OR (K=I AND L=J) THEN GOTO 1250 +1240 LET N=N+VAL L$(K,L) +1250 NEXT L +1260 NEXT K +1270 LET N$(I,J)=L$(I,J) +1280 IF N<=1 OR N>=4 THEN LET N$(I,J)="0" +1290 IF N=3 THEN LET N$(I,J)="1" +1300 NEXT J +1310 NEXT I +1320 FOR I=1 TO M +1330 LET L$(I)=N$(I) +1340 NEXT I +1350 LET G=G+1 +1360 GOTO 1090 diff --git a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-9.basic b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-9.basic index b6f27a46b2..d7d8684671 100644 --- a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-9.basic +++ b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-9.basic @@ -1,6 +1,4 @@ -PROGRAM:PIC2LIFE -:For(I,0,17,1) -:For(J,0,9,1) -:pxl-Test(J,I)→[A](I+1,J+1) -:End -:End +10 DIM L$(3,3) +20 LET L$(1)="000" +30 LET L$(2)="111" +40 LET L$(3)="000" diff --git a/Task/Conways-Game-of-Life/BASIC256/conways-game-of-life-1.basic256 b/Task/Conways-Game-of-Life/BASIC256/conways-game-of-life-1.basic256 deleted file mode 100644 index f28433510b..0000000000 --- a/Task/Conways-Game-of-Life/BASIC256/conways-game-of-life-1.basic256 +++ /dev/null @@ -1,8 +0,0 @@ -# Conway's_Game_of_Life - -X = 59 : Y = 35 : H = 4 - -fastgraphics -graphsize X*H,Y*H - -dim c(X,Y) : dim cn(X,Y) : dim cl(X,Y) diff --git a/Task/Conways-Game-of-Life/BASIC256/conways-game-of-life-2.basic256 b/Task/Conways-Game-of-Life/BASIC256/conways-game-of-life-2.basic256 deleted file mode 100644 index 408b2663f8..0000000000 --- a/Task/Conways-Game-of-Life/BASIC256/conways-game-of-life-2.basic256 +++ /dev/null @@ -1,64 +0,0 @@ -# Thunderbird methuselah -c[X/2-1,Y/3+1] = 1 : c[X/2,Y/3+1] = 1 : c[X/2+1,Y/3+1] = 1 -c[X/2,Y/3+3] = 1 : c[X/2,Y/3+4] = 1 : c[X/2,Y/3+5] = 1 - -s = 0 -do - color black - rect 0,0,graphwidth,graphheight - alive = 0 : stable = 1 - s = s + 1 - for y = 0 to Y-1 - for x = 0 to X-1 - xm1 = (x-1+X)%X : xp1 = (x+1+X)%X - ym1 = (y-1+Y)%Y : yp1 = (y+1+Y)%Y - cn[x,y] = c[xm1,y] + c[xp1,y] - cn[x,y] = c[xm1,ym1] + c[x,ym1] + c[xp1,ym1] + cn[x,y] - cn[x,y] = c[xm1,yp1] + c[x,yp1] + c[xp1,yp1] + cn[x,y] - if c[x,y] = 1 then - if cn[x,y] < 2 or cn[x,y] > 3 then - cn[x,y] = 0 - else - cn[x,y] = 1 - alive = alive + 1 - end if - else - if cn[x,y] = 3 then - cn[x,y] = 1 - alive = alive + 1 - else - cn[x,y] = 0 - end if - end if - if c[x,y] then - if cn[x,y] then - if cl[x,y] then color purple # adult - if not cl[x,y] then color green # newborn - else - if cl[x,y] then color red # old - if not cl[x,y] then color yellow # shortlived - end if - rect x*H,y*H,H,H - end if - next x - next y - refresh - pause 0.06 - # Copy arrays - for i = 0 to X-1 - for j = 0 to Y-1 - if cl[i,j]<>cn[i,j] then stable = 0 - cl[i,j] = c[i,j] - c[i,j] = cn[i,j] - next j - next i -until not alive or stable - -if not alive then - print "Died in "+s+" iterations" - color black - rect 0,0,graphwidth,graphheight - refresh -else - print "Stabilized in "+(s-2)+" iterations" -end if diff --git a/Task/Conways-Game-of-Life/BBC-BASIC/conways-game-of-life.bbc b/Task/Conways-Game-of-Life/BBC-BASIC/conways-game-of-life.bbc deleted file mode 100644 index 9e2ac60ef1..0000000000 --- a/Task/Conways-Game-of-Life/BBC-BASIC/conways-game-of-life.bbc +++ /dev/null @@ -1,35 +0,0 @@ - dx% = 64 - dy% = 64 - DIM old&(dx%+1,dy%+1), new&(dx%+1,dy%+1) - VDU 23,22,dx%*4;dy%*4;16,16,16,0 - OFF - - REM Set blinker: - old&(50,50) = 1 : old&(50,51) = 1 : old&(50,52) = 1 - REM Set glider: - old&(5,7) = 1 : old&(6,7) = 1 : old&(7,7) = 1 : old&(7,6) = 1 : old&(6,5) = 1 - - REM Draw initial grid: - FOR X% = 1 TO dx% - FOR Y% = 1 TO dy% - IF old&(X%,Y%) GCOL 11 ELSE GCOL 4 - PLOT 69, X%*8-6, Y%*8-4 - NEXT - NEXT X% - - REM Run: - GCOL 4,0 - REPEAT - FOR X% = 1 TO dx% - FOR Y% = 1 TO dy% - S% = old&(X%-1,Y%) + old&(X%,Y%-1) + old&(X%-1,Y%-1) + old&(X%+1,Y%-1) + \ - \ old&(X%+1,Y%) + old&(X%,Y%+1) + old&(X%-1,Y%+1) + old&(X%+1,Y%+1) - O% = old&(X%,Y%) - N% = -(S%=3 OR (O%=1 AND S%=2)) - new&(X%,Y%) = N% - IF N%<>O% PLOT X%*8-6, Y%*8-4 - NEXT - NEXT X% - SWAP old&(), new&() - WAIT 30 - UNTIL FALSE diff --git a/Task/Conways-Game-of-Life/Batch-File/conways-game-of-life.bat b/Task/Conways-Game-of-Life/Batch-File/conways-game-of-life.bat new file mode 100644 index 0000000000..ac53b71c1c --- /dev/null +++ b/Task/Conways-Game-of-Life/Batch-File/conways-game-of-life.bat @@ -0,0 +1,108 @@ +@echo off +setlocal enabledelayedexpansion + +if "%1"=="" ( + call:_blinkerArray +) else ( + call:_randomArray %* +) + +for /l %%i in (1,1,%iterations%) do ( + call:_setStatus + call:_display + + for /l %%m in (1,1,%m%) do ( + for /l %%n in (1,1,%m%) do ( + call:_evolution %%m %%n + ) + ) +) + +:_blinkerArray +for /l %%m in (0,1,4) do ( + for /l %%n in (0,1,4) do ( + set cell[%%m][%%n]=0 + ) +) +set cell[2][1]=1 +set cell[2][2]=1 +set cell[2][3]=1 +set iterations=5 +set m=3 +set cellsaddone=4 + +exit /b + +:_randomArray +set cellsaddone=%1+1 +for /l %%m in (0,1,%cellsaddone%) do for /l %%n in (0,1,%cellsaddone%) do set cell[%%m][%%n]=0 +for /l %%m in (1,1,%1) do ( + for /l %%n in (1,1,%1) do ( + set /a cellrandom=!random! %% 101 + set cell[%%m][%%n]=0 + if !cellrandom! leq %2 set cell[%%m][%%n]=1 + ) +) +set iterations=%3 +set m=%1 + +exit /b + +:_setStatus +for /l %%m in (0,1,%cellsaddone%) do ( + for /l %%n in (0,1,%cellsaddone%) do ( + if !cell[%%m][%%n]!==1 set cellstatus[%%m][%%n]=alive + if !cell[%%m][%%n]!==0 set cellstatus[%%m][%%n]=dead + ) +) +exit /b + + +:_evolution +set /a lowerm=%1-1 +set /a upperm=%1+1 +set /a lowern=%2-1 +set /a uppern=%2+1 +set numm=%1 +set numn=%2 +set sum=0 +for /l %%m in (%lowerm%,1,%upperm%) do ( + for /l %%n in (%lowern%,1,%uppern%) do ( + if %%m==%numm% ( + if %%n==%numn% ( + set /a sum=!sum! + ) else ( + if !cellstatus[%%m][%%n]!==alive set /a sum+=1 + ) + ) else ( + if !cellstatus[%%m][%%n]!==alive set /a sum+=1 + ) + ) +) +goto:!cell[%numm%][%numn%]! + +exit /b + +:0 +set alive=3 +set death=0 1 2 4 5 6 7 8 +for %%i in (%alive%) do if %sum%==%%i set cell[%numm%][%numn%]=1 +for %%i in (%death%) do if %sum%==%%i set cell[%numm%][%numn%]=0 +exit /b + +:1 +set alive=2 3 +set death=0 1 4 5 6 7 8 +for %%i in (%alive%) do if %sum%==%%i set cell[%1][%2]=1 +for %%i in (%death%) do if %sum%==%%i set cell[%1][%2]=0 +exit /b + +:_display +echo. +for /l %%m in (1,1,%m%) do ( + set m%%m= + for /l %%n in (1,1,%m%) do set m%%m=!m%%m! !cell[%%m][%%n]! + echo !m%%m! +) + +exit /b diff --git a/Task/Conways-Game-of-Life/Brat/conways-game-of-life.brat b/Task/Conways-Game-of-Life/Brat/conways-game-of-life.brat new file mode 100644 index 0000000000..313f64ce16 --- /dev/null +++ b/Task/Conways-Game-of-Life/Brat/conways-game-of-life.brat @@ -0,0 +1,61 @@ +width = 3 +height = 3 +rounds = 3 + +universe = [[0 1 0] + [0 1 0] + [0 1 0]] + +next = height.of({width.of(0)}) + +cell = { x, y | + true? x < width && { x >= 0 && { y >= 0 && { y < height }}} + { + universe[y][x] + } + { 0 } +} + +neighbors = { x, y | + cell(x - 1, y - 1) + + cell(x, y - 1) + + cell(x + 1, y - 1) + + cell(x + 1, y) + + cell(x + 1, y + 1) + + cell(x, y + 1) + + cell(x - 1, y + 1) + + cell(x - 1, y) +} + +set_next = { x, y, v | + next[y][x] = v +} + +step = { + universe.each_with_index { row, y | + row.each_with_index { c, x | + n = neighbors(x, y) + + when { n < 2 } { set_next x,y, 0 } + { n > 3 } { set_next x, y, 0 } + { n == 3 } { set_next x, y, 1 } + { true } { set_next x, y, c } + } + } + + u2 = universe + universe = next + next = u2 +} + +display = { + p universe.map({ r | + r.map({ n | true? n == 0, '-', "O" }).join + }).join("\n") +} + +rounds.times { + display + p + step +} diff --git a/Task/Conways-Game-of-Life/C-sharp/conways-game-of-life.cs b/Task/Conways-Game-of-Life/C-sharp/conways-game-of-life.cs deleted file mode 100644 index 8cb5d5ef46..0000000000 --- a/Task/Conways-Game-of-Life/C-sharp/conways-game-of-life.cs +++ /dev/null @@ -1,240 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; - -namespace Game_of_Life -{ - internal static class Program - { - private static void Main() - { - var blinker = new Blinker(); - - for (int i = 0; i < 3; i++) - { - blinker.Print(new Cell(-1, -2), new Cell(4, 4)); - blinker.Step(); - } - - var glider = new Glider(); - - for (int i = 0; i < 3; i++) - { - var top = glider.Top; - var left = glider.Left; - var bottom = glider.Bottom; - var right = glider.Right; - - glider.Print(new Cell(left - 1, top - 1), new Cell(right - left + 2, bottom - top + 2)); - glider.Step(); - } - } - - private static void Print(this CellCollection state, Cell topLeft, Cell size) - { - const char alive = '#'; - const char dead = ' '; - - Console.WriteLine("Generation {0} [({1}, {2}), ({3}, {4})] ({5} live cells)", - state.Generation, - topLeft.X, topLeft.Y, - topLeft.X + size.X, topLeft.Y + size.Y, - state.Count); - - for (int i = topLeft.Y; i <= topLeft.Y + size.Y; i++) - { - for (int o = topLeft.X; o <= topLeft.X + size.X; o++) - { - Console.Write(state.Contains(o, i) ? alive : dead); - } - Console.WriteLine(); - } - - Console.WriteLine("Generated in {0} ms.", state.MillisecondsToGenerate); - } - - private class Blinker : CellCollection - { - public Blinker() - { - Add(0, 0); - Add(1, 0); - Add(2, 0); - } - } - - private class Glider : CellCollection - { - public Glider() - { - Add(1, 0); - Add(2, 1); - Add(0, 2); - Add(1, 2); - Add(2, 2); - } - } - - private class CellCollection : List - { - public CellCollection(IEnumerable cells) - : this() - { - foreach (var cell in cells) - Add(cell); - } - - public CellCollection() - { - Generation = 0; - _stopwatch = new Stopwatch(); - } - - // Returns the amount of neighboring cells that are alive. - private byte GetAliveNeighborsCount(int x, int y) - { - byte neighbors = 0; - for (int i = -1; i <= 1; i++) - { - for (int o = -1; o <= 1; o++) - { - if (i == 0 && o == 0) - continue; - if (Contains(x + i, y + o)) - neighbors++; - } - } - return neighbors; - } - - // Returns all neighboring cells. - private IEnumerable GetNeighbors(int x, int y) - { - for (int i = -1; i <= 1; i++) - { - for (int o = -1; o <= 1; o++) - { - if (i == 0 && o == 0) - continue; - - yield return new Cell(x + o, y + i); - } - } - } - - // Steps forward the specified amount of generations. - public void Step(uint steps = 1) - { - _stopwatch.Restart(); - - for (uint step = 0; step < steps; step++) - { - Generation++; - - // Variable to act as a snapshot of the current state while we make changes. - var oldState = new CellCollection(this); - - // Variable to hold the cells that we will check. - var checkCells = new List(oldState); - - // Adds all dead cells neighboring alive cells to the cells that we will check. - checkCells.AddRange( - from cell in oldState - from neighbor in GetNeighbors(cell.X, cell.Y) - where !checkCells.Contains(neighbor) - select neighbor); - - foreach (var cell in checkCells) - { - byte neighbors = oldState.GetAliveNeighborsCount(cell.X, cell.Y); - - /* - * Checks if the current cell is alive or not. - * - * If so, if the cell has less than 2, or more than 3 alive neighbors, - * the cell will be killed. - * - * If not, if the cell has 3 alive neighbors, the cell will be brought to life. - */ - if (oldState.Contains(cell.X, cell.Y)) - { - if (neighbors < 2 || neighbors > 3) - Remove(cell); - } - else - { - if (neighbors == 3) - Add(cell); - } - } - } - - _stopwatch.Stop(); - } - - public void Add(int x, int y) - { - Add(new Cell(x, y)); - } - - public bool Contains(int x, int y) - { - return Contains(new Cell(x, y)); - } - - public int Top - { - get { return (from cell in this orderby cell.Y ascending select cell.Y).First(); } - } - - public int Bottom - { - get { return (from cell in this orderby cell.Y descending select cell.Y).First(); } - } - - public int Left - { - get { return (from cell in this orderby cell.X ascending select cell.X).First(); } - } - - public int Right - { - get { return (from cell in this orderby cell.X descending select cell.X).First(); } - } - - public uint Generation { get; private set; } - public long MillisecondsToGenerate { get { return _stopwatch.ElapsedMilliseconds; } } - - private readonly Stopwatch _stopwatch; - } - - private struct Cell : IEquatable - { - public Cell(int x, int y) - { - _x = x; - _y = y; - } - - private readonly int _x; - - public int X - { - get { return _x; } - } - - private readonly int _y; - - public int Y - { - get { return _y; } - } - - public bool Equals(Cell other) - { - return (X == other.X && Y == other.Y); - } - } - } -} diff --git a/Task/Conways-Game-of-Life/EC/conways-game-of-life.ec b/Task/Conways-Game-of-Life/EC/conways-game-of-life.ec new file mode 100644 index 0000000000..46698764d1 --- /dev/null +++ b/Task/Conways-Game-of-Life/EC/conways-game-of-life.ec @@ -0,0 +1,95 @@ +import "ecere" + +define seed = 12345; +define popInit = 1000; +define width = 100; +define height = 100; +define cellWidth = 4; +define cellHeight = 4; + +Array grid { size = width * height }; +Array newState { size = width * height }; + +class GameOfLife : Window +{ + caption = $"Conway's Game of Life"; + background = lightBlue; + borderStyle = sizable; + hasMaximize = true; + hasMinimize = true; + hasClose = true; + clientSize = { width * cellWidth, height * cellHeight }; + + Timer tickTimer + { + delay = 0.05, started = true, userData = this; + + bool DelayExpired() + { + int y, x, ix = 0; + for(y = 0; y < height; y++) + { + for(x = 0; x < width; x++, ix++) + { + int nCount = 0; + byte alive; + if(x > 0 && y > 0 && grid[ix - width - 1]) nCount++; + if( y > 0 && grid[ix - width ]) nCount++; + if(x < width-1 && y > 0 && grid[ix - width + 1]) nCount++; + if(x > 0 && grid[ix - 1]) nCount++; + if(x < width - 1 && grid[ix + 1]) nCount++; + if(x > 0 && y < height-1 && grid[ix + width - 1]) nCount++; + if( y < height-1 && grid[ix + width ]) nCount++; + if(x < width-1 && y < height-1 && grid[ix + width + 1]) nCount++; + + if(grid[ix]) + alive = nCount >= 2 && nCount <= 3; // Death + else + alive = nCount == 3; // Birth + newState[ix] = alive; + } + } + memcpy(grid.array, newState.array, width * height); + Update(null); + return true; + } + }; + + void OnRedraw(Surface surface) + { + int x, y; + int ix = 0; + + surface.background = navy; + for(y = 0; y < height; y++) + { + for(x = 0; x < width; x++, ix++) + { + if(grid[ix]) + { + int sy = y * cellHeight; + int sx = x * cellWidth; + surface.Area(sx, sy, sx + cellWidth-1, sy + cellHeight-1); + } + } + } + } + + bool OnCreate() + { + int i; + + RandomSeed(seed); + + for(i = 0; i < popInit; i++) + { + int x = GetRandom(0, width-1); + int y = GetRandom(0, height-1); + + grid[y * width + x] = 1; + } + return true; + } +} + +GameOfLife life {}; diff --git a/Task/Conways-Game-of-Life/ERRE/conways-game-of-life.erre b/Task/Conways-Game-of-Life/ERRE/conways-game-of-life.erre new file mode 100644 index 0000000000..b4fc360387 --- /dev/null +++ b/Task/Conways-Game-of-Life/ERRE/conways-game-of-life.erre @@ -0,0 +1,72 @@ +PROGRAM LIFE + +!$INTEGER + +!$KEY +!for C-64 compatibility + +CONST Xmax=38,Ymax=20 + +DIM x,y,N +DIM WORLD[39,21],NextWORLD[39,21] + +BEGIN + +! Glider test +!------------------------------------------ +WORLD[1,1]=1 WORLD[1,2]=0 WORLD[1,3]=0 +WORLD[2,1]=0 WORLD[2,2]=1 WORLD[2,3]=1 +WORLD[3,1]=1 WORLD[3,2]=1 WORLD[3,3]=0 +!------------------------------------------ + +PRINT(CHR$(12);"Press any key to interrupt") +LOOP + PRINT(CHR$(11);) PRINT + PRINT(STRING$(Xmax+2,"-")) + !---------- endless world --------- + FOR y=1 TO Ymax DO + WORLD[0,y]=WORLD[Xmax,y] + WORLD[Xmax+1,y]=WORLD[1,y] + END FOR + FOR x=1 TO Xmax DO + WORLD[x,0]=WORLD[x,Ymax] + WORLD[x,Ymax+1]=WORLD[x,1] + END FOR + WORLD[0,0]=WORLD[Xmax,Ymax] + WORLD[Xmax+1,Ymax+1]=WORLD[1,1] + WORLD[Xmax+1,0]=WORLD[1,Ymax] + WORLD[0,Ymax+1]=WORLD[Xmax,1] + !---------- endless world --------- + FOR y=1 TO Ymax DO + PRINT("|";) + FOR x=1 TO Xmax DO + PRINT(CHR$(32+WORLD[x,y]*3);) + N=WORLD[x-1,y-1]+WORLD[x-1,y]+WORLD[x-1,y+1]+WORLD[x,y-1] + N=N+WORLD[x,y+1]+WORLD[x+1,y-1]+WORLD[x+1,y]+WORLD[x+1,y+1] + IF (WORLD[x,y]<>0 AND (N=2 OR N=3)) OR (WORLD[x,y]=0 AND N=3) THEN + NextWORLD[x,y]=1 + ELSE + NextWORLD[x,y]=0 + END IF + END FOR + PRINT("|") + END FOR + PRINT(STRING$(Xmax+2,"-")) + PAUSE(0.1) + + FOR x=0 TO Xmax+1 DO + FOR y=0 TO Ymax+1 DO + WORLD[x,y]=NextWORLD[x,y] + NextWORLD[x,y]=0 + END FOR + END FOR + REPEAT + GET(A$) + UNTIL A$<>"" + EXIT IF A$=CHR$(27) +END LOOP + +PRINT("Press any key to exit") +REPEAT +UNTIL GETKEY$<>"" +END PROGRAM diff --git a/Task/Conways-Game-of-Life/Elena/conways-game-of-life.elena b/Task/Conways-Game-of-Life/Elena/conways-game-of-life.elena new file mode 100644 index 0000000000..293195b1f9 --- /dev/null +++ b/Task/Conways-Game-of-Life/Elena/conways-game-of-life.elena @@ -0,0 +1,133 @@ +import extensions. +import cellular. +import system'routines. +import system'threading. +import system'text. + +const int maxX = 48. +const int maxY = 28. + +type listener_func = ListenerFunc. + +limited class ListenerFunc :: dispatchable +{ + action eval space:space [] +} + +sealed class Model +{ + space theSpace. + ruleset theRuleSet. + bool started. + + listener_func event onUpdate :: theListener. + + constructor newRandomset ruleset:transformSet + [ + theSpace := IntMatrixSpace new int:maxY int:maxX ruleset:randomSet. + + theRuleSet := transformSet. + + started := false. + ] + + constructor newLoaded ruleset:initSet ruleset:transformSet + [ + theSpace := IntMatrixSpace new int:maxY int:maxX ruleset:initSet. + + theRuleSet := transformSet. + + started := false. + ] + + $onUpdate + [ + if ($nil != theListener) + [ theListener eval space:theSpace ]. + ] + + init + [ + $self $onUpdate. + ] + + run + [ + if (started) + [ theSpace update ruleset:theRuleSet. ]; + [ started := true. ]. + + $self $onUpdate. + ] +} + +const int DELAY = 50. + +symbol testSet = ((0,1,0), + (0,1,0), + (0,1,0)). + +class gameOfLifeRuleSet = BaseRuleSet:: +{ + validate space:s int:x int:y + [ + int cell := s getAt int:x int:y. + int number := s getLiveCell int:x int:y. // NOTE : number of living cells around the self includes the cell itself + + if ((cell == 0) && (number == 3)) + [ ^ true. ]. + + if ((cell == 1) && ((number == 4) || (number == 3))) + [ ^ true. ]. + + ^ false. + ] +}. + +extension space presenterOp +{ + print + [ + console setCursorPosition int:0 int:0. + + int columns := self columns. + int rows := self rows. + + int i := 0. + int j := 0. + while (i < rows) + [ + j := 0. + + while (j < columns) + [ + int cell := self getAt int:i int:j. + + console write((cell == 0)iif(" ","o")). + + j := j + 1. + ]. + + i := i + 1. + console writeLine. + ]. + ] +} + +program = +[ + console clear. + + var model := Model newRandomset ruleset:gameOfLifeRuleSet. + + model onUpdate listener_func(&space:sp)[ sp print ]. + + until (console isKeyAvailable) + [ + model run. + + thread sleep:DELAY. + ]. + + console readChar. +]. diff --git a/Task/Conways-Game-of-Life/Java/conways-game-of-life-3.java b/Task/Conways-Game-of-Life/Java/conways-game-of-life-3.java deleted file mode 100644 index deb39dc6bb..0000000000 --- a/Task/Conways-Game-of-Life/Java/conways-game-of-life-3.java +++ /dev/null @@ -1,277 +0,0 @@ -import java.awt.*; -import java.awt.event.*; -import java.net.URI; -import java.util.ArrayList; -import java.util.ConcurrentModificationException; -import javax.swing.*; - -public class ConwaysGameOfLife extends JFrame implements ActionListener { - private static final Dimension DEFAULT_WINDOW_SIZE = new Dimension(800, 600); - private static final Dimension MINIMUM_WINDOW_SIZE = new Dimension(400, 400); - private static final int BLOCK_SIZE = 10; - private static final int SCREEN_WIDTH = Toolkit.getDefaultToolkit().getScreenSize().width; - private static final int SCREEN_HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().height; - private JMenuBar mb_menu; - private JMenu m_file, m_game; - private JMenuItem mi_file_options, mi_file_exit, mi_game_autofill, mi_game_play, mi_game_stop, mi_game_reset; - private int i_movesPerSecond = 3; - private GameBoard gb_gameBoard; - private Thread game; - - public static void main(String[] args) { - JFrame game = new ConwaysGameOfLife(); - game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - game.setTitle("Conway's Game of Life"); - game.setSize(DEFAULT_WINDOW_SIZE); - game.setMinimumSize(MINIMUM_WINDOW_SIZE); - game.setLocation((SCREEN_WIDTH - game.getWidth())/2, (SCREEN_HEIGHT - game.getHeight())/2); - game.setVisible(true); - } - - public ConwaysGameOfLife() { - mb_menu = new JMenuBar(); - setJMenuBar(mb_menu); - m_file = new JMenu("File"); - mb_menu.add(m_file); - m_game = new JMenu("Game"); - mb_menu.add(m_game); - mi_file_options = new JMenuItem("Options"); - mi_file_options.addActionListener(this); - mi_file_exit = new JMenuItem("Exit"); - mi_file_exit.addActionListener(this); - m_file.add(mi_file_options); - m_file.add(new JSeparator()); - m_file.add(mi_file_exit); - mi_game_autofill = new JMenuItem("Autofill"); - mi_game_autofill.addActionListener(this); - mi_game_play = new JMenuItem("Play"); - mi_game_play.addActionListener(this); - mi_game_stop = new JMenuItem("Stop"); - mi_game_stop.setEnabled(false); - mi_game_stop.addActionListener(this); - mi_game_reset = new JMenuItem("Reset"); - mi_game_reset.addActionListener(this); - m_game.add(mi_game_autofill); - m_game.add(new JSeparator()); - m_game.add(mi_game_play); - m_game.add(mi_game_stop); - m_game.add(mi_game_reset); - gb_gameBoard = new GameBoard(); - add(gb_gameBoard); - } - - public void setGameBeingPlayed(boolean isBeingPlayed) { - if (isBeingPlayed) { - mi_game_play.setEnabled(false); - mi_game_stop.setEnabled(true); - game = new Thread(gb_gameBoard); - game.start(); - } else { - mi_game_play.setEnabled(true); - mi_game_stop.setEnabled(false); - game.interrupt(); - } - } - - @Override - public void actionPerformed(ActionEvent ae) { - if (ae.getSource().equals(mi_file_exit)) { - System.exit(0); - } else if (ae.getSource().equals(mi_file_options)) { - final JFrame f_options = new JFrame(); - f_options.setTitle("Options"); - f_options.setSize(300,60); - f_options.setLocation((SCREEN_WIDTH - f_options.getWidth())/2, (SCREEN_HEIGHT - f_options.getHeight())/2); - f_options.setResizable(false); - JPanel p_options = new JPanel(); - p_options.setOpaque(false); - f_options.add(p_options); - p_options.add(new JLabel("Number of moves per second:")); - Integer[] secondOptions = {1,2,3,4,5,10,15,20}; - final JComboBox cb_seconds = new JComboBox(secondOptions); - p_options.add(cb_seconds); - cb_seconds.setSelectedItem(i_movesPerSecond); - cb_seconds.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent ae) { - i_movesPerSecond = (Integer)cb_seconds.getSelectedItem(); - f_options.dispose(); - } - }); - f_options.setVisible(true); - } else if (ae.getSource().equals(mi_game_autofill)) { - final JFrame f_autoFill = new JFrame(); - f_autoFill.setTitle("Autofill"); - f_autoFill.setSize(360, 60); - f_autoFill.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - f_autoFill.getWidth())/2, - (Toolkit.getDefaultToolkit().getScreenSize().height - f_autoFill.getHeight())/2); - f_autoFill.setResizable(false); - JPanel p_autoFill = new JPanel(); - p_autoFill.setOpaque(false); - f_autoFill.add(p_autoFill); - p_autoFill.add(new JLabel("What percentage should be filled? ")); - Object[] percentageOptions = {"Select",5,10,15,20,25,30,40,50,60,70,80,90,95}; - final JComboBox cb_percent = new JComboBox(percentageOptions); - p_autoFill.add(cb_percent); - cb_percent.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (cb_percent.getSelectedIndex() > 0) { - gb_gameBoard.resetBoard(); - gb_gameBoard.randomlyFillBoard((Integer)cb_percent.getSelectedItem()); - f_autoFill.dispose(); - } - } - }); - f_autoFill.setVisible(true); - } else if (ae.getSource().equals(mi_game_reset)) { - gb_gameBoard.resetBoard(); - gb_gameBoard.repaint(); - } else if (ae.getSource().equals(mi_game_play)) { - setGameBeingPlayed(true); - } else if (ae.getSource().equals(mi_game_stop)) { - setGameBeingPlayed(false); - } - } - - private class GameBoard extends JPanel implements ComponentListener, MouseListener, MouseMotionListener, Runnable { - private Dimension d_gameBoardSize = null; - private ArrayList point = new ArrayList(0); - - public GameBoard() { - addComponentListener(this); - addMouseListener(this); - addMouseMotionListener(this); - } - - private void updateArraySize() { - ArrayList removeList = new ArrayList(0); - for (Point current : point) { - if ((current.x > d_gameBoardSize.width-1) || (current.y > d_gameBoardSize.height-1)) { - removeList.add(current); - } - } - point.removeAll(removeList); - repaint(); - } - - public void addPoint(int x, int y) { - if (!point.contains(new Point(x,y))) { - point.add(new Point(x,y)); - } - repaint(); - } - - public void addPoint(MouseEvent me) { - int x = me.getPoint().x/10-1; - int y = me.getPoint().y/10-1; - if ((x >= 0) && (x < d_gameBoardSize.width) && (y >= 0) && (y < d_gameBoardSize.height)) { - addPoint(x,y); - } - } - - public void removePoint(int x, int y) { - point.remove(new Point(x,y)); - } - - public void resetBoard() { - point.clear(); - } - - public void randomlyFillBoard(int percent) { - for (int i=0; i survivingCells = new ArrayList(0); - for (int i=1; i0 then #w "color red" else #w "color darkgray" - #w "set "; x *mult +20; " "; y *mult +20 - next y - next x -' ______________________________________________________________________________ -'Run - do - for x =1 to gridX - for y =1 to gridY - 'find number of live Moore neighbours - neighbours =old( x -1, y -1) +old( x, y -1) +old( x +1, y -1)+_ - old( x -1, y) +old( x +1, y )+_ - old( x -1, y +1) +old( x, y +1) +old( x +1, y +1) - was =old( x, y) - if was =0 then - if neighbours =3 then N =1 else N =0 - else - if neighbours =3 or neighbours =2 then N =1 else N =0 - end if - new( x, y) = N - '#w "color "; int( N /8 *256); " 0 255" - if N <>0 then #w "color red" else #w "color darkgray" - #w "set "; x *mult +20; " "; y *mult +20 - next y - next x - scan -'swap - for x =1 to gridX - for y =1 to gridY - old( x, y) =new( x, y) - next y - next x -'Re-run until interrupted... - loop until FALSE -'User shutdown received - [quit] - close #w - end diff --git a/Task/Conways-Game-of-Life/OoRexx/conways-game-of-life.rexx b/Task/Conways-Game-of-Life/OoRexx/conways-game-of-life.rexx new file mode 100644 index 0000000000..0551611a30 --- /dev/null +++ b/Task/Conways-Game-of-Life/OoRexx/conways-game-of-life.rexx @@ -0,0 +1,443 @@ +/* REXX --------------------------------------------------------------- +* 07.08.2014 Walter Pachl Conway's Game of life graphical +* Input is a file containing the initial pattern. +* The compute area is extended when needed +* (i.e., when cells are born outside the current compute area) +* When computing the pattern sequence is complete, the graphical +* output starts and continues until Cancel is pressed. +* 10.08.2014 WP fixed the output of what.txt +*--------------------------------------------------------------------*/ + Parse Arg what speed + If what='?' Then Do + Say 'Create a file containing the pattern to be processed' + Say 'named somename.in (octagon.in such as this for the octagon):' + Say ' ** ' + Say ' * * ' + Say ' * * ' + Say '* *' + Say '* *' + Say ' * * ' + Say ' * * ' + Say ' ** ' + Say 'Run the program by entering "rexx conlife somename [pause]"', + 'on the command line.' + Say '(pause is the amount of milliseconds between 2 pictures.', + 'default is 1000)' + Say 'A file somename.lst will be created.' + Say 'Hereafter you will see the pattern''s development', + 'in a new window.' + Say 'Press the Cancel button to end the presentation.' + Exit + End + Parse Version interpreter '_' level '(' + If interpreter<>'REXX-ooRexx' Then Do + Say interpreter level + Say 'This program must be run with object Rexx.' + Exit + End + If what='' Then what='octagon' + If right(what,3)='.in' then + what=left(what,length(what)-3) + infile=what'.in' + If lines(infile)=0 Then Do + Say 'Input file' infile 'not found.' + Say 'Enter conlife ? for help.' + Exit + End + If speed='' Then + speed=1000 + .local~myspeed=speed + + Call tl what + --'type' what'.lst' + + .local~title=what + array=.local~myarrayData + d = .drawDlg~new + if d~initCode <> 0 then do + say 'The Draw dialog was not created correctly. Aborting.' + return d~initCode + end + d~execute("SHOWTOP") + return 0 + +::requires "ooDialog.cls" + +::class 'drawDlg' subclass UserDialog + +::attribute interrupted unguarded + +::method init + expose walterFont + + forward class (super) continue + -- colornames: + -- 1 dark red 7 light grey 13 red + -- 2 dark green 8 pale green 14 light green + -- 3 dark yellow 9 light blue 15 yellow + -- 4 dark blue 10 white 16 blue + -- 5 purple 11 grey 17 pink + -- 6 blue grey 12 dark grey 18 turquoise + + self~interrupted = .true + + -- Create a font to write the nice big letters and digits + opts = .directory~new + opts~weight = 700 + walterFont = self~createFontEx("Arial",14,opts) + walterFont = self~createFontEx("Courier",18,opts) + + if \self~createcenter(200, 235,"Walter's Clock", , ,"System",14) then + self~initCode = 1 + +::method defineDialog + + self~createPushButton(/*IDC_PB_DRAW*/100, 0, 0,240,200,"DISABLED NOTAB") -- The drawing surface. + + self~createPushButton(IDCANCEL,160,220, 35, 12,,"&Cancel") + +::method initDialog unguarded + expose x y dc myPen change al. fid nn what array + change = 0 + x = self~factorx + y = self~factory + dc = self~getButtonDC(100) + myPen = self~createPen(1,'solid',0) + t = .TimeSpan~fromMicroSeconds(500000) -- .5 seconds + msg = .Message~new(self,'life') + alrm = .Alarm~new(t, msg) + array=.local~myArrayData + Do s=1 to array~items + al.s=array[s] + Parse Var al.s ' == ' al.s + End + nn=s-2 + --say 'nn'nn + Call lineout fid + +::method interrupt unguarded + + self~interrupted = .true + +::method cancel unguarded -- Stop the drawing program and quit. + expose x y + self~hide + self~interrupted = .true + return self~cancel:super + +::method leaving unguarded -- Best place to clean up resources + expose dc myPen walterFont + + self~deleteObject(myPen) + self~freeButtonDC(/*IDC_PB_DRAW*/100,dc) + self~deleteFont(walterFont) + +::method life unguarded /* draw individual pixels */ + expose x y dc myPen change walterFont al. nn what + mx = trunc(20*x); my = trunc(20*y); size = 400 + + curPen = self~objectToDC(dc, myPen) + + -- Select the nice big letters and digits into the device context to use to + -- to write with: + curFont = self~fontToDC(dc, walterFont) + + -- Create a white brush and select it into the device to paint with. + whiteBrush = self~createBrush(10) + curBrush = self~objectToDC(dc, whiteBrush) + + -- Paint the drawing area surface with the white brush + self~rectangle(dc, 1, 1, 500, 600, 'FILL') + self~writeDirect(dc, 10, 20,'Conway''s Game of Life') + self~writeDirect(dc, 10, 40,.local~title) + self~writeDirect(dc, 10,460,'Walter Pachl, 8 Aug 2014') + dx=.local~dxval + dy=.local~dyval + do s=1 By 1 until self~interrupted + self~transparentText(dc) + self~interrupted = .false + sm=s//nn+1 + If s>1 Then Do + ali=al.sb + Do While ali<>'' + Parse Var ali x ',' y ali + zxa=(x+dx)*10 + zya=(y+dy)*10 + self~draw_square(dc,zxa,zya,3,10) + End + End + self~draw_square(dc, 380, 10,100,10) + self~writeDirect(dc, 340, 20,time()) + self~writeDirect(dc, 340, 40,right(sm,2) 'of' right(nn,2)) + ali=al.sm + Do While ali<>'' + Parse Var ali x ',' y ali + zxa=(x+dx)*10 + zya=(y+dy)*10 + self~draw_square(dc,zxa,zya,3,5) + End + -- self~interrupted = .true + sb=sm + self~objectToDC(dc, curPen) + self~objectToDC(dc, curBrush) + call msSleep .local~myspeed + --self~pause + End + +::method pause + j = msSleep(10) + +::method draw_square + Use Arg dc, x, y, d, c + Do zx=x-d to x+d + Do zy=y-d to y+d + self~drawPixel(dc, zx, zy, c) + End + End + +::method quot + Parse Arg x,y + If y=0 Then Return '???' + Else Return x/y + +::routine tl +/* REXX --------------------------------------------------------------- +* 02.08.2014 Walter Pachl +* Input is a file containing the initial pattern +* The compute area is extended when needed +* (cells are born outside the current compute area) +* The program stops when the picture shown is the same as the first +* or equal to the previous one +*--------------------------------------------------------------------*/ +Parse Arg f +If f='' Then f='bipole' +fid=f'.in' +oid=f'.txt'; 'erase' oid +oil=f'.lst'; 'erase' oil +debug=0 +If debug Then Do + dbg=f'.xxx'; 'erase' dbg + End +ml=0 +l.='' +ol.='' +Parse Value '10 10' With xb yb +xc=copies(' ',xb) +Do ri=yb+1 By 1 While lines(fid)>0 + l.ri=xc||linein(fid) + ml=max(ml,length(strip(l.ri,'T'))) + End +ri=ri-1 +ml=ml+xb +ri=ri+yb +yy=ri +a.=' ' +b.=' ' +m.='' +x.='' +list.='' +Parse Value 1 ml 1 yy With xmi xma ymi yma +Parse Value '-10 30 -10 30' With xmi xma ymi yma +Parse Value '999 -999 999 -999 999 -999 999 -999', + With xmin xmax ymin ymax xlo xhi ylo yhi +Do y=1 To yy + z=yy-y+1 + l=l.z + Do x=1 By 1 While l<>'' + Parse Var l c +1 l + If c='*' Then + a.x.z='*' + End + End +Call show +Do step=1 To 60 + Call store + If step>1 & is_equal(step,1) Then Leave + If step>1 & is_equal(step,step-1) Then Leave + Call show_neighbors + Do y=yma To ymi By -1 + ol=format(x,3)' ' + Do x=xmi To xma + neighbors=neighbors(x,y) + If a.x.y=' ' Then Do /* dead cell */ + If neighbors=3 Then Do + b.x.y='*' /* gets life */ + mmo=xmi xma ymi yma + xmi=min(xmi,x-1) + xma=max(xma,x+1) + ymi=min(ymi,y-1) + yma=max(yma,y+1) + mm=xmi xma ymi yma + If mm<>mmo Then + Call debug mmo '1->' mm + End + Else /* life cell */ + b.x.y=' ' /* remains dead */ + End + Else Do /* life cell */ + If neighbors=2 |, + neighbors=3 Then Do + b.x.y='*' /* remains life */ + mmo=xmi xma ymi yma + xmi=min(xmi,x-1) + xma=max(xma,x+1) + ymi=min(ymi,y-1) + yma=max(yma,y+1) + mm=xmi xma ymi yma + If mm<>mmo Then + Call debug mmo '2->' mm + End + Else + b.x.y=' ' /* dies */ + End + End + End + /* b. is the new state and is now copied to a. */ + Do y=yma To ymi By -1 + Do x=xmi To xma + a.x.y=b.x.y + End + End + End +/* Output name and all states */ +Call lineout oid,' 'f +st=' +' /* top and bottom border */ +sb=' +' /* top and bottom border */ +Do s=1 To step + st=st||'-'right(s,2,'-')||copies('-',xmax-xmin-2)'+' + sb=sb||copies('-',xmax-xmin+1)'+' + End +array=.array~new +Do y=ymin To ymax + Do s=1 To step + Do x=xmin To xmax + If substr(m.s.y,x,1)='*' Then Do + xlo=min(xlo,x) + xhi=max(xhi,x) + ylo=min(ylo,y) + yhi=max(yhi,y) + End + End + End + End +Do y=ymin To ymax + ol='' + Do s=1 To step + Do x=xmin To xmax + If substr(m.s.y,x,1)='*' Then Do + list.s=list.s (x-xlo+1)','||(y-ylo+1) + End + End + array[s]=s '-' words(list.s) '==' list.s + End + --Call lineout oid,ol '|' + .local~myArrayData=array + End +height=yhi-ylo+1 +width=xhi-xlo+1 +.local~dxval=(48-width)%2 +.local~dyval=(48-height)%2 +Call o st /* top border */ +xl.='|' +Do y=ymax To ymin By -1 + Do s=1 To step + xl.y=xl.y||substr(ol.s.y,xmin,xmax-xmin+1)'|' + End + End +Do y=ymax To ymin By -1 + Call o ' 'xl.y + End +Call o sb /* bottom border */ +Call lineout oid +Say 'frames are shown in' oid +If debug Then Do + Say 'original area' 1 ml '/' 1 yy + Say 'compute area ' xmi xma '/' ymi yma + Say 'used area ' xlo xhi '/' ylo yhi + End +Do s=1 To step + call lineout oil,s '==>' words(list.s) '==' list.s + End +Return + +o: Parse Arg lili + Call lineout oid,lili + Return + +set: Parse Arg x,y + a.x.y='*' + Return + +neighbors: Procedure Expose a. debug + Parse Arg x,y + neighbors=0 + do xa=x-1 to x+1 + do ya=y-1 to y+1 + If xa<>x | ya<>y then + If a.xa.ya='*' Then + neighbors=neighbors+1 + End + End + Return neighbors + +store: +/* store current state (a.) in lines m.step.* */ +Do y=yma To ymi By -1 + ol='' + Do x=xmi To xma + z=a.x.y + ol=ol||z + End + x.step.y=ol + If ol<>'' then Do + ymin=min(ymin,y) + ymax=max(ymax,y) + p=pos('*',ol) + q=length(strip(ol,'T')) + If p>0 Then + xmin=min(xmin,p) + xmax=max(xmax,q) + End + m.step.y=ol + ol.step.y=ol + --If pos('*',ol)>0 Then Do + -- Say '====>' right(step,2) right(y,3) '>'ol'<' xmin xmax + -- Say ' 'copies('1234567890',3) + -- End + End +Return + +is_equal: +/* test ist state a.b is equal to state a.a */ + Parse Arg a,b + Do y=yy To 1 By -1 + If x.b.y<>x.a.y Then + Return 0 + End + Return 1 + +show: Procedure Expose dbg a. yy ml debug +Do y=-5 To 13 + ol='>' + Do x=-5 To 13 + ol=ol||a.x.y + End + Call debug ol + End +Return + +show_neighbors: Procedure Expose a. xmi xma ymi yma dbg debug + Do y=yma To ymi By -1 + ol=format(y,3)' ' + Do x=xmi To xma + ol=ol||neighbors(x,y) + End + Call debug ol + End + Return + +debug: + If debug Then + Return lineout(dbg,arg(1)) + Else + Return diff --git a/Task/Conways-Game-of-Life/Perl-6/conways-game-of-life-1.pl6 b/Task/Conways-Game-of-Life/Perl-6/conways-game-of-life-1.pl6 deleted file mode 100644 index cb3d1ce090..0000000000 --- a/Task/Conways-Game-of-Life/Perl-6/conways-game-of-life-1.pl6 +++ /dev/null @@ -1,47 +0,0 @@ -class Grid { - has Int $.width; - has Int $.height; - has @!a; - - multi method new (@a) { - # Makes a new grid with @!a equal to @a. - Grid.bless(*, - width => @a[0].elems, height => @a.elems, - a => @a) - } - - multi method new (Str $s) { - # Interprets the string as a grid. - Grid.new(map - { [map { $^c eq '#' ?? True !! False }, split '', $^l] }, - grep /\N/, split "\n", $s) - } - - method clone { Grid.new(map { [$^x.clone] }, @!a) } - - method Str { - [~] map - { [~] map({ $^c ?? '#' !! '.' }, |$^row), "\n" }, - @!a - } - - method alive (Int $row, Int $col --> Bool) { - 0 <= $row < $.height and 0 <= $col < $.width - and @!a[$row][$col]; - } - - method nextgen { - my $prev = self.clone; - for ^$.height -> $row { - for ^$.width -> $col { - my $v = [+] - map({ $prev.alive($^r, $^c) }, - ($col - 1, $col, $col + 1 X - $row - 1, $row, $row + 1)), - -$prev.alive($row, $col); - @!a[$row][$col] = - $prev.alive($row, $col) && $v == 2 || $v == 3; - } - } - } -} diff --git a/Task/Conways-Game-of-Life/Perl-6/conways-game-of-life-2.pl6 b/Task/Conways-Game-of-Life/Perl-6/conways-game-of-life-2.pl6 deleted file mode 100644 index a6a8f86fb9..0000000000 --- a/Task/Conways-Game-of-Life/Perl-6/conways-game-of-life-2.pl6 +++ /dev/null @@ -1,14 +0,0 @@ -my Grid $glider .= new ' -............ -............ -............ -.......###.. -.......#.... -........#... -............'; - -loop { - say $glider; - sleep 1; - $glider.nextgen; -} diff --git a/Task/Conways-Game-of-Life/Phix/conways-game-of-life.phix b/Task/Conways-Game-of-Life/Phix/conways-game-of-life.phix new file mode 100644 index 0000000000..685e8f97af --- /dev/null +++ b/Task/Conways-Game-of-Life/Phix/conways-game-of-life.phix @@ -0,0 +1,144 @@ +-- +-- demo\rosetta\Conways_Game_of_Life.exw +-- +include pGUI.e + +Ihandle dlg, canvas, hTimer +cdCanvas cddbuffer, cdcanvas + +sequence c = {}, -- cells + cn, -- new cells + cl -- last cells + +procedure draw(integer what) +integer lx = length(c) +integer ly = length(c[1]) +integer x = floor(lx/2) +integer y = floor(ly/2) + switch what do + case ' ' : -- Clear + c = sq_mul(c,0) + case '+' : -- Blinker + {c[x-1,y],c[x,y],c[x+1,y]} @= 1 + case 'G' : -- Glider + { c[x+1,y+4], + c[x+2,y+2], c[x+2,y+4], + c[x+3,y+3],c[x+3,y+4]} @= 1 + case 'T' : -- Thunderbird + {c[x-1,y+1],c[x,y+1],c[x+1,y+1], + c[x,y+3],c[x,y+4],c[x,y+5]} @= 1 + case 'X' : -- Cross + for x=2 to lx-1 do + y = floor(ly*x/lx) + if y>1 then + {c[x,y],c[x,ly-y]} @= 1 + end if + end for + end switch +end procedure + +atom t0 = time() + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) +integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") +integer colour, cnxy, live, alive = 0 + if length(c)!=height + or length(c[1])!=width then + c = repeat(repeat(0,height),width) + cn = c + cl = c + draw('X') + end if + cdCanvasActivate(cddbuffer) + for y=2 to height-1 do + for x=2 to width-1 do + integer xm1 = x-1, xp1 = x+1, + ym1 = y-1, yp1 = y+1 + cnxy = c[xm1,ym1] + c[x,ym1] + c[xp1,ym1] + + c[xm1,y] + c[xp1,y] + + c[xm1,yp1] + c[x,yp1] + c[xp1,yp1] + if c[x,y]=1 then + live = (cnxy>=2 and cnxy<=3) + else + live = (cnxy=3) + end if + cn[x,y] = live + alive += live + if live then + if c[x,y] then + colour = iff(cl[x,y]?CD_PURPLE -- adult + :CD_GREEN) -- newborn + else + colour = iff(cl[x,y]?CD_RED -- old + :CD_YELLOW) -- shortlived + end if + else + colour = CD_BLACK + end if + cdCanvasPixel(cddbuffer, x, y, colour) + end for + end for + cdCanvasFlush(cddbuffer) + if not alive then + IupStoreAttribute(hTimer, "RUN", "NO") + IupStoreAttribute(dlg, "TITLE", "died") +-- elsif cl=cn then -- (made blinker stable) + elsif c=cn then + IupStoreAttribute(hTimer, "RUN", "NO") + IupStoreAttribute(dlg, "TITLE", "stable") + else + cl = c + c = cn + IupSetStrAttribute(dlg, "TITLE", "%3.2f", {time()-t0}) + end if + return IUP_DEFAULT +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + cdCanvasSetBackground(cddbuffer, CD_WHITE) + cdCanvasSetForeground(cddbuffer, CD_RED) + return IUP_DEFAULT +end function + +function key_cb(Ihandle /*ih*/, atom c) + if find(c," ") then draw(' ') -- Clear + elsif find(c,"+bB") then draw('+') -- Blinker + elsif find(c,"gG") then draw('G') -- Glider + elsif find(c,"tT") then draw('T') -- Thunderbird + elsif find(c,"xX") then draw('X') -- Cross + end if + IupStoreAttribute(hTimer, "RUN", "YES") + IupStoreAttribute(dlg, "TITLE", "Life") + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +function timer_cb(Ihandle /*ih*/) + IupUpdate(canvas) + return IUP_IGNORE +end function + +procedure main() + IupOpen() + + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "200x200") -- initial size + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", "Conway's Game of Life") + IupSetCallback(dlg, "K_ANY", Icallback("key_cb")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + + hTimer = IupTimer(Icallback("timer_cb"), 30) + + IupMap(dlg) + IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation + IupShowXY(dlg,IUP_CENTER,IUP_CENTER) + IupMainLoop() + IupClose() +end procedure + +main() diff --git a/Task/Conways-Game-of-Life/PureBasic/conways-game-of-life.purebasic b/Task/Conways-Game-of-Life/PureBasic/conways-game-of-life.purebasic deleted file mode 100644 index 3cbea8d8cb..0000000000 --- a/Task/Conways-Game-of-Life/PureBasic/conways-game-of-life.purebasic +++ /dev/null @@ -1,56 +0,0 @@ -EnableExplicit -Define.i x, y ,Xmax ,Ymax ,N -Xmax = 13 : Ymax = 20 -Dim world.i(Xmax+1,Ymax+1) -Dim Nextworld.i(Xmax+1,Ymax+1) - -; Glider test -;------------------------------------------ - world(1,1)=1 : world(1,2)=0 : world(1,3)=0 - world(2,1)=0 : world(2,2)=1 : world(2,3)=1 - world(3,1)=1 : world(3,2)=1 : world(3,3)=0 -;------------------------------------------ - -OpenConsole() -EnableGraphicalConsole(1) -ClearConsole() -Print("Press any key to interrupt") -Repeat - ConsoleLocate(0,2) - PrintN(LSet("", Xmax+2, "-")) - ;---------- endless world --------- - For y = 1 To Ymax - world(0,y)=world(Xmax,y) - world(Xmax+1,y)=world(1,y) - Next - For x = 1 To Xmax - world(x,0)=world(x,Ymax) - world(x,Ymax+1)=world(x,1) - Next - world(0 ,0 )=world(Xmax,Ymax) - world(Xmax+1,Ymax+1)=world(1 ,1 ) - world(Xmax+1,0 )=world(1 ,Ymax) - world( 0,Ymax+1)=world(Xmax,1 ) - ;---------- endless world --------- - For y = 1 To Ymax - Print("|") - For x = 1 To Xmax - Print(Chr(32+world(x,y)*3)) - N = world(x-1,y-1)+world(x-1,y)+world(x-1,y+1)+world(x,y-1) - N + world(x,y+1)+world(x+1,y-1)+world(x+1,y)+world(x+1,y+1) - If (world(x,y) And (N = 2 Or N = 3))Or (world(x,y)=0 And N = 3) - Nextworld(x,y)=1 - Else - Nextworld(x,y)=0 - EndIf - Next - PrintN("|") - Next - PrintN(LSet("", Xmax+2, "-")) - Delay(100) - ;Swap world() , Nextworld() ;PB <4.50 - CopyArray(Nextworld(), world());PB =>4.50 - Dim Nextworld.i(Xmax+1,Ymax+1) -Until Inkey() <> "" - -PrintN("Press any key to exit"): Repeat: Until Inkey() <> "" diff --git a/Task/Conways-Game-of-Life/Scilab/conways-game-of-life.scilab b/Task/Conways-Game-of-Life/Scilab/conways-game-of-life.scilab new file mode 100644 index 0000000000..8e28dd23af --- /dev/null +++ b/Task/Conways-Game-of-Life/Scilab/conways-game-of-life.scilab @@ -0,0 +1,103 @@ +Init_state=[0 0 0;... + 1 1 1;... + 0 0 0]; +console_output=%T; + +if (atomsIsLoaded('IPCV') | atomsIsLoaded('SIVP')) & ~console_output then + Input=imread('initial_state.bmp'); //Comment this three lines in case + Init_state=~im2bw(Input,0.1); //there is no input image but + Init_state=1.0.*Init_state; //you still want the graphic window + scf(0); clf(); + imshow(~Init_state); + set(gca(),"isoview","on"); +end + +Curr_state=1.0.*Init_state; +Grid_size=size(Init_state); +Gens=4; + +function varargout=neighbourhood(A,i,j) + R_top=i-1; + if i==1 then + R_top=1; + end + + R_bottom=i+1; + if i==Grid_size(1) then + R_bottom=Grid_size(1); + end + + R_left=j-1; + if j==1 then + R_left=1; + end + + C_right=j+1; + if j==Grid_size(2) then + C_right=Grid_size(2); + end + + varargout=list(A(R_top:R_bottom,R_left:C_right)); +endfunction + +function []=console_print(Grid) + String_grid=string(Grid); + for i=1:size(Grid,'r') + for j=1:size(Grid,'c') + if Grid(i,j) then + String_grid(i,j)="#"; + else + String_grid(i,j)=" "; + end + end + end + disp(String_grid); +endfunction + +neighbours=[]; +Next_state=[]; + +for gen=1:Gens + Next_state=zeros(Init_state); + + for i=1:Grid_size(1) + for j=1:Grid_size(2) + neighbours=zeros(3,3); + neighbours=neighbourhood(Curr_state,i,j); + + Sum_neighbours=sum(neighbours)-1*Curr_state(i,j); + + Alive=Curr_state(i,j); + if Alive then + if Sum_neighbours<2 then + Next_state(i,j)=0; + elseif Sum_neighbours==2 | Sum_neighbours==3 then + Next_state(i,j)=1; + elseif Sum_neighbours>3 then + Next_state(i,j)=0; + end + else + if Sum_neighbours==3 then + Next_state(i,j)=1; + end + end + end + end + + if (atomsIsLoaded('IPCV') | atomsIsLoaded('SIVP')) & ~console_output then + imshow(~Next_state); + sleep(50); + else + sleep(50); + disp("Generation "+string(gen)+":") + console_print(Next_state); + end + + if sum(Next_state)==0 | Curr_state==Next_state then + disp('ALL CELLS HAVE DIED OR BECAME INERT'); + disp('No. of Generations: '+string(gen)) + break + end + + Curr_state=Next_state; +end diff --git a/Task/Conways-Game-of-Life/Sidef/conways-game-of-life.sidef b/Task/Conways-Game-of-Life/Sidef/conways-game-of-life.sidef index b5e1a6e826..4bb7620a09 100644 --- a/Task/Conways-Game-of-Life/Sidef/conways-game-of-life.sidef +++ b/Task/Conways-Game-of-Life/Sidef/conways-game-of-life.sidef @@ -1,5 +1,5 @@ -var w = `tput cols`.to_i -var h = `tput lines`.to_i +var w = Num(`tput cols`) +var h = Num(`tput lines`) var r = "\033[H" var dirs = [[-1,-1], [-1, 0], [-1, 1], [ 0,-1], @@ -7,13 +7,10 @@ var dirs = [[-1,-1], [-1, 0], [-1, 1], [ 0,-1], var universe = h.of { w.of {1.rand < 0.1} } -var rh = h.range -var rw = w.range - func iterate { var new = h.of { w.of(false) } - for i in rh { - for j in rw { + static rx = (^h ~X ^w) + for i,j in rx { var neighbor = 0 for y,x in (dirs.map {|dir| dir »+« [i, j] }) { universe[y % h][x % w] && ++neighbor @@ -22,7 +19,6 @@ func iterate { new[i][j] = (universe[i][j] ? (neighbor==2 || neighbor==3) : (neighbor==3)) - } } universe = new } diff --git a/Task/Conways-Game-of-Life/Simula/conways-game-of-life.simula b/Task/Conways-Game-of-Life/Simula/conways-game-of-life.simula new file mode 100644 index 0000000000..cd250016ad --- /dev/null +++ b/Task/Conways-Game-of-Life/Simula/conways-game-of-life.simula @@ -0,0 +1,165 @@ +COMMENT A PORT OF AN R6RS SCHEME IMPLEMENTATION OF CONWAY'S GAME OF LIFE TO SIMULA --- ASSUMES ; +COMMENT ALL CELLS OUTSIDE THE DEFINED GRID ARE DEAD ; + +BEGIN + + +COMMENT FIRST WE NEED CONS, CAR, CDR, LENGTH AND MAP TO SIMULATE SCHEME ; + +CLASS ATOM;; + +ATOM CLASS CELL(ALIVE); INTEGER ALIVE;; + +ATOM CLASS LIST(A1, A2); REF(ATOM) A1, A2;; + +REF(LIST) PROCEDURE CONS(A1, A2); REF(ATOM) A1, A2; + CONS :- NEW LIST(A1, A2); + +REF(ATOM) PROCEDURE CAR(LST); REF(LIST) LST; + CAR :- LST.A1; + +REF(ATOM) PROCEDURE CDR(LST); REF(LIST) LST; + CDR :- LST.A2; + +INTEGER PROCEDURE LENGTH(LST); REF(LIST) LST; + LENGTH := IF LST == NONE THEN 0 ELSE 1 + LENGTH(CDR(LST)); + +REF(LIST) PROCEDURE MAP(F, LST); PROCEDURE F IS REF(ATOM) PROCEDURE F(ARG); REF(ATOM) ARG;; REF(LIST) LST; + MAP :- IF LST == NONE THEN NONE ELSE CONS(F(CAR(LST)), MAP(F, CDR(LST))); + + + +COMMENT NOW FOLLOWS THE PROBLEM SPECIFIC PART ; + + +COMMENT IF N IS OUTSIDE BOUNDS OF LIST, RETURN 0 ELSE VALUE AT N ; +REF(ATOM) PROCEDURE NTH(N, LST); INTEGER N; REF(LIST) LST; + NTH :- IF N > LENGTH(LST) THEN NEW CELL(0) ELSE + IF N < 1 THEN NEW CELL(0) ELSE + IF N = 1 THEN CAR(LST) ELSE NTH(N - 1, CDR(LST)); + + +COMMENT RETURN THE NEXT STATE OF THE SUPPLIED UNIVERSE ; +REF(LIST) PROCEDURE NEXTUNIVERSE(UNIVERSE); REF(LIST) UNIVERSE; +BEGIN + + COMMENT VALUE AT (X, Y) ; + INTEGER PROCEDURE VALUEAT(X, Y); INTEGER X, Y; + BEGIN + REF(ATOM) A; + A :- NTH(Y, UNIVERSE); + INSPECT A + WHEN LIST DO + VALUEAT := NTH(X, THIS LIST) QUA CELL.ALIVE + OTHERWISE + VALUEAT := 0; + END VALUEAT; + + COMMENT SUM OF THE VALUES OF THE CELLS SURROUNDING (X, Y) ; + INTEGER PROCEDURE NEIGHBORSUM(X, Y); INTEGER X, Y; + NEIGHBORSUM := + VALUEAT(X - 1, Y - 1) + + VALUEAT(X - 1, Y ) + + VALUEAT(X - 1, Y + 1) + + VALUEAT(X, Y - 1) + + VALUEAT(X, Y + 1) + + VALUEAT(X + 1, Y - 1) + + VALUEAT(X + 1, Y ) + + VALUEAT(X + 1, Y + 1); + + COMMENT NEXT STATE OF THE CELL AT (X, Y) ; + INTEGER PROCEDURE NEXTCELL(X, Y); INTEGER X, Y; + BEGIN + INTEGER CUR, NS; + CUR := VALUEAT(X, Y); + NS := NEIGHBORSUM(X, Y); + NEXTCELL := IF CUR = 1 AND (NS < 2 OR NS > 3) THEN 0 ELSE + IF CUR = 0 AND NS = 3 THEN 1 ELSE CUR; + END NEXTCELL; + + COMMENT NEXT STATE OF ROW N ; + REF(LIST) PROCEDURE ROW(N, OUT); INTEGER N; REF(LIST) OUT; + BEGIN + INTEGER W, O; + W := LENGTH(CAR(UNIVERSE)); + O := LENGTH(OUT); + ROW :- IF W = O THEN OUT ELSE ROW(N, CONS(NEW CELL(NEXTCELL(W - O, N)), OUT)); + END ROW; + + + COMMENT A RANGE OF INTS FROM BOT TO TOP ; + REF(LIST) PROCEDURE INTRANGE(BOT, TOP); INTEGER BOT, TOP; + INTRANGE :- IF BOT > TOP THEN NONE ELSE CONS(NEW CELL(BOT), INTRANGE(BOT + 1, TOP)); + + REF(ATOM) PROCEDURE LAMBDA(N); REF(ATOM) N; + LAMBDA :- ROW(N QUA CELL.ALIVE, NONE); + + NEXTUNIVERSE :- MAP(LAMBDA, INTRANGE(1, LENGTH(UNIVERSE))); + +END NEXTUNIVERSE; + +COMMENT DISPLAY THE UNIVERSE ; +PROCEDURE DISPLAY(LST); REF(LIST) LST; +BEGIN + WHILE LST =/= NONE DO + BEGIN + REF(LIST) LI; + LI :- CAR(LST); + WHILE LI =/= NONE DO + BEGIN + REF(CELL) CE; + CE :- CAR(LI); + OUTCHAR(IF CE.ALIVE = 1 THEN '#' ELSE '-'); + LI :- CDR(LI); + END; + OUTIMAGE; + LST :- CDR(LST); + END; +END DISPLAY; + +COMMENT STARTING WITH SEED, SHOW REPS STATES OF THE UNIVERSE ; +PROCEDURE CONWAY(SEED, REPS); REF(LIST) SEED; INTEGER REPS; +BEGIN + IF REPS > 0 THEN + BEGIN + DISPLAY(SEED); + OUTIMAGE; + CONWAY(NEXTUNIVERSE(SEED), REPS - 1); + END; +END CONWAY; + +REF(CELL) O, L; +O :- NEW CELL(0); +L :- NEW CELL(1); + +COMMENT BLINKER IN A 3X3 UNIVERSE ; +! (CONWAY '((0 1 0) + (0 1 0) + (0 1 0)) 5) ; +CONWAY(CONS(CONS(O, CONS(L, CONS(O, NONE))), + CONS(CONS(O, CONS(L, CONS(O, NONE))), + CONS(CONS(O, CONS(L, CONS(O, NONE))), + NONE))), 5); + +COMMENT GLIDER IN AN 8X8 UNIVERSE ; +!(CONWAY '((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)) 30) ; +OUTIMAGE; + +CONWAY(CONS(CONS(O, CONS(O, CONS(L, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))), + CONS(CONS(O, CONS(O, CONS(O, CONS(L, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))), + CONS(CONS(O, CONS(L, CONS(L, CONS(L, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))), + CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))), + CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))), + CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))), + CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))), + CONS(CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, CONS(O, NONE)))))))), + NONE)))))))), 30); + +END. diff --git a/Task/Conways-Game-of-Life/Vedit-macro-language/conways-game-of-life-1.vedit b/Task/Conways-Game-of-Life/Vedit-macro-language/conways-game-of-life-1.vedit deleted file mode 100644 index c1f5784b3a..0000000000 --- a/Task/Conways-Game-of-Life/Vedit-macro-language/conways-game-of-life-1.vedit +++ /dev/null @@ -1,58 +0,0 @@ -IT("Generation 0 ") IN -IT(".O.") IN -IT(".O.") IN -IT(".O.") - -#9 = 2 // number of generations to calculate -#10 = Cur_Line -#11 = Cur_Col-1 -for (#2 = 1; #2 <= #9; #2++) { - Update() - Get_Key("Next gen...", STATLINE) - Call("calculate") - itoa(#2, 20, LEFT) - GL(1) GC(12) Reg_Ins(20, OVERWRITE) -} -EOF -Return - -// Calculate one generation -:calculate: -Goto_Line(2) -While (At_EOF == 0) { - Search("|A",ERRBREAK) // find next living cell - #3 = Cur_Line - #4 = #7 = #8 = Cur_Col - 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 - #8 = #4+1 - Goto_Col(#8) - Ins_Char(Cur_Char+1,OVERWRITE) - } - if (#3 > 2) { // increment 3 cells above - Goto_Line(#3-1) - Call("inc_3") - } - if (#3 < #10) { // increment 3 cells below - Goto_Line(#3+1) - Call("inc_3") - } - Goto_Line(#3) - Goto_Col(#4+1) -} - -Replace("[1QR]", "O", REGEXP+BEGIN+ALL) // these cells alive -Replace("[/-7P-X]", ".", REGEXP+BEGIN+ALL) // these cells dead -Return - -// increment values of 3 characters in a row -:inc_3: -for (#1 = #7; #1 <= #8; #1++) { - Goto_Col(#1) - Ins_Char(Cur_Char+1,OVERWRITE) -} -Return diff --git a/Task/Conways-Game-of-Life/Vedit-macro-language/conways-game-of-life-2.vedit b/Task/Conways-Game-of-Life/Vedit-macro-language/conways-game-of-life-2.vedit deleted file mode 100644 index b9fb8b7047..0000000000 --- a/Task/Conways-Game-of-Life/Vedit-macro-language/conways-game-of-life-2.vedit +++ /dev/null @@ -1,14 +0,0 @@ -Generation 0 -.O. -.O. -.O. - -Generation 1 -... -OOO -... - -Generation 2 -.O. -.O. -.O. 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 new file mode 100644 index 0000000000..da3f4350f4 --- /dev/null +++ b/Task/Conways-Game-of-Life/Zkl/conways-game-of-life-1.zkl @@ -0,0 +1,35 @@ +class Life{ + fcn init(n, r1,c1, r2,c2, etc){ + 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 + icells.pump(Void,Void.Read,fcn(row,col){ cells[row*N+col]=1 }); + } + fcn get(row,col){ + if((0<=row'''2144'''   is not prime;   it would be shown as   '''2\times2\times2\times2\times2\times67.''' -;Related task: -*   [[Prime decomposition]] +;Related tasks: +*   [[prime decomposition]] +*   [[factors of an integer]] +*   [[Sieve of Eratosthenes]] +*   [[primality by trial division]] +*   [[factors of a Mersenne number]] +*   [[trial factoring of a Mersenne number]] +*   [[partition an integer X into N primes]]

    diff --git a/Task/Count-in-factors/360-Assembly/count-in-factors.360 b/Task/Count-in-factors/360-Assembly/count-in-factors.360 new file mode 100644 index 0000000000..0ab18cafd7 --- /dev/null +++ b/Task/Count-in-factors/360-Assembly/count-in-factors.360 @@ -0,0 +1,74 @@ +* Count in factors 24/03/2017 +COUNTFAC CSECT assist plig\COUNTFAC + USING COUNTFAC,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + L R6,=F'1' i=1 + DO WHILE=(C,R6,LE,=F'40') do i=1 to 40 + LR R7,R6 n=i + MVI F,X'01' f=true + MVC PG,=CL80' ' clear buffer + LA R10,PG pgi=0 + XDECO R6,XDEC edit i + MVC 0(12,R10),XDEC output i + LA R10,12(R10) pgi=pgi+12 + MVC 0(1,R10),=C'=' output '=' + LA R10,1(R10) pgi=pgi+1 + IF C,R7,EQ,=F'1' THEN if n=1 then + MVI 0(R10),C'1' output n + ELSE , else + LA R8,2 p=2 + DO WHILE=(CR,R8,LE,R7) do while p<=n + LR R4,R7 n + SRDA R4,32 ~ + DR R4,R8 /p + IF LTR,R4,Z,R4 THEN if n//p=0 then + IF CLI,F,EQ,X'00' THEN if not f then + MVC 0(1,R10),=C'*' output '*' + LA R10,1(R10) pgi=pgi+1 + ELSE , else + MVI F,X'00' f=false + ENDIF , endif + CVD R8,PP convert bin p to packed pp + MVC WORK12,MASX12 in fact L13 + EDMK WORK12,PP+2 edit and mark + LA R9,WORK12+12 end of string(p) + SR R9,R1 li=lengh(p) {r1 from edmk} + MVC EDIT12,WORK12 L12<-L13 + LA R4,EDIT12+12 source+12 + SR R4,R9 -lengh(p) + LR R5,R9 lengh(p) + LR R2,R10 target ix + LR R3,R9 lengh(p) + MVCL R2,R4 f=f||p + AR R10,R9 ix=ix+lengh(p) + LR R4,R7 n + SRDA R4,32 ~ + DR R4,R8 /p + LR R7,R5 n=n/p + ELSE , else + LA R8,1(R8) p=p+1 + ENDIF , endif + ENDDO , enddo while + ENDIF , endif + XPRNT PG,L'PG print buffer + LA R6,1(R6) i++ + ENDDO , enddo i + L R13,4(0,R13) restore previous savearea pointer + LM R14,R12,12(R13) restore previous context + XR R15,R15 rc=0 + BR R14 exit +F DS X flag first factor + DS 0D alignment for cvd +PP DS PL8 packed CL8 +EDIT12 DS CL12 target CL12 +WORK12 DS CL13 char CL13 +MASX12 DC X'40',9X'20',X'212060' CL13 +XDEC DS CL12 temp +PG DS CL80 buffer + YREGS + END COUNTFAC diff --git a/Task/Count-in-factors/Frink/count-in-factors.frink b/Task/Count-in-factors/Frink/count-in-factors.frink new file mode 100644 index 0000000000..ac83edbaf7 --- /dev/null +++ b/Task/Count-in-factors/Frink/count-in-factors.frink @@ -0,0 +1,6 @@ +i = 1 +while true +{ + println[join[" x ", factorFlat[i]]] + i = i + 1 +} diff --git a/Task/Count-in-factors/Kotlin/count-in-factors.kotlin b/Task/Count-in-factors/Kotlin/count-in-factors.kotlin new file mode 100644 index 0000000000..2474568a66 --- /dev/null +++ b/Task/Count-in-factors/Kotlin/count-in-factors.kotlin @@ -0,0 +1,42 @@ +// version 1.1.2 + +fun isPrime(n: Int) : Boolean { + if (n < 2) return false + if (n % 2 == 0) return n == 2 + if (n % 3 == 0) return n == 3 + var d = 5 + while (d * d <= n) { + if (n % d == 0) return false + d += 2 + if (n % d == 0) return false + d += 4 + } + return true +} + +fun getPrimeFactors(n: Int): List { + val factors = mutableListOf() + if (n < 1) return factors + if (n == 1 || isPrime(n)) { + factors.add(n) + return factors + } + var factor = 2 + var nn = n + while (true) { + if (nn % factor == 0) { + factors.add(factor) + nn /= factor + if (nn == 1) return factors + if (isPrime(nn)) factor = nn + } + else if (factor >= 3) factor += 2 + else factor = 3 + } +} + +fun main(args: Array) { + val list = (MutableList(22) { it + 1 } + 2144) + 6358 + for (i in list) + println("${"%4d".format(i)} = ${getPrimeFactors(i).joinToString(" * ")}") +} diff --git a/Task/Count-in-factors/Sidef/count-in-factors.sidef b/Task/Count-in-factors/Sidef/count-in-factors.sidef index e5dd9feb3d..c7d6b4b574 100644 --- a/Task/Count-in-factors/Sidef/count-in-factors.sidef +++ b/Task/Count-in-factors/Sidef/count-in-factors.sidef @@ -1,29 +1,29 @@ class Counter { method factors(n, p=2) { - var out = []; - while (n >= p*p) { - while (n % p == 0) { - out.append(p); - n /= p; + var a = gather { + while (n >= p*p) { + while (p `divides` n) { + take(p) + n //= p + } + p = self.next_prime(p) } - p = self.next_prime(p); } - (n > 1 || out.len.is_zero) && out.append(n); - return out; + (n > 1 || a.is_empty) ? (a << n) : a } - +  method is_prime(n) { self.factors(n).len == 1 } - +  method next_prime(p) { do { - p == 2 ? (p = 3) : (p+=2) - } while (!self.is_prime(p)); - return p; + p == 2 ? (p = 3) : (p+=2) + } while (!self.is_prime(p)) + return p } } - -100.times { |i| - say "#{i} = #{Counter().factors(i).join(' × ')}"; +  +for i in (1..100) { + say "#{i} = #{Counter().factors(i).join(' × ')}" } diff --git a/Task/Count-in-factors/Zkl/count-in-factors-1.zkl b/Task/Count-in-factors/Zkl/count-in-factors-1.zkl new file mode 100644 index 0000000000..80bd582e1b --- /dev/null +++ b/Task/Count-in-factors/Zkl/count-in-factors-1.zkl @@ -0,0 +1 @@ +foreach n in ([1..*]){ println(n,": ",primeFactors(n).concat("\U2715;")) } diff --git a/Task/Count-in-factors/Zkl/count-in-factors-2.zkl b/Task/Count-in-factors/Zkl/count-in-factors-2.zkl new file mode 100644 index 0000000000..cdbcad76c6 --- /dev/null +++ b/Task/Count-in-factors/Zkl/count-in-factors-2.zkl @@ -0,0 +1,13 @@ +fcn primeFactors(n){ // Return a list of factors of n + acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum + if(n==1 or k>maxD) acc.close(); + else{ + 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 + if(n!=m) acc.append(n/m); // opps, missed last factor + else acc; +} diff --git a/Task/Count-in-octal/ALGOL-W/count-in-octal.alg b/Task/Count-in-octal/ALGOL-W/count-in-octal.alg new file mode 100644 index 0000000000..7cb90bb085 --- /dev/null +++ b/Task/Count-in-octal/ALGOL-W/count-in-octal.alg @@ -0,0 +1,27 @@ +begin + string(12) r; + string(8) octDigits; + integer number; + octDigits := "01234567"; + number := -1; + while number < MAXINTEGER do begin + integer v, cPos; + number := number + 1; + v := number; + % build a string of octal digits in r, representing number % + % Algol W uses 32 bit integers, so r should be big enough % + % the most significant digit is on the right % + cPos := 0; + while begin + r( cPos // 1 ) := octDigits( v rem 8 // 1 ); + v := v div 8; + ( v > 0 ) + end do begin + cPos := cPos + 1 + end while_v_gt_0; + % show most significant digit on a newline % + write( r( cPos // 1 ) ); + % continue the line with the remaining digits (if any) % + for c := cPos - 1 step -1 until 0 do writeon( r( c // 1 ) ) + end while_r_lt_MAXINTEGER +end. diff --git a/Task/Count-in-octal/BASIC/count-in-octal-4.basic b/Task/Count-in-octal/BASIC/count-in-octal-4.basic new file mode 100644 index 0000000000..9ec862bcc6 --- /dev/null +++ b/Task/Count-in-octal/BASIC/count-in-octal-4.basic @@ -0,0 +1,14 @@ + 10 LET N$="0" + 20 SCROLL + 30 PRINT N$ + 40 LET L=LEN N$ + 50 LET N=VAL N$(L)+1 + 60 IF N=8 THEN GOTO 90 + 70 LET N$(L)=STR$ N + 80 GOTO 20 + 90 LET N$(L)="0" +100 IF L=1 THEN GOTO 130 +110 LET L=L-1 +120 GOTO 50 +130 LET N$="1"+N$ +140 GOTO 20 diff --git a/Task/Count-in-octal/Batch-File/count-in-octal.bat b/Task/Count-in-octal/Batch-File/count-in-octal.bat new file mode 100644 index 0000000000..06f36ec86b --- /dev/null +++ b/Task/Count-in-octal/Batch-File/count-in-octal.bat @@ -0,0 +1,25 @@ +@echo off +:: {CTRL + C} to exit the batch file + +:: Send incrementing decimal values to the :to_Oct function +set loop=0 +:loop1 +call:to_Oct %loop% +set /a loop+=1 +goto loop1 + +:: Convert the decimal values parsed [%1] to octal and output them on a new line +:to_Oct +set todivide=%1 +set "fulloct=" + +:loop2 +set tomod=%todivide% +set /a appendmod=%tomod% %% 8 +set fulloct=%appendmod%%fulloct% +if %todivide% lss 8 ( + echo %fulloct% + exit /b +) +set /a todivide/=8 +goto loop2 diff --git a/Task/Count-in-octal/Bc/count-in-octal.bc b/Task/Count-in-octal/Bc/count-in-octal.bc new file mode 100644 index 0000000000..30fdea6df2 --- /dev/null +++ b/Task/Count-in-octal/Bc/count-in-octal.bc @@ -0,0 +1,2 @@ +obase = 8 /* Output base is octal. */ +for (num = 0; 1; num++) num /* Loop forever, printing counter. */ diff --git a/Task/Count-in-octal/Crystal/count-in-octal.crystal b/Task/Count-in-octal/Crystal/count-in-octal.crystal new file mode 100644 index 0000000000..13b5c5371b --- /dev/null +++ b/Task/Count-in-octal/Crystal/count-in-octal.crystal @@ -0,0 +1,4 @@ +# version 0.21.1 +# using unsigned 8 bit integer, range 0 to 255 + +(0_u8..255_u8).each { |i| puts i.to_s(8) } diff --git a/Task/Count-in-octal/Elixir/count-in-octal-2.elixir b/Task/Count-in-octal/Elixir/count-in-octal-2.elixir index d90ddf3f14..ca60c16e15 100644 --- a/Task/Count-in-octal/Elixir/count-in-octal-2.elixir +++ b/Task/Count-in-octal/Elixir/count-in-octal-2.elixir @@ -1,2 +1,4 @@ -f = fn ff,i -> :io.fwrite "~.8b~n", [i]; ff.(ff, i+1) end -f.(f, 0) +Stream.unfold(0, fn n -> + IO.puts Integer.to_string(n,8) + {n,n+1} +end) |> Stream.run diff --git a/Task/Count-in-octal/Elixir/count-in-octal-3.elixir b/Task/Count-in-octal/Elixir/count-in-octal-3.elixir new file mode 100644 index 0000000000..d90ddf3f14 --- /dev/null +++ b/Task/Count-in-octal/Elixir/count-in-octal-3.elixir @@ -0,0 +1,2 @@ +f = fn ff,i -> :io.fwrite "~.8b~n", [i]; ff.(ff, i+1) end +f.(f, 0) diff --git a/Task/Count-in-octal/Kotlin/count-in-octal.kotlin b/Task/Count-in-octal/Kotlin/count-in-octal.kotlin new file mode 100644 index 0000000000..56f76b5801 --- /dev/null +++ b/Task/Count-in-octal/Kotlin/count-in-octal.kotlin @@ -0,0 +1,6 @@ +// version 1.1 + +// counts up to 177 octal i.e. 127 decimal +fun main(args: Array) { + (0..Byte.MAX_VALUE).forEach { println("%03o".format(it)) } +} diff --git a/Task/Count-in-octal/Maple/count-in-octal.maple b/Task/Count-in-octal/Maple/count-in-octal.maple new file mode 100644 index 0000000000..0191285ee4 --- /dev/null +++ b/Task/Count-in-octal/Maple/count-in-octal.maple @@ -0,0 +1,3 @@ +octcount := proc (n) + seq(printf("%a \n", convert(i, octal)), i = 1 .. n); + end proc; diff --git a/Task/Count-in-octal/Scala/count-in-octal.scala b/Task/Count-in-octal/Scala/count-in-octal.scala index c9c28f4dfa..f71ed1820f 100644 --- a/Task/Count-in-octal/Scala/count-in-octal.scala +++ b/Task/Count-in-octal/Scala/count-in-octal.scala @@ -1 +1 @@ -0 until Int.MaxValue foreach(i=> println(i toOctalString)) +Stream from 0 foreach (i => println(i.toOctalString)) diff --git a/Task/Count-in-octal/Zkl/count-in-octal.zkl b/Task/Count-in-octal/Zkl/count-in-octal.zkl new file mode 100644 index 0000000000..ca0dc6c0ba --- /dev/null +++ b/Task/Count-in-octal/Zkl/count-in-octal.zkl @@ -0,0 +1 @@ +foreach n in ([0..]){println("%.8B".fmt(n))} diff --git a/Task/Count-occurrences-of-a-substring/BASIC/count-occurrences-of-a-substring-3.basic b/Task/Count-occurrences-of-a-substring/BASIC/count-occurrences-of-a-substring-3.basic new file mode 100644 index 0000000000..243f647729 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/BASIC/count-occurrences-of-a-substring-3.basic @@ -0,0 +1,17 @@ + 10 LET S$="THE THREE TRUTHS" + 20 LET U$="TH" + 30 GOSUB 100 + 40 PRINT N + 50 LET S$="ABABABABAB" + 60 LET U$="ABAB" + 70 GOSUB 100 + 80 PRINT N + 90 STOP +100 LET N=0 +110 LET I=0 +120 LET I=I+1 +130 IF I+LEN U$>LEN S$ THEN RETURN +140 IF S$(I TO I+LEN U$-1)<>U$ THEN GOTO 120 +150 LET N=N+1 +160 LET I=I+LEN U$ +170 GOTO 130 diff --git a/Task/Count-occurrences-of-a-substring/BaCon/count-occurrences-of-a-substring.bacon b/Task/Count-occurrences-of-a-substring/BaCon/count-occurrences-of-a-substring.bacon new file mode 100644 index 0000000000..fd74d038be --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/BaCon/count-occurrences-of-a-substring.bacon @@ -0,0 +1,11 @@ +FUNCTION Uniq_Tally(text$, part$) + LOCAL x + WHILE TALLY(text$, part$) + INCR x + text$ = MID$(text$, INSTR(text$, part$)+LEN(part$)) + WEND + RETURN x +END FUNCTION + +PRINT "the three truths - th: ", Uniq_Tally("the three truths", "th") +PRINT "ababababab - abab: ", Uniq_Tally("ababababab", "abab") diff --git a/Task/Count-occurrences-of-a-substring/C-sharp/count-occurrences-of-a-substring-1.cs b/Task/Count-occurrences-of-a-substring/C-sharp/count-occurrences-of-a-substring-1.cs new file mode 100644 index 0000000000..775cf87ef5 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/C-sharp/count-occurrences-of-a-substring-1.cs @@ -0,0 +1,26 @@ +using System; + +class SubStringTestClass +{ + public static int CountSubStrings(this string testString, string testSubstring) + { + int count = 0; + + if (testString.Contains(testSubstring)) + { + for (int i = 0; i < testString.Length; i++) + { + if (testString.Substring(i).Length >= testSubstring.Length) + { + bool equals = testString.Substring(i, testSubstring.Length).Equals(testSubstring); + if (equals) + { + count++; + i += testSubstring.Length - 1; // Fix: Don't count overlapping matches + } + } + } + } + return count; + } +} diff --git a/Task/Count-occurrences-of-a-substring/C-sharp/count-occurrences-of-a-substring-2.cs b/Task/Count-occurrences-of-a-substring/C-sharp/count-occurrences-of-a-substring-2.cs new file mode 100644 index 0000000000..63cd022d4f --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/C-sharp/count-occurrences-of-a-substring-2.cs @@ -0,0 +1,6 @@ +using System; +class SubStringTestClass +{ + public static int CountSubStrings(this string testString, string testSubstring) => + testString?.Split(new [] { testSubstring }, StringSplitOptions.None)?.Length - 1 ?? 0; +} diff --git a/Task/Count-occurrences-of-a-substring/C-sharp/count-occurrences-of-a-substring.cs b/Task/Count-occurrences-of-a-substring/C-sharp/count-occurrences-of-a-substring.cs deleted file mode 100644 index 50b8b1be67..0000000000 --- a/Task/Count-occurrences-of-a-substring/C-sharp/count-occurrences-of-a-substring.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; - -class SubStringTestClass -{ - public static int CountSubStrings(this string testString, string testSubstring) - { - int count = 0; - - if (testString.Contains(testSubstring)) - { - for (int i = 0; i < testString.Length; i++) - { - if (testString.Substring(i).Length >= testSubstring.Length) - { - bool equals = testString.Substring(i, testSubstring.Length).Equals(testSubstring); - if (equals) - { - count++; - i += testSubstring.Length - 1; // Fix: Don't count overlapping matches - } - } - } - } - return count; - } -} diff --git a/Task/Count-occurrences-of-a-substring/Haskell/count-occurrences-of-a-substring-2.hs b/Task/Count-occurrences-of-a-substring/Haskell/count-occurrences-of-a-substring-2.hs index 20ac2f87b9..25be02dcf7 100644 --- a/Task/Count-occurrences-of-a-substring/Haskell/count-occurrences-of-a-substring-2.hs +++ b/Task/Count-occurrences-of-a-substring/Haskell/count-occurrences-of-a-substring-2.hs @@ -1,9 +1,10 @@ -count :: Eq a => [a] -> [a] -> Int -count [] = error "empty substring" -count sub = go +import Data.Text hiding (length) + +countAll :: String -> String -> Int +countAll needle haystack = length (breakOnAll n h) where - go = scan sub . dropWhile (/= head sub) - scan _ [] = 0 - scan [] xs = 1 + go xs - scan (x:xs) (y:ys) | x == y = scan xs ys - | otherwise = go ys + [n, h] = pack <$> [needle, haystack] + +main :: IO () +main = + print $ countAll "ab" <$> ["ababababab", "abelian absurdity", "babel kebab"] diff --git a/Task/Count-occurrences-of-a-substring/Haskell/count-occurrences-of-a-substring-3.hs b/Task/Count-occurrences-of-a-substring/Haskell/count-occurrences-of-a-substring-3.hs index df6624ba34..20ac2f87b9 100644 --- a/Task/Count-occurrences-of-a-substring/Haskell/count-occurrences-of-a-substring-3.hs +++ b/Task/Count-occurrences-of-a-substring/Haskell/count-occurrences-of-a-substring-3.hs @@ -1,5 +1,9 @@ -import Data.List (tails, stripPrefix) -import Data.Maybe (catMaybes) - count :: Eq a => [a] -> [a] -> Int -count sub = length . catMaybes . map (stripPrefix sub) . tails +count [] = error "empty substring" +count sub = go + where + go = scan sub . dropWhile (/= head sub) + scan _ [] = 0 + scan [] xs = 1 + go xs + scan (x:xs) (y:ys) | x == y = scan xs ys + | otherwise = go ys diff --git a/Task/Count-occurrences-of-a-substring/Haskell/count-occurrences-of-a-substring-4.hs b/Task/Count-occurrences-of-a-substring/Haskell/count-occurrences-of-a-substring-4.hs new file mode 100644 index 0000000000..df6624ba34 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Haskell/count-occurrences-of-a-substring-4.hs @@ -0,0 +1,5 @@ +import Data.List (tails, stripPrefix) +import Data.Maybe (catMaybes) + +count :: Eq a => [a] -> [a] -> Int +count sub = length . catMaybes . map (stripPrefix sub) . tails diff --git a/Task/Count-occurrences-of-a-substring/JavaScript/count-occurrences-of-a-substring.js b/Task/Count-occurrences-of-a-substring/JavaScript/count-occurrences-of-a-substring-1.js similarity index 100% rename from Task/Count-occurrences-of-a-substring/JavaScript/count-occurrences-of-a-substring.js rename to Task/Count-occurrences-of-a-substring/JavaScript/count-occurrences-of-a-substring-1.js diff --git a/Task/Count-occurrences-of-a-substring/JavaScript/count-occurrences-of-a-substring-2.js b/Task/Count-occurrences-of-a-substring/JavaScript/count-occurrences-of-a-substring-2.js new file mode 100644 index 0000000000..5af361ceed --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/JavaScript/count-occurrences-of-a-substring-2.js @@ -0,0 +1 @@ +const countSubString = (str, subStr) => str.split(subStr).length - 1; diff --git a/Task/Count-occurrences-of-a-substring/jq/count-occurrences-of-a-substring-1.jq b/Task/Count-occurrences-of-a-substring/Jq/count-occurrences-of-a-substring-1.jq similarity index 100% rename from Task/Count-occurrences-of-a-substring/jq/count-occurrences-of-a-substring-1.jq rename to Task/Count-occurrences-of-a-substring/Jq/count-occurrences-of-a-substring-1.jq diff --git a/Task/Count-occurrences-of-a-substring/jq/count-occurrences-of-a-substring-2.jq b/Task/Count-occurrences-of-a-substring/Jq/count-occurrences-of-a-substring-2.jq similarity index 100% rename from Task/Count-occurrences-of-a-substring/jq/count-occurrences-of-a-substring-2.jq rename to Task/Count-occurrences-of-a-substring/Jq/count-occurrences-of-a-substring-2.jq diff --git a/Task/Count-occurrences-of-a-substring/Kotlin/count-occurrences-of-a-substring.kotlin b/Task/Count-occurrences-of-a-substring/Kotlin/count-occurrences-of-a-substring.kotlin new file mode 100644 index 0000000000..b4b572c659 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Kotlin/count-occurrences-of-a-substring.kotlin @@ -0,0 +1,9 @@ +// version 1.0.6 + +fun countSubstring(s: String, sub: String): Int = s.split(sub).size - 1 + +fun main(args: Array) { + println(countSubstring("the three truths","th")) + println(countSubstring("ababababab","abab")) + println(countSubstring("","")) +} diff --git a/Task/Count-occurrences-of-a-substring/Lua/count-occurrences-of-a-substring-1.lua b/Task/Count-occurrences-of-a-substring/Lua/count-occurrences-of-a-substring-1.lua new file mode 100644 index 0000000000..b6650d904f --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Lua/count-occurrences-of-a-substring-1.lua @@ -0,0 +1,6 @@ +function countSubstring(s1, s2) + return select(2, s1:gsub(s2, "")) +end + +print(countSubstring("the three truths", "th")) +print(countSubstring("ababababab", "abab")) diff --git a/Task/Count-occurrences-of-a-substring/Lua/count-occurrences-of-a-substring-2.lua b/Task/Count-occurrences-of-a-substring/Lua/count-occurrences-of-a-substring-2.lua new file mode 100644 index 0000000000..7ab762238e --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Lua/count-occurrences-of-a-substring-2.lua @@ -0,0 +1,10 @@ +function countSubstring(s1, s2) + local count = 0 + for eachMatch in s1:gmatch(s2) do + count = count + 1 + end + return count +end + +print(countSubstring("the three truths", "th")) +print(countSubstring("ababababab", "abab")) diff --git a/Task/Count-occurrences-of-a-substring/Lua/count-occurrences-of-a-substring.lua b/Task/Count-occurrences-of-a-substring/Lua/count-occurrences-of-a-substring.lua deleted file mode 100644 index 3717ed98cc..0000000000 --- a/Task/Count-occurrences-of-a-substring/Lua/count-occurrences-of-a-substring.lua +++ /dev/null @@ -1,8 +0,0 @@ -function countSubstring (s1, s2) - local count = 0 - for eachMatch in s1:gmatch(s2) do count = count + 1 end - return count -end - -print(countSubstring("the three truths", "th")) -print(countSubstring("ababababab","abab")) diff --git a/Task/Count-occurrences-of-a-substring/OoRexx/count-occurrences-of-a-substring.rexx b/Task/Count-occurrences-of-a-substring/OoRexx/count-occurrences-of-a-substring.rexx new file mode 100644 index 0000000000..28f984e0bc --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/OoRexx/count-occurrences-of-a-substring.rexx @@ -0,0 +1,12 @@ + bag="the three truths" + x="th" + say left(bag,30) left(x,15) 'found' bag~countstr(x) + + bag="ababababab" + x="abab" + say left(bag,30) left(x,15) 'found' bag~countstr(x) + + -- can be done caselessly too + bag="abABAbaBab" + x="abab" + say left(bag,30) left(x,15) 'found' bag~caselesscountstr(x) diff --git a/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-2.scala b/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-2.scala index 8738e236f0..7feb32b987 100644 --- a/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-2.scala +++ b/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-2.scala @@ -1 +1,2 @@ -def countSubstring( str:String, substr:String ) = substr.r.findAllMatchIn(str).length +def countSubstring(str: String, sub: String): Int = + str.sliding(sub.length).count(_ == sub) diff --git a/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-3.scala b/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-3.scala index 6930881857..8738e236f0 100644 --- a/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-3.scala +++ b/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-3.scala @@ -1,2 +1 @@ -println(countSubstring("ababababab", "abab")) -println(countSubstring("the three truths", "th")) +def countSubstring( str:String, substr:String ) = substr.r.findAllMatchIn(str).length diff --git a/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-4.scala b/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-4.scala new file mode 100644 index 0000000000..6930881857 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-4.scala @@ -0,0 +1,2 @@ +println(countSubstring("ababababab", "abab")) +println(countSubstring("the three truths", "th")) diff --git a/Task/Count-occurrences-of-a-substring/Zkl/count-occurrences-of-a-substring-1.zkl b/Task/Count-occurrences-of-a-substring/Zkl/count-occurrences-of-a-substring-1.zkl new file mode 100644 index 0000000000..bbd63d6511 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Zkl/count-occurrences-of-a-substring-1.zkl @@ -0,0 +1,4 @@ +fcn countSubstring(s,p){ pn:=p.len(); cnt:=n:=0; + while(Void!=(n:=s.find(p,n))){cnt+=1; n+=pn} + cnt +} diff --git a/Task/Count-occurrences-of-a-substring/Zkl/count-occurrences-of-a-substring-2.zkl b/Task/Count-occurrences-of-a-substring/Zkl/count-occurrences-of-a-substring-2.zkl new file mode 100644 index 0000000000..d1d5441262 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Zkl/count-occurrences-of-a-substring-2.zkl @@ -0,0 +1 @@ +fcn countSubstring(s,p){ (pl:=p.len()) and (s.len()-(s-p).len())/pl } diff --git a/Task/Count-the-coins/Dart/count-the-coins.dart b/Task/Count-the-coins/Dart/count-the-coins.dart new file mode 100644 index 0000000000..604ad6665f --- /dev/null +++ b/Task/Count-the-coins/Dart/count-the-coins.dart @@ -0,0 +1,55 @@ +var cache = new Map(); + +main() { + var stopwatch = new Stopwatch()..start(); + + // use the brute-force recursion for the small problem + int amount = 100; + list coinTypes = [25,10,5,1]; + print (coins(amount,coinTypes).toString() + " ways for $amount using $coinTypes coins."); + + // use the cache version for the big problem + amount = 100000; + coinTypes = [100,50,25,10,5,1]; + print (cachedCoins(amount,coinTypes).toString() + " ways for $amount using $coinTypes coins."); + + stopwatch.stop(); + print ("... completed in " + (stopwatch.elapsedMilliseconds/1000).toString() + " seconds"); +} + + +coins(int amount, list coinTypes) { + int count = 0; + + if(coinTypes.length == 1) return (1); // just pennies available, so only one way to make change + + for(int i=0; i<=(amount/coinTypes[0]).toInt(); i++){ // brute force recursion + count += coins(amount-(i*coinTypes[0]),coinTypes.sublist(1)); // sublist(1) is like lisp's '(rest ...)' + } + + // uncomment if you want to see intermediate steps + //print("there are " + count.toString() +" ways to count change for ${amount.toString()} using ${coinTypes} coins."); + return(count); + } + + + cachedCoins(int amount, list coinTypes) { + int count = 0; + + // this is more efficient, looks at last two coins. but not fast enough for the optional exercise. + if(coinTypes.length == 2) return ((amount/coinTypes[0]).toInt() + 1); + + var key = "$amount.$coinTypes"; // lookes like "100.[25,10,5,1]" + var cacheValue = cache[key]; // check whether we have seen this before + + if(cacheValue != null) return(cacheValue); + + count = 0; + // same recursion as simple method, but caches all subqueries too + for(int i=0; i<=(amount/coinTypes[0]).toInt(); i++){ + count += cachedCoins(amount-(i*coinTypes[0]),coinTypes.sublist(1)); // sublist(1) is like lisp's '(rest ...)' + } + + cache[key] = count; // add this to the cache + return(count); + } diff --git a/Task/Count-the-coins/Elixir/count-the-coins.elixir b/Task/Count-the-coins/Elixir/count-the-coins.elixir index a32ea6a84f..89b2805b2c 100644 --- a/Task/Count-the-coins/Elixir/count-the-coins.elixir +++ b/Task/Count-the-coins/Elixir/count-the-coins.elixir @@ -1,6 +1,6 @@ defmodule Coins do def find(coins,lim) do - vals = Enum.into(0..lim,Map.new,&{&1,0}) |> Map.put(0,1) + vals = Map.new(0..lim,&{&1,0}) |> Map.put(0,1) count(coins,lim,vals) |> Map.values |> Enum.max diff --git a/Task/Count-the-coins/Factor/count-the-coins.factor b/Task/Count-the-coins/Factor/count-the-coins-1.factor similarity index 100% rename from Task/Count-the-coins/Factor/count-the-coins.factor rename to Task/Count-the-coins/Factor/count-the-coins-1.factor diff --git a/Task/Count-the-coins/Factor/count-the-coins-2.factor b/Task/Count-the-coins/Factor/count-the-coins-2.factor new file mode 100644 index 0000000000..880df5dc5b --- /dev/null +++ b/Task/Count-the-coins/Factor/count-the-coins-2.factor @@ -0,0 +1,3 @@ +IN: scratchpad [ 100000 { 1 5 10 25 50 100 } make-change . ] time +13398445413854501 +Running time: 0.020869274 seconds diff --git a/Task/Count-the-coins/Factor/count-the-coins-3.factor b/Task/Count-the-coins/Factor/count-the-coins-3.factor new file mode 100644 index 0000000000..772a0db813 --- /dev/null +++ b/Task/Count-the-coins/Factor/count-the-coins-3.factor @@ -0,0 +1,20 @@ +USING: arrays locals math math.ranges sequences sets sorting ; +IN: rosetta-code.count-the-coins + + :> ways + 1 ways set-first + coins [| coin | + coin cents [a,b] [| j | + j coin - ways nth j ways [ + ] change-nth + ] each + ] each ways last ; + +PRIVATE> + +! How many ways can we make the given amount of cents +! with the given set of coins? +: make-change ( cents coins -- ways ) + members [ ] inv-sort-with (make-change) ; diff --git a/Task/Count-the-coins/Factor/count-the-coins-4.factor b/Task/Count-the-coins/Factor/count-the-coins-4.factor new file mode 100644 index 0000000000..011bf7080e --- /dev/null +++ b/Task/Count-the-coins/Factor/count-the-coins-4.factor @@ -0,0 +1,20 @@ +USE: math.ranges + +:: exchange-count ( seq val -- cnt ) + val 1 + 0 :> tab + 0 :> old! + 1 0 tab set-nth + seq length iota [ + seq nth old! + old val [a,b] [| j | + j old - tab nth + j tab nth + + j tab set-nth + ] each + ] each + val tab nth +; + +[ { 1 5 10 25 50 100 } 100000 exchange-count . ] time +13398445413854501 +Running time: 0.029163549 seconds diff --git a/Task/Count-the-coins/Haskell/count-the-coins-1.hs b/Task/Count-the-coins/Haskell/count-the-coins-1.hs index f4999213f6..0df002a135 100644 --- a/Task/Count-the-coins/Haskell/count-the-coins-1.hs +++ b/Task/Count-the-coins/Haskell/count-the-coins-1.hs @@ -1,5 +1,10 @@ +count :: (Integral t, Integral a) => t -> [t] -> a count 0 _ = 1 count _ [] = 0 -count x (c:coins) = sum [ count (x - (n * c)) coins | n <- [0..(quot x c)] ] +count x (c:coins) = + sum + [ count (x - (n * c)) coins + | n <- [0 .. (quot x c)] ] +main :: IO () main = print (count 100 [1, 5, 10, 25]) diff --git a/Task/Count-the-coins/Haskell/count-the-coins-2.hs b/Task/Count-the-coins/Haskell/count-the-coins-2.hs index 753c9195b3..9cc5193e63 100644 --- a/Task/Count-the-coins/Haskell/count-the-coins-2.hs +++ b/Task/Count-the-coins/Haskell/count-the-coins-2.hs @@ -1,7 +1,11 @@ -count = foldr addCoin (1:repeat 0) - where addCoin c oldlist = newlist - where newlist = (take c oldlist) ++ zipWith (+) newlist (drop c oldlist) +count :: Integral a => [Int] -> [a] +count = foldr addCoin (1 : repeat 0) + where + addCoin c oldlist = newlist + where + newlist = take c oldlist ++ zipWith (+) newlist (drop c oldlist) +main :: IO () main = do - print (count [25,10,5,1] !! 100) - print (count [100,50,25,10,5,1] !! 100000) + print (count [25, 10, 5, 1] !! 100) + print (count [100, 50, 25, 10, 5, 1] !! 10000) diff --git a/Task/Count-the-coins/Haskell/count-the-coins-3.hs b/Task/Count-the-coins/Haskell/count-the-coins-3.hs new file mode 100644 index 0000000000..e6aafd62d3 --- /dev/null +++ b/Task/Count-the-coins/Haskell/count-the-coins-3.hs @@ -0,0 +1,20 @@ +import Data.Function (fix) + +count :: Integral a => [Int] -> [a] +count = + foldr + (\x a -> + let (l, r) = splitAt x a + in fix (mappend l . flip (zipWith (+)) r)) + (1 : repeat 0) + + +-- TEST ----------------------------------------------------------------------- +main :: IO () +main = + mapM_ + (print . uncurry ((!!) . count)) + [ ([25, 10, 5, 1], 100) + , ([100, 50, 25, 10, 5, 1], 10000) + , ([100, 50, 25, 10, 5, 1], 1000000) + ] diff --git a/Task/Count-the-coins/J/count-the-coins-4.j b/Task/Count-the-coins/J/count-the-coins-4.j new file mode 100644 index 0000000000..02c443ff50 --- /dev/null +++ b/Task/Count-the-coins/J/count-the-coins-4.j @@ -0,0 +1,9 @@ + init =: 4 : '(1+x)$1' +length1 =: 4 : '1=#y' + f =: 4 : ',/ +/\ (-x) ]\ y' + + 1000 { f ` init @. length1 / 1000 500 200 100 50 20 10 5 2 , 1000 0 +327631322 + +NB. this is a foldLeft once initialised the intermediate right arguments are arrays + 1000 f 500 f 200 f 100 f 50 f 20 f 10 f 5 f 2 f (1000 init 0) diff --git a/Task/Count-the-coins/JavaScript/count-the-coins-1.js b/Task/Count-the-coins/JavaScript/count-the-coins-1.js index 035091897e..2421130528 100644 --- a/Task/Count-the-coins/JavaScript/count-the-coins-1.js +++ b/Task/Count-the-coins/JavaScript/count-the-coins-1.js @@ -1,19 +1,19 @@ function countcoins(t, o) { - 'use strict'; - var targetsLength = t + 1; - var operandsLength = o.length; - t = [1]; + 'use strict'; + var targetsLength = t + 1; + var operandsLength = o.length; + t = [1]; - for (var a = 0; a < operandsLength; a ++) { - for (var b = 1; b < targetsLength; b ++) { + for (var a = 0; a < operandsLength; a++) { + for (var b = 1; b < targetsLength; b++) { - // initialise undefined target - t[b] = t[b] ? t[b] : 0; + // initialise undefined target + t[b] = t[b] ? t[b] : 0; - // accumulate target + operand ways - t[b] += (b < o[a]) ? 0 : t[b - o[a]]; - } - } + // accumulate target + operand ways + t[b] += (b < o[a]) ? 0 : t[b - o[a]]; + } + } - return t[targetsLength - 1]; + return t[targetsLength - 1]; } diff --git a/Task/Count-the-coins/JavaScript/count-the-coins-3.js b/Task/Count-the-coins/JavaScript/count-the-coins-3.js index 53f1a9ef8e..05544062fd 100644 --- a/Task/Count-the-coins/JavaScript/count-the-coins-3.js +++ b/Task/Count-the-coins/JavaScript/count-the-coins-3.js @@ -1,25 +1,25 @@ function countcoins(t, o) { - 'use strict'; - var operandsLength = o.length; - var solutions = 0; + 'use strict'; + var operandsLength = o.length; + var solutions = 0; - function permutate(a, x) { + function permutate(a, x) { - // base case - if (a === t) { - solutions ++; - } + // base case + if (a === t) { + solutions++; + } - // recursive case - else if (a < t) { - for (var i = 0; i < operandsLength; i ++) { - if (i >= x) { - permutate(o[i] + a, i); - } - } - } - } + // recursive case + else if (a < t) { + for (var i = 0; i < operandsLength; i++) { + if (i >= x) { + permutate(o[i] + a, i); + } + } + } + } - permutate(0, 0); - return solutions; + permutate(0, 0); + return solutions; } diff --git a/Task/Count-the-coins/JavaScript/count-the-coins-5.js b/Task/Count-the-coins/JavaScript/count-the-coins-5.js index 12e49df156..98acf6facd 100644 --- a/Task/Count-the-coins/JavaScript/count-the-coins-5.js +++ b/Task/Count-the-coins/JavaScript/count-the-coins-5.js @@ -1,6 +1,8 @@ -var amount=100, coin=[1,5,10,25] -var t=[1]; for (t[amount]=0, a=1; a) { + val c = intArrayOf(1, 5, 10, 25, 50, 100) + println(countCoins(c, 4, 100)) + println(countCoins(c, 6, 1000 * 100)) +} diff --git a/Task/Count-the-coins/Phix/count-the-coins-1.phix b/Task/Count-the-coins/Phix/count-the-coins-1.phix new file mode 100644 index 0000000000..7a0621644d --- /dev/null +++ b/Task/Count-the-coins/Phix/count-the-coins-1.phix @@ -0,0 +1,10 @@ +function coin_count(sequence coins, integer amount) + sequence s = repeat(0,amount+1) + s[1] = 1 + for c=1 to length(coins) do + for n=coins[c] to amount do + s[n+1] += s[n-coins[c]+1] + end for + end for + return s[amount+1] +end function diff --git a/Task/Count-the-coins/Phix/count-the-coins-2.phix b/Task/Count-the-coins/Phix/count-the-coins-2.phix new file mode 100644 index 0000000000..512c195fe9 --- /dev/null +++ b/Task/Count-the-coins/Phix/count-the-coins-2.phix @@ -0,0 +1,44 @@ +function coin_count(sequence coins, integer amount) + -- start with 1 known way to achieve 0 (being no coins) + -- (nb: s[1] holds the solution for 0, s[n+1] for n) + sequence s = repeat(0,amount+1) + s[1] = 1 + -- then for every coin that we can use, increase number of + -- solutions by that previously found for the remainder. + for c=1 to length(coins) do + -- this inner loop is essentially behaving as if we had + -- called this routine with 1..amount, but skipping any + -- less than the coin's value, hence coins[c]..amount. + for n=coins[c] to amount do + s[n+1] += s[n-coins[c]+1] + end for + end for + return s[amount+1] +end function + +-- The key to understanding the above is to try a dry run of this: +printf(1,"%d\n",coin_count({2,3},5)) -- (prints 1) +-- You'll need 4 2p coins, 3 3p coins, and 5 spaces marked 1..5. +-- Place 2p wherever it fits: 1:0 2:1 3:1 4:1 5:1 +-- Add previously found solns: +0 +1 +0 +1 +0 [1] +-- Place 3p wherever it fits: 1:0 2:0 3:1 4:1 5:1 +-- Add previously found solns: +0 +0 +1 +0 +1 [2] +-- [1] obviously at 2: we added the base soln for amount=0, +-- and at 4: we added the previously found soln for 2. +-- also note that we added nothing for 2p+3p, yet, that +-- fact is central to understanding why this works. [3] +-- [2] obviously at 3: we added the base soln for amount=0, +-- at 4: we added the zero solutions yet found for 1p, +-- and at 5: we added the previously found soln for 2. +-- you can imagine at 6,9,12 etc all add in soln for 3, +-- albeit by adding that as just added to the precessor. +-- [3] since we add no 3p solns when processing 2p, we do +-- not count 2p+3p and 3p+2p as two solutions. + +--For N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. +printf(1,"%d\n",coin_count({1,2,3},4)) +--For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. +printf(1,"%d\n\n",coin_count({2,3,5,6},10)) + +printf(1,"%d\n",coin_count({25, 10, 5, 1},1_00)) +printf(1,"%,d\n",coin_count({100, 50, 25, 10, 5, 1},1000_00)) diff --git a/Task/Count-the-coins/Ring/count-the-coins.ring b/Task/Count-the-coins/Ring/count-the-coins.ring new file mode 100644 index 0000000000..f7b2ad7279 --- /dev/null +++ b/Task/Count-the-coins/Ring/count-the-coins.ring @@ -0,0 +1,19 @@ +penny = 1 +nickel = 1 +dime = 1 +quarter = 1 +count = 0 + +for penny = 0 to 100 + for nickel = 0 to 20 + for dime = 0 to 10 + for quarter = 0 to 4 + if (penny + nickel * 5 + dime * 10 + quarter * 25) = 100 + see "" + penny + " pennies " + nickel + " nickels " + dime + " dimes " + quarter + " quarters" + nl + count = count + 1 + ok + next + next + next +next +see count + " ways to make a dollar" + nl diff --git a/Task/Count-the-coins/Rust/count-the-coins.rust b/Task/Count-the-coins/Rust/count-the-coins.rust new file mode 100644 index 0000000000..37edafe493 --- /dev/null +++ b/Task/Count-the-coins/Rust/count-the-coins.rust @@ -0,0 +1,16 @@ +fn make_change(coins: &[usize], cents: usize) -> usize { + let size = cents + 1; + let mut ways = vec![0; size]; + ways[0] = 1; + for &coin in coins { + for amount in coin..size { + ways[amount] += ways[amount - coin]; + } + } + ways[cents] +} + +fn main() { + println!("{}", make_change(&[1,5,10,25], 100)); + println!("{}", make_change(&[1,5,10,25,50,100], 100000)); +} diff --git a/Task/Count-the-coins/Scilab/count-the-coins-1.scilab b/Task/Count-the-coins/Scilab/count-the-coins-1.scilab new file mode 100644 index 0000000000..1de4e3a092 --- /dev/null +++ b/Task/Count-the-coins/Scilab/count-the-coins-1.scilab @@ -0,0 +1,22 @@ +amount=100; +coins=[25 10 5 1]; +n_coins=zeros(coins); +ways=0; + +for a=0:4 + for b=0:10 + for c=0:20 + for d=0:100 + n_coins=[a b c d]; + change=sum(n_coins.*coins); + if change==amount then + ways=ways+1; + elseif change>amount + break + end + end + end + end +end + +disp(ways); diff --git a/Task/Count-the-coins/Scilab/count-the-coins-2.scilab b/Task/Count-the-coins/Scilab/count-the-coins-2.scilab new file mode 100644 index 0000000000..9f751f6d81 --- /dev/null +++ b/Task/Count-the-coins/Scilab/count-the-coins-2.scilab @@ -0,0 +1,15 @@ +function varargout=changes(amount, coins) + ways = zeros(1,amount + 2); + ways(1) = 1; + for coin=coins + for j=coin:(amount+1) + ways(j+1) = ways(j+1) + ways(j + 1 - coin); + end + end + + varargout=list(ways(length(ways))) +endfunction + +a=changes(100, [1, 5, 10, 25]); +b=changes(100000, [1, 5, 10, 25, 50, 100]); +mprintf("%.0f, %.0f", a, b); diff --git a/Task/Count-the-coins/Zkl/count-the-coins-1.zkl b/Task/Count-the-coins/Zkl/count-the-coins-1.zkl new file mode 100644 index 0000000000..85b72d97bb --- /dev/null +++ b/Task/Count-the-coins/Zkl/count-the-coins-1.zkl @@ -0,0 +1,7 @@ +fcn ways_to_make_change(x, coins=T(25,10,5,1)){ + if(not coins) return(0); + if(x<0) return(0); + if(x==0) return(1); + ways_to_make_change(x, coins[1,*]) + ways_to_make_change(x - coins[0], coins) +} +ways_to_make_change(100).println(); diff --git a/Task/Count-the-coins/Zkl/count-the-coins-2.zkl b/Task/Count-the-coins/Zkl/count-the-coins-2.zkl new file mode 100644 index 0000000000..77e2adf5c8 --- /dev/null +++ b/Task/Count-the-coins/Zkl/count-the-coins-2.zkl @@ -0,0 +1,12 @@ +fcn make_change2(amount, coins){ + n, m := amount, coins.len(); + table := (0).pump(n+1,List, (0).pump(m,List().write,1).copy); + foreach i,j in ([1..n],[0..m-1]){ + table[i][j] = (if(i) { + val lp0 = FileWriter("/dev/tape") + lp0.write("Hello, world!") + lp0.close() +} diff --git a/Task/Create-a-file/BASIC/create-a-file.basic b/Task/Create-a-file/BASIC/create-a-file-1.basic similarity index 100% rename from Task/Create-a-file/BASIC/create-a-file.basic rename to Task/Create-a-file/BASIC/create-a-file-1.basic diff --git a/Task/Create-a-file/BASIC/create-a-file-2.basic b/Task/Create-a-file/BASIC/create-a-file-2.basic new file mode 100644 index 0000000000..fd4af22f96 --- /dev/null +++ b/Task/Create-a-file/BASIC/create-a-file-2.basic @@ -0,0 +1,23 @@ +' Create file and dir +TRAP LOCAL + +OPEN "output.txt" FOR WRITING AS afile +CLOSE FILE afile + +CATCH GOTO report +OPEN "/output.txt" FOR WRITING AS afile +CLOSE FILE afile + +LABEL trydir +MAKEDIR "docs" + +CATCH GOTO report2 +MAKEDIR "/docs" +END + +LABEL report + PRINT ERR$(ERROR) + GOTO trydir + +LABEL report2 + PRINT ERR$(ERROR) diff --git a/Task/Create-a-file/Component-Pascal/create-a-file.component b/Task/Create-a-file/Component-Pascal/create-a-file.component new file mode 100644 index 0000000000..cb63018727 --- /dev/null +++ b/Task/Create-a-file/Component-Pascal/create-a-file.component @@ -0,0 +1,18 @@ +MODULE CreateFile; +IMPORT Files, StdLog; + +PROCEDURE Do*; +VAR + f: Files.File; + res: INTEGER; +BEGIN + f := Files.dir.New(Files.dir.This("docs"),Files.dontAsk); + f.Register("output","txt",TRUE,res); + f.Close(); + + f := Files.dir.New(Files.dir.This("C:\AEAT\docs"),Files.dontAsk); + f.Register("output","txt",TRUE,res); + f.Close() +END Do; + +END CreateFile. diff --git a/Task/Create-a-file/Elena/create-a-file.elena b/Task/Create-a-file/Elena/create-a-file.elena index aee912b68f..b244f44c37 100644 --- a/Task/Create-a-file/Elena/create-a-file.elena +++ b/Task/Create-a-file/Elena/create-a-file.elena @@ -1,13 +1,12 @@ -#import system. -#import system'io. +import system'io. -#symbol program = +program = [ - "output.txt" file_path textwriter close. + File new:"output.txt"; textwriter; close. - "\output.txt" file_path textwriter close. + File new:"\output.txt"; textwriter; close. - "docs" directory_path create. + Directory new:"docs"; create. - "\docs" directory_path create. + Directory new:"\docs"; create. ]. diff --git a/Task/Create-a-file/Friendly-interactive-shell/create-a-file.fish b/Task/Create-a-file/Friendly-interactive-shell/create-a-file.fish new file mode 100644 index 0000000000..6e3f57b4d9 --- /dev/null +++ b/Task/Create-a-file/Friendly-interactive-shell/create-a-file.fish @@ -0,0 +1,2 @@ +touch {/,}output.txt # create both /output.txt and output.txt +mkdir {/,}docs # create both /docs and docs diff --git a/Task/Create-a-file/Gambas/create-a-file.gambas b/Task/Create-a-file/Gambas/create-a-file.gambas new file mode 100644 index 0000000000..ce44976c48 --- /dev/null +++ b/Task/Create-a-file/Gambas/create-a-file.gambas @@ -0,0 +1 @@ +File.Save(User.home &/ "FileToSave", "Put this text in a file") diff --git a/Task/Create-a-file/Kotlin/create-a-file.kotlin b/Task/Create-a-file/Kotlin/create-a-file.kotlin new file mode 100644 index 0000000000..625e7bb16e --- /dev/null +++ b/Task/Create-a-file/Kotlin/create-a-file.kotlin @@ -0,0 +1,24 @@ +/* testing on Windows 10 which needs administrative privileges + to create files in the root */ + +import java.io.File + +fun main(args: Array) { + val filePaths = arrayOf("output.txt", "c:\\output.txt") + val dirPaths = arrayOf("docs", "c:\\docs") + var f: File + for (path in filePaths) { + f = File(path) + if (f.createNewFile()) + println("$path successfully created") + else + println("$path already exists") + } + for (path in dirPaths) { + f = File(path) + if (f.mkdir()) + println("$path successfully created") + else + println("$path already exists") + } +} diff --git a/Task/Create-a-file/Rust/create-a-file.rust b/Task/Create-a-file/Rust/create-a-file.rust new file mode 100644 index 0000000000..826380cd5b --- /dev/null +++ b/Task/Create-a-file/Rust/create-a-file.rust @@ -0,0 +1,26 @@ +use std::io::{self, Write}; +use std::fs::{DirBuilder, File}; +use std::path::Path; +use std::{process,fmt}; + +const FILE_NAME: &'static str = "output.txt"; +const DIR_NAME : &'static str = "docs"; + +fn main() { + create(".").and(create("/")) + .unwrap_or_else(|e| error_handler(e,1)); +} + + +fn create

    (root: P) -> io::Result + where P: AsRef +{ + let f_path = root.as_ref().join(FILE_NAME); + let d_path = root.as_ref().join(DIR_NAME); + DirBuilder::new().create(d_path).and(File::create(f_path)) +} + +fn error_handler(error: E, code: i32) -> ! { + let _ = writeln!(&mut io::stderr(), "Error: {}", error); + process::exit(code) +} diff --git a/Task/Create-a-file/Stata/create-a-file.stata b/Task/Create-a-file/Stata/create-a-file.stata new file mode 100644 index 0000000000..989b6ce13e --- /dev/null +++ b/Task/Create-a-file/Stata/create-a-file.stata @@ -0,0 +1,7 @@ +file open f using output.txt, write replace +file close f +mkdir docs + +file open f using \output.txt, write replace +file close f +mkdir \docs diff --git a/Task/Create-a-file/Zkl/create-a-file.zkl b/Task/Create-a-file/Zkl/create-a-file.zkl new file mode 100644 index 0000000000..82659368ee --- /dev/null +++ b/Task/Create-a-file/Zkl/create-a-file.zkl @@ -0,0 +1,18 @@ +$ ls -l docs +ls: cannot access docs: No such file or directory +$ zkl +zkl: fcn createOutputTxt(dir){ dir=dir+"/docs"; File.mkdir(dir); File(dir+"/output.txt","w") } +Void +zkl: createOutputTxt(".") +File(./docs/output.txt) +zkl: createOutputTxt("/") +Stack trace for VM#1 (): + Cmd.createOutputTxt@mkdir addr:16 args(1) reg(0) + Cmd.__constructor@createOutputTxt addr:9 args(0) reg(0) R + startup.__constructor addr:2271 args(0) reg(1) ER + startup.__constructor addr:2207 args(0) reg(22) +Exception thrown: IOError(File.mkdir(//docs): Permission denied) +zkl: ^D +$ ls -l docs +total 0 +-rw-r--r-- 1 craigd craigd 0 Oct 27 22:08 output.txt diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-1.elena b/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-1.elena index a8c7bbaca4..0cc6065430 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-1.elena +++ b/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-1.elena @@ -1,17 +1,16 @@ -#import system. -#import extensions. +import extensions. -#symbol program = +program = [ - #var n := Integer new. - #var m := Integer new. + var n := Integer new. + var m := Integer new. - console write:"Enter two space delimited integers:". - console readLine:n:m. + console write:"Enter two space delimited integers:". + console readLine(n,m). - #var myArray := RealMatrix new:n:m. + var myArray := RealMatrix new(n,m). - myArray@0@0 := 2. + myArray[0][0] := 2. - console writeLine:(myArray@0@0). + console printLine(myArray[0][0]). ]. diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-2.elena b/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-2.elena index be7f190528..be82f65b57 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-2.elena +++ b/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-2.elena @@ -1,19 +1,18 @@ -#import system. -#import system'routines. -#import extensions. +import system'routines. +import extensions. -#symbol program = +program = [ - #var n := Integer new. - #var m := Integer new. + var n := Integer new. + var m := Integer new. - console write:"Enter two space delimited integers:". - console readLine:n:m. + console write:"Enter two space delimited integers:". + console readLine(n,m). - #var myArray2 := Array new:n set &every:(&index:i) [ Array new:m ]. - myArray2@0@0 := 2. - myArray2@1@0 := "Hello". + var myArray2 := Array new:n; populate(:i)( Array new:m ). + myArray2[0][0] := 2. + myArray2[1][0] := "Hello". - console writeLine:(myArray2@0@0). - console writeLine:(myArray2@1@0). + console printLine(myArray2[0][0]). + console printLine(myArray2[1][0]). ]. diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Haskell/create-a-two-dimensional-array-at-runtime.hs b/Task/Create-a-two-dimensional-array-at-runtime/Haskell/create-a-two-dimensional-array-at-runtime.hs index 7e20ef96ec..116249a0fe 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/Haskell/create-a-two-dimensional-array-at-runtime.hs +++ b/Task/Create-a-two-dimensional-array-at-runtime/Haskell/create-a-two-dimensional-array-at-runtime.hs @@ -1 +1,3 @@ - doit n m = a!(0,0) where a = array ((0,0),(n,m)) [((0,0),42)] +import Data.Array + +doit n m = a!(0,0) where a = array ((0,0),(n,m)) [((0,0),42)] diff --git a/Task/Create-a-two-dimensional-array-at-runtime/jq/create-a-two-dimensional-array-at-runtime-1.jq b/Task/Create-a-two-dimensional-array-at-runtime/Jq/create-a-two-dimensional-array-at-runtime-1.jq similarity index 100% rename from Task/Create-a-two-dimensional-array-at-runtime/jq/create-a-two-dimensional-array-at-runtime-1.jq rename to Task/Create-a-two-dimensional-array-at-runtime/Jq/create-a-two-dimensional-array-at-runtime-1.jq diff --git a/Task/Create-a-two-dimensional-array-at-runtime/jq/create-a-two-dimensional-array-at-runtime-2.jq b/Task/Create-a-two-dimensional-array-at-runtime/Jq/create-a-two-dimensional-array-at-runtime-2.jq similarity index 100% rename from Task/Create-a-two-dimensional-array-at-runtime/jq/create-a-two-dimensional-array-at-runtime-2.jq rename to Task/Create-a-two-dimensional-array-at-runtime/Jq/create-a-two-dimensional-array-at-runtime-2.jq diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Kotlin/create-a-two-dimensional-array-at-runtime.kotlin b/Task/Create-a-two-dimensional-array-at-runtime/Kotlin/create-a-two-dimensional-array-at-runtime.kotlin index 0e6aa2f87d..aee0cce76c 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/Kotlin/create-a-two-dimensional-array-at-runtime.kotlin +++ b/Task/Create-a-two-dimensional-array-at-runtime/Kotlin/create-a-two-dimensional-array-at-runtime.kotlin @@ -1,7 +1,15 @@ fun main(args: Array) { - val dim = args.map { it.toInt() } // interpret - val array = Array(dim[0], { IntArray(dim[1]) } ) // build + // build + val dim = arrayOf(10, 15) + val array = Array(dim[0], { IntArray(dim[1]) } ) - array.forEachIndexed { i, it -> for (j in it.indices) it[j] = 1 + i + j } // fill - array.forEach { println(it.asList()) } // print + // fill + array.forEachIndexed { i, it -> + it.indices.forEach { j -> + it[j] = 1 + i + j + } + } + + // print + array.forEach { println(it.asList()) } } diff --git a/Task/Create-a-two-dimensional-array-at-runtime/OoRexx/create-a-two-dimensional-array-at-runtime.rexx b/Task/Create-a-two-dimensional-array-at-runtime/OoRexx/create-a-two-dimensional-array-at-runtime.rexx new file mode 100644 index 0000000000..3079bed9df --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/OoRexx/create-a-two-dimensional-array-at-runtime.rexx @@ -0,0 +1,11 @@ +Say "enter first dimension" +pull d1 +say "enter the second dimension" +pull d2 +a = .array~new(d1, d2) +a[1, 1] = "Abc" +say a[1, 1] +say d1 d2 a[d1,d2] +say a[10,10] +max=1000000000 +b = .array~new(max,max) diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Rust/create-a-two-dimensional-array-at-runtime.rust b/Task/Create-a-two-dimensional-array-at-runtime/Rust/create-a-two-dimensional-array-at-runtime.rust new file mode 100644 index 0000000000..e609400e0c --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Rust/create-a-two-dimensional-array-at-runtime.rust @@ -0,0 +1,28 @@ +use std::env; +fn main() { + let mut args = env::args().skip(1).flat_map(|num| num.parse()); + let rows = args.next().expect("Expected number of rows as first argument"); + let cols = args.next().expect("Expected number of columns as second argument"); + + assert!(rows != 0 && cols != 0); + + // Creates a vector of vectors with all elements initialized to 0. + let mut v = init_vec(rows, || init_vec(cols, || 0)); + v[0][0] = 1; + println!("{}", v[0][0]); + + +} + +// Returns a dynamically-allocated array of size `n`, +// initialized with the values computed by `f` + +fn init_vec(n: usize, f: F) -> Vec + where F: Fn() -> T +{ + let mut vec = Vec::with_capacity(n); + for _ in 0..n { + vec.push(f()); + } + vec +} diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Scheme/create-a-two-dimensional-array-at-runtime-1.ss b/Task/Create-a-two-dimensional-array-at-runtime/Scheme/create-a-two-dimensional-array-at-runtime-1.ss new file mode 100644 index 0000000000..22dafa5577 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Scheme/create-a-two-dimensional-array-at-runtime-1.ss @@ -0,0 +1,24 @@ +(import (scheme base) + (scheme read) + (scheme write)) + +;; Read x/y from user +(define x (begin (display "X: ") (flush-output-port) (read))) +(define y (begin (display "Y: ") (flush-output-port) (read))) + +;; Create a vector, and fill it with a vector for each row +(define arr (make-vector x)) +(do ((i 0 (+ 1 i))) + ((= i x) ) + (vector-set! arr i (make-vector y 0))) + +;; set element (x/2, y/2) to 3 +(vector-set! (vector-ref arr (floor (/ x 2))) + (floor (/ y 2)) + 3) + +(display arr) (newline) +(display "Retrieved: ") +(display (vector-ref (vector-ref arr (floor (/ x 2))) + (floor (/ y 2)))) +(newline) diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Scheme/create-a-two-dimensional-array-at-runtime-2.ss b/Task/Create-a-two-dimensional-array-at-runtime/Scheme/create-a-two-dimensional-array-at-runtime-2.ss new file mode 100644 index 0000000000..5196b68c0c --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Scheme/create-a-two-dimensional-array-at-runtime-2.ss @@ -0,0 +1,18 @@ +(import (except (scheme base) equal?) + (scheme read) + (scheme write) + (srfi 63) ; an array SRFI + ) + +;; Read x/y from user +(define x (begin (display "X: ") (flush-output-port) (read))) +(define y (begin (display "Y: ") (flush-output-port) (read))) + +;; Create an array +(define array (make-array #(0) x y)) + +;; Write to middle element of the array +(array-set! array 3 (floor (/ x 2)) (floor (/ y 2))) + +;; Retrieve and display result +(display (array-ref array (floor (/ x 2)) (floor (/ y 2)))) (newline) diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Stata/create-a-two-dimensional-array-at-runtime-1.stata b/Task/Create-a-two-dimensional-array-at-runtime/Stata/create-a-two-dimensional-array-at-runtime-1.stata new file mode 100644 index 0000000000..3b8d7a8c6e --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Stata/create-a-two-dimensional-array-at-runtime-1.stata @@ -0,0 +1,6 @@ +display "Number of rows?" _request(nr) +display "Number of columns?" _request(nc) +matrix define a=J($nr,$nc,0) +matrix a[1,2]=1.5 +matrix list a +matrix drop a diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Stata/create-a-two-dimensional-array-at-runtime-2.stata b/Task/Create-a-two-dimensional-array-at-runtime/Stata/create-a-two-dimensional-array-at-runtime-2.stata new file mode 100644 index 0000000000..81d2ea9492 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Stata/create-a-two-dimensional-array-at-runtime-2.stata @@ -0,0 +1,8 @@ +mata +mata stata display "Number of rows?" _request(nr) +mata stata display "Number of columns?" _request(nc) +a=J($nr,$nc,0) +a[1,2]=1.5 +a +mata drop a +end diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Zkl/create-a-two-dimensional-array-at-runtime-1.zkl b/Task/Create-a-two-dimensional-array-at-runtime/Zkl/create-a-two-dimensional-array-at-runtime-1.zkl new file mode 100644 index 0000000000..ffb3347a41 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Zkl/create-a-two-dimensional-array-at-runtime-1.zkl @@ -0,0 +1,6 @@ +rows:=ask("Rows: ").toInt(); +cols:=ask("columns: ").toInt(); +array:=rows.pump(List.createLong(rows),List.createLong(cols,0).copy); +array[1][2]=123; +array.println(); +array[1][2].println(); diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Zkl/create-a-two-dimensional-array-at-runtime-2.zkl b/Task/Create-a-two-dimensional-array-at-runtime/Zkl/create-a-two-dimensional-array-at-runtime-2.zkl new file mode 100644 index 0000000000..7c0e2e2abb --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Zkl/create-a-two-dimensional-array-at-runtime-2.zkl @@ -0,0 +1,7 @@ +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +rows:=ask("Rows: ").toInt(); +cols:=ask("columns: ").toInt(); +m:=GSL.Matrix(rows,cols); +m[1,2]=123; +m.format().println(); +println(m[1,2]); diff --git a/Task/Create-an-HTML-table/360-Assembly/create-an-html-table.360 b/Task/Create-an-HTML-table/360-Assembly/create-an-html-table.360 new file mode 100644 index 0000000000..e53d6c810e --- /dev/null +++ b/Task/Create-an-HTML-table/360-Assembly/create-an-html-table.360 @@ -0,0 +1,63 @@ +* Create an HTML table 19/02/2017 +CREHTML CSECT + USING CREHTML,R13 + B 72(R15) + DC 17F'0' + STM R14,R12,12(R13) + ST R13,4(R15) + ST R15,8(R13) + LR R13,R15 end of prolog + LA R8,RND + XPRNT PGBODY,64 + XPRNT PGTAB,64 + SR R6,R6 row=0 + DO WHILE=(C,R6,LE,NROWS) do row=0 to nrows + IF LTR,R6,Z,R6 THEN if row=0 + XPRNT PGTRTH,64 + ELSE , else + XDECO R6,XDEC edit row + MVC PGTR+8(1),XDEC+11 output row heading + XPRNT PGTR,64 + ENDIF , endif + LA R7,1 col=1 + DO WHILE=(C,R7,LE,NCOLS) do col=1 to ncols + IF LTR,R6,Z,R6 THEN if row=0 + LR R1,R7 col + LA R4,TCAR-1(R1) tcar(col) + MVC PGTH+4(1),0(R4) output heading + XPRNT PGTH,64 + ELSE , else + L R2,0(R8) value + XDECO R2,XDEC edit value + MVC PGTD+18(4),XDEC+8 output cell value + XPRNT PGTD,64 + LA R8,4(R8) next value + ENDIF , endif + LA R7,1(R7) col++ + ENDDO , enddo col + XPRNT PGETR,64 + LA R6,1(R6) row++ + ENDDO , enddo row + XPRNT PGETAB,64
    ......
    + XPRNT PGEBODY,64 + L R13,4(0,R13) epilog + LM R14,R12,12(R13) + XR R15,R15 + BR R14 exit +NROWS DC F'4' number of rows +NCOLS DC F'3' number of columns +TCAR DC CL3'XYZ' +RND DC F'7055',F'5334',F'5795',F'2895',F'3019',F'7747' + DC F'140',F'7607',F'8144',F'7090',F'475',F'4140' +PGBODY DC CL64'' +PGTAB DC CL64'' +PGTRTH DC CL64'' +PGTH DC CL64'' +PGETR DC CL64'' +PGTR DC CL64'' +PGTD DC CL64'' +PGETAB DC CL64'
    .
    .....
    ' +PGEBODY DC CL64'' +XDEC DS CL12 + YREGS + END CREHTML diff --git a/Task/Create-an-HTML-table/AWK/create-an-html-table-1.awk b/Task/Create-an-HTML-table/AWK/create-an-html-table-1.awk deleted file mode 100644 index 6cb7bdde87..0000000000 --- a/Task/Create-an-HTML-table/AWK/create-an-html-table-1.awk +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/awk -f -BEGIN { - print "\n " - printf " \n \n \n" - for (i=1; i<=10; i++) { - printf " \n",i, 10*i, 100*i, 1000*i-1 - } - print " \n
    XYZ
    %2i%5i%5i%5i
    \n" -} diff --git a/Task/Create-an-HTML-table/AWK/create-an-html-table-2.awk b/Task/Create-an-HTML-table/AWK/create-an-html-table-2.awk deleted file mode 100644 index 6c70b9b6f7..0000000000 --- a/Task/Create-an-HTML-table/AWK/create-an-html-table-2.awk +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - -
    XYZ
    1 10 100 999
    2 20 200 1999
    3 30 300 2999
    4 40 400 3999
    5 50 500 4999
    6 60 600 5999
    7 70 700 6999
    8 80 800 7999
    9 90 900 8999
    10 100 1000 9999
    diff --git a/Task/Create-an-HTML-table/Batch-File/create-an-html-table.bat b/Task/Create-an-HTML-table/Batch-File/create-an-html-table.bat new file mode 100644 index 0000000000..8b237f3dad --- /dev/null +++ b/Task/Create-an-HTML-table/Batch-File/create-an-html-table.bat @@ -0,0 +1,39 @@ +@echo off +setlocal enabledelayedexpansion + +:: It's easier and neater to create the variables holding the random 4 digit numbers ahead of time +for /l %%i in (1,1,12) do set /a rand%%i=!random! %% 9999 + +:: The command output of everything within the brackets is sent to the file "table.html", overwriting anything already in there +( + echo ^^^^ + echo ^ + echo ^^^ + echo ^X^ + echo ^Y^ + echo ^Z^ + echo ^ + echo ^^1^ + echo ^" <> + Enum.map_join(1..3, fn _ -> + "" + end) <> "\n" + end) + end + + def create_table(n\\3) do + "
    %rand1%^ + echo ^%rand2%^ + echo ^%rand3%^ + echo ^ + echo ^^2^ + echo ^%rand4%^ + echo ^%rand5%^ + echo ^%rand6%^ + echo ^ + echo ^^3^ + echo ^%rand7%^ + echo ^%rand8%^ + echo ^%rand9%^ + echo ^ + echo ^^4^ + echo ^%rand10%^ + echo ^%rand11%^ + echo ^%rand12%^ + echo ^ + echo ^ + echo ^^ +) > table.html +start table.html diff --git a/Task/Create-an-HTML-table/Elixir/create-an-html-table-1.elixir b/Task/Create-an-HTML-table/Elixir/create-an-html-table-1.elixir new file mode 100644 index 0000000000..d5694c6b27 --- /dev/null +++ b/Task/Create-an-HTML-table/Elixir/create-an-html-table-1.elixir @@ -0,0 +1,19 @@ +defmodule Table do + defp put_rows(n) do + Enum.map_join(1..n, fn i -> + "
    #{i}#{:rand.uniform(2000)}
    \n" <> + "\n" <> + put_rows(n) <> + "
    XYZ
    " + end +end + +IO.puts Table.create_table diff --git a/Task/Create-an-HTML-table/Elixir/create-an-html-table-2.elixir b/Task/Create-an-HTML-table/Elixir/create-an-html-table-2.elixir new file mode 100644 index 0000000000..39d2860ad9 --- /dev/null +++ b/Task/Create-an-HTML-table/Elixir/create-an-html-table-2.elixir @@ -0,0 +1,6 @@ + + + + + +
    XYZ
    113621289357
    2116113451176
    339162609
    diff --git a/Task/Create-an-HTML-table/Haskell/create-an-html-table.hs b/Task/Create-an-HTML-table/Haskell/create-an-html-table.hs index 91bc35436a..2fc67bdf91 100644 --- a/Task/Create-an-HTML-table/Haskell/create-an-html-table.hs +++ b/Task/Create-an-HTML-table/Haskell/create-an-html-table.hs @@ -1,20 +1,27 @@ -#!/usr/bin/runhaskell - +import Data.List (unfoldr) import Control.Monad (forM_) -import System.Random -import Data.List as L -import Text.Blaze.Html5 -import Text.Blaze.Html.Renderer.Pretty +import qualified Text.Blaze.Html5 as B +import Text.Blaze.Html.Renderer.Pretty (renderHtml) -makeTable :: RandomGen g => [String] -> Int -> g -> Html +import System.Random (RandomGen, getStdGen, randomRs, split) + +makeTable + :: RandomGen g + => [String] -> Int -> g -> B.Html makeTable headings nRows gen = - table $ do - thead $ tr $ forM_ (L.map toHtml headings) th - tbody $ forM_ (zip [1 .. nRows] $ unfoldr (Just . split) gen) - (\(x,g) -> tr $ forM_ (take (length headings) - (x:randomRs (1000,9999) g)) (td . toHtml)) + B.table $ + do B.thead $ B.tr $ forM_ (B.toHtml <$> headings) B.th + B.tbody $ + forM_ + (zip [1 .. nRows] $ unfoldr (Just . split) gen) + (\(x, g) -> + B.tr $ + forM_ + (take (length headings) (x : randomRs (1000, 9999) g)) + (B.td . B.toHtml)) +main :: IO () main = do g <- getStdGen putStrLn $ renderHtml $ makeTable ["", "X", "Y", "Z"] 3 g diff --git a/Task/Create-an-HTML-table/jq/create-an-html-table-1.jq b/Task/Create-an-HTML-table/Jq/create-an-html-table-1.jq similarity index 100% rename from Task/Create-an-HTML-table/jq/create-an-html-table-1.jq rename to Task/Create-an-HTML-table/Jq/create-an-html-table-1.jq diff --git a/Task/Create-an-HTML-table/jq/create-an-html-table-2.jq b/Task/Create-an-HTML-table/Jq/create-an-html-table-2.jq similarity index 100% rename from Task/Create-an-HTML-table/jq/create-an-html-table-2.jq rename to Task/Create-an-HTML-table/Jq/create-an-html-table-2.jq diff --git a/Task/Create-an-HTML-table/jq/create-an-html-table-3.jq b/Task/Create-an-HTML-table/Jq/create-an-html-table-3.jq similarity index 100% rename from Task/Create-an-HTML-table/jq/create-an-html-table-3.jq rename to Task/Create-an-HTML-table/Jq/create-an-html-table-3.jq 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.kotlin new file mode 100644 index 0000000000..e35b33cfe8 --- /dev/null +++ b/Task/Create-an-HTML-table/Kotlin/create-an-html-table-1.kotlin @@ -0,0 +1,31 @@ +// version 1.1.3 + +import java.util.Random + +fun main(args: Array) { + val r = Random() + val sb = StringBuilder() + val i = " " // indent + with (sb) { + append("\n\n") + append("\n\n\n") + append("\n") + append("$i\n") + append("$i$i") + for (c in 'X'..'Z') append("") + append("\n") + append("$i\n") + append("$i\n") + val f = "$i$i\n" + for (j in 1..4) { + append(f.format(j, r.nextInt(10000), r.nextInt(10000), r.nextInt(10000))) + } + append("$i\n") + append("
    $c
    %d%d%d%d
    \n") + append("\n") + } + println(sb.toString()) +} 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.kotlin new file mode 100644 index 0000000000..8224be23b0 --- /dev/null +++ b/Task/Create-an-HTML-table/Kotlin/create-an-html-table-2.kotlin @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + +
    XYZ
    1144434512568
    28763866824
    3271038458089
    4648078859246
    + + diff --git a/Task/Create-an-HTML-table/Protium/create-an-html-table.protium b/Task/Create-an-HTML-table/Protium/create-an-html-table.protium deleted file mode 100644 index 45b01ab02e..0000000000 --- a/Task/Create-an-HTML-table/Protium/create-an-html-table.protium +++ /dev/null @@ -1,17 +0,0 @@ -<@ 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 - - -|Number Table 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.rust new file mode 100644 index 0000000000..47b8b33532 --- /dev/null +++ b/Task/Create-an-HTML-table/Rust/create-an-html-table-1.rust @@ -0,0 +1,21 @@ +extern crate rand; + +use rand::Rng; + +fn random_cell() -> usize { + // Anything between 0 and 10000 has 4 digits or less + return rand::thread_rng().gen_range(0, 10000); +} + +fn main() { + println!(""); + + for row in 0..3 { + let x = random_cell(); + let y = random_cell(); + let z = random_cell(); + println!("", row, x, y, z); + } + + println!("
    XYZ
    {}{}{}{}
    "); +} 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.rust new file mode 100644 index 0000000000..9803f1e9bb --- /dev/null +++ b/Task/Create-an-HTML-table/Rust/create-an-html-table-2.rust @@ -0,0 +1,5 @@ + + + + +
    XYZ
    0710191113446
    14269518611
    296934194878
    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 new file mode 100644 index 0000000000..e0aac840d1 --- /dev/null +++ b/Task/Create-an-HTML-table/Stata/create-an-html-table-1.stata @@ -0,0 +1,37 @@ +program mat2html +local nr = rowsof(`1') +local nc = colsof(`1') +local rn `: rownames `1'' +local cn `: colnames `1'' +tempname f +qui file open `f' using `2', write text replace +file write `f' "" _n +file write `f' "" _n +file write `f' "" _n +file write `f' `""' _n +file write `f' "" _n +file write `f' "" _n +file write `f' `""' _n +* write column names +file write `f' "" _n +file write `f' "" _n +forv j = 1/`nc' { + 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' "
    `s'
    `s'`=el(`1',`i',`j')'
    " _n +file write `f' "" _n +file write `f' "" _n +file close `f' +end diff --git a/Task/Create-an-HTML-table/Stata/create-an-html-table-2.stata b/Task/Create-an-HTML-table/Stata/create-an-html-table-2.stata new file mode 100644 index 0000000000..65dc8ae958 --- /dev/null +++ b/Task/Create-an-HTML-table/Stata/create-an-html-table-2.stata @@ -0,0 +1,4 @@ +matrix a=2,9,4\7,5,3\6,1,8 +matrix rownames a = A B C +matrix colnames a = X Y Z +mat2html a magic.html diff --git a/Task/Create-an-HTML-table/Zkl/create-an-html-table.zkl b/Task/Create-an-HTML-table/Zkl/create-an-html-table.zkl new file mode 100644 index 0000000000..3552e49609 --- /dev/null +++ b/Task/Create-an-HTML-table/Zkl/create-an-html-table.zkl @@ -0,0 +1,9 @@ +table:=0'|| + ""; +table=Sink(table); +foreach n in ([1..3]){ + table.write("\n "); + foreach n in (3){ table.write(""); } + table.write(""); +} +table.write("\n
    XYZ
    ",n,"",(0).random(10000),"
    \n").close().print(); 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.kotlin new file mode 100644 index 0000000000..f1a5026646 --- /dev/null +++ b/Task/Create-an-object-at-a-given-address/Kotlin/create-an-object-at-a-given-address.kotlin @@ -0,0 +1,11 @@ +// Kotlin/Native Technology Preview + +import kotlinx.cinterop.* + +fun main(args: Array) { + val intVar = nativeHeap.alloc().apply { value = 42 } + with(intVar) { println("Value is $value, address is $rawPtr") } + intVar.value = 52 // create new value at this address + with(intVar) { println("Value is $value, address is $rawPtr") } + nativeHeap.free(intVar) +} 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.rust new file mode 100644 index 0000000000..f26a28ac11 --- /dev/null +++ b/Task/Create-an-object-at-a-given-address/Rust/create-an-object-at-a-given-address.rust @@ -0,0 +1,19 @@ +use std::{mem,ptr}; + +fn main() { + let mut data: i32; + + // Rust does not allow us to use uninitialized memory but the STL provides an `unsafe` + // function to override this protection. + unsafe {data = mem::uninitialized()} + + // Construct a raw pointer (perfectly safe) + let address = &mut data as *mut _; + + unsafe {ptr::write(address, 5)} + println!("{0:p}: {0}", &data); + + unsafe {ptr::write(address, 6)} + println!("{0:p}: {0}", &data); + +} diff --git a/Task/Currying/AppleScript/currying.applescript b/Task/Currying/AppleScript/currying.applescript index 35d4f75e61..53a845839e 100644 --- a/Task/Currying/AppleScript/currying.applescript +++ b/Task/Currying/AppleScript/currying.applescript @@ -1,18 +1,18 @@ -- curry :: (Script|Handler) -> Script on curry(f) script - on lambda(a) + on |λ|(a) script - on lambda(b) - lambda(a, b) of mReturn(f) - end lambda + on |λ|(b) + |λ|(a, b) of mReturn(f) + end |λ| end script - end lambda + end |λ| end script end curry --- TESTS +-- TESTS ---------------------------------------------------------------------- -- add :: Num -> Num -> Num on add(a, b) @@ -31,61 +31,36 @@ curry(add) -- Test 2. -curry(add)'s lambda(2) +curry(add)'s |λ|(2) --> «script» -- Test 3. -curry(add)'s lambda(2)'s lambda(3) +curry(add)'s |λ|(2)'s |λ|(3) --> 5 -- Test 4. -map(curry(product)'s lambda(7), range(1, 10)) +map(curry(product)'s |λ|(7), enumFromTo(1, 10)) --> {7, 14, 21, 28, 35, 42, 49, 56, 63, 70} -- Combined: {curry(add), ¬ - curry(add)'s lambda(2), ¬ - curry(add)'s lambda(2)'s lambda(3), ¬ - map(curry(product)'s lambda(7), range(1, 10))} + curry(add)'s |λ|(2), ¬ + curry(add)'s |λ|(2)'s |λ|(3), ¬ + map(curry(product)'s |λ|(7), enumFromTo(1, 10))} --> {«script», «script», 5, {7, 14, 21, 28, 35, 42, 49, 56, 63, 70}} +-- GENERIC FUNCTIONS ---------------------------------------------------------- --- GENERIC FUNCTIONS - --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn - --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map - --- range :: Int -> Int -> [Int] -on range(m, n) +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) if n < m then set d to -1 else @@ -96,4 +71,28 @@ on range(m, n) set end of lst to i end repeat return lst -end range +end enumFromTo + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn diff --git a/Task/Currying/D/currying.d b/Task/Currying/D/currying.d index 04563b47b6..fa4b742e01 100644 --- a/Task/Currying/D/currying.d +++ b/Task/Currying/D/currying.d @@ -5,7 +5,7 @@ void main() { return a + b; } - alias add2 = curry!(add, 2); + alias add2 = partial!(add, 2); writeln("Add 2 to 3: ", add(2, 3)); writeln("Add 2 to 3 (curried): ", add2(3)); } diff --git a/Task/Currying/Hy/currying-1.hy b/Task/Currying/Hy/currying-1.hy new file mode 100644 index 0000000000..742321ea28 --- /dev/null +++ b/Task/Currying/Hy/currying-1.hy @@ -0,0 +1,3 @@ +(defn addN [n] + (fn [x] + (+ x n))) diff --git a/Task/Currying/Hy/currying-2.hy b/Task/Currying/Hy/currying-2.hy new file mode 100644 index 0000000000..889498b317 --- /dev/null +++ b/Task/Currying/Hy/currying-2.hy @@ -0,0 +1,6 @@ +=> (setv add2 (addN 2)) +=> (add2 7) +9 + +=> ((addN 3) 4) +7 diff --git a/Task/Currying/Haskell/currying-6.hs b/Task/Currying/Hy/currying-3.hy similarity index 100% rename from Task/Currying/Haskell/currying-6.hs rename to Task/Currying/Hy/currying-3.hy diff --git a/Task/Currying/Java/currying.java b/Task/Currying/Java/currying-1.java similarity index 100% rename from Task/Currying/Java/currying.java rename to Task/Currying/Java/currying-1.java diff --git a/Task/Currying/Java/currying-2.java b/Task/Currying/Java/currying-2.java new file mode 100644 index 0000000000..646e78ed5a --- /dev/null +++ b/Task/Currying/Java/currying-2.java @@ -0,0 +1,34 @@ +import java.util.function.BiFunction; +import java.util.function.Function; + +public class Curry { + + //Curry a method + public static Function> curry(BiFunction biFunction) { + return t -> u -> biFunction.apply(t, u); + } + + public static int add(int x, int y) { + return x + y; + } + + public static void curryMethod() { + BiFunction bif = Curry::add; + Function> add = curry(bif); + Function add5 = add.apply(5); + System.out.println(add5.apply(2)); + } + + //Or declare the curried function in one line + public static void curryDirectly() { + Function> add = x -> y -> x + y; + Function add5 = add.apply(5); + System.out.println(add5.apply(2)); + } + + //prints 7 and 7 + public static void main(String[] args) { + curryMethod(); + curryDirectly(); + } +} diff --git a/Task/Currying/jq/currying-1.jq b/Task/Currying/Jq/currying-1.jq similarity index 100% rename from Task/Currying/jq/currying-1.jq rename to Task/Currying/Jq/currying-1.jq diff --git a/Task/Currying/jq/currying-2.jq b/Task/Currying/Jq/currying-2.jq similarity index 100% rename from Task/Currying/jq/currying-2.jq rename to Task/Currying/Jq/currying-2.jq diff --git a/Task/Currying/Julia/currying.julia b/Task/Currying/Julia/currying.julia new file mode 100644 index 0000000000..547dfdf598 --- /dev/null +++ b/Task/Currying/Julia/currying.julia @@ -0,0 +1,4 @@ +function addN(n::Number)::Function + adder(x::Number) = n + x + return adder +end diff --git a/Task/Currying/Kotlin/currying.kotlin b/Task/Currying/Kotlin/currying.kotlin new file mode 100644 index 0000000000..e86eab33e2 --- /dev/null +++ b/Task/Currying/Kotlin/currying.kotlin @@ -0,0 +1,10 @@ +// version 1.1.2 + +fun curriedAdd(x: Int) = { y: Int -> x + y } + +fun main(args: Array) { + val a = 2 + val b = 3 + val sum = curriedAdd(a)(b) + println("$a + $b = $sum") +} diff --git a/Task/Currying/Phix/currying.phix b/Task/Currying/Phix/currying.phix new file mode 100644 index 0000000000..2be41c2af1 --- /dev/null +++ b/Task/Currying/Phix/currying.phix @@ -0,0 +1,17 @@ +sequence curries = {} +function create_curried(integer rid, sequence partial_args) + curries = append(curries,{rid,partial_args}) + return length(curries) -- (return an integer id) +end function + +function call_curried(integer id, sequence args) + {integer rid, sequence partial_args} = curries[id] + return call_func(rid,partial_args&args) +end function + +function add(atom a, b) + return a+b +end function + +integer curried = create_curried(routine_id("add"),{2}) +printf(1,"2+5=%d\n",call_curried(curried,{5})) diff --git a/Task/Currying/Rust/currying.rust b/Task/Currying/Rust/currying.rust index 550e405f9f..b303ddea95 100644 --- a/Task/Currying/Rust/currying.rust +++ b/Task/Currying/Rust/currying.rust @@ -1,6 +1,6 @@ -#![feature(box_syntax)] -fn add_n(n : i32) -> Box i32 + 'static> { - box move |&: x| n + x +#![feature(conservative_impl_trait)] +fn add_n(n : i32) -> impl Fn(i32) -> i32 { + move |x| n + x } fn main() { diff --git a/Task/Currying/Zkl/currying.zkl b/Task/Currying/Zkl/currying.zkl new file mode 100644 index 0000000000..20bd5bf81e --- /dev/null +++ b/Task/Currying/Zkl/currying.zkl @@ -0,0 +1,6 @@ +addOne:= Op("+").fp(1); addOne(5) //-->6 +minusOne:=Op("-").fp1(1); minusOne(5) //-->4, note that this fixed 1 as the second parameter + // fix first and third parameters: +foo:=String.fpM("101","",""); foo("zkl"); //-->"zkl" +fcn g(x){x+1} f:=fcn(f,x){f(x)+x}.fp(g); f(5); //-->11 +f:=fcn(f,x){f(x)+x}.fp(fcn(x){x+1}); // above with lambdas all the way down diff --git a/Task/Cut-a-rectangle/Kotlin/cut-a-rectangle.kotlin b/Task/Cut-a-rectangle/Kotlin/cut-a-rectangle.kotlin new file mode 100644 index 0000000000..4d7604c07f --- /dev/null +++ b/Task/Cut-a-rectangle/Kotlin/cut-a-rectangle.kotlin @@ -0,0 +1,76 @@ +// version 1.0.6 + +object RectangleCutter { + private var w: Int = 0 + private var h: Int = 0 + private var len: Int = 0 + private var cnt: Long = 0 + + private lateinit var grid: ByteArray + private val next = IntArray(4) + private val dir = arrayOf( + intArrayOf(0, -1), + intArrayOf(-1, 0), + intArrayOf(0, 1), + intArrayOf(1, 0) + ) + + private fun walk(y: Int, x: Int) { + if (y == 0 || y == h || x == 0 || x == w) { + cnt += 2 + return + } + val t = y * (w + 1) + x + grid[t]++ + grid[len - t]++ + (0..3).filter { grid[t + next[it]] == 0.toByte() } + .forEach { walk(y + dir[it][0], x + dir[it][1]) } + grid[t]-- + grid[len - t]-- + } + + fun solve(hh: Int, ww: Int, recur: Boolean): Long { + var t: Int + h = hh + w = ww + if ((h and 1) != 0) { + t = w + w = h + h = t + } + if ((h and 1) != 0) return 0L + if (w == 1) return 1L + if (w == 2) return h.toLong() + if (h == 2) return w.toLong() + val cy = h / 2 + val cx = w / 2 + len = (h + 1) * (w + 1) + grid = ByteArray(len) + len-- + next[0] = -1 + next[1] = -w - 1 + next[2] = 1 + next[3] = w + 1 + if (recur) cnt = 0L + for (x in cx + 1 until w) { + t = cy * (w + 1) + x + grid[t] = 1 + grid[len - t] = 1 + walk(cy - 1, x) + } + cnt++ + if (h == w) cnt *= 2 + else if ((w and 1) == 0 && recur) solve(w, h, false) + return cnt + } +} + +fun main(args: Array) { + for (y in 1..10) { + for (x in 1..y) { + if ((x and 1) == 0 || (y and 1) == 0) { + println("${"%2d".format(y)} x ${"%2d".format(x)}: ${RectangleCutter.solve(y, x, true)}") + } + } + } +} diff --git a/Task/Cut-a-rectangle/REXX/cut-a-rectangle-1.rexx b/Task/Cut-a-rectangle/REXX/cut-a-rectangle-1.rexx index f658423938..1e3db49b15 100644 --- a/Task/Cut-a-rectangle/REXX/cut-a-rectangle-1.rexx +++ b/Task/Cut-a-rectangle/REXX/cut-a-rectangle-1.rexx @@ -1,45 +1,46 @@ -/*REXX program cuts rectangles into two symmetric pieces, the rectangles are */ -/*────────────────────────────── cut along unit dimensions and may be rotated.*/ -numeric digits 20 /*be able to handle some big integers. */ -parse arg N .; if N=='' then N=10 /*N not specified? Then use default.*/ -dir.=0; dir.0.1=-1; dir.1.0=-1; dir.2.1=1; dir.3.0=1 /*4 directions.*/ +/*REXX program cuts rectangles into two symmetric pieces, the rectangles are cut along */ +/*────────────────────────────────────────────────── unit dimensions and may be rotated.*/ +numeric digits 20 /*be able to handle some big integers. */ +parse arg N .; if N=='' | N=="," then N=10 /*N not specified? Then use default.*/ +dir.=0; dir.0.1=-1; dir.1.0=-1; dir.2.1=1; dir.3.0=1 /*the four directions.*/ - do y=2 to N; say /*calculate rectangles up to size NxN.*/ - do x=1 for y; if x//2 & y//2 then iterate /*not if both X&Y odd.*/ - _=solve(y,x,1); _=right(_,max(10,length(_))) /*align the output. */ - say right(y,9) "x" right(x,2) 'rectangle can be cut' _ "way"s(_)'.' + do y=2 to N; say /*calculate rectangles up to size NxN.*/ + do x=1 for y; if x//2 & y//2 then iterate /*not if both X&Y odd.*/ + z=solve(y,x,1); _=comma(z); _=right(_, max(14, length(_))) /*align the output. */ + say right(y,9) "x" right(x,2) 'rectangle can be cut' _ "way"s(z). end /*x*/ end /*y*/ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -s: if arg(1)=1 then return arg(3); return word(arg(2) 's',1) /*pluralizer*/ -/*────────────────────────────────────────────────────────────────────────────*/ -solve: procedure expose # dir. @. h len next. w; @.=0 /*zero rect. coördinates*/ - parse arg hh 1 h,ww 1 w,recur /*obtain the values for some arguments.*/ - if h//2 then do; t=w; w=h; h=t; if h//2 then return 0 +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +comma: procedure; arg _; do k=length(_)-3 to 1 by -3; _=insert(',',_,k); end; return _ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +s: if arg(1)=1 then return arg(3); return word(arg(2) 's', 1) /*pluralizer.*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +solve: procedure expose # dir. @. h len next. w; @.=0 /*zero rectangle coördinates.*/ + parse arg h,w,recur /*get values for some args. */ + if h//2 then do; t=w; w=h; h=t; if h//2 then return 0 end if w==1 then return 1 if w==2 then return h - if h==2 then return w /* % is REXX's integer division. */ - cy = h%2; cx=w%2 /*cut the [XY] rectangle in half. */ - len = (h+1) * (w+1) - 1 /*extend the area of the rectangle. */ - next.0=-1; next.1=-w-1; next.2=1; next.3=w+1 /*direction & distance*/ + if h==2 then return w /* [↓] % is REXX's integer division.*/ + cy=h % 2; cx=w % 2; wp=w + 1 /*cut the [XY] rectangle in half. */ + len=(h+1) * wp - 1 /*extend the area of the rectangle. */ + next.0=-1; next.1=-wp; next.2=1; next.3=wp /*direction & distance.*/ if recur then #=0 - do x=cx+1 to w-1; t=x+cy*(w+1) - @.t=1; _=len-t; @._=1; call walk cy-1,x - end /*x*/ + do x=cx+1 to w-1; t=x + cy*wp; @.t=1; _=len - t; @._=1 + call walk cy-1, x + end /*x*/ #=#+1 - if h==w then #=#+# /*double the count of rectangle cuts. */ - else if w//2==0 & recur then call solve w,h,0 + if h==w then #=# + # /*double the count of rectangle cuts. */ + else if w//2==0 & recur then call solve w, h, 0 return # -/*────────────────────────────────────────────────────────────────────────────*/ -walk: procedure expose # dir. @. h len next. w; parse arg y,x - if y==h | x==0 | x==w | y==0 then do; #=#=2; return; end - t=x + y*(w+1); @.t=@.t+1; _=len-t +/*──────────────────────────────────────────────────────────────────────────────────────*/ +walk: procedure expose # dir. @. h len next. w wp; parse arg y,x + if y==h | x==0 | x==w | y==0 then do; #= #+2; return; end + t=x + y*wp; @.t=@.t + 1; _=len - t @._=@._+1 - do j=0 for 4; _ = t+next.j /*try four directions.*/ - if @._==0 then call walk y+dir.j.0, x+dir.j.1 + do j=0 for 4; _=t + next.j /*try each of four directions.*/ + if @._==0 then call walk y + dir.j.0, x + dir.j.1 end /*j*/ - @.t=@.t-1 - _=len-t; @._=@._-1 - return + @.t=@.t - 1 + _=len - t; @._=@._ - 1; return diff --git a/Task/Cut-a-rectangle/REXX/cut-a-rectangle-2.rexx b/Task/Cut-a-rectangle/REXX/cut-a-rectangle-2.rexx index 368793e7bf..745a9eba9f 100644 --- a/Task/Cut-a-rectangle/REXX/cut-a-rectangle-2.rexx +++ b/Task/Cut-a-rectangle/REXX/cut-a-rectangle-2.rexx @@ -1,55 +1,55 @@ -/*REXX program cuts rectangles into two symmetric pieces, the rectangles are */ -/*────────────────────────────── cut along unit dimensions and may be rotated.*/ -numeric digits 20 /*be able to handle some big integers. */ -parse arg N .; if N=='' then N=10 /*N not specified? Then use default.*/ -dir.=0; dir.0.1=-1; dir.1.0=-1; dir.2.1=1; dir.3.0=1 /*4 directions.*/ +/*REXX program cuts rectangles into two symmetric pieces, the rectangles are cut along */ +/*────────────────────────────────────────────────── unit dimensions and may be rotated.*/ +numeric digits 20 /*be able to handle some big integers. */ +parse arg N .; if N=='' | N=="," then N=10 /*N not specified? Then use default.*/ +dir.=0; dir.0.1=-1; dir.1.0=-1; dir.2.1=1; dir.3.0=1 /*the four directions.*/ - do y=2 to N; say /*calculate rectangles up to size NxN.*/ - do x=1 for y; if x//2 & y//2 then iterate /*not if both X&Y odd.*/ - _=solve(y,x,1); _=right(_,max(10,length(_))) /*align the output. */ - say right(y,9) "x" right(x,2) 'rectangle can be cut' _ "way"s(_)'.' + do y=2 to N; say /*calculate rectangles up to size NxN.*/ + do x=1 for y; if x//2 & y//2 then iterate /*not if both X&Y odd.*/ + z=solve(y,x,1); _=comma(z); _=right(_, max(14, length(_))) /*align the output. */ + say right(y,9) "x" right(x,2) 'rectangle can be cut' _ "way"s(z). end /*x*/ end /*y*/ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -s: if arg(1)=1 then return arg(3); return word(arg(2) 's',1) /*pluralizer*/ -/*────────────────────────────────────────────────────────────────────────────*/ -solve: procedure expose # dir. @. h len next. w; @.=0 /*zero rect. coördinates*/ - parse arg hh 1 h,ww 1 w,recur /*obtain the values for some arguments.*/ - if h//2 then do; parse value w h w with t w h; if h//2 then return 0 +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +comma: procedure; arg _; do k=length(_)-3 to 1 by -3; _=insert(',',_,k); end; return _ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +s: if arg(1)=1 then return arg(3); return word(arg(2) 's', 1) /*pluralizer.*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +solve: procedure expose # dir. @. h len next. w; @.=0 /*zero rectangle coördinates.*/ + parse arg h,w,recur /*get values for some args. */ + if h//2 then do; t=w; w=h; h=t; if h//2 then return 0 end if w==1 then return 1 if w==2 then return h - if h==2 then return w /* % is REXX's integer division. */ - cy = h%2; cx=w%2 /*cut the [XY] rectangle in half. */ - len = (h+1) * (w+1) - 1 /*extend the area of the rectangle. */ - next.0=-1; next.1=-w-1; next.2=1; next.3=w+1 /*direction & distance*/ + if h==2 then return w /* [↓] % is REXX's integer division.*/ + cy=h % 2; cx=w % 2; wp=w + 1 /*cut the [XY] rectangle in half. */ + len=(h+1) * wp - 1 /*extend the area of the rectangle. */ + next.0=-1; next.1=-wp; next.2=1; next.3=wp /*direction & distance.*/ if recur then #=0 - do x=cx+1 to w-1; t=x+cy*(w+1) - @.t=1; _=len-t; @._=1; call walk cy-1,x - end /*x*/ + do x=cx+1 to w-1; t=x + cy*wp; @.t=1; _=len - t; @._=1 + call walk cy-1, x + end /*x*/ #=#+1 - if h==w then #=#+# /*double the count of rectangle cuts. */ - else if w//2==0 & recur then call solve w,h,0 + if h==w then #=# + # /*double the count of rectangle cuts. */ + else if w//2==0 & recur then call solve w, h, 0 return # -/*────────────────────────────────────────────────────────────────────────────*/ -walk: procedure expose # dir. @. h len next. w; parse arg y,x - if y==h then do; #=#+2; return; end /*◄──┐ REXX short circuit. */ - if x==0 then do; #=#+2; return; end /*◄──┤ " " " */ - if x==w then do; #=#+2; return; end /*◄──┤ " " " */ - if y==0 then do; #=#+2; return; end /*◄──┤ " " " */ - t=x + y*(w+1); @.t=@.t+1; _=len-t /* │ordered by most likely ►──┐*/ - @._=@._+1 /* └──────────────────────────┘*/ - do j=0 for 4; _ = t+next.j /*try 4 directions.*/ - if @._==0 then do - yn=y+dir.j.0; xn=x+dir.j.1 - if yn==h then do; #=#+2; iterate; end - if xn==0 then do; #=#+2; iterate; end - if xn==w then do; #=#+2; iterate; end - if yn==0 then do; #=#+2; iterate; end - call walk yn, xn - end - end /*j*/ - @.t=@.t-1 - _=len-t; @._=@._-1 - return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +walk: procedure expose # dir. @. h len next. w wp; parse arg y,x + if y==h then do; #=#+2; return; end /* ◄──┐ REXX short circuit. */ + if x==0 then do; #=#+2; return; end /* ◄──┤ " " " */ + if x==w then do; #=#+2; return; end /* ◄──┤ " " " */ + if y==0 then do; #=#+2; return; end /* ◄──┤ " " " */ + t=x + y*wp; @.t=@.t + 1; _=len - t /* │ordered by most likely ►──┐*/ + @._=@._+1 /* └──────────────────────────┘*/ + do j=0 for 4; _=t + next.j /*try each of the four directions.*/ + if @._==0 then do; yn=y + dir.j.0; xn=x + dir.j.1 + if yn==h then do; #=#+2; iterate; end + if xn==0 then do; #=#+2; iterate; end + if xn==w then do; #=#+2; iterate; end + if yn==0 then do; #=#+2; iterate; end + call walk yn, xn + end + end /*j*/ + @.t=@.t - 1 + _=len - t; @._=@._ - 1; return diff --git a/Task/Cut-a-rectangle/Rust/cut-a-rectangle.rust b/Task/Cut-a-rectangle/Rust/cut-a-rectangle.rust new file mode 100644 index 0000000000..97a7ffb491 --- /dev/null +++ b/Task/Cut-a-rectangle/Rust/cut-a-rectangle.rust @@ -0,0 +1,73 @@ +fn cwalk(mut vis: &mut Vec>, count: &mut isize, w: usize, h: usize, y: usize, x: usize, d: usize) { + if x == 0 || y == 0 || x == w || y == h { + *count += 1; + return; + } + + vis[y][x] = true; + vis[h - y][w - x] = true; + + if x != 0 && ! vis[y][x - 1] { + cwalk(&mut vis, count, w, h, y, x - 1, d | 1); + } + if d & 1 != 0 && x < w && ! vis[y][x+1] { + cwalk(&mut vis, count, w, h, y, x + 1, d | 1); + } + if y != 0 && ! vis[y - 1][x] { + cwalk(&mut vis, count, w, h, y - 1, x, d | 2); + } + if d & 2 != 0 && y < h && ! vis[y + 1][x] { + cwalk(&mut vis, count, w, h, y + 1, x, d | 2); + } + + vis[y][x] = false; + vis[h - y][w - x] = false; +} + +fn count_only(x: usize, y: usize) -> isize { + let mut count = 0; + let mut w = x; + let mut h = y; + + if (h * w) & 1 != 0 { + return count; + } + if h & 1 != 0 { + std::mem::swap(&mut w, &mut h); + } + + let mut vis = vec![vec![false; w + 1]; h + 1]; + vis[h / 2][w / 2] = true; + + if w & 1 != 0 { + vis[h / 2][w / 2 + 1] = true; + } + let mut res; + if w > 1 { + cwalk(&mut vis, &mut count, w, h, h / 2, w / 2 - 1, 1); + res = 2 * count - 1; + count = 0; + if w != h { + cwalk(&mut vis, &mut count, w, h, h / 2 + 1, w / 2, if w & 1 != 0 { 3 } else { 2 }); + } + res += 2 * count - if w & 1 == 0 { 1 } else { 0 }; + } + else { + res = 1; + } + + if w == h { + res = 2 * res + 2; + } + res +} + +fn main() { + for y in 1..10 { + for x in 1..y + 1 { + if x & 1 == 0 || y & 1 == 0 { + println!("{} x {}: {}", y, x, count_only(x, y)); + } + } + } +} diff --git a/Task/Cut-a-rectangle/Zkl/cut-a-rectangle-1.zkl b/Task/Cut-a-rectangle/Zkl/cut-a-rectangle-1.zkl new file mode 100644 index 0000000000..d5748071a1 --- /dev/null +++ b/Task/Cut-a-rectangle/Zkl/cut-a-rectangle-1.zkl @@ -0,0 +1,34 @@ +fcn cut_it(h,w){ + if(h.isOdd){ + if(w.isOdd) return(0); + t,h,w=h,w,t; // swap w,h: a,b=c,d --> a=c; b=d; so need a tmp + } + if(w==1) return(1); + + nxt :=T(T(w+1, 1,0), T(-w-1, -1,0), T(-1, 0,-1), T(1, 0,1)); #[next, dy,dx] + blen:=(h + 1)*(w + 1) - 1; + grid:=(blen + 1).pump(List(),False); //-->L(False,False...) + + walk:='wrap(y,x){ // lambda closure + if(y==0 or y==h or x==0 or x==w) return(1); + count,t:=0,y*(w + 1) + x; + grid[t]=grid[blen - t]=True; + foreach nt,dy,dx in (nxt){ + if(not grid[t + nt]) count+=self.fcn(y + dy, x + dx,vm.pasteArgs(2)); + } + grid[t]=grid[blen - t]=False; + count + }; + + t:=h/2*(w + 1) + w/2; + if(w.isOdd){ + grid[t]=grid[t + 1]=True; + count:=walk(h/2, w/2 - 1); + count + walk(h/2 - 1, w/2)*2; + }else{ + grid[t]=True; + count:=walk(h/2, w/2 - 1); + if(h==w) return(count*2); + count + walk(h/2 - 1, w/2); + } +} diff --git a/Task/Cut-a-rectangle/Zkl/cut-a-rectangle-2.zkl b/Task/Cut-a-rectangle/Zkl/cut-a-rectangle-2.zkl new file mode 100644 index 0000000000..1699f45ae7 --- /dev/null +++ b/Task/Cut-a-rectangle/Zkl/cut-a-rectangle-2.zkl @@ -0,0 +1,3 @@ +foreach w,h in ([1..9],[1..w]){ + if((w*h).isEven) println("%d x %d: %d".fmt(w, h, cut_it(w,h))); +} diff --git a/Task/DNS-query/Batch-File/dns-query.bat b/Task/DNS-query/Batch-File/dns-query.bat index 088a81b64e..b3f4e193c0 100644 --- a/Task/DNS-query/Batch-File/dns-query.bat +++ b/Task/DNS-query/Batch-File/dns-query.bat @@ -5,34 +5,34 @@ set "domain=www.kame.net" echo DOMAIN: "%domain%" -echo. +echo( call :DNS_Lookup "%domain%" -echo. pause exit /b ::Main Procedure -::Uses NSLOOKUP Command and a Temporary File -::Also uses a dirty "parsing" to detect IP addresses. - +::Uses NSLOOKUP Command. Also uses a dirty "parsing" to detect IP addresses. :DNS_Lookup [domain] -setlocal enabledelayedexpansion -for /f "delims=" %%T in ('forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(0x09"') do set "TAB=%%T" -set "temp_file=%TMP%\NSLOOKUP_%RANDOM%.TMP" +::Define Variables and the TAB Character +set "dom=%~1" set "record=" -for /f "tokens=1* delims=:" %%x in ('nslookup "%~1" 2^>nul') do ( - set "line=%%x" - if "!line:~0,4!"=="Name" set "record=yes" - if "!line:~0,5!"=="Alias" set "record=" - if "!record!"=="yes" ( - if "%%y"=="" (echo %%x>>"%temp_file%") else (echo %%x:%%y>>"%temp_file%") - ) +set "reccnt=0" +for /f "delims=" %%T in ('forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(0x09"') do set "TAB=%%T" + +setlocal enabledelayedexpansion +for /f "tokens=1* delims=:" %%x in ('nslookup "!dom!" 2^>nul') do ( + set "line=%%x" + if /i "!line:~0,4!"=="Name" set "record=yes" + if /i "!line:~0,5!"=="Alias" set "record=" + if "!record!"=="yes" ( + set /a reccnt+=1 + if "%%y"=="" (set "catch_!reccnt!=%%x") else (set "catch_!reccnt!=%%x:%%y") + ) ) -if exist "%temp_file%" ( - for /f "tokens=*" %%a in ( - 'findstr /BC:"Address" "%temp_file%" ^& findstr /BC:"%TAB%" "%temp_file%"' - ) do (set "data=%%a"&echo !data:*s: =!) - del /q "%temp_file%" -) else (echo Connection to domain failed.) +for /l %%c in (1,1,%reccnt%) do ( + if /i "!catch_%%c:~0,7!"=="Address" echo(!catch_%%c:*s: =! + if /i "!catch_%%c:~0,1!"=="%TAB%" echo(!catch_%%c:%TAB% =! +) +endlocal goto :EOF diff --git a/Task/DNS-query/D/dns-query.d b/Task/DNS-query/D/dns-query.d index fc7fe24675..30c4c78e7a 100644 --- a/Task/DNS-query/D/dns-query.d +++ b/Task/DNS-query/D/dns-query.d @@ -3,7 +3,7 @@ import std.stdio, std.socket; void main() { auto domain = "www.kame.net", port = "80"; - auto a = getAddressInfo(domain, port); + auto a = getAddressInfo(domain, port, AddressFamily.INET); writefln("IPv4 address for %s: %s", domain, a[0].address); a = getAddressInfo(domain, port, AddressFamily.INET6); diff --git a/Task/DNS-query/Erlang/dns-query.erl b/Task/DNS-query/Erlang/dns-query.erl new file mode 100644 index 0000000000..fc16c52037 --- /dev/null +++ b/Task/DNS-query/Erlang/dns-query.erl @@ -0,0 +1,14 @@ +33> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet). +{ok,{hostent,"orange.kame.net", + ["www.kame.net"], + inet,4, + [{203,178,141,194}]}} +34> [inet_parse:ntoa(Addr) || Addr <- AddrList]. +["203.178.141.194"] +35> f(). +ok +36> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet6). +{ok,{hostent,"orange.kame.net",[],inet6,16, + [{8193,512,3583,65521,534,16127,65201,17623}]}} +37> [inet_parse:ntoa(Addr) || Addr <- AddrList]. +["2001:200:DFF:FFF1:216:3EFF:FEB1:44D7"] diff --git a/Task/DNS-query/Go/dns-query-1.go b/Task/DNS-query/Go/dns-query-1.go deleted file mode 100644 index 388858346b..0000000000 --- a/Task/DNS-query/Go/dns-query-1.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "fmt" - "net" -) - -func main() { - if addrs, err := net.LookupHost("www.kame.net"); err == nil { - fmt.Println(addrs) - } else { - fmt.Println(err) - } -} diff --git a/Task/DNS-query/Go/dns-query-2.go b/Task/DNS-query/Go/dns-query-2.go deleted file mode 100644 index 64baaaa7e7..0000000000 --- a/Task/DNS-query/Go/dns-query-2.go +++ /dev/null @@ -1,16 +0,0 @@ -module Main where - -import Network.Socket - -getWebAddresses :: HostName -> IO [SockAddr] -getWebAddresses host = do - results <- getAddrInfo (Just defaultHints) (Just host) (Just "http") - return [ addrAddress a | a <- results, addrSocketType a == Stream ] - -showIPs :: HostName -> IO () -showIPs host = do - putStrLn $ "IP addresses for " ++ host ++ ":" - addresses <- getWebAddresses host - mapM_ (putStrLn . (" "++) . show) addresses - -main = showIPs "www.kame.net" diff --git a/Task/DNS-query/Go/dns-query-3.go b/Task/DNS-query/Go/dns-query-3.go deleted file mode 100644 index 78757db877..0000000000 --- a/Task/DNS-query/Go/dns-query-3.go +++ /dev/null @@ -1,21 +0,0 @@ -import java.net.InetAddress; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.UnknownHostException; - -class DnsQuery { - public static void main(String[] args) { - try { - InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); - for(int i=0; i < ipAddr.length ; i++) { - if (ipAddr[i] instanceof Inet4Address) { - System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); - } else if (ipAddr[i] instanceof Inet6Address) { - System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); - } - } - } catch (UnknownHostException uhe) { - System.err.println("unknown host"); - } - } -} diff --git a/Task/DNS-query/Go/dns-query-4.go b/Task/DNS-query/Go/dns-query-4.go deleted file mode 100644 index 73fb82ed12..0000000000 --- a/Task/DNS-query/Go/dns-query-4.go +++ /dev/null @@ -1,13 +0,0 @@ -/* NetRexx */ -options replace format comments java crossref symbols nobinary - -ir = InetAddress -addresses = InetAddress[] InetAddress.getAllByName('www.kame.net') -loop ir over addresses - if ir <= Inet4Address then do - say 'IPv4 :' ir.getHostAddress - end - if ir <= Inet6Address then do - say 'IPv6 :' ir.getHostAddress - end - end ir diff --git a/Task/DNS-query/Groovy/dns-query-4.groovy b/Task/DNS-query/Groovy/dns-query-4.groovy deleted file mode 100644 index 78757db877..0000000000 --- a/Task/DNS-query/Groovy/dns-query-4.groovy +++ /dev/null @@ -1,21 +0,0 @@ -import java.net.InetAddress; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.UnknownHostException; - -class DnsQuery { - public static void main(String[] args) { - try { - InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); - for(int i=0; i < ipAddr.length ; i++) { - if (ipAddr[i] instanceof Inet4Address) { - System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); - } else if (ipAddr[i] instanceof Inet6Address) { - System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); - } - } - } catch (UnknownHostException uhe) { - System.err.println("unknown host"); - } - } -} diff --git a/Task/DNS-query/Kotlin/dns-query.kotlin b/Task/DNS-query/Kotlin/dns-query.kotlin new file mode 100644 index 0000000000..a7e68f5ea3 --- /dev/null +++ b/Task/DNS-query/Kotlin/dns-query.kotlin @@ -0,0 +1,27 @@ +// version 1.1.3 + +import java.net.InetAddress +import java.net.Inet4Address +import java.net.Inet6Address + +fun showIPAddresses(host: String) { + try { + val ipas = InetAddress.getAllByName(host) + println("The IP address(es) for '$host' is/are:\n") + for (ipa in ipas) { + print(when (ipa) { + is Inet4Address -> " ipv4 : " + is Inet6Address -> " ipv6 : " + else -> " ipv? : " + }) + println(ipa.hostAddress) + } + } + catch (ex: Exception) { + println(ex.message) + } +} + +fun main(args: Array) { + showIPAddresses("www.kame.net") +} diff --git a/Task/DNS-query/Perl-6/dns-query.pl6 b/Task/DNS-query/Perl-6/dns-query.pl6 new file mode 100644 index 0000000000..0e9bf351fa --- /dev/null +++ b/Task/DNS-query/Perl-6/dns-query.pl6 @@ -0,0 +1,9 @@ +use Net::DNS; + +my $resolver = Net::DNS.new('8.8.8.8'); + +my $ip4 = $resolver.lookup('A', 'orange.kame.net'); +my $ip6 = $resolver.lookup('AAAA', 'orange.kame.net'); + +say $ip4[0].octets.join: '.'; +say $ip6[0].octets.».fmt("%.2X").join.comb(4).join: ':'; diff --git a/Task/DNS-query/PicoLisp/dns-query-3.l b/Task/DNS-query/PicoLisp/dns-query-3.l deleted file mode 100644 index e7d685aa6c..0000000000 --- a/Task/DNS-query/PicoLisp/dns-query-3.l +++ /dev/null @@ -1,5 +0,0 @@ -irb(main):001:0> require 'socket' -=> true -irb(main):002:0> Addrinfo.getaddrinfo("www.kame.net", nil, nil, :DGRAM) \ -irb(main):003:0* .map! { |ai| ai.ip_address } -=> ["203.178.141.194", "2001:200:dff:fff1:216:3eff:feb1:44d7"] diff --git a/Task/DNS-query/PicoLisp/dns-query-1.l b/Task/DNS-query/PicoLisp/dns-query.l similarity index 100% rename from Task/DNS-query/PicoLisp/dns-query-1.l rename to Task/DNS-query/PicoLisp/dns-query.l diff --git a/Task/DNS-query/Pike/dns-query.pike b/Task/DNS-query/Pike/dns-query.pike new file mode 100644 index 0000000000..50150388e1 --- /dev/null +++ b/Task/DNS-query/Pike/dns-query.pike @@ -0,0 +1,2 @@ +> array ips = Protocols.DNS.gethostbyname("www.kame.net")[1] || ({}); +> write(ips*"\n"); diff --git a/Task/DNS-query/PowerShell/dns-query-1.psh b/Task/DNS-query/PowerShell/dns-query-1.psh new file mode 100644 index 0000000000..fa8a8c6225 --- /dev/null +++ b/Task/DNS-query/PowerShell/dns-query-1.psh @@ -0,0 +1,2 @@ +$DNS = Resolve-DnsName -Name www.kame.net +Write-Host "IPv4:" $DNS.IP4Address "`nIPv6:" $DNS.IP6Address diff --git a/Task/DNS-query/PicoLisp/dns-query-2.l b/Task/DNS-query/PowerShell/dns-query-2.psh similarity index 100% rename from Task/DNS-query/PicoLisp/dns-query-2.l rename to Task/DNS-query/PowerShell/dns-query-2.psh diff --git a/Task/DNS-query/Rust/dns-query.rust b/Task/DNS-query/Rust/dns-query.rust new file mode 100644 index 0000000000..1a7e90c049 --- /dev/null +++ b/Task/DNS-query/Rust/dns-query.rust @@ -0,0 +1,16 @@ +use std::net::ToSocketAddrs; + +fn main() { + let host = "www.kame.net"; + // Ideally, we would want to use std::net::lookup_host to resolve the host ips, + // but at time of writing this, it is still unstable. Fortunately, we can + // still resolve using the ToSocketAddrs trait, but we need to add a port, + // so we use the dummy port 0. + let host_port = (host, 0); + let ip_iter = host_port.to_socket_addrs().unwrap(); + + + for ip_port in ip_iter { + println!("{}", ip_port.ip()); + } +} diff --git a/Task/DNS-query/Zkl/dns-query.zkl b/Task/DNS-query/Zkl/dns-query.zkl new file mode 100644 index 0000000000..e0e3e0ab6c --- /dev/null +++ b/Task/DNS-query/Zkl/dns-query.zkl @@ -0,0 +1,2 @@ +zkl: Network.TCPClientSocket.addrInfo("www.kame.net") +L("orange.kame.net",L("203.178.141.194","2001:200:dff:fff1:216:3eff:feb1:44d7")) diff --git a/Task/Date-format/BaCon/date-format.bacon b/Task/Date-format/BaCon/date-format.bacon new file mode 100644 index 0000000000..c5e8c20073 --- /dev/null +++ b/Task/Date-format/BaCon/date-format.bacon @@ -0,0 +1,4 @@ +' Date format +n = NOW +PRINT YEAR(n), MONTH(n), DAY(n) FORMAT "%ld-%02ld-%02ld\n" +PRINT WEEKDAY$(n), MONTH$(n), DAY(n), YEAR(n) FORMAT "%s, %s %02ld, %ld\n" diff --git a/Task/Date-format/Batch-File/date-format.bat b/Task/Date-format/Batch-File/date-format.bat new file mode 100644 index 0000000000..43a9562765 --- /dev/null +++ b/Task/Date-format/Batch-File/date-format.bat @@ -0,0 +1,35 @@ +@echo off +setlocal enabledelayedexpansion + +:: Define arrays of days/months we'll need +set daynames=Monday Tuesday Wednesday Thursday Friday Saturday Sunday +set monthnames=January February March April May June July August September October November December + +:: Separate the output of the 'date /t' command (outputs in the format of "Sun 16/04/2017") into 4 variables +for /f "tokens=1,2,3,4 delims=/ " %%i in ('date /t') do ( + set dayname=%%i + set day=%%j + set month=%%k + set year=%%l +) + +:: Crosscheck the first 3 letters of every word in %daynames% to the 3 letter day name found previously +for %%i in (%daynames%) do ( + set tempdayname=%%i + set comparedayname=!tempdayname:~0,3! + if "%dayname%"=="!comparedayname!" set fulldayname=%%i +) + +:: Variables starting with "0" during the 'set /a' command are treated as octal numbers. To avoid this, if the first character of %month% is "0", it is removed +if "%month:~0,1%"=="0" set monthtemp=%month:~1,1% +set monthcount=0 + +:: Iterates through %monthnames% and when it reaches the amount of iterations dictated by %month%, sets %monthname% as the current month being iterated through +for %%i in (%monthnames%) do ( + set /a monthcount+=1 + if %monthtemp%==!monthcount! set monthname=%%i +) + +echo %year%-%month%-%day% +echo %fulldayname%, %monthname% %day%, %year% +pause>nul diff --git a/Task/Date-format/Elixir/date-format.elixir b/Task/Date-format/Elixir/date-format.elixir index 6c5856b397..8cdf512766 100644 --- a/Task/Date-format/Elixir/date-format.elixir +++ b/Task/Date-format/Elixir/date-format.elixir @@ -1,25 +1,23 @@ -defmodule Date do - def iso_date, do: iso_date(:erlang.date) +defmodule Date_format do + def iso_date, do: Date.utc_today |> Date.to_iso8601 - def iso_date(year, month, day), do: iso_date({year, month, day}) + def iso_date(year, month, day), do: Date.from_erl!({year, month, day}) |> Date.to_iso8601 - def iso_date(date), do: - :io.format("~4b-~2..0B-~2..0B~n", Tuple.to_list(date)) + def long_date, do: Date.utc_today |> long_date - def long_date, do: long_date(:erlang.date) + def long_date(year, month, day), do: Date.from_erl!({year, month, day}) |> long_date - def long_date(year, month, day), do: long_date({year, month, day}) - - def long_date(date = {year, month, day}) do - months = { "January", "February", "March", "April", "May", "June", - "July", "August", "September", "October", "November", "December" } - weekdays = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" } - weekday = :calendar.day_of_the_week(date) - IO.puts "#{elem(weekdays, weekday-1)}, #{elem(months, month-1)} #{day}, #{year}" + @months Enum.zip(1..12, ~w[January February March April May June July August September October November December]) + |> Map.new + @weekdays Enum.zip(1..7, ~w[Monday Tuesday Wednesday Thursday Friday Saturday Sunday]) + |> Map.new + def long_date(date) do + weekday = Date.day_of_week(date) + "#{@weekdays[weekday]}, #{@months[date.month]} #{date.day}, #{date.year}" end end -Date.iso_date -Date.iso_date(2007,11,10) -Date.long_date -Date.long_date(2007,11,10) +IO.puts Date_format.iso_date +IO.puts Date_format.long_date +IO.puts Date_format.iso_date(2007,11,10) +IO.puts Date_format.long_date(2007,11,10) diff --git a/Task/Date-format/Gambas/date-format.gambas b/Task/Date-format/Gambas/date-format.gambas new file mode 100644 index 0000000000..5f94347a9e --- /dev/null +++ b/Task/Date-format/Gambas/date-format.gambas @@ -0,0 +1,6 @@ +Public Sub Main() + +Print Format(Now, "yyyy - mm - dd") +Print Format(Now, "dddd, mmmm dd, yyyy") + +End diff --git a/Task/Date-format/Haskell/date-format.hs b/Task/Date-format/Haskell/date-format.hs index 4c4926aee0..c7052f12a5 100644 --- a/Task/Date-format/Haskell/date-format.hs +++ b/Task/Date-format/Haskell/date-format.hs @@ -1,13 +1,11 @@ -import Control.Monad import Data.Time -import System.Locale + (FormatTime, formatTime, defaultTimeLocale, utcToLocalTime, + getCurrentTimeZone, getCurrentTime) -format1 :: FormatTime t => t -> String -format1 = formatTime defaultTimeLocale "%Y-%m-%e" - -format2 :: FormatTime t => t -> String -format2 = formatTime defaultTimeLocale "%A, %B %d, %Y" +formats :: FormatTime t => [t -> String] +formats = (formatTime defaultTimeLocale) <$> ["%F", "%A, %B %d, %Y"] +main :: IO () main = do - t <- liftM2 utcToLocalTime getCurrentTimeZone getCurrentTime - mapM_ putStrLn [format1 t, format2 t] + t <- pure utcToLocalTime <*> getCurrentTimeZone <*> getCurrentTime + putStrLn $ unlines (formats <*> pure t) diff --git a/Task/Date-format/jq/date-format.jq b/Task/Date-format/Jq/date-format.jq similarity index 100% rename from Task/Date-format/jq/date-format.jq rename to Task/Date-format/Jq/date-format.jq diff --git a/Task/Date-format/Kotlin/date-format.kotlin b/Task/Date-format/Kotlin/date-format.kotlin new file mode 100644 index 0000000000..4b8a0ef6ea --- /dev/null +++ b/Task/Date-format/Kotlin/date-format.kotlin @@ -0,0 +1,9 @@ +// version 1.0.6 + +import java.util.GregorianCalendar + +fun main(args: Array) { + val now = GregorianCalendar() + println("%tF".format(now)) + println("%tA, %1\$tB %1\$te, %1\$tY".format(now)) +} diff --git a/Task/Date-format/MIRC-Scripting-Language/date-format.mirc b/Task/Date-format/MIRC-Scripting-Language/date-format.mirc new file mode 100644 index 0000000000..d1c64d080b --- /dev/null +++ b/Task/Date-format/MIRC-Scripting-Language/date-format.mirc @@ -0,0 +1,2 @@ +echo -ag $time(yyyy-mm-dd) +echo -ag $time(dddd $+ $chr(44) mmmm dd $+ $chr(44) yyyy) diff --git a/Task/Date-format/Maple/date-format.maple b/Task/Date-format/Maple/date-format.maple new file mode 100644 index 0000000000..341605b2f6 --- /dev/null +++ b/Task/Date-format/Maple/date-format.maple @@ -0,0 +1,3 @@ +with(StringTools); +FormatTime("%Y-%m-%d") +FormatTime("%A,%B %d, %y") diff --git a/Task/Date-format/Nimrod/date-format.nimrod b/Task/Date-format/Nimrod/date-format.nimrod deleted file mode 100644 index 261c4675d4..0000000000 --- a/Task/Date-format/Nimrod/date-format.nimrod +++ /dev/null @@ -1,5 +0,0 @@ -import times - -var t = getTime().getLocalTime() -echo(t.format("yyyy-MM-dd")) -echo(t.format("dddd',' MMMM d',' yyyy")) diff --git a/Task/Date-format/SQL/date-format.sql b/Task/Date-format/SQL/date-format.sql new file mode 100644 index 0000000000..47a5b9beeb --- /dev/null +++ b/Task/Date-format/SQL/date-format.sql @@ -0,0 +1,3 @@ +select to_char(sysdate,'YYYY-MM-DD') date_fmt_1 from dual; + +select to_char(sysdate,'fmDay, Month DD, YYYY') date_fmt_2 from dual; diff --git a/Task/Date-format/Scheme/date-format.ss b/Task/Date-format/Scheme/date-format.ss new file mode 100644 index 0000000000..c63c22831f --- /dev/null +++ b/Task/Date-format/Scheme/date-format.ss @@ -0,0 +1,16 @@ +(define short-date + (lambda (lt) + (strftime "%Y-%m-%d" (localtime lt)))) + +(define long-date + (lambda (lt) + (strftime "%A, %B %d, %Y" (localtime lt)))) + +(define main + (lambda (args) + ;; Current date + (let ((dt (car (gettimeofday)))) + ;; Short style + (display (short-date dt))(newline) + ;; Long style + (display (long-date dt))(newline)))) diff --git a/Task/Date-format/Stata/date-format.stata b/Task/Date-format/Stata/date-format.stata new file mode 100644 index 0000000000..e53cb35d93 --- /dev/null +++ b/Task/Date-format/Stata/date-format.stata @@ -0,0 +1,2 @@ +display %tdCCYY-NN-DD td($S_DATE) +display %tdDayname,_Month_dd,_CCYY td($S_DATE) diff --git a/Task/Date-format/Zkl/date-format-1.zkl b/Task/Date-format/Zkl/date-format-1.zkl new file mode 100644 index 0000000000..162004cc0f --- /dev/null +++ b/Task/Date-format/Zkl/date-format-1.zkl @@ -0,0 +1,2 @@ +"%d-%02d-%02d".fmt(Time.Clock.localTime.xplode()).println() +//--> "2014-02-28" (ISO format) diff --git a/Task/Date-format/Zkl/date-format-2.zkl b/Task/Date-format/Zkl/date-format-2.zkl new file mode 100644 index 0000000000..7ce4bedb63 --- /dev/null +++ b/Task/Date-format/Zkl/date-format-2.zkl @@ -0,0 +1,2 @@ +Time.Date.prettyDay(Time.Clock.localTime.xplode()) +//--> "Friday, the 28th of February 2014" diff --git a/Task/Date-format/Zkl/date-format-3.zkl b/Task/Date-format/Zkl/date-format-3.zkl new file mode 100644 index 0000000000..ac10da8348 --- /dev/null +++ b/Task/Date-format/Zkl/date-format-3.zkl @@ -0,0 +1,4 @@ +y,m,d:=Time.Clock.localTime; D:=Time.Date; +"%s, %s %d, %d".fmt(D.dayName(D.weekDay(y,m,d)), + D.monthName(m), d,y) +//-->"Friday, February 28, 2014" diff --git a/Task/Date-manipulation/Batch-File/date-manipulation.bat b/Task/Date-manipulation/Batch-File/date-manipulation.bat new file mode 100644 index 0000000000..8e3887dbf8 --- /dev/null +++ b/Task/Date-manipulation/Batch-File/date-manipulation.bat @@ -0,0 +1,81 @@ +@echo off + +call:Date_Manipulation "March 7 2009 7:30pm EST" +call:Date_Manipulation "February 28 2009 2:28pm EST" +call:Date_Manipulation "February 29 2000 9:52pm EST" +pause>nul +exit /b + +:Date_Manipulation +setlocal enabledelayedexpansion + +:: These are the arrays we'll be using +set daysinmonth=31 28 31 30 31 30 31 31 30 31 30 31 +set namesofmonths=January February March April May June July August September October November December + +:: Separate the date given ("%1") into respective variables. Note: For now the "am/pm" is attached to %minutes% +for /f "tokens=1,2,3,4,5,6 delims=: " %%i in ("%~1") do ( + set monthname=%%i + set day=%%j + set year=%%k + set hour=%%l + set minutes=%%m + set timezone=%%n +) + +:: Separate the am/pm and the minutes value into different variables +set ampm=%minutes:~2,2% +set minutes=%minutes:~0,2% + +:: Check if the day needs to be changed based on the status of "am/pm" +if %ampm%==pm ( + set /a day+=1 + set ampm=am +) else ( + set ampm=pm +) + +:: Get the number corresponding to the month given +set tempcount=0 +for %%i in (%namesofmonths%) do ( + set /a tempcount+=1 + if %monthname%==%%i set monthcount=!tempcount! +) + +:: As this step may may be needed to repeat if the month needs to be changed, we add a label here +:getdaysinthemonth +:: Work out how many days are in the current month +set tempcount=0 +for %%i in (%daysinmonth%) do ( + set /a tempcount+=1 + if %monthcount%==!tempcount! set daysinthemonth=%%i +) + +:: If the month is February, check if it is a leap year. If so, add 1 to the amount of days in the month +if %daysinthemonth%==28 ( + set /a leapyearcheck=%year% %% 4 + if !leapyearcheck!==0 set /a daysinthemonth+=1 +) + +:: Check if the month needs to be changed based on the current day and how many days there are in the current month +if %day% gtr %daysinthemonth% ( + set /a monthcount+=1 + set day=1 + if !monthcount! gtr 12 ( + set monthcount=1 + set /a year+=1 + ) + goto getdaysinthemonth +) +:: Everything from :getdaysinthemonth will be repeated once if the month needs to be changed + +:: This block is only required to change the name of the month for the output, however as you have %monthcount%, this is optional +set tempcount=0 +for %%i in (%namesofmonths%) do ( + set /a tempcount+=1 + if %monthcount%==!tempcount! set monthname=%%i +) + +echo Original - %~1 +echo Manipulated - %monthname% %day% %year% %hour%:%minutes%%ampm% %timezone% +exit /b diff --git a/Task/Date-manipulation/jq/date-manipulation-1.jq b/Task/Date-manipulation/Jq/date-manipulation-1.jq similarity index 100% rename from Task/Date-manipulation/jq/date-manipulation-1.jq rename to Task/Date-manipulation/Jq/date-manipulation-1.jq diff --git a/Task/Date-manipulation/jq/date-manipulation-2.jq b/Task/Date-manipulation/Jq/date-manipulation-2.jq similarity index 100% rename from Task/Date-manipulation/jq/date-manipulation-2.jq rename to Task/Date-manipulation/Jq/date-manipulation-2.jq diff --git a/Task/Date-manipulation/Kotlin/date-manipulation.kotlin b/Task/Date-manipulation/Kotlin/date-manipulation.kotlin new file mode 100644 index 0000000000..39aa810d04 --- /dev/null +++ b/Task/Date-manipulation/Kotlin/date-manipulation.kotlin @@ -0,0 +1,19 @@ +// version 1.0.6 + +import java.text.SimpleDateFormat +import java.util.* + +fun main(args: Array) { + val dts = "March 7 2009 7:30pm EST" + val sdf = SimpleDateFormat("MMMM d yyyy h:mma z") + val dt = sdf.parse(dts) + val cal = GregorianCalendar(TimeZone.getTimeZone("EST")) // stay with EST + cal.time = dt + cal.add(Calendar.HOUR_OF_DAY, 12) // add 12 hours + val fmt = "%tB %1\$td %1\$tY %1\$tl:%1\$tM%1\$tp %1\$tZ" + println(fmt.format(cal)) // display new time + + // display time now in Mountain Standard Time which is 2 hours earlier than EST + cal.timeZone = TimeZone.getTimeZone("MST") + println(fmt.format(cal)) +} diff --git a/Task/Date-manipulation/MIRC-Scripting-Language/date-manipulation.mirc b/Task/Date-manipulation/MIRC-Scripting-Language/date-manipulation.mirc new file mode 100644 index 0000000000..cc79f65118 --- /dev/null +++ b/Task/Date-manipulation/MIRC-Scripting-Language/date-manipulation.mirc @@ -0,0 +1 @@ +echo -ag $asctime($calc($ctime(March 7 2009 7:30pm EST)+43200)) diff --git a/Task/Date-manipulation/OoRexx/date-manipulation-1.rexx b/Task/Date-manipulation/OoRexx/date-manipulation-1.rexx new file mode 100644 index 0000000000..e84a4f2416 --- /dev/null +++ b/Task/Date-manipulation/OoRexx/date-manipulation-1.rexx @@ -0,0 +1,126 @@ + sampleDate = 'March 7 2009 7:30pm EST' + + Parse var sampleDate month day year time zone + basedate = .DateTime~fromNormalDate(day month~left(3) year) + basetime = .DateTime~fromCivilTime(time) + -- this will give us this in a merged format...now we can add in the + -- timezone informat + mergedTime = (basedate + basetime~timeofday)~isoDate + zone = .TimeZoneDataBase~getTimeZone(zone) + + finalTime = .DateTime~fromIsoDate(mergedTime, zone~datetimeOffset) + + say 'Original date:' finalTime~utcIsoDate + say 'Result after adding 12 hours:' finalTime~addHours(12)~utcIsoDate + say 'Result shifted to UTC:' finalTime~toTimeZone(0)~utcIsoDate + say 'Result shifted to Pacific Standard Time:' finalTime~toTimeZone(.TimeZoneDataBase~getTimeZone('PST')~datetimeOffset)~utcIsoDate + say 'Result shifted to NepalTime Time:' finalTime~toTimeZone(.TimeZoneDataBase~getTimeZone('NPT')~datetimeOffset)~utcIsoDate + +-- a descriptor for timezone information +::class timezone +::method init + expose code name offset altname region + use strict arg code, name, offset, altname, region + code~upper + +::attribute code GET +::attribute name GET +::attribute offset GET +::attribute altname GET +::attribute region GET +::attribute datetimeOffset GET + expose offset + return offset * 60 + +-- our database of timezones +::class timezonedatabase +-- initialize the class object. This occurs when the program is first loaded +::method init class + expose timezones + + timezones = .directory~new + -- extract the timezone data which is conveniently stored in a method + data = self~instanceMethod('TIMEZONEDATA')~source + + loop line over data + -- skip over the comment delimiters, blank lines, and the 'return' + -- lines that force the comments to be included in the source + if line = '/*' | line = '*/' | line = '' | line = 'return' then iterate + parse var line '{' region '}' + if region \= '' then do + zregion = region + iterate + end + else do + parse var line abbrev . '!' fullname '!' altname . '!' offset . + timezone = .timezone~new(abbrev, fullname, offset, altname, zregion) + timezones[timezone~code] = timezone + end + end + +::method getTimezone class + expose timezones + use strict arg code + return timezones[code~upper] + +-- this is a dummy method containing the timezone database data. +-- we'll access the source directly and extract the data held in comments +-- the two return statements force the comment lines to be included in the +-- source rather than processed as part of comments between directives +::method timeZoneData class private +return +/* +{Universal} +UTC ! Coordinated Universal Time ! ! 0 + +{Europe} +BST ! British Summer Time ! ! +1 +CEST ! Central European Summer Time ! ! +2 +CET ! Central European Time ! ! +1 +EEST ! Eastern European Summer Time ! ! +3 +EET ! Eastern European Time ! ! +2 +GMT ! Greenwich Mean Time ! ! 0 +IST ! Irish Standard Time ! ! +1 +KUYT ! Kuybyshev Time ! ! +4 +MSD ! Moscow Daylight Time ! ! +4 +MSK ! Moscow Standard Time ! ! +3 +SAMT ! Samara Time ! ! +4 +WEST ! Western European Summer Time ! ! +1 +WET ! Western European Time ! ! 0 + +{North America} +ADT ! Atlantic Daylight Time ! HAA ! -3 +AKDT ! Alaska Daylight Time ! HAY ! -8 +AKST ! Alaska Standard Time ! HNY ! -9 +AST ! Atlantic Standard Time ! HNA ! -4 +CDT ! Central Daylight Time ! HAC ! -5 +CST ! Central Standard Time ! HNC ! -6 +EDT ! Eastern Daylight Time ! HAE ! -4 +EGST ! Eastern Greenland Summer Time ! ! 0 +EGT ! East Greenland Time ! ! -1 +EST ! Eastern Standard Time ! HNE,ET ! -5 +HADT ! Hawaii-Aleutian Daylight Time ! ! -9 +HAST ! Hawaii-Aleutian Standard Time ! ! -10 +MDT ! Mountain Daylight Time ! HAR ! -6 +MST ! Mountain Standard Time ! HNR ! -7 +NDT ! Newfoundland Daylight Time ! HAT ! -2.5 +NST ! Newfoundland Standard Time ! HNT ! -3.5 +PDT ! Pacific Daylight Time ! HAP ! -7 +PMDT ! Pierre & Miquelon Daylight Time ! ! -2 +PMST ! Pierre & Miquelon Standard Time ! ! -3 +PST ! Pacific Standard Time ! HNP,PT ! -8 +WGST ! Western Greenland Summer Time ! ! -2 +WGT ! West Greenland Time ! ! -3 + +{India and Indian Ocean} +IST ! India Standard Time ! ! +5.5 +PKT ! Pakistan Standard Time ! ! +5 +BST ! Bangladesh Standard Time ! ! +6 -- Note: collision with British Summer Time +NPT ! Nepal Time ! ! +5.75 +BTT ! Bhutan Time ! ! +6 +BIOT ! British Indian Ocean Territory Time ! IOT ! +6 +MVT ! Maldives Time ! ! +5 +CCT ! Cocos Islands Time ! ! +6.5 +TFT ! French Southern and Antarctic Time ! ! +5 +*/ +return diff --git a/Task/Date-manipulation/OoRexx/date-manipulation-2.rexx b/Task/Date-manipulation/OoRexx/date-manipulation-2.rexx new file mode 100644 index 0000000000..c4ee5624f4 --- /dev/null +++ b/Task/Date-manipulation/OoRexx/date-manipulation-2.rexx @@ -0,0 +1,217 @@ +/* Rexx */ + sampleDate = 'March 7 2009 7:30pm EST' + + Parse value sampleDate with tm td ty tt tz . + Parse value time('l', tt, 'c') with hh ':' mm ':' ss '.' us . + + timezones. = '' + Call initTimezones + mn = monthNameToNumber(tm) + zuluOffset = getTZOffset(tz) + + Drop !TZ !MSG + day.1.!TZ = zuluOffset + day.1.!MSG = 'Original date:' + day.1 = .DateTime~new(ty, mn, td, hh, mm, ss, us, day.1.!TZ * 60) + day.2.!TZ = zuluOffset + day.2.!MSG = 'Result after adding 12 hours to date:' + day.2 = day.1~addHours(12) + day.3.!TZ = getTZOffset('UTC') -- AKA GMT == Greenwich Mean Time + day.3.!MSG = 'Result shifted to "UTC (Zulu)" time zone:' + day.3 = day.1~toTimeZone(day.3.!TZ) + day.4.!TZ = getTZOffset('PST') -- Pacific Standard Time + day.4.!MSG = 'Result shifted to "Pacific Standard Time" time zone:' + day.4 = day.2~toTimeZone(day.4.!TZ * 60) + day.5.!TZ = getTZOffset('NPT') -- Nepal Time + day.5.!MSG = 'Result shifted to "Nepal Time" time zone:' + day.5 = day.2~toTimeZone(day.5.!TZ * 60) + day.0 = 5 + + Say 'Manipulate the date string "'sampleDate'" and present results in ISO 8601 timestamp format:' + Say + Loop d_ = 1 to day.0 + Say day.d_.!MSG + Say day.d_~isoDate || getUTCOffset(day.d_.!TZ, 'z') + Say + End d_ + +Return 0 + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +isTrue: Procedure; Return (1 == 1) + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +isFalse: Procedure; Return \isTrue() + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +monthNameToNumber: +Procedure +Do + Parse arg tm . + + mnamesList = 'January February March April May June July August September October November December' + + Loop mn = 1 to mnamesList~words + mnx = mnamesList~word(mn) + If mnx~upper~abbrev(tm~upper, 3) then Do + Leave mn + End + End mn + + Return mn +End +Exit + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +getTZOffset: +Procedure expose timezones. +Do + Parse upper arg tz . + Drop !REGION !FULLNAME !OFFSET !ZNAMEALT + + offset = 0 + Loop z_ = 1 to timezones.0 + If tz = timezones.z_ then Do + offset = timezones.z_.!OFFSET + Leave z_ + End + End z_ + + Return offset; +End +Exit + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +getUTCOffset: +Procedure expose timezones. +Do + Parse arg oh ., zulu . + + oha = abs(oh) + If oha = 0 & 'ZULU'~abbrev(zulu~upper, 1) then Do + offset = 'Z' + End + else Do + If oh < 0 then ew = '-' + else ew = '+' + om = oha * 60 + oom = om // 60 % 1 + ooh = om % 60 + offset = ew || ooh~right(2, 0) || oom~right(2, 0) + End + + Return offset +End +Exit + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +initTimezones: +Procedure expose timezones. +Do + -- Read time zone info from formatted comment block below + Drop !REGION !FULLNAME !OFFSET !ZNAMEALT + timezones.0 = 0 + region = '' + !datBegin = '__DATA__' + !datEnd = '__ENDD__' + !reading = isFalse() + + Loop l_ = 1 to sourceline() + Parse value sourceline(l_) with sl 0 hd +8 . + If !reading then Do + If hd = !datEnd then Do + !reading = isFalse() + Leave l_ + End + else Do + Parse value sl with sl '--' . + If sl~strip~length = 0 then Iterate l_ + Parse value sl with, + 0 '{' zRegion '}', + 0 zAbbrev . '!' zFullName '!' zAbbrevOther . '!' zUOffset . + If zRegion~length \= 0 then Do + region = zRegion + Iterate l_ + End + else Do + z_ = timezones.0 + 1 + timezones.0 = z_ + timezones.z_ = zAbbrev~strip~upper + timezones.z_.!FULLNAME = zFullName~strip + timezones.z_.!OFFSET = zUOffset~format + timezones.z_.!ZNAMEALT = zAbbrevOther~strip~upper + timezones.z_.!REGION = region + End + End + End + else Do + If hd = !datBegin then Do + !reading = isTrue() + End + Iterate l_ + End + End l_ + + Return timezones.0 +End +Exit +/* + A "HERE" document, sort of... + Everything between the __DATA__ and __ENDD__ delimiters will be read into the timezones. stem: + +__DATA__ +{Universal} +UTC ! Coordinated Universal Time ! ! 0 + +{Europe} +BST ! British Summer Time ! ! +1 +CEST ! Central European Summer Time ! ! +2 +CET ! Central European Time ! ! +1 +EEST ! Eastern European Summer Time ! ! +3 +EET ! Eastern European Time ! ! +2 +GMT ! Greenwich Mean Time ! ! 0 +IST ! Irish Standard Time ! ! +1 +KUYT ! Kuybyshev Time ! ! +4 +MSD ! Moscow Daylight Time ! ! +4 +MSK ! Moscow Standard Time ! ! +3 +SAMT ! Samara Time ! ! +4 +WEST ! Western European Summer Time ! ! +1 +WET ! Western European Time ! ! 0 + +{North America} +ADT ! Atlantic Daylight Time ! HAA ! -3 +AKDT ! Alaska Daylight Time ! HAY ! -8 +AKST ! Alaska Standard Time ! HNY ! -9 +AST ! Atlantic Standard Time ! HNA ! -4 +CDT ! Central Daylight Time ! HAC ! -5 +CST ! Central Standard Time ! HNC ! -6 +EDT ! Eastern Daylight Time ! HAE ! -4 +EGST ! Eastern Greenland Summer Time ! ! 0 +EGT ! East Greenland Time ! ! -1 +EST ! Eastern Standard Time ! HNE,ET ! -5 +HADT ! Hawaii-Aleutian Daylight Time ! ! -9 +HAST ! Hawaii-Aleutian Standard Time ! ! -10 +MDT ! Mountain Daylight Time ! HAR ! -6 +MST ! Mountain Standard Time ! HNR ! -7 +NDT ! Newfoundland Daylight Time ! HAT ! -2.5 +NST ! Newfoundland Standard Time ! HNT ! -3.5 +PDT ! Pacific Daylight Time ! HAP ! -7 +PMDT ! Pierre & Miquelon Daylight Time ! ! -2 +PMST ! Pierre & Miquelon Standard Time ! ! -3 +PST ! Pacific Standard Time ! HNP,PT ! -8 +WGST ! Western Greenland Summer Time ! ! -2 +WGT ! West Greenland Time ! ! -3 + +{India and Indian Ocean} +IST ! India Standard Time ! ! +5.5 +PKT ! Pakistan Standard Time ! ! +5 +BST ! Bangladesh Standard Time ! ! +6 -- Note: collision with British Summer Time +NPT ! Nepal Time ! ! +5.75 +BTT ! Bhutan Time ! ! +6 +BIOT ! British Indian Ocean Territory Time ! IOT ! +6 +MVT ! Maldives Time ! ! +5 +CCT ! Cocos Islands Time ! ! +6.5 +TFT ! French Southern and Antarctic Time ! ! +5 + +__ENDD__ +*/ diff --git a/Task/Date-manipulation/SQL/date-manipulation.sql b/Task/Date-manipulation/SQL/date-manipulation.sql new file mode 100644 index 0000000000..677ef348fd --- /dev/null +++ b/Task/Date-manipulation/SQL/date-manipulation.sql @@ -0,0 +1,32 @@ +-- March 7 2009 7:30pm EST + +select +TO_TIMESTAMP_TZ( +'March 7 2009 7:30pm EST', +'MONTH DD YYYY HH:MIAM TZR' +) +at time zone 'US/Eastern' orig_dt_time +from dual; + +-- 12 hours later DST change + +select +(TO_TIMESTAMP_TZ( +'March 7 2009 7:30pm EST', +'MONTH DD YYYY HH:MIAM TZR' +)+ +INTERVAL '12' HOUR) +at time zone 'US/Eastern' plus_12_dst +from dual; + +-- 12 hours later no DST change +-- Arizona time, always MST + +select +(TO_TIMESTAMP_TZ( +'March 7 2009 7:30pm EST', +'MONTH DD YYYY HH:MIAM TZR' +)+ +INTERVAL '12' HOUR) +at time zone 'US/Arizona' plus_12_nodst +from dual; diff --git a/Task/Date-manipulation/Zkl/date-manipulation-1.zkl b/Task/Date-manipulation/Zkl/date-manipulation-1.zkl new file mode 100644 index 0000000000..3a49bc28a5 --- /dev/null +++ b/Task/Date-manipulation/Zkl/date-manipulation-1.zkl @@ -0,0 +1,11 @@ +var Date=Time.Date; +fcn add12h(dt){ + re:=RegExp(0'|(\w+)\s+(\d+)\s+(\d+)\ +(.+)\s|); + re.search(dt); + _,M,D,Y,hms:=re.matched; //"March","7","2009","7:30pm" + M=Date.monthNames.index(M); //3 + h,m,s:=Date.parseTime(hms); //19,30,0 + dti:=T(Y,M,D, h,m,s).apply("toInt"); + Y,M,D, h,m,s=Date.addHMS(dti,12); + "%s %d %d %s".fmt(Date.monthNames[M],D,Y,Date.toAMPMString(h,m)); +} diff --git a/Task/Date-manipulation/Zkl/date-manipulation-2.zkl b/Task/Date-manipulation/Zkl/date-manipulation-2.zkl new file mode 100644 index 0000000000..481058e1b9 --- /dev/null +++ b/Task/Date-manipulation/Zkl/date-manipulation-2.zkl @@ -0,0 +1 @@ +add12h("March 7 2009 7:30pm EST").println(); diff --git a/Task/Day-of-the-week/AppleScript/day-of-the-week-2.applescript b/Task/Day-of-the-week/AppleScript/day-of-the-week-2.applescript index a28843b4fa..c65b2061bb 100644 --- a/Task/Day-of-the-week/AppleScript/day-of-the-week-2.applescript +++ b/Task/Day-of-the-week/AppleScript/day-of-the-week-2.applescript @@ -1,8 +1,4 @@ -on run - - filter(xmasIsSunday, range(2008, 2121)) - -end run +filter(xmasIsSunday, enumFromTo(2008, 2121)) -- xmasIsSunday :: Int -> Bool @@ -14,33 +10,43 @@ on xmasIsSunday(y) end xmasIsSunday +-- GENERIC FUNCTIONS ---------------------------------------------------------- --- GENERIC FUNCTIONS +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) - script mf - property lambda : f - end script - - set lst to {} - set lng to length of xs - repeat with i from 1 to lng - set v to item i of xs - if mf's lambda(v, i, xs) then - set end of lst to v - end if - end repeat - return lst + tell mReturn(f) + set lst to {} + set lng to length of xs + repeat with i from 1 to lng + set v to item i of xs + if |λ|(v, i, xs) then set end of lst to v + end repeat + return lst + end tell end filter --- range :: Int -> Int -> [Int] -on range(m, n) - set lng to (n - m) + 1 - set base to m - 1 - set lst to {} - repeat with i from 1 to lng - set end of lst to i + base - end repeat - return lst -end range +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn diff --git a/Task/Day-of-the-week/AppleScript/day-of-the-week-3.applescript b/Task/Day-of-the-week/AppleScript/day-of-the-week-3.applescript new file mode 100644 index 0000000000..273f9de48a --- /dev/null +++ b/Task/Day-of-the-week/AppleScript/day-of-the-week-3.applescript @@ -0,0 +1,2 @@ +{2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, +2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118} diff --git a/Task/Day-of-the-week/BASIC/day-of-the-week-2.basic b/Task/Day-of-the-week/BASIC/day-of-the-week-2.basic index f710497dc0..49ee14042e 100644 --- a/Task/Day-of-the-week/BASIC/day-of-the-week-2.basic +++ b/Task/Day-of-the-week/BASIC/day-of-the-week-2.basic @@ -1,24 +1,6 @@ -' version 17-06-2015 -' compile with: fbc -s console - -Function wd(m As Integer, d As Integer, y As Integer) As Integer - If m < 3 Then ' If m = 1 Or m = 2 Then - m += 12 - y -= 1 - End If - Return (y + (y \ 4) - (y \ 100) + (y \ 400) + d + ((153 * m + 8) \ 5)) Mod 7 -End Function - -' ------=< MAIN >=------ - -For yr As Integer = 2008 To 2121 - If wd(12, 25, yr) = 0 Then - Print "Dec 25 "; yr - EndIf -Next - -' empty keyboard buffer -While InKey <> "" : Wend -Print : Print "hit any key to end program" -Sleep -End +' Sunday Christmas +PRINT "Years with Christmas on a Sunday" +FOR y = 2008 TO 2121 + tv = TIMEVALUE(y, 12, 25, 0, 0, 0) + IF WEEKDAY$(tv) = "Sunday" THEN PRINT y +NEXT diff --git a/Task/Day-of-the-week/BASIC/day-of-the-week-3.basic b/Task/Day-of-the-week/BASIC/day-of-the-week-3.basic index 0b877a0389..f710497dc0 100644 --- a/Task/Day-of-the-week/BASIC/day-of-the-week-3.basic +++ b/Task/Day-of-the-week/BASIC/day-of-the-week-3.basic @@ -1,13 +1,20 @@ ' version 17-06-2015 -' Weekday And DateSerial only works with #Include "vbcompat.bi" ' compile with: fbc -s console -#Include Once "vbcompat.bi" -Dim As Double a +Function wd(m As Integer, d As Integer, y As Integer) As Integer + If m < 3 Then ' If m = 1 Or m = 2 Then + m += 12 + y -= 1 + End If + Return (y + (y \ 4) - (y \ 100) + (y \ 400) + d + ((153 * m + 8) \ 5)) Mod 7 +End Function + +' ------=< MAIN >=------ For yr As Integer = 2008 To 2121 - a = DateSerial (yr, 12, 25) - If Weekday(a) = 1 Then Print Format(a, "dd-mm-yyyy") ' 1 = sunday, 2 = monday ... + If wd(12, 25, yr) = 0 Then + Print "Dec 25 "; yr + EndIf Next ' empty keyboard buffer diff --git a/Task/Day-of-the-week/BASIC/day-of-the-week-4.basic b/Task/Day-of-the-week/BASIC/day-of-the-week-4.basic new file mode 100644 index 0000000000..0b877a0389 --- /dev/null +++ b/Task/Day-of-the-week/BASIC/day-of-the-week-4.basic @@ -0,0 +1,17 @@ +' version 17-06-2015 +' Weekday And DateSerial only works with #Include "vbcompat.bi" +' compile with: fbc -s console + +#Include Once "vbcompat.bi" +Dim As Double a + +For yr As Integer = 2008 To 2121 + a = DateSerial (yr, 12, 25) + If Weekday(a) = 1 Then Print Format(a, "dd-mm-yyyy") ' 1 = sunday, 2 = monday ... +Next + +' empty keyboard buffer +While InKey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Day-of-the-week/BASIC/day-of-the-week-5.basic b/Task/Day-of-the-week/BASIC/day-of-the-week-5.basic new file mode 100644 index 0000000000..12cfeee062 --- /dev/null +++ b/Task/Day-of-the-week/BASIC/day-of-the-week-5.basic @@ -0,0 +1,13 @@ + 10 LET M=12 + 20 LET D=25 + 30 FOR Y=2008 TO 2121 + 40 GOSUB 80 + 50 IF W=0 THEN PRINT Y + 60 NEXT Y + 70 STOP + 80 LET A=INT ((14-M)/12) + 90 LET MM=M+12*A-2 +100 LET YY=Y-A +110 LET W=D+INT ((13*MM-1)/5)+YY+INT (YY/4)-INT (YY/100)+INT (YY/400) +120 LET W=W-7*INT (W/7) +130 RETURN diff --git a/Task/Day-of-the-week/Bc/day-of-the-week.bc b/Task/Day-of-the-week/Bc/day-of-the-week.bc new file mode 100644 index 0000000000..51744d8caf --- /dev/null +++ b/Task/Day-of-the-week/Bc/day-of-the-week.bc @@ -0,0 +1,22 @@ +scale = 0 + +/* + * Returns day of week (0 to 6) for year, month m, day d in proleptic + * Gregorian calendar. Sunday is 0. Assumes y >= 1, scale = 0. + */ +define w(y, m, d) { + auto a + + /* Calculate Zeller's congruence. */ + a = (14 - m) / 12 + m += 12 * a + y -= a + return ((d + (13 * m + 8) / 5 + \ + y + y / 4 - y / 100 + y / 400) % 7) +} + +for (y = 2008; y <= 2121; y++) { + /* If December 25 is a Sunday, print year. */ + if (w(y, 12, 25) == 0) y +} +quit diff --git a/Task/Day-of-the-week/CoffeeScript/day-of-the-week-3.coffee b/Task/Day-of-the-week/CoffeeScript/day-of-the-week-3.coffee deleted file mode 100644 index 34aad888da..0000000000 --- a/Task/Day-of-the-week/CoffeeScript/day-of-the-week-3.coffee +++ /dev/null @@ -1,17 +0,0 @@ -2011 -2016 -2022 -2033 -2039 -2044 -2050 -2061 -2067 -2072 -2078 -2089 -2095 -2101 -2107 -2112 -2118 diff --git a/Task/Day-of-the-week/Component-Pascal/day-of-the-week.component b/Task/Day-of-the-week/Component-Pascal/day-of-the-week.component new file mode 100644 index 0000000000..34daa7c912 --- /dev/null +++ b/Task/Day-of-the-week/Component-Pascal/day-of-the-week.component @@ -0,0 +1,37 @@ +MODULE DayOfWeek; +IMPORT DevCommanders, TextMappers, Dates, StdLog; + +PROCEDURE XmastOnSun(s,e: INTEGER); +VAR + i: INTEGER; + d: Dates.Date; +BEGIN + i := s;d.day := 25;d.month := 12; + WHILE i < e DO + d.year := i; + IF Dates.DayOfWeek(d) = Dates.sunday THEN + StdLog.Int(i);StdLog.Ln + END; + INC(i) + END +END XmastOnSun; + +PROCEDURE Do*; +VAR + s: TextMappers.Scanner; + r: ARRAY 2 OF INTEGER; + i: INTEGER; +BEGIN + s.ConnectTo(DevCommanders.par.text); + s.SetPos(DevCommanders.par.beg); + s.Scan;i := 0; + WHILE ~s.rider.eot DO + IF s.type = TextMappers.int THEN + r[i] := s.int; INC(i) + END; + s.Scan + END; + XmastOnSun(r[0],r[1]); +END Do; + +END DayOfWeek. diff --git a/Task/Day-of-the-week/Elixir/day-of-the-week.elixir b/Task/Day-of-the-week/Elixir/day-of-the-week.elixir index 02b7e8caa6..28e740e7ea 100644 --- a/Task/Day-of-the-week/Elixir/day-of-the-week.elixir +++ b/Task/Day-of-the-week/Elixir/day-of-the-week.elixir @@ -1,4 +1,4 @@ Enum.each(2008..2121, fn year -> - wday = :calendar.day_of_the_week(year, 12, 25) + wday = Date.from_erl!({year, 12, 25}) |> Date.day_of_week if wday==7, do: IO.puts "25 December #{year} is sunday" end) diff --git a/Task/Day-of-the-week/Gambas/day-of-the-week.gambas b/Task/Day-of-the-week/Gambas/day-of-the-week.gambas new file mode 100644 index 0000000000..39ac2599be --- /dev/null +++ b/Task/Day-of-the-week/Gambas/day-of-the-week.gambas @@ -0,0 +1,8 @@ +Public Sub Main() +Dim siCount As Short + +For siCount = 2008 To 2121 + If WeekDay(Date(siCount, 12, 25)) = 0 Then Print Format(Date(siCount, 12, 25), "dddd dd mmmm yyyy") & " falls on a Sunday" +Next + +End diff --git a/Task/Day-of-the-week/Haskell/day-of-the-week-1.hs b/Task/Day-of-the-week/Haskell/day-of-the-week-1.hs index 7df32420cc..760a7b4fa8 100644 --- a/Task/Day-of-the-week/Haskell/day-of-the-week-1.hs +++ b/Task/Day-of-the-week/Haskell/day-of-the-week-1.hs @@ -1,8 +1,16 @@ -import Data.Time -import Data.Time.Calendar.WeekDate +import Data.Time (fromGregorian) -isXmasSunday year = wday == 7 - where (_,_,wday) = toWeekDate $ fromGregorian year 12 25 +import Data.Time.Calendar.WeekDate (toWeekDate) -main = mapM_ putStrLn ["25 December " ++ show year ++ " is Sunday" - | year <- [2008..2121], isXmasSunday year] +isXmasSunday :: Integer -> Bool +isXmasSunday year = + let (_, _, wday) = toWeekDate $ fromGregorian year 12 25 + in wday == 7 + +main :: IO () +main = + mapM_ + putStrLn + [ "25 December " ++ show year ++ " is Sunday" + | year <- [2008 .. 2121] + , isXmasSunday year ] diff --git a/Task/Day-of-the-week/Haskell/day-of-the-week-2.hs b/Task/Day-of-the-week/Haskell/day-of-the-week-2.hs index c872b5b2a9..94a10c691a 100644 --- a/Task/Day-of-the-week/Haskell/day-of-the-week-2.hs +++ b/Task/Day-of-the-week/Haskell/day-of-the-week-2.hs @@ -1,21 +1,29 @@ import System.Time +isXmasSunday :: Int -> Bool isXmasSunday year = ctWDay cal == Sunday - where cal = toUTCTime $ toClockTime cal' - cal' = CalendarTime { - ctYear = year, - ctMonth = December, - ctDay = 25, - ctHour = 0, - ctMin = 0, - ctSec = 0, - ctPicosec = 0, - ctWDay = Friday, - ctYDay = 0, - ctTZName = "", - ctTZ = 0, - ctIsDST = False - } + where + cal = toUTCTime $ toClockTime cal' + cal' = + CalendarTime + { ctYear = year + , ctMonth = December + , ctDay = 25 + , ctHour = 0 + , ctMin = 0 + , ctSec = 0 + , ctPicosec = 0 + , ctWDay = Friday + , ctYDay = 0 + , ctTZName = "" + , ctTZ = 0 + , ctIsDST = False + } -main = mapM_ putStrLn ["25 December " ++ show year ++ " is Sunday" - | year <- [2008..2121], isXmasSunday year] +main :: IO () +main = + mapM_ + putStrLn + [ "25 December " ++ show year ++ " is Sunday" + | year <- [2008 .. 2121] + , isXmasSunday year ] diff --git a/Task/Day-of-the-week/JavaScript/day-of-the-week-3.js b/Task/Day-of-the-week/JavaScript/day-of-the-week-3.js new file mode 100644 index 0000000000..7095c8a41f --- /dev/null +++ b/Task/Day-of-the-week/JavaScript/day-of-the-week-3.js @@ -0,0 +1,19 @@ +(() => { + 'use strict'; + + // xmasIsSunday :: Integer -> Bool + const xmasIsSunday = year => (new Date(year, 11, 25)) + .getDay() === 0; + + // range :: Int -> Int -> [Int] + const range = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + + + return range(2008, 2121) + .filter(xmasIsSunday); + +})(); diff --git a/Task/Day-of-the-week/JavaScript/day-of-the-week-4.js b/Task/Day-of-the-week/JavaScript/day-of-the-week-4.js new file mode 100644 index 0000000000..b4215849e6 --- /dev/null +++ b/Task/Day-of-the-week/JavaScript/day-of-the-week-4.js @@ -0,0 +1 @@ +[2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118] diff --git a/Task/Day-of-the-week/jq/day-of-the-week-1.jq b/Task/Day-of-the-week/Jq/day-of-the-week-1.jq similarity index 100% rename from Task/Day-of-the-week/jq/day-of-the-week-1.jq rename to Task/Day-of-the-week/Jq/day-of-the-week-1.jq diff --git a/Task/Day-of-the-week/jq/day-of-the-week-2.jq b/Task/Day-of-the-week/Jq/day-of-the-week-2.jq similarity index 100% rename from Task/Day-of-the-week/jq/day-of-the-week-2.jq rename to Task/Day-of-the-week/Jq/day-of-the-week-2.jq diff --git a/Task/Day-of-the-week/Kotlin/day-of-the-week.kotlin b/Task/Day-of-the-week/Kotlin/day-of-the-week.kotlin new file mode 100644 index 0000000000..529976531d --- /dev/null +++ b/Task/Day-of-the-week/Kotlin/day-of-the-week.kotlin @@ -0,0 +1,12 @@ +// version 1.0.6 + +import java.util.* + +fun main(args: Array) { + println("Christmas day in the following years falls on a Sunday:\n") + val calendar = GregorianCalendar(2008, Calendar.DECEMBER, 25) + for (year in 2008..2121) { + if (Calendar.SUNDAY == calendar[Calendar.DAY_OF_WEEK]) println(year) + calendar.add(Calendar.YEAR, 1) + } +} diff --git a/Task/Day-of-the-week/Lua/day-of-the-week.lua b/Task/Day-of-the-week/Lua/day-of-the-week-1.lua similarity index 100% rename from Task/Day-of-the-week/Lua/day-of-the-week.lua rename to Task/Day-of-the-week/Lua/day-of-the-week-1.lua diff --git a/Task/Day-of-the-week/Lua/day-of-the-week-2.lua b/Task/Day-of-the-week/Lua/day-of-the-week-2.lua new file mode 100644 index 0000000000..b5ee5a8e44 --- /dev/null +++ b/Task/Day-of-the-week/Lua/day-of-the-week-2.lua @@ -0,0 +1,7 @@ +local dTab = {day = 25, month = 12} +for year = 2008, 2121 do + dTab.year = year + if os.date("%A", os.time(dTab)) == "Sunday" then + print(year) + end +end diff --git a/Task/Day-of-the-week/OoRexx/day-of-the-week.rexx b/Task/Day-of-the-week/OoRexx/day-of-the-week.rexx new file mode 100644 index 0000000000..0bb82258ba --- /dev/null +++ b/Task/Day-of-the-week/OoRexx/day-of-the-week.rexx @@ -0,0 +1,13 @@ +date = .datetime~new(2008, 12, 25) +lastdate = .datetime~new(2121, 12, 25) + +resultList = .array~new -- our collector of years + +-- date objects are directly comparable +loop while date <= lastdate + if date~weekday == 7 then resultList~append(date~year) + -- step to the next year + date = date~addYears(1) +end + +say "Christmas falls on Sunday in the years" resultList~toString("Line", ", ") diff --git a/Task/Day-of-the-week/PowerShell/day-of-the-week.psh b/Task/Day-of-the-week/PowerShell/day-of-the-week-1.psh similarity index 100% rename from Task/Day-of-the-week/PowerShell/day-of-the-week.psh rename to Task/Day-of-the-week/PowerShell/day-of-the-week-1.psh diff --git a/Task/Day-of-the-week/PowerShell/day-of-the-week-2.psh b/Task/Day-of-the-week/PowerShell/day-of-the-week-2.psh new file mode 100644 index 0000000000..5042dfcdc4 --- /dev/null +++ b/Task/Day-of-the-week/PowerShell/day-of-the-week-2.psh @@ -0,0 +1,34 @@ +function Get-ChristmasHoliday +{ + [CmdletBinding()] + [OutputType([PSCustomObject])] + Param + ( + [Parameter(Mandatory=$false, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true, + Position=0)] + [ValidateRange(1,9999)] + [int[]] + $Year = (Get-Date).Year + ) + + Process + { + [datetime]$christmas = Get-Date $Year/12/25 + + switch ($christmas.DayOfWeek) + { + "Sunday" {[datetime[]]$dates = 1..5 | ForEach-Object {$christmas.AddDays($_)}} + "Monday" {[datetime[]]$dates = $christmas, $christmas.AddDays(1)} + "Saturday" {[datetime[]]$dates = $christmas.AddDays(-2), $christmas.AddDays(-1)} + Default {[datetime[]]$dates = $christmas.AddDays(-1), $christmas} + } + + $dates | Group-Object -Property Year | + Select-Object -Property @{Name="Year" ; Expression={$_.Name}}, + @{Name="DayOfWeek"; Expression={$christmas.DayOfWeek}}, + @{Name="Christmas"; Expression={$christmas.ToString("MM/dd/yyyy")}}, + @{Name="DaysOff" ; Expression={$_.Group | ForEach-Object {$_.ToString("MM/dd/yyyy")}}} + } +} diff --git a/Task/Day-of-the-week/PowerShell/day-of-the-week-3.psh b/Task/Day-of-the-week/PowerShell/day-of-the-week-3.psh new file mode 100644 index 0000000000..6a846e95d6 --- /dev/null +++ b/Task/Day-of-the-week/PowerShell/day-of-the-week-3.psh @@ -0,0 +1 @@ +2008..2121 | Get-ChristmasHoliday | where DayOfWeek -match Su diff --git a/Task/Day-of-the-week/PowerShell/day-of-the-week-4.psh b/Task/Day-of-the-week/PowerShell/day-of-the-week-4.psh new file mode 100644 index 0000000000..0da0d11191 --- /dev/null +++ b/Task/Day-of-the-week/PowerShell/day-of-the-week-4.psh @@ -0,0 +1 @@ +Get-ChristmasHoliday -Year (2008..2121 | Get-Random) diff --git a/Task/Day-of-the-week/PowerShell/day-of-the-week-5.psh b/Task/Day-of-the-week/PowerShell/day-of-the-week-5.psh new file mode 100644 index 0000000000..6272f2c52a --- /dev/null +++ b/Task/Day-of-the-week/PowerShell/day-of-the-week-5.psh @@ -0,0 +1 @@ +(Get-Date | Get-ChristmasHoliday).DaysOff diff --git a/Task/Day-of-the-week/PowerShell/day-of-the-week-6.psh b/Task/Day-of-the-week/PowerShell/day-of-the-week-6.psh new file mode 100644 index 0000000000..d5e7086412 --- /dev/null +++ b/Task/Day-of-the-week/PowerShell/day-of-the-week-6.psh @@ -0,0 +1 @@ +(Get-Date | Get-ChristmasHoliday).DaysOff | Get-Date diff --git a/Task/Day-of-the-week/Protium/day-of-the-week-1.protium b/Task/Day-of-the-week/Protium/day-of-the-week-1.protium deleted file mode 100644 index 238047e37b..0000000000 --- a/Task/Day-of-the-week/Protium/day-of-the-week-1.protium +++ /dev/null @@ -1,9 +0,0 @@ -<@ SAI> - <@ ITEFORLI3>2121|2008| - <@ LETVARCAP>Christmas Day|25-Dec-<@ SAYVALFOR>... - <@ TSTDOWVARLIT>Christmas Day|1 - <@ IFF> - <@ SAYCAP>Christmas Day <@ SAYVALFOR>... is a Sunday<@ SAYKEY>__Newline - - - diff --git a/Task/Day-of-the-week/Protium/day-of-the-week-2.protium b/Task/Day-of-the-week/Protium/day-of-the-week-2.protium deleted file mode 100644 index 85ec282b61..0000000000 --- a/Task/Day-of-the-week/Protium/day-of-the-week-2.protium +++ /dev/null @@ -1,10 +0,0 @@ -<# suppressimplicitoutput> - <# iterate foriteration literalstring3>2121|2008| - <# let variable capture>Christmas Day|25-Dec-<# say value foriteration>... - <# test dayofweek variable literal>Christmas Day|1 - <# if> - <# say capture>Christmas Day <# say value foriteration>... is a Sunday<# say keyword>__Newline - - - - diff --git a/Task/Day-of-the-week/Python/day-of-the-week.py b/Task/Day-of-the-week/Python/day-of-the-week.py index 1396944d3d..6b77851a09 100644 --- a/Task/Day-of-the-week/Python/day-of-the-week.py +++ b/Task/Day-of-the-week/Python/day-of-the-week.py @@ -1,6 +1,3 @@ -from datetime import date +from calendar import weekday, SUNDAY -for year in range(2008, 2122): - day = date(year, 12, 25) - if day.weekday() == 6: - print(day.strftime('%d %b %Y')) +[year for year in range(2008, 2122) if weekday(year, 12, 25) == SUNDAY] diff --git a/Task/Day-of-the-week/R/day-of-the-week-1.r b/Task/Day-of-the-week/R/day-of-the-week-1.r deleted file mode 100644 index 22141d587d..0000000000 --- a/Task/Day-of-the-week/R/day-of-the-week-1.r +++ /dev/null @@ -1,3 +0,0 @@ -years <- 2008:2121 -xmas <- as.POSIXlt(paste(years, '/12/25', sep="")) -years[xmas$wday==0] diff --git a/Task/Day-of-the-week/R/day-of-the-week-2.r b/Task/Day-of-the-week/R/day-of-the-week-2.r deleted file mode 100644 index c40e7af8fd..0000000000 --- a/Task/Day-of-the-week/R/day-of-the-week-2.r +++ /dev/null @@ -1,4 +0,0 @@ -Also: - -xmas=seq(as.Date("2008/12/25"), as.Date("2121/12/25"), by="year") -as.numeric(format(xmas[weekdays(xmas)== 'Sunday'], "%Y")) diff --git a/Task/Day-of-the-week/R/day-of-the-week-3.r b/Task/Day-of-the-week/R/day-of-the-week-3.r deleted file mode 100644 index 2722bb1fe7..0000000000 --- a/Task/Day-of-the-week/R/day-of-the-week-3.r +++ /dev/null @@ -1,6 +0,0 @@ -#Still another solution, using ISOdate and weekdays -(2008:2121)[weekdays(ISOdate(2008:2121, 12, 25)) == "Sunday"] - -# Simply replace "Sunday" with whatever it's named in your country, -# or set locale first, with -Sys.setlocale(cat="LC_ALL", "en") diff --git a/Task/Day-of-the-week/Sidef/day-of-the-week.sidef b/Task/Day-of-the-week/Sidef/day-of-the-week.sidef index a1fec60ad1..6a1f729d3a 100644 --- a/Task/Day-of-the-week/Sidef/day-of-the-week.sidef +++ b/Task/Day-of-the-week/Sidef/day-of-the-week.sidef @@ -1,9 +1,9 @@ -var tl = frequire('Time::Local'); - -for year in (2008 ..^ 2121) { - var time = tl.timelocal(0,0,0,25,11,year); - var wd = Time.new(time).local.wday; +require('Time::Local') +  +for year in (2008 .. 2121) { + var time = %S.timelocal(0,0,0,25,11,year) + var wd = Time(time).local.wday if (wd == 0) { - say "25 Dec #{year} is Sunday"; + say "25 Dec #{year} is Sunday" } } diff --git a/Task/Day-of-the-week/Stata/day-of-the-week.stata b/Task/Day-of-the-week/Stata/day-of-the-week.stata new file mode 100644 index 0000000000..1f650bc1e4 --- /dev/null +++ b/Task/Day-of-the-week/Stata/day-of-the-week.stata @@ -0,0 +1,28 @@ +clear all +range year 2008 2121 `=2121-2008+1' +list if dow(mdy(12,25,year))==0 + + +------+ + | year | + |------| + 4. | 2011 | + 9. | 2016 | + 15. | 2022 | + 26. | 2033 | + 32. | 2039 | + |------| + 37. | 2044 | + 43. | 2050 | + 54. | 2061 | + 60. | 2067 | + 65. | 2072 | + |------| + 71. | 2078 | + 82. | 2089 | + 88. | 2095 | + 94. | 2101 | +100. | 2107 | + |------| +105. | 2112 | +111. | 2118 | + +------+ diff --git a/Task/Day-of-the-week/VBScript/day-of-the-week.vb b/Task/Day-of-the-week/VBScript/day-of-the-week.vb index 5c4fa890dc..9842fa8eb4 100644 --- a/Task/Day-of-the-week/VBScript/day-of-the-week.vb +++ b/Task/Day-of-the-week/VBScript/day-of-the-week.vb @@ -1,6 +1,5 @@ -For i = 2008 To 2121 - If Weekday(i & "-12-25") = 1 Then - WScript.StdOut.Write i - WScript.StdOut.WriteLine - End If +For year = 2008 To 2121 + If Weekday(DateSerial(year, 12, 25)) = 1 Then + WScript.Echo year + End If Next diff --git a/Task/Day-of-the-week/ZX-Spectrum-Basic/day-of-the-week.zx b/Task/Day-of-the-week/ZX-Spectrum-Basic/day-of-the-week.zx index 7605815f53..aa46a44be6 100644 --- a/Task/Day-of-the-week/ZX-Spectrum-Basic/day-of-the-week.zx +++ b/Task/Day-of-the-week/ZX-Spectrum-Basic/day-of-the-week.zx @@ -1,11 +1,11 @@ 10 CLS 20 FOR y=2008 TO 2121 30 LET year=y: LET m=12: LET d=25: GO SUB 1000 -40 IF wd=1 THEN PRINT d;" ";m;" ";y +40 IF wd=0 THEN PRINT d;" ";m;" ";y 50 NEXT y 60 STOP 1000 REM week day 1010 IF m=1 OR m=2 THEN LET m=m+12: LET year=year-1 -1020 LET wd=FN m(365*year+INT (year/4)-INT (year/100)+INT (year/400)+d+INT ((153*m+8)/5),7)+1 +1020 LET wd=FN m(year+INT (year/4)-INT (year/100)+INT (year/400)+d+INT ((153*m+8)/5),7) 1030 RETURN 1100 DEF FN m(a,b)=a-INT (a/b)*b diff --git a/Task/Day-of-the-week/Zkl/day-of-the-week-1.zkl b/Task/Day-of-the-week/Zkl/day-of-the-week-1.zkl new file mode 100644 index 0000000000..dd83a062f5 --- /dev/null +++ b/Task/Day-of-the-week/Zkl/day-of-the-week-1.zkl @@ -0,0 +1,4 @@ +var [const] D=Time.Date; +foreach y in ([2008..2121]){ + if (D.Sunday==D.weekDay(y,12,25)) println(y) +} diff --git a/Task/Day-of-the-week/Zkl/day-of-the-week-2.zkl b/Task/Day-of-the-week/Zkl/day-of-the-week-2.zkl new file mode 100644 index 0000000000..864701e7c8 --- /dev/null +++ b/Task/Day-of-the-week/Zkl/day-of-the-week-2.zkl @@ -0,0 +1,2 @@ +var [const] D=Time.Date; +[2008..2121].filter(fcn(y){ D.Sunday==D.weekDay(y,12,25) }).println() diff --git a/Task/Deal-cards-for-FreeCell/Elixir/deal-cards-for-freecell.elixir b/Task/Deal-cards-for-FreeCell/Elixir/deal-cards-for-freecell.elixir new file mode 100644 index 0000000000..b75b31bfad --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Elixir/deal-cards-for-freecell.elixir @@ -0,0 +1,29 @@ +defmodule FreeCell do + import Bitwise + + @suits ~w( C D H S ) + @pips ~w( A 2 3 4 5 6 7 8 9 T J Q K ) + @orig_deck for pip <- @pips, suit <- @suits, do: pip <> suit + + def deal(games) do + games = if length(games) == 0, do: [Enum.random(1..32000)], else: games + Enum.each(games, fn seed -> + IO.puts "Game ##{seed}" + Enum.reduce(52..2, {seed,@orig_deck}, fn len,{state,deck} -> + state = ((214013 * state) + 2531011) &&& 0x7fff_ffff + index = rem(state >>> 16, len) + last = len - 1 + {a, b} = {Enum.at(deck, index), Enum.at(deck, last)} + {state, deck |> List.replace_at(index, b) |> List.replace_at(last, a)} + end) + |> elem(1) + |> Enum.reverse + |> Enum.chunk(8,8,[]) + |> Enum.each(fn row -> Enum.join(row, " ") |> IO.puts end) + IO.puts "" + end) + end +end + +System.argv |> Enum.map(&String.to_integer/1) +|> FreeCell.deal diff --git a/Task/Deal-cards-for-FreeCell/Kotlin/deal-cards-for-freecell.kotlin b/Task/Deal-cards-for-FreeCell/Kotlin/deal-cards-for-freecell.kotlin new file mode 100644 index 0000000000..34791a8841 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Kotlin/deal-cards-for-freecell.kotlin @@ -0,0 +1,43 @@ +// version 1.1.3 + +class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) { + private var state = s + + fun nextInt(): Long { + state = (a * state + c) % m + return state / d + } +} + +const val CARDS = "A23456789TJQK" +const val SUITS = "♣♦♥♠" + +fun deal(): Array { + val cards = arrayOfNulls(52) + for (i in 0 until 52) { + val card = CARDS[i / 4] + val suit = SUITS[i % 4] + cards[i] = "$card$suit" + } + return cards +} + +fun game(n: Int) { + require(n > 0) + println("Game #$n:") + val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, n.toLong()) + val cards = deal() + for (m in 52 downTo 1) { + val index = (msc.nextInt() % m).toInt() + val temp = cards[index] + cards[index] = cards[m - 1] + print("$temp ") + if ((53 - m) % 8 == 0) println() + } + println("\n") +} + +fun main(args: Array) { + game(1) + game(617) +} diff --git a/Task/Deal-cards-for-FreeCell/Logo/deal-cards-for-freecell.logo b/Task/Deal-cards-for-FreeCell/Logo/deal-cards-for-freecell.logo new file mode 100644 index 0000000000..580c4bd5b6 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Logo/deal-cards-for-freecell.logo @@ -0,0 +1,56 @@ +; Linear congruential random number generator +make "_lcg_state 0 + +to seed_lcg :seed + make "_lcg_state :seed +end + +to sample_lcg + make "_lcg_state modulo sum product 214013 :_lcg_state 2531011 2147483648 + output int quotient :_lcg_state 65536 +end + +; FreeCell +to card_from_number :number + output word item sum 1 int quotient :number 4 "A23456789TJQK item sum 1 modulo :number 4 "CDHS +end + +to generate_deal :number + (local "deck "size "index "deal) + seed_lcg :number + make "deck [] + repeat 52 [ + make "deck lput difference # 1 :deck + ] + make "deck listtoarray :deck + make "deal [] + repeat 52 [ + make "size difference 53 # + make "index sum 1 modulo sample_lcg :size + make "deal lput item :index :deck :deal + setitem :index :deck item :size :deck + ] + output :deal +end + +to print_deal :number + (local "deal "i "j "index) + make "deal generate_deal :number + repeat 7 [ + make "i difference # 1 + repeat (ifelse [equal? :i 6] 4 8) [ + make "j difference # 1 + make "index (sum 1 product :i 8 :j) + type (word (card_from_number item :index :deal) "| |) + ] + print "|| + ] +end + +print [Game #1] +print_deal 1 +print "|| +print [Game #617] +print_deal 617 +print "|| +bye diff --git a/Task/Deal-cards-for-FreeCell/Phix/deal-cards-for-freecell.phix b/Task/Deal-cards-for-FreeCell/Phix/deal-cards-for-freecell.phix new file mode 100644 index 0000000000..30abcd00fc --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Phix/deal-cards-for-freecell.phix @@ -0,0 +1,39 @@ +atom seed + +function xrnd() + seed = and_bits(seed*214013+2531011,#7FFFFFFF) + return floor(seed/power(2,16)) +end function + +sequence cards = repeat(0,52) + +procedure deal(integer game_num) + seed = game_num + for i=1 to 52 do + cards[i] = 52-i + end for + for i=1 to 51 do + integer j = 52-mod(xrnd(),53-i) + integer s = cards[i] + cards[i] = cards[j] + cards[j] = s + end for +end procedure + +constant suits = "CDHS", + ranks = "A23456789TJQK" + +procedure show() + for idx=1 to 52 do + integer rank = floor(cards[idx]/4)+1 + integer suit = mod(cards[idx],4)+1 + integer eol = remainder(idx-1,13)=12 + printf(1,"%c%c%s",{ranks[rank],suits[suit],iff(eol?"\n":" ")}) + end for +end procedure + +integer game_num = 1 +--integer game_num=617 + deal(game_num) + printf(1,"hand %d\n",{game_num}) + show() diff --git a/Task/Deal-cards-for-FreeCell/Run-BASIC/deal-cards-for-freecell.run b/Task/Deal-cards-for-FreeCell/Run-BASIC/deal-cards-for-freecell.run index 25d18a267f..22303022fe 100644 --- a/Task/Deal-cards-for-FreeCell/Run-BASIC/deal-cards-for-freecell.run +++ b/Task/Deal-cards-for-FreeCell/Run-BASIC/deal-cards-for-freecell.run @@ -2,7 +2,7 @@ projectDir$ = "a_project" ' project d imageDir$ = DefaultDir$ + "\projects\" + projectDir$ + "\image\" ' directory of deck images imagePath$ = "../";projectDir$;"/image/" ' path of deck images -suite$ = "C,D,H,S" ' Club,Diamond,Hart,Spaces +suite$ = "C,D,H,S" ' Club,Diamond,Heart,Spades card$ = "A,2,3,4,5,6,7,8,9,T,J,Q,K" ' Cards Ace to King dim n(55) ' make ordered deck diff --git a/Task/Deal-cards-for-FreeCell/Zkl/deal-cards-for-freecell.zkl b/Task/Deal-cards-for-FreeCell/Zkl/deal-cards-for-freecell.zkl new file mode 100644 index 0000000000..1f59474923 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Zkl/deal-cards-for-freecell.zkl @@ -0,0 +1,17 @@ +var suits=T(0x1F0D1,0x1F0C1,0x1F0B1,0x1F0A1); //unicode 🃑,🃁,🂱,🂡 + +var seed=1; const RMAX32=(1).shiftLeft(31) - 1; +fcn rnd{ (seed=((seed*214013 + 2531011).bitAnd(RMAX32))).shiftRight(16) } + +fcn game(n){ + seed=n; + deck:=(0).pump(52,List,'wrap(n){ if(n>=44) n+=4; // I want JQK, not JCQ + (suits[n%4] + n/4).toString(8) }).copy(); // int-->UTF-8 + [52..1,-1].pump(Void,'wrap(len){ deck.swap(len-1,rnd()%len); }); + deck.reverse(); + println("Game #",n); + foreach n in ([0..51,8]){ deck[n,8].concat(" ").println(); } +} + +game(1); +game(617); diff --git a/Task/Death-Star/00DESCRIPTION b/Task/Death-Star/00DESCRIPTION index fb04a54de2..3fed6b9b0c 100644 --- a/Task/Death-Star/00DESCRIPTION +++ b/Task/Death-Star/00DESCRIPTION @@ -3,7 +3,7 @@ {{omit from|ML/I}} {{omit from|Retro}} -[[File:Deathstar-tcl.gif|300px|thumb]] +[[File:Deathstar-tcl.gif|400px|thumb]] ;Task: Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. diff --git a/Task/Death-Star/J/death-star-1.j b/Task/Death-Star/J/death-star-1.j deleted file mode 100644 index ed24367538..0000000000 --- a/Task/Death-Star/J/death-star-1.j +++ /dev/null @@ -1,39 +0,0 @@ -mag =: +/&.:*:"1 -norm=: %"1 0 mag -dot =: +/@:*"1 - -NB. (pos;posr;neg;negr) getvec (x,y) -getvec =: 4 :0 "1 - pt =. y - 'pos posr neg negr' =. x - if. (dot~ pt-}:pos) > *:posr do. - 0 0 0 - else. - zb =. ({:pos) (-,+) posr -&.:*: pt mag@:- }:pos - if. (dot~ pt-}:neg) > *:negr do. - (pt,{:zb) - pos - else. - zs =. ({:neg) (-,+) negr -&.:*: pt mag@:- }:neg - if. zs >&{. zb do. (pt,{:zb) - pos - elseif. zs >&{: zb do. 0 0 0 - elseif. ({.zs) < ({:zb) do. neg - (pt,{.zs) - elseif. do. (pt,{.zb) - pos end. - end. - end. -) - - -NB. (k;ambient;light) draw_sphere (pos;posr;neg;negr) -draw_sphere =: 4 :0 - 'pos posr neg negr' =. y - 'k ambient light' =. x - vec=. norm y getvec ,"0// (2{.pos) +/ i: 200 j.~ 0.5+posr - - b=. (mag vec) * ambient + k * 0>. light dot vec -) - -togray =: 256#. 255 255 255 <.@*"1 0 (%>./@,) - -env=.(2; 0.5; (norm _50 30 50)) -sph=. 20 20 0; 20; 1 1 _6; 20 -'rgb' viewmat togray env draw_sphere sph diff --git a/Task/Death-Star/J/death-star-2.j b/Task/Death-Star/J/death-star-2.j deleted file mode 100644 index f46325be75..0000000000 --- a/Task/Death-Star/J/death-star-2.j +++ /dev/null @@ -1,54 +0,0 @@ -load'graphics/viewmat' - -resolution=: 8 -spheres=: 3 1 #"1 ] 0 1,_1 1,:0.3 0.6 NB. spheres x y z r - - -coordinates=: (% <:)~ (,"1 0~"0 3 ,"0"1 0~)@:i: -length=: +/ &.: *: -centers=: _ 3&{. -radii=: _ _1&{. - -NB. resolution SlicePittedSphere spheres generates a binary array, 1 in the geometric object -SlicePittedSphere=: (0 { {. > [: +./ }.)@:(radii@[ >:"0 3 ((length@:-"1"_ 1 centers)~ coordinates))~ - -spanTo=: conjunction def '(m<:y)*.y<:n' NB. algebraic similarity, m <= y <= n - -tessellate=: ] ];._3"3~ 3 # [ NB. All cubical edge length x subarrays of array y - -NB. Define "faces" as those points with 9 to 18 inclusive "solid" neighbors. -detectFace=: (9 spanTo 18) @: (+/@:,"3) @: (3&tessellate) - -NB. arrange faces in ANSYS brick face order -ThickFaces=: ((|:"3 , (, |:"2))(,: |."1)3 3 3$2j1#1) /: 'SENWDU' i. 'DUEWSN' -ThinFaces=: ((|:"3 , (, |:"2))(,: |."1)3 3 3$1j2#1) /: 'SENWDU' i. 'DUEWSN' - -FACES=:ThickFaces NB. 6 below comes from #Faces - -NORMALS=: 2 tessellate FACES - -matchNormals=: [: +/@,"6 NORMALS ="6"6 _ (2 tessellate 3 tessellate ]) - -bestFit=: (i.>./)"1&.|: - -topFace=: detectFace i:"1 1: - -choose=: 4 : 'x}y' - -viewmat resolution (topFace choose (,&(#FACES))@:bestFit@matchNormals)@SlicePittedSphere spheres - - - <"_1 ThickFaces NB. display the 6 cubes with reference faces -┌─────┬─────┬─────┬─────┬─────┬─────┐ -│1 1 1│1 1 0│0 0 0│0 1 1│1 1 1│0 0 0│ -│1 1 1│1 1 0│1 1 1│0 1 1│1 1 1│0 0 0│ -│0 0 0│1 1 0│1 1 1│0 1 1│1 1 1│0 0 0│ -│ │ │ │ │ │ │ -│1 1 1│1 1 0│0 0 0│0 1 1│1 1 1│1 1 1│ -│1 1 1│1 1 0│1 1 1│0 1 1│1 1 1│1 1 1│ -│0 0 0│1 1 0│1 1 1│0 1 1│1 1 1│1 1 1│ -│ │ │ │ │ │ │ -│1 1 1│1 1 0│0 0 0│0 1 1│0 0 0│1 1 1│ -│1 1 1│1 1 0│1 1 1│0 1 1│0 0 0│1 1 1│ -│0 0 0│1 1 0│1 1 1│0 1 1│0 0 0│1 1 1│ -└─────┴─────┴─────┴─────┴─────┴─────┘ diff --git a/Task/Death-Star/Perl-6/death-star.pl6 b/Task/Death-Star/Perl-6/death-star.pl6 index 1873583d7d..8e330bc977 100644 --- a/Task/Death-Star/Perl-6/death-star.pl6 +++ b/Task/Death-Star/Perl-6/death-star.pl6 @@ -30,8 +30,8 @@ my $neg = sphere.new( ); sub MAIN ($outfile = 'deathstar-perl6.pgm') { - my $out = open( $outfile, :w, :bin ) or die "$!\n"; - $out.say("P5\n$x $y\n$depth"); # .pgm header + spurt $outfile, ("P5\n$x $y\n$depth"); # .pgm header + my $out = open( $outfile, :a, :bin ) or die "$!\n"; say 'Calculating row:'; $out.write( Blob.new( draw_ds(3, .15) ) ); $out.close; diff --git a/Task/Death-Star/Phix/death-star.phix b/Task/Death-Star/Phix/death-star.phix new file mode 100644 index 0000000000..07478a97e6 --- /dev/null +++ b/Task/Death-Star/Phix/death-star.phix @@ -0,0 +1,103 @@ +-- +-- demo\rosetta\DeathStar.exw +-- +include pGUI.e + +Ihandle dlg, canvas +cdCanvas cddbuffer, cdcanvas + +function dot(sequence x, sequence y) + return sum(sq_mul(x,y)) +end function + +function normalize(sequence v) + atom len = sqrt(dot(v, v)) + if len=0 then return {0,0,0} end if + return sq_mul(v,1/len) +end function + +enum X,Y,Z + +function hit(sequence s, atom x, y, atom r) + x -= s[X] + y -= s[Y] + atom zsq := r*r - (x*x + y*y) + if zsq >= 0 then + atom zsqrt := sqrt(zsq) + return {s[Z] - zsqrt, s[Z] + zsqrt, true} + end if + return {0, 0, false} +end function + +procedure deathStar(integer width, height, atom k, atom amb, sequence direction) +integer lum +sequence vec +integer r = floor((min(width,height)-40)/2) +integer cx = floor(width/2) +integer cy = floor(height/2) +sequence pos = {0,0,0}, + neg = {r*-3/4,r*-3/4,r*-1/4} + + for y = pos[Y]-r to pos[Y]+r do + for x = pos[X]-r to pos[X]+r do + atom {zb1, zb2, hit1} := hit(pos, x, y, r) + if hit1 then + atom {zs1, zs2, hit2} := hit(neg, x, y, r/2) + if not hit2 or zs2<=zb2 then + if hit2 and zs1<=zb1 then + vec = {neg[X] - x, neg[Y] - y, neg[Z] - zs2} + else + vec = {x - pos[X], y - pos[Y], zb1 - pos[Z]} +-- vec = {x, y, zb1} + end if + atom s = dot(direction, normalize(vec)) + lum = and_bits(#FF,255*(iff(s<0?0:power(s,k))+amb)/(1+amb)) + lum += lum*#100+lum*#10000 + cdCanvasPixel(cddbuffer, cx+x, cy-y, lum) + end if + end if + end for + end for +end procedure + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) +integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") + cdCanvasActivate(cddbuffer) + cdCanvasClear(cddbuffer) + deathStar(width, height, 1.5, 0.2, normalize({20, -40, -10})) + cdCanvasFlush(cddbuffer) + return IUP_DEFAULT +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + cdCanvasSetBackground(cddbuffer, CD_BLACK) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "340x340") -- initial size + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", "Draw a sphere") + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + + IupMap(dlg) + IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation + IupShowXY(dlg,IUP_CENTER,IUP_CENTER) + IupMainLoop() + IupClose() +end procedure + +main() diff --git a/Task/Death-Star/REXX/death-star.rexx b/Task/Death-Star/REXX/death-star.rexx index 227a079721..470ab9b7b4 100644 --- a/Task/Death-Star/REXX/death-star.rexx +++ b/Task/Death-Star/REXX/death-star.rexx @@ -2,38 +2,38 @@ call deathStar 2, .5, v3('-50 30 50') exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ +dot: #=0; do j=1 for words(x); #=# + word(x,j)*word(y,j); end; return # dot.: procedure; parse arg x,y; d=dot(x,y); if d<0 then return -d; return 0 -dot: #=0; do j=1 for words(x); #=#+word(x,j)*word(y,j); end; return # ceil: procedure; parse arg x; _=trunc(x); return _+(x>0)*(x\=_) floor: procedure; parse arg x; _=trunc(x); return _-(x<0)*(x\=_) -v3: procedure; parse arg a b c; #=sqrt(a**2 + b**2 + c**2); return a/# b/# c/# +v3: procedure; parse arg a b c; #=sqrt(a**2 + b**2 + c**2); return a/# b/# c/# /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric digits - numeric form; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g * .5'e'_ % 2 + numeric form; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g * .5'e'_ % 2 h=d+6; 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) + numeric digits d; return g/1 /*──────────────────────────────────────────────────────────────────────────────────────*/ -hitSphere: procedure expose !.; parse arg xx yy zz r,x0,y0; x=x0-xx; y=y0-yy - z=r*r-x*x-+y*y; if z<0 then return 0; _=sqrt(z); !.z1=zz-_; !.z2=zz+_; return 1 +hitSphere: procedure expose !.; parse arg xx yy zz r,x0,y0; z=r*r-(x0-xx)**2-(y0-yy)**2 + if z<0 then return 0; _=sqrt(z); !.z1=zz-_; !.z2=zz+_; return 1 /*──────────────────────────────────────────────────────────────────────────────────────*/ deathStar: procedure; parse arg k,ambient,sun /* [↓] display the deathstar to screen*/ parse var sun s1 s2 s3 /*identify the light source coördinates*/ -if 6=='f6'x then shading= '.:!*oe&#%@' /*shading characters for EBCDIC machine*/ +if 6=="f6"x then shading= '.:!*oe&#%@' /*shading characters for EBCDIC machine*/ else shading= '·:!ºoe@░▒▓' /* " " " ASCII " */ shadingL=length(shading) -shades.=' '; do i=1 for shadingL; shades.i=substr(shading,i,1); end /*i*/ +shades.=' '; do i=1 for shadingL; shades.i=substr(shading, i, 1); end /*i*/ -ship= 20 20 0 20 ; parse var ship shipX shipY shipZ shipR -hole= ' 1 1 -6 20'; parse var hole holeX holeY holeZ . +ship= 20 20 0 20 ; parse var ship shipX shipY shipZ shipR +hole= ' 1 1 -6 20' ; parse var hole holeX holeY holeZ . - do i=floor(shipY-shipR) to ceil(shipY+shipR) +1; y=i+.5; @= /*@ is a single line of the deathstar to be displayed.*/ - do j=floor(shipX-shipR*2) to ceil(shipX+shipR*2)+1 - x=.5*(j-shipX)+.5+shipX; !.=0; $bg=0; $pos=0; $neg=0 /*$BG, $POS, and $NEG are boolean values. */ - ?=hitSphere(ship, x, y); b1=!.z1; b2=!.z2 /*? is boolean, "true" indicates ray hits the sphere.*/ + do i=floor(shipY-shipR ) to ceil(shipY+shipR )+1; y=i+.5; @= /*@ is a single line of the deathstar to be displayed.*/ + do j=floor(shipX-shipR*2) to ceil(shipX+shipR*2)+1; !.=0 + x=.5 * (j-shipX+1) + shipX; $bg=0; $pos=0; $neg=0 /*$BG, $POS, and $NEG are boolean values. */ + ?=hitSphere(ship, x, y); b1=!.z1; b2=!.z2 /*? is boolean, "true" indicates ray hits the sphere.*/ if \? then $bg=1 /*ray lands in blank space, so draw the background. */ - else do; ?=hitSphere(hole, x, y); s1=!.z1; s2=!.z2 + else do; ?=hitSphere(hole, x, y); s1=!.z1; s2=!.z2 if \? then $pos=1 /*ray hits ship but not the hole, so draw ship surface. */ else if s1>b1 then $pos=1 /*ray hits both, but ship front surface is closer. */ else if s2>b2 then $bg=1 /*ship surface is inside hole, so show the background. */ @@ -41,15 +41,15 @@ hole= ' 1 1 -6 20'; parse var hole holeX holeY holeZ . else $pos=1 /*························· hole surface will be shown.*/ end select - when $bg then do; @=@' '; iterate j; end /*append a blank character to the line to be displayed. */ - when $pos then vec_=v3(x-shipX y-shipY b1-shipZ) - when $neg then vec_=v3(holeX-x holeY-y holeZ-s2) + when $bg then do; @=@' '; iterate j; end /*append a blank character to the line to be displayed. */ + when $pos then vec_= v3(x-shipX y-shipY b1-shipZ) + when $neg then vec_= v3(holeX-x holeY-y holeZ-s2) end /*select*/ b=1 +min(shadingL, max(0, trunc((1 - (dot.(sun, v3(vec_))**k + ambient)) * shadingL))) @=@ || shades.b /*B the ray's intensity│brightness*/ end /*j*/ /* [↑] build a line for the sphere.*/ - if @\='' then say strip(@,'T') /*strip trailing blanks from line. */ + if @\='' then say strip(@, 'T') /*strip trailing blanks from line. */ end /*i*/ /* [↑] show all lines for sphere. */ return diff --git a/Task/Deconvolution-1D/C/deconvolution-1d-1.c b/Task/Deconvolution-1D/C/deconvolution-1d-1.c deleted file mode 100644 index 0d1cec01f9..0000000000 --- a/Task/Deconvolution-1D/C/deconvolution-1d-1.c +++ /dev/null @@ -1,92 +0,0 @@ -#include -#include -#include -#include - -double PI; -typedef double complex cplx; - -void _fft(cplx buf[], cplx out[], int n, int step) -{ - if (step < n) { - _fft(out, buf, n, step * 2); - _fft(out + step, buf + step, n, step * 2); - - for (int i = 0; i < n; i += 2 * step) { - cplx t = cexp(-I * PI * i / n) * out[i + step]; - buf[i / 2] = out[i] + t; - buf[(i + n)/2] = out[i] - t; - } - } -} - -void fft(cplx buf[], int n) -{ - cplx out[n]; - for (int i = 0; i < n; i++) out[i] = buf[i]; - _fft(buf, out, n, 1); -} - -/* pad array length to power of two */ -cplx *pad_two(double g[], int len, int *ns) -{ - int n = 1; - if (*ns) n = *ns; - else while (n < len) n *= 2; - - cplx *buf = calloc(sizeof(cplx), n); - for (int i = 0; i < len; i++) buf[i] = g[i]; - *ns = n; - return buf; -} - -void deconv(double g[], int lg, double f[], int lf, double out[]) { - int ns = 0; - cplx *g2 = pad_two(g, lg, &ns); - cplx *f2 = pad_two(f, lf, &ns); - - fft(g2, ns); - fft(f2, ns); - - cplx h[ns]; - for (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i]; - fft(h, ns); - - for (int i = 0; i >= lf - lg; i--) - out[-i] = h[(i + ns) % ns]/32; - free(g2); - free(f2); -} - -int main() -{ - PI = atan2(1,1) * 4; - double g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7}; - double f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 }; - double h[] = { -8,-9,-3,-1,-6,7 }; - - int lg = sizeof(g)/sizeof(double); - int lf = sizeof(f)/sizeof(double); - int lh = sizeof(h)/sizeof(double); - - double h2[lh]; - double f2[lf]; - - printf("f[] data is : "); - for (int i = 0; i < lf; i++) printf(" %g", f[i]); - printf("\n"); - - printf("deconv(g, h): "); - deconv(g, lg, h, lh, f2); - for (int i = 0; i < lf; i++) printf(" %g", f2[i]); - printf("\n"); - - printf("h[] data is : "); - for (int i = 0; i < lh; i++) printf(" %g", h[i]); - printf("\n"); - - printf("deconv(g, f): "); - deconv(g, lg, f, lf, h2); - for (int i = 0; i < lh; i++) printf(" %g", h2[i]); - printf("\n"); -} diff --git a/Task/Deconvolution-1D/C/deconvolution-1d-2.c b/Task/Deconvolution-1D/C/deconvolution-1d-2.c deleted file mode 100644 index eccf0bd94e..0000000000 --- a/Task/Deconvolution-1D/C/deconvolution-1d-2.c +++ /dev/null @@ -1,4 +0,0 @@ -f[] data is : -3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1 -deconv(g, h): -3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1 -h[] data is : -8 -9 -3 -1 -6 7 -deconv(g, f): -8 -9 -3 -1 -6 7 diff --git a/Task/Deconvolution-1D/Kotlin/deconvolution-1d.kotlin b/Task/Deconvolution-1D/Kotlin/deconvolution-1d.kotlin new file mode 100644 index 0000000000..d38d8249fd --- /dev/null +++ b/Task/Deconvolution-1D/Kotlin/deconvolution-1d.kotlin @@ -0,0 +1,27 @@ +// version 1.1.3 + +fun deconv(g: DoubleArray, f: DoubleArray): DoubleArray { + val fs = f.size + val h = DoubleArray(g.size - fs + 1) + for (n in h.indices) { + h[n] = g[n] + val lower = if (n >= fs) n - fs + 1 else 0 + for (i in lower until n) h[n] -= h[i] * f[n -i] + h[n] /= f[0] + } + return h +} + +fun main(args: Array) { + val h = doubleArrayOf(-8.0, -9.0, -3.0, -1.0, -6.0, 7.0) + val f = doubleArrayOf(-3.0, -6.0, -1.0, 8.0, -6.0, 3.0, -1.0, -9.0, + -9.0, 3.0, -2.0, 5.0, 2.0, -2.0, -7.0, -1.0) + val g = doubleArrayOf(24.0, 75.0, 71.0, -34.0, 3.0, 22.0, -45.0, + 23.0, 245.0, 25.0, 52.0, 25.0, -67.0, -96.0, + 96.0, 31.0, 55.0, 36.0, 29.0, -43.0, -7.0) + println("${h.map { it.toInt() }}") + println("${deconv(g, f).map { it.toInt() }}") + println() + println("${f.map { it.toInt() }}") + println("${deconv(g, h).map { it.toInt() }}") +} diff --git a/Task/Deconvolution-1D/Phix/deconvolution-1d.phix b/Task/Deconvolution-1D/Phix/deconvolution-1d.phix new file mode 100644 index 0000000000..fed0fe44cf --- /dev/null +++ b/Task/Deconvolution-1D/Phix/deconvolution-1d.phix @@ -0,0 +1,20 @@ +function deconv(sequence g, sequence f) +integer lf = length(f) +sequence h = repeat(0,length(g)-lf+1) + for n = 1 to length(h) do + atom e = g[n] + for i=max(n-lf,0) to n-2 do + e -= h[i+1] * f[n-i] + end for + h[n] = e/f[1] + end for + return h +end function + +constant h = {-8,-9,-3,-1,-6,7} +constant f = {-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1} +constant g = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67, + -96,96,31,55,36,29,-43,-7} +sequence r +r = deconv(g, f) ?{r==h,r} +r = deconv(g, h) ?{r==f,r} diff --git a/Task/Deconvolution-1D/Python/deconvolution-1d.py b/Task/Deconvolution-1D/Python/deconvolution-1d.py index fa4555e4cb..5414a91332 100644 --- a/Task/Deconvolution-1D/Python/deconvolution-1d.py +++ b/Task/Deconvolution-1D/Python/deconvolution-1d.py @@ -22,6 +22,7 @@ def ToReducedRowEchelonForm( M ): lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 + return M def pmtx(mtx): print ('\n'.join(''.join(' %4s' % col for col in row) for row in mtx)) diff --git a/Task/Deconvolution-1D/Zkl/deconvolution-1d-1.zkl b/Task/Deconvolution-1D/Zkl/deconvolution-1d-1.zkl new file mode 100644 index 0000000000..4ae81c93d0 --- /dev/null +++ b/Task/Deconvolution-1D/Zkl/deconvolution-1d-1.zkl @@ -0,0 +1,8 @@ +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +fcn dconv1D(f,g){ + fsz,hsz:=f.len(), g.len() - fsz +1; + A:=GSL.Matrix(g.len(),hsz); + foreach n,fn in ([0..].zip(f)){ foreach rc in (hsz){ A[rc+n,rc]=fn } } + h:=A.AxEQb(g); + h +} diff --git a/Task/Deconvolution-1D/Zkl/deconvolution-1d-2.zkl b/Task/Deconvolution-1D/Zkl/deconvolution-1d-2.zkl new file mode 100644 index 0000000000..aaaa979b34 --- /dev/null +++ b/Task/Deconvolution-1D/Zkl/deconvolution-1d-2.zkl @@ -0,0 +1,7 @@ +f:=GSL.VectorFromData(-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1); +g:=GSL.VectorFromData(24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7); +h:=dconv1D(f,g); +h.format().println(); + +f:=dconv1D(h,g); +f.format().println(); diff --git a/Task/Deconvolution-1D/Zkl/deconvolution-1d-3.zkl b/Task/Deconvolution-1D/Zkl/deconvolution-1d-3.zkl new file mode 100644 index 0000000000..f7648e468b --- /dev/null +++ b/Task/Deconvolution-1D/Zkl/deconvolution-1d-3.zkl @@ -0,0 +1,11 @@ +fcn deconv(g,f){ + flen, glen, delta:=f.len(), g.len(), glen - flen + 1; + result:=List.createLong(delta); // allocate list with space for items + foreach n in (delta){ + e:=g[n]; + lowerBound:=(if (n>=flen) n - flen + 1 else 0); + foreach i in ([lowerBound .. n-1]){ e-=result[i]*f[n - i]; } + result.append(e/f[0]); + } + result; +} diff --git a/Task/Deconvolution-1D/Zkl/deconvolution-1d-4.zkl b/Task/Deconvolution-1D/Zkl/deconvolution-1d-4.zkl new file mode 100644 index 0000000000..bcd14612c0 --- /dev/null +++ b/Task/Deconvolution-1D/Zkl/deconvolution-1d-4.zkl @@ -0,0 +1,6 @@ +h:=T(-8,-9,-3,-1,-6,7); +f:=T(-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1); +g:=T(24,75,71,-34,3,22,-45,23,245,25,52,25,-67, + -96,96,31,55,36,29,-43,-7); +println(deconv(g, f) == h, " ", deconv(g, f)); +println(deconv(g, h) == f, " ", deconv(g, h)); diff --git a/Task/Deepcopy/Go/deepcopy-2.go b/Task/Deepcopy/Go/deepcopy-2.go index 1da88fa9cc..9e0c186d5c 100644 --- a/Task/Deepcopy/Go/deepcopy-2.go +++ b/Task/Deepcopy/Go/deepcopy-2.go @@ -1,62 +1,60 @@ package main -import ( - "encoding/gob" - "fmt" - "os" -) +import "fmt" -// capability requested by task -func deepcopy(dst, src interface{}) error { - r, w, err := os.Pipe() - if err != nil { - return err +// a type that allows cyclic structures +type node []*node + +// recursively print the contents of a node +func (n *node) list() { + if n == nil { + fmt.Println(n) + return } - enc := gob.NewEncoder(w) - err = enc.Encode(src) - if err != nil { - return err + listed := map[*node]bool{nil: true} + var r func(*node) + r = func(n *node) { + listed[n] = true + fmt.Printf("%p -> %v\n", n, *n) + for _, m := range *n { + if !listed[m] { + r(m) + } + } } - dec := gob.NewDecoder(r) - return dec.Decode(dst) + r(n) } -// define linked list type, an example of a recursive type -type link struct { - Value string - Next *link -} - -// method satisfies stringer interface for fmt.Println -func (l *link) String() string { - if l == nil { - return "nil" +// construct a deep copy of a node +func (n *node) ccopy() *node { + if n == nil { + return n } - s := "(" + l.Value - for l = l.Next; l != nil; l = l.Next { - s += " " + l.Value + cc := map[*node]*node{nil: nil} + var r func(*node) *node + r = func(n *node) *node { + c := make(node, len(*n)) + cc[n] = &c + for i, m := range *n { + d, ok := cc[m] + if !ok { + d = r(m) + } + c[i] = d + } + return &c } - return s + ")" + return r(n) } func main() { - // create a linked list with two elements - l1 := &link{"a", &link{Value: "b"}} - // print original - fmt.Println(l1) - // declare a variable to hold deep copy - var l2 *link - // copy - if err := deepcopy(&l2, l1); err != nil { - fmt.Println(err) - return - } - // print copy - fmt.Println(l2) - // now change contents of original list - l1.Value, l1.Next.Value = "c", "d" - // show that it is changed - fmt.Println(l1) - // show that copy is unaffected - fmt.Println(l2) + a := node{nil} + c := &node{&node{&a}} + a[0] = c + c.list() + cc := c.ccopy() + fmt.Println("copy:") + cc.list() + fmt.Println("original:") + c.list() } diff --git a/Task/Deepcopy/Go/deepcopy-3.go b/Task/Deepcopy/Go/deepcopy-3.go new file mode 100644 index 0000000000..1da88fa9cc --- /dev/null +++ b/Task/Deepcopy/Go/deepcopy-3.go @@ -0,0 +1,62 @@ +package main + +import ( + "encoding/gob" + "fmt" + "os" +) + +// capability requested by task +func deepcopy(dst, src interface{}) error { + r, w, err := os.Pipe() + if err != nil { + return err + } + enc := gob.NewEncoder(w) + err = enc.Encode(src) + if err != nil { + return err + } + dec := gob.NewDecoder(r) + return dec.Decode(dst) +} + +// define linked list type, an example of a recursive type +type link struct { + Value string + Next *link +} + +// method satisfies stringer interface for fmt.Println +func (l *link) String() string { + if l == nil { + return "nil" + } + s := "(" + l.Value + for l = l.Next; l != nil; l = l.Next { + s += " " + l.Value + } + return s + ")" +} + +func main() { + // create a linked list with two elements + l1 := &link{"a", &link{Value: "b"}} + // print original + fmt.Println(l1) + // declare a variable to hold deep copy + var l2 *link + // copy + if err := deepcopy(&l2, l1); err != nil { + fmt.Println(err) + return + } + // print copy + fmt.Println(l2) + // now change contents of original list + l1.Value, l1.Next.Value = "c", "d" + // show that it is changed + fmt.Println(l1) + // show that copy is unaffected + fmt.Println(l2) +} diff --git a/Task/Deepcopy/Julia/deepcopy.julia b/Task/Deepcopy/Julia/deepcopy.julia new file mode 100644 index 0000000000..5eb1ecd492 --- /dev/null +++ b/Task/Deepcopy/Julia/deepcopy.julia @@ -0,0 +1,3 @@ +# v0.6.0 + +cp = deepcopy(obj) diff --git a/Task/Deepcopy/Phix/deepcopy-1.phix b/Task/Deepcopy/Phix/deepcopy-1.phix new file mode 100644 index 0000000000..d6a0209534 --- /dev/null +++ b/Task/Deepcopy/Phix/deepcopy-1.phix @@ -0,0 +1,6 @@ +object a, b + a = {1,{2,3},"four",{5.6,7,{8.9}}} + b = a + b[3] = 4 +?a +?b diff --git a/Task/Deepcopy/Phix/deepcopy-2.phix b/Task/Deepcopy/Phix/deepcopy-2.phix new file mode 100644 index 0000000000..71a5570ed5 --- /dev/null +++ b/Task/Deepcopy/Phix/deepcopy-2.phix @@ -0,0 +1,15 @@ +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 diff --git a/Task/Deepcopy/Phix/deepcopy-3.phix b/Task/Deepcopy/Phix/deepcopy-3.phix new file mode 100644 index 0000000000..70b5b97a9a --- /dev/null +++ b/Task/Deepcopy/Phix/deepcopy-3.phix @@ -0,0 +1,3 @@ +include builtins\serialize.e +object d = deserialize(serialize(a)) +?d diff --git a/Task/Deepcopy/Rust/deepcopy.rust b/Task/Deepcopy/Rust/deepcopy.rust new file mode 100644 index 0000000000..da3b1d49a4 --- /dev/null +++ b/Task/Deepcopy/Rust/deepcopy.rust @@ -0,0 +1,26 @@ + // The compiler can automatically implement Clone on structs (assuming all members have implemented Clone). +#[derive(Clone)] +struct Tree { + left: Leaf, + data: T, + right: Leaf, +} + +type Leaf = Option>>; + +impl Tree { + fn root(d: T) -> Self { + Tree { left: None, data: d, right: None } + } + fn leaf(d: T) -> Leaf { + Some(Box::new(Tree::root(d))) + } +} + + +fn main() { + let mut tree = Tree::root(vec![4,5,6]); + tree.right = Tree::leaf(vec![1,2,3]); + tree.left = Tree::leaf(vec![7,8,9]); + let newtree = tree.clone(); +} diff --git a/Task/Define-a-primitive-data-type/Elena/define-a-primitive-data-type.elena b/Task/Define-a-primitive-data-type/Elena/define-a-primitive-data-type.elena new file mode 100644 index 0000000000..3b3bae5a76 --- /dev/null +++ b/Task/Define-a-primitive-data-type/Elena/define-a-primitive-data-type.elena @@ -0,0 +1,63 @@ +type tiny = TinyInt. + +sealed struct TinyInt :: BaseNumber +{ + int theValue. + + explicit int:n + [ + if ((n <= 1)||(n >= 10)) + [ + InvalidArgumentException new; raise + ]. + + theValue := n. + ] + + explicit t(LiteralValue s) + [ + theValue := s toInt. + + if ((theValue <= 1)||(theValue >= 10)) + [ + InvalidArgumentException new; raise + ] + ] + + int = theValue. + + tiny add(TinyInt t) + = theValue + t. + + tiny subtract(TinyInt t) + = theValue + t. + + tiny multiply(TinyInt t) + = theValue + t. + + tiny divide(TinyInt t) + = theValue + t. + + bool equal(TinyInt t) + = theValue == t int. + + bool less(TinyInt t) + = theValue == t int. +} + +program = +[ + tiny i := 4t. + tiny j := i + i. + + try(control do: + [ + tiny k := i + j. + ]) + { + on(InvalidArgumentException e) + [ + console printLine("A value is out of range"). + ] + }. +]. diff --git a/Task/Define-a-primitive-data-type/jq/define-a-primitive-data-type-1.jq b/Task/Define-a-primitive-data-type/Jq/define-a-primitive-data-type-1.jq similarity index 100% rename from Task/Define-a-primitive-data-type/jq/define-a-primitive-data-type-1.jq rename to Task/Define-a-primitive-data-type/Jq/define-a-primitive-data-type-1.jq diff --git a/Task/Define-a-primitive-data-type/jq/define-a-primitive-data-type-2.jq b/Task/Define-a-primitive-data-type/Jq/define-a-primitive-data-type-2.jq similarity index 100% rename from Task/Define-a-primitive-data-type/jq/define-a-primitive-data-type-2.jq rename to Task/Define-a-primitive-data-type/Jq/define-a-primitive-data-type-2.jq diff --git a/Task/Define-a-primitive-data-type/jq/define-a-primitive-data-type-3.jq b/Task/Define-a-primitive-data-type/Jq/define-a-primitive-data-type-3.jq similarity index 100% rename from Task/Define-a-primitive-data-type/jq/define-a-primitive-data-type-3.jq rename to Task/Define-a-primitive-data-type/Jq/define-a-primitive-data-type-3.jq diff --git a/Task/Define-a-primitive-data-type/jq/define-a-primitive-data-type-4.jq b/Task/Define-a-primitive-data-type/Jq/define-a-primitive-data-type-4.jq similarity index 100% rename from Task/Define-a-primitive-data-type/jq/define-a-primitive-data-type-4.jq rename to Task/Define-a-primitive-data-type/Jq/define-a-primitive-data-type-4.jq diff --git a/Task/Define-a-primitive-data-type/jq/define-a-primitive-data-type-5.jq b/Task/Define-a-primitive-data-type/Jq/define-a-primitive-data-type-5.jq similarity index 100% rename from Task/Define-a-primitive-data-type/jq/define-a-primitive-data-type-5.jq rename to Task/Define-a-primitive-data-type/Jq/define-a-primitive-data-type-5.jq diff --git a/Task/Define-a-primitive-data-type/Kotlin/define-a-primitive-data-type.kotlin b/Task/Define-a-primitive-data-type/Kotlin/define-a-primitive-data-type.kotlin new file mode 100644 index 0000000000..3ce236a508 --- /dev/null +++ b/Task/Define-a-primitive-data-type/Kotlin/define-a-primitive-data-type.kotlin @@ -0,0 +1,37 @@ +// version 1.1 + +class TinyInt(i: Int) { + private val value = makeTiny(i) + + operator fun plus (other: TinyInt): TinyInt = TinyInt(this.value + other.value) + operator fun minus(other: TinyInt): TinyInt = TinyInt(this.value - other.value) + operator fun times(other: TinyInt): TinyInt = TinyInt(this.value * other.value) + operator fun div (other: TinyInt): TinyInt = TinyInt(this.value / other.value) + operator fun rem (other: TinyInt): TinyInt = TinyInt(this.value % other.value) + + operator fun inc() = TinyInt(this.value + 1) + operator fun dec() = TinyInt(this.value - 1) + + private fun makeTiny(i: Int): Int = + when { + i < 1 -> 1 + i > 10 -> 10 + else -> i + } + + override fun toString(): String = value.toString() +} + +fun main(args: Array) { + var t1 = TinyInt(6) + var t2 = TinyInt(3) + println("t1 = $t1") + println("t2 = $t2") + println("t1 + t2 = ${t1 + t2}") + println("t1 - t2 = ${t1 - t2}") + println("t1 * t2 = ${t1 * t2}") + println("t1 / t2 = ${t1 / t2}") + println("t1 % t2 = ${t1 % t2}") + println("t1 + 1 = ${++t1}") + println("t2 - 1 = ${--t2}") +} diff --git a/Task/Define-a-primitive-data-type/OoRexx/define-a-primitive-data-type.rexx b/Task/Define-a-primitive-data-type/OoRexx/define-a-primitive-data-type.rexx new file mode 100644 index 0000000000..bbf6c7c01c --- /dev/null +++ b/Task/Define-a-primitive-data-type/OoRexx/define-a-primitive-data-type.rexx @@ -0,0 +1,49 @@ +/* REXX ---------------------------------------------------------------- +* 21.06.2014 Walter Pachl +* implements a data type tinyint that can have an integer value 1..10 +* 22.06.2014 WP corrected by Rony Flatscher to handle arithmetic +*---------------------------------------------------------------------*/ +a=.tinyint~new(1) ; Say 'a='||a~value +Say '2*a='||(2*a) +Say 'a*2='||((0+a)*2) +say "---> rony was here: :)" +say "The above statement was in effect: '(0+a)*2', NOT 'a*2*, hence it worked!" +say "These statements work now:" +say "(a)*2:" (a)*2 +say "a*2: " a*2 +say "<--- rony was here, The end. :)" +b=.tinyint~new(11); Say 'b='||b~value +b=.tinyint~new('B'); Say 'b='||b~value +say 'b='||(b) -- show string value +Say '2*b='||(2*b) +::class tinyint +::method init + Expose v + Use Arg i + Select + When datatype(i,'W') Then Do + If i>=1 & i<=10 Then + v=i + Else Do + Say 'Argument 1 must be between 1 and 10' + Raise Syntax 88.907 array(1,1,10,i) + End + End + Otherwise Do + Say 'Argument 1 must be a whole number between 1 and 10' + Raise Syntax 88.905 array(1,i) + End + End +::method string + Expose v + Return v +::method value + Expose v + Return v + +-- rgf, 20140622, intercept unknown messages, forward arithmetic messages to string value +::method unknown + expose v + use arg methName, methArgs + if wordpos(methName, "+ - * / % //")>0 then -- an arithmetic message in hand? + forward message (methName) to (v) array (methArgs[1]) diff --git a/Task/Delegates/Elena/delegates-1.elena b/Task/Delegates/Elena/delegates-1.elena new file mode 100644 index 0000000000..6ed1b2e25d --- /dev/null +++ b/Task/Delegates/Elena/delegates-1.elena @@ -0,0 +1,54 @@ +import extensions. +import system'routines. + +class IOperable +{ + operate + [ + NotSupportedException new; raise. + ] +} + +class Operable :: IOperable +{ + operate + = "delegate implementation". +} + +class Delegator +{ + object theDelegate. + + constructor new + [ + theDelegate := nil. + ] + + set Delegate:obj + [ + if ($nil == obj) + [ theDelegate := $nil. ]; + [ theDelegate := obj. ]. + ] + + operate(Object operable) + = "default implementation". + + operate(IOperable operable) + = operable operate. + + operate + <= operate(theDelegate). +} + +program = +[ + var delegator := Delegator new. + + (nil, Object new, Operable new) forEach(:o) + [ + delegator Delegate := o. + + console printLine(delegator operate). + ]. +]. diff --git a/Task/Delegates/Elena/delegates-2.elena b/Task/Delegates/Elena/delegates-2.elena new file mode 100644 index 0000000000..844719efcd --- /dev/null +++ b/Task/Delegates/Elena/delegates-2.elena @@ -0,0 +1,53 @@ +import extensions. +import system'routines. + +class Operable +{ + operable = $self. + + operate + = "delegate implementation". +} + +class Delegator +{ + object theDelegate. + + constructor new + [ + theDelegate := nil. + ] + + set Delegate:obj + [ + if ($nil == obj) + [ theDelegate := $nil. ]; + [ theDelegate := obj. ]. + ] + + operate + [ + // if the object does not support "get&operable" message - returns nil + var anOperable := theDelegate operable \ back:$nil. + + if ($nil == anOperable) + [ + ^ "default implementation". + ]; + [ + ^ anOperable operate. + ]. + ] +} + +program = +[ + var delegator := Delegator new. + + (nil, Object new, Operable new) forEach(:o) + [ + delegator Delegate := o. + + console printLine(delegator operate). + ]. +]. diff --git a/Task/Delegates/Elena/delegates.elena b/Task/Delegates/Elena/delegates.elena deleted file mode 100644 index fbe18c42a8..0000000000 --- a/Task/Delegates/Elena/delegates.elena +++ /dev/null @@ -1,48 +0,0 @@ -#import system. -#import system'routines. - -#class Operable -{ - #method cast:verb &to:target - = target::verb eval &delegate:$self. - - #method operate - = "delegate implementation". -} - -#class Delegator -{ - #field theDelegate. - - #constructor new - [ - theDelegate := nil. - ] - - #method set &Delegate:obj - [ - ($nil == obj) - ? [ theDelegate := nil. ] - ! [ theDelegate := obj. ]. - ] - - #method operate - = theDelegate cast:%eval &to: - { - delegate : o = o operate. - - ! : o = "default implementation". - }. -} - -#symbol program = -[ - #var delegator := Delegator new. - - ($nil, Object new, Operable new) run &each: o - [ - delegator set &Delegate:o. - - console writeLine:(delegator operate). - ]. -]. diff --git a/Task/Delegates/Forth/delegates.fth b/Task/Delegates/Forth/delegates.fth index 2c07246b9a..8b16f491e6 100644 --- a/Task/Delegates/Forth/delegates.fth +++ b/Task/Delegates/Forth/delegates.fth @@ -1,38 +1,5 @@ include FMS-SI.f --1 [if] \ add optional introspection facility to FMS - -: fm' ( selector-ID link -- xt | 0 ) \ find method, linked-list search - begin @ dup - while 2dup cell+ @ = - if [ 2 cells ] literal + nip @ exit then - repeat 2drop false ; - -: has-meth-L ( obj addr -- xt | 0 ) - swap >class over @ + fm' ; - -: >xt' ( table-offset ^dispatch -- xt | 0 ) - 2dup @ > if 2drop false exit then - + @ ; - -: has-meth-D ( obj addr -- xt | 0 ) - @ swap @ >xt' ; - -: (has-meth) ( obj addr sel-type -- xt | 0 ) - seltype-L = - if ( obj addr ) has-meth-L - else ( obj addr ) has-meth-D - then ; - -: [has-meth] ( obj "messageName" -- xt | 0 ) \ compile time only, can use ex-meth on xt to execute the method - ' >body dup postpone literal cell+ @ postpone literal postpone (has-meth) ; immediate - -: has-meth ( obj "messageName" -- xt | 0 ) \ interpret time only, can use ex-meth on xt to execute the method - ' >body dup cell+ @ (has-meth) ; -[then] - - - :class delegate :m thing ." delegate implementation" ;m ;class @@ -46,7 +13,7 @@ delegate slave :m default ." default implementation" ;m :m operation del @ 0= if self default exit then - del @ [has-meth] thing + del @ has-meth thing if del @ thing else self default then ;m diff --git a/Task/Delegates/OoRexx/delegates.rexx b/Task/Delegates/OoRexx/delegates.rexx new file mode 100644 index 0000000000..926b1f2d2c --- /dev/null +++ b/Task/Delegates/OoRexx/delegates.rexx @@ -0,0 +1,40 @@ +delegator = .delegator~new -- no delegate +say delegator~operation +-- an invalid delegate type +delegator~delegate = "Some string" +say delegator~operation +-- a good delegate +delegator~delegate = .thing~new +say delegator~operation +-- a directory object with a thing entry defined +d = .directory~new +d~thing = "delegate implementation" +delegator~delegate = d +say delegator~operation + +-- a class we can use as a delegate +::class thing +::method thing + return "delegate implementation" + +::class delegator +::method init + expose delegate + use strict arg delegate = .nil + +::attribute delegate + +::method operation + expose delegate + if delegate == .nil then return "default implementation" + + -- Note: We could use delegate~hasMethod("THING") to check + -- for a THING method, but this will fail of the object relies + -- on an UNKNOWN method to handle the method. By trapping + -- NOMETHOD conditions, we can allow those calls to go + -- through + signal on nomethod + return delegate~thing + +nomethod: + return "default implementation" diff --git a/Task/Delegates/Zkl/delegates-1.zkl b/Task/Delegates/Zkl/delegates-1.zkl new file mode 100644 index 0000000000..0b3a670435 --- /dev/null +++ b/Task/Delegates/Zkl/delegates-1.zkl @@ -0,0 +1,11 @@ +class Thingable{ var thing; } + +class Delegator{ + var delegate; + fcn operation{ + if (delegate) delegate.thing; + else "default implementation" + } +} + +class Delegate(Thingable){ thing = "delegate implementation" } diff --git a/Task/Delegates/Zkl/delegates-2.zkl b/Task/Delegates/Zkl/delegates-2.zkl new file mode 100644 index 0000000000..44bb92b35c --- /dev/null +++ b/Task/Delegates/Zkl/delegates-2.zkl @@ -0,0 +1,7 @@ + // Without a delegate: +a:= Delegator(); +a.operation().println(); //--> "default implementation" + + // With a delegate: +a.delegate = Delegate(); +a.operation().println(); //-->"delegate implementation" diff --git a/Task/Delegates/Zkl/delegates-3.zkl b/Task/Delegates/Zkl/delegates-3.zkl new file mode 100644 index 0000000000..d7b088c5c8 --- /dev/null +++ b/Task/Delegates/Zkl/delegates-3.zkl @@ -0,0 +1,6 @@ +class [static] Logger{ // Only one logging resource + var [mixin=File] dst; // File like semantics, eg Data, Pipe + dst = File.DevNull; + // initially, the logger does nothing + fcn log(msg){dst.writeln(vm.pasteArgs())} +} diff --git a/Task/Delegates/Zkl/delegates-4.zkl b/Task/Delegates/Zkl/delegates-4.zkl new file mode 100644 index 0000000000..59c03d6063 --- /dev/null +++ b/Task/Delegates/Zkl/delegates-4.zkl @@ -0,0 +1,6 @@ +Logger.log("this is a test"); //-->nada +Logger.dst=Console; +Logger.log("this is a test 2"); //-->writes to Console + +class B(Logger){ log("Hello from ",self,"'s constructor"); } +B(); //-->Hello from Class(B)'s constructor diff --git a/Task/Delete-a-file/BASIC/delete-a-file-2.basic b/Task/Delete-a-file/BASIC/delete-a-file-2.basic index 0363d851a4..c46cc509e2 100644 --- a/Task/Delete-a-file/BASIC/delete-a-file-2.basic +++ b/Task/Delete-a-file/BASIC/delete-a-file-2.basic @@ -1 +1,2 @@ -ERASE "m"; 1; "INPUTTXT" +DELETE FILE "input.txt" +DELETE FILE "/input.txt" diff --git a/Task/Delete-a-file/BASIC/delete-a-file-3.basic b/Task/Delete-a-file/BASIC/delete-a-file-3.basic index fd42011cb7..0363d851a4 100644 --- a/Task/Delete-a-file/BASIC/delete-a-file-3.basic +++ b/Task/Delete-a-file/BASIC/delete-a-file-3.basic @@ -1 +1 @@ -ERASE "a:INPUTTXT" +ERASE "m"; 1; "INPUTTXT" diff --git a/Task/Delete-a-file/BASIC/delete-a-file-4.basic b/Task/Delete-a-file/BASIC/delete-a-file-4.basic new file mode 100644 index 0000000000..fd42011cb7 --- /dev/null +++ b/Task/Delete-a-file/BASIC/delete-a-file-4.basic @@ -0,0 +1 @@ +ERASE "a:INPUTTXT" diff --git a/Task/Delete-a-file/Component-Pascal/delete-a-file.component b/Task/Delete-a-file/Component-Pascal/delete-a-file.component new file mode 100644 index 0000000000..f210c2f1c7 --- /dev/null +++ b/Task/Delete-a-file/Component-Pascal/delete-a-file.component @@ -0,0 +1,8 @@ +VAR + l: Files.Locator; +BEGIN + (* Locator is the directory *) + l := Files.dir.This("proof"); + (* delete 'xx.txt' file, in directory 'proof' *) + Files.dir.Delete(l,"xx.txt"); +END ... diff --git a/Task/Delete-a-file/Elena/delete-a-file.elena b/Task/Delete-a-file/Elena/delete-a-file.elena index 0ef080e8a6..43dd359b54 100644 --- a/Task/Delete-a-file/Elena/delete-a-file.elena +++ b/Task/Delete-a-file/Elena/delete-a-file.elena @@ -1,13 +1,12 @@ -#import system. -#import system'io. +import system'io. -#symbol program = +program = [ - "output.txt" file_path delete. + File new:"output.txt"; delete. - "\output.txt" file_path delete. + File new:"\output.txt"; delete. - "docs" directory_path delete. + Directory new:"docs"; delete. - "\docs" directory_path delete. + Directory new:"\docs"; delete. ]. diff --git a/Task/Delete-a-file/Gambas/delete-a-file.gambas b/Task/Delete-a-file/Gambas/delete-a-file.gambas new file mode 100644 index 0000000000..adff43d940 --- /dev/null +++ b/Task/Delete-a-file/Gambas/delete-a-file.gambas @@ -0,0 +1,8 @@ +Public Sub Main() + +Kill User.home &/ "input.txt" +Rmdir User.home &/ "docs" + +'Administrative privileges (sudo) would be required to mess about in Root - I'm not going there! + +End diff --git a/Task/Delete-a-file/Julia/delete-a-file.julia b/Task/Delete-a-file/Julia/delete-a-file.julia new file mode 100644 index 0000000000..d026c02722 --- /dev/null +++ b/Task/Delete-a-file/Julia/delete-a-file.julia @@ -0,0 +1,5 @@ +# Delete a file +rm("input.txt") + +# Delete a directory +rm("docs", recursive = true) diff --git a/Task/Delete-a-file/Kotlin/delete-a-file.kotlin b/Task/Delete-a-file/Kotlin/delete-a-file.kotlin new file mode 100644 index 0000000000..f88aef17f4 --- /dev/null +++ b/Task/Delete-a-file/Kotlin/delete-a-file.kotlin @@ -0,0 +1,18 @@ +// version 1.0.6 + +/* testing on Windows 10 which needs administrative privileges + to delete files from the root */ + +import java.io.File + +fun main(args: Array) { + val paths = arrayOf("input.txt", "docs", "c:\\input.txt", "c:\\docs") + var f: File + for (path in paths) { + f = File(path) + if (f.delete()) + println("$path successfully deleted") + else + println("$path could not be deleted") + } +} diff --git a/Task/Delete-a-file/Nimrod/delete-a-file.nimrod b/Task/Delete-a-file/Nimrod/delete-a-file.nimrod deleted file mode 100644 index 23d6a846aa..0000000000 --- a/Task/Delete-a-file/Nimrod/delete-a-file.nimrod +++ /dev/null @@ -1,5 +0,0 @@ -import os -removeFile("input.txt") -removeFile("/input.txt") -removeDir("docs") -removeDir("/docs") diff --git a/Task/Delete-a-file/OoRexx/delete-a-file.rexx b/Task/Delete-a-file/OoRexx/delete-a-file.rexx new file mode 100644 index 0000000000..8049368e02 --- /dev/null +++ b/Task/Delete-a-file/OoRexx/delete-a-file.rexx @@ -0,0 +1,5 @@ +/*REXX pgm deletes a file */ +file= 'afile.txt' /*name of a file to be deleted.*/ +res=sysFileDelete(file); Say file 'res='res +File= 'bfile.txt' /*name of a file to be deleted.*/ +res=sysFileDelete(file); Say file 'res='res diff --git a/Task/Delete-a-file/Phix/delete-a-file.phix b/Task/Delete-a-file/Phix/delete-a-file.phix new file mode 100644 index 0000000000..230a06b325 --- /dev/null +++ b/Task/Delete-a-file/Phix/delete-a-file.phix @@ -0,0 +1,5 @@ +constant root = iff(platform()=LINUX?"/":"C:\\") +?delete_file("input.txt") +?delete_file(root&"input.txt") +?remove_directory("docs") +?remove_directory(root&"docs") diff --git a/Task/Delete-a-file/Rust/delete-a-file.rust b/Task/Delete-a-file/Rust/delete-a-file.rust new file mode 100644 index 0000000000..ac5f018bff --- /dev/null +++ b/Task/Delete-a-file/Rust/delete-a-file.rust @@ -0,0 +1,25 @@ +use std::io::{self, Write}; +use std::fs::{remove_file,remove_dir}; +use std::path::Path; +use std::{process,display}; + +const FILE_NAME: &'static str = "output.txt"; +const DIR_NAME : &'static str = "docs"; + +fn main() { + delete(".").and(delete("/")) + .unwrap_or_else(|e| error_handler(e,1)); +} + + +fn delete

    (root: P) -> io::Result<()> + where P: AsRef +{ + remove_file(root.as_ref().join(FILE_NAME)) + .and(remove_dir(root.as_ref().join(DIR_NAME))) +} + +fn error_handler(error: E, code: i32) -> ! { + let _ = writeln!(&mut io::stderr(), "{:?}", error); + process::exit(code) +} diff --git a/Task/Delete-a-file/Stata/delete-a-file.stata b/Task/Delete-a-file/Stata/delete-a-file.stata new file mode 100644 index 0000000000..22c5b10ab2 --- /dev/null +++ b/Task/Delete-a-file/Stata/delete-a-file.stata @@ -0,0 +1,2 @@ +erase input.txt +rmdir docs diff --git a/Task/Delete-a-file/Zkl/delete-a-file.zkl b/Task/Delete-a-file/Zkl/delete-a-file.zkl new file mode 100644 index 0000000000..db2ae6f108 --- /dev/null +++ b/Task/Delete-a-file/Zkl/delete-a-file.zkl @@ -0,0 +1,13 @@ +zkl: System.cmd((System.isWindows and "del" or "unlink") + " input.txt") +0 +zkl: System.cmd((System.isWindows and "del" or "unlink") + " /input.txt") +unlink: cannot unlink ‘/input.txt’: No such file or directory +256 +zkl: System.cmd("rmdir docs") +rmdir: failed to remove ‘docs’: Directory not empty +256 +zkl: System.cmd("rm -r docs") +0 +zkl: System.cmd("rm -r /docs") +rm: cannot remove ‘/docs’: No such file or directory +256 diff --git a/Task/Detect-division-by-zero/ALGOL-W/detect-division-by-zero.alg b/Task/Detect-division-by-zero/ALGOL-W/detect-division-by-zero.alg new file mode 100644 index 0000000000..452d391638 --- /dev/null +++ b/Task/Detect-division-by-zero/ALGOL-W/detect-division-by-zero.alg @@ -0,0 +1,28 @@ +begin + % integer division procedure % + % sets c to a divided by b, returns true if the division was OK, % + % false if there was division by zero % + logical procedure divideI ( integer value a, b; integer result c ) ; + begin + % set exception handling to allow integer division by zero to occur once % + INTDIVZERO := EXCEPTION( false, 1, 0, false, "INTDIVZERO" ); + c := a div b; + not XCPNOTED(INTDIVZERO) + end divideI ; + % real division procedure % + % sets c to a divided by b, returns true if the division was OK, % + % false if there was division by zero % + logical procedure divideR ( long real value a, b; long real result c ) ; + begin + % set exception handling to allow realdivision by zero to occur once % + DIVZERO := EXCEPTION( false, 1, 0, false, "DIVZERO" ); + c := a / b; + not XCPNOTED(DIVZERO) + end divideR ; + integer c; + real d; + write( divideI( 4, 2, c ) ); % prints false as no exception % + write( divideI( 5, 0, c ) ); % prints true as division by zero was detected % + write( divideR( 4, 2, d ) ); % prints false as no exception % + write( divideR( 5, 0, d ) ) % prints true as division by zero was detected % +end. diff --git a/Task/Detect-division-by-zero/Ada/detect-division-by-zero.ada b/Task/Detect-division-by-zero/Ada/detect-division-by-zero.ada index b0d54dddc1..05b41b3122 100644 --- a/Task/Detect-division-by-zero/Ada/detect-division-by-zero.ada +++ b/Task/Detect-division-by-zero/Ada/detect-division-by-zero.ada @@ -23,7 +23,7 @@ begin New_Line; Put("Floating point divide by zero: "); Fresult := Fnum / Fdenom; - if Fresult > Float'Last then + if Fresult > Float'Last or Fresult < Float'First then Put("Division by zero detected (infinite value)."); else Put(Item => Fresult, Aft => 9, Exp => 0); diff --git a/Task/Detect-division-by-zero/Applesoft-BASIC/detect-division-by-zero.applesoft b/Task/Detect-division-by-zero/Applesoft-BASIC/detect-division-by-zero.applesoft deleted file mode 100644 index 556e9b99ed..0000000000 --- a/Task/Detect-division-by-zero/Applesoft-BASIC/detect-division-by-zero.applesoft +++ /dev/null @@ -1,10 +0,0 @@ - 100 REM TRY - 110 ONERR GOTO 200 - 120 D = - 44 / 0 - 190 END - 200 REM CATCH - 210 E = PEEK (222) < > 133 - 220 POKE 216,0: REM ONERR OFF - 230 IF E THEN RESUME - 240 CALL - 3288: REM RECOVER - 250 PRINT "DIVISION BY ZERO" diff --git a/Task/Detect-division-by-zero/BBC-BASIC/detect-division-by-zero.bbc b/Task/Detect-division-by-zero/BBC-BASIC/detect-division-by-zero.bbc deleted file mode 100644 index b4ac40401e..0000000000 --- a/Task/Detect-division-by-zero/BBC-BASIC/detect-division-by-zero.bbc +++ /dev/null @@ -1,19 +0,0 @@ - PROCdivide(-44, 0) - PROCdivide(-44, 5) - PROCdivide(0, 5) - PROCdivide(5, 0) - END - - DEF PROCdivide(numerator, denominator) - ON ERROR LOCAL IF FALSE THEN - REM 'Try' clause: - PRINT numerator / denominator - ELSE - REM 'Catch' clause: - CASE ERR OF - WHEN 18: PRINT "Division by zero" - WHEN 20: PRINT "Number too big" - OTHERWISE RESTORE LOCAL : ERROR ERR, REPORT$ - ENDCASE - ENDIF - ENDPROC diff --git a/Task/Detect-division-by-zero/Gambas/detect-division-by-zero.gambas b/Task/Detect-division-by-zero/Gambas/detect-division-by-zero.gambas new file mode 100644 index 0000000000..376c0beea1 --- /dev/null +++ b/Task/Detect-division-by-zero/Gambas/detect-division-by-zero.gambas @@ -0,0 +1,6 @@ +Public Sub Main() + +Try Print 1 / 0 +If Error Then Print Error.Text + +End diff --git a/Task/Detect-division-by-zero/jq/detect-division-by-zero-1.jq b/Task/Detect-division-by-zero/Jq/detect-division-by-zero-1.jq similarity index 100% rename from Task/Detect-division-by-zero/jq/detect-division-by-zero-1.jq rename to Task/Detect-division-by-zero/Jq/detect-division-by-zero-1.jq diff --git a/Task/Detect-division-by-zero/jq/detect-division-by-zero-2.jq b/Task/Detect-division-by-zero/Jq/detect-division-by-zero-2.jq similarity index 100% rename from Task/Detect-division-by-zero/jq/detect-division-by-zero-2.jq rename to Task/Detect-division-by-zero/Jq/detect-division-by-zero-2.jq diff --git a/Task/Detect-division-by-zero/Kotlin/detect-division-by-zero.kotlin b/Task/Detect-division-by-zero/Kotlin/detect-division-by-zero.kotlin new file mode 100644 index 0000000000..f27ec0aaad --- /dev/null +++ b/Task/Detect-division-by-zero/Kotlin/detect-division-by-zero.kotlin @@ -0,0 +1,20 @@ +// version 1.1 + +fun divideByZero(x: Int, y:Int): Boolean = + try { + x / y + false + } catch(e: ArithmeticException) { + true + } + +fun main(args: Array) { + val x = 1 + val y = 0 + if (divideByZero(x, y)) { + println("Attempted to divide by zero") + } else { + @Suppress("DIVISION_BY_ZERO") + println("$x / $y = ${x / y}") + } +} diff --git a/Task/Detect-division-by-zero/Liberty-BASIC/detect-division-by-zero.liberty b/Task/Detect-division-by-zero/Liberty-BASIC/detect-division-by-zero.liberty deleted file mode 100644 index 5b02911f51..0000000000 --- a/Task/Detect-division-by-zero/Liberty-BASIC/detect-division-by-zero.liberty +++ /dev/null @@ -1,12 +0,0 @@ -result = DetectDividebyZero(1, 0) - - -Function DetectDividebyZero(a, b) - On Error GoTo [Error] - DetectDividebyZero= (a/ b) - Exit Function - [Error] - If Err = 11 Then '11 is the error number raised when divide by zero occurs - Notice "Divide by Zero Detected!" - End If -End Function diff --git a/Task/Detect-division-by-zero/Locomotive-Basic/detect-division-by-zero.locomotive b/Task/Detect-division-by-zero/Locomotive-Basic/detect-division-by-zero.locomotive deleted file mode 100644 index 27ec7e1b97..0000000000 --- a/Task/Detect-division-by-zero/Locomotive-Basic/detect-division-by-zero.locomotive +++ /dev/null @@ -1,6 +0,0 @@ -10 ON ERROR GOTO 60 -20 PRINT 2/3 -30 PRINT 3/5 -40 PRINT 4/0 -50 END -60 IF ERR=11 THEN PRINT "Division by zero in line"ERL:RESUME 50 diff --git a/Task/Detect-division-by-zero/MIRC-Scripting-Language/detect-division-by-zero.mirc b/Task/Detect-division-by-zero/MIRC-Scripting-Language/detect-division-by-zero.mirc new file mode 100644 index 0000000000..38d4d05fa2 --- /dev/null +++ b/Task/Detect-division-by-zero/MIRC-Scripting-Language/detect-division-by-zero.mirc @@ -0,0 +1,7 @@ +var %n = $rand(0,1) +if ($calc(1/ %n) == $calc((1/ %n)+1)) { + echo -ag Divides By Zero +} +else { + echo -ag Does Not Divide By Zero +} diff --git a/Task/Detect-division-by-zero/OoRexx/detect-division-by-zero.rexx b/Task/Detect-division-by-zero/OoRexx/detect-division-by-zero.rexx new file mode 100644 index 0000000000..8f6ea4f0f1 --- /dev/null +++ b/Task/Detect-division-by-zero/OoRexx/detect-division-by-zero.rexx @@ -0,0 +1,18 @@ +/* REXX ************************************************************** +* program demonstrates detects and handles division by zero. +* translated from REXX: +* removed fancy error reporting (ooRexx does not support linesize) +* removed label Novalue (as novalue is not enabled there) +* 28.04.2013 Walter Pachl +*********************************************************************/ +Signal on Syntax /*handle all REXX syntax errors. */ +x = sourceline() /*being cute, x=size of this pgm.*/ +y = x-x /*setting to zero the obtuse way.*/ +z = x/y /* attempt to divide by 0 */ +exit /* will not be reached */ + +Syntax: + Say 'Syntax raised in line' sigl + Say sourceline(sigl) + Say 'rc='rc '('errortext(rc)')' + Exit 12 diff --git a/Task/Detect-division-by-zero/Phix/detect-division-by-zero.phix b/Task/Detect-division-by-zero/Phix/detect-division-by-zero.phix new file mode 100644 index 0000000000..0112ea0494 --- /dev/null +++ b/Task/Detect-division-by-zero/Phix/detect-division-by-zero.phix @@ -0,0 +1,6 @@ +try + integer i = 1/0 +catch e + ?e[E_USER] +end try +puts(1,"still running...\n") diff --git a/Task/Detect-division-by-zero/PureBasic/detect-division-by-zero-1.purebasic b/Task/Detect-division-by-zero/PureBasic/detect-division-by-zero-1.purebasic deleted file mode 100644 index 663cc0755f..0000000000 --- a/Task/Detect-division-by-zero/PureBasic/detect-division-by-zero-1.purebasic +++ /dev/null @@ -1,13 +0,0 @@ -;Set up a Procedure to handle any Error -Procedure MyErrorHandler() - Define txt$="The following error happened."+#CRLF$+ ErrorMessage()+"at line "+Str(ErrorLine()) - MessageRequester("OnError test", txt$) -EndProcedure - -; Tell where to go if an Error happens -OnErrorCall(@MyErrorHandler()) - -;Now, do something very stupid so that we may see an Error... -Repeat - A=Random(100)/Random(100) -ForEver diff --git a/Task/Detect-division-by-zero/PureBasic/detect-division-by-zero-2.purebasic b/Task/Detect-division-by-zero/PureBasic/detect-division-by-zero-2.purebasic deleted file mode 100644 index 16b33ba475..0000000000 --- a/Task/Detect-division-by-zero/PureBasic/detect-division-by-zero-2.purebasic +++ /dev/null @@ -1,2 +0,0 @@ -Define.d a, b -Debug a/b diff --git a/Task/Detect-division-by-zero/Run-BASIC/detect-division-by-zero.run b/Task/Detect-division-by-zero/Run-BASIC/detect-division-by-zero.run deleted file mode 100644 index 61985e1dd3..0000000000 --- a/Task/Detect-division-by-zero/Run-BASIC/detect-division-by-zero.run +++ /dev/null @@ -1,7 +0,0 @@ -on error goto [error] -a = 1 / 0 -wait - -[error] ' error 11 is division by zero err number -If err = 11 Then print "Division by Zero" -wait diff --git a/Task/Detect-division-by-zero/Sidef/detect-division-by-zero-1.sidef b/Task/Detect-division-by-zero/Sidef/detect-division-by-zero-1.sidef new file mode 100644 index 0000000000..cb3156dc3e --- /dev/null +++ b/Task/Detect-division-by-zero/Sidef/detect-division-by-zero-1.sidef @@ -0,0 +1,7 @@ +func div_check(a, b){ + var result = a/b + result.abs == Inf ? nil : result +} +  +say div_check(10, 2) # 5 +say div_check(1, 0) # nil (detected) diff --git a/Task/Detect-division-by-zero/Sidef/detect-division-by-zero-2.sidef b/Task/Detect-division-by-zero/Sidef/detect-division-by-zero-2.sidef new file mode 100644 index 0000000000..7f2d700398 --- /dev/null +++ b/Task/Detect-division-by-zero/Sidef/detect-division-by-zero-2.sidef @@ -0,0 +1,6 @@ +func div_check(a, b){ + Perl.eval("#{a} / #{b}") +} +  +say div_check(10, 2) # 5 +say div_check(1, 0) # nil (detected) diff --git a/Task/Detect-division-by-zero/Sidef/detect-division-by-zero.sidef b/Task/Detect-division-by-zero/Sidef/detect-division-by-zero.sidef deleted file mode 100644 index 964b315847..0000000000 --- a/Task/Detect-division-by-zero/Sidef/detect-division-by-zero.sidef +++ /dev/null @@ -1,13 +0,0 @@ -func div(a, b){ - try { - a / b - } - catch { |_, msg| - say "tried to divide by zero" if (msg ~~ /Division by zero/) - nil - } -} - -say div(10, 2); # 5 -say div(1, 0); # inf, 1/0 constants are substituted for infinity -say div(1.c, 0.c); # nil, and prints "tried to divide by zero" (complex numbers) diff --git a/Task/Detect-division-by-zero/Zkl/detect-division-by-zero.zkl b/Task/Detect-division-by-zero/Zkl/detect-division-by-zero.zkl new file mode 100644 index 0000000000..cda8f374ae --- /dev/null +++ b/Task/Detect-division-by-zero/Zkl/detect-division-by-zero.zkl @@ -0,0 +1 @@ +fcn f(x,y){try{x/y}catch(MathError){println(__exception)}} diff --git a/Task/Determine-if-a-string-is-numeric/BaCon/determine-if-a-string-is-numeric.bacon b/Task/Determine-if-a-string-is-numeric/BaCon/determine-if-a-string-is-numeric.bacon new file mode 100644 index 0000000000..32f629f6c2 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/BaCon/determine-if-a-string-is-numeric.bacon @@ -0,0 +1,7 @@ +INPUT "Your string: ", s$ + +IF VAL(s$) = 0 AND s$ <> "0" THEN + PRINT "Not a number" +ELSE + PRINT "This is a number" +END IF diff --git a/Task/Determine-if-a-string-is-numeric/ColdFusion/determine-if-a-string-is-numeric.cfm b/Task/Determine-if-a-string-is-numeric/ColdFusion/determine-if-a-string-is-numeric-1.cfm similarity index 100% rename from Task/Determine-if-a-string-is-numeric/ColdFusion/determine-if-a-string-is-numeric.cfm rename to Task/Determine-if-a-string-is-numeric/ColdFusion/determine-if-a-string-is-numeric-1.cfm diff --git a/Task/Determine-if-a-string-is-numeric/ColdFusion/determine-if-a-string-is-numeric-2.cfm b/Task/Determine-if-a-string-is-numeric/ColdFusion/determine-if-a-string-is-numeric-2.cfm new file mode 100644 index 0000000000..62b836f5ee --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/ColdFusion/determine-if-a-string-is-numeric-2.cfm @@ -0,0 +1 @@ +#isNumeric(42)# diff --git a/Task/Determine-if-a-string-is-numeric/ERRE/determine-if-a-string-is-numeric.erre b/Task/Determine-if-a-string-is-numeric/ERRE/determine-if-a-string-is-numeric.erre new file mode 100644 index 0000000000..e63152fd0e --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/ERRE/determine-if-a-string-is-numeric.erre @@ -0,0 +1,15 @@ +PROGRAM NUMERIC + +PROCEDURE IS_NUMERIC(S$->ANS%) +LOCAL T1,T1$ + T1=VAL(S$) + T1$=STR$(T1) + ANS%=(T1$=S$) OR T1$=" "+S$ +END PROCEDURE + +BEGIN + PRINT(CHR$(12);) + INPUT("Enter a string",S$) + IS_NUMERIC(S$->ANS%) + IF ANS% THEN PRINT("is num") ELSE PRINT("not num") +END PROGRAM diff --git a/Task/Determine-if-a-string-is-numeric/Elixir/determine-if-a-string-is-numeric.elixir b/Task/Determine-if-a-string-is-numeric/Elixir/determine-if-a-string-is-numeric.elixir index a7381f48a5..19947147bc 100644 --- a/Task/Determine-if-a-string-is-numeric/Elixir/determine-if-a-string-is-numeric.elixir +++ b/Task/Determine-if-a-string-is-numeric/Elixir/determine-if-a-string-is-numeric.elixir @@ -2,13 +2,9 @@ defmodule RC do def is_numeric(str) do case Float.parse(str) do {_num, ""} -> true - {_num, _r} -> false # _r : remainder_of_bianry - :error -> false + _ -> false end end end -strs = ["123", "-12.3", "123.", ".05", "-12e5", "+123", " 123", "abc", "123a", "12.3e", "1 2"] -Enum.each(strs, fn str -> - IO.puts "#{inspect str}\t=> #{RC.is_numeric(str)}" -end) +["123", "-12.3", "123.", ".05", "-12e5", "+123", " 123", "abc", "123a", "12.3e", "1 2"] |> Enum.filter(&RC.is_numeric/1) diff --git a/Task/Determine-if-a-string-is-numeric/Gambas/determine-if-a-string-is-numeric.gambas b/Task/Determine-if-a-string-is-numeric/Gambas/determine-if-a-string-is-numeric.gambas new file mode 100644 index 0000000000..4119851023 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Gambas/determine-if-a-string-is-numeric.gambas @@ -0,0 +1,9 @@ +Public Sub Form_Open() +Dim sAnswer, sString As String + +sString = Trim(InputBox("Enter as string", "String or Numeric")) + +If IsNumber(sString) Then sAnswer = "'" & sString & "' is numeric" Else sAnswer = "'" & sString & "' is a string" +Print sAnswer + +End diff --git a/Task/Determine-if-a-string-is-numeric/Haxe/determine-if-a-string-is-numeric.haxe b/Task/Determine-if-a-string-is-numeric/Haxe/determine-if-a-string-is-numeric.haxe new file mode 100644 index 0000000000..62c9310eca --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Haxe/determine-if-a-string-is-numeric.haxe @@ -0,0 +1,11 @@ +static function isNumeric(n:String):Bool +{ + if (Std.parseInt(n) != null) //Std.parseInt converts a string to an int + { + return true; //as long as it results in an integer, the function will return true + } + else + { + return false; + } +} diff --git a/Task/Determine-if-a-string-is-numeric/jq/determine-if-a-string-is-numeric-1.jq b/Task/Determine-if-a-string-is-numeric/Jq/determine-if-a-string-is-numeric-1.jq similarity index 100% rename from Task/Determine-if-a-string-is-numeric/jq/determine-if-a-string-is-numeric-1.jq rename to Task/Determine-if-a-string-is-numeric/Jq/determine-if-a-string-is-numeric-1.jq diff --git a/Task/Determine-if-a-string-is-numeric/jq/determine-if-a-string-is-numeric-2.jq b/Task/Determine-if-a-string-is-numeric/Jq/determine-if-a-string-is-numeric-2.jq similarity index 100% rename from Task/Determine-if-a-string-is-numeric/jq/determine-if-a-string-is-numeric-2.jq rename to Task/Determine-if-a-string-is-numeric/Jq/determine-if-a-string-is-numeric-2.jq diff --git a/Task/Determine-if-a-string-is-numeric/Kotlin/determine-if-a-string-is-numeric.kotlin b/Task/Determine-if-a-string-is-numeric/Kotlin/determine-if-a-string-is-numeric.kotlin new file mode 100644 index 0000000000..1efecf0685 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Kotlin/determine-if-a-string-is-numeric.kotlin @@ -0,0 +1,14 @@ +// version 1.1 + +fun isNumeric(input: String): Boolean = + try { + input.toDouble() + true + } catch(e: NumberFormatException) { + false + } + +fun main(args: Array) { + val inputs = arrayOf("152", "-3.1415926", "Foo123", "-0", "456bar", "1.0E10") + for (input in inputs) println("$input is ${if (isNumeric(input)) "numeric" else "not numeric"}") +} diff --git a/Task/Determine-if-a-string-is-numeric/MIRC-Scripting-Language/determine-if-a-string-is-numeric.mirc b/Task/Determine-if-a-string-is-numeric/MIRC-Scripting-Language/determine-if-a-string-is-numeric.mirc new file mode 100644 index 0000000000..ef6d1b9d74 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/MIRC-Scripting-Language/determine-if-a-string-is-numeric.mirc @@ -0,0 +1,4 @@ +var %value = 3 +if (%value isnum) { + echo -s %value is numeric. +} diff --git a/Task/Determine-if-a-string-is-numeric/Perl-6/determine-if-a-string-is-numeric.pl6 b/Task/Determine-if-a-string-is-numeric/Perl-6/determine-if-a-string-is-numeric.pl6 index 7abea7ebec..29a402ec11 100644 --- a/Task/Determine-if-a-string-is-numeric/Perl-6/determine-if-a-string-is-numeric.pl6 +++ b/Task/Determine-if-a-string-is-numeric/Perl-6/determine-if-a-string-is-numeric.pl6 @@ -1,5 +1,5 @@ sub is-number( $term --> Bool ) { - ?($term ~~ /\d/) and +$term ~~ Numeric; + ?($term ~~ /\d/) and $term ~~ Numeric; } printf "%10s %s\n", "<$_>", is-number( $_ ) for flat diff --git a/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-1.py b/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-1.py index c21b0db3a8..6f53289327 100644 --- a/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-1.py +++ b/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-1.py @@ -1,5 +1,8 @@ -s = '123' -try: - i = float(s) -except (ValueError, TypeError): - print 'not numeric' +def is_numeric(s): + try: + float(s) + return True + except (ValueError, TypeError): + return False + +is_numeric('123.0') diff --git a/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-2.py b/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-2.py index 44802a8f1a..5f3a762d02 100644 --- a/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-2.py +++ b/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-2.py @@ -1,3 +1 @@ -s = '123' -if s.isdigit(): - print int(s) +'123'.isdigit() diff --git a/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-3.py b/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-3.py index ac9c8d2aa3..e806323547 100644 --- a/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-3.py +++ b/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-3.py @@ -1,28 +1,13 @@ -def is_numeric(lit): - 'Return value of numeric literal string or ValueError exception' - - # Handle '0' - if lit == '0': return 0 - # Hex/Binary - litneg = lit[1:] if lit[0] == '-' else lit - if litneg[0] == '0': - if litneg[1] in 'xX': - return int(lit,16) - elif litneg[1] in 'bB': - return int(lit,2) - else: - try: - return int(lit,8) - except ValueError: - pass - - # Int/Float/Complex - try: - return int(lit) - except ValueError: - pass - try: - return float(lit) - except ValueError: - pass - return complex(lit) +def is_numeric(literal): + """Return whether a literal can be parsed as a numeric value""" + castings = [int, float, complex, + lambda s: int(s,2), #binary + lambda s: int(s,8), #octal + lambda s: int(s,16)] #hex + for cast in castings: + try: + cast(literal) + return True + except ValueError: + pass + return False diff --git a/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-4.py b/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-4.py index 589d643611..f417d5a77c 100644 --- a/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-4.py +++ b/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-4.py @@ -1,16 +1,23 @@ ->>> for s in ['0', '00', '123', '-123.', '-123e-4', '0123', '0x1a1', '-123+4.5j', '0b0101', '0.123', '-0xabc', '-0b101']: - print "%14s -> %-14s %s" % ('"'+s+'"', is_numeric(s), type(is_numeric(s))) +def numeric(literal): + """Return value of numeric literal or None if can't parse a value""" + castings = [int, float, complex, + lambda s: int(s,2), #binary + lambda s: int(s,8), #octal + lambda s: int(s,16)] #hex + for cast in castings: + try: + return cast(literal) + except ValueError: + pass + return None - "0" -> 0 - "00" -> 0 - "123" -> 123 - "-123." -> -123.0 - "-123e-4" -> -0.0123 - "0123" -> 83 - "0x1a1" -> 417 - "-123+4.5j" -> (-123+4.5j) - "0b0101" -> 5 - "0.123" -> 0.123 - "-0xabc" -> -2748 - "-0b101" -> -5 ->>> + +tests = [ + '0', '0.', '00', '123', '0123', '+123', '-123', '-123.', '-123e-4', '-.8E-04', + '0.123', '(5)', '-123+4.5j', '0b0101', ' +0B101 ', '0o123', '-0xABC', '0x1a1', + '12.5%', '1/2', '½', '3¼', 'π', 'Ⅻ', '1,000,000', '1 000', '- 001.20e+02', + 'NaN', 'inf', '-Infinity'] + +for s in tests: + print("%14s -> %-14s %-20s is_numeric: %-5s str.isnumeric: %s" % ( + '"'+s+'"', numeric(s), type(numeric(s)), is_numeric(s), s.isnumeric() )) diff --git a/Task/Determine-if-a-string-is-numeric/Rust/determine-if-a-string-is-numeric.rust b/Task/Determine-if-a-string-is-numeric/Rust/determine-if-a-string-is-numeric.rust new file mode 100644 index 0000000000..9ec271db38 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Rust/determine-if-a-string-is-numeric.rust @@ -0,0 +1,4 @@ +// This function is not limited to just numeric types but rather anything that implements the FromStr trait. +fn parsable(s: &str) -> bool { + s.parse::().is_ok() +} diff --git a/Task/Determine-if-a-string-is-numeric/Simula/determine-if-a-string-is-numeric.simula b/Task/Determine-if-a-string-is-numeric/Simula/determine-if-a-string-is-numeric.simula new file mode 100644 index 0000000000..296be5b68a --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Simula/determine-if-a-string-is-numeric.simula @@ -0,0 +1,74 @@ +BEGIN + + BOOLEAN PROCEDURE ISNUMERIC(W); TEXT W; + BEGIN + BOOLEAN PROCEDURE MORE; + MORE := W.MORE; + CHARACTER PROCEDURE NEXT; + NEXT := IF MORE THEN W.GETCHAR ELSE CHAR(0); + CHARACTER PROCEDURE LAST; + LAST := IF W.LENGTH = 0 + THEN CHAR(0) + ELSE W.SUB(W.LENGTH,1).GETCHAR; + CHARACTER CH; + W.SETPOS(1); + IF MORE THEN + BEGIN + CH := NEXT; + IF CH = '-' OR CH = '+' THEN CH := NEXT; + WHILE DIGIT(CH) DO CH := NEXT; + IF CH = '.' THEN + BEGIN + CH := NEXT; + IF NOT DIGIT(CH) THEN GOTO L; + WHILE DIGIT(CH) DO CH := NEXT; + END; + IF CH = '&' THEN + BEGIN + CH := NEXT; + IF CH = '-' OR CH = '+' THEN CH := NEXT; + WHILE DIGIT(CH) DO CH := NEXT; + END; + END; + L: ISNUMERIC := (W.LENGTH > 0) AND THEN (NOT MORE) AND THEN DIGIT(LAST); + END; + + REAL X; + TEXT T; + FOR X := 0, -3.1415, 2.768&+31, 5&10, .5, 5.&10 DO + BEGIN + OUTREAL(X, 10, 20); + OUTIMAGE; + END; + + OUTIMAGE; + + FOR T :- "0", "-3.1415", "2.768&+31", ".5", "5&22" DO + BEGIN + OUTTEXT(IF ISNUMERIC(T) THEN " NUMERIC " ELSE "NOT NUMERIC "); + OUTCHAR('"'); + OUTTEXT(T); + OUTCHAR('"'); + IF T = "0" THEN OUTCHAR(CHAR(9)); OUTCHAR(CHAR(9)); + COMMENT PROBE ; + X := T.GETREAL; + OUTREAL(X, 10, 20); + OUTIMAGE; + END; + + OUTIMAGE; + + X := 5.&10; + !X := 5&; + !X := 5.; + X := .5; + FOR T :- "", "5.", "5&", "5&+", "5.&", "5.&-", "5.&10" DO + BEGIN + OUTTEXT(IF ISNUMERIC(T) THEN " NUMERIC " ELSE "NOT NUMERIC "); + OUTCHAR('"'); + OUTTEXT(T); + OUTCHAR('"'); + OUTIMAGE; + END; + +END diff --git a/Task/Determine-if-a-string-is-numeric/Zkl/determine-if-a-string-is-numeric.zkl b/Task/Determine-if-a-string-is-numeric/Zkl/determine-if-a-string-is-numeric.zkl new file mode 100644 index 0000000000..b0e26c97df --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Zkl/determine-if-a-string-is-numeric.zkl @@ -0,0 +1,6 @@ +fcn isNum(text){ + try{ text.toInt(); True } + catch{ try{ text.toFloat(); True } + catch{ False } + } +} diff --git a/Task/Determine-if-only-one-instance-is-running/Kotlin/determine-if-only-one-instance-is-running.kotlin b/Task/Determine-if-only-one-instance-is-running/Kotlin/determine-if-only-one-instance-is-running.kotlin new file mode 100644 index 0000000000..4ee110d1b6 --- /dev/null +++ b/Task/Determine-if-only-one-instance-is-running/Kotlin/determine-if-only-one-instance-is-running.kotlin @@ -0,0 +1,36 @@ +// version 1.0.6 + +import java.io.IOException +import java.net.* + +object SingleInstance { + private var ss: ServerSocket? = null + + fun alreadyRunning(): Boolean { + try { + ss = ServerSocket(65000, 10, InetAddress.getLocalHost()) // using private port 65000 + } + catch (e: IOException) { + // port already in use so an instance is already running + return true + } + return false + } + + fun close() { + if (ss == null || ss?.isClosed() == true) return + ss?.close() + } +} + +fun main(args: Array) { + if (SingleInstance.alreadyRunning()) { + println("Application is already running, so terminating this instance") + System.exit(0) + } + else { + println("OK, only this instance is running but will terminate in 10 seconds") + Thread.sleep(10000) + SingleInstance.close() + } +} diff --git a/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6 b/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6 index 34b7c53825..3305f877fb 100644 --- a/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6 +++ b/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6 @@ -15,12 +15,12 @@ my $pidfile = open "$lockpid", :w or die "Can't create $lockpid: $!"; $pidfile.say($pid); $pidfile.close; -if try link($lockpid, $lockfile) { +if try link($lockfile, $lockpid) { $havelock = True; } else { shell "kill -CONT `cat $lockfile` || rm $lockfile"; - if try link($lockpid, $lockfile) { + if try link($lockfile, $lockpid) { $havelock = True; } else { diff --git a/Task/Determine-if-only-one-instance-is-running/Phix/determine-if-only-one-instance-is-running.phix b/Task/Determine-if-only-one-instance-is-running/Phix/determine-if-only-one-instance-is-running.phix index 179eb8bda4..e54350efa9 100644 --- a/Task/Determine-if-only-one-instance-is-running/Phix/determine-if-only-one-instance-is-running.phix +++ b/Task/Determine-if-only-one-instance-is-running/Phix/determine-if-only-one-instance-is-running.phix @@ -1,3 +1,6 @@ +-- +-- demo\rosetta\Single_instance.exw +-- include pGUI.e function copydata_cb(Ihandle /*ih*/, atom pCommandLine, integer size) @@ -10,14 +13,14 @@ function esc_close(Ihandle /*ih*/, atom c) return iff(c=K_ESC?IUP_CLOSE:IUP_CONTINUE) end function - IupOpen("../pGUI/") - IupSetGlobal("SINGLEINSTANCE", "Single") -- (must [partially] match the main window title) - if IupGetGlobal("SINGLEINSTANCE")!="" then - Ihandle dlg = IupDialog(IupVbox({IupLabel("hello")},"MARGIN=200x200")) - IupSetAttribute(dlg,"TITLE","Single Instance") - IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) - IupSetCallback(dlg, "COPYDATA_CB", Icallback("copydata_cb")); - IupShow(dlg) - IupMainLoop() - end if - IupClose() +IupOpen() +IupSetGlobal("SINGLEINSTANCE", "Single") -- (must [partially] match the main window title) +if IupGetGlobal("SINGLEINSTANCE")!="" then + Ihandle dlg = IupDialog(IupVbox({IupLabel("hello")},"MARGIN=200x200")) + IupSetAttribute(dlg,"TITLE","Single Instance") + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + IupSetCallback(dlg, "COPYDATA_CB", Icallback("copydata_cb")); + IupShow(dlg) + IupMainLoop() +end if +IupClose() diff --git a/Task/Determine-if-only-one-instance-is-running/TXR/determine-if-only-one-instance-is-running.txr b/Task/Determine-if-only-one-instance-is-running/TXR/determine-if-only-one-instance-is-running.txr new file mode 100644 index 0000000000..8443fdcafb --- /dev/null +++ b/Task/Determine-if-only-one-instance-is-running/TXR/determine-if-only-one-instance-is-running.txr @@ -0,0 +1,25 @@ +;;; Define some typedefs for clear correspondence with Win32 +(typedef HANDLE cptr) +(typedef LPSECURITY_ATTRIBUTES cptr) +(typedef WINERR (enum WINERR ERROR_SUCCESS + (ERROR_ALREADY_EXISTS 183))) +(typedef BOOL (enum BOOL FALSE TRUE)) +(typedef LPCWSTR wstr) + +;;; More familiar spelling for null pointer. +(defvarl NULL cptr-null) + +;;; Define access to foreign functions. +(with-dyn-lib "kernel32.dll" + (deffi CreateMutex "CreateMutexW" HANDLE (LPSECURITY_ATTRIBUTES BOOL LPCWSTR)) + (deffi CloseHandle "CloseHandle" BOOL (HANDLE)) + (deffi GetLastError "GetLastError" WINERR ())) + +;;; Now, the single-instance program: +(defvar m (CreateMutex NULL 'TRUE "ApplicationName")) + +(unless (eq (GetLastError) 'ERROR_ALREADY_EXISTS) + ;; mutual exclusion here + ) + +(CloseHandle m) diff --git a/Task/Digital-root-Multiplicative-digital-root/ALGOL-W/digital-root-multiplicative-digital-root.alg b/Task/Digital-root-Multiplicative-digital-root/ALGOL-W/digital-root-multiplicative-digital-root.alg new file mode 100644 index 0000000000..bbc380ab9a --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/ALGOL-W/digital-root-multiplicative-digital-root.alg @@ -0,0 +1,66 @@ +begin + % calculate the Multiplicative Digital Root (mdr) and Multiplicative Persistence (mp) of n % + procedure getMDR ( integer value n + ; integer result mdr, mp + ) ; + begin + mp := 0; + mdr := abs n; + while mdr > 9 do begin + integer v; + v := mdr; + mdr := 1; + while begin + mdr := mdr * ( v rem 10 ); + v := v div 10; + v > 0 + end do begin end; + mp := mp + 1; + end while_mdr_gt_9 ; + end getMDR ; + + % task test cases % + write( " N MDR MP" ); + for n := 123321, 7739, 893, 899998 do begin + integer mdr, mp; + getMDR( n, mdr, mp ); + write( s_w := 1, i_w := 8, n, i_w := 3, mdr, i_w := 2, mp ) + end for_n ; + + begin % find the first 5 numbers with each possible MDR % + integer requiredMdrs; + requiredMdrs := 5; + begin + integer array firstFew ( 0 :: 9, 1 :: requiredMdrs ); + integer array mdrFOund ( 0 :: 9 ); + integer totalFound, requiredTotal, n; + for i := 0 until 9 do mdrFound( i ) := 0; + totalFound := 0; + requiredTotal := 10 * requiredMdrs; + n := -1; + while totalFound < requiredTotal do begin + integer mdr, mp; + n := n + 1; + getMDR( n, mdr, mp ); + if mdrFound( mdr ) < requiredMdrs then begin + % found another number with this MDR and haven't found enough yet % + totalFound := totalFound + 1; + mdrFound( mdr ) := mdrFound( mdr ) + 1; + firstFew( mdr, mdrFound( mdr ) ) := n + end if_found_another_MDR + end while_totalFound_lt_requiredTotal ; + % print the table of MDRs andnumbers % + write( "MDR: [n0..n4]" ); + write( "=== ========" ); + for v := 0 until 9 do begin + write( i_w := 3, s_w := 0, v, ": [" ); + for foundPos := 1 until requiredMdrs do begin + if foundPos > 1 then writeon( s_w := 0, ", " ); + writeon( i_w := 1, s_w := 0, firstFew( v, foundPos ) ) + end for_foundPos ; + writeon( s_w := 0, "]" ) + end for_v + end + end + +end. diff --git a/Task/Digital-root-Multiplicative-digital-root/Component-Pascal/digital-root-multiplicative-digital-root.component b/Task/Digital-root-Multiplicative-digital-root/Component-Pascal/digital-root-multiplicative-digital-root.component new file mode 100644 index 0000000000..84d3117e90 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Component-Pascal/digital-root-multiplicative-digital-root.component @@ -0,0 +1,69 @@ +MODULE MDR; +IMPORT StdLog, Strings, TextMappers, DevCommanders; + +PROCEDURE CalcMDR(x: LONGINT; OUT mdr, mp: LONGINT); +VAR + str: ARRAY 64 OF CHAR; + i: INTEGER; +BEGIN + mdr := 1; mp := 0; + LOOP + Strings.IntToString(x,str); + IF LEN(str$) = 1 THEN mdr := x; EXIT END; + i := 0;mdr := 1; + WHILE i < LEN(str$) DO + mdr := mdr * (ORD(str[i]) - ORD('0')); + INC(i) + END; + INC(mp); + x := mdr + END +END CalcMDR; + +PROCEDURE Do*; +VAR + mdr,mp: LONGINT; + s: TextMappers.Scanner; +BEGIN + s.ConnectTo(DevCommanders.par.text); + s.SetPos(DevCommanders.par.beg); + REPEAT + s.Scan; + IF (s.type = TextMappers.int) OR (s.type = TextMappers.lint) THEN + CalcMDR(s.int,mdr,mp); + StdLog.Int(s.int); + StdLog.String(" MDR: ");StdLog.Int(mdr); + StdLog.String(" MP: ");StdLog.Int(mp);StdLog.Ln + END + UNTIL s.rider.eot; +END Do; + +PROCEDURE Show(i: INTEGER; x: ARRAY OF LONGINT); +VAR + k: INTEGER; +BEGIN + StdLog.Int(i);StdLog.String(": "); + FOR k := 0 TO LEN(x) - 1 DO + StdLog.Int(x[k]) + END; + StdLog.Ln +END Show; + +PROCEDURE FirstFive*; +VAR + i,j: INTEGER; + five: ARRAY 5 OF LONGINT; + x,mdr,mp: LONGINT; +BEGIN + FOR i := 0 TO 9 DO + j := 0;x := 0; + WHILE (j < LEN(five)) DO + CalcMDR(x,mdr,mp); + IF mdr = i THEN five[j] := x; INC(j) END; + INC(x) + END; + Show(i,five) + END +END FirstFive; + +END MDR. diff --git a/Task/Digital-root-Multiplicative-digital-root/FreeBASIC/digital-root-multiplicative-digital-root.freebasic b/Task/Digital-root-Multiplicative-digital-root/FreeBASIC/digital-root-multiplicative-digital-root.freebasic new file mode 100644 index 0000000000..9db2c21909 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/FreeBASIC/digital-root-multiplicative-digital-root.freebasic @@ -0,0 +1,52 @@ +' FB 1.05.0 Win64 + +Function multDigitalRoot(n As UInteger, ByRef mp As Integer, base_ As Integer = 10) As Integer + Dim mdr As Integer + mp = 0 + Do + mdr = IIf(n > 0, 1, 0) + While n > 0 + mdr *= n Mod base_ + n = n \ base_ + Wend + mp += 1 + n = mdr + Loop until mdr < base_ + Return mdr +End Function + +Dim As Integer mdr, mp +Dim a(3) As UInteger = {123321, 7739, 893, 899998} +For i As UInteger = 0 To 3 + mp = 0 + mdr = multDigitalRoot(a(i), mp) + Print a(i); Tab(10); "MDR ="; mdr; Tab(20); "MP ="; mp + Print +Next +Print +Print "MDR 1 2 3 4 5" +Print "=== ===========================" +Print +Dim num(0 To 9, 0 To 5) As UInteger '' all zero by default +Dim As UInteger n = 0, count = 0 +Do + mdr = multDigitalRoot(n, mp) + If num(mdr, 0) < 5 Then + num(mdr, 0) += 1 + num(mdr, num(mdr, 0)) = n + count += 1 + End If + n += 1 +Loop Until count = 50 + +For i As UInteger = 0 To 9 + Print i; ":" ; + For j As UInteger = 1 To 5 + Print Using "######"; num(i, j); + Next j + Print +Next i + +Print +Print "Press any key to quit" +Sleep diff --git a/Task/Digital-root-Multiplicative-digital-root/jq/digital-root-multiplicative-digital-root-1.jq b/Task/Digital-root-Multiplicative-digital-root/Jq/digital-root-multiplicative-digital-root-1.jq similarity index 100% rename from Task/Digital-root-Multiplicative-digital-root/jq/digital-root-multiplicative-digital-root-1.jq rename to Task/Digital-root-Multiplicative-digital-root/Jq/digital-root-multiplicative-digital-root-1.jq diff --git a/Task/Digital-root-Multiplicative-digital-root/jq/digital-root-multiplicative-digital-root-2.jq b/Task/Digital-root-Multiplicative-digital-root/Jq/digital-root-multiplicative-digital-root-2.jq similarity index 100% rename from Task/Digital-root-Multiplicative-digital-root/jq/digital-root-multiplicative-digital-root-2.jq rename to Task/Digital-root-Multiplicative-digital-root/Jq/digital-root-multiplicative-digital-root-2.jq diff --git a/Task/Digital-root-Multiplicative-digital-root/jq/digital-root-multiplicative-digital-root-3.jq b/Task/Digital-root-Multiplicative-digital-root/Jq/digital-root-multiplicative-digital-root-3.jq similarity index 100% rename from Task/Digital-root-Multiplicative-digital-root/jq/digital-root-multiplicative-digital-root-3.jq rename to Task/Digital-root-Multiplicative-digital-root/Jq/digital-root-multiplicative-digital-root-3.jq 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.kotlin new file mode 100644 index 0000000000..913ee1f93a --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Kotlin/digital-root-multiplicative-digital-root.kotlin @@ -0,0 +1,51 @@ +// version 1.1.2 + +fun multDigitalRoot(n: Int): Pair = when { + n < 0 -> throw IllegalArgumentException("Negative numbers not allowed") + else -> { + var mdr: Int + var mp = 0 + var nn = n + do { + mdr = if (nn > 0) 1 else 0 + while (nn > 0) { + mdr *= nn % 10 + nn /= 10 + } + mp++ + nn = mdr + } + while (mdr >= 10) + Pair(mdr, mp) + } + } + +fun main(args: Array) { + val ia = intArrayOf(123321, 7739, 893, 899998) + for (i in ia) { + val (mdr, mp) = multDigitalRoot(i) + println("${i.toString().padEnd(9)} MDR = $mdr MP = $mp") + } + println() + println("MDR n0 n1 n2 n3 n4") + println("=== ===========================") + val ia2 = Array(10) { IntArray(6) } // all zero by default + var n = 0 + var count = 0 + do { + val (mdr, _) = multDigitalRoot(n) + if (ia2[mdr][0] < 5) { + ia2[mdr][0]++ + ia2[mdr][ia2[mdr][0]] = n + count++ + } + n++ + } + while (count < 50) + + for (i in 0..9) { + print("$i:") + for (j in 1..5) print("%6d".format(ia2[i][j])) + println() + } +} diff --git a/Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-1.rexx b/Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-1.rexx index 727cedd81a..070fc6b7ee 100644 --- a/Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-1.rexx +++ b/Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-1.rexx @@ -1,28 +1,31 @@ -/*REXX pgm finds persistence and multiplicative digital root of some #'s*/ -numeric digits 100 /*increase the number of digits. */ -parse arg x /*get some numbers from the C.L. */ -if x='' then x=123321 7739 893 899998 /*use defaults if none specified.*/ -say center('number',8) ' persistence multiplicative digital root' -say copies('─' ,8) ' ─────────── ───────────────────────────' - /* [↑] title and separator. */ - do j=1 for words(x); n=word(x,j) /*process each number in the list*/ - parse value mdr(n) with mp mdr /*obtain the persistence and MDR.*/ - say right(n,8) center(mp,13) center(mdr,30) /*display #, mp, mdr.*/ - end /*j*/ /* [↑] show MP and MDR for each #*/ -say; target=5 +/*REXX program finds the persistence and multiplicative digital root of some numbers.*/ +numeric digits 100 /*increase the number of decimal digits*/ +parse arg x /*obtain optional arguments from the CL*/ +if x='' | x="," then x=123321 7739 893 899998 /*Not specified? Then use the default.*/ +say center('number', 8) ' persistence multiplicative digital root' +say copies('─' , 8) ' ─────────── ───────────────────────────' + /* [↑] the title and separator. */ + do j=1 for words(x); n=word(x, j) /*process each number in the X list.*/ + parse value MDR(n) with mp mdr /*obtain the persistence and the MDR. */ + say right(n,8) center(mp,13) center(mdr,30) /*display a number, persistence, MDR.*/ + end /*j*/ /* [↑] show MP & MDR for each number. */ +say; target=5 say 'MDR first ' target " numbers that have a matching MDR" say '═══ ═══════════════════════════════════════════════════' - do k=0 for 10; hits=0; _= /*show #'s that have an MDR of K.*/ - do m=k until hits==target /*find target #s with an MDR of K*/ - if word(mdr(m),2)\==k then iterate /*is the MDR what's wanted? */ - hits=hits+1; _=space(_ m',') /*yes, we got a hit, add to list.*/ - end /*m*/ /* [↑] built a list of MDRs = k */ - say " "k': ['strip(_,,',')"]" /*display the K (mdr) and list.*/ - end /*k*/ /* [↑] done with the K mdr list.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────MDR subroutine──────────────────────*/ -mdr: procedure; parse arg y; y=abs(y) /*get the number and find the MDR*/ - do p=1 until y<10 /*find multiplicative digRoot (Y)*/ - parse var y 1 r 2; do k=2 to length(y); r=r*substr(y,k,1); end; y=r - end /*p*/ /*wash, rinse, repeat ··· */ -return p r /*return the persistence and MDR.*/ + + do k=0 for 10; hits=0; _= /*show numbers that have an MDR of K. */ + do m=k until hits==target /*find target numbers with an MDR of K.*/ + if word( MDR(m), 2)\==k then iterate /*is this the MDR that's wanted? */ + hits=hits + 1; _=space(_ m',') /*yes, we got a hit, add to the list. */ + end /*m*/ /* [↑] built a list of MDRs that = K. */ + say " "k': ['strip(_, , ',')"]" /*display the K (MDR) and the list. */ + end /*k*/ /* [↑] done with the K MDR list. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +MDR: procedure; parse arg y; y=abs(y) /*get the number and determine the MDR.*/ + do p=1 until y<10; parse var y r 2 + do k=2 to length(y); r=r * substr(y, k, 1) + end /*k*/ + y=r + end /*p*/ /* [↑] wash, rinse, and repeat ··· */ + return p r /*return the persistence and the MDR. */ diff --git a/Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-2.rexx b/Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-2.rexx index 6f6a8f7a7a..8cac807329 100644 --- a/Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-2.rexx +++ b/Task/Digital-root-Multiplicative-digital-root/REXX/digital-root-multiplicative-digital-root-2.rexx @@ -1,72 +1,81 @@ -/*REXX pgm finds persistence and multiplicative digital root of some #'s*/ -numeric digits 2000 /*increase the number of digits. */ -parse arg target x; if \datatype(target,'W') then target=25 /*default?*/ -if x='' then x=123321 7739 893 899998 /*use the defaults for X ? */ +/*REXX program finds the persistence and multiplicative digital root of some numbers.*/ +numeric digits 2000 /*increase the number of decimal digits*/ +parse arg target x /*obtain optional arguments from the CL*/ +if \datatype(target, 'W') then target=25 /*Not specified? Then use the default.*/ +if x='' | x="," then x=123321 7739 893 899998 /* " " " " " " */ say center('number',8) ' persistence multiplicative digital root' say copies('─' ,8) ' ─────────── ───────────────────────────' - /* [↑] title and separator. */ - do j=1 for words(x); n=abs(word(x,j)) /*process each # in list.*/ - parse value mdr(n) with mp mdr /*obtain the persistence and MDR.*/ - say right(n,8) center(mp,13) center(mdr,30) /*display #, mp, mdr.*/ - end /*j*/ /* [↑] show MP and MDR for each #*/ -say /* [↓] show a blank & title line.*/ + /* [↑] the title and the separator. */ + do j=1 for words(x); n=abs( word(x, j) ) /*process each number in the list. */ + parse value MDR(n) with mp mdr /*obtain the persistence and the MDR. */ + say right(n,8) center(mp,13) center(mdr,30) /*display the number, persistence, MDR.*/ + end /*j*/ /* [↑] show MP and MDR for each number.*/ +say /* [↓] show a blank and the title line.*/ say 'MDR first ' target " numbers that have a matching MDR" -say '═══ ' copies("═",(target+(target+1)**2)%2) /*display a sep line.*/ +say '═══ ' copies("═",(target+(target+1)**2)%2) /*display a separator line (for title).*/ - do k=0 for 9; hits=0; _= /*show #'s that have an MDR of K.*/ - if k==7 then _=@7; else /*handle special seven case. */ + do k=0 for 9; hits=0 /*show numbers that have an MDR of K. */ + _= + if k==7 then _=@7 /*handle the special case of seven. */ + else do m=k until hits==target /*find target numbers with an MDR of K.*/ + parse var m '' -1 ? /*obtain the right─most digit of M. */ + if k\==0 then if ?==0 then iterate + if k==5 then if ?//2==0 then iterate + if k==1 then m=copies(1, hits+1) + else if MDR(m, 1)\==k then iterate + hits=hits+1 /*got a hit, add to the list*/ + _=space(_ m) /*elide superfluous blanks. */ + if k==3 then do; o=strip(m, 'T', 1) /*strip trailing ones from M*/ + if o==3 then m=copies(1, length(m))3 /*make a new M.*/ + else do; t=pos(3, m) - 1 /*position of 3 */ + m=overlay(3, translate(m, 1, 3), t) + end /* [↑] shift the "3" 1 place left.*/ + m=m - 1 /*adjust for DO index increment.*/ + end /* [↑] a shortcut to adj DO index*/ + end /*m*/ /* [↑] built a list of MDRs = K */ - do m=k until hits==target /*find target #s with an MDR of K*/ - ?=right(m,1) /*obtain right-most digit of M. */ - if k\==0 then if ?==0 then iterate - if k==5 then if ?//2==0 then iterate - if k==1 then m=copies(1,hits+1) - else if mdr(m,1)\==k then iterate - hits=hits+1; _=space(_ m) /*yes, we got a hit, add to list.*/ + say " "k': ['_"]" /*display the K (MDR) and the list. */ + if k==3 then @7=translate(_, 7, k) /*save for later, a special "7" case.*/ + end /*k*/ /* [↑] done with the K MDR list. */ - if k==3 then do; o=strip(m,'T',1) /*strip trailing ones*/ - if o==3 then m=copies(1,length(m))3 /*make new M. */ - else do; t=pos(3,m)-1 /*position of 3*/ - m=overlay(3,translate(m,1,3),t) - end /* [↑] shift the "3" 1 place left*/ - m=m-1 /*adjust for DO index advancement*/ - end /* [↑] a shortcut to do DO index*/ - end /*m*/ /* [↑] built a list of MDRs = k */ +@.= /* [↓] handle MDR of "9" special. */ +_=translate(@7, 9, 7) /*translate string for MDR of nine. */ +@9=translate(_, , ',') /*remove trailing commas from numbers. */ +@3= /*assign null string before building. */ - say " "k': ['_"]" /*display the K (mdr) and list.*/ - if k==3 then @7=translate(_,7,k) /*save for later, special 7 case.*/ - end /*k*/ /* [↑] done with the K mdr list.*/ -@.= /* [↓] handle MDR of 9 special. */ -_=translate(@7,9,7) /*translate a string for MDR 9. */ -@9=translate(_,,',') /*remove trailing commas from #'s*/ -@3= /*assine null string before build*/ - do j=1 for words(@9) /*process each number for MDR 9. */ - _=space(translate(word(@9,j),,9),0) /*remove "9"s using SPACE(x,0)*/ - L=length(_)+1 /*use a "fudged" length of the #.*/ - new= /*this is the new numbers so far.*/ - do k=0 for L; q=insert(3,_,k) /*insert the 1st "3" into the #*/ - do i=k to L; z=insert(3,q,i) /* " " 2nd "3" " " "*/ - if @.z\=='' then iterate /*if already define, ignore the #*/ - @.z=z; new=z new /*define it, and then add to list*/ - end /*i*/ /* [↑] end of 2nd insertion of 3*/ - end /*k*/ /* [↑] " " 1st " " "*/ - @3=space(@3 new) /*remove blanks, then add to list*/ - end /*j*/ /* [↑] end of insertion of "3"s.*/ + do j=1 for words(@9) /*process each number for MDR 9 case.*/ + _=space( translate( word(@9, j), , 9), 0) /*elide all "9"s using SPACE(x,0).*/ + L=length(_) + 1 /*use a "fudged" length of the number. */ + new= /*these are the new numbers (so far). */ -a1=@9; a2=@3; @= /*define three strings for merge.*/ - /* [↓] merge two lists, 3s & 9s.*/ - do while a1\=='' & a2\=='' /*process while the lists ¬empty.*/ - x=word(a1,1); y=word(a2,1); if x=='' | y=='' then leave /*empty?*/ - if x= 10) { - mdr = mdr.digits.product + mdr = mdr.digits.prod ++persist } [mdr, persist] } say "Number: MDR MP\n====== === ==" -[123321, 7739, 893, 899998].each{|n| "%6d: %3d %3d\n" \ +[123321, 7739, 893, 899998].each{|n| "%6d: %3d %3d\n" \ .printf(n, mdroot(n)...) } var counter = Hash() -Inf.times { |i| - var j = i-1 - counter{mdroot(j).first} := [] << j +Inf.times { |j| + counter{mdroot(j).first} := [] << j break if counter.values.all {|v| v.len >= 5 } } - +  say "\nMDR: [n0..n4]\n=== ========" -10.times {|i| "%3d: %s\n".printf(i-1, counter{i-1}.first(5)) } +10.times {|i| "%3d: %s\n".printf(i, counter{i}.first(5)) } diff --git a/Task/Digital-root-Multiplicative-digital-root/Zkl/digital-root-multiplicative-digital-root-1.zkl b/Task/Digital-root-Multiplicative-digital-root/Zkl/digital-root-multiplicative-digital-root-1.zkl new file mode 100644 index 0000000000..135af91532 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Zkl/digital-root-multiplicative-digital-root-1.zkl @@ -0,0 +1,7 @@ +fcn mdroot(n){ // Multiplicative digital root + mdr := List(n); + while (mdr[-1] > 9){ + mdr.append(mdr[-1].split().reduce('*,1)); + } + return(mdr.len() - 1, mdr[-1]); +} diff --git a/Task/Digital-root-Multiplicative-digital-root/Zkl/digital-root-multiplicative-digital-root-2.zkl b/Task/Digital-root-Multiplicative-digital-root/Zkl/digital-root-multiplicative-digital-root-2.zkl new file mode 100644 index 0000000000..1af189675f --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Zkl/digital-root-multiplicative-digital-root-2.zkl @@ -0,0 +1,14 @@ +fcn mdroot(n){ + count:=0; mdr:=n; + while(mdr > 9){ + m:=mdr; digitsMul:=1; + while(m){ + reg md; + m,md=m.divr(10); + digitsMul *= md; + } + mdr = digitsMul; + count += 1; + } + return(count, mdr); +} diff --git a/Task/Digital-root-Multiplicative-digital-root/Zkl/digital-root-multiplicative-digital-root-3.zkl b/Task/Digital-root-Multiplicative-digital-root/Zkl/digital-root-multiplicative-digital-root-3.zkl new file mode 100644 index 0000000000..fe909650f1 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Zkl/digital-root-multiplicative-digital-root-3.zkl @@ -0,0 +1,15 @@ +println("Number: (MP, MDR)\n======= ========="); +foreach n in (T(123321, 7739, 893, 899998)) + { println("%7,d: %s".fmt(n, mdroot(n))) } + +table:=D([0..9].zip(fcn{List()}).walk()); // dictionary(0:List, 1:List, ...) +n :=0; +while(table.values.filter(fcn(r){r.len()<5})){ // until each entry has >=5 values + mpersistence, mdr := mdroot(n); + table[mdr].append(n); + n += 1; +} +println("\nMP: [n0..n4]\n== ========"); +foreach mp in (table.keys.sort()){ + println("%2d: %s".fmt(mp, table[mp][0,5])); //print first five values +} diff --git a/Task/Digital-root/360-Assembly/digital-root.360 b/Task/Digital-root/360-Assembly/digital-root.360 new file mode 100644 index 0000000000..6d1618a0e8 --- /dev/null +++ b/Task/Digital-root/360-Assembly/digital-root.360 @@ -0,0 +1,46 @@ +* Digital root 21/04/2017 +DIGROOT CSECT + USING DIGROOT,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + LA R6,1 i=1 + DO WHILE=(C,R6,LE,=A((PG-T)/4)) do i=1 to hbound(t) + LR R1,R6 i + SLA R1,2 *4 + L R10,T-4(R1) nn=t(i) + LR R7,R10 n=nn + SR R9,R9 ap=0 + DO WHILE=(C,R7,GE,=A(10)) do while(n>=10) + SR R8,R8 x=0 + DO WHILE=(C,R7,GE,=A(10)) do while(n>=10) + LR R4,R7 n + SRDA R4,32 >>r5 + D R4,=A(10) m=n//10 + LR R7,R5 n=n/10 + AR R8,R4 x=x+m + ENDDO , end + AR R7,R8 n=x+n + LA R9,1(R9) ap=ap+1 + ENDDO , end + XDECO R10,XDEC nn + MVC PG+7(10),XDEC+2 + XDECO R9,XDEC ap + MVC PG+31(3),XDEC+9 + XDECO R7,XDEC n + MVC PG+41(1),XDEC+11 + XPRNT PG,L'PG print + LA R6,1(R6) i++ + ENDDO , enddo i + L R13,4(0,R13) restore previous savearea pointer + LM R14,R12,12(R13) restore previous context + XR R15,R15 rc=0 + BR R14 exit +T DC F'627615',F'39390',F'588225',F'2147483647' +PG DC CL80'number=xxxxxxxxxx persistence=xxx root=x' +XDEC DS CL12 + YREGS + END DIGROOT diff --git a/Task/Digital-root/Component-Pascal/digital-root.component b/Task/Digital-root/Component-Pascal/digital-root.component new file mode 100644 index 0000000000..5724c1513f --- /dev/null +++ b/Task/Digital-root/Component-Pascal/digital-root.component @@ -0,0 +1,40 @@ +MODULE DigitalRoot; +IMPORT StdLog, Strings, TextMappers, DevCommanders; + +PROCEDURE CalcDigitalRoot(x: LONGINT; OUT dr,pers: LONGINT); +VAR + str: ARRAY 64 OF CHAR; + i: INTEGER; +BEGIN + dr := 0;pers := 0; + LOOP + Strings.IntToString(x,str); + IF LEN(str$) = 1 THEN dr := x ;EXIT END; + i := 0;dr := 0; + WHILE (i < LEN(str$)) DO + INC(dr,ORD(str[i]) - ORD('0')); + INC(i) + END; + INC(pers); + x := dr + END; +END CalcDigitalRoot; + +PROCEDURE Do*; +VAR + dr,pers: LONGINT; + s: TextMappers.Scanner; +BEGIN + s.ConnectTo(DevCommanders.par.text); + s.SetPos(DevCommanders.par.beg); + REPEAT + s.Scan; + IF (s.type = TextMappers.int) OR (s.type = TextMappers.lint) THEN + CalcDigitalRoot(s.int,dr,pers); + StdLog.Int(s.int); + StdLog.String(" Digital root: ");StdLog.Int(dr); + StdLog.String(" Persistence: ");StdLog.Int(pers);StdLog.Ln + END + UNTIL s.rider.eot; +END Do; +END DigitalRoot. diff --git a/Task/Digital-root/Haskell/digital-root-1.hs b/Task/Digital-root/Haskell/digital-root-1.hs index dff616585c..9ae443641f 100644 --- a/Task/Digital-root/Haskell/digital-root-1.hs +++ b/Task/Digital-root/Haskell/digital-root-1.hs @@ -1,11 +1,17 @@ +import Data.Tuple (swap) import Data.List (unfoldr) -digSum base = sum . unfoldr f where - f 0 = Nothing - f n = Just (r,q) where (q,r) = n `divMod` base +digSum :: Int -> Int -> Int +digSum base = sum . unfoldr f + where + f 0 = Nothing + f n = Just (swap (quotRem n base)) -digRoot base = head . dropWhile ((>= base).snd) . zip [0..] . iterate (digSum base) +digRoot :: Int -> Int -> (Int, Int) +digRoot base = + head . dropWhile ((>= base) . snd) . zip [0 ..] . iterate (digSum base) -main = do - putStrLn "in base 10:" - mapM_ print $ map (\x -> (x, digRoot 10 x)) [627615, 39390, 588225, 393900588225] +main :: IO () +main = do + putStrLn "in base 10:" + mapM_ (print . ((,) <*> digRoot 10)) [627615, 39390, 588225, 393900588225] diff --git a/Task/Digital-root/Haskell/digital-root-2.hs b/Task/Digital-root/Haskell/digital-root-2.hs index 319ebab156..ea5b70c3e8 100644 --- a/Task/Digital-root/Haskell/digital-root-2.hs +++ b/Task/Digital-root/Haskell/digital-root-2.hs @@ -1,51 +1,63 @@ -import Data.List (elemIndex, unfoldr) +import Data.Tuple (swap) import Data.Maybe (fromJust) +import Data.List (elemIndex, unfoldr) import Numeric (readInt, showIntAtBase) -- Return a pair consisting of the additive persistence and digital root of a -- base b number. digRoot :: Integer -> Integer -> (Integer, Integer) -digRoot b = find . zip [0..] . iterate (sum . toDigits b) - where find = head . dropWhile ((>= b) . snd) +digRoot b = find . zip [0 ..] . iterate (sum . toDigits b) + where + find = head . dropWhile ((>= b) . snd) -- Print the additive persistence and digital root of a base b number (given as -- a string). printDigRoot :: Integer -> String -> IO () printDigRoot b s = do let (p, r) = digRoot b $ strToInt b s - putStrLn $ s ++ ": additive persistence " ++ show p ++ - ", digital root " ++ intToStr b r + (putStrLn . unwords) + [s, "-> additive persistence:", show p, "digital root:", intToStr b r] -- -- Utility methods for dealing with numbers in different bases. -- - -- Convert a base b number to a list of digits, from least to most significant. -toDigits :: Integral a => a -> a -> [a] +toDigits + :: Integral a + => a -> a -> [a] toDigits b = unfoldr f - where f 0 = Nothing - f n = Just (r,q) where (q,r) = n `quotRem` b + where + f 0 = Nothing + f n = Just (swap (quotRem n b)) -- A list of digits, for bases up to 36. digits :: String -digits = ['0'..'9'] ++ ['A'..'Z'] +digits = ['0' .. '9'] ++ ['A' .. 'Z'] -- Return a number's base b string representation. -intToStr :: (Integral a, Show a) => a -> a -> String -intToStr b n | b < 2 || b > 36 = error "intToStr: base must be in [2..36]" - | otherwise = showIntAtBase b (digits !!) n "" +intToStr + :: (Integral a, Show a) + => a -> a -> String +intToStr b n + | b < 2 || b > 36 = error "intToStr: base must be in [2..36]" + | otherwise = showIntAtBase b (digits !!) n "" -- Return the number for the base b string representation. -strToInt :: Integral a => a -> String -> a -strToInt b = fst . head . readInt b (`elem` digits) - (fromJust . (`elemIndex` digits)) +strToInt + :: Integral a + => a -> String -> a +strToInt b = + fst . head . readInt b (`elem` digits) (fromJust . (`elemIndex` digits)) main :: IO () -main = do - printDigRoot 2 "1001100111011110" - printDigRoot 3 "2000000220" - printDigRoot 8 "5566623376301" - printDigRoot 10 "39390" - printDigRoot 16 "99DE" - printDigRoot 36 "50YE8N29" - printDigRoot 36 "37C71GOYNYJ25M3JTQQVR0FXUK0W9QM71C1LVN" +main = + mapM_ + (uncurry printDigRoot) + [ (2, "1001100111011110") + , (3, "2000000220") + , (8, "5566623376301") + , (10, "39390") + , (16, "99DE") + , (36, "50YE8N29") + , (36, "37C71GOYNYJ25M3JTQQVR0FXUK0W9QM71C1LVN") + ] diff --git a/Task/Digital-root/jq/digital-root-1.jq b/Task/Digital-root/Jq/digital-root-1.jq similarity index 100% rename from Task/Digital-root/jq/digital-root-1.jq rename to Task/Digital-root/Jq/digital-root-1.jq diff --git a/Task/Digital-root/jq/digital-root-2.jq b/Task/Digital-root/Jq/digital-root-2.jq similarity index 100% rename from Task/Digital-root/jq/digital-root-2.jq rename to Task/Digital-root/Jq/digital-root-2.jq diff --git a/Task/Digital-root/jq/digital-root-3.jq b/Task/Digital-root/Jq/digital-root-3.jq similarity index 100% rename from Task/Digital-root/jq/digital-root-3.jq rename to Task/Digital-root/Jq/digital-root-3.jq diff --git a/Task/Digital-root/Kotlin/digital-root.kotlin b/Task/Digital-root/Kotlin/digital-root.kotlin new file mode 100644 index 0000000000..42dc6c8a56 --- /dev/null +++ b/Task/Digital-root/Kotlin/digital-root.kotlin @@ -0,0 +1,36 @@ +// version 1.0.6 + +fun sumDigits(n: Long): Int = when { + n < 0L -> throw IllegalArgumentException("Negative numbers not allowed") + else -> { + var sum = 0 + var nn = n + while (nn > 0L) { + sum += (nn % 10).toInt() + nn /= 10 + } + sum + } + } + +fun digitalRoot(n: Long): Pair = when { + n < 0L -> throw IllegalArgumentException("Negative numbers not allowed") + n < 10L -> Pair(n.toInt(), 0) + else -> { + var dr = n + var ap = 0 + while (dr > 9L) { + dr = sumDigits(dr).toLong() + ap++ + } + Pair(dr.toInt(), ap) + } + } + +fun main(args: Array) { + val a = longArrayOf(1, 14, 267, 8128, 627615, 39390, 588225, 393900588225) + for (n in a) { + val(dr, ap) = digitalRoot(n) + println("${n.toString().padEnd(12)} has additive persistence $ap and digital root of $dr") + } +} diff --git a/Task/Digital-root/Phix/digital-root.phix b/Task/Digital-root/Phix/digital-root.phix new file mode 100644 index 0000000000..09dcf7e2e9 --- /dev/null +++ b/Task/Digital-root/Phix/digital-root.phix @@ -0,0 +1,20 @@ +procedure digital_root(atom n, integer base=10) +integer root, persistence = 1 +atom work = n + while 1 do + root = 0 + while work!=0 do + root += remainder(work,base) + work = floor(work/base) + end while + if root(digital root, additive persistence) + { if(n Cooper # Miller lives on a higher floor than does Cooper + stmt6 = abs(Smith-Fletcher) != 1 # Smith does not live on a floor adjacent to Fletcher's + stmt7 = abs(Fletcher-Cooper) != 1 # Fletcher does not live on a floor adjacent to Cooper's + return(stmt1 stmt2 stmt3 stmt4 stmt5 stmt6 stmt7) +} +function abs(x) { if (x >= 0) { return x } else { return -x } } diff --git a/Task/Dinesmans-multiple-dwelling-problem/C/dinesmans-multiple-dwelling-problem-1.c b/Task/Dinesmans-multiple-dwelling-problem/C/dinesmans-multiple-dwelling-problem-1.c deleted file mode 100644 index 66917bcff2..0000000000 --- a/Task/Dinesmans-multiple-dwelling-problem/C/dinesmans-multiple-dwelling-problem-1.c +++ /dev/null @@ -1,81 +0,0 @@ -#include -#include - -int verbose = 0; -#define COND(a, b) int a(int *s) { return (b); } -typedef int(*condition)(int *); - -/* BEGIN problem specific setup */ -#define N_FLOORS 5 -#define TOP (N_FLOORS - 1) -int solution[N_FLOORS] = { 0 }; -int occupied[N_FLOORS] = { 0 }; - -enum tenants { - baker = 0, - cooper, - fletcher, - miller, - smith, - phantom_of_the_opera, -}; - -const char *names[] = { - "baker", - "cooper", - "fletcher", - "miller", - "smith", -}; - -COND(c0, s[baker] != TOP); -COND(c1, s[cooper] != 0); -COND(c2, s[fletcher] != 0 && s[fletcher] != TOP); -COND(c3, s[miller] > s[cooper]); -COND(c4, abs(s[smith] - s[fletcher]) != 1); -COND(c5, abs(s[cooper] - s[fletcher]) != 1); -#define N_CONDITIONS 6 - -condition cond[] = { c0, c1, c2, c3, c4, c5 }; - -/* END of problem specific setup */ - - -int solve(int person) -{ - int i, j; - if (person == phantom_of_the_opera) { - /* check condition */ - for (i = 0; i < N_CONDITIONS; i++) { - if (cond[i](solution)) continue; - - if (verbose) { - for (j = 0; j < N_FLOORS; j++) - printf("%d %s\n", solution[j], names[j]); - printf("cond %d bad\n\n", i); - } - return 0; - } - - printf("Found arrangement:\n"); - for (i = 0; i < N_FLOORS; i++) - printf("%d %s\n", solution[i], names[i]); - return 1; - } - - for (i = 0; i < N_FLOORS; i++) { - if (occupied[i]) continue; - solution[person] = i; - occupied[i] = 1; - if (solve(person + 1)) return 1; - occupied[i] = 0; - } - return 0; -} - -int main() -{ - verbose = 0; - if (!solve(0)) printf("Nobody lives anywhere\n"); - return 0; -} diff --git a/Task/Dinesmans-multiple-dwelling-problem/C/dinesmans-multiple-dwelling-problem-2.c b/Task/Dinesmans-multiple-dwelling-problem/C/dinesmans-multiple-dwelling-problem-2.c deleted file mode 100644 index 2026e0e224..0000000000 --- a/Task/Dinesmans-multiple-dwelling-problem/C/dinesmans-multiple-dwelling-problem-2.c +++ /dev/null @@ -1,6 +0,0 @@ -Found arrangement: -2 baker -1 cooper -3 fletcher -4 miller -0 smith diff --git a/Task/Dinesmans-multiple-dwelling-problem/Java/dinesmans-multiple-dwelling-problem.java b/Task/Dinesmans-multiple-dwelling-problem/Java/dinesmans-multiple-dwelling-problem.java index 29e8dc8242..039f4f8843 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/Java/dinesmans-multiple-dwelling-problem.java +++ b/Task/Dinesmans-multiple-dwelling-problem/Java/dinesmans-multiple-dwelling-problem.java @@ -1,64 +1,86 @@ import java.util.*; -class DinesmanMultipleDwelling -{ - private static void generatePermutations(String[] apartmentDwellers, Set set, String curPermutation) - { - for (String s : apartmentDwellers) - { - if (!curPermutation.contains(s)) - { - String nextPermutation = curPermutation + s; - if (nextPermutation.length() == apartmentDwellers.length) - set.add(nextPermutation); - else - generatePermutations(apartmentDwellers, set, nextPermutation); - } +class DinesmanMultipleDwelling { + + private static void generatePermutations(String[] apartmentDwellers, Set set, String curPermutation) { + for (String s : apartmentDwellers) { + if (!curPermutation.contains(s)) { + String nextPermutation = curPermutation + s; + if (nextPermutation.length() == apartmentDwellers.length) { + set.add(nextPermutation); + } else { + generatePermutations(apartmentDwellers, set, nextPermutation); + } + } + } } - return; - } - private static boolean topFloor(String permutation, String person) - { return permutation.endsWith(person); } - - private static boolean bottomFloor(String permutation, String person) - { return permutation.startsWith(person); } - - public static boolean livesAbove(String permutation, String upperPerson, String lowerPerson) - { return permutation.indexOf(upperPerson) > permutation.indexOf(lowerPerson); } - - public static boolean adjacent(String permutation, String person1, String person2) - { return (Math.abs(permutation.indexOf(person1) - permutation.indexOf(person2)) == 1); } - - private static boolean isPossible(String s) - { - // Conditions here - if (topFloor(s, "B")) - return false; - if (bottomFloor(s, "C")) - return false; - if (topFloor(s, "F") || bottomFloor(s, "F")) - return false; - if (!livesAbove(s, "M", "C")) - return false; - if (adjacent(s, "S", "F")) - return false; - if (adjacent(s, "F", "C")) - return false; - return true; - } - - public static void main(String[] args) - { - Set set = new HashSet(); - generatePermutations(new String[] { "B", "C", "F", "M", "S" }, set, ""); - for (Iterator iterator = set.iterator(); iterator.hasNext(); ) - { - String permutation = iterator.next(); - if (!isPossible(permutation)) - iterator.remove(); + private static boolean topFloor(String permutation, String person) { //Checks to see if the person is on the top floor + return permutation.endsWith(person); + } + + private static boolean bottomFloor(String permutation, String person) {//Checks to see if the person is on the bottom floor + return permutation.startsWith(person); + } + + public static boolean livesAbove(String permutation, String upperPerson, String lowerPerson) {//Checks to see if the person lives above the other person + return permutation.indexOf(upperPerson) > permutation.indexOf(lowerPerson); + } + + public static boolean adjacent(String permutation, String person1, String person2) { //checks to see if person1 is adjacent to person2 + return (Math.abs(permutation.indexOf(person1) - permutation.indexOf(person2)) == 1); + } + + private static boolean isPossible(String s) { + /* + What this does should be obvious...proper explaination can be given if needed + Conditions here Switching any of these to ! or reverse will change what is given as a result + + example + if(topFloor(s, "B"){ + } + to + if(!topFloor(s, "B"){ + } + or the opposite + if(!topFloor(s, "B"){ + } + to + if(topFloor(s, "B"){ + } + */ + if (topFloor(s, "B")) {//B is on Top Floor + return false; + } + if (bottomFloor(s, "C")) {//C is on Bottom Floor + return false; + } + if (topFloor(s, "F") || bottomFloor(s, "F")) {// F is on top or bottom floor + return false; + } + if (!livesAbove(s, "M", "C")) {// M does not live above C + return false; + } + if (adjacent(s, "S", "F")) { //S lives adjacent to F + return false; + } + return !adjacent(s, "F", "C"); //F does not live adjacent to C + } + + public static void main(String[] args) { + Set set = new HashSet(); + generatePermutations(new String[]{"B", "C", "F", "M", "S"}, set, ""); //Generates Permutations + for (Iterator iterator = set.iterator(); iterator.hasNext();) {//Loops through iterator + String permutation = iterator.next(); + if (!isPossible(permutation)) {//checks to see if permutation is false if so it removes it + iterator.remove(); + } + } + for (String s : set) { + System.out.println("Possible arrangement: " + s); + /* + Prints out possible arranagement...changes depending on what you change in the "isPossible method" + */ + } } - for (String s : set) - System.out.println("Possible arrangement: " + s); - } } diff --git a/Task/Dinesmans-multiple-dwelling-problem/jq/dinesmans-multiple-dwelling-problem-1.jq b/Task/Dinesmans-multiple-dwelling-problem/Jq/dinesmans-multiple-dwelling-problem-1.jq similarity index 100% rename from Task/Dinesmans-multiple-dwelling-problem/jq/dinesmans-multiple-dwelling-problem-1.jq rename to Task/Dinesmans-multiple-dwelling-problem/Jq/dinesmans-multiple-dwelling-problem-1.jq diff --git a/Task/Dinesmans-multiple-dwelling-problem/jq/dinesmans-multiple-dwelling-problem-2.jq b/Task/Dinesmans-multiple-dwelling-problem/Jq/dinesmans-multiple-dwelling-problem-2.jq similarity index 100% rename from Task/Dinesmans-multiple-dwelling-problem/jq/dinesmans-multiple-dwelling-problem-2.jq rename to Task/Dinesmans-multiple-dwelling-problem/Jq/dinesmans-multiple-dwelling-problem-2.jq diff --git a/Task/Dinesmans-multiple-dwelling-problem/jq/dinesmans-multiple-dwelling-problem-3.jq b/Task/Dinesmans-multiple-dwelling-problem/Jq/dinesmans-multiple-dwelling-problem-3.jq similarity index 100% rename from Task/Dinesmans-multiple-dwelling-problem/jq/dinesmans-multiple-dwelling-problem-3.jq rename to Task/Dinesmans-multiple-dwelling-problem/Jq/dinesmans-multiple-dwelling-problem-3.jq diff --git a/Task/Dinesmans-multiple-dwelling-problem/Kotlin/dinesmans-multiple-dwelling-problem.kotlin b/Task/Dinesmans-multiple-dwelling-problem/Kotlin/dinesmans-multiple-dwelling-problem.kotlin new file mode 100644 index 0000000000..aad289adcc --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Kotlin/dinesmans-multiple-dwelling-problem.kotlin @@ -0,0 +1,50 @@ +// version 1.1.3 + +typealias Predicate = (List) -> Boolean + +fun permute(input: List): List> { + if (input.size == 1) return listOf(input) + val perms = mutableListOf>() + val toInsert = input[0] + for (perm in permute(input.drop(1))) { + for (i in 0..perm.size) { + val newPerm = perm.toMutableList() + newPerm.add(i, toInsert) + perms.add(newPerm) + } + } + return perms +} + +/* looks for for all possible solutions, not just the first */ +fun dinesman(occupants: List, predicates: List) = + permute(occupants).filter { perm -> predicates.all { pred -> pred(perm) } } + +fun main(args: Array) { + val occupants = listOf("Baker", "Cooper", "Fletcher", "Miller", "Smith") + + val predicates = listOf( + { it.last() != "Baker" }, + { it.first() != "Cooper" }, + { it.last() != "Fletcher" && it.first() != "Fletcher" }, + { it.indexOf("Miller") > it.indexOf("Cooper") }, + { Math.abs(it.indexOf("Smith") - it.indexOf("Fletcher")) > 1 }, + { Math.abs(it.indexOf("Fletcher") - it.indexOf("Cooper")) > 1 } + ) + + val solutions = dinesman(occupants, predicates) + val size = solutions.size + if (size == 0) { + println("No solutions found") + } + else { + val plural = if (size == 1) "" else "s" + println("$size solution$plural found, namely:\n") + for (solution in solutions) { + for ((i, name) in solution.withIndex()) { + println("Floor ${i + 1} -> $name") + } + println() + } + } +} diff --git a/Task/Dinesmans-multiple-dwelling-problem/Phix/dinesmans-multiple-dwelling-problem-1.phix b/Task/Dinesmans-multiple-dwelling-problem/Phix/dinesmans-multiple-dwelling-problem-1.phix new file mode 100644 index 0000000000..3ddb2f2b5b --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Phix/dinesmans-multiple-dwelling-problem-1.phix @@ -0,0 +1,19 @@ +enum Baker, Cooper, Fletcher, Miller, Smith +constant names={"Baker","Cooper","Fletcher","Miller","Smith"} + +procedure test(sequence flats) + if flats[Baker]!=5 + and flats[Cooper]!=1 + and not find(flats[Fletcher],{1,5}) + and flats[Miller]>flats[Cooper] + and abs(flats[Smith]-flats[Fletcher])!=1 + and abs(flats[Fletcher]-flats[Cooper])!=1 then + for i=1 to 5 do + ?{names[i],flats[i]} + end for + end if +end procedure + +for i=1 to factorial(5) do + test(permute(i,tagset(5))) +end for diff --git a/Task/Dinesmans-multiple-dwelling-problem/Phix/dinesmans-multiple-dwelling-problem-2.phix b/Task/Dinesmans-multiple-dwelling-problem/Phix/dinesmans-multiple-dwelling-problem-2.phix new file mode 100644 index 0000000000..22238c14b3 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Phix/dinesmans-multiple-dwelling-problem-2.phix @@ -0,0 +1,44 @@ +sequence names = {"Baker","Cooper","Fletcher","Miller","Smith"}, + rules = {{"!=","Baker",length(names)}, + {"!=","Cooper",1}, + {"!=","Fletcher",1}, + {"!=","Fletcher",length(names)}, + {">","Miller","Cooper"}, +-- {"!=",{"abs","Smith","Fletcher"},1}, + {"nadj","Smith","Fletcher"}, +-- {"!=",{"abs","Fletcher","Cooper"},1}, + {"nadj","Fletcher","Cooper"}} + +function eval(sequence rule, sequence flats) + {string operand, object op1, object op2} = rule + if string(op1) then + op1 = flats[find(op1,names)] +-- elsif sequence(op1) then +-- op1 = eval(op1,flats) + end if + if string(op2) then + op2 = flats[find(op2,names)] +-- elsif sequence(op2) then +-- op2 = eval(op2,flats) + end if + switch operand do + case "!=": return op1!=op2 + case ">": return op1>op2 +-- case "abs": return abs(op1-op2) + case "nadj": return abs(op1-op2)!=1 + end switch + return 9/0 +end function + +procedure test(sequence flats) + for i=1 to length(rules) do + if not eval(rules[i],flats) then return end if + end for + for i=1 to length(names) do + ?{names[i],flats[i]} + end for +end procedure + +for i=1 to factorial(length(names)) do + test(permute(i,tagset(length(names)))) +end for diff --git a/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-1.sidef b/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-1.sidef index 4d8c94a753..e17edbb94c 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-1.sidef +++ b/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-1.sidef @@ -1,18 +1,18 @@ func dinesman(problem) { - var lines = problem.split('.'); - var names = lines.first.scan(/\b[A-Z]\w*/); - var re_names = Regex(names.join('|')); - + var lines = problem.split('.') + var names = lines.first.scan(/\b[A-Z]\w*/) + var re_names = Regex(names.join('|')) +  # Later on, search for these keywords (the word "not" is handled separately). var words = %w(first second third fourth fifth sixth seventh eighth ninth tenth - bottom top higher lower adjacent); - var re_keywords = Regex(words.join('|')); - + bottom top higher lower adjacent) + var re_keywords = Regex(words.join('|')) +  # Build an array of lambda's var predicates = lines.ft(1, lines.end-1).map{ |line| - var keywords = line.scan(re_keywords); - var (name1, name2) = line.scan(re_names)...; - + var keywords = line.scan(re_keywords) + var (name1, name2) = line.scan(re_names)... +  keywords.map{ |keyword| var l = do { given(keyword) { @@ -24,11 +24,11 @@ func dinesman(problem) { default { ->(c) { c[words.index(keyword)] == name1 } } } } - line ~~ /\bnot\b/ ? func(c) { l(c) -> not } : l; # handle "not" + line ~~ /\bnot\b/ ? func(c) { l(c) -> not } : l; # handle "not" } - }.flatten; - - names.permutations { |candidate| - predicates.all { |predicate| predicate(candidate) } && return candidate; + }.flat +  + names.permutations { |*candidate| + predicates.all { |predicate| predicate(candidate) } && return candidate } } diff --git a/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-2.sidef b/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-2.sidef index 93c1c2edaf..704df91902 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-2.sidef +++ b/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-2.sidef @@ -19,4 +19,4 @@ floor than does Cooper. Smith does not live on a floor adjacent to Fletcher's. Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live?" -[demo1, demo2, problem1, problem2].each{|problem| say dinesman(problem).join("\n"); say '' }; +[demo1, demo2, problem1, problem2].each{|problem| say dinesman(problem).join("\n"); say '' } diff --git a/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-3.sidef b/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-3.sidef index f61d1a3d7f..fff0b96ca1 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-3.sidef +++ b/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-3.sidef @@ -1,15 +1,15 @@ var names = %w(Baker Cooper Fletcher Miller Smith) - +  var predicates = [ - ->(c){ :Baker != c.last }, - ->(c){ :Cooper != c.first }, - ->(c){ (:Fletcher != c.first) && (:Fletcher != c.last) }, + ->(c){ :Baker != c.last }, + ->(c){ :Cooper != c.first }, + ->(c){ (:Fletcher != c.first) && (:Fletcher != c.last) }, ->(c){ c.index(:Miller) > c.index(:Cooper) }, - ->(c){ (c.index(:Smith) - c.index(:Fletcher)).abs != 1 }, - ->(c){ (c.index(:Cooper) - c.index(:Fletcher)).abs != 1 }, + ->(c){ (c.index(:Smith) - c.index(:Fletcher)).abs != 1 }, + ->(c){ (c.index(:Cooper) - c.index(:Fletcher)).abs != 1 }, ] - -names.permutations { |candidate| +  +names.permutations { |*candidate| if (predicates.all {|predicate| predicate(candidate) }) { say candidate.join("\n") break diff --git a/Task/Dinesmans-multiple-dwelling-problem/Zkl/dinesmans-multiple-dwelling-problem.zkl b/Task/Dinesmans-multiple-dwelling-problem/Zkl/dinesmans-multiple-dwelling-problem.zkl new file mode 100644 index 0000000000..dbe0bd0d88 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Zkl/dinesmans-multiple-dwelling-problem.zkl @@ -0,0 +1,20 @@ +var Baker, Cooper, Fletcher, Miller, Smith; // value == floor +const bottom=1,top=5; // floors: 1..5 +// All live on different floors, enforced by using permutations of floors +//fcn c0{ (Baker!=Cooper!=Fletcher) and (Fletcher!=Miller!=Smith) } +fcn c1{ Baker!=top } +fcn c2{ Cooper!=bottom } +fcn c3{ bottom!=Fletcher!=top } +fcn c4{ Miller>Cooper } +fcn c5{ (Fletcher - Smith).abs() !=1 } +fcn c6{ (Fletcher - Cooper).abs()!=1 } + +filters:=T(c1,c2,c3,c4,c5,c6); +dudes:=T("Baker","Cooper","Fletcher","Miller","Smith"); // for reflection +foreach combo in (Utils.Helpers.permuteW([bottom..top].walk())){ // lazy + dudes.zip(combo).apply2(fcn(nameValue){ setVar(nameValue.xplode()) }); + if(not filters.runNFilter(False)){ // all constraints are True + vars.println(); // use reflection to print solution + break; + } +} diff --git a/Task/Dining-philosophers/Zkl/dining-philosophers-1.zkl b/Task/Dining-philosophers/Zkl/dining-philosophers-1.zkl new file mode 100644 index 0000000000..857a4a9a8f --- /dev/null +++ b/Task/Dining-philosophers/Zkl/dining-philosophers-1.zkl @@ -0,0 +1,26 @@ +var [const] forks=(5).pump(List,Atomic.Bool.fp(False)), // True==fork in use + seats=(5).pump(List,'wrap(n){ List(forks[n],forks[(n+1)%5]) }); +fcn sitAndEat(name,n){ // assigned seating + while(1){ + fa,fb:=seats[n].shuffle(); // ambidextrous + if(fa.setIf(True,False)){ // got the first fork + if(fb.setIf(True,False)){ // got the other fork, nom nom time + name.println(" is eating"); + Atomic.sleep((1).random(5)); + fa.set(False); fb.set(False); // put forks down + return(); // leave the table + } + else{ + fa.set(False); // put fork down, try again in a bit + name.println(": Could not get two forks"); + } + } else name.println(": Could not get first fork"); + Atomic.sleep((1).random(2)); // sits for a bit + } +} +fcn philo([(seat,name)]){ // a thread + while(1){ // eat and think forever + name.println(" is thinking."); Atomic.sleep((1).random(5)); + sitAndEat(name,seat); + } +} diff --git a/Task/Dining-philosophers/Zkl/dining-philosophers-2.zkl b/Task/Dining-philosophers/Zkl/dining-philosophers-2.zkl new file mode 100644 index 0000000000..2e9bb2f832 --- /dev/null +++ b/Task/Dining-philosophers/Zkl/dining-philosophers-2.zkl @@ -0,0 +1,4 @@ +T("Aristotle", "Kant", "Spinoza", "Marx", "Russell").enumerate() +.apply(philo.launch); + +Atomic.sleep(100000); // hang out in the REPL, aka thread keep alive diff --git a/Task/Discordian-date/JavaScript/discordian-date-1.js b/Task/Discordian-date/JavaScript/discordian-date-1.js index 606c75e319..bb5ff1b867 100644 --- a/Task/Discordian-date/JavaScript/discordian-date-1.js +++ b/Task/Discordian-date/JavaScript/discordian-date-1.js @@ -1,72 +1,118 @@ /** * All Hail Discordia! - this script prints Discordian date using system date. - * author: jklu, lang: JavaScript + * + * lang: JavaScript + * author: jklu + * contributors: JamesMcGuigan + * + * changelog: + * - Modified to return same output syntax as unix ddate + module.exports - James McGuigan, 2/Chaos/3183 + * + * source: https://rosettacode.org/wiki/Discordian_date#JavaScript */ -var seasons = ["Chaos", "Discord", "Confusion", - "Bureaucracy", "The Aftermath"]; -var weekday = ["Sweetmorn", "Boomtime", "Pungenday", - "Prickle-Prickle", "Setting Orange"]; +var seasons = [ + "Chaos", "Discord", "Confusion", + "Bureaucracy", "The Aftermath" +]; +var weekday = [ + "Sweetmorn", "Boomtime", "Pungenday", + "Prickle-Prickle", "Setting Orange" +]; -var apostle = ["Mungday", "Mojoday", "Syaday", - "Zaraday", "Maladay"]; +var apostle = [ + "Mungday", "Mojoday", "Syaday", + "Zaraday", "Maladay" +]; -var holiday = ["Chaoflux", "Discoflux", "Confuflux", - "Bureflux", "Afflux"]; +var holiday = [ + "Chaoflux", "Discoflux", "Confuflux", + "Bureflux", "Afflux" +]; Date.prototype.isLeapYear = function() { var year = this.getFullYear(); - if ((year & 3) !== 0) return false; + if( (year & 3) !== 0 ) { return false; } return ((year % 100) !== 0 || (year % 400) === 0); }; // Get Day of Year Date.prototype.getDOY = function() { - var dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; - var mn = this.getMonth(); - var dn = this.getDate(); + var dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; + var mn = this.getMonth(); + var dn = this.getDate(); var dayOfYear = dayCount[mn] + dn; - if (mn > 1 && this.isLeapYear()) dayOfYear++; + if( mn > 1 && this.isLeapYear() ) { dayOfYear++; } return dayOfYear; }; -function discordianDate(date) { - var y = date.getFullYear(); - var yold = y + 1166; - var dayOfYear = date.getDOY(); +Date.prototype.isToday = function() { + var today = new Date(); + return this.getDate() === today.getDate() + && this.getMonth() === today.getMonth() + && this.getFullYear() === today.getFullYear() + ; +}; - if (date.isLeapYear()) { - if (dayOfYear == 60) - return "St. Tib's Day, in the YOLD " + yold; - else if (dayOfYear > 60) +function discordianDate(date) { + if( !date ) { date = new Date(); } + + var y = date.getFullYear(); + var yold = y + 1166; + var dayOfYear = date.getDOY(); + var celebrateHoliday = null; + + if( date.isLeapYear() ) { + if( dayOfYear == 60 ) { + celebrateHoliday = "St. Tib's Day"; + } + else if( dayOfYear > 60 ) { dayOfYear--; + } } dayOfYear--; - var divDay= Math.floor(dayOfYear/73); + var divDay = Math.floor(dayOfYear / 73); var seasonDay = (dayOfYear % 73) + 1; - if (seasonDay == 5) - return apostle[divDay] + ", in the YOLD " + yold; - if (seasonDay == 50) - return holiday[divDay] + ", in the YOLD " + yold; + if( seasonDay == 5 ) { + celebrateHoliday = apostle[divDay]; + } + if( seasonDay == 50 ) { + celebrateHoliday = holiday[divDay]; + } - var season = seasons[divDay]; + var season = seasons[divDay]; var dayOfWeek = weekday[dayOfYear % 5]; - return dayOfWeek + ", day " + seasonDay + " of " + - season + " in the YOLD " + yold; + var nth = (seasonDay % 10 == 1) ? 'st' + : (seasonDay % 10 == 2) ? 'nd' + : (seasonDay % 10 == 3) ? 'rd' + : 'th'; + + return "" //(date.isToday() ? "Today is " : '') + + dayOfWeek + + ", the " + seasonDay + nth + + " day of " + season + + " in the YOLD " + yold + + (celebrateHoliday ? ". Celebrate " + celebrateHoliday + "!" : '') + ; } function test(y, m, d, result) { - console.assert((discordianDate(new Date(y, m, d)) == result), result); + console.assert((discordianDate(new Date(y, m, d)) == result), [y, m, d, discordianDate(new Date(y, m, d)), result]); } -console.log(discordianDate(new Date(Date.now()))); -test(2010, 6, 22, "Pungenday, day 57 of Confusion in the YOLD 3176"); -test(2012, 1, 28, "Prickle-Prickle, day 59 of Chaos in the YOLD 3178"); -test(2012, 1, 29, "St. Tib's Day, in the YOLD 3178"); -test(2012, 2, 1, "Setting Orange, day 60 of Chaos in the YOLD 3178"); -test(2010, 0, 5, "Mungday, in the YOLD 3176"); -test(2011, 4, 3, "Discoflux, in the YOLD 3177"); -test(2015, 9, 19, "Boomtime, day 73 of Bureaucracy in the YOLD 3181"); +// Only run test code if node calls this file directly +if( require.main === module ) { + console.log(discordianDate(new Date(Date.now()))); + test(2010, 6, 22, "Pungenday, the 57th day of Confusion in the YOLD 3176"); + test(2012, 1, 28, "Prickle-Prickle, the 59th day of Chaos in the YOLD 3178"); + test(2012, 1, 29, "Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib's Day!"); + test(2012, 2, 1, "Setting Orange, the 60th day of Chaos in the YOLD 3178"); + test(2010, 0, 5, "Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!"); + test(2011, 4, 3, "Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!"); + test(2015, 9, 19, "Boomtime, the 73rd day of Bureaucracy in the YOLD 3181"); +} + +module.exports = discordianDate; diff --git a/Task/Discordian-date/JavaScript/discordian-date-2.js b/Task/Discordian-date/JavaScript/discordian-date-2.js index d49e0f9154..4a80acd654 100644 --- a/Task/Discordian-date/JavaScript/discordian-date-2.js +++ b/Task/Discordian-date/JavaScript/discordian-date-2.js @@ -1,2 +1,2 @@ console.log(discordianDate(new Date(Date.now()))); -"Prickle-Prickle, day 47 of The Aftermath in the YOLD 3181" +"Boomtime, the 2nd day of Chaos in the YOLD 3183" diff --git a/Task/Discordian-date/Julia/discordian-date.julia b/Task/Discordian-date/Julia/discordian-date.julia new file mode 100644 index 0000000000..2f9e89039c --- /dev/null +++ b/Task/Discordian-date/Julia/discordian-date.julia @@ -0,0 +1,39 @@ +# v0.6.0 +using Dates + +function discordiandate(year::Integer, month::Integer, day::Integer) + const DISCORDIANSEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"] + const HOLIDAYS = Dict( + "Chaos 5" => "Mungday", + "Chaos 50" => "Chaoflux", + "Discord 5" => "Mojoday", + "Discord 50" => "Discoflux", + "Confusion 5" => "Syaday", + "Confusion 50" => "Confuflux", + "Bureaucracy 5" => "Zaraday", + "Bureaucracy 50" => "Bureflux", + "The Aftermath 5" => "Maladay", + "The Aftermath 50" => "Afflux", + ) + today = Date(year, month, day) + isleap = isleapyear(year) + if isleap && month == 2 && day == 29 + rst = "St. Tib's Day, YOLD " * string(year + 1166) + else + dy = dayofyear(today) + if isleap && dy >= 60 + dy -= 1 + end + dday = string(DISCORDIANSEASONS[div(dy, 73) + 1], " ", rem(dy, 73)) + if haskey(HOLIDAYS, dday) + rst = dday * " ($(HOLIDAYS[dday])), YOLD $(year + 1166)" + else + rst = dday * ", YOLD $(year + 1166)" + end + end + return rst +end + +@show discordiandate(2017, 08, 15) +@show discordiandate(1996, 02, 29) +@show discordiandate(1996, 02, 19) diff --git a/Task/Discordian-date/PHP/discordian-date.php b/Task/Discordian-date/PHP/discordian-date.php index 8e7d6cfc8b..b2fc49cc7d 100644 --- a/Task/Discordian-date/PHP/discordian-date.php +++ b/Task/Discordian-date/PHP/discordian-date.php @@ -1,62 +1,82 @@ = 60) { //offset day by one if leap year - $dday -= 1; - if($dday % 5 == 0) $ddayname = $DAYS[4]; - else $ddayname = $DAYS[($dday%5)]; - } - } - // Display Discordian date - echo "Today is " . $ddayname . ", " . $dmonth . " " . $dday . ", YOLD " . $dyear; -} -else { // Leap year exception for date from URL - if ($usery % 100 == 0) { // leap year exception for years that are divisible by one hundred - if ($usery % 400 == 0 && $userm == 2 && $userd == 29) { echo "Today is St. Tib's Day, YOLD " . $dyear; } - } - else if ($usery % 4 == 0) { // if the year is a leap year - if ($userm == 2 && $userd == 29) { echo "Today is St. Tib's Day, YOLD " . $dyear; } - elseif ($ddays >= 60) { // offset day by one if leap year - $dday -=1; - if($dday % 5 == 0) $ddayname = $DAYS[4]; - else $ddayname=$DAYS[($dday%5-1)]; - echo "Today is " . $ddayname . ", " . $dmonth . " " . $dday . ", YOLD " . $dyear; - } - else { echo "Today is " . $ddayname . ", " . $dmonth . " " . $dday . ", YOLD " . $dyear; } - } - // Display Discordian date - else { echo "Today is " . $ddayname . ", " . $dmonth . " " . $dday . ", YOLD " . $dyear; } -} -?> + + // Get the current system date and assign to some variables + $edate = explode(" ",date('Y m j L')); + $usery = $edate[0]; + $userm = $edate[1]; + $userd = $edate[2]; + $IsLeap = $edate[3]; + + // If the user supplied us with a date overide the one we got from the system. + // If you could get the date from users browser via javascript and then call + // this script with the users date. ddate.php?y=year&m=month&d=day mostly it + // won't matter but if the server is in a different time zone to the user + // There will be occasional incorrect results from the users POV. + + if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) { + $usery = $_GET['y']; + $userm = $_GET['m']; + $userd = $_GET['d']; + $IsLeap = 0; + if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1; + if ($usery%400 == 0) $IsLeap = 1; + } + + // We need to know the total number of days in the year so far + + $userdays = 0; + $i = 0; + while ($i < ($userm-1)) { + + $userdays = $userdays + $Anerisia[$i]; + $i = $i +1; + } + $userdays = $userdays + $userd; + + // We can now work out the full discordian date for most dates + // PHP does not do integer division, so we use 73.2 as a divisor + // the value 73.2 works, larger values cause an off-by-one on season + // changes for the later seasons . + // This is not needed with the mod operator. + + $IsHolyday = 0; + $dyear = $usery + 1166; + $dmonth = $MONTHS[$userdays/73.2]; + $dday = $userdays%73; + if (0 == $dday) $dday = 73; + $Dname = $DAYS[$userdays%5]; + $Holyday = "St. Tibs Day"; + if ($dday == 5) { + $Holyday = $Holy5[$userdays/73.2]; + $IsHolyday =1; + } + if ($dday == 50) { + $Holyday = $Holy50[$userdays/73.2]; + $IsHolyday =1; + } + + if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2; + + // work out the suffix to the day number + $suff = $Dsuff[$dday%10] ; + if ((11 <= $dday) && (19 >= $dday)) $suff='th'; + + // code to display the date ... + + if ($IsHolyday ==2) + echo "
    Celeberate ",$Holyday," ",$dmonth," YOLD ",$dyear; + if ($IsHolyday ==1) + echo "
    Celeberate for today ", $Dname , " The ", $dday,"",$suff,"", " day of ", $dmonth , " YOLD " , $dyear , " is the holy day of " , $Holyday; + if ($IsHolyday == 0) + echo "
    Today is " , $Dname , " the " , $dday ,"",$suff, " day of " , $dmonth , " YOLD " , $dyear; + + ?> diff --git a/Task/Discordian-date/Pascal/discordian-date.pascal b/Task/Discordian-date/Pascal/discordian-date.pascal new file mode 100644 index 0000000000..1ed5836cce --- /dev/null +++ b/Task/Discordian-date/Pascal/discordian-date.pascal @@ -0,0 +1,159 @@ +program ddate; +{ +This program is free software, it's done it's time +and paid for it's crime. You can copy, edit and use this +software under the terms of the GNU GPL v3 or later. + +Copyright Pope Englebert Finklestien, +On this day Boomtime, the 71st day of Confusion in the YOLD 3183 + +This program will print out the current date in Erisian format as specified in + + P R I N C I P I A D I S C O R D I A + +If you run it with a date it the command line in european format (dd mm yy) it +will print the equvolent Discordian date. If you omit the year and month the +current Anerisiean month and year as assumed. + + +POPE Englebert Finklestien. +} +uses Sysutils; + +var + YY,MM,DD : word; + YOLD : Boolean; + Hedgehog: integer; + Eris: string; + snub: string; + chaotica: string; + midget: string; + bob: string; + + + Anerisiandaysinmonth: array[1..12] of integer = (31,28,31,30,31,30,31,31,30,31,30,31); + + + +procedure anerisiandate; +{ tHIS JUST GETS THE DATE INTO THE DD,MM,YY VARIABLES } +begin + DeCodeDate(date,yy,mm,dd); +end; + +procedure BORIS; +{ This just tests to see if we are in a leap year } +var + snafu : boolean; +begin + snafu := False; + if (yy mod 4 = 0) then snafu := True; + if ((yy mod 100 = 0) and (yy mod 400 <> 0)) then snafu := False; + if ((snafu) and (mm = 2 ) and (dd=29)) then YOLD := True; +end; + +function hodgepodge: integer; +{ This returns the total number of days since the year began. +It doesn't bother with leap years at all. +I get a wierd optical illusion looking at the until in this } +var + fnord : integer; +begin + Hedgehog := 1; + hodgepodge := 0; + fnord :=0; + if (mm > 1) then repeat + fnord := fnord + Anerisiandaysinmonth[Hedgehog]; + Hedgehog := Hedgehog +1; + until Hedgehog = mm; + fnord := fnord + dd; + hodgepodge := fnord; + end; + + +function treesaregreen(): string; +{Returns the YOLD as a string} + +begin + treesaregreen := IntTOStr(yy+1166); +end; + + +procedure GRAYFACE; +{This calculates everything, but does not bother much about leap years} +var + wrestle: integer; + Thwack: string; +begin + Hedgehog := hodgepodge; + wrestle := 0; + Thwack := 'th'; + {set bob to the name of the holyday or St. Tibs day } + bob := 'St. Tibs Day'; + if (Hedgehog = 5 ) then bob := 'Mungday'; + if (Hedgehog = 50 ) then bob := 'Chaoflux'; + if (Hedgehog = 78 ) then bob := 'Mojoday'; + if (Hedgehog = 123) then bob := 'Discoflux'; + if (Hedgehog = 151) then bob := 'Syaday'; + if (Hedgehog = 196) then bob := 'Confuflux'; + if (Hedgehog = 224) then bob := 'Zaraday'; + if (Hedgehog = 269) then bob := 'Bureflux'; + if (Hedgehog = 297) then bob := 'Maladay'; + if (Hedgehog = 342) then bob := 'Afflux'; + {Not doing things the usual way + Lets find the week day and count the number of + 5 day weeks all at the same time} + while (Hedgehog > 5) do begin + Hedgehog := Hedgehog -5; + wrestle := Wrestle + 1; + end; + if (Hedgehog = 1) then snub := 'Sweetmorn' ; + if (Hedgehog = 2) then snub := 'BoomTime'; + if (Hedgehog = 3) then snub := 'Pungenday'; + if (Hedgehog = 4) then snub := 'Prickle-Prickle'; + if (Hedgehog = 5) then snub := 'Setting Orange'; + {Now to set the Season name} + chaotica:='The Aftermath'; + if (wrestle <=57) then chaotica := 'Bureaucracy'; + if ((wrestle = 58) and (Hedgehog < 3)) then chaotica := 'Bureaucracy'; + if (wrestle <= 42) then chaotica := 'Confusion'; + if ((wrestle = 43) and (Hedgehog < 5)) then chaotica := 'Confusion'; + if (wrestle <=28) then chaotica := 'Discord'; + if ((wrestle = 29) and (Hedgehog < 2)) then chaotica := 'Discord'; + if (wrestle <=13) then chaotica := 'Chaos'; + if ((wrestle = 14) and (Hedgehog < 4)) then chaotica := 'Chaos'; + + {Now all we need the day of the season} + wrestle := (wrestle*5)+Hedgehog; + while (wrestle >73) do wrestle := wrestle -73; + {pick the appropriate day postfix, allready set to th} + if (wrestle in [1,21,31,41,51,61,71]) then Thwack:='st'; + if (wrestle in [2,22,32,42,52,62,72]) then Thwack:='nd'; + if (wrestle in [3,23,33,43,53,63,73]) then Thwack:='rd'; + {Check to see if it is a holy day, if so bob will have + the right holyday name already, including St Tibs Day} + if (wrestle in [5,50]) then YOLD := True; + {I love this line of code} + midget := IntToStr(wrestle) + Thwack; +end; + + +{The main program starts here} +begin + anerisiandate; + if (ParamCount >=1) then dd := StrTOInt(ParamStr(1)); + if (ParamCount >=2) then mm := StrToInt(ParamStr(2)); + if (ParamCount =3) then yy := StrToInt(ParamStr(3)); + BORIS; + GRAYFACE; + { The only thing to bother about is holy days and St Tibs day } + Eris := 'Today is: ' + snub +' the ' + midget +' day of the season of ' + chaotica; + if (YOLD) then begin + Eris := 'Celebrate for today, ' + snub + ' the ' + midget + ' day of ' +chaotica + ' is the holy day of ' + bob; + end; + {The only place we deal with St. Tibs Day} + if ((YOLD) and ((mm=2) and (dd=29))) then Eris := 'Celebrate ' + bob + ' Chaos'; + {This next line applies to all possibilities} + Eris := Eris + ' YOLD ' + treesaregreen; + WriteLn(Eris); +end. diff --git a/Task/Discordian-date/Zkl/discordian-date-1.zkl b/Task/Discordian-date/Zkl/discordian-date-1.zkl new file mode 100644 index 0000000000..e06a97f114 --- /dev/null +++ b/Task/Discordian-date/Zkl/discordian-date-1.zkl @@ -0,0 +1,21 @@ +fcn discordianDate(y,m,d){ + var [const] + seasons=T("Chaos","Discord","Confusion","Bureaucracy","The Aftermath"), + weekday=T("Sweetmorn","Boomtime","Pungenday","Prickle-Prickle","Setting Orange"), + apostle=T("Mungday","Mojoday","Syaday","Zaraday","Maladay"), + holiday=T("Chaoflux","Discoflux","Confuflux","Bureflux","Afflux"]; + + dYear,isLeapYear := y + 1166, Time.Date.isLeapYear(y); + if(isLeapYear and m==2 and d==29) + return("St. Tib's Day, in the YOLD " + dYear); + + doy:=Time.Date.nthDayInYear(y,m,d); + if(isLeapYear and doy>=60) doy-=1; + dsDay:=(if(doy%73==0) 73 else doy%73); // Season day. + if(dsDay==5) return(String(apostle[doy/73],", in the YOLD ",dYear)); + if(dsDay==50) return(String(holiday[doy/73],", in the YOLD ",dYear)); + + dSeas:=seasons[(if(doy%73==0) doy-1 else doy)/73]; + dWday:=weekday[(doy - 1)%5]; + "%s, day %s of %s in the YOLD %s".fmt(dWday,dsDay,dSeas,dYear); +} diff --git a/Task/Discordian-date/Zkl/discordian-date-2.zkl b/Task/Discordian-date/Zkl/discordian-date-2.zkl new file mode 100644 index 0000000000..b786a67092 --- /dev/null +++ b/Task/Discordian-date/Zkl/discordian-date-2.zkl @@ -0,0 +1,4 @@ +foreach y,m,d in (T(T(2010,7,22), T(2012,2,28), T(2012,2,29), T(2012,3,1), + T(2010,1, 5), T(2011,5, 3))){ + "%d-%02d-%02d is -->%s".fmt(y,m,d,discordianDate(y,m,d)).println(); +} diff --git a/Task/Distributed-programming/D/distributed-programming-1.d b/Task/Distributed-programming/D/distributed-programming-1.d deleted file mode 100644 index 90abe01ea8..0000000000 --- a/Task/Distributed-programming/D/distributed-programming-1.d +++ /dev/null @@ -1,38 +0,0 @@ -module distributedserver ; -import tango.net.ServerSocket, tango.text.convert.Integer, - tango.text.Util, tango.io.Stdout ; - -void main() { - auto Ip = new InternetAddress("localhost", 12345) ; - auto server = new ServerSocket(Ip) ; - auto socket = server.accept ; - auto buffer = new char[socket.bufferSize] ; - - bool quit = false ; - - while(!quit) { - bool error = false ; - - try { - auto len = socket.input.read(buffer) ; - auto cmd = (len > 0) ? delimit(buffer[0..len], " ") : [""] ; - Stdout(cmd).newline.flush ; - switch (cmd[0]) { - case "square": - socket.output.write(toString(toInt(cmd[1]) * toInt(cmd[1]))) ; break ; - case"add": - socket.output.write(toString(toInt(cmd[1]) + toInt(cmd[2]))) ; break ; - case "quit": - socket.output.write("Server Shut down") ; - quit = true ; break ; - default: error = true ; - } - } catch (Exception e) - error = true ; - if(error) socket.output.write("") ; - if(socket) socket.close ; - if(!quit) socket = server.accept ; - } - - if(socket) socket.close ; -} diff --git a/Task/Distributed-programming/D/distributed-programming-2.d b/Task/Distributed-programming/D/distributed-programming-2.d deleted file mode 100644 index 303af1c933..0000000000 --- a/Task/Distributed-programming/D/distributed-programming-2.d +++ /dev/null @@ -1,24 +0,0 @@ -module distributedclient ; -import tango.net.SocketConduit, tango.net.InternetAddress, - tango.text.Util, tango.io.Stdout ; - -void main(char[][] args) { - - if(args.length> 1) { - try { - auto Ip = new InternetAddress("localhost", 12345) ; - auto socket = new SocketConduit ; - socket.connect(Ip) ; - auto buffer = new char[socket.bufferSize] ; - - socket.output.write(join(args[1..$]," ")) ; - auto len = socket.input.read(buffer) ; - if(len > 0) Stdout(buffer[0..len]).newline ; - - if(socket) socket.close ; - } catch(Exception e) - Stdout(e.msg).newline ; - } else - Stdout("usage: supply argument as,\n\tquit\n" - "\tsquare \n\tadd ").newline ; -} diff --git a/Task/Distributed-programming/Go/distributed-programming-3.go b/Task/Distributed-programming/Go/distributed-programming-3.go new file mode 100644 index 0000000000..348d83281d --- /dev/null +++ b/Task/Distributed-programming/Go/distributed-programming-3.go @@ -0,0 +1,9 @@ +syntax = "proto3"; + +service TaxComputer { + rpc Tax(Amount) returns (Amount) {} +} + +message Amount { + int32 cents = 1; +} diff --git a/Task/Distributed-programming/Go/distributed-programming-4.go b/Task/Distributed-programming/Go/distributed-programming-4.go new file mode 100644 index 0000000000..f0d9092367 --- /dev/null +++ b/Task/Distributed-programming/Go/distributed-programming-4.go @@ -0,0 +1,34 @@ +package main + +import ( + "errors" + "net" + + "golang.org/x/net/context" + "google.golang.org/grpc" + "google.golang.org/grpc/grpclog" + + "taxcomputer" +) + +type taxServer struct { + rate float64 +} + +func (s *taxServer) Tax(ctx context.Context, + amt *taxcomputer.Amount) (*taxcomputer.Amount, error) { + if amt.Cents < 0 { + return nil, errors.New("Negative amounts not allowed") + } + return &taxcomputer.Amount{int32(float64(amt.Cents)*s.rate + .5)}, nil +} + +func main() { + listener, err := net.Listen("tcp", ":1234") + if err != nil { + grpclog.Fatalf(err.Error()) + } + grpcServer := grpc.NewServer() + taxcomputer.RegisterTaxComputerServer(grpcServer, &taxServer{.05}) + grpcServer.Serve(listener) +} diff --git a/Task/Distributed-programming/Go/distributed-programming-5.go b/Task/Distributed-programming/Go/distributed-programming-5.go new file mode 100644 index 0000000000..b03a49b11a --- /dev/null +++ b/Task/Distributed-programming/Go/distributed-programming-5.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + + "golang.org/x/net/context" + "google.golang.org/grpc" + "google.golang.org/grpc/grpclog" + + "taxcomputer" +) + +func main() { + conn, err := grpc.Dial("localhost:1234", grpc.WithInsecure()) + if err != nil { + grpclog.Fatalf(err.Error()) + } + defer conn.Close() + client := taxcomputer.NewTaxComputerClient(conn) + amt := &taxcomputer.Amount{300} + tax, err := client.Tax(context.Background(), amt) + if err != nil { + grpclog.Fatalf(err.Error()) + } + fmt.Println("Tax on", amt.Cents, "cents is", tax.Cents, "cents") +} diff --git a/Task/Distributed-programming/Go/distributed-programming-6.go b/Task/Distributed-programming/Go/distributed-programming-6.go new file mode 100644 index 0000000000..c9a4a12eff --- /dev/null +++ b/Task/Distributed-programming/Go/distributed-programming-6.go @@ -0,0 +1,3 @@ +service TaxService { + i32 tax(1: i32 amt) +} diff --git a/Task/Distributed-programming/Go/distributed-programming-7.go b/Task/Distributed-programming/Go/distributed-programming-7.go new file mode 100644 index 0000000000..a85a3b89df --- /dev/null +++ b/Task/Distributed-programming/Go/distributed-programming-7.go @@ -0,0 +1,33 @@ +package main + +import ( + "errors" + "log" + + "git.apache.org/thrift.git/lib/go/thrift" + + "gen-go/tax" +) + +type taxHandler float64 + +func (r taxHandler) Tax(amt int32) (int32, error) { + if amt < 0 { + return 0, errors.New("Negative amounts not allowed") + } + return int32(float64(amt)*float64(r) + .5), nil +} + +func main() { + transport, err := thrift.NewTServerSocket("localhost:3141") + if err != nil { + log.Fatal(err) + } + transFac := thrift.NewTTransportFactory() + protoFac := thrift.NewTCompactProtocolFactory() + proc := tax.NewTaxServiceProcessor(taxHandler(.05)) + s := thrift.NewTSimpleServer4(proc, transport, transFac, protoFac) + if err := s.Serve(); err != nil { + log.Fatal(err) + } +} diff --git a/Task/Distributed-programming/Go/distributed-programming-8.go b/Task/Distributed-programming/Go/distributed-programming-8.go new file mode 100644 index 0000000000..50c4df4ba8 --- /dev/null +++ b/Task/Distributed-programming/Go/distributed-programming-8.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + "log" + + "git.apache.org/thrift.git/lib/go/thrift" + + "gen-go/tax" +) + +func main() { + transport, err := thrift.NewTSocket("localhost:3141") + if err != nil { + log.Fatal(err) + } + if err := transport.Open(); err != nil { + log.Fatal(err) + } + protoFac := thrift.NewTCompactProtocolFactory() + client := tax.NewTaxServiceClientFactory(transport, protoFac) + amt := int32(300) + t, err := client.Tax(amt) + if err != nil { + log.Print(err) + } else { + fmt.Println("tax on", amt, "is", t) + } + transport.Close() +} diff --git a/Task/Dot-product/Aime/dot-product.aime b/Task/Dot-product/Aime/dot-product.aime new file mode 100644 index 0000000000..d5f173efcd --- /dev/null +++ b/Task/Dot-product/Aime/dot-product.aime @@ -0,0 +1,21 @@ +real +dp(list a, list b) +{ + real p, v; + integer i; + + p = 0; + for (i, v in a) { + p += v * __real(b[i]); + } + + return p; +} + +integer +main(void) +{ + o_(dp(l_effect(1r, 3r, -5r), l_effect(4r, -2r, -1r)), "\n"); + + return 0; +} diff --git a/Task/Dot-product/AppleScript/dot-product-1.applescript b/Task/Dot-product/AppleScript/dot-product-1.applescript index e67fe3eb0f..c4691c0c71 100644 --- a/Task/Dot-product/AppleScript/dot-product-1.applescript +++ b/Task/Dot-product/AppleScript/dot-product-1.applescript @@ -1,9 +1,11 @@ +-- DOT PRODUCT --------------------------------------------------------------- + -- dotProduct :: [Number] -> [Number] -> Number on dotProduct(xs, ys) script product - on lambda(a, b) + on |λ|(a, b) a * b - end lambda + end |λ| end script if length of xs = length of ys then @@ -13,19 +15,8 @@ on dotProduct(xs, ys) end if end dotProduct --- sum :: [Number] -> Number -on sum(xs) - script add - on lambda(a, b) - a + b - end lambda - end script - foldl(add, 0, xs) -end sum - - --- TEST +-- TEST ---------------------------------------------------------------------- on run dotProduct([1, 3, -5], [4, -2, -1]) @@ -34,18 +25,7 @@ on run end run --- GENERIC FUNCTIONS - --- all :: (a -> Bool) -> [a] -> Bool -on all(f, xs) - tell mReturn(f) - set lng to length of xs - repeat with i from 1 to lng - if not lambda(item i of xs) then return false - end repeat - true - end tell -end all +-- GENERIC FUNCTIONS --------------------------------------------------------- -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) @@ -53,29 +33,20 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl --- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -on zipWith(f, xs, ys) - set nx to length of xs - set ny to length of ys - if nx < 1 or ny < 1 then - {} +-- min :: Ord a => a -> a -> a +on min(x, y) + if y < x then + y else - set lng to cond(nx < ny, nx, ny) - set lst to {} - tell mReturn(f) - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, item i of ys) - end repeat - return lst - end tell + x end if -end zipWith +end min -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -84,16 +55,30 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn --- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b) -on cond(bool, f, g) - if bool then - f - else - g - end if -end cond +-- sum :: [Number] -> Number +on sum(xs) + script add + on |λ|(a, b) + a + b + end |λ| + end script + + foldl(add, 0, xs) +end sum + +-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] +on zipWith(f, xs, ys) + set lng to min(length of xs, length of ys) + set lst to {} + tell mReturn(f) + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, item i of ys) + end repeat + return lst + end tell +end zipWith diff --git a/Task/Dot-product/Bc/dot-product.bc b/Task/Dot-product/Bc/dot-product.bc new file mode 100644 index 0000000000..c5d9c08843 --- /dev/null +++ b/Task/Dot-product/Bc/dot-product.bc @@ -0,0 +1,19 @@ +/* Calculate the dot product of two vectors a and b (represented as + * arrays) of size n. + */ +define d(a[], b[], n) { + auto d, i + + for (i = 0; i < n; i++) { + d += a[i] * b[i] + } + return(d) +} + +a[0] = 1 +a[1] = 3 +a[2] = -5 +b[0] = 4 +b[1] = -2 +b[2] = -1 +d(a[], b[], 3) diff --git a/Task/Dot-product/Clojure/dot-product.clj b/Task/Dot-product/Clojure/dot-product.clj index 432c7bd44f..be34e48732 100644 --- a/Task/Dot-product/Clojure/dot-product.clj +++ b/Task/Dot-product/Clojure/dot-product.clj @@ -8,7 +8,13 @@ (map #(apply * %)) (reduce +))) +(defn dot-product3 + "Dot product of vectors. Tested on version 1.8.0." + [v1 v2] + {:pre [(= (count v1) (count v2))]} + (reduce + (map * v1 v2))) ;Example Usage (println (dot-product [1 3 -5] [4 -2 -1])) (println (dot-product2 [1 3 -5] [4 -2 -1])) +(println (dot-product3 [1 3 -5] [4 -2 -1])) diff --git a/Task/Dot-product/Component-Pascal/dot-product.component b/Task/Dot-product/Component-Pascal/dot-product.component new file mode 100644 index 0000000000..6c55042df4 --- /dev/null +++ b/Task/Dot-product/Component-Pascal/dot-product.component @@ -0,0 +1,26 @@ +MODULE DotProduct; +IMPORT StdLog; + +PROCEDURE Calculate*(x,y: ARRAY OF INTEGER): INTEGER; +VAR + i,sum: INTEGER; +BEGIN + sum := 0; + FOR i:= 0 TO LEN(x) - 1 DO + INC(sum,x[i] * y[i]); + END; + RETURN sum +END Calculate; + +PROCEDURE Test*; +VAR + i,sum: INTEGER; + v1,v2: ARRAY 3 OF INTEGER; +BEGIN + v1[0] := 1;v1[1] := 3;v1[2] := -5; + v2[0] := 4;v2[1] := -2;v2[2] := -1; + + StdLog.Int(Calculate(v1,v2));StdLog.Ln +END Test; + +END DotProduct. diff --git a/Task/Dot-product/Haskell/dot-product-1.hs b/Task/Dot-product/Haskell/dot-product-1.hs new file mode 100644 index 0000000000..74e7e9e231 --- /dev/null +++ b/Task/Dot-product/Haskell/dot-product-1.hs @@ -0,0 +1,5 @@ +dotp :: Num a => [a] -> [a] -> a +dotp a b | length a == length b = sum (zipWith (*) a b) + | otherwise = error "Vector sizes must match" + +main = print $ dotp [1, 3, -5] [4, -2, -1] -- prints 3 diff --git a/Task/Dot-product/Haskell/dot-product-2.hs b/Task/Dot-product/Haskell/dot-product-2.hs new file mode 100644 index 0000000000..afa6bcf8c0 --- /dev/null +++ b/Task/Dot-product/Haskell/dot-product-2.hs @@ -0,0 +1,15 @@ +dotp + :: Num a + => [a] -> [a] -> Maybe a +dotp a b + | length a == length b = Just $ sum (zipWith (*) a b) + | otherwise = Nothing + +main :: IO () +main = mbPrint $ dotp [1, 3, -5] [4, -2, -1] -- prints 3 + +mbPrint + :: Show a + => Maybe a -> IO () +mbPrint (Just x) = print x +mbPrint n = print n diff --git a/Task/Dot-product/Haskell/dot-product.hs b/Task/Dot-product/Haskell/dot-product.hs deleted file mode 100644 index f5931bebef..0000000000 --- a/Task/Dot-product/Haskell/dot-product.hs +++ /dev/null @@ -1,4 +0,0 @@ -dotp a b | length a == length b = sum (zipWith (*) a b) - | otherwise = error "Vector sizes must match" - -main = print $ dotp [1, 3, -5] [4, -2, -1] -- prints 3 diff --git a/Task/Dot-product/Hy/dot-product.hy b/Task/Dot-product/Hy/dot-product.hy new file mode 100644 index 0000000000..4124fb3805 --- /dev/null +++ b/Task/Dot-product/Hy/dot-product.hy @@ -0,0 +1,6 @@ +(defn dotp [a b] + (assert (= (len a) (len b))) + (sum (genexpr (* aterm bterm) + [(, aterm bterm) (zip a b)]))) + +(assert (= 3 (dotp [1 3 -5] [4 -2 -1]))) diff --git a/Task/Dot-product/jq/dot-product-1.jq b/Task/Dot-product/Jq/dot-product-1.jq similarity index 100% rename from Task/Dot-product/jq/dot-product-1.jq rename to Task/Dot-product/Jq/dot-product-1.jq diff --git a/Task/Dot-product/jq/dot-product-2.jq b/Task/Dot-product/Jq/dot-product-2.jq similarity index 100% rename from Task/Dot-product/jq/dot-product-2.jq rename to Task/Dot-product/Jq/dot-product-2.jq diff --git a/Task/Dot-product/jq/dot-product-3.jq b/Task/Dot-product/Jq/dot-product-3.jq similarity index 100% rename from Task/Dot-product/jq/dot-product-3.jq rename to Task/Dot-product/Jq/dot-product-3.jq diff --git a/Task/Dot-product/Kotlin/dot-product.kotlin b/Task/Dot-product/Kotlin/dot-product.kotlin index 44205d4d02..1be94327f6 100644 --- a/Task/Dot-product/Kotlin/dot-product.kotlin +++ b/Task/Dot-product/Kotlin/dot-product.kotlin @@ -1,4 +1,6 @@ fun dot(v1: Array, v2: Array) = - v1.zip(v2).map { it.first * it.second }.reduce { a, b -> a + b } + v1.zip(v2).map { it.first * it.second }.reduce { a, b -> a + b } -dot(arrayOf(1.0, 3.0, -5.0), arrayOf(4.0, -2.0, -1.0)).let { println(it) } +fun main(args: Array) { + dot(arrayOf(1.0, 3.0, -5.0), arrayOf(4.0, -2.0, -1.0)).let { println(it) } +} diff --git a/Task/Dot-product/NewLISP/dot-product.newlisp b/Task/Dot-product/NewLISP/dot-product.newlisp new file mode 100644 index 0000000000..7a6f1e8b89 --- /dev/null +++ b/Task/Dot-product/NewLISP/dot-product.newlisp @@ -0,0 +1,4 @@ +(define (dot-product x y) + (apply + (map * x y))) + +(println (dot-product '(1 3 -5) '(4 -2 -1))) diff --git a/Task/Dot-product/REXX/dot-product-1.rexx b/Task/Dot-product/REXX/dot-product-1.rexx index 44b77c8225..bc68b88260 100644 --- a/Task/Dot-product/REXX/dot-product-1.rexx +++ b/Task/Dot-product/REXX/dot-product-1.rexx @@ -1,17 +1,16 @@ /*REXX program computes the dot product of two equal size vectors (of any size).*/ -vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/ -vectorB = ' 4 -2 -1 ' /* " " B " " " */ -say /*display a blank line for readability.*/ + vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/ + vectorB = ' 4 -2 -1 ' /* " " B " " " */ say 'vector A = ' vectorA /*display the elements in the vector A.*/ say 'vector B = ' vectorB /* " " " " " " B.*/ -p=dotProd(vectorA, vectorB) /*invoke function & compute dot product*/ +p=.Prod(vectorA, vectorB) /*invoke function & compute dot product*/ say /*display a blank line for readability.*/ say 'dot product = ' p /*display the dot product to terminal. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -dotProd: procedure; parse arg A,B /*this function compute the dot product*/ - $=0 /*initialize the sum to 0 (zero). */ - do j=1 for words(A) /*multiply each number in the vectors. */ - $=$+word(A,j) * word(B,j) /* ··· and add the product to the sum.*/ - end /*j*/ - return $ /*return the sum to invoker of function*/ +.Prod: procedure; parse arg A,B /*this function compute the dot product*/ + $=0 /*initialize the sum to 0 (zero). */ + do j=1 for words(A) /*multiply each number in the vectors. */ + $=$+word(A,j) * word(B,j) /* ··· and add the product to the sum.*/ + end /*j*/ + return $ /*return the sum to function's invoker.*/ diff --git a/Task/Dot-product/REXX/dot-product-2.rexx b/Task/Dot-product/REXX/dot-product-2.rexx index c7ed386a08..600d452ffa 100644 --- a/Task/Dot-product/REXX/dot-product-2.rexx +++ b/Task/Dot-product/REXX/dot-product-2.rexx @@ -1,7 +1,6 @@ /*REXX program computes the dot product of two equal size vectors (of any size).*/ -vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/ -vectorB = ' 4 -2 -1 ' /* " " B " " " */ -say /*display a blank line for readability.*/ + vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/ + vectorB = ' 4 -2 -1 ' /* " " B " " " */ say 'vector A = ' vectorA /*display the elements in the vector A.*/ say 'vector B = ' vectorB /* " " " " " " B.*/ p=.prod(vectorA, vectorB) /*invoke function & compute dot product*/ @@ -9,8 +8,6 @@ say /*display a blank line for read say 'dot product = ' p /*display the dot product to terminal. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -ser: say "***error*** vector " @.k ' element' j " isn't numeric: " n.k; exit 13 -/*──────────────────────────────────────────────────────────────────────────────────────*/ .prod: procedure; parse arg A,B /*this function compute the dot product*/ lenA = words(A); @.1= 'A' /*the number of numbers in vector A. */ lenB = words(B); @.2= 'B' /* " " " " " " B. */ @@ -24,8 +21,10 @@ ser: say "***error*** vector " @.k ' element' j " isn't numeric: " n.k; do j=1 for lenA /*multiply each number in the vectors. */ #.1=word(A,j) /*use array to hold 2 numbers at a time*/ #.2=word(B,j) - do k=1 for 2; if \datatype(#.k,'N') then call ser + do k=1 for 2; if datatype(#.k,'N') then iterate + say "***error*** vector " @.k ' element' j, + " isn't numeric: " n.k; exit 13 end /*k*/ $=$ + #.1 * #.2 /* ··· and add the product to the sum.*/ end /*j*/ - return $ /*return the sum to invoker of function*/ + return $ /*return the sum to function's invoker.*/ diff --git a/Task/Dot-product/Stata/dot-product-1.stata b/Task/Dot-product/Stata/dot-product-1.stata new file mode 100644 index 0000000000..618ea6747b --- /dev/null +++ b/Task/Dot-product/Stata/dot-product-1.stata @@ -0,0 +1,4 @@ +matrix a=1,3,-5 +matrix b=4,-2,-1 +matrix c=a*b' +di el("c",1,1) diff --git a/Task/Dot-product/Stata/dot-product-2.stata b/Task/Dot-product/Stata/dot-product-2.stata new file mode 100644 index 0000000000..294d3bd7f9 --- /dev/null +++ b/Task/Dot-product/Stata/dot-product-2.stata @@ -0,0 +1,4 @@ +matrix a=1\3\-5 +matrix b=4\-2\-1 +matrix c=a'*b +di el("c",1,1) diff --git a/Task/Dot-product/Stata/dot-product-3.stata b/Task/Dot-product/Stata/dot-product-3.stata new file mode 100644 index 0000000000..6e16e219c6 --- /dev/null +++ b/Task/Dot-product/Stata/dot-product-3.stata @@ -0,0 +1,3 @@ +a=1,3,-5 +b=4,-2,-1 +a*b' diff --git a/Task/Dot-product/Stata/dot-product-4.stata b/Task/Dot-product/Stata/dot-product-4.stata new file mode 100644 index 0000000000..d2b12f2eaf --- /dev/null +++ b/Task/Dot-product/Stata/dot-product-4.stata @@ -0,0 +1,3 @@ +a=1\3\-5 +b=4\-2\-1 +a'*b diff --git a/Task/Dot-product/Stata/dot-product-5.stata b/Task/Dot-product/Stata/dot-product-5.stata new file mode 100644 index 0000000000..e2118e93b3 --- /dev/null +++ b/Task/Dot-product/Stata/dot-product-5.stata @@ -0,0 +1 @@ +sum(a:*b) diff --git a/Task/Dot-product/Zkl/dot-product-1.zkl b/Task/Dot-product/Zkl/dot-product-1.zkl new file mode 100644 index 0000000000..545927a155 --- /dev/null +++ b/Task/Dot-product/Zkl/dot-product-1.zkl @@ -0,0 +1 @@ +fcn dotp(a,b){Utils.zipWith('*,a,b).sum()} diff --git a/Task/Dot-product/Zkl/dot-product-2.zkl b/Task/Dot-product/Zkl/dot-product-2.zkl new file mode 100644 index 0000000000..bc0d415cfb --- /dev/null +++ b/Task/Dot-product/Zkl/dot-product-2.zkl @@ -0,0 +1,3 @@ +fcn dotp2(a,b){if(a.len()!=b.len())throw(Exception.ValueError); + Utils.zipWith('*,a,b).sum() +} diff --git a/Task/Doubly-linked-list-Definition/D/doubly-linked-list-definition.d b/Task/Doubly-linked-list-Definition/D/doubly-linked-list-definition.d index 6b3ade3663..681d79e596 100644 --- a/Task/Doubly-linked-list-Definition/D/doubly-linked-list-definition.d +++ b/Task/Doubly-linked-list-Definition/D/doubly-linked-list-definition.d @@ -1,3 +1,5 @@ +import std.stdio; + class LinkedList(T) { Node!(T) head, tail; @@ -65,13 +67,13 @@ class Node(T) /** Insert an element after this one. */ void insertAfter (T value) { - new Node!(T)(this, next, value, parent); + new Node!(T)(next, this, value, parent); } /** Insert an element before this one. */ void insertBefore (T value) { - new Node!(T)(previous, this, value, parent); + new Node!(T)(this, previous, value, parent); } /** Remove the current node from the list. */ @@ -90,8 +92,8 @@ class Node(T) void main () { - char[][] sample = ["was", "it", "a", "cat", "I", "saw"]; - auto list = LinkedList!(char[]).fromArray (sample); + string[] sample = ["was", "it", "a", "cat", "I", "saw"]; + auto list = LinkedList!string.fromArray (sample); for (auto elem = list.head; elem; elem = elem.next) { writef ("%s ", elem.value); 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.kotlin new file mode 100644 index 0000000000..7d443e79be --- /dev/null +++ b/Task/Doubly-linked-list-Definition/Kotlin/doubly-linked-list-definition.kotlin @@ -0,0 +1,66 @@ +// version 1.1.2 + +class LinkedList { + class Node(var data: E, var prev: Node? = null, var next: Node? = null) { + override fun toString(): String { + val sb = StringBuilder(this.data.toString()) + var node = this.next + while (node != null) { + sb.append(" -> ", node.data.toString()) + node = node.next + } + return sb.toString() + } + } + + var first: Node? = null + var last: Node? = null + + fun addFirst(value: E) { + if (first == null) { + first = Node(value) + last = first + } + else { + val node = first!! + first = Node(value, null, node) + node.prev = first + } + } + + fun addLast(value: E) { + if (last == null) { + last = Node(value) + first = last + } + else { + val node = last!! + last = Node(value, node, null) + node.next = last + } + } + + fun insert(after: Node?, value: E) { + if (after == null) + addFirst(value) + else if (after == last) + addLast(value) + else { + val next = after.next + val new = Node(value, after, next) + after.next = new + if (next != null) next.prev = new + } + } + + override fun toString() = first.toString() +} + +fun main(args: Array) { + val ll = LinkedList() + ll.addFirst(1) + ll.addLast(4) + ll.insert(ll.first, 2) + ll.insert(ll.last!!.prev, 3) + println(ll) +} diff --git a/Task/Doubly-linked-list-Definition/Oberon-2/doubly-linked-list-definition.oberon-2 b/Task/Doubly-linked-list-Definition/Oberon-2/doubly-linked-list-definition.oberon-2 new file mode 100644 index 0000000000..366720cefd --- /dev/null +++ b/Task/Doubly-linked-list-Definition/Oberon-2/doubly-linked-list-definition.oberon-2 @@ -0,0 +1,12 @@ +IMPORT Basic; +TYPE + Node* = POINTER TO NodeDesc; + NodeDesc* = (* ABSTRACT *) RECORD + prev-,next-: Node; + END; + + DLList* = POINTER TO DLListDesc; + DLListDesc* = RECORD + first-,last-: Node; + size-: INTEGER; + END; diff --git a/Task/Doubly-linked-list-Definition/Objeck/doubly-linked-list-definition.objeck b/Task/Doubly-linked-list-Definition/Objeck/doubly-linked-list-definition.objeck new file mode 100644 index 0000000000..1e25c63ca6 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/Objeck/doubly-linked-list-definition.objeck @@ -0,0 +1,17 @@ +use Collection; + +class Program { + function : Main(args : String[]) ~ Nil { + list := List->New(); + list->AddFront("first"); + list->AddBack("last"); + list->Insert("middle"); + + list->Forward(); + do { + list->Get()->As(String)->PrintLine(); + list->Previous(); + } + while(list->Get() <> Nil); + } +} diff --git a/Task/Doubly-linked-list-Definition/Zkl/doubly-linked-list-definition-1.zkl b/Task/Doubly-linked-list-Definition/Zkl/doubly-linked-list-definition-1.zkl new file mode 100644 index 0000000000..a53180a2c4 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/Zkl/doubly-linked-list-definition-1.zkl @@ -0,0 +1,26 @@ +class Node{ + fcn init(_value,_prev=Void,_next=Void) + { var value=_value, prev=_prev, next=_next; } + fcn toString{ value.toString() } + fcn append(value){ // loops not allowed: create a new Node + b,c := Node(value,self,next),next; + next=b; + if(c) c.prev=b; + b + } + fcn delete{ + if(prev) prev.next=next; + if(next) next.prev=prev; + self + } + fcn last { n,p := self,self; while(n){ p,n = n,n.next } p } + fcn first { n,p := self,self; while(n){ p,n = n,n.prev } p } + fcn walker(forward=True){ + dir:=forward and "next" or "prev"; + Walker(fcn(rn,dir){ + if(not (n:=rn.value)) return(Void.Stop); + rn.set(n.setVar(dir)); + n.value; + }.fp(Ref(self),dir)) + } +} diff --git a/Task/Doubly-linked-list-Definition/Zkl/doubly-linked-list-definition-2.zkl b/Task/Doubly-linked-list-Definition/Zkl/doubly-linked-list-definition-2.zkl new file mode 100644 index 0000000000..cc13b5bf91 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/Zkl/doubly-linked-list-definition-2.zkl @@ -0,0 +1,6 @@ +a:=Node("a"); +a.append("c").append("d"); +a.last().append("e"); +a.last().first().append("b"); +foreach n in (a){ print(n," ") } println(); +foreach n in (a.last().walker(False)){ print(n," ") } println(); diff --git a/Task/Doubly-linked-list-Element-definition/Bracmat/doubly-linked-list-element-definition.bracmat b/Task/Doubly-linked-list-Element-definition/Bracmat/doubly-linked-list-element-definition.bracmat new file mode 100644 index 0000000000..92a268e9a5 --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/Bracmat/doubly-linked-list-element-definition.bracmat @@ -0,0 +1 @@ +link=(prev=) (next=) (data=) 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.kotlin new file mode 100644 index 0000000000..189b78addc --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/Kotlin/doubly-linked-list-element-definition.kotlin @@ -0,0 +1,24 @@ +// version 1.1.2 + +class Node(var data: T, var prev: Node? = null, var next: Node? = null) { + override fun toString(): String { + val sb = StringBuilder(this.data.toString()) + var node = this.next + while (node != null) { + sb.append(" -> ", node.data.toString()) + node = node.next + } + return sb.toString() + } +} + +fun main(args: Array) { + val n1 = Node(1) + val n2 = Node(2, n1) + n1.next = n2 + val n3 = Node(3, n2) + n2.next = n3 + println(n1) + println(n2) + println(n3) +} diff --git a/Task/Doubly-linked-list-Element-definition/Oberon-2/doubly-linked-list-element-definition.oberon-2 b/Task/Doubly-linked-list-Element-definition/Oberon-2/doubly-linked-list-element-definition.oberon-2 new file mode 100644 index 0000000000..58f0a311a8 --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/Oberon-2/doubly-linked-list-element-definition.oberon-2 @@ -0,0 +1,19 @@ +MODULE Box; +TYPE + Object* = POINTER TO ObjectDesc; + ObjectDesc* = (* ABSTRACT *) RECORD + END; + + (* ... *) +END Box. + +MODULE Collections; +TYPE + Node* = POINTER TO NodeDesc; + NodeDesc* = (* ABSTRACT *) RECORD + prev-,next-: Node; + value-: Box.Object; + END; + + (* ... *) +END Collections. diff --git a/Task/Doubly-linked-list-Element-definition/Phix/doubly-linked-list-element-definition.phix b/Task/Doubly-linked-list-Element-definition/Phix/doubly-linked-list-element-definition.phix new file mode 100644 index 0000000000..6b1e34c773 --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/Phix/doubly-linked-list-element-definition.phix @@ -0,0 +1,4 @@ +enum NEXT,PREV,DATA +type slnode(object x) + return (sequence(x) and length(x)=DATA and udt(x[DATA]) and integer(x[NEXT] and integer(x[PREV])) +end type 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 index 86b2840c1a..f05fe72380 100644 --- 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 @@ -1,17 +1,12 @@ -pub struct LinkedList { // User-facing implementation - length: usize, - list_head: Link, - list_tail: Rawlink>, -} - -type Link = Option>>; // Type definition - -struct Rawlink { // Pointer is wrapped in struct so that Option-like methods can be added to it later (wrappers around NULL checks) - p: *mut T, // Raw mutable pointer +pub struct LinkedList { + head: Option>>, + tail: Option>>, + len: usize, + marker: PhantomData>>, // Indicates that we logically own a boxed (owned pointer) Node> } struct Node { - next: Link, - prev: Rawlink>, - value: T, + next: Option>>, + prev: Option>>, + element: T, } diff --git a/Task/Doubly-linked-list-Element-definition/Zkl/doubly-linked-list-element-definition-1.zkl b/Task/Doubly-linked-list-Element-definition/Zkl/doubly-linked-list-element-definition-1.zkl new file mode 100644 index 0000000000..8256bba855 --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/Zkl/doubly-linked-list-element-definition-1.zkl @@ -0,0 +1,5 @@ +class Node{ + fcn init(_value,_prev=Void,_next=Void) + { var value=_value, prev=_prev, next=_next; } + fcn toString{ value.toString() } +} diff --git a/Task/Doubly-linked-list-Element-definition/Zkl/doubly-linked-list-element-definition-2.zkl b/Task/Doubly-linked-list-Element-definition/Zkl/doubly-linked-list-element-definition-2.zkl new file mode 100644 index 0000000000..5ab9d96ef2 --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/Zkl/doubly-linked-list-element-definition-2.zkl @@ -0,0 +1,3 @@ +a,b:=Node(1),Node("three"); +a.next=b; b.prev=a; +println(a.next," ",b.prev); 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.kotlin new file mode 100644 index 0000000000..def50e2240 --- /dev/null +++ b/Task/Doubly-linked-list-Element-insertion/Kotlin/doubly-linked-list-element-insertion.kotlin @@ -0,0 +1,30 @@ +// version 1.1.2 + +class Node(var data: T, var prev: Node? = null, var next: Node? = null) { + override fun toString(): String { + val sb = StringBuilder(this.data.toString()) + var node = this.next + while (node != null) { + sb.append(" -> ", node.data.toString()) + node = node.next + } + return sb.toString() + } +} + +fun insert(after: Node, new: Node) { + new.next = after.next + if (after.next != null) after.next!!.prev = new + new.prev = after + after.next = new +} + +fun main(args: Array) { + val a = Node(1) + val b = Node(3, a) + a.next = b + println("Before insertion : $a") + val c = Node(2) + insert(after = a, new = c) + println("After insertion : $a") +} diff --git a/Task/Doubly-linked-list-Element-insertion/Oberon-2/doubly-linked-list-element-insertion.oberon-2 b/Task/Doubly-linked-list-Element-insertion/Oberon-2/doubly-linked-list-element-insertion.oberon-2 new file mode 100644 index 0000000000..dc106be230 --- /dev/null +++ b/Task/Doubly-linked-list-Element-insertion/Oberon-2/doubly-linked-list-element-insertion.oberon-2 @@ -0,0 +1,12 @@ + PROCEDURE (dll: DLList) InsertAfter*(p: Node; o: Box.Object); + VAR + n: Node; + BEGIN + n := NewNode(o); + n.prev := p; + n.next := p.next; + IF p.next # NIL THEN p.next.prev := n END; + p.next := n; + IF p = dll.last THEN dll.last := n END; + INC(dll.size) + END InsertAfter; diff --git a/Task/Doubly-linked-list-Element-insertion/Phix/doubly-linked-list-element-insertion.phix b/Task/Doubly-linked-list-Element-insertion/Phix/doubly-linked-list-element-insertion.phix new file mode 100644 index 0000000000..e4886ab954 --- /dev/null +++ b/Task/Doubly-linked-list-Element-insertion/Phix/doubly-linked-list-element-insertion.phix @@ -0,0 +1,18 @@ +enum NEXT,PREV,DATA +constant empty_dll = {{1,1}} +sequence dll = empty_dll + +procedure insert_after(object data, integer pos=1) +integer prv = dll[pos][PREV] + dll = append(dll,{pos,prv,data}) + if prv!=0 then + dll[prv][NEXT] = length(dll) + end if + dll[pos][PREV] = length(dll) +end procedure + +insert_after("ONE") +insert_after("TWO") +insert_after("THREE") + +?dll diff --git a/Task/Doubly-linked-list-Element-insertion/Zkl/doubly-linked-list-element-insertion-1.zkl b/Task/Doubly-linked-list-Element-insertion/Zkl/doubly-linked-list-element-insertion-1.zkl new file mode 100644 index 0000000000..4376d8d89c --- /dev/null +++ b/Task/Doubly-linked-list-Element-insertion/Zkl/doubly-linked-list-element-insertion-1.zkl @@ -0,0 +1,11 @@ +class Node{ + fcn init(_value,_prev=Void,_next=Void) + { var value=_value, prev=_prev, next=_next; } + fcn toString{ value.toString() } + fcn append(value){ + b,c := Node(value,self,next),next; + next=b; + if(c) c.prev=b; + b + } +} diff --git a/Task/Doubly-linked-list-Element-insertion/Zkl/doubly-linked-list-element-insertion-2.zkl b/Task/Doubly-linked-list-Element-insertion/Zkl/doubly-linked-list-element-insertion-2.zkl new file mode 100644 index 0000000000..6c103adb30 --- /dev/null +++ b/Task/Doubly-linked-list-Element-insertion/Zkl/doubly-linked-list-element-insertion-2.zkl @@ -0,0 +1,3 @@ +a:=Node("a"); +a.append("b").append("c"); +println(a," ",a.next," ",a.next.next); diff --git a/Task/Doubly-linked-list-Traversal/Fortran/doubly-linked-list-traversal.f b/Task/Doubly-linked-list-Traversal/Fortran/doubly-linked-list-traversal.f deleted file mode 100644 index f04c1668f3..0000000000 --- a/Task/Doubly-linked-list-Traversal/Fortran/doubly-linked-list-traversal.f +++ /dev/null @@ -1,48 +0,0 @@ -class DoubleLink (value, prev_link, next_link) - - # insert given node after this one, removing its existing connections - method insert_after (node) - node.prev_link := self - if (\next_link) then next_link.prev_link := node - node.next_link := next_link - self.next_link := node - end - - # use a generator to traverse - # - keep suspending the prev/next link until a null node is reached - method traverse_backwards () - current := self - while \current do { - suspend current - current := current.prev_link - } - end - - method traverse_forwards () - current := self - while \current do { - suspend current - current := current.next_link - } - end - - initially (value, prev_link, next_link) - self.value := value - self.prev_link := prev_link # links are 'null' if not given - self.next_link := next_link -end - -procedure main () - l1 := DoubleLink (1) - l2 := DoubleLink (2) - l1.insert_after (l2) - l1.insert_after (DoubleLink (3)) - - write ("Traverse from beginning to end") - every (node := l1.traverse_forwards ()) do - write (node.value) - - write ("Traverse from end to beginning") - every (node := l2.traverse_backwards ()) do - write (node.value) -end diff --git a/Task/Doubly-linked-list-Traversal/Kotlin/doubly-linked-list-traversal.kotlin b/Task/Doubly-linked-list-Traversal/Kotlin/doubly-linked-list-traversal.kotlin new file mode 100644 index 0000000000..f7b620c8fe --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/Kotlin/doubly-linked-list-traversal.kotlin @@ -0,0 +1,80 @@ +// version 1.1.2 + +class LinkedList { + class Node(var data: E, var prev: Node? = null, var next: Node? = null) { + override fun toString(): String { + val sb = StringBuilder(this.data.toString()) + var node = this.next + while (node != null) { + sb.append(" -> ", node.data.toString()) + node = node.next + } + return sb.toString() + } + } + + var first: Node? = null + var last: Node? = null + + fun addFirst(value: E) { + if (first == null) { + first = Node(value) + last = first + } + else { + val node = first!! + first = Node(value, null, node) + node.prev = first + } + } + + fun addLast(value: E) { + if (last == null) { + last = Node(value) + first = last + } + else { + val node = last!! + last = Node(value, node, null) + node.next = last + } + } + + fun insert(after: Node?, value: E) { + if (after == null) + addFirst(value) + else if (after == last) + addLast(value) + else { + val next = after.next + val new = Node(value, after, next) + after.next = new + if (next != null) next.prev = new + } + } + + override fun toString() = first.toString() + + fun firstToLast() = first?.toString() ?: "" + + fun lastToFirst(): String { + if (last == null) return "" + val sb = StringBuilder(last.toString()) + var node = last!!.prev + while (node != null) { + sb.append(" -> ", node.data.toString()) + node = node.prev + } + return sb.toString() + } +} + +fun main(args: Array) { + val ll = LinkedList() + ll.addFirst(1) + ll.addLast(4) + ll.insert(ll.first, 2) + ll.insert(ll.last!!.prev, 3) + println("First to last : ${ll.firstToLast()}") + println("Last to first : ${ll.lastToFirst()}") +} diff --git a/Task/Doubly-linked-list-Traversal/Oberon-2/doubly-linked-list-traversal.oberon-2 b/Task/Doubly-linked-list-Traversal/Oberon-2/doubly-linked-list-traversal.oberon-2 new file mode 100644 index 0000000000..cb6f5b30fb --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/Oberon-2/doubly-linked-list-traversal.oberon-2 @@ -0,0 +1,30 @@ +MODULE Collections; +IMPORT Box; + +TYPE + Action = PROCEDURE (o: Box.Object); + + PROCEDURE (dll: DLList) GoForth*(do: Action); + VAR + iter: Node; + BEGIN + iter := dll.first; + WHILE iter # NIL DO + do(iter.value); + iter := iter.next + END + END GoForth; + + PROCEDURE (dll: DLList) GoBack*(do: Action); + VAR + iter: Node; + BEGIN + ASSERT(dll.last # NIL); + iter := dll.last; + WHILE iter # NIL DO + do(iter.value); + iter := iter.prev + END + END GoBack; + +END Collections. diff --git a/Task/Doubly-linked-list-Traversal/Phix/doubly-linked-list-traversal.phix b/Task/Doubly-linked-list-Traversal/Phix/doubly-linked-list-traversal.phix new file mode 100644 index 0000000000..0a4fddefb7 --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/Phix/doubly-linked-list-traversal.phix @@ -0,0 +1,29 @@ +enum NEXT,PREV,DATA +constant empty_dll = {{1,1}} +sequence dll = empty_dll + +procedure insert_after(object data, integer pos=1) +integer prv = dll[pos][PREV] + dll = append(dll,{pos,prv,data}) + if prv!=0 then + dll[prv][NEXT] = length(dll) + end if + dll[pos][PREV] = length(dll) +end procedure + +insert_after("ONE") +insert_after("TWO") +insert_after("THREE") + +?dll + +procedure show(integer d) +integer idx = dll[1][d] + while idx!=1 do + ?dll[idx][DATA] + idx = dll[idx][d] + end while +end procedure +show(NEXT) +?"==" +show(PREV) diff --git a/Task/Doubly-linked-list-Traversal/Zkl/doubly-linked-list-traversal-1.zkl b/Task/Doubly-linked-list-Traversal/Zkl/doubly-linked-list-traversal-1.zkl new file mode 100644 index 0000000000..4376d8d89c --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/Zkl/doubly-linked-list-traversal-1.zkl @@ -0,0 +1,11 @@ +class Node{ + fcn init(_value,_prev=Void,_next=Void) + { var value=_value, prev=_prev, next=_next; } + fcn toString{ value.toString() } + fcn append(value){ + b,c := Node(value,self,next),next; + next=b; + if(c) c.prev=b; + b + } +} diff --git a/Task/Doubly-linked-list-Traversal/Zkl/doubly-linked-list-traversal-2.zkl b/Task/Doubly-linked-list-Traversal/Zkl/doubly-linked-list-traversal-2.zkl new file mode 100644 index 0000000000..aa302301ac --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/Zkl/doubly-linked-list-traversal-2.zkl @@ -0,0 +1,5 @@ +a,c := Node("a"), a.append("b").append("c"); +n:=a; while(n){ print(n," "); n=n.next } +println(); +n:=c; while(n){ print(n," "); n=n.prev } +println(); diff --git a/Task/Dragon-curve/Gnuplot/dragon-curve-1.gnuplot b/Task/Dragon-curve/Gnuplot/dragon-curve-1.gnuplot new file mode 100644 index 0000000000..222b33154a --- /dev/null +++ b/Task/Dragon-curve/Gnuplot/dragon-curve-1.gnuplot @@ -0,0 +1,51 @@ +# Return the position of the highest 1-bit in n. +# The least significant bit is position 0. +# For example n=13 is binary "1101" and the high bit is pos=3. +# If n==0 then the return is 0. +# Arranging the test as n>=2 avoids infinite recursion if n==NaN (any +# comparison involving NaN is always false). +# +high_bit_pos(n) = (n>=2 ? 1+high_bit_pos(int(n/2)) : 0) + +# Return 0 or 1 for the bit at position "pos" in n. +# pos==0 is the least significant bit. +# +bit(n,pos) = int(n / 2**pos) & 1 + +# dragon(n) returns a complex number which is the position of the +# dragon curve at integer point "n". n=0 is the first point and is at +# the origin {0,0}. Then n=1 is at {1,0} which is x=1,y=0, etc. If n +# is not an integer then the point returned is for int(n). +# +# The calculation goes by bits of n from high to low. Gnuplot doesn't +# have iteration in functions, but can go recursively from +# pos=high_bit_pos(n) down to pos=0, inclusive. +# +# mul() rotates by +90 degrees (complex "i") at bit transitions 0->1 +# or 1->0. add() is a vector (i+1)**pos for each 1-bit, but turned by +# factor "i" when in a "reversed" section of curve, which is when the +# bit above is also a 1-bit. +# +dragon(n) = dragon_by_bits(n, high_bit_pos(n)) +dragon_by_bits(n,pos) \ + = (pos>=0 ? add(n,pos) + mul(n,pos)*dragon_by_bits(n,pos-1) : 0) + +add(n,pos) = (bit(n,pos) ? (bit(n,pos+1) ? {0,1} * {1,1}**pos \ + : {1,1}**pos) \ + : 0) +mul(n,pos) = (bit(n,pos) == bit(n,pos+1) ? 1 : {0,1}) + +# Plot the dragon curve from 0 to "length" with line segments. +# "trange" and "samples" are set so the parameter t runs through +# integers t=0 to t=length inclusive. +# +# Any trange works, it doesn't have to start at 0. But must have +# enough "samples" that all integers t in the range are visited, +# otherwise vertices in the curve would be missed. +# +length=256 +set trange [0:length] +set samples length+1 +set parametric +set key off +plot real(dragon(t)),imag(dragon(t)) with lines diff --git a/Task/Dragon-curve/Gnuplot/dragon-curve-2.gnuplot b/Task/Dragon-curve/Gnuplot/dragon-curve-2.gnuplot new file mode 100644 index 0000000000..c7cef0604a --- /dev/null +++ b/Task/Dragon-curve/Gnuplot/dragon-curve-2.gnuplot @@ -0,0 +1,20 @@ +## plotdcf.gp 1/11/17 aev +## Plotting a Dragon curve fractal to the png-file. +## Note: assign variables: ord (order), clr (color), filename and ttl (before using load command). +## ord (order) # a.k.a. level - defines size of fractal (also number of mini-curves). +reset +set style arrow 1 nohead linewidth 1 lc rgb @clr +set term png size 1024,1024 +ofn=filename.ord."gp.png" # Output file name +set output ofn +ttl="Dragon curve fractal: order ".ord +set title ttl font "Arial:Bold,12" +unset border; unset xtics; unset ytics; unset key; +set xrange [0:1.0]; set yrange [0:1.0]; +dragon(n, x, y, dx, dy) = n >= ord ? \ + sprintf("set arrow from %f,%f to %f,%f as 1;", x, y, x + dx, y + dy) : \ + dragon(n + 1, x, y, (dx - dy) / 2, (dy + dx) / 2) . \ + dragon(n + 1, x + dx, y + dy, - (dx + dy) / 2, (dx - dy) / 2); +eval(dragon(0, 0.2, 0.4, 0.7, 0.0)) +plot -100 +set output diff --git a/Task/Dragon-curve/Gnuplot/dragon-curve-3.gnuplot b/Task/Dragon-curve/Gnuplot/dragon-curve-3.gnuplot new file mode 100644 index 0000000000..1afaf336bd --- /dev/null +++ b/Task/Dragon-curve/Gnuplot/dragon-curve-3.gnuplot @@ -0,0 +1,20 @@ +## pDCF.gp 1/11/17 aev +## Plotting 3 Dragon curve fractals. +## Note: assign variables: ord (order), clr (color), filename and ttl (before using load command). +## ord (order) # a.k.a. level - defines size of fractal (also number of dots). +#cd 'C:\gnupData' + +##DCF11 +ord=11; clr = '"red"'; +filename = "DCF"; ttl = "Dragon curve fractal, order ".ord; +load "plotdcf.gp" + +##DCF13 +ord=13; clr = '"brown"'; +filename = "DCF"; ttl = "Dragon curve fractal, order ".ord; +load "plotdcf.gp" + +##DCF15 +ord=15; clr = '"navy"'; +filename = "DCF"; ttl = "Dragon curve fractal, order ".ord; +load "plotdcf.gp" diff --git a/Task/Dragon-curve/JavaScript/dragon-curve-3.js b/Task/Dragon-curve/JavaScript/dragon-curve-3.js new file mode 100644 index 0000000000..b555e17189 --- /dev/null +++ b/Task/Dragon-curve/JavaScript/dragon-curve-3.js @@ -0,0 +1,42 @@ + + + + + + +

    Please input order, scale, x-shift, y-shift, color:

    + + + + + + +

    Dragon curve

    + + + diff --git a/Task/Dragon-curve/jq/dragon-curve-1.jq b/Task/Dragon-curve/Jq/dragon-curve-1.jq similarity index 100% rename from Task/Dragon-curve/jq/dragon-curve-1.jq rename to Task/Dragon-curve/Jq/dragon-curve-1.jq diff --git a/Task/Dragon-curve/jq/dragon-curve-2.jq b/Task/Dragon-curve/Jq/dragon-curve-2.jq similarity index 100% rename from Task/Dragon-curve/jq/dragon-curve-2.jq rename to Task/Dragon-curve/Jq/dragon-curve-2.jq diff --git a/Task/Dragon-curve/jq/dragon-curve-3.jq b/Task/Dragon-curve/Jq/dragon-curve-3.jq similarity index 100% rename from Task/Dragon-curve/jq/dragon-curve-3.jq rename to Task/Dragon-curve/Jq/dragon-curve-3.jq diff --git a/Task/Dragon-curve/Kotlin/dragon-curve.kotlin b/Task/Dragon-curve/Kotlin/dragon-curve.kotlin new file mode 100644 index 0000000000..5bb54d3bcd --- /dev/null +++ b/Task/Dragon-curve/Kotlin/dragon-curve.kotlin @@ -0,0 +1,55 @@ +// version 1.0.6 + +import java.awt.Color +import java.awt.Graphics +import javax.swing.JFrame + +class DragonCurve(iter: Int) : JFrame("Dragon Curve") { + private val turns: MutableList + private val startingAngle: Double + private val side: Double + + init { + setBounds(100, 100, 800, 600) + defaultCloseOperation = EXIT_ON_CLOSE + turns = getSequence(iter) + startingAngle = -iter * Math.PI / 4 + side = 400.0 / Math.pow(2.0, iter / 2.0) + } + + fun getSequence(iterations: Int): MutableList { + val turnSequence = mutableListOf() + for (i in 0 until iterations) { + val copy = mutableListOf() + copy.addAll(turnSequence) + copy.reverse() + turnSequence.add(1) + copy.mapTo(turnSequence) { -it } + } + return turnSequence + } + + override fun paint(g: Graphics) { + g.color = Color.BLUE + var angle = startingAngle + var x1 = 230 + var y1 = 350 + var x2 = x1 + (Math.cos(angle) * side).toInt() + var y2 = y1 + (Math.sin(angle) * side).toInt() + g.drawLine(x1, y1, x2, y2) + x1 = x2 + y1 = y2 + for (turn in turns) { + angle += turn * Math.PI / 2.0 + x2 = x1 + (Math.cos(angle) * side).toInt() + y2 = y1 + (Math.sin(angle) * side).toInt() + g.drawLine(x1, y1, x2, y2) + x1 = x2 + y1 = y2 + } + } +} + +fun main(args: Array) { + DragonCurve(14).isVisible = true +} diff --git a/Task/Dragon-curve/Phix/dragon-curve.phix b/Task/Dragon-curve/Phix/dragon-curve.phix new file mode 100644 index 0000000000..6d4e85b8f6 --- /dev/null +++ b/Task/Dragon-curve/Phix/dragon-curve.phix @@ -0,0 +1,68 @@ +-- +-- demo\rosetta\DragonCurve.exw +-- +include pGUI.e + +Ihandle dlg, canvas +cdCanvas cddbuffer, cdcanvas + +integer colour = 0 + +procedure Dragon(integer depth, atom x1, y1, x2, y2) + depth -= 1 + if depth<=0 then + cdCanvasSetForeground(cddbuffer, colour) + cdCanvasLine(cddbuffer, x1, y1, x2, y2) + -- (some interesting colour patterns emerge) + colour += 2 +-- colour += 2000 +-- colour += #100 + else + atom dx = x2-x1, dy = y2-y1, + nx = x1+(dx-dy)/2, + ny = y1+(dx+dy)/2 + Dragon(depth,x1,y1,nx,ny) + Dragon(depth,x2,y2,nx,ny) + end if +end procedure + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) + cdCanvasActivate(cddbuffer) + cdCanvasClear(cddbuffer) + -- (note: depths over 21 take a long time to draw, + -- depths <= 16 look a little washed out) + Dragon(17,100,100,100+256,100) + cdCanvasFlush(cddbuffer) + return IUP_DEFAULT +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + cdCanvasSetBackground(cddbuffer, CD_PARCHMENT) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "420x290") + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + + dlg = IupDialog(canvas,"RESIZE=NO") + IupSetAttribute(dlg, "TITLE", "Dragon Curve") + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + + IupShow(dlg) + IupMainLoop() + IupClose() +end procedure + +main() diff --git a/Task/Dragon-curve/R/dragon-curve.r b/Task/Dragon-curve/R/dragon-curve-1.r similarity index 100% rename from Task/Dragon-curve/R/dragon-curve.r rename to Task/Dragon-curve/R/dragon-curve-1.r diff --git a/Task/Dragon-curve/R/dragon-curve-2.r b/Task/Dragon-curve/R/dragon-curve-2.r new file mode 100644 index 0000000000..2d55f9bc41 --- /dev/null +++ b/Task/Dragon-curve/R/dragon-curve-2.r @@ -0,0 +1,33 @@ +# Generate and plot Dragon curve. +# translation of JavaScript v.#2: http://rosettacode.org/wiki/Dragon_curve#JavaScript +# 2/27/16 aev +# gpDragonCurve(ord, clr, fn, d, as, xsh, ysh) +# Where: ord - order (defines the number of line segments); +# clr - color, fn - file name (.ext will be added), d - segment length, +# as - axis scale, xsh - x-shift, ysh - y-shift +gpDragonCurve <- function(ord, clr, fn, d, as, xsh, ysh) { + cat(" *** START:", date(), "order=",ord, "color=",clr, "\n"); + d=10; m=640; ms=as*m; n=bitwShiftL(1, ord); + c=c1=c2=c2x=c2y=i1=0; x=y=x1=y1=0; + if(fn=="") {fn="DCR"} + pf=paste0(fn, ord, ".png"); + ttl=paste0("Dragon curve, ord=",ord); + cat(" *** Plot file -", pf, "title:", ttl, "n=",n, "\n"); + plot(NA, xlim=c(-ms,ms), ylim=c(-ms,ms), xlab="", ylab="", main=ttl); + for (i in 0:n) { + segments(x1+xsh, y1+ysh, x+xsh, y+ysh, col=clr); x1=x; y1=y; + c1=bitwAnd(c, 1); c2=bitwAnd(c, 2); + c2x=d; if(c2>0) {c2x=(-1)*d}; c2y=(-1)*c2x; + if(c1>0) {y=y+c2y} else {x=x+c2x} + i1=i+1; ii=bitwAnd(i1, -i1); c=c+i1/ii; + } + dev.copy(png, filename=pf, width=m, height=m); # plot to png-file + dev.off(); graphics.off(); # Cleaning + cat(" *** END:",date(),"\n"); +} +## Testing samples: +gpDragonCurve(7, "red", "", 20, 0.2, -30, -30) +##gpDragonCurve(11, "red", "", 10, 0.6, 100, 200) +gpDragonCurve(13, "navy", "", 10, 1, 300, -200) +##gpDragonCurve(15, "darkgreen", "", 10, 2, -450, -500) +gpDragonCurve(16, "darkgreen", "", 10, 3, -1050, -500) diff --git a/Task/Dragon-curve/REXX/dragon-curve.rexx b/Task/Dragon-curve/REXX/dragon-curve.rexx index 4b06347c6e..9d06304650 100644 --- a/Task/Dragon-curve/REXX/dragon-curve.rexx +++ b/Task/Dragon-curve/REXX/dragon-curve.rexx @@ -1,35 +1,31 @@ /*REXX program creates & draws an ASCII Dragon Curve (or Harter-Heighway dragon curve).*/ -z=1; d.=1; d.L=-d.; @.=' '; x=0; x2=x; y=0; y2=y; @.x.y="∙" -plot_pts = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZΘ' /*plot chrs*/ -minX=0; maxX=0; minY=0; maxY=0 /*assign various constants & variables.*/ +d.=1; d.L=-d.; @.=' '; x=0; x2=x; y=0; y2=y; z=d.; @.x.y="∙" +plot_pts = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZΘ' /*plot chars*/ +minX=0; maxX=0; minY=0; maxY=0 /*assign various constants & variables.*/ parse arg # p c . /*#: number of iterations; P=init dir.*/ if #=='' | #=="," then #=11 /*Not specified? Then use the default.*/ -if p=='' | p=="," then p=0 /* " " " " " " */ +if p=='' | p=="," then p= 'north'; upper p /* " " " " " " */ if c=='' then c=plot_pts /* " " " " " " */ if length(c)==2 then c=x2c(c) /*was a hexadecimal code specified? */ if length(c)==3 then c=d2c(c) /* " " decimal " " */ -$= /*assign a null to dragon curve string.*/ - do # /* [↓] create (part of) a dragon curve*/ - $=$'R'reverse( translate($, "RL", 'LR') ) /*append char, flip, and then reverse.*/ - end /*#*/ /* [↑] TRANSLATE (flip) the characters*/ - /* [↓] create the dragon curve. */ - do j=1 for length($); _=substr($, j, 1) /*obtain the next direction for curve. */ - p= (p+d._)//4; if p<0 then p=p+4 /*move dragon curve in a new direction.*/ - if p==0 then do; y=y+1; y2=y+1; end /*curve is going east cartologically.*/ - if p==1 then do; x=x+1; x2=x+1; end /* " " south " */ - if p==2 then do; y=y-1; y2=y-1; end /* " " west " */ - if p==3 then do; x=x-1; x2=x-1; end /* " " north " */ - if j>2**z then z=z+1 /*identify the dragon curve being built*/ +p=translate(left(p,1), 0123, 'NESW'); $= /*get the orientation for dragon curve.*/ + do #; $=$'R'reverse(translate($,"RL",'LR')) /*create the start of a dragon curve. */ + end /*#*/ /*append char, flip, and then reverse.*/ + /* [↓] create the rest of dragon curve*/ + do j=1 for length($); _=substr($,j,1) /*get next cardinal direction for curve*/ + p= (p+d._)//4; if p<0 then p=p+4 /*move dragon curve in a new direction.*/ + if p==0 then do; y=y+1; y2=y+1; end /*curve is going east cartologically.*/ + if p==1 then do; x=x+1; x2=x+1; end /* " " south " */ + if p==2 then do; y=y-1; y2=y-1; end /* " " west " */ + if p==3 then do; x=x-1; x2=x-1; end /* " " north " */ + if j>2**z then z=z+1 /*identify a part of curve being built.*/ !=substr(c,z,1); if !==' ' then !=right(c,1) /*choose plot point character (glyph). */ @.x.y=!; @.x2.y2=! /*draw part of the dragon curve. */ minX=min(minX,x,x2); maxX=max(maxX,x,x2); x=x2 /*define the min & max X graph limits*/ minY=min(minY,y,y2); maxY=max(maxY,y,y2); y=y2 /* " " " " " Y " " */ - end /*j*/ /* [↑] process all of $ char string.*/ - /* [↓] display the dragon curve. */ - do r=minX to maxX; a= /*nullify the line that will bee drawn.*/ - do c=minY to maxY /*create a line (row) of curve points. */ - a=a || @.r.c /*append single column of row at a time*/ - end /*c*/ - a=strip(a, 'T') /*be nice and strip any trailing blanks*/ - if a\=='' then say a /*display a line (row) of curve points.*/ - end /*r*/ /*stick a fork in it, we're all done. */ + end /*j*/ /* [↑] process all of $ char string.*/ + do r=minX to maxX; a= /*nullify the line that will be drawn. */ + do c=minY to maxY; a=a || @.r.c /*create a line (row) of curve points. */ + end /*c*/ /* [↑] append a single column of a row.*/ + if a\='' then say strip(a, 'T') /*display a line (row) of curve points.*/ + end /*r*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Dragon-curve/SPL/dragon-curve.spl b/Task/Dragon-curve/SPL/dragon-curve.spl new file mode 100644 index 0000000000..b55e8d84e2 --- /dev/null +++ b/Task/Dragon-curve/SPL/dragon-curve.spl @@ -0,0 +1,38 @@ +levels = 16 +level = 0 +step = 1 +> + draw(level) + level += step + ? level>levels + step = -1 + level += step*2 + . + ? level=0, step = 1 + #.delay(1) +< + +draw(level)= + mx,my = #.scrsize() + fs = #.min(mx,my)/2 + r = fs/2^((level-1)/2) + x = mx/2+fs*#.sqrt(2)/2 + y = my/2+fs/4 + a = #.pi/4*(level-2) + #.scroff() + #.scrclear() + #.drawline(x,y,x,y) + ss = 2^level-1 + > i, 0..ss + ? #.and(#.and(i,-i)*2,i) + a += #.pi/2 + ! + a -= #.pi/2 + . + x += r*#.cos(a) + y += r*#.sin(a) + #.drawcolor(#.hsv2rgb(i/(ss+1)*360,1,1):3) + #.drawline(x,y) + < + #.scr() +. diff --git a/Task/Dragon-curve/Scilab/dragon-curve.scilab b/Task/Dragon-curve/Scilab/dragon-curve.scilab new file mode 100644 index 0000000000..6eac28c635 --- /dev/null +++ b/Task/Dragon-curve/Scilab/dragon-curve.scilab @@ -0,0 +1,36 @@ +n_folds=10 + +folds=[]; +folds=[0 1]; + +old_folds=[]; +vectors=[]; + +i=[]; + +for i=2:n_folds+1 + + curve_length=length(folds); + + vectors=folds(1:curve_length-1)-folds(curve_length); + + vectors=vectors.*exp(90/180*%i*%pi); + + new_folds=folds(curve_length)+vectors; + + j=curve_length; + + while j>1 + folds=[folds new_folds(j-1)] + j=j-1; + end + +end + +scf(0); clf(); +xname("Dragon curve: "+string(n_folds)+" folds") + +plot2d(real(folds),imag(folds),5); + +set(gca(),"isoview","on"); +set(gca(),"axes_visible",["off","off","off"]); diff --git a/Task/Dragon-curve/Sidef/dragon-curve.sidef b/Task/Dragon-curve/Sidef/dragon-curve.sidef index 69c2e4e24c..e5f61dd4b0 100644 --- a/Task/Dragon-curve/Sidef/dragon-curve.sidef +++ b/Task/Dragon-curve/Sidef/dragon-curve.sidef @@ -1,19 +1,19 @@ -define halfpi = Math.pi/2; +define halfpi = Num.pi/2 # Computing the dragon with a L-System -var dragon = 'FX'; +var dragon = 'FX' { - dragon.gsub!('X', 'x+yF+'); - dragon.gsub!('Y', '-Fx-y'); - dragon.tr!('xy', 'XY'); -} * 10; + dragon.gsub!('X', 'x+yF+') + dragon.gsub!('Y', '-Fx-y') + dragon.tr!('xy', 'XY') +} * 10 # Drawing the dragon in SVG -var (x, y) = (100, 100); -var theta = 0; -var r = 2; +var (x, y) = (100, 100) +var theta = 0 +var r = 2 -print <<'EOT'; +print <<'EOT' @@ -24,14 +24,14 @@ EOT dragon.each { |c| given(c) { when ('F') { - printf("\n"); + printf("\n") } when ('+') { theta += halfpi } when ('-') { theta -= halfpi } } } -print ''; +print '' diff --git a/Task/Dragon-curve/Zkl/dragon-curve.zkl b/Task/Dragon-curve/Zkl/dragon-curve.zkl new file mode 100644 index 0000000000..9a651822f4 --- /dev/null +++ b/Task/Dragon-curve/Zkl/dragon-curve.zkl @@ -0,0 +1,25 @@ +println(0'||"\n" + 0'||"\n" + 0'||); + +order:=13.0; # akin to number of recursion steps +d_size:=1000.0; # size in pixels +pi:=(1.0).pi; +turn_angle:=pi/2; # turn angle of each segment, 90 degrees for the canonical dragon + +angle:=pi - (order * (pi/4)); # starting angle +len:=(d_size/1.5) / (2.0).sqrt().pow(order); # size of each segment +x:=d_size*5/6; y:=d_size*1/3; # starting point + +foreach i in ([0 .. (2.0).pow(order-1)]){ + # find which side to turn based on the iteration + angle += i.bitAnd(-i).shiftLeft(1).bitAnd(i) and -turn_angle or turn_angle; + + dx:=x + len * angle.sin(); dy:=y - len * angle.cos(); + println(""); + x=dx; y=dy; +} +println(""); diff --git a/Task/Nautical-bell/00META.yaml b/Task/Draw-a-clock/00META.yaml similarity index 100% rename from Task/Nautical-bell/00META.yaml rename to Task/Draw-a-clock/00META.yaml diff --git a/Task/Draw-a-clock/FreeBASIC/draw-a-clock.freebasic b/Task/Draw-a-clock/FreeBASIC/draw-a-clock.freebasic new file mode 100644 index 0000000000..d673807173 --- /dev/null +++ b/Task/Draw-a-clock/FreeBASIC/draw-a-clock.freebasic @@ -0,0 +1,83 @@ +' version 05-04-2017 +' compile with: fbc -s gui + +Const As Double deg2rad = Atn(1) / 45 +Const As UInteger w = 199, h = 199 +Const As UInteger x0 = w \ 2, y0 = h \ 2 ' center + +Dim As UInteger x, x1, x2, x3, y, y1, y2, y3 +Dim As String sys_time, press +Dim As Integer hours, minutes, seconds +Dim As Double angle, a_sin, a_cos + +ScreenRes w, h, 8 ' 8bit color depth (palette) +WindowTitle "Simple Clock" + +' create image 8bit (palette) and set pixels to 15 (white) +Dim clockdial As Any Ptr = ImageCreate(w, h, 15, 8) + +If clockdial = 0 Then + Print "Failed to create image." + Sleep + End -1 +End If + +' draw clockdial in memory +Circle clockdial, (x0, y0), 94 ,0 +Circle clockdial, (x0, y0), 90 ,0 + +For x = 0 To 174 Step 6 + a_sin = Sin(x * deg2rad) + a_cos = Cos(x * deg2rad) + + x1 = 94 * a_sin : y1 = 94 * a_cos + If x Mod 30 = 0 Then + x2 = 85 * a_sin : y2 = 85 * a_cos + Else + x2 = 90 * a_sin : y2 = 90 * a_cos + End If + + Line clockdial, (x0 + x1, y0 + y1) - (x0 + x2, y0 + y2), 0 + Line clockdial, (x0 - x1, y0 - y1) - (x0 - x2, y0 - y2), 0 +Next + +'draw clock +Do + sys_time = Time + hours = (sys_time[0] - Asc("0")) * 10 + sys_time[1] - Asc("0") + minutes = (sys_time[3] - Asc("0")) * 10 + sys_time[4] - Asc("0") + seconds = (sys_time[6] - Asc("0")) * 10 + sys_time[7] - Asc("0") + + If hours > 12 Then hours -= 12 + + angle = (180 - (hours * 30 + minutes / 2)) * deg2rad + x1 = 65 * Sin(angle) + y1 = 65 * Cos(angle) + + angle = (180 - (minutes * 6 + seconds / 10)) * deg2rad + x2 = 80 * Sin(angle) + y2 = 80 * Cos(angle) + + angle = (180 - seconds * 6) * deg2rad + x3 = 90 * Sin(angle) + y3 = 90 * Cos(angle) + + ScreenLock + ' load image, setting pixels + Put (0, 0), clockdial, PSet + Line (x0, y0) - (x0 + x1, y0 + y1), 1 ' hour hand blue + Line (x0, y0) - (x0 + x2, y0 + y2), 2 ' minute hand green + Line (x0, y0) - (x0 + x3, y0 + y3), 12 ' second hand red + ScreenUnLock + + Sleep 300, 1 ' wait 300 ms, don't respond to keys pressed + + ' press esc or mouse click on close window to stop program + press = InKey + If press = Chr(27) Or press = Chr(255) + "k" Then Exit Do + +Loop + +ImageDestroy(clockdial) + +End diff --git a/Task/Draw-a-clock/JavaScript/draw-a-clock.js b/Task/Draw-a-clock/JavaScript/draw-a-clock-1.js similarity index 100% rename from Task/Draw-a-clock/JavaScript/draw-a-clock.js rename to Task/Draw-a-clock/JavaScript/draw-a-clock-1.js diff --git a/Task/Draw-a-clock/JavaScript/draw-a-clock-2.js b/Task/Draw-a-clock/JavaScript/draw-a-clock-2.js new file mode 100644 index 0000000000..859baf2f05 --- /dev/null +++ b/Task/Draw-a-clock/JavaScript/draw-a-clock-2.js @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + diff --git a/Task/Draw-a-clock/Kotlin/draw-a-clock.kotlin b/Task/Draw-a-clock/Kotlin/draw-a-clock.kotlin new file mode 100644 index 0000000000..521c5a262b --- /dev/null +++ b/Task/Draw-a-clock/Kotlin/draw-a-clock.kotlin @@ -0,0 +1,71 @@ +// version 1.1 + +import java.awt.* +import java.time.LocalTime +import javax.swing.* + +class Clock : JPanel() { + private val degrees06: Float = (Math.PI / 30.0).toFloat() + private val degrees30: Float = degrees06 * 5.0f + private val degrees90: Float = degrees30 * 3.0f + private val size = 590 + private val spacing = 40 + private val diameter = size - 2 * spacing + private val cx = diameter / 2 + spacing + private val cy = cx + + init { + preferredSize = Dimension(size, size) + background = Color.white + Timer(1000) { + repaint() + }.start() + } + + override public fun paintComponent(gg: Graphics) { + super.paintComponent(gg) + val g = gg as Graphics2D + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + drawFace(g) + val time = LocalTime.now() + val hour = time.hour + val minute = time.minute + val second = time.second + var angle: Float = degrees90 - degrees06 * second + drawHand(g, angle, diameter / 2 - 30, Color.red) + val minsecs: Float = minute + second / 60.0f + angle = degrees90 - degrees06 * minsecs + drawHand(g, angle, diameter / 3 + 10, Color.black) + val hourmins: Float = hour + minsecs / 60.0f + angle = degrees90 - degrees30 * hourmins + drawHand(g, angle, diameter / 4 + 10, Color.black) + } + + private fun drawFace(g: Graphics2D) { + g.stroke = BasicStroke(2.0f) + g.color = Color.yellow + g.fillOval(spacing, spacing, diameter, diameter) + g.color = Color.black + g.drawOval(spacing, spacing, diameter, diameter) + } + + private fun drawHand(g: Graphics2D, angle: Float, radius: Int, color: Color) { + val x: Int = cx + (radius.toDouble() * Math.cos(angle.toDouble())).toInt() + val y: Int = cy - (radius.toDouble() * Math.sin(angle.toDouble())).toInt() + g.color = color + g.drawLine(cx, cy, x, y) + } +} + +fun main(args: Array) { + SwingUtilities.invokeLater { + val f = JFrame() + f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE + f.title = "Clock" + f.isResizable = false + f.add(Clock(), BorderLayout.CENTER) + f.pack() + f.setLocationRelativeTo(null) + f.isVisible = true + } +} diff --git a/Task/Draw-a-clock/OoRexx/draw-a-clock-1.rexx b/Task/Draw-a-clock/OoRexx/draw-a-clock-1.rexx new file mode 100644 index 0000000000..644dda89ab --- /dev/null +++ b/Task/Draw-a-clock/OoRexx/draw-a-clock-1.rexx @@ -0,0 +1,279 @@ +/* REXX --------------------------------------------------------------- +* 09.02.2014 Walter Pachl with a little, well considerable, help from +* a friend (Mark Miesfeld) +* 1) downstripped an example contained in the ooRexx distribution +* 2) constructed the squares for seconds, minutes, and hours +* 3) constructed second-, minute- and hour hand +* 5) removed lots of unnecessary code (courtesy mark Miesfeld again) +* 6) painted the background white +* 7) display date as well as time as text +* 21.02.2014 Attempts to add a minimize icon keep failing +*--------------------------------------------------------------------*/ + d = .drawDlg~new + if d~initCode <> 0 then do + say 'The Draw dialog was not created correctly. Aborting.' + return d~initCode + end + d~execute("SHOWTOP") + return 0 + +::requires "ooDialog.cls" +::requires 'rxmath' library + +::class 'drawDlg' subclass UserDialog + +::attribute interrupted unguarded + +::method init + expose walterFont + + forward class (super) continue + -- colornames: + -- 1 dark red 7 light grey 13 red + -- 2 dark green 8 pale green 14 light green + -- 3 dark yellow 9 light blue 15 yellow + -- 4 dark blue 10 white 16 blue + -- 5 purple 11 grey 17 pink + -- 6 blue grey 12 dark grey 18 turquoise + + self~interrupted = .true + + -- Create a font to write the nice big letters and digits + opts = .directory~new + opts~weight = 700 + walterFont = self~createFontEx("Arial",14,opts) + +-- if \self~createcenter(200, 230,"Walter's Clock","MINIMIZEBOX", ,"System",14) then + if \self~createcenter(200, 230,"Walter's Clock",,,"System",14) then + self~initCode = 1 +-- self~connectDraw(100, "clock", .true) + +::method defineDialog +-- self~createPushButton(/*IDC_PB_DRAW*/100,0,0,240,200,"NOTAB OWNERDRAW") -- The drawing surface. +-- self~createPushButton(/*IDC_PB_DRAW*/100,0,0,240,180,"DISABLED NOTAB") -- better. ??? + self~createPushButton(/*IDC_PB_DRAW*/100,0,0,200,200,"DISABLED NOTAB") -- better. ??? + + self~createPushButton(IDCANCEL,160,212, 35, 12,,"&Cancel") + +::method initDialog unguarded + expose x y dc myPen change + change = 0 + x = self~factorx + y = self~factory + dc = self~getButtonDC(100) + --+ myPen = self~createPen(1,'solid',0) + t = .TimeSpan~fromMicroSeconds(500000) -- .5 seconds + msg = .Message~new(self, 'clock') + alrm = .Alarm~new(t, msg) + +::method interrupt unguarded + + self~interrupted = .true + +::method cancel unguarded -- Stop the drawing program and quit. + expose x y + self~hide + self~interrupted = .true + return self~cancel:super + +::method leaving unguarded -- Best place to clean up resources + expose dc myPen walterFont + + --+ self~deleteObject(myPen) + self~freeButtonDC(/*IDC_PB_DRAW*/100,dc) + self~deleteFont(walterFont) + +::method clock unguarded /* draw individual pixels */ + expose x y dc myPen change walterFont +-- Say 'clock started' + mx = trunc(20*x); my = trunc(20*y); size = 400 + + --+ curPen = self~objectToDC(dc, myPen) + + -- Select the nice big letters and digits into the device context to use to + -- to write with: + curFont = self~fontToDC(dc, walterFont) + + -- Create a white brush and select it into the device to paint with. + whiteBrush = self~createBrush(10) + curBrush = self~objectToDC(dc, whiteBrush) + +-- Paint the drawing area surface with the white brush +-- self~rectangle(dc, 1, 1, 500, 450, 'FILL') -- how does that relate to the 180 above ??? +-- self~rectangle(dc, 1, 1, 480, 400, 'FILL') -- how does that relate to the 180 above ??? + + button = self~newPushButton(100) + clRect = button~clientRect; -- Say clRect + self~rectangle(dc, clRect~left+10, clRect~top+10, clRect~right-10, clRect~bottom-10, 'FILL') + + self~transparentText(dc) + self~writeDirect(dc, 55,20*y,"Walter's Clock") + self~writeDirect(dc,236, 56,'12') + self~writeDirect(dc,428,220,'3') + self~writeDirect(dc,245,375,'6') + self~writeDirect(dc, 60,220,'9') + self~opaqueText(dc) + + -- These 5 lines just have the effect of showing "Walter's Clock" first + -- for a brief instant before the other drawing shows. If you want it all + -- to show at once, then remove this. +/* + if change \= 2 then do + call msSleep 1000 + change = 2 + end +*/ + self~interrupted = .false + + sec=0 + min=0 + hhh=0 + fact=rxCalcPi()/180 + Parse Value '-1 -1 -1 -1' With hho mmo sso hopo + + do dalpha=0 To 359 by 30 until self~interrupted + alpha = dalpha*fact + zxa=trunc(250+124*rxCalcSin(alpha,,'R')) + zya=trunc(230-110*rxCalcCos(alpha,,'R')) + hhh=right(hhh,2,0) + hhh.hhh=right(zxa,3) right(zya,3) + hhh+=1 + self~draw_square(dc,zxa,zya,3,5) + self~draw_square(dc,zxa,zya,2,10) + End + Do a=0 To 59 + a=right(a,2,0) + alpha=a*6*fact + sin.a=rxCalcSin(alpha,,'R') + cos.a=rxCalcCos(alpha,,'R') + sin.0mhh.a=sin.a + cos.0mhh.a=cos.a + End + Do hoi=0 To 12*60-1 + hoi=right(hoi,3,0) + alpha=(hoi/2)*fact + sin.0hoh.hoi=rxCalcSin(alpha,,'R') + cos.0hoh.hoi=rxCalcCos(alpha,,'R') + End + do dalpha=0 To 359 by 6 until self~interrupted + alpha = dalpha*fact + zxa=trunc(250+165*rxCalcSin(alpha,,'R')) + zya=trunc(230-140*rxCalcCos(alpha,,'R')) + sec=right(min,2,0) + sec.sec=right(zxa,3) right(zya,3) + sec+=1 + self~draw_square(dc,zxa,zya,3,5) + self~draw_square(dc,zxa,zya,2,10) + zxa=trunc(250+140*rxCalcSin(alpha,,'R')) + zya=trunc(230-125*rxCalcCos(alpha,,'R')) + min=right(min,2,0) + min.min=right(zxa,3) right(zya,3) + --Call lineout 'pos.xxx',right(min,2) 'min='min.min + min+=1 + self~draw_square(dc,zxa,zya,3,5) + self~draw_square(dc,zxa,zya,2,10) + End + + do dalpha=0 by 6 until self~interrupted + alpha=dalpha*fact + zxa=trunc(250+165*rxCalcSin(alpha,,'R')) + zya=trunc(230-140*rxCalcCos(alpha,,'R')) + time=time() + parse Var time hh ':' mm ':' ss + If hh>=12 Then hh=right(hh-12,2,0) + self~writeDirect(dc, 355,40,time) + date=date() + self~writeDirect(dc, 355,60,date) + If hh<>hho Then Do + If hho>=0 Then Do + Parse Var hhh.hho hx hy + self~draw_square(dc,hx,hy,2,10) + End + Parse Var hhh.hh hx hy + self~draw_square(dc,hx,hy,2,2) + End + If mm<>mmo Then Do + If mmo>=0 Then Do + Parse Var min.mmo mx my + self~draw_square(dc,mx,my,2,10) + End + Parse Var min.mm mx my + self~draw_square(dc,mx,my,2,2) + End + If ss<>sso Then Do + If sso>=0 Then Do + Parse Var sec.sso sx sy + self~draw_square(dc,sx,sy,2,10) + self~draw_second_hand(dc,sso,sin.,cos.,10) + End + Parse Var sec.ss sx sy + self~draw_square(dc,sx,sy,2, 2) + self~draw_second_hand(dc,ss,sin.,cos.,16) + self~draw_square(dc,250,230,4,1) + hop=right(hh*60+mm,3,0) + self~draw_hour_hand(dc,hop,sin.,cos.,13) + self~draw_minute_hand(dc,mm,sin.,cos.,14) + End + If mm<>mmo Then Do + If hopo>=0 Then + self~draw_hour_hand(dc,hopo,sin.,cos.,10) + hop=right(hh*60+mm,3,0) + self~draw_hour_hand(dc,hop,sin.,cos.,13) + hopo=hop + If mmo>=0 Then + self~draw_minute_hand(dc,mmo,sin.,cos.,10) + self~draw_minute_hand(dc,mm,sin.,cos.,14) + End + self~draw_square(dc,250,230,4,1) + hho=hh + mmo=mm + sso=ss + + call msSleep 100 + self~pause + end +-- if kpix >= size then kpix = 1 + + self~interrupted = .true + --+ self~objectToDC(dc, curPen) + self~objectToDC(dc, curBrush) + +::method pause + j = msSleep(10) + +::method draw_square + Use Arg dc, x, y, d, c + Do zx=x-d to x+d + Do zy=y-d to y+d + self~drawPixel(dc, zx, zy, c) + End + End + +::method draw_hour_hand + Use Arg dc, hp, sin., cos., color + Do p=1 To 60 + zx=trunc(250+p*sin.0hoh.hp) + zy=trunc(230-p*cos.0hoh.hp) + self~draw_square(dc, zx, zy, 2, color) + End + +::method draw_minute_hand + Use Arg dc, mp, sin., cos., color + Do p=1 To 80 + zx=trunc(250+p*sin.0mhh.mp) + zy=trunc(230-p*cos.0mhh.mp) + self~draw_square(dc, zx, zy, 1, color) + End + +::method draw_second_hand + Use Arg dc, sp, sin., cos., color + Do p=1 To 113 + zx=trunc(250+p*sin.sp) + zy=trunc(230-p*(140/165)*cos.sp) + self~draw_square(dc, zx, zy, 0, color) + End + +::method quot + Parse Arg x,y + If y=0 Then Return '??' + Else Return x/y diff --git a/Task/Draw-a-clock/OoRexx/draw-a-clock-2.rexx b/Task/Draw-a-clock/OoRexx/draw-a-clock-2.rexx new file mode 100644 index 0000000000..2008fea7d1 --- /dev/null +++ b/Task/Draw-a-clock/OoRexx/draw-a-clock-2.rexx @@ -0,0 +1,143 @@ +/* REXX --------------------------------------------------------------- + Name: clock.rxj + Purpose: create a graphical clock that shows the current time + -- modelled after the Java program + at ? + + Needs: - ooRexx (cf. https://sourceforge.net/projects/oorexx/ ) + - BSF4ooRexx (Rexx-Java-bridge, cf. + https://sourceforge.net/projects/bsf4oorexx/ ) + - Java (cf. http://www.java.com ) + Created: 2014-09-04 + Author: Rony G. Flatscher +*--------------------------------------------------------------------*/ + -- import Java classes, make them available as ooRexx classes +call bsf.import "java.awt.Color" , "awtColor" +call bsf.import "java.awt.RenderingHints", "awtRenderingHints" +call bsf.import "java.lang.Math" , "jMath" +call bsf.import "javax.swing.JFrame" , "swingJFrame" +call bsf.import "javax.swing.Timer" , "swingTimer" + +rxClock=.RexxClock~new -- create Rexx clock object +jrxClock=BSFCreateRexxProxy(rxClock) -- box Rexx object into a Java object (a Java RexxProxy) + + /* extend Java class JPanel, make sure 'paintComponent' method invocations will get + forwarded to a RexxProxy object that needs to be supplied upon instantiating this + extended Java class; this method is defined in JPanel's superclass 'javax.swing.JComponent' */ +exjClz=bsf.createProxyClass("javax.swing.JPanel", "RexxJavaClock", "javax.swing.JComponent paintComponent") +javaClock=exjClz~new(jrxClock) -- create a Java object, supply it the Java RexxProxy that processes method invocations +javaClock~setPreferredSize(.bsf~new("java.awt.Dimension", rxClock~size, rxClock~size)) +javaClock~setBackground(.awtColor~white) + + -- create a JFrame, configure it a little bit +f=.swingJFrame~new +f~defaultCloseOperation=.swingJFrame~EXIT_ON_CLOSE +f~title ="ooRexx Clock" +f~resizable =.false + -- add the clock (a JPanel) to it +f~contentPane~add(javaClock, bsf.loadClass("java.awt.BorderLayout")~CENTER) +f~pack -- let the layout manager do its work +f~locationRelativeTo =.nil -- no specific location (will be centered) + + /* create Rexx object that sends repaint messages to cause the clock to be updated whenever + the swing Timer (see below) issues the "actionPerformed" event; to release the lock when + the 'windowClosing' event is issued */ +rxEH=.RexxEventHandler~new + + /* box Rexx object as a Java object, supply the Java object (javaClock) as user data (will be + be made available under the entry name "userdata" in the slotDir directory, appended + to callbacks as additional argument); declare this Java proxy object to implement + the interfaces 'java.awt.event.ActionListener' and 'java.awt.event.WindowListener' */ +jrxEH=BSFCreateRexxProxy(rxEH, javaClock, "java.awt.event.ActionListener", "java.awt.event.WindowListener") + + /* SwingTimer will cause every second the actionPerformed() event to be issued, + bsf.dispatch() to bypass ooRexx method resolution into .Object (has a 'start' method) */ +.swingTimer~new(1000, jrxEH)~bsf.dispatch("start") +f~addWindowListener(jrxEH) -- this allows us to get notified when the JFrame gets closed +f~~setVisible(.true)~~toFront -- show JFrame, make sure it is in the very front + +say "..." pp(.DateTime~new) "Rexx main program, now waiting until JFrame gets closed ..." +rxEH~wait -- wait +say "..." pp(.DateTime~new) "Rexx main program, JFrame got closed." + + +::requires "BSF.CLS" -- get the Java camouflaging support for ooRexx + +/* This class controls the painting of the clock. */ +::class RexxClock -- will be used for an extension of javax.swing.JPanel overriding paintComponent +::method init -- constructor, used for initializing + expose degrees06 degrees30 degrees90 size spacing diameter x y + + degrees06 = .JMath~toRadians(6) + degrees30 = degrees06 * 5 + degrees90 = degrees30 * 3 + + size = 550 + spacing = 20; + diameter = size - 2 * spacing + x = trunc(diameter / 2) + spacing + y = trunc(diameter / 2) + spacing + +::attribute size get -- make size accessible for clients + +::method paintComponent + expose degrees06 degrees30 degrees90 size spacing diameter x y + use arg g, slotDir + -- call dump2 slotDir, .datetime~new "- paintComponent's slotDir:" + + jobj=slotDir~javaObject -- as the Java object invoked paintComponent the message to the rexx object will supply that Java object + jobj~paintComponent_forwardToSuper(g) -- now invoke the method in the (Java) superclass first + + g~setRenderingHint(.awtRenderingHints~KEY_ANTIALIASING, .awtRenderingHints~VALUE_ANTIALIAS_ON) + + g~setColor(.awtColor~black) + g~drawOval(spacing, spacing, diameter, diameter) + date=.dateTime~new -- use ooRexx' date and time + + angle = degrees90 - (degrees06 * date~seconds) + self~drawHand(g, angle, diameter / 2 - 30, .awtColor~red) + + minsecs = (date~minutes + date~seconds / 60) + angle = degrees90 - (degrees06 * minsecs) + self~drawHand(g, angle, diameter / 3 + 10, .awtColor~green) + + hourmins = (date~hours + minsecs / 60) + angle = degrees90 - (degrees30 * hourmins) + self~drawHand(g, angle, diameter / 4 + 10, .awtColor~black) + + + ::method drawHand + expose x y + use arg g, angle, radius, color + + x2 = trunc(x + radius * .jMath~cos(angle)) + y2 = trunc(y + radius * .jMath~sin(-angle)) -- flip y-axis + g~setColor(color) + g~drawLine(x, y, x2, y2) + + + +/* The following Rexx class implements the event handlers for a java.awt.event.WindowListener to be + able to learn when the JFrame gets closed (event "windowClosing"). + + In addition it implements the java.awt.event.ActionListener for updating the clock every second + (using a swing Timer that causes the "actionPerformed" event to be issued). +*/ +::class RexxEventHandler +::method init -- constructor for initialization + expose wait -- object variable to serve as a control variable + wait=.true -- initialize lock + +::method wait -- method to allow for blocking + expose wait + guard on when wait<>.true -- the caller will be blocked until this condition turns to .false + +::method windowClosing -- Window event when window gets closed, release wait lock + expose wait + wait=.false -- release lock + +::method unknown -- catch all other window-events + +::method actionPerformed -- this event will be caused every second by the swing Timer + use arg eventObj, slotDir + slotDir~userData~repaint -- fetch the Java object and send it the repaint message diff --git a/Task/Draw-a-clock/Phix/draw-a-clock.phix b/Task/Draw-a-clock/Phix/draw-a-clock.phix new file mode 100644 index 0000000000..968346b482 --- /dev/null +++ b/Task/Draw-a-clock/Phix/draw-a-clock.phix @@ -0,0 +1,140 @@ +-- +-- demo\rosetta\Clock.exw +-- +include pGUI.e + +constant USE_OPENGL = 01 + +Ihandle dlg, canvas, hTimer +cdCanvas cd_canvas + +procedure draw_hand(atom degrees, atom r, baseangle, baselen, cx, cy) + atom a = PI-(degrees+90)*PI/180 + -- tip + atom x1 = cos(a)*(r) + atom y1 = sin(a)*(r) + -- base + atom x2 = cos(a+PI-baseangle)*baselen + atom y2 = sin(a+PI-baseangle)*baselen + atom x3 = cos(a+PI+baseangle)*baselen + atom y3 = sin(a+PI+baseangle)*baselen + cdCanvasLineWidth(cd_canvas,1) + cdCanvasLine(cd_canvas,cx+x1,cy+y1,cx+x2,cy+y2) + cdCanvasLine(cd_canvas,cx+x2,cy+y2,cx+x3,cy+y3) + cdCanvasLine(cd_canvas,cx+x3,cy+y3,cx+x1,cy+y1) + cdCanvasBegin(cd_canvas,CD_FILL) + cdCanvasVertex(cd_canvas,cx+x1,cy+y1) + cdCanvasVertex(cd_canvas,cx+x2,cy+y2) + cdCanvasVertex(cd_canvas,cx+x3,cy+y3) + cdCanvasEnd(cd_canvas) +end procedure + +procedure draw_clock(atom cx, cy, d) +atom w = 2+floor(d/25) + cdCanvasFont(cd_canvas, "Helvetica", CD_PLAIN, floor(d/15)) + cdCanvasLineWidth(cd_canvas, w) + cdCanvasArc(cd_canvas, cx, cy, d, d, 0, 360) + d -= w+8 + w = 1+floor(d/50) + for i=6 to 360 by 6 do + integer h = remainder(i,30)=0 + cdCanvasLineWidth(cd_canvas, floor(w*(1+h)/3)) + atom a = PI-(i+90)*PI/180 + atom x1 = cos(a)*d/2, x2 = cos(a)*(d/2-w*(2+h)*.66) + atom y1 = sin(a)*d/2, y2 = sin(a)*(d/2-w*(2+h)*.66) + cdCanvasLine(cd_canvas, cx+x1, cy+y1, cx+x2, cy+y2) + if h then + x1 = cos(a)*(d/2-w*4.5) + y1 = sin(a)*(d/2-w*4.5) + cdCanvasText(cd_canvas,cx+x1,cy+y1,sprintf("%d",{i/30})) + end if + end for + atom {hour,mins,secs,msecs} = date(true)[DT_HOUR..DT_MSEC] + if IupGetInt(hTimer,"TIME")<1000 then + -- (if showing once a second, always land on exact + -- seconds, ie completely ignore msecs, otherwise + -- show smooth running (fractional) second hand.) + secs += msecs/1000 + end if + mins += secs/60 + hour += mins/60 + atom r = d/2 + draw_hand(hour*360/12,r-w*9,0.3,d/20,cx,cy) + draw_hand(mins*360/60,r-w*2,0.2,d/16,cx,cy) + cdCanvasSetForeground(cd_canvas, CD_RED) + draw_hand(secs*360/60,r-w*2,0.05,d/16,cx,cy) + cdCanvasSetForeground(cd_canvas, CD_BLACK) +end procedure + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) +integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") +integer r = floor(min(width,height)*0.9) +integer cx = floor(width/2) +integer cy = floor(height/2) + cdCanvasActivate(cd_canvas) + cdCanvasClear(cd_canvas) + draw_clock(cx,cy,r) + cdCanvasFlush(cd_canvas) + return IUP_DEFAULT +end function + +function timer_cb(Ihandle /*ih*/) + IupUpdate(canvas) + return IUP_IGNORE +end function + +function map_cb(Ihandle ih) + if USE_OPENGL then + atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 + IupGLMakeCurrent(canvas) + cd_canvas = cdCreateCanvas(CD_GL, "10x10 %g", {res}) + else + cd_canvas = cdCreateCanvas(CD_IUPDBUFFER, canvas) + end if + cdCanvasSetBackground(cd_canvas, CD_WHITE) + cdCanvasSetForeground(cd_canvas, CD_BLACK) + {} = cdCanvasTextAlignment(cd_canvas, CD_CENTER) + return IUP_DEFAULT +end function + +function canvas_resize_cb(Ihandle /*canvas*/) + if USE_OPENGL then + integer {canvas_width, canvas_height} = IupGetIntInt(canvas, "DRAWSIZE") + atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 + cdCanvasSetAttribute(cd_canvas, "SIZE", "%dx%d %g", {canvas_width, canvas_height, res}) + end if + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + + if USE_OPENGL then + canvas = IupGLCanvas() + else + canvas = IupCanvas() + end if + IupSetAttribute(canvas, "RASTERSIZE", "350x350") -- initial size + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + IupSetCallback(canvas, "RESIZE_CB", Icallback("canvas_resize_cb")) + + hTimer = IupTimer(Icallback("timer_cb"), 40) -- smooth secs +-- hTimer = IupTimer(Icallback("timer_cb"), 1000) -- tick seconds + + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", "Clock") + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + + IupShowXY(dlg,IUP_CENTER,IUP_CENTER) + IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation + IupMainLoop() + IupClose() +end procedure + +main() diff --git a/Task/Draw-a-clock/Rust/draw-a-clock.rust b/Task/Draw-a-clock/Rust/draw-a-clock.rust new file mode 100644 index 0000000000..280ce8e144 --- /dev/null +++ b/Task/Draw-a-clock/Rust/draw-a-clock.rust @@ -0,0 +1,27 @@ +// cargo-deps: time="0.1" +extern crate time; +use std::thread; + +static TOP: &'static str = " ⡎⢉⢵ ⠀⢺⠀ ⠊⠉⡱ ⠊⣉⡱ ⢀⠔⡇ ⣏⣉⡉ ⣎⣉⡁ ⠊⢉⠝ ⢎⣉⡱ ⡎⠉⢱ ⠀⠶⠀"; +static BOT: &'static str = " ⢗⣁⡸ ⢀⣸⣀ ⣔⣉⣀ ⢄⣀⡸ ⠉⠉⡏ ⢄⣀⡸ ⢇⣀⡸ ⢰⠁⠀ ⢇⣀⡸ ⢈⣉⡹ ⠀⠶⠀"; + +fn main() { + let top: Vec<&str> = TOP.split_whitespace().collect(); + let bot: Vec<&str> = BOT.split_whitespace().collect(); + + loop { + let tm = &time::now().rfc822().to_string()[17..25]; + let top_str: String = tm.chars().map(|x| top[x as usize - '0' as usize]).collect(); + let bot_str: String = tm.chars().map(|x| bot[x as usize - '0' as usize]).collect(); + + clear_screen(); + println!("{}", top_str); + println!("{}", bot_str); + + thread::sleep(std::time::Duration::from_secs(1)); + } +} + +fn clear_screen() { + println!("{}[H{}[J", 27 as char, 27 as char); +} diff --git a/Task/Draw-a-clock/Scheme/draw-a-clock.ss b/Task/Draw-a-clock/Scheme/draw-a-clock.ss new file mode 100644 index 0000000000..328ba29eef --- /dev/null +++ b/Task/Draw-a-clock/Scheme/draw-a-clock.ss @@ -0,0 +1,59 @@ +(import (scheme base) + (scheme inexact) + (scheme time) + (pstk)) + +(define PI 3.1415927) + +;; Draws the hands on the canvas using the current time, and repeats each second +(define (hands canvas) + (canvas 'delete 'withtag "hands") + + (let* ((time (current-second)) ; no time locality used, so displays time in GMT + (hours (floor (/ time 3600))) + (rem (- time (* hours 3600))) + (mins (floor (/ rem 60))) + (secs (- rem (* mins 60))) + (second-angle (* secs (* 2 PI 1/60))) + (minute-angle (* mins (* 2 PI 1/60))) + (hour-angle (* hours (* 2 PI 1/12)))) + (canvas 'create 'line ; second hand + 100 100 + (+ 100 (* 90 (sin second-angle))) + (- 100 (* 90 (cos second-angle))) + 'width: 1 'tags: "hands") + (canvas 'create 'line ; minute hand + 100 100 + (+ 100 (* 85 (sin minute-angle))) + (- 100 (* 85 (cos minute-angle))) + 'width: 3 + 'capstyle: "projecting" + 'tags: "hands") + (canvas 'create 'line ; hour hand + 100 100 + (+ 100 (* 60 (sin hour-angle))) + (- 100 (* 60 (cos hour-angle))) + 'width: 7 + 'capstyle: "projecting" + 'tags: "hands")) + (tk/after 1000 (lambda () (hands canvas)))) + +;; Create the initial frame, clock frame and hours +(let ((tk (tk-start))) + (tk/wm 'title tk "GMT Clock") + + (let ((canvas (tk 'create-widget 'canvas))) + (tk/pack canvas) + (canvas 'configure 'height: 200 'width: 200) + (canvas 'create 'oval 2 2 198 198 'fill: "white" 'outline: "black") + (do ((h 1 (+ 1 h))) + ((> h 12) ) + (let ((angle (- (/ PI 2) (* h PI 1/6)))) + (canvas 'create 'text + (+ 100 (* 90 (cos angle))) + (- 100 (* 90 (sin angle))) + 'text: (number->string h) + 'font: "{Helvetica -12}"))) + + (hands canvas)) + (tk-event-loop tk)) diff --git a/Task/Draw-a-clock/Sidef/draw-a-clock.sidef b/Task/Draw-a-clock/Sidef/draw-a-clock.sidef index 290d4887cf..eeb7e2c317 100644 --- a/Task/Draw-a-clock/Sidef/draw-a-clock.sidef +++ b/Task/Draw-a-clock/Sidef/draw-a-clock.sidef @@ -1,6 +1,6 @@ -STDOUT.autoflush(1) +STDOUT.autoflush(true) -var (rows, cols) = `stty size`.words.map{.to_i}... +var (rows, cols) = `stty size`.nums... var x = (rows/2 - 1 -> int) var y = (cols/2 - 16 -> int) @@ -12,20 +12,20 @@ var chars = [ ].map {|s| s.split(3) } func position(i,j) { - "\e[%d;%dH"%(i, j) + "\e[%d;%dH" % (i, j) } func indices { - var t = Time.local; - "%02d:%02d:%02d"%(t.hour, t.min, t.sec).split(1).map{|c| c.ord - '0'.ord}... + var t = Time.local + "%02d:%02d:%02d" % (t.hour, t.min, t.sec) -> split(1).map{|c| c.ord - '0'.ord } } loop { - print "\e[H\e[J"; - chars.range.each { |i| - print position(x + i, y); - print [chars[i][indices()]].join(' '); + print "\e[H\e[J" + for i in ^chars { + print position(x + i, y) + print [chars[i][indices()]].join(' ') } - print position(1, 1); - Sys.sleep(1); + print position(1, 1) + Sys.sleep(0.1) } diff --git a/Task/Draw-a-clock/Zkl/draw-a-clock.zkl b/Task/Draw-a-clock/Zkl/draw-a-clock.zkl new file mode 100644 index 0000000000..9819c7b3a4 --- /dev/null +++ b/Task/Draw-a-clock/Zkl/draw-a-clock.zkl @@ -0,0 +1,10 @@ +var + t=T("⡎⢉⢵","⠀⢺⠀","⠊⠉⡱","⠊⣉⡱","⢀⠔⡇","⣏⣉⡉","⣎⣉⡁","⠊⢉⠝","⢎⣉⡱","⡎⠉⢱","⠀⠶⠀"), + b=T("⢗⣁⡸","⢀⣸⣀","⣔⣉⣀","⢄⣀⡸","⠉⠉⡏","⢄⣀⡸","⢇⣀⡸","⢰⠁⠀","⢇⣀⡸","⢈⣉⡹","⠀⠶ "); +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 + println(x.pump(String,t.get),"\n",x.pump(String,b.get)); + Atomic.sleep(1); +} diff --git a/Task/Draw-a-cuboid/00DESCRIPTION b/Task/Draw-a-cuboid/00DESCRIPTION index 2c969be978..af7717ae3a 100644 --- a/Task/Draw-a-cuboid/00DESCRIPTION +++ b/Task/Draw-a-cuboid/00DESCRIPTION @@ -5,5 +5,6 @@ Either static or rotational projection is acceptable for this task.

    ;Related tasks -* [[Draw_a_rotating_cube|Draw a rotating cube]] +* [[Draw_a_rotating_cube|draw a rotating cube]] +* [[Write_language_name_in_3D_ASCII|write language name in 3D ASCII]]

    diff --git a/Task/Draw-a-cuboid/C/draw-a-cuboid-1.c b/Task/Draw-a-cuboid/C/draw-a-cuboid-1.c deleted file mode 100644 index dee16bab57..0000000000 --- a/Task/Draw-a-cuboid/C/draw-a-cuboid-1.c +++ /dev/null @@ -1,136 +0,0 @@ -#include -#include -#include - -const char *shades = ".:!*oe&#%@"; - -void vsub(double *v1, double *v2, double *s) { - s[0] = v1[0] - v2[0]; - s[1] = v1[1] - v2[1]; - s[2] = v1[2] - v2[2]; -} - -double normalize(double * v) { - double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); - v[0] /= len; v[1] /= len; v[2] /= len; - return len; -} - -double dot(double *x, double *y) { - return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; -} - -double * cross(double x[3], double y[3], double s[3]) { - s[0] = x[1] * y[2] - x[2] * y[1]; - s[1] = x[2] * y[0] - x[0] * y[2]; - s[2] = x[0] * y[1] - x[1] * y[0]; - return s; -} - -double* madd(double *x, double *y, double d, double *r) { - r[0] = x[0] + y[0] * d; - r[1] = x[1] + y[1] * d; - r[2] = x[2] + y[2] * d; - return r; -} - -double v000[] = { -4, -3, -2 }; -double v100[] = { 4, -3, -2 }; -double v010[] = { -4, 3, -2 }; -double v110[] = { 4, 3, -2 }; -double v001[] = { -4, -3, 2 }; -double v101[] = { 4, -3, 2 }; -double v011[] = { -4, 3, 2 }; -double v111[] = { 4, 3, 2 }; - -typedef struct { - double * v[4]; - double norm[3]; -} face_t; - -face_t f[] = { - { { v000, v010, v110, v100 }, { 0, 0, -1 } }, - { { v001, v011, v111, v101 }, { 0, 0, 1 } }, - { { v000, v010, v011, v001 }, { -1, 0, 0 } }, - { { v100, v110, v111, v101 }, { 1, 0, 0 } }, - { { v000, v100, v101, v001 }, { 0, -1, 0 } }, - { { v010, v110, v111, v011 }, { 0, 1, 0 } }, -}; - -int in_range(double x, double x0, double x1) { - return (x - x0) * (x - x1) <= 0; -} - -int face_hit(face_t *face, double src[3], double dir[3], double hit[3], double *d) -{ - int i; - double dist; - for (i = 0; i < 3; i++) - if (face->norm[i]) - dist = (face->v[0][i] - src[i]) / dir[i]; - - madd(src, dir, dist, hit); - *d = fabs(dot(dir, face->norm) * dist); - - if (face->norm[0]) { - return in_range(hit[1], face->v[0][1], face->v[2][1]) && - in_range(hit[2], face->v[0][2], face->v[2][2]); - } - else if (face->norm[1]) { - return in_range(hit[0], face->v[0][0], face->v[2][0]) && - in_range(hit[2], face->v[0][2], face->v[2][2]); - } - else if (face->norm[2]) { - return in_range(hit[0], face->v[0][0], face->v[2][0]) && - in_range(hit[1], face->v[0][1], face->v[2][1]); - } - return 0; -} - -int main() -{ - int i, j, k; - double eye[3] = { 7, 7, 6 }; - double dir[3] = { -1, -1, -1 }, orig[3] = {0, 0, 0}; - double hit[3], dx[3], dy[3] = {0, 0, 1}, proj[3]; - double d, *norm, dbest, b; - double light[3] = { 6, 8, 6 }, ldist[3], decay, strength = 10; - - normalize(cross(eye, dy, dx)); - normalize(cross(eye, dx, dy)); - - for (i = -10; i <= 17; i++) { - for (j = -35; j < 35; j++) { - vsub(orig, orig, proj); - madd(madd(proj, dx, j / 6., proj), dy, i/3., proj); - vsub(proj, eye, dir); - dbest = 1e100; - norm = 0; - for (k = 0; k < 6; k++) { - if (!face_hit(f + k, eye, dir, hit, &d)) continue; - if (dbest > d) { - dbest = d; - norm = f[k].norm; - } - } - - if (!norm) { - putchar(' '); - continue; - } - - vsub(light, hit, ldist); - decay = normalize(ldist); - b = dot(norm, ldist) / decay * strength; - if (b < 0) b = 0; - else if (b > 1) b = 1; - b += .2; - if (b > 1) b = 0; - else b = 1 - b; - putchar(shades[(int)(b * (sizeof(shades) - 2))]); - } - putchar('\n'); - } - - return 0; -} diff --git a/Task/Draw-a-cuboid/C/draw-a-cuboid-2.c b/Task/Draw-a-cuboid/C/draw-a-cuboid-2.c deleted file mode 100644 index 01aa465244..0000000000 --- a/Task/Draw-a-cuboid/C/draw-a-cuboid-2.c +++ /dev/null @@ -1,28 +0,0 @@ - * - **************!! - *************!!!!!!!!!!!!!!!!!! - ooo************!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - *oooo***********!!!!!!!!!!!!!!!!!::::::::::::::::::::!!! - o*************!!!!!!!!!!!!::::::::::::::::::::::::::::::::::::: - o****!!****!!!!!!!!!!:::::::::::::::::::::::::::::::::::::::::&& - oo****!!!!:!!!!!!!::::::::::::::::.................::::::::e&&& - o*****!!!!:::!!!:::::::::::............................eee&&&& - oo*****!!!!:::...:::::::.............................eeeee&&& - oo*****!!!!:::.....::............................oeeeeee&&& - ooo*****!!!!:::...............................ooooeeeee&&&& - ooo*****!!!!:::...........................ooooooeeeeee&&& - oooo*****!!!!::::......................**ooooooeeeeee&&&& - ooo*****!!!!::::..................****ooooooeeeeee&&&& - oo*****!!!!::::...............*****oooooooeeeeee&&&& - o*****!!!!::::..............****oooooooeeeeee&&&& - *****!!!!:::::............***oooooooeeeeee&&& - ***!!!!!::::...........**oooooooeeeeee&& - ***!!!!:::::.........ooooooooeeeeeee - **!!!!!::::........oooooooeeeeee - *!!!!!:::::.....oooooooeeeee - !!!!!::::....oooooeeeee - !!!!:::::..ooooeeeee - !!!!:::::oooeeee - !!!!:::oeeee - !!!::eee - !ee diff --git a/Task/Draw-a-cuboid/JavaScript/draw-a-cuboid.js b/Task/Draw-a-cuboid/JavaScript/draw-a-cuboid.js new file mode 100644 index 0000000000..779aeab8d5 --- /dev/null +++ b/Task/Draw-a-cuboid/JavaScript/draw-a-cuboid.js @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + diff --git a/Task/Draw-a-cuboid/Kotlin/draw-a-cuboid.kotlin b/Task/Draw-a-cuboid/Kotlin/draw-a-cuboid.kotlin new file mode 100644 index 0000000000..979d3669e9 --- /dev/null +++ b/Task/Draw-a-cuboid/Kotlin/draw-a-cuboid.kotlin @@ -0,0 +1,123 @@ +// version 1.1 + +import java.awt.* +import java.awt.event.MouseAdapter +import java.awt.event.MouseEvent +import javax.swing.* + +class Cuboid: JPanel() { + private val nodes = arrayOf( + doubleArrayOf(-1.0, -1.0, -1.0), + doubleArrayOf(-1.0, -1.0, 1.0), + doubleArrayOf(-1.0, 1.0, -1.0), + doubleArrayOf(-1.0, 1.0, 1.0), + doubleArrayOf( 1.0, -1.0, -1.0), + doubleArrayOf( 1.0, -1.0, 1.0), + doubleArrayOf( 1.0, 1.0, -1.0), + doubleArrayOf( 1.0, 1.0, 1.0) + ) + private val edges = arrayOf( + intArrayOf(0, 1), + intArrayOf(1, 3), + intArrayOf(3, 2), + intArrayOf(2, 0), + intArrayOf(4, 5), + intArrayOf(5, 7), + intArrayOf(7, 6), + intArrayOf(6, 4), + intArrayOf(0, 4), + intArrayOf(1, 5), + intArrayOf(2, 6), + intArrayOf(3, 7) + ) + + private var mouseX: Int = 0 + private var prevMouseX: Int = 0 + private var mouseY: Int = 0 + private var prevMouseY: Int = 0 + + init { + preferredSize = Dimension(640, 640) + background = Color.white + scale(80.0, 120.0, 160.0) + rotateCube(Math.PI / 5.0, Math.PI / 9.0) + addMouseListener(object: MouseAdapter() { + override fun mousePressed(e: MouseEvent) { + mouseX = e.x + mouseY = e.y + } + }) + + addMouseMotionListener(object: MouseAdapter() { + override fun mouseDragged(e: MouseEvent) { + prevMouseX = mouseX + prevMouseY = mouseY + mouseX = e.x + mouseY = e.y + val incrX = (mouseX - prevMouseX) * 0.01 + val incrY = (mouseY - prevMouseY) * 0.01 + rotateCube(incrX, incrY) + repaint() + } + }) + } + + private fun scale(sx: Double, sy: Double, sz: Double) { + for (node in nodes) { + node[0] *= sx + node[1] *= sy + node[2] *= sz + } + } + + private fun rotateCube(angleX: Double, angleY: Double) { + val sinX = Math.sin(angleX) + val cosX = Math.cos(angleX) + val sinY = Math.sin(angleY) + val cosY = Math.cos(angleY) + for (node in nodes) { + val x = node[0] + val y = node[1] + var z = node[2] + node[0] = x * cosX - z * sinX + node[2] = z * cosX + x * sinX + z = node[2] + node[1] = y * cosY - z * sinY + node[2] = z * cosY + y * sinY + } + } + + private fun drawCube(g: Graphics2D) { + g.translate(width / 2, height / 2) + for (edge in edges) { + val xy1 = nodes[edge[0]] + val xy2 = nodes[edge[1]] + g.drawLine(Math.round(xy1[0]).toInt(), Math.round(xy1[1]).toInt(), + Math.round(xy2[0]).toInt(), Math.round(xy2[1]).toInt()) + } + for (node in nodes) { + g.fillOval(Math.round(node[0]).toInt() - 4, Math.round(node[1]).toInt() - 4, 8, 8) + } + } + + override public fun paintComponent(gg: Graphics) { + super.paintComponent(gg) + val g = gg as Graphics2D + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + g.color = Color.blue + drawCube(g) + } +} + +fun main(args: Array) { + SwingUtilities.invokeLater { + val f = JFrame() + f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE + f.title = "Cuboid" + f.isResizable = false + f.add(Cuboid(), BorderLayout.CENTER) + f.pack() + f.setLocationRelativeTo(null) + f.isVisible = true + } +} diff --git a/Task/Draw-a-cuboid/Phix/draw-a-cuboid.phix b/Task/Draw-a-cuboid/Phix/draw-a-cuboid.phix index 0118f8f134..ece11ea293 100644 --- a/Task/Draw-a-cuboid/Phix/draw-a-cuboid.phix +++ b/Task/Draw-a-cuboid/Phix/draw-a-cuboid.phix @@ -1,17 +1,10 @@ -include ..\arwen\arwen.ew -include ..\arwen\axtra.ew +-- +-- demo\rosetta\draw_cuboid.exw +-- +include pGUI.e -constant main = create(Window, "Draw Cuboid", 0, 0, 20, 20, 625, 690, 0), - mainDC = getPrivateDC(main), - backDC = c_func(xCreateCompatibleDC, {NULL}), -- the background - viewDC = c_func(xCreateCompatibleDC, {NULL}), -- with animation - grey = #909090 - -constant MainTimer = createTimer() - -integer dw = 0, dh = 0 -- client area width and height -atom bmBack, bmView -integer bmX = 0, bmY = 0 -- actual size of the bitmaps +Ihandle dlg, canvas, hTimer +cdCanvas cd_canvas -- arrays: 3D coordinates of vertices sequence x = {-2.0, +2.0, +2.0, -2.0, -2.0, +2.0, +2.0, -2.0}, @@ -19,58 +12,130 @@ sequence x = {-2.0, +2.0, +2.0, -2.0, -2.0, +2.0, +2.0, -2.0}, z = {-1.0, -1.0, -1.0, -1.0, +1.0, +1.0, +1.0, +1.0}, Segment = {1,2, 2,3, 3,4, 4,1, 5,6, 6,7, 7,8, 8,5, 1,5, 2,6, 3,7, 4,8} -constant Size=50.0, Sz=0.008, Sx=-0.013 -- drawing size and tumbling speeds +atom Size = 50.0, -- drawing size + Sz = 0.008, -- tumbling speeds + Sx =-0.013, -- "" + Sy =-0.013, -- "" + S = 2 -function mainHandler(integer id, integer msg, atom wParam, object lParam) -atom farthest -integer v1, v2, farv, c - if msg=WM_SIZE then - {{},{},dw,dh} = getClientRect(main) - if dw>bmX or dh>bmY then - -- we need bigger bitmaps - bmBack = c_func(xCreateCompatibleBitmap, {mainDC, dw, dh}) - {} = deleteObject(selectObject(backDC,bmBack)) - -- clear the background - setPenColor(grey) - setPenBkColor(grey) - drawRectangleh(backDC, True, 0, 0, dw, dh) - bmView = c_func(xCreateCompatibleBitmap, {mainDC, dw, dh}) - {} = deleteObject(selectObject(viewDC,bmView)) - {bmX,bmY} = {dw,dh} +procedure draw_cube(integer wx, wh) + atom farthest = 0.0 -- find the farthest vertex + integer farv, v1, v2, c, style + for i=1 to 8 do + if z[i]>farthest then farthest = z[i] farv = i end if + end for + for v=1 to 2*12 by 2 do -- for all the vertices... + v1 = Segment[v] -- get vertex number + v2 = Segment[v+1] + c = CD_RED + style = CD_CONTINUOUS + if v1=farv or v2=farv then + c = CD_BLUE + style = CD_DASHED end if - elsif msg=WM_PAINT then - -- start with a fresh copy of the background - void = c_func(xBitBlt,{viewDC,0,0,dw,dh,backDC,0,0,SRCCOPY}) - farthest = 0.0 -- find the farthest vertex - for i=1 to 8 do - if z[i]>farthest then farthest = z[i] farv = i end if - end for - for v=1 to 2*12 by 2 do -- for all the vertices... - v1 = Segment[v] -- get vertex number - v2 = Segment[v+1] - c = Red; setPenStyle(Solid) - if v1=farv or v2=farv then c=Blue; setPenStyle(Dash) end if - drawLinesh(viewDC,{c,{x[v1]*Size+dw/2, y[v1]*Size+dh/2, - x[v2]*Size+dw/2, y[v2]*Size+dh/2}}) - end for - void = c_func(xBitBlt,{mainDC,0,0,dw,dh,viewDC,0,0,SRCCOPY}) - elsif msg=WM_TIMER then - for i=1 to 8 do - x[i] = x[i]+y[i]*Sz -- rotate vertices in X-Y plane - y[i] = y[i]-x[i]*Sz - y[i] = y[i]+z[i]*Sx -- rotate vertices in Y-Z plane - z[i] = z[i]-y[i]*Sx - end for - repaintWindow(main) - elsif msg=WM_SHOWWINDOW then - startTimer(MainTimer,main,33) - elsif msg=WM_CHAR - and wParam=VK_ESCAPE then - closeWindow(main) - if id or object(lParam) then end if -- suppress warnings - end if - return 0 -end function -setHandler({main},routine_id("mainHandler")) + cdCanvasSetForeground(cd_canvas, c) + cdCanvasLineStyle(cd_canvas, style) + atom x1 = x[v1]*Size+wx, + y1 = y[v1]*Size+wh, + x2 = x[v2]*Size+wx, + y2 = y[v2]*Size+wh + cdCanvasLine(cd_canvas,x1,y1,x2,y2) + end for +end procedure -WinMain(main, SW_NORMAL) +function canvas_action_cb(Ihandle canvas) + cdCanvasActivate(cd_canvas) + cdCanvasClear(cd_canvas) + integer {wx, wh} = sq_floor_div(IupGetIntInt(canvas, "DRAWSIZE"),2) + draw_cube(wx,wh) + cdCanvasFlush(cd_canvas) + return IUP_DEFAULT +end function + +function canvas_map_cb(Ihandle canvas) + atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 + IupGLMakeCurrent(canvas) + cd_canvas = cdCreateCanvas(CD_GL, "10x10 %g", {res}) + cdCanvasSetBackground(cd_canvas, CD_BLACK) + return IUP_DEFAULT +end function + +function canvas_unmap_cb(Ihandle canvas) + cdKillCanvas(cd_canvas) + return IUP_DEFAULT +end function + +function canvas_resize_cb(Ihandle /*canvas*/) + integer {canvas_width, canvas_height} = IupGetIntInt(canvas, "DRAWSIZE") + atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 + cdCanvasSetAttribute(cd_canvas, "SIZE", "%dx%d %g", {canvas_width, canvas_height, res}) + return IUP_DEFAULT +end function + +function k_any(Ihandle /*ih*/, atom c) + if c=K_ESC then + return IUP_CLOSE + elsif c=K_UP then + for i=1 to 8 do + y[i] = y[i]+z[i]*Sx*S -- rotate vertices in Y-Z plane + z[i] = z[i]-y[i]*Sx*S + end for + elsif c=K_DOWN then + for i=1 to 8 do + y[i] = y[i]-z[i]*Sx*S -- rotate vertices in Y-Z plane + z[i] = z[i]+y[i]*Sx*S + end for + elsif c=K_LEFT then + for i=1 to 8 do + x[i] = x[i]+z[i]*Sy*S -- rotate vertices in X-Z plane + z[i] = z[i]-x[i]*Sy*S + end for + elsif c=K_RIGHT then + for i=1 to 8 do + x[i] = x[i]-z[i]*Sy*S -- rotate vertices in X-Z plane + z[i] = z[i]+x[i]*Sy*S + end for + elsif c='+' then + Size += 5 + elsif c='-' then + Size = max(10,Size-5) + elsif c=' ' then + IupSetInt(hTimer,"RUN",not IupGetInt(hTimer,"RUN")) + end if + IupRedraw(canvas) + return IUP_CONTINUE +end function + +function timer_cb(Ihandle /*ih*/) + for i=1 to 8 do + x[i] = x[i]+y[i]*Sz*S -- rotate vertices in X-Y plane + y[i] = y[i]-x[i]*Sz*S + y[i] = y[i]+z[i]*Sx*S -- rotate vertices in Y-Z plane + z[i] = z[i]-y[i]*Sx*S + x[i] = x[i]+z[i]*Sy*S -- rotate vertices in X-Z plane + z[i] = z[i]-x[i]*Sy*S + end for + IupUpdate(canvas) + return IUP_IGNORE +end function + +procedure main() + IupOpen() + IupImageLibOpen() + canvas = IupGLCanvas() + IupSetAttribute(canvas, "RASTERSIZE", "640x480") + IupSetCallback(canvas, "ACTION", Icallback("canvas_action_cb")) + IupSetCallback(canvas, "MAP_CB", Icallback("canvas_map_cb")) + IupSetCallback(canvas, "UNMAP_CB", Icallback("canvas_unmap_cb")) + IupSetCallback(canvas, "RESIZE_CB", Icallback("canvas_resize_cb")) + dlg = IupDialog(IupVbox({canvas})) + IupSetAttribute(dlg, "TITLE", "Draw Cuboid") + IupSetCallback(dlg, "K_ANY", Icallback("k_any")) + IupShow(dlg) + IupSetAttribute(canvas, "RASTERSIZE", NULL) + hTimer = IupTimer(Icallback("timer_cb"), 40) + + IupMainLoop() + IupClose() +end procedure +main() diff --git a/Task/Draw-a-cuboid/Retro/draw-a-cuboid-1.retro b/Task/Draw-a-cuboid/Retro/draw-a-cuboid-1.retro deleted file mode 100644 index 489ef86752..0000000000 --- a/Task/Draw-a-cuboid/Retro/draw-a-cuboid-1.retro +++ /dev/null @@ -1,19 +0,0 @@ -3 elements d h w - -: spaces ( n- ) &space times ; -: --- ( - ) '+ putc @w 2 * [ '- putc ] times '+ putc ; -: ? ( n- ) @h <> [ '| ] [ '+ ] if ; -: slice ( n- ) '/ putc @w 2 * spaces '/ putc @d swap - dup spaces ? putc cr ; -: |...|/ ( - ) @h [ '| putc @w 2 * spaces '| putc 1- spaces '/ putc cr ] iterd ; -: face ( - ) - --- @w 1+ spaces '/ putc cr - |...|/ - --- cr ; - -: cuboid ( whd- ) - !d !h !w cr - @d 1+ spaces --- cr - @d [ dup spaces slice ] iterd - face ; - -2 3 4 cuboid diff --git a/Task/Draw-a-cuboid/Retro/draw-a-cuboid-2.retro b/Task/Draw-a-cuboid/Retro/draw-a-cuboid-2.retro deleted file mode 100644 index 4609441bf0..0000000000 --- a/Task/Draw-a-cuboid/Retro/draw-a-cuboid-2.retro +++ /dev/null @@ -1,10 +0,0 @@ - +----+ - / /| - / / | - / / | - / / + -+----+ / -| | / -| | / -| |/ -+----+ diff --git a/Task/Draw-a-cuboid/Sidef/draw-a-cuboid-1.sidef b/Task/Draw-a-cuboid/Sidef/draw-a-cuboid-1.sidef index 165476a320..90cd1bf69f 100644 --- a/Task/Draw-a-cuboid/Sidef/draw-a-cuboid-1.sidef +++ b/Task/Draw-a-cuboid/Sidef/draw-a-cuboid-1.sidef @@ -1,31 +1,31 @@ -var DIR = Hash.new("-" => [1,0], "|" => [0,1], "/" => [1,1]); - +const dirs = Hash("-" => [1,0], "|" => [0,1], "/" => [1,1]) +  func cuboid(nx, ny, nz) { - say("cuboid %d %d %d:" % [nx, ny, nz]); - var(x, y, z) = (8*nx, 2*ny, 4*nz); - var area = []; + say("cuboid %d %d %d:" % [nx, ny, nz]) + var(x, y, z) = (8*nx, 2*ny, 4*nz) + var area = [] var line = func(n, sx, sy, c) { - var(dx, dy) = DIR{c}...; - 0..n -> each {|i| - var (xi, yi) = (sx + i*dx, sy + i*dy); - area[yi] \\= [" "]*(x+y+1); - area[yi][xi] = (area[yi][xi] == " " ? c : '+'); - }; - }; - - 0 .. nz-1 -> each {|i| line.call(x, 0, 4*i, "-")}; - 0 .. ny -> each {|i| line.call(x, 2*i, z + 2*i, "-")}; - 0 .. nx-1 -> each {|i| line.call(z, 8*i, 0, "|")}; - 0 .. ny -> each {|i| line.call(z, x + 2*i, 2*i, "|")}; - 0 .. nz-1 -> each {|i| line.call(y, x, 4*i, "/")}; - 0 .. nx -> each {|i| line.call(y, 8*i, z, "/")}; - + var(dx, dy) = dirs{c}... + for i (0..n) { + var (xi, yi) = (sx + i*dx, sy + i*dy) + area[yi] \\= [" "]*(x+y+1) + area[yi][xi] = (area[yi][xi] == " " ? c : '+') + } + } +  + 0 .. nz-1 -> each {|i| line(x, 0, 4*i, "-") } + 0 .. ny -> each {|i| line(x, 2*i, z + 2*i, "-") } + 0 .. nx-1 -> each {|i| line(z, 8*i, 0, "|") } + 0 .. ny -> each {|i| line(z, x + 2*i, 2*i, "|") } + 0 .. nz-1 -> each {|i| line(y, x, 4*i, "/") } + 0 .. nx -> each {|i| line(y, 8*i, z, "/") } +  area.reverse.each { |line| - say line.join(''); - }; + say line.join('') + } } - -cuboid(2, 3, 4); -cuboid(1, 1, 1); -cuboid(6, 2, 1); -cuboid(2, 4, 1); +  +cuboid(2, 3, 4) +cuboid(1, 1, 1) +cuboid(6, 2, 1) +cuboid(2, 4, 1) diff --git a/Task/Draw-a-cuboid/Sidef/draw-a-cuboid-2.sidef b/Task/Draw-a-cuboid/Sidef/draw-a-cuboid-2.sidef index 603418cd43..89ec950486 100644 --- a/Task/Draw-a-cuboid/Sidef/draw-a-cuboid-2.sidef +++ b/Task/Draw-a-cuboid/Sidef/draw-a-cuboid-2.sidef @@ -1,30 +1,30 @@ func cuboid (x=1,y=1,z=1,s=' ',c='+',h='-',v='|',d='/') { - say("cuboid %d %d %d:" % (x, y, z)); - ' ' * z+1 + c + h*x + c -> say; + say("cuboid %d %d %d:" % (x, y, z)) + ' ' * z+1 + c + h*x + c -> say { |i| ' ' * (z - i + 1) + d + s*x + d + - (s * (i - (i > y ? i-y : 1))) + - (i - 1 == y ? c : (i > y ? d : v)) -> say - } * z; + (s * (i - (i > y ? i-y : 1))) + + (i - 1 == y ? c : (i > y ? d : v)) -> say + }.for(1..z) - c + h*x + c + (s * (z < y ? z : y) + - (z < y ? v : (z == y ? c : d))) -> say; + c + h*x + c + (s * (z < y ? z : y) + + (z < y ? v : (z == y ? c : d))) -> say { |i| v + s*x + v + (z > y - ? (i >= z ? (s*x + c) : (s * y-i + d)) - : (y - i > z - ? (s * z + v) - : (s * y-i + (y-i == z ? c : d)) +  ? (i >= z ? (s*x + c) : (s * y-i + d)) +  : (y - i > z +  ? (s * z + v) +  : (s * y-i + (y-i == z ? c : d)) ) ) -> say; - } * y; + }.for(1..y) - c + h*x + c -> say; -}; + c + h*x + c -> say +} -cuboid(2, 3, 4); -cuboid(1, 1, 1); -cuboid(6, 2, 1); -cuboid(2, 4, 1); +cuboid(2, 3, 4) +cuboid(1, 1, 1) +cuboid(6, 2, 1) +cuboid(2, 4, 1) diff --git a/Task/Draw-a-cuboid/Zkl/draw-a-cuboid.zkl b/Task/Draw-a-cuboid/Zkl/draw-a-cuboid.zkl new file mode 100644 index 0000000000..ceb6181516 --- /dev/null +++ b/Task/Draw-a-cuboid/Zkl/draw-a-cuboid.zkl @@ -0,0 +1,21 @@ +var [const] M=50.0; +fcn cuboid(w,h,z){ + w*=M; h*=M; z*=M; // relative to abs dimensions + bitmap:=PPM(400,400); + + clr:=0xff0000; // red facing rectangle + bitmap.line(0,0, w,0, clr); bitmap.line(0,0, 0,h, clr); + bitmap.line(0,h, w,h, clr); bitmap.line(w,0, w,h, clr); + + r,a:=(w+z).toFloat().toPolar(0); // relative to the origin + a,b:=r.toRectangular((30.0).toRad() + a).apply("toInt"); c:=a; d:=b+h; + clr=0xff; // blue right side of cuboid + bitmap.line(w,0, a,b, clr); bitmap.line(a,b, c,d, clr); + bitmap.line(w,h, c,d, clr); + + e:=c-w; + clr=0xfff00; // green top of cuboid + bitmap.line(0,h, e,d, clr); bitmap.line(c,d, e,d, clr); + + bitmap.write(File("foo.ppm","wb")); +}(2,3,4); diff --git a/Task/Draw-a-sphere/BASIC/draw-a-sphere-11.basic b/Task/Draw-a-sphere/BASIC/draw-a-sphere-11.basic new file mode 100644 index 0000000000..e490797f13 --- /dev/null +++ b/Task/Draw-a-sphere/BASIC/draw-a-sphere-11.basic @@ -0,0 +1,9 @@ +10 LET I=21 +20 LET J=2 +30 FOR K=-PI TO PI STEP 0.07 +40 PLOT 21+I*SIN K,22+21*COS K +50 PLOT 21+21*SIN K,22+(I-1)*COS K +60 NEXT K +70 LET I=I-J +80 LET J=J+1 +90 IF I>0 THEN GOTO 30 diff --git a/Task/Draw-a-sphere/BBC-BASIC/draw-a-sphere.bbc b/Task/Draw-a-sphere/BBC-BASIC/draw-a-sphere.bbc deleted file mode 100644 index f5a4e0987c..0000000000 --- a/Task/Draw-a-sphere/BBC-BASIC/draw-a-sphere.bbc +++ /dev/null @@ -1,117 +0,0 @@ - MODE 8 - INSTALL @lib$+"D3DLIB" - D3DTS_VIEW = 2 - D3DTS_PROJECTION = 3 - D3DRS_SPECULARENABLE = 29 - - SYS "LoadLibrary", @lib$+"D3DX8BBC.DLL" TO d3dx% - IF d3dx%=0 ERROR 100, "Couldn't load D3DX8BBC.DLL" - SYS "GetProcAddress", d3dx%, "D3DXCreateSphere" TO `D3DXCreateSphere` - SYS "GetProcAddress", d3dx%, "D3DXMatrixLookAtLH" TO `D3DXMatrixLookAtLH` - SYS "GetProcAddress", d3dx%, "D3DXMatrixPerspectiveFovLH" TO `D3DXMatrixPerspectiveFovLH` - - DIM eyepos%(2), lookat%(2), up%(2), mat%(3,3) - - DIM D3Dlight8{Type%, Diffuse{r%,g%,b%,a%}, Specular{r%,g%,b%,a%}, \ - \ Ambient{r%,g%,b%,a%}, Position{x%,y%,z%}, Direction{x%,y%,z%}, \ - \ Range%, Falloff%, Attenuation0%, Attenuation1%, Attenuation2%, \ - \ Theta%, Phi%} - - DIM D3Dmaterial8{Diffuse{r%,g%,b%,a%}, Ambient{r%,g%,b%,a%}, \ - \ Specular{r%,g%,b%,a%}, Emissive{r%,g%,b%,a%}, Power%} - - DIM D3Dbasemesh8{QueryInterface%, Addref%, Release%, \ - \ DrawSubset%, GetNumFaces%, GetNumVertices%, GetFVF%, \ - \ GetDeclaration%, GetOptions%, GetDevice%, \ - \ CloneMeshFVF%, CloneMesh%, GetVertexBuffer%, GetIndexBuffer%, \ - \ LockVertexBuffer%, UnlockVertexBuffer%, LockIndexBuffer%, \ - \ UnlockIndexBuffer%, GetAttributeTable%} - - DIM D3Ddevice8{QueryInterface%, AddRef%, Release%, TestCooperativeLevel%, \ - \ GetAvailableTextureMem%, ResourceManagerDiscardBytes%, GetDirect3D%, \ - \ GetDeviceCaps%, GetDisplayMode%, GetCreationParameters%, SetCursorProperties%, \ - \ SetCursorPosition%, ShowCursor%, CreateAdditionalSwapChain%, Reset%, \ - \ Present%, GetBackBuffer%, GetRasterStatus%, SetGammaRamp%, GetGammaRamp%, \ - \ CreateTexture%, CreateVolumeTexture%, CreateCubeTexture%, CreateVertexBuffer%, \ - \ CreateIndexBuffer%, CreateRenderTarget%, CreateDepthStencilSurface%, \ - \ CreateImageSurface%, CopyRects%, UpdateTexture%, GetFrontBuffer%, \ - \ SetRenderTarget%, GetRenderTarget%, GetDepthStencilSurface%, BeginScene%, \ - \ EndScene%, Clear%, SetTransform%, GetTransform%, MultiplyTransform%, \ - \ SetViewport%, GetViewport%, SetMaterial%, GetMaterial%, SetLight%, GetLight%, \ - \ LightEnable%, GetLightEnable%, SetClipPlane%, GetClipPlane%, SetRenderState%, \ - \ GetRenderState%, BeginStateBlock%, EndStateBlock%, ApplyStateBlock%, \ - \ CaptureStateBlock%, DeleteStateBlock%, CreateStateBlock%, SetClipStatus%, \ - \ GetClipStatus%, GetTexture%, SetTexture%, GetTextureStageState%, \ - \ SetTextureStageState%, ValidateDevice%, GetInfo%, SetPaletteEntries%, \ - \ GetPaletteEntries%, SetCurrentTexturePalette%, GetCurrentTexturePalette%, \ - \ DrawPrimitive%, DrawIndexedPrimitive%, DrawPrimitiveUP%, \ - \ DrawIndexedPrimitiveUP%, ProcessVertices%, CreateVertexShader%, \ - \ SetVertexShader%, GetVertexShader%, DeleteVertexShader%, \ - \ SetVertexShaderConstant%, GetVertexShaderConstant%, GetVertexShaderDeclaration%, \ - \ GetVertexShaderFunction%, SetStreamSource%, GetStreamSource%, SetIndices%, \ - \ GetIndices%, CreatePixelShader%, SetPixelShader%, GetPixelShader%, \ - \ DeletePixelShader%, SetPixelShaderConstant%, GetPixelShaderConstant%, \ - \ GetPixelShaderFunction%, DrawRectPatch%, DrawTriPatch%, DeletePatch%} - - pDevice%=FN_initd3d(@hwnd%, 1, 1) - IF pDevice%=0 ERROR 100, "Couldn't create Direct3D8 device" - !(^D3Ddevice8{}+4) = !pDevice% - - SYS `D3DXCreateSphere`, pDevice%, FN_f4(1), 50, 50, ^meshSphere%, 0 - IF meshSphere% = 0 ERROR 100, "D3DXCreateSphere failed" - !(^D3Dbasemesh8{}+4) = !meshSphere% - - REM. Point-source light: - D3Dlight8.Type%=1 : REM. point source - D3Dlight8.Diffuse.r% = FN_f4(1) - D3Dlight8.Diffuse.g% = FN_f4(1) - D3Dlight8.Diffuse.b% = FN_f4(1) - D3Dlight8.Specular.r% = FN_f4(1) - D3Dlight8.Specular.g% = FN_f4(1) - D3Dlight8.Specular.b% = FN_f4(1) - D3Dlight8.Position.x% = FN_f4(2) - D3Dlight8.Position.y% = FN_f4(1) - D3Dlight8.Position.z% = FN_f4(4) - D3Dlight8.Range% = FN_f4(10) - D3Dlight8.Attenuation0% = FN_f4(1) - - REM. Material: - D3Dmaterial8.Diffuse.r% = FN_f4(0.2) - D3Dmaterial8.Diffuse.g% = FN_f4(0.6) - D3Dmaterial8.Diffuse.b% = FN_f4(1.0) - D3Dmaterial8.Specular.r% = FN_f4(0.4) - D3Dmaterial8.Specular.g% = FN_f4(0.4) - D3Dmaterial8.Specular.b% = FN_f4(0.4) - D3Dmaterial8.Power% = FN_f4(100) - - fovy = RAD(30) - aspect = 5/4 - znear = 1 - zfar = 1000 - bkgnd% = &7F7F7F - eyepos%() = 0, 0, FN_f4(6) - lookat%() = 0, 0, 0 - up%() = 0, FN_f4(1), 0 - - SYS D3Ddevice8.Clear%, pDevice%, 0, 0, 3, bkgnd%, FN_f4(1), 0 - SYS D3Ddevice8.BeginScene%, pDevice% - SYS D3Ddevice8.SetLight%, pDevice%, 0, D3Dlight8{} - SYS D3Ddevice8.LightEnable%, pDevice%, 0, 1 - SYS D3Ddevice8.SetMaterial%, pDevice%, D3Dmaterial8{} - SYS D3Ddevice8.SetRenderState%, pDevice%, D3DRS_SPECULARENABLE, 1 - - SYS `D3DXMatrixLookAtLH`, ^mat%(0,0), ^eyepos%(0), ^lookat%(0), ^up%(0) - SYS D3Ddevice8.SetTransform%, pDevice%, D3DTS_VIEW, ^mat%(0,0) - - SYS `D3DXMatrixPerspectiveFovLH`, ^mat%(0,0), FN_f4(fovy), \ - \ FN_f4(aspect), FN_f4(znear), FN_f4(zfar) - SYS D3Ddevice8.SetTransform%, pDevice%, D3DTS_PROJECTION, ^mat%(0,0) - - SYS D3Dbasemesh8.DrawSubset%, meshSphere%, 0 - SYS D3Ddevice8.EndScene%, pDevice% - SYS D3Ddevice8.Present%, pDevice%, 0, 0, 0, 0 - - SYS D3Ddevice8.Release%, pDevice% - SYS D3Dbasemesh8.Release%, meshSphere% - SYS "FreeLibrary", d3dx% - END diff --git a/Task/Draw-a-sphere/C/draw-a-sphere-3.c b/Task/Draw-a-sphere/C/draw-a-sphere-3.c deleted file mode 100644 index dc31435dd2..0000000000 --- a/Task/Draw-a-sphere/C/draw-a-sphere-3.c +++ /dev/null @@ -1,162 +0,0 @@ -#include -#include -#include - -#define MAXD 8 -int g[] = { -1, 1, -1, 1 }; -/* Perlin-like noise */ -inline void -hashed(int *data, int *out, int len) { -# define ror(a, d) ((a << (d)) | (a >> (32 - d))) - register unsigned int h = 0x12345678, tmp; - unsigned int *d = (void*)data; - int i = len; - - while (i--) { - tmp = *d++; - h += ror(h, 15) ^ ror(tmp, 5); - } - - h ^= ror(h, 7); - h += ror(h, 23); - h ^= ror(h, 19); - h += ror(h, 11); - h ^= ror(h, 13); - h += ror(h, 17); -# undef ror - for (i = len; i--; ) { - out[i] = g[h & 3]; - h >>= 2; - } -} - -double scale[MAXD], scale_u[MAXD]; -void noise_init() -{ - int i; - for (i = 1; i < MAXD; i++) { - scale[i] = 1 / (1 + sqrt(i + 1)); - scale_u[i] = scale[i] / sqrt(i + 1); - } -} - -double noise(double *x, int d) -{ -# define sum(s, x) for (s = 0, j = 0; j < d; j++) s += x - register int i, j; - int n[MAXD], o[MAXD], g[MAXD], tmp; - double s, r, t, w, ret, u[MAXD]; - - sum(s, x[j]); - s *= scale[d]; - - for (i = 0; i < d; i++) { - o[i] = i; - t = x[i] + s; - u[i] = t - (n[i] = floor(t)); - } - o[d] = 0; - - for (i = 0; i < d - 1; i++) - for (j = i; j < d; j++) - if (u[o[i]] < u[o[j]]) - tmp = o[i], o[i] = o[j], o[j] = tmp; - - ret = w = 0, r = 1; - for (s = 0, j = 0; j < d; j++) s += n[j]; - s *= scale_u[d]; - - for (i = 0; i <= d; i++) { - for (j = 0; j < d; j++) - u[j] = x[j] + s - n[j]; - - for (t = (d + 1.) / (2 * d), j = 0; j < d; j++) { - t -= u[j] * u[j]; - if (t <= 0) break; - } - - if (t >= 0) { - r = 0; - hashed(n, g, d); - for (j = 0; j < d; j++) - if (g[j]) r += (g[j] == 1 ? u[j] : -u[j]); - t *= t; - ret += r * t * t; - } - - if (i < d) { - n[o[i]]++; - s += scale_u[d]; - } - } - return ret * (d * d); -} - -double get_noise2(double x, double y) -{ - int i, ws; - double r = 0, v[2]; - - for (i = 1, ws = 0; i <= 128; i <<= 1) { - v[0] = x * i, v[1] = y * i; - r += noise(v, 2); - ws ++; - } - r /= ws; - return r; -} - -double get_noise3(double x, double y, double z) -{ - int i, ws; - double r = 0, v[3], w; - - for (i = 1, ws = 0; i <= 32; i <<= 1) { - v[0] = x * i, v[1] = y * i, v[2] = z * i; - w = 1./sqrt(i); - r += noise(v, 3) * w; - ws += w; - } - return r / ws; -} - - -int main(int c, char** v) -{ - unsigned char pix[256 * 256], *p; - int i, j; - double x, y, z, w; - FILE *fp; - - noise_init(); - - for (p = pix, i = 0; i < 256 * 256; i++) *p++ = 0; - - for (p = pix, i = 0; i < 256; i++) { - y = (i - 128) / 125.; - for (j = 0; j < 256; j++, p++) { - x = (j - 128) / 125.; - *p = (get_noise2(i/256., j/256.) + 1) / 6 * i; - - z = 1- x*x - y*y; - if (z < 0) continue; - - z = sqrt(z); - - w = get_noise3(x, y, z); - - w = (w + 1) / 2; - w *= (1 + x - y + z) / 3.5; - if (w < 0) w = 0; - - *p = w * 255; - } - } - - fp = fopen("out.pgm", "w+"); - fprintf(fp, "P5\n256 256\n255\n"); - fwrite(pix, 1, 256 * 256, fp); - fclose(fp); - - return 0; -} diff --git a/Task/Draw-a-sphere/jq/draw-a-sphere-1.jq b/Task/Draw-a-sphere/Jq/draw-a-sphere-1.jq similarity index 100% rename from Task/Draw-a-sphere/jq/draw-a-sphere-1.jq rename to Task/Draw-a-sphere/Jq/draw-a-sphere-1.jq diff --git a/Task/Draw-a-sphere/jq/draw-a-sphere-2.jq b/Task/Draw-a-sphere/Jq/draw-a-sphere-2.jq similarity index 100% rename from Task/Draw-a-sphere/jq/draw-a-sphere-2.jq rename to Task/Draw-a-sphere/Jq/draw-a-sphere-2.jq diff --git a/Task/Draw-a-sphere/jq/draw-a-sphere-3.jq b/Task/Draw-a-sphere/Jq/draw-a-sphere-3.jq similarity index 100% rename from Task/Draw-a-sphere/jq/draw-a-sphere-3.jq rename to Task/Draw-a-sphere/Jq/draw-a-sphere-3.jq diff --git a/Task/Draw-a-sphere/Julia/draw-a-sphere.julia b/Task/Draw-a-sphere/Julia/draw-a-sphere.julia new file mode 100644 index 0000000000..7f12d6a75a --- /dev/null +++ b/Task/Draw-a-sphere/Julia/draw-a-sphere.julia @@ -0,0 +1,29 @@ +# v0.6 + +function draw_sphere(r, k, ambient, light) + shades = ('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@') + for i in floor(Int, -r):ceil(Int, r) + x = i + 0.5 + line = IOBuffer() + for j in floor(Int, -2r):ceil(2r) + y = j / 2 + 0.5 + if x ^ 2 + y ^ 2 ≤ r ^ 2 + v = normalize([x, y, sqrt(r ^ 2 - x ^ 2 - y ^ 2)]) + b = dot(light, v) ^ k + ambient + intensity = ceil(Int, (1 - b) * (length(shades) - 1)) + if intensity < 1 + intensity = 1 end + if intensity > length(shades) + intensity = length(shades) end + print(shades[intensity]) + else + print(' ') + end + end + println() + end +end + +light = normalize([30, 30, -50]) +draw_sphere(20, 4, 0.1, light) +draw_sphere(10, 2, 0.4, light) diff --git a/Task/Draw-a-sphere/Kotlin/draw-a-sphere.kotlin b/Task/Draw-a-sphere/Kotlin/draw-a-sphere.kotlin new file mode 100644 index 0000000000..3fc21d5d44 --- /dev/null +++ b/Task/Draw-a-sphere/Kotlin/draw-a-sphere.kotlin @@ -0,0 +1,47 @@ +// version 1.0.6 + +const val shades = ".:!*oe&#%@" +val light = doubleArrayOf(30.0, 30.0, -50.0) + +fun normalize(v: DoubleArray) { + val len = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]) + v[0] /= len; v[1] /= len; v[2] /= len +} + +fun dot(x: DoubleArray, y: DoubleArray): Double { + val d = x[0] * y[0] + x[1] * y[1] + x[2] * y[2] + return if (d < 0.0) -d else 0.0 +} + +fun drawSphere(r: Double, k: Double, ambient: Double) { + val vec = DoubleArray(3) + var intensity: Int + var b : Double + var x: Double + var y: Double + for (i in Math.floor(-r).toInt() .. Math.ceil(r).toInt()) { + x = i + 0.5 + for (j in Math.floor(-2.0 * r).toInt() .. Math.ceil(2.0 * r).toInt()) { + y = j / 2.0 + 0.5 + if (x * x + y * y <= r * r) { + vec[0] = x + vec[1] = y + vec[2] = Math.sqrt(r * r - x * x - y * y) + normalize(vec) + b = Math.pow(dot(light, vec), k) + ambient + intensity = ((1.0 - b) * (shades.length - 1)).toInt() + if (intensity < 0) intensity = 0 + if (intensity >= shades.length - 1) intensity = shades.length - 2 + print(shades[intensity]) + } + else print(' ') + } + println() + } +} + +fun main(args: Array) { + normalize(light) + drawSphere(20.0, 4.0, 0.1) + drawSphere(10.0, 2.0, 0.4) +} diff --git a/Task/Draw-a-sphere/Liberty-BASIC/draw-a-sphere.liberty b/Task/Draw-a-sphere/Liberty-BASIC/draw-a-sphere.liberty deleted file mode 100644 index 735550a7b8..0000000000 --- a/Task/Draw-a-sphere/Liberty-BASIC/draw-a-sphere.liberty +++ /dev/null @@ -1,26 +0,0 @@ -WindowWidth =420 -WindowHeight =460 - -nomainwin - -open "Sphere" for graphics_nsb_nf as #w - -#w "down ; fill lightgray" - -xS =200 -yS =200 -for radius =150 to 0 step -1 - level$ =str$( int( 256 -256 *radius /150)) - c$ =level$ +" " +level$ +" " +level$ - #w "color "; c$ - #w "backcolor "; c$ - #w "place "; xS; " "; yS - xS =xS -0.5 - yS =yS -0.2 - #w "circlefilled "; radius -next radius - -#w "flush" -wait -close #w -end diff --git a/Task/Draw-a-sphere/Perl-6/draw-a-sphere.pl6 b/Task/Draw-a-sphere/Perl-6/draw-a-sphere.pl6 index 6eee506c40..88277048d0 100644 --- a/Task/Draw-a-sphere/Perl-6/draw-a-sphere.pl6 +++ b/Task/Draw-a-sphere/Perl-6/draw-a-sphere.pl6 @@ -6,8 +6,8 @@ my @light = normalize([ 3, 2, -5 ]); my $depth = 255; sub MAIN ($outfile = 'sphere-perl6.pgm') { - my $out = open( $outfile, :w, :bin ) or die "$!\n"; - $out.say("P5\n$x $y\n$depth"); # .pgm header + spurt $outfile, "P5\n$x $y\n$depth\n"; # .pgm header + my $out = open( $outfile, :a, :bin ) or die "$!\n"; $out.write( Blob.new(draw_sphere( ($x-1)/2, .9, .2) ) ); $out.close; } diff --git a/Task/Draw-a-sphere/Phix/draw-a-sphere.phix b/Task/Draw-a-sphere/Phix/draw-a-sphere.phix new file mode 100644 index 0000000000..83ae7db48c --- /dev/null +++ b/Task/Draw-a-sphere/Phix/draw-a-sphere.phix @@ -0,0 +1,77 @@ +-- +-- demo\rosetta\Draw_a_sphere.exw +-- +include pGUI.e + +Ihandle dlg, canvas +cdCanvas cddbuffer, cdcanvas + +function dot(sequence x, sequence y) + return sum(sq_mul(x,y)) +end function + +function normalize(sequence v) + atom len = sqrt(dot(v, v)) + if len=0 then return {0,0,0} end if + return sq_mul(v,1/len) +end function + +procedure drawSphere(integer width, height, atom k, atom amb, sequence direction) +integer r = floor((min(width,height)-20)/2) +integer cx = floor(width/2) +integer cy = floor(height/2) +integer lum + for x=-r to r do + for y=-r to r do + integer z = r*r-x*x-y*y + if z>=0 then + atom s = dot(direction, normalize({x,y,sqrt(z)})) + lum = and_bits(#FF,255*(power(iff(s<0?0:s),k)+amb)/(1+amb)) + lum += lum*#100+lum*#10000 + cdCanvasPixel(cddbuffer, x+cx, y+cy, lum) + end if + end for + end for +end procedure + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) +integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") + cdCanvasActivate(cddbuffer) + cdCanvasClear(cddbuffer) + drawSphere(width,height,1.5,0.2,normalize({-30,-30,50})) + cdCanvasFlush(cddbuffer) + return IUP_DEFAULT +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + cdCanvasSetBackground(cddbuffer, CD_BLACK) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "340x340") -- initial size + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", "Draw a sphere") + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + + IupMap(dlg) + IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation + IupShowXY(dlg,IUP_CENTER,IUP_CENTER) + IupMainLoop() + IupClose() +end procedure + +main() diff --git a/Task/Draw-a-sphere/PureBasic/draw-a-sphere.purebasic b/Task/Draw-a-sphere/PureBasic/draw-a-sphere.purebasic deleted file mode 100644 index 62ec5d717d..0000000000 --- a/Task/Draw-a-sphere/PureBasic/draw-a-sphere.purebasic +++ /dev/null @@ -1,251 +0,0 @@ -; Original by Comtois @ 28/03/06 -; -; Updated/Formated by Fluid Byte @ March.24,2009 -; -; http://www.purebasic.fr/english/viewtopic.php?p=281258#p281258 - -Declare CreateSphere(M,P) -Declare UpdateMesh() - -#_SIZEVERT = 36 -#_SIZETRIS = 6 -#FULLSCREEN = 0 - -Structure VECTOR - X.f - Y.f - Z.f -EndStructure - -Structure VERTEX - X.f - Y.f - Z.f - NX.f - NY.f - NZ.f - Color.l - U.f - V.f -EndStructure - -Structure TRIANGLE - V1.w - V2.w - V3.w -EndStructure - -Macro CALC_NORMALS - *PtrV\NX = *PtrV\X - *PtrV\NY = *PtrV\Y - *PtrV\NZ = *PtrV\Z -EndMacro - -Global *VBuffer, *IBuffer -Global Meridian = 50, Parallele = 50, PasLength = 4, Length - -Define EventID, i, NbSommet, CameraMode, Angle.f, Pas.f = 0.5 - -InitEngine3D() : InitSprite() : InitKeyboard() - -Add3DArchive(GetTemporaryDirectory(),#PB_3DArchive_FileSystem) -Add3DArchive(#PB_Compiler_Home + "Examples\Sources\Data\",#PB_3DArchive_FileSystem) - -If #FULLSCREEN - OpenScreen(800,600,32,"Sphere 3D") -Else - OpenWindow(0,0,0,800,600,"Sphere 3D",#PB_Window_SystemMenu | 1) - OpenWindowedScreen(WindowID(0),0,0,800,600,0,0,0) -EndIf - -;-Texture -CreateImage(0,128,128) -StartDrawing(ImageOutput(0)) -For i = 0 To 127 Step 4 - Box(0,i,ImageWidth(0),2,RGB(255,255,255)) - Box(0,i + 2,ImageWidth(0),2,RGB(0,0,155)) -Next i -StopDrawing() -SaveImage(0,GetTemporaryDirectory() + "temp.bmp") : FreeImage(0) - -;-Material -CreateMaterial(0,LoadTexture(0,"temp.bmp")) -RotateMaterial(0,0.1,#PB_Material_Animated) - -;-Mesh -CreateSphere(Meridian,Parallele) - -;-Entity -CreateEntity(0,MeshID(0),MaterialID(0)) -ScaleEntity(0,60,60,60) - -;-Camera -CreateCamera(0,0,0,100,100) -MoveCamera(0,0,0,-200) -CameraLookAt(0,EntityX(0),EntityY(0),EntityZ(0)) - -;-Light -AmbientColor(RGB(105, 105, 105)) -CreateLight(0, RGB(255, 255, 55), EntityX(0) + 150, EntityY(0) , EntityZ(0)) -CreateLight(1, RGB( 55, 255, 255), EntityX(0) - 150, EntityY(0) , EntityZ(0)) -CreateLight(2, RGB( 55, 55, 255), EntityX(0) , EntityY(0) + 150, EntityZ(0)) -CreateLight(3, RGB(255, 55, 255), EntityX(0) , EntityY(0) - 150, EntityZ(0)) - -; ---------------------------------------------------------------------------------------------------- -; MAINLOOP -; ---------------------------------------------------------------------------------------------------- - -Repeat - If #FULLSCREEN = 0 - Repeat - EventID = WindowEvent() - - Select EventID - Case #PB_Event_CloseWindow : End - EndSelect - Until EventID = 0 - EndIf - - Angle + Pas - RotateEntity(0, Angle, Angle,Angle) - - If PasLength > 0 : UpdateMesh() : EndIf - - If ExamineKeyboard() - If KeyboardReleased(#PB_Key_F1) - CameraMode = 1 - CameraMode - CameraRenderMode(0, CameraMode) - EndIf - EndIf - - RenderWorld() - FlipBuffers() -Until KeyboardPushed(#PB_Key_Escape) - -; ---------------------------------------------------------------------------------------------------- -; FUNCTIONS -; ---------------------------------------------------------------------------------------------------- - -Procedure CreateSphere(M,P) - ; M = Meridian - ; P = Parallele - ; The radius is 1. Front to remove it later, it's just for the demo. - - If M < 3 Or P < 2 : ProcedureReturn 0 : EndIf - - Protected Normale.VECTOR, NbSommet, i, j, Theta.f, cTheta.f, sTheta.f - Protected Alpha.f, cAlpha.f, sAlpha.f, *PtrV.VERTEX, *PtrF.TRIANGLE, NbTriangle - - NbSommet = 2 + ((M + 1) * P) - *VBuffer = AllocateMemory(#_SIZEVERT * Nbsommet) - - For i = 0 To M - Theta = i * #PI * 2.0 / M - cTheta = Cos(theta) - sTheta = Sin(theta) - - For j = 1 To P - Alpha = j * #PI / (P + 1) - cAlpha = Cos(Alpha) - sAlpha = Sin(Alpha) - *PtrV = *VBuffer + #_SIZEVERT * ((i * P) + (j - 1)) - *PtrV\X = sAlpha * cTheta - *PtrV\Y = sAlpha * sTheta - *PtrV\Z = cAlpha - *PtrV\U = Theta / (2.0 * #PI) - *PtrV\V = Alpha / #PI - CALC_NORMALS - Next j - Next i - - ; Southpole - *PtrV = *VBuffer + #_SIZEVERT * ((M + 1) * P) - *PtrV\X = 0 - *PtrV\Y = 0 - *PtrV\Z = -1 - *PtrV\U = 0 - *PtrV\V = 0 - CALC_NORMALS - - ; Northpole - *PtrV + #_SIZEVERT - *PtrV\X = 0 - *PtrV\Y = 0 - *PtrV\Z = 1 - *PtrV\U = 0 - *PtrV\V = 0 - CALC_NORMALS - - ; Les facettes - NbTriangle = 4 * M * P - *IBuffer = AllocateMemory(#_SIZETRIS * NbTriangle) - *PtrF = *IBuffer - - For i = 0 To M - 1 - For j = 1 To P - 1 - *PtrF\V1 = ((i + 1) * P) + j - *PtrF\V2 = ((i + 1) * P) + (j - 1) - *PtrF\V3 = (i * P) + (j - 1) - *PtrF + #_SIZETRIS - *PtrF\V3 = ((i + 1) * P) + j ;Recto - *PtrF\V2 = ((i + 1) * P) + (j - 1) ;Recto - *PtrF\V1 = (i * P) + (j - 1) ;Recto - *PtrF + #_SIZETRIS - *PtrF\V1 = i * P + j - *PtrF\V2 = ((i + 1) * P) + j - *PtrF\V3 = (i * P) + (j - 1) - *PtrF + #_SIZETRIS - *PtrF\V3 = i * P + j ;Recto - *PtrF\V2 = ((i + 1) * P) + j ;Recto - *PtrF\V1 = (i * P) + (j - 1) ;Recto - *PtrF + #_SIZETRIS - Next j - Next i - - ; The Poles - For i = 0 To M - 1 - *PtrF\V3 = (M + 1) * P + 1 - *PtrF\V2 = (i + 1) * P - *PtrF\V1 = i * P - *PtrF + #_SIZETRIS - *PtrF\V1 = (M + 1) * P + 1 ;Recto - *PtrF\V2 = (i + 1) * P ;Recto - *PtrF\V3 = i * P ;Recto - *PtrF + #_SIZETRIS - Next i - - For i = 0 To M - 1 - *PtrF\V3 = (M + 1) * P - *PtrF\V2 = i * P + (P - 1) - *PtrF\V1 = (i + 1) * P + (P - 1) - *PtrF + #_SIZETRIS - *PtrF\V1 = (M + 1) * P ;Recto - *PtrF\V2 = i * P + (P - 1) ;Recto - *PtrF\V3 = (i + 1) * P + (P - 1) ;Recto - *PtrF + #_SIZETRIS - Next i - - If CreateMesh(0,100) - Protected Flag = #PB_Mesh_Vertex | #PB_Mesh_Normal | #PB_Mesh_UVCoordinate | #PB_Mesh_Color - SetMeshData(0,Flag,*VBuffer,NbSommet) - SetMeshData(0,#PB_Mesh_Face,*IBuffer,NbTriangle) - ProcedureReturn 1 - EndIf - - ProcedureReturn 0 -EndProcedure - -; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Procedure UpdateMesh() - Protected NbTriangle = 4 * Meridian * Parallele - - Length + PasLength - - If Length >= NbTriangle - PasLength = 0 - Length = Nbtriangle - EndIf - - SetMeshData(0,#PB_Mesh_Face,*IBuffer,Length) -EndProcedure diff --git a/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx b/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx index a743b61228..671d65d0aa 100644 --- a/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx +++ b/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx @@ -12,21 +12,22 @@ drawSphere: procedure; parse arg r, k, ambient /*get the arguments else shading= "·:!°oe@░▒▓" /* ASCII " " */ lightSource= '30 30 -50' /*position of light source.*/ parse value norm(lightSource) with s1 s2 s3 /*normalize light source. */ - sLen=length(shading)-1; rr=r*r /*handy─dandy variables. */ + shadeLen=length(shading) - 1; rr=r**2; r2=r+r /*handy─dandy variables. */ - do i=floor(-r) to ceil(r) ; x= i+.5; xx=x**2; $= - do j=floor(-2*r) to ceil(r+r); y=j/2+.5; yy=y**2 + do i=floor( -r) to ceil( r); x=i + .5; xx=x**2; $= + do j=floor(-r2) to ceil(r2); y=j * .5 + .5; yy=y**2 if xx+yy<=rr then do /*is point within sphere ? */ - parse value norm(x y sqrt(rr-xx-yy)) with v1 v2 v3 - dot=s1*v1 + s2*v2 + s3*v3 /*the dot product of the Vs*/ + parse value norm(x y sqrt(rr-xx-yy) ) with v1 v2 v3 + dot=s1*v1 + s2*v2 + s3*v3 /*the dot product of the Vs*/ + if dot>0 then dot=0 /*if positive, make it zero*/ /*◄■■■■ same as: dot=max(0, dot) */ if dot>0 then dot=0 /*if positive, make it zero*/ - b=abs(dot)**k + ambient /*calculate the brightness.*/ - if b<=0 then brite=sLen - else brite=trunc( max( (1-b) * sLen, 0) ) - $=($)substr(shading,brite+1,1) /*construct a display line.*/ - end + b=-dot**k + ambient /*calculate the brightness.*/ + if b<=0 then brite=shadeLen + else brite=max( (1-b) * shadeLen, 0) % 1 + $=($)substr(shading, brite + 1, 1) + end /* [↑] build display line.*/ else $=$' ' /*append a blank to line. */ - end /*j*/ + end /*j*/ /*[↓] strip trailing blanks*/ say strip($, 'T') /*show a line of the sphere*/ end /*i*/ /* [↑] display the sphere.*/ return diff --git a/Task/Draw-a-sphere/Run-BASIC/draw-a-sphere.run b/Task/Draw-a-sphere/Run-BASIC/draw-a-sphere.run deleted file mode 100644 index 9050322206..0000000000 --- a/Task/Draw-a-sphere/Run-BASIC/draw-a-sphere.run +++ /dev/null @@ -1,4 +0,0 @@ -graphic #g, 300, 300 'create a graphic object -#g place(100,100) 'place the drawing pen at 100,100 -#g circle(75) 'make a circle with radius 75 -render #g 'show it diff --git a/Task/Draw-a-sphere/Sidef/draw-a-sphere.sidef b/Task/Draw-a-sphere/Sidef/draw-a-sphere.sidef index 6b454adec2..b4a582b9ad 100644 --- a/Task/Draw-a-sphere/Sidef/draw-a-sphere.sidef +++ b/Task/Draw-a-sphere/Sidef/draw-a-sphere.sidef @@ -1,5 +1,5 @@ func normalize (vec) { vec »/» (vec »*« vec -> sum.sqrt) } -func dot (x, y) { -(x »*« y -> sum) ^max^ 0 } +func dot (x, y) { -(x »*« y -> sum) `max` 0 }   var x = var y = 255 x += 1 if x.is_even # must be odd @@ -15,7 +15,7 @@ func draw_sphere(rad, k, ambient) { if ((var x2 = x*x) + (var y2 = y*y) < r2) { var vector = normalize([x, y, (r2 - x2 - y2).sqrt]) var intensity = (dot(light, vector)**k + ambient) - var pixel = (0 ^max^ (intensity*depth -> int) ^min^ depth) + var pixel = (0 `max` (intensity*depth -> int) `min` depth) pixels << pixel } else { @@ -29,5 +29,5 @@ var outfile = %f'sphere-sidef.pgm' var out = outfile.open('>:raw')   out.say("P5\n#{x} #{y}\n#{depth}") # .pgm header -out.write(draw_sphere((x-1)/2, .9, .2).map{.chr}.join) +out.print(draw_sphere((x-1)/2, .9, .2).map{.chr}.join) out.close diff --git a/Task/Draw-a-sphere/Zkl/draw-a-sphere-1.zkl b/Task/Draw-a-sphere/Zkl/draw-a-sphere-1.zkl new file mode 100644 index 0000000000..81e54abe2f --- /dev/null +++ b/Task/Draw-a-sphere/Zkl/draw-a-sphere-1.zkl @@ -0,0 +1,15 @@ +img:=PPM(640,480); +R:=100; R2:=R*R; //radius, in pixels; radius squared +X0:=640/2; Y0:=480/2; //coordinates of center of screen +foreach Y in ([-R..R]){ //for all the coordinates near the circle + foreach X in ([-R..R]){ // which is under the sphere + D2:=X*X + Y*Y; + C:=0; //default color is black + if(D2<=R2){ //coordinate is inside circle under sphere + Z:=(R2-D2).toFloat().sqrt();//height of point on surface of sphere above X,Y + C=0x82+Z-(X+Y)/2; //color is proportional; offset X and Y, and + } // shift color to upper limit of its range + img[X+X0,Y+Y0]=C.shiftLeft(8)+C; //green + blue = cyan + } +} +img.write(File("foo.ppm","wb")); diff --git a/Task/Draw-a-sphere/Zkl/draw-a-sphere-2.zkl b/Task/Draw-a-sphere/Zkl/draw-a-sphere-2.zkl new file mode 100644 index 0000000000..a2b16b618b --- /dev/null +++ b/Task/Draw-a-sphere/Zkl/draw-a-sphere-2.zkl @@ -0,0 +1 @@ +img[X+X0,Y+Y0]=C*140+C; diff --git a/Task/Draw-a-sphere/Zkl/draw-a-sphere-3.zkl b/Task/Draw-a-sphere/Zkl/draw-a-sphere-3.zkl new file mode 100644 index 0000000000..2e2bc01282 --- /dev/null +++ b/Task/Draw-a-sphere/Zkl/draw-a-sphere-3.zkl @@ -0,0 +1,23 @@ +#<<< +cmd:=0'| +set term wxt +set parametric +set urange [0:pi] +set vrange [0:2*pi] +set xyplane 0 +set view equal xyz +set pm3d hidden3d 100 depthorder +set style line 100 lt 7 lw 0.1 +set palette defined (0 "dark-blue", 1 "light-blue") +unset key +set samples 24 +set isosamples 36 +set title 'sphere (pm3d)' font "Times,20" +R = 3 +splot R*sin(u)*cos(v), R*sin(u)*sin(v), R*cos(u) w pm3d +|; +#<<< + +gnuplot:=System.popen("gnuplot","w"); +gnuplot.write(cmd); gnuplot.flush(); +ask("Hit return to finish"); gnuplot.close(); diff --git a/Task/Dutch-national-flag-problem/BaCon/dutch-national-flag-problem.bacon b/Task/Dutch-national-flag-problem/BaCon/dutch-national-flag-problem.bacon new file mode 100644 index 0000000000..01cf23c65b --- /dev/null +++ b/Task/Dutch-national-flag-problem/BaCon/dutch-national-flag-problem.bacon @@ -0,0 +1,9 @@ +DECLARE color$[] = { "red", "white", "blue" } + +DOTIMES 16 + ball$ = APPEND$(ball$, 0, color$[RANDOM(3)] ) +DONE + +PRINT "Unsorted: ", ball$ + +PRINT " Sorted: ", REPLACE$(SORT$(REPLACE$(ball$, "blue", "z")), "z", "blue") diff --git a/Task/Dutch-national-flag-problem/Elixir/dutch-national-flag-problem.elixir b/Task/Dutch-national-flag-problem/Elixir/dutch-national-flag-problem.elixir index ffd91a6231..449904fe50 100644 --- a/Task/Dutch-national-flag-problem/Elixir/dutch-national-flag-problem.elixir +++ b/Task/Dutch-national-flag-problem/Elixir/dutch-national-flag-problem.elixir @@ -3,9 +3,9 @@ defmodule Dutch_national_flag do defp ball(:white), do: 2 defp ball(:blue), do: 3 - @color {:red, :white, :blue} - defp random_ball, do: elem(@color, :rand.uniform(3)-1) - defp random_ball(n), do: (for _ <- 1..n, do: random_ball) + defp random_ball, do: Enum.random([:red, :white, :blue]) + + defp random_ball(n), do: (for _ <- 1..n, do: random_ball()) defp is_dutch([]), do: true defp is_dutch([_]), do: true @@ -13,7 +13,8 @@ defmodule Dutch_national_flag do defp is_dutch(_), do: false def dutch(list), do: dutch([], [], [], list) - defp dutch(r, w, b, []), do: r ++ w ++ b + + defp dutch(r, w, b, []), do: r ++ w ++ b defp dutch(r, w, b, [:red | list]), do: dutch([:red | r], w, b, list) defp dutch(r, w, b, [:white | list]), do: dutch(r, [:white | w], b, list) defp dutch(r, w, b, [:blue | list]), do: dutch(r, w, [:blue | b], list) diff --git a/Task/Dutch-national-flag-problem/Gambas/dutch-national-flag-problem.gambas b/Task/Dutch-national-flag-problem/Gambas/dutch-national-flag-problem.gambas new file mode 100644 index 0000000000..bd91734ac3 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Gambas/dutch-national-flag-problem.gambas @@ -0,0 +1,26 @@ +Public Sub Main() +Dim Red As String = "0" +Dim White As String = "1" +Dim Blue As String = "2" +Dim siCount As Short +Dim sColours As New String[] +Dim sTemp As String + +For siCount = 1 To 20 + sColours.Add(Rand(Red, Blue)) +Next + +Print "Random: - "; + +For siCount = 1 To 2 + For Each sTemp In sColours + If sTemp = Red Then Print "Red "; + If sTemp = White Then Print "White "; + If sTemp = Blue Then Print "Blue "; + Next + sColours.Sort + Print + If siCount = 1 Then Print "Sorted: - "; +Next + +End diff --git a/Task/Dutch-national-flag-problem/JavaScript/dutch-national-flag-problem.js b/Task/Dutch-national-flag-problem/JavaScript/dutch-national-flag-problem.js new file mode 100644 index 0000000000..dfd921f67f --- /dev/null +++ b/Task/Dutch-national-flag-problem/JavaScript/dutch-national-flag-problem.js @@ -0,0 +1,81 @@ +const dutchNationalFlag = () => { + + /** + * Return the name of the given number in this way: + * 0 = Red + * 1 = White + * 2 = Blue + * @param {!number} e + */ + const name = e => e > 1 ? 'Blue' : e > 0 ? 'White' : 'Red'; + + /** + * Given an array of numbers return true if each number is bigger than + * or the same as the previous + * @param {!Array} arr + */ + const isSorted = arr => arr.every((e,i) => e >= arr[Math.max(i-1, 0)]); + + /** + * Generator that keeps yielding a random int between 0(inclusive) and + * max(exclusive), up till n times, and then is done. + * @param max + * @param n + */ + function* randomGen (max, n) { + let i = 0; + while (i < n) { + i += 1; + yield Math.floor(Math.random() * max); + } + } + + /** + * An array of random integers between 0 and 3 + * @type {[!number]} + */ + const mixedBalls = [...(randomGen(3, 22))]; + + /** + * Sort the given array into 3 sub-arrays and then concatenate those. + */ + const sortedBalls = mixedBalls + .reduce((p,c) => p[c].push(c) && p, [[],[],[]]) + .reduce((p,c) => p.concat(c), []); + + /** + * A verbatim implementation of the Wikipedia pseudo-code + * @param {!Array} A + * @param {!number} mid The value of the 'mid' number. In our case 1 as + * low is 0 and high is 2 + */ + const dutchSort = (A, mid) => { + let i = 0; + let j = 0; + let n = A.length - 1; + while(j <= n) { + if (A[j] < mid) { + [A[i], A[j]] = [A[j], A[i]]; + i += 1; + j += 1; + } else if (A[j] > mid) { + [A[j], A[n]] = [A[n], A[j]]; + n -= 1 + } else { + j += 1; + } + } + }; + + console.log(`Mixed balls : ${mixedBalls.map(name).join()}`); + console.log(`Is sorted: ${isSorted(mixedBalls)}`); + + console.log(`Sorted balls : ${sortedBalls.map(name).join()}`); + console.log(`Is sorted: ${isSorted(sortedBalls)}`); + + // Only do the dutch sort now as it mutates the mixedBalls array in place. + dutchSort(mixedBalls, 1); + console.log(`Dutch Sorted balls: ${mixedBalls.map(name).join()}`); + console.log(`Is sorted: ${isSorted(mixedBalls)}`); +}; +dutchNationalFlag(); 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.kotlin new file mode 100644 index 0000000000..14b4e5e62e --- /dev/null +++ b/Task/Dutch-national-flag-problem/Kotlin/dutch-national-flag-problem.kotlin @@ -0,0 +1,53 @@ +// version 1.1.4 + +import java.util.Random + +enum class DutchColors { RED, WHITE, BLUE } + +fun Array.swap(i: Int, j: Int) { + val temp = this[i] + this[i] = this[j] + this[j] = temp +} + +fun Array.sort() { + var lo = 0 + var mid = 0 + var hi = this.lastIndex + + while (mid <= hi) { + when (this[mid]) { + DutchColors.RED -> this.swap(lo++, mid++) + DutchColors.WHITE -> mid++ + DutchColors.BLUE -> this.swap(mid, hi--) + } + } +} + +fun Array.isSorted(): Boolean { + return (1 until this.size) + .none { this[it].ordinal < this[it - 1].ordinal } +} + +const val NUM_BALLS = 9 + +fun main(args: Array) { + val r = Random() + val balls = Array(NUM_BALLS) { DutchColors.RED } + val colors = DutchColors.values() + + // give balls random colors whilst ensuring they're not already sorted + do { + for (i in 0 until NUM_BALLS) balls[i] = colors[r.nextInt(3)] + } + while (balls.isSorted()) + + // print the colors of the balls before sorting + println("Before sorting : ${balls.contentToString()}") + + // sort the balls in DutchColors order + balls.sort() + + // print the colors of the balls after sorting + println("After sorting : ${balls.contentToString()}") +} 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 new file mode 100644 index 0000000000..a605f7e17e --- /dev/null +++ b/Task/Dutch-national-flag-problem/Phix/dutch-national-flag-problem.phix @@ -0,0 +1,38 @@ +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 + +procedure show(string msg, sequence s) + for i=1 to length(s) do + s[i] = colours[s[i]] + end for + printf(1,"%s: %s\n",{msg,join(s)}) +end procedure + +sequence unsorted, sorted + while 1 do + unsorted = sq_rand(repeat(maxc,12)) +-- sorted = sort(unsorted) -- (works just as well) + sorted = three_way_partition(unsorted, white) + if unsorted!=sorted then exit end if + ?"oops" + end while + show("Unsorted",unsorted) + show("Sorted",sorted) 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 new file mode 100644 index 0000000000..0a6e2a4972 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Rust/dutch-national-flag-problem.rust @@ -0,0 +1,44 @@ +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/Zkl/dutch-national-flag-problem.zkl b/Task/Dutch-national-flag-problem/Zkl/dutch-national-flag-problem.zkl new file mode 100644 index 0000000000..df7181196f --- /dev/null +++ b/Task/Dutch-national-flag-problem/Zkl/dutch-national-flag-problem.zkl @@ -0,0 +1,10 @@ +const RED=0, WHITE=1, BLUE=2; var BALLS=T(RED,WHITE,BLUE); +fcn colorBalls(balls){ balls.apply(T("red","white","blue").get).concat(", "); } + +reg balls, sortedBalls; +do{ + balls=(0).pump(12,List,fcn{ BALLS[(0).random(3)] }); // create list of 12 random balls + sortedBalls=balls.sort(); // balls is read only, sort creates new list +}while(balls==sortedBalls); // make sure sort does something +println("Original ball order:\n", colorBalls(balls)); +println("\nSorted ball order:\n", colorBalls(sortedBalls)); diff --git a/Task/Dynamic-variable-names/Elena/dynamic-variable-names.elena b/Task/Dynamic-variable-names/Elena/dynamic-variable-names.elena index 00ce33028a..dad4220661 100644 --- a/Task/Dynamic-variable-names/Elena/dynamic-variable-names.elena +++ b/Task/Dynamic-variable-names/Elena/dynamic-variable-names.elena @@ -1,25 +1,24 @@ -#import system. -#import system'dynamic. -#import extensions. +import system'dynamic. +import extensions. -#class TestClass +class TestClass { - #field theVariables. + object theVariables. - #constructor new + constructor new [ theVariables := DynamicStruct new. ] - #method eval + eval [ - #var(type:subject) varRef := Signature new &literal:(console write:"Enter the variable name:" readLine). - theVariables::varRef set:42. + subject varRef := Signature new literal:(console write:"Enter the variable name:"; readLine). + theVariables~varRef set:42. - #var v := theVariables::varRef get. + var v := theVariables~varRef get. - console writeLine:(varRef name):"=":(theVariables::varRef get). + console printLine(varRef literal,"=",theVariables~varRef get); readChar. ] } -#symbol program = TestClass new. +program = TestClass new. diff --git a/Task/Dynamic-variable-names/Jq/dynamic-variable-names.jq b/Task/Dynamic-variable-names/Jq/dynamic-variable-names.jq new file mode 100644 index 0000000000..731a00d5dd --- /dev/null +++ b/Task/Dynamic-variable-names/Jq/dynamic-variable-names.jq @@ -0,0 +1,4 @@ +"Enter a variable name:", +(input as $var + | ("Enter a value:" , + (input as $value | { ($var) : $value }))) diff --git a/Task/Dynamic-variable-names/Kotlin/dynamic-variable-names.kotlin b/Task/Dynamic-variable-names/Kotlin/dynamic-variable-names.kotlin new file mode 100644 index 0000000000..361b35b3fc --- /dev/null +++ b/Task/Dynamic-variable-names/Kotlin/dynamic-variable-names.kotlin @@ -0,0 +1,41 @@ +// version 1.1.4 + +fun main(args: Array) { + var n: Int + do { + print("How many integer variables do you want to create (max 5) : ") + n = readLine()!!.toInt() + } + while (n < 1 || n > 5) + + val map = mutableMapOf() + var name: String + var value: Int + var i = 1 + println("OK, enter the variable names and their values, below") + do { + println("\n Variable $i") + print(" Name : ") + name = readLine()!! + if (map.containsKey(name)) { + println(" Sorry, you've already created a variable of that name, try again") + continue + } + print(" Value : ") + value = readLine()!!.toInt() + map.put(name, value) + i++ + } + while (i <= n) + + println("\nEnter q to quit") + var v: Int? + while (true) { + print("\nWhich variable do you want to inspect : ") + name = readLine()!! + if (name.toLowerCase() == "q") return + v = map[name] + if (v == null) println("Sorry there's no variable of that name, try again") + else println("It's value is $v") + } +} diff --git a/Task/Dynamic-variable-names/Nim/dynamic-variable-names.nim b/Task/Dynamic-variable-names/Nim/dynamic-variable-names.nim new file mode 100644 index 0000000000..ca6b078c3c --- /dev/null +++ b/Task/Dynamic-variable-names/Nim/dynamic-variable-names.nim @@ -0,0 +1,17 @@ +import tables + +var + theVar: int = 5 + varMap = initTable[string, pointer]() + +proc ptrToInt(p: pointer): int = + result = cast[ptr int](p)[] + +proc main() = + write(stdout, "Enter a var name: ") + let sVar = readLine(stdin) + varMap.add($svar, theVar.addr) + echo "Variable ", sVar, " is ", ptrToInt(varMap[$sVar]) + +when isMainModule: + main() diff --git a/Task/Dynamic-variable-names/Perl-6/dynamic-variable-names.pl6 b/Task/Dynamic-variable-names/Perl-6/dynamic-variable-names.pl6 index 0e892a5cd0..c0b38b46b8 100644 --- a/Task/Dynamic-variable-names/Perl-6/dynamic-variable-names.pl6 +++ b/Task/Dynamic-variable-names/Perl-6/dynamic-variable-names.pl6 @@ -1,3 +1,11 @@ -my $vname = prompt 'Variable name: '; -$GLOBAL::($vname) = 42; -say $GLOBAL::($vname); +our $our-var = 'The our var'; +my $my-var = 'The my var'; + +my $name = prompt 'Variable name: '; +my $value = $::($name); # use the right sigil, etc + +put qq/Var ($name) starts with value 「$value」/; + +$::($name) = 137; + +put qq/Var ($name) ends with value 「{$::($name)}」/; diff --git a/Task/Dynamic-variable-names/Phix/dynamic-variable-names.phix b/Task/Dynamic-variable-names/Phix/dynamic-variable-names.phix new file mode 100644 index 0000000000..eff1329801 --- /dev/null +++ b/Task/Dynamic-variable-names/Phix/dynamic-variable-names.phix @@ -0,0 +1,16 @@ +constant globals = new_dict() + +while 1 do + string name = prompt_string("Enter name or press Enter to quit:") + if length(name)=0 then exit end if + integer k = getd_index(name,globals) + if k=0 then + string data = prompt_string("No such name, enter a value:") + setd(name,data,globals) + else + string data = prompt_string(sprintf("Already exists, new value[%s]:",{getd(name,globals)})) + if length(data) then + setd(name,data,globals) + end if + end if +end while diff --git a/Task/Dynamic-variable-names/Stata/dynamic-variable-names.stata b/Task/Dynamic-variable-names/Stata/dynamic-variable-names.stata new file mode 100644 index 0000000000..9a0bfdc1c8 --- /dev/null +++ b/Task/Dynamic-variable-names/Stata/dynamic-variable-names.stata @@ -0,0 +1,3 @@ +display "Name?" _request(s) +scalar $s=10 +display $s diff --git a/Task/Dynamic-variable-names/Zkl/dynamic-variable-names.zkl b/Task/Dynamic-variable-names/Zkl/dynamic-variable-names.zkl new file mode 100644 index 0000000000..fcd3265c73 --- /dev/null +++ b/Task/Dynamic-variable-names/Zkl/dynamic-variable-names.zkl @@ -0,0 +1,5 @@ +vname:="foo"; // or vname:=ask("var name = "); +klass:=Compiler.Compiler.compileText("var %s=123".fmt(vname))(); // compile & run the constructor +klass.vars.println(); +klass.foo.println(); +klass.setVar(vname).println(); // setVar(name,val) sets the var diff --git a/Task/Echo-server/Aime/echo-server.aime b/Task/Echo-server/Aime/echo-server.aime new file mode 100644 index 0000000000..543faac86e --- /dev/null +++ b/Task/Echo-server/Aime/echo-server.aime @@ -0,0 +1,51 @@ +void +readc(dispatch w, file i, file o, data b) +{ + integer e; + data t; + + while (1) { + e = f_b_read(i, t, 1 << 10); + if (e < 1) { + if (e == -1) { + w_resign(w, i); + } + + break; + } else { + e = b_frame(t, '\n'); + if (e != -1) { + e += 1; + b_rule(b, -1, t, 0, e); + f_data(o, b); + w_register(w, o); + b_bill(b, t, e, ~t - e); + } else { + b_add(b, t); + } + } + } +} + +void +serve(dispatch w, file s) +{ + file i, o; + data b; + + accept(i, o, s, NONBLOCKING_INPUT | NONBLOCKING_OUTPUT); + w_watch(w, i, readc, w, i, o, b); +} + +integer +main(void) +{ + dispatch w; + file s; + + tcpip_listen(s, 12321, 0); + w_watch(w, s, serve, w, s); + w_press(w); + + return 0; +} diff --git a/Task/Echo-server/Kotlin/echo-server.kotlin b/Task/Echo-server/Kotlin/echo-server.kotlin new file mode 100644 index 0000000000..da6b8456d4 --- /dev/null +++ b/Task/Echo-server/Kotlin/echo-server.kotlin @@ -0,0 +1,49 @@ +// version 1.1.3 + +import java.io.BufferedReader +import java.io.InputStreamReader +import java.io.PrintWriter +import java.net.ServerSocket +import java.net.Socket + +class ClientHandler(private val clientSocket: Socket): Runnable { + private val connectionId: Int + + init { + connectionId = ++numConnections + println("Handling connection, #$connectionId") + } + + override fun run() { + val pw = PrintWriter(clientSocket.outputStream, true) + val br = BufferedReader(InputStreamReader(clientSocket.inputStream)) + while (true) { + val line = br.readLine() ?: break + println("Received: $line") + pw.write("$line\n") + pw.flush() + if (line == "exit") break + } + br.close() + pw.close() + clientSocket.close() + println("Closing connection, #$connectionId") + } + + private companion object { + var numConnections = 0 + } +} + +fun main(args: Array) { + val serverSocket = ServerSocket(12321) + try { + while (true) { + Thread(ClientHandler(serverSocket.accept())).start() + } + } + finally { + serverSocket.close() + println("Closing server socket") + } +} diff --git a/Task/Echo-server/Zkl/echo-server.zkl b/Task/Echo-server/Zkl/echo-server.zkl new file mode 100644 index 0000000000..03ddbeb418 --- /dev/null +++ b/Task/Echo-server/Zkl/echo-server.zkl @@ -0,0 +1,16 @@ +const PORT=12321; +pipe:=Thread.Pipe(); // how server tells thread to connect to user + +fcn echo(socket){ // a thread, one per connection + text:=Data(); + while(t:=socket.read()){ + text.append(t); + if(text.find("\n",text.cursor)){ text.readln().print(); } + } + // socket was closed +} + + // Set up the server socket. +server:=Network.TCPServerSocket.open(PORT); +println("Listening on %s:%s".fmt(server.hostname,server.port)); +server.listen(echo.launch); // Main event loop diff --git a/Task/Element-wise-operations/jq/element-wise-operations-1.jq b/Task/Element-wise-operations/Jq/element-wise-operations-1.jq similarity index 100% rename from Task/Element-wise-operations/jq/element-wise-operations-1.jq rename to Task/Element-wise-operations/Jq/element-wise-operations-1.jq diff --git a/Task/Element-wise-operations/jq/element-wise-operations-2.jq b/Task/Element-wise-operations/Jq/element-wise-operations-2.jq similarity index 100% rename from Task/Element-wise-operations/jq/element-wise-operations-2.jq rename to Task/Element-wise-operations/Jq/element-wise-operations-2.jq diff --git a/Task/Element-wise-operations/jq/element-wise-operations-3.jq b/Task/Element-wise-operations/Jq/element-wise-operations-3.jq similarity index 100% rename from Task/Element-wise-operations/jq/element-wise-operations-3.jq rename to Task/Element-wise-operations/Jq/element-wise-operations-3.jq diff --git a/Task/Element-wise-operations/jq/element-wise-operations-4.jq b/Task/Element-wise-operations/Jq/element-wise-operations-4.jq similarity index 100% rename from Task/Element-wise-operations/jq/element-wise-operations-4.jq rename to Task/Element-wise-operations/Jq/element-wise-operations-4.jq diff --git a/Task/Element-wise-operations/jq/element-wise-operations-5.jq b/Task/Element-wise-operations/Jq/element-wise-operations-5.jq similarity index 100% rename from Task/Element-wise-operations/jq/element-wise-operations-5.jq rename to Task/Element-wise-operations/Jq/element-wise-operations-5.jq diff --git a/Task/Element-wise-operations/jq/element-wise-operations-6.jq b/Task/Element-wise-operations/Jq/element-wise-operations-6.jq similarity index 100% rename from Task/Element-wise-operations/jq/element-wise-operations-6.jq rename to Task/Element-wise-operations/Jq/element-wise-operations-6.jq diff --git a/Task/Element-wise-operations/Julia/element-wise-operations.julia b/Task/Element-wise-operations/Julia/element-wise-operations.julia new file mode 100644 index 0000000000..f2abef842e --- /dev/null +++ b/Task/Element-wise-operations/Julia/element-wise-operations.julia @@ -0,0 +1,7 @@ +@show [1 2 3; 3 2 1] .+ [2 1 2; 0 2 1] +@show [1 2 3; 2 1 2] .+ 1 +@show [1 2 3; 2 2 1] .- [1 1 1; 2 1 0] +@show [1 2 1; 1 2 3] .* [3 2 1; 1 0 1] +@show [1 2 3; 3 2 1] .* 2 +@show [9 8 6; 3 2 3] ./ [3 1 2; 2 1 2] +@show [3 2 2; 1 2 3] .^ [1 2 3; 2 1 2] diff --git a/Task/Element-wise-operations/Rust/element-wise-operations.rust b/Task/Element-wise-operations/Rust/element-wise-operations.rust new file mode 100644 index 0000000000..09317c9bfc --- /dev/null +++ b/Task/Element-wise-operations/Rust/element-wise-operations.rust @@ -0,0 +1,135 @@ +struct Matrix { + elements: Vec, + pub height: u32, + pub width: u32, +} + +impl Matrix { + fn new(elements: Vec, height: u32, width: u32) -> Matrix { + // Should check for dimensions but omitting to be succient + Matrix { + elements: elements, + height: height, + width: width, + } + } + + fn get(&self, row: u32, col: u32) -> f32 { + let row = row as usize; + let col = col as usize; + self.elements[col + row * (self.width as usize)] + } + + fn set(&mut self, row: u32, col: u32, value: f32) { + let row = row as usize; + let col = col as usize; + self.elements[col + row * (self.width as usize)] = value; + } + + fn print(&self) { + for row in 0..self.height { + for col in 0..self.width { + print!("{:3.0}", self.get(row, col)); + } + println!(""); + } + println!(""); + } +} + +// Matrix addition will perform element-wise addition +fn matrix_addition(first: &Matrix, second: &Matrix) -> Result { + if first.width == second.width && first.height == second.height { + let mut result = Matrix::new(vec![0.0f32; (first.height * first.width) as usize], + first.height, + first.width); + for row in 0..first.height { + for col in 0..first.width { + let first_value = first.get(row, col); + let second_value = second.get(row, col); + result.set(row, col, first_value + second_value); + } + } + Ok(result) + } else { + Err("Dimensions don't match".to_owned()) + } +} + +fn scalar_multiplication(scalar: f32, matrix: &Matrix) -> Matrix { + let mut result = Matrix::new(vec![0.0f32; (matrix.height * matrix.width) as usize], + matrix.height, + matrix.width); + for row in 0..matrix.height { + for col in 0..matrix.width { + let value = matrix.get(row, col); + result.set(row, col, scalar * value); + } + } + result +} + +// Subtract second from first +fn matrix_subtraction(first: &Matrix, second: &Matrix) -> Result { + if first.width == second.width && first.height == second.height { + let negative_matrix = scalar_multiplication(-1.0, second); + let result = matrix_addition(first, &negative_matrix).unwrap(); + Ok(result) + } else { + Err("Dimensions don't match".to_owned()) + } +} + +// First must be a l x m matrix and second a m x n matrix for this to work. +fn matrix_multiplication(first: &Matrix, second: &Matrix) -> Result { + if first.width == second.height { + let mut result = Matrix::new(vec![0.0f32; (first.height * second.width) as usize], + first.height, + second.width); + for row in 0..result.height { + for col in 0..result.width { + let mut value = 0.0; + for it in 0..first.width { + value += first.get(row, it) * second.get(it, col); + } + result.set(row, col, value); + } + } + Ok(result) + } else { + Err("Dimensions don't match. Width of first must equal height of second".to_owned()) + } +} + + +fn main() { + let height = 2; + let width = 3; + // Matrix will look like: + // | 1.0 2.0 3.0 | + // | 4.0 5.0 6.0 | + let matrix1 = Matrix::new(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], height, width); + + // Matrix will look like: + // | 6.0 5.0 4.0 | + // | 3.0 2.0 1.0 | + let matrix2 = Matrix::new(vec![6.0, 5.0, 4.0, 3.0, 2.0, 1.0], height, width); + + // | 7.0 7.0 7.0 | + // | 7.0 7.0 7.0 | + matrix_addition(&matrix1, &matrix2).unwrap().print(); + // | 2.0 4.0 6.0 | + // | 8.0 10.0 12.0 | + scalar_multiplication(2.0, &matrix1).print(); + // | -5.0 -3.0 -1.0 | + // | 1.0 3.0 5.0 | + matrix_subtraction(&matrix1, &matrix2).unwrap().print(); + + // | 1.0 | + // | 1.0 | + // | 1.0 | + let matrix3 = Matrix::new(vec![1.0, 1.0, 1.0], width, 1); + // | 6 | + // | 15 | + matrix_multiplication(&matrix1, &matrix3).unwrap().print(); +} diff --git a/Task/Element-wise-operations/Zkl/element-wise-operations.zkl b/Task/Element-wise-operations/Zkl/element-wise-operations.zkl new file mode 100644 index 0000000000..3f0f820ca7 --- /dev/null +++ b/Task/Element-wise-operations/Zkl/element-wise-operations.zkl @@ -0,0 +1,12 @@ +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +M:=GSL.Matrix(3,3).set(3,5,7, 1,2,3, 2,4,6); +x:=2; +println("M = \n%s\nx = %s".fmt(M.format(),x)); +foreach op in (T('+,'-,'*,'/)){ + println("M %s x:\n%s\n".fmt(op.toString()[3,1],op(M.copy(),x).format())); +} +foreach op in (T("addElements","subElements","mulElements","divElements")){ + println("M %s M:\n%s\n".fmt(op, M.copy().resolve(op)(M).format())); +} +mSqrd:=M.pump(0,M.copy(),fcn(x){ x*x }); // M element by element +println("M square elements:\n%s\n".fmt(mSqrd.format())); diff --git a/Task/Empty-directory/AWK/empty-directory.awk b/Task/Empty-directory/AWK/empty-directory.awk new file mode 100644 index 0000000000..edf02ec9c6 --- /dev/null +++ b/Task/Empty-directory/AWK/empty-directory.awk @@ -0,0 +1,37 @@ +# syntax: GAWK -f EMPTY_DIRECTORY.AWK +BEGIN { + n = split("C:\\TEMP3,C:\\NOTHERE,C:\\AWK\\FILENAME,C:\\WINDOWS",arr,",") + for (i=1; i<=n; i++) { + printf("'%s' %s\n",arr[i],is_dir(arr[i])) + } + exit(0) +} +function is_dir(path, cmd,dots,entries,msg,rec,valid_dir) { + cmd = sprintf("DIR %s 2>NUL",path) # MS-Windows + while ((cmd | getline rec) > 0) { + if (rec ~ /[0-9]:[0-5][0-9]/) { + if (rec ~ / (\.|\.\.)$/) { # . or .. + dots++ + continue + } + entries++ + } + if (rec ~ / Dir\(s\) .* bytes free$/) { + valid_dir = 1 + } + } + close(cmd) + if (valid_dir == 0) { + msg = "does not exist" + } + else if (valid_dir == 1 && entries == 0) { + msg = "is an empty directory" + } + else if (dots == 0 && entries == 1) { + msg = "is a file" + } + else { + msg = sprintf("is a directory with %d entries",entries) + } + return(msg) +} diff --git a/Task/Empty-directory/BaCon/empty-directory.bacon b/Task/Empty-directory/BaCon/empty-directory.bacon new file mode 100644 index 0000000000..fdef2186ce --- /dev/null +++ b/Task/Empty-directory/BaCon/empty-directory.bacon @@ -0,0 +1,19 @@ +' empty directory test +somedir$ = "somedir" +files = testdir(somedir$) +IF files = 0 THEN PRINT somedir$, " directory empty" + +files = testdir(".") +PRINT "Current directory holds ", files, " files" +END + +FUNCTION testdir(somedir$) + OPEN somedir$ FOR DIRECTORY AS adir + total = 0 + REPEAT + GETFILE afile$ FROM adir + IF afile$ != "." AND afile$ != ".." AND afile$ != "" THEN INCR total + UNTIL ISFALSE(LEN(afile$)) + IF (long)adir != 0 THEN CLOSE DIRECTORY adir + RETURN total +END FUNCTION diff --git a/Task/Empty-directory/Gambas/empty-directory.gambas b/Task/Empty-directory/Gambas/empty-directory.gambas new file mode 100644 index 0000000000..0477fcb871 --- /dev/null +++ b/Task/Empty-directory/Gambas/empty-directory.gambas @@ -0,0 +1,12 @@ +Public Sub Main() +Dim sFolder As String = User.home &/ "Rosetta" +Dim sDir As String[] = Dir(sFolder) +Dim sTemp As String +Dim sOutput As String = sfolder & " is NOT empty" + +Try sTemp = sDir[0] +If Error Then sOutput = sfolder & " is empty" + +Print sOutput + +End diff --git a/Task/Empty-directory/Julia/empty-directory.julia b/Task/Empty-directory/Julia/empty-directory.julia new file mode 100644 index 0000000000..f24424b619 --- /dev/null +++ b/Task/Empty-directory/Julia/empty-directory.julia @@ -0,0 +1,5 @@ +# v0.6.0 +isemptydir(dir::AbstractString) = isempty(readdir(dir)) + +@show isemptydir(".") +@show isemptydir("/home") diff --git a/Task/Empty-directory/Kotlin/empty-directory.kotlin b/Task/Empty-directory/Kotlin/empty-directory.kotlin new file mode 100644 index 0000000000..b82a997266 --- /dev/null +++ b/Task/Empty-directory/Kotlin/empty-directory.kotlin @@ -0,0 +1,9 @@ +// version 1.1.4 + +import java.io.File + +fun main(args: Array) { + val dirPath = "docs" // or whatever + val isEmpty = (File(dirPath).list().isEmpty()) + println("$dirPath is ${if (isEmpty) "empty" else "not empty"}") +} diff --git a/Task/Empty-directory/Maple/empty-directory.maple b/Task/Empty-directory/Maple/empty-directory.maple new file mode 100644 index 0000000000..9c31c69205 --- /dev/null +++ b/Task/Empty-directory/Maple/empty-directory.maple @@ -0,0 +1,3 @@ +emptydirectory := proc (dir) +is(listdir(dir) = [".", ".."]); +end proc; diff --git a/Task/Empty-directory/OoRexx/empty-directory.rexx b/Task/Empty-directory/OoRexx/empty-directory.rexx new file mode 100644 index 0000000000..38e85a8434 --- /dev/null +++ b/Task/Empty-directory/OoRexx/empty-directory.rexx @@ -0,0 +1,20 @@ +Call test 'D:\nodir' /* no such directory */ +Call test 'D:\edir' /* an empty directory */ +Call test 'D:\somedir' /* directory with 2 files */ +Call test 'D:\somedir','S' /* directory with 3 files */ +Exit +test: Parse Arg fd,nest +If SysIsFileDirectory(fd)=0 Then + Say 'Directory' fd 'not found' +Else Do + ret=SysFileTree(fd'\*.*','X', 'F'nest) + If x.0=0 Then + say 'Directory' fd 'is empty' + Else Do + If nest='' Then + say 'Directory' fd 'contains' x.0 'files' + Else + say 'Directory' fd 'contains' x.0 'files (some nested)' + End + End +Return diff --git a/Task/Empty-directory/Phix/empty-directory.phix b/Task/Empty-directory/Phix/empty-directory.phix new file mode 100644 index 0000000000..a4aa3bf2d2 --- /dev/null +++ b/Task/Empty-directory/Phix/empty-directory.phix @@ -0,0 +1,27 @@ +procedure test(string filename) +string msg + switch get_file_type(filename) do + case FILETYPE_UNDEFINED: msg = "is UNDEFINED" + case FILETYPE_NOT_FOUND: msg = "is NOT_FOUND" + case FILETYPE_FILE: msg = "is a FILE" + case FILETYPE_DIRECTORY: + sequence d = dir(filename) + integer count = 0 + for i=1 to length(d) do + if not find(d[i][D_NAME],{".",".."}) then + count += 1 + end if + end for + if count=0 then + msg = "is an empty directory" + else + msg = sprintf("is a directory containing %d files",{count}) + end if + end switch + printf(1,"%s %s\n",{filename,msg}) +end procedure + +constant tests = {"C:\\xx","C:\\not_there","C:\\Program Files (x86)\\Phix\\p.exe","C:\\Windows"} +for i=1 to length(tests) do + test(tests[i]) +end for diff --git a/Task/Empty-directory/Ruby/empty-directory-1.rb b/Task/Empty-directory/Ruby/empty-directory-1.rb deleted file mode 100644 index 892fad62a7..0000000000 --- a/Task/Empty-directory/Ruby/empty-directory-1.rb +++ /dev/null @@ -1,5 +0,0 @@ -# Checks if a directory is empty, but raises SystemCallError -# if _path_ is not a directory. -def empty_dir?(path) - not Dir.foreach(path).detect {|f| f != '.' and f != '..'} -end diff --git a/Task/Empty-directory/Ruby/empty-directory-2.rb b/Task/Empty-directory/Ruby/empty-directory-2.rb deleted file mode 100644 index f9db3dc053..0000000000 --- a/Task/Empty-directory/Ruby/empty-directory-2.rb +++ /dev/null @@ -1,8 +0,0 @@ -# Checks if a directory is empty, but raises SystemCallError -# if _path_ is not a directory. -def empty_dir?(path) - Dir.foreach(path) {|f| - return false if f != '.' and f != '..' - } - return true -end diff --git a/Task/Empty-directory/Zkl/empty-directory.zkl b/Task/Empty-directory/Zkl/empty-directory.zkl new file mode 100644 index 0000000000..9073085d3a --- /dev/null +++ b/Task/Empty-directory/Zkl/empty-directory.zkl @@ -0,0 +1,3 @@ +path:="Empty"; File.isDir(path).println(); +File.mkdir(path); File.isDir(path).println(); +File.glob(path+"/*").println(); // show contents of directory diff --git a/Task/Empty-program/EC/empty-program.ec b/Task/Empty-program/EC/empty-program.ec new file mode 100644 index 0000000000..a66c09a47c --- /dev/null +++ b/Task/Empty-program/EC/empty-program.ec @@ -0,0 +1,7 @@ +class EmptyApp : Application +{ + void Main() + { + + } +} diff --git a/Task/Empty-program/ESQL/empty-program.esql b/Task/Empty-program/ESQL/empty-program.esql new file mode 100644 index 0000000000..f71077fee9 --- /dev/null +++ b/Task/Empty-program/ESQL/empty-program.esql @@ -0,0 +1,6 @@ +CREATE COMPUTE MODULE ESQL_Compute + CREATE FUNCTION Main() RETURNS BOOLEAN + BEGIN + RETURN TRUE; + END; +END MODULE; diff --git a/Task/Empty-program/Elena/empty-program.elena b/Task/Empty-program/Elena/empty-program.elena index a497f4ae57..1ad0a4b1ae 100644 --- a/Task/Empty-program/Elena/empty-program.elena +++ b/Task/Empty-program/Elena/empty-program.elena @@ -1,3 +1,3 @@ -#symbol program = +program = [ ]. diff --git a/Task/Empty-program/Elm/empty-program.elm b/Task/Empty-program/Elm/empty-program.elm new file mode 100644 index 0000000000..41b4f4d6f2 --- /dev/null +++ b/Task/Empty-program/Elm/empty-program.elm @@ -0,0 +1,4 @@ +--Language prints the text in " " +import Html +main = + Html.text"empty" diff --git a/Task/Empty-program/Friendly-interactive-shell/empty-program.fish b/Task/Empty-program/Friendly-interactive-shell/empty-program.fish new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Task/Empty-program/Inform-7/empty-program.inf b/Task/Empty-program/Inform-7/empty-program.inf new file mode 100644 index 0000000000..56e29fb1be --- /dev/null +++ b/Task/Empty-program/Inform-7/empty-program.inf @@ -0,0 +1 @@ +X is a room diff --git a/Task/Empty-program/Jq/empty-program.jq b/Task/Empty-program/Jq/empty-program.jq new file mode 100644 index 0000000000..c6cac69265 --- /dev/null +++ b/Task/Empty-program/Jq/empty-program.jq @@ -0,0 +1 @@ +empty diff --git a/Task/Empty-program/Oz/empty-program-3.oz b/Task/Empty-program/Oz/empty-program-3.oz deleted file mode 100644 index ea82901629..0000000000 --- a/Task/Empty-program/Oz/empty-program-3.oz +++ /dev/null @@ -1,4 +0,0 @@ -functor -define - skip -end diff --git a/Task/Empty-program/Perl/empty-program-3.pl b/Task/Empty-program/Perl/empty-program-3.pl deleted file mode 100644 index 57216f0412..0000000000 --- a/Task/Empty-program/Perl/empty-program-3.pl +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/perl -# A program without a body will work too diff --git a/Task/Empty-program/Perl/empty-program-4.pl b/Task/Empty-program/Perl/empty-program-4.pl deleted file mode 100644 index 1f1c293970..0000000000 --- a/Task/Empty-program/Perl/empty-program-4.pl +++ /dev/null @@ -1 +0,0 @@ -#!/usr/bin/perl diff --git a/Task/Empty-program/PlainTeX/empty-program.tex b/Task/Empty-program/PlainTeX/empty-program.tex new file mode 100644 index 0000000000..18f593054b --- /dev/null +++ b/Task/Empty-program/PlainTeX/empty-program.tex @@ -0,0 +1 @@ +\bye diff --git a/Task/Empty-program/REXX/empty-program-3.rexx b/Task/Empty-program/REXX/empty-program-3.rexx deleted file mode 100644 index 9d6f459ad8..0000000000 --- a/Task/Empty-program/REXX/empty-program-3.rexx +++ /dev/null @@ -1 +0,0 @@ -/**/ diff --git a/Task/Empty-program/REXX/empty-program-4.rexx b/Task/Empty-program/REXX/empty-program-4.rexx deleted file mode 100644 index 76138cf7f3..0000000000 --- a/Task/Empty-program/REXX/empty-program-4.rexx +++ /dev/null @@ -1 +0,0 @@ -/*REXX*/ diff --git a/Task/Empty-program/REXX/empty-program-5.rexx b/Task/Empty-program/REXX/empty-program-5.rexx deleted file mode 100644 index 7893e47dd7..0000000000 --- a/Task/Empty-program/REXX/empty-program-5.rexx +++ /dev/null @@ -1 +0,0 @@ -/*this REXX program calculates if a date is a workday for the XYZ Company.*/ diff --git a/Task/Empty-program/Stata/empty-program-1.stata b/Task/Empty-program/Stata/empty-program-1.stata new file mode 100644 index 0000000000..3d62ea9210 --- /dev/null +++ b/Task/Empty-program/Stata/empty-program-1.stata @@ -0,0 +1,3 @@ +program define nop + version 15 +end diff --git a/Task/Empty-program/Stata/empty-program-2.stata b/Task/Empty-program/Stata/empty-program-2.stata new file mode 100644 index 0000000000..4a59335a47 --- /dev/null +++ b/Task/Empty-program/Stata/empty-program-2.stata @@ -0,0 +1,2 @@ +function nop() { +} diff --git a/Task/Empty-program/UNIX-Shell/empty-program-3.sh b/Task/Empty-program/UNIX-Shell/empty-program-3.sh new file mode 100644 index 0000000000..c4fa4178e6 --- /dev/null +++ b/Task/Empty-program/UNIX-Shell/empty-program-3.sh @@ -0,0 +1 @@ +#!/bin/ksh diff --git a/Task/Empty-program/Zkl/empty-program.zkl b/Task/Empty-program/Zkl/empty-program.zkl new file mode 100644 index 0000000000..af1983215c --- /dev/null +++ b/Task/Empty-program/Zkl/empty-program.zkl @@ -0,0 +1,2 @@ +c:=Compiler.Compiler.compileText(""); +c() //--> Class(RootClass#) diff --git a/Task/Empty-string/BASIC/empty-string-3.basic b/Task/Empty-string/BASIC/empty-string-3.basic new file mode 100644 index 0000000000..80e245ef97 --- /dev/null +++ b/Task/Empty-string/BASIC/empty-string-3.basic @@ -0,0 +1,4 @@ +' Empty string +a$ = "" +IF a$ = "" THEN PRINT "Empty string" +IF a$ != "" THEN PRINT "Non empty string" diff --git a/Task/Empty-string/Elena/empty-string.elena b/Task/Empty-string/Elena/empty-string.elena index d192193e3b..e2d29a9c68 100644 --- a/Task/Empty-string/Elena/empty-string.elena +++ b/Task/Empty-string/Elena/empty-string.elena @@ -1,12 +1,11 @@ -#import system. -#import extensions. +import extensions. -#symbol program = [ - #var s := emptyLiteralValue. +program = [ + var s := emptyLiteralValue. - (s is &empty) - ? [ console writeLine:"'":s:"' is empty". ]. + if (s isEmpty) + [ console printLine("'", s, "' is empty") ]. - (s is &nonempty) - ? [ console writeLine:"'":s:"' is not empty". ]. + if (s isNonempty) + [ console printLine("'", s, "' is not empty") ] ]. diff --git a/Task/Empty-string/Gambas/empty-string.gambas b/Task/Empty-string/Gambas/empty-string.gambas new file mode 100644 index 0000000000..816013d4c0 --- /dev/null +++ b/Task/Empty-string/Gambas/empty-string.gambas @@ -0,0 +1,15 @@ +Public Sub Main() +Dim sString As String[] = ["", "Hello", "world", "", "Today", "Tomorrow", "", "", "End!"] +Dim sTemp As String +Dim siCount As Short + +For Each sTemp In sString + If sString[siCount] Then + Print "String " & siCount & " = " & sString[siCount] + Else + Print "String " & siCount & " is empty" + End If + Inc siCount +Next + +End diff --git a/Task/Empty-string/jq/empty-string-1.jq b/Task/Empty-string/Jq/empty-string-1.jq similarity index 100% rename from Task/Empty-string/jq/empty-string-1.jq rename to Task/Empty-string/Jq/empty-string-1.jq diff --git a/Task/Empty-string/jq/empty-string-2.jq b/Task/Empty-string/Jq/empty-string-2.jq similarity index 100% rename from Task/Empty-string/jq/empty-string-2.jq rename to Task/Empty-string/Jq/empty-string-2.jq diff --git a/Task/Empty-string/jq/empty-string-3.jq b/Task/Empty-string/Jq/empty-string-3.jq similarity index 100% rename from Task/Empty-string/jq/empty-string-3.jq rename to Task/Empty-string/Jq/empty-string-3.jq diff --git a/Task/Empty-string/Kotlin/empty-string.kotlin b/Task/Empty-string/Kotlin/empty-string.kotlin index 90dc415ac5..1c6bae5ffa 100644 --- a/Task/Empty-string/Kotlin/empty-string.kotlin +++ b/Task/Empty-string/Kotlin/empty-string.kotlin @@ -1,6 +1,8 @@ -val s = "" -println(s.isEmpty()) // true -println(s.isNotEmpty()) // false -println(s.length) // 0 -println(s.none()) // true -println(s.any()) // false +fun main(args: Array) { + val s = "" + println(s.isEmpty()) // true + println(s.isNotEmpty()) // false + println(s.length) // 0 + println(s.none()) // true + println(s.any()) // false +} diff --git a/Task/Empty-string/Oberon-2/empty-string.oberon-2 b/Task/Empty-string/Oberon-2/empty-string.oberon-2 new file mode 100644 index 0000000000..8f747c0e5a --- /dev/null +++ b/Task/Empty-string/Oberon-2/empty-string.oberon-2 @@ -0,0 +1,14 @@ +MODULE EmptyString; +IMPORT Out; +VAR + str: ARRAY 64 OF CHAR; +BEGIN + str := ""; + Out.String("for str := ");Out.Char('"');Out.Char('"');Out.Char(';');Out.Ln; + Out.String("checking str = ");Out.Char('"');Out.Char('"');Out.String(" Is Empty? ");Out.Bool(str = "");Out.Ln; + Out.String("checking str[0] = 0X. Is Empty? ");Out.Bool(str[0] = 0X);Out.Ln; + str := "Hello Rossetta"; + Out.String("for str :=");Out.Char('"');Out.String(str);Out.Char('"');Out.Char(";");Out.Ln; + Out.String("checking str = ");Out.Char('"');Out.String(str);Out.Char('"');Out.String(" Is Empty? ");Out.Bool(str = "");Out.Ln; + Out.String("checking str[0] = 0X. Is Empty? ");Out.Bool(str[0] = 0X);Out.Ln; +END EmptyString. diff --git a/Task/Empty-string/Ol/empty-string.ol b/Task/Empty-string/Ol/empty-string.ol new file mode 100644 index 0000000000..242b4e169e --- /dev/null +++ b/Task/Empty-string/Ol/empty-string.ol @@ -0,0 +1,17 @@ +; define the empty string +(define empty-string "") + +; three simplest tests for 'the-string emptiness +(if (or + (string-eq? the-string "") + (string=? the-string "") + (eq? (string-length the-string) 0)) + (print "the-string is empty") + +; four simplest tests for 'the-string not emptiness +(if (or + (not (string-eq? the-string "")) + (not (string=? the-string "")) + (not (eq? (string-length the-string) 0)) + (less? 0 (string-length the-string))) + (print "the-string is NOT empty)) diff --git a/Task/Empty-string/OoRexx/empty-string.rexx b/Task/Empty-string/OoRexx/empty-string.rexx new file mode 100644 index 0000000000..26ca63cfb4 --- /dev/null +++ b/Task/Empty-string/OoRexx/empty-string.rexx @@ -0,0 +1,5 @@ +v='' +w=' ' +if v=='' Then Say 'v contains the empty string'< +If length(w)>0 Then Say 'Variable w does not contain the empty string' +If w='' Then Say 'this is not a good test' diff --git a/Task/Empty-string/Stata/empty-string.stata b/Task/Empty-string/Stata/empty-string.stata new file mode 100644 index 0000000000..2d0bc27e04 --- /dev/null +++ b/Task/Empty-string/Stata/empty-string.stata @@ -0,0 +1,6 @@ +scalar s="" + +display s=="" + +* Alternatively, check the length +display length(s)==0 diff --git a/Task/Empty-string/XLISP/empty-string.xlisp b/Task/Empty-string/XLISP/empty-string.xlisp new file mode 100644 index 0000000000..22bd6ff574 --- /dev/null +++ b/Task/Empty-string/XLISP/empty-string.xlisp @@ -0,0 +1,9 @@ +[1] (define my-empty-string "") ;; assign an empty string to a variable + +MY-EMPTY-STRING +[2] (string-null? my-empty-string) + +#T +[3] (string-null? "A non-empty string") + +() diff --git a/Task/Empty-string/Zkl/empty-string.zkl b/Task/Empty-string/Zkl/empty-string.zkl new file mode 100644 index 0000000000..b9b1eeece8 --- /dev/null +++ b/Task/Empty-string/Zkl/empty-string.zkl @@ -0,0 +1,3 @@ +s:=""; // or s:=String, String is the object "" +s.toBool() //-->False +if (s) println("not empty") diff --git a/Task/Enforced-immutability/00DESCRIPTION b/Task/Enforced-immutability/00DESCRIPTION index aa909bdb14..9c2cd00e5f 100644 --- a/Task/Enforced-immutability/00DESCRIPTION +++ b/Task/Enforced-immutability/00DESCRIPTION @@ -1 +1,3 @@ +;Task: Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created. +

    diff --git a/Task/Enforced-immutability/jq/enforced-immutability.jq b/Task/Enforced-immutability/Jq/enforced-immutability.jq similarity index 100% rename from Task/Enforced-immutability/jq/enforced-immutability.jq rename to Task/Enforced-immutability/Jq/enforced-immutability.jq diff --git a/Task/Enforced-immutability/Kotlin/enforced-immutability.kotlin b/Task/Enforced-immutability/Kotlin/enforced-immutability.kotlin new file mode 100644 index 0000000000..1c64315eaa --- /dev/null +++ b/Task/Enforced-immutability/Kotlin/enforced-immutability.kotlin @@ -0,0 +1,27 @@ +// version 1.1.0 + +// constant top level property +const val N = 5 + +// read-only top level property +val letters = listOf('A', 'B', 'C', 'D', 'E') // 'listOf' creates here a List) { + val mc = MyClass() // 'mc' cannot be re-assigned a different object + println(mc.myInt) + mc.myFunc(0) +} diff --git a/Task/Enforced-immutability/SuperCollider/enforced-immutability.supercollider b/Task/Enforced-immutability/SuperCollider/enforced-immutability.supercollider new file mode 100644 index 0000000000..90e2669a9e --- /dev/null +++ b/Task/Enforced-immutability/SuperCollider/enforced-immutability.supercollider @@ -0,0 +1,5 @@ +// you can freeze any object. +b = [1, 2, 3]; +b[1] = 100; // returns [1, 100, 3] +b.freeze; // make b immutable +b[1] = 2; // throws an error ("Attempted write to immutable object.") diff --git a/Task/Enforced-immutability/Zkl/enforced-immutability.zkl b/Task/Enforced-immutability/Zkl/enforced-immutability.zkl new file mode 100644 index 0000000000..97443fe55a --- /dev/null +++ b/Task/Enforced-immutability/Zkl/enforced-immutability.zkl @@ -0,0 +1,5 @@ +List(1,2,3).del(0) //--> L(2,3) +ROList(1,2,3).del(0) //-->SyntaxError : Can't find del, which means you can't call it +d:=Dictionary(); d.add("one",1) +D(one:1) +d.makeReadOnly(); d.add("2",2) //-->AccessError(This Dictionary is read only) diff --git a/Task/Entropy/00DESCRIPTION b/Task/Entropy/00DESCRIPTION index f254b81d88..1edd596a2e 100644 --- a/Task/Entropy/00DESCRIPTION +++ b/Task/Entropy/00DESCRIPTION @@ -1,7 +1,7 @@ ;Task: Calculate the Shannon entropy   H   of a given input string. -Given the discreet random variable X that is a string of N "symbols" (total characters) consisting of n different characters (n=2 for binary), the Shannon entropy of X in '''bits/symbol''' is : +Given the discrete random variable X that is a string of N "symbols" (total characters) consisting of n different characters (n=2 for binary), the Shannon entropy of X in '''bits/symbol''' is : :H_2(X) = -\sum_{i=1}^n \frac{count_i}{N} \log_2 \left(\frac{count_i}{N}\right) where count_i is the count of character n_i. diff --git a/Task/Entropy/Elena/entropy.elena b/Task/Entropy/Elena/entropy.elena new file mode 100644 index 0000000000..d7abb6fb27 --- /dev/null +++ b/Task/Entropy/Elena/entropy.elena @@ -0,0 +1,41 @@ +import system'math. +import system'collections. +import system'routines. +import extensions. + +extension $op +{ + logTwo + = self ln / 2 ln. +} + +symbol program = +[ + var input := console readLine. + var infoC := 0.0r. + var table := Dictionary new. + + input forEach(:ch) + [ + var n := table[ch]. + if ($nil == n) + [ + table[ch] := 1. + ]; + [ + table[ch] := n + 1. + ] + ]. + + var freq := 0. + table forEach(:letter) + [ + freq := letter int; realDiv(input length). + + infoC += (freq * freq logTwo). + ]. + + infoC *= -1. + + console printLine("The Entropy of ", input, " is ", infoC). +]. diff --git a/Task/Entropy/Friendly-interactive-shell/entropy.fish b/Task/Entropy/Friendly-interactive-shell/entropy.fish new file mode 100644 index 0000000000..d64525b9eb --- /dev/null +++ b/Task/Entropy/Friendly-interactive-shell/entropy.fish @@ -0,0 +1,21 @@ +function entropy + for arg in $argv + set name count_$arg + if not count $$name > /dev/null + set $name 0 + set values $values $arg + end + set $name (math $$name + 1) + end + set entropy 0 + for value in $values + set name count_$value + set entropy (echo " + scale = 50 + p = "$$name" / "(count $argv)" + $entropy - p * l(p) + " | bc -l) + end + echo "$entropy / l(2)" | bc -l +end +entropy (echo 1223334444 | fold -w1) diff --git a/Task/Entropy/Go/entropy-1.go b/Task/Entropy/Go/entropy-1.go new file mode 100644 index 0000000000..b1b6165712 --- /dev/null +++ b/Task/Entropy/Go/entropy-1.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "math" + "strings" +) + +func main(){ + fmt.Println(H("1223334444")) +} + +func H(data string) (entropy float64) { + if data == "" { + return 0 + } + for i := 0; i < 256; i++ { + px := float64(strings.Count(data, string(byte(i)))) / float64(len(data)) + if px > 0 { + entropy += -px * math.Log2(px) + } + } + return entropy +} diff --git a/Task/Entropy/Go/entropy-2.go b/Task/Entropy/Go/entropy-2.go new file mode 100644 index 0000000000..3bb86d8cf0 --- /dev/null +++ b/Task/Entropy/Go/entropy-2.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + "math" +) + +func main() { + const s = "1223334444" + + m := map[rune]float64{} + for _, r := range s { + m[r]++ + } + var fm float64 + for _, c := range m { + hm += c * math.Log2(c) + } + const l = float64(len(s)) + fmt.Println(math.Log2(l) - hm/l) +} diff --git a/Task/Entropy/Go/entropy.go b/Task/Entropy/Go/entropy.go deleted file mode 100644 index 6fc111c43f..0000000000 --- a/Task/Entropy/Go/entropy.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "fmt" - "math" -) - -const s = "1223334444" - -func main() { - m := map[rune]float64{} - for _, r := range s { - m[r]++ - } - hm := 0. - for _, c := range m { - hm += c * math.Log2(c) - } - const l = float64(len(s)) - fmt.Println(math.Log2(l) - hm/l) -} diff --git a/Task/Entropy/jq/entropy-1.jq b/Task/Entropy/Jq/entropy-1.jq similarity index 100% rename from Task/Entropy/jq/entropy-1.jq rename to Task/Entropy/Jq/entropy-1.jq diff --git a/Task/Entropy/jq/entropy-2.jq b/Task/Entropy/Jq/entropy-2.jq similarity index 100% rename from Task/Entropy/jq/entropy-2.jq rename to Task/Entropy/Jq/entropy-2.jq diff --git a/Task/Entropy/Kotlin/entropy.kotlin b/Task/Entropy/Kotlin/entropy.kotlin new file mode 100644 index 0000000000..a5edab76c4 --- /dev/null +++ b/Task/Entropy/Kotlin/entropy.kotlin @@ -0,0 +1,33 @@ +// version 1.0.6 + +fun log2(d: Double) = Math.log(d) / Math.log(2.0) + +fun shannon(s: String): Double { + val counters = mutableMapOf() + for (c in s) { + if (counters.containsKey(c)) counters[c] = counters[c]!! + 1 + else counters.put(c, 1) + } + val nn = s.length.toDouble() + var sum = 0.0 + for (key in counters.keys) { + val term = counters[key]!! / nn + sum += term * log2(term) + } + return -sum +} + +fun main(args: Array) { + val samples = arrayOf( + "1223334444", + "1223334444555555555", + "122333", + "1227774444", + "aaBBcccDDDD", + "1234567890abcdefghijklmnopqrstuvwxyz", + "Rosetta Code" + ) + println(" String Entropy") + println("------------------------------------ ------------------") + for (sample in samples) println("${sample.padEnd(36)} -> ${"%18.16f".format(shannon(sample))}") +} diff --git a/Task/Entropy/Phix/entropy.phix b/Task/Entropy/Phix/entropy.phix new file mode 100644 index 0000000000..e9105bc661 --- /dev/null +++ b/Task/Entropy/Phix/entropy.phix @@ -0,0 +1,28 @@ +function log2(atom v) + return log(v)/log(2) +end function + +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 + integer n = length(counts) + for i=1 to n do + atom ci = counts[i]/N + H -= ci*log2(ci) + end for + return H +end function + +?entropy("1223334444") diff --git a/Task/Entropy/REXX/entropy-3.rexx b/Task/Entropy/REXX/entropy-3.rexx index 05a43a5517..543d4ddc83 100644 --- a/Task/Entropy/REXX/entropy-3.rexx +++ b/Task/Entropy/REXX/entropy-3.rexx @@ -1,18 +1,18 @@ /*REXX program calculates the information entropy for a given character string. */ numeric digits 50 /*use 50 decimal digits for precision. */ -parse arg $; if $='' then $=1223334444 /*obtain the optional input from the CL*/ -#=0; @.=0; L=length($); $$= /*define handy-dandy REXX variables. */ - - do j=1 for L; _=substr($,j,1) /*process each character in $ string.*/ - if @._==0 then do; #=#+1 /*Unique? Yes, bump character counter.*/ - $$=$$ || _ /*add this character to the $$ list. */ - end - @._=@._+1 /*keep track of this character's count.*/ - end /*j*/ +parse arg $; if $='' then $=1223334444 /*obtain the optional input from the CL*/ +#=0; @.=0; L=length($) /*define handy-dandy REXX variables. */ +$$= /*initialize the $$ list. */ + do j=1 for L; _=substr($, j, 1) /*process each character in $ string.*/ + if @._==0 then do; #=# + 1 /*Unique? Yes, bump character counter.*/ + $$=$$ || _ /*add this character to the $$ list. */ + end + @._=@._ + 1 /*keep track of this character's count.*/ + end /*j*/ sum=0 /*calculate info entropy for each char.*/ - do i=1 for #; _=substr($$,i,1) /*obtain a character from unique list. */ - sum=sum - @._/L * log2(@._/L) /*add (negatively) the char entropies. */ - end /*i*/ + do i=1 for #; _=substr($$, i, 1) /*obtain a character from unique list. */ + sum=sum - @._/L * log2(@._/L) /*add (negatively) the char entropies. */ + end /*i*/ say ' input string: ' $ say 'string length: ' L @@ -23,8 +23,8 @@ exit /*stick a fork in it, we're al log2: procedure; parse arg x 1 ox; ig= x>1.5; ii=0; is=1 - 2 * (ig\==1) numeric digits digits()+5 /* [↓] precision of E must be≥digits()*/ e=2.71828182845904523536028747135266249775724709369995957496696762772407663035354759 - do while ig & ox>1.5 | \ig&ox<.5; _=e; do j=-1; iz=ox* _**-is + do while ig & ox>1.5 | \ig&ox<.5; _=e; do j=-1; iz=ox * _ ** -is if j>=0 & (ig & iz<1 | \ig&iz>.5) then leave; _=_*_; izz=iz; end /*j*/ - ox=izz; ii=ii+is*2**j; end; x=x* e**-ii-1; z=0; _=-1; p=z + ox=izz; ii=ii+is*2**j; end /*while*/; x=x * e** -ii -1; z=0; _=-1; p=z do k=1; _=-_*x; z=z+_/k; if z=p then leave; p=z; end /*k*/ r=z+ii; if arg()==2 then return r; return r/log2(2,.) diff --git a/Task/Entropy/Ring/entropy.ring b/Task/Entropy/Ring/entropy.ring new file mode 100644 index 0000000000..e96275450c --- /dev/null +++ b/Task/Entropy/Ring/entropy.ring @@ -0,0 +1,32 @@ +decimals(8) +entropy = 0 +countOfChar = list(255) + +source="1223334444" +charCount =len( source) +usedChar ="" + +for i =1 to len( source) + ch =substr(source, i, 1) + if not(substr( usedChar, ch)) usedChar =usedChar +ch ok + j =substr( usedChar, ch) + countOfChar[j] =countOfChar[j] +1 +next + +l =len(usedChar) +for i =1 to l + probability =countOfChar[i] /charCount + entropy =entropy - (probability *logBase(probability, 2)) +next + +see "Characters used and the number of occurrences of each " + nl +for i =1 to l + see "'" + substr(usedChar, i, 1) + "' " + countOfChar[i] + nl +next + +see " Entropy of " + source + " is " + entropy + " bits." + nl +see " The result should be around 1.84644 bits." + nl + +func logBase (x, b) + logBase =log( x) /log( 2) + return logBase diff --git a/Task/Entropy/Scheme/entropy.ss b/Task/Entropy/Scheme/entropy.ss new file mode 100644 index 0000000000..7500c0ff84 --- /dev/null +++ b/Task/Entropy/Scheme/entropy.ss @@ -0,0 +1,42 @@ +(define (entropy input) + (define (close? a b) + (define (norm x y) + (define (infinite_norm m n) + (define (absminus p q) + (cond ((null? p) '()) + (else (cons (abs (- (car p) (car q))) (absminus (cdr p) (cdr q)))))) + (define (mm l) + (cond ((null? (cdr l)) (car l)) + ((> (car l) (cadr l)) (mm (cons (car l) (cddr l)))) + (else (mm (cdr l))))) + (mm (absminus m n))) + (if (pair? x) (infinite_norm x y) (abs (- x y)))) + (let ((epsilon 0.2)) + (< (norm a b) epsilon))) + (define (freq-list x) + (define (f x) + (define (count a b) + (cond ((null? b) 1) + (else (+ (if (close? a (car b)) 1 0) (count a (cdr b)))))) + (let ((t (car x)) (tt (cdr x))) + (count t tt))) + (define (g x) + (define (filter a b) + (cond ((null? b) '()) + ((close? a (car b)) (filter a (cdr b))) + (else (cons (car b) (filter a (cdr b)))))) + (let ((t (car x)) (tt (cdr x))) + (filter t tt))) + (cond ((null? x) '()) + (else (cons (f x) (freq-list (g x)))))) + (define (scale x) + (define (sum x) + (if (null? x) 0.0 (+ (car x) (sum (cdr x))))) + (let ((z (sum x))) + (map (lambda(m) (/ m z)) x))) + (define (cal x) + (if (null? x) 0 (+ (* (car x) (/ (log (car x)) (log 2))) (cal (cdr x))))) + (- (cal (scale (freq-list input))))) + +(entropy (list 1 2 2 3 3 3 4 4 4 4)) +(entropy (list (list 1 1) (list 1.1 1.1) (list 1.2 1.2) (list 1.3 1.3) (list 1.5 1.5) (list 1.6 1.6))) diff --git a/Task/Entropy/Scilab/entropy.scilab b/Task/Entropy/Scilab/entropy.scilab new file mode 100644 index 0000000000..7c7c1ab580 --- /dev/null +++ b/Task/Entropy/Scilab/entropy.scilab @@ -0,0 +1,20 @@ +function E = entropy(d) + d=strsplit(d); + n=unique(string(d)); + N=size(d,'r'); + + count=zeros(n); + n_size = size(n,'r'); + for i = 1:n_size + count(i) = sum ( d == n(i) ); + end + + E=0; + for i=1:length(count) + E = E - count(i)/N * log(count(i)/N) / log(2); + end +endfunction + +word ='1223334444'; +E = entropy(word); +disp('The entropy of '+word+' is '+string(E)+'.'); diff --git a/Task/Entropy/Zkl/entropy.zkl b/Task/Entropy/Zkl/entropy.zkl new file mode 100644 index 0000000000..ca9adbdcfa --- /dev/null +++ b/Task/Entropy/Zkl/entropy.zkl @@ -0,0 +1,10 @@ +fcn entropy(text){ + text.pump(Void,fcn(c,freq){ c=c.toAsc(); freq[c]+=1; freq } + .fp1( (0).pump(256,List,0.0).copy() )) // array[256] of 0.0 + .filter() // remove all zero entries from array + .apply('/(text.len())) // (num of char)/len + .apply(fcn(p){-p*p.log()}) // |p*ln(p)| + .sum(0.0)/(2.0).log(); // sum * ln(e)/ln(2) to convert to log2 +} + +entropy("1223334444").println(" bits"); diff --git a/Task/Enumerations/BASIC/enumerations.basic b/Task/Enumerations/BASIC/enumerations-1.basic similarity index 100% rename from Task/Enumerations/BASIC/enumerations.basic rename to Task/Enumerations/BASIC/enumerations-1.basic diff --git a/Task/Enumerations/BASIC/enumerations-2.basic b/Task/Enumerations/BASIC/enumerations-2.basic new file mode 100644 index 0000000000..c356fe3090 --- /dev/null +++ b/Task/Enumerations/BASIC/enumerations-2.basic @@ -0,0 +1,18 @@ +' Enumerations +' Start at zero +ENUM + cat, dog, parrot +END ENUM +PRINT "Dogs are #", dog + +' Set value +ENUM + Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday +END ENUM +PRINT Sunday, " ", Wednesday, " ", Saturday + +' Change values, ENUM names must be unique +ENUM + sunday=7, monday=1, tuesday, wednesday, thursday, friday, saturday +END ENUM +PRINT sunday, " ", wednesday, " ", saturday diff --git a/Task/Enumerations/JavaScript/enumerations.js b/Task/Enumerations/JavaScript/enumerations.js index 493039a3ed..ad9cc3c743 100644 --- a/Task/Enumerations/JavaScript/enumerations.js +++ b/Task/Enumerations/JavaScript/enumerations.js @@ -1,2 +1,7 @@ -var fruits = { APPLE : 0, BANANA : 1, CHERRY : 2 }; -Object.freeze(fruits); +// enum fruits { apple, banana, cherry } + +var f = "apple"; + +if(f == "apple"){ + f = "banana"; +} diff --git a/Task/Enumerations/Julia/enumerations.julia b/Task/Enumerations/Julia/enumerations.julia new file mode 100644 index 0000000000..84bd1bbfa6 --- /dev/null +++ b/Task/Enumerations/Julia/enumerations.julia @@ -0,0 +1 @@ +@enum Fruits APPLE BANANA CHERRY diff --git a/Task/Enumerations/Kotlin/enumerations.kotlin b/Task/Enumerations/Kotlin/enumerations.kotlin new file mode 100644 index 0000000000..0891ffe436 --- /dev/null +++ b/Task/Enumerations/Kotlin/enumerations.kotlin @@ -0,0 +1,15 @@ +// version 1.0.5-2 + +enum class Animals { + CAT, DOG, ZEBRA +} + +enum class Dogs(val id: Int) { + BULLDOG(1), TERRIER(2), WOLFHOUND(4) +} + +fun main(args: Array) { + for (value in Animals.values()) println("${value.name.padEnd(5)} : ${value.ordinal}") + println() + for (value in Dogs.values()) println("${value.name.padEnd(9)} : ${value.id}") +} diff --git a/Task/Enumerations/PureBasic/enumerations-4.purebasic b/Task/Enumerations/PureBasic/enumerations-4.purebasic new file mode 100644 index 0000000000..e53e81c378 --- /dev/null +++ b/Task/Enumerations/PureBasic/enumerations-4.purebasic @@ -0,0 +1,19 @@ +;This starts the enumeration of a named group 'NamedGroup'. +Enumeration NamedGroup 5 + #Green ; 5 + #Orange ; 6 +EndEnumeration + +;EnumerationBinary will use values that are a double of the previous value (or starting value). +EnumerationBinary + #North ; 1 + #West ; 2 + #South ; 4 + #East ; 8 +EndEnumeration + +;This continues the enumeration of the previously named group 'NamedGroup'. +Enumeration NamedGroup + #Yellow ; 7 + #Red ; 8 +EndEnumeration diff --git a/Task/Enumerations/Zkl/enumerations-1.zkl b/Task/Enumerations/Zkl/enumerations-1.zkl new file mode 100644 index 0000000000..36fe7a09d8 --- /dev/null +++ b/Task/Enumerations/Zkl/enumerations-1.zkl @@ -0,0 +1,6 @@ +const RGB_COLOR{ // put color names in a name space + const RED =0xf00; + const BLUE=0x0f0, GREEN = 0x00f; + const CYAN=BLUE + GREEN; // → 0x0ff +} +println(RGB_COLOR.BLUE); diff --git a/Task/Enumerations/Zkl/enumerations-2.zkl b/Task/Enumerations/Zkl/enumerations-2.zkl new file mode 100644 index 0000000000..a6e5e88b40 --- /dev/null +++ b/Task/Enumerations/Zkl/enumerations-2.zkl @@ -0,0 +1,4 @@ +const X0=N; // --> 0 +const A=N,B=N,C=N; // --> 1,2,3 +const{ _n=-1; } // reset Enum, this should be a const space function +const X=N; // -->0 diff --git a/Task/Enumerations/Zkl/enumerations-3.zkl b/Task/Enumerations/Zkl/enumerations-3.zkl new file mode 100644 index 0000000000..df021c2e32 --- /dev/null +++ b/Task/Enumerations/Zkl/enumerations-3.zkl @@ -0,0 +1,3 @@ +#continuing ... +z:=N; // -->2 NOT 1 as it is set AFTER Y (compile time vs parse time) +const Y=N; // -->1! because it is set before z diff --git a/Task/Enumerations/jq/enumerations.jq b/Task/Enumerations/jq/enumerations.jq deleted file mode 100644 index b2058ebad0..0000000000 --- a/Task/Enumerations/jq/enumerations.jq +++ /dev/null @@ -1,2 +0,0 @@ -{"fruits" : { "apple" : null, "banana" : null, "cherry" : null } -{"fruits" : { "apple" : 0, "banana" : 1, "cherry" : 2 } diff --git a/Task/Environment-variables/BASIC/environment-variables-2.basic b/Task/Environment-variables/BASIC/environment-variables-2.basic index 10cbaccf17..e3839f0d98 100644 --- a/Task/Environment-variables/BASIC/environment-variables-2.basic +++ b/Task/Environment-variables/BASIC/environment-variables-2.basic @@ -1,3 +1 @@ -10 PRINT "The border colour is "; PEEK (23624): REM bordcr -20 PRINT "The ramtop address is "; PEEK (23730) + 256 * PEEK (23731): REM ramtop -30 POKE 23609,50: REM set keyboard pip to 50 +PRINT GETENVIRON$("PATH") diff --git a/Task/Special-variables/Tcl/special-variables-2.tcl b/Task/Environment-variables/BASIC/environment-variables-3.basic similarity index 100% rename from Task/Special-variables/Tcl/special-variables-2.tcl rename to Task/Environment-variables/BASIC/environment-variables-3.basic diff --git a/Task/Environment-variables/jq/environment-variables.jq b/Task/Environment-variables/Jq/environment-variables.jq similarity index 100% rename from Task/Environment-variables/jq/environment-variables.jq rename to Task/Environment-variables/Jq/environment-variables.jq diff --git a/Task/Environment-variables/Kotlin/environment-variables.kotlin b/Task/Environment-variables/Kotlin/environment-variables.kotlin new file mode 100644 index 0000000000..b8f4934fe1 --- /dev/null +++ b/Task/Environment-variables/Kotlin/environment-variables.kotlin @@ -0,0 +1,7 @@ +// version 1.0.6 + +// tested on Windows 10 + +fun main(args: Array) { + println(System.getenv("SystemRoot")) +} diff --git a/Task/Environment-variables/Logtalk/environment-variables.logtalk b/Task/Environment-variables/Logtalk/environment-variables.logtalk new file mode 100644 index 0000000000..9a085bcc47 --- /dev/null +++ b/Task/Environment-variables/Logtalk/environment-variables.logtalk @@ -0,0 +1 @@ +os::environment_variable('PATH', Path). diff --git a/Task/Environment-variables/Stata/environment-variables.stata b/Task/Environment-variables/Stata/environment-variables.stata new file mode 100644 index 0000000000..6b40d34e17 --- /dev/null +++ b/Task/Environment-variables/Stata/environment-variables.stata @@ -0,0 +1,3 @@ +display "`: env PATH'" +display "`: env USERNAME'" +display "`: env USERPROFILE'" diff --git a/Task/Environment-variables/Zkl/environment-variables.zkl b/Task/Environment-variables/Zkl/environment-variables.zkl new file mode 100644 index 0000000000..9e8a606be5 --- /dev/null +++ b/Task/Environment-variables/Zkl/environment-variables.zkl @@ -0,0 +1,3 @@ +System.getenv("HOME") +/home/craigd +System.getenv() //--> Dictionary of all env vars diff --git a/Task/Equilibrium-index/AppleScript/equilibrium-index.applescript b/Task/Equilibrium-index/AppleScript/equilibrium-index.applescript new file mode 100644 index 0000000000..6ca2cab943 --- /dev/null +++ b/Task/Equilibrium-index/AppleScript/equilibrium-index.applescript @@ -0,0 +1,178 @@ +-- equilibriumIndices :: [Int] -> [Int] +on equilibriumIndices(xs) + + script balancedPair + on |λ|(a, pair, i) + set {x, y} to pair + if x = y then + {i - 1} & a + else + a + end if + end |λ| + end script + + script plus + on |λ|(a, b) + a + b + end |λ| + end script + + -- Fold over zipped pairs of sums from left + -- and sums from right + + foldr(balancedPair, {}, ¬ + zip(scanl1(plus, xs), scanr1(plus, xs))) + +end equilibriumIndices + +-- TEST ----------------------------------------------------------------------- +on run + + map(equilibriumIndices, {¬ + {-7, 1, 5, 2, -4, 3, 0}, ¬ + {2, 4, 6}, ¬ + {2, 9, 2}, ¬ + {1, -1, 1, -1, 1, -1, 1}, ¬ + {1}, ¬ + {}}) + + --> {{3, 6}, {}, {1}, {0, 1, 2, 3, 4, 5, 6}, {0}, {}} +end run + + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl + +-- foldr :: (a -> b -> a) -> a -> [b] -> a +on foldr(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from lng to 1 by -1 + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldr + +-- init :: [a] -> [a] +on init(xs) + set lng to length of xs + if lng > 1 then + items 1 thru -2 of xs + else if lng > 0 then + {} + else + missing value + end if +end init + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- min :: Ord a => a -> a -> a +on min(x, y) + if y < x then + y + else + x + end if +end min + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- scanl :: (b -> a -> b) -> b -> [a] -> [b] +on scanl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + set lst to {startValue} + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + set end of lst to v + end repeat + return lst + end tell +end scanl + +-- scanl1 :: (a -> a -> a) -> [a] -> [a] +on scanl1(f, xs) + if length of xs > 0 then + scanl(f, item 1 of xs, tail(xs)) + else + {} + end if +end scanl1 + +-- scanr :: (b -> a -> b) -> b -> [a] -> [b] +on scanr(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + set lst to {startValue} + repeat with i from lng to 1 by -1 + set v to |λ|(v, item i of xs, i, xs) + set end of lst to v + end repeat + return reverse of lst + end tell +end scanr + +-- scanr1 :: (a -> a -> a) -> [a] -> [a] +on scanr1(f, xs) + if length of xs > 0 then + scanr(f, item -1 of xs, init(xs)) + else + {} + end if +end scanr1 + +-- tail :: [a] -> [a] +on tail(xs) + if length of xs > 1 then + items 2 thru -1 of xs + else + {} + end if +end tail + +-- zip :: [a] -> [b] -> [(a, b)] +on zip(xs, ys) + set lng to min(length of xs, length of ys) + set lst to {} + repeat with i from 1 to lng + set end of lst to {item i of xs, item i of ys} + end repeat + return lst +end zip diff --git a/Task/Equilibrium-index/Haskell/equilibrium-index-4.hs b/Task/Equilibrium-index/Haskell/equilibrium-index-4.hs new file mode 100644 index 0000000000..331c5b95f1 --- /dev/null +++ b/Task/Equilibrium-index/Haskell/equilibrium-index-4.hs @@ -0,0 +1,27 @@ +equilibriumIndices :: [Int] -> [Int] +equilibriumIndices xs = + foldr + (\(x, y, i) a -> + (if x == y + then i : a + else a)) + [] + (zip3 + (scanl1 (+) xs) -- Sums from the left + (scanr1 (+) xs) -- Sums from the right + [0 ..] -- Indices + ) + +-- TEST ----------------------------------------------------------------------- +main :: IO () +main = + mapM_ + print + (equilibriumIndices <$> + [ [-7, 1, 5, 2, -4, 3, 0] + , [2, 4, 6] + , [2, 9, 2] + , [1, -1, 1, -1, 1, -1, 1] + , [1] + , [] + ]) diff --git a/Task/Equilibrium-index/JavaScript/equilibrium-index.js b/Task/Equilibrium-index/JavaScript/equilibrium-index-1.js similarity index 100% rename from Task/Equilibrium-index/JavaScript/equilibrium-index.js rename to Task/Equilibrium-index/JavaScript/equilibrium-index-1.js diff --git a/Task/Equilibrium-index/JavaScript/equilibrium-index-2.js b/Task/Equilibrium-index/JavaScript/equilibrium-index-2.js new file mode 100644 index 0000000000..617450f7f1 --- /dev/null +++ b/Task/Equilibrium-index/JavaScript/equilibrium-index-2.js @@ -0,0 +1,93 @@ +(() => { + // EQUILIBRIUM INDICES ---------------------------------------------------- + + // equilibriumIndices :: [Int] -> [Int] + const equilibriumIndices = xs => + foldr((a, [x, y], i) => + x === y ? cons(i, a) : a, + [], + zip( + scanl1(plus, xs), // Sums from the left + scanr1(plus, xs) // Sums from the right + ) + ); + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // cons :: a -> [a] -> [a] + const cons = (x, xs) => [x].concat(xs); + + // foldr (a -> b -> a) -> a -> [b] -> a + const foldr = (f, a, xs) => xs.reduceRight(f, a); + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // plus :: Num a => a -> a -> a + const plus = (a, b) => a + b; + + // scanl :: (b -> a -> b) -> b -> [a] -> [b] + const scanl = (f, startValue, xs) => + xs.reduce((a, x) => { + const v = f(a.acc, x); + return { + acc: v, + scan: a.scan.concat(v) + }; + }, { + acc: startValue, + scan: [startValue] + }) + .scan; + + // scanl1 :: (a -> a -> a) -> [a] -> [a] + const scanl1 = (f, xs) => + xs.length > 0 ? scanl(f, xs[0], xs.slice(1)) : []; + + // scanr :: (b -> a -> b) -> b -> [a] -> [b] + const scanr = (f, startValue, xs) => + xs.reduceRight((a, x) => { + const v = f(a.acc, x); + return { + acc: v, + scan: [v].concat(a.scan) + }; + }, { + acc: startValue, + scan: [startValue] + }) + .scan; + + // scanr1 :: (a -> a -> a) -> [a] -> [a] + const scanr1 = (f, xs) => + xs.length > 0 ? scanr(f, xs.slice(-1)[0], xs.slice(0, -1)) : []; + + // Any value -> optional number of indents -> String + // show :: a -> String + // show :: a -> Int -> String + const show = (...x) => + JSON.stringify.apply( + null, x.length > 1 ? [x[0], null, x[1]] : x + ); + + // tail :: [a] -> [a] + const tail = xs => xs.length ? xs.slice(1) : undefined; + + // zip :: [a] -> [b] -> [(a,b)] + const zip = (xs, ys) => + xs.slice(0, Math.min(xs.length, ys.length)) + .map((x, i) => [x, ys[i]]); + + // TEST ------------------------------------------------------------------- + return show( + map(equilibriumIndices, [ + [-7, 1, 5, 2, -4, 3, 0], + [2, 4, 6], + [2, 9, 2], + [1, -1, 1, -1, 1, -1, 1], + [1], + [] + ]) + ); + // -> [[3, 6], [], [1], [0, 1, 2, 3, 4, 5, 6], [0], []] +})(); diff --git a/Task/Equilibrium-index/JavaScript/equilibrium-index-3.js b/Task/Equilibrium-index/JavaScript/equilibrium-index-3.js new file mode 100644 index 0000000000..8c60265a6c --- /dev/null +++ b/Task/Equilibrium-index/JavaScript/equilibrium-index-3.js @@ -0,0 +1 @@ +[[3,6],[],[1],[0,1,2,3,4,5,6],[0],[]] diff --git a/Task/Equilibrium-index/jq/equilibrium-index-1.jq b/Task/Equilibrium-index/Jq/equilibrium-index-1.jq similarity index 100% rename from Task/Equilibrium-index/jq/equilibrium-index-1.jq rename to Task/Equilibrium-index/Jq/equilibrium-index-1.jq diff --git a/Task/Equilibrium-index/jq/equilibrium-index-2.jq b/Task/Equilibrium-index/Jq/equilibrium-index-2.jq similarity index 100% rename from Task/Equilibrium-index/jq/equilibrium-index-2.jq rename to Task/Equilibrium-index/Jq/equilibrium-index-2.jq diff --git a/Task/Equilibrium-index/jq/equilibrium-index-3.jq b/Task/Equilibrium-index/Jq/equilibrium-index-3.jq similarity index 100% rename from Task/Equilibrium-index/jq/equilibrium-index-3.jq rename to Task/Equilibrium-index/Jq/equilibrium-index-3.jq diff --git a/Task/Equilibrium-index/Julia/equilibrium-index.julia b/Task/Equilibrium-index/Julia/equilibrium-index.julia new file mode 100644 index 0000000000..be510dc429 --- /dev/null +++ b/Task/Equilibrium-index/Julia/equilibrium-index.julia @@ -0,0 +1,19 @@ +# v0.6.0 + +function equindex2pass(data::Array) + rst = Array{Int}([]) + suml, sumr, ddelayed = 0, sum(data), 0 + for (i, d) in enumerate(data) + suml += ddelayed + sumr -= d + ddelayed = d + if suml == sumr + push!(rst, i) + end + end + return length(rst) > 0 ? rst : nothing +end + +@show equindex2pass([1, -1, 1, -1, 1, -1, 1]) +@show equindex2pass([1, 2, 2, 1]) +@show equindex2pass([-7, 1, 5, 2, -4, 3, 0]) diff --git a/Task/Equilibrium-index/Kotlin/equilibrium-index.kotlin b/Task/Equilibrium-index/Kotlin/equilibrium-index.kotlin new file mode 100644 index 0000000000..5b629c3c9d --- /dev/null +++ b/Task/Equilibrium-index/Kotlin/equilibrium-index.kotlin @@ -0,0 +1,25 @@ +// version 1.1 + +fun equilibriumIndices(a: IntArray): MutableList { + val ei = mutableListOf() + if (a.isEmpty()) return ei // empty list + val sumAll = a.sumBy { it } + var sumLeft = 0 + var sumRight: Int + for (i in 0 until a.size) { + sumRight = sumAll - sumLeft - a[i] + if (sumLeft == sumRight) ei.add(i) + sumLeft += a[i] + } + return ei +} + +fun main(args: Array) { + val a = intArrayOf(-7, 1, 5, 2, -4, 3, 0) + val ei = equilibriumIndices(a) + when (ei.size) { + 0 -> println("There are no equilibrium indices") + 1 -> println("The only equilibrium index is : ${ei[0]}") + else -> println("The equilibrium indices are : ${ei.joinToString(", ")}") + } +} diff --git a/Task/Equilibrium-index/Perl-6/equilibrium-index-2.pl6 b/Task/Equilibrium-index/Perl-6/equilibrium-index-2.pl6 index a461c80ca8..39e08cd301 100644 --- a/Task/Equilibrium-index/Perl-6/equilibrium-index-2.pl6 +++ b/Task/Equilibrium-index/Perl-6/equilibrium-index-2.pl6 @@ -1,5 +1,5 @@ sub equilibrium_index(@list) { my @a = [\+] @list; - my @b := reverse [\+] reverse @list; + my @b = reverse [\+] reverse @list; ^@list Zxx (@a »==« @b); } diff --git a/Task/Equilibrium-index/REXX/equilibrium-index-1.rexx b/Task/Equilibrium-index/REXX/equilibrium-index-1.rexx index e445c8b045..bd884ff449 100644 --- a/Task/Equilibrium-index/REXX/equilibrium-index-1.rexx +++ b/Task/Equilibrium-index/REXX/equilibrium-index-1.rexx @@ -1,21 +1,17 @@ /*REXX program calculates and displays the equilibrium index for a numeric array (list).*/ parse arg x /*obtain the optional arguments from CL*/ if x='' then x=copies(" 7 -7", 50) 7 /*Not specified? Then use the default.*/ -say ' array list: ' space(x) /*echo the array list to the terminal. */ -n=words(x) /*the number of numbers in the X list.*/ - do j=0 for n /*zero─start is for zero─based array. */ - A.j=word(x, j+1) /*define the array element ───► A.j */ - end /*j*/ /* [↑] assign A.0 A.1 A.3 ··· */ +say ' array list: ' space(x) /*echo the array list to the terminal. */ +#=words(x) /*the number of elements in the X list.*/ + do j=0 for #; @.j=word(x, j+1) /*zero─start is for zero─based array. */ + end /*j*/ /* [↑] assign @.0 @.1 @.3 ··· */ say /* ··· and also display a blank line. */ -ans=equilibriumIDX(n) /*calculate the equilibrium index. */ -say 'equilibrium' word("indices index", 1 + (words(ans==1)))': ' ans +answer=equilibriumIDX(); w=words(answer) /*calculate the equilibrium index. */ +say 'equilibrium' word("(none) index: indices:", 1 + (w>0) + (w>1)) answer exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -equilibriumIDX: procedure expose A.; parse arg # /*expose the array A. (make global).*/ -$= /*equilibrium indices (so far). */ - do i=0 for #; sum=0 - do k=0 for #; sum=sum + A.k*sign(k-i); end /*k*/ - if sum=0 then $=$ i - end /*i*/ -if $=='' then $="(none)" /*adjust if no indices were found. */ -return strip($) /*return the equilibrium list. */ +equilibriumIDX: $=; do i=0 for #; sum=0 + do k=0 for #; sum=sum + @.k*sign(k-i); end /*k*/ + if sum==0 then $=$ i + end /*i*/ /* [↑] Zero? Found an equilibrium index*/ + return $ /*return equilibrium list (may be null)*/ diff --git a/Task/Equilibrium-index/Zkl/equilibrium-index-1.zkl b/Task/Equilibrium-index/Zkl/equilibrium-index-1.zkl new file mode 100644 index 0000000000..89af822ee5 --- /dev/null +++ b/Task/Equilibrium-index/Zkl/equilibrium-index-1.zkl @@ -0,0 +1,9 @@ +fcn equilibrium(lst){ // two pass + reg acc=List(), left=0,right=lst.sum(0),i=0; + foreach x in (lst){ + right-=x; + if(left==right) acc.write(i); + i+=1; left+=x; + } + acc +} diff --git a/Task/Equilibrium-index/Zkl/equilibrium-index-2.zkl b/Task/Equilibrium-index/Zkl/equilibrium-index-2.zkl new file mode 100644 index 0000000000..8e2a2e100c --- /dev/null +++ b/Task/Equilibrium-index/Zkl/equilibrium-index-2.zkl @@ -0,0 +1,3 @@ +fcn equilibrium(lst){ // lst should immutable, n^2 + (0).filter(lst.len(),'wrap(n){ lst[0,n].sum(0) == lst[n+1,*].sum(0) }) +} diff --git a/Task/Equilibrium-index/Zkl/equilibrium-index-3.zkl b/Task/Equilibrium-index/Zkl/equilibrium-index-3.zkl new file mode 100644 index 0000000000..e47b0245ed --- /dev/null +++ b/Task/Equilibrium-index/Zkl/equilibrium-index-3.zkl @@ -0,0 +1 @@ +equilibrium(T(-7, 1, 5, 2, -4, 3, 0)).println(); diff --git a/Task/Ethiopian-multiplication/ALGOL-W/ethiopian-multiplication.alg b/Task/Ethiopian-multiplication/ALGOL-W/ethiopian-multiplication.alg new file mode 100644 index 0000000000..7bdd3f8f39 --- /dev/null +++ b/Task/Ethiopian-multiplication/ALGOL-W/ethiopian-multiplication.alg @@ -0,0 +1,38 @@ +begin + % returns half of a % + integer procedure halve ( integer value a ) ; a div 2; + % returns a doubled % + integer procedure double ( integer value a ) ; a * 2; + % returns true if a is even, false otherwise % + logical procedure even ( integer value a ) ; not odd( a ); + % returns the product of a and b using ethopian multiplication % + % rather than keep a table of the intermediate results, % + % we examine then as they are generated % + integer procedure ethopianMultiplication ( integer value a, b ) ; + begin + integer v, r, accumulator; + v := a; + r := b; + accumulator := 0; + i_w := 4; s_w := 0; % set output formatting % + while begin + write( v ); + if even( v ) then writeon( " ---" ) + else begin + accumulator := accumulator + r; + writeon( " ", r ); + end; + v := halve( v ); + r := double( r ); + v > 0 + end do begin end; + write( " =====" ); + accumulator + end ethopianMultiplication ; + % task test case % + begin + integer m; + m := ethopianMultiplication( 17, 34 ); + write( " ", m ) + end +end. diff --git a/Task/Ethiopian-multiplication/ActionScript/ethiopian-multiplication-1.as b/Task/Ethiopian-multiplication/ActionScript/ethiopian-multiplication-1.as deleted file mode 100644 index d76c91f540..0000000000 --- a/Task/Ethiopian-multiplication/ActionScript/ethiopian-multiplication-1.as +++ /dev/null @@ -1,31 +0,0 @@ -function Divide(a:Number):Number { - return ((a-(a%2))/2); -} -function Multiply(a:Number):Number { - return (a *= 2); -} -function isEven(a:Number):Boolean { - if (a%2 == 0) { - return (true); - } else { - return (false); - } -} -function Ethiopian(left:Number, right:Number) { - var r:Number = 0; - trace(left+" "+right); - while (left != 1) { - var State:String = "Keep"; - if (isEven(Divide(left))) { - State = "Strike"; - } - trace(Divide(left)+" "+Multiply(right)+" "+State); - left = Divide(left); - right = Multiply(right); - if (State == "Keep") { - r += right; - } - } - trace("="+" "+r); -} -} diff --git a/Task/Ethiopian-multiplication/ActionScript/ethiopian-multiplication-2.as b/Task/Ethiopian-multiplication/ActionScript/ethiopian-multiplication-2.as deleted file mode 100644 index 501920d2ee..0000000000 --- a/Task/Ethiopian-multiplication/ActionScript/ethiopian-multiplication-2.as +++ /dev/null @@ -1,6 +0,0 @@ -17 34 -8 68 Strike -4 136 Strike -2 272 Strike -1 544 Keep -= 578 diff --git a/Task/Ethiopian-multiplication/Ada/ethiopian-multiplication-1.ada b/Task/Ethiopian-multiplication/Ada/ethiopian-multiplication-1.ada deleted file mode 100644 index 0a202f89f3..0000000000 --- a/Task/Ethiopian-multiplication/Ada/ethiopian-multiplication-1.ada +++ /dev/null @@ -1,3 +0,0 @@ -package Ethiopian is - function Multiply(Left, Right : Integer) return Integer; -end Ethiopian; diff --git a/Task/Ethiopian-multiplication/Ada/ethiopian-multiplication-2.ada b/Task/Ethiopian-multiplication/Ada/ethiopian-multiplication-2.ada deleted file mode 100644 index 5fd786e3cc..0000000000 --- a/Task/Ethiopian-multiplication/Ada/ethiopian-multiplication-2.ada +++ /dev/null @@ -1,31 +0,0 @@ -package body Ethiopian is - function Is_Even(Item : Integer) return Boolean is - begin - return Item mod 2 = 0; - end Is_Even; - - function Double(Item : Integer) return Integer is - begin - return Item * 2; - end Double; - - function Half(Item : Integer) return Integer is - begin - return Item / 2; - end Half; - - function Multiply(Left, Right : Integer) return Integer is - Temp : Integer := 0; - Plier : Integer := Left; - Plicand : Integer := Right; - begin - while Plier >= 1 loop - if not Is_Even(Plier) then - Temp := Temp + Plicand; - end if; - Plier := Half(Plier); - Plicand := Double(Plicand); - end loop; - return Temp; - end Multiply; -end Ethiopian; diff --git a/Task/Ethiopian-multiplication/Ada/ethiopian-multiplication-3.ada b/Task/Ethiopian-multiplication/Ada/ethiopian-multiplication-3.ada deleted file mode 100644 index 5e992b8709..0000000000 --- a/Task/Ethiopian-multiplication/Ada/ethiopian-multiplication-3.ada +++ /dev/null @@ -1,11 +0,0 @@ -with Ethiopian; use Ethiopian; -with Ada.Text_Io; use Ada.Text_Io; - -procedure Ethiopian_Test is - First : Integer := 17; - Second : Integer := 34; -begin - Put_Line(Integer'Image(First) & " times " & - Integer'Image(Second) & " = " & - Integer'Image(Multiply(First, Second))); -end Ethiopian_Test; diff --git a/Task/Ethiopian-multiplication/Ada/ethiopian-multiplication.ada b/Task/Ethiopian-multiplication/Ada/ethiopian-multiplication.ada new file mode 100644 index 0000000000..cacf23d924 --- /dev/null +++ b/Task/Ethiopian-multiplication/Ada/ethiopian-multiplication.ada @@ -0,0 +1,14 @@ +with ada.text_io;use ada.text_io; + +procedure ethiopian is + function double (n : Natural) return Natural is (2*n); + function halve (n : Natural) return Natural is (n/2); + function is_even (n : Natural) return Boolean is (n mod 2 = 0); + + function mul (l, r : Natural) return Natural is + (if l = 0 then 0 elsif l = 1 then r elsif is_even (l) then mul (halve (l),double (r)) + else r + double (mul (halve (l), r))); + +begin + put_line (mul (17,34)'img); +end ethiopian; diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-1.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-1.basic index d720605383..ba019dedce 100644 --- a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-1.basic +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-1.basic @@ -1,4 +1,4 @@ -{{works with|QBasic}}While building the table, it's easier to simply not print unused values, rather than have to go back and strike them out afterward. (Both that and the actual adding happen in the "IF NOT (isEven(x))" block.)DECLARE FUNCTION half% (a AS INTEGER) +DECLARE FUNCTION half% (a AS INTEGER) DECLARE FUNCTION doub% (a AS INTEGER) DECLARE FUNCTION isEven% (a AS INTEGER) diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-8.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-8.basic new file mode 100644 index 0000000000..65f15f18a3 --- /dev/null +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-8.basic @@ -0,0 +1,38 @@ + 10 LET HALVE=320 + 20 LET DOUBLE=340 + 30 LET EVEN=360 + 40 DIM L(20) + 50 DIM R(20) + 60 INPUT L(1) + 70 INPUT R(1) + 80 LET I=1 + 90 PRINT L(1),R(1) +100 IF L(I)=1 THEN GOTO 200 +110 LET I=I+1 +120 IF I>20 THEN STOP +130 LET X=L(I-1) +140 GOSUB HALVE +150 LET L(I)=Y +160 LET X=R(I-1) +170 GOSUB DOUBLE +180 LET R(I)=Y +190 GOTO 90 +200 FOR K=1 TO I +210 LET X=L(K) +220 GOSUB EVEN +230 IF NOT Y THEN GOTO 260 +240 LET R(K)=0 +250 PRINT AT K-1,16;" " +260 NEXT K +270 LET A=0 +280 FOR K=1 TO I +290 LET A=A+R(K) +300 NEXT K +310 GOTO 380 +320 LET Y=INT (X/2) +330 RETURN +340 LET Y=X*2 +350 RETURN +360 LET Y=X/2=INT (X/2) +370 RETURN +380 PRINT AT I+1,16;A diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-9.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-9.basic new file mode 100644 index 0000000000..2e096710f7 --- /dev/null +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-9.basic @@ -0,0 +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) +END diff --git a/Task/Ethiopian-multiplication/BBC-BASIC/ethiopian-multiplication.bbc b/Task/Ethiopian-multiplication/BBC-BASIC/ethiopian-multiplication.bbc deleted file mode 100644 index 58c6c595f3..0000000000 --- a/Task/Ethiopian-multiplication/BBC-BASIC/ethiopian-multiplication.bbc +++ /dev/null @@ -1,22 +0,0 @@ - x% = 17 - y% = 34 - - REPEAT - IF NOT FNeven(x%) THEN - p% += y% - PRINT x%, y% - ELSE - PRINT x%, " ---" - ENDIF - x% = FNhalve(x%) - y% = FNdouble(y%) - UNTIL x% = 0 - PRINT " " , " ===" - PRINT " " , p% - END - - DEF FNdouble(A%) = A% * 2 - - DEF FNhalve(A%) = A% DIV 2 - - DEF FNeven(A%) = ((A% AND 1) = 0) diff --git a/Task/Ethiopian-multiplication/Batch-File/ethiopian-multiplication.bat b/Task/Ethiopian-multiplication/Batch-File/ethiopian-multiplication.bat new file mode 100644 index 0000000000..9caa635585 --- /dev/null +++ b/Task/Ethiopian-multiplication/Batch-File/ethiopian-multiplication.bat @@ -0,0 +1,78 @@ +@echo off +:: Pick 2 random, non-zero, 2-digit numbers to send to :_main +set /a param1=%random% %% 98 + 1 +set /a param2=%random% %% 98 + 1 +call:_main %param1% %param2% +pause>nul +exit /b + +:: This is the main function that outputs the answer in the form of "%1 * %2 = %answer%" +:_main +setlocal enabledelayedexpansion +set l0=%1 +set r0=%2 +set leftcount=1 +set lefttempcount=0 +set rightcount=1 +set righttempcount=0 + +:: Creates an array ("l[]") with the :_halve function. %l0% is the initial left number parsed +:: This section will loop until the most recent member of "l[]" is equal to 0 +:left +set /a lefttempcount=%leftcount%-1 +if !l%lefttempcount%!==1 goto right +call:_halve !l%lefttempcount%! +set l%leftcount%=%errorlevel% +set /a leftcount+=1 +goto left + +:: Creates an array ("r[]") with the :_double function, %r0% is the initial right number parsed +:: This section will loop until it has the same amount of entries as "l[]" +:right +set /a righttempcount=%rightcount%-1 +if %rightcount%==%leftcount% goto both +call:_double !r%righttempcount%! +set r%rightcount%=%errorlevel% +set /a rightcount+=1 +goto right + +:both +:: Creates an boolean array ("e[]") corresponding with whether or not the respective "l[]" entry is even +for /l %%i in (0,1,%lefttempcount%) do ( + call:_even !l%%i! + set e%%i=!errorlevel! +) + +:: Adds up all entries of "r[]" based on the value of "e[]", respectively +set answer=0 +for /l %%i in (0,1,%lefttempcount%) do ( + if !e%%i!==1 ( + set /a answer+=!r%%i! + :: Everything from this----------------------------- + set iseven%%i=KEEP + ) else ( + set iseven%%i=STRIKE + ) + echo L: !l%%i! R: !r%%i! - !iseven%%i! + :: To this, is for cosmetics and is optional-------- + +) +echo %l0% * %r0% = %answer% +exit /b + +:: These are the three functions being used. The output of these functions are expressed in the errorlevel that they return +:_halve +setlocal +set /a temp=%1/2 +exit /b %temp% + +:_double +setlocal +set /a temp=%1*2 +exit /b %temp% + +:_even +setlocal +set int=%1 +set /a modint=%int% %% 2 +exit /b %modint% diff --git a/Task/Ethiopian-multiplication/Dc/ethiopian-multiplication.dc b/Task/Ethiopian-multiplication/Dc/ethiopian-multiplication.dc new file mode 100644 index 0000000000..d2d18ed417 --- /dev/null +++ b/Task/Ethiopian-multiplication/Dc/ethiopian-multiplication.dc @@ -0,0 +1,30 @@ +0k [ Make sure we're doing integer division ]sx +[ 2 / ] sH [ Define "halve" function in register H ]sx +[ 2 * ] sD [ Define "double" function in register D ]sx +[ 2 % 1 r - ] sE [ Define "even?" function in register E ]sx + +[ Entry into the main Ethiopian multiplication function is register M ]sx +[ Keeps running value for the product in register p ]sx +[ 0 sp lLx lp ] sM + +[ The body of the main loop is in register L ]sx + +[ + sb sa [ First thing we do is cheat and store the parameters in + registers, which is safe because the only recursion is of + the tail variety. This avoids tricky stack + manipulations, which dc doesn't have good support for + (unlike, say, Forth). ]sx + + la lEx sr [ r = even?(a) ]sx + lr 0 =S [ if r = 0 then call s]sx + la lHx d [ a = halve(a)]sx + lb lDx [ b = double(b)]sx + r 0 !=L [ if a !=0 then recurse ] +] sL + +[ Utility macro that just adds the current value of b to the total in p ]sx +[ lp lb + sp ]sS + +[ Demo by multiplying 17 and 34 ]sx +17 34 lMx p diff --git a/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication-1.e b/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication-1.e deleted file mode 100644 index 8a2f1cc43c..0000000000 --- a/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication-1.e +++ /dev/null @@ -1,41 +0,0 @@ -class - ETHIOPIAN_MULTIPLICATION -feature{NONE} - double_int(n: INTEGER): INTEGER - do - Result:= n*2 - end - - halve_int(n: INTEGER) : INTEGER - do - Result:= n//2 - end - - even_int(n: INTEGER): BOOLEAN - do - Result:= n\\2=0 - end -feature - ethiopian_mult(a,b: INTEGER): INTEGER - require - a_positive: a>0 - b_positive: b>0 - local - new_a, new_b: INTEGER - do - new_a:= a - new_b:= b - from - until - new_a<=0 - loop - if even_int(new_a)= FALSE then - Result:= Result+new_b - end - new_a:= halve_int(new_a) - new_b:= double_int(new_b) - end - ensure - Result_correct: Result= a*b - end -end diff --git a/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication-2.e b/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication-2.e deleted file mode 100644 index 35f653935e..0000000000 --- a/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication-2.e +++ /dev/null @@ -1,15 +0,0 @@ -class - APPLICATION -inherit - ARGUMENTS -create - make -feature {NONE} -- Initialization - make - local - do - create mult - io.put_integer ( mult.ethiopian_mult (17,34)) - end - mult: ETHIOPIAN_MULTIPLICATION -end diff --git a/Task/Ethiopian-multiplication/GW-BASIC/ethiopian-multiplication.gw-basic b/Task/Ethiopian-multiplication/GW-BASIC/ethiopian-multiplication.gw-basic deleted file mode 100644 index 509d216c77..0000000000 --- a/Task/Ethiopian-multiplication/GW-BASIC/ethiopian-multiplication.gw-basic +++ /dev/null @@ -1,10 +0,0 @@ -10 DEF FNE(A)=(A+1) MOD 2 -20 DEF FNH(A)=INT(A/2) -30 DEF FND(A)=2*A -40 X=17:Y=34:TOT=0 -50 WHILE X>=1 -60 PRINT X, -70 IF FNE(X)=0 THEN TOT=TOT+Y:PRINT Y ELSE PRINT -80 X=FNH(X):Y=FND(Y) -90 WEND -100 PRINT "=", TOT diff --git a/Task/Ethiopian-multiplication/Haskell/ethiopian-multiplication-1.hs b/Task/Ethiopian-multiplication/Haskell/ethiopian-multiplication-1.hs new file mode 100644 index 0000000000..e8b4edd6af --- /dev/null +++ b/Task/Ethiopian-multiplication/Haskell/ethiopian-multiplication-1.hs @@ -0,0 +1,21 @@ +import Prelude hiding (odd) +import Control.Monad (join) + +halve :: Int -> Int +halve = (`div` 2) + +double :: Int -> Int +double = join (+) + +odd :: Int -> Bool +odd = (== 1) . (`mod` 2) + +ethiopicmult :: Int -> Int -> Int +ethiopicmult a b = + sum $ + map snd $ + filter (odd . fst) $ + zip (takeWhile (>= 1) $ iterate halve a) (iterate double b) + +main :: IO () +main = print $ ethiopicmult 17 34 == 17 * 34 diff --git a/Task/Ethiopian-multiplication/Haskell/ethiopian-multiplication-2.hs b/Task/Ethiopian-multiplication/Haskell/ethiopian-multiplication-2.hs new file mode 100644 index 0000000000..3e0a61076e --- /dev/null +++ b/Task/Ethiopian-multiplication/Haskell/ethiopian-multiplication-2.hs @@ -0,0 +1,25 @@ +import Data.Tuple (swap) +import Data.List (unfoldr) +import Control.Monad (join) + +-- ETHIOPIAN MULTIPLICATION --------------------------------------------------- +ethMult :: Int -> Int -> Int +ethMult n m = + foldr + (\(d, x) a -> + if d > 0 -- Odd ? + then (+) a x + else a) + 0 $ + zip + (unfoldr + (\h -> + if h > 0 + then Just $ swap (quotRem h 2) -- (half, (0|1) remainder) + else Nothing) + n) + (iterate (join (+)) m) -- Iterative duplication ( add to self ) + +-- TEST ----------------------------------------------------------------------- +main :: IO () +main = print $ ethMult 17 34 diff --git a/Task/Ethiopian-multiplication/Haskell/ethiopian-multiplication-3.hs b/Task/Ethiopian-multiplication/Haskell/ethiopian-multiplication-3.hs new file mode 100644 index 0000000000..cc19a92f99 --- /dev/null +++ b/Task/Ethiopian-multiplication/Haskell/ethiopian-multiplication-3.hs @@ -0,0 +1,35 @@ +import Data.Monoid (mempty, (<>), getSum, getProduct) +import Control.Monad (join) +import Data.List (unfoldr) +import Data.Tuple (swap) + +-- ETHIOPIAN MULTIPLICATION --------------------------------------------------- +ethMult + :: (Monoid m) + => Int -> m -> m +ethMult n m = + foldr + (\(d, x) a -> + case d of + 0 -> a + _ -> a <> x) + mempty $ + zip + (unfoldr + (\h -> + case h of + 0 -> Nothing + _ -> Just . swap $ quotRem h 2) + n) + (iterate (join (<>)) m) + +-- TEST ----------------------------------------------------------------------- +main :: IO () +main = do + mapM_ print $ + [ getSum $ ethMult 17 34 -- 34 * 17 + , getProduct $ ethMult 3 34 -- 34 ^ 3 + ] <> + (getProduct <$> ([ethMult 17] <*> [3, 4])) -- [3 ^ 17, 4 ^ 17] + print $ ethMult 17 "34" + print $ ethMult 17 [3, 4] diff --git a/Task/Ethiopian-multiplication/Haskell/ethiopian-multiplication.hs b/Task/Ethiopian-multiplication/Haskell/ethiopian-multiplication.hs deleted file mode 100644 index c941f9b00d..0000000000 --- a/Task/Ethiopian-multiplication/Haskell/ethiopian-multiplication.hs +++ /dev/null @@ -1,15 +0,0 @@ -import Prelude hiding (odd) - -halve, double :: Integral a => a -> a -halve = (`div` 2) -double = (2 *) - -odd :: Integral a => a -> Bool -odd = (== 1) . (`mod` 2) - -ethiopicmult :: Integral a => a -> a -> a -ethiopicmult a b = sum $ map snd $ filter (odd . fst) $ zip - (takeWhile (>= 1) $ iterate halve a) - (iterate double b) - -main = print $ ethiopicmult 17 34 == 17 * 34 diff --git a/Task/Ethiopian-multiplication/J/ethiopian-multiplication-5.j b/Task/Ethiopian-multiplication/J/ethiopian-multiplication-5.j deleted file mode 100644 index 4c0275e7be..0000000000 --- a/Task/Ethiopian-multiplication/J/ethiopian-multiplication-5.j +++ /dev/null @@ -1 +0,0 @@ -ethio=: *@] -@]^:(0 > [) (ethiop |) diff --git a/Task/Ethiopian-multiplication/J/ethiopian-multiplication-6.j b/Task/Ethiopian-multiplication/J/ethiopian-multiplication-6.j deleted file mode 100644 index ac489587c8..0000000000 --- a/Task/Ethiopian-multiplication/J/ethiopian-multiplication-6.j +++ /dev/null @@ -1,8 +0,0 @@ - 7 ethio 11 -77 - 7 ethio _11 -_77 - _7 ethio 11 -_77 - _7 ethio _11 -77 diff --git a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-5.julia b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-5.julia deleted file mode 100644 index 1ea4761dee..0000000000 --- a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-5.julia +++ /dev/null @@ -1 +0,0 @@ -def pairs: while( .[0] > 0; [ (.[0] | halve), (.[1] | double) ]); diff --git a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-6.julia b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-6.julia deleted file mode 100644 index 8cef496ce6..0000000000 --- a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-6.julia +++ /dev/null @@ -1,15 +0,0 @@ -def halve: (./2) | floor; - -def double: 2 * .; - -def isEven: . % 2 == 0; - -def ethiopian_multiply(a;b): - def pairs: recurse( if .[0] > 0 - then [ (.[0] | halve), (.[1] | double) ] - else empty - end ); - reduce ([a,b] | pairs - | select( .[0] | isEven | not) - | .[1] ) as $i - (0; . + $i) ; diff --git a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-7.julia b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-7.julia deleted file mode 100644 index e89ad806a5..0000000000 --- a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-7.julia +++ /dev/null @@ -1 +0,0 @@ -ethiopian_multiply(17;34) # => 578 diff --git a/Task/Ethiopian-multiplication/Kotlin/ethiopian-multiplication.kotlin b/Task/Ethiopian-multiplication/Kotlin/ethiopian-multiplication.kotlin new file mode 100644 index 0000000000..ae887b5b82 --- /dev/null +++ b/Task/Ethiopian-multiplication/Kotlin/ethiopian-multiplication.kotlin @@ -0,0 +1,24 @@ +// version 1.1.2 + +fun halve(n: Int) = n / 2 + +fun double(n: Int) = n * 2 + +fun isEven(n: Int) = n % 2 == 0 + +fun ethiopianMultiply(x: Int, y: Int): Int { + var xx = x + var yy = y + var sum = 0 + while (xx >= 1) { + if (!isEven(xx)) sum += yy + xx = halve(xx) + yy = double(yy) + } + return sum +} + +fun main(args: Array) { + println("17 x 34 = ${ethiopianMultiply(17, 34)}") + println("99 x 99 = ${ethiopianMultiply(99, 99)}") +} diff --git a/Task/Ethiopian-multiplication/Liberty-BASIC/ethiopian-multiplication.liberty b/Task/Ethiopian-multiplication/Liberty-BASIC/ethiopian-multiplication.liberty deleted file mode 100644 index 0330729a24..0000000000 --- a/Task/Ethiopian-multiplication/Liberty-BASIC/ethiopian-multiplication.liberty +++ /dev/null @@ -1,29 +0,0 @@ -x = 17 -y = 34 -msg$ = str$(x) + " * " + str$(y) + " = " -Print str$(x) + " " + str$(y) -'In this routine we will not worry about discarding the right hand value whos left hand partner is even; -'we will just not add it to our product. -Do Until x < 2 - If Not(isEven(x)) Then - product = (product + y) - End If - x = halveInt(x) - y = doubleInt(y) - Print str$(x) + " " + str$(y) -Loop -product = (product + y) -If (x < 0) Then product = (product * -1) -Print msg$ + str$(product) - -Function isEven(num) - isEven = Abs(Not(num Mod 2)) -End Function - -Function halveInt(num) - halveInt = Int(num/ 2) -End Function - -Function doubleInt(num) - doubleInt = (num * 2) -End Function diff --git a/Task/Ethiopian-multiplication/Object-Pascal/ethiopian-multiplication-3.object b/Task/Ethiopian-multiplication/Object-Pascal/ethiopian-multiplication-3.object deleted file mode 100644 index 7813ae1599..0000000000 --- a/Task/Ethiopian-multiplication/Object-Pascal/ethiopian-multiplication-3.object +++ /dev/null @@ -1 +0,0 @@ -17 * 34 = 578 diff --git a/Task/Ethiopian-multiplication/Ol/ethiopian-multiplication.ol b/Task/Ethiopian-multiplication/Ol/ethiopian-multiplication.ol new file mode 100644 index 0000000000..b1817c74c0 --- /dev/null +++ b/Task/Ethiopian-multiplication/Ol/ethiopian-multiplication.ol @@ -0,0 +1,13 @@ +(define (ethiopian-multiplication l r) + (let ((even? (lambda (n) + (eq? (mod n 2) 0)))) + + (let loop ((sum 0) (l l) (r r)) + (print "sum: " sum ", l: " l ", r: " r) + (if (eq? l 0) + sum + (loop + (if (even? l) (+ sum r) sum) + (floor (/ l 2)) (* r 2)))))) + +(print (ethiopian-multiplication 17 34)) diff --git a/Task/Ethiopian-multiplication/PureBasic/ethiopian-multiplication-1.purebasic b/Task/Ethiopian-multiplication/PureBasic/ethiopian-multiplication-1.purebasic deleted file mode 100644 index d7e6262e40..0000000000 --- a/Task/Ethiopian-multiplication/PureBasic/ethiopian-multiplication-1.purebasic +++ /dev/null @@ -1,33 +0,0 @@ -Procedure isEven(x) - ProcedureReturn (x & 1) ! 1 -EndProcedure - -Procedure halveValue(x) - ProcedureReturn x / 2 -EndProcedure - -Procedure doubleValue(x) - ProcedureReturn x << 1 -EndProcedure - -Procedure EthiopianMultiply(x, y) - Protected sum - Print("Ethiopian multiplication of " + Str(x) + " and " + Str(y) + " ... ") - Repeat - If Not isEven(x) - sum + y - EndIf - x = halveValue(x) - y = doubleValue(y) - Until x < 1 - PrintN(" equals " + Str(sum)) - ProcedureReturn sum -EndProcedure - -If OpenConsole() - EthiopianMultiply(17,34) - - Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") - Input() - CloseConsole() -EndIf diff --git a/Task/Ethiopian-multiplication/PureBasic/ethiopian-multiplication-2.purebasic b/Task/Ethiopian-multiplication/PureBasic/ethiopian-multiplication-2.purebasic deleted file mode 100644 index 91695fb6bf..0000000000 --- a/Task/Ethiopian-multiplication/PureBasic/ethiopian-multiplication-2.purebasic +++ /dev/null @@ -1,38 +0,0 @@ -Procedure isEven(x) - ProcedureReturn (x & 1) ! 1 -EndProcedure - -Procedure halveValue(x) - ProcedureReturn x / 2 -EndProcedure - -Procedure doubleValue(x) - ProcedureReturn x << 1 -EndProcedure - -Procedure EthiopianMultiply(x, y) - Protected sum, sign = x - - Print("Ethiopian multiplication of " + Str(x) + " and " + Str(y) + " ...") - Repeat - If Not isEven(x) - sum + y - EndIf - x = halveValue(x) - y = doubleValue(y) - Until x = 0 - If sign < 0 : sum * -1: EndIf - - PrintN(" equals " + Str(sum)) - ProcedureReturn sum -EndProcedure - -If OpenConsole() - EthiopianMultiply(17,34) - EthiopianMultiply(-17,34) - EthiopianMultiply(-17,-34) - - Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") - Input() - CloseConsole() -EndIf diff --git a/Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-3.vb b/Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-3.vb deleted file mode 100644 index f61b514d2e..0000000000 --- a/Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-3.vb +++ /dev/null @@ -1 +0,0 @@ -578 diff --git a/Task/Ethiopian-multiplication/X86-Assembly/ethiopian-multiplication-1.x86 b/Task/Ethiopian-multiplication/X86-Assembly/ethiopian-multiplication-1.x86 new file mode 100644 index 0000000000..3d078eced9 --- /dev/null +++ b/Task/Ethiopian-multiplication/X86-Assembly/ethiopian-multiplication-1.x86 @@ -0,0 +1,109 @@ + extern printf + global main + + section .text + +halve + shr ebx, 1 + ret + +double + shl ebx, 1 + ret + +iseven + 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 eax ; result of 17*34 + push fmt + call printf + add esp, 8 + + 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 +.notut0 + + 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 +.notut1 + 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, edx ; plicand <<= 1 + call double + mov edx, ebx + + jmp .whileloop +.multend + leave + ret + + +tutorme + 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 + + section .data + +fmt + db "%d", 10, 0 +preamblefmt + db "ethiopic multiplication of %d and %d", 10, 0 +tutorfmt + db "%4d %6d %s", 10, 0 +strucktxt + db "struck", 0 +kepttxt + db "kept", 0 diff --git a/Task/Ethiopian-multiplication/X86-Assembly/ethiopian-multiplication-2.x86 b/Task/Ethiopian-multiplication/X86-Assembly/ethiopian-multiplication-2.x86 new file mode 100644 index 0000000000..4088d2c00e --- /dev/null +++ b/Task/Ethiopian-multiplication/X86-Assembly/ethiopian-multiplication-2.x86 @@ -0,0 +1,4 @@ +test,01 +jz Even +Odd: +Even: diff --git a/Task/Ethiopian-multiplication/X86-Assembly/ethiopian-multiplication-3.x86 b/Task/Ethiopian-multiplication/X86-Assembly/ethiopian-multiplication-3.x86 new file mode 100644 index 0000000000..c71b05aed3 --- /dev/null +++ b/Task/Ethiopian-multiplication/X86-Assembly/ethiopian-multiplication-3.x86 @@ -0,0 +1,29 @@ +;calling program + + 1BDC:0100 6A11 PUSH 11 ;17 Put operands on the stack + 1BDC:0102 6A22 PUSH 22 ;34 + 1BDC:0104 E80900 CALL 0110 ; call the mulitplcation routine +;putting some space in, (not needed) + 1BDC:0107 90 NOP + 1BDC:0108 90 NOP + 1BDC:0109 90 NOP + 1BDC:010A 90 NOP + 1BDC:010B 90 NOP + 1BDC:010C 90 NOP + 1BDC:010D 90 NOP + 1BDC:010E 90 NOP + 1BDC:010F 90 NOP +;mulitplication routine starts here + 1BDC:0110 89E5 MOV BP,SP ; prepare to get operands off stack + 1BDC:0112 8B4E02 MOV CX,[BP+02] ; Get the first operand + 1BDC:0115 8B5E04 MOV BX,[BP+04] ; get the second oerand + 1BDC:0118 31C0 XOR AX,AX ; zero out the result + 1BDC:011A F7C10100 TEST CX,0001 ; are we odd + 1BDC:011E 7402 JZ 0122 ; no skip the next instruction + 1BDC:0120 01D8 ADD AX,BX ; we are odd so add to the result + 1BDC:0122 D1E3 SHL BX,1 ; multiply by 2 + 1BDC:0124 D1E9 SHR CX,1 ; divide by 2 (if zr flag is set, we are done) + 1BDC:0126 75F2 JNZ 011A ; cx not 0, go back and do it again + 1BDC:0128 C3 RET ; return with the result in AX + +;pretty small, just 24 bytes diff --git a/Task/Ethiopian-multiplication/Zkl/ethiopian-multiplication-1.zkl b/Task/Ethiopian-multiplication/Zkl/ethiopian-multiplication-1.zkl new file mode 100644 index 0000000000..a75023c7ea --- /dev/null +++ b/Task/Ethiopian-multiplication/Zkl/ethiopian-multiplication-1.zkl @@ -0,0 +1,8 @@ +fcn ethiopianMultiply(l,r){ // l is a non-negative integer + halve :=fcn(n){ n/2 }; + double :=fcn(n){ n+n }; + lr:=List(T(l,r)); // ( (l,r) .. (1,r*n) ) + while(l>1){ lr.write( T(l=halve(l),r=double(r)) ) } + lr.filter(fcn([(l,r)]){ (not l.isEven) }); // strike out even left rows + .reduce(fcn(sum,[(l,r)]){ sum + r },0); // sum right column +} diff --git a/Task/Ethiopian-multiplication/Zkl/ethiopian-multiplication-2.zkl b/Task/Ethiopian-multiplication/Zkl/ethiopian-multiplication-2.zkl new file mode 100644 index 0000000000..ccd084685d --- /dev/null +++ b/Task/Ethiopian-multiplication/Zkl/ethiopian-multiplication-2.zkl @@ -0,0 +1,3 @@ +foreach l,r in ( T(T(17,34),T(34,1),T(34,2),T(34,0)) ){ + println(ethiopianMultiply(l,r)," ",ethiopianMultiply(r,l)); +} diff --git a/Task/Euler-method/BBC-BASIC/euler-method.bbc b/Task/Euler-method/BBC-BASIC/euler-method.bbc deleted file mode 100644 index 432f76c6ac..0000000000 --- a/Task/Euler-method/BBC-BASIC/euler-method.bbc +++ /dev/null @@ -1,15 +0,0 @@ - PROCeuler("-0.07*(y-20)", 100, 0, 100, 2) - PROCeuler("-0.07*(y-20)", 100, 0, 100, 5) - PROCeuler("-0.07*(y-20)", 100, 0, 100, 10) - END - - DEF PROCeuler(df$, y, a, b, s) - LOCAL t, @% - @% = &2030A - t = a - WHILE t <= b - PRINT t, y - y += s * EVAL(df$) - t += s - ENDWHILE - ENDPROC diff --git a/Task/Euler-method/Futhark/euler-method.futhark b/Task/Euler-method/Futhark/euler-method.futhark index b98c34cd0a..7b8f0b6d2d 100644 --- a/Task/Euler-method/Futhark/euler-method.futhark +++ b/Task/Euler-method/Futhark/euler-method.futhark @@ -1,15 +1,17 @@ +import "futlib/math" + fun analytic(t0: f64) (time: f64): f64 = - 20.0 + (t0 - 20.0) * exp64(-0.07*time) + 20.0 + (t0 - 20.0) * f64.exp(-0.07*time) fun cooling(_time: f64) (temperature: f64): f64 = -0.07 * (temperature-20.0) fun main(t0: f64) (a: f64) (b: f64) (h: f64): []f64 = - let steps = int((b-a)/h) + let steps = i32((b-a)/h) let temps = replicate steps 0.0 loop ((t,temps)=(t0,temps)) = for i < steps do let x = a + f64(i) * h - let temps[i] = abs(t-analytic t0 x) + let temps[i] = f64.abs(t-analytic t0 x) in (t + h * cooling x t, temps) in temps diff --git a/Task/Euler-method/jq/euler-method-1.jq b/Task/Euler-method/Jq/euler-method-1.jq similarity index 100% rename from Task/Euler-method/jq/euler-method-1.jq rename to Task/Euler-method/Jq/euler-method-1.jq diff --git a/Task/Euler-method/jq/euler-method-2.jq b/Task/Euler-method/Jq/euler-method-2.jq similarity index 100% rename from Task/Euler-method/jq/euler-method-2.jq rename to Task/Euler-method/Jq/euler-method-2.jq diff --git a/Task/Euler-method/jq/euler-method-3.jq b/Task/Euler-method/Jq/euler-method-3.jq similarity index 100% rename from Task/Euler-method/jq/euler-method-3.jq rename to Task/Euler-method/Jq/euler-method-3.jq diff --git a/Task/Euler-method/jq/euler-method-4.jq b/Task/Euler-method/Jq/euler-method-4.jq similarity index 100% rename from Task/Euler-method/jq/euler-method-4.jq rename to Task/Euler-method/Jq/euler-method-4.jq diff --git a/Task/Euler-method/Kotlin/euler-method.kotlin b/Task/Euler-method/Kotlin/euler-method.kotlin new file mode 100644 index 0000000000..95750efd91 --- /dev/null +++ b/Task/Euler-method/Kotlin/euler-method.kotlin @@ -0,0 +1,32 @@ +// version 1.1.2 + +typealias Deriv = (Double) -> Double // only one parameter needed here + +const val FMT = " %7.3f" + +fun euler(f: Deriv, y: Double, step: Int, end: Int) { + var yy = y + print(" Step %2d: ".format(step)) + for (t in 0..end step step) { + if (t % 10 == 0) print(FMT.format(yy)) + yy += step * f(yy) + } + println() +} + +fun analytic() { + print(" Time: ") + for (t in 0..100 step 10) print(" %7d".format(t)) + print("\nAnalytic: ") + for (t in 0..100 step 10) + print(FMT.format(20.0 + 80.0 * Math.exp(-0.07 * t))) + println() +} + +fun cooling(temp: Double) = -0.07 * (temp - 20.0) + +fun main(args: Array) { + analytic() + for (i in listOf(2, 5, 10)) + euler(::cooling, 100.0, i, 100) +} diff --git a/Task/Euler-method/Run-BASIC/euler-method.run b/Task/Euler-method/Run-BASIC/euler-method.run deleted file mode 100644 index 6cffaf383f..0000000000 --- a/Task/Euler-method/Run-BASIC/euler-method.run +++ /dev/null @@ -1,14 +0,0 @@ -x = euler(-0.07,-20, 100, 0, 100, 2) -x = euler-0.07,-20, 100, 0, 100, 5) -x = euler(-0.07,-20, 100, 0, 100, 10) -end - -FUNCTION euler(da,db, y, a, b, s) -print "===== da:";da;" db:";db;" y:";y;" a:";a;" b:";b;" s:";s;" ===================" -t = a -WHILE t <= b - PRINT t;chr$(9);y - y = y + s * (da * (y + db)) - t = t + s -WEND -END FUNCTION diff --git a/Task/Euler-method/Zkl/euler-method.zkl b/Task/Euler-method/Zkl/euler-method.zkl new file mode 100644 index 0000000000..648ed78bc4 --- /dev/null +++ b/Task/Euler-method/Zkl/euler-method.zkl @@ -0,0 +1,25 @@ +const FMT=" %7.3f"; + +fcn ivp_euler(f,y,step,end_t){ + print(" Step %2d: ".fmt(step)); + foreach t in ([0..end_t,step]){ + if (t % 10 == 0) print(FMT.fmt(y)); + y += f(t,y) * step; + } + println(); +} + +fcn analytic{ + print(" Time: "); + foreach t in ([0..100,10]){ print(" %7g".fmt(t)) } + print("\nAnalytic: "); + foreach t in ([0..100,10]){ print(FMT.fmt(20.0 + 80.0 * (-0.07 * t).exp())) } + println(); +} + +fcn cooling(_,temp){ return(-0.07 * (temp - 20)) } + +analytic(); +ivp_euler(cooling, 100.0, 2, 100); +ivp_euler(cooling, 100.0, 5, 100); +ivp_euler(cooling, 100.0, 10, 100); diff --git a/Task/Evaluate-binomial-coefficients/AWK/evaluate-binomial-coefficients.awk b/Task/Evaluate-binomial-coefficients/AWK/evaluate-binomial-coefficients.awk new file mode 100644 index 0000000000..ff89b0d475 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/AWK/evaluate-binomial-coefficients.awk @@ -0,0 +1,14 @@ +# syntax: GAWK -f EVALUATE_BINOMIAL_COEFFICIENTS.AWK +BEGIN { + main(5,3) + main(100,2) + main(33,17) + exit(0) +} +function main(n,k, i,r) { + r = 1 + for (i=1; i -#include - -typedef unsigned long ULONG; - -ULONG binomial(ULONG n, ULONG k) -{ - ULONG r = 1, d = n - k; - - /* choose the smaller of k and n - k */ - if (d > k) { k = d; d = n - k; } - - while (n > k) { - if (r >= UINT_MAX / n) return 0; /* overflown */ - r *= n--; - - /* divide (n - k)! as soon as we can to delay overflows */ - while (d > 1 && !(r % d)) r /= d--; - } - return r; -} - -int main() -{ - printf("%lu\n", binomial(5, 3)); - return 0; -} diff --git a/Task/Evaluate-binomial-coefficients/C/evaluate-binomial-coefficients-2.c b/Task/Evaluate-binomial-coefficients/C/evaluate-binomial-coefficients-2.c deleted file mode 100644 index f599e28b8a..0000000000 --- a/Task/Evaluate-binomial-coefficients/C/evaluate-binomial-coefficients-2.c +++ /dev/null @@ -1 +0,0 @@ -10 diff --git a/Task/Evaluate-binomial-coefficients/CoffeeScript/evaluate-binomial-coefficients-1.coffee b/Task/Evaluate-binomial-coefficients/CoffeeScript/evaluate-binomial-coefficients-1.coffee deleted file mode 100644 index 025c550049..0000000000 --- a/Task/Evaluate-binomial-coefficients/CoffeeScript/evaluate-binomial-coefficients-1.coffee +++ /dev/null @@ -1,9 +0,0 @@ -binomial_coefficient = (n, k) -> - result = 1 - for i in [0...k] - result *= (n - i) / (i + 1) - result - -n = 5 -for k in [0..n] - console.log "binomial_coefficient(#{n}, #{k}) = #{binomial_coefficient(n,k)}" diff --git a/Task/Evaluate-binomial-coefficients/CoffeeScript/evaluate-binomial-coefficients-2.coffee b/Task/Evaluate-binomial-coefficients/CoffeeScript/evaluate-binomial-coefficients-2.coffee deleted file mode 100644 index 7e836aac52..0000000000 --- a/Task/Evaluate-binomial-coefficients/CoffeeScript/evaluate-binomial-coefficients-2.coffee +++ /dev/null @@ -1,7 +0,0 @@ -> coffee binomial.coffee -binomial_coefficient(5, 0) = 1 -binomial_coefficient(5, 1) = 5 -binomial_coefficient(5, 2) = 10 -binomial_coefficient(5, 3) = 10 -binomial_coefficient(5, 4) = 5 -binomial_coefficient(5, 5) = 1 diff --git a/Task/Evaluate-binomial-coefficients/Dc/evaluate-binomial-coefficients-1.dc b/Task/Evaluate-binomial-coefficients/Dc/evaluate-binomial-coefficients-1.dc new file mode 100644 index 0000000000..6702780b4b --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Dc/evaluate-binomial-coefficients-1.dc @@ -0,0 +1 @@ +[sx1q]sz[d0=zd1-lfx*]sf[skdlfxrlk-lfxlklfx*/]sb diff --git a/Task/Evaluate-binomial-coefficients/Dc/evaluate-binomial-coefficients-2.dc b/Task/Evaluate-binomial-coefficients/Dc/evaluate-binomial-coefficients-2.dc new file mode 100644 index 0000000000..35f7cbac91 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Dc/evaluate-binomial-coefficients-2.dc @@ -0,0 +1 @@ +5 3lbxp diff --git a/Task/Evaluate-binomial-coefficients/Dc/evaluate-binomial-coefficients-3.dc b/Task/Evaluate-binomial-coefficients/Dc/evaluate-binomial-coefficients-3.dc new file mode 100644 index 0000000000..b3bb0ec7ca --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Dc/evaluate-binomial-coefficients-3.dc @@ -0,0 +1,31 @@ +[ macro z: factorial base case when n is (z)ero ]sx +[sx [ x is our dump register; get rid of extraneous copy of n we no longer need]sx + 1 [ return value is 1 ]sx + q] [ abort processing of calling macro ]sx +sz + +[ macro f: factorial ]sx [ + d [ duplicate the input (n) ]sx + 0 =z [ if n is zero, call z, which stops here and returns 1 ]sx + d [ otherwise, duplicate n again ]sx + 1 - [ subtract 1 ]sx + lfx [ take the factorial ]sx + * [ we have (n-1)!; multiply it by the copy of n to get n! ]sx +] sf + +[ macro b(n,k): binomial function (n choose k). + straightforward RPN version of formula.]sx [ + sk [ remember k. stack: n ]sx + d [ duplicate: n n ]sx + lfx [ call factorial: n n! ]sx + r [ swap: n! n ]sx + lk [ load k: n! n k ]sx + - [ subtract: n! n-k ]sx + lfx [ call factorial: n! (n-k)! ]sx + lk [ load k: n! (n-k)! k ]sx + lfx [ call factorial; n! (n-k)! k! ]sx + * [ multiply: n! (n-k)!k! ]sx + / [ divide: n!/(n-k)!k! ]sx +] sb + +5 3 lb x p [print(5 choose 3)]sx diff --git a/Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients-1.f b/Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients-1.f deleted file mode 100644 index de43ce23b8..0000000000 --- a/Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients-1.f +++ /dev/null @@ -1,31 +0,0 @@ -program test_choose - - implicit none - - write (*, '(i0)') choose (5, 3) - -contains - - function factorial (n) result (res) - - implicit none - integer, intent (in) :: n - integer :: res - integer :: i - - res = product ((/(i, i = 1, n)/)) - - end function factorial - - function choose (n, k) result (res) - - implicit none - integer, intent (in) :: n - integer, intent (in) :: k - integer :: res - - res = factorial (n) / (factorial (k) * factorial (n - k)) - - end function choose - -end program test_choose diff --git a/Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients-2.f b/Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients-2.f deleted file mode 100644 index f599e28b8a..0000000000 --- a/Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients-2.f +++ /dev/null @@ -1 +0,0 @@ -10 diff --git a/Task/Evaluate-binomial-coefficients/jq/evaluate-binomial-coefficients.jq b/Task/Evaluate-binomial-coefficients/Jq/evaluate-binomial-coefficients.jq similarity index 100% rename from Task/Evaluate-binomial-coefficients/jq/evaluate-binomial-coefficients.jq rename to Task/Evaluate-binomial-coefficients/Jq/evaluate-binomial-coefficients.jq diff --git a/Task/Evaluate-binomial-coefficients/Kotlin/evaluate-binomial-coefficients.kotlin b/Task/Evaluate-binomial-coefficients/Kotlin/evaluate-binomial-coefficients.kotlin new file mode 100644 index 0000000000..00bc97b3a9 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Kotlin/evaluate-binomial-coefficients.kotlin @@ -0,0 +1,28 @@ +// version 1.0.5-2 + +fun factorial(n: Int) = when { + n < 0 -> throw IllegalArgumentException("negative numbers not allowed") + else -> { + var ans = 1L + for (i in 2..n) ans *= i + ans + } +} + +fun binomial(n: Int, k: Int) = when { + n < 0 || k < 0 -> throw IllegalArgumentException("negative numbers not allowed") + n == k -> 1L + else -> { + var ans = 1L + for (i in n - k + 1..n) ans *= i + ans / factorial(k) + } +} + +fun main(args: Array) { + for (n in 0..14) { + for (k in 0..n) + print("%4d ".format(binomial(n, k))) + println() + } +} diff --git a/Task/Evaluate-binomial-coefficients/Lua/evaluate-binomial-coefficients.lua b/Task/Evaluate-binomial-coefficients/Lua/evaluate-binomial-coefficients-1.lua similarity index 100% rename from Task/Evaluate-binomial-coefficients/Lua/evaluate-binomial-coefficients.lua rename to Task/Evaluate-binomial-coefficients/Lua/evaluate-binomial-coefficients-1.lua diff --git a/Task/Evaluate-binomial-coefficients/Lua/evaluate-binomial-coefficients-2.lua b/Task/Evaluate-binomial-coefficients/Lua/evaluate-binomial-coefficients-2.lua new file mode 100644 index 0000000000..09d4b6b263 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Lua/evaluate-binomial-coefficients-2.lua @@ -0,0 +1,30 @@ +local Binomial = setmetatable({},{ + __call = function(self,n,k) + local hash = (n<<32) | (k & 0xffffffff) + local ans = self[hash] + if not ans then + if n<0 or k>n then + return 0 -- not save + elseif n<=1 or k==0 or k==n then + ans = 1 + else + if 2*k > n then + ans = self(n, n - k) + else + local lhs = self(n-1,k) + local rhs = self(n-1,k-1) + local sum = lhs + rhs + if sum<0 or not math.tointeger(sum)then + -- switch to double + ans = lhs/1.0 + rhs/1.0 -- approximate + else + ans = sum + end + end + end + rawset(self,hash,ans) + end + return ans + end +}) +print( Binomial(100,50)) -- 1.0089134454556e+029 diff --git a/Task/Evaluate-binomial-coefficients/PL-I/evaluate-binomial-coefficients-1.pli b/Task/Evaluate-binomial-coefficients/PL-I/evaluate-binomial-coefficients-1.pli deleted file mode 100644 index 915ada747d..0000000000 --- a/Task/Evaluate-binomial-coefficients/PL-I/evaluate-binomial-coefficients-1.pli +++ /dev/null @@ -1,22 +0,0 @@ -binomial_coefficients: - procedure options (main); - declare (n, k) fixed; - - get (n, k); - put (coefficient(n, k)); - -coefficient: procedure (n, k) returns (fixed decimal (15)); - declare (n, k) fixed; - return (fact(n)/ (fact(n-k) * fact(k)) ); -end coefficient; - -fact: procedure (n) returns (fixed decimal (15)); - declare n fixed; - declare i fixed, f fixed decimal (15); - f = 1; - do i = 1 to n; - f = f * i; - end; - return (f); -end fact; -end binomial_coefficients; diff --git a/Task/Evaluate-binomial-coefficients/PL-I/evaluate-binomial-coefficients-2.pli b/Task/Evaluate-binomial-coefficients/PL-I/evaluate-binomial-coefficients-2.pli deleted file mode 100644 index ae5e04d5dc..0000000000 --- a/Task/Evaluate-binomial-coefficients/PL-I/evaluate-binomial-coefficients-2.pli +++ /dev/null @@ -1 +0,0 @@ - 10 diff --git a/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-1.phix b/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-1.phix new file mode 100644 index 0000000000..6a4fe30249 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-1.phix @@ -0,0 +1,5 @@ +function binom(integer n, k) + return factorial(n)/(factorial(k)*factorial(n-k)) +end function + +?binom(5,3) diff --git a/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-2.phix b/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-2.phix new file mode 100644 index 0000000000..0da8f2433b --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-2.phix @@ -0,0 +1,14 @@ +include builtins\bigatom.e + +function ba_binom(integer n, k) +bigatom r = ba_new(1) + for i=1 to k do + r = ba_divide(ba_multiply(r,n-i+1),i) + end for + return r +end function + +?ba_sprintf("%B",ba_binom(5,3)) +?ba_sprintf("%B",ba_binom(100,50)) +?ba_sprintf("%B",ba_binom(60,30)) +?ba_sprintf("%B",ba_binom(1200,120)) diff --git a/Task/Evaluate-binomial-coefficients/R/evaluate-binomial-coefficients-1.r b/Task/Evaluate-binomial-coefficients/R/evaluate-binomial-coefficients-1.r deleted file mode 100644 index 77351d6616..0000000000 --- a/Task/Evaluate-binomial-coefficients/R/evaluate-binomial-coefficients-1.r +++ /dev/null @@ -1 +0,0 @@ -choose(5,3) diff --git a/Task/Evaluate-binomial-coefficients/R/evaluate-binomial-coefficients-2.r b/Task/Evaluate-binomial-coefficients/R/evaluate-binomial-coefficients-2.r deleted file mode 100644 index 715a58cc3b..0000000000 --- a/Task/Evaluate-binomial-coefficients/R/evaluate-binomial-coefficients-2.r +++ /dev/null @@ -1 +0,0 @@ -[1] 10 diff --git a/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-4.scala b/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-4.scala deleted file mode 100644 index 28da26ccbf..0000000000 --- a/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-4.scala +++ /dev/null @@ -1,2 +0,0 @@ -java Binomial 100 30 -The Binomial Coefficient of 100 and 30 equals 29,372,339,821,610,944,823,963,760. diff --git a/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-5.scala b/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-5.scala deleted file mode 100644 index 7d60043fd9..0000000000 --- a/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-5.scala +++ /dev/null @@ -1,6 +0,0 @@ - def bico(n: Long, k: Long): Long = (n, k) match { - case (n, 0) => 1 - case (0, k) => 0 - case (n, k) => bico(n - 1, k - 1) + bico(n - 1, k) - } - println("bico(5,3) = " + bico(5, 3)) diff --git a/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-6.scala b/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-6.scala deleted file mode 100644 index 3cdcdec3e1..0000000000 --- a/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-6.scala +++ /dev/null @@ -1 +0,0 @@ -bico(5,3) = 10 diff --git a/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-1.ss b/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-1.ss deleted file mode 100644 index 7cb1067ef0..0000000000 --- a/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-1.ss +++ /dev/null @@ -1,12 +0,0 @@ -(define (factorial n) - (define (*factorial n acc) - (if (zero? n) - acc - (*factorial (- n 1) (* acc n)))) - (*factorial n 1)) - -(define (choose n k) - (/ (factorial n) (* (factorial k) (factorial (- n k))))) - -(display (choose 5 3)) -(newline) diff --git a/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-2.ss b/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-2.ss deleted file mode 100644 index f599e28b8a..0000000000 --- a/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-2.ss +++ /dev/null @@ -1 +0,0 @@ -10 diff --git a/Task/Evaluate-binomial-coefficients/SequenceL/evaluate-binomial-coefficients-1.sequencel b/Task/Evaluate-binomial-coefficients/SequenceL/evaluate-binomial-coefficients-1.sequencel new file mode 100644 index 0000000000..f6e8767076 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/SequenceL/evaluate-binomial-coefficients-1.sequencel @@ -0,0 +1 @@ +choose(n, k) := product(k + 1 ... n) / product(1 ... n - k); diff --git a/Task/Evaluate-binomial-coefficients/SequenceL/evaluate-binomial-coefficients-2.sequencel b/Task/Evaluate-binomial-coefficients/SequenceL/evaluate-binomial-coefficients-2.sequencel new file mode 100644 index 0000000000..b67c79b4b4 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/SequenceL/evaluate-binomial-coefficients-2.sequencel @@ -0,0 +1,5 @@ +choose(n,k) := binomial(n, k, 1, 1); + +binomial(n, k, i, result) := + result when i > k else + binomial(n, k, i + 1, (result * (n - i + 1)) / i); diff --git a/Task/Evaluate-binomial-coefficients/Stata/evaluate-binomial-coefficients.stata b/Task/Evaluate-binomial-coefficients/Stata/evaluate-binomial-coefficients.stata new file mode 100644 index 0000000000..7be9bfdee4 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Stata/evaluate-binomial-coefficients.stata @@ -0,0 +1,2 @@ +. display comb(5,3) +10 diff --git a/Task/Evaluate-binomial-coefficients/Zkl/evaluate-binomial-coefficients.zkl b/Task/Evaluate-binomial-coefficients/Zkl/evaluate-binomial-coefficients.zkl new file mode 100644 index 0000000000..4ecf233677 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Zkl/evaluate-binomial-coefficients.zkl @@ -0,0 +1 @@ +fcn binomial(n,k){ (1).reduce(k,fcn(p,i,n){ p*(n-i+1)/i },1,n) } diff --git a/Task/Even-or-odd/AppleScript/even-or-odd-1.applescript b/Task/Even-or-odd/AppleScript/even-or-odd-1.applescript new file mode 100644 index 0000000000..29e0e5b314 --- /dev/null +++ b/Task/Even-or-odd/AppleScript/even-or-odd-1.applescript @@ -0,0 +1,8 @@ +set nList to {3, 2, 1, 0, -1, -2, -3} +repeat with n in nList + if (n / 2) = n / 2 as integer then + log "Value " & n & " is even." + else + log "Value " & n & " is odd." + end if +end repeat diff --git a/Task/Even-or-odd/AppleScript/even-or-odd-2.applescript b/Task/Even-or-odd/AppleScript/even-or-odd-2.applescript new file mode 100644 index 0000000000..db68fcef1f --- /dev/null +++ b/Task/Even-or-odd/AppleScript/even-or-odd-2.applescript @@ -0,0 +1,45 @@ +-- even :: Integral a => a -> Bool +on even(n) + n mod 2 = 0 +end even + +-- odd :: Integral a => a -> Bool +on odd(n) + not even(n) +end odd + + +-- GENERIC FUNCTIONS FOR TEST ---------------------------------- + +-- filter :: (a -> Bool) -> [a] -> [a] +on filter(f, xs) + tell mReturn(f) + set lst to {} + set lng to length of xs + repeat with i from 1 to lng + set v to item i of xs + if lambda(v, i, xs) then set end of lst to v + end repeat + return lst + end tell +end filter + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property lambda : f + end script + end if +end mReturn + + +-- TEST --------------------------------------------------------- +on run + set xs to [-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6] + + {filter(even, xs), filter(odd, xs)} +end run diff --git a/Task/Even-or-odd/AppleScript/even-or-odd-3.applescript b/Task/Even-or-odd/AppleScript/even-or-odd-3.applescript new file mode 100644 index 0000000000..0dc53c2722 --- /dev/null +++ b/Task/Even-or-odd/AppleScript/even-or-odd-3.applescript @@ -0,0 +1 @@ +{{-6, -4, -2, 0, 2, 4, 6}, {-5, -3, -1, 1, 3, 5}} diff --git a/Task/Even-or-odd/AppleScript/even-or-odd.applescript b/Task/Even-or-odd/AppleScript/even-or-odd.applescript deleted file mode 100644 index d2f455e6f5..0000000000 --- a/Task/Even-or-odd/AppleScript/even-or-odd.applescript +++ /dev/null @@ -1,8 +0,0 @@ -set nList to {3, 2, 1, 0, -1, -2, -3} -repeat with n in nList - if (n / 2) = n / 2 as integer then - log "Value " & n & " is even." - else - log "Value " & n & " is odd." - end if -end repeat diff --git a/Task/Even-or-odd/BaCon/even-or-odd.bacon b/Task/Even-or-odd/BaCon/even-or-odd.bacon new file mode 100644 index 0000000000..704281b7a6 --- /dev/null +++ b/Task/Even-or-odd/BaCon/even-or-odd.bacon @@ -0,0 +1,5 @@ +' Even or odd +OPTION MEMTYPE int +SPLIT ARGUMENT$ BY " " TO arg$ SIZE dim +n = IIF$(dim < 2, 0, VAL(arg$[1])) +PRINT n, " is ", IIF$(EVEN(n), "even", "odd") diff --git a/Task/Even-or-odd/Bc/even-or-odd.bc b/Task/Even-or-odd/Bc/even-or-odd.bc new file mode 100644 index 0000000000..b158da5940 --- /dev/null +++ b/Task/Even-or-odd/Bc/even-or-odd.bc @@ -0,0 +1,8 @@ +i = -3 + +/* Assumes that i is an integer. */ +scale = 0 +if (i % 2 == 0) "i is even +" +if (i % 2) "i is odd +" diff --git a/Task/Even-or-odd/ColdFusion/even-or-odd.cfm b/Task/Even-or-odd/ColdFusion/even-or-odd.cfm index ed68067fb7..4ebf6acc62 100644 --- a/Task/Even-or-odd/ColdFusion/even-or-odd.cfm +++ b/Task/Even-or-odd/ColdFusion/even-or-odd.cfm @@ -1,5 +1,3 @@ - - She's even - - He's odd - +function f(numeric n) { + return n mod 2?"odd":"even" +} diff --git a/Task/Even-or-odd/EDSAC-order-code/even-or-odd.edsac b/Task/Even-or-odd/EDSAC-order-code/even-or-odd.edsac new file mode 100644 index 0000000000..0af2783ed3 --- /dev/null +++ b/Task/Even-or-odd/EDSAC-order-code/even-or-odd.edsac @@ -0,0 +1,33 @@ +[ Even or odd + =========== + + A program for the EDSAC + + Determines whether the number stored at + address 15@ is even or odd, and prints + 'E' or 'O' accordingly + + Works with Initial Orders 2 ] + + T56K [ load point ] + GK [ base address ] + + O11@ [ print letter shift ] + T10@ [ clear accumulator ] + H15@ [ multiplier := n ] + C12@ [ acc +:= mult AND 1 ] + S12@ [ acc -:= 1 ] + G8@ [ branch on negative ] + O14@ [ print 'O' ] + ZF [ halt ] +[ 8 ] O13@ [ print 'E' ] + ZF [ halt ] + +[ 10 ] P0F [ used to clear acc ] +[ 11 ] *F [ letter shift character ] +[ 12 ] P0D [ const: 1 ] +[ 13 ] EF [ character 'E' ] +[ 14 ] OF [ character 'O' ] +[ 15 ] P18D [ number to test: 37 ] + + EZPF [ branch to load point ] diff --git a/Task/Even-or-odd/Elixir/even-or-odd-1.elixir b/Task/Even-or-odd/Elixir/even-or-odd-1.elixir index 45429c262c..81a58f6b27 100644 --- a/Task/Even-or-odd/Elixir/even-or-odd-1.elixir +++ b/Task/Even-or-odd/Elixir/even-or-odd-1.elixir @@ -1,13 +1,13 @@ defmodule RC do - require Integer + import Integer - def even_or_odd(n) when Integer.is_even(n), do: "#{n} is even" - def even_or_odd(n) , do: "#{n} is odd" + def even_or_odd(n) when is_even(n), do: "#{n} is even" + def even_or_odd(n) , do: "#{n} is odd" # In second "def", the guard clauses of "is_odd(n)" is unnecessary. # Another definition way def even_or_odd2(n) do - if Integer.is_even(n), do: "#{n} is even", else: "#{n} is odd" + if is_even(n), do: "#{n} is even", else: "#{n} is odd" end end diff --git a/Task/Even-or-odd/Gambas/even-or-odd.gambas b/Task/Even-or-odd/Gambas/even-or-odd.gambas new file mode 100644 index 0000000000..50c5380fe2 --- /dev/null +++ b/Task/Even-or-odd/Gambas/even-or-odd.gambas @@ -0,0 +1,15 @@ +Public Sub Form_Open() +Dim sAnswer, sMessage As String + +sAnswer = InputBox("Input an integer", "Odd or even") + +If IsInteger(sAnswer) Then + If Odd(Val(sAnswer)) Then sMessage = "' is an odd number" + If Even(Val(sAnswer)) Then sMessage = "' is an even number" +Else + sMessage = "' does not compute!!" +Endif + +Print "'" & sAnswer & sMessage + +End diff --git a/Task/Even-or-odd/Haskell/even-or-odd.hs b/Task/Even-or-odd/Haskell/even-or-odd-1.hs similarity index 100% rename from Task/Even-or-odd/Haskell/even-or-odd.hs rename to Task/Even-or-odd/Haskell/even-or-odd-1.hs diff --git a/Task/Even-or-odd/Haskell/even-or-odd-2.hs b/Task/Even-or-odd/Haskell/even-or-odd-2.hs new file mode 100644 index 0000000000..9306a1f5fc --- /dev/null +++ b/Task/Even-or-odd/Haskell/even-or-odd-2.hs @@ -0,0 +1,11 @@ +import Prelude hiding (even, odd) + +even, odd + :: (Integral a) + => a -> Bool +even = (0 ==) . (`rem` 2) + +odd = not . even + +main :: IO () +main = print (even <$> [0 .. 9]) diff --git a/Task/Even-or-odd/JavaScript/even-or-odd-3.js b/Task/Even-or-odd/JavaScript/even-or-odd-3.js index d56169e1d9..2e91f993cd 100644 --- a/Task/Even-or-odd/JavaScript/even-or-odd-3.js +++ b/Task/Even-or-odd/JavaScript/even-or-odd-3.js @@ -1,2 +1,2 @@ // EMCAScript 6 -const isEven=x=>!(x%2) +const isEven = x => !(x % 2) diff --git a/Task/Even-or-odd/JavaScript/even-or-odd-4.js b/Task/Even-or-odd/JavaScript/even-or-odd-4.js new file mode 100644 index 0000000000..d1044aa12c --- /dev/null +++ b/Task/Even-or-odd/JavaScript/even-or-odd-4.js @@ -0,0 +1,25 @@ +(() => { + 'use strict'; + + // even : Integral a => a -> Bool + const even = x => (x % 2) === 0; + + // odd : Integral a => a -> Bool + const odd = x => !even(x); + + + // TEST ---------------------------------------- + // range :: Int -> Int -> [Int] + const range = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // show :: a -> String + const show = JSON.stringify; + + // xs :: [Int] + const xs = range(-6, 6); + + return show([xs.filter(even), xs.filter(odd)]); +})(); diff --git a/Task/Even-or-odd/jq/even-or-odd-1.jq b/Task/Even-or-odd/Jq/even-or-odd-1.jq similarity index 100% rename from Task/Even-or-odd/jq/even-or-odd-1.jq rename to Task/Even-or-odd/Jq/even-or-odd-1.jq diff --git a/Task/Even-or-odd/jq/even-or-odd-2.jq b/Task/Even-or-odd/Jq/even-or-odd-2.jq similarity index 100% rename from Task/Even-or-odd/jq/even-or-odd-2.jq rename to Task/Even-or-odd/Jq/even-or-odd-2.jq diff --git a/Task/Even-or-odd/Kotlin/even-or-odd.kotlin b/Task/Even-or-odd/Kotlin/even-or-odd.kotlin new file mode 100644 index 0000000000..f17a2df3e2 --- /dev/null +++ b/Task/Even-or-odd/Kotlin/even-or-odd.kotlin @@ -0,0 +1,13 @@ +// version 1.0.5-2 + +fun main(args: Array) { + while (true) { + print("Enter an integer or 0 to finish : ") + val n = readLine()!!.toInt() + when { + n == 0 -> return + n % 2 == 0 -> println("Your number is even") + else -> println("Your number is odd") + } + } +} diff --git a/Task/Even-or-odd/Processing/even-or-odd b/Task/Even-or-odd/Processing/even-or-odd new file mode 100644 index 0000000000..f0c2a433e2 --- /dev/null +++ b/Task/Even-or-odd/Processing/even-or-odd @@ -0,0 +1,7 @@ +boolean isEven(int i){ + return i%2 == 0; +} + +boolean isOdd(int i){ + return i%2 == 1; +} diff --git a/Task/Even-or-odd/Ruby/even-or-odd-1.rb b/Task/Even-or-odd/Ruby/even-or-odd-1.rb index 0c7b5082c6..ad9edc0ab3 100644 --- a/Task/Even-or-odd/Ruby/even-or-odd-1.rb +++ b/Task/Even-or-odd/Ruby/even-or-odd-1.rb @@ -1,4 +1,4 @@ print "evens: " -p -5.upto(5).select {|n| n.even?} +p -5.upto(5).select(&:even?) print "odds: " -p -5.upto(5).select {|n| n.odd?} +p -5.upto(5).select(&:odd?) diff --git a/Task/Even-or-odd/SPL/even-or-odd.spl b/Task/Even-or-odd/SPL/even-or-odd.spl new file mode 100644 index 0000000000..b3883f42b2 --- /dev/null +++ b/Task/Even-or-odd/SPL/even-or-odd.spl @@ -0,0 +1,4 @@ +> n, 0..9 + ? #.even(n), #.output(n," even") + ? #.odd(n), #.output(n," odd") +< diff --git a/Task/Even-or-odd/Shen/even-or-odd-1.shen b/Task/Even-or-odd/Shen/even-or-odd-1.shen new file mode 100644 index 0000000000..2466b186eb --- /dev/null +++ b/Task/Even-or-odd/Shen/even-or-odd-1.shen @@ -0,0 +1,7 @@ +(define even? + 0 -> true + X -> (odd? (- X 1))) + +(define odd? + 0 -> false + X -> (even? (- X 1))) diff --git a/Task/Even-or-odd/Shen/even-or-odd-2.shen b/Task/Even-or-odd/Shen/even-or-odd-2.shen new file mode 100644 index 0000000000..ff36ff104f --- /dev/null +++ b/Task/Even-or-odd/Shen/even-or-odd-2.shen @@ -0,0 +1,3 @@ +(define even? X -> (= 0 (shen.mod X 2))) + +(define odd? X -> (not (= 0 (shen.mod X 2)))) diff --git a/Task/Even-or-odd/XEec/even-or-odd.xeec b/Task/Even-or-odd/XEec/even-or-odd.xeec new file mode 100644 index 0000000000..2cedf5ccfd --- /dev/null +++ b/Task/Even-or-odd/XEec/even-or-odd.xeec @@ -0,0 +1,4 @@ +>100 p i# jz-1 o# t h#1 ms jz2003 p >0110 h#2 r ms t h#1 ms p +jz1002 h? jz2003 p jn0110 h#10 o$ p jn100 >2003 p p h#0 h#10 +h$d h$d h$o h#32 h$s h$i h#32 jn0000 >1002 p p h#0 h#10 +h$n h$e h$v h$e h#32 h$s h$i h#32 >0000 o$ p jn0000 jz100 diff --git a/Task/Even-or-odd/XLISP/even-or-odd.xlisp b/Task/Even-or-odd/XLISP/even-or-odd.xlisp new file mode 100644 index 0000000000..2184539307 --- /dev/null +++ b/Task/Even-or-odd/XLISP/even-or-odd.xlisp @@ -0,0 +1,5 @@ +(defun my-evenp (x) + (= (logand x 1) 0) ) + +(defun my-oddp (x) + (/= (logand x 1) 0) ) diff --git a/Task/Even-or-odd/Zkl/even-or-odd-1.zkl b/Task/Even-or-odd/Zkl/even-or-odd-1.zkl new file mode 100644 index 0000000000..0c22846d39 --- /dev/null +++ b/Task/Even-or-odd/Zkl/even-or-odd-1.zkl @@ -0,0 +1 @@ +[-3..4].pump(fcn(n){ println(n," is ",n.isEven and "even" or "odd") }) diff --git a/Task/Even-or-odd/Zkl/even-or-odd-2.zkl b/Task/Even-or-odd/Zkl/even-or-odd-2.zkl new file mode 100644 index 0000000000..1db760bd2d --- /dev/null +++ b/Task/Even-or-odd/Zkl/even-or-odd-2.zkl @@ -0,0 +1 @@ +[-3..4].apply("isEven").println(); diff --git a/Task/Events/Elixir/events.elixir b/Task/Events/Elixir/events.elixir index e4f3711332..86a8f4152f 100644 --- a/Task/Events/Elixir/events.elixir +++ b/Task/Events/Elixir/events.elixir @@ -1,7 +1,7 @@ defmodule Events do def log(msg) do - {h,m,s} = :erlang.time - :io.fwrite("~2.B:~2.B:~2.B => ~s~n",[h,m,s,msg]) + time = Time.utc_now |> to_string |> String.slice(0..7) + IO.puts "#{time} => #{msg}" end def task do @@ -14,12 +14,14 @@ defmodule Events do def main do log("Program start") - pid = spawn(Events,:task,[]) + {pid,ref} = spawn_monitor(__MODULE__,:task,[]) log("Program sleeping") - :timer.sleep(1000) + Process.sleep(1000) log("Program signalling event") send(pid, :go) - :timer.sleep(100) + receive do + {:DOWN,^ref,_,_,_} -> :task_is_down + end end end diff --git a/Task/Events/Gambas/events.gambas b/Task/Events/Gambas/events.gambas new file mode 100644 index 0000000000..61f06611c2 --- /dev/null +++ b/Task/Events/Gambas/events.gambas @@ -0,0 +1,5 @@ +Public Sub Timer1_Timer() + +Print Str(Time(Now)) + +End diff --git a/Task/Events/PowerShell/events.psh b/Task/Events/PowerShell/events.psh new file mode 100644 index 0000000000..fc99eb4928 --- /dev/null +++ b/Task/Events/PowerShell/events.psh @@ -0,0 +1,16 @@ +$timer = New-Object -TypeName System.Timers.Timer -Property @{Enabled=$true; Interval=1000; AutoReset=$true} + +$action = { + $global:counter += 1 + Write-Host “Event counter is ${counter}: $((Get-Date).ToString("hh:mm:ss"))” + if ($counter -ge $event.MessageData) + { + Write-Host “Timer stopped” + $timer.Stop() + } +} + +$job = Register-ObjectEvent -InputObject $timer -MessageData 5 -SourceIdentifier Count -EventName Elapsed -Action $action + +$global:counter = 0 +& $job.Module {$global:counter} diff --git a/Task/Events/Zkl/events.zkl b/Task/Events/Zkl/events.zkl new file mode 100644 index 0000000000..31c2089561 --- /dev/null +++ b/Task/Events/Zkl/events.zkl @@ -0,0 +1,6 @@ +var event=Atomic.Bool(); // False + // create thread waiting for event +fcn(event){event.wait(); println(vm," ping!")}.launch(event); +Atomic.sleep(1); +event.set(); +println("done") diff --git a/Task/Evolutionary-algorithm/00DESCRIPTION b/Task/Evolutionary-algorithm/00DESCRIPTION index 4bfc47362f..8553b6c95c 100644 --- a/Task/Evolutionary-algorithm/00DESCRIPTION +++ b/Task/Evolutionary-algorithm/00DESCRIPTION @@ -9,7 +9,7 @@ Starting with: :* repeat until the parent converges, (hopefully), to the target. -;Related tasks: +;See also: *   [[wp:Weasel_program#Weasel_algorithm|Weasel algorithm]]. *   [[wp:Evolutionary algorithm|Evolutionary algorithm]]. diff --git a/Task/Evolutionary-algorithm/Batch-File/evolutionary-algorithm.bat b/Task/Evolutionary-algorithm/Batch-File/evolutionary-algorithm.bat new file mode 100644 index 0000000000..03bada66fc --- /dev/null +++ b/Task/Evolutionary-algorithm/Batch-File/evolutionary-algorithm.bat @@ -0,0 +1,88 @@ +@echo off +setlocal enabledelayedexpansion + +set target=M E T H I N K S @ I T @ I S @ L I K E @ A @ W E A S E L +set chars=A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @ + +set tempcount=0 +for %%i in (%target%) do ( + set /a tempcount+=1 + set target!tempcount!=%%i +) +call:parent + +echo %target% +echo -------------------------------------------------------- + +:loop +call:fitness parent +set currentfit=%errorlevel% +if %currentfit%==28 goto end +echo %parent% - %currentfit% [%attempts%] +set attempts=0 + +:innerloop +set /a attempts+=1 +title Attemps - %attempts% +call:mutate %parent% +call:fitness tempparent +set newfit=%errorlevel% +if %newfit% gtr %currentfit% ( + set tempcount=0 + set "parent=" + for %%i in (%tempparent%) do ( + set /a tempcount+=1 + set parent!tempcount!=%%i + set parent=!parent! %%i + ) + goto loop +) +goto innerloop + +:end +echo %parent% - %currentfit% [%attempts%] +echo Done. +exit /b + +:parent +set "parent=" +for /l %%i in (1,1,28) do ( + set /a charchosen=!random! %% 27 + 1 + set tempcount=0 + for %%j in (%chars%) do ( + set /a tempcount+=1 + if !charchosen!==!tempcount! ( + set parent%%i=%%j + set parent=!parent! %%j + ) + ) +) +exit /b + +:fitness +set fitness=0 +set array=%1 +for /l %%i in (1,1,28) do if !%array%%%i!==!target%%i! set /a fitness+=1 +exit /b %fitness% + +:mutate +set tempcount=0 +set returnarray=tempparent +set "%returnarray%=" +for %%i in (%*) do ( + set /a tempcount+=1 + set %returnarray%!tempcount!=%%i + set %returnarray%=!%returnarray%! %%i +) +set /a tomutate=%random% %% 28 + 1 +set /a mutateto=%random% %% 27 + 1 +set tempcount=0 +for %%i in (%chars%) do ( + set /a tempcount+=1 + if %mutateto%==!tempcount! ( + set %returnarray%!tomutate!=%%i + ) +) +set "%returnarray%=" +for /l %%i in (1,1,28) do set %returnarray%=!%returnarray%! !%returnarray%%%i! +exit /b diff --git a/Task/Evolutionary-algorithm/C++/evolutionary-algorithm.cpp b/Task/Evolutionary-algorithm/C++/evolutionary-algorithm.cpp index 5a7e7eaf61..69793fe296 100644 --- a/Task/Evolutionary-algorithm/C++/evolutionary-algorithm.cpp +++ b/Task/Evolutionary-algorithm/C++/evolutionary-algorithm.cpp @@ -97,8 +97,7 @@ int main() { std::cout << parent << ": " << fitness << "\n"; double const mutation_rate = 0.02 + (0.9*fitness)/initial_fitness; - typedef std::vector childvec; - childvec childs; + std::vector childs; childs.reserve(C+1); childs.push_back(parent); diff --git a/Task/Evolutionary-algorithm/D/evolutionary-algorithm-1.d b/Task/Evolutionary-algorithm/D/evolutionary-algorithm-1.d deleted file mode 100644 index d03e58f6d3..0000000000 --- a/Task/Evolutionary-algorithm/D/evolutionary-algorithm-1.d +++ /dev/null @@ -1,33 +0,0 @@ -import std.stdio, std.random, std.algorithm, std.range, std.ascii; - -void evolve(string target, double prob=0.05, int C=100) { - auto chars = uppercase ~ " "; - char rndCh() { return chars[uniform(0, $)]; } - void mutate(char[] parent, char[] child) { - foreach (i, ref c; child) - c = uniform(0.0, 1.0) < prob ? rndCh() : parent[i]; - } - int fitness(char[] subject, string target) { - return count!q{ a[0] != a[1] }(zip(subject, target)); - } - auto parent= map!(i => rndCh())(target).array(); - auto best = parent.dup; - auto child = new char[target.length]; - int currDist = fitness(parent, target); - for (int gen; currDist > 0; gen++) { - foreach (_; 0 .. C) { - mutate(parent, child); - int dist = fitness(child, target); - if (dist < currDist) { - currDist = dist; - best[] = child[]; - } - } - parent = best; - writefln("Generation %2s, dist=%2s: %s", gen, currDist, best); - } -} - -void main() { - evolve("METHINKS IT IS LIKE A WEASEL"); -} diff --git a/Task/Evolutionary-algorithm/D/evolutionary-algorithm-2.d b/Task/Evolutionary-algorithm/D/evolutionary-algorithm-2.d deleted file mode 100644 index 442301370f..0000000000 --- a/Task/Evolutionary-algorithm/D/evolutionary-algorithm-2.d +++ /dev/null @@ -1,19 +0,0 @@ -import std.stdio, std.random, std.algorithm, std.range; - -enum target = "METHINKS IT IS LIKE A WEASEL"d; -enum C = 100; // Number of children in each generation. -enum P = 0.05; // Mutation probability. -auto alphabet = " ABCDEFGHIJLKLMNOPQRSTUVWXYZ"d.dup; -const fitness = (dchar[] s) => count!"a[0] != a[1]"(zip(s, target)); -const rndc = () => alphabet[uniform(0, $)]; -const mutate = (dchar[] s) => - s.map!(a => uniform(0., 1.) < P ? rndc() : a)().array(); - -void main() { - auto parent = target.length.iota().map!(_ => rndc())().array(); - for (int gen = 1; parent != target; gen++) { - auto offs = parent.repeat(C).map!mutate().array(); - parent = offs.minPos!((a, b) => fitness(a) < fitness(b))()[0]; - writefln("Gen %2d, dist=%2d: %s", gen, fitness(parent), parent); - } -} diff --git a/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena b/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena index f3160aafd3..7dcfe1d16a 100644 --- a/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena +++ b/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena @@ -1,65 +1,68 @@ -#import system. -#import system'routines. -#import extensions. +import system'routines. +import extensions. -#symbol Target = "METHINKS IT IS LIKE A WEASEL". -#symbol AllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ". -#symbol C = 100. -#symbol P = 0.05r. -#symbol rnd = randomGenerator. +const Target = "METHINKS IT IS LIKE A WEASEL". +const AllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ". -#symbol randomChar - = AllowedCharacters @ (rnd nextInt:(AllowedCharacters length)). +const C = 100. +const P = 0.05r. -#class(extension) evoHelper +rnd = randomGenerator. + +randomChar + = AllowedCharacters[rnd nextInt(AllowedCharacters length)]. + +extension evoHelper { - #method randomString - = 0 repeat &till:self &each:x [ randomChar ] summarize:(String new) literal. + randomString + = 0 till:self repeat(:x)( randomChar ); summarize:(String new); literal. - #method fitness &of:s - = self zip:s &into:(:a:b)[ (a == b)iif:1:0 ] summarize:(Integer new) int. + fitnessOf:s + = self zip:s by(:a:b)( (a == b)iif(1,0) ); summarize(Integer new); int. - #method mutate : p - = self select &each: ch [ (rnd nextReal <= p) iif:randomChar:ch ] summarize:(String new) literal. + mutate : p + = self selectBy(:ch)( (rnd nextReal <= p) iif(randomChar,ch) ); summarize(String new); literal. } -#class EvoAlgorithm :: Enumerator +class EvoAlgorithm :: Enumerator { - #field theTarget. - #field theCurrent. - #field theVariantCount. + object theTarget. + object theCurrent. + object theVariantCount. - #constructor new : s &of:count + constructor new : s of:count [ theTarget := s. theVariantCount := count int. ] - #method get = theCurrent. + get = theCurrent. - #method next + next [ - ($nil == theCurrent) - ? [ theCurrent := theTarget length randomString. ^ true. ]. + if ($nil == theCurrent) + [ theCurrent := theTarget length; randomString. ^ true ]. - (theTarget == theCurrent) - ? [ ^ false. ]. + if (theTarget == theCurrent) + [ ^ false ]. - #var variants := Array new:theVariantCount set &every:(&index:x) [ theCurrent mutate:P ]. + var variants := Array new:theVariantCount; populate(:x)( theCurrent mutate:P ). - theCurrent := variants array sort:(:a:b) [ a fitness &of:Target > b fitness &of:Target ] getAt:0. + theCurrent := variants array; sort(:a:b)( a fitnessOf:Target > b fitnessOf:Target ); getAt:0. ^ true. ] } -#symbol program = +program = [ - #var attempt := Integer new. - EvoAlgorithm new:Target &of:C run &each:current + var attempt := Integer new. + EvoAlgorithm new:Target of:C; forEach(:current) [ console - writeLiteral:"#":(attempt += 1) &paddingLeft:10 - writeLine:" ":current:" fitness: ":(current fitness &of:Target). + printPaddingLeft(10,"#",attempt append:1); + printLine(" ",current," fitness: ",current fitnessOf:Target). ]. + + console readChar. ]. diff --git a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-1.elixir b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-1.elixir deleted file mode 100644 index 92eec62082..0000000000 --- a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-1.elixir +++ /dev/null @@ -1,15 +0,0 @@ -defmodule Rand do - def init do # Initialize the random values. - << a :: 32, b :: 32, c :: 32 >> = :crypto.strong_rand_bytes(12) - :random.seed(a,b,c) - end - - def num do # Returns a value between 0.0 and 1.0. - init - :random.uniform - end - - def char(list) do # Returns a random letter or a space. - Enum.at(list, :random.uniform(length(list)) - 1) - end -end diff --git a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-2.elixir b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-2.elixir deleted file mode 100644 index 91adc351c1..0000000000 --- a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-2.elixir +++ /dev/null @@ -1,9 +0,0 @@ -defmodule Log do - def show(offspring,i) do - IO.puts "Generation: #{i}, Offspring: #{offspring}" - end - - def found([target|i]) do - IO.puts "#{target} found in #{i} iterations" - end -end diff --git a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-3.elixir b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-3.elixir deleted file mode 100644 index e0e70e9698..0000000000 --- a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-3.elixir +++ /dev/null @@ -1,57 +0,0 @@ -defmodule Evolution do - def select(target) do - # Generate char list from A to Z; 32 is the ord value for space. - chars = (?A..?Z) |> Enum.to_list() |> List.insert_at(0, 32) - - (1..String.length(target)) # Creates parent for generation 0. - |> Enum.map(fn _-> Rand.char(chars) end) - |> mutate(String.to_char_list(target),0,[],chars) - |> Log.found() - end - - # w is used to denote fitness in population genetics. - - def mutate(parent,target,i,_,_) when target == parent, do: [parent|i] - def mutate(parent,target,i,_,chars) when target != parent do - w = fitness(parent,target) - prev = reproduce(target,parent,w,0,mu_rate(w),chars) - - # Check if the most fit member of the new gen has a greater fitness than the parent. - if w < fitness(prev,target) do - parent = prev - Log.show(parent,i) - end - mutate(parent,target,i+1,prev,chars) - end - - # Generate 100 offspring and select the one with the greatest fitness. - - def reproduce(target,parent,_,_,rate,chars) do - (1..100) - |> Enum.to_list() - |> Stream.map(fn _-> mutation(parent,rate,chars) end) - |> List.insert_at(0, parent) - |> Enum.max_by(fn n -> fitness(n,target) end) - end - - # Calculate fitness by checking difference between parent and offspring chars. - - def fitness(t,r) do - (0..length(t)-1) - |> Stream.map(fn n -> abs(Enum.at(t,n) - Enum.at(r,n)) end) - |> Enum.reduce(fn a,b -> a + b end) - |> calc() - end - - # Generate offspring based on parent. - - def mutation(p,r,chars) do - # Copy the parent chars, then check each val against the random mutation rate - (0..length(p)-1) - |> Stream.map(fn n -> Enum.at(p,n) end) - |> Enum.map(fn n -> if Rand.num <= r, do: Rand.char(chars), else: n end) - end - - def calc(sum), do: 100 * :math.exp(sum/-10) - def mu_rate(n), do: 1 - :math.exp(-(100-n)/400) -end diff --git a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-4.elixir b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-4.elixir deleted file mode 100644 index 5c9e247529..0000000000 --- a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-4.elixir +++ /dev/null @@ -1 +0,0 @@ -Evolution.select("METHINKS IT IS LIKE A WEASEL") diff --git a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm.elixir b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm.elixir index eb18c07e54..07569b5e02 100644 --- a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm.elixir +++ b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm.elixir @@ -15,7 +15,7 @@ defmodule Evolution do def select(target) do (1..String.length(target)) # Creates parent for generation 0. |> Enum.map(fn _-> Enum.random(@chars) end) - |> mutate(to_char_list(target),0) + |> mutate(to_charlist(target),0) |> Log.found end @@ -28,16 +28,17 @@ defmodule Evolution do # Check if the most fit member of the new gen has a greater fitness than the parent. if w < fitness(prev,target) do - parent = prev - Log.show(parent,i) + Log.show(prev,i) + mutate(prev,target,i+1) + else + mutate(parent,target,i+1) end - mutate(parent,target,i+1) end # Generate 100 offspring and select the one with the greatest fitness. defp reproduce(target,parent,rate) do - [parent | Enum.map(1..100, fn _-> mutation(parent,rate) end)] + [parent | (for _ <- 1..100, do: mutation(parent,rate))] |> Enum.max_by(fn n -> fitness(n,target) end) end diff --git a/Task/Evolutionary-algorithm/Julia/evolutionary-algorithm-1.julia b/Task/Evolutionary-algorithm/Julia/evolutionary-algorithm-1.julia index 3062be8f9e..fd184a4f13 100644 --- a/Task/Evolutionary-algorithm/Julia/evolutionary-algorithm-1.julia +++ b/Task/Evolutionary-algorithm/Julia/evolutionary-algorithm-1.julia @@ -1,27 +1,22 @@ -function evolve(parent,target,mutation_rate,num_children) -println("Initial parent is $parent, its fitness is $(fitness(parent,target))") -gens=0 -while parent!=target -children=[mutate(parent,mutation_rate) for i=1:num_children] -bestfit,best=findmax(map(child->fitness(child,target),children)) -parent=children[best] -gens+=1 -if gens%10==0 -println("After $gens generations, the new parent is $parent and its fitness is $(fitness(parent,target))") -end -end -println("After $gens generations, the parent evolved into the target $target") +function evolve(parent::String, target::String, mutrate::Float64, nchild::Int) + fitness(a, b::String=target) = count(l == t for (l, t) in zip(a, b)) + function mutate(str::String, rate::Float64=mutrate) + L = split(" ABCDEFGHIJKLMNOPQRSTUVWXYZ", "") + r = collect(rand() < rate ? rand(L) : c for c in str) + return string(r...) + end + println("Initial parent is $parent, its fitness is $(fitness(parent))") + gens = 0 + while parent != target + children = collect(mutate(parent, mutrate) for i in 1:nchild) + bestfit, best = findmax(fitness.(children)) + parent = children[best] + gens += 1 + if gens % 10 == 0 + println("After $gens generations, the new parent is $parent and its fitness is $(fitness(parent))") + end + end + println("After $gens generations, the parent evolved into the target $target") end -fitness(s1,s2)=count(x->x,convert(Array{Char,1},s1).==convert(Array{Char,1},s2)) - -function mutate(s,rate) -new_s="" -for c in s -new_s*=string(rand() mutationRate) it else randomChar() } + .joinToString(separator = "") + +fun main(args: Array) { + val initialString = (0 until target.length).map { randomChar() }.joinToString(separator = "") + + println(initialString) + println(mutate(initialString, 0.2)) + + val mutationRate = 0.05 + val childrenPerGen = 50 + + var i = 0 + var currVal = initialString + while (currVal != target) { + i += 1 + currVal = (0..childrenPerGen).map { mutate(currVal, mutationRate) }.maxBy { fitness(it) }!! + } + println("Evolution found target after $i generations") +} diff --git a/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 b/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 index 9f569b1609..77b2564479 100644 --- a/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 +++ b/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 @@ -3,7 +3,7 @@ constant mutate_chance = .08; constant @alphabet = flat 'A'..'Z',' '; constant C = 100; -sub mutate { $^string.subst(/./, { rand < mutate_chance ?? @alphabet.pick !! $/ }, :g) } +sub mutate { [~] (rand < mutate_chance ?? @alphabet.pick !! $_ for $^string.comb) } sub fitness { [+] $^string.comb Zeq state @ = target.comb } loop ( diff --git a/Task/Evolutionary-algorithm/Pony/evolutionary-algorithm-1.pony b/Task/Evolutionary-algorithm/Pony/evolutionary-algorithm-1.pony index ef45c5b88d..0c7a28f78e 100644 --- a/Task/Evolutionary-algorithm/Pony/evolutionary-algorithm-1.pony +++ b/Task/Evolutionary-algorithm/Pony/evolutionary-algorithm-1.pony @@ -45,7 +45,7 @@ actor Main var i: USize = 0 while i < trial.size() do try - if trial(i) == _target(i) then + if trial(i)? == _target(i)? then ret_val = ret_val + 1 end end @@ -64,7 +64,7 @@ actor Main if rnd_real <= rate then let rnd_int: U64 = _rand.int(_possibilities.size().u64()) try - ret_val.push(_possibilities(rnd_int.usize())) + ret_val.push(_possibilities(rnd_int.usize())?) end else ret_val.push(char) diff --git a/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-1.rexx b/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-1.rexx index bdf6762c2f..1a0b52bea1 100644 --- a/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-1.rexx +++ b/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-1.rexx @@ -26,7 +26,7 @@ fitness: parse arg x; $=0; do k=1 for Ltar; $=$+(substr(x,k,1)==substr(target, return $ /*──────────────────────────────────────────────────────────────────────────────────────*/ mutate: parse arg x,rate; $= /*set X to 1st argument, RATE to 2nd.*/ - do j=1 for Ltar; r=random(1,100000) /*REXX's max for RANSOM*/ + do j=1 for Ltar; r=random(1,100000) /*REXX's max for RANDOM*/ if .00001*r<=rate then $=$ || substr(abc,r//Labc+1, 1) else $=$ || substr(x ,j , 1) end /*j*/ diff --git a/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-3.rexx b/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-3.rexx deleted file mode 100644 index d7f21be771..0000000000 --- a/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-3.rexx +++ /dev/null @@ -1,45 +0,0 @@ -/*REXX program demonstrates an evolutionary algorithm (using mutation).*/ -parse arg children MR seed . /*get options (maybe) from C.L. */ -if children=='' then children = 10 /*# of children produced each gen*/ -if MR =='' then MR = "4%" /*the char Mutation Rate each gen*/ -if right(MR,1)=='%' then MR=strip(MR,,"%")/100 /*expressed as %? Adjust*/ -if seed\=='' then call random ,,seed /*allow the runs to be repeatable*/ -abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ' ; Labc=length(abc) - - do i=0 for Labc /*define array (faster compare), */ - A.i=substr(abc, i+1, 1) /* it's better than picking out a*/ - end /*i*/ /* byte from a character string. */ - -target= 'METHINKS IT IS LIKE A WEASEL' ; Ltar=length(target) - - do i=1 for Ltar /*define array (faster compare), */ - T.i=substr(target, i, 1) /*it's better than a byte-by-byte*/ - end /*i*/ /*compare using character strings*/ - -parent= mutate( left('', Ltar), 1) /*gen rand str,same length as tar*/ -say center('target string', Ltar, '─') "children" 'mutationRate' -say target center(children, 8) center((MR*100/1)'%', 12) ; say -say center('new string', Ltar, '─') "closeness" 'generation' - - do gen=0 until parent==target; close=fitness(parent) - almost=parent - do children; child=mutate(parent, MR) - _=fitness(child); if _<=close then iterate - close=_; almost=child - say almost right(close, 9) right(gen, 10) - end /*children*/ - parent=almost - end /*gen*/ -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────────FITNESS subroutine─────────────────*/ -fitness: parse arg x; hit=0; do k=1 for Ltar - hit=hit + (substr(x,k,1) == T.k) - end /*k*/ -return hit -/*───────────────────────────────────MUTATE subroutine──────────────────*/ -mutate: parse arg x,rate,? /*set ? to a null, x=string. */ - do j=1 for Ltar; r=random(1, 100000) - if .00001*r<=rate then do; _=r//Labc; ?=? || A._; end - else ?=? || substr(x,j,1) - end /*j*/ -return ? diff --git a/Task/Evolutionary-algorithm/Scheme/evolutionary-algorithm.ss b/Task/Evolutionary-algorithm/Scheme/evolutionary-algorithm.ss new file mode 100644 index 0000000000..7f5d33fff0 --- /dev/null +++ b/Task/Evolutionary-algorithm/Scheme/evolutionary-algorithm.ss @@ -0,0 +1,57 @@ +(import (scheme base) + (scheme write) + (srfi 27)) ; random numbers + +(random-source-randomize! default-random-source) + +(define target "METHINKS IT IS LIKE A WEASEL") ; target string +(define C 100) ; size of population +(define p 0.1) ; chance any char is mutated + +;; return a random character in given range +(define (random-char) + (string-ref "ABCDEFGHIJKLMNOPQRSTUVWXYZ " + (random-integer 27))) + +;; compute distance of given string from target +(define (fitness str) + (apply + + (map (lambda (c1 c2) (if (char=? c1 c2) 0 1)) + (string->list str) + (string->list target)))) + +;; mutate given parent string, returning a new string +(define (mutate str) + (string-map (lambda (c) + (if (< (random-real) p) + (random-char) + c)) + str)) + +;; create a population by mutating parent, +;; returning a list of variations +(define (make-population parent) + (do ((pop '() (cons (mutate parent) pop))) + ((= C (length pop)) pop))) + +;; find the most fit candidate in given list +(define (find-best candidates) + (define (select-best a b) + (if (< (fitness a) (fitness b)) a b)) + ; + (do ((best (car candidates) (select-best best (car rem))) + (rem (cdr candidates) (cdr rem))) + ((null? rem) best))) + +;; create first parent from random characters +;; of same size as target string +(define (initial-parent) + (do ((res '() (cons (random-char) res))) + ((= (length res) (string-length target)) + (list->string res)))) + +;; run the search +(do ((parent (initial-parent) (find-best (cons parent (make-population parent))))) ; select best from parent and population + ((string=? parent target) + (display (string-append "Found: " parent "\n"))) + (display parent) (newline)) diff --git a/Task/Evolutionary-algorithm/Sinclair-ZX81-BASIC/evolutionary-algorithm.sinclair b/Task/Evolutionary-algorithm/Sinclair-ZX81-BASIC/evolutionary-algorithm.sinclair new file mode 100644 index 0000000000..223351c279 --- /dev/null +++ b/Task/Evolutionary-algorithm/Sinclair-ZX81-BASIC/evolutionary-algorithm.sinclair @@ -0,0 +1,43 @@ + 10 LET A$="ABCDEFGHIJKLMNOPQRSTUVWXYZ " + 20 LET T$="METHINKS IT IS LIKE A WEASEL" + 30 LET L=LEN T$ + 40 LET C=10 + 50 LET M=0.05 + 60 LET G=0 + 70 DIM C$(C,L) + 80 LET P$="" + 90 FOR I=1 TO L +100 LET P$=P$+A$(INT (RND*LEN A$)+1) +110 NEXT I +120 PRINT AT 1,0;P$ +130 LET S$=P$ +140 GOSUB 390 +150 LET N=R +160 PRINT AT 1,30;N +170 PRINT AT 0,4;G +180 IF P$=T$ THEN GOTO 440 +190 FOR I=1 TO C +200 FOR J=1 TO L +210 LET C$(I,J)=P$(J) +220 IF RND<=M THEN LET C$(I,J)=A$(INT (RND*LEN A$)+1) +230 PRINT AT I+2,J-1;C$(I,J) +240 NEXT J +250 PRINT AT I+2,30;" " +260 NEXT I +270 LET F=0 +280 FOR I=1 TO C +290 LET S$=C$(I) +300 GOSUB 390 +310 PRINT AT I+2,30;R +320 IF R>N THEN LET F=I +330 IF R>N THEN LET N=R +340 NEXT I +350 IF F>0 THEN LET P$=C$(F) +360 LET G=G+1 +370 PRINT AT 1,0;P$ +380 GOTO 160 +390 LET R=0 +400 FOR K=1 TO L +410 IF S$(K)=T$(K) THEN LET R=R+1 +420 NEXT K +430 RETURN diff --git a/Task/Evolutionary-algorithm/VBScript/evolutionary-algorithm.vb b/Task/Evolutionary-algorithm/VBScript/evolutionary-algorithm.vb new file mode 100644 index 0000000000..cbd127d4f7 --- /dev/null +++ b/Task/Evolutionary-algorithm/VBScript/evolutionary-algorithm.vb @@ -0,0 +1,98 @@ +'This is the string we want to "evolve" to. Any string of any length will +'do as long as it consists only of upper case letters and spaces. + +Target = "METHINKS IT IS LIKE A WEASEL" + +'This is the pool of letters that will be selected at random for a mutation + +letters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ" + +'A mutation rate of 0.5 means that there is a 50% chance that one letter +'will be mutated at random in the next child + +mutation_rate = 0.5 + +'Set for 10 children per generation + +Dim child(10) + +'Generate the first guess as random letters + +Randomize +Parent = "" + +for i = 1 to len(Target) + Parent = Parent & Mid(letters,Random(1,Len(letters)),1) +next + +gen = 0 + +Do + bestfit = 0 + bestind = 0 + + gen = gen + 1 + + 'make n copies of the current string and find the one + 'that best matches the target string + + For i = 0 to ubound(child) + + child(i) = Mutate(Parent, mutation_rate) + + fit = Fitness(Target, child(i)) + + If fit > bestfit Then + bestfit = fit + bestind = i + End If + + Next + + 'Select the child that has the best fit with the target string + + Parent = child(bestind) + Wscript.Echo parent, "(fit=" & bestfit & ")" + +Loop Until Parent = Target + +Wscript.Echo vbcrlf & "Generations = " & gen + +'apply a random mutation to a random character in a string + +Function Mutate ( ByVal str , ByVal rate ) + + Dim pos 'a random position in the string' + Dim ltr 'a new letter chosen at random ' + + If rate > Rnd(1) Then + + ltr = Mid(letters,Random(1,len(letters)),1) + pos = Random(1,len(str)) + str = Left(str, pos - 1) & ltr & Mid(str, pos + 1) + + End If + + Mutate = str + +End Function + +'returns the number of letters in the two strings that match + +Function Fitness (ByVal str , ByVal ref ) + + Dim i + + Fitness = 0 + + For i = 1 To Len(str) + If Mid(str, i, 1) = Mid(ref, i, 1) Then Fitness = Fitness + 1 + Next + +End Function + +'Return a random integer in the range lower to upper (inclusive) + +Private Function Random ( lower , upper ) + Random = Int((upper - lower + 1) * Rnd + lower) +End Function diff --git a/Task/Evolutionary-algorithm/Zkl/evolutionary-algorithm.zkl b/Task/Evolutionary-algorithm/Zkl/evolutionary-algorithm.zkl new file mode 100644 index 0000000000..67c2e69115 --- /dev/null +++ b/Task/Evolutionary-algorithm/Zkl/evolutionary-algorithm.zkl @@ -0,0 +1,14 @@ +const target = "METHINKS IT IS LIKE A WEASEL"; +const C = 100; // Number of children in each generation. +const P = 0.05; // Mutation probability. +const A2ZS = ["A".."Z"].walk().append(" ").concat(); +fcn fitness(s){ Utils.zipWith('!=,target,s).sum(0) } // bigger is worser +fcn rnd{ A2ZS[(0).random(27)] } +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) -#include - -typedef struct exception { - int extype; - char what[128]; -} exception; - -typedef struct exception_ctx { - exception * exs; - int size; - int pos; -} exception_ctx; - -exception_ctx * Create_Ex_Ctx(int length) { - const int safety = 8; // alignment precaution. - char * tmp = (char*) malloc(safety+sizeof(exception_ctx)+sizeof(exception)*length); - if (! tmp) return NULL; - exception_ctx * ctx = (exception_ctx*)tmp; - ctx->size = length; - ctx->pos = -1; - ctx->exs = (exception*) (tmp + sizeof(exception_ctx)); - return ctx; -} - -void Free_Ex_Ctx(exception_ctx * ctx) { - free(ctx); -} - -int Has_Ex(exception_ctx * ctx) { - return (ctx->pos >= 0) ? 1 : 0; -} - -int Is_Ex_Type(exception_ctx * exctx, int extype) { - return (exctx->pos >= 0 && exctx->exs[exctx->pos].extype == extype) ? 1 : 0; -} - -void Pop_Ex(exception_ctx * ctx) { - if (ctx->pos >= 0) --ctx->pos; -} - -const char * Get_What(exception_ctx * ctx) { - if (ctx->pos >= 0) return ctx->exs[ctx->pos].what; - return NULL; -} - -int Push_Ex(exception_ctx * exctx, int extype, const char * msg) { - if (++exctx->pos == exctx->size) { - // Use last slot and report error. - --exctx->pos; - fprintf(stderr, "*** Error: Overflow in exception context.\n"); - } - snprintf(exctx->exs[exctx->pos].what, sizeof(exctx->exs[0].what), "%s", msg); - exctx->exs[exctx->pos].extype = extype; - return -1; -} - -////////////////////////////////////////////////////////////////////// - -exception_ctx * GLOBALEX = NULL; -enum { U0_DRINK_ERROR = 10, U1_ANGRYBARTENDER_ERROR }; - -void baz(int n) { - if (! n) { - Push_Ex(GLOBALEX, U0_DRINK_ERROR , "U0 Drink Error. Insufficient drinks in bar Baz."); - return; - } - else { - Push_Ex(GLOBALEX, U1_ANGRYBARTENDER_ERROR , "U1 Bartender Error. Bartender kicked customer out of bar Baz."); - return; - } -} - -void bar(int n) { - fprintf(stdout, "Bar door is open.\n"); - baz(n); - if (Has_Ex(GLOBALEX)) goto bar_cleanup; - fprintf(stdout, "Baz has been called without errors.\n"); -bar_cleanup: - fprintf(stdout, "Bar door is closed.\n"); -} - -void foo() { - fprintf(stdout, "Foo entering bar.\n"); - bar(0); - while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) { - fprintf(stderr, "I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [%s]\n", Get_What(GLOBALEX)); - Pop_Ex(GLOBALEX); - } - if (Has_Ex(GLOBALEX)) return; - fprintf(stdout, "Foo left the bar.\n"); - fprintf(stdout, "Foo entering bar again.\n"); - bar(1); - while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) { - fprintf(stderr, "I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [%s]\n", Get_What(GLOBALEX)); - Pop_Ex(GLOBALEX); - } - if (Has_Ex(GLOBALEX)) return; - fprintf(stdout, "Foo left the bar.\n"); -} - - -int main(int argc, char ** argv) { - exception_ctx * ctx = Create_Ex_Ctx(5); - GLOBALEX = ctx; - - foo(); - if (Has_Ex(ctx)) goto main_ex; - - fprintf(stdout, "No errors encountered.\n"); - -main_ex: - while (Has_Ex(ctx)) { - fprintf(stderr, "*** Error: %s\n", Get_What(ctx)); - Pop_Ex(ctx); - } - Free_Ex_Ctx(ctx); - return 0; -} diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call-2.c b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call-2.c deleted file mode 100644 index 087671ccf1..0000000000 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call-2.c +++ /dev/null @@ -1,9 +0,0 @@ -Foo entering bar. -Bar door is open. -Bar door is closed. -I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [U0 Drink Error. Insufficient drinks in bar Baz.] -Foo left the bar. -Foo entering bar again. -Bar door is open. -Bar door is closed. -*** Error: U1 Bartender Error. Bartender kicked customer out of bar Baz. diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/jq/exceptions-catch-an-exception-thrown-in-a-nested-call.jq b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Jq/exceptions-catch-an-exception-thrown-in-a-nested-call.jq similarity index 100% rename from Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/jq/exceptions-catch-an-exception-thrown-in-a-nested-call.jq rename to Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Jq/exceptions-catch-an-exception-thrown-in-a-nested-call.jq diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Kotlin/exceptions-catch-an-exception-thrown-in-a-nested-call.kotlin b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Kotlin/exceptions-catch-an-exception-thrown-in-a-nested-call.kotlin new file mode 100644 index 0000000000..8411f92feb --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Kotlin/exceptions-catch-an-exception-thrown-in-a-nested-call.kotlin @@ -0,0 +1,29 @@ +// version 1.0.6 + +class U0 : Throwable("U0 occurred") +class U1 : Throwable("U1 occurred") + +fun foo() { + for (i in 1..2) { + try { + bar(i) + } catch(e: U0) { + println(e.message) + } + } +} + +fun bar(i: Int) { + baz(i) +} + +fun baz(i: Int) { + when (i) { + 1 -> throw U0() + 2 -> throw U1() + } +} + +fun main(args: Array) { + foo() +} diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Maple/exceptions-catch-an-exception-thrown-in-a-nested-call.maple b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Maple/exceptions-catch-an-exception-thrown-in-a-nested-call.maple new file mode 100644 index 0000000000..9a0dee45ff --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Maple/exceptions-catch-an-exception-thrown-in-a-nested-call.maple @@ -0,0 +1,16 @@ +num_times:=0: +baz := proc() + global num_times := num_times + 1; + error `if`(num_times <= 1, "U0", "U1"); +end proc: + +bar:=proc() + baz(); +end proc; + +foo:=proc() + local i; + for i from 0 to 1 do + bar(); + end do; +end proc; diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Phix/exceptions-catch-an-exception-thrown-in-a-nested-call.phix b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Phix/exceptions-catch-an-exception-thrown-in-a-nested-call.phix new file mode 100644 index 0000000000..f1b728fd16 --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Phix/exceptions-catch-an-exception-thrown-in-a-nested-call.phix @@ -0,0 +1,35 @@ +constant U0 = 0, + U1 = 1 + +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 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 + +foo() diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call-1.rb b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call-1.rb deleted file mode 100644 index 688d38e720..0000000000 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call-1.rb +++ /dev/null @@ -1,25 +0,0 @@ -def foo - begin - bar - rescue U0 - puts "captured exception U0" - end -end - -def bar - baz -end - -def baz - raise $bazcount == 1 ? U0 : U1 -end - -class U0 < Exception -end - -class U1 < Exception -end - -for $bazcount in [1, 2] - foo -end diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call-2.rb b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call-2.rb deleted file mode 100644 index f64c21a9b8..0000000000 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call-2.rb +++ /dev/null @@ -1,3 +0,0 @@ -for $bazcount in [1, 2] - foo -end diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call-3.rb b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call-3.rb deleted file mode 100644 index 87e52f1840..0000000000 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call-3.rb +++ /dev/null @@ -1 +0,0 @@ -[1, 2].each {|$bazcount| foo} diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Zkl/exceptions-catch-an-exception-thrown-in-a-nested-call.zkl b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Zkl/exceptions-catch-an-exception-thrown-in-a-nested-call.zkl new file mode 100644 index 0000000000..6a634ea51f --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Zkl/exceptions-catch-an-exception-thrown-in-a-nested-call.zkl @@ -0,0 +1,7 @@ +class U0(Exception.Exception){fcn init{Exception.init("U0")}} +class U1(Exception.Exception){fcn init{Exception.init("U1")}} + +fcn foo{try{bar(U0)}catch(U0){} bar(U1)} +fcn bar(e){baz(e)} +fcn baz(e){throw(e)} +foo() diff --git a/Task/Exceptions/00DESCRIPTION b/Task/Exceptions/00DESCRIPTION index 011dfa6f12..2c9e8e7569 100644 --- a/Task/Exceptions/00DESCRIPTION +++ b/Task/Exceptions/00DESCRIPTION @@ -7,4 +7,7 @@ This task is to give an example of an exception handling routine and to "throw" a new exception. -Cf. [[Exceptions Through Nested Calls]] + +;Related task: +*   [[Exceptions Through Nested Calls]] +

    diff --git a/Task/Exceptions/ALGOL-68/exceptions-3.alg b/Task/Exceptions/ALGOL-68/exceptions-3.alg deleted file mode 100644 index ede38d00f4..0000000000 --- a/Task/Exceptions/ALGOL-68/exceptions-3.alg +++ /dev/null @@ -1,9 +0,0 @@ -FOOOBJECTNEW foo instance := foo base; # exception x routines are specific to a foo # - -FOOMEND prior foo exception x mend = foo exception x mended OF foo; -on foo exception x(foo instance, raise foo exception x); - -WHILE TRUE DO - # now manually raise example "foo exception x" # - raise foo exception x(foo instance) -OD; diff --git a/Task/Exceptions/ALGOL-68/exceptions-4.alg b/Task/Exceptions/ALGOL-68/exceptions-4.alg deleted file mode 100644 index c23e6dca0f..0000000000 --- a/Task/Exceptions/ALGOL-68/exceptions-4.alg +++ /dev/null @@ -1,8 +0,0 @@ - on foo exception x(foo instance, prior foo exception x mend); -... EXIT -except foo exception x: - SKIP # exception x caught code here ... # -# to continue to propagate an exception x is a bit more problematic...# -# and requires nesting/restoring prior "raise foo exception x"# - on foo exception x(foo instance, prior foo exception x mend); - raise foo exception x(foo instance) diff --git a/Task/Exceptions/Elena/exceptions-1.elena b/Task/Exceptions/Elena/exceptions-1.elena new file mode 100644 index 0000000000..9f3c853847 --- /dev/null +++ b/Task/Exceptions/Elena/exceptions-1.elena @@ -0,0 +1,5 @@ +class MyException :: Exception +{ + constructor new + <= new literal:"MyException raised". +} diff --git a/Task/Exceptions/Elena/exceptions-2.elena b/Task/Exceptions/Elena/exceptions-2.elena new file mode 100644 index 0000000000..b3da93a002 --- /dev/null +++ b/Task/Exceptions/Elena/exceptions-2.elena @@ -0,0 +1,4 @@ +foo + [ + MyException new; raise. + ] diff --git a/Task/Exceptions/Elena/exceptions-3.elena b/Task/Exceptions/Elena/exceptions-3.elena new file mode 100644 index 0000000000..2891d680ce --- /dev/null +++ b/Task/Exceptions/Elena/exceptions-3.elena @@ -0,0 +1,7 @@ +try(o foo) + { + on(MyException e) + [ + // handle exceptions of type MyException and derived + ] + } diff --git a/Task/Exceptions/Elena/exceptions-4.elena b/Task/Exceptions/Elena/exceptions-4.elena new file mode 100644 index 0000000000..c245e6f571 --- /dev/null +++ b/Task/Exceptions/Elena/exceptions-4.elena @@ -0,0 +1,4 @@ +o foo | if(:e) + [ + // handle any type of exception not handled by above catches + ]. diff --git a/Task/Exceptions/Gambas/exceptions.gambas b/Task/Exceptions/Gambas/exceptions.gambas new file mode 100644 index 0000000000..8118dc376b --- /dev/null +++ b/Task/Exceptions/Gambas/exceptions.gambas @@ -0,0 +1,30 @@ +Public Sub Main() +Dim iInteger As Integer + +MakeError +DivError + +iInteger = "2.54" + +Catch + Print Error.Text + +End +'______________________ +Public Sub DivError() + +Print 10 / 0 + +Catch + Print Error.Text + +End +'______________________ +Public Sub MakeError() + +Error.Raise("My Error") + +Catch + Print Error.Text + +End diff --git a/Task/Exceptions/jq/exceptions-1.jq b/Task/Exceptions/Jq/exceptions-1.jq similarity index 100% rename from Task/Exceptions/jq/exceptions-1.jq rename to Task/Exceptions/Jq/exceptions-1.jq diff --git a/Task/Exceptions/jq/exceptions-2.jq b/Task/Exceptions/Jq/exceptions-2.jq similarity index 100% rename from Task/Exceptions/jq/exceptions-2.jq rename to Task/Exceptions/Jq/exceptions-2.jq diff --git a/Task/Exceptions/Kotlin/exceptions.kotlin b/Task/Exceptions/Kotlin/exceptions.kotlin new file mode 100644 index 0000000000..1a53e12799 --- /dev/null +++ b/Task/Exceptions/Kotlin/exceptions.kotlin @@ -0,0 +1,23 @@ +// version 1.0.6 + +// In Kotlin all Exception classes derive from Throwable and, by convention, end with the word 'Exception' +class MyException (override val message: String?): Throwable(message) + +fun foo() { + throw MyException("Bad foo!") +} + +fun goo() { + try { + foo() + } + catch (me: MyException) { + println("Caught MyException due to '${me.message}'") + println("\nThe stack trace is:\n") + me.printStackTrace() + } +} + +fun main(args: Array) { + goo() +} diff --git a/Task/Exceptions/Logtalk/exceptions-1.logtalk b/Task/Exceptions/Logtalk/exceptions-1.logtalk deleted file mode 100644 index af5ff6800f..0000000000 --- a/Task/Exceptions/Logtalk/exceptions-1.logtalk +++ /dev/null @@ -1,23 +0,0 @@ -:- object(exceptions). - - :- public(double/2). - double(X, Y) :- - catch(double_it(X,Y), Error, handler(Error, Y)). - - handler(error(not_a_number(X), logtalk(This::double(X,Y), Sender)), Y) :- - % try to fix the error and resume computation; - % if not possible, rethrow the exception - ( catch(number_codes(Nx, X), _, fail) -> - double_it(Nx, Y) - ; throw(error(not_a_number(X), logtalk(This::double(X,Y), Sender))) - ). - - double_it(X, Y) :- - ( number(X) -> - Y is 2*X - ; this(This), - sender(Sender), - throw(error(not_a_number(X), logtalk(This::double(X,Y), Sender))) - ). - -:- end_object. diff --git a/Task/Exceptions/Logtalk/exceptions-2.logtalk b/Task/Exceptions/Logtalk/exceptions-2.logtalk deleted file mode 100644 index 3f420be11b..0000000000 --- a/Task/Exceptions/Logtalk/exceptions-2.logtalk +++ /dev/null @@ -1,10 +0,0 @@ -| ?- exceptions::double(1, Double). -Double = 2 -yes - -| ?- exceptions::double("1", Double). -Double = 2 -yes - -| ?- exceptions::double(a, Double). -uncaught exception: error(not_a_number(a),logtalk(exceptions::double(a,_),user)) diff --git a/Task/Exceptions/Maple/exceptions.maple b/Task/Exceptions/Maple/exceptions.maple new file mode 100644 index 0000000000..063d5e4289 --- /dev/null +++ b/Task/Exceptions/Maple/exceptions.maple @@ -0,0 +1,8 @@ +errorproc:=proc(n) +local a; +try +a:=1/n; +catch "numeric exception: division by zero": +error "Something went wrong when dividing." +end try; +end proc; diff --git a/Task/Exceptions/Phix/exceptions-1.phix b/Task/Exceptions/Phix/exceptions-1.phix new file mode 100644 index 0000000000..dd197e394a --- /dev/null +++ b/Task/Exceptions/Phix/exceptions-1.phix @@ -0,0 +1,3 @@ +throw("oh no") +throw(1) +throw(501,{"she",made[me],Do(it)}) diff --git a/Task/Exceptions/Phix/exceptions-2.phix b/Task/Exceptions/Phix/exceptions-2.phix new file mode 100644 index 0000000000..1806a3a6ab --- /dev/null +++ b/Task/Exceptions/Phix/exceptions-2.phix @@ -0,0 +1,9 @@ +try + one_of(these) +catch e + if e[E_CODE]=501 then + puts(1,"that's no excuse!\n") + else + throw(e) + end if +end try diff --git a/Task/Exceptions/PowerShell/exceptions-1.psh b/Task/Exceptions/PowerShell/exceptions-1.psh new file mode 100644 index 0000000000..cf0d6d8f23 --- /dev/null +++ b/Task/Exceptions/PowerShell/exceptions-1.psh @@ -0,0 +1 @@ +throw "Any error message." diff --git a/Task/Exceptions/PowerShell/exceptions-2.psh b/Task/Exceptions/PowerShell/exceptions-2.psh new file mode 100644 index 0000000000..f6a157f89b --- /dev/null +++ b/Task/Exceptions/PowerShell/exceptions-2.psh @@ -0,0 +1 @@ +throw [System.IO.FileNotFoundException] ".\temp.txt not found." diff --git a/Task/Exceptions/PowerShell/exceptions-3.psh b/Task/Exceptions/PowerShell/exceptions-3.psh new file mode 100644 index 0000000000..da54c99fb8 --- /dev/null +++ b/Task/Exceptions/PowerShell/exceptions-3.psh @@ -0,0 +1,12 @@ +try +{ + Get-Content -Path .\temp.txt +} +catch [System.IO.FileNotFoundException] +{ + Write-Host "File not found exception" +} +catch [System.Exception] +{ + Write-Host "Other exception" +} diff --git a/Task/Exceptions/PowerShell/exceptions-4.psh b/Task/Exceptions/PowerShell/exceptions-4.psh new file mode 100644 index 0000000000..3c74388dad --- /dev/null +++ b/Task/Exceptions/PowerShell/exceptions-4.psh @@ -0,0 +1 @@ +$Error[0] | Get-Member diff --git a/Task/Exceptions/REXX/exceptions.rexx b/Task/Exceptions/REXX/exceptions.rexx index 9d74874db8..836b4ea7b9 100644 --- a/Task/Exceptions/REXX/exceptions.rexx +++ b/Task/Exceptions/REXX/exceptions.rexx @@ -1,15 +1,13 @@ -/*REXX program demonstrates handling an exception; catching is via a label. */ +/*REXX program demonstrates handling an exception (negative #); catching is via a label.*/ do j=9 by -5 - say 'square root of' j "is" sqrt(j) + say 'the square root of ' j " is " sqrt(j) end /*j*/ -exit /*stick a fork in it, we're all done. */ - -.sqrtNeg: say 'illegal SQRT argument (argument is negative):' x -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9 - numeric digits 9; numeric form; h=d+6; if x<0 then signal .sqrtNeg - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ - numeric digits d; return (g/1) /*make complex if X < 0.*/ +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 diff --git a/Task/Exceptions/Stata/exceptions.stata b/Task/Exceptions/Stata/exceptions.stata new file mode 100644 index 0000000000..ea5a864cb4 --- /dev/null +++ b/Task/Exceptions/Stata/exceptions.stata @@ -0,0 +1,10 @@ +capture confirm file titanium.dta +if _rc { + if _rc==601 { + display "the file does not exist" + } + else { + * all other cases + display "there was an error with return code " _rc + } +} diff --git a/Task/Exceptions/Zkl/exceptions-1.zkl b/Task/Exceptions/Zkl/exceptions-1.zkl new file mode 100644 index 0000000000..23c09bba98 --- /dev/null +++ b/Task/Exceptions/Zkl/exceptions-1.zkl @@ -0,0 +1,4 @@ +try{ throw(Exception.BadDay) } +catch { println(__exception," was thrown") } +fallthrough { println("No exception was thrown") } +println("OK"); diff --git a/Task/Exceptions/Zkl/exceptions-2.zkl b/Task/Exceptions/Zkl/exceptions-2.zkl new file mode 100644 index 0000000000..604fcbfec9 --- /dev/null +++ b/Task/Exceptions/Zkl/exceptions-2.zkl @@ -0,0 +1,11 @@ +fcn f(b){ + try{ + onExitBlock("Exit code".println); + if (b) throw(Exception.BadDay) + } + catch{ println(__exception," was thrown") } + fallthrough{ println("No exception was thrown") } + println("OK"); +} +f(False); println("--------"); +f(True); diff --git a/Task/Executable-library/Phix/executable-library-1.phix b/Task/Executable-library/Phix/executable-library-1.phix new file mode 100644 index 0000000000..c14ab8f9c4 --- /dev/null +++ b/Task/Executable-library/Phix/executable-library-1.phix @@ -0,0 +1,64 @@ +function isMainOrInclude() +-- returns 1 if called from the main file, 0 if from an include +integer res + #ilASM{ + [32] + mov eax,[ebp+20] -- prev_ebp + mov eax,[eax+8] -- rtn + mov [res],eax + [64] + mov rax,[rbp+40] -- prev_ebp + mov rax,[rax+16] -- rtn + mov [res],rax + [] + } + return res=21 -- (21=T_maintls) +end function + +--global (if you want to be able to call this from test.exw) +function hailstone(atom n) +sequence s = {n} + while n!=1 do + if remainder(n,2)=0 then + n /= 2 + else + n = 3*n+1 + end if + s &= n + end while + return s +end function + +global function hailstone_count(atom n) +integer count = 1 + while n!=1 do + if remainder(n,2)=0 then + n /= 2 + else + n = 3*n+1 + end if + count += 1 + end while + return count +end function + +if isMainOrInclude() then + + sequence s = hailstone(27) + integer ls = length(s) + s[5..-5] = {".."} + puts(1,"hailstone(27) = ") + ? s + printf(1,"length = %d\n\n",ls) + + integer hmax = 1, imax = 1,count + for i=2 to 1e5-1 do + count = hailstone_count(i) + if count>hmax then + hmax = count + imax = i + end if + end for + + printf(1,"The longest hailstone sequence under 100,000 is %d with %d elements.\n",{imax,hmax}) +end if diff --git a/Task/Executable-library/Phix/executable-library-2.phix b/Task/Executable-library/Phix/executable-library-2.phix new file mode 100644 index 0000000000..2244876636 --- /dev/null +++ b/Task/Executable-library/Phix/executable-library-2.phix @@ -0,0 +1,11 @@ +include hail.exw + +sequence counts = {} +for i=1 to 100000 do + integer l = hailstone_count(i) + if length(counts)",h27[0,4].concat(","),"...", + h27[-4,*].concat(",")," length ",h27.len()); + +[2..0d100_000].pump(Void, // loop n from 2 to 100,000 + collatz, // generate Collatz sequence(n) + fcn(c,n){ // if new longest sequence, save length/C, return longest + if(c.len()>n[0]) n.clear(c.len(),c[0]); n}.fp1(L(0,0))) +.println(); diff --git a/Task/Executable-library/Zkl/executable-library-2.zkl b/Task/Executable-library/Zkl/executable-library-2.zkl new file mode 100644 index 0000000000..2cf221b012 --- /dev/null +++ b/Task/Executable-library/Zkl/executable-library-2.zkl @@ -0,0 +1,12 @@ +#!/home/craigd/Bin/zkl +collatz:=Import("hailstone",False,False,False).collatz; // don't run constructor +d:=Dictionary(); +[2..0d100_000].pump(Void, // loop n from 2 to 100,000 + collatz, // generate Collatz sequence(n) + 'wrap(c){ d.incV(c.len()) } // save length +); +println("Number of different lengths: ",d.len()); +longest:=(0).max(d.values); +mostFreqLen:=d.filter1('wrap([(k,v)]){ v==longest })[0]; +println("Most frequent length: %d; %d sequences of that length." + .fmt(mostFreqLen,longest)); diff --git a/Task/Execute-Brain----/68000-Assembly/execute-brain----.68000 b/Task/Execute-Brain----/68000-Assembly/execute-brain----.68000 new file mode 100644 index 0000000000..b90bd832e1 --- /dev/null +++ b/Task/Execute-Brain----/68000-Assembly/execute-brain----.68000 @@ -0,0 +1,331 @@ +; +; Brainfuck interpreter by Thorham +; +; 68000+ AmigaOs2+ +; +; Cell size is a byte +; + incdir "asminc:" + + include "dos/dosextens.i" + include "lvo/lvos.i" + +execBase equ 4 + +start + +; parse command line parameter + + move.l a0,fileName + + move.b (a0)+,d0 + beq exit ; no parameter + + cmp.b #'"',d0 ; filter out double quotes + bne .loop + + addq.l #1,fileName + +.loop + move.b (a0)+,d0 + + cmp.b #'"',d0 ; filter out double quotes + beq .done + + cmp.b #32,d0 + bge .loop + +.done + clr.b -(a0) ; end of string + +; open dos library + + move.l execBase,a6 + + lea dosName,a1 + moveq #36,d0 + jsr _LVOOpenLibrary(a6) + move.l d0,dosBase + beq exit + +; get stdin and stdout handles + + move.l dosBase,a6 + + jsr _LVOInput(a6) + move.l d0,stdIn + beq exit + + jsr _LVOOutput(a6) + move.l d0,stdOut + beq exit + + move.l stdIn,d1 + jsr _LVOFlush(a6) + +; open file + + move.l fileName,d1 + move.l #MODE_OLDFILE,d2 + jsr _LVOOpen(a6) + move.l d0,fileHandle + beq exit + +; examine file + + lea fileInfoBlock,a4 + + move.l fileHandle,d1 + move.l a4,d2 + jsr _LVOExamineFH(a6) + tst.w d0 + beq exit + +; exit if the file is a folder + + tst.l fib_DirEntryType(a4) + bge exit + +; allocate file memory + + move.l execBase,a6 + + move.l fib_Size(a4),d0 + beq exit ; exit if file is empty + clr.l d1 + jsr _LVOAllocVec(a6) + move.l d0,program + beq exit + +; read file + + move.l dosBase,a6 + + move.l fileHandle,d1 + move.l program,d2 + move.l fib_Size(a4),d3 + jsr _LVORead(a6) + tst d0 + ble exit ; exit if read didn't succeed + +; close file + + move.l fileHandle,d1 + jsr _LVOClose(a6) + clr.l fileHandle + +; clear tape (bss section is allocated by os but not cleared) + + lea tape,a0 + lea tapeEnd,a1 + +.loopClear + clr.b (a0)+ + cmp.l a0,a1 + bne .loopClear + +; interpreter + + move.l program,a2 + lea tape,a3 + + clr.l d2 + + move.l a2,d6 ; start of program + move.l a2,d7 ; end of program + add.l fib_Size(a4),d7 + +loop + move.b (a2)+,d2 + + cmp.b #">",d2 + beq .incPtr + + cmp.b #"<",d2 + beq .decPtr + + cmp.b #"+",d2 + beq .incMem + + cmp.b #"-",d2 + beq .decMem + + cmp.b #".",d2 + beq .outMem + + cmp.b #",",d2 + beq .inMem + + cmp.b #"[",d2 + beq .jmpForward + + cmp.b #"]",d2 + beq .jmpBack + +; next command + +.next + cmp.l d7,a2 ; test end of program + blt loop + +; end of program reached + + bra exit + +; command implementations + +.incPtr + addq.l #1,a3 + cmp.l #tapeEnd,a3 ; test end of tape + bge exit + bra .next + +.decPtr + subq.l #1,a3 + cmp.l #tape,a3 ; test start of tape + blt exit + bra .next + +.incMem + addq.b #1,(a3) + bra .next + +.decMem + subq.b #1,(a3) + bra .next + +.outMem + move.l stdOut,d1 + move.b (a3),d2 + jsr _LVOFPutC(a6) + bra .next + +.inMem + move.l stdIn,d1 + jsr _LVOFGetC(a6) + + cmp.b #27,d0 ; convert escape to 0 + bne .notEscape + moveq #0,d0 +.notEscape + move.b d0,(a3) + + bra .next + +.jmpForward + tst.b (a3) + bne .next + + move.l a2,a4 + clr.l d3 + +.loopf + cmp.l d7,a4 ; test end of program + bge exit + + move.b (a4)+,d2 + + cmp.b #"[",d2 + bne .lf + + addq.l #1,d3 + bra .loopf +.lf + cmp.b #"]",d2 + bne .loopf + + subq.l #1,d3 + bge .loopf + + move.l a4,a2 + bra .next + +.jmpBack + tst.b (a3) + beq .next + + move.l a2,a4 + clr.l d3 + +.loopb + move.b -(a4),d2 + + cmp.l d6,a4 ; test start of program + blt exit + + cmp.b #"]",d2 + bne .lb + + addq.l #1,d3 + bra .loopb +.lb + cmp.b #"[",d2 + bne .loopb + + subq.l #1,d3 + bgt .loopb + + move.l a4,a2 + bra .next + +; cleanup and exit + +exit + move.l dosBase,a6 + + move.l fileHandle,d1 + beq .noFile + jsr _LVOClose(a6) +.noFile + + move.l execBase,a6 + + move.l program,a1 + tst.l a1 + beq .noMem + jsr _LVOFreeVec(a6) +.noMem + + move.l dosBase,a1 + tst.l a1 + beq .noLib + jsr _LVOCloseLibrary(a6) +.noLib + + rts + +; data + + section data,data_p + +dosBase + dc.l 0 + +fileName + dc.l 0 + +fileHandle + dc.l 0 + +fileInfoBlock + dcb.b fib_SIZEOF + +stdIn + dc.l 0 + +stdOut + dc.l 0 + +program + dc.l 0 + +dosName + dc.b "dos.library",0 + +; tape memory + + section mem,bss_p + +tape + ds.b 1024*64 +tapeEnd diff --git a/Task/Execute-Brain----/Agena/execute-brain----.agena b/Task/Execute-Brain----/Agena/execute-brain----.agena new file mode 100644 index 0000000000..becfb717b7 --- /dev/null +++ b/Task/Execute-Brain----/Agena/execute-brain----.agena @@ -0,0 +1,89 @@ +# Brain**** interpreter + +# 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; + +# 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; diff --git a/Task/Execute-Brain----/BASIC/execute-brain----.basic b/Task/Execute-Brain----/BASIC/execute-brain-----1.basic similarity index 100% rename from Task/Execute-Brain----/BASIC/execute-brain----.basic rename to Task/Execute-Brain----/BASIC/execute-brain-----1.basic diff --git a/Task/Execute-Brain----/BASIC/execute-brain-----2.basic b/Task/Execute-Brain----/BASIC/execute-brain-----2.basic new file mode 100644 index 0000000000..d5199fc8c4 --- /dev/null +++ b/Task/Execute-Brain----/BASIC/execute-brain-----2.basic @@ -0,0 +1,88 @@ +REM +REM Brainfuck interpreter + +REM Get the separate arguments +SPLIT ARGUMENT$ BY " " TO arg$ SIZE dim + +IF dim < 2 THEN + PRINT "Usage: bf " + END +ENDIF + +REM Determine size +filesize = FILELEN(arg$[1]) + +REM Get the contents +OPEN arg$[1] FOR READING AS bf + +REM claim memory +txt = MEMORY(filesize) + +REM Read file into memory +GETBYTE txt FROM bf SIZE filesize + +CLOSE FILE bf + +REM Initialize work memory +mem = MEMORY(30000) + +REM This is The Pointer pointing to memory +thepointer = 0 + +REM This is the cursor pointing in the current program +cursor = 0 + +REM Start interpreting program +WHILE cursor < filesize DO + + command = PEEK(txt + cursor) + + SELECT command + CASE 62 + INCR thepointer + + CASE 60 + DECR thepointer + + CASE 43 + POKE mem + thepointer, PEEK(mem + thepointer) + 1 + + CASE 45 + POKE mem + thepointer, PEEK(mem + thepointer) - 1 + + CASE 46 + PRINT CHR$(PEEK(mem + thepointer)); + + CASE 44 + key = GETKEY + POKE mem + thepointer, key + + CASE 91 + jmp = 1 + IF ISFALSE(PEEK(mem + thepointer)) THEN + REPEAT + INCR cursor + IF PEEK(txt + cursor) = 91 THEN + INCR jmp + ELIF PEEK(txt + cursor) = 93 THEN + DECR jmp + END IF + UNTIL PEEK(txt + cursor) = 93 AND NOT(jmp) + END IF + + CASE 93 + jmp = 1 + IF ISTRUE(PEEK(mem + thepointer)) THEN + REPEAT + DECR cursor + IF PEEK(txt + cursor) = 93 THEN + INCR jmp + ELIF PEEK(txt + cursor) = 91 THEN + DECR jmp + END IF + UNTIL PEEK(txt + cursor) = 91 AND NOT(jmp) + END IF + END SELECT + + INCR cursor +WEND diff --git a/Task/Execute-Brain----/Comefrom0x10/execute-brain----.comefrom0x10 b/Task/Execute-Brain----/Comefrom0x10/execute-brain----.comefrom0x10 new file mode 100644 index 0000000000..165d7941c2 --- /dev/null +++ b/Task/Execute-Brain----/Comefrom0x10/execute-brain----.comefrom0x10 @@ -0,0 +1,183 @@ +pointer_alpha = 1/0 +pointer_numeric = 1/0 +tape_behind = '' +tape_ahead = 1/0 +tape_pos = 0 # only for debugging +array_behind = 1/0 +array_ahead = '' +set_tape_ahead = array_ahead +array_ahead = 1/0 +# +shift + comefrom if array_ahead is array_ahead + cdr = 1/0 + cdr = array_ahead + shift_tail = cdr + new_cell + comefrom shift if shift_tail is '' + itoa = 0 + shift_tail = itoa + car = 1/0 + car = array_ahead + array_behind = car array_behind + done = shift_tail + array_ahead = shift_tail + comefrom shift if array_ahead is done + +set_pointer_alpha = 1/0 +set_pointer_alpha + comefrom if set_pointer_alpha + atoi = set_pointer_alpha + cdr = tape_ahead + set_tape_ahead = set_pointer_alpha cdr + set_pointer_alpha = 1/0 + +set_tape_ahead = 1/0 +set_pointer_vals + comefrom if set_tape_ahead + tape_ahead = set_tape_ahead + car = tape_ahead + pointer_alpha = car + atoi = pointer_alpha + pointer_numeric = atoi + set_tape_ahead = 1/0 + +pointer_change = 1/0 +change_pointer_val + comefrom if pointer_change + car = tape_ahead + cdr = tape_ahead + itoa = pointer_numeric + pointer_change + set_tape_ahead = itoa cdr + pointer_change = 1/0 + +file = 0 # initialize to something other than undefined so jump from file works when read fails +read_path = argv +error_reading_program + comefrom file if file + 0 is 0 + 'Error: cannot read Brainfuck program at "' read_path '"' + '' + +program_loaded + comefrom file if file is file + program_behind = '' + program_ahead = file + + run + comefrom program_loaded + opcode = 1/0 + opcode_numeric = 1/0 + in_buffer = '' # cf0x10 stdin is line-buffered + jumping = 0 + moving = 1 + comefrom run + + comefrom execute if opcode_numeric is 0 + '' + execute + comefrom run if moving + # can be useful for debugging: + #program_ahead moving ':' jumping '@' tape_pos ':' pointer_numeric + car = program_ahead + atoi = car + opcode_numeric = atoi + opcode = car + opcode = 1/0 + + # + + program_forward + comefrom execute if moving > 0 + array_behind = program_behind + array_ahead = 1/0 + array_ahead = program_ahead + program_behind = array_behind + program_ahead = array_ahead + + forward_jump + comefrom execute if opcode is '[' + + jump + comefrom forward_jump if pointer_numeric is 0 + jumping = jumping + 1 + moving = 1 + match_brace + comefrom forward_jump if jumping < 0 + jumping = jumping + 1 + stop_jump + comefrom match_brace if jumping is 0 + moving = 1 + + program_backward + comefrom execute if moving < 0 + array_behind = program_ahead + array_ahead = 1/0 + array_ahead = program_behind + program_behind = array_ahead + program_ahead = array_behind + + backward_jump + comefrom execute if opcode is ']' + + jump + comefrom backward_jump if pointer_numeric > 0 + jumping = jumping - 1 + moving = -1 + match_brace + comefrom backward_jump if jumping > 0 + jumping = jumping - 1 + stop_jump + comefrom match_brace if jumping is 0 + moving = 1 + + op + comefrom execute if opcode + + moving = 1 + do_op = opcode + comefrom op if jumping + # + forward + comefrom op if do_op is '>' + tape_pos = tape_pos + 1 + array_ahead = 1/0 + array_behind = tape_behind + array_ahead = tape_ahead + tape_behind = array_behind + set_tape_ahead = array_ahead + backward + comefrom op if do_op is '<' + tape_pos = tape_pos - 1 + array_ahead = 1/0 + array_behind = tape_ahead + array_ahead = tape_behind + tape_behind = array_ahead + set_tape_ahead = array_behind + + increment + comefrom op if do_op is '+' + pointer_change = 1 + decrement + comefrom op if do_op is '-' + pointer_change = -1 + + print + comefrom op if do_op is '.' + pointer_alpha... + read + comefrom op if do_op is ',' + # + cdr = 1/0 + cdr = in_buffer + car = in_buffer + set_pointer_alpha = car + cdr = in_buffer + in_buffer = cdr + comefrom stdin if stdin + 0 is 0 + # + block_for_input + comefrom read if cdr is '' + stdin = '' + in_buffer = stdin + cdr = in_buffer + comefrom stdin if stdin + 0 is 0 diff --git a/Task/Execute-Brain----/Dodo0/execute-brain----.dodo0 b/Task/Execute-Brain----/Dodo0/execute-brain----.dodo0 new file mode 100644 index 0000000000..e8db195aa1 --- /dev/null +++ b/Task/Execute-Brain----/Dodo0/execute-brain----.dodo0 @@ -0,0 +1,243 @@ +#Import some functions +clojure('count', 1) -> size +clojure('nth', 2) -> charAt +clojure('inc', 1) -> inc +clojure('dec', 1) -> dec +clojure('char', 1) -> char +clojure('int', 1) -> int +clojure('read-line', 0) -> readLine + +#The characters we will need +charAt("\n", 0) -> newLine +charAt("@", 0) -> exitCommand +charAt("+", 0) -> incrCommand +charAt("-", 0) -> decrCommand +charAt("<", 0) -> shlCommand +charAt(">", 0) -> shrCommand +charAt(".", 0) -> printCommand +charAt(",", 0) -> inputCommand +charAt("[", 0) -> repeatCommand +charAt("]", 0) -> endCommand + +#Read a character from a line of input. +fun readChar -> return +( + readLine() -> line + size(line) -> length + + #Return the ith character and a continuation + fun nextFromLine -> i, return + ( + '='(i, length) -> eol + if (eol) -> + ( + return(newLine, readChar) #end of line + ) + | + charAt(line, i) -> value + inc(i) -> i + fun next (-> return) nextFromLine(i, return) | next + return(value, next) + ) + | nextFromLine + + nextFromLine(0, return) #first character (position 0) +) +| readChar + +#Define a buffer as a value and a left and right stack +fun empty (-> return, throw) throw("Error: out of bounds") | empty +fun fill (-> return, throw) return(0, fill) | fill + +fun makeBuffer -> value, left, right, return +( + fun buffer (-> return) return(value, left, right) | buffer + return(buffer) +) +| makeBuffer + +fun push -> value, stack, return +( + fun newStack (-> return, throw) return(value, stack) | newStack + return(newStack) +) +| push + +#Brainf*** operations +fun noop -> buffer, input, return +( + return(buffer, input) +) +| noop + +fun selectOp -> command, return +( + '='(command, incrCommand) -> eq + if (eq) -> + ( + fun increment -> buffer, input, return + ( + buffer() -> value, left, right + inc(value) -> value + makeBuffer(value, left, right) -> buffer + return(buffer, input) + ) + | increment + return(increment) + ) + | + '='(command, decrCommand) -> eq + if (eq) -> + ( + fun decrement -> buffer, input, return + ( + buffer() -> value, left, right + dec(value) -> value + makeBuffer(value, left, right) -> buffer + return(buffer, input) + ) + | decrement + return(decrement) + ) + | + '='(command, shlCommand) -> eq + if (eq) -> + ( + fun shiftLeft -> buffer, input, return + ( + buffer() -> value, left, right + push(value, right) -> right + left() -> value, left + ( + makeBuffer(value, left, right) -> buffer + return(buffer, input) + ) + | message + println(message) -> + exit() + ) + | shiftLeft + return(shiftLeft) + ) + | + '='(command, shrCommand) -> eq + if (eq) -> + ( + fun shiftRight -> buffer, input, return + ( + buffer() -> value, left, right + push(value, left) -> left + right() -> value, right + ( + makeBuffer(value, left, right) -> buffer + return(buffer, input) + ) + | message + println(message) -> + exit() + ) + | shiftRight + return(shiftRight) + ) + | + '='(command, printCommand) -> eq + if (eq) -> + ( + fun putChar -> buffer, input, return + ( + buffer() -> value, left, right + char(value) -> value + 'print'(value) -> dummy + 'flush'() -> dummy + return(buffer, input) + ) + | putChar + return(putChar) + ) + | + '='(command, inputCommand) -> eq + if (eq) -> + ( + fun getChar -> buffer, input, return + ( + input() -> letter, input + int(letter) -> letter + buffer() -> value, left, right + makeBuffer(letter, left, right) -> buffer + return(buffer, input) + ) + | getChar + return(getChar) + ) + | + return(noop) +) +| selectOp + +#Repeat until zero operation +fun whileLoop -> buffer, input, continue, break +( + buffer() -> value, left, right + '='(value, 0) -> zero + if (zero) -> + ( + break(buffer, input) + ) + | + continue(buffer, input) -> buffer, input + whileLoop(buffer, input, continue, break) +) +| whileLoop + +#Convert the Brainf*** program into dodo0 instructions +fun compile -> input, endmark, return +( + input() -> command, input + + '='(command, endmark) -> eq + if (eq) -> + ( + return(noop, input) #the end, stop compiling + ) + | + #Put in sequence the current operation and the rest of the program + fun chainOp -> op, input, return + ( + compile(input, endmark) -> program, input + fun exec -> buffer, input, return + ( + op(buffer, input) -> buffer, input + program(buffer, input, return) + ) + | exec + return(exec, input) + ) + | chainOp + + '='(command, repeatCommand) -> eq + if (eq) -> + ( + compile(input, endCommand) -> body, input #compile until "]" + + #Repeat the loop body until zero + fun repeat -> buffer, input, return + ( + whileLoop(buffer, input, body, return) + ) + | repeat + chainOp(repeat, input, return) + ) + | + selectOp(command) -> op + chainOp(op, input, return) +) +| compile + +#Main program +compile(readChar, exitCommand) -> program, input +makeBuffer(0, empty, fill) -> buffer +input() -> nl, input #consume newline from input + +#Execute the program instructions +program(buffer, input) -> buffer, input +exit() diff --git a/Task/Execute-Brain----/Elena/execute-brain----.elena b/Task/Execute-Brain----/Elena/execute-brain----.elena deleted file mode 100644 index 5f77c51cbb..0000000000 --- a/Task/Execute-Brain----/Elena/execute-brain----.elena +++ /dev/null @@ -1,82 +0,0 @@ -statement ::= next; -statement ::= prev; -statement ::= inc; -statement ::= dec; -statement ::= out; -statement ::= in; -statement ::= "[" while; -statement ::= idle; - -next ::= ">"; -prev ::= "<"; -inc ::= "+"; -dec ::= "-"; -out ::= "."; -in ::= ","; -idle ::= $any; - -while ::= statement while_r; - -while_r ::= "]"; -while_r ::= statement while_r; - -tape ::= statement statements; - -statements ::= statement statements; -statements ::= $eps; - -start ::= tape; - -tape => - // 1: append - &subject - // 2: goto - &subject - // 3: loop - &subject - // 4: inc action - &1 1 &echo - // 5: dec action - &1 -1 &echo - // 6: next action - &2 1 &echo - // 7: prev action - &2 -1 &echo - // 8: output action - &__write &nil 'program'output &wrap - // 9: group - &nil - sys'dynamics'groupvariable - &std'basic'factory'array_size &sys'vm'routines'egetprop 1024 &prop - &std'basic'factory'pattern &sys'vm'routines'egetprop 0 std'basic'widecharvar &prop - &union2 - std'basic'factory'patternarrayfactory - std'basic'factory'newarray - 0 ^refer - ~ sys'dynamics'group_member ^append - // :: append method - &1 &__append &9 &prop - ~ sys'dynamics'group_member ^append - // :: goto method - &2 &__append &std'dictionary'index &9 &wrap &prop - ~ sys'dynamics'group_member ^append - // :: loop method - &3 &__run &std'patterns'ewhilenotzero &9 &wrap &prop - ~ sys'dynamics'group_member ^append - - // 10: in action - &__save &__get &nil 'program'input &nil &action &wrap - - // build command batch - &cast - $body - &9 - ^ invoke; - -inc => &4 |= $body; -dec => &5 |= $body; -next => &6 |= $body; -prev => &7 |= $body; -out => &8 |= $body; -in => &10 |= $body; -while => &3 &__eval &cast $body &wrap &echo |=; diff --git a/Task/Execute-Brain----/Fortran/execute-brain-----1.f b/Task/Execute-Brain----/Fortran/execute-brain-----1.f index 70a29f07bc..a44138f8e3 100644 --- a/Task/Execute-Brain----/Fortran/execute-brain-----1.f +++ b/Task/Execute-Brain----/Fortran/execute-brain-----1.f @@ -10,29 +10,21 @@ I = 1 !First element of the prog. DO WHILE(I.LE.LEN(PROG)) !Off the end yet? - C = PROG(I:I) !Load the opcode fingered by I. - I = I + 1 !Advance one. The classic. - SELECT CASE(C) !Now decode the instruction. - CASE(">") !Move the data finger one place right. - D = D + 1 - CASE("<") !Move the data finger one place left. - D = D - 1 - CASE("+") !Add one to the fingered datum. - STORE(D) = CHAR(ICHAR(STORE(D)) + 1) - CASE("-") !Subtract one. - STORE(D) = CHAR(ICHAR(STORE(D)) - 1) - CASE(".") !Write a character. - WRITE (MSG,1) STORE(D) - CASE(",") !Read a character. - READ (KBD,1) STORE(D) - CASE("[") !Conditionally, surge forward. - IF (ICHAR(STORE(D)).EQ.0) CALL SEEK(+1) - CASE("]") !Conditionally, retreat. - IF (ICHAR(STORE(D)).NE.0) CALL SEEK(-1) - CASE DEFAULT !For all others, - !Do nothing. - END SELECT !That was simple. - END DO !See what comes next. + C = PROG(I:I) !Load the opcode fingered by I. + I = I + 1 !Advance one. The classic. + SELECT CASE(C) !Now decode the instruction. + CASE(">"); D = D + 1 !Move the data finger one place right. + CASE("<"); D = D - 1 !Move the data finger one place left. + CASE("+"); STORE(D) = CHAR(ICHAR(STORE(D)) + 1) !Add one to the fingered datum. + CASE("-"); STORE(D) = CHAR(ICHAR(STORE(D)) - 1) !Subtract one. + CASE("."); WRITE (MSG,1) STORE(D) !Write a character. + CASE(","); READ (KBD,1) STORE(D) !Read a character. + CASE("["); IF (ICHAR(STORE(D)).EQ.0) CALL SEEK(+1) !Conditionally, surge forward. + CASE("]"); IF (ICHAR(STORE(D)).NE.0) CALL SEEK(-1) !Conditionally, retreat. + CASE DEFAULT !For all others, + !Do nothing. + END SELECT !That was simple. + END DO !See what comes next. 1 FORMAT (A1,$) !One character, no advance to the next line. CONTAINS !Now for an assistant. diff --git a/Task/Execute-Brain----/Fortran/execute-brain-----2.f b/Task/Execute-Brain----/Fortran/execute-brain-----2.f index aff35b0fb3..79c7b10b54 100644 --- a/Task/Execute-Brain----/Fortran/execute-brain-----2.f +++ b/Task/Execute-Brain----/Fortran/execute-brain-----2.f @@ -79,7 +79,7 @@ Closedown. END IF !Rather than just one at a time. END IF !Curse the double evaluation of WHILE(L < LEN(PROG) & ...) END FUNCTION RATTLE !Computers excel at counting. - END SUBROUTINE BRAINFORT!They only need be direction as to what to count... + END SUBROUTINE BRAINFORT!Their only need be direction as to what to count... END MODULE BRAIN !Simple in itself. PROGRAM POKE !A tester. diff --git a/Task/Execute-Brain----/Groovy/execute-brain-----1.groovy b/Task/Execute-Brain----/Groovy/execute-brain-----1.groovy index fb3a85ebad..9d125dd0d0 100644 --- a/Task/Execute-Brain----/Groovy/execute-brain-----1.groovy +++ b/Task/Execute-Brain----/Groovy/execute-brain-----1.groovy @@ -4,18 +4,17 @@ class BrainfuckProgram { def instructionPointer = 0, dataPointer = 0 def execute() { - while (instructionPointer < program.size()) { + while (instructionPointer < program.size()) switch(program[instructionPointer++]) { case '>': dataPointer++; break; case '<': dataPointer--; break; - case '+': memory[dataPointer] = memoryValue + 1; break; - case '-': memory[dataPointer] = memoryValue - 1; break; - case ',': memory[dataPointer] = System.in.read(); break; - case '.': print((char)memoryValue); break; - case '[': handleLoopStart(); break; - case ']': handleLoopEnd(); break; + case '+': memory[dataPointer] = memoryValue + 1; break + case '-': memory[dataPointer] = memoryValue - 1; break + case ',': memory[dataPointer] = System.in.read(); break + case '.': print String.valueOf(Character.toChars(memoryValue)); break + case '[': handleLoopStart(); break + case ']': handleLoopEnd(); break } - } } private getMemoryValue() { memory[dataPointer] ?: 0 } @@ -23,13 +22,12 @@ class BrainfuckProgram { private handleLoopStart() { if (memoryValue) return - int depth = 1; - while (instructionPointer < program.size()) { + int depth = 1 + while (instructionPointer < program.size()) switch(program[instructionPointer++]) { - case '[': depth++; break; - case ']': if (!(--depth)) return; + case '[': depth++; break + case ']': if (!(--depth)) return } - } throw new IllegalStateException('Could not find matching end bracket') } @@ -37,8 +35,8 @@ class BrainfuckProgram { int depth = 0 while (instructionPointer >= 0) { switch(program[--instructionPointer]) { - case ']': depth++; break; - case '[': if (!(--depth)) return; break; + case ']': depth++; break + case '[': if (!(--depth)) return; break } } throw new IllegalStateException('Could not find matching start bracket') diff --git a/Task/Execute-Brain----/Kotlin/execute-brain----.kotlin b/Task/Execute-Brain----/Kotlin/execute-brain----.kotlin new file mode 100644 index 0000000000..41ac3e8914 --- /dev/null +++ b/Task/Execute-Brain----/Kotlin/execute-brain----.kotlin @@ -0,0 +1,51 @@ +// version 1.1.2 + +class Brainf__k(val prog: String, memSize: Int) { + private val mem = IntArray(memSize) + private var ip = 0 + private var dp = 0 + private val memVal get() = mem.getOrElse(dp) { 0 } + + fun execute() { + while (ip < prog.length) { + when (prog[ip++]) { + '>' -> dp++ + '<' -> dp-- + '+' -> mem[dp] = memVal + 1 + '-' -> mem[dp] = memVal - 1 + ',' -> mem[dp] = System.`in`.read() + '.' -> print(memVal.toChar()) + '[' -> handleLoopStart() + ']' -> handleLoopEnd() + } + } + } + + private fun handleLoopStart() { + if (memVal != 0) return + var depth = 1 + while (ip < prog.length) { + when (prog[ip++]) { + '[' -> depth++ + ']' -> if (--depth == 0) return + } + } + throw IllegalStateException("Could not find matching end bracket") + } + + private fun handleLoopEnd() { + var depth = 0 + while (ip >= 0) { + when (prog[--ip]) { + ']' -> depth++ + '[' -> if (--depth == 0) return + } + } + throw IllegalStateException("Could not find matching start bracket") + } +} + +fun main(args: Array) { + val prog = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>." + Brainf__k(prog, 10).execute() +} diff --git a/Task/Execute-Brain----/Nimrod/execute-brain----.nimrod b/Task/Execute-Brain----/Nimrod/execute-brain----.nimrod deleted file mode 100644 index ca51153b63..0000000000 --- a/Task/Execute-Brain----/Nimrod/execute-brain----.nimrod +++ /dev/null @@ -1,63 +0,0 @@ -import strutils - -proc jumpBackward(pos: var int, program: string) = - var level = 1 - while pos > 0 and level != 0: - dec pos - case program[pos] - of '[': - dec level - of ']': - inc level - else: - discard 1 - dec pos - -proc jumpForward(pos: var int, program: string) = - var level = 1 - while pos < program.len and level != 0: - inc pos - case program[pos] - of ']': - inc level - of '[': - dec level - else: - discard 1 - -proc bf(program: string) = - var tape: array[0..20, int] - var pointer = 0 - var pos = 0 - var indent = 0 - - while pos < program.len: - var token = program[pos] - case token - of '+': - inc tape[pointer] - of '-': - dec tape[pointer] - of ',': - tape[pointer] = int(stdin.readChar()) - of '.': - stdout.write(chr(tape[pointer])) - of '[': - if tape[pointer] == 0: - jumpForward(pos, program) - of ']': - if tape[pointer] != 0: - jumpBackward(pos, program) - of '>': - inc pointer - of '<': - dec pointer - else: - discard 1 - inc pos - -var addition = ",>++++++[<-------->-],[<+>-]<." -var hello_world = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>." - -bf(addition) -# bf(hello_world) diff --git a/Task/Execute-Brain----/Objeck/execute-brain----.objeck b/Task/Execute-Brain----/Objeck/execute-brain----.objeck new file mode 100644 index 0000000000..7f53c93ade --- /dev/null +++ b/Task/Execute-Brain----/Objeck/execute-brain----.objeck @@ -0,0 +1,70 @@ +class Brainfu_k { + @program : String; @mem : Int[]; + @ip : Int; @dp : Int; + + New(program : String, size : Int) { + @program := program; + @mem := Int → New[size]; + } + + function : Main(args : String[]) ~ Nil { + if(args → Size() = 2) { + Brainfu_k → New(args[0], args[1] → ToInt()) → Execute(); + }; + } + + method : Execute() ~ Nil { + while(@ip < @program → Size()) { + instr := @program → Get(@ip); + select(instr) { + label '>': { @dp += 1; } + label '<': { @dp -= 1; } + label '+': { @mem[@dp] := @mem[@dp] + 1; } + label '-': { @mem[@dp] := @mem[@dp] - 1; } + label '.': { value := @mem[@dp] → As(Char); value → Print(); } + label ',': { @mem[@dp] := Read(); } + label '[': { JumpForward(); } + label ']': { JumpBack(); } + }; + @ip += 1; + }; + } + + method : JumpForward() ~ Nil { + depth := 1; + if(@mem[@dp] = 0) { + while(@ip < @program → Size()) { + instr := @program → Get(@ip); + if(instr = ']') { + depth -= 1; if(depth = 0) { return; }; + } + else if(instr = '[') { depth += 1; }; + @ip += 1; + }; + "*** Unbalanced jump ***" → ErrorLine(); + Runtime → Exit(1); + }; + } + + method : JumpBack() ~ Nil { + depth := 1; + if(@mem[@dp] <> 0) { + while(@ip > 0) { + @ip -= 1; + instr := @program → Get(@ip); + if(instr = '[') { + depth -= 1; if(depth = 0) { return; }; + } + else if(instr = ']') { depth += 1; }; + }; + "*** Unbalanced jump ***" → ErrorLine(); + Runtime → Exit(1); + }; + } + + method : Read() ~ Int { + in := IO.Console → ReadString(); + if(in → Size() > 0) { return in → ToInt(); }; + return 0; + } +} diff --git a/Task/Execute-Brain----/Ol/execute-brain----.ol b/Task/Execute-Brain----/Ol/execute-brain----.ol new file mode 100644 index 0000000000..2039f3b820 --- /dev/null +++ b/Task/Execute-Brain----/Ol/execute-brain----.ol @@ -0,0 +1,40 @@ +(define (bf program stack-length) + (let ((program (string-append program "]")) + (program-counter 0) + (stack (make-vector stack-length 0)) + (stack-pointer 0)) + (letrec ((skip (lambda (PC sp) + (let loop ((pc PC) (sp sp)) + (let ((ch (string-ref program pc)) + (pc (+ pc 1))) + (case ch + (#\] (list pc sp)) + (#\[ (apply loop (skip pc sp))) + (else + (loop pc sp))))))) + (step (lambda (PC SP) + (let loop ((pc PC) (sp SP)) + (let ((ch (string-ref program pc)) + (pc (+ pc 1))) + (case ch + (#\] (list (- PC 1) sp)) + (#\[ (if (eq? (vector-ref stack sp) 0) + (apply loop (skip pc sp)) + (apply loop (step pc sp)))) + (#\+ (set-ref! stack sp (+ (vector-ref stack sp) 1)) + (loop pc sp)) + (#\- (set-ref! stack sp (- (vector-ref stack sp) 1)) + (loop pc sp)) + (#\> (loop pc (+ sp 1))) + (#\< (loop pc (- sp 1))) + (#\. (display (make-string 1 (vector-ref stack sp))) + (loop pc sp)) + (else + (loop pc sp)))))))) + (step 0 0)))) + +; testing: +; (bf ",++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>." 30000) +; ==> Hello World! +; (bf ">>++++[<++++[<++++>-]>-]<<.[-]++++++++++." 30000) +; ==> @ diff --git a/Task/Execute-Brain----/Pascal/execute-brain----.pascal b/Task/Execute-Brain----/Pascal/execute-brain----.pascal new file mode 100644 index 0000000000..269d056b2f --- /dev/null +++ b/Task/Execute-Brain----/Pascal/execute-brain----.pascal @@ -0,0 +1,96 @@ +program rcExceuteBrainF; + +uses + Crt; + +Const + DataSize= 1024; // Size of Data segment + MaxNest= 1000; // Maximum nesting depth of [] + +procedure ExecuteBF(Source: string); +var + Dp: pByte; // Used as the Data Pointer + DataSeg: Pointer; // Start of the DataSegment (Cell 0) + Ip: pChar; // Used as instruction Pointer + LastIp: Pointer; // Last adr of code. + JmpStack: array[0..MaxNest-1] of pChar; // Stack to Keep track of active "[" locations + JmpPnt: Integer; // Stack pointer ^^ + JmpCnt: Word; // Used to count brackets when skipping forward. + + +begin + + // Set up then data segment + getmem(DataSeg,dataSize); + dp:=DataSeg; + fillbyte(dp^,dataSize,0); + + // Set up the JmpStack + JmpPnt:=-1; + + // Set up Instruction Pointer + Ip:=@Source[1]; + LastIp:=@Source[length(source)]; + if Ip=nil then exit; + + // Main Execution loop + repeat { until Ip > LastIp } + Case Ip^ of + '<': dec(dp); + '>': inc(dp); + '+': inc(dp^); + '-': dec(dp^); + '.': write(stdout,chr(dp^)); + ',': dp^:=ord(readkey); + '[': if dp^=0 then + begin + // skip forward until matching bracket; + JmpCnt:=1; + while (JmpCnt>0) and (ip<=lastip) do + begin + inc(ip); + Case ip^ of + '[': inc(JmpCnt); + ']': dec(JmpCnt); + #0: begin + Writeln(StdErr,'Error brackets don''t match'); + halt; + end; + end; + end; + end else begin + // Add location to Jump stack + inc(JmpPnt); + JmpStack[jmpPnt]:=ip; + end; + ']': if dp^>0 then + // Jump Back to matching [ + ip:=JmpStack[jmpPnt] + else + // Remove Jump from stack + dec(jmpPnt); + end; + inc(ip); + until Ip>lastIp; + freemem(DataSeg,dataSize); +end; + +Const + HelloWorldWiki = '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>'+ + '---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.'; + + pressESCtoCont = '>[-]+++++++[<++++++++++>-]<->>[-]+++++++[<+++++++++++'+ + '+>-]<->>[-]++++[<++++++++>-]+>[-]++++++++++[<++++++++'+ + '++>-]>[-]++++++++[<++++++++++++++>-]<.++.+<.>..<<.<<.'+ + '-->.<.>>.>>+.-----.<<.[<<+>>-]<<.>>>>.-.++++++.<++++.'+ + '+++++.>+.<<<<++.>+[>+<--]>++++...'; + waitForEsc = '[-]>[-]++++[<+++++++>-]<->[-]>+[[-]<<[>+>+<<-]'+'>>[<'+ + '<+>>-],<[->-<]>]'; + +begin + // Execute "Hello World" example from Wikipedia + ExecuteBF(HelloWorldWiki); + + // Print text "press ESC to continue....." and wait for ESC to be pressed + ExecuteBF(pressESCtoCont+waitForEsc); +end. diff --git a/Task/Execute-Brain----/VBScript/execute-brain----.vb b/Task/Execute-Brain----/VBScript/execute-brain----.vb new file mode 100644 index 0000000000..fd43154b98 --- /dev/null +++ b/Task/Execute-Brain----/VBScript/execute-brain----.vb @@ -0,0 +1,76 @@ +'Execute BrainFuck +'VBScript Implementation + +'The Main Interpreter +Function BFInpt(s, sp, d, dp, i, ip, o) + While sp < Len(s) + Select Case Mid(s, sp + 1, 1) + Case "+" + newd = Asc(d(dp)) + 1 + If newd > 255 Then newd = newd Mod 256 'To take account of values over 255 + d(dp) = Chr(newd) + Case "-" + newd = Asc(d(dp)) - 1 + If newd < 0 Then newd = (newd Mod 256) + 256 'To take account of negative values + d(dp) = Chr(newd) + Case ">" + dp = dp + 1 + If dp > UBound(d) Then + ReDim Preserve d(UBound(d) + 1) + d(dp) = Chr(0) + End If + Case "<" + dp = dp - 1 + Case "." + o = o & d(dp) + Case "," + If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1) + Case "[" + If Asc(d(dp)) = 0 Then + bracket = 1 + While bracket And sp < Len(s) + sp = sp + 1 + If Mid(s, sp + 1, 1) = "[" Then + bracket = bracket + 1 + ElseIf Mid(s, sp + 1, 1) = "]" Then + bracket = bracket - 1 + End If + WEnd + Else + pos = sp - 1 + sp = sp + 1 + If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos + End If + Case "]" + BFInpt = Asc(d(dp)) <> 0 + Exit Function + End Select + sp = sp + 1 + WEnd +End Function + +'This Prepares the Intepreter +Function BFuck(source, input) + Dim data() : ReDim data(0) + data(0) = Chr(0) + DataPtr = 0 + SrcPtr = 0 + InputPtr = 0 + output = "" + + BFInpt source , SrcPtr , _ + data , DataPtr , _ + input , InputPtr , _ + output + BFuck = output +End Function + + +'Sample Run +'The input is a string. The first character will be scanned by the first comma +'in the code, the next character will be scanned by the next comma, and so on. + +code = ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>" & _ + ">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++." +inpstr = "" +WScript.StdOut.Write BFuck(code, inpstr) diff --git a/Task/Execute-Brain----/Zkl/execute-brain-----1.zkl b/Task/Execute-Brain----/Zkl/execute-brain-----1.zkl new file mode 100644 index 0000000000..7fdd36d0d4 --- /dev/null +++ b/Task/Execute-Brain----/Zkl/execute-brain-----1.zkl @@ -0,0 +1,29 @@ +fcn bf(pgm,input=""){ pgm=pgm.text; // handle both String and Data + const CELLS=0d30_000; + if(Void==pgm.span("[","]")){ println("Mismatched brackets"); return(); } + fcn(code,z,jmpTable){ // build jump table (for [ & ]) + if(span:=code.span("[","]")){ + a,b:=span; b+=a-1; jmpTable[a+z]=b+z; jmpTable[b+z]=a+z; + self.fcn(code[a+1,b-a-1],z+a+1,jmpTable); + self.fcn(code[b+1,*],z+b+1,jmpTable); + } + }(pgm,0,jmpTable:=Dictionary()); + + tape:=CELLS.pump(Data(CELLS,Int),0); + ip:=dp:=0; input=input.walker(); + try{ + while(1){ + switch(pgm[ip]){ + case(">"){ dp+=1 } + case("<"){ dp-=1 } + case("+"){ tape[dp]=tape[dp]+1 } + case("-"){ tape[dp]=tape[dp]-1 } + case("."){ tape[dp].toChar().print() } + case(","){ c:=input._next(); tape[dp]=(c and input.value or 0); } + case("["){ if(0==tape[dp]){ ip=jmpTable[ip] }} + case("]"){ if(tape[dp]) { ip=jmpTable[ip] }} + } + ip+=1; + } // while + }catch(IndexError){} // read past end of tape == end of program +} diff --git a/Task/Execute-Brain----/Zkl/execute-brain-----2.zkl b/Task/Execute-Brain----/Zkl/execute-brain-----2.zkl new file mode 100644 index 0000000000..2cc296bdc1 --- /dev/null +++ b/Task/Execute-Brain----/Zkl/execute-brain-----2.zkl @@ -0,0 +1,27 @@ + // print Hello World! +bf("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++.." + "+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."); + + // print @ +bf(">>++++[<++++[<++++>-]>-]<<.[-]++++++++++."); + + // read 3 characters, inc by 1 and print: "abc"-->"bcd" +bf(",>,>,><<<[+.>]","abc"); println(); + +bf(",>++++++[<-------->-],[<+>-]<.","23"); println(); // add two digits + + // "Enter your name:", prints name backwards +bf(">+++++++++++++++++++++++++++++++++++++++++" + "++++++++++++++++++++++++++++.++++++++++++++" + "+++++++++++++++++++++++++++.++++++.-------------" + "--.+++++++++++++.>++++++++++++++++++++++++++" + "++++++.<+++++++.----------.++++++.---.>.<----.----------" + "---.++++++++++++.--------.-----------------------------------" + "--------.>.<>>>+[>,----------]++++++++++.<[+++++++++" + "+.<][<]","Sam Iam\n"); + + // word count +bf(File("wc.b").read(),"This\n is a test"); + + // rot13 +bf(File("rot13.b").read(),"This is a test 123"); diff --git a/Task/Execute-HQ9+/C++/execute-hq9+.cpp b/Task/Execute-HQ9+/C++/execute-hq9+.cpp index 2679a199a2..78424a77f9 100644 --- a/Task/Execute-HQ9+/C++/execute-hq9+.cpp +++ b/Task/Execute-HQ9+/C++/execute-hq9+.cpp @@ -1,7 +1,8 @@ void runCode(string code) { int c_len = code.length(); - int accumulator=0, bottles; + unsigned accumulator=0; + int bottles; for(int i=0;i match { + when amount == 1 then "One bottle" + when amount == 0 then "No bottles" + otherwise amount + " bottles" +} + +function ninety9Bottles = { + foreach n in [99..0]: decrementBy(1) { + println(bottles(n) + " of beer on the wall,") + println(bottles(n) + " of beer!") + println("Take one down, pass it around,") + println(bottles(n - 1) + " of beer on the wall!") + } +} diff --git a/Task/Execute-HQ9+/Kotlin/execute-hq9+.kotlin b/Task/Execute-HQ9+/Kotlin/execute-hq9+.kotlin new file mode 100644 index 0000000000..71e9ddd737 --- /dev/null +++ b/Task/Execute-HQ9+/Kotlin/execute-hq9+.kotlin @@ -0,0 +1,33 @@ +// version 1.1.3 + +fun hq9plus(code: String) { + var acc = 0 + val sb = StringBuilder() + for (c in code) { + sb.append( + when (c) { + 'h', 'H' -> "Hello, world!\n" + 'q', 'Q' -> code + "\n" + '9'-> { + val sb2 = StringBuilder() + for (i in 99 downTo 1) { + val s = if (i > 1) "s" else "" + sb2.append("$i bottle$s of beer on the wall\n") + sb2.append("$i bottle$s of beer\n") + sb2.append("Take one down, pass it around\n") + } + sb2.append("No more bottles of beer on the wall!\n") + sb2.toString() + } + '+' -> { acc++; "" } // yeah, it's weird! + else -> throw IllegalArgumentException("Code contains illegal operation '$c'") + } + ) + } + println(sb) +} + +fun main(args: Array) { + val code = args[0] // pass in code as command line argument (using hq9+) + hq9plus(code) +} diff --git a/Task/Execute-HQ9+/Lua/execute-hq9+.lua b/Task/Execute-HQ9+/Lua/execute-hq9+.lua new file mode 100644 index 0000000000..507a4b54cd --- /dev/null +++ b/Task/Execute-HQ9+/Lua/execute-hq9+.lua @@ -0,0 +1,20 @@ +function runCode( code ) + local acc, lc = 0 + for i = 1, #code do + lc = code:sub( i, i ):upper() + if lc == "Q" then print( lc ) + elseif lc == "H" then print( "Hello, World!" ) + elseif lc == "+" then acc = acc + 1 + elseif lc == "9" then + for j = 99, 1, -1 do + if j > 1 then + print( string.format( "%d bottles of beer on the wall\n%d bottles of beer\nTake one down, pass it around\n%d bottles of beer on the wall\n", j, j, j - 1 ) ) + else + print( "1 bottle of beer on the wall\n1 bottle of beer\nTake one down and pass it around\nno more bottles of beer on the wall\n\n".. + "No more bottles of beer on the wall\nNo more bottles of beer\n".. + "Go to the store and buy some more\n99 bottles of beer on the wall.\n" ) + end + end + end + end +end diff --git a/Task/Execute-HQ9+/Nimrod/execute-hq9+.nimrod b/Task/Execute-HQ9+/Nimrod/execute-hq9+.nimrod deleted file mode 100644 index 9be71c092c..0000000000 --- a/Task/Execute-HQ9+/Nimrod/execute-hq9+.nimrod +++ /dev/null @@ -1,31 +0,0 @@ -var program = "9hHqQ+" -var i = 0 - -proc bottle(n: int): string = - case n - of 0: - result = "No more bottles" - of 1: - result = "1 bottle" - else: - result = $n & " bottles" - -proc ninetyNineBottles = - for n in countdown(99, 1): - echo bottle(n), " bottle of beer on the wall" - echo bottle(n), " bottle of beer" - echo "Take one down, pass it around" - echo bottle(n - 1), " of beer on the wall" - -for token in items(program): - case token - of 'h', 'H': - echo("Hello, world!") - of 'q', 'Q': - echo(program) - of '9': - ninetyNineBottles() - of '+': - inc(i) - else: - echo("Unknown command: ", token) diff --git a/Task/Execute-HQ9+/Perl-6/execute-hq9+-3.pl6 b/Task/Execute-HQ9+/Perl-6/execute-hq9+-3.pl6 deleted file mode 100644 index f26f465e40..0000000000 --- a/Task/Execute-HQ9+/Perl-6/execute-hq9+-3.pl6 +++ /dev/null @@ -1,6 +0,0 @@ -my $hq9 = HQ9Interpreter.new; -while 1 { - my $in = prompt('HQ9+>').chomp; - last unless $in.chars; - $hq9.run($in) -} diff --git a/Task/Execute-HQ9+/Ring/execute-hq9+.ring b/Task/Execute-HQ9+/Ring/execute-hq9+.ring new file mode 100644 index 0000000000..a9a2c83f4d --- /dev/null +++ b/Task/Execute-HQ9+/Ring/execute-hq9+.ring @@ -0,0 +1,32 @@ +# Project : Execute HQ9 +# Date : 2017/09/12 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +bottle("hq9+HqQ+Qq") + +func bottle(code) + accumulator = 0 + for i = 1 to len(code) + switch code[i] + on "h" + see "Hello, world!" + nl + on "H" + see "hello, world!" + nl + on "q" + see code + nl + on "Q" + see code + nl + on "9" + bottles = 99 + while bottles > 0 + see "" + bottles + " bottles of beer on the wall, " + see "" + bottles + " bottles of beer," + nl + bottles = bottles - 1 + see "take one down, pass it around, " + see "" + bottles + " bottles of beer on the wall." + nl + end + on "+" + accumulator = accumulator + 1 + off + next diff --git a/Task/Execute-HQ9+/X86-Assembly/execute-hq9+.x86 b/Task/Execute-HQ9+/X86-Assembly/execute-hq9+.x86 new file mode 100644 index 0000000000..57d158ea8b --- /dev/null +++ b/Task/Execute-HQ9+/X86-Assembly/execute-hq9+.x86 @@ -0,0 +1,130 @@ +;ds:si: pointer to asciiz string containing HQ9++ source code +ExecuteHQ9: + push ax + push dx + push si + push di + push es + push bx + mov bx, si + .interpret: + lodsb + cmp al, 'H' + je .doHelloWorld + cmp al, 'Q' + je .doPrintCode + cmp al, '9' + je .doDrinkBeer + cmp al, '+' + je .doCounter + pop bx + pop es + pop di + pop si + pop dx + pop ax + ret + + .doHelloWorld: + push ds + mov ax, cs + mov ds, ax + push si + mov si, .dataHelloWorld + call .printString + pop si + pop ds + jmp .interpret + + .doPrintCode: + push si + mov si, bx + call .printString + pop si + jmp .interpret + + .doDrinkBeer: + push ds + push si + push ax + mov ax, cs + mov ds, ax + mov ax, 99 + .beer_loop: + call .printHexNumber + mov si, .dataBeerSong1 + call .printString + call .printHexNumber + mov si, .dataBeerSong2 + call .printString + dec ax + call .printHexNumber + mov si, .dataBeerSong3 + call .printString + test ax, ax + jnz .beer_loop + pop ax + pop si + pop ds + jmp .interpret + + .doCounter: + push ax + inc ax + pop ax + jmp .interpret + + .printString: + push ax + push si + .looping: + lodsb + test al, al + jz .done + mov ah, 0Eh + int 10h + jmp .looping + .done: + pop si + pop ax + ret + + .printHexNumber: + pusha + push ds + mov ax, cs + mov ds, ax + push word 0 + mov bx, ax + xor dx, dx + mov cx, 4r + .convert_loop: + mov ax, bx + and ax, 0Fh + cmp ax, 9 + ja .greater_than_9 + add ax, '0' + jmp .converted + .greater_than_9: + add ax, 'A'-0Ah + .converted: + push ax + shr bx, 4 + dec cx + jnz .convert_loop + .popoff: + pop ax + cmp ax, 0 + je .done + mov ah, 0Eh + int 10h + jmp .popoff + .done: + pop ds + popa + ret + + .dataHelloWorld: db "Hello World!", 0 + .dataBeerSong1: db " bottles of beer on the wall ", 0 + .dataBeerSong2: db " bottles of beer", 13, 10, "Take one down, pass it around " + .dataBeerSong3: db 0, " bottles of beer on the wall", 0 diff --git a/Task/Execute-HQ9+/Zkl/execute-hq9+-1.zkl b/Task/Execute-HQ9+/Zkl/execute-hq9+-1.zkl new file mode 100644 index 0000000000..d3ff76a8a8 --- /dev/null +++ b/Task/Execute-HQ9+/Zkl/execute-hq9+-1.zkl @@ -0,0 +1,23 @@ +fcn runHQ9(code){ + acc:=0; + foreach c in (code){ + switch(c){ + case("H"){ println("hello, world"); } + case("Q"){ print(code); } + case("+"){ acc+=1; } + case("9"){ wall_O_beer(); } + } + } +} +fcn wall_O_beer(){ + [99..0,-1].pump(fcn(n){ + println(beers(n), " on the wall, ", beers(n).toLower(), ".\n", + n==0 and ("Go to the store and buy some more, 99 bottles of beer") or + ("Take one down and pass it around, " + beers(n-1).toLower()), + " on the wall.\n") + }); +} +fcn beers(n){ + (n==0 and "No more bottles" or (n==1 and "1 bottle" or "" + n + " bottles")) + + " of beer" +} diff --git a/Task/Execute-HQ9+/Zkl/execute-hq9+-2.zkl b/Task/Execute-HQ9+/Zkl/execute-hq9+-2.zkl new file mode 100644 index 0000000000..cb771a7164 --- /dev/null +++ b/Task/Execute-HQ9+/Zkl/execute-hq9+-2.zkl @@ -0,0 +1 @@ +runHQ9("90HQ+junk"); diff --git a/Task/Execute-SNUSP/Kotlin/execute-snusp.kotlin b/Task/Execute-SNUSP/Kotlin/execute-snusp.kotlin new file mode 100644 index 0000000000..698fb4725b --- /dev/null +++ b/Task/Execute-SNUSP/Kotlin/execute-snusp.kotlin @@ -0,0 +1,63 @@ +// version 1.1.2 + +// requires 5 chars (10 bytes) of data store +const val hw = """ +/++++!/===========?\>++.>+.+++++++..+++\ +\+++\ | /+>+++++++>/ /++++++++++<<.++>./ +$+++/ | \+++++++++>\ \+++++.>.+++.-----\ + \==-<<<<+>+++/ /=.>.+>.--------.-/""" + +// input is a multi-line string. +fun snusp(dlen: Int, raw: String) { + val ds = CharArray(dlen) // data store + var dp = 0 // data pointer + var s = raw + + // remove leading '\n' from string if present + s = s.trimStart('\n') + + // make 2 dimensional instruction store and declare instruction pointers + val cs = s.split('\n') + var ipr = 0 + var ipc = 0 + + // look for starting instruction + findStart@ for ((r, row) in cs.withIndex()) { + for ((i, c) in row.withIndex()) { + if (c == '$') { + ipr = r + ipc = i + break@findStart + } + } + } + + var id = 0 + val step = fun() { + if (id and 1 == 0) + ipc += 1 - (id and 2) + else + ipr += 1 - (id and 2) + } + + // execute + while ((ipr in 0 until cs.size) && (ipc in 0 until cs[ipr].length)) { + when (cs[ipr][ipc]) { + '>' -> dp++ + '<' -> dp-- + '+' -> ds[dp]++ + '-' -> ds[dp]-- + '.' -> print(ds[dp]) + ',' -> ds[dp] = readLine()!![0] + '/' -> id = id.inv() + '\\' -> id = id xor 1 + '!' -> step() + '?' -> if (ds[dp] == '\u0000') step() + } + step() + } +} + +fun main(args: Array) { + snusp(5, hw) +} diff --git a/Task/Execute-SNUSP/Perl-6/execute-snusp.pl6 b/Task/Execute-SNUSP/Perl-6/execute-snusp.pl6 new file mode 100644 index 0000000000..8874b31de1 --- /dev/null +++ b/Task/Execute-SNUSP/Perl-6/execute-snusp.pl6 @@ -0,0 +1,71 @@ +class SNUSP { + + has @!inst-pointer; + has @!call-stack; + has @!direction; + has @!memory; + has $!mem-pointer; + + method run ($code) { + init(); + my @code = pad( |$code.lines ); + for @code.kv -> $r, @l { + my $index = @l.grep( /'$'/, :k ); + if $index { + @!inst-pointer = $r, $index; + last + } + } + + loop { + my $instruction = @code[@!inst-pointer[0]; @!inst-pointer[1]]; + given $instruction { + when '>' { $!mem-pointer++ } + when '<' { $!mem-pointer-- } + when '+' { @!memory[$!mem-pointer]++ } + when '-' { @!memory[$!mem-pointer]-- } + when '.' { print @!memory[$!mem-pointer].chr } + when ',' { @!memory[$!mem-pointer] = $*IN.getc.ord } + when '/' { @!direction = @!direction.reverse «*» -1 } + when '\\' { @!direction = @!direction.reverse } + when '!' { nexti() } + when '?' { nexti() unless @!memory[$!mem-pointer] } + when '@' { @!call-stack.push: @!inst-pointer.Array } + when '#' { + last unless +@!call-stack; + @!inst-pointer = |@!call-stack.pop; + nexti(); + } + } + nexti(); + last if @!inst-pointer[0] > +@code or + @!inst-pointer[1] > +@code[0]; + } + + sub init () { + @!inst-pointer = 0, 0; + @!direction = 0, 1; + $!mem-pointer = 0; + @!memory = () + } + + sub nexti () { @!inst-pointer Z+= @!direction } + + sub pad ( *@lines ) { + my $max = max @lines».chars; + my @pad = @lines.map: $max - *.chars; + map -> $i { flat @lines[$i].comb, ' ' xx @pad[$i] }, ^@lines; + } + } +} + +# TESTING +my $hw = q:to/END/; + /++++!/===========?\>++.>+.+++++++..+++\ + \+++\ | /+>+++++++>/ /++++++++++<<.++>./ + $+++/ | \+++++++++>\ \+++++.>.+++.-----\ + \==-<<<<+>+++/ /=.>.+>.--------.-/ + END + +my $snusp = SNUSP.new; +$snusp.run($hw) diff --git a/Task/Execute-SNUSP/Phix/execute-snusp.phix b/Task/Execute-SNUSP/Phix/execute-snusp.phix new file mode 100644 index 0000000000..4237a22ed8 --- /dev/null +++ b/Task/Execute-SNUSP/Phix/execute-snusp.phix @@ -0,0 +1,60 @@ +integer id = 0, ipr = 1, ipc = 1 + +procedure step() + if and_bits(id,1) == 0 then + ipc += 1 - and_bits(id,2) + else + ipr += 1 - and_bits(id,2) + end if +end procedure + +procedure snusp(integer dlen, string s) +sequence ds = repeat(0,dlen) -- data store +integer dp = 1 -- data pointer + + -- remove leading '\n' from string if present + s = trim_head(s,'\n') + + -- make 2 dimensional instruction store and set instruction pointers + sequence cs = split(s,'\n') + ipr = 1 + ipc = 1 + + -- look for starting instruction + for i=1 to length(cs) do + ipc = find('$',cs[i]) + if ipc then + ipr = i + exit + end if + end for + + id = 0 + + -- execute + while ipr>=1 and ipr<=length(cs) + and ipc>=1 and ipc<=length(cs[ipr]) do + integer op = cs[ipr][ipc] + switch op do + case '>' : dp += 1 + case '<' : dp -= 1 + case '+' : ds[dp] += 1 + case '-' : ds[dp] -= 1 + case '.' : puts(1,ds[dp]) + case ',' : ds[dp] = getc(0) + case '/' : id = not_bits(id) + case '\\': id = xor_bits(id,1) + case '!' : step() + case '?' : if ds[dp]=0 then step() end if + end switch + step() + end while +end procedure + +constant hw = """ +/++++!/===========?\>++.>+.+++++++..+++\ +\+++\ | /+>+++++++>/ /++++++++++<<.++>./ +$+++/ | \+++++++++>\ \+++++.>.+++.-----\ + \==-<<<<+>+++/ /=.>.+>.--------.-/""" + +snusp(5, hw) diff --git a/Task/Execute-a-Markov-algorithm/Go/execute-a-markov-algorithm-1.go b/Task/Execute-a-Markov-algorithm/Go/execute-a-markov-algorithm-1.go deleted file mode 100644 index 26d343dec3..0000000000 --- a/Task/Execute-a-Markov-algorithm/Go/execute-a-markov-algorithm-1.go +++ /dev/null @@ -1,91 +0,0 @@ -package main - -import ( - "fmt" - "strings" -) - -type testCase struct { - ruleSet, sample, output string -} - -var testSet []testCase // initialized in separate source file - -func main() { - fmt.Println("validating", len(testSet), "test cases") - var failures bool - for i, tc := range testSet { - if r := ma(tc.ruleSet, tc.sample); r != tc.output { - fmt.Println("test", i+1, "fail") - failures = true - } - } - if !failures { - fmt.Println("no failures") - } -} - -type rule struct { - pat string - rep string - term bool -} - -func ma(rs, s string) string { - // compile rules per task description - var rules []rule - for _, line := range strings.Split(rs, "\n") { - if line == "" || line[0] == '#' { - continue - } - a := strings.Index(line, "->") - if a == -1 { - fmt.Println("invalid rule:", line) - return "" - - } - pat := line[:a] - for { - if pat == "" { - b := strings.Index(line[a+2:], "->") - if b == -1 { - fmt.Println("invalid rule:", line) - return "" - } - a += 2 + b - pat = line[:a] - continue - } - last := pat[len(pat)-1] - if last != ' ' && last != '\t' { - break - } - pat = pat[:len(pat)-1] - } - rep := line[a+2:] - for rep > "" && (rep[0] == ' ' || rep[0] == '\t') { - rep = rep[1:] - } - var term bool - if rep > "" && rep[0] == '.' { - term = true - rep = rep[1:] - } - rules = append(rules, rule{pat, rep, term}) - } - // execute algorithm per WP - for r := 0; r < len(rules); { - pat := rules[r].pat - if f := strings.Index(s, pat); f == -1 { - r++ - } else { - - s = s[:f] + rules[r].rep + s[f+len(pat):] - if rules[r].term { - break - } - r = 0 - } - } - return s -} diff --git a/Task/Execute-a-Markov-algorithm/Go/execute-a-markov-algorithm-2.go b/Task/Execute-a-Markov-algorithm/Go/execute-a-markov-algorithm-2.go deleted file mode 100644 index e9a0d20691..0000000000 --- a/Task/Execute-a-Markov-algorithm/Go/execute-a-markov-algorithm-2.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -func init() { - testSet = []testCase{ - { -`# 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`, - "I bought a B of As from T S.", - "I bought a bag of apples from my brother."}, - { -`# Slightly modified from the rules on Wikipedia -A -> apple -B -> bag -... diff --git a/Task/Execute-a-Markov-algorithm/Phix/execute-a-markov-algorithm.phix b/Task/Execute-a-Markov-algorithm/Phix/execute-a-markov-algorithm.phix new file mode 100644 index 0000000000..adcdfaf411 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Phix/execute-a-markov-algorithm.phix @@ -0,0 +1,125 @@ +procedure markov(string rules, input, expected) + sequence subs = {}, reps = {} + sequence lines = split(substitute(rules,"\t"," "),'\n') + for i=1 to length(lines) do + string li = lines[i] + if length(li) and li[1]!='#' then + integer k = match(" -> ",li) + if k then + subs = append(subs,trim(li[1..k-1])) + reps = append(reps,trim(li[k+4..$])) + end if + end if + end for + string res = input + bool term = false + while 1 do + bool found = false + for i=1 to length(subs) do + string sub = subs[i] + integer k = match(sub,res) + if k then + found = true + string rep = reps[i] + if length(rep) and rep[1]='.' then + rep = rep[2..$] + term = true + end if + res[k..k+length(sub)-1] = rep + exit + end if + if term then exit end if + end for + if term or not found then exit end if + end while + ?{input,res,iff(res=expected?"ok":"**ERROR**")} +end procedure + +constant 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.") + +constant 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.") + +constant 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.") + +constant 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") + +constant 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") diff --git a/Task/Execute-a-Markov-algorithm/SequenceL/execute-a-markov-algorithm.sequencel b/Task/Execute-a-Markov-algorithm/SequenceL/execute-a-markov-algorithm.sequencel new file mode 100644 index 0000000000..cbafe3ec89 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/SequenceL/execute-a-markov-algorithm.sequencel @@ -0,0 +1,47 @@ +import ; + +Rule ::= ( pattern : char(1), + replacement : char(1), + terminal : bool); + +ReplaceResult ::= (newString : char(1), wasReplaced : bool); + +main(args(2)) := markov(createRule(split(args[1], '\n')), 1, args[2]); + +createRule(line(1)) := + let + containsComments := firstIndexOf(line, '#'); + removedComments := line when containsComments = 0 else + line[1 ... containsComments - 1]; + + arrowLocation := startOfArrow(removedComments, 1); + lhs := removedComments[1 ... arrowLocation-1]; + rhs := removedComments[arrowLocation + 4 ... size(removedComments)]; + isTerminal := size(rhs) > 0 and rhs[1] = '.'; + in + (pattern : lhs, + replacement : rhs[2 ... size(rhs)] when isTerminal else rhs, + terminal : isTerminal) when size(removedComments) > 0 and arrowLocation /= -1; + +startOfArrow(line(1), n) := + -1 when n > size(line) - 3 else + n when (line[n]=' ' or line[n]='\t') and + line[n+1] = '-' and line[n+2] = '>' and + (line[n+3]=' ' or line[n+3]='\t') else + startOfArrow(line, n+1); + +markov(rules(1), n, input(1)) := + let + replaced := replaceSubString(input, rules[n].pattern, rules[n].replacement, 1); + in + input when n > size(rules) else + replaced.newString when replaced.wasReplaced and rules[n].terminal else + markov(rules, 1, replaced.newString) when replaced.wasReplaced else + markov(rules, n+1, input); + +replaceSubString(str(1), original(1), new(1), n) := + (newString : str, wasReplaced : false) + when n > size(str) - size(original) + 1 else + (newString : str[1 ... n - 1] ++ new ++ str[n + size(original) ... size(str)], wasReplaced : true) + when equalList(str[n ... n + size(original) - 1], original) else + replaceSubString(str, original, new, n + 1); diff --git a/Task/Execute-a-Markov-algorithm/Zkl/execute-a-markov-algorithm-1.zkl b/Task/Execute-a-Markov-algorithm/Zkl/execute-a-markov-algorithm-1.zkl new file mode 100644 index 0000000000..de665b50d3 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Zkl/execute-a-markov-algorithm-1.zkl @@ -0,0 +1,26 @@ +fcn parseRuleSet(lines){ + if(vm.numArgs>1) lines=vm.arglist; // lines or object + ks:=L(); vs:=L(); + foreach line in (lines){ + if(line[0]=="#") continue; // nuke + pattern,replacement:=line.replace("\t"," ") + .split(" -> ",1).apply("strip"); + ks.append(pattern); vs.append(replacement); + } + return(ks,vs); +} + +fcn markov(text,rules){ + ks,vs:=rules; eks:=ks.enumerate(); + do{ go:=False; + foreach n,k in (eks){ + if (Void!=text.find(k)){ + if (Void==(v:=vs[n])) return(text); + if (v[0,1]==".") v=v[1,*] else go=True; + text=text.replace(k,v,1); + break; // restart after every rule application, unless terminating + } + } + }while(go); + text +} diff --git a/Task/Execute-a-Markov-algorithm/Zkl/execute-a-markov-algorithm-2.zkl b/Task/Execute-a-Markov-algorithm/Zkl/execute-a-markov-algorithm-2.zkl new file mode 100644 index 0000000000..aacd2f6e20 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Zkl/execute-a-markov-algorithm-2.zkl @@ -0,0 +1,6 @@ +ruleSet:=parseRuleSet("# This rules file is extracted from Wikipedia:", + "# http://en.wikipedia.org/wiki/Markov_Algorithm", + "A\t->\tapple", "B -> bag", "S -> shop", "T -> the", + "the shop -> my brother", "a never used -> .terminating rule"); +ruleSet.println(); +markov("I bought a B of As from T S.",ruleSet).println(); diff --git a/Task/Execute-a-Markov-algorithm/Zkl/execute-a-markov-algorithm-3.zkl b/Task/Execute-a-Markov-algorithm/Zkl/execute-a-markov-algorithm-3.zkl new file mode 100644 index 0000000000..4f3fb44561 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Zkl/execute-a-markov-algorithm-3.zkl @@ -0,0 +1,11 @@ +parseRuleSet( // rule set in a list + T("# 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("I bought a B of As from T S.",_).println(); + +parseRuleSet("# 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("I bought a B of As W my Bgage from T S.",_).println(); diff --git a/Task/Execute-a-Markov-algorithm/Zkl/execute-a-markov-algorithm-4.zkl b/Task/Execute-a-Markov-algorithm/Zkl/execute-a-markov-algorithm-4.zkl new file mode 100644 index 0000000000..3c3fc78b43 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Zkl/execute-a-markov-algorithm-4.zkl @@ -0,0 +1,2 @@ +parseRuleSet(File("ruleSet4")) : markov("_1111*11111_",_).println(); +parseRuleSet(File("ruleSet5")) : markov("000000A000000",_).println(); diff --git a/Task/Execute-a-system-command/00DESCRIPTION b/Task/Execute-a-system-command/00DESCRIPTION index 815097698d..4f4304c73b 100644 --- a/Task/Execute-a-system-command/00DESCRIPTION +++ b/Task/Execute-a-system-command/00DESCRIPTION @@ -1,6 +1,6 @@ ;Task: Run either the   '''ls'''   system command   ('''dir'''   on Windows),   or the   '''pause'''   system command.

    -;Related tasks +;Related task * [[Get_system_command_output | Get system command output]]

    diff --git a/Task/Execute-a-system-command/BASIC/execute-a-system-command.basic b/Task/Execute-a-system-command/BASIC/execute-a-system-command-1.basic similarity index 100% rename from Task/Execute-a-system-command/BASIC/execute-a-system-command.basic rename to Task/Execute-a-system-command/BASIC/execute-a-system-command-1.basic diff --git a/Task/Execute-a-system-command/BASIC/execute-a-system-command-2.basic b/Task/Execute-a-system-command/BASIC/execute-a-system-command-2.basic new file mode 100644 index 0000000000..5b2eefdc76 --- /dev/null +++ b/Task/Execute-a-system-command/BASIC/execute-a-system-command-2.basic @@ -0,0 +1,2 @@ +' Execute a system command +SYSTEM "ls" diff --git a/Task/Execute-a-system-command/Dc/execute-a-system-command.dc b/Task/Execute-a-system-command/Dc/execute-a-system-command.dc new file mode 100644 index 0000000000..c745359a9f --- /dev/null +++ b/Task/Execute-a-system-command/Dc/execute-a-system-command.dc @@ -0,0 +1 @@ +! ls diff --git a/Task/Execute-a-system-command/Gambas/execute-a-system-command.gambas b/Task/Execute-a-system-command/Gambas/execute-a-system-command.gambas new file mode 100644 index 0000000000..de60d04603 --- /dev/null +++ b/Task/Execute-a-system-command/Gambas/execute-a-system-command.gambas @@ -0,0 +1,5 @@ +Public Sub Main() + +Shell "ls -aul" + +End diff --git a/Task/Execute-a-system-command/Gnuplot/execute-a-system-command.gnuplot b/Task/Execute-a-system-command/Gnuplot/execute-a-system-command.gnuplot new file mode 100644 index 0000000000..f38fd003e2 --- /dev/null +++ b/Task/Execute-a-system-command/Gnuplot/execute-a-system-command.gnuplot @@ -0,0 +1 @@ +!ls 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.kotlin new file mode 100644 index 0000000000..e9e2a38f99 --- /dev/null +++ b/Task/Execute-a-system-command/Kotlin/execute-a-system-command.kotlin @@ -0,0 +1,10 @@ +// version 1.0.6 + +import java.util.Scanner + +fun main(args: Array) { + val proc = Runtime.getRuntime().exec("cmd /C dir") // testing on Windows 10 + Scanner(proc.inputStream).use { + while (it.hasNextLine()) println(it.nextLine()) + } +} diff --git a/Task/Execute-a-system-command/Lang5/execute-a-system-command.lang5 b/Task/Execute-a-system-command/Lang5/execute-a-system-command-1.lang5 similarity index 100% rename from Task/Execute-a-system-command/Lang5/execute-a-system-command.lang5 rename to Task/Execute-a-system-command/Lang5/execute-a-system-command-1.lang5 diff --git a/Task/Execute-a-system-command/Lang5/execute-a-system-command-2.lang5 b/Task/Execute-a-system-command/Lang5/execute-a-system-command-2.lang5 new file mode 100644 index 0000000000..d999f0f5b2 --- /dev/null +++ b/Task/Execute-a-system-command/Lang5/execute-a-system-command-2.lang5 @@ -0,0 +1 @@ +"ls -a" system diff --git a/Task/Execute-a-system-command/Logtalk/execute-a-system-command.logtalk b/Task/Execute-a-system-command/Logtalk/execute-a-system-command.logtalk new file mode 100644 index 0000000000..c6fedd2a9b --- /dev/null +++ b/Task/Execute-a-system-command/Logtalk/execute-a-system-command.logtalk @@ -0,0 +1 @@ +os::shell('ls -a'). diff --git a/Task/Execute-a-system-command/Stata/execute-a-system-command.stata b/Task/Execute-a-system-command/Stata/execute-a-system-command.stata new file mode 100644 index 0000000000..3a75c1f778 --- /dev/null +++ b/Task/Execute-a-system-command/Stata/execute-a-system-command.stata @@ -0,0 +1,13 @@ +!dir + +* print a message and wait +!echo Ars Longa Vita Brevis && pause + +* load Excel from Stata +!start excel + +* run a Python program (Python must be installed and accessible in the PATH environment variable) +!python preprocessing.py + +* load Windows Notepad +winexec notepad diff --git a/Task/Execute-a-system-command/Zkl/execute-a-system-command.zkl b/Task/Execute-a-system-command/Zkl/execute-a-system-command.zkl new file mode 100644 index 0000000000..ad872740fe --- /dev/null +++ b/Task/Execute-a-system-command/Zkl/execute-a-system-command.zkl @@ -0,0 +1 @@ +System.cmd(System.isWindows and "dir" or "ls") diff --git a/Task/Exponentiation-operator/Erlang/exponentiation-operator-1.erl b/Task/Exponentiation-operator/Erlang/exponentiation-operator-1.erl deleted file mode 100644 index 8c2ea201cf..0000000000 --- a/Task/Exponentiation-operator/Erlang/exponentiation-operator-1.erl +++ /dev/null @@ -1,19 +0,0 @@ -% -spec attribute is for documentation and dialyzer static analysis purposes only. -% It does not constrain the function like a guard (when ... ). --spec exp_int(X :: integer(), N :: non_neg_integer()) -> integer(). - -% X ^ 0 -exp_int(X, 0) when is_integer(X) -> % is_integer guard is required, otherwise X would match anything. - 1; - -% X ^ odd -exp_int(X, N) when is_integer(X), N >= 1, N rem 2 == 1 -> - Part = exp_int(X, (N-1) div 2), - X * Part * Part; - -% X ^ even -exp_int(X, N) when is_integer(X), N >= 2, N rem 2 == 0 -> - Part = exp_int(X, N div 2), - Part * Part. - -% X ^ negative is excluded because it would return float. diff --git a/Task/Exponentiation-operator/Erlang/exponentiation-operator-2.erl b/Task/Exponentiation-operator/Erlang/exponentiation-operator-2.erl deleted file mode 100644 index 706299b682..0000000000 --- a/Task/Exponentiation-operator/Erlang/exponentiation-operator-2.erl +++ /dev/null @@ -1,21 +0,0 @@ -% -spec attribute is for documentation and dialyzer static analysis purposes only. -% It does not constrain the function like a guard (when ... ). --spec exp_float(X :: float(), N :: integer()) -> float(). - -% X ^ 0 -exp_float(X, 0) when is_float(X) -> % is_float guard is required, otherwise X would match anything. - 1.0; - -% X ^ negative -exp_float(X, N) when is_float(X), N < 0 -> - 1.0 / exp_float(X, -N); - -% X ^ even -exp_float(X, N) when is_float(X), N >= 1, N rem 2 == 1 -> - Part = exp_float(X, (N-1) div 2), - X * Part * Part; - -% X ^ odd -exp_float(X, N) when is_float(X), N >= 2, N rem 2 == 0 -> - Part = exp_float(X, N div 2), - Part * Part. diff --git a/Task/Exponentiation-operator/Forth/exponentiation-operator-3.fth b/Task/Exponentiation-operator/Forth/exponentiation-operator-3.fth deleted file mode 100644 index ce3e5bee49..0000000000 --- a/Task/Exponentiation-operator/Forth/exponentiation-operator-3.fth +++ /dev/null @@ -1,11 +0,0 @@ -: pow ( n m -- n^m ) -( written in Retro Forth ) -1 2rot -[ - dup 1 and 0 <> - [ [ tuck * swap ] dip ] ifTrue - [ dup * ] dip - 1 >> - dup 0 <> -] while -drop drop ; diff --git a/Task/Exponentiation-operator/jq/exponentiation-operator-1.jq b/Task/Exponentiation-operator/Jq/exponentiation-operator-1.jq similarity index 100% rename from Task/Exponentiation-operator/jq/exponentiation-operator-1.jq rename to Task/Exponentiation-operator/Jq/exponentiation-operator-1.jq diff --git a/Task/Exponentiation-operator/jq/exponentiation-operator-2.jq b/Task/Exponentiation-operator/Jq/exponentiation-operator-2.jq similarity index 100% rename from Task/Exponentiation-operator/jq/exponentiation-operator-2.jq rename to Task/Exponentiation-operator/Jq/exponentiation-operator-2.jq diff --git a/Task/Exponentiation-operator/Julia/exponentiation-operator.julia b/Task/Exponentiation-operator/Julia/exponentiation-operator.julia new file mode 100644 index 0000000000..4ccd0b40ad --- /dev/null +++ b/Task/Exponentiation-operator/Julia/exponentiation-operator.julia @@ -0,0 +1,7 @@ +function pow(base::Number, exp::Integer) + r = one(base) + for i = 1:exp + r *= base + end + return r +end diff --git a/Task/Exponentiation-operator/Kotlin/exponentiation-operator.kotlin b/Task/Exponentiation-operator/Kotlin/exponentiation-operator.kotlin new file mode 100644 index 0000000000..2fc03baf58 --- /dev/null +++ b/Task/Exponentiation-operator/Kotlin/exponentiation-operator.kotlin @@ -0,0 +1,43 @@ +// version 1.0.6 + +infix fun Int.ipow(exp: Int): Int = + when { + this == 1 -> 1 + this == -1 -> if (exp % 2 == 0) 1 else -1 + exp < 0 -> throw IllegalArgumentException("invalid exponent") + exp == 0 -> 1 + else -> { + var ans = 1 + var base = this + var e = exp + while (e > 0) { + if (e and 1 == 1) ans *= base + e = e shr 1 + base *= base + } + ans + } + } + +infix fun Double.dpow(exp: Int): Double { + var ans = 1.0 + var e = exp + var base = if (e < 0) 1.0 / this else this + if (e < 0) e = -e + while (e > 0) { + if (e and 1 == 1) ans *= base + e = e shr 1 + base *= base + } + return ans +} + +fun main(args: Array) { + println("2 ^ 3 = ${2 ipow 3}") + println("1 ^ -10 = ${1 ipow -10}") + println("-1 ^ -3 = ${-1 ipow -3}") + println() + println("2.0 ^ -3 = ${2.0 dpow -3}") + println("1.5 ^ 0 = ${1.5 dpow 0}") + println("4.5 ^ 2 = ${4.5 dpow 2}") +} diff --git a/Task/Exponentiation-operator/Rust/exponentiation-operator.rust b/Task/Exponentiation-operator/Rust/exponentiation-operator.rust new file mode 100644 index 0000000000..eae6297e1c --- /dev/null +++ b/Task/Exponentiation-operator/Rust/exponentiation-operator.rust @@ -0,0 +1,24 @@ +extern crate num; +use num::traits::One; +use std::ops::Mul; + +fn pow(mut base: T, mut exp: usize) -> T + where T: Clone + One + Mul +{ + if exp == 0 { return T::one() } + while exp & 1 == 0 { + base = base.clone() * base; + exp >>= 1; + } + if exp == 1 { return base } + let mut acc = base.clone(); + + while exp > 1 { + exp >>= 1; + base = base.clone() * base; + if exp & 1 == 1 { + acc = acc * base.clone(); + } + } + acc +} diff --git a/Task/Exponentiation-operator/Zkl/exponentiation-operator-1.zkl b/Task/Exponentiation-operator/Zkl/exponentiation-operator-1.zkl new file mode 100644 index 0000000000..93c7df86b9 --- /dev/null +++ b/Task/Exponentiation-operator/Zkl/exponentiation-operator-1.zkl @@ -0,0 +1,16 @@ +fcn pow(n,exp){ + reg v; + if(n.isType(1)){ // Int + if (exp<0) return(if(n*n!=1) 0 else (if(exp.isOdd) n else 1)); + v=1; + }else{ + if(exp<0){ n=1.0/n; exp=-exp; } + v=1.0; + } + while(exp>0){ + if(exp.isOdd) v*=n; + n*=n; + exp/=2; + } + v +} diff --git a/Task/Exponentiation-operator/Zkl/exponentiation-operator-2.zkl b/Task/Exponentiation-operator/Zkl/exponentiation-operator-2.zkl new file mode 100644 index 0000000000..6f3908c9e3 --- /dev/null +++ b/Task/Exponentiation-operator/Zkl/exponentiation-operator-2.zkl @@ -0,0 +1,4 @@ +println("2^6 = %d".fmt(pow(2,6))); +println("2^-6 = %d".fmt(pow(2,-6))); +println("2.71^6 = %f".fmt(pow(2.71,6))); +println("2.71^-6 = %f".fmt(pow(2.71,-6))); diff --git a/Task/Extend-your-language/Kotlin/extend-your-language.kotlin b/Task/Extend-your-language/Kotlin/extend-your-language.kotlin new file mode 100644 index 0000000000..076b48f4e8 --- /dev/null +++ b/Task/Extend-your-language/Kotlin/extend-your-language.kotlin @@ -0,0 +1,53 @@ +// version 1.0.6 + +data class IfBoth(val cond1: Boolean, val cond2: Boolean) { + fun elseFirst(func: () -> Unit): IfBoth { + if (cond1 && !cond2) func() + return this + } + + fun elseSecond(func: () -> Unit): IfBoth { + if (cond2 && !cond1) func() + return this + } + + fun elseNeither(func: () -> Unit): IfBoth { + if (!cond1 && !cond2) func() + return this // in case it's called out of order + } +} + +fun ifBoth(cond1: Boolean, cond2: Boolean, func: () -> Unit): IfBoth { + if (cond1 && cond2) func() + return IfBoth(cond1, cond2) +} + +fun main(args: Array) { + var a = 0 + var b = 1 + ifBoth (a == 1, b == 3) { + println("a = 1 and b = 3") + } + .elseFirst { + println("a = 1 and b <> 3") + } + .elseSecond { + println("a <> 1 and b = 3") + } + .elseNeither { + println("a <> 1 and b <> 3") + } + + // It's also possible to omit any (or all) of the 'else' clauses or to call them out of order + a = 1 + b = 0 + ifBoth (a == 1, b == 3) { + println("a = 1 and b = 3") + } + .elseNeither { + println("a <> 1 and b <> 3") + } + .elseFirst { + println("a = 1 and b <> 3") + } +} diff --git a/Task/Extend-your-language/Perl-6/extend-your-language.pl6 b/Task/Extend-your-language/Perl-6/extend-your-language.pl6 index f253ea6f66..601c1c32fb 100644 --- a/Task/Extend-your-language/Perl-6/extend-your-language.pl6 +++ b/Task/Extend-your-language/Perl-6/extend-your-language.pl6 @@ -1,9 +1,9 @@ my &if2 = -> \a, \b, &x { my @*IF2 = ?a,?b; x } -my &if-both = -> &x { x if @*IF2 ~~ (True,True) } -my &if-first = -> &x { x if @*IF2 ~~ (True,False) } -my &if-second = -> &x { x if @*IF2 ~~ (False,True) } -my &if-neither = -> &x { x if @*IF2 ~~ (False,False)} +my &if-both = -> &x { x if @*IF2 eq (True,True) } +my &if-first = -> &x { x if @*IF2 eq (True,False) } +my &if-second = -> &x { x if @*IF2 eq (False,True) } +my &if-neither = -> &x { x if @*IF2 eq (False,False)} sub test ($a,$b) { $_ = "G"; # Demo correct scoping of topic. @@ -18,7 +18,4 @@ sub test ($a,$b) { } } -test 1,1; -test 1,0; -test 0,1; -test 0,0; +say test |$_ for 1,0 X 1,0; diff --git a/Task/Extend-your-language/Phix/extend-your-language-1.phix b/Task/Extend-your-language/Phix/extend-your-language-1.phix new file mode 100644 index 0000000000..10cb4e4aaa --- /dev/null +++ b/Task/Extend-your-language/Phix/extend-your-language-1.phix @@ -0,0 +1,6 @@ +switch {condition1,condition2} do + case {true,true}: + case {true,false}: + case {false,true}: + case {false,false}: +end switch diff --git a/Task/Extend-your-language/Phix/extend-your-language-2.phix b/Task/Extend-your-language/Phix/extend-your-language-2.phix new file mode 100644 index 0000000000..6347876338 --- /dev/null +++ b/Task/Extend-your-language/Phix/extend-your-language-2.phix @@ -0,0 +1,10 @@ +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 diff --git a/Task/Extend-your-language/Phix/extend-your-language-3.phix b/Task/Extend-your-language/Phix/extend-your-language-3.phix new file mode 100644 index 0000000000..865e7ac3d9 --- /dev/null +++ b/Task/Extend-your-language/Phix/extend-your-language-3.phix @@ -0,0 +1,12 @@ +enum BOTH = 0b11, FIRST = 0b10, SECOND = 0b01, NEITHER = 0b00 + +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 diff --git a/Task/Extend-your-language/Phix/extend-your-language-4.phix b/Task/Extend-your-language/Phix/extend-your-language-4.phix new file mode 100644 index 0000000000..ed779e8381 --- /dev/null +++ b/Task/Extend-your-language/Phix/extend-your-language-4.phix @@ -0,0 +1,3 @@ +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) diff --git a/Task/Extend-your-language/Phix/extend-your-language-5.phix b/Task/Extend-your-language/Phix/extend-your-language-5.phix new file mode 100644 index 0000000000..673cfa15b8 --- /dev/null +++ b/Task/Extend-your-language/Phix/extend-your-language-5.phix @@ -0,0 +1,2 @@ +--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} diff --git a/Task/Extend-your-language/Phix/extend-your-language-6.phix b/Task/Extend-your-language/Phix/extend-your-language-6.phix new file mode 100644 index 0000000000..777e3fcde6 --- /dev/null +++ b/Task/Extend-your-language/Phix/extend-your-language-6.phix @@ -0,0 +1 @@ + elsif ttidx=T_if2 then DoIf2() diff --git a/Task/Extend-your-language/Phix/extend-your-language-7.phix b/Task/Extend-your-language/Phix/extend-your-language-7.phix new file mode 100644 index 0000000000..5a5690632b --- /dev/null +++ b/Task/Extend-your-language/Phix/extend-your-language-7.phix @@ -0,0 +1,12 @@ +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 diff --git a/Task/Extend-your-language/Rust/extend-your-language.rust b/Task/Extend-your-language/Rust/extend-your-language.rust new file mode 100644 index 0000000000..4ba3fbc21c --- /dev/null +++ b/Task/Extend-your-language/Rust/extend-your-language.rust @@ -0,0 +1,31 @@ +#![allow(unused_variables)] +macro_rules! if2 { + ($cond1: expr, $cond2: expr + => $both:expr + => $first: expr + => $second:expr + => $none:expr) + => { + match ($cond1, $cond2) { + (true, true) => $both, + (true, _ ) => $first, + (_ , true) => $second, + _ => $none + } + } +} + +fn main() { + let i = 1; + let j = 2; + if2!(i > j, i + j >= 3 + => { + // code blocks and statements can go here also + let k = i + j; + println!("both were true") + } + => println!("the first was true") + => println!("the second was true") + => println!("neither were true") + ) +} diff --git a/Task/Extensible-prime-generator/00DESCRIPTION b/Task/Extensible-prime-generator/00DESCRIPTION index 44e851e553..508295e3b2 100644 --- a/Task/Extensible-prime-generator/00DESCRIPTION +++ b/Task/Extensible-prime-generator/00DESCRIPTION @@ -20,6 +20,7 @@ Show output on this page. '''Note 2:''' If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation). -;See also: -* The task is written so it may be useful in solving task [[Emirp primes]] as well as others (depending on its efficiency). + +;Related task: +* The task is written so it may be useful in solving the task   [[Emirp primes]]   as well as others (depending on its efficiency).

    diff --git a/Task/Extensible-prime-generator/Fortran/extensible-prime-generator-2.f b/Task/Extensible-prime-generator/Fortran/extensible-prime-generator-2.f index d69dee03c8..148a15d52a 100644 --- a/Task/Extensible-prime-generator/Fortran/extensible-prime-generator-2.f +++ b/Task/Extensible-prime-generator/Fortran/extensible-prime-generator-2.f @@ -303,8 +303,24 @@ Can invoke GETSREC, which can invoke PSURGE, which ... invokes NEXTPRIME. Oh dea LOGICAL FUNCTION ISPRIME(N) !Could fool around explicity testing 2 and 3 and say 5, INTEGER N !But that means also checking that N > 2, N > 3, and N > 5. - ISPRIME = N .EQ. NEXTPRIME(N - 1) !This is so much easier. - END FUNCTION ISPRIME !No divisions up to SQRT(N) or the like either. +c ISPRIME = N .EQ. NEXTPRIME(N - 1) !This is so much easier, but involves scanning to reach the next prime. + INTEGER R,IST,I,C,B !Assistants for indexing the bit array. + IF (N.LE.1) THEN !First, preclude sillyness. + ISPRIME = .FALSE. !Not a prime. + ELSE IF (N.EQ.2) THEN !This is the only even number + ISPRIME = .TRUE. !That is a prime. + ELSE IF (MOD(N,2).EQ.0) THEN !Other even numbers + ISPRIME = .FALSE. !Are not prime numbers. + ELSE !Righto, now N is an odd number and there is a bit array for them. + R = (N - SORG)/(2*SBITS) !SORG is odd, so (N - SORG) is even. + CALL GETSREC(R + 1) !The first record is numbered one, not zero. + IST = SORG + R*(2*SBITS) !The number for its first bit: even numbers are omitted. + I = (N - IST)/2 !Offset into the record. N - IST is even. + C = I/8 !Which character in SCHAR(0:SCHARS - 1)? + B = MOD(I,8) !Which bit in SCHAR(C), indexing from zero? + ISPRIME = IAND(ICHAR(SCHAR(C)),ICHAR(BITON(B))).GT.0 !The bit is on for a prime. + END IF !All that fuss to find a single bit. + END FUNCTION ISPRIME !But, no divisions up to SQRT(N) or the like. END MODULE PRIMEBAG !Functions updating a disc file as a side effect... PROGRAM POKE diff --git a/Task/Extensible-prime-generator/jq/extensible-prime-generator-1.jq b/Task/Extensible-prime-generator/Jq/extensible-prime-generator-1.jq similarity index 100% rename from Task/Extensible-prime-generator/jq/extensible-prime-generator-1.jq rename to Task/Extensible-prime-generator/Jq/extensible-prime-generator-1.jq diff --git a/Task/Extensible-prime-generator/jq/extensible-prime-generator-2.jq b/Task/Extensible-prime-generator/Jq/extensible-prime-generator-2.jq similarity index 100% rename from Task/Extensible-prime-generator/jq/extensible-prime-generator-2.jq rename to Task/Extensible-prime-generator/Jq/extensible-prime-generator-2.jq diff --git a/Task/Extensible-prime-generator/jq/extensible-prime-generator-3.jq b/Task/Extensible-prime-generator/Jq/extensible-prime-generator-3.jq similarity index 100% rename from Task/Extensible-prime-generator/jq/extensible-prime-generator-3.jq rename to Task/Extensible-prime-generator/Jq/extensible-prime-generator-3.jq diff --git a/Task/Extensible-prime-generator/jq/extensible-prime-generator-4.jq b/Task/Extensible-prime-generator/Jq/extensible-prime-generator-4.jq similarity index 100% rename from Task/Extensible-prime-generator/jq/extensible-prime-generator-4.jq rename to Task/Extensible-prime-generator/Jq/extensible-prime-generator-4.jq diff --git a/Task/Extensible-prime-generator/Kotlin/extensible-prime-generator.kotlin b/Task/Extensible-prime-generator/Kotlin/extensible-prime-generator.kotlin new file mode 100644 index 0000000000..426f1eda3b --- /dev/null +++ b/Task/Extensible-prime-generator/Kotlin/extensible-prime-generator.kotlin @@ -0,0 +1,36 @@ +// version 1.1.2 +// compiled with flag -Xcoroutines=enable to suppress 'experimental' warning + +import kotlin.coroutines.experimental.* + +fun isPrime(n: Int) : Boolean { + if (n < 2) return false + if (n % 2 == 0) return n == 2 + if (n % 3 == 0) return n == 3 + var d : Int = 5 + while (d * d <= n) { + if (n % d == 0) return false + d += 2 + if (n % d == 0) return false + d += 4 + } + return true +} + +fun generatePrimes() = + buildSequence { + yield(2) + var p = 3 + while (p <= Int.MAX_VALUE) { + if (isPrime(p)) yield(p) + p += 2 + } + } + +fun main(args: Array) { + val primes = generatePrimes().take(10000) // generate first 10,000 primes + println("First 20 primes : ${primes.take(20).toList()}") + println("Primes between 100 and 150 : ${primes.filter { it in 100..150 }.toList()}") + println("Number of primes between 7700 and 8000 = ${primes.filter { it in 7700..8000 }.count()}") + println("10,000th prime = ${primes.last()}") +} diff --git a/Task/Extensible-prime-generator/Phix/extensible-prime-generator.phix b/Task/Extensible-prime-generator/Phix/extensible-prime-generator.phix new file mode 100644 index 0000000000..9e700dd9ab --- /dev/null +++ b/Task/Extensible-prime-generator/Phix/extensible-prime-generator.phix @@ -0,0 +1,59 @@ +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 p20 +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_prime(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 8 do + integer k = power(10,i) + while length(primes)>()); + println!("Primes between 100 and 150:\n {:?}", + primes_paged().skip_while(|&x| x < 100) + .take_while(|&x| x < 150) + .collect::>()); + let diff = count_primes_paged(8000) - count_primes_paged(7700); + println!("There are {} primes between 7,700 and 8,000", diff); + println!("The 10,000th prime is {}", primes_paged().nth(10_000).unwrap()); +} diff --git a/Task/Extensible-prime-generator/Zkl/extensible-prime-generator-1.zkl b/Task/Extensible-prime-generator/Zkl/extensible-prime-generator-1.zkl new file mode 100644 index 0000000000..7f16d9f2f7 --- /dev/null +++ b/Task/Extensible-prime-generator/Zkl/extensible-prime-generator-1.zkl @@ -0,0 +1,30 @@ +// http://stackoverflow.com/revisions/10733621/4 + +fcn postponed_sieve(){ # postponed sieve, by Will Ness + vm.yield(2); vm.yield(3); # original code David Eppstein, + vm.yield(5); vm.yield(7); # ActiveState Recipe 2002 + D:=Dictionary(); + ps:=Utils.Generator(postponed_sieve); # a separate Primes Supply: + p:=ps.pump(2,Void); # (3) a Prime to add to dict + q:=p*p; # (9) when its sQuare is + c:=9; # the next Candidate + while(1){ + if (not D.holds(c)){ # not a multiple of any prime seen so far: + if (c < q) vm.yield(c); # a prime, or + else{ # (c==q): # the next prime's square: + add(D,c + 2*p,2*p); # (9+6,6 : 15,21,27,33,...) + p=ps.next(); # (5) + q=p*p; # (25) + } + }else{ # 'c' is a composite: + s := D.pop(c); # step of increment + add(D,c + s,s); # next multiple, same step + } + c += 2; # next odd candidate + } +} + +fcn add(D,x,s){ # make no multiple keys in Dict + while(D.holds(x)){ x += s } # increment by the given step + D[x] = s; +} diff --git a/Task/Extensible-prime-generator/Zkl/extensible-prime-generator-2.zkl b/Task/Extensible-prime-generator/Zkl/extensible-prime-generator-2.zkl new file mode 100644 index 0000000000..5e6780ebff --- /dev/null +++ b/Task/Extensible-prime-generator/Zkl/extensible-prime-generator-2.zkl @@ -0,0 +1,16 @@ +primes:=Utils.Generator(postponed_sieve); +primes.walk(20).println(); // first 20 primes + +primes.pump(List,fcn(p){ // the primes between 100 & 150 + if (p<100) Void.Skip else if(p>150) Void.Stop else p +}).println(); + +primes.reduce(fcn(n,p){ // count of primes between 7700 & 8000 + if (p<=7700) n else if(p>8000) Void.Stop else n+1 +},0).println(); + +primes=Utils.Generator(postponed_sieve); // new Generator +primes.drop(0d9_999); primes.next().println(); // 10,000th prime + + // or to carry on until the 100,000th: +primes.pump(Void,'wrap(p){ primes.n<=0d100_000 and p or Void.Stop }).println(); diff --git a/Task/Extensible-prime-generator/Zkl/extensible-prime-generator-3.zkl b/Task/Extensible-prime-generator/Zkl/extensible-prime-generator-3.zkl new file mode 100644 index 0000000000..dbc6670302 --- /dev/null +++ b/Task/Extensible-prime-generator/Zkl/extensible-prime-generator-3.zkl @@ -0,0 +1,2 @@ +var [const] BN=Import("zklBigNum"); // libGMP +bigPrimes:=Walker(fcn(p){ p.nextPrime().copy(); }.fp(BN(1))); diff --git a/Task/Extensible-prime-generator/Zkl/extensible-prime-generator-4.zkl b/Task/Extensible-prime-generator/Zkl/extensible-prime-generator-4.zkl new file mode 100644 index 0000000000..5c44834013 --- /dev/null +++ b/Task/Extensible-prime-generator/Zkl/extensible-prime-generator-4.zkl @@ -0,0 +1,2 @@ +bigPrimes.walk(20).println(); // first 20 primes +bigPrimes.pump(Void,'wrap(p){ bigPrimes.n<=0d10_000 and p or Void.Stop }).println(); diff --git a/Task/Extreme-floating-point-values/Haskell/extreme-floating-point-values.hs b/Task/Extreme-floating-point-values/Haskell/extreme-floating-point-values.hs new file mode 100644 index 0000000000..8fd12a9839 --- /dev/null +++ b/Task/Extreme-floating-point-values/Haskell/extreme-floating-point-values.hs @@ -0,0 +1,25 @@ +main = do +let inf = 1/0 +let minus_inf = -1/0 +let minus_zero = -1/inf +let nan = 0/0 + +putStrLn ("Positive infinity = "++(show inf)) +putStrLn ("Negative infinity = "++(show minus_inf)) +putStrLn ("Negative zero = "++(show minus_zero)) +putStrLn ("Not a number = "++(show nan)) + +--Some Arithmetic + +putStrLn ("inf + 2.0 = "++(show (inf+2.0))) +putStrLn ("inf - 10 = "++(show (inf-10))) +putStrLn ("inf - inf = "++(show (inf-inf))) +putStrLn ("inf * 0 = "++(show (inf * 0))) +putStrLn ("nan + 1.0= "++(show (nan+1.0))) +putStrLn ("nan + nan = "++(show (nan + nan))) + +--Some Comparisons + +putStrLn ("nan == nan = "++(show (nan == nan))) +putStrLn ("0.0 == - 0.0 = "++(show (0.0 == minus_zero))) +putStrLn ("inf == inf = "++(show (inf == inf))) diff --git a/Task/Extreme-floating-point-values/jq/extreme-floating-point-values-1.jq b/Task/Extreme-floating-point-values/Jq/extreme-floating-point-values-1.jq similarity index 100% rename from Task/Extreme-floating-point-values/jq/extreme-floating-point-values-1.jq rename to Task/Extreme-floating-point-values/Jq/extreme-floating-point-values-1.jq diff --git a/Task/Extreme-floating-point-values/jq/extreme-floating-point-values-2.jq b/Task/Extreme-floating-point-values/Jq/extreme-floating-point-values-2.jq similarity index 100% rename from Task/Extreme-floating-point-values/jq/extreme-floating-point-values-2.jq rename to Task/Extreme-floating-point-values/Jq/extreme-floating-point-values-2.jq diff --git a/Task/Extreme-floating-point-values/jq/extreme-floating-point-values-3.jq b/Task/Extreme-floating-point-values/Jq/extreme-floating-point-values-3.jq similarity index 100% rename from Task/Extreme-floating-point-values/jq/extreme-floating-point-values-3.jq rename to Task/Extreme-floating-point-values/Jq/extreme-floating-point-values-3.jq diff --git a/Task/Extreme-floating-point-values/jq/extreme-floating-point-values-4.jq b/Task/Extreme-floating-point-values/Jq/extreme-floating-point-values-4.jq similarity index 100% rename from Task/Extreme-floating-point-values/jq/extreme-floating-point-values-4.jq rename to Task/Extreme-floating-point-values/Jq/extreme-floating-point-values-4.jq diff --git a/Task/Extreme-floating-point-values/jq/extreme-floating-point-values-5.jq b/Task/Extreme-floating-point-values/Jq/extreme-floating-point-values-5.jq similarity index 100% rename from Task/Extreme-floating-point-values/jq/extreme-floating-point-values-5.jq rename to Task/Extreme-floating-point-values/Jq/extreme-floating-point-values-5.jq diff --git a/Task/Extreme-floating-point-values/Julia/extreme-floating-point-values.julia b/Task/Extreme-floating-point-values/Julia/extreme-floating-point-values.julia new file mode 100644 index 0000000000..2f6886e3e1 --- /dev/null +++ b/Task/Extreme-floating-point-values/Julia/extreme-floating-point-values.julia @@ -0,0 +1,16 @@ +function showextremes() + values = [0.0, -0.0, Inf, -Inf, NaN] + println(1 ./ values) +end + +showextremes() + +@show Inf + 2.0 +@show Inf + Inf +@show Inf - Inf +@show Inf * Inf +@show Inf / Inf +@show Inf * 0 +@show 0 == -0 +@show NaN == NaN +@show NaN === NaN diff --git a/Task/Extreme-floating-point-values/Kotlin/extreme-floating-point-values.kotlin b/Task/Extreme-floating-point-values/Kotlin/extreme-floating-point-values.kotlin new file mode 100644 index 0000000000..f3ab0a2a5f --- /dev/null +++ b/Task/Extreme-floating-point-values/Kotlin/extreme-floating-point-values.kotlin @@ -0,0 +1,28 @@ +// version 1.0.5-2 + +@Suppress("DIVISION_BY_ZERO", "FLOAT_LITERAL_CONFORMS_ZERO") + +fun main(args: Array) { + val inf = 1.0 / 0.0 + val negInf = -1.0 / 0.0 + val nan = 0.0 / 0.0 + val negZero = -1.0e-325 + + println("*** Indirect ***\n") + println("Infinity : $inf") + println("Negative infinity : $negInf") + println("Not a number : $nan") + println("Negative zero : $negZero") + + println("\n*** Direct ***\n") + println("Infinity : ${Double.POSITIVE_INFINITY}") + println("Negative infinity : ${Double.NEGATIVE_INFINITY}") + println("Not a number : ${Double.NaN}") + println("Negative zero : ${-0.0}") + + println("\n*** Calculations ***\n") + println("inf * inf : ${inf * inf}") + println("inf + negInf : ${inf + negInf}") + println("nan / nan : ${nan / nan}") + println("negZero + 0.0 : ${negZero + 0.0}") +} diff --git a/Task/Extreme-floating-point-values/Lua/extreme-floating-point-values-1.lua b/Task/Extreme-floating-point-values/Lua/extreme-floating-point-values-1.lua new file mode 100644 index 0000000000..024bece6ec --- /dev/null +++ b/Task/Extreme-floating-point-values/Lua/extreme-floating-point-values-1.lua @@ -0,0 +1,4 @@ +local inf=math.huge +local minusInf=-math.huge +local NaN=0/0 +local negativeZeroSorta=-1E-240 diff --git a/Task/Extreme-floating-point-values/Lua/extreme-floating-point-values-2.lua b/Task/Extreme-floating-point-values/Lua/extreme-floating-point-values-2.lua new file mode 100644 index 0000000000..3a80b1ccf9 --- /dev/null +++ b/Task/Extreme-floating-point-values/Lua/extreme-floating-point-values-2.lua @@ -0,0 +1,2 @@ +1/(1/-math.huge)==math.huge +true diff --git a/Task/Extreme-floating-point-values/Rust/extreme-floating-point-values.rust b/Task/Extreme-floating-point-values/Rust/extreme-floating-point-values.rust new file mode 100644 index 0000000000..847a3f2468 --- /dev/null +++ b/Task/Extreme-floating-point-values/Rust/extreme-floating-point-values.rust @@ -0,0 +1,22 @@ +fn main() { + let inf: f64 = 1. / 0.; // or std::f64::INFINITY + let minus_inf: f64 = -1. / 0.; // or std::f64::NEG_INFINITY + let minus_zero: f64 = -1. / inf; // or -0.0 + let nan: f64 = 0. / 0.; // or std::f64::NAN + // or std::f32 for the above + println!("positive infinity: {:+}", inf); + println!("negative infinity: {:+}", minus_inf); + println!("negative zero: {:+?}", minus_zero); + println!("not a number: {:+}", nan); + println!(); + println!("+inf + 2.0 = {:+}", inf + 2.); + println!("+inf - 10.0 = {:+}", inf - 10.); + println!("+inf + -inf = {:+}", inf + minus_inf); + println!("0.0 * inf = {:+}", 0. * inf); + println!("1.0 / -0.0 = {:+}", 1. / -0.); + println!("NaN + 1.0 = {:+}", nan + 1.); + println!("NaN + NaN = {:+}", nan + nan); + println!(); + println!("NaN == NaN = {}", nan == nan); + println!("0.0 == -0.0 = {}", 0. == -0.); +} diff --git a/Task/Extreme-floating-point-values/S-lang/extreme-floating-point-values-1.slang b/Task/Extreme-floating-point-values/S-lang/extreme-floating-point-values-1.slang new file mode 100644 index 0000000000..81ebe2df1d --- /dev/null +++ b/Task/Extreme-floating-point-values/S-lang/extreme-floating-point-values-1.slang @@ -0,0 +1,5 @@ +foreach $1 ([{-0.0}, {_Inf, "1.0/0"}, {-_Inf, "-1.0/0"}, {_NaN}]) { + () = printf("%S", $1[0]); + if (length($1) > 1) () = printf("\t%S\n", eval($1[1])); + else () = printf("\n"); +} diff --git a/Task/Extreme-floating-point-values/S-lang/extreme-floating-point-values-2.slang b/Task/Extreme-floating-point-values/S-lang/extreme-floating-point-values-2.slang new file mode 100644 index 0000000000..667326e094 --- /dev/null +++ b/Task/Extreme-floating-point-values/S-lang/extreme-floating-point-values-2.slang @@ -0,0 +1,4 @@ +% And make some comparisons: +() = printf("-0.0 and 0.0 are %sequal\n", -0.0 == 0.0 ? "" : "not "); +() = printf("-_Inf == _Inf are %sequal\n", -_Inf == _Inf ? "" : "not "); +() = printf("-0.0 and 0.0 are %sthe 'same'\n", __is_same(-0.0, 0.0) ? "" : "not "); diff --git a/Task/Extreme-floating-point-values/Stata/extreme-floating-point-values.stata b/Task/Extreme-floating-point-values/Stata/extreme-floating-point-values.stata new file mode 100644 index 0000000000..8d16a41bef --- /dev/null +++ b/Task/Extreme-floating-point-values/Stata/extreme-floating-point-values.stata @@ -0,0 +1,11 @@ +. display %21x . ++1.0000000000000X+3ff + +. display %21x .a ++1.0010000000000X+3ff + +. display %21x .z ++1.01a0000000000X+3ff + +. display %21x c(maxdouble) ++1.fffffffffffffX+3fe diff --git a/Task/Factorial/00DESCRIPTION b/Task/Factorial/00DESCRIPTION index b708d7953f..3f49c6dda1 100644 --- a/Task/Factorial/00DESCRIPTION +++ b/Task/Factorial/00DESCRIPTION @@ -1,7 +1,7 @@ ;Definitions: +:*   The factorial of   '''0'''   (zero)   is [[wp:Factorial#Definition|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 -:*   The factorial of   '''0'''   (zero)   is [[wp:Factorial#Definition|defined]] as being   1   (unity). ;Task: diff --git a/Task/Factorial/ALGOL-M/factorial.algol-m b/Task/Factorial/ALGOL-M/factorial.algol-m new file mode 100644 index 0000000000..eea6507f4c --- /dev/null +++ b/Task/Factorial/ALGOL-M/factorial.algol-m @@ -0,0 +1,8 @@ +INTEGER FUNCTION FACTORIAL( N ); INTEGER N; +BEGIN + INTEGER I, FACT; + FACT := 1; + FOR I := 2 STEP 1 UNTIL N DO + FACT := FACT * I; + FACTORIAL := FACT; +END; diff --git a/Task/Factorial/AppleScript/factorial-3.applescript b/Task/Factorial/AppleScript/factorial-3.applescript index a283ee3f8d..5e78df0c5c 100644 --- a/Task/Factorial/AppleScript/factorial-3.applescript +++ b/Task/Factorial/AppleScript/factorial-3.applescript @@ -1,17 +1,18 @@ +-- FACTORIAL ----------------------------------------------------------------- + -- factorial :: Int -> Int on factorial(x) script product - on lambda(a, b) + on |λ|(a, b) a * b - end lambda + end |λ| end script - foldl(product, 1, range(1, x)) + foldl(product, 1, enumFromTo(1, x)) end factorial - --- TEST +-- TEST ---------------------------------------------------------------------- on run factorial(11) @@ -21,23 +22,11 @@ on run end run --- GENERIC LIBRARY PRIMITIVES +-- GENERIC FUNCTIONS --------------------------------------------------------- --- foldl :: (a -> b -> a) -> a -> [b] -> a -on foldl(f, startValue, xs) - tell mReturn(f) - set v to startValue - set lng to length of xs - repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) - end repeat - return v - end tell -end foldl - --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then set d to -1 else set d to 1 @@ -47,8 +36,19 @@ on range(m, n) set end of lst to i end repeat return lst -end range +end enumFromTo +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -57,7 +57,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Factorial/BASIC/factorial-3.basic b/Task/Factorial/BASIC/factorial-3.basic new file mode 100644 index 0000000000..7923959fce --- /dev/null +++ b/Task/Factorial/BASIC/factorial-3.basic @@ -0,0 +1,11 @@ +10 REM FACTORIAL +20 REM COMMODORE BASIC 2.0 +30 N = 10 : GOSUB 100 +40 PRINT N"! ="F +50 END +100 REM FACTORIAL CALC USING SIMPLE LOOP +110 F = 1 +120 FOR I=1 TO N +130 F = F*I +140 NEXT +150 RETURN diff --git a/Task/Factorial/BASIC/factorial-4.basic b/Task/Factorial/BASIC/factorial-4.basic new file mode 100644 index 0000000000..ed2c8cd76d --- /dev/null +++ b/Task/Factorial/BASIC/factorial-4.basic @@ -0,0 +1,6 @@ + 10 INPUT N + 20 LET FACT=1 + 30 FOR I=2 TO N + 40 LET FACT=FACT*I + 50 NEXT I + 60 PRINT FACT diff --git a/Task/Factorial/BASIC/factorial-5.basic b/Task/Factorial/BASIC/factorial-5.basic new file mode 100644 index 0000000000..211173100d --- /dev/null +++ b/Task/Factorial/BASIC/factorial-5.basic @@ -0,0 +1,10 @@ + 10 INPUT N + 20 LET FACT=1 + 30 GOSUB 60 + 40 PRINT FACT + 50 STOP + 60 IF N=0 THEN RETURN + 70 LET FACT=FACT*N + 80 LET N=N-1 + 90 GOSUB 60 +100 RETURN diff --git a/Task/Factorial/BaCon/factorial.bacon b/Task/Factorial/BaCon/factorial.bacon new file mode 100644 index 0000000000..df6aaa0d09 --- /dev/null +++ b/Task/Factorial/BaCon/factorial.bacon @@ -0,0 +1,11 @@ +' Factorial +FUNCTION factorial(NUMBER n) TYPE NUMBER + IF n <= 1 THEN + RETURN 1 + ELSE + RETURN n * factorial(n - 1) + ENDIF +END FUNCTION + +n = VAL(TOKEN$(ARGUMENT$, 2)) +PRINT n, factorial(n) FORMAT "%ld! = %ld\n" diff --git a/Task/Factorial/Bc/factorial.bc b/Task/Factorial/Bc/factorial.bc new file mode 100644 index 0000000000..48527eaf28 --- /dev/null +++ b/Task/Factorial/Bc/factorial.bc @@ -0,0 +1,7 @@ +#! /usr/bin/bc -q + +define f(x) { + if (x <= 1) return (1); return (f(x-1) * x) +} +f(1000) +quit diff --git a/Task/Factorial/Beeswax/factorial-1.beeswax b/Task/Factorial/Beeswax/factorial-1.beeswax new file mode 100644 index 0000000000..29d44e9844 --- /dev/null +++ b/Task/Factorial/Beeswax/factorial-1.beeswax @@ -0,0 +1,4 @@ + p < +_>1FT"pF>M"p~.~d + >Pd >~{Np + d < diff --git a/Task/Factorial/Beeswax/factorial-2.beeswax b/Task/Factorial/Beeswax/factorial-2.beeswax new file mode 100644 index 0000000000..79238526be --- /dev/null +++ b/Task/Factorial/Beeswax/factorial-2.beeswax @@ -0,0 +1,3 @@ + p < +_1FT"pF>M"p~.~d + >Pd >~{; diff --git a/Task/Factorial/Beeswax/factorial-3.beeswax b/Task/Factorial/Beeswax/factorial-3.beeswax new file mode 100644 index 0000000000..7547910dea --- /dev/null +++ b/Task/Factorial/Beeswax/factorial-3.beeswax @@ -0,0 +1,13 @@ +julia> beeswax("factorial.bswx") +i0 +1 +i1 +1 +i2 +2 +i3 +6 +i10 +3628800 +i22 +17196083355034583040 diff --git a/Task/Factorial/Comefrom0x10/factorial.comefrom0x10 b/Task/Factorial/Comefrom0x10/factorial.comefrom0x10 new file mode 100644 index 0000000000..6cc9fcb57e --- /dev/null +++ b/Task/Factorial/Comefrom0x10/factorial.comefrom0x10 @@ -0,0 +1,15 @@ +n = 5 # calculates n! +acc = 1 + +factorial + comefrom + + comefrom accumulate if n < 1 + +accumulate + comefrom factorial + acc = acc * n + comefrom factorial if n is 0 + n = n - 1 + +acc # prints the result diff --git a/Task/Factorial/Dc/factorial.dc b/Task/Factorial/Dc/factorial.dc new file mode 100644 index 0000000000..9895287dbb --- /dev/null +++ b/Task/Factorial/Dc/factorial.dc @@ -0,0 +1,19 @@ +[* + * (n) lfx -- (factorial of n) + *]sz +[ + 1 Sp [product = 1]sz + [ [Loop while 1 < n:]sz + d lp * sp [product = n * product]sz + 1 - [n = n - 1]sz + d 1 1, do: fac_tail(n - 1, acc * n) + # Tail recursive function with default parameter + def fac_default(n, acc \\ 1) + def fac_default(0, acc), do: acc + def fac_default(n, acc) when n > 0, do: fac_default(n - 1, acc * n) + # Using Enumeration features def fac_reduce(0), do: 1 def fac_reduce(n) when n > 0, do: Enum.reduce(1..n, 1, &*/2) + + # Using Enumeration features with pipe operator + def fac_pipe(0), do: 1 + def fac_pipe(n) when n > 0, do: 1..n |> Enum.reduce(1, &*/2) + end diff --git a/Task/Factorial/Friendly-interactive-shell/factorial-1.fish b/Task/Factorial/Friendly-interactive-shell/factorial-1.fish new file mode 100644 index 0000000000..05752944cb --- /dev/null +++ b/Task/Factorial/Friendly-interactive-shell/factorial-1.fish @@ -0,0 +1,8 @@ +function factorial + set x $argv[1] + set result 1 + for i in (seq $x) + set result (expr $i '*' $result) + end + echo $result +end diff --git a/Task/Factorial/Friendly-interactive-shell/factorial-2.fish b/Task/Factorial/Friendly-interactive-shell/factorial-2.fish new file mode 100644 index 0000000000..51e6bfa538 --- /dev/null +++ b/Task/Factorial/Friendly-interactive-shell/factorial-2.fish @@ -0,0 +1,8 @@ +function factorial + set x $argv[1] + if [ $x -eq 1 ] + echo 1 + else + expr (factorial (expr $x - 1)) '*' $x + end +end diff --git a/Task/Factorial/Gnuplot/factorial-1.gnuplot b/Task/Factorial/Gnuplot/factorial-1.gnuplot new file mode 100644 index 0000000000..c70ee81bd0 --- /dev/null +++ b/Task/Factorial/Gnuplot/factorial-1.gnuplot @@ -0,0 +1,3 @@ +set xrange [0:4.95] +set key left +plot int(x)! diff --git a/Task/Factorial/Gnuplot/factorial-2.gnuplot b/Task/Factorial/Gnuplot/factorial-2.gnuplot new file mode 100644 index 0000000000..f7884782f2 --- /dev/null +++ b/Task/Factorial/Gnuplot/factorial-2.gnuplot @@ -0,0 +1,11 @@ +# Using int(n) allows non-integer "n" inputs with the factorial +# calculated on int(n) in that case. +# Arranging the condition as "n>=2" avoids infinite recursion if +# n==NaN, since any comparison involving NaN is false. Could change +# "1" to an expression like "n*0+1" to propagate a NaN input to the +# output too, if desired. +# +factorial(n) = (n >= 2 ? int(n)*factorial(n-1) : 1) +set xrange [0:4.95] +set key left +plot factorial(x) diff --git a/Task/Factorial/Groovy/factorial-4.groovy b/Task/Factorial/Groovy/factorial-4.groovy deleted file mode 100644 index 6100d01f08..0000000000 --- a/Task/Factorial/Groovy/factorial-4.groovy +++ /dev/null @@ -1 +0,0 @@ -(0..6).each { println "${it}: ${iFact(it)}" } diff --git a/Task/Factorial/Hy/factorial.hy b/Task/Factorial/Hy/factorial.hy new file mode 100644 index 0000000000..4932fa6ee2 --- /dev/null +++ b/Task/Factorial/Hy/factorial.hy @@ -0,0 +1,7 @@ +(defn ! [n] + (reduce * + (range 1 (inc n)) + 1)) + +(print (! 6)) ; 720 +(print (! 0)) ; 1 diff --git a/Task/Factorial/JavaScript/factorial-1.js b/Task/Factorial/JavaScript/factorial-1.js index 2a3e0d135c..9d8d214b38 100644 --- a/Task/Factorial/JavaScript/factorial-1.js +++ b/Task/Factorial/JavaScript/factorial-1.js @@ -6,7 +6,7 @@ function factorial(n) { //we skip zero and one since both are 1 and are identity while (n > 1) { sum *= n; - n -= 1; + n--; } return sum; } diff --git a/Task/Factorial/jq/factorial-1.jq b/Task/Factorial/Jq/factorial-1.jq similarity index 100% rename from Task/Factorial/jq/factorial-1.jq rename to Task/Factorial/Jq/factorial-1.jq diff --git a/Task/Factorial/jq/factorial-2.jq b/Task/Factorial/Jq/factorial-2.jq similarity index 100% rename from Task/Factorial/jq/factorial-2.jq rename to Task/Factorial/Jq/factorial-2.jq diff --git a/Task/Factorial/jq/factorial-3.jq b/Task/Factorial/Jq/factorial-3.jq similarity index 100% rename from Task/Factorial/jq/factorial-3.jq rename to Task/Factorial/Jq/factorial-3.jq diff --git a/Task/Factorial/Klong/factorial.klong b/Task/Factorial/Klong/factorial.klong index 4d7e8f4f08..a9d0d78129 100644 --- a/Task/Factorial/Klong/factorial.klong +++ b/Task/Factorial/Klong/factorial.klong @@ -1,2 +1,2 @@ - factRecursive::{:[x>1;x*_.f(x-1);1]} + factRecursive::{:[x>1;x*.f(x-1);1]} factIterative::{*/1+!x} diff --git a/Task/Factorial/Kotlin/factorial.kotlin b/Task/Factorial/Kotlin/factorial.kotlin index b259f35c70..b02001b531 100644 --- a/Task/Factorial/Kotlin/factorial.kotlin +++ b/Task/Factorial/Kotlin/factorial.kotlin @@ -1,6 +1,6 @@ fun facti(n: Int) = when { n < 0 -> throw IllegalArgumentException("negative numbers not allowed") - else -> { + else -> { var ans = 1L for (i in 2..n) ans *= i ans @@ -10,7 +10,7 @@ fun facti(n: Int) = when { fun factr(n: Int): Long = when { n < 0 -> throw IllegalArgumentException("negative numbers not allowed") n < 2 -> 1L - else -> n * factr(n - 1) + else -> n * factr(n - 1) } fun main(args: Array) { diff --git a/Task/Factorial/NewLISP/factorial.newlisp b/Task/Factorial/NewLISP/factorial.newlisp new file mode 100644 index 0000000000..df982e6f93 --- /dev/null +++ b/Task/Factorial/NewLISP/factorial.newlisp @@ -0,0 +1,4 @@ +> (define (factorial n) (exp (gammaln (+ n 1)))) +(lambda (n) (exp (gammaln (+ n 1)))) +> (factorial 4) +24 diff --git a/Task/Factorial/Protium/factorial-1.protium b/Task/Factorial/Protium/factorial-1.protium deleted file mode 100644 index 689459dd2c..0000000000 --- a/Task/Factorial/Protium/factorial-1.protium +++ /dev/null @@ -1 +0,0 @@ -<@ SAYFCTLIT>5 diff --git a/Task/Factorial/Protium/factorial-2.protium b/Task/Factorial/Protium/factorial-2.protium deleted file mode 100644 index 006917e3a4..0000000000 --- a/Task/Factorial/Protium/factorial-2.protium +++ /dev/null @@ -1,2 +0,0 @@ -<@ DEFUDOLITLIT>FAT|__Transformer|<@ LETSCPLIT>result|1<@ ITEFORPARLIT>1|<@ ACTMULSCPPOSFOR>result|...<@ LETRESSCP>...|result -<@ SAYFATLIT>123 diff --git a/Task/Factorial/Python/factorial-6.py b/Task/Factorial/Python/factorial-6.py deleted file mode 100644 index 5bf8836512..0000000000 --- a/Task/Factorial/Python/factorial-6.py +++ /dev/null @@ -1,5 +0,0 @@ -def factorial(n): - z=1 - if n>1: - z=n*factorial(n-1) - return z diff --git a/Task/Factorial/Rascal/factorial-4.rascal b/Task/Factorial/Rascal/factorial-4.rascal deleted file mode 100644 index ac0fc94a25..0000000000 --- a/Task/Factorial/Rascal/factorial-4.rascal +++ /dev/null @@ -1,4 +0,0 @@ -public int factorial_rec(int n){ - if(n>1) return n*factorial_rec(n-1); - else return 1; -} diff --git a/Task/Factorial/Rascal/factorial-5.rascal b/Task/Factorial/Rascal/factorial-5.rascal deleted file mode 100644 index 668fd98e4c..0000000000 --- a/Task/Factorial/Rascal/factorial-5.rascal +++ /dev/null @@ -1,2 +0,0 @@ -rascal>factorial_rec(10) -int: 3628800 diff --git a/Task/Factorial/SPL/factorial.spl b/Task/Factorial/SPL/factorial.spl new file mode 100644 index 0000000000..8458e226e2 --- /dev/null +++ b/Task/Factorial/SPL/factorial.spl @@ -0,0 +1,4 @@ +fact(n)= + ? n!>1, <=1 + <= n*fact(n-1) +. diff --git a/Task/Factorial/Scilab/factorial-4.scilab b/Task/Factorial/Scilab/factorial-4.scilab new file mode 100644 index 0000000000..7f1a62310c --- /dev/null +++ b/Task/Factorial/Scilab/factorial-4.scilab @@ -0,0 +1,3 @@ +function f=factorgamma(n) + f = gamma(n+1) +endfunction diff --git a/Task/Factorial/Sidef/factorial-1.sidef b/Task/Factorial/Sidef/factorial-1.sidef new file mode 100644 index 0000000000..028432ba59 --- /dev/null +++ b/Task/Factorial/Sidef/factorial-1.sidef @@ -0,0 +1,3 @@ +func factorial_recursive(n) { + n == 0 ? 1 : (n * __FUNC__(n-1)) +} diff --git a/Task/Factorial/Sidef/factorial-2.sidef b/Task/Factorial/Sidef/factorial-2.sidef new file mode 100644 index 0000000000..84f39f5878 --- /dev/null +++ b/Task/Factorial/Sidef/factorial-2.sidef @@ -0,0 +1,3 @@ +func factorial_reduce(n) { + 1..n -> reduce({|a,b| a * b }, 1) +} diff --git a/Task/Factorial/Sidef/factorial-3.sidef b/Task/Factorial/Sidef/factorial-3.sidef new file mode 100644 index 0000000000..96a7e1788e --- /dev/null +++ b/Task/Factorial/Sidef/factorial-3.sidef @@ -0,0 +1,5 @@ +func factorial_iterative(n) { + var f = 1 + {|i| f *= i } << 2..n + return f +} diff --git a/Task/Factorial/Sidef/factorial-4.sidef b/Task/Factorial/Sidef/factorial-4.sidef new file mode 100644 index 0000000000..44f2f6ac12 --- /dev/null +++ b/Task/Factorial/Sidef/factorial-4.sidef @@ -0,0 +1 @@ +say 5! diff --git a/Task/Factorial/Sidef/factorial.sidef b/Task/Factorial/Sidef/factorial.sidef deleted file mode 100644 index 0d91366547..0000000000 --- a/Task/Factorial/Sidef/factorial.sidef +++ /dev/null @@ -1,19 +0,0 @@ -# Recursive -func factorial_recursive(n) { - n == 0 ? 1 : (n * __FUNC__(n-1)); -} - -# Iterative with Array#reduce -func factorial_reduce(n) { - 1..n -> reduce('*'); -} - -# Iterative with Block#repeat -func factorial_iterative(n) { - var f = 1; - {|i| f *= i } * n; - return f; -} - -# Built-in Number#factorial: -say 5!; diff --git a/Task/Factorial/Slate/factorial-3.slate b/Task/Factorial/Slate/factorial-3.slate deleted file mode 100644 index 0b23e91bf5..0000000000 --- a/Task/Factorial/Slate/factorial-3.slate +++ /dev/null @@ -1,2 +0,0 @@ -slate[5]> 100 factorial. -93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 diff --git a/Task/Factorial/Stata/factorial.stata b/Task/Factorial/Stata/factorial.stata new file mode 100644 index 0000000000..dc21836fc4 --- /dev/null +++ b/Task/Factorial/Stata/factorial.stata @@ -0,0 +1,15 @@ +mata +real scalar function fact1(real scalar n) { + if (n<2) return(1) + else return(fact1(n-1)*n) +} + +real scalar function fact2(real scalar n) { + a=1 + for (i=2;i<=n;i++) a=a*i + return(a) +} + +printf("%f\n",fact1(8)) +printf("%f\n",fact2(8)) +printf("%f\n",factorial(8)) diff --git a/Task/Factorial/Swift/factorial-1.swift b/Task/Factorial/Swift/factorial-1.swift index 3e18273713..70ab9722ae 100644 --- a/Task/Factorial/Swift/factorial-1.swift +++ b/Task/Factorial/Swift/factorial-1.swift @@ -1,4 +1,3 @@ -func factorial(num: Int) -> Int { - - return num < 1 ? 1 : reduce(1...num, 1, *) +func factorial(_ n: Int) -> Int { + return n < 2 ? 1 : (2...n).reduce(1, *) } diff --git a/Task/Factorial/Swift/factorial-2.swift b/Task/Factorial/Swift/factorial-2.swift index 8d87119921..30a3938328 100644 --- a/Task/Factorial/Swift/factorial-2.swift +++ b/Task/Factorial/Swift/factorial-2.swift @@ -1,4 +1,3 @@ -func factorial(num: Int) -> Int { - - return num < 1 ? 1 : num * factorial(num - 1) +func factorial(_ n: Int) -> Int { + return n < 2 ? 1 : n * factorial(n - 1) } diff --git a/Task/Factorial/TransFORTH/factorial.transforth b/Task/Factorial/TransFORTH/factorial.transforth new file mode 100644 index 0000000000..9ab1d0c2ec --- /dev/null +++ b/Task/Factorial/TransFORTH/factorial.transforth @@ -0,0 +1,4 @@ +: FACTORIAL +1 SWAP +1 + 1 DO +I * LOOP ; diff --git a/Task/Factorial/X86-Assembly/factorial-1.x86 b/Task/Factorial/X86-Assembly/factorial-1.x86 new file mode 100644 index 0000000000..5d6af085f5 --- /dev/null +++ b/Task/Factorial/X86-Assembly/factorial-1.x86 @@ -0,0 +1,11 @@ +global factorial +section .text + +; Input in ECX register (greater than 0!) +; Output in EAX register +factorial: + mov eax, 1 +.factor: + mul ecx + loop .factor + ret diff --git a/Task/Factorial/X86-Assembly/factorial-2.x86 b/Task/Factorial/X86-Assembly/factorial-2.x86 new file mode 100644 index 0000000000..246f0f8a01 --- /dev/null +++ b/Task/Factorial/X86-Assembly/factorial-2.x86 @@ -0,0 +1,20 @@ +global fact +section .text + +; Input and output in EAX register +fact: + cmp eax, 1 + je .done ; if eax == 1 goto done + + ; inductive case + push eax ; save n (ie. what EAX is) + dec eax ; n - 1 + call fact ; fact(n - 1) + pop ebx ; fetch old n + mul ebx ; multiplies EAX with EBX, ie. n * fac(n - 1) + ret + +.done: + ; base case: return 1 + mov eax, 1 + ret diff --git a/Task/Factorial/X86-Assembly/factorial-3.x86 b/Task/Factorial/X86-Assembly/factorial-3.x86 new file mode 100644 index 0000000000..939341b918 --- /dev/null +++ b/Task/Factorial/X86-Assembly/factorial-3.x86 @@ -0,0 +1,17 @@ +global factorial +section .text + +; Input in ECX register +; Output in EAX register +factorial: + mov eax, 1 ; default argument, store 1 in accumulator + +.base_case: + test ecx, ecx + jnz .inductive_case ; return accumulator if n == 0 + ret + +.inductive_case: + mul ecx ; accumulator *= n + dec ecx ; n -= 1 + jmp .base_case ; tail call diff --git a/Task/Factorial/XLISP/factorial.xlisp b/Task/Factorial/XLISP/factorial.xlisp new file mode 100644 index 0000000000..56ea612ac6 --- /dev/null +++ b/Task/Factorial/XLISP/factorial.xlisp @@ -0,0 +1,6 @@ +(defun factorial (x) + (if (< x 0) + nil + (if (<= x 1) + 1 + (* x (factorial (- x 1))) ) ) ) diff --git a/Task/Factorial/Zkl/factorial-1.zkl b/Task/Factorial/Zkl/factorial-1.zkl new file mode 100644 index 0000000000..dddf6c3cc5 --- /dev/null +++ b/Task/Factorial/Zkl/factorial-1.zkl @@ -0,0 +1,5 @@ +fcn fact(n){[2..n].reduce('*,1)} +fcn factTail(n,N=1) { // tail recursion + if (n == 0) return(N); + return(self.fcn(n-1,n*N)); +} diff --git a/Task/Factorial/Zkl/factorial-2.zkl b/Task/Factorial/Zkl/factorial-2.zkl new file mode 100644 index 0000000000..79f5109181 --- /dev/null +++ b/Task/Factorial/Zkl/factorial-2.zkl @@ -0,0 +1,3 @@ +fact(6).println(); +var BN=Import("zklBigNum"); +factTail(BN(42)) : "%,d".fmt(_).println(); // built in as BN(42).factorial() diff --git a/Task/Factors-of-a-Mersenne-number/00DESCRIPTION b/Task/Factors-of-a-Mersenne-number/00DESCRIPTION index 0de4dde3f3..dfc86bf8a1 100644 --- a/Task/Factors-of-a-Mersenne-number/00DESCRIPTION +++ b/Task/Factors-of-a-Mersenne-number/00DESCRIPTION @@ -17,14 +17,14 @@ Convert the exponent 23 to binary, you get 10111. Starting with square Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: - Remove Optional - square top bit multiply by 2 mod 47 - ------------ ------- ------------- ------ - 1*1 = 1 1 0111 1*2 = 2 2 - 2*2 = 4 0 111 no 4 - 4*4 = 16 1 11 16*2 = 32 32 - 32*32 = 1024 1 1 1024*2 = 2048 27 - 27*27 = 729 1 729*2 = 1458 1 + remove optional + square top bit multiply by 2 mod 47 + ──────────── ─────── ───────────── ────── + 1*1 = 1 1 0111 1*2 = 2 2 + 2*2 = 4 0 111 no 4 + 4*4 = 16 1 11 16*2 = 32 32 + 32*32 = 1024 1 1 1024*2 = 2048 27 + 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) @@ -41,6 +41,14 @@ These primality tests only work on Mersenne numbers where P is prime. For exampl Using the above method find a factor of 2929-1 (aka M929) -;Related task: -* [https://www.youtube.com/watch?v=SNwvJ7psoow Computers in 1948: 2¹²⁷-1]
    +;Related tasks: +*   [[count in factors]] +*   [[prime decomposition]] +*   [[factors of an integer]] +*   [[Sieve of Eratosthenes]] +*   [[primality by trial division]] +*   [[trial factoring of a Mersenne number]] +*   [[partition an integer X into N primes]] +*   [[sequence of primes by Trial Division]] +*   [https://www.youtube.com/watch?v=SNwvJ7psoow Computers in 1948: 2¹²⁷-1]

    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.elixir new file mode 100644 index 0000000000..8246c8f8d5 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Elixir/factors-of-a-mersenne-number.elixir @@ -0,0 +1,36 @@ +defmodule Mersenne do + def mersenne_factor(p) do + limit = :math.sqrt(:math.pow(2, p) - 1) + mersenne_loop(p, limit, 1) + end + + defp mersenne_loop(p, limit, k) when (2*k*p - 1) > limit, do: nil + defp mersenne_loop(p, limit, k) do + q = 2*k*p + 1 + if prime?(q) and rem(q,8) in [1,7] and trial_factor(2,p,q), + do: q, else: mersenne_loop(p, limit, k+1) + end + + defp trial_factor(base, exp, mod) do + Integer.digits(exp, 2) + |> Enum.reduce(1, fn bit,square -> + (square * square * (if bit==1, do: base, else: 1)) |> rem(mod) + end) == 1 + end + + def check_mersenne(p) do + IO.write "M#{p} = 2**#{p}-1 is " + f = mersenne_factor(p) + IO.puts if f, do: "composite with factor #{f}", else: "prime" + end + + def prime?(n), do: prime?(n, :math.sqrt(n), 2) + + defp prime?(_, limit, i) when limit < i, do: true + defp prime?(n, limit, i) do + if rem(n,i) == 0, do: false, else: prime?(n, limit, i+1) + end +end + +[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,929] +|> Enum.each(fn p -> Mersenne.check_mersenne(p) 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.julia new file mode 100644 index 0000000000..58d973b9fd --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Julia/factors-of-a-mersenne-number.julia @@ -0,0 +1,24 @@ +# v0.6 + +using Primes + +function mersennefactor(p::Int)::Int + maxk = floor(Int, 16384 / p) + for k in 0:maxk + q = 2p * k + 1 + if ! Primes.isprime(q) + continue + elseif ! (q % 8 in (1, 7)) + continue + elseif powermod(2, p, q) == 1 + return q + end + end + return -1 +end + +for i in push!(collect(1:20), 929) + mf = mersennefactor(i) + if mf != -1; println("M$i = ", mf, " × ", big(2) ^ i ÷ mf) + else println("M$i is prime") end +end 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.kotlin new file mode 100644 index 0000000000..728bb1a26f --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Kotlin/factors-of-a-mersenne-number.kotlin @@ -0,0 +1,47 @@ +// version 1.0.6 + +fun isPrime(n: Int): Boolean { + if (n < 2) return false + if (n % 2 == 0) return n == 2 + if (n % 3 == 0) return n == 3 + var d = 5 + while (d * d <= n) { + if (n % d == 0) return false + d += 2 + if (n % d == 0) return false + d += 4 + } + return true +} + +fun main(args: Array) { + // test 929 plus all prime numbers below 100 which are known not to be Mersenne primes + val q = intArrayOf(11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929) + for (k in 0 until q.size) { + if (isPrime(q[k])) { + var i: Long + var d: Int + var p: Int + var r: Int = q[k] + while (r > 0) r = r shl 1 + d = 2 * q[k] + 1 + while (true) { + i = 1L + p = r + while (p != 0) { + i = (i * i) % d + if (p < 0) i *= 2 + if (i > d) i -= d + p = p shl 1 + } + if (i != 1L) + d += 2 * q[k] + else + break + } + println("2^${"%3d".format(q[k])} - 1 = 0 (mod $d)") + } else { + println("${q[k]} is not prime") + } + } +} 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 new file mode 100644 index 0000000000..a1cd33ea22 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Phix/factors-of-a-mersenne-number.phix @@ -0,0 +1,48 @@ +function is_prime(integer n) + if n<2 then return 0 end if + if n=2 then return 1 end if + if remainder(n,2)=0 then return 0 end if + for i=3 to floor(sqrt(n)) by 2 do + if remainder(n,i)=0 then + return 0 + end if + end for + return 1 +end function + +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 + +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 + +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 diff --git a/Task/Factors-of-a-Mersenne-number/Sidef/factors-of-a-mersenne-number.sidef b/Task/Factors-of-a-Mersenne-number/Sidef/factors-of-a-mersenne-number.sidef index 2811aac19a..98c667b68f 100644 --- a/Task/Factors-of-a-Mersenne-number/Sidef/factors-of-a-mersenne-number.sidef +++ b/Task/Factors-of-a-Mersenne-number/Sidef/factors-of-a-mersenne-number.sidef @@ -1,21 +1,21 @@ func mtest(b, p) { - var bits = b.base(2).to_i.digits + var bits = b.base(2).digits for (var sq = 1; bits; sq %= p) { - sq *= sq; - sq += sq if bits.shift.is_one + sq *= sq + sq += sq if bits.shift==1 } sq == 1 } -for m in (2..60 -> grep{.is_prime} + [929]) { +for m (2..60 -> grep{ .is_prime }, 929) { var f = 0 var x = (2**m - 1) var q - Inf.times { |k| + { |k| q = (2*k*m + 1) q%8 ~~ [1,7] || q.is_prime || next q*q > x || (f = mtest(m, q)) && break - } + } << 1..Inf say (f ? "M#{m} is composite with factor #{q}" : "M#{m} is prime") } diff --git a/Task/Factors-of-a-Mersenne-number/Zkl/factors-of-a-mersenne-number-1.zkl b/Task/Factors-of-a-Mersenne-number/Zkl/factors-of-a-mersenne-number-1.zkl new file mode 100644 index 0000000000..7f5d3c579f --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Zkl/factors-of-a-mersenne-number-1.zkl @@ -0,0 +1,17 @@ +var [const] BN=Import("zklBigNum"); // libGMP + + // M = 2^P - 1 , P prime + // Look for a prime divisor q such as: + // q < M.sqrt(), q = 1 or 7 modulo 8, q = 1 + 2kP + // q is divisor if 2.powmod(P,q) == 1 + // m-divisor returns q or False +fcn m_divisor(P){ + // must limit the search as M.sqrt() may be HUGE and I'm slow + maxPrime:='wrap{ BN(2).pow(P).sqrt().min(0d5_000_000) }; + t,b2:=BN(0),BN(2); // so I can do some in place BigInt math + foreach q in (maxPrime(P*2)){ // 0..maxPrime -1, faster than just odd #s + if((q%8==1 or q%8==7) and t.set(q).probablyPrime() and + b2.powm(P,q)==1) return(q); + } + False +} diff --git a/Task/Factors-of-a-Mersenne-number/Zkl/factors-of-a-mersenne-number-2.zkl b/Task/Factors-of-a-Mersenne-number/Zkl/factors-of-a-mersenne-number-2.zkl new file mode 100644 index 0000000000..b0f87637db --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Zkl/factors-of-a-mersenne-number-2.zkl @@ -0,0 +1,3 @@ +m_divisor(929).println(); // 13007 +m_divisor(4423).println(); // False +(BN(2).pow(4423) - 1).probablyPrime().println(); // True diff --git a/Task/Factors-of-an-integer/00DESCRIPTION b/Task/Factors-of-an-integer/00DESCRIPTION index c9104f9e64..41f968ab60 100644 --- a/Task/Factors-of-an-integer/00DESCRIPTION +++ b/Task/Factors-of-an-integer/00DESCRIPTION @@ -12,6 +12,14 @@ These factors are the positive integers by which the number being factored can b Note that every prime number has two factors:   '''1'''   and itself. -;Related task: -*   [[Prime decomposition]] +;Related tasks: +*   [[count in factors]] +*   [[prime decomposition]] +*   [[Sieve of Eratosthenes]] +*   [[primality by trial division]] +*   [[factors of a Mersenne number]] +*   [[trial factoring of a Mersenne number]] +*   [[partition an integer X into N primes]] +*   [[sequence of primes by Trial Division]] +

    diff --git a/Task/Factors-of-an-integer/AppleScript/factors-of-an-integer-1.applescript b/Task/Factors-of-an-integer/AppleScript/factors-of-an-integer-1.applescript index 6db19874d2..59fb673549 100644 --- a/Task/Factors-of-an-integer/AppleScript/factors-of-an-integer-1.applescript +++ b/Task/Factors-of-an-integer/AppleScript/factors-of-an-integer-1.applescript @@ -9,19 +9,19 @@ on integerFactors(n) -- isFactor :: Int -> Bool script isFactor - on lambda(x) + on |λ|(x) (n mod x) = 0 - end lambda + end |λ| end script -- Factors up to square root of n, - set lows to filter(isFactor, range(1, intRoot)) + set lows to filter(isFactor, enumFromTo(1, intRoot)) -- integerQuotient :: Int -> Int script integerQuotient - on lambda(x) + on |λ|(x) (n / x) as integer - end lambda + end |λ| end script -- and quotients of these factors beyond the square root. @@ -30,8 +30,7 @@ on integerFactors(n) end if end integerFactors - --- TEST +-- TEST ------------------------------------------------------------------------ on run integerFactors(120) @@ -40,8 +39,21 @@ on run end run +-- GENERIC FUNCTIONS ----------------------------------------------------------- --- GENERIC LIBRARY FUNCTIONS +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if n < m then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) @@ -50,7 +62,7 @@ on filter(f, xs) set lng to length of xs repeat with i from 1 to lng set v to item i of xs - if lambda(v, i, xs) then set end of lst to v + if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell @@ -62,26 +74,12 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then - set d to -1 - else - set d to 1 - end if - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range - -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) @@ -89,7 +87,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Factors-of-an-integer/BASIC/factors-of-an-integer.basic b/Task/Factors-of-an-integer/BASIC/factors-of-an-integer-1.basic similarity index 100% rename from Task/Factors-of-an-integer/BASIC/factors-of-an-integer.basic rename to Task/Factors-of-an-integer/BASIC/factors-of-an-integer-1.basic diff --git a/Task/Factors-of-an-integer/BASIC/factors-of-an-integer-2.basic b/Task/Factors-of-an-integer/BASIC/factors-of-an-integer-2.basic new file mode 100644 index 0000000000..3c3ad41837 --- /dev/null +++ b/Task/Factors-of-an-integer/BASIC/factors-of-an-integer-2.basic @@ -0,0 +1,4 @@ +10 INPUT N +20 FOR I=1 TO N +30 IF N/I=INT (N/I) THEN PRINT I;" "; +40 NEXT I diff --git a/Task/Factors-of-an-integer/Bc/factors-of-an-integer.bc b/Task/Factors-of-an-integer/Bc/factors-of-an-integer.bc new file mode 100644 index 0000000000..bdd84142b7 --- /dev/null +++ b/Task/Factors-of-an-integer/Bc/factors-of-an-integer.bc @@ -0,0 +1,44 @@ +/* Calculate the factors of n and return their count. + * This function mutates the global array f[] which will + * contain all factors of n in ascending order after the call! + */ +define f(n) { + auto i, d, h, h[], l, o + /* Local variables: + * i: Loop variable. + * d: Complementary (higher) factor to i. + * h: Will always point to the last element of h[]. + * h[]: Array to hold the greater factor of the pair (x, y), where + * x * y == n. The factors are stored in descending order. + * l: Will always point to the next free spot in f[]. + * o: For saving the value of scale. + */ + + /* Use integer arithmetic */ + o = scale + scale = 0 + + /* Two factors are 1 and n (if n != 1) */ + f[l++] = 1 + if (n == 1) return(1) + h[0] = n + + /* Main loop */ + for (i = 2; i < h[h]; i++) { + if (n % i == 0) { + d = n / i + if (d != i) { + h[++h] = d + } + f[l++] = i + } + } + + /* Append the values in h[] to f[] */ + while (h >= 0) { + f[l++] = h[h--] + } + + scale = o + return(l) +} diff --git a/Task/Factors-of-an-integer/CoffeeScript/factors-of-an-integer-1.coffee b/Task/Factors-of-an-integer/CoffeeScript/factors-of-an-integer-1.coffee deleted file mode 100644 index 50fa310a15..0000000000 --- a/Task/Factors-of-an-integer/CoffeeScript/factors-of-an-integer-1.coffee +++ /dev/null @@ -1,59 +0,0 @@ -# Reference implementation for finding factors is slow, but hopefully -# robust--we'll use it to verify the more complicated (but hopefully faster) -# algorithm. -slow_factors = (n) -> - (i for i in [1..n] when n % i == 0) - -# The rest of this code does two optimizations: -# 1) When you find a prime factor, divide it out of n (smallest_prime_factor). -# 2) Find the prime factorization first, then compute composite factors from those. - -smallest_prime_factor = (n) -> - for i in [2..n] - return n if i*i > n - return i if n % i == 0 - -prime_factors = (n) -> - return {} if n == 1 - spf = smallest_prime_factor n - result = prime_factors(n / spf) - result[spf] or= 0 - result[spf] += 1 - result - -fast_factors = (n) -> - prime_hash = prime_factors n - exponents = [] - for p of prime_hash - exponents.push - p: p - exp: 0 - result = [] - while true - factor = 1 - for obj in exponents - factor *= Math.pow obj.p, obj.exp - result.push factor - break if factor == n - # roll the odometer - for obj, i in exponents - if obj.exp < prime_hash[obj.p] - obj.exp += 1 - break - else - obj.exp = 0 - - return result.sort (a, b) -> a - b - -verify_factors = (factors, n) -> - expected_result = slow_factors n - throw Error("wrong length") if factors.length != expected_result.length - for factor, i in expected_result - console.log Error("wrong value") if factors[i] != factor - - -for n in [1, 3, 4, 8, 24, 37, 1001, 11111111111, 99999999999] - factors = fast_factors n - console.log n, factors - if n < 1000000 - verify_factors factors, n diff --git a/Task/Factors-of-an-integer/CoffeeScript/factors-of-an-integer-2.coffee b/Task/Factors-of-an-integer/CoffeeScript/factors-of-an-integer-2.coffee deleted file mode 100644 index 532bee5b8f..0000000000 --- a/Task/Factors-of-an-integer/CoffeeScript/factors-of-an-integer-2.coffee +++ /dev/null @@ -1,21 +0,0 @@ -> coffee factors.coffee -1 [ 1 ] -3 [ 1, 3 ] -4 [ 1, 2, 4 ] -8 [ 1, 2, 4, 8 ] -24 [ 1, 2, 3, 4, 6, 8, 12, 24 ] -37 [ 1, 37 ] -1001 [ 1, 7, 11, 13, 77, 91, 143, 1001 ] -11111111111 [ 1, 21649, 513239, 11111111111 ] -99999999999 [ 1, - 3, - 9, - 21649, - 64947, - 194841, - 513239, - 1539717, - 4619151, - 11111111111, - 33333333333, - 99999999999 ] diff --git a/Task/Factors-of-an-integer/Gosu/factors-of-an-integer.gosu b/Task/Factors-of-an-integer/Gosu/factors-of-an-integer.gosu new file mode 100644 index 0000000000..b81466d1d1 --- /dev/null +++ b/Task/Factors-of-an-integer/Gosu/factors-of-an-integer.gosu @@ -0,0 +1,9 @@ +var numbers = {11, 21, 32, 45, 67, 96} +numbers.each(\ number -> printFactors(number)) + +function printFactors(n: int) { + if (n < 1) return + var result ="${n} => " + (1 .. n/2).each(\ i -> {result += n % i == 0 ? "${i} " : ""}) + print("${result}${n}") +} diff --git a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-4.hs b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-4.hs index 9c7d2f29a7..dc5b624859 100644 --- a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-4.hs +++ b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-4.hs @@ -1 +1,19 @@ -factors_naive n = [i | i <-[1..n], mod n i == 0] +import Control.Arrow ((&&&)) + +integerFactors :: Int -> [Int] +integerFactors n + | n < 1 = [] + | otherwise = + lows ++ + (quot n <$> + (if intSquared == n -- A perfect square, + then tail -- and cofactor of square root would be redundant. + else id) + (reverse lows)) + where + (intSquared, lows) = + (^ 2) &&& (filter ((0 ==) . rem n) . enumFromTo 1) $ + floor (sqrt $ fromIntegral n) + +main :: IO () +main = print $ integerFactors 600 diff --git a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-5.hs b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-5.hs index 0d8bf0cf0e..9c7d2f29a7 100644 --- a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-5.hs +++ b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-5.hs @@ -1,2 +1 @@ -~> factors_naive 25 -[1,5,25] +factors_naive n = [i | i <-[1..n], mod n i == 0] diff --git a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-6.hs b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-6.hs index f5db03ec62..0d8bf0cf0e 100644 --- a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-6.hs +++ b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-6.hs @@ -1,7 +1,2 @@ -import Data.List -tuple_to_list xs = fst xs ++ snd xs -factors_co n = sort (tuple_to_list (unzip - [ (i, (div n i)) | i <- [1..floor (sqrt (fromIntegral n))-1] - , mod n i == 0]) ++ - [ i | i <- [floor (sqrt (fromIntegral n))] - , mod n i == 0]) +~> factors_naive 25 +[1,5,25] diff --git a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-7.hs b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-7.hs index 4e11691fa2..1b49b78ab2 100644 --- a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-7.hs +++ b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-7.hs @@ -1,5 +1,3 @@ import Data.List -factors_o n = ds ++ [r | mod n r == 0] ++ reverse (map (n `div`) ds) - where - r = floor (sqrt (fromIntegral n)) - ds = [i | i <- [1..r-1], mod n i == 0] +factors_co n = sort [ i | i <- [1..floor (sqrt (fromIntegral n))] + , (d,0) <- [divMod n i], i <- [i]++[d|d>i] ] diff --git a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-8.hs b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-8.hs index 958619c426..48e156f9e4 100644 --- a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-8.hs +++ b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-8.hs @@ -1,9 +1,5 @@ -*Main> :set +s -~> factors_o 120 -[1,2,3,4,5,6,8,10,12,15,20,24,30,40,60,120] -(0.01 secs, 7578656 bytes) - -~> factors_o 12041111117 -[1,7,41,287,541,3787,22181,77551,155267,542857,3179591,22257137,41955091,2936856 -37,1720158731,12041111117] -(0.31 secs, 51583744 bytes) +import Data.List +factors_o n = ds ++ [r | (d,0) <- [divMod n r], r <- r:[d | d>r]] ++ reverse (map (n `div`) ds) + where + r = floor (sqrt (fromIntegral n)) + ds = [i | i <- [1..r-1], mod n i == 0] diff --git a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-9.hs b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-9.hs new file mode 100644 index 0000000000..d14f1447a9 --- /dev/null +++ b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-9.hs @@ -0,0 +1,9 @@ +*Main> :set +s +~> factors_o 120 +[1,2,3,4,5,6,8,10,12,15,20,24,30,40,60,120] +(0.00 secs, 0 bytes) + +~> factors_o 12041111117 +[1,7,41,287,541,3787,22181,77551,155267,542857,3179591,22257137,41955091,2936856 +37,1720158731,12041111117] +(0.09 secs, 50758224 bytes) diff --git a/Task/Factors-of-an-integer/J/factors-of-an-integer-1.j b/Task/Factors-of-an-integer/J/factors-of-an-integer-1.j index 5cd20495c7..c2add4f7f2 100644 --- a/Task/Factors-of-an-integer/J/factors-of-an-integer-1.j +++ b/Task/Factors-of-an-integer/J/factors-of-an-integer-1.j @@ -1,2 +1 @@ -q: 40 - 2 2 2 5 +foi=: [: I. 0 = (|~ i.@>:) diff --git a/Task/Factors-of-an-integer/J/factors-of-an-integer-10.j b/Task/Factors-of-an-integer/J/factors-of-an-integer-10.j new file mode 100644 index 0000000000..a2920ad14a --- /dev/null +++ b/Task/Factors-of-an-integer/J/factors-of-an-integer-10.j @@ -0,0 +1,2 @@ + factors 568474220x +1 2 4 5 10 17 20 34 68 85 170 340 1671983 3343966 6687932 8359915 16719830 28423711 33439660 56847422 113694844 142118555 284237110 568474220 diff --git a/Task/Factors-of-an-integer/J/factors-of-an-integer-11.j b/Task/Factors-of-an-integer/J/factors-of-an-integer-11.j new file mode 100644 index 0000000000..cfa234ef6c --- /dev/null +++ b/Task/Factors-of-an-integer/J/factors-of-an-integer-11.j @@ -0,0 +1,7 @@ +factorsOfNumber=: monad define + Y=. y"_ + /:~ ~. ( , Y%]) ( #~ 0=]|Y) 1+i.>.%:y +) + + factorsOfNumber 40 +1 2 4 5 8 10 20 40 diff --git a/Task/Factors-of-an-integer/J/factors-of-an-integer-12.j b/Task/Factors-of-an-integer/J/factors-of-an-integer-12.j new file mode 100644 index 0000000000..14e066807c --- /dev/null +++ b/Task/Factors-of-an-integer/J/factors-of-an-integer-12.j @@ -0,0 +1,2 @@ +odometer =: #: i.@(*/) +factors=: (*/@:^"1 odometer@:>:)/@q:~&__ diff --git a/Task/Factors-of-an-integer/J/factors-of-an-integer-2.j b/Task/Factors-of-an-integer/J/factors-of-an-integer-2.j index e58d6446fc..748a2944e8 100644 --- a/Task/Factors-of-an-integer/J/factors-of-an-integer-2.j +++ b/Task/Factors-of-an-integer/J/factors-of-an-integer-2.j @@ -1,3 +1,2 @@ - __ q: 420 -2 3 5 7 -2 1 1 1 + foi 40 +1 2 4 5 8 10 20 40 diff --git a/Task/Factors-of-an-integer/J/factors-of-an-integer-3.j b/Task/Factors-of-an-integer/J/factors-of-an-integer-3.j index e0757e798c..5cd20495c7 100644 --- a/Task/Factors-of-an-integer/J/factors-of-an-integer-3.j +++ b/Task/Factors-of-an-integer/J/factors-of-an-integer-3.j @@ -1,4 +1,2 @@ - (^ i.@>:)&.>/ __ q: 420 -┌─────┬───┬───┬───┐ -│1 2 4│1 3│1 5│1 7│ -└─────┴───┴───┴───┘ +q: 40 + 2 2 2 5 diff --git a/Task/Factors-of-an-integer/J/factors-of-an-integer-4.j b/Task/Factors-of-an-integer/J/factors-of-an-integer-4.j index 6d29de6a01..e58d6446fc 100644 --- a/Task/Factors-of-an-integer/J/factors-of-an-integer-4.j +++ b/Task/Factors-of-an-integer/J/factors-of-an-integer-4.j @@ -1,6 +1,3 @@ -factrs=: */&>@{@((^ i.@>:)&.>/)@q:~&__ - factrs 40 - 1 5 - 2 10 - 4 20 - 8 40 + __ q: 420 +2 3 5 7 +2 1 1 1 diff --git a/Task/Factors-of-an-integer/J/factors-of-an-integer-5.j b/Task/Factors-of-an-integer/J/factors-of-an-integer-5.j index efd8eced61..e0757e798c 100644 --- a/Task/Factors-of-an-integer/J/factors-of-an-integer-5.j +++ b/Task/Factors-of-an-integer/J/factors-of-an-integer-5.j @@ -1,3 +1,4 @@ - factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__ - factors 420 -1 2 3 4 5 6 7 10 12 14 15 20 21 28 30 35 42 60 70 84 105 140 210 420 + (^ i.@>:)&.>/ __ q: 420 +┌─────┬───┬───┬───┐ +│1 2 4│1 3│1 5│1 7│ +└─────┴───┴───┴───┘ diff --git a/Task/Factors-of-an-integer/J/factors-of-an-integer-6.j b/Task/Factors-of-an-integer/J/factors-of-an-integer-6.j index 318ac2efa1..6d29de6a01 100644 --- a/Task/Factors-of-an-integer/J/factors-of-an-integer-6.j +++ b/Task/Factors-of-an-integer/J/factors-of-an-integer-6.j @@ -1,2 +1,6 @@ - ~.,*/&> { 1 ,&.> q: 40 -1 5 2 10 4 20 8 40 +factrs=: */&>@{@((^ i.@>:)&.>/)@q:~&__ + factrs 40 + 1 5 + 2 10 + 4 20 + 8 40 diff --git a/Task/Factors-of-an-integer/J/factors-of-an-integer-7.j b/Task/Factors-of-an-integer/J/factors-of-an-integer-7.j index cfa234ef6c..efd8eced61 100644 --- a/Task/Factors-of-an-integer/J/factors-of-an-integer-7.j +++ b/Task/Factors-of-an-integer/J/factors-of-an-integer-7.j @@ -1,7 +1,3 @@ -factorsOfNumber=: monad define - Y=. y"_ - /:~ ~. ( , Y%]) ( #~ 0=]|Y) 1+i.>.%:y -) - - factorsOfNumber 40 -1 2 4 5 8 10 20 40 + factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__ + factors 420 +1 2 3 4 5 6 7 10 12 14 15 20 21 28 30 35 42 60 70 84 105 140 210 420 diff --git a/Task/Factors-of-an-integer/J/factors-of-an-integer-8.j b/Task/Factors-of-an-integer/J/factors-of-an-integer-8.j index 14e066807c..318ac2efa1 100644 --- a/Task/Factors-of-an-integer/J/factors-of-an-integer-8.j +++ b/Task/Factors-of-an-integer/J/factors-of-an-integer-8.j @@ -1,2 +1,2 @@ -odometer =: #: i.@(*/) -factors=: (*/@:^"1 odometer@:>:)/@q:~&__ + ~.,*/&> { 1 ,&.> q: 40 +1 5 2 10 4 20 8 40 diff --git a/Task/Factors-of-an-integer/J/factors-of-an-integer-9.j b/Task/Factors-of-an-integer/J/factors-of-an-integer-9.j new file mode 100644 index 0000000000..970ecbfe9d --- /dev/null +++ b/Task/Factors-of-an-integer/J/factors-of-an-integer-9.j @@ -0,0 +1,2 @@ + factors 568474220 +1 2 4 5 10 17 20 34 68 85 170 340 1.67198e6 3.34397e6 6.68793e6 8.35992e6 1.67198e7 2.84237e7 3.34397e7 5.68474e7 1.13695e8 1.42119e8 2.84237e8 5.68474e8 diff --git a/Task/Factors-of-an-integer/jq/factors-of-an-integer.jq b/Task/Factors-of-an-integer/Jq/factors-of-an-integer.jq similarity index 100% rename from Task/Factors-of-an-integer/jq/factors-of-an-integer.jq rename to Task/Factors-of-an-integer/Jq/factors-of-an-integer.jq diff --git a/Task/Factors-of-an-integer/Kotlin/factors-of-an-integer.kotlin b/Task/Factors-of-an-integer/Kotlin/factors-of-an-integer.kotlin new file mode 100644 index 0000000000..3142c6204c --- /dev/null +++ b/Task/Factors-of-an-integer/Kotlin/factors-of-an-integer.kotlin @@ -0,0 +1,13 @@ +fun printFactors(n: Int) { + if (n < 1) return + print("$n => ") + (1..n / 2) + .filter { n % it == 0 } + .forEach { print("$it ") } + println(n) +} + +fun main(args: Array) { + val numbers = intArrayOf(11, 21, 32, 45, 67, 96) + for (number in numbers) printFactors(number) +} diff --git a/Task/Factors-of-an-integer/PILOT/factors-of-an-integer.pilot b/Task/Factors-of-an-integer/PILOT/factors-of-an-integer.pilot new file mode 100644 index 0000000000..5c30c7e563 --- /dev/null +++ b/Task/Factors-of-an-integer/PILOT/factors-of-an-integer.pilot @@ -0,0 +1,12 @@ +T :Enter a number. +A :#n +C :factor = 1 +T :The factors of #n are: +*Loop +C :remainder = n % factor +T ( remainder = 0 ) :#factor +J ( factor = n ) :*Finished +C :factor = factor + 1 +J :*Loop +*Finished +END: diff --git a/Task/Factors-of-an-integer/Scala/factors-of-an-integer.scala b/Task/Factors-of-an-integer/Scala/factors-of-an-integer.scala index 138a1f9fe2..06a3cfceb0 100644 --- a/Task/Factors-of-an-integer/Scala/factors-of-an-integer.scala +++ b/Task/Factors-of-an-integer/Scala/factors-of-an-integer.scala @@ -4,9 +4,10 @@ Brute force approach: (1 to num).filter { divisor => num % divisor == 0 } - + } Since factors can't be higher than sqrt(num), the code above can be edited as follows def factors(num: Int) = { (1 to sqrt(num)).filter { divisor => num % divisor == 0 } + } diff --git a/Task/Factors-of-an-integer/Sidef/factors-of-an-integer.sidef b/Task/Factors-of-an-integer/Sidef/factors-of-an-integer.sidef index 1f20b7e860..e2724b4cbc 100644 --- a/Task/Factors-of-an-integer/Sidef/factors-of-an-integer.sidef +++ b/Task/Factors-of-an-integer/Sidef/factors-of-an-integer.sidef @@ -1,11 +1,11 @@ func factors(n) { - var divs = [] - range(1, n.sqrt.int).each { |d| - divs << d if n%%d - } - divs + [divs[-1]**2 == n ? divs.pop : ()] + divs.reverse.map{|d| n/d } + gather { + { |d| + take(d, n//d) if d.divides(n) + } << 1..n.isqrt + }.sort.uniq } - -[53, 64, 32766].each { |n| +  +for n [53, 64, 32766] { say "factors(#{n}): #{factors(n)}" } diff --git a/Task/Factors-of-an-integer/Zkl/factors-of-an-integer.zkl b/Task/Factors-of-an-integer/Zkl/factors-of-an-integer.zkl new file mode 100644 index 0000000000..89d001d7da --- /dev/null +++ b/Task/Factors-of-an-integer/Zkl/factors-of-an-integer.zkl @@ -0,0 +1,3 @@ +fcn f(n){ (1).pump(n.toFloat().sqrt(), List, + 'wrap(m){((n % m)==0) and T(m,n/m) or Void.Skip}) } +fcn g(n){ [[(m); [1..n.toFloat().sqrt()],'{n%m==0}; '{T(m,n/m)} ]] } // list comprehension diff --git a/Task/Fast-Fourier-transform/C++/fast-fourier-transform.cpp b/Task/Fast-Fourier-transform/C++/fast-fourier-transform.cpp index ecdb002975..7f88f3d507 100644 --- a/Task/Fast-Fourier-transform/C++/fast-fourier-transform.cpp +++ b/Task/Fast-Fourier-transform/C++/fast-fourier-transform.cpp @@ -33,12 +33,14 @@ void fft(CArray& x) // Cooley-Tukey FFT (in-place, breadth-first, decimation-in-frequency) // Better optimized but less intuitive +// !!! Warning : in some cases this code make result different from not optimased version above (need to fix bug) +// The bug is now fixed @2017/05/30 void fft(CArray &x) { // DFT unsigned int N = x.size(), k = N, n; double thetaT = 3.14159265358979323846264338328L / N; - Complex phiT = Complex(cos(thetaT), sin(thetaT)), T; + Complex phiT = Complex(cos(thetaT), -sin(thetaT)), T; while (k > 1) { n = k; diff --git a/Task/Fast-Fourier-transform/jq/fast-fourier-transform-1.jq b/Task/Fast-Fourier-transform/Jq/fast-fourier-transform-1.jq similarity index 100% rename from Task/Fast-Fourier-transform/jq/fast-fourier-transform-1.jq rename to Task/Fast-Fourier-transform/Jq/fast-fourier-transform-1.jq diff --git a/Task/Fast-Fourier-transform/jq/fast-fourier-transform-2.jq b/Task/Fast-Fourier-transform/Jq/fast-fourier-transform-2.jq similarity index 100% rename from Task/Fast-Fourier-transform/jq/fast-fourier-transform-2.jq rename to Task/Fast-Fourier-transform/Jq/fast-fourier-transform-2.jq diff --git a/Task/Fast-Fourier-transform/jq/fast-fourier-transform-3.jq b/Task/Fast-Fourier-transform/Jq/fast-fourier-transform-3.jq similarity index 100% rename from Task/Fast-Fourier-transform/jq/fast-fourier-transform-3.jq rename to Task/Fast-Fourier-transform/Jq/fast-fourier-transform-3.jq diff --git a/Task/Fast-Fourier-transform/Kotlin/fast-fourier-transform-1.kotlin b/Task/Fast-Fourier-transform/Kotlin/fast-fourier-transform-1.kotlin index 04d610f0ab..2b19133c19 100644 --- a/Task/Fast-Fourier-transform/Kotlin/fast-fourier-transform-1.kotlin +++ b/Task/Fast-Fourier-transform/Kotlin/fast-fourier-transform-1.kotlin @@ -1,5 +1,3 @@ -package fft - import java.lang.Math.* class Complex(val re: Double, val im: Double) { @@ -17,6 +15,6 @@ class Complex(val re: Double, val im: Double) { else -> a + " - " + b + 'i' } - private final val a = "%1.3f".format(re) - private final val b = "%1.3f".format(abs(im)) + private val a = "%1.3f".format(re) + private val b = "%1.3f".format(abs(im)) } diff --git a/Task/Fast-Fourier-transform/Kotlin/fast-fourier-transform-2.kotlin b/Task/Fast-Fourier-transform/Kotlin/fast-fourier-transform-2.kotlin index 15768a2e89..0d44b75863 100644 --- a/Task/Fast-Fourier-transform/Kotlin/fast-fourier-transform-2.kotlin +++ b/Task/Fast-Fourier-transform/Kotlin/fast-fourier-transform-2.kotlin @@ -1,5 +1,3 @@ -package fft - object FFT { fun fft(a: Array) = _fft(a, Complex(0.0, 2.0), 1.0) fun rfft(a: Array) = _fft(a, Complex(0.0, -2.0), 2.0) diff --git a/Task/Fast-Fourier-transform/Kotlin/fast-fourier-transform-3.kotlin b/Task/Fast-Fourier-transform/Kotlin/fast-fourier-transform-3.kotlin index d4e2497269..30247a6346 100644 --- a/Task/Fast-Fourier-transform/Kotlin/fast-fourier-transform-3.kotlin +++ b/Task/Fast-Fourier-transform/Kotlin/fast-fourier-transform-3.kotlin @@ -1,5 +1,3 @@ -package fft - fun Array<*>.println() = println(joinToString(prefix = "[", postfix = "]")) fun main(args: Array) { diff --git a/Task/Fast-Fourier-transform/OoRexx/fast-fourier-transform.rexx b/Task/Fast-Fourier-transform/OoRexx/fast-fourier-transform.rexx new file mode 100644 index 0000000000..67e4317dad --- /dev/null +++ b/Task/Fast-Fourier-transform/OoRexx/fast-fourier-transform.rexx @@ -0,0 +1,118 @@ +Numeric Digits 16 +list='1 1 1 1 0 0 0 0' +n=words(list) +x=.array~new(n) +Do i=1 To n + x[i]=.complex~new(word(list,i),0) + End +Call show 'FFT in',x +call fft x +Call show 'FFT out',x +Exit + +show: Procedure + Use Arg data,x + Say '---data--- num real-part imaginary-part' + Say '---------- --- --------- --------------' + Do i=1 To x~size + say data right(i,7)' ' x[i]~string + End + Return + +fft: Procedure + Use Arg in + Numeric Digits 16 + n=in~size + If n=1 Then Return + odd=.array~new(n/2) + even=.array~new(n/2) + Do j=1 To n By 2; odd[(j+1)/2]=in[j]; End + Do j=2 To n By 2; even[j/2]=in[j]; End + Call fft odd + Call fft even + pi=3.14159265358979323E0 + n_2=n/2 + Do i=1 To n_2 + w=-2*pi*(i-1)/N + t=.complex~new(rxCalcCos(w,,'R'),rxCalcSin(w,,'R'))*even[i] + in[i]=odd[i]+t + in[i+n_2]=odd[i]-t + End + Return + +::class complex +::method init + expose r i + use strict arg r, i = 0 + +-- complex instances are immutable, so these are +-- read only attributes +::attribute r GET +::attribute i GET + +::method add + expose r i + Numeric Digits 16 + use strict arg other + if other~isa(.complex) then + return self~class~new(r + other~r, i + other~i) + else return self~class~new(r + other, i) + +::method subtract + expose r i + Numeric Digits 16 + use strict arg other + if other~isa(.complex) then + return self~class~new(r - other~r, i - other~i) + else return self~class~new(r - other, i) + +::method "+" + Numeric Digits 16 + -- 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 "-" + Numeric Digits 16 + -- need to check if this is a prefix minus or a subtract + if arg() == 0 then + forward message("NEGATIVE") + else + forward message("SUBTRACT") + +::method times + expose r i + Numeric Digits 16 + use strict arg other + if other~isa(.complex) then + return self~class~new(r * other~r - i * other~i, r * other~i + i * other~r) + else return self~class~new(r * other, i * other) + +::method "*" + Numeric Digits 16 + forward message("TIMES") + +::method string + expose r i + Numeric Digits 12 + Select + When i=0 Then + If r=0 Then + Return '0' + Else + Return format(r,1,9) + When i>0 Then + Return format(r,1,9)' +'format(i,1,9)'i' + Otherwise + Return format(r,1,9)' -'format(abs(i),1,9)'i' + End + +::method formatnumber private + use arg value + Numeric Digits 16 + if value > 0 then return "+" value + else return "-" value~abs + +::requires rxMath library diff --git a/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform-1.pl6 b/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform-1.pl6 new file mode 100644 index 0000000000..b4180d6925 --- /dev/null +++ b/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform-1.pl6 @@ -0,0 +1,9 @@ +sub fft { + return @_ if @_ == 1; + my @evn = fft( @_[0, 2 ... *] ); + my @odd = fft( @_[1, 3 ... *] ) Z* + map &cis, (0, -tau / @_ ... *); + return flat @evn »+« @odd, @evn »-« @odd; +} + +.say for fft <1 1 1 1 0 0 0 0>; diff --git a/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform-2.pl6 b/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform-2.pl6 new file mode 100644 index 0000000000..842e11e4d7 --- /dev/null +++ b/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform-2.pl6 @@ -0,0 +1,5 @@ +sub fft { + @_ == 1 ?? @_ !! + fft(@_[0,2...*]) «+« + fft(@_[1,3...*]) «*« map &cis, (0,-τ/@_...^-τ) +} diff --git a/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform-3.pl6 b/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform-3.pl6 new file mode 100644 index 0000000000..1b76d5faa2 --- /dev/null +++ b/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform-3.pl6 @@ -0,0 +1,6 @@ +sub fft { + use TrigPi; + @_ == 1 ?? @_ !! + fft(@_[0,2...*]) «+« + fft(@_[1,3...*]) «*« map &cisPi, (0,-2/@_...^-2) +} diff --git a/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform.pl6 b/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform.pl6 deleted file mode 100644 index 130b2db033..0000000000 --- a/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform.pl6 +++ /dev/null @@ -1,14 +0,0 @@ -sub fft { - return @_ if @_ == 1; - my @evn = fft( @_[0, 2 ... *] ); - my @odd = fft( @_[1, 3 ... *] ) Z* - map &cis, (0, tau / @_ ... *); - return flat @evn »+« @odd, @evn »-« @odd; -} - -my @seq = ^16; -my $cycles = 3; -my @wave = map { sin( tau * $_ / @seq * $cycles ) }, @seq; -say "wave: ", @wave.fmt("%7.3f"); - -say "fft: ", fft(@wave)».abs.fmt("%7.3f"); diff --git a/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl b/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl index 6e03ad7e35..f901d8dfc9 100644 --- a/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl +++ b/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl @@ -13,10 +13,4 @@ sub fft { (map { $evn[$_] - $odd[$_] } 0 .. $#evn ); } - -my @seq = 0 .. 15; -my $cycles = 3; -my @wave = map { sin( $_ * 2*pi/ @seq * $cycles ) } @seq; -print "wave: ", join " ", map { sprintf "%7.3f", $_ } @wave; -print "\n"; -print "fft: ", join " ", map { sprintf "%7.3f", abs $_ } fft(@wave); +print "$_\n" for fft qw(1 1 1 1 0 0 0 0); diff --git a/Task/Fast-Fourier-transform/Phix/fast-fourier-transform.phix b/Task/Fast-Fourier-transform/Phix/fast-fourier-transform.phix new file mode 100644 index 0000000000..1829b653bb --- /dev/null +++ b/Task/Fast-Fourier-transform/Phix/fast-fourier-transform.phix @@ -0,0 +1,129 @@ +-- +-- demo\rosetta\FastFourierTransform.exw +-- ===================================== +-- +-- Originally written by Robert Craig and posted to EuForum Dec 13, 2001 +-- + +constant REAL = 1, IMAG = 2 + +type complex(sequence x) + return length(x)=2 and atom(x[REAL]) and atom(x[IMAG]) +end type + +function p2round(integer x) +-- rounds x up to a power of two +integer p = 1 + while p0 then + integer p = -1 + while floor(x)=x do + x /= 2 + p += 1 + end while + if x=0.5 then + return p + end if + end if + return -1 +end function + +function bitrev(sequence a) +-- bitrev an array of complex numbers +integer j=1, n = length(a) + for i=1 to n-1 do + if i=size ; end /*number of args exactly a power of 2? */ - do j=size+1 to 2**p;data=data 0; end /*add zeroes to DATA 'til a power of 2.*/ -size=words(data); ph=p%2; call hdr /*╔═══════════════════════════╗*/ +size=words(data); pad=left('', 6) /*PAD: for indenting and padding SAYs.*/ + do p=0 until 2**p>=size ; end /*number of args exactly a power of 2? */ + do j=size+1 to 2**p; data=data 0; end /*add zeroes to DATA 'til a power of 2.*/ +size=words(data); ph=p%2 ; call hdr /*╔═══════════════════════════╗*/ /* [↓] TRANSLATE allows I & J*/ /*║ Numbers in data can be in ║*/ do j=0 for size /*║ seven formats: real ║*/ - _=translate( word(data,j+1), 'J', "I") /*║ real,imag ║*/ + _=translate( word(data, j+1), 'J', "I") /*║ real,imag ║*/ parse var _ #.1.j '' $ 1 "," #.2.j /*║ ,imag ║*/ if $=='J' then parse var #.1.j #2.j "J" #.1.j /*║ nnnJ ║*/ /*║ nnnj ║*/ @@ -18,52 +18,51 @@ size=words(data); ph=p%2; call hdr /*╔══════ say pad ' FFT in ' center(j+1, 7) pad fmt(#.1.j) fmt(#.2.j, "i") end /*j*/ say -tran=pi()*2 / 2**p; !.=0; hp=2**p %2; A=2**(p-ph); ptr=A; dbl=1 +tran=pi()*2 / 2**p; !.=0; hp=2**p %2; A=2**(p-ph); ptr=A; dbl=1 say - do p-ph; halfPtr=ptr%2 - do i=halfPtr by ptr to A-halfPtr; _=i-halfPtr; !.i=!._+dbl - end /*i*/ - dbl=dbl*2; ptr=halfPtr + do p-ph; halfPtr=ptr % 2 + do i=halfPtr by ptr to A-halfPtr; _=i - halfPtr; !.i=!._ + dbl + end /*i*/ + ptr=halfPtr; dbl=dbl+dbl end /*p-ph*/ - do j=0 to 2**p%4; cmp.j=cos(j*tran); _=hp - j; cmp._= -cmp.j - _=hp + j; cmp._= -cmp.j + do j=0 to 2**p%4; cmp.j=cos(j*tran); _=hp - j; cmp._= -cmp.j + _=hp + j; cmp._= -cmp.j end /*j*/ B=2**ph - do i=0 for A; q=i * B - do j=0 for B; h=q+j; _=!.j*B+!.i; if _<=h then iterate - parse value #.1._ #.1.h #.2._ #.2.h with #.1.h #.1._ #.2.h #.2._ + do i=0 for A; q=i * B + do j=0 for B; h=q+j; _=!.j*B+!.i; if _<=h then iterate + parse value #.1._ #.1.h #.2._ #.2.h with #.1.h #.1._ #.2.h #.2._ end /*j*/ /* [↑] swap two sets of values. */ end /*i*/ dbl=1 - do p ; w=hp % dbl - do k=0 for dbl ; Lb=w * k ; Lh=Lb + 2**p % 4 - do j=0 for w ; a=j * dbl * 2 + k ; b= a + dbl - r=#.1.a; i=#.2.a ; c1=cmp.Lb * #.1.b ; c4=cmp.Lb * #.2.b - c2=cmp.Lh * #.2.b ; c3=cmp.Lh * #.1.b - #.1.a=r + c1 - c2 ; #.2.a=i + c3 + c4 - #.1.b=r - c1 + c2 ; #.2.b=i - c3 - c4 + do p ; w= hp % dbl + do k=0 for dbl ; Lb= w * k ; Lh= Lb + 2**p % 4 + do j=0 for w ; a= j * dbl * 2 + k ; b= a + dbl + r=#.1.a; i=#.2.a ; c1= cmp.Lb * #.1.b ; c4= cmp.Lb * #.2.b + c2= cmp.Lh * #.2.b ; c3= cmp.Lh * #.1.b + #.1.a= r + c1 - c2 ; #.2.a= i + c3 + c4 + #.1.b= r - c1 + c2 ; #.2.b= i - c3 - c4 end /*j*/ end /*k*/ dbl=dbl+dbl end /*p*/ call hdr do i=0 for size - say pad " FFT out " center(i+1,7) pad fmt(#.1.i) fmt(#.2.i,'j') + say pad " FFT out " center(i+1,7) pad fmt(#.1.i) fmt(#.2.i,'j') end /*i*/ /*[↑] #s are shown with 10 decimal digs*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ cos: procedure; parse arg x; q=r2r(x)**2; z=1; _=1; p=1 /*bare bones COS. */ - do k=2 by 2; _=-_*q/(k*(k-1)); z=z+_; if z=p then leave; p=z; end; return z + do k=2 by 2; _=-_*q/(k*(k-1)); z=z+_; if z=p then return z; p=z; end /*k*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ -fmt: procedure; parse arg y,j; y=y/1 /*prettifies complex numbers for show. */ - if abs(y) < '1e-'digits()%4 then y=0; if y=0 & j\=='' then return '' - y=format(y, , 10); if pos(.,y)\==0 then y=strip(y, 'T', 0) - y=strip(y, , .); if y>=0 then y=' 'y; return left(y || j, 12) +fmt: procedure; parse arg y,j; y=y/1 /*prettifies complex numbers for output*/ + if abs(y) < '1e-'digits()%4 then y=0; if y=0 & j\=='' then return '' + y=format(y, , 10); if pos(.,y)\==0 then y=strip(y, 'T', 0) + y=strip(y, , .); if y>=0 then y=' 'y; return left(y || j, 12) /*──────────────────────────────────────────────────────────────────────────────────────*/ -hdr: _='───data─── num real─part imaginary─part'; say pad _ - say pad translate(_, " "copies('═',256), " "xrange()); return +hdr: _= '───data─── num real─part imaginary─part'; say pad _ + say pad translate(_, " "copies('═', 256), " "xrange()); return /*──────────────────────────────────────────────────────────────────────────────────────*/ pi: return 3.1415926535897932384626433832795028841971693993751058209749445923078164062862 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -r2r: return arg(1) // ( pi()*2 ) /*reduce the radians to a unit circle. */ +r2r: return arg(1) // ( pi()*2 ) /*reduce the radians to a unit circle. */ diff --git a/Task/Fast-Fourier-transform/Racket/fast-fourier-transform-1.rkt b/Task/Fast-Fourier-transform/Racket/fast-fourier-transform-1.rkt deleted file mode 100644 index 69c72874ad..0000000000 --- a/Task/Fast-Fourier-transform/Racket/fast-fourier-transform-1.rkt +++ /dev/null @@ -1,3 +0,0 @@ -#lang racket -(require math) -(array-fft (array #[1. 1. 1. 1. 0. 0. 0. 0.])) diff --git a/Task/Fast-Fourier-transform/Racket/fast-fourier-transform-2.rkt b/Task/Fast-Fourier-transform/Racket/fast-fourier-transform-2.rkt deleted file mode 100644 index 704ca72a2d..0000000000 --- a/Task/Fast-Fourier-transform/Racket/fast-fourier-transform-2.rkt +++ /dev/null @@ -1,9 +0,0 @@ -(fcarray - #[4.0+0.0i - 1.0-2.414213562373095i - 0.0+0.0i - 1.0-0.4142135623730949i - 0.0+0.0i - 0.9999999999999999+0.4142135623730949i - 0.0+0.0i - 0.9999999999999997+2.414213562373095i]) diff --git a/Task/Fast-Fourier-transform/Stata/fast-fourier-transform.stata b/Task/Fast-Fourier-transform/Stata/fast-fourier-transform.stata new file mode 100644 index 0000000000..46cbd87215 --- /dev/null +++ b/Task/Fast-Fourier-transform/Stata/fast-fourier-transform.stata @@ -0,0 +1,8 @@ +. mata +: a=1,2,3,4 +: fft(a) + 1 2 3 4 + +-----------------------------------------+ + 1 | 10 -2 - 2i -2 -2 + 2i | + +-----------------------------------------+ +: end diff --git a/Task/Fast-Fourier-transform/Zkl/fast-fourier-transform.zkl b/Task/Fast-Fourier-transform/Zkl/fast-fourier-transform.zkl new file mode 100644 index 0000000000..a1b2a926c7 --- /dev/null +++ b/Task/Fast-Fourier-transform/Zkl/fast-fourier-transform.zkl @@ -0,0 +1,3 @@ +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +v:=GSL.ZVector(8).set(1,1,1,1); +GSL.FFT(v).toList().concat("\n").println(); // in place diff --git a/Task/Fibonacci-n-step-number-sequences/00DESCRIPTION b/Task/Fibonacci-n-step-number-sequences/00DESCRIPTION index beec7e67fa..68f576f43a 100644 --- a/Task/Fibonacci-n-step-number-sequences/00DESCRIPTION +++ b/Task/Fibonacci-n-step-number-sequences/00DESCRIPTION @@ -33,6 +33,8 @@ For small values of n, [[wp:Number prefix#Greek_series|Greek numeri Allied sequences can be generated where the initial values are changed: : '''The [[wp:Lucas number|Lucas series]]''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values. + +
    ;Task: # Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. @@ -43,5 +45,9 @@ Allied sequences can be generated where the initial values are changed: *   [[Fibonacci sequence]] *   [http://mathworld.wolfram.com/Fibonaccin-StepNumber.html Wolfram Mathworld] *   [[Hofstadter Q sequence‎]] +*   [[Leonardo numbers]] + + +;Also see: *   [https://www.youtube.com/watch?v=PeUbRXnbmms Lucas Numbers - Numberphile] (Video)

    diff --git a/Task/Fibonacci-n-step-number-sequences/Batch-File/fibonacci-n-step-number-sequences.bat b/Task/Fibonacci-n-step-number-sequences/Batch-File/fibonacci-n-step-number-sequences.bat new file mode 100644 index 0000000000..6de387cd27 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Batch-File/fibonacci-n-step-number-sequences.bat @@ -0,0 +1,48 @@ +@echo off + +echo Fibonacci Sequence: +call:nfib 1 1 +echo. + +echo Tribonacci Sequence: +call:nfib 1 1 2 +echo. + +echo Tetranacci Sequence: +call:nfib 1 1 2 4 +echo. + +echo Lucas Numbers: +call:nfib 2 1 +echo. + +pause>nul +exit /b + +:nfib +setlocal enabledelayedexpansion + +for %%i in (%*) do ( + set /a count+=1 + set seq=!seq! %%i +) +set "seq=%seq% ^| " +set n=-%count% +set /a n+=1 +for %%i in (%*) do ( + set F!n!=%%i + set /a n+=1 +) + +for /l %%i in (1,1,10) do ( + set /a termstart=%%i-%count%% + set /a termend=%%i-1 + for /l %%j in (!termstart!,1,!termend!) do ( + set /a F%%i+=!F%%j! + ) + set seq=!seq! !F%%i! +) +echo %seq% + +endlocal +exit /b diff --git a/Task/Fibonacci-n-step-number-sequences/jq/fibonacci-n-step-number-sequences-1.jq b/Task/Fibonacci-n-step-number-sequences/Jq/fibonacci-n-step-number-sequences-1.jq similarity index 100% rename from Task/Fibonacci-n-step-number-sequences/jq/fibonacci-n-step-number-sequences-1.jq rename to Task/Fibonacci-n-step-number-sequences/Jq/fibonacci-n-step-number-sequences-1.jq diff --git a/Task/Fibonacci-n-step-number-sequences/jq/fibonacci-n-step-number-sequences-2.jq b/Task/Fibonacci-n-step-number-sequences/Jq/fibonacci-n-step-number-sequences-2.jq similarity index 100% rename from Task/Fibonacci-n-step-number-sequences/jq/fibonacci-n-step-number-sequences-2.jq rename to Task/Fibonacci-n-step-number-sequences/Jq/fibonacci-n-step-number-sequences-2.jq diff --git a/Task/Fibonacci-n-step-number-sequences/Kotlin/fibonacci-n-step-number-sequences.kotlin b/Task/Fibonacci-n-step-number-sequences/Kotlin/fibonacci-n-step-number-sequences.kotlin new file mode 100644 index 0000000000..ce9bbb011c --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Kotlin/fibonacci-n-step-number-sequences.kotlin @@ -0,0 +1,27 @@ +// version 1.1.2 + +fun fibN(initial: IntArray, numTerms: Int) : IntArray { + val n = initial.size + require(n >= 2 && numTerms >= 0) + val fibs = initial.copyOf(numTerms) + if (numTerms <= n) return fibs + for (i in n until numTerms) { + var sum = 0 + for (j in i - n until i) sum += fibs[j] + fibs[i] = sum + } + return fibs +} + +fun main(args: Array) { + val names = arrayOf("fibonacci", "tribonacci", "tetranacci", "pentanacci", "hexanacci", + "heptanacci", "octonacci", "nonanacci", "decanacci") + val initial = intArrayOf(1, 1, 2, 4, 8, 16, 32, 64, 128, 256) + println(" n name values") + var values = fibN(intArrayOf(2, 1), 15).joinToString(", ") + println("%2d %-10s %s".format(2, "lucas", values)) + for (i in 0..8) { + values = fibN(initial.sliceArray(0 until i + 2), 15).joinToString(", ") + println("%2d %-10s %s".format(i + 2, names[i], values)) + } +} diff --git a/Task/Fibonacci-n-step-number-sequences/Lua/fibonacci-n-step-number-sequences.lua b/Task/Fibonacci-n-step-number-sequences/Lua/fibonacci-n-step-number-sequences.lua index 4cdb622bc1..30001edd0d 100644 --- a/Task/Fibonacci-n-step-number-sequences/Lua/fibonacci-n-step-number-sequences.lua +++ b/Task/Fibonacci-n-step-number-sequences/Lua/fibonacci-n-step-number-sequences.lua @@ -1,37 +1,20 @@ -function n_Nacci (n, seqLength, lucas) - local seq, nextNum = {1} - if lucas then - seq = {2, 1} - else - for power = 1, n - 1 do - table.insert(seq, 2 ^ power) - end - end - while #seq < seqLength do - nextNum = 0 - for i = #seq - (n-1), #seq do - nextNum = nextNum + seq[i] - end - table.insert(seq, nextNum) +function nStepFibs (seq, limit) + local iMax, sum = #seq - 1 + while #seq < limit do + sum = 0 + for i = 0, iMax do sum = sum + seq[#seq - i] end + table.insert(seq, sum) end return seq end -function display (t) - print(" n\t|\t\t\tValues") - print(string.rep("-", 75)) - for k, v in pairs(t) do - io.write(" " .. k, "\t| ") - for _, val in pairs(v) do - io.write(val .. " ") - end - print("...") - end +local fibSeqs = { + {name = "Fibonacci", values = {1, 1} }, + {name = "Tribonacci", values = {1, 1, 2} }, + {name = "Tetranacci", values = {1, 1, 2, 4}}, + {name = "Lucas", values = {2, 1} } +} +for _, sequence in pairs(fibSeqs) do + io.write(sequence.name .. ": ") + print(table.concat(nStepFibs(sequence.values, 10), " ")) end - -local nacciTab = {} -for n = 2, 10 do - nacciTab[n] = n_Nacci(n, 16) -- 16 of each fits in one cmd line -end -nacciTab.lucas = n_Nacci(2, 16, "lucas") -display(nacciTab) diff --git a/Task/Fibonacci-n-step-number-sequences/Perl-6/fibonacci-n-step-number-sequences-1.pl6 b/Task/Fibonacci-n-step-number-sequences/Perl-6/fibonacci-n-step-number-sequences-1.pl6 index 8f21ed5012..95502e5189 100644 --- a/Task/Fibonacci-n-step-number-sequences/Perl-6/fibonacci-n-step-number-sequences-1.pl6 +++ b/Task/Fibonacci-n-step-number-sequences/Perl-6/fibonacci-n-step-number-sequences-1.pl6 @@ -1,11 +1,12 @@ +use MONKEY-SEE-NO-EVAL; + sub fibo ($n) { constant @starters = 1,1,2,4 ... *; nacci @starters[^$n]; } sub nacci (*@starter) { - my &fun = EVAL join '+', '*' xx @starter; - @starter, &fun ... *; + EVAL "|@starter, { join '+', '*' xx @starter } ... *"; } for 2..10 -> $n { say fibo($n)[^20] } diff --git a/Task/Fibonacci-n-step-number-sequences/Phix/fibonacci-n-step-number-sequences.phix b/Task/Fibonacci-n-step-number-sequences/Phix/fibonacci-n-step-number-sequences.phix new file mode 100644 index 0000000000..748944621a --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Phix/fibonacci-n-step-number-sequences.phix @@ -0,0 +1,18 @@ +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: %s\n",{names[i],sprint(f)}) +end for diff --git a/Task/Fibonacci-n-step-number-sequences/PowerShell/fibonacci-n-step-number-sequences-1.psh b/Task/Fibonacci-n-step-number-sequences/PowerShell/fibonacci-n-step-number-sequences-1.psh new file mode 100644 index 0000000000..a062d172a9 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/PowerShell/fibonacci-n-step-number-sequences-1.psh @@ -0,0 +1,17 @@ +#Create generator of extended fibonaci +Function Get-ExtendedFibonaciGenerator($InitialValues ){ + $Values = $InitialValues + { + #exhaust initial values first before calculating next values by summation + if ($InitialValues.Length -gt 0) { + $NextValue = $InitialValues[0] + $Script:InitialValues = $InitialValues | Select -Skip 1 + return $NextValue + } + + $NextValue = $Values | Measure-Object -Sum | Select -ExpandProperty Sum + $Script:Values = @($Values | Select-Object -Skip 1) + @($NextValue) + + $NextValue + }.GetNewClosure() +} diff --git a/Task/Fibonacci-n-step-number-sequences/PowerShell/fibonacci-n-step-number-sequences-2.psh b/Task/Fibonacci-n-step-number-sequences/PowerShell/fibonacci-n-step-number-sequences-2.psh new file mode 100644 index 0000000000..5b4c7f0141 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/PowerShell/fibonacci-n-step-number-sequences-2.psh @@ -0,0 +1,10 @@ +$Name = 'fibo tribo tetra penta hexa hepta octo nona deca'.Split() +0..($Name.Length-1) | foreach { $Index = $_ + $InitialValues = @(1) + @(foreach ($I In 0..$Index) { [Math]::Pow(2,$I) }) + $Generator = Get-ExtendedFibonaciGenerator $InitialValues + [PSCustomObject] @{ + n = $InitialValues.Length; + Name = "$($Name[$Index])naci"; + Sequence = 1..15 | foreach { & $Generator } | Join-String -Separator ',' + } +} | Format-Table -AutoSize diff --git a/Task/Fibonacci-n-step-number-sequences/Ruby/fibonacci-n-step-number-sequences-3.rb b/Task/Fibonacci-n-step-number-sequences/Ruby/fibonacci-n-step-number-sequences-3.rb deleted file mode 100644 index e7d96596a3..0000000000 --- a/Task/Fibonacci-n-step-number-sequences/Ruby/fibonacci-n-step-number-sequences-3.rb +++ /dev/null @@ -1,4 +0,0 @@ -fibonacci: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] -lucasnacci: [2, 1, 3, 4, 7, 11, 18, 29, 47, 76] -tribonacci: [1, 1, 2, 4, 7, 13, 24, 44, 81, 149] -tetranacci: [1, 1, 2, 4, 8, 15, 29, 56, 108, 208] diff --git a/Task/Fibonacci-n-step-number-sequences/Scheme/fibonacci-n-step-number-sequences.ss b/Task/Fibonacci-n-step-number-sequences/Scheme/fibonacci-n-step-number-sequences.ss new file mode 100644 index 0000000000..780b6dab29 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Scheme/fibonacci-n-step-number-sequences.ss @@ -0,0 +1,26 @@ +(import (scheme base) + (scheme write) + (srfi 1)) + +;; uses n-step sequence formula to +;; continue lst until of length num +(define (n-fib lst num) + (let ((n (length lst))) + (do ((result (reverse lst) + (cons (fold + 0 (take result n)) + result))) + ((= num (length result)) (reverse result))))) + +;; display examples +(do ((i 2 (+ 1 i))) + ((> i 4) ) + (display (string-append "n = " + (number->string i) + ": ")) + (display (n-fib (cons 1 (list-tabulate (- i 1) (lambda (n) (expt 2 n)))) + 15)) + (newline)) + +(display "Lucas: ") +(display (n-fib '(2 1) 15)) +(newline) diff --git a/Task/Fibonacci-n-step-number-sequences/Zkl/fibonacci-n-step-number-sequences-1.zkl b/Task/Fibonacci-n-step-number-sequences/Zkl/fibonacci-n-step-number-sequences-1.zkl new file mode 100644 index 0000000000..664ba95866 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Zkl/fibonacci-n-step-number-sequences-1.zkl @@ -0,0 +1 @@ +fcn fibN(ns){ fcn(ns){ ns.append(ns.sum()).pop(0) }.fp(vm.arglist.copy()); } diff --git a/Task/Fibonacci-n-step-number-sequences/Zkl/fibonacci-n-step-number-sequences-2.zkl b/Task/Fibonacci-n-step-number-sequences/Zkl/fibonacci-n-step-number-sequences-2.zkl new file mode 100644 index 0000000000..7a312c5909 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Zkl/fibonacci-n-step-number-sequences-2.zkl @@ -0,0 +1,7 @@ +N:=15; +lucas:=fibN(2,1); do(N){ lucas().print(","); } println(); // Lucas +ns:=L(1); foreach _ in ([ns.len()+1..10]){ // Fibonacci n-step for 2 .. 10 + ns.append(ns.sum()); // the inital values for the series + "%2d: ".fmt(ns.len()).print(); + (N).pump(List,fibN(ns.xplode())).println(); +} diff --git a/Task/Fibonacci-sequence/00DESCRIPTION b/Task/Fibonacci-sequence/00DESCRIPTION index fa5f010f92..f778fc540f 100644 --- a/Task/Fibonacci-sequence/00DESCRIPTION +++ b/Task/Fibonacci-sequence/00DESCRIPTION @@ -1,8 +1,8 @@ The '''Fibonacci sequence''' is a sequence   Fn   of natural numbers defined recursively: - F0 = 0 - F1 = 1 - Fn = Fn-1 + Fn-2, if n>1 + F0 = 0 + F1 = 1 + Fn = Fn-1 + Fn-2, if n>1 ;Task: @@ -17,8 +17,9 @@ The sequence is sometimes extended into negative numbers by using a straightforw support for negative     n     in the solution is optional. -;Related task: +;Related tasks: *   [[Fibonacci n-step number sequences‎]] +*   [[Leonardo numbers]] ;References: diff --git a/Task/Fibonacci-sequence/ABAP/fibonacci-sequence-1.abap b/Task/Fibonacci-sequence/ABAP/fibonacci-sequence-1.abap new file mode 100644 index 0000000000..530161bedd --- /dev/null +++ b/Task/Fibonacci-sequence/ABAP/fibonacci-sequence-1.abap @@ -0,0 +1,14 @@ +FORM fibonacci_iter USING index TYPE i + CHANGING number_fib TYPE i. + DATA: lv_old type i, + lv_cur type i. + Do index times. + If sy-index = 1 or sy-index = 2. + lv_cur = 1. + lv_old = 0. + endif. + number_fib = lv_cur + lv_old. + lv_old = lv_cur. + lv_cur = number_fib. + enddo. +ENDFORM. diff --git a/Task/Fibonacci-sequence/ABAP/fibonacci-sequence-2.abap b/Task/Fibonacci-sequence/ABAP/fibonacci-sequence-2.abap new file mode 100644 index 0000000000..cece2fa242 --- /dev/null +++ b/Task/Fibonacci-sequence/ABAP/fibonacci-sequence-2.abap @@ -0,0 +1,9 @@ +cl_demo_output=>display( REDUCE #( INIT fibnm = VALUE stringtab( ( |0| ) ( |1| ) ) + n TYPE string + x = `0` + y = `1` + FOR i = 1 WHILE i <= 100 + NEXT n = ( x + y ) + fibnm = VALUE #( BASE fibnm ( n ) ) + x = y + y = n ) ). diff --git a/Task/Fibonacci-sequence/ALGOL-M/fibonacci-sequence-1.algol-m b/Task/Fibonacci-sequence/ALGOL-M/fibonacci-sequence-1.algol-m new file mode 100644 index 0000000000..16b87ea6ad --- /dev/null +++ b/Task/Fibonacci-sequence/ALGOL-M/fibonacci-sequence-1.algol-m @@ -0,0 +1,13 @@ +INTEGER FUNCTION FIBONACCI( X ); INTEGER X; +BEGIN + INTEGER M, N, A, I; + M := 0; + N := 1; + FOR I := 2 STEP 1 UNTIL X DO + BEGIN + A := N; + N := M + N; + M := A; + END; + FIBONACCI := N; +END; diff --git a/Task/Fibonacci-sequence/ALGOL-M/fibonacci-sequence-2.algol-m b/Task/Fibonacci-sequence/ALGOL-M/fibonacci-sequence-2.algol-m new file mode 100644 index 0000000000..3cd0434cb3 --- /dev/null +++ b/Task/Fibonacci-sequence/ALGOL-M/fibonacci-sequence-2.algol-m @@ -0,0 +1,7 @@ +INTEGER FUNCTION FIBONACCI( X ); INTEGER X; +BEGIN + IF X < 3 THEN + FIBONACCI := 1 + ELSE + FIBONACCI := FIBONACCI( X - 2 ) + FIBONACCI( X - 1 ); +END; diff --git a/Task/Fibonacci-sequence/AppleScript/fibonacci-sequence-3.applescript b/Task/Fibonacci-sequence/AppleScript/fibonacci-sequence-3.applescript index 2a9087d2a4..53aea176fa 100644 --- a/Task/Fibonacci-sequence/AppleScript/fibonacci-sequence-3.applescript +++ b/Task/Fibonacci-sequence/AppleScript/fibonacci-sequence-3.applescript @@ -1,19 +1,18 @@ -- fib :: Int -> Int on fib(n) - -- (Int, Int) -> (Int, Int) + -- lastTwo : (Int, Int) -> (Int, Int) script lastTwo - on lambda([a, b]) + on |λ|([a, b]) [b, a + b] - end lambda + end |λ| end script - item 1 of foldl(lastTwo, {0, 1}, range(1, n)) + item 1 of foldl(lastTwo, {0, 1}, enumFromTo(1, n)) end fib - --- TEST +-- TEST ----------------------------------------------------------------------- on run fib(32) @@ -21,9 +20,21 @@ on run --> 2178309 end run +-- GENERIC FUNCTIONS ---------------------------------------------------------- - --- GENERIC FUNCTIONS +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if n < m then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) @@ -31,7 +42,7 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -44,21 +55,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn - --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then - set d to -1 - else - set d to 1 - end if - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range diff --git a/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-5.basic b/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-5.basic new file mode 100644 index 0000000000..361d390965 --- /dev/null +++ b/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-5.basic @@ -0,0 +1,8 @@ +10 INPUT "ENTER VALUE OF N"; N +20 N1 = 0 : N2 = 1 +30 FOR K=1 TO N +40 SUM = N1+N2 +50 N1 = N2 +60 N2 = SUM +70 NEXT K +80 PRINT N1 diff --git a/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-6.basic b/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-6.basic new file mode 100644 index 0000000000..ffba04a3d1 --- /dev/null +++ b/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-6.basic @@ -0,0 +1,10 @@ + 10 INPUT N + 20 A=0 + 30 B=1 + 40 FOR I=2 TO N + 50 C=B + 60 B=A+B + 70 A=C + 80 NEXT I + 90 PRINT B +100 END diff --git a/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-7.basic b/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-7.basic new file mode 100644 index 0000000000..8d4e29ded2 --- /dev/null +++ b/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-7.basic @@ -0,0 +1,2 @@ + 10 INPUT N + 20 PRINT INT (0.5+(((SQR 5+1)/2)**N)/SQR 5) diff --git a/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-8.basic b/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-8.basic new file mode 100644 index 0000000000..a62249b7ab --- /dev/null +++ b/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-8.basic @@ -0,0 +1,9 @@ + 10 INPUT N + 20 LET A=0 + 30 LET B=1 + 40 FOR I=2 TO N + 50 LET C=B + 60 LET B=A+B + 70 LET A=C + 80 NEXT I + 90 PRINT B diff --git a/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-9.basic b/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-9.basic new file mode 100644 index 0000000000..dd6f67209d --- /dev/null +++ b/Task/Fibonacci-sequence/BASIC/fibonacci-sequence-9.basic @@ -0,0 +1,13 @@ + 10 INPUT N + 20 LET A=0 + 30 LET B=1 + 40 GOSUB 70 + 50 PRINT B + 60 STOP + 70 IF N=1 THEN RETURN + 80 LET C=B + 90 LET B=A+B +100 LET A=C +110 LET N=N-1 +120 GOSUB 70 +130 RETURN diff --git a/Task/Fibonacci-sequence/Bc/fibonacci-sequence.bc b/Task/Fibonacci-sequence/Bc/fibonacci-sequence.bc new file mode 100644 index 0000000000..1e2ea76648 --- /dev/null +++ b/Task/Fibonacci-sequence/Bc/fibonacci-sequence.bc @@ -0,0 +1,15 @@ +#! /usr/bin/bc -q + +define fib(x) { + if (x <= 0) return 0; + if (x == 1) return 1; + + a = 0; + b = 1; + for (i = 1; i < x; i++) { + c = a+b; a = b; b = c; + } + return c; +} +fib(1000) +quit diff --git a/Task/Fibonacci-sequence/Beeswax/fibonacci-sequence-1.beeswax b/Task/Fibonacci-sequence/Beeswax/fibonacci-sequence-1.beeswax new file mode 100644 index 0000000000..0ad0551aad --- /dev/null +++ b/Task/Fibonacci-sequence/Beeswax/fibonacci-sequence-1.beeswax @@ -0,0 +1,4 @@ + #>'#{; +_`Enter n: `TN`Fib(`{`)=`X~P~K#{; + #>~P~L#MM@>+@'q@{; + b~@M< diff --git a/Task/Fibonacci-sequence/Beeswax/fibonacci-sequence-2.beeswax b/Task/Fibonacci-sequence/Beeswax/fibonacci-sequence-2.beeswax new file mode 100644 index 0000000000..fc6d23b81e --- /dev/null +++ b/Task/Fibonacci-sequence/Beeswax/fibonacci-sequence-2.beeswax @@ -0,0 +1,29 @@ +julia> beeswax("n-th Fibonacci number.bswx") +Enter n: i0 + +Fib(0)=0 +Program finished! + +julia> beeswax("n-th Fibonacci number.bswx") +Enter n: i10 + +Fib(10)=55 +Program finished! + +julia> beeswax("n-th Fibonacci number.bswx") +Enter n: i92 + +Fib(92)=7540113804746346429 +Program finished! + +julia> beeswax("n-th Fibonacci number.bswx") +Enter n: i93 + +Fib(93)=12200160415121876738 +Program finished! + +julia> beeswax("n-th Fibonacci number.bswx") +Enter n: i94 + +Fib(94)=1293530146158671551 +Program finished! diff --git a/Task/Fibonacci-sequence/Comefrom0x10/fibonacci-sequence.comefrom0x10 b/Task/Fibonacci-sequence/Comefrom0x10/fibonacci-sequence.comefrom0x10 new file mode 100644 index 0000000000..00e1bfcabc --- /dev/null +++ b/Task/Fibonacci-sequence/Comefrom0x10/fibonacci-sequence.comefrom0x10 @@ -0,0 +1,15 @@ +stop = 6 +a = 1 +i = 1 # start +a # print result + +fib + comefrom if i is 1 # start + b = 1 + comefrom fib # start of loop + i = i + 1 + next_b = a + b + a = b + b = next_b + + comefrom fib if i > stop diff --git a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp deleted file mode 100644 index ab03fa12dd..0000000000 --- a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp +++ /dev/null @@ -1,21 +0,0 @@ -(defconstant +2x2-identity+ '(1 0 0 1)) -(defconstant +fib-seed+ '(1 1 1 0)) - -(defun multiply-2x2 (matrix-1 matrix-2) - (let* ((a (first matrix-1)) (b (second matrix-1)) (c (third matrix-1)) (d (fourth matrix-1)) - (e (first matrix-2)) (f (second matrix-2)) (g (third matrix-2)) (h (fourth matrix-2)) - (ae (* a e)) (bg (* b g)) (af (* a f)) (bh (* b h)) - (ce (* c e)) (dg (* d g)) (cf (* c f)) (dh (* d h))) - (list (+ ae bg) (+ af bh) (+ ce dg) (+ cf dh)))) - -(defun square-2x2 (matrix) - (multiply-2x2 matrix matrix)) - -(defun 2x2-exponentiation (matrix n) - (cond ((zerop n) +2x2-identity+) - ((eql n 1) matrix) - ((evenp n) (square-2x2 (2x2-exponentiation matrix (/ n 2)))) - (t (multiply-2x2 (square-2x2 (2x2-exponentiation matrix (/ (1- n) 2))) matrix)))) - -(defun fib (n) - (car (2x2-exponentiation +fib-seed+ (1- n)))) diff --git a/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-1.erl b/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-1.erl index ecdeca770e..b32dd4f64e 100644 --- a/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-1.erl +++ b/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-1.erl @@ -1,5 +1,5 @@ -module(fib). --export([fib/1). +-export([fib/1]). fib(0) -> 1; fib(1) -> 1; diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-1.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-1.hs index b0ad32a369..398ede260e 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-1.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-1.hs @@ -1 +1,6 @@ -[floor(0.01+(1/p**n+p**n)/sqrt 5)|let p=(1+sqrt 5)/2, n<-[0..42]] +main :: IO () +main = + print + [ floor (0.01 + (1 / p ** n + p ** n) / sqrt 5) + | let p = (1 + sqrt 5) / 2 + , n <- [0 .. 42] ] diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-10.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-10.hs index 834fc5fc26..7d1f929f9b 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-10.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-10.hs @@ -1,15 +1,44 @@ -import Data.List +import Data.List (transpose) -xs <+> ys = zipWith (+) xs ys -xs <*> ys = sum $ zipWith (*) xs ys +fib + :: (Integral b, Num a) + => b -> a +fib 0 = 0 -- this line is necessary because "something ^ 0" returns "fromInteger 1", which unfortunately +-- in our case is not our multiplicative identity (the identity matrix) but just a 1x1 matrix of 1 +fib n = (last . head . unMat) (Mat [[1, 1], [1, 0]] ^ n) -newtype Mat a = Mat {unMat :: [[a]]} deriving Eq +-- Code adapted from Matrix exponentiation operator task --------------------- +(<+>) + :: Num c + => [c] -> [c] -> [c] +(<+>) = zipWith (+) -instance Show a => Show (Mat a) where +(<*>) + :: Num a + => [a] -> [a] -> a +(<*>) = (sum .) . zipWith (*) + +newtype Mat a = Mat + { unMat :: [[a]] + } deriving (Eq) + +instance Show a => + Show (Mat a) where show xm = "Mat " ++ show (unMat xm) -instance Num a => Num (Mat a) where +instance Num a => + Num (Mat a) where negate xm = Mat $ map (map negate) $ unMat xm - xm + ym = Mat $ zipWith (<+>) (unMat xm) (unMat ym) - xm * ym = Mat [[xs <*> ys | ys <- transpose $ unMat ym] | xs <- unMat xm] + xm + ym = Mat $ zipWith (<+>) (unMat xm) (unMat ym) + xm * ym = + Mat + [ [ xs Main.<*> ys -- to distinguish from standard applicative operator + | ys <- transpose $ unMat ym ] + | xs <- unMat xm ] fromInteger n = Mat [[fromInteger n]] + abs = undefined + signum = undefined + +-- TEST ---------------------------------------------------------------------- +main :: IO () +main = (print . take 10 . show . fib) (10 ^ 5) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-11.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-11.hs index 1f3ba1d2e4..593d8551aa 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-11.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-11.hs @@ -1,3 +1,35 @@ -fib 0 = 0 -- this line is necessary because "something ^ 0" returns "fromInteger 1", which unfortunately - -- in our case is not our multiplicative identity (the identity matrix) but just a 1x1 matrix of 1 -fib n = last $ head $ unMat $ (Mat [[1,1],[1,0]]) ^ n +import Control.Arrow ((&&&)) + +fibstep :: (Integer, Integer) -> (Integer, Integer) +fibstep (a, b) = (b, a + b) + +fibnums :: [Integer] +fibnums = map fst $ iterate fibstep (0, 1) + +fibN2 :: Integer -> (Integer, Integer) +fibN2 m + | m < 10 = iterate fibstep (0, 1) !! fromIntegral m +fibN2 m = fibN2_next (n, r) (fibN2 n) + where + (n, r) = quotRem m 3 + +fibN2_next (n, r) (f, g) + | r == 0 = (a, b) -- 3n ,3n+1 + | r == 1 = (b, c) -- 3n+1,3n+2 + | r == 2 = (c, d) -- 3n+2,3n+3 (*) + where + a = + 5 * f ^ 3 + + if even n + then 3 * f + else (-3 * f) -- 3n + b = g ^ 3 + 3 * g * f ^ 2 - f ^ 3 -- 3n+1 + c = g ^ 3 + 3 * g ^ 2 * f + f ^ 3 -- 3n+2 + d = + 5 * g ^ 3 + + if even n + then (-3 * g) + else 3 * g -- 3(n+1) (*) + +main :: IO () +main = print $ (length &&& take 20) . show . fst $ fibN2 (10 ^ 2) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-12.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-12.hs index 2589d7e629..c69d736bc9 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-12.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-12.hs @@ -1,20 +1,2 @@ -fibsteps (a,b) n - | n <= 0 = (a,b) - | otherwise = fibsteps (b, a+b) (n-1) - -fibnums :: [Integer] -fibnums = map fst $ iterate (`fibsteps` 1) (0,1) - -fibN2 :: Integer -> (Integer, Integer) -fibN2 m | m < 10 = fibsteps (0,1) m -fibN2 m = fibN2_next (n,r) (fibN2 n) - where (n,r) = quotRem m 3 - -fibN2_next (n,r) (f,g) | r==0 = (a,b) -- 3n ,3n+1 - | r==1 = (b,c) -- 3n+1,3n+2 - | r==2 = (c,d) -- 3n+2,3n+3 (*) - where - a = ( 5*f^3 + if even n then 3*f else (- 3*f) ) -- 3n - b = ( g^3 + 3 * g * f^2 - f^3 ) -- 3n+1 - c = ( g^3 + 3 * g^2 * f + f^3 ) -- 3n+2 - d = ( 5*g^3 + if even n then (- 3*g) else 3*g ) -- 3(n+1) (*) + *Main> (length &&& take 20) . show . fst $ fibN2 (10^6) +(208988,"19532821287077577316") diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-13.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-13.hs index 3a908740e5..7f0a39dbc2 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-13.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-13.hs @@ -1,2 +1 @@ - *Main> take 10 $ show $ fst $ fibN2 (10^6) - "1953282128" +f (n,(a,b)) = (2*n,(a*a+b*b,2*a*b+b*b)) -- iterate f (1,(0,1)) ; b is nth diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-14.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-14.hs new file mode 100644 index 0000000000..dd052ec7a3 --- /dev/null +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-14.hs @@ -0,0 +1 @@ +g (n,(a,b)) = (2*n,(2*a*b-a*a,a*a+b*b)) -- iterate g (1,(1,1)) ; a is nth diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-2.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-2.hs index a7a77004a4..44f96af76f 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-2.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-2.hs @@ -1 +1,6 @@ -fib x = if x < 1 then 0 else if x < 2 then 1 else fib(x - 1) + fib(x - 2) +fib x = + if x < 1 + then 0 + else if x < 2 + then 1 + else fib (x - 1) + fib (x - 2) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-3.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-3.hs index 4c75d11644..6f37d67d3e 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-3.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-3.hs @@ -1,5 +1,8 @@ -fib x = if x < 1 then 0 - else if x==1 then 1 - else fibs!!(x - 1) + fibs!!(x - 2) +fib x = + if x < 1 + then 0 + else if x == 1 + then 1 + else fibs !! (x - 1) + fibs !! (x - 2) where - fibs = map fib [0..] + fibs = map fib [0 ..] diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-4.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-4.hs index b3558a3788..3e0209338c 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-4.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-4.hs @@ -1,2 +1,5 @@ -fib :: Integer -> Integer -fib n = fst $ foldl (\(a, b) _ -> (b, a + b)) (0, 1) [1 .. n] +fib n = go n 0 1 + where + go n a b + | n == 0 = a + | otherwise = go (n - 1) b (a + b) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-5.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-5.hs index b8a0c82ac7..eb85845a7f 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-5.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-5.hs @@ -1,4 +1 @@ -fib n = go n 0 1 - where - go n a b | n==0 = a - | otherwise = go (n-1) b (a+b) +fib = 0 : 1 : zipWith (+) fib (tail fib) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-6.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-6.hs index eb85845a7f..170aaccf3f 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-6.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-6.hs @@ -1 +1 @@ -fib = 0 : 1 : zipWith (+) fib (tail fib) +fib = 0 : 1 : (zipWith (+) <*> tail) fib diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-7.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-7.hs index d5ff9995cc..bac976bc03 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-7.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-7.hs @@ -1 +1 @@ - fib = 0 : 1 : (zipWith (+) <*> tail) fib +fib = 0 : 1 : next fib where next (a: t@(b:_)) = (a+b) : next t diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-8.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-8.hs index bac976bc03..093c22af12 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-8.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-8.hs @@ -1 +1 @@ -fib = 0 : 1 : next fib where next (a: t@(b:_)) = (a+b) : next t +fib = 0 : scanl (+) 1 fib diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-9.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-9.hs index 093c22af12..754992047c 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-9.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-9.hs @@ -1 +1,9 @@ -fib = 0 : scanl (+) 1 fib +import Data.List (foldl') --' + +fib :: Integer -> Integer +fib n = + fst $ + foldl' --' + (\(a, b) _ -> (b, a + b)) + (0, 1) + [1 .. n] diff --git a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-1.js b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-1.js index 2546838ad4..2b5dcb13d2 100644 --- a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-1.js +++ b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-1.js @@ -1,5 +1,3 @@ function fib(n) { - return function(n,a,b) { - return n>0 ? arguments.callee(n-1,b,a+b) : a; - }(n,0,1); + return n<2?n:fib(n-1)+fib(n-2); } diff --git a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-10.js b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-10.js new file mode 100644 index 0000000000..20f1368b43 --- /dev/null +++ b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-10.js @@ -0,0 +1,22 @@ +(() => { + 'use strict'; + + // fib :: Int -> Int + let fib = n => range(1, n) + .reduce(([a, b]) => [b, a + b], [0, 1])[0]; + + + // GENERIC [m..n] + + // range :: Int -> Int -> [Int] + let range = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + + // TEST + return fib(32); + + // --> 2178309 +})(); diff --git a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-2.js b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-2.js index 74590caf0c..a1ff46a929 100644 --- a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-2.js +++ b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-2.js @@ -1,10 +1,3 @@ function fib(n) { - var a = 0, b = 1, t; - while (n-- > 0) { - t = a; - a = b; - b += t; - console.log(a); - } - return a; + if (n<2) { return n; } else { return fib(n-1)+fib(n-2); } } diff --git a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-3.js b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-3.js index 7b3b4d45fc..2546838ad4 100644 --- a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-3.js +++ b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-3.js @@ -1,7 +1,5 @@ -var fib = (function(cache){ - return cache = cache || {}, function(n){ - if (cache[n]) return cache[n]; - else return cache[n] = n == 0 ? 0 : n < 0 ? -fib(-n) - : n <= 2 ? 1 : fib(n-2) + fib(n-1); - }; -})(); +function fib(n) { + return function(n,a,b) { + return n>0 ? arguments.callee(n-1,b,a+b) : a; + }(n,0,1); +} diff --git a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-4.js b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-4.js index 97864141c2..74590caf0c 100644 --- a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-4.js +++ b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-4.js @@ -1,17 +1,10 @@ -(function () { - 'use strict'; - - function fib(n) { - return Array.apply(null, Array(n + 1)) - .map(function (_, i, lst) { - return lst[i] = ( - i ? i < 2 ? 1 : - lst[i - 2] + lst[i - 1] : - 0 - ); - })[n]; - } - - return fib(32); - -})(); +function fib(n) { + var a = 0, b = 1, t; + while (n-- > 0) { + t = a; + a = b; + b += t; + console.log(a); + } + return a; +} diff --git a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-5.js b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-5.js index 9c507fdc23..7b3b4d45fc 100644 --- a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-5.js +++ b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-5.js @@ -1,17 +1,7 @@ -function Y(dn) { - return (function(fn) { - return fn(fn); - }(function(fn) { - return dn(function() { - return fn(fn).apply(null, arguments); - }); - })); -} -var fib = Y(function(fn) { - return function(n) { - if (n === 0 || n === 1) { - return n; - } - return fn(n - 1) + fn(n - 2); +var fib = (function(cache){ + return cache = cache || {}, function(n){ + if (cache[n]) return cache[n]; + else return cache[n] = n == 0 ? 0 : n < 0 ? -fib(-n) + : n <= 2 ? 1 : fib(n-2) + fib(n-1); }; -}); +})(); diff --git a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-6.js b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-6.js index cbb9a58664..97864141c2 100644 --- a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-6.js +++ b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-6.js @@ -1,10 +1,17 @@ -function* fibonacciGenerator() { - var prev = 0; - var curr = 1; - while (true) { - yield curr; - curr = curr + prev; - prev = curr - prev; +(function () { + 'use strict'; + + function fib(n) { + return Array.apply(null, Array(n + 1)) + .map(function (_, i, lst) { + return lst[i] = ( + i ? i < 2 ? 1 : + lst[i - 2] + lst[i - 1] : + 0 + ); + })[n]; } -} -var fib = fibonacciGenerator(); + + return fib(32); + +})(); diff --git a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-7.js b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-7.js index 6e6003e9db..9c507fdc23 100644 --- a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-7.js +++ b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-7.js @@ -1,35 +1,17 @@ -(() => { - 'use strict'; - - // Nth member of fibonacci series - - // fib :: Int -> Int - function fib(n) { - return mapAccumL(([a, b]) => [ - [b, a + b], b - ], [0, 1], range(1, n))[0][0]; +function Y(dn) { + return (function(fn) { + return fn(fn); + }(function(fn) { + return dn(function() { + return fn(fn).apply(null, arguments); + }); + })); +} +var fib = Y(function(fn) { + return function(n) { + if (n === 0 || n === 1) { + return n; + } + return fn(n - 1) + fn(n - 2); }; - - // GENERIC FUNCTIONS - - // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) - let mapAccumL = (f, acc, xs) => { - return xs.reduce((a, x) => { - let pair = f(a[0], x); - - return [pair[0], a[1].concat(pair[1])]; - }, [acc, []]); - } - - // range :: Int -> Int -> Maybe Int -> [Int] - let range = (m, n) => - Array.from({ - length: Math.floor(n - m) + 1 - }, (_, i) => m + i); - - - // TEST - return fib(32); - - // --> 2178309 -})(); +}); diff --git a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-8.js b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-8.js index 20f1368b43..cbb9a58664 100644 --- a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-8.js +++ b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-8.js @@ -1,22 +1,10 @@ -(() => { - 'use strict'; - - // fib :: Int -> Int - let fib = n => range(1, n) - .reduce(([a, b]) => [b, a + b], [0, 1])[0]; - - - // GENERIC [m..n] - - // range :: Int -> Int -> [Int] - let range = (m, n) => - Array.from({ - length: Math.floor(n - m) + 1 - }, (_, i) => m + i); - - - // TEST - return fib(32); - - // --> 2178309 -})(); +function* fibonacciGenerator() { + var prev = 0; + var curr = 1; + while (true) { + yield curr; + curr = curr + prev; + prev = curr - prev; + } +} +var fib = fibonacciGenerator(); diff --git a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-9.js b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-9.js new file mode 100644 index 0000000000..6e6003e9db --- /dev/null +++ b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-9.js @@ -0,0 +1,35 @@ +(() => { + 'use strict'; + + // Nth member of fibonacci series + + // fib :: Int -> Int + function fib(n) { + return mapAccumL(([a, b]) => [ + [b, a + b], b + ], [0, 1], range(1, n))[0][0]; + }; + + // GENERIC FUNCTIONS + + // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) + let mapAccumL = (f, acc, xs) => { + return xs.reduce((a, x) => { + let pair = f(a[0], x); + + return [pair[0], a[1].concat(pair[1])]; + }, [acc, []]); + } + + // range :: Int -> Int -> Maybe Int -> [Int] + let range = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + + // TEST + return fib(32); + + // --> 2178309 +})(); diff --git a/Task/Fibonacci-sequence/jq/fibonacci-sequence-1.jq b/Task/Fibonacci-sequence/Jq/fibonacci-sequence-1.jq similarity index 100% rename from Task/Fibonacci-sequence/jq/fibonacci-sequence-1.jq rename to Task/Fibonacci-sequence/Jq/fibonacci-sequence-1.jq diff --git a/Task/Fibonacci-sequence/jq/fibonacci-sequence-2.jq b/Task/Fibonacci-sequence/Jq/fibonacci-sequence-2.jq similarity index 100% rename from Task/Fibonacci-sequence/jq/fibonacci-sequence-2.jq rename to Task/Fibonacci-sequence/Jq/fibonacci-sequence-2.jq diff --git a/Task/Fibonacci-sequence/jq/fibonacci-sequence-3.jq b/Task/Fibonacci-sequence/Jq/fibonacci-sequence-3.jq similarity index 100% rename from Task/Fibonacci-sequence/jq/fibonacci-sequence-3.jq rename to Task/Fibonacci-sequence/Jq/fibonacci-sequence-3.jq diff --git a/Task/Fibonacci-sequence/jq/fibonacci-sequence-4.jq b/Task/Fibonacci-sequence/Jq/fibonacci-sequence-4.jq similarity index 100% rename from Task/Fibonacci-sequence/jq/fibonacci-sequence-4.jq rename to Task/Fibonacci-sequence/Jq/fibonacci-sequence-4.jq diff --git a/Task/Fibonacci-sequence/jq/fibonacci-sequence-5.jq b/Task/Fibonacci-sequence/Jq/fibonacci-sequence-5.jq similarity index 100% rename from Task/Fibonacci-sequence/jq/fibonacci-sequence-5.jq rename to Task/Fibonacci-sequence/Jq/fibonacci-sequence-5.jq diff --git a/Task/Fibonacci-sequence/jq/fibonacci-sequence-6.jq b/Task/Fibonacci-sequence/Jq/fibonacci-sequence-6.jq similarity index 100% rename from Task/Fibonacci-sequence/jq/fibonacci-sequence-6.jq rename to Task/Fibonacci-sequence/Jq/fibonacci-sequence-6.jq diff --git a/Task/Fibonacci-sequence/Kotlin/fibonacci-sequence.kotlin b/Task/Fibonacci-sequence/Kotlin/fibonacci-sequence.kotlin index 91228c19ab..2bdf2fd3fa 100644 --- a/Task/Fibonacci-sequence/Kotlin/fibonacci-sequence.kotlin +++ b/Task/Fibonacci-sequence/Kotlin/fibonacci-sequence.kotlin @@ -1,12 +1,10 @@ -package fibonacci - enum class Fibonacci { ITERATIVE { - override fun invoke(n: Long) = if (n < 2 ) + override fun invoke(n: Long) = if (n < 2) { n - else { - var n1: Long = 0 - var n2: Long = 1 + } else { + var n1 = 0L + var n2 = 1L var i = n do { val sum = n1 + n2 diff --git a/Task/Fibonacci-sequence/LOLCODE/fibonacci-sequence.lol b/Task/Fibonacci-sequence/LOLCODE/fibonacci-sequence.lol new file mode 100644 index 0000000000..533f4fbbe2 --- /dev/null +++ b/Task/Fibonacci-sequence/LOLCODE/fibonacci-sequence.lol @@ -0,0 +1,16 @@ +HAI 1.2 +HOW DUZ I fibonacci YR N + EITHER OF BOTH SAEM N AN 1 AN BOTH SAEM N AN 0 + O RLY? + YA RLY, FOUND YR 1 + NO WAI + I HAS A N1 + I HAS A N2 + N1 R DIFF OF N AN 1 + N2 R DIFF OF N AN 2 + N1 R fibonacci N1 + N2 R fibonacci N2 + FOUND YR SUM OF N1 AN N2 + OIC +IF U SAY SO +KTHXBYE diff --git a/Task/Fibonacci-sequence/Nimrod/fibonacci-sequence-1.nimrod b/Task/Fibonacci-sequence/Nimrod/fibonacci-sequence-1.nimrod deleted file mode 100644 index cd7185d540..0000000000 --- a/Task/Fibonacci-sequence/Nimrod/fibonacci-sequence-1.nimrod +++ /dev/null @@ -1,5 +0,0 @@ -proc Fibonacci(n: int): int64 = - var fn = float64(n) - var p: float64 = (1.0 + sqrt(5.0)) / 2.0 - var q: float64 = 1.0 / p - return int64((pow(p, fn) + pow(q, fn)) / sqrt(5.0)) diff --git a/Task/Fibonacci-sequence/Nimrod/fibonacci-sequence-2.nimrod b/Task/Fibonacci-sequence/Nimrod/fibonacci-sequence-2.nimrod deleted file mode 100644 index 5ee44b1b2c..0000000000 --- a/Task/Fibonacci-sequence/Nimrod/fibonacci-sequence-2.nimrod +++ /dev/null @@ -1,10 +0,0 @@ -proc Fibonacci(n: int): int = - var - first = 0 - second = 1 - - for i in 0 .. 0 - | 1 -> 1 - | n -> if n > 0 then fib (n-1) + fib (n-2) - else fib (n+2) - fib (n+1) +let fib = + let rec fib_aux f0 f1 = function + | 0 -> f0 + | 1 -> f1 + | n -> fib_aux f1 (f1 +/ f0) (n - 1) + in + fib_aux (num_of_int 0) (num_of_int 1) + +(* support for negatives *) +let fib n = + if n < 0 && n mod 2 = 0 then minus_num (fib (abs n)) + else fib (abs n) +;; +(* It can be called from the command line with an argument *) +(* Result is send to standart output *) +let n = int_of_string Sys.argv.(1) in +print_endline (string_of_num (fib n)) diff --git a/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-3.ocaml b/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-3.ocaml index f622edb097..78872a7853 100644 --- a/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-3.ocaml +++ b/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-3.ocaml @@ -1,12 +1,16 @@ -let fib n = - let rec fib_aux n a b = - match n with - | 0 -> a - | _ -> fib_aux (n-1) b (a+b) - in - fib_aux n 0 1 +open Num + +let mul (a,b,c) (d,e,f) = let bxe = b*/e in + (a*/d +/ bxe, a*/e +/ b*/f, bxe +/ c*/f) + +let id = (Int 1, Int 0, Int 1) +let rec pow a n = + if n=0 then id else + let b = pow a (n/2) in + if (n mod 2) = 0 then mul b b else mul a (mul b b) -(* support for negatives *) let fib n = - if n < 0 && n mod 2 = 0 then -fib (abs n) - else fib (abs n) + let (_,y,_) = (pow (Int 1, Int 1, Int 0) n) in + string_of_num y +;; +Printf.printf "fib %d = %s\n" 300 (fib 300) diff --git a/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-4.ocaml b/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-4.ocaml deleted file mode 100644 index bb210b6820..0000000000 --- a/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-4.ocaml +++ /dev/null @@ -1,19 +0,0 @@ -open Num - -let fib = - let rec fib_aux f0 f1 = function - | 0 -> f0 - | 1 -> f1 - | n -> fib_aux f1 (f1 +/ f0) (n - 1) - in - fib_aux (num_of_int 0) (num_of_int 1) - -(* support for negatives *) -let fib n = - if n < 0 && n mod 2 = 0 then minus_num (fib (abs n)) - else fib (abs n) -;; -(* It can be called from the command line with an argument *) -(* Result is send to standart output *) -let n = int_of_string Sys.argv.(1) in -print_endline (string_of_num (fib n)) diff --git a/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-5.ocaml b/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-5.ocaml deleted file mode 100644 index 78872a7853..0000000000 --- a/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-5.ocaml +++ /dev/null @@ -1,16 +0,0 @@ -open Num - -let mul (a,b,c) (d,e,f) = let bxe = b*/e in - (a*/d +/ bxe, a*/e +/ b*/f, bxe +/ c*/f) - -let id = (Int 1, Int 0, Int 1) -let rec pow a n = - if n=0 then id else - let b = pow a (n/2) in - if (n mod 2) = 0 then mul b b else mul a (mul b b) - -let fib n = - let (_,y,_) = (pow (Int 1, Int 1, Int 0) n) in - string_of_num y -;; -Printf.printf "fib %d = %s\n" 300 (fib 300) diff --git a/Task/Fibonacci-sequence/Phix/fibonacci-sequence-1.phix b/Task/Fibonacci-sequence/Phix/fibonacci-sequence-1.phix index de0f62040d..4c8027e950 100644 --- a/Task/Fibonacci-sequence/Phix/fibonacci-sequence-1.phix +++ b/Task/Fibonacci-sequence/Phix/fibonacci-sequence-1.phix @@ -1,18 +1,16 @@ -sequence fcache = {1,1} - -function fibonamem(integer n) -- memoized, works for -ve numbers, inaccurate above 78 -integer absn = abs(n) +function fibonacci(integer n) -- iterative, works for -ve numbers +atom a=0, b=1 if n=0 then return 0 end if - if absn>length(fcache) then - fcache = append(fcache,fibonamem(absn-1)+fibonamem(absn-2)) - if absn!=length(fcache) then ?9/0 end if - end if + if abs(n)>=79 then ?9/0 end if -- inaccuracies creep in above 78 + for i=1 to abs(n)-1 do + {a,b} = {b,a+b} + end for if n<0 and remainder(n,2)=0 then return -fcache[absn] end if return fcache[absn] end function -for i=0 to 30 do - printf(1,"%d", fibonamem(i)) - if i!=30 then puts(1,", ") end if +for i=0 to 28 do + if i then puts(1,", ") end if + printf(1,"%d", fibonacci(i)) end for puts(1,"\n") diff --git a/Task/Fibonacci-sequence/Phix/fibonacci-sequence-2.phix b/Task/Fibonacci-sequence/Phix/fibonacci-sequence-2.phix index e0f3536ae8..27ea96d521 100644 --- a/Task/Fibonacci-sequence/Phix/fibonacci-sequence-2.phix +++ b/Task/Fibonacci-sequence/Phix/fibonacci-sequence-2.phix @@ -5,18 +5,17 @@ sequence fcacheba = {BA_ONE,BA_ONE} function fibonamemba(integer n) -- memoized, works for -ve numbers, yields bigatom integer absn = abs(n) if n=0 then return BA_ZERO end if - if absn>length(fcacheba) then - fcacheba = append(fcacheba,ba_add(fibonamemba(absn-1),fibonamemba(absn-2))) - if absn!=length(fcacheba) then ?9/0 end if - end if + while length(fcacheba)0: - yield a - a, b, n = b, a+b, n-1 +def fibFastRec(n): + def fib(prvprv, prv, c): + if c < 1: + return prvprv + else: + return fib(prv, prvprv + prv, c - 1) + return fib(0, 1, n) diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-7.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-7.py index c84cd923b1..231e92fdd0 100644 --- a/Task/Fibonacci-sequence/Python/fibonacci-sequence-7.py +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-7.py @@ -1,3 +1,5 @@ ->>> [i for i in fibGen(11)] - -[0,1,1,2,3,5,8,13,21,34,55] +def fibGen(n): + a, b = 0, 1 + while n>0: + yield a + a, b, n = b, a+b, n-1 diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-8.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-8.py index 4bb8438a9e..c84cd923b1 100644 --- a/Task/Fibonacci-sequence/Python/fibonacci-sequence-8.py +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-8.py @@ -1,30 +1,3 @@ -def prevPowTwo(n): - 'Gets the power of two that is less than or equal to the given input' - if ((n & -n) == n): - return n - else: - n -= 1 - n |= n >> 1 - n |= n >> 2 - n |= n >> 4 - n |= n >> 8 - n |= n >> 16 - n += 1 - return (n/2) +>>> [i for i in fibGen(11)] -def crazyFib(n): - 'Crazy fast fibonacci number calculation' - powTwo = prevPowTwo(n) - - q = r = i = 1 - s = 0 - - while(i < powTwo): - i *= 2 - q, r, s = q*q + r*r, r * (q + s), (r*r + s*s) - - while(i < n): - i += 1 - q, r, s = q+r, q, r - - return q +[0,1,1,2,3,5,8,13,21,34,55] diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-9.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-9.py index c3bd4903b0..4bb8438a9e 100644 --- a/Task/Fibonacci-sequence/Python/fibonacci-sequence-9.py +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-9.py @@ -1,7 +1,30 @@ -def fib(n, c={0:1, 1:1}): - if n not in c: - x = n // 2 - c[n] = fib(x-1) * fib(n-x-1) + fib(x) * fib(n - x) - return c[n] +def prevPowTwo(n): + 'Gets the power of two that is less than or equal to the given input' + if ((n & -n) == n): + return n + else: + n -= 1 + n |= n >> 1 + n |= n >> 2 + n |= n >> 4 + n |= n >> 8 + n |= n >> 16 + n += 1 + return (n/2) -fib(10000000) # calculating it takes a few seconds, printing it takes eons +def crazyFib(n): + 'Crazy fast fibonacci number calculation' + powTwo = prevPowTwo(n) + + q = r = i = 1 + s = 0 + + while(i < powTwo): + i *= 2 + q, r, s = q*q + r*r, r * (q + s), (r*r + s*s) + + while(i < n): + i += 1 + q, r, s = q+r, q, r + + return q diff --git a/Task/Fibonacci-sequence/R/fibonacci-sequence-1.r b/Task/Fibonacci-sequence/R/fibonacci-sequence-1.r new file mode 100644 index 0000000000..7bfee9c69c --- /dev/null +++ b/Task/Fibonacci-sequence/R/fibonacci-sequence-1.r @@ -0,0 +1,6 @@ +fib=function(n,x=c(0,1)) { + if (abs(n)>1) for (i in seq(abs(n)-1)) x=c(x[2],sum(x)) + if (n<0) return(x[2]*(-1)^(abs(n)-1)) else if (n) return(x[2]) else return(0) +} + +sapply(seq(-31,31),fib) diff --git a/Task/Fibonacci-sequence/R/fibonacci-sequence.r b/Task/Fibonacci-sequence/R/fibonacci-sequence-2.r similarity index 100% rename from Task/Fibonacci-sequence/R/fibonacci-sequence.r rename to Task/Fibonacci-sequence/R/fibonacci-sequence-2.r diff --git a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-5.rb b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-5.rb index 044e3a789b..5fe136a53e 100644 --- a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-5.rb +++ b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-5.rb @@ -1,11 +1,7 @@ -require 'generator' - -def fib_gen - Generator.new do |g| - f0, f1 = 0, 1 - loop do - g.yield f0 - f0, f1 = f1, f0 + f1 - end - end +fib = Enumerator.new do |y| + f0, f1 = 0, 1 + loop do + y << f0 + f0, f1 = f1, f0 + f1 + end end diff --git a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-3.rust b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-3.rust index 8f36c8c7a9..926c587f81 100644 --- a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-3.rust +++ b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-3.rust @@ -6,9 +6,9 @@ fn main() { } } -fn fibonacci_gen(terms: i32) -> impl Iterator { +fn fibonacci_gen(terms: i32) -> impl Iterator { let sqrt_5 = 5.0f64.sqrt(); - let p = (1.0 +sqrt_5) / 2.0; + let p = (1.0 + sqrt_5) / 2.0; let q = 1.0/p; - (1..terms).map(move |n| ((p.powi(n) + q.powi(n)) / sqrt_5 + 0.5).floor()) + (1..terms).map(move |n| ((p.powi(n) + q.powi(n)) / sqrt_5 + 0.5) as u64) } diff --git a/Task/Fibonacci-sequence/SPL/fibonacci-sequence-1.spl b/Task/Fibonacci-sequence/SPL/fibonacci-sequence-1.spl new file mode 100644 index 0000000000..69bbdc979b --- /dev/null +++ b/Task/Fibonacci-sequence/SPL/fibonacci-sequence-1.spl @@ -0,0 +1,4 @@ +fibo(n)= + s5 = #.sqrt(5) + <= (((1+s5)/2)^n-((1-s5)/2)^n)/s5 +. diff --git a/Task/Fibonacci-sequence/SPL/fibonacci-sequence-2.spl b/Task/Fibonacci-sequence/SPL/fibonacci-sequence-2.spl new file mode 100644 index 0000000000..f10ec6ee22 --- /dev/null +++ b/Task/Fibonacci-sequence/SPL/fibonacci-sequence-2.spl @@ -0,0 +1,11 @@ +fibo(n)= + ? n<2, <= n + f2 = 0 + f1 = 1 + > i, 2..n + f = f1+f2 + f2 = f1 + f1 = f + < + <= f +. diff --git a/Task/Fibonacci-sequence/SPL/fibonacci-sequence-3.spl b/Task/Fibonacci-sequence/SPL/fibonacci-sequence-3.spl new file mode 100644 index 0000000000..3b3cf734c1 --- /dev/null +++ b/Task/Fibonacci-sequence/SPL/fibonacci-sequence-3.spl @@ -0,0 +1,4 @@ +fibo(n)= + ? n<2, <= n + <= fibo(n-1)+fibo(n-2) +. diff --git a/Task/Fibonacci-sequence/SQL/fibonacci-sequence-3.sql b/Task/Fibonacci-sequence/SQL/fibonacci-sequence-3.sql index f99cad4c99..272e2e4ce8 100644 --- a/Task/Fibonacci-sequence/SQL/fibonacci-sequence-3.sql +++ b/Task/Fibonacci-sequence/SQL/fibonacci-sequence-3.sql @@ -1,27 +1,16 @@ -CREATE FUNCTION fib(n int) RETURNS numeric AS $$ - -- This recursive with generates endless list of Fibonacci numbers. - WITH RECURSIVE fibonacci(current, previous) AS ( - -- Initialize the current with 0, so the first value will be 0. - -- The previous value is set to 1, because its only goal is not - -- special casing the zero case, and providing 1 as the second - -- number in the sequence. - -- - -- The numbers end with dots to make them numeric type in - -- Postgres. Numeric type has almost arbitrary precision - -- (technically just 131,072 digits, but that's good enough for - -- most purposes, including calculating huge Fibonacci numbers) - SELECT 0., 1. - UNION ALL - -- To generate Fibonacci number, we need to add together two - -- previous Fibonacci numbers. Current number is saved in order - -- to be accessed in the next iteration of recursive function. - SELECT previous + current, current FROM fibonacci - ) - -- The user is only interested in current number, not previous. - SELECT current FROM fibonacci - -- We only need one number, so limit to 1 - LIMIT 1 - -- Offset the query by the requested argument to get the correct - -- position in the list. - OFFSET n -$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT IMMUTABLE; +SQL> with fib(e,f) as (select 1, 1 from dual union all select e+f,e from fib where e <= 55) select f from fib; + + F +---------- + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + +10 rows selected. diff --git a/Task/Fibonacci-sequence/SQL/fibonacci-sequence-4.sql b/Task/Fibonacci-sequence/SQL/fibonacci-sequence-4.sql new file mode 100644 index 0000000000..f99cad4c99 --- /dev/null +++ b/Task/Fibonacci-sequence/SQL/fibonacci-sequence-4.sql @@ -0,0 +1,27 @@ +CREATE FUNCTION fib(n int) RETURNS numeric AS $$ + -- This recursive with generates endless list of Fibonacci numbers. + WITH RECURSIVE fibonacci(current, previous) AS ( + -- Initialize the current with 0, so the first value will be 0. + -- The previous value is set to 1, because its only goal is not + -- special casing the zero case, and providing 1 as the second + -- number in the sequence. + -- + -- The numbers end with dots to make them numeric type in + -- Postgres. Numeric type has almost arbitrary precision + -- (technically just 131,072 digits, but that's good enough for + -- most purposes, including calculating huge Fibonacci numbers) + SELECT 0., 1. + UNION ALL + -- To generate Fibonacci number, we need to add together two + -- previous Fibonacci numbers. Current number is saved in order + -- to be accessed in the next iteration of recursive function. + SELECT previous + current, current FROM fibonacci + ) + -- The user is only interested in current number, not previous. + SELECT current FROM fibonacci + -- We only need one number, so limit to 1 + LIMIT 1 + -- Offset the query by the requested argument to get the correct + -- position in the list. + OFFSET n +$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT IMMUTABLE; diff --git a/Task/Fibonacci-sequence/Sed/fibonacci-sequence.sed b/Task/Fibonacci-sequence/Sed/fibonacci-sequence.sed new file mode 100644 index 0000000000..d2b340ad12 --- /dev/null +++ b/Task/Fibonacci-sequence/Sed/fibonacci-sequence.sed @@ -0,0 +1,40 @@ +#!/bin/sed -f + +# First we need to convert each number into the right number of ticks +# Start by marking digits +s/[0-9]/<&/g + +# We have to do the digits manually. +s/0//g; s/1/|/g; s/2/||/g; s/3/|||/g; s/4/||||/g; s/5/|||||/g +s/6/||||||/g; s/7/|||||||/g; s/8/||||||||/g; s/9/|||||||||/g + +# Multiply by ten for each digit from the front. +:tens +s/|= 2 ticks into two of n-1, with a mark between +s/|\(|\+\)/\1-\1/g +# Convert the previous mark and the first tick after it to a different mark +# giving us n-1+n-2 marks. +s/-|/+/g +# Jump back unless we're done. +t split +# Get rid of the pluses, we're done with them. +s/+//g + +# Convert back to digits +:back +s/||||||||||/ roundf(0); + define S = (1.25.sqrt + 0.5) + define T = (-S + 1) + (S**n - T**n) / (-T + S) -> round } diff --git a/Task/Fibonacci-sequence/Sidef/fibonacci-sequence-5.sidef b/Task/Fibonacci-sequence/Sidef/fibonacci-sequence-5.sidef new file mode 100644 index 0000000000..6013851093 --- /dev/null +++ b/Task/Fibonacci-sequence/Sidef/fibonacci-sequence-5.sidef @@ -0,0 +1 @@ +say fib(12) #=> 144 diff --git a/Task/Fibonacci-sequence/Smart-BASIC/fibonacci-sequence.smart b/Task/Fibonacci-sequence/Smart-BASIC/fibonacci-sequence.smart new file mode 100644 index 0000000000..4b83b0c95c --- /dev/null +++ b/Task/Fibonacci-sequence/Smart-BASIC/fibonacci-sequence.smart @@ -0,0 +1,31 @@ +FOR i = 0 TO 15 + PRINT fibR(i),fibI(i),fibN(i) +NEXT i + +/* Recursive Method */ +DEF fibR(n) + IF n <= 1 THEN + fibR = n + ELSE + fibR = fibR(n-1) + fibR(n-2) + ENDIF +END DEF + +/* Iterative Method */ +DEF fibI(n) + a = 0 + b = 1 + FOR i = 1 TO n + temp = a + b + a = b + b = temp + NEXT i + fibI = a +END DEF + +/* N-th Term Method */ +DEF fibN(n) + uphi = .5 + SQR(5)/2 + lphi = .5 - SQR(5)/2 + fibN = (uphi^n-lphi^n)/SQR(5) +END DEF diff --git a/Task/Fibonacci-sequence/Standard-ML/fibonacci-sequence.ml b/Task/Fibonacci-sequence/Standard-ML/fibonacci-sequence.ml deleted file mode 100644 index 3eb1a6a1f9..0000000000 --- a/Task/Fibonacci-sequence/Standard-ML/fibonacci-sequence.ml +++ /dev/null @@ -1,7 +0,0 @@ -fun fib n = - let - fun fib' (0,a,b) = a - | fib' (n,a,b) = fib' (n-1,a+b,a) - in - fib' (n,0,1) - end diff --git a/Task/Fibonacci-sequence/Stata/fibonacci-sequence.stata b/Task/Fibonacci-sequence/Stata/fibonacci-sequence.stata new file mode 100644 index 0000000000..b9d766270b --- /dev/null +++ b/Task/Fibonacci-sequence/Stata/fibonacci-sequence.stata @@ -0,0 +1,12 @@ +. mata +: function fib(n) { + return((((1+sqrt(5))/2):^n-((1-sqrt(5))/2):^n)/sqrt(5)) +} + +: fib(0..10) + 1 2 3 4 5 6 7 8 9 10 11 + +--------------------------------------------------------+ + 1 | 0 1 1 2 3 5 8 13 21 34 55 | + +--------------------------------------------------------+ + +: end diff --git a/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-3.ti-83 b/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-3.ti-83 deleted file mode 100644 index 37a91e910c..0000000000 --- a/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-3.ti-83 +++ /dev/null @@ -1,3 +0,0 @@ -:Prompt N -:.5(1+√(5))→P -:(P^N–(-1/P)^N)/√(5) diff --git a/Task/Fibonacci-sequence/Wart/fibonacci-sequence-3.wart b/Task/Fibonacci-sequence/Wart/fibonacci-sequence-3.wart index f9ce333bc2..123f614911 100644 --- a/Task/Fibonacci-sequence/Wart/fibonacci-sequence-3.wart +++ b/Task/Fibonacci-sequence/Wart/fibonacci-sequence-3.wart @@ -1,5 +1,5 @@ def (fib n saved) - # all args in wart are optional, and we expect callers to not provide saved + # all args in Wart are optional, and we expect callers to not provide `saved` default saved :to (table 0 0 1 1) # pre-populate base cases default saved.n :to (+ (fib n-1 saved) (fib n-2 saved)) diff --git a/Task/Fibonacci-sequence/X86-Assembly/fibonacci-sequence.x86 b/Task/Fibonacci-sequence/X86-Assembly/fibonacci-sequence.x86 new file mode 100644 index 0000000000..a9714a1f6e --- /dev/null +++ b/Task/Fibonacci-sequence/X86-Assembly/fibonacci-sequence.x86 @@ -0,0 +1,51 @@ +TITLE i hate visual studio 4 (Fibs.asm) +; __ __/--------\ +; >__ \ / | |\ +; \ \___/ @ \ / \__________________ +; \____ \ / \\\ +; \____ Coded with love by: ||| +; \ Alexander Alvonellos ||| +; | 9/29/2011 / || +; | | MM +; | |--------------| | +; |< | |< | +; | | | | +; |mmmmmm| |mmmmm| +;; Epic Win. + +INCLUDE Irvine32.inc + +.data + BEERCOUNT = 48; + Fibs dd 0, 1, BEERCOUNT DUP(0); + +.code +main PROC +; I am not responsible for this code. +; They made me write it, against my will. + ;Here be dragons + mov esi, offset Fibs; offset array; ;;were to start (start) + mov ecx, BEERCOUNT; ;;count of items (how many) + mov ebx, 4; ;;size (in number of bytes) + call DumpMem; + + mov ecx, BEERCOUNT; ;//http://www.wolframalpha.com/input/?i=F ib%5B47%5D+%3E+4294967295 + mov esi, offset Fibs + NextPlease:; + mov eax, [esi]; ;//Get me the data from location at ESI + add eax, [esi+4]; ;//add into the eax the data at esi + another double (next mem loc) + mov [esi+8], eax; ;//Move that data into the memory location after the second number + add esi, 4; ;//Update the pointer + loop NextPlease; ;//Thank you sir, may I have another? + + + ;Here be dragons + mov esi, offset Fibs; offset array; ;;were to start (start) + mov ecx, BEERCOUNT; ;;count of items (how many) + mov ebx, 4; ;;size (in number of bytes) + call DumpMem; + + exit ; exit to operating system +main ENDP + +END main diff --git a/Task/Fibonacci-sequence/XEec/fibonacci-sequence.xeec b/Task/Fibonacci-sequence/XEec/fibonacci-sequence.xeec new file mode 100644 index 0000000000..4ec3998a1f --- /dev/null +++ b/Task/Fibonacci-sequence/XEec/fibonacci-sequence.xeec @@ -0,0 +1,7 @@ +h#1 h#1 h#1 o# +h#10 o$ p +>f + o# h#10 o$ p + ma h? jnext p + t +jnf diff --git a/Task/Fibonacci-sequence/XLISP/fibonacci-sequence-3.xlisp b/Task/Fibonacci-sequence/XLISP/fibonacci-sequence-3.xlisp new file mode 100644 index 0000000000..a702dd3b1f --- /dev/null +++ b/Task/Fibonacci-sequence/XLISP/fibonacci-sequence-3.xlisp @@ -0,0 +1,8 @@ +(defun fibonacci (x) + (defun fib (a b n) + (if (= n 2) + b + (fib b (+ a b) (- n 1)) ) ) + (if (< x 2) + x + (fib 1 1 x) ) ) diff --git a/Task/Fibonacci-sequence/ZX-Spectrum-Basic/fibonacci-sequence.zx b/Task/Fibonacci-sequence/ZX-Spectrum-Basic/fibonacci-sequence-1.zx similarity index 100% rename from Task/Fibonacci-sequence/ZX-Spectrum-Basic/fibonacci-sequence.zx rename to Task/Fibonacci-sequence/ZX-Spectrum-Basic/fibonacci-sequence-1.zx diff --git a/Task/Fibonacci-sequence/ZX-Spectrum-Basic/fibonacci-sequence-2.zx b/Task/Fibonacci-sequence/ZX-Spectrum-Basic/fibonacci-sequence-2.zx new file mode 100644 index 0000000000..76c54c5b69 --- /dev/null +++ b/Task/Fibonacci-sequence/ZX-Spectrum-Basic/fibonacci-sequence-2.zx @@ -0,0 +1 @@ +10 DEF FN f(x)=INT (0.5+(((SQR 5+1)/2)^x)/SQR 5) diff --git a/Task/Fibonacci-sequence/Zkl/fibonacci-sequence.zkl b/Task/Fibonacci-sequence/Zkl/fibonacci-sequence.zkl new file mode 100644 index 0000000000..cf3df9cd79 --- /dev/null +++ b/Task/Fibonacci-sequence/Zkl/fibonacci-sequence.zkl @@ -0,0 +1 @@ +var fibShift=fcn(ab){ab.append(ab.sum()).pop(0)}.fp(L(0,1)); diff --git a/Task/Fibonacci-word-fractal/Kotlin/fibonacci-word-fractal.kotlin b/Task/Fibonacci-word-fractal/Kotlin/fibonacci-word-fractal.kotlin new file mode 100644 index 0000000000..651d75ccd7 --- /dev/null +++ b/Task/Fibonacci-word-fractal/Kotlin/fibonacci-word-fractal.kotlin @@ -0,0 +1,70 @@ +// version 1.1.2 + +import java.awt.* +import javax.swing.* + +class FibonacciWordFractal(n: Int) : JPanel() { + private val wordFractal: String + + init { + preferredSize = Dimension(450, 620) + background = Color.black + wordFractal = wordFractal(n) + } + + fun wordFractal(i: Int): String { + if (i < 2) return if (i == 1) "1" else "" + val f1 = StringBuilder("1") + val f2 = StringBuilder("0") + + for (j in i - 2 downTo 1) { + val tmp = f2.toString() + f2.append(f1) + f1.setLength(0) + f1.append(tmp) + } + + return f2.toString() + } + + private fun drawWordFractal(g: Graphics2D, x: Int, y: Int, dx: Int, dy: Int) { + var x2 = x + var y2 = y + var dx2 = dx + var dy2 = dy + for (i in 0 until wordFractal.length) { + g.drawLine(x2, y2, x2 + dx2, y2 + dy2) + x2 += dx2 + y2 += dy2 + if (wordFractal[i] == '0') { + val tx = dx2 + dx2 = if (i % 2 == 0) -dy2 else dy2 + dy2 = if (i % 2 == 0) tx else -tx + } + } + } + + override fun paintComponent(gg: Graphics) { + super.paintComponent(gg) + val g = gg as Graphics2D + g.color = Color.green + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON) + drawWordFractal(g, 20, 20, 1, 0) + } +} + +fun main(args: Array) { + SwingUtilities.invokeLater { + val f = JFrame() + with(f) { + defaultCloseOperation = JFrame.EXIT_ON_CLOSE + title = "Fibonacci Word Fractal" + isResizable = false + add(FibonacciWordFractal(23), BorderLayout.CENTER) + pack() + setLocationRelativeTo(null) + isVisible = true + } + } +} diff --git a/Task/Fibonacci-word-fractal/Lua/fibonacci-word-fractal.lua b/Task/Fibonacci-word-fractal/Lua/fibonacci-word-fractal.lua new file mode 100644 index 0000000000..7734485015 --- /dev/null +++ b/Task/Fibonacci-word-fractal/Lua/fibonacci-word-fractal.lua @@ -0,0 +1,48 @@ +RIGHT, LEFT, UP, DOWN = 1, 2, 4, 8 +function drawFractals( w ) + love.graphics.setCanvas( canvas ) + love.graphics.clear() + love.graphics.setColor( 255, 255, 255 ) + local dir, facing, lineLen, px, py, c = RIGHT, UP, 1, 10, love.graphics.getHeight() - 20, 1 + local x, y = 0, -lineLen + local pts = {} + table.insert( pts, px + .5 ); table.insert( pts, py + .5 ) + for i = 1, #w do + px = px + x; table.insert( pts, px + .5 ) + py = py + y; table.insert( pts, py + .5 ) + if w:sub( i, i ) == "0" then + if c % 2 == 1 then dir = RIGHT else dir = LEFT end + if facing == UP then + if dir == RIGHT then x = lineLen; facing = RIGHT + else x = -lineLen; facing = LEFT end; y = 0 + elseif facing == RIGHT then + if dir == RIGHT then y = lineLen; facing = DOWN + else y = -lineLen; facing = UP end; x = 0 + elseif facing == DOWN then + if dir == RIGHT then x = -lineLen; facing = LEFT + else x = lineLen; facing = RIGHT end; y = 0 + elseif facing == LEFT then + if dir == RIGHT then y = -lineLen; facing = UP + else y = lineLen; facing = DOWN end; x = 0 + end + end + c = c + 1 + end + love.graphics.line( pts ) + love.graphics.setCanvas() +end +function createWord( wordLen ) + local a, b, w = "1", "0" + repeat + w = b .. a; a = b; b = w; wordLen = wordLen - 1 + until wordLen == 0 + return w +end +function love.load() + wid, hei = love.graphics.getWidth(), love.graphics.getHeight() + canvas = love.graphics.newCanvas( wid, hei ) + drawFractals( createWord( 21 ) ) +end +function love.draw() + love.graphics.draw( canvas ) +end diff --git a/Task/Fibonacci-word-fractal/Phix/fibonacci-word-fractal.phix b/Task/Fibonacci-word-fractal/Phix/fibonacci-word-fractal.phix new file mode 100644 index 0000000000..aac74717d2 --- /dev/null +++ b/Task/Fibonacci-word-fractal/Phix/fibonacci-word-fractal.phix @@ -0,0 +1,60 @@ +-- +-- demo\rosetta\FibonacciFractal.exw +-- +include pGUI.e + +Ihandle dlg, canvas +cdCanvas cddbuffer, cdcanvas + +procedure drawFibonacci(integer x, y, dx, dy, n) +string prev = "1", word = "0" + for i=3 to n do {prev,word} = {word,word&prev} end for + for i=1 to length(word) do + cdCanvasLine(cddbuffer, x, y, x+dx, y+dy) + x += dx y += dy + if word[i]=='0' then + {dx,dy} = iff(remainder(i,2)?{dy,-dx}:{-dy,dx}) + end if + end for +end procedure + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) + cdCanvasActivate(cddbuffer) + cdCanvasClear(cddbuffer) + drawFibonacci(20, 20, 0, 1, 23) + cdCanvasFlush(cddbuffer) + return IUP_DEFAULT +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + cdCanvasSetBackground(cddbuffer, CD_WHITE) + cdCanvasSetForeground(cddbuffer, CD_GREEN) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "620x450") + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + + dlg = IupDialog(canvas, "RESIZE=NO") + IupSetAttribute(dlg, "TITLE", "Fibonacci Fractal") + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + + IupMap(dlg) + IupShowXY(dlg,IUP_CENTER,IUP_CENTER) + IupMainLoop() + IupClose() +end procedure + +main() diff --git a/Task/Fibonacci-word-fractal/R/fibonacci-word-fractal.r b/Task/Fibonacci-word-fractal/R/fibonacci-word-fractal.r new file mode 100644 index 0000000000..9e570f1a45 --- /dev/null +++ b/Task/Fibonacci-word-fractal/R/fibonacci-word-fractal.r @@ -0,0 +1,32 @@ +## Fibonacci word/fractal 2/20/17 aev +## Create Fibonacci word order n +fibow <- function(n) { + t2="0"; t1="01"; t=""; + if(n<2) {n=2} + for (i in 2:n) {t=paste0(t1,t2); t2=t1; t1=t} + return(t) +} +## Plot Fibonacci word/fractal: +## n - word order, w - width, h - height, d - segment size, clr - color. +pfibofractal <- function(n, w, h, d, clr) { + dx=d; x=y=x2=y2=tx=dy=nr=0; + if(n<2) {n=2} + fw=fibow(n); nf=nchar(fw); + pf = paste0("FiboFractR", n, ".png"); + ttl=paste0("Fibonacci word/fractal, n=",n); + cat(ttl,"nf=", nf, "pf=", pf,"\n"); + plot(NA, xlim=c(0,w), ylim=c(-h,0), xlab="", ylab="", main=ttl) + for (i in 1:nf) { + fwi=substr(fw, i, i); + x2=x+dx; y2=y+dy; + segments(x, y, x2, y2, col=clr); x=x2; y=y2; + if(fwi=="0") {tx=dx; nr=i%%2; + if(nr==0) {dx=-dy;dy=tx} else {dx=dy;dy=-tx}} + } + dev.copy(png, filename=pf, width=w, height=h); # plot to png-file + dev.off(); graphics.off(); # Cleaning +} + +## Executing: +pfibofractal(23, 1000, 1000, 1, "navy") +pfibofractal(25, 2300, 1000, 1, "red") diff --git a/Task/Fibonacci-word-fractal/Scilab/fibonacci-word-fractal.scilab b/Task/Fibonacci-word-fractal/Scilab/fibonacci-word-fractal.scilab new file mode 100644 index 0000000000..65c36ed7d3 --- /dev/null +++ b/Task/Fibonacci-word-fractal/Scilab/fibonacci-word-fractal.scilab @@ -0,0 +1,71 @@ +final_length = 37; + +word_n = ''; +word_n_1 = ''; +word_n_2 = ''; + +for i = 1:final_length + if i == 1 then + word_n = '1'; + elseif i == 2 + word_n = '0'; + elseif i == 3 + word_n = '01'; + word_n_1 = '0'; + else + word_n_2 = word_n_1; + word_n_1 = word_n; + word_n = word_n_1 + word_n_2; + end +end + +word = strsplit(word_n); +fractal_size = sum(word' == '0'); +fractal = zeros(1+fractal_size,2); + +direction_vectors = [1,0; 0,-1; -1,0; 0,1]; +direction = direction_vectors(4,:); +direction_name = 'N'; + +for j = 1:length(word_n); + fractal(j+1,:) = fractal(j,:) + direction; + if word(j) == '0' then + if pmodulo(j,2) then + //right + select direction_name + case 'N' then + direction = direction_vectors(1,:); + direction_name = 'E'; + case 'E' then + direction = direction_vectors(2,:); + direction_name = 'S'; + case 'S' then + direction = direction_vectors(3,:); + direction_name = 'W'; + case 'W' then + direction = direction_vectors(4,:); + direction_name = 'N'; + end + else + //left + select direction_name + case 'N' then + direction = direction_vectors(3,:); + direction_name = 'W'; + case 'W' then + direction = direction_vectors(2,:); + direction_name = 'S'; + case 'S' then + direction = direction_vectors(1,:); + direction_name = 'E'; + case 'E' then + direction = direction_vectors(4,:); + direction_name = 'N'; + end + end + end +end + +scf(0); clf(); +plot2d(fractal(:,1),fractal(:,2)); +set(gca(),'isoview','on'); diff --git a/Task/Fibonacci-word-fractal/Sidef/fibonacci-word-fractal.sidef b/Task/Fibonacci-word-fractal/Sidef/fibonacci-word-fractal.sidef index df06089f41..8aaf7434ba 100644 --- a/Task/Fibonacci-word-fractal/Sidef/fibonacci-word-fractal.sidef +++ b/Task/Fibonacci-word-fractal/Sidef/fibonacci-word-fractal.sidef @@ -1,8 +1,8 @@ var(m=17, scale=3) = ARGV.map{.to_i}... (var world = Hash.new){0}{0} = 1 -var loc = Complex(0, 0) -var dir = Complex.i +var loc = 0 +var dir = 1i var fib = ['1', '0'] func fib_word(n) { @@ -16,11 +16,11 @@ func step { } } -func turn_left { dir *= Complex.i } -func turn_right { dir *= -Complex.i } +func turn_left { dir *= 1i } +func turn_right { dir *= -1i } var n = 1 -fib_word(m).each_char { |c| +fib_word(m).each { |c| if (c == '0') { step() n % 2 == 0 ? turn_left() @@ -29,7 +29,7 @@ fib_word(m).each_char { |c| } func braille_graphics(a) { - var (xlo, xhi, ylo, yhi) = +([Inf, -Inf]*2)... + var (xlo, xhi, ylo, yhi) = ([Inf, -Inf]*2)... a.each_key { |y| ylo.min!(y.to_i) @@ -40,8 +40,8 @@ func braille_graphics(a) { } } - for y in (ylo .. (yhi, 4)) { - for x in (xlo .. (xhi, 2)) { + for y in (ylo..yhi `by` 4) { + for x in (xlo..xhi `by` 2) { var cell = 0x2800 a{y+0}{x+0} && (cell += 1) diff --git a/Task/Fibonacci-word-fractal/Zkl/fibonacci-word-fractal.zkl b/Task/Fibonacci-word-fractal/Zkl/fibonacci-word-fractal.zkl new file mode 100644 index 0000000000..a99f8f79c5 --- /dev/null +++ b/Task/Fibonacci-word-fractal/Zkl/fibonacci-word-fractal.zkl @@ -0,0 +1,17 @@ +fcn drawFibonacci(img,x,y,word){ // word is "01001010...", 75025 characters + dx:=0; dy:=1; // turtle direction + foreach i,c in ([1..].zip(word)){ // Walker.zip(list)-->Walker of zipped list + a:=x; b:=y; x+=dx; y+=dy; + img.line(a,b, x,y, 0x00ff00); + if (c=="0"){ + dxy:=dx+dy; + if(i.isEven){ dx=(dx - dxy)%2; dy=(dxy - dy)%2; }// turn left + else { dx=(dxy - dx)%2; dy=(dy - dxy)%2; }// turn right + } + } +} + +img:=PPM(1050,1050); +fibWord:=L("1","0"); do(23){ fibWord.append(fibWord[-1] + fibWord[-2]); } +drawFibonacci(img,20,20,fibWord[-1]); +img.write(File("foo.ppm","wb")); diff --git a/Task/Fibonacci-word/Aime/fibonacci-word.aime b/Task/Fibonacci-word/Aime/fibonacci-word.aime new file mode 100644 index 0000000000..986d5fe340 --- /dev/null +++ b/Task/Fibonacci-word/Aime/fibonacci-word.aime @@ -0,0 +1,44 @@ +real +entropy(data b) +{ + integer count, i; + real ones, zeros; + + ones = zeros = 0; + + i = -(count = b_length(b)); + while (i) { + if (b[i] == '0') { + zeros += 1; + } else { + ones += 1; + } + + i += 1; + } + + return -(ones /= count) * log2(ones) - (zeros /= count) * log2(zeros); +} + +integer +main(void) +{ + data a, b; + integer i; + + a = "1"; + b = "0"; + + o_form("%2d %9d /w12p10d10/ ~\n", 1, b_length(a), 0r, a); + o_form("%2d %9d /w12p10d10/ ~\n", 2, b_length(b), 0r, b); + i = 3; + while (i <= 37) { + b_stock(a, 0, b); + o_form("%2d %9d /w12p10d10/ ~\n", i, b_length(a), entropy(a), + __hold(i < 10, a, "")); + i += 1; + b_swap(a, b); + } + + return 0; +} diff --git a/Task/Fibonacci-word/jq/fibonacci-word-1.jq b/Task/Fibonacci-word/Jq/fibonacci-word-1.jq similarity index 100% rename from Task/Fibonacci-word/jq/fibonacci-word-1.jq rename to Task/Fibonacci-word/Jq/fibonacci-word-1.jq diff --git a/Task/Fibonacci-word/jq/fibonacci-word-2.jq b/Task/Fibonacci-word/Jq/fibonacci-word-2.jq similarity index 100% rename from Task/Fibonacci-word/jq/fibonacci-word-2.jq rename to Task/Fibonacci-word/Jq/fibonacci-word-2.jq diff --git a/Task/Fibonacci-word/jq/fibonacci-word-3.jq b/Task/Fibonacci-word/Jq/fibonacci-word-3.jq similarity index 100% rename from Task/Fibonacci-word/jq/fibonacci-word-3.jq rename to Task/Fibonacci-word/Jq/fibonacci-word-3.jq diff --git a/Task/Fibonacci-word/Julia/fibonacci-word.julia b/Task/Fibonacci-word/Julia/fibonacci-word.julia new file mode 100644 index 0000000000..0000460053 --- /dev/null +++ b/Task/Fibonacci-word/Julia/fibonacci-word.julia @@ -0,0 +1,26 @@ +# Code for "entropy" taken from https://rosettacode.org/wiki/Entropy#Julia +entropy(s::String)::Float32 = -sum(x -> x * log(2, x), [count(x -> x == c, s) / length(s) for c in unique(s)]) + +function fibboword(n::Int64)::Array{String} + # Initialize the result + r = Array{String}(n) + # First element + r[1] = "0" + # If more than 2, set the second element + if (n ≥ 2) + r[2] = "1" + end + # Recursively create elements > 3 + for i in 3:n + r[i] = r[i - 1] * r[i - 2] + end + return r +end + +function testfibbo(n::Int64) + fib = fibboword(n) + for i in 1:length(fib) + println(i, "\t", length(fib[i]), "\t", entropy(fib[i])) + end + return 0 +end diff --git a/Task/Fibonacci-word/Kotlin/fibonacci-word.kotlin b/Task/Fibonacci-word/Kotlin/fibonacci-word.kotlin new file mode 100644 index 0000000000..9f16bedaa5 --- /dev/null +++ b/Task/Fibonacci-word/Kotlin/fibonacci-word.kotlin @@ -0,0 +1,32 @@ +// version 1.0.6 + +fun fibWord(n: Int): String { + if (n < 1) throw IllegalArgumentException("Argument can't be less than 1") + if (n == 1) return "1" + val words = Array(n){ "" } + words[0] = "1" + words[1] = "0" + for (i in 2 until n) words[i] = words[i - 1] + words[i - 2] + return words[n - 1] +} + +fun log2(d: Double) = Math.log(d) / Math.log(2.0) + +fun shannon(s: String): Double { + if (s.length <= 1) return 0.0 + val count0 = s.count { it == '0' } + val count1 = s.length - count0 + val nn = s.length.toDouble() + return -(count0 / nn * log2(count0 / nn) + count1 / nn * log2(count1 / nn)) +} + +fun main(args: Array) { + println("N Length Entropy Word") + println("-- -------- ------------------ ----------------------------------") + for (i in 1..37) { + val s = fibWord(i) + print(String.format("%2d %8d %18.16f", i, s.length, shannon(s))) + if (i < 10) println(" $s") + else println() + } +} diff --git a/Task/Fibonacci-word/OoRexx/fibonacci-word.rexx b/Task/Fibonacci-word/OoRexx/fibonacci-word.rexx new file mode 100644 index 0000000000..69b180c6dc --- /dev/null +++ b/Task/Fibonacci-word/OoRexx/fibonacci-word.rexx @@ -0,0 +1,51 @@ +/* REXX --------------------------------------------------------------- +* 09.08.2014 Walter Pachl 'copied' from REXX +* lists the # of chars in fibonacci words and the words' entropy +* as well as (part of) the Fibonacci word and the number of 0's and 1's +* Note: ooRexx allows for computing up to 47 Fibonacci words +*--------------------------------------------------------------------*/ + Numeric Digits 20 /* use more precision, default=9.*/ + Parse Arg n fw.1 fw.2 . /* get optional args from the C.L.*/ + If n=='' Then n=50 /* Not specified? Then use default*/ + If fw.1=='' Then fw.1=1 /* " " " " " */ + If fw.2=='' Then fw.2=0 /* " " " " " */ + hdr1=' N length Entropy Fibonacci word ', + '# of zeroes # of ones' + hdr2='-- ---------- ---------------------- --------------------', + '--------- ---------' + Say hdr1 + Say hdr2 + Do j=1 For n /* display N fibonacci words. */ + j1=j-1 + j2=j-2 + If j>2 Then /* calculate FIBword if we need to*/ + fw.j=fw.j1||fw.j2 + If length(fw.j)<20 Then + fwd=left(fw.j,20) /* display the Fibonacci word */ + Else + fwd=left(fw.j,5)'...'right(fw.j,12) /* display parts thereof */ + Say right(j,2)' 'right(length(fw.j),9)' 'entropy(fw.j)' 'fwd, + right(aa.0,9) right(aa.1,9) + End + Say hdr2 + Say hdr1 + Exit + +entropy: Procedure Expose aa. + Parse Arg dd + l=length(dd) + d=digits() + aa.0=l-length(space(translate(dd,,0),0)) /*fast way to count zeroes*/ + aa.1=l-aa.0 /* and figure the number of ones. */ + If l==1 Then + Return left(0,d+2) /* handle special case of one char*/ + s=0 /* [?] calc entropy for each char */ + do i=1 for 2 + _=i-1 /* construct a chr from the ether.*/ + p=aa._/l /* 'probability of aa-_ in fw */ + s=s-p*rxmlog(p,d,2) /* add (negatively) the entropies.*/ + End + If s=1 Then + Return left(1,d+2) /* return a left-justified "1". */ + Return format(s,,d) /* normalize the number (sum or S)*/ +::requires rxm.cls diff --git a/Task/Fibonacci-word/Phix/fibonacci-word.phix b/Task/Fibonacci-word/Phix/fibonacci-word.phix new file mode 100644 index 0000000000..8f1927fc3a --- /dev/null +++ b/Task/Fibonacci-word/Phix/fibonacci-word.phix @@ -0,0 +1,37 @@ +function log2(atom v) + return log(v)/log(2) +end function + +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 + integer n = length(counts) + for i=1 to n do + atom ci = counts[i]/N + H -= ci*log2(ci) + end for + return H +end function + +sequence F_words = {"1","0"} +for i=3 to 37 do + F_words = append(F_words,F_words[i-1]&F_words[i-2]) +end for + +for i=1 to length(F_words) do + printf(1,"%2d: length %9d, entropy %f %s\n", + {i,length(F_words[i]),entropy(F_words[i]), + iff(i<10?F_words[i],"...")}) +end for diff --git a/Task/Fibonacci-word/Scheme/fibonacci-word.ss b/Task/Fibonacci-word/Scheme/fibonacci-word.ss new file mode 100644 index 0000000000..79e6be05e8 --- /dev/null +++ b/Task/Fibonacci-word/Scheme/fibonacci-word.ss @@ -0,0 +1,42 @@ +(import (scheme base) + (scheme inexact) + (scheme write)) + +(define *words* (make-vector 38 "")) + +(define (create-words) + (vector-set! *words* 1 "1") + (vector-set! *words* 2 "0") + (do ((i 3 (+ 1 i))) + ((= i (vector-length *words*)) ) + (vector-set! *words* i (string-append (vector-ref *words* (- i 1)) + (vector-ref *words* (- i 2)))))) + +;; in this context, word only contains 1 or 0 +(define (entropy word) + (let* ((N (string-length word)) + (num-ones 0) + (num-zeros 0)) + (string-for-each (lambda (c) + (if (char=? c #\1) + (set! num-ones (+ 1 num-ones)) + (set! num-zeros (+ 1 num-zeros)))) + word) + (if (or (zero? num-ones) (zero? num-zeros)) + 0 + (- 0 + (* (/ num-ones N) (log (/ num-ones N) 2)) + (* (/ num-zeros N) (log (/ num-zeros N) 2)))))) + +;; display values +(create-words) +(do ((i 1 (+ 1 i))) + ((= i (vector-length *words*)) ) + (display (string-append (number->string i) + " " + (number->string + (string-length (vector-ref *words* i))) + " " + (number->string + (entropy (vector-ref *words* i))) + "\n"))) diff --git a/Task/Fibonacci-word/Scilab/fibonacci-word-1.scilab b/Task/Fibonacci-word/Scilab/fibonacci-word-1.scilab new file mode 100644 index 0000000000..5a581a7847 --- /dev/null +++ b/Task/Fibonacci-word/Scilab/fibonacci-word-1.scilab @@ -0,0 +1,31 @@ +exec('.\entropy.sci',0); + +function word=fiboword(n) + word_1 = '1'; word_2 = '0'; + select n + case 1 + word = word_1 + case 2 + word = word_2; + case 3 + word = strcat([word_2 word_1]); + else + word = strcat([fiboword(n-1) fiboword(n-2)]) + end +endfunction + +final_length = 37; + +N=[1:final_length]'; +char_length = zeros(N); +entropies = zeros(N); +tic(); +for i=1:final_length + word = fiboword(i); + char_length(i) = length(word); + entropies(i) = entropy(word); +end +time = toc(); + +disp('EXECUTION TIME: '+string(time)+'s.'); +disp(['N', 'LENGTH', 'ENTROPY'; string([N char_length entropies])]); diff --git a/Task/Fibonacci-word/Scilab/fibonacci-word-2.scilab b/Task/Fibonacci-word/Scilab/fibonacci-word-2.scilab new file mode 100644 index 0000000000..429e8e3538 --- /dev/null +++ b/Task/Fibonacci-word/Scilab/fibonacci-word-2.scilab @@ -0,0 +1,33 @@ +exec('.\entropy.sci',0); + +final_length = 37; + +word_n = ''; +word_n_1 = ''; +word_n_2 = ''; + +N = [1:final_length]'; +word_length = zeros(N); +entropies = zeros(N); + +tic(); +for i = 1:final_length + if i == 1 then + word_n = '1'; + elseif i == 2 + word_n = '0'; + elseif i == 3 + word_n = '01'; + word_n_1 = '0'; + else + word_n_2 = word_n_1; + word_n_1 = word_n; + word_n = word_n_1 + word_n_2; + end + word_length(i) = length(word_n); + entropies(i) = entropy(word_n); +end +time = toc(); + +disp('EXECUTION TIME: '+string(time)+'s.'); +disp(['N', 'LENGTH', 'ENTROPY'; string([N word_length entropies])]); diff --git a/Task/Fibonacci-word/Zkl/fibonacci-word.zkl b/Task/Fibonacci-word/Zkl/fibonacci-word.zkl new file mode 100644 index 0000000000..8e5ff8ae60 --- /dev/null +++ b/Task/Fibonacci-word/Zkl/fibonacci-word.zkl @@ -0,0 +1,14 @@ +fcn entropy(bs){ //binary String-->Float + len:=bs.len(); num1s:=(bs-"0").len(); + T(num1s,len-num1s).filter().apply('wrap(p){ p=p.toFloat()/len; -p*p.log() }) + .sum(0.0) / (2.0).log(); +} + +" N Length Entropy Fibword".println(); +ws:=L("1","0"); +foreach n in ([1..37]){ + if(n>2) ws.append(ws[-1]+ws[-2]); + w:=ws[-1]; + "%3d %10d %2.10f %s".fmt(n,w.len(),entropy(w), + w.len()<50 and w or "").println(); +} diff --git a/Task/File-input-output/BASIC/file-input-output-2.basic b/Task/File-input-output/BASIC/file-input-output-2.basic index ab05afe9b9..13e6a48c46 100644 --- a/Task/File-input-output/BASIC/file-input-output-2.basic +++ b/Task/File-input-output/BASIC/file-input-output-2.basic @@ -1,20 +1,24 @@ 100 I$ = "INPUT.TXT" 110 O$ = "OUTPUT.TXT" -120 D$ = CHR$(4) -130 M$ = CHR$(13) +120 M$ = CHR$(13) +130 D$ = CHR$(4) 140 PRINT D$"VERIFY"I$ -150 PRINT D$"OPEN"O$M$D$"CLOSE"O$M$D$"DELETE"O$ -160 PRINT D$"OPEN"O$M$D$"OPEN"I$; +150 PRINT D$"OPEN"O$ +160 PRINT D$"DELETE"O$ +170 PRINT D$"OPEN"O$ +180 PRINT D$"OPEN"I$ -170 PRINT M$D$"READ"I$ -180 ONERR GOTO 250 -190 GET C$ -200 POKE 216,0 -210 PRINT M$D$"WRITE"O$",B"B -220 IF C$ <> M$ THEN PRINT C$; -230 B = B + 1 -240 GOTO 170 +190 PRINT D$"READ"I$ +200 ONERR GOTO 280 +210 GET C$ +220 POKE 216,0 +230 PRINT M$D$"WRITE"O$",B"B +240 B = B + 1 +250 P = 2 - (C$ <> M$) +260 PRINT MID$(C$, P) +270 GOTO 190 -250 POKE 216,0 -260 IF PEEK(222) <> 5 THEN RESUME -270 PRINT M$D$"CLOSE"I$M$D$"CLOSE"O$ +280 POKE 216,0 +290 EOF = PEEK(222) = 5 +300 IF NOT EOF THEN RESUME +310 PRINT M$D$"CLOSE" diff --git a/Task/File-input-output/BASIC/file-input-output-3.basic b/Task/File-input-output/BASIC/file-input-output-3.basic new file mode 100644 index 0000000000..2b5bbaae94 --- /dev/null +++ b/Task/File-input-output/BASIC/file-input-output-3.basic @@ -0,0 +1,13 @@ +10 print chr$(14) : rem switch to upper+lower case set +20 print "read seq file input.txt and write to seq file output.txt" +30 open 4,8,4,"input.txt,seq,read" +40 open 8,8,8,"@:output.txt,seq,write" : rem '@'== new file +50 for i=0 to 1 : rem while i==0 +60 input#4,a$ +70 i=64 and st : rem check bit 6=='end of file' +80 print a$ +90 print#8,a$ +100 next : rem end while +110 close 4 +120 close 8 +130 end diff --git a/Task/File-input-output/Gambas/file-input-output.gambas b/Task/File-input-output/Gambas/file-input-output.gambas new file mode 100644 index 0000000000..1082e48b19 --- /dev/null +++ b/Task/File-input-output/Gambas/file-input-output.gambas @@ -0,0 +1,11 @@ +Public Sub Main() +Dim sOutput As String = "Hello " +Dim sInput As String = File.Load(User.Home &/ "input.txt") 'Has the word 'World!' stored + +File.Save(User.Home &/ "output.txt", sOutput) +File.Save(User.Home &/ "input.txt", sOutput & sInput) + +Print "'input.txt' contains - " & sOutput & sInput +Print "'output.txt' contains - " & sOutput + +End diff --git a/Task/File-input-output/jq/file-input-output-1.jq b/Task/File-input-output/Jq/file-input-output-1.jq similarity index 100% rename from Task/File-input-output/jq/file-input-output-1.jq rename to Task/File-input-output/Jq/file-input-output-1.jq diff --git a/Task/File-input-output/jq/file-input-output-2.jq b/Task/File-input-output/Jq/file-input-output-2.jq similarity index 100% rename from Task/File-input-output/jq/file-input-output-2.jq rename to Task/File-input-output/Jq/file-input-output-2.jq diff --git a/Task/File-input-output/Kotlin/file-input-output.kotlin b/Task/File-input-output/Kotlin/file-input-output.kotlin new file mode 100644 index 0000000000..5b8c7a83c5 --- /dev/null +++ b/Task/File-input-output/Kotlin/file-input-output.kotlin @@ -0,0 +1,8 @@ +// version 1.1.2 + +import java.io.File + +fun main(args: Array) { + val text = File("input.txt").readText() + File("output.txt").writeText(text) +} diff --git a/Task/File-input-output/MIRC-Scripting-Language/file-input-output.mirc b/Task/File-input-output/MIRC-Scripting-Language/file-input-output.mirc new file mode 100644 index 0000000000..0413d79d9a --- /dev/null +++ b/Task/File-input-output/MIRC-Scripting-Language/file-input-output.mirc @@ -0,0 +1,4 @@ +alias Write2FileAndReadIt { +.write myfilename.txt Goodbye Mike! +.echo -a Myfilename.txt contains: $read(myfilename.txt,1) +} diff --git a/Task/File-input-output/Maple/file-input-output.maple b/Task/File-input-output/Maple/file-input-output.maple new file mode 100644 index 0000000000..cec03cef83 --- /dev/null +++ b/Task/File-input-output/Maple/file-input-output.maple @@ -0,0 +1,5 @@ +inout:=proc(filename) +local f; +f:=FileTools[Text][ReadFile](filename); +FileTools[Text][WriteFile]("output.txt",f); +end proc; diff --git a/Task/File-input-output/REXX/file-input-output-1.rexx b/Task/File-input-output/REXX/file-input-output-1.rexx index dd93e0998c..668cf04dbc 100644 --- a/Task/File-input-output/REXX/file-input-output-1.rexx +++ b/Task/File-input-output/REXX/file-input-output-1.rexx @@ -1,10 +1,12 @@ -/*REXX program to read a file and store the contents into an output file*/ -iFID = 'input.txt' /*name of the input file. */ -oFID = 'output.txt' /*name of the output file. */ -call lineout oFID,,1 /*insure output starts at line 1.*/ +/*REXX program reads a file and copies the contents into an output file (on a line by line basis).*/ +iFID = 'input.txt' /*the name of the input file. */ +oFID = 'output.txt' /* " " " " output " */ +call lineout iFID,,1 /*insure the input starts at line one.*/ /* ◄■■■■■■ optional.*/ +call lineout oFID,,1 /* " " output " " " " */ /* ◄■■■■■■ optional.*/ - do while lines(iFID)\==0 /*read records until finished. */ - y = linein(iFID) /*read a record from input. */ - call lineout oFID,y /*write a record to output. */ - end /*while ···*/ - /*stick a fork in it, we're done.*/ + do while lines(iFID)\==0; $=linein(iFID) /*read records from input 'til finished*/ + call lineout oFID, $ /*write the record just read ──► output*/ + end /*while*/ /*stick a fork in it, we're all done. */ + +call lineout iFID /*close input file, just to be safe.*/ /* ◄■■■■■■ best programming practice.*/ +call lineout oFID /* " output " " " " " */ /* ◄■■■■■■ best programming practice.*/ diff --git a/Task/File-input-output/Stata/file-input-output.stata b/Task/File-input-output/Stata/file-input-output.stata new file mode 100644 index 0000000000..8b61ea5b88 --- /dev/null +++ b/Task/File-input-output/Stata/file-input-output.stata @@ -0,0 +1,14 @@ +program copyfile + file open fin using `1', read text + file open fout using `2', write text replace + + file read fin line + while !r(eof) { + file write fout `"`line'"' _newline + file read fin line + } + file close fin + file close fout +end + +copyfile input.txt output.txt diff --git a/Task/File-input-output/TUSCRIPT/file-input-output.tu b/Task/File-input-output/TUSCRIPT/file-input-output.tu new file mode 100644 index 0000000000..7eade7083b --- /dev/null +++ b/Task/File-input-output/TUSCRIPT/file-input-output.tu @@ -0,0 +1,10 @@ +$$ MODE TUSCRIPT +ERROR/STOP CREATE ("input.txt", seq-o,-std-) +ERROR/STOP CREATE ("output.txt",seq-o,-std-) + +FILE/ERASE "input.txt" = "Some irrelevant content" +path2input =FULLNAME(TUSTEP,"input.txt", -std-) +status=READ (path2input,contentinput) + +path2output=FULLNAME(TUSTEP,"output.txt",-std-) +status=WRITE(path2output,contentinput) diff --git a/Task/File-input-output/TXR/file-input-output-1.txr b/Task/File-input-output/TXR/file-input-output-1.txr new file mode 100644 index 0000000000..866da57c40 --- /dev/null +++ b/Task/File-input-output/TXR/file-input-output-1.txr @@ -0,0 +1,2 @@ +(let ((var (file-get-string "input.txt"))) + (file-put-string "output.txt" var)) diff --git a/Task/File-input-output/TXR/file-input-output-2.txr b/Task/File-input-output/TXR/file-input-output-2.txr new file mode 100644 index 0000000000..8d4b8289af --- /dev/null +++ b/Task/File-input-output/TXR/file-input-output-2.txr @@ -0,0 +1,2 @@ +(let ((var (file-get-lines "input.txt"))) + (file-put-lines "output.txt" var)) diff --git a/Task/File-input-output/Zkl/file-input-output-1.zkl b/Task/File-input-output/Zkl/file-input-output-1.zkl new file mode 100644 index 0000000000..30b4688621 --- /dev/null +++ b/Task/File-input-output/Zkl/file-input-output-1.zkl @@ -0,0 +1,3 @@ +var d=File("input.txt").read(); +(f:=File("output.txt","w")).write(d); f.close(); // one read, one write copy +File("output.txt").pump(Console); // verify by printing diff --git a/Task/File-input-output/Zkl/file-input-output-2.zkl b/Task/File-input-output/Zkl/file-input-output-2.zkl new file mode 100644 index 0000000000..94dfeb42cd --- /dev/null +++ b/Task/File-input-output/Zkl/file-input-output-2.zkl @@ -0,0 +1,3 @@ +var in=File("input.txt"), out=File("output.txt","w"); +foreach line in (in) { out.write(line) } // copy line by line +out.close(); // or out=Void and let GC close the file diff --git a/Task/File-input-output/Zkl/file-input-output-3.zkl b/Task/File-input-output/Zkl/file-input-output-3.zkl new file mode 100644 index 0000000000..fde433cb4f --- /dev/null +++ b/Task/File-input-output/Zkl/file-input-output-3.zkl @@ -0,0 +1,2 @@ +fin,fout:=File("input.txt","rb"), File("output.txt","wb"); // copy in chunks, implicit buffer +fin.pump(Data(0d524_287),fout); fin.close(); fout.close(); diff --git a/Task/File-input-output/Zkl/file-input-output-4.zkl b/Task/File-input-output/Zkl/file-input-output-4.zkl new file mode 100644 index 0000000000..a1c06e9d5a --- /dev/null +++ b/Task/File-input-output/Zkl/file-input-output-4.zkl @@ -0,0 +1,2 @@ +// copy in chunks, let GC close file handles +File("input.txt","rb").pump(Data(0d524_287),File("output.txt","wb")); diff --git a/Task/File-input-output/Zkl/file-input-output-5.zkl b/Task/File-input-output/Zkl/file-input-output-5.zkl new file mode 100644 index 0000000000..17d826b3a4 --- /dev/null +++ b/Task/File-input-output/Zkl/file-input-output-5.zkl @@ -0,0 +1 @@ +File("input.txt").pump(Data(),File("output.txt","w"),"text","toUpper"); diff --git a/Task/File-modification-time/Gambas/file-modification-time.gambas b/Task/File-modification-time/Gambas/file-modification-time.gambas new file mode 100644 index 0000000000..c594f0ac97 --- /dev/null +++ b/Task/File-modification-time/Gambas/file-modification-time.gambas @@ -0,0 +1,9 @@ +' There is no built in command in Gambas to 'set' the modification time of a file +' A shell call to 'touch' would do it + +Public Sub Main() +Dim stInfo As Stat = Stat(User.home &/ "Rosetta.txt") + +Print "Rosetta.txt was last modified " & Format(stInfo.LastModified, "dd/mm/yyy hh:nn:ss") + +End diff --git a/Task/File-modification-time/Kotlin/file-modification-time.kotlin b/Task/File-modification-time/Kotlin/file-modification-time.kotlin new file mode 100644 index 0000000000..a7f6f5250b --- /dev/null +++ b/Task/File-modification-time/Kotlin/file-modification-time.kotlin @@ -0,0 +1,14 @@ +// version 1.0.6 + +import java.io.File + +fun main(args: Array) { + val filePath = "input.txt" // or whatever + val file = File(filePath) + with (file) { + println("%tc".format(lastModified())) + // update to current time, say + setLastModified(System.currentTimeMillis()) + println("%tc".format(lastModified())) + } +} diff --git a/Task/File-modification-time/Objeck/file-modification-time.objeck b/Task/File-modification-time/Objeck/file-modification-time.objeck new file mode 100644 index 0000000000..567731d7be --- /dev/null +++ b/Task/File-modification-time/Objeck/file-modification-time.objeck @@ -0,0 +1,7 @@ +use System.IO.File; + +class Program { + function : Main(args : String[]) ~ Nil { + File->ModifiedTime("file_mod.obs")->ToString()->PrintLine(); + } +} diff --git a/Task/File-modification-time/Ring/file-modification-time.ring b/Task/File-modification-time/Ring/file-modification-time.ring new file mode 100644 index 0000000000..45ee51e646 --- /dev/null +++ b/Task/File-modification-time/Ring/file-modification-time.ring @@ -0,0 +1,9 @@ +load "stdlib.ring" +see GetFileInfo( "test.ring" ) + +func GetFileInfo cFile + cOutput = systemcmd("dir /T:W " + cFile ) + aList = str2list(cOutput) + cLine = aList[6] + aInfo = split(cLine," ") + return aInfo diff --git a/Task/File-modification-time/Zkl/file-modification-time.zkl b/Task/File-modification-time/Zkl/file-modification-time.zkl new file mode 100644 index 0000000000..0d2ad77ec2 --- /dev/null +++ b/Task/File-modification-time/Zkl/file-modification-time.zkl @@ -0,0 +1,6 @@ +info:=File.info("input.txt"); + // -->T(size,last status change time,last mod time,isDir,mode), from stat(2) +info.println(); +Time.Date.ctime(info[2]).println(); +File.setModTime("input.txt",Time.Clock.mktime(2014,2,1,0,0,0)); +File.info("input.txt")[2] : Time.Date.ctime(_).println(); diff --git a/Task/File-size/BaCon/file-size.bacon b/Task/File-size/BaCon/file-size.bacon new file mode 100644 index 0000000000..8f6f6e12a1 --- /dev/null +++ b/Task/File-size/BaCon/file-size.bacon @@ -0,0 +1,12 @@ +' file size +' Return the entire message, FILELEN returns a NUMBER +FUNCTION printlen$(STRING name$) + IF FILEEXISTS(name$) THEN + RETURN name$ & ": " & STR$(FILELEN(name$)) + ELSE + RETURN "file " & name$ & " not found" + END IF +END FUNCTION + +PRINT printlen$("input.txt") +PRINT printlen$("/input.txt") diff --git a/Task/File-size/D/file-size-1.d b/Task/File-size/D/file-size-1.d deleted file mode 100644 index ec974a572a..0000000000 --- a/Task/File-size/D/file-size-1.d +++ /dev/null @@ -1,5 +0,0 @@ -import std.file; - -void main() { - auto len = getSize("data.txt"); -} diff --git a/Task/File-size/D/file-size-2.d b/Task/File-size/D/file-size-2.d deleted file mode 100644 index 2afe352248..0000000000 --- a/Task/File-size/D/file-size-2.d +++ /dev/null @@ -1,35 +0,0 @@ -import std.stdio, std.path, std.file, std.stream; -// NB: mmfile can treat the file as an array in memory -import std.mmfile; - -string[] generateTwoNames(string name) { - string cwd = curdir ~ sep; // on current directory - string root = sep; // on root - - // remove path, left only basename - name = std.path.getBaseName(name); - - // NB: in D ver.2, getBaseName is alias of basename - return [cwd ~ name, root ~ name]; -} - -void testsize(string fileName1) { - foreach (fileName2; generateTwoNames(fileName1)) { - try { - writefln("File %s has size:", fileName2); - writefln("%10d bytes by std.file.getSize (function),", - std.file.getSize(fileName2)); - writefln("%10d bytes by std.stream (class),", - (new std.stream.File(fileName2)).size); - writefln("%10d bytes by std.mmfile (class).", - (new std.mmfile.MmFile(fileName2)).length); - } catch (Exception e) { - writefln(e.msg); - } - writeln(); - } -} - -void main() { - testsize(r"input.txt"); -} diff --git a/Task/File-size/Elena/file-size.elena b/Task/File-size/Elena/file-size.elena index 19310a8eaf..f35b23a829 100644 --- a/Task/File-size/Elena/file-size.elena +++ b/Task/File-size/Elena/file-size.elena @@ -1,9 +1,9 @@ -#import system. -#import system'io. +import system'io. +import extensions. -#symbol program = +program = [ - console writeLine:("input.txt" file_path length). + console printLine(File new:"input.txt"; length). - console writeLine:("\input.txt" file_path length). + console printLine(File new("\input.txt"); length). ]. diff --git a/Task/File-size/Gambas/file-size.gambas b/Task/File-size/Gambas/file-size.gambas new file mode 100644 index 0000000000..c8c25d3536 --- /dev/null +++ b/Task/File-size/Gambas/file-size.gambas @@ -0,0 +1,8 @@ +Public Sub Main() +Dim stInfo As Stat = Stat(User.home &/ "input.txt") +Dim stInfo1 As Stat = Stat("/input.txt") + +Print User.Home &/ "input.txt = " & stInfo.Size & " bytes" +Print "/input.txt = " & stInfo1.Size & " bytes" + +End diff --git a/Task/File-size/jq/file-size.jq b/Task/File-size/Jq/file-size.jq similarity index 100% rename from Task/File-size/jq/file-size.jq rename to Task/File-size/Jq/file-size.jq diff --git a/Task/File-size/Kotlin/file-size.kotlin b/Task/File-size/Kotlin/file-size.kotlin new file mode 100644 index 0000000000..83c07f17a2 --- /dev/null +++ b/Task/File-size/Kotlin/file-size.kotlin @@ -0,0 +1,9 @@ +// version 1.0.6 + +import java.io.File + +fun main(args: Array) { + val paths = arrayOf("input.txt", "c:\\input.txt") + for (path in paths) + println("Length of $path is ${File(path).length()} bytes") +} diff --git a/Task/File-size/Lua/file-size-1.lua b/Task/File-size/Lua/file-size-1.lua deleted file mode 100644 index 695a00ea58..0000000000 --- a/Task/File-size/Lua/file-size-1.lua +++ /dev/null @@ -1 +0,0 @@ -FileTools:-Size( "input.txt" ) diff --git a/Task/File-size/Lua/file-size-2.lua b/Task/File-size/Lua/file-size-2.lua deleted file mode 100644 index 4cf2ef9b67..0000000000 --- a/Task/File-size/Lua/file-size-2.lua +++ /dev/null @@ -1 +0,0 @@ -FileTools:-Size( "/input.txt" ) diff --git a/Task/File-size/MIRC-Scripting-Language/file-size.mirc b/Task/File-size/MIRC-Scripting-Language/file-size.mirc new file mode 100644 index 0000000000..23db160ab2 --- /dev/null +++ b/Task/File-size/MIRC-Scripting-Language/file-size.mirc @@ -0,0 +1,2 @@ +echo -ag $file(input.txt).size bytes +echo -ag $file(C:\input.txt).size bytes diff --git a/Task/File-size/OoRexx/file-size.rexx b/Task/File-size/OoRexx/file-size.rexx new file mode 100644 index 0000000000..7aafe281c5 --- /dev/null +++ b/Task/File-size/OoRexx/file-size.rexx @@ -0,0 +1,13 @@ +Parse Version v +Say v +fid='test.txt' +x=sysfiletree(fid,a.) +Say a.0 +Say a.1 +Say left(copies('123456789.',10),length(a.1)) +Parse Var a.1 20 size . +Say 'file size:' size +s=charin(fid,,1000) +Say length(s) +Say 'file' fid +'type' fid diff --git a/Task/File-size/Stata/file-size-1.stata b/Task/File-size/Stata/file-size-1.stata new file mode 100644 index 0000000000..ca699485f3 --- /dev/null +++ b/Task/File-size/Stata/file-size-1.stata @@ -0,0 +1,5 @@ +file open f using input.txt, read binary +file seek f eof +file seek f query +display r(loc) +file close f diff --git a/Task/File-size/Stata/file-size-2.stata b/Task/File-size/Stata/file-size-2.stata new file mode 100644 index 0000000000..37d097daa8 --- /dev/null +++ b/Task/File-size/Stata/file-size-2.stata @@ -0,0 +1,2 @@ +describe using test.dta +display r(N)*r(width) diff --git a/Task/File-size/X86-Assembly/file-size.x86 b/Task/File-size/X86-Assembly/file-size.x86 new file mode 100644 index 0000000000..349199f692 --- /dev/null +++ b/Task/File-size/X86-Assembly/file-size.x86 @@ -0,0 +1,68 @@ +; x86_64 linux nasm + +section .data +localFileName: db "input.txt", 0 +rootFileName: db "/initrd.img", 0 + +section .text + +global _start + +_start: + + ; open file in current dir + mov rax, 2 + mov rdi, localFileName + xor rsi, rsi + mov rdx, 0 + syscall + push rax + + mov rdi, rax ; file descriptior + mov rsi, 0 ; offset + mov rdx, 2 ; whence + mov rax, 8 ; sys_lseek + syscall + + ; compare result to actual size + cmp rax, 11 + jne fail + + ; close the file + pop rdi + mov rax, 3 + syscall + + ; open file in root dir + mov rax, 2 + mov rdi, rootFileName + xor rsi, rsi + mov rdx, 0 + syscall + push rax + + mov rdi, rax ; file descriptior + mov rsi, 0 ; offset + mov rdx, 2 ; whence + mov rax, 8 ; sys_lseek + syscall + + ; compare result to actual size + cmp rax, 37722243 + jne fail + + ; close the file + pop rdi + mov rax, 3 + syscall + + ; test successful + mov rax, 60 + mov rdi, 0 + syscall + + ; test failed + fail: + mov rax, 60 + mov rdi, 1 + syscall diff --git a/Task/File-size/Zkl/file-size.zkl b/Task/File-size/Zkl/file-size.zkl new file mode 100644 index 0000000000..681e394ec1 --- /dev/null +++ b/Task/File-size/Zkl/file-size.zkl @@ -0,0 +1,2 @@ +File.info("input.txt").println(); +File.info("/input.txt").println(); diff --git a/Task/Filter/APL/filter.apl b/Task/Filter/APL/filter.apl new file mode 100644 index 0000000000..d9d2d14b69 --- /dev/null +++ b/Task/Filter/APL/filter.apl @@ -0,0 +1,2 @@ + (0=2|x)/x←⍳20 +2 4 6 8 10 12 14 16 18 20 diff --git a/Task/Filter/AppleScript/filter-3.applescript b/Task/Filter/AppleScript/filter-3.applescript index 787a8f04f2..29dc7975aa 100644 --- a/Task/Filter/AppleScript/filter-3.applescript +++ b/Task/Filter/AppleScript/filter-3.applescript @@ -1,30 +1,40 @@ -- filter :: (a -> Bool) -> [a] -> [a] --- filter :: (a -> Int -> Bool) -> [a] -> [a] --- filter :: (a -> Int -> [a] -> Bool) -> [a] -> [a] on filter(f, xs) - script mf - property lambda : f - end script - - set lst to {} - set lng to length of xs - repeat with i from 1 to lng - set v to item i of xs - if mf's lambda(v, i, xs) then - set end of lst to v - end if - end repeat - return lst + tell mReturn(f) + set lst to {} + set lng to length of xs + repeat with i from 1 to lng + set v to item i of xs + if |λ|(v, i, xs) then set end of lst to v + end repeat + return lst + end tell end filter - --- Ordinary AppleScript predicate function, rather than a script object +-- TEST ----------------------------------------------------------------------- -- isEven :: (a -> Bool) on isEven(x) x mod 2 = 0 end isEven -set lstRange to {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} +on run -filter(isEven, lstRange) + filter(isEven, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) + + -- {0, 2, 4, 6, 8, 10} +end run + +-- GENERIC FUNCTION ----------------------------------------------------------- + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn diff --git a/Task/Filter/Batch-File/filter.bat b/Task/Filter/Batch-File/filter.bat new file mode 100644 index 0000000000..68655c613c --- /dev/null +++ b/Task/Filter/Batch-File/filter.bat @@ -0,0 +1,58 @@ +@echo off +setlocal enabledelayedexpansion + +set numberarray=1 2 3 4 5 6 7 8 9 10 +for %%i in (%numberarray%) do ( + set /a tempcount+=1 + set numberarray!tempcount!=%%i +) + +echo Filtering all even numbers from numberarray into newarray... +call:filternew numberarray +echo numberarray - %numberarray% +echo newarray -%newarray% +echo. +echo Filtering numberarray so that only even entries remain... +call:filterdestroy numberarray +echo numberarray -%numberarray% +pause>nul +exit /b + +:filternew +set arrayname=%1 +call:arraylength %arrayname% +set tempcount=0 +for /l %%i in (1,1,%length%) do ( + set /a cond=!%arrayname%%%i! %% 2 + if !cond!==0 ( + set /a tempcount+=1 + set newarray!tempcount!=!%arrayname%%%i! + set newarray=!newarray! !%arrayname%%%i! + ) +) +exit /b + +:filterdestroy +set arrayname=%1 +call:arraylength %arrayname% +set tempcount=0 +set "%arrayname%=" +for /l %%i in (1,1,%length%) do ( + set /a cond=!%arrayname%%%i! %% 2 + if !cond!==0 ( + set /a tempcount+=1 + set %arrayname%!tempcount!=!%arrayname%%%i! + set %arrayname%=!%arrayname%! !%arrayname%%%i! + ) +) +exit /b + +:arraylength +set tempcount=0 +set lengthname=%1 +set length=0 +:lengthloop +set /a tempcount+=1 +if "!%lengthname%%tempcount%!"=="" exit /b +set /a length+=1 +goto lengthloop diff --git a/Task/Filter/Gambas/filter.gambas b/Task/Filter/Gambas/filter.gambas new file mode 100644 index 0000000000..82acfab84c --- /dev/null +++ b/Task/Filter/Gambas/filter.gambas @@ -0,0 +1,43 @@ +sRandom As New String[] +'______________________________________________________________________________________________________ +Public Sub Main() +Dim siCount As Short + +For siCount = 0 To 19 + sRandom.Add(Rand(1, 100)) +Next + +Print sRandom.join(",") + +NewArray +Destructive + +End +'______________________________________________________________________________________________________ +Public Sub NewArray() 'Select certain elements from an array into a new array in a generic way +Dim sEven As New String[] +Dim siCount As Short + +For siCount = 0 To sRandom.Max + If Even(sRandom[siCount]) Then sEven.Add(sRandom[siCount]) +Next + +Print sEven.join(",") + +End +'______________________________________________________________________________________________________ +Public Sub Destructive() 'Give a second solution which filters destructively +Dim siIndex As New Short[] +Dim siCount As Short + +For siCount = 0 To sRandom.Max + If Odd(sRandom[siCount]) Then siIndex.Add(siCount) +Next + +For siCount = siIndex.max DownTo 0 + sRandom.Extract(siIndex[siCount], 1) +Next + +Print sRandom.join(",") + +End diff --git a/Task/Filter/JavaScript/filter-5.js b/Task/Filter/JavaScript/filter-5.js new file mode 100644 index 0000000000..96613003b8 --- /dev/null +++ b/Task/Filter/JavaScript/filter-5.js @@ -0,0 +1,14 @@ +(() => { + 'use strict'; + + // isEven :: Int -> Bool + const isEven = n => n % 2 === 0; + + + // TEST + + return [1,2,3,4,5,6,7,8,9] + .filter(isEven); + + // [2, 4, 6, 8] +})(); diff --git a/Task/Filter/JavaScript/filter-6.js b/Task/Filter/JavaScript/filter-6.js new file mode 100644 index 0000000000..4fc043e9fd --- /dev/null +++ b/Task/Filter/JavaScript/filter-6.js @@ -0,0 +1 @@ +[2, 4, 6, 8] diff --git a/Task/Filter/jq/filter-1.jq b/Task/Filter/Jq/filter-1.jq similarity index 100% rename from Task/Filter/jq/filter-1.jq rename to Task/Filter/Jq/filter-1.jq diff --git a/Task/Filter/jq/filter-2.jq b/Task/Filter/Jq/filter-2.jq similarity index 100% rename from Task/Filter/jq/filter-2.jq rename to Task/Filter/Jq/filter-2.jq diff --git a/Task/Filter/Kotlin/filter.kotlin b/Task/Filter/Kotlin/filter.kotlin new file mode 100644 index 0000000000..88b189db6d --- /dev/null +++ b/Task/Filter/Kotlin/filter.kotlin @@ -0,0 +1,13 @@ +// version 1.0.5-2 + +fun main(args: Array) { + val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9) + println(array.joinToString(" ")) + + val filteredArray = array.filter{ it % 2 == 0 } + println(filteredArray.joinToString(" ")) + + val mutableList = array.toMutableList() + mutableList.retainAll { it % 2 == 0 } + println(mutableList.joinToString(" ")) +} diff --git a/Task/Filter/Maple/filter.maple b/Task/Filter/Maple/filter.maple new file mode 100644 index 0000000000..25b1bdb095 --- /dev/null +++ b/Task/Filter/Maple/filter.maple @@ -0,0 +1,3 @@ +evennum:=proc(nums::list(integer)) + return select(x->type(x, even), nums); +end proc; diff --git a/Task/Filter/OoRexx/filter.rexx b/Task/Filter/OoRexx/filter.rexx new file mode 100644 index 0000000000..53ee52ef8e --- /dev/null +++ b/Task/Filter/OoRexx/filter.rexx @@ -0,0 +1,31 @@ + Call random ,,1234567 + a=.array~new + b=.array~new + Do i=1 To 10 + a[i]=random(1,9999) + End + Say 'Unfiltered values:' a~makestring(line,' ') + /* copy even numbers to array b */ + j=0 + Do i=1 to 10 + If filter(a[i]) Then Do + j = j + 1 + b[j]=a[i] + End + end + Say 'Filtered values (in second array): ' b~makestring(line,' ') + /* destructive filtering: copy within array a */ + j=0 + Do i=1 to 10 + If filter(a[i]) Then Do + j = j + 1 + a[j]=a[i] + End + end + /* destructive filtering: delete the remaining elements */ + Do i=10 To j+1 By -1 + a~delete(i) + End + Say 'Filtered values (destructive filtering):' a~makestring(line,' ') + Exit + filter: Return arg(1)//2=0 diff --git a/Task/Filter/Protium/filter.protium b/Task/Filter/Protium/filter.protium deleted file mode 100644 index 1117fe8188..0000000000 --- a/Task/Filter/Protium/filter.protium +++ /dev/null @@ -1,8 +0,0 @@ -<@ LETCNWLSTLIT>numbers|1 2 3 4 5 6 7 8 9 10 11 12 -<@ DEFLST>evens -<@ ENULSTLIT>numbers| -<@ TSTEVEELTLST>... -<@ IFF> -<@ LETLSTELTLST>evens|... - - diff --git a/Task/Filter/Ruby/filter-2.rb b/Task/Filter/Ruby/filter-2.rb index 52e014d743..95e764511f 100644 --- a/Task/Filter/Ruby/filter-2.rb +++ b/Task/Filter/Ruby/filter-2.rb @@ -1,9 +1,3 @@ -# Integer#even? is new to Ruby 1.8.7. -# Define it for older Ruby. -unless Integer.method_defined? :even? - class Integer - def even? - self % 2 == 0 - end - end -end +ary = [1, 2, 3, 4, 5, 6] +ary.select! {|elem| elem.even?} +p ary # => [2, 4, 6] diff --git a/Task/Filter/Ruby/filter-3.rb b/Task/Filter/Ruby/filter-3.rb deleted file mode 100644 index 95e764511f..0000000000 --- a/Task/Filter/Ruby/filter-3.rb +++ /dev/null @@ -1,3 +0,0 @@ -ary = [1, 2, 3, 4, 5, 6] -ary.select! {|elem| elem.even?} -p ary # => [2, 4, 6] diff --git a/Task/Filter/Ruby/filter-4.rb b/Task/Filter/Ruby/filter-4.rb deleted file mode 100644 index 4415c3bd0d..0000000000 --- a/Task/Filter/Ruby/filter-4.rb +++ /dev/null @@ -1,11 +0,0 @@ -# Array#select! is new to Ruby 1.9.2. -# Define it for older Ruby. -unless Array.method_defined? :select! - class Array - def select! - enum_for(:select!) unless block_given? - delete_if { |elem| not yield elem } - self - end - end -end diff --git a/Task/Filter/Standard-ML/filter.ml b/Task/Filter/Standard-ML/filter.ml deleted file mode 100644 index 2954747bb1..0000000000 --- a/Task/Filter/Standard-ML/filter.ml +++ /dev/null @@ -1,2 +0,0 @@ -val ary = [1,2,3,4,5,6]; -List.filter (fn x => x mod 2 = 0) ary diff --git a/Task/Filter/Stata/filter.stata b/Task/Filter/Stata/filter.stata new file mode 100644 index 0000000000..195272c8c0 --- /dev/null +++ b/Task/Filter/Stata/filter.stata @@ -0,0 +1,9 @@ +mata +a=2,9,4,7,5,3,6,1,8 + +// Select even elements of a +select(a,mod(a,2):==0) + +// Select the indices of even elements of a +selectindex(mod(a,2):==0) +end diff --git a/Task/Filter/Zkl/filter.zkl b/Task/Filter/Zkl/filter.zkl new file mode 100644 index 0000000000..aada09985a --- /dev/null +++ b/Task/Filter/Zkl/filter.zkl @@ -0,0 +1,3 @@ +T(1,4,9,16,25,36,"37",49,64,81,100, True,self) + .filter(fcn(n){(0).isType(n) and n.isOdd}) +//-->L(1,9,25,49,81) diff --git a/Task/Find-common-directory-path/Batch-File/find-common-directory-path.bat b/Task/Find-common-directory-path/Batch-File/find-common-directory-path.bat new file mode 100644 index 0000000000..387da03f74 --- /dev/null +++ b/Task/Find-common-directory-path/Batch-File/find-common-directory-path.bat @@ -0,0 +1,61 @@ +@echo off +setlocal enabledelayedexpansion + +call:commonpath /home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members +pause>nul +exit /b + +:commonpath +setlocal enabledelayedexpansion + +for %%i in (%*) do ( + set /a args+=1 + set arg!args!=%%i + set fullarg!args!=%%i +) +for /l %%i in (1,1,%args%) do set fullarg%%i=!fullarg%%i:/= ! + +for /l %%i in (1,1,%args%) do ( + set tempcount=0 + for %%j in (!fullarg%%i!) do ( + set /a tempcount+=1 + set arg%%it!tempcount!=%%j + set arg%%itokencount=!tempcount! + ) +) + +set mintokencount=%arg1tokencount% +set leasttokens=1 +for /l %%i in (1,1,%args%) do ( + set currenttokencount=!arg%%itokencount! + if !currenttokencount! lss !mintokencount! ( + set mintokencount=!currenttokencount! + set leasttokens=%%i + ) +) + +for /l %%i in (1,1,%mintokencount%) do set commonpath%%i=!arg%leasttokens%t%%i! + +for /l %%i in (1,1,%mintokencount%) do ( + for /l %%j in (1,1,%args%) do ( + set currentpath=!arg%%jt%%i! + if !currentpath!==!commonpath%%i! set pathtokens%%j=%%i + ) +) + +set minpathtokens=%pathtokens1% +set leastpathtokens=1 +for /l %%i in (1,1,%args%) do ( + set currentpathtokencount=!pathtokens%%i! + if !currentpathtokencount! lss !minpathtokens! ( + set minpathtokencount=!currentpathtokencount! + set leastpathtokens=%%i + ) +) + +set commonpath=/ +for /l %%i in (1,1,!pathtokens%leastpathtokens%!) do set commonpath=!commonpath!!arg%leastpathtokens%t%%i!/ +echo %commonpath% + +endlocal +exit /b diff --git a/Task/Find-common-directory-path/Gambas/find-common-directory-path.gambas b/Task/Find-common-directory-path/Gambas/find-common-directory-path.gambas new file mode 100644 index 0000000000..608fb180bb --- /dev/null +++ b/Task/Find-common-directory-path/Gambas/find-common-directory-path.gambas @@ -0,0 +1,17 @@ +Public Sub Main() +Dim sFolder As String[] = ["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"] +Dim sSame As String +Dim siCount As Short = 1 + +Do + If Mid(sFolder[0], siCount, 1) = Mid(sFolder[1], siCount, 1) And Mid(sFolder[0], siCount, 1) = Mid(sFolder[2], siCount, 1) Then + sSame &= Mid(sFolder[0], siCount, 1) + Else + Break + End If + Inc siCount +Loop + +Print Mid(sSame, 1, RInStr(sSame, "/") - 1) + +End diff --git a/Task/Find-common-directory-path/jq/find-common-directory-path-1.jq b/Task/Find-common-directory-path/Jq/find-common-directory-path-1.jq similarity index 100% rename from Task/Find-common-directory-path/jq/find-common-directory-path-1.jq rename to Task/Find-common-directory-path/Jq/find-common-directory-path-1.jq diff --git a/Task/Find-common-directory-path/jq/find-common-directory-path-2.jq b/Task/Find-common-directory-path/Jq/find-common-directory-path-2.jq similarity index 100% rename from Task/Find-common-directory-path/jq/find-common-directory-path-2.jq rename to Task/Find-common-directory-path/Jq/find-common-directory-path-2.jq diff --git a/Task/Find-common-directory-path/Maple/find-common-directory-path.maple b/Task/Find-common-directory-path/Maple/find-common-directory-path.maple new file mode 100644 index 0000000000..908c327ec0 --- /dev/null +++ b/Task/Find-common-directory-path/Maple/find-common-directory-path.maple @@ -0,0 +1,9 @@ +dirpath:=proc(a,b,c) + local dirtemp,dirnew,x; + use StringTools in + dirtemp:=LongestCommonSubString(c, LongestCommonSubString(a,b)); + x:=FirstFromRight("/",dirtemp); + dirnew:=dirtemp[1..x]; + return dirnew; + end use; +end proc; diff --git a/Task/Find-common-directory-path/Phix/find-common-directory-path.phix b/Task/Find-common-directory-path/Phix/find-common-directory-path.phix new file mode 100644 index 0000000000..68c871fdea --- /dev/null +++ b/Task/Find-common-directory-path/Phix/find-common-directory-path.phix @@ -0,0 +1,22 @@ +function common_directory_path(sequence paths, integer sep='/') +sequence res = {} + if length(paths) then + res = split(paths[1],sep)[1..-2] + for i=2 to length(paths) do + sequence pi = split(paths[i],sep)[1..-2] + for j=1 to length(res) do + if j>length(pi) or res[j]!=pi[j] then + res = res[1..j-1] + exit + end if + end for + if length(res)=0 then exit end if + end for + end if + return join(res,sep) +end function + +constant test = {"/home/user1/tmp/coverage/test", + "/home/user1/tmp/covert/operator", + "/home/user1/tmp/coven/members"} +?common_directory_path(test) diff --git a/Task/Find-common-directory-path/Ring/find-common-directory-path.ring b/Task/Find-common-directory-path/Ring/find-common-directory-path.ring new file mode 100644 index 0000000000..4f2fb20500 --- /dev/null +++ b/Task/Find-common-directory-path/Ring/find-common-directory-path.ring @@ -0,0 +1,26 @@ +# Project : Find common directory path +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "stdlib.ring" +i = null +o = null +path = list(3) + +path[1] = "/home/user1/tmp/coverage/test" +path[2] = "/home/user1/tmp/covert/operator" +path[3] = "/home/user1/tmp/coven/members" + +see commonpath(path, "/") + +func commonpath(p, s) +while i != 0 + o = i + i = substring(p[1], s, i+1) + for j = 2 to len(p) + if left(p[1], i) != left(p[j], i) + exit 2 + ok + next +end +return left(p[1], o-1) diff --git a/Task/Find-common-directory-path/Swift/find-common-directory-path.swift b/Task/Find-common-directory-path/Swift/find-common-directory-path.swift new file mode 100644 index 0000000000..22d0a0199a --- /dev/null +++ b/Task/Find-common-directory-path/Swift/find-common-directory-path.swift @@ -0,0 +1,17 @@ +import Foundation + + +func getPrefix(_ text:[String]) -> String? { + var common:String = text[0] + for i in text { + common = i.commonPrefix(with: common) + } + return common +} + +var test = ["/home/user1/tmp/coverage/test", + "/home/user1/tmp/covert/operator", + "/home/user1/tmp/coven/members"] + +var output:String = getPrefix(test)! +print(output) diff --git a/Task/Find-common-directory-path/Zkl/find-common-directory-path.zkl b/Task/Find-common-directory-path/Zkl/find-common-directory-path.zkl new file mode 100644 index 0000000000..2c52b3861d --- /dev/null +++ b/Task/Find-common-directory-path/Zkl/find-common-directory-path.zkl @@ -0,0 +1,5 @@ +dirs:=T("/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", + "/home/user1/tmp/coven/members"); +n:=Utils.zipWith('==,dirs.xplode()).find(False); // character pos which differs +n=dirs[0][0,n].rfind("/"); // find last "/" +dirs[0][0,n]; diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-1.f b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-1.f new file mode 100644 index 0000000000..d326e85bac --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-1.f @@ -0,0 +1,82 @@ + USE PRIMEBAG !Gain access to NEXTPRIME and ISPRIME. +Calculates the largest "left-truncatable" digit sequence that is a prime number, in various bases. + INTEGER LBASE,MANY,ENUFF !Some sizes. + PARAMETER (LBASE = 13, MANY = 66666, ENUFF = 66) + INTEGER NS,START(LBASE) !A list of single-digit prime numbers for starters. + INTEGER NH,LH !Counters for the horde. + INTEGER N,HORDEN(MANY) !Numerical value of a digit sequence. + INTEGER*1 HORDED(ENUFF,MANY) !Single-digit values only. + INTEGER B,D,DB !The base, a digit, some power of the base. + INTEGER L !The length of the digit sequence: DB = B**L. + INTEGER P !Possibly a prime number. + INTEGER I !A stepper. + + MSG = 6 !I/O unit number for "standard output". + IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file!" !Attempt in hope. + NS = 0 !No starters. + P = 1 !Start looking for some primes. + 1 P = NEXTPRIME(P) !Thus skipping non-primes. + IF (P.LE.LBASE) THEN !Beyond the limit? + NS = NS + 1 !No. Count another starter. + START(NS) = P !Save its value. + GO TO 1 !And seek further. + END IF !One could insted prepare some values, the primes being well-known. + WRITE (MSG,2) LBASE,NS,START(1:NS) !But, parameterisation is easy enough. + 2 FORMAT ("Working in bases 3 to ",I0," there are ",I0, !Announce the known. + * " single-digit primes: ",666(I0:", ")) !The : sez stop if the list is exhausted. + WRITE (MSG,3) !Produce a heading for the tabular output. + 3 FORMAT (/"Base Digits Count Max. Value = (in base)") + + 10 DO B = 3,LBASE !Work through the bases. + NH = 0 !The horde is empty. + DO I = 1,NS !Prepare the starters for base B. + IF (START(I).GE.B) EXIT !Like, they're single-digits in base B. + NH = NH + 1 !So, count another in. + HORDEN(NH) = START(I) !Its numerical value. + HORDED(1,NH) = START(I) !Its digits. Just one. + END DO !On to the next single-digit prime number. + L = 0 !Syncopation. The length of the digit sequences. + DB = 1 !The power for the incoming digit. + + 20 L = L + 1 !We're about to add another digit. + IF (L.GE.ENUFF) STOP "Too many digits!" !Hopefully, there's room. + DB = DB*B !The new power of B. + IF (DB.LE.0) GO TO 29 !Integer overflow? + LH = NH !The live ones, awaiting extension. + DO I = 1,LH !Step through each starter. + N = HORDEN(I) !Grab its numerical value. + DO D = 1,B - 1 !Consider all possible lead digits. + P = D*DB + N !Place it at the start of the number. + IF (P.LE.0) GO TO 29 !Oh for IF OVERFLOW ... + IF (ISPRIME(P)) THEN !And if it is a prime, + IF (NH.GE.MANY) STOP "Too many sequences!" !Add a sequence. + NH = NH + 1 !Count in a survivor. + HORDEN(NH) = P !The numerical value. + HORDED(1:L,NH) = HORDED(1:L,I) !The digits. + HORDED(L + 1,NH) = D !Plus the added high-order digit. + END IF !So much for persistent primality. + END DO !On to the next lead digit. + END DO !On to the next starter. + + N = NH - LH !The number of entries added to the horde. + IF (N.GT.0) THEN !Were there any? + DO I = 1,MIN(LH,N) !Yes. Overwrite the starters. + HORDEN(I) = HORDEN(NH) !From the tail end of the horde. + HORDED(1:L + 1,I) = HORDED(1:L + 1,NH) !Digit sequences as well. + NH = NH - 1 !One snipped off. + END DO !Thus fill the gap at the start. + NH = N !The new horde count. + LH = NH !All are starters for the next level. + GO TO 20 !See how it goes. + END IF !So much for further progress. + GO TO 30 !But if none, done. + 29 WRITE (MSG,28) B,L,NH,DB,P !Curses. Offer some details. + 28 FORMAT (I4,I7,I6,28X,"Integer overflow!",2I12) + CYCLE !Or, GO TO the end of the loop. + + 30 I = MAXLOC(HORDEN(1:NH),DIM = 1) !Finger the mostest number. + WRITE (MSG,31) B,L,NH,HORDEN(I),HORDED(L:1:-1,I) !Results! + 31 FORMAT (I4,I7,I6,I11," = "666(I0:".")) !See Format 3. + + END DO !On to the next base. + END !Simple enough. diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-2.f b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-2.f new file mode 100644 index 0000000000..46f28aeb60 --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-2.f @@ -0,0 +1,10 @@ + MODULE BIGNUMBERVB !Limited services: integers, no negative numbers, variable base possible. + INTEGER BIGORDER !A limited attempt at generality. + PARAMETER (BIGORDER = 1) !This is the order of the base of the big number arithmetic. + INTEGER BIGBASE,BIGLIMIT !Sized thusly. +c PARAMETER (BIGBASE = 10**BIGORDER, BIGLIMIT = 8888/BIGORDER) !Enough? + PARAMETER (BIGLIMIT = 666) + TYPE BIGNUM !So, a big number is simple. + INTEGER LAST !This many digits (of size BIGBASE) are in use. + INTEGER DIGIT(BIGLIMIT) !The digits, in ascending power order. + END TYPE BIGNUM !So much for that. diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-3.f b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-3.f new file mode 100644 index 0000000000..66152baab5 --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-3.f @@ -0,0 +1 @@ + IF (MOD(BIGBASE,10).NE.0) STOP "BIGTASTE expects powers of 10" !Alas. Otherwise the "E" formalism fails. diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-4.f b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-4.f new file mode 100644 index 0000000000..d2564bdf2c --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-4.f @@ -0,0 +1,28 @@ + SUBROUTINE BIGWRITE(F,B) !Show B. + INTEGER F !I/O unit number. + TYPE(BIGNUM) B !The number. + WRITE (F,1,ADVANCE="NO") B.DIGIT(B.LAST:1:-1) !Roll the digits in base BIGBASE. + 1 FORMAT (666(I0:".")) !Not bothering with using letters for digits above nine. + END SUBROUTINE BIGWRITE !Simple, but messy. + + SUBROUTINE BIGTEN(B,TEXT) !Produce a base ten digit string. + TYPE(BIGNUM) B !The number. + CHARACTER*(*) TEXT !The digits. + TYPE(BIGNUM) N !A copy I can mess with. + INTEGER L,D !Assistants. + N.LAST = B.LAST !So, make my copy. + N.DIGIT(1:N.LAST) = B.DIGIT(1:B.LAST) !Only the live digits are wanted. + TEXT = "" !Clear for action. + L = LEN(TEXT) !Find the far end. + 10 D = BIGDIVRN(N,10) !Digits emerge from the low-order end of the number. + TEXT(L:L) = CHAR(ICHAR("0") + D) !Convert a digit to text, usual assumptions. + IF (N.LAST.EQ.1 .AND. N.DIGIT(1).EQ.0) RETURN !If zero, N is finished. + L = L - 1 !Otherwise, another digits will emerge. + IF (L.GT.0) GO TO 10 !If there is space, go for it. + TEXT(1:1) = "!" !Otherwise, signify overflow. + END SUBROUTINE BIGTEN !No negatives, so no sign is needed. + + LOGICAL FUNCTION BIGISPRIME(B) !Ad-hoc report. + TYPE(BIGNUM) B !The number. + BIGISPRIME = ABS(BIGFACTOR(B,2800)).EQ.1 !Condensed report. + END FUNCTION BIGISPRIME !Can't be bothered with ISPRIME from PRIMEBAG. diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-5.f b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-5.f new file mode 100644 index 0000000000..8a367e2ed0 --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-5.f @@ -0,0 +1,11 @@ +Catch some annoying cases, to protect the direct tests for divisibility by two and three... + IF (N.LAST.LE.2) THEN !A smallish number? I want to compare to four, but BIGBASE might be two. + NR = BIGVALUE(N) !Surely so. + IF (NR.LE.4) THEN !Some special values are known. + BIGMRPRIME = NR.GE.2 .AND. NR.LE.3 !Like, the neighbours. + RETURN !Thus allow 2 to be reported as prime. + END IF !Yet, test for 2 as a possible factor for larger numbers. + END IF !Without struggling over SQRT and suchlike. + BIGMRPRIME = .FALSE. !Most numbers are not primes. + IF (BIGMOD2(N).EQ.0) RETURN !A single expression using .OR. risks always evaluating BOTH parts, damnit, + IF (BIGMODN(N,3).EQ.0) RETURN !Even for even numbers. Possibly doing so "in parallel" is no consolation. diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-6.f b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-6.f new file mode 100644 index 0000000000..466bd1da8e --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Fortran/find-largest-left-truncatable-prime-in-a-given-base-6.f @@ -0,0 +1,91 @@ + USE PRIMEBAG !Gain access to NEXTPRIME and ISPRIME. + USE BIGNUMBERVB !Alas, INTEGER*600 is not available. +Calculates the largest "left-truncatable" digit sequence that is a prime number, in various bases. + INTEGER LBASE,MANY !Some sizes. + PARAMETER (LBASE = 17, MANY = 66666) + INTEGER NS,START(LBASE) !A list of single-digit prime numbers for starters. + TYPE(BIGNUM) HORDE(MANY) !A collection. + INTEGER N,NH,LH !Counters for the horde. + INTEGER L !The length of the digit sequence. + INTEGER I,D !Steppers. + CHARACTER*42 TEXT !A scratchpad, for decimal values. + REAL T0,T1 !In memory of lost time. + + MSG = 6 !I/O unit number for "standard output". + IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file!" !Attempt in hope. + NS = 0 !No starters. + N = 1 !Start looking for some primes. + 1 N = NEXTPRIME(N) !Thus skipping non-primes. + IF (N.LE.LBASE) THEN !Beyond the limit? + NS = NS + 1 !No. Count another starter. + START(NS) = N !Save its value. + GO TO 1 !And seek further. + END IF !One could insted prepare some values, the primes being well-known. + WRITE (MSG,2) LBASE,NS,START(1:NS) !But, parameterisation is easy enough. + 2 FORMAT ("Working in bases 3 to ",I0," there are ",I0, !Announce the known. + * " single-digit primes: ",666(I0:", ")) !The : sez stop if the list is exhausted. + WRITE (MSG,3) !Produce a heading for the tabular output. + 3 FORMAT (/"Base Digits Count",29X," Maximum Value = (in base)") !See Format 31. + +Chug through the various bases to be used for the numerology. + CALL CPU_TIME(T0) !Start the timing. + 10 DO BIGBASE = 3,LBASE !Not really very BIG bases. + NH = 0 !The horde is empty. + DO I = 1,NS !Prepare the starters for base BIGBASE. + IF (START(I).GE.BIGBASE) EXIT !Like, they're single-digits in base BIGBASE which may exceed ten... + NH = NH + 1 !So, count another in. + HORDE(NH).DIGIT(1) = START(I) !Its numerical value. + HORDE(NH).LAST = 1 !Its digit count. Just one. + END DO !On to the next single-digit prime number in BIGBASE. + L = 1 !The numbers all have one digit. +Consider each starter for extension via another high-order digit, to be placed at DIGIT(L + 1). + 20 L = L + 1 !We're about to add another digit, now at DIGIT(L). + IF (L.GT.BIGLIMIT) STOP "Too many digits!" !Hopefully, there's room. + HORDE(1:NH).LAST = L !There is. Advise the BIGNUM horde of this. + LH = NH !The live ones, awaiting extension. + DO I = 1,LH !Step through each starter. + DO D = 1,BIGBASE - 1 !Consider all possible lead digits. + HORDE(I).DIGIT(L) = D !Place it at the start of the number. + IF (BIGISPRIME(HORDE(I))) THEN !And if it is a prime, or seems likely to be ... + IF (NH.GE.MANY) STOP "Too many sequences!" !Add a sequence. + NH = NH + 1 !Count in a survivor. + HORDE(NH).LAST = L !Its digit count. + HORDE(NH).DIGIT(1:L) = HORDE(I).DIGIT(1:L) !Its digits. + END IF !So much for persistent primality. + END DO !On to the next lead digit. + END DO !On to the next starter. +Check for added entries and compact the collection if there are some. + N = NH - LH !The number of entries added to the horde. + IF (N.GT.0) THEN !Were there any? + DO I = 1,MIN(LH,N) !Yes. Overwrite the starters. + HORDE(I).LAST = HORDE(NH).LAST !From the tail end of the horde. + HORDE(I).DIGIT(1:L) = HORDE(NH).DIGIT(1:L) !Copying only the live digits. + NH = NH - 1 !One snipped off. + END DO !Thus fill the gap at the start. + NH = N !The new horde count. + GO TO 20 !See how it goes. + END IF !So much for further progress. +Cast forth the mostest of the starters. + 30 HORDE(1:NH).LAST = L - 1 !The testing involved an extra digit, which was not accepted. + L = 1 !Now go looking for the mostest of the survivors. + DO I = 2,NH !By comparing all the rest. + IF (BIGSIGN(HORDE(L),HORDE(I)).LT.0) L = I !Consider A - B. + END DO !On to the next. + CALL BIGTEN(HORDE(L),TEXT) !Get a decimal digit string. + WRITE (MSG,31) BIGBASE,HORDE(L).LAST,NH,TEXT !Some auxiliary details. + 31 FORMAT (I4,I7,I6,1X,A," = ",$) !See Format 3. + CALL BIGWRITE(MSG,HORDE(L)) !The number at last! + WRITE (MSG,*) !Finish the line. + END DO !On to the next base. + CALL CPU_TIME(T1) !Completed the run. + +Closedown. + 200 WRITE (MSG,201) !First, some statistics. + 201 FORMAT (/,"The MR prime test makes a series of trials, " + 1 "stopping early",/'only when a "definitely composite" ', + 2 "result is encountered.") + WRITE (MSG,202) "Trial",(I,I = 1,BIGMRTRIALS) !Roll the trial number. + WRITE (MSG,202) "Count",BIGMRCOUNT !Now the counts. + 202 FORMAT (A6,": ",666I8) !This should do. + WRITE (MSG,*) "CPU time:",T1 - T0 !The cost. + END !Simple enough. diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Kotlin/find-largest-left-truncatable-prime-in-a-given-base.kotlin b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Kotlin/find-largest-left-truncatable-prime-in-a-given-base.kotlin new file mode 100644 index 0000000000..7cd09c9363 --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Kotlin/find-largest-left-truncatable-prime-in-a-given-base.kotlin @@ -0,0 +1,41 @@ +// version 1.1.2 + +import java.math.BigInteger + +fun nextLeftTruncatablePrimes(n: BigInteger, radix: Int, certainty: Int): List { + val probablePrimes = mutableListOf() + val baseString = if (n == BigInteger.ZERO) "" else n.toString(radix) + for (i in 1 until radix) { + val p = BigInteger(i.toString(radix) + baseString, radix) + if (p.isProbablePrime(certainty)) probablePrimes.add(p) + } + return probablePrimes +} + +fun largestLeftTruncatablePrime(radix: Int, certainty: Int): BigInteger? { + var lastList: List? = null + var list = nextLeftTruncatablePrimes(BigInteger.ZERO, radix, certainty) + while (!list.isEmpty()) { + lastList = list + list = mutableListOf() + for (n in lastList) list.addAll(nextLeftTruncatablePrimes(n, radix, certainty)) + } + if (lastList == null) return null + return lastList.sorted().last() +} + +fun main(args: Array) { + print("Enter maximum radix : ") + val maxRadix = readLine()!!.toInt() + print("Enter certainty : ") + val certainty = readLine()!!.toInt() + println() + for (radix in 3..maxRadix) { + val largest = largestLeftTruncatablePrime(radix, certainty) + print("Base = ${"%-2d".format(radix)} : ") + if (largest == null) + println("No left truncatable prime") + else + println("${largest.toString().padEnd(35)} -> ${largest.toString(radix)}") + } +} diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Perl-6/find-largest-left-truncatable-prime-in-a-given-base.pl6 b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Perl-6/find-largest-left-truncatable-prime-in-a-given-base.pl6 index 315e70e311..47d4195da4 100644 --- a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Perl-6/find-largest-left-truncatable-prime-in-a-given-base.pl6 +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Perl-6/find-largest-left-truncatable-prime-in-a-given-base.pl6 @@ -1,40 +1,19 @@ -for 3..* -> $base { +for 3 .. * -> $base { say "Starting base $base..."; - my @stems = grep { is-prime($_, 100)}, ^$base; - my @runoff; + my @stems = grep { .is-prime }, ^$base; for 1 .. * -> $digits { - print ' ', @stems.elems; - my @new; - my $place = $base ** $digits; - my $tries = 1; - for @stems -> $stem { - for 1 ..^ $base -> $digit { - my $new = $digit * $place + $stem; - @new.push($new) if is-prime($new, $tries); + print ' ', @stems.elems; + my @new; + my $place = $base ** $digits; + for 1 ..^ $base -> $digit { + my $left = $digit * $place; + for @stems -> $stem { + my $new = $left + $stem; + @new.push($new) if $new.is-prime; + } } - } - last unless @new; - push @runoff, @stems if @new < @stems and @new < 100; - @stems = @new; - } - push @runoff, @stems; - say "\n Finalists: ", +@runoff; - - for @runoff.sort(-*) -> $finalist { - my $b = $finalist.base($base); - say " Checking :$base\<", $b, '>'; - my $ok = True; - for $base ** 2, $base ** 3, $base ** 4 ... $base ** $b.chars -> $place { - my $f = $finalist % $place; - if not is-prime($f, 100) { - say " Oops, :$base\<", $f.base($base), '> is not a prime!!!'; - $ok = False; - last; - } - } - next unless $ok; - - say " Largest ltp in base $base = $finalist"; - last; + last unless @new; + @stems = @new; } + say "\nLargest ltp in base $base = { @stems.tail } or :$base\<{@stems.tail.base($base)}>\n"; } diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Sidef/find-largest-left-truncatable-prime-in-a-given-base.sidef b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Sidef/find-largest-left-truncatable-prime-in-a-given-base.sidef index e19120dbf7..01285703ef 100644 --- a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Sidef/find-largest-left-truncatable-prime-in-a-given-base.sidef +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Sidef/find-largest-left-truncatable-prime-in-a-given-base.sidef @@ -4,8 +4,7 @@ func primes(n) { loop { i = j.next_prime i <= n || break - take(i) - j = i + take(j = i) } } } @@ -14,20 +13,18 @@ func lltp(n) { var b = 1 var best = nil var v = primes(n-1) - +  while (v) { best = v.max b *= n - v = gather { - v.each { |vi| - take((n-1).of { |i| i*b + vi }.grep{.is_prime}...) - } + v.map! { |vi| + {|i| i*b + vi }.map(1..^n).grep{.is_prime}... } } - +  return best } for i in (3..17) { - printf("%2d %s\n", i, lltp(i)) + printf("%2d %s\n", i, lltp(i)) } diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Zkl/find-largest-left-truncatable-prime-in-a-given-base.zkl b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Zkl/find-largest-left-truncatable-prime-in-a-given-base.zkl new file mode 100644 index 0000000000..90883071e3 --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Zkl/find-largest-left-truncatable-prime-in-a-given-base.zkl @@ -0,0 +1,19 @@ +var [const] BN=Import("zklBigNum"); // libGMP +fcn largest_lefty_prime(base){ + primes,p:=List(),BN(1); while(p.nextPrime()biggest) biggest=z; + } + } + primes=ps; // the number of lists is small + } + biggest +} + +foreach n in ([3..17]){ println("%2d %s".fmt(n,largest_lefty_prime(n))) } diff --git a/Task/Find-limit-of-recursion/BASIC/find-limit-of-recursion-2.basic b/Task/Find-limit-of-recursion/BASIC/find-limit-of-recursion-2.basic index 2bd41e4da2..e468d1cc30 100644 --- a/Task/Find-limit-of-recursion/BASIC/find-limit-of-recursion-2.basic +++ b/Task/Find-limit-of-recursion/BASIC/find-limit-of-recursion-2.basic @@ -1,6 +1,8 @@ -10 LET d=0: REM depth -100 PRINT AT 1,1; "Recursion depth: ";d -110 LET d=d+1 -120 GO SUB 100: REM recursion -130 RETURN: REM this is never reached -200 STOP +' Recursion limit +FUNCTION recurse(i) + PRINT i + extraneous = recurse(i+1) + RETURN 0 +END FUNCTION + +extraneous = recurse(0) diff --git a/Task/Find-limit-of-recursion/BASIC/find-limit-of-recursion-3.basic b/Task/Find-limit-of-recursion/BASIC/find-limit-of-recursion-3.basic new file mode 100644 index 0000000000..a5af5197ed --- /dev/null +++ b/Task/Find-limit-of-recursion/BASIC/find-limit-of-recursion-3.basic @@ -0,0 +1,5 @@ +10 LET D=0 +20 GOSUB 30 +30 PRINT AT 0,0;D +40 LET D=D+1 +50 GOSUB 30 diff --git a/Task/Find-limit-of-recursion/BASIC/find-limit-of-recursion-4.basic b/Task/Find-limit-of-recursion/BASIC/find-limit-of-recursion-4.basic new file mode 100644 index 0000000000..2bd41e4da2 --- /dev/null +++ b/Task/Find-limit-of-recursion/BASIC/find-limit-of-recursion-4.basic @@ -0,0 +1,6 @@ +10 LET d=0: REM depth +100 PRINT AT 1,1; "Recursion depth: ";d +110 LET d=d+1 +120 GO SUB 100: REM recursion +130 RETURN: REM this is never reached +200 STOP diff --git a/Task/Find-limit-of-recursion/C++/find-limit-of-recursion.cpp b/Task/Find-limit-of-recursion/C++/find-limit-of-recursion.cpp new file mode 100644 index 0000000000..192d5c1e88 --- /dev/null +++ b/Task/Find-limit-of-recursion/C++/find-limit-of-recursion.cpp @@ -0,0 +1,12 @@ +#include + +void recurse(unsigned int i) +{ + std::cout< 0 ? recurse(n-1) : 'ok') +print "try recurse ", try +print recurse(try) +reread diff --git a/Task/Find-limit-of-recursion/Haskell/find-limit-of-recursion-1.hs b/Task/Find-limit-of-recursion/Haskell/find-limit-of-recursion-1.hs new file mode 100644 index 0000000000..ecc63a96df --- /dev/null +++ b/Task/Find-limit-of-recursion/Haskell/find-limit-of-recursion-1.hs @@ -0,0 +1,7 @@ +import Debug.Trace (trace) + +recurse :: Int -> Int +recurse n = trace (show n) recurse (succ n) + +main :: IO () +main = print $ recurse 1 diff --git a/Task/Find-limit-of-recursion/Haskell/find-limit-of-recursion-2.hs b/Task/Find-limit-of-recursion/Haskell/find-limit-of-recursion-2.hs new file mode 100644 index 0000000000..b627e0578c --- /dev/null +++ b/Task/Find-limit-of-recursion/Haskell/find-limit-of-recursion-2.hs @@ -0,0 +1,8 @@ +import Debug.Trace (trace) +import Data.Function (fix) + +recurse :: Int -> Int +recurse = fix ((<*> succ) . flip (trace . show)) + +main :: IO () +main = print $ recurse 1 diff --git a/Task/Find-limit-of-recursion/Haskell/find-limit-of-recursion-3.hs b/Task/Find-limit-of-recursion/Haskell/find-limit-of-recursion-3.hs new file mode 100644 index 0000000000..b49280351f --- /dev/null +++ b/Task/Find-limit-of-recursion/Haskell/find-limit-of-recursion-3.hs @@ -0,0 +1,9 @@ +import Debug.Trace (trace) + +testToDepth :: Int -> Int -> Int +testToDepth max n + | n >= max = max + | otherwise = trace (show n) testToDepth max (succ n) + +main :: IO () +main = print $ testToDepth 1000000 1 diff --git a/Task/Find-limit-of-recursion/jq/find-limit-of-recursion-1.jq b/Task/Find-limit-of-recursion/Jq/find-limit-of-recursion-1.jq similarity index 100% rename from Task/Find-limit-of-recursion/jq/find-limit-of-recursion-1.jq rename to Task/Find-limit-of-recursion/Jq/find-limit-of-recursion-1.jq diff --git a/Task/Find-limit-of-recursion/jq/find-limit-of-recursion-2.jq b/Task/Find-limit-of-recursion/Jq/find-limit-of-recursion-2.jq similarity index 100% rename from Task/Find-limit-of-recursion/jq/find-limit-of-recursion-2.jq rename to Task/Find-limit-of-recursion/Jq/find-limit-of-recursion-2.jq diff --git a/Task/Find-limit-of-recursion/jq/find-limit-of-recursion-3.jq b/Task/Find-limit-of-recursion/Jq/find-limit-of-recursion-3.jq similarity index 100% rename from Task/Find-limit-of-recursion/jq/find-limit-of-recursion-3.jq rename to Task/Find-limit-of-recursion/Jq/find-limit-of-recursion-3.jq diff --git a/Task/Find-limit-of-recursion/jq/find-limit-of-recursion-4.jq b/Task/Find-limit-of-recursion/Jq/find-limit-of-recursion-4.jq similarity index 100% rename from Task/Find-limit-of-recursion/jq/find-limit-of-recursion-4.jq rename to Task/Find-limit-of-recursion/Jq/find-limit-of-recursion-4.jq diff --git a/Task/Find-limit-of-recursion/jq/find-limit-of-recursion-5.jq b/Task/Find-limit-of-recursion/Jq/find-limit-of-recursion-5.jq similarity index 100% rename from Task/Find-limit-of-recursion/jq/find-limit-of-recursion-5.jq rename to Task/Find-limit-of-recursion/Jq/find-limit-of-recursion-5.jq diff --git a/Task/Find-limit-of-recursion/Kotlin/find-limit-of-recursion.kotlin b/Task/Find-limit-of-recursion/Kotlin/find-limit-of-recursion.kotlin new file mode 100644 index 0000000000..314c1b8915 --- /dev/null +++ b/Task/Find-limit-of-recursion/Kotlin/find-limit-of-recursion.kotlin @@ -0,0 +1,12 @@ +// version 1.1.2 + +fun recurse(i: Int) { + try { + recurse(i + 1) + } + catch(e: StackOverflowError) { + println("Limit of recursion is $i") + } +} + +fun main(args: Array) = recurse(0) diff --git a/Task/Find-limit-of-recursion/Lua/find-limit-of-recursion.lua b/Task/Find-limit-of-recursion/Lua/find-limit-of-recursion.lua index 789a1c135a..3a3fe4bfa5 100644 --- a/Task/Find-limit-of-recursion/Lua/find-limit-of-recursion.lua +++ b/Task/Find-limit-of-recursion/Lua/find-limit-of-recursion.lua @@ -1,9 +1,15 @@ -counter = 0 - -function test() - print("Depth:", counter) - counter = counter + 1 - test() +local c = 0 +function Tail(proper) + c = c + 1 + if proper then + if c < 9999999 then return Tail(proper) else return c end + else + return 1/c+Tail(proper) -- make the recursive call must keep previous stack + end end -test() +local ok,check = pcall(Tail,true) +print(c, ok, check) +c=0 +ok,check = pcall(Tail,false) +print(c, ok, check) diff --git a/Task/Find-limit-of-recursion/PowerShell/find-limit-of-recursion-1.psh b/Task/Find-limit-of-recursion/PowerShell/find-limit-of-recursion-1.psh deleted file mode 100644 index 3f09e8691f..0000000000 --- a/Task/Find-limit-of-recursion/PowerShell/find-limit-of-recursion-1.psh +++ /dev/null @@ -1,2 +0,0 @@ -The script failed due to call depth overflow. The call depth reached 1001 and the maximum is 1000. -System.Management.Automation diff --git a/Task/Find-limit-of-recursion/PowerShell/find-limit-of-recursion-2.psh b/Task/Find-limit-of-recursion/PowerShell/find-limit-of-recursion-2.psh deleted file mode 100644 index 8664608242..0000000000 --- a/Task/Find-limit-of-recursion/PowerShell/find-limit-of-recursion-2.psh +++ /dev/null @@ -1,11 +0,0 @@ -function Check-Recursion{ - trap [Exception] { - Write-Host $_.Exception.Message - } - Check-Recursion -} - -trap [Exception] { - Write-Host $_.Exception.Message -} -Check-Recursion diff --git a/Task/Find-limit-of-recursion/PowerShell/find-limit-of-recursion-3.psh b/Task/Find-limit-of-recursion/PowerShell/find-limit-of-recursion-3.psh deleted file mode 100644 index 2e3de70b8b..0000000000 --- a/Task/Find-limit-of-recursion/PowerShell/find-limit-of-recursion-3.psh +++ /dev/null @@ -1,6 +0,0 @@ -function Check-Recursion{ - Check-Recursion -} - -try { Check-Recursion } -catch { Write-Host $_.Exception.Message } diff --git a/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion-1.rust b/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion-1.rust deleted file mode 100644 index 8dead19a30..0000000000 --- a/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion-1.rust +++ /dev/null @@ -1,8 +0,0 @@ -fn recurse(n: int) { - println(fmt!("deep: %?", n)); - recurse(n + 1); -} - -fn main() { - recurse(0); -} diff --git a/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion-2.rust b/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion-2.rust deleted file mode 100644 index dbdba9f2dd..0000000000 --- a/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion-2.rust +++ /dev/null @@ -1,8 +0,0 @@ -fn recurse(n: int) { - println!("deep: {:d}", n); - recurse(n + 1); -} - -fn main() { - recurse(0); -} diff --git a/Task/Find-limit-of-recursion/X86-Assembly/find-limit-of-recursion.x86 b/Task/Find-limit-of-recursion/X86-Assembly/find-limit-of-recursion.x86 new file mode 100644 index 0000000000..ba016b7ded --- /dev/null +++ b/Task/Find-limit-of-recursion/X86-Assembly/find-limit-of-recursion.x86 @@ -0,0 +1,13 @@ + global main + + section .text + +main + xor eax, eax + call recurse + ret + +recurse + add eax, 1 + call recurse + ret diff --git a/Task/Find-limit-of-recursion/Zkl/find-limit-of-recursion.zkl b/Task/Find-limit-of-recursion/Zkl/find-limit-of-recursion.zkl new file mode 100644 index 0000000000..64dad73f62 --- /dev/null +++ b/Task/Find-limit-of-recursion/Zkl/find-limit-of-recursion.zkl @@ -0,0 +1 @@ +fcn{self.fcn()}() diff --git a/Task/Find-the-last-Sunday-of-each-month/360-Assembly/find-the-last-sunday-of-each-month.360 b/Task/Find-the-last-Sunday-of-each-month/360-Assembly/find-the-last-sunday-of-each-month.360 new file mode 100644 index 0000000000..af999dca73 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/360-Assembly/find-the-last-sunday-of-each-month.360 @@ -0,0 +1,79 @@ +* Last Sunday of each month 31/01/2017 +LASTSUND CSECT + USING LASTSUND,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) prolog + ST R13,4(R15) " <- + ST R15,8(R13) " -> + LR R13,R15 " addressability + L R4,YEAR year + SRDA R4,32 . + D R4,=F'400' year/400 + LTR R4,R4 if year//400=0 + BZ LEAP + L R4,YEAR year + SRDA R4,32 . + D R4,=F'4' year/4 + LTR R4,R4 if year//4=0 + BNZ NOTLEAP + L R4,YEAR year + SRDA R4,32 . + D R4,=F'100' year/400 + LTR R4,R4 if year//100=0 + BZ NOTLEAP +LEAP MVC DAYS+4(4),=F'29' days(2)=29 +NOTLEAP L R8,YEAR year + BCTR R8,0 y=year-1 + LA R7,42 42 + AR R7,R8 +y + LR R3,R8 y + SRA R3,2 y/4 + AR R7,R3 +y/4 + LR R4,R8 y + SRDA R4,32 . + D R4,=F'100' y/100 + LA R4,0 . + M R4,=F'6' *6 + AR R7,R5 +6*(y/100) + LR R4,R8 y + SRDA R4,32 . + D R4,=F'400' y/100 + AR R7,R5 k=42+y+y/4+6*(y/100)+y/400 + LA R6,1 m=1 +LOOPM C R6,=F'12' do m=1 to 12 + BH ELOOPM + LR R1,R6 m + SLA R1,2 . + L R2,DAYS-4(R1) days(m) + AR R7,R2 k=k+days(m) + LR R4,R7 k + SRDA R4,32 . + D R4,=F'7' k/7 + SR R2,R4 days(m)-k//7 + LR R9,R2 d=days(m)-k//7 + L R1,YEAR year + CVD R1,DW year: binary to packed + OI DW+7,X'0F' zap sign + UNPK PG(4),DW unpack (ZL4) + CVD R6,DW m : binary to packed + OI DW+7,X'0F' zap sign + UNPK PG+5(2),DW unpack (ZL2) + CVD R9,DW d: binary to packed + OI DW+7,X'0F' zap sign + UNPK PG+8(2),DW unpack (ZL2) + XPRNT PG,L'PG print buffer + LA R6,1(R6) m=m+1 + B LOOPM +ELOOPM L R13,4(0,R13) epilog + LM R14,R12,12(R13) " restore + XR R15,R15 " rc=0 + BR R14 exit +YEAR DC F'2013' <== input year +DAYS DC F'31',F'28',F'31',F'30',F'31',F'30' + DC F'31',F'31',F'30',F'31',F'30',F'31' +PG DC CL80'YYYY-MM-DD' buffer +XDEC DS CL12 temp +DW DS D packed (PL8) 15num + YREGS + END LASTSUND diff --git a/Task/Find-the-last-Sunday-of-each-month/AppleScript/find-the-last-sunday-of-each-month.applescript b/Task/Find-the-last-Sunday-of-each-month/AppleScript/find-the-last-sunday-of-each-month.applescript index 1f27012f72..95a855a929 100644 --- a/Task/Find-the-last-Sunday-of-each-month/AppleScript/find-the-last-sunday-of-each-month.applescript +++ b/Task/Find-the-last-Sunday-of-each-month/AppleScript/find-the-last-sunday-of-each-month.applescript @@ -1,23 +1,25 @@ +-- LAST SUNDAYS OF YEAR ------------------------------------------------------ + -- lastSundaysOfYear :: Int -> [Date] on lastSundaysOfYear(y) -- lastWeekDaysOfYear :: Int -> Int -> [Date] script lastWeekDaysOfYear - on lambda(intYear, iWeekday) + on |λ|(intYear, iWeekday) -- lastWeekDay :: Int -> Int -> Date script lastWeekDay - on lambda(iLastDay, iMonth) + on |λ|(iLastDay, iMonth) set iYear to intYear calendarDate(iYear, iMonth, iLastDay - ¬ (((weekday of calendarDate(iYear, iMonth, iLastDay)) as integer) + ¬ (7 - (iWeekday))) mod 7) - end lambda + end |λ| end script map(lastWeekDay, lastDaysOfMonths(intYear)) - end lambda + end |λ| -- isLeapYear :: Int -> Bool on isLeapYear(y) @@ -30,11 +32,11 @@ on lastSundaysOfYear(y) end lastDaysOfMonths end script - lastWeekDaysOfYear's lambda(y, Sunday as integer) + lastWeekDaysOfYear's |λ|(y, Sunday as integer) end lastSundaysOfYear --- TEST +-- TEST ---------------------------------------------------------------------- on run argv intercalate(linefeed, ¬ @@ -45,7 +47,7 @@ on run argv end run --- ARGUMENT HANDLING +-- ARGUMENT HANDLING --------------------------------------------------------- -- Up to two optional command line arguments: [yearFrom], [yearTo] -- (Default range in absence of arguments: from two years ago, to two years ahead) @@ -62,7 +64,7 @@ end singleYearOrRange -- fiveCurrentYears :: () -> [Int] on fiveCurrentYears(_) set intThisYear to year of (current date) - range(intThisYear - 2, intThisYear + 2) + enumFromTo(intThisYear - 2, intThisYear + 2) end fiveCurrentYears -- argIntegers :: maybe [String] -> [Int] @@ -75,9 +77,12 @@ on argIntegers(argv) end argIntegers --- GENERIC FUNCTIONS ------------------------------------------------------------------------- +-- GENERIC FUNCTIONS --------------------------------------------------------- --- Dates and date strings +-- apply (a -> b) -> a -> b +on apply(f, a) + mReturn(f)'s |λ|(a) +end apply -- calendarDate :: Int -> Int -> Int -> Date on calendarDate(intYear, intMonth, intDay) @@ -88,38 +93,28 @@ on calendarDate(intYear, intMonth, intDay) end tell end calendarDate --- isoDateString :: Date -> String -on isoDateString(dte) - (((year of dte) as string) & ¬ - "-" & text items -2 thru -1 of ¬ - ("0" & ((month of dte) as integer) as string)) & ¬ - "-" & text items -2 thru -1 of ¬ - ("0" & day of dte) -end isoDateString +-- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b) +on cond(bool, f, g) + if bool then + f + else + g + end if +end cond --- parseInt :: String -> Int -on parseInt(s) - s as integer -end parseInt - --- Testing and tabulation - --- transpose :: [[a]] -> [[a]] -on transpose(xss) - script column - on lambda(_, iCol) - script row - on lambda(xs) - item iCol of xs - end lambda - end script - - map(row, xss) - end lambda - end script - - map(column, item 1 of xss) -end transpose +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) @@ -130,34 +125,27 @@ on intercalate(strText, lstText) return strJoined end intercalate +-- isoDateString :: Date -> String +on isoDateString(dte) + (((year of dte) as string) & ¬ + "-" & text items -2 thru -1 of ¬ + ("0" & ((month of dte) as integer) as string)) & ¬ + "-" & text items -2 thru -1 of ¬ + ("0" & day of dte) +end isoDateString + -- isoRow :: [Date] -> String on isoRow(lstDate) intercalate(tab, map(my isoDateString, lstDate)) end isoRow --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then - set d to -1 - else - set d to 1 - end if - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range - --- Higher-order functions - -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -170,21 +158,29 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn --- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b) -on cond(bool, f, g) - if bool then - f - else - g - end if -end cond +-- parseInt :: String -> Int +on parseInt(s) + s as integer +end parseInt --- apply (a -> b) -> a -> b -on apply(f, a) - mReturn(f)'s lambda(a) -end apply +-- transpose :: [[a]] -> [[a]] +on transpose(xss) + script column + on |λ|(_, iCol) + script row + on |λ|(xs) + item iCol of xs + end |λ| + end script + + map(row, xss) + end |λ| + end script + + map(column, item 1 of xss) +end transpose diff --git a/Task/Find-the-last-Sunday-of-each-month/Common-Lisp/find-the-last-sunday-of-each-month.lisp b/Task/Find-the-last-Sunday-of-each-month/Common-Lisp/find-the-last-sunday-of-each-month.lisp new file mode 100644 index 0000000000..c799475a43 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Common-Lisp/find-the-last-sunday-of-each-month.lisp @@ -0,0 +1,16 @@ +(defun last-sundays (year) + (loop for month from 1 to 12 + for last-month-p = (= month 12) + for next-month = (if last-month-p 1 (1+ month)) + for year-of-next-month = (if last-month-p (1+ year) year) + for 1st-day-next-month = (encode-universal-time 0 0 0 1 next-month year-of-next-month 0) + for 1st-day-dow = (nth-value 6 (decode-universal-time 1st-day-next-month 0)) + ;; 0: monday, 1: tuesday, ... 6: sunday + for diff-to-last-sunday = (1+ 1st-day-dow) + for last-sunday = (- 1st-day-next-month (* diff-to-last-sunday 24 60 60)) + do (multiple-value-bind (second minute hour date month year) + (decode-universal-time last-sunday 0) + (declare (ignore second minute hour)) + (format t "~D-~2,'0D-~2,'0D~%" year month date)))) + +(last-sundays 2013) diff --git a/Task/Find-the-last-Sunday-of-each-month/Gambas/find-the-last-sunday-of-each-month.gambas b/Task/Find-the-last-Sunday-of-each-month/Gambas/find-the-last-sunday-of-each-month.gambas new file mode 100644 index 0000000000..7fffc98a0d --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Gambas/find-the-last-sunday-of-each-month.gambas @@ -0,0 +1,19 @@ +Public Sub Form_Open() +Dim sYear As String 'To store the year chosen +Dim siDay, siMonth, siWeekday As Short 'Day, Month and Weekday + +sYear = InputBox("Input year", "Last Sunday of each month") 'Get the user to enter a year +Print "Last Sundays in " & sYear 'Print a heading + +For siMonth = 1 To 12 'Loop for each month + For siDay = 31 DownTo 23 'Count backwards from 31 to 23 (Sunday 23rd February 1930) + siWeekday = 7 'Set the Weekday to Saturday in case of error in the next line + Try siWeekday = WeekDay(Date(Val(sYear), siMonth, siDay)) 'TRY and get the Weekday. If there is an error it will be ignored e.g. 31 February + If siWeekday = 0 Then 'If Weekday is Sunday then.. + Print Format(Date(Val(sYear), siMonth, siDay), "dddd dd mmmm yyyy") 'Print the date + Break 'Jump out of this loop + End If + Next +Next + +End diff --git a/Task/Find-the-last-Sunday-of-each-month/Haskell/find-the-last-sunday-of-each-month.hs b/Task/Find-the-last-Sunday-of-each-month/Haskell/find-the-last-sunday-of-each-month.hs index 691cd26d0e..b6be6c1a02 100644 --- a/Task/Find-the-last-Sunday-of-each-month/Haskell/find-the-last-sunday-of-each-month.hs +++ b/Task/Find-the-last-Sunday-of-each-month/Haskell/find-the-last-sunday-of-each-month.hs @@ -1,17 +1,26 @@ import Data.Time.Calendar -import Data.Time.Calendar.WeekDate + (Day, addDays, showGregorian, fromGregorian, gregorianMonthLength) +import Data.Time.Calendar.WeekDate (toWeekDate) +import Data.List (transpose, intercalate) --- 1 for Monday to 7 for Sunday -findWeekDay dayOfWeek date = head $ filter isWeekDay $ map toDate [-6 .. 0] - where - toDate ago = addDays ago date - isWeekDay theDate = let (_ , _ , day) = toWeekDate theDate - in day == dayOfWeek +-- [1 .. 7] for [Mon .. Sun] +findWeekDay :: Int -> Day -> Day +findWeekDay dayOfWeek date = + head + (filter + (\x -> + let (_, _, day) = toWeekDate x + in (day == dayOfWeek)) + ((`addDays` date) <$> [-6 .. 0])) -weekDayDates dayOfWeek year = map (showGregorian . findWeekDay dayOfWeek) lastDaysInMonth - where - lastDaysInMonth = map findLastDay [1 .. 12] - findLastDay month = fromGregorian year month (gregorianMonthLength year month) +weekDayDates :: Int -> Integer -> [String] +weekDayDates dayOfWeek year = + ((showGregorian . findWeekDay dayOfWeek) . + (fromGregorian year <*> gregorianMonthLength year)) <$> + [1 .. 12] -sundayDates = weekDayDates 7 -main = readLn >>= mapM_ putStrLn.sundayDates +main :: IO () +main = + mapM_ + putStrLn + (intercalate " " <$> transpose (weekDayDates 7 <$> [2013 .. 2017])) diff --git a/Task/Find-the-last-Sunday-of-each-month/JavaScript/find-the-last-sunday-of-each-month-3.js b/Task/Find-the-last-Sunday-of-each-month/JavaScript/find-the-last-sunday-of-each-month-3.js new file mode 100644 index 0000000000..a484e0e80c --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/JavaScript/find-the-last-sunday-of-each-month-3.js @@ -0,0 +1,55 @@ +(() => { + 'use strict' + + // lastWeekDaysOfYear :: Int -> Int -> [Date] + const lastWeekDaysOfYear = (iWeekDay, y) => [ + 31, + 0 === y % 4 && 0 !== y % 100 || 0 === y % 400 ? 29 : 28, + 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 + ] + .map((d, m) => + new Date(Date.UTC( + y, m, d - ((new Date(Date.UTC(y, m, d)) + .getDay() + (7 - iWeekDay)) % 7)))); + + const days = { + sunday: 0, + monday: 1, + tuesday: 2, + wednesday: 3, + thursday: 4, + friday: 5, + saturday: 6 + }; + + // GENERIC FUNCTIONS + + // curry :: ((a, b) -> c) -> a -> b -> c + const curry = f => a => b => f(a, b); + + // isoDateString :: Date -> String + const isoDateString = dte => + dte.toISOString() + .substr(0, 10); + + // range :: Int -> Int -> [Int] + const range = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // transpose :: [[a]] -> [[a]] + const transpose = lst => + lst[0].map((_, iCol) => + lst.map(row => row[iCol])); + + // TEST + return transpose( + range(2015, 2019) + .map(curry(lastWeekDaysOfYear)(days.sunday)) + ) + .map(row => row + .map(isoDateString) + .join('\t')) + .join('\n'); +})(); diff --git a/Task/Find-the-last-Sunday-of-each-month/jq/find-the-last-sunday-of-each-month-1.jq b/Task/Find-the-last-Sunday-of-each-month/Jq/find-the-last-sunday-of-each-month-1.jq similarity index 100% rename from Task/Find-the-last-Sunday-of-each-month/jq/find-the-last-sunday-of-each-month-1.jq rename to Task/Find-the-last-Sunday-of-each-month/Jq/find-the-last-sunday-of-each-month-1.jq diff --git a/Task/Find-the-last-Sunday-of-each-month/jq/find-the-last-sunday-of-each-month-2.jq b/Task/Find-the-last-Sunday-of-each-month/Jq/find-the-last-sunday-of-each-month-2.jq similarity index 100% rename from Task/Find-the-last-Sunday-of-each-month/jq/find-the-last-sunday-of-each-month-2.jq rename to Task/Find-the-last-Sunday-of-each-month/Jq/find-the-last-sunday-of-each-month-2.jq diff --git a/Task/Find-the-last-Sunday-of-each-month/jq/find-the-last-sunday-of-each-month-3.jq b/Task/Find-the-last-Sunday-of-each-month/Jq/find-the-last-sunday-of-each-month-3.jq similarity index 100% rename from Task/Find-the-last-Sunday-of-each-month/jq/find-the-last-sunday-of-each-month-3.jq rename to Task/Find-the-last-Sunday-of-each-month/Jq/find-the-last-sunday-of-each-month-3.jq diff --git a/Task/Find-the-last-Sunday-of-each-month/Kotlin/find-the-last-sunday-of-each-month.kotlin b/Task/Find-the-last-Sunday-of-each-month/Kotlin/find-the-last-sunday-of-each-month.kotlin new file mode 100644 index 0000000000..5c6f8ae2f5 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Kotlin/find-the-last-sunday-of-each-month.kotlin @@ -0,0 +1,21 @@ +// version 1.0.6 + +import java.util.* + +fun main(args: Array) { + print("Enter a year : ") + val year = readLine()!!.toInt() + + println("The last Sundays of each month in $year are as follows:") + val calendar = GregorianCalendar(year, 0, 31) + for (month in 1..12) { + val daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH) + val lastSunday = daysInMonth - (calendar[Calendar.DAY_OF_WEEK] - Calendar.SUNDAY) + println("$year-" + "%02d-".format(month) + "%02d".format(lastSunday)) + if (month < 12) { + calendar.add(Calendar.DAY_OF_MONTH, 1) + calendar.add(Calendar.MONTH, 1) + calendar.add(Calendar.DAY_OF_MONTH, -1) + } + } +} diff --git a/Task/Find-the-last-Sunday-of-each-month/PureBasic/find-the-last-sunday-of-each-month.purebasic b/Task/Find-the-last-Sunday-of-each-month/PureBasic/find-the-last-sunday-of-each-month.purebasic new file mode 100644 index 0000000000..b510aec823 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/PureBasic/find-the-last-sunday-of-each-month.purebasic @@ -0,0 +1,34 @@ +Procedure LastSundayOfEachMonth(yyyy.i,List lfem.i()) + Define dv.i=ParseDate("%yyyy",Str(yyyy)), mv.i=1 + NewList d.i() + For d=1 To 365 + dv=AddDate(dv,#PB_Date_Day,1) + If DayOfWeek(dv)=0 + AddElement(d()) : d()=dv + EndIf + Next + dv=0 + For mv=1 To 12 + ForEach d() + If dv1971 And y<2038 + PrintN("Last Sunday of each month...") + LastSundayOfEachMonth(y,lf()) + ForEach lf() + PrintN(FormatDate("%dd.%mm.%yyyy",lf())) + Next +EndIf +Print("...End") +Input() diff --git a/Task/Find-the-last-Sunday-of-each-month/Swift/find-the-last-sunday-of-each-month.swift b/Task/Find-the-last-Sunday-of-each-month/Swift/find-the-last-sunday-of-each-month.swift new file mode 100644 index 0000000000..0e91e8e47a --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Swift/find-the-last-sunday-of-each-month.swift @@ -0,0 +1,31 @@ +import Foundation + +func lastSundays(of year: Int) -> [Date] { + + let calendar = Calendar.current + var dates = [Date]() + + for month in 1...12 { + + var dateComponents = DateComponents(calendar: calendar, + year: year, + month: month + 1, + day: 0, + hour: 12) + + let date = calendar.date(from: dateComponents)! + let weekday = calendar.component(.weekday, from: date) + + if weekday != 1 { + dateComponents.day! -= weekday - 1 + } + + dates.append(calendar.date(from: dateComponents)!) + } + return dates +} + +var dateFormatter = DateFormatter() +dateFormatter.dateStyle = .short + +print(lastSundays(of: 2013).map(dateFormatter.string).joined(separator: "\n")) diff --git a/Task/Find-the-missing-permutation/Aime/find-the-missing-permutation.aime b/Task/Find-the-missing-permutation/Aime/find-the-missing-permutation.aime new file mode 100644 index 0000000000..b62e58e26b --- /dev/null +++ b/Task/Find-the-missing-permutation/Aime/find-the-missing-permutation.aime @@ -0,0 +1,36 @@ +void +paste(record r, index x, data p, integer a,) +{ + i_delete(x, a); + p[i_size(x)] = a; + if (i_size(x)) { + i_wcall(x, paste, -1, -1, r, x, p); + } else { + r[b_string(p)] = 0; + } + x[a] = 0; +} + +integer +main(void) +{ + record r; + list l; + index x; + data p; + + l_bill(l, 0, "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", + "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", + "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"); + + i_fit(x, 'A', 0, 'B', 0, 'C', 0, 'D', 0); + + b_size(p, 4); + i_wcall(x, paste, -1, -1, r, x, p); + + l_ucall(l, r_delete, 1, r); + + o_(r_low(r), "\n"); + + return 0; +} diff --git a/Task/Find-the-missing-permutation/AppleScript/find-the-missing-permutation.applescript b/Task/Find-the-missing-permutation/AppleScript/find-the-missing-permutation.applescript index e1f48a5261..9b864c7c09 100644 --- a/Task/Find-the-missing-permutation/AppleScript/find-the-missing-permutation.applescript +++ b/Task/Find-the-missing-permutation/AppleScript/find-the-missing-permutation.applescript @@ -1,85 +1,39 @@ -use framework "Foundation" +use framework "Foundation" -- ( sort ) --- UNDER-REPRESENTED CHARACTER IN EACH OF N COLUMNS - --- missingChar :: Record -> Character -script missingChar - -- mean :: [Num] -> Num - on mean(xs) - script sum - on lambda(a, b) - a + b - end lambda - end script - - foldl(sum, 0, xs) / (length of xs) - end mean - - -- Record -> Character - on lambda(rec) - set nMean to mean(allValues(rec)) - - script belowMean - on lambda(a, x, i) - set k to toLowerCase(x) - if a is missing value then - set v to keyValue(rec, k) - if v < nMean then - toUpperCase(x) - else - missing value - end if - else - a - end if - end lambda - end script - - foldl(belowMean, missing value, allKeys(rec)) - end lambda -end script - --- Count of each character type in each character column - --- colCounts :: [Character] -> Record -script colCounts - on lambda(xs) - script tally - on lambda(a, x) - set k to toLowerCase(x) - set v to keyValue(a, k) - if v is missing value then - set n to 1 - else - set n to v + 1 - end if - updatedRecord(a, k, n) - end lambda - end script - - foldl(tally, {name:""}, xs) - end lambda -end script - --- TEST +-- RAREST LETTER IN EACH COLUMN ----------------------------------------------- on run - - map(missingChar, ¬ - map(colCounts, ¬ - transpose(map(curry(splitOn)'s lambda(""), ¬ - splitOn(space, ¬ - "ABCD CABD ACDB DACB BCDA ACBD " & ¬ - "ADCB CDAB DABC BCAD CADB CDBA " & ¬ - "CBAD ABDC ADBC BDCA DCBA BACD " & ¬ - "BADC BDAC CBDA DBCA DCAB"))))) as text + intercalate("", ¬ + map(compose({¬ + sort, ¬ + group, ¬ + curry(minimumBy)'s lambda(comparing(_length)), ¬ + head}), ¬ + transpose(map(stringChars, (splitOn(space, ¬ + "ABCD CABD ACDB DACB BCDA ACBD " & ¬ + "ADCB CDAB DABC BCAD CADB CDBA " & ¬ + "CBAD ABDC ADBC BDCA DCBA BACD " & ¬ + "BADC BDAC CBDA DBCA DCAB")))))) --> "DBAC" end run ---------------------------------------------------------------------------- +-- GENERIC FUNCTIONS ---------------------------------------------------------- --- GENERIC FUNCTIONS +-- compose :: [(a -> a)] -> (a -> a) +on compose(fs) + script + on lambda(x) + script + on lambda(a, f) + mReturn(f)'s lambda(a) + end lambda + end script + + foldl(result, x, fs) + end lambda + end script +end compose -- transpose :: [[a]] -> [[a]] on transpose(xss) @@ -98,6 +52,61 @@ on transpose(xss) map(column, item 1 of xss) end transpose +-- sort :: [a] -> [a] +on sort(lst) + ((current application's NSArray's arrayWithArray:lst)'s ¬ + sortedArrayUsingSelector:"compare:") as list +end sort + +-- group :: Eq a => [a] -> [[a]] +on group(xs) + script eq + on lambda(a, b) + a = b + end lambda + end script + + groupBy(eq, xs) +end group + +-- minimumBy :: (a -> a -> Ordering) -> [a] -> a +on minimumBy(f, xs) + set mf to mReturn(f) + script min + on lambda(a, b) + if a is missing value then + b + else if mf's lambda(a, b) < 0 then + a + else + b + end if + end lambda + end script + + foldl(min, missing value, xs) +end minimumBy + +-- comparing :: (a -> b) -> (a -> a -> Ordering) +on comparing(f) + set mf to mReturn(f) + script + on lambda(a, b) + set x to mf's lambda(a) + set y to mf's lambda(b) + if x < y then + -1 + else + if x > y then + 1 + else + 0 + end if + end if + end lambda + end script +end comparing + -- curry :: (Script|Handler) -> Script on curry(f) script @@ -111,6 +120,82 @@ on curry(f) end script end curry +-- groupBy :: (a -> a -> Bool) -> [a] -> [[a]] +on groupBy(f, xs) + set mf to mReturn(f) + + script enGroup + on lambda(a, x) + if length of (active of a) > 0 then + set h to item 1 of active of a + else + set h to missing value + end if + + if h is not missing value and mf's lambda(h, x) then + {active:(active of a) & x, sofar:sofar of a} + else + {active:{x}, sofar:(sofar of a) & {active of a}} + end if + end lambda + end script + + if length of xs > 0 then + set dct to foldl(enGroup, {active:{item 1 of xs}, sofar:{}}, tail(xs)) + if length of (active of dct) > 0 then + sofar of dct & {active of dct} + else + sofar of dct + end if + else + {} + end if +end groupBy + +-- head :: [a] -> a +on head(xs) + if length of xs > 0 then + item 1 of xs + else + missing value + end if +end head + +-- tail :: [a] -> [a] +on tail(xs) + if length of xs > 1 then + items 2 thru -1 of xs + else + {} + end if +end tail + +-- splitOn :: Text -> Text -> [Text] +on splitOn(strDelim, strMain) + set {dlm, my text item delimiters} to {my text item delimiters, strDelim} + set xs to text items of strMain + set my text item delimiters to dlm + return xs +end splitOn + +-- stringChars :: String -> [Char] +on stringChars(s) + characters of s +end stringChars + +-- length :: [a] -> Int +on _length(xs) + length of xs +end _length + +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) @@ -135,19 +220,6 @@ on foldl(f, startValue, xs) end tell end foldl --- splitOn :: Text -> Text -> [Text] -on splitOn(strDelim, strMain) - set {dlm, my text item delimiters} to {my text item delimiters, strDelim} - set xs to text items of strMain - set my text item delimiters to dlm - return xs -end splitOn - --- ord :: Character -> Int -on ord(x) - id of x -end ord - -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) @@ -159,52 +231,3 @@ on mReturn(f) end script end if end mReturn - - --- NSString - --- toLowerCase :: String -> String -on toLowerCase(str) - set ca to current application - ((ca's NSString's stringWithString:(str))'s ¬ - lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text -end toLowerCase - --- toUpperCase :: String -> String -on toUpperCase(str) - set ca to current application - ((ca's NSString's stringWithString:(str))'s ¬ - uppercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text -end toUpperCase - - --- NSDictionary - --- allKeys :: Record -> [String] -on allKeys(rec) - (current application's NSDictionary's dictionaryWithDictionary:rec)'s allKeys() as list -end allKeys - --- allValues :: Record -> [a] -on allValues(rec) - (current application's NSDictionary's dictionaryWithDictionary:rec)'s allValues() as list -end allValues - --- keyValue :: Record -> String -> Maybe String -on keyValue(rec, strKey) - set ca to current application - set v to (ca's NSDictionary's dictionaryWithDictionary:rec)'s objectForKey:strKey - if v is not missing value then - item 1 of ((ca's NSArray's arrayWithObject:v) as list) - else - missing value - end if -end keyValue - --- updatedRecord :: Record -> String -> a -> Record -on updatedRecord(rec, strKey, varValue) - set ca to current application - set nsDct to (ca's NSMutableDictionary's dictionaryWithDictionary:rec) - nsDct's setValue:varValue forKey:strKey - item 1 of ((ca's NSArray's arrayWithObject:nsDct) as list) -end updatedRecord diff --git a/Task/Find-the-missing-permutation/CoffeeScript/find-the-missing-permutation-1.coffee b/Task/Find-the-missing-permutation/CoffeeScript/find-the-missing-permutation-1.coffee deleted file mode 100644 index 5f8bf42fae..0000000000 --- a/Task/Find-the-missing-permutation/CoffeeScript/find-the-missing-permutation-1.coffee +++ /dev/null @@ -1,35 +0,0 @@ -missing_permutation = (arr) -> - # Find the missing permutation in an array of N! - 1 permutations. - - # We won't validate every precondition, but we do have some basic - # guards. - if arr.length == 0 - throw Error "Need more data" - if arr.length == 1 - return [arr[0][1] + arr[0][0]] - - # Now we know that for each position in the string, elements should appear - # an even number of times (N-1 >= 2). We can use a set to detect the element appearing - # an odd number of times. Detect odd occurrences by toggling admission/expulsion - # to and from the set for each value encountered. At the end of each pass one element - # will remain in the set. - result = '' - for pos in [0...arr[0].length] - set = {} - for permutation in arr - c = permutation[pos] - if set[c] - delete set[c] - else - set[c] = true - for c of set - result += c - break - result - -given = '''ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA - CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB''' - -arr = (s for s in given.replace('\n', ' ').split ' ' when s != '') - -console.log missing_permutation(arr) diff --git a/Task/Find-the-missing-permutation/CoffeeScript/find-the-missing-permutation-2.coffee b/Task/Find-the-missing-permutation/CoffeeScript/find-the-missing-permutation-2.coffee deleted file mode 100644 index b2ab004134..0000000000 --- a/Task/Find-the-missing-permutation/CoffeeScript/find-the-missing-permutation-2.coffee +++ /dev/null @@ -1,2 +0,0 @@ - > coffee missing_permute.coffee -DBAC diff --git a/Task/Find-the-missing-permutation/D/find-the-missing-permutation-1.d b/Task/Find-the-missing-permutation/D/find-the-missing-permutation-1.d deleted file mode 100644 index e0065167af..0000000000 --- a/Task/Find-the-missing-permutation/D/find-the-missing-permutation-1.d +++ /dev/null @@ -1,13 +0,0 @@ -import std.stdio, std.string, std.algorithm, std.array, std.range; - -void main() { - const givenSet = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC - BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA - DBCA DCAB"d.split().zip(repeat(true)).assocArray(); - - auto p = "ABCD"d.dup; - do { - if (p !in givenSet) - writeln("Missing permutation: ", p); - } while (p.nextPermutation()); -} diff --git a/Task/Find-the-missing-permutation/D/find-the-missing-permutation-2.d b/Task/Find-the-missing-permutation/D/find-the-missing-permutation-2.d deleted file mode 100644 index 3d296ac8c0..0000000000 --- a/Task/Find-the-missing-permutation/D/find-the-missing-permutation-2.d +++ /dev/null @@ -1,40 +0,0 @@ -import std.stdio, std.string, std.algorithm, std.conv; - -void main() { - const perms = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC - BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD - BADC BDAC CBDA DBCA DCAB".split(); - - // Version 1: XOR all the ASCII values, the uneven one gets - // flushed out; based on Perl 6 (via Go) - ubyte[4] b; - foreach (perm; perms) - foreach (i, c; perm) - b[i] ^= c; - writeln(cast(char[])b); - - // Version 2 : Sum ASCII values - auto sumr = perms[0].reduce!q{a + b}(); // sum row - foreach (i; 0 .. 4) { - // sum columns - const sumc = reduce!((a,b)=> text(to!int(a) + b[i]))("0",perms); - // see how much it falls short - write(cast(char)(sumr - to!int(sumc) % sumr)); - } - writeln(); - - // Version 3: some sort of checksum, don't ask - // me: translation of Java - enum int len = 4; - int maxCode = len - 1; - foreach_reverse (i; 3 .. len + 1) - maxCode *= i; // maxCode will be 36 - foreach (i; 0 .. len) { - int code = 0; - foreach (p; perms) - code += perms[0].countUntil(p[i]); - - // code will come up 3, 1, 0, 2 short of 36 - write(cast(char)perms[0][maxCode - code]); - } -} diff --git a/Task/Find-the-missing-permutation/Forth/find-the-missing-permutation.fth b/Task/Find-the-missing-permutation/Forth/find-the-missing-permutation.fth new file mode 100644 index 0000000000..d7108cc72f --- /dev/null +++ b/Task/Find-the-missing-permutation/Forth/find-the-missing-permutation.fth @@ -0,0 +1,7 @@ + hex + ABCD CABD xor ACDB xor DACB xor BCDA xor ACBD xor + ADCB xor CDAB xor DABC xor BCAD xor CADB xor CDBA xor + CBAD xor ABDC xor ADBC xor BDCA xor DCBA xor BACD xor + BADC xor BDAC xor CBDA xor DBCA xor DCAB xor + cr .( Missing permutation: ) u. + decimal diff --git a/Task/Find-the-missing-permutation/FreeBASIC/find-the-missing-permutation-1.freebasic b/Task/Find-the-missing-permutation/FreeBASIC/find-the-missing-permutation-1.freebasic new file mode 100644 index 0000000000..2e436d0ced --- /dev/null +++ b/Task/Find-the-missing-permutation/FreeBASIC/find-the-missing-permutation-1.freebasic @@ -0,0 +1,37 @@ +' version 30-03-2017 +' compile with: fbc -s console + +Data "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD" +Data "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA" +Data "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD" +Data "BADC", "BDAC", "CBDA", "DBCA", "DCAB" + +' ------=< MAIN >=------ + +Dim As ulong total(3, Asc("A") To Asc("D")) ' total(0 to 3, 65 to 68) +Dim As ULong i, j, n = 24 \ 4 ' n! \ n +Dim As String tmp + +For i = 1 To 23 + Read tmp + For j = 0 To 3 + total(j, tmp[j]) += 1 + Next +Next + +tmp = Space(4) +For i = 0 To 3 + For j = Asc("A") To Asc("D") + If total(i, j) <> n Then + tmp[i] = j + End If + Next +Next + +Print "The missing permutation is : "; tmp + +' empty keyboard buffer +While InKey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Find-the-missing-permutation/FreeBASIC/find-the-missing-permutation-2.freebasic b/Task/Find-the-missing-permutation/FreeBASIC/find-the-missing-permutation-2.freebasic new file mode 100644 index 0000000000..ef7d0c4ed9 --- /dev/null +++ b/Task/Find-the-missing-permutation/FreeBASIC/find-the-missing-permutation-2.freebasic @@ -0,0 +1,34 @@ +' version 30-03-2017 +' compile with: fbc -s console + +Data "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD" +Data "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA" +Data "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD" +Data "BADC", "BDAC", "CBDA", "DBCA", "DCAB" + +' ------=< MAIN >=------ + +Dim As ULong total(3) ' total(0 to 3) +Dim As ULong i, j, n = 24 \ 4 ' n! \ n +Dim As ULong total_val = (Asc("A") + Asc("B") + Asc("C") + Asc("D")) * n +Dim As String tmp + +For i = 1 To 23 + Read tmp + For j = 0 To 3 + total(j) += tmp[j] + Next +Next + +tmp = Space(4) +For i = 0 To 3 + tmp[i] = total_val - total(i) +Next + +Print "The missing permutation is : "; tmp + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Find-the-missing-permutation/FreeBASIC/find-the-missing-permutation-3.freebasic b/Task/Find-the-missing-permutation/FreeBASIC/find-the-missing-permutation-3.freebasic new file mode 100644 index 0000000000..b7816c1fd7 --- /dev/null +++ b/Task/Find-the-missing-permutation/FreeBASIC/find-the-missing-permutation-3.freebasic @@ -0,0 +1,27 @@ +' version 30-03-2017 +' compile with: fbc -s console + +Data "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD" +Data "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA" +Data "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD" +Data "BADC", "BDAC", "CBDA", "DBCA", "DCAB" + +' ------=< MAIN >=------ + +Dim As ULong i,j +Dim As String tmp, missing = chr(0, 0, 0, 0) ' or string(4, 0) + +For i = 1 To 23 + Read tmp + For j = 0 To 3 + missing[j] Xor= tmp[j] + Next +Next + +Print "The missing permutation is : "; missing + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Find-the-missing-permutation/Haskell/find-the-missing-permutation-1.hs b/Task/Find-the-missing-permutation/Haskell/find-the-missing-permutation-1.hs new file mode 100644 index 0000000000..762bf5dcc2 --- /dev/null +++ b/Task/Find-the-missing-permutation/Haskell/find-the-missing-permutation-1.hs @@ -0,0 +1,37 @@ +import Data.List ((\\), permutations, nub) +import Control.Monad (join) + +missingPerm + :: Eq a + => [[a]] -> [[a]] +missingPerm = (\\) =<< permutations . nub . join + +deficientPermsList :: [String] +deficientPermsList = + [ "ABCD" + , "CABD" + , "ACDB" + , "DACB" + , "BCDA" + , "ACBD" + , "ADCB" + , "CDAB" + , "DABC" + , "BCAD" + , "CADB" + , "CDBA" + , "CBAD" + , "ABDC" + , "ADBC" + , "BDCA" + , "DCBA" + , "BACD" + , "BADC" + , "BDAC" + , "CBDA" + , "DBCA" + , "DCAB" + ] + +main :: IO () +main = print $ missingPerm deficientPermsList diff --git a/Task/Find-the-missing-permutation/Haskell/find-the-missing-permutation-2.hs b/Task/Find-the-missing-permutation/Haskell/find-the-missing-permutation-2.hs new file mode 100644 index 0000000000..b7e725e90a --- /dev/null +++ b/Task/Find-the-missing-permutation/Haskell/find-the-missing-permutation-2.hs @@ -0,0 +1,37 @@ +import Data.List (minimumBy, group, sort, transpose) +import Data.Ord (comparing) + +missingPerm + :: Ord a + => [[a]] -> [a] +missingPerm = ((head . minimumBy (comparing length) . group . sort) <$>) . transpose + +deficientPermsList :: [String] +deficientPermsList = + [ "ABCD" + , "CABD" + , "ACDB" + , "DACB" + , "BCDA" + , "ACBD" + , "ADCB" + , "CDAB" + , "DABC" + , "BCAD" + , "CADB" + , "CDBA" + , "CBAD" + , "ABDC" + , "ADBC" + , "BDCA" + , "DCBA" + , "BACD" + , "BADC" + , "BDAC" + , "CBDA" + , "DBCA" + , "DCAB" + ] + +main :: IO () +main = print $ missingPerm deficientPermsList diff --git a/Task/Find-the-missing-permutation/Haskell/find-the-missing-permutation.hs b/Task/Find-the-missing-permutation/Haskell/find-the-missing-permutation.hs deleted file mode 100644 index 2e5fd8597f..0000000000 --- a/Task/Find-the-missing-permutation/Haskell/find-the-missing-permutation.hs +++ /dev/null @@ -1,16 +0,0 @@ -import Data.List -import Control.Monad -import Control.Arrow - -missingPerm :: Eq a => [[a]] -> [[a]] -missingPerm = (\\) =<< permutations . nub . join - -deficientPermsList = ["ABCD","CABD","ACDB","DACB", - "BCDA","ACBD","ADCB","CDAB", - "DABC","BCAD","CADB","CDBA", - "CBAD","ABDC","ADBC","BDCA", - "DCBA","BACD","BADC","BDAC", - "CBDA","DBCA","DCAB"] - -main = do - print $ missingPerm deficientPermsList diff --git a/Task/Find-the-missing-permutation/JavaScript/find-the-missing-permutation-5.js b/Task/Find-the-missing-permutation/JavaScript/find-the-missing-permutation-5.js new file mode 100644 index 0000000000..f606440fd4 --- /dev/null +++ b/Task/Find-the-missing-permutation/JavaScript/find-the-missing-permutation-5.js @@ -0,0 +1,96 @@ +(() => { + 'use strict'; + + // MISSING PERMUTATION --------------------------------------------------- + + // missingPermutation :: [String] -> String + const missingPermutation = xs => + map( + // Rarest letter, + compose([ + sort, + group, + curry(minimumBy)(comparing(length)), + head + ]), + + // in each column. + transpose(map(stringChars, xs)) + ) + .join(''); + + + // GENERIC FUNCTIONAL PRIMITIVES ----------------------------------------- + + // transpose :: [[a]] -> [[a]] + const transpose = xs => + xs[0].map((_, iCol) => xs.map(row => row[iCol])); + + // sort :: Ord a => [a] -> [a] + const sort = xs => xs.sort(); + + // group :: Eq a => [a] -> [[a]] + const group = xs => groupBy((a, b) => a === b, xs); + + // groupBy :: (a -> a -> Bool) -> [a] -> [[a]] + const groupBy = (f, xs) => { + const dct = xs.slice(1) + .reduce((a, x) => { + const + h = a.active.length > 0 ? a.active[0] : undefined, + blnGroup = h !== undefined && f(h, x); + + return { + active: blnGroup ? a.active.concat(x) : [x], + sofar: blnGroup ? a.sofar : a.sofar.concat([a.active]) + }; + }, { + active: xs.length > 0 ? [xs[0]] : [], + sofar: [] + }); + return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []); + }; + + // length :: [a] -> Int + const length = xs => xs.length; + + // comparing :: (a -> b) -> (a -> a -> Ordering) + const comparing = f => + (x, y) => { + const + a = f(x), + b = f(y); + return a < b ? -1 : a > b ? 1 : 0 + }; + + // minimumBy :: (a -> a -> Ordering) -> [a] -> a + const minimumBy = (f, xs) => + xs.reduce((a, x) => a === undefined ? x : ( + f(x, a) < 0 ? x : a + ), undefined); + + // head :: [a] -> a + const head = xs => xs.length ? xs[0] : undefined; + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f) + + // compose :: [(a -> a)] -> (a -> a) + const compose = fs => x => fs.reduce((a, f) => f(a), x); + + // curry :: ((a, b) -> c) -> a -> b -> c + const curry = f => a => b => f(a, b); + + // stringChars :: String -> [Char] + const stringChars = s => s.split(''); + + + // TEST ------------------------------------------------------------------ + + return missingPermutation(["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", + "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", + "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB" + ]); + + // -> "DBAC" +})(); diff --git a/Task/Find-the-missing-permutation/jq/find-the-missing-permutation-1.jq b/Task/Find-the-missing-permutation/Jq/find-the-missing-permutation-1.jq similarity index 100% rename from Task/Find-the-missing-permutation/jq/find-the-missing-permutation-1.jq rename to Task/Find-the-missing-permutation/Jq/find-the-missing-permutation-1.jq diff --git a/Task/Find-the-missing-permutation/jq/find-the-missing-permutation-2.jq b/Task/Find-the-missing-permutation/Jq/find-the-missing-permutation-2.jq similarity index 100% rename from Task/Find-the-missing-permutation/jq/find-the-missing-permutation-2.jq rename to Task/Find-the-missing-permutation/Jq/find-the-missing-permutation-2.jq diff --git a/Task/Find-the-missing-permutation/jq/find-the-missing-permutation-3.jq b/Task/Find-the-missing-permutation/Jq/find-the-missing-permutation-3.jq similarity index 100% rename from Task/Find-the-missing-permutation/jq/find-the-missing-permutation-3.jq rename to Task/Find-the-missing-permutation/Jq/find-the-missing-permutation-3.jq diff --git a/Task/Find-the-missing-permutation/Kotlin/find-the-missing-permutation.kotlin b/Task/Find-the-missing-permutation/Kotlin/find-the-missing-permutation.kotlin new file mode 100644 index 0000000000..2a55b471c2 --- /dev/null +++ b/Task/Find-the-missing-permutation/Kotlin/find-the-missing-permutation.kotlin @@ -0,0 +1,34 @@ +// version 1.1.2 + +fun permute(input: List): List> { + if (input.size == 1) return listOf(input) + val perms = mutableListOf>() + val toInsert = input[0] + for (perm in permute(input.drop(1))) { + for (i in 0..perm.size) { + val newPerm = perm.toMutableList() + newPerm.add(i, toInsert) + perms.add(newPerm) + } + } + return perms +} + +fun missingPerms(input: List, perms: List>) = permute(input) - perms + +fun main(args: Array) { + val input = listOf('A', 'B', 'C', 'D') + val strings = listOf( + "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", + "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", + "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB" + ) + val perms = strings.map { it.toList() } + val missing = missingPerms(input, perms) + if (missing.size == 1) + print("The missing permutation is ${missing[0].joinToString("")}") + else { + println("There are ${missing.size} missing permutations, namely:\n") + for (perm in missing) println(perm.joinToString("")) + } +} diff --git a/Task/Find-the-missing-permutation/R/find-the-missing-permutation-1.r b/Task/Find-the-missing-permutation/R/find-the-missing-permutation-1.r deleted file mode 100644 index c3f591cc30..0000000000 --- a/Task/Find-the-missing-permutation/R/find-the-missing-permutation-1.r +++ /dev/null @@ -1,12 +0,0 @@ -library(combinat) - -permute.me <- c("A", "B", "C", "D") -perms <- permn(permute.me) # list of all permutations -perms2 <- matrix(unlist(perms), ncol=length(permute.me), byrow=T) # matrix of all permutations -perms3 <- apply(perms2, 1, paste, collapse="") # vector of all permutations - -incomplete <- c("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", - "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", - "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB") - -setdiff(perms3, incomplete) diff --git a/Task/Find-the-missing-permutation/R/find-the-missing-permutation-2.r b/Task/Find-the-missing-permutation/R/find-the-missing-permutation-2.r deleted file mode 100644 index aa8d97698d..0000000000 --- a/Task/Find-the-missing-permutation/R/find-the-missing-permutation-2.r +++ /dev/null @@ -1 +0,0 @@ -[1] "DBAC" diff --git a/Task/Find-the-missing-permutation/Sidef/find-the-missing-permutation.sidef b/Task/Find-the-missing-permutation/Sidef/find-the-missing-permutation.sidef index f9544b7b74..a49917da19 100644 --- a/Task/Find-the-missing-permutation/Sidef/find-the-missing-permutation.sidef +++ b/Task/Find-the-missing-permutation/Sidef/find-the-missing-permutation.sidef @@ -1,14 +1,15 @@ func check_perm(arr) { - (var hash = Hash.new).@{arr} = @[1]*arr.len; + var hash = Hash() + hash.set_keys(arr...) arr.each { |s| - s.len.times { - var t = (s.substr(1) + s.substr(0, 1)); - hash.has_key(t) || return t; - } + { + var t = (s.substr(1) + s.substr(0, 1)) + hash.has_key(t) || return t + } * s.len } } var perms = %w(ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA - CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB); + CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB) -say check_perm(perms); +say check_perm(perms) diff --git a/Task/Find-the-missing-permutation/Tcl/find-the-missing-permutation-1.tcl b/Task/Find-the-missing-permutation/Tcl/find-the-missing-permutation-1.tcl deleted file mode 100644 index ddf0b76f51..0000000000 --- a/Task/Find-the-missing-permutation/Tcl/find-the-missing-permutation-1.tcl +++ /dev/null @@ -1,24 +0,0 @@ -package require struct::list -package require struct::set - -# Make complete list of permutations of a string of characters -proc allCharPerms s { - set perms {} - set p [struct::list firstperm [split $s {}]] - while {$p ne ""} { - lappend perms [join $p {}] - set p [struct::list nextperm $p] - } - return $perms -} - -# The set of provided permutations (wrapped for convenience) -set have { - ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC - ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB -} -# Get the real list of permutations... -set all [allCharPerms [lindex $have 0]] -# Find the missing one(s)! -set missing [struct::set difference $all $have] -puts "missing permutation(s): $missing" diff --git a/Task/Find-the-missing-permutation/Tcl/find-the-missing-permutation-2.tcl b/Task/Find-the-missing-permutation/Tcl/find-the-missing-permutation-2.tcl deleted file mode 100644 index 295f2c271d..0000000000 --- a/Task/Find-the-missing-permutation/Tcl/find-the-missing-permutation-2.tcl +++ /dev/null @@ -1,24 +0,0 @@ -package require struct::list -package require struct::set - -proc foreachPermutation {varName listToPermute body} { - upvar 1 $varName v - set p [struct::list firstperm $listToPermute] - for {} {$p ne ""} {set p [struct::list nextperm $p]} { - set v $p; uplevel 1 $body - } -} - -proc findMissingCharPermutations {set} { - set all {} - foreachPermutation charPerm [split [lindex $set 0] {}] { - lappend all [join $charPerm {}] - } - return [struct::set difference $all $set] -} - -set have { - ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC - ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB -} -set missing [findMissingCharPermutations $have] diff --git a/Task/Find-the-missing-permutation/Zkl/find-the-missing-permutation.zkl b/Task/Find-the-missing-permutation/Zkl/find-the-missing-permutation.zkl new file mode 100644 index 0000000000..134508fed1 --- /dev/null +++ b/Task/Find-the-missing-permutation/Zkl/find-the-missing-permutation.zkl @@ -0,0 +1,4 @@ +var data=L("ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB", + "DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA", + "DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB"); +Utils.Helpers.permute(["A".."D"]).apply("concat").copy().remove(data.xplode()); diff --git a/Task/First-class-environments/Jq/first-class-environments-1.jq b/Task/First-class-environments/Jq/first-class-environments-1.jq new file mode 100644 index 0000000000..96e941f42b --- /dev/null +++ b/Task/First-class-environments/Jq/first-class-environments-1.jq @@ -0,0 +1,5 @@ +def code: + # Given an integer as input, compute the corresponding hailstone value: + def hail: if . % 2 == 0 then ./2|floor else 3*. + 1 end; + + if .value > 1 then (.value |= hail) | .count += 1 else . end; diff --git a/Task/First-class-environments/Jq/first-class-environments-2.jq b/Task/First-class-environments/Jq/first-class-environments-2.jq new file mode 100644 index 0000000000..4c3270b20b --- /dev/null +++ b/Task/First-class-environments/Jq/first-class-environments-2.jq @@ -0,0 +1,3 @@ +filter_and_last( generate; + map(.value) | @tsv; + "", "Counts:", (map(.count) | @tsv )) diff --git a/Task/First-class-environments/Kotlin/first-class-environments.kotlin b/Task/First-class-environments/Kotlin/first-class-environments.kotlin new file mode 100644 index 0000000000..0c4712cf95 --- /dev/null +++ b/Task/First-class-environments/Kotlin/first-class-environments.kotlin @@ -0,0 +1,56 @@ +// version 1.1.3 + +class Environment(var seq: Int, var count: Int) + +const val JOBS = 12 +val envs = List(JOBS) { Environment(it + 1, 0) } +var seq = 0 // 'seq' for current environment +var count = 0 // 'count' for current environment +var currId = 0 // index of current environment + +fun switchTo(id: Int) { + if (id != currId) { + envs[currId].seq = seq + envs[currId].count = count + currId = id + } + seq = envs[id].seq + count = envs[id].count +} + +fun hailstone() { + print("%4d".format(seq)) + if (seq == 1) return + count++ + seq = if (seq % 2 == 1) 3 * seq + 1 else seq / 2 +} + +val allDone get(): Boolean { + for (a in 0 until JOBS) { + switchTo(a) + if (seq != 1) return false + } + return true +} + +fun code() { + do { + for (a in 0 until JOBS) { + switchTo(a) + hailstone() + } + println() + } + while (!allDone) + + println("\nCOUNTS:") + for (a in 0 until JOBS) { + switchTo(a) + print("%4d".format(count)) + } + println() +} + +fun main(args: Array) { + code() +} diff --git a/Task/First-class-environments/Phix/first-class-environments-1.phix b/Task/First-class-environments/Phix/first-class-environments-1.phix new file mode 100644 index 0000000000..ad7da07653 --- /dev/null +++ b/Task/First-class-environments/Phix/first-class-environments-1.phix @@ -0,0 +1,48 @@ +function hail(integer n) + if remainder(n,2)=0 then + n /= 2 + else + n = 3*n+1 + end if + return n +end function + +sequence hails = tagset(12), + counts = repeat(0,12), + results = columnize({hails}) + +function step(integer edx) + integer n = hails[edx] + if n=1 then return 0 end if + n = hail(n) + hails[edx] = n + counts[edx] += 1 + results[edx] &= n + return 1 +end function + +procedure main() + bool done = false + while not done do + done = true + for i=1 to 12 do + if step(i) then + done = false + end if + end for + end while + + for i=1 to max(counts)+1 do + for j=1 to 12 do + puts(1,iff(i<=length(results[j])?sprintf("%4d",{results[j][i]}):" ")) + end for + puts(1,"\n") + end for + printf(1," %s\n",{join(repeat("===",12))}) + for j=1 to 12 do + printf(1,"%4d",{counts[j]}) + end for + puts(1,"\n") +end procedure + +main() diff --git a/Task/First-class-environments/Phix/first-class-environments-2.phix b/Task/First-class-environments/Phix/first-class-environments-2.phix new file mode 100644 index 0000000000..2f3415869b --- /dev/null +++ b/Task/First-class-environments/Phix/first-class-environments-2.phix @@ -0,0 +1,61 @@ +function hail(integer n) + if remainder(n,2)=0 then + n /= 2 + else + n = 3*n+1 + end if + return n +end function + +function step(integer edx) + integer n = getd("hail",edx) + if n=1 then return 0 end if + n = hail(n) + setd("hail",n,edx) + setd("count",getd("count",edx)+1,edx) + setd("results",getd("results",edx)&n,edx) + return 1 +end function + +sequence dicts = {} + +procedure main() + for i=1 to 12 do + integer d = new_dict() + setd("hail",i,d) + setd("count",0,d) + setd("results",{i},d) + dicts &= d + end for + + bool done = false + while not done do + done = true + for i=1 to 12 do + if step(dicts[i]) then + done = false + end if + end for + end while + + done = false + integer i = 1 + while not done do + done = true + for j=1 to 12 do + sequence res = getd("results",dicts[j]) + if i A NB. Corresponds to ]B =. inverse&.> A +┌───┬────┬────────┐ +│0.5│0.25│0.166667│ +└───┴────┴────────┘ + ]BA=. B multiplier&.> A NB. Corresponds to B compose&.> A +┌───┬───┬───┐ +│1&*│1&*│1&*│ +└───┴───┴───┘ + BA of &> 0.5 NB. Corresponds to BA of &> 0.5 (exactly) +0.5 0.5 0.5 diff --git a/Task/First-class-functions-Use-numbers-analogously/jq/first-class-functions-use-numbers-analogously.jq b/Task/First-class-functions-Use-numbers-analogously/Jq/first-class-functions-use-numbers-analogously.jq similarity index 100% rename from Task/First-class-functions-Use-numbers-analogously/jq/first-class-functions-use-numbers-analogously.jq rename to Task/First-class-functions-Use-numbers-analogously/Jq/first-class-functions-use-numbers-analogously.jq diff --git a/Task/First-class-functions-Use-numbers-analogously/Kotlin/first-class-functions-use-numbers-analogously.kotlin b/Task/First-class-functions-Use-numbers-analogously/Kotlin/first-class-functions-use-numbers-analogously.kotlin new file mode 100644 index 0000000000..81bbee4ed8 --- /dev/null +++ b/Task/First-class-functions-Use-numbers-analogously/Kotlin/first-class-functions-use-numbers-analogously.kotlin @@ -0,0 +1,18 @@ +// version 1.1.2 + +fun multiplier(n1: Double, n2: Double) = { m: Double -> n1 * n2 * m} + +fun main(args: Array) { + val x = 2.0 + val xi = 0.5 + val y = 4.0 + val yi = 0.25 + val z = x + y + val zi = 1.0 / ( x + y) + val a = doubleArrayOf(x, y, z) + val ai = doubleArrayOf(xi, yi, zi) + val m = 0.5 + for (i in 0 until a.size) { + println("${multiplier(a[i], ai[i])(m)} = multiplier(${a[i]}, ${ai[i]})($m)") + } +} diff --git a/Task/First-class-functions-Use-numbers-analogously/Sidef/first-class-functions-use-numbers-analogously.sidef b/Task/First-class-functions-Use-numbers-analogously/Sidef/first-class-functions-use-numbers-analogously.sidef index 8d76835f0e..55d4b5df3f 100644 --- a/Task/First-class-functions-Use-numbers-analogously/Sidef/first-class-functions-use-numbers-analogously.sidef +++ b/Task/First-class-functions-Use-numbers-analogously/Sidef/first-class-functions-use-numbers-analogously.sidef @@ -1,19 +1,19 @@ func multiplier(n1, n2) { func (n3) { - n1 * n2 * n3; + n1 * n2 * n3 } } -var x = 2.0; -var xi = 0.5; -var y = 4.0; -var yi = 0.25; -var z = (x + y); -var zi = (1 / (x + y)); +var x = 2.0 +var xi = 0.5 +var y = 4.0 +var yi = 0.25 +var z = (x + y) +var zi = (1 / (x + y)) -var numbers = [x, y, z]; -var inverses = [xi, yi, zi]; +var numbers = [x, y, z] +var inverses = [xi, yi, zi] -numbers.pair_with(inverses).each { |g, f| - say multiplier(g, f)(0.5); +for f,g (numbers ~Z inverses) { + say multiplier(f, g)(0.5) } diff --git a/Task/First-class-functions-Use-numbers-analogously/Zkl/first-class-functions-use-numbers-analogously-1.zkl b/Task/First-class-functions-Use-numbers-analogously/Zkl/first-class-functions-use-numbers-analogously-1.zkl new file mode 100644 index 0000000000..6997569094 --- /dev/null +++ b/Task/First-class-functions-Use-numbers-analogously/Zkl/first-class-functions-use-numbers-analogously-1.zkl @@ -0,0 +1,2 @@ +var x=2.0, y=4.0, z=(x+y), c=T(x,y,z).apply(fcn(n){ T(n,1.0/n) }); + //-->L(L(2,0.5),L(4,0.25),L(6,0.166667)) diff --git a/Task/First-class-functions-Use-numbers-analogously/Zkl/first-class-functions-use-numbers-analogously-2.zkl b/Task/First-class-functions-Use-numbers-analogously/Zkl/first-class-functions-use-numbers-analogously-2.zkl new file mode 100644 index 0000000000..5590a71891 --- /dev/null +++ b/Task/First-class-functions-Use-numbers-analogously/Zkl/first-class-functions-use-numbers-analogously-2.zkl @@ -0,0 +1 @@ +fcn multiplier(n1,n2){ return('*.fp(n1,n2)) } diff --git a/Task/First-class-functions-Use-numbers-analogously/Zkl/first-class-functions-use-numbers-analogously-3.zkl b/Task/First-class-functions-Use-numbers-analogously/Zkl/first-class-functions-use-numbers-analogously-3.zkl new file mode 100644 index 0000000000..b500342918 --- /dev/null +++ b/Task/First-class-functions-Use-numbers-analogously/Zkl/first-class-functions-use-numbers-analogously-3.zkl @@ -0,0 +1 @@ +fcn multiplier(n1,n2){ fcn(n,X){ n*X }.fp(n1*n2) } diff --git a/Task/First-class-functions-Use-numbers-analogously/Zkl/first-class-functions-use-numbers-analogously-4.zkl b/Task/First-class-functions-Use-numbers-analogously/Zkl/first-class-functions-use-numbers-analogously-4.zkl new file mode 100644 index 0000000000..2863418a37 --- /dev/null +++ b/Task/First-class-functions-Use-numbers-analogously/Zkl/first-class-functions-use-numbers-analogously-4.zkl @@ -0,0 +1,5 @@ +var ms=c.apply(fcn([(n1,n2)]){ multiplier(n1,n2) }); + //-->L(Deferred,Deferred,Deferred) // lazy eval of n*(1/n)*X +ms.run(True,1.0) //-->L(1,1,1) +ms.run(True,5.0) //-->L(5,5,5) +ms.run(True,0.5) //-->L(0.5,0.5,0.5) diff --git a/Task/First-class-functions/AppleScript/first-class-functions-2.applescript b/Task/First-class-functions/AppleScript/first-class-functions-2.applescript index aee9141485..8c3d64f02d 100644 --- a/Task/First-class-functions/AppleScript/first-class-functions-2.applescript +++ b/Task/First-class-functions/AppleScript/first-class-functions-2.applescript @@ -1,30 +1,30 @@ -on run {} +on run - set lstFn to {sin_, cos_, cube_} - set lstInvFn to {asin_, acos_, croot_} + set fs to {sin_, cos_, cube_} + set afs to {asin_, acos_, croot_} -- Form a list of three composed function objects, -- and map testWithHalf() across the list to produce the results of -- application of each composed function (base function composed with inverse) to 0.5 - map(testWithHalf, zipWith(mCompose, lstFn, lstInvFn)) + script testWithHalf + on |λ|(f) + mReturn(f)'s |λ|(0.5) + end |λ| + end script + map(testWithHalf, zipWith(mCompose, fs, afs)) --> {0.5, 0.5, 0.5} - end run -on testWithHalf(mf) - mf's lambda(0.5) -end testWithHalf - -- Simple composition of two unadorned handlers into -- a method of a script object on mCompose(f, g) script - on lambda(x) - mReturn(f)'s lambda(mReturn(g)'s lambda(x)) - end lambda + on |λ|(x) + mReturn(f)'s |λ|(mReturn(g)'s |λ|(x)) + end |λ| end script end mCompose @@ -34,7 +34,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -47,37 +47,31 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn -- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] on zipWith(f, xs, ys) - set nx to length of xs - set ny to length of ys - if nx < 1 or ny < 1 then - {} - else - set lng to cond(nx < ny, nx, ny) - set lst to {} - tell mReturn(f) - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, item i of ys) - end repeat - return lst - end tell - end if + set lng to min(length of xs, length of ys) + set lst to {} + tell mReturn(f) + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, item i of ys) + end repeat + return lst + end tell end zipWith --- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b) -on cond(bool, f, g) - if bool then - f +-- min :: Ord a => a -> a -> a +on min(x, y) + if y < x then + y else - g + x end if -end cond +end min on sin:r (do shell script "echo 's(" & r & ")' | bc -l") as real diff --git a/Task/First-class-functions/Elena/first-class-functions.elena b/Task/First-class-functions/Elena/first-class-functions.elena index 6b7c462f7a..7b9a493263 100644 --- a/Task/First-class-functions/Elena/first-class-functions.elena +++ b/Task/First-class-functions/Elena/first-class-functions.elena @@ -1,19 +1,18 @@ -#import system. -#import system'routines. -#import system'math. -#import extensions'routines. +import system'routines. +import system'math. +import extensions'routines. -#class(extension)op +extension op { - #method compose : f : g - = (self::g eval)::f eval. + compose : f : g + = (self~g eval)~f eval. } -#symbol program = +program = [ - #var fs := (%"mathOp.sin[0]", %"mathOp.cos[0]", ()[ this power:3.0r ]). - #var gs := (%"mathOp.arcsin[0]", %"mathOp.arccos[0]", ()[ this power:(1.0r / 3) ]). + var fs := (%"mathOp.sin[0]", %"mathOp.cos[0]", [ ^ closure power:3.0r ]). + var gs := (%"mathOp.arcsin[0]", %"mathOp.arccos[0]", [ ^ closure power:(1.0r / 3) ]). - fs zip:gs &into: (:f:g)[ 0.5r compose:f:g ] - run &each:printingLn. + fs zip:gs by(:f:g)( 0.5r compose(f,g) ); + forEach:printingLn. ]. diff --git a/Task/First-class-functions/FreeBASIC/first-class-functions.freebasic b/Task/First-class-functions/FreeBASIC/first-class-functions.freebasic new file mode 100644 index 0000000000..2ae600e88f --- /dev/null +++ b/Task/First-class-functions/FreeBASIC/first-class-functions.freebasic @@ -0,0 +1,73 @@ +' FB 1.05.0 Win64 + +#Include "crt/math.bi" '' include math functions in C runtime library + +' Declare function pointer type +' This implicitly assumes default StdCall calling convention on Windows +Type Class2Func As Function(As Double) As Double + +' A couple of functions with the above prototype +Function functionA(v As Double) As Double + Return v*v*v '' cube of v +End Function + +Function functionB(v As Double) As Double + Return Exp(Log(v)/3) '' same as cube root of v which would normally be v ^ (1.0/3.0) in FB +End Function + +' A function taking a function as an argument +Function function1(f2 As Class2Func, val_ As Double) As Double + Return f2(val_) +End Function + +' A function returning a function +Function whichFunc(idx As Long) As Class2Func + Return IIf(idx < 4, @functionA, @functionB) +End Function + +' Additional function needed to treat CDecl function pointer as StdCall +' Get compiler warning otherwise +Function cl2(f As Function CDecl(As Double) As Double) As Class2Func + Return CPtr(Class2Func, f) +End Function + +' A list of functions +' Using C Runtime library versions of trig functions as it doesn't appear +' to be possible to apply address operator (@) to FB's built-in versions +Dim funcListA(0 To 3) As Class2Func = {@functionA, cl2(@sin_), cl2(@cos_), cl2(@tan_)} +Dim funcListB(0 To 3) As Class2Func = {@functionB, cl2(@asin_), cl2(@acos_), cl2(@atan_)} + +' Composing Functions +Function invokeComposed(f1 As Class2Func, f2 As Class2Func, val_ As double) As Double + Return f1(f2(val_)) +End Function + +Type Composition + As Class2Func f1, f2 +End Type + +Function compose(f1 As Class2Func, f2 As Class2Func) As Composition Ptr + Dim comp As Composition Ptr = Allocate(SizeOf(Composition)) + comp->f1 = f1 + comp->f2 = f2 + Return comp +End Function + +Function callComposed(comp As Composition Ptr, val_ As Double ) As Double + Return comp->f1(comp->f2(val_)) +End Function + +Dim ix As Integer +Dim c As Composition Ptr + +Print "function1(functionA, 3.0) = "; CSng(function1(whichFunc(0), 3.0)) +Print +For ix = 0 To 3 + c = compose(funcListA(ix), funcListB(ix)) + Print "Composition"; ix; "(0.9) = "; CSng(callComposed(c, 0.9)) +Next + +Deallocate(c) +Print +Print "Press any key to quit" +Sleep diff --git a/Task/First-class-functions/J/first-class-functions-3.j b/Task/First-class-functions/J/first-class-functions-3.j new file mode 100644 index 0000000000..d4025c4189 --- /dev/null +++ b/Task/First-class-functions/J/first-class-functions-3.j @@ -0,0 +1,21 @@ + train =. (<'`:')(0:`)(,^:)&6 NB. Producing the function train corresponding to the functional `:6 + inverse=. (<'^:')(0:`)(,^:)&_1 NB. Producing the function inverse corresponding to the functional ^:_1 + compose=. (<'@:')(0:`)(,^:) NB. Producing the function compose corresponding to the functional @: + an =. <@:((,'0') ; ]) NB. Producing the atomic representation of a noun + of =. train@:([ ; an) NB. Evaluating a function for an argument + box =. < @: train"0 NB. Producing a boxed list of the trains of the components + + ]A =. box (1&o.)`(2&o.)`(^&3) NB. Producing a boxed list containing the Sin, Cos and Cubic functions +┌────┬────┬───┐ +│1&o.│2&o.│^&3│ +└────┴────┴───┘ + ]B =. inverse &.> A NB. Producing their inverses +┌────────┬────────┬───────┐ +│1&o.^:_1│2&o.^:_1│^&3^:_1│ +└────────┴────────┴───────┘ + ]BA=. B compose &.> A NB. Producing the compositions of the functions and their inverses +┌────────────────┬────────────────┬──────────────┐ +│1&o.^:_1@:(1&o.)│2&o.^:_1@:(2&o.)│^&3^:_1@:(^&3)│ +└────────────────┴────────────────┴──────────────┘ + BA of &> 0.5 NB. Evaluating the compositions at 0.5 +0.5 0.5 0.5 diff --git a/Task/First-class-functions/Kotlin/first-class-functions.kotlin b/Task/First-class-functions/Kotlin/first-class-functions.kotlin new file mode 100644 index 0000000000..9f588d516f --- /dev/null +++ b/Task/First-class-functions/Kotlin/first-class-functions.kotlin @@ -0,0 +1,12 @@ +// version 1.0.6 + +fun compose(f: (Double) -> Double, g: (Double) -> Double ): (Double) -> Double = { f(g(it)) } + +fun cube(d: Double) = d * d * d + +fun main(args: Array) { + val listA = listOf(Math::sin, Math::cos, ::cube) + val listB = listOf(Math::asin, Math::acos, Math::cbrt) + val x = 0.5 + for (i in 0..2) println(compose(listA[i], listB[i])(x)) +} diff --git a/Task/First-class-functions/Lambdatalk/first-class-functions.lambdatalk b/Task/First-class-functions/Lambdatalk/first-class-functions.lambdatalk new file mode 100644 index 0000000000..856b478a3e --- /dev/null +++ b/Task/First-class-functions/Lambdatalk/first-class-functions.lambdatalk @@ -0,0 +1,14 @@ +{def cube {lambda {:x} {pow :x 3}}} +{def cuberoot {lambda {:x} {pow :x {/ 1 3}}}} +{def compose {lambda {:f :g :x} {:f {:g :x}}}} +{def fun sin cos cube} +{def inv asin acos cuberoot} +{def display {lambda {:i} + {br}{compose {nth :i {fun}} + {nth :i {inv}} 0.5}}} +{map display {serie 0 2}} + +Output: +0.5 +0.49999999999999994 +0.5000000000000001 diff --git a/Task/First-class-functions/NewLISP/first-class-functions.newlisp b/Task/First-class-functions/NewLISP/first-class-functions.newlisp new file mode 100644 index 0000000000..8c86b0b58e --- /dev/null +++ b/Task/First-class-functions/NewLISP/first-class-functions.newlisp @@ -0,0 +1,12 @@ +> (define (compose f g) (expand (lambda (x) (f (g x))) 'f 'g)) +(lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g)) +> (define (cube x) (pow x 3)) +(lambda (x) (pow x 3)) +> (define (cube-root x) (pow x (div 1 3))) +(lambda (x) (pow x (div 1 3))) +> (define functions '(sin cos cube)) +(sin cos cube) +> (define inverses '(asin acos cube-root)) +(asin acos cube-root) +> (map (fn (f g) ((compose f g) 0.5)) functions inverses) +(0.5 0.5 0.5) diff --git a/Task/First-class-functions/PostScript/first-class-functions.ps b/Task/First-class-functions/PostScript/first-class-functions.ps new file mode 100644 index 0000000000..bd3c4671c5 --- /dev/null +++ b/Task/First-class-functions/PostScript/first-class-functions.ps @@ -0,0 +1,23 @@ +% PostScript has 'sin' and 'cos', but not these +/asin { dup dup 1. add exch 1. exch sub mul sqrt atan } def +/acos { dup dup 1. add exch 1. exch sub mul sqrt exch atan } def + +/cube { 3 exp } def +/cuberoot { 1. 3. div exp } def + +/compose { % f g -> { g f } + [ 3 1 roll exch + % procedures are not executed when encountered directly + % insert an 'exec' after procedures, but not after operators + 1 index type /operatortype ne { /exec cvx exch } if + dup type /operatortype ne { /exec cvx } if + ] cvx +} def + +/funcs [ /sin load /cos load /cube load ] def +/ifuncs [ /asin load /acos load /cuberoot load ] def + +0 1 funcs length 1 sub { /i exch def + ifuncs i get funcs i get compose + .5 exch exec == +} for diff --git a/Task/First-class-functions/Sidef/first-class-functions.sidef b/Task/First-class-functions/Sidef/first-class-functions.sidef index 2512c1d278..a1c08b4598 100644 --- a/Task/First-class-functions/Sidef/first-class-functions.sidef +++ b/Task/First-class-functions/Sidef/first-class-functions.sidef @@ -1,15 +1,15 @@ func compose(f,g) { func (*args) { - f(g(args...)); + f(g(args...)) } } -var cube = func(a) { a.pow(3) }; -var croot = func(a) { a.root(3) }; +var cube = func(a) { a.pow(3) } +var croot = func(a) { a.root(3) } -var flist1 = [Math.method(:sin), Math.method(:cos), cube]; -var flist2 = [Math.method(:asin), Math.method(:acos), croot]; +var flist1 = [Num.method(:sin), Num.method(:cos), cube] +var flist2 = [Num.method(:asin), Num.method(:acos), croot] -flist1.range.each { |i| - say compose(flist1[i], flist2[i])(0.5); +for a,b (flist1 ~Z flist2) { + say compose(a, b)(0.5) } diff --git a/Task/First-class-functions/Zkl/first-class-functions.zkl b/Task/First-class-functions/Zkl/first-class-functions.zkl new file mode 100644 index 0000000000..4dc1f40f43 --- /dev/null +++ b/Task/First-class-functions/Zkl/first-class-functions.zkl @@ -0,0 +1,8 @@ +var a=T(fcn(x){ x.toRad().sin() }, fcn(x){ x.toRad().cos() }, fcn(x){ x*x*x} ); +var b=T(fcn(x){ x.asin().toDeg() }, fcn(x){ x.acos().toDeg() }, fcn(x){ x.pow(1.0/3) }); + +var H=Utils.Helpers; +var ab=b.zipWith(H.fcomp,a); //-->list of deferred calculations +ab.run(True,5.0); //-->L(5.0,5.0,5.0) + +a.run(True,5.0) //-->L(0.0871557,0.996195,125) diff --git a/Task/Five-weekends/AppleScript/five-weekends-2.applescript b/Task/Five-weekends/AppleScript/five-weekends-2.applescript index 8c621b45dd..d06ec576a3 100644 --- a/Task/Five-weekends/AppleScript/five-weekends-2.applescript +++ b/Task/Five-weekends/AppleScript/five-weekends-2.applescript @@ -1,44 +1,47 @@ +-- TEST ----------------------------------------------------------------------- on run fiveWeekends(1900, 2100) end run +-- FIVE WEEKENDS -------------------------------------------------------------- + -- fiveWeekends :: Int -> Int -> Record on fiveWeekends(fromYear, toYear) - set lstYears to range(fromYear, toYear) + set lstYears to enumFromTo(fromYear, toYear) -- yearMonthString :: (Int, Int) -> String script yearMonthString - on lambda(lstYearMonth) + on |λ|(lstYearMonth) ((item 1 of lstYearMonth) as string) & " " & ¬ item (item 2 of lstYearMonth) of ¬ {"January", "", "March", "", "May", "", ¬ "July", "August", "", "October", "", "December"} - end lambda + end |λ| end script -- addLongMonthsOfYear :: [(Int, Int)] -> [(Int, Int)] script addLongMonthsOfYear - on lambda(lstYearMonth, intYear) + on |λ|(lstYearMonth, intYear) -- yearMonth :: Int -> (Int, Int) script yearMonth - on lambda(intMonth) - return {intYear, intMonth} - end lambda + on |λ|(intMonth) + {intYear, intMonth} + end |λ| end script lstYearMonth & ¬ map(yearMonth, my longMonthsStartingFriday(intYear)) - end lambda + end |λ| end script -- leanYear :: Int -> Bool script leanYear - on lambda(intYear) + on |λ|(intYear) 0 = length of longMonthsStartingFriday(intYear) - end lambda + end |λ| end script set lstFullMonths to map(yearMonthString, ¬ @@ -46,32 +49,26 @@ on fiveWeekends(fromYear, toYear) set lstLeanYears to filter(leanYear, lstYears) - return {{|number|:length of lstFullMonths}, ¬ + {{|number|:length of lstFullMonths}, ¬ {firstFive:(items 1 thru 5 of lstFullMonths)}, ¬ {lastFive:(items -5 thru -1 of lstFullMonths)}, ¬ {leanYearCount:length of lstLeanYears}, ¬ {leanYears:lstLeanYears}} end fiveWeekends - -- longMonthsStartingFriday :: Int -> [Int] on longMonthsStartingFriday(intYear) -- startIsFriday :: Int -> Bool script startIsFriday - on lambda(iMonth) + on |λ|(iMonth) weekday of calendarDate(intYear, iMonth, 1) is Friday - end lambda + end |λ| end script filter(startIsFriday, [1, 3, 5, 7, 8, 10, 12]) end longMonthsStartingFriday - ---------------------------------------------------------------------------- - --- GENERIC FUNCTIONS - -- calendarDate :: Int -> Int -> Int -> Date on calendarDate(intYear, intMonth, intDay) tell (current date) @@ -81,6 +78,50 @@ on calendarDate(intYear, intMonth, intDay) end tell end calendarDate +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- enumFromTo :: Enum a => a -> a -> [a] +on enumFromTo(m, n) + set {intM, intN} to {fromEnum(m), fromEnum(n)} + + if intM > intN then + set d to -1 + else + set d to 1 + end if + set lst to {} + if class of m is text then + repeat with i from intM to intN by d + set end of lst to chr(i) + end repeat + else + repeat with i from intM to intN by d + set end of lst to i + end repeat + end if + return lst +end enumFromTo + +-- fromEnum :: Enum a => a -> Int +on fromEnum(x) + set c to class of x + if c is boolean then + if x then + 1 + else + 0 + end if + else if c is text then + if x ≠ "" then + id of x + else + missing value + end if + else + x as integer + end if +end fromEnum + -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) tell mReturn(f) @@ -88,7 +129,7 @@ on filter(f, xs) set lng to length of xs repeat with i from 1 to lng set v to item i of xs - if lambda(v, i, xs) then set end of lst to v + if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell @@ -100,7 +141,7 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -112,25 +153,12 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then - set d to -1 - else - set d to 1 - end if - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -139,7 +167,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Five-weekends/Gambas/five-weekends.gambas b/Task/Five-weekends/Gambas/five-weekends.gambas new file mode 100644 index 0000000000..af0ba5b9b7 --- /dev/null +++ b/Task/Five-weekends/Gambas/five-weekends.gambas @@ -0,0 +1,38 @@ +Public Sub Main() +Dim aMonth As Short[] = [1, 3, 5, 7, 8, 10, 12] 'All 31 day months +Dim aMMStore As New String[] 'To store results +Dim siYear, siMonth, siCount As Short 'Various variables +Dim dDay As Date 'To store the day to check +Dim sTemp As String 'Temp string + +For siYear = 1900 To 2100 'Loop through each year + For siMonth = 0 To 6 'Loop through each 31 day month + dDay = Date(siYear, aMonth[siMonth], 1) 'Get the date of the 1st of the month + If WeekDay(dDay) = 5 Then aMMStore.Add(Format(dDay, "mmmm yyyy")) 'If the 1st is a Friday then store the result + Next +Next + +For Each sTemp In aMMStore 'For each item in the stored array.. + Inc siCount 'Increase siCount + If siCount < 6 Then Print aMMStore[siCount] 'If 1 of the 1st 5 dates then print it + If siCount = 6 Then Print String$(14, "-") 'Print a separator + If siCount > aMMStore.Max - 4 Then Print aMMStore[siCount - 1] 'If 1 of the last 5 dates then print it +Next + +Print gb.NewLine & "Total months = " & Str(siCount) 'Print the number of months found + +siCount = 0 'Reset siCount +sTemp = aMMStore.Join(",") 'Put all the stored dates in one string joined by commas +aMMStore.Clear 'Clear the store for reuse + +For siYear = 1900 To 2100 'Loop through each year + If Not InStr(sTemp, Str(siYear)) Then 'If the year is not in the stored string then.. + Inc siCount 'Increase siCount (Amount of years that don't have 5 weekend months) + aMMStore.Add(Str(siYear)) 'Add to the store + End If +Next + +Print gb.NewLine & "There are " & Str(siCount) & + " years that do not have at least one five-weekend month" 'Print the amount of years with no 5 weekend months +Print aMMStore.Join(",") 'Print the years with no 5 weekend months +End diff --git a/Task/Five-weekends/Haskell/five-weekends.hs b/Task/Five-weekends/Haskell/five-weekends-1.hs similarity index 100% rename from Task/Five-weekends/Haskell/five-weekends.hs rename to Task/Five-weekends/Haskell/five-weekends-1.hs diff --git a/Task/Five-weekends/Haskell/five-weekends-2.hs b/Task/Five-weekends/Haskell/five-weekends-2.hs new file mode 100644 index 0000000000..8a5b10511f --- /dev/null +++ b/Task/Five-weekends/Haskell/five-weekends-2.hs @@ -0,0 +1,47 @@ +import Data.Time (Day, fromGregorian, gregorianMonthLength) +import Data.Time.Calendar.WeekDate (toWeekDate) +import Data.List.Split (chunksOf) +import Data.List (intercalate) + + +-- MONTHS WITH FIVE WEEKENDS -------------------------------------------------- +fiveFridayMonths :: Integer -> [(Integer, Int)] +fiveFridayMonths y = + [1 .. 12] >>= + \m -> + [ (y, m) + | isFriday (fromGregorian y m 1) + , gregorianMonthLength y m == 31 ] + +isFriday :: Day -> Bool +isFriday d = + let (_, _, day) = toWeekDate d + in day == 5 + + +-- TEST ----------------------------------------------------------------------- +main :: IO () +main = do + let years = [1900 .. 2100] + xs = fiveFridayMonths <$> years + lean = + concat $ + zipWith + (\months year -> + [ year + | null months ]) + xs + years + n = (length . concat) xs + (putStrLn . intercalate "\n\n") + [ "How many five-weekend months 1900-2100 ?" + , '\t' : show n + , "First five ?" + , '\t' : show (concat (take 5 xs)) + , "Last five ?" + , '\t' : show (concat (drop (n - 5) xs)) + , "How many lean years ? (No five-weekend months)" + , '\t' : show (length lean) + , "Which years are lean ?" + , unlines (('\t' :) <$> fmap (unwords . fmap show) (chunksOf 5 lean)) + ] diff --git a/Task/Five-weekends/JavaScript/five-weekends-3.js b/Task/Five-weekends/JavaScript/five-weekends-3.js index e38d24fccd..c32a2dd057 100644 --- a/Task/Five-weekends/JavaScript/five-weekends-3.js +++ b/Task/Five-weekends/JavaScript/five-weekends-3.js @@ -1,7 +1,6 @@ (function () { 'use strict'; - // longMonthsStartingFriday :: Int -> Int function longMonthsStartingFriday(y) { return [0, 2, 4, 6, 7, 9, 11] @@ -11,7 +10,6 @@ }); } - // range :: Int -> Int -> [Int] function range(m, n) { return Array.apply(null, Array(n - m + 1)) @@ -53,5 +51,4 @@ }, null, 2 ); - })(); diff --git a/Task/Five-weekends/JavaScript/five-weekends-4.js b/Task/Five-weekends/JavaScript/five-weekends-4.js new file mode 100644 index 0000000000..4ebc0271f1 --- /dev/null +++ b/Task/Five-weekends/JavaScript/five-weekends-4.js @@ -0,0 +1,60 @@ +(() => { + // longMonthsStartingFriday :: Int -> [Int] + const longMonthsStartingFriday = y => + filter(m => (new Date(Date.UTC(y, m, 1))) + .getDay() === 5, [0, 2, 4, 6, 7, 9, 11]); + + // Years -> YearMonths + // fullMonths :: [Int] -> [String] + const fullMonths = xs => + foldl((a, y) => a.concat( + map(m => `${y.toString()} ${[ + 'January', '', 'March', '', 'May', '', + 'July', 'August', '', 'October', '', 'December' + ][m]}`, longMonthsStartingFriday(y)) + ), [], xs); + + // leanYears :: [Int] -> [Int] + const leanYears = years => + filter(y => longMonthsStartingFriday(y) + .length === 0, years); + + // GENERIC ---------------------------------------------------------------- + + // A list of functions applied to a list of arguments + // <*> :: [(a -> b)] -> [a] -> [b] + const ap = (fs, xs) => // + [].concat.apply([], fs.map(f => // + [].concat.apply([], xs.map(x => [f(x)])))); + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // filter :: (a -> Bool) -> [a] -> [a] + const filter = (f, xs) => xs.filter(f); + + // foldl :: (b -> a -> b) -> b -> [a] -> b + const foldl = (f, a, xs) => xs.reduce(f, a); + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // show :: a -> String + const show = x => JSON.stringify(x, null, 2); + + + // TEST ------------------------------------------------------------------- + const [lstFullMonths, lstLeanYears] = ap( + [fullMonths, leanYears], [enumFromTo(1900, 2100)] + ); + + return show({ + number: lstFullMonths.length, + firstFive: lstFullMonths.slice(0, 5), + lastFive: lstFullMonths.slice(-5), + leanYearCount: lstLeanYears.length + }); +})(); diff --git a/Task/Five-weekends/jq/five-weekends-1.jq b/Task/Five-weekends/Jq/five-weekends-1.jq similarity index 100% rename from Task/Five-weekends/jq/five-weekends-1.jq rename to Task/Five-weekends/Jq/five-weekends-1.jq diff --git a/Task/Five-weekends/jq/five-weekends-2.jq b/Task/Five-weekends/Jq/five-weekends-2.jq similarity index 100% rename from Task/Five-weekends/jq/five-weekends-2.jq rename to Task/Five-weekends/Jq/five-weekends-2.jq diff --git a/Task/Five-weekends/jq/five-weekends-3.jq b/Task/Five-weekends/Jq/five-weekends-3.jq similarity index 100% rename from Task/Five-weekends/jq/five-weekends-3.jq rename to Task/Five-weekends/Jq/five-weekends-3.jq diff --git a/Task/Five-weekends/jq/five-weekends-4.jq b/Task/Five-weekends/Jq/five-weekends-4.jq similarity index 100% rename from Task/Five-weekends/jq/five-weekends-4.jq rename to Task/Five-weekends/Jq/five-weekends-4.jq diff --git a/Task/Five-weekends/K/five-weekends.k b/Task/Five-weekends/K/five-weekends.k new file mode 100644 index 0000000000..aec57a32b6 --- /dev/null +++ b/Task/Five-weekends/K/five-weekends.k @@ -0,0 +1,14 @@ +cal_j:(_jd[19000101]+!(-/_jd 21010101 19000101)) / enumerate the calendar +is_we:(cal_j!7) _lin 4 5 6 / identify friday saturdays and sundays +m:__dj[cal_j]%100 / label the months +mi:&15=+/'is_we[=m] / group by month and sum the weekend days +`0:,"There are ",($#mi)," months with five weekends" +m5:(?m)[mi] +`0:$5#m5 +`0:,"..." +`0:$-5#m5 +y:1900+!201 / enumerate the years in the range +y5:?_ m5%100 / label the years of the months +yn5:y@&~y _lin y5 / find any years not in the 5 weekend month list +`0:,"There are ",($#yn5)," years without any five-weekend months" +`0:,1_,/",",/:$yn5 diff --git a/Task/Five-weekends/Kotlin/five-weekends.kotlin b/Task/Five-weekends/Kotlin/five-weekends.kotlin new file mode 100644 index 0000000000..8048904b44 --- /dev/null +++ b/Task/Five-weekends/Kotlin/five-weekends.kotlin @@ -0,0 +1,27 @@ +// version 1.0.6 + +import java.util.* + +fun main(args: Array) { + val calendar = GregorianCalendar(1900, 0, 1) + val months31 = arrayOf(1, 3, 5, 7, 8, 10, 12) + val monthsWithFive = mutableListOf() + val yearsWithNone = mutableListOf() + for (year in 1900..2100) { + var countInYear = 0 // counts months in a given year with 5 weekends + for (month in 1..12) { + if ((month in months31) && (Calendar.FRIDAY == calendar[Calendar.DAY_OF_WEEK])) { + countInYear++ + monthsWithFive.add("%02d".format(month) + "-" + year) + } + calendar.add(Calendar.MONTH, 1) + } + if (countInYear == 0) yearsWithNone.add(year) + } + println("There are ${monthsWithFive.size} months with 5 weekends") + println("The first 5 are ${monthsWithFive.take(5)}") + println("The final 5 are ${monthsWithFive.takeLast(5)}") + println() + println("There are ${yearsWithNone.size} years with no months which have 5 weekends, namely:") + println(yearsWithNone) +} diff --git a/Task/Five-weekends/Racket/five-weekends-1.rkt b/Task/Five-weekends/Racket/five-weekends-1.rkt deleted file mode 100644 index 31dcecae17..0000000000 --- a/Task/Five-weekends/Racket/five-weekends-1.rkt +++ /dev/null @@ -1,26 +0,0 @@ -#lang racket -(require srfi/19) - -(define long-months '(1 3 5 7 8 10 12)) -(define days #(sun mon tue wed thu fri sat)) - -(define (week-day date) - (vector-ref days (date-week-day date))) - -(define (five-weekends-a-month start end) - (for*/list ([year (in-range start (+ end 1))] - [month long-months] - [date (in-value (make-date 0 0 0 0 31 month year 0))] - #:when (eq? (week-day date) 'sun)) - date)) - -(define weekends (five-weekends-a-month 1900 2100)) -(define count (length weekends)) - -(displayln (~a "There are " count " weeks with five weekends.")) -(displayln "The first five are: ") -(for ([w (take weekends 5)]) - (displayln (date->string w "~b ~Y"))) -(displayln "The last five are: ") -(for ([w (drop weekends (- count 5))]) - (displayln (date->string w "~b ~Y"))) diff --git a/Task/Five-weekends/Racket/five-weekends-2.rkt b/Task/Five-weekends/Racket/five-weekends-2.rkt deleted file mode 100644 index f63c3b0379..0000000000 --- a/Task/Five-weekends/Racket/five-weekends-2.rkt +++ /dev/null @@ -1,13 +0,0 @@ -There are 201 weeks with five weekends. -The first five are: -Mar 1901 -Aug 1902 -May 1903 -Jan 1904 -Jul 1904 -The last five are: -Mar 2097 -Aug 2098 -May 2099 -Jan 2100 -Oct 2100 diff --git a/Task/Five-weekends/Simula/five-weekends.simula b/Task/Five-weekends/Simula/five-weekends.simula new file mode 100644 index 0000000000..5806992401 --- /dev/null +++ b/Task/Five-weekends/Simula/five-weekends.simula @@ -0,0 +1,89 @@ +! TRANSLATION OF FREEBASIC VERSION ; +BEGIN + + INTEGER PROCEDURE WD(M, D, Y); INTEGER M, D, Y; + BEGIN + ! ZELLERISH + ! 0 = SUNDAY, 1 = MONDAY, 2 = TUESDAY, 3 = WEDNESDAY + ! 4 = THURSDAY, 5 = FRIDAY, 6 = SATURDAY + ; + + IF M < 3 THEN ! IF M = 1 OR M = 2 THEN ; + BEGIN + M := M + 12; + Y := Y - 1 + END; + WD := MOD(Y + (Y // 4) + - (Y // 100) + + (Y // 400) + + D + ((153 * M + 8) // 5), 7) + END WD; + + ! ------=< MAIN >=------ + ! ONLY MONTHS WITH 31 DAY CAN HAVE FIVE WEEKENDS + ! THESE MONTHS ARE: JANUARY, MARCH, MAY, JULY, AUGUST, OCTOBER, DECEMBER + ! IN NR: 1, 3, 5, 7, 8, 10, 12 + ! THE 1E DAY NEEDS TO BE ON A FRIDAY (= 5) + ; + + TEXT PROCEDURE MONTHNAMES(M); INTEGER M; + MONTHNAMES :- IF M = 1 THEN "JANUARY" + ELSE IF M = 2 THEN "FEBRUARY" + ELSE IF M = 3 THEN "MARCH" + ELSE IF M = 4 THEN "APRIL" + ELSE IF M = 5 THEN "MAY" + ELSE IF M = 6 THEN "JUNE" + ELSE IF M = 7 THEN "JULY" + ELSE IF M = 8 THEN "AUGUST" + ELSE IF M = 9 THEN "SEPTEMBER" + ELSE IF M = 10 THEN "OCTOBER" + ELSE IF M = 11 THEN "NOVEMBER" + ELSE IF M = 12 THEN "DECEMBER" + ELSE NOTEXT; + + INTEGER M, YR, TOTAL, I, J; + INTEGER ARRAY YR_WITHOUT(1:200); + TEXT ANSWER; + + FOR YR := 1900 STEP 1 UNTIL 2100 DO ! GREGORIAN CALENDAR ; + BEGIN + ANSWER :- NOTEXT; + FOR M := 1 STEP 2 UNTIL 12 DO + BEGIN + IF M = 9 THEN M := 8; + IF WD(M, 1, YR) = 5 THEN + BEGIN + ANSWER :- ANSWER & MONTHNAMES(M) & ", "; + TOTAL := TOTAL + 1 + END + END; + IF ANSWER =/= NOTEXT THEN + BEGIN + OUTIMAGE; + OUTINT(YR, 4); OUTTEXT(" | "); + OUTTEXT(ANSWER.SUB(1, ANSWER.LENGTH - 2)) ! GET RID OF EXTRA " ," ; + END + ELSE + BEGIN + I := I + 1; + YR_WITHOUT(I) := YR + END + END; + + OUTIMAGE; + OUTTEXT("NR OF MONTH FOR 1900 TO 2100 THAT HAS FIVE WEEKENDS "); + OUTINT(TOTAL, 0); + OUTIMAGE; + OUTIMAGE; + OUTINT(I, 0); + OUTTEXT(" YEARS DON'T HAVE MONTHS WITH FIVE WEEKENDS"); + OUTIMAGE; + + FOR J := 1 STEP 1 UNTIL I DO + BEGIN + OUTINT(YR_WITHOUT(J), 0); OUTCHAR(' '); + IF MOD(J, 8) = 0 THEN OUTIMAGE + END; + OUTIMAGE + +END. diff --git a/Task/Five-weekends/Zkl/five-weekends-1.zkl b/Task/Five-weekends/Zkl/five-weekends-1.zkl new file mode 100644 index 0000000000..5dc322bdd6 --- /dev/null +++ b/Task/Five-weekends/Zkl/five-weekends-1.zkl @@ -0,0 +1,4 @@ +var [const] D=Time.Date, r=L(); +foreach y,m in ([1900..2100],[1..12]){ + if (D.daysInMonth(y,m)==31 and 5==D.weekDay(y,m,1)) r.append(String(y,"-",m)) +} diff --git a/Task/Five-weekends/Zkl/five-weekends-2.zkl b/Task/Five-weekends/Zkl/five-weekends-2.zkl new file mode 100644 index 0000000000..74701fa1c5 --- /dev/null +++ b/Task/Five-weekends/Zkl/five-weekends-2.zkl @@ -0,0 +1,3 @@ +r:=[[(y,m); [1900..2100]; + [1..12],{D.daysInMonth(y,m)==31 and 5==D.weekDay(y,m,1)}; + {String(y,"-",m)}]]; diff --git a/Task/Five-weekends/Zkl/five-weekends-3.zkl b/Task/Five-weekends/Zkl/five-weekends-3.zkl new file mode 100644 index 0000000000..cd6b55da28 --- /dev/null +++ b/Task/Five-weekends/Zkl/five-weekends-3.zkl @@ -0,0 +1,7 @@ +var [const] D=Time.Date, r=L(); +foreach y in ([1900..2100]){ yes:=True; + foreach m in ([1..12]){ + if (D.daysInMonth(y,m)==31 and 5==D.weekDay(y,m,1)) { yes=False; break; } + } + if (yes) r.append(y) +} diff --git a/Task/Five-weekends/Zkl/five-weekends-4.zkl b/Task/Five-weekends/Zkl/five-weekends-4.zkl new file mode 100644 index 0000000000..7727c11368 --- /dev/null +++ b/Task/Five-weekends/Zkl/five-weekends-4.zkl @@ -0,0 +1,5 @@ +var yes, r=[[(y,m); + [1900..2100]; + [1..12],{if(m==1)yes=True; if(D.daysInMonth(y,m)==31 and 5==D.weekDay(y,m,1)) yes=False; True}, + {if (m==12) yes else False}; + {y}]] diff --git a/Task/FizzBuzz/360-Assembly/fizzbuzz.360 b/Task/FizzBuzz/360-Assembly/fizzbuzz.360 deleted file mode 100644 index 8840f27c02..0000000000 --- a/Task/FizzBuzz/360-Assembly/fizzbuzz.360 +++ /dev/null @@ -1,86 +0,0 @@ -FIZZBUZZ CSECT A SECTION OF CODE STARTS HERE, LABEL IT FIZZBUZZ -**********HOUSE KEEPING AREA********************** - USING *,12 FOR THIS PROGRAM WE ARE GOING TO USE REGISTER 12 - STM 14,12,12(13) SAVE REGISTERS 14,15, AND 0-12 IN CALLER'S SAVE AREA - LR 12,15 PUT OUR ENTRY ADDRESS(IN R15) INTO OUR BASE REGISTER - LA 15,SAVE POINT R15 AT THE *OUR* SAVE AREA (DEFINED AT THE END) - ST 15,8(13) SET FORWARD CHAIN - ST 13,4(15) SET BACKWARD CHAIN - LR 13,15 SET R13 TO THE ADDRESS OF OUT NEW SAVE AREA -**********MAIN*PROGRAM**************************** - LA 10,LOOP PUT THE LOOP START ADDRESS IN R10 - LA 8,100 PUT THE NUMBER OF ITERATIONS IN R8 - LA 5,=F'1' INITIALIZE BINARY COUNTER TO ONE -LOOP EQU * LABEL THE LOOP START - A 5,=F'1' ADD TO BINARY LOOP COUNTER - AP NUM,=PL1'1' ADD TO PACKED LOOP COUNTER - B CHK15 CHECK IF COUNTER IS % 12 -LCHK15 EQU * IF NOT, COME BACK - B CHK3 CHECK IF COUNTER IS % 3 -LCHK3 EQU * IF NOT, COME BACK - B CHK5 CHECK IF COUNTER IS % 4 -LCHK5 EQU * IF NOT, COME BACK - MVC EOUT,EMSK PREPARE TO PKD->EBCDIC - EDMK EOUT,NUM PKD->EBCDIC -ENLOOP EQU * IF A TEST WAS POSITIVE RETURN HERE - WTO MF=(E,WTOSTART) PRINT RESULT OF LOOP - BCTR 8,10 START OVER -**********HOUSE KEEPING AREA********************** - L 13,4(13) RESTORE ADDRESS TO CALLER'S SAVE AREA - LM 14,12,12(13) RESTORE REGISTERS AS ON ENTRY - XR 15,15 XOR R15 SO IT IS ALL 0 (R15 CREATES THE PROGRAM RETURN CODE) - BR 14 RETURN WHERE YOU CAME FROM -**********SUBROUTINE AREA************************* -*////////CHK3////////////////////////////////////* -CHK3 EQU * LABEL ENTRY POINT - LR 6,5 LOAD R6 WITH R5(THE BINARY LOOP INDEX) - A 6,=F'1' ADD ONE TO R6 - SRDA 6,32 SHIFT RD VAL 32 BITS RIGHT(TO R7) - D 6,=F'3' DIVIDE BY 3 - C 6,=F'0' IS REMAINDER 0? - BE DIV3 IF SO GOTO DIV3 ROUTINE - B LCHK3 IF NOT GO BACK TO LOOP -*////////CHK15///////////////////////////////////* -CHK15 EQU * LABEL ENTRY POINT - LR 6,5 LOAD R6 WITH R5(THE BINARY LOOP INDEX) - A 6,=F'1' ADD ONE TO R6 - SRDA 6,32 SHIFT RD VAL 32 BITS RIGHT(TO R7) - D 6,=F'15' DIVIDE BY 15 - C 6,=F'0' IS REMAINDER 0? - BE DIV15 IF SO GOTO DIV15 ROUTINE - B LCHK15 IF NOT GO BACK TO LOOP -*////////CHK5////////////////////////////////////* -CHK5 EQU * LABEL ENTRY POINT - LR 6,5 LOAD R6 WITH R5(THE BINARY LOOP INDEX) - A 6,=F'1' ADD ONE TO R6 - SRDA 6,32 SHIFT RD VAL 32 BITS RIGHT(TO R7) - D 6,=F'5' DIVIDE BY 5 - C 6,=F'0' IS REMAINDER 0? - BE DIV5 IF SO GOTO DIV5 ROUTINE - B LCHK5 IF NOT GO BACK TO LOOP -*////////////////////////////////////////////////* -DIV3 EQU * LABEL ENRTY POINT - MVC EOUT,FIZZ SAY FIZZ - B ENLOOP RETURN TO LOOP -*////////////////////////////////////////////////* -DIV5 EQU * LABEL ENTRY POINT - MVC EOUT,BUZZ SAY BUZZ - B ENLOOP RETURN TO LOOP -*////////////////////////////////////////////////* -DIV15 EQU * LABEL ENTRY POINT - MVC EOUT,FIZZBUZ SAY FIZZBUZZ - B ENLOOP RETURN TO LOOP -**********VARIABLE STORAGE************************ -FIZZBUZ DC CL10'FIZZBUZZ!' CREATE A STRING IN MEMORY, LABEL THE ADDRESS FIZZBUZ -FIZZ DC CL10'FIZZ!' CREATE A STRING IN MEMORY, LABEL THE ADDRESS FIZZ -BUZZ DC CL10'BUZZ!' CREATE A STRING IN MEMORY, LABEL THE ADDRESS BUZZ -NUM DC PL3'0' CREATE A DECIMAL IN MEMORY, MAKE IT ZERO, LABEL IT NUM -TEMP DS D RESERVE A DOUBLE WORD (8 BYTES) IN MEMORY, LABEL IT TEMP -EMSK DC X'402020202020' CREATE A HEX ARRAY IN MEMORY, LABEL IT EMSK -WTOSTART DC Y(WTOEND-*,0) LABEL THIS WTOSTART, DEFINE A CONSTANT ADDRESS EQUAL TO -* "WTOEND" MINUS HERE(*) -EOUT DS CL10 RESERVE SPACE FOR 10 CHARACTERS, LABEL THIS EOUT -WTOEND EQU * THE MEMORY ADDRESS LOCATED HERE IS LABELED WTOEND -**********HOUSE KEEPING AREA********************** -SAVE DS 18F - END HELLO diff --git a/Task/FizzBuzz/6502-Assembly/fizzbuzz.6502 b/Task/FizzBuzz/6502-Assembly/fizzbuzz.6502 deleted file mode 100644 index 3dae559cde..0000000000 --- a/Task/FizzBuzz/6502-Assembly/fizzbuzz.6502 +++ /dev/null @@ -1,79 +0,0 @@ - .lf fzbz6502.lst - .cr 6502 - .tf fzbz6502.obj,ap1 -;------------------------------------------------------ -; FizzBuzz for the 6502 by barrym95838 2013.04.04 -; Thanks to sbprojects.com for a very nice assembler! -; The target for this assembly is an Apple II with -; mixed-case output capabilities and Applesoft -; BASIC in ROM (or language card) -; Tested and verified on AppleWin 1.20.0.0 -;------------------------------------------------------ -; Constant Section -; -FizzCt = 3 ;Fizz Counter (must be < 255) -BuzzCt = 5 ;Buzz Counter (must be < 255) -Lower = 1 ;Loop start value (must be 1) -Upper = 100 ;Loop end value (must be < 255) -CharOut = $fded ;Specific to the Apple II -IntOut = $ed24 ;Specific to ROM Applesoft -;====================================================== - .or $0f00 -;------------------------------------------------------ -; The main program -; -main ldx #Lower ;init LoopCt - lda #FizzCt - sta Fizz ;init FizzCt - lda #BuzzCt - sta Buzz ;init BuzzCt -next ldy #0 ;reset string pointer (y) - dec Fizz ;LoopCt mod FizzCt == 0? - bne noFizz ; yes: - lda #FizzCt - sta Fizz ; restore FizzCt - ldy #sFizz-str ; point y to "Fizz" - jsr puts ; output "Fizz" -noFizz dec Buzz ;LoopCt mod BuzzCt == 0? - bne noBuzz ; yes: - lda #BuzzCt - sta Buzz ; restore BuzzCt - ldy #sBuzz-str ; point y to "Buzz" - jsr puts ; output "Buzz" -noBuzz dey ;any output yet this cycle? - bpl noInt ; no: - txa ; save LoopCt - pha - lda #0 ; set up regs for IntOut - jsr IntOut ; output itoa(LoopCt) - pla - tax ; restore LoopCt -noInt ldy #sNL-str - jsr puts ;output "\n" - inx ;increment LoopCt - cpx #Upper+1 ;LoopCt >= Upper+1? - bcc next ; no: loop back - rts ; yes: end main -;------------------------------------------------------ -; Output zero-terminated string @ (str+y) -; (Entry point is puts, not outch) -; -outch jsr CharOut ;output string char - iny ;advance string ptr -puts lda str,y ;get a string char - bne outch ;output and loop if non-zero - rts ;return -;------------------------------------------------------ -; String literals (in '+128' ascii, Apple II style) -; -str: ; string base offset -sFizz .az -"Fizz" -sBuzz .az -"Buzz" -sNL .az -#13 -;------------------------------------------------------ -; Variable Section -; -Fizz .da #0 -Buzz .da #0 -;------------------------------------------------------ - .en diff --git a/Task/FizzBuzz/8086-Assembly/fizzbuzz.8086 b/Task/FizzBuzz/8086-Assembly/fizzbuzz.8086 deleted file mode 100644 index c41f2fb723..0000000000 --- a/Task/FizzBuzz/8086-Assembly/fizzbuzz.8086 +++ /dev/null @@ -1,88 +0,0 @@ - ; Init the registers -mov dx,03030h ; For easier printing, the number is - ;kept in Binary Coded Decimal, in ----- - - ;the DX register. -mov ah,0Eh ; 0Eh is the IBM PC interrupt 10h - ;function that does write text on - ;the screen in teletype mode. -mov bl,100d ; BL is the counter (100 numbers). -xor cx,cx ; CX is a counter that will be used - ;for screen printing. -xor bh,bh ; BH is the counter for counting - ;multiples of three. - -writeloop: ; Increment the BCD number in DX. -inc dl ; Increment the low digit -cmp dl,3Ah ; If it does not overflow nine, -jnz writeloop1 ;continue with the program, -mov dl,30h ;otherwise reset it to zero and -inc dh ;increment the high digit -writeloop1: -inc bh ; Increment the BH counter. -cmp bh,03h ; If it reached three, we did - ;increment the number three times - ;from the last time the number was - ;a multiple of three, so the number - ;is now a multiple of three now, -jz writefizz ;then we need to write "fizz" on the - ;screen. -cmp dl,30h ; The number isn't a multiple of -jz writebuzz ;three, so we check if it's a -cmp dl,35h ;multiple of five. If it is, we -jz writebuzz ;need to write "buzz". The program - ;checks if the last digit is zero or - ;five. -mov al,dh ; If we're here, there's no need to -int 10h ;write neither "fizz" nor "buzz", so -mov al,dl ;the program writes the BCD number -int 10h ;in DX -writespace: -mov al,020h ;and a white space. -int 10h -dec bl ; Loop if we didn't process 100 -jnz writeloop ;numbers. - -programend: ; When we did reach 100 numbers, -cli ;the program flow falls here, where -hlt ;interrupts are cleared and the -jmp programend ;program is stopped. - -writefizz: ; There's need to write "fizz": -mov si,offset fizz ; SI points to the "fizz" string, -call write ;that is written on the screen. -xor bh,bh ; BH, the counter for computing the - ;multiples of three, is cleared. -cmp dl,30h ; We did write "fizz", but, if the -jz writebuzz ;number is a multiple of five, we -cmp dl,35h ;could need to write "buzz" also: -jnz writespace ;check if the number is multiple of - ;five. If not, write a space and - ;return to the main loop. -writebuzz: ; (The above code falls here if - ;the last digit is five, otherwise - ;it jumps) -mov si,offset buzz ;SI points to the "buzz" string, -call write ;that is written on the screen. -jmp writespace ; Write a space to return to the main - ;loop. - -write: ; Write subroutine: -mov cl,04h ; Set CX to the lenght of the string: - ;both strings are 4 bytes long. -write1: -mov al,[si] ; Load the character to write in AL. -inc si ; Increment the counter SI. -int 10h ; Call interrupt 10h, function 0Eh to - ;write the character and advance the - ;text cursor (teletype mode) -loop write1 ; Decrement CX: if CX is not zero, do -ret ;loop, otherwise return from - ;subroutine. - -fizz: ;The "fizz" string. -db "fizz" - -buzz: ;The "buzz" string. -db "buzz" diff --git a/Task/FizzBuzz/ABAP/fizzbuzz.abap b/Task/FizzBuzz/ABAP/fizzbuzz-1.abap similarity index 100% rename from Task/FizzBuzz/ABAP/fizzbuzz.abap rename to Task/FizzBuzz/ABAP/fizzbuzz-1.abap diff --git a/Task/FizzBuzz/ABAP/fizzbuzz-2.abap b/Task/FizzBuzz/ABAP/fizzbuzz-2.abap new file mode 100644 index 0000000000..2e2a44ca75 --- /dev/null +++ b/Task/FizzBuzz/ABAP/fizzbuzz-2.abap @@ -0,0 +1,5 @@ +cl_demo_output=>display( VALUE stringtab( FOR i = 1 WHILE i <= 100 ( COND #( LET m3 = i MOD 3 m5 = i MOD 5 IN + WHEN m3 = 0 AND m5 = 0 THEN |FIZZBUZZ| + WHEN m3 = 0 THEN |FIZZ| + WHEN m5 = 0 THEN |BUZZ| + ELSE i ) ) ) ). diff --git a/Task/FizzBuzz/AWK/fizzbuzz-1.awk b/Task/FizzBuzz/AWK/fizzbuzz-1.awk deleted file mode 100644 index 47de5c3719..0000000000 --- a/Task/FizzBuzz/AWK/fizzbuzz-1.awk +++ /dev/null @@ -1,11 +0,0 @@ -BEGIN { - for (NUM=1; NUM<=100; NUM++) - if (NUM % 15 == 0) - {print "FizzBuzz"} - else if (NUM % 3 == 0) - {print "Fizz"} - else if (NUM % 5 == 0) - {print "Buzz"} - else - {print NUM} -} diff --git a/Task/FizzBuzz/AWK/fizzbuzz-2.awk b/Task/FizzBuzz/AWK/fizzbuzz-2.awk deleted file mode 100644 index 8fbaccfadf..0000000000 --- a/Task/FizzBuzz/AWK/fizzbuzz-2.awk +++ /dev/null @@ -1,7 +0,0 @@ -echo {1..100} | awk ' -BEGIN{RS=" "} -$1 % 15 == 0 {print "FizzBuzz"} -$1 % 5 == 0 {print "Buzz"} -$1 % 3 == 0 {print "Fizz"} -{print} -' diff --git a/Task/FizzBuzz/AWK/fizzbuzz-3.awk b/Task/FizzBuzz/AWK/fizzbuzz-3.awk deleted file mode 100644 index b8c6edaa8d..0000000000 --- a/Task/FizzBuzz/AWK/fizzbuzz-3.awk +++ /dev/null @@ -1 +0,0 @@ -seq 100 | awk '$0=NR%15?NR%5?NR%3?$0:"Fizz":"Buzz":"FizzBuzz"' diff --git a/Task/FizzBuzz/Apex/fizzbuzz.apex b/Task/FizzBuzz/Apex/fizzbuzz.apex new file mode 100644 index 0000000000..e3b5900279 --- /dev/null +++ b/Task/FizzBuzz/Apex/fizzbuzz.apex @@ -0,0 +1,10 @@ +for(integer i=1; i <= 100; i++){ + String output = ''; + if(math.mod(i, 3) == 0) output += 'Fizz'; + if(math.mod(i, 5) == 0) output += 'Buzz'; + if(output != ''){ + System.debug(output); + } else { + System.debug(i); + } +} diff --git a/Task/FizzBuzz/AppleScript/fizzbuzz-2.applescript b/Task/FizzBuzz/AppleScript/fizzbuzz-2.applescript index 1df0778bd0..9838c061ca 100644 --- a/Task/FizzBuzz/AppleScript/fizzbuzz-2.applescript +++ b/Task/FizzBuzz/AppleScript/fizzbuzz-2.applescript @@ -1,23 +1,4 @@ -on run - - intercalate(linefeed, ¬ - map(fizzBuzz, range(1, 100))) - -end run - - --- fizzBuzz :: Int -> String -on fizzBuzz(x) - caseOf(x, [[my fizzAndBuzz, "FizzBuzz"], ¬ - [my fizz, "Fizz"], ¬ - [my buzz, "Buzz"]], ¬ - x as string) -end fizzBuzz - --- fizzAndBuzz :: Int -> Bool -on fizzAndBuzz(n) - n mod 15 = 0 -end fizzAndBuzz +-- FIZZBUZZ ------------------------------------------------------------------ -- fizz :: Int -> Bool on fizz(n) @@ -29,18 +10,53 @@ on buzz(n) n mod 5 = 0 end buzz +-- fizzAndBuzz :: Int -> Bool +on fizzAndBuzz(n) + n mod 15 = 0 +end fizzAndBuzz --- GENERIC LIBRARY FUNCTIONS +-- fizzBuzz :: Int -> String +on fizzBuzz(x) + caseOf(x, [[my fizzAndBuzz, "FizzBuzz"], ¬ + [my fizz, "Fizz"], ¬ + [my buzz, "Buzz"]], x as string) +end fizzBuzz + + +-- TEST ---------------------------------------------------------------------- +on run + + intercalate(linefeed, ¬ + map(fizzBuzz, enumFromTo(1, 100))) + +end run + + +-- GENERIC FUNCTIONS --------------------------------------------------------- -- caseOf :: a -> [(predicate, b)] -> Maybe b -> Maybe b on caseOf(e, lstPV, default) repeat with lstCase in lstPV set {p, v} to contents of lstCase - if mReturn(p)'s lambda(e) then return v + if mReturn(p)'s |λ|(e) then return v end repeat return default end caseOf +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo + -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} @@ -55,7 +71,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -68,21 +84,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn - --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then - set d to -1 - else - set d to 1 - end if - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range diff --git a/Task/FizzBuzz/BASIC/fizzbuzz-1.basic b/Task/FizzBuzz/BASIC/fizzbuzz-1.basic deleted file mode 100644 index 5706ae5dcc..0000000000 --- a/Task/FizzBuzz/BASIC/fizzbuzz-1.basic +++ /dev/null @@ -1,11 +0,0 @@ -FOR A = 1 TO 100 - IF A MOD 15 = 0 THEN - PRINT "FizzBuzz" - ELSE IF A MOD 3 = 0 THEN - PRINT "Fizz" - ELSE IF A MOD 5 = 0 THEN - PRINT "Buzz" - ELSE - PRINT A - END IF -NEXT A diff --git a/Task/FizzBuzz/BASIC/fizzbuzz-2.basic b/Task/FizzBuzz/BASIC/fizzbuzz-2.basic deleted file mode 100644 index 5c45404ca3..0000000000 --- a/Task/FizzBuzz/BASIC/fizzbuzz-2.basic +++ /dev/null @@ -1,17 +0,0 @@ -FOR A = 1 TO 100 - OUT$ = "" - - IF A MOD 3 = 0 THEN - OUT$ = "Fizz" - END IF - - IF A MOD 5 = 0 THEN - OUT$ = OUT$ + "Buzz" - END IF - - IF OUT$ = "" THEN - OUT$ = STR$(A) - END IF - - PRINT OUT$ -NEXT A diff --git a/Task/FizzBuzz/BASIC/fizzbuzz-3.basic b/Task/FizzBuzz/BASIC/fizzbuzz-3.basic deleted file mode 100644 index 96de6a181a..0000000000 --- a/Task/FizzBuzz/BASIC/fizzbuzz-3.basic +++ /dev/null @@ -1,8 +0,0 @@ -10 DEF FN M(N) = ((A / N) - INT (A / N)) * N -20 FOR A = 1 TO 100 -30 LET O$ = "" -40 IF FN M(3) = 0 THEN O$ = "FIZZ" -50 IF FN M(5) = 0 THEN O$ = O$ + "BUZZ" -60 IF O$ = "" THEN O$ = STR$ (A) -70 PRINT O$ -80 NEXT A diff --git a/Task/FizzBuzz/BBC-BASIC/fizzbuzz.bbc b/Task/FizzBuzz/BBC-BASIC/fizzbuzz.bbc deleted file mode 100644 index e2723d4492..0000000000 --- a/Task/FizzBuzz/BBC-BASIC/fizzbuzz.bbc +++ /dev/null @@ -1,8 +0,0 @@ - FOR number% = 1 TO 100 - CASE TRUE OF - WHEN number% MOD 15 = 0: PRINT "FizzBuzz" - WHEN number% MOD 3 = 0: PRINT "Fizz" - WHEN number% MOD 5 = 0: PRINT "Buzz" - OTHERWISE: PRINT ; number% - ENDCASE - NEXT number% diff --git a/Task/FizzBuzz/Bc/fizzbuzz.bc b/Task/FizzBuzz/Bc/fizzbuzz.bc new file mode 100644 index 0000000000..fdf42e0f63 --- /dev/null +++ b/Task/FizzBuzz/Bc/fizzbuzz.bc @@ -0,0 +1,9 @@ +for (i = 1; i <= 100; i++) { + w = 0 + if (i % 3 == 0) { "Fizz"; w = 1; } + if (i % 5 == 0) { "Buzz"; w = 1; } + if (w == 0) i + if (w == 1) " +" +} +quit diff --git a/Task/FizzBuzz/Beeswax/fizzbuzz-1.beeswax b/Task/FizzBuzz/Beeswax/fizzbuzz-1.beeswax new file mode 100644 index 0000000000..e5aa87f1c3 --- /dev/null +++ b/Task/FizzBuzz/Beeswax/fizzbuzz-1.beeswax @@ -0,0 +1,4 @@ + > q + >@F5~%"d@F{ > @F q +_1>F3~%'d`Fizz`@F5~%'d >`Buzz`@FNp + ;bL@~.~4~.5~5@ P< diff --git a/Task/FizzBuzz/Beeswax/fizzbuzz-2.beeswax b/Task/FizzBuzz/Beeswax/fizzbuzz-2.beeswax new file mode 100644 index 0000000000..953167e9a2 --- /dev/null +++ b/Task/FizzBuzz/Beeswax/fizzbuzz-2.beeswax @@ -0,0 +1,4 @@ + >@?q + > q >Ag'd@{?p +_>"1F3~%'d`Fizz`f>@F5~%'d`Buzz`@p + b P~;"-~@~.+0~P9@N?< diff --git a/Task/FizzBuzz/Befunge/fizzbuzz.bf b/Task/FizzBuzz/Befunge/fizzbuzz.bf deleted file mode 100644 index 5de7a0e33c..0000000000 --- a/Task/FizzBuzz/Befunge/fizzbuzz.bf +++ /dev/null @@ -1,9 +0,0 @@ -55*4*v _ v -v <>:1-:^ - |:<$ < ,*48 < - @>0"zzif">:#,_$ v ->:3%!| >0"zzub">:#,_$^ - >:5%!| -v "buzz"0<>:. ^ - |!%5: < ->:#,_ $> ^ diff --git a/Task/FizzBuzz/Brainf---/fizzbuzz.bf b/Task/FizzBuzz/Brainf---/fizzbuzz.bf deleted file mode 100644 index 55763f5e35..0000000000 --- a/Task/FizzBuzz/Brainf---/fizzbuzz.bf +++ /dev/null @@ -1,156 +0,0 @@ -FizzBuzz - -Memory: - Zero - Zero - Counter 1 - Counter 2 - - Zero - ASCIIDigit 3 - ASCIIDigit 2 - ASCIIDigit 1 - - Zero - Digit 3 - Digit 2 - Digit 1 - - CopyPlace - Mod 3 - Mod 5 - PrintNumber - - TmpFlag - -Counters for the loop -++++++++++[>++++++++++[>+>+<<-]<-] - -Number representation in ASCII ->>>> -++++++++ ++++++++ ++++++++ ++++++++ ++++++++ ++++++++ [>+>+>+<<<-] -<<<< - ->> -[ - Do hundret times: - - Decrement counter - ->-> - - Increment Number - > >>+> - > >>+> - <<<< - <<<< - - Check for Overflow - ++++++++++ - >>> >>>> - >++++++++++< - [-<<< <<<<->>>> >>> >-<] - ++++++++++ - <<< <<<< - - Restore the digit - [->>>> >>>-<<< <<<<] - >>>> [-]+ >>>>[<<<< - >>>>[-]]<<<< <<<< - - If there is an overflow - >>>>[ - <<<< - - >>>----------> >>>----------<+<< <<+<< - - Check for Overflow - ++++++++++ - >> >>>> - >>++++++++++<< - [-<< <<<<->>>> >> >>-<<] - ++++++++++ - << <<<< - - Restore the digit - [->>>> >>-<< <<<<] - >>>> [-]+ >>>>[<<<< - >>>>[-]]<<<< <<<< - - If there (again) is an overflow - >>>>[ - <<<< - >>---------->> >>----------<+< <<<+< - - >>>> - [-] - ]<<<< - - >>>> - [-] - ]<<<< - - >>>> >>>> - - Set if to print the number - >>>[-]+<<< - - Handle the Mod 3 counter - [-]+++ - - >>>>[-]+<<<< - >+[-<->]+++< - [->->>>[-]<<<<] - >>>>[ - <[-]> - - [-] - Print "Fizz" - ++++++++ ++++++++ ++++++++ ++++++++ - ++++++++ ++++++++ ++++++++ ++++++++ - ++++++. - - ++++++++ ++++++++ ++++++++ ++++++++ - +++. - - ++++++++ ++++++++ +.. - - [-] - <<<--->>> - ]<<<< - - Handle the Mod 5 counter - [-]+++++ - - >>>>[-]+<<<< - >>+[-<<->>]+++++<< - [->>->>[-]<<<<] - >>>>[ - <[-]> - - [-] - Print "Buzz" - ++++++++ ++++++++ ++++++++ ++++++++ - ++++++++ ++++++++ ++++++++ ++++++++ - ++. - - ++++++++ ++++++++ ++++++++ ++++++++ - ++++++++ ++++++++ +++. - - +++++.. - - [-] - <<----->> - ]<<<< - - Check if to print the number (Leading zeros) - >>>[ - <<< <<<< <<<< - >.>.>.<<< - >>> >>>> >>>> - [-] - ]<<< - - <<<< <<<< - - Print New Line - <<<<[-]++++ ++++ ++++ +.---.[-]>> -] -<< diff --git a/Task/FizzBuzz/C/fizzbuzz-1.c b/Task/FizzBuzz/C/fizzbuzz-1.c index d022ac5eb2..3f31c9a1a0 100644 --- a/Task/FizzBuzz/C/fizzbuzz-1.c +++ b/Task/FizzBuzz/C/fizzbuzz-1.c @@ -1,5 +1 @@ -#include - -int main() { - for (int i=1; i<=105; i++) if (i%3 && i%5) printf("%3d ", i); else printf("%s%s%s", i%3?"":"Fizz", i%5?"":"Buzz", i%15?" ":"\n"); -} +for(i=0;i<100;console.log((++i%3?"":"Fizz")+(i%5?"":"Buzz")||i)); diff --git a/Task/FizzBuzz/C/fizzbuzz-10.c b/Task/FizzBuzz/C/fizzbuzz-10.c new file mode 100644 index 0000000000..a3b8a4d01f --- /dev/null +++ b/Task/FizzBuzz/C/fizzbuzz-10.c @@ -0,0 +1,11 @@ +#include + +int main(void) +{ + for (int i = 1; i <= 100; ++i) { + if (i % 3 == 0) printf("fizz"); + if (i % 5 == 0) printf("buzz"); + if (i * i * i * i % 15 == 1) printf("%d", i); + puts(""); + } +} diff --git a/Task/FizzBuzz/C/fizzbuzz-11.c b/Task/FizzBuzz/C/fizzbuzz-11.c new file mode 100644 index 0000000000..6cf2ee6c45 --- /dev/null +++ b/Task/FizzBuzz/C/fizzbuzz-11.c @@ -0,0 +1,10 @@ +#include +int main() +{ + for (int i=0;++i<101;puts("")) + { + char f[] = "FizzBuzz%d"; + f[8-i%5&12]=0; + printf (f+(-i%3&4+f[8]/8), i); + } +} diff --git a/Task/FizzBuzz/C/fizzbuzz-2.c b/Task/FizzBuzz/C/fizzbuzz-2.c index b6e087e7ae..c008160854 100644 --- a/Task/FizzBuzz/C/fizzbuzz-2.c +++ b/Task/FizzBuzz/C/fizzbuzz-2.c @@ -1,20 +1,4 @@ -#include - -int main (void) -{ - int i; - for (i = 1; i <= 100; i++) - { - if (!(i % 15)) - printf ("FizzBuzz"); - else if (!(i % 3)) - printf ("Fizz"); - else if (!(i % 5)) - printf ("Buzz"); - else - printf ("%d", i); - - printf("\n"); - } - return 0; -} + int i = 0 ; char B[88] ; + while ( i++ < 100 ) + !sprintf( B, "%s%s", i%3 ? "":"Fizz", i%5 ? "":"Buzz" ) + ? sprintf( B, "%d", i ):0, printf( ", %s", B ); diff --git a/Task/FizzBuzz/C/fizzbuzz-3.c b/Task/FizzBuzz/C/fizzbuzz-3.c index 10d5072f99..6124ef8007 100644 --- a/Task/FizzBuzz/C/fizzbuzz-3.c +++ b/Task/FizzBuzz/C/fizzbuzz-3.c @@ -1,16 +1,5 @@ -#include - -main() { - int i = 1; - while(i <= 100) { - if(i % 15 == 0) - puts("FizzBuzz"); - else if(i % 3 == 0) - puts("Fizz"); - else if(i % 5 == 0) - puts("Buzz"); - else - printf("%d\n", i); - i++; - } -} + int i = 0 ; char B[88] ; + while ( i++ < 100 ) + !sprintf( B, "%s%s%s%s", + i%3 ? "":"Fiz", i%5 ? "":"Buz", i%7 ? "":"Goz", i%11 ? "":"Kaz" ) + ? sprintf( B, "%d", i ):0, printf( ", %s", B ); diff --git a/Task/FizzBuzz/C/fizzbuzz-4.c b/Task/FizzBuzz/C/fizzbuzz-4.c index daa85416cc..3dec808e25 100644 --- a/Task/FizzBuzz/C/fizzbuzz-4.c +++ b/Task/FizzBuzz/C/fizzbuzz-4.c @@ -1,3 +1 @@ -#include -#define F(x,y) printf("%s",i%x?"":#y"zz") -int main(int i){for(--i;i++^100;puts(""))F(3,Fi)|F(5,Bu)||printf("%i",i);return 0;} +Output: ..., 89, FizBuz, Goz, 92, Fiz, 94, Buz, Fiz, 97, Goz, FizKaz, Buz diff --git a/Task/FizzBuzz/C/fizzbuzz-5.c b/Task/FizzBuzz/C/fizzbuzz-5.c index de8671632b..d022ac5eb2 100644 --- a/Task/FizzBuzz/C/fizzbuzz-5.c +++ b/Task/FizzBuzz/C/fizzbuzz-5.c @@ -1,11 +1,5 @@ -#include +#include -int main () -{ - int i; - const char *s[] = { "%d\n", "Fizz\n", s[3] + 4, "FizzBuzz\n" }; - for (i = 1; i <= 100; i++) - printf(s[!(i % 3) + 2 * !(i % 5)], i); - - return 0; +int main() { + for (int i=1; i<=105; i++) if (i%3 && i%5) printf("%3d ", i); else printf("%s%s%s", i%3?"":"Fizz", i%5?"":"Buzz", i%15?" ":"\n"); } diff --git a/Task/FizzBuzz/C/fizzbuzz-6.c b/Task/FizzBuzz/C/fizzbuzz-6.c index a3b8a4d01f..de8671632b 100644 --- a/Task/FizzBuzz/C/fizzbuzz-6.c +++ b/Task/FizzBuzz/C/fizzbuzz-6.c @@ -1,11 +1,11 @@ -#include +#include -int main(void) +int main () { - for (int i = 1; i <= 100; ++i) { - if (i % 3 == 0) printf("fizz"); - if (i % 5 == 0) printf("buzz"); - if (i * i * i * i % 15 == 1) printf("%d", i); - puts(""); - } + int i; + const char *s[] = { "%d\n", "Fizz\n", s[3] + 4, "FizzBuzz\n" }; + for (i = 1; i <= 100; i++) + printf(s[!(i % 3) + 2 * !(i % 5)], i); + + return 0; } diff --git a/Task/FizzBuzz/C/fizzbuzz-7.c b/Task/FizzBuzz/C/fizzbuzz-7.c index 6cf2ee6c45..b6e087e7ae 100644 --- a/Task/FizzBuzz/C/fizzbuzz-7.c +++ b/Task/FizzBuzz/C/fizzbuzz-7.c @@ -1,10 +1,20 @@ -#include -int main() +#include + +int main (void) { - for (int i=0;++i<101;puts("")) + int i; + for (i = 1; i <= 100; i++) { - char f[] = "FizzBuzz%d"; - f[8-i%5&12]=0; - printf (f+(-i%3&4+f[8]/8), i); + if (!(i % 15)) + printf ("FizzBuzz"); + else if (!(i % 3)) + printf ("Fizz"); + else if (!(i % 5)) + printf ("Buzz"); + else + printf ("%d", i); + + printf("\n"); } + return 0; } diff --git a/Task/FizzBuzz/C/fizzbuzz-8.c b/Task/FizzBuzz/C/fizzbuzz-8.c new file mode 100644 index 0000000000..10d5072f99 --- /dev/null +++ b/Task/FizzBuzz/C/fizzbuzz-8.c @@ -0,0 +1,16 @@ +#include + +main() { + int i = 1; + while(i <= 100) { + if(i % 15 == 0) + puts("FizzBuzz"); + else if(i % 3 == 0) + puts("Fizz"); + else if(i % 5 == 0) + puts("Buzz"); + else + printf("%d\n", i); + i++; + } +} diff --git a/Task/FizzBuzz/C/fizzbuzz-9.c b/Task/FizzBuzz/C/fizzbuzz-9.c new file mode 100644 index 0000000000..daa85416cc --- /dev/null +++ b/Task/FizzBuzz/C/fizzbuzz-9.c @@ -0,0 +1,3 @@ +#include +#define F(x,y) printf("%s",i%x?"":#y"zz") +int main(int i){for(--i;i++^100;puts(""))F(3,Fi)|F(5,Bu)||printf("%i",i);return 0;} diff --git a/Task/FizzBuzz/Chef/fizzbuzz.chef b/Task/FizzBuzz/Chef/fizzbuzz.chef deleted file mode 100644 index 891e88acec..0000000000 --- a/Task/FizzBuzz/Chef/fizzbuzz.chef +++ /dev/null @@ -1,187 +0,0 @@ -Irish Soda Bread with Club Soda. - -This is FizzBuzz - -Ingredients. -1 l buttermilk - -Method. -Take buttermilk from refrigerator. -Shake the buttermilk. - Put buttermilk into the 6th mixing bowl. - Serve with club soda. - Pour contents of the 1st mixing bowl into the 1st baking dish. - Clean the 1st mixing bowl. -Watch the buttermilk until shaked. - -Serves 1. - -Club Soda. - -Gets whether to print fizz buzz fizzbuzz or number. - -Ingredients. -70 g flour -105 g salt -122 ml milk -66 g sugar -117 ml vegetable oil -3 cups fizzle -5 cups seltzer -1 cup bmilk -1 cup ice -1 cup baking soda -1 g oregano -32 ml vinegar -1 g thyme -1 g sage - -Method. -Put milk into the 1st mixing bowl. -Put salt into the 1st mixing bowl. -Put flour into the 1st mixing bowl. -Put vinegar into the 1st mixing bowl. -Put milk into the 1st mixing bowl. -Stir the 1st mixing bowl for 5 minutes. -Liquify contents of the 1st mixing bowl. -Put fizzle into the 3rd mixing bowl. -Combine seltzer into the 3rd mixing bowl. -Fold bmilk into the 6th mixing bowl. -Put bmilk into the 6th mixing bowl. -Put seltzer into the 6th mixing bowl. -Put bmilk into the 6th mixing bowl. -Serve with moist cake. -Fold bmilk into the 1st mixing bowl. -Fold sage into the 6th mixing bowl. -Fold sage into the 6th mixing bowl. -Put bmilk into the 4th mixing bowl. -Remove seltzer from the 4th mixing bowl. -Fold oregano into the 4th mixing bowl. -Smell the oregano. - Fold bmilk into the 6th mixing bowl. - Put bmilk into the 6th mixing bowl. - Put fizzle into the 6th mixing bowl. - Put bmilk into the 6th mixing bowl. - Serve with moist cake. - Fold bmilk into the 1st mixing bowl. - Fold sage into the 6th mixing bowl. - Fold sage into the 6th mixing bowl. - Put bmilk into the 4th mixing bowl. - Remove fizzle from the 4th mixing bowl. - Fold oregano into the 4th mixing bowl. - Crush the oregano. - Clean the 1st mixing bowl. - Fold bmilk into the 6th mixing bowl. - Put bmilk into the 1st mixing bowl. - Refrigerate. - Grind until crushed. - Refrigerate. -Shuffle until smelled. -Clean the 1st mixing bowl. -Put milk into the 1st mixing bowl. -Put vegetable oil into the 1st mixing bowl. -Put sugar into the 1st mixing bowl. -Put vinegar into the 1st mixing bowl. -Put milk into the 1st mixing bowl. -Stir the 1st mixing bowl for 5 minutes. -Liquify contents of the 1st mixing bowl. -Fold baking soda into the 3rd mixing bowl. -Fold bmilk into the 6th mixing bowl. -Put bmilk into the 6th mixing bowl. -Put baking soda into the 6th mixing bowl. -Put bmilk into the 6th mixing bowl. -Serve with moist cake. -Fold bmilk into the 1st mixing bowl. -Fold sage into the 6th mixing bowl. -Fold sage into the 6th mixing bowl. -Put bmilk into the 4th mixing bowl. -Remove baking soda from the 4th mixing bowl. -Fold oregano into the 4th mixing bowl. -Separate the oregano. - Refrigerate. -Part until separated. -Put fizzle into the 6th mixing bowl. -Serve with club soda. -Stir the 1st mixing bowl for 1 minute. -Stir the 1st mixing bowl for 7 minutes. -Stir the 1st mixing bowl for 1 minute. -Stir the 1st mixing bowl for 7 minutes. -Stir the 1st mixing bowl for 5 minutes. -Fold the oregano into the 1st mixing bowl. -Fold the oregano into the 1st mixing bowl. -Fold the oregano into the 1st mixing bowl. -Fold the oregano into the 1st mixing bowl. -Fold the oregano into the 1st mixing bowl. -Refrigerate. - -Moist cake. - -Mods a number - -Ingredients. -1 cup chocolate -70 g wheat flour -1 cup white chocolate chips -1 cup baking powder -105 g honey -5 cups syrup -1 g vanilla -1 g rosemary - -Method. -Fold chocolate into the 6th mixing bowl. -Fold syrup into the 6th mixing bowl. -Clean the 1st mixing bowl. -Put chocolate into the 5th mixing bowl. -Fold wheat flour into the 5th mixing bowl. -Put white chocolate chips into the 5th mixing bowl. -Remove white chocolate chips from the 5th mixing bowl. -Fold baking powder into the 5th mixing bowl. -Put baking powder into the 5th mixing bowl. -Fold honey into the 5th mixing bowl. -Sift the wheat flour. - Put honey into the 5th mixing bowl. - Add white chocolate chips into the 5th mixing bowl. - Fold honey into the 5th mixing bowl. - Put honey into the 5th mixing bowl. - Remove syrup from the 5th mixing bowl. - Fold vanilla into the 5th mixing bowl. - Sprinkle the vanilla. - Put white chocolate chips into the 5th mixing bowl. - Remove white chocolate chips from the 5th mixing bowl. - Fold rosemary into the 5th mixing bowl. - Set aside. - Move until sprinkled. - Recite the rosemary. - Put white chocolate chips into the 5th mixing bowl. - Remove white chocolate chips from the 5th mixing bowl. - Fold honey into the 5th mixing bowl. - Put baking powder into the 5th mixing bowl. - Add white chocolate chips into the 5th mixing bowl. - Fold baking powder into the 5th mixing bowl. - Set aside. - Repeat until recited. - Put white chocolate chips into the 5th mixing bowl. - Fold rosemary into the 5th mixing bowl. -Shuffle the wheat flour until sifted. -Put the baking powder into the 5th mixing bowl. -Combine syrup into the 5th mixing bowl. -Fold honey into the 5th mixing bowl. -Put chocolate into the 5th mixing bowl. -Remove honey from the 5th mixing bowl. -Fold chocolate into the 5th mixing bowl. -Put white chocolate chips into the 5th mixing bowl. -Fold rosemary into the 5th mixing bowl. -Siphon chocolate. - Put white chocolate chips into the 5th mixing bowl. - Remove white chocolate chips from the 5th mixing bowl. - Fold rosemary into the 5th mixing bowl. - Set aside. -Gulp until siphoned. -Quote the rosemary. - Put syrup into the 5th mixing bowl. - Fold chocolate into the 5th mixing bowl. - Set aside. -Repeat until quoted. -Put chocolate into the 1st mixing bowl. -Refrigerate. diff --git a/Task/FizzBuzz/ColdFusion/fizzbuzz-2.cfm b/Task/FizzBuzz/ColdFusion/fizzbuzz-2.cfm index 1a04809a41..48a3077e75 100644 --- a/Task/FizzBuzz/ColdFusion/fizzbuzz-2.cfm +++ b/Task/FizzBuzz/ColdFusion/fizzbuzz-2.cfm @@ -1,7 +1,7 @@ result = ""; for(i=1;i<=100;i++){ - result=ListAppend(result, (i%15==0) ? "FizzBuzz": (i%5==0) ? "Buzz" : (i%3 eq 0)? "Fizz" : i ); + result=ListAppend(result, (i%15==0) ? "FizzBuzz": (i%5==0) ? "Buzz" : (i%3 eq 0)? "Fizz" : i ); } WriteOutput(result); diff --git a/Task/FizzBuzz/Comefrom0x10/fizzbuzz.comefrom0x10 b/Task/FizzBuzz/Comefrom0x10/fizzbuzz.comefrom0x10 new file mode 100644 index 0000000000..0c3508841f --- /dev/null +++ b/Task/FizzBuzz/Comefrom0x10/fizzbuzz.comefrom0x10 @@ -0,0 +1,24 @@ +fizzbuzz + mod_three = 3 + mod_five = 5 + comefrom fizzbuzz + n + comefrom fizzbuzz if n is mod_three + comefrom fizzbuzz if n is mod_five + n = n + 1 + + fizz + comefrom fizzbuzz if n is mod_three + 'Fizz'... + mod_three = mod_three + 3 + linebreak + # would like to write "unless mod_three is mod_five" + comefrom fizz if mod_three - mod_five - 3 + '' + + buzz + comefrom fizzbuzz if n is mod_five + 'Buzz' + mod_five = mod_five + 5 + + comefrom fizzbuzz if n is 100 diff --git a/Task/FizzBuzz/Common-Lisp/fizzbuzz-7.lisp b/Task/FizzBuzz/Common-Lisp/fizzbuzz-7.lisp new file mode 100644 index 0000000000..0aaaf5e0ef --- /dev/null +++ b/Task/FizzBuzz/Common-Lisp/fizzbuzz-7.lisp @@ -0,0 +1,16 @@ +(defun core (x) + (mapcar + #'(lambda (a b) (if (equal 0 (mod x a)) b x)) + '(3 5) + '("fizz" "buzz"))) + +(defun filter-core (x) + (if (equal 1 (length (remove-duplicates x))) + (list (car x)) + (remove-if-not #'stringp x))) + +(defun fizzbuzz (x) + (loop for a from 1 to x do + (print (format nil "~{~a~}" (filter-core (core a)))))) + +(fizzbuzz 100) diff --git a/Task/FizzBuzz/DUP/fizzbuzz-1.dup b/Task/FizzBuzz/DUP/fizzbuzz-1.dup new file mode 100644 index 0000000000..088ee36d7d --- /dev/null +++ b/Task/FizzBuzz/DUP/fizzbuzz-1.dup @@ -0,0 +1,2 @@ +[$$3/%$[]['F,'i,'z,'z,]?\5/%$[]['B,'u,'z,'z,]?*[$.][]?10,]c: {define function c: mod 3, mod 5 tests, print proper output} +0[$100<][1+c;!]# {loop from 1 to 100} diff --git a/Task/FizzBuzz/DUP/fizzbuzz-2.dup b/Task/FizzBuzz/DUP/fizzbuzz-2.dup new file mode 100644 index 0000000000..768e8a26d5 --- /dev/null +++ b/Task/FizzBuzz/DUP/fizzbuzz-2.dup @@ -0,0 +1,3 @@ +[\[^^>][$;,1+]#%%]⇒P {define operator P: print stored string} +[$$3/%$[][0$"Fizz"P]?\5/%$[][0$"Buzz"P]?*[$.][]?10,]c: {define function c: mod 3, mod 5 tests, print according output} +0[$100<][1+c;!]# {loop from 1 to 100} diff --git a/Task/FizzBuzz/Dart/fizzbuzz.dart b/Task/FizzBuzz/Dart/fizzbuzz.dart index 86a204e82b..1fe2f72ea6 100644 --- a/Task/FizzBuzz/Dart/fizzbuzz.dart +++ b/Task/FizzBuzz/Dart/fizzbuzz.dart @@ -1,5 +1,10 @@ main() { for (int i = 1; i <= 100; i++) { - print((i % 3 == 0 ? "Fizz" : "") + (i % 5 == 0 ? "Buzz" : "") + (i % 3 != 0 && i % 5 != 0 ? "$i" : "")); + List out = []; + if (i % 3 == 0) + out.add("Fizz"); + if (i % 5 == 0) + out.add("Buzz"); + print(out.length > 0 ? out.join("") : i); } } diff --git a/Task/FizzBuzz/Dc/fizzbuzz-1.dc b/Task/FizzBuzz/Dc/fizzbuzz-1.dc new file mode 100644 index 0000000000..2907225c01 --- /dev/null +++ b/Task/FizzBuzz/Dc/fizzbuzz-1.dc @@ -0,0 +1,16 @@ +[[Fizz]P 1 sw]sF +[[Buzz]P 1 sw]sB +[li p sz]sN +[[ +]P]sW +[ + 0 sw [w = 0]sz + li 3 % 0 =F [Fizz if 0 == i % 3]sz + li 5 % 0 =B [Buzz if 0 == i % 5]sz + lw 0 =N [print Number if 0 == w]sz + lw 1 =W [print neWline if 1 == w]sz + li 1 + si [i += 1]sz + li 100 != i]sz +]sL +1 si [i = 1]sz +0 0 =L [enter Loop]sz diff --git a/Task/FizzBuzz/Dc/fizzbuzz-2.dc b/Task/FizzBuzz/Dc/fizzbuzz-2.dc new file mode 100644 index 0000000000..3a75f75e36 --- /dev/null +++ b/Task/FizzBuzz/Dc/fizzbuzz-2.dc @@ -0,0 +1,18 @@ +# dc is stack based, so we use the stack instead of a variable for our +# current number. + +1 # Number = 1 +[[Fizz]n 1 sw]sF # Prints "Fizz" prevents Number from printing +[[Buzz]n 1 sw]sB # Prints "Buzz" prevents Number from printing +[dn]sN # Prints Number +[ + dd # Put two extra copies of Number on stack + 0 sw # w = 0 + 3% 0=F # Fizz if 0 == Number % 3 (destroys 1st copy) + 5% 0=B # Buzz if 0 == Number % 5 (destroys 2nd copy) + lw 0=N # Print Number if 0 == w + [ +]n # Print new line + 1+d # Number += 1 and put extra copy on stack + 100!= Number (destroys copy) +]dsLx # Enter Loop diff --git a/Task/FizzBuzz/FALSE/fizzbuzz.false b/Task/FizzBuzz/FALSE/fizzbuzz.false deleted file mode 100644 index de41c71a9c..0000000000 --- a/Task/FizzBuzz/FALSE/fizzbuzz.false +++ /dev/null @@ -1,4 +0,0 @@ -[\$@$@\/*=]d: -[1\$3d;!["Fizz"\%0\]?$5d;!["Buzz"\%0\]?\[$.]?" -"]f: -0[$100\>][1+f;!]#% diff --git a/Task/FizzBuzz/Gambas/fizzbuzz.gambas b/Task/FizzBuzz/Gambas/fizzbuzz.gambas new file mode 100644 index 0000000000..79e365f675 --- /dev/null +++ b/Task/FizzBuzz/Gambas/fizzbuzz.gambas @@ -0,0 +1,13 @@ +Public Sub Main() +Dim siCount As Short +Dim sText As String + +For siCount = 1 To 100 + sText = "" + If siCount Mod 3 = 0 Then sText = "Fizz" + If siCount Mod 5 = 0 Then sText = "Buzz" + If siCount Mod 15 = 0 Then sText = "FizzBuzz" + If sText Then Print sText Else Print siCount +Next + +End diff --git a/Task/FizzBuzz/Genyris/fizzbuzz.genyris b/Task/FizzBuzz/Genyris/fizzbuzz.genyris new file mode 100644 index 0000000000..a6ba77f2cb --- /dev/null +++ b/Task/FizzBuzz/Genyris/fizzbuzz.genyris @@ -0,0 +1,20 @@ +@prefix u "http://www.genyris.org/lang/utilities#" + +def fizzbuzz (n) + map-left ^((3 = 'fizz') (5 = 'buzz')) + lambda (d) + cond + (equal? 0 (% n d!left)) + d!right + else + '' + + +for n in (range 1 100) + define fb (''(.join (fizzbuzz n))) + u:format "%a\n" + cond + (equal? fb '') + n + else + fb diff --git a/Task/FizzBuzz/Golo/fizzbuzz.golo b/Task/FizzBuzz/Golo/fizzbuzz.golo new file mode 100644 index 0000000000..232628da8f --- /dev/null +++ b/Task/FizzBuzz/Golo/fizzbuzz.golo @@ -0,0 +1,16 @@ +module FizzBuzz + +augment java.lang.Integer { + function getFizzAndOrBuzz = |this| -> match { + when this % 15 == 0 then "FizzBuzz" + when this % 3 == 0 then "Fizz" + when this % 5 == 0 then "Buzz" + otherwise this + } +} + +function main = |args| { + foreach i in [1..101] { + println(i: getFizzAndOrBuzz()) + } +} diff --git a/Task/FizzBuzz/Groovy/fizzbuzz.groovy b/Task/FizzBuzz/Groovy/fizzbuzz.groovy index 83fb591e8f..6d5bb3f115 100644 --- a/Task/FizzBuzz/Groovy/fizzbuzz.groovy +++ b/Task/FizzBuzz/Groovy/fizzbuzz.groovy @@ -1,3 +1 @@ -for (i in 1..100) { - println "${i%3?'':'Fizz'}${i%5?'':'Buzz'}" ?: i -} +1.upto(100, { i -> println "${i % 3 ? '' : 'Fizz'}${i % 5 ? '' : 'Buzz'}" ?: i }) diff --git a/Task/FizzBuzz/HolyC/fizzbuzz.holyc b/Task/FizzBuzz/HolyC/fizzbuzz.holyc new file mode 100644 index 0000000000..f1ff8d2efb --- /dev/null +++ b/Task/FizzBuzz/HolyC/fizzbuzz.holyc @@ -0,0 +1,12 @@ +U8 i; +for (i = 1; i <= 100; i++) { + if (!(i % 15)) + Print("FizzBuzz"); + else if (!(i % 3)) + Print("Fizz"); + else if (!(i % 5)) + Print("Buzz"); + else + Print("%d", i); + Print("\n"); +} diff --git a/Task/FizzBuzz/Idris/fizzbuzz.idris b/Task/FizzBuzz/Idris/fizzbuzz.idris index 344c76609d..e847d46a34 100644 --- a/Task/FizzBuzz/Idris/fizzbuzz.idris +++ b/Task/FizzBuzz/Idris/fizzbuzz.idris @@ -1,7 +1,8 @@ +partial fizzBuzz : Nat -> String -fizzBuzz n = if (n `mod` 15) == 0 then "FizzBuzz" - else if (n `mod` 3) == 0 then "Fizz" - else if (n `mod` 5) == 0 then "Buzz" +fizzBuzz n = if (n `modNat` 15) == 0 then "FizzBuzz" + else if (n `modNat` 3) == 0 then "Fizz" + else if (n `modNat` 5) == 0 then "Buzz" else show n main : IO () diff --git a/Task/FizzBuzz/Java/fizzbuzz-1.java b/Task/FizzBuzz/Java/fizzbuzz-1.java deleted file mode 100644 index 96990a8f58..0000000000 --- a/Task/FizzBuzz/Java/fizzbuzz-1.java +++ /dev/null @@ -1,15 +0,0 @@ -public class FizzBuzz{ - public static void main(String[] args){ - for(int i= 1; i <= 100; i++){ - if(i % 15 == 0){ - System.out.println("FizzBuzz"); - }else if(i % 3 == 0){ - System.out.println("Fizz"); - }else if(i % 5 == 0){ - System.out.println("Buzz"); - }else{ - System.out.println(i); - } - } - } -} diff --git a/Task/FizzBuzz/Java/fizzbuzz-2.java b/Task/FizzBuzz/Java/fizzbuzz-2.java deleted file mode 100644 index f5113e4fb8..0000000000 --- a/Task/FizzBuzz/Java/fizzbuzz-2.java +++ /dev/null @@ -1,11 +0,0 @@ -public class FizzBuzz{ - public static void main(String[] args){ - for(int i= 1; i <= 100; i++){ - String output = ""; - if(i % 3 == 0) output += "Fizz"; - if(i % 5 == 0) output += "Buzz"; - if(output.equals("")) output += i; - System.out.println(output); - } - } -} diff --git a/Task/FizzBuzz/Java/fizzbuzz-3.java b/Task/FizzBuzz/Java/fizzbuzz-3.java deleted file mode 100644 index d6e99c199f..0000000000 --- a/Task/FizzBuzz/Java/fizzbuzz-3.java +++ /dev/null @@ -1,8 +0,0 @@ -public class FizzBuzz{ - public static void main(String[] args){ - for(int i= 1; i <= 100; i++){ - System.out.println(i % 15 != 0 ? i % 5 != 0 ? i % 3 != 0 ? - i : "Fizz" : "Buzz" : "FizzBuzz"); - } - } -} diff --git a/Task/FizzBuzz/Java/fizzbuzz-4.java b/Task/FizzBuzz/Java/fizzbuzz-4.java deleted file mode 100644 index 676d8c6410..0000000000 --- a/Task/FizzBuzz/Java/fizzbuzz-4.java +++ /dev/null @@ -1,12 +0,0 @@ -public String fizzBuzz(int n){ - String s = ""; - if (n == 0) - return s; - if((n % 5) == 0) - s = "Buzz" + s; - if((n % 3) == 0) - s = "Fizz" + s; - if (s.equals("")) - s = n + ""; - return fizzBuzz(n-1) + s; -} diff --git a/Task/FizzBuzz/Java/fizzbuzz-5.java b/Task/FizzBuzz/Java/fizzbuzz-5.java deleted file mode 100644 index 767a3fa569..0000000000 --- a/Task/FizzBuzz/Java/fizzbuzz-5.java +++ /dev/null @@ -1,5 +0,0 @@ -public String fizzBuzz(int n){ - return (n>0) ? fizzBuzz(n-1) + - (n % 15 != 0? n % 5 != 0? n % 3 != 0? (n+"") :"Fizz" : "Buzz" : "FizzBuzz") - : ""; -} diff --git a/Task/FizzBuzz/Java/fizzbuzz-6.java b/Task/FizzBuzz/Java/fizzbuzz-6.java deleted file mode 100644 index 80ab9dd867..0000000000 --- a/Task/FizzBuzz/Java/fizzbuzz-6.java +++ /dev/null @@ -1,7 +0,0 @@ -class FizzBuzz { - public static void main( String [] args ) { - for( int i = 1 ; i <= 100 ; i++ ) { - System.out.println( new String[]{ i+"", "Fizz", "Buzz", "FizzBuzz" }[ ( i%3==0?1:0 ) + ( i%5==0?2:0 ) ]); - } - } -} diff --git a/Task/FizzBuzz/JavaScript/fizzbuzz-4.js b/Task/FizzBuzz/JavaScript/fizzbuzz-4.js index 9733b1f347..37305d139b 100644 --- a/Task/FizzBuzz/JavaScript/fizzbuzz-4.js +++ b/Task/FizzBuzz/JavaScript/fizzbuzz-4.js @@ -1,11 +1 @@ -(function rng(i) { - return i ? rng(i - 1).concat(i) : [] -})(100).map( - function (n) { - return n % 3 ? ( - n % 5 ? n : "Buzz" - ) : ( - n % 5 ? "Fizz" : "FizzBuzz" - ) - } -).join(' ') +for(i=1;i<101;i++)console.log((i%3?'':'Fizz')+(i%5?'':'Buzz')||i) diff --git a/Task/FizzBuzz/JavaScript/fizzbuzz-5.js b/Task/FizzBuzz/JavaScript/fizzbuzz-5.js index 8179b5aff3..9733b1f347 100644 --- a/Task/FizzBuzz/JavaScript/fizzbuzz-5.js +++ b/Task/FizzBuzz/JavaScript/fizzbuzz-5.js @@ -1,8 +1,11 @@ -(function() { - var i; - - for (i = 1; i <= 100; i++) { - console.log([i % 3 === 0 ? 'Fizz' : void 0] + [i % 5 === 0 ? 'Buzz' : void 0] || i); - } - -}).call(this); +(function rng(i) { + return i ? rng(i - 1).concat(i) : [] +})(100).map( + function (n) { + return n % 3 ? ( + n % 5 ? n : "Buzz" + ) : ( + n % 5 ? "Fizz" : "FizzBuzz" + ) + } +).join(' ') diff --git a/Task/FizzBuzz/JavaScript/fizzbuzz-6.js b/Task/FizzBuzz/JavaScript/fizzbuzz-6.js index 6d37d23951..e6280a64d7 100644 --- a/Task/FizzBuzz/JavaScript/fizzbuzz-6.js +++ b/Task/FizzBuzz/JavaScript/fizzbuzz-6.js @@ -1,25 +1,36 @@ -var divs = [15, 3, 5]; -var says = ['FizzBuzz', 'Fizz', 'Buzz']; +(() => { -function fizzBuzz(first, last) { - for (var n = first; n <= last; n++) { - print(getFizzBuzz(n)); - } -} + // FIZZBUZZ -------------------------------------------------------------- -function getFizzBuzz(n) { - var sayWhat = n; - for (var d = 0; d < divs.length; d++) { - if (isMultOf(n, divs[d])) { - sayWhat = says[d]; - break; - } - } - return sayWhat; -} + // fizzBuzz :: Int -> String + const fizzBuzz = n => + caseOf(n, [ + [x => x % 15 === 0, "FizzBuzz"], + [x => x % 3 === 0, "Fizz"], + [x => x % 5 === 0, "Buzz"] + ], n.toString()); -function isMultOf(n, d) { - return n % d == 0; -} + // GENERIC FUNCTIONS ----------------------------------------------------- -fizzBuzz(1, 100); + // caseOf :: a -> [(a -> Bool, b)] -> b -> b + const caseOf = (e, pvs, otherwise) => + pvs.reduce((a, [p, v]) => + a !== otherwise ? a : (p(e) ? v : a), otherwise); + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + // TEST ------------------------------------------------------------------ + return unlines( + map(fizzBuzz, enumFromTo(1, 100)) + ); +})(); diff --git a/Task/FizzBuzz/jq/fizzbuzz-1.jq b/Task/FizzBuzz/Jq/fizzbuzz-1.jq similarity index 100% rename from Task/FizzBuzz/jq/fizzbuzz-1.jq rename to Task/FizzBuzz/Jq/fizzbuzz-1.jq diff --git a/Task/FizzBuzz/jq/fizzbuzz-2.jq b/Task/FizzBuzz/Jq/fizzbuzz-2.jq similarity index 100% rename from Task/FizzBuzz/jq/fizzbuzz-2.jq rename to Task/FizzBuzz/Jq/fizzbuzz-2.jq diff --git a/Task/FizzBuzz/K/fizzbuzz-4.k b/Task/FizzBuzz/K/fizzbuzz-4.k new file mode 100644 index 0000000000..827c202ee0 --- /dev/null +++ b/Task/FizzBuzz/K/fizzbuzz-4.k @@ -0,0 +1 @@ +{,/$(s;x)@~#s:`Fizz`Buzz@&~x!'3 5}'1+!30 diff --git a/Task/FizzBuzz/Klong/fizzbuzz.klong b/Task/FizzBuzz/Klong/fizzbuzz.klong index 3b29f089ab..a637231415 100644 --- a/Task/FizzBuzz/Klong/fizzbuzz.klong +++ b/Task/FizzBuzz/Klong/fizzbuzz.klong @@ -1,11 +1 @@ -{[fizzy buzzy fizzybuzzy]; - fizzy::x!3; - buzzy::x!5; - fizzybuzzy::(fizzy+buzzy); - :[0=fizzybuzzy;.d("FizzBuzz") - :|0=fizzy; - .d("Fizz") - :|0=buzzy; - .d("Buzz"); - .d(x)]; - .d(" ")}'1+!100 +{:[0=x!15;:FizzBuzz:|0=x!5;:Buzz:|0=x!3;:Fizz;x]}'1+!100 diff --git a/Task/FizzBuzz/Kotlin/fizzbuzz-2.kotlin b/Task/FizzBuzz/Kotlin/fizzbuzz-2.kotlin index acbafdb9e3..e2cfaba27b 100644 --- a/Task/FizzBuzz/Kotlin/fizzbuzz-2.kotlin +++ b/Task/FizzBuzz/Kotlin/fizzbuzz-2.kotlin @@ -1,7 +1,7 @@ -fun fizzBuzz() { - fun fizzbuzz(x: Int) = if(x % 15 == 0) "FizzBuzz" else x - fun fizz(x: Any) = if(x is Int && x % 3 == 0) "Buzz" else x - fun buzz(x: Any) = if(x is Int && x.toInt() % 5 == 0) "Fizz" else x +fun fizzBuzz1() { + fun fizzBuzz(x: Int) = if (x % 15 == 0) "FizzBuzz" else x.toString() + fun fizz(x: Any) = if (x is Int && x % 3 == 0) "Buzz" else x + fun buzz(x: Any) = if (x is Int && x.toInt() % 5 == 0) "Fizz" else x - (1..100).map { fizzbuzz(it) }.map { fizz(it) }.map { buzz(it) }.forEach { println(it) } + (1..100).map { fizzBuzz(it) }.map { fizz(it) }.map { buzz(it) }.forEach { println(it) } } diff --git a/Task/FizzBuzz/Kotlin/fizzbuzz-3.kotlin b/Task/FizzBuzz/Kotlin/fizzbuzz-3.kotlin index 6b29235775..db4e48b201 100644 --- a/Task/FizzBuzz/Kotlin/fizzbuzz-3.kotlin +++ b/Task/FizzBuzz/Kotlin/fizzbuzz-3.kotlin @@ -1,4 +1,4 @@ -fun fizzBuzz() { +fun fizzBuzz2() { fun fizz(x: Pair) = if(x.first % 3 == 0) x.apply { second.append("Fizz") } else x fun buzz(x: Pair) = if(x.first % 5 == 0) x.apply { second.append("Buzz") } else x fun none(x: Pair) = if(x.second.isBlank()) x.second.apply { append(x.first) } else x.second diff --git a/Task/FizzBuzz/LOLCODE/fizzbuzz.lol b/Task/FizzBuzz/LOLCODE/fizzbuzz.lol deleted file mode 100644 index 563246d44c..0000000000 --- a/Task/FizzBuzz/LOLCODE/fizzbuzz.lol +++ /dev/null @@ -1,18 +0,0 @@ -HAI 1.3 - -IM IN YR fizz UPPIN YR i TIL BOTH SAEM i AN 100 - I HAS A i ITZ SUM OF i AN 1 BTW, ALL LUPZ START AT 0 :/ - I HAS A mod3 ITZ NOT MOD OF i AN 3 - I HAS A mod5 ITZ NOT MOD OF i AN 5 - - mod3, O RLY?, YA RLY, VISIBLE "Fizz"!, OIC - mod5, O RLY?, YA RLY, VISIBLE "Buzz"!, OIC - - NOT EITHER OF mod3 AN mod5, O RLY? - YA RLY, VISIBLE i! - OIC - - VISIBLE "" -IM OUTTA YR fizz - -KTHXBYE diff --git a/Task/FizzBuzz/Liberty-BASIC/fizzbuzz.liberty b/Task/FizzBuzz/Liberty-BASIC/fizzbuzz.liberty deleted file mode 100644 index 691732ed92..0000000000 --- a/Task/FizzBuzz/Liberty-BASIC/fizzbuzz.liberty +++ /dev/null @@ -1,12 +0,0 @@ -for i = 1 to 100 - select case - case i mod 15 = 0 - print "FizzBuzz" - case i mod 3 = 0 - print "Fizz" - case i mod 5 = 0 - print "Buzz" - case else - print i - end select -next i diff --git a/Task/FizzBuzz/Make/fizzbuzz.make b/Task/FizzBuzz/Make/fizzbuzz.make new file mode 100644 index 0000000000..6bad3cb2d4 --- /dev/null +++ b/Task/FizzBuzz/Make/fizzbuzz.make @@ -0,0 +1,28 @@ +MOD3 = 0 +MOD5 = 0 +ALL != jot 100 + +all: say-100 + +.for NUMBER in $(ALL) + +MOD3 != expr \( $(MOD3) + 1 \) % 3; true +MOD5 != expr \( $(MOD5) + 1 \) % 5; true + +. if "$(NUMBER)" > 1 +PRED != expr $(NUMBER) - 1 +say-$(NUMBER): say-$(PRED) +. else +say-$(NUMBER): +. endif +. if "$(MOD3)$(MOD5)" == "00" + @echo FizzBuzz +. elif "$(MOD3)" == "0" + @echo Fizz +. elif "$(MOD5)" == "0" + @echo Buzz +. else + @echo $(NUMBER) +. endif + +.endfor diff --git a/Task/FizzBuzz/Moonscript/fizzbuzz.moon b/Task/FizzBuzz/Moonscript/fizzbuzz.moon new file mode 100644 index 0000000000..f790c69e84 --- /dev/null +++ b/Task/FizzBuzz/Moonscript/fizzbuzz.moon @@ -0,0 +1,4 @@ +for i = 1,100 + print ((a) -> a == "" and i or a) table.concat { + i % 3 == 0 and "Fizz" or "" + i % 5 == 0 and "Buzz" or ""} diff --git a/Task/FizzBuzz/Nimrod/fizzbuzz-1.nimrod b/Task/FizzBuzz/Nimrod/fizzbuzz-1.nimrod deleted file mode 100644 index 9566ba2377..0000000000 --- a/Task/FizzBuzz/Nimrod/fizzbuzz-1.nimrod +++ /dev/null @@ -1,9 +0,0 @@ -for i in 1..100: - if i mod 15 == 0: - echo("FizzBuzz") - elif i mod 3 == 0: - echo("Fizz") - elif i mod 5 == 0: - echo("Buzz") - else: - echo(i) diff --git a/Task/FizzBuzz/Nimrod/fizzbuzz-2.nimrod b/Task/FizzBuzz/Nimrod/fizzbuzz-2.nimrod deleted file mode 100644 index 21f20a4546..0000000000 --- a/Task/FizzBuzz/Nimrod/fizzbuzz-2.nimrod +++ /dev/null @@ -1,6 +0,0 @@ -var messages = @["", "Fizz", "Buzz", "FizzBuzz"] -var acc = 810092048 -for i in 1..100: - var c = acc and 3 - echo(if c == 0: $i else: messages[c]) - acc = acc shr 2 or c shl 28 diff --git a/Task/FizzBuzz/PILOT/fizzbuzz.pilot b/Task/FizzBuzz/PILOT/fizzbuzz.pilot new file mode 100644 index 0000000000..58f29dd32a --- /dev/null +++ b/Task/FizzBuzz/PILOT/fizzbuzz.pilot @@ -0,0 +1,23 @@ +C :i = 0 +*loop +C :i = i + 1 +J ( i > 100 ) : *finished +C :modulo = i % 15 +J ( modulo = 0 ) : *fizzbuzz +C :modulo = i % 3 +J ( modulo = 0 ) : *fizz +C :modulo = i % 5 +J ( modulo = 0 ) : *buzz +T :#i +J : *loop +*fizzbuzz +T :FizzBuzz +J : *loop +*fizz +T :Fizz +J : *loop +*buzz +T :Buzz +J : *loop +*finished +END: diff --git a/Task/FizzBuzz/Perl/fizzbuzz-6.pl b/Task/FizzBuzz/Perl/fizzbuzz-6.pl new file mode 100644 index 0000000000..0567479cb4 --- /dev/null +++ b/Task/FizzBuzz/Perl/fizzbuzz-6.pl @@ -0,0 +1,11 @@ +sub fizz_buzz { + join("\n", map { + sub mult {$_ % shift == 0}; + my @out; + if (mult 3) { push @out, "Fizz"; } + if (mult 5) { push @out, "Buzz"; } + if (!@out) {push @out, $_; } + join('', @out); + } (1..100))."\n"; +} +print fizz_buzz; diff --git a/Task/FizzBuzz/Protium/fizzbuzz-1.protium b/Task/FizzBuzz/Protium/fizzbuzz-1.protium deleted file mode 100644 index e9073913ab..0000000000 --- a/Task/FizzBuzz/Protium/fizzbuzz-1.protium +++ /dev/null @@ -1,9 +0,0 @@ -<# DEFINE USERDEFINEDROUTINE LITERAL>__FizzBuzz|<# SUPPRESSAUTOMATICWHITESPACE> -<# TEST ISITMODULUSZERO PARAMETER LITERAL>1|3 -<# TEST ISITMODULUSZERO PARAMETER LITERAL>1|5 -<# ONLYFIRSTOFLASTTWO><# SAY LITERAL>Fizz -<# ONLYSECONDOFLASTTWO><# SAY LITERAL>Buzz -<# BOTH><# SAY LITERAL>FizzBuzz -<# NEITHER><# SAY PARAMETER>1 - -<# ITERATE FORITERATION LITERAL LITERAL>100|<# ACT USERDEFINEDROUTINE POSITION FORITERATION>__FizzBuzz|... diff --git a/Task/FizzBuzz/Protium/fizzbuzz-2.protium b/Task/FizzBuzz/Protium/fizzbuzz-2.protium deleted file mode 100644 index 79cf46b79b..0000000000 --- a/Task/FizzBuzz/Protium/fizzbuzz-2.protium +++ /dev/null @@ -1,9 +0,0 @@ -<@ DEFUDRLIT>__FizzBuzz|<@ SAW> -<@ TSTMD0PARLIT>1|3 -<@ TSTMD0PARLIT>1|5 -<@ O12><@ SAYLIT>Fizz -<@ O22><@ SAYLIT>Buzz -<@ BTH><@ SAYLIT>FizzBuzz -<@ NTH><@ SAYPAR>1 - -<@ ITEFORLITLIT>100|<@ ACTUDRPOSFOR>__FizzBuzz|... diff --git a/Task/FizzBuzz/PureBasic/fizzbuzz.purebasic b/Task/FizzBuzz/PureBasic/fizzbuzz.purebasic deleted file mode 100644 index ef67912a3f..0000000000 --- a/Task/FizzBuzz/PureBasic/fizzbuzz.purebasic +++ /dev/null @@ -1,13 +0,0 @@ -OpenConsole() -For x = 1 To 100 - If x%15 = 0 - PrintN("FizzBuzz") - ElseIf x%3 = 0 - PrintN("Fizz") - ElseIf x%5 = 0 - PrintN("Buzz") - Else - PrintN(Str(x)) - EndIf -Next -Input() diff --git a/Task/FizzBuzz/Python/fizzbuzz-4.py b/Task/FizzBuzz/Python/fizzbuzz-4.py index b29ebd9a54..96cb0268bd 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-4.py +++ b/Task/FizzBuzz/Python/fizzbuzz-4.py @@ -1,13 +1,3 @@ -from itertools import cycle, izip, count, islice - -fizzes = cycle([""] * 2 + ["Fizz"]) -buzzes = cycle([""] * 4 + ["Buzz"]) -both = (f + b for f, b in izip(fizzes, buzzes)) - -# if the string is "", yield the number -# otherwise yield the string -fizzbuzz = (word or n for word, n in izip(both, count(1))) - -# print the first 100 -for i in islice(fizzbuzz, 100): - print i +for n in range(1, 100): + fb = ''.join([ denom[1] if n % denom[0] == 0 else '' for denom in [(3,'fizz'),(5,'buzz')] ]) + print fb if fb else n diff --git a/Task/FizzBuzz/Python/fizzbuzz-5.py b/Task/FizzBuzz/Python/fizzbuzz-5.py index ad3bf57d31..746414bdc9 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-5.py +++ b/Task/FizzBuzz/Python/fizzbuzz-5.py @@ -1,2 +1 @@ -for i in range(1, 101): - print 'Fizz'*(not(i%3))+'Buzz'*(not(i%5)) or i +[print("FizzBuzz") if i % 15 == 0 else print("Fizz") if i % 3 == 0 else print("Buzz") if i % 5 == 0 else print(i) for i in range(1,101)] diff --git a/Task/FizzBuzz/Python/fizzbuzz-6.py b/Task/FizzBuzz/Python/fizzbuzz-6.py index 77a5ab5a81..b29ebd9a54 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-6.py +++ b/Task/FizzBuzz/Python/fizzbuzz-6.py @@ -1,6 +1,13 @@ -messages = [None, "Fizz", "Buzz", "FizzBuzz"] -acc = 810092048 -for i in xrange(1, 101): - c = acc & 3 - print messages[c] if c else i - acc = acc >> 2 | c << 28 +from itertools import cycle, izip, count, islice + +fizzes = cycle([""] * 2 + ["Fizz"]) +buzzes = cycle([""] * 4 + ["Buzz"]) +both = (f + b for f, b in izip(fizzes, buzzes)) + +# if the string is "", yield the number +# otherwise yield the string +fizzbuzz = (word or n for word, n in izip(both, count(1))) + +# print the first 100 +for i in islice(fizzbuzz, 100): + print i diff --git a/Task/FizzBuzz/Python/fizzbuzz-7.py b/Task/FizzBuzz/Python/fizzbuzz-7.py deleted file mode 100644 index 6c7b67d446..0000000000 --- a/Task/FizzBuzz/Python/fizzbuzz-7.py +++ /dev/null @@ -1,14 +0,0 @@ ->>> ' '.join(''.join(''.join(['' if i%3 else 'F', - '' if i%5 else 'B']) - or str('00')) - for i in range(1,16)) -'00 00 F 00 B F 00 00 F B 00 F 00 00 FB' ->>> _ -'00 00 F 00 B F 00 00 F B 00 F 00 00 FB' ->>> _.replace('FB','11').replace('F','01').replace('B','10').split()[::-1] -['11', '00', '00', '01', '00', '10', '01', '00', '00', '01', '10', '00', '01', '00', '00'] ->>> '0b' + ''.join(_) -'0b110000010010010000011000010000' ->>> eval(_) -810092048 ->>> diff --git a/Task/FizzBuzz/Python/fizzbuzz-8.py b/Task/FizzBuzz/Python/fizzbuzz-8.py deleted file mode 100644 index a86ce7860c..0000000000 --- a/Task/FizzBuzz/Python/fizzbuzz-8.py +++ /dev/null @@ -1,6 +0,0 @@ -import random - -for i in range(0, 100): - if not i % 15: - random.seed(1178741599) - print [i+1, "Fizz", "Buzz", "FizzBuzz"][random.randint(0,3)] diff --git a/Task/FizzBuzz/Python/fizzbuzz-9.py b/Task/FizzBuzz/Python/fizzbuzz-9.py deleted file mode 100644 index b29ebd9a54..0000000000 --- a/Task/FizzBuzz/Python/fizzbuzz-9.py +++ /dev/null @@ -1,13 +0,0 @@ -from itertools import cycle, izip, count, islice - -fizzes = cycle([""] * 2 + ["Fizz"]) -buzzes = cycle([""] * 4 + ["Buzz"]) -both = (f + b for f, b in izip(fizzes, buzzes)) - -# if the string is "", yield the number -# otherwise yield the string -fizzbuzz = (word or n for word, n in izip(both, count(1))) - -# print the first 100 -for i in islice(fizzbuzz, 100): - print i diff --git a/Task/FizzBuzz/REALbasic/fizzbuzz.realbasic b/Task/FizzBuzz/REALbasic/fizzbuzz.realbasic deleted file mode 100644 index 00aaf6bf48..0000000000 --- a/Task/FizzBuzz/REALbasic/fizzbuzz.realbasic +++ /dev/null @@ -1,11 +0,0 @@ - For i As Integer = 1 To 100 - If i mod 3 = 0 And i mod 5 = 0 Then - Print("FizzBuzz") - ElseIf i mod 3 = 0 Then - Print("Fizz") - ElseIf i mod 5 = 0 Then - Print("Buzz") - Else - Print(Str(i)) - End If - Next diff --git a/Task/FizzBuzz/Run-BASIC/fizzbuzz.run b/Task/FizzBuzz/Run-BASIC/fizzbuzz.run deleted file mode 100644 index c3eb67c728..0000000000 --- a/Task/FizzBuzz/Run-BASIC/fizzbuzz.run +++ /dev/null @@ -1,7 +0,0 @@ -for i = 1 to 100 - print i; - if (i mod 15) = 0 then print " FuzzBuzz"; - if (i mod 3) = 0 then print " Fuzz"; - if (i mod 5) = 0 then print " Buzz"; - print -next i diff --git a/Task/FizzBuzz/Rust/fizzbuzz-1.rust b/Task/FizzBuzz/Rust/fizzbuzz-1.rust index f5fa200750..d18e3ce843 100644 --- a/Task/FizzBuzz/Rust/fizzbuzz-1.rust +++ b/Task/FizzBuzz/Rust/fizzbuzz-1.rust @@ -1,12 +1,11 @@ -use std::borrow::Cow; fn main() { - for i in 1..101 { - let word: Cow<_> = match (i % 3, i % 5) { - (0,0) => "FizzBuzz".into(), - (0,_) => "Fizz".into(), - (_, 0) => "Buzz".into(), - _ => i.to_string().into(), - }; - println!("{}", word); + let result = (1..101).map(|n| match (n % 3, n % 5) { + (0, 0) => "FizzBuzz".to_owned(), + (0, _) => "Fizz".to_owned(), + (_, 0) => "Buzz".to_owned(), + _ => n.to_string() + }); + for r in result { + println!("{}", r); } } diff --git a/Task/FizzBuzz/Rust/fizzbuzz-2.rust b/Task/FizzBuzz/Rust/fizzbuzz-2.rust index 6691231910..a217d3f240 100644 --- a/Task/FizzBuzz/Rust/fizzbuzz-2.rust +++ b/Task/FizzBuzz/Rust/fizzbuzz-2.rust @@ -1,37 +1,11 @@ - #![no_std] -#![feature(asm, lang_items, libc, no_std, start)] - -extern crate libc; - -const LEN: usize = 413; -static OUT: [u8; LEN] = *b"\ - 1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n\ - 16\n17\nFizz\n19\nBuzz\nFizz\n22\n23\nFizz\nBuzz\n26\nFizz\n28\n29\nFizzBuzz\n\ - 31\n32\nFizz\n34\nBuzz\nFizz\n37\n38\nFizz\nBuzz\n41\nFizz\n43\n44\nFizzBuzz\n\ - 46\n47\nFizz\n49\nBuzz\nFizz\n52\n53\nFizz\nBuzz\n56\nFizz\n58\n59\nFizzBuzz\n\ - 61\n62\nFizz\n64\nBuzz\nFizz\n67\n68\nFizz\nBuzz\n71\nFizz\n73\n74\nFizzBuzz\n\ - 76\n77\nFizz\n79\nBuzz\nFizz\n82\n83\nFizz\nBuzz\n86\nFizz\n88\n89\nFizzBuzz\n\ - 91\n92\nFizz\n94\nBuzz\nFizz\n97\n98\nFizz\nBuzz\n"; - -#[start] -fn start(_argc: isize, _argv: *const *const u8) -> isize { - unsafe { - asm!( - " - mov $$1, %rax - mov $$1, %rdi - mov $0, %rsi - mov $1, %rdx - syscall - " - : - : "r" (&OUT[0]) "r" (LEN) - : "rax", "rdi", "rsi", "rdx" - : - ); +fn main() { + for i in 1..101 { + let word = match (i % 3, i % 5) { + (0, 0) => "FizzBuzz".to_owned(), + (0, _) => "Fizz".to_owned(), + (_, 0) => "Buzz".to_owned(), + _ => i.to_string().to_owned(), + }; + println!("{}", word); } - 0 } - -#[lang = "eh_personality"] extern fn eh_personality() {} -#[lang = "panic_fmt"] extern fn panic_fmt() {} diff --git a/Task/FizzBuzz/Rust/fizzbuzz-3.rust b/Task/FizzBuzz/Rust/fizzbuzz-3.rust index f8ffe1699c..6691231910 100644 --- a/Task/FizzBuzz/Rust/fizzbuzz-3.rust +++ b/Task/FizzBuzz/Rust/fizzbuzz-3.rust @@ -1,16 +1,37 @@ -// rust 0.11 + #![no_std] +#![feature(asm, lang_items, libc, no_std, start)] -fn main() { - for num in std::iter::range_inclusive(1i, 100) { - println!("{}", fizzbuzz(num)) +extern crate libc; + +const LEN: usize = 413; +static OUT: [u8; LEN] = *b"\ + 1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n\ + 16\n17\nFizz\n19\nBuzz\nFizz\n22\n23\nFizz\nBuzz\n26\nFizz\n28\n29\nFizzBuzz\n\ + 31\n32\nFizz\n34\nBuzz\nFizz\n37\n38\nFizz\nBuzz\n41\nFizz\n43\n44\nFizzBuzz\n\ + 46\n47\nFizz\n49\nBuzz\nFizz\n52\n53\nFizz\nBuzz\n56\nFizz\n58\n59\nFizzBuzz\n\ + 61\n62\nFizz\n64\nBuzz\nFizz\n67\n68\nFizz\nBuzz\n71\nFizz\n73\n74\nFizzBuzz\n\ + 76\n77\nFizz\n79\nBuzz\nFizz\n82\n83\nFizz\nBuzz\n86\nFizz\n88\n89\nFizzBuzz\n\ + 91\n92\nFizz\n94\nBuzz\nFizz\n97\n98\nFizz\nBuzz\n"; + +#[start] +fn start(_argc: isize, _argv: *const *const u8) -> isize { + unsafe { + asm!( + " + mov $$1, %rax + mov $$1, %rdi + mov $0, %rsi + mov $1, %rdx + syscall + " + : + : "r" (&OUT[0]) "r" (LEN) + : "rax", "rdi", "rsi", "rdx" + : + ); } + 0 } -fn fizzbuzz(num: int) -> String { - match (num % 3, num % 5) { - (0, 0) => format!("FizzBuzz"), - (0, _) => format!("Fizz"), - (_, 0) => format!("Buzz"), - (_, _) => format!("{}", num), - } -} +#[lang = "eh_personality"] extern fn eh_personality() {} +#[lang = "panic_fmt"] extern fn panic_fmt() {} diff --git a/Task/FizzBuzz/Rust/fizzbuzz-4.rust b/Task/FizzBuzz/Rust/fizzbuzz-4.rust deleted file mode 100644 index f6c50bb0f1..0000000000 --- a/Task/FizzBuzz/Rust/fizzbuzz-4.rust +++ /dev/null @@ -1,20 +0,0 @@ -// rust 0.8 - -fn main() { - let mut n:uint = 1; - while n <= 100 { - if n % 15 == 0 { - println("FizzBuzz"); - } - else if n % 3 == 0 { - println("Fizz"); - } - else if n % 5 == 0 { - println("Buzz"); - } - else { - println(n.to_str()); - } - n += 1; - } -} diff --git a/Task/FizzBuzz/Rust/fizzbuzz-5.rust b/Task/FizzBuzz/Rust/fizzbuzz-5.rust deleted file mode 100644 index 1f48319e30..0000000000 --- a/Task/FizzBuzz/Rust/fizzbuzz-5.rust +++ /dev/null @@ -1,11 +0,0 @@ -// rust 0.8 - -fn main() { for n in std::iter::range_inclusive(1,100) { fizzbuzz(n) }} - -fn fizzbuzz(n:int) { - let mut buf = ~""; - if n % 3 == 0 { buf.push_str("Fizz") } - if n % 5 == 0 { buf.push_str("Buzz") } - if buf != ~"" { println!("{}", buf ) } - else { println!("{}", n ) } -} diff --git a/Task/FizzBuzz/Rust/fizzbuzz-6.rust b/Task/FizzBuzz/Rust/fizzbuzz-6.rust deleted file mode 100644 index 7a71249c2b..0000000000 --- a/Task/FizzBuzz/Rust/fizzbuzz-6.rust +++ /dev/null @@ -1,14 +0,0 @@ -// rust 0.8 - -fn main() { - for num in std::iter::range_inclusive(1, 100) { - println( - match (num % 3, num % 5) { - (0, 0) => ~"FizzBuzz", - (0, _) => ~"Fizz", - (_, 0) => ~"Buzz", - (_, _) => num.to_str() - } - ); - } -} diff --git a/Task/FizzBuzz/Rust/fizzbuzz-7.rust b/Task/FizzBuzz/Rust/fizzbuzz-7.rust deleted file mode 100644 index 7fe1c0669b..0000000000 --- a/Task/FizzBuzz/Rust/fizzbuzz-7.rust +++ /dev/null @@ -1,14 +0,0 @@ -// rust 0.8 - -fn main() { - for num in std::iter::range_inclusive(1, 100) { - println( - match (num % 3 == 0, num % 5 == 0) { - (false, false) => num.to_str(), - (true, false) => ~"Fizz", - (false, true) => ~"Buzz", - (true, true) => ~"FizzBuzz" - } - ); - } -} diff --git a/Task/FizzBuzz/Rust/fizzbuzz-8.rust b/Task/FizzBuzz/Rust/fizzbuzz-8.rust deleted file mode 100644 index 876ca5f309..0000000000 --- a/Task/FizzBuzz/Rust/fizzbuzz-8.rust +++ /dev/null @@ -1,20 +0,0 @@ -// rust 0.8 - -fn main() { - for num in range(1,101) { - let answer = - if num % 15 == 0 { - ~"FizzBuzz" - } - else if num % 3 == 0 { - ~"Fizz" - } - else if num % 5 == 0 { - ~"Buzz" - } - else { - num.to_str() - }; - println(answer); - } -} diff --git a/Task/FizzBuzz/SNUSP/fizzbuzz.snusp b/Task/FizzBuzz/SNUSP/fizzbuzz.snusp deleted file mode 100644 index f12abdc99e..0000000000 --- a/Task/FizzBuzz/SNUSP/fizzbuzz.snusp +++ /dev/null @@ -1,35 +0,0 @@ - / 'B' @=@@=@@++++# - // / 'u' @@@@@=@+++++# - // // / 'z' @=@@@@+@++++# - // // // / 'i' @@@@@@=+++++# - // // // // / 'F' @@@=@@+++++# - // // // // // / LF ++++++++++# - // // // // // // / 100 @@@=@@@=++++# -$@/>@/>@/>@/>@/>@/>@/\ 0 -/ / -! /======= Fizz <<<.<.<..>>># -/ | \ -\?!#->+ @\.>?!#->+ @\.>?!#->+@/.>\ | -/ ! ! ! / | -\?!#->+ @\.>?!#->+@\ .>?!#->+@/.>\ | -/ ! \!===\! ! / | -\?!#->+ @\.>?!#->+ @\.>?!#->+@/.>\ | -/ ! ! | ! / | -\?!#->+@\ .>?!#->+ @\.>?!#->+@/.>\ | -/ \!==========!===\! ! / | -\?!#->+ @\.>?!#->+ @\.>?!#->+@/>>@\.>/ - ! | | | - /==========/ \========!\=== Buzz <<<<<<<.>.>..>>># - | - \!/=dup==?\>>@\+>-/ | \>+<- / - | -/======================/ -| -| /recurse\ #/?\ zero -\print=!\@\>?!\@/<@\.!\-/ - | \=/ \=itoa=@@@+@+++++# - ! /+ !/+ !/+ !/+ \ mod10 - /<+> -\!?-\!?-\!?-\!?-\! - \?!\-?!\-?!\-?!\-?!\-?/\ div10 - # +/! +/! +/! +/! +/ diff --git a/Task/FizzBuzz/Sed/fizzbuzz-2.sed b/Task/FizzBuzz/Sed/fizzbuzz-2.sed index 70ff66685e..e76457f983 100644 --- a/Task/FizzBuzz/Sed/fizzbuzz-2.sed +++ b/Task/FizzBuzz/Sed/fizzbuzz-2.sed @@ -1 +1 @@ -seq 1 100 | sed -r '3~3 s/[0-9]*/Fizz/; 5~5 s/[0-9]*$/Buzz/' +seq 100 | sed '/.*[05]$/s//Buzz/;n;s//Buzz/;n;s//Buzz/;s/^[0-9]*/Fizz/' diff --git a/Task/FizzBuzz/Sed/fizzbuzz-3.sed b/Task/FizzBuzz/Sed/fizzbuzz-3.sed new file mode 100644 index 0000000000..161da3815f --- /dev/null +++ b/Task/FizzBuzz/Sed/fizzbuzz-3.sed @@ -0,0 +1 @@ +seq 100 | sed '0~3 s/.*/Fizz/; 0~5 s/[0-9]*$/Buzz/' diff --git a/Task/FizzBuzz/Sed/fizzbuzz-4.sed b/Task/FizzBuzz/Sed/fizzbuzz-4.sed new file mode 100644 index 0000000000..b6837d0f81 --- /dev/null +++ b/Task/FizzBuzz/Sed/fizzbuzz-4.sed @@ -0,0 +1 @@ +yes | sed -n '0~3s/y/Fizz/;0~5s/y*$/Buzz/;tx;=;b;:x;p;100q' diff --git a/Task/FizzBuzz/Sed/fizzbuzz-5.sed b/Task/FizzBuzz/Sed/fizzbuzz-5.sed new file mode 100644 index 0000000000..1e12017b0d --- /dev/null +++ b/Task/FizzBuzz/Sed/fizzbuzz-5.sed @@ -0,0 +1 @@ +sed -nz '0~3s/^/Fizz/;0~5s/$/Buzz/;tx;=;b;:x;p;100q' /dev/zero | sed 'y/\c@/\n/' diff --git a/Task/FizzBuzz/Standard-ML/fizzbuzz-1.ml b/Task/FizzBuzz/Standard-ML/fizzbuzz-1.ml deleted file mode 100644 index a8457895ac..0000000000 --- a/Task/FizzBuzz/Standard-ML/fizzbuzz-1.ml +++ /dev/null @@ -1,14 +0,0 @@ -local - fun fbstr i = - case (i mod 3 = 0, i mod 5 = 0) of - (true , true ) => "FizzBuzz" - | (true , false) => "Fizz" - | (false, true ) => "Buzz" - | (false, false) => Int.toString i - - fun fizzbuzz' (n, j) = - if n = j then () else (print (fbstr j ^ "\n"); fizzbuzz' (n, j+1)) -in - fun fizzbuzz n = fizzbuzz' (n, 1) - val _ = fizzbuzz 100 -end diff --git a/Task/FizzBuzz/Standard-ML/fizzbuzz-2.ml b/Task/FizzBuzz/Standard-ML/fizzbuzz-2.ml deleted file mode 100644 index 007a5bfe89..0000000000 --- a/Task/FizzBuzz/Standard-ML/fizzbuzz-2.ml +++ /dev/null @@ -1,8 +0,0 @@ -local - fun fb i = let val fizz = i mod 3 = 0 andalso (print "Fizz"; true) - val buzz = i mod 5 = 0 andalso (print "Buzz"; true) - in fizz orelse buzz orelse (print (Int.toString i); true) end -in - fun fizzbuzz n = (List.tabulate (n, fn i => (fb (i+1); print "\n")); ()) - val _ = fizzbuzz 100 -end diff --git a/Task/FizzBuzz/TI-83-BASIC/fizzbuzz.ti-83 b/Task/FizzBuzz/TI-83-BASIC/fizzbuzz.ti-83 deleted file mode 100644 index 3cfb6831e1..0000000000 --- a/Task/FizzBuzz/TI-83-BASIC/fizzbuzz.ti-83 +++ /dev/null @@ -1,16 +0,0 @@ -PROGRAM:FIZZBUZZ -:For(I,1,100) - :0→N - :If fPart(I/5)=0 - :2→N - :If fPart(I/3)=0 - :1+N→N - :If N=0 - :Disp I - :If N=1 - :Disp "FIZZ" - :If N=2 - :Disp "BUZZ" - :If N=3 - :Disp "FIZZBUZZ" -:End diff --git a/Task/FizzBuzz/TransFORTH/fizzbuzz.transforth b/Task/FizzBuzz/TransFORTH/fizzbuzz.transforth new file mode 100644 index 0000000000..55eed888db --- /dev/null +++ b/Task/FizzBuzz/TransFORTH/fizzbuzz.transforth @@ -0,0 +1,10 @@ +: FIZZBUZZ +101 1 DO +I 15 MOD 0 = IF +PRINT " FIZZBUZZ " +ELSE I 3 MOD 0 = IF +PRINT " FIZZ " +ELSE I 5 MOD 0 = IF +PRINT " BUZZ " +ELSE I . THEN THEN THEN +CR LOOP ; diff --git a/Task/FizzBuzz/Visual-Basic-.NET/fizzbuzz.visual b/Task/FizzBuzz/Visual-Basic-.NET/fizzbuzz.visual deleted file mode 100644 index 761a40cf29..0000000000 --- a/Task/FizzBuzz/Visual-Basic-.NET/fizzbuzz.visual +++ /dev/null @@ -1,15 +0,0 @@ -Sub Main() - - For i = 1 To 100 - If i Mod 15 = 0 Then - Console.WriteLine("FizzBuzz") - ElseIf i Mod 5 = 0 Then - Console.WriteLine("Buzz") - ElseIf i Mod 3 = 0 Then - Console.WriteLine("Fizz") - Else - Console.WriteLine(i) - End If - Next - -End Sub diff --git a/Task/FizzBuzz/Whitespace/fizzbuzz-2.ws b/Task/FizzBuzz/Whitespace/fizzbuzz-2.ws deleted file mode 100644 index 59a6f52f82..0000000000 --- a/Task/FizzBuzz/Whitespace/fizzbuzz-2.ws +++ /dev/null @@ -1,29 +0,0 @@ -push 1 ; Initialize a counter. - -0: - dup dup ; Get two copies for the mod checks. - push 3 mod jz 1 - push 5 mod jz 2 - dup onum jump 4 ; If we're still here, just print the number. - -1: ; Print "Fizz", then maybe "Buzz". - push F ochr - push i ochr - call 3 push 5 mod - jz 2 - jump 4 - -2: ; Print "Buzz". - push B ochr - push u ochr - call 3 jump 4 - -3: ; Print "zz"; called as a function for convenient return. - push z dup ochr ochr ret - -4: - push 10 ochr ; Print a newline. - push 1 add dup ; Increment the counter. - push 101 sub - jn 0 ; Go again unless we're at 100. - pop exit ; Exit clean. diff --git a/Task/FizzBuzz/XSLT-1.0/fizzbuzz-1.xslt b/Task/FizzBuzz/XSLT-1.0/fizzbuzz-1.xslt deleted file mode 100644 index 01f77c093c..0000000000 --- a/Task/FizzBuzz/XSLT-1.0/fizzbuzz-1.xslt +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - Fizz - Buzz - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Task/FizzBuzz/XSLT-1.0/fizzbuzz-2.xslt b/Task/FizzBuzz/XSLT-1.0/fizzbuzz-2.xslt deleted file mode 100644 index 282be80d91..0000000000 --- a/Task/FizzBuzz/XSLT-1.0/fizzbuzz-2.xslt +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - <_> - - - - - - - - - -Fizz - - -Buzz - - -FizzBuzz - - - - - - - diff --git a/Task/FizzBuzz/XSLT-2.0/fizzbuzz.xslt b/Task/FizzBuzz/XSLT-2.0/fizzbuzz.xslt deleted file mode 100644 index 6cb338dede..0000000000 --- a/Task/FizzBuzz/XSLT-2.0/fizzbuzz.xslt +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - diff --git a/Task/FizzBuzz/Zkl/fizzbuzz-1.zkl b/Task/FizzBuzz/Zkl/fizzbuzz-1.zkl new file mode 100644 index 0000000000..ef0dda205f --- /dev/null +++ b/Task/FizzBuzz/Zkl/fizzbuzz-1.zkl @@ -0,0 +1,6 @@ +foreach n in ([1..100]) { + if(n % 3 == 0) print("Fizz"); + if(not (n%5)) "Buzz".print(); + if(n%3 and n%5) print(n); + println(); +} diff --git a/Task/FizzBuzz/Zkl/fizzbuzz-2.zkl b/Task/FizzBuzz/Zkl/fizzbuzz-2.zkl new file mode 100644 index 0000000000..0702ddcdbb --- /dev/null +++ b/Task/FizzBuzz/Zkl/fizzbuzz-2.zkl @@ -0,0 +1,3 @@ +fcn f(a,b,c){ a+b and a+b or c } +Walker.cycle("","","Fizz").zipWith(f,Walker.cycle("","","","","Buzz"),[1..]) + .walk(100).concat("\n").println(); diff --git a/Task/FizzBuzz/Zkl/fizzbuzz-3.zkl b/Task/FizzBuzz/Zkl/fizzbuzz-3.zkl new file mode 100644 index 0000000000..b8708859b9 --- /dev/null +++ b/Task/FizzBuzz/Zkl/fizzbuzz-3.zkl @@ -0,0 +1,2 @@ +Walker.cycle(0,0,"Fizz",0,"Buzz","Fizz",0,0,"Fizz","Buzz",0,"Fizz",0,0,"FizzBuzz") + .zipWith(fcn(a,b){ a or b },[1..]).walk(100).concat("\n").println(); diff --git a/Task/Flatten-a-list/Aime/flatten-a-list.aime b/Task/Flatten-a-list/Aime/flatten-a-list.aime index 0c0eea69e0..4e26cc92c3 100644 --- a/Task/Flatten-a-list/Aime/flatten-a-list.aime +++ b/Task/Flatten-a-list/Aime/flatten-a-list.aime @@ -12,9 +12,9 @@ show_list(list l) while (i < l_length(l)) { o_text(s); if (l_s_integer(l, i)) { - o_integer(l_q_integer(l, i)); + o_integer(l[i]); } else { - show_list(l_q_list(l, i)); + show_list(l[i]); } s = ", "; i += 1; @@ -24,18 +24,12 @@ show_list(list l) } void -flat(list c, list l) +flat(list c, object o) { - integer i; - - i = 0; - while (i < l_length(l)) { - if (l_s_integer(l, i)) { - lb_p_integer(c, l_q_integer(l, i)); - } else { - flat(c, l_q_list(l, i)); - } - i += 1; + if (__id(o) == INTEGER_ID) { + l_append(c, o); + } else { + l_ucall(o, flat, 1, c); } } @@ -44,7 +38,7 @@ flatten(list l) { list c; - flat(c, l); + l_ucall(l, flat, 1, c); return c; } @@ -52,16 +46,7 @@ flatten(list l) list nl(...) { - integer i; - list l; - - i = 0; - while (i < count()) { - l_append(l, $i); - i += 1; - } - - return l; + return xcall(l_assemble); } integer @@ -69,8 +54,7 @@ main(void) { list l; - l_set(l, nl(nl(1), 2, nl(nl(3, 4), 5), nl(nl(nl())), nl(nl(nl(6))), 7, 8, - nl())); + l = nl(nl(1), 2, nl(nl(3, 4), 5), nl(nl(nl())), nl(nl(nl(6))), 7, 8, nl()); show_list(l); o_byte('\n'); diff --git a/Task/Flatten-a-list/AppleScript/flatten-a-list-2.applescript b/Task/Flatten-a-list/AppleScript/flatten-a-list-2.applescript index 08924dd3fa..e1f947df6d 100644 --- a/Task/Flatten-a-list/AppleScript/flatten-a-list-2.applescript +++ b/Task/Flatten-a-list/AppleScript/flatten-a-list-2.applescript @@ -1,59 +1,34 @@ --- quickSort :: (Ord a) => [a] -> [a] -on quickSort(xs) - set headTail to uncons(xs) - if headTail is not missing value then - set {h, t} to headTail - - -- lessOrEqual :: a -> Bool - script lessOrEqual - on lambda(x) - x ≤ h - end lambda - end script - - set {less, more} to partition(lessOrEqual, t) - - quickSort(less) & h & quickSort(more) +-- flatten :: Tree a -> [a] +on flatten(t) + if class of t is list then + concatMap(flatten, t) else - xs + t end if -end quickSort +end flatten - --- TEST +-- TEST ----------------------------------------------------------------------- on run - quickSort([11.8, 14.1, 21.3, 8.5, 16.7, 5.7]) - - --> {5.7, 8.5, 11.8, 14.1, 16.7, 21.3} + flatten([[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]) + --> {1, 2, 3, 4, 5, 6, 7, 8} end run +-- GENERIC FUNCTIONS ---------------------------------------------------------- --- GENERIC FUNCTIONS - --- partition :: predicate -> List -> (Matches, nonMatches) --- partition :: (a -> Bool) -> [a] -> ([a], [a]) -on partition(f, xs) +-- concatMap :: (a -> [b]) -> [a] -> [b] +on concatMap(f, xs) + set lst to {} + set lng to length of xs tell mReturn(f) - set lst to {{}, {}} - repeat with x in xs - set v to contents of x - set end of item ((lambda(v) as integer) + 1) of lst to v + repeat with i from 1 to lng + set lst to (lst & |λ|(item i of xs, i, xs)) end repeat - return {item 2 of lst, item 1 of lst} end tell -end partition - --- uncons :: [a] -> Maybe (a, [a]) -on uncons(xs) - if length of xs > 0 then - {item 1 of xs, rest of xs} - else - missing value - end if -end uncons + return lst +end concatMap -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -62,7 +37,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Flatten-a-list/BaCon/flatten-a-list.bacon b/Task/Flatten-a-list/BaCon/flatten-a-list.bacon new file mode 100644 index 0000000000..d79a691885 --- /dev/null +++ b/Task/Flatten-a-list/BaCon/flatten-a-list.bacon @@ -0,0 +1,11 @@ +OPTION COLLAPSE TRUE + +lst$ = "\"1\",2,\"\\\"3,4\\\",5\",\"\\\"\\\\\"\\\\\"\\\"\",\"\\\"\\\\\"6\\\\\"\\\"\",7,8,\"\"" + +PRINT lst$ + +REPEAT + lst$ = FLATTEN$(lst$) +UNTIL AMOUNT(lst$, ",") = AMOUNT(FLATTEN$(lst$), ",") + +PRINT SORT$(lst$, ",") diff --git a/Task/Flatten-a-list/Gambas/flatten-a-list.gambas b/Task/Flatten-a-list/Gambas/flatten-a-list.gambas new file mode 100644 index 0000000000..ba571d7977 --- /dev/null +++ b/Task/Flatten-a-list/Gambas/flatten-a-list.gambas @@ -0,0 +1,16 @@ +'Code 'borrowed' from Run BASIC + +Public Sub Main() +Dim sComma, sString, sFlatter As String +Dim siCount As Short + +sString = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]" +For siCount = 1 To Len(sString) + If InStr("[] ,", Mid$(sString, siCount, 1)) = 0 Then + sFlatter = sFlatter & sComma & Mid(sString, siCount, 1) + sComma = "," + End If +Next +Print "["; sFlatter; "]" + +End diff --git a/Task/Flatten-a-list/Haskell/flatten-a-list-1.hs b/Task/Flatten-a-list/Haskell/flatten-a-list-1.hs index ae17e9286b..82243d255f 100644 --- a/Task/Flatten-a-list/Haskell/flatten-a-list-1.hs +++ b/Task/Flatten-a-list/Haskell/flatten-a-list-1.hs @@ -1,24 +1,26 @@ -import Data.Tree +import Data.Tree (Tree(..), flatten) -- [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] -- implemented as multiway tree: - -- Data.Tree represents trees where nodes have values too, unlike the trees in our problem. -- so we use a list as that value, where a node will have an empty list value, -- and a leaf will have a one-element list value and no subtrees list :: Tree [Int] -list = Node [] [ - Node [] [Node [1] []], - Node [2] [], - Node [] [ - Node [] [ Node [3] [],Node [4] []], - Node [5] [] - ], - Node [] [Node [] [Node [] []]], - Node [] [Node [] [Node [6] []]], - Node [7] [], - Node [8] [], - Node [] [] - ] +list = + Node + [] + [ Node [] [Node [1] []] + , Node [2] [] + , Node [] [Node [] [Node [3] [], Node [4] []], Node [5] []] + , Node [] [Node [] [Node [] []]] + , Node [] [Node [] [Node [6] []]] + , Node [7] [] + , Node [8] [] + , Node [] [] + ] -flattenList = concat.flatten +flattenList :: Tree [a] -> [a] +flattenList = concat . flatten + +main :: IO () +main = print $ flattenList list diff --git a/Task/Flatten-a-list/Haskell/flatten-a-list-2.hs b/Task/Flatten-a-list/Haskell/flatten-a-list-2.hs index a46d4fba81..3a05799b06 100644 --- a/Task/Flatten-a-list/Haskell/flatten-a-list-2.hs +++ b/Task/Flatten-a-list/Haskell/flatten-a-list-2.hs @@ -1,16 +1,22 @@ -data Tree a = Leaf a | Node [Tree a] +data Tree a + = Leaf a + | Node [Tree a] flatten :: Tree a -> [a] flatten (Leaf x) = [x] flatten (Node xs) = concatMap flatten xs -main = print $ flatten $ Node [Node [Leaf 1], - Leaf 2, - Node [Node [Leaf 3, Leaf 4], Leaf 5], - Node [Node [Node []]], - Node [Node [Node [Leaf 6]]], - Leaf 7, - Leaf 8, - Node []] - +main :: IO () +main = + (print . flatten) $ + Node + [ Node [Leaf 1] + , Leaf 2 + , Node [Node [Leaf 3, Leaf 4], Leaf 5] + , Node [Node [Node []]] + , Node [Node [Node [Leaf 6]]] + , Leaf 7 + , Leaf 8 + , Node [] + ] -- output: [1,2,3,4,5,6,7,8] diff --git a/Task/Flatten-a-list/Haskell/flatten-a-list-3.hs b/Task/Flatten-a-list/Haskell/flatten-a-list-3.hs index f418c4d075..77f935dcd7 100644 --- a/Task/Flatten-a-list/Haskell/flatten-a-list-3.hs +++ b/Task/Flatten-a-list/Haskell/flatten-a-list-3.hs @@ -1,17 +1,29 @@ -data NestedList a = NList [NestedList a] | Entry a +data NestedList a + = NList [NestedList a] + | Entry a flatten :: NestedList a -> [a] -flatten nl = flatten' nl [] +flatten nl = flatten_ nl [] where - -- By passing through a list which the results will be preprended to we allow efficient lazy evaluation - flatten' :: NestedList a -> [a] -> [a] - flatten' (Entry a) cont = a:cont - flatten' (NList entries) cont = foldr flatten' cont entries + flatten_ :: NestedList a -> [a] -> [a] + flatten_ (Entry a) cont = a : cont + flatten_ (NList entries) cont = foldr flatten_ cont entries +-- By passing through a list to which the results will be prepended, +-- we allow for efficient lazy evaluation example :: NestedList Int -example = NList [ NList [Entry 1], Entry 2, NList [NList [Entry 3, Entry 4], Entry 5], NList [NList [NList []]], NList [ NList [ NList [Entry 6]]], Entry 7, Entry 8, NList []] +example = + NList + [ NList [Entry 1] + , Entry 2 + , NList [NList [Entry 3, Entry 4], Entry 5] + , NList [NList [NList []]] + , NList [NList [NList [Entry 6]]] + , Entry 7 + , Entry 8 + , NList [] + ] main :: IO () main = print $ flatten example - -- output [1,2,3,4,5,6,7,8] diff --git a/Task/Flatten-a-list/Hy/flatten-a-list.hy b/Task/Flatten-a-list/Hy/flatten-a-list.hy new file mode 100644 index 0000000000..8b14bcaf20 --- /dev/null +++ b/Task/Flatten-a-list/Hy/flatten-a-list.hy @@ -0,0 +1,9 @@ +(defn flatten [lst] + (sum (genexpr (if (isinstance x list) + (flatten x) + [x]) + [x lst]) + [])) + +(print (flatten [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []])) +; [1, 2, 3, 4, 5, 6, 7, 8] diff --git a/Task/Flatten-a-list/jq/flatten-a-list-1.jq b/Task/Flatten-a-list/Jq/flatten-a-list-1.jq similarity index 100% rename from Task/Flatten-a-list/jq/flatten-a-list-1.jq rename to Task/Flatten-a-list/Jq/flatten-a-list-1.jq diff --git a/Task/Flatten-a-list/jq/flatten-a-list-2.jq b/Task/Flatten-a-list/Jq/flatten-a-list-2.jq similarity index 100% rename from Task/Flatten-a-list/jq/flatten-a-list-2.jq rename to Task/Flatten-a-list/Jq/flatten-a-list-2.jq diff --git a/Task/Flatten-a-list/Julia/flatten-a-list-1.julia b/Task/Flatten-a-list/Julia/flatten-a-list-1.julia index 5d423fde4b..b5ada8a348 100644 --- a/Task/Flatten-a-list/Julia/flatten-a-list-1.julia +++ b/Task/Flatten-a-list/Julia/flatten-a-list-1.julia @@ -1,10 +1 @@ -julia> t = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] -8-element Int32 Array: - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 +flat(A) = mapreduce(x->isa(x,Array)? flat(x): x, vcat, [], A) diff --git a/Task/Flatten-a-list/Julia/flatten-a-list-2.julia b/Task/Flatten-a-list/Julia/flatten-a-list-2.julia index 6437725aa5..3fce66af5a 100644 --- a/Task/Flatten-a-list/Julia/flatten-a-list-2.julia +++ b/Task/Flatten-a-list/Julia/flatten-a-list-2.julia @@ -1 +1,8 @@ -flat(A) = [[isa(x,Array)? flat(x): x for x in A]...] +function flat(A) + result = Any[] + grep(a) = for x in a + isa(x,Array) ? grep(x) : push!(result,x) + end + grep(A) + result + end diff --git a/Task/Flatten-a-list/Julia/flatten-a-list-3.julia b/Task/Flatten-a-list/Julia/flatten-a-list-3.julia deleted file mode 100644 index b5ada8a348..0000000000 --- a/Task/Flatten-a-list/Julia/flatten-a-list-3.julia +++ /dev/null @@ -1 +0,0 @@ -flat(A) = mapreduce(x->isa(x,Array)? flat(x): x, vcat, [], A) diff --git a/Task/Flatten-a-list/Julia/flatten-a-list-4.julia b/Task/Flatten-a-list/Julia/flatten-a-list-4.julia deleted file mode 100644 index 3fce66af5a..0000000000 --- a/Task/Flatten-a-list/Julia/flatten-a-list-4.julia +++ /dev/null @@ -1,8 +0,0 @@ -function flat(A) - result = Any[] - grep(a) = for x in a - isa(x,Array) ? grep(x) : push!(result,x) - end - grep(A) - result - end diff --git a/Task/Flatten-a-list/Kotlin/flatten-a-list.kotlin b/Task/Flatten-a-list/Kotlin/flatten-a-list.kotlin new file mode 100644 index 0000000000..25d78c6dca --- /dev/null +++ b/Task/Flatten-a-list/Kotlin/flatten-a-list.kotlin @@ -0,0 +1,29 @@ +// version 1.0.6 + +@Suppress("UNCHECKED_CAST") + +fun flattenList(nestList: List, flatList: MutableList) { + for (e in nestList) + if (e is Int) + flatList.add(e) + else + // using unchecked cast here as can't check for instance of 'erased' generic type + flattenList(e as List, flatList) +} + +fun main(args: Array) { + val nestList : List = listOf( + listOf(1), + 2, + listOf(listOf(3, 4), 5), + listOf(listOf(listOf())), + listOf(listOf(listOf(6))), + 7, + 8, + listOf() + ) + println("Nested : " + nestList) + val flatList = mutableListOf() + flattenList(nestList, flatList) + println("Flattened : " + flatList) +} diff --git a/Task/Flatten-a-list/Objective-C/flatten-a-list-1.m b/Task/Flatten-a-list/Objective-C/flatten-a-list-1.m deleted file mode 100644 index fed3cd3ba1..0000000000 --- a/Task/Flatten-a-list/Objective-C/flatten-a-list-1.m +++ /dev/null @@ -1,56 +0,0 @@ -#import - -@interface NSArray (FlattenExt) --(NSArray *)flatten; -@end - -@implementation NSArray (FlattenExt) --(NSArray *)flatten -{ - NSMutableArray *r = [NSMutableArray array]; - NSEnumerator *en = [self objectEnumerator]; - id o; - while ( (o = [en nextObject]) ) { - if ( [o isKindOfClass: [NSArray class]] ) - [r addObjectsFromArray: [o flatten]]; - else - [r addObject: o]; - } - return [NSArray arrayWithArray: r]; -} -@end - -int main() -{ - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - NSArray *p = [NSArray - arrayWithObjects: - [NSArray arrayWithObjects: [NSNumber numberWithInt: 1], nil], - [NSNumber numberWithInt: 2], - [NSArray arrayWithObjects: - [NSArray arrayWithObjects: [NSNumber numberWithInt: 3], - [NSNumber numberWithInt: 4], nil], - [NSNumber numberWithInt: 5], nil], - [NSArray arrayWithObjects: - [NSArray arrayWithObjects: - [NSArray arrayWithObjects: nil], nil], nil], - [NSArray arrayWithObjects: - [NSArray arrayWithObjects: - [NSArray arrayWithObjects: - [NSNumber numberWithInt: 6], nil], nil], nil], - [NSNumber numberWithInt: 7], - [NSNumber numberWithInt: 8], - [NSArray arrayWithObjects: nil], nil]; - NSArray *f = [p flatten]; - NSEnumerator *e = [f objectEnumerator]; - id o; - while( (o = [e nextObject]) ) - { - NSLog(@"%@", o); - } - - - [pool drain]; - return 0; -} diff --git a/Task/Flatten-a-list/Objective-C/flatten-a-list-2.m b/Task/Flatten-a-list/Objective-C/flatten-a-list-2.m deleted file mode 100644 index 9149e6788b..0000000000 --- a/Task/Flatten-a-list/Objective-C/flatten-a-list-2.m +++ /dev/null @@ -1,40 +0,0 @@ -#import - -@interface NSArray (FlattenExt) -@property (nonatomic, readonly) NSArray *flattened; -@end - -@implementation NSArray (FlattenExt) --(NSArray *) flattened { - NSMutableArray *flattened = [[NSMutableArray alloc] initWithCapacity:self.count]; - - for (id object in self) { - if ([object isKindOfClass:[NSArray class]]) - [flattened addObjectsFromArray:((NSArray *)object).flattened]; - else - [flattened addObject:object]; - } - - return [flattened autorelease]; -} -@end - -int main() { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSArray *unflattened = [NSArray arrayWithObjects:[NSArray arrayWithObject:[NSNumber numberWithInteger:1]], - [NSNumber numberWithInteger:2], - [NSArray arrayWithObjects:[NSArray arrayWithObjects:[NSNumber numberWithInteger:3], [NSNumber numberWithInteger:4], nil], - [NSNumber numberWithInteger:5], nil], - [NSArray arrayWithObject:[NSArray arrayWithObject:[NSArray array]]], - [NSArray arrayWithObject:[NSArray arrayWithObject:[NSArray arrayWithObject:[NSNumber numberWithInteger:6]]]], - [NSNumber numberWithInteger:7], - [NSNumber numberWithInteger:8], - [NSArray array], nil]; - - for (id object in unflattened.flattened) - NSLog(@"%@", object); - - [pool drain]; - - return 0; -} diff --git a/Task/Flatten-a-list/OoRexx/flatten-a-list.rexx b/Task/Flatten-a-list/OoRexx/flatten-a-list.rexx new file mode 100644 index 0000000000..8c7276a97d --- /dev/null +++ b/Task/Flatten-a-list/OoRexx/flatten-a-list.rexx @@ -0,0 +1,36 @@ +sub1 = .array~of(1) +sub2 = .array~of(3, 4) +sub3 = .array~of(sub2, 5) +sub4 = .array~of(.array~of(.array~new)) +sub5 = .array~of(.array~of(.array~of(6))) +sub6 = .array~new + +-- final list construction +list = .array~of(sub1, 2, sub3, sub4, sub5, 7, 8, sub6) + +-- flatten +flatlist = flattenList(list) + +say "["flatlist~toString("line", ", ")"]" + +::routine flattenList + use arg list + -- we could use a list or queue, but let's just use an array + accumulator = .array~new + + -- now go to the recursive processing version + call flattenSublist list, accumulator + + return accumulator + +::routine flattenSublist + use arg list, accumulator + + -- ask for the items explicitly, since this will allow + -- us to flatten indexed collections as well + do item over list~allItems + -- if the object is some sort of collection, flatten this out rather + -- than add to the accumulator + if item~isA(.collection) then call flattenSublist item, accumulator + else accumulator~append(item) + end diff --git a/Task/Flatten-a-list/Perl-6/flatten-a-list.pl6 b/Task/Flatten-a-list/Perl-6/flatten-a-list-1.pl6 similarity index 100% rename from Task/Flatten-a-list/Perl-6/flatten-a-list.pl6 rename to Task/Flatten-a-list/Perl-6/flatten-a-list-1.pl6 diff --git a/Task/Flatten-a-list/Perl-6/flatten-a-list-2.pl6 b/Task/Flatten-a-list/Perl-6/flatten-a-list-2.pl6 new file mode 100644 index 0000000000..c4ddfbfff8 --- /dev/null +++ b/Task/Flatten-a-list/Perl-6/flatten-a-list-2.pl6 @@ -0,0 +1 @@ +say { |(@$_ > 1 ?? map(&?BLOCK, @$_) !! $_) }(@l) diff --git a/Task/Flatten-a-list/Racket/flatten-a-list-3.rkt b/Task/Flatten-a-list/Racket/flatten-a-list-3.rkt deleted file mode 100644 index 23d561f717..0000000000 --- a/Task/Flatten-a-list/Racket/flatten-a-list-3.rkt +++ /dev/null @@ -1,6 +0,0 @@ -#lang racket -(define (flatten l) - (cond [(empty? l) null] - [(not (list? l)) (list l)] - [else (append (flatten (first l)) (flatten (rest l)))])) -(flatten '(1 (2 (3 4 5) (6 7)) 8 9)) diff --git a/Task/Flatten-a-list/Rust/flatten-a-list.rust b/Task/Flatten-a-list/Rust/flatten-a-list.rust new file mode 100644 index 0000000000..a9f75485aa --- /dev/null +++ b/Task/Flatten-a-list/Rust/flatten-a-list.rust @@ -0,0 +1,92 @@ +use std::{vec, mem, iter}; + +enum List { + Node(Vec>), + Leaf(T), +} + +impl IntoIterator for List { + type Item = List; + type IntoIter = ListIter; + fn into_iter(self) -> Self::IntoIter { + match self { + List::Node(vec) => ListIter::NodeIter(vec.into_iter()), + leaf @ List::Leaf(_) => ListIter::LeafIter(iter::once(leaf)), + } + } +} + +enum ListIter { + NodeIter(vec::IntoIter>), + LeafIter(iter::Once>), +} + +impl ListIter { + fn flatten(self) -> Flatten { + Flatten { + stack: Vec::new(), + curr: self, + } + } +} + +impl Iterator for ListIter { + type Item = List; + fn next(&mut self) -> Option { + match *self { + ListIter::NodeIter(ref mut v_iter) => v_iter.next(), + ListIter::LeafIter(ref mut o_iter) => o_iter.next(), + } + } +} + +struct Flatten { + stack: Vec>, + curr: ListIter, +} + +// Flatten code is a little messy since we are shoehorning recursion into an Iterator +impl Iterator for Flatten { + type Item = T; + fn next(&mut self) -> Option { + loop { + match self.curr.next() { + Some(list) => { + match list { + node @ List::Node(_) => { + self.stack.push(node.into_iter()); + let len = self.stack.len(); + mem::swap(&mut self.stack[len - 1], &mut self.curr); + } + List::Leaf(item) => return Some(item), + } + } + None => { + if let Some(next) = self.stack.pop() { + self.curr = next; + } else { + return None; + } + } + } + } + } +} + +use List::*; +fn main() { + let list = Node(vec![Node(vec![Leaf(1)]), + Leaf(2), + Node(vec![Node(vec![Leaf(3), Leaf(4)]), Leaf(5)]), + Node(vec![Node(vec![Node(vec![])])]), + Node(vec![Node(vec![Node(vec![Leaf(6)])])]), + Leaf(7), + Leaf(8), + Node(vec![])]); + + for elem in list.into_iter().flatten() { + print!("{} ", elem); + } + println!(); + +} diff --git a/Task/Flatten-a-list/VBScript/flatten-a-list-4.vb b/Task/Flatten-a-list/VBScript/flatten-a-list-4.vb deleted file mode 100644 index 527938aa5f..0000000000 --- a/Task/Flatten-a-list/VBScript/flatten-a-list-4.vb +++ /dev/null @@ -1,15 +0,0 @@ -' Flatten the example array... -a = FlattenArray(Array(Array(1), 2, Array(Array(3,4), 5), Array(Array(Array())), Array(Array(Array(6))), 7, 8, Array())) - -' Print the list, comma-separated... -WScript.Echo Join(a, ",") - -Function FlattenArray(a) - If IsArray(a) Then DoFlatten a, FlattenArray: FlattenArray = Split(Trim(FlattenArray)) -End Function - -Sub DoFlatten(a, s) - For i = 0 To UBound(a) - If IsArray(a(i)) Then DoFlatten a(i), s Else s = s & a(i) & " " - Next -End Sub diff --git a/Task/Flatten-a-list/Zkl/flatten-a-list.zkl b/Task/Flatten-a-list/Zkl/flatten-a-list.zkl new file mode 100644 index 0000000000..aaaa6c49d8 --- /dev/null +++ b/Task/Flatten-a-list/Zkl/flatten-a-list.zkl @@ -0,0 +1,5 @@ +fcn flatten(list){ list.pump(List, + fcn(i){ if(List.isType(i)) return(Void.Recurse,i,self.fcn); i}) } + +flatten(L(L(1), L(2), L(L(3,4), 5), L(L(L())), L(L(L(6))), 7, 8, L())) +//-->L(1,2,3,4,5,6,7,8) diff --git a/Task/Flipping-bits-game/Haskell/flipping-bits-game.hs b/Task/Flipping-bits-game/Haskell/flipping-bits-game.hs index 382accf1d3..078f3a7add 100644 --- a/Task/Flipping-bits-game/Haskell/flipping-bits-game.hs +++ b/Task/Flipping-bits-game/Haskell/flipping-bits-game.hs @@ -1,7 +1,10 @@ -import Data.Array -import Data.List -import Control.Monad -import System.Random +import Data.List (intersperse) + +import System.Random (randomRIO) + +import Data.Array (Array, (!), (//), array, bounds) + +import Control.Monad (zipWithM_, replicateM, foldM, when) type Board = Array (Char, Char) Int @@ -9,86 +12,104 @@ flp :: Int -> Int flp 0 = 1 flp 1 = 0 -numRows, numCols :: Board -> [Char] -numRows t = let ((a, _), (b, _)) = bounds t in [a .. b] +numRows, numCols :: Board -> String +numRows t = + let ((a, _), (b, _)) = bounds t + in [a .. b] -numCols t = let ((_, a), (_, b)) = bounds t in [a .. b] +numCols t = + let ((_, a), (_, b)) = bounds t + in [a .. b] flipRow, flipCol :: Board -> Char -> Board -flipRow t r = let e = [ (ix, flp (t ! ix)) | ix <- - zip (repeat r) (numCols t) ] - in t // e +flipRow t r = + let e = + [ (ix, flp (t ! ix)) + | ix <- zip (repeat r) (numCols t) ] + in t // e -flipCol t c = let e = [ (ix, flp (t ! ix)) | ix <- - zip (numRows t) (repeat c) ] - in t // e +flipCol t c = + let e = + [ (ix, flp (t ! ix)) + | ix <- zip (numRows t) (repeat c) ] + in t // e printBoard :: Board -> IO () printBoard t = do - let rows = numRows t - cols = numCols t - f 0 = '0' - f 1 = '1' - p r xs = putStrLn $ [r, ' '] ++ intersperse ' ' (map f xs) - putStrLn $ " " ++ intersperse ' ' cols - zipWithM_ p rows [ [ t ! (y, x) | x <- cols ] | y <- rows ] + let rows = numRows t + cols = numCols t + f 0 = '0' + f 1 = '1' + p r xs = putStrLn $ [r, ' '] ++ intersperse ' ' (map f xs) + putStrLn $ " " ++ intersperse ' ' cols + zipWithM_ + p + rows + [ [ t ! (y, x) + | x <- cols ] + | y <- rows ] -- create a random goal board, and flip rows and columns randomly -- to get a starting board setupGame :: Char -> Char -> IO (Board, Board) -setupGame sizey sizex = do - -- random cell value at (row, col) - let mk rc = fmap (\v -> (rc, v)) $ randomRIO (0, 1) - rows = ['a' .. sizey] - cols = ['1' .. sizex] - goal <- fmap (array (('a', '1'), (sizey, sizex))) $ - mapM mk [ (r, c) | r <- rows, c <- cols ] - start <- do - let change :: Board -> Int -> IO Board - -- flip random row - change t 0 = fmap (flipRow t) $ randomRIO ('a', sizey) - -- flip random col - change t 1 = fmap (flipCol t) $ randomRIO ('1', sizex) - numMoves <- randomRIO (3, 15) -- how many flips (3 - 15) - -- determine if rows or cols are flipped - moves <- replicateM numMoves $ randomRIO (0, 1) - -- make changes and get a starting board - foldM change goal moves - if goal /= start -- check if boards are different - then return (goal, start) -- all ok, return both boards - else setupGame sizey sizex -- try again +setupGame sizey sizex + -- random cell value at (row, col) + = do + let mk rc = (\v -> (rc, v)) <$> randomRIO (0, 1) + rows = ['a' .. sizey] + cols = ['1' .. sizex] + goal <- + array (('a', '1'), (sizey, sizex)) <$> + mapM + mk + [ (r, c) + | r <- rows + , c <- cols ] + start <- + do let change :: Board -> Int -> IO Board + -- flip random row + change t 0 = flipRow t <$> randomRIO ('a', sizey) + -- flip random col + change t 1 = flipCol t <$> randomRIO ('1', sizex) + numMoves <- randomRIO (3, 15) -- how many flips (3 - 15) + -- determine if rows or cols are flipped + moves <- replicateM numMoves $ randomRIO (0, 1) + -- make changes and get a starting board + foldM change goal moves + if goal /= start -- check if boards are different + then return (goal, start) -- all ok, return both boards + else setupGame sizey sizex -- try again main :: IO () main = do - putStrLn "Select a board size (1 - 9).\nPress any other key to exit." - sizec <- getChar - when (sizec `elem` ['1' .. '9']) $ do - let size = read [sizec] - 1 - (g, s) <- setupGame (['a'..] !! size) (['1'..] !! size) - turns g s 0 - - where - turns goal current moves = do - putStrLn "\nGoal:" - printBoard goal - putStrLn "\nBoard:" - printBoard current - when (moves > 0) $ - putStrLn $ "\nYou've made " ++ show moves ++ " moves so far." - putStrLn $ "\nFlip a row (" ++ numRows current ++ - ") or a column (" ++ numCols current ++ ")" - v <- getChar - if v `elem` numRows current - then check $ flipRow current v - else if v `elem` numCols current - then check $ flipCol current v - else tryAgain - - where check t = if t == goal - then putStrLn $ "\nYou've won in " ++ - show (moves + 1) ++ " moves!" - else turns goal t (moves + 1) - - tryAgain = do - putStrLn ": Invalid row or column." - turns goal current moves + putStrLn "Select a board size (1 - 9).\nPress any other key to exit." + sizec <- getChar + when (sizec `elem` ['1' .. '9']) $ + do let size = read [sizec] - 1 + (g, s) <- setupGame (['a' ..] !! size) (['1' ..] !! size) + turns g s 0 + where + turns goal current moves = do + putStrLn "\nGoal:" + printBoard goal + putStrLn "\nBoard:" + printBoard current + when (moves > 0) $ + putStrLn $ "\nYou've made " ++ show moves ++ " moves so far." + putStrLn $ + "\nFlip a row (" ++ + numRows current ++ ") or a column (" ++ numCols current ++ ")" + v <- getChar + if v `elem` numRows current + then check $ flipRow current v + else if v `elem` numCols current + then check $ flipCol current v + else tryAgain + where + check t = + if t == goal + then putStrLn $ "\nYou've won in " ++ show (moves + 1) ++ " moves!" + else turns goal t (moves + 1) + tryAgain = do + putStrLn ": Invalid row or column." + turns goal current moves diff --git a/Task/Flipping-bits-game/Kotlin/flipping-bits-game.kotlin b/Task/Flipping-bits-game/Kotlin/flipping-bits-game.kotlin new file mode 100644 index 0000000000..8689ed870a --- /dev/null +++ b/Task/Flipping-bits-game/Kotlin/flipping-bits-game.kotlin @@ -0,0 +1,92 @@ +// version 1.1.3 + +import java.util.Random + +val rand = Random() +val target = Array(3) { IntArray(3) { rand.nextInt(2) } } +val board = Array(3) { IntArray(3) } + +fun flipRow(r: Int) { + for (c in 0..2) board[r][c] = if (board[r][c] == 0) 1 else 0 +} + +fun flipCol(c: Int) { + for (r in 0..2) board[r][c] = if (board[r][c] == 0) 1 else 0 +} + +/** starting from the target we make 9 random row or column flips */ +fun initBoard() { + for (i in 0..2) { + for (j in 0..2) board[i][j] = target[i][j] + } + repeat(9) { + val rc = rand.nextInt(2) + if (rc == 0) + flipRow(rand.nextInt(3)) + else + flipCol(rand.nextInt(3)) + } +} + +fun printBoard(label: String, isTarget: Boolean = false) { + val a = if (isTarget) target else board + println("$label:") + println(" | a b c") + println("---------") + for (r in 0..2) { + print("${r + 1} |") + for (c in 0..2) print(" ${a[r][c]}") + println() + } + println() +} + +fun gameOver(): Boolean { + for (r in 0..2) { + for (c in 0..2) if (board[r][c] != target[r][c]) return false + } + return true +} + +fun main(args: Array) { + // initialize board and ensure it differs from the target i.e. game not already over! + do { + initBoard() + } + while(gameOver()) + + printBoard("TARGET", true) + printBoard("OPENING BOARD") + var flips = 0 + + do { + var isRow = true + var n = -1 + do { + print("Enter row number or column letter to be flipped: ") + val input = readLine()!! + val ch = if (input.isNotEmpty()) input[0].toLowerCase() else '0' + if (ch !in "123abc") { + println("Must be 1, 2, 3, a, b or c") + continue + } + if (ch in '1'..'3') { + n = ch.toInt() - 49 + } + else { + isRow = false + n = ch.toInt() - 97 + } + } + while (n == -1) + + flips++ + if (isRow) flipRow(n) else flipCol(n) + val plural = if (flips == 1) "" else "S" + printBoard("\nBOARD AFTER $flips FLIP$plural") + } + while (!gameOver()) + + val plural = if (flips == 1) "" else "s" + println("You've succeeded in $flips flip$plural") +} diff --git a/Task/Flipping-bits-game/Lua/flipping-bits-game.lua b/Task/Flipping-bits-game/Lua/flipping-bits-game.lua new file mode 100644 index 0000000000..76cf2074ff --- /dev/null +++ b/Task/Flipping-bits-game/Lua/flipping-bits-game.lua @@ -0,0 +1,95 @@ +target, board, moves, W, H = {}, {}, 0, 3, 3 + +function getIndex( i, j ) return i + j * W - W end + +function flip( d, r ) + function invert( a ) if a == 1 then return 0 end return 1 end + local idx + if d == 1 then + for i = 1, W do + idx = getIndex( i, r ) + board[idx] = invert( board[idx] ) + end + else + for i = 1, H do + idx = getIndex( r, i ) + board[idx] = invert( board[idx] ) + end + end + moves = moves + 1 +end +function createTarget() + target, board = {}, {} + local idx + for j = 1, H do + for i = 1, W do + idx = getIndex( i, j ) + if math.random() < .5 then target[idx] = 0 + else target[idx] = 1 + end + board[idx] = target[idx] + end + end + for i = 1, 103 do + if math.random() < .5 then flip( 1, math.random( H ) ) + else flip( 2, math.random( W ) ) + end + end + moves = 0 +end +function getUserInput() + io.write( "Input row and/or column: " ); local r = io.read() + local a + for i = 1, #r do + a = string.byte( r:sub( i, i ):lower() ) + if a >= 48 and a <= 57 then flip( 2, a - 48 ) end + if a >= 97 and a <= string.byte( 'z' ) then flip( 1, a - 96 ) end + end +end +function solved() + local idx + for j = 1, H do + for i = 1, W do + idx = getIndex( i, j ) + if target[idx] ~= board[idx] then return false end + end + end + return true +end +function display() + local idx + io.write( "\nTARGET\n " ) + for i = 1, W do io.write( string.format( "%d ", i ) ) end; print() + for j = 1, H do + io.write( string.format( "%s ", string.char( 96 + j ) ) ) + for i = 1, W do + idx = getIndex( i, j ) + io.write( string.format( "%d ", target[idx] ) ) + end; io.write( "\n" ) + end + io.write( "\nBOARD\n " ) + for i = 1, W do io.write( string.format( "%d ", i ) ) end; print() + for j = 1, H do + io.write( string.format( "%s ", string.char( 96 + j ) ) ) + for i = 1, W do + idx = getIndex( i, j ) + io.write( string.format( "%d ", board[idx] ) ) + end; io.write( "\n" ) + end + io.write( string.format( "Moves: %d\n", moves ) ) +end +function play() + while true do + createTarget() + repeat + display() + getUserInput() + until solved() + display() + io.write( "Very well!\nPlay again(Y/N)? " ); + if io.read():lower() ~= "y" then return end + end +end +--[[entry point]]-- +math.randomseed( os.time() ) +play() diff --git a/Task/Flipping-bits-game/Perl-6/flipping-bits-game.pl6 b/Task/Flipping-bits-game/Perl-6/flipping-bits-game.pl6 index 25463da7f6..e479be4bcd 100644 --- a/Task/Flipping-bits-game/Perl-6/flipping-bits-game.pl6 +++ b/Task/Flipping-bits-game/Perl-6/flipping-bits-game.pl6 @@ -39,7 +39,7 @@ sub build (%hash) { my $string = ' '; $string ~= sprintf "%2s ", $_ for sort keys %hash{'1'}; $string ~= "\n"; - for sort keys %hash -> $key { + for %hash.keys.sort: +* -> $key { $string ~= sprintf "%2s ", $key; $string ~= sprintf "%2s ", %hash{$key}{$_} for sort keys %hash{$key}; $string ~= "\n"; @@ -49,6 +49,6 @@ sub build (%hash) { sub scramble(%hash) { my @keys = keys %hash; - @keys ,= keys %hash{'1'}; + @keys.push: | keys %hash{'1'}; flip $_, %hash for @keys.pick( @keys/2 ); } diff --git a/Task/Flipping-bits-game/REXX/flipping-bits-game.rexx b/Task/Flipping-bits-game/REXX/flipping-bits-game.rexx index 7653d874fe..e6db114432 100644 --- a/Task/Flipping-bits-game/REXX/flipping-bits-game.rexx +++ b/Task/Flipping-bits-game/REXX/flipping-bits-game.rexx @@ -1,16 +1,14 @@ /*REXX program presents a "flipping bit" puzzle. The user can solve via it via C.L. */ -parse arg N u on off . /*get optional arguments from the C.L. */ +parse arg N u . /*get optional arguments from the C.L. */ if N=='' | N=="," then N =3 /*Size given? Then use default of 3.*/ if u=='' | u=="," then u =N /*the number of bits initialized to ON.*/ -if on =='' then on =1 /*the character used for "on". */ -if off=='' then off=0 /* " " " " "off". */ col@= 'a b c d e f g h i j k l m n o p q r s t u v w x y z' /*for the column id.*/ -cols=space(col@,0); upper cols /*letters to be used for the columns. */ -@.=off; !.=off /*set both arrays to "off" characters.*/ +cols=space(col@, 0); upper cols /*letters to be used for the columns. */ +@.=0; !.=0 /*set both arrays to "off" characters.*/ tries=0 /*number of player's attempts (so far).*/ do while show(0) < u /* [↓] turn "on" U number of bits.*/ - r=random(1,N); c=random(1,N) /*get a random row and column. */ - @.r.c=on ; !.r.c=on /*set (both) row and column to ON. */ + r=random(1, N); c=random(1, N) /*get a random row and column. */ + @.r.c=1 ; !.r.c=1 /*set (both) row and column to ON. */ end /*while*/ /* [↑] keep going 'til U bits set.*/ oz=z /*keep the original array string. */ call show 1, ' ◄───target' /*show target for user to attain. */ @@ -19,11 +17,11 @@ call show 1, ' ◄───target' /*show target for user call flip 'C',random(1,N) /* " " column " " */ end /*random···*/ /* [↑] just perform 1 or 2 times. */ -if z==oz then call flip 'R',random(1,N) /*ensure it's not target we're flipping*/ +if z==oz then call flip 'R', random(1, N) /*ensure it's not target we're flipping*/ do until z==oz /*prompt until they get it right. */ call prompt /*get a row or column number from C.L. */ - call flip left(?,1),substr(?,2) /*flip a user selected row or column. */ + call flip left(?, 1), substr(?, 2) /*flip a user selected row or column. */ call show 0 /*get image (Z) of the updated array. */ end /*until···*/ @@ -32,13 +30,13 @@ say '─────────Congrats! You did it in' tries "tries exit tries /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ halt: say 'program was halted!'; exit /*the REXX program was halted by user. */ -isInt: return datatype(arg(1),'W') /*returns 1 if arg is an integer.*/ -isLet: return datatype(arg(1),'M') /*returns 1 if arg is a letter. */ +isInt: return datatype(arg(1), 'W') /*returns 1 if arg is an integer.*/ +isLet: return datatype(arg(1), 'M') /*returns 1 if arg is a letter. */ terr: if ok then say '***error!***: illegal' arg(1); ok=0; return /*──────────────────────────────────────────────────────────────────────────────────────*/ flip: parse arg x,# /*X is R or C; #: is which one.*/ - do c=1 for N while x=='R'; if @.#.c==on then @.#.c=off; else @.#.c=on; end - do r=1 for N while x=='C'; if @.r.#==on then @.r.#=off; else @.r.#=on; end + do c=1 for N while x=='R'; @.#.c=\@.#.c; end /*c*/ + do r=1 for N while x=='C'; @.r.#=\@.r.#; end /*r*/ return /* [↑] the bits can be ON or OFF. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ prompt: if tries\==0 then say '─────────bit array after play: ' tries @@ -47,7 +45,7 @@ prompt: if tries\==0 then say '─────────bit array after play call show 1, ' ◄───your array' /*display the array to the terminal. */ do forever; ok=1; say; say !; pull ? _ . 1 all /*prompt & get ans*/ - if abbrev('QUIT',?,1) then do; say 'quitting···'; exit 0; end + if abbrev('QUIT', ?, 1) then do; say 'quitting···'; exit 0; end if ?=='' then do; call show 1," ◄───target",.; ok=0 call show 1," ◄───your array" end /* [↑] reshow targ*/ @@ -56,7 +54,7 @@ prompt: if tries\==0 then say '─────────bit array after play if isLet(?) then a=pos(?,cols) if isLet(?) & (a<1 | a>N) then call terr 'column: ' ? if isLet(?) & length(?)>1 then call terr 'column: ' ? - if isLet(?) then ?='C'pos(?,cols) + if isLet(?) then ?='C'pos(?, cols) if isInt(?) & (?<1 | ?>N) then call terr 'row: ' ? if isInt(?) then ?=?/1 /*normalize number*/ if isInt(?) then ?='R'? @@ -66,20 +64,19 @@ prompt: if tries\==0 then say '─────────bit array after play tries=tries+1 /*bump da counter.*/ return ? /*return response.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ -show: $=0; _=; z=; parse arg tell,tx,o /*$: # of ON bits.*/ +show: $=0; _=; parse arg tell,tx,o /*$≡num of ON bits*/ if tell then do; say /*are we telling? */ say ' ' subword(col@,1,N) " column letter" say 'row ╔'copies('═',N+N+1) /*prepend col hdrs*/ end /* [↑] grid hdrs.*/ - + z= /* [↓] build grid.*/ do r=1 for N /*show grid rows.*/ - do c=1 for N /*build grid cols.*/ - if o==. then do; z=z || !.r.c; _=_ !.r.c; $=$+(!.r.c==on); end - else do; z=z || @.r.c; _=_ @.r.c; $=$+(@.r.c==on); end + do c=1 for N; if o==. then do; z=z || !.r.c; _=_ !.r.c; $=$+!.r.c; end + else do; z=z || @.r.c; _=_ @.r.c; $=$+@.r.c; end end /*c*/ /*··· and sum ONs.*/ if tx\=='' then tar.r=_ tx /*build da target?*/ - if tell then say right(r,2) ' ║'_ tx; _= /*show the grid? */ + if tell then say right(r, 2) ' ║'_ tx; _= /*show the grid? */ end /*r*/ /*show a grid row.*/ if tell then say /*show blank line.*/ - return $ /*$: # of ON bits.*/ + return $ /*num of on bits. */ diff --git a/Task/Flow-control-structures/ALGOL-W/flow-control-structures.alg b/Task/Flow-control-structures/ALGOL-W/flow-control-structures.alg new file mode 100644 index 0000000000..7ed9a86fe4 --- /dev/null +++ b/Task/Flow-control-structures/ALGOL-W/flow-control-structures.alg @@ -0,0 +1,18 @@ +begin + integer i; + integer procedure getNumber ; + begin + integer n; + write( "n> " ); + read( i ); + if i< 0 then goto negativeNumber; + i + end getNumber ; + + i := getNumber; + write( "positive or zero" ); + go to endProgram; +negativeNumber: + writeon( "negative" ); +endProgram: +end. diff --git a/Task/Flow-control-structures/Gambas/flow-control-structures.gambas b/Task/Flow-control-structures/Gambas/flow-control-structures.gambas new file mode 100644 index 0000000000..fe8b3a44c0 --- /dev/null +++ b/Task/Flow-control-structures/Gambas/flow-control-structures.gambas @@ -0,0 +1,11 @@ +Public Sub Main() +Dim siCount As Short + +LOOPIT: + +Print siCount;; +Inc siCount +If siCount > 100 Then Quit +Goto LoopIt + +End diff --git a/Task/Flow-control-structures/Jq/flow-control-structures.jq b/Task/Flow-control-structures/Jq/flow-control-structures.jq new file mode 100644 index 0000000000..07e41302e6 --- /dev/null +++ b/Task/Flow-control-structures/Jq/flow-control-structures.jq @@ -0,0 +1,2 @@ +# Emit at most one item from the stream generated by g: +def first(g): label $out | g | ., break $out; diff --git a/Task/Flow-control-structures/Kotlin/flow-control-structures.kotlin b/Task/Flow-control-structures/Kotlin/flow-control-structures.kotlin new file mode 100644 index 0000000000..77d808c66e --- /dev/null +++ b/Task/Flow-control-structures/Kotlin/flow-control-structures.kotlin @@ -0,0 +1,14 @@ +// version 1.0.6 + +fun main(args: Array) { + for (i in 0 .. 2) { + for (j in 0 .. 2) { + if (i + j == 2) continue + if (i + j == 3) break + println(i + j) + } + } + println() + if (args.isNotEmpty()) throw IllegalArgumentException("No command line arguments should be supplied") + println("Goodbye!") // won't be executed +} diff --git a/Task/Flow-control-structures/Lua/flow-control-structures.lua b/Task/Flow-control-structures/Lua/flow-control-structures-1.lua similarity index 100% rename from Task/Flow-control-structures/Lua/flow-control-structures.lua rename to Task/Flow-control-structures/Lua/flow-control-structures-1.lua diff --git a/Task/Flow-control-structures/Lua/flow-control-structures-2.lua b/Task/Flow-control-structures/Lua/flow-control-structures-2.lua new file mode 100644 index 0000000000..6e5cba0831 --- /dev/null +++ b/Task/Flow-control-structures/Lua/flow-control-structures-2.lua @@ -0,0 +1,9 @@ +function func1 () + return func2() +end + +function func2 () + return func1() +end + +func1() diff --git a/Task/Flow-control-structures/Stata/flow-control-structures.stata b/Task/Flow-control-structures/Stata/flow-control-structures.stata new file mode 100644 index 0000000000..b27c00738b --- /dev/null +++ b/Task/Flow-control-structures/Stata/flow-control-structures.stata @@ -0,0 +1,16 @@ +mata +function pythagorean_triple(n) { + for (a=1; a<=n; a++) { + for (b=a; b<=n-a; b++) { + c=n-a-b + if (c>b & c*c==a*a+b*b) { + printf("%f %f %f\n",a,b,c) + goto END + } + } + } + END: +} + +pythagorean_triple(1980) +165 900 915 diff --git a/Task/Flow-control-structures/Zkl/flow-control-structures-1.zkl b/Task/Flow-control-structures/Zkl/flow-control-structures-1.zkl new file mode 100644 index 0000000000..b0be8ee6b9 --- /dev/null +++ b/Task/Flow-control-structures/Zkl/flow-control-structures-1.zkl @@ -0,0 +1,4 @@ +continue; continue(n); // continue nth nested loop +break; break(n); // break out of nth nested loop +try{ ... }catch(exception){ ... } [else{ ... }] +onExit(fcn); // run fcn when enclosing function exits diff --git a/Task/Flow-control-structures/Zkl/flow-control-structures-2.zkl b/Task/Flow-control-structures/Zkl/flow-control-structures-2.zkl new file mode 100644 index 0000000000..1d62fcfd71 --- /dev/null +++ b/Task/Flow-control-structures/Zkl/flow-control-structures-2.zkl @@ -0,0 +1,3 @@ +urlText.pump(String, + fcn(c){ if(c=="%")return(Void.Read,2); return(Void.Skip,c) }, + fcn(_,b,c){(b+c).toInt(16).toChar()}) diff --git a/Task/Flow-control-structures/Zkl/flow-control-structures-3.zkl b/Task/Flow-control-structures/Zkl/flow-control-structures-3.zkl new file mode 100644 index 0000000000..2a264dac0d --- /dev/null +++ b/Task/Flow-control-structures/Zkl/flow-control-structures-3.zkl @@ -0,0 +1,2 @@ +urlText:="http%3A%2F%2Ffoo.com%2Fbar"; +urlText.pump(...).println(); diff --git a/Task/Floyds-triangle/ALGOL-W/floyds-triangle.alg b/Task/Floyds-triangle/ALGOL-W/floyds-triangle.alg new file mode 100644 index 0000000000..d09d62b5f1 --- /dev/null +++ b/Task/Floyds-triangle/ALGOL-W/floyds-triangle.alg @@ -0,0 +1,41 @@ +begin + % prints a Floyd's Triangle with n lines % + procedure floydsTriangle ( integer value n ) ; + 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 highest number that will be printed % + % ( the sum of the integeregers 1, 2, ... n ) % + integer array widths( 1 :: n ); + integer maxNumber, number; + maxNumber := ( n * ( n + 1 ) ) div 2; + % determine the widths required to print the numbers of the final row % + number := maxNumber; + for col := n step -1 until 1 do begin + integer v, w; + w := 0; + v := number; + number := number - 1; + while v > 0 do begin + w := w + 1; + v := v div 10 + end while_v_gt_0 ; + widths( col ) := w + end for_col; + % print the triangle % + number := 0; + for row := 1 until n do begin + for col := 1 until row do begin + number := number + 1; + writeon( i_w := widths( col ), s_w := 0, " ", number ) + end for_col ; + write() + end for_row + end; % floyds triangle % + + floydsTriangle( 5 ); + write(); + floydsTriangle( 14 ) + +end. diff --git a/Task/Floyds-triangle/Ada/floyds-triangle.ada b/Task/Floyds-triangle/Ada/floyds-triangle.ada index 9e6b226408..ead449d8b1 100644 --- a/Task/Floyds-triangle/Ada/floyds-triangle.ada +++ b/Task/Floyds-triangle/Ada/floyds-triangle.ada @@ -1,23 +1,12 @@ with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line; procedure Floyd_Triangle is - - Rows: constant Positive := Integer'Value(Ada.Command_Line.Argument(1)); - Current: Positive := 1; - Width: array(1 .. Rows) of Positive; - + rows : constant Natural := Natural'Value(Ada.Command_Line.Argument(1)); begin - -- compute the width for the different columns - for I in Width'Range loop - Width(I) := Integer'Image(I + (Rows * (Rows-1))/2)'Length; - end loop; - - -- output the triangle - for Line in 1 .. Rows loop - for Column in 1 .. Line loop - Ada.Integer_Text_IO.Put(Current, Width => Width(Column)); - Current := Current + 1; - end loop; - Ada.Text_IO.New_Line; - end loop; + for r in 1..rows loop + for i in 1..r loop + Ada.Integer_Text_IO.put (r*(r-1)/2+i, Width=> Natural'Image(rows*(rows-1)/2+i)'Length); + end loop; + Ada.Text_IO.New_Line; + end loop; end Floyd_Triangle; diff --git a/Task/Floyds-triangle/AppleScript/floyds-triangle.applescript b/Task/Floyds-triangle/AppleScript/floyds-triangle.applescript new file mode 100644 index 0000000000..16bedbca48 --- /dev/null +++ b/Task/Floyds-triangle/AppleScript/floyds-triangle.applescript @@ -0,0 +1,276 @@ +-- FLOYDs TRIANGLE ----------------------------------------------------------- + +-- floyd :: Int -> [[Int]] +on floyd(n) + script floydRow + on |λ|(start, row) + {start + row + 1, enumFromTo(start, start + row)} + end |λ| + end script + + snd(mapAccumL(floydRow, 1, enumFromTo(0, n - 1))) +end floyd + +-- showFloyd :: [[Int]] -> String +on showFloyd(xss) + set ws to map(compose({my succ, my |length|, my show}), |last|(xss)) + + script aligned + on |λ|(xs) + script pad + on |λ|(w, x) + justifyRight(w, space, show(x)) + end |λ| + end script + + concat(zipWith(pad, ws, xs)) + end |λ| + end script + + unlines(map(aligned, xss)) +end showFloyd + + +-- TEST ---------------------------------------------------------------------- +on run + script test + on |λ|(n) + showFloyd(floyd(n)) & linefeed + end |λ| + end script + + unlines(map(test, {5, 14})) +end run + + +-- GENERIC FUNCTIONS --------------------------------------------------------- + +-- compose :: [(a -> a)] -> (a -> a) +on compose(fs) + script + on |λ|(x) + script + on |λ|(f, a) + mReturn(f)'s |λ|(a) + end |λ| + end script + + foldr(result, x, fs) + end |λ| + end script +end compose + +-- concat :: [[a]] -> [a] | [String] -> String +on concat(xs) + if length of xs > 0 and class of (item 1 of xs) is string then + set acc to "" + else + set acc to {} + end if + repeat with i from 1 to length of xs + set acc to acc & item i of xs + end repeat + acc +end concat + +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if n < m then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo + +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl + +-- foldr :: (b -> a -> a) -> a -> [b] -> a +on foldr(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from lng to 1 by -1 + set v to |λ|(item i of xs, v, i, xs) + end repeat + return v + end tell +end foldr + +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + +-- justifyRight :: Int -> Char -> Text -> Text +on justifyRight(n, cFiller, strText) + if n > length of strText then + text -n thru -1 of ((replicate(n, cFiller) as text) & strText) + else + strText + end if +end justifyRight + +-- last :: [a] -> a +on |last|(xs) + if length of xs > 0 then + item -1 of xs + else + missing value + end if +end |last| + +-- length :: [a] -> Int +on |length|(xs) + length of xs +end |length| + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- 'The mapAccumL function behaves like a combination of map and foldl; +-- it applies a function to each element of a list, passing an +-- accumulating parameter from left to right, and returning a final +-- value of this accumulator together with the new list.' (see Hoogle) + +-- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) +on mapAccumL(f, acc, xs) + script + on |λ|(a, x) + tell mReturn(f) to set pair to |λ|(item 1 of a, x) + [item 1 of pair, (item 2 of a) & {item 2 of pair}] + end |λ| + end script + + foldl(result, [acc, []], xs) +end mapAccumL + +-- min :: Ord a => a -> a -> a +on min(x, y) + if y < x then + y + else + x + end if +end min + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- Egyptian multiplication - progressively doubling a list, appending +-- stages of doubling to an accumulator where needed for binary +-- assembly of a target length + +-- replicate :: Int -> a -> [a] +on replicate(n, a) + set out to {} + if n < 1 then return out + set dbl to {a} + + repeat while (n > 1) + if (n mod 2) > 0 then set out to out & dbl + set n to (n div 2) + set dbl to (dbl & dbl) + end repeat + return out & dbl +end replicate + +-- snd :: (a, b) -> b +on snd(xs) + if class of xs is list and length of xs > 1 then + item 2 of xs + else + missing value + end if +end snd + +-- show :: a -> String +on show(e) + set c to class of e + if c = list then + script serialized + on |λ|(v) + show(v) + end |λ| + end script + + "{" & intercalate(", ", map(serialized, e)) & "}" + else if c = record then + script showField + on |λ|(kv) + set {k, v} to kv + k & ":" & show(v) + end |λ| + end script + + "{" & intercalate(", ", ¬ + map(showField, zip(allKeys(e), allValues(e)))) & "}" + else if c = date then + ("date \"" & e as text) & "\"" + else if c = text then + "\"" & e & "\"" + else + try + e as text + on error + ("«" & c as text) & "»" + end try + end if +end show + +-- succ :: Int -> Int +on succ(x) + x + 1 +end succ + +-- unlines :: [String] -> String +on unlines(xs) + intercalate(linefeed, xs) +end unlines + +-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] +on zipWith(f, xs, ys) + set lng to min(length of xs, length of ys) + set lst to {} + tell mReturn(f) + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, item i of ys) + end repeat + return lst + end tell +end zipWith diff --git a/Task/Floyds-triangle/Batch-File/floyds-triangle.bat b/Task/Floyds-triangle/Batch-File/floyds-triangle.bat new file mode 100644 index 0000000000..33d5494b80 --- /dev/null +++ b/Task/Floyds-triangle/Batch-File/floyds-triangle.bat @@ -0,0 +1,52 @@ +@echo off + +call:floyd 5 +echo. +call:floyd 14 +pause>nul +exit /b + +:floyd +setlocal enabledelayedexpansion +set iterations=%1 +set startn=1 +set endn=1 + +for /l %%i in (1,1,%iterations%) do ( + for /l %%j in (!startn!,1,!endn!) do ( + set lastnum=%%j + set /a startn=%%j+1 + ) + set /a endn=!startn!+%%i +) + +call:getlength %startn% +set digits=%errorlevel% + +set startn=1 +set endn=1 + +for /l %%i in (1,1,%iterations%) do ( + set "line=" + for /l %%j in (!startn!,1,!endn!) do ( + set "space=" + call:getlength %%j + set /a sparespace=%digits%-!errorlevel! + for /l %%k in (0,1,!sparespace!) do set "space=!space! " + + set line=!line!!space!%%j + set /a startn=%%j+1 + ) + echo !line! + set /a endn=!startn!+%%i +) +exit /b + +:getlength +setlocal enabledelayedexpansion +set offset=0 +set string=%1 +:floydloop +if "!string:~%offset%,1!"=="" endlocal && exit /b %offset% +set /a offset+=1 +goto floydloop diff --git a/Task/Floyds-triangle/Clojure/floyds-triangle.clj b/Task/Floyds-triangle/Clojure/floyds-triangle.clj new file mode 100644 index 0000000000..6127450bb9 --- /dev/null +++ b/Task/Floyds-triangle/Clojure/floyds-triangle.clj @@ -0,0 +1,17 @@ +(defn TriangleList [n] + (let [l (map inc (range))] + (loop [l l x 1 nl []] + (if (= n (count nl)) + nl + (recur (drop x l) (inc x) (conj nl (take x l))))))) + +(defn TrianglePrint [n] + (let [t (TriangleList n) + m (count (str (last (last t)))) + f (map #(map str %) t) + l (map #(map (fn [x] (if (> m (count x)) + (str (apply str (take (- m (count x)) + (repeat " "))) x) + x)) %) f) + e (map #(map (fn [x] (str " " x)) %) l)] + (map #(println (apply str %)) e))) diff --git a/Task/Floyds-triangle/Gambas/floyds-triangle.gambas b/Task/Floyds-triangle/Gambas/floyds-triangle.gambas new file mode 100644 index 0000000000..43ea619080 --- /dev/null +++ b/Task/Floyds-triangle/Gambas/floyds-triangle.gambas @@ -0,0 +1,25 @@ +Public Sub Main() +Dim siCount, siNo, siCounter As Short +Dim siLine As Short = 1 +Dim siInput As Short[] = [5, 14] + +For siCount = 0 To siInput.Max + Print "Floyd's triangle to " & siInput[siCount] & " lines" + Do + Inc siNo + Inc siCounter + Print Format(siNo, "####"); + If siLine = siCounter Then + Print + Inc siLine + siCounter = 0 + End If + If siLine - 1 = siInput[siCount] Then Break + Loop + siLine = 1 + siCounter = 0 + siNo = 0 + Print +Next + +End diff --git a/Task/Floyds-triangle/Haskell/floyds-triangle-1.hs b/Task/Floyds-triangle/Haskell/floyds-triangle-1.hs index 5d1c9b9b32..b644f9f5c5 100644 --- a/Task/Floyds-triangle/Haskell/floyds-triangle-1.hs +++ b/Task/Floyds-triangle/Haskell/floyds-triangle-1.hs @@ -1,12 +1,17 @@ -import Data.List -import Control.Monad -import Control.Arrow +import Control.Monad (liftM2) + +floydTriangle = + liftM2 + (zipWith (liftM2 (.) enumFromTo ((pred .) . (+)))) + (scanl (+) 1) + id + [1 ..] alignR :: Int -> Integer -> String -alignR n = (\s -> replicate (n - length s) ' ' ++ s). show +alignR n = (\s -> replicate (n - length s) ' ' ++ s) . show -floydTriangle = liftM2 (zipWith (liftM2 (.) enumFromTo ((pred.). (+)))) (scanl (+) 1) id [1..] - -formatFT n = mapM_ (putStrLn. unwords. zipWith alignR ws) t where - t = take n floydTriangle - ws = map (length. show) $ last t +formatFT :: Int -> IO () +formatFT n = mapM_ (putStrLn . unwords . zipWith alignR ws) t + where + t = take n floydTriangle + ws = map (length . show) $ last t diff --git a/Task/Floyds-triangle/Haskell/floyds-triangle-3.hs b/Task/Floyds-triangle/Haskell/floyds-triangle-3.hs new file mode 100644 index 0000000000..402668abe2 --- /dev/null +++ b/Task/Floyds-triangle/Haskell/floyds-triangle-3.hs @@ -0,0 +1,21 @@ +import Data.List (mapAccumL) + +floyd :: Int -> [[Int]] +floyd n = + snd $ + mapAccumL + (\start row -> (start + succ row, [start .. start + row])) + 1 + [0 .. pred n] + +-- TEST ----------------------------------------------------------------------- +showFloyd :: [[Int]] -> String +showFloyd xs = + let padRight n = length >>= (<$> mappend (replicate n ' ')) . drop + in unlines $ + (concat . + zipWith ((. show) . padRight) ((succ . length . show) <$> last xs)) <$> + xs + +main :: IO () +main = mapM_ putStrLn $ (showFloyd . floyd) <$> [5, 14] diff --git a/Task/Floyds-triangle/JavaScript/floyds-triangle-1.js b/Task/Floyds-triangle/JavaScript/floyds-triangle-1.js index 1795b4fd03..23dd827f26 100644 --- a/Task/Floyds-triangle/JavaScript/floyds-triangle-1.js +++ b/Task/Floyds-triangle/JavaScript/floyds-triangle-1.js @@ -1,78 +1,121 @@ -// Floyd triangles of 5 and 14 rows -// right-aligned monospaced columns (nMargin allows for extra spacing) -// () --> s -function main() { - // minimum space between numbers - adjust for visual preference - var nMargin = 1; +(function () { + 'use strict'; - // Formatted strings for Floyd's triangles of 5 and 14 rows - return (function (lstN) { - return lstN.map(function (nFloydRows) { - var lstRows = floydIntegerLists(nFloydRows), - iLast = nFloydRows - 1; + // FLOYD's TRIANGLE ------------------------------------------------------- - return colsSpacedRight( - lstRows, - // Minimum space required per number cell - // nMargin more than the width of the final number - lstRows[iLast][iLast].toString().length + nMargin - ) - }).join('\n\n'); - })([5, 14]); -} + // floyd :: Int -> [[Int]] + function floyd(n) { + return snd(mapAccumL(function (start, row) { + return [start + row + 1, enumFromTo(start, start + row)]; + }, 1, enumFromTo(0, n - 1))); + }; -// n Floyd's triangle rows -// n --> [[n]] -function floydIntegerLists(nRows) { + // showFloyd :: [[Int]] -> String + function showFloyd(xss) { + var ws = map(compose([succ, length, show]), last(xss)); + return unlines(map(function (xs) { + return concat(zipWith(function (w, x) { + return justifyRight(w, ' ', show(x)); + }, ws, xs)); + }, xss)); + }; - // Full integer list folded into list of rows - // [n] --> [[n]] - return (function triangleNumbers(lstInt, startWidth) { - var n = startWidth || 1; - return n > lstInt.length ? [] : [lstInt.slice(0, n)].concat( - triangleNumbers(lstInt.slice(n), n + 1) - ) - })( - range( - 1, - Math.floor( - (nRows * nRows) / 2 - ) + Math.ceil( - nRows / 2 - ) - ) - ); -} + // GENERIC FUNCTIONS ------------------------------------------------------ -// list of list of numbers --> lines of fixed right-aligned col width -// [[n]] --> s -function colsSpacedRight(lstLines, nColWidth) { - return lstLines.reduce( - function (s, line) { - return s + line.map(function (n) { - return rightAligned(n, nColWidth) - }).join('') + '\n'; - }, '' - ) -} + // compose :: [(a -> a)] -> (a -> a) + function compose(fs) { + return function (x) { + return fs.reduceRight(function (a, f) { + return f(a); + }, x); + }; + }; -// range(1, 20) --> [1..20] -function range(m, n) { - return Array.apply(null, Array(n - m + 1)).map( - function (x, i) { + // concat :: [[a]] -> [a] | [String] -> String + function concat(xs) { + if (xs.length > 0) { + var unit = typeof xs[0] === 'string' ? '' : []; + return unit.concat.apply(unit, xs); + } else return []; + }; + + // enumFromTo :: Int -> Int -> [Int] + function enumFromTo(m, n) { + return Array.from({ + length: Math.floor(n - m) + 1 + }, function (_, i) { return m + i; - } - ); -} + }); + }; -// Integer as right-padded string of given width -// n --> n --> s -function rightAligned(n, width) { - var strN = n.toString(); - return Array(width - strN.length + 1).join(' ') + strN; -} + // justifyRight :: Int -> Char -> Text -> Text + function justifyRight(n, cFiller, strText) { + return n > strText.length ? (cFiller.repeat(n) + strText) + .slice(-n) : strText; + }; -console.log( // if the context is a browser - main() -); + // last :: [a] -> a + function last(xs) { + return xs.length ? xs.slice(-1)[0] : undefined; + }; + + // length :: [a] -> Int + function length(xs) { + return xs.length; + }; + + // map :: (a -> b) -> [a] -> [b] + function map(f, xs) { + return xs.map(f); + }; + + // 'The mapAccumL function behaves like a combination of map and foldl; + // it applies a function to each element of a list, passing an accumulating + // parameter from left to right, and returning a final value of this + // accumulator together with the new list.' (See hoogle ) + + // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) + function mapAccumL(f, acc, xs) { + return xs.reduce(function (a, x) { + var pair = f(a[0], x); + + return [pair[0], a[1].concat([pair[1]])]; + }, [acc, []]); + }; + + // show :: + // (a -> String) f, Num n => + // a -> maybe f -> maybe n -> String + var show = JSON.stringify; + + // snd :: (a, b) -> b + function snd(tpl) { + return Array.isArray(tpl) ? tpl[1] : undefined; + }; + + // succ :: Int -> Int + function succ(x) { + return x + 1; + }; + + // unlines :: [String] -> String + function unlines(xs) { + return xs.join('\n'); + }; + + // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] + function zipWith(f, xs, ys) { + var ny = ys.length; + return (xs.length <= ny ? xs : xs.slice(0, ny)) + .map(function (x, i) { + return f(x, ys[i]); + }); + }; + + // TEST ( n=5 and n=14 rows ) --------------------------------------------- + + return unlines(map(function (n) { + return showFloyd(floyd(n)) + '\n'; + }, [5, 14])); +})(); diff --git a/Task/Floyds-triangle/JavaScript/floyds-triangle-2.js b/Task/Floyds-triangle/JavaScript/floyds-triangle-2.js index 1f1a207190..7e4a4567d3 100644 --- a/Task/Floyds-triangle/JavaScript/floyds-triangle-2.js +++ b/Task/Floyds-triangle/JavaScript/floyds-triangle-2.js @@ -1,36 +1,97 @@ -#!/usr/bin/env js +(() => { + 'use strict'; -function main() { - print('Floyd 5:'); - floyd(5); - print('\nFloyd 14:'); - floyd(14); -} + // FLOYD's TRIANGLE ------------------------------------------------------- + + // floyd :: Int -> [[Int]] + const floyd = n => snd(mapAccumL( + (start, row) => [start + row + 1, enumFromTo(start, start + row)], + 1, enumFromTo(0, n - 1) + )); + + // showFloyd :: [[Int]] -> String + const showFloyd = xss => { + const ws = map(compose([succ, length, show]), last(xss)); + return unlines( + map(xs => concat(zipWith( + (w, x) => justifyRight(w, ' ', show(x)), ws, xs + )), + xss + ) + ); + }; + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // compose :: [(a -> a)] -> (a -> a) + const compose = fs => x => fs.reduceRight((a, f) => f(a), x); + + // concat :: [[a]] -> [a] | [String] -> String + const concat = xs => { + if (xs.length > 0) { + const unit = typeof xs[0] === 'string' ? '' : []; + return unit.concat.apply(unit, xs); + } else return []; + }; + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // justifyRight :: Int -> Char -> Text -> Text + const justifyRight = (n, cFiller, strText) => + n > strText.length ? ( + (cFiller.repeat(n) + strText) + .slice(-n) + ) : strText; + + // last :: [a] -> a + const last = xs => xs.length ? xs.slice(-1)[0] : undefined; + + // length :: [a] -> Int + const length = xs => xs.length; + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f) + + // 'The mapAccumL function behaves like a combination of map and foldl; + // it applies a function to each element of a list, passing an accumulating + // parameter from left to right, and returning a final value of this + // accumulator together with the new list.' (See hoogle ) + + // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) + const mapAccumL = (f, acc, xs) => + xs.reduce((a, x) => { + const pair = f(a[0], x); + + return [pair[0], a[1].concat([pair[1]])]; + }, [acc, []]); + + // show :: + // (a -> String) f, Num n => + // a -> maybe f -> maybe n -> String + const show = JSON.stringify; + + // snd :: (a, b) -> b + const snd = tpl => Array.isArray(tpl) ? tpl[1] : undefined; + + // succ :: Int -> Int + const succ = x => x + 1 + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); -function padLeft(s, w) { - for (s = String(s); s.length < w; s = ' ' + s); - return s; -} + // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] + const zipWith = (f, xs, ys) => { + const ny = ys.length; + return (xs.length <= ny ? xs : xs.slice(0, ny)) + .map((x, i) => f(x, ys[i])); + }; + // TEST ( n=5 and n=14 rows ) --------------------------------------------- -function floyd(nRows) { - var lowerLeft = nRows * (nRows - 1) / 2 + 1; - var lowerRight = nRows * (nRows + 1) / 2; - - var colWidths = []; - for (var col = lowerLeft; col <= lowerRight; col++) { - colWidths.push(String(col).length); - } - - var num = 1; - for (var row = 0; row < nRows; row++) { - var line = []; - for (var col = 0; col <= row; col++, num++) { - line.push(padLeft(num, colWidths[col])); - } - print(line.join(' ')); - } -} - -main(); + return unlines(map(n => showFloyd(floyd(n)) + '\n', [5, 14])) +})(); diff --git a/Task/Floyds-triangle/JavaScript/floyds-triangle-3.js b/Task/Floyds-triangle/JavaScript/floyds-triangle-3.js new file mode 100644 index 0000000000..1f1a207190 --- /dev/null +++ b/Task/Floyds-triangle/JavaScript/floyds-triangle-3.js @@ -0,0 +1,36 @@ +#!/usr/bin/env js + +function main() { + print('Floyd 5:'); + floyd(5); + print('\nFloyd 14:'); + floyd(14); +} + + +function padLeft(s, w) { + for (s = String(s); s.length < w; s = ' ' + s); + return s; +} + + +function floyd(nRows) { + var lowerLeft = nRows * (nRows - 1) / 2 + 1; + var lowerRight = nRows * (nRows + 1) / 2; + + var colWidths = []; + for (var col = lowerLeft; col <= lowerRight; col++) { + colWidths.push(String(col).length); + } + + var num = 1; + for (var row = 0; row < nRows; row++) { + var line = []; + for (var col = 0; col <= row; col++, num++) { + line.push(padLeft(num, colWidths[col])); + } + print(line.join(' ')); + } +} + +main(); diff --git a/Task/Floyds-triangle/jq/floyds-triangle-1.jq b/Task/Floyds-triangle/Jq/floyds-triangle-1.jq similarity index 100% rename from Task/Floyds-triangle/jq/floyds-triangle-1.jq rename to Task/Floyds-triangle/Jq/floyds-triangle-1.jq diff --git a/Task/Floyds-triangle/jq/floyds-triangle-2.jq b/Task/Floyds-triangle/Jq/floyds-triangle-2.jq similarity index 100% rename from Task/Floyds-triangle/jq/floyds-triangle-2.jq rename to Task/Floyds-triangle/Jq/floyds-triangle-2.jq diff --git a/Task/Floyds-triangle/jq/floyds-triangle-3.jq b/Task/Floyds-triangle/Jq/floyds-triangle-3.jq similarity index 100% rename from Task/Floyds-triangle/jq/floyds-triangle-3.jq rename to Task/Floyds-triangle/Jq/floyds-triangle-3.jq diff --git a/Task/Floyds-triangle/MATLAB/floyds-triangle.m b/Task/Floyds-triangle/MATLAB/floyds-triangle.m index f2a086ddbb..ee81d4f21e 100644 --- a/Task/Floyds-triangle/MATLAB/floyds-triangle.m +++ b/Task/Floyds-triangle/MATLAB/floyds-triangle.m @@ -1,7 +1,6 @@ function floyds_triangle(n) - -width = 1+floor(log10(nr*(nr+1)/2)); -for k=1:n, - fprintf(stdout,' %*i',[width(ones(1,k));k*(k-1)/2+1:k*(k+1)/2]); - fprintf(stdout,'\n'); -end; + s = 1; + for k = 1 : n + disp(s : s + k - 1) + s = s + k; + end diff --git a/Task/Floyds-triangle/Phix/floyds-triangle.phix b/Task/Floyds-triangle/Phix/floyds-triangle.phix new file mode 100644 index 0000000000..4aa31b5db9 --- /dev/null +++ b/Task/Floyds-triangle/Phix/floyds-triangle.phix @@ -0,0 +1,17 @@ +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) diff --git a/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx b/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx index 1809dbe8f6..ec3513edff 100644 --- a/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx +++ b/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx @@ -1,12 +1,11 @@ /*REXX program constructs & displays Floyd's triangle for any number of specified rows.*/ -parse arg rows .; if rows=='' then rows=5 /*Not specified? Then use the default.*/ -mx=rows * (rows+1) % 2 /*calculate maximum value of any value.*/ -say 'displaying a ' rows " row Floyd's triangle:" /*show header for the triangle.*/ +parse arg N .; if N=='' | N=="," then N=5 /*Not specified? Then use the default.*/ +mx=N * (N+1) % 2 - N /*calculate maximum value of any value.*/ +say 'displaying a ' N " row Floyd's triangle:" /*show the header for Floyd's triangle.*/ say -#=1; do r=1 for rows; i=0; _= /*construct Floyd's triangle row by row*/ - do #=# for r; i=i+1 /*start to construct a row of triangle.*/ - _=_ right(#, length(mx-rows+i)) /*build a row of the Floyd's triangle. */ +#=1; do r=1 for N; i=0; _= /*construct Floyd's triangle row by row*/ + do #=# for r; i=i+1 /*start to construct a row of triangle.*/ + _=_ right(#, length( mx+i ) ) /*build a row of the Floyd's triangle. */ end /*#*/ - say substr(_,2) /*remove 1st leading blank in the line,*/ - end /*r*/ /* [↑] introduced by first abutment. */ - /*stick a fork in it, we're all done. */ + say substr(_, 2) /*remove 1st leading blank in the line.*/ + end /*r*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Floyds-triangle/REXX/floyds-triangle-3.rexx b/Task/Floyds-triangle/REXX/floyds-triangle-3.rexx index 848d5b36bf..7f2db79961 100644 --- a/Task/Floyds-triangle/REXX/floyds-triangle-3.rexx +++ b/Task/Floyds-triangle/REXX/floyds-triangle-3.rexx @@ -1,12 +1,11 @@ /*REXX program constructs & displays Floyd's triangle for any number of rows in base 16.*/ -parse arg rows .; if rows=='' then rows=6 /*Not specified? Then use the default.*/ -mx=rows * (rows+1) % 2 /*calculate maximum value of any value.*/ -say 'displaying a ' rows " row Floyd's triangle in base 16:"; say /*show triangle hdr*/ -#=1 - do r=1 for rows; i=0; _= /*construct Floyd's triangle row by row*/ - do #=# for r; i=i+1 /*start to construct a row of triangle.*/ - _=_ right(d2x(#),length(d2x(mx-rows+i))) /*build a row of the Floyd's triangle. */ - end /*#*/ - say substr(_,2) /*remove 1st leading blank in the line,*/ - end /*r*/ /* [↑] introduced by first abutment. */ - /*stick a fork in it, we're all done. */ +parse arg N .; if N=='' | N=="," then N=6 /*Not specified? Then use the default.*/ +mx=N * (N+1) % 2 - N /*calculate maximum value of any value.*/ +say 'displaying a ' N " row Floyd's triangle in base 16:" /*show triangle header.*/ +say +#=1; do r=1 for N; i=0; _= /*construct Floyd's triangle row by row*/ + do #=# for r; i=i+1 /*start to construct a row of triangle.*/ + _=_ right( d2x(#), length( d2x(mx+i))) /*build a row of the Floyd's triangle. */ + end /*#*/ + say substr(_, 2) /*remove 1st leading blank in the line.*/ + end /*r*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Floyds-triangle/REXX/floyds-triangle-4.rexx b/Task/Floyds-triangle/REXX/floyds-triangle-4.rexx index f975650beb..4419bfb799 100644 --- a/Task/Floyds-triangle/REXX/floyds-triangle-4.rexx +++ b/Task/Floyds-triangle/REXX/floyds-triangle-4.rexx @@ -1,50 +1,50 @@ /*REXX program constructs/shows Floyd's triangle for any number of rows in any base ≤90.*/ -parse arg rows radx . /*obtain optional arguments from the CL*/ -if rows=='' | rows=="," then rows= 5 /*Not specified? Then use the default.*/ +parse arg N radx . /*obtain optional arguments from the CL*/ +if N=='' | N=="," then N= 5 /*Not specified? Then use the default.*/ if radx=='' | radx=="," then radx=10 /* " " " " " " */ -mx=rows * (rows+1) % 2 /*calculate maximum value of any value.*/ -say 'displaying a ' rows " row Floyd's triangle in base" radx':'; say /*display hdr*/ -#=1 - do r=1 for rows; i=0; _= /*construct Floyd's triangle row by row*/ +mx=N * (N+1) % 2 - N /*calculate maximum value of any value.*/ +say 'displaying a ' N " row Floyd's triangle in base" radx':' /*display the header.*/ +say +#=1; do r=1 for N; i=0; _= /*construct Floyd's triangle row by row*/ do #=# for r; i=i+1 /*start to construct a row of triangle.*/ - _=_ right(base(#, radx), length(base(mx-rows+i, radx))) /*build triangle row*/ + _=_ right(base(#, radx), length( base(mx+i, radx) ) ) /*build triangle row.*/ end /*#*/ - say substr(_,2) /*remove 1st leading blank in the line,*/ + say substr(_, 2) /*remove 1st leading blank in the line,*/ end /*r*/ /* [↑] introduced by first abutment. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ base: procedure; parse arg x 1 ox,toB,inB /*obtain number, toBase, inBase. */ - @abc='abcdefghijklmnopqrstuvwxyz' /*lowercase Latin alphabet. */ - @abcU=@abc; upper @abcU /*go whole hog and extend 'em. */ - @@@='0123456789'@abc || @abcU /*prefix 'em with numeric digits.*/ + @abc= 'abcdefghijklmnopqrstuvwxyz' /*lowercase Latin alphabet. */ + @abcU=@abc; upper @abcU /*go whole hog and extend 'em. */ + @@@= '0123456789'@abc || @abcU /*prefix 'em with numeric digits.*/ @@@=@@@'<>[]{}()?~!@#$%^&*_=|\/;:¢¬≈' /*add some special chars as well.*/ - /*handles up to base 90, all chars must be viewable.*/ - numeric digits 1000 /*what the hey, support gihugeics*/ + /* [↑] handles up to base 90, all chars must be viewable.*/ + numeric digits 3000 /*what the hey, support gihugeics*/ mxB=length(@@@) /*max base (radix) supported here*/ if toB=='' | toB=="," then toB=10 /*if skipped, assume default (10)*/ if inB=='' | inB=="," then inB=10 /* " " " " " */ if inB<2 | inb>mxB then call erb 'inBase',inB /*invalid/illegal arg: inBase. */ if toB<2 | tob>mxB then call erb 'toBase',toB /* " " " toBase. */ if x=='' then call erm /* " " " number. */ - sigX=left(x,1) - if pos(sigX,'-+')\==0 then x=substr(x,2) /*X number has a leading sign? */ - else sigX= /* ··· no leading sign.*/ - #=0; do j=1 for length(x) /*convert X, base inB ──► base 10*/ - _=substr(x, j, 1) /*pick off a numeral from X. */ + sigX=left(x, 1) /*obtain a possible leading sign.*/ + if pos(sigX, '-+')\==0 then x=substr(x, 2) /*X number has a leading sign? */ + else sigX= /* ··· no leading sign.*/ + #=0 + do j=1 for length(x); _=substr(x, j, 1) /*convert X, base inB ──► base 10*/ v=pos(_, @@@) /*get the value of this "digit". */ if v==0 | v>inB then call erd x,j,inB /*is this an illegal "numeral" ? */ - #=#*inB+v-1 /*construct new num, dig by dig. */ + #=# * inB + v - 1 /*construct new num, dig by dig. */ end /*j*/ y= do while # >= toB /*convert #, base 10 ──► base toB*/ - y=substr(@@@, (#//toB)+1, 1)y /*construct the number for output*/ - #=#%toB /* ··· and whittle # down also.*/ + y=substr(@@@, (# // toB) + 1, 1)y /*construct the number for output*/ + #=# % toB /* ··· and whittle # down also.*/ end /*while*/ y=sigX || substr(@@@, #+1, 1)y /*prepend the sign if it existed.*/ return y /*return the number in base toB.*/ -/*───────────────────────────────────────────────────────────────────────────────────────*/ -erb: call ser 'illegal' arg(2) "base:" arg(1) "must be in range: 2──►" mxB -erd: call ser 'illegal "digit" in' x":" _ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +erb: call ser 'illegal' arg(2) "base: " arg(1) "must be in range: 2──► " mxB +erd: call ser 'illegal "digit" in' x":" _ erm: call ser 'no argument specified.' -ser: say; say '*** error! ***'; say arg(1); say; exit 13 +ser: say; say '***error***'; say arg(1); say; exit 13 diff --git a/Task/Floyds-triangle/SPL/floyds-triangle.spl b/Task/Floyds-triangle/SPL/floyds-triangle.spl new file mode 100644 index 0000000000..23a38720fb --- /dev/null +++ b/Task/Floyds-triangle/SPL/floyds-triangle.spl @@ -0,0 +1,15 @@ +floyd(5) +floyd(14) + +floyd(n)= + k = 0 + > r, 1..n + s = "" + > j, 1..r + k += 1 + f = ">"+#.upper(#.log10((n-1)*n/2+j+1)+1)+">" + s += #.str(k,f) + < + #.output(s) + < +. diff --git a/Task/Floyds-triangle/Sidef/floyds-triangle.sidef b/Task/Floyds-triangle/Sidef/floyds-triangle.sidef index d6c984498b..de67338125 100644 --- a/Task/Floyds-triangle/Sidef/floyds-triangle.sidef +++ b/Task/Floyds-triangle/Sidef/floyds-triangle.sidef @@ -1,10 +1,10 @@ func floyd(rows, n=1) { - var max = Math.range_sum(1, rows); - var widths = (max-rows .. max-1 -> map{(.+n).to_s.len}); + var max = Math.range_sum(1, rows) + var widths = (max-rows .. max-1 -> map{.+n->to_s.len}) { |r| - say %'#{1..r -> map{|i| "%#{widths[i-1]}d" % n++}.join(" ")}'; - } * rows; + say %'#{1..r -> map{|i| "%#{widths[i-1]}d" % n++}.join(" ")}' + } << 1..rows } -floyd(5); # or: floyd(5, 88); -floyd(14); # or: floyd(14, 900); +floyd(5) # or: floyd(5, 88) +floyd(14) # or: floyd(14, 900) diff --git a/Task/Floyds-triangle/VBA/floyds-triangle-1.vba b/Task/Floyds-triangle/VBA/floyds-triangle-1.vba new file mode 100644 index 0000000000..3cf5b118cf --- /dev/null +++ b/Task/Floyds-triangle/VBA/floyds-triangle-1.vba @@ -0,0 +1,24 @@ +Option Explicit +Dim o As String +Sub floyd(L As Integer) + Dim r, c, m, n As Integer + n = L * (L - 1) / 2 + m = 1 + For r = 1 To L + o = o & vbCrLf + For c = 1 To r + o = o & Space(Len(CStr(n + c)) - Len(CStr(m))) & m & " " + m = m + 1 + Next + Next +End Sub +Sub triangle() + o = "5 lines" + Call floyd(5) + o = o & vbCrLf & "14 lines" + Call floyd(14) + With Selection + .Font.Name = "Courier New" + .TypeText Text:=o + End With +End Sub diff --git a/Task/Floyds-triangle/VBA/floyds-triangle-2.vba b/Task/Floyds-triangle/VBA/floyds-triangle-2.vba new file mode 100644 index 0000000000..eff4fb1f7e --- /dev/null +++ b/Task/Floyds-triangle/VBA/floyds-triangle-2.vba @@ -0,0 +1,22 @@ +5 lines + 1 + 2 3 + 4 5 6 + 7 8 9 10 +11 12 13 14 15 + +14 lines + 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 101 102 103 104 105 diff --git a/Task/Floyds-triangle/Zkl/floyds-triangle.zkl b/Task/Floyds-triangle/Zkl/floyds-triangle.zkl new file mode 100644 index 0000000000..6501af685a --- /dev/null +++ b/Task/Floyds-triangle/Zkl/floyds-triangle.zkl @@ -0,0 +1,11 @@ +fcn lcNum(row){(row*(row+1)/2+1)} // lazy caterer's sequence +fcn floydsTriangle(rows){ + fmt:=[lcNum(rows-1)..lcNum(rows)-1].pump(String,fcn(n){ + String("%",n.toString().len(),"d ")}); // eg "%2d %2d %3d %3d" + foreach row in (rows){ + ns:=[lcNum(row)..lcNum(row+1)-1].walk(); // eg L(4.5,6) + fmt[0,ns.len()*4].fmt(ns.xplode()).println(); // eg "%2d %2d %2d ".fmt(4,5,6) + } +} +floydsTriangle(5); println(); +floydsTriangle(14); diff --git a/Task/Forest-fire/BASIC/forest-fire-10.basic b/Task/Forest-fire/BASIC/forest-fire-10.basic new file mode 100644 index 0000000000..a78a164bdf --- /dev/null +++ b/Task/Forest-fire/BASIC/forest-fire-10.basic @@ -0,0 +1,56 @@ + 10 PAPER 6: CLS + 20 DIM n$(20,30) + 30 LET init=.5 + 40 LET f=.02 + 50 LET p=.05 + 60 PAPER 0 + 70 FOR i=0 TO 31 + 80 PRINT AT 0,i;" " + 90 PRINT AT 21,i;" " +100 NEXT i +110 FOR i=0 TO 21 +120 PRINT AT i,0;" " +130 PRINT AT i,31;" " +140 NEXT i +150 INK 7 +160 PRINT AT 0,1;"FOREST FIRE for Rosetta Code" +170 LET generation=0 +180 PRINT AT 21,1;"Generation 0" +190 LET trees=0 +200 PRINT AT 21,22;"Cover" +210 FOR i=1 TO 20 +220 FOR j=1 TO 30 +230 IF RND RND(1) THEN - new&(x%,y%) = 1 - GCOL 2 - PLOT 4*x%,4*y% - ENDIF - WHEN 1: - IF f > RND(1) OR old&(x%-1,y%)=2 OR old&(x%+1,y%)=2 OR \ - \ old&(x%-1,y%-1)=2 OR old&(x%,y%-1)=2 OR old&(x%+1,y%-1)=2 OR \ - \ old&(x%-1,y%+1)=2 OR old&(x%,y%+1)=2 OR old&(x%+1,y%+1)=2 THEN - new&(x%,y%) = 2 - GCOL 1 - PLOT 4*x%,4*y% - ENDIF - WHEN 2: - new&(x%,y%) = 0 - GCOL 15 - PLOT 4*x%,4*y% - ENDCASE - NEXT - NEXT x% - old&() = new&() - UNTIL FALSE diff --git a/Task/Forest-fire/Batch-File/forest-fire.bat b/Task/Forest-fire/Batch-File/forest-fire.bat new file mode 100644 index 0000000000..0571607620 --- /dev/null +++ b/Task/Forest-fire/Batch-File/forest-fire.bat @@ -0,0 +1,116 @@ +@echo off +setlocal enabledelayedexpansion + +if "%1"=="" ( + call:default +) else ( + call:setargs %* +) + +call:createarray +call:fillarray +call:display +echo. +echo ------------------- +echo. + +for /l %%i in (1,1,%i%) do ( + echo. + echo ------------------- + echo. + call:evolve + call:display +) +pause>nul + +:default +set m=10 +set n=11 +set p=50 +set f=5 +set i=5 +exit /b + +:setargs +set m=%1 +set n=%m%+1 +set p=%2 +set f=%3 +set i=%4 +exit /b + +:createarray +for /l %%m in (0,1,%n%) do ( + for /l %%n in (0,1,%n%) do ( + set a%%m%%n=0 + ) +) +exit /b + +:fillarray +for /l %%m in (1,1,%m%) do ( + for /l %%n in (1,1,%m%) do ( + set /a treerandom=!random! %% 101 + if !treerandom! leq %p% set a%%m%%n=T + ) +) +exit /b + +:display +for /l %%m in (1,1,%m%) do ( + set "line%%m=" + for /l %%n in (1,1,%m%) do ( + set line%%m=!line%%m! !a%%m%%n! + ) + set line%%m=!line%%m:0= ! + echo.!line%%m! +) +exit /b + +:evolve +for /l %%m in (1,1,%m%) do ( + for /l %%n in (1,1,%m%) do ( + call:nexttick !a%%m%%n! %%m %%n + set newa%%m%%n=!errorlevel! + ) +) +call:update +exit /b + +:nexttick + +if %1==0 ( + set /a treerandom=!random! %% 101 + if !treerandom! leq %p% exit /b 1 + exit /b 0 +) + +if %1==T ( + set /a lowerm=%2-1 + set /a upperm=%2+1 + set /a lowern=%3-1 + set /a uppern=%3+1 + set burn=0 + for /l %%m in (!lowerm!,1,!upperm!) do ( + for /l %%n in (!lowern!,1,!uppern!) do ( + if !a%%m%%n!==# set burn=1 + ) + ) + if !burn!==1 exit /b 2 + + set /a burnrandom=!random! %% 101 + if !burnrandom! leq %f% exit /b 2 + exit /b 1 +) + +if %1==# exit /b 0 + +:update +for /l %%m in (1,1,%m%) do ( + for /l %%n in (1,1,%m%) do ( + if !newa%%m%%n!==1 set newa%%m%%n=T + if !newa%%m%%n!==2 set newa%%m%%n=# + set a%%m%%n=!newa%%m%%n! + ) +) +exit /b diff --git a/Task/Forest-fire/C-sharp/forest-fire.cs b/Task/Forest-fire/C-sharp/forest-fire.cs deleted file mode 100644 index 19761750e1..0000000000 --- a/Task/Forest-fire/C-sharp/forest-fire.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System; - -namespace ForestFire -{ - internal class Program - { - private static void Main(string[] args) - { - Console.Write("Height? "); - int height = int.Parse(Console.ReadLine()); - Console.Write("Width? "); - int width = int.Parse(Console.ReadLine()); - Console.Write("Probability of a tree spontaneously combusting? 1/"); - int f = int.Parse(Console.ReadLine()); - Console.Write("Probability of a tree growing? 1/"); - int p = int.Parse(Console.ReadLine()); - Console.Clear(); - - var state = InitializeForestFire(height, width); - - uint generation = 0; - - do - { - state = StepForestFire(state, f, p); - - Console.SetCursorPosition(0, 0); - Console.ResetColor(); - Console.WriteLine("Generation " + ++generation); - - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - switch (state[y, x]) - { - case CellState.Empty: - Console.Write(' '); - break; - case CellState.Tree: - Console.ForegroundColor = ConsoleColor.DarkGreen; - Console.Write('T'); - break; - case CellState.Burning: - Console.ForegroundColor = ConsoleColor.DarkRed; - Console.Write('F'); - break; - } - } - - Console.WriteLine(); - } - } while (Console.ReadKey(true).Key != ConsoleKey.Q && generation < uint.MaxValue); - } - - private static CellState[,] InitializeForestFire(int height, int width) - { - // Create our state array, initialize all indices as Empty, and return it. - var state = new CellState[height, width]; - state.Initialize(); - return state; - } - - private enum CellState : byte - { - Empty = 0, - Tree = 1, - Burning = 2 - } - - private static readonly Random Random = new Random(); - - private static CellState[,] StepForestFire(CellState[,] state, int f, int p) - { - /* Clone our old state, so we can write to our new state - * without changing any values in the old state. */ - var newState = (CellState[,]) state.Clone(); - - int height = state.GetLength(0); - int width = state.GetLength(1); - - for (int i = 1; i < height - 1; i++) - { - for (int o = 1; o < width - 1; o++) - { - /* - * Check the current cell. - * - * If it's empty, give it a 1/p chance of becoming a tree. - * - * If it's a tree, check to see if any neighbors are burning. - * If so, set the cell's state to burning, otherwise give it - * a 1/f chance of combusting. - * - * If it's burning, set it to empty. - */ - switch (state[i, o]) - { - case CellState.Empty: - if (Random.Next(0, p) == 0) - newState[i, o] = CellState.Tree; - break; - case CellState.Tree: - if (IsNeighbor(state, i, o, CellState.Burning) || - Random.Next(0, f) == 0) - newState[i, o] = CellState.Burning; - break; - case CellState.Burning: - newState[i, o] = CellState.Empty; - break; - } - } - } - - return newState; - } - - private static bool IsNeighbor(CellState[,] state, int x, int y, CellState value) - { - // Check each cell within a 1 cell radius for the specified value. - for (int i = -1; i <= 1; i++) - { - for (int o = -1; o <= 1; o++) - { - if (i == 0 && o == 0) - continue; - - if (state[x + i, y + o] == value) - return true; - } - } - - return false; - } - } -} diff --git a/Task/Forest-fire/Ceylon/forest-fire.ceylon b/Task/Forest-fire/Ceylon/forest-fire.ceylon index 8c97ab9bd6..ba33d01435 100644 --- a/Task/Forest-fire/Ceylon/forest-fire.ceylon +++ b/Task/Forest-fire/Ceylon/forest-fire.ceylon @@ -1,135 +1,124 @@ -import ceylon.random { - - DefaultRandom -} +import ceylon.random { DefaultRandom } -class Cell of tree | empty | burning { - - shared new tree {} - shared new empty {} - shared new burning {} -} +abstract class Cell() of tree | dirt | burning {} +object tree extends Cell() { string => "A"; } +object dirt extends Cell() { string => " "; } +object burning extends Cell() { string => "#"; } class Forest(Integer width, Integer height, Float f, Float p) { - - value random = DefaultRandom(); - function chance(Float probability) => random.nextFloat() < probability; - - object doubleBufferedGrid satisfies Iterable, Null> { - - function makeGrid(Cell|Cell() initialValue) => [ - for(j in 0:height) - Array { - for(i in 0:width) - switch(initialValue) - case(is Cell) initialValue - case(is Cell()) initialValue() - } - ]; - - value grids = [ - makeGrid(() => - if(chance(0.5)) - then Cell.tree - else Cell.empty), - makeGrid(Cell.empty) - ]; - - variable value firstIsFront = true; - value front => firstIsFront then grids.first else grids.last; - value back => firstIsFront then grids.last else grids.first; - - iterator() => front.iterator(); - shared Cell? get(Integer x, Integer y) => front[y]?.get(x); - shared void set(Integer x, Integer y, Cell cell) => back[y]?.set(x, cell); - shared void flip() => firstIsFront = !firstIsFront; - } - - shared void evolve() { - - function fireNearby(Integer x, Integer y) { - for(i in -1..1) { - for(j in -1..1) { - if(i == 0 && j == 0) { - continue; - } - if(exists cell = doubleBufferedGrid.get(x + i, y + j), - cell == Cell.burning) { - return true; - } - } - } - return false; - } - - for(j->row in doubleBufferedGrid.indexed) { - for(i->cell in row.indexed) { - switch(cell) - case(Cell.burning) { - doubleBufferedGrid.set(i, j, Cell.empty); - } - case(Cell.empty) { - value nextCell = chance(p) then Cell.tree else Cell.empty; - doubleBufferedGrid.set(i, j, nextCell); - } - case(Cell.tree) { - value nextCell = - fireNearby(i, j) || chance(f) - then Cell.burning - else Cell.tree; - doubleBufferedGrid.set(i, j, nextCell); - } - } - } - - doubleBufferedGrid.flip(); - } - - shared void display() { - - void drawLine() => print("-".repeat(width + 2)); - - drawLine(); - for(row in doubleBufferedGrid) { - process.write("|"); - for(cell in row) { - switch(cell) - case(Cell.empty) { - process.write(" "); - } - case(Cell.tree) { - process.write("A"); - } - case(Cell.burning) { - process.write("#"); - } - } - print("|"); - } - drawLine(); - } + + value random = DefaultRandom(); + function chance(Float probability) => random.nextFloat() < probability; + value sparked => chance(f); + value sprouted => chance(p); + + alias Point => Integer[2]; + interface Row => {Cell*}; + + object doubleBufferedGrid satisfies + Correspondence & + KeyedCorrespondenceMutator { + + value grids = [ + Array { + for (j in 0:height) + Array { + for (i in 0:width) + chance(0.5) then tree else dirt + } + }, + Array { + for (j in 0:height) + Array.ofSize(width, dirt) + } + ]; + + variable value showFirst = true; + value currentState => showFirst then grids.first else grids.last; + value nextState => showFirst then grids.last else grids.first; + + shared void swapStates() => showFirst = !showFirst; + + shared {Row*} rows => currentState; + + shared actual Boolean defines(Point key) => + let (x = key[0], y = key[1]) + 0 <= x < width && 0 <= y < height; + shared actual Cell? get(Point key) => + let (x = key[0], y = key[1]) + currentState.get(y)?.get(x); + + shared actual void put(Point key, Cell cell) { + value [x, y] = key; + nextState.get(y)?.set(x, cell); + } + } + + variable value evolutions = 0; + shared Integer generation => evolutions + 1; + + shared void evolve() { + + evolutions++; + + function firesNearby(Integer x, Integer y) => { + for (j in y - 1 : 3) + for (i in x - 1 : 3) + doubleBufferedGrid[[i, j]] + }.coalesced.any(burning.equals); + + for(j->row in doubleBufferedGrid.rows.indexed) { + for(i->cell in row.indexed) { + switch (cell) + case (burning) { + doubleBufferedGrid[[i, j]] = dirt; + } + case (dirt) { + doubleBufferedGrid[[i, j]] = sprouted then tree else dirt; + } + case (tree) { + doubleBufferedGrid[[i, j]] = + firesNearby(i, j) || sparked + then burning else tree; + } + } + } + + doubleBufferedGrid.swapStates(); + } + + shared void display() { + + void drawLine() => print("-".repeat(width + 2)); + + drawLine(); + for (row in doubleBufferedGrid.rows) { + process.write("|"); + for (cell in row) { + process.write(cell.string); + } + print("|"); + } + drawLine(); + } } shared void run() { - - value forest = Forest(78, 38, 0.02, 0.03); - variable value generation = 1; - - while(true) { - - forest.display(); - forest.evolve(); - - print("Generation ``generation++`` - Press enter for next generation or q and then enter to quit"); - - value input = process.readLine(); - if(exists input) { - switch(input.trimmed) - case("q" | "Q") { - return; - } - else {} - } - } + + value forest = Forest(78, 38, 0.02, 0.03); + + while (true) { + + forest.display(); + + print("Generation ``forest.generation``"); + print("Press enter for next generation or q and then enter to quit"); + + value input = process.readLine(); + if (exists input, input.trimmed.lowercased == "q") { + return; + } + + forest.evolve(); + } } diff --git a/Task/Forest-fire/D/forest-fire-1.d b/Task/Forest-fire/D/forest-fire-1.d index 64fa9b2212..b850fdc096 100644 --- a/Task/Forest-fire/D/forest-fire-1.d +++ b/Task/Forest-fire/D/forest-fire-1.d @@ -7,7 +7,7 @@ enum cProb = 0.01; // Tree creation probability. enum Cell : char { empty=' ', tree='T', fire='#' } alias World = Cell[][]; -bool hasBurningNeighbours(in World world, in int r, in int c) +bool hasBurningNeighbours(in World world, in ulong r, in ulong c) pure nothrow @safe @nogc { foreach (immutable rowShift; -1 .. 2) foreach (immutable colShift; -1 .. 2) @@ -19,8 +19,8 @@ pure nothrow @safe @nogc { } void nextState(in World world, World nextWorld) /*nothrow*/ @safe /*@nogc*/ { - foreach (immutable r, const row; world) - foreach (immutable c, immutable elem; row) + foreach (r, row; world) + foreach (c, elem; row) final switch (elem) with (Cell) { case empty: nextWorld[r][c]= (uniform01 < cProb) ? tree : empty; diff --git a/Task/Forest-fire/D/forest-fire-3.d b/Task/Forest-fire/D/forest-fire-3.d deleted file mode 100644 index d9b48ea23c..0000000000 --- a/Task/Forest-fire/D/forest-fire-3.d +++ /dev/null @@ -1,77 +0,0 @@ -#chance of empty->tree -set :p 0.004 -#chance of spontaneous tree combustion -set :f 0.001 -#chance of tree in initial state -set :s 0.5 -#height of world -set :H 10 -#width of world -set :W 20 - -has-burning-neigbour state pos: - for i range -- swap ++ dup &< pos: - for j range -- swap ++ dup &> pos: - & i j - try: - state! - catch value-error: - :empty - if = :burning: - return true - false - -evolve state pos: - state! pos - if = :tree dup: - if has-burning-neigbour state pos: - :burning drop - elseif chance f: - :burning drop - elseif = :burning: - :empty - else: - if chance p: - :tree - else: - :empty - -step state: - local :next {} - for k in keys state: - set-to next k evolve state k - next - -local :(c) { :tree "T" :burning "B" :empty "." } -print-state state: - for j range 0 H: - for i range 0 W: - print\ (c)! state! & i j - print "" - -init-state: - local :first {} - for j range 0 H: - for i range 0 W: - if chance s: - :tree - else: - :empty - set-to first & i j - first - -run: - init-state - while true: - print-state dup - print "" - step - -run-slowly: - init-state - while true: - print-state dup - drop input - step - -run diff --git a/Task/Forest-fire/Haskell/forest-fire-1.hs b/Task/Forest-fire/Haskell/forest-fire-1.hs deleted file mode 100644 index af60384e6b..0000000000 --- a/Task/Forest-fire/Haskell/forest-fire-1.hs +++ /dev/null @@ -1,47 +0,0 @@ -import Data.List -import Control.Arrow -import Control.Monad -import System.Random - -data Cell = Empty | Tree | Fire deriving (Eq) - -instance Show Cell where - show Empty = " " - show Tree = "T" - show Fire = "$" - -randomCell = liftM ([Empty, Tree] !!) (randomRIO (0,1) :: IO Int) -randomChance = randomRIO (0,1.0) :: IO Double - -rim b = map (fb b). (fb =<< rb) where - fb = liftM2 (.) (:) (flip (++) . return) - rb = fst. unzip. zip (repeat b). head - -take3x3 = concatMap (transpose. map take3). take3 where - take3 = init. init. takeWhile (not.null). map(take 3). tails - -list2Mat n = takeWhile(not.null). map(take n). iterate(drop n) - -evolveForest :: Int -> Int -> Int -> IO () -evolveForest m n k = do - let s = m*n - fs <- replicateM s randomCell - - let nextState xs = do - ts <- replicateM s randomChance - vs <- replicateM s randomChance - let rv [r1,[l,c,r],r3] newTree fire - | c == Fire = Empty - | c == Tree && Fire `elem` concat [r1,[l,r],r3] = Fire - | c == Tree && 0.01 >= fire = Fire - | c == Empty && 0.1 >= newTree = Tree - | otherwise = c - return $ zipWith3 rv xs ts vs - - evolve i xs = unless (i > k) $ - do let nfs = nextState $ take3x3 $ rim Empty $ list2Mat n xs - putStrLn ("\n>>>>>> " ++ show i ++ ":") - mapM_ (putStrLn. concatMap show) $ list2Mat n xs - nfs >>= evolve (i+1) - - evolve 1 fs diff --git a/Task/Forest-fire/Haskell/forest-fire-2.hs b/Task/Forest-fire/Haskell/forest-fire-2.hs deleted file mode 100644 index 2feca4a1c6..0000000000 --- a/Task/Forest-fire/Haskell/forest-fire-2.hs +++ /dev/null @@ -1,25 +0,0 @@ -*Main> evolveForest 6 50 3 - ->>>>>> 1: - T T T TTTTTTTTT TT TT T T T TT TT - TTT TT T TT TTTT T T TT T T T T T T TTTTT T - T TT T TTT T TTTTT TTTTTTTT T TTT TTTT TT - TT TT T TT T TTT T T T TTTT T TTT TT T TT - TT TT TT TT T T T T TT T T TT T T TTTTT - T TT T T T TTTTTT T T T T T TT T TT - ->>>>>> 2: - T T T TTTTTTTTT TT TT TT T $ TT TT - TTT TT T TT TTTT T T TT T T T T T T TTTTT T - TT TTTT TT$ T TTTTTT TTTTT$TT T T$T TTTT TT - TT TT T TT T TTTTTTT T TTTT T TTT TT T TT - TT TT TT TT T T T T TT T T TT T T TTTTT -TTT TT TT T T TTTTTT T T T T T TT TT TT - ->>>>>> 3: - TTTTT T TTTTTTTTT TT TT TT T TT TT - TTTT TT T $$ TTTT T T $$ T T T T $ $ TTTTT T - TTTTTTT T$ T TTTTTT TTTT$ $T T $ $ TTTTT TT - TT TT T $$ T TTTTTTT T $$$T T TTT $$ T T TTT - TT TT TT TTT T T TT TT TT T T TT T T TTTTT -TTT TT TT T T T TTTTTT T T T T T TT TT TT diff --git a/Task/Forest-fire/Haskell/forest-fire.hs b/Task/Forest-fire/Haskell/forest-fire.hs new file mode 100644 index 0000000000..62f705af26 --- /dev/null +++ b/Task/Forest-fire/Haskell/forest-fire.hs @@ -0,0 +1,59 @@ +import System.Random (randomRIO) +import Data.List (tails, transpose) +import Control.Monad (liftM2, replicateM, unless) + +data Cell + = Empty + | Tree + | Fire + deriving (Eq) + +instance Show Cell where + show Empty = " " + show Tree = "T" + show Fire = "$" + +randomCell :: IO Cell +randomCell = fmap ([Empty, Tree] !!) (randomRIO (0, 1) :: IO Int) + +randomChance :: IO Double +randomChance = randomRIO (0, 1.0) :: IO Double + +rim :: a -> [[a]] -> [[a]] +rim b = fmap (fb b) . (fb =<< rb) + where + fb = liftM2 (.) (:) (flip (++) . return) + rb = fst . unzip . zip (repeat b) . head + +take3x3 :: [[a]] -> [[[a]]] +take3x3 = concatMap (transpose . fmap take3) . take3 + where + take3 = init . init . takeWhile (not . null) . fmap (take 3) . tails + +list2Mat :: Int -> [a] -> [[a]] +list2Mat n = takeWhile (not . null) . fmap (take n) . iterate (drop n) + +evolveForest :: Int -> Int -> Int -> IO () +evolveForest m n k = do + let s = m * n + fs <- replicateM s randomCell + let nextState xs = do + ts <- replicateM s randomChance + vs <- replicateM s randomChance + let rv [r1, [l, c, r], r3] newTree fire + | c == Fire = Empty + | c == Tree && Fire `elem` concat [r1, [l, r], r3] = Fire + | c == Tree && 0.01 >= fire = Fire + | c == Empty && 0.1 >= newTree = Tree + | otherwise = c + return $ zipWith3 rv xs ts vs + evolve i xs = + unless (i > k) $ + do let nfs = nextState $ take3x3 $ rim Empty $ list2Mat n xs + putStrLn ("\n>>>>>> " ++ show i ++ ":") + mapM_ (putStrLn . concatMap show) $ list2Mat n xs + nfs >>= evolve (i + 1) + evolve 1 fs + +main :: IO () +main = evolveForest 6 50 3 diff --git a/Task/Forest-fire/Julia/forest-fire.julia b/Task/Forest-fire/Julia/forest-fire.julia new file mode 100644 index 0000000000..0ab0740022 --- /dev/null +++ b/Task/Forest-fire/Julia/forest-fire.julia @@ -0,0 +1,61 @@ +# v0.6 + +@enum State empty tree fire + + +function evolution(nepoch::Int=100, init::Matrix{State}=fill(tree, 30, 50)) + # Single evolution + function evolve!(forest::Matrix{State}; f::Float64=0.12, p::Float64=0.5) + dir = [-1 -1; -1 0; -1 1; 0 -1; 0 1; 1 -1; 1 0; 1 1] + # A tree will burn if at least one neighbor is burning + for i in 1:size(forest, 1), j in 1:size(forest, 2) + for k in 1:size(dir, 1) + if checkbounds(Bool, forest, i + dir[k, 1], j + dir[k, 2]) && + get(forest, i + dir[k, 1], j + dir[k, 2]) == fire + forest[i, j] = fire + break + end + end + end + for i in linearindices(forest) + # A burning cell turns into an empty cell + if forest[i] == fire forest[i] = empty end + # A tree ignites with probability f even if no neighbor is burning + if forest[i] == tree && rand() < f forest[i] = fire end + # An empty space fills with a tree with probability p + if forest[i] == empty && rand() < p forest[i] = tree end + end + end + + # Print functions + function printforest(f::Matrix{State}) + for i in 1:size(f, 1) + for j in 1:size(f, 2) + print(f[i, j] == empty ? ' ' : f[i, j] == tree ? '🌲' : '🔥') + end + println() + end + end + function printstats(f::Matrix{State}) + tot = length(f) + nt = count(x -> x in (tree, fire), f) + nb = count(x -> x == fire, f) + @printf("\n%6i cell(s), %6i tree(s), %6i currently burning (%6.2f%%, %6.2f%%)\n", + tot, nt, nb, nt / tot * 100, nb / nt * 100) + end + + # Main + printforest(init) + printstats(init) + for i in 1:nepoch + # println("\33[2J") + evolve!(init) + # printforest(init) + # printstats(init) + # sleep(1) + end + printforest(init) + printstats(init) +end + +evolution() diff --git a/Task/Forest-fire/Liberty-BASIC/forest-fire.liberty b/Task/Forest-fire/Liberty-BASIC/forest-fire.liberty deleted file mode 100644 index 77a0e2a71e..0000000000 --- a/Task/Forest-fire/Liberty-BASIC/forest-fire.liberty +++ /dev/null @@ -1,41 +0,0 @@ -'[RC] Forest Fire - dim oldgen(200,200), newgen(200,200) - p =0.99 - f =0.9999 - - nomainwin - WindowWidth = 200 - WindowHeight = 200 - open "Forest Fire" for graphics_nsb_nf as #1 - #1 "trapclose [quit]" - #1 "down ; fill brown ; flush" - - p =0.99 - f =0.9999 - - for generation = 1 to 200 - for x = 1 to 199 - for y = 1 to 199 - scan 'we can break early - select case oldgen(x,y) - case 0 - if rnd(0) > p then newgen(x,y) = 1 : #1 "color green ; set "; x; " "; y - case 2 - newgen(x,y) = 0 : #1 "color brown ; set "; x; " "; y - case 1 - if oldgen(x-1,y-1) = 2 or oldgen(x-1,y) = 2 or oldgen(x-1,y+1) = 2_ - or oldgen(x,y-1) = 2 or oldgen(x,y+1) = 2 or oldgen(x+1,y-1) = 2_ - or oldgen(x+1,y) = 2 or oldgen(x+1,y+1) = 2 or rnd(0) > f then - #1 "color red ; set "; x; " "; y - newgen(x,y) = 2 - end if - end select - oldgen(x-1,y-1)=newgen(x-1,y-1) - next y - next x - next generation - - - [quit] - close #1 - end diff --git a/Task/Forest-fire/PHP/forest-fire.php b/Task/Forest-fire/PHP/forest-fire.php new file mode 100644 index 0000000000..042f49bfd6 --- /dev/null +++ b/Task/Forest-fire/PHP/forest-fire.php @@ -0,0 +1,112 @@ + function(){ + return isProb(TREE_PROB) ? TREE : BARE; + } + ]); +} + + +function displayForest($forest, $generationNum) { + system("clear"); + echo PHP_EOL . "Generation: $generationNum" . PHP_EOL; + mapForest(['forest' => $forest, 'func' => function($f, $x, $y){ + echo $f[$y][$x] . ($x == WIDTH - 1 ? PHP_EOL : ''); + } + ]); + echo PHP_EOL; + usleep(PAUSE); +} + + +function getNextForest($oldForest) { + return mapForest(['forest' => $oldForest, 'func' => function($f, $x, $y){ + switch ($f[$y][$x]) { + case BURN: + return BARE; + case BARE: + return isProb(GROW_PROB) ? TREE : BARE; + case TREE: + $caughtFire = isProb(FIRE_PROB); + $ablaze = $caughtFire ? true : getNumBurningNeighbors($f, $x, $y) > 0; + return $ablaze ? BURN : TREE; + } + } + ]); +} + + +function getNumBurningNeighbors($forest, $x, $y) { + $burningNeighbors = mapForest([ + 'forest' => $forest, + 'x1' => $x - 1, 'x2' => $x + 2, + 'y1' => $y - 1, 'y2' => $y + 2, + 'default' => 0, + 'func' => function($f, $x, $y){ + return $f[$y][$x] == BURN ? 1 : 0; + } + ]); + + $numOnFire = 0; + foreach ($burningNeighbors as $row) { + $numOnFire += array_sum($row); + } + return $numOnFire; +} + + +function mapForest($params) { + $p = array_merge([ + 'forest' => [], + 'func' => function(){echo "default\n";}, + 'x1' => 0, + 'x2' => WIDTH, + 'y1' => 0, + 'y2' => HEIGHT, + 'default' => BARE + ], $params); + + $newForest = []; + for ($y = $p['y1']; $y < $p['y2']; $y++) { + $newRow = []; + for ($x = $p['x1']; $x < $p['x2']; $x++) { + $inBounds = ($x >= 0 && $x < WIDTH && $y >= 0 && $y < HEIGHT); + $newRow[] = ($inBounds ? $p['func']($p['forest'], $x, $y) : $p['default']); + } + $newForest[] = $newRow; + } + return $newForest; +} + + +function isProb($prob) { + return rand(0, 100) < $prob; +} diff --git a/Task/Forest-fire/Phix/forest-fire.phix b/Task/Forest-fire/Phix/forest-fire.phix new file mode 100644 index 0000000000..d289b4550a --- /dev/null +++ b/Task/Forest-fire/Phix/forest-fire.phix @@ -0,0 +1,94 @@ +-- +-- demo\rosetta\Forest_fire.exw +-- +include pGUI.e + +Ihandle dlg, canvas, hTimer +cdCanvas cddbuffer, cdcanvas + +constant TITLE = "Forest Fire" + +sequence f = {} -- the forest + +atom P = 0.03 -- probability of new tree growing +atom F = 0.00003 -- probability of new fire starting + +enum EMPTY,TREE,FIRE -- (1,2,3) +constant colours = {CD_BLACK,CD_GREEN,CD_YELLOW} + +function randomf() + return rand(1000000)/1000000 -- returns 0.000001..1.000000 +end function + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) +integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE") + cdCanvasActivate(cddbuffer) + if length(f)!=w+2 + or length(f[1])!=h+2 then + f = sq_rand(repeat(repeat(2,h+2),w+2)) -- (EMPTY or TREE) + end if + sequence fn = f + for x = 2 to w+1 do + for y = 2 to h+1 do + integer fnxy + switch f[x,y] do + case EMPTY: + fnxy = EMPTY+(randomf()max - n=max - EndIf - ProcedureReturn n -EndProcedure - -Procedure SpreadFire(x,y) - Protected cnt=0, i, j - For i=Limit(x-1, 0, #Width) To Limit(x+1, 0, #Width) - For j=Limit(y-1, 0, #Height) To Limit(y+1, 0, #Height) - If Forest(i,j)>=#Tree - Forest(i,j)=#Ignited - EndIf - Next - Next -EndProcedure - -Procedure InitMap() - Protected x, y, type - For y=1 To #Height - For x=1 To #Width - If Rnd()<=#SeedATree - type=#Tree - Else - type=#Empty - EndIf - Forest(x,y)=type - Next - Next -EndProcedure - -Procedure UpdateMap() - Protected x, y - For y=1 To #Height - For x=1 To #Width - Select Forest(x,y) - Case #Burning - Forest(x,y)=#Empty - SpreadFire(x,y) - Case #Ignited - Forest(x,y)=#Burning - Case #Empty - If Rnd()<=#p - Forest(x,y)=#Tree - EndIf - Default - If Rnd()<=#f - Forest(x,y)=#Burning - Else - Forest(x,y)+1 - EndIf - EndSelect - Next - Next -EndProcedure - -Procedure PresentMap() - Protected x, y, c - cnt+1 - SetWindowTitle(0,Title$+", time frame="+Str(cnt)) - StartDrawing(ImageOutput(1)) - For y=0 To OutputHeight()-1 - For x=0 To OutputWidth()-1 - Select Forest(x,y) - Case #Empty - c=#BackGround - Case #Burning, #Ignited - c=#Fire - Default - If Forest(x,y)<#Tree+#Old - c=#YoungTree - ElseIf Forest(x,y)<#Tree+2*#Old - c=#NormalTree - ElseIf Forest(x,y)<#Tree+3*#Old - c=#MatureTree - ElseIf Forest(x,y)<#Tree+4*#Old - c=#OldTree - Else ; Tree died of old age - Forest(x,y)=#Empty - c=#Black - EndIf - EndSelect - Plot(x,y,c) - Next - CompilerIf #UnLoadCPU>1 - Delay(1) - CompilerEndIf - Next - StopDrawing() - ImageGadget(1, 0, 0, #Width, #Height, ImageID(1)) -EndProcedure - -If OpenWindow(0, 10, 30, #Width, #Height, Title$, #PB_Window_MinimizeGadget) - SmartWindowRefresh(0, 1) - If CreateImage(1, #Width, #Height) - Define Event, freq - If ExamineDesktops() And DesktopFrequency(0) - freq=DesktopFrequency(0) - Else - freq=60 - EndIf - AddWindowTimer(0,0,5000/freq) - InitMap() - Repeat - Event = WaitWindowEvent() - Select Event - Case #PB_Event_CloseWindow - End - Case #PB_Event_Timer - CompilerIf #UnLoadCPU>0 - Delay(25) - CompilerEndIf - UpdateMap() - PresentMap() - EndSelect - ForEver - EndIf -EndIf diff --git a/Task/Forest-fire/REALbasic/forest-fire-1.realbasic b/Task/Forest-fire/REALbasic/forest-fire-1.realbasic deleted file mode 100644 index 09e3fcf37b..0000000000 --- a/Task/Forest-fire/REALbasic/forest-fire-1.realbasic +++ /dev/null @@ -1,65 +0,0 @@ -Sub Run() - //Handy named constants - Const empty = 0 - Const tree = 1 - Const fire = 2 - Const ablaze = &cFF0000 //Using the &c numeric operator to indicate a color in hex - Const alive = &c00FF00 - Const dead = &c804040 - - //Our forest - Dim worldPic As New Picture(480, 480, 32) - Dim newWorld(120, 120) As Integer - Dim oldWorld(120, 120) As Integer - - //Initialize forest - Dim rand As New Random - For x as Integer = 0 to 119 - For y as Integer = 0 to 119 - if rand.InRange(0, 2) = 0 Or x = 119 or y = 119 or x = 0 or y = 0 Then - newWorld(x, y) = empty - worldPic.Graphics.ForeColor = dead - worldPic.Graphics.FillRect(x*4, y*4, 4, 4) - Else - newWorld(x, y) = tree - worldPic.Graphics.ForeColor = alive - worldPic.Graphics.FillRect(x*4, y*4, 4, 4) - end if - Next - Next - oldWorld = newWorld - - //Burn, baby burn! - While Window1.stop = False - For x as Integer = 0 To 119 - For y As Integer = 0 to 119 - Dim willBurn As Integer = rand.InRange(0, Window1.burnProb.Value) - Dim willGrow As Integer = rand.InRange(0, Window1.growProb.Value) - if x = 119 or y = 119 or x = 0 or y = 0 Then - Continue - end if - Select Case oldWorld(x, y) - Case empty - If willGrow = (Window1.growProb.Value) Then - newWorld(x, y) = tree - worldPic.Graphics.ForeColor = alive - worldPic.Graphics.FillRect(x*4, y*4, 4, 4) - end if - Case tree - if oldWorld(x - 1, y) = fire Or oldWorld(x, y - 1) = fire Or oldWorld(x + 1, y) = fire Or oldWorld(x, y + 1) = fire Or oldWorld(x + 1, y + 1) = fire Or oldWorld(x - 1, y - 1) = fire Or oldWorld(x - 1, y + 1) = fire Or oldWorld(x + 1, y - 1) = fire Or willBurn = (Window1.burnProb.Value) Then - newWorld(x, y) = fire - worldPic.Graphics.ForeColor = ablaze - worldPic.Graphics.FillRect(x*4, y*4, 4, 4) - end if - Case fire - newWorld(x, y) = empty - worldPic.Graphics.ForeColor = dead - worldPic.Graphics.FillRect(x*4, y*4, 4, 4) - End Select - Next - Next - Window1.Canvas1.Graphics.DrawPicture(worldPic, 0, 0) - oldWorld = newWorld - me.Sleep(Window1.speed.Value) - Wend -End Sub diff --git a/Task/Forest-fire/REALbasic/forest-fire-2.realbasic b/Task/Forest-fire/REALbasic/forest-fire-2.realbasic deleted file mode 100644 index 150d62e642..0000000000 --- a/Task/Forest-fire/REALbasic/forest-fire-2.realbasic +++ /dev/null @@ -1,11 +0,0 @@ -Sub Open() - //First method to run on the creation of a new Window. We instantiate an instance of our forestFire thread and run it. - Dim fire As New forestFire - fire.Run() -End Sub - -stop As Boolean //a globally accessible property of Window1. Boolean properties default to False. - -Sub Pushbutton1.Action() - stop = True -End Sub diff --git a/Task/Forest-fire/REXX/forest-fire.rexx b/Task/Forest-fire/REXX/forest-fire.rexx index 472c204cc0..a318992ecd 100644 --- a/Task/Forest-fire/REXX/forest-fire.rexx +++ b/Task/Forest-fire/REXX/forest-fire.rexx @@ -1,15 +1,13 @@ /*REXX program grows and displays a forest (with growth and fires caused by lightning).*/ -signal on halt /*handle any forest life interruptus. */ parse value scrSize() with sd sw . /*the size of the terminal display. */ -parse arg generations birth lightning randSeed . /*obtain the optional arguments from CL*/ -if randSeed\=='' then call random ,,randSeed /*do we want RANDOM BIF repeatability?*/ +parse arg generations birth lightning rSeed . /*obtain the optional arguments from CL*/ +if datatype(rSeed,'W') then call random ,,rSeed /*do we want RANDOM BIF repeatability?*/ generations = p(generations 100) /*maybe use one hundred generations. */ birth = p(strip(birth , ,'%') 50 ) *100 /*calculate the percentage for births. */ lightning = p(strip(lightning, ,'%') 1/8) *100 /* " " " " lightning*/ -clearScreen = 1 /*(or 0) ─── uses CLS (a DOS command).*/ bare! = ' ' /*the glyph used to show a bare place. */ fire! = '▒' /*glyph is close to a conflagration. */ - tree! = '18'x /*this is an up─arrow [↑] glyph (tree).*/ + tree! = '↑' /*this is an up─arrow [↑] glyph (tree).*/ rows = max(12, sd-2) /*shrink the usable screen rows by two.*/ cols = max(79, sw-1) /* " " " " cols " one.*/ every = 999999999 /*shows a snapshot every Nth generation*/ @@ -17,6 +15,7 @@ clearScreen = 1 /*(or 0) ─── uses CLS (a $.=bare! /*forest: it is now a treeless field. */ @.=$. /*ditto, for the "shadow" forest. */ gens=abs(generations) /*use this for convenience. */ +signal on halt /*handle any forest life interruptus. */ /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒observe the forest grow and/or burn. */ do life=1 for gens /*simulate a forest's life cycle. */ do r=1 for rows; rank=bare! /*start a forest rank as being bare. */ @@ -24,31 +23,28 @@ gens=abs(generations) /*use this for convenience. select /*select the most likeliest choice 1st.*/ when ?==tree! then if ignite?() then ??=fire! /*on fire ? */ when ?==bare! then if random(1, field)<=birth then ??=tree! /*new growth.*/ - otherwise ??=bare! /*it's baren.*/ + otherwise ??=bare! /*it's barren*/ end /*select*/ /* [↑] when (↑) if ≡ short circuit.*/ rank=rank || ?? /*build rank: 1 forest "row" at a time*/ end /*c*/ /*ignore column one, start with col two*/ @.r=rank /*and assign rank to alternate forest. */ end /*r*/ /* [↓] ··· and, later, yet back again.*/ - do r=1 for rows; $.r=@.r; end /*r*/ /*assign alternate cells ──► real cells*/ - if life//every==0 | generations>0 | life==gens then call showForest + do r=1 for rows; $.r=@.r; end /*r*/ /*assign alternate cells ──► real cells*/ + if \(life//every==0 | generations>0 | life==gens) then iterate + 'CLS' /* ◄─── change this command for your OS*/ + do r=rows by -1 for rows; say strip(substr($.r, 2), 'T') /*a row of trees*/ + end /*r*/ /* [↑] display forest to the terminal.*/ + say right(copies('▒', cols)life, cols) /*show and tell for a stand of trees. */ end /*life*/ /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒stop observing the forest evolve. */ halt: if life-1\==gens then say 'Forest simulation interrupted.' /*was this pgm HALTed?*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -ignite?: if substr($.r,c+1,1)==fire! then return 1 /*is east on fire? */ - if substr($.r,c-1,1)==fire! then return 1 /* " west " " */ - cm=c-1; rm=r-1; rp=r+1 /*curr. row offsets.*/ - if pos(fire!, substr($.rm, cm, 3)substr($.rp, cm,3))\==0 then return 1 +ignite?: if substr($.r, c+1, 1) == fire! then return 1 /*is east on fire? */ + cm=c-1; if substr($.r, cm , 1) == fire! then return 1 /* " west " " */ + rm=r-1; rp=r+1 /*test north & south*/ + if pos(fire!, substr($.rm, cm, 3)substr($.rp, cm, 3)) \== 0 then return 1 return random(1, field) <= lightning /*lightning ignition*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ p: return word(arg(1), 1) /*pick─a─word: first or second word.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -showForest: if clearScreen then 'CLS' /* ◄───change this command for your OS*/ - do r=rows by -1 for rows /*show the forest grid in proper order.*/ - say strip(substr($.r, 2), 'T') /*be smart/neat about trailing blanks. */ - end /*r*/ /* [↑] that is to say, remove them. */ - say right(copies('▒',cols)life,cols) /*show and tell for a stand of trees. */ - return diff --git a/Task/Forest-fire/Run-BASIC/forest-fire.run b/Task/Forest-fire/Run-BASIC/forest-fire.run deleted file mode 100644 index 049ad7a6d4..0000000000 --- a/Task/Forest-fire/Run-BASIC/forest-fire.run +++ /dev/null @@ -1,25 +0,0 @@ -graphic #g, 200,200 -dim preGen(200,200) -dim newGen(200,200) - -for gen = 1 to 200 - for x = 1 to 199 - for y = 1 to 199 - select case preGen(x,y) - case 0 - if rnd(0) > .99 then newGen(x,y) = 1 : #g "color green ; set "; x; " "; y - case 2 - newGen(x,y) = 0 : #g "color brown ; set "; x; " "; y - case 1 - if preGen(x-1,y-1) = 2 or preGen(x-1,y) = 2 or preGen(x-1,y+1) = 2 _ - or preGen(x,y-1) = 2 or preGen(x,y+1) = 2 or preGen(x+1,y-1) = 2 _ - or preGen(x+1,y) = 2 or preGen(x+1,y+1) = 2 or rnd(0) > .999 then - #g "color red ; set "; x; " "; y - newGen(x,y) = 2 - end if - end select - preGen(x-1,y-1) = newGen(x-1,y-1) - next y - next x -next gen -render #g diff --git a/Task/Forest-fire/Visual-Basic-.NET/forest-fire.visual b/Task/Forest-fire/Visual-Basic-.NET/forest-fire.visual deleted file mode 100644 index c6dab6da3f..0000000000 --- a/Task/Forest-fire/Visual-Basic-.NET/forest-fire.visual +++ /dev/null @@ -1,104 +0,0 @@ -Public Class ForestFire - Private _forest(,) As ForestState - Private _isBuilding As Boolean - Private _bm As Bitmap - Private _gen As Integer - Private _sw As Stopwatch - - Private Const _treeStart As Double = 0.5 - Private Const _f As Double = 0.00001 - Private Const _p As Double = 0.001 - - Private Const _winWidth As Integer = 300 - Private Const _winHeight As Integer = 300 - - Private Enum ForestState - Empty - Burning - Tree - End Enum - - Private Sub ForestFire_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - Me.ClientSize = New Size(_winWidth, _winHeight) - ReDim _forest(_winWidth, _winHeight) - - Dim rnd As New Random() - For i As Integer = 0 To _winHeight - 1 - For j As Integer = 0 To _winWidth - 1 - _forest(j, i) = IIf(rnd.NextDouble <= _treeStart, ForestState.Tree, ForestState.Empty) - Next - Next - - _sw = New Stopwatch - _sw.Start() - DrawForest() - Timer1.Start() - End Sub - - Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick - If _isBuilding Then Exit Sub - - _isBuilding = True - GetNextGeneration() - - DrawForest() - _isBuilding = False - End Sub - - Private Sub GetNextGeneration() - Dim forestCache(_winWidth, _winHeight) As ForestState - Dim rnd As New Random() - - For i As Integer = 0 To _winHeight - 1 - For j As Integer = 0 To _winWidth - 1 - Select Case _forest(j, i) - Case ForestState.Tree - If forestCache(j, i) <> ForestState.Burning Then - forestCache(j, i) = IIf(rnd.NextDouble <= _f, ForestState.Burning, ForestState.Tree) - End If - - Case ForestState.Burning - For i2 As Integer = i - 1 To i + 1 - If i2 = -1 OrElse i2 >= _winHeight Then Continue For - For j2 As Integer = j - 1 To j + 1 - If j2 = -1 OrElse i2 >= _winWidth Then Continue For - If _forest(j2, i2) = ForestState.Tree Then forestCache(j2, i2) = ForestState.Burning - Next - Next - forestCache(j, i) = ForestState.Empty - - Case Else - forestCache(j, i) = IIf(rnd.NextDouble <= _p, ForestState.Tree, ForestState.Empty) - End Select - Next - Next - - _forest = forestCache - _gen += 1 - End Sub - - Private Sub DrawForest() - Dim bmCache As New Bitmap(_winWidth, _winHeight) - - For i As Integer = 0 To _winHeight - 1 - For j As Integer = 0 To _winWidth - 1 - Select Case _forest(j, i) - Case ForestState.Tree - bmCache.SetPixel(j, i, Color.Green) - - Case ForestState.Burning - bmCache.SetPixel(j, i, Color.Red) - End Select - Next - Next - - _bm = bmCache - Me.Refresh() - End Sub - - Private Sub ForestFire_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint - e.Graphics.DrawImage(_bm, 0, 0) - - Me.Text = "Gen " & _gen.ToString() & " @ " & (_gen / (_sw.ElapsedMilliseconds / 1000)).ToString("F02") & " FPS: Forest Fire" - End Sub -End Class diff --git a/Task/Fork/BaCon/fork.bacon b/Task/Fork/BaCon/fork.bacon new file mode 100644 index 0000000000..3605bb4d15 --- /dev/null +++ b/Task/Fork/BaCon/fork.bacon @@ -0,0 +1,14 @@ +' Fork +pid = FORK +IF pid = 0 THEN + PRINT "I am the child, my PID is:", MYPID + ENDFORK +ELIF pid > 0 THEN + PRINT "I am the parent, pid of child:", pid + REPEAT + PRINT "Waiting for child to exit" + SLEEP 50 + UNTIL REAP(pid) +ELSE + PRINT "Error in fork" +ENDIF diff --git a/Task/Fork/Nimrod/fork.nimrod b/Task/Fork/Nimrod/fork.nimrod deleted file mode 100644 index 47ccd91b3a..0000000000 --- a/Task/Fork/Nimrod/fork.nimrod +++ /dev/null @@ -1,11 +0,0 @@ -import posix - -var pid = fork() -if pid < 0: - # error forking a child -elif pid > 0: - # parent, and pid is process id of child -else: - # child - quit() -# further Parent stuff here diff --git a/Task/Fork/OoRexx/fork-1.rexx b/Task/Fork/OoRexx/fork-1.rexx new file mode 100644 index 0000000000..7a076ea864 --- /dev/null +++ b/Task/Fork/OoRexx/fork-1.rexx @@ -0,0 +1,15 @@ +sub=.fork~new +sub~sub +Call syssleep 1 +Do 3 + Say 'program ' time() + Call syssleep 1 + End + +::class fork +:: method sub +Reply +Do 6 + Say 'subroutine' time() + Call syssleep 1 + End diff --git a/Task/Fork/OoRexx/fork-2.rexx b/Task/Fork/OoRexx/fork-2.rexx new file mode 100644 index 0000000000..7ed7993c7f --- /dev/null +++ b/Task/Fork/OoRexx/fork-2.rexx @@ -0,0 +1,15 @@ +sub=.fork~new +sub~start('start_working') + +Call syssleep 1 +Do 3 + Say 'program ' time() + Call syssleep 1 + End + +::class fork +:: method start_working +Do 6 + Say 'subroutine' time() + Call syssleep 1 + End diff --git a/Task/Fork/X86-Assembly/fork.x86 b/Task/Fork/X86-Assembly/fork.x86 index 1b0581857d..f033669db7 100644 --- a/Task/Fork/X86-Assembly/fork.x86 +++ b/Task/Fork/X86-Assembly/fork.x86 @@ -1,32 +1,71 @@ -extern fork -extern printf +; x86_64 linux nasm + +%include "/home/james/Desktop/ASM_LIB/Print.asm" +%include "/home/james/Desktop/ASM_LIB/Sleep.asm" + +section .data + +parent: db "Parent: " +child: db "Child: " +newLine: db 10 section .text - global _start - - _start: - call fork - cmp eax, 0 - je _child - jg _parent - jmp _exit - - _parent: - push p_msg - call printf - jmp _exit - _child: - push c_msg - call printf - jmp _exit - - _exit: - push 0x1 - mov eax, 1 - push eax - int 0x80 - ret - -section .data -c_msg db "Printed from Child process",13,10,0 -p_msg db "Printed from Parent process",13,10,0 + +global _start + +_start: + mov rax, 57 ; fork syscall + syscall + cmp rax, 0 ; if the return value is 0, we're in the child process + je printChild + + printParent: ; else it's the child's PID, we're in the parent + + mov rax, 1 + mov rdi, 1 + mov rsi, parent + mov rdx, 8 + syscall + + mov rax, 39 ; sys_getpid + syscall + mov rdi, rax + call Print_Unsigned + + mov rax, 1 + mov rdi, 1 + mov rsi, newLine + mov rdx, 1 + syscall + + mov rdi, 1 ; sleep so the child process can print befor the parent exits + call Sleep ; you might not see the child output if you don't do this + + jmp exit + + printChild: + + mov rdi, 1 + call Sleep ; sleep and wait for parent to print to screen first + + mov rax, 1 + mov rdi, 1 + mov rsi, child + mov rdx, 7 + syscall + + mov rax, 39 ; sys_getpid + syscall + mov rdi, rax + call Print_Unsigned + + mov rax, 1 + mov rdi, 1 + mov rsi, newLine + mov rdx, 1 + syscall + + exit: + mov rax, 60 + mov rdi, 0 + syscall diff --git a/Task/Fork/Zkl/fork.zkl b/Task/Fork/Zkl/fork.zkl new file mode 100644 index 0000000000..4f4f00c24c --- /dev/null +++ b/Task/Fork/Zkl/fork.zkl @@ -0,0 +1 @@ +zkl: System.cmd("ls &") diff --git a/Task/Formal-power-series/jq/formal-power-series-1.jq b/Task/Formal-power-series/Jq/formal-power-series-1.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-1.jq rename to Task/Formal-power-series/Jq/formal-power-series-1.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-10.jq b/Task/Formal-power-series/Jq/formal-power-series-10.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-10.jq rename to Task/Formal-power-series/Jq/formal-power-series-10.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-11.jq b/Task/Formal-power-series/Jq/formal-power-series-11.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-11.jq rename to Task/Formal-power-series/Jq/formal-power-series-11.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-12.jq b/Task/Formal-power-series/Jq/formal-power-series-12.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-12.jq rename to Task/Formal-power-series/Jq/formal-power-series-12.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-13.jq b/Task/Formal-power-series/Jq/formal-power-series-13.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-13.jq rename to Task/Formal-power-series/Jq/formal-power-series-13.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-14.jq b/Task/Formal-power-series/Jq/formal-power-series-14.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-14.jq rename to Task/Formal-power-series/Jq/formal-power-series-14.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-15.jq b/Task/Formal-power-series/Jq/formal-power-series-15.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-15.jq rename to Task/Formal-power-series/Jq/formal-power-series-15.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-16.jq b/Task/Formal-power-series/Jq/formal-power-series-16.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-16.jq rename to Task/Formal-power-series/Jq/formal-power-series-16.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-17.jq b/Task/Formal-power-series/Jq/formal-power-series-17.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-17.jq rename to Task/Formal-power-series/Jq/formal-power-series-17.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-2.jq b/Task/Formal-power-series/Jq/formal-power-series-2.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-2.jq rename to Task/Formal-power-series/Jq/formal-power-series-2.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-3.jq b/Task/Formal-power-series/Jq/formal-power-series-3.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-3.jq rename to Task/Formal-power-series/Jq/formal-power-series-3.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-4.jq b/Task/Formal-power-series/Jq/formal-power-series-4.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-4.jq rename to Task/Formal-power-series/Jq/formal-power-series-4.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-5.jq b/Task/Formal-power-series/Jq/formal-power-series-5.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-5.jq rename to Task/Formal-power-series/Jq/formal-power-series-5.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-6.jq b/Task/Formal-power-series/Jq/formal-power-series-6.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-6.jq rename to Task/Formal-power-series/Jq/formal-power-series-6.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-7.jq b/Task/Formal-power-series/Jq/formal-power-series-7.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-7.jq rename to Task/Formal-power-series/Jq/formal-power-series-7.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-8.jq b/Task/Formal-power-series/Jq/formal-power-series-8.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-8.jq rename to Task/Formal-power-series/Jq/formal-power-series-8.jq diff --git a/Task/Formal-power-series/jq/formal-power-series-9.jq b/Task/Formal-power-series/Jq/formal-power-series-9.jq similarity index 100% rename from Task/Formal-power-series/jq/formal-power-series-9.jq rename to Task/Formal-power-series/Jq/formal-power-series-9.jq diff --git a/Task/Formal-power-series/Zkl/formal-power-series-1.zkl b/Task/Formal-power-series/Zkl/formal-power-series-1.zkl new file mode 100644 index 0000000000..3f0b60c644 --- /dev/null +++ b/Task/Formal-power-series/Zkl/formal-power-series-1.zkl @@ -0,0 +1,29 @@ +class IPS{ + var [protected] w; // the coefficients of the infinite series + fcn init(w_or_a,b,c,etc){ // IPS(1,2,3) --> (1,2,3,0,0,...) + switch [arglist]{ + case(Walker) { w=w_or_a.tweak(Void,0) } + else { w=vm.arglist.walker().tweak(Void,0) } + } + } + fcn __opAdd(ipf){ //IPS(1,2,3)+IPS(4,5)-->IPS(5,6,3,0,...), returns modified self + switch[arglist]{ + case(1){ addConst(ipf) } // IPS + int/float + else { w=w.zipWith('+,ipf.w) } // IPS + IPS + } + self + } + fcn __opSub(ipf){ w=w.zipWith('-,ipf.w); self } // IPS - IPSHaskell + fcn __opMul(ipf){ } // stub + fcn __opDiv(x){ w.next().toFloat()/x } // *IPS/x, for integtate() + fcn __opNegate { w=w.tweak(Op("--")); self } + // integtate: b0 = 0 by convention, bn = an-1/n + fcn integrate{ w=w.zipWith('/,[1..]).push(0.0); self } + fcn diff { w=w.zipWith('*,[1..]); self } + fcn facts{ (1).walker(*).tweak(fcn(n){ (1).reduce(n,'*,1) }) } // 1!,2!... + fcn walk(n){ w.walk(n) } + fcn value(x,N=15){ ns:=[1..]; w.reduce(N,'wrap(s,an){ s + an*x.pow(ns.next()) }) } + fcn cons(k){ w.push(k); self } //--> k, a0, a1, a2, ... + // addConst(k) --> k + a0, a1, a2, ..., same as k + IPS + fcn addConst(k){ (w.next() + k) : w.push(_); self } +} diff --git a/Task/Formal-power-series/Zkl/formal-power-series-2.zkl b/Task/Formal-power-series/Zkl/formal-power-series-2.zkl new file mode 100644 index 0000000000..ea4c5c8503 --- /dev/null +++ b/Task/Formal-power-series/Zkl/formal-power-series-2.zkl @@ -0,0 +1,2 @@ +(IPS(1,2,3) + IPS(4,5)).walk(5).println(); +(-IPS([1..]) + 11).walk(5).println(); diff --git a/Task/Formal-power-series/Zkl/formal-power-series-3.zkl b/Task/Formal-power-series/Zkl/formal-power-series-3.zkl new file mode 100644 index 0000000000..515ee54392 --- /dev/null +++ b/Task/Formal-power-series/Zkl/formal-power-series-3.zkl @@ -0,0 +1,17 @@ +fcn sine{ // sine Taylor series: 0 + x - x^3/3! + x^5/5! - x^7/7! + x^9/9! - ... + IPS(Utils.Helpers.cycle(1.0, 0.0, -1.0, 0.0).zipWith('/,IPS.facts())) + .cons(0.0) +} +print("Sine Taylor series: "); dostuff(sine,"sin"); + +fcn cosine{ -sine().integrate() + 1.0 } +print("Cosine power series: "); dostuff(cosine,"cos"); + +fcn dostuff(ips,name){ // print series, evaluate at various points + f:='wrap(x,xnm){ v:=ips().value(x); + println("%s(%s) \U2192; %f \U394;=%f".fmt(name,xnm,v,x.Method(name)()-v)); + }; + ips().walk(15).println(); + f(0.0,"0"); f((1.0).pi/4,"\Ubc;\U3c0;"); + f((1.0).pi/2,"\Ubd;\U3c0;"); f((1.0).pi,"\U3c0;"); +} diff --git a/Task/Formatted-numeric-output/BaCon/formatted-numeric-output.bacon b/Task/Formatted-numeric-output/BaCon/formatted-numeric-output.bacon new file mode 100644 index 0000000000..3515d5731f --- /dev/null +++ b/Task/Formatted-numeric-output/BaCon/formatted-numeric-output.bacon @@ -0,0 +1,3 @@ +' Formatted numeric output +n = 7.125 +PRINT n FORMAT "%09.3f\n" diff --git a/Task/Formatted-numeric-output/Bc/formatted-numeric-output-1.bc b/Task/Formatted-numeric-output/Bc/formatted-numeric-output-1.bc new file mode 100644 index 0000000000..8d168e2962 --- /dev/null +++ b/Task/Formatted-numeric-output/Bc/formatted-numeric-output-1.bc @@ -0,0 +1,77 @@ +/* + * Print number n, using at least c characters. + * + * Different from normal, this function: + * 1. Uses the current ibase (not the obase) to print the number. + * 2. Prunes "0" digits from the right, so p(1.500, 1) prints "1.5". + * 3. Pads "0" digits to the left, so p(-1.5, 6) prints "-001.5". + * 4. Never prints a newline. + * + * Use an assignment, as t = p(1.5, 1), to discard the return value + * from this function so that bc not prints the return value. + */ +define p(n, c) { + auto d, d[], f, f[], i, m, r, s, v + s = scale /* Save original scale. */ + + if (n < 0) { + "-" /* Print negative sign. */ + c -= 1 + n = -n /* Remove negative sign from n. */ + } + + /* d[] takes digits before the radix point. */ + scale = 0 + for (m = n / 1; m != 0; m /= 10) d[d++] = m % 10 + + /* f[] takes digits after the radix point. */ + r = n - (n / 1) /* r is these digits. */ + scale = scale(n) + f = -1 /* f counts the digits of r. */ + for (m = r + 1; m != 0; m /= 10) f += 1 + scale = 0 + r = r * (10 ^ f) / 1 /* Remove radix point from r. */ + if (r != 0) { + while (r % 10 == 0) { /* Prune digits. */ + f -= 1 + r /= 10 + } + for (i = 0; i < f; i++) { + f[i] = r % 10 + r /= 10 + } + } + + /* Pad "0" digits to reach c characters. */ + c -= d + if (f > 0) c -= 1 + f + for (1; c > 0; c--) "0" /* Print "0". */ + + /* i = index, m = maximum index, r = digit to print. */ + m = d + f + for (i = 1; i <= m; i++) { + if (i <= d) r = d[d - i] + if (i > d) r = f[m - i] + if (i == d + 1) "." /* Print radix point. */ + + v = 0 + if (r == v++) "0" /* Print digit. */ + if (r == v++) "1" + if (r == v++) "2" /* r == 2 might not work, */ + if (r == v++) "3" /* unless ibase is ten. */ + if (r == v++) "4" + if (r == v++) "5" + if (r == v++) "6" + if (r == v++) "7" + if (r == v++) "8" + if (r == v++) "9" + if (r == v++) "A" + if (r == v++) "B" + if (r == v++) "C" + if (r == v++) "D" + if (r == v++) "E" + if (r == v++) "F" + } + + scale = s /* Restore original scale. */ +} diff --git a/Task/Formatted-numeric-output/Bc/formatted-numeric-output-2.bc b/Task/Formatted-numeric-output/Bc/formatted-numeric-output-2.bc new file mode 100644 index 0000000000..270f5e4e93 --- /dev/null +++ b/Task/Formatted-numeric-output/Bc/formatted-numeric-output-2.bc @@ -0,0 +1,10 @@ +x = 7.125 +"Decimal: "; t = p(x, 9); " +" +ibase = 16 +"Hexadecimal: "; t = p(x, 9); " +" +ibase = 2 +"Binary: "; t = p(x, 1001); " +" +quit diff --git a/Task/Formatted-numeric-output/Dc/formatted-numeric-output-1.dc b/Task/Formatted-numeric-output/Dc/formatted-numeric-output-1.dc new file mode 100644 index 0000000000..6f28818258 --- /dev/null +++ b/Task/Formatted-numeric-output/Dc/formatted-numeric-output-1.dc @@ -0,0 +1,112 @@ +[* + * (n) (c) lpx + * Print number n, using at least c characters. + * + * Different from normal, this function: + * 1. Uses the current ibase (not the obase) to print the number. + * 2. Prunes "0" digits from the right, so [1.500 1 lxp] prints "1.5". + * 3. Pads "0" digits to the left, so [_1.5 6 lxp] prints "-001.5". + * 4. Never prints a newline. + *]sz +[ + Sc Sn [Local n, c = from stack.]sz + K Ss [Local s = original scale.]sz + [Reserve local variables D, F, I, L.]sz + 0 SD 0 SF 0 SI 0 SL + + [ [If n < 0:]sz + [-]P [Print negative sign.]sz + lc 1 - sc [Decrement c.]sz + 0 ln - sn [Negate n.]sz + ]sI 0 ln 0:]sz + 1 lf + - [Subtract 1 radix point + f from count.]sz + ]sI 0 lf >I + [ [Loop:]sz + [0]P [Print a padding "0".]sz + 1 - [Decrement count.]sz + d 0 0.]sz + ]sL d 0 0.]sz + ]sL d 0 0:]sz + [.]P [Print radix point.]sz + lf [Push counter = f.]sz + [ [Loop:]sz + 1 - [Decrement counter.]sz + d ;F lPx [Print digit F[counter].]sz + d 0 0.]sz + ]sL d 0 I + + [Restore variables n, c, d, f, D, F, L, I, P.]sz + Lnsz Lcsz Ldsz Lfsz LDsz LFsz LLsz LIsz LPsz + Ls k [Restore variable s. Restore original scale.]sz +]sp diff --git a/Task/Formatted-numeric-output/Dc/formatted-numeric-output-2.dc b/Task/Formatted-numeric-output/Dc/formatted-numeric-output-2.dc new file mode 100644 index 0000000000..7100801912 --- /dev/null +++ b/Task/Formatted-numeric-output/Dc/formatted-numeric-output-2.dc @@ -0,0 +1,5 @@ +7.125 sx +[Decimal: ]P lx 9 lpx [ +]P 16 i [Hexadecimal: ]P lx 9 lpx [ +]P 2 i [Binary: ]P lx 9 lpx [ +]P diff --git a/Task/Formatted-numeric-output/Gambas/formatted-numeric-output.gambas b/Task/Formatted-numeric-output/Gambas/formatted-numeric-output.gambas new file mode 100644 index 0000000000..83d0519a99 --- /dev/null +++ b/Task/Formatted-numeric-output/Gambas/formatted-numeric-output.gambas @@ -0,0 +1,5 @@ +Public Sub Main() + +Print Format("7.125", "00000.000") + +End diff --git a/Task/Formatted-numeric-output/Gnuplot/formatted-numeric-output.gnuplot b/Task/Formatted-numeric-output/Gnuplot/formatted-numeric-output.gnuplot new file mode 100644 index 0000000000..cf4ac23cdf --- /dev/null +++ b/Task/Formatted-numeric-output/Gnuplot/formatted-numeric-output.gnuplot @@ -0,0 +1 @@ +print sprintf("%09.3f", 7.125) diff --git a/Task/Formatted-numeric-output/jq/formatted-numeric-output-1.jq b/Task/Formatted-numeric-output/Jq/formatted-numeric-output-1.jq similarity index 100% rename from Task/Formatted-numeric-output/jq/formatted-numeric-output-1.jq rename to Task/Formatted-numeric-output/Jq/formatted-numeric-output-1.jq diff --git a/Task/Formatted-numeric-output/jq/formatted-numeric-output-2.jq b/Task/Formatted-numeric-output/Jq/formatted-numeric-output-2.jq similarity index 100% rename from Task/Formatted-numeric-output/jq/formatted-numeric-output-2.jq rename to Task/Formatted-numeric-output/Jq/formatted-numeric-output-2.jq diff --git a/Task/Formatted-numeric-output/jq/formatted-numeric-output-3.jq b/Task/Formatted-numeric-output/Jq/formatted-numeric-output-3.jq similarity index 100% rename from Task/Formatted-numeric-output/jq/formatted-numeric-output-3.jq rename to Task/Formatted-numeric-output/Jq/formatted-numeric-output-3.jq diff --git a/Task/Formatted-numeric-output/jq/formatted-numeric-output-4.jq b/Task/Formatted-numeric-output/Jq/formatted-numeric-output-4.jq similarity index 100% rename from Task/Formatted-numeric-output/jq/formatted-numeric-output-4.jq rename to Task/Formatted-numeric-output/Jq/formatted-numeric-output-4.jq diff --git a/Task/Formatted-numeric-output/jq/formatted-numeric-output-5.jq b/Task/Formatted-numeric-output/Jq/formatted-numeric-output-5.jq similarity index 100% rename from Task/Formatted-numeric-output/jq/formatted-numeric-output-5.jq rename to Task/Formatted-numeric-output/Jq/formatted-numeric-output-5.jq diff --git a/Task/Formatted-numeric-output/Kotlin/formatted-numeric-output.kotlin b/Task/Formatted-numeric-output/Kotlin/formatted-numeric-output.kotlin new file mode 100644 index 0000000000..b847e6ce43 --- /dev/null +++ b/Task/Formatted-numeric-output/Kotlin/formatted-numeric-output.kotlin @@ -0,0 +1,6 @@ +// version 1.0.5-2 + +fun main(args: Array) { + val num = 7.125 + println("%09.3f".format(num)) +} diff --git a/Task/Formatted-numeric-output/Stata/formatted-numeric-output.stata b/Task/Formatted-numeric-output/Stata/formatted-numeric-output.stata new file mode 100644 index 0000000000..e39e458c83 --- /dev/null +++ b/Task/Formatted-numeric-output/Stata/formatted-numeric-output.stata @@ -0,0 +1,2 @@ +. display %010.3f (57/8) +000007.125 diff --git a/Task/Formatted-numeric-output/Zkl/formatted-numeric-output.zkl b/Task/Formatted-numeric-output/Zkl/formatted-numeric-output.zkl new file mode 100644 index 0000000000..32ed39cdff --- /dev/null +++ b/Task/Formatted-numeric-output/Zkl/formatted-numeric-output.zkl @@ -0,0 +1,5 @@ +"%09.3f".fmt(7.125) //-->"00007.125" +"%09.3e".fmt(7.125) //-->"7.125e+00" +"%09.3g".fmt(7.125) //-->"000007.12" +"%09d".fmt(7.125) //-->"000000007" +"%09,d".fmt(78901.125)//-->"00078,901" diff --git a/Task/Forward-difference/AppleScript/forward-difference.applescript b/Task/Forward-difference/AppleScript/forward-difference.applescript new file mode 100644 index 0000000000..64cd1bf4e5 --- /dev/null +++ b/Task/Forward-difference/AppleScript/forward-difference.applescript @@ -0,0 +1,138 @@ +-- FORWARD DIFFERENCE -------------------------------------------------------- + +-- forwardDifference :: Int -> [Int] -> [Int] +on forwardDifference(n, xs) + set lng to length of xs + + -- atLength :: [Int] -> Bool + script atLength + property fullLength : lng + property ndx : n + + on |λ|(ds) + (atLength's fullLength) - (length of ds) ≥ atLength's ndx + end |λ| + end script + + -- fd :: [Int] -> [Int] + script fd + on |λ|(xs) + script minus + on |λ|(a, b) + a - b + end |λ| + end script + + zipWith(minus, tail(xs), xs) + end |λ| + end script + + |until|(atLength, fd, xs) +end forwardDifference + + +-- TEST ---------------------------------------------------------------------- +on run + set xs to {90, 47, 58, 29, 22, 32, 55, 5, 55, 73} + + script test + on |λ|(n) + intercalate(" -> [", ¬ + {{n}} & intercalate(", ", forwardDifference(n, xs))) & "]" + end |λ| + end script + + intercalate(linefeed, map(test, enumFromTo(1, 9))) +end run + + +-- GENERIC FUNCTIONS --------------------------------------------------------- + +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo + +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- min :: Ord a => a -> a -> a +on min(x, y) + if y < x then + y + else + x + end if +end min + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- tail :: [a] -> [a] +on tail(xs) + if length of xs > 1 then + items 2 thru -1 of xs + else + {} + end if +end tail + +-- until :: (a -> Bool) -> (a -> a) -> a -> a +on |until|(p, f, x) + set mp to mReturn(p) + set v to x + + tell mReturn(f) + repeat until mp's |λ|(v) + set v to |λ|(v) + end repeat + end tell + return v +end |until| + +-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] +on zipWith(f, xs, ys) + set lng to min(length of xs, length of ys) + set lst to {} + tell mReturn(f) + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, item i of ys) + end repeat + return lst + end tell +end zipWith diff --git a/Task/Forward-difference/HicEst/forward-difference-1.hicest b/Task/Forward-difference/HicEst/forward-difference-1.hicest deleted file mode 100644 index 83e9a5903e..0000000000 --- a/Task/Forward-difference/HicEst/forward-difference-1.hicest +++ /dev/null @@ -1,12 +0,0 @@ -REAL :: n=10, list(n) - -list = ( 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 ) -WRITE(Format='i1, (i6)') 0, list - -DO i = 1, n-1 - ALIAS(list,1, diff,n-i) ! rename list(1 ... n-i) with diff - diff = list($+1) - diff ! $ is the running left hand array index - WRITE(Format='i1, (i6)') i, diff -ENDDO - -END diff --git a/Task/Forward-difference/HicEst/forward-difference-2.hicest b/Task/Forward-difference/HicEst/forward-difference-2.hicest deleted file mode 100644 index eb2eefc020..0000000000 --- a/Task/Forward-difference/HicEst/forward-difference-2.hicest +++ /dev/null @@ -1,10 +0,0 @@ -0 90 47 58 29 22 32 55 5 55 73 -1 -43 11 -29 -7 10 23 -50 50 18 -2 54 -40 22 17 13 -73 100 -32 -3 -94 62 -5 -4 -86 173 -132 -4 156 -67 1 -82 259 -305 -5 -223 68 -83 341 -564 -6 291 -151 424 -905 -7 -442 575 -1329 -8 1017 -1904 -9 -2921 diff --git a/Task/Forward-difference/JavaScript/forward-difference.js b/Task/Forward-difference/JavaScript/forward-difference.js new file mode 100644 index 0000000000..bbb3eaa8bc --- /dev/null +++ b/Task/Forward-difference/JavaScript/forward-difference.js @@ -0,0 +1,57 @@ +(() => { + 'use strict'; + + // forwardDifference :: [Int] -> [Int] + const forwardDifference = (n, xs) => { + const fd = xs => zipWith((a, b) => a - b, tail(xs), xs); + return until( + m => m.index < 1, + m => ({ + index: m.index - 1, + list: fd(m.list) + }), { + index: n, + list: xs + } + ) + .list; + }; + + + // GENERIC FUNCTIONS --------------------------------------- + + // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] + const zipWith = (f, xs, ys) => { + const ny = ys.length; + return (xs.length <= ny ? xs : xs.slice(0, ny)) + .map((x, i) => f(x, ys[i])); + }; + + // until :: (a -> Bool) -> (a -> a) -> a -> a + const until = (p, f, x) => { + const go = x => p(x) ? x : go(f(x)); + return go(x); + }; + + // tail :: [a] -> [a] + const tail = xs => xs.length ? xs.slice(1) : undefined; + + + // TEST ---------------------------------------------------- + + // range :: Int -> Int -> [Int] + const range = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // show :: a -> String + const show = x => JSON.stringify(x); + + // Sample + const test = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]; + + return range(1, 9) + .map(x => `${x} ${show(forwardDifference(x, test))}`) + .join('\n'); +})(); diff --git a/Task/Forward-difference/jq/forward-difference-1.jq b/Task/Forward-difference/Jq/forward-difference-1.jq similarity index 100% rename from Task/Forward-difference/jq/forward-difference-1.jq rename to Task/Forward-difference/Jq/forward-difference-1.jq diff --git a/Task/Forward-difference/jq/forward-difference-2.jq b/Task/Forward-difference/Jq/forward-difference-2.jq similarity index 100% rename from Task/Forward-difference/jq/forward-difference-2.jq rename to Task/Forward-difference/Jq/forward-difference-2.jq diff --git a/Task/Forward-difference/jq/forward-difference-3.jq b/Task/Forward-difference/Jq/forward-difference-3.jq similarity index 100% rename from Task/Forward-difference/jq/forward-difference-3.jq rename to Task/Forward-difference/Jq/forward-difference-3.jq diff --git a/Task/Forward-difference/Julia/forward-difference-1.julia b/Task/Forward-difference/Julia/forward-difference-1.julia deleted file mode 100644 index 18d19000f9..0000000000 --- a/Task/Forward-difference/Julia/forward-difference-1.julia +++ /dev/null @@ -1 +0,0 @@ -ndiff(A, n::Integer) = n < 1 ? A : diff(ndiff(A, n-1)) diff --git a/Task/Forward-difference/Julia/forward-difference-2.julia b/Task/Forward-difference/Julia/forward-difference-2.julia deleted file mode 100644 index 961e8531df..0000000000 --- a/Task/Forward-difference/Julia/forward-difference-2.julia +++ /dev/null @@ -1,13 +0,0 @@ -julia> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] -julia> [ndiff(s, i) for i in 0:9] -10-element Array{Any,1}: - [90,47,58,29,22,32,55,5,55,73] - [-43,11,-29,-7,10,23,-50,50,18] - [54,-40,22,17,13,-73,100,-32] - [-94,62,-5,-4,-86,173,-132] - [156,-67,1,-82,259,-305] - [-223,68,-83,341,-564] - [291,-151,424,-905] - [-442,575,-1329] - [1017,-1904] - [-2921] diff --git a/Task/Forward-difference/Kotlin/forward-difference.kotlin b/Task/Forward-difference/Kotlin/forward-difference.kotlin new file mode 100644 index 0000000000..e7d48d5ef4 --- /dev/null +++ b/Task/Forward-difference/Kotlin/forward-difference.kotlin @@ -0,0 +1,36 @@ +// version 1.1.2 + +fun forwardDifference(ia: IntArray, order: Int): IntArray { + if (order < 0) throw IllegalArgumentException("Order must be non-negative") + if (order == 0) return ia + val size = ia.size + if (size == 0) return ia // same empty array + if (order >= size) return intArrayOf() // new empty array + var old = ia + var new = old + var count = order + while (count-- >= 1) { + new = IntArray(old.size - 1) + for (i in 0 until new.size) new[i] = old[i + 1] - old[i] + old = new + } + return new +} + +fun printArray(ia: IntArray) { + print("[") + for (i in 0 until ia.size) { + print("%5d".format(ia[i])) + if (i < ia .size - 1) print(", ") + } + println("]") +} + +fun main(args: Array) { + val ia = intArrayOf(90, 47, 58, 29, 22, 32, 55, 5, 55, 73) + for (order in 0..ia.size) { + val fd = forwardDifference(ia, order) + print("%2d".format(order) + ": ") + printArray(fd) + } +} diff --git a/Task/Forward-difference/MATLAB/forward-difference-1.m b/Task/Forward-difference/MATLAB/forward-difference-1.m deleted file mode 100644 index e0126dd9c9..0000000000 --- a/Task/Forward-difference/MATLAB/forward-difference-1.m +++ /dev/null @@ -1 +0,0 @@ -Y = diff(X,n); diff --git a/Task/Forward-difference/MATLAB/forward-difference-2.m b/Task/Forward-difference/MATLAB/forward-difference-2.m deleted file mode 100644 index 71ea9d133a..0000000000 --- a/Task/Forward-difference/MATLAB/forward-difference-2.m +++ /dev/null @@ -1,5 +0,0 @@ -diff([1 2 3 4 5]) - -ans = - - 1 1 1 1 diff --git a/Task/Forward-difference/Phix/forward-difference.phix b/Task/Forward-difference/Phix/forward-difference.phix new file mode 100644 index 0000000000..693b1588e9 --- /dev/null +++ b/Task/Forward-difference/Phix/forward-difference.phix @@ -0,0 +1,15 @@ +function fwd_diff_n(sequence s, integer order) + if order>=length(s) then ?9/0 end if + 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 + +constant s = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73} +for i=1 to 9 do + ?fwd_diff_n(s,i) +end for diff --git a/Task/Forward-difference/SQL/forward-difference.sql b/Task/Forward-difference/SQL/forward-difference.sql index 213fa634e5..d63aaddf1a 100644 --- a/Task/Forward-difference/SQL/forward-difference.sql +++ b/Task/Forward-difference/SQL/forward-difference.sql @@ -1,37 +1,37 @@ -create table list (n integer, v real); -insert into list values (0, 90); -insert into list values (1, 47); -insert into list values (2, 58); -insert into list values (3, 29); -insert into list values (4, 22); -insert into list values (5, 32); -insert into list values (6, 55); -insert into list values (7, 5); -insert into list values (8, 55); -insert into list values (9, 73); - -create view diff1 as select list.n, (select next.v from list as next where next.n = list.n + 1) - list.v as v from list; -create view diff2 as select list.n, (select next.v from diff1 as next where next.n = list.n + 1) - list.v as v from diff1 as list; - -select * from diff1; - 0|-43.0 - 1|11.0 - 2|-29.0 - 3|-7.0 - 4|10.0 - 5|23.0 - 6|-50.0 - 7|50.0 - 8|18.0 - 9| -select * from diff2; - 0|54.0 - 1|-40.0 - 2|22.0 - 3|17.0 - 4|13.0 - 5|-73.0 - 6|100.0 - 7|-32.0 - 8| - 9| +WITH RECURSIVE +T0 (N, ITEM, LIST, NEW_LIST) AS +( + SELECT 1, + NULL, + '90,47,58,29,22,32,55,5,55,73' || ',', + NULL + UNION ALL + SELECT CASE + WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) = '' + THEN N + 1 + ELSE N + END, + CASE + WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) <> '' + THEN SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) + ELSE NULL + END, + CASE + WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) = '' + THEN IFNULL(NEW_LIST || (SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) - ITEM) || ',', '') + ELSE SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) + END, + CASE + WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) <> '' + THEN IFNULL(NEW_LIST, '') || IFNULL((SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) - ITEM) || ',', '') + ELSE NULL + END + FROM T0 + WHERE INSTR(LIST, ',') > 0 +) +SELECT N, + TRIM(LIST, ',') LIST + FROM T0 + WHERE NEW_LIST IS NULL + AND LIST <> '' + ORDER BY N; diff --git a/Task/Forward-difference/SequenceL/forward-difference-1.sequencel b/Task/Forward-difference/SequenceL/forward-difference-1.sequencel new file mode 100644 index 0000000000..5d66d3e04b --- /dev/null +++ b/Task/Forward-difference/SequenceL/forward-difference-1.sequencel @@ -0,0 +1,8 @@ +forwardDifference(x(1), n) := forwardDifferenceHelper(x, n, [x]); + +forwardDifferenceHelper(x(1), n, result(2)) := + let + difference := tail(x) - x[1 ... size(x) - 1]; + in + result when n = 0 or size(x) = 1 else + forwardDifferenceHelper(difference, n - 1, result ++ [difference]); diff --git a/Task/Forward-difference/SequenceL/forward-difference-2.sequencel b/Task/Forward-difference/SequenceL/forward-difference-2.sequencel new file mode 100644 index 0000000000..a2f72e59b6 --- /dev/null +++ b/Task/Forward-difference/SequenceL/forward-difference-2.sequencel @@ -0,0 +1,3 @@ +forwardDifference(x(1),n) := + x when n = 0 or size(x) = 1 else + forwardDifference(tail(x) - x[1 ... size(x) - 1], n - 1); diff --git a/Task/Forward-difference/Sidef/forward-difference.sidef b/Task/Forward-difference/Sidef/forward-difference.sidef index 5850872e23..e54fd66b26 100644 --- a/Task/Forward-difference/Sidef/forward-difference.sidef +++ b/Task/Forward-difference/Sidef/forward-difference.sidef @@ -1,15 +1,15 @@ func dif(arr) { gather { - range(0, arr.end-1).each { |i| - take(arr[i+1] - arr[i]); + for i (0 ..^ arr.end) { + take(arr[i+1] - arr[i]) } } } func difn(n, arr) { - n.times { arr = dif(arr) }; - arr; + { arr = dif(arr) } * n + arr } -say dif([1, 23, 45, 678]); # => [22, 22, 633] -say difn(2, [1, 23, 45, 678]); # => [0, 611] +say dif([1, 23, 45, 678]) # => [22, 22, 633] +say difn(2, [1, 23, 45, 678]) # => [0, 611] diff --git a/Task/Forward-difference/Stata/forward-difference-1.stata b/Task/Forward-difference/Stata/forward-difference-1.stata new file mode 100644 index 0000000000..e2be8fcbf4 --- /dev/null +++ b/Task/Forward-difference/Stata/forward-difference-1.stata @@ -0,0 +1 @@ +gen y=x[_n+1]-x[_n] diff --git a/Task/Forward-difference/Stata/forward-difference-2.stata b/Task/Forward-difference/Stata/forward-difference-2.stata new file mode 100644 index 0000000000..9574ca1299 --- /dev/null +++ b/Task/Forward-difference/Stata/forward-difference-2.stata @@ -0,0 +1,10 @@ +* First create a dataset +clear all +set obs 100 +gen i=_n +tsset i +gen x=rnormal() + +* Differences +display "Difference order?" _request(k) +gen y=D${k}F${k}.x diff --git a/Task/Forward-difference/Zkl/forward-difference-1.zkl b/Task/Forward-difference/Zkl/forward-difference-1.zkl new file mode 100644 index 0000000000..e53e05a900 --- /dev/null +++ b/Task/Forward-difference/Zkl/forward-difference-1.zkl @@ -0,0 +1,10 @@ +fcn forwardDiff(lst){ + if(lst.len()<2) + return(T); + return(T(lst[1]-lst[0]).extend(forwardDiff(lst[1,*]))) +} +fcn nthForwardDiff(n,xs){ + if(n==0) + return(xs); + return(nthForwardDiff(n-1,forwardDiff(xs))) // tail recursion +} diff --git a/Task/Forward-difference/Zkl/forward-difference-2.zkl b/Task/Forward-difference/Zkl/forward-difference-2.zkl new file mode 100644 index 0000000000..561a6f04a1 --- /dev/null +++ b/Task/Forward-difference/Zkl/forward-difference-2.zkl @@ -0,0 +1 @@ +nthForwardDiff(9,T(90, 47, 58, 29, 22, 32, 55, 5, 55, 73)).println(); diff --git a/Task/Four-bit-adder/AutoIt/four-bit-adder-3.autoit b/Task/Four-bit-adder/AutoIt/four-bit-adder-3.autoit deleted file mode 100644 index 8c9439ea15..0000000000 --- a/Task/Four-bit-adder/AutoIt/four-bit-adder-3.autoit +++ /dev/null @@ -1,2 +0,0 @@ -result: 1010 ==> carry out: 0 -result: 0011 ==> carry out: 1 diff --git a/Task/Four-bit-adder/Batch-File/four-bit-adder.bat b/Task/Four-bit-adder/Batch-File/four-bit-adder.bat new file mode 100644 index 0000000000..6171f6cf90 --- /dev/null +++ b/Task/Four-bit-adder/Batch-File/four-bit-adder.bat @@ -0,0 +1,136 @@ +@echo off +setlocal enabledelayedexpansion + +:: ":main" is where all the non-logic-gate stuff happens +:main +:: User input two 4-digit binary numbers +:: There is no error checking for these numbers, however if the first 4 digits of both inputs are in binary... +:: The program will use them. All non-binary numbers are treated as 0s, but having less than 4 digits will crash it +set /p "input1=First 4-Bit Binary Number: " +set /p "input2=Second 4-Bit Binary Number: " + +:: Put the first 4 digits of the binary numbers and separate them into "A[]" for input A and "B[]" for input B +for /l %%i in (0,1,3) do ( + set A%%i=!input1:~%%i,1! + set B%%i=!input2:~%%i,1! +) + +:: Run the 4-bit Adder with "A[]" and "B[]" as parameters. The program supports a 9th parameter for a Carry input +call:_4bitAdder %A3% %A2% %A1% %A0% %B3% %B2% %B1% %B0% 0 + +:: Display the answer and exit +echo %input1% + %input2% = %outputC%%outputS4%%outputS3%%outputS2%%outputS1% +pause>nul +exit /b + +:: Function for the 4-bit Adder following the logic given +:_4bitAdder +set inputA1=%1 +set inputA2=%2 +set inputA3=%3 +set inputA4=%4 + +set inputB1=%5 +set inputB2=%6 +set inputB3=%7 +set inputB4=%8 + +set inputC=%9 + +call:_FullAdder %inputA1% %inputB1% %inputC% +set outputS1=%outputS% +set inputC=%outputC% + +call:_FullAdder %inputA2% %inputB2% %inputC% +set outputS2=%outputS% +set inputC=%outputC% + +call:_FullAdder %inputA3% %inputB3% %inputC% +set outputS3=%outputS% +set inputC=%outputC% + +call:_FullAdder %inputA4% %inputB4% %inputC% +set outputS4=%outputS% +set inputC=%outputC% + +:: In order return more than one number (of which is usually done via 'exit /b') we declare them while ending the local environment +endlocal && set "outputS1=%outputS1%" && set "outputS2=%outputS2%" && set "outputS3=%outputS3%" && set "outputS4=%outputS4%" && set "outputC=%inputC%" +exit /b + +:: Function for the 1-bit Adder following the logic given +:_FullAdder +setlocal +set inputA=%1 +set inputB=%2 +set inputC1=%3 + +call:_halfAdder %inputA% %inputB% +set inputA1=%outputS% +set inputA2=%inputA1% +set inputC2=%outputC% + +call:_HalfAdder %inputA1% %inputC1% +set outputS=%outputS% +set inputC1=%outputC% + +call:_Or %inputC1% %inputC2% +set outputC=%errorlevel% + +endlocal && set "outputS=%outputS%" && set "outputC=%outputC%" +exit /b + +:: Function for the half-bit adder following the logic given +:_halfAdder +setlocal +set inputA1=%1 +set inputA2=%inputA1% +set inputB1=%2 +set inputB2=%inputB1% + +call:_XOr %inputA1% %inputB2% +set outputS=%errorlevel% + +call:_And %inputA2% %inputB2% +set outputC=%errorlevel% + +endlocal && set "outputS=%outputS%" && set "outputC=%outputC%" +exit /b + +:: Function for the XOR-gate following the logic given +:_XOr +setlocal +set inputA1=%1 +set inputB1=%2 + +call:_Not %inputA1% +set inputA2=%errorlevel% + +call:_Not %inputB1% +set inputB2=%errorlevel% + +call:_And %inputA1% %inputB2% +set inputA=%errorlevel% + +call:_And %inputA2% %inputB1% +set inputB=%errorlevel% + +call:_Or %inputA% %inputB% +set outputA=%errorlevel% + +:: As there is only one output, we can use 'exit /b {errorlevel}' to return a specified errorlevel +exit /b %outputA% + +:: The basic 3 logic gates that every other funtion is composed of +:_Not +setlocal +if %1==0 exit /b 1 +exit /b 0 +:_Or +setlocal +if %1==1 exit /b 1 +if %2==1 exit /b 1 +exit /b 0 +:_And +setlocal +if %1==1 if %2==1 exit /b 1 +exit /b 0 diff --git a/Task/Four-bit-adder/Clojure/four-bit-adder-3.clj b/Task/Four-bit-adder/Clojure/four-bit-adder-3.clj new file mode 100644 index 0000000000..74f104b42f --- /dev/null +++ b/Task/Four-bit-adder/Clojure/four-bit-adder-3.clj @@ -0,0 +1,33 @@ +(defn to-binary-seq [^long x] + (map #(- (int %) (int \0)) + (Long/toBinaryString x))) + +(defn half-adder [a b] + [(bit-xor a b) + (bit-and a b)]) + +(defn full-adder [a b carry] + (let [added (half-adder b carry) + half-sum (first added)] + [(first (half-adder a half-sum)) + (bit-or (second (half-adder a half-sum)) (second added))])) + +(defn ripple-carry-adder [a b] + (loop [a (reverse a) + b (reverse b) + sum '() + carry 0] + (let [added (full-adder (first a) (first b) carry)] + (if (and (empty? (next a)) (empty? (next b))) + (conj sum (first added) (bit-or carry 1)) + (recur (next a) (next b) (conj sum (first added)) (second added)))))) + +(deftest adder + (is (= (Long/parseLong (apply str (ripple-carry-adder (to-binary-seq 10) (to-binary-seq 10))) 2) + (+ 10 10))) + (is (= (Long/parseLong (apply str (ripple-carry-adder (to-binary-seq 50) (to-binary-seq 50))) 2) + (+ 50 50))) + (is (= (Long/parseLong (apply str (ripple-carry-adder (to-binary-seq 32) (to-binary-seq 38))) 2) + (+ 32 38))) + (is (= (Long/parseLong (apply str (ripple-carry-adder (to-binary-seq 130) (to-binary-seq 250))) 2) + (+ 130 250)))) diff --git a/Task/Four-bit-adder/Common-Lisp/four-bit-adder.lisp b/Task/Four-bit-adder/Common-Lisp/four-bit-adder.lisp new file mode 100644 index 0000000000..836d0a9d6d --- /dev/null +++ b/Task/Four-bit-adder/Common-Lisp/four-bit-adder.lisp @@ -0,0 +1,32 @@ +;; returns a list of bits: '(sum carry) +(defun half-adder (a b) + (list (logxor a b) (logand a b))) + +;; returns a list of bits: '(sum, carry) +(defun full-adder (a b c-in) + (let* + ((h1 (half-adder c-in a)) + (h2 (half-adder (first h1) b))) + (list (first h2) (logior (second h1) (second h2))))) + +;; a and b are lists of 4 bits each +(defun 4-bit-adder (a b) + (let* + ((add-1 (full-adder (fourth a) (fourth b) 0)) + (add-2 (full-adder (third a) (third b) (second add-1))) + (add-3 (full-adder (second a) (second b) (second add-2))) + (add-4 (full-adder (first a) (first b) (second add-3)))) + (list + (list (first add-4) (first add-3) (first add-2) (first add-1)) + (second add-4)))) + +(defun main () + (print (4-bit-adder (list 0 0 0 0) (list 0 0 0 0))) ;; '(0 0 0 0) and 0 + (print (4-bit-adder (list 0 0 0 0) (list 1 1 1 1))) ;; '(1 1 1 1) and 0 + (print (4-bit-adder (list 1 1 1 1) (list 0 0 0 0))) ;; '(1 1 1 1) and 0 + (print (4-bit-adder (list 0 1 0 1) (list 1 1 0 0))) ;; '(0 0 0 1) and 1 + (print (4-bit-adder (list 1 1 1 1) (list 1 1 1 1))) ;; '(1 1 1 0) and 1 + (print (4-bit-adder (list 1 0 1 0) (list 0 1 0 1))) ;; '(1 1 1 1) and 0 + ) + +(main) diff --git a/Task/Four-bit-adder/Icon/four-bit-adder.icon b/Task/Four-bit-adder/Icon/four-bit-adder.icon new file mode 100644 index 0000000000..3240b8207b --- /dev/null +++ b/Task/Four-bit-adder/Icon/four-bit-adder.icon @@ -0,0 +1,103 @@ +# +# 4bitadder.icn, emulate a 4 bit adder. Using only and, or, not +# +record carry(c) + +# +# excercise the adder, either "test" or 2 numbers +# +procedure main(argv) + c := carry(0) + + # cli test + if map(\argv[1]) == "test" then { + # Unicon allows explicit radix literals + every i := (2r0000 | 2r1001 | 2r1111) do { + write(i, "+0,3,9,15") + every j := (0 | 3 | 9 | 15) do { + ans := fourbitadder(t1 := fourbits(i), t2 := fourbits(j), c) + write(t1, " + ", t2, " = ", c.c, ":", ans) + } + } + return + } + # command line, two values, if given, first try four bit binaries + cli := fourbitadder(t1 := (*\argv[1] = 4 & fourbits("2r" || argv[1])), + t2 := (*\argv[2] = 4 & fourbits("2r" || argv[2])), c) + write(t1, " + ", t2, " = ", c.c, ":", \cli) & return + + # if no result for that, try decimal values + cli := fourbitadder(t1 := fourbits(\argv[1]), + t2 := fourbits(\argv[2]), c) + write(t1, " + ", t2, " = ", c.c, ":", \cli) & return + + # or display the help + write("Usage: 4bitadder [\"test\"] | [bbbb bbbb] | [n n], range 0-15") +end + +# +# integer to fourbits as string +# +procedure fourbits(i) + local s, t + if not numeric(i) then fail + if not (0 <= integer(i) < 16) then { + write("out of range: ", i) + fail + } + s := "" + every t := (8 | 4 | 2 | 1) do { + s ||:= if iand(i, t) ~= 0 then "1" else "0" + } + return s +end + +# +# low level xor emulation with or, and, not +# +procedure xor(a, b) + return ior(iand(a, icom(b)), iand(b, icom(a))) +end + +# +# half adder, and into carry, xor for result bit +# +procedure halfadder(a, b, carry) + carry.c := iand(a,b) + return xor(a,b) +end + +# +# full adder, two half adders, or for carry +# +procedure fulladder(a, b, c0, c1) + local c2, c3, r + c2 := carry(0) + c3 := carry(0) + + # connect two half adders with carry + r := halfadder(halfadder(c0.c, a, c2), b, c3) + c1.c := ior(c2.c, c3.c) + return r +end + +# +# fourbit adder, as bit string +# +procedure fourbitadder(a, b, cr) + local cs, c0, c1, c2, s + cs := carry(0) + c0 := carry(0) + c1 := carry(0) + c2 := carry(0) + + # create a string for subscripting. strings are immutable, new strings created + s := "0000" + # bit 0 is string position 4 + s[4+:1] := fulladder(a[4+:1], b[4+:1], cs, c0) + s[3+:1] := fulladder(a[3+:1], b[3+:1], c0, c1) + s[2+:1] := fulladder(a[2+:1], b[2+:1], c1, c2) + s[1+:1] := fulladder(a[1+:1], b[1+:1], c2, cr) + # cr.c is the overflow carry + return s +end diff --git a/Task/Four-bit-adder/jq/four-bit-adder-1.jq b/Task/Four-bit-adder/Jq/four-bit-adder-1.jq similarity index 100% rename from Task/Four-bit-adder/jq/four-bit-adder-1.jq rename to Task/Four-bit-adder/Jq/four-bit-adder-1.jq diff --git a/Task/Four-bit-adder/jq/four-bit-adder-2.jq b/Task/Four-bit-adder/Jq/four-bit-adder-2.jq similarity index 100% rename from Task/Four-bit-adder/jq/four-bit-adder-2.jq rename to Task/Four-bit-adder/Jq/four-bit-adder-2.jq diff --git a/Task/Four-bit-adder/Phix/four-bit-adder.phix b/Task/Four-bit-adder/Phix/four-bit-adder.phix new file mode 100644 index 0000000000..ad30e51697 --- /dev/null +++ b/Task/Four-bit-adder/Phix/four-bit-adder.phix @@ -0,0 +1,47 @@ +function xor_gate(bool a, bool b) + return (a and not b) or (not a and b) +end function + +function half_adder(bool a, bool b) + bool s = xor_gate(a,b) + bool 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) + bool {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) + bool {b0,b1,b2,b3} = int_to_bits(b,4) + bool {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}) + printf(1,"%04b + %04b = %04b %b (%d+%d=%d)\n",{a,b,r,c,a,b,c*16+r}) +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) diff --git a/Task/Four-bit-adder/Scheme/four-bit-adder.ss b/Task/Four-bit-adder/Scheme/four-bit-adder.ss new file mode 100644 index 0000000000..630d1c9951 --- /dev/null +++ b/Task/Four-bit-adder/Scheme/four-bit-adder.ss @@ -0,0 +1,33 @@ +(import (scheme base) + (scheme write) + (srfi 60)) ;; for logical bits + +;; Returns a list of bits: '(sum carry) +(define (half-adder a b) + (list (bitwise-xor a b) (bitwise-and a b))) + +;; Returns a list of bits: '(sum carry) +(define (full-adder a b c-in) + (let* ((h1 (half-adder c-in a)) + (h2 (half-adder (car h1) b))) + (list (car h2) (bitwise-ior (cadr h1) (cadr h2))))) + +;; a and b are lists of 4 bits each +(define (four-bit-adder a b) + (let* ((add-1 (full-adder (list-ref a 3) (list-ref b 3) 0)) + (add-2 (full-adder (list-ref a 2) (list-ref b 2) (list-ref add-1 1))) + (add-3 (full-adder (list-ref a 1) (list-ref b 1) (list-ref add-2 1))) + (add-4 (full-adder (list-ref a 0) (list-ref b 0) (list-ref add-3 1)))) + (list (list (car add-4) (car add-3) (car add-2) (car add-1)) + (cadr add-4)))) + +(define (show-eg a b) + (display a) (display " + ") (display b) (display " = ") + (display (four-bit-adder a b)) (newline)) + +(show-eg (list 0 0 0 0) (list 0 0 0 0)) +(show-eg (list 0 0 0 0) (list 1 1 1 1)) +(show-eg (list 1 1 1 1) (list 0 0 0 0)) +(show-eg (list 0 1 0 1) (list 1 1 0 0)) +(show-eg (list 1 1 1 1) (list 1 1 1 1)) +(show-eg (list 1 0 1 0) (list 0 1 0 1)) diff --git a/Task/Four-bit-adder/Zkl/four-bit-adder-1.zkl b/Task/Four-bit-adder/Zkl/four-bit-adder-1.zkl new file mode 100644 index 0000000000..c782ee6c23 --- /dev/null +++ b/Task/Four-bit-adder/Zkl/four-bit-adder-1.zkl @@ -0,0 +1,24 @@ +fcn xor(a,b) // a,b are 1|0 -->a^b(1|0) + { a.bitAnd(b.bitNot()).bitOr(b.bitAnd(a.bitNot())) } + +fcn halfAdder(a,b) // -->(carry, a+b) (1|0) + { return(a.bitAnd(b), xor(a,b)) } + +fcn fullBitAdder(c, a,b){ //-->(carry, a+b+c), a,b,c are 1|0 + c1,s := halfAdder(a,c); + c2,s := halfAdder(s,b); + c3 := c1.bitOr(c2); + return(c3,s); +} + + // big endian +fcn fourBitAdder(a3,a2,a1,a0, b3,b2,b1,b0){ //-->(carry, s3,s2,s1,s0) + c,s0 := fullBitAdder(0, a0,b0); + c,s1 := fullBitAdder(c, a1,b1); + c,s2 := fullBitAdder(c, a2,b2); + c,s3 := fullBitAdder(c, a3,b3); + return(c, s3,s2,s1,s0); +} + +// add(10,9) result should be 1 0 0 1 1 (0x13, 3 carry 1) +println(fourBitAdder(1,0,1,0, 1,0,0,1)); diff --git a/Task/Four-bit-adder/Zkl/four-bit-adder-2.zkl b/Task/Four-bit-adder/Zkl/four-bit-adder-2.zkl new file mode 100644 index 0000000000..b430ab20c6 --- /dev/null +++ b/Task/Four-bit-adder/Zkl/four-bit-adder-2.zkl @@ -0,0 +1,8 @@ +fcn nBitAddr(as,bs){ //-->(carry, sn..s3,s2,s1,s0) + (ss:=List()).append( + [as.len()-1 .. 0,-1].reduce('wrap(c,n){ + c2,s:=fullBitAdder(c,as[n],bs[n]); ss + s; c2 + },0)) + .reverse(); +} +println(nBitAddr(T(1,0,1,0), T(1,0,0,1))); diff --git a/Task/Fractal-tree/FreeBASIC/fractal-tree.freebasic b/Task/Fractal-tree/FreeBASIC/fractal-tree.freebasic new file mode 100644 index 0000000000..96fdf2244c --- /dev/null +++ b/Task/Fractal-tree/FreeBASIC/fractal-tree.freebasic @@ -0,0 +1,40 @@ +' version 17-03-2017 +' compile with: fbc -s gui + +Const As Double deg2rad = Atn(1) / 45 +Dim Shared As Double scale = 0.76 +Dim Shared As Double spread = 25 * deg2rad ' convert degree's to rad's + +Sub branch(x1 As ULong, y1 As ULong, size As ULong, angle As Double, depth As ULong) + + Dim As ULong x2, y2 + + x2 = x1 + size * Cos(angle) + y2 = y1 + size * Sin(angle) + + Line (x1,y1) - (x2,y2), 2 ' palette color green + If depth > 0 Then + branch(x2, y2, size * scale, angle - spread, depth -1) + branch(x2, y2, size * scale, angle + spread, depth -1) + End If + +End Sub + +' ------=< MAIN >=----- + +Dim As Double angle = -90 * deg2rad ' make sure that the tree grows up +Dim As ULong SizeX = 800 +Dim As ULong SizeY = SizeX * 3 \ 4 +Dim As Double size = SizeY \ 4 +Dim As ULong depth = 11 + +ScreenRes SizeX, SizeY, 8 +WindowTitle ("Fractal Tree") + +branch(SizeX\2, SizeY, size, angle, depth) + +' empty keyboard buffer +While InKey <> "" : Wend +windowtitle ("Fractal Tree, hit any key to end program") +Sleep +End diff --git a/Task/Fractal-tree/Haskell/fractal-tree-1.hs b/Task/Fractal-tree/Haskell/fractal-tree-1.hs index 03c72d5227..4b54b9b739 100644 --- a/Task/Fractal-tree/Haskell/fractal-tree-1.hs +++ b/Task/Fractal-tree/Haskell/fractal-tree-1.hs @@ -5,4 +5,8 @@ type Model = [Picture -> Picture] fractal :: Int -> Model -> Picture -> Picture fractal n model pict = pictures $ take n $ iterate (mconcat model) pict +tree1 _ = fractal 10 branches $ Line [(0,0),(0,100)] + where branches = [ Translate 0 100 . Scale 0.75 0.75 . Rotate 30 + , Translate 0 100 . Scale 0.5 0.5 . Rotate (-30) ] + main = animate (InWindow "Tree" (800, 800) (0, 0)) white $ tree1 . (* 60) diff --git a/Task/Fractal-tree/Haskell/fractal-tree-2.hs b/Task/Fractal-tree/Haskell/fractal-tree-2.hs index 2fc69d57f5..5a6fdbeb41 100644 --- a/Task/Fractal-tree/Haskell/fractal-tree-2.hs +++ b/Task/Fractal-tree/Haskell/fractal-tree-2.hs @@ -1,3 +1,24 @@ -tree1 _ = fractal 10 branches $ Line [(0,0),(0,100)] - where branches = [ Translate 0 100 . Scale 0.75 0.75 . Rotate 30 - , Translate 0 100 . Scale 0.5 0.5 . Rotate (-30) ] +--animated tree +tree2 t = fractal 8 branches $ Line [(0,0),(0,100)] + where branches = [ Translate 0 100 . Scale 0.75 0.75 . Rotate t + , Translate 0 100 . Scale 0.6 0.6 . Rotate 0 + , Translate 0 100 . Scale 0.5 0.5 . Rotate (-2*t) ] + +--animated fractal clock +circles t = fractal 10 model $ Circle 100 + where model = [ Translate 0 50 . Scale 0.5 0.5 . Rotate t + , Translate 0 (-50) . Scale 0.5 0.5 . Rotate (-2*t) ] + +--Pythagoras tree +pithagor _ = fractal 10 model $ rectangleWire 100 100 + where model = [ Translate 50 100 . Scale s s . Rotate 45 + , Translate (-50) 100 . Scale s s . Rotate (-45)] + s = 1/sqrt 2 + +--Sierpinski pentagon +pentaflake _ = fractal 5 model $ pentagon + where model = map copy [0,72..288] + copy a = Scale s s . Rotate a . Translate 0 x + pentagon = Line [ (sin a, cos a) | a <- [0,2*pi/5..2*pi] ] + x = 2*cos(pi/5) + s = 1/(1+x) diff --git a/Task/Fractal-tree/Haskell/fractal-tree-3.hs b/Task/Fractal-tree/Haskell/fractal-tree-3.hs index 9461cd643b..5b4763c4b6 100644 --- a/Task/Fractal-tree/Haskell/fractal-tree-3.hs +++ b/Task/Fractal-tree/Haskell/fractal-tree-3.hs @@ -1,4 +1,31 @@ -tree2 t = fractal 8 branches $ Line [(0,0),(0,100)] - where branches = [ Translate 0 100 . Scale 0.75 0.75 . Rotate t - , Translate 0 100 . Scale 0.6 0.6 . Rotate 0 - , Translate 0 100 . Scale 0.5 0.5 . Rotate (-2*t) ] +import Graphics.HGL.Window +import Graphics.HGL.Run +import Control.Arrow +import Control.Monad +import Data.List + +enumBase :: Int -> Int -> [[Int]] +enumBase n = mapM (enumFromTo 0). replicate n. pred + +psPlus (a,b) (p,q) = (a+p, b+q) + +toInt :: Double -> Int +toInt = fromIntegral.round + +intPoint = toInt *** toInt + +pts n = + map (map (intPoint.psPlus (100,0)). ((0,300):). scanl1 psPlus. ((r,300):). zipWith (\h a -> (h*cos a, h*sin a)) rs) hs + where + [r,h,sr,sh] = [50, pi/5, 0.9, 0.75] + rs = take n $ map (r*) $ iterate(*sr) sr + lhs = map (map (((-1)**).fromIntegral)) $ enumBase n 2 + rhs = take n $ map (h*) $ iterate(*sh) 1 + hs = map (scanl1 (+). zipWith (*)rhs) lhs + +fractalTree :: Int -> IO () +fractalTree n = + runWindow "Fractal Tree" (500,600) + (\w -> setGraphic w (overGraphics ( map polyline $ pts (n-1))) >> getKey w) + +main = fractalTree 10 diff --git a/Task/Fractal-tree/Haskell/fractal-tree-4.hs b/Task/Fractal-tree/Haskell/fractal-tree-4.hs deleted file mode 100644 index f1940629bd..0000000000 --- a/Task/Fractal-tree/Haskell/fractal-tree-4.hs +++ /dev/null @@ -1,3 +0,0 @@ -circles t = fractal 10 model $ Circle 100 - where model = [ Translate 0 50 . Scale 0.5 0.5 . Rotate t - , Translate 0 (-50) . Scale 0.5 0.5 . Rotate (-2*t) ] diff --git a/Task/Fractal-tree/Haskell/fractal-tree-5.hs b/Task/Fractal-tree/Haskell/fractal-tree-5.hs deleted file mode 100644 index 65758459fd..0000000000 --- a/Task/Fractal-tree/Haskell/fractal-tree-5.hs +++ /dev/null @@ -1,4 +0,0 @@ -pithagor _ = fractal 10 model $ rectangleWire 100 100 - where model = [ Translate 50 100 . Scale s s . Rotate 45 - , Translate (-50) 100 . Scale s s . Rotate (-45)] - s = 1/sqrt 2 diff --git a/Task/Fractal-tree/Haskell/fractal-tree-6.hs b/Task/Fractal-tree/Haskell/fractal-tree-6.hs deleted file mode 100644 index 97cf12e4c0..0000000000 --- a/Task/Fractal-tree/Haskell/fractal-tree-6.hs +++ /dev/null @@ -1,6 +0,0 @@ -pentaflake _ = fractal 5 model $ pentagon - where model = map copy [0,72..288] - copy a = Scale s s . Rotate a . Translate 0 x - pentagon = Line [ (sin a, cos a) | a <- [0,2*pi/5..2*pi] ] - x = 2*cos(pi/5) - s = 1/(1+x) diff --git a/Task/Fractal-tree/Haskell/fractal-tree-7.hs b/Task/Fractal-tree/Haskell/fractal-tree-7.hs deleted file mode 100644 index 89e9632527..0000000000 --- a/Task/Fractal-tree/Haskell/fractal-tree-7.hs +++ /dev/null @@ -1,29 +0,0 @@ -import Graphics.HGL.Window -import Graphics.HGL.Run -import Control.Arrow -import Control.Monad -import Data.List - -enumBase :: Int -> Int -> [[Int]] -enumBase n = mapM (enumFromTo 0). replicate n. pred - -psPlus (a,b) (p,q) = (a+p, b+q) - -toInt :: Double -> Int -toInt = fromIntegral.round - -intPoint = toInt *** toInt - -pts n = - map (map (intPoint.psPlus (100,0)). ((0,300):). scanl1 psPlus. ((r,300):). zipWith (\h a -> (h*cos a, h*sin a)) rs) hs - where - [r,h,sr,sh] = [50, pi/5, 0.9, 0.75] - rs = take n $ map (r*) $ iterate(*sr) sr - lhs = map (map (((-1)**).fromIntegral)) $ enumBase n 2 - rhs = take n $ map (h*) $ iterate(*sh) 1 - hs = map (scanl1 (+). zipWith (*)rhs) lhs - -fractalTree :: Int -> IO () -fractalTree n = - runWindow "Fractal Tree" (500,600) - (\w -> setGraphic w (overGraphics ( map polyline $ pts (n-1))) >> getKey w) diff --git a/Task/Fractal-tree/jq/fractal-tree.jq b/Task/Fractal-tree/Jq/fractal-tree.jq similarity index 100% rename from Task/Fractal-tree/jq/fractal-tree.jq rename to Task/Fractal-tree/Jq/fractal-tree.jq diff --git a/Task/Fractal-tree/Kotlin/fractal-tree.kotlin b/Task/Fractal-tree/Kotlin/fractal-tree.kotlin new file mode 100644 index 0000000000..c8cff49221 --- /dev/null +++ b/Task/Fractal-tree/Kotlin/fractal-tree.kotlin @@ -0,0 +1,32 @@ +// version 1.1.2 + +import java.awt.Color +import java.awt.Graphics +import javax.swing.JFrame + +class FractalTree : JFrame("Fractal Tree") { + init { + background = Color.black + setBounds(100, 100, 800, 600) + isResizable = false + defaultCloseOperation = EXIT_ON_CLOSE + } + + private fun drawTree(g: Graphics, x1: Int, y1: Int, angle: Double, depth: Int) { + if (depth == 0) return + val x2 = x1 + (Math.cos(Math.toRadians(angle)) * depth * 10.0).toInt() + val y2 = y1 + (Math.sin(Math.toRadians(angle)) * depth * 10.0).toInt() + g.drawLine(x1, y1, x2, y2) + drawTree(g, x2, y2, angle - 20, depth - 1) + drawTree(g, x2, y2, angle + 20, depth - 1) + } + + override fun paint(g: Graphics) { + g.color = Color.white + drawTree(g, 400, 500, -90.0, 9) + } +} + +fun main(args: Array) { + FractalTree().isVisible = true +} diff --git a/Task/Fractal-tree/Lua/fractal-tree.lua b/Task/Fractal-tree/Lua/fractal-tree.lua new file mode 100644 index 0000000000..3f47a5eb6e --- /dev/null +++ b/Task/Fractal-tree/Lua/fractal-tree.lua @@ -0,0 +1,37 @@ +g, angle = love.graphics, 26 * math.pi / 180 +wid, hei = g.getWidth(), g.getHeight() +function rotate( x, y, a ) + local s, c = math.sin( a ), math.cos( a ) + local a, b = x * c - y * s, x * s + y * c + return a, b +end +function branches( a, b, len, ang, dir ) + len = len * .76 + if len < 5 then return end + g.setColor( len * 16, 255 - 2 * len , 0 ) + if dir > 0 then ang = ang - angle + else ang = ang + angle + end + local vx, vy = rotate( 0, len, ang ) + vx = a + vx; vy = b - vy + g.line( a, b, vx, vy ) + branches( vx, vy, len, ang, 1 ) + branches( vx, vy, len, ang, 0 ) +end +function createTree() + local lineLen = 127 + local a, b = wid / 2, hei - lineLen + g.setColor( 160, 40 , 0 ) + g.line( wid / 2, hei, a, b ) + branches( a, b, lineLen, 0, 1 ) + branches( a, b, lineLen, 0, 0 ) +end +function love.load() + canvas = g.newCanvas( wid, hei ) + g.setCanvas( canvas ) + createTree() + g.setCanvas() +end +function love.draw() + g.draw( canvas ) +end diff --git a/Task/Fractal-tree/Phix/fractal-tree.phix b/Task/Fractal-tree/Phix/fractal-tree.phix index bdb24c7102..03ad786a8b 100644 --- a/Task/Fractal-tree/Phix/fractal-tree.phix +++ b/Task/Fractal-tree/Phix/fractal-tree.phix @@ -1,4 +1,7 @@ -include ..\pGUI\pGUI.e +-- +-- demo\rosetta\FractalTree.exw +-- +include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas @@ -38,7 +41,7 @@ function esc_close(Ihandle /*ih*/, atom c) end function procedure main() - IupOpen("..\\pGUI\\") + IupOpen() canvas = IupCanvas(NULL) IupSetAttribute(canvas, "RASTERSIZE", "640x480") diff --git a/Task/Fractal-tree/R/fractal-tree.r b/Task/Fractal-tree/R/fractal-tree.r new file mode 100644 index 0000000000..bbe2dffe90 --- /dev/null +++ b/Task/Fractal-tree/R/fractal-tree.r @@ -0,0 +1,34 @@ +## Recursive FT plotting +plotftree <- function(x, y, a, d, c) { +x2=y2=0; d2r=pi/180.0; a1 <- a*d2r; d1=0; +if(d<=0) {return()} +if(d>0) + { d1=d*10.0; + x2=x+cos(a1)*d1; + y2=y+sin(a1)*d1; + segments(x*c, y*c, x2*c, y2*c, col='darkgreen'); + plotftree(x2,y2,a-20,d-1,c); + plotftree(x2,y2,a+20,d-1,c); + #return(2); + } +} +## Plotting Fractal Tree. aev 3/27/17 +## ord - order/depth, c - scale, xsh - x-shift, fn - file name, +## ttl - plot title. +pFractalTree <- function(ord, c=1, xsh=0, fn="", ttl="") { + cat(" *** START FRT:", date(), "\n"); + m=640; + if(fn=="") {pf=paste0("FRTR", ord, ".png")} else {pf=paste0(fn, ".png")}; + if(ttl=="") {ttl=paste0("Fractal tree, order - ", ord)}; + cat(" *** Plot file -", pf, "title:", ttl, "\n"); + ##plot(NA, xlim=c(0,m), ylim=c(-m,0), xlab="", ylab="", main=ttl); + plot(NA, xlim=c(0,m), ylim=c(0,m), xlab="", ylab="", main=ttl); + plotftree(m/2+xsh,100,90,ord,c); + dev.copy(png, filename=pf, width=m, height=m); + dev.off(); graphics.off(); + cat(" *** END FRT:",date(),"\n"); +} +## Executing: +pFractalTree(9); +pFractalTree(12,0.6,210); +pFractalTree(15,0.35,600); diff --git a/Task/Fractal-tree/Scheme/fractal-tree.ss b/Task/Fractal-tree/Scheme/fractal-tree.ss new file mode 100644 index 0000000000..21462df370 --- /dev/null +++ b/Task/Fractal-tree/Scheme/fractal-tree.ss @@ -0,0 +1,51 @@ +(import (scheme base) + (scheme file) + (scheme inexact) + (scheme write)) + +(define *scale* 10) ; controls overall size of tree +(define *split* 20) ; controls angle of split (in degrees) + +;; construct lines for tree as list of 5-tuples (x1 y1 x2 y2 depth) +;; - x1 y1 is start point +;; - angle of this line, in radians +;; - depth, depth within tree (controls length of line) +(define (create-tree x1 y1 angle depth) + (define (degrees->radians d) + (let ((pi 3.14159265358979323846264338327950288419716939937510582097)) + (* d pi 1/180))) + ; + (if (zero? depth) + '() + (let ((x2 (+ x1 (* (cos (degrees->radians angle)) depth *scale*))) + (y2 (+ y1 (* (sin (degrees->radians angle)) depth *scale*)))) + (append (list (map truncate (list x1 y1 x2 y2 depth))) + (create-tree x2 y2 (- angle *split*) (- depth 1)) + (create-tree x2 y2 (+ angle *split*) (- depth 1)))))) + +;; output the tree to an eps file +(define (output-tree-as-eps filename tree) + (when (file-exists? filename) (delete-file filename)) + (with-output-to-file + filename + (lambda () + (display "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 800 800\n") + + ;; add each line - sets linewidth based on depth in tree + (for-each (lambda (line) + (display + (string-append "newpath\n" + (number->string (list-ref line 0)) " " + (number->string (list-ref line 1)) " " + "moveto\n" + (number->string (list-ref line 2)) " " + (number->string (list-ref line 3)) " " + "lineto\n" + (number->string (truncate (/ (list-ref line 4) 2))) + " setlinewidth\n" + "stroke\n" + ))) + tree) + (display "\n%%EOF")))) + +(output-tree-as-eps "fractal.eps" (create-tree 400 200 90 9)) diff --git a/Task/Fractal-tree/Scilab/fractal-tree-1.scilab b/Task/Fractal-tree/Scilab/fractal-tree-1.scilab new file mode 100644 index 0000000000..3ff6942a64 --- /dev/null +++ b/Task/Fractal-tree/Scilab/fractal-tree-1.scilab @@ -0,0 +1,80 @@ +trunk = 1; //trunk length +ratio = 0.8; //size ratio between two consecutive branches +depth = 9; //final number of branch levels +orign = 0; //origin of the tree (should be complex) +angle = 45*%pi/180; //angle between two branches [rad] +trunk_angle = 90*%pi/180; //angle between trunk and X-axis [rad] + +right_angle = angle/2; //angles to the right or to the left +left_angle = 0.8*angle; //can be set independently or + //as function of 'angle' + +//L-system definition: +//Alphabet: FBD[]+- + //F: go forward B: go backwards + //[: start new branch ]: end current branch + //+: branch to the right -: branch to the left + //D: double line (forward then backward) +//Axiom: D +//Rule: D -> F[+D-D]B + +//L-system sentence generation +sentence = 'D' +rule = 'F[+D-D]B'; +for i=1:depth + sentence = strsubst(sentence,'D',rule); +end +sentence = strsplit(sentence)'; + +//Empty tree +tree_size = 1.0... + + length(find(sentence=='F'|sentence=='B'))... + + 2 * length(find(sentence=='D')); +tree=zeros(tree_size,1); + +//Drawing the tree +branch_level = 0; +curr_angle = trunk_angle; +curr_pos = 1; + +for ind = 1:size(sentence,'c') + charac = sentence(ind); + + select charac + case 'F' then //Draw line forward + tree(curr_pos+1) = tree(curr_pos)... + + trunk * ratio^branch_level * exp(curr_angle*%i); + curr_pos = curr_pos + 1; + + case 'B' then //Draw line backwards + tree(curr_pos+1) = tree(curr_pos)... + + trunk * ratio^branch_level * exp((%pi+curr_angle)*%i); + curr_pos = curr_pos + 1; + + case '[' then //New branch + branch_level = branch_level + 1; + + case '+' then //Turn right + curr_angle = curr_angle - right_angle; + + case '-' then //Turn left + curr_angle = curr_angle + right_angle + left_angle; + + case ']' then //End of branch + branch_level = branch_level - 1; + curr_angle = curr_angle - left_angle; + + case 'D' then //Double line + tree(curr_pos+1) = tree(curr_pos)... + + trunk * ratio^branch_level * exp(curr_angle*%i); + tree(curr_pos+2) = tree(curr_pos+1)... + + trunk * ratio^branch_level * exp((%pi+curr_angle)*%i); + curr_pos = curr_pos + 2; + end +end + +scf(); clf(); +xname('Fractal tree: '+string(depth)+' levels') +plot2d(real(tree),imag(tree),14); +set(gca(),'isoview','on'); +set(gca(),'axes_visible',['off','off','off']); diff --git a/Task/Fractal-tree/Scilab/fractal-tree-2.scilab b/Task/Fractal-tree/Scilab/fractal-tree-2.scilab new file mode 100644 index 0000000000..330295b759 --- /dev/null +++ b/Task/Fractal-tree/Scilab/fractal-tree-2.scilab @@ -0,0 +1,17 @@ +width = 512; +height = 512; +img=scf(); +set(img,'figure_size',[width,height]); + +function drawTree(x1, y1, angle, depth) + if depth ~= 0 then + x2 = x1 + cos(angle * %pi/180) * depth * 10; + y2 = y1 + sin(angle * %pi/180) * depth * 10; + plot2d([x1 x2],[y1 y2],14); + drawTree(x2, y2, angle - 20, depth - 1); + drawTree(x2, y2, angle + 20, depth - 1); + end +endfunction + +drawTree(width/2,height,90,10); +set(gca(),'isoview','on'); diff --git a/Task/Fractal-tree/Zkl/fractal-tree.zkl b/Task/Fractal-tree/Zkl/fractal-tree.zkl new file mode 100644 index 0000000000..417ad405b5 --- /dev/null +++ b/Task/Fractal-tree/Zkl/fractal-tree.zkl @@ -0,0 +1,18 @@ +fcn fractalTree(){ + scale:=0.76; + sizeX:=400; sizeY:=300; + bitmap:=PPM(sizeX*2,sizeY*2,0xFF|FF|FF); + branch:='wrap(x1,y1,size,angle,depth){ + ar:=angle.toRad(); + x2:=x1 - size*ar.cos(); + y2:=y1 + size*ar.sin(); + color:=(0xff-depth*8).shiftLeft(16) + (depth*12+100).shiftLeft(8); + bitmap.line(x1,y1, x2,y2, color); + if(depth){ + self.fcn(x2,y2,scale*size,angle - 30,depth - 1,vm.pasteArgs(5)); + self.fcn(x2,y2,scale*size,angle + 8, depth - 1,vm.pasteArgs(5)); + } + }; + branch(sizeX,0,sizeY/2,90.0,10); + bitmap.write(File("foo.ppm","wb")); +}(); diff --git a/Task/Fractran/Kotlin/fractran.kotlin b/Task/Fractran/Kotlin/fractran.kotlin new file mode 100644 index 0000000000..ff7dff969d --- /dev/null +++ b/Task/Fractran/Kotlin/fractran.kotlin @@ -0,0 +1,45 @@ +// version 1.1.3 + +import java.math.BigInteger + +class Fraction(val num: BigInteger, val denom: BigInteger) { + operator fun times(n: BigInteger) = Fraction (n * num, denom) + + fun isIntegral() = num % denom == BigInteger.ZERO +} + +fun String.toFraction(): Fraction { + val split = this.split('/') + return Fraction(BigInteger(split[0]), BigInteger(split[1])) +} + +val BigInteger.isPowerOfTwo get() = this.and(this - BigInteger.ONE) == BigInteger.ZERO + +val log2 = Math.log(2.0) + +fun fractran(program: String, n: Int, limit: Int, primesOnly: Boolean): List { + val fractions = program.split(' ').map { it.toFraction() } + val results = mutableListOf() + if (!primesOnly) results.add(n) + var nn = BigInteger.valueOf(n.toLong()) + while (results.size < limit) { + val frac = fractions.find { (it * nn).isIntegral() } ?: break + nn = nn * frac.num / frac.denom + if (!primesOnly) { + results.add(nn.toInt()) + } + else if (primesOnly && nn.isPowerOfTwo) { + val prime = (Math.log(nn.toDouble()) / log2).toInt() + results.add(prime) + } + } + return results +} + +fun main(args: Array) { + val program = "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" + println("First twenty numbers:") + println(fractran(program, 2, 20, false)) + println("\nFirst twenty primes:") + println(fractran(program, 2, 20, true)) +} diff --git a/Task/Fractran/Perl-6/fractran-1.pl6 b/Task/Fractran/Perl-6/fractran-1.pl6 index 83b8a491dd..5436cdc88f 100644 --- a/Task/Fractran/Perl-6/fractran-1.pl6 +++ b/Task/Fractran/Perl-6/fractran-1.pl6 @@ -1,5 +1,5 @@ sub fractran(@program) { - 2, { +first Int, map (* * $_).narrow, @program } ... 0 + 2, { first Int, map (* * $_).narrow, @program } ... 0 } say 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>)[^100]; diff --git a/Task/Fractran/Perl-6/fractran-2.pl6 b/Task/Fractran/Perl-6/fractran-2.pl6 index d415b3e7dc..4165244c9f 100644 --- a/Task/Fractran/Perl-6/fractran-2.pl6 +++ b/Task/Fractran/Perl-6/fractran-2.pl6 @@ -1,4 +1,4 @@ for 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> { - say $++, "\t", .msb, "\t", $_ if .log %% log(2); + say $++, "\t", .msb, "\t", $_ if 1 +< .msb == $_; } diff --git a/Task/Fractran/Scheme/fractran.ss b/Task/Fractran/Scheme/fractran.ss new file mode 100644 index 0000000000..d207ed9ce1 --- /dev/null +++ b/Task/Fractran/Scheme/fractran.ss @@ -0,0 +1,62 @@ +(import (scheme base) + (scheme inexact) + (scheme read) + (scheme write)) + +(define *string-fractions* ; string input of fractions + "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") + +(define *fractions* ; create vector of fractions from string input + (list->vector ; convert result to a vector, for constant access times + (read (open-input-string ; read from the string of fractions, as a list + (string-append "(" *string-fractions* ")"))))) + +;; run a fractran interpreter, returning the next number for n +;; or #f if no next number available +;; assume fractions: ordered vector of positive fractions +;; n: a positive integer +(define (fractran fractions n) + (let ((max-n (vector-length fractions))) + (let loop ((i 0)) + (cond ((= i max-n) + #f) + ((integer? (* n (vector-ref fractions i))) + (* n (vector-ref fractions i))) + (else + (loop (+ 1 i))))))) + +;; Task +(define (display-result max-n) + (do ((i 0 (+ 1 i)) + (n 2 (fractran *fractions* n))) + ((= i max-n) (newline)) + (display n) (display " "))) + +(display "Task: ") +(display-result 20) ; show first 20 numbers + +;; Extra Credit: derive first 20 prime numbers +(define (generate-primes target-number initial-n) + (define (is-power-of-two? n) + (and (> n 2) + (integer? (log n 2)))) + (define (extract-prime n) + (exact (log n 2))) + ; + (let loop ((count 0) + (n initial-n)) + (when (< count target-number) + (cond ((eq? n #f) + (display "-- FAILED TO COMPUTE N --\n")) + ((is-power-of-two? n) + (display (extract-prime n)) (display " ") + (loop (+ 1 count) + (fractran *fractions* n))) + (else + (loop count + (fractran *fractions* n)))))) + (newline)) + +(display "Primes:\n") +(generate-primes 20 2) ; create first 20 primes diff --git a/Task/Fractran/Sidef/fractran.sidef b/Task/Fractran/Sidef/fractran.sidef index e7d21ce504..e9dc7687cc 100644 --- a/Task/Fractran/Sidef/fractran.sidef +++ b/Task/Fractran/Sidef/fractran.sidef @@ -1,20 +1,20 @@ var str ="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" -const FractalProgram = str.split(',').map{.to_r} #=> array of rationals +const FractalProgram = str.split(',').map{.num} #=> array of rationals func runner(n, callback) { - var num = 2.rat + var num = 2 n.times { - callback(num *= FractalProgram.find { |f| (f*num).de.is_one }) + callback(num *= FractalProgram.find { |f| f * num -> is_int }) } } func prime_generator(n, callback) { var x = 0; - runner(Math.inf, { |num| - var l = num.to_f.log2 + runner(Inf, { |num| + var l = num.log2 if (l.floor == l) { - callback(l.to_i) - ++x == n && return + callback(l.int) + ++x == n && return nil } }) } diff --git a/Task/Fractran/Zkl/fractran-1.zkl b/Task/Fractran/Zkl/fractran-1.zkl new file mode 100644 index 0000000000..ab1e3d8182 --- /dev/null +++ b/Task/Fractran/Zkl/fractran-1.zkl @@ -0,0 +1,15 @@ +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), ...) + Walker(fcn(rn,fracs){ + n:=rn.value; + foreach a,b in (fracs){ + if(n*a%b == 0){ + rn.set(n*a/b); + return(n); + } + } + }.fp(Ref(n),fracs)) +} diff --git a/Task/Fractran/Zkl/fractran-2.zkl b/Task/Fractran/Zkl/fractran-2.zkl new file mode 100644 index 0000000000..69d2a7367b --- /dev/null +++ b/Task/Fractran/Zkl/fractran-2.zkl @@ -0,0 +1 @@ +fractranW(2,fracs).walk(20).println(); diff --git a/Task/Fractran/Zkl/fractran-3.zkl b/Task/Fractran/Zkl/fractran-3.zkl new file mode 100644 index 0000000000..00de8a061b --- /dev/null +++ b/Task/Fractran/Zkl/fractran-3.zkl @@ -0,0 +1,11 @@ +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)); + } + } +} +fractranPrimes(); diff --git a/Task/Function-composition/AppleScript/function-composition-2.applescript b/Task/Function-composition/AppleScript/function-composition-2.applescript index 544b0a8fdd..249a5a20b0 100644 --- a/Task/Function-composition/AppleScript/function-composition-2.applescript +++ b/Task/Function-composition/AppleScript/function-composition-2.applescript @@ -1,22 +1,4 @@ --- Compose (right to left) a list of ordinary 2nd class handlers (of arbitrary length) - --- compose :: [(a -> a)] -> (a -> a) -on compose(fs) - script - on lambda(x) - script - on lambda(a, f) - mReturn(f)'s lambda(a) - end lambda - end script - - foldr(result, x, fs) - end lambda - end script -end compose - - --- TEST +-- FUNCTIONS TO COMPOSE ------------------------------------------------------- on root(x) x ^ 0.5 @@ -30,17 +12,30 @@ on half(x) x / 2 end half - +-- TEST ----------------------------------------------------------------------- on run - tell compose([half, succ, root]) to lambda(5) + compose([half, succ, root])'s |λ|(5) --> 1.61803398875 end run +-- GENERIC FUNCTIONS ---------------------------------------------------------- +-- compose :: [(a -> a)] -> (a -> a) +on compose(fs) + script + on |λ|(x) + script + on |λ|(a, f) + mReturn(f)'s |λ|(a) + end |λ| + end script --- GENERIC FUNCTIONS + foldr(result, x, fs) + end |λ| + end script +end compose -- foldr :: (a -> b -> a) -> a -> [b] -> a on foldr(f, startValue, xs) @@ -48,7 +43,7 @@ on foldr(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -61,7 +56,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Function-composition/Elena/function-composition.elena b/Task/Function-composition/Elena/function-composition.elena new file mode 100644 index 0000000000..2a001ea0fa --- /dev/null +++ b/Task/Function-composition/Elena/function-composition.elena @@ -0,0 +1,14 @@ +import extensions. + +func1 extension op +{ + compose(BaseFunction1 f) + = (:x)(self eval(f eval:x)). +} + +program = +[ + var fg := (:x)(x + 1) compose(:x)(x * x). + + console printLine(fg eval(3)). +]. diff --git a/Task/Function-composition/Erlang/function-composition-1.erl b/Task/Function-composition/Erlang/function-composition-1.erl index ec47d3660d..845734f147 100644 --- a/Task/Function-composition/Erlang/function-composition-1.erl +++ b/Task/Function-composition/Erlang/function-composition-1.erl @@ -1,5 +1,5 @@ -module(fn). --export([compose/1, multicompose/2]). +-export([compose/2, multicompose/1]). compose(F,G) -> fun(X) -> F(G(X)) end. diff --git a/Task/Function-composition/Groovy/function-composition-1.groovy b/Task/Function-composition/Groovy/function-composition-1.groovy deleted file mode 100644 index f61dfba237..0000000000 --- a/Task/Function-composition/Groovy/function-composition-1.groovy +++ /dev/null @@ -1 +0,0 @@ -def compose = { f, g -> { x -> f(g(x)) } } diff --git a/Task/Function-composition/Groovy/function-composition-2.groovy b/Task/Function-composition/Groovy/function-composition-2.groovy deleted file mode 100644 index f7b345aab1..0000000000 --- a/Task/Function-composition/Groovy/function-composition-2.groovy +++ /dev/null @@ -1,15 +0,0 @@ -def sq = { it * it } -def plus1 = { it + 1 } -def minus1 = { it - 1 } - -def plus1sqd = compose(sq,plus1) -def sqminus1 = compose(minus1,sq) -def identity = compose(plus1,minus1) -def plus1sqdminus1 = compose(minus1,compose(sq,plus1)) -def identity2 = compose(Math.&sin,Math.&asin) - -println "(x+1)**2 = (0+1)**2 = " + plus1sqd(0) -println "x**2-1 = 20**2-1 = " + sqminus1(20) -println "(x+1)-1 = (12+1)-1 = " + identity(12) -println "(x+1)**2-1 = (3+1)**2-1 = " + plus1sqdminus1(3) -println "sin(asin(x)) = sin(asin(1)) = " + identity2(1) diff --git a/Task/Function-composition/Hy/function-composition.hy b/Task/Function-composition/Hy/function-composition.hy new file mode 100644 index 0000000000..8d2154d6dc --- /dev/null +++ b/Task/Function-composition/Hy/function-composition.hy @@ -0,0 +1,3 @@ +(defn compose [f g] + (fn [x] + (f (g x)))) diff --git a/Task/Function-composition/JavaScript/function-composition-4.js b/Task/Function-composition/JavaScript/function-composition-4.js index ca5bb79926..f5c9d010ab 100644 --- a/Task/Function-composition/JavaScript/function-composition-4.js +++ b/Task/Function-composition/JavaScript/function-composition-4.js @@ -1,20 +1,16 @@ (() => { 'use strict'; - // compose :: [(a -> a)] -> (a -> a) let compose = fs => x => fs.reduceRight((a, f) => f(a), x); - // TEST a composition of 3 functions (right to left) - let sqrt = Math.sqrt, succ = x => x + 1, half = x => x / 2; - return compose([half, succ, sqrt])(5); // --> 1.618033988749895 diff --git a/Task/Function-composition/JavaScript/function-composition-5.js b/Task/Function-composition/JavaScript/function-composition-5.js new file mode 100644 index 0000000000..996e810b43 --- /dev/null +++ b/Task/Function-composition/JavaScript/function-composition-5.js @@ -0,0 +1,19 @@ +(() => { + 'use strict'; + + // compose :: (a -> b) -> (b -> c) -> (a -> c) + const compose = (f, g) => x => g(f(x)); + + + // TEST + const + sqrt = Math.sqrt, + succ = x => x + 1, + half = x => x / 2; + + const + succSqrt = compose(sqrt, succ), + halfSuccSqrt = compose(succSqrt, half); + + return halfSuccSqrt(5); +})(); diff --git a/Task/Function-composition/jq/function-composition.jq b/Task/Function-composition/Jq/function-composition.jq similarity index 100% rename from Task/Function-composition/jq/function-composition.jq rename to Task/Function-composition/Jq/function-composition.jq diff --git a/Task/Function-composition/K/function-composition-1.k b/Task/Function-composition/K/function-composition-1.k index ca1dd3329d..6e85a931b8 100644 --- a/Task/Function-composition/K/function-composition-1.k +++ b/Task/Function-composition/K/function-composition-1.k @@ -1 +1 @@ -compose: {x@y@z} +compose:{'[x;y]} diff --git a/Task/Function-composition/K/function-composition-2.k b/Task/Function-composition/K/function-composition-2.k index 9cff3f65a0..086ff3424b 100644 --- a/Task/Function-composition/K/function-composition-2.k +++ b/Task/Function-composition/K/function-composition-2.k @@ -1,3 +1 @@ - sin_asin: compose[_sin;_asin] - sin_asin 0.5 -0.5 +compose:{x[y[z]]} diff --git a/Task/Function-composition/K/function-composition-3.k b/Task/Function-composition/K/function-composition-3.k new file mode 100644 index 0000000000..2ced52ace6 --- /dev/null +++ b/Task/Function-composition/K/function-composition-3.k @@ -0,0 +1,3 @@ + sin_asin:compose[sin;asin] // or compose . (sin;asin) + sin_asin 0.5 +0.5 diff --git a/Task/Function-composition/Kotlin/function-composition.kotlin b/Task/Function-composition/Kotlin/function-composition.kotlin new file mode 100644 index 0000000000..87ad414027 --- /dev/null +++ b/Task/Function-composition/Kotlin/function-composition.kotlin @@ -0,0 +1,12 @@ +// version 1.0.6 + +fun f(x: Int): Int = x * x + +fun g(x: Int): Int = x + 2 + +fun compose(f: (Int) -> Int, g: (Int) -> Int): (Int) -> Int = { f(g(it)) } + +fun main(args: Array) { + val x = 10 + println(compose(::f, ::g)(x)) +} diff --git a/Task/Function-composition/Objective-C/function-composition-1.m b/Task/Function-composition/Objective-C/function-composition-1.m deleted file mode 100644 index 07fa9020e3..0000000000 --- a/Task/Function-composition/Objective-C/function-composition-1.m +++ /dev/null @@ -1,119 +0,0 @@ -#include - -// the protocol of objects that can behave "like function" -@protocol FunctionCapsule --(id)computeWith: (id)x; -@end - - -// a commodity for "encapsulating" double f(double) -typedef double (*func_t)(double); -@interface FunctionCaps : NSObject -{ - func_t function; -} -+(id)capsuleFor: (func_t)f; --(id)initWithFunc: (func_t)f; -@end - -@implementation FunctionCaps --(id)initWithFunc: (func_t)f -{ - if ((self = [self init])) { - function = f; - } - return self; -} -+(id)capsuleFor: (func_t)f -{ - return [[[self alloc] initWithFunc: f] autorelease]; -} --(id)computeWith: (id)x -{ - return [NSNumber numberWithDouble: function([x doubleValue])]; -} -@end - - -// the "functions" composer -@interface FunctionComposer : NSObject -{ - id funcA; - id funcB; -} -+(id) createCompositeFunctionWith: (id)A and: (id)B; --(id) initComposing: (id)A with: (id)B; -@end - -@implementation FunctionComposer -+(id) createCompositeFunctionWith: (id)A and: (id)B -{ - return [[[self alloc] initComposing: A with: B] autorelease]; -} - --(id) init -{ - [self release]; - @throw [NSException exceptionWithName:NSInternalInconsistencyException - reason:@"FunctionComposer: init with initComposing!" - userInfo:nil]; - return nil; -} - --(id) initComposing: (id)A with: (id)B -{ - if ((self = [super init])) { - if ( [A respondsToSelector: @selector(computeWith:)] && - [B respondsToSelector: @selector(computeWith:)] ) { - funcA = [A retain]; funcB = [B retain]; - return self; - } - NSLog(@"FunctionComposer: cannot compose functions not responding to protocol FunctionCapsule!"); - [self release]; - } - return nil; -} - --(id)computeWith: (id)x -{ - return [funcA computeWith: [funcB computeWith: x]]; -} - --(void) dealloc -{ - [funcA release]; - [funcB release]; - [super dealloc]; -} -@end - - -// functions outside... -double my_f(double x) -{ - return x+1.0; -} - -double my_g(double x) -{ - return x*x; -} - - -int main() -{ - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - id funcf = [FunctionCaps capsuleFor: my_f]; - id funcg = [FunctionCaps capsuleFor: my_g]; - - id composed = [FunctionComposer - createCompositeFunctionWith: funcf and: funcg]; - - printf("g(2.0) = %lf\n", [[funcg computeWith: [NSNumber numberWithDouble: 2.0]] doubleValue]); - printf("f(2.0) = %lf\n", [[funcf computeWith: [NSNumber numberWithDouble: 2.0]] doubleValue]); - printf("f(g(2.0)) = %lf\n", [[composed computeWith: [NSNumber numberWithDouble: 2.0]] doubleValue]); - - [pool release]; - return 0; -} diff --git a/Task/Function-composition/Objective-C/function-composition-2.m b/Task/Function-composition/Objective-C/function-composition-2.m deleted file mode 100644 index b277f86038..0000000000 --- a/Task/Function-composition/Objective-C/function-composition-2.m +++ /dev/null @@ -1,42 +0,0 @@ -#include - -typedef id (^Function)(id); - -// a commodity for "encapsulating" double f(double) -typedef double (*func_t)(double); -Function encapsulate(func_t f) { - return [[^(id x) { return [NSNumber numberWithDouble: f([x doubleValue])]; } copy] autorelease]; -} - -Function compose(Function a, Function b) { - return [[^(id x) { return a(b(x)); } copy] autorelease]; -} - -// functions outside... -double my_f(double x) -{ - return x+1.0; -} - -double my_g(double x) -{ - return x*x; -} - - -int main() -{ - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - Function f = encapsulate(my_f); - Function g = encapsulate(my_g); - - Function composed = compose(f, g); - - printf("g(2.0) = %lf\n", [g([NSNumber numberWithDouble: 2.0]) doubleValue]); - printf("f(2.0) = %lf\n", [f([NSNumber numberWithDouble: 2.0]) doubleValue]); - printf("f(g(2.0)) = %lf\n", [composed([NSNumber numberWithDouble: 2.0]) doubleValue]); - - [pool release]; - return 0; -} diff --git a/Task/Function-composition/Perl-6/function-composition-1.pl6 b/Task/Function-composition/Perl-6/function-composition-1.pl6 deleted file mode 100644 index a66e2270c3..0000000000 --- a/Task/Function-composition/Perl-6/function-composition-1.pl6 +++ /dev/null @@ -1,3 +0,0 @@ -sub infix:<∘> (&f, &g --> Block) { - -> |args { f g |args } -} diff --git a/Task/Function-composition/Perl-6/function-composition-2.pl6 b/Task/Function-composition/Perl-6/function-composition-2.pl6 deleted file mode 100644 index c88b867d54..0000000000 --- a/Task/Function-composition/Perl-6/function-composition-2.pl6 +++ /dev/null @@ -1,3 +0,0 @@ -sub triple($n) { 3 * $n } -my &f = &triple ∘ &prefix:<-> ∘ { $^n + 2 }; -say &f(5); # Prints "-21". diff --git a/Task/Function-composition/Perl-6/function-composition.pl6 b/Task/Function-composition/Perl-6/function-composition.pl6 index c88b867d54..e08d28875c 100644 --- a/Task/Function-composition/Perl-6/function-composition.pl6 +++ b/Task/Function-composition/Perl-6/function-composition.pl6 @@ -1,3 +1,3 @@ sub triple($n) { 3 * $n } -my &f = &triple ∘ &prefix:<-> ∘ { $^n + 2 }; +my &f = &triple ∘ &[-] ∘ { $^n + 2 }; say &f(5); # Prints "-21". diff --git a/Task/Function-composition/PostScript/function-composition.ps b/Task/Function-composition/PostScript/function-composition.ps index 778c2afc2e..a7a9ca0aa2 100644 --- a/Task/Function-composition/PostScript/function-composition.ps +++ b/Task/Function-composition/PostScript/function-composition.ps @@ -1,7 +1,12 @@ +/compose { % f g -> { g f } + [ 3 1 roll exch + % procedures are not executed when encountered directly + % insert an 'exec' after procedures, but not after operators + 1 index type /operatortype ne { /exec cvx exch } if + dup type /operatortype ne { /exec cvx } if + ] cvx +} def + /square { dup mul } def /plus1 { 1 add } def -/sqPlus1{ square plus1 } def - -% if the task really demands we make a function called "compose", well -/compose { def } def % so now we can say: -/sqPlus1 { square plus1 } compose +/sqPlus1 /square load /plus1 load compose def diff --git a/Task/Function-composition/REXX/function-composition.rexx b/Task/Function-composition/REXX/function-composition.rexx index 4f3fba4bdb..5036f78de6 100644 --- a/Task/Function-composition/REXX/function-composition.rexx +++ b/Task/Function-composition/REXX/function-composition.rexx @@ -1,3 +1,3 @@ -compose: procedure; parse arg f,g,x; interpret 'return' f"(" g'(' x "))" +compose: procedure; parse arg f,g,x; interpret 'return' f"(" g'(' x "))" -exit /*control never gets here, but this was added just in case.*/ +exit /*control should never gets here, but this was added just in case.*/ diff --git a/Task/Function-composition/Rust/function-composition-1.rust b/Task/Function-composition/Rust/function-composition-1.rust new file mode 100644 index 0000000000..2ac6b8943b --- /dev/null +++ b/Task/Function-composition/Rust/function-composition-1.rust @@ -0,0 +1,6 @@ +fn compose<'a,F,G,T,U,V>(f: F, g: G) -> Box V + 'a> + where F: Fn(U) -> V + 'a, + G: Fn(T) -> U + 'a, +{ + Box::new(move |x| f(g(x))) +} diff --git a/Task/Function-composition/Rust/function-composition-2.rust b/Task/Function-composition/Rust/function-composition-2.rust new file mode 100644 index 0000000000..afa603e27d --- /dev/null +++ b/Task/Function-composition/Rust/function-composition-2.rust @@ -0,0 +1,7 @@ +#![feature(conservative_impl_trait)] +fn compose<'a,F,G,T,U,V>(f: F, g: G) -> impl Fn(T) -> V + 'a + where F: Fn(U) -> V + 'a, + G: Fn(T) -> U + 'a, +{ + move |x| f(g(x)) +} diff --git a/Task/Function-composition/Sidef/function-composition.sidef b/Task/Function-composition/Sidef/function-composition.sidef index d3b91dfed1..8e057a9b2f 100644 --- a/Task/Function-composition/Sidef/function-composition.sidef +++ b/Task/Function-composition/Sidef/function-composition.sidef @@ -1,5 +1,6 @@ func compose(f, g) { - func(x) { f(g(x)) }; -}; -var fg = compose(func(x){Math.sin(x)}, func(x){Math.cos(x)}); -say fg(0.5); # => 0.7691963548410084218525147580510688880995 + func(x) { f(g(x)) } +} + +var fg = compose(func(x){ sin(x) }, func(x){ cos(x) }) +say fg(0.5) # => 0.76919635484100842185251475805107 diff --git a/Task/Function-composition/Zkl/function-composition-1.zkl b/Task/Function-composition/Zkl/function-composition-1.zkl new file mode 100644 index 0000000000..0702a1adcd --- /dev/null +++ b/Task/Function-composition/Zkl/function-composition-1.zkl @@ -0,0 +1 @@ +Utils.Helpers.fcomp('+(1),'*(2))(5) //-->11 diff --git a/Task/Function-composition/Zkl/function-composition-2.zkl b/Task/Function-composition/Zkl/function-composition-2.zkl new file mode 100644 index 0000000000..57742fa171 --- /dev/null +++ b/Task/Function-composition/Zkl/function-composition-2.zkl @@ -0,0 +1,2 @@ +fcn fcomp(f,g,h,etc){ + { fcn(x,hgf){ T(x).pump(Void,hgf.xplode()) }.fp1(vm.arglist.reverse()); } diff --git a/Task/Function-definition/ALGOL-M/function-definition.algol-m b/Task/Function-definition/ALGOL-M/function-definition.algol-m new file mode 100644 index 0000000000..c353bb2149 --- /dev/null +++ b/Task/Function-definition/ALGOL-M/function-definition.algol-m @@ -0,0 +1,5 @@ +INTEGER FUNCTION MULTIPLY( A, B ); +INTEGER A, B; +BEGIN + MULTIPLY := A * B; +END; diff --git a/Task/Function-definition/Bc/function-definition.bc b/Task/Function-definition/Bc/function-definition.bc new file mode 100644 index 0000000000..8ee286862f --- /dev/null +++ b/Task/Function-definition/Bc/function-definition.bc @@ -0,0 +1,3 @@ +define multiply(a, b) { return a*b } + +print multiply(2, 3) diff --git a/Task/Function-definition/Dc/function-definition-1.dc b/Task/Function-definition/Dc/function-definition-1.dc new file mode 100644 index 0000000000..a0beadcf35 --- /dev/null +++ b/Task/Function-definition/Dc/function-definition-1.dc @@ -0,0 +1 @@ +[*] sm diff --git a/Task/Function-definition/Dc/function-definition-2.dc b/Task/Function-definition/Dc/function-definition-2.dc new file mode 100644 index 0000000000..0f107bd470 --- /dev/null +++ b/Task/Function-definition/Dc/function-definition-2.dc @@ -0,0 +1,2 @@ +3 4 lm x f += 12 diff --git a/Task/Function-definition/Elena/function-definition-1.elena b/Task/Function-definition/Elena/function-definition-1.elena new file mode 100644 index 0000000000..18afdad38b --- /dev/null +++ b/Task/Function-definition/Elena/function-definition-1.elena @@ -0,0 +1,2 @@ +real multiply(RealNumber a, RealNumber b) + = a * b. diff --git a/Task/Function-definition/Elena/function-definition-2.elena b/Task/Function-definition/Elena/function-definition-2.elena new file mode 100644 index 0000000000..01b0be4ff0 --- /dev/null +++ b/Task/Function-definition/Elena/function-definition-2.elena @@ -0,0 +1 @@ +symbol f := (:x:y)(x * y). diff --git a/Task/Function-definition/Elm/function-definition.elm b/Task/Function-definition/Elm/function-definition.elm new file mode 100644 index 0000000000..15c35e5c31 --- /dev/null +++ b/Task/Function-definition/Elm/function-definition.elm @@ -0,0 +1,7 @@ +--There are multiple ways to create a function in Elm + +--This is a named function +multiply x y = x*y + +--This is an anonymous function +\x y -> x*y diff --git a/Task/Function-definition/Gambas/function-definition.gambas b/Task/Function-definition/Gambas/function-definition.gambas new file mode 100644 index 0000000000..82a51ee383 --- /dev/null +++ b/Task/Function-definition/Gambas/function-definition.gambas @@ -0,0 +1,11 @@ +Public Sub Main() + +Print Multiply(56, 4.66) + +End + +Public Sub Multiply(f1 As Float, f2 As Float) As Float + +Return f1 * f2 + +End diff --git a/Task/Function-definition/Halon/function-definition.halon b/Task/Function-definition/Halon/function-definition.halon new file mode 100644 index 0000000000..95481dbe0b --- /dev/null +++ b/Task/Function-definition/Halon/function-definition.halon @@ -0,0 +1,4 @@ +function multiply( $a, $b ) +{ + return $a * $b; +} diff --git a/Task/Function-definition/Hy/function-definition-1.hy b/Task/Function-definition/Hy/function-definition-1.hy new file mode 100644 index 0000000000..f31df15dc0 --- /dev/null +++ b/Task/Function-definition/Hy/function-definition-1.hy @@ -0,0 +1,2 @@ +(defn multiply [a b] + (* a b)) diff --git a/Task/Function-definition/Hy/function-definition-2.hy b/Task/Function-definition/Hy/function-definition-2.hy new file mode 100644 index 0000000000..8fb24bb8fe --- /dev/null +++ b/Task/Function-definition/Hy/function-definition-2.hy @@ -0,0 +1 @@ +(def multiply (fn [a b] (* a b))) diff --git a/Task/Function-definition/IWBASIC/function-definition.iwbasic b/Task/Function-definition/IWBASIC/function-definition.iwbasic new file mode 100644 index 0000000000..202d842760 --- /dev/null +++ b/Task/Function-definition/IWBASIC/function-definition.iwbasic @@ -0,0 +1,96 @@ +'1. Not Object Oriented Program + +DECLARE Multiply(N1:INT,N2:INT),INT + +DEF A,B:INT + +A=2:B=2 + +OPENCONSOLE + +PRINT Multiply(A,B) + +PRINT + +'When compiled as a console only program, a press any key to continue is automatic. +CLOSECONSOLE + +END + +SUB Multiply(N1:INT,N2:INT),INT + + DEF Product:INT + + Product=N1*N2 + +RETURN Product +ENDSUB + +'Can also be written with no code in the subroutine and just RETURN N1*N2. + +---- + +'2. Not Object Oriented Program Using A Macro + +$MACRO Multiply (N1,N2) (N1*N2) + +DEF A,B:INT + +A=5:B=5 + +OPENCONSOLE + +PRINT Multiply (A,B) + +PRINT + +'When compiled as a console only program, a press any key to continue is automatic. +CLOSECONSOLE + +END + +---- + +'3. In An Object Oriented Program + +CLASS Associate +'functions/methods +DECLARE Associate:'object constructor +DECLARE _Associate:'object destructor +'***Multiply declared*** +DECLARE Multiply(UnitsSold:UINT),UINT +'members +DEF m_Price:UINT +DEF m_UnitsSold:UINT +DEF m_SalesTotal:UINT +ENDCLASS + +DEF Emp:Associate + +m_UnitsSold=10 + +Ass.Multiply(m_UnitsSold) + +OPENCONSOLE + +PRINT"Sales total: ",:PRINT"$"+LTRIM$(STR$(Emp.m_SalesTotal)) + +PRINT + +CLOSECONSOLE + +END + +'m_price is set in constructor +SUB Associate::Multiply(UnitsSold:UINT),UINT + m_SalesTotal=m_Price*UnitsSold + RETURN m_SalesTotal +ENDSUB + +SUB Associate::Associate() + m_Price=10 +ENDSUB + +SUB Associate::_Associate() +'Nothing to cleanup +ENDSUB diff --git a/Task/Function-definition/jq/function-definition-1.jq b/Task/Function-definition/Jq/function-definition-1.jq similarity index 100% rename from Task/Function-definition/jq/function-definition-1.jq rename to Task/Function-definition/Jq/function-definition-1.jq diff --git a/Task/Function-definition/jq/function-definition-2.jq b/Task/Function-definition/Jq/function-definition-2.jq similarity index 100% rename from Task/Function-definition/jq/function-definition-2.jq rename to Task/Function-definition/Jq/function-definition-2.jq diff --git a/Task/Function-definition/jq/function-definition-3.jq b/Task/Function-definition/Jq/function-definition-3.jq similarity index 100% rename from Task/Function-definition/jq/function-definition-3.jq rename to Task/Function-definition/Jq/function-definition-3.jq diff --git a/Task/Function-definition/jq/function-definition-4.jq b/Task/Function-definition/Jq/function-definition-4.jq similarity index 100% rename from Task/Function-definition/jq/function-definition-4.jq rename to Task/Function-definition/Jq/function-definition-4.jq diff --git a/Task/Function-definition/MATLAB/function-definition.m b/Task/Function-definition/MATLAB/function-definition.m deleted file mode 100644 index efd709df93..0000000000 --- a/Task/Function-definition/MATLAB/function-definition.m +++ /dev/null @@ -1,3 +0,0 @@ -function C = multiply(A,B) - C = A*B; -end diff --git a/Task/Function-definition/Nimrod/function-definition-1.nimrod b/Task/Function-definition/Nimrod/function-definition-1.nimrod deleted file mode 100644 index e7b62db71b..0000000000 --- a/Task/Function-definition/Nimrod/function-definition-1.nimrod +++ /dev/null @@ -1,2 +0,0 @@ -proc multiply(a, b: Int): Int = - result = a * b diff --git a/Task/Function-definition/Nimrod/function-definition-2.nimrod b/Task/Function-definition/Nimrod/function-definition-2.nimrod deleted file mode 100644 index 508013d357..0000000000 --- a/Task/Function-definition/Nimrod/function-definition-2.nimrod +++ /dev/null @@ -1,2 +0,0 @@ -proc multiply(a, b: Int): Int = - return a * b diff --git a/Task/Function-definition/OASYS-Assembler/function-definition.oasys b/Task/Function-definition/OASYS-Assembler/function-definition.oasys new file mode 100644 index 0000000000..a1ea42acdd --- /dev/null +++ b/Task/Function-definition/OASYS-Assembler/function-definition.oasys @@ -0,0 +1 @@ +[&MULTIPLY#,A#,B#],A#<,B# 13.5 diff --git a/Task/Function-definition/Zkl/function-definition-3.zkl b/Task/Function-definition/Zkl/function-definition-3.zkl new file mode 100644 index 0000000000..48473eb38d --- /dev/null +++ b/Task/Function-definition/Zkl/function-definition-3.zkl @@ -0,0 +1,2 @@ +fcn multiply{vm.arglist.reduce('*)} +multiply(1,2,3,4,5) //--> 120 diff --git a/Task/Function-definition/Zkl/function-definition-4.zkl b/Task/Function-definition/Zkl/function-definition-4.zkl new file mode 100644 index 0000000000..164713355e --- /dev/null +++ b/Task/Function-definition/Zkl/function-definition-4.zkl @@ -0,0 +1 @@ +var mul=Op("*"); mul(4,5) //-->20 diff --git a/Task/Function-frequency/Sidef/function-frequency.sidef b/Task/Function-frequency/Sidef/function-frequency.sidef index 000bc54e16..5f2552719b 100644 --- a/Task/Function-frequency/Sidef/function-frequency.sidef +++ b/Task/Function-frequency/Sidef/function-frequency.sidef @@ -1,15 +1,10 @@ -var program = <<'EOT' func foo { } func bar { } foo(); foo(); foo() bar(); bar(); -EOT -var parser = Parser.new # initialize a new parser -parser.parse_script( code => program ) # parse the code - -var data = Perl.to_sidef(parser{:vars}{:main}).flatten +var data = Perl.to_sidef(Parser{:vars}{:main}).flatten data.sort_by { |v| -v{:count} }.first(10).each { |entry| if (entry{:type} == :func) { diff --git a/Task/Function-prototype/C-sharp/function-prototype-1.cs b/Task/Function-prototype/C-sharp/function-prototype-1.cs new file mode 100644 index 0000000000..cf2f3729fb --- /dev/null +++ b/Task/Function-prototype/C-sharp/function-prototype-1.cs @@ -0,0 +1,12 @@ +using System; +abstract class Printer +{ + public abstract void Print(); +} + +class PrinterImpl : Printer +{ + public override void Print() { + Console.WriteLine("Hello world!"); + } +} diff --git a/Task/Function-prototype/C-sharp/function-prototype-2.cs b/Task/Function-prototype/C-sharp/function-prototype-2.cs new file mode 100644 index 0000000000..26f19cb511 --- /dev/null +++ b/Task/Function-prototype/C-sharp/function-prototype-2.cs @@ -0,0 +1,22 @@ +using System; +public delegate int IntFunction(int a, int b); + +public class Program +{ + public static int Add(int x, int y) { + return x + y; + } + + public static int Multiply(int x, int y) { + return x * y; + } + + public static void Main() { + IntFunction func = Add; + Console.WriteLine(func(2, 3)); //prints 5 + func = Multiply; + Console.WriteLine(func(2, 3)); //prints 6 + func += Add; + Console.WriteLine(func(2, 3)); //prints 5. Both functions are called, but only the last result is kept. + } +} diff --git a/Task/Function-prototype/C-sharp/function-prototype-3.cs b/Task/Function-prototype/C-sharp/function-prototype-3.cs new file mode 100644 index 0000000000..db79e15a4b --- /dev/null +++ b/Task/Function-prototype/C-sharp/function-prototype-3.cs @@ -0,0 +1,20 @@ +//file1.cs +public partial class Program +{ + partial void Print(); +} + +//file2.cs +using System; + +public partial class Program +{ + partial void Print() { + Console.WriteLine("Hello world!"); + } + + static void Main() { + Program p = new Program(); + p.Print(); //If the implementation above is not written, the compiler will remove this line. + } +} diff --git a/Task/Function-prototype/Kotlin/function-prototype.kotlin b/Task/Function-prototype/Kotlin/function-prototype.kotlin new file mode 100644 index 0000000000..1844c0dfd4 --- /dev/null +++ b/Task/Function-prototype/Kotlin/function-prototype.kotlin @@ -0,0 +1,35 @@ +// version 1.0.6 + +interface MyInterface { + fun foo() // no arguments, no return type + fun goo(i: Int, j: Int) // two arguments, no return type + fun voo(vararg v: Int) // variable number of arguments, no return type + fun ooo(o: Int = 1): Int // optional argument with default value and return type Int + fun roo(): Int // no arguments with return type Int + val poo: Int // read only property of type Int +} + +abstract class MyAbstractClass { + abstract fun afoo() // abstract member function, no arguments or return type + abstract var apoo: Int // abstract read/write member property of type Int +} + +class Derived : MyAbstractClass(), MyInterface { + override fun afoo() {} + override var apoo: Int = 0 + + override fun foo() {} + override fun goo(i: Int, j: Int) {} + override fun voo(vararg v: Int) {} + override fun ooo(o: Int): Int = o // can't specify default argument again here but same as in interface + override fun roo(): Int = 2 + override val poo: Int = 3 +} + +fun main(args: Array) { + val d = Derived() + println(d.apoo) + println(d.ooo()) // default argument of 1 inferred + println(d.roo()) + println(d.poo) +} diff --git a/Task/Function-prototype/Phix/function-prototype.phix b/Task/Function-prototype/Phix/function-prototype.phix new file mode 100644 index 0000000000..e0de53dfb6 --- /dev/null +++ b/Task/Function-prototype/Phix/function-prototype.phix @@ -0,0 +1,5 @@ +forward function noargs() -- Declare a function with no arguments +forward procedure twoargs(integer a, integer b) -- Declare a procedure with two arguments +forward procedure twoargs(integer, integer /*b*/) -- Parameter names are optional in forward (and actual) definitions +forward function anyargs(sequence s) -- varargs are [best/often] handled as a (single) sequence in Phix +forward function atleastonearg(integer a, integer b=1, ...); -- Default makes args optional (== actual defn) diff --git a/Task/Function-prototype/SNOBOL4/function-prototype-1.sno b/Task/Function-prototype/SNOBOL4/function-prototype-1.sno new file mode 100644 index 0000000000..ba8a149b11 --- /dev/null +++ b/Task/Function-prototype/SNOBOL4/function-prototype-1.sno @@ -0,0 +1,8 @@ + define('multiply(a,b)') :(mul_end) +multiply multiply = a * b :(return) +mul_end + +* Test + output = multiply(10.1,12.2) + output = multiply(10,12) +end diff --git a/Task/Function-prototype/SNOBOL4/function-prototype-2.sno b/Task/Function-prototype/SNOBOL4/function-prototype-2.sno new file mode 100644 index 0000000000..51cbfc1948 --- /dev/null +++ b/Task/Function-prototype/SNOBOL4/function-prototype-2.sno @@ -0,0 +1,21 @@ + define('multiply(a,b)') + +* +* Assume lots more code goes here. +* + :(test) + +* +* MORE CODE! +* + +multiply multiply = a * b :(return) + +* +* MORE CODE! +* + +test + output = multiply(10.1,12.2) + output = multiply(10,12) +end diff --git a/Task/Function-prototype/SNOBOL4/function-prototype-3.sno b/Task/Function-prototype/SNOBOL4/function-prototype-3.sno new file mode 100644 index 0000000000..78ce58bfd7 --- /dev/null +++ b/Task/Function-prototype/SNOBOL4/function-prototype-3.sno @@ -0,0 +1,10 @@ + define('multiply(a,b)acc1,acc2','mult_impl') :(mult_end) +mult_impl acc1 = a + acc2 = b + multiply = acc1 * acc2 :(return) +mult_end + +* Test + output = multiply(10.1,12.2) + output = multiply(10,12) +end diff --git a/Task/Function-prototype/Zkl/function-prototype.zkl b/Task/Function-prototype/Zkl/function-prototype.zkl new file mode 100644 index 0000000000..3c259dcdfa --- /dev/null +++ b/Task/Function-prototype/Zkl/function-prototype.zkl @@ -0,0 +1,24 @@ +fcn{"Hello World"} // no expected args +fcn(){"Hello World"} // ditto + +fcn{vm.arglist}(1,2) // ask the VM for the passed in args -->L(1,2) +fcn f(a,b){a+b} // fcn(1,2,3) works just fine +fcn f(args){}(1,2,3) //args = 1 +fcn(args){vm.arglist.sum()}(1,2,3) //-->6 + +fcn(a=1,b=2){vm.arglist}() //-->L(1,2) +fcn(a=1,b=2){vm.arglist}(5) //-->L(5,2) +fcn(a=1,b){vm.arglist}() //-->L(1), error if you try to use b +fcn(a,b=2){vm.arglist}(5) //-->L(5,2) +fcn(a,b=2,c){vm.arglist}(1) //-->L(1,2) + +fcn(){vm.nthArg(1)}(5,6) //-->6 +fcn{vm.numArgs}(1,2,3,4,5,6,7,8,9) //-->9 +fcn{vm.argsMatch(...)} // a somewhat feeble attempt arg pattern matching based on type (vs value) + + // you can do list assignment in the prototype: +fcn(a,[(b,c)],d){vm.arglist}(1,L(2,3,4),5) //-->L(1,L(2,3,4),5) +fcn(a,[(b,c)],d){"%s,%s,%s,%s".fmt(a,b,c,d)}(1,L(2,3,4),5) //-->1,2,3,5 + + // no type enforcement but you can give a hint to the compiler +fcn([Int]n){n.sin()} //--> syntax error as Ints don't do sin diff --git a/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions-1.egl b/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions-1.egl deleted file mode 100644 index bc7b40f449..0000000000 --- a/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions-1.egl +++ /dev/null @@ -1,5 +0,0 @@ -browser Browser{}; -bvh int = browser.getViewportHeight(); -bvw int = browser.getViewportWidth(); -SysLib.writeStdout("ViewportHeight: " + bvh); -SysLib.writeStdout("ViewportWidth: " + bvw); diff --git a/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions-2.egl b/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions-2.egl deleted file mode 100644 index 8079f1ca5c..0000000000 --- a/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions-2.egl +++ /dev/null @@ -1,2 +0,0 @@ -FMain.Maximized = True -FMain.Visible = False ' The form can be invisible diff --git a/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions-3.egl b/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions-3.egl deleted file mode 100644 index b9a1b98527..0000000000 --- a/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions-3.egl +++ /dev/null @@ -1,7 +0,0 @@ -PUBLIC SUB _new() - -END - -PUBLIC SUB Form_Open() - -END diff --git a/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions-4.egl b/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions-4.egl deleted file mode 100644 index 62c047491e..0000000000 --- a/Task/GUI-Maximum-window-dimensions/EGL/gui-maximum-window-dimensions-4.egl +++ /dev/null @@ -1,3 +0,0 @@ -PUBLIC SUB Form_Resize() - PRINT "The maximum window size that can be used without scrolling is "; FMain.Width; " x "; FMain.Height -END diff --git a/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-3.fbsl b/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-3.fbsl deleted file mode 100644 index 8079f1ca5c..0000000000 --- a/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-3.fbsl +++ /dev/null @@ -1,2 +0,0 @@ -FMain.Maximized = True -FMain.Visible = False ' The form can be invisible diff --git a/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-4.fbsl b/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-4.fbsl deleted file mode 100644 index b9a1b98527..0000000000 --- a/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-4.fbsl +++ /dev/null @@ -1,7 +0,0 @@ -PUBLIC SUB _new() - -END - -PUBLIC SUB Form_Open() - -END diff --git a/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-5.fbsl b/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-5.fbsl deleted file mode 100644 index 62c047491e..0000000000 --- a/Task/GUI-Maximum-window-dimensions/FBSL/gui-maximum-window-dimensions-5.fbsl +++ /dev/null @@ -1,3 +0,0 @@ -PUBLIC SUB Form_Resize() - PRINT "The maximum window size that can be used without scrolling is "; FMain.Width; " x "; FMain.Height -END diff --git a/Task/GUI-Maximum-window-dimensions/Gambas/gui-maximum-window-dimensions.gambas b/Task/GUI-Maximum-window-dimensions/Gambas/gui-maximum-window-dimensions.gambas new file mode 100644 index 0000000000..25af5db2bc --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/Gambas/gui-maximum-window-dimensions.gambas @@ -0,0 +1,6 @@ +Public Sub Form_Open() + +Print Desktop.Width +Print Desktop.Height + +End diff --git a/Task/GUI-Maximum-window-dimensions/IWBASIC/gui-maximum-window-dimensions.iwbasic b/Task/GUI-Maximum-window-dimensions/IWBASIC/gui-maximum-window-dimensions.iwbasic new file mode 100644 index 0000000000..67341cec8c --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/IWBASIC/gui-maximum-window-dimensions.iwbasic @@ -0,0 +1,35 @@ +DEF Win:WINDOW +DEF Close:CHAR + +DEF ScreenSizeX,ScreenSizeY:UINT +DEF L,T,ClientWidth,ClientHeight:INT + +GETSCREENSIZE(ScreenSizeX,ScreenSizeY) + +OPENWINDOW Win,0,0,ScreenSizeX,ScreenSizeY,@MAXBOX|@MINBOX|@SIZE|@MAXIMIZED,NULL,"Get client area",&MainHandler + +'Left and top are always zero for this function. +GETCLIENTSIZE (Win,L,T,ClientWidth,ClientHeight) + +PRINT Win,"Maximum drawing area values: width is"+STR$(ClientWidth)+" and height is"+STR$(ClientHeight)+"." + +WAITUNTIL Close=1 + +CLOSEWINDOW WIN + +END + +SUB MainHandler + + SELECT @MESSAGE + + CASE @IDCLOSEWINDOW + + Close=1 + + ENDSELECT + +RETURN +ENDSUB + +Output: Maximum drawing area values: width is 1280 and height is 749. diff --git a/Task/GUI-Maximum-window-dimensions/Kotlin/gui-maximum-window-dimensions.kotlin b/Task/GUI-Maximum-window-dimensions/Kotlin/gui-maximum-window-dimensions.kotlin new file mode 100644 index 0000000000..4fc9042042 --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/Kotlin/gui-maximum-window-dimensions.kotlin @@ -0,0 +1,24 @@ +// version 1.1 + +import java.awt.Toolkit +import javax.swing.JFrame + +class Test : JFrame() { + init { + val r = Regex("""\[.*\]""") + val toolkit = Toolkit.getDefaultToolkit() + val screenSize = toolkit.screenSize + println("Physical screen size : ${formatOutput(screenSize, r)}") + val insets = toolkit.getScreenInsets(graphicsConfiguration) + println("Insets : ${formatOutput(insets, r)}") + screenSize.width -= (insets.left + insets.right) + screenSize.height -= (insets.top + insets.bottom) + println("Max available : ${formatOutput(screenSize, r)}") + } + + private fun formatOutput(output: Any, r: Regex) = r.find(output.toString())!!.value.replace(",", ", ") +} + +fun main(args: Array) { + Test() +} diff --git a/Task/GUI-Maximum-window-dimensions/Nimrod/gui-maximum-window-dimensions.nimrod b/Task/GUI-Maximum-window-dimensions/Nimrod/gui-maximum-window-dimensions.nimrod deleted file mode 100644 index bf0af51a53..0000000000 --- a/Task/GUI-Maximum-window-dimensions/Nimrod/gui-maximum-window-dimensions.nimrod +++ /dev/null @@ -1,7 +0,0 @@ -import - gtk2, gdk2 - -nimrod_init() -var w = gdk2.screen_width() -var h = gdk2.screen_height() -echo("WxH=",w,"x",h) diff --git a/Task/GUI-Maximum-window-dimensions/Phix/gui-maximum-window-dimensions.phix b/Task/GUI-Maximum-window-dimensions/Phix/gui-maximum-window-dimensions.phix new file mode 100644 index 0000000000..dabc2c3da1 --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/Phix/gui-maximum-window-dimensions.phix @@ -0,0 +1,15 @@ +include pGUI.e + +IupOpen() + +string scrnFullSize = IupGetGlobal("FULLSIZE") +string scrnSize = IupGetGlobal("SCREENSIZE") +string scrnMInfo = IupGetGlobal("MONITORSINFO") +string scrnVScreen = IupGetGlobal("VIRTUALSCREEN") + +Ihandle dlg = IupDialog(NULL,"SIZE=FULL") +string scrnXSize = IupGetAttribute(dlg,"MAXSIZE") + +?{scrnFullSize, scrnSize, scrnMInfo, scrnVScreen, scrnXSize} + +IupClose() diff --git a/Task/GUI-Maximum-window-dimensions/Python/gui-maximum-window-dimensions.py b/Task/GUI-Maximum-window-dimensions/Python/gui-maximum-window-dimensions.py new file mode 100644 index 0000000000..cf72c7c05c --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/Python/gui-maximum-window-dimensions.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python3 + +import tkinter as tk # import the module. + +root = tk.Tk() # Create an instance of the class. +root.state('zoomed') # Maximized the window. +root.update_idletasks() # Update the display. +tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())), + font=("Helvetica", 25)).pack() # add a label and set the size to text. +root.mainloop() diff --git a/Task/GUI-component-interaction/00DESCRIPTION b/Task/GUI-component-interaction/00DESCRIPTION index 5471208bb1..9738abd180 100644 --- a/Task/GUI-component-interaction/00DESCRIPTION +++ b/Task/GUI-component-interaction/00DESCRIPTION @@ -1,5 +1,6 @@ {{omit from|ACL2}} {{omit from|Applesoft BASIC|no concept of a GUI}} +{{omit from|Commodore BASIC}} {{omit from|AWK|no concept of a GUI}} {{omit from|Batch File}} {{omit from|Blast}} diff --git a/Task/GUI-component-interaction/Delphi/gui-component-interaction-2.delphi b/Task/GUI-component-interaction/Delphi/gui-component-interaction-2.delphi index e4e70e8515..075d75a4c6 100644 --- a/Task/GUI-component-interaction/Delphi/gui-component-interaction-2.delphi +++ b/Task/GUI-component-interaction/Delphi/gui-component-interaction-2.delphi @@ -28,18 +28,19 @@ implementation {$R *.dfm} procedure TForm1.EditInputFieldChange(Sender: TObject); +Var + Value: Integer; begin - TRY - StrToInt(EditInputField.Text); - EXCEPT - ShowMessage('Error! The Input Value is not numeric!'); + if not TryStrToInt(EditInputField.Text, value) then + begin + ShowMessage('Error! The Input Value is not numeric!'); EditInputField.Text := '0'; - END; + end; end; procedure TForm1.ButtonIncrementClick(Sender: TObject); begin - EditInputField.text := IntToStr(StrToInt(EditInputField.Text) + 1); + EditInputField.text := IntToStr (StrToInt(EditInputField.Text) + 1); end; procedure TForm1.ButtonRandomClick(Sender: TObject); diff --git a/Task/GUI-component-interaction/EchoLisp/gui-component-interaction.echolisp b/Task/GUI-component-interaction/EchoLisp/gui-component-interaction.echolisp new file mode 100644 index 0000000000..7d6b954007 --- /dev/null +++ b/Task/GUI-component-interaction/EchoLisp/gui-component-interaction.echolisp @@ -0,0 +1,40 @@ +(require 'interface) + +;; helper new button with text +(define (ui-add-button text) + (define b (ui-create-element "button" '((type "button")))) + (ui-set-html b text) + (ui-add b)) + + +(define (panel ) + (ui-clear) + (info-text "My rosetta application" "blue") + +;; input field (checked for numeric) + (define f-input (ui-create-element "input" '((type number)))) + (ui-set-value f-input 0) + (ui-add f-input) + (ui-on-focus f-input (lambda(e) (info-text ""))) + +;; Increment button + (define btn-inc (ui-add-button "Increment")) + (define (increment elem) + (define val (ui-get-numvalue f-input)) + (if val ;; checked legal numeric + (ui-set-value f-input (1+ val)) + (info-text "Need a number" "red"))) + (ui-on-click btn-inc increment) + (ui-add btn-inc) + + (define btn-random (ui-add-button "Random")) + (define (set-random elem) + (when (confirm "Really random?") + (ui-set-value f-input (random-prime 1000000)))) + (ui-on-click btn-random set-random) + + (ui-focus btn-inc) + (stdout-hide #t) + (stdin-hide #t)) ;; end panel + +(panel) diff --git a/Task/GUI-component-interaction/Elena/gui-component-interaction.elena b/Task/GUI-component-interaction/Elena/gui-component-interaction.elena index 851be83677..e2a3940349 100644 --- a/Task/GUI-component-interaction/Elena/gui-component-interaction.elena +++ b/Task/GUI-component-interaction/Elena/gui-component-interaction.elena @@ -1,70 +1,70 @@ -#import system. -#import forms. -#import extensions. - -#class Window +import forms. +import extensions. +class Window { - #field form. - #field btmIncrement. - #field btmRandom. - #field txtNumber. + object form. + object btmIncrement. + object btmRandom. + object txtNumber. - #constructor new + constructor new [ form := SDIDialog new. btmIncrement := Button new. btmRandom := Button new. txtNumber := Edit new. - form controls - += btmIncrement - += btmRandom - += txtNumber. + form controls; + append:btmIncrement; + append:btmRandom; + append:txtNumber. - form set &caption:"Rosseta Code". - form set &x:100 &y:100. - form set &width:160 &height:120. + form + set caption:"Rosseta Code"; + set x:100 y:100; + set width:160 height:120. - txtNumber set &x:7 &y:7. - txtNumber set &width:140 &height:25. - txtNumber set &caption:"0". + txtNumber + set x:7 y:7; + set width:140 height:25; + set caption:"0". - btmIncrement set &x:7 &y:35. - btmIncrement set &width:140 &height:25. - btmIncrement set &caption:"Increment". - btmIncrement set &onClick:args + btmIncrement + set x:7 y:35; + set width:140 height:25; + set caption:"Increment"; + set onClick: (:args) + [ $self $onButtonIncrementClick ]. - [ $self $onButtonIncrementClick. ]. - - btmRandom set &x:7 &y:65. - btmRandom set &width:140 &height:25. - btmRandom set &caption:"Random". - btmRandom set &onClick:args - - [ $self $onButtonRandomClick. ]. + btmRandom + set x:7 y:65; + set width:140 height:25; + set caption:"Random"; + set onClick(:args) + [ $self $onButtonRandomClick ] ] - #method $onButtonIncrementClick + $onButtonIncrementClick [ - #var number := txtNumber value toInt. + var number := txtNumber value; toInt. number := number + 1. $self $changeTextBoxValue:number. ] - #method $onButtonRandomClick + $onButtonRandomClick [ - (messageDialog open &caption:"Inf" &question:"Really reset to random value?")? + if(messageDialog open caption:"Inf" question:"Really reset to random value?") [ - $self $changeTextBoxValue:(randomGenerator eval:99999999). - ]. + $self $changeTextBoxValue(randomGenerator eval:99999999) + ] ] - #method $changeTextBoxValue : number + $changeTextBoxValue : number [ - txtNumber set &caption:(number literal). + txtNumber set caption(number literal). ] - #method => form. + dispatch => form. } diff --git a/Task/GUI-component-interaction/Gambas/gui-component-interaction.gambas b/Task/GUI-component-interaction/Gambas/gui-component-interaction.gambas new file mode 100644 index 0000000000..e807076825 --- /dev/null +++ b/Task/GUI-component-interaction/Gambas/gui-component-interaction.gambas @@ -0,0 +1,56 @@ +hValueBox As ValueBox 'We need a ValueBox + +Public Sub Form_Open() +Dim hButton As Button 'We need 2 Buttons + +With Me 'Set the Form's Properties.. + .height = 95 'Set the Height + .Width = 350 'Set the Width + .Arrangement = Arrange.Vertical 'Arrange items vertically + .Padding = 5 'Border area + .Title = "GUI component interaction" 'Title displayed on the Form +End With + +hValueBox = New ValueBox(Me) 'Add a ValueBox to the Form + +With hValueBox 'Set the ValueBox's Properties.. + .Expand = True 'Expand the ValueBox + .Value = 0 'Set it's value to 0 +End With + +hButton = New Button(Me) As "ButtonInc" 'Add a Button to the form as Event "ButtonInc" + +With hButton 'Set the Button's Properties.. + .Height = 28 'Set the Height + .Text = "&Increment" 'Add Text (The '&' adds a keyboard shortcut) +End With + +hButton = New Button(Me) As "ButtonRand" 'Add a Button to the form as Event "ButtonRand" + +With hButton 'Set the Button's Properties.. + .Height = 28 'Set the Height + .Text = "&Random" 'Add Text (The '&' adds a keyboard shortcut) +End With + +End + +Public Sub ButtonInc_Click() 'When the 'Increment' Button is clicked.. + +hValueBox.Value += 1 'Increase the Value in the ValueBox by 1 + +End + +Public Sub ButtonRand_Click() 'When the 'Random' Button is clicked.. +Dim siRand As Short 'To store random number +Dim byAnswer As Byte 'To store the answer to the MessageBox question + +siRand = Rand(1, 32767) 'Create a 'Random' mnumber + +byAnswer = Message.Question("Would you like to set the ValueBox to " & siRand & "?", "Yes", "No") ' Ask if the number is OK +If byAnswer = 1 Then 'If the user says 'Yes' then + hValueBox.Value = siRand 'Display the 'Random' number in the ValueBox +Else 'ELSE + hValueBox.Value = 0 'Set the ValueBox Value to 0 +End If + +End diff --git a/Task/GUI-component-interaction/Kotlin/gui-component-interaction.kotlin b/Task/GUI-component-interaction/Kotlin/gui-component-interaction.kotlin index c9844ec7fe..a9d855827e 100644 --- a/Task/GUI-component-interaction/Kotlin/gui-component-interaction.kotlin +++ b/Task/GUI-component-interaction/Kotlin/gui-component-interaction.kotlin @@ -3,50 +3,43 @@ import java.awt.event.ActionEvent import java.awt.event.ActionListener import java.awt.event.KeyEvent import java.awt.event.KeyListener - -import java.lang.Long // jet.Long doesn't suit our needs here -import javax.swing.JButton -import javax.swing.JFrame -import javax.swing.JOptionPane -import javax.swing.JPanel -import javax.swing.JTextField +import javax.swing.* class Interact : JFrame() { val numberField = JTextField() val incButton = JButton("Increment") val randButton = JButton("Random") - val buttonPanel = JPanel(); + val buttonPanel = JPanel() - { - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) - numberField setText "0" + init { + defaultCloseOperation = JFrame.EXIT_ON_CLOSE + numberField.text = "0" - numberField addKeyListener(object : KeyListener { - public override fun keyTyped(e : KeyEvent) : Unit = - if(!Character.isDigit(e.getKeyChar())) e.consume() - public override fun keyReleased(e : KeyEvent?) {} - public override fun keyPressed(e : KeyEvent) {} - }); - - incButton addActionListener(object : ActionListener { - public override fun actionPerformed(e : ActionEvent) { - val num = Long.parseLong(numberField.getText() ?: "") - numberField setText (num + 1).toString() + numberField.addKeyListener(object : KeyListener { + override fun keyTyped(e : KeyEvent) : Unit { + if (!Character.isDigit(e.keyChar)) e.consume() } - }); + override fun keyReleased(e : KeyEvent?) {} + override fun keyPressed(e : KeyEvent) {} + }) - randButton addActionListener(object : ActionListener { + incButton.addActionListener { + val num = (numberField.text ?: "").toDouble() + numberField.text = (num + 1).toString() + } + + randButton.addActionListener(object : ActionListener { fun proceedOrNot() = JOptionPane.showConfirmDialog(randButton, "Are you sure?") - public override fun actionPerformed(e : ActionEvent) { + override fun actionPerformed(e : ActionEvent) { if(proceedOrNot() == JOptionPane.YES_OPTION) - numberField setText Long.toString((Math.random() * Long.MAX_VALUE).toLong()) + numberField.text = (Math.random() * Long.MAX_VALUE).toString() } - }); + }) - setLayout(GridLayout(2, 1)) - buttonPanel setLayout GridLayout(1, 2) - buttonPanel add incButton - buttonPanel add randButton + layout = GridLayout(2, 1) + buttonPanel.layout = GridLayout(1, 2) + buttonPanel.add(incButton) + buttonPanel.add(randButton) add(numberField) add(buttonPanel) pack() @@ -54,5 +47,5 @@ class Interact : JFrame() { } fun main(args : Array) { - Interact() setVisible(true) + Interact().isVisible = true } diff --git a/Task/GUI-component-interaction/Nimrod/gui-component-interaction.nimrod b/Task/GUI-component-interaction/Nimrod/gui-component-interaction.nimrod deleted file mode 100644 index 2534d3f647..0000000000 --- a/Task/GUI-component-interaction/Nimrod/gui-component-interaction.nimrod +++ /dev/null @@ -1,68 +0,0 @@ -import - gtk2, gdk2, glib2, strutils, math - -var valu: int = 0 -var chngd_txt_hndler: gulong = 0 - -proc thisDestroy(widget: pWidget, data: pgpointer) {.cdecl.} = - main_quit() - -randomize() -nimrod_init() -var win = window_new(gtk2.WINDOW_TOPLEVEL) -var content = vbox_new(TRUE,10) -var hbox1 = hbox_new(TRUE,10) -var hbox2 = hbox_new(FALSE,1) -var lbl = label_new("Value:") -var entry_fld = entry_new() -entry_fld.set_text("0") -var btn_quit = button_new("Quit") -var btn_inc = button_new("Increment") -var btn_rnd = button_new("Random") -add(hbox2,lbl) -add(hbox2,entry_fld) -add(hbox1,btn_inc) -add(hbox1,btn_rnd) -pack_start(content, hbox2, TRUE, TRUE, 0) -pack_start(content, hbox1, TRUE, TRUE, 0) -pack_start(content, btn_quit, TRUE, TRUE, 0) -set_border_width(Win, 5) -add(win, content) - -proc on_question_clicked: Bool = - var dialog = win.message_dialog_new(0, MESSAGE_QUESTION, - BUTTONS_YES_NO, "Use a Random number?") - var response = dialog.run() - if response == RESPONSE_YES: - result = True - elif response == RESPONSE_NO: - result = False - dialog.destroy() - -proc thisInc(widget: pWidget, data: pgpointer){.cdecl.} = - inc(valu) - entry_fld.set_text($valu) - -proc thisRnd(widget: pWidget, data: pgpointer){.cdecl.} = - if on_question_clicked(): - valu = random(20) - entry_fld.set_text($valu) - -proc thisTextChanged(widget: pWidget, data: pgpointer) {.cdecl.} = - #signal_handler_block(entry_fld, chngd_txt_hndler) - try: - valu = parseInt($entry_fld.get_text()) - except EInvalidValue: - valu = 0 - entry_fld.set_text($valu) - #signal_handler_unblock(entry_fld, chngd_txt_hndler) - #signal_emit_stop(entry_fld, signal_lookup("changed",TYPE_EDITABLE()),0) - -discard signal_connect(win, "destroy", SIGNAL_FUNC(thisDestroy), nil) -discard signal_connect(btn_quit, "clicked", SIGNAL_FUNC(thisDestroy), nil) -discard signal_connect(btn_inc, "clicked", SIGNAL_FUNC(thisInc), nil) -discard signal_connect(btn_rnd, "clicked", SIGNAL_FUNC(thisRnd), nil) -chngd_txt_hndler = signal_connect(entry_fld, "changed", SIGNAL_FUNC(thisTextChanged), nil) - -win.show_all() -main() diff --git a/Task/GUI-component-interaction/Phix/gui-component-interaction.phix b/Task/GUI-component-interaction/Phix/gui-component-interaction.phix index 729eee898a..a4e9c4e90a 100644 --- a/Task/GUI-component-interaction/Phix/gui-component-interaction.phix +++ b/Task/GUI-component-interaction/Phix/gui-component-interaction.phix @@ -24,14 +24,14 @@ function esc_close(Ihandle /*ih*/, atom c) return iff(c=K_ESC?IUP_CLOSE:IUP_CONTINUE) end function - IupOpen("../pGUI/") - txt = IupText(Icallback("action_cb"),"EXPAND=YES") - increment = IupButton("increment",Icallback("increment_cb")) - random = IupButton("random",Icallback("random_cb")) - hbx = IupHbox({increment,random},"MARGIN=0x10, GAP=20") - vbx = IupVbox({txt,hbx},"MARGIN=40x20") - dlg = IupDialog(vbx) - IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) - IupShow(dlg) - IupMainLoop() - IupClose() +IupOpen() +txt = IupText(Icallback("action_cb"),"EXPAND=YES") +increment = IupButton("increment",Icallback("increment_cb")) +random = IupButton("random",Icallback("random_cb")) +hbx = IupHbox({increment,random},"MARGIN=0x10, GAP=20") +vbx = IupVbox({txt,hbx},"MARGIN=40x20") +dlg = IupDialog(vbx) +IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) +IupShow(dlg) +IupMainLoop() +IupClose() diff --git a/Task/GUI-enabling-disabling-of-controls/00DESCRIPTION b/Task/GUI-enabling-disabling-of-controls/00DESCRIPTION index 5634048522..da9da1798a 100644 --- a/Task/GUI-enabling-disabling-of-controls/00DESCRIPTION +++ b/Task/GUI-enabling-disabling-of-controls/00DESCRIPTION @@ -1,5 +1,6 @@ {{omit from|ACL2}} {{omit from|Applesoft BASIC|no concept of a GUI}} +{{omit from|Commodore BASIC}} {{omit from|AWK|no concept of a GUI}} {{omit from|Batch File}} {{omit from|Blast}} diff --git a/Task/GUI-enabling-disabling-of-controls/Fantom/gui-enabling-disabling-of-controls-1.fantom b/Task/GUI-enabling-disabling-of-controls/Fantom/gui-enabling-disabling-of-controls.fantom similarity index 100% rename from Task/GUI-enabling-disabling-of-controls/Fantom/gui-enabling-disabling-of-controls-1.fantom rename to Task/GUI-enabling-disabling-of-controls/Fantom/gui-enabling-disabling-of-controls.fantom diff --git a/Task/GUI-enabling-disabling-of-controls/FreeBASIC/gui-enabling-disabling-of-controls.freebasic b/Task/GUI-enabling-disabling-of-controls/FreeBASIC/gui-enabling-disabling-of-controls.freebasic new file mode 100644 index 0000000000..53430443c1 --- /dev/null +++ b/Task/GUI-enabling-disabling-of-controls/FreeBASIC/gui-enabling-disabling-of-controls.freebasic @@ -0,0 +1,37 @@ +#Include "windows.bi" + +Dim As HWND Window_Main, Edit_Number, Button_Inc, Button_Dec +Dim As MSG msg +Dim As Integer n +Dim As String text + +'Create a window with an input field and two buttons: +Window_Main = CreateWindow("#32770", "GUI Enabling/Disabling of Controls", WS_OVERLAPPEDWINDOW Or WS_VISIBLE, 100, 100, 250, 200, 0, 0, 0, 0) +Var Static_Number = CreateWindow("STATIC", "Value:", WS_VISIBLE Or WS_CHILD, 10, 10, 100, 20, Window_Main, 0, 0, 0) +Edit_Number = CreateWindow("EDIT", "0", WS_BORDER Or WS_VISIBLE Or WS_CHILD Or ES_AUTOHSCROLL Or ES_Number, 110, 10, 100, 20, Window_Main, 0, 0, 0) +Button_Inc = CreateWindow("BUTTON", "Increment", WS_VISIBLE Or WS_CHILD, 110, 40, 100, 20, Window_Main, 0, 0, 0) +Button_Dec = CreateWindow("BUTTON", "Decrement", WS_VISIBLE Or WS_CHILD, 110, 70, 100, 20, Window_Main, 0, 0, 0) + +'Windows message loop: +While GetMessage(@msg, Window_Main, 0, 0) + text = Space(GetWindowTextLength(Edit_Number) + 1) 'Buffer for the text + GetWindowText(Edit_Number, text, Len(text)) + n = Val(text) + If n <> 0 Then EnableWindow(Edit_Number, False) Else EnableWindow(Edit_Number, True) + If n > 9 Then EnableWindow(Button_Inc, False) Else EnableWindow(Button_Inc, True) + If n > 0 Then EnableWindow(Button_Dec, True) Else EnableWindow(Button_Dec, False) + TranslateMessage(@msg) + DispatchMessage(@msg) + Select Case msg.hwnd + Case Button_Inc + 'Increment value: + If msg.message = WM_LBUTTONDOWN Then SetWindowText(Edit_Number, Str(n + 1)) + Case Button_Dec + 'Decrement value: + If msg.message = WM_LBUTTONDOWN Then SetWindowText(Edit_Number, Str(n - 1)) + Case Window_Main + If msg.message = WM_COMMAND Then End + End Select +Wend + +End diff --git a/Task/GUI-enabling-disabling-of-controls/Gambas/gui-enabling-disabling-of-controls-1.gambas b/Task/GUI-enabling-disabling-of-controls/Gambas/gui-enabling-disabling-of-controls-1.gambas new file mode 100644 index 0000000000..13a1fa6469 --- /dev/null +++ b/Task/GUI-enabling-disabling-of-controls/Gambas/gui-enabling-disabling-of-controls-1.gambas @@ -0,0 +1,79 @@ +hValueBox As ValueBox 'We need a ValueBox +hButton0 As Button 'We need a button +hButton1 As Button 'We need another button + +Public Sub Form_Open() + +With Me 'Set the Form's Properties.. + .height = 95 'Set the Height + .Width = 350 'Set the Width + .Arrangement = Arrange.Vertical 'Arrange items vertically + .Padding = 5 'Border area + .Title = "GUI enable/disable" 'Title displayed on the Form +End With + +hValueBox = New ValueBox(Me) As "ValBox" 'Add a ValueBox to the Form as Event 'ValBox' + +With hValueBox 'Set the ValueBox's Properties.. + .Expand = True 'Expand the ValueBox + .Value = 0 'Set it's value to 0 +End With + +hButton0 = New Button(Me) As "ButtonInc" 'Add a Button to the form as Event "ButtonInc" + +With hButton0 'Set the Button's Properties.. + .Height = 28 'Set the Height + .Text = "&Increment" 'Add Text (The '&' adds a keyboard shortcut) +End With + +hButton1 = New Button(Me) As "ButtonDec" 'Add a Button to the form as Event "ButtonDec" + +With hButton1 'Set the Button's Properties.. + .Height = 28 'Set the Height + .Text = "&Decrement" 'Add Text (The '&' adds a keyboard shortcut) + .Enabled = False 'Disable the button +End With + +End + +Public Sub ButtonInc_Click() 'When the 'Increment' Button is clicked.. + +hValueBox.Value += 1 'Increase the Value in the ValueBox by 1 +Checks + +End + +Public Sub ButtonDec_Click() 'When the 'Decrement' Button is clicked.. + +hValueBox.Value -= 1 'Increase the Value in the ValueBox by 1 +Checks + +End + +Public Sub Checks() 'Checks the values to see which controls to en/disable + +If hValueBox.Value = 0 Then 'If the ValueBox = 0 then.. + hValueBox.enabled = True 'Enable the control +Else 'Else.. + hValueBox.enabled = False 'Disable the control +End If + +If hValueBox.Value > 9 Then 'If the ValueBox greater than 9 then.. + hButton0.enabled = False 'Disable the control +Else 'Else.. + hButton0.enabled = True 'Enable the control +End If + +If hValueBox.Value < 1 Then 'If the ValueBox less than 1 then.. + hButton1.enabled = False 'Disable the control +Else 'Else.. + hButton1.enabled = True 'Enable the control +End If + +End + +Public Sub ValBox_Leave() 'When the mouse leaves the ValueBox.. + +Checks 'Rune the Checks routine + +End diff --git a/Task/GUI-enabling-disabling-of-controls/Fantom/gui-enabling-disabling-of-controls-2.fantom b/Task/GUI-enabling-disabling-of-controls/Gambas/gui-enabling-disabling-of-controls-2.gambas similarity index 100% rename from Task/GUI-enabling-disabling-of-controls/Fantom/gui-enabling-disabling-of-controls-2.fantom rename to Task/GUI-enabling-disabling-of-controls/Gambas/gui-enabling-disabling-of-controls-2.gambas diff --git a/Task/GUI-enabling-disabling-of-controls/Nimrod/gui-enabling-disabling-of-controls.nimrod b/Task/GUI-enabling-disabling-of-controls/Nimrod/gui-enabling-disabling-of-controls.nimrod deleted file mode 100644 index 06c7b0e5ad..0000000000 --- a/Task/GUI-enabling-disabling-of-controls/Nimrod/gui-enabling-disabling-of-controls.nimrod +++ /dev/null @@ -1,68 +0,0 @@ -import - gtk2, strutils, glib2 - -var valu: int = 0 -var chngd_txt_hndler: gulong = 0 - -proc thisCheckBtns # forward declaration - -proc thisDestroy(widget: pWidget, data: pgpointer){.cdecl.} = - main_quit() - -nimrod_init() -var window = window_new(gtk2.WINDOW_TOPLEVEL) -var content = vbox_new(TRUE,10) -var hbox1 = hbox_new(TRUE,10) -var entry_fld = entry_new() -entry_fld.set_text("0") -var btn_quit = button_new("Quit") -var btn_inc = button_new("Increment") -var btn_dec = button_new("Decrement") -add(hbox1,btn_inc) -add(hbox1,btn_dec) -pack_start(content, entry_fld, TRUE, TRUE, 0) -pack_start(content, hbox1, TRUE, TRUE, 0) -pack_start(content, btn_quit, TRUE, TRUE, 0) -set_border_width(Window, 5) -add(window, content) - -proc thisInc(widget: pWidget, data: pgpointer){.cdecl.} = - inc(valu) - entry_fld.set_text($valu) - thisCheckBtns() - -proc thisDec(widget: pWidget, data: pgpointer){.cdecl.} = - dec(valu) - entry_fld.set_text($valu) - thisCheckBtns() - -proc thisTextChanged(widget: pWidget, data: pgpointer) {.cdecl.} = - #signal_handler_block(entry_fld, chngd_txt_hndler) - try: - valu = parseInt($entry_fld.get_text()) - except EInvalidValue: - valu = 0 - entry_fld.set_text($valu) - #signal_handler_unblock(entry_fld, chngd_txt_hndler) - #signal_emit_stop(entry_fld, signal_lookup("changed",TYPE_EDITABLE()),0) - thisCheckBtns() - -proc thisCheckBtns = - set_sensitive(btn_inc, valu < 10) - set_sensitive(btn_dec, valu > 0) - set_sensitive(entry_fld, valu == 0) - -discard signal_connect(window, "destroy", - SIGNAL_FUNC(thisDestroy), nil) -discard signal_connect(btn_quit, "clicked", - SIGNAL_FUNC(thisDestroy), nil) -discard signal_connect(btn_inc, "clicked", - SIGNAL_FUNC(thisInc), nil) -discard signal_connect(btn_dec, "clicked", - SIGNAL_FUNC(thisDec), nil) -chngd_txt_hndler = signal_connect(entry_fld, "changed", - SIGNAL_FUNC(thisTextChanged), nil) - -show_all(window) -thisCheckBtns() -main() diff --git a/Task/GUI-enabling-disabling-of-controls/Phix/gui-enabling-disabling-of-controls.phix b/Task/GUI-enabling-disabling-of-controls/Phix/gui-enabling-disabling-of-controls.phix index 17e26dddeb..873496b08d 100644 --- a/Task/GUI-enabling-disabling-of-controls/Phix/gui-enabling-disabling-of-controls.phix +++ b/Task/GUI-enabling-disabling-of-controls/Phix/gui-enabling-disabling-of-controls.phix @@ -26,14 +26,14 @@ function esc_close(Ihandle /*ih*/, atom c) return iff(c=K_ESC?IUP_CLOSE:IUP_CONTINUE) end function - IupOpen("../pGUI/") - txt = IupText("VALUECHANGED_CB",Icallback("valuechanged_cb"),"FILTER=NUMBER, EXPAND=YES") - inc = IupButton("increment",Icallback("inc_cb")) - dec = IupButton("decrement",Icallback("dec_cb"),"ACTIVE=NO") - hbx = IupHbox({inc,dec},"MARGIN=0x10, GAP=20") - vbx = IupVbox({txt,hbx},"MARGIN=40x20") - dlg = IupDialog(vbx) - IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) - IupShow(dlg) - IupMainLoop() - IupClose() +IupOpen() +txt = IupText("VALUECHANGED_CB",Icallback("valuechanged_cb"),"FILTER=NUMBER, EXPAND=YES") +inc = IupButton("increment",Icallback("inc_cb")) +dec = IupButton("decrement",Icallback("dec_cb"),"ACTIVE=NO") +hbx = IupHbox({inc,dec},"MARGIN=0x10, GAP=20") +vbx = IupVbox({txt,hbx},"MARGIN=40x20") +dlg = IupDialog(vbx) +IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) +IupShow(dlg) +IupMainLoop() +IupClose() diff --git a/Task/GUI-enabling-disabling-of-controls/Python/gui-enabling-disabling-of-controls.py b/Task/GUI-enabling-disabling-of-controls/Python/gui-enabling-disabling-of-controls.py new file mode 100644 index 0000000000..0343435ca9 --- /dev/null +++ b/Task/GUI-enabling-disabling-of-controls/Python/gui-enabling-disabling-of-controls.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 + +import tkinter as tk + +class MyForm(tk.Frame): + + def __init__(self, master=None): + tk.Frame.__init__(self, master) + self.pack(expand=True, fill="both", padx=10, pady=10) + self.master.title("Controls") + self.setupUI() + + def setupUI(self): + self.value_entry = tk.Entry(self, justify=tk.CENTER) + self.value_entry.grid(row=0, column=0, columnspan=2, + padx=5, pady=5, sticky="nesw") + self.value_entry.insert('end', '0') + self.value_entry.bind("", self.eventHandler) + + self.decre_btn = tk.Button(self, text="Decrement", state=tk.DISABLED) + self.decre_btn.grid(row=1, column=0, padx=5, pady=5) + self.decre_btn.bind("", self.eventHandler) + + self.incre_btn = tk.Button(self, text="Increment") + self.incre_btn.grid(row=1, column=1, padx=5, pady=5) + self.incre_btn.bind("", self.eventHandler) + + def eventHandler(self, event): + value = int(self.value_entry.get()) + if event.widget == self.value_entry: + if value > 10: + self.value_entry.delete("0", "end") + self.value_entry.insert("end", "0") + elif value == 10: + self.value_entry.config(state=tk.DISABLED) + self.incre_btn.config(state=tk.DISABLED) + self.decre_btn.config(state=tk.NORMAL) + elif value == 0: + self.value_entry.config(state=tk.NORMAL) + self.incre_btn.config(state=tk.NORMAL) + self.decre_btn.config(state=tk.DISABLED) + elif (value > 0) and (value < 10): + self.value_entry.config(state=tk.DISABLED) + self.incre_btn.config(state=tk.NORMAL) + self.decre_btn.config(state=tk.NORMAL) + else: + if event.widget == self.incre_btn: + if (value >= 0) and (value < 10): + value += 1 + self.value_entry.config(state=tk.NORMAL) + self.value_entry.delete("0", "end") + self.value_entry.insert("end", str(value)) + if value > 0: + self.decre_btn.config(state=tk.NORMAL) + self.value_entry.config(state=tk.DISABLED) + if value == 10: + self.incre_btn.config(state=tk.DISABLED) + elif event.widget == self.decre_btn: + if (value > 0) and (value <= 10): + value -= 1 + self.value_entry.config(state=tk.NORMAL) + self.value_entry.delete("0", "end") + self.value_entry.insert("end", str(value)) + self.value_entry.config(state=tk.DISABLED) + if (value) < 10: + self.incre_btn.config(state=tk.NORMAL) + if (value) == 0: + self.decre_btn.config(state=tk.DISABLED) + self.value_entry.config(state=tk.NORMAL) + +def main(): + app = MyForm() + app.mainloop() + +if __name__ == "__main__": + main() diff --git a/Task/Galton-box-animation/Phix/galton-box-animation-1.phix b/Task/Galton-box-animation/Phix/galton-box-animation-1.phix new file mode 100644 index 0000000000..54c9b166ef --- /dev/null +++ b/Task/Galton-box-animation/Phix/galton-box-animation-1.phix @@ -0,0 +1,44 @@ +constant balls = 80 +clear_screen() +sequence screen = repeat(repeat(' ',23),12) + & repeat(join(repeat(':',12)),12) + & {repeat('.',23)}, + Pxy = repeat({12,1},balls) +for peg=1 to 10 do + screen[peg+2][13-peg..11+peg] = join(repeat('.',peg)) +end for +puts(1,join(screen,"\n")) +text_color(BRIGHT_RED) +bool moved = true +integer top = ' ' -- (new drop every other iteration) +while moved or top!=' ' do + moved = false + for i=1 to balls do + integer {Px,Py} = Pxy[i] + if Py!=1 or top=' ' then + integer Dx = 0, Dy = 0 + if screen[Py+1,Px]=' ' then -- can vertical? + Dy = 1 + else + Dx = {-1,+1}[rand(2)] -- try l;r or r;l + if screen[Py+1,Px+Dx]!=' ' then Dx = -Dx end if + if screen[Py+1,Px+Dx]==' ' then + Dy = 1 + end if + end if + if Dy then + position(Py,Px) puts(1," ") screen[Py,Px] = ' ' + Px += Dx + Py += Dy + position(Py,Px) puts(1,"o") screen[Py,Px] = 'o' + Pxy[i] = {Px,Py} + moved = true + if Py=2 then top = 'o' end if + end if + end if + end for + position(26,1) + sleep(0.2) + if get_key()!=-1 then exit end if + top = screen[2][12] +end while diff --git a/Task/Galton-box-animation/Phix/galton-box-animation-2.phix b/Task/Galton-box-animation/Phix/galton-box-animation-2.phix new file mode 100644 index 0000000000..2419ca41e5 --- /dev/null +++ b/Task/Galton-box-animation/Phix/galton-box-animation-2.phix @@ -0,0 +1,108 @@ +-- +-- demo\rosetta\GaltonBox.exw +-- +constant TITLE = "Galton Box" + +include pGUI.e + +Ihandle dlg, canvas, timershow +cdCanvas cddbuffer, cdcanvas + +integer brem = 80 +sequence balls = {{0,1,0}} +sequence bins = repeat(0,8) + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) + integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE"), x, y + atom xx, yy + cdCanvasActivate(cddbuffer) + cdCanvasClear(cddbuffer) + -- draw the pins, then balls, then bins + cdCanvasSetForeground(cddbuffer, CD_DARK_GREEN) + integer pinsize = min(floor(h/40),floor(w/50)) + for y=4 to 16 by 2 do + for x=-(y-4) to (y-4) by 4 do + xx = w/2 + x*w/32 + yy = h -y*h/32 + cdCanvasSector(cddbuffer, xx, yy, pinsize, pinsize, 0, 360) + end for + end for + cdCanvasSetForeground(cddbuffer, CD_INDIGO) + for i=1 to length(balls) do + {x, y} = balls[i] + xx = w/2 + x*w/32 + yy = h -y*h/32 + cdCanvasSector(cddbuffer, xx, yy, pinsize*4, pinsize*4, 0, 360) + end for + cdCanvasLineWidth(cddbuffer,w/9) + for i=1 to length(bins) do + xx = w/2+(i*4-18)*w/32 + yy = bins[i]*h/64+10 + cdCanvasLine(cddbuffer,xx,10,xx,yy) + end for + cdCanvasFlush(cddbuffer) + return IUP_DEFAULT +end function + +function timer_cb(Ihandle ih) +integer x, y=9, dx + if length(balls) then + {x,y,dx} = balls[1] + if y>20 then + bins[(x+18)/4] += 1 + balls = balls[2..$] + end if + end if + for i=1 to length(balls) do + {x,y,dx} = balls[i] + if y>15 then + dx = 0 + elsif and_bits(y,1)=0 then + dx = {-1,+1}[rand(2)] + end if + balls[i] = {x+dx,y+1,dx} + end for + if y>4 and brem!=0 then + brem -= 1 + balls = append(balls,{0,1,0}) + end if + if brem=0 and length(balls)=0 then + IupSetAttribute(timershow,"RUN","NO") + end if + IupUpdate(canvas) + return IUP_IGNORE +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + cdCanvasSetBackground(cddbuffer, CD_GREY) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "640x380") + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + + timershow = IupTimer(Icallback("timer_cb"), 80) + + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", TITLE) + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + + IupShow(dlg) + IupSetAttribute(canvas, "RASTERSIZE", NULL) + IupMainLoop() + IupClose() +end procedure + +main() diff --git a/Task/Galton-box-animation/Python/galton-box-animation.py b/Task/Galton-box-animation/Python/galton-box-animation.py new file mode 100644 index 0000000000..230b6806d8 --- /dev/null +++ b/Task/Galton-box-animation/Python/galton-box-animation.py @@ -0,0 +1,85 @@ +#!/usr/bin/python + +import sys, os +import random +import time + +def print_there(x, y, text): + sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text)) + sys.stdout.flush() + + +class Ball(): + def __init__(self): + self.x = 0 + self.y = 0 + + def update(self): + self.x += random.randint(0,1) + self.y += 1 + + def fall(self): + self.y +=1 + + +class Board(): + def __init__(self, width, well_depth, N): + self.balls = [] + self.fallen = [0] * (width + 1) + self.width = width + self.well_depth = well_depth + self.N = N + self.shift = 4 + + def update(self): + for ball in self.balls: + if ball.y < self.width: + ball.update() + elif ball.y < self.width + self.well_depth - self.fallen[ball.x]: + ball.fall() + elif ball.y == self.width + self.well_depth - self.fallen[ball.x]: + self.fallen[ball.x] += 1 + else: + pass + + def balls_on_board(self): + return len(self.balls) - sum(self.fallen) + + def add_ball(self): + if(len(self.balls) <= self.N): + self.balls.append(Ball()) + + def print_board(self): + for y in range(self.width + 1): + for x in range(y): + print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, "#") + def print_ball(self, ball): + if ball.y <= self.width: + x = self.width - ball.y + 2*ball.x + self.shift + else: + x = 2*ball.x + self.shift + y = ball.y + 1 + print_there(y, x, "*") + + def print_all(self): + print(chr(27) + "[2J") + self.print_board(); + for ball in self.balls: + self.print_ball(ball) + + +def main(): + board = Board(width = 15, well_depth = 5, N = 10) + board.add_ball() #initialization + while(board.balls_on_board() > 0): + board.print_all() + time.sleep(0.25) + board.update() + board.print_all() + time.sleep(0.25) + board.update() + board.add_ball() + + +if __name__=="__main__": + main() diff --git a/Task/Gamma-function/FreeBASIC/gamma-function.freebasic b/Task/Gamma-function/FreeBASIC/gamma-function.freebasic index f7f44481a9..1eeb463bb1 100644 --- a/Task/Gamma-function/FreeBASIC/gamma-function.freebasic +++ b/Task/Gamma-function/FreeBASIC/gamma-function.freebasic @@ -27,7 +27,7 @@ Function gammaLanczos (x As Double) As Double Dim a As Double = p(0) Dim t As Double = x + g + 0.5 - For i As Integer = 1 To 7 + For i As Integer = 1 To 8 a += p(i) / (x + i) Next diff --git a/Task/Gamma-function/Haskell/gamma-function-1.hs b/Task/Gamma-function/Haskell/gamma-function-1.hs index 4b26d301e4..94652f58e6 100644 --- a/Task/Gamma-function/Haskell/gamma-function-1.hs +++ b/Task/Gamma-function/Haskell/gamma-function-1.hs @@ -1,10 +1,21 @@ cof :: [Double] -cof = [76.18009172947146,-86.50532032941677,24.01409824083091,-1.231739572450155,0.001208650973866179,-0.000005395239384953] +cof = + [ 76.18009172947146 + , -86.50532032941677 + , 24.01409824083091 + , -1.231739572450155 + , 0.001208650973866179 + , -0.000005395239384953 + ] ser :: Double ser = 1.000000000190015 gammaln :: Double -> Double -gammaln xx = let tmp' = (xx+5.5) - (xx+0.5)*log(xx+5.5) - ser' = ser + sum (zipWith (/) cof [xx+1..]) - in -tmp' + log(2.5066282746310005 * ser' / xx) +gammaln xx = + let tmp_ = (xx + 5.5) - (xx + 0.5) * log (xx + 5.5) + ser_ = ser + sum (zipWith (/) cof [xx + 1 ..]) + in -tmp_ + log (2.5066282746310005 * ser_ / xx) + +main :: IO () +main = mapM_ print $ gammaln <$> [0.1,0.2 .. 1.0] diff --git a/Task/Gamma-function/JavaScript/gamma-function.js b/Task/Gamma-function/JavaScript/gamma-function.js index fcb80dc1c7..25a0b1e266 100644 --- a/Task/Gamma-function/JavaScript/gamma-function.js +++ b/Task/Gamma-function/JavaScript/gamma-function.js @@ -1,19 +1,20 @@ -function gamma(x){ - var p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, - 771.32342877765313, -176.61502916214059, 12.507343278686905, - -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7]; - - var g = 7; - if(x < 0.5){ - return Math.PI / (Math.sin(Math.PI * x)*gamma(1-x)); - } +function gamma(x) { + var p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, + 771.32342877765313, -176.61502916214059, 12.507343278686905, + -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7 + ]; - x -= 1; - var a = p[0]; - var t = x+g+0.5; - for(var i = 1; i < p.length; i++){ - a += p[i]/(x+i); - } + var g = 7; + if (x < 0.5) { + return Math.PI / (Math.sin(Math.PI * x) * gamma(1 - x)); + } - return Math.sqrt(2*Math.PI)*Math.pow(t, x+0.5)*Math.exp(-t)*a; + x -= 1; + var a = p[0]; + var t = x + g + 0.5; + for (var i = 1; i < p.length; i++) { + a += p[i] / (x + i); + } + + return Math.sqrt(2 * Math.PI) * Math.pow(t, x + 0.5) * Math.exp(-t) * a; } diff --git a/Task/Gamma-function/jq/gamma-function-1.jq b/Task/Gamma-function/Jq/gamma-function-1.jq similarity index 100% rename from Task/Gamma-function/jq/gamma-function-1.jq rename to Task/Gamma-function/Jq/gamma-function-1.jq diff --git a/Task/Gamma-function/jq/gamma-function-2.jq b/Task/Gamma-function/Jq/gamma-function-2.jq similarity index 100% rename from Task/Gamma-function/jq/gamma-function-2.jq rename to Task/Gamma-function/Jq/gamma-function-2.jq diff --git a/Task/Gamma-function/jq/gamma-function-3.jq b/Task/Gamma-function/Jq/gamma-function-3.jq similarity index 100% rename from Task/Gamma-function/jq/gamma-function-3.jq rename to Task/Gamma-function/Jq/gamma-function-3.jq diff --git a/Task/Gamma-function/jq/gamma-function-4.jq b/Task/Gamma-function/Jq/gamma-function-4.jq similarity index 100% rename from Task/Gamma-function/jq/gamma-function-4.jq rename to Task/Gamma-function/Jq/gamma-function-4.jq diff --git a/Task/Gamma-function/jq/gamma-function-5.jq b/Task/Gamma-function/Jq/gamma-function-5.jq similarity index 100% rename from Task/Gamma-function/jq/gamma-function-5.jq rename to Task/Gamma-function/Jq/gamma-function-5.jq diff --git a/Task/Gamma-function/Kotlin/gamma-function.kotlin b/Task/Gamma-function/Kotlin/gamma-function.kotlin new file mode 100644 index 0000000000..a79e2597ff --- /dev/null +++ b/Task/Gamma-function/Kotlin/gamma-function.kotlin @@ -0,0 +1,35 @@ +// version 1.0.6 + +fun gammaStirling(x: Double): Double = Math.sqrt(2.0 * Math.PI / x) * Math.pow(x / Math.E, x) + +fun gammaLanczos(x: Double): Double { + var xx = x + val p = doubleArrayOf( + 0.99999999999980993, + 676.5203681218851, + -1259.1392167224028, + 771.32342877765313, + -176.61502916214059, + 12.507343278686905, + -0.13857109526572012, + 9.9843695780195716e-6, + 1.5056327351493116e-7 + ) + val g = 7 + if (xx < 0.5) return Math.PI / (Math.sin(Math.PI * xx) * gammaLanczos(1.0 - xx)) + xx-- + var a = p[0] + val t = xx + g + 0.5 + for (i in 1 until p.size) a += p[i] / (xx + i) + return Math.sqrt(2.0 * Math.PI) * Math.pow(t, xx + 0.5) * Math.exp(-t) * a +} + +fun main(args: Array) { + println(" x\tStirling\t\tLanczos\n") + for (i in 1 .. 20) { + val d = i / 10.0 + print("%4.2f\t".format(d)) + print("%17.15f\t".format(gammaStirling(d))) + println("%17.15f".format(gammaLanczos(d))) + } +} diff --git a/Task/Gamma-function/Phix/gamma-function.phix b/Task/Gamma-function/Phix/gamma-function.phix new file mode 100644 index 0000000000..3f7e0122e7 --- /dev/null +++ b/Task/Gamma-function/Phix/gamma-function.phix @@ -0,0 +1,39 @@ +sequence c = repeat(0,12) + +function 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 + +procedure sq(atom x, atom mul) +atom p = x*mul + printf(1,"%18.16g,%18.15g\n",{x,p*p}) +end procedure + +procedure si(atom x) + printf(1,"%18.15f\n",{x}) +end procedure + +sq(gamma(-3/2),3/4) +sq(gamma(-1/2),-1/2) +sq(gamma(1/2),1) +si(gamma(1)) +sq(gamma(3/2),2) +si(gamma(2)) +sq(gamma(5/2),4/3) +si(gamma(3)) +sq(gamma(7/2),8/15) +si(gamma(4)) diff --git a/Task/Gamma-function/REXX/gamma-function.rexx b/Task/Gamma-function/REXX/gamma-function.rexx index 4189ca6539..593e1c1fea 100644 --- a/Task/Gamma-function/REXX/gamma-function.rexx +++ b/Task/Gamma-function/REXX/gamma-function.rexx @@ -1,7 +1,7 @@ -/*REXX program calculates GAMMA using the Taylor series coefficients, ≈80 decimal digits*/ - /*The GAMMA function symbol is the Greek capital letter: Γ */ +/*REXX program calculates GAMMA using the Taylor series coefficients; ≈80 decimal digits*/ + /*The GAMMA function symbol is the Greek capital letter: Γ */ numeric digits 90 /*be able to handle extended precision.*/ -parse arg LO HI . /*allow specification of gamma argument*/ +parse arg LO HI . /*allow specification of gamma arg/args*/ /* [↓] either show a range or a ··· */ do j=word(LO 1, 1) to word(HI LO 9, 1) /* ··· single gamma value.*/ say 'gamma('j") =" gamma(j) /*compute gamma of J and display value.*/ @@ -9,8 +9,8 @@ parse arg LO HI . /*allow specification of gamma exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ gamma: procedure; parse arg x; xm=x-1; sum=0 - /*coefficients thanks to: Arne Fransén & Staffan Wrigge.*/ - #.1 = 1 /* [↓] #.2 is the Euler-Mascheroni constant. */ + /*coefficients thanks to: Arne Fransén & Staffan Wrigge.*/ + #.1 = 1 /* [↓] #.2 is the Euler-Mascheroni constant. */ #.2 = 0.57721566490153286060651209008240243104215933593992359880576723488486772677766467 #.3 = -0.65587807152025388107701951514539048127976638047858434729236244568387083835372210 #.4 = -0.04200263503409523552900393487542981871139450040110609352206581297618009687597599 @@ -62,7 +62,7 @@ gamma: procedure; parse arg x; xm=x-1; sum=0 #.50 = -0.00000000000000000000000000000000000000001056233178503581218600561071538285049997 #.51 = 0.00000000000000000000000000000000000000000026784429826430494783549630718908519485 #.52 = 0.00000000000000000000000000000000000000000002424715494851782689673032938370921241 -#=52; do k=# by -1 for # - sum=sum*xm + #.k - end /*k*/ +#=52; do k=# by -1 for # + sum=sum*xm + #.k + end /*k*/ return 1/sum diff --git a/Task/Gamma-function/Scheme/gamma-function.ss b/Task/Gamma-function/Scheme/gamma-function.ss new file mode 100644 index 0000000000..c0c8b46011 --- /dev/null +++ b/Task/Gamma-function/Scheme/gamma-function.ss @@ -0,0 +1,62 @@ +(import (scheme base) + (scheme inexact) + (scheme write)) + +(define PI 3.14159265358979323846264338327950) +(define e 2.7182818284590452353602875) + +(define gamma-lanczos + (let ((p '(676.5203681218851 -1259.1392167224028 771.32342877765313 + -176.61502916214059 12.507343278686905 -0.13857109526572012 + 9.9843695780195716e-6 1.5056327351493116e-7))) + (lambda (x) + (if (< x 0.5) + (/ PI (* (sin (* PI x)) (gamma-lanczos (- 1 x)))) + (let* ((x2 (- x 1)) + (t (+ x2 7 0.5)) + (a (do ((ps p (cdr ps)) + (idx 0 (+ 1 idx)) + (res 0.99999999999980993 (+ res + (/ (car ps) + (+ x2 idx 1))))) + ((null? ps) res)))) + (* (sqrt (* 2 PI)) (expt t (+ x2 0.5)) (exp (- t)) a)))))) + +(define (gamma-stirling x) + (* (sqrt (* 2 (/ PI x))) (expt (/ x e) x))) + +(define gamma-taylor + (let ((a (reverse + '(1.00000000000000000000 0.57721566490153286061 + -0.65587807152025388108 -0.04200263503409523553 + 0.16653861138229148950 -0.04219773455554433675 + -0.00962197152787697356 0.00721894324666309954 + -0.00116516759185906511 -0.00021524167411495097 + 0.00012805028238811619 -0.00002013485478078824 + -0.00000125049348214267 0.00000113302723198170 + -0.00000020563384169776 0.00000000611609510448 + 0.00000000500200764447 -0.00000000118127457049 + 0.00000000010434267117 0.00000000000778226344 + -0.00000000000369680562 0.00000000000051003703 + -0.00000000000002058326 -0.00000000000000534812 + 0.00000000000000122678 -0.00000000000000011813 + 0.00000000000000000119 0.00000000000000000141 + -0.00000000000000000023 0.00000000000000000002)))) + (lambda (x) + (let ((y (- x 1))) + (do ((as a (cdr as)) + (res 0 (+ (car as) (* res y)))) + ((null? as) (/ 1 res))))))) + +(do ((i 0.1 (+ i 0.1))) + ((> i 2.01) ) + (display (string-append "Gamma (" + (number->string i) + "): " + "\n --- Lanczos : " + (number->string (gamma-lanczos i)) + "\n --- Stirling: " + (number->string (gamma-stirling i)) + "\n --- Taylor : " + (number->string (gamma-taylor i)) + "\n"))) diff --git a/Task/Gamma-function/Sidef/gamma-function-1.sidef b/Task/Gamma-function/Sidef/gamma-function-1.sidef index b8691abecc..1d56917da6 100644 --- a/Task/Gamma-function/Sidef/gamma-function-1.sidef +++ b/Task/Gamma-function/Sidef/gamma-function-1.sidef @@ -7,13 +7,13 @@ var a = [ 1.00000_00000_00000_00000, 0.57721_56649_01532_86061, -0.65587_80715_ 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 ]; + 0.00000_00000_00000_00141, -0.00000_00000_00000_00023, 0.00000_00000_00000_00002 ] func gamma(x) { - var y = (x - 1); - 1 / a.reverse.reduce {|sum, an| sum*y + an}; + var y = (x - 1) + 1 / a.reverse.reduce {|sum, an| sum*y + an} } for i in 1..10 { - say ("%.14e" % gamma(i/3)); + say ("%.14e" % gamma(i/3)) } diff --git a/Task/Gamma-function/Sidef/gamma-function-2.sidef b/Task/Gamma-function/Sidef/gamma-function-2.sidef index bbc613c99f..bcb370461e 100644 --- a/Task/Gamma-function/Sidef/gamma-function-2.sidef +++ b/Task/Gamma-function/Sidef/gamma-function-2.sidef @@ -3,36 +3,35 @@ func gamma(z) { func withinepsilon(x) { abs(x - abs(x)) <= epsilon } - +  var p = [ 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7, ] - - var result; - z = Complex(z) - const pi = Complex.pi - - if (z.real < 0.5) { - result = (pi / (sin(pi * z) * gamma(Complex(1) - z))) +  + var result = 0 + const pi = Num.pi +  + if (z.re < 0.5) { + result = (pi / (sin(pi * z) * gamma(1 - z))) } else { z -= 1 var x = 0.99999999999980993 - +  p.each_kv { |i, v| x += v/(z + i + 1) } - +  var t = (z + p.len - 0.5) result = (sqrt(pi*2) * t**(z+0.5) * exp(-t) * x) } - - withinepsilon(result.im) ? result.real : result +  + withinepsilon(result.im) ? result.re : result } - +  for i in 1..10 { - say ("%.14e" % gamma(i/3)); + say ("%.14e" % gamma(i/3)) } diff --git a/Task/Gamma-function/Sidef/gamma-function-3.sidef b/Task/Gamma-function/Sidef/gamma-function-3.sidef index c3be5093dd..e352a9f0c0 100644 --- a/Task/Gamma-function/Sidef/gamma-function-3.sidef +++ b/Task/Gamma-function/Sidef/gamma-function-3.sidef @@ -1,11 +1,11 @@ -define e = Math.e; -define pi = Math.pi; - +define ℯ = Num.e +define τ = Num.tau +  func Γ(t) { - t < 20 ? (__FUNC__(t + 1) / t) - : (Math.sqrt(2*pi*t) * Math.pow(t/e + 1/(12*e*t), t) / t); + t < 20 ? (__FUNC__(t + 1) / t) +  : (sqrt(τ*t) * pow(t/ℯ + 1/(12*ℯ*t), t) / t) } - -for i in 1..10 { - say ("%.14e" % Γ(i/3)); +  +for i in (1..10) { + say ("%.14e" % Γ(i/3)) } diff --git a/Task/Gamma-function/Zkl/gamma-function-1.zkl b/Task/Gamma-function/Zkl/gamma-function-1.zkl new file mode 100644 index 0000000000..fad3e474ec --- /dev/null +++ b/Task/Gamma-function/Zkl/gamma-function-1.zkl @@ -0,0 +1,23 @@ +fcn taylorGamma(x){ + var table = T( + 0x1p+0, 0x1.2788cfc6fb618f4cp-1, + -0x1.4fcf4026afa2dcecp-1, -0x1.5815e8fa27047c8cp-5, + 0x1.5512320b43fbe5dep-3, -0x1.59af103c340927bep-5, + -0x1.3b4af28483e214e4p-7, 0x1.d919c527f60b195ap-8, + -0x1.317112ce3a2a7bd2p-10, -0x1.c364fe6f1563ce9cp-13, + 0x1.0c8a78cd9f9d1a78p-13, -0x1.51ce8af47eabdfdcp-16, + -0x1.4fad41fc34fbb2p-20, 0x1.302509dbc0de2c82p-20, + -0x1.b9986666c225d1d4p-23, 0x1.a44b7ba22d628acap-28, + 0x1.57bc3fc384333fb2p-28, -0x1.44b4cedca388f7c6p-30, + 0x1.cae7675c18606c6p-34, 0x1.11d065bfaf06745ap-37, + -0x1.0423bac8ca3faaa4p-38, 0x1.1f20151323cd0392p-41, + -0x1.72cb88ea5ae6e778p-46, -0x1.815f72a05f16f348p-48, + 0x1.6198491a83bccbep-50, -0x1.10613dde57a88bd6p-53, + 0x1.5e3fee81de0e9c84p-60, 0x1.a0dc770fb8a499b6p-60, + -0x1.0f635344a29e9f8ep-62, 0x1.43d79a4b90ce8044p-66).reverse(); + + y := x.toFloat() - 1.0; + sm := table[1,*].reduce('wrap(sm,an){ sm * y + an },table[0]); + + return(1.0 / sm); +} diff --git a/Task/Gamma-function/Zkl/gamma-function-2.zkl b/Task/Gamma-function/Zkl/gamma-function-2.zkl new file mode 100644 index 0000000000..29ce624a59 --- /dev/null +++ b/Task/Gamma-function/Zkl/gamma-function-2.zkl @@ -0,0 +1,28 @@ +fcn lanczosGamma(z) { z = z.toFloat(); + // Coefficients used by the GNU Scientific Library. + // http://en.wikipedia.org/wiki/Lanczos_approximation + const g = 7, PI = (0.0).pi; + exp := (0.0).e.pow; + var table = T( + 0.99999_99999_99809_93, + 676.52036_81218_851, + -1259.13921_67224_028, + 771.32342_87776_5313, + -176.61502_91621_4059, + 12.50734_32786_86905, + -0.13857_10952_65720_12, + 9.98436_95780_19571_6e-6, + 1.50563_27351_49311_6e-7); + + // Reflection formula. + if (z < 0.5) { + return(PI / ((PI * z).sin() * lanczosGamma(1.0 - z))); + } else { + z -= 1; + x := table[0]; + foreach i in ([1 .. g + 1]){ + x += table[i] / (z + i); } + t := z + g + 0.5; + return((2.0 * PI).sqrt() * t.pow(z + 0.5) * exp(-t) * x); + } +} diff --git a/Task/Gaussian-elimination/Zkl/gaussian-elimination-1.zkl b/Task/Gaussian-elimination/Zkl/gaussian-elimination-1.zkl new file mode 100644 index 0000000000..b8b4f92c57 --- /dev/null +++ b/Task/Gaussian-elimination/Zkl/gaussian-elimination-1.zkl @@ -0,0 +1,11 @@ +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +a:=GSL.Matrix(6,6).set( + 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:=GSL.VectorFromData(-0.01, 0.61, 0.91, 0.99, 0.60, 0.02); +x:=a.AxEQb(b); +x.format(8,5).println(); diff --git a/Task/Gaussian-elimination/Zkl/gaussian-elimination-2.zkl b/Task/Gaussian-elimination/Zkl/gaussian-elimination-2.zkl new file mode 100644 index 0000000000..5f6e5b7adc --- /dev/null +++ b/Task/Gaussian-elimination/Zkl/gaussian-elimination-2.zkl @@ -0,0 +1,23 @@ +fcn gaussEliminate(a,b){ // modifies a&b --> vector + n:=b.len(); + foreach dia in ([0..n-1]){ + maxRow:=dia; max:=a[dia][dia]; + foreach row in ([dia+1 .. n-1]){ + if((tmp:=a[row][dia].abs()) > max){ maxRow=row; max=tmp; } + } + a.swap(dia,maxRow); b.swap(dia,maxRow); // swap rows + foreach row in ([dia+1 .. n-1]){ + ar:=a[row]; ad:=a[dia]; tmp:=ar[dia] / ad[dia]; + foreach col in ([dia+1 .. n-1]){ ar[col]-=tmp*ad[col]; } + ar[dia]=0.0; + b[row]-=tmp*b[dia]; + } + } + x:=(0).pump(n,List().write); // -->list filled with garbage + foreach row in ([n-1 .. 0,-1]){ + tmp:=b[row]; ar:=a[row]; + foreach j in ([n-1 .. row+1,-1]){ tmp-=x[j]*ar[j]; } + x[row]=tmp/a[row][row]; + } + x +} diff --git a/Task/Gaussian-elimination/Zkl/gaussian-elimination-3.zkl b/Task/Gaussian-elimination/Zkl/gaussian-elimination-3.zkl new file mode 100644 index 0000000000..ffbb1fa8c6 --- /dev/null +++ b/Task/Gaussian-elimination/Zkl/gaussian-elimination-3.zkl @@ -0,0 +1,8 @@ +a:=List( List(1.00, 0.00, 0.00, 0.00, 0.00, 0.00,), + List(1.00, 0.63, 0.39, 0.25, 0.16, 0.10,), + List(1.00, 1.26, 1.58, 1.98, 2.49, 3.13,), + List(1.00, 1.88, 3.55, 6.70, 12.62, 23.80,), + List(1.00, 2.51, 6.32, 15.88, 39.90, 100.28,), + List(1.00, 3.14, 9.87, 31.01, 97.41, 306.02) ); +b:=List( -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 ); +gaussEliminate(a,b).println(); diff --git a/Task/Generate-Chess960-starting-position/00DESCRIPTION b/Task/Generate-Chess960-starting-position/00DESCRIPTION index 0713eb18e1..dd0b053203 100644 --- a/Task/Generate-Chess960-starting-position/00DESCRIPTION +++ b/Task/Generate-Chess960-starting-position/00DESCRIPTION @@ -1,4 +1,4 @@ -'''[[wp:Chess960|Chess960]]'''   is a variant of chess created by world champion [[wp:Bobby Fisher|Bobby Fisher]]. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: +'''[[wp:Chess960|Chess960]]'''   is a variant of chess created by world champion [[wp:Bobby Fischer|Bobby Fischer]]. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: * as in the standard chess game, all eight white pawns must be placed on the second rank. * White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints: diff --git a/Task/Generate-Chess960-starting-position/JavaScript/generate-chess960-starting-position.js b/Task/Generate-Chess960-starting-position/JavaScript/generate-chess960-starting-position.js index 417cf5cdfb..d973c8b8d0 100644 --- a/Task/Generate-Chess960-starting-position/JavaScript/generate-chess960-starting-position.js +++ b/Task/Generate-Chess960-starting-position/JavaScript/generate-chess960-starting-position.js @@ -22,5 +22,5 @@ function ch960startPos() { return rank; } -// test +// testing (10 times) for (var x = 1; x <= 10; x++) console.log(ch960startPos().join(" | ")); diff --git a/Task/Generate-Chess960-starting-position/Kotlin/generate-chess960-starting-position.kotlin b/Task/Generate-Chess960-starting-position/Kotlin/generate-chess960-starting-position.kotlin index 00bb41f27b..cd5cb01140 100644 --- a/Task/Generate-Chess960-starting-position/Kotlin/generate-chess960-starting-position.kotlin +++ b/Task/Generate-Chess960-starting-position/Kotlin/generate-chess960-starting-position.kotlin @@ -5,20 +5,24 @@ object Chess960 : Iterable { if (e.length <= 1) { val s = b + e if (s.is_valid()) patterns += s - } else - for (i in 0..e.length - 1) + } else { + for (i in 0 until e.length) { invoke(b + e[i], e.substring(0, i) + e.substring(i + 1)) + } + } } private fun String.is_valid(): Boolean { val k = indexOf('K') return indexOf('R') < k && k < lastIndexOf('R') && - indexOf('B') % 2 != lastIndexOf('B') % 2 + indexOf('B') % 2 != lastIndexOf('B') % 2 } private val patterns = sortedSetOf() - init { invoke("", "KQRRNNBB") } + init { + invoke("", "KQRRNNBB") + } } fun main(args: Array) { diff --git a/Task/Generate-Chess960-starting-position/PARI-GP/generate-chess960-starting-position.pari b/Task/Generate-Chess960-starting-position/PARI-GP/generate-chess960-starting-position.pari new file mode 100644 index 0000000000..43049d14b0 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/PARI-GP/generate-chess960-starting-position.pari @@ -0,0 +1,9 @@ +chess960() = +{ + my (C = vector(8), i, j, r); + + C[random(4) * 2 + 1] = C[random(4) * 2 + 2] = "B"; + for (i = 1, 3, while (C[r = random(8) + 1],); C[r] = Vec("NNQ")[i]); + for (i = 1, 8, if (!C[i], C[i] = Vec("RKR")[j++])); + C +} diff --git a/Task/Generate-Chess960-starting-position/Phix/generate-chess960-starting-position.phix b/Task/Generate-Chess960-starting-position/Phix/generate-chess960-starting-position.phix new file mode 100644 index 0000000000..11291eebd0 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Phix/generate-chess960-starting-position.phix @@ -0,0 +1,25 @@ +sequence solutions = {} +--integer d = new_dict() + +for i=1 to factorial(8) do + sequence s = permute(i,"RNBQKBNR") +-- sequence s = permute(rand(factorial(8),"RNBQKBNR") + integer b1 = find('B',s), + b2 = find('B',s,b1+1) + if and_bits(b2-b1,1)=1 then + integer k = find('K',s) + integer r1 = find('R',s) + integer r2 = find('R',s,r1+1) + if r1957 Then Say format(cnt.1,3) poss r1 kk r2 ol diff --git a/Task/Generate-Chess960-starting-position/Scheme/generate-chess960-starting-position.ss b/Task/Generate-Chess960-starting-position/Scheme/generate-chess960-starting-position.ss new file mode 100644 index 0000000000..dd426ae09f --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Scheme/generate-chess960-starting-position.ss @@ -0,0 +1,56 @@ +(import (scheme base) (scheme write) + (srfi 1) ; list library + (srfi 27)) ; random numbers + +(random-source-randomize! default-random-source) + +;; Random integer in [start, end) +(define (random-between start end) + (let ((len (- end start 1))) + (if (< len 2) + start + (+ start (random-integer len))))) + +;; Random item in list +(define (random-pick lst) + (if (= 1 (length lst)) + (car lst) + (list-ref lst (random-integer (length lst))))) + +;; Construct a random piece placement for Chess960 +(define (random-piece-positions) + (define (free-indices positions) ; return list of empty slot indices + (let loop ((i 0) + (free '())) + (if (= 8 i) + free + (loop (+ 1 i) + (if (string=? "." (vector-ref positions i)) + (cons i free) + free))))) + ; + (define (place-king+rooks positions) + (let ((king-posn (random-between 1 8))) + (vector-set! positions king-posn "K") + ; left-rook is between left-edge and king + (vector-set! positions (random-between 0 king-posn) "R") + ; right-rook is between right-edge and king + (vector-set! positions (random-between (+ 1 king-posn) 8) "R"))) + ; + (define (place-bishops positions) + (let-values (((evens odds) (partition even? (free-indices positions)))) + (vector-set! positions (random-pick evens) "B") + (vector-set! positions (random-pick odds) "B"))) + ; + (let ((positions (make-vector 8 "."))) + (place-king+rooks positions) + (place-bishops positions) + ;; place the queen in a random remaining slot + (vector-set! positions (random-pick (free-indices positions)) "Q") + ;; place the two knights in the remaining slots + (for-each (lambda (idx) (vector-set! positions idx "N")) + (free-indices positions)) + + positions)) + +(display "First rank: ") (display (random-piece-positions)) (newline) diff --git a/Task/Generate-Chess960-starting-position/Zkl/generate-chess960-starting-position-1.zkl b/Task/Generate-Chess960-starting-position/Zkl/generate-chess960-starting-position-1.zkl new file mode 100644 index 0000000000..3a07b97849 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Zkl/generate-chess960-starting-position-1.zkl @@ -0,0 +1,8 @@ +const pieces="KQRrBbNN"; +starts:=pieces:Utils.Helpers.permuteW(_).filter(fcn(p){ + I:=p.index; + I("B") % 2 != I("b") % 2 and // Bishop constraint. + // King constraint. + ((I("r") < I("K") and I("K") < I("R")) or + (I("R") < I("K") and I("K") < I("r"))) +}).pump(List,"concat","toUpper"):Utils.Helpers.listUnique(_); diff --git a/Task/Generate-Chess960-starting-position/Zkl/generate-chess960-starting-position-2.zkl b/Task/Generate-Chess960-starting-position/Zkl/generate-chess960-starting-position-2.zkl new file mode 100644 index 0000000000..210f013162 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Zkl/generate-chess960-starting-position-2.zkl @@ -0,0 +1,4 @@ +N:=starts.len(); println(N); +glyphs:=Dictionary("K","\u2654", "Q","\u2655", "R","\u2656", "B","\u2657", "N","\u2658"); +// pick some random starts and transform BBNRKQRN to glyphs +do(10){ starts[(0).random(N)].apply(glyphs.find).println() } diff --git a/Task/Generate-lower-case-ASCII-alphabet/AppleScript/generate-lower-case-ascii-alphabet-1.applescript b/Task/Generate-lower-case-ASCII-alphabet/AppleScript/generate-lower-case-ascii-alphabet-1.applescript index 2d4f1eb221..c9d3f1bdf5 100644 --- a/Task/Generate-lower-case-ASCII-alphabet/AppleScript/generate-lower-case-ascii-alphabet-1.applescript +++ b/Task/Generate-lower-case-ASCII-alphabet/AppleScript/generate-lower-case-ascii-alphabet-1.applescript @@ -1,62 +1,60 @@ --- showCharRange :: String -> String -> [String] -on showCharRange(strFrom, strTo) - -- showChar :: Int -> String - script showChar - on lambda(intID) - character id intID - end lambda - end script - - map(showChar, range(id of strFrom, id of strTo)) -end showCharRange - - --- TEST on run - {showCharRange("a", "z"), ¬ - showCharRange("🐐", "🐟")} + {enumFromTo("a", "z"), ¬ + enumFromTo("🐐", "🐟")} end run +-- GENERIC FUNCTIONS ---------------------------------------------------------- ---------------------------------------------------------------------------- --- GENERIC FUNCTIONS +-- chr :: Int -> Char +on chr(n) + character id n +end chr --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map +-- ord :: Char -> Int +on ord(c) + id of c +end ord --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn +-- enumFromTo :: Enum a => a -> a -> [a] +on enumFromTo(m, n) + set {intM, intN} to {fromEnum(m), fromEnum(n)} --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then + if intM > intN then set d to -1 else set d to 1 end if set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat + if class of m is text then + repeat with i from intM to intN by d + set end of lst to chr(i) + end repeat + else + repeat with i from intM to intN by d + set end of lst to i + end repeat + end if return lst -end range +end enumFromTo + +-- fromEnum :: Enum a => a -> Int +on fromEnum(x) + set c to class of x + if c is boolean then + if x then + 1 + else + 0 + end if + else if c is text then + if x ≠ "" then + id of x + else + missing value + end if + else + x as integer + end if +end fromEnum diff --git a/Task/Generate-lower-case-ASCII-alphabet/BBC-BASIC/generate-lower-case-ascii-alphabet.bbc b/Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-1.basic similarity index 100% rename from Task/Generate-lower-case-ASCII-alphabet/BBC-BASIC/generate-lower-case-ascii-alphabet.bbc rename to Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-1.basic diff --git a/Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-2.basic b/Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-2.basic new file mode 100644 index 0000000000..be9b5cbfc7 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-2.basic @@ -0,0 +1,5 @@ +10 FOR I=ASC("A") TO ASC("Z") +20 A$ = A$+CHR$(I) +30 NEXT +40 PRINT CHR$(14) : REM 'SWITCH CHARACTER SET TO LOWER/UPPER CASES +50 PRINT A$ diff --git a/Task/Generate-lower-case-ASCII-alphabet/FreeBASIC/generate-lower-case-ascii-alphabet.freebasic b/Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-3.basic similarity index 100% rename from Task/Generate-lower-case-ASCII-alphabet/FreeBASIC/generate-lower-case-ascii-alphabet.freebasic rename to Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-3.basic diff --git a/Task/Generate-lower-case-ASCII-alphabet/PureBasic/generate-lower-case-ascii-alphabet.purebasic b/Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-4.basic similarity index 100% rename from Task/Generate-lower-case-ASCII-alphabet/PureBasic/generate-lower-case-ascii-alphabet.purebasic rename to Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-4.basic diff --git a/Task/Generate-lower-case-ASCII-alphabet/Run-BASIC/generate-lower-case-ascii-alphabet.run b/Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-5.basic similarity index 100% rename from Task/Generate-lower-case-ASCII-alphabet/Run-BASIC/generate-lower-case-ascii-alphabet.run rename to Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-5.basic diff --git a/Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-6.basic b/Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-6.basic new file mode 100644 index 0000000000..2c1a42d146 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-6.basic @@ -0,0 +1 @@ +For x= ORD("a") To ORD("z") : @(x - ORD("a")) = x : Next diff --git a/Task/Generate-lower-case-ASCII-alphabet/ZX-Spectrum-Basic/generate-lower-case-ascii-alphabet.zx b/Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-7.basic similarity index 100% rename from Task/Generate-lower-case-ASCII-alphabet/ZX-Spectrum-Basic/generate-lower-case-ascii-alphabet.zx rename to Task/Generate-lower-case-ASCII-alphabet/BASIC/generate-lower-case-ascii-alphabet-7.basic diff --git a/Task/Generate-lower-case-ASCII-alphabet/Batch-File/generate-lower-case-ascii-alphabet.bat b/Task/Generate-lower-case-ASCII-alphabet/Batch-File/generate-lower-case-ascii-alphabet.bat new file mode 100644 index 0000000000..5b04e7d551 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Batch-File/generate-lower-case-ascii-alphabet.bat @@ -0,0 +1,11 @@ +@echo off +setlocal enabledelayedexpansion + +:: This code appends the ASCII characters from 97-122 to %alphabet%, removing any room for error. + +for /l %%i in (97,1,122) do ( + cmd /c exit %%i + set "alphabet=!alphabet! !=exitcodeAscii!" +) +echo %alphabet% +pause>nul diff --git a/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet-1.lisp b/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet-1.lisp new file mode 100644 index 0000000000..98837d41db --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet-1.lisp @@ -0,0 +1,4 @@ +(defvar *lower* + (loop with a = (char-code #\a) + for i below 26 + collect (code-char (+ a i)))) diff --git a/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet-2.lisp b/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet-2.lisp new file mode 100644 index 0000000000..82bf5d1c43 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet-2.lisp @@ -0,0 +1,5 @@ +(defvar *lowercase-alphabet-string* + (map 'string #'code-char (loop + for c from (char-code #\a) to (char-code #\z) + collect c)) + "The 26 lower case letters in alphabetical order.") diff --git a/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet-3.lisp b/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet-3.lisp new file mode 100644 index 0000000000..942fd60b93 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet-3.lisp @@ -0,0 +1,4 @@ +(assert (= 26 (length *lowercase-alphabet-string*) (length *lower*))) +(assert (every #'char< *lowercase-alphabet-string* (subseq *lowercase-alphabet-string* 1))) +(assert (apply #'char< *lower*)) +(assert (string= *lowercase-alphabet-string* (coerce *lower* 'string))) diff --git a/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet.lisp b/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet.lisp deleted file mode 100644 index 5ef72bd592..0000000000 --- a/Task/Generate-lower-case-ASCII-alphabet/Common-Lisp/generate-lower-case-ascii-alphabet.lisp +++ /dev/null @@ -1,4 +0,0 @@ -(defvar *lower* - (loop with a = (char-code #\a) - for i upto 25 - collect (code-char (+ a i)))) diff --git a/Task/Generate-lower-case-ASCII-alphabet/Gambas/generate-lower-case-ascii-alphabet.gambas b/Task/Generate-lower-case-ASCII-alphabet/Gambas/generate-lower-case-ascii-alphabet.gambas new file mode 100644 index 0000000000..a8d67512f8 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Gambas/generate-lower-case-ascii-alphabet.gambas @@ -0,0 +1,8 @@ +Public Sub Main() +Dim siCount As Short + +For siCount = Asc("a") To Asc("z") + Print Chr(siCount); +Next + +End diff --git a/Task/Generate-lower-case-ASCII-alphabet/Haskell/generate-lower-case-ascii-alphabet-1.hs b/Task/Generate-lower-case-ASCII-alphabet/Haskell/generate-lower-case-ascii-alphabet-1.hs new file mode 100644 index 0000000000..24bbadbd88 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Haskell/generate-lower-case-ascii-alphabet-1.hs @@ -0,0 +1,3 @@ +lower = ['a' .. 'z'] + +main = print lower diff --git a/Task/Generate-lower-case-ASCII-alphabet/Haskell/generate-lower-case-ascii-alphabet-2.hs b/Task/Generate-lower-case-ASCII-alphabet/Haskell/generate-lower-case-ascii-alphabet-2.hs new file mode 100644 index 0000000000..d1019be143 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Haskell/generate-lower-case-ascii-alphabet-2.hs @@ -0,0 +1,5 @@ +alpha :: String +alpha = enumFromTo 'a' 'z' + +main :: IO () +main = print alpha diff --git a/Task/Generate-lower-case-ASCII-alphabet/Haskell/generate-lower-case-ascii-alphabet.hs b/Task/Generate-lower-case-ASCII-alphabet/Haskell/generate-lower-case-ascii-alphabet.hs deleted file mode 100644 index 4629d65cb4..0000000000 --- a/Task/Generate-lower-case-ASCII-alphabet/Haskell/generate-lower-case-ascii-alphabet.hs +++ /dev/null @@ -1,4 +0,0 @@ -lower = ['a' .. 'z'] - -main = do - print lower diff --git a/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-6.js b/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-6.js index 4d194803af..487caaebec 100644 --- a/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-6.js +++ b/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-6.js @@ -1,20 +1,55 @@ -(lstRanges => { - - // charRange :: Char -> Char -> [Char] - function charRange(cFrom, cTo) { - let [m, n] = [cFrom, cTo] - .map(s => s.codePointAt(0)); - +(() => { + // enumFromTo :: Enum a => a -> a -> [a] + const enumFromTo = (m, n) => { + const [intM, intN] = [m, n].map(fromEnum), + f = typeof m === 'string' ? ( + (_, i) => chr(intM + i) + ) : (_, i) => intM + i; return Array.from({ - length: (n - m) + 1 - }, (_, i) => String.fromCodePoint(m + i)); - } + length: Math.floor(intN - intM) + 1 + }, f); + }; + // GENERIC FUNCTIONS ------------------------------------------------------ - // TEST - return lstRanges - .map(([from, to]) => charRange(from, to).join(' ')) - .join('\n') + // compose :: (b -> c) -> (a -> b) -> (a -> c) + const compose = (f, g) => x => f(g(x)); -})([['a', 'z'], ['א','ת'],['α', 'ω'],['🐐', '🐟']]); + // chr :: Int -> Char + const chr = x => String.fromCodePoint(x); + + // ord :: Char -> Int + const ord = c => c.codePointAt(0); + + // fromEnum :: Enum a => a -> Int + const fromEnum = x => { + const type = typeof x; + return type === 'boolean' ? ( + x ? 1 : 0 + ) : type === 'string' ? ord(x) : x; + }; + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // show :: a -> String + const show = x => JSON.stringify(x); + + // uncurry :: Function -> Function + const uncurry = f => args => f.apply(null, args); + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + // unwords :: [String] -> String + const unwords = xs => xs.join(' '); + + // TEST ------------------------------------------------------------------- + return unlines(map(compose(unwords, uncurry(enumFromTo)), [ + ['a', 'z'], + ['α', 'ω'], + ['א', 'ת'], + ['🐐', '🐟'] + ])); +})(); diff --git a/Task/Generate-lower-case-ASCII-alphabet/jq/generate-lower-case-ascii-alphabet.jq b/Task/Generate-lower-case-ASCII-alphabet/Jq/generate-lower-case-ascii-alphabet.jq similarity index 100% rename from Task/Generate-lower-case-ASCII-alphabet/jq/generate-lower-case-ascii-alphabet.jq rename to Task/Generate-lower-case-ASCII-alphabet/Jq/generate-lower-case-ascii-alphabet.jq diff --git a/Task/Generate-lower-case-ASCII-alphabet/Kotlin/generate-lower-case-ascii-alphabet.kotlin b/Task/Generate-lower-case-ASCII-alphabet/Kotlin/generate-lower-case-ascii-alphabet.kotlin new file mode 100644 index 0000000000..5995e74dbf --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Kotlin/generate-lower-case-ascii-alphabet.kotlin @@ -0,0 +1,6 @@ +// version 1.0.6 + +fun main(args: Array) { + val alphabet = CharArray(26) { (it + 97).toChar() }.joinToString("") + println(alphabet) +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/R/generate-lower-case-ascii-alphabet.r b/Task/Generate-lower-case-ASCII-alphabet/R/generate-lower-case-ascii-alphabet.r index 9f4f99e7f3..a78277386b 100644 --- a/Task/Generate-lower-case-ASCII-alphabet/R/generate-lower-case-ascii-alphabet.r +++ b/Task/Generate-lower-case-ASCII-alphabet/R/generate-lower-case-ascii-alphabet.r @@ -1,2 +1,5 @@ # From constants built into R: letters + +# Or generate the same with: +sapply(97:122, intToUtf8) diff --git a/Task/Generate-lower-case-ASCII-alphabet/SPL/generate-lower-case-ascii-alphabet.spl b/Task/Generate-lower-case-ASCII-alphabet/SPL/generate-lower-case-ascii-alphabet.spl new file mode 100644 index 0000000000..4df6eca724 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/SPL/generate-lower-case-ascii-alphabet.spl @@ -0,0 +1,9 @@ +> i, 1..26 + d = [i+96,0] + a[i] = #.str(d) +< +'now A is an array of letters a..z + +> i, 1..#.size(a,1) + #.output(a[i],#.rs) +< diff --git a/Task/Generate-lower-case-ASCII-alphabet/Snobol/generate-lower-case-ascii-alphabet.sno b/Task/Generate-lower-case-ASCII-alphabet/Snobol/generate-lower-case-ascii-alphabet.sno new file mode 100644 index 0000000000..bd428682d2 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Snobol/generate-lower-case-ascii-alphabet.sno @@ -0,0 +1 @@ + &ALPHABET ('a' LEN(25)) . OUTPUT ;* Works in ASCII but not EBCDIC. diff --git a/Task/Generate-lower-case-ASCII-alphabet/Stata/generate-lower-case-ascii-alphabet.stata b/Task/Generate-lower-case-ASCII-alphabet/Stata/generate-lower-case-ascii-alphabet.stata new file mode 100644 index 0000000000..5080f44663 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Stata/generate-lower-case-ascii-alphabet.stata @@ -0,0 +1,13 @@ +// built-in: lowercase and uppercase letters +display c(alpha) +display c(ALPHA) + +// generate a variable with the letters +clear +set obs 26 +gen a=char(96+_n) + +// or in Mata +mata +char(97..122) +end diff --git a/Task/Generate-lower-case-ASCII-alphabet/XEec/generate-lower-case-ascii-alphabet.xeec b/Task/Generate-lower-case-ASCII-alphabet/XEec/generate-lower-case-ascii-alphabet.xeec new file mode 100644 index 0000000000..6918689c97 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/XEec/generate-lower-case-ascii-alphabet.xeec @@ -0,0 +1 @@ +h$` h$` >0_0 t h$y ms p h? jn00_0 p r h#1 ma t jn0_0 >00_0 p p r p diff --git a/Task/Generate-lower-case-ASCII-alphabet/Zkl/generate-lower-case-ascii-alphabet.zkl b/Task/Generate-lower-case-ASCII-alphabet/Zkl/generate-lower-case-ascii-alphabet.zkl new file mode 100644 index 0000000000..35394a8833 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Zkl/generate-lower-case-ascii-alphabet.zkl @@ -0,0 +1,6 @@ +["a".."z"] // lasy list +["a".."z"].walk() //-->L("a","b","c","d","e",... +"a".toAsc().pump(26,List,"toChar") // another way to create the list +"a".toAsc().pump(26,String,"toChar") // create a string + //-->"abcdefghijklmnopqrstuvwxyz" +Utils.Helpers.lowerLetters // string const diff --git a/Task/Generator-Exponential/C-sharp/generator-exponential-1.cs b/Task/Generator-Exponential/C-sharp/generator-exponential-1.cs deleted file mode 100644 index 2fdae5326c..0000000000 --- a/Task/Generator-Exponential/C-sharp/generator-exponential-1.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace RosettaGenerator -{ - class ClosureStyle - { - static void Main(string[] args) - { - Func squaresGenerator = PowerGeneratorAsClosure(2); - Func cubesGenerator = PowerGeneratorAsClosure(3); - - Func filter = FilterAsClosure(squaresGenerator, cubesGenerator); - - foreach (int i in Enumerable.Range(0, 20)) - filter(); - foreach (int i in Enumerable.Range(21, 10)) - Console.Write(filter() + " "); - Console.WriteLine(); - } - - public static Func PowerGeneratorAsClosure(int exponent) - { - int x = 0; - return () => { return (int)Math.Pow(x++, exponent); }; - } - - public static Func FilterAsClosure(Func squaresGenerator, Func cubesGenerator) - { - int squareValue; - int cubeValue = cubesGenerator(); - return () => - { - while (true) - { - squareValue = squaresGenerator(); - while (squareValue > cubeValue) - cubeValue = cubesGenerator(); - if (squareValue < cubeValue) - return squareValue; - } - }; - } - } -} diff --git a/Task/Generator-Exponential/C-sharp/generator-exponential-2.cs b/Task/Generator-Exponential/C-sharp/generator-exponential-2.cs deleted file mode 100644 index 00330b3ccd..0000000000 --- a/Task/Generator-Exponential/C-sharp/generator-exponential-2.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace RosettaGenerator -{ - class ListStyle - { - static void Main(string[] args) - { - IEnumerator squaresGenerator = PowerGeneratorAsList(2); - IEnumerator cubesGenerator = PowerGeneratorAsList(3); - - IEnumerable filter = FilterAsList(squaresGenerator, cubesGenerator); - - foreach (int value in filter.Skip(20).Take(10)) - Console.Write(value + " "); - Console.WriteLine(); - } - - public static IEnumerator PowerGeneratorAsList(int exponent) - { - int x = 0; - while (true) - yield return (int)Math.Pow(x++, exponent); - } - - public static IEnumerable FilterAsList(IEnumerator squaresGenerator, IEnumerator cubesGenerator) - { - int squareValue; - int cubeValue = cubesGenerator.Current; - while (true) - { - squareValue = squaresGenerator.Current; - while (squareValue > cubeValue) - { - cubesGenerator.MoveNext(); - cubeValue = cubesGenerator.Current; - } - if (squareValue < cubeValue) - yield return squareValue; - squaresGenerator.MoveNext(); - } - } - } -} diff --git a/Task/Generator-Exponential/C/generator-exponential-3.c b/Task/Generator-Exponential/C/generator-exponential-3.c deleted file mode 100644 index 91e1234705..0000000000 --- a/Task/Generator-Exponential/C/generator-exponential-3.c +++ /dev/null @@ -1,10 +0,0 @@ -529 -576 -625 -676 -784 -841 -900 -961 -1024 -1089 diff --git a/Task/Generator-Exponential/JavaScript/generator-exponential.js b/Task/Generator-Exponential/JavaScript/generator-exponential-1.js similarity index 100% rename from Task/Generator-Exponential/JavaScript/generator-exponential.js rename to Task/Generator-Exponential/JavaScript/generator-exponential-1.js diff --git a/Task/Generator-Exponential/JavaScript/generator-exponential-2.js b/Task/Generator-Exponential/JavaScript/generator-exponential-2.js new file mode 100644 index 0000000000..f4b942f784 --- /dev/null +++ b/Task/Generator-Exponential/JavaScript/generator-exponential-2.js @@ -0,0 +1,20 @@ +function* nPowerGen(n) { + let e = 0; + while (1) { e++ && (yield Math.pow(e, n)); } +} + +function* filterGen(gS, gC, skip=0) { + let s = 0; // The square value + let c = 0; // The cube value + let n = 0; // A skip counter + + while(1) { + s = gS.next().value; + s > c && (c = gC.next().value); + s == c ? + c = gC.next().value : + n++ && n > skip && (yield s); + } +} + +const filtered = filterGen(nPowerGen(2), nPowerGen(3), skip=20); diff --git a/Task/Generator-Exponential/JavaScript/generator-exponential-3.js b/Task/Generator-Exponential/JavaScript/generator-exponential-3.js new file mode 100644 index 0000000000..622697e3f8 --- /dev/null +++ b/Task/Generator-Exponential/JavaScript/generator-exponential-3.js @@ -0,0 +1,4 @@ +// Generate the first 10 values +for (let n = 0; n < 10; n++) { + console.log(filtered.next().value) +} diff --git a/Task/Generator-Exponential/jq/generator-exponential-1.jq b/Task/Generator-Exponential/Jq/generator-exponential-1.jq similarity index 100% rename from Task/Generator-Exponential/jq/generator-exponential-1.jq rename to Task/Generator-Exponential/Jq/generator-exponential-1.jq diff --git a/Task/Generator-Exponential/jq/generator-exponential-2.jq b/Task/Generator-Exponential/Jq/generator-exponential-2.jq similarity index 100% rename from Task/Generator-Exponential/jq/generator-exponential-2.jq rename to Task/Generator-Exponential/Jq/generator-exponential-2.jq diff --git a/Task/Generator-Exponential/jq/generator-exponential-3.jq b/Task/Generator-Exponential/Jq/generator-exponential-3.jq similarity index 100% rename from Task/Generator-Exponential/jq/generator-exponential-3.jq rename to Task/Generator-Exponential/Jq/generator-exponential-3.jq diff --git a/Task/Generator-Exponential/jq/generator-exponential-4.jq b/Task/Generator-Exponential/Jq/generator-exponential-4.jq similarity index 100% rename from Task/Generator-Exponential/jq/generator-exponential-4.jq rename to Task/Generator-Exponential/Jq/generator-exponential-4.jq diff --git a/Task/Generator-Exponential/jq/generator-exponential-5.jq b/Task/Generator-Exponential/Jq/generator-exponential-5.jq similarity index 100% rename from Task/Generator-Exponential/jq/generator-exponential-5.jq rename to Task/Generator-Exponential/Jq/generator-exponential-5.jq diff --git a/Task/Generator-Exponential/Kotlin/generator-exponential.kotlin b/Task/Generator-Exponential/Kotlin/generator-exponential.kotlin new file mode 100644 index 0000000000..d6fe942628 --- /dev/null +++ b/Task/Generator-Exponential/Kotlin/generator-exponential.kotlin @@ -0,0 +1,37 @@ +// version 1.1.0 +// compiled with flag -Xcoroutines=enable to suppress 'experimental' warning + +import kotlin.coroutines.experimental.buildSequence + +fun generatePowers(m: Int) = + buildSequence { + var n = 0 + val mm = m.toDouble() + while (true) yield(Math.pow((n++).toDouble(), mm).toLong()) + } + +fun generateNonCubicSquares(squares: Sequence, cubes: Sequence) = + buildSequence { + val iter2 = squares.iterator() + val iter3 = cubes.iterator() + var square = iter2.next() + var cube = iter3.next() + while (true) { + if (square > cube) { + cube = iter3.next() + continue + } else if (square < cube) { + yield(square) + } + square = iter2.next() + } + } + +fun main(args: Array) { + val squares = generatePowers(2) + val cubes = generatePowers(3) + val ncs = generateNonCubicSquares(squares, cubes) + print("Non-cubic squares (21st to 30th) : ") + ncs.drop(20).take(10).forEach { print("$it ") } // print 21st to 30th items + println() +} diff --git a/Task/Generator-Exponential/PARI-GP/generator-exponential.pari b/Task/Generator-Exponential/PARI-GP/generator-exponential.pari new file mode 100644 index 0000000000..fe5178f868 --- /dev/null +++ b/Task/Generator-Exponential/PARI-GP/generator-exponential.pari @@ -0,0 +1,5 @@ +g = List(1); \\ generator stack + +genpow(p) = my(a=g[1]++);listput(g,[0,p]);()->g[a][1]++^g[a][2]; + +genpowf(p,f) = my(a=g[1]++);listput(g,[0,p]);(s=0)->my(q);while(ispower(p=g[a][1]++^g[a][2],f)||(s&&q++<=s),);p; diff --git a/Task/Generator-Exponential/Phix/generator-exponential.phix b/Task/Generator-Exponential/Phix/generator-exponential.phix new file mode 100644 index 0000000000..8ce5659737 --- /dev/null +++ b/Task/Generator-Exponential/Phix/generator-exponential.phix @@ -0,0 +1,42 @@ +-- +-- demo\rosetta\Generator_Exponential.exw +-- ====================================== +-- +bool terminate = false + +atom res + +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(routine_id("powers"),{2}), + cubes = task_create(routine_id("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 cube20 then + ?square + end if +end for +terminate = 1 diff --git a/Task/Generator-Exponential/REXX/generator-exponential.rexx b/Task/Generator-Exponential/REXX/generator-exponential.rexx index 149af9f91a..5aaf5d1650 100644 --- a/Task/Generator-Exponential/REXX/generator-exponential.rexx +++ b/Task/Generator-Exponential/REXX/generator-exponential.rexx @@ -1,40 +1,36 @@ -/*REXX program demonstrates how to use a generator (also known as iterators).*/ -parse arg N .; if N=='' then N=20 /*N not specified? Then use default.*/ -@.= /* [↓] calculate squares,cubes,pureSq.*/ - do j=1 for N; call Gsquare j - call Gcube j - call GpureSquare j /*these are cube─free squares.*/ - end /*j*/ +/*REXX program demonstrates how to use a generator (also known as an iterator). */ +parse arg N .; if N=='' | N=="," then N=20 /*N not specified? Then use default.*/ +@.= /* [↓] calculate squares,cubes,pureSq.*/ + do i=1 for N; call Gsquare i + call Gcube i + call GpureSquare i /*these are cube─free square numbers.*/ + end /*i*/ - do k=1 for N; @.pureSquare.k=; end /*k*/ /*dropping 1st N values.*/ + do k=1 for N; @.pureSquare.k=; end /*k*/ /*this is used to drop 1st N values.*/ -w=length(N+10); ps='pure square' /*width of the numbers. */ +w=length(N+10); ps= 'pure square' /*the width of the numbers; a literal.*/ do m=N+1 for 10; say ps right(m, w)":" right(GpureSquare(m), 3*w) end /*m*/ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ Gpower: procedure expose @.; parse arg x,p; q=@.pow.x.p - if q\=='' then return q; _=x**p - if pos(.,_)\==0 then do - parse var _ 'E' e; numeric digits e+5; _=x**p - end /* [↑] re─calculate with more digits.*/ - @.pow.x.p=_ + if q\=='' then return q; _=x**p; @.pow.x.p=_ return _ -/*────────────────────────────────────────────────────────────────────────────*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ Gsquare: procedure expose @.; parse arg x; q=@.square.x - if q=='' then @.square.x=Gpower(x,2) + if q=='' then @.square.x=Gpower(x, 2) return @.square.x -/*────────────────────────────────────────────────────────────────────────────*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ Gcube: procedure expose @.; parse arg x; q=@.cube.x - if q=='' then @.cube.x=Gpower(x,3); _=@.cube.x; @.3pow._=1 + if q=='' then @.cube.x=Gpower(x, 3) _=@.cube.x; @.3pow._=1 return @.cube.x -/*────────────────────────────────────────────────────────────────────────────*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ GpureSquare: procedure expose @.; parse arg x; q=@.pureSquare.x if q\=='' then return q #=0 - do j=1 until #==x; ?=Gpower(j,2) /*search for pure square*/ - if @.3pow.?==1 then iterate /*is it a power of 3 ? */ - #=#+1; @.pureSquare.#=? /*assign next pureSquare*/ + do j=1 until #==x; ?=Gpower(j, 2) /*search for pure square. */ + if @.3pow.?==1 then iterate /*is it a power of three? */ + #=#+1; @.pureSquare.#=? /*assign next pureSquare. */ end /*j*/ return @.pureSquare.x diff --git a/Task/Generator-Exponential/Scheme/generator-exponential-1.ss b/Task/Generator-Exponential/Scheme/generator-exponential-1.ss deleted file mode 100644 index 8e72b6dd0f..0000000000 --- a/Task/Generator-Exponential/Scheme/generator-exponential-1.ss +++ /dev/null @@ -1,27 +0,0 @@ -(define (power-seq n) - (let ((i 0)) - (lambda () - (set! i (+ 1 i)) - (expt i n)))) - -(define (filter-seq m n) - (let* ((s1 (power-seq m)) (s2 (power-seq n)) - (a 0) (b 0)) - (lambda () - (set! a (s1)) - (let loop () - (if (>= a b) (begin - (cond ((> a b) (set! b (s2))) - ((= a b) (set! a (s1)))) - (loop)))) - a))) - -(let loop ((seq (filter-seq 2 3)) (i 0)) - (if (< i 30) - (begin - (if (> i 20) - (begin - (display (seq)) - (newline)) - (seq)) - (loop seq (+ 1 i))))) diff --git a/Task/Generator-Exponential/Scheme/generator-exponential-2.ss b/Task/Generator-Exponential/Scheme/generator-exponential-2.ss deleted file mode 100644 index 10bd1555bc..0000000000 --- a/Task/Generator-Exponential/Scheme/generator-exponential-2.ss +++ /dev/null @@ -1,9 +0,0 @@ -576 -625 -676 -784 -841 -900 -961 -1024 -1089 diff --git a/Task/Generator-Exponential/Zkl/generator-exponential-1.zkl b/Task/Generator-Exponential/Zkl/generator-exponential-1.zkl new file mode 100644 index 0000000000..bb1cc8301d --- /dev/null +++ b/Task/Generator-Exponential/Zkl/generator-exponential-1.zkl @@ -0,0 +1,13 @@ +fcn powers(m){ n:=0.0; while(1){vm.yield(n.pow(m).toInt()); n+=1} } +var squared=Utils.Generator(powers,2), cubed=Utils.Generator(powers,3); + +fcn filtered(sg,cg){s:=sg.next(); c:=cg.next(); + while(1){ + if(s>c){c=cg.next(); continue;} + else if(sc) { cg.next(); return(self.fcn(sg,cg)); } + sg.next(); return(s); +} +var f=[0..].tweak(filtered.fp(squared,cubed)) +f.drop(20).walk(10).println(); diff --git a/Task/Generic-swap/Dc/generic-swap-1.dc b/Task/Generic-swap/Dc/generic-swap-1.dc new file mode 100644 index 0000000000..06e1ab0e89 --- /dev/null +++ b/Task/Generic-swap/Dc/generic-swap-1.dc @@ -0,0 +1,2 @@ +1 2 SaSbLaLb f +=2 1 diff --git a/Task/Generic-swap/Dc/generic-swap-2.dc b/Task/Generic-swap/Dc/generic-swap-2.dc new file mode 100644 index 0000000000..f66e1bb403 --- /dev/null +++ b/Task/Generic-swap/Dc/generic-swap-2.dc @@ -0,0 +1,2 @@ +1 2 r f +=2 1 diff --git a/Task/Generic-swap/Elena/generic-swap.elena b/Task/Generic-swap/Elena/generic-swap.elena new file mode 100644 index 0000000000..1f256a9744 --- /dev/null +++ b/Task/Generic-swap/Elena/generic-swap.elena @@ -0,0 +1,24 @@ +import extensions. + +singleton swap +{ + eval ref:v1 ref:v2 + [ + var tmp := v1 value. + + v1 object := v2 value. + v2 object := tmp. + ] +} + +program = +[ + var n := 2. + var s := "abc". + + console printLine(n," ",s). + + swap eval ref:n ref:s. + + console printLine(n," ",s). +]. diff --git a/Task/Generic-swap/Gambas/generic-swap.gambas b/Task/Generic-swap/Gambas/generic-swap.gambas new file mode 100644 index 0000000000..9ea50f002d --- /dev/null +++ b/Task/Generic-swap/Gambas/generic-swap.gambas @@ -0,0 +1,9 @@ +Public Sub Main() +Dim vA As Variant = " World" +Dim vB As Variant = 1 + +Swap vA, vB + +Print vA; vB + +End diff --git a/Task/Generic-swap/JavaScript/generic-swap-2.js b/Task/Generic-swap/JavaScript/generic-swap-2.js index 27d11419f8..569207a41c 100644 --- a/Task/Generic-swap/JavaScript/generic-swap-2.js +++ b/Task/Generic-swap/JavaScript/generic-swap-2.js @@ -1,9 +1,9 @@ function swap(aName, bName) { - return ('(function(){ arguments[0] = aName; aName = bName; bName = arguments[0] })()' + eval('(function(){ arguments[0] = aName; aName = bName; bName = arguments[0] })()' .replace(/aName/g, aName) .replace(/bName/g, bName) ) } var x = 1 var y = 2 -eval(swap('x', 'y')) +swap('x', 'y') diff --git a/Task/Generic-swap/jq/generic-swap-1.jq b/Task/Generic-swap/Jq/generic-swap-1.jq similarity index 100% rename from Task/Generic-swap/jq/generic-swap-1.jq rename to Task/Generic-swap/Jq/generic-swap-1.jq diff --git a/Task/Generic-swap/jq/generic-swap-2.jq b/Task/Generic-swap/Jq/generic-swap-2.jq similarity index 100% rename from Task/Generic-swap/jq/generic-swap-2.jq rename to Task/Generic-swap/Jq/generic-swap-2.jq diff --git a/Task/Generic-swap/jq/generic-swap-3.jq b/Task/Generic-swap/Jq/generic-swap-3.jq similarity index 100% rename from Task/Generic-swap/jq/generic-swap-3.jq rename to Task/Generic-swap/Jq/generic-swap-3.jq diff --git a/Task/Generic-swap/Kotlin/generic-swap.kotlin b/Task/Generic-swap/Kotlin/generic-swap.kotlin new file mode 100644 index 0000000000..cea112162c --- /dev/null +++ b/Task/Generic-swap/Kotlin/generic-swap.kotlin @@ -0,0 +1,20 @@ +// version 1.1 + +fun swap(t1: T, t2: T) = Pair(t2, t1) + +fun main(args: Array) { + var a = 3 + var b = 4 + val c = swap(a, b) // infers that swap be used + a = c.first + b = c.second + println("a = $a") + println("b = $b") + var d = false + var e = true + val f = swap(d, e) // infers that swap be used + d = f.first + e = f.second + println("d = $d") + println("e = $e") +} diff --git a/Task/Generic-swap/Nimrod/generic-swap.nimrod b/Task/Generic-swap/Nimrod/generic-swap.nimrod deleted file mode 100644 index 0a57ac0104..0000000000 --- a/Task/Generic-swap/Nimrod/generic-swap.nimrod +++ /dev/null @@ -1 +0,0 @@ -swap(a, b) diff --git a/Task/Generic-swap/OASYS-Assembler/generic-swap-1.oasys b/Task/Generic-swap/OASYS-Assembler/generic-swap-1.oasys new file mode 100644 index 0000000000..dadf1e4dab --- /dev/null +++ b/Task/Generic-swap/OASYS-Assembler/generic-swap-1.oasys @@ -0,0 +1 @@ +%A#%B#<%B#%A#<>> diff --git a/Task/Generic-swap/OASYS-Assembler/generic-swap-2.oasys b/Task/Generic-swap/OASYS-Assembler/generic-swap-2.oasys new file mode 100644 index 0000000000..02363fc73f --- /dev/null +++ b/Task/Generic-swap/OASYS-Assembler/generic-swap-2.oasys @@ -0,0 +1 @@ +[&SW,A^,B^],A^<,B^<<,B^<,A^<<>> diff --git a/Task/Generic-swap/OASYS-Assembler/generic-swap-3.oasys b/Task/Generic-swap/OASYS-Assembler/generic-swap-3.oasys new file mode 100644 index 0000000000..a23b7da75f --- /dev/null +++ b/Task/Generic-swap/OASYS-Assembler/generic-swap-3.oasys @@ -0,0 +1 @@ ++%A#%B#&SW diff --git a/Task/Generic-swap/Stata/generic-swap.stata b/Task/Generic-swap/Stata/generic-swap.stata new file mode 100644 index 0000000000..4593c7463c --- /dev/null +++ b/Task/Generic-swap/Stata/generic-swap.stata @@ -0,0 +1,5 @@ +mata +a=1,2,3 +b="ars longa vita brevis" +swap(a, b) +end diff --git a/Task/Generic-swap/Zkl/generic-swap.zkl b/Task/Generic-swap/Zkl/generic-swap.zkl new file mode 100644 index 0000000000..ddfda4996a --- /dev/null +++ b/Task/Generic-swap/Zkl/generic-swap.zkl @@ -0,0 +1,9 @@ +class C{var v; fcn init(n){v=n}} +var c1=C(1), c2=C(2); +println(c1.v," : ",c2.v); +fcn swap(ca,cb,name){ + tmp:=ca.resove(name); + ca.setVar(name,cb.resolve(name)); cb.setVar(name,tmp) +} +swap(c1,c2,"v"); +println(c1.v," : ",c2.v); diff --git a/Task/Globally-replace-text-in-several-files/Jq/globally-replace-text-in-several-files-1.jq b/Task/Globally-replace-text-in-several-files/Jq/globally-replace-text-in-several-files-1.jq new file mode 100644 index 0000000000..b704501010 --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/Jq/globally-replace-text-in-several-files-1.jq @@ -0,0 +1,5 @@ +for file +do + jq -Rr 'gsub($from; $to)' --arg from 'Goodbye London!' --arg to 'Hello New York!' "$file" | + sponge "$file" +done diff --git a/Task/Globally-replace-text-in-several-files/Jq/globally-replace-text-in-several-files-2.jq b/Task/Globally-replace-text-in-several-files/Jq/globally-replace-text-in-several-files-2.jq new file mode 100644 index 0000000000..f64aa3cc29 --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/Jq/globally-replace-text-in-several-files-2.jq @@ -0,0 +1,6 @@ +def gsubst($from; $to): + ($from | length) as $len + | def g: + index($from) as $ix + | if $ix then .[:$ix] + $to + (.[($ix+$len):] | g) else . end; + g; diff --git a/Task/Globally-replace-text-in-several-files/Phix/globally-replace-text-in-several-files.phix b/Task/Globally-replace-text-in-several-files/Phix/globally-replace-text-in-several-files.phix new file mode 100644 index 0000000000..09eb361fd5 --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/Phix/globally-replace-text-in-several-files.phix @@ -0,0 +1,16 @@ +procedure global_replace(string s, string r, sequence file_list) + for i=1 to length(file_list) do + string filename = file_list[i] + integer fn = open(filename,"rb") + if fn=-1 then ?9/0 end if -- message/retry? + string text = get_text(fn) + close(fn) + text = substitute(text,s,r) + fn = open(filename,"wb") + puts(fn,text) + close(fn) + end for +end procedure + +sequence file_list = {"ctrace.out"} +global_replace("Goodbye London!", "Hello New York!", file_list) diff --git a/Task/Globally-replace-text-in-several-files/Sidef/globally-replace-text-in-several-files.sidef b/Task/Globally-replace-text-in-several-files/Sidef/globally-replace-text-in-several-files.sidef index 90a7f91c94..ad3ee5c674 100644 --- a/Task/Globally-replace-text-in-several-files/Sidef/globally-replace-text-in-several-files.sidef +++ b/Task/Globally-replace-text-in-several-files/Sidef/globally-replace-text-in-several-files.sidef @@ -1,11 +1,11 @@ -var files = %w( +var names = %w( a.txt b.txt c.txt - ); - -files.map{.to_file}.each { |file| + ) +  +names.map{ File(_) }.each { |file| say file.edit { |line| - line.gsub("Goodbye London!", "Hello New York!"); - }; + line.gsub("Goodbye London!", "Hello New York!") + } } diff --git a/Task/Globally-replace-text-in-several-files/Zkl/globally-replace-text-in-several-files-1.zkl b/Task/Globally-replace-text-in-several-files/Zkl/globally-replace-text-in-several-files-1.zkl new file mode 100644 index 0000000000..a498e830c5 --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/Zkl/globally-replace-text-in-several-files-1.zkl @@ -0,0 +1,11 @@ +fcn sed(data,src,dst){ + srcSz:=src.len(); dstSz:=dst.len(); md5:=Utils.MD5.calc(data); + n:=0; while(Void!=(n:=data.find(src,n))) + { data.del(n,srcSz); data.insert(n,dst); n+= dstSz; } + return(md5!=Utils.MD5.calc(data)); // changed? +} +fcn sedFile(fname,src,dst){ + f:=File(fname,"r"); data:=f.read(); f.close(); + if(sed(data,"Goodbye London!", "Hello New York!")) + { f:=File(fname,"w"); f.write(data); f.close(); } +} diff --git a/Task/Globally-replace-text-in-several-files/Zkl/globally-replace-text-in-several-files-2.zkl b/Task/Globally-replace-text-in-several-files/Zkl/globally-replace-text-in-several-files-2.zkl new file mode 100644 index 0000000000..f3d4c002df --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/Zkl/globally-replace-text-in-several-files-2.zkl @@ -0,0 +1,2 @@ +vm.arglist.apply2(sedFile); +$ zkl bbb foo.txt bar.txt diff --git a/Task/Gray-code/Bc/gray-code.bc b/Task/Gray-code/Bc/gray-code.bc new file mode 100644 index 0000000000..ef2e8936dc --- /dev/null +++ b/Task/Gray-code/Bc/gray-code.bc @@ -0,0 +1,46 @@ +scale = 0 /* to use integer division */ + +/* encode Gray code */ +define e(i) { + auto h, r + + if (i <= 0) return 0 + h = i / 2 + r = e(h) * 2 /* recurse */ + if (h % 2 != i % 2) r += 1 /* xor low bits of h, i */ + return r +} + +/* decode Gray code */ +define d(i) { + auto h, r + + if (i <= 0) return 0 + h = d(i / 2) /* recurse */ + r = h * 2 + if (h % 2 != i % 2) r += 1 /* xor low bits of h, i */ + return r +} + + +/* print i as 5 binary digits */ +define p(i) { + auto d, d[] + + for (d = 0; d <= 4; d++) { + d[d] = i % 2 + i /= 2 + } + for (d = 4; d >= 0; d--) { + if(d[d] == 0) "0" + if(d[d] == 1) "1" + } +} + +for (i = 0; i < 32; i++) { + /* original */ t = p(i); " => " + /* encoded */ e = e(i); t = p(e); " => " + /* decoded */ d = d(e); t = p(d); " +" +} +quit diff --git a/Task/Gray-code/Crystal/gray-code-1.crystal b/Task/Gray-code/Crystal/gray-code-1.crystal new file mode 100644 index 0000000000..df2699cf8f --- /dev/null +++ b/Task/Gray-code/Crystal/gray-code-1.crystal @@ -0,0 +1,12 @@ +def gray_encode(bin) + bin ^ (bin >> 1) +end + +def gray_decode(gray) + bin = gray + while gray > 0 + gray >>= 1 + bin ^= gray + end + bin +end diff --git a/Task/Gray-code/Crystal/gray-code-2.crystal b/Task/Gray-code/Crystal/gray-code-2.crystal new file mode 100644 index 0000000000..63dbbaeea3 --- /dev/null +++ b/Task/Gray-code/Crystal/gray-code-2.crystal @@ -0,0 +1,5 @@ +(0..31).each do |n| + gr = gray_encode n + bin = gray_decode gr + printf "%2d : %05b => %05b => %05b : %2d\n", n, n, gr, bin, bin +end diff --git a/Task/Gray-code/D/gray-code-2.d b/Task/Gray-code/D/gray-code-2.d index af792710c9..da3bc19dc3 100644 --- a/Task/Gray-code/D/gray-code-2.d +++ b/Task/Gray-code/D/gray-code-2.d @@ -17,7 +17,7 @@ T[][] grayDict(int N, T)() pure nothrow { T[][] dict = [gray!(N, T)(), [0]]; // Append inversed gray encoding mapping. foreach (immutable i; 1 .. dict[0].length) - dict[1] ~= countUntil(dict[0], i); + dict[1] ~= cast(T)countUntil(dict[0], i); return dict; } diff --git a/Task/Gray-code/FreeBASIC/gray-code.freebasic b/Task/Gray-code/FreeBASIC/gray-code.freebasic new file mode 100644 index 0000000000..95722fd32a --- /dev/null +++ b/Task/Gray-code/FreeBASIC/gray-code.freebasic @@ -0,0 +1,41 @@ +' version 18-01-2017 +' compile with: fbc -s console + +Function gray2bin(g As UInteger) As UInteger + + Dim As UInteger b = g + + While g + g Shr= 1 + b Xor= g + Wend + + Return b + +End Function + +Function bin2gray(b As UInteger) As UInteger + + Return b Xor (b Shr 1) + +End Function + +' ------=< MAIN >=------ + +Dim As UInteger i + +Print " i binary gray gra2bin" +Print String(32,"=") + +For i = 0 To 31 + Print Using "## --> "; i; + print Bin(i,5); " --> "; + Print Bin(bin2gray(i),5); " --> "; + Print Bin(gray2bin(bin2gray(i)),5) +Next + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Gray-code/Kotlin/gray-code.kotlin b/Task/Gray-code/Kotlin/gray-code.kotlin new file mode 100644 index 0000000000..464fa99d13 --- /dev/null +++ b/Task/Gray-code/Kotlin/gray-code.kotlin @@ -0,0 +1,24 @@ +// version 1.0.6 + +object Gray { + fun encode(n: Int) = n xor (n shr 1) + + fun decode(n: Int): Int { + var p = n + var nn = n + while (nn != 0) { + nn = nn shr 1 + p = p xor nn + } + return p + } +} + +fun main(args: Array) { + println("Number\tBinary\tGray\tDecoded") + for (i in 0..31) { + print("$i\t${Integer.toBinaryString(i)}\t") + val g = Gray.encode(i) + println("${Integer.toBinaryString(g)}\t${Gray.decode(g)}") + } +} diff --git a/Task/Gray-code/PHP/gray-code-1.php b/Task/Gray-code/PHP/gray-code-1.php deleted file mode 100644 index 9ce3e0152d..0000000000 --- a/Task/Gray-code/PHP/gray-code-1.php +++ /dev/null @@ -1,28 +0,0 @@ -> 1); -} - -/** - * @param int $gray - * @return int - */ -function gray_decode($gray){ - $binary = $gray; - while($gray >>= 1) $binary ^= $gray; - return $binary; -} - -for($i=0;$i<32;$i++){ - $gray_encoded = gray_encode($i); - printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); -} diff --git a/Task/Gray-code/PHP/gray-code-2.php b/Task/Gray-code/PHP/gray-code-2.php deleted file mode 100644 index 220e2f5522..0000000000 --- a/Task/Gray-code/PHP/gray-code-2.php +++ /dev/null @@ -1,31 +0,0 @@ -(stringrange, stringsize): -Gray_code: procedure options (main); /* 15 November 2013 */ - declare (bin(0:31), g(0:31), b2(0:31)) bit (5); - declare (c, carry) bit (1); - declare (i, j) fixed binary (7); - - bin(0) = '00000'b; - do i = 0 to 31; - if i > 0 then - do; - carry = '1'b; - bin(i) = bin(i-1); - do j = 5 to 1 by -1; - c = substr(bin(i), j, 1) & carry; - substr(bin(i), j, 1) = substr(bin(i), j, 1) ^ carry; - carry = c; - end; - end; - g(i) = bin(i) ^ '0'b || substr(bin(i), 1, 4); - end; - do i = 0 to 31; - substr(b2(i), 1, 1) = substr(g(i), 1, 1); - do j = 2 to 5; - substr(b2(i), j, 1) = substr(g(i), j, 1) ^ substr(bin(i), j-1, 1); - end; - end; - - do i = 0 to 31; - put skip edit (i, bin(i), g(i), b2(i)) (f(2), 3(x(1), b)); - end; -end Gray_code; diff --git a/Task/Gray-code/Sidef/gray-code.sidef b/Task/Gray-code/Sidef/gray-code.sidef index 9cad9c2366..aada5efa75 100644 --- a/Task/Gray-code/Sidef/gray-code.sidef +++ b/Task/Gray-code/Sidef/gray-code.sidef @@ -1,14 +1,14 @@ func bin2gray(n) { - n ^ (n >> 1); + n ^ (n >> 1) } func gray2bin(num) { - var bin = num; - while (num >>= 1) { bin ^= num }; - return bin; + var bin = num + while (num >>= 1) { bin ^= num } + return bin } -0..31 -> each { |i| - var gr = bin2gray(i); - printf("%d\t%b\t%b\t%b\n", i, i, gr, gray2bin(gr)); -} +{ |i| + var gr = bin2gray(i) + printf("%d\t%b\t%b\t%b\n", i, i, gr, gray2bin(gr)) +} << ^32 diff --git a/Task/Gray-code/Zkl/gray-code-1.zkl b/Task/Gray-code/Zkl/gray-code-1.zkl new file mode 100644 index 0000000000..947ea194a3 --- /dev/null +++ b/Task/Gray-code/Zkl/gray-code-1.zkl @@ -0,0 +1,2 @@ +fcn grayEncode(n){ n.bitXor(n.shiftRight(1)) } +fcn grayDecode(g){ b:=g; while(g/=2){ b=b.bitXor(g) } b } diff --git a/Task/Gray-code/Zkl/gray-code-2.zkl b/Task/Gray-code/Zkl/gray-code-2.zkl new file mode 100644 index 0000000000..a84128d040 --- /dev/null +++ b/Task/Gray-code/Zkl/gray-code-2.zkl @@ -0,0 +1,4 @@ +foreach n in ([0..31]){ + g:=grayEncode(n); b:=grayDecode(g); + println("%2d(%05.2B) --> %2d(%05.2B) --> %2d(%05.2B)".fmt(n,n,g,g,b,b)); +} diff --git a/Task/Grayscale-image/Zkl/grayscale-image-1.zkl b/Task/Grayscale-image/Zkl/grayscale-image-1.zkl new file mode 100644 index 0000000000..91a540189c --- /dev/null +++ b/Task/Grayscale-image/Zkl/grayscale-image-1.zkl @@ -0,0 +1,7 @@ +fcn toGrayScale(img){ // in-place conversion + foreach x,y in (img.w,img.h){ + r,g,b:=img[x,y].toBigEndian(3); + lum:=(0.2126*r + 0.7152*g + 0.0722*b).toInt(); + img[x,y]=((lum*256) + lum)*256 + lum; + } +} diff --git a/Task/Grayscale-image/Zkl/grayscale-image-2.zkl b/Task/Grayscale-image/Zkl/grayscale-image-2.zkl new file mode 100644 index 0000000000..69a052c343 --- /dev/null +++ b/Task/Grayscale-image/Zkl/grayscale-image-2.zkl @@ -0,0 +1,3 @@ +img:=PPM.readPPMFile("lena.ppm"); +toGrayScale(img); +img.write(File("foo.ppm","wb")); diff --git a/Task/Greatest-common-divisor/Alore/greatest-common-divisor-1.alore b/Task/Greatest-common-divisor/Alore/greatest-common-divisor-1.alore deleted file mode 100644 index 4d1ae8100d..0000000000 --- a/Task/Greatest-common-divisor/Alore/greatest-common-divisor-1.alore +++ /dev/null @@ -1,6 +0,0 @@ -def gcd(a as Int, b as Int) as Int - while b != 0 - a,b = b, a mod b - end - return Abs(a) -end diff --git a/Task/Greatest-common-divisor/Alore/greatest-common-divisor-2.alore b/Task/Greatest-common-divisor/Alore/greatest-common-divisor-2.alore deleted file mode 100644 index 4c247b32a5..0000000000 --- a/Task/Greatest-common-divisor/Alore/greatest-common-divisor-2.alore +++ /dev/null @@ -1,14 +0,0 @@ -_GCD(18, 12) -_GCD(1071, 1029) -_GCD(3528, 3780) - -Func _GCD($ia, $ib) - Local $ret = "GCD of " & $ia & " : " & $ib & " = " - Local $imod - While True - $imod = Mod($ia, $ib) - If $imod = 0 Then Return ConsoleWrite($ret & $ib & @CRLF) - $ia = $ib - $ib = $imod - WEnd -EndFunc ;==>_GCD diff --git a/Task/Greatest-common-divisor/BASIC/greatest-common-divisor-3.basic b/Task/Greatest-common-divisor/BASIC/greatest-common-divisor-3.basic new file mode 100644 index 0000000000..8cb5cfd10b --- /dev/null +++ b/Task/Greatest-common-divisor/BASIC/greatest-common-divisor-3.basic @@ -0,0 +1,8 @@ + 10 LET M=119 + 20 LET N=544 + 30 LET R=M-N*INT (M/N) + 40 IF R=0 THEN GOTO 80 + 50 LET M=N + 60 LET N=R + 70 GOTO 30 + 80 PRINT N diff --git a/Task/Greatest-common-divisor/Clojure/greatest-common-divisor-3.clj b/Task/Greatest-common-divisor/Clojure/greatest-common-divisor-3.clj new file mode 100644 index 0000000000..ba273c3728 --- /dev/null +++ b/Task/Greatest-common-divisor/Clojure/greatest-common-divisor-3.clj @@ -0,0 +1,8 @@ +(defn stein-gcd [a b] + (cond + (zero? a) b + (zero? b) a + (and (even? a) (even? b)) (* 2 (stein-gcd (unsigned-bit-shift-right a 1) (unsigned-bit-shift-right b 1))) + (and (even? a) (odd? b)) (recur (unsigned-bit-shift-right a 1) b) + (and (odd? a) (even? b)) (recur a (unsigned-bit-shift-right b 1)) + (and (odd? a) (odd? b)) (recur (unsigned-bit-shift-right (Math/abs (- a b)) 1) (min a b)))) diff --git a/Task/Greatest-common-divisor/Frink/greatest-common-divisor-1.frink b/Task/Greatest-common-divisor/Frink/greatest-common-divisor-1.frink deleted file mode 100644 index 5f3dcda643..0000000000 --- a/Task/Greatest-common-divisor/Frink/greatest-common-divisor-1.frink +++ /dev/null @@ -1 +0,0 @@ -println[gcd[12345,98765]] diff --git a/Task/Greatest-common-divisor/Frink/greatest-common-divisor-2.frink b/Task/Greatest-common-divisor/Frink/greatest-common-divisor-2.frink deleted file mode 100644 index c4243cbd50..0000000000 --- a/Task/Greatest-common-divisor/Frink/greatest-common-divisor-2.frink +++ /dev/null @@ -1,19 +0,0 @@ -# Built-in -GcdInt(35, 42); -# 7 - -# Euclidean algorithm -GcdInteger := function(a, b) - local c; - a := AbsInt(a); - b := AbsInt(b); - while b > 0 do - c := a; - a := b; - b := RemInt(c, b); - od; - return a; -end; - -GcdInteger(35, 42); -# 7 diff --git a/Task/Greatest-common-divisor/Gnuplot/greatest-common-divisor-1.gnuplot b/Task/Greatest-common-divisor/Gnuplot/greatest-common-divisor-1.gnuplot new file mode 100644 index 0000000000..c2adfdabda --- /dev/null +++ b/Task/Greatest-common-divisor/Gnuplot/greatest-common-divisor-1.gnuplot @@ -0,0 +1 @@ +gcd (a, b) = b == 0 ? a : gcd (b, a % b) diff --git a/Task/Greatest-common-divisor/Gnuplot/greatest-common-divisor-2.gnuplot b/Task/Greatest-common-divisor/Gnuplot/greatest-common-divisor-2.gnuplot new file mode 100644 index 0000000000..1a158b0384 --- /dev/null +++ b/Task/Greatest-common-divisor/Gnuplot/greatest-common-divisor-2.gnuplot @@ -0,0 +1 @@ +print gcd (111111, 1111) diff --git a/Task/Greatest-common-divisor/Gnuplot/greatest-common-divisor-3.gnuplot b/Task/Greatest-common-divisor/Gnuplot/greatest-common-divisor-3.gnuplot new file mode 100644 index 0000000000..b4de394767 --- /dev/null +++ b/Task/Greatest-common-divisor/Gnuplot/greatest-common-divisor-3.gnuplot @@ -0,0 +1 @@ +11 diff --git a/Task/Greatest-common-divisor/Haskell/greatest-common-divisor.hs b/Task/Greatest-common-divisor/Haskell/greatest-common-divisor.hs index 4a87199613..3ff34b674a 100644 --- a/Task/Greatest-common-divisor/Haskell/greatest-common-divisor.hs +++ b/Task/Greatest-common-divisor/Haskell/greatest-common-divisor.hs @@ -1,5 +1,5 @@ gcd :: (Integral a) => a -> a -> a -gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined" -gcd x y = gcd' (abs x) (abs y) where - gcd' a 0 = a - gcd' a b = gcd' b (a `rem` b) +gcd x y = gcd_ (abs x) (abs y) + where + gcd_ a 0 = a + gcd_ a b = gcd_ b (a `rem` b) diff --git a/Task/Greatest-common-divisor/jq/greatest-common-divisor-1.jq b/Task/Greatest-common-divisor/Jq/greatest-common-divisor-1.jq similarity index 100% rename from Task/Greatest-common-divisor/jq/greatest-common-divisor-1.jq rename to Task/Greatest-common-divisor/Jq/greatest-common-divisor-1.jq diff --git a/Task/Greatest-common-divisor/jq/greatest-common-divisor-2.jq b/Task/Greatest-common-divisor/Jq/greatest-common-divisor-2.jq similarity index 100% rename from Task/Greatest-common-divisor/jq/greatest-common-divisor-2.jq rename to Task/Greatest-common-divisor/Jq/greatest-common-divisor-2.jq diff --git a/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-1.nimrod b/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-1.nimrod deleted file mode 100644 index d142fd38b0..0000000000 --- a/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-1.nimrod +++ /dev/null @@ -1,5 +0,0 @@ -proc gcd_recursive(u, v: int64): int64 = - if u %% v != 0: - result = gcd_recursive(v, u %% v) - else: - result = v diff --git a/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-2.nimrod b/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-2.nimrod deleted file mode 100644 index d4eacdbfe8..0000000000 --- a/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-2.nimrod +++ /dev/null @@ -1,9 +0,0 @@ -proc gcd_iterative(u1, v1: int64): int64 = - var t: int64 = 0 - var u = u1 - var v = v1 - while v != 0: - t = u - u = v - v = t %% v - result = abs(u) diff --git a/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-3.nimrod b/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-3.nimrod deleted file mode 100644 index c6eb2b88b1..0000000000 --- a/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-3.nimrod +++ /dev/null @@ -1,35 +0,0 @@ -proc gcd_binary(u1, v1: int64): int64 = - var t, k: int64 - var u = u1 - var v = v1 - u = abs(u) - v = abs(v) - if u < v: - t = u - u = v - v = t - if v == 0: - result = u - else: - k = 1 - while (u %% 2 == 0) and (v %% 2 == 0): - u = u shl 1 - v = v shl 1 - k = k shr 1 - if (u %% 2) == 0: - t = u - else: - t = -v - while t != 0: - while (t %% 2) == 0: - t = t div 2 - if t > 0: - u = t - else: - v = -t - t = u - v - result = u * k - -echo ("GCD(", 49865, ", ", 69811, "): ", gcd_iterative(49865, 69811), " (iterative)") -echo ("GCD(", 49865, ", ", 69811, "): ", gcd_recursive(49865, 69811), " (recursive)") -echo ("GCD(", 49865, ", ", 69811, "): ", gcd_binary (49865, 69811), " (binary)") diff --git a/Task/Greatest-common-divisor/R/greatest-common-divisor-3.r b/Task/Greatest-common-divisor/R/greatest-common-divisor-3.r deleted file mode 100644 index e2b41c8f09..0000000000 --- a/Task/Greatest-common-divisor/R/greatest-common-divisor-3.r +++ /dev/null @@ -1 +0,0 @@ -print(50 %gcd% 75) diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-4.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-4.rust index 9226e291d3..9be3299b53 100644 --- a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-4.rust +++ b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-4.rust @@ -1,7 +1,13 @@ - println!("{}",gcd(399,-3999)); - println!("{}",gcd(0,3999)); - println!("{}",gcd(13*13,13*29)); - -3 -3999 -13 +use std::cmp::{min, max}; +fn gcd(a: usize, b: usize) -> usize { + match ((a, b), (a & 1, b & 1)) { + ((x, y), _) if x == y => y, + ((0, x), _) | ((x, 0), _) => x, + ((x, y), (0, 1)) | ((y, x), (1, 0)) => gcd(x >> 1, y), + ((x, y), (0, 0)) => gcd(x >> 1, y >> 1) << 1, + ((x, y), (1, 1)) => { let (x, y) = (min(x, y), max(x, y)); + gcd((y - x) >> 1, x) + } + _ => unreachable!(), + } +} diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-5.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-5.rust new file mode 100644 index 0000000000..9226e291d3 --- /dev/null +++ b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-5.rust @@ -0,0 +1,7 @@ + println!("{}",gcd(399,-3999)); + println!("{}",gcd(0,3999)); + println!("{}",gcd(13*13,13*29)); + +3 +3999 +13 diff --git a/Task/Greatest-common-divisor/Standard-ML/greatest-common-divisor.ml b/Task/Greatest-common-divisor/Standard-ML/greatest-common-divisor.ml deleted file mode 100644 index 450eb66767..0000000000 --- a/Task/Greatest-common-divisor/Standard-ML/greatest-common-divisor.ml +++ /dev/null @@ -1,2 +0,0 @@ -fun gcd a 0 = a - | gcd a b = gcd b (a mod b) diff --git a/Task/Greatest-common-divisor/TXR/greatest-common-divisor.txr b/Task/Greatest-common-divisor/TXR/greatest-common-divisor.txr index 20242a646f..800aa17d31 100644 --- a/Task/Greatest-common-divisor/TXR/greatest-common-divisor.txr +++ b/Task/Greatest-common-divisor/TXR/greatest-common-divisor.txr @@ -1,2 +1,2 @@ -$ txr -c @(bind g @(gcd (expt 2 123) (expt 6 49))) -g="562949953421312" +$ txr -p '(gcd (expt 2 123) (expt 6 49))' +562949953421312 diff --git a/Task/Greatest-common-divisor/X86-Assembly/greatest-common-divisor.x86 b/Task/Greatest-common-divisor/X86-Assembly/greatest-common-divisor.x86 new file mode 100644 index 0000000000..9237d0a12c --- /dev/null +++ b/Task/Greatest-common-divisor/X86-Assembly/greatest-common-divisor.x86 @@ -0,0 +1,24 @@ +.text +.global pgcd + +pgcd: + push %ebp + mov %esp, %ebp + + mov 8(%ebp), %eax + mov 12(%ebp), %ecx + push %edx + +.loop: + cmp $0, %ecx + je .end + xor %edx, %edx + div %ecx + mov %ecx, %eax + mov %edx, %ecx + jmp .loop + +.end: + pop %edx + leave + ret diff --git a/Task/Greatest-common-divisor/Zkl/greatest-common-divisor-1.zkl b/Task/Greatest-common-divisor/Zkl/greatest-common-divisor-1.zkl new file mode 100644 index 0000000000..4c21b23f39 --- /dev/null +++ b/Task/Greatest-common-divisor/Zkl/greatest-common-divisor-1.zkl @@ -0,0 +1 @@ +(123456789).gcd(987654321) //-->9 diff --git a/Task/Greatest-common-divisor/Zkl/greatest-common-divisor-2.zkl b/Task/Greatest-common-divisor/Zkl/greatest-common-divisor-2.zkl new file mode 100644 index 0000000000..70cf06a638 --- /dev/null +++ b/Task/Greatest-common-divisor/Zkl/greatest-common-divisor-2.zkl @@ -0,0 +1,2 @@ +var BN=Import("zklBigNum"); +BN(123456789).gcd(987654321) //-->9 diff --git a/Task/Greatest-common-divisor/Zkl/greatest-common-divisor-3.zkl b/Task/Greatest-common-divisor/Zkl/greatest-common-divisor-3.zkl new file mode 100644 index 0000000000..0885ce9748 --- /dev/null +++ b/Task/Greatest-common-divisor/Zkl/greatest-common-divisor-3.zkl @@ -0,0 +1 @@ +fcn gcd(a,b){ while(b){ t:=a; a=b; b=t%b } a.abs() } diff --git a/Task/Greatest-element-of-a-list/APL/greatest-element-of-a-list-1.apl b/Task/Greatest-element-of-a-list/APL/greatest-element-of-a-list-1.apl deleted file mode 100644 index ab345d8fe1..0000000000 --- a/Task/Greatest-element-of-a-list/APL/greatest-element-of-a-list-1.apl +++ /dev/null @@ -1,2 +0,0 @@ -LIST←2 4 6 3 8 -⌈/LIST diff --git a/Task/Greatest-element-of-a-list/APL/greatest-element-of-a-list-2.apl b/Task/Greatest-element-of-a-list/APL/greatest-element-of-a-list-2.apl deleted file mode 100644 index 45a4fb75db..0000000000 --- a/Task/Greatest-element-of-a-list/APL/greatest-element-of-a-list-2.apl +++ /dev/null @@ -1 +0,0 @@ -8 diff --git a/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list-2.applescript b/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list-2.applescript index 74d3e395a1..4e845788ff 100644 --- a/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list-2.applescript +++ b/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list-2.applescript @@ -1,25 +1,24 @@ -- maximumBy :: (a -> a -> Ordering) -> [a] -> a on maximumBy(f, xs) + set cmp to mReturn(f) script max - property cmp : f - on lambda(a, b) - if a is missing value or cmp(a, b) < 0 then + on |λ|(a, b) + if a is missing value or cmp's |λ|(a, b) < 0 then b else a end if - end lambda + end |λ| end script foldl(max, missing value, xs) end maximumBy - --- TEST +-- TEST ----------------------------------------------------------------------- on run set lstWords to ["alpha", "beta", "gamma", "delta", "epsilon", ¬ - "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu"] + "zeta", "eta", "theta", "iota", "kappa", "|λ|", "mu"] set lstCities to [{name:"Shanghai", population:24.15}, ¬ {name:"Karachi", population:23.5}, ¬ @@ -29,89 +28,41 @@ on run {name:"Lagos", population:13.4}, ¬ {name:"Tokyo", population:13.3}] - return {¬ - maximumBy(wordAZ, lstWords), ¬ - maximumBy(wordZA, lstWords), ¬ - maximumBy(wordLong, lstWords), ¬ - maximumBy(wordShort, lstWords), ¬ - maximumBy(cityMostPopulation, lstCities), ¬ - maximumBy(cityLeastPopulation, lstCities), ¬ - maximumBy(cityNameAZ, lstCities), ¬ - maximumBy(cityNameZA, lstCities)} + script population + on |λ|(x) + population of x + end |λ| + end script + return {¬ + maximumBy(comparing(|length|), lstWords), ¬ + maximumBy(comparing(population), lstCities)} + + --> {"epsilon", {name:"Shanghai", population:24.15}} end run --- COMPARISON FUNCTIONS FOR SPECIFIC DATA TYPES --- Ordering: (LT|EQ|GT) --- GT: 1 (or other positive n) --- EQ: 0 --- LT: -1 (or other negative n) +-- GENERIC FUNCTIONS ---------------------------------------------------------- -on wordAZ(a, b) - if a < b then - 1 - else if a > b then - -1 - else - 0 - end if -end wordAZ - -on wordZA(a, b) - if a < b then - -1 - else if a > b then - 1 - else - 0 - end if -end wordZA - -on wordLong(a, b) - (length of a) - (length of b) -end wordLong - -on wordShort(a, b) - (length of b) - (length of a) -end wordShort - -on cityMostPopulation(a, b) - (population of a) - (population of b) -end cityMostPopulation - -on cityLeastPopulation(a, b) - (population of b) - (population of a) -end cityLeastPopulation - -on cityNameAZ(a, b) - set strA to name of a - set strB to name of b - - if strA < strB then - 1 - else if strA > strB then - -1 - else - 0 - end if -end cityNameAZ - -on cityNameZA(a, b) - set strA to name of a - set strB to name of b - - if strA < strB then - -1 - else if strA > strB then - 1 - else - 0 - end if -end cityNameZA - - --- GENERIC LIBRARY FUNCTIONS +-- comparing :: (a -> b) -> (a -> a -> Ordering) +on comparing(f) + set mf to mReturn(f) + script + on |λ|(a, b) + set x to mf's |λ|(a) + set y to mf's |λ|(b) + if x < y then + -1 + else + if x > y then + 1 + else + 0 + end if + end if + end |λ| + end script +end comparing -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) @@ -119,12 +70,16 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl +-- length :: [a] -> Int +on |length|(xs) + length of xs +end |length| -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -133,7 +88,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list-3.applescript b/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list-3.applescript index 060c15beb9..5d78771f84 100644 --- a/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list-3.applescript +++ b/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list-3.applescript @@ -1,3 +1 @@ -{"alpha", "zeta", "epsilon", "mu", -{name:"Shanghai", population:24.15}, {name:"Tokyo", population:13.3}, -{name:"Beijing", population:21.5}, {name:"Tokyo", population:13.3}} +{"epsilon", {name:"Shanghai", population:24.15}} diff --git a/Task/Greatest-element-of-a-list/BASIC/greatest-element-of-a-list.basic b/Task/Greatest-element-of-a-list/BASIC/greatest-element-of-a-list-1.basic similarity index 100% rename from Task/Greatest-element-of-a-list/BASIC/greatest-element-of-a-list.basic rename to Task/Greatest-element-of-a-list/BASIC/greatest-element-of-a-list-1.basic diff --git a/Task/Greatest-element-of-a-list/BASIC/greatest-element-of-a-list-2.basic b/Task/Greatest-element-of-a-list/BASIC/greatest-element-of-a-list-2.basic new file mode 100644 index 0000000000..49442b7f8e --- /dev/null +++ b/Task/Greatest-element-of-a-list/BASIC/greatest-element-of-a-list-2.basic @@ -0,0 +1,22 @@ +' Greatest element from list +' Populate sample array of numbers +READ elements +DECLARE numbers TYPE NUMBER ARRAY elements +FOR i = 0 TO elements - 1 + READ numbers[i] +NEXT +DATA 6 +DATA 100,-2,300,4,500,6 + +' Demonstrate the function +PRINT greatest(elements, numbers) +END + +' Return greatest element given count and list of numbers +FUNCTION greatest(n, NUMBER a[]) + LOCAL mx = a[0] + FOR i = 1 TO n - 1 + mx = MAX(mx, a[i]) + NEXT + RETURN mx +END FUNCTION diff --git a/Task/Greatest-element-of-a-list/Bc/greatest-element-of-a-list.bc b/Task/Greatest-element-of-a-list/Bc/greatest-element-of-a-list.bc new file mode 100644 index 0000000000..25fcd1e68d --- /dev/null +++ b/Task/Greatest-element-of-a-list/Bc/greatest-element-of-a-list.bc @@ -0,0 +1,9 @@ +define m(a[], n) { + auto m, i + + m = a[0] + for (i = 1; i < n; i++) { + if (a[i] > m) m = a[i] + } + return(m) +} diff --git a/Task/Greatest-element-of-a-list/Dc/greatest-element-of-a-list.dc b/Task/Greatest-element-of-a-list/Dc/greatest-element-of-a-list.dc new file mode 100644 index 0000000000..f807a577e1 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Dc/greatest-element-of-a-list.dc @@ -0,0 +1,12 @@ +[sm llx] sg +[lm p q] sq +[d lm - list_max(Rest, Head). - -list_max([], Res) -> Res; -list_max([Head|Rest], Max) when Head > Max -> - list_max(Rest, Head); -list_max([_Head|Rest], Max) -> list_max(Rest, Max). diff --git a/Task/Greatest-element-of-a-list/Erlang/greatest-element-of-a-list-2.erl b/Task/Greatest-element-of-a-list/Erlang/greatest-element-of-a-list-2.erl deleted file mode 100644 index f284c183ae..0000000000 --- a/Task/Greatest-element-of-a-list/Erlang/greatest-element-of-a-list-2.erl +++ /dev/null @@ -1 +0,0 @@ -list_max([H|T]) -> lists:foldl(fun erlang:max/2, H, T). diff --git a/Task/Greatest-element-of-a-list/Erlang/greatest-element-of-a-list-3.erl b/Task/Greatest-element-of-a-list/Erlang/greatest-element-of-a-list-3.erl deleted file mode 100644 index b7bf5bf86e..0000000000 --- a/Task/Greatest-element-of-a-list/Erlang/greatest-element-of-a-list-3.erl +++ /dev/null @@ -1,2 +0,0 @@ ->list_max([9,4,3,8,5]). -9 diff --git a/Task/Greatest-element-of-a-list/Haskell/greatest-element-of-a-list-3.hs b/Task/Greatest-element-of-a-list/Haskell/greatest-element-of-a-list-3.hs new file mode 100644 index 0000000000..738fdb41db --- /dev/null +++ b/Task/Greatest-element-of-a-list/Haskell/greatest-element-of-a-list-3.hs @@ -0,0 +1,8 @@ +import Data.List (maximumBy) +import Data.Ord (comparing) + +wds :: [String] +wds = ["alpha", "beta", "gamma", "delta", "epsilon", "zeta"] + +main :: IO () +main = print $ maximumBy (comparing length) wds diff --git a/Task/Greatest-element-of-a-list/Haskell/greatest-element-of-a-list-4.hs b/Task/Greatest-element-of-a-list/Haskell/greatest-element-of-a-list-4.hs new file mode 100644 index 0000000000..7a3e1f2b9f --- /dev/null +++ b/Task/Greatest-element-of-a-list/Haskell/greatest-element-of-a-list-4.hs @@ -0,0 +1,9 @@ +maximumBy + :: Foldable t + => (a -> a -> Ordering) -> t a -> a +maximumBy cmp = + let max_ x y = + case cmp x y of + GT -> x + _ -> y + in foldr1 max_ diff --git a/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-5.js b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-5.js new file mode 100644 index 0000000000..1853dc5313 --- /dev/null +++ b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-5.js @@ -0,0 +1,55 @@ +(() => { + 'use strict'; + + // MAXIMUM BY ... -------------------------------------------------------- + + // maximumBy :: (a -> a -> Ordering) -> [a] -> a + const maximumBy = (f, xs) => + xs.reduce((a, x) => a === undefined ? x : ( + f(x, a) > 0 ? x : a + ), undefined); + + // comparing :: (a -> b) -> (a -> a -> Ordering) + const comparing = f => + (x, y) => { + const + a = f(x), + b = f(y); + return a < b ? -1 : a > b ? 1 : 0 + }; + + + // TEST ------------------------------------------------------------------ + const words = ["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta"]; + const cities = [{ + k: 'Bejing', + n: 21.5 + }, { + k: 'Delhi', + n: 16.7 + }, { + k: 'Karachi', + n: 23.5 + }, { + k: 'Lagos', + n: 16.0 + }, { + k: 'Shanghai', + n: 24.3 + }]; + + // length :: [a] -> Int + const length = xs => xs.length; + + // population :: {k: String, n: Float} + const population = dct => dct.n; + + // show :: a -> String + const show = x => JSON.stringify(x, null, 2); + + // OUTPUT ---------------------------------------------------------------- + return show({ + byWordLength: maximumBy(comparing(length), words), + byCityPopulation: maximumBy(comparing(population), cities) + }); +})(); diff --git a/Task/Greatest-element-of-a-list/jq/greatest-element-of-a-list-1.jq b/Task/Greatest-element-of-a-list/Jq/greatest-element-of-a-list-1.jq similarity index 100% rename from Task/Greatest-element-of-a-list/jq/greatest-element-of-a-list-1.jq rename to Task/Greatest-element-of-a-list/Jq/greatest-element-of-a-list-1.jq diff --git a/Task/Greatest-element-of-a-list/jq/greatest-element-of-a-list-2.jq b/Task/Greatest-element-of-a-list/Jq/greatest-element-of-a-list-2.jq similarity index 100% rename from Task/Greatest-element-of-a-list/jq/greatest-element-of-a-list-2.jq rename to Task/Greatest-element-of-a-list/Jq/greatest-element-of-a-list-2.jq 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.kotlin new file mode 100644 index 0000000000..da15038f3d --- /dev/null +++ b/Task/Greatest-element-of-a-list/Kotlin/greatest-element-of-a-list.kotlin @@ -0,0 +1,11 @@ +// version 1.0.5-2 +fun main(args: Array) { + print("Number of values to be input = ") + val n = readLine()!!.toInt() + val array = DoubleArray(n) + for (i in 0 until n) { + print("Value ${i + 1} = ") + array[i] = readLine()!!.toDouble() + } + println("\nThe greatest element is ${array.max()}") +} diff --git a/Task/Greatest-element-of-a-list/Mathematica/greatest-element-of-a-list-4.math b/Task/Greatest-element-of-a-list/Mathematica/greatest-element-of-a-list-4.math deleted file mode 100644 index 4825b3c27f..0000000000 --- a/Task/Greatest-element-of-a-list/Mathematica/greatest-element-of-a-list-4.math +++ /dev/null @@ -1 +0,0 @@ -Max[Max[], Max[-4, -3]] diff --git a/Task/Greatest-element-of-a-list/Nimrod/greatest-element-of-a-list.nimrod b/Task/Greatest-element-of-a-list/Nimrod/greatest-element-of-a-list.nimrod deleted file mode 100644 index 534cbd12fc..0000000000 --- a/Task/Greatest-element-of-a-list/Nimrod/greatest-element-of-a-list.nimrod +++ /dev/null @@ -1 +0,0 @@ -echo max([2,3,4,5,6,1]) diff --git a/Task/Greatest-element-of-a-list/Ol/greatest-element-of-a-list-1.ol b/Task/Greatest-element-of-a-list/Ol/greatest-element-of-a-list-1.ol new file mode 100644 index 0000000000..3ad795d583 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Ol/greatest-element-of-a-list-1.ol @@ -0,0 +1,5 @@ +; builtin function +(max 1 2 3 4 5) + +; using to numbers list +(apply max '(1 2 3 4 5)) diff --git a/Task/Greatest-element-of-a-list/Ol/greatest-element-of-a-list-2.ol b/Task/Greatest-element-of-a-list/Ol/greatest-element-of-a-list-2.ol new file mode 100644 index 0000000000..8f2cb2b3f8 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Ol/greatest-element-of-a-list-2.ol @@ -0,0 +1,17 @@ +; let's input the numbers list +(define x (read)) +; <== (1 2 3 4 5) + +(print x) +; ==> '(1 2 3 4 5) + +(print (apply max x)) +; ==> 5 + +(print (fold max (car x) x)) +; ==> 5 + +(print (fold (lambda (a b) + (if (less? a b) b a)) + (car x) x)) +; ==> 5 diff --git a/Task/Greatest-element-of-a-list/OoRexx/greatest-element-of-a-list-1.rexx b/Task/Greatest-element-of-a-list/OoRexx/greatest-element-of-a-list-1.rexx new file mode 100644 index 0000000000..4a7c7cfed1 --- /dev/null +++ b/Task/Greatest-element-of-a-list/OoRexx/greatest-element-of-a-list-1.rexx @@ -0,0 +1,15 @@ +-- routine that will work with any ordered collection or sets and bags containing numbers. +::routine listMax + use arg list + items list~makearray -- since we're dealing with different collection types, reduce to an array + if items~isEmpty then return .nil -- return a failure indicator. could also raise an error, if desired + largest = items[1] + + + -- note, this method does call max one extra time. This could also use the + -- do i = 2 to items~size to avoid this + do item over items + largest = max(item, largest) + end + + return largest diff --git a/Task/Greatest-element-of-a-list/OoRexx/greatest-element-of-a-list-2.rexx b/Task/Greatest-element-of-a-list/OoRexx/greatest-element-of-a-list-2.rexx new file mode 100644 index 0000000000..bca176921f --- /dev/null +++ b/Task/Greatest-element-of-a-list/OoRexx/greatest-element-of-a-list-2.rexx @@ -0,0 +1,18 @@ +/* REXX *************************************************************** +* 30.07.2013 Walter Pachl as for REXX +**********************************************************************/ +s=.list~of('Walter','lives','in','Vienna') +say listMax(s) +-- routine that will work with any ordered collection or sets and bags. +::routine listMax + use arg list + items=list~makearray -- since we're dealing with different collection types, reduce to an array + if items~isEmpty then return .nil -- return a failure indicator. could also raise an error, if desired + largest = items[1] + -- note, this method uses one extra comparison. It could use + -- do i = 2 to items~size to avoid this + do item over items + If item>>largest Then + largest = item + end + return largest diff --git a/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list-1.pl6 b/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list-1.pl6 deleted file mode 100644 index 2810399a0c..0000000000 --- a/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list-1.pl6 +++ /dev/null @@ -1 +0,0 @@ -say [max] 17, 13, 50, 56, 28, 63, 62, 66, 74, 54; diff --git a/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list-2.pl6 b/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list-2.pl6 deleted file mode 100644 index e31b338a2e..0000000000 --- a/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list-2.pl6 +++ /dev/null @@ -1 +0,0 @@ -say [max] 'my', 'dog', 'has', 'fleas'; diff --git a/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list-3.pl6 b/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list-3.pl6 deleted file mode 100644 index 2e2898ba6e..0000000000 --- a/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list-3.pl6 +++ /dev/null @@ -1,2 +0,0 @@ -sub max2 (*@a) { reduce -> $x, $y { $y after $x ?? $y !! $x }, @a } -say max2 17, 13, 50, 56, 28, 63, 62, 66, 74, 54; diff --git a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-1.rexx b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-1.rexx index cbf33d91fe..8655ed8f5a 100644 --- a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-1.rexx +++ b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-1.rexx @@ -1,11 +1,9 @@ -/*REXX program finds the greatest element in a list (of numbers). */ - /* [↓] list of first twenty reversed primes*/ -y = 2 3 5 7 11 31 71 91 32 92 13 73 14 34 74 35 95 16 76 17 -big=word(y,1) /*choose a initial biggest number*/ - do j=2 to words(y) /*traipse through the list. */ - big=max(big, word(y,j)) /*use the MAX bif to find biggie.*/ - end /*j*/ - -say 'the biggest value in a list of ' words(y) " numbers is: " big - /* [↑] list of first twenty reversed primes*/ - /*stick a fork in it, we're done.*/ +/*REXX program finds the greatest element in a list (of the first 25 reversed primes).*/ +$ = reverse(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) +say 'list of numbers = ' $ /*show the original list of numbers. */ +big=word($, 1) /*choose an initial biggest number. */ +# = words($); do j=2 to # /*traipse through the list, find max. */ + big=max(big, word($, j) ) /*use the MAX BIF to find the biggie.*/ + end /*j*/ +say /*stick a fork in it, we're all done. */ +say 'the biggest value in a list of ' # " numbers is: " big diff --git a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-2.rexx b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-2.rexx index dbc7f6c1f1..1b59c18977 100644 --- a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-2.rexx +++ b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-2.rexx @@ -1,14 +1,11 @@ -/*REXX program finds the greatest element in an array (of numbers). */ -y.= /*set all array elements to null.*/ -y.1 = 2; y.2 = 3; y.3 = 5; y.4 = 7; y.5 = 11 -y.6 = 31; y.7 = 71; y.8 = 91; y.9 = 32; y.10 = 92 -y.11 = 13; y.12 = 73; y.13 = 14; y.14 = 34; y.15 = 74 -y.16 = 35; y.17 = 95; y.18 = 16; y.19 = 76; y.20 = 17 - -big = y.1 /*choose a initial biggest number*/ - do j=2 while y.j\=='' /*traipse through the whole array*/ - big = max(big, y.j) /*use a BIF to find the biggie.*/ - end /*j*/ - -say 'the biggest value in an array of ' j-1 " elements is: " big - /*stick a fork in it, we're done.*/ +/*REXX program finds the greatest element in a list (of the first 25 reversed primes).*/ +@.=; @.1 = 2; @.2 = 3; @.3 = 5; @.4 = 7; @.5 =11; @.6 =31; @.7 =71 + @.8 =91; @.9 =32; @.10=92; @.11=13; @.12=73; @.13=14; @.14=34 + @.15=74; @.16=35; @.17=95; @.18=16; @.19=76; @.20=17; @.21=37 + @.22=97; @.23=38; @.24=98; @.25=79 +big=@.1 /*choose an initial biggest number. */ + do #=2 while @.#\=='' /*traipse through whole array of nums. */ + big = max(big, @.#) /*use a BIF to find the biggest number.*/ + end /*#*/ + /*stick a fork in it, we're all done. */ +say 'the biggest value in an array of ' #-1 " elements is: " big diff --git a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-3.rexx b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-3.rexx index cc6f66c9ec..6830f77701 100644 --- a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-3.rexx +++ b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-3.rexx @@ -1,13 +1,9 @@ -/*REXX program finds the greatest element in an array (of numbers). */ -say 'Please enter a list of numbers (separated by blanks or commas):' -parse pull nums /*get a list from console (user).*/ -nums=translate(nums,,',') /*change commas (,) to blanks.*/ -items=words(nums) /*obtain the number of numbers. */ -big=word(nums,1) /*assume the biggest is the 1st #*/ - - do j=2 to items /*traipse through the list. */ - big = max(big, word(nums,j) ) /*use a BIF for finding the max. */ - end /*j*/ - -say 'the biggest value in the list of ' items " elements is: " big - /*stick a fork in it, we're done.*/ +/*REXX program finds the greatest element in a list of numbers entered at the terminal*/ +say '────────────────── Please enter a list of numbers (separated by blanks or commas):' +parse pull $; #=words($) /*get a list of numbers from terminal. */ +$=translate($, , ',') /*change all commas (,) to blanks. */ +big=word($,1); do j=2 to # /*traipse through the list of numbers. */ + big=max(big, word($,j)) /*use a BIF for finding the max number.*/ + end /*j*/ +say /*stick a fork in it, we're all done. */ +say '────────────────── The biggest value in the list of ' # " elements is: " big diff --git a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-4.rexx b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-4.rexx index a0bfa71650..abba47e801 100644 --- a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-4.rexx +++ b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-4.rexx @@ -1,19 +1,3 @@ -/* REXX *************************************************************** -* If the list contains any character strings, the following will work -* Note the use of >> (instead of >) to avoid numeric comparison -* Note that max() overrides the builtin function MAX -* 30.07.2013 Walter Pachl -**********************************************************************/ -list='Walter Pachl living in Vienna' -Say max(list) -list='8 33 -12' -Say max(list) -Exit -max: Procedure -Parse Arg l -max=word(l,1) -Do i=2 To words(l) - If word(l,i)>>max Then - max=word(l,i) - End -Return max +···; do j=2 to #; _=word($,j) + if _>big then big=_ + end /*j*/ diff --git a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-5.rexx b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-5.rexx new file mode 100644 index 0000000000..a0bfa71650 --- /dev/null +++ b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-5.rexx @@ -0,0 +1,19 @@ +/* REXX *************************************************************** +* If the list contains any character strings, the following will work +* Note the use of >> (instead of >) to avoid numeric comparison +* Note that max() overrides the builtin function MAX +* 30.07.2013 Walter Pachl +**********************************************************************/ +list='Walter Pachl living in Vienna' +Say max(list) +list='8 33 -12' +Say max(list) +Exit +max: Procedure +Parse Arg l +max=word(l,1) +Do i=2 To words(l) + If word(l,i)>>max Then + max=word(l,i) + End +Return max diff --git a/Task/Greatest-element-of-a-list/Racket/greatest-element-of-a-list-5.rkt b/Task/Greatest-element-of-a-list/Racket/greatest-element-of-a-list-5.rkt deleted file mode 100644 index 7b2458b691..0000000000 --- a/Task/Greatest-element-of-a-list/Racket/greatest-element-of-a-list-5.rkt +++ /dev/null @@ -1,10 +0,0 @@ -(define (my-max l) - (define (max-h l greatest) - (cond [(empty? l) greatest] - [(> (first l) greatest) - (max-h (rest l) (first l))] - [else - (max-h (rest l) greatest)])) - (if (empty? l) - empty - (max-h l (first l)))) diff --git a/Task/Greatest-element-of-a-list/Racket/greatest-element-of-a-list-6.rkt b/Task/Greatest-element-of-a-list/Racket/greatest-element-of-a-list-6.rkt deleted file mode 100644 index 13a90b0105..0000000000 --- a/Task/Greatest-element-of-a-list/Racket/greatest-element-of-a-list-6.rkt +++ /dev/null @@ -1 +0,0 @@ - (my-max '(12 9 8 17 1)) diff --git a/Task/Greatest-element-of-a-list/Racket/greatest-element-of-a-list-7.rkt b/Task/Greatest-element-of-a-list/Racket/greatest-element-of-a-list-7.rkt deleted file mode 100644 index d193859153..0000000000 --- a/Task/Greatest-element-of-a-list/Racket/greatest-element-of-a-list-7.rkt +++ /dev/null @@ -1 +0,0 @@ - 17 diff --git a/Task/Greatest-element-of-a-list/Scala/greatest-element-of-a-list-1.scala b/Task/Greatest-element-of-a-list/Scala/greatest-element-of-a-list-1.scala deleted file mode 100644 index d68af188b1..0000000000 --- a/Task/Greatest-element-of-a-list/Scala/greatest-element-of-a-list-1.scala +++ /dev/null @@ -1 +0,0 @@ -List(1,2,3,4) reduceLeft { _ max _ } diff --git a/Task/Greatest-element-of-a-list/Scala/greatest-element-of-a-list-2.scala b/Task/Greatest-element-of-a-list/Scala/greatest-element-of-a-list-2.scala deleted file mode 100644 index 5939b5ac38..0000000000 --- a/Task/Greatest-element-of-a-list/Scala/greatest-element-of-a-list-2.scala +++ /dev/null @@ -1 +0,0 @@ -List(1,2,3,4).max diff --git a/Task/Greatest-element-of-a-list/Zkl/greatest-element-of-a-list-1.zkl b/Task/Greatest-element-of-a-list/Zkl/greatest-element-of-a-list-1.zkl new file mode 100644 index 0000000000..dcd42da0ac --- /dev/null +++ b/Task/Greatest-element-of-a-list/Zkl/greatest-element-of-a-list-1.zkl @@ -0,0 +1,2 @@ +(1).max(1,2,3) //-->3 +(66).max(1,2,3.14) //-->66 diff --git a/Task/Greatest-element-of-a-list/Zkl/greatest-element-of-a-list-2.zkl b/Task/Greatest-element-of-a-list/Zkl/greatest-element-of-a-list-2.zkl new file mode 100644 index 0000000000..cfd4e95755 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Zkl/greatest-element-of-a-list-2.zkl @@ -0,0 +1,3 @@ +(66).max(T(1,2,3)) //-->3 +(66).max(T(1,2,3.14)) //-->3 +(6.6).max(T(1,2,3.14)) //-->3.14 diff --git a/Task/Greatest-element-of-a-list/Zkl/greatest-element-of-a-list-3.zkl b/Task/Greatest-element-of-a-list/Zkl/greatest-element-of-a-list-3.zkl new file mode 100644 index 0000000000..bc64166cd6 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Zkl/greatest-element-of-a-list-3.zkl @@ -0,0 +1 @@ +fcn max{ vm.arglist.reduce(fcn(p,n){ if(p < n) n else p }) } diff --git a/Task/Greatest-subsequential-sum/JavaScript/greatest-subsequential-sum.js b/Task/Greatest-subsequential-sum/JavaScript/greatest-subsequential-sum.js index 2db3d8bbf5..a11274ef9a 100644 --- a/Task/Greatest-subsequential-sum/JavaScript/greatest-subsequential-sum.js +++ b/Task/Greatest-subsequential-sum/JavaScript/greatest-subsequential-sum.js @@ -1,25 +1,25 @@ -function MaximumSubsequence( population ) { - var maxValue = 0; - var subsequence = []; - - for( var i=0, len=population.length; i < len; i++ ) { - for( var j=i; j <= len; j++ ) { - var subsequence = population.slice(i,j); - var value = sumValues(subsequence); - if( value > maxValue ) { - maxValue = value; - greatest = subsequence; - }; - } - } - - return greatest; +function MaximumSubsequence(population) { + var maxValue = 0; + var subsequence = []; + + for (var i = 0, len = population.length; i < len; i++) { + for (var j = i; j <= len; j++) { + var subsequence = population.slice(i, j); + var value = sumValues(subsequence); + if (value > maxValue) { + maxValue = value; + greatest = subsequence; + }; + } + } + + return greatest; } function sumValues(arr) { - var result = 0; - for( var i=0, len=arr.length; i < len; i++) { - result += arr[i]; - } - return result; + var result = 0; + for (var i = 0, len = arr.length; i < len; i++) { + result += arr[i]; + } + return result; } diff --git a/Task/Greatest-subsequential-sum/jq/greatest-subsequential-sum-1.jq b/Task/Greatest-subsequential-sum/Jq/greatest-subsequential-sum-1.jq similarity index 100% rename from Task/Greatest-subsequential-sum/jq/greatest-subsequential-sum-1.jq rename to Task/Greatest-subsequential-sum/Jq/greatest-subsequential-sum-1.jq diff --git a/Task/Greatest-subsequential-sum/jq/greatest-subsequential-sum-2.jq b/Task/Greatest-subsequential-sum/Jq/greatest-subsequential-sum-2.jq similarity index 100% rename from Task/Greatest-subsequential-sum/jq/greatest-subsequential-sum-2.jq rename to Task/Greatest-subsequential-sum/Jq/greatest-subsequential-sum-2.jq diff --git a/Task/Greatest-subsequential-sum/jq/greatest-subsequential-sum-3.jq b/Task/Greatest-subsequential-sum/Jq/greatest-subsequential-sum-3.jq similarity index 100% rename from Task/Greatest-subsequential-sum/jq/greatest-subsequential-sum-3.jq rename to Task/Greatest-subsequential-sum/Jq/greatest-subsequential-sum-3.jq diff --git a/Task/Greatest-subsequential-sum/Kotlin/greatest-subsequential-sum.kotlin b/Task/Greatest-subsequential-sum/Kotlin/greatest-subsequential-sum.kotlin new file mode 100644 index 0000000000..58ca5c1c9b --- /dev/null +++ b/Task/Greatest-subsequential-sum/Kotlin/greatest-subsequential-sum.kotlin @@ -0,0 +1,34 @@ +// version 1.1 + +fun gss(seq: IntArray): Triple { + if (seq.isEmpty()) throw IllegalArgumentException("Array cannot be empty") + var sum: Int + var maxSum = seq[0] + var first = 0 + var last = 0 + for (i in 1 until seq.size) { + sum = 0 + for (j in i until seq.size) { + sum += seq[j] + if (sum > maxSum) { + maxSum = sum + first = i + last = j + } + } + } + return Triple(maxSum, first, last) +} + +fun main(args: Array) { + val seq = intArrayOf(-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1) + val(maxSum, first, last) = gss(seq) + if (maxSum > 0) { + println("Maximum subsequence is from indices $first to $last") + print("Elements are : ") + for (i in first .. last) print("${seq[i]} ") + println("\nSum is $maxSum") + } + else + println("Maximum subsequence is the empty sequence which has a sum of 0") +} diff --git a/Task/Greatest-subsequential-sum/Perl-6/greatest-subsequential-sum-1.pl6 b/Task/Greatest-subsequential-sum/Perl-6/greatest-subsequential-sum-1.pl6 index 436c02c579..780ffe514f 100644 --- a/Task/Greatest-subsequential-sum/Perl-6/greatest-subsequential-sum-1.pl6 +++ b/Task/Greatest-subsequential-sum/Perl-6/greatest-subsequential-sum-1.pl6 @@ -1,4 +1,4 @@ -sub maxsubseq (*@a) { +sub max-subseq (*@a) { my ($start, $end, $sum, $maxsum) = -1, -1, 0, 0; for @a.kv -> $i, $x { $sum += $x; diff --git a/Task/Greatest-subsequential-sum/Perl-6/greatest-subsequential-sum-2.pl6 b/Task/Greatest-subsequential-sum/Perl-6/greatest-subsequential-sum-2.pl6 index f2cf65574d..7c51c87490 100644 --- a/Task/Greatest-subsequential-sum/Perl-6/greatest-subsequential-sum-2.pl6 +++ b/Task/Greatest-subsequential-sum/Perl-6/greatest-subsequential-sum-2.pl6 @@ -1,16 +1,16 @@ -sub max_sub-seq ( *@a ) { +sub max-subseq ( *@a ) { - my $max_subset = []; + my $max-subset = (); while @a { - my @subsets = @a.keys.map: { [ @a[0..$_] ] }; - @subsets.push($max_subset); - $max_subset = @subsets.max: { [+] .list }; + my @subsets = [\,] @a; + @subsets.push: $max-subset; + $max-subset = @subsets.max: { [+] .list }; @a.shift; } - return $max_subset; + return $max-subset; } -max_sub-seq( -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 ).perl.say; -max_sub-seq( -2, -2, -1, 3, 5, 6, -1, 4, -4, 2, -1 ).perl.say; -max_sub-seq( -2, -2, -1, -3, -5, -6, -1, -4, -4, -2, -1 ).perl.say; +max-subseq( -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 ).say; +max-subseq( -2, -2, -1, 3, 5, 6, -1, 4, -4, 2, -1 ).say; +max-subseq( -2, -2, -1, -3, -5, -6, -1, -4, -4, -2, -1 ).say; diff --git a/Task/Greatest-subsequential-sum/Zkl/greatest-subsequential-sum-1.zkl b/Task/Greatest-subsequential-sum/Zkl/greatest-subsequential-sum-1.zkl new file mode 100644 index 0000000000..f4f681ec68 --- /dev/null +++ b/Task/Greatest-subsequential-sum/Zkl/greatest-subsequential-sum-1.zkl @@ -0,0 +1,9 @@ +fcn maxsubseq(s){ + s.reduce(fcn([(sum, seq, maxsum, maxseq)], x){ + sum=sum+x; seq=T(x).extend(seq); + if(sum < 0) return(0,T,maxsum,maxseq); + if (sum>maxsum) return(sum, seq, sum, seq); + return(sum, seq, maxsum, maxseq); + }, + T(0,T,0,T))[3].reverse(); // -->maxseq.reverse() +} diff --git a/Task/Greatest-subsequential-sum/Zkl/greatest-subsequential-sum-2.zkl b/Task/Greatest-subsequential-sum/Zkl/greatest-subsequential-sum-2.zkl new file mode 100644 index 0000000000..e904ad9223 --- /dev/null +++ b/Task/Greatest-subsequential-sum/Zkl/greatest-subsequential-sum-2.zkl @@ -0,0 +1,6 @@ +s:=maxsubseq(T(-1,-2,3,5,6,-2,-1,4,-4,2,-1)); +println(s.sum()," : ",s); + +s:=maxsubseq(T(-1,-2)); println(s.sum()," : ",s); + +s:=maxsubseq(T); println(s.sum()," : ",s); diff --git a/Task/Greyscale-bars-Display/FreeBASIC/greyscale-bars-display.freebasic b/Task/Greyscale-bars-Display/FreeBASIC/greyscale-bars-display.freebasic new file mode 100644 index 0000000000..bb677f5ed0 --- /dev/null +++ b/Task/Greyscale-bars-Display/FreeBASIC/greyscale-bars-display.freebasic @@ -0,0 +1,35 @@ +' version 01-09-2017 +' compile with: fbc -s console +' or compile with: fbc -s gui +' hit any key to stop + +Dim As UInteger d, blocks, blocksize, ps, col, h, w, x, y1, y2 + +ScreenInfo w, h +' create display size window, 8bit color (palette), no frame +ScreenRes w, h, 8,, 8 + +For x = 0 To 255 ' create grayscale palette for + Palette x, x, x, x ' the window we just opened +Next + +h = h \ 4 : y2 = h -1 + +If w Mod 64 <> 0 Then w -= (w Mod 64) +blocks = 8 : blocksize = w \ 8 + +For ps = 1 To 4 + For x = 0 To blocks -1 + col = 255 * x \ (blocks -1) ' from black to white + If (ps And 1) = 0 Then col = 255 - col ' from white to black + Line (x * blocksize, y1) - (((x +1) * blocksize) -1, y2), col, bf + Next + y1 += h : y2 += h + blocks *= 2 : blocksize \= 2 +Next + +' empty keyboard buffer +While Inkey <> "" : Wend + +Sleep +End diff --git a/Task/Greyscale-bars-Display/Gambas/greyscale-bars-display.gambas b/Task/Greyscale-bars-Display/Gambas/greyscale-bars-display.gambas new file mode 100644 index 0000000000..f10ce02cd1 --- /dev/null +++ b/Task/Greyscale-bars-Display/Gambas/greyscale-bars-display.gambas @@ -0,0 +1,29 @@ +Public Sub Form_Open() +Dim iRow, iCol, iClr As Integer 'For Row, Column and Colour +Dim iInc As Integer = 4 'To calculate RGB colour +Dim h1Panel As Panel 'Panels to display colours + +With Me 'Setup the Form + .Arrangement = Arrange.Row 'Arrange children in rows + .Border = False 'No Border + .Height = Desktop.Height 'Fill the screen + .Width = Desktop.Width 'Fill the screen + .Fullscreen = True 'Set the Form to Fullscreen +End With + +For iRow = 1 To 4 'For each row.. + iInc += iInc 'Increase iInc by itself + For iCol = 0 To iInc - 1 'For each column.. + iClr = iCol * (256 / iInc) 'Set the RGB colour + If iRow = 2 Or iRow = 4 Then iClr = 255 - (iCol * (256 / iInc)) 'If row 2 or 4 then reverse the colours + h1Panel = New Panel(Me) 'Create a new Panel + With h1Panel 'With the Panel.. + .Width = Desktop.Width / iInc 'Set the width + .Height = Desktop.Height / 4 'Set the height + .Background = Color.RGB(iClr, iClr, iClr) 'Set the Background colour + .Border = Border.Plain 'Set a Border (It's easier to see the colour changes) + End With + Next +Next + +End diff --git a/Task/Greyscale-bars-Display/Java/greyscale-bars-display.java b/Task/Greyscale-bars-Display/Java/greyscale-bars-display.java index 3509cb5535..9650bba8bc 100644 --- a/Task/Greyscale-bars-Display/Java/greyscale-bars-display.java +++ b/Task/Greyscale-bars-Display/Java/greyscale-bars-display.java @@ -16,21 +16,22 @@ public class Greybars extends JFrame { public void paint ( Graphics g ) { int run = 0 ; - int colorcomp = 0 ; //component of the color + double colorcomp = 0.0 ; //component of the color for ( int columncount = 8 ; columncount < 128 ; columncount *= 2 ) { - int colorgap = 255 / columncount ; //by this gap we change the background color + double colorgap = 255.0 / (columncount - 1) ; //by this gap we change the background color int columnwidth = width / columncount ; int columnheight = height / 4 ; if ( run % 2 == 0 ) //switches color directions with every for loop - colorcomp = 0 ; + colorcomp = 0.0 ; else { - colorcomp = 255 ; - colorgap *= -1 ; + colorcomp = 255.0 ; + colorgap *= -1.0 ; } int ystart = 0 + columnheight * run ; int xstart = 0 ; for ( int i = 0 ; i < columncount ; i++ ) { - Color nextColor = new Color( colorcomp, colorcomp, colorcomp ) ; + int icolor = (int)Math.round(colorcomp) ; //round to nearer integer + Color nextColor = new Color( icolor , icolor, icolor ) ; g.setColor( nextColor ) ; g.fillRect( xstart , ystart , columnwidth , columnheight ) ; xstart += columnwidth ; diff --git a/Task/Greyscale-bars-Display/Kotlin/greyscale-bars-display.kotlin b/Task/Greyscale-bars-Display/Kotlin/greyscale-bars-display.kotlin new file mode 100644 index 0000000000..b914405ca4 --- /dev/null +++ b/Task/Greyscale-bars-Display/Kotlin/greyscale-bars-display.kotlin @@ -0,0 +1,51 @@ +// version 1.1 + +import java.awt.Color +import java.awt.Graphics +import javax.swing.JFrame + +class GreyBars : JFrame("grey bars example!") { + private val w: Int + private val h: Int + + init { + w = 640 + h = 320 + setSize(w, h) + defaultCloseOperation = JFrame.EXIT_ON_CLOSE + isVisible = true + } + + override fun paint(g: Graphics) { + var run = 0 + var colorComp: Double // component of the color + var columnCount = 8 + while (columnCount < 128) { + var colorGap = 255.0 / (columnCount - 1) // by this gap we change the background color + val columnWidth = w / columnCount + val columnHeight = h / 4 + if (run % 2 == 0) // switches color directions with each iteration of while loop + colorComp = 0.0 + else { + colorComp = 255.0 + colorGap *= -1.0 + } + val ystart = columnHeight * run + var xstart = 0 + for (i in 0 until columnCount) { + val iColor = Math.round(colorComp).toInt() + val nextColor = Color(iColor, iColor, iColor) + g.color = nextColor + g.fillRect(xstart, ystart, columnWidth, columnHeight) + xstart += columnWidth + colorComp += colorGap + } + run++ + columnCount *= 2 + } + } +} + +fun main(args: Array) { + GreyBars() +} diff --git a/Task/Greyscale-bars-Display/Phix/greyscale-bars-display.phix b/Task/Greyscale-bars-Display/Phix/greyscale-bars-display.phix new file mode 100644 index 0000000000..2e37551324 --- /dev/null +++ b/Task/Greyscale-bars-Display/Phix/greyscale-bars-display.phix @@ -0,0 +1,70 @@ +-- +-- demo\rosetta\Greyscale_bars.exw +-- +include pGUI.e + +Ihandle dlg, canvas +cdCanvas cddbuffer, cdcanvas + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) + cdCanvasActivate(cddbuffer) + integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") + integer h = ceil(height/4) + for row=1 to 4 do + integer x = 0, p2 = power(2,row+2), c = floor(255/(p2-1)) + for n=0 to p2-1 do + integer colour = c*n*#010101 + if and_bits(row,1)=0 then colour = xor_bits(colour,#FFFFFF) end if + cdCanvasSetForeground(cddbuffer, colour) + integer nx = ceil(width*(n+1)/p2) + cdCanvasBox(cddbuffer, x, nx, height-h, height) + x = nx + end for + height -= h + end for + cdCanvasFlush(cddbuffer) + return IUP_DEFAULT +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + return IUP_DEFAULT +end function + +function unmap_cb(Ihandle /*ih*/) + cdKillCanvas(cddbuffer) + cdKillCanvas(cdcanvas) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "600x400") + + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + IupSetCallback(canvas, "UNMAP_CB", Icallback("unmap_cb")) + + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", "Greyscale bars") + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + + IupMap(dlg) + IupSetAttribute(canvas, "RASTERSIZE", NULL) + + IupShowXY(dlg,IUP_CENTER,IUP_CENTER) + + IupMainLoop() + + IupClose() +end procedure + +main() diff --git a/Task/Greyscale-bars-Display/Zkl/greyscale-bars-display.zkl b/Task/Greyscale-bars-Display/Zkl/greyscale-bars-display.zkl new file mode 100644 index 0000000000..d374dbec37 --- /dev/null +++ b/Task/Greyscale-bars-Display/Zkl/greyscale-bars-display.zkl @@ -0,0 +1,13 @@ +img:=PPM(640,480); +foreach q in ([0..3]){ //quarter of screen + n:=(8).shiftLeft(q); //number of bars + w:=640/n; //width of bar (pixels) + foreach b in ([0..n-1]){ //for each bar... + c:=(255.0/(n-1).toFloat() * (if(q.isOdd) n-1-b else b)).toInt(); + c:=c.shiftLeft(16) + c.shiftLeft(8) + c; //RGB color = gray + foreach y in ([(3-q)*120 .. (3-q+1)*120-1]){ // flip image vertically + img.line(w*b,y, w*(b+1)-1,y, c); + } + } +} +img.write(File("foo.ppm","wb")); diff --git a/Task/Guess-the-number-With-feedback--player-/00DESCRIPTION b/Task/Guess-the-number-With-feedback--player-/00DESCRIPTION index 52757aca4c..ef99f7f245 100644 --- a/Task/Guess-the-number-With-feedback--player-/00DESCRIPTION +++ b/Task/Guess-the-number-With-feedback--player-/00DESCRIPTION @@ -1,8 +1,11 @@ -The task is to write a player for the game that follows the following rules: +:Task: +Write a player for the game that follows the following rules: :The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number. The computer should guess intelligently based on the accumulated scores given. One way is to use a [[Binary search]] based algorithm. -;Cf. -* [[Guess the number/With Feedback]] -* [[Bulls and cows/Player]] + +;Related tasks: +*   [[Guess the number/With Feedback]] +* *nbsp; [[Bulls and cows/Player]] +

    diff --git a/Task/Guess-the-number-With-feedback--player-/ALGOL-68/guess-the-number-with-feedback--player-.alg b/Task/Guess-the-number-With-feedback--player-/ALGOL-68/guess-the-number-with-feedback--player-.alg new file mode 100644 index 0000000000..6eda60dd10 --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/ALGOL-68/guess-the-number-with-feedback--player-.alg @@ -0,0 +1,26 @@ +BEGIN + INT lower := 1; + INT upper := 100; + print( ( "Think of a number between ", whole( lower, 0 ), " and ", whole( upper, 0 ), newline ) ); + print( ( "Please enter Y if I guess correctly, L is it is lower, G if it is greater or Q if you've had enough", newline ) ); + WHILE + INT mid = lower + ( ( upper - lower ) OVER 2 ); + CHAR reply; + WHILE + print( ( "Is it ", whole( mid, 0 ), "? Y/L/G/Q: " ) ); + read( ( reply, newline ) ); + NOT char in string( reply, NIL, "YLGQylgq" ) + DO SKIP OD; + IF reply = "Q" OR reply = "q" OR reply = "Y" OR reply = "y" + THEN FALSE + ELIF lower >= upper THEN + print( ( "Based on your answers so far, it must be ", whole( lower, 0 ), newline ) ); + FALSE + ELSE + IF reply = "L" OR reply = "l" THEN upper := mid - 1 + ELIF reply = "G" OR reply = "g" THEN lower := mid + 1 + FI; + TRUE + FI + DO SKIP OD +END diff --git a/Task/Guess-the-number-With-feedback--player-/Batch-File/guess-the-number-with-feedback--player-.bat b/Task/Guess-the-number-With-feedback--player-/Batch-File/guess-the-number-with-feedback--player-.bat new file mode 100644 index 0000000000..ec044fda49 --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/Batch-File/guess-the-number-with-feedback--player-.bat @@ -0,0 +1,30 @@ +@echo off + +:: Player is prompted to give a number between %min% and %max%. If the input is out of those limits they are prompted to choose again +:choose +set min=0 +set max=100 + +set /p "number=Choose a number [%min%-%max%]: " +if %number% gtr %max% goto choose +if %number% lss %min% goto choose +set attempts=0 + +:: Loops the guessing process until completed +:comp +set /a attempts+=1 +set /a guess=(%max%-%min%)/2+%min% +choice /c "HLE" /n /m "Guess: %guess% - [H]igher, [L]ower or [E]qual" +if errorlevel 3 goto end +if errorlevel 2 ( + set max=%guess% + goto comp +) +if errorlevel 1 ( + set min=%guess% + goto comp +) + +:end +echo Guesses: %attempts% +pause>nul diff --git a/Task/Guess-the-number-With-feedback--player-/Kotlin/guess-the-number-with-feedback--player-.kotlin b/Task/Guess-the-number-With-feedback--player-/Kotlin/guess-the-number-with-feedback--player-.kotlin new file mode 100644 index 0000000000..8ac60e28f8 --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/Kotlin/guess-the-number-with-feedback--player-.kotlin @@ -0,0 +1,35 @@ +// version 1.0.5-2 + +fun main(args: Array) { + var hle: Char + var lowest = 1 + var highest = 20 + var guess = 10 + println("Please choose a number between 1 and 20 but don't tell me what it is yet\n") + + while (true) { + println("My guess is $guess") + + do { + print("Is this higher/lower than or equal to your chosen number h/l/e : ") + hle = readLine()!!.first().toLowerCase() + if (hle == 'l' && guess == highest) { + println("It can't be more than $highest, try again") + hle = 'i' // signifies invalid + } + else if (hle == 'h' && guess == lowest) { + println("It can't be less than $lowest, try again") + hle = 'i' + } + } + while (hle !in "hle") + + when (hle) { + 'e' -> { println("Good, thanks for playing the game with me!") ; return } + 'h' -> if (highest > guess - 1) highest = guess - 1 + 'l' -> if (lowest < guess + 1) lowest = guess + 1 + } + + guess = (lowest + highest) / 2 + } +} diff --git a/Task/Guess-the-number-With-feedback--player-/Sidef/guess-the-number-with-feedback--player-.sidef b/Task/Guess-the-number-With-feedback--player-/Sidef/guess-the-number-with-feedback--player-.sidef index 825f62d379..6cfe46c5e5 100644 --- a/Task/Guess-the-number-With-feedback--player-/Sidef/guess-the-number-with-feedback--player-.sidef +++ b/Task/Guess-the-number-With-feedback--player-/Sidef/guess-the-number-with-feedback--player-.sidef @@ -1,14 +1,14 @@ -var min = 1; -var max = 99; -var tries = 0; -var guess = max.rand(min).int; +var min = 1 +var max = 99 +var tries = 0 +var guess = pick(min..max)   -print <<"EOT".chomp; +print <<"EOT".chomp \n=>> Think of a number between #{min} and #{max} and I'll guess it!\n Press when are you ready... EOT   -STDIN.readline; +STDIN.readline   loop { print <<-EOT.chomp @@ -16,27 +16,27 @@ loop { >#{' '} EOT   - ++tries; + ++tries given (STDIN.readline) { case (max <= min) { - say "\nI give up..."; - break; + say "\nI give up..." + break } when (/^h/i) { - min = guess+1; + min = guess+1 } when (/^l/i) { - max = guess; + max = guess } when (/^e/i) { - say "\nI knew it! It took me only #{tries} tries."; - break; + say "\nI knew it! It took me only #{tries} tries." + break } default { - say "error: invalid score"; - next; + say "error: invalid score" + next } }   - guess = (min+max / 2 -> int); + guess = ((min+max) // 2) } diff --git a/Task/Guess-the-number-With-feedback--player-/Zkl/guess-the-number-with-feedback--player-.zkl b/Task/Guess-the-number-With-feedback--player-/Zkl/guess-the-number-with-feedback--player-.zkl new file mode 100644 index 0000000000..12ac0553dc --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/Zkl/guess-the-number-with-feedback--player-.zkl @@ -0,0 +1,10 @@ +println("Pick a number between 0 and 100 and remember it."); +low,high,g := 0,100, 20; +while(True){ + r:=ask("I guess %d; is that high, low or =? ".fmt(g)).strip().toLower(); + if(r=="="){ println("Yea!"); break; } + if(r[0]=="h") high=g-1 else low=g+1; + if(low==high){ println("Yea! the number is ",low); break; } + if(low>high){ println("I'm confused!"); break; } + g=(low + high)/2; +} diff --git a/Task/Guess-the-number-With-feedback/Julia/guess-the-number-with-feedback.julia b/Task/Guess-the-number-With-feedback/Julia/guess-the-number-with-feedback.julia index f7a3e1882f..72c8743104 100644 --- a/Task/Guess-the-number-With-feedback/Julia/guess-the-number-with-feedback.julia +++ b/Task/Guess-the-number-With-feedback/Julia/guess-the-number-with-feedback.julia @@ -1,7 +1,7 @@ function guess_feedback(n) number = rand(1:n) print("I choose a number between 1 and $n\nYour guess? ") - while((guess = chomp(readline(STDIN))) != string(number)) + while((guess = readline(STDIN)) != string(number)) isdigit(guess) ? print("Too $(parse(Int,guess) < number ? "small" : "big")") : print("Enter an integer please") diff --git a/Task/Guess-the-number-With-feedback/Kotlin/guess-the-number-with-feedback.kotlin b/Task/Guess-the-number-With-feedback/Kotlin/guess-the-number-with-feedback.kotlin new file mode 100644 index 0000000000..f2bd6736dd --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Kotlin/guess-the-number-with-feedback.kotlin @@ -0,0 +1,18 @@ +// version 1.1.2 + +fun main(args: Array) { + val rand = java.util.Random() + val n = 1 + rand.nextInt(20) + var guess :Int + println("Guess which number I've chosen in the range 1 to 20\n") + while (true) { + print(" Your guess : ") + guess = readLine()!!.toInt() + when (guess) { + n -> { println("Correct, well guessed!") ; return } + in n + 1 .. 20 -> println("Your guess is higher than the chosen number, try again") + in 1 .. n - 1 -> println("Your guess is lower than the chosen number, try again") + else -> println("Your guess is inappropriate, try again") + } + } +} diff --git a/Task/Guess-the-number-With-feedback/Ol/guess-the-number-with-feedback.ol b/Task/Guess-the-number-With-feedback/Ol/guess-the-number-with-feedback.ol new file mode 100644 index 0000000000..16d9038616 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Ol/guess-the-number-with-feedback.ol @@ -0,0 +1,26 @@ +(import (otus random!)) + +(define from 0) +(define to 100) + +(define number (+ from (rand! (+ from to 1)))) + +(let loop () + (for-each display `("Pick a number from " ,from " through " ,to ": ")) + (let ((guess (read))) + (cond + ((not (number? guess)) + (print "Not a number!") + (loop)) + ((or (< guess from) + (< to guess)) + (print "Out of range!") + (loop)) + ((< guess number) + (print "Too low!") + (loop)) + ((> guess number) + (print "Too high!") + (loop)) + ((= guess number) + (print "Well guessed!"))))) diff --git a/Task/Guess-the-number-With-feedback/OoRexx/guess-the-number-with-feedback.rexx b/Task/Guess-the-number-With-feedback/OoRexx/guess-the-number-with-feedback.rexx new file mode 100644 index 0000000000..ecc348d3e4 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/OoRexx/guess-the-number-with-feedback.rexx @@ -0,0 +1,56 @@ +/*REXX program that plays the guessing (the number) game. */ + low=1 /*lower range for the guessing game.*/ +high=100 /*upper range for the guessing game.*/ +try=0 /*number of valid attempts. */ +r=random(1,100) /*get a random number (low-->high). */ + +do forever + say + say "guess the number, it's between" low 'and' high '(inclusive)', + 'or enter quit to end the game.' + say + pull g + say + g=space(g) + Select + When g='' then iterate + When g='QUIT' then exit + When g='?' then Do + Say 'The number you are looking for is' r + Iterate + End + When \datatype(g,'W') then do + call ser g "isn't a valid number" + iterate + end + When ghigh then do + call ser g 'is above the higher limit of' high + iterate + end + When g=r then do + try=try+1 + Leave + End + Otherwise Do + try=try+1 + if g>r then what='high' + else what='low' + say 'your guess of' g 'is too' what'.' + end + end + end + +say +tries='tries' +if try=1 then + say 'Congratulations!, you guessed the number in 1 try. Did you cheat?' +Else + say 'Congratulations!, you guessed the number in' try 'tries.' +say +exit + +ser: say; say '*** error ! ***'; say arg(1); say; return diff --git a/Task/Guess-the-number-With-feedback/REXX/guess-the-number-with-feedback.rexx b/Task/Guess-the-number-With-feedback/REXX/guess-the-number-with-feedback.rexx index 8648c39ed1..7fd5a8d187 100644 --- a/Task/Guess-the-number-With-feedback/REXX/guess-the-number-with-feedback.rexx +++ b/Task/Guess-the-number-With-feedback/REXX/guess-the-number-with-feedback.rexx @@ -1,36 +1,36 @@ /*REXX program plays guess the number game with a human; the computer picks the number*/ - low= 1 /*the lower range for the guessing game*/ -high=100 /* " upper " " " " " */ - try= 0 /*the number of valid (guess) attempts.*/ - r=random(1, 100) /*get a random number (low ───◄ high).*/ + low= 1 /*the lower range for the guessing game*/ + high=100 /* " upper " " " " " */ + try= 0 /*the number of valid (guess) attempts.*/ + r=random(1, 100) /*get a random number (low ───► high).*/ lows= 'too_low too_small too_little below under underneath too_puny' highs= 'too_high too_big too_much above over over_the_top too_huge' erm= '***error***' @gtn= "guess the number, it's between" prompt=centre(@gtn low 'and' high '(inclusive) ───or─── Quit:', 79, "─") - /* [↓] by 0 --- used to LEAVE aloop.*/ + /* [↓] BY 0 ─── used to LEAVE a loop*/ do ask=0 by 0; say; say prompt; say; pull g; g=space(g); say do validate=0 by 0 select - when g=='' then iterate ask - when abbrev('QUIT',g,1) then exit /*what a whoos.*/ - when words(g)\==1 then say erm 'too many numbers entered:' g - when \datatype(g,'N') then say erm g "isn't numeric" - when \datatype(g,'W') then say erm g "isn't a whole number" - when ghigh then say erm g 'is above the higher limit of' high + when g=='' then iterate ask + when abbrev('QUIT', g, 1) then exit /*what a whoos.*/ + when words(g)\==1 then say erm 'too many numbers entered:' g + when \datatype(g, 'N') then say erm g "isn't numeric" + when \datatype(g, 'W') then say erm g "isn't a whole number" + when ghigh then say erm g 'is above the higher limit of' high otherwise leave /*validate*/ - end /*select*/ + end /*select*/ iterate ask - end /*validate*/ + end /*validate*/ try=try+1 if g=r then leave - if g>r then what=word(highs, random(1, words(highs))) - else what=word( lows, random(1, words( lows))) + if g>r then what=word(highs, random(1, words(highs) ) ) + else what=word( lows, random(1, words( lows) ) ) say 'your guess of' g "is" translate(what'.', , "_") - end /*ask*/ + end /*ask*/ -if try==1 then say 'Gadzooks!!! You guessed the number right away!' +if try==1 then say 'Gadzooks!!! You guessed the number right away!' else say 'Congratulations!, you guessed the number in ' try " tries." /*stick a fork in it, we're all done. */ diff --git a/Task/Guess-the-number-With-feedback/Zkl/guess-the-number-with-feedback.zkl b/Task/Guess-the-number-With-feedback/Zkl/guess-the-number-with-feedback.zkl new file mode 100644 index 0000000000..d0487b99d1 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Zkl/guess-the-number-with-feedback.zkl @@ -0,0 +1,7 @@ +r:=(0).random(10)+1; +while(1){ + n:=ask("Num between 1 & 10: "); + try{n=n.toInt()}catch{ println("Number please"); continue; } + if(n==r){ println("Well guessed!"); break; } + println((n
    diff --git a/Task/Guess-the-number/AppleScript/guess-the-number-1.applescript b/Task/Guess-the-number/AppleScript/guess-the-number-1.applescript index c4e42d36f4..df1047c1ba 100644 --- a/Task/Guess-the-number/AppleScript/guess-the-number-1.applescript +++ b/Task/Guess-the-number/AppleScript/guess-the-number-1.applescript @@ -1,25 +1,25 @@ on run - -- define the number to be guessed - set numberToGuess to (random number from 1 to 10) - -- prepare a variable to store the user's answer - set guessedNumber to missing value - -- start a loop (will be exited by using "exit repeat" after a correct guess) - repeat - try - -- ask the user for his/her guess - set usersChoice to (text returned of (display dialog "Guess the number between 1 and 10 inclusive" default answer "" buttons {"Check"} default button "Check")) - -- try to convert the given answer to an integer - set guessedNumber to usersChoice as integer - on error - -- something gone wrong, overwrite user's answer with a non-matching value - set guessedNumber to missing value - end try - -- decide if the user's answer was the right one - if guessedNumber is equal to numberToGuess then - -- the user guessed the correct number and gets informed - display dialog "Well guessed! The number was " & numberToGuess buttons {"OK"} default button "OK" - -- exit the loop (quits this application) - exit repeat - end if - end repeat + -- define the number to be guessed + set numberToGuess to (random number from 1 to 10) + -- prepare a variable to store the user's answer + set guessedNumber to missing value + -- start a loop (will be exited by using "exit repeat" after a correct guess) + repeat + try + -- ask the user for his/her guess + set usersChoice to (text returned of (display dialog "Guess the number between 1 and 10 inclusive" default answer "" buttons {"Check"} default button "Check")) + -- try to convert the given answer to an integer + set guessedNumber to usersChoice as integer + on error + -- something gone wrong, overwrite user's answer with a non-matching value + set guessedNumber to missing value + end try + -- decide if the user's answer was the right one + if guessedNumber is equal to numberToGuess then + -- the user guessed the correct number and gets informed + display dialog "Well guessed! The number was " & numberToGuess buttons {"OK"} default button "OK" + -- exit the loop (quits this application) + exit repeat + end if + end repeat end run diff --git a/Task/Guess-the-number/AppleScript/guess-the-number-2.applescript b/Task/Guess-the-number/AppleScript/guess-the-number-2.applescript index ebe8f21cce..390948dfa7 100644 --- a/Task/Guess-the-number/AppleScript/guess-the-number-2.applescript +++ b/Task/Guess-the-number/AppleScript/guess-the-number-2.applescript @@ -1,9 +1,11 @@ +-- GUESS THE NUMBER ---------------------------------------------------------- + on run -- isMatch :: Int -> Bool script isMatch - on lambda(x) + on |λ|(x) tell x to its guess = its secret - end lambda + end |λ| end script -- challenge :: () -> {secret: Int, guess: Int} @@ -21,14 +23,14 @@ on run end if end response - on lambda(rec) + on |λ|(rec) {secret:(random number from 1 to 10), guess:response() ¬ of challenge, attempts:(attempts of rec) + 1} - end lambda + end |λ| end script - -- MAIN LOOP + -- MAIN LOOP ------------------------------------------------------------- set rec to |until|(isMatch, challenge, {secret:-1, guess:0, attempts:0}) display dialog (((guess of rec) as string) & ": Well guessed ! " & ¬ @@ -36,29 +38,7 @@ on run end run - --- GENERIC LBRARY FUNCTIONS - --- until :: (a -> Bool) -> (a -> a) -> a -> a -on |until|(p, f, x) - set mp to mReturn(p) - set mf to mReturn(f) - - script - property p : mp's lambda - property f : mf's lambda - - on lambda(v) - repeat until p(v) - set v to f(v) - end repeat - return v - end lambda - end script - - result's lambda(x) -end |until| - +-- GENERIC FUNCTIONS --------------------------------------------------------- -- isInteger :: a -> Bool on isInteger(e) @@ -77,7 +57,20 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn + +-- until :: (a -> Bool) -> (a -> a) -> a -> a +on |until|(p, f, x) + set mp to mReturn(p) + set v to x + + tell mReturn(f) + repeat until mp's |λ|(v) + set v to |λ|(v) + end repeat + end tell + return v +end |until| diff --git a/Task/Guess-the-number/BASIC/guess-the-number-3.basic b/Task/Guess-the-number/BASIC/guess-the-number-3.basic index 9fb0d48fa8..4dc45eb278 100644 --- a/Task/Guess-the-number/BASIC/guess-the-number-3.basic +++ b/Task/Guess-the-number/BASIC/guess-the-number-3.basic @@ -1,3 +1,3 @@ 1 LET n=INT (RND*10)+1 -2 INPUT "Guess a number that is between 1 and 10: ",g: IF g=n THEN PRINT "That's my number!": STOP +2 INPUT "Guess a number that's between 1 and 10: ",g: IF g=n THEN PRINT "That's my number!": STOP 3 PRINT "Guess again!": GO TO 2 diff --git a/Task/Guess-the-number/Dart/guess-the-number.dart b/Task/Guess-the-number/Dart/guess-the-number.dart new file mode 100644 index 0000000000..d15aee79db --- /dev/null +++ b/Task/Guess-the-number/Dart/guess-the-number.dart @@ -0,0 +1,12 @@ +import 'dart:math'; +void main() +{ + int y=5; + int max=11,min=1; + var x= new Random(); + x=x.nextInt(max-min); + if (y==x) + print("WON"); + else + print('Try Again'); +} diff --git a/Task/Guess-the-number/Gambas/guess-the-number.gambas b/Task/Guess-the-number/Gambas/guess-the-number.gambas new file mode 100644 index 0000000000..e4355a27dd --- /dev/null +++ b/Task/Guess-the-number/Gambas/guess-the-number.gambas @@ -0,0 +1,15 @@ +Public Sub Form_Open() +Dim byGuess, byGos As Byte +Dim byNo As Byte = Rand(1, 10) +Dim sHead As String = "Guess the number" + +Repeat + Inc byGos + byGuess = InputBox("Guess the number between 1 and 10", sHead) + sHead = "Sorry, have another go" +Until byGuess = byNo + +Message.Info("Well guessed! You took " & Str(byGos) & " gos to guess the number was " & Str(byNo), "OK") +Me.Close + +End diff --git a/Task/Guess-the-number/Jq/guess-the-number-1.jq b/Task/Guess-the-number/Jq/guess-the-number-1.jq new file mode 100644 index 0000000000..e315f491fb --- /dev/null +++ b/Task/Guess-the-number/Jq/guess-the-number-1.jq @@ -0,0 +1,3 @@ +{prompt: "Please enter your guess:", random: (1+rand(9)) } +| ( (while( .guess != .random; .guess = (input|tonumber) ) | .prompt), + "Well done!" diff --git a/Task/Guess-the-number/Jq/guess-the-number-2.jq b/Task/Guess-the-number/Jq/guess-the-number-2.jq new file mode 100644 index 0000000000..933404ebef --- /dev/null +++ b/Task/Guess-the-number/Jq/guess-the-number-2.jq @@ -0,0 +1,15 @@ +# LCG::Microsoft generates 15-bit integers using the same formula +# as rand() from the Microsoft C Runtime. +# Input: [ count, state, random ] +def next_rand_Microsoft: + .[0] as $count + | ((214013 * .[1]) + 2531011) % 2147483648 # mod 2^31 + | [$count+1 , ., (. / 65536 | floor) ]; + +def rand_Microsoft(seed): + [0,seed] + | next_rand_Microsoft # the seed is not so random + | next_rand_Microsoft | .[2]; + +# A random integer in [0 ... (n-1)]: +def rand(n): n * (rand_Microsoft($seed|tonumber) / 32768) | trunc; diff --git a/Task/Guess-the-number/Julia/guess-the-number.julia b/Task/Guess-the-number/Julia/guess-the-number.julia index 22227107d5..8206a296ac 100644 --- a/Task/Guess-the-number/Julia/guess-the-number.julia +++ b/Task/Guess-the-number/Julia/guess-the-number.julia @@ -1,7 +1,7 @@ function guess() number = rand(1:10) print("Guess my number! ") - while(chomp(readline(STDIN)) != string(number)) + while(readline(STDIN) != string(number)) print("Nope, try again! ") end println("Well guessed!") diff --git a/Task/Guess-the-number/Kotlin/guess-the-number.kotlin b/Task/Guess-the-number/Kotlin/guess-the-number.kotlin new file mode 100644 index 0000000000..afacbf1eb6 --- /dev/null +++ b/Task/Guess-the-number/Kotlin/guess-the-number.kotlin @@ -0,0 +1,16 @@ +// version 1.0.5-2 + +fun main(args: Array) { + val rand = java.util.Random() + val n = 1 + rand.nextInt(10) + var guess: Int + println("Guess which number I've chosen in the range 1 to 10\n") + while (true) { + print(" Your guess : ") + guess = readLine()!!.toInt() + if (n == guess) { + println("\nWell guessed!") + return + } + } +} diff --git a/Task/Guess-the-number/Nimrod/guess-the-number.nimrod b/Task/Guess-the-number/Nimrod/guess-the-number.nimrod deleted file mode 100644 index 4ddc36ad9f..0000000000 --- a/Task/Guess-the-number/Nimrod/guess-the-number.nimrod +++ /dev/null @@ -1,13 +0,0 @@ -import strutils, math - -randomize() -var chosen = 1 + random(10) -echo "I have thought of a number. Try to guess it!" - -var guess = parseInt(readLine(stdin)) - -while guess != chosen: - echo "Your guess was wrong. Try again!" - guess = parseInt(readLine(stdin)) - -echo "Well guessed!" diff --git a/Task/Guess-the-number/Ol/guess-the-number.ol b/Task/Guess-the-number/Ol/guess-the-number.ol new file mode 100644 index 0000000000..b4f8ce8d18 --- /dev/null +++ b/Task/Guess-the-number/Ol/guess-the-number.ol @@ -0,0 +1,8 @@ +(import (otus random!)) + +(define number (+ 1 (rand! 10))) +(let loop () + (display "Pick a number from 1 through 10: ") + (if (eq? (read) number) + (print "Well guessed!") + (loop))) diff --git a/Task/Guess-the-number/Python/guess-the-number.py b/Task/Guess-the-number/Python/guess-the-number.py index 272b0f2dae..b785c41d0e 100644 --- a/Task/Guess-the-number/Python/guess-the-number.py +++ b/Task/Guess-the-number/Python/guess-the-number.py @@ -1,5 +1,6 @@ import random target, guess = random.randint(1, 10), 0 +guess = int(input("Guess a number that's between 1 and 10: ")) while target != guess: - guess = int(input("Guess a number that is between 1 and 10: ")) + guess = int(input("Guess again! ")) print("That's right!") diff --git a/Task/Guess-the-number/REXX/guess-the-number-2.rexx b/Task/Guess-the-number/REXX/guess-the-number-2.rexx index 8a013f7c5c..83f5f1594c 100644 --- a/Task/Guess-the-number/REXX/guess-the-number-2.rexx +++ b/Task/Guess-the-number/REXX/guess-the-number-2.rexx @@ -1,9 +1,9 @@ -/*REXX program interactively plays "guess my number" with a human. */ -?=random(1,10) /*generate a low random integer. */ -say 'Try to guess my number between 1 ──► 10 (inclusive).' /*directive*/ +/*REXX program interactively plays "guess my number" with a human, the range is 1──►10. */ +?=random(1, 10) /*generate a low random integer. */ +say 'Try to guess my number between 1 ──► 10 (inclusive).' /*the directive.*/ - do j=1 until g=? /*keep at it ···*/ - if j\==1 then say 'Try again.' /*2nd-ary prompt*/ - pull g /*obtain a guess*/ + do j=1 until g=? /*keep at it ···*/ + if j\==1 then say 'Try again.' /*2nd-ary prompt*/ + pull g /*obtain a guess*/ end /*j*/ -say 'Well guessed!' /*stick a fork in it, we're done.*/ +say 'Well guessed!' /*stick a fork in it, we're all done. */ diff --git a/Task/Guess-the-number/Sidef/guess-the-number.sidef b/Task/Guess-the-number/Sidef/guess-the-number.sidef index 6ddc1c6702..943a7f1745 100644 --- a/Task/Guess-the-number/Sidef/guess-the-number.sidef +++ b/Task/Guess-the-number/Sidef/guess-the-number.sidef @@ -1,6 +1,6 @@ -var n = 10.rand(1).int; -print 'Guess the number: '; -while (n != read(Number).int) { +var n = pick(1..10) +print 'Guess the number: ' +while (n != read(Number).int) { print 'Wrong! Guess again: ' } -say 'Well guessed!'; +say 'Well guessed!' diff --git a/Task/Guess-the-number/Zkl/guess-the-number.zkl b/Task/Guess-the-number/Zkl/guess-the-number.zkl new file mode 100644 index 0000000000..9f61b5cfda --- /dev/null +++ b/Task/Guess-the-number/Zkl/guess-the-number.zkl @@ -0,0 +1,6 @@ +r:=((0).random(10)+1).toString(); +while(1){ + n:=ask("Num between 1 & 10: "); + if(n==r){ println("Well guessed!"); break; } + println("Nope") +} diff --git a/Task/HTTP/BaCon/http.bacon b/Task/HTTP/BaCon/http.bacon new file mode 100644 index 0000000000..8ba5e4fce6 --- /dev/null +++ b/Task/HTTP/BaCon/http.bacon @@ -0,0 +1,18 @@ +' +' Read and display a website +' +SPLIT ARGUMENT$ BY " " TO arg$ SIZE dim +IF dim < 2 THEN + website$ = "www.basic-converter.org" +ELSE + website$ = arg$[1] +ENDIF + +OPEN CONCAT$(website$, ":80") FOR NETWORK AS mynet +SEND CONCAT$("GET / HTTP/1.1\r\nHost: ", website$, "\r\n\r\n") TO mynet +REPEAT + RECEIVE dat$ FROM mynet + total$ = total$ & dat$ +UNTIL ISFALSE(WAIT(mynet, 5000)) +CLOSE NETWORK mynet +PRINT total$ diff --git a/Task/HTTP/Friendly-interactive-shell/http-1.fish b/Task/HTTP/Friendly-interactive-shell/http-1.fish new file mode 100644 index 0000000000..91ce011b16 --- /dev/null +++ b/Task/HTTP/Friendly-interactive-shell/http-1.fish @@ -0,0 +1 @@ +curl -s -L http://rosettacode.org/ diff --git a/Task/HTTP/Friendly-interactive-shell/http-2.fish b/Task/HTTP/Friendly-interactive-shell/http-2.fish new file mode 100644 index 0000000000..5fcc1c9dd0 --- /dev/null +++ b/Task/HTTP/Friendly-interactive-shell/http-2.fish @@ -0,0 +1 @@ +lynx -source http://rosettacode.org/ diff --git a/Task/HTTP/Friendly-interactive-shell/http-3.fish b/Task/HTTP/Friendly-interactive-shell/http-3.fish new file mode 100644 index 0000000000..a8e9bf851b --- /dev/null +++ b/Task/HTTP/Friendly-interactive-shell/http-3.fish @@ -0,0 +1 @@ +wget -O - -q http://rosettacode.org/ diff --git a/Task/HTTP/Friendly-interactive-shell/http-4.fish b/Task/HTTP/Friendly-interactive-shell/http-4.fish new file mode 100644 index 0000000000..0c60c13724 --- /dev/null +++ b/Task/HTTP/Friendly-interactive-shell/http-4.fish @@ -0,0 +1 @@ +lftp -c "cat http://rosettacode.org/" diff --git a/Task/HTTP/Friendly-interactive-shell/http-5.fish b/Task/HTTP/Friendly-interactive-shell/http-5.fish new file mode 100644 index 0000000000..c06fc5c7b2 --- /dev/null +++ b/Task/HTTP/Friendly-interactive-shell/http-5.fish @@ -0,0 +1 @@ +ftp -o - http://rosettacode.org ^ /dev/null diff --git a/Task/HTTP/Gastona/http.gastona b/Task/HTTP/Gastona/http.gastona new file mode 100644 index 0000000000..79af7acc7d --- /dev/null +++ b/Task/HTTP/Gastona/http.gastona @@ -0,0 +1,5 @@ +#listix# + +
    + LOOP, TEXT FILE, http://www.rosettacode.org + , BODY, @ diff --git a/Task/HTTP/Halon/http.halon b/Task/HTTP/Halon/http.halon new file mode 100644 index 0000000000..91da60e8bf --- /dev/null +++ b/Task/HTTP/Halon/http.halon @@ -0,0 +1 @@ +echo http("http://www.rosettacode.org"); diff --git a/Task/HTTP/Kotlin/http.kotlin b/Task/HTTP/Kotlin/http.kotlin new file mode 100644 index 0000000000..dfb70dd256 --- /dev/null +++ b/Task/HTTP/Kotlin/http.kotlin @@ -0,0 +1,13 @@ +// version 1.1.2 + +import java.net.URL +import java.io.InputStreamReader +import java.util.Scanner + +fun main(args: Array) { + val url = URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt") + val isr = InputStreamReader(url.openStream()) + val sc = Scanner(isr) + while (sc.hasNextLine()) println(sc.nextLine()) + sc.close() +} diff --git a/Task/HTTP/NewLISP/http.newlisp b/Task/HTTP/NewLISP/http.newlisp new file mode 100644 index 0000000000..0efd0512b1 --- /dev/null +++ b/Task/HTTP/NewLISP/http.newlisp @@ -0,0 +1 @@ +(get-url "http://www.rosettacode.org") diff --git a/Task/HTTP/OoRexx/http.rexx b/Task/HTTP/OoRexx/http.rexx new file mode 100644 index 0000000000..9029ce7ae1 --- /dev/null +++ b/Task/HTTP/OoRexx/http.rexx @@ -0,0 +1,6 @@ +url=.bsf~new("java.net.URL","http://teletext.orf.at") +sc =.bsf~new("java.util.Scanner",url~openStream) +loop while sc~hasNext + say sc~nextLine + End +::requires BSF.CLS -- get Java camouflaging support diff --git a/Task/HTTP/Protium/http-1.protium b/Task/HTTP/Protium/http-1.protium deleted file mode 100644 index 8183050b74..0000000000 --- a/Task/HTTP/Protium/http-1.protium +++ /dev/null @@ -1 +0,0 @@ -<@ SAYURLLIT>http://rosettacode.org/wiki/Main_Page diff --git a/Task/HTTP/Protium/http-2.protium b/Task/HTTP/Protium/http-2.protium deleted file mode 100644 index 727442c3c8..0000000000 --- a/Task/HTTP/Protium/http-2.protium +++ /dev/null @@ -1 +0,0 @@ -<# SAY URLSOURCE LITERAL>http://rosettacode.org/wiki/Main_Page diff --git a/Task/HTTP/Sidef/http.sidef b/Task/HTTP/Sidef/http.sidef index 467928aabe..0931d6ad19 100644 --- a/Task/HTTP/Sidef/http.sidef +++ b/Task/HTTP/Sidef/http.sidef @@ -1,13 +1,13 @@ func get(url) { var lwp = ( try { require('LWP::UserAgent') } - catch { warn "'LWP::UserAgent' is not installed!"; return } - ); - var ua = lwp.new(agent => 'Mozilla/5.0'); + catch { warn "'LWP::UserAgent' is not installed!"; return nil } + ) + var ua = lwp.new(agent => 'Mozilla/5.0') if (var resp = ua.get(url); resp.is_success) { - return resp.decoded_content; - }; - return; + return resp.decoded_content + } + return nil } -print get("http://rosettacode.org"); +print get("http://rosettacode.org") diff --git a/Task/HTTP/Zkl/http.zkl b/Task/HTTP/Zkl/http.zkl new file mode 100644 index 0000000000..21858eee6f --- /dev/null +++ b/Task/HTTP/Zkl/http.zkl @@ -0,0 +1,14 @@ +url := ask(0,"URL: "); + +host := url; +dir := "/"; +port := 80; +if (n := url.find("/")) { dir = url[n,*]; host = url[0,n]; } +if (n := host.find(":")) { port = host[n+1,*]; host = host[0,n]; } + +get := "GET %s HTTP/1.0\r\nHost: %s:%s\r\n\r\n".fmt(dir,host,port.toInt()); +println("-->",get); +server := Network.TCPClientSocket.connectTo(host,port); +server.write(get); +data := server.read(True); +println(data.text); diff --git a/Task/HTTPS-Authenticated/Zkl/https-authenticated.zkl b/Task/HTTPS-Authenticated/Zkl/https-authenticated.zkl new file mode 100644 index 0000000000..a7b021ddd5 --- /dev/null +++ b/Task/HTTPS-Authenticated/Zkl/https-authenticated.zkl @@ -0,0 +1,4 @@ +zkl: var ZC=Import("zklCurl") +zkl: var data=ZC().get("http://usr:pw@192.168.1.1/computer_list.xml") +L(Data(1,049),121,0) +zkl: data[0][121,*].text diff --git a/Task/HTTPS-Client-authenticated/Perl/https-client-authenticated.pl b/Task/HTTPS-Client-authenticated/Perl/https-client-authenticated.pl new file mode 100644 index 0000000000..42a376f45f --- /dev/null +++ b/Task/HTTPS-Client-authenticated/Perl/https-client-authenticated.pl @@ -0,0 +1,22 @@ +#!/usr/bin/env perl -T +use 5.018_002; +use warnings; +use LWP; + +our $VERSION = 1.000_000; + +my $ua = LWP::UserAgent->new( + ssl_opts => { + SSL_cert_file => 'certificate.pem', + SSL_key_file => 'key.pem', + verify_hostname => 1, + } +); +my $req = HTTP::Request->new( GET => 'https://www.example.com' ); +my $res = $ua->request($req); +if ( $res->is_success ) { + say $res->content; +} +else { + say $res->status_line; +} diff --git a/Task/HTTPS-Client-authenticated/Run-BASIC/https-client-authenticated.run b/Task/HTTPS-Client-authenticated/Run-BASIC/https-client-authenticated.run deleted file mode 100644 index 5bfd8e8e1b..0000000000 --- a/Task/HTTPS-Client-authenticated/Run-BASIC/https-client-authenticated.run +++ /dev/null @@ -1,32 +0,0 @@ -html " -
    - -
    LOGIN
    UserName" - TEXTBOX #userName, "" -html "
    Password:" -PasswordBox #passWord, "" - -html "
    " -button #si, "Signin", [doSignin] -html " " -button #ex, "Exit", [exit] -html "
    " -WAIT - -[doSignin] -loginUserName$ = trim$(#userName contents$()) -loginPassWord$ = trim$(#passWord contents$()) -if (loginUserName$ = "admin" and loginPassWord$ = "admin" then - print "Login ok" - else - print "invalid User or Pass" - cls - goto [loop] -end if - -print Platform$ ' OS where Run BASIC is being hosted -print UserInfo$ ' Information about the user's web browser -print UserAddress$ ' IP address of the user - -[exit] -end diff --git a/Task/HTTPS-Client-authenticated/Zkl/https-client-authenticated.zkl b/Task/HTTPS-Client-authenticated/Zkl/https-client-authenticated.zkl new file mode 100644 index 0000000000..c2ebc7b7b8 --- /dev/null +++ b/Task/HTTPS-Client-authenticated/Zkl/https-client-authenticated.zkl @@ -0,0 +1,3 @@ +var CURL=Import("zklCurl"), c=CURL(); +c.setOpt("SSLCERT","certFile.pem"); c.setOpt("SSLCERTTYPE","pem"); +c.get("http://zenkinetic.com"); // lame example to show how to read diff --git a/Task/HTTPS/Haskell/https.hs b/Task/HTTPS/Haskell/https-1.hs similarity index 100% rename from Task/HTTPS/Haskell/https.hs rename to Task/HTTPS/Haskell/https-1.hs diff --git a/Task/HTTPS/Unicon/https.unicon b/Task/HTTPS/Haskell/https-2.hs similarity index 100% rename from Task/HTTPS/Unicon/https.unicon rename to Task/HTTPS/Haskell/https-2.hs diff --git a/Task/HTTPS/Julia/https.julia b/Task/HTTPS/Julia/https.julia new file mode 100644 index 0000000000..fe6a931dba --- /dev/null +++ b/Task/HTTPS/Julia/https.julia @@ -0,0 +1,5 @@ +# v0.6.0 + +using Requests + +str = readstring(get("https://sourceforge.net/")) diff --git a/Task/HTTPS/Kotlin/https.kotlin b/Task/HTTPS/Kotlin/https.kotlin new file mode 100644 index 0000000000..80a2b5b7ab --- /dev/null +++ b/Task/HTTPS/Kotlin/https.kotlin @@ -0,0 +1,14 @@ +// version 1.1.2 +import java.net.URL +import javax.net.ssl.HttpsURLConnection +import java.io.InputStreamReader +import java.util.Scanner + +fun main(args: Array) { + val url = URL("https://en.wikipedia.org/wiki/Main_Page") + val connection = url.openConnection() as HttpsURLConnection + val isr = InputStreamReader(connection.inputStream) + val sc = Scanner(isr) + while (sc.hasNextLine()) println(sc.nextLine()) + sc.close() +} diff --git a/Task/HTTPS/Zkl/https.zkl b/Task/HTTPS/Zkl/https.zkl new file mode 100644 index 0000000000..735876cce3 --- /dev/null +++ b/Task/HTTPS/Zkl/https.zkl @@ -0,0 +1,3 @@ +zkl: var ZC=Import("zklCurl") +zkl: var data=ZC().get("https://sourceforge.net") +L(Data(36,265),826,0) diff --git a/Task/Hailstone-sequence/00DESCRIPTION b/Task/Hailstone-sequence/00DESCRIPTION index d6f92d4d17..fa499ad5f2 100644 --- a/Task/Hailstone-sequence/00DESCRIPTION +++ b/Task/Hailstone-sequence/00DESCRIPTION @@ -4,16 +4,16 @@ The Hailstone sequence of numbers can be generated from a starting positive inte *   If   n   is   '''odd'''   then the next   n   of the sequence   = (3 * n) + 1 -The (unproven),   [[wp:Collatz conjecture|Collatz conjecture]]   is that the hailstone sequence for any starting number always terminates. +The (unproven) [[wp:Collatz conjecture|Collatz conjecture]] is that the hailstone sequence for any starting number always terminates. -The   ''hailstone sequence''   is also known as   ''hailstone numbers''   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).   The   ''hailstone sequence''   is also sometimes known as the   ''Collatz sequence''. +The hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud), or as the ''Collatz sequence''. ;Task: -#   Create a routine to generate the hailstone sequence for a number. -#   Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 -#   Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
      (But don't show the actual sequence!) +# Create a routine to generate the hailstone sequence for a number. +# Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 +# Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
      (But don't show the actual sequence!) ;See also: diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-3.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-3.basic index 25ddfbd791..599dfc10f9 100644 --- a/Task/Hailstone-sequence/BASIC/hailstone-sequence-3.basic +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-3.basic @@ -1,91 +1,23 @@ -' version 17-06-2015 -' compile with: fbc -s console - -Function hailstone_fast(number As ULongInt) As ULongInt - ' faster version - ' only counts the sequence - - Dim As ULongInt count = 1 - - While number <> 1 - If (number And 1) = 1 Then - number += number Shr 1 + 1 ' 3*n+1 and n/2 in one - count += 2 - Else - number Shr= 1 ' divide number by 2 - count += 1 - End If - Wend - - Return count - -End Function - -Sub hailstone_print(number As ULongInt) - ' print the number and sequence - - Dim As ULongInt count = 1 - - Print "sequence for number "; number - Print Using "########"; number; 'starting number - - While number <> 1 - If (number And 1) = 1 Then - number = number * 3 + 1 ' n * 3 + 1 - count += 1 - Else - number = number \ 2 ' n \ 2 - count += 1 - End If - Print Using "########"; number; - Wend - - Print : Print - Print "sequence length = "; count - Print - Print String(79,"-") - -End Sub - -Function hailstone(number As ULongInt) As ULongInt - ' normal version - ' only counts the sequence - - Dim As ULongInt count = 1 - - While number <> 1 - If (number And 1) = 1 Then - number = number * 3 + 1 ' n * 3 + 1 - count += 1 - End If - number = number \ 2 ' divide number by 2 - count += 1 - Wend - - Return count - -End Function - -' ------=< MAIN >=------ - -Dim As ULongInt number -Dim As UInteger x, max_x, max_seq - -hailstone_print(27) -Print - -For x As UInteger = 1 To 100000 - number = hailstone(x) - If number > max_seq Then - max_x = x - max_seq = number - End If -Next - -Print "The longest sequence is for "; max_x; ", it has a sequence length of "; max_seq - -' empty keyboard buffer -While Inkey <> "" : Wend -Print : Print : Print "hit any key to end program" -Sleep -End +100 PRINT : PRINT "HAILSTONE SEQUENCE FOR N = 27:" +110 N=27 : SHOW=1 +120 GOSUB 1000 +130 PRINT X"ELEMENTS" +140 PRINT : PRINT "FINDING N WITH THE LONGEST HAILSTONE SEQUENCE" +150 SHOW=0 +160 T0 = TI +170 FOR N=2 TO 100000 +180 : GOSUB 1000 +190 : IF X>MAX THEN MAX=X : NMAX = N +200 : REM' PRINT N,X,MAX +210 NEXT +230 PRINT "LONGEST HAILSTONE SEQUENCE STARTS WITH "NMAX"." +240 PRINT "IT HAS"MAX"ELEMENTS" +260 END +1000 REM '*** HAILSTONE SEQUENCE SUBROUTINE *** +1010 X = 0 : S = N +1020 IF SHOW THEN PRINT S, +1030 X = X+1 +1040 IF S=1 THEN RETURN +1050 IF INT(S/2)=S/2 THEN S = S/2 : GOTO 1020 +1060 S = 3*S+1 +1070 GOTO 1020 diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-4.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-4.basic index 8f487d6014..25ddfbd791 100644 --- a/Task/Hailstone-sequence/BASIC/hailstone-sequence-4.basic +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-4.basic @@ -1,52 +1,91 @@ -print "Part 1: Create a routine to generate the hailstone sequence for a number." -print "" -while hailstone < 1 or hailstone <> int(hailstone) - input "Please enter a positive integer: "; hailstone -wend -print "" -print "The following is the 'Hailstone Sequence' for your number..." -print "" -print hailstone -while hailstone <> 1 - if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 - print hailstone -wend -print "" -input "Hit 'Enter' to continue to part 2...";dummy$ -cls -print "Part 2: Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1." -print "" -print "No. in Seq.","Hailstone Sequence Number for 27" -print "" -c = 1: hailstone = 27 -print c, hailstone -while hailstone <> 1 - c = c + 1 - if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 - print c, hailstone -wend -print "" -input "Hit 'Enter' to continue to part 3...";dummy$ -cls -print "Part 3: Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.(But don't show the actual sequence)!" -print "" -print "Calculating result... Please wait... This could take a little while..." -print "" -print "Percent Done", "Start Number", "Seq. Length", "Maximum Sequence So Far" -print "" -for cc = 1 to 99999 - hailstone = cc: c = 1 - while hailstone <> 1 - c = c + 1 - if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 - wend - if c > max then max = c: largesthailstone = cc - locate 1, 7 - print " " - locate 1, 7 - print using("###.###", cc / 99999 * 100);"%", cc, c, max - scan -next cc -print "" -print "The number less than 100,000 with the longest 'Hailstone Sequence' is "; largesthailstone;". It's sequence length is "; max;"." -end +' version 17-06-2015 +' compile with: fbc -s console + +Function hailstone_fast(number As ULongInt) As ULongInt + ' faster version + ' only counts the sequence + + Dim As ULongInt count = 1 + + While number <> 1 + If (number And 1) = 1 Then + number += number Shr 1 + 1 ' 3*n+1 and n/2 in one + count += 2 + Else + number Shr= 1 ' divide number by 2 + count += 1 + End If + Wend + + Return count + +End Function + +Sub hailstone_print(number As ULongInt) + ' print the number and sequence + + Dim As ULongInt count = 1 + + Print "sequence for number "; number + Print Using "########"; number; 'starting number + + While number <> 1 + If (number And 1) = 1 Then + number = number * 3 + 1 ' n * 3 + 1 + count += 1 + Else + number = number \ 2 ' n \ 2 + count += 1 + End If + Print Using "########"; number; + Wend + + Print : Print + Print "sequence length = "; count + Print + Print String(79,"-") + +End Sub + +Function hailstone(number As ULongInt) As ULongInt + ' normal version + ' only counts the sequence + + Dim As ULongInt count = 1 + + While number <> 1 + If (number And 1) = 1 Then + number = number * 3 + 1 ' n * 3 + 1 + count += 1 + End If + number = number \ 2 ' divide number by 2 + count += 1 + Wend + + Return count + +End Function + +' ------=< MAIN >=------ + +Dim As ULongInt number +Dim As UInteger x, max_x, max_seq + +hailstone_print(27) +Print + +For x As UInteger = 1 To 100000 + number = hailstone(x) + If number > max_seq Then + max_x = x + max_seq = number + End If +Next + +Print "The longest sequence is for "; max_x; ", it has a sequence length of "; max_seq + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-5.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-5.basic index d8536360e3..8f487d6014 100644 --- a/Task/Hailstone-sequence/BASIC/hailstone-sequence-5.basic +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-5.basic @@ -1,37 +1,52 @@ -function Hailstone(sys *n) -'========================= -if n and 1 - n=n*3+1 -else - n=n>>1 -end if -end function - -function HailstoneSequence(sys n) as sys -'======================================= -count=1 -do - Hailstone n - Count++ - if n=1 then exit do -end do -return count -end function - -'MAIN -'==== - -maxc=0 -maxn=0 -e=100000 -for n=1 to e - c=HailstoneSequence n - if c>maxc - maxc=c - maxn=n - end if -next - -print e ", " maxn ", " maxc - -'result 100000, 77031, 351 +print "Part 1: Create a routine to generate the hailstone sequence for a number." +print "" +while hailstone < 1 or hailstone <> int(hailstone) + input "Please enter a positive integer: "; hailstone +wend +print "" +print "The following is the 'Hailstone Sequence' for your number..." +print "" +print hailstone +while hailstone <> 1 + if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 + print hailstone +wend +print "" +input "Hit 'Enter' to continue to part 2...";dummy$ +cls +print "Part 2: Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1." +print "" +print "No. in Seq.","Hailstone Sequence Number for 27" +print "" +c = 1: hailstone = 27 +print c, hailstone +while hailstone <> 1 + c = c + 1 + if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 + print c, hailstone +wend +print "" +input "Hit 'Enter' to continue to part 3...";dummy$ +cls +print "Part 3: Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.(But don't show the actual sequence)!" +print "" +print "Calculating result... Please wait... This could take a little while..." +print "" +print "Percent Done", "Start Number", "Seq. Length", "Maximum Sequence So Far" +print "" +for cc = 1 to 99999 + hailstone = cc: c = 1 + while hailstone <> 1 + c = c + 1 + if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 + wend + if c > max then max = c: largesthailstone = cc + locate 1, 7 + print " " + locate 1, 7 + print using("###.###", cc / 99999 * 100);"%", cc, c, max + scan +next cc +print "" +print "The number less than 100,000 with the longest 'Hailstone Sequence' is "; largesthailstone;". It's sequence length is "; max;"." +end diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-6.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-6.basic index 76de11443f..d8536360e3 100644 --- a/Task/Hailstone-sequence/BASIC/hailstone-sequence-6.basic +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-6.basic @@ -1,48 +1,37 @@ -NewList Hailstones.i() ; Make a linked list to use as we do not know the numbers of elements needed for an Array +function Hailstone(sys *n) +'========================= +if n and 1 + n=n*3+1 +else + n=n>>1 +end if +end function -Procedure.i FillHailstones(n) ; Fills the list & returns the amount of elements in the list - Shared Hailstones() ; Get access to the Hailstones-List - ClearList(Hailstones()) ; Remove old data - Repeat - AddElement(Hailstones()) ; Add an element to the list - Hailstones()=n ; Fill current value in the new list element - If n=1 - ProcedureReturn ListSize(Hailstones()) - ElseIf n%2=0 - n/2 - Else - n=(3*n)+1 - EndIf - ForEver -EndProcedure +function HailstoneSequence(sys n) as sys +'======================================= +count=1 +do + Hailstone n + Count++ + if n=1 then exit do +end do +return count +end function -If OpenConsole() - Define i, l, maxl, maxi - l=FillHailstones(27) - Print("#27 has "+Str(l)+" elements and the sequence is: "+#CRLF$) - ForEach Hailstones() - If i=6 - Print(#CRLF$) - i=0 - EndIf - i+1 - Print(RSet(Str(Hailstones()),5)) - If Hailstones()<>1 - Print(", ") - EndIf - Next +'MAIN +'==== - i=1 - Repeat - l=FillHailstones(i) - If l>maxl - maxl=l - maxi=i - EndIf - i+1 - Until i>=100000 - Print(#CRLF$+#CRLF$+"The longest sequence below 100000 is #"+Str(maxi)+", and it has "+Str(maxl)+" elements.") +maxc=0 +maxn=0 +e=100000 +for n=1 to e + c=HailstoneSequence n + if c>maxc + maxc=c + maxn=n + end if +next - Print(#CRLF$+#CRLF$+"Press ENTER to exit."): Input() - CloseConsole() -EndIf +print e ", " maxn ", " maxc + +'result 100000, 77031, 351 diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-7.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-7.basic index 84d246dfee..76de11443f 100644 --- a/Task/Hailstone-sequence/BASIC/hailstone-sequence-7.basic +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-7.basic @@ -1,40 +1,48 @@ -print "Part 1: Create a routine to generate the hailstone sequence for a number." -print "" +NewList Hailstones.i() ; Make a linked list to use as we do not know the numbers of elements needed for an Array -while hailstone < 1 or hailstone <> int(hailstone) - input "Please enter a positive integer: "; hailstone -wend -count = doHailstone(hailstone,"Y") +Procedure.i FillHailstones(n) ; Fills the list & returns the amount of elements in the list + Shared Hailstones() ; Get access to the Hailstones-List + ClearList(Hailstones()) ; Remove old data + Repeat + AddElement(Hailstones()) ; Add an element to the list + Hailstones()=n ; Fill current value in the new list element + If n=1 + ProcedureReturn ListSize(Hailstones()) + ElseIf n%2=0 + n/2 + Else + n=(3*n)+1 + EndIf + ForEver +EndProcedure -print: print "Part 2: Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1." -count = doHailstone(27,"Y") +If OpenConsole() + Define i, l, maxl, maxi + l=FillHailstones(27) + Print("#27 has "+Str(l)+" elements and the sequence is: "+#CRLF$) + ForEach Hailstones() + If i=6 + Print(#CRLF$) + i=0 + EndIf + i+1 + Print(RSet(Str(Hailstones()),5)) + If Hailstones()<>1 + Print(", ") + EndIf + Next -print: print "Part 3: Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.(But don't show the actual sequence)!" -print "Calculating result... Please wait... This could take a little while..." -print "Stone Percent Count" -for i = 1 to 99999 - count = doHailstone(i,"N") - if count > maxCount then - theBigStone = i - maxCount = count - print using("#####",i);" ";using("###.#", i / 99999 * 100);"% ";using("####",count) - end if -next i -end + i=1 + Repeat + l=FillHailstones(i) + If l>maxl + maxl=l + maxi=i + EndIf + i+1 + Until i>=100000 + Print(#CRLF$+#CRLF$+"The longest sequence below 100000 is #"+Str(maxi)+", and it has "+Str(maxl)+" elements.") -'--------------------------------------------- -' pass number and print (Y/N) -FUNCTION doHailstone(hailstone,prnt$) -if prnt$ = "Y" then - print - print "The following is the 'Hailstone Sequence' for number:";hailstone -end if -while hailstone <> 1 - if (hailstone and 1) then hailstone = (hailstone * 3) + 1 else hailstone = hailstone / 2 - doHailstone = doHailstone + 1 - if prnt$ = "Y" then - print hailstone;chr$(9); - if (doHailstone mod 10) = 0 then print - end if -wend -END FUNCTION + Print(#CRLF$+#CRLF$+"Press ENTER to exit."): Input() + CloseConsole() +EndIf diff --git a/Task/Hailstone-sequence/Run-BASIC/hailstone-sequence.run b/Task/Hailstone-sequence/BASIC/hailstone-sequence-8.basic similarity index 100% rename from Task/Hailstone-sequence/Run-BASIC/hailstone-sequence.run rename to Task/Hailstone-sequence/BASIC/hailstone-sequence-8.basic diff --git a/Task/Hailstone-sequence/BBC-BASIC/hailstone-sequence.bbc b/Task/Hailstone-sequence/BBC-BASIC/hailstone-sequence.bbc deleted file mode 100644 index cb03395d1f..0000000000 --- a/Task/Hailstone-sequence/BBC-BASIC/hailstone-sequence.bbc +++ /dev/null @@ -1,23 +0,0 @@ - seqlen% = FNhailstone(27, TRUE) - PRINT '"Sequence length = "; seqlen% - maxlen% = 0 - FOR number% = 2 TO 100000 - seqlen% = FNhailstone(number%, FALSE) - IF seqlen% > maxlen% THEN - maxlen% = seqlen% - maxnum% = number% - ENDIF - NEXT - PRINT "The number with the longest hailstone sequence is " ; maxnum% - PRINT "Its sequence length is " ; maxlen% - END - - DEF FNhailstone(N%, S%) - LOCAL L% - IF S% THEN PRINT N%; - WHILE N% <> 1 - IF N% AND 1 THEN N% = 3 * N% + 1 ELSE N% DIV= 2 - IF S% THEN PRINT N%; - L% += 1 - ENDWHILE - = L% + 1 diff --git a/Task/Hailstone-sequence/Beeswax/hailstone-sequence-1.beeswax b/Task/Hailstone-sequence/Beeswax/hailstone-sequence-1.beeswax new file mode 100644 index 0000000000..1720348066 --- /dev/null +++ b/Task/Hailstone-sequence/Beeswax/hailstone-sequence-1.beeswax @@ -0,0 +1,3 @@ + >@:N q +>%"d3~@.PNp +d~2~pL~1F{@:N q +>%"d3~@.PNq +d~2~qL~1Ff{@: q pf1_# +>%"d3~@.Pqf#{g?` `{gpK@~BP9~5@P@q'M< +d~2~pL~1Ff< < >?d + >zAg?MM@1~y@~gLpz2~yg@~3~hAg?M d + >?~fz1~y?yg@hhAg?Mb diff --git a/Task/Hailstone-sequence/Beeswax/hailstone-sequence-5.beeswax b/Task/Hailstone-sequence/Beeswax/hailstone-sequence-5.beeswax new file mode 100644 index 0000000000..59970ae1ec --- /dev/null +++ b/Task/Hailstone-sequence/Beeswax/hailstone-sequence-5.beeswax @@ -0,0 +1 @@ +77031 351 diff --git a/Task/Hailstone-sequence/Futhark/hailstone-sequence.futhark b/Task/Hailstone-sequence/Futhark/hailstone-sequence.futhark index b96d23c881..8ed73feb9d 100644 --- a/Task/Hailstone-sequence/Futhark/hailstone-sequence.futhark +++ b/Task/Hailstone-sequence/Futhark/hailstone-sequence.futhark @@ -17,7 +17,7 @@ fun hailstone_seq(x: int): []int = let x = hailstone_step x let steps[i] = x in (capacity, i+1, steps, x) - in (split i steps).0 + in #1 (split i steps) fun hailstone_len(x: int): int = let i = 1 diff --git a/Task/Hailstone-sequence/Haskell/hailstone-sequence-1.hs b/Task/Hailstone-sequence/Haskell/hailstone-sequence-1.hs index b0500be0f4..66db1b763a 100644 --- a/Task/Hailstone-sequence/Haskell/hailstone-sequence-1.hs +++ b/Task/Hailstone-sequence/Haskell/hailstone-sequence-1.hs @@ -1,18 +1,26 @@ import Data.List (maximumBy) import Data.Ord (comparing) -main = do putStrLn $ "Collatz sequence for 27: " - ++ ((show.hailstone) 27) - ++ "\n" - ++ "The number " - ++ (show longestChain) - ++" has the longest hailstone sequence" - ++" for any number less then 100000. " - ++"The sequence has length " - ++ (show.length.hailstone $ longestChain) +hailstone :: Int -> [Int] +hailstone = takeWhile (/= 1) . iterate collatz + where + collatz n = + if even n + then n `div` 2 + else 3 * n + 1 -hailstone = takeWhile (/=1) . (iterate collatz) - where collatz n = if even n then n `div` 2 else 3*n+1 +longestChain :: Int +longestChain = + fst + (maximumBy (comparing snd) (((,) <*> length . hailstone) <$> [1 .. 100000])) -longestChain = fst $ maximumBy (comparing snd) $ - map ((\x -> (x,(length.hailstone) x))) [1..100000] +--TEST ------------------------------------------------------------------------- +main = + mapM_ + putStrLn + [ "Collatz sequence for 27: " + , (show . hailstone) 27 + , "The number " ++ show longestChain + , "has the longest hailstone sequence for any number less then 100000. " + , "The sequence has length: " ++ (show . length . hailstone $ longestChain) + ] diff --git a/Task/Hailstone-sequence/Haskell/hailstone-sequence-2.hs b/Task/Hailstone-sequence/Haskell/hailstone-sequence-2.hs index 212faec0a9..6cba7631f6 100644 --- a/Task/Hailstone-sequence/Haskell/hailstone-sequence-2.hs +++ b/Task/Hailstone-sequence/Haskell/hailstone-sequence-2.hs @@ -1,19 +1,26 @@ -import Data.List (maximumBy) import Data.Ord (comparing) +import Data.List (maximumBy, intercalate) hailstone :: Int -> [Int] -hailstone 1 = [1] -hailstone n | even n = n : hailstone (n `div` 2) - | otherwise = n : hailstone (n * 3 + 1) +hailstone 1 = [1] +hailstone n + | even n = n : hailstone (n `div` 2) + | otherwise = n : hailstone (n * 3 + 1) -withResult :: (t -> t1) -> t -> (t1, t) +withResult :: (Int -> Int) -> Int -> (Int, Int) withResult f x = (f x, x) +h27 :: [Int] +h27 = hailstone 27 + main :: IO () -main = do - let h27 = hailstone 27 - print $ length h27 - let h4 = show $ take 4 h27 - let t4 = show $ drop (length h27 - 4) h27 - putStrLn ("hailstone 27: " ++ h4 ++ " ... " ++ t4) - print $ maximumBy (comparing fst) $ map (withResult (length . hailstone)) [1..100000] +main = + mapM_ + putStrLn + [ (show . length) h27 + , "hailstone 27: " ++ + intercalate " ... " (show <$> [take 4 h27, drop (length h27 - 4) h27]) + , show $ + maximumBy (comparing fst) $ + withResult (length . hailstone) <$> [1 .. 100000] + ] diff --git a/Task/Hailstone-sequence/Haskell/hailstone-sequence-3.hs b/Task/Hailstone-sequence/Haskell/hailstone-sequence-3.hs new file mode 100644 index 0000000000..f9b2cbed6b --- /dev/null +++ b/Task/Hailstone-sequence/Haskell/hailstone-sequence-3.hs @@ -0,0 +1,53 @@ +import Data.List (unfoldr) + +hailStones :: Int -> [Int] +hailStones = + (++ [1]) . + unfoldr + (\x -> + if x < 2 + then Nothing + else Just + ( x + , if even x + then div x 2 + else (3 * x) + 1)) + +mostStones :: Int -> (Int, Int) +mostStones n = + foldr + (\x (m, ml) -> + let l = length (hailStones x) + in if l > ml + then (x, l) + else (m, ml)) + (0, 0) + [1 .. n] + +-- GENERIC ------------------------------------------------------------------- +lastN_ :: Int -> [Int] -> [Int] +lastN_ = (foldr (const (drop 1)) <*>) . drop + +-- TEST ----------------------------------------------------------------------- +h27, start27, end27 :: [Int] +[h27, start27, end27] = [id, take 4, lastN_ 4] <*> [hailStones 27] + +maxNum, maxLen :: Int +(maxNum, maxLen) = mostStones 100000 + +main :: IO () +main = + mapM_ + putStrLn + [ "Sequence 27 length:" + , show $ length h27 + , "Sequence 27 start:" + , show start27 + , "Sequence 27 end:" + , show end27 + , "" + , "N with longest sequence where N <= 100000" + , show maxNum + , "length of this sequence:" + , show maxLen + ] diff --git a/Task/Hailstone-sequence/JavaScript/hailstone-sequence-9.js b/Task/Hailstone-sequence/JavaScript/hailstone-sequence-9.js new file mode 100644 index 0000000000..47afdc8726 --- /dev/null +++ b/Task/Hailstone-sequence/JavaScript/hailstone-sequence-9.js @@ -0,0 +1,58 @@ +(() => { + const dctMemo = {}; + + // Length only of hailstone sequence + // collatzLength :: Int -> Int + const collatzLength = n => { + let i = 1; + let a = n; + let lng; + + while (a !== 1) { + lng = dctMemo[a]; + if ('u' === (typeof lng)[0]) { + a = (a % 2 ? 3 * a + 1 : a / 2); + i++; + } else return lng + i - 1; + } + return i; + }; + + // range :: Int -> Int -> Maybe Int -> [Int] + const range = (m, n, delta) => { + const blnUp = n > m, + d = blnUp ? (delta || 1) : -(delta || 1), + lng = Math.abs(Math.floor((blnUp ? n - m : m - n) / d) + 1), + a = Array(lng); + let i = lng; + + while (i--) a[i] = (d * i) + m; + return a; + }; + + // longestBelow :: Int -> {Number::Int, Length:Int} + const longestBelow = n => + range(1, n) + .reduce( + (a, x) => { + const lng = dctMemo[x] || (dctMemo[x] = collatzLength(x)); + + return lng > a.l ? { + n: x, + l: lng + } : a + + }, { + n: 0, + l: 0 + } + ); + + // TEST + // show :: a -> String + const show = x => JSON.stringify(x, null, 2); + + return show( + [100000, 1000000, 10000000].map(longestBelow) + ); +})(); diff --git a/Task/Hailstone-sequence/jq/hailstone-sequence-1.jq b/Task/Hailstone-sequence/Jq/hailstone-sequence-1.jq similarity index 100% rename from Task/Hailstone-sequence/jq/hailstone-sequence-1.jq rename to Task/Hailstone-sequence/Jq/hailstone-sequence-1.jq diff --git a/Task/Hailstone-sequence/jq/hailstone-sequence-2.jq b/Task/Hailstone-sequence/Jq/hailstone-sequence-2.jq similarity index 100% rename from Task/Hailstone-sequence/jq/hailstone-sequence-2.jq rename to Task/Hailstone-sequence/Jq/hailstone-sequence-2.jq diff --git a/Task/Hailstone-sequence/jq/hailstone-sequence-3.jq b/Task/Hailstone-sequence/Jq/hailstone-sequence-3.jq similarity index 100% rename from Task/Hailstone-sequence/jq/hailstone-sequence-3.jq rename to Task/Hailstone-sequence/Jq/hailstone-sequence-3.jq diff --git a/Task/Hailstone-sequence/Liberty-BASIC/hailstone-sequence.liberty b/Task/Hailstone-sequence/Liberty-BASIC/hailstone-sequence.liberty deleted file mode 100644 index 8f487d6014..0000000000 --- a/Task/Hailstone-sequence/Liberty-BASIC/hailstone-sequence.liberty +++ /dev/null @@ -1,52 +0,0 @@ -print "Part 1: Create a routine to generate the hailstone sequence for a number." -print "" -while hailstone < 1 or hailstone <> int(hailstone) - input "Please enter a positive integer: "; hailstone -wend -print "" -print "The following is the 'Hailstone Sequence' for your number..." -print "" -print hailstone -while hailstone <> 1 - if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 - print hailstone -wend -print "" -input "Hit 'Enter' to continue to part 2...";dummy$ -cls -print "Part 2: Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1." -print "" -print "No. in Seq.","Hailstone Sequence Number for 27" -print "" -c = 1: hailstone = 27 -print c, hailstone -while hailstone <> 1 - c = c + 1 - if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 - print c, hailstone -wend -print "" -input "Hit 'Enter' to continue to part 3...";dummy$ -cls -print "Part 3: Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.(But don't show the actual sequence)!" -print "" -print "Calculating result... Please wait... This could take a little while..." -print "" -print "Percent Done", "Start Number", "Seq. Length", "Maximum Sequence So Far" -print "" -for cc = 1 to 99999 - hailstone = cc: c = 1 - while hailstone <> 1 - c = c + 1 - if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 - wend - if c > max then max = c: largesthailstone = cc - locate 1, 7 - print " " - locate 1, 7 - print using("###.###", cc / 99999 * 100);"%", cc, c, max - scan -next cc -print "" -print "The number less than 100,000 with the longest 'Hailstone Sequence' is "; largesthailstone;". It's sequence length is "; max;"." -end diff --git a/Task/Hailstone-sequence/MATLAB/hailstone-sequence-1.m b/Task/Hailstone-sequence/MATLAB/hailstone-sequence-1.m index b818b3ce74..4e902d3483 100644 --- a/Task/Hailstone-sequence/MATLAB/hailstone-sequence-1.m +++ b/Task/Hailstone-sequence/MATLAB/hailstone-sequence-1.m @@ -1,19 +1,11 @@ - function x = hailstone(n) - % iterative definition - global VERBOSE; - x = 1; - while (1) - if VERBOSE, - printf('%i ',n); % print element - end; - - if n==1, - return; - elseif mod(n,2), - n = 3*n+1; - else - n = n/2; - end; - x = x + 1; - end; - end; +function x = hailstone(n) + x = n; + while n > 1 + % faster than mod(n, 2) + if n ~= floor(n / 2) * 2 + n = n * 3 + 1; + else + n = n / 2; + end + x(end + 1) = n; %#ok + end diff --git a/Task/Hailstone-sequence/MATLAB/hailstone-sequence-2.m b/Task/Hailstone-sequence/MATLAB/hailstone-sequence-2.m index 0a9d613d13..c5084fd9b1 100644 --- a/Task/Hailstone-sequence/MATLAB/hailstone-sequence-2.m +++ b/Task/Hailstone-sequence/MATLAB/hailstone-sequence-2.m @@ -1,4 +1,2 @@ - global VERBOSE; - VERBOSE = 1; % display of sequence elements turned on - N = hailstone(27); %display sequence - printf('\n\n%i\n',N); % +x = hailstone(27); +fprintf('hailstone(27): %d %d %d %d ... %d %d %d %d\nnumber of elements: %d\n', x(1:4), x(end-3:end), numel(x)) diff --git a/Task/Hailstone-sequence/MATLAB/hailstone-sequence-3.m b/Task/Hailstone-sequence/MATLAB/hailstone-sequence-3.m index ecc946b2f7..0539114b0d 100644 --- a/Task/Hailstone-sequence/MATLAB/hailstone-sequence-3.m +++ b/Task/Hailstone-sequence/MATLAB/hailstone-sequence-3.m @@ -1,8 +1,9 @@ - global VERBOSE; - VERBOSE = 0; % display of sequence elements turned off - N = 100000; - M = zeros(N,1); - for k=1:N, - M(k) = hailstone(k); %display sequence - end; - [maxLength, n] = max(M) +N = 1e5; +maxLen = 0; +for k = 1:N + kLen = numel(hailstone(k)); + if kLen > maxLen + maxLen = kLen; + n = k; + end +end diff --git a/Task/Hailstone-sequence/MATLAB/hailstone-sequence-4.m b/Task/Hailstone-sequence/MATLAB/hailstone-sequence-4.m new file mode 100644 index 0000000000..b887c2c67d --- /dev/null +++ b/Task/Hailstone-sequence/MATLAB/hailstone-sequence-4.m @@ -0,0 +1,18 @@ +function [n, maxLen] = longestHailstone(N) + maxLen = 0; + for k = 1:N + a = k; + kLen = 1; + while a > 1 + if a ~= floor(a / 2) * 2 + a = a * 3 + 1; + else + a = a / 2; + end + kLen = kLen + 1; + end + if kLen > maxLen + maxLen = kLen; + n = k; + end + end diff --git a/Task/Hailstone-sequence/MATLAB/hailstone-sequence-5.m b/Task/Hailstone-sequence/MATLAB/hailstone-sequence-5.m new file mode 100644 index 0000000000..f6474ec650 --- /dev/null +++ b/Task/Hailstone-sequence/MATLAB/hailstone-sequence-5.m @@ -0,0 +1,3 @@ +>> [n, maxLen] = longestHailstone(1e5) +n = 77031 +maxLen = 351 diff --git a/Task/Hailstone-sequence/MATLAB/hailstone-sequence-6.m b/Task/Hailstone-sequence/MATLAB/hailstone-sequence-6.m new file mode 100644 index 0000000000..2ae29c7b18 --- /dev/null +++ b/Task/Hailstone-sequence/MATLAB/hailstone-sequence-6.m @@ -0,0 +1,22 @@ +function [n, maxLen] = longestHailstone(N) + lenList(N) = 0; + lenList(1) = 1; + maxLen = 0; + for k = 2:N + a = k; + kLen = 0; + while a >= k + if a == floor(a / 2) * 2 + a = a / 2; + else + a = a * 3 + 1; + end + kLen = kLen + 1; + end + kLen = kLen + lenList(a); + lenList(k) = kLen; + if kLen > maxLen + maxLen = kLen; + n = k; + end + end diff --git a/Task/Hailstone-sequence/MATLAB/hailstone-sequence-7.m b/Task/Hailstone-sequence/MATLAB/hailstone-sequence-7.m new file mode 100644 index 0000000000..f6474ec650 --- /dev/null +++ b/Task/Hailstone-sequence/MATLAB/hailstone-sequence-7.m @@ -0,0 +1,3 @@ +>> [n, maxLen] = longestHailstone(1e5) +n = 77031 +maxLen = 351 diff --git a/Task/Hailstone-sequence/OoRexx/hailstone-sequence.rexx b/Task/Hailstone-sequence/OoRexx/hailstone-sequence.rexx new file mode 100644 index 0000000000..11de00d9ed --- /dev/null +++ b/Task/Hailstone-sequence/OoRexx/hailstone-sequence.rexx @@ -0,0 +1,27 @@ +sequence = hailstone(27) +say "Hailstone sequence for 27 has" sequence~items "elements and is ["sequence~toString('l', ", ")"]" + +highestNumber = 1 +highestCount = 1 + +loop i = 2 to 100000 + sequence = hailstone(i) + count = sequence~items + if count > highestCount then do + highestNumber = i + highestCount = count + end +end +say "Number" highestNumber "has the longest sequence with" highestCount "elements" + +-- short routine to generate a hailstone sequence +::routine hailstone + use arg n + + sequence = .array~of(n) + loop while n \= 1 + if n // 2 == 0 then n = n / 2 + else n = 3 * n + 1 + sequence~append(n) + end + return sequence diff --git a/Task/Hailstone-sequence/OxygenBasic/hailstone-sequence.oxy b/Task/Hailstone-sequence/OxygenBasic/hailstone-sequence.oxy deleted file mode 100644 index d8536360e3..0000000000 --- a/Task/Hailstone-sequence/OxygenBasic/hailstone-sequence.oxy +++ /dev/null @@ -1,37 +0,0 @@ -function Hailstone(sys *n) -'========================= -if n and 1 - n=n*3+1 -else - n=n>>1 -end if -end function - -function HailstoneSequence(sys n) as sys -'======================================= -count=1 -do - Hailstone n - Count++ - if n=1 then exit do -end do -return count -end function - -'MAIN -'==== - -maxc=0 -maxn=0 -e=100000 -for n=1 to e - c=HailstoneSequence n - if c>maxc - maxc=c - maxn=n - end if -next - -print e ", " maxn ", " maxc - -'result 100000, 77031, 351 diff --git a/Task/Hailstone-sequence/PlainTeX/hailstone-sequence.tex b/Task/Hailstone-sequence/PlainTeX/hailstone-sequence.tex new file mode 100644 index 0000000000..70f4a6d17e --- /dev/null +++ b/Task/Hailstone-sequence/PlainTeX/hailstone-sequence.tex @@ -0,0 +1,37 @@ +\newif\ifprint +\newcount\itercount +\newcount\currentnum +\def\hailstone#1{\itercount=0 \currentnum=#1 \hailstoneaux} +\def\hailstoneaux{% + \advance\itercount1 + \ifprint\number\currentnum\space\space\fi + \ifnum\currentnum>1 + \ifodd\currentnum + \multiply\currentnum3 \advance\currentnum1 + \else + \divide\currentnum2 + \fi + \expandafter\hailstoneaux + \fi +} + +\parindent=0pt +\printtrue\hailstone{27} +Length = \number\itercount +\bigbreak + +\newcount\ii \ii=1 +\printfalse +\def\lenmax{0} +\def\seed{0} +\loop + \ifnum\ii<100000 + \hailstone\ii + \ifnum\itercount>\lenmax\relax + \edef\lenmax{\number\itercount}% + \edef\seed{\number\ii}% + \fi + \advance\ii1 +\repeat +Seed max = \seed, length = \lenmax +\bye diff --git a/Task/Hailstone-sequence/PureBasic/hailstone-sequence.purebasic b/Task/Hailstone-sequence/PureBasic/hailstone-sequence.purebasic deleted file mode 100644 index 76de11443f..0000000000 --- a/Task/Hailstone-sequence/PureBasic/hailstone-sequence.purebasic +++ /dev/null @@ -1,48 +0,0 @@ -NewList Hailstones.i() ; Make a linked list to use as we do not know the numbers of elements needed for an Array - -Procedure.i FillHailstones(n) ; Fills the list & returns the amount of elements in the list - Shared Hailstones() ; Get access to the Hailstones-List - ClearList(Hailstones()) ; Remove old data - Repeat - AddElement(Hailstones()) ; Add an element to the list - Hailstones()=n ; Fill current value in the new list element - If n=1 - ProcedureReturn ListSize(Hailstones()) - ElseIf n%2=0 - n/2 - Else - n=(3*n)+1 - EndIf - ForEver -EndProcedure - -If OpenConsole() - Define i, l, maxl, maxi - l=FillHailstones(27) - Print("#27 has "+Str(l)+" elements and the sequence is: "+#CRLF$) - ForEach Hailstones() - If i=6 - Print(#CRLF$) - i=0 - EndIf - i+1 - Print(RSet(Str(Hailstones()),5)) - If Hailstones()<>1 - Print(", ") - EndIf - Next - - i=1 - Repeat - l=FillHailstones(i) - If l>maxl - maxl=l - maxi=i - EndIf - i+1 - Until i>=100000 - Print(#CRLF$+#CRLF$+"The longest sequence below 100000 is #"+Str(maxi)+", and it has "+Str(maxl)+" elements.") - - Print(#CRLF$+#CRLF$+"Press ENTER to exit."): Input() - CloseConsole() -EndIf diff --git a/Task/Hailstone-sequence/R/hailstone-sequence-1.r b/Task/Hailstone-sequence/R/hailstone-sequence-1.r deleted file mode 100644 index 7fce19013e..0000000000 --- a/Task/Hailstone-sequence/R/hailstone-sequence-1.r +++ /dev/null @@ -1,34 +0,0 @@ -### PART 1: -makeHailstone <- function(n){ - hseq <- n - while (hseq[length(hseq)] > 1){ - current.value <- hseq[length(hseq)] - if (current.value %% 2 == 0){ - next.value <- current.value / 2 - } else { - next.value <- (3 * current.value) + 1 - } - hseq <- append(hseq, next.value) - } - return(list(hseq=hseq, seq.length=length(hseq))) -} - -### PART 2: -twenty.seven <- makeHailstone(27) -twenty.seven$hseq -twenty.seven$seq.length - -### PART 3: -max.length <- 0; lower.bound <- 1; upper.bound <- 100000 - -for (index in lower.bound:upper.bound){ - current.hseq <- makeHailstone(index) - if (current.hseq$seq.length > max.length){ - max.length <- current.hseq$seq.length - max.index <- index - } -} - -cat("Between ", lower.bound, " and ", upper.bound, ", the input of ", - max.index, " gives the longest hailstone sequence, which has length ", - max.length, ". \n", sep="") diff --git a/Task/Hailstone-sequence/R/hailstone-sequence-2.r b/Task/Hailstone-sequence/R/hailstone-sequence-2.r deleted file mode 100644 index e897d84759..0000000000 --- a/Task/Hailstone-sequence/R/hailstone-sequence-2.r +++ /dev/null @@ -1,15 +0,0 @@ -> twenty.seven$hseq - [1] 27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 - [16] 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 - [31] 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 - [46] 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 - [61] 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 - [76] 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 - [91] 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 -[106] 10 5 16 8 4 2 1 - -> twenty.seven$seq.length -[1] 112 - -Between 1 and 1e+05, the input of 77031 gives the longest hailstone sequence, -which has length 351. diff --git a/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx b/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx index 0ee9ad1658..4291b2db38 100644 --- a/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx +++ b/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx @@ -1,7 +1,7 @@ /*REXX program tests a number and also a range for hailstone (Collatz) sequences. */ !.=0; !.0=1; !.2=1; !.4=1; !.6=1; !.8=1 /*assign even numerals to be "true". */ numeric digits 20; @.=0 /*handle big numbers; initialize array.*/ -parse arg x y z .; !.h=y /*get optional arguments from the C,L. */ +parse arg x y z .; !.h=y /*get optional arguments from the C.L. */ if x=='' | x=="," then x= 27 /*No 1st argument? Then use default.*/ if y=='' | y=="," then y=100000 - 1 /* " 2nd " " " " */ if z=='' | z=="," then z= 12 /*head/tail number? " " " */ @@ -24,7 +24,7 @@ hailstone: procedure expose @. !. hm; parse arg n 1 s 1 o,@.1 /*N,S,O: are the do while @.n==0 /*loop while the residual is unknown. */ parse var n '' -1 L /*extract the last decimal digit of N.*/ if !.L then n=n%2 /*N is even? Then calculate fast ÷ */ - else n=n*3 + 1 /*? ? odd ? Then calculate 3*n + 1 */ + else n=n*3 + 1 /*" " odd ? " " 3*n + 1 */ s=s n /* [↑] %: is the REXX integer division*/ end /*while*/ /* [↑] append N to the sequence list*/ s=s @.n /*append the number to a sequence list.*/ diff --git a/Task/Hailstone-sequence/Sidef/hailstone-sequence.sidef b/Task/Hailstone-sequence/Sidef/hailstone-sequence.sidef index 4979c2768b..aa6f8054d8 100644 --- a/Task/Hailstone-sequence/Sidef/hailstone-sequence.sidef +++ b/Task/Hailstone-sequence/Sidef/hailstone-sequence.sidef @@ -1,24 +1,24 @@ func hailstone (n) { - var sequence = [n]; + var sequence = [n] while (n > 1) { - sequence.append( - n.is_even ? n.div!(2) - : n.mul!(3).add!(1) - ); + sequence << ( + n.is_even ? n.div!(2) +  : n.mul!(3).add!(1) + ) } - return(sequence); + return(sequence) } - +  # The hailstone sequence for the number 27 -var arr = hailstone(var nr = 27); -say "#{nr}: #{arr.first(4).to_s} ... #{arr.last(4).to_s} (#{arr.len})"; - +var arr = hailstone(var nr = 27) +say "#{nr}: #{arr.first(4)} ... #{arr.last(4)} (#{arr.len})" +  # The longest hailstone sequence for a number less than 100,000 -var h = [0, 0]; -99_999.times { |i| +var h = [0, 0] +for i (1 .. 99_999) { (var l = hailstone(i).len) > h[1] && ( - h = [i, l]; - ); + h = [i, l] + ) } - -printf("%d: (%d)\n", h...); +  +printf("%d: (%d)\n", h...) diff --git a/Task/Hailstone-sequence/Zkl/hailstone-sequence-1.zkl b/Task/Hailstone-sequence/Zkl/hailstone-sequence-1.zkl new file mode 100644 index 0000000000..7df9a4e53e --- /dev/null +++ b/Task/Hailstone-sequence/Zkl/hailstone-sequence-1.zkl @@ -0,0 +1,2 @@ +fcn collatz(n,z=L()){ z.append(n); if(n==1) return(z); + if(n.isEven) return(self.fcn(n/2,z)); return(self.fcn(n*3+1,z)) } diff --git a/Task/Hailstone-sequence/Zkl/hailstone-sequence-2.zkl b/Task/Hailstone-sequence/Zkl/hailstone-sequence-2.zkl new file mode 100644 index 0000000000..c7097beaa1 --- /dev/null +++ b/Task/Hailstone-sequence/Zkl/hailstone-sequence-2.zkl @@ -0,0 +1,4 @@ +[2..0d100_000].pump(Void, // loop n from 2 to 100,000 + collatz, // generate Collatz sequence(n) + fcn(c,n){ // if new longest sequence, save length/C, return longest + if(c.len()>n[0]) n.clear(c.len(),c[0]); n}.fp1(L(0,0))) diff --git a/Task/Hamming-numbers/360-Assembly/hamming-numbers.360 b/Task/Hamming-numbers/360-Assembly/hamming-numbers.360 new file mode 100644 index 0000000000..96f9ee5704 --- /dev/null +++ b/Task/Hamming-numbers/360-Assembly/hamming-numbers.360 @@ -0,0 +1,108 @@ +* Hamming numbers 12/03/2017 +HAM CSECT + USING HAM,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + LA R6,1 ii=1 + DO WHILE=(C,R6,LE,=F'20') do ii=1 to 20 + BAL R14,PRTHAM call prtham + LA R6,1(R6) ii++ + ENDDO , enddo ii + LA R6,1691 ii=1691 + BAL R14,PRTHAM call prtham + L R13,4(0,R13) restore previous savearea pointer + LM R14,R12,12(R13) restore previous context + XR R15,R15 rc=0 + BR R14 exit +PRTHAM EQU * ---- prtham + ST R14,R14PRT save return addr + LR R1,R6 ii + XDECO R1,XDEC edit + MVC PG+2(4),XDEC+8 output ii + LR R1,R6 ii + BAL R14,HAMMING call hamming(ii) + XDECO R0,XDEC edit + MVC PG+8(10),XDEC+2 output hamming(ii) + XPRNT PG,L'PG print buffer + L R14,R14PRT restore return addr + BR R14 ---- return +HAMMING EQU * ---- hamming(ll) + ST R14,R14HAM save return addr + ST R1,LL ll + MVC HH,=F'1' h(1)=1 + SR R0,R0 0 + ST R0,I i=0 + ST R0,J j=0 + ST R0,K k=0 + MVC X2,=F'2' x2=2 + MVC X3,=F'3' x3=3 + MVC X5,=F'5' x5=5 + LA R7,1 n=1 + L R2,LL ll + BCTR R2,0 -1 + ST R2,LLM1 ll-1 + DO WHILE=(C,R7,LE,LLM1) do n=1 to ll-1 + L R4,X2 m=x2 + IF C,R4,GT,X3 THEN if m>x3 then + L R4,X3 m=x3 + ENDIF , endif + IF C,R4,GT,X5 THEN if m>x5 then + L R4,X5 m=x5 + ENDIF , endif + LR R1,R7 n + SLA R1,2 *4 + ST R4,HH(R1) h(n+1)=m + IF C,R4,EQ,X2 THEN if m=x2 then + L R1,I i + LA R1,1(R1) i+1 + ST R1,I i=i+1 + SLA R1,2 *4 + L R2,HH(R1) h(i+1) + MH R2,=H'2' *2 + ST R2,X2 x2=2*h(i+1) + ENDIF , endif + IF C,R4,EQ,X3 THEN if m=x3 then + L R1,J j + LA R1,1(R1) j+1 + ST R1,J j=j+1 + SLA R1,2 *4 + L R2,HH(R1) h(j+1) + MH R2,=H'3' *3 + ST R2,X3 x3=3*h(j+1) + ENDIF , endif + IF C,R4,EQ,X5 THEN if m=x5 then + L R1,K k + LA R1,1(R1) k+1 + ST R1,K k=k+1 + SLA R1,2 *4 + L R2,HH(R1) h(k+1) + MH R2,=H'5' *5 + ST R2,X5 x5=5*h(k+1) + ENDIF , endif + LA R7,1(R7) n++ + ENDDO , enddo n + L R1,LL ll + SLA R1,2 *4 + L R0,HH-4(R1) return h(ll) + L R14,R14HAM restore return addr + BR R14 ---- return +R14HAM DS A return addr of hamming +R14PRT DS A return addr of print +LL DS F ll +LLM1 DS F ll-1 +I DS F i +J DS F j +K DS F k +X2 DS F x2 +X3 DS F x3 +X5 DS F x5 +PG DC CL80'H(xxxx)=xxxxxxxxxx' +XDEC DS CL12 temp + LTORG positioning literal pool +HH DS 1691F array h(1691) + YREGS + END HAM diff --git a/Task/Hamming-numbers/ALGOL-W/hamming-numbers.alg b/Task/Hamming-numbers/ALGOL-W/hamming-numbers.alg new file mode 100644 index 0000000000..88365def89 --- /dev/null +++ b/Task/Hamming-numbers/ALGOL-W/hamming-numbers.alg @@ -0,0 +1,41 @@ +begin + % returns the minimum of a and b % + integer procedure min ( integer value a, b ) ; if a < b then a else b; + % find and print Hamming Numbers % + % Algol W only supports 32-bit integers so we just find % + % the 1691 32-bit Hamming Numbers % + integer MAX_HAMMING; + MAX_HAMMING := 1691; + begin + integer array H( 1 :: MAX_HAMMING ); + integer p2, p3, p5, last2, last3, last5; + H( 1 ) := 1; + last2 := last3 := last5 := 1; + p2 := 2; + p3 := 3; + p5 := 5; + for hPos := 2 until MAX_HAMMING do begin + integer m; + % the next Hamming number is the lowest of the next multiple of 2, 3, and 5 % + m := min( min( p2, p3 ), p5 ); + H( hPos ) := m; + if m = p2 then begin + last2 := last2 + 1; + p2 := 2 * H( last2 ) + end if_used_power_of_2 ; + if m = p3 then begin + last3 := last3 + 1; + p3 := 3 * H( last3 ) + end if_used_power_of_3 ; + if m = p5 then begin + last5 := last5 + 1; + p5 := 5 * H( last5 ) + end if_used_power_of_5 ; + end for_hPos ; + i_w := 1; + s_w := 1; + write( H( 1 ) ); + for i := 2 until 20 do writeon( H( i ) ); + write( H( MAX_HAMMING ) ) + end +end. diff --git a/Task/Hamming-numbers/Bc/hamming-numbers.bc b/Task/Hamming-numbers/Bc/hamming-numbers.bc new file mode 100644 index 0000000000..2e895ae94c --- /dev/null +++ b/Task/Hamming-numbers/Bc/hamming-numbers.bc @@ -0,0 +1,30 @@ +cat hamming_numbers.bc +define min(x,y) { + if (x < y) { + return x + } else { + return y + } +} +define hamming(limit) { + i = 0 + j = 0 + k = 0 + h[0] = 1 + x2 = 2 + x3 = 3 + x5 = 5 + for (n=1; n<=limit; n++) { + h[n] = min(x2,min(x3,x5)) + if (h[n] == x2) { x2 = 2 * h[++i] } + if (h[n] == x3) { x3 = 3 * h[++j] } + if (h[n] == x5) { x5 = 5 * h[++k] } + } + return (h[limit-1]) +} +for (lab=1; lab<=20; lab++) { + hamming(lab) +} +hamming(1691) +hamming(1000000) +quit diff --git a/Task/Hamming-numbers/C++/hamming-numbers-4.cpp b/Task/Hamming-numbers/C++/hamming-numbers-4.cpp new file mode 100644 index 0000000000..6c61c1a12c --- /dev/null +++ b/Task/Hamming-numbers/C++/hamming-numbers-4.cpp @@ -0,0 +1,96 @@ +#include +#include +#include +#include +#include + +template +class Lazy { +public: + T _v; +private: + std::function _f; + +public: + explicit Lazy(std::function thnk) + : _v(T()), _f(thnk) {}; + T value() { // not thread safe! + if (this->_f != nullptr) { + this->_v = this->_f(); + this->_f = nullptr; + } + return this->_v; + } +}; + +template +class LazyList { +public: + T head; + std::shared_ptr>> tail; + LazyList(): head(T()) {} // only used in initializing Lazy... + LazyList(T head, std::function()> thnk) + : head(head), tail(std::make_shared>>(thnk)) {} + // default Copy/Move constructors and assignment operators seem to work well enough + bool isEmpty() { return this->tail == nullptr; } +}; + +typedef std::shared_ptr PBI; +typedef LazyList LL; +typedef std::function FLL2LL; + +LL merge(LL a, LL b) { + auto ha = a.head; auto hb = b.head; + if (*ha < *hb) { + return LL(ha, [=]() { return merge(a.tail->value(), b); }); + } else { + return LL(hb, [=]() { return merge(a, b.tail->value()); }); + } +} + +LL smult(int m, LL s) { + const auto im = mpz_class(m); + const auto psmlt = + std::make_shared([](LL ss) { return ss; }); + *psmlt = [=](LL ss) { + return LL(std::make_shared(*ss.head * im), + [=]() { return (*psmlt)(ss.tail->value()); }); + }; + return (*psmlt)(s); // worker wrapper pattern with recursive closure as worker... +} + +LL u(LL s, int n) { + const auto r = std::make_shared(LL()); // interior mutable... + *r = smult(n, LL(std::make_shared(1), [=]() { return *r; })); + if (!s.isEmpty()) { *r = merge(s, *r); } + return *r; +} + +LL hammings() { + auto r = LL(); + for (auto pn : std::vector({5, 3, 2})) { + r = u(r, pn); + } + return LL(std::make_shared(1), [=]() { return r; }); +} + +int main() { + auto hmgs = hammings(); + for (auto i = 0; i < 20; ++i) { + std::cout << *hmgs.head << " "; + hmgs = hmgs.tail->value(); + } + std::cout << "\n"; + + hmgs = hammings(); + for (auto i = 1; i < 1691; ++i) hmgs = hmgs.tail->value(); + std::cout << *hmgs.head << "\n"; + + auto start = std::chrono::steady_clock::now(); + hmgs = hammings(); + for (auto i = 1; i < 1000000; ++i) hmgs = hmgs.tail->value(); + auto stop = std::chrono::steady_clock::now(); + + auto ms = std::chrono::duration_cast(stop - start); + std::cout << *hmgs.head << " in " << ms.count() << "milliseconds.\n"; +} diff --git a/Task/Hamming-numbers/C++/hamming-numbers-5.cpp b/Task/Hamming-numbers/C++/hamming-numbers-5.cpp new file mode 100644 index 0000000000..4837c2c828 --- /dev/null +++ b/Task/Hamming-numbers/C++/hamming-numbers-5.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +#include + +class Hammings { +private: + const mpz_class _two = 2, _three = 3, _five = 5; + std::vector _m = {}, _h = {1}; + mpz_class _x5 = 5, _x53 = 9, _mrg = 3, _x532 = 2; + int _i = 1, _j = 0; +public: + Hammings() {_m.reserve(65536); _h.reserve(65536); }; + bool operator!=(const Hammings& other) const { return true; } + Hammings begin() const { return *this; } + Hammings end() const { return *this; } + mpz_class operator*() { return _h.back(); } + const Hammings& operator++() { + if (_i > _h.capacity() / 2) { + _h.erase(_h.begin(), _h.begin() + _i); + _i = 0; + } + if (_x532 < _mrg) { + _h.push_back(_x532); + _x532 = _h[_i++] * _two; + } else { + _h.push_back(_mrg); + if (_x53 < _x5) { + _mrg = _x53; + _x53 = _m[_j++] * _three; + } else { + _mrg = _x5; + _x5 = _x5 * _five; + } + if (_j > _m.capacity() / 2) { + _m.erase(_m.begin(), _m.begin() + _j); + _j = 0; + } + _m.push_back(_mrg); + } + return *this; + } +}; + +int main() { + auto cnt = 1; + for (auto hmg : Hammings()) { + if (cnt <= 20) std::cout << hmg << " "; + if (cnt == 20) std::cout << "\n"; + if (cnt++ >= 1691) { + std::cout << hmg << "\n"; + break; + } + } + + auto start = std::chrono::steady_clock::now(); + hmgs = hammings(); + auto&& hmgitr = Hammings(); + for (auto i = 1; i < 1000000; ++i) ++hmgitr; + auto stop = std::chrono::steady_clock::now(); + + auto ms = std::chrono::duration_cast(stop - start); + std::cout << *hmgitr << " in " << ms.count() << "milliseconds.\n"; +} diff --git a/Task/Hamming-numbers/jq/hamming-numbers-1.jq b/Task/Hamming-numbers/Jq/hamming-numbers-1.jq similarity index 100% rename from Task/Hamming-numbers/jq/hamming-numbers-1.jq rename to Task/Hamming-numbers/Jq/hamming-numbers-1.jq diff --git a/Task/Hamming-numbers/jq/hamming-numbers-2.jq b/Task/Hamming-numbers/Jq/hamming-numbers-2.jq similarity index 100% rename from Task/Hamming-numbers/jq/hamming-numbers-2.jq rename to Task/Hamming-numbers/Jq/hamming-numbers-2.jq diff --git a/Task/Hamming-numbers/jq/hamming-numbers-3.jq b/Task/Hamming-numbers/Jq/hamming-numbers-3.jq similarity index 100% rename from Task/Hamming-numbers/jq/hamming-numbers-3.jq rename to Task/Hamming-numbers/Jq/hamming-numbers-3.jq diff --git a/Task/Hamming-numbers/jq/hamming-numbers-4.jq b/Task/Hamming-numbers/Jq/hamming-numbers-4.jq similarity index 100% rename from Task/Hamming-numbers/jq/hamming-numbers-4.jq rename to Task/Hamming-numbers/Jq/hamming-numbers-4.jq diff --git a/Task/Hamming-numbers/Kotlin/hamming-numbers-1.kotlin b/Task/Hamming-numbers/Kotlin/hamming-numbers-1.kotlin index a877d96348..b26a0cf663 100644 --- a/Task/Hamming-numbers/Kotlin/hamming-numbers-1.kotlin +++ b/Task/Hamming-numbers/Kotlin/hamming-numbers-1.kotlin @@ -1,13 +1,13 @@ import java.math.BigInteger -import java.util.PriorityQueue +import java.util.* -val Three = BigInteger.valueOf(3) -val Five = BigInteger.valueOf(5) +val Three = BigInteger.valueOf(3)!! +val Five = BigInteger.valueOf(5)!! fun updateFrontier(x : BigInteger, pq : PriorityQueue) { - pq add(x shiftLeft(1)) - pq add(x multiply(Three)) - pq add(x multiply(Five)) + pq.add(x.shiftLeft(1)) + pq.add(x.multiply(Three)) + pq.add(x.multiply(Five)) } fun hamming(n : Int) : BigInteger { @@ -16,7 +16,7 @@ fun hamming(n : Int) : BigInteger { var lowest = BigInteger.ONE for (i in 1 .. n-1) { lowest = frontier.poll() ?: lowest - while (frontier.peek() equals(lowest)) + while (frontier.peek() == lowest) frontier.poll() updateFrontier(lowest, frontier) } @@ -24,9 +24,9 @@ fun hamming(n : Int) : BigInteger { } fun main(args : Array) { - System.out print("Hamming(1 .. 20) =") + System.out.print("Hamming(1 .. 20) =") for (i in 1 .. 20) - System.out print(" ${hamming(i)}") - System.out println("\nHamming(1691) = ${hamming(1691)}") - System.out println("Hamming(1000000) = ${hamming(1000000)}") + System.out.print(" ${hamming(i)}") + System.out.println("\nHamming(1691) = ${hamming(1691)}") + System.out.println("Hamming(1000000) = ${hamming(1000000)}") } diff --git a/Task/Hamming-numbers/Kotlin/hamming-numbers-2.kotlin b/Task/Hamming-numbers/Kotlin/hamming-numbers-2.kotlin index 32971039fc..5fb010db7b 100644 --- a/Task/Hamming-numbers/Kotlin/hamming-numbers-2.kotlin +++ b/Task/Hamming-numbers/Kotlin/hamming-numbers-2.kotlin @@ -1,9 +1,9 @@ import java.math.BigInteger -import java.util.PriorityQueue +import java.util.* -val One = BigInteger.ONE -val Three = BigInteger.valueOf(3) -val Five = BigInteger.valueOf(5) +val One = BigInteger.ONE!! +val Three = BigInteger.valueOf(3)!! +val Five = BigInteger.valueOf(5)!! fun PriorityQueue.update(x: BigInteger) : PriorityQueue { add(x.shiftLeft(1)) diff --git a/Task/Hamming-numbers/Kotlin/hamming-numbers-3.kotlin b/Task/Hamming-numbers/Kotlin/hamming-numbers-3.kotlin index c7770ea7d5..12d69607a9 100644 --- a/Task/Hamming-numbers/Kotlin/hamming-numbers-3.kotlin +++ b/Task/Hamming-numbers/Kotlin/hamming-numbers-3.kotlin @@ -1,9 +1,9 @@ import java.math.BigInteger -import java.util.PriorityQueue +import java.util.* -val One = BigInteger.ONE -val Three = BigInteger.valueOf(3) -val Five = BigInteger.valueOf(5) +val One = BigInteger.ONE!! +val Three = BigInteger.valueOf(3)!! +val Five = BigInteger.valueOf(5)!! infix fun PriorityQueue.update(x: BigInteger) : PriorityQueue { add(x.shiftLeft(1)) diff --git a/Task/Hamming-numbers/Kotlin/hamming-numbers-4.kotlin b/Task/Hamming-numbers/Kotlin/hamming-numbers-4.kotlin index c8fd71c571..3fb6bd5e08 100644 --- a/Task/Hamming-numbers/Kotlin/hamming-numbers-4.kotlin +++ b/Task/Hamming-numbers/Kotlin/hamming-numbers-4.kotlin @@ -1,38 +1,38 @@ import java.math.BigInteger as BI data class LazyList(val head: T, val lztail: Lazy?>) { - fun toSequence() = generateSequence(this) { it.lztail.value } - .map { it.head } + fun toSequence() = generateSequence(this) { it.lztail.value } + .map { it.head } } fun hamming(): LazyList { - fun merge(s1: LazyList, s2: LazyList): LazyList { - val s1v = s1.head; val s2v = s2.head - if (s1v < s2v) { - return LazyList(s1v, lazy({->merge(s1.lztail.value!!, s2)})) - } else { - return LazyList(s2v, lazy({->merge(s1, s2.lztail.value!!)})) - } - } - fun llmult(m: BI, s: LazyList): LazyList { - fun llmlt(ss: LazyList): LazyList { - return LazyList(m * ss.head, lazy({->llmlt(ss.lztail.value!!)})) - } - return llmlt(s) - } - fun u(s: LazyList?, n: Long): LazyList { - var r: LazyList? = null // mutable nullable so can do the below - if (s == null) { // recursively referenced variables are ugly!!! - r = llmult(BI.valueOf(n), LazyList(BI.valueOf(1), lazy{ -> r })) - } else { // recursively referenced variables only work with lazy - r = merge(s, llmult(BI.valueOf(n), // or a loop race limit - LazyList(BI.valueOf(1), lazy{ -> r }))) - } - return r - } - val prms = arrayOf(5L, 3L, 2L) - val thunk = {->prms.fold?>(null, {s, n -> u(s,n)})!!} - return LazyList(BI.valueOf(1), lazy(thunk)) + fun merge(s1: LazyList, s2: LazyList): LazyList { + val s1v = s1.head; val s2v = s2.head + if (s1v < s2v) { + return LazyList(s1v, lazy({->merge(s1.lztail.value!!, s2)})) + } else { + return LazyList(s2v, lazy({->merge(s1, s2.lztail.value!!)})) + } + } + fun llmult(m: BI, s: LazyList): LazyList { + fun llmlt(ss: LazyList): LazyList { + return LazyList(m * ss.head, lazy({->llmlt(ss.lztail.value!!)})) + } + return llmlt(s) + } + fun u(s: LazyList?, n: Long): LazyList { + var r: LazyList? = null // mutable nullable so can do the below + if (s == null) { // recursively referenced variables are ugly!!! + r = llmult(BI.valueOf(n), LazyList(BI.valueOf(1), lazy{ -> r })) + } else { // recursively referenced variables only work with lazy + r = merge(s, llmult(BI.valueOf(n), // or a loop race limit + LazyList(BI.valueOf(1), lazy{ -> r }))) + } + return r + } + val prms = arrayOf(5L, 3L, 2L) + val thunk = {->prms.fold?>(null, {s, n -> u(s,n)})!!} + return LazyList(BI.valueOf(1), lazy(thunk)) } fun main(args: Array) { diff --git a/Task/Hamming-numbers/Phix/hamming-numbers-1.phix b/Task/Hamming-numbers/Phix/hamming-numbers-1.phix new file mode 100644 index 0000000000..5949737e05 --- /dev/null +++ b/Task/Hamming-numbers/Phix/hamming-numbers-1.phix @@ -0,0 +1,44 @@ +function hamming(integer N) +sequence h = repeat(1,N) +atom x2 = 2, x3 = 3, x5 = 5, hn +integer i = 1, j = 1, k = 1 + for n=2 to N do + hn = min(x2,min(x3,x5)) + h[n] = hn + if hn=x2 then i += 1 x2 = 2*h[i] end if + if hn=x3 then j += 1 x3 = 3*h[j] end if + if hn=x5 then k += 1 x5 = 5*h[k] end if + end for + return h[N] +end function + +include builtins\bigatom.e + +function ba_min(bigatom a, bigatom b) + return iff(ba_compare(a,b)<0?a:b) +end function + +function ba_hamming(integer N) +sequence h = repeat(ba_new(1),N) +bigatom x2 = ba_new(2), x3 = ba_new(3), x5 = ba_new(5), hn +integer i = 1, j = 1, k = 1 + for n=2 to N do + hn = ba_min(x2,ba_min(x3,x5)) + h[n] = hn + if ba_compare(hn,x2)=0 then i += 1 x2 = ba_multiply(2,h[i]) end if + if ba_compare(hn,x3)=0 then j += 1 x3 = ba_multiply(3,h[j]) end if + if ba_compare(hn,x5)=0 then k += 1 x5 = ba_multiply(5,h[k]) end if + end for + return h[N] +end function + +sequence s = {} +for i=1 to 20 do + s = append(s,hamming(i)) +end for +?s +?hamming(1691) +?{hamming(1000000),"wrong!"} + +?ba_sprintf("%B\n",ba_hamming(1691)) +?ba_sprintf("%B\n",ba_hamming(1000000)) diff --git a/Task/Hamming-numbers/Phix/hamming-numbers-2.phix b/Task/Hamming-numbers/Phix/hamming-numbers-2.phix new file mode 100644 index 0000000000..be52becb61 --- /dev/null +++ b/Task/Hamming-numbers/Phix/hamming-numbers-2.phix @@ -0,0 +1,52 @@ +-- numbers kept as {log,{pow2,pow3,pow5}}, +-- value is ~= exp(log), == (2^pow2)*(3^pow3)*(5^pow5) +enum LOG, POWS +enum POW2, POW3, POW5 + +function lnmin(sequence a, sequence b) + return iff(a[LOG] 500000) return(2.4496 , 0.0076); #-- empirical estimation + if(n > 50000) return(2.4424 , 0.0146); #-- correction, base 2 + if(n > 500) return(2.3948 , 0.0723); #-- (dist,width) + if(n > 1) return(2.2506 , 0.2887); #-- around (log $ sqrt 30), + return(2.2506 , 0.5771); #-- says WP +} + +fcn nthHam(n){ // -> (Double, (Int, Int, Int)) #-- n: 1-based: 1,2,3... + d,w := rngval(n); #-- correction dist, width + hi := estval(n.toFloat()) - d; #-- hi > logval > hi-w + c,b := band(hi,w); #-- total count, the band + s := b.sort(fcn(a,b){ a[0]>b[0] }); #-- sorted decreasing, result + m := c - n; #-- m 0-based from top + nb := b.len(); #-- |band| + res := s[m]; #-- result + + if(w >= 1) throw(Exception.Generic("Breach of contract: (w < 1): " + w)); + if(m < 0) throw(Exception.Generic("Not enough triples generated: " +c+n)); + if(m >= nb)throw(Exception.Generic("Generated band is too narrow: " +m+nb)); + return(res); +} + +fcn band(hi,w){ //--> #-- total count, the band + b := Sink(List); cnt := 0; + foreach k in ([0 .. (hi/lg5).floor()]){ p := lg5*k; + foreach j in ([0 .. ((hi-p)/lg3).floor()]){ q := lg3*j + p; + i,frac := (hi-q).modf(); r := hi-frac; #-- r = i + q + cnt+=(i+1); #-- total count + if(frac2^%d * 3^%d * 5^%d-->\n%s".fmt(n,i,j,k,h)); +} + +printHam(1691); //(5,12,3), 10 digits +printHam(0d1_000_000); //(55,47,64), 84 digits +printHam(0d10_000_000); //(80,92,162), 182 digits, 80 zeros at end +printHam(0d1_000_000_000); //(1334,335,404), 845 digits diff --git a/Task/Handle-a-signal/00DESCRIPTION b/Task/Handle-a-signal/00DESCRIPTION index 2ad9e31cd5..ec7fe7511d 100644 --- a/Task/Handle-a-signal/00DESCRIPTION +++ b/Task/Handle-a-signal/00DESCRIPTION @@ -10,13 +10,12 @@ {{omit from|Unlambda|Does not handle signals.}} {{omit from|XSLT}} -Most general purpose operating systems provide interrupt facilities, sometimes called signals. +Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal. - ;Task: -Provide a program that displays a single integer on each line of output at the rate of one integer in each half second. - -Upon receipt of the SigInt signal (often created by the user typing ctrl-C) the program will cease printing integers to its output, print the number of seconds the program has run, and then the program will terminate. +Provide a program that displays an integer on each line of output at the rate of about one per half second. + +Upon receipt of the SIGINT signal (often generated by the user typing ctrl-C ( or better yet, SIGQUIT ctrl-\ )) the program will cease outputting integers, output the number of seconds the program has run, and then the program will quit.

    diff --git a/Task/Handle-a-signal/BaCon/handle-a-signal.bacon b/Task/Handle-a-signal/BaCon/handle-a-signal.bacon new file mode 100644 index 0000000000..59ccd37f3a --- /dev/null +++ b/Task/Handle-a-signal/BaCon/handle-a-signal.bacon @@ -0,0 +1,14 @@ +' Handle signal +SUB Finished + SIGNAL SIG_DFL, SIGINT : ' Restore SIGINT to default + PRINT "Running for", TIMER / 1000.0, "seconds" FORMAT "%s %f %s\n" + STOP SIGINT : ' Send another terminating SIGINT +ENDSUB + +SIGNAL Finished, SIGINT +iter = 1 +WHILE TRUE + SLEEP 500 + PRINT iter + iter = iter + 1 +WEND diff --git a/Task/Handle-a-signal/Gambas/handle-a-signal.gambas b/Task/Handle-a-signal/Gambas/handle-a-signal.gambas new file mode 100644 index 0000000000..4d2b147e43 --- /dev/null +++ b/Task/Handle-a-signal/Gambas/handle-a-signal.gambas @@ -0,0 +1,31 @@ +hTimer As Timer +fTime As Float + +Public Sub Application_Signal(x As Integer) + +Print "Program stopped after " & fTime & " seconds" +Quit + +End + +Public Sub Main() + +hTimer = New Timer As "IntTimer" + +Print "Press [Ctrl] + " & Chr(92) & " to stop" + +Signal[Signal.SIGQUIT].Catch + +With hTimer + .Delay = 500 + .Start +End With + +End + +Public Sub IntTimer_Timer() + +Print Rand(0, 100) +fTime += 0.5 + +End diff --git a/Task/Handle-a-signal/Kotlin/handle-a-signal.kotlin b/Task/Handle-a-signal/Kotlin/handle-a-signal.kotlin new file mode 100644 index 0000000000..7a32528359 --- /dev/null +++ b/Task/Handle-a-signal/Kotlin/handle-a-signal.kotlin @@ -0,0 +1,22 @@ +// version 1.1.3 + +import sun.misc.Signal +import sun.misc.SignalHandler + +fun main(args: Array) { + val startTime = System.currentTimeMillis() + + Signal.handle(Signal("INT"), object : SignalHandler { + override fun handle(sig: Signal) { + val elapsedTime = (System.currentTimeMillis() - startTime) / 1000.0 + println("\nThe program has run for $elapsedTime seconds") + System.exit(0) + } + }) + + var i = 0 + while(true) { + println(i++) + Thread.sleep(500) + } +} diff --git a/Task/Handle-a-signal/Perl/handle-a-signal-1.pl b/Task/Handle-a-signal/Perl/handle-a-signal-1.pl deleted file mode 100644 index 033cb6521d..0000000000 --- a/Task/Handle-a-signal/Perl/handle-a-signal-1.pl +++ /dev/null @@ -1,8 +0,0 @@ -my $start = time; - -$SIG{INT} = sub - {print 'Ran for ', time - $start, " seconds.\n"; - exit;}; - -for (my $n = 0 ;; select(undef, undef, undef, .5)) - {print ++$n, "\n";} diff --git a/Task/Handle-a-signal/Perl/handle-a-signal-2.pl b/Task/Handle-a-signal/Perl/handle-a-signal-2.pl deleted file mode 100644 index c7c10c267b..0000000000 --- a/Task/Handle-a-signal/Perl/handle-a-signal-2.pl +++ /dev/null @@ -1,9 +0,0 @@ -use 5.010; -use AnyEvent; -my $start = AE::time; -my $exit = AE::cv; -my $int = AE::signal 'INT', $exit; -my $n; -my $num = AE::timer 0, 0.5, sub { say $n++ }; -$exit->recv; -say " interrupted after ", AE::time - $start, " seconds"; diff --git a/Task/Handle-a-signal/Perl/handle-a-signal.pl b/Task/Handle-a-signal/Perl/handle-a-signal.pl new file mode 100644 index 0000000000..7d0d89e0bd --- /dev/null +++ b/Task/Handle-a-signal/Perl/handle-a-signal.pl @@ -0,0 +1,63 @@ +my $start = time; # seconds since epohc +my $arlm=5; # every 5 seconds show how we're doing +my $i; + +$SIG{QUIT} = sub + {print " Ran for ", time - $start, " seconds.\n"; die; }; +$SIG{INT} = sub + {print " Running for ", time - $start, " seconds.\n"; }; +$SIG{ALRM} = sub + {print " After $arlm seconds i= $i. Executing for ", time - $start, " seconds.\n"; alarm $arlm }; + + +alarm $arlm; # trigger ALaRM after we've run for a while + +print " ^C to inerrupt, ^\\ to quit, takes a break at $arlm seconds \n"; + +while ( 1 ) { + for ( $w=11935000; $w--; $w>0 ){}; # spinning is bad, but hey it's only a demo + + print ( ++$i," \n"); + } + ^C to inerrupt, ^\ to quit, takes a break at 5 seconds +1 +2 +^C Running for 1 seconds. +3 +4 +^C Running for 2 seconds. +5 +6 +7 +^C Running for 3 seconds. +8 +9 +10 + After 5 seconds i= 10. Executing for 5 seconds. +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 + After 5 seconds i= 20. Executing for 10 seconds. +21 +22 +^\ Ran for 11 seconds. +Died at 0.pl line 6.. + + +This example does the required task: +use 5.010; +use AnyEvent; +my $start = AE::time; +my $exit = AE::cv; +my $int = AE::signal 'INT', $exit; +my $n; +my $num = AE::timer 0, 0.5, sub { say $n++ }; +$exit->recv; +say " interrupted after ", AE::time - $start, " seconds"; diff --git a/Task/Handle-a-signal/Zkl/handle-a-signal.zkl b/Task/Handle-a-signal/Zkl/handle-a-signal.zkl new file mode 100644 index 0000000000..e301685b52 --- /dev/null +++ b/Task/Handle-a-signal/Zkl/handle-a-signal.zkl @@ -0,0 +1,3 @@ +var t=Time.Clock.time; +try{ n:=0; while(1){(n+=1).println(); Atomic.sleep(0.5)} } +catch{ println("ran for ",Time.Clock.time-t," seconds"); System.exit() } diff --git a/Task/Happy-numbers/8th/happy-numbers.8th b/Task/Happy-numbers/8th/happy-numbers.8th new file mode 100644 index 0000000000..a2fddc3475 --- /dev/null +++ b/Task/Happy-numbers/8th/happy-numbers.8th @@ -0,0 +1,29 @@ +: until! "not while!" eval i; + +with: w +with: n + +: sumsqd \ n -- n + 0 swap repeat + 0; 10 /mod -rot sqr + swap + again ; + +: cycle \ n xt -- n + >r + dup r@ exec \ -- tortoise, hare + repeat + swap r@ exec + swap r@ exec r@ exec + 2dup = until! + rdrop drop ; + +: happy? ' sumsqd cycle 1 = ; + +: .happy \ n -- + 1 repeat + dup happy? if dup . space swap 1- swap then 1+ + over 0 > while! + 2drop cr ; + +;with +;with diff --git a/Task/Happy-numbers/AppleScript/happy-numbers-2.applescript b/Task/Happy-numbers/AppleScript/happy-numbers-2.applescript index 0595df944e..79f71bbf73 100644 --- a/Task/Happy-numbers/AppleScript/happy-numbers-2.applescript +++ b/Task/Happy-numbers/AppleScript/happy-numbers-2.applescript @@ -1,3 +1,5 @@ +-- HAPPY NUMBERS -------------------------------------------------------------- + -- isHappy :: Int -> Bool on isHappy(n) @@ -9,64 +11,62 @@ on isHappy(n) -- digitSquared :: Int -> Int -> Int script digitSquared - on lambda(a, x) + on |λ|(a, x) (a + (x as integer) ^ 2) as integer - end lambda + end |λ| end script - on lambda(n) + on |λ|(n) foldl(digitSquared, 0, splitOn("", n as string)) - end lambda + end |λ| end script -- [Int] -> Int -> Bool - on lambda(s, n) + on |λ|(s, n) if n = 1 then true else if s contains n then false else - lambda(s & n, lambda(n) of sumOfSquaredDigits) + |λ|(s & n, |λ|(n) of sumOfSquaredDigits) end if end if - end lambda + end |λ| end script - endsInOne's lambda({}, n) + endsInOne's |λ|({}, n) end isHappy - --- TEST +-- TEST ----------------------------------------------------------------------- on run -- seriesLength :: {n:Int, xs:[Int]} -> Bool script seriesLength property target : 8 - on lambda(rec) + on |λ|(rec) length of xs of rec = target of seriesLength - end lambda + end |λ| end script -- succTest :: {n:Int, xs:[Int]} -> {n:Int, xs:[Int]} script succTest - on lambda(rec) - set xs to xs of rec - set n to n of rec + on |λ|(rec) + tell rec to set {xs, n} to {its xs, its n} script testResult - on lambda(x) + on |λ|(x) if isHappy(x) then xs & x else xs end if - end lambda + end |λ| end script - {n:n + 1, xs:testResult's lambda(n)} - end lambda + {n:n + 1, xs:testResult's |λ|(n)} + end |λ| end script xs of |until|(seriesLength, succTest, {n:1, xs:{}}) @@ -75,8 +75,7 @@ on run end run - --- GENERIC FUNCTIONS +-- GENERIC FUNCTIONS ---------------------------------------------------------- -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) @@ -84,31 +83,23 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl --- until :: (a -> Bool) -> (a -> a) -> a -> a -on |until|(p, f, x) - set mp to mReturn(p) - set mf to mReturn(f) - - script - property p : mp's lambda - property f : mf's lambda - - on lambda(v) - repeat until p(v) - set v to f(v) - end repeat - return v - end lambda - end script - - result's lambda(x) -end |until| +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn -- splitOn :: Text -> Text -> [Text] on splitOn(strDelim, strMain) @@ -118,14 +109,15 @@ on splitOn(strDelim, strMain) return xs end splitOn --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn +-- until :: (a -> Bool) -> (a -> a) -> a -> a +on |until|(p, f, x) + set mp to mReturn(p) + set v to x + + tell mReturn(f) + repeat until mp's |λ|(v) + set v to |λ|(v) + end repeat + end tell + return v +end |until| diff --git a/Task/Happy-numbers/Dc/happy-numbers.dc b/Task/Happy-numbers/Dc/happy-numbers.dc new file mode 100644 index 0000000000..366e314cc4 --- /dev/null +++ b/Task/Happy-numbers/Dc/happy-numbers.dc @@ -0,0 +1,4 @@ +[lcI~rscd*+lc0_z8>s]dssx diff --git a/Task/Happy-numbers/Forth/happy-numbers.fth b/Task/Happy-numbers/Forth/happy-numbers-1.fth similarity index 100% rename from Task/Happy-numbers/Forth/happy-numbers.fth rename to Task/Happy-numbers/Forth/happy-numbers-1.fth diff --git a/Task/Happy-numbers/Forth/happy-numbers-2.fth b/Task/Happy-numbers/Forth/happy-numbers-2.fth new file mode 100644 index 0000000000..d69da0c52b --- /dev/null +++ b/Task/Happy-numbers/Forth/happy-numbers-2.fth @@ -0,0 +1,10 @@ +CREATE HAPPINESS 0 C, 1 C, 0 C, 0 C, 0 C, 0 C, 0 C, 1 C, 0 C, 0 C, +: next ( n -- n') + 0 swap BEGIN dup WHILE 10 /mod >r dup * + r> REPEAT drop ; +: happy? ( n -- t|f) + BEGIN dup 10 >= WHILE next REPEAT chars HAPPINESS + C@ 0<> ; +: happy-numbers ( n --) >r 0 + BEGIN r@ WHILE + BEGIN 1+ dup happy? UNTIL dup . r> 1- >r + REPEAT r> drop drop ; +8 happy-numbers diff --git a/Task/Happy-numbers/Forth/happy-numbers-3.fth b/Task/Happy-numbers/Forth/happy-numbers-3.fth new file mode 100644 index 0000000000..7f5be08074 --- /dev/null +++ b/Task/Happy-numbers/Forth/happy-numbers-3.fth @@ -0,0 +1,5 @@ +: happy-number ( n -- n') \ produce the nth happy number + >r 0 BEGIN r@ WHILE + BEGIN 1+ dup happy? UNTIL r> 1- >r + REPEAT r> drop ; +1000000 happy-number . \ 7105849 diff --git a/Task/Happy-numbers/Haskell/happy-numbers-1.hs b/Task/Happy-numbers/Haskell/happy-numbers-1.hs index d8fab6956a..497ee0e23e 100644 --- a/Task/Happy-numbers/Haskell/happy-numbers-1.hs +++ b/Task/Happy-numbers/Haskell/happy-numbers-1.hs @@ -3,9 +3,11 @@ import Data.Set (member, insert, empty) isHappy :: Integer -> Bool isHappy = p empty - where p _ 1 = True - p s n | n `member` s = False - | otherwise = p (insert n s) (f n) - f = sum . map ((^2) . toInteger . digitToInt) . show + where + p _ 1 = True + p s n + | n `member` s = False + | otherwise = p (insert n s) (f n) + f = sum . (((^ 2) . toInteger . digitToInt) <$>) . show -main = mapM_ print $ take 8 $ filter isHappy [1..] +main = mapM_ print $ take 8 $ filter isHappy [1 ..] diff --git a/Task/Happy-numbers/Haskell/happy-numbers-2.hs b/Task/Happy-numbers/Haskell/happy-numbers-2.hs index a3ae3c605e..b239b63882 100644 --- a/Task/Happy-numbers/Haskell/happy-numbers-2.hs +++ b/Task/Happy-numbers/Haskell/happy-numbers-2.hs @@ -1,10 +1,18 @@ import Data.Array -happy x = if xx <= 150 then seen!xx else happy xx where - xx = dsum x - seen :: Array Int Bool - seen = listArray (1,150) $ True:False:False:False:(map happy [5..150]) - dsum n | n < 10 = n * n - | otherwise = let (q,r) = n `divMod` 10 in r*r + dsum q +happy x = + if xx <= 150 + then seen ! xx + else happy xx + where + xx = dsum x + seen :: Array Int Bool + seen = + listArray (1, 150) $ True : False : False : False : (happy <$> [5 .. 150]) + dsum n + | n < 10 = n * n + | otherwise = + let (q, r) = n `divMod` 10 + in r * r + dsum q -main = print $ sum $ take 10000 $ filter happy [1..] +main = print $ sum $ take 10000 $ filter happy [1 ..] diff --git a/Task/Happy-numbers/JavaScript/happy-numbers-2.js b/Task/Happy-numbers/JavaScript/happy-numbers-2.js index c92ac25a78..9d443cf575 100644 --- a/Task/Happy-numbers/JavaScript/happy-numbers-2.js +++ b/Task/Happy-numbers/JavaScript/happy-numbers-2.js @@ -1,25 +1,60 @@ (() => { - 'use strict'; // isHappy :: Int -> Bool - function isHappy(n) { - let f = n => n.toString() - .split('') - .reduce((a, x) => a + Math.pow(parseInt(x, 10), 2), 0), - p = (s, n) => n === 1 ? true : ( - s.has(n) ? false : p(s.add(n), f(n)) + const isHappy = n => { + const f = n => + foldl( + (a, x) => a + raise(read(x), 2), // ^2 + 0, + splitOn('', show(n)) + ), + p = (s, n) => n === 1 ? ( + true + ) : member(n, s) ? ( + false + ) : p( + insert(n, s), f(n) ); return p(new Set(), n); - } + }; - // TEST + // GENERIC FUNCTIONS ------------------------------------------------------ - // range :: Int -> Int -> [Int] - let range = (m, n) => Array.from({ - length: Math.floor(n - m) + 1 - }, (_, i) => m + i); + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); - return range(1, 50) - .filter(isHappy) - .slice(0, 8); + // filter :: (a -> Bool) -> [a] -> [a] + const filter = (f, xs) => xs.filter(f); + + // foldl :: (b -> a -> b) -> b -> [a] -> b + const foldl = (f, a, xs) => xs.reduce(f, a); + + // insert :: Ord a => a -> Set a -> Set a + const insert = (e, s) => s.add(e); + + // member :: Ord a => a -> Set a -> Bool + const member = (e, s) => s.has(e); + + // read :: Read a => String -> a + const read = JSON.parse; + + // show :: a -> String + const show = x => JSON.stringify(x); + + // splitOn :: String -> String -> [String] + const splitOn = (cs, xs) => xs.split(cs); + + // raise :: Num -> Int -> Num + const raise = (n, e) => Math.pow(n, e); + + // take :: Int -> [a] -> [a] + const take = (n, xs) => xs.slice(0, n); + + // TEST ------------------------------------------------------------------- + return show( + take(8, filter(isHappy, enumFromTo(1, 50))) + ); })() diff --git a/Task/Happy-numbers/JavaScript/happy-numbers-4.js b/Task/Happy-numbers/JavaScript/happy-numbers-4.js index 4d9502d888..7db8b932b9 100644 --- a/Task/Happy-numbers/JavaScript/happy-numbers-4.js +++ b/Task/Happy-numbers/JavaScript/happy-numbers-4.js @@ -1,35 +1,71 @@ (() => { - 'use strict'; // isHappy :: Int -> Bool - let isHappy = n => { - let f = n => n.toString() - .split('') - .reduce((a, x) => a + Math.pow(parseInt(x, 10), 2), 0), - p = (s, n) => n === 1 ? true : ( - s.has(n) ? false : p(s.add(n), f(n)) + const isHappy = n => { + const f = n => + foldl( + (a, x) => a + raise(read(x), 2), // ^2 + 0, + splitOn('', show(n)) + ), + p = (s, n) => n === 1 ? ( + true + ) : member(n, s) ? ( + false + ) : p( + insert(n, s), f(n) ); return p(new Set(), n); - }, + }; + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // filter :: (a -> Bool) -> [a] -> [a] + const filter = (f, xs) => xs.filter(f); + + // foldl :: (b -> a -> b) -> b -> [a] -> b + const foldl = (f, a, xs) => xs.reduce(f, a); + + // insert :: Ord a => a -> Set a -> Set a + const insert = (e, s) => s.add(e); + + // member :: Ord a => a -> Set a -> Bool + const member = (e, s) => s.has(e); + + // read :: Read a => String -> a + const read = JSON.parse; + + // show :: a -> String + const show = x => JSON.stringify(x); + + // splitOn :: String -> String -> [String] + const splitOn = (cs, xs) => xs.split(cs); + + // raise :: Num -> Int -> Num + const raise = (n, e) => Math.pow(n, e); // until :: (a -> Bool) -> (a -> a) -> a -> a - until = (p, f, x) => { + const until = (p, f, x) => { let v = x; while (!p(v)) v = f(v); return v; }; - return until( - m => m.xs.length === 8, - m => { - let n = m.n; - return { - n: n + 1, - xs: isHappy(n) ? m.xs.concat(n) : m.xs - }; - }, { - n: 1, - xs: [] - } - ).xs; + // TEST ------------------------------------------------------------------- + return show( + until( + m => m.xs.length === 8, + m => { + const n = m.n; + return { + n: n + 1, + xs: isHappy(n) ? m.xs.concat(n) : m.xs + }; + }, { + n: 1, + xs: [] + } + ) + .xs + ); })(); diff --git a/Task/Happy-numbers/jq/happy-numbers-1.jq b/Task/Happy-numbers/Jq/happy-numbers-1.jq similarity index 100% rename from Task/Happy-numbers/jq/happy-numbers-1.jq rename to Task/Happy-numbers/Jq/happy-numbers-1.jq diff --git a/Task/Happy-numbers/jq/happy-numbers-2.jq b/Task/Happy-numbers/Jq/happy-numbers-2.jq similarity index 100% rename from Task/Happy-numbers/jq/happy-numbers-2.jq rename to Task/Happy-numbers/Jq/happy-numbers-2.jq diff --git a/Task/Happy-numbers/jq/happy-numbers-3.jq b/Task/Happy-numbers/Jq/happy-numbers-3.jq similarity index 100% rename from Task/Happy-numbers/jq/happy-numbers-3.jq rename to Task/Happy-numbers/Jq/happy-numbers-3.jq diff --git a/Task/Happy-numbers/Kotlin/happy-numbers.kotlin b/Task/Happy-numbers/Kotlin/happy-numbers.kotlin new file mode 100644 index 0000000000..c959368e72 --- /dev/null +++ b/Task/Happy-numbers/Kotlin/happy-numbers.kotlin @@ -0,0 +1,30 @@ +// version 1.0.5-2 + +fun isHappy(n: Int): Boolean { + val cache = mutableListOf() + var sum = 0 + var nn = n + var digit: Int + while (nn != 1) { + if (nn in cache) return false + cache.add(nn) + while (nn != 0) { + digit = nn % 10 + sum += digit * digit + nn /= 10 + } + nn = sum + sum = 0 + } + return true +} + +fun main(args: Array) { + var num = 1 + val happyNums = mutableListOf() + while (happyNums.size < 8) { + if (isHappy(num)) happyNums.add(num) + num++ + } + println("First 8 happy numbers : " + happyNums.joinToString(", ")) +} diff --git a/Task/Happy-numbers/OoRexx/happy-numbers.rexx b/Task/Happy-numbers/OoRexx/happy-numbers.rexx new file mode 100644 index 0000000000..e941f8d08a --- /dev/null +++ b/Task/Happy-numbers/OoRexx/happy-numbers.rexx @@ -0,0 +1,28 @@ +count = 0 +say "First 8 happy numbers are:" +loop i = 1 while count < 8 + if happyNumber(i) then do + count += 1 + say i + end +end + +::routine happyNumber + use strict arg number + + -- use to trace previous cycle results + previous = .set~new + loop forever + -- stop when we hit the target + if number = 1 then return .true + -- stop as soon as we start cycling + if previous[number] \== .nil then return .false + previous~put(number) + next = 0 + -- loop over all of the digits + loop digit over number~makearray('') + next += digit * digit + end + -- and repeat the cycle + number = next + end diff --git a/Task/Happy-numbers/Zkl/happy-numbers-1.zkl b/Task/Happy-numbers/Zkl/happy-numbers-1.zkl new file mode 100644 index 0000000000..dceb36ba12 --- /dev/null +++ b/Task/Happy-numbers/Zkl/happy-numbers-1.zkl @@ -0,0 +1,9 @@ +fcn happyNumbers{ // continously spew happy numbers + foreach N in ([1..]){ + n:=N; while(1){ + n=n.split().reduce(fcn(p,n){ p + n*n },0); + if(n==1) { vm.yield(N); break; } + if(n==4) break; // unhappy cycle + } + } +} diff --git a/Task/Happy-numbers/Zkl/happy-numbers-2.zkl b/Task/Happy-numbers/Zkl/happy-numbers-2.zkl new file mode 100644 index 0000000000..fae8cdaf2d --- /dev/null +++ b/Task/Happy-numbers/Zkl/happy-numbers-2.zkl @@ -0,0 +1,2 @@ +h:=Utils.Generator(happyNumbers); +h.walk(8).println(); diff --git a/Task/Happy-numbers/Zkl/happy-numbers-3.zkl b/Task/Happy-numbers/Zkl/happy-numbers-3.zkl new file mode 100644 index 0000000000..d454531def --- /dev/null +++ b/Task/Happy-numbers/Zkl/happy-numbers-3.zkl @@ -0,0 +1 @@ +Utils.Generator(happyNumbers).drop(0d1_000_000-1).next().println(); diff --git a/Task/Harshad-or-Niven-series/Batch-File/harshad-or-niven-series.bat b/Task/Harshad-or-Niven-series/Batch-File/harshad-or-niven-series.bat new file mode 100644 index 0000000000..6c8ae506a6 --- /dev/null +++ b/Task/Harshad-or-Niven-series/Batch-File/harshad-or-niven-series.bat @@ -0,0 +1,36 @@ +@echo off +setlocal enabledelayedexpansion + +for /l %%i in (1,1,20) do ( + call:harshad + echo Harshad number %%i - !errorlevel! +) + +:loop +call:harshad +if %errorlevel% leq 1000 goto loop +echo First Harshad number greater than 1000: %errorlevel% +pause>nul +exit /b + +:harshad +if "%harshadnum%"=="" set harshadnum=0 +set /a harshadnum+=1 +call:strlength %harshadnum% + +set harshadsum=0 +for /l %%i in (0,1,%errorlevel%) do set /a harshadsum+=!harshadnum:~%%i,1! + +set /a isharshad=%harshadnum% %% %harshadsum% +if %isharshad%==0 exit /b %harshadnum% +goto harshad + +:strlength +setlocal enabledelayedexpansion +set tempcount=1 +set str=%1 +:strlengthloop +set /a length=%tempcount%-1 +if "!str:~%tempcount%,1!"=="" endlocal && exit /b %length% +set /a tempcount+=1 +goto strlengthloop diff --git a/Task/Harshad-or-Niven-series/Gambas/harshad-or-niven-series.gambas b/Task/Harshad-or-Niven-series/Gambas/harshad-or-niven-series.gambas new file mode 100644 index 0000000000..4bd6a9d7c5 --- /dev/null +++ b/Task/Harshad-or-Niven-series/Gambas/harshad-or-niven-series.gambas @@ -0,0 +1,28 @@ +Public Sub Main() +Dim siCount, siLoop, siTotal, siCounter As Short +Dim sNo, sTemp As String +Dim sHold, sNiven As New String[] + +For siCount = 1 To 1500 + sNo = Str(siCount) + For siLoop = 1 To Len(sNo) + sHold.Add(Mid(sNo, siLoop, 1)) + Next + For Each sTemp In sHold + siTotal += Val(sTemp) + Next + If siCount Mod siTotal = 0 Then + Inc siCounter + If siCounter < 21 Or siCount > 1000 Then + sNiven.Add(Str(siCount)) + If siCount > 1000 Then Break + Endif + Endif + siTotal = 0 + sHold.Clear +Next + +Print "First twenty Harshad numbers and the first Harshad number greater than 1000" +Print sNiven.Join(", ") + +End diff --git a/Task/Harshad-or-Niven-series/Groovy/harshad-or-niven-series.groovy b/Task/Harshad-or-Niven-series/Groovy/harshad-or-niven-series.groovy new file mode 100644 index 0000000000..21754dd2a0 --- /dev/null +++ b/Task/Harshad-or-Niven-series/Groovy/harshad-or-niven-series.groovy @@ -0,0 +1,37 @@ +​class HarshadNiven{ public static boolean find(int x) + { + int sum = 0,temp,var; + var = x; + while(x>0) + { + temp = x%10; + sum = sum + temp; + x = x/10; + } + if(var%sum==0) temp = 1; + else temp = 0; + return temp; + } + public static void main(String[] args) + { + int t,i; + t = 0; + for(i=1;t<20;i++) + { + if(find(i)) + { + print(i + " "); + t++; + } + } + int x = 0; + int y = 1000; + while(x!=1) + { + if(find(y)) x = 1; + y++; + } + println(); + println(y+1); + } +} diff --git a/Task/Harshad-or-Niven-series/Haskell/harshad-or-niven-series-1.hs b/Task/Harshad-or-Niven-series/Haskell/harshad-or-niven-series-1.hs new file mode 100644 index 0000000000..281795830b --- /dev/null +++ b/Task/Harshad-or-Niven-series/Haskell/harshad-or-niven-series-1.hs @@ -0,0 +1,9 @@ +import Data.Char (ord) + +harshads :: [Int] +harshads = + let digsum = sum . map ((48 -) . ord) . show + in filter ((0 ==) . (mod <*> digsum)) [1 ..] + +main :: IO () +main = mapM_ print [take 20 harshads, [(head . filter (> 1000)) harshads]] diff --git a/Task/Harshad-or-Niven-series/Haskell/harshad-or-niven-series-2.hs b/Task/Harshad-or-Niven-series/Haskell/harshad-or-niven-series-2.hs new file mode 100644 index 0000000000..12e16c5044 --- /dev/null +++ b/Task/Harshad-or-Niven-series/Haskell/harshad-or-niven-series-2.hs @@ -0,0 +1,9 @@ +harshadSeries :: [Int] +harshadSeries = filter ((0 ==) . (rem <*> (sum . digitList))) [1 ..] + +digitList :: Int -> [Int] +digitList 0 = [] +digitList n = rem n 10 : digitList (quot n 10) + +main :: IO () +main = mapM_ print $ [take 20, take 1 . dropWhile (<= 1000)] <*> [harshadSeries] diff --git a/Task/Harshad-or-Niven-series/Haskell/harshad-or-niven-series.hs b/Task/Harshad-or-Niven-series/Haskell/harshad-or-niven-series.hs deleted file mode 100644 index e9c1aaee1c..0000000000 --- a/Task/Harshad-or-Niven-series/Haskell/harshad-or-niven-series.hs +++ /dev/null @@ -1,6 +0,0 @@ -import Data.Char (ord) - -main = do print $ take 20 harshads - print $ head $ filter (> 1000) harshads - where digsum = sum . map ((48 -) . ord) . show - harshads = filter (\n -> mod n (digsum n) == 0) [1..] diff --git a/Task/Harshad-or-Niven-series/JavaScript/harshad-or-niven-series.js b/Task/Harshad-or-Niven-series/JavaScript/harshad-or-niven-series-1.js similarity index 100% rename from Task/Harshad-or-Niven-series/JavaScript/harshad-or-niven-series.js rename to Task/Harshad-or-Niven-series/JavaScript/harshad-or-niven-series-1.js diff --git a/Task/Harshad-or-Niven-series/JavaScript/harshad-or-niven-series-2.js b/Task/Harshad-or-Niven-series/JavaScript/harshad-or-niven-series-2.js new file mode 100644 index 0000000000..e44d2524d7 --- /dev/null +++ b/Task/Harshad-or-Niven-series/JavaScript/harshad-or-niven-series-2.js @@ -0,0 +1,69 @@ +(() => { + 'use strict'; + + // HARSHADS --------------------------------------------------------------- + + // nHarshads :: Int -> [Int] + const nHarshads = n => { + + // isHarshad :: Int -> Bool + const isHarshad = n => 0 === n % sum(digitList(n)); + + return until( + dct => dct.nth === n, + dct => { + const + next = succ(dct.i), + blnHarshad = isHarshad(next); + return { + i: next, + hs: blnHarshad ? dct.hs.concat(next) : dct.hs, + nth: dct.nth + (blnHarshad ? 1 : 0) + }; + }, { + i: 0, + hs: [], + nth: 0 + } + ) + .hs; + }; + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // digitList :: Int -> [Int] + const digitList = n => + n > 0 ? [n % 10].concat(digitList(Math.floor(n / 10))) : []; + + // dropWhile :: (a -> Bool) -> [a] -> [a] + const dropWhile = (p, xs) => { + let i = 0; + for (let lng = xs.length; + (i < lng) && p(xs[i]); i++) {} + return xs.slice(i); + }; + + // head :: [a] -> a + const head = xs => xs.length ? xs[0] : undefined; + + // a -> String + const show = x => JSON.stringify(x, null, 2); + + // succ :: Int -> Int + const succ = x => x + 1 + + // sum :: (Num a) => [a] -> a + const sum = xs => xs.reduce((a, x) => a + x, 0); + + // until :: (a -> Bool) -> (a -> a) -> a -> a + const until = (p, f, x) => { + const go = x => p(x) ? x : go(f(x)); + return go(x); + }; + + // TEST ------------------------------------------------------------------- + return show({ + firstTwenty: nHarshads(20), + firstOver1000: head(dropWhile(x => x <= 1000, nHarshads(1000))) + }); +})(); diff --git a/Task/Harshad-or-Niven-series/jq/harshad-or-niven-series.jq b/Task/Harshad-or-Niven-series/Jq/harshad-or-niven-series.jq similarity index 100% rename from Task/Harshad-or-Niven-series/jq/harshad-or-niven-series.jq rename to Task/Harshad-or-Niven-series/Jq/harshad-or-niven-series.jq diff --git a/Task/Harshad-or-Niven-series/Kotlin/harshad-or-niven-series.kotlin b/Task/Harshad-or-Niven-series/Kotlin/harshad-or-niven-series.kotlin new file mode 100644 index 0000000000..163ef67eda --- /dev/null +++ b/Task/Harshad-or-Niven-series/Kotlin/harshad-or-niven-series.kotlin @@ -0,0 +1,39 @@ +// version 1.1 + +fun sumDigits(n: Int): Int = when { + n <= 0 -> 0 + else -> { + var sum = 0 + var nn = n + while (nn > 0) { + sum += nn % 10 + nn /= 10 + } + sum + } + } + +fun isHarshad(n: Int): Boolean = (n % sumDigits(n) == 0) + +fun main(args: Array) { + println("The first 20 Harshad numbers are:") + var count = 0 + var i = 0 + + while (true) { + if (isHarshad(++i)) { + print("$i ") + if (++count == 20) break + } + } + + println("\n\nThe first Harshad number above 1000 is:") + i = 1000 + + while (true) { + if (isHarshad(++i)) { + println(i) + return + } + } +} diff --git a/Task/Harshad-or-Niven-series/OoRexx/harshad-or-niven-series.rexx b/Task/Harshad-or-Niven-series/OoRexx/harshad-or-niven-series.rexx new file mode 100644 index 0000000000..348d375e99 --- /dev/null +++ b/Task/Harshad-or-Niven-series/OoRexx/harshad-or-niven-series.rexx @@ -0,0 +1,33 @@ +/* REXX --------------------------------------------------------------- +* 21.01.2014 Walter Pachl modi-(simpli-)fied from REXX version 1 +*--------------------------------------------------------------------*/ + Parse Arg x y . /* get optional arguments: X Y */ + If x='' Then x=20 /* Not specified? Use default */ + If y='' Then y=1000 /* " " " " */ + n=0 /* Niven count */ + nl='' /* Niven list. */ + + Do j=1 Until n=x /* let's go Niven number hunting.*/ + If j//sumdigs(j)=0 Then Do /* j is a Niven number */ + n=n+1 /* bump Niven count */ + nl=nl j /* add to list. */ + End + End + + Say 'first' n 'Niven numbers:'nl + + Do j=y+1 /* start with first candidate */ + If j//sumdigs(j)=0 Then /* j is a Niven number */ + Leave + End + + Say 'first Niven number >' y 'is:' j + Exit + +sumdigs: Procedure /* compute sum of n's digits */ + Parse Arg n + sum=left(n,1) + Do k=2 To length(n) + sum=sum+substr(n,k,1) + End + Return sum diff --git a/Task/Harshad-or-Niven-series/Phix/harshad-or-niven-series-1.phix b/Task/Harshad-or-Niven-series/Phix/harshad-or-niven-series-1.phix new file mode 100644 index 0000000000..de4886236a --- /dev/null +++ b/Task/Harshad-or-Niven-series/Phix/harshad-or-niven-series-1.phix @@ -0,0 +1,31 @@ +integer n = 0 +sequence digits={0} + +procedure nNiven() + while 1 do + n += 1 + for i=length(digits) to 0 by -1 do + if i=0 then + digits = prepend(digits,1) + exit + end if + if digits[i]<9 then + digits[i] += 1 + exit + end if + digits[i] = 0 + end for + if remainder(n,sum(digits))=0 then exit end if + end while +end procedure + +sequence s = {} +for i=1 to 20 do + nNiven() + s &= n +end for +?s +while n<=1000 do + nNiven() +end while +?n diff --git a/Task/Harshad-or-Niven-series/Phix/harshad-or-niven-series-2.phix b/Task/Harshad-or-Niven-series/Phix/harshad-or-niven-series-2.phix new file mode 100644 index 0000000000..f9340e770f --- /dev/null +++ b/Task/Harshad-or-Niven-series/Phix/harshad-or-niven-series-2.phix @@ -0,0 +1,15 @@ +function isHarshad(integer n) + return remainder(n,sum(sq_sub(sprint(n),'0')))=0 +end function + +sequence s = {} +integer n = 0 +while length(s)<20 do + n += 1 + if isHarshad(n) then + s &= n + end if +end while +n = 1001 +while not isHarshad(n) do n += 1 end while +?s&n diff --git a/Task/Harshad-or-Niven-series/Ruby/harshad-or-niven-series.rb b/Task/Harshad-or-Niven-series/Ruby/harshad-or-niven-series.rb index 7120f1de98..55c971250d 100644 --- a/Task/Harshad-or-Niven-series/Ruby/harshad-or-niven-series.rb +++ b/Task/Harshad-or-Niven-series/Ruby/harshad-or-niven-series.rb @@ -1,9 +1,4 @@ -def digsum n - n.to_s.chars.map(&:to_i).reduce(:+) -end - -harshad = 1.step.lazy.select { |n| n % digsum(n) == 0 } -#harshad = (1..Float::INFINITY).lazy.select { |n| n % digsum(n) == 0 } # ver 2.0 +harshad = 1.step.lazy.select { |n| n % n.digits.sum == 0 } p harshad.first(20) p harshad.find { |n| n > 1000 } diff --git a/Task/Harshad-or-Niven-series/Scala/harshad-or-niven-series.scala b/Task/Harshad-or-Niven-series/Scala/harshad-or-niven-series.scala index 28cfcbc6bf..c3f8593fc8 100644 --- a/Task/Harshad-or-Niven-series/Scala/harshad-or-niven-series.scala +++ b/Task/Harshad-or-Niven-series/Scala/harshad-or-niven-series.scala @@ -1,10 +1,8 @@ object Harshad extends App { - import language.postfixOps - import Stream._ - val fh: Stream[Int] => Stream[Int] = ints => - ints.head #:: fh((ints.tail) filter { i => i % (i.toString.map(_.asDigit) :\ 0)(_ + _) == 0 }) - val harshads = fh(from(1)) - println(harshads take 20 toList) - println(harshads filter (_ > 1000) head) + val harshads = Stream from 1 filter (i => i % i.toString.map(_.asDigit).sum == 0) + + println(harshads.take(20).toList) + println(harshads.filter(_ > 1000).head) + } diff --git a/Task/Harshad-or-Niven-series/Sinclair-ZX81-BASIC/harshad-or-niven-series.sinclair b/Task/Harshad-or-Niven-series/Sinclair-ZX81-BASIC/harshad-or-niven-series.sinclair new file mode 100644 index 0000000000..996b7b1797 --- /dev/null +++ b/Task/Harshad-or-Niven-series/Sinclair-ZX81-BASIC/harshad-or-niven-series.sinclair @@ -0,0 +1,15 @@ + 10 FAST + 20 LET N=0 + 30 LET H=0 + 40 LET N=N+1 + 50 LET N$=STR$ N + 60 LET SD=0 + 70 FOR I=1 TO LEN N$ + 80 LET SD=SD+VAL N$(I) + 90 NEXT I +100 IF N/SD<>INT (N/SD) THEN GOTO 40 +110 LET H=H+1 +120 IF H<=20 OR N>1000 THEN PRINT N +130 IF N>1000 THEN GOTO 150 +140 GOTO 40 +150 SLOW diff --git a/Task/Harshad-or-Niven-series/Zkl/harshad-or-niven-series.zkl b/Task/Harshad-or-Niven-series/Zkl/harshad-or-niven-series.zkl new file mode 100644 index 0000000000..8e9de74a93 --- /dev/null +++ b/Task/Harshad-or-Niven-series/Zkl/harshad-or-niven-series.zkl @@ -0,0 +1,5 @@ +fcn harshad(n){ 0==n%(n.split().sum(0)) } +[1..].tweak(fcn(n){ if(not harshad(n)) return(Void.Skip); n }) + .walk(20).println(); +[1..].filter(20,harshad).println(); +[1001..].filter1(harshad).println(); diff --git a/Task/Hash-from-two-arrays/Gambas/hash-from-two-arrays.gambas b/Task/Hash-from-two-arrays/Gambas/hash-from-two-arrays.gambas new file mode 100644 index 0000000000..319e268244 --- /dev/null +++ b/Task/Hash-from-two-arrays/Gambas/hash-from-two-arrays.gambas @@ -0,0 +1,15 @@ +Public Sub Main() +Dim sValue As String[] = ["Zero", "One", "Two", "Three", "Four", "Five"] +Dim sKey As String[] = [0, 1, 2, 3, 4, 5] +Dim sCol As New Collection +Dim siCount As Short + +For siCount = 0 To sKey.max + sCol.Add(sValue[siCount], sKey[siCount]) +Next + +For siCount = 0 To sKey.max + Print Str(sicount) & " = " & sCol[siCount] +Next + +End diff --git a/Task/Hash-from-two-arrays/jq/hash-from-two-arrays-1.jq b/Task/Hash-from-two-arrays/Jq/hash-from-two-arrays-1.jq similarity index 100% rename from Task/Hash-from-two-arrays/jq/hash-from-two-arrays-1.jq rename to Task/Hash-from-two-arrays/Jq/hash-from-two-arrays-1.jq diff --git a/Task/Hash-from-two-arrays/jq/hash-from-two-arrays-2.jq b/Task/Hash-from-two-arrays/Jq/hash-from-two-arrays-2.jq similarity index 100% rename from Task/Hash-from-two-arrays/jq/hash-from-two-arrays-2.jq rename to Task/Hash-from-two-arrays/Jq/hash-from-two-arrays-2.jq diff --git a/Task/Hash-from-two-arrays/jq/hash-from-two-arrays-3.jq b/Task/Hash-from-two-arrays/Jq/hash-from-two-arrays-3.jq similarity index 100% rename from Task/Hash-from-two-arrays/jq/hash-from-two-arrays-3.jq rename to Task/Hash-from-two-arrays/Jq/hash-from-two-arrays-3.jq diff --git a/Task/Hash-from-two-arrays/Kotlin/hash-from-two-arrays.kotlin b/Task/Hash-from-two-arrays/Kotlin/hash-from-two-arrays.kotlin new file mode 100644 index 0000000000..653ae3702c --- /dev/null +++ b/Task/Hash-from-two-arrays/Kotlin/hash-from-two-arrays.kotlin @@ -0,0 +1,8 @@ +// version 1.1.0 + +fun main(args: Array) { + val names = arrayOf("Jimmy", "Bill", "Barack", "Donald") + val ages = arrayOf(92, 70, 55, 70) + val hash = mapOf(*names.zip(ages).toTypedArray()) + hash.forEach { println("${it.key.padEnd(6)} aged ${it.value}") } +} diff --git a/Task/Hash-from-two-arrays/OoRexx/hash-from-two-arrays.rexx b/Task/Hash-from-two-arrays/OoRexx/hash-from-two-arrays.rexx new file mode 100644 index 0000000000..dbec5144a9 --- /dev/null +++ b/Task/Hash-from-two-arrays/OoRexx/hash-from-two-arrays.rexx @@ -0,0 +1,13 @@ +array1 = .array~of("Rick", "Mike", "David") +array2 = .array~of("555-9862", "555-5309", "555-6666") + +-- if the index items are constrained to string objects, this can +-- be a directory too. +hash = .table~new + +loop i = 1 to array1~size + hash[array1[i]] = array2[i] +end +Say 'Enter a name' +Parse Pull name +Say name '->' hash[name] diff --git a/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-5.pl6 b/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-5.pl6 deleted file mode 100644 index 92213b65e4..0000000000 --- a/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-5.pl6 +++ /dev/null @@ -1 +0,0 @@ -{ @keys »=>« @values } diff --git a/Task/Hash-from-two-arrays/Phix/hash-from-two-arrays.phix b/Task/Hash-from-two-arrays/Phix/hash-from-two-arrays.phix new file mode 100644 index 0000000000..6d663d69d1 --- /dev/null +++ b/Task/Hash-from-two-arrays/Phix/hash-from-two-arrays.phix @@ -0,0 +1,16 @@ +function make_hash(sequence keyarray, sequence valuearray) +integer dict = new_dict() + for i=1 to length(keyarray) do + setd(keyarray[i],valuearray[i],dict) +-- setd(keyarray[i],i,dict) + end for + return dict +end function + +constant keyarray = {1,"two",PI} +constant valuearray = {"one",2,PI} +integer dict = make_hash(keyarray,valuearray) +?getd(1,dict) +?getd("two",dict) +?getd(PI,dict) +--?valuearray[getd(1,dict)] diff --git a/Task/Hash-from-two-arrays/Zkl/hash-from-two-arrays.zkl b/Task/Hash-from-two-arrays/Zkl/hash-from-two-arrays.zkl new file mode 100644 index 0000000000..10bf5bc20a --- /dev/null +++ b/Task/Hash-from-two-arrays/Zkl/hash-from-two-arrays.zkl @@ -0,0 +1,4 @@ +keys:=T("a","b","c","d"); vals:=T(1,2,3,4); +d:=keys.zip(vals).toDictionary(); +d.println(); +d["b"].println(); diff --git a/Task/Hash-join/AWK/hash-join.awk b/Task/Hash-join/AWK/hash-join.awk new file mode 100644 index 0000000000..a9173a9170 --- /dev/null +++ b/Task/Hash-join/AWK/hash-join.awk @@ -0,0 +1,61 @@ +# syntax: GAWK -f HASH_JOIN.AWK [-v debug={0|1}] TABLE_A TABLE_B +# +# sorting: +# PROCINFO["sorted_in"] is used by GAWK +# SORTTYPE is used by Thompson Automation's TAWK +# +BEGIN { + FS = "," + PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1 + if (ARGC-1 != 2) { + print("error: incorrect number of arguments") ; errors++ + exit # go to END + } +} +{ if (NR == FNR) { # table A + if (FNR == 1) { + a_head = prefix_column_names("A") + next + } + a_arr[$2][$1] = $0 # [name][age] + } + if (NR != FNR) { # table B + if (FNR == 1) { + b_head = prefix_column_names("B") + next + } + b_arr[$1][$2] = $0 # [character][nemesis] + } +} +END { + if (errors > 0) { exit(1) } + if (debug == 1) { + dump_table(a_arr,a_head) + dump_table(b_arr,b_head) + } + printf("%s%s%s\n",a_head,FS,b_head) # table heading + for (i in a_arr) { + if (i in b_arr) { + for (j in a_arr[i]) { + for (k in b_arr[i]) { + print(a_arr[i][j] FS b_arr[i][k]) # join table A & table B + } + } + } + } + exit(0) +} +function dump_table(arr,heading, i,j) { + printf("%s\n",heading) + for (i in arr) { + for (j in arr[i]) { + printf("%s\n",arr[i][j]) + } + } + print("") +} +function prefix_column_names(p, tmp) { + tmp = p "." $0 + gsub(/,/,"&" p ".",tmp) + return(tmp) +} diff --git a/Task/Hash-join/AppleScript/hash-join.applescript b/Task/Hash-join/AppleScript/hash-join.applescript index 0cde4e04df..0a785b4f96 100644 --- a/Task/Hash-join/AppleScript/hash-join.applescript +++ b/Task/Hash-join/AppleScript/hash-join.applescript @@ -1,11 +1,13 @@ use framework "Foundation" -- Yosemite onwards, for record-handling functions +-- HASH JOIN ----------------------------------------------------------------- + -- hashJoin :: [Record] -> [Record] -> String -> [Record] on hashJoin(tblA, tblB, strJoin) set {jA, jB} to splitOn("=", strJoin) script instanceOfjB - on lambda(a, x) + on |λ|(a, x) set strID to keyValue(x, jB) set maybeInstances to keyValue(a, strID) @@ -14,32 +16,32 @@ on hashJoin(tblA, tblB, strJoin) else updatedRecord(a, strID, [x]) end if - end lambda + end |λ| end script set M to foldl(instanceOfjB, {name:"multiMap"}, tblB) script joins - on lambda(a, x) + on |λ|(a, x) set matches to keyValue(M, keyValue(x, jA)) if matches is not missing value then script concat - on lambda(row) + on |λ|(row) x & row - end lambda + end |λ| end script a & map(concat, matches) else a end if - end lambda + end |λ| end script foldl(joins, {}, tblA) end hashJoin --- TEST +-- TEST ---------------------------------------------------------------------- on run set lstA to [¬ {age:27, |name|:"Jonah"}, ¬ @@ -60,12 +62,13 @@ on run end run --- RECORD PRIMITIVES +-- RECORD FUNCTIONS ---------------------------------------------------------- -- keyValue :: String -> Record -> Maybe a on keyValue(rec, strKey) set ca to current application - set v to (ca's NSDictionary's dictionaryWithDictionary:rec)'s objectForKey:strKey + set v to (ca's NSDictionary's dictionaryWithDictionary:rec)'s ¬ + objectForKey:strKey if v is not missing value then item 1 of ((ca's NSArray's arrayWithObject:v) as list) else @@ -82,7 +85,7 @@ on updatedRecord(rec, strKey, varValue) end updatedRecord --- GENERIC PRIMITIVES +-- GENERIC FUNCTIONS --------------------------------------------------------- -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) @@ -90,7 +93,7 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -102,20 +105,12 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map --- splitOn :: Text -> Text -> [Text] -on splitOn(strDelim, strMain) - set {dlm, my text item delimiters} to {my text item delimiters, strDelim} - set lstParts to text items of strMain - set my text item delimiters to dlm - return lstParts -end splitOn - -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) @@ -123,7 +118,15 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn + +-- splitOn :: Text -> Text -> [Text] +on splitOn(strDelim, strMain) + set {dlm, my text item delimiters} to {my text item delimiters, strDelim} + set lstParts to text items of strMain + set my text item delimiters to dlm + return lstParts +end splitOn diff --git a/Task/Hash-join/jq/hash-join-1.jq b/Task/Hash-join/Jq/hash-join-1.jq similarity index 100% rename from Task/Hash-join/jq/hash-join-1.jq rename to Task/Hash-join/Jq/hash-join-1.jq diff --git a/Task/Hash-join/jq/hash-join-2.jq b/Task/Hash-join/Jq/hash-join-2.jq similarity index 100% rename from Task/Hash-join/jq/hash-join-2.jq rename to Task/Hash-join/Jq/hash-join-2.jq diff --git a/Task/Hash-join/jq/hash-join-3.jq b/Task/Hash-join/Jq/hash-join-3.jq similarity index 100% rename from Task/Hash-join/jq/hash-join-3.jq rename to Task/Hash-join/Jq/hash-join-3.jq diff --git a/Task/Hash-join/jq/hash-join-4.jq b/Task/Hash-join/Jq/hash-join-4.jq similarity index 100% rename from Task/Hash-join/jq/hash-join-4.jq rename to Task/Hash-join/Jq/hash-join-4.jq diff --git a/Task/Hash-join/jq/hash-join-5.jq b/Task/Hash-join/Jq/hash-join-5.jq similarity index 100% rename from Task/Hash-join/jq/hash-join-5.jq rename to Task/Hash-join/Jq/hash-join-5.jq diff --git a/Task/Hash-join/jq/hash-join-6.jq b/Task/Hash-join/Jq/hash-join-6.jq similarity index 100% rename from Task/Hash-join/jq/hash-join-6.jq rename to Task/Hash-join/Jq/hash-join-6.jq diff --git a/Task/Hash-join/Julia/hash-join-1.julia b/Task/Hash-join/Julia/hash-join-1.julia new file mode 100644 index 0000000000..bdd52d2c70 --- /dev/null +++ b/Task/Hash-join/Julia/hash-join-1.julia @@ -0,0 +1,8 @@ +using DataFrames + +A = DataFrame(Age = [27, 18, 28, 18, 28], Name = ["Jonah", "Alan", "Glory", "Popeye", "Alan"]) +B = DataFrame(Name = ["Jonah", "Jonah", "Alan", "Alan", "Glory"], + Nemesis = ["Whales", "Spiders", "Ghosts", "Zombies", "Buffy"]) +AB = join(A, B, on = :Name) + +@show A B AB diff --git a/Task/Hash-join/Julia/hash-join-2.julia b/Task/Hash-join/Julia/hash-join-2.julia new file mode 100644 index 0000000000..3dfe540a1d --- /dev/null +++ b/Task/Hash-join/Julia/hash-join-2.julia @@ -0,0 +1,19 @@ +function hashjoin(A::Array, ja::Int, B::Array, jb::Int) + M = Dict(t[jb] => filter(l -> l[jb] == t[jb], B) for t in B) + return collect([a, b] for a in A for b in get(M, a[ja], ())) +end + +table1 = [(27, "Jonah"), + (18, "Alan"), + (28, "Glory"), + (18, "Popeye"), + (28, "Alan")] +table2 = [("Jonah", "Whales"), + ("Jonah", "Spiders"), + ("Alan", "Ghosts"), + ("Alan", "Zombies"), + ("Glory", "Buffy")] + +for r in hashjoin(table1, 2, table2, 1) + println(r) +end diff --git a/Task/Hash-join/Kotlin/hash-join.kotlin b/Task/Hash-join/Kotlin/hash-join.kotlin new file mode 100644 index 0000000000..05eac3f750 --- /dev/null +++ b/Task/Hash-join/Kotlin/hash-join.kotlin @@ -0,0 +1,39 @@ +data class A(val age: Int, val name: String) + +data class B(val character: String, val nemesis: String) + +data class C(val rowA: A, val rowB: B) + +fun hashJoin(tableA: List
    , tableB: List): List { + val mm = tableB.groupBy { it.character } + val tableC = mutableListOf() + for (a in tableA) { + val value = mm[a.name] ?: continue + for (b in value) tableC.add(C(a, b)) + } + return tableC.toList() +} + +fun main(args: Array) { + val tableA = listOf( + A(27, "Jonah"), + A(18, "Alan"), + A(28, "Glory"), + A(18, "Popeye"), + A(28, "Alan") + ) + val tableB = listOf( + B("Jonah", "Whales"), + B("Jonah", "Spiders"), + B("Alan", "Ghosts"), + B("Alan", "Zombies"), + B("Glory", "Buffy") + ) + val tableC = hashJoin(tableA, tableB) + println("A.Age A.Name B.Character B.Nemesis") + println("----- ------ ----------- ---------") + for (c in tableC) { + print("${c.rowA.age} ${c.rowA.name.padEnd(6)} ") + println("${c.rowB.character.padEnd(6)} ${c.rowB.nemesis}") + } +} diff --git a/Task/Hash-join/Phix/hash-join.phix b/Task/Hash-join/Phix/hash-join.phix new file mode 100644 index 0000000000..cc78e9e12c --- /dev/null +++ b/Task/Hash-join/Phix/hash-join.phix @@ -0,0 +1,34 @@ +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}) diff --git a/Task/Hash-join/PlainTeX/hash-join.tex b/Task/Hash-join/PlainTeX/hash-join.tex new file mode 100644 index 0000000000..42de6a8e1b --- /dev/null +++ b/Task/Hash-join/PlainTeX/hash-join.tex @@ -0,0 +1,20 @@ +\newtoks\tabjoin +\def\quark{\quark} +\def\tabA{27:Jonah,18:Alan,28:Glory,18:Popeye,28:Alan} +\def\tabB{Jonah:Whales,Jonah:Spiders,Alan:Ghosts,Alan:Zombies,Glory:Buffy} +\def\mergejoin{\tabjoin{}\expandafter\mergejoini\tabA,\quark:\quark,} +\def\mergejoini#1:#2,{% + \ifx\quark#1\the\tabjoin + \else + \def\mergejoinii##1,#2:##2,{% + \ifx\quark##2\else + \tabjoin\expandafter{\the\tabjoin#1 : #2 : ##2\par}% + \expandafter\mergejoinii\expandafter,% + \fi + }% + \expandafter\mergejoinii\expandafter,\tabB,#2:\quark,% + \expandafter\mergejoini + \fi +} +\mergejoin +\bye diff --git a/Task/Hash-join/PureBasic/hash-join.purebasic b/Task/Hash-join/PureBasic/hash-join.purebasic new file mode 100644 index 0000000000..3889148d31 --- /dev/null +++ b/Task/Hash-join/PureBasic/hash-join.purebasic @@ -0,0 +1,47 @@ +Structure tabA + age.i + name.s +EndStructure + +Structure tabB + char_name.s + nemesis.s +EndStructure + +NewList listA.tabA() +NewList listB.tabB() + +Macro SetListA(c_age, c_name) + AddElement(listA()) : listA()\age = c_age : listA()\name = c_name +EndMacro + +Macro SetListB(c_char, c_nem) + AddElement(listB()) : listB()\char_name = c_char : listB()\nemesis = c_nem +EndMacro + +SetListA(27, "Jonah") : SetListA(18, "Alan") : SetListA(28, "Glory") +SetListA(18, "Popeye") : SetListA(28, "Alan") + +SetListB("Jonah", "Whales") : SetListB("Jonah", "Spiders") +SetListB("Alan", "Ghosts") : SetListB("Alan", "Zombies") +SetListB("Glory", "Buffy") + +If OpenConsole("Hash_join") + ForEach listA() + PrintN("Input A = "+Str(listA()\age)+~"\t"+listA()\name) + Next + PrintN("") + ForEach listB() + PrintN("Input B = "+listB()\char_name+~"\t"+listB()\nemesis) + Next + PrintN(~"\nOutput\nA.Age\tA.Name\tB.Char.\tB.Nemesis") + ForEach listA() + ForEach listB() + If listA()\name = listB()\char_name + PrintN(Str(listA()\age)+~"\t"+listA()\name+~"\t"+ + listB()\char_name+~"\t"+listB()\nemesis) + EndIf + Next + Next + Input() +EndIf diff --git a/Task/Hash-join/Rust/hash-join.rust b/Task/Hash-join/Rust/hash-join.rust index c57b7f6ee5..c53ca9b06f 100644 --- a/Task/Hash-join/Rust/hash-join.rust +++ b/Task/Hash-join/Rust/hash-join.rust @@ -12,13 +12,15 @@ fn main() { // hash phase let mut h = HashMap::new(); for (i, a) in table_a.iter().enumerate() { - h.entry(a.1).or_insert(vec![]).push(i); + h.entry(a.1).or_insert_with(Vec::new).push(i); } // join phase for b in table_b { - for i in h.get(b.0).unwrap_or(&vec![]) { - let a = table_a.get(*i).unwrap(); - println!("{:?} {:?}", a, b); + if let Some(vals) = h.get(b.0) { + for &val in vals { + let a = table_a.get(val).unwrap(); + println!("{:?} {:?}", a, b); + } } } } diff --git a/Task/Hash-join/Zkl/hash-join.zkl b/Task/Hash-join/Zkl/hash-join.zkl new file mode 100644 index 0000000000..8c8fbc14eb --- /dev/null +++ b/Task/Hash-join/Zkl/hash-join.zkl @@ -0,0 +1,24 @@ +ageName:=T(27,"Jonah", 18,"Alan", 28,"Glory", 18,"Popeye", 28,"Alan"); +nameNemesis:=T("Jonah","Whales", "Jonah","Spiders", "Alan","Ghosts", + "Alan","Zombies", "Glory","Buffy"); + +fcn addAN(age,name,d){ // keys are names, values are ( (age,...),() ) + if (r:=d.find(name)) d[name] = T(r[0].append(age),r[1]); + else d.add(name,T(T(age),T)); + d // return d so pump will use that as result for assignment +} +fcn addNN(name,nemesis,d){ // values-->( (age,age...), (nemesis,...) ) + if (r:=d.find(name)){ + ages,nemesises := r; + d[name] = T(ages,nemesises.append(nemesis)); + } +} + // Void.Read --> take existing i, read next one, pass both to next function +var d=ageName.pump(Void,Void.Read,T(addAN,Dictionary())); +nameNemesis.pump(Void,Void.Read,T(addNN,d)); + +d.println(); // the union of the two tables +d.keys.sort().pump(Console.println,'wrap(name){ //pretty print the join + val:=d[name]; if (not val[1])return(Void.Skip); + String(name,":",d[name][1].concat(",")); +}) diff --git a/Task/Haversine-formula/Elm/haversine-formula.elm b/Task/Haversine-formula/Elm/haversine-formula.elm new file mode 100644 index 0000000000..f367d9e41f --- /dev/null +++ b/Task/Haversine-formula/Elm/haversine-formula.elm @@ -0,0 +1,26 @@ +haversine : ( Float, Float ) -> ( Float, Float ) -> Float +haversine ( lat1, lon1 ) ( lat2, lon2 ) = + let + r = + 6372.8 + + dLat = + degrees (lat2 - lat1) + + dLon = + degrees (lon2 - lon1) + + a = + (sin (dLat / 2)) + ^ 2 + + (sin (dLon / 2)) + ^ 2 + * cos (degrees lat1) + * cos (degrees lat2) + in + r * 2 * asin (sqrt a) + +view = + Html.div [] + [ Html.text (toString (haversine ( 36.12, -86.67 ) ( 33.94, -118.4 ))) + ] diff --git a/Task/Haversine-formula/Haskell/haversine-formula.hs b/Task/Haversine-formula/Haskell/haversine-formula.hs index 3cd45d50f9..954886fecb 100644 --- a/Task/Haversine-formula/Haskell/haversine-formula.hs +++ b/Task/Haversine-formula/Haskell/haversine-formula.hs @@ -1,28 +1,33 @@ import Text.Printf +import Control.Arrow ((***)) -- The haversine of an angle. -hsin t = let u = sin (t/2) in u*u - --- The distance between two points, given by latitude and longtitude, on a --- circle. The points are specified in radians. -distRad radius (lat1, lng1) (lat2, lng2) = - let hlat = hsin (lat2 - lat1) - hlng = hsin (lng2 - lng1) - root = sqrt (hlat + cos lat1 * cos lat2 * hlng) - in 2 * radius * asin (min 1.0 root) - --- The distance between two points, given by latitude and longtitude, on a --- circle. The points are specified in degrees. -distDeg radius p1 p2 = distRad radius (deg2rad p1) (deg2rad p2) - where deg2rad (t, u) = (d2r t, d2r u) - d2r t = t * pi / 180 +haversine :: Float -> Float +haversine = (^ 2) . sin . (/ 2) -- The approximate distance, in kilometers, between two points on Earth. -- The latitude and longtitude are assumed to be in degrees. -earthDist = distDeg 6372.8 +earthDist :: (Float, Float) -> (Float, Float) -> Float +earthDist = distDeg 6371 + where + distDeg radius p1 p2 = distRad radius (deg2rad p1) (deg2rad p2) + distRad radius (lat1, lng1) (lat2, lng2) = + (2 * radius) * + asin + (min + 1.0 + (sqrt $ + haversine (lat2 - lat1) + + ((cos lat1 * cos lat2) * haversine (lng2 - lng1)))) + deg2rad = d2r *** d2r + where + d2r = (/ 180) . (pi *) -main = do - let bna = (36.12, -86.67) - lax = (33.94, -118.40) - dst = earthDist bna lax :: Double - printf "The distance between BNA and LAX is about %0.f km.\n" dst +main :: IO () +main = + printf + "The distance between BNA and LAX is about %0.f km.\n" + (earthDist bna lax) + where + bna = (36.12, -86.67) + lax = (33.94, -118.40) diff --git a/Task/Haversine-formula/jq/haversine-formula.jq b/Task/Haversine-formula/Jq/haversine-formula.jq similarity index 100% rename from Task/Haversine-formula/jq/haversine-formula.jq rename to Task/Haversine-formula/Jq/haversine-formula.jq diff --git a/Task/Haversine-formula/Kotlin/haversine-formula.kotlin b/Task/Haversine-formula/Kotlin/haversine-formula.kotlin index aa41bf051a..bd6e7ab72e 100644 --- a/Task/Haversine-formula/Kotlin/haversine-formula.kotlin +++ b/Task/Haversine-formula/Kotlin/haversine-formula.kotlin @@ -1,5 +1,3 @@ -package haversine - import java.lang.Math.* const val R = 6372.8 // in kilometers @@ -7,7 +5,7 @@ const val R = 6372.8 // in kilometers fun haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double { val λ1 = toRadians(lat1) val λ2 = toRadians(lat2) - val Δλ = toRadians(λ2 - λ1) + val Δλ = toRadians(lat2 - lat1) val Δφ = toRadians(lon2 - lon1) return 2 * R * asin(sqrt(pow(sin(Δλ / 2), 2.0) + pow(sin(Δφ / 2), 2.0) * cos(λ1) * cos(λ2))) } diff --git a/Task/Haversine-formula/MySQL/haversine-formula.sql b/Task/Haversine-formula/MySQL/haversine-formula.sql new file mode 100644 index 0000000000..2defcf033e --- /dev/null +++ b/Task/Haversine-formula/MySQL/haversine-formula.sql @@ -0,0 +1,26 @@ +DELIMITER $$ + +CREATE FUNCTION haversine ( + lat1 FLOAT, lon1 FLOAT, + lat2 FLOAT, lon2 FLOAT + ) RETURNS FLOAT + NO SQL DETERMINISTIC +BEGIN + DECLARE r FLOAT unsigned DEFAULT 6372.8; + DECLARE dLat FLOAT unsigned; + DECLARE dLon FLOAT unsigned; + DECLARE a FLOAT unsigned; + DECLARE c FLOAT unsigned; + + SET dLat = RADIANS(lat2 - lat1); + SET dLon = RADIANS(lon2 - lon1); + SET lat1 = RADIANS(lat1); + SET lat2 = RADIANS(lat2); + + SET a = POW(SIN(dLat / 2), 2) + COS(lat1) * COS(lat2) * POW(SIN(dLon / 2), 2); + SET c = 2 * ASIN(SQRT(a)); + + RETURN (r * c); +END$$ + +DELIMITER ; diff --git a/Task/Haversine-formula/OoRexx/haversine-formula.rexx b/Task/Haversine-formula/OoRexx/haversine-formula.rexx new file mode 100644 index 0000000000..94b1a7ae0f --- /dev/null +++ b/Task/Haversine-formula/OoRexx/haversine-formula.rexx @@ -0,0 +1,26 @@ +/*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) +kdist=format(dist/1 ,,2) /*show 2 digs past decimal point.*/ +mdist=format(dist/1.609344,,2) /* " " " " " " */ +ndist=format(mdist*5280/6076.1,,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----------*/ +surfaceDistance: arg th1,ph1,th2,ph2 /*use haversine formula for dist.*/ + radius = 6372.8 /*earth's mean radius in km */ + ph1 = ph1-ph2 + x = cos(ph1) * cos(th1) - cos(th2) + y = sin(ph1) * cos(th1) + z = sin(th1) - sin(th2) + return radius * 2 * aSin(sqrt(x**2+y**2+z**2)/2 ) + +cos: Return RxCalcCos(arg(1)) +sin: Return RxCalcSin(arg(1)) +asin: Return RxCalcArcSin(arg(1),,'R') +sqrt: Return RxCalcSqrt(arg(1)) +::requires rxMath library diff --git a/Task/Haversine-formula/Phix/haversine-formula.phix b/Task/Haversine-formula/Phix/haversine-formula.phix new file mode 100644 index 0000000000..42279a255e --- /dev/null +++ b/Task/Haversine-formula/Phix/haversine-formula.phix @@ -0,0 +1,13 @@ +constant MER = 6371 -- mean earth radius(km) +constant DEG_TO_RAD = PI/180 + +function haversine(atom lat1, long1, lat2, long2) + 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 + +atom d = haversine(36.12,-86.67,33.94,-118.4) +printf(1,"Distance is %f km (%f miles)\n",{d,d/1.609344}) diff --git a/Task/Haversine-formula/PureBasic/haversine-formula.purebasic b/Task/Haversine-formula/PureBasic/haversine-formula.purebasic new file mode 100644 index 0000000000..cbc9cfeb10 --- /dev/null +++ b/Task/Haversine-formula/PureBasic/haversine-formula.purebasic @@ -0,0 +1,21 @@ +#DIA=2*6372.8 + +Procedure.d Haversine(th1.d,ph1.d,th2.d,ph2.d) + Define dx.d, + dy.d, + dz.d + + ph1=Radian(ph1-ph2) + th1=Radian(th1) + th2=Radian(th2) + + dz=Sin(th1)-Sin(th2) + dx=Cos(ph1)*Cos(th1)-Cos(th2) + dy=Sin(ph1)*Cos(th1) + ProcedureReturn ASin(Sqr(Pow(dx,2)+Pow(dy,2)+Pow(dz,2))/2)*#DIA +EndProcedure + +OpenConsole("Haversine distance") +Print("Haversine distance: ") +Print(StrD(Haversine(36.12,-86.67,33.94,-118.4),7)+" km.") +Input() diff --git a/Task/Haversine-formula/REXX/haversine-formula-1.rexx b/Task/Haversine-formula/REXX/haversine-formula-1.rexx deleted file mode 100644 index fb8c6e1d08..0000000000 --- a/Task/Haversine-formula/REXX/haversine-formula-1.rexx +++ /dev/null @@ -1,65 +0,0 @@ -/*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 -$.= /*set defaults for subroutines. */ -dist=surfaceDistance(36.12, -86.67, 33.94, -118.4) -kdist=format(dist/1 ,,2) /*show 2 digs past decimal point.*/ -mdist=format(dist/1.609344,,2) /* " " " " " " */ -ndist=format(mdist*5280/6076.1,,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──────────*/ -surfaceDistance: arg th1,ph1,th2,ph2 /*use haversine formula for dist.*/ -numeric digits digits()*2 /*double the number of digits. */ -radius = 6372.8 /*earth's mean radius in km */ - ph1 = d2r(ph1-ph2) /*convert degs──►radians & reduce*/ - ph2 = d2r(ph2) /* " " " " " */ - th1 = d2r(th1) /* " " " " " */ - th2 = d2r(th2) - x = cos(ph1) * cos(th1) - cos(th2) - y = sin(ph1) * cos(th1) - z = sin(th1) - sin(th2) -return radius * 2 * aSin(sqrt(x**2+y**2+z**2)/2 ) -/*═════════════════════════════general 1-line subs══════════════════════*/ -d2d: return arg(1) // 360 /*normalize degrees. */ -d2r: return r2r(arg(1)*pi() / 180) /*normalize and convert deg──►rad*/ -r2d: return d2d((arg(1)*180 / pi())) /*normalize and convert rad──►deg*/ -r2r: return arg(1) // (2*pi()) /*normalize radians. */ -p: return word(arg(1),1) /*pick the first of two words. */ -pi: if $.pipi=='' then $.pipi=$pi(); return $.pipi /*return π.*/ - -aCos: procedure expose $.; arg x; if x<-1|x>1 then call $81r -1,1,x,"ACOS" - return .5*pi()-aSin(x) /*$81R says arg is out of range,*/ - /* and it isn't included here.*/ -aSin: procedure expose $.; parse arg x - if x<-1 | x>1 then call $81r -1,1,x,"ASIN"; s=x*x - if abs(x)>=.7 then return sign(x)*aCos(sqrt(1-s),'-ASIN') - z=x; o=x; p=z; do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1) - if z=p then leave; p=z; end; return z - -cos: procedure expose $.; parse arg x; x=r2r(x); a=abs(x) - numeric fuzz min(9,digits()-9); if a=pi() then return -1 - if a=pi()/2 | a=2*pi() then return 0; if a=pi()/3 then return .5 - if a=2*pi()/3 then return -.5; return .sinCos(1,1,-1) - -sin: procedure expose $.; parse arg x; x=r2r(x); - numeric fuzz min(5,digits()-3) - if abs(x)=pi() then return 0; return .sinCos(x,x,1) - -.sinCos: parse arg z,_,i; x=x*x; p=z; do k=2 by 2; _=-_*x/(k*(k+i)); z=z+_ - if z=p then leave; p=z; end; return z /*used by SIN & COS.*/ - -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits() - numeric digits 11; g=.sqrtGuess(); do j=0 while p>9; m.j=p; p=p%2+1; end - do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k; g=.5*(g+x/g);end - numeric digits d; return g/1 -.sqrtGuess: numeric form; m.=11; p=d+d%4+2 - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2 - -$pi: return , -'3.1415926535897932384626433832795028841971693993751058209749445923078'||, -'164062862089986280348253421170679821480865132823066470938446095505822'||, -'3172535940812848111745028410270193852110555964462294895493038196' diff --git a/Task/Haversine-formula/REXX/haversine-formula-2.rexx b/Task/Haversine-formula/REXX/haversine-formula-2.rexx deleted file mode 100644 index b8d0790a04..0000000000 --- a/Task/Haversine-formula/REXX/haversine-formula-2.rexx +++ /dev/null @@ -1,24 +0,0 @@ - ┌───────────────────────────────────────────────────────────────────────┐ - │ A note on built-in functions. REXX doesn't have a lot of mathmatical │ - │ or (particularly) trigomentric functions, so REXX programmers have │ - │ to write their own. Usually, this is done once, or most likely, one │ - │ is borrowed from another program. Knowing this, the one that is used │ - │ has a lot of boilerplate in it. Once coded and throughly debugged, I │ - │ put those commonly-used subroutines into the "1-line sub" section. │ - │ │ - │ Programming note: the "general 1-line" subroutines are taken from │ - │ other programs that I wrote, but I broke up their one line of source │ - │ so it can be viewed without shifting the viewing window. │ - │ │ - │ The "er 81" [which won't happen here] just shows an error telling │ - │ the legal range for ARCxxx functions (in this case: -1 ──► +1). │ - │ │ - │ Similarly, the SQRT function checks for a negative argument │ - │ [which again, won't happen here]. │ - │ │ - │ The pi constant (as used here) is actually a much more robust function│ - │ and will return up to one million digits in the real version. │ - │ │ - │ One bad side effect is that, like a automobile without a hood, you see│ - │ all the dirty stuff going on. Also, don't visit a sausage factory. │ - └───────────────────────────────────────────────────────────────────────┘ diff --git a/Task/Haversine-formula/Sidef/haversine-formula.sidef b/Task/Haversine-formula/Sidef/haversine-formula.sidef index 738d7f814e..543a5ec66b 100644 --- a/Task/Haversine-formula/Sidef/haversine-formula.sidef +++ b/Task/Haversine-formula/Sidef/haversine-formula.sidef @@ -1,17 +1,17 @@ class EarthPoint(lat, lon) { - const earth_radius = 6371; # mean earth radius - const radian_ratio = Math.pi/180; + const earth_radius = 6371 # mean earth radius + const radian_ratio = Num.pi/180 # accessors for radians - method latR { self.lat * radian_ratio }; - method lonR { self.lon * radian_ratio }; + method latR { self.lat * radian_ratio } + method lonR { self.lon * radian_ratio } method haversine_dist(EarthPoint p) { var arc = EarthPoint( self.lat - p.lat, self.lon - p.lon, - ); + ) var a = Math.sum( (arc.latR / 2).sin**2, @@ -19,11 +19,11 @@ class EarthPoint(lat, lon) { self.latR.cos * p.latR.cos ) - earth_radius * a.sqrt.asin * 2; + earth_radius * a.sqrt.asin * 2 } } -var BNA = EarthPoint.new(lat: 36.12, lon: -86.67); -var LAX = EarthPoint.new(lat: 33.94, lon: -118.4); +var BNA = EarthPoint.new(lat: 36.12, lon: -86.67) +var LAX = EarthPoint.new(lat: 33.94, lon: -118.4) -say BNA.haversine_dist(LAX); # => 2886.44444283798329974715782394574672 +say BNA.haversine_dist(LAX) #=> 2886.444442837983299747157823945746716... diff --git a/Task/Haversine-formula/Stata/haversine-formula-1.stata b/Task/Haversine-formula/Stata/haversine-formula-1.stata new file mode 100644 index 0000000000..5d83dc30b5 --- /dev/null +++ b/Task/Haversine-formula/Stata/haversine-formula-1.stata @@ -0,0 +1,17 @@ +program spheredist + version 15.0 + syntax varlist(min=4 max=4 numeric), GENerate(namelist max=1) /// + [Radius(real 6371) ALTitude(real 0) LABel(string)] + confirm new variable `generate' + local lat1 : word 1 of `varlist' + local lon1 : word 2 of `varlist' + local lat2 : word 3 of `varlist' + local lon2 : word 4 of `varlist' + local r=2*(`radius'+`altitude'/1000) + local k=_pi/180 + gen `generate'=`r'*asin(sqrt(sin((`lat2'-`lat1')*`k'/2)^2+ /// + cos(`lat1'*`k')*cos(`lat2'*`k')*sin((`lon2'-`lon1')*`k'/2)^2)) + if `"`label'"' != "" { + label variable `generate' `"`label'"' + } +end diff --git a/Task/Haversine-formula/Stata/haversine-formula-2.stata b/Task/Haversine-formula/Stata/haversine-formula-2.stata new file mode 100644 index 0000000000..dc9dd9fda2 --- /dev/null +++ b/Task/Haversine-formula/Stata/haversine-formula-2.stata @@ -0,0 +1,15 @@ +import delimited airports.csv, clear +format %9.4f l* +list + + +----------------------------------------------------------------------------------------------------+ + | iata airport city country lat lon | + |----------------------------------------------------------------------------------------------------| + 1. | AMS Amsterdam Airport Schiphol Amsterdam Netherlands 52.3086 4.7639 | + 2. | BNA Nashville International Airport Nashville United States 36.1245 -86.6782 | + 3. | CDG Charles de Gaulle International Airport Paris France 49.0128 2.5500 | + 4. | CGN Cologne Bonn Airport Cologne Germany 50.8659 7.1427 | + 5. | LAX Los Angeles International Airport Los Angeles United States 33.9425 -118.4080 | + |----------------------------------------------------------------------------------------------------| + 6. | MEM Memphis International Airport Memphis United States 35.0424 -89.9767 | + +----------------------------------------------------------------------------------------------------+ diff --git a/Task/Haversine-formula/Stata/haversine-formula-3.stata b/Task/Haversine-formula/Stata/haversine-formula-3.stata new file mode 100644 index 0000000000..9b859f79f4 --- /dev/null +++ b/Task/Haversine-formula/Stata/haversine-formula-3.stata @@ -0,0 +1,32 @@ +keep iata lat lon +rename (iata lat lon) =2 +gen k=0 +tempfile tmp +save "`tmp'" +rename *2 *1 +joinby k using `tmp' +drop if iata1>=iata2 +drop k +list + + +-----------------------------------------------------------+ + | iata1 lat1 lon1 iata2 lat2 lon2 | + |-----------------------------------------------------------| + 1. | AMS 52.3086 4.7639 BNA 36.1245 -86.6782 | + 2. | AMS 52.3086 4.7639 CGN 50.8659 7.1427 | + 3. | AMS 52.3086 4.7639 LAX 33.9425 -118.4080 | + 4. | AMS 52.3086 4.7639 CDG 49.0128 2.5500 | + 5. | AMS 52.3086 4.7639 MEM 35.0424 -89.9767 | + |-----------------------------------------------------------| + 6. | BNA 36.1245 -86.6782 CGN 50.8659 7.1427 | + 7. | BNA 36.1245 -86.6782 CDG 49.0128 2.5500 | + 8. | BNA 36.1245 -86.6782 LAX 33.9425 -118.4080 | + 9. | BNA 36.1245 -86.6782 MEM 35.0424 -89.9767 | + 10. | CDG 49.0128 2.5500 LAX 33.9425 -118.4080 | + |-----------------------------------------------------------| + 11. | CDG 49.0128 2.5500 MEM 35.0424 -89.9767 | + 12. | CDG 49.0128 2.5500 CGN 50.8659 7.1427 | + 13. | CGN 50.8659 7.1427 LAX 33.9425 -118.4080 | + 14. | CGN 50.8659 7.1427 MEM 35.0424 -89.9767 | + 15. | LAX 33.9425 -118.4080 MEM 35.0424 -89.9767 | + +-----------------------------------------------------------+ diff --git a/Task/Haversine-formula/Stata/haversine-formula-4.stata b/Task/Haversine-formula/Stata/haversine-formula-4.stata new file mode 100644 index 0000000000..787f2f5df7 --- /dev/null +++ b/Task/Haversine-formula/Stata/haversine-formula-4.stata @@ -0,0 +1,26 @@ +spheredist lat1 lon1 lat2 lon2, gen(dist) lab(Distance at sea level) +spheredist lat1 lon1 lat2 lon2, gen(fl350) alt(10680) lab(Distance at FL350 altitude) +format %9.2f dist fl350 +list iata* dist fl350 + + +-----------------------------------+ + | iata1 iata2 dist fl350 | + |-----------------------------------| + 1. | AMS CGN 229.64 230.03 | + 2. | AMS CDG 398.27 398.94 | + 3. | AMS MEM 7295.19 7307.56 | + 4. | AMS BNA 7004.61 7016.48 | + 5. | AMS LAX 8955.95 8971.13 | + |-----------------------------------| + 6. | BNA LAX 2886.32 2891.21 | + 7. | BNA CGN 7222.75 7234.99 | + 8. | BNA CDG 7018.39 7030.29 | + 9. | BNA MEM 321.62 322.16 | + 10. | CDG LAX 9102.51 9117.94 | + |-----------------------------------| + 11. | CDG CGN 387.82 388.48 | + 12. | CDG MEM 7317.82 7330.23 | + 13. | CGN LAX 9185.47 9201.04 | + 14. | CGN MEM 7514.96 7527.70 | + 15. | LAX MEM 2599.71 2604.12 | + +-----------------------------------+ diff --git a/Task/Haversine-formula/Swift/haversine-formula.swift b/Task/Haversine-formula/Swift/haversine-formula.swift index 9b696fe015..c3fff7a1be 100644 --- a/Task/Haversine-formula/Swift/haversine-formula.swift +++ b/Task/Haversine-formula/Swift/haversine-formula.swift @@ -1,10 +1,10 @@ import Foundation func haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double) -> Double { - let lat1rad = lat1 * M_PI/180 - let lon1rad = lon1 * M_PI/180 - let lat2rad = lat2 * M_PI/180 - let lon2rad = lon2 * M_PI/180 + let lat1rad = lat1 * Double.pi/180 + let lon1rad = lon1 * Double.pi/180 + let lat2rad = lat2 * Double.pi/180 + let lon2rad = lon2 * Double.pi/180 let dLat = lat2rad - lat1rad let dLon = lon2rad - lon1rad @@ -15,4 +15,4 @@ func haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double) -> Double { return R * c } -println(haversine(36.12, -86.67, 33.94, -118.40)) +print(haversine(lat1:36.12, lon1:-86.67, lat2:33.94, lon2:-118.40)) diff --git a/Task/Haversine-formula/TechBASIC/haversine-formula.techbasic b/Task/Haversine-formula/TechBASIC/haversine-formula.techbasic new file mode 100644 index 0000000000..40a5c2a777 --- /dev/null +++ b/Task/Haversine-formula/TechBASIC/haversine-formula.techbasic @@ -0,0 +1,30 @@ +FUNCTION HAVERSINE +!--------------------------------------------------------------- +!*** Haversine Formula - Calculate distances by LAT/LONG +! + +!*** LAT/LON of the two locations and Unit of measure are GLOBAL +!*** as they are defined in the main logic of the program, so they +!*** available for use in the Function. +!*** Usage: X=HAVERSINE + + + Radius=6378.137 + Lat1=(Lat1*MATH.PI/180) + Lon1=(Lon1*MATH.PI/180) + Lat2=(Lat2*MATH.PI/180) + Lon2=(Lon2*MATH.PI/180) + DLon=Lon1-Lon2 + ANSWER=ACOS(SIN(Lat1)*SIN(Lat2)+COS(Lat1)*COS(Lat2)*COS(DLon))*Radius + + DISTANCE="kilometers" + SELECT CASE UNIT + CASE "M" + HAVERSINE=ANSWER*0.621371192 + Distance="miles" + CASE "N" + HAVERSINE=ANSWER*0.539956803 + Distance="nautical miles" + END SELECT + +END FUNCTION diff --git a/Task/Haversine-formula/Zkl/haversine-formula.zkl b/Task/Haversine-formula/Zkl/haversine-formula.zkl new file mode 100644 index 0000000000..be4bc1bc68 --- /dev/null +++ b/Task/Haversine-formula/Zkl/haversine-formula.zkl @@ -0,0 +1,14 @@ +haversine(36.12, -86.67, 33.94, -118.40).println(); + +fcn haversine(Lat1, Long1, Lat2, Long2){ + const R = 6372.8; // In kilometers; + Diff_Lat := (Lat2 - Lat1) .toRad(); + Diff_Long := (Long2 - Long1).toRad(); + NLat := Lat1.toRad(); + NLong := Lat2.toRad(); + A := (Diff_Lat/2) .sin().pow(2) + + (Diff_Long/2).sin().pow(2) * + NLat.cos() * NLong.cos(); + C := 2.0 * A.sqrt().asin(); + R*C; +} diff --git a/Task/Hello-world-Graphical/BaCon/hello-world-graphical.bacon b/Task/Hello-world-Graphical/BaCon/hello-world-graphical.bacon new file mode 100644 index 0000000000..e5515beba6 --- /dev/null +++ b/Task/Hello-world-Graphical/BaCon/hello-world-graphical.bacon @@ -0,0 +1,11 @@ +REM GUI greeting + +INCLUDE "hug.bac" + +mainwindow = WINDOW("BaCon greeting", 225, 40) + +greeting = ENTRY("Goodbye, World!", 115, 30) +ATTACH(mainwindow, greeting, 5, 5) + +REM gtk event loop... +DISPLAY diff --git a/Task/Hello-world-Graphical/COBOL/hello-world-graphical-4.cobol b/Task/Hello-world-Graphical/COBOL/hello-world-graphical-4.cobol index 32f523ea75..3865c89666 100644 --- a/Task/Hello-world-Graphical/COBOL/hello-world-graphical-4.cobol +++ b/Task/Hello-world-Graphical/COBOL/hello-world-graphical-4.cobol @@ -1,19 +1,62 @@ - program-id. ghello. - data division. - working-storage section. - 01 var pic x(1). - 01 lynz pic 9(3). - 01 colz pic 9(3). - 01 msg pic x(15) value "Goodbye, world!". - procedure division. - accept lynz from lines end-accept - divide lynz by 2 giving lynz. - accept colz from columns end-accept - divide colz by 2 giving colz. - subtract 7 from colz giving colz. - display msg - at line number lynz - column number colz - end-display - accept var end-accept - stop run. + *> + *> cobweb-gui-hello, using gtk-label + *> Tectonics: + *> cobc -w -xj cobweb-gui-hello.cob cobweb-gtk.cob \ + *> `pkg-config --libs gtk+-3.0` + *> + identification division. + program-id. cobweb-gui-hello. + + environment division. + configuration section. + repository. + function new-window + function new-box + function new-label + function gtk-go + function all intrinsic. + + data division. + working-storage section. + + 01 TOPLEVEL usage binary-long value 0. + 01 HORIZONTAL usage binary-long value 0. + 01 VERTICAL usage binary-long value 1. + + 01 width-hint usage binary-long value 160. + 01 height-hint usage binary-long value 16. + + 01 spacing usage binary-long value 8. + 01 homogeneous usage binary-long value 0. + + 01 extraneous usage binary-long. + + 01 gtk-window-data. + 05 gtk-window usage pointer. + 01 gtk-container-data. + 05 gtk-container usage pointer. + + 01 gtk-box-data. + 05 gtk-box usage pointer. + 01 gtk-label-data. + 05 gtk-label usage pointer. + + procedure division. + cobweb-hello-main. + + *> Main window and top level container + move new-window("Hello", TOPLEVEL, width-hint, height-hint) + to gtk-window-data + move new-box(gtk-window, VERTICAL, spacing, homogeneous) + to gtk-container-data + + *> Box, across, with simple label + move new-box(gtk-container, HORIZONTAL, spacing, homogeneous) + to gtk-box-data + move new-label(gtk-box, "Goodbye, World!") to gtk-label-data + + *> GTK+ event loop now takes over + move gtk-go(gtk-window) to extraneous + + goback. + end program cobweb-gui-hello. diff --git a/Task/Hello-world-Graphical/COBOL/hello-world-graphical-5.cobol b/Task/Hello-world-Graphical/COBOL/hello-world-graphical-5.cobol new file mode 100644 index 0000000000..32f523ea75 --- /dev/null +++ b/Task/Hello-world-Graphical/COBOL/hello-world-graphical-5.cobol @@ -0,0 +1,19 @@ + program-id. ghello. + data division. + working-storage section. + 01 var pic x(1). + 01 lynz pic 9(3). + 01 colz pic 9(3). + 01 msg pic x(15) value "Goodbye, world!". + procedure division. + accept lynz from lines end-accept + divide lynz by 2 giving lynz. + accept colz from columns end-accept + divide colz by 2 giving colz. + subtract 7 from colz giving colz. + display msg + at line number lynz + column number colz + end-display + accept var end-accept + stop run. diff --git a/Task/Hello-world-Graphical/EC/hello-world-graphical-1.ec b/Task/Hello-world-Graphical/EC/hello-world-graphical-1.ec new file mode 100644 index 0000000000..8915eedb25 --- /dev/null +++ b/Task/Hello-world-Graphical/EC/hello-world-graphical-1.ec @@ -0,0 +1,2 @@ +import "ecere" +MessageBox goodBye { contents = "Goodbye, World!" }; diff --git a/Task/Hello-world-Graphical/EC/hello-world-graphical-2.ec b/Task/Hello-world-Graphical/EC/hello-world-graphical-2.ec new file mode 100644 index 0000000000..885a81465f --- /dev/null +++ b/Task/Hello-world-Graphical/EC/hello-world-graphical-2.ec @@ -0,0 +1,2 @@ +import "ecere" +Label label { text = "Goodbye, World!", hasClose = true, opacity = 1, size = { 320, 200 } }; diff --git a/Task/Hello-world-Graphical/EC/hello-world-graphical-3.ec b/Task/Hello-world-Graphical/EC/hello-world-graphical-3.ec new file mode 100644 index 0000000000..2093859790 --- /dev/null +++ b/Task/Hello-world-Graphical/EC/hello-world-graphical-3.ec @@ -0,0 +1,15 @@ +import "ecere" + +class GoodByeForm : Window +{ + text = "Goodbye, World!"; + size = { 320, 200 }; + hasClose = true; + + void OnRedraw(Surface surface) + { + surface.WriteTextf(10, 10, "Goodbye, World!"); + } +} + +GoodByeForm form {}; diff --git a/Task/Hello-world-Graphical/Elena/hello-world-graphical.elena b/Task/Hello-world-Graphical/Elena/hello-world-graphical.elena index 928a1a4f33..f1981c1bc2 100644 --- a/Task/Hello-world-Graphical/Elena/hello-world-graphical.elena +++ b/Task/Hello-world-Graphical/Elena/hello-world-graphical.elena @@ -1,31 +1,33 @@ -#import forms. -#import system. +import forms. -#class Window :: SDIDialog +class Window :: SDIDialog { - #field goodByeWorldLabel. - #field closeButton. + object goodByeWorldLabel. + object closeButton. - #constructor new <= (new) + constructor new + <= new; [ goodByeWorldLabel := Label new. closeButton := Button new. - theControls append:goodByeWorldLabel. - theControls append:closeButton. + theControls + append:goodByeWorldLabel; + append:closeButton. - $self set &x:250 &y:200. - $self set &width:200 &height:110. + $self + set x:250 y:200; + set width:200 height:110. - goodByeWorldLabel set &x:40 &y:10. - goodByeWorldLabel set &width:150 &height:30. - goodByeWorldLabel set &caption:"Goodbye, World!". + goodByeWorldLabel + set x:40 y:10; + set width:150 height:30; + set caption:"Goodbye, World!". - closeButton set &x:20 &y:40. - closeButton set &width:150 &height:30. - closeButton set &caption:"Close". - - closeButton set &onClick:args - [ 'program stop. ]. + closeButton + set x:20 y:40; + set width:150 height:30; + set caption:"Close"; + set onClick(:args)[ 'program stop ] ] } diff --git a/Task/Hello-world-Graphical/HicEst/hello-world-graphical-1.hicest b/Task/Hello-world-Graphical/HicEst/hello-world-graphical-1.hicest deleted file mode 100644 index 3888b21856..0000000000 --- a/Task/Hello-world-Graphical/HicEst/hello-world-graphical-1.hicest +++ /dev/null @@ -1 +0,0 @@ -WRITE(Messagebox='!') 'Goodbye, World!' diff --git a/Task/Hello-world-Graphical/HicEst/hello-world-graphical-2.hicest b/Task/Hello-world-Graphical/HicEst/hello-world-graphical-2.hicest deleted file mode 100644 index 6343cb20aa..0000000000 --- a/Task/Hello-world-Graphical/HicEst/hello-world-graphical-2.hicest +++ /dev/null @@ -1,6 +0,0 @@ -link graphics -procedure main() - WOpen("size=100,20") | stop("No window") - WWrites("Goodbye, World!") - WDone() -end diff --git a/Task/Hello-world-Graphical/HicEst/hello-world-graphical-3.hicest b/Task/Hello-world-Graphical/HicEst/hello-world-graphical-3.hicest deleted file mode 100644 index fce8c59d05..0000000000 --- a/Task/Hello-world-Graphical/HicEst/hello-world-graphical-3.hicest +++ /dev/null @@ -1,21 +0,0 @@ -import gui -$include "guih.icn" - -class WindowApp : Dialog () - - # -- automatically called when the dialog is created - method component_setup () - # add 'hello world' label - label := Label("label=Hello world","pos=0,0") - add (label) - - # make sure we respond to close event - connect(self, "dispose", CLOSE_BUTTON_EVENT) - end -end - -# create and show the window -procedure main () - w := WindowApp () - w.show_modal () -end diff --git a/Task/Hello-world-Graphical/IWBASIC/hello-world-graphical.iwbasic b/Task/Hello-world-Graphical/IWBASIC/hello-world-graphical.iwbasic new file mode 100644 index 0000000000..0098cfbe42 --- /dev/null +++ b/Task/Hello-world-Graphical/IWBASIC/hello-world-graphical.iwbasic @@ -0,0 +1,23 @@ +DEF Win:WINDOW +DEF Close:CHAR +DEF ScreenSizeX,ScreenSizeY:UINT + +GETSCREENSIZE(ScreenSizeX,ScreenSizeY) + +OPENWINDOW Win,0,0,ScreenSizeX,ScreenSizeY,NULL,NULL,"Goodbye program",&MainHandler + +PRINT Win,"Goodbye, World!" +'Prints in upper left corner of the window (position 0,0). + +WAITUNTIL Close=1 + +CLOSEWINDOW Win + +END + +SUB MainHandler + + IF @MESSAGE=@IDCLOSEWINDOW THEN Close=1 + +RETURN +ENDSUB diff --git a/Task/Hello-world-Graphical/jq/hello-world-graphical-1.jq b/Task/Hello-world-Graphical/Jq/hello-world-graphical-1.jq similarity index 100% rename from Task/Hello-world-Graphical/jq/hello-world-graphical-1.jq rename to Task/Hello-world-Graphical/Jq/hello-world-graphical-1.jq diff --git a/Task/Hello-world-Graphical/jq/hello-world-graphical-2.jq b/Task/Hello-world-Graphical/Jq/hello-world-graphical-2.jq similarity index 100% rename from Task/Hello-world-Graphical/jq/hello-world-graphical-2.jq rename to Task/Hello-world-Graphical/Jq/hello-world-graphical-2.jq diff --git a/Task/Hello-world-Graphical/MIRC-Scripting-Language/hello-world-graphical.mirc b/Task/Hello-world-Graphical/MIRC-Scripting-Language/hello-world-graphical.mirc new file mode 100644 index 0000000000..350d542b61 --- /dev/null +++ b/Task/Hello-world-Graphical/MIRC-Scripting-Language/hello-world-graphical.mirc @@ -0,0 +1,10 @@ +alias goodbyegui { + dialog -m Goodbye Goodbye +} + +dialog Goodbye { + title "Goodbye, World!" + size -1 -1 80 20 + option dbu + text "Goodbye, World!", 1, 20 6 41 7 +} diff --git a/Task/Hello-world-Graphical/NewLISP/hello-world-graphical.newlisp b/Task/Hello-world-Graphical/NewLISP/hello-world-graphical.newlisp new file mode 100644 index 0000000000..99e0dc0bb9 --- /dev/null +++ b/Task/Hello-world-Graphical/NewLISP/hello-world-graphical.newlisp @@ -0,0 +1,23 @@ +; hello-gui.lsp +; oofoe 2012-01-18 + +; Initialize GUI server. +(load (append (env "NEWLISPDIR") "/guiserver.lsp")) +(gs:init) + +; Create window frame. +(gs:frame 'Goodbye 100 100 300 200 "Goodbye!") +(gs:set-resizable 'Goodbye nil) +(gs:set-flow-layout 'Goodbye "center") + +; Add final message. +(gs:label 'Message "Goodbye, World!" "center") +(gs:add-to 'Goodbye 'Message) + +; Show frame. +(gs:set-visible 'Goodbye true) + +; Start event loop. +(gs:listen) + +(exit) ; NewLisp normally goes to listener after running script. diff --git a/Task/Hello-world-Graphical/Phix/hello-world-graphical.phix b/Task/Hello-world-Graphical/Phix/hello-world-graphical.phix index 2eb60c7ea3..fc5449c71a 100644 --- a/Task/Hello-world-Graphical/Phix/hello-world-graphical.phix +++ b/Task/Hello-world-Graphical/Phix/hello-world-graphical.phix @@ -1,4 +1,4 @@ include pGUI.e -IupOpen("demo/pGUI/") +IupOpen() IupMessage("Bye","Goodbye, World!") IupClose() diff --git a/Task/Hello-world-Graphical/Scilab/hello-world-graphical.scilab b/Task/Hello-world-Graphical/Scilab/hello-world-graphical.scilab new file mode 100644 index 0000000000..134e4efd3f --- /dev/null +++ b/Task/Hello-world-Graphical/Scilab/hello-world-graphical.scilab @@ -0,0 +1 @@ +messagebox("Goodbye, World!") diff --git a/Task/Hello-world-Graphical/Stata/hello-world-graphical.stata b/Task/Hello-world-Graphical/Stata/hello-world-graphical.stata new file mode 100644 index 0000000000..9f835387c5 --- /dev/null +++ b/Task/Hello-world-Graphical/Stata/hello-world-graphical.stata @@ -0,0 +1 @@ +window stopbox note "Goodbye, World!" diff --git a/Task/Hello-world-Graphical/TXR/hello-world-graphical.txr b/Task/Hello-world-Graphical/TXR/hello-world-graphical.txr new file mode 100644 index 0000000000..e1bb34b871 --- /dev/null +++ b/Task/Hello-world-Graphical/TXR/hello-world-graphical.txr @@ -0,0 +1,4 @@ +(with-dyn-lib "user32.dll" + (deffi messagebox "MessageBoxW" int (cptr wstr wstr uint))) + +(messagebox cptr-null "Hello" "World" 0) ;; 0 is MB_OK diff --git a/Task/Hello-world-Graphical/Zkl/hello-world-graphical.zkl b/Task/Hello-world-Graphical/Zkl/hello-world-graphical.zkl new file mode 100644 index 0000000000..1e32cac61d --- /dev/null +++ b/Task/Hello-world-Graphical/Zkl/hello-world-graphical.zkl @@ -0,0 +1,3 @@ +System.cmd(0'|zenity --info --text="Goodbye, World!"|); // GTK+ pop up +System.cmd(0'|notify-send "Goodbye, World!"|); // desktop notification +System.cmd(0'|xmessage -buttons Ok:0,"Not sure":1,Cancel:2 -default Ok -nearmouse "Goodbye, World!" -timeout 10|); // X Windows dialog diff --git a/Task/Hello-world-Line-printer/BASIC/hello-world-line-printer.basic b/Task/Hello-world-Line-printer/BASIC/hello-world-line-printer-1.basic similarity index 100% rename from Task/Hello-world-Line-printer/BASIC/hello-world-line-printer.basic rename to Task/Hello-world-Line-printer/BASIC/hello-world-line-printer-1.basic diff --git a/Task/Hello-world-Line-printer/BASIC/hello-world-line-printer-2.basic b/Task/Hello-world-Line-printer/BASIC/hello-world-line-printer-2.basic new file mode 100644 index 0000000000..6f9b58724e --- /dev/null +++ b/Task/Hello-world-Line-printer/BASIC/hello-world-line-printer-2.basic @@ -0,0 +1,8 @@ +' Hello, printer +READ msg$ +DATA "Hello World!\n" + +' Assume printer is on /dev/lp0 +OPEN "/dev/lp0" FOR DEVICE AS printer +PUTBYTE msg$ TO printer SIZE LEN(msg$) +CLOSE DEVICE printer diff --git a/Task/Hello-world-Line-printer/Common-Lisp/hello-world-line-printer.lisp b/Task/Hello-world-Line-printer/Common-Lisp/hello-world-line-printer.lisp new file mode 100644 index 0000000000..a554b70b07 --- /dev/null +++ b/Task/Hello-world-Line-printer/Common-Lisp/hello-world-line-printer.lisp @@ -0,0 +1,7 @@ +(defun main () + (with-open-file (stream "/dev/lp0" + :direction :output + :if-exists :append) + (format stream "Hello World~%"))) + +(main) diff --git a/Task/Hello-world-Line-printer/EDSAC-order-code/hello-world-line-printer.edsac b/Task/Hello-world-Line-printer/EDSAC-order-code/hello-world-line-printer.edsac new file mode 100644 index 0000000000..3ef70017f2 --- /dev/null +++ b/Task/Hello-world-Line-printer/EDSAC-order-code/hello-world-line-printer.edsac @@ -0,0 +1,61 @@ +[ Hello world + =========== + + A program for the EDSAC + + Can be used to print any character string: + the string (including necessary *F and #F + characters) should be stored in sequential + memory addresses beginning at @+17. + + The last character of the string should be + marked with a 1 in the least significant + bit. This can be coded by using D in place + of F, e.g. AD would be an 'A' as the last + character + + Works with Initial Orders 2 ] + + T56K + GK + +[ 0 ] O17@ [ Print character ] + +[ 1 ] H17@ [ AND character with 1: ] + C15@ [ if the result is 1, we ] + S15@ [ have reached the end ] + E13@ [ of the string ] + + T14@ [ Modify the orders in ] + A@ [ addresses @+0 and @+1 ] + A16@ [ to point to the next ] + T@ [ character ] + A1@ + A16@ + T1@ + E@ + +[ 13 ] ZF + +[ 14 ] PF +[ 15 ] PD +[ 16 ] P1F [ NB Least significant bit + is not part of address, + so add 2 not 1 ] + +[ 17 ] *F [ Letter shift ] + HF + EF + LF + LF + OF + !F [ Blank ] + WF + OF + RF + LF + DF + @F [ Carriage return ] + &D [ Line feed + 1 ] + + EZPF diff --git a/Task/Hello-world-Line-printer/Kotlin/hello-world-line-printer.kotlin b/Task/Hello-world-Line-printer/Kotlin/hello-world-line-printer.kotlin new file mode 100644 index 0000000000..91dbc1f054 --- /dev/null +++ b/Task/Hello-world-Line-printer/Kotlin/hello-world-line-printer.kotlin @@ -0,0 +1,6 @@ +import java.io.File + +fun main(args: Array) { + val text = "Hello World!\n" + File("/dev/lp0").writeText(text) +} diff --git a/Task/Hello-world-Line-printer/Sidef/hello-world-line-printer.sidef b/Task/Hello-world-Line-printer/Sidef/hello-world-line-printer.sidef index 55376fe8b2..830d05daf1 100644 --- a/Task/Hello-world-Line-printer/Sidef/hello-world-line-printer.sidef +++ b/Task/Hello-world-Line-printer/Sidef/hello-world-line-printer.sidef @@ -1,3 +1,3 @@ -Sys.open(\var fh, '>', '/dev/lp0') - && fh.println("Hello World!") - && fh.close; +Sys.open(\var fh, '>', '/dev/lp0') \ + && fh.say("Hello World!") \ + && fh.close diff --git a/Task/Hello-world-Newbie/00DESCRIPTION b/Task/Hello-world-Newbie/00DESCRIPTION index 87543fa777..5a4972ca5b 100644 --- a/Task/Hello-world-Newbie/00DESCRIPTION +++ b/Task/Hello-world-Newbie/00DESCRIPTION @@ -1,4 +1,4 @@ -{{omit from|ABAP|There's no newbie frienly way to install ABAP. It's part of the enterprise NetWeaver Application Server.}} +{{omit from|ABAP|There's no newbie friendly way to install ABAP. It's part of the enterprise NetWeaver Application Server.}} ;Task: Guide a new user of a language through the steps necessary diff --git a/Task/Hello-world-Newbie/Java/hello-world-newbie.java b/Task/Hello-world-Newbie/Java/hello-world-newbie.java new file mode 100644 index 0000000000..214f8e71de --- /dev/null +++ b/Task/Hello-world-Newbie/Java/hello-world-newbie.java @@ -0,0 +1,7 @@ +public class HelloWorld { + + public static void main(String[] args) { + System.out.println("Hello world!"); + } + +} diff --git a/Task/Hello-world-Newbie/jq/hello-world-newbie-1.jq b/Task/Hello-world-Newbie/Jq/hello-world-newbie-1.jq similarity index 100% rename from Task/Hello-world-Newbie/jq/hello-world-newbie-1.jq rename to Task/Hello-world-Newbie/Jq/hello-world-newbie-1.jq diff --git a/Task/Hello-world-Newbie/jq/hello-world-newbie-2.jq b/Task/Hello-world-Newbie/Jq/hello-world-newbie-2.jq similarity index 100% rename from Task/Hello-world-Newbie/jq/hello-world-newbie-2.jq rename to Task/Hello-world-Newbie/Jq/hello-world-newbie-2.jq diff --git a/Task/Hello-world-Newbie/jq/hello-world-newbie-3.jq b/Task/Hello-world-Newbie/Jq/hello-world-newbie-3.jq similarity index 100% rename from Task/Hello-world-Newbie/jq/hello-world-newbie-3.jq rename to Task/Hello-world-Newbie/Jq/hello-world-newbie-3.jq diff --git a/Task/Hello-world-Newbie/jq/hello-world-newbie-4.jq b/Task/Hello-world-Newbie/Jq/hello-world-newbie-4.jq similarity index 100% rename from Task/Hello-world-Newbie/jq/hello-world-newbie-4.jq rename to Task/Hello-world-Newbie/Jq/hello-world-newbie-4.jq diff --git a/Task/Hello-world-Newbie/jq/hello-world-newbie-5.jq b/Task/Hello-world-Newbie/Jq/hello-world-newbie-5.jq similarity index 100% rename from Task/Hello-world-Newbie/jq/hello-world-newbie-5.jq rename to Task/Hello-world-Newbie/Jq/hello-world-newbie-5.jq diff --git a/Task/Hello-world-Newbie/jq/hello-world-newbie-6.jq b/Task/Hello-world-Newbie/Jq/hello-world-newbie-6.jq similarity index 100% rename from Task/Hello-world-Newbie/jq/hello-world-newbie-6.jq rename to Task/Hello-world-Newbie/Jq/hello-world-newbie-6.jq diff --git a/Task/Hello-world-Newbie/Kotlin/hello-world-newbie.kotlin b/Task/Hello-world-Newbie/Kotlin/hello-world-newbie.kotlin new file mode 100644 index 0000000000..0b69e213e7 --- /dev/null +++ b/Task/Hello-world-Newbie/Kotlin/hello-world-newbie.kotlin @@ -0,0 +1,3 @@ +fun main(args: Array) { + println("Hello, World!") +} diff --git a/Task/Hello-world-Newbie/Maple/hello-world-newbie.maple b/Task/Hello-world-Newbie/Maple/hello-world-newbie.maple new file mode 100644 index 0000000000..b27882bd89 --- /dev/null +++ b/Task/Hello-world-Newbie/Maple/hello-world-newbie.maple @@ -0,0 +1 @@ +"Hello World"; diff --git a/Task/Hello-world-Newbie/Nim/hello-world-newbie.nim b/Task/Hello-world-Newbie/Nim/hello-world-newbie.nim new file mode 100644 index 0000000000..f42ff39593 --- /dev/null +++ b/Task/Hello-world-Newbie/Nim/hello-world-newbie.nim @@ -0,0 +1 @@ +echo "Hello world!" diff --git a/Task/Hello-world-Newbie/Phix/hello-world-newbie-1.phix b/Task/Hello-world-Newbie/Phix/hello-world-newbie-1.phix new file mode 100644 index 0000000000..99c2263e7c --- /dev/null +++ b/Task/Hello-world-Newbie/Phix/hello-world-newbie-1.phix @@ -0,0 +1 @@ +puts(1,"Hello world!") diff --git a/Task/Hello-world-Newbie/Phix/hello-world-newbie-2.phix b/Task/Hello-world-Newbie/Phix/hello-world-newbie-2.phix new file mode 100644 index 0000000000..99c2263e7c --- /dev/null +++ b/Task/Hello-world-Newbie/Phix/hello-world-newbie-2.phix @@ -0,0 +1 @@ +puts(1,"Hello world!") diff --git a/Task/Hello-world-Newbie/Ruby/hello-world-newbie.rb b/Task/Hello-world-Newbie/Ruby/hello-world-newbie.rb new file mode 100644 index 0000000000..b6a27ca0ba --- /dev/null +++ b/Task/Hello-world-Newbie/Ruby/hello-world-newbie.rb @@ -0,0 +1 @@ + puts "Hello World!!" diff --git a/Task/Hello-world-Newline-omission/Agena/hello-world-newline-omission.agena b/Task/Hello-world-Newline-omission/Agena/hello-world-newline-omission.agena new file mode 100644 index 0000000000..4228bea36e --- /dev/null +++ b/Task/Hello-world-Newline-omission/Agena/hello-world-newline-omission.agena @@ -0,0 +1 @@ +io.write( "Goodbye, World!" ) diff --git a/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-2.basic b/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-2.basic index 6f3e0b2530..d057c09072 100644 --- a/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-2.basic +++ b/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-2.basic @@ -1 +1,2 @@ -PRINT "GOODBYE, WORLD!"; +PRINT "Goodbye, World!"; +PRINT "Goodbye, World!" FORMAT "%s" diff --git a/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-3.basic b/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-3.basic new file mode 100644 index 0000000000..6f3e0b2530 --- /dev/null +++ b/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-3.basic @@ -0,0 +1 @@ +PRINT "GOODBYE, WORLD!"; diff --git a/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-4.basic b/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-4.basic new file mode 100644 index 0000000000..212a2b6378 --- /dev/null +++ b/Task/Hello-world-Newline-omission/BASIC/hello-world-newline-omission-4.basic @@ -0,0 +1,7 @@ +10 print chr$(14) : rem Switch to lower+uppercase character set +20 print "Goodbye, World!"; +30 rem * If we end this program here, we will not see the effect because +40 rem BASIC will print 'READY' at a new line anyway. +50 rem * So, we just print additional message... +60 print "(End of the world)" +70 end diff --git a/Task/Hello-world-Newline-omission/Beeswax/hello-world-newline-omission.beeswax b/Task/Hello-world-Newline-omission/Beeswax/hello-world-newline-omission.beeswax new file mode 100644 index 0000000000..ae4afc268c --- /dev/null +++ b/Task/Hello-world-Newline-omission/Beeswax/hello-world-newline-omission.beeswax @@ -0,0 +1 @@ +_`Goodbye, World! diff --git a/Task/Hello-world-Newline-omission/Gecho/hello-world-newline-omission.gecho b/Task/Hello-world-Newline-omission/Gecho/hello-world-newline-omission.gecho new file mode 100644 index 0000000000..605a385305 --- /dev/null +++ b/Task/Hello-world-Newline-omission/Gecho/hello-world-newline-omission.gecho @@ -0,0 +1 @@ +'Hello, <> 'world! print diff --git a/Task/Hello-world-Newline-omission/IWBASIC/hello-world-newline-omission.iwbasic b/Task/Hello-world-Newline-omission/IWBASIC/hello-world-newline-omission.iwbasic new file mode 100644 index 0000000000..8672bfc54e --- /dev/null +++ b/Task/Hello-world-Newline-omission/IWBASIC/hello-world-newline-omission.iwbasic @@ -0,0 +1,46 @@ +'In a window + +DEF Win:WINDOW +DEF Close:CHAR +DEF ScreenSizeX,ScreenSizeY:UINT + +GETSCREENSIZE(ScreenSizeX,ScreenSizeY) + +OPENWINDOW Win,0,0,ScreenSizeX,ScreenSizeY,NULL,NULL,"Goodbye program",&MainHandler + +PRINT Win,"Goodbye, World!" +'Prints in upper left corner of the window (position 0,0). +PRINT Win," You won't have this program to kick around anymore." + +'There does not appear to be a means of starting a new line when printing in a window, other than by using the MOVE command. +'Therefore, both sentences here will print on the same line, i.e., in the same vertical position. + +WAITUNTIL Close=1 + +CLOSEWINDOW Win + +END + +SUB MainHandler + + IF @MESSAGE=@IDCLOSEWINDOW THEN Close=1 + +RETURN +ENDSUB + +'In the console + +OPENCONSOLE + +'by inserting a trailing comma. +PRINT"Goodbye, World!", +PRINT" You won't have this program to kick around anymore." + +PRINT:PRINT + +'A press any key to continue message is automatic in a program compiled as console only. +'I presume the compiler adds the code. +CLOSECONSOLE + +'Since this an IWBASIC console program. +END diff --git a/Task/Hello-world-Newline-omission/jq/hello-world-newline-omission-1.jq b/Task/Hello-world-Newline-omission/Jq/hello-world-newline-omission-1.jq similarity index 100% rename from Task/Hello-world-Newline-omission/jq/hello-world-newline-omission-1.jq rename to Task/Hello-world-Newline-omission/Jq/hello-world-newline-omission-1.jq diff --git a/Task/Hello-world-Newline-omission/jq/hello-world-newline-omission-2.jq b/Task/Hello-world-Newline-omission/Jq/hello-world-newline-omission-2.jq similarity index 100% rename from Task/Hello-world-Newline-omission/jq/hello-world-newline-omission-2.jq rename to Task/Hello-world-Newline-omission/Jq/hello-world-newline-omission-2.jq diff --git a/Task/Hello-world-Newline-omission/M4/hello-world-newline-omission.m4 b/Task/Hello-world-Newline-omission/M4/hello-world-newline-omission.m4 new file mode 100644 index 0000000000..35eab709bd --- /dev/null +++ b/Task/Hello-world-Newline-omission/M4/hello-world-newline-omission.m4 @@ -0,0 +1 @@ +`Goodbye, World!'dnl diff --git a/Task/Hello-world-Newline-omission/MIRC-Scripting-Language/hello-world-newline-omission.mirc b/Task/Hello-world-Newline-omission/MIRC-Scripting-Language/hello-world-newline-omission.mirc new file mode 100644 index 0000000000..b065462966 --- /dev/null +++ b/Task/Hello-world-Newline-omission/MIRC-Scripting-Language/hello-world-newline-omission.mirc @@ -0,0 +1 @@ +echo -ag Goodbye, World! diff --git a/Task/Hello-world-Newline-omission/Scilab/hello-world-newline-omission.scilab b/Task/Hello-world-Newline-omission/Scilab/hello-world-newline-omission.scilab new file mode 100644 index 0000000000..b4f3181031 --- /dev/null +++ b/Task/Hello-world-Newline-omission/Scilab/hello-world-newline-omission.scilab @@ -0,0 +1 @@ +print("Goodbye, World!") diff --git a/Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-1.sql b/Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-1.sql index 4920e98776..a6af4e4a19 100644 --- a/Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-1.sql +++ b/Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-1.sql @@ -1 +1 @@ - PRINT 'Goodby, World!' + PRINT 'Goodbye, World!' diff --git a/Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-2.sql b/Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-2.sql index e5f6de5326..58c23fc4c2 100644 --- a/Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-2.sql +++ b/Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-2.sql @@ -1 +1 @@ - select 'Goodby, World!' + select 'Goodbye, World!' diff --git a/Task/Hello-world-Newline-omission/Zkl/hello-world-newline-omission.zkl b/Task/Hello-world-Newline-omission/Zkl/hello-world-newline-omission.zkl new file mode 100644 index 0000000000..80cdf6ed01 --- /dev/null +++ b/Task/Hello-world-Newline-omission/Zkl/hello-world-newline-omission.zkl @@ -0,0 +1,2 @@ +print("Goodbye, World!"); +Console.write("Goodbye, World!"); diff --git a/Task/Hello-world-Standard-error/Agena/hello-world-standard-error.agena b/Task/Hello-world-Standard-error/Agena/hello-world-standard-error.agena new file mode 100644 index 0000000000..cdea7ffd33 --- /dev/null +++ b/Task/Hello-world-Standard-error/Agena/hello-world-standard-error.agena @@ -0,0 +1 @@ +io.write( io.stderr, "Goodbye, World!\n" ) diff --git a/Task/Hello-world-Standard-error/BASIC/hello-world-standard-error-1.basic b/Task/Hello-world-Standard-error/BASIC/hello-world-standard-error-1.basic new file mode 100644 index 0000000000..91db79d131 --- /dev/null +++ b/Task/Hello-world-Standard-error/BASIC/hello-world-standard-error-1.basic @@ -0,0 +1 @@ +EPRINT "Goodbye, World!" diff --git a/Task/Hello-world-Standard-error/BASIC/hello-world-standard-error.basic b/Task/Hello-world-Standard-error/BASIC/hello-world-standard-error-2.basic similarity index 100% rename from Task/Hello-world-Standard-error/BASIC/hello-world-standard-error.basic rename to Task/Hello-world-Standard-error/BASIC/hello-world-standard-error-2.basic diff --git a/Task/Hello-world-Standard-error/C++/hello-world-standard-error.cpp b/Task/Hello-world-Standard-error/C++/hello-world-standard-error.cpp index 8089af8f0a..7f85cc6602 100644 --- a/Task/Hello-world-Standard-error/C++/hello-world-standard-error.cpp +++ b/Task/Hello-world-Standard-error/C++/hello-world-standard-error.cpp @@ -1,5 +1,5 @@ #include -int main () { - std::cerr << "Goodbye, World!" << std::endl; +int main() { + std::cerr << "Goodbye, World!\n"; } diff --git a/Task/Hello-world-Standard-error/jq/hello-world-standard-error.jq b/Task/Hello-world-Standard-error/Jq/hello-world-standard-error.jq similarity index 100% rename from Task/Hello-world-Standard-error/jq/hello-world-standard-error.jq rename to Task/Hello-world-Standard-error/Jq/hello-world-standard-error.jq diff --git a/Task/Hello-world-Standard-error/Kotlin/hello-world-standard-error.kotlin b/Task/Hello-world-Standard-error/Kotlin/hello-world-standard-error.kotlin new file mode 100644 index 0000000000..3a739582f3 --- /dev/null +++ b/Task/Hello-world-Standard-error/Kotlin/hello-world-standard-error.kotlin @@ -0,0 +1,3 @@ +fun main(args: Array) { + System.err.println("Goodbye, World!") +} diff --git a/Task/Hello-world-Standard-error/M4/hello-world-standard-error.m4 b/Task/Hello-world-Standard-error/M4/hello-world-standard-error.m4 new file mode 100644 index 0000000000..81f0913f21 --- /dev/null +++ b/Task/Hello-world-Standard-error/M4/hello-world-standard-error.m4 @@ -0,0 +1,2 @@ +errprint(`Goodbye, World! +')dnl diff --git a/Task/Hello-world-Standard-error/Maple/hello-world-standard-error.maple b/Task/Hello-world-Standard-error/Maple/hello-world-standard-error.maple new file mode 100644 index 0000000000..5f83e5817d --- /dev/null +++ b/Task/Hello-world-Standard-error/Maple/hello-world-standard-error.maple @@ -0,0 +1 @@ +error "Goodbye World" diff --git a/Task/Hello-world-Standard-error/OoRexx/hello-world-standard-error-1.rexx b/Task/Hello-world-Standard-error/OoRexx/hello-world-standard-error-1.rexx new file mode 100644 index 0000000000..509d6a494a --- /dev/null +++ b/Task/Hello-world-Standard-error/OoRexx/hello-world-standard-error-1.rexx @@ -0,0 +1 @@ +.error~lineout("Goodbye, World!") diff --git a/Task/Hello-world-Standard-error/OoRexx/hello-world-standard-error-2.rexx b/Task/Hello-world-Standard-error/OoRexx/hello-world-standard-error-2.rexx new file mode 100644 index 0000000000..8e81920a17 --- /dev/null +++ b/Task/Hello-world-Standard-error/OoRexx/hello-world-standard-error-2.rexx @@ -0,0 +1 @@ +.stderr~lineout("Goodbye, World!") diff --git a/Task/Hello-world-Standard-error/OoRexx/hello-world-standard-error-3.rexx b/Task/Hello-world-Standard-error/OoRexx/hello-world-standard-error-3.rexx new file mode 100644 index 0000000000..1133bf9826 --- /dev/null +++ b/Task/Hello-world-Standard-error/OoRexx/hello-world-standard-error-3.rexx @@ -0,0 +1,9 @@ +/* REXX --------------------------------------------------------------- +* 07.07.2014 Walter Pachl +* 12.07.2014 WP see Discussion where redirection from within the program is shown +*--------------------------------------------------------------------*/ +Say 'rexx serr 2>err.txt directs the stderr output to the file err.txt' +Call lineout 'stderr','Good bye, world!' +Call lineout ,'Hello, world!' +Say 'and this is the error output:' +'type err.txt' diff --git a/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-4.rexx b/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-4.rexx deleted file mode 100644 index 5d1d4f463b..0000000000 --- a/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-4.rexx +++ /dev/null @@ -1,14 +0,0 @@ -/* REXX --------------------------------------------------------------- -* 07.07.2014 Walter Pachl -* enter the appropriate command shown in a command prompt. -* "rexx serr.rex 2>err.txt" -* or "regina serr.rex 2>err.txt" -* 2>file will redirect the stderr stream to the specified file. -* I don't know any other way to catch this stream -*--------------------------------------------------------------------*/ -Parse Version v -Say v -Call lineout 'stderr','Good bye, world!' -Call lineout ,'Hello, world!' -Say 'and this is the error output:' -'type err.txt' diff --git a/Task/Hello-world-Standard-error/Rust/hello-world-standard-error-1.rust b/Task/Hello-world-Standard-error/Rust/hello-world-standard-error-1.rust index f4f70e6e54..4ff2c77561 100644 --- a/Task/Hello-world-Standard-error/Rust/hello-world-standard-error-1.rust +++ b/Task/Hello-world-Standard-error/Rust/hello-world-standard-error-1.rust @@ -1,9 +1,8 @@ -use std::io::{self,Write}; - fn main() { - writeln!(&mut io::stderr(), "Goodbye, world!").expect("Could not write to stderr"); - // writeln! supports formatted strings so the following works as well - let goodbye = "Goodbye"; - let world = "world"; - writeln!(&mut io::stderr(), "{}, {}!", goodbye, world).expect("Could not write to stderr"); + use ::std::io::Write; + let (stderr, errmsg) = (&mut ::std::io::stderr(), "Error writing to stderr"); + writeln!(stderr, "Bye, world!").expect(errmsg); + + let (goodbye, world) = ("Goodbye", "world"); + writeln!(stderr, "{}, {}!", goodbye, world).expect(errmsg); } diff --git a/Task/Hello-world-Standard-error/Scilab/hello-world-standard-error.scilab b/Task/Hello-world-Standard-error/Scilab/hello-world-standard-error.scilab new file mode 100644 index 0000000000..728aca0368 --- /dev/null +++ b/Task/Hello-world-Standard-error/Scilab/hello-world-standard-error.scilab @@ -0,0 +1 @@ +error("Goodbye, World!") diff --git a/Task/Hello-world-Standard-error/Sed/hello-world-standard-error-1.sed b/Task/Hello-world-Standard-error/Sed/hello-world-standard-error-1.sed new file mode 100644 index 0000000000..b699893fb0 --- /dev/null +++ b/Task/Hello-world-Standard-error/Sed/hello-world-standard-error-1.sed @@ -0,0 +1,4 @@ +#n +1 { + s/.*/Goodbye, World!/w /dev/stderr +} diff --git a/Task/Hello-world-Standard-error/Sed/hello-world-standard-error-2.sed b/Task/Hello-world-Standard-error/Sed/hello-world-standard-error-2.sed new file mode 100644 index 0000000000..83a99fecb1 --- /dev/null +++ b/Task/Hello-world-Standard-error/Sed/hello-world-standard-error-2.sed @@ -0,0 +1,2 @@ +$ echo a | sed -f error.sed >/dev/null +Goodbye, World! diff --git a/Task/Hello-world-Standard-error/VBScript/hello-world-standard-error.vb b/Task/Hello-world-Standard-error/VBScript/hello-world-standard-error.vb new file mode 100644 index 0000000000..60bf0b56f9 --- /dev/null +++ b/Task/Hello-world-Standard-error/VBScript/hello-world-standard-error.vb @@ -0,0 +1 @@ +WScript.StdErr.WriteLine "Goodbye, World!" diff --git a/Task/Hello-world-Standard-error/Zkl/hello-world-standard-error.zkl b/Task/Hello-world-Standard-error/Zkl/hello-world-standard-error.zkl new file mode 100644 index 0000000000..953367ba24 --- /dev/null +++ b/Task/Hello-world-Standard-error/Zkl/hello-world-standard-error.zkl @@ -0,0 +1 @@ +File.stderr.writeln("Goodbye, World!") diff --git a/Task/Hello-world-Text/ALGOL-M/hello-world-text.algol-m b/Task/Hello-world-Text/ALGOL-M/hello-world-text.algol-m new file mode 100644 index 0000000000..db0c1bccd1 --- /dev/null +++ b/Task/Hello-world-Text/ALGOL-M/hello-world-text.algol-m @@ -0,0 +1,3 @@ +BEGIN + WRITE( "Hello world!" ); +END diff --git a/Task/Hello-world-Text/Agena/hello-world-text.agena b/Task/Hello-world-Text/Agena/hello-world-text.agena new file mode 100644 index 0000000000..c61fd26a0b --- /dev/null +++ b/Task/Hello-world-Text/Agena/hello-world-text.agena @@ -0,0 +1 @@ +print( "Hello world!" ) diff --git a/Task/Hello-world-Text/Astro/hello-world-text.astro b/Task/Hello-world-Text/Astro/hello-world-text.astro new file mode 100644 index 0000000000..ed708ec5fb --- /dev/null +++ b/Task/Hello-world-Text/Astro/hello-world-text.astro @@ -0,0 +1 @@ +print "Hello world!" diff --git a/Task/Hello-world-Text/Bc/hello-world-text.bc b/Task/Hello-world-Text/Bc/hello-world-text.bc new file mode 100644 index 0000000000..a829090ff5 --- /dev/null +++ b/Task/Hello-world-Text/Bc/hello-world-text.bc @@ -0,0 +1,2 @@ +"Hello world! +" diff --git a/Task/Hello-world-Text/Beeswax/hello-world-text-1.beeswax b/Task/Hello-world-Text/Beeswax/hello-world-text-1.beeswax new file mode 100644 index 0000000000..7adb265ba4 --- /dev/null +++ b/Task/Hello-world-Text/Beeswax/hello-world-text-1.beeswax @@ -0,0 +1 @@ +*`Hello, World! diff --git a/Task/Hello-world-Text/Beeswax/hello-world-text-2.beeswax b/Task/Hello-world-Text/Beeswax/hello-world-text-2.beeswax new file mode 100644 index 0000000000..e4b7dd2838 --- /dev/null +++ b/Task/Hello-world-Text/Beeswax/hello-world-text-2.beeswax @@ -0,0 +1,7 @@ +>`ld! +` + r + o + W + ` + b` ,olleH`_ diff --git a/Task/Hello-world-Text/Beeswax/hello-world-text-3.beeswax b/Task/Hello-world-Text/Beeswax/hello-world-text-3.beeswax new file mode 100644 index 0000000000..6c68dcf35e --- /dev/null +++ b/Task/Hello-world-Text/Beeswax/hello-world-text-3.beeswax @@ -0,0 +1,7 @@ +r l + l o + `` +ol`*`,d! + `` + e H + W diff --git a/Task/Hello-world-Text/Comefrom0x10/hello-world-text-1.comefrom0x10 b/Task/Hello-world-Text/Comefrom0x10/hello-world-text-1.comefrom0x10 new file mode 100644 index 0000000000..adb9840044 --- /dev/null +++ b/Task/Hello-world-Text/Comefrom0x10/hello-world-text-1.comefrom0x10 @@ -0,0 +1 @@ +'Hello world!' diff --git a/Task/Hello-world-Text/jq/hello-world-text.jq b/Task/Hello-world-Text/Comefrom0x10/hello-world-text-2.comefrom0x10 similarity index 100% rename from Task/Hello-world-Text/jq/hello-world-text.jq rename to Task/Hello-world-Text/Comefrom0x10/hello-world-text-2.comefrom0x10 diff --git a/Task/Hello-world-Text/DM/hello-world-text.dm b/Task/Hello-world-Text/DM/hello-world-text.dm new file mode 100644 index 0000000000..43c39c9ef0 --- /dev/null +++ b/Task/Hello-world-Text/DM/hello-world-text.dm @@ -0,0 +1,3 @@ +/client/New() + ..() + src << "Hello world!" diff --git a/Task/Hello-world-Text/Dafny/hello-world-text.dafny b/Task/Hello-world-Text/Dafny/hello-world-text.dafny new file mode 100644 index 0000000000..2c28bfa9a0 --- /dev/null +++ b/Task/Hello-world-Text/Dafny/hello-world-text.dafny @@ -0,0 +1,4 @@ +method Main() { + print "hello, world!\n"; + assert 10 < 2; +} diff --git a/Task/Hello-world-Text/Dc/hello-world-text.dc b/Task/Hello-world-Text/Dc/hello-world-text.dc new file mode 100644 index 0000000000..502d2384a3 --- /dev/null +++ b/Task/Hello-world-Text/Dc/hello-world-text.dc @@ -0,0 +1 @@ +[Hello world!]p diff --git a/Task/Hello-world-Text/EC/hello-world-text.ec b/Task/Hello-world-Text/EC/hello-world-text.ec new file mode 100644 index 0000000000..c3223a8bb6 --- /dev/null +++ b/Task/Hello-world-Text/EC/hello-world-text.ec @@ -0,0 +1,7 @@ +class GoodByeApp : Application +{ + void Main() + { + PrintLn("Hello world!"); + } +} diff --git a/Task/Hello-world-Text/ElastiC/hello-world-text.elastic b/Task/Hello-world-Text/ElastiC/hello-world-text.elastic new file mode 100644 index 0000000000..51a7d343c1 --- /dev/null +++ b/Task/Hello-world-Text/ElastiC/hello-world-text.elastic @@ -0,0 +1,18 @@ +package hello; + + // Import the `basic' package + import basic; + + // Define a simple function + function hello() + { + // Print hello world + basic.print( "Hello world!\n" ); + } + + /* + * Here we start to execute package code + */ + + // Invoke the `hello' function + hello(); diff --git a/Task/Hello-world-Text/Elena/hello-world-text-1.elena b/Task/Hello-world-Text/Elena/hello-world-text-1.elena index 063e09abb6..cd64d5f156 100644 --- a/Task/Hello-world-Text/Elena/hello-world-text-1.elena +++ b/Task/Hello-world-Text/Elena/hello-world-text-1.elena @@ -1,4 +1,4 @@ -#symbol program = +program = [ - system'console writeLine:"Hello world!". + console writeLine:"Hello world!". ]. diff --git a/Task/Hello-world-Text/Elena/hello-world-text-2.elena b/Task/Hello-world-Text/Elena/hello-world-text-2.elena index 6621721e07..42a5870562 100644 --- a/Task/Hello-world-Text/Elena/hello-world-text-2.elena +++ b/Task/Hello-world-Text/Elena/hello-world-text-2.elena @@ -1,5 +1 @@ -#import system. -#import system'dynamic. - -#symbol program - = Tape("Hello world!",system'console,%"writeLine[1]"). +program = system'dynamic'Tape("Hello world!",system'console,%"writeLine[1]"). diff --git a/Task/Hello-world-Text/Euphoria/hello-world-text.euphoria b/Task/Hello-world-Text/Euphoria/hello-world-text.euphoria deleted file mode 100644 index 1b865d44c7..0000000000 --- a/Task/Hello-world-Text/Euphoria/hello-world-text.euphoria +++ /dev/null @@ -1 +0,0 @@ -puts(1,"Goodbye, World!\n") diff --git a/Task/Hello-world-Text/Ferite/hello-world-text.ferite b/Task/Hello-world-Text/Ferite/hello-world-text.ferite new file mode 100644 index 0000000000..f40b7f7b0e --- /dev/null +++ b/Task/Hello-world-Text/Ferite/hello-world-text.ferite @@ -0,0 +1,2 @@ +uses "console"; +Console.println( "Goodby, World!" ); diff --git a/Task/Hello-world-Text/Friendly-interactive-shell/hello-world-text.fish b/Task/Hello-world-Text/Friendly-interactive-shell/hello-world-text.fish new file mode 100644 index 0000000000..3af583cd85 --- /dev/null +++ b/Task/Hello-world-Text/Friendly-interactive-shell/hello-world-text.fish @@ -0,0 +1 @@ +echo Hello world! diff --git a/Task/Hello-world-Text/Gambas/hello-world-text.gambas b/Task/Hello-world-Text/Gambas/hello-world-text.gambas index 386f4e4cc6..d7db5982ff 100644 --- a/Task/Hello-world-Text/Gambas/hello-world-text.gambas +++ b/Task/Hello-world-Text/Gambas/hello-world-text.gambas @@ -1 +1,5 @@ +Public Sub Main() + PRINT "Hello world!" + +End diff --git a/Task/Hello-world-Text/Gecho/hello-world-text.gecho b/Task/Hello-world-Text/Gecho/hello-world-text.gecho new file mode 100644 index 0000000000..3188ddd193 --- /dev/null +++ b/Task/Hello-world-Text/Gecho/hello-world-text.gecho @@ -0,0 +1 @@ +'Hello, <> 'World! print diff --git a/Task/Hello-world-Text/Halon/hello-world-text.halon b/Task/Hello-world-Text/Halon/hello-world-text.halon new file mode 100644 index 0000000000..6b07235552 --- /dev/null +++ b/Task/Hello-world-Text/Halon/hello-world-text.halon @@ -0,0 +1 @@ +echo "Hello world!"; diff --git a/Task/Hello-world-Text/Haskell/hello-world-text.hs b/Task/Hello-world-Text/Haskell/hello-world-text.hs index bc88e41bcf..1136b1e880 100644 --- a/Task/Hello-world-Text/Haskell/hello-world-text.hs +++ b/Task/Hello-world-Text/Haskell/hello-world-text.hs @@ -1 +1,3 @@ -main = putStrLn "Hello world!" +message :: String +message = "Hello world!" +main = putStrLn message diff --git a/Task/Hello-world-Text/IWBASIC/hello-world-text.iwbasic b/Task/Hello-world-Text/IWBASIC/hello-world-text.iwbasic new file mode 100644 index 0000000000..624384ff00 --- /dev/null +++ b/Task/Hello-world-Text/IWBASIC/hello-world-text.iwbasic @@ -0,0 +1,13 @@ +OPENCONSOLE + +PRINT"Hello world!" + +'This line could be left out. +PRINT:PRINT:PRINT"Press any key to end." + +'Keep the console from closing right away so the text can be read. +DO:UNTIL INKEY$<>"" + +CLOSECONSOLE + +END diff --git a/Task/Hello-world-Text/J/hello-world-text-2.j b/Task/Hello-world-Text/J/hello-world-text-2.j index 5d07467dcb..39c2d9e599 100644 --- a/Task/Hello-world-Text/J/hello-world-text-2.j +++ b/Task/Hello-world-Text/J/hello-world-text-2.j @@ -4,3 +4,8 @@ Hello world! Hello world! smoutput data Hello world! + + NB. unassigned names are verbs of infinite rank awaiting definition. + NB. j pretty prints the train. + Hello World! +Hello World ! diff --git a/Task/Hello-world-Text/Jq/hello-world-text.jq b/Task/Hello-world-Text/Jq/hello-world-text.jq new file mode 100644 index 0000000000..6ccebb9abe --- /dev/null +++ b/Task/Hello-world-Text/Jq/hello-world-text.jq @@ -0,0 +1 @@ +"Hello world!" diff --git a/Task/Hello-world-Text/Lilypond/hello-world-text.lily b/Task/Hello-world-Text/Lilypond/hello-world-text.lily new file mode 100644 index 0000000000..47daaa6e9e --- /dev/null +++ b/Task/Hello-world-Text/Lilypond/hello-world-text.lily @@ -0,0 +1,11 @@ +\version "2.18.2" +global = { + \time 4/4 + \key c \major + \tempo 4=100 +} +\relative c''{ g e e( g2) +} +\addlyrics { + Hel -- lo, World! +} diff --git a/Task/Hello-world-Text/MIRC-Scripting-Language/hello-world-text.mirc b/Task/Hello-world-Text/MIRC-Scripting-Language/hello-world-text.mirc new file mode 100644 index 0000000000..f72d4250ef --- /dev/null +++ b/Task/Hello-world-Text/MIRC-Scripting-Language/hello-world-text.mirc @@ -0,0 +1 @@ +echo -ag Hello world! diff --git a/Task/Hello-world-Text/Make/hello-world-text.make b/Task/Hello-world-Text/Make/hello-world-text.make new file mode 100644 index 0000000000..23802735a0 --- /dev/null +++ b/Task/Hello-world-Text/Make/hello-world-text.make @@ -0,0 +1,2 @@ +all: +$(info Hello world!) diff --git a/Task/Hello-world-Text/NewLISP/hello-world-text.newlisp b/Task/Hello-world-Text/NewLISP/hello-world-text.newlisp new file mode 100644 index 0000000000..fe1102b873 --- /dev/null +++ b/Task/Hello-world-Text/NewLISP/hello-world-text.newlisp @@ -0,0 +1 @@ +(println "Hello world!") diff --git a/Task/Hello-world-Text/Nimrod/hello-world-text.nimrod b/Task/Hello-world-Text/Nimrod/hello-world-text.nimrod deleted file mode 100644 index 6abfcc9268..0000000000 --- a/Task/Hello-world-Text/Nimrod/hello-world-text.nimrod +++ /dev/null @@ -1 +0,0 @@ -echo("Goodbye, World!") diff --git a/Task/Hello-world-Text/Objective-C/hello-world-text-4.m b/Task/Hello-world-Text/Objective-C/hello-world-text-4.m deleted file mode 100644 index d5029aa0df..0000000000 --- a/Task/Hello-world-Text/Objective-C/hello-world-text-4.m +++ /dev/null @@ -1 +0,0 @@ -[[NSFileHandle fileHandleWithStandardOutput] writeData:[@"Goodbye, World!" dataUsingEncoding:NSUTF8StringEncoding]]; diff --git a/Task/Hello-world-Text/Objective-C/hello-world-text-5.m b/Task/Hello-world-Text/Objective-C/hello-world-text-5.m deleted file mode 100644 index df1e4c99d6..0000000000 --- a/Task/Hello-world-Text/Objective-C/hello-world-text-5.m +++ /dev/null @@ -1 +0,0 @@ -NSLog(@"Goodbye, World!"); diff --git a/Task/Hello-world-Text/OoRexx/hello-world-text.rexx b/Task/Hello-world-Text/OoRexx/hello-world-text.rexx new file mode 100644 index 0000000000..6357100820 --- /dev/null +++ b/Task/Hello-world-Text/OoRexx/hello-world-text.rexx @@ -0,0 +1,2 @@ +/* Rexx */ +say 'Hello world!' diff --git a/Task/Hello-world-Text/PILOT/hello-world-text.pilot b/Task/Hello-world-Text/PILOT/hello-world-text.pilot new file mode 100644 index 0000000000..df7b090d06 --- /dev/null +++ b/Task/Hello-world-Text/PILOT/hello-world-text.pilot @@ -0,0 +1 @@ +T:Hello world! diff --git a/Task/Hello-world-Text/PL-SQL/hello-world-text.sql b/Task/Hello-world-Text/PL-SQL/hello-world-text.sql new file mode 100644 index 0000000000..c414c4ca5d --- /dev/null +++ b/Task/Hello-world-Text/PL-SQL/hello-world-text.sql @@ -0,0 +1,6 @@ +set serveroutput on + +BEGIN + DBMS_OUTPUT.PUT_LINE('Hello world!'); +END; +/ diff --git a/Task/Hello-world-Text/Red/hello-world-text.red b/Task/Hello-world-Text/Red/hello-world-text.red new file mode 100644 index 0000000000..ed708ec5fb --- /dev/null +++ b/Task/Hello-world-Text/Red/hello-world-text.red @@ -0,0 +1 @@ +print "Hello world!" diff --git a/Task/Hello-world-Text/SPL/hello-world-text.spl b/Task/Hello-world-Text/SPL/hello-world-text.spl new file mode 100644 index 0000000000..82e3fffb04 --- /dev/null +++ b/Task/Hello-world-Text/SPL/hello-world-text.spl @@ -0,0 +1 @@ +#.output("Hello world!") diff --git a/Task/Hello-world-Text/SQL/hello-world-text.sql b/Task/Hello-world-Text/SQL/hello-world-text.sql new file mode 100644 index 0000000000..de163bddff --- /dev/null +++ b/Task/Hello-world-Text/SQL/hello-world-text.sql @@ -0,0 +1 @@ +select 'Hello world!' text from dual; diff --git a/Task/Hello-world-Text/Sed/hello-world-text.sed b/Task/Hello-world-Text/Sed/hello-world-text.sed new file mode 100644 index 0000000000..979febeddc --- /dev/null +++ b/Task/Hello-world-Text/Sed/hello-world-text.sed @@ -0,0 +1,3 @@ +i\ +Hello world! +q diff --git a/Task/Hello-world-Text/Setl4/hello-world-text.setl4 b/Task/Hello-world-Text/Setl4/hello-world-text.setl4 new file mode 100644 index 0000000000..8e80f280e8 --- /dev/null +++ b/Task/Hello-world-Text/Setl4/hello-world-text.setl4 @@ -0,0 +1 @@ +out("Hello world!");end diff --git a/Task/Hello-world-Text/Smart-BASIC/hello-world-text.smart b/Task/Hello-world-Text/Smart-BASIC/hello-world-text.smart new file mode 100644 index 0000000000..386f4e4cc6 --- /dev/null +++ b/Task/Hello-world-Text/Smart-BASIC/hello-world-text.smart @@ -0,0 +1 @@ +PRINT "Hello world!" diff --git a/Task/Hello-world-Text/Stata/hello-world-text.stata b/Task/Hello-world-Text/Stata/hello-world-text.stata new file mode 100644 index 0000000000..74b23f46df --- /dev/null +++ b/Task/Hello-world-Text/Stata/hello-world-text.stata @@ -0,0 +1 @@ +display "Hello world!" diff --git a/Task/Hello-world-Text/TransFORTH/hello-world-text.transforth b/Task/Hello-world-Text/TransFORTH/hello-world-text.transforth new file mode 100644 index 0000000000..4abbf2975e --- /dev/null +++ b/Task/Hello-world-Text/TransFORTH/hello-world-text.transforth @@ -0,0 +1 @@ +PRINT " Hello world! " diff --git a/Task/Hello-world-Text/True-BASIC/hello-world-text.true b/Task/Hello-world-Text/True-BASIC/hello-world-text.true new file mode 100644 index 0000000000..57a4983b0d --- /dev/null +++ b/Task/Hello-world-Text/True-BASIC/hello-world-text.true @@ -0,0 +1,3 @@ +! In True BASIC all programs run in their own window. So this is almost a graphical version. +PRINT "Hello world!" +END diff --git a/Task/Hello-world-Text/Viua-VM-assembly/hello-world-text.viua b/Task/Hello-world-Text/Viua-VM-assembly/hello-world-text.viua new file mode 100644 index 0000000000..f1c098a7dd --- /dev/null +++ b/Task/Hello-world-Text/Viua-VM-assembly/hello-world-text.viua @@ -0,0 +1,6 @@ +.function: main/0 + text %1 local "Hello World!" + print %1 local + izero %0 local + return +.end diff --git a/Task/Hello-world-Text/XEec/hello-world-text.xeec b/Task/Hello-world-Text/XEec/hello-world-text.xeec new file mode 100644 index 0000000000..993cf84dc3 --- /dev/null +++ b/Task/Hello-world-Text/XEec/hello-world-text.xeec @@ -0,0 +1,2 @@ +h#10 h$! h$d h$l h$r h$o h$w h#32 +h$o h$l h$l h$e h$H >o o$ p jno diff --git a/Task/Hello-world-Text/Zkl/hello-world-text.zkl b/Task/Hello-world-Text/Zkl/hello-world-text.zkl new file mode 100644 index 0000000000..b078aeee5c --- /dev/null +++ b/Task/Hello-world-Text/Zkl/hello-world-text.zkl @@ -0,0 +1 @@ +println("Hello world!"); diff --git a/Task/Hello-world-Web-server/Aime/hello-world-web-server-1.aime b/Task/Hello-world-Web-server/Aime/hello-world-web-server-1.aime new file mode 100644 index 0000000000..0c08ef0519 --- /dev/null +++ b/Task/Hello-world-Web-server/Aime/hello-world-web-server-1.aime @@ -0,0 +1,34 @@ +void +serve(dispatch w, file s, list colors) +{ + file i, o; + date d; + + accept(i, o, s, 0); + f_(o, "HTTP/1.1 200 OK\n" +"Content-Type: text/html; charset=UTF-8\n\n" +"Bye-bye baby bye-bye" +"" +"

    Goodbye, world!

    \n"); + + # chrome won't show the page if we close right away. we'll close in 2s. + d_now(d); + d_offset(d, 2, 0); + w_schedule(w, d, f_close, i); +} + + +integer +main(void) +{ + dispatch w; + file s; + + tcpip_listen(s, 8080, 0); + w_watch(w, s, serve, w, s, l_effect("blue", "green", "red", "yellow")); + w_press(w); + + return 0; +} diff --git a/Task/Hello-world-Web-server/Aime/hello-world-web-server-2.aime b/Task/Hello-world-Web-server/Aime/hello-world-web-server-2.aime new file mode 100644 index 0000000000..60db1ea423 --- /dev/null +++ b/Task/Hello-world-Web-server/Aime/hello-world-web-server-2.aime @@ -0,0 +1,11 @@ +file i, o, s; + +tcpip_listen(s, 8080, 0); +while (1) { + accept(i, o, s, 0); + f_(o, "HTTP/1.1 200 OK\n" +"Content-Type: text/html; charset=UTF-8\n\n" +"baby bye-bye" +"

    Goodbye, world!

    \n"); + f_flush(o); +} diff --git a/Task/Hello-world-Web-server/BaCon/hello-world-web-server.bacon b/Task/Hello-world-Web-server/BaCon/hello-world-web-server.bacon new file mode 100644 index 0000000000..ff4029e42d --- /dev/null +++ b/Task/Hello-world-Web-server/BaCon/hello-world-web-server.bacon @@ -0,0 +1,47 @@ +' Define HTTP constants +CONST New$ = CHR$(13) & NL$ +CONST Sep$ = CHR$(13) & NL$ & CHR$(13) & NL$ +CONST Msg$ = "BaCon web greeting

    Goodbye, World!

    " + +' Get our IP +Ip$ = "localhost" +PRINT "Connect from browser '", Ip$, ":8080'." + +' Ignore child signals to avoid zombie processes +SIGNAL SIG_IGN, SIGCHLD + +' Keep receiving requests +WHILE TRUE + + ' Open listening port + OPEN Ip$ & ":8080" FOR SERVER AS mynet + + ' Incoming connection -> create background process + spawn = FORK + + ' We are in the child + IF spawn = 0 THEN + + ' Get the request + REPEAT + RECEIVE dat$ FROM mynet + PRINT dat$ + UNTIL RIGHT$(dat$, 4) = Sep$ + + ' Reply that we're OK + SEND "HTTP/1.1 200 Ok" & New$ & "Content-Length: " & STR$(LEN(Msg$)) & Sep$ & Msg$ TO mynet + + ' Close connection + CLOSE SERVER mynet + + ' End this process + END + + ' We are in the parent + ELIF spawn > 0 THEN + + ' Close connection in parent + CLOSE SERVER mynet + + ENDIF +WEND diff --git a/Task/Hello-world-Web-server/Dart/hello-world-web-server.dart b/Task/Hello-world-Web-server/Dart/hello-world-web-server.dart index 475b8131e8..69cd51acdc 100644 --- a/Task/Hello-world-Web-server/Dart/hello-world-web-server.dart +++ b/Task/Hello-world-Web-server/Dart/hello-world-web-server.dart @@ -1,9 +1,11 @@ import 'dart:io'; -void main(){ - HttpServer.bind('localhost', 8080) - .then((HttpServer server) => - server.listen((HttpRequest request) => - request..response.write('Hello, world') - ..response.close())); +main() async { + var server = await HttpServer.bind('127.0.0.1', 8080); + + await for (HttpRequest request in server) { + request.response + ..write('Hello, world') + ..close(); + } } diff --git a/Task/Hello-world-Web-server/Gastona/hello-world-web-server.gastona b/Task/Hello-world-Web-server/Gastona/hello-world-web-server.gastona new file mode 100644 index 0000000000..d77794e63a --- /dev/null +++ b/Task/Hello-world-Web-server/Gastona/hello-world-web-server.gastona @@ -0,0 +1,13 @@ +#javaj# + + oConsole + +#listix# + +
    + MICOHTTP, START, myServer, 8080 + + + // + // Goodbye world! + // diff --git a/Task/Hello-world-Web-server/Julia/hello-world-web-server.julia b/Task/Hello-world-Web-server/Julia/hello-world-web-server.julia new file mode 100644 index 0000000000..b927483c6a --- /dev/null +++ b/Task/Hello-world-Web-server/Julia/hello-world-web-server.julia @@ -0,0 +1,5 @@ +using HttpServer +server = Server() do req, res + "Goodbye, World!" +end +run(server, 8080) diff --git a/Task/Hello-world-Web-server/Kotlin/hello-world-web-server.kotlin b/Task/Hello-world-Web-server/Kotlin/hello-world-web-server.kotlin new file mode 100644 index 0000000000..c0db04b2e6 --- /dev/null +++ b/Task/Hello-world-Web-server/Kotlin/hello-world-web-server.kotlin @@ -0,0 +1,11 @@ +import java.io.PrintWriter +import java.net.ServerSocket + +fun main(args: Array) { + val listener = ServerSocket(8080) + while(true) { + val sock = listener.accept() + PrintWriter(sock.outputStream, true).println("Goodbye, World!") + sock.close() + } +} diff --git a/Task/Hello-world-Web-server/Ol/hello-world-web-server.ol b/Task/Hello-world-Web-server/Ol/hello-world-web-server.ol new file mode 100644 index 0000000000..00f06ece87 --- /dev/null +++ b/Task/Hello-world-Web-server/Ol/hello-world-web-server.ol @@ -0,0 +1,14 @@ +(import (lib http)) + +(http:run 8080 (lambda (fd request headers send close) + (send "HTTP/1.0 200 OK\n" + "Connection: close\n" + "Content-Type: text/html; charset=UTF-8\n" + "Server: " (car *version*) "/" (cdr *version*) + "\n\n" + + "

    Goodbye, World!

    " + (ref request 1) ": " (ref request 2) + "
    " headers "") + (close #t) +)) diff --git a/Task/Hello-world-Web-server/REXX/hello-world-web-server.rexx b/Task/Hello-world-Web-server/REXX/hello-world-web-server.rexx new file mode 100644 index 0000000000..1312ebcd9b --- /dev/null +++ b/Task/Hello-world-Web-server/REXX/hello-world-web-server.rexx @@ -0,0 +1,12 @@ +/* HTTP hello server */ +response.1 = 'HTTP/1.1 200 OK' || '0D0A'X, + || 'Connection: close' || '0D0A'X, + || 'Content-Type: text/html' || '0D0A0D0A'X +response.2 = '' || '0A'X, + || 'Hello, Rosetta' || '0A'X, + || '

    Goodbye, World!

    ' || '0A'X, + || '' || '0A'X + +DO FOREVER + ADDRESS SYSTEM 'nc -l 8080' WITH INPUT STEM response. +END diff --git a/Task/Hello-world-Web-server/Zkl/hello-world-web-server.zkl b/Task/Hello-world-Web-server/Zkl/hello-world-web-server.zkl new file mode 100644 index 0000000000..64db112edc --- /dev/null +++ b/Task/Hello-world-Web-server/Zkl/hello-world-web-server.zkl @@ -0,0 +1,46 @@ +const PORT=8080; +const SERVLET_THREADS=4; + + // A class to process requests from clients (eg browsers) + // in a thread. Requests are received via a pipe, which feeds + // all Servlet threads. +class Servlet{ + fcn init(jobPipe){ self.launch(jobPipe); } + fcn liftoff(jobPipe){ + while(1){ // read request, write response, repeat + socket:=jobPipe.read(); + if(socket.wait(60) != 1) // what is Chrome doing? + { socket.close(); continue; } + if (request:=socket.read()) + try{ processRequest(request,socket); } catch{} + } + } + fcn splashdown(h,e){ println("Servlet died before its time"); } +} + +fcn processRequest(request,socket){ + response:=responseHeader(); + response+="Goodbye, World!"; + socket.write(response); socket.close(); // no Keep-Alive +} + +fcn responseHeader(status=200,reason="OK"){ + String( + "HTTP/1.0 ",status," ",reason,"\r\n", + Time.Date.httpDate(),"\r\n" + "Server: ZTWS (zkl)\r\n" + "Connection: close\r\n" + "Content-Type: text/html; charset=UTF-8\r\n" + "\r\n") +} + + //////////////////// Start the server /////////////////////// +var jobPipe=Thread.Pipe(); // a queue of requests +do(SERVLET_THREADS){ Servlet(jobPipe) } // start threads + + // Create the HTTP server listen socket + // Sits here forever passing client HTTP connects to Servlets +serverSocket:=Network.TCPServerSocket.open(PORT); +println("HTTP server started at http://", + serverSocket.hostname, ":", serverSocket.port); +serverSocket.listen(jobPipe); diff --git a/Task/Here-document/D/here-document-1.d b/Task/Here-document/D/here-document-1.d deleted file mode 100644 index 4336aadcfa..0000000000 --- a/Task/Here-document/D/here-document-1.d +++ /dev/null @@ -1 +0,0 @@ -auto s = q"[a string that you "don't" have to escape]"; diff --git a/Task/Here-document/D/here-document-2.d b/Task/Here-document/D/here-document-2.d deleted file mode 100644 index cf080f7f0a..0000000000 --- a/Task/Here-document/D/here-document-2.d +++ /dev/null @@ -1,6 +0,0 @@ -writefln(q"EOS -This -is a multi-line -heredoc string -EOS" -); diff --git a/Task/Here-document/jq/here-document-1.jq b/Task/Here-document/Jq/here-document-1.jq similarity index 100% rename from Task/Here-document/jq/here-document-1.jq rename to Task/Here-document/Jq/here-document-1.jq diff --git a/Task/Here-document/jq/here-document-2.jq b/Task/Here-document/Jq/here-document-2.jq similarity index 100% rename from Task/Here-document/jq/here-document-2.jq rename to Task/Here-document/Jq/here-document-2.jq diff --git a/Task/Here-document/jq/here-document-3.jq b/Task/Here-document/Jq/here-document-3.jq similarity index 100% rename from Task/Here-document/jq/here-document-3.jq rename to Task/Here-document/Jq/here-document-3.jq diff --git a/Task/Here-document/jq/here-document-4.jq b/Task/Here-document/Jq/here-document-4.jq similarity index 100% rename from Task/Here-document/jq/here-document-4.jq rename to Task/Here-document/Jq/here-document-4.jq diff --git a/Task/Here-document/jq/here-document-5.jq b/Task/Here-document/Jq/here-document-5.jq similarity index 100% rename from Task/Here-document/jq/here-document-5.jq rename to Task/Here-document/Jq/here-document-5.jq diff --git a/Task/Here-document/Kotlin/here-document.kotlin b/Task/Here-document/Kotlin/here-document.kotlin new file mode 100644 index 0000000000..e485a118e7 --- /dev/null +++ b/Task/Here-document/Kotlin/here-document.kotlin @@ -0,0 +1,28 @@ +// version 1.1.0 + +fun main(args: Array) { + val ev = "embed variables" + + val here = """ + This is a raw string literal + which does not treat escaped characters + (\t, \b, \n, \r, \', \", \\, \$ and \u) + specially and can contain new lines, + indentation and other whitespace + within the string. + +"Quotes" or doubled ""quotes"" can +be included without problem but not +tripled quotes. + + It's also possible to $ev + in a raw string literal using string + interpolation. + + If you need to include a + literal ${'$'} sign in a raw string literal then + don't worry you've just done it! + """ + + println(here) +} diff --git a/Task/Here-document/Zkl/here-document.zkl b/Task/Here-document/Zkl/here-document.zkl new file mode 100644 index 0000000000..8e902f8746 --- /dev/null +++ b/Task/Here-document/Zkl/here-document.zkl @@ -0,0 +1,9 @@ +x:= +#<<< +"#<<< starts a block of lines that are concatenated verbatim +and fed into the parser as one line. #<<< ends the block. +Both #<<< tokens must start the line that is otherwise ignored + +Note that is isn't a string, but arbitrary source " + 1 + 23; +#<<< +x.println(); diff --git a/Task/Heronian-triangles/C++/heronian-triangles-1.cpp b/Task/Heronian-triangles/C++/heronian-triangles-1.cpp deleted file mode 100644 index 45f58f8458..0000000000 --- a/Task/Heronian-triangles/C++/heronian-triangles-1.cpp +++ /dev/null @@ -1,86 +0,0 @@ -#include -#include -#include -#include -#include - -int gcd(int a, int b) -{ - int rem = 1, dividend, divisor; - std::tie(divisor, dividend) = std::minmax(a, b); - while (rem != 0) { - rem = dividend % divisor; - if (rem != 0) { - dividend = divisor; - divisor = rem; - } - } - return divisor; -} - -struct Triangle -{ - int a; - int b; - int c; -}; - -int perimeter(const Triangle& triangle) -{ - return triangle.a + triangle.b + triangle.c; -} - -double area(const Triangle& t) -{ - double p_2 = perimeter(t) / 2.; - double area_sq = p_2 * ( p_2 - t.a ) * ( p_2 - t.b ) * ( p_2 - t.c ); - return sqrt(area_sq); -} - -std::vector generate_triangles(int side_limit = 200) -{ - std::vector result; - for(int a = 1; a <= side_limit; ++a) - for(int b = 1; b <= a; ++b) - for(int c = a+1-b; c <= b; ++c) // skip too-small values of c, which will violate triangle inequality - { - Triangle t{a, b, c}; - double t_area = area(t); - if(t_area == 0) continue; - if( std::floor(t_area) == std::ceil(t_area) && gcd(a, gcd(b, c)) == 1) - result.push_back(t); - } - return result; -} - -bool compare(const Triangle& lhs, const Triangle& rhs) -{ - return std::make_tuple(area(lhs), perimeter(lhs), std::max(lhs.a, std::max(lhs.b, lhs.c))) < - std::make_tuple(area(rhs), perimeter(rhs), std::max(rhs.a, std::max(rhs.b, rhs.c))); -} - -struct area_compare -{ - bool operator()(const Triangle& t, int i) { return area(t) < i; } - bool operator()(int i, const Triangle& t) { return i < area(t); } -}; - -int main() -{ - auto tri = generate_triangles(); - std::cout << "There are " << tri.size() << " primitive Heronian triangles with sides up to 200\n\n"; - - std::cout << "First ten when ordered by increasing area, then perimeter, then maximum sides:\n"; - std::sort(tri.begin(), tri.end(), compare); - std::cout << "area\tperimeter\tsides\n"; - for(int i = 0; i < 10; ++i) - std::cout << area(tri[i]) << '\t' << perimeter(tri[i]) << "\t\t" << - tri[i].a << 'x' << tri[i].b << 'x' << tri[i].c << '\n'; - - std::cout << "\nAll with area 210 subject to the previous ordering:\n"; - auto range = std::equal_range(tri.begin(), tri.end(), 210, area_compare()); - std::cout << "area\tperimeter\tsides\n"; - for(auto it = range.first; it != range.second; ++it) - std::cout << area(*it) << '\t' << perimeter(*it) << "\t\t" << - it->a << 'x' << it->b << 'x' << it->c << '\n'; -} diff --git a/Task/Heronian-triangles/C++/heronian-triangles-2.cpp b/Task/Heronian-triangles/C++/heronian-triangles-2.cpp deleted file mode 100644 index e425b0f81b..0000000000 --- a/Task/Heronian-triangles/C++/heronian-triangles-2.cpp +++ /dev/null @@ -1,23 +0,0 @@ -There are 517 primitive Heronian triangles with sides up to 200 - -First ten when ordered by increasing area, then perimeter, then maximum sides: -area perimeter sides -6 12 5x4x3 -12 16 6x5x5 -12 18 8x5x5 -24 32 15x13x4 -30 30 13x12x5 -36 36 17x10x9 -36 54 26x25x3 -42 42 20x15x7 -60 36 13x13x10 -60 40 17x15x8 - -All with area 210 subject to the previous ordering: -area perimeter sides -210 70 28x25x17 -210 70 29x21x20 -210 84 37x35x12 -210 84 39x28x17 -210 140 68x65x7 -210 300 149x148x3 diff --git a/Task/Heronian-triangles/Java/heronian-triangles-1.java b/Task/Heronian-triangles/Java/heronian-triangles-1.java deleted file mode 100644 index c93822fcb2..0000000000 --- a/Task/Heronian-triangles/Java/heronian-triangles-1.java +++ /dev/null @@ -1,57 +0,0 @@ -import java.util.ArrayList; -public class Heron { - public static void main(String[] args) { - ArrayList list = new ArrayList(); - for(int c = 1; c <= 200; c++){ - for(int b = 1; b <= c; b++){ - for(int a = 1; a <= b; a++){ - if(gcd(gcd(a, b), c) == 1 && isHeron(heronArea(a, b, c) - list.add(new int[]{a, b, c, a + b + c, (int)heronArea(a, b, c)}); - } - } - } - sort(list); - System.out.printf("Number of primitive Heronian triangles with sides up to 200: %d\n\nFirst ten when ordered by increasing area, then perimeter:\nSides Perimeter Area", list.size()); - for(int i = 0; i < 10; i++){ - System.out.printf("\n%d x %d x %d %d %d",list.get(i)[0], list.get(i)[1], list.get(i)[2], list.get(i)[3], list.get(i)[4]); - } - System.out.printf("\n\nArea = 210\nSides Perimeter Area"); - for(int i = 0; i < list.size(); i++){ - if(list.get(i)[4] == 210) - System.out.printf("\n%d x %d x %d %d %d",list.get(i)[0], list.get(i)[1], list.get(i)[2], list.get(i)[3], list.get(i)[4]); - } - } - public static double heronArea(int a, int b, int c){ - double s = (a + b + c)/ 2f; - return Math.sqrt(s *(s -a)*(s - b)*(s - c)); - } - public static boolean isHeron(double h){ - return h % 1 == 0 && h > 0; - } - public static int gcd(int a, int b){ - int leftover = 1, dividend = a > b ? a : b, divisor = a > b ? b : a; - while(leftover != 0){ - leftover = dividend % divisor; - if(leftover > 0){ - dividend = divisor; - divisor = leftover; - } - } - return divisor; - } - public static void sort(ArrayList list){ - boolean swapped = true; - int[] temp; - while(swapped){ - swapped = false; - for(int i = 1; i < list.size(); i++){ - if(list.get(i)[4] < list.get(i - 1)[4] || list.get(i)[4] == list.get(i - 1)[4] && list.get(i)[3] < list.get(i - 1)[3]){ - temp = list.get(i); - list.set(i, list.get(i - 1)); - list.set(i - 1, temp); - swapped = true; - } - } - } - } -} diff --git a/Task/Heronian-triangles/Java/heronian-triangles-2.java b/Task/Heronian-triangles/Java/heronian-triangles-2.java deleted file mode 100644 index 4e65cc8305..0000000000 --- a/Task/Heronian-triangles/Java/heronian-triangles-2.java +++ /dev/null @@ -1,23 +0,0 @@ -Number of primitive Heronian triangles with sides up to 200: 517 - -First ten when ordered by increasing area, then perimeter: -Sides Perimeter Area -3 x 4 x 5 12 6 -5 x 5 x 6 16 12 -5 x 5 x 8 18 12 -4 x 13 x 15 32 24 -5 x 12 x 13 30 30 -9 x 10 x 17 36 36 -3 x 25 x 26 54 36 -7 x 15 x 20 42 42 -10 x 13 x 13 36 60 -8 x 15 x 17 40 60 - -Area = 210 -Sides Perimeter Area -17 x 25 x 28 70 210 -20 x 21 x 29 70 210 -12 x 35 x 37 84 210 -17 x 28 x 39 84 210 -7 x 65 x 68 140 210 -3 x 148 x 149 300 210 diff --git a/Task/Heronian-triangles/JavaScript/heronian-triangles-3.js b/Task/Heronian-triangles/JavaScript/heronian-triangles-3.js deleted file mode 100644 index 88cb16834d..0000000000 --- a/Task/Heronian-triangles/JavaScript/heronian-triangles-3.js +++ /dev/null @@ -1,82 +0,0 @@ -(function (n) { - - var chain = function (xs, f) { // Monadic bind/chain - return [].concat.apply([], xs.map(f)); - }, - - hArea = function (x, y, z) { - var s = (x + y + z) / 2, - a = s * (s - x) * (s - y) * (s - z); - return a ? Math.sqrt(a) : 0; - }, - - gcd = function (m, n) { return n ? gcd(n, m % n) : m; }, - - rng = function (m, n) { - return Array.apply(null, Array(n - m + 1)).map(function (x, i) { - return m + i; - }); - }, - - sum = function (a, x) { return a + x; }; - - // DEFINING THE SORTED SUB-SET IN TERMS OF A LIST MONAD - - var lstHeron = chain( rng(1, n), function (x) { - return chain( rng(x, n), function (y) { - return chain( rng(y, n), function (z) { - - return ( - (x + y > z) && - gcd(gcd(x, y), z) === 1 && // Primitive. - (function () { // Heronian. - var a = hArea(x, y, z); - return a && (a === parseInt(a, 10)) - })() - ) ? [[x, y, z]] : []; // Monadic inject or fail - - })})}).sort(function (a, b) { - var dArea = hArea.apply(null, a) - hArea.apply(null, b); - if (dArea) return dArea; - else { - var dPerim = a.reduce(sum, 0) - b.reduce(sum, 0); - return dPerim ? dPerim : (a[2] - b[2]); - } - }); - - // OUPUT FORMATTED AS TWO WIKITABLES - - var lstColumns = ['Sides Perimeter Area'.split(' ')], - fnData = function (lst) { - return [JSON.stringify(lst), lst.reduce(sum, 0), hArea.apply(null, lst)]; - }, - wikiTable = function (lstRows, blnHeaderRow, strStyle) { - return '{| class="wikitable" ' + ( - strStyle ? 'style="' + strStyle + '"' : '' - ) + lstRows.map(function (lstRow, iRow) { - var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|'); - - return '\n|-\n' + strDelim + ' ' + lstRow.map(function (v) { - return typeof v === 'undefined' ? ' ' : v; - }).join(' ' + strDelim + strDelim + ' '); - }).join('') + '\n|}'; - }; - - return 'Found: ' + lstHeron.length + - ' primitive Heronian triangles with sides up to ' + n + '.\n\n' + - '(Showing first 10, sorted by increasing area, ' + - 'perimeter, and longest side)\n\n' + - wikiTable( - lstColumns.concat(lstHeron.slice(0, 10).map(fnData)), - true - ) + '\n\n' + - 'All primitive Heronian triangles in this range where area = 210\n' + - '\n(also in order of increasing perimeter and longest side)\n\n' + - wikiTable( - lstColumns.concat(lstHeron.filter(function (x) { - return 210 === hArea.apply(null, x); - }).map(fnData)), - true - ) + '\n\n'; - -})(200); diff --git a/Task/Heronian-triangles/jq/heronian-triangles-1.jq b/Task/Heronian-triangles/Jq/heronian-triangles-1.jq similarity index 100% rename from Task/Heronian-triangles/jq/heronian-triangles-1.jq rename to Task/Heronian-triangles/Jq/heronian-triangles-1.jq diff --git a/Task/Heronian-triangles/jq/heronian-triangles-2.jq b/Task/Heronian-triangles/Jq/heronian-triangles-2.jq similarity index 100% rename from Task/Heronian-triangles/jq/heronian-triangles-2.jq rename to Task/Heronian-triangles/Jq/heronian-triangles-2.jq diff --git a/Task/Heronian-triangles/Kotlin/heronian-triangles.kotlin b/Task/Heronian-triangles/Kotlin/heronian-triangles.kotlin index 65d15e2d6f..474b4d8e5e 100644 --- a/Task/Heronian-triangles/Kotlin/heronian-triangles.kotlin +++ b/Task/Heronian-triangles/Kotlin/heronian-triangles.kotlin @@ -1,4 +1,4 @@ -import java.util.* +import java.util.ArrayList object Heron { private val n = 200 @@ -19,7 +19,7 @@ object Heron { sort(l) print("\n\nFirst ten when ordered by increasing area, then perimeter:" + header) - for (i in 0..10 - 1) { + for (i in 0 until 10) { print(format(l[i])) } val a = 210 @@ -45,7 +45,7 @@ object Heron { var swapped = true while (swapped) { swapped = false - for (i in 1..l.size - 1) + for (i in 1 until l.size) if (l[i][4] < l[i - 1][4] || l[i][4] == l[i - 1][4] && l[i][3] < l[i - 1][3]) { val temp = l[i] l[i] = l[i - 1] @@ -55,7 +55,7 @@ object Heron { } } - private fun isHeron(h: Double) = h.mod(1) == 0.0 && h > 0 + private fun isHeron(h: Double) = h.rem(1) == 0.0 && h > 0 private val header = "\nSides Perimeter Area" private fun format(a: IntArray) = "\n%3d x %3d x %3d %5d %10d".format(a[0], a[1], a[2], a[3], a[4]) diff --git a/Task/Heronian-triangles/OoRexx/heronian-triangles.rexx b/Task/Heronian-triangles/OoRexx/heronian-triangles.rexx new file mode 100644 index 0000000000..2facd56294 --- /dev/null +++ b/Task/Heronian-triangles/OoRexx/heronian-triangles.rexx @@ -0,0 +1,138 @@ +/*REXX pgm generates primitive Heronian triangles by side length & area.*/ + Call time 'R' + Numeric Digits 12 + Parse Arg mxs area list + If mxs ='' Then mxs =200 + If area='' Then area=210 + If list='' Then list=10 + tx='primitive Heronian triangles' + Call heronian mxs /* invoke sub with max SIDES. */ + Say nt tx 'found with side length up to' mxs "(inclusive)." + Call show '2' + Call show '3' + Say time('E') 'seconds elapsed' + Exit + +heronian: + abc.=0 /* abc.ar.p.* contains 'a b c' for area ar and perimeter p */ + nt=0 /* number of triangles found */ + min.='' + max.='' + mem.=0 + ln=length(mxs) + Do a=3 To mxs + Do b=a To mxs + ab=a+b + Do c=b To mxs + If hgcd(a,b,c)=1 Then Do /* GCD=1 */ + ar=heron_area() + If pos('.',ar)=0 Then Do /* is an integer */ + nt=nt+1 /* a primitive Heronian triangle.*/ + Call minmax '0P',p + Call minmax '0A',a + per=ab+c + abc_ar=right(per,4) right(a,4) right(b,4) right(c,4), + right(ar,5) + Call mem abc_ar + End + End + End + End + End + /* + say 'min.p='min.0p + say 'max.p='max.0p + say 'min.a='min.0a + say 'max.a='max.0a + */ + Return nt + +hgcd: Procedure + Parse Arg x + Do j=2 For 2 + y=arg(j) + Do Until _==0 + _=x//y + x=y + y=_ + End + End + Return x + +minmax: + Parse Arg which,x + If min.which='' Then Do + min.which=x + max.which=x + End + Else Do + min.which=min(min.which,x) + max.which=max(max.which,x) + End + --Say which min.which '-' max.which + Return + +heron_area: + p=ab+c /* perimeter */ + s=p/2 + ar2=s*(s-a)*(s-b)*(s-c) /* area**2 */ + If pos(right(ar2,1),'014569')=0 Then /* ar2 cannot be */ + Return '.' /* square of an integer*/ + If ar2>0 Then + ar=sqrt(ar2) /* area */ + Else + ar='.' + Return ar + +show: Parse Arg which + Say '' + Select + When which='2' Then Do + Say 'Listing of the first' list tx":" + Do i=1 To list + Call ot i,mem.i + End + End + When which='3' Then Do + Say 'Listing of the' tx "with area=210" + j=0 + Do i=1 To mem.0 + Parse Var mem.i per a b c area + If area=210 Then Do + j=j+1 + Call ot j,mem.i + End + End + End + End + Return + +ot: Parse Arg k,mem + Parse Var mem per a b c area + Say right(k,9)' area:'right(area,6)||, + ' perimeter:'right(per,4)' sides:', + right(a,3) right(b,3) right(c,3) + Return + +mem: + Parse Arg e + Do i=1 To mem.0 + If mem.i>>e Then Leave + End + Do j=mem.0 to i By -1 + j1=j+1 + mem.j1=mem.j + End + mem.i=e + mem.0=mem.0+1 + Return +/* for "Classic" REXX +sqrt: procedure; parse arg x;if x=0 then return 0;d=digits();numeric digits 11 +numeric form; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'E'_%2 +p=d+d%4+2; m.=11; do j=0 while p>9; m.j=p; p=p%2+1; end; do k=j+5 to 0 by -1 +if m.k>11 then numeric digits m.k;g=.5*(g+x/g);end;numeric digits d;return g/1 +*/ +/* for ooRexx */ +::requires rxmath library +::routine sqrt + Return rxCalcSqrt(arg(1),14) diff --git a/Task/Heronian-triangles/Ring/heronian-triangles.ring b/Task/Heronian-triangles/Ring/heronian-triangles.ring deleted file mode 100644 index 3e3c7269f9..0000000000 --- a/Task/Heronian-triangles/Ring/heronian-triangles.ring +++ /dev/null @@ -1,29 +0,0 @@ -size = 20 -number = 0 -see " a b c area perimeter" + nl -for i = 1 to size - for j = i + 1 to size - for k = j + 1 to size - perim = (i + j + k) / 2 - heronian = sqrt(perim*(perim - i)*(perim - j)*(perim-k)) - if heronian = floor(heronian) - if gcd(gcd(i, j),k) = 1 - if i + j > k and i + k > j and j + k > i - number += 1 - if number <= 20 - if len(string(i)) = 1 stri = " " + string(i) else stri = string(i) ok - if len(string(j)) = 1 strj = " " + string(j) else strj = string(j) ok - if len(string(k)) = 1 strk = " " + string(k) else strk = string(k) ok - if len(string(heronian)) = 1 her = " " + string(heronian) else her = string(heronian) ok - see stri + " "+ strj + " "+ strk + " " + her + " " + perim*2 + nl ok ok ok ok - next - next -next - -func gcd gcd, b - while b - c = gcd - gcd = b - b = c % b - end - return gcd diff --git a/Task/Heronian-triangles/SPL/heronian-triangles.spl b/Task/Heronian-triangles/SPL/heronian-triangles.spl new file mode 100644 index 0000000000..15bf67340d --- /dev/null +++ b/Task/Heronian-triangles/SPL/heronian-triangles.spl @@ -0,0 +1,33 @@ +h,t = getem(200) +#.sort(h,4,5,1,2,3) +#.output("There are ",t," Heronian triangles") +#.output(" a b c area perimeter") +#.output("----- ----- ----- ------ ---------") +> i, 1..#.min(10,t) + print(h,i) +< +#.output(#.str("...",">34<")) +> i, 1..t + ? h[4,i]=210, print(h,i) +< +print(h,i)= + #.output(#.str(h[1,i],">4>")," ",#.str(h[2,i],">4>")," ",#.str(h[3,i],">4>")," ",#.str(h[4,i],">5>")," ",#.str(h[5,i],">8>")) +. +getem(n)= + > a, 1..n + > b, #.upper((a+1)/2)..a + > c, a-b+1..b + x = ((a+b+c)*(a+b-c)*(a-b+c)*(b-a+c))^0.5 + >> x%1 | #.gcd(a,b,c)>1 + t += 1 + h[1,t],h[2,t],h[3,t] = #.sort(a,b,c) + h[4,t],h[5,t] = heron(a,b,c) + < + < + < + <= h,t +. +heron(a,b,c)= + s = (a+b+c)/2 + <= (s*(s-a)*(s-b)*(s-c))^0.5, s*2 +. diff --git a/Task/Heronian-triangles/Zkl/heronian-triangles-1.zkl b/Task/Heronian-triangles/Zkl/heronian-triangles-1.zkl new file mode 100644 index 0000000000..13e9ab08bf --- /dev/null +++ b/Task/Heronian-triangles/Zkl/heronian-triangles-1.zkl @@ -0,0 +1,8 @@ +fcn hero(a,b,c){ //--> area (float) + s,a2:=(a + b + c).toFloat()/2, s*(s - a)*(s - b)*(s - c); + (a2 > 0) and a2.sqrt() or 0.0 +} +fcn isHeronian(a,b,c){ + A:=hero(a,b,c); + (A>0) and A.modf()[1].closeTo(0.0,1.0e-6) and A //--> area or False +} diff --git a/Task/Heronian-triangles/Zkl/heronian-triangles-2.zkl b/Task/Heronian-triangles/Zkl/heronian-triangles-2.zkl new file mode 100644 index 0000000000..fcfdb9df76 --- /dev/null +++ b/Task/Heronian-triangles/Zkl/heronian-triangles-2.zkl @@ -0,0 +1,22 @@ +const MAX_SIDE=200; +heros:=Sink(List); +foreach a,b,c in ([1..MAX_SIDE],[a..MAX_SIDE],[b..MAX_SIDE]){ + if(a.gcd(b).gcd(c)==1 and (h:=isHeronian(a,b,c))) heros.write(T(h,a+b+c,a,b,c)); +} +// sort by increasing area, perimeter, then sides +heros=heros.close().sort(fcn([(h1,p1,_,_,c1)],[(h2,p2,_,_,c2)]){ + if(h1!=h2) return(h1 1) f *= nn + val b = BigDecimal(f).divide(a, MathContext.DECIMAL128) + val c = b.movePointRight(1).toBigInteger() % BigInteger.TEN + return c.toString().matches(Regex("[09]")) + } +} + +fun main(args: Array) { + for (n in 1..17) println("${"%2d".format(n)} is almost integer: ${Hickerson.almostInteger(n)}") +} diff --git a/Task/Hickerson-series-of-almost-integers/Sidef/hickerson-series-of-almost-integers.sidef b/Task/Hickerson-series-of-almost-integers/Sidef/hickerson-series-of-almost-integers.sidef index 24f977f3c6..5b458a9e59 100644 --- a/Task/Hickerson-series-of-almost-integers/Sidef/hickerson-series-of-almost-integers.sidef +++ b/Task/Hickerson-series-of-almost-integers/Sidef/hickerson-series-of-almost-integers.sidef @@ -1,8 +1,8 @@ func h(n) { - n! / (2 * Math.pow(2.log, n+1)); -} - -17.times { |n| - "h(%2d) = %22s is%s almost an integer.\n".printf( - n, var hn = h(n).roundf(-3), hn.to_s ~~ /\.[09]/ ? '' : ' NOT'); + n! / (2 * pow(2.log, n+1)) } +  +{ |n| + "h(%2d) = %22s is%s almost an integer.\n".printf( + n, var hn = h(n).round(-3), hn.to_s ~~ /\.[09]/ ? '' : ' NOT') +} << 1..17 diff --git a/Task/Hickerson-series-of-almost-integers/Zkl/hickerson-series-of-almost-integers-1.zkl b/Task/Hickerson-series-of-almost-integers/Zkl/hickerson-series-of-almost-integers-1.zkl new file mode 100644 index 0000000000..fdc4152549 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Zkl/hickerson-series-of-almost-integers-1.zkl @@ -0,0 +1,5 @@ +var [const] BN=Import("zklBigNum"), + X =BN("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), + ln2X=BN("693147180559945309417232121458176568075500134360255254120680009493393621969694715605863326996418687") + ; +fcn hickerson(n){ BN(n).factorial()*X.pow(n+1)*10/2/ln2X.pow(n+1) } diff --git a/Task/Hickerson-series-of-almost-integers/Zkl/hickerson-series-of-almost-integers-2.zkl b/Task/Hickerson-series-of-almost-integers/Zkl/hickerson-series-of-almost-integers-2.zkl new file mode 100644 index 0000000000..431e18c478 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Zkl/hickerson-series-of-almost-integers-2.zkl @@ -0,0 +1,4 @@ +foreach n in ([1..18]){ + hs,ld,isH:=hickerson(n).toString(),hs[-1],"90".holds(ld); + println("h(%2d)=%s.%s almost integer: %b".fmt(n,hs[0,-1],ld,isH)); +} diff --git a/Task/Higher-order-functions/AppleScript/higher-order-functions-2.applescript b/Task/Higher-order-functions/AppleScript/higher-order-functions-2.applescript index f19a156054..04d2523965 100644 --- a/Task/Higher-order-functions/AppleScript/higher-order-functions-2.applescript +++ b/Task/Higher-order-functions/AppleScript/higher-order-functions-2.applescript @@ -39,7 +39,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -58,7 +58,7 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -68,14 +68,13 @@ end foldl -- Sublist of those elements for which the predicate -- function returns true -- filter :: (a -> Bool) -> [a] -> [a] --- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) tell mReturn(f) set lst to {} set lng to length of xs repeat with i from 1 to lng set v to item i of xs - if lambda(v, i, xs) then set end of lst to v + if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell @@ -88,7 +87,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Higher-order-functions/jq/higher-order-functions-1.jq b/Task/Higher-order-functions/Jq/higher-order-functions-1.jq similarity index 100% rename from Task/Higher-order-functions/jq/higher-order-functions-1.jq rename to Task/Higher-order-functions/Jq/higher-order-functions-1.jq diff --git a/Task/Higher-order-functions/jq/higher-order-functions-2.jq b/Task/Higher-order-functions/Jq/higher-order-functions-2.jq similarity index 100% rename from Task/Higher-order-functions/jq/higher-order-functions-2.jq rename to Task/Higher-order-functions/Jq/higher-order-functions-2.jq diff --git a/Task/Higher-order-functions/jq/higher-order-functions-3.jq b/Task/Higher-order-functions/Jq/higher-order-functions-3.jq similarity index 100% rename from Task/Higher-order-functions/jq/higher-order-functions-3.jq rename to Task/Higher-order-functions/Jq/higher-order-functions-3.jq diff --git a/Task/Higher-order-functions/jq/higher-order-functions-4.jq b/Task/Higher-order-functions/Jq/higher-order-functions-4.jq similarity index 100% rename from Task/Higher-order-functions/jq/higher-order-functions-4.jq rename to Task/Higher-order-functions/Jq/higher-order-functions-4.jq diff --git a/Task/Higher-order-functions/Kotlin/higher-order-functions-1.kotlin b/Task/Higher-order-functions/Kotlin/higher-order-functions-1.kotlin index 70d9b430df..10cdaf2c67 100644 --- a/Task/Higher-order-functions/Kotlin/higher-order-functions-1.kotlin +++ b/Task/Higher-order-functions/Kotlin/higher-order-functions-1.kotlin @@ -1,7 +1,7 @@ fun main(args: Array) { val list = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) - var a = list.map({ x -> x + 2 }).average() - var h = list.map({ x -> x * x }).average() - var g = list.map({ x -> x * x * x }).average() + val a = list.map({ x -> x + 2 }).average() + val h = list.map({ x -> x * x }).average() + val g = list.map({ x -> x * x * x }).average() println("A = %f G = %f H = %f".format(a, g, h)) } diff --git a/Task/Higher-order-functions/OoRexx/higher-order-functions.rexx b/Task/Higher-order-functions/OoRexx/higher-order-functions.rexx new file mode 100644 index 0000000000..ef80abd00b --- /dev/null +++ b/Task/Higher-order-functions/OoRexx/higher-order-functions.rexx @@ -0,0 +1,56 @@ +say callit(.routines~fib, 10) +say callit(.routines~fact, 6) +say callit(.routines~square, 13) +say callit(.routines~cube, 3) +say callit(.routines~reverse, 721) +say callit(.routines~sumit, 1, 2) +say callit(.routines~sumit, 2, 4, 6, 8) + +-- call the provided routine object with the provided variable number of arguments +::routine callit + use arg function + args = arg(2, 'a') -- get all arguments after the first to pass along + return function~callWith(args) -- and pass along the call + +::routine cube + use arg n + return n**3 + +::routine square + use arg n + return n**2 + +::routine reverse + use arg n + return reverse(n) + +::routine fact + use arg n + accum = 1 + loop j = 2 to n + accum = accum * j + end + return accum + +::routine sumit + use arg n + accum = 0 + do i over arg(1, 'a') -- iterate over the array of args + accum += i + end + return accum + +::routine fib + use arg n + if n == 0 then + return n + if n == 1 then + return n + last = 0 + next = 1 + loop j = 2 to n; + current = last + next + last = next + next = current + end + return current diff --git a/Task/Higher-order-functions/PostScript/higher-order-functions.ps b/Task/Higher-order-functions/PostScript/higher-order-functions.ps index fd84d996cf..40d179e6c6 100644 --- a/Task/Higher-order-functions/PostScript/higher-order-functions.ps +++ b/Task/Higher-order-functions/PostScript/higher-order-functions.ps @@ -1,2 +1,10 @@ -/x_times_3_sub_1 {3 * 1 sub}. -[0 1 2 3 4] {x_times_3_sub_1} map +% operator example +% 'ifelse' is passed a boolean and two procedures +/a 5 def +a 0 gt { (Hello!) } { (World?) } ifelse == + +% procedure example +% 'bar' is loaded onto the stack and passed to 'foo' +/foo { exec } def +/bar { (Hello, world!) } def +/bar load foo == diff --git a/Task/Higher-order-functions/REXX/higher-order-functions.rexx b/Task/Higher-order-functions/REXX/higher-order-functions.rexx index 033cd9bdad..95629ca316 100644 --- a/Task/Higher-order-functions/REXX/higher-order-functions.rexx +++ b/Task/Higher-order-functions/REXX/higher-order-functions.rexx @@ -1,18 +1,12 @@ -/*REXX program demonstrates passing a function (as a name) to another function. */ - n=3735928559 -funcName = 'fib' ; q= 10; call someFunk funcName, q; call tell -funcName = 'fact' ; q= 6; call someFunk funcName, q; call tell -funcName = 'square' ; q= 13; call someFunk funcName, q; call tell -funcName = 'cube' ; q= 3; call someFunk funcName, q; call tell - q=721; call someFunk 'reverse',q; call tell -say copies('═', 30) /*display a nice separator fence */ -say 'done as' d2x(n). /*prove that variable N is still intact*/ +/*REXX program demonstrates the passing of a name of a function to another function. */ +call function 'fact' , 6; say right( 'fact{'$"} = ", 30) result +call function 'square' , 13; say right( 'square{'$"} = ", 30) result +call function 'cube' , 3; say right( 'cube{'$"} = ", 30) result +call function 'reverse', 721; say right( 'reverse{'$"} = ", 30) result exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -cube: return n**3 -fact: !=1; do j=2 to n; !=!*j; end; return ! -fib: if n<2 then return n; _=0; a=0; b=1; do j=2 to n; _=a+b; a=b; b=_; end; return _ -reverse: return 'REVERSE'(n) -someFunk: procedure; arg ?,n; signal value (?); say result 'result'; return -square: return n**2 -tell: say right(funcName'('q") = ",20) result; return +cube: return $**3 +fact: procedure expose $; !=1; do j=2 to $; !=!*j; end; return ! +function: arg ?.; parse arg ,$; signal value (?.) +reverse: return 'REVERSE'($) +square: return $**2 diff --git a/Task/Higher-order-functions/VBA/higher-order-functions.vba b/Task/Higher-order-functions/VBA/higher-order-functions.vba new file mode 100644 index 0000000000..fff8724052 --- /dev/null +++ b/Task/Higher-order-functions/VBA/higher-order-functions.vba @@ -0,0 +1,11 @@ +Sub HigherOrder() + Dim result As Single + result = first("second") + MsgBox result +End Sub +Function first(f As String) As Single + first = Application.Run(f, 1) + 2 +End Function +Function second(x As Single) As Single + second = x / 2 +End Function diff --git a/Task/Higher-order-functions/Zkl/higher-order-functions-1.zkl b/Task/Higher-order-functions/Zkl/higher-order-functions-1.zkl new file mode 100644 index 0000000000..a3b9866de0 --- /dev/null +++ b/Task/Higher-order-functions/Zkl/higher-order-functions-1.zkl @@ -0,0 +1 @@ +fcn f(g){ g() } fcn g{ "Hello World!".println() } diff --git a/Task/Higher-order-functions/Zkl/higher-order-functions-2.zkl b/Task/Higher-order-functions/Zkl/higher-order-functions-2.zkl new file mode 100644 index 0000000000..927038e56a --- /dev/null +++ b/Task/Higher-order-functions/Zkl/higher-order-functions-2.zkl @@ -0,0 +1,2 @@ +fcn f(g){ g() } +fcn(g){ g() }(fcn{ "Hello World!".println() } ) diff --git a/Task/History-variables/Kotlin/history-variables.kotlin b/Task/History-variables/Kotlin/history-variables.kotlin new file mode 100644 index 0000000000..3b90f5c346 --- /dev/null +++ b/Task/History-variables/Kotlin/history-variables.kotlin @@ -0,0 +1,28 @@ +// version 1.1.4 + +class HistoryVariable(initialValue: T) { + private val history = mutableListOf() + + var currentValue: T + get() = history[history.size - 1] + set(value) { + history.add(value) + } + + init { + currentValue = initialValue + } + + fun showHistory() { + println("The variable's history, oldest values first, is:") + for (item in history) println(item) + } +} + +fun main(args: Array) { + val v = HistoryVariable(1) + v.currentValue = 2 + v.currentValue = 3 + v.showHistory() + println("\nCurrentvalue is ${v.currentValue}") +} diff --git a/Task/History-variables/OCaml/history-variables.ocaml b/Task/History-variables/OCaml/history-variables.ocaml new file mode 100644 index 0000000000..e70d9feea3 --- /dev/null +++ b/Task/History-variables/OCaml/history-variables.ocaml @@ -0,0 +1,16 @@ +open Stack +(* The following line is only for convenience when typing code *) +module H = Stack + +let show_entry e = + Printf.printf "History entry: %5d\n" e + +let () = + let hs = H.create() in + H.push 111 hs ; + H.push 4 hs ; + H.push 42 hs ; + H.iter show_entry hs; + hs |> H.pop |> Printf.printf "%d\n"; + hs |> H.pop |> Printf.printf "%d\n"; + hs |> H.pop |> Printf.printf "%d\n" diff --git a/Task/History-variables/Protium/history-variables-1.protium b/Task/History-variables/Protium/history-variables-1.protium deleted file mode 100644 index 6b41a128ad..0000000000 --- a/Task/History-variables/Protium/history-variables-1.protium +++ /dev/null @@ -1,11 +0,0 @@ -Turn history on <@ DEFHST>__on -Notify Protium we are interested in the variable mv -<@ DEFHST>mv -Assign a value: <@ LETVARLIT>mv|first value<@ SAYVAR>mv -Reassign the value: <@ LETVARLIT>mv|second value<@ SAYVAR>mv -Reassign the value: <@ LETVARLIT>mv|third value<@ SAYVAR>mv -Dump history <@ SAYDMPHSTVAR>mv -Current value: <@ SAYVAR>mv -Undo once: <@ ACTUNDVAR>mv<@ SAYVAR>mv -Undo twice: <@ ACTUNDVAR>mv<@ SAYVAR>mv -Turn history off <@ DEFHST>__off diff --git a/Task/History-variables/Protium/history-variables-2.protium b/Task/History-variables/Protium/history-variables-2.protium deleted file mode 100644 index 8838f81f41..0000000000 --- a/Task/History-variables/Protium/history-variables-2.protium +++ /dev/null @@ -1,11 +0,0 @@ -Turn history on <# 定义变量史>__on -Notify Protium we are interested in the variable mv -<# 定义变量史>mv -Assign a value: <# 指定变量字串>mv|first value<# 显示变量>mv -Reassign the value: <# 指定变量字串>mv|second value<# 显示变量>mv -Reassign the value: <# 指定变量字串>mv|third value<# 显示变量>mv -Dump history <# 显示全内容变量史变量>mv -Current value: <# 显示变量>mv -Undo once: <# 运行撤消变量>mv<# 显示变量>mv -Undo twice: <# 运行撤消变量>mv<# 显示变量>mv -Turn history off <# 定义变量史>__off diff --git a/Task/History-variables/Zkl/history-variables-1.zkl b/Task/History-variables/Zkl/history-variables-1.zkl new file mode 100644 index 0000000000..c4eb3a6923 --- /dev/null +++ b/Task/History-variables/Zkl/history-variables-1.zkl @@ -0,0 +1,18 @@ +class HistoryVar{ + var [private] _v, _history=List(), maxSz; + fcn init(v,maxEntries=3){ maxSz=maxEntries; set(v) } + fcn set(v){ + _v=v; _history.append(T(Time.Clock.time,v)); + if(_history.len()>maxSz) _history.del(0); + self + } + fcn get(n=0){ // look back into history + z:=_history.len(); + n=(if(n>=z) 0 else z-n-1); + _history[n][1] + } + var [proxy] v=fcn{ _v }; + var [proxy] history= + fcn{ _history.pump(List,fcn([(t,v)]){ T(Time.Date.ctime(t),v) }) }; + fcn __opAdd(x){ set(_v + x); self } +} diff --git a/Task/History-variables/Zkl/history-variables-2.zkl b/Task/History-variables/Zkl/history-variables-2.zkl new file mode 100644 index 0000000000..3eba4e76a3 --- /dev/null +++ b/Task/History-variables/Zkl/history-variables-2.zkl @@ -0,0 +1,6 @@ +hv:=HistoryVar(123); +hv+4; +hv.set("Shuttle prepared for liftoff"); +hv+": orbit achived"; +hv.history.concat("\n").println(); +hv.get(3).println("<-- value two changes ago"); diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Julia/hofstadter-conway-$10,000-sequence.julia b/Task/Hofstadter-Conway-$10,000-sequence/Julia/hofstadter-conway-$10,000-sequence.julia new file mode 100644 index 0000000000..167ab9f962 --- /dev/null +++ b/Task/Hofstadter-Conway-$10,000-sequence/Julia/hofstadter-conway-$10,000-sequence.julia @@ -0,0 +1,38 @@ +# v0.6 + +# Task 1 +function hofstadterconway(n::Integer)::Vector{Int} + rst = fill(1, n) + for i in 3:n + rst[i] = rst[rst[i - 1]] + rst[i - rst[i - 1]] + end + return rst +end + +function hcfraction(n::Integer)::Vector{Float64} + rst = Array{Float64}(n) + for (i, a) in enumerate(hofstadterconway(n)) + rst[i] = abs(a) / i + end + return rst +end + +# Task 2 +seq = hcfraction(2 ^ 20) +for i in 1:20 + a, b = 2 ^ (i - 1), 2 ^ i + @printf("max value of a(n)/n in %6i < n < %7i = %5.3f\n", a, b, maximum(seq[a:b])) +end + +# Task 3 +function lastindex(val::Float64) + r, p = 1, 0 + # Find the range of 2 power in which the maximum is < val + seq = hcfraction(2 ^ 15) + while maximum(seq[2^p:2^(p+1)]) > val; p += 1 end + r = 2 ^ (p + 1) + while seq[r] < val; r -= 1 end + return r +end + +println("You too might have won \$1000 with the mallows number of ", lastindex(0.55)) diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Kotlin/hofstadter-conway-$10,000-sequence.kotlin b/Task/Hofstadter-Conway-$10,000-sequence/Kotlin/hofstadter-conway-$10,000-sequence.kotlin new file mode 100644 index 0000000000..9651daa061 --- /dev/null +++ b/Task/Hofstadter-Conway-$10,000-sequence/Kotlin/hofstadter-conway-$10,000-sequence.kotlin @@ -0,0 +1,37 @@ +// version 1.1.2 + +fun main(args: Array) { + val limit = (1 shl 20) + 1 + val a = IntArray(limit) + a[1] = 1 + a[2] = 1 + for (n in 3 until limit) { + val p = a[n - 1] + a[n] = a[p] + a[n - p] + } + + println(" Range Maximum") + println("---------------- --------") + var pow2 = 1 + var p = 1 + var max = a[1].toDouble() + for (n in 2 until limit) { + val r = a[n].toDouble() / n + if (r > max) max = r + if (n == pow2 * 2) { + println("2 ^ ${"%2d".format(p - 1)} to 2 ^ ${"%2d".format(p)} ${"%f".format(max)}") + pow2 *= 2 + p++ + max = r + } + } + + var prize = 0 + for (n in limit - 1 downTo 1) { + if (a[n].toDouble() / n >= 0.55) { + prize = n + break + } + } + println("\nMallows' number = $prize") +} diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Python/hofstadter-conway-$10,000-sequence.py b/Task/Hofstadter-Conway-$10,000-sequence/Python/hofstadter-conway-$10,000-sequence.py index 78712d30d9..ce98f7d37c 100644 --- a/Task/Hofstadter-Conway-$10,000-sequence/Python/hofstadter-conway-$10,000-sequence.py +++ b/Task/Hofstadter-Conway-$10,000-sequence/Python/hofstadter-conway-$10,000-sequence.py @@ -1,20 +1,28 @@ from __future__ import division -def maxandmallows(nmaxpower2=20): - # Note: The first hc number is returned in hc[1]; - # hc[0] is not part of the series. +def maxandmallows(nmaxpower2): nmax = 2**nmaxpower2 - hc, mallows, mx, mxpow2 = [None, 1, 1], None, (0.5, 2), [] + mx = (0.5, 2) + mxpow2 = [] + mallows = None + + # Hofstadter-Conway sequence starts at hc[1], + # hc[0] is not part of the series. + hc = [None, 1, 1] + for n in range(2, nmax + 1): ratio = hc[n] / n - if ratio > mx[0]: mx = (ratio, n) - if ratio >= 0.55: mallows = n + if ratio > mx[0]: + mx = (ratio, n) + if ratio >= 0.55: + mallows = n if ratio == 0.5: - print("In the region %7i < n <= %7i: max a(n)/n = %s" % - ((n)//2, n, "%6.4f at n = %i" % mx)) + print("In the region %7i < n <= %7i: max a(n)/n = %6.4f at n = %i" % + (n//2, n, mx[0], mx[1])) mxpow2.append(mx[0]) mx = (ratio, n) hc.append(hc[hc[n]] + hc[-hc[n]]) + return hc, mallows if mxpow2 and mxpow2[-1] < 0.55 and n > 4 else None if __name__ == '__main__': diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Ruby/hofstadter-conway-$10,000-sequence-1.rb b/Task/Hofstadter-Conway-$10,000-sequence/Ruby/hofstadter-conway-$10,000-sequence-1.rb deleted file mode 100644 index e5096b7a17..0000000000 --- a/Task/Hofstadter-Conway-$10,000-sequence/Ruby/hofstadter-conway-$10,000-sequence-1.rb +++ /dev/null @@ -1,15 +0,0 @@ -class HofstadterConway10000 - def initialize - @sequence = [nil, 1, 1] - end - attr_reader :sequence - - def [](n) - raise ArgumentError, "n must be >= 1" if n < 1 - a = @sequence - a.length.upto(n) {|i| a[i] = a[a[i-1]] + a[i-a[i-1]] } - a[n] - end -end - -hc = HofstadterConway10000.new diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Ruby/hofstadter-conway-$10,000-sequence-2.rb b/Task/Hofstadter-Conway-$10,000-sequence/Ruby/hofstadter-conway-$10,000-sequence-2.rb deleted file mode 100644 index 1e9125fb06..0000000000 --- a/Task/Hofstadter-Conway-$10,000-sequence/Ruby/hofstadter-conway-$10,000-sequence-2.rb +++ /dev/null @@ -1,13 +0,0 @@ -p = -1 -20.downto(1).each_cons(2) do |j, i| - max_n, max_v = -1, -1 - (2**j).downto(2**i).each do |n| - v = hc[n].to_f / n - max_n, max_v = n, v if v > max_v - # Mallows number - p = n if p == -1 and v >= 0.55 - end - puts "maximum between 2^#{i} and 2^#{j} occurs at #{max_n}: #{max_v}" -end - -puts "the mallows number is #{p}" diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Scheme/hofstadter-conway-$10,000-sequence.ss b/Task/Hofstadter-Conway-$10,000-sequence/Scheme/hofstadter-conway-$10,000-sequence.ss new file mode 100644 index 0000000000..27b0cc6698 --- /dev/null +++ b/Task/Hofstadter-Conway-$10,000-sequence/Scheme/hofstadter-conway-$10,000-sequence.ss @@ -0,0 +1,43 @@ +(import (scheme base) + (scheme write) + (only (srfi 1) iota)) + +;; maximum size of sequence to consider, as a power of 2 +(define *max-power* 20) +(define *size* (expt 2 *max-power*)) + +;; Task 1: Generate members of the sequence +(define *seq* (make-vector (+ 1 *size*))) ; add 1, to use 1-indexing into sequence + +(vector-set! *seq* 1 1) +(vector-set! *seq* 2 1) +(for-each + (lambda (n) + (let ((x (vector-ref *seq* (- n 1)))) + (vector-set! *seq* n (+ (vector-ref *seq* x) + (vector-ref *seq* (- n x)))))) + (iota (- *size* 2) 3)) + +;; Task 2: Show maxima of a(n)/n between successive powers of two +(for-each + (lambda (power) + (let ((start-idx (+ (expt 2 (- power 1)) 1)) + (end-idx (expt 2 power))) + (do ((i start-idx (+ 1 i)) + (maximum 0 (max maximum (/ (vector-ref *seq* i) + i)))) + ((> i end-idx) + (display + (string-append + "Maximum between 2^" (number->string (- power 1)) + " and 2^" (number->string power) + " = " (number->string (inexact maximum)) + "\n")))))) + (iota (- *max-power* 1) 2)) + +;; Task 3: Find value of p where a(n)/n < 0.55 for all n > p (in our sequence) +(do ((idx *size* (- idx 1))) + ((or (zero? idx) ; safety net + (> (/ (vector-ref *seq* idx) idx) + 0.55)) + (display (string-append "\np=" (number->string idx) "\n")))) diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Sidef/hofstadter-conway-$10,000-sequence.sidef b/Task/Hofstadter-Conway-$10,000-sequence/Sidef/hofstadter-conway-$10,000-sequence.sidef index 10b4fe21f8..5a2db2a4b6 100644 --- a/Task/Hofstadter-Conway-$10,000-sequence/Sidef/hofstadter-conway-$10,000-sequence.sidef +++ b/Task/Hofstadter-Conway-$10,000-sequence/Sidef/hofstadter-conway-$10,000-sequence.sidef @@ -1,9 +1,8 @@ class HofstadterConway10000 { has sequence = [nil, 1, 1] - method term(n {.is_pos}) { var a = sequence - a.len .. n -> each {|i| a[i] = a[a[i-1]]+a[i-a[i-1]] } + {|i| a[i] = a[a[i-1]]+a[i-a[i-1]] } << a.len..n a[n] } } @@ -19,7 +18,7 @@ for i in (1..19) { (max_n, max_v) = (n, v) if (v > max_v) mallows = n if (v >= 0.55) } - say ("maximum between 2^%2d and 2^%2d occurs at%7d: %.8f" % (i, j, max_n, max_v)) + say ("maximum between 2^%2d and 2^%2d occurs at%7d: %.8f" % (i, j, max_n, max_v)) } say "the mallows number is #{mallows}" diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Zkl/hofstadter-conway-$10,000-sequence.zkl b/Task/Hofstadter-Conway-$10,000-sequence/Zkl/hofstadter-conway-$10,000-sequence.zkl new file mode 100644 index 0000000000..375bb04cbc --- /dev/null +++ b/Task/Hofstadter-Conway-$10,000-sequence/Zkl/hofstadter-conway-$10,000-sequence.zkl @@ -0,0 +1,20 @@ +fcn hofstadterConwaySequence(m){ + a:=List.createLong(m + 1,0); + a[0]=a[1]=1; + v,p2,lg2, amax, mallow := a[2],4,1, 0.0, Void; + + foreach n in ([2 .. m]){ + v=a[n]=a[v] + a[n - v]; + f:=1.0*v/n; + if(f>=0.55) mallow=n; + amax=amax.max(f); + if(n==p2){ + println("Max in [2^%d, 2^%d]: %f".fmt(lg2, lg2+1, amax)); + amax,p2 = 0.0, (n+1).nextPowerOf2; + lg2+=1; + } + } + if(mallow) println("Winning number = ",mallow); +} + +hofstadterConwaySequence((2).pow(20)); diff --git a/Task/Hofstadter-Figure-Figure-sequences/AWK/hofstadter-figure-figure-sequences.awk b/Task/Hofstadter-Figure-Figure-sequences/AWK/hofstadter-figure-figure-sequences.awk new file mode 100644 index 0000000000..7f033ecea7 --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/AWK/hofstadter-figure-figure-sequences.awk @@ -0,0 +1,89 @@ +# Hofstadter Figure-Figure sequences +# +# R(1) = 1; S(1) = 2; +# R(n) = R(n-1) + S(n-1), n > 1 +# S(n) is the values not in R(n) + +BEGIN { + + # start with the first two values of R and S to simplify finding S[n]: + R[ 1 ] = 1; + R[ 2 ] = 3; + S[ 1 ] = 2; + S[ 2 ] = 4; + # maximum n we currently have of R and S + rMax = 2; + sMax = 2; + + # calculate and show the first 10 values of R: + printf( "R[1..10]:" ); + for( n = 1; n < 11; n ++ ) + { + printf( " %d", ffr( n ) ); + } + printf( "\n" ); + # check that R[1..40] and S[1..960] contain the numbers 1..1000 once each + # add the values of R[ 1..40 ] to the set V + for( n = 1; n <= 40; n ++ ) + { + V[ ffr( n ) ] ++; + } + # add the values of S[ 1..960 ] to the set V + for( n = 1; n <= 960; n ++ ) + { + V[ ffs( n ) ] ++; + } + # check all numbers are present and not duplicated + ok = 1; + for( n = 1; n <= 1000; n ++ ) + { + if( ! ( n in V ) ) + { + printf( "%d not present in R[1..40], S[1..960]\n", n ); + ok = 0; + } + else if( V[ n ] != 1 ) + { + printf( "%d occurs %d times in R[1..40], S[1..960]\n", n, V[ n ] ); + ok = 0; + } + } + if( ok ) + { + printf( "R[1..40] and S[1..960] uniquely contain all 1..1000\n" ); + } + +} # BEGIN + +function ffr( n ) +{ + # calculate R[n] + if( ! ( n in R ) ) + { + # we haven't calculated R[ n ] yet + R[ n ] = ffs( n - 1 ); + R[ n ] += ffr( n - 1 ); + } +return R[ n ]; +} # ffr + +function ffs( n ) +{ + # calculate S[n] + if( ! ( n in S ) ) + { + # starting at the highest known R, calculate the next one and fill in the S values + # continuing until we have enough S values + do + { + R[ rMax + 1 ] = R[ rMax ] + S[ rMax ]; + for( sValue = R[ rMax ] + 1; sValue < R[ rMax + 1 ]; sValue ++ ) + { + S[ sMax ++ ] = sValue; + } + rMax ++; + } + while( sMax < n ); + } +return S[ n ]; +} # ffs diff --git a/Task/Hofstadter-Figure-Figure-sequences/Common-Lisp/hofstadter-figure-figure-sequences-1.lisp b/Task/Hofstadter-Figure-Figure-sequences/Common-Lisp/hofstadter-figure-figure-sequences-1.lisp deleted file mode 100644 index bb071d4c53..0000000000 --- a/Task/Hofstadter-Figure-Figure-sequences/Common-Lisp/hofstadter-figure-figure-sequences-1.lisp +++ /dev/null @@ -1,34 +0,0 @@ -;;; equally doable with a list -(flet ((seq (i) (make-array 1 :element-type 'integer - :initial-element i - :fill-pointer 1 - :adjustable t))) - (let ((rr (seq 1)) (ss (seq 2))) - (labels ((extend-r () - (let* ((l (1- (length rr))) - (r (+ (aref rr l) (aref ss l))) - (s (elt ss (1- (length ss))))) - (vector-push-extend r rr) - (loop while (<= s r) do - (if (/= (incf s) r) - (vector-push-extend s ss)))))) - (defun seq-r (n) - (loop while (> n (length rr)) do (extend-r)) - (elt rr (1- n))) - - (defun seq-s (n) - (loop while (> n (length ss)) do (extend-r)) - (elt ss (1- n)))))) - -(defun take (f n) - (loop for x from 1 to n collect (funcall f x))) - -(format t "First of R: ~a~%" (take #'seq-r 10)) - -(mapl (lambda (l) (if (and (cdr l) - (/= (1+ (car l)) (cadr l))) - (error "not in sequence"))) - (sort (append (take #'seq-r 40) - (take #'seq-s 960)) - #'<)) -(princ "Ok") diff --git a/Task/Hofstadter-Figure-Figure-sequences/Common-Lisp/hofstadter-figure-figure-sequences-2.lisp b/Task/Hofstadter-Figure-Figure-sequences/Common-Lisp/hofstadter-figure-figure-sequences-2.lisp deleted file mode 100644 index e405bc5764..0000000000 --- a/Task/Hofstadter-Figure-Figure-sequences/Common-Lisp/hofstadter-figure-figure-sequences-2.lisp +++ /dev/null @@ -1,2 +0,0 @@ -First of R: (1 3 7 12 18 26 35 45 56 69) -Ok diff --git a/Task/Hofstadter-Figure-Figure-sequences/Kotlin/hofstadter-figure-figure-sequences.kotlin b/Task/Hofstadter-Figure-Figure-sequences/Kotlin/hofstadter-figure-figure-sequences.kotlin index 4eec6b69c3..a9f05301b8 100644 --- a/Task/Hofstadter-Figure-Figure-sequences/Kotlin/hofstadter-figure-figure-sequences.kotlin +++ b/Task/Hofstadter-Figure-Figure-sequences/Kotlin/hofstadter-figure-figure-sequences.kotlin @@ -1,5 +1,3 @@ -package hofstadter - fun ffr(n: Int) = get(n, 0)[n - 1] fun ffs(n: Int) = get(0, n)[n - 1] diff --git a/Task/Hofstadter-Figure-Figure-sequences/Sidef/hofstadter-figure-figure-sequences.sidef b/Task/Hofstadter-Figure-Figure-sequences/Sidef/hofstadter-figure-figure-sequences.sidef index ce099194fd..84ce9bc988 100644 --- a/Task/Hofstadter-Figure-Figure-sequences/Sidef/hofstadter-figure-figure-sequences.sidef +++ b/Task/Hofstadter-Figure-Figure-sequences/Sidef/hofstadter-figure-figure-sequences.sidef @@ -3,33 +3,33 @@ var s = [nil, 2] func ffsr(n) { while(r.end < n) { - r << s[r.end]+r[-1]; + r << s[r.end]+r[-1] s << [(s[-1]+1 .. r[-1]-1)..., r[-1]+1].grep{ s[-1] < _ }... } - return n; + return n } func ffr(n) { r[ffsr(n)] } func ffs(n) { s[ffsr(n)] } -printf(" i: R(i) S(i)\n"); -printf("==============\n"); -10.of { |i| - printf("%3d: %3d %3d\n", i, ffr(i), ffs(i)) -} -printf("\nR(40)=%3d S(960)=%3d R(41)=%3d\n", ffr(40), ffs(960), ffr(41)); +printf(" i: R(i) S(i)\n") +printf("==============\n") +{ |i| + printf("%3d:  %3d  %3d\n", i, ffr(i), ffs(i)) +} << 1..10 +printf("\nR(40)=%3d S(960)=%3d R(41)=%3d\n", ffr(40), ffs(960), ffr(41)) var seen = Hash() -40.of { |i| seen{ffr(i)} := 0 ++ } -960.of { |i| seen{ffs(i)} := 0 ++ } +{|i| seen{ffr(i)} := 0 ++ } << 1..40 +{|i| seen{ffs(i)} := 0 ++ } << 1..960 if (seen.count {|k,v| (k.to_i >= 1) && (k.to_i <= 1000) && (v == 1) } == 1000) { - say "All occured exactly once."; + say "All occured exactly once." } else { - var missed = (1..1000 -> grep { !seen.has_key(_) }) - var dupped = seen.grep { |_, v| v > 1 }.keys.sort; - say "These were missed: #{missed}"; - say "These were duplicated: #{dupped}"; + var missed = { !seen.has_key(_) }.grep(1..1000) + var dupped = seen.grep { |_, v| v > 1 }.keys.sort + say "These were missed: #{missed}" + say "These were duplicated: #{dupped}" } diff --git a/Task/Hofstadter-Figure-Figure-sequences/Zkl/hofstadter-figure-figure-sequences-1.zkl b/Task/Hofstadter-Figure-Figure-sequences/Zkl/hofstadter-figure-figure-sequences-1.zkl new file mode 100644 index 0000000000..b59754adf8 --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/Zkl/hofstadter-figure-figure-sequences-1.zkl @@ -0,0 +1,12 @@ +fcn genRS(reset=False){ //-->(n,R,S) + var n=0, Rs=L(0,1), S=2; + if(True==reset){ n=0; Rs=L(0,1); S=2; return(); } + + if (n==0) return(n=1,1,2); + R:=Rs[-1] + S; Rs.append(R); + foreach s in ([S+1..]){ + if(not Rs.holds(s)) { S=s; break; } // trimming Rs doesn't save space + } + return(n+=1,R,S); +} +fcn ffrs(n) { genRS(True); do(n){ n=genRS() } n[1,2] } //-->( R(n),S(n) ) diff --git a/Task/Hofstadter-Figure-Figure-sequences/Zkl/hofstadter-figure-figure-sequences-2.zkl b/Task/Hofstadter-Figure-Figure-sequences/Zkl/hofstadter-figure-figure-sequences-2.zkl new file mode 100644 index 0000000000..2479b9a298 --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/Zkl/hofstadter-figure-figure-sequences-2.zkl @@ -0,0 +1,4 @@ +genRS(True); // reset +sink:=(0).pump(40,List, 'wrap(ns){ T(Void.Write,Void.Write,genRS()[1,*]) }); +sink= (0).pump(960-40,sink,'wrap(ns){ T(Void.Write,genRS()[2]) }); +(sink.sort()==[1..1000].walk()).println("<-- should be True"); diff --git a/Task/Hofstadter-Q-sequence/Common-Lisp/hofstadter-q-sequence-3.lisp b/Task/Hofstadter-Q-sequence/Common-Lisp/hofstadter-q-sequence-3.lisp deleted file mode 100644 index 363deb7e14..0000000000 --- a/Task/Hofstadter-Q-sequence/Common-Lisp/hofstadter-q-sequence-3.lisp +++ /dev/null @@ -1,12 +0,0 @@ -(let ((cc (make-array 3 :element-type 'integer - :initial-element 1 - :adjustable t - :fill-pointer 3))) - (defun q (n) - (when (>= n (length cc)) - (loop for i from (length cc) below n do (q i)) - (vector-push-extend - (+ (aref cc (- n (aref cc (- n 1)))) - (aref cc (- n (aref cc (- n 2))))) - cc)) - (aref cc n))) diff --git a/Task/Hofstadter-Q-sequence/jq/hofstadter-q-sequence-1.jq b/Task/Hofstadter-Q-sequence/Jq/hofstadter-q-sequence-1.jq similarity index 100% rename from Task/Hofstadter-Q-sequence/jq/hofstadter-q-sequence-1.jq rename to Task/Hofstadter-Q-sequence/Jq/hofstadter-q-sequence-1.jq diff --git a/Task/Hofstadter-Q-sequence/jq/hofstadter-q-sequence-2.jq b/Task/Hofstadter-Q-sequence/Jq/hofstadter-q-sequence-2.jq similarity index 100% rename from Task/Hofstadter-Q-sequence/jq/hofstadter-q-sequence-2.jq rename to Task/Hofstadter-Q-sequence/Jq/hofstadter-q-sequence-2.jq diff --git a/Task/Hofstadter-Q-sequence/Kotlin/hofstadter-q-sequence.kotlin b/Task/Hofstadter-Q-sequence/Kotlin/hofstadter-q-sequence.kotlin new file mode 100644 index 0000000000..1f50a632fa --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Kotlin/hofstadter-q-sequence.kotlin @@ -0,0 +1,13 @@ +// version 1.1.4 + +fun main(args: Array) { + val q = IntArray(100_001) + q[1] = 1 + q[2] = 1 + for (n in 3..100_000) q[n] = q[n - q[n - 1]] + q[n - q[n - 2]] + print("The first 10 terms are : ") + for (i in 1..10) print("${q[i]} ") + println("\n\nThe 1000th term is : ${q[1000]}") + val flips = (2..100_000).count { q[it] < q[it - 1] } + println("\nThe number of flips for the first 100,000 terms is : $flips") +} diff --git a/Task/Hofstadter-Q-sequence/Scheme/hofstadter-q-sequence-1.ss b/Task/Hofstadter-Q-sequence/Scheme/hofstadter-q-sequence-1.ss deleted file mode 100644 index f3bb905a55..0000000000 --- a/Task/Hofstadter-Q-sequence/Scheme/hofstadter-q-sequence-1.ss +++ /dev/null @@ -1,47 +0,0 @@ -(define qc '#(0 1 1)) -(define filled 3) -(define len 3) - -;; chicken scheme: vector-resize! -;; gambit: vector-append -(define (extend-qc) - (let* ((new-len (* 2 len)) - (new-qc (make-vector new-len))) - (let copy ((n 0)) - (if (< n len) - (begin - (vector-set! new-qc n (vector-ref qc n)) - (copy (+ 1 n))))) - (set! len new-len) - (set! qc new-qc))) - -(define (q n) - (let loop () - (if (>= filled len) (extend-qc)) - (if (>= n filled) - (begin - (vector-set! qc filled (+ (q (- filled (q (- filled 1)))) - (q (- filled (q (- filled 2)))))) - (set! filled (+ 1 filled)) - (loop)) - (vector-ref qc n)))) - -(display "Q(1 .. 10): ") -(let loop ((i 1)) - ;; (print) behave differently regarding newline across compilers - (display (q i)) - (display " ") - (if (< i 10) - (loop (+ 1 i)) - (newline))) - -(display "Q(1000): ") -(display (q 1000)) -(newline) - -(display "bumps up to 100000: ") -(display - (let loop ((s 0) (i 1)) - (if (>= i 100000) s - (loop (+ s (if (> (q i) (q (+ 1 i))) 1 0)) (+ 1 i))))) -(newline) diff --git a/Task/Hofstadter-Q-sequence/Scheme/hofstadter-q-sequence-2.ss b/Task/Hofstadter-Q-sequence/Scheme/hofstadter-q-sequence-2.ss deleted file mode 100644 index 35644fa2ca..0000000000 --- a/Task/Hofstadter-Q-sequence/Scheme/hofstadter-q-sequence-2.ss +++ /dev/null @@ -1,3 +0,0 @@ -Q(1 .. 10): 1 1 2 3 3 4 5 5 6 6 -Q(1000): 502 -bumps up to 100000: 49798 diff --git a/Task/Hofstadter-Q-sequence/Sidef/hofstadter-q-sequence-1.sidef b/Task/Hofstadter-Q-sequence/Sidef/hofstadter-q-sequence-1.sidef index 6d5da09d2e..fc1f0ec24d 100644 --- a/Task/Hofstadter-Q-sequence/Sidef/hofstadter-q-sequence-1.sidef +++ b/Task/Hofstadter-Q-sequence/Sidef/hofstadter-q-sequence-1.sidef @@ -1,8 +1,8 @@ func Q(n) is cached { - n <= 2 ? 1 - : Q(n - Q(n-1))+Q(n-Q(n-2)) + n <= 2 ? 1 +  : Q(n - Q(n-1))+Q(n-Q(n-2)) } - -say "First 10 terms: #{10.of {|n| Q(n) }.dump }" +  +say "First 10 terms: #{ {|n| Q(n) }.map(1..10) }" say "Term 1000: #{Q(1000)}" say "Terms less than preceding in first 100k: #{2..100000->count{|i|Q(i)count{|i|Q[i] q[i + 1]) } +println("flips: ",flip); diff --git a/Task/Holidays-related-to-Easter/Bc/holidays-related-to-easter-1.bc b/Task/Holidays-related-to-Easter/Bc/holidays-related-to-easter-1.bc new file mode 100644 index 0000000000..0013dfd870 --- /dev/null +++ b/Task/Holidays-related-to-Easter/Bc/holidays-related-to-easter-1.bc @@ -0,0 +1,60 @@ +scale = 0 + +/* Format d days after March 21. Assumes March, April, May or June. */ +define format(d) { + if (d > 80) { print " Jun ", d - 71 + } else if (d > 71) { print " Jun 0", d - 71 + } else if (d > 49) { print " May ", d - 40 + } else if (d > 40) { print " May 0", d - 40 + } else if (d > 19) { print " Apr ", d - 10 + } else if (d > 10) { print " Apr 0", d - 10 + } else { print " Mar ", d + 21 + } +} + +/* + * For year n, print Easter and related holidays. + * Assumes n >= 1, scale = 0. + */ +define easter(n) { + auto a, b, d, e, j + + /* + * Calculate e = day of Easter, following the 1886 paper, + * Kalender-Formeln (Calendar Formulae) by Chr. Zeller. + * http://www.merlyn.demon.co.uk/zel-1886.htm + * + * With bc, p % 7 gives the wrong result when p < 0. To give the + * correct result, this code uses "+ 6 * j" where one might have + * used "- j". This works because because 6 == -1 (mod 7). + */ + if (n < 1583) { + /* Julian calendar (before October 1582) */ + b = (19 * (n % 19) + 15) % 30 + d = (b + n + n / 4) % 7 + } else { + /* Gregorian calendar (after October 1582) */ + j = n / 100 + a = n % 19 + b = (19 * a + 15 + j - (8 * j + 13) / 25 - j / 4) % 30 + d = (b + n + n / 4 + 6 * j + j / 4 + 2) % 7 + if (d == 0 && (b == 29 || (b == 28 && a > 10))) d = 7 + } + e = b + 7 - d /* This counts days after 21 March. */ + + if(n < 1000) " " + print n + z = format(e) /* Easter */ + z = format(e + 39) /* Ascension Thursday */ + z = format(e + 49) /* Pentecost */ + z = format(e + 56) /* Trinity Sunday */ + z = format(e + 60) /* Corpus Christi */ + print "\n" +} + +print " Easter Ascension Trinity Corpus\n" +print " AD Sunday Thursday Pentecost Sunday Christi\n" +for (year = 400; year <= 2000; year += 100) z = easter(year) +for (year = 2010; year <= 2020; year += 1) z = easter(year) +z = easter(2100) +quit diff --git a/Task/Holidays-related-to-Easter/Bc/holidays-related-to-easter-2.bc b/Task/Holidays-related-to-Easter/Bc/holidays-related-to-easter-2.bc new file mode 100644 index 0000000000..fbad69de84 --- /dev/null +++ b/Task/Holidays-related-to-Easter/Bc/holidays-related-to-easter-2.bc @@ -0,0 +1,55 @@ +scale = 0 + +/* Format d days after March 21. Assumes March, April, May or June. */ +define format(d) { + if (d > 80) { print " Jun ", d - 71 + } else if (d > 71) { print " Jun 0", d - 71 + } else if (d > 49) { print " May ", d - 40 + } else if (d > 40) { print " May 0", d - 40 + } else if (d > 19) { print " Apr ", d - 10 + } else if (d > 10) { print " Apr 0", d - 10 + } else { print " Mar ", d + 21 + } +} + +/* + * For year n, print Easter and related holidays. + * Assumes n >= 1, scale = 0. + */ +define easter(n) { + auto a, b, d, e, j + + /* + * Calculate e = day of Easter, following the 1886 paper, + * Kalender-Formeln (Calendar Formulae) by Chr. Zeller. + * http://www.merlyn.demon.co.uk/zel-1886.htm + */ + b = (19 * (n % 19) + 15) % 30 + d = (b + n + n / 4) % 7 + e = b + 7 - d /* This counts days after 21 March. */ + + /* + * Starting at 1924 March 10 (Julian) / March 23 (Gregorian), + * change to the Gregorian calendar. Easter 1924 is April 27, + * after this change. + */ + if (n >= 1924) { + /* This formula only works from March to December. */ + e += n / 100 - n / 400 - 2 + } + + if(n < 1000) " " + print n + z = format(e) /* Easter */ + z = format(e + 39) /* Ascension Thursday */ + z = format(e + 49) /* Pentecost */ + z = format(e + 56) /* All Saints' Sunday */ + print "\n" +} + +print " Easter Ascension All\n" +print " AD Sunday Thursday Pentecost Saints\n" +for (year = 400; year <= 2000; year += 100) z = easter(year) +for (year = 2010; year <= 2020; year += 1) z = easter(year) +z = easter(2100) +quit diff --git a/Task/Holidays-related-to-Easter/Julia/holidays-related-to-easter.julia b/Task/Holidays-related-to-Easter/Julia/holidays-related-to-easter.julia new file mode 100644 index 0000000000..f194811192 --- /dev/null +++ b/Task/Holidays-related-to-Easter/Julia/holidays-related-to-easter.julia @@ -0,0 +1,43 @@ +# v0.6 + +using Dates + +function easter(year::Int)::Date + a = rem(year, 19) + b, c = divrem(year, 100) + d = rem(19a + b - div(b, 4) - div(b - div(b + 8, 25) + 1, 3) + 15, 30) + e = rem(32 + 2 * rem(b, 4) + 2 * div(c, 4) - d - rem(c, 4), 7) + f = d + e - 7 * div(a + 11d + 22e, 451) + 114 + month, day = divrem(f, 31) + day += 1 + return Date(year, month, day) +end + +function holiday_values(year::Int)::Dict{String,Date} + offsets = Dict{String,Day}("Easter" => Day(0), "Ascension" => Day(39), + "Pentecost" => Day(49), "Trinity" => Day(56), "Corpus" => Day(60)) + easterdate = easter(year) + rst = Dict{String,Date}(holiday => easterdate + days for (holiday, days) in offsets) + return rst +end + +function holiday2str(year::Int)::String + function holiday2str(holiday::String, date::Date)::String + dayname, daynumb, month = dayabbr(date), day(date), monthabbr(date) + return @sprintf "%s: %s %2i %s" holiday dayname daynumb month + end + cal = holiday_values(year) + rst = join(collect(holiday2str(hday, cal[hday]) for hday in + ("Easter", "Ascension", "Pentecost", "Trinity", "Corpus")), ", ") + return "$year -> " * rst +end + +println("\nChristian holidays, related to Easter, for each centennial from 400 to 2100 CE:") +for yr in 400:100:2200 + println(holiday2str(yr)) +end + +println("\nChristian holidays, related to Easter, for years from 2010 to 2020 CE:") +for yr in 2010:2020 + println(holiday2str(yr)) +end diff --git a/Task/Holidays-related-to-Easter/Kotlin/holidays-related-to-easter.kotlin b/Task/Holidays-related-to-Easter/Kotlin/holidays-related-to-easter.kotlin new file mode 100644 index 0000000000..d0b4a16bb4 --- /dev/null +++ b/Task/Holidays-related-to-Easter/Kotlin/holidays-related-to-easter.kotlin @@ -0,0 +1,58 @@ +// version 1.1.2 + +import java.util.Calendar +import java.util.GregorianCalendar + +val holidayOffsets = listOf( + "Easter" to 0, + "Ascension" to 39, + "Pentecost" to 49, + "Trinity" to 56, + "C/Christi" to 60 +) + +fun String.padCenter(n: Int): String { + val len = this.length + if (n <= len) return this + return this.padStart((n + len) / 2).padEnd(n) +} + +fun calculateEaster(year: Int): GregorianCalendar { + val a = year % 19 + val b = year / 100 + val c = year % 100 + val d = b / 4 + val e = b % 4 + val f = (b + 8) / 25 + val g = (b - f + 1) / 3 + val h = (19 * a + b - d - g + 15) % 30 + val i = c / 4 + val k = c % 4 + val l = (32 + 2 * e + 2 * i - h - k) % 7 + val m = (a + 11 * h + 22 * l) / 451 + val n = h + l - 7 * m + 114 + val month = n / 31 - 1 // months indexed from 0 + val day = (n % 31) + 1 + return GregorianCalendar(year, month, day) +} + +fun outputHolidays(year: Int) { + val date = calculateEaster(year) + print("%4d ".format(year)) + var po = 0 + for ((h, o) in holidayOffsets) { + date.add(Calendar.DATE, o - po) + po = o + print("${"%1\$td %1\$tb".format(date).padCenter(h.length)} ") + } + println() +} + +fun main(args: Array) { + println("Year Easter Ascension Pentecost Trinity C/Christi") + println(" CE Sunday Thursday Sunday Sunday Thursday ") + println("---- ------ --------- --------- ------- ---------") + for (year in 400..2100 step 100) outputHolidays(year) + println() + for (year in 2010..2020) outputHolidays(year) +} diff --git a/Task/Holidays-related-to-Easter/Phix/holidays-related-to-easter.phix b/Task/Holidays-related-to-Easter/Phix/holidays-related-to-easter.phix new file mode 100644 index 0000000000..ac034afbcc --- /dev/null +++ b/Task/Holidays-related-to-Easter/Phix/holidays-related-to-easter.phix @@ -0,0 +1,59 @@ +-- +-- demo\rosetta\Easter.exw +-- ======================= +-- +function easter(integer year) +-- from https://en.wikipedia.org/wiki/Computus#Anonymous_Gregorian_algorithm + integer a = mod(year,19), + b = floor(year/100), + c = mod(year,100), + d = floor(b/4), + e = mod(b,4), + f = floor((b+8)/25), + g = floor((b-f+1)/3), + h = mod(19*a+b-d-g+15,30), + i = floor(c/4), + k = mod(c,4), + l = mod(32+2*e+2*i-h-k,7), + m = floor((a+11*h+22*l)/451), + n = h+l-7*m+114, + month = floor(n/31), + day = mod(n,31)+1 + return {year,month,day,0,0,0,0,0,0} +end function + +constant dates = {{"Easter ",0}, + {"Ascension",39}, + {"Pentecost",49}, + {"Trinity ",56}, + {"Corpus ",60}} + +constant fmt = join(repeat(" %12s",length(dates))), + fmt0 = " "&fmt&"\n", + fmtN = "%4d"&fmt&"\n" + +include builtins\timedate.e + +set_timedate_formats({"Ddd ddth Mmm"}) + +procedure show(integer year) + if year=0 then + printf(1,fmt0, columnize(dates,1)[1]) + else + timedate e = easter(year) + sequence args = {year} + for i=1 to length(dates) do + string d = format_timedate(adjust_timedate(e,timedelta(days:=dates[i][2]))) + args = append(args,d) + end for + printf(1,fmtN, args) + end if +end procedure +show(0) +for year=400 to 2000 by 100 do + show(year) +end for +show(0) +for year=2010 to 2020 do + show(year) +end for diff --git a/Task/Holidays-related-to-Easter/Sidef/holidays-related-to-easter.sidef b/Task/Holidays-related-to-Easter/Sidef/holidays-related-to-easter.sidef index 5e6d435b40..b3b0632385 100644 --- a/Task/Holidays-related-to-Easter/Sidef/holidays-related-to-easter.sidef +++ b/Task/Holidays-related-to-Easter/Sidef/holidays-related-to-easter.sidef @@ -1,6 +1,6 @@ -require('Date::Calc'); +require('Date::Calc') -var abbr = < Nil Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec >; +var abbr = < Nil Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec > var holidays = [ [Easter => 0], @@ -8,37 +8,37 @@ var holidays = [ [Pentecost => 49], [Trinity => 56], [Corpus => 60], -]; +] func easter(year) { - var ay = (year % 19); - var by = int(year / 100); - var cy = (year % 100); - var dy = int(by / 4); - var ey = (by % 4); - var fy = int((by + 8) / 25); - var gy = int((by - fy + 1) / 3); - var hy = ((19*ay + by - dy - gy + 15) % 30); - var iy = int(cy / 4); - var ky = (cy % 4); - var ly = ((32 + 2*ey + 2*iy - hy - ky) % 7); - var md = (hy + ly - 7*int((ay + 11*hy + 22*ly) / 451) + 114); - var month = int(md / 31); - var day = (md % 31 + 1); - return(month, day); + var ay = (year % 19) + var by = (year // 100) + var cy = (year % 100) + var dy = (by // 4) + var ey = (by % 4) + var fy = ((by + 8) // 25) + var gy = ((by - fy + 1) // 3) + var hy = ((19*ay + by - dy - gy + 15) % 30) + var iy = (cy // 4) + var ky = (cy % 4) + var ly = ((32 + 2*ey + 2*iy - hy - ky) % 7) + var md = (hy + ly - 7*((ay + 11*hy + 22*ly) // 451) + 114) + var month = (md // 31) + var day = (md % 31 + 1) + return(month, day) } - +  func cholidays(year) { - var (emon, eday) = easter(year); - printf("%4s: ", year); + var (emon, eday) = easter(year) + printf("%4s: ", year) say gather { holidays.each { |holiday| - var (_, mo, da) = %S'Date::Calc'.Add_Delta_Days(year, emon, eday, holiday[1]); - take("#{holiday[0]}: #{'%02d' % da} #{abbr[mo]}") + var (_, mo, da) = %S.Add_Delta_Days(year, emon, eday, holiday[1]) + take("#{holiday[0]}: #{'%02d' % da} #{abbr[mo]}") } - }.join(', '); + }.join(', ') } - -[400..(2100, 100), 2010..2020, 2100].flatten.each { |year| - cholidays(year); +  +for year in (400..2100 `by` 100, 2010..2020) { + cholidays(year) } diff --git a/Task/Honeycombs/Java/honeycombs-1.java b/Task/Honeycombs/Java/honeycombs-1.java deleted file mode 100644 index dbc6a6093e..0000000000 --- a/Task/Honeycombs/Java/honeycombs-1.java +++ /dev/null @@ -1,131 +0,0 @@ -import java.awt.*; -import java.awt.event.*; -import javax.swing.*; - -public class Honeycombs extends JFrame { - - public static void main(String[] args) { - SwingUtilities.invokeLater(() -> { - JFrame f = new Honeycombs(); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - f.setVisible(true); - }); - } - - public Honeycombs() { - add(new HoneycombsPanel(), BorderLayout.CENTER); - setTitle("Honeycombs"); - setResizable(false); - pack(); - setLocationRelativeTo(null); - } -} - -class HoneycombsPanel extends JPanel { - - Hexagon[] comb; - - public HoneycombsPanel() { - setPreferredSize(new Dimension(600, 500)); - setBackground(Color.white); - setFocusable(true); - - addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - for (Hexagon hex : comb) - if (hex.contains(e.getX(), e.getY())) { - hex.setSelected(); - break; - } - repaint(); - } - }); - - addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - for (Hexagon hex : comb) - if (hex.letter == Character.toUpperCase(e.getKeyChar())) { - hex.setSelected(); - break; - } - repaint(); - } - }); - - char[] letters = "LRDGITPFBVOKANUYCESM".toCharArray(); - comb = new Hexagon[20]; - - int x1 = 150, y1 = 100, x2 = 225, y2 = 143, w = 150, h = 87; - for (int i = 0; i < comb.length; i++) { - int x, y; - if (i < 12) { - x = x1 + (i % 3) * w; - y = y1 + (i / 3) * h; - } else { - x = x2 + (i % 2) * w; - y = y2 + ((i - 12) / 2) * h; - } - comb[i] = new Hexagon(x, y, w / 3, letters[i]); - } - - requestFocus(); - } - - @Override - public void paintComponent(Graphics gg) { - super.paintComponent(gg); - Graphics2D g = (Graphics2D) gg; - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - g.setFont(new Font("SansSerif", Font.BOLD, 30)); - g.setStroke(new BasicStroke(3)); - - for (Hexagon hex : comb) - hex.draw(g); - } -} - -class Hexagon extends Polygon { - final Color baseColor = Color.yellow; - final Color selectedColor = Color.magenta; - final char letter; - - private boolean hasBeenSelected; - - Hexagon(int x, int y, int halfWidth, char c) { - letter = c; - for (int i = 0; i < 6; i++) - addPoint((int) (x + halfWidth * Math.cos(i * Math.PI / 3)), - (int) (y + halfWidth * Math.sin(i * Math.PI / 3))); - getBounds(); - } - - void setSelected() { - hasBeenSelected = true; - } - - void draw(Graphics2D g) { - g.setColor(hasBeenSelected ? selectedColor : baseColor); - g.fillPolygon(this); - - g.setColor(Color.black); - g.drawPolygon(this); - - g.setColor(hasBeenSelected ? Color.black : Color.red); - drawCenteredString(g, String.valueOf(letter)); - } - - void drawCenteredString(Graphics2D g, String s) { - FontMetrics fm = g.getFontMetrics(); - int asc = fm.getAscent(); - int dec = fm.getDescent(); - - int x = bounds.x + (bounds.width - fm.stringWidth(s)) / 2; - int y = bounds.y + (asc + (bounds.height - (asc + dec)) / 2); - - g.drawString(s, x, y); - } -} diff --git a/Task/Honeycombs/Java/honeycombs-2.java b/Task/Honeycombs/Java/honeycombs-2.java deleted file mode 100644 index 84f41e2dca..0000000000 --- a/Task/Honeycombs/Java/honeycombs-2.java +++ /dev/null @@ -1,184 +0,0 @@ -package graphics; - -import java.awt.BasicStroke; -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Polygon; -import java.awt.RenderingHints; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import javax.swing.JFrame; -import javax.swing.JPanel; - -import static java.util.Arrays.parallelSetAll; -import static java.util.Arrays.stream; -import static java.util.stream.IntStream.range; - -public class Honeycombs extends JFrame { - HoneycombsPanel panel; - - public static void main(String[] args) { - JFrame f = new Honeycombs(); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - f.setVisible(true); - } - - public Honeycombs() { - Container content = getContentPane(); - content.setLayout(new BorderLayout()); - panel = new HoneycombsPanel(); - content.add(panel, BorderLayout.CENTER); - setTitle("Honeycombs"); - setResizable(false); - pack(); - setLocationRelativeTo(null); - } -} - -class HoneycombsPanel extends JPanel { - Hexagon[] comb; - - @FunctionalInterface - private static interface MousePressed extends MouseListener { - public static MousePressed new_(MousePressed mousePressed) { - return mousePressed; - } - - @Override - public default void mouseClicked(MouseEvent mouseEvent) {} - - @Override - public default void mouseEntered(MouseEvent mouseEvent) {} - - @Override - public default void mouseExited(MouseEvent mouseEvent) {} - - @Override - public default void mouseReleased(MouseEvent mouseEvent) {} - } - - @FunctionalInterface - private static interface KeyPressed extends KeyListener { - public static KeyPressed new_(KeyPressed keyPressed) { - return keyPressed; - } - - @Override - public default void keyReleased(KeyEvent keyEvent) {} - - @Override - public default void keyTyped(KeyEvent keyEvent) {} - } - - public HoneycombsPanel() { - setPreferredSize(new Dimension(600, 500)); - setBackground(Color.white); - setFocusable(true); - - addMouseListener(MousePressed.new_(e -> { - stream(comb) - .filter(hex -> hex.contains(e.getX(), e.getY())) - .findFirst() - .ifPresent(hex -> hex.setSelected()) - ; - repaint(); - })); - - addKeyListener(KeyPressed.new_(e -> { - stream(comb) - .filter(hex -> hex.letter == Character.toUpperCase(e.getKeyChar())) - .findFirst() - .ifPresent(hex -> hex.setSelected()) - ; - repaint(); - })); - - char[] letters = "LRDGITPFBVOKANUYCESM".toCharArray(); - comb = new Hexagon[20]; - - int x1 = 150, y1 = 100, x2 = 225, y2 = 143, w = 150, h = 87; - parallelSetAll(comb, i -> { - int x, y; - if (i < 12) { - x = x1 + (i % 3) * w; - y = y1 + (i / 3) * h; - } else { - x = x2 + (i % 2) * w; - y = y2 + ((i - 12) / 2) * h; - } - return new Hexagon(x, y, w / 3, letters[i]); - }); - - requestFocus(); - } - - @Override - public void paintComponent(Graphics gg) { - super.paintComponent(gg); - Graphics2D g = (Graphics2D) gg; - g.setRenderingHint( - RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON - ); - - g.setFont(new Font("SansSerif", Font.BOLD, 30)); - g.setStroke(new BasicStroke(3)); - - stream(comb) - .forEach(hex -> hex.draw(g)) - ; - } -} - -class Hexagon extends Polygon { - final Color baseColor = Color.yellow; - final Color selectedColor = Color.magenta; - final char letter; - - private boolean hasBeenSelected; - - Hexagon(int x, int y, int halfWidth, char c) { - letter = c; - range(0, 6) - .forEach(i -> - addPoint((int) (x + halfWidth * Math.cos(i * Math.PI / 3)), - (int) (y + halfWidth * Math.sin(i * Math.PI / 3))) - ) - ; - getBounds(); - } - - void setSelected() { - hasBeenSelected = true; - } - - void draw(Graphics2D g) { - g.setColor(hasBeenSelected ? selectedColor : baseColor); - g.fillPolygon(this); - - g.setColor(Color.black); - g.drawPolygon(this); - - g.setColor(hasBeenSelected ? Color.black : Color.red); - drawCenteredString(g, String.valueOf(letter)); - } - - void drawCenteredString(Graphics2D g, String s) { - FontMetrics fm = g.getFontMetrics(); - int asc = fm.getAscent(); - int dec = fm.getDescent(); - - int x = bounds.x + (bounds.width - fm.stringWidth(s)) / 2; - int y = bounds.y + (asc + (bounds.height - (asc + dec)) / 2); - - g.drawString(s, x, y); - } -} diff --git a/Task/Honeycombs/Kotlin/honeycombs.kotlin b/Task/Honeycombs/Kotlin/honeycombs.kotlin new file mode 100644 index 0000000000..e8a395ca6a --- /dev/null +++ b/Task/Honeycombs/Kotlin/honeycombs.kotlin @@ -0,0 +1,147 @@ +// version 1.1.4 + +import java.awt.BasicStroke +import java.awt.BorderLayout +import java.awt.Color +import java.awt.Dimension +import java.awt.Font +import java.awt.Graphics +import java.awt.Graphics2D +import java.awt.Polygon +import java.awt.RenderingHints +import java.awt.event.KeyAdapter +import java.awt.event.KeyEvent +import java.awt.event.MouseAdapter +import java.awt.event.MouseEvent +import java.awt.event.WindowEvent +import javax.swing.JFrame +import javax.swing.JPanel +import javax.swing.SwingUtilities + +class Honeycombs : JPanel() { + private val comb: Array = arrayOfNulls(20) + + init { + preferredSize = Dimension(600, 500) + background = Color.white + isFocusable = true + + addMouseListener(object : MouseAdapter() { + override fun mousePressed(e: MouseEvent) { + for (hex in comb) + if (hex!!.contains(e.x, e.y)) { + hex.setSelected() + checkForClosure() + break + } + repaint() + } + }) + + addKeyListener(object : KeyAdapter() { + override fun keyPressed(e: KeyEvent) { + for (hex in comb) + if (hex!!.letter == e.keyChar.toUpperCase()) { + hex.setSelected() + checkForClosure() + break + } + repaint() + } + }) + + val letters = "LRDGITPFBVOKANUYCESM".toCharArray() + val x1 = 150 + val y1 = 100 + val x2 = 225 + val y2 = 143 + val w = 150 + val h = 87 + + for (i in 0 until comb.size) { + var x: Int + var y: Int + if (i < 12) { + x = x1 + (i % 3) * w + y = y1 + (i / 3) * h + } + else { + x = x2 + (i % 2) * w + y = y2 + ((i - 12) / 2) * h + } + comb[i] = Hexagon(x, y, w / 3, letters[i]) + } + + requestFocus() + } + + override fun paintComponent(gg: Graphics) { + super.paintComponent(gg) + val g = gg as Graphics2D + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON) + g.font = Font("SansSerif", Font.BOLD, 30) + g.stroke = BasicStroke(3.0f) + for (hex in comb) hex!!.draw(g) + } + + private fun checkForClosure() { + if (comb.all { it!!.hasBeenSelected } ) { + val f = SwingUtilities.getWindowAncestor(this) as JFrame + f.dispatchEvent(WindowEvent(f, WindowEvent.WINDOW_CLOSING)) + } + } +} + +class Hexagon(x: Int, y: Int, halfWidth: Int, c: Char) : Polygon() { + private val baseColor = Color.yellow + private val selectedColor = Color.magenta + var hasBeenSelected = false + val letter = c + + init { + for (i in 0..5) + addPoint((x + halfWidth * Math.cos(i * Math.PI / 3.0)).toInt(), + (y + halfWidth * Math.sin(i * Math.PI / 3.0)).toInt()) + getBounds() + } + + fun setSelected() { + hasBeenSelected = true + } + + fun draw(g: Graphics2D) { + with(g) { + color = if (hasBeenSelected) selectedColor else baseColor + fillPolygon(this@Hexagon) + color = Color.black + drawPolygon(this@Hexagon) + color = if (hasBeenSelected) Color.black else Color.red + drawCenteredString(g, letter.toString()) + } + } + + private fun drawCenteredString(g: Graphics2D, s: String) { + val fm = g.fontMetrics + val asc = fm.ascent + val dec = fm.descent + val x = bounds.x + (bounds.width - fm.stringWidth(s)) / 2 + val y = bounds.y + (asc + (bounds.height - (asc + dec)) / 2) + g.drawString(s, x, y) + } +} + +fun main(args: Array) { + SwingUtilities.invokeLater { + val f = JFrame() + with(f) { + defaultCloseOperation = JFrame.EXIT_ON_CLOSE + add(Honeycombs(), BorderLayout.CENTER) + title = "Honeycombs" + isResizable = false + pack() + setLocationRelativeTo(null) + isVisible = true + } + } +} diff --git a/Task/Honeycombs/Sidef/honeycombs.sidef b/Task/Honeycombs/Sidef/honeycombs.sidef index c46b473a87..fcc2b66000 100644 --- a/Task/Honeycombs/Sidef/honeycombs.sidef +++ b/Task/Honeycombs/Sidef/honeycombs.sidef @@ -63,7 +63,7 @@ class Honeycombs( } method display(title) { - fork { + { var mw = %s'MainWindow'.new('-title' => title) var canvas = mw.Canvas('-width' => 8*size, '-height' => 8*size).pack @@ -77,7 +77,7 @@ class Honeycombs( ).pack mw.bind('', { btn.invoke }) tk.MainLoop() - } + }.fork } } diff --git a/Task/Horizontal-sundial-calculations/FreeBASIC/horizontal-sundial-calculations.freebasic b/Task/Horizontal-sundial-calculations/FreeBASIC/horizontal-sundial-calculations.freebasic new file mode 100644 index 0000000000..3c61d65530 --- /dev/null +++ b/Task/Horizontal-sundial-calculations/FreeBASIC/horizontal-sundial-calculations.freebasic @@ -0,0 +1,35 @@ +' version 04-11-2016 +' compile with: fbc -s console + +#Macro deg2rad (x) + (x) * Atn(1) / 45 +#EndMacro + +#Macro rad2deg (x) + (x) * 45 / Atn(1) +#EndMacro + +' ------=< MAIN >=------ + +Dim As Double latitude, longitude, meridian, hra, hla +Dim As ULong h + +Input " Enter latitude (degrees): ", latitude +Input " Enter longitude (degrees): ", longitude +Input "Enter legal meridian (degrees): ", meridian + +Print +Print " Time Sun hour angle Dial hour line angle" + +For h = 6 To 18 + hra = h * 15 - longitude + meridian - 180 + hla = rad2deg(Atn(Sin(deg2rad(latitude)) * Tan(deg2rad(hra)))) + If Abs(hra) > 90 Then hla += 180 * Sgn(hra * latitude) + Print Using "##.## ####.### ####.###"; h; hra; hla +Next + +' empty keyboard buffer +While InKey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Horizontal-sundial-calculations/Julia/horizontal-sundial-calculations.julia b/Task/Horizontal-sundial-calculations/Julia/horizontal-sundial-calculations.julia new file mode 100644 index 0000000000..c145a36886 --- /dev/null +++ b/Task/Horizontal-sundial-calculations/Julia/horizontal-sundial-calculations.julia @@ -0,0 +1,20 @@ +print("Enter latitude => ") +lat = parse(Float64, readline(STDIN)) +print("Enter longitude => ") +lng = parse(Float64, readline(STDIN)) +print("Enter legal meridian => ") +ref = parse(Float64, readline(STDIN)) +println() + +slat = sin(deg2rad(lat)) +@printf " sine of latitude: %.3f\n" slat +@printf " diff longitude: %.3f\n" (lng - ref) + +println("\nHour, sun hour angle, dial hour line angle from 6am to 6pm\n") + +for h in -6:6 + hra = 15 * h + hra -= lng - ref + hla = rad2deg(atan(slat * tan(deg2rad(hra)))) + @printf "HR = %3d; HRA = %7.3f; HLA = %7.3f\n" h hra hla +end diff --git a/Task/Horizontal-sundial-calculations/Kotlin/horizontal-sundial-calculations.kotlin b/Task/Horizontal-sundial-calculations/Kotlin/horizontal-sundial-calculations.kotlin new file mode 100644 index 0000000000..08e2d114d7 --- /dev/null +++ b/Task/Horizontal-sundial-calculations/Kotlin/horizontal-sundial-calculations.kotlin @@ -0,0 +1,33 @@ +import java.lang.Math.atan2 +import java.lang.Math.cos +import java.lang.Math.sin +import java.lang.Math.toDegrees +import java.lang.Math.toRadians + +// version 1.1.4 + +fun main(args: Array) { + println("Please enter the following in degrees:") + print(" Latitude : ") + val lat = readLine()!!.toDouble() + print(" Longitude : ") + val lng = readLine()!!.toDouble() + print(" Legal Meridian : ") + val mer = readLine()!!.toDouble() + + val slat = sin(toRadians(lat)) + val diff = lng - mer + println("\nSine of latitude = ${"%.6f".format(slat)}") + println("Longitude - Meridian = ${"%.3f".format(diff)}\n") + println("Hour Sun Hour Angle Dial Hour Line Angle") + println("----- -------------- --------------------") + println(" ° °") + for (h in -6..6) { + var hr = h + 12 + val am = if (hr < 12) "AM" else "PM" + if (hr > 12) hr -= 12 + val sha = 15.0 * h - diff + val dhla = toDegrees(atan2(slat * sin(toRadians(sha)), cos(toRadians(sha)))) + println("%2d %s %+7.3f %+7.3f".format(hr, am, sha, dhla)) + } +} diff --git a/Task/Horizontal-sundial-calculations/REXX/horizontal-sundial-calculations.rexx b/Task/Horizontal-sundial-calculations/REXX/horizontal-sundial-calculations.rexx index c7d03107f7..87580aa0a7 100644 --- a/Task/Horizontal-sundial-calculations/REXX/horizontal-sundial-calculations.rexx +++ b/Task/Horizontal-sundial-calculations/REXX/horizontal-sundial-calculations.rexx @@ -1,82 +1,68 @@ -/*REXX pgm shows: hour, sun hour angle, dial hour line angle, 6am ───► 6pm*/ -numeric digits 60 /*better overkill then underkill for dig*/ - -parse arg lat lng mer . /*get the optional arguments from the CL*/ - /*None specified? Then use the default of Jules */ - /*Verne's Lincoln Island, aka Ernest Legouve Reef.*/ - -if lat=='' | lat==',' then lat=-4.95 /*Not specified? Then use the default.*/ -if lng=='' | lng==',' then lng=-150.5 /* " " " " " " */ -if mer=='' | mer==',' then mer=-150 /* " " " " " " */ -L=max(length(lat), length(lng), length(mer)) - say ' latitude:' right(lat,L) - say ' longitude:' right(lng,L) - say ' legal meridian:' right(mer,L) -sineLat=sin(d2r(lat)) -w1=max(length('hour') ,length('midnight'))+2 -w2=max(length('sun hour') ,length('angle'))+2 -w3=max(length('dial hour'),length('line angle'))+2 -indent=left('',30) /*make the presentation prettier. */ -say indent center(' ',w1) center('sun hour',w2) center('dial hour' ,w3) -say indent center('hour',w1) center('angle' ,w2) center('line angle',w3) -call sep /*add a separator line for the eyeballs*/ - - do h=-6 to 6 /*Okey dokey then, let's get busy. */ - select - when abs(h)==12 then hc='midnight' /*above the arctic circle? */ - when h<0 then hc=-h 'am' /*convert the hour for human beans. */ - when h==0 then hc='noon' /* ... easier to understand now. */ - when h>0 then hc=h 'pm' /* ... even more meaningful. */ - end /*select*/ - hra=15*h-lng+mer - hla=r2d(Atan(sineLat*tan(d2r(hra)))) - say indent center(hc,w1) right(format(hra,,1),w2) right(format(hla,,1),w3) - end /*h*/ - -call sep -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────subroutines───────────────────────────────*/ -sep: say indent copies('═',w1) copies('═',w2) copies('═',w3); return -d2d: return arg(1) // 360 /*normalize degrees ──► a unit circle. */ -d2r: return r2r(arg(1)*pi() / 180) /*convert degrees ──► radians. */ -r2d: return d2d((arg(1)*180 / pi())) /*convert radians ──► degrees. */ -r2r: return arg(1) //(pi()*2) /*normalize radians ──► a unit circle. */ -tan: procedure; parse arg x; _=cos(x); if _=0 then call tanErr; return sin(x)/_ -tanErr: call tellErr 'tan(' || x") causes division by zero, X=" || x -tellErr: say; say '*** error! ***'; say; say arg(1); say; exit 13 -AsinErr: call tellErr 'Asin(x), X must be in the range of -1 ──► +1, X=' ||x -sqrtErr: call tellErr "sqrt(x), X can't be negative, X=" || x -AcosErr: call tellErr 'Acos(x), X must be in the range of -1 ──► +1, X=' ||x -Acos: procedure; arg x; if x<-1|x>1 then call AcosErr; return .5*pi()-Asin(x) - -Atan: procedure; arg x; if abs(x)=1 then return pi()/4*sign(x) - return Asin(x/sqrt(1+x**2)) - -sin: procedure; arg x; x=r2r(x); numeric fuzz min(5,digits()-3) - if abs(x)=pi() then return 0; return .sinCos(x,x,1) - -cos: procedure; parse arg x; x=r2r(x); a=abs(x); hpi=pi*.5 - numeric fuzz min(6,digits()-3); if a=pi() then return -1 - if a=hpi | a=hpi*3 then return 0; if a=pi()/3 then return .5 - if a=pi()*2/3 then return -.5; return .sinCos(1,1,-1) - -.sinCos: parse arg z,_,i; x=x*x; p=z - do k=2 by 2; _=-_*x/(k*(k+i));z=z+_; if z=p then leave; p=z; end; return z - -Asin: procedure; parse arg x; if x<-1 | x>1 then call AsinErr; s=x*x - if abs(x)>=.7 then return sign(x)*Acos(sqrt(1-s)); z=x; o=x; p=z - do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end - return z - -pi: pi=, /*a bit of an overkill, but hey !! */ - 3.1415926535897932384626433832795028841971693993751058209749445923078164062862 - return pi /*Note: the real PI subroutine returns PI's accuracy that */ - /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ - /*John Machin's formula is used for calculating more digits. */ - -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 - numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ - numeric digits d; return (g/1)i /*make complex if X < 0.*/ +/*REXX program displays: hour, sun hour angle, dial hour line angle, 6am ───► 6pm. */ +numeric digits 60 /*in case sundial is in polar regions. */ +parse arg lat lng . /*obtain optional arguments from the CL*/ + /* ┌───────────◄ None specified? Then use the default*/ + /* │ of Jules Verne's Lincoln Island, */ + /* ↓ aka Ernest Legouve Reed. */ +if lat=='' | lat=="," then lat= -4.95 /*Not specified? Then use the default.*/ +if lng=='' | lng=="," then lng= -150.5 /* " " " " " " */ +mer=format(lng/15, , 0) * 15 /*calculate legal meridian longitude. */ +sineLat=sin( d2r(lat) ) /*calculate sine of (radian) latitude. */ +w1=max( length('hour' ), length("midnight" )) + 2 /*compute the max hour width.*/ +w2=max( length('sun hour' ), length("angle" )) + 2 /* " " " angle " */ +w3=max( length('dial hour'), length("line angle")) + 2 /* " " " lineº " */ +L=max(length(lat), length(lng), length(mer) ) /*find maximum length of three numbers.*/ + say ' latitude:' right(lat, L) /*display the latitude to the terminal*/ + say ' longitude:' right(lng, L) /* " " longitude " " " */ + say ' legal meridian:' right(mer, L) /* " legal meridian " " " */ + indent=left('', 30) /*make prettier: indented presentation.*/ + say indent center(' ', w1) center("sun hour", w2) center('dial hour' , w3) + say indent center('hour', w1) center("angle" , w2) center('line angle', w3) +call sep /*to help a one-eyed pirate's eyeball. */ + do h=-6 to 6 /*Okey dokey then, now let's show stuff*/ + select + when abs(h)==12 then hc='midnight' /*Holy smokes! Above the arctic circle.*/ + when h <0 then hc= -h 'am' /*convert da hour for human beans (sic)*/ + when h==0 then hc='noon' /* ··· easier to understand now. */ + when h >0 then hc= h 'pm' /* ··· even more meaningful. */ + end /*select*/ + hra=15 * h - lng + mer /*calculate sun hour angle (in degrees)*/ + hla=r2d( Atan(sineLat * tan( d2r(hra)))) /*this is the heavy lifting calculation*/ + say indent center(hc, w1) right(format(hra, ,1), w2) right(format(hla, ,1), w3) + end /*h*/ +call sep /*to help a one-eyed pirate's eyeball. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +pi: pi= 3.1415926535897932384626433832795028841971693993751058209749445923078; return pi +d2d: return arg(1) // 360 /*normalize degrees ──► a unit circle. */ +d2r: return r2r( arg(1) * pi() / 180) /*convert degrees ──► radians. */ +r2d: return d2d( (arg(1) * 180 / pi() ) ) /*convert radians ──► degrees. */ +r2r: return arg(1) //(pi() * 2) /*normalize radians ──► a unit circle. */ +sep: say indent copies('═', w1) copies("═", w2) copies('═', w3); return +tan: procedure; parse arg x; _=cos(x); if _=0 then call tanErr; return sin(x)/_ +tellErr: say; say '*** error ***'; say; say arg(1); say; exit 13 +AsinErr: call tellErr 'Asin(x), X must be in the range of -1 ──► +1, X=' x +AcosErr: call tellErr 'Acos(x), X must be in the range of -1 ──► +1, X=' x +tanErr: call tellErr 'tan(' || x") causes division by zero, X=" x +Acos: procedure; arg x; if x<-1 | x>1 then call AcosErr; return .5 * pi() - Asin(x) +Atan: procedure; parse arg x; if abs(x)=1 then return pi()/4*x; return Asin(x/sqrt(1+x*x)) +/*──────────────────────────────────────────────────────────────────────────────────────*/ +Asin: procedure; parse arg x; if x<-1 | x>1 then call AsinErr; s=x*x + if abs(x)>=sqrt(2)*.4 then return sign(x) * Acos(sqrt(1-s)); z=x; o=x; p=z + do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end; return z +/*──────────────────────────────────────────────────────────────────────────────────────*/ +sin: procedure; parse arg x; x=r2r(x); numeric fuzz min(5, digits() - 3) + if abs(x)=pi() then return ; return .sinCos(x,x,1) +/*──────────────────────────────────────────────────────────────────────────────────────*/ +cos: procedure; parse arg x; x=r2r(x); a=abs(x); hpi=pi*.5 + numeric fuzz min(6, digits() - 3); if a=pi() then return -1 + if a=hpi | a=hpi*3 then return 0; if a=pi()/3 then return .5 + if a=pi() * 2 / 3 then return -.5; return .sinCos(1,1,-1) +/*──────────────────────────────────────────────────────────────────────────────────────*/ +.sinCos: parse arg z,_,i; x=x*x; p=z + do k=2 by 2; _= -_*x/(k*(k+i)); z=z+_; if z=p then leave; p=z; end; return z +/*──────────────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h=d+6 + m.=9; numeric form; 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 diff --git a/Task/Horizontal-sundial-calculations/Sidef/horizontal-sundial-calculations.sidef b/Task/Horizontal-sundial-calculations/Sidef/horizontal-sundial-calculations.sidef index 38d6e23b84..eed49144a8 100644 --- a/Task/Horizontal-sundial-calculations/Sidef/horizontal-sundial-calculations.sidef +++ b/Task/Horizontal-sundial-calculations/Sidef/horizontal-sundial-calculations.sidef @@ -1,23 +1,23 @@ -var latitude = read('Enter latitude => ', Number); -var longitude = read('Enter longitude => ', Number); -var meridian = read('Enter legal meridian => ', Number); - -var lat_sin = Math.sin(Math.deg2rad(latitude)); -var offset = (meridian - longitude); - -say('Sine of latitude: ', "%.4f" % lat_sin); -say('Longitude offset: ', offset); -say('=' * 48); -say(' Hour : Sun hour angle° : Dial hour line angle°'); - -for hour in range(-6, 6) { - var sun_deg = (15*hour + offset); - var line_deg = Math.rad2deg( - Math.atan2( - Math.sin(Math.deg2rad(sun_deg)) * lat_sin, - Math.cos(Math.deg2rad(sun_deg)) +var latitude = read('Enter latitude => ', Number) +var longitude = read('Enter longitude => ', Number) +var meridian = read('Enter legal meridian => ', Number) +  +var lat_sin = latitude.deg2rad.sin +var offset = (meridian - longitude) +  +say('Sine of latitude: ', "%.4f" % lat_sin) +say('Longitude offset: ', offset) +say('=' * 48) +say(' Hour  : Sun hour angle° : Dial hour line angle°') +  +for hour (-6 .. 6) { + var sun_deg = (15*hour + offset) + var line_deg = rad2deg( + atan2( + sin(deg2rad(sun_deg)) * lat_sin, + cos(deg2rad(sun_deg)) ) ) - printf("%2d %s %7.3f %7.3f\n", - (hour + 12) % 12 || 12, (hour < 0 ? 'AM' : 'PM'), sun_deg, line_deg); + printf("%2d %s  %7.3f  %7.3f\n", + (hour + 12) % 12 || 12, (hour < 0 ? 'AM' : 'PM'), sun_deg, line_deg) } diff --git a/Task/Horizontal-sundial-calculations/X86-Assembly/horizontal-sundial-calculations.x86 b/Task/Horizontal-sundial-calculations/X86-Assembly/horizontal-sundial-calculations.x86 new file mode 100644 index 0000000000..9e17b667cc --- /dev/null +++ b/Task/Horizontal-sundial-calculations/X86-Assembly/horizontal-sundial-calculations.x86 @@ -0,0 +1,137 @@ + global main + extern printf, scanf + + section .text + +getvalue: + push edx + push eax + call printf + add esp, 4 + push in_ft + call scanf + add esp, 8 + ret + +st0dr: + fld qword [drfact] + fmul + ret + + +main: + lea eax, [lat_t] + lea edx, [lat] + call getvalue + lea eax, [lng_t] + lea edx, [lng] + call getvalue + lea eax, [ref_t] + lea edx, [ref] + call getvalue + + push newline + call printf + add esp, 4 + + fld qword [lat] + call st0dr + fsin + fst qword [slat] + + sub esp, 8 + fstp qword [esp] + push sin_ft + call printf + add esp, 12 + + fld qword [lng] + fld qword [ref] + fsubr st0, st1 + sub esp, 8 + fstp qword [esp] + push diff_ft + call printf + add esp, 12 + + push tab_t + call printf + add esp, 4 + + mov ecx, -6 +.loop: + cmp ecx, 6 + jg .endloop + + push ecx + fild dword [esp] + fld qword [xv] + fmulp + fld qword [lng] + fsubp + fld qword [ref] + faddp + pop ecx + + sub esp, 20 + mov dword [esp], ecx + fst qword [esp+4] + + call st0dr + + fptan + fxch + fld qword [slat] + fmulp + fxch + fpatan + + fld qword [rdinv] + fmul + + fstp qword [esp+12] + + push o_ft + call printf + mov ecx, [esp+4] + add esp, 24 + + inc ecx + jmp .loop +.endloop: + + xor eax, eax + ret + + + section .data + +lat: dq 0.0 +lng: dq 0.0 +ref: dq 0.0 +xv: dq 15.0 +slat: dq 0.0 +drfact: dq 0.01745329251994329576 +rdinv: dq 57.29577951308232090712 + + + section .rodata + +lat_t: db "Enter latitude: ", 0 +lng_t: db "Enter longitude: ", 0 +ref_t: db "Enter legal meridian: ", 0 + +in_ft: db "%lf", 0 +newline: + db 10, 0 + +sin_ft: + db "sine of latitude: %.3f", 10, 0 +diff_ft: + db "diff longitude: %.3f", 10, 10, 0 + +tab_t: + db "Hour, sun hour angle, dial hour line angle from 6am to 6pm", 10, 0 + +o_ft: + db "HR= %3d; ",9," HRA=%7.3f; ",9," HLA= %7.3f", 10, 0 diff --git a/Task/Horizontal-sundial-calculations/Zkl/horizontal-sundial-calculations.zkl b/Task/Horizontal-sundial-calculations/Zkl/horizontal-sundial-calculations.zkl new file mode 100644 index 0000000000..9746e7e00c --- /dev/null +++ b/Task/Horizontal-sundial-calculations/Zkl/horizontal-sundial-calculations.zkl @@ -0,0 +1,23 @@ +//(degree measure)*Degrees => Radian measure +//(radian measure)/Degrees => Degree measure +const pi=(0.0).pi, toDeg=(0.0).pi/180; + +latitude :=ask(0,"Enter latitude: ").toFloat(); +longitude:=ask(1,"Enter longitude: ").toFloat(); +meridian :=ask(2,"Enter legal meridian: ").toFloat(); + +sineLatitude:=(latitude * toDeg).sin(); +Console.writeln(); +Console.writeln("Sine of latitude: ",sineLatitude); +Console.writeln("Difference of Longitudes (given longitude - meridian): ",longitude-meridian); +Console.writeln(); + +println("Numbers from 6 AM to 6 PM: "); +println("Hour\t\tSun hour angle\t Dial hour line angle"); + +foreach hour in ([-6..6]){ + clockHour:=( if(hour < 0) "%sAM".fmt(hour.abs()) else "%sPM".fmt(hour) ); + shr :=15.0*hour - (longitude - meridian); + dhla :=(sineLatitude*(shr*toDeg).tan()).atan()/toDeg; + Console.writeln("%s\t\t%5.1f\t\t%+7.3f".fmt(clockHour,shr,dhla)); +} diff --git a/Task/Horners-rule-for-polynomial-evaluation/Batch-File/horners-rule-for-polynomial-evaluation.bat b/Task/Horners-rule-for-polynomial-evaluation/Batch-File/horners-rule-for-polynomial-evaluation.bat new file mode 100644 index 0000000000..c299e0a948 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Batch-File/horners-rule-for-polynomial-evaluation.bat @@ -0,0 +1,23 @@ +@echo off + +call:horners a:-19 b:7 c:-4 d:6 x:3 +call:horners x:3 a:-19 c:-4 d:6 b:7 +pause>nul +exit /b + +:horners +setlocal enabledelayedexpansion +set a=0 +set b=0 +set c=0 +set d=0 +set x=0 + +for %%i in (%*) do ( + for /f "tokens=1,2 delims=:" %%j in ("%%i") do ( + set %%j=%%k + ) +) +set /a return=((((0)*%x%+%d%)*%x%+(%c%))*%x%+%b%)*%x%+(%a%) +echo %return% +exit /b diff --git a/Task/Horners-rule-for-polynomial-evaluation/Kotlin/horners-rule-for-polynomial-evaluation.kotlin b/Task/Horners-rule-for-polynomial-evaluation/Kotlin/horners-rule-for-polynomial-evaluation.kotlin new file mode 100644 index 0000000000..79ed118a7f --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Kotlin/horners-rule-for-polynomial-evaluation.kotlin @@ -0,0 +1,12 @@ +// version 1.1.2 + +fun horner(coeffs: DoubleArray, x: Double): Double { + var sum = 0.0 + for (i in coeffs.size - 1 downTo 0) sum = sum * x + coeffs[i] + return sum +} + +fun main(args: Array) { + val coeffs = doubleArrayOf(-19.0, 7.0, -4.0, 6.0) + println(horner(coeffs, 3.0)) +} diff --git a/Task/Horners-rule-for-polynomial-evaluation/OoRexx/horners-rule-for-polynomial-evaluation.rexx b/Task/Horners-rule-for-polynomial-evaluation/OoRexx/horners-rule-for-polynomial-evaluation.rexx new file mode 100644 index 0000000000..26f9ebfb89 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/OoRexx/horners-rule-for-polynomial-evaluation.rexx @@ -0,0 +1,12 @@ +/* Rexx --------------------------------------------------------------- +* 04.03.2014 Walter Pachl +*--------------------------------------------------------------------*/ +c = .array~of(-19,7,-4,6) -- coefficients of all x^0..x^n in order +n=3 +x=3 +r=0 +loop i=n+1 to 1 by -1 + r=r*x+c[i] + End +Say r +Say 6*x**3-4*x**2+7*x-19 diff --git a/Task/Horners-rule-for-polynomial-evaluation/Phix/horners-rule-for-polynomial-evaluation.phix b/Task/Horners-rule-for-polynomial-evaluation/Phix/horners-rule-for-polynomial-evaluation.phix new file mode 100644 index 0000000000..2e0a5cd2a3 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Phix/horners-rule-for-polynomial-evaluation.phix @@ -0,0 +1,9 @@ +function horner(atom x, sequence coeff) +atom res = 0 + for i=length(coeff) to 1 by -1 do + res = res*x + coeff[i] + end for + return res +end function + +?horner(3,{-19, 7, -4, 6}) diff --git a/Task/Horners-rule-for-polynomial-evaluation/Prolog/horners-rule-for-polynomial-evaluation-4.pro b/Task/Horners-rule-for-polynomial-evaluation/Prolog/horners-rule-for-polynomial-evaluation-4.pro new file mode 100644 index 0000000000..3d2e689964 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Prolog/horners-rule-for-polynomial-evaluation-4.pro @@ -0,0 +1,3 @@ +:- module(_, [horner/3], [fsyntax, hiord]). +:- use_module(library(hiordlib)). +horner(L, X) := ~foldr((''(H,V0,V) :- V is V0*X + H), L, 0). diff --git a/Task/Horners-rule-for-polynomial-evaluation/Zkl/horners-rule-for-polynomial-evaluation.zkl b/Task/Horners-rule-for-polynomial-evaluation/Zkl/horners-rule-for-polynomial-evaluation.zkl new file mode 100644 index 0000000000..a4e891478c --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Zkl/horners-rule-for-polynomial-evaluation.zkl @@ -0,0 +1,2 @@ +fcn horner(coeffs,x) + { coeffs.reverse().reduce('wrap(a,coeff){ a*x + coeff },0.0) } diff --git a/Task/Host-introspection/Kotlin/host-introspection.kotlin b/Task/Host-introspection/Kotlin/host-introspection.kotlin new file mode 100644 index 0000000000..386b2f4a58 --- /dev/null +++ b/Task/Host-introspection/Kotlin/host-introspection.kotlin @@ -0,0 +1,6 @@ +// version 1.0.6 + +fun main(args: Array) { + println("Word size : ${System.getProperty("sun.arch.data.model")} bits") + println("Endianness: ${System.getProperty("sun.cpu.endian")}-endian") +} diff --git a/Task/Host-introspection/Phix/host-introspection.phix b/Task/Host-introspection/Phix/host-introspection.phix new file mode 100644 index 0000000000..0d213a6644 --- /dev/null +++ b/Task/Host-introspection/Phix/host-introspection.phix @@ -0,0 +1,16 @@ +function endianness() +atom m4 = allocate(4) + poke4(m4,#01020304) + integer b1 = peek1s(m4) + free(m4) + if b1=#01 then + return "big-endian" + elsif b1=#04 then + return "little-endian" + else + return "???" + end if +end function + +printf(1,"Endianness: %s\n",{endianness()}) +printf(1,"Word size: %d bytes/%d bits\n",{machine_word(),machine_bits()}) diff --git a/Task/Host-introspection/R/host-introspection-1.r b/Task/Host-introspection/R/host-introspection-1.r deleted file mode 100644 index e9493a3428..0000000000 --- a/Task/Host-introspection/R/host-introspection-1.r +++ /dev/null @@ -1,3 +0,0 @@ -8 * .Machine$sizeof.long # e.g. 32 -# or -object.size(0L) # e.g. 32 bytes diff --git a/Task/Host-introspection/R/host-introspection-2.r b/Task/Host-introspection/R/host-introspection-2.r deleted file mode 100644 index 1847947008..0000000000 --- a/Task/Host-introspection/R/host-introspection-2.r +++ /dev/null @@ -1 +0,0 @@ -.Platform$endian # e.g. "little" diff --git a/Task/Hostname/BaCon/hostname.bacon b/Task/Hostname/BaCon/hostname.bacon new file mode 100644 index 0000000000..d5fbc32808 --- /dev/null +++ b/Task/Hostname/BaCon/hostname.bacon @@ -0,0 +1 @@ +PRINT "Hostname: ", HOSTNAME$ diff --git a/Task/Hostname/COBOL/hostname.cobol b/Task/Hostname/COBOL/hostname.cobol new file mode 100644 index 0000000000..96ce63bb49 --- /dev/null +++ b/Task/Hostname/COBOL/hostname.cobol @@ -0,0 +1,15 @@ + identification division. + program-id. hostname. + + data division. + working-storage section. + 01 hostname pic x(256). + 01 nullpos pic 999 value 1. + + procedure division. + call "gethostname" using hostname by value length of hostname + string hostname delimited by low-value into hostname + with pointer nullpos + display "Host: " hostname(1 : nullpos - 1) + goback. + end program hostname. diff --git a/Task/Hostname/Friendly-interactive-shell/hostname-1.fish b/Task/Hostname/Friendly-interactive-shell/hostname-1.fish new file mode 100644 index 0000000000..ecd88aee75 --- /dev/null +++ b/Task/Hostname/Friendly-interactive-shell/hostname-1.fish @@ -0,0 +1 @@ +hostname diff --git a/Task/Hostname/Friendly-interactive-shell/hostname-2.fish b/Task/Hostname/Friendly-interactive-shell/hostname-2.fish new file mode 100644 index 0000000000..c84daec6c5 --- /dev/null +++ b/Task/Hostname/Friendly-interactive-shell/hostname-2.fish @@ -0,0 +1 @@ +uname -n diff --git a/Task/Hostname/Gambas/hostname.gambas b/Task/Hostname/Gambas/hostname.gambas new file mode 100644 index 0000000000..9f9f08d36d --- /dev/null +++ b/Task/Hostname/Gambas/hostname.gambas @@ -0,0 +1,5 @@ +Public Sub Main() + +Print System.Host + +End diff --git a/Task/Hostname/Kotlin/hostname.kotlin b/Task/Hostname/Kotlin/hostname.kotlin new file mode 100644 index 0000000000..954300ac10 --- /dev/null +++ b/Task/Hostname/Kotlin/hostname.kotlin @@ -0,0 +1,7 @@ +// version 1.1.4 + +import java.net.InetAddress + +fun main(args: Array) { + println(InetAddress.getLocalHost().hostName) +} diff --git a/Task/Hostname/MIRC-Scripting-Language/hostname.mirc b/Task/Hostname/MIRC-Scripting-Language/hostname.mirc new file mode 100644 index 0000000000..5ba6811961 --- /dev/null +++ b/Task/Hostname/MIRC-Scripting-Language/hostname.mirc @@ -0,0 +1 @@ +echo -ag $host diff --git a/Task/Hostname/OoRexx/hostname-1.rexx b/Task/Hostname/OoRexx/hostname-1.rexx new file mode 100644 index 0000000000..765123be9c --- /dev/null +++ b/Task/Hostname/OoRexx/hostname-1.rexx @@ -0,0 +1 @@ +say .oleObject~new('WScript.Network')~computerName diff --git a/Task/Hostname/OoRexx/hostname-2.rexx b/Task/Hostname/OoRexx/hostname-2.rexx new file mode 100644 index 0000000000..00ad7c5059 --- /dev/null +++ b/Task/Hostname/OoRexx/hostname-2.rexx @@ -0,0 +1 @@ +say value('COMPUTERNAME',,'environment') diff --git a/Task/Hostname/OoRexx/hostname-3.rexx b/Task/Hostname/OoRexx/hostname-3.rexx new file mode 100644 index 0000000000..85cadd566c --- /dev/null +++ b/Task/Hostname/OoRexx/hostname-3.rexx @@ -0,0 +1 @@ +address command 'hostname -f' diff --git a/Task/Hostname/OoRexx/hostname-4.rexx b/Task/Hostname/OoRexx/hostname-4.rexx new file mode 100644 index 0000000000..620e12593c --- /dev/null +++ b/Task/Hostname/OoRexx/hostname-4.rexx @@ -0,0 +1 @@ +address command "echo $HOSTNAME" diff --git a/Task/Hostname/OoRexx/hostname-5.rexx b/Task/Hostname/OoRexx/hostname-5.rexx new file mode 100644 index 0000000000..b8b1ec1cc2 --- /dev/null +++ b/Task/Hostname/OoRexx/hostname-5.rexx @@ -0,0 +1,7 @@ +/* Rexx */ +address command "echo $HOSTNAME | rxqueue" +address command "hostname -f | rxqueue" +loop q_ = 1 while queued() > 0 + parse pull hn + say q_~right(2)':' hn + end q_ diff --git a/Task/Hostname/OoRexx/hostname-6.rexx b/Task/Hostname/OoRexx/hostname-6.rexx new file mode 100644 index 0000000000..58a32a9faa --- /dev/null +++ b/Task/Hostname/OoRexx/hostname-6.rexx @@ -0,0 +1,8 @@ +/* Rexx */ +qq = .rexxqueue~new() +address command "echo $HOSTNAME | rxqueue" +address command "hostname -f | rxqueue" +loop q_ = 1 while qq~queued() > 0 + hn = qq~pull() + say q_~right(2)':' hn + end q_ diff --git a/Task/Hostname/SQL/hostname.sql b/Task/Hostname/SQL/hostname.sql new file mode 100644 index 0000000000..73a5ef1d2b --- /dev/null +++ b/Task/Hostname/SQL/hostname.sql @@ -0,0 +1 @@ +select host_name from v$instance; diff --git a/Task/Hostname/Zkl/hostname-1.zkl b/Task/Hostname/Zkl/hostname-1.zkl new file mode 100644 index 0000000000..6e88df247e --- /dev/null +++ b/Task/Hostname/Zkl/hostname-1.zkl @@ -0,0 +1 @@ +System.hostname diff --git a/Task/Hostname/Zkl/hostname-2.zkl b/Task/Hostname/Zkl/hostname-2.zkl new file mode 100644 index 0000000000..b5739e8d44 --- /dev/null +++ b/Task/Hostname/Zkl/hostname-2.zkl @@ -0,0 +1 @@ +Network.TCPServerSocket.open(8080).hostname diff --git a/Task/Hough-transform/Haskell/hough-transform-1.hs b/Task/Hough-transform/Haskell/hough-transform-1.hs index 1bdb14621f..ebb73ca653 100644 --- a/Task/Hough-transform/Haskell/hough-transform-1.hs +++ b/Task/Hough-transform/Haskell/hough-transform-1.hs @@ -5,22 +5,30 @@ import qualified Data.Foldable as F (maximum) import System.Environment (getArgs, getProgName) -- Library JuicyPixels: -import Codec.Picture (DynamicImage(ImageRGB8, ImageRGBA8), Image, - PixelRGB8(PixelRGB8), PixelRGBA8(PixelRGBA8), - imageWidth, imageHeight, pixelAt, generateImage, - readImage, pixelMap, savePngImage) +import Codec.Picture + (DynamicImage(ImageRGB8, ImageRGBA8), Image, PixelRGB8(PixelRGB8), + PixelRGBA8(PixelRGBA8), imageWidth, imageHeight, pixelAt, + generateImage, readImage, pixelMap, savePngImage) import Codec.Picture.Types (extractLumaPlane, dropTransparency) -dot :: Num a => (a, a) -> (a, a) -> a +dot + :: Num a + => (a, a) -> (a, a) -> a dot (x1, y1) (x2, y2) = x1 * x2 + y1 * y2 -mag :: Floating a => (a, a) -> a +mag + :: Floating a + => (a, a) -> a mag a = sqrt $ dot a a -sub :: Num a => (a, a) -> (a, a) -> (a, a) +sub + :: Num a + => (a, a) -> (a, a) -> (a, a) sub (x1, y1) (x2, y2) = (x1 - x2, y1 - y2) -fromIntegralP :: (Integral a, Num b) => (a, a) -> (b, b) +fromIntegralP + :: (Integral a, Num b) + => (a, a) -> (b, b) fromIntegralP (x, y) = (fromIntegral x, fromIntegral y) {- @@ -39,63 +47,59 @@ hough image thetaSize distSize = hImage hMax = height - 1 xCenter = wMax `div` 2 yCenter = hMax `div` 2 - lumaMap = extractLumaPlane image - gradient x y = let orig = pixelAt lumaMap x y - x' = pixelAt lumaMap (min (x + 1) wMax) y - y' = pixelAt lumaMap x (min (y + 1) hMax) - in fromIntegralP (orig - x', orig - y') - - gradMap = [((x, y), gradient x y) | x <- [0..wMax], y <- [0..hMax]] - + x_ = pixelAt lumaMap (min (x + 1) wMax) y + y_ = pixelAt lumaMap x (min (y + 1) hMax) + in fromIntegralP (orig - x_, orig - y_) + gradMap = + [ ((x, y), gradient x y) + | x <- [0 .. wMax] + , y <- [0 .. hMax] ] -- The longest distance from the center, half the hypotenuse of the image. distMax :: Double distMax = (sqrt . fromIntegral $ height ^ 2 + width ^ 2) / 2 - {- The accumulation bins of the polar values. For each value in the gradient image, if the gradient length exceeds some threshold, consider it evidence of a line and plot all of the lines that go through that point in Hough space. -} - accBin = runSTArray $ do - arr <- newArray ((0, 0), (thetaSize, distSize)) 0 - forM_ gradMap $ \((x, y), grad) -> do - let (x', y') = fromIntegralP $ (xCenter, yCenter) `sub` (x, y) - - when (mag grad > 127) $ - forM_ [0..thetaSize] $ \theta -> do - let theta' = (fromIntegral theta) * 360 / (fromIntegral thetaSize) - / 180 * pi :: Double - dist = (cos theta' * x' + sin theta' * y') - dist' = truncate $ dist * (fromIntegral distSize) / distMax - idx = (theta, dist') - - when (dist' >= 0 && dist' < distSize) $ do - old <- readArray arr idx - writeArray arr idx $ old + 1 - - return arr - + accBin = + runSTArray $ + do arr <- newArray ((0, 0), (thetaSize, distSize)) 0 + forM_ gradMap $ + \((x, y), grad) -> do + let (x_, y_) = fromIntegralP $ (xCenter, yCenter) `sub` (x, y) + when (mag grad > 127) $ + forM_ [0 .. thetaSize] $ + \theta -> do + let theta_ = + fromIntegral theta * 360 / fromIntegral thetaSize / 180 * + pi :: Double + dist = cos theta_ * x_ + sin theta_ * y_ + dist_ = truncate $ dist * fromIntegral distSize / distMax + idx = (theta, dist_) + when (dist_ >= 0 && dist_ < distSize) $ + do old <- readArray arr idx + writeArray arr idx $ old + 1 + return arr maxAcc = F.maximum accBin - -- The image representation of the accumulation bins. hTransform x y = - let l = 255 - (truncate $ (accBin ! (x, y)) / maxAcc * 255) + let l = 255 - truncate ((accBin ! (x, y)) / maxAcc * 255) in PixelRGB8 l l l - hImage = generateImage hTransform thetaSize distSize houghIO :: FilePath -> FilePath -> Int -> Int -> IO () houghIO path outpath thetaSize distSize = do image <- readImage path case image of - Left err -> putStrLn err - Right (ImageRGB8 image') -> doImage image' - Right (ImageRGBA8 image') -> doImage $ pixelMap dropTransparency image' - _ -> putStrLn $ "Expecting RGB8 or RGBA8 image" + Left err -> putStrLn err + Right (ImageRGB8 image_) -> doImage image_ + Right (ImageRGBA8 image_) -> doImage $ pixelMap dropTransparency image_ + _ -> putStrLn "Expecting RGB8 or RGBA8 image" where doImage image = do let houghImage = hough image thetaSize distSize @@ -108,4 +112,6 @@ main = do case args of [path, outpath, thetaSize, distSize] -> houghIO path outpath (read thetaSize) (read distSize) - _ -> putStrLn $ "Usage: " ++ prog ++ " " + _ -> + putStrLn $ + "Usage: " ++ prog ++ " " diff --git a/Task/Hough-transform/J/hough-transform-2.j b/Task/Hough-transform/J/hough-transform-2.j index 34c9eb8c09..bed6703000 100644 --- a/Task/Hough-transform/J/hough-transform-2.j +++ b/Task/Hough-transform/J/hough-transform-2.j @@ -1,3 +1,4 @@ - require 'viewmat media/platimg' - Img=: readimg jpath '~temp/pentagon.png' + require 'viewmat' + require 'media/platimg' NB. addon required pre J8 + Img=: readimg_jqtide_ jpath '~temp/pentagon.png' viewmat 460 360 houghTransform _1 > Img diff --git a/Task/Hough-transform/Kotlin/hough-transform.kotlin b/Task/Hough-transform/Kotlin/hough-transform.kotlin index 118cad676f..94f8fa6896 100644 --- a/Task/Hough-transform/Kotlin/hough-transform.kotlin +++ b/Task/Hough-transform/Kotlin/hough-transform.kotlin @@ -1,11 +1,10 @@ -import java.awt.image.* +import java.awt.image.BufferedImage import java.io.File -import javax.imageio.* +import javax.imageio.ImageIO internal class ArrayData(val dataArray: IntArray, val width: Int, val height: Int) { - constructor(width: Int, height: Int) : this(IntArray(width * height), width, height) { - } + constructor(width: Int, height: Int) : this(IntArray(width * height), width, height) operator fun get(x: Int, y: Int) = dataArray[y * width + x] diff --git a/Task/Hough-transform/Zkl/hough-transform-1.zkl b/Task/Hough-transform/Zkl/hough-transform-1.zkl new file mode 100644 index 0000000000..a98c8f39da --- /dev/null +++ b/Task/Hough-transform/Zkl/hough-transform-1.zkl @@ -0,0 +1,17 @@ +const WHITE=0xffFFff, X=0x010101; +fcn houghTransform(image,hx=460,hy=360){ + if(hy.isOdd) hy-=1; // hy argument must be even + out:=PPM(hx,hy,WHITE); + rMax:=image.w.toFloat().hypot(image.h); + dr,dTh:=rMax/(hy/2), (0.0).pi/hx; + + foreach y,x in (image.h,image.w){ + if(image[x,y]==WHITE) continue; + foreach iTh in (hx){ + th,r:=dTh*iTh, th.cos()*x + th.sin()*y; + iry:=hy/2 + (r/dr + 0.5).floor(); // y==0 is top + if(out[iTh,iry]>0) out[iTh,iry]=out[iTh,iry] - X; + } + } + out +} diff --git a/Task/Hough-transform/Zkl/hough-transform-2.zkl b/Task/Hough-transform/Zkl/hough-transform-2.zkl new file mode 100644 index 0000000000..687ba13573 --- /dev/null +++ b/Task/Hough-transform/Zkl/hough-transform-2.zkl @@ -0,0 +1,8 @@ +fcn readPNG2PPM(fileName){ + p:=System.popen("convert \"%s\" ppm:-".fmt(fileName),"r"); + img:=PPM.readPPM(p); + p.close(); + img +} +houghTransform(readPNG2PPM("pentagon.png")) +.write(File("pentagon_hough.ppm","wb")); diff --git a/Task/Huffman-coding/C/huffman-coding-3.c b/Task/Huffman-coding/C/huffman-coding-3.c deleted file mode 100644 index 1e18cd3110..0000000000 --- a/Task/Huffman-coding/C/huffman-coding-3.c +++ /dev/null @@ -1,21 +0,0 @@ -' ': 000 -'a': 1000 -'c': 01101 -'d': 01100 -'e': 0101 -'f': 0010 -'g': 010000 -'h': 1101 -'i': 0011 -'l': 010001 -'m': 1111 -'n': 101 -'o': 1110 -'p': 10011 -'r': 10010 -'s': 1100 -'t': 01111 -'u': 01110 -'x': 01001 -encoded: 0111111010011110000000111100000100010100001010100110001111100110100010101000001011101001000011010111000100010111110001010000101101011011110011000011101010000 -decoded: this is an example for huffman encoding diff --git a/Task/Huffman-coding/CoffeeScript/huffman-coding-1.coffee b/Task/Huffman-coding/CoffeeScript/huffman-coding-1.coffee deleted file mode 100644 index d8ebaa3963..0000000000 --- a/Task/Huffman-coding/CoffeeScript/huffman-coding-1.coffee +++ /dev/null @@ -1,85 +0,0 @@ -huffman_encoding_table = (counts) -> - # counts is a hash where keys are characters and - # values are frequencies; - # return a hash where keys are codes and values - # are characters - - build_huffman_tree = -> - # returns a Huffman tree. Each node has - # cnt: total frequency of all chars in subtree - # c: character to be encoded (leafs only) - # children: children nodes (branches only) - q = min_queue() - for c, cnt of counts - q.enqueue cnt, - cnt: cnt - c: c - while q.size() >= 2 - a = q.dequeue() - b = q.dequeue() - cnt = a.cnt + b.cnt - node = - cnt: cnt - children: [a, b] - q.enqueue cnt, node - root = q.dequeue() - - root = build_huffman_tree() - - codes = {} - encode = (node, code) -> - if node.c? - codes[code] = node.c - else - encode node.children[0], code + "0" - encode node.children[1], code + "1" - - encode(root, "") - codes - -min_queue = -> - # This is very non-optimized; you could use a binary heap for better - # performance. Items with smaller priority get dequeued first. - arr = [] - enqueue: (priority, data) -> - i = 0 - while i < arr.length - if priority < arr[i].priority - break - i += 1 - arr.splice i, 0, - priority: priority - data: data - dequeue: -> - arr.shift().data - size: -> arr.length - _internal: -> - arr - -freq_count = (s) -> - cnts = {} - for c in s - cnts[c] ?= 0 - cnts[c] += 1 - cnts - -rpad = (s, n) -> - while s.length < n - s += ' ' - s - -examples = [ - "this is an example for huffman encoding" - "abcd" - "abbccccddddddddeeeeeeeee" -] - -for s in examples - console.log "---- #{s}" - counts = freq_count(s) - huffman_table = huffman_encoding_table(counts) - codes = (code for code of huffman_table).sort() - for code in codes - c = huffman_table[code] - console.log "#{rpad(code, 5)}: #{c} (#{counts[c]})" - console.log() diff --git a/Task/Huffman-coding/CoffeeScript/huffman-coding-2.coffee b/Task/Huffman-coding/CoffeeScript/huffman-coding-2.coffee deleted file mode 100644 index ba94c69a9e..0000000000 --- a/Task/Huffman-coding/CoffeeScript/huffman-coding-2.coffee +++ /dev/null @@ -1,34 +0,0 @@ -> coffee huffman.coffee ----- this is an example for huffman encoding -000 : n (4) -0010 : s (2) -0011 : m (2) -0100 : o (2) -01010: t (1) -01011: x (1) -01100: p (1) -01101: l (1) -01110: r (1) -01111: u (1) -10000: c (1) -10001: d (1) -1001 : i (3) -101 : (6) -1100 : a (3) -1101 : e (3) -1110 : f (3) -11110: g (1) -11111: h (2) - ----- abcd -00 : a (1) -01 : b (1) -10 : c (1) -11 : d (1) - ----- abbccccddddddddeeeeeeeee -0 : e (9) -1000 : a (1) -1001 : b (2) -101 : c (4) -11 : d (8) diff --git a/Task/Huffman-coding/Haskell/huffman-coding-1.hs b/Task/Huffman-coding/Haskell/huffman-coding-1.hs index 95cedb08dd..8cdaf89f1e 100644 --- a/Task/Huffman-coding/Haskell/huffman-coding-1.hs +++ b/Task/Huffman-coding/Haskell/huffman-coding-1.hs @@ -2,23 +2,36 @@ import Data.List import Control.Arrow import Data.Ord -data HTree a = Leaf a | Branch (HTree a) (HTree a) - deriving (Show, Eq, Ord) +data HTree a + = Leaf a + | Branch (HTree a) + (HTree a) + deriving (Show, Eq, Ord) test :: String -> IO () -test s = mapM_ (\(a,b)-> putStrLn ('\'' : a : "\' : " ++ b)) - . serialize . huffmanTree . freq $ s +test = + mapM_ (\(a, b) -> putStrLn ('\'' : a : "\' : " ++ b)) . + serialize . huffmanTree . freq serialize :: HTree a -> [(a, String)] -serialize (Branch l r) = map (second('0':)) (serialize l) ++ map (second('1':)) (serialize r) -serialize (Leaf x) = [(x, "")] +serialize (Branch l r) = + (second ('0' :) <$> serialize l) ++ (second ('1' :) <$> serialize r) +serialize (Leaf x) = [(x, "")] -huffmanTree :: (Ord w, Num w) => [(w, a)] -> HTree a -huffmanTree = snd . head . until (null.tail) hstep - . sortBy (comparing fst) . map (second Leaf) +huffmanTree + :: (Ord w, Num w) + => [(w, a)] -> HTree a +huffmanTree = + snd . + head . until (null . tail) hstep . sortBy (comparing fst) . (second Leaf <$>) -hstep :: (Ord a, Num a) => [(a, HTree b)] -> [(a, HTree b)] -hstep ((w1,t1):(w2,t2):wts) = insertBy (comparing fst) (w1 + w2, Branch t1 t2) wts +hstep + :: (Ord a, Num a) + => [(a, HTree b)] -> [(a, HTree b)] +hstep ((w1, t1):(w2, t2):wts) = + insertBy (comparing fst) (w1 + w2, Branch t1 t2) wts -freq :: Ord a => [a] -> [(Int, a)] -freq = map (length &&& head) . group . sort +freq + :: Ord a + => [a] -> [(Int, a)] +freq = ((length &&& head) <$>) . group . sort diff --git a/Task/Huffman-coding/Kotlin/huffman-coding.kotlin b/Task/Huffman-coding/Kotlin/huffman-coding.kotlin index a486d5f948..4dc0f3c6c4 100644 --- a/Task/Huffman-coding/Kotlin/huffman-coding.kotlin +++ b/Task/Huffman-coding/Kotlin/huffman-coding.kotlin @@ -1,3 +1,5 @@ +import java.util.* + abstract class HuffmanTree(var freq: Int) : Comparable { override fun compareTo(other: HuffmanTree) = freq - other.freq } diff --git a/Task/Huffman-coding/Perl/huffman-coding-1.pl b/Task/Huffman-coding/Perl/huffman-coding-1.pl deleted file mode 100644 index e842c7adf0..0000000000 --- a/Task/Huffman-coding/Perl/huffman-coding-1.pl +++ /dev/null @@ -1,52 +0,0 @@ -sub make_tree { - my %letters; - $letters{$_}++ for (split "", shift); - my (@nodes, $n) = map({ a=>$_, freq=>$letters{$_} }, keys %letters); - while ((@nodes = sort { $a->{freq} <=> $b->{freq} - or $a->{a} cmp $b->{a} } @nodes) > 1) - { - $n = { "0"=>shift(@nodes), "1"=>shift(@nodes) }; - $n->{freq} = $n->{0}{freq} + $n->{1}{freq}; - push @nodes, $n; - } - - walk($n, "", $n->{tree} = {}); - $n; -} - -sub walk { - my ($n, $s, $h) = @_; - exists $n->{a} and do { - print "'$n->{a}': $s\n"; - $h->{$n->{a}} = $s if $h; - return; - }; - walk($n->{0}, $s.0, $h); - walk($n->{1}, $s.1, $h); -} - -sub encode { - my ($s, $t) = @_; - $t = $t->{tree}; - join("", map($t->{$_}, split("", $s))); -} - -sub decode { - my @b = split("", shift); - my ($n, $out) = $_[0]; - - while (@b) { - $n = $n->{shift @b}; - if ($n->{a}) { - $out .= $n->{a}; - $n = $_[0]; - } - } - $out; -} - -my $text = "this is an example for huffman encoding"; -my $tree = make_tree($text); -my $e = encode($text, $tree); -print "$e\n"; -print decode($e, $tree), "\n"; diff --git a/Task/Huffman-coding/Perl/huffman-coding-2.pl b/Task/Huffman-coding/Perl/huffman-coding-2.pl deleted file mode 100644 index fb8f765ad2..0000000000 --- a/Task/Huffman-coding/Perl/huffman-coding-2.pl +++ /dev/null @@ -1,21 +0,0 @@ -'g': 00000 -'l': 00001 -'p': 00010 -'r': 00011 -'t': 00100 -'u': 00101 -'h': 0011 -'m': 0100 -'o': 0101 -'n': 011 -'s': 1000 -'x': 10010 -'c': 100110 -'d': 100111 -'a': 1010 -'e': 1011 -'f': 1100 -'i': 1101 -' ': 111 -0010000111101100011111...111110101100000 -this is an example for huffman encoding diff --git a/Task/Huffman-coding/Rust/huffman-coding.rust b/Task/Huffman-coding/Rust/huffman-coding.rust new file mode 100644 index 0000000000..febc8c56be --- /dev/null +++ b/Task/Huffman-coding/Rust/huffman-coding.rust @@ -0,0 +1,86 @@ +use std::collections::BTreeMap; +use std::collections::binary_heap::BinaryHeap; + +#[derive(Debug, Eq, PartialEq)] +enum NodeKind { + Internal(Box, Box), + Leaf(char), +} + +#[derive(Debug, Eq, PartialEq)] +struct Node { + frequency: usize, + kind: NodeKind, +} + +impl Ord for Node { + fn cmp(&self, rhs: &Self) -> std::cmp::Ordering { + rhs.frequency.cmp(&self.frequency) + } +} + +impl PartialOrd for Node { + fn partial_cmp(&self, rhs: &Self) -> Option { + Some(self.cmp(&rhs)) + } +} + +type HuffmanCodeMap = BTreeMap>; + +fn main() { + let text = "this is an example for huffman encoding"; + + let mut frequencies = BTreeMap::new(); + for ch in text.chars() { + *frequencies.entry(ch).or_insert(0) += 1; + } + + let mut prioritized_frequencies = BinaryHeap::new(); + for counted_char in frequencies { + prioritized_frequencies.push(Node { + frequency: counted_char.1, + kind: NodeKind::Leaf(counted_char.0), + }); + } + + while prioritized_frequencies.len() > 1 { + let left_child = prioritized_frequencies.pop().unwrap(); + let right_child = prioritized_frequencies.pop().unwrap(); + prioritized_frequencies.push(Node { + frequency: right_child.frequency + left_child.frequency, + kind: NodeKind::Internal(Box::new(left_child), Box::new(right_child)), + }); + } + + let mut codes = HuffmanCodeMap::new(); + generate_codes( + prioritized_frequencies.peek().unwrap(), + vec![0u8; 0], + &mut codes, + ); + + for item in codes { + print!("{}: ", item.0); + for bit in item.1 { + print!("{}", bit); + } + println!(); + } +} + +fn generate_codes(node: &Node, prefix: Vec, out_codes: &mut HuffmanCodeMap) { + match node.kind { + NodeKind::Internal(ref left_child, ref right_child) => { + let mut left_prefix = prefix.clone(); + left_prefix.push(0); + generate_codes(&left_child, left_prefix, out_codes); + + let mut right_prefix = prefix; + right_prefix.push(1); + generate_codes(&right_child, right_prefix, out_codes); + } + NodeKind::Leaf(ch) => { + out_codes.insert(ch, prefix); + } + } +} diff --git a/Task/Huffman-coding/Zkl/huffman-coding-1.zkl b/Task/Huffman-coding/Zkl/huffman-coding-1.zkl new file mode 100644 index 0000000000..6f6cb16f95 --- /dev/null +++ b/Task/Huffman-coding/Zkl/huffman-coding-1.zkl @@ -0,0 +1,23 @@ +fcn buildHuffman(text){ //-->(encode dictionary, decode dictionary) + ft:=Dictionary(); + foreach c in (text){ ft[c]=ft.find(c,0)+1 } // leafs w/count + + // 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 + + 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[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 }); + encodeTable:=tree.toDictionary(); // symbol:Huffman code + decodeTable:=encodeTable.pump(Dictionary(),"reverse"); // code:symbol + return(encodeTable,decodeTable); +} diff --git a/Task/Huffman-coding/Zkl/huffman-coding-2.zkl b/Task/Huffman-coding/Zkl/huffman-coding-2.zkl new file mode 100644 index 0000000000..26fe58270b --- /dev/null +++ b/Task/Huffman-coding/Zkl/huffman-coding-2.zkl @@ -0,0 +1,8 @@ +fcn encode(text,table){ text.pump(String,table.get) } +fcn decode(bits,table){ // this is a horrible decoder, for testing only + w:=bits.walker(); sink:=Sink(String); + try{ s:=""; while(1){ + s+=w.next(); if(c:=table.find(s)) { sink.write(c); s=""; } + }}catch(TheEnd){} + sink.close(); +} diff --git a/Task/Huffman-coding/Zkl/huffman-coding-3.zkl b/Task/Huffman-coding/Zkl/huffman-coding-3.zkl new file mode 100644 index 0000000000..1dc22452e7 --- /dev/null +++ b/Task/Huffman-coding/Zkl/huffman-coding-3.zkl @@ -0,0 +1,10 @@ +text:="this is an example for huffman encoding"; +encodeTable,decodeTable := buildHuffman(text); +encodeTable.pump(Console.println,fcn(kv){"%s : %s".fmt(kv.xplode())}); + +e:=encode(text,encodeTable); +"Encode %d characters (%d bits) to %d bits (%d bytes):" + .fmt(text.len(),text.len()*8,e.len(),(e.len()+7)/8).println(); +println(e); + +0'|Bits decoded to: "%s"|.fmt(decode(e,decodeTable)).println(); diff --git a/Task/I-before-E-except-after-C/jq/i-before-e-except-after-c-1.jq b/Task/I-before-E-except-after-C/Jq/i-before-e-except-after-c-1.jq similarity index 100% rename from Task/I-before-E-except-after-C/jq/i-before-e-except-after-c-1.jq rename to Task/I-before-E-except-after-C/Jq/i-before-e-except-after-c-1.jq diff --git a/Task/I-before-E-except-after-C/jq/i-before-e-except-after-c-2.jq b/Task/I-before-E-except-after-C/Jq/i-before-e-except-after-c-2.jq similarity index 100% rename from Task/I-before-E-except-after-C/jq/i-before-e-except-after-c-2.jq rename to Task/I-before-E-except-after-C/Jq/i-before-e-except-after-c-2.jq 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.julia new file mode 100644 index 0000000000..36928859fe --- /dev/null +++ b/Task/I-before-E-except-after-C/Julia/i-before-e-except-after-c.julia @@ -0,0 +1,28 @@ +# v0.0.6 + +open("unixdict.txt") do txtfile + rule1, notrule1, rule2, notrule2 = 0, 0, 0, 0 + for word in eachline(txtfile) + # "I before E when not preceded by C" + if ismatch(r"ie"i, word) + if ismatch(r"cie"i, word) + notrule1 += 1 + else + rule1 += 1 + end + end + # "E before I when preceded by C" + if ismatch(r"ei"i, word) + if ismatch(r"cei"i, word) + rule2 += 1 + else + notrule2 += 1 + end + end + end + + print("Plausibility of \"I before E when not preceded by C\": ") + println(rule1 > 2 * notrule1 ? "PLAUSIBLE" : "UNPLAUSIBLE") + print("Plausibility of \"E before I when preceded by C\":") + println(rule2 > 2 * notrule2 ? "PLAUSIBLE" : "UNPLAUSIBLE") +end 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 new file mode 100644 index 0000000000..ceab8a0421 --- /dev/null +++ b/Task/I-before-E-except-after-C/Kotlin/i-before-e-except-after-c.kotlin @@ -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("http://www.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/Perl-6/i-before-e-except-after-c-1.pl6 b/Task/I-before-E-except-after-C/Perl-6/i-before-e-except-after-c-1.pl6 index 9709d8672d..dab882de73 100644 --- a/Task/I-before-E-except-after-C/Perl-6/i-before-e-except-after-c-1.pl6 +++ b/Task/I-before-E-except-after-C/Perl-6/i-before-e-except-after-c-1.pl6 @@ -22,12 +22,12 @@ grammar CollectWords { class CollectWords::Actions { method TOP($/) { - make $».ast.Bag; + make $».ast.flat.Bag; } method word($/) { if $ + $ { - make ($».ast, $».ast); + make flat $».ast, $».ast; } else { make (); } @@ -52,10 +52,10 @@ class CollectWords::Actions { sub plausible($good, $bad, $msg) { if $good > 2*$bad { - say "$msg: PLAUSIBLE ($good ✔ vs. $bad ✘)"; + say "$msg: PLAUSIBLE ($good vs. $bad ✘)"; return True; } else { - say "$msg: NOT PLAUSIBLE ($good ✔ vs. $bad ✘)"; + say "$msg: NOT PLAUSIBLE ($good vs. $bad ✘)"; return False; } } diff --git a/Task/I-before-E-except-after-C/Perl-6/i-before-e-except-after-c-2.pl6 b/Task/I-before-E-except-after-C/Perl-6/i-before-e-except-after-c-2.pl6 index c6ea5a84b6..e77c14fb9d 100644 --- a/Task/I-before-E-except-after-C/Perl-6/i-before-e-except-after-c-2.pl6 +++ b/Task/I-before-E-except-after-C/Perl-6/i-before-e-except-after-c-2.pl6 @@ -26,12 +26,12 @@ grammar CollectWords { class CollectWords::Actions { method TOP($/) { - make $».ast».flat.Bag; + make $».ast.flat.Bag; } method word($/) { if $ + $ { - make ($».ast xx $, $».ast xx $); + make flat $».ast xx $, $».ast xx $; } else { make (); } @@ -48,10 +48,10 @@ class CollectWords::Actions { sub plausible($good, $bad, $msg) { if $good > 2*$bad { - say "$msg: PLAUSIBLE ($good ✔ vs. $bad ✘)"; + say "$msg: PLAUSIBLE ($good vs. $bad ✘)"; return True; } else { - say "$msg: NOT PLAUSIBLE ($good ✔ vs. $bad ✘)"; + say "$msg: NOT PLAUSIBLE ($good vs. $bad ✘)"; return False; } } diff --git a/Task/I-before-E-except-after-C/Phix/i-before-e-except-after-c.phix b/Task/I-before-E-except-after-C/Phix/i-before-e-except-after-c.phix new file mode 100644 index 0000000000..e8d9a28c09 --- /dev/null +++ b/Task/I-before-E-except-after-C/Phix/i-before-e-except-after-c.phix @@ -0,0 +1,50 @@ +-- +-- demo\rosetta\IbeforeE.exw +-- ========================= +-- +procedure fatal(string msg) + printf(1,"unixdict.txt %s. download it from http://www.puzzlers.org/pub/wordlists/unixdict.txt\n",{msg}) + if getc(0) then end if + abort(1) +end procedure + +procedure show_plausibility(string msg, integer w, wo) + printf(1, "%s (pro: %3d, anti: %3d) is%s plausible\n",{msg,w,wo," not"[1..-(w<2*wo)]}) +end procedure + +integer fn = open(join_path({"..","unixdict.txt"}),"r") +if fn=-1 then + fn = open("unixdict.txt","r") + if fn=-1 then fatal("not found") end if +end if +string text = get_text(fn) +close(fn) +-- Note: my unixdict.txt begins with "10th" and ends +-- with "zygote", so boundary checks can be skipped. +integer {cei,xei,cie,xie} @= 0 +for i=1 to length(text) do + if text[i]='i' then + if text[i-1]='e' then + if text[i-2]='c' then + cei += 1 + else + xei += 1 + end if + end if + -- (not elsif here; "eie" occurs twice) + if text[i+1]='e' then + if text[i-1]='c' then + cie += 1 + else + xie += 1 + end if + end if + end if +end for +printf(1,"occurances: cie:%d, xie:%d, cei:%d, xei:%d\n", {cie,xie,cei,xei}) +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, cei) +show_plausibility("e before i when after c", cei, cie) +show_plausibility("i before e in general", xie + cie, xei + cei) +show_plausibility("e before i in general", xei + cei, xie + cie) 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-1.psh similarity index 100% rename from Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.psh rename to Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c-1.psh diff --git a/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c-2.psh b/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c-2.psh new file mode 100644 index 0000000000..725ea4154c --- /dev/null +++ b/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c-2.psh @@ -0,0 +1,29 @@ +$Web = New-Object -TypeName Net.Webclient +$Words = $web.DownloadString('http://www.puzzlers.org/pub/wordlists/unixdict.txt') + +$IE = $EI = $CIE = $CEI = @() + +$Clause1 = $Clause2 = $MainClause = $false + +foreach ($Word in $Words.split()) +{ + switch ($Word) + { + {$_ -like '*cei*'} {$CEI += $Word; break} + {$_ -like '*cie*'} {$CIE += $Word; break} + {$_ -like '*ie*'} {$IE += $Word} + {$_ -like '*ei*'} {$EI += $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/REXX/i-before-e-except-after-c-1.rexx b/Task/I-before-E-except-after-C/REXX/i-before-e-except-after-c-1.rexx index e1229b4b8e..1393e0330f 100644 --- a/Task/I-before-E-except-after-C/REXX/i-before-e-except-after-c-1.rexx +++ b/Task/I-before-E-except-after-C/REXX/i-before-e-except-after-c-1.rexx @@ -7,30 +7,30 @@ if iFID=='' | iFID=="," then iFID='UNIXDICT.TXT' /*Not specified? Then use the 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*/ - if pos('EI',u)\==0 & pos('IE',u)\==0 then #.both=#.both + 1 /*the word has both.*/ - call find 'ie' /*look for ie */ - call find 'ei' /* " " ei */ - end /*r*/ + if pos('EI', u)\==0 & pos('IE', u)\==0 then #.both=#.both + 1 /*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 '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) -say 'words with "IE" and preceded by "C": ' right(#.ie.c ,L) -say 'words with "IE" and not preceded by "C": ' right(#.ie.z ,L) -say 'words with "EI" and preceded by "C": ' right(#.ei.c ,L) -say 'words with "EI" and not preceded by "C": ' right(#.ei.z ,L) -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.' +say 'words with "IE" and "EI" (in same word): ' right(#.both, L) +say 'words with "IE" and preceded by "C": ' right(#.ie.c ,L) +say 'words with "IE" and not preceded by "C": ' right(#.ie.z ,L) +say 'words with "EI" and preceded by "C": ' right(#.ei.c ,L) +say 'words with "EI" and not preceded by "C": ' right(#.ei.z ,L) +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 + 1 - else #.x.z=#.x.z + 1 - s=_+1 /*handle the cases of multiple finds. */ +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 index 633c0ee56c..59c7da9267 100644 --- 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 @@ -4,15 +4,15 @@ 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' /* " " " " " " */ -tabs=xrange(, "f"x) /*get kinds of "tabs": '00'x ──► '0f'x*/ +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 - u=translate( linein(wFID), , tabs); upper u /*translate various tabs and low hexes.*/ + 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 /*Is it not an integer? Then ignore it*/ + 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.*/ @@ -21,10 +21,10 @@ f.=1 /*default word frequency multip #.freqs=#.freqs + 1 /*bump word counter in the FREQ list.*/ f._=f._ + freq /*add to a word's frequency count. */ end /*ws*/ - end /*recs*/ + 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 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 @@ -33,30 +33,29 @@ say 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*/ + 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 '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.' +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. */ - end /*forever*/ +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/TUSCRIPT/i-before-e-except-after-c.tu b/Task/I-before-E-except-after-C/TUSCRIPT/i-before-e-except-after-c.tu new file mode 100644 index 0000000000..cae74997df --- /dev/null +++ b/Task/I-before-E-except-after-C/TUSCRIPT/i-before-e-except-after-c.tu @@ -0,0 +1,62 @@ +$$ MODE TUSCRIPT,{} +words=REQUEST("http://www.puzzlers.org/pub/wordlists/unixdict.txt") +size=SIZE(words) +ieei=cie=xie=cei=xei=0 + +LOOP word=words +IF (word.nc." ie "," ei ") CYCLE + +IF (word.ct." ie "&& word.ct." ei ") THEN + ieei=ieei+1 + IF (word.ct." Cie ") THEN + cie=cie+1 + ELSEIF (word.ct." Cei ") THEN + cei=cei+1 + ELSE + xei=xei+1 + ENDIF +ENDIF + +IF (word.ct." ie ") THEN + IF (word.ct." Cie ") THEN + cie=cie+1 + ELSE + xie=xie+1 + ENDIF +ELSEIF (word.ct." ei ") THEN + IF (word.ct." Cei ") THEN + cei=cei+1 + ELSE + xei=xei+1 + ENDIF +ENDIF + +ENDLOOP + +PRINT "ieee ", ieei +PRINT "cie ", cie +PRINT "xie ", xie +PRINT "cei ", cei +PRINT "xei ", xei + +doublexei=2*xei +doublecei=cei*2 + +IF (xie>doublexei) THEN + check1="plausible" +ELSE + check1="not plausible" +ENDIF + +IF (cei>xei) THEN + check2="plausible" +ELSE + check2="not plausible" +ENDIF +IF (check1==check2) THEN + checkall="plausible" +ELSE + checkall="not plausible" +ENDIF + +TRAcE *check1,check2,checkall diff --git a/Task/I-before-E-except-after-C/Zkl/i-before-e-except-after-c-1.zkl b/Task/I-before-E-except-after-C/Zkl/i-before-e-except-after-c-1.zkl new file mode 100644 index 0000000000..0eec880879 --- /dev/null +++ b/Task/I-before-E-except-after-C/Zkl/i-before-e-except-after-c-1.zkl @@ -0,0 +1,9 @@ +fcn wcnt(wordList,altrs,aAdjust,bltrs,bAdjust,text){ + a:=wordList.reduce('wrap(cnt,word){ cnt+word.holds(altrs) },0) - aAdjust; + b:=wordList.reduce('wrap(cnt,word){ cnt+word.holds(bltrs) },0) - bAdjust; + ratio:=a.toFloat()/b; + "%s is %splausible".fmt(text,ratio<2 and "im" or "").println(); + " %d cases for and %d cases against is a ratio of %.3f.".fmt(a,b,ratio).println(); + return(a,b,ratio); +} +wordList:=File("unixdict.txt").read(); diff --git a/Task/I-before-E-except-after-C/Zkl/i-before-e-except-after-c-2.zkl b/Task/I-before-E-except-after-C/Zkl/i-before-e-except-after-c-2.zkl new file mode 100644 index 0000000000..48d44f6a32 --- /dev/null +++ b/Task/I-before-E-except-after-C/Zkl/i-before-e-except-after-c-2.zkl @@ -0,0 +1,3 @@ +a,b,r1:=wcnt(wordList,"cei",0,"cie",0,"E before I when preceded by C"); +_,_,r2:=wcnt(wordList,"ie",b,"ei",a, "I before E when not preceded by C"); +"Overall the rule is %splausible".fmt((r1<2 or r2<2) and "im" or "").println(); diff --git a/Task/I-before-E-except-after-C/Zkl/i-before-e-except-after-c-3.zkl b/Task/I-before-E-except-after-C/Zkl/i-before-e-except-after-c-3.zkl new file mode 100644 index 0000000000..d460dcc407 --- /dev/null +++ b/Task/I-before-E-except-after-C/Zkl/i-before-e-except-after-c-3.zkl @@ -0,0 +1,15 @@ +fcn wc2(wordList,altrs,aAdjust,bltrs,bAdjust,text){ + a,b:=wordList.reduce('wrap(cnts,line){ + // don't care if line is "Word PoS Freq" or "as yet Adv 14" + word,_,n:=line.split(); + if(word.holds(altrs)) cnts[0]=cnts[0]+n; + if(word.holds(bltrs)) cnts[1]=cnts[1]+n; + cnts + },L(0,0)); + a-=aAdjust; b-=bAdjust; + ratio:=a.toFloat()/b; + "%s is %splausible".fmt(text,ratio<2 and "im" or "").println(); + " %d cases for and %d cases against is a ratio of %.3f.".fmt(a,b,ratio).println(); + return(a,b,ratio); +} +wordList:=File("1_2_all_freq.txt").read(); diff --git a/Task/IBAN/00DESCRIPTION b/Task/IBAN/00DESCRIPTION index 8e52defff4..74414ec4e3 100644 --- a/Task/IBAN/00DESCRIPTION +++ b/Task/IBAN/00DESCRIPTION @@ -1,8 +1,20 @@ {{wikipedia}} -The [[wp:International_Bank_Account_Number|International Bank Account Number (IBAN)]] is an internationally agreed means of identifying bank accounts across national borders with a reduced risk of propagating [[wp:Transcription_error|transcription errors]].
    -The IBAN consists of up to 34 alphanumeric characters: first the two-letter ISO 3166-1 alpha-2 country code, then two check digits, and finally a country-specific Basic Bank Account Number (BBAN).
    + + +The   [[wp:International_Bank_Account_Number|International Bank Account Number (IBAN)]]   is an internationally agreed means of identifying bank accounts across national borders with a reduced risk of propagating [[wp:Transcription_error|transcription errors]]. + +The IBAN consists of up to '''34''' alphanumeric characters: +::*   first the two-letter ISO 3166-1 alpha-2 country code, +::*   then two check digits, and +::*   finally a country-specific Basic Bank Account Number (BBAN). + + The check digits enable a sanity check of the bank account number to confirm its integrity even before submitting a transaction. -The task here is to validate the following fictitious IBAN: GB82 WEST 1234 5698 7654 32. + +;Task: +Validate the following fictitious IBAN:   GB82 WEST 1234 5698 7654 32 + Details of the algorithm can be found on the Wikipedia page. +

    diff --git a/Task/IBAN/Java/iban.java b/Task/IBAN/Java/iban.java index 162cf8680a..4c9c184ae1 100644 --- a/Task/IBAN/Java/iban.java +++ b/Task/IBAN/Java/iban.java @@ -2,36 +2,40 @@ import java.math.BigInteger; import java.util.*; public class IBAN { - static final Map isoPairs; - - static final String iso = "AL28 AD24 AT20 AZ28 BE16 BH22 BA20 BR29 BG22 " + private static final String DEFSTRS = "" + + "AL28 AD24 AT20 AZ28 BE16 BH22 BA20 BR29 BG22 " + "HR21 CY28 CZ24 DK18 DO28 EE20 FO18 FI18 FR27 GE22 DE22 GI23 " + "GL18 GT28 HU28 IS26 IE22 IL23 IT27 KZ20 KW30 LV21 LB28 LI21 " + "LT20 LU20 MK19 MT31 MR27 MU30 MC27 MD24 ME22 NL18 NO15 PK24 " + "PS29 PL28 PT25 RO24 SM27 SA24 RS22 SK24 SI19 ES24 SE24 CH21 " + "TN24 TR26 AE23 GB22 VG24 GR27 CR21"; + private static final Map DEFINITIONS = new HashMap<>(); static { - isoPairs = new HashMap<>(); - for (String p : iso.split(" ")) - isoPairs.put(p.substring(0, 2), Integer.parseInt(p.substring(2))); + for (String definition : DEFSTRS.split(" ")) + DEFINITIONS.put(definition.substring(0, 2), Integer.parseInt(definition.substring(2))); } public static void main(String[] args) { - for (String iban : new String[]{"GB82 WEST 1234 5698 7654 32", - "GB82 TEST 1234 5698 7654 32", - "GB81 WEST 1234 5698 7654 32", - "SA03 8000 0000 6080 1016 7519", - "CH93 0076 2011 6238 5295 7"}) - System.out.printf("%s is valid: %s%n%n", iban, validateIBAN(iban)); + String[] ibans = { + "GB82 WEST 1234 5698 7654 32", + "GB82 TEST 1234 5698 7654 32", + "GB81 WEST 1234 5698 7654 32", + "SA03 8000 0000 6080 1016 7519", + "CH93 0076 2011 6238 5295 7", + "XX00 0000", + "", + "DE", + "DE13 äöü_ 1234 1234 1234 12"}; + for (String iban : ibans) + System.out.printf("%s is %s.%n", iban, validateIBAN(iban) ? "valid" : "not valid"); } static boolean validateIBAN(String iban) { - iban = iban.replaceAll("\\s", "").toUpperCase(); + iban = iban.replaceAll("\\s", "").toUpperCase(Locale.ROOT); int len = iban.length(); - - if (len < 4 || isoPairs.get(iban.substring(0, 2)) != len) + if (len < 4 || !iban.matches("[0-9A-Z]+") || DEFINITIONS.getOrDefault(iban.substring(0, 2), 0) != len) return false; iban = iban.substring(4) + iban.substring(0, 4); @@ -42,6 +46,6 @@ public class IBAN { BigInteger bigInt = new BigInteger(sb.toString()); - return bigInt.mod(new BigInteger("97")).intValue() == 1; + return bigInt.mod(BigInteger.valueOf(97)).intValue() == 1; } } diff --git a/Task/IBAN/jq/iban-1.jq b/Task/IBAN/Jq/iban-1.jq similarity index 100% rename from Task/IBAN/jq/iban-1.jq rename to Task/IBAN/Jq/iban-1.jq diff --git a/Task/IBAN/jq/iban-2.jq b/Task/IBAN/Jq/iban-2.jq similarity index 100% rename from Task/IBAN/jq/iban-2.jq rename to Task/IBAN/Jq/iban-2.jq diff --git a/Task/IBAN/jq/iban-3.jq b/Task/IBAN/Jq/iban-3.jq similarity index 100% rename from Task/IBAN/jq/iban-3.jq rename to Task/IBAN/Jq/iban-3.jq diff --git a/Task/IBAN/Julia/iban.julia b/Task/IBAN/Julia/iban.julia new file mode 100644 index 0000000000..6bd739af9e --- /dev/null +++ b/Task/IBAN/Julia/iban.julia @@ -0,0 +1,28 @@ +# v0.6.0 +function validiban(iban::String) + const COUNTRY2LENGTH = 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 + ) + + # Ensure upper alphanumeric input. + iban = replace(iban, " ", "") + iban = replace(iban, "\t", "") + + rst = ismatch(r"^[\dA-Z]+$", iban) + # Validate country code against expected length. + rst = rst && length(iban) == COUNTRY2LENGTH[iban[1:2]] + # Shift and convert. + iban = iban[5:end] * iban[1:4] + digits = parse(BigInt, join(string(parse(Int, ch, 36)) for ch in iban)) + return rst && digits % 97 == 1 +end + +@show validiban("GB82 WEST 1234 5698 7654 32") +@show validiban("GB82 TEST 1234 5698 7654 32") diff --git a/Task/IBAN/Kotlin/iban.kotlin b/Task/IBAN/Kotlin/iban.kotlin new file mode 100644 index 0000000000..3a7d8b32de --- /dev/null +++ b/Task/IBAN/Kotlin/iban.kotlin @@ -0,0 +1,40 @@ +// version 1.0.6 + +import java.math.BigInteger + +object Iban { + /* List updated to release 73, January 2017, of IBAN Registry (75 countries) */ + private val countryCodes = + "AD24 AE23 AL28 AT20 AZ28 BA20 BE16 BG22 BH22 BR29 BY28 CH21 CR22 CY28 CZ24 DE22 " + + "DK18 DO28 EE20 ES24 FI18 FO18 FR27 GB22 GE22 GI23 GL18 GR27 GT28 HR21 HU28 IE22 " + + "IL23 IQ23 IS26 IT27 JO30 KW30 KZ20 LB28 LC32 LI21 LT20 LU20 LV21 MC27 MD24 ME22 " + + "MK19 MR27 MT31 MU30 NL18 NO15 PK24 PL28 PS29 PT25 QA29 RO24 RS22 SA24 SC31 SE24 " + + "SI19 SK24 SM27 ST25 SV28 TL23 TN24 TR26 UA29 VG24 XK20" + + private fun checkCountryCode(cc: String) = cc in countryCodes + + fun validate(iban: String): Boolean { + // remove spaces from IBAN + var s = iban.replace(" ", "") + + // check country code + if (!checkCountryCode(s.substring(0, 2) + s.length)) return false + + // move first 4 characters to end + s = s.substring(4) + s.substring(0, 4) + + // replace A to Z with numbers 10 To 35 + for (ch in 'A'..'Z') s = s.replace(ch.toString(), (ch - 55).toInt().toString()) + + // check whether mod 97 calculation gives a remainder of 1 + return BigInteger(s) % BigInteger.valueOf(97L) == BigInteger.ONE + } +} + +fun main(args: Array) { + val ibans = arrayOf("GB82 WEST 1234 5698 7654 32", "GB82 TEST 1234 5698 7654 32") + for (iban in ibans) { + val isValid = Iban.validate(iban) + println(iban + if(isValid) " may be valid" else " is not valid") + } +} diff --git a/Task/IBAN/Phix/iban.phix b/Task/IBAN/Phix/iban.phix new file mode 100644 index 0000000000..c0e7c26a4f --- /dev/null +++ b/Task/IBAN/Phix/iban.phix @@ -0,0 +1,59 @@ +-- +-- 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) + +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 + +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) diff --git a/Task/IBAN/Rust/iban.rust b/Task/IBAN/Rust/iban.rust new file mode 100644 index 0000000000..1f04259364 --- /dev/null +++ b/Task/IBAN/Rust/iban.rust @@ -0,0 +1,65 @@ +fn main() { + for iban in [ + "", + "x", + "QQ82", + "QQ82W", + "GB82 TEST 1234 5698 7654 322", + "gb82 WEST 1234 5698 7654 32", + "GB82 WEST 1234 5698 7654 32", + "GB82 TEST 1234 5698 7654 32", + "GB81 WEST 1234 5698 7654 32", + "SA03 8000 0000 6080 1016 7519", + "CH93 0076 2011 6238 5295 7", + ].iter() + { + println!( + "'{}' is {}valid", + iban, + if validate_iban(iban) { "" } else { "NOT " } + ); + } +} + +fn validate_iban(iban: &str) -> bool { + let iso_len = [ + ("AL", 28), ("AD", 24), ("AT", 20), ("AZ", 28), ("BE", 16), ("BH", 22), + ("BA", 20), ("BR", 29), ("BG", 22), ("HR", 21), ("CY", 28), ("CZ", 24), + ("DK", 18), ("DO", 28), ("EE", 20), ("FO", 18), ("FI", 18), ("FR", 27), + ("GE", 22), ("DE", 22), ("GI", 23), ("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), ("GR", 27), ("CR", 21), + ]; + let trimmed_iban = iban.chars() + .filter(|&ch| ch != ' ') + .collect::() + .to_uppercase(); + if trimmed_iban.len() < 4 { + return false; + } + let prefix = &trimmed_iban[0..2]; + if let Some(pair) = iso_len.iter().find(|&&(code, _)| code == prefix) { + if pair.1 != trimmed_iban.len() { + return false; + } + } else { + return false; + } + let reversed_iban = format!("{}{}", &trimmed_iban[4..], &trimmed_iban[0..4]); + let mut expanded_iban = String::new(); + for ch in reversed_iban.chars() { + expanded_iban.push_str(&if ch.is_numeric() { + format!("{}", ch) + } else { + format!("{}", ch as u8 - 'A' as u8 + 10u8) + }); + } + expanded_iban.bytes().fold(0, |acc, ch| { + (acc * 10 + ch as u32 - '0' as u32) % 97 + }) == 1 +} diff --git a/Task/IBAN/Sidef/iban.sidef b/Task/IBAN/Sidef/iban.sidef index b2101eed51..15a9e30f12 100644 --- a/Task/IBAN/Sidef/iban.sidef +++ b/Task/IBAN/Sidef/iban.sidef @@ -1,5 +1,5 @@ func valid_iban(iban) { - static len = Hash.new( + static len = Hash( AD=>24, AE=>23, AL=>28, AO=>25, AT=>20, AZ=>28, BA=>20, BE=>16, BF=>27, BG=>22, BH=>22, BI=>16, BJ=>28, BR=>29, CG=>27, CH=>21, CI=>28, CM=>27, CR=>21, CV=>25, CY=>28, CZ=>24, DE=>22, DK=>18, DO=>28, DZ=>24, EE=>20, @@ -10,22 +10,22 @@ func valid_iban(iban) { MZ=>25, NL=>18, NO=>15, PK=>24, PL=>28, PS=>29, PT=>25, QA=>29, RO=>24, RS=>22, SA=>24, SE=>24, SI=>19, SK=>24, SM=>27, SN=>28, TN=>24, TR=>26, UA=>29, VG=>24, - ); + ) # Ensure upper alphanumeric input. - iban -= /\s+/g; - iban.uc! ~~ /^[0-9A-Z]+\z/ || return false; + iban -= /\s+/g + iban.uc! ~~ /^[0-9A-Z]+\z/ || return false # Validate country code against expected length. - var cc = iban.substr(0, 2); - iban.len == len{cc} || return false; + var cc = iban.substr(0, 2) + iban.len == len{cc} || return false # Shift and convert. - iban.sub!(/(.{4})(.+)/, {|a,b| b+a}); - iban.gsub!(/([A-Z])/, {|a| a.ord - 55}); + iban.sub!(/(.{4})(.+)/, {|a,b| b+a}) + iban.gsub!(/([A-Z])/, {|a| a.ord - 55}) - iban.to_i % 97 == 1; + iban.to_i % 97 == 1 } -say valid_iban("GB82 WEST 1234 5698 7654 32"); #=> true -say valid_iban("GB82 TEST 1234 5698 7654 32"); #=> false +say valid_iban("GB82 WEST 1234 5698 7654 32") #=> true +say valid_iban("GB82 TEST 1234 5698 7654 32") #=> false diff --git a/Task/IBAN/Standard-ML/iban.ml b/Task/IBAN/Standard-ML/iban.ml new file mode 100644 index 0000000000..815bdd0f1e --- /dev/null +++ b/Task/IBAN/Standard-ML/iban.ml @@ -0,0 +1,67 @@ +(* country_code : string -> int *) +(* Get the length of a valid IBAN given the two chars long country code *) +fun country_code (str : string) : int = + case str of + "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 + | _ => raise Domain + + +(* removespace : string -> string *) +(* Removes all spaces from a string *) +fun removespace s = String.translate (fn #" " => "" | c => str c) s + +(* to_upper : string -> string *) +(* Convert every char to upper of a string *) +fun to_upper (s : string) : string = + String.translate (fn c => str (Char.toUpper c)) s + +(* convert_to_number : char -> string *) +(* Covert a alphanumeric char into a numerical string *) +fun convert_to_number (c : char) : string = + if Char.isDigit c then str c else + if Char.isUpper c then Int.toString (10 + ord c - ord #"A") else + raise Domain + + +(* verify_iban : string -> bool *) +(* Check weather a string is a valid IBAN *) +fun verify_iban str = + let + (* Remove spaces and make upper case *) + val str = to_upper (removespace str) + (* Fetch first two chars (country code) *) + val country = String.substring (str, 0, 2) + val len = country_code country + in + (* size test *) + String.size str = len + andalso + (* Every char must be alphanumeric *) + List.all Char.isAlphaNum (explode str) + andalso + let + (* Reorder *) + val str = String.substring (str, 4, String.size str - 4) ^ String.substring (str, 0, 4) + (* Convert into digits *) + val str = String.translate convert_to_number str + (* Convert into a big number *) + val number = valOf (IntInf.fromString str) + in + IntInf.mod (number, 97) = 1 + end + end handle Subscript => false | Domain => false diff --git a/Task/IBAN/ZX-Spectrum-Basic/iban.zx b/Task/IBAN/ZX-Spectrum-Basic/iban.zx new file mode 100644 index 0000000000..b2fc2d94eb --- /dev/null +++ b/Task/IBAN/ZX-Spectrum-Basic/iban.zx @@ -0,0 +1,64 @@ +10 REM REM Used the following as official standard: +20 REM REM http://www.cnb.cz/cs/platebni_styk/iban/download/EBS204.pdf +30 REM REM Pairs of ISO 3166 country code & expected IBAN length for this country +40 LET c$="AL28 AD24 AT20 AZ28 BE16 BH22 BA20 BR29 BG22 CR21 HR21 CY28 CZ24 DK18 DO28 EE20 " +50 LET c$=c$+"FO18 FI18 FR27 GE22 DE22 GI23 GR27 GL18 GT28 HU28 IS26 IE22 IL23 IT27 KZ20 KW30 " +60 LET c$=c$+"LV21 LB28 LI21 LT20 LU20 MK19 MT31 MR27 MU30 MC27 MD24 ME22 NL18 NO15 PK24 PS29 " +70 LET c$=c$+"PL28 PT25 RO24 SM27 SA24 RS22 SK24 SI19 ES24 SE24 CH21 TN24 TR26 AE23 GB22 VG24 " +80 LET e$="" +100 LET i$="GB82 WEST 1234 5698 7654 32": GO SUB 1000 +110 LET i$="gb82 west 1234 5698 7654 32": GO SUB 1000 +120 LET i$="GB82 TEST 1234 5698 7654 32": GO SUB 1000 +130 LET i$="GR16 0110 1250 0000 0001 2300 695": GO SUB 1000 +140 LET i$="IL62-0108-0000-0009-9999-999": GO SUB 1000 +900 STOP +1000 REM IBAN check routine +1010 LET explen=0: LET lenc=LEN c$ +1020 FOR i=1 TO lenc STEP 5 +1030 IF i$( TO 2)=c$(i TO i+1) THEN LET explen=VAL c$(i+2 TO i+3): GO TO 2000 +1040 NEXT i +2000 LET match=explen>0 +2010 REM Continue if country code found +2020 IF NOT match THEN LET e$="country code: "+i$( TO 2): GO TO 3000 +2030 REM Remove espace = convert to digital IBAN +2040 LET d$="" +2050 FOR i=1 TO LEN i$ +2060 IF i$(i)>" " THEN LET d$=d$+i$(i) +2070 NEXT i +2080 LET match=explen=LEN d$ +2090 REM Continue if length is correct +2100 IF NOT match THEN LET e$="code length, expected length: "+STR$ explen: GO TO 3000 +2110 REM Create temporary string with country code appended +2120 LET t$=d$(5 TO )+d$(1 TO 2) +2130 REM Make big number, replacing letters by numbers using next conversion table: A=10 ... Z=35 +2140 LET b$="" +2150 FOR i=1 TO LEN t$ +2160 LET c= CODE t$(i) +2170 IF (c>64 AND c<91) THEN LET b$=b$+STR$ (c-55): GO TO 2200 +2190 IF (c>47 AND c<58) THEN LET b$=b$+t$(i) +2200 NEXT i +2210 REM MOD 97 on bignum$+"00" and subtract result from 98 to obtain control number +2220 LET k$=b$+"00": GO SUB 4000 +2230 LET kk=98-mod97 +2240 REM Compare with control number in IBAN +2250 LET match=VAL i$(3 TO 4)=kk +2260 REM Continue if control number matches +2270 IF NOT match THEN LET e$="check digits, should be: "+STR$ kk: GO TO 3000 +2280 REM Append kk to bignum$ and determine if MOD 97 results in 1 +2285 LET k$="0"+STR$ kk +2290 LET k$=b$+k$(LEN k$-1 TO ): GO SUB 4000 +2300 LET match=mod97=1 +2310 REM Continue if mod 97 +2320 IF NOT match THEN LET e$="result from modulo 97" +3000 IF match THEN PRINT " ": GO TO 3100 +3010 PRINT "in";: LET e$=" ***error!*** invalid "+e$ +3100 PRINT "valid IBAN: ";i$;e$: LET e$="" +3110 RETURN +4000 REM Modulo 97 +4010 LET mod97=0 +4020 FOR i=1 TO LEN k$ +4030 LET d$=STR$ (mod97)+k$(i) +4040 LET mod97=FN m(VAL (d$),97) +4050 NEXT i +4060 RETURN +5000 DEF FN m(a,b)=a-INT (a/b)*b: REM modulo diff --git a/Task/IBAN/Zkl/iban-1.zkl b/Task/IBAN/Zkl/iban-1.zkl new file mode 100644 index 0000000000..76fcbe9437 --- /dev/null +++ b/Task/IBAN/Zkl/iban-1.zkl @@ -0,0 +1,6 @@ +var BN=Import("zklBigNum"); +fcn validateIBAN(iban){ + iban=iban-" \t"; + alphaNums.matches(iban) and (ibans.find(iban[0,2])==iban.len()) and + ( BN((iban[4,*]+iban[0,4]).apply("toInt",36)) % 97 == 1 ) +} diff --git a/Task/IBAN/Zkl/iban-2.zkl b/Task/IBAN/Zkl/iban-2.zkl new file mode 100644 index 0000000000..99d6473d40 --- /dev/null +++ b/Task/IBAN/Zkl/iban-2.zkl @@ -0,0 +1,12 @@ +fcn validateIBAN(iban){ + iban=iban-" \t"; + alphaNums.matches(iban) and (ibans.find(iban[0,2])==iban.len()) and + ( (iban[4,*]+iban[0,4]).apply("toInt",36) : mod97(_) == 1 ) +} +fcn mod97(str){ + n:=0; m:=9; M:=0; while(N:=str[n,m]){ + M=((M.toString()+N).toInt()) % 97; + n+=m; m=7; + } + M +} diff --git a/Task/IBAN/Zkl/iban-3.zkl b/Task/IBAN/Zkl/iban-3.zkl new file mode 100644 index 0000000000..8e1b314676 --- /dev/null +++ b/Task/IBAN/Zkl/iban-3.zkl @@ -0,0 +1,10 @@ +var alphaNums=RegExp("^[0-9A-Z]+$"); +var ibans= // Dictionary("AD":24, ...) + ("AD24 AE23 AL28 AO25 AT20 AZ28 BA20 BE16 BF27 BG22 BH22 BI16 " + "BJ28 BR29 CG27 CH21 CI28 CM27 CR21 CV25 CY28 CZ24 DE22 DK18 " + "DO28 DZ24 EE20 EG27 ES24 FI18 FO18 FR27 GA27 GB22 GE22 GI23 " + "GL18 GR27 GT28 HR21 HU28 IE22 IL23 IR26 IS26 IT27 JO30 KW30 " + "KZ20 LB28 LI21 LT20 LU20 LV21 MC27 MD24 ME22 MG27 MK19 ML28 " + "MR27 MT31 MU30 MZ25 NL18 NO15 PK24 PL28 PS29 PT25 QA29 RO24 " + "RS22 SA24 SE24 SI19 SK24 SM27 SN28 TN24 TR26 UA29 VG24") + .split(" ").pump(D(),fcn(w){return(w[0,2],w[2,*].toInt())}); diff --git a/Task/IBAN/Zkl/iban-4.zkl b/Task/IBAN/Zkl/iban-4.zkl new file mode 100644 index 0000000000..99f4b34a1c --- /dev/null +++ b/Task/IBAN/Zkl/iban-4.zkl @@ -0,0 +1,20 @@ + // all valid +T("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") +.apply(validateIBAN).println(); + + // all invalid +T("gb82 west 1234 5698 7654 32","GB82 TEST 1234 5698 7654 32", + "GB82 WEST 1243 5698 7654 32","AE82 WEST 1234 5698 7654 32" + "IL62-0108-0000-0009-9999-999","US12 3456 7890 0987 6543 210", + "GR16 0110 1250 0000 0001 2300 695X","GT11 2222 3333 4444 5555 6666 7777", + "MK11 2222 3333 4444 555") +.apply(validateIBAN).println(); + + // white list from Scala +("AD1200012030200359100100 AE260211000000230064016 AL47212110090000000235698741 " +... +"CH9300762011623852957").split() +.apply(validateIBAN).toString(*).println(); diff --git a/Task/Identity-matrix/360-Assembly/identity-matrix.360 b/Task/Identity-matrix/360-Assembly/identity-matrix.360 new file mode 100644 index 0000000000..b12dc23f62 --- /dev/null +++ b/Task/Identity-matrix/360-Assembly/identity-matrix.360 @@ -0,0 +1,73 @@ +* Identity matrix 31/03/2017 +INDENMAT CSECT + USING INDENMAT,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + L R1,N n + MH R1,N+2 n*n + SLA R1,2 *4 + ST R1,LL amount of storage required + GETMAIN RU,LV=(R1) allocate storage for matrix + USING DYNA,R11 make storage addressable + LR R11,R1 set addressability + LA R6,1 i=1 + DO WHILE=(C,R6,LE,N) do i=1 to n + LA R7,1 j=1 + DO WHILE=(C,R7,LE,N) do j=1 to n + IF CR,R6,EQ,R7 THEN if i=j then + LA R2,1 k=1 + ELSE , else + LA R2,0 k=0 + ENDIF , endif + LR R1,R6 i + BCTR R1,0 -1 + MH R1,N+2 *n + AR R1,R7 (i-1)*n+j + BCTR R1,0 -1 + SLA R1,2 *4 + ST R2,A(R1) a(i,j)=k + LA R7,1(R7) j++ + ENDDO , enddo j + LA R6,1(R6) i++ + ENDDO , enddo i + LA R6,1 i=1 + DO WHILE=(C,R6,LE,N) do i=1 to n + LA R10,PG pgi=0 + LA R7,1 j=1 + DO WHILE=(C,R7,LE,N) do j=1 to n + LR R1,R6 i + BCTR R1,0 -1 + MH R1,N+2 *n + AR R1,R7 (i-1)*n+j + BCTR R1,0 -1 + SLA R1,2 *4 + L R2,A(R1) a(i,j) + XDECO R2,XDEC edit + MVC 0(1,R10),XDEC+11 output + LA R10,1(R10) pgi+=1 + LA R7,1(R7) j++ + ENDDO , enddo j + XPRNT PG,L'PG print + LA R6,1(R6) i++ + ENDDO , enddo i + LA R1,A address to free + LA R2,LL amount of storage to free + FREEMAIN A=(R1),LV=(R2) free allocated storage + DROP R11 drop register + L R13,4(0,R13) restore previous savearea pointer + LM R14,R12,12(R13) restore previous context + XR R15,R15 rc=0 + BR R14 exit +NN EQU 10 parameter n (90=>32K) +N DC A(NN) n +LL DS F n*n*4 +PG DC CL(NN)' ' buffer +XDEC DS CL12 temp +DYNA DSECT +A DS F a(n,n) + YREGS + END INDENMAT diff --git a/Task/Identity-matrix/APL/identity-matrix-3.apl b/Task/Identity-matrix/APL/identity-matrix-3.apl index f880266da1..10f4b814b4 100644 --- a/Task/Identity-matrix/APL/identity-matrix-3.apl +++ b/Task/Identity-matrix/APL/identity-matrix-3.apl @@ -1 +1,2 @@ - ID←{⍵ ⍵ ρ 1, ⍵ρ0} + ID←∘.=⍨⍳ + ID←⍳∘.=⍳ diff --git a/Task/Identity-matrix/APL/identity-matrix-4.apl b/Task/Identity-matrix/APL/identity-matrix-4.apl new file mode 100644 index 0000000000..f880266da1 --- /dev/null +++ b/Task/Identity-matrix/APL/identity-matrix-4.apl @@ -0,0 +1 @@ + ID←{⍵ ⍵ ρ 1, ⍵ρ0} diff --git a/Task/Identity-matrix/AppleScript/identity-matrix.applescript b/Task/Identity-matrix/AppleScript/identity-matrix.applescript index f2819a1ebe..1d4dbac1bc 100644 --- a/Task/Identity-matrix/AppleScript/identity-matrix.applescript +++ b/Task/Identity-matrix/AppleScript/identity-matrix.applescript @@ -1,24 +1,30 @@ +-- ID MATRIX ----------------------------------------------------------------- + -- idMatrix :: Int -> [(0|1)] on idMatrix(n) - set xs to range(1, n) + set xs to enumFromTo(1, n) script row - on lambda(x) - script zeroOrOne - on lambda(i) - cond(i = x, 1, 0) - end lambda + on |λ|(x) + script + on |λ|(i) + if i = x then + 1 + else + 0 + end if + end |λ| end script - map(zeroOrOne, xs) - end lambda + map(result, xs) + end |λ| end script map(row, xs) end idMatrix --- TEST +-- TEST ---------------------------------------------------------------------- on run idMatrix(5) @@ -26,8 +32,21 @@ on run end run +-- GENERIC FUNCTIONS --------------------------------------------------------- --- GENERIC FUNCTIONS ------------------------------------------ +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if n < m then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- map :: (a -> b) -> [a] -> [b] on map(f, xs) @@ -35,7 +54,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -48,30 +67,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn - --- cond :: Bool -> a -> a -> a -on cond(bool, f, g) - if bool then - f - else - g - end if -end cond - --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then - set d to -1 - else - set d to 1 - end if - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range diff --git a/Task/Identity-matrix/Elena/identity-matrix.elena b/Task/Identity-matrix/Elena/identity-matrix.elena index ee807cdf78..c40d02a599 100644 --- a/Task/Identity-matrix/Elena/identity-matrix.elena +++ b/Task/Identity-matrix/Elena/identity-matrix.elena @@ -1,14 +1,14 @@ -#import system. -#import extensions. -#import system'routines. -#import system'collections. +import extensions. +import system'routines. +import system'collections. -#symbol program= +program = [ - #var n := console write:"Enter the matrix size:" readLine toInt. + var n := console write:"Enter the matrix size:"; readLine; toInt. - #var identity := n repeat &each: i = [ n repeat &each: j = [ (i == j)iif:1:0 ] summarize:(ArrayList new) ] summarize:(ArrayList new). + var identity := 0 till:n repeat(:i)( 0 till:n repeat(:j)( (i == j)iif(1,0) ); summarize(ArrayList new) ); + summarize(ArrayList new). - identity run &each: - row = [ console writeLine:row ]. + identity forEach + (:row) [ console printLine:row ]. ]. diff --git a/Task/Identity-matrix/Forth/identity-matrix.fth b/Task/Identity-matrix/Forth/identity-matrix.fth new file mode 100644 index 0000000000..ffee94f908 --- /dev/null +++ b/Task/Identity-matrix/Forth/identity-matrix.fth @@ -0,0 +1,16 @@ +S" fsl-util.fs" REQUIRED + +: build-identity ( 'p n -- 'p ) \ make an NxN identity matrix + 0 DO + I 1+ 0 DO + I J = IF 1.0E0 DUP I J }} F! + ELSE + 0.0E0 DUP J I }} F! + 0.0E0 DUP I J }} F! + THEN + LOOP + LOOP ; + +6 6 float matrix a{{ +a{{ 6 build-identity +6 6 a{{ }}fprint diff --git a/Task/Identity-matrix/Haskell/identity-matrix-4.hs b/Task/Identity-matrix/Haskell/identity-matrix-4.hs new file mode 100644 index 0000000000..4a681469eb --- /dev/null +++ b/Task/Identity-matrix/Haskell/identity-matrix-4.hs @@ -0,0 +1,7 @@ +idMatrix :: Int -> [[Int]] +idMatrix n = + let xs = [1 .. n] + in xs >>= \x -> [xs >>= \y -> [fromEnum (x == y)]] + +main :: IO () +main = (putStr . unlines) $ fmap (unwords . fmap show) (idMatrix 5) diff --git a/Task/Identity-matrix/JavaScript/identity-matrix-2.js b/Task/Identity-matrix/JavaScript/identity-matrix-2.js index 4316a87c8d..bb7d18dce7 100644 --- a/Task/Identity-matrix/JavaScript/identity-matrix-2.js +++ b/Task/Identity-matrix/JavaScript/identity-matrix-2.js @@ -7,7 +7,11 @@ length: n }, (_, j) => i !== j ? 0 : 1)); + // show :: a -> String + const show = JSON.stringify; // TEST - return idMatrix(5); + return idMatrix(5) + .map(show) + .join('\n'); })(); diff --git a/Task/Identity-matrix/JavaScript/identity-matrix-3.js b/Task/Identity-matrix/JavaScript/identity-matrix-3.js deleted file mode 100644 index dac012ce07..0000000000 --- a/Task/Identity-matrix/JavaScript/identity-matrix-3.js +++ /dev/null @@ -1,2 +0,0 @@ -[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], -[0, 0, 0, 1, 0], [0, 0, 0, 0, 1]] diff --git a/Task/Identity-matrix/jq/identity-matrix-1.jq b/Task/Identity-matrix/Jq/identity-matrix-1.jq similarity index 100% rename from Task/Identity-matrix/jq/identity-matrix-1.jq rename to Task/Identity-matrix/Jq/identity-matrix-1.jq diff --git a/Task/Identity-matrix/jq/identity-matrix-2.jq b/Task/Identity-matrix/Jq/identity-matrix-2.jq similarity index 100% rename from Task/Identity-matrix/jq/identity-matrix-2.jq rename to Task/Identity-matrix/Jq/identity-matrix-2.jq diff --git a/Task/Identity-matrix/jq/identity-matrix-3.jq b/Task/Identity-matrix/Jq/identity-matrix-3.jq similarity index 100% rename from Task/Identity-matrix/jq/identity-matrix-3.jq rename to Task/Identity-matrix/Jq/identity-matrix-3.jq diff --git a/Task/Identity-matrix/K/identity-matrix.k b/Task/Identity-matrix/K/identity-matrix.k new file mode 100644 index 0000000000..fa6a209911 --- /dev/null +++ b/Task/Identity-matrix/K/identity-matrix.k @@ -0,0 +1,11 @@ + =4 +(1 0 0 0 + 0 1 0 0 + 0 0 1 0 + 0 0 0 1) + =5 +(1 0 0 0 0 + 0 1 0 0 0 + 0 0 1 0 0 + 0 0 0 1 0 + 0 0 0 0 1) diff --git a/Task/Identity-matrix/Kotlin/identity-matrix.kotlin b/Task/Identity-matrix/Kotlin/identity-matrix.kotlin new file mode 100644 index 0000000000..8e873fc892 --- /dev/null +++ b/Task/Identity-matrix/Kotlin/identity-matrix.kotlin @@ -0,0 +1,17 @@ +// 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/OoRexx/identity-matrix.rexx b/Task/Identity-matrix/OoRexx/identity-matrix.rexx new file mode 100644 index 0000000000..607874e1bb --- /dev/null +++ b/Task/Identity-matrix/OoRexx/identity-matrix.rexx @@ -0,0 +1,29 @@ +say "a 3x3 identity matrix" +say +call printMatrix createIdentityMatrix(3) +say +say "a 5x5 identity matrix" +say +call printMatrix createIdentityMatrix(5) + +::routine createIdentityMatrix + use arg size + matrix = .array~new(size, size) + loop i = 1 to size + loop j = 1 to size + if i == j then matrix[i, j] = 1 + else matrix[i, j] = 0 + end j + end i + return matrix + +::routine printMatrix + use arg matrix + + loop i = 1 to matrix~dimension(1) + line = "" + loop j = 1 to matrix~dimension(2) + line = line matrix[i, j] + end j + say line + end i diff --git a/Task/Identity-matrix/Phix/identity-matrix.phix b/Task/Identity-matrix/Phix/identity-matrix.phix new file mode 100644 index 0000000000..9027cd0f27 --- /dev/null +++ b/Task/Identity-matrix/Phix/identity-matrix.phix @@ -0,0 +1,13 @@ +function identity(integer n) +sequence res = repeat(repeat(0,n),n) + for i=1 to n do + res[i][i] = 1 + end for + return res +end function + +ppOpt({pp_Nest,1}) +pp(identity(3)) +pp(identity(5)) +pp(identity(7)) +pp(identity(9)) diff --git a/Task/Identity-matrix/Sidef/identity-matrix.sidef b/Task/Identity-matrix/Sidef/identity-matrix.sidef index cd73f9e22f..bbc2576b12 100644 --- a/Task/Identity-matrix/Sidef/identity-matrix.sidef +++ b/Task/Identity-matrix/Sidef/identity-matrix.sidef @@ -1,12 +1,14 @@ func identity_matrix(n) { - 1..n -> map { |i| - 1..n -> map {|j| j == i ? 1 : 0 } + n.of { |i| + n.of { |j| + i == j ? 1 : 0 + } } } -(ARGV.len ? ARGV.map{.to_i} : [4, 5, 6]) -> each { |n| - say "\n#{n}:"; - identity_matrix(n).each { |row| - say row.join(' '); +for n (ARGV ? ARGV.map{.to_i} : [4, 5, 6]) { + say "\n#{n}:" + for row (identity_matrix(n)) { + say row.join(' ') } } diff --git a/Task/Identity-matrix/Sinclair-ZX81-BASIC/identity-matrix.sinclair b/Task/Identity-matrix/Sinclair-ZX81-BASIC/identity-matrix.sinclair new file mode 100644 index 0000000000..f54d760869 --- /dev/null +++ b/Task/Identity-matrix/Sinclair-ZX81-BASIC/identity-matrix.sinclair @@ -0,0 +1,12 @@ + 10 INPUT S + 20 DIM M(S,S) + 30 FOR I=1 TO S + 40 LET M(I,I)=1 + 50 NEXT I + 60 FOR I=1 TO S + 70 SCROLL + 80 FOR J=1 TO S + 90 PRINT M(I,J); +100 NEXT J +110 PRINT +120 NEXT I diff --git a/Task/Identity-matrix/TypeScript/identity-matrix.type b/Task/Identity-matrix/TypeScript/identity-matrix.type new file mode 100644 index 0000000000..f220c6f2ad --- /dev/null +++ b/Task/Identity-matrix/TypeScript/identity-matrix.type @@ -0,0 +1,14 @@ +function identity(n) { + if (n < 1) return "Not defined"; + else if (n == 1) return 1; + else { + var idMatrix:number[][]; + for (var i: number = 0; i < n; i++) { + for (var j: number = 0; j < n; j++) { + if (i != j) idMatrix[i][j] = 0; + else idMatrix[i][j] = 1; + } + } + return idMatrix; + } +} diff --git a/Task/Identity-matrix/Unicon/identity-matrix.unicon b/Task/Identity-matrix/Unicon/identity-matrix.unicon deleted file mode 100644 index 3fbb7c3dd1..0000000000 --- a/Task/Identity-matrix/Unicon/identity-matrix.unicon +++ /dev/null @@ -1,6 +0,0 @@ -link matrix -procedure main(argv) - if not (integer(argv[1]) > 0) then stop("Argument must be a positive integer.") - matrix1 := identity_matrix(argv[1], argv[1]) - write_matrix(&output,matrix1) -end diff --git a/Task/Identity-matrix/ZX-Spectrum-Basic/identity-matrix.zx b/Task/Identity-matrix/ZX-Spectrum-Basic/identity-matrix.zx new file mode 100644 index 0000000000..6abdf1373f --- /dev/null +++ b/Task/Identity-matrix/ZX-Spectrum-Basic/identity-matrix.zx @@ -0,0 +1,16 @@ +10 INPUT "Matrix size: ";size +20 GO SUB 200: REM Identity matrix +30 FOR r=1 TO size +40 FOR c=1 TO size +50 LET s$=CHR$ 13 +60 IF c`(`<,>`(Statistics:-Sample(Uniform(0, 1), [1000, 2])), LinearAlgebra:-RandomVector(1000, generator = rand(0 .. 2)))); + +f := plots:-pointplot(data[NULL .. NULL, 1], data[NULL .. NULL, 2], symbolsize = 20, symbol = solidbox, colorscheme = ["valuesplit", data[NULL .. NULL, 3], [0 = "Black", 1 = "White", 2 = "Grey"]], axes = none); +DocumentTools:-SetProperty('Plot0', 'value', plots:-display(f,plots:-textplot([0.5,0.5,sprintf("FPS: %a", (a/(time[real]()-t)))],color=red)), refresh=true); + +end do: diff --git a/Task/Include-a-file/BaCon/include-a-file-1.bacon b/Task/Include-a-file/BaCon/include-a-file-1.bacon new file mode 100644 index 0000000000..c06e048b73 --- /dev/null +++ b/Task/Include-a-file/BaCon/include-a-file-1.bacon @@ -0,0 +1 @@ +other = 42 diff --git a/Task/Include-a-file/BaCon/include-a-file-2.bacon b/Task/Include-a-file/BaCon/include-a-file-2.bacon new file mode 100644 index 0000000000..2cdd7e84dd --- /dev/null +++ b/Task/Include-a-file/BaCon/include-a-file-2.bacon @@ -0,0 +1,3 @@ +' Include a file +INCLUDE "other.bac" +PRINT other diff --git a/Task/Include-a-file/Factor/include-a-file.factor b/Task/Include-a-file/Factor/include-a-file.factor new file mode 100644 index 0000000000..b1dfee5c41 --- /dev/null +++ b/Task/Include-a-file/Factor/include-a-file.factor @@ -0,0 +1 @@ +USING: vocaba vocabb... ; diff --git a/Task/Include-a-file/Gambas/include-a-file.gambas b/Task/Include-a-file/Gambas/include-a-file.gambas new file mode 100644 index 0000000000..7b5b5ca9d8 --- /dev/null +++ b/Task/Include-a-file/Gambas/include-a-file.gambas @@ -0,0 +1,6 @@ +Public Sub Form_Open() +Dim sFile As String + +sFile = File.Load("FileToLoad") + +End diff --git a/Task/Include-a-file/IWBASIC/include-a-file-1.iwbasic b/Task/Include-a-file/IWBASIC/include-a-file-1.iwbasic new file mode 100644 index 0000000000..73b8c8d641 --- /dev/null +++ b/Task/Include-a-file/IWBASIC/include-a-file-1.iwbasic @@ -0,0 +1 @@ +$INCLUDE "ishelllink.inc" diff --git a/Task/Include-a-file/IWBASIC/include-a-file-2.iwbasic b/Task/Include-a-file/IWBASIC/include-a-file-2.iwbasic new file mode 100644 index 0000000000..65c1f91941 --- /dev/null +++ b/Task/Include-a-file/IWBASIC/include-a-file-2.iwbasic @@ -0,0 +1 @@ +$USE "libraries\\mylib.lib" diff --git a/Task/Include-a-file/IWBASIC/include-a-file-3.iwbasic b/Task/Include-a-file/IWBASIC/include-a-file-3.iwbasic new file mode 100644 index 0000000000..21395f9107 --- /dev/null +++ b/Task/Include-a-file/IWBASIC/include-a-file-3.iwbasic @@ -0,0 +1 @@ +Success=LOADRESOURCE(ID,Type,Variable) diff --git a/Task/Include-a-file/IWBASIC/include-a-file-4.iwbasic b/Task/Include-a-file/IWBASIC/include-a-file-4.iwbasic new file mode 100644 index 0000000000..7c44445539 --- /dev/null +++ b/Task/Include-a-file/IWBASIC/include-a-file-4.iwbasic @@ -0,0 +1,12 @@ +@RESCURSOR +@RESBITMAP +@RESICON +@RESMENU +@RESDIALOG +@RESSTRING +@RESACCEL +@RESDATA +@RESMESSAGETABLE +@RESGROUPCURSOR +@RESGROUPICON +@RESVERSION diff --git a/Task/Include-a-file/jq/include-a-file-1.jq b/Task/Include-a-file/Jq/include-a-file-1.jq similarity index 100% rename from Task/Include-a-file/jq/include-a-file-1.jq rename to Task/Include-a-file/Jq/include-a-file-1.jq diff --git a/Task/Include-a-file/jq/include-a-file-2.jq b/Task/Include-a-file/Jq/include-a-file-2.jq similarity index 100% rename from Task/Include-a-file/jq/include-a-file-2.jq rename to Task/Include-a-file/Jq/include-a-file-2.jq diff --git a/Task/Include-a-file/jq/include-a-file-3.jq b/Task/Include-a-file/Jq/include-a-file-3.jq similarity index 100% rename from Task/Include-a-file/jq/include-a-file-3.jq rename to Task/Include-a-file/Jq/include-a-file-3.jq diff --git a/Task/Include-a-file/Kotlin/include-a-file-1.kotlin b/Task/Include-a-file/Kotlin/include-a-file-1.kotlin new file mode 100644 index 0000000000..7341f3f43e --- /dev/null +++ b/Task/Include-a-file/Kotlin/include-a-file-1.kotlin @@ -0,0 +1 @@ +fun f() = println("f called") diff --git a/Task/Include-a-file/Kotlin/include-a-file-2.kotlin b/Task/Include-a-file/Kotlin/include-a-file-2.kotlin new file mode 100644 index 0000000000..12124dcbe4 --- /dev/null +++ b/Task/Include-a-file/Kotlin/include-a-file-2.kotlin @@ -0,0 +1,7 @@ +// version 1.1.2 + +import package1.f // import f from package `package1` + +fun main(args: Array) { + f() // invoke f without qualification +} diff --git a/Task/Include-a-file/M4/include-a-file.m4 b/Task/Include-a-file/M4/include-a-file.m4 new file mode 100644 index 0000000000..2b7933c3f1 --- /dev/null +++ b/Task/Include-a-file/M4/include-a-file.m4 @@ -0,0 +1 @@ +include(filename) diff --git a/Task/Include-a-file/OoRexx/include-a-file.rexx b/Task/Include-a-file/OoRexx/include-a-file.rexx new file mode 100644 index 0000000000..6f9f656cc8 --- /dev/null +++ b/Task/Include-a-file/OoRexx/include-a-file.rexx @@ -0,0 +1 @@ + ::requires "regex.cls" diff --git a/Task/Include-a-file/SPL/include-a-file.spl b/Task/Include-a-file/SPL/include-a-file.spl new file mode 100644 index 0000000000..1a922b6635 --- /dev/null +++ b/Task/Include-a-file/SPL/include-a-file.spl @@ -0,0 +1 @@ +$include.txt diff --git a/Task/Include-a-file/VBScript/include-a-file-1.vb b/Task/Include-a-file/VBScript/include-a-file-1.vb new file mode 100644 index 0000000000..ae8f323194 --- /dev/null +++ b/Task/Include-a-file/VBScript/include-a-file-1.vb @@ -0,0 +1,8 @@ +Include "D:\include\pad.vbs" + +Wscript.Echo lpad(12,14,"-") + +Sub Include (file) + dim fso: set fso = CreateObject("Scripting.FileSystemObject") + if fso.FileExists(file) then ExecuteGlobal fso.OpenTextFile(file).ReadAll +End Sub diff --git a/Task/Include-a-file/VBScript/include-a-file-2.vb b/Task/Include-a-file/VBScript/include-a-file-2.vb new file mode 100644 index 0000000000..bb23fb4a1d --- /dev/null +++ b/Task/Include-a-file/VBScript/include-a-file-2.vb @@ -0,0 +1 @@ + - +var mandelIter; +fetch("./mandelIter.wasm") + .then(res => { + if (res.ok) return res.arrayBuffer(); + throw new Error('Unable to fetch WASM.'); + }) + .then(bytes => { return WebAssembly.compile(bytes); }) + .then(module => { return WebAssembly.instantiate(module); }) + .then(instance => { WebAssembly.instance = instance; draw(); }) - -

    Mandelbrot set

    +function mandelbrot(canvas, xmin, xmax, ymin, ymax, iterations) { + // ... + var i = WebAssembly.instance.exports.mandelIter(x, y, iterations); + // ... +} -
    - - - - - - - - - - - - - -
    xmin =xmax =
    ymin =ymax =
    -

    iterations = -

    -

    - - -

    -
    - - - This page needs a browser with canvas support. - - - +function draw() { + // canvas initialization if necessary + // ... + mandelbrot(canvas, -2, 1, -1, 1, 1000); + // ... +} diff --git a/Task/Mandelbrot-set/JavaScript/mandelbrot-set.js b/Task/Mandelbrot-set/JavaScript/mandelbrot-set.js deleted file mode 100644 index 738a6a6047..0000000000 --- a/Task/Mandelbrot-set/JavaScript/mandelbrot-set.js +++ /dev/null @@ -1,69 +0,0 @@ -function mandelIter(cx, cy, maxIter) { - var x = 0.0; - var y = 0.0; - var xx = 0; - var yy = 0; - var xy = 0; - - var i = maxIter; - while (i-- && xx + yy <= 4) { - xy = x * y; - xx = x * x; - yy = y * y; - x = xx - yy + cx; - y = xy + xy + cy; - } - return maxIter - i; -} - -function mandelbrot(canvas, xmin, xmax, ymin, ymax, iterations) { - var width = canvas.width; - var height = canvas.height; - - var ctx = canvas.getContext('2d'); - var img = ctx.getImageData(0, 0, width, height); - var pix = img.data; - - for (var ix = 0; ix < width; ++ix) { - for (var iy = 0; iy < height; ++iy) { - var x = xmin + (xmax - xmin) * ix / (width - 1); - var y = ymin + (ymax - ymin) * iy / (height - 1); - var i = mandelIter(x, y, iterations); - var ppos = 4 * (width * iy + ix); - - if (i > iterations) { - pix[ppos] = 0; - pix[ppos + 1] = 0; - pix[ppos + 2] = 0; - } else { - var c = 3 * Math.log(i) / Math.log(iterations - 1.0); - - if (c < 1) { - pix[ppos] = 255 * c; - pix[ppos + 1] = 0; - pix[ppos + 2] = 0; - } - else if ( c < 2 ) { - pix[ppos] = 255; - pix[ppos + 1] = 255 * (c - 1); - pix[ppos + 2] = 0; - } else { - pix[ppos] = 255; - pix[ppos + 1] = 255; - pix[ppos + 2] = 255 * (c - 2); - } - } - pix[ppos + 3] = 255; - } - } - - ctx.putImageData(img, 0, 0); -} - -var canvas = document.createElement('canvas'); -canvas.width = 900; -canvas.height = 600; - -document.body.insertBefore(canvas, document.body.childNodes[0]); - -mandelbrot(canvas, -2, 1, -1, 1, 1000); diff --git a/Task/Mandelbrot-set/jq/mandelbrot-set-1.jq b/Task/Mandelbrot-set/Jq/mandelbrot-set-1.jq similarity index 100% rename from Task/Mandelbrot-set/jq/mandelbrot-set-1.jq rename to Task/Mandelbrot-set/Jq/mandelbrot-set-1.jq diff --git a/Task/Mandelbrot-set/jq/mandelbrot-set-2.jq b/Task/Mandelbrot-set/Jq/mandelbrot-set-2.jq similarity index 100% rename from Task/Mandelbrot-set/jq/mandelbrot-set-2.jq rename to Task/Mandelbrot-set/Jq/mandelbrot-set-2.jq diff --git a/Task/Mandelbrot-set/jq/mandelbrot-set-3.jq b/Task/Mandelbrot-set/Jq/mandelbrot-set-3.jq similarity index 100% rename from Task/Mandelbrot-set/jq/mandelbrot-set-3.jq rename to Task/Mandelbrot-set/Jq/mandelbrot-set-3.jq diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-1.julia similarity index 100% rename from Task/Mandelbrot-set/Julia/mandelbrot-set.julia rename to Task/Mandelbrot-set/Julia/mandelbrot-set-1.julia diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-2.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-2.julia new file mode 100644 index 0000000000..b9cbbcdfe0 --- /dev/null +++ b/Task/Mandelbrot-set/Julia/mandelbrot-set-2.julia @@ -0,0 +1,56 @@ +using Images + +@inline function hsv2rgb(h, s, v) + const c = v * s + const x = c * (1 - abs(((h/60) % 2) - 1)) + const m = v - c + + const r,g,b = + if h < 60 + (c, x, 0) + elseif h < 120 + (x, c, 0) + elseif h < 180 + (0, c, x) + elseif h < 240 + (0, x, c) + elseif h < 300 + (x, 0, c) + else + (c, 0, x) + end + + (r + m), (b + m), (g + m) +end + +function mandelbrot() + + const w, h = 1000, 1000 + + const zoom = 0.5 + const moveX = 0 + const moveY = 0 + + const img = Array{RGB{Float64}}(h, w) + const maxIter = 30 + + for x in 1:w + for y in 1:h + i = maxIter + const c = Complex( + (2*x - w) / (w * zoom) + moveX, + (2*y - h) / (h * zoom) + moveY + ) + z = c + while abs(z) < 2 && (i -= 1) > 0 + z = z^2 + c + end + const r,g,b = hsv2rgb(i / maxIter * 360, 1, i / maxIter) + img[y,x] = RGB{Float64}(r, g, b) + end + end + + save("mandelbrot_set.png", img) +end + +mandelbrot() diff --git a/Task/Mandelbrot-set/Kotlin/mandelbrot-set.kotlin b/Task/Mandelbrot-set/Kotlin/mandelbrot-set.kotlin new file mode 100644 index 0000000000..3a0e19ccc3 --- /dev/null +++ b/Task/Mandelbrot-set/Kotlin/mandelbrot-set.kotlin @@ -0,0 +1,45 @@ +// version 1.1.2 + +import java.awt.Graphics +import java.awt.image.BufferedImage +import javax.swing.JFrame + +class Mandelbrot: JFrame("Mandelbrot Set") { + companion object { + private const val MAX_ITER = 570 + private const val ZOOM = 150.0 + } + + private val img: BufferedImage + + init { + setBounds(100, 100, 800, 600) + isResizable = false + defaultCloseOperation = EXIT_ON_CLOSE + img = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) + for (y in 0 until height) { + for (x in 0 until width) { + var zx = 0.0 + var zy = 0.0 + val cX = (x - 400) / ZOOM + val cY = (y - 300) / ZOOM + var iter = MAX_ITER + while (zx * zx + zy * zy < 4.0 && iter > 0) { + val tmp = zx * zx - zy * zy + cX + zy = 2.0 * zx * zy + cY + zx = tmp + iter-- + } + img.setRGB(x, y, iter or (iter shl 7)) + } + } + } + + override fun paint(g: Graphics) { + g.drawImage(img, 0, 0, this) + } +} + +fun main(args: Array) { + Mandelbrot().isVisible = true +} diff --git a/Task/Mandelbrot-set/Liberty-BASIC/mandelbrot-set.liberty b/Task/Mandelbrot-set/Liberty-BASIC/mandelbrot-set.liberty deleted file mode 100644 index c8cd216008..0000000000 --- a/Task/Mandelbrot-set/Liberty-BASIC/mandelbrot-set.liberty +++ /dev/null @@ -1,55 +0,0 @@ -nomainwin - -WindowWidth =440 -WindowHeight =460 - -open "Mandelbrot Set" for graphics_nsb_nf as #w - -#w "trapclose [quit]" -#w "down" - -for x0 = -2 to 1 step .0033 - for y0 = -1.5 to 1.5 step .0075 - x = 0 - y = 0 - - iteration = 0 - maxIteration = 255 - - while ( ( x *x +y *y) <=4) and ( iteration maxIteration then - c =iteration - else - c =0 - end if - - call pSet x0, y0, c - scan - next -next - -#w "flush" - -wait - -sub pSet x, y, c - xScreen = 10 +( x +2) /3 *400 - yScreen = 10 +( y +1.5) /3 *400 - if c =0 then - col$ ="red" - else - if c mod 2 =1 then col$ ="lightgray" else col$ ="white" - end if - #w "color "; col$ - #w "set "; xScreen; " "; yScreen -end sub - -[quit] -close #w -end diff --git a/Task/Mandelbrot-set/Lua/mandelbrot-set.lua b/Task/Mandelbrot-set/Lua/mandelbrot-set.lua new file mode 100644 index 0000000000..11db525ca3 --- /dev/null +++ b/Task/Mandelbrot-set/Lua/mandelbrot-set.lua @@ -0,0 +1,68 @@ +local maxIterations = 250 +local minX, maxX, minY, maxY = -2.5, 2.5, -2.5, 2.5 +local miX, mxX, miY, mxY +function remap( x, t1, t2, s1, s2 ) + local f = ( x - t1 ) / ( t2 - t1 ) + local g = f * ( s2 - s1 ) + s1 + return g; +end +function drawMandelbrot() + local pts, a, as, za, b, bs, zb, cnt, clr = {} + for j = 0, hei - 1 do + for i = 0, wid - 1 do + a = remap( i, 0, wid, minX, maxX ) + b = remap( j, 0, hei, minY, maxY ) + cnt = 0; za = a; zb = b + while( cnt < maxIterations ) do + as = a * a - b * b; bs = 2 * a * b + a = za + as; b = zb + bs + if math.abs( a ) + math.abs( b ) > 16 then break end + cnt = cnt + 1 + end + if cnt == maxIterations then clr = 0 + else clr = remap( cnt, 0, maxIterations, 0, 255 ) + end + pts[1] = { i, j, clr, clr, 0, 255 } + love.graphics.points( pts ) + end + end +end +function startFractal() + love.graphics.setCanvas( canvas ); love.graphics.clear() + love.graphics.setColor( 255, 255, 255 ) + drawMandelbrot(); love.graphics.setCanvas() +end +function love.load() + wid, hei = love.graphics.getWidth(), love.graphics.getHeight() + canvas = love.graphics.newCanvas( wid, hei ) + startFractal() +end +function love.mousepressed( x, y, button, istouch ) + if button == 1 then + startDrag = true; miX = x; miY = y + else + minX = -2.5; maxX = 2.5; minY = minX; maxY = maxX + startFractal() + startDrag = false + end +end +function love.mousereleased( x, y, button, istouch ) + if startDrag then + local l + if x > miX then mxX = x + else l = x; mxX = miX; miX = l + end + if y > miY then mxY = y + else l = y; mxY = miY; miY = l + end + miX = remap( miX, 0, wid, minX, maxX ) + mxX = remap( mxX, 0, wid, minX, maxX ) + miY = remap( miY, 0, hei, minY, maxY ) + mxY = remap( mxY, 0, hei, minY, maxY ) + minX = miX; maxX = mxX; minY = miY; maxY = mxY + startFractal() + end +end +function love.draw() + love.graphics.draw( canvas ) +end diff --git a/Task/Mandelbrot-set/Nim/mandelbrot-set.nim b/Task/Mandelbrot-set/Nim/mandelbrot-set.nim index 2a86b231cc..4e8ea3792b 100644 --- a/Task/Mandelbrot-set/Nim/mandelbrot-set.nim +++ b/Task/Mandelbrot-set/Nim/mandelbrot-set.nim @@ -1,10 +1,10 @@ import complex -proc mandelbrot(a): Complex = +proc mandelbrot(a: Complex): Complex = for i in 0 .. <50: result = result * result + a -iterator stepIt(start, step, iterations) = +iterator stepIt(start, step: float, iterations: int): auto = for i in 0 .. iterations: yield start + float(i) * step diff --git a/Task/Mandelbrot-set/PARI-GP/mandelbrot-set.pari b/Task/Mandelbrot-set/PARI-GP/mandelbrot-set.pari new file mode 100644 index 0000000000..1ac3bf4bbb --- /dev/null +++ b/Task/Mandelbrot-set/PARI-GP/mandelbrot-set.pari @@ -0,0 +1,7 @@ +mandelbrot() = +{ + forstep(y=-1, 1, 0.05, + forstep(x=-2, 0.5, 0.0315, + print1(((c)->my(z=c);for(i=1,20,z=z*z+c;if(abs(z)>2,return(" ")));"#")(x+y*I))); + print()); +} diff --git a/Task/Mandelbrot-set/SPL/mandelbrot-set.spl b/Task/Mandelbrot-set/SPL/mandelbrot-set.spl new file mode 100644 index 0000000000..6eab1fe36a --- /dev/null +++ b/Task/Mandelbrot-set/SPL/mandelbrot-set.spl @@ -0,0 +1,18 @@ +w,h = #.scrsize() +sfx = -2.5; sfy = -2*h/w; fs = 4/w +#.aaoff() +> y, 1...h + > x, 1...w + fx = sfx + x*fs; fy = sfy + y*fs + #.drawpoint(x,y,color(fx,fy):3) + < +< +color(x,y)= + zr = x; zi = y; n = 0; maxn = 150 + > zr*zr+zi*zi<4 & n 2 && return true; - } * 20; - return false; + var c = z + { z = (z*z + c) + z.abs > 2 && return true + } * 20 + return false } - -1 ^.. (-1, 0.05) -> each { |y| - -2 ..^ (0.5, 0.0315) -> each { |x| - print(mandelbrot(y.i + x) ? ' ' : '#'); +  +for y range(1, -1, -0.05) { + for x in range(-2, 0.5, 0.0315) { + print(mandelbrot(x + y.i) ? ' ' : '#') } - print "\n"; + print "\n" } diff --git a/Task/Mandelbrot-set/Zkl/mandelbrot-set.zkl b/Task/Mandelbrot-set/Zkl/mandelbrot-set.zkl new file mode 100644 index 0000000000..53b4c59b8a --- /dev/null +++ b/Task/Mandelbrot-set/Zkl/mandelbrot-set.zkl @@ -0,0 +1,20 @@ +fcn mandelbrot{ // lord this is slooooow + bitmap:=PPM(640,480); + foreach y,x in ([0..479],[0..639]){ + cx:=(x.toFloat()/640 - 0.5)*4.0; //range: -2.0 to +2.0 + cy:=((y-240).toFloat()/240.0)*1.5; //range: -1.5 to +1.5 + cnt:=0; zx:=0.0; zy:=0.0; + do(1000){ + if(zx*zx + zy*zy > 2.0){ //z heads toward infinity + //set color of pixel to rate it approaches infinity + bitmap[x,y]=cnt.shiftLeft(21) + cnt.shiftLeft(10) + cnt*8; + break; + } + temp:=zx*zy; + zx=zx*zx - zy*zy + cx; //calculate next iteration of z + zy=2.0*temp + cy; + cnt+=1; + } + } + bitmap.write(File("foo.ppm","wb")); +}(); diff --git a/Task/Map-range/Axiom/map-range-3.axiom b/Task/Map-range/Axiom/map-range-3.axiom deleted file mode 100644 index 566481936c..0000000000 --- a/Task/Map-range/Axiom/map-range-3.axiom +++ /dev/null @@ -1,7 +0,0 @@ - b + 8a 2b + 7a b + 2a 4b + 5a 5b + 4a - [(1,a), (2,------), (3,-------), (4,------), (5,-------), (6,-------), - 9 9 3 9 9 - 2b + a 7b + 2a 8b + a - (7,------), (8,-------), (9,------), (10,b)] - 3 9 9 - Type: List(Tuple(Fraction(Polynomial(Integer)))) diff --git a/Task/Map-range/BBC-BASIC/map-range.bbc b/Task/Map-range/BASIC/map-range-1.basic similarity index 100% rename from Task/Map-range/BBC-BASIC/map-range.bbc rename to Task/Map-range/BASIC/map-range-1.basic diff --git a/Task/Map-range/BASIC/map-range-2.basic b/Task/Map-range/BASIC/map-range-2.basic new file mode 100644 index 0000000000..d864d11a9a --- /dev/null +++ b/Task/Map-range/BASIC/map-range-2.basic @@ -0,0 +1,9 @@ +10 REM MAP RANGE +20 REM COMMODORE BASIC 2.0 +30 REM ================================ +40 A1 = 0 : A2 = 10 +50 B1 = -1 : B2 = 0 +60 DEF FN MR(S)=B1+(S-A1)*(B2-B1)/(A2-A1) +70 FOR S=0 TO 10 +80 PRINT S;"MAPS TO ";FN MR(S) +90 NEXT diff --git a/Task/Map-range/Bc/map-range.bc b/Task/Map-range/Bc/map-range.bc new file mode 100644 index 0000000000..c0d37174ac --- /dev/null +++ b/Task/Map-range/Bc/map-range.bc @@ -0,0 +1,16 @@ +/* map s from [a, b] to [c, d] */ +define m(a, b, c, d, s) { + return (c + (s - a) * (d - c) / (b - a)) +} + +scale = 6 /* division to 6 decimal places */ +"[0, 10] => [-1, 0] +" +for (i = 0; i <= 10; i += 2) { + /* + * If your bc(1) has a print statement, you can try + * print i, " => ", m(0, 10, -1, 0, i), "\n" + */ + i; " => "; m(0, 10, -1, 0, i) +} +quit diff --git a/Task/Map-range/C/map-range-1.c b/Task/Map-range/C/map-range-1.c deleted file mode 100644 index 70d23f80cf..0000000000 --- a/Task/Map-range/C/map-range-1.c +++ /dev/null @@ -1,19 +0,0 @@ -#include - -double mapRange(double a1,double a2,double b1,double b2,double s) -{ - return b1 + (s-a1)*(b2-b1)/(a2-a1); -} - -int main() -{ - int i; - puts("Mapping [0,10] to [-1,0] at intervals of 1:"); - - for(i=0;i<=10;i++) - { - printf("f(%d) = %g\n",i,mapRange(0,10,-1,0,i)); - } - - return 0; -} diff --git a/Task/Map-range/C/map-range-2.c b/Task/Map-range/C/map-range-2.c deleted file mode 100644 index 7fd3989a65..0000000000 --- a/Task/Map-range/C/map-range-2.c +++ /dev/null @@ -1,12 +0,0 @@ -Mapping [0,10] to [-1,0] at intervals of 1: -f(0) = -1 -f(1) = -0.9 -f(2) = -0.8 -f(3) = -0.7 -f(4) = -0.6 -f(5) = -0.5 -f(6) = -0.4 -f(7) = -0.3 -f(8) = -0.2 -f(9) = -0.1 -f(10) = 0 diff --git a/Task/Map-range/Haskell/map-range.hs b/Task/Map-range/Haskell/map-range.hs index a1541716bd..cc99f14992 100644 --- a/Task/Map-range/Haskell/map-range.hs +++ b/Task/Map-range/Haskell/map-range.hs @@ -1,21 +1,28 @@ import Data.Ratio -import Text.Printf +import Text.Printf (PrintfType, printf) -- Map a value from the range [a1,a2] to the range [b1,b2]. We don't check -- for empty ranges. -mapRange :: (Fractional a) => (a, a) -> (a, a) -> a -> a -mapRange (a1,a2) (b1,b2) s = b1+(s-a1)*(b2-b1)/(a2-a1) +mapRange + :: Fractional a + => (a, a) -> (a, a) -> a -> a +mapRange (a1, a2) (b1, b2) s = b1 + (s - a1) * (b2 - b1) / (a2 - a1) -main = do - -- Perform the mapping over floating point numbers. +main :: IO () +main +-- Perform the mapping over floating point numbers. + = do putStrLn "---------- Floating point ----------" - mapM_ (\n -> prtD n . mapRange (0,10) (-1,0) $ fromIntegral n) [0..10] - + mapM_ (\n -> prtD n . mapRange (0, 10) (-1, 0) $ fromIntegral n) [0 .. 10] -- Perform the same mapping over exact rationals. putStrLn "---------- Rationals ----------" - mapM_ (\n -> prtR n . mapRange (0,10) (-1,0) $ n%1) [0..10] - - where prtD :: PrintfType r => Integer -> Double -> r - prtD n x = printf "%2d -> %6.3f\n" n x - prtR :: PrintfType r => Integer -> Rational -> r - prtR n x = printf "%2d -> %s\n" n (show x) + mapM_ (\n -> prtR n . mapRange (0, 10) (-1, 0) $ n % 1) [0 .. 10] + where + prtD + :: PrintfType r + => Integer -> Double -> r + prtD = printf "%2d -> %6.3f\n" + prtR + :: PrintfType r + => Integer -> Rational -> r + prtR n x = printf "%2d -> %s\n" n (show x) diff --git a/Task/Map-range/jq/map-range-1.jq b/Task/Map-range/Jq/map-range-1.jq similarity index 100% rename from Task/Map-range/jq/map-range-1.jq rename to Task/Map-range/Jq/map-range-1.jq diff --git a/Task/Map-range/jq/map-range-2.jq b/Task/Map-range/Jq/map-range-2.jq similarity index 100% rename from Task/Map-range/jq/map-range-2.jq rename to Task/Map-range/Jq/map-range-2.jq diff --git a/Task/Map-range/jq/map-range-3.jq b/Task/Map-range/Jq/map-range-3.jq similarity index 100% rename from Task/Map-range/jq/map-range-3.jq rename to Task/Map-range/Jq/map-range-3.jq diff --git a/Task/Map-range/Kotlin/map-range.kotlin b/Task/Map-range/Kotlin/map-range.kotlin new file mode 100644 index 0000000000..e2396133d8 --- /dev/null +++ b/Task/Map-range/Kotlin/map-range.kotlin @@ -0,0 +1,16 @@ +// version 1.0.6 + +class FloatRange(override val start: Float, override val endInclusive: Float) : ClosedRange + +fun mapRange(range1: FloatRange, range2: FloatRange, value: Float): Float { + if (value !in range1) throw IllegalArgumentException("value is not within the first range") + if (range1.endInclusive == range1.start) throw IllegalArgumentException("first range cannot be single-valued") + return range2.start + (value - range1.start) * (range2.endInclusive - range2.start) / (range1.endInclusive - range1.start) +} + +fun main(args: Array) { + for (i in 0..10) { + val mappedValue = mapRange(FloatRange(0.0f, 10.0f), FloatRange(-1.0f, 0.0f), i.toFloat()) + println(String.format("%2d maps to %+4.2f", i, mappedValue)) + } +} diff --git a/Task/Map-range/PowerShell/map-range-1.psh b/Task/Map-range/PowerShell/map-range-1.psh new file mode 100644 index 0000000000..a96b79ae12 --- /dev/null +++ b/Task/Map-range/PowerShell/map-range-1.psh @@ -0,0 +1,36 @@ +function Group-Range +{ + [CmdletBinding()] + [OutputType([PSCustomObject])] + Param + ( + [Parameter(Mandatory=$true, + Position=0)] + [ValidateCount(2,2)] + [double[]] + $Range1, + + [Parameter(Mandatory=$true, + Position=1)] + [ValidateCount(2,2)] + [double[]] + $Range2, + + [Parameter(Mandatory=$true, + ValueFromPipeline=$true, + Position=2)] + [double] + $Map + ) + + Process + { + foreach ($number in $Map) + { + [PSCustomObject]@{ + Index = $number + Mapping = $Range2[0] + ($number - $Range1[0]) * ($Range2[0] - $Range2[1]) / ($Range1[0] - $Range1[1]) + } + } + } +} diff --git a/Task/Map-range/PowerShell/map-range-2.psh b/Task/Map-range/PowerShell/map-range-2.psh new file mode 100644 index 0000000000..9163b25ed6 --- /dev/null +++ b/Task/Map-range/PowerShell/map-range-2.psh @@ -0,0 +1 @@ +0..10 | Group-Range (0,10) (-1,0) diff --git a/Task/Map-range/REXX/map-range-4.rexx b/Task/Map-range/REXX/map-range-4.rexx index 90266d33b7..3406abb3ef 100644 --- a/Task/Map-range/REXX/map-range-4.rexx +++ b/Task/Map-range/REXX/map-range-4.rexx @@ -1,5 +1,5 @@ /*REXX program maps a number from one range to another range. */ -/* 31.10.2013 Walter Pachl +/* 31.10.2013 Walter Pachl */ /* 'translated' from version 1 without using Procedure */ do j=0 to 10 say right(j,3) ' maps to ' mapRange(0,10,-1,0,j) diff --git a/Task/Map-range/Ring/map-range.ring b/Task/Map-range/Ring/map-range.ring new file mode 100644 index 0000000000..59ea9128ea --- /dev/null +++ b/Task/Map-range/Ring/map-range.ring @@ -0,0 +1,15 @@ +# Project : Map range +# Date : 2017/09/20 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +al = 0 +ah = 10 +bl = -1 +bh = 0 +for n = 0 to 10 + see " maps to " + maprange(al, bl, n) + nl +next + +func maprange(al, bl, s) + return bl + (s - al) * (bh - bl) / (ah - al) diff --git a/Task/Map-range/Zkl/map-range.zkl b/Task/Map-range/Zkl/map-range.zkl new file mode 100644 index 0000000000..870ab0c830 --- /dev/null +++ b/Task/Map-range/Zkl/map-range.zkl @@ -0,0 +1,7 @@ +fcn mapRange([(a1,a2)], [(b1,b2)], s) // a1a2 is List(a1,a2) + { b1 + ((s - a1) * (b2 - b1) / (a2 - a1)) } + +r1:=T(0.0, 10.0); r2:=T(-1.0, 0.0); +foreach s in ([0.0 .. 10]){ + "%2d maps to %5.2f".fmt(s,mapRange(r1,r2, s)).println(); +} diff --git a/Task/Matrix-arithmetic/Forth/matrix-arithmetic.fth b/Task/Matrix-arithmetic/Forth/matrix-arithmetic.fth new file mode 100644 index 0000000000..8240d0a20b --- /dev/null +++ b/Task/Matrix-arithmetic/Forth/matrix-arithmetic.fth @@ -0,0 +1,38 @@ +S" fsl-util.fs" REQUIRED +S" fsl/dynmem.seq" REQUIRED +[UNDEFINED] defines [IF] SYNONYM defines IS [THEN] +S" fsl/structs.seq" REQUIRED +S" fsl/lufact.seq" REQUIRED +S" fsl/dets.seq" REQUIRED +S" permute.fs" REQUIRED + +VARIABLE the-mat +: add-perm ( p0 p1 p2 ... pn n s -- ) + DROP \ sign + 1E + 1 DO + the-mat @ SWAP 1- I 1- }} F@ F* + LOOP + DROP \ Dummy element because we're using 1-based indexing + F+ ; +: permanent ( len mat -- ) ( F: -- perm ) + the-mat ! + 0E + ['] add-perm perms ; + +3 SET-PRECISION +2 2 float matrix m2{{ +1e 2e 3e 4e 2 2 m2{{ }}fput +lumatrix lmat +3 3 float matrix m3{{ +2e 9e 4e 7e 5e 3e 6e 1e 8e 3 3 m3{{ }}fput + +lmat 2 lu-malloc +m2{{ lmat lufact +lmat det F. 2 m2{{ permanent F. CR +lmat lu-free + +lmat 3 lu-malloc +m3{{ lmat lufact +lmat det F. 3 m3{{ permanent F. CR +lmat lu-free diff --git a/Task/Matrix-arithmetic/Go/matrix-arithmetic.go b/Task/Matrix-arithmetic/Go/matrix-arithmetic-1.go similarity index 100% rename from Task/Matrix-arithmetic/Go/matrix-arithmetic.go rename to Task/Matrix-arithmetic/Go/matrix-arithmetic-1.go diff --git a/Task/Matrix-arithmetic/Go/matrix-arithmetic-2.go b/Task/Matrix-arithmetic/Go/matrix-arithmetic-2.go new file mode 100644 index 0000000000..85849e206f --- /dev/null +++ b/Task/Matrix-arithmetic/Go/matrix-arithmetic-2.go @@ -0,0 +1,44 @@ +package main + +import "fmt" + +func main() { + fmt.Println(ryser([][]float64{ + {1, 2}, + {3, 4}})) + fmt.Println(ryser([][]float64{ + {2, 9, 4}, + {7, 5, 3}, + {6, 1, 8}})) +} + +func ryser(m [][]float64) (d float64) { + gray := 0 + csum := make([]float64, len(m)) + sgn := float64(len(m)&1<<1 - 1) + n2 := uint32(1) << uint(len(m)) + for i := uint32(1); i < n2; i++ { + r := [...]byte{ + 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, + 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9, + }[i&-i*0x077CB531>>27] + b := 1 << r + if gray&b == 0 { + for c, e := range m[r] { + csum[c] += e + } + } else { + for c, e := range m[r] { + csum[c] -= e + } + } + gray ^= b + p := sgn + for _, e := range csum { + p *= e + } + d += p + sgn = -sgn + } + return +} diff --git a/Task/Matrix-arithmetic/Go/matrix-arithmetic-3.go b/Task/Matrix-arithmetic/Go/matrix-arithmetic-3.go new file mode 100644 index 0000000000..71dca1f5a3 --- /dev/null +++ b/Task/Matrix-arithmetic/Go/matrix-arithmetic-3.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + + "github.com/skelterjohn/go.matrix" +) + +func main() { + fmt.Println(matrix.MakeDenseMatrixStacked([][]float64{ + {1, 2}, + {3, 4}}).Det()) + fmt.Println(matrix.MakeDenseMatrixStacked([][]float64{ + {2, 9, 4}, + {7, 5, 3}, + {6, 1, 8}}).Det()) +} diff --git a/Task/Matrix-arithmetic/Go/matrix-arithmetic-4.go b/Task/Matrix-arithmetic/Go/matrix-arithmetic-4.go new file mode 100644 index 0000000000..5b087d874d --- /dev/null +++ b/Task/Matrix-arithmetic/Go/matrix-arithmetic-4.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + + "github.com/gonum/matrix/mat64" +) + +func main() { + fmt.Println(mat64.Det(mat64.NewDense(2, 2, []float64{ + 1, 2, + 3, 4}))) + fmt.Println(mat64.Det(mat64.NewDense(3, 3, []float64{ + 2, 9, 4, + 7, 5, 3, + 6, 1, 8}))) +} diff --git a/Task/Matrix-arithmetic/Haskell/matrix-arithmetic.hs b/Task/Matrix-arithmetic/Haskell/matrix-arithmetic.hs index d6141874f8..9b4f608225 100644 --- a/Task/Matrix-arithmetic/Haskell/matrix-arithmetic.hs +++ b/Task/Matrix-arithmetic/Haskell/matrix-arithmetic.hs @@ -1,39 +1,59 @@ -s_permutations :: [a] -> [([a], Int)] -s_permutations = flip zip (cycle [1, -1]) . (foldl aux [[]]) - where aux items x = do - (f,item) <- zip (cycle [reverse,id]) items - f (insertEv x item) - insertEv x [] = [[x]] - insertEv x l@(y:ys) = (x:l) : map (y:) (insertEv x ys) +sPermutations :: [a] -> [([a], Int)] +sPermutations = flip zip (cycle [1, -1]) . foldl aux [[]] + where + aux items x = do + (f, item) <- zip (cycle [reverse, id]) items + f (insertEv x item) + insertEv x [] = [[x]] + insertEv x l@(y:ys) = (x : l) : ((y :) <$>) (insertEv x ys) -elemPos::[[a]] -> Int -> Int -> a +elemPos :: [[a]] -> Int -> Int -> a elemPos ms i j = (ms !! i) !! j -prod:: Num a => ([[a]] -> Int -> Int -> a) -> [[a]] -> [Int] -> a -prod f ms = product.zipWith (f ms) [0..] +prod + :: Num a + => ([[a]] -> Int -> Int -> a) -> [[a]] -> [Int] -> a +prod f ms = product . zipWith (f ms) [0 ..] -s_determinant:: Num a => ([[a]] -> Int -> Int -> a) -> [[a]] -> [([Int],Int)] -> a -s_determinant f ms = sum.map (\(is,s) -> fromIntegral s * prod f ms is) +sDeterminant + :: Num a + => ([[a]] -> Int -> Int -> a) -> [[a]] -> [([Int], Int)] -> a +sDeterminant f ms = sum . fmap (\(is, s) -> fromIntegral s * prod f ms is) -determinant:: Num a => [[a]] -> a -determinant ms = s_determinant elemPos ms.s_permutations $ [0..pred.length $ ms] +determinant + :: Num a + => [[a]] -> a +determinant ms = + sDeterminant elemPos ms . sPermutations $ [0 .. pred . length $ ms] -permanent:: Num a => [[a]] -> a -permanent ms = sum.map (prod elemPos ms.fst).s_permutations $ [0..pred.length $ ms] +permanent + :: Num a + => [[a]] -> a +permanent ms = + sum . fmap (prod elemPos ms . fst) . sPermutations $ [0 .. pred . length $ ms] -result ms = do - putStrLn "Matrice:" - mapM_ print ms - putStrLn "Determinant:" - print $ determinant ms - putStrLn "Permanent:" - print $ permanent ms +-- TEST ----------------------------------------------------------------------- +result + :: (Num a, Show a) + => [[a]] -> String +result ms = + unlines + [ "Matrix:" + , unlines (show <$> ms) + , "Determinant:" + , show (determinant ms) + , "Permanent:" + , show (permanent ms) + ] -main = do - let m1 = [[5]] - let m2 = [[1,0,0],[0,1,0],[0,0,1]] - let m3 = [[0,0,1],[0,1,0],[1,0,0]] - let m4 = [[4,3],[2,5]] - let m5 = [[2,5],[4,3]] - let m6 = [[4,4],[2,2]] - mapM_ result [m1,m2,m3,m4,m5,m6] +main :: IO () +main = + mapM_ + (putStrLn . result) + [ [[5]] + , [[1, 0, 0], [0, 1, 0], [0, 0, 1]] + , [[0, 0, 1], [0, 1, 0], [1, 0, 0]] + , [[4, 3], [2, 5]] + , [[2, 5], [4, 3]] + , [[4, 4], [2, 2]] + ] diff --git a/Task/Matrix-arithmetic/jq/matrix-arithmetic-1.jq b/Task/Matrix-arithmetic/Jq/matrix-arithmetic-1.jq similarity index 100% rename from Task/Matrix-arithmetic/jq/matrix-arithmetic-1.jq rename to Task/Matrix-arithmetic/Jq/matrix-arithmetic-1.jq diff --git a/Task/Matrix-arithmetic/jq/matrix-arithmetic-2.jq b/Task/Matrix-arithmetic/Jq/matrix-arithmetic-2.jq similarity index 100% rename from Task/Matrix-arithmetic/jq/matrix-arithmetic-2.jq rename to Task/Matrix-arithmetic/Jq/matrix-arithmetic-2.jq diff --git a/Task/Matrix-arithmetic/jq/matrix-arithmetic-3.jq b/Task/Matrix-arithmetic/Jq/matrix-arithmetic-3.jq similarity index 100% rename from Task/Matrix-arithmetic/jq/matrix-arithmetic-3.jq rename to Task/Matrix-arithmetic/Jq/matrix-arithmetic-3.jq diff --git a/Task/Matrix-arithmetic/jq/matrix-arithmetic-4.jq b/Task/Matrix-arithmetic/Jq/matrix-arithmetic-4.jq similarity index 100% rename from Task/Matrix-arithmetic/jq/matrix-arithmetic-4.jq rename to Task/Matrix-arithmetic/Jq/matrix-arithmetic-4.jq diff --git a/Task/Matrix-arithmetic/jq/matrix-arithmetic-5.jq b/Task/Matrix-arithmetic/Jq/matrix-arithmetic-5.jq similarity index 100% rename from Task/Matrix-arithmetic/jq/matrix-arithmetic-5.jq rename to Task/Matrix-arithmetic/Jq/matrix-arithmetic-5.jq diff --git a/Task/Matrix-arithmetic/Kotlin/matrix-arithmetic.kotlin b/Task/Matrix-arithmetic/Kotlin/matrix-arithmetic.kotlin new file mode 100644 index 0000000000..d7d9c446bc --- /dev/null +++ b/Task/Matrix-arithmetic/Kotlin/matrix-arithmetic.kotlin @@ -0,0 +1,87 @@ +// version 1.1.2 + +typealias Matrix = Array + +fun johnsonTrotter(n: Int): Pair, List> { + val p = IntArray(n) { it } // permutation + val q = IntArray(n) { it } // inverse permutation + val d = IntArray(n) { -1 } // direction = 1 or -1 + var sign = 1 + val perms = mutableListOf() + val signs = mutableListOf() + + fun permute(k: Int) { + if (k >= n) { + perms.add(p.copyOf()) + signs.add(sign) + sign *= -1 + return + } + permute(k + 1) + for (i in 0 until k) { + val z = p[q[k] + d[k]] + p[q[k]] = z + p[q[k] + d[k]] = k + q[z] = q[k] + q[k] += d[k] + permute(k + 1) + } + d[k] *= -1 + } + + permute(0) + return perms to signs +} + +fun determinant(m: Matrix): Double { + val (sigmas, signs) = johnsonTrotter(m.size) + var sum = 0.0 + for ((i, sigma) in sigmas.withIndex()) { + var prod = 1.0 + for ((j, s) in sigma.withIndex()) prod *= m[j][s] + sum += signs[i] * prod + } + return sum +} + +fun permanent(m: Matrix) : Double { + val (sigmas, _) = johnsonTrotter(m.size) + var sum = 0.0 + for (sigma in sigmas) { + var prod = 1.0 + for ((i, s) in sigma.withIndex()) prod *= m[i][s] + sum += prod + } + return sum +} + +fun main(args: Array) { + val m1 = arrayOf( + doubleArrayOf(1.0) + ) + + val m2 = arrayOf( + doubleArrayOf(1.0, 2.0), + doubleArrayOf(3.0, 4.0) + ) + + val m3 = arrayOf( + doubleArrayOf(2.0, 9.0, 4.0), + doubleArrayOf(7.0, 5.0, 3.0), + doubleArrayOf(6.0, 1.0, 8.0) + ) + + val m4 = arrayOf( + doubleArrayOf( 1.0, 2.0, 3.0, 4.0), + doubleArrayOf( 4.0, 5.0, 6.0, 7.0), + doubleArrayOf( 7.0, 8.0, 9.0, 10.0), + doubleArrayOf(10.0, 11.0, 12.0, 13.0) + ) + + val matrices = arrayOf(m1, m2, m3, m4) + for (m in matrices) { + println("m${m.size} -> ") + println(" determinant = ${determinant(m)}") + println(" permanent = ${permanent(m)}\n") + } +} diff --git a/Task/Matrix-arithmetic/PARI-GP/matrix-arithmetic-4.pari b/Task/Matrix-arithmetic/PARI-GP/matrix-arithmetic-4.pari new file mode 100644 index 0000000000..8cdde3d76f --- /dev/null +++ b/Task/Matrix-arithmetic/PARI-GP/matrix-arithmetic-4.pari @@ -0,0 +1 @@ +matpermanent(M) diff --git a/Task/Matrix-arithmetic/Phix/matrix-arithmetic.phix b/Task/Matrix-arithmetic/Phix/matrix-arithmetic.phix new file mode 100644 index 0000000000..f287dcccff --- /dev/null +++ b/Task/Matrix-arithmetic/Phix/matrix-arithmetic.phix @@ -0,0 +1,88 @@ +function minor(sequence a, integer x, integer y) +integer l = length(a)-1 +sequence result = repeat(repeat(0,l),l) + for i=1 to l do + for j=1 to l do + result[i][j] = a[i+(i>=x)][j+(j>=y)] + end for + end for + return result +end function + +function det(sequence a) + if length(a)=1 then + return a[1][1] + end if + integer sgn = 1 + integer res = 0 + for i=1 to length(a) do + res += sgn*a[1][i]*det(minor(a,1,i)) + sgn *= -1 + end for + return res +end function + +function perm(sequence a) + if length(a)=1 then + return a[1][1] + end if + integer res = 0 + for i=1 to length(a) do + res += a[1][i]*perm(minor(a,1,i)) + end for + return res +end function + +constant tests = { +{{1, 2}, + {3, 4}}, +--Determinant: -2, permanent: 10 +{{2, 9, 4}, + {7, 5, 3}, + {6, 1, 8}}, +--Determinant: -360, permanent: 900 +{{ 1, 2, 3, 4}, + { 4, 5, 6, 7}, + { 7, 8, 9, 10}, + {10, 11, 12, 13}}, +--Determinant: 0, permanent: 29556 +{{ 0, 1, 2, 3, 4}, + { 5, 6, 7, 8, 9}, + {10, 11, 12, 13, 14}, + {15, 16, 17, 18, 19}, + {20, 21, 22, 23, 24}}, +--Determinant: 0, permanent: 6778800 +{{5}}, +--Determinant: 5, permanent: 5 +{{1,0,0}, + {0,1,0}, + {0,0,1}}, +--Determinant: 1, permanent: 1 +{{0,0,1}, + {0,1,0}, + {1,0,0}}, +--Determinant: -1, Permanent: 1 +{{4,3}, + {2,5}}, +--Determinant: 14, Permanent: 26 +{{2,5}, + {4,3}}, +--Determinant: -14, Permanent: 26 +{{4,4}, + {2,2}}, +--Determinant: 0, Permanent: 16 +{{7, 2, -2, 4}, + {4, 4, 1, 7}, + {11, -8, 9, 10}, + {10, 5, 12, 13}}, +--det: -4319 permanent: 10723 + +{{-2, 2, -3}, + {-1, 1, 3}, + {2 , 0, -1}} +--det: 18 permanent: 10 +} +for i=1 to length(tests) do + sequence ti = tests[i] + ?{det(ti),perm(ti)} +end for diff --git a/Task/Matrix-arithmetic/Simula/matrix-arithmetic.simula b/Task/Matrix-arithmetic/Simula/matrix-arithmetic.simula new file mode 100644 index 0000000000..2ae5bd68ee --- /dev/null +++ b/Task/Matrix-arithmetic/Simula/matrix-arithmetic.simula @@ -0,0 +1,99 @@ +! MATRIX ARITHMETIC ; +BEGIN + + INTEGER PROCEDURE LENGTH(A); REAL ARRAY A; + LENGTH := UPPERBOUND(A, 1) - LOWERBOUND(A, 1) + 1; + + PROCEDURE MINOR(A, X, Y, MAT); REAL ARRAY A, MAT; INTEGER X, Y; + BEGIN + INTEGER I, J, M; M := LENGTH(A) - 1; + FOR I := 1 STEP 1 UNTIL M DO + FOR J := 1 STEP 1 UNTIL M DO + BEGIN + IF I < X AND J < Y THEN + MAT(I, J) := A(I, J) + ELSE IF I >= X AND J < Y THEN + MAT(I, J) := A(I + 1, J) + ELSE IF I < X AND J >= Y THEN + MAT(I, J) := A(I, J + 1) + ELSE ! I > X AND J > Y ; + MAT(I, J) := A(I + 1, J + 1) + END + END MINOR; + + REAL PROCEDURE DET(A); REAL ARRAY A; + BEGIN + INTEGER N; N := LENGTH(A); + IF N = 1 THEN + DET := A(1, 1) + ELSE + BEGIN + INTEGER I, SIGN; + REAL SUM; + SIGN := 1; + FOR I := 1 STEP 1 UNTIL N DO + BEGIN + REAL ARRAY MAT(1:N-1, 1:N-1); + MINOR(A, 1, I, MAT); + SUM := SUM + SIGN * A(1, I) * DET(MAT); + SIGN := SIGN * -1 + END; + DET := SUM + END + END DET; + + REAL PROCEDURE PERM(A); REAL ARRAY A; + BEGIN + INTEGER N; N := LENGTH(A); + IF N = 1 THEN + PERM := A(1, 1) + ELSE + BEGIN + REAL SUM; + INTEGER I; + + FOR I := 1 STEP 1 UNTIL N DO + BEGIN + REAL ARRAY MAT(1:N-1, 1:N-1); + MINOR(A, 1, I, MAT); + SUM := SUM + A(1, I) * PERM(MAT) + END; + PERM := SUM + END + END PERM; + + INTEGER SIZE; + SIZE := ININT; + BEGIN + REAL ARRAY A(1:SIZE, 1:SIZE); + INTEGER I, J; + + FOR I := 1 STEP 1 UNTIL SIZE DO + FOR J := 1 STEP 1 UNTIL SIZE DO + A(I, J) := INREAL; + + OUTTEXT("DETERMINANT ... : "); OUTREAL(DET (A), 10, 20); OUTIMAGE; + OUTTEXT("PERMANENT ..... : "); OUTREAL(PERM(A), 10, 20); OUTIMAGE; + END + + ! NOTE THAT THE FIRST INPUT IS THE SIZE OF THE MATRIX. + ! FOR EXAMPLE: + + COMMENT + ! 2 + ! 1 2 + ! 3 4 + ! DETERMINANT: -2.0 + ! PERMANENT: 10.0 ; + + COMMENT + ! 5 + ! 0 1 2 3 4 + ! 5 6 7 8 9 + ! 10 11 12 13 14 + ! 15 16 17 18 19 + ! 20 21 22 23 24 + ! DETERMINANT: 0.0 + ! PERMANENT: 6778800.0 ; + +END diff --git a/Task/Matrix-arithmetic/Zkl/matrix-arithmetic-1.zkl b/Task/Matrix-arithmetic/Zkl/matrix-arithmetic-1.zkl new file mode 100644 index 0000000000..d85598ef8f --- /dev/null +++ b/Task/Matrix-arithmetic/Zkl/matrix-arithmetic-1.zkl @@ -0,0 +1,11 @@ +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +fcn perm(A){ // should verify A is square + numRows:=A.rows; + Utils.Helpers.permute(numRows.toList()).reduce( // permute(0,1,..numRows) + 'wrap(s,pm){ s + numRows.reduce('wrap(x,i){ x*A[i,pm[i]] },1.0) }, + 0.0) +} +test:=fcn(A){ + println(A.format()); + println("Permanent: %.2f, determinant: %.2f".fmt(perm(A),A.det())); +}; diff --git a/Task/Matrix-arithmetic/Zkl/matrix-arithmetic-2.zkl b/Task/Matrix-arithmetic/Zkl/matrix-arithmetic-2.zkl new file mode 100644 index 0000000000..63ae2ab412 --- /dev/null +++ b/Task/Matrix-arithmetic/Zkl/matrix-arithmetic-2.zkl @@ -0,0 +1,5 @@ +A:=GSL.Matrix(2,2).set(1,2, 3,4); +B:=GSL.Matrix(4,4).set(1,2,3,4, 4,5,6,7, 7,8,9,10, 10,11,12,13); +C:=GSL.Matrix(5,5).set( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12,13,14, + 15,16,17,18,19, 20,21,22,23,24); +T(A,B,C).apply2(test); diff --git a/Task/Matrix-exponentiation-operator/Haskell/matrix-exponentiation-operator.hs b/Task/Matrix-exponentiation-operator/Haskell/matrix-exponentiation-operator.hs index 45093f18e6..5af0dd9963 100644 --- a/Task/Matrix-exponentiation-operator/Haskell/matrix-exponentiation-operator.hs +++ b/Task/Matrix-exponentiation-operator/Haskell/matrix-exponentiation-operator.hs @@ -1,12 +1,32 @@ -import Data.List +import Data.List (transpose) -xs <+> ys = zipWith (+) xs ys -xs <*> ys = sum $ zipWith (*) xs ys +(<+>) + :: Num a + => [a] -> [a] -> [a] +(<+>) = zipWith (+) -newtype Mat a = Mat [[a]] deriving (Eq, Show) +(<*>) + :: Num a + => [a] -> [a] -> a +(<*>) = (sum .) . zipWith (*) -instance Num a => Num (Mat a) where +newtype Mat a = + Mat [[a]] + deriving (Eq, Show) + +instance Num a => + Num (Mat a) where negate (Mat x) = Mat $ map (map negate) x - Mat x + Mat y = Mat $ zipWith (<+>) x y - Mat x * Mat y = Mat [[xs <*> ys | ys <- transpose y] | xs <- x] + Mat x + Mat y = Mat $ zipWith (<+>) x y + Mat x * Mat y = + Mat + [ [ xs Main.<*> ys -- Main prefix to distinguish fron applicative operator + | ys <- transpose y ] + | xs <- x ] + abs = undefined fromInteger _ = undefined -- don't know dimension of the desired matrix + signum = undefined + +-- TEST ---------------------------------------------------------------------- +main :: IO () +main = print $ Mat [[1, 2], [0, 1]] ^ 4 diff --git a/Task/Matrix-exponentiation-operator/jq/matrix-exponentiation-operator-1.jq b/Task/Matrix-exponentiation-operator/Jq/matrix-exponentiation-operator-1.jq similarity index 100% rename from Task/Matrix-exponentiation-operator/jq/matrix-exponentiation-operator-1.jq rename to Task/Matrix-exponentiation-operator/Jq/matrix-exponentiation-operator-1.jq diff --git a/Task/Matrix-exponentiation-operator/jq/matrix-exponentiation-operator-2.jq b/Task/Matrix-exponentiation-operator/Jq/matrix-exponentiation-operator-2.jq similarity index 100% rename from Task/Matrix-exponentiation-operator/jq/matrix-exponentiation-operator-2.jq rename to Task/Matrix-exponentiation-operator/Jq/matrix-exponentiation-operator-2.jq diff --git a/Task/Matrix-exponentiation-operator/jq/matrix-exponentiation-operator-3.jq b/Task/Matrix-exponentiation-operator/Jq/matrix-exponentiation-operator-3.jq similarity index 100% rename from Task/Matrix-exponentiation-operator/jq/matrix-exponentiation-operator-3.jq rename to Task/Matrix-exponentiation-operator/Jq/matrix-exponentiation-operator-3.jq diff --git a/Task/Matrix-exponentiation-operator/jq/matrix-exponentiation-operator-4.jq b/Task/Matrix-exponentiation-operator/Jq/matrix-exponentiation-operator-4.jq similarity index 100% rename from Task/Matrix-exponentiation-operator/jq/matrix-exponentiation-operator-4.jq rename to Task/Matrix-exponentiation-operator/Jq/matrix-exponentiation-operator-4.jq diff --git a/Task/Matrix-exponentiation-operator/Kotlin/matrix-exponentiation-operator.kotlin b/Task/Matrix-exponentiation-operator/Kotlin/matrix-exponentiation-operator.kotlin new file mode 100644 index 0000000000..d11f1dfd94 --- /dev/null +++ b/Task/Matrix-exponentiation-operator/Kotlin/matrix-exponentiation-operator.kotlin @@ -0,0 +1,57 @@ +// version 1.1.3 + +typealias Vector = DoubleArray +typealias Matrix = Array + +operator fun Matrix.times(other: Matrix): Matrix { + val rows1 = this.size + val cols1 = this[0].size + val rows2 = other.size + val cols2 = other[0].size + require(cols1 == rows2) + val result = Matrix(rows1) { Vector(cols2) } + for (i in 0 until rows1) { + for (j in 0 until cols2) { + for (k in 0 until rows2) { + result[i][j] += this[i][k] * other[k][j] + } + } + } + return result +} + +fun identityMatrix(n: Int): Matrix { + require(n >= 1) + val ident = Matrix(n) { Vector(n) } + for (i in 0 until n) ident[i][i] = 1.0 + return ident +} + +infix fun Matrix.pow(n : Int): Matrix { + require (n >= 0 && this.size == this[0].size) + if (n == 0) return identityMatrix(this.size) + if (n == 1) return this + var pow = identityMatrix(this.size) + var base = this + var e = n + while (e > 0) { + if ((e and 1) == 1) pow *= base + e = e shr 1 + base *= base + } + return pow +} + +fun printMatrix(m: Matrix, n: Int) { + println("** Power of $n **") + for (i in 0 until m.size) println(m[i].contentToString()) + println() +} + +fun main(args: Array) { + val m = arrayOf( + doubleArrayOf(3.0, 2.0), + doubleArrayOf(2.0, 1.0) + ) + for (i in 0..10) printMatrix(m pow i, i) +} diff --git a/Task/Matrix-exponentiation-operator/Perl-6/matrix-exponentiation-operator.pl6 b/Task/Matrix-exponentiation-operator/Perl-6/matrix-exponentiation-operator.pl6 index 07ff211f0e..7ae3bb6992 100644 --- a/Task/Matrix-exponentiation-operator/Perl-6/matrix-exponentiation-operator.pl6 +++ b/Task/Matrix-exponentiation-operator/Perl-6/matrix-exponentiation-operator.pl6 @@ -12,23 +12,22 @@ multi infix:<**> (SqMat $m, Int $n is copy where { $_ >= 0 }) { my $tmp = $m; my $out = [for ^$m -> $i { [ for ^$m -> $j { +($i == $j) } ] } ]; loop { - $out = $out * $tmp if $n +& 1; - last unless $n +>= 1; - $tmp = $tmp * $tmp; + $out = $out * $tmp if $n +& 1; + last unless $n +>= 1; + $tmp = $tmp * $tmp; } $out; } multi show (SqMat $m) { - my $size = 1; - for ^$m X ^$m -> ($i, $j) { $size max= $m[$i][$j].Str.chars; } - .put for @$m».fmt("%{$size}s"); + my $size = $m.flatmap( *.list».chars ).max; + say .fmt("%{$size}s", ' ') for $m.list; } my @m = [1, 2, 0], - [0, 3, 1], - [1, 0, 0]; + [0, 3, 1], + [1, 0, 0]; for 0 .. 10 -> $order { say "### Order $order"; diff --git a/Task/Matrix-exponentiation-operator/Phix/matrix-exponentiation-operator.phix b/Task/Matrix-exponentiation-operator/Phix/matrix-exponentiation-operator.phix new file mode 100644 index 0000000000..0b7c364618 --- /dev/null +++ b/Task/Matrix-exponentiation-operator/Phix/matrix-exponentiation-operator.phix @@ -0,0 +1,55 @@ +function identity(integer n) +sequence res = repeat(repeat(0,n),n) + for i=1 to n do + res[i][i] = 1 + end for + return res +end function + +function matrix_mul(sequence a, sequence b) +sequence c + if length(a[1]) != length(b) then + return 0 + else + c = repeat(repeat(0,length(b[1])),length(a)) + for i=1 to length(a) do + for j=1 to length(b[1]) do + for k=1 to length(a[1]) do + c[i][j] += a[i][k]*b[k][j] + end for + end for + end for + return c + end if +end function + +function matrix_exponent(sequence m, integer n) +integer l = length(m) + if n=0 then return identity(l) end if + sequence res = m + for i=2 to n do + res = matrix_mul(res,m) + end for + return res +end function + +constant M1 = {{5}} +constant M2 = {{3, 2}, + {2, 1}} +constant M3 = {{1, 2, 0}, + {0, 3, 1}, + {1, 0, 0}} + +ppOpt({pp_Nest,1}) +pp(matrix_exponent(M1,0)) +pp(matrix_exponent(M1,1)) +pp(matrix_exponent(M1,2)) +puts(1,"==\n") +pp(matrix_exponent(M2,0)) +pp(matrix_exponent(M2,1)) +pp(matrix_exponent(M2,2)) +pp(matrix_exponent(M2,10)) +puts(1,"==\n") +pp(matrix_exponent(M3,10)) +puts(1,"==\n") +pp(matrix_exponent(identity(4),5)) diff --git a/Task/Matrix-multiplication/AppleScript/matrix-multiplication-1.applescript b/Task/Matrix-multiplication/AppleScript/matrix-multiplication-1.applescript index 8618ce1afe..c4779b228a 100644 --- a/Task/Matrix-multiplication/AppleScript/matrix-multiplication-1.applescript +++ b/Task/Matrix-multiplication/AppleScript/matrix-multiplication-1.applescript @@ -1,26 +1,24 @@ --- matrixMultiply :: [[n]] -> [[n]] -> [[n]] +-- matrixMultiply :: Num a => [[a]] -> [[a]] -> [[a]] to matrixMultiply(a, b) script rows property xs : transpose(b) - on lambda(row) + on |λ|(row) script columns - on lambda(col) - dotProduct(row, col) - end lambda + on |λ|(col) + my dotProduct(row, col) + end |λ| end script map(columns, xs) - end lambda + end |λ| end script map(rows, a) end matrixMultiply - --- TEST - +-- TEST ----------------------------------------------------------- on run matrixMultiply({¬ {-1, 1, 4}, ¬ @@ -37,64 +35,34 @@ on run end run +-- GENERIC FUNCTIONS ---------------------------------------------- + -- dotProduct :: [n] -> [n] -> Maybe n on dotProduct(xs, ys) - script product - on lambda(a, b) + script mult + on |λ|(a, b) a * b - end lambda + end |λ| end script if length of xs is not length of ys then missing value else - sum(zipWith(product, xs, ys)) + sum(zipWith(mult, xs, ys)) end if end dotProduct --- transpose :: [[a]] -> [[a]] -on transpose(xss) - script column - on lambda(_, iCol) - script row - on lambda(xs) - item iCol of xs - end lambda - end script - - map(row, xss) - end lambda - end script - - map(column, item 1 of xss) -end transpose - --- sum :: [n] -> n -on sum(xs) - script add - on lambda(a, b) - a + b - end lambda - end script - - foldl(add, 0, xs) -end sum - - - --- GENERIC LIBRARY FUNCTIONS - --- foldl :: (a -> b -> a) -> a -> [b] -> a -on foldl(f, startValue, xs) +-- foldr :: (a -> b -> a) -> a -> [b] -> a +on foldr(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs - repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + repeat with i from lng to 1 by -1 + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell -end foldl +end foldr -- map :: (a -> b) -> [a] -> [b] on map(f, xs) @@ -102,35 +70,80 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map --- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -on zipWith(f, xs, ys) - set lng to length of xs - if lng is not length of ys then - missing value +-- min :: Ord a => a -> a -> a +on min(x, y) + if y < x then + y else - tell mReturn(f) - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, item i of ys) - end repeat - return lst - end tell + x end if -end zipWith +end min --- Script | Handler -> Script +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script - property lambda : f + property |λ| : f end script end if end mReturn + +-- product :: Num a => [a] -> a +on product(xs) + script mult + on |λ|(a, b) + a * b + end |λ| + end script + + foldr(mult, 1, xs) +end product + +-- sum :: Num a => [a] -> a +on sum(xs) + script add + on |λ|(a, b) + a + b + end |λ| + end script + + foldr(add, 0, xs) +end sum + +-- transpose :: [[a]] -> [[a]] +on transpose(xss) + script column + on |λ|(_, iCol) + script row + on |λ|(xs) + item iCol of xs + end |λ| + end script + + map(row, xss) + end |λ| + end script + + map(column, item 1 of xss) +end transpose + +-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] +on zipWith(f, xs, ys) + set lng to min(length of xs, length of ys) + set lst to {} + tell mReturn(f) + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, item i of ys) + end repeat + return lst + end tell +end zipWith diff --git a/Task/Matrix-multiplication/Forth/matrix-multiplication.fth b/Task/Matrix-multiplication/Forth/matrix-multiplication.fth index 6d4498cde8..001f648107 100644 --- a/Task/Matrix-multiplication/Forth/matrix-multiplication.fth +++ b/Task/Matrix-multiplication/Forth/matrix-multiplication.fth @@ -1,10 +1,14 @@ -include fsl-util.f +S" fsl-util.fs" REQUIRED +S" fsl/dynmem.seq" REQUIRED +: F+! ( addr -- ) ( F: r -- ) DUP F@ F+ F! ; +: FSQR ( F: r1 -- r2 ) FDUP F* ; +S" fsl/gaussj.seq" REQUIRED - 3 3 float matrix A{{ - A{{ 3 3 }}fread 1e 2e 3e 4e 5e 6e 7e 8e 9e - 3 3 float matrix B{{ - B{{ 3 3 }}fread 3e 3e 3e 2e 2e 2e 1e 1e 1e - 3 3 float matrix C{{ \ result +3 3 float matrix A{{ +1e 2e 3e 4e 5e 6e 7e 8e 9e 3 3 A{{ }}fput +3 3 float matrix B{{ +3e 3e 3e 2e 2e 2e 1e 1e 1e 3 3 B{{ }}fput +float dmatrix C{{ \ result - A{{ B{{ C{{ mat* - C{{ }}print +A{{ 3 3 B{{ 3 3 & C{{ mat* +3 3 C{{ }}fprint diff --git a/Task/Matrix-multiplication/JavaScript/matrix-multiplication-3.js b/Task/Matrix-multiplication/JavaScript/matrix-multiplication-3.js new file mode 100644 index 0000000000..8562aca032 --- /dev/null +++ b/Task/Matrix-multiplication/JavaScript/matrix-multiplication-3.js @@ -0,0 +1,2 @@ +[[51, -8, 26, -18], [-8, -38, -6, 34], + [33, 42, 38, -14], [17, 74, 72, 44]] diff --git a/Task/Matrix-multiplication/JavaScript/matrix-multiplication-4.js b/Task/Matrix-multiplication/JavaScript/matrix-multiplication-4.js new file mode 100644 index 0000000000..766049e0dc --- /dev/null +++ b/Task/Matrix-multiplication/JavaScript/matrix-multiplication-4.js @@ -0,0 +1,52 @@ +((() => { + 'use strict'; + + // matrixMultiply :: Num a => [[a]] -> [[a]] -> [[a]] + const matrixMultiply = (a, b) => { + const bCols = transpose(b); + return a.map(aRow => bCols.map(bCol => dotProduct(aRow, bCol))); + } + + // dotProduct :: Num a => [[a]] -> [[a]] -> [[a]] + const dotProduct = (xs, ys) => sum(zipWith(product, xs, ys)); + + + // GENERIC + + // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] + const zipWith = (f, xs, ys) => + xs.length === ys.length ? ( + xs.map((x, i) => f(x, ys[i])) + ) : undefined; + + // transpose :: [[a]] -> [[a]] + const transpose = xs => + xs[0].map((_, iCol) => xs.map(row => row[iCol])); + + // sum :: (Num a) => [a] -> a + const sum = xs => + xs.reduce((a, x) => a + x, 0); + + // product :: Num a => a -> a -> a + const product = (a, b) => a * b; + + + // TEST + return matrixMultiply( + [ + [-1, 1, 4], + [6, -4, 2], + [-3, 5, 0], + [3, 7, -2] + ], + + [ + [-1, 1, 4, 8], + [6, 9, 10, 2], + [11, -4, 5, -3] + ] + ); + + // --> [[51, -8, 26, -18], [-8, -38, -6, 34], + // [33, 42, 38, -14], [17, 74, 72, 44]] +}))(); diff --git a/Task/Matrix-multiplication/JavaScript/matrix-multiplication-5.js b/Task/Matrix-multiplication/JavaScript/matrix-multiplication-5.js new file mode 100644 index 0000000000..7be28246fc --- /dev/null +++ b/Task/Matrix-multiplication/JavaScript/matrix-multiplication-5.js @@ -0,0 +1,2 @@ +[[51, -8, 26, -18], [-8, -38, -6, 34], +[33, 42, 38, -14], [17, 74, 72, 44]] diff --git a/Task/Matrix-multiplication/jq/matrix-multiplication.jq b/Task/Matrix-multiplication/Jq/matrix-multiplication.jq similarity index 100% rename from Task/Matrix-multiplication/jq/matrix-multiplication.jq rename to Task/Matrix-multiplication/Jq/matrix-multiplication.jq diff --git a/Task/Matrix-multiplication/Kotlin/matrix-multiplication.kotlin b/Task/Matrix-multiplication/Kotlin/matrix-multiplication.kotlin new file mode 100644 index 0000000000..333431b6f7 --- /dev/null +++ b/Task/Matrix-multiplication/Kotlin/matrix-multiplication.kotlin @@ -0,0 +1,40 @@ +// version 1.1.3 + +typealias Vector = DoubleArray +typealias Matrix = Array + +operator fun Matrix.times(other: Matrix): Matrix { + val rows1 = this.size + val cols1 = this[0].size + val rows2 = other.size + val cols2 = other[0].size + require(cols1 == rows2) + val result = Matrix(rows1) { Vector(cols2) } + for (i in 0 until rows1) { + for (j in 0 until cols2) { + for (k in 0 until rows2) { + result[i][j] += this[i][k] * other[k][j] + } + } + } + return result +} + +fun printMatrix(m: Matrix) { + for (i in 0 until m.size) println(m[i].contentToString()) +} + +fun main(args: Array) { + val m1 = arrayOf( + doubleArrayOf(-1.0, 1.0, 4.0), + doubleArrayOf( 6.0, -4.0, 2.0), + doubleArrayOf(-3.0, 5.0, 0.0), + doubleArrayOf( 3.0, 7.0, -2.0) + ) + val m2 = arrayOf( + doubleArrayOf(-1.0, 1.0, 4.0, 8.0), + doubleArrayOf( 6.0, 9.0, 10.0, 2.0), + doubleArrayOf(11.0, -4.0, 5.0, -3.0) + ) + printMatrix(m1 * m2) +} diff --git a/Task/Matrix-multiplication/Rust/matrix-multiplication.rust b/Task/Matrix-multiplication/Rust/matrix-multiplication.rust new file mode 100644 index 0000000000..557667ec9e --- /dev/null +++ b/Task/Matrix-multiplication/Rust/matrix-multiplication.rust @@ -0,0 +1,58 @@ +struct Matrix { + dat: [[f32; 3]; 3] +} + +impl Matrix { + pub fn mult_m(a: Matrix, b: Matrix) -> Matrix + { + let mut out = Matrix { + dat: [[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.] + ] + }; + + for i in 0..3{ + for j in 0..3 { + for k in 0..3 { + out.dat[i][j] += a.dat[i][k] * b.dat[k][j]; + } + } + } + + out + } + + pub fn print(self) + { + for i in 0..3 { + for j in 0..3 { + print!("{} ", self.dat[i][j]); + } + print!("\n"); + } + } +} + +fn main() +{ + let a = Matrix { + dat: [[1., 2., 3.], + [4., 5., 6.], + [7., 8., 9.] + ] + }; + + let b = Matrix { + dat: [[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]] + }; + + + + let c = Matrix::mult_m(a, b); + + + c.print(); +} diff --git a/Task/Matrix-multiplication/Zkl/matrix-multiplication-1.zkl b/Task/Matrix-multiplication/Zkl/matrix-multiplication-1.zkl new file mode 100644 index 0000000000..680b96f1f8 --- /dev/null +++ b/Task/Matrix-multiplication/Zkl/matrix-multiplication-1.zkl @@ -0,0 +1,4 @@ +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +A:=GSL.Matrix(4,2).set(1,2, 3,4, 5,6, 7,8); +B:=GSL.Matrix(2,3).set(1,2,3, 4,5,6); +(A*B).format().println(); // creates a new matrix diff --git a/Task/Matrix-multiplication/Zkl/matrix-multiplication-2.zkl b/Task/Matrix-multiplication/Zkl/matrix-multiplication-2.zkl new file mode 100644 index 0000000000..2c281fcf78 --- /dev/null +++ b/Task/Matrix-multiplication/Zkl/matrix-multiplication-2.zkl @@ -0,0 +1,6 @@ +fcn matMult(a,b){ + n,m,p:=a[0].len(),a.len(),b[0].len(); + ans:=(0).pump(m,List().write, (0).pump(p,List,0).copy); // matrix of zeros + foreach i,j,k in (m,p,n){ ans[i][j]+=a[i][k]*b[k][j]; } + ans +} diff --git a/Task/Matrix-multiplication/Zkl/matrix-multiplication-3.zkl b/Task/Matrix-multiplication/Zkl/matrix-multiplication-3.zkl new file mode 100644 index 0000000000..2831f505e8 --- /dev/null +++ b/Task/Matrix-multiplication/Zkl/matrix-multiplication-3.zkl @@ -0,0 +1,6 @@ +a:=L( L(1,2,), L(3,4,), L(5,6,), L(7,8) ); +b:=L( L(1,2,3,), L(4,5,6) ); +printM(matMult(a,b)); + +fcn printM(m){ m.pump(Console.println,rowFmt) } +fcn rowFmt(row){ ("%4d "*row.len()).fmt(row.xplode()) } diff --git a/Task/Matrix-transposition/AppleScript/matrix-transposition-2.applescript b/Task/Matrix-transposition/AppleScript/matrix-transposition-2.applescript index f0463970c5..dd680a6667 100644 --- a/Task/Matrix-transposition/AppleScript/matrix-transposition-2.applescript +++ b/Task/Matrix-transposition/AppleScript/matrix-transposition-2.applescript @@ -1,31 +1,31 @@ +-- TRANSPOSE ----------------------------------------------------------------- + -- transpose :: [[a]] -> [[a]] on transpose(xss) script column - on lambda(_, iCol) + on |λ|(_, iCol) script row - on lambda(xs) + on |λ|(xs) item iCol of xs - end lambda + end |λ| end script map(row, xss) - end lambda + end |λ| end script map(column, item 1 of xss) end transpose --- TEST +-- TEST ---------------------------------------------------------------------- on run - transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) --> {{1, 4, 7, 10}, {2, 5, 8, 11}, {3, 6, 9, 12}} end run - --- GENERIC LIBRARY FUNCTIONS +-- GENERIC FUNCTIONS --------------------------------------------------------- -- map :: (a -> b) -> [a] -> [b] on map(f, xs) @@ -33,7 +33,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -46,7 +46,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Matrix-transposition/Clojure/matrix-transposition-1.clj b/Task/Matrix-transposition/Clojure/matrix-transposition-1.clj deleted file mode 100644 index 0859f4342b..0000000000 --- a/Task/Matrix-transposition/Clojure/matrix-transposition-1.clj +++ /dev/null @@ -1,11 +0,0 @@ -(defmulti matrix-transpose - "Switch rows with columns." - class) - -(defmethod matrix-transpose clojure.lang.PersistentList - [mtx] - (apply map list mtx)) - -(defmethod matrix-transpose clojure.lang.PersistentVector - [mtx] - (vec (apply map vector mtx))) diff --git a/Task/Matrix-transposition/Clojure/matrix-transposition-2.clj b/Task/Matrix-transposition/Clojure/matrix-transposition-2.clj deleted file mode 100644 index d9c0129fc8..0000000000 --- a/Task/Matrix-transposition/Clojure/matrix-transposition-2.clj +++ /dev/null @@ -1,2 +0,0 @@ -=> (matrix-transpose [[1 2 3] [4 5 6]]) -[[1 4] [2 5] [3 6]] diff --git a/Task/Matrix-transposition/Forth/matrix-transposition.fth b/Task/Matrix-transposition/Forth/matrix-transposition.fth new file mode 100644 index 0000000000..e3423c2150 --- /dev/null +++ b/Task/Matrix-transposition/Forth/matrix-transposition.fth @@ -0,0 +1,12 @@ +S" fsl-util.fs" REQUIRED +S" fsl/dynmem.seq" REQUIRED +: F+! ( addr -- ) ( F: r -- ) DUP F@ F+ F! ; +: FSQR ( F: r1 -- r2 ) FDUP F* ; +S" fsl/gaussj.seq" REQUIRED + +5 3 float matrix a{{ +1e 2e 3e 4e 5e 6e 7e 8e 9e 10e 11e 12e 13e 14e 15e 5 3 a{{ }}fput +float dmatrix b{{ + +a{{ 5 3 & b{{ transpose +3 5 b{{ }}fprint diff --git a/Task/Matrix-transposition/Fortran/matrix-transposition-4.f b/Task/Matrix-transposition/Fortran/matrix-transposition-4.f new file mode 100644 index 0000000000..0e040623c1 --- /dev/null +++ b/Task/Matrix-transposition/Fortran/matrix-transposition-4.f @@ -0,0 +1,28 @@ + DIMENSION A(3,5),B(5,3),C(5,3) + EQUIVALENCE (A,C) !Occupy the same storage. + DATA A/ + 1 1, 2, 3, 4, 5, + 2 6, 7, 8, 9,10, + 3 11,12,13,14,15/ !Supplies values in storage order. + + WRITE (6,*) "Three rows of five values:" + WRITE (6,1) A !This shows values in storage order. + WRITE (6,*) "...written as C(row,column):" + WRITE (6,2) ((C(I,J),J = 1,3),I = 1,5) + WRITE (6,*) "... written as A(row,column):" + WRITE (6,1) ((A(I,J),J = 1,5),I = 1,3) + + WRITE (6,*) + WRITE (6,*) "B = Transpose(A)" + DO 10 I = 1,3 + DO 10 J = 1,5 + 10 B(J,I) = A(I,J) + + WRITE (6,*) "Five rows of three values:" + WRITE (6,2) B + WRITE (6,*) "... written as B(row,column):" + WRITE (6,2) ((B(I,J),J = 1,3),I = 1,5) + + 1 FORMAT (5F6.1) !Five values per line. + 2 FORMAT (3F6.1) !Three values per line. + END diff --git a/Task/Matrix-transposition/HicEst/matrix-transposition-1.hicest b/Task/Matrix-transposition/HicEst/matrix-transposition-1.hicest deleted file mode 100644 index 1e6b41e55a..0000000000 --- a/Task/Matrix-transposition/HicEst/matrix-transposition-1.hicest +++ /dev/null @@ -1,7 +0,0 @@ -REAL :: mtx(2, 4) - -mtx = 1.1 * $ -WRITE() mtx - -SOLVE(Matrix=mtx, Transpose=mtx) -WRITE() mtx diff --git a/Task/Matrix-transposition/HicEst/matrix-transposition-2.hicest b/Task/Matrix-transposition/HicEst/matrix-transposition-2.hicest deleted file mode 100644 index 47f8a06049..0000000000 --- a/Task/Matrix-transposition/HicEst/matrix-transposition-2.hicest +++ /dev/null @@ -1,7 +0,0 @@ -1.1 2.2 3.3 4.4 -5.5 6.6 7.7 8.8 - -1.1 5.5 -2.2 6.6 -3.3 7.7 -4.4 8.8 diff --git a/Task/Matrix-transposition/jq/matrix-transposition.jq b/Task/Matrix-transposition/Jq/matrix-transposition.jq similarity index 100% rename from Task/Matrix-transposition/jq/matrix-transposition.jq rename to Task/Matrix-transposition/Jq/matrix-transposition.jq diff --git a/Task/Matrix-transposition/Klong/matrix-transposition.klong b/Task/Matrix-transposition/Klong/matrix-transposition.klong new file mode 100644 index 0000000000..1e3ee4e0b7 --- /dev/null +++ b/Task/Matrix-transposition/Klong/matrix-transposition.klong @@ -0,0 +1,13 @@ + [5 5]:^!25 +[[0 1 2 3 4] + [5 6 7 8 9] + [10 11 12 13 14] + [15 16 17 18 19] + [20 21 22 23 24]] + + +[5 5]:^!25 +[[0 5 10 15 20] + [1 6 11 16 21] + [2 7 12 17 22] + [3 8 13 18 23] + [4 9 14 19 24]] diff --git a/Task/Matrix-transposition/Kotlin/matrix-transposition.kotlin b/Task/Matrix-transposition/Kotlin/matrix-transposition.kotlin new file mode 100644 index 0000000000..c6d432fe6b --- /dev/null +++ b/Task/Matrix-transposition/Kotlin/matrix-transposition.kotlin @@ -0,0 +1,28 @@ +// version 1.1.3 + +typealias Vector = DoubleArray +typealias Matrix = Array + +fun Matrix.transpose(): Matrix { + val rows = this.size + val cols = this[0].size + val trans = Matrix(cols) { Vector(rows) } + for (i in 0 until cols) { + for (j in 0 until rows) trans[i][j] = this[j][i] + } + return trans +} + +fun printMatrix(m: Matrix) { + for (i in 0 until m.size) println(m[i].contentToString()) +} + +fun main(args: Array) { + val m = arrayOf( + doubleArrayOf( 1.0, 2.0, 3.0), + doubleArrayOf( 4.0, 5.0, 6.0), + doubleArrayOf( 7.0, 8.0, 9.0), + doubleArrayOf(10.0, 11.0, 12.0) + ) + printMatrix(m.transpose()) +} diff --git a/Task/Matrix-transposition/Perl-6/matrix-transposition-1.pl6 b/Task/Matrix-transposition/Perl-6/matrix-transposition-1.pl6 deleted file mode 100644 index 63d0661a8d..0000000000 --- a/Task/Matrix-transposition/Perl-6/matrix-transposition-1.pl6 +++ /dev/null @@ -1,16 +0,0 @@ -sub transpose(@m) -{ - my @t; - for ^@m X ^@m[0] -> ($x, $y) { @t[$y][$x] = @m[$x][$y] } - return @t; -} - -# creates a random matrix -my @a; -for ^5 X ^5 -> ($x, $y) { @a[$x][$y] = ('a'..'z').pick; } -say "original:"; -.gist.say for @a; - -my @b = transpose(@a); -say "transposed:"; -.gist.say for @b; diff --git a/Task/Matrix-transposition/Perl-6/matrix-transposition-2.pl6 b/Task/Matrix-transposition/Perl-6/matrix-transposition-2.pl6 deleted file mode 100644 index 03af3ef144..0000000000 --- a/Task/Matrix-transposition/Perl-6/matrix-transposition-2.pl6 +++ /dev/null @@ -1,10 +0,0 @@ -sub transpose (@m) { - ([ @m[*;$_] ] for ^@m[0]); -} - -my @a = < a b c d e >, - < f g h i j >, - < k l m n o >, - < p q r s t >; - -.say for @a.&transpose; diff --git a/Task/Matrix-transposition/Perl-6/matrix-transposition-3.pl6 b/Task/Matrix-transposition/Perl-6/matrix-transposition.pl6 similarity index 100% rename from Task/Matrix-transposition/Perl-6/matrix-transposition-3.pl6 rename to Task/Matrix-transposition/Perl-6/matrix-transposition.pl6 diff --git a/Task/Matrix-transposition/REXX/matrix-transposition-1.rexx b/Task/Matrix-transposition/REXX/matrix-transposition-1.rexx new file mode 100644 index 0000000000..f522311b35 --- /dev/null +++ b/Task/Matrix-transposition/REXX/matrix-transposition-1.rexx @@ -0,0 +1,23 @@ +/*REXX program transposes any sized rectangular matrix, displays before & after matrices*/ +@.=; @.1 = 1.02 2.03 3.04 4.05 5.06 6.07 7.08 + @.2 = 111 2222 33333 444444 5555555 66666666 777777777 + do row=1 while @.row\=='' + do col=1 while @.row\==''; parse var @.row A.row.col @.row + end /*c*/ + end /*r*/ /* [↑] build matrix A from matrix X*/ +rows=row-1; cols=col-1 /*adjust for the DO loop indices. */ +L=0; do j=1 for rows + do k=1 for cols + B.k.j=A.j.k; L=max( L, length(B.k.j) ) + end /*k*/ /* ↑ */ + end /*j*/ /* └─── is maximum width element value*/ +call showMat 'A',rows,cols +call showMat 'B',cols,rows +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +showMat: arg mat,rows,cols; say; say center( mat 'matrix', (L+1)*cols +4, "─") + do r=1 for rows; _= + do c=1 for cols; _=_ right( value( mat'.'r"."c), L) + end /*c*/ + say _ + end /*r*/; return diff --git a/Task/Matrix-transposition/REXX/matrix-transposition-2.rexx b/Task/Matrix-transposition/REXX/matrix-transposition-2.rexx new file mode 100644 index 0000000000..a06b0226b8 --- /dev/null +++ b/Task/Matrix-transposition/REXX/matrix-transposition-2.rexx @@ -0,0 +1,8 @@ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +showMat: arg mat,rows,cols; say; say center( mat 'matrix', (L+1)*cols +4, "─") + $=. + do r=1 for rows; _= + do c=1 for cols; _=_ right( value( mat || $ || r || $ || c), L) + end /*c*/ + say _ + end /*r*/; return diff --git a/Task/Matrix-transposition/REXX/matrix-transposition.rexx b/Task/Matrix-transposition/REXX/matrix-transposition.rexx deleted file mode 100644 index 0e30d79773..0000000000 --- a/Task/Matrix-transposition/REXX/matrix-transposition.rexx +++ /dev/null @@ -1,28 +0,0 @@ -/*REXX program transposes a matrix, and displays the before and after matrices. */ -x.=; x.1 = 1.02 2.03 3.04 4.05 5.06 6.07 7.07 - x.2 = 111 2222 33333 444444 5555555 66666666 777777777 - - do r=1 while x.r\=='' /*build matrix A from matrix X.*/ - do c=1 while x.r\=='' - parse var x.r a.r.c x.r - end /*c*/ - end /*r*/ -rows=r-1; cols=c-1 /*adjust for DO loop indices. */ -L=0 /*L is max width element value. */ - do i=1 for rows - do j=1 for cols - b.j.i=a.i.j; L=max( L, length(b.j.i) ) - end /*j*/ - end /*i*/ - -call showMat 'A', rows, cols -call showMat 'B', cols, rows -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -showMat: parse arg mat,rows,cols; say; say center(mat 'matrix', cols*(L+1)+4, "─") - do r=1 for rows; _= - do c=1 for cols; _=_ right(value(mat'.'r"."c), L) - end /*c*/ - say _ - end /*r*/ - return diff --git a/Task/Matrix-transposition/Rust/matrix-transposition.rust b/Task/Matrix-transposition/Rust/matrix-transposition.rust new file mode 100644 index 0000000000..96950b8dd3 --- /dev/null +++ b/Task/Matrix-transposition/Rust/matrix-transposition.rust @@ -0,0 +1,48 @@ +struct Matrix { + dat: [[i32; 3]; 3] +} + + + +impl Matrix { + pub fn transpose_m(a: Matrix) -> Matrix + { + let mut out = Matrix { + dat: [[0, 0, 0], + [0, 0, 0], + [0, 0, 0] + ] + }; + + for i in 0..3{ + for j in 0..3{ + + out.dat[i][j] = a.dat[j][i]; + } + } + + out + } + + pub fn print(self) + { + for i in 0..3 { + for j in 0..3 { + print!("{} ", self.dat[i][j]); + } + print!("\n"); + } + } +} + +fn main() +{ + let a = Matrix { + dat: [[1, 2, 3], + [4, 5, 6], + [7, 8, 9] ] + }; + +let c = Matrix::transpose_m(a); + c.print(); +} diff --git a/Task/Matrix-transposition/Zkl/matrix-transposition-1.zkl b/Task/Matrix-transposition/Zkl/matrix-transposition-1.zkl new file mode 100644 index 0000000000..afdd12ed9d --- /dev/null +++ b/Task/Matrix-transposition/Zkl/matrix-transposition-1.zkl @@ -0,0 +1,6 @@ +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +GSL.Matrix(2,3).set(1,2,3, 4,5,6).transpose().format(5).println(); // in place +println("---"); +GSL.Matrix(2,2).set(1,2, 3,4).transpose().format(5).println(); // in place +println("---"); +GSL.Matrix(3,1).set(1,2,3).transpose().format(5).println(); // in place diff --git a/Task/Matrix-transposition/Zkl/matrix-transposition-2.zkl b/Task/Matrix-transposition/Zkl/matrix-transposition-2.zkl new file mode 100644 index 0000000000..0c16b09398 --- /dev/null +++ b/Task/Matrix-transposition/Zkl/matrix-transposition-2.zkl @@ -0,0 +1,4 @@ +fcn transpose(M){ + if(M.len()==1) M[0].pump(List,List.create); // 1 row --> n columns + else M[0].zip(M.xplode(1)); +} diff --git a/Task/Matrix-transposition/Zkl/matrix-transposition-3.zkl b/Task/Matrix-transposition/Zkl/matrix-transposition-3.zkl new file mode 100644 index 0000000000..a5dddd8e76 --- /dev/null +++ b/Task/Matrix-transposition/Zkl/matrix-transposition-3.zkl @@ -0,0 +1,5 @@ +m:=T(T(1,2,3),T(4,5,6)); transpose(m).println(); +m:=L(L(1,"a"),L(2,"b"),L(3,"c")); transpose(m).println(); +transpose(L(L(1,2,3))).println(); +transpose(L(L(1),L(2),L(3))).println(); +transpose(L(L(1))).println(); diff --git a/Task/Maximum-triangle-path-sum/AppleScript/maximum-triangle-path-sum.applescript b/Task/Maximum-triangle-path-sum/AppleScript/maximum-triangle-path-sum.applescript new file mode 100644 index 0000000000..32ca68e850 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/AppleScript/maximum-triangle-path-sum.applescript @@ -0,0 +1,170 @@ +-- MAX PATH SUM --------------------------------------------------------------- + +-- Working from the bottom of the triangle upwards, +-- summing each number with the larger of the two below +-- until the maximum emerges at the top. + +-- maxPathSum :: [[Int]] -> Int +on maxPathSum(xss) + + -- With the last row as the initial accumulator, + -- folding from the penultimate line, + -- towards the top of the triangle: + + -- sumWithRowBelow :: [Int] -> [Int] -> [Int] + script sumWithRowBelow + on |λ|(row, accum) + + -- plusGreaterOfTwoBelow :: Int -> Int -> Int -> Int + script plusGreaterOfTwoBelow + on |λ|(x, intLeft, intRight) + x + max(intLeft, intRight) + end |λ| + end script + + -- The accumulator, zipped with the tail of the + -- accumulator, yields pairs of adjacent sums so far. + + zipWith3(plusGreaterOfTwoBelow, row, accum, tail(accum)) + end |λ| + end script + + -- A list of lists folded down to a list of just one remaining integer. + -- Head returns that integer from the list. + + head(foldr1(sumWithRowBelow, xss)) +end maxPathSum + + +-- TEST ----------------------------------------------------------------------- +on run + + maxPathSum({¬ + {55}, ¬ + {94, 48}, ¬ + {95, 30, 96}, ¬ + {77, 71, 26, 67}, ¬ + {97, 13, 76, 38, 45}, ¬ + {7, 36, 79, 16, 37, 68}, ¬ + {48, 7, 9, 18, 70, 26, 6}, ¬ + {18, 72, 79, 46, 59, 79, 29, 90}, ¬ + {20, 76, 87, 11, 32, 7, 7, 49, 18}, ¬ + {27, 83, 58, 35, 71, 11, 25, 57, 29, 85}, ¬ + {14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55}, ¬ + {2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23}, ¬ + {92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42}, ¬ + {56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72}, ¬ + {44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36}, ¬ + {85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52}, ¬ + {6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15}, ¬ + {27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93} ¬ + }) + + --> 1320 +end run + + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl + +-- foldr1 :: (a -> a -> a) -> [a] -> a +on foldr1(f, xs) + if length of xs > 1 then + tell mReturn(f) + set v to item -1 of xs + set lng to length of xs + repeat with i from lng - 1 to 1 by -1 + set v to |λ|(item i of xs, v, i, xs) + end repeat + return v + end tell + else + xs + end if +end foldr1 + +-- head :: [a] -> a +on head(xs) + if length of xs > 0 then + item 1 of xs + else + missing value + end if +end head + +-- max :: Ord a => a -> a -> a +on max(x, y) + if x > y then + x + else + y + end if +end max + +-- min :: Ord a => a -> a -> a +on min(x, y) + if y < x then + y + else + x + end if +end min + +-- minimum :: [a] -> a +on minimum(xs) + script min + on |λ|(a, x) + if x < a or a is missing value then + x + else + a + end if + end |λ| + end script + + foldl(min, missing value, xs) +end minimum + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- tail :: [a] -> [a] +on tail(xs) + if length of xs > 1 then + items 2 thru -1 of xs + else + {} + end if +end tail + +-- zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] +on zipWith3(f, xs, ys, zs) + set lng to minimum({length of xs, length of ys, length of zs}) + set lst to {} + tell mReturn(f) + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, item i of ys, item i of zs) + end repeat + return lst + end tell +end zipWith3 diff --git a/Task/Maximum-triangle-path-sum/Astro/maximum-triangle-path-sum.astro b/Task/Maximum-triangle-path-sum/Astro/maximum-triangle-path-sum.astro new file mode 100644 index 0000000000..442873227e --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Astro/maximum-triangle-path-sum.astro @@ -0,0 +1,28 @@ +fun solve(!tri): + while tri.size > 1: + let t0 = tri.pop() + for (i, t) in enumerate(tri[!0]): + tri[!0, i] = max(t0[i], t0[i+1]) + t + tri[0, 0] + +let data = """ + 55 + 94 48 + 95 30 96 + 77 71 26 67 + 97 13 76 38 45 + 07 36 79 16 37 68 + 48 07 09 18 70 26 06 + 18 72 79 46 59 79 29 90 + 20 76 87 11 32 07 07 49 18 + 27 83 58 35 71 11 25 57 29 85 + 14 64 36 96 27 11 58 56 92 18 55 + 02 90 03 60 48 49 41 46 33 36 47 23 + 92 50 48 02 36 59 42 79 72 20 82 77 42 + 56 78 38 80 39 75 02 71 66 66 01 03 55 72 + 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 + 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 + 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 +27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93""" + +print solve data.lines.map |x| -> x.trim().split().map(int) diff --git a/Task/Maximum-triangle-path-sum/Haskell/maximum-triangle-path-sum.hs b/Task/Maximum-triangle-path-sum/Haskell/maximum-triangle-path-sum-1.hs similarity index 100% rename from Task/Maximum-triangle-path-sum/Haskell/maximum-triangle-path-sum.hs rename to Task/Maximum-triangle-path-sum/Haskell/maximum-triangle-path-sum-1.hs diff --git a/Task/Maximum-triangle-path-sum/Haskell/maximum-triangle-path-sum-2.hs b/Task/Maximum-triangle-path-sum/Haskell/maximum-triangle-path-sum-2.hs new file mode 100644 index 0000000000..0269506bed --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Haskell/maximum-triangle-path-sum-2.hs @@ -0,0 +1,26 @@ +maxPathSum :: [[Int]] -> Int +maxPathSum = head . foldr1 ((<*> tail) . zipWith3 (\x y z -> x + max y z)) + +main :: IO () +main = + print $ + maxPathSum + [ [55] + , [94, 48] + , [95, 30, 96] + , [77, 71, 26, 67] + , [97, 13, 76, 38, 45] + , [07, 36, 79, 16, 37, 68] + , [48, 07, 09, 18, 70, 26, 06] + , [18, 72, 79, 46, 59, 79, 29, 90] + , [20, 76, 87, 11, 32, 07, 07, 49, 18] + , [27, 83, 58, 35, 71, 11, 25, 57, 29, 85] + , [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55] + , [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23] + , [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42] + , [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72] + , [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36] + , [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52] + , [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15] + , [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93] + ] diff --git a/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-1.js b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-1.js new file mode 100644 index 0000000000..ca0ac26176 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-1.js @@ -0,0 +1,39 @@ +var arr = [ +[55], +[94, 48], +[95, 30, 96], +[77, 71, 26, 67], +[97, 13, 76, 38, 45], +[07, 36, 79, 16, 37, 68], +[48, 07, 09, 18, 70, 26, 06], +[18, 72, 79, 46, 59, 79, 29, 90], +[20, 76, 87, 11, 32, 07, 07, 49, 18], +[27, 83, 58, 35, 71, 11, 25, 57, 29, 85], +[14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55], +[02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23], +[92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42], +[56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72], +[44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36], +[85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52], +[06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15], +[27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93] +]; + +while (arr.length !== 1) { + var len = arr.length; + var row = []; + var current = arr[len-2]; + var currentLen = current.length - 1; + var end = arr[len-1]; + + for ( var i = 0; i <= currentLen; i++ ) { + row.push(Math.max(current[i] + end[i] || 0, current[i] + end[i+1] || 0) ) + } + + arr.pop(); + arr.pop(); + + arr.push(row); +} + +console.log(arr); diff --git a/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-2.js b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-2.js new file mode 100644 index 0000000000..ba69092f0e --- /dev/null +++ b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-2.js @@ -0,0 +1 @@ +[ [ 1320 ] ] diff --git a/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-3.js b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-3.js new file mode 100644 index 0000000000..c9706968c5 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-3.js @@ -0,0 +1,50 @@ +(function () { + + // Right fold using final element as initial accumulator + // (a -> a -> a) -> t a -> a + function foldr1(f, lst) { + return lst.length > 1 ? ( + f(lst[0], foldr1(f, lst.slice(1))) + ) : lst[0]; + } + + // function of arity 3 mapped over nth items of each of 3 lists + // (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] + function zipWith3(f, xs, ys, zs) { + return zs.length ? [f(xs[0], ys[0], zs[0])].concat( + zipWith3(f, xs.slice(1), ys.slice(1), zs.slice(1))) : []; + } + + // Evaluating from bottom up (right fold) + // and with recursion left to right (head and first item of tail at each stage) + return foldr1( + function (xs, ys) { + return zipWith3( + function (x, y, z) { + return x + (y < z ? z : y); + }, + xs, ys, ys.slice(1) // item above, and larger of two below + ); + }, [ + [55], + [94, 48], + [95, 30, 96], + [77, 71, 26, 67], + [97, 13, 76, 38, 45], + [07, 36, 79, 16, 37, 68], + [48, 07, 09, 18, 70, 26, 06], + [18, 72, 79, 46, 59, 79, 29, 90], + [20, 76, 87, 11, 32, 07, 07, 49, 18], + [27, 83, 58, 35, 71, 11, 25, 57, 29, 85], + [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55], + [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23], + [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42], + [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72], + [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36], + [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52], + [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15], + [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93] + ] + )[0]; + +})(); diff --git a/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-4.js b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-4.js new file mode 100644 index 0000000000..0718dd8e65 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-4.js @@ -0,0 +1 @@ +1320 diff --git a/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-5.js b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-5.js new file mode 100644 index 0000000000..e4782aa15a --- /dev/null +++ b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-5.js @@ -0,0 +1,42 @@ +function maximumTrianglePathSum(triangle) { + + function distilLastLine() { + let lastLine = triangle.pop(), + aboveLine = triangle.pop(); + for (let i = 0; i < aboveLine.length; i++) + aboveLine[i] = Math.max( + aboveLine[i] + lastLine[i], + aboveLine[i] + lastLine[i + 1] + ); + triangle.push(aboveLine); + } + + do { + distilLastLine(); + } while (triangle.length > 1); + return triangle[0][0]; +} + +// testing +let theTriangle = [ +[55], +[94, 48], +[95, 30, 96], +[77, 71, 26, 67], +[97, 13, 76, 38, 45], +[ 7, 36, 79, 16, 37, 68], +[48, 7, 9, 18, 70, 26, 6], +[18, 72, 79, 46, 59, 79, 29, 90], +[20, 76, 87, 11, 32, 7, 7, 49, 18], +[27, 83, 58, 35, 71, 11, 25, 57, 29, 85], +[14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55], +[ 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23], +[92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42], +[56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72], +[44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36], +[85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52], +[ 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15], +[27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93] +]; + +console.log(maximumTrianglePathSum(theTriangle)); diff --git a/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-6.js b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-6.js new file mode 100644 index 0000000000..0718dd8e65 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-6.js @@ -0,0 +1 @@ +1320 diff --git a/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-7.js b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-7.js new file mode 100644 index 0000000000..ffdb82d2f8 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-7.js @@ -0,0 +1,88 @@ +(() => { + 'use strict'; + + // MAX PATH SUM ----------------------------------------------------------- + + // Working from the bottom of the triangle upwards, + // summing each number with the larger of the two below + // until the maximum emerges at the top. + + // maxPathSum ::[[Int]] -> Int + const maxPathSum = xss => + + // A list of lists folded down to a list of just one remaining integer. + // The head function returns that integer from the list. + + head( + foldr1( + + // The accumulator, zipped with the tail of the + // accumulator, yields pairs of adjacent sums so far. + (ys, xs) => zipWith3( + + // Plus greater of two below + (a, b, c) => a + max(b, c), + xs, ys, tail(ys) + ), + xss + ) + ); + + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // Right fold using final element as initial accumulator + // foldr1 :: (a -> a -> a) -> [a] -> a + const foldr1 = (f, xs) => + xs.length > 0 ? init(xs) + .reduceRight(f, last(xs)) : []; + + // head :: [a] -> a + const head = xs => xs.length ? xs[0] : undefined; + + // init :: [a] -> [a] + const init = xs => xs.length ? xs.slice(0, -1) : undefined; + + // last :: [a] -> a + const last = xs => xs.length ? xs.slice(-1)[0] : undefined; + + // max :: Ord a => a -> a -> a + const max = (a, b) => b > a ? b : a; + + // minimum :: [a] -> a + const minimum = xs => + xs.reduce((a, x) => (x < a || a === undefined ? x : a), undefined); + + // tail :: [a] -> [a] + const tail = xs => xs.length ? xs.slice(1) : undefined; + + // Function of arity 3 mapped over nth items of each of 3 lists + // zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] + const zipWith3 = (f, xs, ys, zs) => + Array.from({ + length: minimum([xs.length, ys.length, zs.length]) + }, (_, i) => f(xs[i], ys[i], zs[i])); + + + // TEST ------------------------------------------------------------------- + return maxPathSum([ + [55], + [94, 48], + [95, 30, 96], + [77, 71, 26, 67], + [97, 13, 76, 38, 45], + [7, 36, 79, 16, 37, 68], + [48, 7, 9, 18, 70, 26, 6], + [18, 72, 79, 46, 59, 79, 29, 90], + [20, 76, 87, 11, 32, 7, 7, 49, 18], + [27, 83, 58, 35, 71, 11, 25, 57, 29, 85], + [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55], + [2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23], + [92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42], + [56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72], + [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36], + [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52], + [6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15], + [27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93] + ]); +})(); diff --git a/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-8.js b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-8.js new file mode 100644 index 0000000000..0718dd8e65 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/JavaScript/maximum-triangle-path-sum-8.js @@ -0,0 +1 @@ +1320 diff --git a/Task/Maximum-triangle-path-sum/jq/maximum-triangle-path-sum.jq b/Task/Maximum-triangle-path-sum/Jq/maximum-triangle-path-sum.jq similarity index 100% rename from Task/Maximum-triangle-path-sum/jq/maximum-triangle-path-sum.jq rename to Task/Maximum-triangle-path-sum/Jq/maximum-triangle-path-sum.jq diff --git a/Task/Maximum-triangle-path-sum/Kotlin/maximum-triangle-path-sum.kotlin b/Task/Maximum-triangle-path-sum/Kotlin/maximum-triangle-path-sum.kotlin new file mode 100644 index 0000000000..4381b37973 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Kotlin/maximum-triangle-path-sum.kotlin @@ -0,0 +1,40 @@ +// version 1.1.2 + +val tri = intArrayOf( + 55, + 94, 48, + 95, 30, 96, + 77, 71, 26, 67, + 97, 13, 76, 38, 45, + 7, 36, 79, 16, 37, 68, + 48, 7, 9, 18, 70, 26, 6, + 18, 72, 79, 46, 59, 79, 29, 90, + 20, 76, 87, 11, 32, 7, 7, 49, 18, + 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, + 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, + 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, + 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, + 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, + 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, + 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, + 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, + 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 +) + +fun main(args: Array) { + val triangles = arrayOf(tri.sliceArray(0..9), tri) + for (triangle in triangles) { + val size = triangle.size + val base = ((Math.sqrt(8.0 * size + 1.0) - 1.0)/ 2.0).toInt() + var step = base - 1 + var stepc = 0 + for (i in (size - base - 1) downTo 0) { + triangle[i] += maxOf(triangle[i + step], triangle[i + step + 1]) + if (++stepc == step) { + step-- + stepc = 0 + } + } + println("Maximum total = ${triangle[0]}") + } +} diff --git a/Task/Maximum-triangle-path-sum/Phix/maximum-triangle-path-sum.phix b/Task/Maximum-triangle-path-sum/Phix/maximum-triangle-path-sum.phix new file mode 100644 index 0000000000..d3551f819f --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Phix/maximum-triangle-path-sum.phix @@ -0,0 +1,27 @@ +sequence tri = {{55}, + {94, 48}, + {95, 30, 96}, + {77, 71, 26, 67}, + {97, 13, 76, 38, 45}, + { 7, 36, 79, 16, 37, 68}, + {48, 7, 9, 18, 70, 26, 6}, + {18, 72, 79, 46, 59, 79, 29, 90}, + {20, 76, 87, 11, 32, 7, 7, 49, 18}, + {27, 83, 58, 35, 71, 11, 25, 57, 29, 85}, + {14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55}, + { 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23}, + {92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42}, + {56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72}, + {44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36}, + {85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52}, + { 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15}, + {27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93}} + +-- update each row from last but one upwards, with the larger +-- child, so the first step is to replace 6 with 6+27 or 6+2. +for r=length(tri)-1 to 1 by -1 do + for c=1 to length(tri[r]) do + tri[r][c] += max(tri[r+1][c..c+1]) + end for +end for +?tri[1][1] diff --git a/Task/Maximum-triangle-path-sum/Zkl/maximum-triangle-path-sum-1.zkl b/Task/Maximum-triangle-path-sum/Zkl/maximum-triangle-path-sum-1.zkl new file mode 100644 index 0000000000..744103e1bb --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Zkl/maximum-triangle-path-sum-1.zkl @@ -0,0 +1,8 @@ +tri:=File("triangle.txt").pump(List,fcn(s){ s.strip().split(" ").apply("toInt") }).copy(); +while(tri.len()>1){ + t0:=tri.pop(); + t1:=tri.pop(); + tri.append( [[(it); t1.enumerate(); + 'wrap([(i,t)]){ t + t0[i].max(t0[i+1]) }]]) +} +tri[0][0].println(); diff --git a/Task/Maximum-triangle-path-sum/Zkl/maximum-triangle-path-sum-2.zkl b/Task/Maximum-triangle-path-sum/Zkl/maximum-triangle-path-sum-2.zkl new file mode 100644 index 0000000000..4e7097d4de --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Zkl/maximum-triangle-path-sum-2.zkl @@ -0,0 +1,4 @@ +data:=File("triangle.txt").pump(List,fcn(s){ s.strip().split(" ").apply("toInt") }); +fcn f(x,y,z){ x + y.max(z) } +fcn g(xs,ys){ Utils.zipWith(f,ys,xs,xs[1,*]); } +data.reverse().reduce(g)[0].println(); diff --git a/Task/Maximum-triangle-path-sum/Zkl/maximum-triangle-path-sum-3.zkl b/Task/Maximum-triangle-path-sum/Zkl/maximum-triangle-path-sum-3.zkl new file mode 100644 index 0000000000..6fb0ecaf66 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Zkl/maximum-triangle-path-sum-3.zkl @@ -0,0 +1,11 @@ +lines:=File("triangle.txt").pump(List,fcn(s){ s.strip().split(" ").apply("toInt") }); +d:=lines[-1].copy(); +foreach row in ([lines.len()-2..0,-1]){ + d1:=d[1,*]; + l :=d[0]; + foreach i,u in (lines[row].enumerate()){ + d[i] = u + l.max(r:=d1[i]); + l = r; + } +} +println(d[0]); diff --git a/Task/Maze-generation/Aime/maze-generation.aime b/Task/Maze-generation/Aime/maze-generation.aime index 55fc31b522..cc5f8a42e5 100644 --- a/Task/Maze-generation/Aime/maze-generation.aime +++ b/Task/Maze-generation/Aime/maze-generation.aime @@ -4,36 +4,17 @@ grid_maze(data b, integer N) data d; integer i, j; - j = N; - while (j) { - b_suffix(d, "+---"); - j -= 1; - } - { - b_suffix(d, "+\n"); - } + call_n(N, b_suffix, d, "+---"); + b_suffix(d, "+\n"); - j = N; - while (j) { - b_suffix(d, "| * "); - j -= 1; - } - { - b_suffix(d, "|\n"); - } + call_n(N, b_suffix, d, "| * "); + b_suffix(d, "|\n"); - i = N; - while (i) { - b_extend(b, d); - - i -= 1; - } + call_n(N, b_extend, b, d); b_size(d, N * 4 + 2); - { - b_extend(b, d); - } + b_extend(b, d); } void @@ -50,17 +31,18 @@ walk_cell(data b, integer N, integer line_size, integer x, integer y, while (i < 4) { integer p, q; - p = x + l_q_integer(x_offsets, (r + i) & 3); - q = y + l_q_integer(y_offsets, (r + i) & 3); + p = x + (p = x_offsets[(r + i) & 3]); + q = y_offsets[(r + i) & 3]; + q += y; if (-1 < p && p < line_size && -1 < q && q < line_size * (N * 2 + 1)) { - if (b_text(b, q + p) == '*') { + if (b[q + p] == '*') { walk_cell(b, N, line_size, p, q, x_offsets, y_offsets); - b_replace(b, (q + y) / 2 + (p + x) / 2, ' '); - if (p == x) { - b_replace(b, (q + y) / 2 + p - 1, ' '); - b_replace(b, (q + y) / 2 + p + 1, ' '); + b[(q + y) / 2 + (p + x) / 2] = ' '; + if (p == x) { + b[(q + y) / 2 + p - 1] = ' '; + b[(q + y) / 2 + p + 1] = ' '; } } } @@ -77,14 +59,8 @@ walk_maze(data b, integer N) line_size = N * 4 + 1 + 1; - lb_p_integer(x_offsets, 4); - lb_p_integer(y_offsets, 0); - lb_p_integer(x_offsets, 0); - lb_p_integer(y_offsets, line_size * 2); - lb_p_integer(x_offsets, -4); - lb_p_integer(y_offsets, 0); - lb_p_integer(x_offsets, 0); - lb_p_integer(y_offsets, line_size * -2); + l_bill(x_offsets, 0, 4, 0, -4, 0); + l_bill(y_offsets, 0, 0, line_size * 2, 0, line_size * -2); x = drand(N - 1) * 4 + 2; y = line_size * (drand(N - 1) * 2 + 1); @@ -101,10 +77,9 @@ main(void) N = 10; grid_maze(b, N); - walk_maze(b, N); - o_text(b_string(b)); + o_(b); return 0; } diff --git a/Task/Maze-generation/C/maze-generation-1.c b/Task/Maze-generation/C/maze-generation-1.c deleted file mode 100644 index a3e1685141..0000000000 --- a/Task/Maze-generation/C/maze-generation-1.c +++ /dev/null @@ -1,146 +0,0 @@ -#include -#include -#include -#include - -#define DOUBLE_SPACE 1 - -#if DOUBLE_SPACE -# define SPC " " -#else -# define SPC " " -#endif - -wchar_t glyph[] = L""SPC"│││─┘┐┤─└┌├─┴┬┼"SPC"┆┆┆┄╯╮ ┄╰╭ ┄"; - -typedef unsigned char byte; -enum { N = 1, S = 2, W = 4, E = 8, V = 16 }; - -byte **cell; -int w, h, avail; -#define each(i, x, y) for (i = x; i <= y; i++) - -int irand(int n) -{ - int r, rmax = n * (RAND_MAX / n); - while ((r = rand()) >= rmax); - return r / (RAND_MAX/n); -} - -void show() -{ - int i, j, c; - each(i, 0, 2 * h) { - each(j, 0, 2 * w) { - c = cell[i][j]; - if (c > V) printf("\033[31m"); - printf("%lc", glyph[c]); - if (c > V) printf("\033[m"); - } - putchar('\n'); - } -} - -inline int max(int a, int b) { return a >= b ? a : b; } -inline int min(int a, int b) { return b >= a ? a : b; } - -static int dirs[4][2] = {{-2, 0}, {0, 2}, {2, 0}, {0, -2}}; -void walk(int x, int y) -{ - int i, t, x1, y1, d[4] = { 0, 1, 2, 3 }; - - cell[y][x] |= V; - avail--; - - for (x1 = 3; x1; x1--) - if (x1 != (y1 = irand(x1 + 1))) - i = d[x1], d[x1] = d[y1], d[y1] = i; - - for (i = 0; avail && i < 4; i++) { - x1 = x + dirs[ d[i] ][0], y1 = y + dirs[ d[i] ][1]; - - if (cell[y1][x1] & V) continue; - - /* break walls */ - if (x1 == x) { - t = (y + y1) / 2; - cell[t][x+1] &= ~W, cell[t][x] &= ~(E|W), cell[t][x-1] &= ~E; - } else if (y1 == y) { - t = (x + x1)/2; - cell[y-1][t] &= ~S, cell[y][t] &= ~(N|S), cell[y+1][t] &= ~N; - } - walk(x1, y1); - } -} - -int solve(int x, int y, int tox, int toy) -{ - int i, t, x1, y1; - - cell[y][x] |= V; - if (x == tox && y == toy) return 1; - - each(i, 0, 3) { - x1 = x + dirs[i][0], y1 = y + dirs[i][1]; - if (cell[y1][x1]) continue; - - /* mark path */ - if (x1 == x) { - t = (y + y1)/2; - if (cell[t][x] || !solve(x1, y1, tox, toy)) continue; - - cell[t-1][x] |= S, cell[t][x] |= V|N|S, cell[t+1][x] |= N; - } else if (y1 == y) { - t = (x + x1)/2; - if (cell[y][t] || !solve(x1, y1, tox, toy)) continue; - - cell[y][t-1] |= E, cell[y][t] |= V|E|W, cell[y][t+1] |= W; - } - return 1; - } - - /* backtrack */ - cell[y][x] &= ~V; - return 0; -} - -void make_maze() -{ - int i, j; - int h2 = 2 * h + 2, w2 = 2 * w + 2; - byte **p; - - p = calloc(sizeof(byte*) * (h2 + 2) + w2 * h2 + 1, 1); - - p[1] = (byte*)(p + h2 + 2) + 1; - each(i, 2, h2) p[i] = p[i-1] + w2; - p[0] = p[h2]; - cell = &p[1]; - - each(i, -1, 2 * h + 1) cell[i][-1] = cell[i][w2 - 1] = V; - each(j, 0, 2 * w) cell[-1][j] = cell[h2 - 1][j] = V; - each(i, 0, h) each(j, 0, 2 * w) cell[2*i][j] |= E|W; - each(i, 0, 2 * h) each(j, 0, w) cell[i][2*j] |= N|S; - each(j, 0, 2 * w) cell[0][j] &= ~N, cell[2*h][j] &= ~S; - each(i, 0, 2 * h) cell[i][0] &= ~W, cell[i][2*w] &= ~E; - - avail = w * h; - walk(irand(2) * 2 + 1, irand(h) * 2 + 1); - - /* reset visited marker (it's also used by path finder) */ - each(i, 0, 2 * h) each(j, 0, 2 * w) cell[i][j] &= ~V; - solve(1, 1, 2 * w - 1, 2 * h - 1); - - show(); -} - -int main(int c, char **v) -{ - setlocale(LC_ALL, ""); - if (c < 2 || (w = atoi(v[1])) <= 0) w = 16; - if (c < 3 || (h = atoi(v[2])) <= 0) h = 8; - - make_maze(); - - return 0; -} diff --git a/Task/Maze-generation/C/maze-generation-2.c b/Task/Maze-generation/C/maze-generation-2.c deleted file mode 100644 index 2efb2d9fb3..0000000000 --- a/Task/Maze-generation/C/maze-generation-2.c +++ /dev/null @@ -1,184 +0,0 @@ -#include -#include -#include - -#define CW 10 /* cell width. This decides how big the output is */ - -typedef struct cell_t cell_t, *cell; - -enum { N, E, S, W, V }; -struct cell_t { - unsigned int flags; - cell prev, next, nei[4]; /* neighbors */ -}; - -int sx, sy, sz, w, h; - -#define C(y, x) c[(y) * w + x] -#define P(y, x) pix[(y) * w2 + x] -void draw_maze(cell *c) -{ -#define FOR(a, b) for(a = 0; a < b; a++) - FILE *fp; - int w2 = w * CW + 8, h2 = h * CW + 7; - char *pix = malloc(w2 * h2); - memset(pix, 200, w2 * h2); - - void draw_face(int x, int y, int ww, int hh, int px, int py) { - int i, j, k, l; - cell t; - - px += 2, py += 2; - for (i = py; i <= py + hh * CW; i++) - memset(&P(i, px), 0, ww * CW+1); - - px++, py++; -# define mark(y, x) P(py + CW*i + y, px + CW*j + x) = 255 - FOR (i, hh) FOR (j, ww) { - FOR(k, CW - 1) FOR(l, CW - 1) mark(k, l); - - t = C(y + i, x + j); - if (t->flags & (1 << N)) - FOR (l, CW - 1) mark(-1, l); - if (t->flags & (1 << S)) - FOR (l, CW - 1) mark(CW - 1, l); - if (t->flags & (1 << E)) - FOR (l, CW - 1) mark(l, CW - 1); - if (t->flags & (1 << W)) - FOR (l, CW - 1) mark(l, -1); - } - } - - draw_face(0, 0, sx, sy, 0, 0); - draw_face(0, sy, sx, sz, 0, CW*sy + 1); - draw_face(sx, sy, sy, sz, CW*sx + 1, CW*sy + 1); - draw_face(sx + sy, sy, sx, sz, CW*(sx + sy) + 2, CW*sy + 1); - draw_face(sx + sy + sx, sy, sy, sz, CW*(sx + sy + sx) + 3, CW*sy + 1); - draw_face(sx + sy, sy + sz, sx, sy, CW*(sx + sy) + 2, CW*(sy + sz) + 2); - - fp = fopen("maze.pgm", "w+"); - fprintf(fp, "P5\n%d %d\n255\n", w2, h2); - fwrite(pix, 1, w2 * h2, fp); - fclose(fp); -} - -cell rand_neighbor(cell x) -{ - cell r = 0; - int i, c = 1; - for (i = N; i <= W; i++) { - if (!x->nei[i] || (x->nei[i]->flags & (1 << V))) - continue; - if (rand() % c++ == 0) - r = x->nei[i]; - } - return r; -} - -void link_cells(cell a, cell b) -{ - int i; - for (i = N; i <= W; i++) { - if (a->nei[i] != b) continue; - a->flags |= 1 << i; - break; - } - for (i = N; i <= W; i++) { - if (b->nei[i] != a) continue; - b->flags |= 1 << i; - break; - } -} - -void walk(cell head) -{ - cell tail = head, p, n; - - while (head) { - for (p = head; p; p = n) { - p->flags |= 1 << V; - n = rand_neighbor(p); - if (!n) break; - tail->next = n; - n->prev = tail; - - tail = n; - link_cells(p, n); - } - while (head && !rand_neighbor(head)) head = head->next; - } -} - -void make_maze(void) -{ - int i, j; - int n = (sx * sy + sx * sz + sy * sz) * 2; - cell t, *c; - cell_t * cells; - - w = 2 * sx + 2 * sy, h = sy * 2 + sz; - cells = calloc(sizeof(cell_t), n); - c = calloc(sizeof(cell), w * h); - - for (i = 0; i < sy; i++) - for (j = 0; j < sx; j++) - C(i, j) = cells + --n; - for (; i < sy + sz; i++) - for (j = 0; j < w; j++) - C(i, j) = cells + --n; - for (; i < h; i++) - for (j = sx + sy; j < w - sy; j++) - C(i, j) = cells + --n; - - for (i = 0; i < h; i++) { - for (j = 0; j < w; j++) { - t = C(i, j); - if (!t) continue; - if (i) t->nei[N] = C(i - 1, j); - if (i < h - 1) t->nei[S] = C(i + 1, j); - if (j) t->nei[W] = C(i, j - 1); - if (j < w - 1) t->nei[E] = C(i, j + 1); - } - } - - for (j = 0; j < sx; j++) { - C(0, j)->nei[N] = C(sy, w - sy - j - 1); - C(sy, w - sy - j - 1)->nei[N] = C(0, j); - - C(h - sy - 1, j)->nei[S] = C(h - 1, w - sy - j - 1); - C(h - 1, w - sy - j - 1)->nei[S] = C(h - sy - 1, j); - } - - for (i = sy; i < sy + sz; i++) { - C(i, 0)->nei[W] = C(i, w - 1); - C(i, w - 1)->nei[E] = C(i, 0); - } - - for (i = 0; i < sy; i++) { - C(i, 0)->nei[W] = C(sy, w - sy + i); - C(sy, w - sy + i)->nei[N] = C(i, 0); - - C(i, sx - 1)->nei[E] = C(sy, sx + sy - i - 1); - C(sy, sx + sy - i - 1)->nei[N] = C(i, sx - 1); - - C(h - sy - 1, sx + i)->nei[S] = C(h - 1 - i, sx + sy); - C(h - 1 - i, sx + sy)->nei[W] = C(h - sy - 1, sx + i); - - C(sy + sz + i, w - sy - 1)->nei[E] = C(sy + sz - 1, w - sy + i); - C(sy + sz - 1, w - sy + i)->nei[S] = C(sy + sz + i, w - sy - 1); - } - - walk(C(0, 0)); - draw_maze(c); -} - -int main(int c, char **v) -{ - if (c < 2 || (sx = atoi(v[1])) <= 0) sx = 10; - if (c < 3 || (sy = atoi(v[2])) <= 0) sy = sx; - if (c < 4 || (sz = atoi(v[3])) <= 0) sz = sy; - - make_maze(); - - return 0; -} diff --git a/Task/Maze-generation/Clojure/maze-generation.clj b/Task/Maze-generation/Clojure/maze-generation.clj new file mode 100644 index 0000000000..393d621359 --- /dev/null +++ b/Task/Maze-generation/Clojure/maze-generation.clj @@ -0,0 +1,94 @@ +(ns maze.core + (:require [clojure.set :refer [intersection + select]] + [clojure.string :as str])) + +;; Misc functions +(defn neighborhood + ([] (neighborhood [0 0])) + ([coord] (neighborhood coord 1)) + ([[y x] r] + (let [y-- (- y r) y++ (+ y r) + x-- (- x r) x++ (+ x r)] + #{[y++ x] [y-- x] [y x--] [y x++]}))) + +(defn cell-empty? [maze coords] + (= :empty (get-in maze coords))) + +(defn wall? [maze coords] + (= :wall (get-in maze coords))) + +(defn filter-maze + ([pred maze coords] + (select (partial pred maze) (set coords))) + ([pred maze] + (filter-maze + pred + maze + (for [y (range (count maze)) + x (range (count (nth maze y)))] + [y x])))) + +(defn create-empty-maze [width height] + (let [width (inc (* 2 width)) + height (inc (* 2 height))] + (vec (take height + (interleave + (repeat (vec (take width (repeat :wall)))) + (repeat (vec (take width (cycle [:wall :empty]))))))))) + +(defn next-step [possible-steps] + (rand-nth (vec possible-steps))) + +;;Algo +(defn create-random-maze [width height] + (loop [maze (create-empty-maze width height) + stack [] + nonvisited (filter-maze cell-empty? maze) + visited #{} + coords (next-step nonvisited)] + (if (empty? nonvisited) + maze + (let [nonvisited-neighbors (intersection (neighborhood coords 2) nonvisited)] + (cond + (seq nonvisited-neighbors) + (let [next-coords (next-step nonvisited-neighbors) + wall-coords (map #(+ %1 (/ (- %2 %1) 2)) coords next-coords)] + (recur (assoc-in maze wall-coords :empty) + (conj stack coords) + (disj nonvisited next-coords) + (conj visited next-coords) + next-coords)) + + (seq stack) + (recur maze (pop stack) nonvisited visited (last stack))))))) + +;;Conversion to string +(def cell-code->str + [" " " " " " " " "· " "╵ " "╴ " "┘ " + " " " " " " " " "╶─" "└─" "──" "┴─" + " " " " " " " " "╷ " "│ " "┐ " "┤ " + " " " " " " " " "┌─" "├─" "┬─" "┼─"]) + +(defn cell-code [maze coord] + (transduce + (comp + (map (partial wall? maze)) + (keep-indexed (fn [idx el] (when el idx))) + (map (partial bit-shift-left 1))) + (completing bit-or) + 0 + (sort (cons coord (neighborhood coord))))) + +(defn cell->str [maze coord] + (get cell-code->str (cell-code maze coord))) + +(defn maze->str [maze] + (->> (for [y (range (count maze))] + (for [x (range (count (nth maze y)))] + (cell->str maze [y x]))) + (map str/join) + (str/join \newline))) + +;;Task +(println (maze->str (create-random-maze 10 10))) diff --git a/Task/Maze-generation/Julia/maze-generation.julia b/Task/Maze-generation/Julia/maze-generation.julia index f34b6cc82a..1a20b49c8f 100644 --- a/Task/Maze-generation/Julia/maze-generation.julia +++ b/Task/Maze-generation/Julia/maze-generation.julia @@ -2,7 +2,7 @@ function walk(maze, cell, visited = Any[]) push!(visited, cell) for neigh in shuffle(neighbors(cell, size(maze))) if !(neigh in visited) - maze[round(Int,(cell+neigh)/2)...] = 0 # ifloor(n/2) == n >> 1 + maze[round.(Int,(cell+neigh)/2)...] = 0 walk(maze, neigh, visited) end end @@ -17,7 +17,7 @@ maze(w, h) = walk([i%2|j%2 for i=1:2w+1,j=1:2h+1], 2*[rand(1:w),rand(1:h)]) pprint(matrix) = for i = 1:size(matrix,1) println(join(matrix[i,:])) end -function printmaze(maze, wall = convert(UTF32String, "╹╸┛╺┗━┻╻┃┓┫┏┣┳╋")) +function printmaze(maze, wall = split("╹ ╸ ┛ ╺ ┗ ━ ┻ ╻ ┃ ┓ ┫ ┏ ┣ ┳ ╋")) h,w = size(maze) pprint([ maze[i,j] == 0 ? ' ' : wall[Int(sum(c-> 2.0^.5(3c[1]+c[2]+3), diff --git a/Task/Maze-generation/Kotlin/maze-generation.kotlin b/Task/Maze-generation/Kotlin/maze-generation.kotlin index 3ee17bbf75..d0bcc66340 100644 --- a/Task/Maze-generation/Kotlin/maze-generation.kotlin +++ b/Task/Maze-generation/Kotlin/maze-generation.kotlin @@ -1,8 +1,10 @@ -import shuffle.shuffle +import java.util.* + +class MazeGenerator(val x: Int, val y: Int) { + private val maze = Array(x) { IntArray(y) } -class Maze_generator(val x: Int, val y: Int) { fun generate(cx: Int, cy: Int) { - arrayOf(*DIR.values()).shuffle().forEach { + Direction.values().shuffle().forEach { val nx = cx + it.dx val ny = cy + it.dy if (between(nx, x) && between(ny, y) && maze[nx][ny] == 0) { @@ -31,10 +33,16 @@ class Maze_generator(val x: Int, val y: Int) { println('+') } - private enum class DIR(val bit: Int, val dx: Int, val dy: Int) { + inline private fun Array.shuffle(): Array { + val list = toMutableList() + Collections.shuffle(list) + return list.toTypedArray() + } + + private enum class Direction(val bit: Int, val dx: Int, val dy: Int) { N(1, 0, -1), S(2, 0, 1), E(4, 1, 0),W(8, -1, 0); - var opposite: DIR? = null + var opposite: Direction? = null companion object { init { @@ -47,14 +55,12 @@ class Maze_generator(val x: Int, val y: Int) { } private fun between(v: Int, upper: Int) = v >= 0 && v < upper - - private val maze = Array(x) { IntArray(y) } } fun main(args: Array) { val x = if (args.size >= 1) args[0].toInt() else 8 val y = if (args.size == 2) args[1].toInt() else 8 - with(Maze_generator(x, y)) { + with(MazeGenerator(x, y)) { generate(0, 0) display() } diff --git a/Task/Maze-generation/Lua/maze-generation-1.lua b/Task/Maze-generation/Lua/maze-generation-1.lua deleted file mode 100644 index 72a3e8b265..0000000000 --- a/Task/Maze-generation/Lua/maze-generation-1.lua +++ /dev/null @@ -1,17 +0,0 @@ -Stack = {} - -function Stack:Create() - local stack = {} - - function stack:push(item) - self[#self + 1] = item - end - - function stack:pop() - local item = self[#self] - self[#self] = nil - return item - end - - return stack -end diff --git a/Task/Maze-generation/Lua/maze-generation-2.lua b/Task/Maze-generation/Lua/maze-generation-2.lua deleted file mode 100644 index e0f5d29ee4..0000000000 --- a/Task/Maze-generation/Lua/maze-generation-2.lua +++ /dev/null @@ -1,114 +0,0 @@ -require "stack" - -Maze = -{ - directions = - { - north = { x = 0, y = -1 }, - east = { x = 1, y = 0 }, - south = { x = 0, y = 1 }, - west = { x = -1, y = 0 } - } -} - -function Maze:Create(width, height, closed) - -- Actual maze setup - local maze = {} - for y = 1, height do - maze[y] = {} - for x = 1, width do - maze[y][x] = { east = self:CreateDoor(closed), south = self:CreateDoor(closed)} - - -- Doors are shared beetween the cells to avoid out of sync conditions and data dublication - if x ~= 1 then maze[y][x].west = maze[y][x - 1].east - else maze[y][x].west = self:CreateDoor(closed) end - - if y ~= 1 then maze[y][x].north = maze[y - 1][x].south - else maze[y][x].north = self:CreateDoor(closed) end - end - end - - function maze:resetDoors(close) - for y = 1, #self do - self[y][#self[1]].east:setOpened(not close) - - for i, cell in ipairs(self[y]) do - cell.north:setOpened(not close) - cell.west:setOpened(not close) - end - end - - for i, cell in ipairs(self[#self]) do - cell.south:setOpened(not close) - end - end - - function maze:resetVisited() - for y = 1, #self do - for x = 1, #self[1] do - self[y][x].visited = nil - end - end - end - - function maze:tostring(wall, passage) - wall = wall or "#" - passage = passage or " " - - local result = "" - - local verticalBorder = "" - for i = 1, #self[1] do - verticalBorder = verticalBorder .. wall .. (self[1][i].north:isClosed() and wall or passage) - end - verticalBorder = verticalBorder .. wall - result = result .. verticalBorder .. "\n" - - for y, row in ipairs(self) do - local line = row[1].west:isClosed() and wall or passage - local underline = wall - for x, cell in ipairs(row) do - line = line .. " " .. (cell.east:isClosed() and wall or passage) - underline = underline .. (cell.south:isClosed() and wall or passage) .. wall - end - result = result .. line .. "\n" .. underline .. "\n" - end - - return result - end - - return maze -end - - --- This function was designed to be easily replaced by the function generating Legend of Grimrock doors -function Maze:CreateDoor(closed) - local door = {} - door._closed = closed and true or false - - function door:isClosed() - return self._closed - end - - function door:isOpened() - return not self._closed - end - - function door:close() - self._closed = true - end - - function door:open() - self._closed = false - end - - function door:setOpened(opened) - if opened then - self:open() - else - self:close() - end - end - - return door -end diff --git a/Task/Maze-generation/Lua/maze-generation-3.lua b/Task/Maze-generation/Lua/maze-generation-3.lua deleted file mode 100644 index 9a579c437c..0000000000 --- a/Task/Maze-generation/Lua/maze-generation-3.lua +++ /dev/null @@ -1,41 +0,0 @@ -require "maze" - --- Backtracker algorithm (a variation of the recursive backtracker algorithm made without recursion) -function Maze:Backtracker(maze) - maze:resetDoors(true) - - local stack = Stack:Create() - - local cell = { x = 1, y = 1 } - while true do - maze[cell.y][cell.x].visited = true - - -- Gathering all possible travel direction in a list - local directions = {} - for key, value in pairs(self.directions) do - local newPos = { x = cell.x + value.x, y = cell.y + value.y } - -- Checking if the targeted cell is in bounds and was not visited previously - if maze[newPos.y] and maze[newPos.y][newPos.x] and not maze[newPos.y][newPos.x].visited then - directions[#directions + 1] = { name = key, pos = newPos } - end - end - - -- If there are no possible travel directions - backtracking - if #directions == 0 then - if #stack > 0 then - cell = stack:pop() - goto countinue - else break end -- Stack is empty and there are no possible directions - maze is generated - end - - -- Choosing a random direction from a list of possible direction and carving - stack:push(cell) - local dir = directions[math.random(#directions)] - maze[cell.y][cell.x][dir.name]:open() - cell = dir.pos - - ::countinue:: - end - - maze:resetVisited() -end diff --git a/Task/Maze-generation/Lua/maze-generation-4.lua b/Task/Maze-generation/Lua/maze-generation-4.lua deleted file mode 100644 index be684280ac..0000000000 --- a/Task/Maze-generation/Lua/maze-generation-4.lua +++ /dev/null @@ -1,9 +0,0 @@ -require "maze" -require "backtracker" - -maze = Maze:Create(30, 10, true) ---[[ Maze generation depends on the random seed, so you will get exactly - identical maze every time you pass exactly identical seed ]] -math.randomseed(os.time()) -Maze:Backtracker(maze) -print(maze:tostring()) diff --git a/Task/Maze-generation/PHP/maze-generation.php b/Task/Maze-generation/PHP/maze-generation.php deleted file mode 100644 index 5f29db1ccb..0000000000 --- a/Task/Maze-generation/PHP/maze-generation.php +++ /dev/null @@ -1,246 +0,0 @@ -x = $x; - $this->y = $y; - $this->r = $r; - $this->b = $b; - $this->c = $c; - $this->f = hexrgb($f); - $this->m = hexrgb($m); - $this->e = hexrgb($e); - $this->s = hexrgb($s); - } - -// Checks if cell is a closed room - - function isroom($x, $y) - { - return((empty($this->H[$x][$y]) - && empty($this->V[$x][$y]) - && empty($this->H[$x][$y+1]) - && empty($this->V[$x+1][$y])) ? true : false); - } - -// Save the stack as solution path - - function save(&$x, &$y, &$m) - { - if ($this->r == 1 && $x == $this->x - 1 && $y == $this->y - 1) - { - $this->r = $m; - array_push($this->r, array($x, $y)); - } - } - -// Dig the maze - - function dig() - { - $x = 0; - $y = 0; - $cc = $this->x * $this->y; - $v = 1; - $m = array(); - while ($v < $cc) - { - $c = ''; - if ($y > 0 && $this->isroom($x, $y - 1)) - $c .= 'N'; - if ($y < $this->y - 1 && $this->isroom($x, $y + 1)) - $c .= 'S'; - if ($x < $this->x - 1 && $this->isroom($x + 1, $y)) - $c .= 'E'; - if ($x > 0 && $this->isroom($x - 1, $y)) - $c .= 'W'; - if ($c) - { - $v++; - array_push($m, array($x, $y)); - $d = $c[rand(0, strlen($c) - 1)]; - if ($d == 'N') - $this->H[$x][$y--] = true; - if ($d == 'S') - $this->H[$x][$y++ + 1] = true; - if ($d == 'E') - $this->V[$x++ + 1][$y] = true; - if ($d == 'W') - $this->V[$x--][$y] = true; - } - else - list($x, $y) = array_pop($m); - $this->save($x, $y, $m); - } - $this->save($x, $y, $m); - $this->V[0][0] = 1; - $this->V[$this->x][$this->y - 1] = 1; - } - -// Draw the maze full grid - - function grid(&$m) - { - for ($y = 0; $y <= $this->y; ++$y) - { - imagefilledrectangle($this->i, 0, $y * ($this->c + $this->b), - $this->b + $this->x * ($this->c + $this->b) - 1, - $this->b + $y * ($this->c + $this->b) - 1, - $m); - } - for ($x = 0; $x <= $this->x; ++$x) - { - imagefilledrectangle($this->i, $x * ($this->c + $this->b), 0, - $this->b + $x * ($this->c + $this->b) - 1, - $this->b + $this->y * ($this->c + $this->b) - 1, - $m); - } - } - -// Breaks the horizontal walls - - function line($x, $y, &$f) - { - imagefilledrectangle($this->i, - $x * ($this->c + $this->b) + $this->b, - $y * ($this->c + $this->b), - $x * ($this->c + $this->b) + $this->b + $this->c - 1, - $y * ($this->c + $this->b) + $this->b, - $f); - } - -// Breaks the vertical walls - - function col($x, $y, &$f) - { - imagefilledrectangle($this->i, - $x * ($this->c + $this->b), - $y * ($this->c + $this->b) + $this->b, - $x * ($this->c + $this->b) + $this->b, - $y * ($this->c + $this->b) + $this->b + $this->c - 1, - $f); - } - -// Breaks the walls - - function dot(&$f) - { - for ($x = 0; $x <= $this->x; ++$x) - { - for ($y = 0; $y <= $this->y; ++$y) - { - if (isset($this->H[$x][$y])) - $this->line($x, $y, $f); - if (isset($this->V[$x][$y])) - $this->col($x, $y, $f); - } - } - } - -// Fill color cell - - function cellfill(&$x, &$y, &$c) - { - imagefilledrectangle($this->i, - $x * ($this->c + $this->b) + $this->b, - $y * ($this->c + $this->b) + $this->b, - $x * ($this->c + $this->b) + $this->b + $this->c - 1, - $y * ($this->c + $this->b) + $this->b + $this->c - 1, - $c); - } - -// Draw solution - - function path() - { - $l = count($this->r); - for ($i = 0; $i < $l; ++$i) - { - list($x, $y) = $this->r[$i]; - $r = ($this->e[0] * ($l - $i) + $this->s[0] * $i) / $l; - $g = ($this->e[1] * ($l - $i) + $this->s[1] * $i) / $l; - $b = ($this->e[2] * ($l - $i) + $this->s[2] * $i) / $l; - if (!isset($c[$r][$g][$b])) - $c[$r][$g][$b] = imagecolorallocate($this->i, $r, $g, $b); - $this->cellfill($x, $y, $c[$r][$g][$b]); - if (isset($ox, $oy)) - { - if ($ox - $x == -1) - $this->col($x, $y, $c[$r][$g][$b]); - if ($oy - $y == -1) - $this->line($x, $y, $c[$r][$g][$b]); - if ($ox - $x == 1) - $this->col($ox, $oy, $c[$r][$g][$b]); - if ($oy - $y == 1) - $this->line($ox, $oy, $c[$r][$g][$b]); - } - if ($i == 0) - $this->col(0, 0, $c[$r][$g][$b]); - if ($i == $l - 1) - $this->col($x + 1, $y, $c[$r][$g][$b]); - $ox = $x; - $oy = $y; - } - } - -// Call digger and make rendering - - function __destruct() - { - $this->dig(); - $this->i = imagecreatetruecolor( - $this->b + $this->x * ($this->c + $this->b), - $this->b + $this->y * ($this->c + $this->b)); - $f = rgbc($this->i, $this->f); - $m = rgbc($this->i, $this->m); - unset($this->f, $this->m); - imagefill($this->i, 0, 0, $f); - $this->grid($m); - $this->dot($f); - unset($f, $m, $this->H, $this->V); - if ($this->r) - $this->path(); - unset($this->r, $this->e, $this->s); - header('content-disposition:inline;filename="maze.png"'); - header('cache-control:no-store,no-cache,must-revalidate'); - header('content-type:image/png'); - imagepng($this->i, NULL, 9, PNG_ALL_FILTERS); - imagedestroy($this->i); - } -} diff --git a/Task/Maze-generation/Phix/maze-generation.phix b/Task/Maze-generation/Phix/maze-generation.phix new file mode 100644 index 0000000000..ef0563270c --- /dev/null +++ b/Task/Maze-generation/Phix/maze-generation.phix @@ -0,0 +1,46 @@ +-- +-- grid is eg for w=3,h=2: {"+---+---+---+", -- ("wall") +-- "| ? | ? | ? |", -- ("cell") +-- "+---+---+---+", -- ("wall") +-- "| ? | ? | ? |", -- ("cell") +-- "+---+---+---+", -- ("wall") +-- ""} -- (for a trailing \n) +-- +-- note those ?(x,y) are at [y*2][x*4-1], and we navigate +-- using y=2..2*h (+/-2), x=3..w*4-1 (+/-4) directly. +-- +constant w = 11, h = 8 + +sequence wall = join(repeat("+",w+1),"---")&"\n", + cell = join(repeat("|",w+1)," ? ")&"\n", + grid = split(join(repeat(wall,h+1),cell),'\n') + +procedure amaze(integer x, integer y) + grid[y][x] = ' ' -- mark cell visited + sequence p = shuffle({{x-4,y},{x,y+2},{x+4,y},{x,y-2}}) + for i=1 to length(p) do + integer {nx,ny} = p[i] + if nx>1 and nx1 and ny<=2*h and grid[ny][nx]='?' then + integer mx = (x+nx)/2 + grid[(y+ny)/2][mx-1..mx+1] = ' ' -- knock down wall + amaze(nx,ny) + end if + end for +end procedure + +function heads() + return rand(2)=1 -- 50:50 true(1)/false(0) +end function + +integer {x,y} = {(rand(w)*4)-1,rand(h)*2} +amaze(x,y) +-- mark start pos +grid[y][x] = '*' +-- add a random door (heads=rhs/lhs, tails=top/btm) +if heads() then + grid[rand(h)*2][heads()*w*4-1] = ' ' +else + x = rand(w)*4-1 + grid[heads()*h*2+1][x-1..x+1] = ' ' +end if +puts(1,join(grid,'\n')) diff --git a/Task/Maze-generation/Swift/maze-generation.swift b/Task/Maze-generation/Swift/maze-generation.swift index aad22146fb..8685271d6a 100644 --- a/Task/Maze-generation/Swift/maze-generation.swift +++ b/Task/Maze-generation/Swift/maze-generation.swift @@ -1,109 +1,173 @@ import Foundation -class Direction { - var vect:(Int, Int, Int) - var bit:Int { - let (bit, dx, dy) = vect - return bit +extension Array { + mutating func swap(_ index1:Int, _ index2:Int) { + let temp = self[index1] + self[index1] = self[index2] + self[index2] = temp } - var dx:Int { - let (bit, dx, dy) = vect - return dx - } - - var dy:Int { - let (bit, dx, dy) = vect - return dy - } - - var opposite:Direction { - switch (vect) { - case (1, 0, -1): - return Direction(bit: 2, dx: 0, dy: 1) - case (2, 0, 1): - return Direction(bit: 1, dx: 0, dy: -1) - case (4, 1, 0): - return Direction(bit: 8, dx: -1, dy: 0) - case (8, -1, 0): - return Direction(bit: 4, dx: 1, dy: 0) - default: - return Direction(bit: 0, dx: 0, dy: 0) + mutating func shuffle() { + for _ in 0.. Bool { + return inBounds(value:testX, upper:self.x) && inBounds(value:testY, upper:self.y) + } + + private func inBounds(value:Int, upper:Int) -> Bool { + return (value >= 0) && (value < upper) + } + + func display() { + let cellWidth = 3 + for j in 0.. Bool { - return (v >= 0) && (v < upper) + func displayDirections() { + for j in 0.. String { + var line = "" + for direction in Direction.allDirections { + if (value & direction.rawValue) != 0 { + line += direction.char + } + } + return line } } -let x = 10 + +let x = 20 let y = 10 let maze = MazeGenerator(x, y) maze.display() diff --git a/Task/Maze-generation/Zkl/maze-generation.zkl b/Task/Maze-generation/Zkl/maze-generation.zkl new file mode 100644 index 0000000000..c0183c93e7 --- /dev/null +++ b/Task/Maze-generation/Zkl/maze-generation.zkl @@ -0,0 +1,21 @@ +fcn make_maze(w = 16, h = 8){ + // make arrays with lists of lists (all mutable) + vis:=(w.pump(List().write,0)+1)*h + w.pump(List().write,1); + ver:=(w.pump(List().write,T(Void,"| ")) + "|")*h + T; + hor:=(w.pump(List().write,T(Void,"+---")) + "+")*(h + 1); + + fcn(x,y,vis,ver,hor){ + vis[y][x] = 1; + + 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); + } + }((0).random(w),(0).random(h),vis,ver,hor); + foreach a,b in (hor.zip(ver)) { println(a.concat(),"\n",b.concat()) } + return(ver,hor); +} +make_maze(); diff --git a/Task/Maze-solving/AutoHotkey/maze-solving.ahk b/Task/Maze-solving/AutoHotkey/maze-solving.ahk new file mode 100644 index 0000000000..aba2bb41e0 --- /dev/null +++ b/Task/Maze-solving/AutoHotkey/maze-solving.ahk @@ -0,0 +1,185 @@ +Width := 10, Height := 10 ; set grid size +SleepTime := 0 + +gosub, Startup + +Gui, +AlwaysOnTop +Gui, font, s12, consolas +Gui, add, edit, vEditGrid x10, % maze +Gui, add, button, xs gStartup Default, Generate maze +Gui, add, button, x+10 gSolve, Solve +Gui, show,, maze +GuiControl,, EditGrid, % maze ; show maze +return + +;----------------------------------------------------------------------- +^Esc:: +GuiEscape: +GuiClose: +ExitApp +return + +;----------------------------------------------------------------------- +Startup: +oMaze := [] ; initialize +Solved := false +loop, % Height +{ + row := A_Index + loop, % Width ; create oMaze[row,column] borders + col := A_Index, oMaze[row,col] := "LRTB" ; i.e. oMaze[2,5] := LRTB (add all borders) +} +Random, row, 1, % Height ; random row +Random, col, 1, % Width ; random col +grid := maze2text(oMaze) ; object to text +GuiControl,, EditGrid, % Grid ; show Grid +row := col := 1 ; reset to 1,1 +oMaze := Generate_maze(row, col, oMaze) ; generate maze starting from random row/column +oMaze[1,1] .= "X" ; start from 1,1 +maze := maze2text(oMaze) ; object to text +GuiControl,, EditGrid, % maze ; show maze +GuiControl,, EditRoute ; clear route +GuiControl, Enable, Solve +return + +;----------------------------------------------------------------------- +Solve: +GuiControl, Disable, Generate maze +GuiControl, Disable, Solve +loop % oRoute.MaxIndex() + oRoute.pop() + +oSolution := Solve(1, 1, oMaze) ; solve starting from 1,1 +oMaze := oSolution.1 +oRoute := oSolution.2 +Update(oMaze, oRoute) +Solved := true +GuiControl, Enable, Generate maze +return + +;----------------------------------------------------------------------- +Update(oMaze, oRoute){ + global SleepTime + GuiControl,, EditGrid, % maze2text(oMaze) + Sleep, % SleepTime +} + +;----------------------------------------------------------------------- +maze2text(oMaze){ + width := oMaze.1.MaxIndex() + BLK := "█" + for row, objRow in oMaze + { + for col, val in objRow ; add ceiling + { + ceiling := InStr(oMaze[row, col] , "x") && InStr(oMaze[row-1, col] , "x") ? "+ " BLK " " : "+ " + grid .= (InStr(val, "T") ? "+---" : ceiling) (col = Width ? "+`n" : "") + } + for col, val in objRow ; add left wall + { + wall := SubStr(val, 0) = "X" ? BLK : " " + grid .= (InStr(val, "L") ? "| " : " ") wall " " (col = Width ? "|`n" : "") ; add left wall if needed then outer right border + } + } + Loop % Width + Grid .= "+---" ; add bottom floor + Grid .= "+" ; add right bottom corner + return RegExReplace(grid , BLK " (?=" BLK ")" , BLK BLK BLK BLK) ; fill gaps +} + +;----------------------------------------------------------------------- +Generate_maze(row, col, oMaze) { + neighbors := row+1 "," col "`n" row-1 "," col "`n" row "," col+1 "`n" row "," col-1 + Sort, neighbors, random ; randomize neighbors list + Loop, parse, neighbors, `n ; for each neighbor + { + rowX := StrSplit(A_LoopField, ",").1 ; this neighbor row + colX := StrSplit(A_LoopField, ",").2 ; this neighbor column + if !instr(oMaze[rowX,colX], "LRTB") || !oMaze[rowX, colX] ; if visited (has a missing border) or out of bounds + continue ; skip + + ; remove borders + if (row > rowX) ; Cell is below this neighbor + oMaze[row,col] := StrReplace(oMaze[row,col], "T") , oMaze[rowX,colX] := StrReplace(oMaze[rowX,colX], "B") + else if (row < rowX) ; Cell is above this neighbor + oMaze[row,col] := StrReplace(oMaze[row,col], "B") , oMaze[rowX,colX] := StrReplace(oMaze[rowX,colX], "T") + else if (col > colX) ; Cell is right of this neighbor + oMaze[row,col] := StrReplace(oMaze[row,col], "L") , oMaze[rowX,colX] := StrReplace(oMaze[rowX,colX], "R") + else if (col < colX) ; Cell is left of this neighbor + oMaze[row,col] := StrReplace(oMaze[row,col], "R") , oMaze[rowX,colX] := StrReplace(oMaze[rowX,colX], "L") + + Generate_maze(rowX, colX, oMaze) ; recurse for this neighbor + } + return, oMaze +} + +;----------------------------------------------------------------------- +Solve(row, col, oMaze){ + static oRoute := [] + oNeighbor := [], targetrow := oMaze.MaxIndex(), targetCol := oMaze.1.MaxIndex() + + ;~ Update(oMaze, oRoute) + oRoute.push(row ":" col) ; push current cell address to oRoute + oMaze[row, col] .= "X" ; mark it visited "X" + + if (row = targetrow) && (Col = targetCol) ; if solved + return true ; return ture + + ; create list of Neighbors + oNeighbor[row, col] := [] + if !InStr(oMaze[row, col], "R") ; if no Right border + oNeighbor[row, col].push(row "," col+1) ; add neighbor + if !InStr(oMaze[row, col], "B") ; if no Bottom border + oNeighbor[row, col].push(row+1 "," col) ; add neighbor + if !InStr(oMaze[row, col], "T") ; if no Top border + oNeighbor[row, col].push(row-1 "," col) ; add neighbor + if !InStr(oMaze[row, col], "L") ; if no Left border + oNeighbor[row, col].push(row "," col-1) ; add neighbor + + ; recurese for each oNeighbor + for each, neighbor in oNeighbor[row, col] ; for each neighbor + { + Update(oMaze, oRoute) + startrow := StrSplit(neighbor, ",").1 ; this neighbor + startCol := StrSplit(neighbor, ",").2 ; becomes starting point + + if !InStr(oMaze[startrow, startCol], "X") ; if it was not visited + if Solve(startrow, startCol, oMaze) ; recurse for current neighbor + return [oMaze, oRoute] ; return solution if solved + } + oRoute.pop() ; no solution found, back track + oMaze[row, Col] := StrReplace(oMaze[row, Col], "X") ; no solution found, back track + ;~ Update(oMaze, oRoute) +} + +;----------------------------------------------------------------------- +#IfWinActive, maze +Right:: +Left:: +Up:: +Down:: +if Solved + return + +if (A_ThisHotkey="Right") && (!InStr(oMaze[row,col], "R")) + oMaze[row, col] := StrReplace(oMaze[row, col], "X") , col++ +if (A_ThisHotkey="Left") && (!InStr(oMaze[row,col], "L")) + oMaze[row, col] := StrReplace(oMaze[row, col], "X") , col-- +if (A_ThisHotkey="Up") && (!InStr(oMaze[row,col], "T")) + oMaze[row, col] := StrReplace(oMaze[row, col], "X") , row-- +if (A_ThisHotkey="Down") && (!InStr(oMaze[row,col], "B")) + oMaze[row, col] := StrReplace(oMaze[row, col], "X") , row++ + +oMaze[row, col] .= "X" +GuiControl,, EditGrid, % maze2text(oMaze) + +if (col = Width) && (row = Height) +{ + Solved := true + oMaze[height, width] := StrReplace(oMaze[height, width], "X") + SleepTime := 0 + gosub, solve + return +} +return +#IfWinActive diff --git a/Task/Maze-solving/Clojure/maze-solving.clj b/Task/Maze-solving/Clojure/maze-solving.clj new file mode 100644 index 0000000000..36d1844080 --- /dev/null +++ b/Task/Maze-solving/Clojure/maze-solving.clj @@ -0,0 +1,106 @@ +(ns small-projects.find-shortest-way + (:require [clojure.string :as str])) + +;Misk functions +(defn cell-empty? [maze coords] + (= :empty (get-in maze coords))) + +(defn wall? [maze coords] + (= :wall (get-in maze coords))) + +(defn track? [maze coords] + (= :track (get-in maze coords))) + +(defn get-neighbours [maze [y x cell]] + [[y (dec x)] [(inc y) x] [y (inc x)] [(dec y) x]]) + +(defn get-difference [coll1 filter-coll] + (filter #(not (contains? filter-coll %)) coll1)) + +(defn get-empties [maze cell] + (->> (get-neighbours maze cell) + (filter (partial cell-empty? maze)))) + +(defn possible-ways [maze cell filter-coll] + (-> (get-empties maze cell) + (get-difference filter-coll))) + +(defn replace-cells [maze coords v] + (if (empty? coords) + maze + (recur (assoc-in maze (first coords) v) (rest coords) v))) + +;Print and parse functions +(def cell-code->str + [" " " " " " " " "· " "╵ " "╴ " "┘ " + " " " " " " " " "╶─" "└─" "──" "┴─" + " " " " " " " " "╷ " "│ " "┐ " "┤ " + " " " " " " " " "┌─" "├─" "┬─" "┼─" + " " " " " " " " "■ " "╹ " "╸ " "┛ " + " " " " " " " " "╺━" "┗━" "━━" "┻━" + " " " " " " " " "╻ " "┃ " "┓ " "┫ " + " " " " " " " " "┏━" "┣━" "┳━" "╋━" + " "]) + +(defn get-cell-code [maze coords] + (let [mode (if (track? maze coords) 1 0) + check (if (zero? mode) wall? track?)] + (transduce + (comp + (map (partial check maze)) + (keep-indexed (fn [idx test] (when test idx))) + (map (partial bit-shift-left 1))) + (completing bit-or) + (bit-shift-left mode 5) + (sort (conj (get-neighbours maze coords) coords))))) + +(defn code->str [cell-code] + (nth cell-code->str cell-code)) + +(defn maze->str-symbols [maze] + (for [y (range (count maze))] + (for [x (range (count (nth maze y)))] + (code->str (get-cell-code maze [y x]))))) + +(defn maze->str [maze] + (->> (maze->str-symbols maze) + (map str/join) + (str/join "\n"))) + +(defn parse-pretty-maze [maze-str] + (->> (str/split-lines maze-str) + (map (partial take-nth 2)) + (map (partial map #(if (= \space %) :empty :wall))) + (map vec) + (vec))) + +;Core +(defn find-new-border [maze border old-border] + (apply conj (map (fn [cell] + (zipmap (possible-ways maze cell (conj border old-border)) + (repeat cell))) + (keys border)))) + +(defn backtrack [visited route] + (let [cur-cell (get visited (first route))] + (if (= cur-cell :start) + route + (recur visited (conj route cur-cell))))) + +(defn breadth-first-search [maze start-cell end-cell] + (loop [visited {start-cell :start} + border {start-cell :start} + old-border {start-cell :start}] + (if (contains? old-border end-cell) + (backtrack visited (list end-cell)) + (recur + (conj visited border) + (find-new-border maze border old-border) + border)))) + +(def maze (parse-pretty-maze maze-str)) + +(def solved-maze + (replace-cells maze (breadth-first-search maze [1 1] [19 19]) :track)) + +(println (maze->str solved-maze)) diff --git a/Task/Maze-solving/D/maze-solving.d b/Task/Maze-solving/D/maze-solving.d index ffbac9bd79..487aa5a638 100644 --- a/Task/Maze-solving/D/maze-solving.d +++ b/Task/Maze-solving/D/maze-solving.d @@ -13,6 +13,8 @@ bool solveMaze(char[][] maze, in V2 s, in V2 end) pure nothrow @safe @nogc { foreach (immutable d; [V2(0, -cy), V2(+cx, 0), V2(0, +cy), V2(-cx, 0)]) if (maze[s.y + (d.y / 2)][s.x + (d.x / 2)] == ' ' && maze[s.y + d.y][s.x + d.x] == ' ') { +//Would this help? +// maze[s.y + (d.y / 2)][s.x + (d.x / 2)] = pathSymbol; maze[s.y + d.y][s.x + d.x] = pathSymbol; if (solveMaze(maze, V2(s.x + d.x, s.y + d.y), end)) return true; diff --git a/Task/Maze-solving/Haskell/maze-solving.hs b/Task/Maze-solving/Haskell/maze-solving.hs index 80b9541154..c3355e340c 100644 --- a/Task/Maze-solving/Haskell/maze-solving.hs +++ b/Task/Maze-solving/Haskell/maze-solving.hs @@ -1,10 +1,10 @@ #!/usr/bin/runhaskell -import Data.Maybe +import Data.Maybe (fromMaybe) -- given two points, returns the average of them average :: (Int, Int) -> (Int, Int) -> (Int, Int) -average (x, y) (x', y') = ((x + x') `div` 2, (y + y') `div` 2) +average (x, y) (x_, y_) = ((x + x_) `div` 2, (y + y_) `div` 2) -- given a maze and a tuple of position and wall position, returns -- true if the wall position is not blocked (first position is unused) @@ -22,41 +22,47 @@ substitute orig pos el = -- given a maze and a position, draw a '*' at that position in the maze draw :: [String] -> (Int, Int) -> [String] -draw maze (x,y) = substitute maze y $ substitute row x '*' - where row = maze !! y +draw maze (x, y) = + let row = maze !! y + in substitute maze y $ substitute row x '*' -- given a maze, a previous position, and a list of tuples of potential -- new positions and their wall positions, returns the solved maze, or -- None if it cannot be solved -tryMoves :: [String] -> (Int, Int) -> [((Int, Int), (Int, Int))] -> Maybe [String] +tryMoves :: [String] + -> (Int, Int) + -> [((Int, Int), (Int, Int))] + -> Maybe [String] tryMoves _ _ [] = Nothing -tryMoves maze prevPos ((newPos,wallPos):more) = - case solve' maze newPos prevPos - of Nothing -> tryMoves maze prevPos more - Just maze' -> Just $ foldl draw maze' [newPos, wallPos] +tryMoves maze prevPos ((newPos, wallPos):more) = + case solve_ maze newPos prevPos of + Nothing -> tryMoves maze prevPos more + Just maze_ -> Just $ foldl draw maze_ [newPos, wallPos] -- given a maze, a new position, and a previous position, returns -- the solved maze, or None if it cannot be solved -- (assumes goal is upper-left corner of maze) -solve' :: [String] -> (Int, Int) -> (Int, Int) -> Maybe [String] -solve' maze (2, 1) _ = Just maze -solve' maze pos@(x, y) prevPos = +solve_ :: [String] -> (Int, Int) -> (Int, Int) -> Maybe [String] +solve_ maze (2, 1) _ = Just maze +solve_ maze pos@(x, y) prevPos = let newPositions = [(x, y - 2), (x + 4, y), (x, y + 2), (x - 4, y)] - notPrev pos' = pos' /= prevPos - newPositions' = filter notPrev newPositions - wallPositions = map (average pos) newPositions' - zipped = zip newPositions' wallPositions + notPrev pos_ = pos_ /= prevPos + newPositions_ = filter notPrev newPositions + wallPositions = map (average pos) newPositions_ + zipped = zip newPositions_ wallPositions legalMoves = filter (notBlocked maze) zipped in tryMoves maze pos legalMoves -- given a maze, returns a solved maze, or None if it cannot be solved -- (starts at lower right corner and goes to upper left corner) solve :: [String] -> Maybe [String] -solve maze = solve' (draw maze start) start (-1, -1) - where startx = length (head maze) - 3 - starty = length maze - 2 - start = (startx, starty) +solve maze = solve_ (draw maze start) start (-1, -1) + where + startx = length (head maze) - 3 + starty = length maze - 2 + start = (startx, starty) -- takes unsolved maze on standard input, prints solved maze on standard output -main = interact main' - where main' x = unlines $ fromMaybe ["can't solve"] $ solve $ lines x +main = + let main_ = unlines . fromMaybe ["can_t solve"] . solve . lines + in interact main_ diff --git a/Task/Maze-solving/JavaScript/maze-solving.js b/Task/Maze-solving/JavaScript/maze-solving.js new file mode 100644 index 0000000000..82a705ea7b --- /dev/null +++ b/Task/Maze-solving/JavaScript/maze-solving.js @@ -0,0 +1,135 @@ +var ctx, wid, hei, cols, rows, maze, stack = [], start = {x:-1, y:-1}, end = {x:-1, y:-1}, grid = 8; +function drawMaze() { + for( var i = 0; i < cols; i++ ) { + for( var j = 0; j < rows; j++ ) { + switch( maze[i][j] ) { + case 0: ctx.fillStyle = "black"; break; + case 1: ctx.fillStyle = "green"; break; + case 2: ctx.fillStyle = "red"; break; + case 3: ctx.fillStyle = "yellow"; break; + case 4: ctx.fillStyle = "#500000"; break; + } + ctx.fillRect( grid * i, grid * j, grid, grid ); + } + } +} +function getFNeighbours( sx, sy, a ) { + var n = []; + if( sx - 1 > 0 && maze[sx - 1][sy] == a ) { + n.push( { x:sx - 1, y:sy } ); + } + if( sx + 1 < cols - 1 && maze[sx + 1][sy] == a ) { + n.push( { x:sx + 1, y:sy } ); + } + if( sy - 1 > 0 && maze[sx][sy - 1] == a ) { + n.push( { x:sx, y:sy - 1 } ); + } + if( sy + 1 < rows - 1 && maze[sx][sy + 1] == a ) { + n.push( { x:sx, y:sy + 1 } ); + } + return n; +} +function solveMaze() { + if( start.x == end.x && start.y == end.y ) { + for( var i = 0; i < cols; i++ ) { + for( var j = 0; j < rows; j++ ) { + switch( maze[i][j] ) { + case 2: maze[i][j] = 3; break; + case 4: maze[i][j] = 0; break; + } + } + } + drawMaze(); + return; + } + var neighbours = getFNeighbours( start.x, start.y, 0 ); + if( neighbours.length ) { + stack.push( start ); + start = neighbours[0]; + maze[start.x][start.y] = 2; + } else { + maze[start.x][start.y] = 4; + start = stack.pop(); + } + + drawMaze(); + requestAnimationFrame( solveMaze ); +} +function getCursorPos( event ) { + var rect = this.getBoundingClientRect(); + var x = Math.floor( ( event.clientX - rect.left ) / grid ), + y = Math.floor( ( event.clientY - rect.top ) / grid ); + if( maze[x][y] ) return; + if( start.x == -1 ) { + start = { x: x, y: y }; + } else { + end = { x: x, y: y }; + maze[start.x][start.y] = 2; + solveMaze(); + } +} +function getNeighbours( sx, sy, a ) { + var n = []; + if( sx - 1 > 0 && maze[sx - 1][sy] == a && sx - 2 > 0 && maze[sx - 2][sy] == a ) { + n.push( { x:sx - 1, y:sy } ); n.push( { x:sx - 2, y:sy } ); + } + if( sx + 1 < cols - 1 && maze[sx + 1][sy] == a && sx + 2 < cols - 1 && maze[sx + 2][sy] == a ) { + n.push( { x:sx + 1, y:sy } ); n.push( { x:sx + 2, y:sy } ); + } + if( sy - 1 > 0 && maze[sx][sy - 1] == a && sy - 2 > 0 && maze[sx][sy - 2] == a ) { + n.push( { x:sx, y:sy - 1 } ); n.push( { x:sx, y:sy - 2 } ); + } + if( sy + 1 < rows - 1 && maze[sx][sy + 1] == a && sy + 2 < rows - 1 && maze[sx][sy + 2] == a ) { + n.push( { x:sx, y:sy + 1 } ); n.push( { x:sx, y:sy + 2 } ); + } + return n; +} +function createArray( c, r ) { + var m = new Array( c ); + for( var i = 0; i < c; i++ ) { + m[i] = new Array( r ); + for( var j = 0; j < r; j++ ) { + m[i][j] = 1; + } + } + return m; +} +function createMaze() { + var neighbours = getNeighbours( start.x, start.y, 1 ), l; + if( neighbours.length < 1 ) { + if( stack.length < 1 ) { + drawMaze(); stack = []; + start.x = start.y = -1; + document.getElementById( "canvas" ).addEventListener( "mousedown", getCursorPos, false ); + return; + } + start = stack.pop(); + } else { + var i = 2 * Math.floor( Math.random() * ( neighbours.length / 2 ) ) + l = neighbours[i]; maze[l.x][l.y] = 0; + l = neighbours[i + 1]; maze[l.x][l.y] = 0; + start = l + stack.push( start ) + } + drawMaze(); + requestAnimationFrame( createMaze ); +} +function createCanvas( w, h ) { + var canvas = document.createElement( "canvas" ); + wid = w; hei = h; + canvas.width = wid; canvas.height = hei; + canvas.id = "canvas"; + ctx = canvas.getContext( "2d" ); + ctx.fillStyle = "black"; ctx.fillRect( 0, 0, wid, hei ); + document.body.appendChild( canvas ); +} +function init() { + cols = 73; rows = 53; + createCanvas( grid * cols, grid * rows ); + maze = createArray( cols, rows ); + start.x = Math.floor( Math.random() * ( cols / 2 ) ); + start.y = Math.floor( Math.random() * ( rows / 2 ) ); + if( !( start.x & 1 ) ) start.x++; if( !( start.y & 1 ) ) start.y++; + maze[start.x][start.y] = 0; + createMaze(); +} diff --git a/Task/Maze-solving/Phix/maze-solving.phix b/Task/Maze-solving/Phix/maze-solving.phix new file mode 100644 index 0000000000..3a38c5b419 --- /dev/null +++ b/Task/Maze-solving/Phix/maze-solving.phix @@ -0,0 +1,58 @@ +constant w = 11, h = 8 + +sequence wall = join(repeat("+",w+1),"---")&"\n", + cell = join(repeat("|",w+1)," ? ")&"\n", + grid = split(join(repeat(wall,h+1),cell),'\n') + +procedure amaze(integer x, integer y) + grid[y][x] = ' ' -- mark cell visited + sequence p = shuffle({{x-4,y},{x,y+2},{x+4,y},{x,y-2}}) + for i=1 to length(p) do + integer {nx,ny} = p[i] + if nx>1 and nx1 and ny<=2*h and grid[ny][nx]='?' then + integer mx = (x+nx)/2 + grid[(y+ny)/2][mx-1..mx+1] = ' ' -- knock down wall + amaze(nx,ny) + end if + end for +end procedure + +integer dx,dy -- door location (in a wall!) + +function solve_maze(integer x, y) + sequence p = {{x-4,y},{x,y+2},{x+4,y},{x,y-2}} + for d=1 to length(p) do + integer {nx,ny} = p[d] + integer {wx,wy} = {(x+nx)/2,(y+ny)/2} + if grid[wy][wx]=' ' then + grid[wy][wx] = "-:-:"[d] -- mark path + if {wx,wy}={dx,dy} then return true end if + if grid[ny][nx]=' ' then + grid[ny][nx] = 'o' -- mark cell + if solve_maze(nx,ny) then return true end if + grid[ny][nx] = ' ' -- unmark cell + end if + grid[wy][wx] = ' ' -- unmark path + end if + end for + return false +end function + +function heads() + return rand(2)=1 -- toin coss 50:50 true(1)/false(0) +end function + +integer {x,y} = {(rand(w)*4)-1,rand(h)*2} +amaze(x,y) +-- mark start pos +grid[y][x] = '*' +-- add a random door (heads=rhs/lhs, tails=top/btm) +if heads() then + {dy,dx} = {rand(h)*2,heads()*w*4+1} + grid[dy][dx] = ' ' +else + {dy,dx} = {heads()*h*2+1,rand(w)*4-1} + grid[dy][dx-1..dx+1] = ' ' +end if +{} = solve_maze(x,y) +puts(1,join(grid,'\n')) diff --git a/Task/Maze-solving/Zkl/maze-solving.zkl b/Task/Maze-solving/Zkl/maze-solving.zkl new file mode 100644 index 0000000000..a6afcf8fa6 --- /dev/null +++ b/Task/Maze-solving/Zkl/maze-solving.zkl @@ -0,0 +1,43 @@ +ver,hor:=make_maze(); // see above link for this code + +fcn munge(a,b){ String(a[0,2],b,a[3,*]) } // "+---" --> "+-*-" + +fcn solveMaze(ver,hor, a,b, u,v, w,h){ + if (a==u and b==v) return(True); + + sh:=hor[b][a]; sv:=ver[b][a]; + hor[b][a]=munge(sh,"*"); ver[b][a]=munge(sv,"*"); // drop breadcrumb + + foreach dx,dy in (T( T(0,-1),T(1,0),T(0,1),T(-1,0) )){ + x:=a+dx; y:=b+dy; hy:=hor[y]; vy:=ver[y]; + if ( (0<=xnew image + var [const] window=[-2..2].walk(), edge=(window.len()/2); // 5x5 window + + MX,MY,new := img.w,img.h,PPM(MX,MY); + pixel,pixels:=List(),List(); + foreach x,y in ([edge..MX-edge-1],[edge..MY-edge-1]){ + pixels.clear(); + foreach ox,oy in (window,window){ // construct sorted list as pixels are read. + pixels.merge(pixel.clear(img[x+ox, y+oy])); // merge sort two lists + } + new[x,y]=pixels[4]; // median value + } + new +} diff --git a/Task/Median-filter/Zkl/median-filter-2.zkl b/Task/Median-filter/Zkl/median-filter-2.zkl new file mode 100644 index 0000000000..21cd78fefc --- /dev/null +++ b/Task/Median-filter/Zkl/median-filter-2.zkl @@ -0,0 +1,2 @@ +filtered:=medianFilter(PPM.readJPGFile("lena.jpg")); +filtered.writeJPGFile("lenaMedianFiltered.zkl.jpg"); diff --git a/Task/Memory-allocation/ALGOL-W/memory-allocation.alg b/Task/Memory-allocation/ALGOL-W/memory-allocation.alg new file mode 100644 index 0000000000..0094137d2c --- /dev/null +++ b/Task/Memory-allocation/ALGOL-W/memory-allocation.alg @@ -0,0 +1,10 @@ +begin + % define a record structure - instances must be created dynamically % + record Element ( integer atomicNumber; string(16) name ); + reference(Element) X; + % allocate and initialise memory for X - heap storage is the only option % + X := Element( 1, "Hydrogen" ); + % allocate new memory for X, the original could now be garbage collected % + X := Element( 2, "Helium" ) + % the memory allocated will now be garbage collected - there is no explicit de-allocation % +end. diff --git a/Task/Memory-allocation/Kotlin/memory-allocation.kotlin b/Task/Memory-allocation/Kotlin/memory-allocation.kotlin new file mode 100644 index 0000000000..c6431735eb --- /dev/null +++ b/Task/Memory-allocation/Kotlin/memory-allocation.kotlin @@ -0,0 +1,30 @@ +// version 1.1.2 + +class MyClass(val myInt: Int) { + // in theory this method should be called automatically prior to GC + protected fun finalize() { + println("MyClass being finalized...") + } +} + +fun myFun() { + val mc: MyClass = MyClass(2) // new non-nullable MyClass object allocated on the heap + println(mc.myInt) + var mc2: MyClass? = MyClass(3) // new nullable MyClass object allocated on the heap + println(mc2?.myInt) + mc2 = null // allowed as mc2 is nullable + println(mc2?.myInt) + // 'mc' and 'mc2' both become eligible for garbage collection here as no longer used +} + +fun main(args: Array) { + myFun() + Thread.sleep(3000) // allow time for GC to execute + val i: Int = 4 // new non-nullable Int allocated on stack + println(i) + var j: Int? = 5 // new nullable Int allocated on heap + println(j) + j = null // allowed as 'j' is nullable + println(j) + // 'j' becomes eligible for garbage collection here as no longer used +} diff --git a/Task/Memory-allocation/Sinclair-ZX81-BASIC/memory-allocation-1.sinclair b/Task/Memory-allocation/Sinclair-ZX81-BASIC/memory-allocation-1.sinclair new file mode 100644 index 0000000000..dddd00430d --- /dev/null +++ b/Task/Memory-allocation/Sinclair-ZX81-BASIC/memory-allocation-1.sinclair @@ -0,0 +1 @@ +PRINT PEEK 16388+256*16389 diff --git a/Task/Memory-allocation/Sinclair-ZX81-BASIC/memory-allocation-2.sinclair b/Task/Memory-allocation/Sinclair-ZX81-BASIC/memory-allocation-2.sinclair new file mode 100644 index 0000000000..602fb124a9 --- /dev/null +++ b/Task/Memory-allocation/Sinclair-ZX81-BASIC/memory-allocation-2.sinclair @@ -0,0 +1,9 @@ +10 REM ABCDEFGH +20 LET P$="3E03010400814FC9" +30 LET ADDR=16514 +40 POKE ADDR,CODE P$*16+CODE P$(2)-476 +50 LET P$=P$(3 TO ) +60 LET ADDR=ADDR+1 +70 IF P$<>"" THEN GOTO 40 +80 CLEAR +90 PRINT USR 16514 diff --git a/Task/Memory-allocation/Sinclair-ZX81-BASIC/memory-allocation-3.sinclair b/Task/Memory-allocation/Sinclair-ZX81-BASIC/memory-allocation-3.sinclair new file mode 100644 index 0000000000..39de81cbb1 --- /dev/null +++ b/Task/Memory-allocation/Sinclair-ZX81-BASIC/memory-allocation-3.sinclair @@ -0,0 +1,5 @@ +3e 03 ld a, 3 +01 04 00 ld bc,0004 +81 add a, c +4f ld c, a +c9 ret diff --git a/Task/Memory-allocation/Sinclair-ZX81-BASIC/memory-allocation-4.sinclair b/Task/Memory-allocation/Sinclair-ZX81-BASIC/memory-allocation-4.sinclair new file mode 100644 index 0000000000..3a3edbddf3 --- /dev/null +++ b/Task/Memory-allocation/Sinclair-ZX81-BASIC/memory-allocation-4.sinclair @@ -0,0 +1 @@ +10 REM Y▀▀:▖ ▟?TAN diff --git a/Task/Memory-allocation/X86-Assembly/memory-allocation.x86 b/Task/Memory-allocation/X86-Assembly/memory-allocation.x86 new file mode 100644 index 0000000000..3501f954d3 --- /dev/null +++ b/Task/Memory-allocation/X86-Assembly/memory-allocation.x86 @@ -0,0 +1,104 @@ +; linux x86_64 + +struc block +free: resb 1 ; whether or not this block is free +size: resb 2 ; size of the chunk of memory +next: resb 8 ; the next chunk after this one +mem: +endstruc + +section .data +hStart: dq 0 ; the beginning of our heap space +break: dq 0 ; the current end of our heap space + + +section .text + +Allocate: + + push rdi ; save the size argument + + cmp qword [break], 0 ; if breakpoint is zero this + je firstAlloc ; is the first call to allocate + + mov rdi, qword [hStart] ; else address of heap start + + findBlock: ; look for a suitable block of memory + + cmp byte [rdi + free], 2 + je newBlock ; end of heap reached, create new block + + cmp byte [rdi + free], 0 + je skipBlock ; this block taken + + ; this block is free, make + ; sure it's big enough + mov bx, word [rdi + size] + mov rcx, qword [rsp] ; compare against our size arg + cmp cx, bx + jg skipBlock ; keep looking if not big enough + + mov byte [rdi + free], 0 ; else mark as taken + add rdi, mem + add rsp, 8 ; discard size arg, we didn't need it + mov rax, rdi ; return pointer to this block + ret + + skipBlock: + mov rsi, qword [rdi + next] ; load next + mov rdi, rsi ' block address + jmp findBlock + + newBlock: + mov rax, rdi + add rdi, 1024 + cmp rdi, qword [break] + jl initAndAllocate + push rax + mov rdi, qword [break] ; if we are getting low on + add rdi, 4096 ; heap space, we ask OS for + mov rax, 12 ; more memory with brk syscall + syscall + cmp rax, qword [break] ; if breakpoint has not increased, + je allocFail ; then memory could not be allocated + mov qword [break], rax + pop rax + jmp initAndAllocate + + + firstAlloc: ; extra work has to be done on first + mov rax, 12 ; call to this subroutine + mov rdi, 0 + syscall + mov qword [hStart], rax ; init heap start + add rax, 4096 + mov rdi, rax + mov rax, 12 ; get heap memory with sys brk + syscall + cmp rax, qword [hStart] + je allocFail + mov qword [break], rax + mov rax, qword [hStart] + + initAndAllocate: + mov byte [rax + free], 0 ; mark block free + pop rdi ; pop size arg off stack + mov word [rax + size], di ; mark it's size + lea rsi, [rax + mem + rdi] + mov byte [rsi + free], 2 ; mark heap end block + mov qword [rax + next], rsi ; mark next block + add rax, mem ; return pointer to block's memory space + ret + +allocFail: ; exit(1) when allocation fails + mov rax, 60 + mov rdi, 1 + syscall + ret + +; free this block so it can be +; reused in a subsequent call to allocate +Release: + sub rdi, mem + mov byte [rdi + free], 1 + ret diff --git a/Task/Memory-allocation/Zkl/memory-allocation.zkl b/Task/Memory-allocation/Zkl/memory-allocation.zkl new file mode 100644 index 0000000000..8e1dfbb78f --- /dev/null +++ b/Task/Memory-allocation/Zkl/memory-allocation.zkl @@ -0,0 +1,2 @@ +Data(123); // this bit bucket expects hold 123 bytes +List.createLong(123); // this list expects to hold 123 elements diff --git a/Task/Memory-layout-of-a-data-structure/Kotlin/memory-layout-of-a-data-structure.kotlin b/Task/Memory-layout-of-a-data-structure/Kotlin/memory-layout-of-a-data-structure.kotlin new file mode 100644 index 0000000000..ba2fe07a21 --- /dev/null +++ b/Task/Memory-layout-of-a-data-structure/Kotlin/memory-layout-of-a-data-structure.kotlin @@ -0,0 +1,42 @@ +// version 1.0.6 + +const val OFF = false +const val ON = true + +fun toOnOff(b: Boolean) = if (b) "ON" else "OFF" + +data class Rs232Pins9( + var carrierDetect : Boolean = OFF, + var receivedData : Boolean = OFF, + var transmittedData : Boolean = OFF, + var dataTerminalReady : Boolean = OFF, + var signalGround : Boolean = OFF, + var dataSetReady : Boolean = OFF, + var requestToSend : Boolean = OFF, + var clearToSend : Boolean = OFF, + var ringIndicator : Boolean = OFF +) { + fun setPin(n: Int, v: Boolean) { + when (n) { + 1 -> carrierDetect = v + 2 -> receivedData = v + 3 -> transmittedData = v + 4 -> dataTerminalReady = v + 5 -> signalGround = v + 6 -> dataSetReady = v + 7 -> requestToSend = v + 8 -> clearToSend = v + 9 -> ringIndicator = v + } + } +} + +fun main(args: Array) { + val plug = Rs232Pins9(carrierDetect = ON, receivedData = ON) // set first two pins, say + println(toOnOff(plug.component2())) // print value of pin 2 by number + plug.transmittedData = ON // set pin 3 by name + plug.setPin(4, ON) // set pin 4 by number + println(toOnOff(plug.component3())) // print value of pin 3 by number + println(toOnOff(plug.dataTerminalReady)) // print value of pin 4 by name + println(toOnOff(plug.ringIndicator)) // print value of pin 9 by name +} diff --git a/Task/Memory-layout-of-a-data-structure/Phix/memory-layout-of-a-data-structure.phix b/Task/Memory-layout-of-a-data-structure/Phix/memory-layout-of-a-data-structure.phix new file mode 100644 index 0000000000..325e394753 --- /dev/null +++ b/Task/Memory-layout-of-a-data-structure/Phix/memory-layout-of-a-data-structure.phix @@ -0,0 +1,8 @@ +constant CD=1, RD=2, TD=3, DTR=4, ... +atom addr = allocate(2) -- or wherever +--read +sequence bits = int_to_bits(peek2u(addr),16) +integer dtr = bits[DTR] +--write +bits[DTR] = 1 +poke2(addr,bits_to_int(bits)) diff --git a/Task/Menu/Gambas/menu.gambas b/Task/Menu/Gambas/menu.gambas new file mode 100644 index 0000000000..7d5642f3bd --- /dev/null +++ b/Task/Menu/Gambas/menu.gambas @@ -0,0 +1,10 @@ +Public Sub Form_Open() +Dim sMenu As String[] = ["fee fie", "huff and puff", "mirror mirror", "tick tock"] +Dim sAnswer As String + +Do + sAnswer = InputBox("0: fee fie 1: huff and puff 2: mirror mirror 3: tick tock", "Please select an number") + If InStr("0123", sAnswer) Then Message("You selected item " & sAnswer & " - " & sMenu[Val(sAnswer)], "OK") +Loop + +End diff --git a/Task/Menu/jq/menu-1.jq b/Task/Menu/Jq/menu-1.jq similarity index 100% rename from Task/Menu/jq/menu-1.jq rename to Task/Menu/Jq/menu-1.jq diff --git a/Task/Menu/jq/menu-2.jq b/Task/Menu/Jq/menu-2.jq similarity index 100% rename from Task/Menu/jq/menu-2.jq rename to Task/Menu/Jq/menu-2.jq diff --git a/Task/Menu/jq/menu-3.jq b/Task/Menu/Jq/menu-3.jq similarity index 100% rename from Task/Menu/jq/menu-3.jq rename to Task/Menu/Jq/menu-3.jq diff --git a/Task/Menu/Kotlin/menu.kotlin b/Task/Menu/Kotlin/menu.kotlin new file mode 100644 index 0000000000..d47496d84d --- /dev/null +++ b/Task/Menu/Kotlin/menu.kotlin @@ -0,0 +1,25 @@ +// version 1.1.2 + +fun menu(list: List): String { + if (list.isEmpty()) return "" + val n = list.size + while (true) { + println("\n M E N U\n") + for (i in 0 until n) println("${i + 1}: ${list[i]}") + print("\nEnter your choice 1 - $n : ") + val index = readLine()!!.toIntOrNull() + if (index == null || index !in 1..n) continue + return list[index - 1] + } +} + +fun main(args: Array) { + val list = listOf( + "fee fie", + "huff and puff", + "mirror mirror", + "tick tock" + ) + val choice = menu(list) + println("\nYou chose : $choice") +} diff --git a/Task/Menu/Pascal/menu.pascal b/Task/Menu/Pascal/menu.pascal new file mode 100644 index 0000000000..623d789f2c --- /dev/null +++ b/Task/Menu/Pascal/menu.pascal @@ -0,0 +1,61 @@ +program Menu; +{$ASSERTIONS ON} +uses + objects; +var + MenuItems :PUnSortedStrCollection; + selected :string; + +Function SelectMenuItem(MenuItems :PUnSortedStrCollection):string; +var + i, idx :integer; + code :word; + choice :string; +begin + // Return empty string if the collection is empty. + if MenuItems^.Count = 0 then + begin + SelectMenuItem := ''; + Exit; + end; + + repeat + for i:=0 to MenuItems^.Count-1 do + begin + writeln(i+1:2, ') ', PString(MenuItems^.At(i))^); + end; + write('Make your choice: '); + readln(choice); + // Try to convert choice to an integer. + // Code contains 0 if this was successful. + val(choice, idx, code) + until (code=0) and (idx>0) and (idx<=MenuItems^.Count); + // Return the selected element. + SelectMenuItem := PString(MenuItems^.At(idx-1))^; +end; + +begin + // Create an unsorted string collection for the menu items. + MenuItems := new(PUnSortedStrCollection, Init(10, 10)); + + // Add some menu items to the collection. + MenuItems^.Insert(NewStr('fee fie')); + MenuItems^.Insert(NewStr('huff and puff')); + MenuItems^.Insert(NewStr('mirror mirror')); + MenuItems^.Insert(NewStr('tick tock')); + + // Display the menu and get user input. + selected := SelectMenuItem(MenuItems); + writeln('You chose: ', selected); + + dispose(MenuItems, Done); + + // Test function with an empty collection. + MenuItems := new(PUnSortedStrCollection, Init(10, 10)); + + selected := SelectMenuItem(MenuItems); + // Assert that the function returns an empty string. + assert(selected = '', 'Assertion failed: the function did not return an empty string.'); + + dispose(MenuItems, Done); +end. diff --git a/Task/Menu/PowerShell/menu-1.psh b/Task/Menu/PowerShell/menu-1.psh deleted file mode 100644 index 004d9dc989..0000000000 --- a/Task/Menu/PowerShell/menu-1.psh +++ /dev/null @@ -1,11 +0,0 @@ -function Get-Choice ([array] $Items) { - Set-StrictMode -Version Latest - - do { - $Items | ForEach-Object { $i = 0 } { '{0,3}. {1}' -f (++$i),$_ } - $choice = Read-Host Your choice - } while ($choice -notmatch '^\d+$' -or - !(1..$Items.Length -eq $choice)) - - $Items[$choice-1] -} diff --git a/Task/Menu/PowerShell/menu-2.psh b/Task/Menu/PowerShell/menu-2.psh deleted file mode 100644 index 402452839d..0000000000 --- a/Task/Menu/PowerShell/menu-2.psh +++ /dev/null @@ -1 +0,0 @@ -Get-Choice 'fee fie', 'huff and puff', 'mirror mirror', 'tick tock' diff --git a/Task/Menu/Ruby/menu.rb b/Task/Menu/Ruby/menu.rb index 4ae83f1987..b5b16846e6 100644 --- a/Task/Menu/Ruby/menu.rb +++ b/Task/Menu/Ruby/menu.rb @@ -1,23 +1,26 @@ -def select(prompt, items) - return "" if items.empty? - loop do - items.each_index {|i| puts "#{i}. #{items[i]}"} - print "#{prompt}: " - begin - answer = Integer(gets) - rescue ArgumentError - redo +def select(prompt, items = []) + if items.empty? + '' + else + answer = -1 + until (0...items.length).cover?(answer) + items.each_with_index {|i,j| puts "#{j}. #{i}"} + print "#{prompt}: " + begin + answer = Integer(gets) + rescue ArgumentError + redo + end end - return items[answer] if (0...items.length).cover?(answer) + items[answer] end end # test empty list -response = select("Which is empty", []) -puts "empty list returns: >#{response}<" -puts +response = select('Which is empty') +puts "empty list returns: >#{response}<\n" # "real" test items = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock'] -response = select("Which is from the three pigs", items) +response = select('Which is from the three pigs', items) puts "you chose: >#{response}<" diff --git a/Task/Menu/Zkl/menu.zkl b/Task/Menu/Zkl/menu.zkl new file mode 100644 index 0000000000..80f74516ad --- /dev/null +++ b/Task/Menu/Zkl/menu.zkl @@ -0,0 +1,13 @@ +fcn teleprompter(options){ + os:=T("exit").extend(vm.arglist); N:=os.len(); + if(N==1) return(""); + while(1){ + Utils.zipWith(fcn(n,o){"%d) %s".fmt(n,o).println()},[0..],os); + a:=ask("Your choice: "); + try{ n:=a.toInt(); if(0<=n) { + val d = 2.0 pwr 8.0 + println(d) +} diff --git a/Task/Metaprogramming/Perl-6/metaprogramming-4.pl6 b/Task/Metaprogramming/Perl-6/metaprogramming-4.pl6 deleted file mode 100644 index a4aed44433..0000000000 --- a/Task/Metaprogramming/Perl-6/metaprogramming-4.pl6 +++ /dev/null @@ -1,2 +0,0 @@ -say "Foo = $foo\n"; # normal double quotes -say Q:qq 【Foo = $foo\n】; # a more explicit derivation, new quotes diff --git a/Task/Metaprogramming/Racket/metaprogramming-1.rkt b/Task/Metaprogramming/Racket/metaprogramming-1.rkt new file mode 100644 index 0000000000..81232f240c --- /dev/null +++ b/Task/Metaprogramming/Racket/metaprogramming-1.rkt @@ -0,0 +1,10 @@ +#lang racket + +(define-syntax-rule (list-when test body) + (if test + body + '())) + +(let ([not-a-string 42]) + (list-when (string? not-a-string) + (string->list not-a-string))) diff --git a/Task/Metaprogramming/Racket/metaprogramming-2.rkt b/Task/Metaprogramming/Racket/metaprogramming-2.rkt new file mode 100644 index 0000000000..8de096a696 --- /dev/null +++ b/Task/Metaprogramming/Racket/metaprogramming-2.rkt @@ -0,0 +1,8 @@ +(require (for-syntax syntax/parse)) + +(define-syntax list-when + (syntax-parser + [(_ test:expr body:expr) + #'(if test + body + null)])) diff --git a/Task/Metaprogramming/Sidef/metaprogramming-2.sidef b/Task/Metaprogramming/Sidef/metaprogramming-2.sidef index 2611bd29b1..363abf60a1 100644 --- a/Task/Metaprogramming/Sidef/metaprogramming-2.sidef +++ b/Task/Metaprogramming/Sidef/metaprogramming-2.sidef @@ -9,12 +9,12 @@ var colors = Hash( 'white' => "fff", ) -colors.each { |color, code| +for color,code in colors { String.def_method("in_#{color}", func (self) { '' + self + '' }) } -say "blue".in_blue; -say "red".in_red; -say "white".in_white; +say "blue".in_blue +say "red".in_red +say "white".in_white diff --git a/Task/Metaprogramming/Zkl/metaprogramming-1.zkl b/Task/Metaprogramming/Zkl/metaprogramming-1.zkl new file mode 100644 index 0000000000..0da8c4356f --- /dev/null +++ b/Task/Metaprogramming/Zkl/metaprogramming-1.zkl @@ -0,0 +1,3 @@ +#define name [0|1] +#if [0|1|name] +#else, #endif diff --git a/Task/Metaprogramming/Zkl/metaprogramming-2.zkl b/Task/Metaprogramming/Zkl/metaprogramming-2.zkl new file mode 100644 index 0000000000..248777bcae --- /dev/null +++ b/Task/Metaprogramming/Zkl/metaprogramming-2.zkl @@ -0,0 +1,3 @@ +//Full zkl functionality but limited access to the parse stream; only #defines +#ifdef name +#fcn name {code} diff --git a/Task/Metaprogramming/Zkl/metaprogramming-3.zkl b/Task/Metaprogramming/Zkl/metaprogramming-3.zkl new file mode 100644 index 0000000000..f52f06910d --- /dev/null +++ b/Task/Metaprogramming/Zkl/metaprogramming-3.zkl @@ -0,0 +1,3 @@ +// Shove text into the parse stream +#text name text +#tokenize name, #tokenize f, #tokenize f(a) diff --git a/Task/Metaprogramming/Zkl/metaprogramming-4.zkl b/Task/Metaprogramming/Zkl/metaprogramming-4.zkl new file mode 100644 index 0000000000..a01c7b2e9d --- /dev/null +++ b/Task/Metaprogramming/Zkl/metaprogramming-4.zkl @@ -0,0 +1,3 @@ +#<<<# +text, any text, inside #<<<# pairs is ignored +#<<<# diff --git a/Task/Metaprogramming/Zkl/metaprogramming-5.zkl b/Task/Metaprogramming/Zkl/metaprogramming-5.zkl new file mode 100644 index 0000000000..ede8bcd885 --- /dev/null +++ b/Task/Metaprogramming/Zkl/metaprogramming-5.zkl @@ -0,0 +1,8 @@ +string:= +#<<< +"here docs: +all text in #<<< pairs is collected into one [long] line and passed +verbatim to the tokenizer. Illustrated here as quoted (\") strings +can not span lines."; +#<<< +println(string); // contains newlines diff --git a/Task/Metaprogramming/Zkl/metaprogramming-6.zkl b/Task/Metaprogramming/Zkl/metaprogramming-6.zkl new file mode 100644 index 0000000000..306eed3ba7 --- /dev/null +++ b/Task/Metaprogramming/Zkl/metaprogramming-6.zkl @@ -0,0 +1,4 @@ +const{ var _n=-1; var [proxy] N=fcn{ _n+=1 } } +const X=N; // → 0 +println(_n); // → 2 code time is after const time +const Y=N,Z=N; // → 1,2 diff --git a/Task/Metered-concurrency/Go/metered-concurrency-3.go b/Task/Metered-concurrency/Go/metered-concurrency-3.go deleted file mode 100644 index aade0f645f..0000000000 --- a/Task/Metered-concurrency/Go/metered-concurrency-3.go +++ /dev/null @@ -1,56 +0,0 @@ -package main - -import ( - "log" - "os" - "sync" - "time" -) - -var fmt = log.New(os.Stdout, "", 0) - -func main() { - // three operations per task description - acquire := make(chan int) - release := make(chan int) - count := make(chan chan int) - - // library analogy per WP article - go librarian(acquire, release, count, 10) - nStudents := 20 - var studied sync.WaitGroup - studied.Add(nStudents) - for i := 0; i < nStudents; i++ { - go student(acquire, release, count, &studied) - } - // wait until all students have studied before terminating program - studied.Wait() -} - -func librarian(a, r chan int, c chan chan int, count int) { - p := a // acquire operation is served or not depending on count - for { - select { - case <-p: // acquire/p/wait operation - count-- - if count == 0 { - p = nil - } - case <-r: // release/v operation - count++ - p = a - case cc := <-c: // count operation - cc <- count - } - } -} - -func student(a, r chan int, c chan chan int, studied *sync.WaitGroup) { - cc := make(chan int) - a <- 0 // acquire - c <- cc // request count - fmt.Printf("Room entered. Count is %d. Studying...\n", <-cc) - time.Sleep(2 * time.Second) // sleep per task description - r <- 0 // release - studied.Done() // signal done -} diff --git a/Task/Metered-concurrency/Phix/metered-concurrency.phix b/Task/Metered-concurrency/Phix/metered-concurrency.phix new file mode 100644 index 0000000000..04e457045e --- /dev/null +++ b/Task/Metered-concurrency/Phix/metered-concurrency.phix @@ -0,0 +1,69 @@ +sequence sems = {} +constant COUNTER = 1, QUEUE = 2 + +function semaphore(integer n) + if n>0 then + sems = append(sems,{n,{}}) + return length(sems) + else + return 0 + end if +end function + +procedure acquire(integer id) + if sems[id][COUNTER]=0 then + task_suspend(task_self()) + sems[id][QUEUE] &= task_self() + task_yield() + end if + sems[id][COUNTER] -= 1 +end procedure + +procedure release(integer id) + sems[id][COUNTER] += 1 + if length(sems[id][QUEUE])>0 then + task_schedule(sems[id][QUEUE][1],1) + sems[id][QUEUE] = sems[id][QUEUE][2..$] + end if +end procedure + +function count(integer id) + return sems[id][COUNTER] +end function + +procedure delay(atom delaytime) +atom t = time() + while time()-t1 do + task_yield() + integer scnew = count(sem) + if scnew!=sc + or time()>t0 then + sc = scnew + printf(1,"Semaphore count now %d\n",{sc}) + t0 = time()+2 + end if +end while +?"done" diff --git a/Task/Metered-concurrency/Ruby/metered-concurrency.rb b/Task/Metered-concurrency/Ruby/metered-concurrency.rb new file mode 100644 index 0000000000..45f4973771 --- /dev/null +++ b/Task/Metered-concurrency/Ruby/metered-concurrency.rb @@ -0,0 +1,44 @@ +require 'thread' + +# Simple Semaphore implementation +class Semaphore + def initialize(size = 1) + @queue = SizedQueue.new(size) + size.times { acquire } + end + + def acquire + tap { @queue.push(nil) } + end + + def release + tap { @queue.pop } + end + + # @return [Integer] + def count + @queue.length + end + + def synchronize + release + yield + ensure + acquire + end +end + +def foo(id, sem) + sem.synchronize do + puts "Thread #{id} Acquired lock" + sleep(2) + end +end + +threads = [] +n = 5 +s = Semaphore.new(3) +n.times do |i| + threads << Thread.new { foo i, s } +end +threads.each(&:join) diff --git a/Task/Metered-concurrency/Zkl/metered-concurrency.zkl b/Task/Metered-concurrency/Zkl/metered-concurrency.zkl new file mode 100644 index 0000000000..10dcdca625 --- /dev/null +++ b/Task/Metered-concurrency/Zkl/metered-concurrency.zkl @@ -0,0 +1,8 @@ +fcn job(name,sem){ + name.println(" wait"); sem.acquire(); + name.println(" go"); Atomic.sleep(2); + sem.release(); name.println(" done") +} + // start 3 threads using the same semphore +s:=Thread.Semaphore(1); +job.launch("1",s); job.launch("2",s); job.launch("3",s); diff --git a/Task/Metronome/Kotlin/metronome.kotlin b/Task/Metronome/Kotlin/metronome.kotlin new file mode 100644 index 0000000000..ba4273050b --- /dev/null +++ b/Task/Metronome/Kotlin/metronome.kotlin @@ -0,0 +1,16 @@ +// version 1.1.2 + +fun metronome(bpm: Int, bpb: Int, maxBeats: Int = Int.MAX_VALUE) { + val delay = 60_000L / bpm + var beats = 0 + do { + Thread.sleep(delay) + if (beats % bpb == 0) print("\nTICK ") + else print("tick ") + beats++ + } + while (beats < maxBeats) + println() +} + +fun main(args: Array) = metronome(120, 4, 20) // limit to 20 beats diff --git a/Task/Metronome/Ruby/metronome.rb b/Task/Metronome/Ruby/metronome.rb new file mode 100644 index 0000000000..50d2a4669f --- /dev/null +++ b/Task/Metronome/Ruby/metronome.rb @@ -0,0 +1,14 @@ +#!/usr/bin/ruby + +bpm = Integer(ARGV[0]) rescue 60 # sets BPM by the first command line argument, set to 60 if none provided +msr = Integer(ARGV[1]) rescue 4 # sets number of beats in a measure by the second command line argument, set to 4 if none provided +i = 0 + +loop do + (msr-1).times do + puts "\a" + sleep(60.0/bpm) + end + puts "\aAND #{i += 1}" + sleep(60.0/bpm) +end 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 e111739e61..3ee7c8ffdc 100644 --- a/Task/Middle-three-digits/ALGOL-68/middle-three-digits.alg +++ b/Task/Middle-three-digits/ALGOL-68/middle-three-digits.alg @@ -1,92 +1,63 @@ # 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 , 100, -12345 # the following values should fail # , 1, 2, -1, -10, 2002, -2002, 0 ); - FOR test number FROM LWB test values TO UPB test values DO - CASE middle 3 digits( test values[ test number ] ) IN ( INT success value ): # got the middle 3 digits # - printf( ( $ 11z-d, " : ", 3d $ , test values[ test number ] , success value ) ) , - ( STRING error message ): # got an error message # - printf( ( $ 11z-d, " : ", n( UPB error message )a $ , test values[ test number ] , error message ) ) - ESAC; - print( ( newline ) ) - OD - ) diff --git a/Task/Middle-three-digits/ALGOL-W/middle-three-digits.alg b/Task/Middle-three-digits/ALGOL-W/middle-three-digits.alg new file mode 100644 index 0000000000..d34ee07287 --- /dev/null +++ b/Task/Middle-three-digits/ALGOL-W/middle-three-digits.alg @@ -0,0 +1,48 @@ +begin + % record structure that will be used to return the middle 3 digits of a number % + % if the middle three digits can't be determined, isOk will be false and message % + % will contain an error message % + % if the middle 3 digts can be determined, middle3 will contain the middle 3 % + % digits and isOk will be true % + record MiddleThreeDigits ( integer middle3; logical isOk; string(80) message ); + + % finds the middle3 digits of a number or describes why they can't be found % + reference(MiddleThreeDigits) procedure findMiddleThreeDigits ( integer value number ) ; + begin + integer n, digitCount, d; + + n := abs( number ); + % count the number of digits the number has % + digitCount := if n = 0 then 1 else 0; + d := n; + while d > 0 do begin + digitCount := digitCount + 1; + d := d div 10 + end while_d_gt_0 ; + if digitCount < 3 then MiddleThreeDigits( 0, false, "Number must have at least 3 digits" ) + else if not odd( digitCount ) then MiddleThreeDigits( 0, false, "Number must have an odd number of digits" ) + else begin + % can find the middle three digits % + integer m3; + m3 := n; + for d := 1 until ( digitCount - 3 ) div 2 do m3 := m3 div 10; + MiddleThreeDigits( m3 rem 1000, true, "" ) + end + end findMiddleThreeDigits ; + + % test the findMiddleThreeDigits procedure % + for n := 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0 do begin + reference(MiddleThreeDigits) m3; + i_w := 10; s_w := 0; % set output formating % + m3 := findMiddleThreeDigits( n ); + write( n, ": " ); + if not isOk(m3) then writeon( message(m3) ) + else begin + % as we return the middle three digits as an integer, we must manually 0 pad % + if middle3(m3) < 100 then writeon( "0" ); + if middle3(m3) < 10 then writeon( "0" ); + writeon( i_w := 1, middle3(m3) ) + end + end for_n + +end. diff --git a/Task/Middle-three-digits/ATS/middle-three-digits.ats b/Task/Middle-three-digits/ATS/middle-three-digits.ats new file mode 100644 index 0000000000..b98b1d0c98 --- /dev/null +++ b/Task/Middle-three-digits/ATS/middle-three-digits.ats @@ -0,0 +1,120 @@ +(* ****** ****** *) +// +#include +"share/atspre_staload.hats" +#include +"share/HATS/atspre_staload_libats_ML.hats" +// +(* ****** ****** *) +// +extern +fun +int2digits(x: int): list0(int) +// +(* ****** ****** *) + +implement +int2digits(x) = +loop(x, list0_nil) where +{ +// +fun +loop +( + x: int, res: list0(int) +) : list0(int) = + if x > 0 then loop(x/10, list0_cons(x%10, res)) else res +// +} (* end of [int2digits] *) + +(* ****** ****** *) + +extern +fun +Middle_three_digits(x: int): void + +(* ****** ****** *) + +implement +Middle_three_digits + (x0) = let +// +val x1 = +( +if x0 >= 0 then x0 else ~x0 +) : int +// +fun +skip +( +ds: list0(int), k: int +) : list0(int) = + if k > 0 then skip(ds.tail(), k-1) else ds +// +val ds = + int2digits(x1) +// +val n0 = length(ds) +// +in +// +if +(n0 <= 2) +then +( +println! ("Middle-three-digits(", x0, "): Too small!") +) +else +( +if +(n0 % 2 = 0) +then +( +println! +( +"Middle-three-digits(", x0, "): Even number of digits!" +) +) +else let + val ds = + skip(ds, (n0-3)/2) + val-list0_cons(d1, ds) = ds + val-list0_cons(d2, ds) = ds + val-list0_cons(d3, ds) = ds +in + println! ("Middle-three-digits(", x0, "): ", d1, d2, d3) +end // end of [else] +) +// +end // end of [Middle_three_digits] + +(* ****** ****** *) + +implement +main0() = +{ +// +val +thePassing = +g0ofg1 +( +$list{int} +( + 123 +, 12345 +, 1234567 +, 987654321 +, 10001, ~10001 +, ~123, ~100, 100, ~12345 +) +) +val +theFailing = +g0ofg1($list{int}(1, 2, ~1, ~10, 2002, ~2002, 0)) +// +val () = thePassing.foreach()(lam x => Middle_three_digits(x)) +val () = theFailing.foreach()(lam x => Middle_three_digits(x)) +// +} (* end of [main0] *) + +(* ****** ****** *) diff --git a/Task/Middle-three-digits/Dart/middle-three-digits.dart b/Task/Middle-three-digits/Dart/middle-three-digits.dart new file mode 100644 index 0000000000..1f0a9729e1 --- /dev/null +++ b/Task/Middle-three-digits/Dart/middle-three-digits.dart @@ -0,0 +1,46 @@ +import'dart:math'; + int length(int x) + { + int i,y; + for(i=0;;i++) + { + y=pow(10,i); + if(x%y==x) + break; + } + return i; + } + int middle(int x,int l) + { + int a=(x/10)-((x%10)/10); + int b=a%(pow(10,l-2)); + int l2=length(b); + if(l2==3) + { + return b; + } + if(l2!=3) + { + return middle(b,l2); + } + return 0; + } + + +main() +{ + int x=-100,y; + if(x<0) + x=-x; + int l=length(x); + if(l.isEven||x<100) + {print('error');} + if(l==3) + {print('$x');} + + if(l.isOdd&& x>100) + { + y=middle(x,l); + print('$y'); + } +} diff --git a/Task/Middle-three-digits/FBSL/middle-three-digits.fbsl b/Task/Middle-three-digits/FBSL/middle-three-digits.fbsl deleted file mode 100644 index 46990d4d99..0000000000 --- a/Task/Middle-three-digits/FBSL/middle-three-digits.fbsl +++ /dev/null @@ -1,45 +0,0 @@ -#APPTYPE CONSOLE - -DIM numbers AS STRING = "123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0" -DIM dict[] = Split(numbers, ",") -DIM num AS INTEGER -DIM num2 AS INTEGER -DIM powered AS INTEGER - -FOR DIM i = 0 TO COUNT(dict) - 1 - num2 = dict[i] - num = ABS(num2) - IF num < 100 THEN - display(num2, "is too small") - ELSE - FOR DIM j = 9 DOWNTO 1 - powered = 10 ^ j - IF num >= powered THEN - IF j MOD 2 = 1 THEN - display(num2, "has even number of digits") - ELSE - display(num2, middle3(num, j)) - END IF - EXIT FOR - END IF - NEXT - END IF -NEXT - -PAUSE - -FUNCTION display(num, msg) - PRINT LPAD(num, 11, " "), " --> ", msg -END FUNCTION - -FUNCTION middle3(n, pwr) - DIM power AS INTEGER = (pwr \ 2) - 1 - DIM m AS INTEGER = n - m = m \ (10 ^ power) - m = m MOD 1000 - IF m = 0 THEN - RETURN "000" - ELSE - RETURN m - END IF -END FUNCTION diff --git a/Task/Middle-three-digits/Gambas/middle-three-digits.gambas b/Task/Middle-three-digits/Gambas/middle-three-digits.gambas new file mode 100644 index 0000000000..fbe1e643d9 --- /dev/null +++ b/Task/Middle-three-digits/Gambas/middle-three-digits.gambas @@ -0,0 +1,24 @@ +Public Sub Main() +Dim iList As Integer[] = [123, 12345, 1234567, 987654321, 10001, + -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0] 'Array of integers to process +Dim sTemp As String 'Temp string +Dim siCount As Short 'Counter +Dim sAnswer As New String[] 'Array, resons for failure or 'middle three digits' + +For siCount = 0 To iList.Max 'Loop through the integers + sTemp = Str(Abs(iList[siCount])) 'Convert integer to positive and place in sTemp as a string + If Len(sTemp) < 3 Then 'If sTemp has less than 3 characters then.. + sAnswer.Add("This integer has less than 3 characters") 'Place text in sAnswers + Else If Even(Len(sTemp)) Then 'Else If sTemp is of even length then + sAnswer.Add("This integer has an even length") 'Place text in sAnswers + Else 'Else.. + sAnswer.Add(Mid(sTemp, Int(Len(sTemp) / 2), 3)) 'Place the middle 3 digits in sAnswer + Endif +Next + +For siCount = 0 To iList.Max 'Loop through the integers + Print Space$(10 - Len(Str(iList[siCount]))) & + iList[siCount] & " : " & sAnswer[siCount] 'Print out results +Next + +End diff --git a/Task/Middle-three-digits/Gosu/middle-three-digits.gosu b/Task/Middle-three-digits/Gosu/middle-three-digits.gosu new file mode 100644 index 0000000000..c23c66a3ab --- /dev/null +++ b/Task/Middle-three-digits/Gosu/middle-three-digits.gosu @@ -0,0 +1,13 @@ +var valid = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345} +valid.each(\ num ->print(middleThree(num))) + +var errant = {1, 2, -1, -10, 2002, -2002, 0} +errant.each(\ num ->print(middleThree(num))) + +function middleThree(x: int) : String { + var s = Math.abs(x) as String + if(s.length < 3) return "Error: ${x} has less than 3 digits" + if(s.length % 2 == 0) return "Error: ${x} has an even number of digits" + var start = (s.length / 2) - 1 + return s.substring(start, start + 3) +} diff --git a/Task/Middle-three-digits/Haskell/middle-three-digits.hs b/Task/Middle-three-digits/Haskell/middle-three-digits.hs index 8e31a85a7f..f198a94a8a 100644 --- a/Task/Middle-three-digits/Haskell/middle-three-digits.hs +++ b/Task/Middle-three-digits/Haskell/middle-three-digits.hs @@ -1,17 +1,35 @@ -import Numeric +mid3 :: Int -> Either String String +mid3 n + | m < 100 = Left "is too small" + | even l = Left "has an even number of digits" + | otherwise = Right . take 3 $ drop ((l - 3) `div` 2) s + where + m = abs n + s = show m + l = length s -mid3 :: Integral a => a -> Either String String -mid3 n | m < 100 = Left "is too small" - | even l = Left "has an even number of digits" - | otherwise = Right . take 3 $ drop ((l-3) `div` 2) s - where m = abs n - s = showInt m "" - l = length s - -showMid3 :: Integer -> String +showMid3 :: Int -> String showMid3 n = show n ++ ": " ++ either id id (mid3 n) main :: IO () -main = mapM_ (putStrLn . showMid3) [ - 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, - 1, 2, -1, -10, 2002, -2002, 0] +main = + mapM_ + (putStrLn . showMid3) + [ 123 + , 12345 + , 1234567 + , 987654321 + , 10001 + , -10001 + , -123 + , -100 + , 100 + , -12345 + , 1 + , 2 + , -1 + , -10 + , 2002 + , -2002 + , 0 + ] diff --git a/Task/Middle-three-digits/jq/middle-three-digits-1.jq b/Task/Middle-three-digits/Jq/middle-three-digits-1.jq similarity index 100% rename from Task/Middle-three-digits/jq/middle-three-digits-1.jq rename to Task/Middle-three-digits/Jq/middle-three-digits-1.jq diff --git a/Task/Middle-three-digits/jq/middle-three-digits-2.jq b/Task/Middle-three-digits/Jq/middle-three-digits-2.jq similarity index 100% rename from Task/Middle-three-digits/jq/middle-three-digits-2.jq rename to Task/Middle-three-digits/Jq/middle-three-digits-2.jq diff --git a/Task/Middle-three-digits/Phix/middle-three-digits.phix b/Task/Middle-three-digits/Phix/middle-three-digits.phix new file mode 100644 index 0000000000..b8e59bad59 --- /dev/null +++ b/Task/Middle-three-digits/Phix/middle-three-digits.phix @@ -0,0 +1,11 @@ +procedure mid3(integer i) + string s = sprintf("%d",abs(i)) + integer k = length(s)-3 + printf(1,"%10d: %s\n",{i,iff(k<0 or and_bits(k,1)?"error":s[k/2+1..k/2+3])}) +end procedure + +constant tests = {123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345, + 1,2,-1,-10,2002,-2002,0} +for i=1 to length(tests) do + mid3(tests[i]) +end for diff --git a/Task/Middle-three-digits/PureBasic/middle-three-digits.purebasic b/Task/Middle-three-digits/PureBasic/middle-three-digits.purebasic deleted file mode 100644 index e35d5c73d7..0000000000 --- a/Task/Middle-three-digits/PureBasic/middle-three-digits.purebasic +++ /dev/null @@ -1,28 +0,0 @@ -Procedure.s middleThreeDigits(x.q) - Protected x$, digitCount - - If x < 0: x = -x: EndIf - - x$ = Str(x) - digitCount = Len(x$) - If digitCount < 3 - ProcedureReturn "invalid input: too few digits" - ElseIf digitCount % 2 = 0 - ProcedureReturn "invalid input: even number of digits" - EndIf - - ProcedureReturn Mid(x$,digitCount / 2, 3) -EndProcedure - -If OpenConsole() - Define testValues$ = "123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0" - - Define i, value.q, numTests = CountString(testValues$, " ") + 1 - For i = 1 To numTests - value = Val(StringField(testValues$, i, " ")) - PrintN(RSet(Str(value), 12, " ") + " : " + middleThreeDigits(value)) - Next - - Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input() - CloseConsole() -EndIf diff --git a/Task/Middle-three-digits/Run-BASIC/middle-three-digits.run b/Task/Middle-three-digits/Run-BASIC/middle-three-digits.run deleted file mode 100644 index 7a77efa890..0000000000 --- a/Task/Middle-three-digits/Run-BASIC/middle-three-digits.run +++ /dev/null @@ -1,13 +0,0 @@ -x$ = "123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0" - -while word$(x$,i+1,",") <> "" - i = i + 1 - a1$ = trim$(word$(x$,i,",")) - if left$(a1$,1) = "-" then a$ = mid$(a1$,2) else a$ = a1$ - if (len(a$) and 1) = 0 or len(a$) < 3 then - print a1$;chr$(9);" length < 3 or is even" - else - print mid$(a$,((len(a$)-3)/2)+1,3);" ";a1$ - end if -wend -end diff --git a/Task/Middle-three-digits/S-lang/middle-three-digits.slang b/Task/Middle-three-digits/S-lang/middle-three-digits.slang new file mode 100644 index 0000000000..b05ba54206 --- /dev/null +++ b/Task/Middle-three-digits/S-lang/middle-three-digits.slang @@ -0,0 +1,29 @@ +define m3(i) +{ + variable s = string(i), sabs = s, l; + + if (sabs[0] == '-') + sabs = sabs[[1:]]; + l = strlen(sabs); + + if (l < 3) + print(sprintf("%s doesn't have enough digits", s)); + else if (l & 1) { + variable st = (l-3) >> 1; + print(sprintf("%13s: %s", s, sabs[[st:st+2]])); + } + else + print(sprintf("%s has an even number of digits", s)); +} + +define middle_3(lst) +{ + foreach (lst) + m3( () ); +} + +middle_3( { 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, +#ifexists Int64_Type + 6644221335577ll, -11122588999ll, +#endif + 1, 2, -1, -10, 2002, -2002, 0 } ); diff --git a/Task/Middle-three-digits/Swift/middle-three-digits.swift b/Task/Middle-three-digits/Swift/middle-three-digits.swift new file mode 100644 index 0000000000..eb2062e863 --- /dev/null +++ b/Task/Middle-three-digits/Swift/middle-three-digits.swift @@ -0,0 +1,16 @@ +var num:Int = \\enter your number here +if num<0{num = -num} +var numArray:[Int]=[] +while num>0{ + var temp:Int=num%10 + numArray.append(temp) + num=num/10 +} +var i:Int=numArray.count +if i<3||i%2==0{ + print("Invalid Input") +} +else{ + i=i/2 + print("\(numArray[i+1]),\(numArray[i]),\(numArray[i-1])") +} diff --git a/Task/Middle-three-digits/Zkl/middle-three-digits.zkl b/Task/Middle-three-digits/Zkl/middle-three-digits.zkl new file mode 100644 index 0000000000..0889b508e6 --- /dev/null +++ b/Task/Middle-three-digits/Zkl/middle-three-digits.zkl @@ -0,0 +1,9 @@ +fcn middle(ns){ + ns.apply("toString").apply('-("-")) + .apply(fcn(n){nl:=n.len(); + if(nl<3 or nl.isEven) return(False); + n[(nl-3)/2,3] : "%03d".fmt(_) + }) +} +middle(T(123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345)).println() +middle(T(1, 2, -1, -10, 2002, -2002, 0)).println(); diff --git a/Task/Miller-Rabin-primality-test/00DESCRIPTION b/Task/Miller-Rabin-primality-test/00DESCRIPTION deleted file mode 100644 index 1f7d1064c0..0000000000 --- a/Task/Miller-Rabin-primality-test/00DESCRIPTION +++ /dev/null @@ -1,24 +0,0 @@ -{{Wikipedia|Miller–Rabin primality test}} - -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 - '''for''' ''r'' = 1 .. ''s'' − 1 - ''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) diff --git a/Task/Miller-Rabin-primality-test/00META.yaml b/Task/Miller-Rabin-primality-test/00META.yaml deleted file mode 100644 index 06b4f1f0c9..0000000000 --- a/Task/Miller-Rabin-primality-test/00META.yaml +++ /dev/null @@ -1,2 +0,0 @@ ---- -note: Prime Numbers 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/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/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-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/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/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/Erlang/miller-rabin-primality-test.erl b/Task/Miller-Rabin-primality-test/Erlang/miller-rabin-primality-test.erl deleted file mode 100644 index 2873ce9c57..0000000000 --- a/Task/Miller-Rabin-primality-test/Erlang/miller-rabin-primality-test.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/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/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.hs b/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test.hs deleted file mode 100644 index 720a753764..0000000000 --- a/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test.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/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 e7e8edaaa0..0000000000 --- a/Task/Miller-Rabin-primality-test/JavaScript/miller-rabin-primality-test.js +++ /dev/null @@ -1,33 +0,0 @@ -function probablyPrime(n, k) { - 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 % 2 === 0) { - d /= 2; - ++s; - } - - WitnessLoop: do { - // A base between 2 and n - 2 - var x = Math.pow(2 + Math.floor(Math.random() * (n - 3)), d) % n; - - if (x === 1 || x === n - 1) - continue; - - for (var i = s - 1; i--;) { - x = x * x % n; - if (x === 1) - return false; - if (x === n - 1) - continue WitnessLoop; - } - - return false; - } while (--k); - - return true; -} 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/Liberty-BASIC/miller-rabin-primality-test.liberty b/Task/Miller-Rabin-primality-test/Liberty-BASIC/miller-rabin-primality-test.liberty deleted file mode 100644 index 5cb0cea40c..0000000000 --- a/Task/Miller-Rabin-primality-test/Liberty-BASIC/miller-rabin-primality-test.liberty +++ /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/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/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.pari b/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-1.pari deleted file mode 100644 index 881f191a12..0000000000 --- a/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-1.pari +++ /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.pari b/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-2.pari deleted file mode 100644 index b7a49019a4..0000000000 --- a/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-2.pari +++ /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.pari b/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-3.pari deleted file mode 100644 index 0e788eb524..0000000000 --- a/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-3.pari +++ /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-6/miller-rabin-primality-test.pl6 b/Task/Miller-Rabin-primality-test/Perl-6/miller-rabin-primality-test.pl6 deleted file mode 100644 index e106bb5ba6..0000000000 --- a/Task/Miller-Rabin-primality-test/Perl-6/miller-rabin-primality-test.pl6 +++ /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/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 64f4e2375b..0000000000 --- a/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-1.pl +++ /dev/null @@ -1,35 +0,0 @@ -use bigint; -sub is_prime -{ - my ($n,$k) = @_; - return 1 if $n == 2; - return 0 if $n < 2 or $n % 2 == 0; - - $d = $n - 1; - $s = 0; - - while(!($d % 2)) - { - $d /= 2; - $s++; - } - - LOOP: for(1..$k) - { - $a = 2 + int(rand($n-2)); - - $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/PicoLisp/miller-rabin-primality-test.l b/Task/Miller-Rabin-primality-test/PicoLisp/miller-rabin-primality-test.l deleted file mode 100644 index 3a51d0a2a5..0000000000 --- a/Task/Miller-Rabin-primality-test/PicoLisp/miller-rabin-primality-test.l +++ /dev/null @@ -1,47 +0,0 @@ -(de longRand (N) - (use (R D) - (while (=0 (setq R (abs (rand))))) - (until (> R N) - (unless (=0 (setq D (abs (rand)))) - (setq R (* R D)) ) ) - (% R N) ) ) - -(de **Mod (X Y N) - (let M 1 - (loop - (when (bit? 1 Y) - (setq M (% (* M X) N)) ) - (T (=0 (setq Y (>> 1 Y))) - M ) - (setq X (% (* X X) N)) ) ) ) - -(de _prim? (N D S) - (use (A X R) - (while (> 2 (setq A (longRand N)))) - (setq R 0 X (**Mod A D N)) - (loop - (T - (or - (and (=0 R) (= 1 X)) - (= X (dec N)) ) - T ) - (T - (or - (and (> R 0) (= 1 X)) - (>= (inc 'R) S) ) - NIL ) - (setq X (% (* X X) N)) ) ) ) - -(de prime? (N K) - (default K 50) - (and - (> N 1) - (bit? 1 N) - (let (D (dec N) S 0) - (until (bit? 1 D) - (setq - D (>> 1 D) - S (inc S) ) ) - (do K - (NIL (_prim? N D S)) - T ) ) ) ) diff --git a/Task/Miller-Rabin-primality-test/Prolog/miller-rabin-primality-test.pro b/Task/Miller-Rabin-primality-test/Prolog/miller-rabin-primality-test.pro deleted file mode 100644 index db250b459a..0000000000 --- a/Task/Miller-Rabin-primality-test/Prolog/miller-rabin-primality-test.pro +++ /dev/null @@ -1,83 +0,0 @@ -:- module(primality, [is_prime/2]). - -% is_prime/2 returns false if N is composite, true if N probably prime -% implements a Miller-Rabin primality test and is deterministic for N < 3.415e+14, -% and is probabilistic for larger N. Adapted from the Erlang version. -is_prime(1, Ret) :- Ret = false, !. % 1 is non-prime -is_prime(2, Ret) :- Ret = true, !. % 2 is prime -is_prime(3, Ret) :- Ret = true, !. % 3 is prime -is_prime(N, Ret) :- - N > 3, (N mod 2 =:= 0), Ret = false, !. % even number > 3 is composite -is_prime(N, Ret) :- - N > 3, (N mod 2 =:= 1), % odd number > 3 - N < 341550071728321, - deterministic_witnesses(N, L), - is_mr_prime(N, L, Ret), !. % deterministic test -is_prime(N, Ret) :- - random_witnesses(N, 100, [], Out), - is_mr_prime(N, Out, Ret), !. % probabilistic test - -% returns list of deterministic witnesses -deterministic_witnesses(N, L) :- N < 1373653, - L = [2, 3]. -deterministic_witnesses(N, L) :- N < 9080191, - L = [31, 73]. -deterministic_witnesses(N, L) :- N < 25326001, - L = [2, 3, 5]. -deterministic_witnesses(N, L) :- N < 3215031751, - L = [2, 3, 5, 7]. -deterministic_witnesses(N, L) :- N < 4759123141, - L = [2, 7, 61]. -deterministic_witnesses(N, L) :- N < 1122004669633, - L = [2, 13, 23, 1662803]. -deterministic_witnesses(N, L) :- N < 2152302898747, - L = [2, 3, 5, 7, 11]. -deterministic_witnesses(N, L) :- N < 3474749660383, - L = [2, 3, 5, 7, 11, 13]. -deterministic_witnesses(N, L) :- N < 341550071728321, - L = [2, 3, 5, 7, 11, 13, 17]. - -% random_witnesses/4 returns a list of K witnesses selected at random with range 2 -> N-2 -random_witnesses(_, 0, T, T). -random_witnesses(N, K, T, Out) :- - G is N - 2, - H is 1 + random(G), - I is K - 1, - random_witnesses(N, I, [H | T], Out), !. - -% find_ds/2 receives odd integer N and returns [D, S] s.t. N-1 = 2^S * D -find_ds(N, L) :- - A is N - 1, - find_ds(A, 0, L), !. - -find_ds(D, S, L) :- - D mod 2 =:= 0, - P is D // 2, - Q is S + 1, - find_ds(P, Q, L), !. -find_ds(D, S, L) :- - L = [D, S]. - -is_mr_prime(N, As, Ret) :- - find_ds(N, L), - L = [D | T], - T = [S | _], - outer_loop(N, As, D, S, Ret), !. - -outer_loop(N, As, D, S, Ret) :- - As = [A | At], - Base is powm(A, D, N), - inner_loop(Base, N, 0, S, Result), - ( Result == false -> Ret = false - ; Result == true, At == [] -> Ret = true - ; outer_loop(N, At, D, S, Ret) - ). - -inner_loop(Base, N, Loop, S, Result) :- - Next_Base is (Base * Base) mod N, - Next_Loop is Loop + 1, - ( Loop =:= 0, Base =:= 1 -> Result = true - ; Base =:= N-1 -> Result = true - ; Next_Loop =:= S -> Result = false - ; inner_loop(Next_Base, N, Next_Loop, S, Result) - ). diff --git a/Task/Miller-Rabin-primality-test/PureBasic/miller-rabin-primality-test.purebasic b/Task/Miller-Rabin-primality-test/PureBasic/miller-rabin-primality-test.purebasic deleted file mode 100644 index 3d608e8f2d..0000000000 --- a/Task/Miller-Rabin-primality-test/PureBasic/miller-rabin-primality-test.purebasic +++ /dev/null @@ -1,29 +0,0 @@ -Enumeration - #Composite - #Probably_prime -EndEnumeration - -Procedure Miller_Rabin(n, k) - Protected d=n-1, s, x, r - If n=2 - ProcedureReturn #Probably_prime - ElseIf n%2=0 Or n<2 - ProcedureReturn #Composite - EndIf - While d%2=0 - d/2 - s+1 - Wend - While k>0 - k-1 - x=Int(Pow(2+Random(n-4),d))%n - If x=1 Or x=n-1: Continue: EndIf - For r=1 To s-1 - x=(x*x)%n - If x=1: ProcedureReturn #Composite: EndIf - If x=n-1: Break: EndIf - Next - If x<>n-1: ProcedureReturn #Composite: EndIf - Wend - ProcedureReturn #Probably_prime -EndProcedure diff --git a/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-1.py b/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-1.py deleted file mode 100644 index 092d294d11..0000000000 --- a/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-1.py +++ /dev/null @@ -1,78 +0,0 @@ -import random - -_mrpt_num_trials = 5 # number of bases to test - -def is_probable_prime(n): - """ - Miller-Rabin primality test. - - A return value of False means n is certainly not prime. A return value of - True means n is very likely a prime. - - >>> is_probable_prime(1) - Traceback (most recent call last): - ... - AssertionError - >>> is_probable_prime(2) - True - >>> is_probable_prime(3) - True - >>> is_probable_prime(4) - False - >>> is_probable_prime(5) - True - >>> is_probable_prime(123456789) - False - - >>> primes_under_1000 = [i for i in range(2, 1000) if is_probable_prime(i)] - >>> len(primes_under_1000) - 168 - >>> primes_under_1000[-10:] - [937, 941, 947, 953, 967, 971, 977, 983, 991, 997] - - >>> is_probable_prime(6438080068035544392301298549614926991513861075340134\ -3291807343952413826484237063006136971539473913409092293733259038472039\ -7133335969549256322620979036686633213903952966175107096769180017646161\ -851573147596390153) - True - - >>> is_probable_prime(7438080068035544392301298549614926991513861075340134\ -3291807343952413826484237063006136971539473913409092293733259038472039\ -7133335969549256322620979036686633213903952966175107096769180017646161\ -851573147596390153) - False - """ - assert n >= 2 - # special case 2 - if n == 2: - return True - # ensure n is odd - if n % 2 == 0: - return False - # write n-1 as 2**s * d - # repeatedly try to divide n-1 by 2 - s = 0 - d = n-1 - while True: - quotient, remainder = divmod(d, 2) - if remainder == 1: - break - s += 1 - d = quotient - assert(2**s * d == n-1) - - # test the base a to see whether it is a witness for the compositeness of n - def try_composite(a): - if pow(a, d, n) == 1: - return False - for i in range(s): - if pow(a, 2**i * d, n) == n-1: - return False - return True # n is definitely composite - - for i in range(_mrpt_num_trials): - a = random.randrange(2, n) - if try_composite(a): - return False - - return True # no base tested showed n as composite diff --git a/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-2.py b/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-2.py deleted file mode 100644 index e2edb1ea85..0000000000 --- a/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-2.py +++ /dev/null @@ -1,37 +0,0 @@ -def _try_composite(a, d, n, s): - if pow(a, d, n) == 1: - return False - for i in range(s): - if pow(a, 2**i * d, n) == n-1: - return False - return True # n is definitely composite - -def is_prime(n, _precision_for_huge_n=16): - if n in _known_primes or n in (0, 1): - return True - if any((n % p) == 0 for p in _known_primes): - return False - d, s = n - 1, 0 - while not d % 2: - d, s = d >> 1, s + 1 - # Returns exact according to http://primes.utm.edu/prove/prove2_3.html - if n < 1373653: - return not any(_try_composite(a, d, n, s) for a in (2, 3)) - if n < 25326001: - return not any(_try_composite(a, d, n, s) for a in (2, 3, 5)) - if n < 118670087467: - if n == 3215031751: - return False - return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7)) - if n < 2152302898747: - return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11)) - if n < 3474749660383: - return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13)) - if n < 341550071728321: - return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13, 17)) - # otherwise - return not any(_try_composite(a, d, n, s) - for a in _known_primes[:_precision_for_huge_n]) - -_known_primes = [2, 3] -_known_primes += [x for x in range(5, 1000, 2) if is_prime(x)] diff --git a/Task/Miller-Rabin-primality-test/README b/Task/Miller-Rabin-primality-test/README deleted file mode 100644 index 6f32fd0ac4..0000000000 --- a/Task/Miller-Rabin-primality-test/README +++ /dev/null @@ -1 +0,0 @@ -Data source: http://rosettacode.org/wiki/Miller-Rabin_primality_test 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 34dcc2b712..0000000000 --- a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx +++ /dev/null @@ -1,62 +0,0 @@ -/*REXX program puts the Miller-Rabin primality test through its paces.*/ -parse arg limit accur . /*get some optional arguments*/ -if limit=='' | limit==',' then limit=1000 /*maybe assume LIMIT default.*/ -if accur=='' | accur==',' then accur=10 /* " " ACCUR " */ -numeric digits max(200, 2*limit) /*we're dealing with some biggies*/ -tell= accur<0 /*show primes if K is negative.*/ -accur=abs(accur) /*now, use absolute value of K.*/ -call suspenders limit /*suspenders now, belt later ··· */ -primePi=# /*save the count of (real) primes*/ -say "There are" primePi 'primes ≤' limit /*might as well crow a wee bit*/ -say /*nothing wrong with whitespace. */ - do a=2 to accur /*(skipping 1) do range of K's.*/ - say copies('─',79) /*show separator for the eyeballs*/ - mrp=0 /*prime counter for this pass. */ - do z=1 for limit /*now, let's get busy and crank. */ - p=Miller_Rabin(z,a) /*invoke and pray... */ - if p==0 then iterate /*Not prime? Then try another. */ - mrp=mrp+1 /*well, found another one, by gum*/ - if tell then say z, /*maybe should do a show & tell ?*/ - 'is prime according to Miller-Rabin primality test with K='a - if !.z\==0 then iterate - say '[K='a"] " z "isn't prime !" /*oopsy-doopsy & whoopsy-daisy!*/ - end /*z*/ - say 'for 1──►'limit", K="a', Miller-Rabin primality test found' mrp, - 'primes {out of' primePi"}" - end /*a*/ -exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────Miller─Rabin primality test.─────*/ -/*─────────────────────────────────────Rabin─Miller (also known as)─────*/ -Miller_Rabin: procedure; parse arg n,k -if n==2 then return 1 /*special case of an even prime. */ -if n<2 | n//2==0 then return 0 /*check for low, or even number.*/ -d=n-1 /*just a temp variable for speed.*/ -nL=n-1 /*saves a bit of time, down below*/ -s=0 /*teeter-toter variable (see-saw)*/ - do while d//2==0; d=d%2; s=s+1; end /*while d//2==0*/ - - do k; a=random(2,nL) - x=(a**d) // n /*this number can get big fast. */ - if x==1 | x==nL then iterate /*if so, try another power of A. */ - do r=1 for s-1; x=(x*x)//n /*compute new X ≡ X² modulus N.*/ - if x==1 then return 0 /*it's definitely not prime. */ - if x==nL then leave - end /*r*/ - if x\==nL then return 0 /*nope, it ain't prime nohows. */ - end /*k*/ - /*maybe it is, maybe it ain't ...*/ -return 1 /*coulda/woulda/shoulda be prime.*/ -/*──────────────────────────────────SUSPENDERS subroutine───────────────*/ -suspenders: parse arg high; @.=0; !.=0 /*crank up the ole prime factory.*/ -_='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' - do #=1 for words(_); p=word(_,#); @.#=p; s.#=p*p; !.p=1; end /*#*/ -#=#-1 /*adjust the # of primes so far. */ - do j=@.#+2 by 2 to high /*just process the odd integers. */ - if j//3==0 then iterate /*divisible by three? Yes, ¬prime*/ - if right(j,1)==5 then iterate /* " " five? " " */ - do k=4 while s.k<=j /*let's do the ole primality test*/ - if j//@.k==0 then iterate j /*the Greek way, in days of yore.*/ - end /*k*/ /*a useless comment, but hey!! */ - #=#+1; @.#=j; s.#=j*j; !.j=1 /*bump prime ctr, prime, primeidx*/ - end /*j*/ /*this comment not left blank. */ -return /*whew! All done with the primes*/ 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/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 37dd4236b8..0000000000 --- a/Task/Miller-Rabin-primality-test/Ruby/miller-rabin-primality-test-1.rb +++ /dev/null @@ -1,23 +0,0 @@ -require 'openssl' -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 = OpenSSL::BN::new(a.to_s).mod_exp(d,n) #x = (a**d) % n - next if x == 1 or x == n-1 - for r in (1 .. s-1) - x = x.mod_exp(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/Run-BASIC/miller-rabin-primality-test.run b/Task/Miller-Rabin-primality-test/Run-BASIC/miller-rabin-primality-test.run deleted file mode 100644 index 88b4eddd11..0000000000 --- a/Task/Miller-Rabin-primality-test/Run-BASIC/miller-rabin-primality-test.run +++ /dev/null @@ -1,54 +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 - x = (int(rnd(1) * (n-4))^d) mod n - if x = 1 or 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/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/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/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/Tcl/miller-rabin-primality-test.tcl b/Task/Miller-Rabin-primality-test/Tcl/miller-rabin-primality-test.tcl deleted file mode 100644 index 4e002e0d01..0000000000 --- a/Task/Miller-Rabin-primality-test/Tcl/miller-rabin-primality-test.tcl +++ /dev/null @@ -1,34 +0,0 @@ -package require Tcl 8.5 - -proc miller_rabin {n k} { - if {$n <= 3} {return true} - if {$n % 2 == 0} {return false} - - # write n - 1 as 2^s·d with d odd by factoring powers of 2 from n − 1 - set d [expr {$n - 1}] - set s 0 - while {$d % 2 == 0} { - set d [expr {$d / 2}] - incr s - } - - while {$k > 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/Minesweeper-game/GUISS/minesweeper-game.guiss b/Task/Minesweeper-game/GUISS/minesweeper-game.guiss deleted file mode 100644 index f3139f80c5..0000000000 --- a/Task/Minesweeper-game/GUISS/minesweeper-game.guiss +++ /dev/null @@ -1 +0,0 @@ -Start,Programs,Games,Minesweeper diff --git a/Task/Minesweeper-game/MATLAB/minesweeper-game-1.m b/Task/Minesweeper-game/MATLAB/minesweeper-game-1.m new file mode 100644 index 0000000000..becfeae077 --- /dev/null +++ b/Task/Minesweeper-game/MATLAB/minesweeper-game-1.m @@ -0,0 +1 @@ +xpbombs diff --git a/Task/Minesweeper-game/MATLAB/minesweeper-game.m b/Task/Minesweeper-game/MATLAB/minesweeper-game-2.m similarity index 100% rename from Task/Minesweeper-game/MATLAB/minesweeper-game.m rename to Task/Minesweeper-game/MATLAB/minesweeper-game-2.m diff --git a/Task/Modular-exponentiation/Clojure/modular-exponentiation.clj b/Task/Modular-exponentiation/Clojure/modular-exponentiation-1.clj similarity index 100% rename from Task/Modular-exponentiation/Clojure/modular-exponentiation.clj rename to Task/Modular-exponentiation/Clojure/modular-exponentiation-1.clj diff --git a/Task/Modular-exponentiation/Clojure/modular-exponentiation-2.clj b/Task/Modular-exponentiation/Clojure/modular-exponentiation-2.clj new file mode 100644 index 0000000000..d6324e16ab --- /dev/null +++ b/Task/Modular-exponentiation/Clojure/modular-exponentiation-2.clj @@ -0,0 +1,5 @@ +(defn modpow + " b^e mod m (using Java which solves some cases the pure clojure method has to be modified to tackle--i.e. with large b & e and + calculation simplications when gcd(b, m) == 1 and gcd(e, m) == 1) " + [b e m] + (.modPow (biginteger b) (biginteger e) (biginteger m))) diff --git a/Task/Modular-exponentiation/Factor/modular-exponentiation.factor b/Task/Modular-exponentiation/Factor/modular-exponentiation.factor new file mode 100644 index 0000000000..41fdf788bc --- /dev/null +++ b/Task/Modular-exponentiation/Factor/modular-exponentiation.factor @@ -0,0 +1,6 @@ +! Built-in +2988348162058574136915891421498819466320163312926952423791023078876139 +2351399303373464486466122544523690094744975233415544072992656881240319 +10 40 ^ +^mod . +1527229998585248450016808958343740453059 diff --git a/Task/Modular-exponentiation/Gnuplot/modular-exponentiation.gnuplot b/Task/Modular-exponentiation/Gnuplot/modular-exponentiation.gnuplot new file mode 100644 index 0000000000..bdb57a9af5 --- /dev/null +++ b/Task/Modular-exponentiation/Gnuplot/modular-exponentiation.gnuplot @@ -0,0 +1,5 @@ +_powm(b, e, m, r) = (e == 0 ? r : (e % 2 == 1 ? _powm(b * b % m, e / 2, m, r * b % m) : _powm(b * b % m, e / 2, m, r))) +powm(b, e, m) = _powm(b, e, m, 1) +# Usage +print powm(2, 3453, 131) +# Where b is the base, e is the exponent, m is the modulus, i.e.: b^e mod m diff --git a/Task/Modular-exponentiation/Haskell/modular-exponentiation.hs b/Task/Modular-exponentiation/Haskell/modular-exponentiation.hs index 4909d2944e..4d32b8f1f7 100644 --- a/Task/Modular-exponentiation/Haskell/modular-exponentiation.hs +++ b/Task/Modular-exponentiation/Haskell/modular-exponentiation.hs @@ -1,10 +1,12 @@ powm :: Integer -> Integer -> Integer -> Integer -> Integer powm b 0 m r = r -powm b e m r | e `mod` 2 == 1 = powm (b * b `mod` m) (e `div` 2) m (r * b `mod` m) +powm b e m r + | e `mod` 2 == 1 = powm (b * b `mod` m) (e `div` 2) m (r * b `mod` m) powm b e m r = powm (b * b `mod` m) (e `div` 2) m r main :: IO () -main = putStrLn . show $ +main = + print $ powm 2988348162058574136915891421498819466320163312926952423791023078876139 2351399303373464486466122544523690094744975233415544072992656881240319 diff --git a/Task/Modular-exponentiation/Kotlin/modular-exponentiation.kotlin b/Task/Modular-exponentiation/Kotlin/modular-exponentiation.kotlin new file mode 100644 index 0000000000..b50138abba --- /dev/null +++ b/Task/Modular-exponentiation/Kotlin/modular-exponentiation.kotlin @@ -0,0 +1,10 @@ +// version 1.0.6 + +import java.math.BigInteger + +fun main(args: Array) { + val a = BigInteger("2988348162058574136915891421498819466320163312926952423791023078876139") + val b = BigInteger("2351399303373464486466122544523690094744975233415544072992656881240319") + val m = BigInteger.TEN.pow(40) + println(a.modPow(b, m)) +} diff --git a/Task/Modular-exponentiation/OoRexx/modular-exponentiation.rexx b/Task/Modular-exponentiation/OoRexx/modular-exponentiation.rexx new file mode 100644 index 0000000000..f6303385cb --- /dev/null +++ b/Task/Modular-exponentiation/OoRexx/modular-exponentiation.rexx @@ -0,0 +1,22 @@ +/* Modular exponentiation */ + +numeric digits 100 +say powerMod(, + 2988348162058574136915891421498819466320163312926952423791023078876139,, + 2351399303373464486466122544523690094744975233415544072992656881240319,, + 1e40) +exit + +powerMod: procedure + +use strict arg base, exponent, modulus + +exponent=exponent~d2x~x2b~strip('L','0') +result=1 +base = base // modulus +do exponentPos=exponent~length to 1 by -1 + if (exponent~subChar(exponentPos) == '1') + then result = (result * base) // modulus + base = (base * base) // modulus +end +return result diff --git a/Task/Modular-exponentiation/REXX/modular-exponentiation-1.rexx b/Task/Modular-exponentiation/REXX/modular-exponentiation-1.rexx index 0046162d10..13025dc2d4 100644 --- a/Task/Modular-exponentiation/REXX/modular-exponentiation-1.rexx +++ b/Task/Modular-exponentiation/REXX/modular-exponentiation-1.rexx @@ -18,9 +18,9 @@ powerMod: procedure; parse arg x,p,n /*fast modular exponentiat if p<0 then do; say '***error*** power is negative:' p; exit 13; end parse value max(x**2,p,n)'E0' with "E" e /*obtain the biggest of the three.*/ numeric digits max(20, e*2) /*big enough to handle A². */ - _=1 /*use this for the first value. */ + $=1 /*use this for the first value. */ do while p\==0 /*perform while P isn't zero.*/ - if p//2 then _=_*x//n /*is P odd? (is ÷ remainder≡1).*/ - p=p%2; x=x*x//n /*halve P; calculate x² mod n */ + if p//2 then $=$ * x // n /*is P odd? (is ÷ remainder≡1).*/ + p=p%2; x=x * x // n /*halve P; calculate x² mod n */ end /*while*/ /* [↑] keep mod'ing 'til equal 0.*/ - return _ + return $ diff --git a/Task/Modular-exponentiation/Racket/modular-exponentiation-1.rkt b/Task/Modular-exponentiation/Racket/modular-exponentiation-1.rkt deleted file mode 100644 index ea35a93e0e..0000000000 --- a/Task/Modular-exponentiation/Racket/modular-exponentiation-1.rkt +++ /dev/null @@ -1,6 +0,0 @@ -#lang racket -(require math) -(define a 2988348162058574136915891421498819466320163312926952423791023078876139) -(define b 2351399303373464486466122544523690094744975233415544072992656881240319) -(define m (expt 10 40)) -(modular-expt a b m) diff --git a/Task/Modular-exponentiation/Racket/modular-exponentiation-2.rkt b/Task/Modular-exponentiation/Racket/modular-exponentiation-2.rkt deleted file mode 100644 index 5780a0ee51..0000000000 --- a/Task/Modular-exponentiation/Racket/modular-exponentiation-2.rkt +++ /dev/null @@ -1 +0,0 @@ -1527229998585248450016808958343740453059 diff --git a/Task/Modular-exponentiation/Zkl/modular-exponentiation.zkl b/Task/Modular-exponentiation/Zkl/modular-exponentiation.zkl new file mode 100644 index 0000000000..e51d20fd29 --- /dev/null +++ b/Task/Modular-exponentiation/Zkl/modular-exponentiation.zkl @@ -0,0 +1,6 @@ +var BN=Import("zklBigNum"); +a:=BN("2988348162058574136915891421498819466320163312926952423791023078876139"); +b:=BN("2351399303373464486466122544523690094744975233415544072992656881240319"); +m:=BN(10).pow(40); +a.powm(b,m).println(); +a.powm(b,m) : "%,d".fmt(_).println(); diff --git a/Task/Modular-inverse/Ada/modular-inverse-1.ada b/Task/Modular-inverse/Ada/modular-inverse-1.ada deleted file mode 100644 index 144737c41b..0000000000 --- a/Task/Modular-inverse/Ada/modular-inverse-1.ada +++ /dev/null @@ -1,11 +0,0 @@ -package Mod_Inv is - - procedure X_GCD(A, B: in Natural; D, X, Y: out Integer); - -- the Extended Euclidean Algorithm - -- finds (D, X, Y) with D = GCD(A, B) = A*X + B*Y - - function Inverse(A, M: Integer) return Integer; - -- computes the multiplicative inverse Inv_A of A mod M, using X_GCD - -- raises Constraint_Error if Inv_A does not exist - -end Mod_Inv; diff --git a/Task/Modular-inverse/Ada/modular-inverse-2.ada b/Task/Modular-inverse/Ada/modular-inverse-2.ada deleted file mode 100644 index 69a034dd24..0000000000 --- a/Task/Modular-inverse/Ada/modular-inverse-2.ada +++ /dev/null @@ -1,36 +0,0 @@ -package body Mod_Inv is - - procedure X_GCD(A, B: in Natural; D, X, Y: out Integer) is - -- the Extended Euclidean Algorithm - -- finds (D, X, Y) with D = GCD(A, B) = A*X + B*Y - R: Natural := A mod B; - begin - if R=0 then - D := B; - X := 0; - Y := 1; - else - X_GCD(B, R, D, Y, X); - Y := Y - (A/B)*X; - end if; - end X_GCD; - - function Inverse(A, M: Integer) return Integer is - -- computes the multiplicative inverse of A mod M, using X_GCD - Result, GCD, Dummy: Integer; - begin - X_GCD(A, M, GCD, Result, Dummy); - if GCD /= 1 then -- inverse does not exist! - raise Constraint_Error with - "GCD (" & Integer'Image(A) & "," & Integer'Image(M) & " ) =" & - Integer'Image(GCD) & " /= 1"; - else -- make sure Result is in {0, ..., M-1} - if Result < 0 then - return Result+M; - else - return Result; - end if; - end if; - end Inverse; - -end Mod_Inv; diff --git a/Task/Modular-inverse/Ada/modular-inverse-3.ada b/Task/Modular-inverse/Ada/modular-inverse-3.ada deleted file mode 100644 index c8fdf4306d..0000000000 --- a/Task/Modular-inverse/Ada/modular-inverse-3.ada +++ /dev/null @@ -1,9 +0,0 @@ -with Ada.Text_IO; with Mod_Inv; use Mod_Inv, Ada.text_IO; - -procedure Mod_Inv_Test is -begin - -- Put_Line(Natural'Image(Inverse(154, 3311))); - -- The above would raise CONSTRAINT_ERROR : GCD ( 154, 3311 ) = 77 /= 1 - - Put_Line(Natural'Image(Inverse(42, 2017))); -end Mod_Inv_Test; diff --git a/Task/Modular-inverse/Ada/modular-inverse.ada b/Task/Modular-inverse/Ada/modular-inverse.ada new file mode 100644 index 0000000000..d1baf768e9 --- /dev/null +++ b/Task/Modular-inverse/Ada/modular-inverse.ada @@ -0,0 +1,18 @@ +with Ada.Text_IO;use Ada.Text_IO; +procedure modular_inverse is + -- inv_mod calculates the inverse of a mod n. We should have n>0 and, at the end, the contract is a*Result=1 mod n + -- If this is false then we raise an exception (don't forget the -gnata option when you compile + function inv_mod (a : Integer; n : Positive) return Integer with post=> (a * inv_mod'Result) mod n = 1 is + -- To calculate the inverse we do as if we would calculate the GCD with the Euclid extended algorithm + -- (but we just keep the coefficient on a) + function inverse (a, b, u, v : Integer) return Integer is (if b=0 then u else inverse (b, a mod b, v, u-(v*a)/b)); + begin + return inverse (a, n, 1, 0); + end inv_mod; +begin + -- This will output -48 (which is correct) + Put_Line (inv_mod (42,2017)'img); + -- The further line will raise an exception since the GCD will not be 1 + Put_Line (inv_mod (42,77)'img); + exception when others => Put_Line ("The inverse doesn't exist."); +end bitmap; diff --git a/Task/Modular-inverse/Kotlin/modular-inverse.kotlin b/Task/Modular-inverse/Kotlin/modular-inverse.kotlin new file mode 100644 index 0000000000..8a1e58842c --- /dev/null +++ b/Task/Modular-inverse/Kotlin/modular-inverse.kotlin @@ -0,0 +1,9 @@ +// version 1.0.6 + +import java.math.BigInteger + +fun main(args: Array) { + val a = BigInteger.valueOf(42) + val m = BigInteger.valueOf(2017) + println(a.modInverse(m)) +} diff --git a/Task/Modular-inverse/Zkl/modular-inverse.zkl b/Task/Modular-inverse/Zkl/modular-inverse.zkl new file mode 100644 index 0000000000..19ecabde05 --- /dev/null +++ b/Task/Modular-inverse/Zkl/modular-inverse.zkl @@ -0,0 +1,5 @@ +fcn gcdExt(a,b){ + if(b==0) return(1,0,a); + q,r:=a.divr(b); s,t,g:=gcdExt(b,r); return(t,s-q*t,g); +} +fcn modInv(a,m){i,_,g:=gcdExt(a,m); if(g==1) {if(i<0)i+m} else Void} diff --git a/Task/Monte-Carlo-methods/360-Assembly/monte-carlo-methods.360 b/Task/Monte-Carlo-methods/360-Assembly/monte-carlo-methods.360 new file mode 100644 index 0000000000..dff92a4f4d --- /dev/null +++ b/Task/Monte-Carlo-methods/360-Assembly/monte-carlo-methods.360 @@ -0,0 +1,82 @@ +* Monte Carlo methods 08/03/2017 +MONTECAR CSECT + USING MONTECAR,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + LA R8,1000 isamples=1000 + LA R6,4 i=4 + DO WHILE=(C,R6,LE,=F'7') do i=4 to 7 + MH R8,=H'10' isamples=isamples*10 + ZAP HITS,=P'0' hits=0 + LA R7,1 j=1 + DO WHILE=(CR,R7,LE,R8) do j=1 to isamples + BAL R14,RNDPK call random + ZAP X,RND x=rnd + BAL R14,RNDPK call random + ZAP Y,RND y=rnd + ZAP WP,X x + MP WP,X x**2 + DP WP,ONE ~ + ZAP XX,WP(8) x**2 normalized + ZAP WP,Y y + MP WP,Y y**2 + DP WP,ONE ~ + ZAP YY,WP(8) y**2 normalized + AP XX,YY xx=x**2+y**2 + IF CP,XX,LT,ONE THEN if x**2+y**2<1 then + AP HITS,=P'1' hits=hits+1 + ENDIF , endif + LA R7,1(R7) j++ + ENDDO , enddo j + CVD R8,PSAMPLES psamples=isamples + ZAP WP,=P'4' 4 + MP WP,ONE ~ + MP WP,HITS *hits + DP WP,PSAMPLES /psamples + ZAP MCPI,WP(8) mcpi=4*hits/psamples + XDECO R6,WC edit i + MVC PG+4(1),WC+11 output i + MVC WC,MASK load mask + ED WC,PSAMPLES edit psamples + MVC PG+6(8),WC+8 output psamples + UNPK WC,MCPI unpack mcpi + OI WC+15,X'F0' zap sign + MVC PG+31(1),WC+6 output mcpi + MVC PG+33(6),WC+7 output mcpi decimals + XPRNT PG,L'PG print buffer + LA R6,1(R6) i++ + ENDDO , enddo i + L R13,4(0,R13) restore previous savearea pointer + LM R14,R12,12(R13) restore previous context + XR R15,R15 rc=0 + BR R14 exit +RNDPK EQU * ---- random number generator + ZAP WP,RNDSEED w=seed + MP WP,RNDCNSTA w*=cnsta + AP WP,RNDCNSTB w+=cnstb + MVC RNDSEED,WP+8 seed=w mod 10**15 + MVC RND,=PL8'0' 0<=rnd<1 + MVC RND+3(5),RNDSEED+3 return rnd + BR R14 ---- return +PSAMPLES DS 0D,PL8 F(15,0) +RNDSEED DC PL8'613058151221121' linear congruential constant +RNDCNSTA DC PL8'944021285986747' " +RNDCNSTB DC PL8'852529586767995' " +RND DS PL8 fixed(15,9) +ONE DC PL8'1.000000000' 1 fixed(15,9) +HITS DS PL8 fixed(15,0) +X DS PL8 fixed(15,9) +Y DS PL8 fixed(15,9) +MCPI DS PL8 fixed(15,9) +XX DS PL8 fixed(15,9) +YY DS PL8 fixed(15,9) +PG DC CL80'10**x xxxxxxxx samples give Pi=x.xxxxxx' buffer +MASK DC X'40202020202020202020202020202120' mask CL16 15num +WC DS PL16 character 16 +WP DS PL16 packed decimal 16 + YREGS + END MONTECAR diff --git a/Task/Monte-Carlo-methods/Dart/monte-carlo-methods.dart b/Task/Monte-Carlo-methods/Dart/monte-carlo-methods.dart new file mode 100644 index 0000000000..3471bda9cd --- /dev/null +++ b/Task/Monte-Carlo-methods/Dart/monte-carlo-methods.dart @@ -0,0 +1,50 @@ +import 'dart:async'; +import 'dart:html'; +import 'dart:math' show Random; + +// We changed 5 lines of code to make this sample nicer on +// the web (so that the execution waits for animation frame, +// the number gets updated in the DOM, and the program ends +// after 500 iterations). + +main() async { + print('Compute π using the Monte Carlo method.'); + var output = querySelector("#output"); + await for (var estimate in computePi().take(500)) { + print('π ≅ $estimate'); + output.text = estimate.toStringAsFixed(5); + await window.animationFrame; + } +} + +/// Generates a stream of increasingly accurate estimates of π. +Stream computePi({int batch: 100000}) async* { + var total = 0; + var count = 0; + while (true) { + var points = generateRandom().take(batch); + var inside = points.where((p) => p.isInsideUnitCircle); + total += batch; + count += inside.length; + var ratio = count / total; + // Area of a circle is A = π⋅r², therefore π = A/r². + // So, when given random points with x ∈ <0,1>, + // y ∈ <0,1>, the ratio of those inside a unit circle + // should approach π / 4. Therefore, the value of π + // should be: + yield ratio * 4; + } +} + +Iterable generateRandom([int seed]) sync* { + final random = new Random(seed); + while (true) { + yield new Point(random.nextDouble(), random.nextDouble()); + } +} + +class Point { + final double x, y; + const Point(this.x, this.y); + bool get isInsideUnitCircle => x * x + y * y <= 1; +} diff --git a/Task/Monte-Carlo-methods/F-Sharp/monte-carlo-methods.fs b/Task/Monte-Carlo-methods/F-Sharp/monte-carlo-methods.fs new file mode 100644 index 0000000000..cd9bccac2f --- /dev/null +++ b/Task/Monte-Carlo-methods/F-Sharp/monte-carlo-methods.fs @@ -0,0 +1,19 @@ +let print x = printfn "%A" x + +let MonteCarloPiGreco niter = + let eng = System.Random() + let action () = + let x: float = eng.NextDouble() + let y: float = eng.NextDouble() + let res: float = System.Math.Sqrt(x**2.0 + y**2.0) + if res < 1.0 then + 1 + else + 0 + let res = [ for x in 1..niter do yield action() ] + let tmp: float = float(List.reduce (+) res) / float(res.Length) + 4.0*tmp + +MonteCarloPiGreco 1000 |> print +MonteCarloPiGreco 10000 |> print +MonteCarloPiGreco 100000 |> print diff --git a/Task/Monte-Carlo-methods/Futhark/monte-carlo-methods.futhark b/Task/Monte-Carlo-methods/Futhark/monte-carlo-methods.futhark index 7bde2173a1..d426996d19 100644 --- a/Task/Monte-Carlo-methods/Futhark/monte-carlo-methods.futhark +++ b/Task/Monte-Carlo-methods/Futhark/monte-carlo-methods.futhark @@ -1,6 +1,8 @@ +import "futlib/math" + default(f32) -fun dirvcts(): [2][30]int = +fun dirvcts(): [2][30]i32 = [ [ 536870912, 268435456, 134217728, 67108864, 33554432, 16777216, 8388608, 4194304, 2097152, 1048576, 524288, 262144, 131072, 65536, 32768, 16384, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1 @@ -11,36 +13,36 @@ fun dirvcts(): [2][30]int = ] -fun grayCode(x: int): int = (x >> 1) ^ x +fun grayCode(x: i32): i32 = (x >> 1) ^ x ---------------------------------------- --- Sobol Generator ---------------------------------------- -fun testBit(n: int, ind: int): bool = +fun testBit(n: i32, ind: i32): bool = let t = (1 << ind) in (n & t) == t -fun xorInds(n: int) (dir_vs: [num_bits]int): int = - let reldv_vals = zipWith (fn dv i => +fun xorInds(n: i32) (dir_vs: [num_bits]i32): i32 = + let reldv_vals = zipWith (\ dv i -> if testBit(grayCode n,i) then dv else 0) dir_vs (iota num_bits) in reduce (^) 0 reldv_vals -fun sobolIndI (dir_vs: [m][num_bits]int, n: int): [m]int = +fun sobolIndI (dir_vs: [m][num_bits]i32, n: i32): [m]i32 = map (xorInds n) dir_vs -fun sobolIndR(dir_vs: [m][num_bits]int) (n: int ): [m]f32 = +fun sobolIndR(dir_vs: [m][num_bits]i32) (n: i32 ): [m]f32 = let divisor = 2.0 ** f32(num_bits) let arri = sobolIndI( dir_vs, n ) - in map (fn (x: int): f32 => f32(x) / divisor) arri + in map (\ (x: i32): f32 -> f32(x) / divisor) arri -fun main(n: int): f32 = +fun main(n: i32): f32 = let rand_nums = map (sobolIndR (dirvcts())) (iota n) - let dists = map (fn xy => - let (x,y) = (xy[0],xy[1]) in sqrt32(x*x + y*y)) + let dists = map (\xy -> + let (x,y) = (xy[0],xy[1]) in f32.sqrt(x*x + y*y)) rand_nums - let bs = map (fn d => if d <= 1.0f32 then 1 else 0) dists + let bs = map (\d -> if d <= 1.0f32 then 1 else 0) dists let inside = reduce (+) 0 bs in 4.0f32*f32(inside)/f32(n) diff --git a/Task/Monte-Carlo-methods/JavaScript/monte-carlo-methods-1.js b/Task/Monte-Carlo-methods/JavaScript/monte-carlo-methods-1.js new file mode 100644 index 0000000000..1010756604 --- /dev/null +++ b/Task/Monte-Carlo-methods/JavaScript/monte-carlo-methods-1.js @@ -0,0 +1,20 @@ +function mcpi(n) { + var x, y, m = 0; + + for (var i = 0; i < n; i += 1) { + x = Math.random(); + y = Math.random(); + + if (x * x + y * y < 1) { + m += 1; + } + } + + return 4 * m / n; +} + +console.log(mcpi(1000)); +console.log(mcpi(10000)); +console.log(mcpi(100000)); +console.log(mcpi(1000000)); +console.log(mcpi(10000000)); diff --git a/Task/Monte-Carlo-methods/JavaScript/monte-carlo-methods-2.js b/Task/Monte-Carlo-methods/JavaScript/monte-carlo-methods-2.js new file mode 100644 index 0000000000..f9ab456a6a --- /dev/null +++ b/Task/Monte-Carlo-methods/JavaScript/monte-carlo-methods-2.js @@ -0,0 +1,30 @@ +(() => { + 'use strict'; + + // monteCarloPi :: Int -> Float + const monteCarloPi = n => + 4 * range(1, n) + .reduce(a => { + const [x, y] = [rnd(), rnd()]; + return x * x + y * y < 1 ? a + 1 : a; + }, 0) / n; + + + // GENERIC FUNCTIONS + + // range :: Int -> Int -> [Int] + const range = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // rnd :: () -> Float + const rnd = Math.random; + + + // TEST with from 1000 samples to 10E8 samples + return range(3, 8) + .map(x => monteCarloPi(Math.pow(10, x))); + + // e.g. -> [3.14, 3.1404, 3.13304, 3.142408, 3.1420304, 3.14156788] +})(); diff --git a/Task/Monte-Carlo-methods/JavaScript/monte-carlo-methods-3.js b/Task/Monte-Carlo-methods/JavaScript/monte-carlo-methods-3.js new file mode 100644 index 0000000000..233de9ea72 --- /dev/null +++ b/Task/Monte-Carlo-methods/JavaScript/monte-carlo-methods-3.js @@ -0,0 +1 @@ +[3.14, 3.1404, 3.13304, 3.142408, 3.1420304, 3.14156788] diff --git a/Task/Monte-Carlo-methods/JavaScript/monte-carlo-methods.js b/Task/Monte-Carlo-methods/JavaScript/monte-carlo-methods.js deleted file mode 100644 index 05c118d53f..0000000000 --- a/Task/Monte-Carlo-methods/JavaScript/monte-carlo-methods.js +++ /dev/null @@ -1,18 +0,0 @@ -function mcpi(n){ - var x,y,m=0; - - for(var i = 0; i < n; i += 1) { - x = Math.random(); - y = Math.random(); - - if (x*x + y*y < 1) { m += 1; } - } - - return 4*m/n; -} - -console.log(mcpi(1000)); -console.log(mcpi(10000)); -console.log(mcpi(100000)); -console.log(mcpi(1000000)); -console.log(mcpi(10000000)); diff --git a/Task/Monte-Carlo-methods/Kotlin/monte-carlo-methods.kotlin b/Task/Monte-Carlo-methods/Kotlin/monte-carlo-methods.kotlin new file mode 100644 index 0000000000..d19195cf57 --- /dev/null +++ b/Task/Monte-Carlo-methods/Kotlin/monte-carlo-methods.kotlin @@ -0,0 +1,23 @@ +// version 1.1.0 + +fun mcPi(n: Int): Double { + var inside = 0 + (1..n).forEach { + val x = Math.random() + val y = Math.random() + if (x * x + y * y <= 1.0) inside++ + } + return 4.0 * inside / n +} + +fun main(args: Array) { + println("Iterations -> Approx Pi -> Error%") + println("---------- ---------- ------") + var n = 1_000 + while (n <= 100_000_000) { + val pi = mcPi(n) + val err = Math.abs(Math.PI - pi) / Math.PI * 100.0 + println(String.format("%9d -> %10.8f -> %6.4f", n, pi, err)) + n *= 10 + } +} diff --git a/Task/Monte-Carlo-methods/Perl/monte-carlo-methods.pl b/Task/Monte-Carlo-methods/Perl/monte-carlo-methods.pl index 8876a0471c..74e7a57bff 100644 --- a/Task/Monte-Carlo-methods/Perl/monte-carlo-methods.pl +++ b/Task/Monte-Carlo-methods/Perl/monte-carlo-methods.pl @@ -2,8 +2,8 @@ sub pi { my $nthrows = shift; my $inside = 0; foreach (1 .. $nthrows) { - my $x = rand * 2 - 1, - $y = rand * 2 - 1; + my $x = rand() * 2 - 1; + my $y = rand() * 2 - 1; if (sqrt($x*$x + $y*$y) < 1) { $inside++; } @@ -11,4 +11,4 @@ sub pi { return 4 * $inside / $nthrows; } -printf "%9d: %07f\n", $_, pi($_) foreach 10**4, 10**6; +printf "%9d: %07f\n", $_, pi($_) for 10**4, 10**6; diff --git a/Task/Monte-Carlo-methods/Phix/monte-carlo-methods.phix b/Task/Monte-Carlo-methods/Phix/monte-carlo-methods.phix new file mode 100644 index 0000000000..dd0a02a36a --- /dev/null +++ b/Task/Monte-Carlo-methods/Phix/monte-carlo-methods.phix @@ -0,0 +1,11 @@ +integer N = 100 +for i=1 to 6 do + integer inside = 0 + for i=1 to N do + integer x = rand(N), + y = rand(N) + inside += (x*x+y*y; +import ; + +main(args(2)) := monteCarlo(stringToInt(args[1]), stringToInt(args[2])); + +monteCarlo(n, seed) := + let + totalHits := monteCarloHelper(n, seedRandom(seed), 0); + in + (totalHits / intToFloat(n))*4.0; + +monteCarloHelper(n, generator, result) := + let + xRand := getRandom(generator); + x := xRand.Value/(generator.RandomMax + 1.0); + yRand := getRandom(xRand.Generator); + y := yRand.Value/(generator.RandomMax + 1.0); + + newResult := result + 1 when x^2 + y^2 < 1.0 else + result; + in + result when n < 0 else + monteCarloHelper(n - 1, yRand.Generator, newResult); diff --git a/Task/Monte-Carlo-methods/SequenceL/monte-carlo-methods-2.sequencel b/Task/Monte-Carlo-methods/SequenceL/monte-carlo-methods-2.sequencel new file mode 100644 index 0000000000..6fe86335e7 --- /dev/null +++ b/Task/Monte-Carlo-methods/SequenceL/monte-carlo-methods-2.sequencel @@ -0,0 +1,25 @@ +import ; +import ; + +main(args(2)) := monteCarlo(stringToInt(args[1]), stringToInt(args[2])); + +chunks := 100; +monteCarlo3(n, seed) := + let + newSeeds := getRandomSequence(seedRandom(seed), chunks).Value; + totalHits := monteCarloHelper(n / chunks, seedRandom(newSeeds), 0); + in + (sum(totalHits) / intToFloat((n / chunks)*chunks))*4.0; + +monteCarloHelper(n, generator, result) := + let + xRand := getRandom(generator); + x := xRand.Value/(generator.RandomMax + 1.0); + yRand := getRandom(xRand.Generator); + y := yRand.Value/(generator.RandomMax + 1.0); + + newResult := result + 1 when x^2 + y^2 < 1.0 else + result; + in + result when n < 0 else + monteCarloHelper(n - 1, yRand.Generator, newResult); diff --git a/Task/Monte-Carlo-methods/Sidef/monte-carlo-methods.sidef b/Task/Monte-Carlo-methods/Sidef/monte-carlo-methods.sidef new file mode 100644 index 0000000000..2255386b13 --- /dev/null +++ b/Task/Monte-Carlo-methods/Sidef/monte-carlo-methods.sidef @@ -0,0 +1,9 @@ +func monteCarloPi(nthrows) { + 4 * (^nthrows -> count_by { + hypot(1.rand(2) - 1, 1.rand(2) - 1) < 1 + }) / nthrows +} + +for n in [1e2, 1e3, 1e4, 1e5, 1e6] { + printf("%9d: %07f\n", n, monteCarloPi(n)) +} diff --git a/Task/Monte-Carlo-methods/Stata/monte-carlo-methods.stata b/Task/Monte-Carlo-methods/Stata/monte-carlo-methods.stata new file mode 100644 index 0000000000..903389caf5 --- /dev/null +++ b/Task/Monte-Carlo-methods/Stata/monte-carlo-methods.stata @@ -0,0 +1,17 @@ +program define mcdisk + clear all + quietly set obs `1' + gen x=2*runiform() + gen y=2*runiform() + quietly count if (x-1)^2+(y-1)^2<1 + display 4*r(N)/_N +end + +. mcdisk 10000 +3.1424 + +. mcdisk 1000000 +3.141904 + +. mcdisk 100000000 +3.1416253 diff --git a/Task/Monte-Carlo-methods/Zkl/monte-carlo-methods-1.zkl b/Task/Monte-Carlo-methods/Zkl/monte-carlo-methods-1.zkl new file mode 100644 index 0000000000..dfb3341731 --- /dev/null +++ b/Task/Monte-Carlo-methods/Zkl/monte-carlo-methods-1.zkl @@ -0,0 +1,8 @@ +fcn monty(n){ + inCircle:=0; + do(n){ + x:=(0.0).random(1); y:=(0.0).random(1); + if(x*x + y*y < 1.0) inCircle+=1; + } + 4.0*inCircle/n +} diff --git a/Task/Monte-Carlo-methods/Zkl/monte-carlo-methods-2.zkl b/Task/Monte-Carlo-methods/Zkl/monte-carlo-methods-2.zkl new file mode 100644 index 0000000000..4a65a1db51 --- /dev/null +++ b/Task/Monte-Carlo-methods/Zkl/monte-carlo-methods-2.zkl @@ -0,0 +1,7 @@ +fcn monty(n){ + 4.0 * (1).pump(n,Void,fcn(r){ + x:=(0.0).random(1); y:=(0.0).random(1); + if(x*x + y*y < 1.0) r.inc(); + r + }.fp(Ref(0)) ).value/n; +} diff --git a/Task/Monty-Hall-problem/BASIC/monty-hall-problem.basic b/Task/Monty-Hall-problem/BASIC/monty-hall-problem-1.basic similarity index 100% rename from Task/Monty-Hall-problem/BASIC/monty-hall-problem.basic rename to Task/Monty-Hall-problem/BASIC/monty-hall-problem-1.basic diff --git a/Task/Monty-Hall-problem/BASIC/monty-hall-problem-2.basic b/Task/Monty-Hall-problem/BASIC/monty-hall-problem-2.basic new file mode 100644 index 0000000000..4baee0e3c4 --- /dev/null +++ b/Task/Monty-Hall-problem/BASIC/monty-hall-problem-2.basic @@ -0,0 +1,15 @@ + 10 PRINT " WINS IF YOU" + 20 PRINT "STICK","SWITCH" + 30 LET STICK=0 + 40 LET SWITCH=0 + 50 FOR I=1 TO 1000 + 60 LET CAR=INT (RND*3) + 70 LET GUESS=INT (RND*3) + 80 LET SHOW=INT (RND*3) + 90 IF SHOW=GUESS OR SHOW=CAR THEN GOTO 80 +100 LET NEWGUESS=INT (RND*3) +110 IF NEWGUESS=GUESS OR NEWGUESS=SHOW THEN GOTO 100 +120 IF GUESS=CAR THEN LET STICK=STICK+1 +130 IF NEWGUESS=CAR THEN LET SWITCH=SWITCH+1 +140 PRINT AT 2,0;STICK,SWITCH +150 NEXT I diff --git a/Task/Monty-Hall-problem/Kotlin/monty-hall-problem.kotlin b/Task/Monty-Hall-problem/Kotlin/monty-hall-problem.kotlin new file mode 100644 index 0000000000..af43a77c12 --- /dev/null +++ b/Task/Monty-Hall-problem/Kotlin/monty-hall-problem.kotlin @@ -0,0 +1,28 @@ +// version 1.1.2 + +import java.util.Random + +fun montyHall(games: Int) { + var switchWins = 0 + var stayWins = 0 + val rnd = Random() + (1..games).forEach { + val doors = IntArray(3) // all zero (goats) by default + doors[rnd.nextInt(3)] = 1 // put car in a random door + val choice = rnd.nextInt(3) // choose a door at random + var shown: Int + do { + shown = rnd.nextInt(3) // the shown door + } + while (doors[shown] == 1 || shown == choice) + stayWins += doors[choice] + switchWins += doors[3 - choice - shown] + } + println("Simulating $games games:") + println("Staying wins $stayWins times") + println("Switching wins $switchWins times") +} + +fun main(args: Array) { + montyHall(1_000_000) +} diff --git a/Task/Monty-Hall-problem/Ring/monty-hall-problem.ring b/Task/Monty-Hall-problem/Ring/monty-hall-problem.ring new file mode 100644 index 0000000000..8ca261a20d --- /dev/null +++ b/Task/Monty-Hall-problem/Ring/monty-hall-problem.ring @@ -0,0 +1,22 @@ +total = 10000 +swapper = 0 +sticker = 0 +revealdoor = 0 +for trial = 1 to total + prizedoor = random(3) + 1 + guessdoor = random(3) + 1 + if prizedoor = guessdoor + revealdoor = random(2) + 1 + if prizedoor = 1 revealdoor += 1 ok + if (prizedoor = 2 and revealdoor = 2) revealdoor = 3 ok + else + revealdoor = (prizedoor ^ guessdoor) + ok + stickdoor = guessdoor + swapdoor = (guessdoor ^ revealdoor) + if stickdoor = prizedoor sticker += 1 ok + if swapdoor = prizedoor swapper += 1 ok +next +see "after a total of " + total + " trials," + nl +see "the 'sticker' won " + sticker + " times (" + floor(sticker/total*100) + "%)" + nl +see "the 'swapper' won " + swapper + " times (" + floor(swapper/total*100) + "%)" + nl diff --git a/Task/Monty-Hall-problem/Rust/monty-hall-problem.rust b/Task/Monty-Hall-problem/Rust/monty-hall-problem.rust new file mode 100644 index 0000000000..1a18a50556 --- /dev/null +++ b/Task/Monty-Hall-problem/Rust/monty-hall-problem.rust @@ -0,0 +1,26 @@ +extern crate rand; +use rand::Rng; + +#[derive(Clone, Copy, PartialEq)] +enum Prize {Goat , Car} + +const GAMES: usize = 3_000_000; +fn main() { + let mut switch_wins = 0; + let mut rng = rand::thread_rng(); + + for _ in 0..GAMES { + let mut doors = [Prize::Goat; 3]; + *rng.choose_mut(&mut doors).unwrap() = Prize::Car; + + // You only lose by switching if you pick the car the first time + if rng.choose(&doors).unwrap() != &Prize::Car { + switch_wins += 1; + } + } + println!("I played the game {total} times and won {wins} times ({percent}%).", + total = GAMES, + wins = switch_wins, + percent = switch_wins as f64 / GAMES as f64 * 100.0 + ); +} diff --git a/Task/Monty-Hall-problem/Sidef/monty-hall-problem.sidef b/Task/Monty-Hall-problem/Sidef/monty-hall-problem.sidef index e0047a5fae..3caec47ee7 100644 --- a/Task/Monty-Hall-problem/Sidef/monty-hall-problem.sidef +++ b/Task/Monty-Hall-problem/Sidef/monty-hall-problem.sidef @@ -1,21 +1,21 @@ -var n = 1000; # number of times to play -var switchWins = (var stayWins = 0); # sum of each strategy's wins - +var n = 1000 # number of times to play +var switchWins = (var stayWins = 0) # sum of each strategy's wins +  n.times { # play the game n times - var prize = 3.rand.int; - var chosen = 3.rand.int; - + var prize = pick(^3) + var chosen = pick(^3) +  var show; do { - show = 3.rand.int - } while (show ~~ [chosen, prize]); - + show = pick(^3) + } while (show ~~ [chosen, prize]) +  given(chosen) { when (prize) { stayWins += 1 } when ([3 - show - prize]) { switchWins += 1 } default { die "~ error ~" } - } + } } - -say ("Staying wins %.2f%% of the time." % (100.0 * stayWins / n)); -say ("Switching wins %.2f%% of the time." % (100.0 * switchWins / n)); +  +say ("Staying wins %.2f%% of the time." % (100.0 * stayWins / n)) +say ("Switching wins %.2f%% of the time." % (100.0 * switchWins / n)) diff --git a/Task/Monty-Hall-problem/Zkl/monty-hall-problem.zkl b/Task/Monty-Hall-problem/Zkl/monty-hall-problem.zkl new file mode 100644 index 0000000000..2df06a4e3d --- /dev/null +++ b/Task/Monty-Hall-problem/Zkl/monty-hall-problem.zkl @@ -0,0 +1,17 @@ +const games=0d100_000; + +reg switcherWins=0, keeperWins=0, shown=0; +do(games){ + doors := L(0,0,0); + doors[(0).random(3)] = 1; // Set which one has the car + choice := (0).random(3); // Choose a door + while(1){ shown = (0).random(3); + if (not (shown == choice or doors[shown] == 1)) break; } + switcherWins += doors[3 - choice - shown]; + keeperWins += doors[choice]; +} + +"Switcher Wins: %,d (%3.2f%%)".fmt( + switcherWins, switcherWins.toFloat() / games * 100).println(); +"Keeper Wins: %,d (%3.2f%%)".fmt( + keeperWins, keeperWins.toFloat() / games * 100).println(); diff --git a/Task/Morse-code/Gambas/morse-code.gambas b/Task/Morse-code/Gambas/morse-code.gambas new file mode 100644 index 0000000000..55ac0b2725 --- /dev/null +++ b/Task/Morse-code/Gambas/morse-code.gambas @@ -0,0 +1,52 @@ +'Requires component 'gb.sdl2.audio' + +Public Sub Main() +Dim sMessage As String = "Hello World" +Dim sFile As String = File.Load("../morse.txt") 'Contains A,.- B,-... etc +Dim sChar As New String[] +Dim sMorse As New String[] +Dim sOutPut As New String[] +Dim sTemp As String +Dim siCount, siLoop As Short +Dim bTrigger As Boolean +Dim fDelay As Float = 0.4 + +If Not Exist("/tmp/dot.ogg") Then Copy "../dot.ogg" To "/tmp/dot.ogg" 'Sounds downloaded from +If Not Exist("/tmp/dash.ogg") Then Copy "../dash.ogg" To "/tmp/dash.ogg" 'https://en.wikipedia.org/wiki/Morse_code#Letters.2C_numbers.2C_punctuation.2C_prosigns_for_Morse_code_and_non-English_variants + +For Each sTemp In Split(sFile, gb.NewLine) + sChar.add(Split(Trim(sTemp))[0]) + sMorse.add(Split(Trim(sTemp))[1]) +Next + +For siCount = 1 To Len(sMessage) + For siLoop = 0 To sChar.Max + If sChar[siLoop] = Mid(UCase(sMessage), siCount, 1) Then + sOutPut.Add(sMorse[siLoop]) + bTrigger = True + Break + End If + Next + If bTrigger = False Then sOutPut.Add(" ") + bTrigger = False +Next + +Print sOutPut.Join(" ") + +For siCount = 0 To Len(sMessage) - 1 + For siLoop = 0 To Len(sOutPut[siCount]) - 1 + If Mid(sOutPut[siCount], siLoop + 1, 1) = "." Then + Music.Load("/tmp/dot.ogg") + Music.Play + Wait fDelay + Else If Mid(sOutPut[siCount], siLoop + 1, 1) = "-" Then + Music.Load("/tmp/dash.ogg") + Music.Play + Wait fDelay + Else + Wait fDelay + Endif + Next +Next + +End diff --git a/Task/Morse-code/Kotlin/morse-code.kotlin b/Task/Morse-code/Kotlin/morse-code.kotlin index 0fd9de89ab..f2bff26ff6 100644 --- a/Task/Morse-code/Kotlin/morse-code.kotlin +++ b/Task/Morse-code/Kotlin/morse-code.kotlin @@ -1,48 +1,49 @@ import javax.sound.sampled.AudioFormat import javax.sound.sampled.AudioSystem -val morseCode = hashMapOf('a' to ".-", 'b' to "-...", 'c' to "-.-.", - 'd' to "-..", 'e' to ".", 'f' to "..-.", - 'g' to "--.", 'h' to "....", 'i' to "..", - 'j' to ".---", 'k' to "-.-", 'l' to ".-..", - 'm' to "--", 'n' to "-.", 'o' to "---", - 'p' to ".--.", 'q' to "--.-", 'r' to ".-.", - 's' to "...", 't' to "-", 'u' to "..-", - 'v' to "...-", 'w' to ".--", 'x' to "-..-", - 'y' to "-.--", 'z' to "--..", +val morseCode = hashMapOf( + 'a' to ".-", 'b' to "-...", 'c' to "-.-.", + 'd' to "-..", 'e' to ".", 'f' to "..-.", + 'g' to "--.", 'h' to "....", 'i' to "..", + 'j' to ".---", 'k' to "-.-", 'l' to ".-..", + 'm' to "--", 'n' to "-.", 'o' to "---", + 'p' to ".--.", 'q' to "--.-", 'r' to ".-.", + 's' to "...", 't' to "-", 'u' to "..-", + 'v' to "...-", 'w' to ".--", 'x' to "-..-", + 'y' to "-.--", 'z' to "--..", - '0' to ".....", '1' to "-....", '2' to "--...", - '3' to "---..", '4' to "----.", '5' to "-----", - '6' to ".----", '7' to "..---", '8' to "...--", - '9' to "....-", + '0' to ".....", '1' to "-....", '2' to "--...", + '3' to "---..", '4' to "----.", '5' to "-----", + '6' to ".----", '7' to "..---", '8' to "...--", + '9' to "....-", - ' ' to "/", ',' to "--..--", '!' to "-.-.--", - '"' to ".-..-.", '.' to ".-.-.-", '?' to "..--..", - '\'' to ".----.", '/' to "-..-.", '-' to "-....-", - '(' to "-.--.-", ')' to "-.--.-") + ' ' to "/", ',' to "--..--", '!' to "-.-.--", + '"' to ".-..-.", '.' to ".-.-.-", '?' to "..--..", + '\'' to ".----.", '/' to "-..-.", '-' to "-....-", + '(' to "-.--.-", ')' to "-.--.-" +) val symbolDurationInMs = hashMapOf('.' to 200, '-' to 500, '/' to 1000) -fun main(args: Array) { - args.forEach { playMorseCode(toMorseCode(it.toLowerCase())) } -} fun toMorseCode(message: String) = message.filter { morseCode.containsKey(it) } - .fold("") { (acc, ch) -> acc + morseCode[ch]!! } + .fold("") { acc, ch -> acc + morseCode[ch]!! } fun playMorseCode(morseCode: String) = morseCode.forEach { symbol -> beep(symbolDurationInMs[symbol]!!) } fun beep(durationInMs: Int) { val soundBuffer = ByteArray(durationInMs * 8) - for ((i, elem) in soundBuffer.withIndices()) { + for ((i, _) in soundBuffer.withIndex()) { soundBuffer[i] = (Math.sin(i / 8.0 * 2.0 * Math.PI) * 80.0).toByte() } - val audioFormat = AudioFormat(/*sampleRate*/ 8000F, - /*sampleSizeInBits*/ 8, - /*channels*/ 1, - /*signed*/ true, - /*bigEndian*/ false) + val audioFormat = AudioFormat( + /*sampleRate*/ 8000F, + /*sampleSizeInBits*/ 8, + /*channels*/ 1, + /*signed*/ true, + /*bigEndian*/ false + ) with (AudioSystem.getSourceDataLine(audioFormat)!!) { open(audioFormat) @@ -53,3 +54,9 @@ fun beep(durationInMs: Int) { close() } } + +fun main(args: Array) { + args.forEach { + playMorseCode(toMorseCode(it.toLowerCase())) + } +} diff --git a/Task/Morse-code/Ol/morse-code.ol b/Task/Morse-code/Ol/morse-code.ol new file mode 100644 index 0000000000..e4c47db427 --- /dev/null +++ b/Task/Morse-code/Ol/morse-code.ol @@ -0,0 +1,25 @@ +(display "Please, enter the string in lower case bounded by \" sign: ") +(lfor + (list->ff '( + (#\a . ".-" ) (#\b . "-..." ) (#\c . "-.-." ) + (#\d . "-.." ) (#\e . "." ) (#\f . "..-." ) + (#\g . "--." ) (#\h . "...." ) (#\i . ".." ) + (#\j . ".---" ) (#\k . "-.-" ) (#\l . ".-.." ) + (#\m . "--" ) (#\n . "-." ) (#\o . "---" ) + (#\p . ".--." ) (#\q . "--.-" ) (#\r . ".-." ) + (#\s . "..." ) (#\t . "-" ) (#\u . "..-" ) + (#\v . "...-" ) (#\w . ".--" ) (#\x . "-..-" ) + (#\y . "-.--" ) (#\z . "--.." ) (#\1 . ".----") + (#\2 . "..---") (#\3 . "...--") (#\4 . "....-") + (#\5 . ".....") (#\6 . "-....") (#\7 . "--...") + (#\8 . "---..") (#\9 . "----.") (#\0 . "-----") + (#\space . " ") (#\. . " "))) + (str-iter (read)) + (lambda (codes char) + (let ((out (getf codes char))) + (if out (display out))) + codes)) + +; ==> Please, enter the string in lower case bounded by " sign: +; <== "hello world" +; ==> ......-...-..--- .-----.-..-..-.. diff --git a/Task/Morse-code/PowerShell/morse-code-2.psh b/Task/Morse-code/PowerShell/morse-code-2.psh index 84f7a3655e..64dafdabce 100644 --- a/Task/Morse-code/PowerShell/morse-code-2.psh +++ b/Task/Morse-code/PowerShell/morse-code-2.psh @@ -1 +1 @@ -Send-MorseCode -Message "S.O.S" +Send-MorseCode -Message "S.O.S" -ShowCode diff --git a/Task/Morse-code/Sed/morse-code-1.sed b/Task/Morse-code/Sed/morse-code-1.sed new file mode 100644 index 0000000000..d17bfee668 --- /dev/null +++ b/Task/Morse-code/Sed/morse-code-1.sed @@ -0,0 +1,11 @@ +#!/bin/sed -rf +# Convert to uppercase +s/.*/\U&/ +# Add lookup table +s/$/\nA.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--../ +# Main loop +:a +s/([A-Z])([^\n]*\n.*\1([-.]+))/\3 \2/ +ta +# Remove lookup table +s/\n.*// diff --git a/Task/Morse-code/Sed/morse-code-2.sed b/Task/Morse-code/Sed/morse-code-2.sed new file mode 100644 index 0000000000..f7d4d20b96 --- /dev/null +++ b/Task/Morse-code/Sed/morse-code-2.sed @@ -0,0 +1,2 @@ +$ echo hello world! | ./morse.sed +.... . .-.. .-.. --- .-- --- .-. .-.. -.. ! diff --git a/Task/Mouse-position/Kotlin/mouse-position.kotlin b/Task/Mouse-position/Kotlin/mouse-position.kotlin new file mode 100644 index 0000000000..74aec1a47e --- /dev/null +++ b/Task/Mouse-position/Kotlin/mouse-position.kotlin @@ -0,0 +1,11 @@ +// version 1.1.2 + +import java.awt.MouseInfo + +fun main(args: Array) { + (1..5).forEach { + Thread.sleep(1000) + val p = MouseInfo.getPointerInfo().location // gets screen coordinates + println("${it}: x = ${"%-4d".format(p.x)} y = ${"%-4d".format(p.y)}") + } +} diff --git a/Task/Mouse-position/Phix/mouse-position.phix b/Task/Mouse-position/Phix/mouse-position.phix new file mode 100644 index 0000000000..ebbdbdb58a --- /dev/null +++ b/Task/Mouse-position/Phix/mouse-position.phix @@ -0,0 +1,66 @@ +-- +-- demo\rosetta\Mouse_position.exw +-- +include pGUI.e + +Ihandle global_lbl, canvas_lbl, timer_lbl + +function globalmotion_cb(integer x, integer y, atom /*pStatus*/) + IupSetStrAttribute(global_lbl,"TITLE","globalmotion_cb %d, %d",{x,y}) + return IUP_DEFAULT +end function + +function canvas_motion_cb(Ihandle /*canvas*/, integer x, integer y, atom pStatus) + IupSetStrAttribute(canvas_lbl,"TITLE","canvasmotion_cb %d, %d",{x,y}) + return IUP_DEFAULT; +end function + +function OnTimer(Ihandle /*ih*/) + integer {x,y} = IupGetIntInt(NULL,"CURSORPOS") + IupSetStrAttribute(timer_lbl,"TITLE","timer %d, %d",{x,y}) + return IUP_IGNORE +end function + +function esc_close(Ihandle /*ih*/, atom c) + return iff(c=K_ESC?IUP_CLOSE:IUP_CONTINUE) +end function + +procedure main() +Ihandle separator1, separator2, + canvas, frame_1, frame_2, + dialog + + IupOpen() + + global_lbl = IupLabel("Move the mouse anywhere on the window","EXPAND=HORIZONTAL") + separator1 = IupLabel(NULL,"SEPARATOR=HORIZONTAL") + canvas_lbl = IupLabel("Move the mouse anywhere on the canvas","EXPAND=HORIZONTAL") + separator2 = IupLabel(NULL,"SEPARATOR=HORIZONTAL") + timer_lbl = IupLabel("This one runs on a three second timer","EXPAND=HORIZONTAL") + + frame_1 = IupFrame(IupVbox({global_lbl, + separator1, + canvas_lbl, + separator2, + timer_lbl}), + "TITLE=IupLabel, SIZE=200x") + + canvas = IupCanvas("MOTION_CB", Icallback("canvas_motion_cb"), + "EXPAND=HORIZONTAL, RASTERSIZE=200x200") + frame_2 = IupFrame(canvas, "TITLE=IupCanvas") + + dialog = IupDialog(IupHbox({frame_1,frame_2}, "MARGIN=5x5, GAP=5")) + IupSetAttribute(dialog,"TITLE","Mouse motion"); + IupSetCallback(dialog, "K_ANY", Icallback("esc_close")); + + IupSetGlobal("INPUTCALLBACKS", "Yes"); + IupSetGlobalFunction("GLOBALMOTION_CB", Icallback("globalmotion_cb")); + + Ihandle hTimer = IupTimer(Icallback("OnTimer"), 3000) + + IupShow(dialog) + + IupMainLoop() + IupClose() +end procedure +main() diff --git a/Task/Move-to-front-algorithm/Clojure/move-to-front-algorithm.clj b/Task/Move-to-front-algorithm/Clojure/move-to-front-algorithm.clj new file mode 100644 index 0000000000..db8360b5b7 --- /dev/null +++ b/Task/Move-to-front-algorithm/Clojure/move-to-front-algorithm.clj @@ -0,0 +1,21 @@ +(def lowercase (map char (range (int \a) (inc (int \z))))) + +(defn move-to-front [x xs] + (cons x (remove #{x} xs))) + +(defn encode [text table & {:keys [acc] :or {acc []}}] + (let [c (first text) + idx (.indexOf table c)] + (if (empty? text) acc (recur (drop 1 text) (move-to-front c table) {:acc (conj acc idx)})))) + +(defn decode [indices table & {:keys [acc] :or {acc []}}] + (if (empty? indices) (apply str acc) + (let [n (first indices) + c (nth table n)] + (recur (drop 1 indices) (move-to-front c table) {:acc (conj acc c)})))) + +(doseq [word ["broood" "bananaaa" "hiphophiphop"]] + (let [encoded (encode word lowercase) + decoded (decode encoded lowercase)] + (println (format "%s encodes to %s which decodes back to %s." + word encoded decoded)))) diff --git a/Task/Move-to-front-algorithm/Gambas/move-to-front-algorithm.gambas b/Task/Move-to-front-algorithm/Gambas/move-to-front-algorithm.gambas new file mode 100644 index 0000000000..2f2598ccbc --- /dev/null +++ b/Task/Move-to-front-algorithm/Gambas/move-to-front-algorithm.gambas @@ -0,0 +1,33 @@ +Public Sub Main() +Dim sToCode As String[] = ["broood", "bananaaa", "hiphophiphop"] 'Samples to process +Dim sHold As New String[] 'To store results +Dim siCount, siCounter, siPos As Short 'Various variables +Dim sOutput, sCode, sWork, sEach As String 'Various variables + +For siCounter = 0 To sToCode.Max 'To loop through each 'Sample' + sCode = "abcdefghijklmnopqrstuvwxyz" 'Set sCode to default setting + For siCount = 1 To Len(sToCode[siCounter]) 'Loop through each letter in 'Sample' + sWork = Mid(sToCode[siCounter], siCount, 1) 'sWork to store the Letter + siPos = InStr(scode, sWork) - 1 'Find the position of the letter in sCode, -1 for '0' based array + sOutput &= Str(siPos) & " " 'Add the postion to sOutput + sCode = Mid(sCode, siPos + 1, 1) & Replace(sCode, sWork, "") 'sCode = the letter + the rest of sCode except the letter + Next + Print sToCode[siCounter] & " = " & sOutput 'Print the 'Sample' and the coded version + sHold.Add(Trim(sOutput)) 'Add the code to the sHold array + sOutput = "" 'Clear sOutput +Next + +Print 'Print a blank line + +For siCounter = 0 To sHold.Max 'To loop through each coded 'Sample' + sCode = "abcdefghijklmnopqrstuvwxyz" 'Set sCode to default setting + For Each sEach In Split(sHold[siCounter], " ") 'For each 'code' in coded 'Sample' + sWork = Mid(sCode, Val(sEach) + 1, 1) 'sWork = the decoded letter + sOutput &= sWork 'Add the decoded letter to sOutput + sCode = sWork & Replace(sCode, sWork, "") 'sCode = the decoded letter + the rest of sCode except the letter + Next + Print sHold[siCounter] & " = " & sOutput 'Print the coded and decoded result + sOutput = "" 'Clear sOutput +Next + +End diff --git a/Task/Move-to-front-algorithm/Haskell/move-to-front-algorithm.hs b/Task/Move-to-front-algorithm/Haskell/move-to-front-algorithm.hs index 01726c7889..fd234ba7bb 100644 --- a/Task/Move-to-front-algorithm/Haskell/move-to-front-algorithm.hs +++ b/Task/Move-to-front-algorithm/Haskell/move-to-front-algorithm.hs @@ -1,19 +1,25 @@ -import qualified Data.List as L -import qualified Data.Maybe as M +import Data.List (delete, elemIndex, mapAccumL) + +import Data.Maybe (fromJust) table :: String -table = ['a'..'z'] +table = ['a' .. 'z'] encode :: String -> [Int] -encode = snd . L.mapAccumL f table - where - f t s = ((s : L.delete s t), M.fromJust (L.elemIndex s t)) +encode = + let f t s = (s : delete s t, fromJust (elemIndex s t)) + in snd . mapAccumL f table decode :: [Int] -> String -decode = snd . L.mapAccumL f table +decode = snd . mapAccumL f table where - f t i = let s = (t !! i) in ((s : L.delete s t), s) + f t i = + let s = (t !! i) + in (s : delete s t, s) main :: IO () -main = mapM_ (\s -> let t@(e, _) = (encode s, decode e) in print t) - ["broood", "bananaaa", "hiphophiphop"] +main = + mapM_ print $ + (,) <*> uncurry ((==) . fst) <$> -- Test that ((fst . fst) x) == snd x) + ((,) <*> (decode . snd) <$> + ((,) <*> encode <$> ["broood", "bananaaa", "hiphophiphop"])) diff --git a/Task/Move-to-front-algorithm/jq/move-to-front-algorithm-1.jq b/Task/Move-to-front-algorithm/Jq/move-to-front-algorithm-1.jq similarity index 100% rename from Task/Move-to-front-algorithm/jq/move-to-front-algorithm-1.jq rename to Task/Move-to-front-algorithm/Jq/move-to-front-algorithm-1.jq diff --git a/Task/Move-to-front-algorithm/jq/move-to-front-algorithm-2.jq b/Task/Move-to-front-algorithm/Jq/move-to-front-algorithm-2.jq similarity index 100% rename from Task/Move-to-front-algorithm/jq/move-to-front-algorithm-2.jq rename to Task/Move-to-front-algorithm/Jq/move-to-front-algorithm-2.jq diff --git a/Task/Move-to-front-algorithm/jq/move-to-front-algorithm-3.jq b/Task/Move-to-front-algorithm/Jq/move-to-front-algorithm-3.jq similarity index 100% rename from Task/Move-to-front-algorithm/jq/move-to-front-algorithm-3.jq rename to Task/Move-to-front-algorithm/Jq/move-to-front-algorithm-3.jq diff --git a/Task/Move-to-front-algorithm/Kotlin/move-to-front-algorithm.kotlin b/Task/Move-to-front-algorithm/Kotlin/move-to-front-algorithm.kotlin new file mode 100644 index 0000000000..5a26ad050a --- /dev/null +++ b/Task/Move-to-front-algorithm/Kotlin/move-to-front-algorithm.kotlin @@ -0,0 +1,48 @@ +// version 1.1.2 + +fun encode(s: String): IntArray { + if (s.isEmpty()) return intArrayOf() + val symbols = "abcdefghijklmnopqrstuvwxyz".toCharArray() + val result = IntArray(s.length) + for ((i, c) in s.withIndex()) { + val index = symbols.indexOf(c) + if (index == -1) + throw IllegalArgumentException("$s contains a non-alphabetic character") + result[i] = index + if (index == 0) continue + for (j in index - 1 downTo 0) symbols[j + 1] = symbols[j] + symbols[0] = c + } + return result +} + +fun decode(a: IntArray): String { + if (a.isEmpty()) return "" + val symbols = "abcdefghijklmnopqrstuvwxyz".toCharArray() + val result = CharArray(a.size) + for ((i, n) in a.withIndex()) { + if (n !in 0..25) + throw IllegalArgumentException("${a.contentToString()} contains an invalid number") + result[i] = symbols[n] + if (n == 0) continue + for (j in n - 1 downTo 0) symbols[j + 1] = symbols[j] + symbols[0] = result[i] + } + return result.joinToString("") +} + +fun main(args: Array) { + val strings = arrayOf("broood", "bananaaa", "hiphophiphop") + val encoded = Array(strings.size) { null } + for ((i, s) in strings.withIndex()) { + encoded[i] = encode(s) + println("${s.padEnd(12)} -> ${encoded[i]!!.contentToString()}") + } + println() + val decoded = Array(encoded.size) { null } + for ((i, a) in encoded.withIndex()) { + decoded[i] = decode(a!!) + print("${a.contentToString().padEnd(38)} -> ${decoded[i]!!.padEnd(12)}") + println(" -> ${if (decoded[i] == strings[i]) "correct" else "incorrect"}") + } +} diff --git a/Task/Move-to-front-algorithm/Phix/move-to-front-algorithm.phix b/Task/Move-to-front-algorithm/Phix/move-to-front-algorithm.phix new file mode 100644 index 0000000000..9462110d60 --- /dev/null +++ b/Task/Move-to-front-algorithm/Phix/move-to-front-algorithm.phix @@ -0,0 +1,38 @@ +function encode(string s) + string symtab = "abcdefghijklmnopqrstuvwxyz" + sequence res = {} + for i=1 to length(s) do + integer ch = s[i] + integer k = find(ch,symtab) + res &= k-1 + for j=k to 2 by -1 do + symtab[j] = symtab[j-1] + end for + symtab[1] = ch + end for + return res +end function + +function decode(sequence s) + string symtab = "abcdefghijklmnopqrstuvwxyz" + string res = "" + for i=1 to length(s) do + integer k = s[i]+1 + integer ch = symtab[k] + res &= ch + for j=k to 2 by -1 do + symtab[j] = symtab[j-1] + end for + symtab[1] = ch + end for + return res +end function + +procedure test(string s) + sequence e = encode(s) + string d = decode(e) + ?{s,e,d,{"**ERROR**","ok"}[(s=d)+1]} +end procedure +test("broood") +test("bananaaa") +test("hiphophiphop") diff --git a/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx b/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx index 5f9182cfab..fe60f1375d 100644 --- a/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx +++ b/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx @@ -1,18 +1,17 @@ /*REXX program demonstrates the move─to─front algorithm encode/decode symbol table. */ parse arg xxx; if xxx='' then xxx= 'broood bananaaa hiphophiphop' /*use the default?*/ one=1 /*(offset) for this task's requirement.*/ - do j=1 for words(xxx); x=word(xxx, j) /*process a single word at a time. */ - @= 'abcdefghijklmnopqrstuvwxyz'; @@=@ /*symbol table: the lowercase alphabet */ + do j=1 for words(xxx); x=word(xxx, j) /*process a single word at a time. */ + @= 'abcdefghijklmnopqrstuvwxyz'; @@=@ /*symbol table: the lowercase alphabet */ $= /*set the decode string to a null. */ - do k=1 for length(x); z=substr(x, k, 1) /*encrypt a symbol in the word. */ - _=pos(z, @); if _==0 then iterate /*the symbol position in symbol table. */ - $=$ _ - one; @=z || delstr(@, _, 1) /*adjust the symbol table string. */ - end /*k*/ /* [↑] the move─to─front encoding. */ + do k=1 for length(x); z=substr(x, k, 1) /*encrypt a symbol in the word. */ + _=pos(z, @); if _==0 then iterate /*the symbol position in symbol table. */ + $=$ _ - one; @=z || delstr(@, _, 1) /*(re-)adjust the symbol table string. */ + end /*k*/ /* [↑] the move─to─front encoding. */ != /*set the encode string to a null. */ - do m=1 for words($); n=word($, m) +one /*decode the sequence table string. */ - y=substr(@@, n, 1); !=! || y /*the decode symbol for the word. */ - @@=y || delstr(@@, n, 1) /*rebuild the symbol table string. */ - end /*m*/ /* [↑] the move─to─front decoding. */ - + do m=1 for words($); n=word($, m) +one /*decode the sequence table string. */ + y=substr(@@, n, 1); !=! || y /*the decode symbol for the N word.*/ + @@=y || delstr(@@, n, 1) /*rebuild the symbol table string. */ + end /*m*/ /* [↑] the move─to─front decoding. */ say ' word: ' left(x, 20) "encoding:" left($, 35) word('wrong OK', 1+(!==x) ) - end /*j*/ /*stick a fork in it, we're all done. */ + end /*j*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Move-to-front-algorithm/Swift/move-to-front-algorithm.swift b/Task/Move-to-front-algorithm/Swift/move-to-front-algorithm.swift new file mode 100644 index 0000000000..1ff1b86542 --- /dev/null +++ b/Task/Move-to-front-algorithm/Swift/move-to-front-algorithm.swift @@ -0,0 +1,69 @@ +var str="broood" +var number:[Int]=[1,17,15,0,0,5] + +//function to encode the string +func encode(st:String)->[Int] +{ + +var array:[Character]=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] + + var num:[Int]=[] + var temp:Character="a" + var i1:Int=0 + for i in st.characters + { + for j in 0...25 + { + if i==array[j] + { + num.append(j) + temp=array[j] + i1=j + while(i1>0) + { + array[i1]=array[i1-1] + i1=i1-1 + + } + array[0]=temp + } + + } + + + } + + return num + +} + +func decode(s:[Int])->[Character] +{ + + var st1:[Character]=[] + var alph:[Character]=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] + var temp1:Character="a" + var i2:Int=0 + for i in 0...s.character.count-1 + { + i2=s[i] + st1.append(alph[i2]) + temp1=alph[i2] + + while(i2>0) + { + alph[i2]=alph[i2-1] + i2=i2-1 + + } + alph[0]=temp1 + + } + return st1 + +} + +var encarr:[Int]=encode(st:str) +var decarr:[Character]=decode(s:number) +print(encarr) +print(decarr) diff --git a/Task/Move-to-front-algorithm/Zkl/move-to-front-algorithm-1.zkl b/Task/Move-to-front-algorithm/Zkl/move-to-front-algorithm-1.zkl new file mode 100644 index 0000000000..abb749db4d --- /dev/null +++ b/Task/Move-to-front-algorithm/Zkl/move-to-front-algorithm-1.zkl @@ -0,0 +1,6 @@ +fcn encode(text){ //-->List + st:=["a".."z"].pump(Data); //"abcd..z" as byte array + text.reduce(fcn(st,c,sink){ + n:=st.index(c); sink.write(n); st.del(n).insert(0,c); },st,sink:=L()); + sink; +} diff --git a/Task/Move-to-front-algorithm/Zkl/move-to-front-algorithm-2.zkl b/Task/Move-to-front-algorithm/Zkl/move-to-front-algorithm-2.zkl new file mode 100644 index 0000000000..73f6d49111 --- /dev/null +++ b/Task/Move-to-front-algorithm/Zkl/move-to-front-algorithm-2.zkl @@ -0,0 +1,6 @@ +fcn decode(list){ //-->String + st:=["a".."z"].pump(String); //"abcd..z" + sink:=Sink(String); + list.reduce('wrap(st,n){ c:=st[n]; sink.write(c); c+st.del(n); },st); + sink.close(); +} diff --git a/Task/Move-to-front-algorithm/Zkl/move-to-front-algorithm-3.zkl b/Task/Move-to-front-algorithm/Zkl/move-to-front-algorithm-3.zkl new file mode 100644 index 0000000000..27c253aaab --- /dev/null +++ b/Task/Move-to-front-algorithm/Zkl/move-to-front-algorithm-3.zkl @@ -0,0 +1,6 @@ +texts:=T("broood","bananaaa","hiphophiphop"); +out:=texts.apply(encode); +texts.zipWith(fcn(t,e){ println(t,"-->",e) },out); + +out.apply(decode).println(); +texts.zipWith('==,out.apply(decode)).println(); diff --git a/Task/Multifactorial/ALGOL-W/multifactorial.alg b/Task/Multifactorial/ALGOL-W/multifactorial.alg new file mode 100644 index 0000000000..0e2c977c1e --- /dev/null +++ b/Task/Multifactorial/ALGOL-W/multifactorial.alg @@ -0,0 +1,22 @@ +begin + % returns the multifactorial of n with the specified degree % + integer procedure multifactorial ( integer value n, degree ) ; + begin + integer mf, v; + mf := v := n; + while begin + v := v - degree; + v > 1 + end do mf := mf * v; + mf + end multifactorial ; + + % tests as per task % + for degree := 1 until 5 do begin + i_w := 1; s_w := 0; % output formatting % + write( "Degree: ", degree, ":" ); + for v := 1 until 10 do begin + writeon( " ", multifactorial( v, degree ) ) + end for_v + end for_degree +end. diff --git a/Task/Multifactorial/Dart/multifactorial.dart b/Task/Multifactorial/Dart/multifactorial.dart new file mode 100644 index 0000000000..cd061c4dc4 --- /dev/null +++ b/Task/Multifactorial/Dart/multifactorial.dart @@ -0,0 +1,25 @@ +main() +{ + int n=5,d=3; +int z= fact(n,d); +print('$n factorial of degree $d is $z'); +for(var j=1;j<=5;j++) +{ + print('first 10 numbers of degree $j :'); + for(var i=1;i<=10;i++) + { + int z=fact(i,j); + print('$z'); +} + print('\n'); +} +} + +int fact(int a,int b) +{ + + if(a<=b||a==0) + return a; + if(a>1) + return a*fact((a-b),b); +} diff --git a/Task/Multifactorial/JavaScript/multifactorial-4.js b/Task/Multifactorial/JavaScript/multifactorial-4.js index dd640c8630..107a650405 100644 --- a/Task/Multifactorial/JavaScript/multifactorial-4.js +++ b/Task/Multifactorial/JavaScript/multifactorial-4.js @@ -1,3 +1,3 @@ function multifact(n, deg){ - return n <= deg ? n : n * multifact(n - deg, deg); + return n <= deg ? n : n * multifact(n - deg, deg); } diff --git a/Task/Multifactorial/JavaScript/multifactorial-5.js b/Task/Multifactorial/JavaScript/multifactorial-5.js index 801ebc14fd..915757b045 100644 --- a/Task/Multifactorial/JavaScript/multifactorial-5.js +++ b/Task/Multifactorial/JavaScript/multifactorial-5.js @@ -1,9 +1,9 @@ function test (n, deg) { - for (var i = 1; i <= deg; i ++) { - var results = ''; - for (var j = 1; j <= n; j ++) { - results += multifact(j, i) + ' '; - } - console.log('Degree ' + i + ': ' + results); - } + for (var i = 1; i <= deg; i ++) { + var results = ''; + for (var j = 1; j <= n; j ++) { + results += multifact(j, i) + ' '; + } + console.log('Degree ' + i + ': ' + results); + } } diff --git a/Task/Multifactorial/jq/multifactorial-1.jq b/Task/Multifactorial/Jq/multifactorial-1.jq similarity index 100% rename from Task/Multifactorial/jq/multifactorial-1.jq rename to Task/Multifactorial/Jq/multifactorial-1.jq diff --git a/Task/Multifactorial/jq/multifactorial-2.jq b/Task/Multifactorial/Jq/multifactorial-2.jq similarity index 100% rename from Task/Multifactorial/jq/multifactorial-2.jq rename to Task/Multifactorial/Jq/multifactorial-2.jq diff --git a/Task/Multifactorial/jq/multifactorial-3.jq b/Task/Multifactorial/Jq/multifactorial-3.jq similarity index 100% rename from Task/Multifactorial/jq/multifactorial-3.jq rename to Task/Multifactorial/Jq/multifactorial-3.jq diff --git a/Task/Multifactorial/jq/multifactorial-4.jq b/Task/Multifactorial/Jq/multifactorial-4.jq similarity index 100% rename from Task/Multifactorial/jq/multifactorial-4.jq rename to Task/Multifactorial/Jq/multifactorial-4.jq diff --git a/Task/Multifactorial/Phix/multifactorial.phix b/Task/Multifactorial/Phix/multifactorial.phix new file mode 100644 index 0000000000..1a5d45626b --- /dev/null +++ b/Task/Multifactorial/Phix/multifactorial.phix @@ -0,0 +1,15 @@ +function multifactorial(integer n, integer order) +atom res = 1 + if n>0 then + res = n*multifactorial(n-order,order) + end if + 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 + ?s +end for diff --git a/Task/Multifactorial/PlainTeX/multifactorial.tex b/Task/Multifactorial/PlainTeX/multifactorial.tex new file mode 100644 index 0000000000..6ca1c74d2f --- /dev/null +++ b/Task/Multifactorial/PlainTeX/multifactorial.tex @@ -0,0 +1,14 @@ +\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 +} +\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} +\newcount\result +\def\multifact#1#2{% + \result=1 + \fornum\multifactiter=#1 to 1(-#2){\multiply\result\multifactiter}% + \number\result +} +\fornum\degree=1 to 5(+1){Degree \degree: \fornum\ii=1 to 10(+1){\multifact\ii\degree\space\space}\par} +\bye diff --git a/Task/Multifactorial/Scheme/multifactorial.ss b/Task/Multifactorial/Scheme/multifactorial.ss new file mode 100644 index 0000000000..81c4ecc2e8 --- /dev/null +++ b/Task/Multifactorial/Scheme/multifactorial.ss @@ -0,0 +1,19 @@ +(import (scheme base) + (scheme write) + (srfi 1)) + +(define (multi-factorial n m) + (fold * 1 (iota (ceiling (/ n m)) n (- m)))) + +(for-each + (lambda (degree) + (display (string-append "degree " + (number->string degree) + ": ")) + (for-each + (lambda (num) + (display (string-append (number->string (multi-factorial num degree)) + " "))) + (iota 10 1)) + (newline)) + (iota 5 1)) diff --git a/Task/Multifactorial/Sidef/multifactorial.sidef b/Task/Multifactorial/Sidef/multifactorial.sidef index 9f6eb256ee..c36e4a9b40 100644 --- a/Task/Multifactorial/Sidef/multifactorial.sidef +++ b/Task/Multifactorial/Sidef/multifactorial.sidef @@ -1,7 +1,7 @@ func mfact(s, n) { n > 0 ? (n * mfact(s, n-s)) : 1 } -  -10.times { |s| - say "step=#{s}: #{1..10 -> map {|n| mfact(s, n)}.join(' ')}" -} + +{ |s| + say "step=#{s}: #{{|n| mfact(s, n)}.map(1..10).join(' ')}" +} << 1..10 diff --git a/Task/Multifactorial/Zkl/multifactorial.zkl b/Task/Multifactorial/Zkl/multifactorial.zkl new file mode 100644 index 0000000000..a2855dfd81 --- /dev/null +++ b/Task/Multifactorial/Zkl/multifactorial.zkl @@ -0,0 +1,2 @@ +fcn mfact(n,m){ [n..1,-m].reduce('*,1) } +foreach m in ([1..5]){ println("%d: %s".fmt(m,[1..10].apply(mfact.fp1(m)))) } diff --git a/Task/Multiple-distinct-objects/00META.yaml b/Task/Multiple-distinct-objects/00META.yaml deleted file mode 100644 index 43afe9a8b6..0000000000 --- a/Task/Multiple-distinct-objects/00META.yaml +++ /dev/null @@ -1,2 +0,0 @@ ---- -note: Object oriented diff --git a/Task/Multiple-distinct-objects/Aime/multiple-distinct-objects.aime b/Task/Multiple-distinct-objects/Aime/multiple-distinct-objects.aime index dcfc82748c..ffdfeeffca 100644 --- a/Task/Multiple-distinct-objects/Aime/multiple-distinct-objects.aime +++ b/Task/Multiple-distinct-objects/Aime/multiple-distinct-objects.aime @@ -1,15 +1,11 @@ void show_sublist(list l) { - integer i; + integer i, v; - i = 0; - while (i < l_length(l)) { - if (i) { - o_space(1); - } - o_integer(l_q_integer(l, i)); - i += 1; + for (i, v in l) { + o_space(sign(i)); + o_integer(v); } } @@ -17,13 +13,12 @@ void show_list(list l) { integer i; + list v; - i = 0; - while (i < l_length(l)) { + for (i, v in l) { o_text(" ["); - show_sublist(l_q_list(l, i)); + show_sublist(v); o_text("]"); - i += 1; } o_byte('\n'); @@ -34,10 +29,7 @@ multiple_distinct(integer n, object o) { list l; - while (n) { - l_append(l, o); - n -= 1; - } + call_n(n, l_append, l, o); return l; } @@ -57,7 +49,7 @@ main(void) l = multiple_distinct(8, z); # modify one of the sublists - l_r_integer(l_q_list(l, 3), 0, 7); + l_q_list(l, 3)[0] = 7; # display the list of lists show_list(l); diff --git a/Task/Multiple-distinct-objects/jq/multiple-distinct-objects.jq b/Task/Multiple-distinct-objects/Jq/multiple-distinct-objects.jq similarity index 100% rename from Task/Multiple-distinct-objects/jq/multiple-distinct-objects.jq rename to Task/Multiple-distinct-objects/Jq/multiple-distinct-objects.jq diff --git a/Task/Multiple-distinct-objects/Kotlin/multiple-distinct-objects.kotlin b/Task/Multiple-distinct-objects/Kotlin/multiple-distinct-objects.kotlin new file mode 100644 index 0000000000..f1c9a17ed4 --- /dev/null +++ b/Task/Multiple-distinct-objects/Kotlin/multiple-distinct-objects.kotlin @@ -0,0 +1,26 @@ +// version 1.1.2 + +class Foo { + val id: Int + + init { + id = ++numCreated // creates a distict id for each object + } + + companion object { + private var numCreated = 0 + } +} + +fun main(args: Array) { + val n = 3 // say + + /* correct approach - creates references to distinct objects */ + val fooList = List(n) { Foo() } + for (foo in fooList) println(foo.id) + + /* incorrect approach - creates references to same object */ + val f = Foo() + val fooList2 = List(n) { f } + for (foo in fooList2) println(foo.id) +} diff --git a/Task/Multiple-distinct-objects/OoRexx/multiple-distinct-objects.rexx b/Task/Multiple-distinct-objects/OoRexx/multiple-distinct-objects.rexx new file mode 100644 index 0000000000..c5582cd958 --- /dev/null +++ b/Task/Multiple-distinct-objects/OoRexx/multiple-distinct-objects.rexx @@ -0,0 +1,19 @@ +-- get an array of directory objects +array = fillArrayWith(3, .directory) +say "each object will have a different identityHash" +say +loop d over array + say d~identityHash +end + +::routine fillArrayWith + use arg size, class + + array = .array~new(size) + loop i = 1 to size + -- Note, this assumes this object class can be created with + -- no arguments + array[i] = class~new + end + +return array diff --git a/Task/Multiple-distinct-objects/Perl-6/multiple-distinct-objects-1.pl6 b/Task/Multiple-distinct-objects/Perl-6/multiple-distinct-objects-1.pl6 deleted file mode 100644 index 310ce42955..0000000000 --- a/Task/Multiple-distinct-objects/Perl-6/multiple-distinct-objects-1.pl6 +++ /dev/null @@ -1,2 +0,0 @@ -# WRONG -my @a = Foo.new xx $n; diff --git a/Task/Multiple-distinct-objects/Perl-6/multiple-distinct-objects-2.pl6 b/Task/Multiple-distinct-objects/Perl-6/multiple-distinct-objects-2.pl6 deleted file mode 100644 index 981f9dce05..0000000000 --- a/Task/Multiple-distinct-objects/Perl-6/multiple-distinct-objects-2.pl6 +++ /dev/null @@ -1 +0,0 @@ -my @a = map { Foo.new }, ^$n diff --git a/Task/Multiple-distinct-objects/Phix/multiple-distinct-objects-1.phix b/Task/Multiple-distinct-objects/Phix/multiple-distinct-objects-1.phix new file mode 100644 index 0000000000..6b7730f1d3 --- /dev/null +++ b/Task/Multiple-distinct-objects/Phix/multiple-distinct-objects-1.phix @@ -0,0 +1,8 @@ +sequence s = repeat("x",3*rand(3)) +?s + s[rand(length(s))] = 5 +?s + s[rand(length(s))] &= 'y' +?s + s[rand(length(s))] = s +?s diff --git a/Task/Multiple-distinct-objects/Phix/multiple-distinct-objects-2.phix b/Task/Multiple-distinct-objects/Phix/multiple-distinct-objects-2.phix new file mode 100644 index 0000000000..544f7bd163 --- /dev/null +++ b/Task/Multiple-distinct-objects/Phix/multiple-distinct-objects-2.phix @@ -0,0 +1 @@ +sequence s = repeat(my_func(),5) diff --git a/Task/Multiple-distinct-objects/Phix/multiple-distinct-objects-3.phix b/Task/Multiple-distinct-objects/Phix/multiple-distinct-objects-3.phix new file mode 100644 index 0000000000..e3fd2a6785 --- /dev/null +++ b/Task/Multiple-distinct-objects/Phix/multiple-distinct-objects-3.phix @@ -0,0 +1,4 @@ +sequence s = repeat(0,5) +for i=1 to length(s) do + s[i] = my_func() +end for diff --git a/Task/Multiple-distinct-objects/Zkl/multiple-distinct-objects.zkl b/Task/Multiple-distinct-objects/Zkl/multiple-distinct-objects.zkl new file mode 100644 index 0000000000..cc58693dfa --- /dev/null +++ b/Task/Multiple-distinct-objects/Zkl/multiple-distinct-objects.zkl @@ -0,0 +1,18 @@ +n:=3; +n.pump(List) //-->L(0,1,2) + +n.pump(List,List) //-->L(0,1,2), not expected + because the second list can be used to describe a calculation +n.pump(List,List(Void,List)) //--> L(L(),L(),L()) all same + List(Void,List) means returns List, which is a "known" value +n.pump(List,List.fpM("-")) //--> L(L(),L(),L()) all distinct + fpM is partial application: call List.create() + +n.pump(List,(0.0).random.fp(1)) //--> 3 [0,1) randoms +L(0.902645,0.799657,0.0753809) + +n.pump(String) //-->"012", default action is id function + +class C{ var n; fcn init(x){n=x} } +n.pump(List,C) //--> L(C,C,C) +n.pump(List,C).apply("n") //-->L(0,1,2) ie all classes distinct diff --git a/Task/Multiple-regression/Fortran/multiple-regression.f b/Task/Multiple-regression/Fortran/multiple-regression.f new file mode 100644 index 0000000000..b7e06c9d48 --- /dev/null +++ b/Task/Multiple-regression/Fortran/multiple-regression.f @@ -0,0 +1,85 @@ +*----------------------------------------------------------------------- +* MR - multiple regression using the SLATEC library routine DHFTI +* +* Finds the nearest approximation to BETA in the system of linear equations: +* +* X(j,i) . BETA(i) = Y(j) +* where +* 1 ... j ... N +* 1 ... i ... K +* and +* K .LE. N +* +* INPUT ARRAYS ARE DESTROYED! +* +*___Name_________Type_______________In/Out____Description________________________ +* X(N,K) Double precision In Predictors +* Y(N) Double precision Both On input: N Observations +* On output: K beta weights +* N Integer In Number of observations +* K Integer In Number of predictor variables +* DWORK(3*K) Double precision Neither Workspace +* IWORK(K) Integer Neither Workspace +*----------------------------------------------------------------------- + SUBROUTINE MR (X, Y, N, K, DWORK, IWORK) + IMPLICIT NONE + INTEGER K, N, IWORK + DOUBLE PRECISION X, Y, DWORK + DIMENSION X(N,K), Y(N), DWORK(3*K), IWORK(K) + +* local variables + INTEGER I, J + DOUBLE PRECISION TAU, TOT + +* maximum of all column sums of magnitudes + TAU = 0. + DO J = 1, K + TOT = 0. + DO I = 1, N + TOT = TOT + ABS(X(I,J)) + END DO + IF (TOT > TAU) TAU = TOT + END DO + TAU = TAU * EPSILON(TAU) ! tolerance argument + +* call function + CALL DHFTI (X, N, N, K, Y, N, 1, TAU, + $ J, DWORK(1), DWORK(K+1), DWORK(2*K+1), IWORK) + IF (J < K) PRINT *, 'mr: solution is rank deficient!' + RETURN + END ! of MR + +*----------------------------------------------------------------------- + PROGRAM t_mr ! polynomial regression example + IMPLICIT NONE + INTEGER N, K + PARAMETER (N=15, K=3) + INTEGER IWORK(K), I, J + DOUBLE PRECISION XIN(N), X(N,K), Y(N), DWORK(3*K) + + DATA XIN / 1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, + $ 1.70, 1.73, 1.75, 1.78, 1.80, 1.83 / + DATA Y / 52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, + $ 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46 / + +* make coefficient matrix + DO J = 1, K + DO I = 1, N + X(I,J) = XIN(I) **(J-1) + END DO + END DO + +* solve + CALL MR (X, Y, N, K, DWORK, IWORK) + +* print result + 10 FORMAT ('beta: ', $) + 20 FORMAT (F12.4, $) + 30 FORMAT () + PRINT 10 + DO J = 1, K + PRINT 20, Y(J) + END DO + PRINT 30 + STOP 'program complete' + END diff --git a/Task/Multiple-regression/J/multiple-regression-4.j b/Task/Multiple-regression/J/multiple-regression-4.j new file mode 100644 index 0000000000..11cf83731d --- /dev/null +++ b/Task/Multiple-regression/J/multiple-regression-4.j @@ -0,0 +1,4 @@ + load 'math/lapack' + load 'math/lapack/gels' + gels_jlapack_ X;y +128.813 _143.162 61.9603 diff --git a/Task/Multiple-regression/Zkl/multiple-regression-1.zkl b/Task/Multiple-regression/Zkl/multiple-regression-1.zkl new file mode 100644 index 0000000000..c3c08e4203 --- /dev/null +++ b/Task/Multiple-regression/Zkl/multiple-regression-1.zkl @@ -0,0 +1,9 @@ +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +height:=GSL.VectorFromData(1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, + 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83); +weight:=GSL.VectorFromData(52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, + 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46); +v:=GSL.polyFit(height,weight,2); +v.format().println(); +GSL.Helpers.polyString(v).println(); +GSL.Helpers.polyEval(v,height).format().println(); diff --git a/Task/Multiple-regression/Zkl/multiple-regression-2.zkl b/Task/Multiple-regression/Zkl/multiple-regression-2.zkl new file mode 100644 index 0000000000..c35eb3daed --- /dev/null +++ b/Task/Multiple-regression/Zkl/multiple-regression-2.zkl @@ -0,0 +1,56 @@ +// Solve a linear system AX=B where A is symmetric and positive definite, so it can be Cholesky decomposed. +fcn linsys(A,B){ + n,m:=A.len(),B[1].len(); // A.rows,B.cols + y:=n.pump(List.createLong(n).write,0.0); // writable vector of n zeros + X:=make_array(n,m,0.0); + L:=cholesky(A); // A=LL' + + foreach col in (m){ + foreach k in (n){ // Forward substitution: y = L\B + y[k]=( B[k][col] - k.reduce('wrap(s,j){ s + L[k][j]*y[j] },0.0) ) + /L[k][k]; + } + foreach k in ([n-1..0,-1]){ // Back substitution. x=L'\y + X[k][col]= + ( y[k] - (k+1).reduce(n-k-1,'wrap(s,j){ s + L[j][k]*X[j][col] },0.0) ) + /L[k][k]; + } + } + X +} +fcn cholesky(mat){ // Cholesky decomposition task + rows:=mat.len(); + r:=(0).pump(rows,List().write, (0).pump(rows,List,0.0).copy); // matrix of zeros + foreach i,j in (rows,i+1){ + s:=(0).reduce(j,'wrap(s,k){ s + r[i][k]*r[j][k] },0.0); + r[i][j]=( if(i==j)(mat[i][i] - s).sqrt() + else 1.0/r[j][j]*(mat[i][j] - s) ); + } + r +} + +// Solve a linear least squares problem. Ax=b, with A being mxn, with m>n. +// Solves the linear system A'Ax=A'b. +fcn lsqr(A,b){ + at:=transpose(A); + linsys(matMult(at,A), matMult(at,b)); +} +// Least square fit of a polynomial of order n the x-y-curve. +fcn polyfit(x,y,n){ + n+=1; + m:=x[0].len(); // columns + A:=make_array(m,n,0.0); + foreach i,j in (m,n){ A[i][j]=x[0][i].pow(j); } + lsqr(A, transpose(y)); +} +fcn make_array(n,m,v){ (m).pump(List.createLong(m).write,v)*n } +fcn matMult(a,b){ + n,m,p:=a[0].len(),a.len(),b[0].len(); + ans:=make_array(m,p,0.0); + foreach i,j,k in (m,p,n){ ans[i][j]+=a[i][k]*b[k][j]; } + ans +} +fcn transpose(M){ + if(M.len()==1) M[0].pump(List,List.create); // 1 row --> n columns + else M[0].zip(M.xplode(1)); +} diff --git a/Task/Multiple-regression/Zkl/multiple-regression-3.zkl b/Task/Multiple-regression/Zkl/multiple-regression-3.zkl new file mode 100644 index 0000000000..3e9597bb4e --- /dev/null +++ b/Task/Multiple-regression/Zkl/multiple-regression-3.zkl @@ -0,0 +1,5 @@ +height:=T(T(1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, + 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83)); +weight:=T(T(52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, + 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46)); +polyfit(height,weight,2).flatten().println(); diff --git a/Task/Multiplication-tables/Agena/multiplication-tables.agena b/Task/Multiplication-tables/Agena/multiplication-tables.agena new file mode 100644 index 0000000000..2127271ec5 --- /dev/null +++ b/Task/Multiplication-tables/Agena/multiplication-tables.agena @@ -0,0 +1,14 @@ +scope + # print a school style multiplication table + # NB: print outputs a newline at the end, write and printf do not + write( " " ); + for i to 12 do printf( " %3d", i ) od; + printf( "\n +" ); + for i to 12 do write( "----" ) od; + for i to 12 do + printf( "\n%3d|", i ); + for j to i - 1 do write( " " ) od; + for j from i to 12 do printf( " %3d", i * j ) od; + od; + print() +epocs diff --git a/Task/Multiplication-tables/AppleScript/multiplication-tables-2.applescript b/Task/Multiplication-tables/AppleScript/multiplication-tables-2.applescript index 98b3c97038..16f05d7146 100644 --- a/Task/Multiplication-tables/AppleScript/multiplication-tables-2.applescript +++ b/Task/Multiplication-tables/AppleScript/multiplication-tables-2.applescript @@ -1,89 +1,113 @@ --- MULTIPLICATION TABLE FOR INTEGERS M TO N +tableText(multTable(1, 12)) --- table :: Int -> Int -> [[String]] -on table(m, n) +-- multTable :: Int -> [[String]] +on multTable(m, n) - set axis to range(m, n) + set axis to enumFromTo(m, n) script column - on lambda(x) + on |λ|(x) script row - on lambda(y) + on |λ|(y) if y < x then - {""} + "" else - {(x * y) as text} + (x * y) as string end if - end lambda + end |λ| end script {x & map(row, axis)} - end lambda + end |λ| end script {{"x"} & axis} & concatMap(column, axis) -end table +end multTable +-- TABLE DISPLAY -------------------------------------------------------------- -on run - - tableText(table(1, 12)) - -end run - - --- TABLE DISPLAY - --- tableText :: [[String]] -> String +-- tableText :: [[Int]] -> String on tableText(lstTable) script tableLine - on lambda(lstLine) + on |λ|(lstLine) script tableCell - on lambda(cell) - (characters -4 thru -1 of (" " & cell)) as string - end lambda + on |λ|(int) + (characters -4 thru -1 of (" " & int)) as string + end |λ| end script intercalate(" ", map(tableCell, lstLine)) - end lambda + end |λ| end script intercalate(linefeed, map(tableLine, lstTable)) end tableText --- GENERIC LIBRARY FUNCTIONS +-- GENERIC FUNCTIONS ---------------------------------------------------------- -- concatMap :: (a -> [b]) -> [a] -> [b] on concatMap(f, xs) - script append - on lambda(a, b) - a & b - end lambda - end script - - foldl(append, {}, map(f, xs)) + set lst to {} + set lng to length of xs + tell mReturn(f) + repeat with i from 1 to lng + set lst to (lst & |λ|(item i of xs, i, xs)) + end repeat + end tell + return lst end concatMap +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo + -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + +-- justifyRight :: Int -> Char -> Text -> Text +on justifyRight(n, cFiller, strText) + if n > length of strText then + text -n thru -1 of ((replicate(n, cFiller) as text) & strText) + else + strText + end if +end justifyRight + -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -96,29 +120,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn - --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then - set d to -1 - else - set d to 1 - end if - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range - --- intercalate :: Text -> [Text] -> Text -on intercalate(strText, lstText) - set {dlm, my text item delimiters} to {my text item delimiters, strText} - set strJoined to lstText as text - set my text item delimiters to dlm - return strJoined -end intercalate diff --git a/Task/Multiplication-tables/C/multiplication-tables-1.c b/Task/Multiplication-tables/C/multiplication-tables-1.c deleted file mode 100644 index ae132d1d00..0000000000 --- a/Task/Multiplication-tables/C/multiplication-tables-1.c +++ /dev/null @@ -1,13 +0,0 @@ -int main() -{ - int i, j, n = 12; - - for (j = 1; j <= n; j++) printf("%3d%c", j, j - n ? ' ':'\n'); - for (j = 0; j <= n; j++) printf(j - n ? "----" : "+\n"); - - for (i = 1; i <= n; printf("| %d\n", i++)) - for (j = 1; j <= n; j++) - printf(j < i ? " " : "%3d ", i * j); - - return 0; -} diff --git a/Task/Multiplication-tables/C/multiplication-tables-2.c b/Task/Multiplication-tables/C/multiplication-tables-2.c deleted file mode 100644 index 65e7dd3346..0000000000 --- a/Task/Multiplication-tables/C/multiplication-tables-2.c +++ /dev/null @@ -1,14 +0,0 @@ - 1 2 3 4 5 6 7 8 9 10 11 12 ------------------------------------------------- - 1 2 3 4 5 6 7 8 9 10 11 12 | 1 - 4 6 8 10 12 14 16 18 20 22 24 | 2 - 9 12 15 18 21 24 27 30 33 36 | 3 - 16 20 24 28 32 36 40 44 48 | 4 - 25 30 35 40 45 50 55 60 | 5 - 36 42 48 54 60 66 72 | 6 - 49 56 63 70 77 84 | 7 - 64 72 80 88 96 | 8 - 81 90 99 108 | 9 - 100 110 120 | 10 - 121 132 | 11 - 144 | 12 diff --git a/Task/Multiplication-tables/CoffeeScript/multiplication-tables-1.coffee b/Task/Multiplication-tables/CoffeeScript/multiplication-tables-1.coffee deleted file mode 100644 index d9b87b39fd..0000000000 --- a/Task/Multiplication-tables/CoffeeScript/multiplication-tables-1.coffee +++ /dev/null @@ -1,31 +0,0 @@ -print_multiplication_tables = (n) -> - width = 4 - - pad = (s, n=width, c=' ') -> - s = s.toString() - result = '' - padding = n - s.length - while result.length < padding - result += c - result + s - - s = pad('') + '|' - for i in [1..n] - s += pad i - console.log s - - s = pad('', width, '-') + '+' - for i in [1..n] - s += pad '', width, '-' - console.log s - - - for i in [1..n] - s = pad i - s += '|' - s += pad '', width*(i - 1) - for j in [i..n] - s += pad i*j - console.log s - -print_multiplication_tables 12 diff --git a/Task/Multiplication-tables/CoffeeScript/multiplication-tables-2.coffee b/Task/Multiplication-tables/CoffeeScript/multiplication-tables-2.coffee deleted file mode 100644 index a0aa40554d..0000000000 --- a/Task/Multiplication-tables/CoffeeScript/multiplication-tables-2.coffee +++ /dev/null @@ -1,15 +0,0 @@ -> coffee multiply.coffee - | 1 2 3 4 5 6 7 8 9 10 11 12 -----+------------------------------------------------ - 1| 1 2 3 4 5 6 7 8 9 10 11 12 - 2| 4 6 8 10 12 14 16 18 20 22 24 - 3| 9 12 15 18 21 24 27 30 33 36 - 4| 16 20 24 28 32 36 40 44 48 - 5| 25 30 35 40 45 50 55 60 - 6| 36 42 48 54 60 66 72 - 7| 49 56 63 70 77 84 - 8| 64 72 80 88 96 - 9| 81 90 99 108 - 10| 100 110 120 - 11| 121 132 - 12| 144 diff --git a/Task/Multiplication-tables/Gambas/multiplication-tables.gambas b/Task/Multiplication-tables/Gambas/multiplication-tables.gambas new file mode 100644 index 0000000000..d4876a2a25 --- /dev/null +++ b/Task/Multiplication-tables/Gambas/multiplication-tables.gambas @@ -0,0 +1,23 @@ +'Code 'stolen' from Free Basic and altered to work in Gambas + +Public Sub Main() +Dim i, j As Integer + +Print " X|"; +For i = 1 To 12 + Print Format(i, "####"); +Next + +Print +Print "---+"; String(48, "-") + +For i = 1 To 12 + Print Format(i, "###"); + Print "|"; Space(4 * (i - 1)); + For j = i To 12 + Print Format(i * j, "####"); + Next + Print +Next + +End diff --git a/Task/Multiplication-tables/Haskell/multiplication-tables.hs b/Task/Multiplication-tables/Haskell/multiplication-tables.hs index a8d752aec1..2aa5a6cf12 100644 --- a/Task/Multiplication-tables/Haskell/multiplication-tables.hs +++ b/Task/Multiplication-tables/Haskell/multiplication-tables.hs @@ -1,8 +1,26 @@ -import Control.Monad -import Text.Printf +import Data.Monoid ((<>)) +import Data.List (intercalate, transpose) -main = do - putStrLn $ " x" ++ concatMap fmt [1..12] - zipWithM_ f [1..12] $ iterate (" " ++) "" - where f n s = putStrLn $ fmt n ++ s ++ concatMap (fmt . (*n)) [n..12] - fmt n = printf "%4d" (n :: Int) +multTable :: Int -> [[String]] +multTable n = + let xs = [1 .. n] + in xs >>= + \x -> + [ show x <> ":" : + (xs >>= + \y -> + [ if y < x + then mempty + else show (x * y) + ]) + ] + +table :: String -> [[String]] -> [String] +table delim rows = + let justifyRight c n s = drop (length s) (replicate n c <> s) + in intercalate delim <$> + transpose + ((fmap =<< justifyRight ' ' . maximum . fmap length) <$> transpose rows) + +main :: IO () +main = (putStrLn . unlines . table " " . multTable) 12 diff --git a/Task/Multiplication-tables/Kotlin/multiplication-tables.kotlin b/Task/Multiplication-tables/Kotlin/multiplication-tables.kotlin new file mode 100644 index 0000000000..5683cc8de6 --- /dev/null +++ b/Task/Multiplication-tables/Kotlin/multiplication-tables.kotlin @@ -0,0 +1,12 @@ +// version 1.0.6 + +fun main(args: Array) { + print(" x|") + for (i in 1..12) print("%4d".format(i)) + println("\n---+${"-".repeat(48)}") + for (i in 1..12) { + print("%3d".format(i) +"|${" ".repeat(4 * i - 4)}") + for (j in i..12) print("%4d".format(i * j)) + println() + } +} diff --git a/Task/Multiplication-tables/MATLAB/multiplication-tables-3.m b/Task/Multiplication-tables/MATLAB/multiplication-tables-3.m deleted file mode 100644 index 307da97377..0000000000 --- a/Task/Multiplication-tables/MATLAB/multiplication-tables-3.m +++ /dev/null @@ -1,17 +0,0 @@ -timesTable(12) - -ans = - - 0 1 2 3 4 5 6 7 8 9 10 11 12 - 1 1 2 3 4 5 6 7 8 9 10 11 12 - 2 0 4 6 8 10 12 14 16 18 20 22 24 - 3 0 0 9 12 15 18 21 24 27 30 33 36 - 4 0 0 0 16 20 24 28 32 36 40 44 48 - 5 0 0 0 0 25 30 35 40 45 50 55 60 - 6 0 0 0 0 0 36 42 48 54 60 66 72 - 7 0 0 0 0 0 0 49 56 63 70 77 84 - 8 0 0 0 0 0 0 0 64 72 80 88 96 - 9 0 0 0 0 0 0 0 0 81 90 99 108 - 10 0 0 0 0 0 0 0 0 0 100 110 120 - 11 0 0 0 0 0 0 0 0 0 0 121 132 - 12 0 0 0 0 0 0 0 0 0 0 0 144 diff --git a/Task/Multiplication-tables/Perl-6/multiplication-tables.pl6 b/Task/Multiplication-tables/Perl-6/multiplication-tables.pl6 index 9c39618293..3c1f83c3fc 100644 --- a/Task/Multiplication-tables/Perl-6/multiplication-tables.pl6 +++ b/Task/Multiplication-tables/Perl-6/multiplication-tables.pl6 @@ -2,10 +2,10 @@ my $max = 12; my $width = chars $max**2; my $f = "%{$width}s"; -say 'x'.fmt($f), '┃ ', (1..$max).fmt($f); -say '━' x $width, '╋', '━' x $max*$width + $max; +say 'x'.fmt($f), '│ ', (1..$max).fmt($f); +say '─' x $width, '┼', '─' x $max*$width + $max; for 1..$max -> $i { - say $i.fmt($f), '┃ ', ( + say $i.fmt($f), '│ ', ( for 1..$max -> $j { $i <= $j ?? $i*$j !! ''; } diff --git a/Task/Multiplication-tables/R/multiplication-tables-1.r b/Task/Multiplication-tables/R/multiplication-tables-1.r deleted file mode 100644 index 9ef629625f..0000000000 --- a/Task/Multiplication-tables/R/multiplication-tables-1.r +++ /dev/null @@ -1 +0,0 @@ -upper.tri(1:12 %o% 1:12, diag = TRUE) * 1:12 %o% 1:12 diff --git a/Task/Multiplication-tables/R/multiplication-tables-2.r b/Task/Multiplication-tables/R/multiplication-tables-2.r deleted file mode 100644 index ff51afb0db..0000000000 --- a/Task/Multiplication-tables/R/multiplication-tables-2.r +++ /dev/null @@ -1,10 +0,0 @@ -multiplication_table <- function(n=12) -{ - one_to_n <- 1:n - x <- matrix(one_to_n) %*% t(one_to_n) - x[lower.tri(x)] <- 0 - rownames(x) <- colnames(x) <- one_to_n - print(as.table(x), zero.print="") - invisible(x) -} -multiplication_table() diff --git a/Task/Multiplication-tables/REXX/multiplication-tables.rexx b/Task/Multiplication-tables/REXX/multiplication-tables.rexx index 129a0d150e..05b18c83c6 100644 --- a/Task/Multiplication-tables/REXX/multiplication-tables.rexx +++ b/Task/Multiplication-tables/REXX/multiplication-tables.rexx @@ -1,45 +1,39 @@ /*REXX program displays a NxN multiplication table (in a boxed grid) to the terminal.*/ parse arg high . /*obtain optional grid size from the CL*/ if high=='' | high=="," then high=12 /*Not specified? Then use the default.*/ - bar = '│' ; dash = "─" /*(vertical) bar; horizontal bar (dash)*/ - bj = '┴' ; tj = "┬" /*bottom and top junctions (or tees).*/ - cj = '┼' /*center junction (or cross). */ - lj = '├' ; rj = "┤" /*left and right junctions (or tees).*/ - tlc = '┌' ; trc = "┐" /* top left and right corners. */ - blc = '└' ; brc = "┘" /*bottom " " " " */ - /* [↑] define stuff to hold box glyphs*/ + bar = '│' ; dash = "─" /*(vertical) bar; horizontal bar (dash)*/ + bj = '┴' ; tj = "┬" /*bottom and top junctions (or tees).*/ + cj = '┼' /*center junction (or cross). */ + lj = '├' ; rj = "┤" /*left and right junctions (or tees).*/ + tlc = '┌' ; trc = "┐" /* top left and right corners. */ + blc = '└' ; brc = "┘" /*bottom " " " " */ cell = cj || copies(dash,max(5,length(high) +1)) /*define the top of the cell. */ sep = copies(cell, high+1)rj /*construct the table separator. */ size = length(cell) - 1 /*width for the products in the table. */ box. = left('', size) /*initialize all the cells in the table*/ + do j=0 to high /*step through zero ───► high. */ + _=right(j, size - 2)'x ' /*build the "label" (border) number. */ + box.0.j=center(_, size) /* " " top label cell. */ + box.j.0=center(_, max(5, size) ) /* " " left label cell. */ + end /*j*/ +box.0.0=center('times', max(5, size)) /*redefine box.0.0 with "times". */ + do r=1 for high /*step through row one ───► high. */ + do c=r to high /*step through column row ───► high. */ + box.r.c=right(r*c, size) /*build a single multiplication cell. */ + end /*c*/ + end /*r*/ /*only build the top right-half of grid*/ - do j=0 to high /*step through zero ───► high. */ - _=right(j, size - 2)'x ' /*build the "label" (border) number. */ - box.0.j=center(_, size) /* " " top label cell. */ - box.j.0=center(_, max(5, size) ) /* " " left label cell. */ - end /*j*/ - -box.0.0=center('times', max(5, size)) /*redefine box.0.0 with "times". */ - - do r=1 for high /*step through row one ───► high. */ - do c=r to high /*step through column row ───► high. */ - box.r.c=right(r*c, size) /*build a single multiplication cell. */ - end /*c*/ - end /*r*/ /*only build the top right-half of grid*/ - - do r=0 to high; @=sep /*step through all lines; use a mod sep*/ - if r==0 then do - @=overlay(tlc, @ , 1) /*use a better tlc (top left corner). */ - @=overlay(trc, @ , length(sep)) /* " " " trc ( " right " ). */ - @=translate(@, tj, cj) /* " " " tj (top junction/tee).*/ - end - else @=overlay(lj, @, 1) /* " " " lj (left junction/tee).*/ - say @ /*display a single table grid line. */ - if r==0 then call buildLine 00 /* " " " blank grid " */ - call buildLine r /*build a single line of the grid. */ - if r==0 then call buildLine 00 /*display a single blank grid line. */ - end /*r*/ - + do r=0 to high; @=sep; L=length(sep) /*step through all lines; use a mod sep*/ + if r==0 then do; @=overlay(tlc, @ , 1) /*use a better tlc (top left corner). */ + @=overlay(trc, @ , L) /* " " " trc ( " right " ). */ + @=translate(@, tj,cj) /* " " " tj (top junction/tee).*/ + end + else @=overlay(lj, @, 1) /* " " " lj (left junction/tee).*/ + say @ /*display a single table grid line. */ + if r==0 then call buildLine 00 /* " " " blank grid " */ + call buildLine r /*build a single line of the grid. */ + if r==0 then call buildLine 00 /*display a single blank grid line. */ + end /*r*/ @=sep /*allow use of a modified separator. */ @=overlay(blc, @ , 1) /*use a better bottom left corner. */ @=overlay(brc, @ , length(sep) ) /* " " " " right corner. */ @@ -47,9 +41,7 @@ box.0.0=center('times', max(5, size)) /*redefine box.0.0 with " say @ /*display a (single) table grid line. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -buildLine: parse arg row,,$ /*start with a blank cell ($). */ - do col=0 to high /*step through zero ───► high. */ - $=$ || bar || box.row.col /*build one cell at a time. */ - end /*col*/ - say $ || bar /*finish building the last cell.*/ - return +buildLine: parse arg row,,$; do col=0 to high /*step through zero ───► high. */ + $=$ ||bar ||box.row.col /*build one cell at a time. */ + end /*col*/ /* [↑] build (row) line by cols*/ + say $ || bar; return /*finish building the last cell.*/ diff --git a/Task/Multiplication-tables/Scala/multiplication-tables.scala b/Task/Multiplication-tables/Scala/multiplication-tables.scala new file mode 100644 index 0000000000..b3b2433bab --- /dev/null +++ b/Task/Multiplication-tables/Scala/multiplication-tables.scala @@ -0,0 +1,48 @@ +//Multiplication Table + +object mulTable{ + def main( args:Array[String] ){ + + print(" |") //Horizontal row + for( i <- 1 to 12 ) + if( i<10 ) + print( " " + i ) + else + print(" " + i ) + println("") + println("---------------------------------------------------------------------") + + for( i <- 1 to 12 ){ + + if( i<10 ) //Vertical column + print(" " + i + "|" ) + else + print(" " + i + "|" ) + + + for( j <- 1 to 12 ){ + + if( i*j < 10 ){ + if( i<=j ) + print(" " + i*j ) + else + print(" ") + } + else if( i*j < 100 ){ + if( i<=j ) + print(" " + i*j ) + else + print(" ") + } + else{ + if( i<=j ) + print(" " + i*j ) + else + print(" ") + } + } + println("") + } + + } +} diff --git a/Task/Multiplication-tables/Sidef/multiplication-tables.sidef b/Task/Multiplication-tables/Sidef/multiplication-tables.sidef index 7f336181d2..cb07406787 100644 --- a/Task/Multiplication-tables/Sidef/multiplication-tables.sidef +++ b/Task/Multiplication-tables/Sidef/multiplication-tables.sidef @@ -1,13 +1,13 @@ -var max = 12; -var width = (max**2 -> len+1); - +var max = 12 +var width = (max**2 -> len+1) +  func fmt_row(*items) { - items.map { |s| "%*s" % (width, s) }.join(''); + items.map {|s| "%*s" % (width, s) }.join } +  +say fmt_row('x┃', (1..max)...) +say "#{'━' * (width - 1)}╋#{'━' * (max * width)}" -say fmt_row('x┃', (1..max)...); -say "#{'━' * (width - 1)}╋#{'━' * (max * width)}"; - -max.times { |i| - say fmt_row("#{i}┃", (1..max).map {|j| i <= j ? i*j : ''}...); -}; +{ |i|  + say fmt_row("#{i}┃", {|j| i <= j ? i*j : ''}.map(1..max)...) +} << 1..max diff --git a/Task/Multiplication-tables/Zkl/multiplication-tables.zkl b/Task/Multiplication-tables/Zkl/multiplication-tables.zkl new file mode 100644 index 0000000000..ad7220bb42 --- /dev/null +++ b/Task/Multiplication-tables/Zkl/multiplication-tables.zkl @@ -0,0 +1,10 @@ +fcn multiplicationTable(n){ + w,fmt := (n*n).numDigits, " %%%dd".fmt(w).fmt; // eg " %3".fmt + header:=[1..n].apply(fmt).concat(); // 1 2 3 4 ... + println(" x ", header, "\n ", "-"*header.len()); + dash:=String(" "*w,"-"); // eg " -" + foreach a in ([1..n]){ + print("%2d|".fmt(a),dash*(a-1)); + [a..n].pump(String,'*(a),fmt).println(); + } +}(12); diff --git a/Task/Multiplicative-order/Perl-6/multiplicative-order.pl6 b/Task/Multiplicative-order/Perl-6/multiplicative-order.pl6 index b1d0536065..061f52f1ea 100644 --- a/Task/Multiplicative-order/Perl-6/multiplicative-order.pl6 +++ b/Task/Multiplicative-order/Perl-6/multiplicative-order.pl6 @@ -21,7 +21,7 @@ sub mo-prime($a, $p, $e) { my $t = ($p - 1) * ($p ** ($e - 1)); # = Phi($p**$e) where $p prime my @qs = 1; for factor($t) -> $f { - @qs = @qs.map(-> $q { (0..$f.value).map(-> $j { $q * $f.key ** $j }) }); + @qs = flat @qs.map(-> $q { (0..$f.value).map(-> $j { $q * $f.key ** $j }) }); } @qs.sort(); @@ -30,15 +30,13 @@ sub mo-prime($a, $p, $e) { sub mo($a, $m) { $a gcd $m == 1 || die "$a and $m are not relatively prime"; - [lcm] 1, factor($m).map(-> $r { mo-prime($a, $r.key, $r.value) }); + [lcm] flat 1, factor($m).map(-> $r { mo-prime($a, $r.key, $r.value) }); } sub MAIN("test") { use Test; for (10, 21, 25, 150, 1231, 123141, 34131) -> $n { - # say factor($n).perl; - # say factor($n).map(-> $pair { $pair.key ** $pair.value }).perl; is ([*] factor($n).map(-> $pair { $pair.key ** $pair.value })), $n, "$n factors correctly"; } diff --git a/Task/Multiplicative-order/REXX/multiplicative-order.rexx b/Task/Multiplicative-order/REXX/multiplicative-order.rexx new file mode 100644 index 0000000000..080b3861e9 --- /dev/null +++ b/Task/Multiplicative-order/REXX/multiplicative-order.rexx @@ -0,0 +1,26 @@ +/*REXX pgm computes multiplicative order of a minimum integer N such that a^n mod m≡1*/ +wa=0; wm=0 /* ═a═ ══m══ */ /*maximum widths of the A and M values.*/ +@.=.; @.1= 3 10 + @.2= 37 1000 + @.3= 37 10000 + @.4= 37 3343 + @.5= 37 3344 + @.6= 2 1000 +pad=left('',9) +d=100 /*use 100 decimal digits for a starter.*/ + do w=1 for 2 /*when W≡1, find max widths of A and M.*/ + do j=1 while @.j\==.; parse var @.j a . 1 r m , n + if w==1 then do; wa=max(wa, length(a)); wm=max(wm, length(m)); iterate; end + if m//a==0 then n= ' [solution not possible]' /*test co-prime for A and B. */ + numeric digits d /*start with 100 decimal digits. */ + if n=='' then do n=2; p=r*a /*compute product──may have an exponent*/ + parse var p 'E' _ /*try to extract the exponent from P. */ + if _\=='' then do; numeric digits _+d /*bump the decimal digs.*/ + p=r*a /*recalculate integer P.*/ + end + if p//m==1 then leave /*now, perform the nitty-gritty modulo.*/ + r=p /*assign product to R for next mult. */ + end /*n*/ /* [↑] // is really ÷ remainder.*/ + say pad 'a=' right(a,wa) pad "m=" right(m,wm) pad 'multiplicative order:' n + end /*j*/ + end /*w*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Multiplicative-order/Zkl/multiplicative-order-1.zkl b/Task/Multiplicative-order/Zkl/multiplicative-order-1.zkl new file mode 100644 index 0000000000..3fa1d8b537 --- /dev/null +++ b/Task/Multiplicative-order/Zkl/multiplicative-order-1.zkl @@ -0,0 +1,35 @@ +var BN =Import("zklBigNum"); +var Sieve=Import("sieve"); + + // factor n into powers of primes + // eg 9090 == 2^1 * 3^2 * 5^1 * 101^1 +fcn factor2PP(n){ // lazy factors using lazy primes --> (prime,power) ... + Utils.Generator(fcn(a){ + primes:=Utils.Generator(Sieve.postponed_sieve); + foreach p in (primes){ + e:=0; while(a%p == 0){ a /= p; e+=1; } + if (e) vm.yield(p,e); + if (a1) vm.yield(a,1); + },n) +} + +fcn _multOrdr1(a,p,e){ + m:=p.pow(e); + t:=m/p*(p - 1); + qs:=L(BN(1)); + foreach p2,e2 in (factor2PP(t)){ + qs=[[(e,q); [0..e2]; qs; '{ q*BN(p2).pow(e) }]]; + } + qs.filter1('wrap(q){ a.powm(q,m)==1 }); +} + +fcn multiOrder(a,m){ + if (m.gcd(a)!=1) throw(Exception.ValueError("Not co-prime")); + res:=BN(1); + foreach p,e in (factor2PP(m)){ + res = res.lcm(_multOrdr1(BN(a),BN(p),e)); + } + return(res); +} diff --git a/Task/Multiplicative-order/Zkl/multiplicative-order-2.zkl b/Task/Multiplicative-order/Zkl/multiplicative-order-2.zkl new file mode 100644 index 0000000000..14ea8ac8d3 --- /dev/null +++ b/Task/Multiplicative-order/Zkl/multiplicative-order-2.zkl @@ -0,0 +1,9 @@ +multiOrder(37,1000).println(); +b:=BN(10).pow(20)-1; +multiOrder(2,b).println(); +multiOrder(17,b).println(); + +b=0d10_0001; +[BN(1)..multiOrder(54,b)-1].filter1('wrap(r,b54){b54.powm(r,b)==1},BN(54)) : +if (_) println("Exists a power r < 9090 where (54^r)%b)==1"); +else println("Everything checks."); diff --git a/Task/Multisplit/ALGOL-68/multisplit.alg b/Task/Multisplit/ALGOL-68/multisplit.alg new file mode 100644 index 0000000000..71c965097a --- /dev/null +++ b/Task/Multisplit/ALGOL-68/multisplit.alg @@ -0,0 +1,66 @@ +# split a string based on a number of separators # + +# MODE to hold the split results # +MODE SPLITINFO = STRUCT( STRING text # delimited string, may be empty # + , INT position # starting position of the token # + , STRING delimiter # the delimiter that terminated the token # + ); +# calculates the length of string s # +OP LENGTH = ( STRING s )INT: ( UPB s + 1 ) - LWB s; +# returns TRUE if s starts with p, FALSE otherwise # +PRIO STARTSWITH = 5; +OP STARTSWITH = ( STRING s, p )BOOL: IF LENGTH p > LENGTH s THEN FALSE ELSE s[ LWB s : ( LWB s + LENGTH p ) - 1 ] = p FI; +# returns an array of SPLITINFO describing the tokens in str based on the delimiters # +# zero-length delimiters are ignored # +PRIO SPLIT = 5; +OP SPLIT = ( STRING str, []STRING delimiters )[]SPLITINFO: + BEGIN + # count the number of tokens # + # allow there to be as many tokens as characters in the string + 2 # + # that would cater for a string composed of delimiters only # + [ 1 : ( UPB str + 3 ) - LWB str ]SPLITINFO tokens; + INT token count := 0; + INT str pos := LWB str; + INT str max = UPB str; + BOOL token pending := FALSE; + # construct the tokens # + str pos := LWB str; + INT prev pos := LWB str; + token count := 0; + token pending := FALSE; + WHILE str pos <= str max + DO + BOOL found delimiter := FALSE; + FOR d FROM LWB delimiters TO UPB delimiters WHILE NOT found delimiter DO + IF LENGTH delimiters[ d ] > 0 THEN + IF found delimiter := str[ str pos : ] STARTSWITH delimiters[ d ] THEN + token count +:= 1; + tokens[ token count ] := ( str[ prev pos : str pos - 1 ], prev pos, delimiters[ d ] ); + str pos +:= LENGTH delimiters[ d ]; + prev pos := str pos; + token pending := FALSE + FI + FI + OD; + IF NOT found delimiter THEN + # the current character is part of s token # + token pending := TRUE; + str pos +:= 1 + FI + OD; + IF token pending THEN + # there is an additional token after the final delimiter # + token count +:= 1; + tokens[ token count ] := ( str[ prev pos : ], prev pos, "" ) + FI; + # return an array of the actual tokens # + tokens[ 1 : token count ] + END # SPLIT # ; + + +# test the SPLIT operator # +[]SPLITINFO test tokens = "a!===b=!=c" SPLIT []STRING( "==", "!=", "=" ); +FOR t FROM LWB test tokens TO UPB test tokens DO + SPLITINFO token = test tokens[ t ]; + print( ( "token: [", text OF token, "] at: ", whole( position OF token, 0 ), " delimiter: (", delimiter OF token, ")", newline ) ) +OD diff --git a/Task/Multisplit/Haskell/multisplit.hs b/Task/Multisplit/Haskell/multisplit.hs index cf5d0f8276..bd9d1ada29 100644 --- a/Task/Multisplit/Haskell/multisplit.hs +++ b/Task/Multisplit/Haskell/multisplit.hs @@ -1,27 +1,28 @@ -import Data.List as L -import Data.Maybe +import Data.List + (isPrefixOf, stripPrefix, genericLength, intercalate) -trysplit :: Eq a => [a] -> [[a]] -> Maybe ([a], [a]) +trysplit :: String -> [String] -> Maybe (String, String) trysplit s delims = - case filter (`L.isPrefixOf` s) delims of - [] -> Nothing - (d:_) -> Just (d, fromJust $ L.stripPrefix d s) + case filter (`isPrefixOf` s) delims of + [] -> Nothing + (d:_) -> Just (d, (\(Just x) -> x) $ stripPrefix d s) -multisplit :: (Eq a, Num n) => [a] -> [[a]] -> [([a], [a], n)] +multisplit :: String -> [String] -> [(String, String, Int)] multisplit list delims = - let ms [] acc pos = [(acc, [], pos)] + let ms [] acc pos = [(acc, [], pos)] ms l@(s:sx) acc pos = case trysplit l delims of - Nothing -> ms sx (s:acc) (pos + 1) - Just (d, sxx) -> (acc, d, pos) : ms sxx [] (pos + L.genericLength d) + Nothing -> ms sx (s : acc) (pos + 1) + Just (d, sxx) -> (acc, d, pos) : ms sxx [] (pos + genericLength d) in ms list [] 0 main :: IO () main = do - let test = "a!===b=!=c" - delims = ["==", "!=", "="] - parsed = multisplit test delims - putStrLn "split string:" - putStrLn $ L.intercalate "," $ map (\(a, _, _) -> a) parsed - putStrLn "with [(string, delimiter, offset)]:" - print parsed + let parsed = multisplit "a!===b=!=c" ["==", "!=", "="] + mapM_ + putStrLn + [ "split string:" + , intercalate "," $ map (\(a, _, _) -> a) parsed + , "with [(string, delimiter, offset)]:" + , show parsed + ] diff --git a/Task/Multisplit/jq/multisplit.jq b/Task/Multisplit/Jq/multisplit.jq similarity index 100% rename from Task/Multisplit/jq/multisplit.jq rename to Task/Multisplit/Jq/multisplit.jq diff --git a/Task/Multisplit/Kotlin/multisplit.kotlin b/Task/Multisplit/Kotlin/multisplit.kotlin new file mode 100644 index 0000000000..5c169ad2ac --- /dev/null +++ b/Task/Multisplit/Kotlin/multisplit.kotlin @@ -0,0 +1,31 @@ +// version 1.0.6 + +fun main(args: Array) { + val input = "a!===b=!=c" + val delimiters = arrayOf("==", "!=", "=") + val output = input.split(*delimiters).toMutableList() + for (i in 0 until output.size) { + if (output[i].isEmpty()) output[i] = "empty string" + else output[i] = "\"" + output[i] + "\"" + } + println("The splits are:") + println(output) + + // now find positions of matched delimiters + val matches = mutableListOf>() + var index = 0 + while (index < input.length) { + var matched = false + for (d in delimiters) { + if (input.drop(index).take(d.length) == d) { + matches.add(d to index) + index += d.length + matched = true + break + } + } + if (!matched) index++ + } + println("\nThe delimiters matched and the indices at which they occur are:") + println(matches) +} diff --git a/Task/Multisplit/Phix/multisplit.phix b/Task/Multisplit/Phix/multisplit.phix new file mode 100644 index 0000000000..e8fbd5d827 --- /dev/null +++ b/Task/Multisplit/Phix/multisplit.phix @@ -0,0 +1,24 @@ +procedure multisplit(string text, sequence delims) +integer k = 1, kdx + while 1 do + integer kmin = 0 + for i=1 to length(delims) do + integer ki = match(delims[i],text,k) + if ki!=0 then + if kmin=0 or ki lastmatch) matches.append(text[lastmatch,i-lastmatch]); + matches.append(T(j,i)); # Replace the string containing the matched separator with a tuple of which separator and where in the string the match occured + lastmatch = i + s.len(); + i += s.len()-1; + break; + } + } + i += 1; + } + if(i > lastmatch) matches.append(text[lastmatch,i-lastmatch]); + return(matches); +} diff --git a/Task/Multisplit/Zkl/multisplit-2.zkl b/Task/Multisplit/Zkl/multisplit-2.zkl new file mode 100644 index 0000000000..0030d56467 --- /dev/null +++ b/Task/Multisplit/Zkl/multisplit-2.zkl @@ -0,0 +1,2 @@ +multisplit("a!===b=!=c", T("==", "!=", "=")).println(); +multisplit("a!===b=!=c", T("!=", "==", "=")).println(); diff --git a/Task/Munching-squares/Haskell/munching-squares.hs b/Task/Munching-squares/Haskell/munching-squares.hs index 682da41cee..deb1286ab0 100644 --- a/Task/Munching-squares/Haskell/munching-squares.hs +++ b/Task/Munching-squares/Haskell/munching-squares.hs @@ -1,4 +1,13 @@ -import Data.ByteString -import Data.Bits +import qualified Data.ByteString as BY (writeFile, pack) -main = Data.ByteString.writeFile "out.pgm" (pack (fmap (fromIntegral . fromEnum) "P5\n256 256\n256\n" ++ [x `xor` y | x <- [0..255], y <- [0..255]])) +import Data.Bits (xor) + +main :: IO () +main = + BY.writeFile + "out.pgm" + (BY.pack + (fmap (fromIntegral . fromEnum) "P5\n256 256\n256\n" ++ + [ x `xor` y + | x <- [0 .. 255] + , y <- [0 .. 255] ])) diff --git a/Task/Munching-squares/jq/munching-squares-1.jq b/Task/Munching-squares/Jq/munching-squares-1.jq similarity index 100% rename from Task/Munching-squares/jq/munching-squares-1.jq rename to Task/Munching-squares/Jq/munching-squares-1.jq diff --git a/Task/Munching-squares/jq/munching-squares-2.jq b/Task/Munching-squares/Jq/munching-squares-2.jq similarity index 100% rename from Task/Munching-squares/jq/munching-squares-2.jq rename to Task/Munching-squares/Jq/munching-squares-2.jq diff --git a/Task/Munching-squares/jq/munching-squares-3.jq b/Task/Munching-squares/Jq/munching-squares-3.jq similarity index 100% rename from Task/Munching-squares/jq/munching-squares-3.jq rename to Task/Munching-squares/Jq/munching-squares-3.jq diff --git a/Task/Munching-squares/jq/munching-squares-4.jq b/Task/Munching-squares/Jq/munching-squares-4.jq similarity index 100% rename from Task/Munching-squares/jq/munching-squares-4.jq rename to Task/Munching-squares/Jq/munching-squares-4.jq diff --git a/Task/Munching-squares/jq/munching-squares-5.jq b/Task/Munching-squares/Jq/munching-squares-5.jq similarity index 100% rename from Task/Munching-squares/jq/munching-squares-5.jq rename to Task/Munching-squares/Jq/munching-squares-5.jq diff --git a/Task/Munching-squares/Lua/munching-squares.lua b/Task/Munching-squares/Lua/munching-squares.lua new file mode 100644 index 0000000000..93e6a8ed6f --- /dev/null +++ b/Task/Munching-squares/Lua/munching-squares.lua @@ -0,0 +1,27 @@ +local clr = {} +function drawMSquares() + local pts = {} + for j = 0, hei - 1 do + for i = 0, wid - 1 do + idx = bit.bxor( i, j ) % 256 + pts[1] = { i, j, clr[idx][1], clr[idx][2], clr[idx][3], 255 } + love.graphics.points( pts ) + end + end +end +function createPalette() + for i = 0, 255 do + clr[i] = { bit.band( i * 2.8, 255 ), bit.band( i * 3.2, 255 ), bit.band( i * 1.5, 255 ) } + end +end +function love.load() + wid, hei = love.graphics.getWidth(), love.graphics.getHeight() + canvas = love.graphics.newCanvas( wid, hei ) + love.graphics.setCanvas( canvas ); love.graphics.clear() + love.graphics.setColor( 255, 255, 255 ) + createPalette(); drawMSquares(); + love.graphics.setCanvas() +end +function love.draw() + love.graphics.draw( canvas ) +end diff --git a/Task/Munching-squares/Perl-6/munching-squares-1.pl6 b/Task/Munching-squares/Perl-6/munching-squares-1.pl6 index 9e28bce049..297b951179 100644 --- a/Task/Munching-squares/Perl-6/munching-squares-1.pl6 +++ b/Task/Munching-squares/Perl-6/munching-squares-1.pl6 @@ -1,4 +1,4 @@ -my $ppm = open("munching.ppm", :w, :bin) or +my $ppm = open("munching.ppm", :w) or die "Can't create munching.ppm: $!"; $ppm.print(q :to 'EOT'); diff --git a/Task/Munching-squares/Perl-6/munching-squares-2.pl6 b/Task/Munching-squares/Perl-6/munching-squares-2.pl6 index 36f7da2256..54a23e89a0 100644 --- a/Task/Munching-squares/Perl-6/munching-squares-2.pl6 +++ b/Task/Munching-squares/Perl-6/munching-squares-2.pl6 @@ -5,7 +5,7 @@ my @colors = map -> $r, $g, $b { Buf.new: $r, $g, $b }, flat (0,2...254),(254,252...0)); -my $PPM = open "munching.ppm", :w, :bin or die "Can't create munching.ppm: $!"; +my $PPM = open "munching.ppm", :w or die "Can't create munching.ppm: $!"; $PPM.print: qq:to/EOH/; P6 diff --git a/Task/Munching-squares/Rust/munching-squares.rust b/Task/Munching-squares/Rust/munching-squares.rust new file mode 100644 index 0000000000..9d381d08ec --- /dev/null +++ b/Task/Munching-squares/Rust/munching-squares.rust @@ -0,0 +1,16 @@ +extern crate image; + +use image::{ImageBuffer, Pixel, Rgb}; + +fn main() { + let mut img = ImageBuffer::new(256, 256); + + for x in 0..256 { + for y in 0..256 { + let pixel = Rgb::from_channels(0, x as u8 ^ y as u8, 0, 0); + img.put_pixel(x, y, pixel); + } + } + + let _ = img.save("output.png"); +} diff --git a/Task/Munching-squares/Sidef/munching-squares.sidef b/Task/Munching-squares/Sidef/munching-squares.sidef index ca416b6801..44d500a598 100644 --- a/Task/Munching-squares/Sidef/munching-squares.sidef +++ b/Task/Munching-squares/Sidef/munching-squares.sidef @@ -1,10 +1,10 @@ -require('GD') +require('Imager') -var img = %s.new(256, 256, 1) +var img = %O.new(xsize => 256, ysize => 256) -for y,x in (^256 ~X ^256) { - var color = img.colorAllocate((255 - x - y).abs, (255-x)^y, x^(255-y)) - img.setPixel(x, y, color) +for x,y in (^256 ~X ^256) { + var rgb = [(255 - x - y).abs, (255-x)^y, x^(255-y)] + img.setpixel(x => x, y => y, color => rgb) } -File('xor.png').write(img.png, :raw) +img.write(file => 'xor.png') diff --git a/Task/Munching-squares/Zkl/munching-squares-1.zkl b/Task/Munching-squares/Zkl/munching-squares-1.zkl new file mode 100644 index 0000000000..a8afa7363f --- /dev/null +++ b/Task/Munching-squares/Zkl/munching-squares-1.zkl @@ -0,0 +1,12 @@ +fcn muncher{ + bitmap:=PPM(256,256); + coolness:=(1).random(0x10000); // 55379, 18180, 40, 51950, 57619, 43514, 65465 + foreach y,x in ([0 .. 255],[0 .. 255]){ + b:=x.bitXor(y); // shades of blue +// rgb:=b*coolness; // kaleidoscopic image +// rgb:=(b*coolness + b)*coolness + b; // more coolness + rgb:=(b*0x10000 + b)*0x10000 + b; // copy ADA image + bitmap[x,y]=rgb; + } + bitmap.write(File("foo.ppm","wb")); +}(); diff --git a/Task/Munching-squares/Zkl/munching-squares-2.zkl b/Task/Munching-squares/Zkl/munching-squares-2.zkl new file mode 100644 index 0000000000..206109bbb0 --- /dev/null +++ b/Task/Munching-squares/Zkl/munching-squares-2.zkl @@ -0,0 +1 @@ +while(1){ muncher(); Atomic.sleep(3); } diff --git a/Task/Mutual-recursion/BaCon/mutual-recursion.bacon b/Task/Mutual-recursion/BaCon/mutual-recursion.bacon new file mode 100644 index 0000000000..63874d4af6 --- /dev/null +++ b/Task/Mutual-recursion/BaCon/mutual-recursion.bacon @@ -0,0 +1,21 @@ +' Mutually recursive +FUNCTION F(int n) TYPE int + RETURN IIF(n = 0, 1, n - M(F(n -1))) +END FUNCTION + +FUNCTION M(int n) TYPE int + RETURN IIF(n = 0, 0, n - F(M(n - 1))) +END FUNCTION + +' Get iteration limit, default 20 +SPLIT ARGUMENT$ BY " " TO arg$ SIZE args +limit = IIF(args > 1, VAL(arg$[1]), 20) + +FOR i = 0 TO limit + PRINT F(i) FORMAT "%2d " +NEXT +PRINT +FOR i = 0 TO limit + PRINT M(i) FORMAT "%2d " +NEXT +PRINT diff --git a/Task/Mutual-recursion/Io/mutual-recursion.io b/Task/Mutual-recursion/Io/mutual-recursion.io new file mode 100644 index 0000000000..665de794e2 --- /dev/null +++ b/Task/Mutual-recursion/Io/mutual-recursion.io @@ -0,0 +1,6 @@ +f := method(n, if( n == 0, 1, n - m(f(n-1)))) +m := method(n, if( n == 0, 0, n - f(m(n-1)))) + +Range +0 to(19) map(n,f(n)) println +0 to(19) map(n,m(n)) println diff --git a/Task/Mutual-recursion/Jq/mutual-recursion-1.jq b/Task/Mutual-recursion/Jq/mutual-recursion-1.jq new file mode 100644 index 0000000000..6d5b991c4d --- /dev/null +++ b/Task/Mutual-recursion/Jq/mutual-recursion-1.jq @@ -0,0 +1,6 @@ +def M: + def F: if . == 0 then 1 else . - ((. - 1) | F | M) end; + if . == 0 then 0 else . - ((. - 1) | M | F) end; + +def F: + if . == 0 then 1 else . - ((. - 1) | F | M) end; diff --git a/Task/Mutual-recursion/jq/mutual-recursion-2.jq b/Task/Mutual-recursion/Jq/mutual-recursion-2.jq similarity index 100% rename from Task/Mutual-recursion/jq/mutual-recursion-2.jq rename to Task/Mutual-recursion/Jq/mutual-recursion-2.jq diff --git a/Task/Mutual-recursion/jq/mutual-recursion-3.jq b/Task/Mutual-recursion/Jq/mutual-recursion-3.jq similarity index 100% rename from Task/Mutual-recursion/jq/mutual-recursion-3.jq rename to Task/Mutual-recursion/Jq/mutual-recursion-3.jq diff --git a/Task/Mutual-recursion/Kotlin/mutual-recursion.kotlin b/Task/Mutual-recursion/Kotlin/mutual-recursion.kotlin new file mode 100644 index 0000000000..00dc67b757 --- /dev/null +++ b/Task/Mutual-recursion/Kotlin/mutual-recursion.kotlin @@ -0,0 +1,27 @@ +// version 1.0.6 + +fun f(n: Int): Int = + when { + n == 0 -> 1 + else -> n - m(f(n - 1)) + } + +fun m(n: Int): Int = + when { + n == 0 -> 0 + else -> n - f(m(n - 1)) + } + +fun main(args: Array) { + val n = 24 + print("n :") + for (i in 0..n) print("%3d".format(i)) + println() + println("-".repeat(78)) + print("F :") + for (i in 0..24) print("%3d".format(f(i))) + println() + print("M :") + for (i in 0..24) print("%3d".format(m(i))) + println() +} diff --git a/Task/Mutual-recursion/SPL/mutual-recursion.spl b/Task/Mutual-recursion/SPL/mutual-recursion.spl new file mode 100644 index 0000000000..272469cdbe --- /dev/null +++ b/Task/Mutual-recursion/SPL/mutual-recursion.spl @@ -0,0 +1,14 @@ +f(n)= + ? n=0, <= 1 + <= n-m(f(n-1)) +. +m(n)= + ? n=0, <= 0 + <= n-f(m(n-1)) +. +> i, 0..20 + fs += " "+f(i) + ms += " "+m(i) +< +#.output("F:",fs) +#.output("M:",ms) diff --git a/Task/Mutual-recursion/Sidef/mutual-recursion.sidef b/Task/Mutual-recursion/Sidef/mutual-recursion.sidef index 13f361449e..ecf9410304 100644 --- a/Task/Mutual-recursion/Sidef/mutual-recursion.sidef +++ b/Task/Mutual-recursion/Sidef/mutual-recursion.sidef @@ -1,9 +1,9 @@ -func F(){}; -func M(){}; - -F = func(n) { n > 0 ? (n - M(F(n-1))) : 1 }; -M = func(n) { n > 0 ? (n - F(M(n-1))) : 0 }; - +func F(){} +func M(){} +  +F = func(n) { n > 0 ? (n - M(F(n-1))) : 1 } +M = func(n) { n > 0 ? (n - F(M(n-1))) : 0 } +  [F, M].each { |seq| - (0..19).map {|i| seq.call(i)}.join(' ').say; + {|i| seq.call(i)}.map(^20).join(' ').say } diff --git a/Task/Mutual-recursion/X86-Assembly/mutual-recursion.x86 b/Task/Mutual-recursion/X86-Assembly/mutual-recursion.x86 new file mode 100644 index 0000000000..4589061c09 --- /dev/null +++ b/Task/Mutual-recursion/X86-Assembly/mutual-recursion.x86 @@ -0,0 +1,82 @@ + global main + extern printf + + section .text + +func_f + mov eax, [esp+4] + cmp eax, 0 + jz f_ret + dec eax + push eax + call func_f + mov [esp+0], eax + call func_m + add esp, 4 + mov ebx, [esp+4] + sub ebx, eax + mov eax, ebx + ret +f_ret + mov eax, 1 + ret + +func_m + mov eax, [esp+4] + cmp eax, 0 + jz m_ret + dec eax + push eax + call func_m + mov [esp+0], eax + call func_f + add esp, 4 + mov ebx, [esp+4] + sub ebx, eax + mov eax, ebx + ret +m_ret + xor eax, eax + ret + +main + mov edx, func_f + call output_res + mov edx, func_m + call output_res + ret + +output_res + xor ecx, ecx +loop0 + push ecx + call edx + + push edx + + push eax + push form + call printf + add esp, 8 + + pop edx + pop ecx + + inc ecx + cmp ecx, 20 + jnz loop0 + + push newline + call printf + add esp, 4 + + ret + + + section .rodata +form + db '%d ',0 +newline + db 10,0 + + end diff --git a/Task/Mutual-recursion/Zkl/mutual-recursion.zkl b/Task/Mutual-recursion/Zkl/mutual-recursion.zkl new file mode 100644 index 0000000000..d597c49995 --- /dev/null +++ b/Task/Mutual-recursion/Zkl/mutual-recursion.zkl @@ -0,0 +1,4 @@ +fcn f(n){ if(n==0)return(1); n-m(f(n-1,m),f) } +fcn m(n){ if(n==0)return(0); n-f(m(n-1,f),m) } +[0..19].apply(f).println(); // or foreach n in ([0..19]){ print(f(n)," ") } +[0..19].apply(m).println(); // or foreach n in ([0..19]){ print(m(n)," ") } diff --git a/Task/Mutual-recursion/jq/mutual-recursion-1.jq b/Task/Mutual-recursion/jq/mutual-recursion-1.jq deleted file mode 100644 index d8bf50bd1a..0000000000 --- a/Task/Mutual-recursion/jq/mutual-recursion-1.jq +++ /dev/null @@ -1,4 +0,0 @@ -def F: 0; # declare required signature - -def M: if . == 0 then 0 else . - ((. - 1) | M | F) end; -def F: if . == 0 then 1 else . - ((. - 1) | F | M) end; diff --git a/Task/N-queens-problem/00DESCRIPTION b/Task/N-queens-problem/00DESCRIPTION index c34ec41525..237c49cfee 100644 --- a/Task/N-queens-problem/00DESCRIPTION +++ b/Task/N-queens-problem/00DESCRIPTION @@ -10,10 +10,12 @@ You can extend the problem to solve the puzzle with a board of size   For the number of solutions for small values of   '''N''',   see   [http://oeis.org/A000170 oeis.org sequence A170]. -;See also: -*   [[Knight's tour]] -*   [[Solve a Hidato puzzle]] -*   [[Solve a Holy Knight's tour]] -*   [[Solve a Numbrix puzzle]] -*   [[Solve a Hopido puzzle]] +;Related tasks: +* [[A* search algorithm]] +* [[Solve a Hidato puzzle]] +* [[Solve a Holy Knight's tour]] +* [[Knight's tour]] +* [[Solve a Hopido puzzle]] +* [[Solve a Numbrix puzzle]] +* [[Solve the no connection puzzle]]

    diff --git a/Task/N-queens-problem/360-Assembly/n-queens-problem.360 b/Task/N-queens-problem/360-Assembly/n-queens-problem.360 index f4518766f2..e040b3602e 100644 --- a/Task/N-queens-problem/360-Assembly/n-queens-problem.360 +++ b/Task/N-queens-problem/360-Assembly/n-queens-problem.360 @@ -1,5 +1,4 @@ * N-QUEENS PROBLEM 04/09/2015 - PRINT NOGEN MACRO &LAB XDECO ®,&TARGET &LAB B I&SYSNDX branch around work area @@ -12,16 +11,21 @@ I&SYSNDX CVD ®,P&SYSNDX convert to decimal MVC 0(1,R1),W&SYSNDX+12 move the sign MVC &TARGET.(12),W&SYSNDX move to target MEND - PRINT NOGEN NQUEENS CSECT SAVE (14,12) save registers on entry - PRINT NOGEN BALR R12,0 establish addressability USING *,R12 set base register ST R13,SAVEA+4 link mySA->prevSA LA R11,SAVEA mySA ST R11,8(R13) link prevSA->mySA LR R13,R11 set mySA pointer + LA R7,LL l + LA R6,1 i=1 +LOOPI LR R1,R6 do i=1 to l + SLA R1,1 i*2 + STH R6,A-2(R1) a(i)=i + LA R6,1(R6) i=i+1 + BCT R7,LOOPI loop do i OPENEM OPEN (OUTDCB,OUTPUT) open the printer file LA R9,1 n=1 start of loop LOOPN CH R9,L do n=1 to l @@ -126,13 +130,13 @@ ELOOPN CLOSE (OUTDCB) close output LTORG SAVEA DS 18F save area for chaining OUTDCB DCB DSORG=PS,MACRF=PM,DDNAME=OUTDD use OUTDD in jcl -L DC H'13' input value -A DC H'01',H'02',H'03',H'04',H'05',H'06' - DC H'07',H'08',H'09',H'10',H'11',H'12' -U DC 46H'0' -S DS 12H +LL EQU 14 ll<=16 +L DC AL2(LL) input value +A DS (LL)H +S DS (LL)H Z DS H Y DS H PG DS CL24 buffer - REGS make sure to incld copybook jcl +U DC (4*LL-2)H'0' stack + REGS make sure to include copybook jcl END NQUEENS diff --git a/Task/N-queens-problem/AppleScript/n-queens-problem.applescript b/Task/N-queens-problem/AppleScript/n-queens-problem.applescript index d314720587..386d0d0231 100644 --- a/Task/N-queens-problem/AppleScript/n-queens-problem.applescript +++ b/Task/N-queens-problem/AppleScript/n-queens-problem.applescript @@ -9,146 +9,156 @@ property Test_Count : 0 property Rotated : {} on run - local diff - local endTime - local msg - local rows - local startTime - - set Patterns to {} - set Solutions to {} - set Rotated to {} - - set Test_Count to 0 - - set rows to Make_Empty_List(Grid_Size) - - set startTime to current date - Solve(1, rows) - set endTime to current date - set diff to endTime - startTime - - set msg to ("Found " & (count Solutions) & " solutions with " & (count Patterns) & " patterns in " & diff & " seconds.") as text - display alert msg + local diff + local endTime + local msg + local rows + local startTime + + set Patterns to {} + set Solutions to {} + set Rotated to {} + + set Test_Count to 0 + + set rows to Make_Empty_List(Grid_Size) + + set startTime to current date + Solve(1, rows) + set endTime to current date + set diff to endTime - startTime + + set msg to ("Found " & (count Solutions) & " solutions with " & (count Patterns) & " patterns in " & diff & " seconds.") as text + display alert msg + + return Solutions end run on Solve(row as integer, rows as list) - if row is greater than (count rows) then - Append_Solution(rows) - return - end if - - repeat with column from 1 to Grid_Size - set Test_Count to Test_Count + 1 - if Place_Queen(column, row, rows) then - Solve(row + 1, rows) - end if - end repeat + if row is greater than (count rows) then + Append_Solution(rows) + return + end if + + repeat with column from 1 to Grid_Size + set Test_Count to Test_Count + 1 + if Place_Queen(column, row, rows) then + Solve(row + 1, rows) + end if + end repeat end Solve +on abs(n) + if n < 0 then + -n + else + n + end if +end abs + on Place_Queen(column as integer, row as integer, rows as list) - local colDiff - local previousRow - local rowDiff - local testColumn - - repeat with previousRow from 1 to (row - 1) - set testColumn to item previousRow of rows - - if testColumn is equal to column then - return false - end if - - set colDiff to abs (testColumn - column) as integer - set rowDiff to row - previousRow - if colDiff is equal to rowDiff then - return false - end if - end repeat - - set item row of rows to column - return true + local colDiff + local previousRow + local rowDiff + local testColumn + + repeat with previousRow from 1 to (row - 1) + set testColumn to item previousRow of rows + + if testColumn is equal to column then + return false + end if + + set colDiff to abs(testColumn - column) as integer + set rowDiff to row - previousRow + if colDiff is equal to rowDiff then + return false + end if + end repeat + + set item row of rows to column + return true end Place_Queen on Append_Solution(rows as list) - local column - local rowsCopy - local testReflection - local testReflectionText - local testRotation - local testRotationText - local testRotations - - copy rows to rowsCopy - set end of Solutions to rowsCopy - local rowsCopy - - copy rows to testRotation - set testRotations to {} - repeat 3 times - set testRotation to Rotate(testRotation) - set testRotationText to testRotation as text - if Rotated contains testRotationText then - return - end if - set end of testRotations to testRotationText - - set testReflection to Reflect(testRotation) - set testReflectionText to testReflection as text - if Rotated contains testReflectionText then - return - end if - set end of testRotations to testReflectionText - end repeat - - repeat with testRotationText in testRotations - set end of Rotated to (contents of testRotationText) - end repeat - set end of Rotated to (rowsCopy as text) - set end of Rotated to (Reflect(rowsCopy) as text) - - set end of Patterns to rowsCopy + local column + local rowsCopy + local testReflection + local testReflectionText + local testRotation + local testRotationText + local testRotations + + copy rows to rowsCopy + set end of Solutions to rowsCopy + local rowsCopy + + copy rows to testRotation + set testRotations to {} + repeat 3 times + set testRotation to Rotate(testRotation) + set testRotationText to testRotation as text + if Rotated contains testRotationText then + return + end if + set end of testRotations to testRotationText + + set testReflection to Reflect(testRotation) + set testReflectionText to testReflection as text + if Rotated contains testReflectionText then + return + end if + set end of testRotations to testReflectionText + end repeat + + repeat with testRotationText in testRotations + set end of Rotated to (contents of testRotationText) + end repeat + set end of Rotated to (rowsCopy as text) + set end of Rotated to (Reflect(rowsCopy) as text) + + set end of Patterns to rowsCopy end Append_Solution on Make_Empty_List(depth as integer) - local i - local emptyList - - set emptyList to {} - repeat with i from 1 to depth - set end of emptyList to missing value - end repeat - return emptyList + local i + local emptyList + + set emptyList to {} + repeat with i from 1 to depth + set end of emptyList to missing value + end repeat + return emptyList end Make_Empty_List on Rotate(rows as list) - local column - local newColumn - local newRow - local newRows - local row - local rowCount - - set rowCount to (count rows) - set newRows to Make_Empty_List(rowCount) - repeat with row from 1 to rowCount - set column to (contents of item row of rows) - set newRow to column - set newColumn to rowCount - row + 1 - set item newRow of newRows to newColumn - end repeat - - return newRows + local column + local newColumn + local newRow + local newRows + local row + local rowCount + + set rowCount to (count rows) + set newRows to Make_Empty_List(rowCount) + repeat with row from 1 to rowCount + set column to (contents of item row of rows) + set newRow to column + set newColumn to rowCount - row + 1 + set item newRow of newRows to newColumn + end repeat + + return newRows end Rotate on Reflect(rows as list) - local column - local newRows - - set newRows to {} - repeat with column in rows - set end of newRows to (count rows) - column + 1 - end repeat - - return newRows + local column + local newRows + + set newRows to {} + repeat with column in rows + set end of newRows to (count rows) - column + 1 + end repeat + + return newRows end Reflect diff --git a/Task/N-queens-problem/F-Sharp/n-queens-problem-1.fs b/Task/N-queens-problem/F-Sharp/n-queens-problem-1.fs new file mode 100644 index 0000000000..6ea904fb65 --- /dev/null +++ b/Task/N-queens-problem/F-Sharp/n-queens-problem-1.fs @@ -0,0 +1,42 @@ +let rec iterate f value = seq { + yield value + yield! iterate f (f value) } + +let up i = i + 1 +let right i = i +let down i = i - 1 + +let noCollisionGivenDir solution number dir = + Seq.forall2 (<>) solution (Seq.skip 1 (iterate dir number)) + +let goodAddition solution number = + List.forall (noCollisionGivenDir solution number) [ up; right; down ] + +let rec extendSolution n ps = + [0..n - 1] + |> List.filter (goodAddition ps) + |> List.map (fun num -> num :: ps) + +let allSolutions n = + iterate (List.collect (extendSolution n)) [[]] + +// Print one solution for the 8x8 case +let printOneSolution () = + allSolutions 8 + |> Seq.item 8 + |> Seq.head + |> List.iter (fun rowIndex -> + printf "|" + [0..8] |> List.iter (fun i -> printf (if i = rowIndex then "X|" else " |")) + printfn "") + +// Print number of solution for the other cases +let printNumberOfSolutions () = + printfn "Size\tNr of solutions" + [1..11] + |> List.map ((fun i -> Seq.item i (allSolutions i)) >> List.length) + |> List.iteri (fun i cnt -> printfn "%d\t%d" (i+1) cnt) + +printOneSolution() + +printNumberOfSolutions() diff --git a/Task/N-queens-problem/F-Sharp/n-queens-problem-2.fs b/Task/N-queens-problem/F-Sharp/n-queens-problem-2.fs new file mode 100644 index 0000000000..cd060236c1 --- /dev/null +++ b/Task/N-queens-problem/F-Sharp/n-queens-problem-2.fs @@ -0,0 +1,21 @@ +| | | |X| | | | | | +| |X| | | | | | | | +| | | | | | |X| | | +| | |X| | | | | | | +| | | | | |X| | | | +| | | | | | | |X| | +| | | | |X| | | | | +|X| | | | | | | | | + +Size Nr of solutions +1 1 +2 0 +3 0 +4 2 +5 10 +6 4 +7 40 +8 92 +9 352 +10 724 +11 2680 diff --git a/Task/N-queens-problem/FreeBASIC/n-queens-problem.freebasic b/Task/N-queens-problem/FreeBASIC/n-queens-problem.freebasic new file mode 100644 index 0000000000..4405ff1f11 --- /dev/null +++ b/Task/N-queens-problem/FreeBASIC/n-queens-problem.freebasic @@ -0,0 +1,56 @@ +' version 13-04-2017 +' compile with: fbc -s console +Dim Shared As ULong count, c() + +Sub n_queens(row As ULong, n As ULong, show As ULong = 0) + + Dim As ULong x, y + + For x = 1 To n + + For y = 1 To row -1 + If c(y) = x OrElse ((row - y) - Abs(x - c(y))) = 0 Then + Continue For, For + End If + Next + + c(row) = x + If row < n Then + n_queens(row +1 , n, show) + Else + count += 1 + + If show <> 0 Then + For y = 1 To n + Print Using "###"; c(y); + Next + Print + End If + + End If + + Next + +End Sub + +' ------=< MAIN >=------ + +Dim As ULong n = 5 +ReDim c(n) +' n_queens(1, n, show = 0 only show total | show <> 0 show every solution +n_queens(1, n, 1) +Print Using "## x ## board, ##### solutions"; n; n; count +Print + +For n = 1 To 14 + ReDim c(n) + count = 0 + n_queens(1, n) + Print Using "A ## x ## board has ######## solutions"; n; n; count +Next + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/N-queens-problem/Haskell/n-queens-problem-4.hs b/Task/N-queens-problem/Haskell/n-queens-problem-4.hs new file mode 100644 index 0000000000..56858b80cb --- /dev/null +++ b/Task/N-queens-problem/Haskell/n-queens-problem-4.hs @@ -0,0 +1,50 @@ +import Data.List (transpose, intercalate) + +queenPuzzle :: Int -> Int -> [[Int]] +queenPuzzle nRows nCols + | nRows <= 0 = [[]] + | otherwise = + foldr + (\solution a -> + a ++ + foldr + (\iCol b -> + if safe (nRows - 1) iCol solution + then b ++ [solution ++ [iCol]] + else b) + [] + [1 .. nCols]) + [] + (queenPuzzle (nRows - 1) nCols) + where + safe iRow iCol solution = + True `notElem` + zipWith + (\sc sr -> + (iCol == sc) || (sc + sr == iCol + iRow) || (sc - sr == iCol - iRow)) + solution + [0 .. iRow - 1] + +-- TEST ------------------------------------------------------------------------ +-- 10 columns of solutions for the 7*7 board: +showSolutions :: Int -> Int -> [String] +showSolutions nCols nBoardSize = + unlines <$> + (((intercalate " " <$>) . transpose . (boardLines <$>)) <$> + chunksOf nCols (queenPuzzle nBoardSize nBoardSize)) + where + boardLines rows = + (\r -> foldMap (\c -> if_ (c == r) "♛" ".") [1 .. (length rows)]) <$> rows + +chunksOf :: Int -> [a] -> [[a]] +chunksOf i xs = take i <$> ($ (:)) (splits xs) [] + where + splits [] _ n = [] + splits l c n = l `c` splits (drop i l) c n + +if_ :: Bool -> a -> a -> a +if_ True x _ = x +if_ False _ y = y + +main :: IO () +main = mapM_ putStrLn $ showSolutions 10 7 diff --git a/Task/N-queens-problem/JavaScript/n-queens-problem-1.js b/Task/N-queens-problem/JavaScript/n-queens-problem-1.js new file mode 100644 index 0000000000..a97ed0902d --- /dev/null +++ b/Task/N-queens-problem/JavaScript/n-queens-problem-1.js @@ -0,0 +1,33 @@ +function queenPuzzle(rows, columns) { + if (rows <= 0) { + return [[]]; + } else { + return addQueen(rows - 1, columns); + } +} + +function addQueen(newRow, columns, prevSolution) { + var newSolutions = []; + var prev = queenPuzzle(newRow, columns); + for (var i = 0; i < prev.length; i++) { + var solution = prev[i]; + for (var newColumn = 0; newColumn < columns; newColumn++) { + if (!hasConflict(newRow, newColumn, solution)) + newSolutions.push(solution.concat([newColumn])) + } + } + return newSolutions; +} + +function hasConflict(newRow, newColumn, solution) { + for (var i = 0; i < newRow; i++) { + if (solution[i] == newColumn || + solution[i] + i == newColumn + newRow || + solution[i] - i == newColumn - newRow) { + return true; + } + } + return false; +} + +console.log(queenPuzzle(8,8)); diff --git a/Task/N-queens-problem/JavaScript/n-queens-problem-2.js b/Task/N-queens-problem/JavaScript/n-queens-problem-2.js new file mode 100644 index 0000000000..992a4bcc79 --- /dev/null +++ b/Task/N-queens-problem/JavaScript/n-queens-problem-2.js @@ -0,0 +1,101 @@ +(() => { + 'use strict'; + + // N QUEENS PROBLEM ------------------------------------------------------ + + // queenPuzzle :: Int -> Int -> [[Int]] + const queenPuzzle = (nRows, nCols) => + nRows <= 0 ? [ + [] + ] : queenPuzzle(nRows - 1, nCols) + .reduce((a, solution) => + append(a, enumFromTo(0, nCols - 1) + .reduce((b, iCol) => + safe(nRows - 1, iCol, solution) ? ( + b.concat([solution.concat(iCol)]) + ) : b, []) + ), []); + + // safe : Int -> Int -> [Int] -> Bool + const safe = (iRow, iCol, solution) => !any( + ([sc, sr]) => + (iCol === sc) || (sc + sr === iCol + iRow) || (sc - sr === iCol - iRow), + zip(solution, enumFromTo(0, iRow - 1)) + ); + + // GENERIC FUNCTIONS ----------------------------------------------------- + + // abs :: Num a => a -> a + const abs = Math.abs + + // any :: (a -> Bool) -> [a] -> Bool + const any = (f, xs) => xs.some(f); + + // (++) :: [a] -> [a] -> [a] + const append = (xs, ys) => xs.concat(ys); + + // chunksOf :: Int -> [a] -> [[a]] + const chunksOf = (n, xs) => + xs.reduce((a, _, i, xs) => + i % n ? a : a.concat([xs.slice(i, i + n)]), []); + + // concat :: [[a]] -> [a] | [String] -> String + const concat = xs => { + if (xs.length > 0) { + const unit = typeof xs[0] === 'string' ? '' : []; + return unit.concat.apply(unit, xs); + } else return []; + }; + + // concatMap :: (a -> [b]) -> [a] -> [b] + const concatMap = (f, xs) => [].concat.apply([], xs.map(f)); + + // 2 or more arguments + // curry :: Function -> Function + const curry = (f, ...args) => { + const go = xs => xs.length >= f.length ? (f.apply(null, xs)) : + function () { + return go(xs.concat([].slice.apply(arguments))); + }; + return go([].slice.call(args, 1)); + }; + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // intercalate :: String -> [a] -> String + const intercalate = curry((s, xs) => xs.join(s)); + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f) + + // transpose :: [[a]] -> [[a]] + const transpose = xs => + xs[0].map((_, iCol) => xs.map(row => row[iCol])); + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + // zip :: [a] -> [b] -> [(a,b)] + const zip = (xs, ys) => + xs.slice(0, Math.min(xs.length, ys.length)) + .map((x, i) => [x, ys[i]]); + + // TEST ------------------------------------------------------------------ + // Ten columns of solutions to the 7*7 board + + // showSolutions :: Int -> Int -> String + const showSolutions = (nCols, nBoardSize) => + intercalate('\n\n', map(unlines, + map(col => map(intercalate(" "), transpose(map(rows => + map(r => concat(concatMap(c => + c === r ? '♛' : '.', + enumFromTo(1, rows.length))), rows), col))), + chunksOf(nCols, queenPuzzle(nBoardSize, nBoardSize)) + ))); + + return showSolutions(10, 7); +})(); diff --git a/Task/N-queens-problem/jq/n-queens-problem-1.jq b/Task/N-queens-problem/Jq/n-queens-problem-1.jq similarity index 100% rename from Task/N-queens-problem/jq/n-queens-problem-1.jq rename to Task/N-queens-problem/Jq/n-queens-problem-1.jq diff --git a/Task/N-queens-problem/jq/n-queens-problem-2.jq b/Task/N-queens-problem/Jq/n-queens-problem-2.jq similarity index 100% rename from Task/N-queens-problem/jq/n-queens-problem-2.jq rename to Task/N-queens-problem/Jq/n-queens-problem-2.jq diff --git a/Task/N-queens-problem/jq/n-queens-problem-3.jq b/Task/N-queens-problem/Jq/n-queens-problem-3.jq similarity index 100% rename from Task/N-queens-problem/jq/n-queens-problem-3.jq rename to Task/N-queens-problem/Jq/n-queens-problem-3.jq diff --git a/Task/N-queens-problem/jq/n-queens-problem-4.jq b/Task/N-queens-problem/Jq/n-queens-problem-4.jq similarity index 100% rename from Task/N-queens-problem/jq/n-queens-problem-4.jq rename to Task/N-queens-problem/Jq/n-queens-problem-4.jq diff --git a/Task/N-queens-problem/jq/n-queens-problem-5.jq b/Task/N-queens-problem/Jq/n-queens-problem-5.jq similarity index 100% rename from Task/N-queens-problem/jq/n-queens-problem-5.jq rename to Task/N-queens-problem/Jq/n-queens-problem-5.jq diff --git a/Task/N-queens-problem/Kotlin/n-queens-problem.kotlin b/Task/N-queens-problem/Kotlin/n-queens-problem.kotlin new file mode 100644 index 0000000000..39fb8e6292 --- /dev/null +++ b/Task/N-queens-problem/Kotlin/n-queens-problem.kotlin @@ -0,0 +1,30 @@ +// version 1.1.3 + +var count = 0 +var c = IntArray(0) +var f = "" + +fun nQueens(row: Int, n: Int) { + outer@ for (x in 1..n) { + for (y in 1..row - 1) { + if (c[y] == x) continue@outer + if (row - y == Math.abs(x - c[y])) continue@outer + } + c[row] = x + if (row < n) nQueens(row + 1, n) + else if (++count == 1) f = c.drop(1).map { it - 1 }.toString() + } +} + +fun main(args: Array) { + for (n in 1..14) { + count = 0 + c = IntArray(n + 1) + f = "" + nQueens(1, n) + println("For a $n x $n board:") + println(" Solutions = $count") + if (count > 0) println(" First is $f") + println() + } +} diff --git a/Task/N-queens-problem/Phix/n-queens-problem.phix b/Task/N-queens-problem/Phix/n-queens-problem.phix new file mode 100644 index 0000000000..e563dd2ec5 --- /dev/null +++ b/Task/N-queens-problem/Phix/n-queens-problem.phix @@ -0,0 +1,54 @@ +-- +-- demo\rosetta\n_queens.exw +-- ========================= +-- +sequence co, -- columns occupied + -- (ro is implicit) + fd, -- forward diagonals + bd, -- backward diagonals + board + +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] = 1 + fd[fdi] = 1 + bd[bdi] = 1 + 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] = 0 + fd[fdi] = 0 + bd[bdi] = 0 + end if + end if + end for +end procedure + +procedure n_queens(integer N=8, integer show=1) + co = repeat(0,N) + fd = repeat(0,N*2-1) + bd = repeat(0,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 14 do + n_queens(N,N<5) +end for diff --git a/Task/N-queens-problem/Pure/n-queens-problem.pure b/Task/N-queens-problem/Pure/n-queens-problem.pure new file mode 100644 index 0000000000..b20ace0f59 --- /dev/null +++ b/Task/N-queens-problem/Pure/n-queens-problem.pure @@ -0,0 +1,19 @@ +/* + n-queens.pure + Tectonics: + pure -c queens.pure -o queens + or + pure -q -i queens.pure +*/ +using system; + +queens n = search n 1 [] with + search n i p = [reverse p] if i>n; + = cat [search n (i+1) ((i,j):p) | j = 1..n; safe (i,j) p]; + safe (i,j) p = ~any (check (i,j)) p; + check (i1,j1) (i2,j2) + = i1==i2 || j1==j2 || i1+j1==i2+j2 || i1-j1==i2-j2; +end; + +compiling || (puts("queens 4: " + str(queens 4)) $$ + puts("Solutions to queens 7: " + str(#queens 7))); diff --git a/Task/N-queens-problem/REXX/n-queens-problem.rexx b/Task/N-queens-problem/REXX/n-queens-problem.rexx index a02b260e12..d9e37abcff 100644 --- a/Task/N-queens-problem/REXX/n-queens-problem.rexx +++ b/Task/N-queens-problem/REXX/n-queens-problem.rexx @@ -1,49 +1,48 @@ /*REXX program places N queens on an NxN chessboard (the eight queens problem). */ parse arg N . /*obtain optional argument from the CL.*/ if N=='' | N=="," then N=8 /*Not specified: Then use the default.*/ -if N<1 then call noSol /*display a message, the board is bad. */ +if N<1 then signal nOK /*display a message, the board is bad. */ rank=1; file=1; #=0 /*starting rank&file; #≡number queens.*/ @.=0; pad=left('', 9* (N<18)) /*define empty board; set indentation.*/ - - do while #N; rank=rank-1; if rank==0 then call noSol - do j=1 for N; if \@.j.rank then iterate /*occupied?*/ - file=j; @.file.rank=0; #=#-1; file=j+1; leave /*j*/ + file=file+1 /*So, try the next (higher) chess file.*/ + do while file>N; rank=rank-1; if rank==0 then call nOK + do j=1 for N; if \@.j.rank then iterate /*¿ocupado?*/ + @.j.rank=0; #=#-1; file=j+1; leave end /*j*/ end /*while file>N*/ end /*while #(0 to 7).forall(i=>(i+1 to 7). + forall(j=>j-i!=Math.abs(v(i)-v(j)))))){ + println("_"*15) + v.map(i=>println("_|"*i+"Q"+"|_"*(7-i))) +} diff --git a/Task/N-queens-problem/Scheme/n-queens-problem.ss b/Task/N-queens-problem/Scheme/n-queens-problem.ss new file mode 100644 index 0000000000..449b00272b --- /dev/null +++ b/Task/N-queens-problem/Scheme/n-queens-problem.ss @@ -0,0 +1,74 @@ +(import (scheme base) + (scheme write) + (srfi 1)) + +;; return list of solutions to n-queens problem +(define (n-queens n) ; breadth-first solution + (define (place-initial-row) ; puts a queen on each column of row 0 + (list-tabulate n (lambda (col) (list (cons 0 col))))) + (define (place-on-row soln-so-far row) + (define (invalid? col) + (any (lambda (posn) + (or (= col (cdr posn)) ; on same column + (= (abs (- row (car posn))) ; on same diagonal + (abs (- col (cdr posn)))))) + soln-so-far)) + ; + (do ((col 0 (+ 1 col)) + (res '() (if (invalid? col) + res + (cons (cons (cons row col) soln-so-far) + res)))) + ((= col n) res))) + ; + (do ((res (place-initial-row) + (apply append + (map (lambda (soln-so-far) (place-on-row soln-so-far row)) + res))) + (row 1 (+ 1 row))) + ((= row n) res))) + +;; display solutions in 2-d array form +(define (pretty-print solutions n) + (define (posn->index posn) + (+ (* n (cdr posn)) + (car posn))) + (define (pp solution) + (let ((board (make-vector (square n) "."))) + (for-each (lambda (queen) (vector-set! board + (posn->index queen) + "Q")) + solution) + (let loop ((row 0) + (col 0)) + (cond ((= row n) + (newline)) + ((= col n) + (newline) + (loop (+ 1 row) 0)) + (else + (display (vector-ref board (posn->index (cons row col)))) + (loop row (+ 1 col))))))) + ; + (display (string-append "Found " + (number->string (length solutions)) + " solutions for n=" + (number->string n) + "\n\n")) + (for-each pp solutions)) + +;; create table of number of solutions +(do ((n 1 (+ 1 n))) + ((> n 10) ) + (display n) + (display " ") + (display (length (n-queens n))) + (newline)) + +;; show some examples +(pretty-print (n-queens 1) 1) +(pretty-print (n-queens 2) 2) +(pretty-print (n-queens 3) 3) +(pretty-print (n-queens 4) 4) +(pretty-print (n-queens 5) 5) +(pretty-print (n-queens 8) 8) diff --git a/Task/N-queens-problem/Scilab/n-queens-problem.scilab b/Task/N-queens-problem/Scilab/n-queens-problem.scilab new file mode 100644 index 0000000000..45b8b663be --- /dev/null +++ b/Task/N-queens-problem/Scilab/n-queens-problem.scilab @@ -0,0 +1,142 @@ +//Length of board side +Board_size = 8; + +function flag_out = no_attack(side, board, pos) + //Evaluates (pos(1),pos(2)) in board if it's not on any queen attacking range + //side (scalar): board's side length + //board (sidexside matrix): matrix of 0s and 1s representing queens on a board + //pos (1x2 matrix): postition on board to be evaluated + //flag_out (bool): %T if position is available, and %F otherwise + + //Counting queens on rows and columns + row_col = sum(board(pos(1),:)) + sum(board(:,pos(2))); + + //Counting queens on first diagonal + diag_1 = sum(... + diag(board, 0 +... + (pos(2)>pos(1))*(pos(2)-pos(1)) +... + (pos(1)>pos(2))*(pos(2)-pos(1))... + )... + ); + + //Counting queens on second diagonal + a = pos(1) + pos(2); + if a<=side+1 then + rows = [1:a-1] + cols = a - rows; + else + d = 2*(side+1)-a-1; + rows = [side:-1:side-d+1] + cols = a - rows; + end + + diag_2 = 0; + for i = 1:length(rows) + diag_2 = diag_2 + board(rows(i),cols(i)); + end + + //Check if there's any queen + flag_out = ( ~(row_col | diag_1 | diag_2) ); +endfunction + +//Solution counter +Sol_count = 0; + +//"Soltion found" flag +Sol_found = %F; + +//Empty board +Board = zeros(Board_size,Board_size); + +//Matrix for backtracking +Queens= zeros(Board_size,2); + +//Queens counter +N_queens = Board_size; + +//Row and column counters +i = 1; j = 1; + +//Start counting time +tic(); + +//Begin search +while i <= Board_size + while j <= Board_size + //Availability flag: check position (i,j) + flag = %F; + if (0 < i & 0 < j) & (i <= Board_size & j <= Board_size) then + flag = no_attack(Board_size,Board,[i j]); + end + + //Reset solution flag + Sol_found = %F; + + if flag then + //Put a queen on the board if position is available + Board(i,j) = 1; + + //Update number of remaining queens + N_queens = N_queens - 1; + + //Keep track of queens positions + Queens(Board_size - N_queens,:) = [i j]; + + //Jump to next row end of line is reached + if i+1<=Board_size + i = i + 1; + end + //Start over from the begining of new line + j = 0; + + //Count and flag a solution if all queens have + //been placed on the board + if N_queens == 0 then + Sol_count = Sol_count + 1; + Sol_found = %T; + break + end + end + + //Increment column number + j = j + 1; + end + + //Increment row number and start from first column + if ~Sol_found then + i = i + 1; + j = 1; + + //Limiting placement of the first queen to the first row + //Stop searching solutions if columns of first row + //have been tested + if i == 2 & j == 1 & sum(Board) == 0 then + break + end + end + + //Backtracking: if (i,j) reaches the and of the board + //and there are queens left to be placed on it + if ~Sol_found & i == Board_size + 1 & j == 1 then + ind = Board_size - N_queens; + if ind > 0 then + //Recover last queen's position + i = Queens(ind,1); + j = Queens(ind,2); + + //Remove it from the board and from the counter + Board(i,j) = 0; + Queens(ind,:) = [0 0]; + N_queens = N_queens + 1; + + //Move to next column + j = j + 1; + end + end +end + +//Printing result on console +disp("There are "+string(Sol_count)+" solutions for a "+... + string(Board_size)+"x"+string(Board_size)+" board."); +//Time elapsed +disp("Time: "+string(toc())+"s."); diff --git a/Task/N-queens-problem/Stata/n-queens-problem-1.stata b/Task/N-queens-problem/Stata/n-queens-problem-1.stata new file mode 100644 index 0000000000..4271153966 --- /dev/null +++ b/Task/N-queens-problem/Stata/n-queens-problem-1.stata @@ -0,0 +1,60 @@ +mata +real matrix queens(real scalar n) { + real scalar i, j, k, p, q + real rowvector a, s, u, v + real matrix m + + m = J(0, n, .) + a = 1..n + s = J(1, n, 0) + u = J(1, 2*n-1, 1) + v = J(1, 2*n-1, 1) + i = j = 1 +L1: k = a[j] + a[j] = a[i] + a[i] = k + p = i-k+n + q = i+k-1 + if (u[p] & v[q]) { + s[i++] = j + u[p] = v[q] = 0 + if (i > n) { + m = m\a + goto L3 + } + j = i + goto L1 + } +L2: if (++j <= n) goto L1 + while (--j > i) { + k = a[i] + a[i] = a[j] + a[j] = k + } +L3: if (--i == 0) return(m) + p = i-a[i]+n + q = i+a[i]-1 + j = s[i] + u[p] = v[q] = 1 + goto L2 +} + +a = queens(8) +e = I(8) +1:/e[a[1,.],.] + 1 2 3 4 5 6 7 8 + +---------------------------------+ + 1 | 1 . . . . . . . | + 2 | . . . . 1 . . . | + 3 | . . . . . . . 1 | + 4 | . . . . . 1 . . | + 5 | . . 1 . . . . . | + 6 | . . . . . . 1 . | + 7 | . 1 . . . . . . | + 8 | . . . 1 . . . . | + +---------------------------------+ + + +rows(a) + 92 +end diff --git a/Task/N-queens-problem/Stata/n-queens-problem-2.stata b/Task/N-queens-problem/Stata/n-queens-problem-2.stata new file mode 100644 index 0000000000..38d2d2dc47 --- /dev/null +++ b/Task/N-queens-problem/Stata/n-queens-problem-2.stata @@ -0,0 +1,4 @@ +clear +mata: a=queens(8) +getmata (a*)=a +save queens, replace diff --git a/Task/N-queens-problem/Stata/n-queens-problem-3.stata b/Task/N-queens-problem/Stata/n-queens-problem-3.stata new file mode 100644 index 0000000000..b7ea6aeb55 --- /dev/null +++ b/Task/N-queens-problem/Stata/n-queens-problem-3.stata @@ -0,0 +1,58 @@ +mata +real matrix queens(real scalar n) { + real rowvector a, u, v + real matrix m + + a = 1..n + u = J(1, 2*n-1, 1) + v = J(1, 2*n-1, 1) + m = J(0, n, .) + queens_aux(n, 1, a, u, v, m) + return(m) +} + +void queens_aux(real scalar n, real scalar i, real rowvector a, + real rowvector u, real rowvector v, real matrix m) { + + real scalar j, k, s + + if (i > n) { + m = m\a + } else { + for (k = i; k <= n; k++) { + j = a[k] + p = i+j-1 + q = i-j+n + if (u[p] & v[q]) { + u[p] = v[q] = 0 + s = a[i] + a[i] = a[k] + a[k] = s + queens_aux(n, i+1, a, u, v, m) + u[p] = v[q] = 1 + s = a[i] + a[i] = a[k] + a[k] = s + } + } + } +} + +a = queens(8) +e = I(8) +1:/e[a[1,.],.] + 1 2 3 4 5 6 7 8 + +---------------------------------+ + 1 | 1 . . . . . . . | + 2 | . . . . 1 . . . | + 3 | . . . . . . . 1 | + 4 | . . . . . 1 . . | + 5 | . . 1 . . . . . | + 6 | . . . . . . 1 . | + 7 | . 1 . . . . . . | + 8 | . . . 1 . . . . | + +---------------------------------+ + +rows(a) + 92 +end diff --git a/Task/N-queens-problem/VBA/n-queens-problem.vba b/Task/N-queens-problem/VBA/n-queens-problem.vba new file mode 100644 index 0000000000..66c3965643 --- /dev/null +++ b/Task/N-queens-problem/VBA/n-queens-problem.vba @@ -0,0 +1,58 @@ +'N-queens problem - non recursive & structured - vba - 26/02/2017 +Sub n_queens() + Const l = 15 'number of queens + Const b = False 'print option + Dim a(l), s(l), u(4 * l - 2) + Dim n, m, i, j, p, q, r, k, t, z + For i = 1 To UBound(a): a(i) = i: Next i + For n = 1 To l + m = 0 + i = 1 + j = 0 + r = 2 * n - 1 + Do + i = i - 1 + j = j + 1 + p = 0 + q = -r + Do + i = i + 1 + u(p) = 1 + u(q + r) = 1 + z = a(j): a(j) = a(i): a(i) = z 'Swap a(i), a(j) + p = i - a(i) + n + q = i + a(i) - 1 + s(i) = j + j = i + 1 + Loop Until j > n Or u(p) Or u(q + r) + If u(p) = 0 Then + If u(q + r) = 0 Then + m = m + 1 'm: number of solutions + If b Then + Debug.Print "n="; n; "m="; m + For k = 1 To n + For t = 1 To n + Debug.Print IIf(a(n - k + 1) = t, "Q", "."); + Next t + Debug.Print + Next k + End If + End If + End If + j = s(i) + Do While j >= n And i <> 0 + Do + z = a(j): a(j) = a(i): a(i) = z 'Swap a(i), a(j) + j = j - 1 + Loop Until j < i + i = i - 1 + p = i - a(i) + n + q = i + a(i) - 1 + j = s(i) + u(p) = 0 + u(q + r) = 0 + Loop + Loop Until i = 0 + Debug.Print n, m 'number of queens, number of solutions + Next n +End Sub 'n_queens diff --git a/Task/N-queens-problem/VBScript/n-queens-problem.vb b/Task/N-queens-problem/VBScript/n-queens-problem.vb new file mode 100644 index 0000000000..d8c90cf52b --- /dev/null +++ b/Task/N-queens-problem/VBScript/n-queens-problem.vb @@ -0,0 +1,46 @@ +'N-queens problem - non recursive & structured - vbs - 24/02/2017 +const l=15 +dim a(),s(),u(): redim a(l),s(l),u(4*l-2) +for i=1 to l: a(i)=i: next +for n=1 to l + m=0 + i=1 + j=0 + r=2*n-1 + Do + i=i-1 + j=j+1 + p=0 + q=-r + Do + i=i+1 + u(p)=1 + u(q+r)=1 + z=a(j): a(j)=a(i): a(i)=z 'swap a(i),a(j) + p=i-a(i)+n + q=i+a(i)-1 + s(i)=j + j=i+1 + Loop Until j>n Or u(p)<>0 Or u(q+r)<>0 + If u(p)=0 Then + If u(q+r)=0 Then + m=m+1 'm: number of solutions + 'x="": for k=1 to n: x=x&" "&a(k): next: msgbox x,,m + End If + End If + j=s(i) + Do While j>=n And i<>0 + Do + z=a(j): a(j)=a(i): a(i)=z 'swap a(i),a(j) + j=j-1 + Loop Until j n Or u(p) Or u(q + r) + If u(p) = 0 Then + If u(q + r) = 0 Then + m = m + 1 'm: number of solutions + If b Then + Debug.Print("n=" & n & " m=" & m) : w = "" + For k = 1 To n + For t = 1 To n + w = w & If(a(n - k + 1) = t, "Q", ".") + Next t + Debug.Print(w) + Next k + End If + End If + End If + j = s(i) + Do While j >= n And i <> 0 + Do + z = a(j) : a(j) = a(i) : a(i) = z 'Swap a(i), a(j) + j = j - 1 + Loop Until j < i + i = i - 1 + p = i - a(i) + n + q = i + a(i) - 1 + j = s(i) + u(p) = 0 + u(q + r) = 0 + Loop + Loop Until i = 0 + Debug.Print(n & vbTab & m) 'number of queens, number of solutions + Next n + End Sub 'n_queens +End Module diff --git a/Task/N-queens-problem/Visual-Basic/n-queens-problem.vb b/Task/N-queens-problem/Visual-Basic/n-queens-problem.vb new file mode 100644 index 0000000000..6e3677a1db --- /dev/null +++ b/Task/N-queens-problem/Visual-Basic/n-queens-problem.vb @@ -0,0 +1,58 @@ +'N-queens problem - non recursive & structured - vb6 - 25/02/2017 +Sub n_queens() + Const l = 15 'number of queens + Const b = False 'print option + Dim a(l), s(l), u(4 * l - 2) + Dim n, m, i, j, p, q, r, k, t, z + For i = 1 To UBound(a): a(i) = i: Next i + For n = 1 To l + m = 0 + i = 1 + j = 0 + r = 2 * n - 1 + Do + i = i - 1 + j = j + 1 + p = 0 + q = -r + Do + i = i + 1 + u(p) = 1 + u(q + r) = 1 + z = a(j): a(j) = a(i): a(i) = z 'Swap a(i), a(j) + p = i - a(i) + n + q = i + a(i) - 1 + s(i) = j + j = i + 1 + Loop Until j > n Or u(p) Or u(q + r) + If u(p) = 0 Then + If u(q + r) = 0 Then + m = m + 1 'm: number of solutions + If b Then + Debug.Print "n="; n; "m="; m + For k = 1 To n + For t = 1 To n + Debug.Print IIf(a(n - k + 1) = t, "Q", "."); + Next t + Debug.Print + Next k + End If + End If + End If + j = s(i) + Do While j >= n And i <> 0 + Do + z = a(j): a(j) = a(i): a(i) = z 'Swap a(i), a(j) + j = j - 1 + Loop Until j < i + i = i - 1 + p = i - a(i) + n + q = i + a(i) - 1 + j = s(i) + u(p) = 0 + u(q + r) = 0 + Loop + Loop Until i = 0 + Debug.Print n, m 'number of queens, number of solutions + Next n +End Sub 'n_queens diff --git a/Task/N-queens-problem/Zkl/n-queens-problem-1.zkl b/Task/N-queens-problem/Zkl/n-queens-problem-1.zkl new file mode 100644 index 0000000000..54fa32185b --- /dev/null +++ b/Task/N-queens-problem/Zkl/n-queens-problem-1.zkl @@ -0,0 +1,9 @@ +fcn isAttacked([(x,y)],a,b) // explode list (x,y) into args x & y + { (x==a or y==b or x+y==a+b or x-y==a-b) } +fcn isSafe(a,b,qs){(not qs.filter1(isAttacked,a,b))} // stop at first attack +fcn queensN(N=8,row=1,queens=T){ // T is read only list + qs := [1..N].filter(isSafe.fpM("101",row,queens)) // fpM makes r&q first & third args + .apply(fcn(c,r,qs){qs+T(r,c)},row,queens); + if (row == N) return(qs); + return(qs.apply(self.fcn.fp(N,row+1)).flatten()); // recurse +} diff --git a/Task/N-queens-problem/Zkl/n-queens-problem-2.zkl b/Task/N-queens-problem/Zkl/n-queens-problem-2.zkl new file mode 100644 index 0000000000..9e25a43702 --- /dev/null +++ b/Task/N-queens-problem/Zkl/n-queens-problem-2.zkl @@ -0,0 +1,6 @@ +queens := queensN(4); +println(queens.len()," solution(s):"); +queens.apply2(Console.println); +--> 2 solution(s): +L(L(1,2),L(2,4),L(3,1),L(4,3)) +L(L(1,3),L(2,1),L(3,4),L(4,2)) diff --git a/Task/Named-parameters/Factor/named-parameters.factor b/Task/Named-parameters/Factor/named-parameters.factor new file mode 100644 index 0000000000..28b9e1b14e --- /dev/null +++ b/Task/Named-parameters/Factor/named-parameters.factor @@ -0,0 +1 @@ +:: my-named-params ( a b -- c ) a b * ; diff --git a/Task/Named-parameters/jq/named-parameters-1.jq b/Task/Named-parameters/Jq/named-parameters-1.jq similarity index 100% rename from Task/Named-parameters/jq/named-parameters-1.jq rename to Task/Named-parameters/Jq/named-parameters-1.jq diff --git a/Task/Named-parameters/jq/named-parameters-2.jq b/Task/Named-parameters/Jq/named-parameters-2.jq similarity index 100% rename from Task/Named-parameters/jq/named-parameters-2.jq rename to Task/Named-parameters/Jq/named-parameters-2.jq diff --git a/Task/Named-parameters/Kotlin/named-parameters.kotlin b/Task/Named-parameters/Kotlin/named-parameters.kotlin new file mode 100644 index 0000000000..a5b665cc02 --- /dev/null +++ b/Task/Named-parameters/Kotlin/named-parameters.kotlin @@ -0,0 +1,19 @@ +// version 1.0.6 + +fun someFunction(first: String, second: Int = 2, third: Double) { + println("First = ${first.padEnd(10)}, Second = $second, Third = $third") +} + +fun main(args: Array) { + // using positional parameters + someFunction("positional", 1, 2.0) + + // using named parameters + someFunction(first = "named", second = 1, third = 2.0) + + // omitting 2nd parameter which is optional because it has a default value + someFunction(first = "omitted", third = 2.0) + + // using first and third parameters in reverse + someFunction(third = 2.0, first = "reversed") +} diff --git a/Task/Narcissist/Kotlin/narcissist.kotlin b/Task/Narcissist/Kotlin/narcissist.kotlin new file mode 100644 index 0000000000..abb91f515e --- /dev/null +++ b/Task/Narcissist/Kotlin/narcissist.kotlin @@ -0,0 +1,9 @@ +// version 1.1.0 (run on Windows 10) + +fun main(args: Array) { + val text = java.io.File("narcissist.kt").readText() + println("Enter the number of lines to be input followed by those lines:\n") + val n = readLine()!!.toInt() + val lines = Array(n) { readLine()!! } + if (lines.joinToString("\r\n") == text) println("\naccept") else println("\nreject") +} diff --git a/Task/Narcissist/Swift/narcissist.swift b/Task/Narcissist/Swift/narcissist.swift new file mode 100644 index 0000000000..0894353353 --- /dev/null +++ b/Task/Narcissist/Swift/narcissist.swift @@ -0,0 +1,13 @@ +#! /usr/bin/swift +import Foundation + +let script = CommandLine.arguments[0] +print(script) +let mytext = try? String.init(contentsOfFile: script, encoding: .utf8) + +var enteredtext = readLine() +if mytext == enteredtext { + print("Accept") +} else { + print("Reject") +} diff --git a/Task/Narcissist/Zkl/narcissist.zkl b/Task/Narcissist/Zkl/narcissist.zkl new file mode 100644 index 0000000000..8105790ecb --- /dev/null +++ b/Task/Narcissist/Zkl/narcissist.zkl @@ -0,0 +1,3 @@ +stdin:=File.stdin.read(); +thisFileSrc:=File(System.argv[1]).read(); +println((stdin==thisFileSrc) and "input matches "+System.argv[1] or "No match"); diff --git a/Task/Narcissistic-decimal-number/ALGOL-W/narcissistic-decimal-number.alg b/Task/Narcissistic-decimal-number/ALGOL-W/narcissistic-decimal-number.alg new file mode 100644 index 0000000000..69099abe75 --- /dev/null +++ b/Task/Narcissistic-decimal-number/ALGOL-W/narcissistic-decimal-number.alg @@ -0,0 +1,66 @@ +begin + % print the first 25 narcissistic numbers % + + integer array power( 0 :: 9 ); + integer count, candidate, prevDigits, digits; + + power( 0 ) := 0; + for i := 1 until 9 do power( i ) := 1; + + count := 0; + candidate := 0; + prevDigits := 0; + digits := 1; + + for d9 := 0 until 2 do begin + if d9 > 0 and digits < 9 then digits := 9; + for d8 := 0 until 9 do begin + if d8 > 0 and digits < 8 then digits := 8; + for d7 := 0 until 9 do begin + if d7 > 0 and digits < 7 then digits := 7; + for d6 := 0 until 9 do begin + if d6 > 0 and digits < 6 then digits := 6; + for d5 := 0 until 9 do begin + if d5 > 0 and digits < 5 then digits := 5; + for d4 := 0 until 9 do begin + if d4 > 0 and digits < 4 then digits := 4; + for d3 := 0 until 9 do begin + if d3 > 0 and digits < 3 then digits := 3; + for d2 := 0 until 9 do begin + if d2 > 0 and digits < 2 then digits := 2; + for d1 := 0 until 9 do begin + integer number, sum; + if prevDigits <> digits then begin + % number of digits has increased % + % - increase the powers % + prevDigits := digits; + for i := 2 until 9 do power( i ) := power( i ) * i; + end; + + % sum the digits'th powers of the % + % digits of candidate % + sum := power( d1 ) + power( d2 ) + power( d3 ) + + power( d4 ) + power( d5 ) + power( d6 ) + + power( d7 ) + power( d8 ) + power( d9 ) + ; + if candidate = sum then begin + % found another narcissistic % + % decimal number % + writeon( i_w := 1, s_w := 1, candidate ); + count := count + 1; + if count >= 25 then goto done + end; + candidate := candidate + 1 + end d1; + end d2; + end d3; + end d4; + end d5; + end d6; + end d7; + end d8; + end d9; +done: + write() + +end. diff --git a/Task/Narcissistic-decimal-number/Agena/narcissistic-decimal-number.agena b/Task/Narcissistic-decimal-number/Agena/narcissistic-decimal-number.agena new file mode 100644 index 0000000000..9f621e8606 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Agena/narcissistic-decimal-number.agena @@ -0,0 +1,56 @@ +scope + # print the first 25 narcissistic numbers + + local power := reg( 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ); + local count := 0; + local maxCount := 25; + local candidate := 0; + local prevDigits := 0; + local digits := 1; + + for d9 from 0 to 2 while count < maxCount do + if d9 > 0 and digits < 9 then digits := 9 fi; + for d8 from 0 to 9 while count < maxCount do + if d8 > 0 and digits < 8 then digits := 8 fi; + for d7 from 0 to 9 while count < maxCount do + if d7 > 0 and digits < 7 then digits := 7 fi; + for d6 from 0 to 9 while count < maxCount do + if d6 > 0 and digits < 6 then digits := 6 fi; + for d5 from 0 to 9 while count < maxCount do + if d5 > 0 and digits < 5 then digits := 5 fi; + for d4 from 0 to 9 while count < maxCount do + if d4 > 0 and digits < 4 then digits := 4 fi; + for d3 from 0 to 9 while count < maxCount do + if d3 > 0 and digits < 3 then digits := 3 fi; + for d2 from 0 to 9 while count < maxCount do + if d2 > 0 and digits < 2 then digits := 2 fi; + for d1 from 0 to 9 do + if prevDigits <> digits then + # number of digits has increased - increase the powers + prevDigits := digits; + for i from 2 to 9 do mul power[ i + 1 ], i od; + fi; + # sum the digits'th powers of the digits of candidate + local sum := power[ d1 + 1 ] + power[ d2 + 1 ] + power[ d3 + 1 ] + + power[ d4 + 1 ] + power[ d5 + 1 ] + power[ d6 + 1 ] + + power[ d7 + 1 ] + power[ d8 + 1 ] + power[ d9 + 1 ] + ; + if candidate = sum + then + # found another narcissistic decimal number + io.write( " ", candidate ); + inc count, 1 + fi; + inc candidate, 1 + od; # d1 + od; # d2 + od; # d3 + od; # d4 + od; # d5 + od; # d6 + od; # d7 + od; # d8 + od; # d9 + io.writeline() + +epocs diff --git a/Task/Narcissistic-decimal-number/AppleScript/narcissistic-decimal-number-1.applescript b/Task/Narcissistic-decimal-number/AppleScript/narcissistic-decimal-number-1.applescript new file mode 100644 index 0000000000..0e8dac97c9 --- /dev/null +++ b/Task/Narcissistic-decimal-number/AppleScript/narcissistic-decimal-number-1.applescript @@ -0,0 +1,172 @@ +-- NARCISSI ------------------------------------------------------------------- + +-- isDaffodil :: Int -> Int -> Bool +on isDaffodil(e, n) + set ds to digitList(n) + (e = length of ds) and (n = powerSum(e, ds)) +end isDaffodil + +-- digitList :: Int -> [Int] +on digitList(n) + if n > 0 then + {n mod 10} & digitList(n div 10) + else + {} + end if +end digitList + +-- powerSum :: Int -> [Int] -> Int +on powerSum(e, ns) + script + on |λ|(a, x) + a + x ^ e + end |λ| + end script + + foldl(result, 0, ns) as integer +end powerSum + +-- narcissiOfLength :: Int -> [Int] +on narcissiOfLength(nDigits) + script nthPower + on |λ|(x) + {x, x ^ nDigits as integer} + end |λ| + end script + set powers to map(nthPower, enumFromTo(0, 9)) + + script combn + on digitTree(n, parents) + if n > 0 then + if parents ≠ {} then + script nextLayer + on |λ|(pair) + set {digit, intSum} to pair + script addPower + on |λ|(dp) + set {d, p} to dp + {d, p + intSum} + end |λ| + end script + + map(addPower, items 1 thru (digit + 1) of powers) + end |λ| + end script + + set nodes to concatMap(nextLayer, parents) + else + set nodes to powers + end if + digitTree(n - 1, nodes) + else + script + on |λ|(pair) + isDaffodil(nDigits, item 2 of pair) + end |λ| + end script + + filter(result, parents) + end if + end digitTree + end script + + script snd + on |λ|(ab) + item 2 of ab + end |λ| + end script + map(snd, combn's digitTree(nDigits, {})) +end narcissiOfLength + + +-- TEST ----------------------------------------------------------------------- +on run + + {0} & concatMap(narcissiOfLength, enumFromTo(1, 5)) + -- 4 seconds, 20 narcissi + + -- {0} & concatMap(narcissiOfLength, enumFromTo(1, 6)) + -- 103 seconds, 21 narcissi + + -- {0} & concatMap(narcissiOfLength, enumFromTo(1, 7)) + -- 13.75 minutes, 25 narcissi + +end run + + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- concatMap :: (a -> [b]) -> [a] -> [b] +on concatMap(f, xs) + set lst to {} + set lng to length of xs + tell mReturn(f) + repeat with i from 1 to lng + set lst to (lst & |λ|(item i of xs, i, xs)) + end repeat + end tell + return lst +end concatMap + +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if n < m then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo + +-- filter :: (a -> Bool) -> [a] -> [a] +on filter(f, xs) + tell mReturn(f) + set lst to {} + set lng to length of xs + repeat with i from 1 to lng + set v to item i of xs + if |λ|(v, i, xs) then set end of lst to v + end repeat + return lst + end tell +end filter + +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn diff --git a/Task/Narcissistic-decimal-number/AppleScript/narcissistic-decimal-number-2.applescript b/Task/Narcissistic-decimal-number/AppleScript/narcissistic-decimal-number-2.applescript new file mode 100644 index 0000000000..458983251f --- /dev/null +++ b/Task/Narcissistic-decimal-number/AppleScript/narcissistic-decimal-number-2.applescript @@ -0,0 +1 @@ +{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834, 1741725, 4210818, 9800817, 9926315} diff --git a/Task/Narcissistic-decimal-number/Clojure/narcissistic-decimal-number.clj b/Task/Narcissistic-decimal-number/Clojure/narcissistic-decimal-number.clj new file mode 100644 index 0000000000..ebd19a5381 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Clojure/narcissistic-decimal-number.clj @@ -0,0 +1,13 @@ +(ns narcissistic.core + (:require [clojure.math.numeric-tower :as math])) + +(defn digits [n] ;; digits of a number. + (->> n str (map (comp read-string str)))) + +(defn narcissistic? [n] ;; True if the number is a Narcissistic one. + (let [d (digits n) + s (count d)] + (= n (reduce + (map #(math/expt % s) d))))) + +(defn firstNnarc [n] ;;list of the first "n" Narcissistic numbers. + (take n (filter narcissistic? (range)))) diff --git a/Task/Narcissistic-decimal-number/ERRE/narcissistic-decimal-number.erre b/Task/Narcissistic-decimal-number/ERRE/narcissistic-decimal-number.erre index 83a0fbd082..71d8939d65 100644 --- a/Task/Narcissistic-decimal-number/ERRE/narcissistic-decimal-number.erre +++ b/Task/Narcissistic-decimal-number/ERRE/narcissistic-decimal-number.erre @@ -5,10 +5,10 @@ PROGRAM NARCISISTIC BEGIN N=0 LOOP - LENG=LEN(MID$(STR$(N),2)) + C$=MID$(STR$(N),2) + LENG=LEN(C$) SUM=0 FOR I=1 TO LENG DO - C$=MID$(STR$(N),2) C=VAL(MID$(C$,I,1)) SUM+=C^LENG END FOR diff --git a/Task/Narcissistic-decimal-number/FreeBASIC/narcissistic-decimal-number-1.freebasic b/Task/Narcissistic-decimal-number/FreeBASIC/narcissistic-decimal-number-1.freebasic index f2a60e272f..d54b0cc65b 100644 --- a/Task/Narcissistic-decimal-number/FreeBASIC/narcissistic-decimal-number-1.freebasic +++ b/Task/Narcissistic-decimal-number/FreeBASIC/narcissistic-decimal-number-1.freebasic @@ -1,6 +1,6 @@ -' normal version: 17-06-2015 +' normal version: 14-03-2017 ' compile with: fbc -s console -' can go up to 19 digits (ulongint is 64bit), above 19 overflow will occur +' can go up to 18 digits (ulongint is 64bit), above 18 overflow will occur Dim As Integer n, n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, a, b Dim As Integer d() @@ -20,8 +20,8 @@ For n = 1 To 7 For n1 = n-n9-n8-n7-n6-n5-n4-n3-n2 To 0 Step -1 n0 = n-n9-n8-n7-n6-n5-n4-n3-n2-n1 - x = n1*d2pow(1) + n2*d2pow(2) + n3*d2pow(3) + n4*d2pow(4) + n5*d2pow(5)_ - + n6*d2pow(6) + n7*d2pow(7) + n8*d2pow(8) + n9*d2pow(9) + x = n1 + n2*d2pow(2) + n3*d2pow(3) + n4*d2pow(4) + n5*d2pow(5)_ + + n6*d2pow(6) + n7*d2pow(7) + n8*d2pow(8) + n9*d2pow(9) str_x = Str(x) If Len(str_x) = n Then diff --git a/Task/Narcissistic-decimal-number/GW-BASIC/narcissistic-decimal-number.gw-basic b/Task/Narcissistic-decimal-number/GW-BASIC/narcissistic-decimal-number.gw-basic new file mode 100644 index 0000000000..2f264d3579 --- /dev/null +++ b/Task/Narcissistic-decimal-number/GW-BASIC/narcissistic-decimal-number.gw-basic @@ -0,0 +1,31 @@ +1 DEFINT A-W : DEFDBL X-Z : DIM D(9) : DIM X2(9) : KEY OFF : CLS +2 FOR A = 0 TO 9 : X2(A) = A : NEXT A +3 FOR N = 1 TO 7 +4 FOR N9 = N TO 0 STEP -1 +5 FOR N8 = N-N9 TO 0 STEP -1 +6 FOR N7 = N-N9-N8 TO 0 STEP -1 +7 FOR N6 = N-N9-N8-N7 TO 0 STEP -1 +8 FOR N5 = N-N9-N8-N7-N6 TO 0 STEP -1 +9 FOR N4 = N-N9-N8-N7-N6-N5 TO 0 STEP -1 +10 FOR N3 = N-N9-N8-N7-N6-N5-N4 TO 0 STEP -1 +11 FOR N2 = N-N9-N8-N7-N6-N5-N4-N3 TO 0 STEP -1 +12 FOR N1 = N-N9-N8-N7-N6-N5-N4-N3-N2 TO 0 STEP -1 +13 N0 = N-N9-N8-N7-N6-N5-N4-N3-N2-N1 +14 X = N1 + N2*X2(2) + N3*X2(3) + N4*X2(4) + N5*X2(5) + N6*X2(6) + N7*X2(7) + N8*X2(8) + N9*X2(9) +15 S$ = MID$(STR$(X),2) +16 IF LEN(S$) < N THEN GOTO 25 +17 IF LEN(S$) <> N THEN GOTO 24 +18 FOR A = 0 TO 9 : D(A) = 0 : NEXT A +19 FOR A = 0 TO N-1 +20 B = ASC(MID$(S$,A+1,1))-48 +21 D(B) = D(B) + 1 +22 NEXT A +23 IF N0 = D(0) AND N1 = D(1) AND N2 = D(2) AND N3 = D(3) AND N4 = D(4) AND N5 = D(5) AND N6 = D(6) AND N7 = D(7) AND N8 = D(8) AND N9 = D(9) THEN PRINT X, +24 NEXT N1 : NEXT N2 : NEXT N3 : NEXT N4 : NEXT N5 : NEXT N6 : NEXT N7 : NEXT N8 : NEXT N9 +25 FOR A = 2 TO 9 +26 X2(A) = X2(A) * A +27 NEXT A +28 NEXT N +29 PRINT +30 PRINT "done" +31 END diff --git a/Task/Narcissistic-decimal-number/Haskell/narcissistic-decimal-number-1.hs b/Task/Narcissistic-decimal-number/Haskell/narcissistic-decimal-number-1.hs new file mode 100644 index 0000000000..2174d38f7e --- /dev/null +++ b/Task/Narcissistic-decimal-number/Haskell/narcissistic-decimal-number-1.hs @@ -0,0 +1,10 @@ +import Data.Char (digitToInt) + +isNarcissistic :: Int -> Bool +isNarcissistic n = (sum ((^ digitCount) <$> digits) ==) n + where + digits = digitToInt <$> show n + digitCount = length digits + +main :: IO () +main = mapM_ print $ take 25 (filter isNarcissistic [0 ..]) diff --git a/Task/Narcissistic-decimal-number/Haskell/narcissistic-decimal-number-2.hs b/Task/Narcissistic-decimal-number/Haskell/narcissistic-decimal-number-2.hs new file mode 100644 index 0000000000..722f1a7eeb --- /dev/null +++ b/Task/Narcissistic-decimal-number/Haskell/narcissistic-decimal-number-2.hs @@ -0,0 +1,32 @@ +import Control.Arrow (second) + +isDaffodil :: Int -> Int -> Bool +isDaffodil e n = + let ds = digitList n + in e == length ds && n == powerSum e ds + +powerSum :: Int -> [Int] -> Int +powerSum n = foldr ((+) . (^ n)) 0 + +digitList :: Int -> [Int] +digitList 0 = [] +digitList n = rem n 10 : digitList (quot n 10) + +narcissiOfLength :: Int -> [Int] +narcissiOfLength nDigits = snd <$> digitTree nDigits [] + where + powers = ((,) <*> (^ nDigits)) <$> [0 .. 9] + digitTree n parents = + if n > 0 + then digitTree -- Power sums for all unordered digit combinations. + (n - 1) -- (Digit order is irrelevant when summing powers) + (if null parents + then powers + else concatMap + (\(d, pwrSum) -> + (second (pwrSum +) <$> take (d + 1) powers)) + parents) + else filter (isDaffodil nDigits . snd) parents + +main :: IO () +main = print $ 0 : concatMap narcissiOfLength [1 .. 7] diff --git a/Task/Narcissistic-decimal-number/Haskell/narcissistic-decimal-number.hs b/Task/Narcissistic-decimal-number/Haskell/narcissistic-decimal-number.hs deleted file mode 100644 index f2cd096994..0000000000 --- a/Task/Narcissistic-decimal-number/Haskell/narcissistic-decimal-number.hs +++ /dev/null @@ -1,15 +0,0 @@ -import System.IO - -digits :: (Read a, Show a) => a -> [a] -digits n = map (read . (:[])) $ show n - -isNarcissistic :: (Show a, Read a, Num a, Eq a) => a -> Bool -isNarcissistic n = - let dig = digits n - len = length dig - in n == (sum $ map (^ len) $ dig) - -main :: IO () -main = do - hSetBuffering stdout NoBuffering - putStrLn $ unwords $ map show $ take 25 $ filter isNarcissistic [(0 :: Int)..] diff --git a/Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number.js b/Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number-1.js similarity index 100% rename from Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number.js rename to Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number-1.js diff --git a/Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number-2.js b/Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number-2.js new file mode 100644 index 0000000000..211b63b342 --- /dev/null +++ b/Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number-2.js @@ -0,0 +1,40 @@ +(() => { + 'use strict'; + + // digits :: Int -> [Int] + const digits = n => n.toString() + .split('') + .map(x => parseInt(x, 10)); + + // pow :: Int -> Int -> Int + const pow = Math.pow; + + // isNarc :: Int -> Bool + const isNarc = n => { + const + ds = digits(n), + len = ds.length; + + return ds.reduce((a, x) => + a + pow(x, len), 0) === n; + }; + + // until :: (a -> Bool) -> (a -> a) -> a -> a + const until = (p, f, x) => { + let v = x; + while (!p(v)) v = f(v); + return v; + }; + + return until( + x => x.narc.length > 24, + x => ({ + n: x.n + 1, + narc: (isNarc(x.n) ? x.narc.concat(x.n) : x.narc) + }), { + n: 0, + narc: [] + } + ) + .narc +})(); diff --git a/Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number-3.js b/Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number-3.js new file mode 100644 index 0000000000..8b85ca0a69 --- /dev/null +++ b/Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number-3.js @@ -0,0 +1 @@ +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834, 1741725, 4210818, 9800817, 9926315] diff --git a/Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number-4.js b/Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number-4.js new file mode 100644 index 0000000000..e610d52c54 --- /dev/null +++ b/Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number-4.js @@ -0,0 +1,107 @@ +(() => { + 'use strict'; + + // DAFFODILS -------------------------------------------------------------- + + // narcissiOfLength :: Int -> [Int] + const narcissiOfLength = n => + n > 0 ? filter(curry(isDaffodil)(n), digitPowerSums(n)) : [0]; + + // Do the decimal digits of N, each raised to the power E, sum to N itself ? + +// isDaffodil :: Int -> Int -> Bool +const isDaffodil = (e, n) => { + const + powerSum = (n, xs) => xs.reduce((a, x) => a + Math.pow(x, n), 0), + digitList = n => (n > 0) ? ( + cons((n % 10), digitList(Math.floor(n / 10))) + ) : [], + ds = digitList(n); + return e === ds.length && n === powerSum(e, ds); +}; + + // The subset of integers of n digits that actually need daffodil checking: + + // (Flattened leaves of a tree of unique digit combinations, in which + // order is not significant. Digit sequence doesn't affect power summing) + + // digitPowerSums :: Int -> [Int] + const digitPowerSums = nDigits => { + const + digitPowers = map(x => [x, pow(x, nDigits)], enumFromTo(0, 9)), + treeGrowth = (n, parentPairs) => (n > 0) ? ( + treeGrowth(n - 1, + isNull(parentPairs) ? ( + digitPowers + ) : concatMap(([parentDigit, parentSum]) => + map(([leafDigit, leafSum]) => // + [leafDigit, parentSum + leafSum], + take(parentDigit + 1, digitPowers) + ), + parentPairs + )) + ) : parentPairs; + return map(snd, treeGrowth(nDigits, [])); + }; + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // enumFromTo :: Int -> Int -> Maybe Int -> [Int] + const enumFromTo = (m, n, step) => { + const d = (step || 1) * (n >= m ? 1 : -1); + return Array.from({ + length: Math.floor((n - m) / d) + 1 + }, (_, i) => m + (i * d)); + }; + // concatMap :: (a -> [b]) -> [a] -> [b] + const concatMap = (f, xs) => [].concat.apply([], xs.map(f)); + + // cons :: a -> [a] -> [a] + const cons = (x, xs) => [x].concat(xs); + + // 2 or more arguments + // curry :: Function -> Function + const curry = (f, ...args) => { + const go = xs => xs.length >= f.length ? (f.apply(null, xs)) : + function () { + return go(xs.concat([].slice.apply(arguments))); + }; + return go([].slice.call(args, 1)); + }; + + // filter :: (a -> Bool) -> [a] -> [a] + const filter = (f, xs) => xs.filter(f); + + // map :: (a -> b) -> [a] -> [b] + const map = curry((f, xs) => xs.map(f)); + + // isNull :: [a] -> Bool + const isNull = xs => (xs instanceof Array) ? xs.length < 1 : undefined; + + // length :: [a] -> Int + const length = xs => xs.length; + + // pow :: Int -> Int -> Int + const pow = Math.pow + + // take :: Int -> [a] -> [a] + const take = (n, xs) => xs.slice(0, n); + + // show :: + // (a -> String) f, Num n => + // a -> maybe f -> maybe n -> String + const show = JSON.stringify; + + // snd :: (a, b) -> b + const snd = tpl => Array.isArray(tpl) ? tpl[1] : undefined; + + + // TEST ------------------------------------------------------------------- + + // return length(concatMap(digitPowerSums, enumFromTo(0, 7))); + + return show( + //digitPowerSums(3) + concatMap(narcissiOfLength, enumFromTo(0, 7)) + ); +})(); diff --git a/Task/Narcissistic-decimal-number/jq/narcissistic-decimal-number-1.jq b/Task/Narcissistic-decimal-number/Jq/narcissistic-decimal-number-1.jq similarity index 100% rename from Task/Narcissistic-decimal-number/jq/narcissistic-decimal-number-1.jq rename to Task/Narcissistic-decimal-number/Jq/narcissistic-decimal-number-1.jq diff --git a/Task/Narcissistic-decimal-number/jq/narcissistic-decimal-number-2.jq b/Task/Narcissistic-decimal-number/Jq/narcissistic-decimal-number-2.jq similarity index 100% rename from Task/Narcissistic-decimal-number/jq/narcissistic-decimal-number-2.jq rename to Task/Narcissistic-decimal-number/Jq/narcissistic-decimal-number-2.jq diff --git a/Task/Narcissistic-decimal-number/jq/narcissistic-decimal-number-3.jq b/Task/Narcissistic-decimal-number/Jq/narcissistic-decimal-number-3.jq similarity index 100% rename from Task/Narcissistic-decimal-number/jq/narcissistic-decimal-number-3.jq rename to Task/Narcissistic-decimal-number/Jq/narcissistic-decimal-number-3.jq diff --git a/Task/Narcissistic-decimal-number/jq/narcissistic-decimal-number-4.jq b/Task/Narcissistic-decimal-number/Jq/narcissistic-decimal-number-4.jq similarity index 100% rename from Task/Narcissistic-decimal-number/jq/narcissistic-decimal-number-4.jq rename to Task/Narcissistic-decimal-number/Jq/narcissistic-decimal-number-4.jq diff --git a/Task/Narcissistic-decimal-number/jq/narcissistic-decimal-number-5.jq b/Task/Narcissistic-decimal-number/Jq/narcissistic-decimal-number-5.jq similarity index 100% rename from Task/Narcissistic-decimal-number/jq/narcissistic-decimal-number-5.jq rename to Task/Narcissistic-decimal-number/Jq/narcissistic-decimal-number-5.jq diff --git a/Task/Narcissistic-decimal-number/Kotlin/narcissistic-decimal-number.kotlin b/Task/Narcissistic-decimal-number/Kotlin/narcissistic-decimal-number.kotlin new file mode 100644 index 0000000000..8d8a5d3a9a --- /dev/null +++ b/Task/Narcissistic-decimal-number/Kotlin/narcissistic-decimal-number.kotlin @@ -0,0 +1,29 @@ +// version 1.1.0 + +fun isNarcissistic(n: Int): Boolean { + if (n < 0) throw IllegalArgumentException("Argument must be non-negative") + var nn = n + val digits = mutableListOf() + val powers = IntArray(10) { 1 } + while (nn > 0) { + digits.add(nn % 10) + for (i in 1..9) powers[i] *= i // no need to calculate powers[0] + nn /= 10 + } + val sum = digits.filter { it > 0 }.map { powers[it] }.sum() + return n == sum +} + +fun main(args: Array) { + println("The first 25 narcissistic (or Armstrong) numbers are:") + var i = 0 + var count = 0 + do { + if (isNarcissistic(i)) { + print("$i ") + count++ + } + i++ + } + while (count < 25) +} diff --git a/Task/Narcissistic-decimal-number/Phix/narcissistic-decimal-number.phix b/Task/Narcissistic-decimal-number/Phix/narcissistic-decimal-number.phix new file mode 100644 index 0000000000..388eb25952 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Phix/narcissistic-decimal-number.phix @@ -0,0 +1,17 @@ +function narcissistic(integer n) + string d = sprintf("%d",n) + integer l = length(d) + integer 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 +?s diff --git a/Task/Narcissistic-decimal-number/Sidef/narcissistic-decimal-number.sidef b/Task/Narcissistic-decimal-number/Sidef/narcissistic-decimal-number.sidef index 959a17410b..ec5d3652cd 100644 --- a/Task/Narcissistic-decimal-number/Sidef/narcissistic-decimal-number.sidef +++ b/Task/Narcissistic-decimal-number/Sidef/narcissistic-decimal-number.sidef @@ -1,9 +1,9 @@ func is_narcissistic(n) { - n.digits »**» n.len -> sum(0) == n + n.digits »**» n.len -> sum == n } - +  var count = 0 -for i in (0..^Inf) { +for i in ^Inf { if (is_narcissistic(i)) { say "#{++count}\t#{i}" break if (count == 25) diff --git a/Task/Narcissistic-decimal-number/ZX-Spectrum-Basic/narcissistic-decimal-number.zx b/Task/Narcissistic-decimal-number/ZX-Spectrum-Basic/narcissistic-decimal-number.zx new file mode 100644 index 0000000000..5fca4d6eb6 --- /dev/null +++ b/Task/Narcissistic-decimal-number/ZX-Spectrum-Basic/narcissistic-decimal-number.zx @@ -0,0 +1,39 @@ + 1 DIM K(10): DIM M(10) + 2 FOR Y=0 TO 9: LET M(Y+1)=Y: NEXT Y + 3 FOR N=1 TO 7 + 4 FOR J=N TO 0 STEP -1 + 5 FOR I=N-J TO 0 STEP -1 + 6 FOR H=N-J-I TO 0 STEP -1 + 7 FOR G=N-J-I-H TO 0 STEP -1 + 8 FOR F=N-J-I-H-G TO 0 STEP -1 + 9 FOR E=N-J-I-H-G-F TO 0 STEP -1 +10 FOR D=N-J-I-H-G-F-E TO 0 STEP -1 +11 FOR C=N-J-I-H-G-F-E-D TO 0 STEP -1 +12 FOR B=N-J-I-H-G-F-E-D-C TO 0 STEP -1 +13 LET A=N-J-I-H-G-F-E-D-C-B +14 LET X=B+C*M(3)+D*M(4)+E*M(5)+F*M(6)+G*M(7)+H*M(8)+I*M(9)+J*M(10) +15 LET S$=STR$ (X) +16 IF LEN (S$)N THEN GO TO 33 +18 FOR Y=1 TO 10: LET K(Y)=0: NEXT Y +19 FOR Y=1 TO N +20 LET Z= CODE (S$(Y))-47 +21 LET K(Z)=K(Z)+1 +22 NEXT Y +23 IF A<>K(1) THEN GO TO 33 +24 IF B<>K(2) THEN GO TO 33 +25 IF C<>K(3) THEN GO TO 33 +26 IF D<>K(4) THEN GO TO 33 +27 IF E<>K(5) THEN GO TO 33 +28 IF F<>K(6) THEN GO TO 33 +29 IF G<>K(7) THEN GO TO 33 +30 IF H<>K(8) THEN GO TO 33 +31 IF I<>K(9) THEN GO TO 33 +32 IF J=K(10) THEN PRINT X, +33 NEXT B: NEXT C: NEXT D: NEXT E: NEXT F: NEXT G: NEXT H: NEXT I: NEXT J +34 FOR Y=2 TO 9 +35 LET M(Y+1)=M(Y+1)*Y +36 NEXT Y +37 NEXT N +38 PRINT +39 PRINT "DONE" diff --git a/Task/Narcissistic-decimal-number/Zkl/narcissistic-decimal-number-1.zkl b/Task/Narcissistic-decimal-number/Zkl/narcissistic-decimal-number-1.zkl new file mode 100644 index 0000000000..5a6df0bf44 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Zkl/narcissistic-decimal-number-1.zkl @@ -0,0 +1,4 @@ +fcn isNarcissistic(n){ + ns,m := n.split(), ns.len() - 1; + ns.reduce('wrap(s,d){ z:=d; do(m){z*=d} s+z },0) == n +} diff --git a/Task/Narcissistic-decimal-number/Zkl/narcissistic-decimal-number-2.zkl b/Task/Narcissistic-decimal-number/Zkl/narcissistic-decimal-number-2.zkl new file mode 100644 index 0000000000..60537dcfcf --- /dev/null +++ b/Task/Narcissistic-decimal-number/Zkl/narcissistic-decimal-number-2.zkl @@ -0,0 +1,6 @@ +var [const] powers=(10).pump(List,'wrap(n){ + (1).pump(15,List,'wrap(p){ n.toFloat().pow(p).toInt() }) }); +fcn isNarcissistic2(n){ + m:=(n.numDigits - 1); + n.split().reduce('wrap(s,d){ s + powers[d][m] },0) == n +} diff --git a/Task/Narcissistic-decimal-number/Zkl/narcissistic-decimal-number-3.zkl b/Task/Narcissistic-decimal-number/Zkl/narcissistic-decimal-number-3.zkl new file mode 100644 index 0000000000..6e79ca7ea1 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Zkl/narcissistic-decimal-number-3.zkl @@ -0,0 +1,4 @@ +ns:=[0..].filter.fp1(isNarcissistic); +ns(15).println(); +ns(5).println(); +ns(5).println(); diff --git a/Task/Natural-sorting/00DESCRIPTION b/Task/Natural-sorting/00DESCRIPTION index 94e27f40aa..8baed898d0 100644 --- a/Task/Natural-sorting/00DESCRIPTION +++ b/Task/Natural-sorting/00DESCRIPTION @@ -1,3 +1,5 @@ +{{Sorting Algorithm}} + Natural sorting is the sorting of text that does more than rely on the order of individual characters codes to make the finding of individual strings easier for a ''human'' reader. diff --git a/Task/Natural-sorting/00META.yaml b/Task/Natural-sorting/00META.yaml new file mode 100644 index 0000000000..ecd07d0417 --- /dev/null +++ b/Task/Natural-sorting/00META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Sorting +note: Sorting Algorithms diff --git a/Task/Natural-sorting/D/natural-sorting.d b/Task/Natural-sorting/D/natural-sorting.d index 57853de7f6..1f6f38d26c 100644 --- a/Task/Natural-sorting/D/natural-sorting.d +++ b/Task/Natural-sorting/D/natural-sorting.d @@ -1,5 +1,5 @@ import std.stdio, std.string, std.algorithm, std.array, std.conv, - std.ascii, std.range; + std.ascii, std.range; string[] naturalSort(string[] arr) /*pure @safe*/ { static struct Part { @@ -7,8 +7,8 @@ string[] naturalSort(string[] arr) /*pure @safe*/ { int opCmp(in ref Part other) const pure { return (s[0].isDigit && other.s[0].isDigit) ? - cmp([s.to!ulong], [other.s.to!ulong]) : - cmp(s, other.s); + cmp([s.to!ulong], [other.s.to!ulong]) : + cmp(s, other.s); } } @@ -17,7 +17,7 @@ string[] naturalSort(string[] arr) /*pure @safe*/ { .strip .tr(whitespace, " ", "s") .toLower - .groupBy!isDigit + .chunkBy!isDigit .map!(p => Part(p.text)) .array; return (r.length > 1 && r[0].s == "the") ? r.dropOne : r; @@ -27,32 +27,40 @@ string[] naturalSort(string[] arr) /*pure @safe*/ { } void main() /*@safe*/ { - auto tests = [ - // Ignoring leading spaces. - ["ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " + const tests = [ + // Ignoring leading spaces. + ["ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " ignore leading spaces: 2+1", " ignore leading spaces: 2+0"], - // Ignoring multiple adjacent spaces (m.a.s). - ["ignore m.a.s spaces: 2-2", "ignore m.a.s spaces: 2-1", - "ignore m.a.s spaces: 2+0", "ignore m.a.s spaces: 2+1"], + // Ignoring multiple adjacent spaces (m.a.s). + ["ignore m.a.s spaces: 2-2", "ignore m.a.s spaces: 2-1", + "ignore m.a.s spaces: 2+0", "ignore m.a.s spaces: 2+1"], - // Equivalent whitespace characters. - ["Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2", - "Equiv.\x0cspaces: 3-1", "Equiv.\x0bspaces: 3+0", - "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2"], + // Equivalent whitespace characters. + ["Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2", + "Equiv.\x0cspaces: 3-1", "Equiv.\x0bspaces: 3+0", + "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2"], - // Case Indepenent sort. - ["cASE INDEPENENT: 3-2", "caSE INDEPENENT: 3-1", - "casE INDEPENENT: 3+0", "case INDEPENENT: 3+1"], + // Case Indepenent [sic] sort. + ["cASE INDEPENENT: 3-2" /* [sic] */, "caSE INDEPENENT: 3-1" /* [sic] */, + "casE INDEPENENT: 3+0" /* [sic] */, "case INDEPENENT: 3+1" /* [sic] */], - // Numeric fields as numerics. - ["foo100bar99baz0.txt", "foo100bar10baz0.txt", - "foo1000bar99baz10.txt", "foo1000bar99baz9.txt"], + // Numeric fields as numerics. + ["foo100bar99baz0.txt", "foo100bar10baz0.txt", + "foo1000bar99baz10.txt", "foo1000bar99baz9.txt"], - // Title sorts. - ["The Wind in the Willows", "The 40th step more", - "The 39 steps", "Wanda"]]; + // Title sorts. + ["The Wind in the Willows", "The 40th step more", + "The 39 steps", "Wanda"]]; - foreach (test; tests) - writeln(test, "\n", test.naturalSort, "\n"); + void printTexts(Range)(string tag, Range range) { + const sic = range.front.canFind("INDEPENENT") ? " [sic]" : ""; + writefln("\n%s%s:\n%-( |%s|%|\n%)", tag, sic, range); + } + + foreach (test; tests) { + printTexts("Test strings", test); + printTexts("Normally sorted", test.dup.sort()); + printTexts("Naturally sorted", test.dup.naturalSort()); + } } diff --git a/Task/Natural-sorting/jq/natural-sorting-1.jq b/Task/Natural-sorting/Jq/natural-sorting-1.jq similarity index 100% rename from Task/Natural-sorting/jq/natural-sorting-1.jq rename to Task/Natural-sorting/Jq/natural-sorting-1.jq diff --git a/Task/Natural-sorting/jq/natural-sorting-2.jq b/Task/Natural-sorting/Jq/natural-sorting-2.jq similarity index 100% rename from Task/Natural-sorting/jq/natural-sorting-2.jq rename to Task/Natural-sorting/Jq/natural-sorting-2.jq diff --git a/Task/Natural-sorting/jq/natural-sorting-3.jq b/Task/Natural-sorting/Jq/natural-sorting-3.jq similarity index 100% rename from Task/Natural-sorting/jq/natural-sorting-3.jq rename to Task/Natural-sorting/Jq/natural-sorting-3.jq diff --git a/Task/Natural-sorting/Kotlin/natural-sorting.kotlin b/Task/Natural-sorting/Kotlin/natural-sorting.kotlin new file mode 100644 index 0000000000..120ffcc82d --- /dev/null +++ b/Task/Natural-sorting/Kotlin/natural-sorting.kotlin @@ -0,0 +1,181 @@ +// version 1.1.4-3 + +val r2 = Regex("""[ ]{2,}""") +val r3 = Regex("""\s""") // \s represents any whitespace character +val r5 = Regex("""\d+""") + +/** Only covers ISO-8859-1 accented characters plus (for consistency) Ÿ */ +val ucAccented = arrayOf("ÀÁÂÃÄÅ", "Ç", "ÈÉÊË", "ÌÍÎÏ", "Ñ", "ÒÓÔÕÖØ", "ÙÚÛÜ", "ÝŸ") +val lcAccented = arrayOf("àáâãäå", "ç", "èéêë", "ìíîï", "ñ", "òóôõöø", "ùúûü", "ýÿ") +val ucNormal = "ACEINOUY" +val lcNormal = "aceinouy" + +/** Only the commoner ligatures */ +val ucLigatures = "ÆIJŒ" +val lcLigatures = "æijœ" +val ucSeparated = arrayOf("AE", "IJ", "OE") +val lcSeparated = arrayOf("ae", "ij", "oe") + +/** Miscellaneous replacements */ +val miscLetters = "ßſʒ" +val miscReplacements = arrayOf("ss", "s", "s") + +/** Displays strings including whitespace as if the latter were literal characters */ +fun String.toDisplayString(): String { + val whitespace = arrayOf("\t", "\n", "\u000b", "\u000c", "\r") + val whitespace2 = arrayOf("\\t", "\\n", "\\u000b", "\\u000c", "\\r") + var s = this + for (i in 0..4) s = s.replace(whitespace[i], whitespace2[i]) + return s +} + +/** Ignoring leading space(s) */ +fun selector1(s: String) = s.trimStart(' ') + +/** Ignoring multiple adjacent spaces i.e. condensing to a single space */ +fun selector2(s: String) = s.replace(r2, " ") + +/** Equivalent whitespace characters (equivalent to a space say) */ +fun selector3(s: String) = s.replace(r3, " ") + +/** Case independent sort */ +fun selector4(s: String) = s.toLowerCase() + +/** Numeric fields as numerics (deals with up to 20 digits) */ +fun selector5(s: String) = r5.replace(s) { it.value.padStart(20, '0') } + +/** Title sort */ +fun selector6(s: String): String { + if (s.startsWith("the ", true)) return s.drop(4) + if (s.startsWith("an ", true)) return s.drop(3) + if (s.startsWith("a ", true)) return s.drop(2) + return s +} + +/** Equivalent accented characters (and case) */ +fun selector7(s: String): String { + val sb = StringBuilder() + outer@ for (c in s) { + for ((i, ucs) in ucAccented.withIndex()) { + if (c in ucs) { + sb.append(ucNormal[i]) + continue@outer + } + } + for ((i, lcs) in lcAccented.withIndex()) { + if (c in lcs) { + sb.append(lcNormal[i]) + continue@outer + } + } + sb.append(c) + } + return sb.toString().toLowerCase() +} + +/** Separated ligatures */ +fun selector8(s: String): String { + var ss = s + for ((i, c) in ucLigatures.withIndex()) ss = ss.replace(c.toString(), ucSeparated[i]) + for ((i, c) in lcLigatures.withIndex()) ss = ss.replace(c.toString(), lcSeparated[i]) + return ss +} + +/** Character replacements */ +fun selector9(s: String): String { + var ss = s + for ((i, c) in miscLetters.withIndex()) ss = ss.replace(c.toString(), miscReplacements[i]) + return ss +} + +fun main(args: Array) { + println("The 9 string lists, sorted 'naturally':\n") + val s1 = arrayOf( + "ignore leading spaces: 2-2", + " ignore leading spaces: 2-1", + " ignore leading spaces: 2+0", + " ignore leading spaces: 2+1" + ) + s1.sortBy(::selector1) + println(s1.map { "'$it'" }.joinToString("\n")) + + val s2 = arrayOf( + "ignore m.a.s spaces: 2-2", + "ignore m.a.s spaces: 2-1", + "ignore m.a.s spaces: 2+0", + "ignore m.a.s spaces: 2+1" + ) + println() + s2.sortBy(::selector2) + println(s2.map { "'$it'" }.joinToString("\n")) + + val s3 = arrayOf( + "Equiv. spaces: 3-3", + "Equiv.\rspaces: 3-2", + "Equiv.\u000cspaces: 3-1", + "Equiv.\u000bspaces: 3+0", + "Equiv.\nspaces: 3+1", + "Equiv.\tspaces: 3+2" + ) + println() + s3.sortBy(::selector3) + println(s3.map { "'$it'".toDisplayString() }.joinToString("\n")) + + val s4 = arrayOf( + "cASE INDEPENENT: 3-2", + "caSE INDEPENENT: 3-1", + "casE INDEPENENT: 3+0", + "case INDEPENENT: 3+1" + ) + println() + s4.sortBy(::selector4) + println(s4.map { "'$it'" }.joinToString("\n")) + + val s5 = arrayOf( + "foo100bar99baz0.txt", + "foo100bar10baz0.txt", + "foo1000bar99baz10.txt", + "foo1000bar99baz9.txt" + ) + println() + s5.sortBy(::selector5) + println(s5.map { "'$it'" }.joinToString("\n")) + + val s6 = arrayOf( + "The Wind in the Willows", + "The 40th step more", + "The 39 steps", + "Wanda" + ) + println() + s6.sortBy(::selector6) + println(s6.map { "'$it'" }.joinToString("\n")) + + val s7 = arrayOf( + "Equiv. ý accents: 2-2", + "Equiv. Ý accents: 2-1", + "Equiv. y accents: 2+0", + "Equiv. Y accents: 2+1" + ) + println() + s7.sortBy(::selector7) + println(s7.map { "'$it'" }.joinToString("\n")) + + val s8 = arrayOf( + "IJ ligatured ij", + "no ligature" + ) + println() + s8.sortBy(::selector8) + println(s8.map { "'$it'" }.joinToString("\n")) + + val s9 = arrayOf( + "Start with an ʒ: 2-2", + "Start with an ſ: 2-1", + "Start with an ß: 2+0", + "Start with an s: 2+1" + ) + println() + s9.sortBy(::selector9) + println(s9.map { "'$it'" }.joinToString("\n")) +} diff --git a/Task/Natural-sorting/Perl-6/natural-sorting-1.pl6 b/Task/Natural-sorting/Perl-6/natural-sorting-1.pl6 deleted file mode 100644 index 0b910c590d..0000000000 --- a/Task/Natural-sorting/Perl-6/natural-sorting-1.pl6 +++ /dev/null @@ -1,27 +0,0 @@ -# Sort groups of digits in number order. Sort by order of magnitude then lexically. -sub naturally ($a) { $a.lc.subst(/(\d+)/, ->$/ {0~$0.chars.chr~$0},:g) ~"\x0"~$a } - -# Collapse multiple ws characters to a single. -sub collapse ($a) { $a.subst( / ( \s ) $0+ /, -> $/ { $0 }, :g ) } - -# Convert all ws characters to a space. -sub normalize ($a) { $a.subst( / ( \s ) /, ' ', :g ) } - -# Ignore common leading articles for title sorts -sub title ($a) { $a.subst( / :i ^ ( a | an | the ) >> \s* /, '' ) } - -# Decompose ISO-Latin1 glyphs to their base character. -sub latin1_decompose ($a) { - my %tr = < - Æ AE æ ae Þ TH þ th Ð TH ð th ß ss À A Á A  A à A Ä A Å A à a á a - â a ã a ä a å a Ç C ç c È E É E Ê E Ë E è e é e ê e ë e Ì I Í I Î - I Ï I ì i í i î i ï i Ò O Ó O Ô O Õ O Ö O Ø O ò o ó o ô o õ o ö o - ø o Ñ N ñ n Ù U Ú U Û U Ü U ù u ú u û u ü u Ý Y ÿ y ý y - >; - -# Would probably be better implemented as -# $a.trans( [%tr.keys] => [%tr.values] ); -# but the underlying Parrot VM leaks through in current Rakudo. - my $re = '<[' ~ %tr.keys.join('|') ~ ']>'; - $a.subst(/ (<$re>) /, -> $/ { %tr{$0} }, :g) -} diff --git a/Task/Natural-sorting/Perl-6/natural-sorting-2.pl6 b/Task/Natural-sorting/Perl-6/natural-sorting-2.pl6 deleted file mode 100644 index 36ca541575..0000000000 --- a/Task/Natural-sorting/Perl-6/natural-sorting-2.pl6 +++ /dev/null @@ -1,79 +0,0 @@ -my @tests = ( - [ - "Task 1a\nSort while ignoring leading spaces.", - [ - 'ignore leading spaces: 1', ' ignore leading spaces: 4', - ' ignore leading spaces: 3', ' ignore leading spaces: 2' - ], - {.trim} # builtin method. - ], - [ - "Task 1b\nSort while ignoring multiple adjacent spaces.", - [ - 'ignore m.a.s spaces: 3', 'ignore m.a.s spaces: 1', - 'ignore m.a.s spaces: 4', 'ignore m.a.s spaces: 2' - ], - {.&collapse} - ], - [ - "Task 2\nSort with all white space normalized to regular spaces.", - [ - "Normalized\tspaces: 4", "Normalized\xa0spaces: 1", - "Normalized\x20spaces: 2", "Normalized\nspaces: 3" - ], - {.&normalize} - ], - [ - "Task 3\nSort case independently.", - [ - 'caSE INDEPENDENT: 3', 'casE INDEPENDENT: 2', - 'cASE INDEPENDENT: 4', 'case INDEPENDENT: 1' - ], - {.lc} # builtin method - ], - [ - "Task 4\nSort groups of digits in natural number order.", - [ - - ], - {.&naturally} - ], - [ - "Task 5 ( mixed with 1, 2, 3 & 4 )\n" - ~ "Sort titles, normalize white space, collapse multiple spaces to\n" - ~ "single, trim leading white space, ignore common leading articles\n" - ~ 'and sort digit groups in natural order.', - [ - 'The Wind in the Willows 8', ' The 39 Steps 3', - 'The 7th Seal 1', 'Wanda 6', - 'A Fish Called Wanda 5', ' The Wind and the Lion 7', - 'Any Which Way But Loose 4', '12 Monkeys 2' - ], - {.&normalize.&collapse.trim.&title.&naturally} - ], - [ - "Task 6, 7, 8\nMap letters in Latin1 that have accents or decompose to two\n" - ~ 'characters to their base characters for sorting.', - [ - - ], - {.&latin1_decompose.&naturally} - ] -); - - -for @tests -> $case { - my $code_ref = $case.pop; - my @array = $case.pop.list; - say $case.pop, "\n"; - - say "Standard Sort:\n"; - .say for @array.sort; - - say "\nNatural Sort:\n"; - .say for @array.sort: {.$code_ref}; - - say "\n" ~ '*' x 40 ~ "\n"; -} diff --git a/Task/Natural-sorting/Phix/natural-sorting.phix b/Task/Natural-sorting/Phix/natural-sorting.phix new file mode 100644 index 0000000000..dfac6abbdd --- /dev/null +++ b/Task/Natural-sorting/Phix/natural-sorting.phix @@ -0,0 +1,148 @@ +-- +-- demo/rosetta/Natural_sorting.exw +-- +function utf32ch(sequence s) + for i=1 to length(s) do + s[i] = utf8_to_utf32(s[i])[1] + end for + return s +end function + +constant common = {"the","it","to","a","of","is"}, + {al,ac_replacements} = columnize({ + {"Æ","AE"},{"æ","ae"},{"Þ","TH"},{"þ","th"}, + {"Ð","TH"},{"ð","th"},{"ß","ss"},{"�","fi"}, + {"�","fl"},{"",'s'},{"’",'z'}, + {"À",'A'},{"Á",'A'},{"Â",'A'},{"Ã",'A'}, + {"Ä",'A'},{"Å",'A'},{"à",'a'},{"á",'a'}, + {"â",'a'},{"ã",'a'},{"ä",'a'},{"å",'a'}, + {"Ç",'C'},{"ç",'c'},{"È",'E'},{"É",'E'}, + {"Ê",'E'},{"Ë",'E'},{"è",'e'},{"é",'e'}, + {"ê",'e'},{"ë",'e'},{"Ì",'I'},{"Í",'I'}, + {"Î",'I'},{"Ï",'I'},{"ì",'i'},{"í",'i'}, + {"î",'i'},{"ï",'i'},{"Ò",'O'},{"Ó",'O'}, + {"Ô",'O'},{"Õ",'O'},{"Ö",'O'},{"Ø",'O'}, + {"ò",'o'},{"ó",'o'},{"ô",'o'},{"õ",'o'}, + {"ö",'o'},{"ø",'o'},{"Ñ",'N'},{"ñ",'n'}, + {"Ù",'U'},{"Ú",'U'},{"Û",'U'},{"Ü",'U'}, + {"ù",'u'},{"ú",'u'},{"û",'u'},{"ü",'u'}, + {"Ý",'Y'},{"ÿ",'y'},{"ý",'y'}}), + accents_and_ligatures = utf32ch(al) + +function normalise(string s) + sequence utf32 = utf8_to_utf32(s) + sequence res = {} + integer i = 1, ch, prev + for i=1 to length(utf32) do + ch = utf32[i] + if find(ch," \t\r\n\x0b\x0c") then + if length(res)>0 and prev!=' ' then + res &= -1 + end if + prev = ' ' + elsif find(ch,"0123456789") then + if length(res)=0 or prev!='0' then + res &= ch-'0' + else + res[$] = res[$]*10+ch-'0' + end if + prev = '0' + else + object rep = find(ch,accents_and_ligatures) + if rep then + rep = lower(ac_replacements[rep]) + else + rep = lower(ch) + end if + if length(res) and sequence(res[$]) then + res[$] &= rep + else + res = append(res,""&rep) + end if + prev = ch + end if + end for + for i=1 to length(common) do + while 1 do + integer k = find(common[i],res) + if k=0 then exit end if + res[k..k] = {} + if length(res) and res[1]=-1 then + res = res[2..$] + end if + end while + end for + if length(res) and prev=' ' then + res = res[1..$-1] + end if + return res +end function + +sequence tests = { + {" leading spaces: 4", + " leading spaces: 3", + "leading spaces: 2", + " leading spaces: 1"}, + {"adjacent spaces: 3", + "adjacent spaces: 4", + "adjacent spaces: 1", + "adjacent spaces: 2"}, + {"white space: 3-2", + "white\r space: 3-3", + "white\x0cspace: 3-1", + "white\x0bspace: 3+0", + "white\n space: 3+1", + "white\t space: 3+2"}, + {"caSE independent: 3-1", + "cASE independent: 3-2", + "casE independent: 3+0", + "case independent: 3+1"}, + {"foo1000bar99baz9.txt", + "foo100bar99baz0.txt", + "foo100bar10baz0.txt", + "foo1000bar99baz10.txt"}, + {"foo1bar", + "foo100bar", + "foo bar", + "foo1000bar"}, + {"The Wind in the Willows", + "The 40th step more", + "The 39 steps", + "Wanda"}, + {"ignore ý accents: 2-2", + "ignore Ý accents: 2-1", + "ignore y accents: 2+0", + "ignore Y accents: 2+1"}, + {"Ball","Card","above","aether", + "apple","autumn","außen","bald", + "car","e-mail","evoke","nina", + "niño","Æon","Évian","æon"}, + } + +sequence s, n, t, tags + +function natural(integer i, integer j) + return compare(t[i],t[j]) +end function + +for i=1 to length(tests) do + s = tests[i] + n = sort(s) + t = repeat(0,length(s)) + for j=1 to length(s) do + t[j] = normalise(s[j]) + end for + tags = custom_sort(routine_id("natural"),tagset(length(s))) + if i=3 then -- clean up the whitespace mess + for j=1 to length(s) do + s[j] = substitute_all(s[j],{"\r","\x0c","\x0b","\n","\t"},{"\\r","\\x0c","\\x0b","\\n","\\t"}) + n[j] = substitute_all(n[j],{"\r","\x0c","\x0b","\n","\t"},{"\\r","\\x0c","\\x0b","\\n","\\t"}) + end for + end if + printf(1,"%-30s %-30s %-30s\n",{"original","normal","natural"}) + printf(1,"%-30s %-30s %-30s\n",{"========","======","======="}) + for k=1 to length(tags) do + printf(1,"%-30s|%-30s|%-30s\n",{s[k],n[k],s[tags[k]]}) + end for + puts(1,"\n") +end for diff --git a/Task/Natural-sorting/Scheme/natural-sorting.ss b/Task/Natural-sorting/Scheme/natural-sorting.ss new file mode 100644 index 0000000000..28c9b6a7e6 --- /dev/null +++ b/Task/Natural-sorting/Scheme/natural-sorting.ss @@ -0,0 +1,91 @@ +(import (scheme base) + (scheme char) + (scheme write) + (only (srfi 1) drop take-while) + (only (srfi 13) string-drop string-join string-prefix-ci? string-tokenize) + (srfi 132)) + + +;; Natural sort function +(define (natural-sort lst) + ; <1><2> ignores leading, trailing and multiple adjacent spaces + ; by tokenizing on whitespace (all whitespace characters), + ; and joining with a single space + (define (ignore-spaces str) + (string-join (string-tokenize str) " ")) + ; <5> Remove articles from string + (define (drop-articles str) + (define (do-drop articles str) + (cond ((null? articles) + str) + ((string-prefix-ci? (car articles) str) + (string-drop str (string-length (car articles)))) + (else + (do-drop (cdr articles) str)))) + (do-drop '("a " "an " "the ") str)) + ; <4> split string into number/non-number groups + (define (group-digits str) + (let loop ((chars (string->list str)) + (doing-num? (char-numeric? (string-ref str 0))) + (groups '())) + (if (null? chars) + (map (lambda (s) ; convert numbers to actual numbers + (if (char-numeric? (string-ref s 0)) + (string->number s) + s)) + (map list->string groups)) ; leave groups in reverse, as right-most significant + (let ((next-group (take-while (if doing-num? + char-numeric? + (lambda (c) (not (char-numeric? c)))) + chars))) + (loop (drop chars (length next-group)) + (not doing-num?) + (cons next-group groups)))))) + ; + (list-sort + (lambda (a b) ; implements the numeric fields comparison <4> + (let loop ((lft (group-digits (drop-articles (ignore-spaces a)))) + (rgt (group-digits (drop-articles (ignore-spaces b))))) + (cond ((null? lft) ; a is shorter + #t) + ((null? rgt) ; b is shorter + #f) + ((equal? (car lft) (car rgt)) ; if equal, look at next pair + (loop (cdr lft) (cdr rgt))) + ((and (number? (car lft)) ; compare as numbers + (number? (car rgt))) + (< (car lft) (car rgt))) + ((and (string? (car lft)) ; compare as strings + (string? (car rgt))) + (string-ci ignoring case + ((and (number? (car lft)) ; strings before numbers + (string? (car rgt))) + #f) + ((and (string? (car lft)) ; strings before numbers + (number? (car rgt))) + #t)))) + lst)) + +;; run string examples +(define (display-list title lst) + (display title) (newline) + (display "[\n") (for-each (lambda (i) (display i)(newline)) lst) (display "]\n")) + +(for-each + (lambda (title example) + (display title) (newline) + (display-list "Text strings:" example) + (display-list "Normally sorted:" (list-sort string
    diff --git a/Task/Nautical-bell/C/nautical-bell.c b/Task/Nautical-bell/C/nautical-bell.c new file mode 100644 index 0000000000..e57c58c0c3 --- /dev/null +++ b/Task/Nautical-bell/C/nautical-bell.c @@ -0,0 +1,35 @@ +#include +#include +#include + +#define DELAY 3000 + +int main(){ + int i,times; + + time_t t; + struct tm* currentTime; + + while(1){ + time(&t); + currentTime = localtime(&t); + + times = (currentTime->tm_hour%12==0)?12:currentTime->tm_hour%12; + + if(currentTime->tm_min==0 && currentTime->tm_sec==0){ + printf("\nIt is now %d:00 %s. Sounding the bell %d times.",times,(currentTime->tm_hour>11)?"PM":"AM",times); + + for(i=0;itm_min==30 && currentTime->tm_sec==0){ + printf("\nIt is now %d:30 %s. Sounding the bell once.",times,(currentTime->tm_hour>11)?"PM":"AM"); + printf("\a"); + } + } + + return 0; +} diff --git a/Task/Nautical-bell/Kotlin/nautical-bell.kotlin b/Task/Nautical-bell/Kotlin/nautical-bell.kotlin new file mode 100644 index 0000000000..a2f20d98c2 --- /dev/null +++ b/Task/Nautical-bell/Kotlin/nautical-bell.kotlin @@ -0,0 +1,54 @@ +// version 1.1.3 + +import java.text.DateFormat +import java.text.SimpleDateFormat +import java.util.TimeZone + +class NauticalBell: Thread() { + + override fun run() { + val sdf = SimpleDateFormat("HH:mm:ss") + sdf.timeZone = TimeZone.getTimeZone("UTC") + var numBells = 0 + var time = System.currentTimeMillis() + var next = time - (time % (24 * 60 * 60 * 1000)) // midnight + + while (next < time) { + next += 30 * 60 * 1000 // 30 minutes + numBells = 1 + (numBells % 8) + } + + while (true) { + var wait = 100L + time = System.currentTimeMillis() + if ((time - next) >= 0) { + val bells = if (numBells == 1) "bell" else "bells" + val timeString = sdf.format(time) + println("%s : %d %s".format(timeString, numBells, bells)) + next += 30 * 60 * 1000 + wait = next - time + numBells = 1 + (numBells % 8) + } + try { + Thread.sleep(wait) + } + catch (ie: InterruptedException) { + return + } + } + } +} + +fun main(args: Array) { + val bells = NauticalBell() + with (bells) { + setDaemon(true) + start() + try { + join() + } + catch (ie: InterruptedException) { + println(ie.message) + } + } +} diff --git a/Task/Non-continuous-subsequences/C++/non-continuous-subsequences-1.cpp b/Task/Non-continuous-subsequences/C++/non-continuous-subsequences-1.cpp new file mode 100644 index 0000000000..67bebf3e5f --- /dev/null +++ b/Task/Non-continuous-subsequences/C++/non-continuous-subsequences-1.cpp @@ -0,0 +1,15 @@ +/* + * Nigel Galloway, July 19th., 2017 - Yes well is this any better? + */ +class N{ + uint n,i,g,e,l; +public: + N(uint n): n(n-1),i{},g{},e(1),l(n-1){} + bool hasNext(){ + g=(1<0); + } + uint next() {return g;} +}; diff --git a/Task/Non-continuous-subsequences/C++/non-continuous-subsequences-2.cpp b/Task/Non-continuous-subsequences/C++/non-continuous-subsequences-2.cpp new file mode 100644 index 0000000000..ac43cac586 --- /dev/null +++ b/Task/Non-continuous-subsequences/C++/non-continuous-subsequences-2.cpp @@ -0,0 +1,4 @@ +int main(){ + N n(4); + while (n.hasNext()) std::cout << n.next() << "\t* " << std::bitset<4>(n.next()) << std::endl; +} diff --git a/Task/Non-continuous-subsequences/C++/non-continuous-subsequences-3.cpp b/Task/Non-continuous-subsequences/C++/non-continuous-subsequences-3.cpp new file mode 100644 index 0000000000..4006cd73f3 --- /dev/null +++ b/Task/Non-continuous-subsequences/C++/non-continuous-subsequences-3.cpp @@ -0,0 +1,4 @@ +int main(){ + N n(31); + int z{};for (;n.hasNext();++z); std::cout << z << std::endl; +} diff --git a/Task/Non-continuous-subsequences/C++/non-continuous-subsequences.cpp b/Task/Non-continuous-subsequences/C++/non-continuous-subsequences.cpp deleted file mode 100644 index 0ee85f9c37..0000000000 --- a/Task/Non-continuous-subsequences/C++/non-continuous-subsequences.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - Not best code, wrote it really quick. Will add updated code using more C++11 features soon! -*/ - -#include -#include -#include -#include - -int main() { - std::vector sequence = { 0, 1, 2, 3, 4 }; - std::vector work = { 0 }; - std::vector> results; - while (work != sequence) { - bool zeroed = false; - size_t index_zero_started = 0; - for (size_t i = 0; i < work.size(); ++i) { - if (work[i] >= sequence.size()) { - if (i == 0) { - work[i] = 0; - work.push_back(0); - index_zero_started = i; - } else { - ++work[i - 1]; - for (size_t j = i; j < work.size(); ++j) { - work[j] = 0; - } - index_zero_started = i - 1; - } - zeroed = true; - break; - } - } - if (zeroed) { - for (size_t i = index_zero_started + 1; i < work.size(); ++i) { - work[i] = work[i - 1] + 1; - } - } else { - std::vector temp_differences; - std::adjacent_difference(std::begin(work), std::end(work), std::back_inserter(temp_differences)); - if (std::find_if(std::begin(temp_differences) + 1, std::end(temp_differences), - [](const int& n) { return n > 1; }) != std::end(temp_differences)) { - results.push_back(work); - } - ++work.back(); - } - } - std::cout << "Non-continuous subsequences of "; - std::copy(std::begin(sequence), std::end(sequence), std::ostream_iterator(std::cout, " ")); - std::cout << std::endl; - for (auto& e: results) { - std::cout << "- "; - std::copy(std::begin(e), std::end(e), std::ostream_iterator(std::cout, " ")); - std::cout << std::endl; - } - return 0; -} diff --git a/Task/Non-continuous-subsequences/CoffeeScript/non-continuous-subsequences-1.coffee b/Task/Non-continuous-subsequences/CoffeeScript/non-continuous-subsequences-1.coffee deleted file mode 100644 index 083089fd98..0000000000 --- a/Task/Non-continuous-subsequences/CoffeeScript/non-continuous-subsequences-1.coffee +++ /dev/null @@ -1,57 +0,0 @@ -is_contigous_binary = (n) -> - # return true if binary representation of n is - # of the form 1+0+ - # examples: - # 0 true - # 1 true - # 100 true - # 110 true - # 1001 false - # 1010 false - - # special case zero, or you'll get an infinite loop later - return true if n == 0 - - # first remove 0s from end - while n % 2 == 0 - n = n / 2 - - # next, take advantage of the fact that a continuous - # run of 1s would be of the form 2^n - 1 - is_power_of_two(n + 1) - -is_power_of_two = (m) -> - while m % 2 == 0 - m = m / 2 - m == 1 - -seq_from_bitmap = (arr, n) -> - # grabs elements from array according to a bitmap - # e.g. if n == 13 (1101), and arr = ['a', 'b', 'c', 'd'], - # then return ['a', 'c', 'd'] (flipping bits to 1011, so - # that least significant bit comes first) - i = 0 - new_arr = [] - while n > 0 - if n % 2 == 1 - new_arr.push arr[i] - n -= 1 - n /= 2 - i += 1 - new_arr - -non_contig_subsequences = (arr) -> - # Return all subsqeuences from an array that have a "hole" in - # them. The order of the subsequences is not specified here. - - # This algorithm uses binary counting, so it is limited to - # small lists, but large lists would be unwieldy regardless. - bitmasks = [0...Math.pow(2, arr.length)] - (seq_from_bitmap arr, n for n in bitmasks when !is_contigous_binary n) - -arr = [1,2,3,4] -console.log non_contig_subsequences arr -for n in [1..10] - arr = [1..n] - num_solutions = non_contig_subsequences(arr).length - console.log "for n=#{n} there are #{num_solutions} solutions" diff --git a/Task/Non-continuous-subsequences/CoffeeScript/non-continuous-subsequences-2.coffee b/Task/Non-continuous-subsequences/CoffeeScript/non-continuous-subsequences-2.coffee deleted file mode 100644 index 33d7bfd36c..0000000000 --- a/Task/Non-continuous-subsequences/CoffeeScript/non-continuous-subsequences-2.coffee +++ /dev/null @@ -1,16 +0,0 @@ -> coffee non_contig_subseq.coffee -[ [ 1, 3 ], - [ 1, 4 ], - [ 2, 4 ], - [ 1, 2, 4 ], - [ 1, 3, 4 ] ] -for n=1 there are 0 solutions -for n=2 there are 0 solutions -for n=3 there are 1 solutions -for n=4 there are 5 solutions -for n=5 there are 16 solutions -for n=6 there are 42 solutions -for n=7 there are 99 solutions -for n=8 there are 219 solutions -for n=9 there are 466 solutions -for n=10 there are 968 solutions diff --git a/Task/Non-continuous-subsequences/jq/non-continuous-subsequences-1.jq b/Task/Non-continuous-subsequences/Jq/non-continuous-subsequences-1.jq similarity index 100% rename from Task/Non-continuous-subsequences/jq/non-continuous-subsequences-1.jq rename to Task/Non-continuous-subsequences/Jq/non-continuous-subsequences-1.jq diff --git a/Task/Non-continuous-subsequences/jq/non-continuous-subsequences-2.jq b/Task/Non-continuous-subsequences/Jq/non-continuous-subsequences-2.jq similarity index 100% rename from Task/Non-continuous-subsequences/jq/non-continuous-subsequences-2.jq rename to Task/Non-continuous-subsequences/Jq/non-continuous-subsequences-2.jq diff --git a/Task/Non-continuous-subsequences/Kotlin/non-continuous-subsequences.kotlin b/Task/Non-continuous-subsequences/Kotlin/non-continuous-subsequences.kotlin new file mode 100644 index 0000000000..3e5277e3cf --- /dev/null +++ b/Task/Non-continuous-subsequences/Kotlin/non-continuous-subsequences.kotlin @@ -0,0 +1,33 @@ +// version 1.1.2 + +fun ncs(a: Array) { + fun generate(m: Int, k: Int, c: IntArray) { + if (k == m) { + if (c[m - 1] != c[0] + m - 1) { + for (i in 0 until m) print("${a[c[i]]} ") + println() + } + } + else { + for (j in 0 until a.size) { + if (k == 0 || j > c[k - 1]) { + c[k] = j + generate(m, k + 1, c) + } + } + } + } + + for (m in 2 until a.size) { + val c = IntArray(m) + generate(m, 0, c) + } +} + +fun main(args: Array) { + val a = arrayOf(1, 2, 3, 4) + ncs(a) + println() + val ca = arrayOf('a', 'b', 'c', 'd', 'e') + ncs(ca) +} diff --git a/Task/Non-continuous-subsequences/Phix/non-continuous-subsequences.phix b/Task/Non-continuous-subsequences/Phix/non-continuous-subsequences.phix new file mode 100644 index 0000000000..048efc6ded --- /dev/null +++ b/Task/Non-continuous-subsequences/Phix/non-continuous-subsequences.phix @@ -0,0 +1,33 @@ +bool countonly = false +integer count = 0 + +procedure ncs(sequence rest, integer ri=0, sequence taken={}, bool contig=false, bool gap=false) + if ri>=length(rest) then + if contig then + if countonly then + count += 1 + else + ?taken + end if + end if + else + ri += 1 + ncs(rest,ri,taken&rest[ri],gap,gap) + ncs(rest,ri,taken,contig,length(taken)!=0) + end if +end procedure + +ncs({1,2,3}) +?"===" +ncs({1,2,3,4}) +?"===" +countonly = true +atom t0 = time() +sequence s = {} +for i=1 to 20 do + count = 0 + ncs(tagset(i)) + s = append(s,count) +end for +?time()-t0 +?s diff --git a/Task/Non-continuous-subsequences/Pop11/non-continuous-subsequences-1.pop11 b/Task/Non-continuous-subsequences/Pop11/non-continuous-subsequences-1.pop11 deleted file mode 100644 index 7e11154186..0000000000 --- a/Task/Non-continuous-subsequences/Pop11/non-continuous-subsequences-1.pop11 +++ /dev/null @@ -1,24 +0,0 @@ -define ncsubseq(l); - lvars acc = [], gap_started = false, is_continuous = true; - define do_it(l1, l2); - dlocal gap_started; - lvars el, save_is_continuous = is_continuous; - if l2 = [] then - if not(is_continuous) then - cons(l1, acc) -> acc; - endif; - else - front(l2) -> el; - back(l2) -> l2; - not(gap_started) and is_continuous -> is_continuous; - do_it(cons(el, l1), l2); - save_is_continuous -> is_continuous; - not(l1 = []) or gap_started -> gap_started; - do_it(l1, l2); - endif; - enddefine; - do_it([], rev(l)); - acc; -enddefine; - -ncsubseq([1 2 3 4 5]) => diff --git a/Task/Non-continuous-subsequences/Pop11/non-continuous-subsequences-2.pop11 b/Task/Non-continuous-subsequences/Pop11/non-continuous-subsequences-2.pop11 deleted file mode 100644 index 2f3e37f3cc..0000000000 --- a/Task/Non-continuous-subsequences/Pop11/non-continuous-subsequences-2.pop11 +++ /dev/null @@ -1,2 +0,0 @@ -[[1 3] [1 4] [2 4] [1 2 4] [1 3 4] [1 5] [2 5] [1 2 5] [3 5] [1 3 5] - [2 3 5] [1 2 3 5] [1 4 5] [2 4 5] [1 2 4 5] [1 3 4 5]] diff --git a/Task/Non-continuous-subsequences/Zkl/non-continuous-subsequences-1.zkl b/Task/Non-continuous-subsequences/Zkl/non-continuous-subsequences-1.zkl new file mode 100644 index 0000000000..039c2d0d7c --- /dev/null +++ b/Task/Non-continuous-subsequences/Zkl/non-continuous-subsequences-1.zkl @@ -0,0 +1,9 @@ +fcn non_continuous_subsequences(ary){ + pwerSet(ary).filter(fcn(list){(not isContinuous(list)) }) +} +fcn isContinuous(ary){ + if(ary.len()<2) return(True); + foreach n in (ary.len()-1){ if(1+ary[n]!=ary[n+1]) return(False); } + return(True); +} +non_continuous_subsequences(T(1,2,3,4)).println(); diff --git a/Task/Non-continuous-subsequences/Zkl/non-continuous-subsequences-2.zkl b/Task/Non-continuous-subsequences/Zkl/non-continuous-subsequences-2.zkl new file mode 100644 index 0000000000..6698cd61b8 --- /dev/null +++ b/Task/Non-continuous-subsequences/Zkl/non-continuous-subsequences-2.zkl @@ -0,0 +1,4 @@ +fcn pwerSet(list){ + (0).pump(list.len(),List,List,Utils.Helpers.pickNFrom.fp1(list), + T(T,Void.Write,Void.Write) ) .append(list) +} diff --git a/Task/Non-continuous-subsequences/Zkl/non-continuous-subsequences-3.zkl b/Task/Non-continuous-subsequences/Zkl/non-continuous-subsequences-3.zkl new file mode 100644 index 0000000000..bce83eb30b --- /dev/null +++ b/Task/Non-continuous-subsequences/Zkl/non-continuous-subsequences-3.zkl @@ -0,0 +1,5 @@ +fcn brokenSubsequences(str){ + pwerSet(str.split("")).apply("concat") + .filter('wrap(substr){ (not str.holds(substr)) }) +} +brokenSubsequences("1234").println(); diff --git a/Task/Non-decimal-radices-Convert/AppleScript/non-decimal-radices-convert-1.applescript b/Task/Non-decimal-radices-Convert/AppleScript/non-decimal-radices-convert-1.applescript new file mode 100644 index 0000000000..dda467e716 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/AppleScript/non-decimal-radices-convert-1.applescript @@ -0,0 +1,107 @@ +-- toBase :: Int -> Int -> String +on toBase(intBase, n) + if (intBase < 36) and (intBase > 0) then + inBaseDigits(items 1 thru intBase of "0123456789abcdefghijklmnopqrstuvwxyz", n) + else + "not defined for base " & (n as string) + end if +end toBase + + +-- inBaseDigits :: String -> Int -> [String] +on inBaseDigits(strDigits, n) + set intBase to length of strDigits + + script nextDigit + on lambda(residue) + set {divided, remainder} to quotRem(residue, intBase) + + {valid:divided > 0, value:(item (remainder + 1) of strDigits), new:divided} + end lambda + end script + + reverse of unfoldr(nextDigit, n) as string +end inBaseDigits + + + +-- OTHER FUNCTIONS DERIVABLE FROM inBaseDigits + +-- inUpperHex :: Int -> String +on inUpperHex(n) + inBaseDigits("0123456789ABCDEF", n) +end inUpperHex + +-- inDevanagariDecimal :: Int -> String +on inDevanagariDecimal(n) + inBaseDigits("०१२३४५६७८९", n) +end inDevanagariDecimal + +-- TEST +on run + script + on lambda(x) + {{binary:toBase(2, x), octal:toBase(8, x), hex:toBase(16, x)}, ¬ + {upperHex:inUpperHex(x), dgDecimal:inDevanagariDecimal(x)}} + end lambda + end script + + map(result, [255, 240]) +end run + + +-- GENERIC FUNCTIONS + +-- unfoldr :: (b -> Maybe (a, b)) -> b -> [a] +on unfoldr(f, v) + set mf to mReturn(f) + set lst to {} + set recM to mf's lambda(v) + repeat while (valid of recM) is true + set end of lst to value of recM + set recM to mf's lambda(new of recM) + end repeat + lst & value of recM +end unfoldr + +-- quotRem :: Integral a => a -> a -> (a, a) +on quotRem(m, n) + {m div n, m mod n} +end quotRem + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to lambda(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property lambda : f + end script + end if +end mReturn + +-- until :: (a -> Bool) -> (a -> a) -> a -> a +on |until|(p, f, x) + set mp to mReturn(p) + set v to x + + tell mReturn(f) + repeat until mp's lambda(v) + set v to lambda(v) + end repeat + end tell + return v +end |until| diff --git a/Task/Non-decimal-radices-Convert/AppleScript/non-decimal-radices-convert-2.applescript b/Task/Non-decimal-radices-Convert/AppleScript/non-decimal-radices-convert-2.applescript new file mode 100644 index 0000000000..34c92a9212 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/AppleScript/non-decimal-radices-convert-2.applescript @@ -0,0 +1,2 @@ +{{{binary:"11111111", octal:"377", hex:"ff"}, {upperHex:"FF", dgDecimal:"२५५"}}, +{{binary:"11110000", octal:"360", hex:"f0"}, {upperHex:"F0", dgDecimal:"२४०"}}} diff --git a/Task/Non-decimal-radices-Convert/Haskell/non-decimal-radices-convert-4.hs b/Task/Non-decimal-radices-Convert/Haskell/non-decimal-radices-convert-4.hs new file mode 100644 index 0000000000..93c0478506 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Haskell/non-decimal-radices-convert-4.hs @@ -0,0 +1,52 @@ +import Data.List (unfoldr) +import Data.Char (intToDigit) + +inBaseDigits :: [Char] -> Int -> String +inBaseDigits ds n = + let base = length ds + in reverse $ + unfoldr + (\x -> + (if x > 0 + then let (d, r) = quotRem x base + in Just (ds !! r, d) + else Nothing)) + n + +inLowerHex :: Int -> String +inLowerHex = inBaseDigits "0123456789abcdef" + +inUpperHex :: Int -> String +inUpperHex = inBaseDigits "0123456789ABCDEF" + +inBinary :: Int -> String +inBinary = inBaseDigits "01" + +inOctal :: Int -> String +inOctal = inBaseDigits "01234567" + +inDevanagariDecimal :: Int -> String +inDevanagariDecimal = inBaseDigits "०१२३४५६७८९" + +inHinduArabicDecimal :: Int -> String +inHinduArabicDecimal = inBaseDigits "٠١٢٣٤٥٦٧٨٩" + +toBase :: Int -> Int -> String +toBase intBase n = + if (intBase < 36) && (intBase > 0) + then inBaseDigits (take intBase (['0' .. '9'] ++ ['a' .. 'z'])) n + else [] + +main :: IO () +main = + mapM_ putStrLn $ + [ inLowerHex + , inUpperHex + , inBinary + , inOctal + , toBase 16 + , toBase 2 + , inDevanagariDecimal + , inHinduArabicDecimal + ] <*> + [254] diff --git a/Task/Non-decimal-radices-Convert/JavaScript/non-decimal-radices-convert-4.js b/Task/Non-decimal-radices-Convert/JavaScript/non-decimal-radices-convert-4.js new file mode 100644 index 0000000000..01d723c784 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/JavaScript/non-decimal-radices-convert-4.js @@ -0,0 +1,93 @@ +(() => { + 'use strict'; + + // toBase :: Int -> Int -> String + const toBase = (intBase, n) => + intBase < 36 && intBase > 0 ? + inBaseDigits('0123456789abcdef'.substr(0, intBase), n) : []; + + + // inBaseDigits :: String -> Int -> [String] + const inBaseDigits = (digits, n) => { + const intBase = digits.length; + + return unfoldr(maybeResidue => { + const [divided, remainder] = quotRem(maybeResidue.new, intBase); + + return { + valid: divided > 0, + value: digits[remainder], + new: divided + }; + }, n) + .reverse() + .join(''); + }; + + + // GENERIC FUNCTIONS + + // unfoldr :: (b -> Maybe (a, b)) -> b -> [a] + const unfoldr = (mf, v) => { + var xs = []; + return (until( + m => !m.valid, + m => { + const m2 = mf(m); + return ( + xs = xs.concat(m2.value), + m2 + ); + }, { + valid: true, + value: v, + new: v, + } + ), xs); + }; + + // curry :: ((a, b) -> c) -> a -> b -> c + const curry = f => a => b => f(a, b); + + // until :: (a -> Bool) -> (a -> a) -> a -> a + const until = (p, f, x) => { + let v = x; + while (!p(v)) v = f(v); + return v; + } + + // quotRem :: Integral a => a -> a -> (a, a) + const quotRem = (m, n) => [Math.floor(m / n), m % n]; + + // show :: a -> String + const show = x => JSON.stringify(x, null, 2); + + + // OTHER FUNCTIONS DERIVABLE FROM inBaseDigits + + // inLowerHex :: Int -> String + const inLowerHex = curry(inBaseDigits)('0123456789abcdef'); + + /// inUpperHex :: Int -> String + const inUpperHex = curry(inBaseDigits)('0123456789ABCDEF'); + + // inOctal :: Int -> String + const inOctal = curry(inBaseDigits)('01234567'); + + // inDevanagariDecimal :: Int -> String + const inDevanagariDecimal = curry(inBaseDigits)('०१२३४५६७८९'); + + + // TESTS + // testNumber :: [Int] + const testNumbers = [255, 240]; + + return testNumbers.map(n => show({ + binary: toBase(2, n), + base5: toBase(5, n), + hex: toBase(16, n), + upperHex: inUpperHex(n), + octal: inOctal(n), + devanagariDecimal: inDevanagariDecimal(n) + })); +})(); diff --git a/Task/Non-decimal-radices-Convert/jq/non-decimal-radices-convert-1.jq b/Task/Non-decimal-radices-Convert/Jq/non-decimal-radices-convert-1.jq similarity index 91% rename from Task/Non-decimal-radices-Convert/jq/non-decimal-radices-convert-1.jq rename to Task/Non-decimal-radices-Convert/Jq/non-decimal-radices-convert-1.jq index 38708e77c1..33f502a38c 100644 --- a/Task/Non-decimal-radices-Convert/jq/non-decimal-radices-convert-1.jq +++ b/Task/Non-decimal-radices-Convert/Jq/non-decimal-radices-convert-1.jq @@ -10,7 +10,7 @@ def convert(base): end end; -# input string is converted from "base" to an integer, wihtin limits +# input string is converted from "base" to an integer, within limits # of the underlying arithmetic operations, and without error-checking: def to_i(base): explode diff --git a/Task/Non-decimal-radices-Convert/jq/non-decimal-radices-convert-2.jq b/Task/Non-decimal-radices-Convert/Jq/non-decimal-radices-convert-2.jq similarity index 100% rename from Task/Non-decimal-radices-Convert/jq/non-decimal-radices-convert-2.jq rename to Task/Non-decimal-radices-Convert/Jq/non-decimal-radices-convert-2.jq diff --git a/Task/Non-decimal-radices-Convert/Julia/non-decimal-radices-convert.julia b/Task/Non-decimal-radices-Convert/Julia/non-decimal-radices-convert.julia new file mode 100644 index 0000000000..15d21d6e10 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Julia/non-decimal-radices-convert.julia @@ -0,0 +1,7 @@ +# 26 in base 16 or 2 +base(16, 26) +base(2, 26) + +# Parse to integer +parse(Int, "1a", 16) +parse(Int, "101101", 2) diff --git a/Task/Non-decimal-radices-Convert/Kotlin/non-decimal-radices-convert.kotlin b/Task/Non-decimal-radices-Convert/Kotlin/non-decimal-radices-convert.kotlin new file mode 100644 index 0000000000..2e5cb734ad --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Kotlin/non-decimal-radices-convert.kotlin @@ -0,0 +1,45 @@ +// version 1.0.6 + +fun min(x: Int, y: Int) = if (x < y) x else y + +fun convertToBase(n: Int, b: Int): String { + if (n < 2 || b < 2 || b == 10 || b > 36) return n.toString() // leave as decimal + val sb = StringBuilder() + var digit: Int + var nn = n + while (nn > 0) { + digit = nn % b + if (digit < 10) sb.append(digit) + else sb.append((digit + 87).toChar()) + nn /= b + } + return sb.reverse().toString() +} + +fun convertToDecimal(s: String, b: Int): Int { + if (b !in 2..36) throw IllegalArgumentException("Base must be between 2 and 36") + if (b == 10) return s.toInt() + val t = s.toLowerCase() + var result = 0 + var digit: Int + var multiplier = 1 + for (i in t.length - 1 downTo 0) { + digit = -1 + if (t[i] >= '0' && t[i] <= min(57, 47 + b).toChar()) + digit = t[i].toInt() - 48 + else if (b > 10 && t[i] >= 'a' && t[i] <= min(122, 87 + b).toChar()) + digit = t[i].toInt() - 87 + if (digit == -1) throw IllegalArgumentException("Invalid digit present") + if (digit > 0) result += multiplier * digit + multiplier *= b + } + return result +} + +fun main(args: Array) { + for (b in 2..36) { + val s = convertToBase(36, b) + val f = "%2d".format(b) + println("36 base $f = ${s.padEnd(6)} -> base $f = ${convertToDecimal(s, b)}") + } +} diff --git a/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert-1.rexx b/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert-1.rexx deleted file mode 100644 index b09919bbb1..0000000000 --- a/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert-1.rexx +++ /dev/null @@ -1,12 +0,0 @@ - ┌────────────────────────────────────────────────────────────────────┐ -┌─┘ Input to this program (bases must be positive integers > 1): └─┐ -│ │ -│ x is required (it may have a sign). │ -│ toBase the base to convert X to. │ -│ inBase the base X is expressed in. │ -│ │ -│ If X has a leading sign, it is maintained (kept) after conversion. │ -│ │ -│ toBase or inBase can be a comma (,) which causes the default │ -└─┐ of 10 to be used. The limits of bases are: 2 ──► 90. ┌─┘ - └────────────────────────────────────────────────────────────────────┘ diff --git a/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert-2.rexx b/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert-2.rexx deleted file mode 100644 index bc81c530d7..0000000000 --- a/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert-2.rexx +++ /dev/null @@ -1,37 +0,0 @@ -/*REXX pgm converts integers from one base to another (base 2 ──► 90). */ -@abc = 'abcdefghijklmnopqrstuvwxyz' /*the lowercase (Latin) alphabet.*/ -parse upper var @abc @abcU /*uppercase a version of @abc. */ -@@ = 0123456789 || @abc || @abcU /*prefix 'em with numeric digits.*/ -@@ = @@'<>[]{}()?~!@#$%^&*_=|\/;:¢¬≈' /*add some special chars as well.*/ - /* [↑] all chars must be viewable*/ -numeric digits 3000 /*what da hey, support gihugeics.*/ -maxB=length(@@) /*max base (radix) supported here*/ -parse arg x toB inB 1 ox . 1 sigX 2 x2 . /*get: 3 args, origX, sign···*/ -if pos(sigX,"+-")\==0 then x=x2 /*Does X have a leading sign? */ - else sigX= /*Nope. No leading sign for X. */ -if x=='' then call erm /*if no X number, issue error.*/ -if toB=='' | toB=="," then toB=10 /*if skipped, assume default (10)*/ -if inB=='' | inB=="," then inB=10 /* " " " " " */ -if inB<2 | inb>maxB | \datatype(inB,'W') then call erb 'inBase ' inB -if toB<2 | toB>maxB | \datatype(toB,'W') then call erb 'toBase ' toB -#=0 /*result of converted X (base 10)*/ - do j=1 for length(x) /*convert X, base inB ──► base 10*/ - ?=substr(x,j,1) /*pick off a numeral/digit from X*/ - _=pos(?, @@) /*calculate this numeral's value.*/ - if _==0 | _>inB then call erd x /*_ character an illegal numeral?*/ - #=#*inB+_-1 /*build a new number, dig by dig.*/ - end /*j*/ /* [↑] this also verifies digits*/ -y= /*the value of X in base B. */ - do while # >= toB /*convert #, base 10 ──► base toB*/ - y=substr(@@, (#//toB)+1, 1)y /*construct the output number. */ - #=#%toB /*··· and whittle # down also. */ - end /*while*/ /* [↑] process leaves a residual*/ - /* [↓] Y is the residual*/ -y=sigX || substr(@@, #+1, 1)y /*prepend the sign if it existed.*/ -say ox "(base" inB')' center('is',20) y "(base" toB')' -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────one─liner subroutines───────────────*/ -erb: call ser 'illegal' arg(1)", it must be in the range: 2──►"maxB -erd: call ser 'illegal digit/numeral ['?"] in: " x -erm: call ser 'no argument specified.' -ser: say; say '***error!***'; say arg(1); exit 13 diff --git a/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-1.rb b/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-1.rb deleted file mode 100644 index 11502afb64..0000000000 --- a/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-1.rb +++ /dev/null @@ -1,2 +0,0 @@ -s = 26.to_s(16) # returns the string 1a -i = '1a'.to_i(16) # returns the integer 26 diff --git a/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-2.rb b/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-2.rb deleted file mode 100644 index abf9962fea..0000000000 --- a/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-2.rb +++ /dev/null @@ -1 +0,0 @@ -"59".to_i(7) # returns 5, but this is probably not what you wanted diff --git a/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-3.rb b/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-3.rb deleted file mode 100644 index 65d6b53405..0000000000 --- a/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-3.rb +++ /dev/null @@ -1,32 +0,0 @@ -module BaseConvert - DIGITS = [*"0".."9", *"a".."z"] - - def baseconvert(str, basefrom, baseto) - dec2base(base2dec(str, basefrom), baseto) - end - - def base2dec(str, base) - raise ArgumentError, "base is invalid" unless base.between?(2, DIGITS.length) - str.to_s.downcase.each_char.inject(0) do |res, c| - idx = DIGITS[0,base].index(c) - idx.nil? and raise ArgumentError, "invalid base-#{base} digit: #{c}" - res = res * base + idx - end - end - - def dec2base(n, base) - return "0" if n == 0 - raise ArgumentError, "base is invalid" unless base.between?(2, DIGITS.length) - res = [] - while n > 0 - n, r = n.divmod(base) - res.unshift(DIGITS[r]) - end - res.join - end -end - -include BaseConvert -p dec2base(26, 16) # => "1a" -p base2dec("1a", 16) # => 26 -p baseconvert("107h", 23, 7) # => "50664" diff --git a/Task/Non-decimal-radices-Convert/Zkl/non-decimal-radices-convert-1.zkl b/Task/Non-decimal-radices-Convert/Zkl/non-decimal-radices-convert-1.zkl new file mode 100644 index 0000000000..27114bda2f --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Zkl/non-decimal-radices-convert-1.zkl @@ -0,0 +1,2 @@ +(26).toString(16) //--> "1a" +"1a".toInt(16) //-->26 diff --git a/Task/Non-decimal-radices-Convert/Zkl/non-decimal-radices-convert-2.zkl b/Task/Non-decimal-radices-Convert/Zkl/non-decimal-radices-convert-2.zkl new file mode 100644 index 0000000000..74223de749 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Zkl/non-decimal-radices-convert-2.zkl @@ -0,0 +1 @@ +"%x %,.2B".fmt(26,26) //-->"1a 1|1010" diff --git a/Task/Non-decimal-radices-Input/Julia/non-decimal-radices-input-1.julia b/Task/Non-decimal-radices-Input/Julia/non-decimal-radices-input-1.julia new file mode 100644 index 0000000000..6827bbfc9b --- /dev/null +++ b/Task/Non-decimal-radices-Input/Julia/non-decimal-radices-input-1.julia @@ -0,0 +1,6 @@ +# Version 5.2 +txt = "100" +for base = 2:21 + base10 = parse(Int, txt, base) + println("String $txt in base $base is $base10 in base 10") +end diff --git a/Task/Non-decimal-radices-Input/Julia/non-decimal-radices-input-2.julia b/Task/Non-decimal-radices-Input/Julia/non-decimal-radices-input-2.julia new file mode 100644 index 0000000000..976c666357 --- /dev/null +++ b/Task/Non-decimal-radices-Input/Julia/non-decimal-radices-input-2.julia @@ -0,0 +1,4 @@ +@show parse(Int, "123459") +@show parse(Int, "0xabcf123") +@show parse(Int, "0o7651") +@show parse(Int, "0b101011001") diff --git a/Task/Non-decimal-radices-Input/Kotlin/non-decimal-radices-input.kotlin b/Task/Non-decimal-radices-Input/Kotlin/non-decimal-radices-input.kotlin new file mode 100644 index 0000000000..df6cc0652c --- /dev/null +++ b/Task/Non-decimal-radices-Input/Kotlin/non-decimal-radices-input.kotlin @@ -0,0 +1,8 @@ +// version 1.1.2 + +fun main(args: Array) { + val s = "100" + val bases = intArrayOf(2, 8, 10, 16, 19, 36) + for (base in bases) + println("$s in base ${"%2d".format(base)} is ${s.toInt(base)}") +} diff --git a/Task/Non-decimal-radices-Input/PowerShell/non-decimal-radices-input-1.psh b/Task/Non-decimal-radices-Input/PowerShell/non-decimal-radices-input-1.psh new file mode 100644 index 0000000000..c90bfade04 --- /dev/null +++ b/Task/Non-decimal-radices-Input/PowerShell/non-decimal-radices-input-1.psh @@ -0,0 +1,79 @@ +function Select-NumberFromString +{ + [CmdletBinding(DefaultParameterSetName="Decimal")] + [OutputType([PSCustomObject])] + Param + ( + [Parameter(Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true, + Position=0)] + [string] + $InputObject, + + [Parameter(ParameterSetName="Decimal")] + [Alias("d","Dec")] + [switch] + $Decimal, + + [Parameter(ParameterSetName="Hexadecimal")] + [Alias("h","Hex")] + [switch] + $Hexadecimal, + + [Parameter(ParameterSetName="Octal")] + [Alias("o","Oct")] + [switch] + $Octal, + + [Parameter(ParameterSetName="Binary")] + [Alias("b","Bin")] + [switch] + $Binary + ) + + Begin + { + switch ($PSCmdlet.ParameterSetName) + { + "Decimal" {$base = 10; $pattern = '[+-]?\b[0-9]+\b'; break} + "Hexadecimal" {$base = 16; $pattern = '\b[0-9A-F]+\b' ; break} + "Octal" {$base = 8; $pattern = '\b[0-7]+\b' ; break} + "Binary" {$base = 2; $pattern = '\b[01]+\b' ; break} + "Default" {$base = 10; $pattern = '[+-]?\b[0-9]+\b'; break} + } + } + Process + { + foreach ($object in $InputObject) + { + if ($object -match $pattern) + { + $string = $Matches[0] + } + else + { + $string = $null + } + + + try + { + $value = [Convert]::ToInt32($string, $base) + } + catch + { + $value = $null + } + + [PSCustomObject]@{ + Number = $value + String = $string + Base = $base + IsNumber = $value -is [int] + InputString = $object + } + + } + } +} diff --git a/Task/Non-decimal-radices-Input/PowerShell/non-decimal-radices-input-2.psh b/Task/Non-decimal-radices-Input/PowerShell/non-decimal-radices-input-2.psh new file mode 100644 index 0000000000..fbdb7baf21 --- /dev/null +++ b/Task/Non-decimal-radices-Input/PowerShell/non-decimal-radices-input-2.psh @@ -0,0 +1,7 @@ +$file = @' +John Doe abc1 K2hdystkrs +Jane Doe xyz2 Ew3jtdkufy +Joe Blow def3 Ouy1ttluyl +'@ -split [Environment]::NewLine + +$file | Select-NumberFromString -Hexadecimal | Format-Table diff --git a/Task/Non-decimal-radices-Input/REXX/non-decimal-radices-input.rexx b/Task/Non-decimal-radices-Input/REXX/non-decimal-radices-input.rexx index 28a6519d16..70ec79024c 100644 --- a/Task/Non-decimal-radices-Input/REXX/non-decimal-radices-input.rexx +++ b/Task/Non-decimal-radices-Input/REXX/non-decimal-radices-input.rexx @@ -25,7 +25,7 @@ bb=123. /*the same can be said for the rest of 'em.*/ cc=+123 dd=' + 123' ee=0000123 -ff=1.23e+1 +ff=1.23e+2 gg=001.23E0002 hh=1230e-1 ii=122.999999999999999999999999999999999 /*assuming NUMERIC DIGITS 9 */ diff --git a/Task/Non-decimal-radices-Input/Zkl/non-decimal-radices-input.zkl b/Task/Non-decimal-radices-Input/Zkl/non-decimal-radices-input.zkl new file mode 100644 index 0000000000..979d58dbfa --- /dev/null +++ b/Task/Non-decimal-radices-Input/Zkl/non-decimal-radices-input.zkl @@ -0,0 +1,6 @@ +fcn b2b(base){ + ns:=[20..30].pump(List,T("toString",base)); + ns.println(); + ns.pump(List,T("toInt",base)).println("\n") +} +b2b(2); b2b(10); b2b(16); b2b(19); diff --git a/Task/Non-decimal-radices-Output/ALGOL-W/non-decimal-radices-output.alg b/Task/Non-decimal-radices-Output/ALGOL-W/non-decimal-radices-output.alg new file mode 100644 index 0000000000..4563941652 --- /dev/null +++ b/Task/Non-decimal-radices-Output/ALGOL-W/non-decimal-radices-output.alg @@ -0,0 +1,4 @@ +begin + % print some numbers in hex % + for i := 0 until 20 do write( intbase16( i ) ) +end. diff --git a/Task/Non-decimal-radices-Output/Haskell/non-decimal-radices-output-3.hs b/Task/Non-decimal-radices-Output/Haskell/non-decimal-radices-output-3.hs new file mode 100644 index 0000000000..81e83ebe06 --- /dev/null +++ b/Task/Non-decimal-radices-Output/Haskell/non-decimal-radices-output-3.hs @@ -0,0 +1,40 @@ +import Data.Monoid ((<>)) +import Data.Array (Array, listArray, (!)) +import Data.List (unfoldr, transpose, intercalate) + +-- ARBITRARY RADICES ---------------------------------------------------------- +bases :: [Int] +bases = abs <$> [2, 7, 8, 10, 12, 16, 32] + +tableRows :: [[String]] +tableRows = ((([baseDigits] <*> bases) <*>) . return) <$> [1 .. 33] + +digits :: Array Int Char +digits = listArray (0, 35) (['0' .. '9'] <> ['A' .. 'Z']) + +baseDigits :: Int -> Int -> String +baseDigits base + | base > 36 = const "Needs glyphs beyond Z" + | otherwise = reverse . unfoldr remQuot + where + remQuot 0 = Nothing + remQuot n = + let (q, r) = quotRem n base + in Just (digits ! r, q) + +-- TEST AND TABULATION--------------------------------------------------------- +table :: String -> [[String]] -> [String] +table delim rows = + intercalate delim <$> + transpose + ((\col -> + let width = maximum (length <$> col) + justifyRight n c s = drop (length s) (replicate n c <> s) + in justifyRight width ' ' <$> col) <$> + transpose rows) + +main :: IO () +main = + mapM_ + putStrLn + (table " " (([(show <$>), (const "----" <$>)] <*> [bases]) <> tableRows)) diff --git a/Task/Non-decimal-radices-Output/Icon/non-decimal-radices-output.icon b/Task/Non-decimal-radices-Output/Icon/non-decimal-radices-output.icon index 88a1e91302..21a3e328e3 100644 --- a/Task/Non-decimal-radices-Output/Icon/non-decimal-radices-output.icon +++ b/Task/Non-decimal-radices-Output/Icon/non-decimal-radices-output.icon @@ -1,4 +1,4 @@ -rocedure main() +procedure main() write("Non-decimal radices/Output") every i := 255 | 2 | 5 | 16 do { printf("%%d = %d\n",i) # integer format diff --git a/Task/Non-decimal-radices-Output/Kotlin/non-decimal-radices-output.kotlin b/Task/Non-decimal-radices-Output/Kotlin/non-decimal-radices-output.kotlin new file mode 100644 index 0000000000..ed9b6cc4f5 --- /dev/null +++ b/Task/Non-decimal-radices-Output/Kotlin/non-decimal-radices-output.kotlin @@ -0,0 +1,12 @@ +// version 1.1.2 + +fun main(args: Array) { + val bases = intArrayOf(2, 8, 10, 16, 19, 36) + for (base in bases) print("%6s".format(base)) + println() + println("-".repeat(6 * bases.size)) + for (i in 0..35) { + for (base in bases) print("%6s".format(i.toString(base))) + println() + } +} diff --git a/Task/Non-decimal-radices-Output/Ring/non-decimal-radices-output.ring b/Task/Non-decimal-radices-Output/Ring/non-decimal-radices-output.ring new file mode 100644 index 0000000000..e35db044f2 --- /dev/null +++ b/Task/Non-decimal-radices-Output/Ring/non-decimal-radices-output.ring @@ -0,0 +1,11 @@ +# Project : Editing Non Decimal radices/Output +# Date : 2017/09/15 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +see string(0) + nl +see string(123456789) + nl +see string(-987654321) + nl + +see upper(hex(43981)) + nl +see upper(hex(-1)) + nl diff --git a/Task/Non-decimal-radices-Output/Zkl/non-decimal-radices-output-1.zkl b/Task/Non-decimal-radices-Output/Zkl/non-decimal-radices-output-1.zkl new file mode 100644 index 0000000000..781af5510a --- /dev/null +++ b/Task/Non-decimal-radices-Output/Zkl/non-decimal-radices-output-1.zkl @@ -0,0 +1,3 @@ +const N=16; +var fmt=[2..N].pump(String,"%%5.%dB".fmt); // %5.2B%5.3B%5.4B%5.5B ... +foreach n in (17){fmt.fmt(n.pump(N,List,n.fp(n)).xplode()).println()} diff --git a/Task/Non-decimal-radices-Output/Zkl/non-decimal-radices-output-2.zkl b/Task/Non-decimal-radices-Output/Zkl/non-decimal-radices-output-2.zkl new file mode 100644 index 0000000000..63de03cf44 --- /dev/null +++ b/Task/Non-decimal-radices-Output/Zkl/non-decimal-radices-output-2.zkl @@ -0,0 +1 @@ +(100).toString(36) //-->"2s" diff --git a/Task/Non-decimal-radices-Output/Zkl/non-decimal-radices-output-3.zkl b/Task/Non-decimal-radices-Output/Zkl/non-decimal-radices-output-3.zkl new file mode 100644 index 0000000000..0fcc1c14a1 --- /dev/null +++ b/Task/Non-decimal-radices-Output/Zkl/non-decimal-radices-output-3.zkl @@ -0,0 +1,3 @@ +"%,.2B".fmt(1234567) //-->"1|0010|1101|0110|1000|0111" +"%,d".fmt(1234567) //-->"1,234,567" +"%,x".fmt(1234567) //-->"12|d6|87" diff --git a/Task/Nth-root/Bc/nth-root.bc b/Task/Nth-root/Bc/nth-root.bc new file mode 100644 index 0000000000..13089a4cf9 --- /dev/null +++ b/Task/Nth-root/Bc/nth-root.bc @@ -0,0 +1,30 @@ +/* Take the nth root of 'a' (a positive real number). + * 'n' must be an integer. + * Result will have 'd' digits after the decimal point. + */ +define r(a, n, d) { + auto e, o, x, y, z + + if (n == 0) return(1) + if (a == 0) return(0) + + o = scale + scale = d + e = 1 / 10 ^ d + + if (n < 0) { + n = -n + a = 1 / a + } + + x = 1 + while (1) { + y = ((n - 1) * x + a / x ^ (n - 1)) / n + z = x - y + if (z < 0) z = -z + if (z < e) break + x = y + } + scale = o + return(y) +} diff --git a/Task/Nth-root/jq/nth-root-1.jq b/Task/Nth-root/Jq/nth-root-1.jq similarity index 100% rename from Task/Nth-root/jq/nth-root-1.jq rename to Task/Nth-root/Jq/nth-root-1.jq diff --git a/Task/Nth-root/jq/nth-root-2.jq b/Task/Nth-root/Jq/nth-root-2.jq similarity index 100% rename from Task/Nth-root/jq/nth-root-2.jq rename to Task/Nth-root/Jq/nth-root-2.jq diff --git a/Task/Nth-root/jq/nth-root-3.jq b/Task/Nth-root/Jq/nth-root-3.jq similarity index 100% rename from Task/Nth-root/jq/nth-root-3.jq rename to Task/Nth-root/Jq/nth-root-3.jq diff --git a/Task/Nth-root/Kotlin/nth-root.kotlin b/Task/Nth-root/Kotlin/nth-root.kotlin new file mode 100644 index 0000000000..cdd6d9663e --- /dev/null +++ b/Task/Nth-root/Kotlin/nth-root.kotlin @@ -0,0 +1,21 @@ +// version 1.0.6 + +fun nthRoot(x: Double, n: Int): Double { + if (n < 2) throw IllegalArgumentException("n must be more than 1") + if (x <= 0.0) throw IllegalArgumentException("x must be positive") + val np = n - 1 + fun iter(g: Double) = (np * g + x / Math.pow(g, np.toDouble())) / n + var g1 = x + var g2 = iter(g1) + while (g1 != g2) { + g1 = iter(g1) + g2 = iter(iter(g2)) + } + return g1 +} + +fun main(args: Array) { + val numbers = arrayOf(1728.0 to 3, 1024.0 to 10, 2.0 to 2) + for (number in numbers) + println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}") +} diff --git a/Task/Nth-root/Lua/nth-root.lua b/Task/Nth-root/Lua/nth-root.lua index d0b7bc481a..71d7245e66 100644 --- a/Task/Nth-root/Lua/nth-root.lua +++ b/Task/Nth-root/Lua/nth-root.lua @@ -1,3 +1,3 @@ -function nth_root(num,root) +function nroot(root, num) return num^(1/root) end diff --git a/Task/Nth-root/Phix/nth-root.phix b/Task/Nth-root/Phix/nth-root.phix new file mode 100644 index 0000000000..87a104eb21 --- /dev/null +++ b/Task/Nth-root/Phix/nth-root.phix @@ -0,0 +1,33 @@ +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 +atom 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 {y,n,x,power(y,1/n)} +end function + +?nth_root(1024,10) +?nth_root(27,3) +?nth_root(2,2) +?nth_root(5642,125) +--?nth_root(7,0.5) -- needs power(), not pow_() +?nth_root(4913,3) +?nth_root(8,3) +?nth_root(16,2) +?nth_root(16,4) +?nth_root(125,3) +?nth_root(1000000000,3) +?nth_root(1000000000,9) diff --git a/Task/Nth-root/SPL/nth-root.spl b/Task/Nth-root/SPL/nth-root.spl new file mode 100644 index 0000000000..140e6274b7 --- /dev/null +++ b/Task/Nth-root/SPL/nth-root.spl @@ -0,0 +1,14 @@ +nthr(n,r) <= n^(1/r) + +nthroot(n,r)= + a = n/r + g = n + > g!=a + g = a + a = (1/r)*(((r-1)*g)+(n/(g^(r-1)))) + < + <= a +. + +#.output(nthr(2,2)) +#.output(nthroot(2,2)) diff --git a/Task/Nth-root/Zkl/nth-root.zkl b/Task/Nth-root/Zkl/nth-root.zkl new file mode 100644 index 0000000000..4f1c12b0b2 --- /dev/null +++ b/Task/Nth-root/Zkl/nth-root.zkl @@ -0,0 +1,11 @@ +fcn nthroot(nth,a,precision=1.0e-5){ + x:=prev:=a=a.toFloat(); n1:=nth-1; + do{ + prev=x; + x=( prev*n1 + a/prev.pow(n1) ) / nth; + } + while( not prev.closeTo(x,precision) ); + x +} + +nthroot(5,34) : "%.20f".fmt(_).println() # => 2.02439745849988828041 diff --git a/Task/Nth/BaCon/nth.bacon b/Task/Nth/BaCon/nth.bacon new file mode 100644 index 0000000000..459754f95d --- /dev/null +++ b/Task/Nth/BaCon/nth.bacon @@ -0,0 +1,28 @@ +' Nth (sans apostrophes) +FUNCTION nth$(NUMBER n) TYPE STRING + LOCAL suffix + IF n < 0 THEN RETURN STR$(n) + IF MOD(n, 100) >= 11 AND MOD(n, 100) <= 13 THEN + suffix = "th" + ELSE + suffix = MID$("thstndrdthththththth", MOD(n, 10) * 2 + 1, 2) + ENDIF + RETURN CONCAT$(STR$(n), suffix) +END FUNCTION + +' Test a few ranges +FOR i = 1 TO 4 + READ first, last + per = 1 + FOR n = first TO last + PRINT nth$(n) FORMAT "%s " + ' limit to 10 entries per line + IF per = 10 OR n = last THEN + per = 1 + PRINT + ELSE + INCR per + ENDIF + NEXT +NEXT +DATA 0, 25, 250, 265, 1000, 1025, -20, -11 diff --git a/Task/Nth/Gambas/nth.gambas b/Task/Nth/Gambas/nth.gambas new file mode 100644 index 0000000000..9e264fb1ee --- /dev/null +++ b/Task/Nth/Gambas/nth.gambas @@ -0,0 +1,17 @@ +Public Sub Main() +Dim siNums As Short[] = [0, 25, 250, 265, 1000, 1025] +Dim siCount, siNumbers As Short +Dim sOrdinal As String + +For siNumbers = 0 To 4 Step 2 + For siCount = siNums[siNumbers] To siNums[siNumbers + 1] + sOrdinal = "th" + If Right(Str(siCount), 1) = "1" And Right(Str(siCount), 2) <> "11" Then sOrdinal = "st" + If Right(Str(siCount), 1) = "2" And Right(Str(siCount), 2) <> "12" Then sOrdinal = "nd" + If Right(Str(siCount), 1) = "3" And Right(Str(siCount), 2) <> "13" Then sOrdinal = "rd" + Print siCount & sOrdinal;; + Next + Print gb.NewLine +Next + +End diff --git a/Task/Nth/jq/nth.jq b/Task/Nth/Jq/nth.jq similarity index 100% rename from Task/Nth/jq/nth.jq rename to Task/Nth/Jq/nth.jq diff --git a/Task/Nth/OCaml/nth.ocaml b/Task/Nth/OCaml/nth.ocaml new file mode 100644 index 0000000000..23d8a5eba9 --- /dev/null +++ b/Task/Nth/OCaml/nth.ocaml @@ -0,0 +1,15 @@ +let show_nth n = + if (n mod 10 = 1) && (n mod 100 <> 11) then "st" + else if (n mod 10 = 2) && (n mod 100 <> 12) then "nd" + else if (n mod 10 = 3) && (n mod 100 <> 13) then "rd" + else "th" + + +let () = + let show_ordinals (min, max) = + for i=min to max do + Printf.printf "%d%s " i (show_nth i) + done; + print_newline() in + + List.iter show_ordinals [ (0,25); (250,265); (1000,1025) ] diff --git a/Task/Nth/Phix/nth.phix b/Task/Nth/Phix/nth.phix new file mode 100644 index 0000000000..4db481aa14 --- /dev/null +++ b/Task/Nth/Phix/nth.phix @@ -0,0 +1,16 @@ +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 + +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 diff --git a/Task/Nth/REXX/nth.rexx b/Task/Nth/REXX/nth.rexx index 79d5dca18e..f734fc671e 100644 --- a/Task/Nth/REXX/nth.rexx +++ b/Task/Nth/REXX/nth.rexx @@ -1,17 +1,13 @@ -/*REXX pgm shows ranges of numbers with ordinal (st/nd/rd/th) suffixes.*/ -call tell 0, 25 /*show the 1st range of numbers. */ -call tell 250, 265 /* " " 2nd " " " */ -call tell 1000, 1025 /* " " 3rd " " " */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────TELL subroutine─────────────────────*/ -tell: procedure; parse arg L,H; $= /*get Low & High #s, nullify list*/ - do j=L to H /*process the range, low───►high.*/ - $=$ j || th(j) /*append the Nth number to list*/ - end /*j*/ /* [↑] $ has a leading blank. */ -say 'numbers from ' L " to " H ' (inclusive):' /*display the title.*/ -say strip($) /*display the list. */ -say /*display blank line*/ -return /*return to invoker.*/ -/*──────────────────────────────────TH subroutine───────────────────────*/ -th: procedure; parse arg x; x=abs(x) /*just use ABS value*/ -return word('th st nd rd', 1 + x//10 * (x//100%10 \== 1) * (x//10 < 4) ) +/*REXX program shows ranges of numbers with ordinal (st/nd/rd/th) suffixes attached.*/ +call tell 0, 25 /*display the 1st range of numbers. */ +call tell 250, 265 /* " " 2nd " " " */ +call tell 1000, 1025 /* " " 3rd " " " */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +tell: procedure; parse arg L,H,,$ /*get the Low and High #s, nullify list*/ + do j=L to H; $=$ th(j); end /*process the range, from low ───► high*/ + say 'numbers from ' L " to " H ' (inclusive):' /*display the title. */ + say strip($); say; say /*display line; 2 sep*/ + return /*return to invoker. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +th: parse arg z; x=abs(z); return z||word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4)) diff --git a/Task/Nth/Sidef/nth.sidef b/Task/Nth/Sidef/nth.sidef index 11259976b2..5680356142 100644 --- a/Task/Nth/Sidef/nth.sidef +++ b/Task/Nth/Sidef/nth.sidef @@ -1,8 +1,8 @@ func nth(n) { - static irregulars = Hash.new(<1 ˢᵗ 2 ⁿᵈ 3 ʳᵈ 11 ᵗʰ 12 ᵗʰ 13 ᵗʰ>...); - n.to_s + (irregulars{n % 100} \\ irregulars{n % 10} \\ 'ᵗʰ'); + static irregulars = Hash(<1 ˢᵗ 2 ⁿᵈ 3 ʳᵈ 11 ᵗʰ 12 ᵗʰ 13 ᵗʰ>...) + n.to_s + (irregulars{n % 100} \\ irregulars{n % 10} \\ 'ᵗʰ') } -[range(0, 25), range(250, 265), range(1000, 1025)].each { |r| - say r.map {|n| nth(n) }.join(" "); +for r in [0..25, 250..265, 1000..1025] { + say r.map {|n| nth(n) }.join(" ") } diff --git a/Task/Nth/Sinclair-ZX81-BASIC/nth.sinclair b/Task/Nth/Sinclair-ZX81-BASIC/nth.sinclair new file mode 100644 index 0000000000..4839e0fed1 --- /dev/null +++ b/Task/Nth/Sinclair-ZX81-BASIC/nth.sinclair @@ -0,0 +1,24 @@ + 10 FOR N=0 TO 25 + 20 GOSUB 160 + 30 PRINT N$;" "; + 40 NEXT N + 50 PRINT + 60 FOR N=250 TO 265 + 70 GOSUB 160 + 80 PRINT N$;" "; + 90 NEXT N +100 PRINT +110 FOR N=1000 TO 1025 +120 GOSUB 160 +130 PRINT N$;" "; +140 NEXT N +150 STOP +160 LET N$=STR$ N +170 LET S$="TH" +180 IF LEN N$=1 THEN GOTO 200 +190 IF N$(LEN N$-1)="1" THEN GOTO 230 +200 IF N$(LEN N$)="1" THEN LET S$="ST" +210 IF N$(LEN N$)="2" THEN LET S$="ND" +220 IF N$(LEN N$)="3" THEN LET S$="RD" +230 LET N$=N$+S$ +240 RETURN diff --git a/Task/Nth/ZX-Spectrum-Basic/nth.zx b/Task/Nth/ZX-Spectrum-Basic/nth.zx new file mode 100644 index 0000000000..9ad05f3da1 --- /dev/null +++ b/Task/Nth/ZX-Spectrum-Basic/nth.zx @@ -0,0 +1,22 @@ + 10 FOR n=0 TO 25 + 20 GO SUB 140 + 30 PRINT n$;" "; + 40 NEXT n + 50 FOR n=250 TO 265 + 60 GO SUB 140 + 70 PRINT n$;" "; + 80 NEXT n + 90 FOR n=1000 TO 1025 +100 GO SUB 140 +110 PRINT n$;" "; +120 NEXT n +130 STOP +140 LET s$="th" +150 LET n$=STR$ n +160 IF LEN n$=1 THEN GO TO 180 +170 IF n$(LEN n$-1)="1" THEN GO TO 210 +180 IF n$(LEN n$)="1" THEN LET s$="st" +190 IF n$(LEN n$)="2" THEN LET s$="nd" +200 IF n$(LEN n$)="3" THEN LET s$="rd" +210 LET n$=n$+s$ +220 RETURN diff --git a/Task/Nth/Zkl/nth-1.zkl b/Task/Nth/Zkl/nth-1.zkl new file mode 100644 index 0000000000..639648bc58 --- /dev/null +++ b/Task/Nth/Zkl/nth-1.zkl @@ -0,0 +1,14 @@ +#if 0 +fcn addSuffix(n){ + z:=n.abs()%100; + if(11<=z<=13) return(String(n,"th")); + z=z%10; + String(n,(z==1 and "st") or (z==2 and "nd") or (z==3 and "rd") or "th"); +} +#else +fcn addSuffix(n){ + var suffixes=T("th","st","nd","rd","th","th","th","th","th","th"); //0..10 + z:=n.abs()%100; + String(n,(z<=10 or z>20) and suffixes[z%10] or "th"); +} +#endif diff --git a/Task/Nth/Zkl/nth-2.zkl b/Task/Nth/Zkl/nth-2.zkl new file mode 100644 index 0000000000..52a2404f33 --- /dev/null +++ b/Task/Nth/Zkl/nth-2.zkl @@ -0,0 +1,3 @@ +[0..25] .apply(addSuffix).concat(",").println(); +[250..265] .apply(addSuffix).concat(",").println(); +[1000..1025].apply(addSuffix).concat(",").println(); diff --git a/Task/Null-object/BBC-BASIC/null-object.bbc b/Task/Null-object/BBC-BASIC/null-object.bbc deleted file mode 100644 index 6480acd3a8..0000000000 --- a/Task/Null-object/BBC-BASIC/null-object.bbc +++ /dev/null @@ -1,13 +0,0 @@ - PROCtestobjects - END - - DEF PROCtestobjects - PRIVATE a(), b(), s{}, t{} - DIM a(123) - DIM s{a%, b#, c$} - - IF !^a() <= 1 PRINT "a() is null" ELSE PRINT "a() is not null" - IF !^b() <= 1 PRINT "b() is null" ELSE PRINT "b() is not null" - IF !^s{} <= 1 PRINT "s{} is null" ELSE PRINT "s{} is not null" - IF !^t{} <= 1 PRINT "t{} is null" ELSE PRINT "t{} is not null" - ENDPROC diff --git a/Task/Null-object/jq/null-object.jq b/Task/Null-object/Jq/null-object.jq similarity index 100% rename from Task/Null-object/jq/null-object.jq rename to Task/Null-object/Jq/null-object.jq diff --git a/Task/Null-object/Kotlin/null-object.kotlin b/Task/Null-object/Kotlin/null-object.kotlin new file mode 100644 index 0000000000..a01e64e0c2 --- /dev/null +++ b/Task/Null-object/Kotlin/null-object.kotlin @@ -0,0 +1,9 @@ +// version 1.1.0 + +fun main(args: Array) { + val i: Int = 3 // non-nullable Int type - can't be assigned null + println(i) + val j: Int? = null // nullable Int type - can be assigned null + println(j) + println(null is Nothing?) // test that null is indeed of type Nothing? +} diff --git a/Task/Null-object/OoRexx/null-object-1.rexx b/Task/Null-object/OoRexx/null-object-1.rexx new file mode 100644 index 0000000000..77acb1ea8e --- /dev/null +++ b/Task/Null-object/OoRexx/null-object-1.rexx @@ -0,0 +1 @@ + if a[i] == .nil then say "Item" i "is missing" diff --git a/Task/Null-object/OoRexx/null-object-2.rexx b/Task/Null-object/OoRexx/null-object-2.rexx new file mode 100644 index 0000000000..6d83efdbcb --- /dev/null +++ b/Task/Null-object/OoRexx/null-object-2.rexx @@ -0,0 +1,5 @@ +a=.array~of('A','B') + i=3 + if a[i] == .nil then say "Item" i "of array A is missing" + if \var("INPUT") then say "Variable INPUT is not assigned" + if \var("var") then say "Variable" var "is not assigned" diff --git a/Task/Null-object/S-lang/null-object.slang b/Task/Null-object/S-lang/null-object.slang new file mode 100644 index 0000000000..b0d5623d4f --- /dev/null +++ b/Task/Null-object/S-lang/null-object.slang @@ -0,0 +1,4 @@ +variable foo = NULL; +print(foo); +if (foo == NULL) + print(typeof(foo)); diff --git a/Task/Null-object/Zkl/null-object.zkl b/Task/Null-object/Zkl/null-object.zkl new file mode 100644 index 0000000000..5bdeea8fa5 --- /dev/null +++ b/Task/Null-object/Zkl/null-object.zkl @@ -0,0 +1,2 @@ +if(Void == n) ... +return(Void) diff --git a/Task/Number-names/00DESCRIPTION b/Task/Number-names/00DESCRIPTION index b59b6902f8..59a3fb0aae 100644 --- a/Task/Number-names/00DESCRIPTION +++ b/Task/Number-names/00DESCRIPTION @@ -4,4 +4,8 @@ Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. + + +;Related task: +*   [[Spelling of ordinal numbers]].

    diff --git a/Task/Number-names/360-Assembly/number-names.360 b/Task/Number-names/360-Assembly/number-names.360 new file mode 100644 index 0000000000..5dbeca44ec --- /dev/null +++ b/Task/Number-names/360-Assembly/number-names.360 @@ -0,0 +1,183 @@ +* Number names 20/02/2017 +NUMNAME CSECT + USING NUMNAME,R13 + B 72(R15) + DC 17F'0' + STM R14,R12,12(R13) + ST R13,4(R15) + ST R15,8(R13) + LR R13,R15 end of prolog + LA R6,1 i=1 + DO WHILE=(C,R6,LE,=A(NG)) do i=1 to hbound(g) + LR R1,R6 i + SLA R1,2 + L R2,G-4(R1) g(i) + ST R2,N n=g(i) + L R4,N + IF LTR,R4,Z,R4 THEN if n=0 then + MVC R,=CL256'zero' r='zero' + ELSE , else + MVC R,=CL256' ' r='' + MVC D,=F'10' d=10 + MVC C,=F'100' c=100 + MVC K,=F'1000' k=1000 + L R2,N n + LPR R2,R2 abs(n) + ST R2,A a=abs(n) + SR R7,R7 j=0 + DO WHILE=(C,R7,LE,D) do j=0 to d + L R4,A a + SRDA R4,32 + D R4,C /c + M R4,C *a + L R8,A a + SR R8,R5 h=a-c*a/c + IF C,R8,GT,=F'0',AND,C,R8,LT,D THEN if h>0 & h9 & h<20 then + LR R1,R8 h + S R1,D -d + MH R1,=H'10' + LA R4,T(R1) @t(h-d+1) + MVC PG(10),0(R4) t(h-d+1) + MVC PG+10(246),R !!r + MVC R,PG r=t(h-d+1)!!' '!!r + ENDIF , endif + IF C,R8,GT,=F'19',AND,C,R8,LT,C THEN if h>19 & h0 then + L R4,A a + SRDA R4,32 + D R4,K /k + M R4,K *k + L R8,A a + SR R8,R5 h=a-k*(a/k) + IF LTR,R8,NZ,R8 THEN if h^=0 then + LR R1,R7 j + MH R1,=H'10' + LA R4,V(R1) @v(j+1) + MVC PG(10),0(R4) v(j+1) + MVC PG+10(246),R !!r + MVC R,PG r=v(j+1)!!' '!!r + ENDIF , endif + ENDIF , endif + LA R3,1 l=0 + LA R9,256 jr=256 + LA R10,R ir=0 + LA R11,R-1 irr=-1 +LOOP CLI 0(R10),C' ' if r[ii]=' ' .....+ + BNE OPT | + CLI 1(R10),C' ' if r[ii+1]=' ' | + BE ITER | + CLI 1(R10),C'-' if r[ii+1]='-' | + BE ITER | +OPT LA R11,1(R11) irr=irr+1 | + MVC 0(1,R11),0(R10) rr=rr!!ci | + LA R3,1(R3) l=l+1 | +ITER LA R10,1(R10) ir=ir+1 | + BCT R9,LOOP ...................+ + LA R1,R-1 @r + AR R1,R3 +lr + MVC 0(80,R1),=CL80' ' clean the end + L R4,A a + IF LTR,R4,NP,R4 THEN if a<=0 then + B LEAVEJ leave + ENDIF , endif a<=0 + LA R7,1(R7) j++ + ENDDO , enddo j +LEAVEJ L R4,N n + IF LTR,R4,M,R4 THEN if n<0 then + MVC PG(6),=C'minus ' 'minus ' + MVC PG+6(250),R !!r + MVC R,PG r='minus '!!r + ENDIF , endif n<0 + ENDIF , endif n=0 + MVC PG,=CL132' ' clear buffer + L R1,N n + XDECO R1,PG edit n + MVC PG+13(256),R r + XPRNT PG,132 print buffer + LA R6,1(R6) i++ + ENDDO , enddo i + L R13,4(0,R13) epilog + LM R14,R12,12(R13) + XR R15,R15 + BR R14 exit +S DC CL10' ',CL10'one',CL10'two',CL10'three',CL10'four' + DC CL10'five',CL10'six',CL10'seven',CL10'eight',CL10'nine' +T DC CL50'ten eleven twelve thirteen fourteen' + DC CL50'fifteen sixteen seventeen eighteen nineteen' +U DC CL50' twenty thirty forty' + DC CL50'fifty sixty seventy eighty ninety' +V DC CL50'thousand million billion trillion' +G DC F'0',F'2',F'19',F'20',F'21',F'99',F'100',F'101',F'-123' + DC F'9123',F'467889',F'1234567',F'2147483647' +NG EQU (*-G)/4 +N DS F +D DS F +C DS F +K DS F +A DS F +X DS F +Y DS CL1 +R DS CL256 +XDEC DS CL12 +PG DS CL256 + YREGS + END NUMNAME diff --git a/Task/Number-names/CoffeeScript/number-names-1.coffee b/Task/Number-names/CoffeeScript/number-names-1.coffee deleted file mode 100644 index 00571a360c..0000000000 --- a/Task/Number-names/CoffeeScript/number-names-1.coffee +++ /dev/null @@ -1,57 +0,0 @@ -spell_integer = (n) -> - tens = [null, null, "twenty", "thirty", "forty", - "fifty", "sixty", "seventy", "eighty", "ninety"] - - small = ["zero", "one", "two", "three", "four", "five", - "six", "seven", "eight", "nine", "ten", "eleven", - "twelve", "thirteen", "fourteen", "fifteen", - "sixteen", "seventeen", "eighteen", "nineteen"] - - bl = [null, null, "m", "b", "tr", "quadr", - "quint", "sext", "sept", "oct", "non", "dec"] - - divmod = (n, d) -> - [Math.floor(n / d), n % d] - - nonzero = (c, n) -> - if n == 0 - "" - else - c + spell_integer n - - big = (e, n) -> - if e == 0 - spell_integer n - else if e == 1 - spell_integer(n) + " thousand" - else - spell_integer(n) + " " + bl[e] + "illion" - - base1000_rev = (n) -> - # generates the value of the digits of n in base 1000 - # (i.e. 3-digit chunks), in reverse. - chunks = [] - while n != 0 - [n, r] = divmod n, 1000 - chunks.push r - chunks - - if n < 0 - throw Error "spell_integer: negative input" - else if n < 20 - small[n] - else if n < 100 - [a, b] = divmod n, 10 - tens[a] + nonzero("-", b) - else if n < 1000 - [a, b] = divmod n, 100 - small[a] + " hundred" + nonzero(" ", b) - else - chunks = (big(exp, x) for x, exp in base1000_rev(n) when x) - chunks.reverse().join ', ' - -# example -console.log spell_integer 1278 -console.log spell_integer 1752 -console.log spell_integer 2010 -console.log spell_integer 4000123007913 diff --git a/Task/Number-names/CoffeeScript/number-names-2.coffee b/Task/Number-names/CoffeeScript/number-names-2.coffee deleted file mode 100644 index 290302a78e..0000000000 --- a/Task/Number-names/CoffeeScript/number-names-2.coffee +++ /dev/null @@ -1,5 +0,0 @@ -> coffee spell_number.coffee -one thousand, two hundred seventy-eight -one thousand, seven hundred fifty-two -two thousand, ten -four trillion, one hundred twenty-three million, seven thousand, nine hundred thirteen diff --git a/Task/Number-names/Elixir/number-names.elixir b/Task/Number-names/Elixir/number-names.elixir new file mode 100644 index 0000000000..b355b281ab --- /dev/null +++ b/Task/Number-names/Elixir/number-names.elixir @@ -0,0 +1,48 @@ +defmodule RC do + @small ~w(zero one two three four five six seven eight nine ten + eleven twelve thirteen fourteen fifteen sixteen seventeen + eighteen nineteen) + @tens ~w(wrong wrong twenty thirty forty fifty sixty seventy eighty ninety) + @big [nil, "thousand"] ++ + (~w( m b tr quadr quint sext sept oct non dec) |> Enum.map(&"#{&1}illion")) + + def wordify(number) when number<0, do: "negative #{wordify(-number)}" + def wordify(number) when number<20, do: Enum.at(@small,number) + def wordify(number) when number<100 do + rm = rem(number,10) + Enum.at(@tens,div(number,10)) <> (if rm==0, do: "", else: "-#{wordify(rm)}") + end + def wordify(number) when number<1000 do + rm = rem(number,100) + "#{Enum.at(@small,div(number,100))} hundred" <> (if rm==0, do: "", else: " and #{wordify(rm)}") + end + def wordify(number) do + # separate into 3-digit chunks + chunks = chunk(number, []) + if length(chunks) > length(@big), do: raise(ArgumentError, "Integer value too large.") + Enum.map(chunks, &wordify(&1)) + |> Enum.zip(@big) + |> Enum.filter_map(fn {a,_} -> a != "zero" end, fn {a,b} -> "#{a} #{b}" end) + |> Enum.reverse + |> Enum.join(", ") + end + + defp chunk(0, res), do: Enum.reverse(res) + defp chunk(number, res) do + chunk(div(number,1000), [rem(number,1000) | res]) + end +end + +data = [-1123, 0, 1, 20, 123, 200, 220, 1245, 2000, 2200, 2220, 467889, + 23_000_467, 23_234_467, 2_235_654_234, 12_123_234_543_543_456, + 987_654_321_098_765_432_109_876_543_210_987_654, + 123890812938219038290489327894327894723897432] + +Enum.each(data, fn n -> + IO.write "#{n}: " + try do + IO.inspect RC.wordify(n) + rescue + e in ArgumentError -> IO.puts Exception.message(e) + end +end) diff --git a/Task/Number-names/jq/number-names-1.jq b/Task/Number-names/Jq/number-names-1.jq similarity index 100% rename from Task/Number-names/jq/number-names-1.jq rename to Task/Number-names/Jq/number-names-1.jq diff --git a/Task/Number-names/jq/number-names-2.jq b/Task/Number-names/Jq/number-names-2.jq similarity index 100% rename from Task/Number-names/jq/number-names-2.jq rename to Task/Number-names/Jq/number-names-2.jq diff --git a/Task/Number-names/Kotlin/number-names.kotlin b/Task/Number-names/Kotlin/number-names.kotlin new file mode 100644 index 0000000000..9f2eee0748 --- /dev/null +++ b/Task/Number-names/Kotlin/number-names.kotlin @@ -0,0 +1,103 @@ +// version 1.1.2 + +val names = mapOf( + 1 to "one", + 2 to "two", + 3 to "three", + 4 to "four", + 5 to "five", + 6 to "six", + 7 to "seven", + 8 to "eight", + 9 to "nine", + 10 to "ten", + 11 to "eleven", + 12 to "twelve", + 13 to "thirteen", + 14 to "fourteen", + 15 to "fifteen", + 16 to "sixteen", + 17 to "seventeen", + 18 to "eighteen", + 19 to "nineteen", + 20 to "twenty", + 30 to "thirty", + 40 to "forty", + 50 to "fifty", + 60 to "sixty", + 70 to "seventy", + 80 to "eighty", + 90 to "ninety" +) +val bigNames = mapOf( + 1_000L to "thousand", + 1_000_000L to "million", + 1_000_000_000L to "billion", + 1_000_000_000_000L to "trillion", + 1_000_000_000_000_000L to "quadrillion", + 1_000_000_000_000_000_000L to "quintillion" +) + +fun numToText(n: Long, uk: Boolean = false): String { + if (n == 0L) return "zero" + val neg = n < 0L + val maxNeg = n == Long.MIN_VALUE + var nn = if (maxNeg) -(n + 1) else if (neg) -n else n + val digits3 = IntArray(7) + for (i in 0..6) { // split number into groups of 3 digits from the right + digits3[i] = (nn % 1000).toInt() + nn /= 1000 + } + + fun threeDigitsToText(number: Int) : String { + val sb = StringBuilder() + if (number == 0) return "" + val hundreds = number / 100 + val remainder = number % 100 + if (hundreds > 0) { + sb.append(names[hundreds], " hundred") + if (remainder > 0) sb.append(if (uk) " and " else " ") + } + if (remainder > 0) { + val tens = remainder / 10 + val units = remainder % 10 + if (tens > 1) { + sb.append(names[tens * 10]) + if (units > 0) sb.append("-", names[units]) + } + else sb.append(names[remainder]) + } + return sb.toString() + } + + val strings = Array(7) { threeDigitsToText(digits3[it]) } + var text = strings[0] + var andNeeded = uk && digits3[0] in 1..99 + var big = 1000L + for (i in 1..6) { + if (digits3[i] > 0) { + var text2 = strings[i] + " " + bigNames[big] + if (text.length > 0) { + text2 += if (andNeeded) " and " else ", " + andNeeded = false + } + else andNeeded = uk && digits3[i] in 1..99 + text = text2 + text + } + big *= 1000 + } + if (maxNeg) text = text.dropLast(5) + "eight" + return (if (neg) "minus " else "") + text +} + +fun main(args: Array) { + val la = longArrayOf( + 0, 1, 7, 10, 18, 22, 67, 99, 100, 105, 999, -1056, 1000005000, + 2074000000, 1234000000745003L, Long.MIN_VALUE + ) + println("Using US representation:") + for (i in la) println("${"%20d".format(i)} = ${numToText(i)}") + println() + println("Using UK representation:") + for (i in la) println("${"%20d".format(i)} = ${numToText(i, true)}") +} diff --git a/Task/Number-names/Perl-6/number-names.pl6 b/Task/Number-names/Perl-6/number-names-1.pl6 similarity index 100% rename from Task/Number-names/Perl-6/number-names.pl6 rename to Task/Number-names/Perl-6/number-names-1.pl6 diff --git a/Task/Number-names/Perl-6/number-names-2.pl6 b/Task/Number-names/Perl-6/number-names-2.pl6 new file mode 100644 index 0000000000..c70bc03a1d --- /dev/null +++ b/Task/Number-names/Perl-6/number-names-2.pl6 @@ -0,0 +1,9 @@ +use Lingua::EN::Numbers::Cardinal; + +put join "\n", .&cardinal, .&cardinal(:improper) with -7/4; + +printf "%-7s : %19s : %s\n", $_, cardinal($_), cardinal($_, :denominator(16)) for 1/16, 2/16 ... 1; + +put join "\n", .&cardinal, .&cardinal-year, .&ordinal, .&ordinal-digit with 1999; + +.&cardinal.put for 6.022e23, 42000, π; diff --git a/Task/Number-names/Phix/number-names.phix b/Task/Number-names/Phix/number-names.phix index 12e4bbc17d..ae317aff3c 100644 --- a/Task/Number-names/Phix/number-names.phix +++ b/Task/Number-names/Phix/number-names.phix @@ -1,3 +1,6 @@ +-- +-- demo/rosetta/Number_names.exw +-- constant twenties = {"zero","one","two","three","four","five","six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"} @@ -67,7 +70,7 @@ integer n return res end function -function spell(atom N) +global function spell(atom N) string res = "" if N<0 then res = "minus " @@ -77,11 +80,14 @@ string res = "" return res end function +global constant Samples = {99, 300, 310, 417,1_501, 12_609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, - -1501,1234,12.34,10000001.2,1E-3,-2.7182818} + -1501,1234,12.34,10000001.2,1E-3,-2.7182818, + 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, + 201021,-20102,2010,-201,20,-2} -function smartp(atom N) +global function smartp(atom N) string res if N=floor(N) then return sprintf("%d",N) end if res = sprintf("%18.8f",N) @@ -91,14 +97,32 @@ string res return res end function +procedure main() atom si -for i=1 to length(Samples) do - si = Samples[i] - printf(1,"%18s %s\n",{smartp(si),spell(si)}) -end for + for i=1 to length(Samples) do + si = Samples[i] + printf(1,"%18s %s\n",{smartp(si),spell(si)}) + end for +end procedure -si = 201021002001 -while si!=0 do - printf(1,"%18s %s\n",{smartp(si),spell(si)}) - si = trunc(si/-10) -end while +-- from Executable_library#Phix -- +function isMainOrInclude() +-- returns 1 if called from the main file, 0 if from an include +integer res + #ilASM{ + [32] + mov eax,[ebp+20] -- prev_ebp + mov eax,[eax+8] -- rtn + mov [res],eax + [64] + mov rax,[rbp+40] -- prev_ebp + mov rax,[rax+16] -- rtn + mov [res],rax + [] + } + return res=21 -- (21=T_maintls) +end function + +if isMainOrInclude() then + main() +end if diff --git a/Task/Number-names/PureBasic/number-names-3.purebasic b/Task/Number-names/PureBasic/number-names-3.purebasic new file mode 100644 index 0000000000..6ed711f5b9 --- /dev/null +++ b/Task/Number-names/PureBasic/number-names-3.purebasic @@ -0,0 +1,49 @@ +def int_to_english(n): + if n < 0: return "minus " + int_to_english(-n) + if n < 10: + return ["zero", "one", "two", "three", "four", "five", + "six", "seven", "eight", "nine"][n] + if n < 20: + return ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", + "sixteen", "seventeen", "eighteen", "nineteen"][n-10] + if n < 100: + tens = ["twenty", "thirty", "forty", "fifty", "sixty", + "seventy", "eighty", "ninety"][(n // 10 - 2)%10] + if n % 10 != 0: + return tens + "-" + int_to_english(n % 10) + else: + return tens + if n < 1000: + if n % 100 == 0: + return int_to_english(n // 100) + " hundred" + else: + return int_to_english(n // 100) + " hundred and " +\ + int_to_english(n % 100) + # http://www.isthe.com/chongo/tech/math/number/tenpower.html + powers = [("thousand", 3), ("million", 6), + ("billion", 9), ("trillion", 12), ("quadrillion", 15), + ("quintillion", 18), ("sextillion", 21), ("septillion", 24), + ("octillion", 27), ("nonillion", 30), ("decillion", 33), + ("undecillion", 36), ("duodecillion", 39), ("tredecillion", 42), + ("quattuordecillion", 45), ("quindecillion", 48), + ("sexdecillion", 51), ("eptendecillion", 54), + ("octadecillion", 57), ("novemdecillion", 61), + ("vigintillion", 64)] + ns = str(n) + idx = len(powers) - 1 + while True: + d = powers[idx][1] + if len(ns) > d: + first = int_to_english(int(ns[:-d])) + second = int_to_english(int(ns[-d:])) + if second == "zero": + return first + " " + powers[idx][0] + else: + return first + " " + powers[idx][0] + " " + second + idx = idx - 1 + +if __name__ == "__main__": + print(int_to_english(42)) + print(int_to_english(3 ** 7)) + print(int_to_english(2 ** 100)) + print(int_to_english(10 ** (2*64))) diff --git a/Task/Number-names/Zkl/number-names-1.zkl b/Task/Number-names/Zkl/number-names-1.zkl new file mode 100644 index 0000000000..63a015bf83 --- /dev/null +++ b/Task/Number-names/Zkl/number-names-1.zkl @@ -0,0 +1,22 @@ +var + ns =[1..20].chain([30..90,10]).walk(), + names=T("one","two","three","four","five","six","seven","eight","nine", + "ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen", + "seventeen","eighteen","nineteen","twenty", + "thirty","forty","fifty","sixty","seventy","eighty","ninety"), + hs =T( 100, 1000, 1000000, 1000000000,1000000000000), + hnames=T("hundred","thousand","million","billion", "trillion"); + +fcn numberToString(n){ // n>0 + fcn(n){ + if(100<=n<0d100_000_0000_000){ + idx,h,name,r := hs.filter1n('>(n))-1, hs[idx], hnames[idx], n%h; + String(self.fcn(n/h),name, + if(r==0) "" else if(0(n))-1, ns[idx], names[idx], n-t; + String(name, if(00 - ar_not_void: numbers /= void - local - i,j:INTEGER - new_array: ARRAY[INTEGER] - do - create new_array.make_empty - new_array.copy (numbers) - from - i:= 1 - j:=upper - until - i>j - loop - new_array[i]:=numbers[j] - new_array[j]:=numbers[i] - i:=i+1 - j:=j-1 - end - numbers := new_array - end - - is_sorted(ar: ARRAY[INTEGER];l, r: INTEGER): BOOLEAN - require - ar_not_empty: ar.is_empty= FALSE - local - smaller : BOOLEAN - i: INTEGER - do - smaller:= TRUE - from - i:= l - until - i=r - loop - if ar[i]> ar[i+1] then - smaller:= FALSE - end - i:= i+1 - end - if smaller = TRUE then - RESULT := TRUE - else - RESULT:= FALSE - end - end -end diff --git a/Task/Number-reversal-game/Eiffel/number-reversal-game-2.e b/Task/Number-reversal-game/Eiffel/number-reversal-game-2.e deleted file mode 100644 index 922e9adf97..0000000000 --- a/Task/Number-reversal-game/Eiffel/number-reversal-game-2.e +++ /dev/null @@ -1,14 +0,0 @@ -class - APPLICATION -inherit - ARGUMENTS -create - make -feature {NONE} -- Initialization - make - do - create nr - nr.play_game - end - nr: NUMBER_REVERSAL_GAME -end diff --git a/Task/Number-reversal-game/Elena/number-reversal-game.elena b/Task/Number-reversal-game/Elena/number-reversal-game.elena index e145eb0082..362108e79e 100644 --- a/Task/Number-reversal-game/Elena/number-reversal-game.elena +++ b/Task/Number-reversal-game/Elena/number-reversal-game.elena @@ -1,21 +1,25 @@ -#import system. -#import system'routines. -#import extensions. +import system'routines. +import extensions. -#symbol program = +program = [ - #var sorted := Array new:9 set &every: (&index:n) [ n + 1 ]. - #var values := sorted clone randomize:9. + var sorted := Array new:9; populate(:n)( n + 1 ). + var values := sorted clone; randomize:9. - #var tries := Integer new. - #loop (sorted sequenceEqual:values)! + while (sorted sequenceEqual:values) [ - tries += 1. - - console writeLiteral:"# ":tries:" : LIST : ":values:" - Flip how many?". - - values reverse:(console readLine toInt) &at:0. + values := sorted randomize:9 ]. - console writeLine:"You took ":tries:" attempts to put the digits in order!" readChar. + var tries := Integer new. + until (sorted sequenceEqual:values) + [ + tries append:1. + + console print("# ",tries," : LIST : ",values," - Flip how many?"). + + values sequenceReverse(console readLine; toInt) at:0. + ]. + + console printLine("You took ",tries," attempts to put the digits in order!"); readChar. ]. diff --git a/Task/Number-reversal-game/Jq/number-reversal-game-1.jq b/Task/Number-reversal-game/Jq/number-reversal-game-1.jq new file mode 100644 index 0000000000..241088bd50 --- /dev/null +++ b/Task/Number-reversal-game/Jq/number-reversal-game-1.jq @@ -0,0 +1,19 @@ +# Input: the initial array +def play: + def sorted: . == sort; + + def reverse(n): (.[0:n] | reverse) + .[n:]; + + def prompt: "List: \(.list)\nEnter a pivot number: "; + + def report: "Great! Your score is \(.score)"; + + {list: ., score: 0} + | (if .list | sorted then "List was sorted to begin with." + else + prompt, + ( label $done + | foreach inputs as $n (.; + .list |= reverse($n) | .score +=1; + if .list | sorted then report, break $done else prompt end )) + end); diff --git a/Task/Number-reversal-game/Jq/number-reversal-game-2.jq b/Task/Number-reversal-game/Jq/number-reversal-game-2.jq new file mode 100644 index 0000000000..cf9a2a01bd --- /dev/null +++ b/Task/Number-reversal-game/Jq/number-reversal-game-2.jq @@ -0,0 +1 @@ +[1,2,3,9,8,7,6,5,4] | play diff --git a/Task/Number-reversal-game/Julia/number-reversal-game.julia b/Task/Number-reversal-game/Julia/number-reversal-game.julia new file mode 100644 index 0000000000..188e9bdd31 --- /dev/null +++ b/Task/Number-reversal-game/Julia/number-reversal-game.julia @@ -0,0 +1,18 @@ +# v0.6 + +function numrevgame() + l = collect(1:9) + while issorted(l) shuffle!(l) end + score = 0 + println("# Number reversal game") + while !issorted(l) + print("$l\nInsert the index up to which to revert: ") + n = parse(Int, readline()) + reverse!(l, 1, n) + score += 1 + end + println("$l... You won!\nScore: $score") + return score +end + +numrevgame() diff --git a/Task/Number-reversal-game/Kotlin/number-reversal-game.kotlin b/Task/Number-reversal-game/Kotlin/number-reversal-game.kotlin new file mode 100644 index 0000000000..e8e4525d57 --- /dev/null +++ b/Task/Number-reversal-game/Kotlin/number-reversal-game.kotlin @@ -0,0 +1,42 @@ +// version 1.1.2 + +fun isAscending(a: IntArray): Boolean { + for (i in 0..8) if (a[i] != i + 1) return false + return true +} + +fun main(args: Array) { + val r = java.util.Random() + var count = 0 + val numbers = IntArray(9) + numbers[0] = 2 + r.nextInt(8) // this will ensure list isn't ascending + for (i in 1..8) { + var rn: Int + do { + rn = 1 + r.nextInt(9) + } while (rn in numbers) + numbers[i] = rn + } + println("Here's your first list : ${numbers.joinToString()}") + while (true) { + var rev: Int + do { + print("How many numbers from the left are to be reversed : ") + rev = readLine()!!.toInt() + } while (rev !in 2..9) + count++ + var i = 0 + var j = rev - 1 + while (i < j) { + val temp = numbers[i] + numbers[i++] = numbers[j] + numbers[j--] = temp + } + if (isAscending(numbers)) { + println("Here's your final list : ${numbers.joinToString()}") + break + } + println("Here's your list now : ${numbers.joinToString()}") + } + println("So you've completed the game with a score of $count") +} diff --git a/Task/Number-reversal-game/Lua/number-reversal-game.lua b/Task/Number-reversal-game/Lua/number-reversal-game.lua index 049dcd9caf..32f7351b4e 100644 --- a/Task/Number-reversal-game/Lua/number-reversal-game.lua +++ b/Task/Number-reversal-game/Lua/number-reversal-game.lua @@ -1,60 +1,65 @@ -math.randomseed(os.time()) -- Random values are used by numList:build() -math.random() - +-- Initialisation +math.randomseed(os.time()) numList = {values = {}} -function numList:contains (n) -- Check whether list contains n - for k, v in pairs(self.values) do - if v == n then return true end - end - return false +-- Check whether list contains n +function numList:contains (n) + for k, v in pairs(self.values) do + if v == n then return true end + end + return false end -function numList:inOrder () -- Check whether list is in order - for k, v in pairs(self.values) do - if k ~=v then return false end - end - return true +-- Check whether list is in order +function numList:inOrder () + for k, v in pairs(self.values) do + if k ~=v then return false end + end + return true end -function numList:build () -- Create necessarily out-of-order list - local newNum - repeat - for i = 1, 9 do - repeat - newNum = math.random(1, 9) - until not numList:contains(newNum) - table.insert(self.values, newNum) - end - until not numList:inOrder() +-- Create necessarily out-of-order list +function numList:build () + local newNum + repeat + for i = 1, 9 do + repeat + newNum = math.random(1, 9) + until not numList:contains(newNum) + table.insert(self.values, newNum) + end + until not numList:inOrder() end -function numList:show () -- Display list of numbers on one line - for k, v in pairs(self.values) do - io.write(v .. " ") - end - io.write(":\t") +-- Display list of numbers on one line +function numList:show () + for k, v in pairs(self.values) do + io.write(v .. " ") + end + io.write(":\t") end -function numList:reverse (n) -- Reverse n values from left - local swapList = {} - for k, v in pairs(self.values) do - table.insert(swapList, v) - end - for i = 1, n do - swapList[i] = self.values[n + 1 - i] - end - self.values = swapList +-- Reverse n values from left +function numList:reverse (n) + local swapList = {} + for k, v in pairs(self.values) do + table.insert(swapList, v) + end + for i = 1, n do + swapList[i] = self.values[n + 1 - i] + end + self.values = swapList end -local score = 0 -- Start of main procedure +-- Main procedure +local score = 0 print("\nRosetta Code Number Reversal Game in Lua") print("========================================\n") numList:build() repeat - numList:show() - numList:reverse(tonumber(io.read())) - score = score + 1 + numList:show() + numList:reverse(tonumber(io.read())) + score = score + 1 until numList:inOrder() numList:show() -print("\nW00t! You scored:", score) +print("\n\nW00t! You scored:", score) diff --git a/Task/Number-reversal-game/Scheme/number-reversal-game.ss b/Task/Number-reversal-game/Scheme/number-reversal-game.ss new file mode 100644 index 0000000000..f7f1641aff --- /dev/null +++ b/Task/Number-reversal-game/Scheme/number-reversal-game.ss @@ -0,0 +1,36 @@ +(import (scheme base) + (scheme read) + (scheme write) + (srfi 1) ; list functions + (srfi 27)) ; random numbers + +(random-source-randomize! default-random-source) + +(define (make-randomised-list) + (let ((vec (apply vector (iota 9 1)))) + (do ((c 0 (+ 1 c))) + ((and (>= c 20) ; at least 20 tries + (not (apply < (vector->list vec)))) ; ensures list not in order + (vector->list vec)) + (let* ((i (random-integer 9)) ; swap two randomly chosen elements + (j (random-integer 9)) + (tmp (vector-ref vec i))) + (vector-set! vec i (vector-ref vec j)) + (vector-set! vec j tmp))))) + +(define (play-game lst plays) + (define (reverse-first n lst) + (let-values (((start tail) (split-at lst n))) + (append (reverse start) tail))) + ; + (display "List: ") (display lst) (newline) + (display "How many numbers should be flipped? ") + (let* ((flip (string->number (read-line))) + (new-lst (reverse-first flip lst))) + (if (apply < new-lst) + (display (string-append "Finished in " + (number->string plays) + " attempts\n")) + (play-game new-lst (+ 1 plays))))) + +(play-game (make-randomised-list) 1) diff --git a/Task/Number-reversal-game/Zkl/number-reversal-game.zkl b/Task/Number-reversal-game/Zkl/number-reversal-game.zkl new file mode 100644 index 0000000000..ce0eea9bd5 --- /dev/null +++ b/Task/Number-reversal-game/Zkl/number-reversal-game.zkl @@ -0,0 +1,13 @@ +correctList,scrambledList,N:=[1..9].walk(), correctList.shuffle(),correctList.len(); +correctList,scrambledList=correctList.concat(""), scrambledList.concat(""); // list to string +attempts:=0; +while(scrambledList!=correctList){ // Repeat until the sequence is correct + n:=ask(("[%d] %s How many numbers (from the left) should be flipped? ") + .fmt(attempts,scrambledList)); + try{ n=n.toInt() }catch{ println("Not a number"); continue; } + if(not (0<=n(float,float) + if(n==1) return(x,1.0); + m1,m2:=legendrePair(n-1,x); + u:=1.0 - 1.0/n; + return( (u + 1)*x*m1 - u*m2, m1); +} +fcn legendre(n,x){ //-->float + if(n==0) return(0.0); + legendrePair(n,x)[0] +} +fcn legendrePrime(n,x){ //-->float + if(n==0) return(0.0); + if(n==1) return(1.0); + m0,m1:=legendrePair(n,x); + (m1 - m0*x)*n/(1.0 - x*x); +} +fcn approximateLegendreRoot(n,k){ # Approximation due to Francesco Tricomi + t:=(4.0*k - 1)/(4.0*n + 2); + (1.0 - (n - 1)/(8*n*n*n))*((0.0).pi*t).cos(); +} +fcn newtonRaphson(f,fPrime,r,eps=2.0e-16){ + while(not (dr:=-f(r)/fPrime(r)).closeTo(0.0,eps)){ r+=dr } + r; +} +fcn legendreRoot(n,k){ + newtonRaphson(legendre.fp(n),legendrePrime.fp(n), + approximateLegendreRoot(n,k)); +} +fcn weight(n,r){ + lp:=legendrePrime(n,r); + 2.0/((1.0 - r*r)*lp*lp) +} +fcn nodes(n){ //-->( (r,weight), (r,w), ...) length n + sink:=n.isOdd and L(T(0.0,weight(n,0))) or List; + (1).pump(n/2,sink,'wrap(m){ + r:=legendreRoot(n,m); + w:=weight(n,r); + return( Void.Write,T(r,w),T(-r,w) ) + }) +} +fcn quadrature(n,f,a,b,nds=Void){ + if(not nds) nds=nodes(n); + scale:='wrap(x){ (x*(b - a) + a + b) / 2 }; + nds.reduce('wrap(p,[(r,w)]){ p + w*f(scale(r)) },0.0) * (b - a)/2 +} diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Zkl/numerical-integration-gauss-legendre-quadrature-2.zkl b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Zkl/numerical-integration-gauss-legendre-quadrature-2.zkl new file mode 100644 index 0000000000..82b014fbbf --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Zkl/numerical-integration-gauss-legendre-quadrature-2.zkl @@ -0,0 +1,5 @@ +[5..10].walk().append(20).pump(Console.println,fcn(n){ + ("Gauss-Legendre %2d-point quadrature " + "\U222B;\U208B;\U2083;\U207A;\UB3; exp(x) dx = %.13f") + .fmt(n,quadrature(n, fcn(x){ x.exp() }, -3, 3)) +}) diff --git a/Task/Numerical-integration/Haskell/numerical-integration-6.hs b/Task/Numerical-integration/Haskell/numerical-integration-6.hs index c5e5fe2b77..4245b58dbe 100644 --- a/Task/Numerical-integration/Haskell/numerical-integration-6.hs +++ b/Task/Numerical-integration/Haskell/numerical-integration-6.hs @@ -1,70 +1,89 @@ -approx f xs ws = sum [w * f x | (x,w) <- zip xs ws] +approx + :: Fractional a + => (a1 -> a) -> [a1] -> [a] -> a +approx f xs ws = + sum + [ w * f x + | (x, w) <- zip xs ws ] -integrateOpen :: Fractional a => a -> [a] -> (a -> a) -> a -> a -> Int -> a -integrateOpen v vs f a b n = approx f xs ws * h / v where - m = fromIntegral (length vs) * n - h = (b-a) / fromIntegral m - ws = concat $ replicate n vs - c = a + h/2 - xs = [c + h * fromIntegral i | i <- [0..m-1]] +integrateOpen + :: Fractional a + => a -> [a] -> (a -> a) -> a -> a -> Int -> a +integrateOpen v vs f a b n = approx f xs ws * h / v + where + m = fromIntegral (length vs) * n + h = (b - a) / fromIntegral m + ws = concat $ replicate n vs + c = a + h / 2 + xs = + [ c + h * fromIntegral i + | i <- [0 .. m - 1] ] -integrateClosed :: Fractional a => a -> [a] -> (a -> a) -> a -> a -> Int -> a -integrateClosed v vs f a b n = approx f xs ws * h / v where - m = fromIntegral (length vs - 1) * n - h = (b-a) / fromIntegral m - ws = overlap n vs - xs = [a + h * fromIntegral i | i <- [0..m]] +integrateClosed + :: Fractional a + => a -> [a] -> (a -> a) -> a -> a -> Int -> a +integrateClosed v vs f a b n = approx f xs ws * h / v + where + m = fromIntegral (length vs - 1) * n + h = (b - a) / fromIntegral m + ws = overlap n vs + xs = + [ a + h * fromIntegral i + | i <- [0 .. m] ] -overlap :: Num a => Int -> [a] -> [a] -overlap n [] = [] -overlap n (x:xs) = x : inter n xs where - inter 1 ys = ys - inter n [] = x : inter (n-1) xs - inter n [y] = (x+y) : inter (n-1) xs - inter n (y:ys) = y : inter n ys - -intLeftRect = integrateClosed 1 [1,0] -intMidRect = integrateOpen 1 [1] -intRightRect = integrateClosed 1 [0,1] -intTrapezium = integrateClosed 2 [1,1] -intSimpson = integrateClosed 3 [1,4,1] +overlap + :: Num a + => Int -> [a] -> [a] +overlap n [] = [] +overlap n (x:xs) = x : inter n xs + where + inter 1 ys = ys + inter n [] = x : inter (n - 1) xs + inter n [y] = (x + y) : inter (n - 1) xs + inter n (y:ys) = y : inter n ys +uncurry4 :: (t1 -> t2 -> t3 -> t4 -> t) -> (t1, t2, t3, t4) -> t uncurry4 f ~(a, b, c, d) = f a b c d -main = do - let m1 = "rectangular left: " - let m2 = "rectangular middle: " - let m3 = "rectangular right: " - let m4 = "trapezium: " - let m5 = "simpson: " +-- TEST ---------------------------------------------------------------------- +ms + :: Fractional a + => [(String, (a -> a) -> a -> a -> Int -> a)] +ms = + [ ("rectangular left", integrateClosed 1 [1, 0]) + , ("rectangular middle", integrateOpen 1 [1]) + , ("rectangular right", integrateClosed 1 [0, 1]) + , ("trapezium", integrateClosed 2 [1, 1]) + , ("simpson", integrateClosed 3 [1, 4, 1]) + ] - let arg1 = ((\x -> x ^ 3), 0, 1, 100) - putStrLn $ m1 ++ (show $ uncurry4 intLeftRect arg1) - putStrLn $ m2 ++ (show $ uncurry4 intMidRect arg1) - putStrLn $ m3 ++ (show $ uncurry4 intRightRect arg1) - putStrLn $ m4 ++ (show $ uncurry4 intTrapezium arg1) - putStrLn $ m5 ++ (show $ uncurry4 intSimpson arg1) - putStrLn "" +integrations + :: (Fractional a, Num t, Num t1, Num t2) + => [(String, (a -> a, t, t1, t2))] +integrations = + [ ("x^3", ((^ 3), 0, 1, 100)) + , ("1/x", ((1 /), 1, 100, 1000)) + , ("x", (id, 0, 5000, 500000)) + , ("x", (id, 0, 6000, 600000)) + ] - let arg2 = ((\x -> 1 / x), 1, 100, 1000) - putStrLn $ m1 ++ (show $ uncurry4 intLeftRect arg2) - putStrLn $ m2 ++ (show $ uncurry4 intMidRect arg2) - putStrLn $ m3 ++ (show $ uncurry4 intRightRect arg2) - putStrLn $ m4 ++ (show $ uncurry4 intTrapezium arg2) - putStrLn $ m5 ++ (show $ uncurry4 intSimpson arg2) - putStrLn "" - - let arg3 = ((\x -> x), 0, 5000, 5000000) - putStrLn $ m1 ++ (show $ uncurry4 intLeftRect arg3) - putStrLn $ m2 ++ (show $ uncurry4 intMidRect arg3) - putStrLn $ m3 ++ (show $ uncurry4 intRightRect arg3) - putStrLn $ m4 ++ (show $ uncurry4 intTrapezium arg3) - putStrLn $ m5 ++ (show $ uncurry4 intSimpson arg3) - putStrLn "" - - let arg4 = ((\x -> x), 0, 6000, 6000000) - putStrLn $ m1 ++ (show $ uncurry4 intLeftRect arg4) - putStrLn $ m2 ++ (show $ uncurry4 intMidRect arg4) - putStrLn $ m3 ++ (show $ uncurry4 intRightRect arg4) - putStrLn $ m4 ++ (show $ uncurry4 intTrapezium arg4) - putStrLn $ m5 ++ (show $ uncurry4 intSimpson arg4) +main :: IO () +main = + mapM_ + (\(s, e@(_, a, b, n)) -> do + putStrLn + (concat + [ indent 20 ("f(x) = " ++ s) + , show [a, b] + , " (" + , show n + , " approximations)" + ]) + mapM_ + (\(s, integration) -> + putStrLn (indent 20 (s ++ ":") ++ show (uncurry4 integration e))) + ms + putStrLn []) + integrations + where + indent n = take n . (++ replicate n ' ') diff --git a/Task/Numerical-integration/Kotlin/numerical-integration.kotlin b/Task/Numerical-integration/Kotlin/numerical-integration.kotlin new file mode 100644 index 0000000000..a370139fdf --- /dev/null +++ b/Task/Numerical-integration/Kotlin/numerical-integration.kotlin @@ -0,0 +1,26 @@ +// version 1.1.2 + +typealias Func = (Double) -> Double + +fun integrate(a: Double, b: Double, n: Int, f: Func) { + val h = (b - a) / n + val sum = DoubleArray(5) + for (i in 0 until n) { + val 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 + } + val methods = listOf("LeftRect ", "MidRect ", "RightRect", "Trapezium", "Simpson ") + for (i in 0..4) println("${methods[i]} = ${"%f".format(sum[i] * h)}") + println() +} + +fun main(args: Array) { + integrate(0.0, 1.0, 100) { it * it * it } + integrate(1.0, 100.0, 1_000) { 1.0 / it } + integrate(0.0, 5000.0, 5_000_000) { it } + integrate(0.0, 6000.0, 6_000_000) { it } +} diff --git a/Task/Numerical-integration/Zkl/numerical-integration.zkl b/Task/Numerical-integration/Zkl/numerical-integration.zkl new file mode 100644 index 0000000000..4061d2758d --- /dev/null +++ b/Task/Numerical-integration/Zkl/numerical-integration.zkl @@ -0,0 +1,24 @@ +fcn integrate(F,f,a,b,steps){ + h:=(b - a) / steps; + h*(0).reduce(steps,'wrap(s,i){ F(f, h*i + a, h) + s },0.0); +} + +fcn rectangularLeft(f,x) { f(x) } +fcn rectangularMiddle(f,x,h){ f(x+h/2) } +fcn rectangularRight(f,x,h) { f(x+h) } +fcn trapezium(f,x,h) { (f(x) + f(x+h))/2 } +fcn simpson(f,x,h) { (f(x) + 4.0*f(x+h/2) + f(x+h))/6 } + +args:=T( T(fcn(x){ x.pow(3) }, 0.0, 1.0, 10), + T(fcn(x){ 1.0 / x }, 1.0, 100.0, 1000), + T(fcn(x){ x }, 0.0, 5000.0, 0d5_000_000), + T(fcn(x){ x }, 0.0, 6000.0, 0d6_000_000) ); +fs:=T(rectangularLeft,rectangularMiddle,rectangularRight, + trapezium,simpson); +names:=fs.pump(List,"name",'+(":"),"%-18s".fmt); + +foreach a in (args){ + names.zipWith('wrap(nm,f){ + "%s %f".fmt(nm,integrate(f,a.xplode())).println() }, fs); + println(); +} diff --git a/Task/Object-serialization/Zkl/object-serialization.zkl b/Task/Object-serialization/Zkl/object-serialization.zkl new file mode 100644 index 0000000000..eeab0c2575 --- /dev/null +++ b/Task/Object-serialization/Zkl/object-serialization.zkl @@ -0,0 +1,26 @@ +class [static] ARootClass{ // A top level class, no instances + class A{ self.println(" constructor"); } // a regular class + class B(A){ // ditto + var x; + fcn init(x=123){ self.x=x } + fcn toString{ "x is "+x } + } +} + +ARootClass.B(456).println(); // create an instance + // prints: + Class(A) constructor + x is 456 + +f:=File("object.dat","wb"); +Compiler.Asm.writeRootClass(ARootClass,f); // serialize to file +f.close(); + +f:=File("object.dat","rb"); +rc:=Compiler.Asm.readRootClass(f); // read and re-create + // prints (readRootClass calls all constructors by default): + Class(A) constructor +f.close(); +rc.B().println(); // create a new instance of B + // prints: + x is 123 diff --git a/Task/Odd-word-problem/BaCon/odd-word-problem.bacon b/Task/Odd-word-problem/BaCon/odd-word-problem.bacon new file mode 100644 index 0000000000..f7516e926a --- /dev/null +++ b/Task/Odd-word-problem/BaCon/odd-word-problem.bacon @@ -0,0 +1,42 @@ +OPEN "/dev/stdin" FOR DEVICE AS in + +FUNCTION get_odd() + + LOCAL ch, letter + + ch = MEMORY(1) + GETBYTE ch FROM in + + IF NOT(REGEX(CHR$(PEEK(ch)), "[[:punct:]]")) THEN + letter = get_odd() + PRINT CHR$(PEEK(ch)); + ELSE + letter = PEEK(ch) + END IF + + FREE ch + RETURN letter + +END FUNCTION + +mem = MEMORY(1) +PRINT "Enter string: "; + +WHILE TRUE + + GETBYTE mem FROM in + PRINT CHR$(PEEK(mem)); + + IF REGEX(CHR$(PEEK(mem)), "[[:punct:]]") THEN + IF PEEK(mem) <> 46 THEN + POKE mem, get_odd() + PRINT CHR$(PEEK(mem)); + END IF + IF PEEK(mem) = 46 THEN BREAK + END IF +WEND + +FREE mem +CLOSE DEVICE in + +PRINT diff --git a/Task/Odd-word-problem/Kotlin/odd-word-problem.kotlin b/Task/Odd-word-problem/Kotlin/odd-word-problem.kotlin new file mode 100644 index 0000000000..529f53b615 --- /dev/null +++ b/Task/Odd-word-problem/Kotlin/odd-word-problem.kotlin @@ -0,0 +1,31 @@ +// version 1.1.3 + +typealias Func = () -> Unit + +fun doChar(odd: Boolean, f: Func?): Boolean { + val c = System.`in`.read() + if (c == -1) return false // end of stream reached + val ch = c.toChar() + + fun writeOut() { + print(ch) + if (f != null) f() + } + + if (!odd) print(ch) + if (ch.isLetter()) return doChar(odd, ::writeOut) + if (odd) { + if (f != null) f() + print(ch) + } + return ch != '.' +} + +fun main(args: Array) { + repeat(2) { + var b = true + while (doChar(!b, null)) b = !b + System.`in`.read() // remove '\n' from buffer + println("\n") + } +} diff --git a/Task/Odd-word-problem/Phix/odd-word-problem.phix b/Task/Odd-word-problem/Phix/odd-word-problem.phix new file mode 100644 index 0000000000..48b6a58983 --- /dev/null +++ b/Task/Odd-word-problem/Phix/odd-word-problem.phix @@ -0,0 +1,33 @@ +string s = "what,is,the;meaning,of:life." +--string s = "we,are;not,in,kansas;any,more." +integer i = 0 + +function getchar() + i += 1 + return s[i] +end function + +function wrod(integer rev) + integer ch = getchar(), nch +-- integer ch = getc(0), nch + if not find(ch," .,:;!?") then + if rev then + nch = wrod(rev) + end if + puts(1,ch) + if not rev then + nch = wrod(rev) + end if + ch = nch + end if + return ch +end function + +--puts(1,"Enter words separated by a single punctuation mark (i.e. !?,.;:) and ending with .\n") +integer rev = 0 +while 1 do + integer ch = wrod(rev) + puts(1,ch) + if ch='.' then exit end if + rev = 1-rev +end while diff --git a/Task/Odd-word-problem/Zkl/odd-word-problem-1.zkl b/Task/Odd-word-problem/Zkl/odd-word-problem-1.zkl new file mode 100644 index 0000000000..c6de180437 --- /dev/null +++ b/Task/Odd-word-problem/Zkl/odd-word-problem-1.zkl @@ -0,0 +1,15 @@ +var [const] delim=",:;/?!@#$%^&*()_+", stop="."; +fcn oddly(inStream){ + inStream=inStream.walker(3); // character iterator: string, file, etc + doWord:=fcn(inStream,rev,f){ // print next word forewards or reverse + c:=inStream.next(); + if(not rev) c.print(); + if(not (c==stop or delim.holds(c))) + return(self.fcn(inStream,rev,'{ c.print(); f(); })); + if(rev){ f(); c.print(); } + return(c!=stop); + }; + tf:=Walker.cycle(False,True); // every other word printed backwords + while(doWord(inStream, tf.next(), Void)) {} + println(); +} diff --git a/Task/Odd-word-problem/Zkl/odd-word-problem-2.zkl b/Task/Odd-word-problem/Zkl/odd-word-problem-2.zkl new file mode 100644 index 0000000000..44ab094a7a --- /dev/null +++ b/Task/Odd-word-problem/Zkl/odd-word-problem-2.zkl @@ -0,0 +1,2 @@ +oddly("what,is,the;meaning,of:life."); +oddly(Data(0,String,"we,are;not,in,kansas;any,more.")); diff --git a/Task/Old-lady-swallowed-a-fly/C/old-lady-swallowed-a-fly.c b/Task/Old-lady-swallowed-a-fly/C/old-lady-swallowed-a-fly.c index 85e395f4fc..2aada18b7b 100644 --- a/Task/Old-lady-swallowed-a-fly/C/old-lady-swallowed-a-fly.c +++ b/Task/Old-lady-swallowed-a-fly/C/old-lady-swallowed-a-fly.c @@ -1,29 +1,36 @@ #include - -const char *dict[] = { -"_ha _c _e _p,/Quite absurd_f_p;_`cat,/Fancy that_fcat;_j`dog,/What a hog" -"_fdog;_l`pig,/Her mouth_qso big_fpig;_d_r,/She just opened her throat_f_" -"r;_icow,/_mhow she_ga cow;_k_o,/It_qrather wonky_f_o;_a_o_bcow,_khorse.." -"./She's dead, of course!/","_a_p_b_e ","/S_t "," to catch the ","fly,/Bu" -"t _mwhy s_t fly,/Perhaps she'll die!//_ha","_apig_bdog,_l`","spider,/Tha" -"t wr_nj_ntickled inside her;_aspider_b_c",", to_s a ","_sed ","There_qan" -" old lady who_g","_a_r_bpig,_d","_acat_b_p,_","_acow_b_r,_i","_adog_bcat" -",_j","I don't know ","iggled and ","donkey","bird"," was ","goat"," swal" -"low","he_gthe" +static char const *animals[] = { + "fly", + "spider", + "bird", + "cat", + "dog", + "goat", + "cow", + "horse" +}; +static char const *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" }; -int print(const char *c, int s) -{ - do { - if (s) s = print(dict[*c - 95], 0); - else if (*c == '_') s = 1; - else putchar(*c == '/' ? '\n' : *c); - } while (*++c); - return s; -} +#define LEN(ARR) (sizeof ARR / sizeof *ARR) -int main() +int main(void) { - print(dict[0], 0); - return 0; + for (size_t i = 0; i < LEN(animals); i++) { + printf("There was an old lady who swallowed a %s\n%s\n", animals[i], verses[i]); + for (size_t j = i; j > 0 && i < LEN(animals) - 1; j--) { + printf("She swallowed the %s to catch the %s\n", animals[j], animals[j-1]); + if (j == 1) { + printf("%s\n", verses[0]); + } + } + } } 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 96783962bc..130e4b8c47 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,10 +1,9 @@ -#import system. -#import extensions. +import extensions. -#symbol Creatures = ("fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"). -#symbol Comments = +const Creatures = ("fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"). +const Comments = ( - "I don't know why she swallowed that fly"#10"Perhaps she'll die", + "I don't know why she swallowed that fly"$10"Perhaps she'll die", "That wiggled and jiggled and tickled inside her", "How absurd, to swallow a bird", "Imagine that. She swallowed a cat", @@ -14,22 +13,22 @@ "She's dead of course" ). -#symbol program = +program = [ - 0 till:(Creatures length) &doEach: i + 0 till(Creatures length) do(:i) [ console - writeLine:"There was an old lady who swallowed a {0}" &args:(Creatures@i) - writeLine:(Comments@i). + printLineFormatted("There was an old lady who swallowed a {0}",Creatures[i]); + printLine(Comments[i]). - ((i != 0)&&(i != Creatures length - 1))? + if((i != 0)&&(i != Creatures length - 1)) [ - i till:0 &by:1 &doEach:j + i till:0 do(:j) [ - console writeLine:"She swallowed the {0} to catch the {1}" &args:(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. diff --git a/Task/Old-lady-swallowed-a-fly/Free-Pascal/old-lady-swallowed-a-fly.free b/Task/Old-lady-swallowed-a-fly/Free-Pascal/old-lady-swallowed-a-fly.free new file mode 100644 index 0000000000..a9953cbad3 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Free-Pascal/old-lady-swallowed-a-fly.free @@ -0,0 +1,80 @@ +(* A mixture of the lyrics found in Wikipedia and the Ada version + in Rosetta Code. It formats the lyrics like the Wikipedia one *) +program OldLady; + +uses + SysUtils; + +const + MaxLadies = 9; //Number of iterations and array items + Animals: array[1..MaxLadies + 1] of shortstring = ( //Add one for the song's end + 'fly', + 'spider', + 'bird', + 'cat', + 'dog', + 'pig', + 'goat', + 'cow', + 'donkey', + 'horse' + ); + + Verse1 = 'There was an old lady who swallowed a %s;'; + //Verse 2 variations + Verse2Var1 = ' %s'; //Doubles as a spacing formatter + Verse2Var2 = ' %s to swallow a %s;'; + Verse2Var3 = ' %s and swallowed a %s'; + Verse2Var4 = ' %s she swallowed a %s'; + Verse3 = ' She swallowed the %s to catch the %s;'; + VerseEnd = 'I don''t know why she swallowed a fly - perhaps she''ll die!'; + SongEnd = ' ...She''s dead of course!'; + + SwallowResult: array[1..MaxLadies] of shortstring = ( + VerseEnd, + 'That wiggled and jiggled and tickled inside her!', + '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' + ); + + procedure PrintSong; + var + i, j: byte; + SwallowStr: shortstring; + + begin + for i := 1 to MaxLadies do + begin + WriteLn(Format(Verse1, [Animals[i]])); + case i of + 1..2: SwallowStr := Verse2Var1; + 3..5: SwallowStr := Verse2Var2; + 6, 8..9: SwallowStr := Verse2Var4; + else + SwallowStr := Verse2Var3; + end; + WriteLn(Format(SwallowStr, [SwallowResult[i], Animals[i]])); + if i >= 2 then + begin + for j := i downto 2 do + begin + WriteLn(Format(Verse3, [Animals[j], Animals[j - 1]])); + if (j - 1 = 2) and (i >= 3) then + WriteLn(Format(Verse2Var1, [SwallowResult[2]])); + end; + if j >= 2 then + WriteLn(Format(Verse2Var1, [VerseEnd])); + end; + end; + WriteLn(Format(Verse1, [Animals[MaxLadies + 1]])); + WriteLn(SongEnd); + end; + +begin + PrintSong; +end. diff --git a/Task/Old-lady-swallowed-a-fly/Go/old-lady-swallowed-a-fly.go b/Task/Old-lady-swallowed-a-fly/Go/old-lady-swallowed-a-fly.go index 41207371f2..d86124e28a 100644 --- a/Task/Old-lady-swallowed-a-fly/Go/old-lady-swallowed-a-fly.go +++ b/Task/Old-lady-swallowed-a-fly/Go/old-lady-swallowed-a-fly.go @@ -26,9 +26,8 @@ func main() { break } - for i > 0 { + for ; i > 0; i-- { fmt.Printf("She swallowed the %s to catch the %s,\n", animals[i][name], animals[i-1][name]) - i-- } fmt.Println(animals[0][lyric] + "\n") diff --git a/Task/Old-lady-swallowed-a-fly/Haskell/old-lady-swallowed-a-fly.hs b/Task/Old-lady-swallowed-a-fly/Haskell/old-lady-swallowed-a-fly.hs index c0b828aa7c..470e3f8017 100644 --- a/Task/Old-lady-swallowed-a-fly/Haskell/old-lady-swallowed-a-fly.hs +++ b/Task/Old-lady-swallowed-a-fly/Haskell/old-lady-swallowed-a-fly.hs @@ -1,6 +1,4 @@ -#!/usr/bin/env runhaskell - -import Data.List +import Data.List (tails) -- Once means the phrase is only printed in the verse about that animal. -- Every means the phrase is printed for every verse. It is used for "fly", @@ -8,34 +6,43 @@ import Data.List -- "wriggled and jiggled..." is repeated every verse. -- Die is only used for the horse, and means the chain of animals won't be -- included in the verse. -data AnimalAction = Once | Every | Die +data AnimalAction + = Once + | Every + | Die -animals = [("horse", Die, "She's dead, of course!"), - ("donkey", Once, "It was rather wonky. To swallow a donkey."), - ("cow", Once, "I don't know how. To swallow a cow."), - ("goat", Once, "She just opened her throat. To swallow a goat."), - ("pig", Once, "Her mouth was so big. To swallow a pig."), - ("dog", Once, "What a hog. To swallow a dog."), - ("cat", Once, "Fancy that. To swallow a cat."), - ("bird", Once, "Quite absurd. To swallow a bird."), - ("spider", Once, "That wriggled and jiggled and tickled inside her."), - ("fly", Every, "I don't know why she swallowed the fly.")] +animals = + [ ("horse", Die, "She's dead, of course!") + , ("donkey", Once, "It was rather wonky. To swallow a donkey.") + , ("cow", Once, "I don't know how. To swallow a cow.") + , ("goat", Once, "She just opened her throat. To swallow a goat.") + , ("pig", Once, "Her mouth was so big. To swallow a pig.") + , ("dog", Once, "What a hog. To swallow a dog.") + , ("cat", Once, "Fancy that. To swallow a cat.") + , ("bird", Once, "Quite absurd. To swallow a bird.") + , ("spider", Once, "That wriggled and jiggled and tickled inside her.") + , ("fly", Every, "I don't know why she swallowed the fly.") + ] verse :: [(String, AnimalAction, String)] -> [String] verse ((anim, act, phrase):restAnims) = let lns = ["I know an old lady who swallowed a " ++ anim ++ ".", phrase] - in case act of Die -> lns - _ -> lns ++ verse' restAnims anim + in case act of + Die -> lns + _ -> lns ++ verse' restAnims anim verse' :: [(String, AnimalAction, String)] -> String -> [String] verse' [] _ = ["Perhaps she'll die."] verse' ((anim, act, phrase):restAnims) prevAnim = let why = "She swallowed the " ++ prevAnim ++ " to catch the " ++ anim ++ "." - lns = case act of Every -> [why, phrase] - _ -> [why] + lns = + case act of + Every -> [why, phrase] + _ -> [why] in lns ++ verse' restAnims anim song :: [String] -song = concatMap verse $ tail $ reverse $ tails animals +song = concatMap verse . tail . reverse $ tails animals +main :: IO () main = putStr $ unlines song 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.kotlin new file mode 100644 index 0000000000..92083ae883 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Kotlin/old-lady-swallowed-a-fly.kotlin @@ -0,0 +1,35 @@ +// version 1.1.3 + +val animals = listOf("fly", "spider", "bird", "cat","dog", "goat", "cow", "horse") + +val phrases = listOf( + "", + "That wriggled and jiggled and tickled inside her", + "How absurd to swallow a bird", + "Fancy that to swallow a cat", + "What a hog, to swallow a dog", + "She just opened her throat and swallowed a goat", + "I don't know how she swallowed a cow", + "\n ...She's dead of course" +) + +fun sing() { + for (i in 0..7) { + println("There was an old lady who swallowed a ${animals[i]};") + if (i > 0) println("${phrases[i]}!") + if (i == 7) return + println() + if (i > 0) { + for (j in i downTo 1) { + print(" She swallowed the ${animals[j]} to catch the ${animals[j - 1]}") + println(if (j < 3) ";" else ",") + if (j == 2) println(" ${phrases[1]}!") + } + } + println(" I don't know why she swallowed a fly - Perhaps she'll die!\n") + } +} + +fun main(args: Array) { + sing() +} diff --git a/Task/Old-lady-swallowed-a-fly/Python/old-lady-swallowed-a-fly.py b/Task/Old-lady-swallowed-a-fly/Python/old-lady-swallowed-a-fly-1.py similarity index 100% rename from Task/Old-lady-swallowed-a-fly/Python/old-lady-swallowed-a-fly.py rename to Task/Old-lady-swallowed-a-fly/Python/old-lady-swallowed-a-fly-1.py diff --git a/Task/Old-lady-swallowed-a-fly/Python/old-lady-swallowed-a-fly-2.py b/Task/Old-lady-swallowed-a-fly/Python/old-lady-swallowed-a-fly-2.py new file mode 100644 index 0000000000..566c0f40b1 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Python/old-lady-swallowed-a-fly-2.py @@ -0,0 +1,20 @@ +animals = [ + ("fly", "I don't know why she swallowed a fly, perhaps she'll die."), + ("spider", "It wiggled and jiggled and tickled inside her."), + ("bird", "How absurd, to swallow a bird."), + ("cat", "Imagine that, she swallowed a cat."), + ("dog", "What a hog, to swallow a dog."), + ("goat", "She just opened her throat and swallowed a goat."), + ("cow", "I don't know how she swallowed a cow."), + ("horse", "She's dead, of course.")] + +for i, (animal, lyric) in enumerate(animals): + print "There was an old lady who swallowed a {}.\n{}".format(animal, lyric) + + if animal == "horse": break + + for (predator, _), (prey, _) in zip(animals[i:0:-1], animals[i-1::-1]): + print "\tShe swallowed the {} to catch the {}".format(predator, prey) + + if animal != "fly": print animals[0][1] # fly lyric + print # new line diff --git a/Task/Old-lady-swallowed-a-fly/REXX/old-lady-swallowed-a-fly.rexx b/Task/Old-lady-swallowed-a-fly/REXX/old-lady-swallowed-a-fly.rexx index 0a458d1ad7..2d4b1d861c 100644 --- a/Task/Old-lady-swallowed-a-fly/REXX/old-lady-swallowed-a-fly.rexx +++ b/Task/Old-lady-swallowed-a-fly/REXX/old-lady-swallowed-a-fly.rexx @@ -1,5 +1,5 @@ -/*REXX pgm displays song lyrics for "I Know an Old Lady who Swallowed a Fly". */ -sw=79 /*width of terminal screen, -1.*/ +/*REXX program displays song lyrics for: "I Know an Old Lady who Swallowed a Fly". */ +sw=79 /*the width of the terminal screen, -1.*/ I_know= "I know an old lady who swallowed a" @ate = 'She swallowed the'; @2catch= "to catch the" ; @.= @.1 = "I don't know why she swallowed a fly," @@ -11,15 +11,14 @@ I_know= "I know an old lady who swallowed a" @.7 = "I wonder how she swallowed a cow?!" @.8 = "She's dead, of course!!" $ = 'fly spider bird cat dog goat cow horse' ; #=words($) - /* [↓] display blank line*/ - do j=1 for #; fauna=word($,j); say + /* [↓] display a blank line to term. */ + do j=1 for #; fauna=word($,j); say say center(I_know fauna',', sw); if j\==1 then say center(@.j, sw) - if j==# then leave /*Last verse? We're done.*/ - do k=j to 2 by -1; km=k-1 - say center(@ate word($,k) @2catch word($,km)',',sw) + if j==# then leave /*Is this the last verse? We're done.*/ + do k=j to 2 by -1; km=k-1 + say center(@ate word($, k) @2catch word($, km)',', sw) if @.km.0\=='' then say center(@.km, sw) - end /*k*/ /* [↑] display the lyrics of the song.*/ + end /*k*/ /* [↑] display the lyrics of the song.*/ say center(@.1, sw) say center("I guess she'll die.", sw) - end /*j*/ - /*stick a fork in it, we're all done. */ + end /*j*/ /*stick a fork in it, we're all done. */ 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.rust new file mode 100644 index 0000000000..0708bde065 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Rust/old-lady-swallowed-a-fly.rust @@ -0,0 +1,27 @@ +enum Action {Once, Every, Die} +use Action::*; + +fn main() { + let animals = [ ("horse" , Die , "She's dead, of course!") + , ("donkey", Once , "It was rather wonky. To swallow a donkey.") + , ("cow" , Once , "I don't know how. To swallow a cow.") + , ("goat" , Once , "She just opened her throat. To swallow a goat.") + , ("pig" , Once , "Her mouth was so big. To swallow a pig.") + , ("dog" , Once , "What a hog. To swallow a dog.") + , ("cat" , Once , "Fancy that. To swallow a cat.") + , ("bird" , Once , "Quite absurd. To swallow a bird.") + , ("spider", Once , "That wriggled and jiggled and tickled inside her.") + , ("fly" , Every, "I don't know why she swallowed the fly.") + ]; + for (i, a) in animals.iter().enumerate().rev() { + println!("There was an old lady who swallowed a {}\n{}", a.0, a.2); + if let Die = a.1 {break} + for (swallowed, to_catch) in animals[i..].iter().zip(&animals[i+1..]) { + println!("She swallowed the {} to catch the {}.", swallowed.0, to_catch.0); + if let Every = to_catch.1 { + println!("{}", to_catch.2); + } + } + println!("Perhaps she'll die.\n"); + } +} diff --git a/Task/Old-lady-swallowed-a-fly/Zkl/old-lady-swallowed-a-fly.zkl b/Task/Old-lady-swallowed-a-fly/Zkl/old-lady-swallowed-a-fly.zkl new file mode 100644 index 0000000000..265f04c104 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Zkl/old-lady-swallowed-a-fly.zkl @@ -0,0 +1,11 @@ +var ZLib=Import("zeelib"), MsgHash=Import("zklMsgHash"); +text:= + "eJztlE1uwyAQhdflFOOVNyhXyLap1FV7AWKIoaFMBFjIt++M7YVpLfVHilQp2cHMg3l8T+IA" + "54AFVAD0GrzSIxSLkIryHovRoODkRykOoDG0eVYXO0KyZqXKtFt0/WBS4nbrPWhndoKK3w5J" + "F6dNlA/i1aoMJbq+99wIGt5W6+y6M69dSKQHa+JOvHxxMl8GGaFTubNrd9d9xdFFLcUjq45p" + "iJotLP2l22zY5XptdqHxaxjyP8GgcXT4XfUuGLqNdjUO6m/RoHJtdoZ6M9g09lI8j5Ia9AoF" + "lvY1OFJsgaNybXcK4LYA/4Bvj4zlaUgZ8GIC1SzbsBEZN9n/LN5izfXa+hTbPZQ/fxZY+HDB" + "wPMtqesBk2K/+V+QtvI7B3zP7OqZWYzJTI7aBNooLQFPlMdA5aYRH3dS5jc="; + +MsgHash.base64decode(text) : +ZLib.Inflator().write(_).close().read().text.println(); diff --git a/Task/One-dimensional-cellular-automata/ALGOL-W/one-dimensional-cellular-automata.alg b/Task/One-dimensional-cellular-automata/ALGOL-W/one-dimensional-cellular-automata.alg new file mode 100644 index 0000000000..1e63312522 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/ALGOL-W/one-dimensional-cellular-automata.alg @@ -0,0 +1,20 @@ +begin + string(20) state; + string(20) nextState; + integer generation; + generation := 0; + state := "_###_##_#_#_#_#__#__"; + while begin + write( i_w := 1, s_w := 1, "Generation ", generation, state ); + nextState := "____________________"; + for cPos := 1 until 18 do begin + string(3) curr; + curr := state( cPos - 1 // 3 ); + nextState( cPos // 1 ) := if curr = "_##" or curr = "#_#" or curr = "##_" then "#" else "_" + end for_cPos ; + ( state not = nextState ) + end do begin + state := nextState; + generation := generation + 1 + end while_not_finished +end. diff --git a/Task/One-dimensional-cellular-automata/BASIC/one-dimensional-cellular-automata.basic b/Task/One-dimensional-cellular-automata/BASIC/one-dimensional-cellular-automata-1.basic similarity index 100% rename from Task/One-dimensional-cellular-automata/BASIC/one-dimensional-cellular-automata.basic rename to Task/One-dimensional-cellular-automata/BASIC/one-dimensional-cellular-automata-1.basic diff --git a/Task/One-dimensional-cellular-automata/BASIC/one-dimensional-cellular-automata-2.basic b/Task/One-dimensional-cellular-automata/BASIC/one-dimensional-cellular-automata-2.basic new file mode 100644 index 0000000000..bc4b438f01 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/BASIC/one-dimensional-cellular-automata-2.basic @@ -0,0 +1,19 @@ + 10 LET N$="01110110101010100100" + 20 LET G=1 + 30 PRINT N$ + 40 LET O$=N$ + 50 LET N$="" + 60 PRINT AT 0,28;G + 70 LET N=0 + 80 FOR I=1 TO LEN O$ + 90 IF I=1 THEN GOTO 120 +100 LET N=VAL O$(I-1) +110 IF I=LEN O$ THEN GOTO 130 +120 LET N=N+VAL O$(I+1) +130 IF N=0 THEN LET N$=N$+"0" +140 IF N=1 THEN LET N$=N$+O$(I) +150 IF N=2 THEN LET N$=N$+STR$ NOT VAL O$(I) +160 PRINT AT 0,I-1;N$(I) +170 NEXT I +180 LET G=G+1 +190 IF N$<>O$ THEN GOTO 40 diff --git a/Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata.cobol b/Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata-1.cobol similarity index 100% rename from Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata.cobol rename to Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata-1.cobol diff --git a/Task/One-dimensional-cellular-automata/CoffeeScript/one-dimensional-cellular-automata-1.coffee b/Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata-2.cobol similarity index 100% rename from Task/One-dimensional-cellular-automata/CoffeeScript/one-dimensional-cellular-automata-1.coffee rename to Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata-2.cobol diff --git a/Task/One-dimensional-cellular-automata/CoffeeScript/one-dimensional-cellular-automata-2.coffee b/Task/One-dimensional-cellular-automata/CoffeeScript/one-dimensional-cellular-automata-2.coffee deleted file mode 100644 index d3ad75ccb0..0000000000 --- a/Task/One-dimensional-cellular-automata/CoffeeScript/one-dimensional-cellular-automata-2.coffee +++ /dev/null @@ -1,11 +0,0 @@ -> coffee cellular_automata.coffee -.###.##.#.#.#.#..#.. -.#.#####.#.#.#...... -..##...##.#.#....... -..##...###.#........ -..##...#.##......... -..##....###......... -..##....#.#......... -..##.....#.......... -..##................ -equilibrium achieved diff --git a/Task/One-dimensional-cellular-automata/CoffeeScript/one-dimensional-cellular-automata.coffee b/Task/One-dimensional-cellular-automata/CoffeeScript/one-dimensional-cellular-automata.coffee deleted file mode 100644 index 417d619935..0000000000 --- a/Task/One-dimensional-cellular-automata/CoffeeScript/one-dimensional-cellular-automata.coffee +++ /dev/null @@ -1,32 +0,0 @@ -# We could cheat and count the bits, but let's keep this general. -# . = dead, # = alive, middle cells survives iff one of the configurations -# below is satisified. -survival_scenarios = [ - '.##' # happy neighbors - '#.#' # birth - '##.' # happy neighbors -] - -b2c = (b) -> if b then '#' else '.' - -cell_next_gen = (left_alive, me_alive, right_alive) -> - fingerprint = b2c(left_alive) + b2c(me_alive) + b2c(right_alive) - fingerprint in survival_scenarios - -cells_for_next_gen = (cells) -> - # This function assumes a finite array, i.e. cells can't be born outside - # the original array. - (cell_next_gen(cells[i-1], cells[i], cells[i+1]) for i in [0...cells.length]) - -display = (cells) -> - (b2c(is_alive) for is_alive in cells).join '' - -simulate = (cells) -> - while true - console.log display cells - new_cells = cells_for_next_gen cells - break if display(cells) == display(new_cells) - cells = new_cells - console.log "equilibrium achieved" - -simulate (c == '#' for c in ".###.##.#.#.#.#..#..") diff --git a/Task/One-dimensional-cellular-automata/Haskell/one-dimensional-cellular-automata-1.hs b/Task/One-dimensional-cellular-automata/Haskell/one-dimensional-cellular-automata-1.hs index 45d6ccfa21..bc258555f5 100644 --- a/Task/One-dimensional-cellular-automata/Haskell/one-dimensional-cellular-automata-1.hs +++ b/Task/One-dimensional-cellular-automata/Haskell/one-dimensional-cellular-automata-1.hs @@ -1,24 +1,32 @@ -module Life1D where +import Data.List (unfoldr) +import System.Random (newStdGen, randomRs) +import Control.Monad (liftM2, ap) -import Data.List -import System.Random -import Control.Monad -import Control.Arrow - -bnd :: [Char] -> Char +bnd :: String -> Char bnd bs = - case bs of - "_##" -> '#' - "#_#" -> '#' - "##_" -> '#' - _ -> '_' + case bs of + "_##" -> '#' + "#_#" -> '#' + "##_" -> '#' + _ -> '_' -donxt xs = unfoldr(\xs -> case xs of [_,_] -> Nothing ; - _ -> Just (bnd $ take 3 xs, drop 1 xs)) $ '_':xs++"_" +donxt :: String -> String +donxt xs = + unfoldr + (\xs -> + case xs of + [_, _] -> Nothing + _ -> Just (bnd $ take 3 xs, drop 1 xs)) $ + '_' : xs ++ "_" -lahmahgaan xs = init.until (liftM2 (==) last (last. init)) (ap (++)(return. donxt. last)) $ [xs, donxt xs] +lahmahgaan :: String -> [String] +lahmahgaan xs = + init . + until (liftM2 (==) last (last . init)) (ap (++) (return . donxt . last)) $ + [xs, donxt xs] +main :: IO () main = do - g <- newStdGen - let oersoep = map ("_#"!!). take 36 $ randomRs(0,1) g - mapM_ print . lahmahgaan $ oersoep + g <- newStdGen + let oersoep = map ("_#" !!) . take 36 $ randomRs (0, 1) g + mapM_ print . lahmahgaan $ oersoep diff --git a/Task/One-dimensional-cellular-automata/jq/one-dimensional-cellular-automata-1.jq b/Task/One-dimensional-cellular-automata/Jq/one-dimensional-cellular-automata-1.jq similarity index 100% rename from Task/One-dimensional-cellular-automata/jq/one-dimensional-cellular-automata-1.jq rename to Task/One-dimensional-cellular-automata/Jq/one-dimensional-cellular-automata-1.jq diff --git a/Task/One-dimensional-cellular-automata/jq/one-dimensional-cellular-automata-2.jq b/Task/One-dimensional-cellular-automata/Jq/one-dimensional-cellular-automata-2.jq similarity index 100% rename from Task/One-dimensional-cellular-automata/jq/one-dimensional-cellular-automata-2.jq rename to Task/One-dimensional-cellular-automata/Jq/one-dimensional-cellular-automata-2.jq diff --git a/Task/One-dimensional-cellular-automata/Liberty-BASIC/one-dimensional-cellular-automata.liberty b/Task/One-dimensional-cellular-automata/Liberty-BASIC/one-dimensional-cellular-automata.liberty index f05cb93d6e..e5673fb8e7 100644 --- a/Task/One-dimensional-cellular-automata/Liberty-BASIC/one-dimensional-cellular-automata.liberty +++ b/Task/One-dimensional-cellular-automata/Liberty-BASIC/one-dimensional-cellular-automata.liberty @@ -1,16 +1,15 @@ ' [RC] 'One-dimensional cellular automata' - -global rule$, state$ - +' does not wrap so fails for some rules rule$ ="00010110" ' Rule 22 decimal state$ ="0011101101010101001000" for j =1 to 20 + print state$ oldState$ =state$ state$ ="0" - for k =2 to 32 + for k =2 to len( oldState$) -1 NHood$ =mid$( oldState$, k -1, 3) ' pick 3 char neighbourhood and turn binary string to decimal vNHood =0 for kk =3 to 1 step -1 @@ -19,8 +18,8 @@ for j =1 to 20 ' .... & use it to index into rule$ to find appropriate new value state$ =state$ +mid$( rule$, vNHood +1, 1) next k + state$ =state$ +"0" - print state$ next j end diff --git a/Task/One-dimensional-cellular-automata/Mathematica/one-dimensional-cellular-automata-2.math b/Task/One-dimensional-cellular-automata/Mathematica/one-dimensional-cellular-automata-2.math index 364c35a0ce..3bb13c0dc1 100644 --- a/Task/One-dimensional-cellular-automata/Mathematica/one-dimensional-cellular-automata-2.math +++ b/Task/One-dimensional-cellular-automata/Mathematica/one-dimensional-cellular-automata-2.math @@ -1,13 +1 @@ -###.##.#.#.#.#..# -#.#####.#.#.#.... -.##...##.#.#..... -.##...###.#...... -.##...#.##....... -.##....###....... -.##....#.#....... -.##.....#........ -.##.............. -.##.............. -.##.............. -.##.............. -.##.............. +CellularAutomaton[2^^01101000 (* == 104 *), {{1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1}, 0}, 12]; diff --git a/Task/One-dimensional-cellular-automata/Mathematica/one-dimensional-cellular-automata-3.math b/Task/One-dimensional-cellular-automata/Mathematica/one-dimensional-cellular-automata-3.math new file mode 100644 index 0000000000..364c35a0ce --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Mathematica/one-dimensional-cellular-automata-3.math @@ -0,0 +1,13 @@ +###.##.#.#.#.#..# +#.#####.#.#.#.... +.##...##.#.#..... +.##...###.#...... +.##...#.##....... +.##....###....... +.##....#.#....... +.##.....#........ +.##.............. +.##.............. +.##.............. +.##.............. +.##.............. diff --git a/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata-1.nimrod b/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata-1.nimrod deleted file mode 100644 index ef2639f28e..0000000000 --- a/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata-1.nimrod +++ /dev/null @@ -1,68 +0,0 @@ -import math -randomize() - -type - TBoolArray = array[0..30, bool] # an array that is indexed with 0..10 - TSymbols = tuple[on: char , off: char] - -const - num_turns = 20 - symbols:TSymbols = ('#','_') - -proc `==` (x:TBoolArray,y:TBoolArray): bool = - if len(x) != len(y): - return False - for i in 0..(len(x)-1): - if x[i] != y[i]: - return False - return True - -proc count_neighbours(map:TBoolArray , tile:int):int = - result = 0 - if tile != len(map)-1 and map[tile+1]: - result += 1 - if tile != 0 and map[tile-1]: - result += 1 - -proc print_map(map:TBoolArray, symbols:TSymbols) = - for i in map: - if i: - write(stdout,symbols[0]) - else: - write(stdout,symbols[1]) - write(stdout,"\n") - -proc random_map(): TBoolArray = - var map = [False,False,False,False,False,False,False,False,False,False,False, - False,False,False,False,False,False,False,False,False,False,False, - False,False,False,False,False,False,False,False,False] - for i in 0..(len(map)-1): - map[i] = bool(random(2)) - return map - -proc fixed_map(): TBoolArray = - var map = [False,True,True,True,False,True,True,False,True,False,True, - False,True,False,True,False,False,True,False,False,False,False, - False,False,False,False,False,False,False,False,False] - return map - -#make the map -var map:TBoolArray -#map = random_map() # uncomment for random start -map = fixed_map() -print_map(map,symbols) -for i in 0..num_turns: - var new_map = map - for j in 0..(len(map)-1): - if map[j]: - if count_neighbours(map, j) == 2 or - count_neighbours(map, j) == 0: - new_map[j] = False - else: - if count_neighbours(map, j) == 2: - new_map[j] = True - if new_map == map: - print_map(map,symbols) - break - map = new_map - print_map(map,symbols) diff --git a/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata-2.nimrod b/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata-2.nimrod deleted file mode 100644 index 7b502630ca..0000000000 --- a/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata-2.nimrod +++ /dev/null @@ -1,26 +0,0 @@ -const - s_init: string = "_###_##_#_#_#_#__#__" - arrLen: int = 20 - -var q0: string = s_init & repeatChar(arrLen-20,'_') -var q1: string = q0 - -proc life(s:string): char = - var str: string = s - if len(normalize(str)) == 2: # normalize eliminates underscores - return '#' - return '_' - -proc evolve(q: string): string = - result = repeatChar(arrLen,'_') - #result[0] = '_' - for i in 1 .. q.len-1: - result[i] = life(substr(q & '_',i-1,i+1)) - -echo(q1) -q1 = evolve(q0) -echo(q1) -while q1 != q0: - q0 = q1 - q1 = evolve(q0) - echo(q1) diff --git a/Task/One-dimensional-cellular-automata/Pascal/one-dimensional-cellular-automata.pascal b/Task/One-dimensional-cellular-automata/Pascal/one-dimensional-cellular-automata.pascal new file mode 100644 index 0000000000..2f84d34f9e --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Pascal/one-dimensional-cellular-automata.pascal @@ -0,0 +1,73 @@ +program Test; +{$IFDEF FPC}{$MODE DELPHI}{$ELSE}{$APPTYPE}{$ENDIF} +uses + sysutils; +const + cCHAR: array[0..1] of char = ('_','#'); +type + TRow = array of byte; + +function ConvertToRow(const s:string):tRow; +var + i : NativeInt; +Begin + i := length(s); + setlength(Result,length(s)); + For i := i downto 0 do + result[i-1]:= ORD(s[i]=cChar[1]); +end; + +function OutRow(const row:tRow):string; +//create output string +var + i: NativeInt; +Begin + i := length(row); + setlength(result,i); + For i := i downto 1 do + result[i]:= cChar[row[i-1]]; +end; + +procedure NextRow(row:pByteArray;MaxIdx:NativeInt); +//compute next row in place by the using a small storage for the +//2 values, that would otherwise be overridden +var + leftValue,Value: NativeInt; + i,trpCnt: NativeInt; +Begin + leftValue := 0; + trpCnt := row[0]+row[1]; + + i := 0; + while i < MaxIdx do + Begin + Value := row[i]; + //the rule for survive : PopCnt == 2 + row[i] := ORD(trpCnt= 2); + //reduce popcnt of element before + dec(trpCnt,leftValue); + //goto next element + inc(i); + leftValue := Value; + //increment popcnt by right element + inc(trpCnt,row[i+1]); + //move to next position in ring buffer + end; + row[MaxIdx] := ORD(trpCnt= 2); +end; + +const + TestString: string=' ### ## # # # # # '; +var + s: string; + row:tRow; + i: NativeInt; +begin + s := Teststring; + row:= ConvertToRow(s); + For i := 0 to 9 do + Begin + writeln(OutRow(row)); + NextRow(@row[0],High(row)); + end; +end. diff --git a/Task/One-dimensional-cellular-automata/Prolog/one-dimensional-cellular-automata.pro b/Task/One-dimensional-cellular-automata/Prolog/one-dimensional-cellular-automata.pro index a2ee05e30f..7ff9b9856e 100644 --- a/Task/One-dimensional-cellular-automata/Prolog/one-dimensional-cellular-automata.pro +++ b/Task/One-dimensional-cellular-automata/Prolog/one-dimensional-cellular-automata.pro @@ -33,7 +33,28 @@ compute_next([1, 1, 1 | R], [0 | R1]) :- % the last four possibilies => % we consider that there is à 0 after the end -compute_next([0, 0], [0]). +complang jq># The 1-d cellular automaton: +def next: + # Conveniently, jq treats null as 0 when it comes to addition + # so there is no need to fiddle with the boundaries + . as $old + | reduce range(0; length) as $i + ([]; + ($old[$i-1] + $old[$i+1]) as $s + | if $s == 0 then .[$i] = 0 + elif $s == 1 then .[$i] = (if $old[$i] == 1 then 1 else 0 end) + else .[$i] = (if $old[$i] == 1 then 0 else 1 end) + end); + + +# pretty-print an array: +def pp: reduce .[] as $i (""; . + (if $i == 0 then " " else "*" end)); + +# continue until quiescence: +def go: recurse(. as $prev | next | if . == $prev then empty else . end) | pp; + +# Example: +[0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0] | goute_next([0, 0], [0]). compute_next([1, 0], [0]). diff --git a/Task/One-dimensional-cellular-automata/SequenceL/one-dimensional-cellular-automata.sequencel b/Task/One-dimensional-cellular-automata/SequenceL/one-dimensional-cellular-automata.sequencel new file mode 100644 index 0000000000..70abd243f9 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/SequenceL/one-dimensional-cellular-automata.sequencel @@ -0,0 +1,30 @@ +import ; + +main(args(2)) := + run(args[1], stringToInt(args[2])) when size(args) = 2 +else + "Usage error: exec "; + +stringToCells(string(1))[i] := 0 when string[i] = '_' else 1; +cellsToString(cells(1))[i] := '#' when cells[i] = 1 else '_'; + +run(cellsString(1), generations) := + runHelper(stringToCells(cellsString), generations, cellsString); + +runHelper(cells(1), generations, result(1)) := + let + nextCells := step(cells); + in + result when generations = 0 + else + runHelper(nextCells, generations - 1, + result ++ "\n" ++ cellsToString(nextCells)); + +step(cells(1))[i] := + let + left := cells[i-1] when i > 1 else 0; + right := cells[i + 1] when i < size(cells) else 0; + in + 1 when (left + cells[i] + right) = 2 + else + 0; diff --git a/Task/One-dimensional-cellular-automata/Wart/one-dimensional-cellular-automata-2.wart b/Task/One-dimensional-cellular-automata/Wart/one-dimensional-cellular-automata-2.wart index 89234b824e..0b404f5776 100644 --- a/Task/One-dimensional-cellular-automata/Wart/one-dimensional-cellular-automata-2.wart +++ b/Task/One-dimensional-cellular-automata/Wart/one-dimensional-cellular-automata-2.wart @@ -1,10 +1,10 @@ -def (uca l) # new datatype: unidim CA +def (uca l) # new datatype: Uni-dimensional Cellular Automaton (tag uca (list l len.l)) def (len l) :case (isa uca l) # how to compute its length rep.l.1 -defcoerce uca list # converting it to list +defcoerce uca list # how to convert it to a list (fn(_) rep._.0) def (pr l) :case (isa uca l) # how to print it diff --git a/Task/One-dimensional-cellular-automata/Zkl/one-dimensional-cellular-automata-1.zkl b/Task/One-dimensional-cellular-automata/Zkl/one-dimensional-cellular-automata-1.zkl new file mode 100644 index 0000000000..52a2fced60 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Zkl/one-dimensional-cellular-automata-1.zkl @@ -0,0 +1,5 @@ +fcn life1D(line){ + right:=line[1,*] + False; // shift left, False fill + left :=T(False).extend(line[0,-1]); // shift right + left.zip(line,right).apply(fcn(hood){ hood.sum(0)==2 }); +} diff --git a/Task/One-dimensional-cellular-automata/Zkl/one-dimensional-cellular-automata-2.zkl b/Task/One-dimensional-cellular-automata/Zkl/one-dimensional-cellular-automata-2.zkl new file mode 100644 index 0000000000..9e5d15fb32 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Zkl/one-dimensional-cellular-automata-2.zkl @@ -0,0 +1,3 @@ +chars:=T("_","#"); +cells:="_###_##_#_#_#_#__#__".split("").apply('==("#")); //-->L(False,True,True,True,False...) +do(10){ cells.apply(chars.get).concat().println(); cells=life1D(cells); } diff --git a/Task/One-dimensional-cellular-automata/Zkl/one-dimensional-cellular-automata-3.zkl b/Task/One-dimensional-cellular-automata/Zkl/one-dimensional-cellular-automata-3.zkl new file mode 100644 index 0000000000..3210523d55 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Zkl/one-dimensional-cellular-automata-3.zkl @@ -0,0 +1,7 @@ +fcn life1D(line){ + right:=line[1,*] + "_"; // shift left, "_" fill + left :="_" + line[0,-1]; // shift right + Utils.Helpers.zipWith( + fcn(a,b,c){ (String(a,b,c) - "_") == "##" and "#" or "_" }, + left,line,right).concat(); +} diff --git a/Task/One-dimensional-cellular-automata/Zkl/one-dimensional-cellular-automata-4.zkl b/Task/One-dimensional-cellular-automata/Zkl/one-dimensional-cellular-automata-4.zkl new file mode 100644 index 0000000000..3e78fbbbc6 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Zkl/one-dimensional-cellular-automata-4.zkl @@ -0,0 +1,2 @@ +cells:="_###_##_#_#_#_#__#__"; +do(10){ cells.println(); cells=life1D(cells); } diff --git a/Task/One-of-n-lines-in-a-file/Zkl/one-of-n-lines-in-a-file.zkl b/Task/One-of-n-lines-in-a-file/Zkl/one-of-n-lines-in-a-file.zkl new file mode 100644 index 0000000000..77263f84bc --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Zkl/one-of-n-lines-in-a-file.zkl @@ -0,0 +1,20 @@ +fcn one_of_n(lines){ # lines is any iterable +#if 0 // iterative + choice:=Void; + foreach i,line in ([0..].zip(lines)){ + if((0).random(i+1)==0) choice=line; + } + return(choice); +#else // functional + [0..].zip(lines).pump(Ref(Void).set,fcn([(n,line)]) + { if((0).random(n+1)==0) line else Void.Skip }).value +#endif +} + +fcn one_of_n_test(n=10, trials=0d1_000_000){ + bins:=n.pump(List(),0); // List(0,0,0...) + if(n){ foreach i in (trials){ bins[one_of_n((n).walker())]+=1 } } + return(bins); +} + +println(one_of_n_test()); diff --git a/Task/OpenGL/EC/opengl.ec b/Task/OpenGL/EC/opengl.ec new file mode 100644 index 0000000000..e68b333f57 --- /dev/null +++ b/Task/OpenGL/EC/opengl.ec @@ -0,0 +1,35 @@ +#include +import "ecere" + +class GLTriangle : Window +{ + text = "Triangle"; + displayDriver = "OpenGL"; + background = activeBorder; + nativeDecorations = true; + borderStyle = sizable; + hasMaximize = true, hasMinimize = true, hasClose = true; + size = { 640, 480 }; + + void OnRedraw(Surface surface) + { + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(-30, 30, -30, 30, -30, 30); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(-15, -15, 0); + glShadeModel(GL_SMOOTH); + + glBegin(GL_TRIANGLES); + glColor3f(1, 0, 0); + glVertex2f(0, 0); + glColor3f(0, 1, 0); + glVertex2f(30, 0); + glColor3f(0, 0, 1); + glVertex2f(0, 30); + glEnd(); + } +} + +GLTriangle window {}; diff --git a/Task/OpenGL/Kotlin/opengl.kotlin b/Task/OpenGL/Kotlin/opengl.kotlin new file mode 100644 index 0000000000..1e5829427b --- /dev/null +++ b/Task/OpenGL/Kotlin/opengl.kotlin @@ -0,0 +1,48 @@ +// Kotlin Native version 0.3 + +import kotlinx.cinterop.* +import opengl.* + +fun paint() { + glClearColor(0.3f, 0.3f, 0.3f, 0.0f) + glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT) + + glShadeModel(GL_SMOOTH) + + glLoadIdentity() + glTranslatef(-15.0f, -15.0f, 0.0f) + + glBegin(GL_TRIANGLES) + glColor3f(1.0f, 0.0f, 0.0f) + glVertex2f(0.0f, 0.0f) + glColor3f(0.0f, 1.0f, 0.0f) + glVertex2f(30.0f, 0.0f) + glColor3f(0.0f, 0.0f, 1.0f) + glVertex2f(0.0f, 30.0f) + glEnd() + + glFlush() +} + +fun reshape(width: Int, height: Int) { + glViewport(0, 0, width, height) + glMatrixMode(GL_PROJECTION) + glLoadIdentity() + glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0) + glMatrixMode(GL_MODELVIEW) +} + +fun main(args: Array) { + memScoped { + val argc = alloc().apply { value = 0 } + glutInit(argc.ptr, null) + } + + glutInitWindowSize(640, 480) + glutCreateWindow("Triangle") + + glutDisplayFunc(staticCFunction(::paint)) + glutReshapeFunc(staticCFunction(::reshape)) + + glutMainLoop() +} diff --git a/Task/OpenGL/Nim/opengl.nim b/Task/OpenGL/Nim/opengl.nim index 61c06a201e..50a8eb7096 100644 --- a/Task/OpenGL/Nim/opengl.nim +++ b/Task/OpenGL/Nim/opengl.nim @@ -20,7 +20,7 @@ proc paint() {.cdecl.} = glFlush() -proc reshape(width, height) {.cdecl.} = +proc reshape(width, height: cint) {.cdecl.} = glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() diff --git a/Task/Operator-precedence/REXX/operator-precedence.rexx b/Task/Operator-precedence/REXX/operator-precedence.rexx deleted file mode 100644 index f592e4c5cc..0000000000 --- a/Task/Operator-precedence/REXX/operator-precedence.rexx +++ /dev/null @@ -1,90 +0,0 @@ -/* - ╔══════════════════════════════════════════════════════════════════════╗ - ║ ║ - ║ The following is a table that lists the precedence and associativity ║ - ║ of all the operators in the (classic) REXX language. ║ - ║ ║ - ║ 1 is the highest precedence. ║ - ║ ║ - ╠══════════╤════════╤══════════════════════════════════════════════════╣ - ║ │ │ ║ - ║precedence│operator│ description ║ - ║ │ │ ║ - ╟──────────┼────────┼──────────────────────────────────────────────────╢ - ║ 1 │ - │ unary minus ║ - ║ │ + │ unary plus ║ - ║ │ \ │ logical not ║ - ║ │ ├──(the following aren't supported by all REXXes)──╢ - ║ │ ¬ │ logical not ║ - ║ │ ~ │ logical not ║ - ║ │ ^ │ logical not ║ - ╟──────────┼────────┼──────────────────────────────────────────────────╢ - ║ 2 │ ** │ exponentiation (integer power) ║ - ╟──────────┼────────┼──────────────────────────────────────────────────╢ - ║ 3 │ * │ multiplication ║ - ║ │ / │ division ║ - ║ │ % │ integer division ║ - ║ │ // │ modulus (remainder division, sign of dividend)║ - ║ │ / / │ modulus (any 2 or 3 character operators may ║ - ║ │ │ have whitespace between characters.) ║ - ╟──────────┼────────┼──────────────────────────────────────────────────╢ - ║ 4 │ + │ addition ║ - ║ │ - │ subtraction ║ - ╟──────────┼────────┼──────────────────────────────────────────────────╢ - ║ 5 │ || │ concatenation ║ - ╟──────────┼────────┼──────────────────────────────────────────────────╢ - ║ 6 │ & │ logical AND ║ - ║ │ | │ logical OR (inclusive OR) ║ - ║ │ && │ logical XOR (exclusive OR) ║ - ╟──────────┼────────┼──────────────────────────────────────────────────╢ - ║ 7 │[blank] │ concatenation ║ - ║ │abuttal │ concatenation ║ - ╟──────────┼────────┼──────────────────────────────────────────────────╢ - ║ 8 │ = │ equal to ║ - ║ │ == │ exactly equal to (also, strictly equal to) ║ - ║ │ \= │ not equal to ║ - ║ │ <> │ not equal to (also, less than or greater than) ║ - ║ │ >< │ not equal to (also, greater than or less than) ║ - ║ │ > │ greater than ║ - ║ │ >= │ greater than or equal to ║ - ║ │ < │ less than ║ - ║ │ <= │ less than or equal to ║ - ║ │ >> │ exactly greater than ║ - ║ │ << │ exactly less than ║ - ║ │ <<= │ exactly less than or equal to ║ - ║ │ >>= │ exactly greater than or equal to ║ - ║ │ ├──(the following aren't supported by all REXXes)──╢ - ║ │ /= │ not equal to ║ - ║ │ ¬= │ not equal to ║ - ║ │ ~= │ not equal to ║ - ║ │ ^= │ not equal to ║ - ║ │ /== │ not exactly equal to ║ - ║ │ \== │ not exactly equal to ║ - ║ │ ¬== │ not exactly equal to ║ - ║ │ ~== │ not exactly equal to ║ - ║ │ ^== │ not exactly equal to ║ - ║ │ /< │ not less than ║ - ║ │ ~< │ not less than ║ - ║ │ ¬< │ not less than ║ - ║ │ ^< │ not less than ║ - ║ │ /> │ not greater than ║ - ║ │ ¬> │ not greater than ║ - ║ │ ~> │ not greater than ║ - ║ │ ^> │ not greater than ║ - ║ │ /<= │ not less than or equal to ║ - ║ │ ¬<= │ not less than or equal to ║ - ║ │ ~<= │ not less than or equal to ║ - ║ │ ^<= │ not less than or equal to ║ - ║ │ />= │ not greater than or equal to ║ - ║ │ ¬>= │ not greater than or equal to ║ - ║ │ ~>= │ not greater than or equal to ║ - ║ │ ^>= │ not greater than or equal to ║ - ║ │ \>> │ not exactly greater than ║ - ║ │ ¬>> │ not exactly greater than ║ - ║ │ ~>> │ not exactly greater than ║ - ║ │ ^>> │ not exactly greater than ║ - ║ │ \<< │ not exactly less than ║ - ║ │ ¬<< │ not exactly less than ║ - ║ │ ~<< │ not exactly less than ║ - ║ │ ^<< │ not exactly less than ║ - ╚══════════╧════════╧══════════════════════════════════════════════════╝ */ diff --git a/Task/Optional-parameters/Go/optional-parameters-1.go b/Task/Optional-parameters/Go/optional-parameters-1.go index 7fbf9dc68f..3c6f8f1c6b 100644 --- a/Task/Optional-parameters/Go/optional-parameters-1.go +++ b/Task/Optional-parameters/Go/optional-parameters-1.go @@ -1,5 +1,20 @@ +type cell string + type spec struct { - ordering func(cell, cell) bool + less func(cell, cell) bool column int reverse bool } + +func newSpec() (s spec) { + // initialize any defaults + return +} + +// sort with all defaults +t.sort(newSpec()) + +// reverse sort +s := newSpec +s.reverse = true +t.sort(s) diff --git a/Task/Optional-parameters/Go/optional-parameters-2.go b/Task/Optional-parameters/Go/optional-parameters-2.go index 903d12efe0..7fbf9dc68f 100644 --- a/Task/Optional-parameters/Go/optional-parameters-2.go +++ b/Task/Optional-parameters/Go/optional-parameters-2.go @@ -1 +1,5 @@ -spec{reverse: true} +type spec struct { + ordering func(cell, cell) bool + column int + reverse bool +} diff --git a/Task/Optional-parameters/Go/optional-parameters-3.go b/Task/Optional-parameters/Go/optional-parameters-3.go index 504aee76d4..903d12efe0 100644 --- a/Task/Optional-parameters/Go/optional-parameters-3.go +++ b/Task/Optional-parameters/Go/optional-parameters-3.go @@ -1,93 +1 @@ -package main - -import ( - "fmt" - "sort" -) - -type cell string -type row []cell -type table struct { - rows []row - column int - less func(cell, cell) bool -} - -func (c cell) String() string { - return fmt.Sprintf("%q", string(c)) -} - -func (t table) printRows(heading string) { - fmt.Println("--", heading) - for _, row := range t.rows { - fmt.Println(row) - } - fmt.Println() -} - -// sort.Interface -func (t table) Len() int { return len(t.rows) } -func (t table) Swap(i, j int) { t.rows[i], t.rows[j] = t.rows[j], t.rows[i] } -func (t table) Less(i, j int) bool { - return t.less(t.rows[i][t.column], t.rows[j][t.column]) -} - -// struct implements named parameter-like capability -type spec struct { - ordering func(cell, cell) bool - column int - reverse bool -} - - -func (t *table) sort(s spec) { - // set up column and comparison function for sort - t.column = s.column - switch { - case s.ordering != nil: - t.less = s.ordering - case s.reverse: - t.less = func(a, b cell) bool { return a > b } - default: - t.less = func(a, b cell) bool { return a < b } - } - - // sort - sort.Sort(t) - - // reverse if necessary - if s.ordering == nil || !s.reverse { - return - } - last := len(t.rows) - 1 - for i := last / 2; i >= 0; i-- { - t.rows[i], t.rows[last-i] = t.rows[last-i], t.rows[i] - } -} - -func main() { - t := table{rows: []row{ - {"pail", "food"}, - {"pillbox", "nurse maids"}, - {"suitcase", "airedales"}, - {"bathtub", "chocolate"}, - {"schooner", "ice cream sodas"}, - }} - - t.printRows("song") - - // no "parameters" - t.sort(spec{}) - t.printRows("sorted on first column") - - // "named parameter" reverse. - t.sort(spec{reverse: true}) - t.printRows("reverse sorted on first column") - - // "named parameters" column and ordering - t.sort(spec{ - column: 1, - ordering: func(a, b cell) bool { return len(a) > len(b) }, - }) - t.printRows("sorted by descending string length on second column") -} +spec{reverse: true} diff --git a/Task/Optional-parameters/Go/optional-parameters-4.go b/Task/Optional-parameters/Go/optional-parameters-4.go new file mode 100644 index 0000000000..504aee76d4 --- /dev/null +++ b/Task/Optional-parameters/Go/optional-parameters-4.go @@ -0,0 +1,93 @@ +package main + +import ( + "fmt" + "sort" +) + +type cell string +type row []cell +type table struct { + rows []row + column int + less func(cell, cell) bool +} + +func (c cell) String() string { + return fmt.Sprintf("%q", string(c)) +} + +func (t table) printRows(heading string) { + fmt.Println("--", heading) + for _, row := range t.rows { + fmt.Println(row) + } + fmt.Println() +} + +// sort.Interface +func (t table) Len() int { return len(t.rows) } +func (t table) Swap(i, j int) { t.rows[i], t.rows[j] = t.rows[j], t.rows[i] } +func (t table) Less(i, j int) bool { + return t.less(t.rows[i][t.column], t.rows[j][t.column]) +} + +// struct implements named parameter-like capability +type spec struct { + ordering func(cell, cell) bool + column int + reverse bool +} + + +func (t *table) sort(s spec) { + // set up column and comparison function for sort + t.column = s.column + switch { + case s.ordering != nil: + t.less = s.ordering + case s.reverse: + t.less = func(a, b cell) bool { return a > b } + default: + t.less = func(a, b cell) bool { return a < b } + } + + // sort + sort.Sort(t) + + // reverse if necessary + if s.ordering == nil || !s.reverse { + return + } + last := len(t.rows) - 1 + for i := last / 2; i >= 0; i-- { + t.rows[i], t.rows[last-i] = t.rows[last-i], t.rows[i] + } +} + +func main() { + t := table{rows: []row{ + {"pail", "food"}, + {"pillbox", "nurse maids"}, + {"suitcase", "airedales"}, + {"bathtub", "chocolate"}, + {"schooner", "ice cream sodas"}, + }} + + t.printRows("song") + + // no "parameters" + t.sort(spec{}) + t.printRows("sorted on first column") + + // "named parameter" reverse. + t.sort(spec{reverse: true}) + t.printRows("reverse sorted on first column") + + // "named parameters" column and ordering + t.sort(spec{ + column: 1, + ordering: func(a, b cell) bool { return len(a) > len(b) }, + }) + t.printRows("sorted by descending string length on second column") +} diff --git a/Task/Optional-parameters/Go/optional-parameters-5.go b/Task/Optional-parameters/Go/optional-parameters-5.go new file mode 100644 index 0000000000..4042a2cf56 --- /dev/null +++ b/Task/Optional-parameters/Go/optional-parameters-5.go @@ -0,0 +1,112 @@ +package main + +import ( + "fmt" + "sort" +) + +type cell string +type row []cell +type table struct { + rows []row + column int + less func(cell, cell) bool +} + +func (c cell) String() string { + return fmt.Sprintf("%q", string(c)) +} + +func (t table) printRows(heading string) { + fmt.Println("--", heading) + for _, row := range t.rows { + fmt.Println(row) + } + fmt.Println() +} + +// sort.Interface +func (t table) Len() int { return len(t.rows) } +func (t table) Swap(i, j int) { t.rows[i], t.rows[j] = t.rows[j], t.rows[i] } +func (t table) Less(i, j int) bool { + return t.less(t.rows[i][t.column], t.rows[j][t.column]) +} + +// struct implements named parameter-like capability +type spec struct { + ordering func(cell, cell) bool + column int + reverse bool +} + +// A defined option type is not really needed by the technique, but has +// a nice advantage for documentation. If this type is exported, then +// the the Go documentation tool go doc will organize all of the option +// functions together under the type. (Go doc will see them as constructors +// for the type.) +type Option func(*spec) + +func ordering(o func(cell, cell) bool) Option { + return func(s *spec) { s.ordering = o } +} + +func column(c int) Option { + return func(s *spec) { s.column = c } +} + +func reverse() Option { + return func(s *spec) { s.reverse = true } +} + +func (t *table) sort(options ...Option) { + var s spec + for _, o := range options { + o(&s) + } + // set up column and comparison function for sort + t.column = s.column + switch { + case s.ordering != nil: + t.less = s.ordering + case s.reverse: + t.less = func(a, b cell) bool { return a > b } + default: + t.less = func(a, b cell) bool { return a < b } + } + + // sort + sort.Sort(t) + + // reverse if necessary + if s.ordering == nil || !s.reverse { + return + } + last := len(t.rows) - 1 + for i := last / 2; i >= 0; i-- { + t.rows[i], t.rows[last-i] = t.rows[last-i], t.rows[i] + } +} + +func main() { + t := table{rows: []row{ + {"pail", "food"}, + {"pillbox", "nurse maids"}, + {"suitcase", "airedales"}, + {"bathtub", "chocolate"}, + {"schooner", "ice cream sodas"}, + }} + + t.printRows("song") + // no parameters + t.sort() + t.printRows("sorted on first column") + + // "named parameter" reverse. + t.sort(reverse()) + t.printRows("reverse sorted on first column") + + // "named parameters" column and ordering + byLen := func(a, b cell) bool { return len(a) > len(b) } + t.sort(column(1), ordering(byLen)) + t.printRows("sorted by descending string length on second column") +} diff --git a/Task/Optional-parameters/jq/optional-parameters-1.jq b/Task/Optional-parameters/Jq/optional-parameters-1.jq similarity index 100% rename from Task/Optional-parameters/jq/optional-parameters-1.jq rename to Task/Optional-parameters/Jq/optional-parameters-1.jq diff --git a/Task/Optional-parameters/jq/optional-parameters-2.jq b/Task/Optional-parameters/Jq/optional-parameters-2.jq similarity index 100% rename from Task/Optional-parameters/jq/optional-parameters-2.jq rename to Task/Optional-parameters/Jq/optional-parameters-2.jq diff --git a/Task/Optional-parameters/jq/optional-parameters-3.jq b/Task/Optional-parameters/Jq/optional-parameters-3.jq similarity index 100% rename from Task/Optional-parameters/jq/optional-parameters-3.jq rename to Task/Optional-parameters/Jq/optional-parameters-3.jq diff --git a/Task/Optional-parameters/jq/optional-parameters-4.jq b/Task/Optional-parameters/Jq/optional-parameters-4.jq similarity index 100% rename from Task/Optional-parameters/jq/optional-parameters-4.jq rename to Task/Optional-parameters/Jq/optional-parameters-4.jq diff --git a/Task/Optional-parameters/Zkl/optional-parameters.zkl b/Task/Optional-parameters/Zkl/optional-parameters.zkl new file mode 100644 index 0000000000..96ea0db4d4 --- /dev/null +++ b/Task/Optional-parameters/Zkl/optional-parameters.zkl @@ -0,0 +1,8 @@ +const lex="L"; +fcn mystrySort(table,ordering=lex,column=0,reverse=False,other){ + vm.arglist.println(); +} +mystrySort.prototype.println(); +mystrySort("table"); +mystrySort("table",lex,1); +mystrySort("table",lex,1,True,D("row",35,"type","foobar")); diff --git a/Task/Order-disjoint-list-items/Aime/order-disjoint-list-items.aime b/Task/Order-disjoint-list-items/Aime/order-disjoint-list-items.aime new file mode 100644 index 0000000000..708f76a50b --- /dev/null +++ b/Task/Order-disjoint-list-items/Aime/order-disjoint-list-items.aime @@ -0,0 +1,46 @@ +void +order(integer m, ...) +{ + integer i, j; + record r; + text s; + + ocall(o_, 0, 1, m, " "); + + o_("| "); + + i = (j = m) + 1; + while (i < count()) { + r[s = $i] += 1; + o_(s, " "); + i += 1; + } + + o_("->"); + + i = 0; + do { + i += 1; + if ((r[s = $i] += -1) < 0) { + o_(" ", s); + } else { + o_(" ", $(j += 1)); + } + } while (i < m); + + o_newline(); +} + +integer +main(void) +{ + order(6, "the", "cat", "sat", "on", "the", "mat", "mat", "cat"); + order(6, "the", "cat", "sat", "on", "the", "mat", "cat", "mat"); + order(9, "A", "B", "C", "A", "B", "C", "A", "B", "C", "C", "A", "C", "A"); + order(9, "A", "B", "C", "A", "B", "D", "A", "B", "E", "E", "A", "D", "A"); + order(2, "A", "B", "B"); + order(2, "A", "B", "B", "A"); + order(4, "A", "B", "B", "A", "B", "A"); + + return 0; +} diff --git a/Task/Order-disjoint-list-items/AppleScript/order-disjoint-list-items.applescript b/Task/Order-disjoint-list-items/AppleScript/order-disjoint-list-items.applescript index 7b64ff17e6..34e66779e7 100644 --- a/Task/Order-disjoint-list-items/AppleScript/order-disjoint-list-items.applescript +++ b/Task/Order-disjoint-list-items/AppleScript/order-disjoint-list-items.applescript @@ -1,3 +1,5 @@ +-- DISJOINT ORDER ------------------------------------------------------------ + -- disjointOrder :: String -> String -> String on disjointOrder(m, n) set {ms, ns} to map(my |words|, {m, n}) @@ -8,15 +10,17 @@ end disjointOrder -- segments :: [String] -> [String] -> [String] on segments(ms, ns) script segmentation - on lambda(a, x) + on |λ|(a, x) set wds to |words| of a if wds contains x then - {parts:(parts of a) & [current of a], current:[], |words|:deleteFirst(x, wds)} + {parts:(parts of a) & ¬ + [current of a], current:[], |words|:deleteFirst(x, wds)} ¬ + else {parts:(parts of a), current:(current of a) & x, |words|:wds} end if - end lambda + end |λ| end script tell foldl(segmentation, {|words|:ns, parts:[], current:[]}, ms) @@ -25,14 +29,14 @@ on segments(ms, ns) end segments --- TEST -------------------------------------------------------------------------------------- +-- TEST ---------------------------------------------------------------------- on run script order - on lambda(rec) + on |λ|(rec) tell rec [its m, its n, my disjointOrder(its m, its n)] end tell - end lambda + end |λ| end script arrowTable(map(order, [¬ @@ -43,18 +47,18 @@ on run {m:"A B", n:"B"}, {m:"A B", n:"B A"}, ¬ {m:"A B B A", n:"B A"}])) --- the cat sat on the mat -> mat cat -> the mat sat on the cat --- the cat sat on the mat -> cat mat -> the cat sat on the mat --- A B C A B C A B C -> C A C A -> C B A C B A A B C --- A B C A B D A B E -> E A D A -> E B C A B D A B A --- A B -> B -> A B --- A B -> B A -> B A --- A B B A -> B A -> B A B A + -- the cat sat on the mat -> mat cat -> the mat sat on the cat + -- the cat sat on the mat -> cat mat -> the cat sat on the mat + -- A B C A B C A B C -> C A C A -> C B A C B A A B C + -- A B C A B D A B E -> E A D A -> E B C A B D A B A + -- A B -> B -> A B + -- A B -> B A -> B A + -- A B B A -> B A -> B A B A end run --- GENERIC FUNCTIONS ---------------------------------------------------------------------- +-- GENERIC FUNCTIONS --------------------------------------------------------- -- Formatting test results @@ -63,52 +67,99 @@ on arrowTable(rows) script leftAligned script width - on lambda(a, b) + on |λ|(a, b) (length of a) - (length of b) - end lambda + end |λ| end script - on lambda(col) + on |λ|(col) set widest to length of maximumBy(width, col) script padding - on lambda(s) + on |λ|(s) justifyLeft(widest, space, s) - end lambda + end |λ| end script map(padding, col) - end lambda + end |λ| end script script arrows - on lambda(row) + on |λ|(row) intercalate(" -> ", row) - end lambda + end |λ| end script intercalate(linefeed, ¬ map(arrows, ¬ transpose(map(leftAligned, transpose(rows))))) - end arrowTable --- transpose :: [[a]] -> [[a]] -on transpose(xss) - script column - on lambda(_, iCol) - script row - on lambda(xs) - item iCol of xs - end lambda - end script - - map(row, xss) - end lambda +-- concatMap :: (a -> [b]) -> [a] -> [b] +on concatMap(f, xs) + script append + on |λ|(a, b) + a & b + end |λ| end script - map(column, item 1 of xss) -end transpose + foldl(append, {}, map(f, xs)) +end concatMap + +-- deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a] +on deleteBy(fnEq, x, xs) + if length of xs > 0 then + set {h, t} to uncons(xs) + if |λ|(x, h) of mReturn(fnEq) then + t + else + {h} & deleteBy(fnEq, x, t) + end if + else + {} + end if +end deleteBy + +-- deleteFirst :: a -> [a] -> [a] +on deleteFirst(x, xs) + script Eq + on |λ|(a, b) + a = b + end |λ| + end script + + deleteBy(Eq, x, xs) +end deleteFirst + +-- flatten :: Tree a -> [a] +on flatten(t) + if class of t is list then + concatMap(my flatten, t) + else + t + end if +end flatten + +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl + +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate -- justifyLeft :: Int -> Char -> Text -> Text on justifyLeft(n, cFiller, strText) @@ -119,22 +170,61 @@ on justifyLeft(n, cFiller, strText) end if end justifyLeft +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + -- maximumBy :: (a -> a -> Ordering) -> [a] -> a on maximumBy(f, xs) set cmp to mReturn(f) script max - on lambda(a, b) - if a is missing value or cmp's lambda(a, b) < 0 then + on |λ|(a, b) + if a is missing value or cmp's |λ|(a, b) < 0 then b else a end if - end lambda + end |λ| end script foldl(max, missing value, xs) end maximumBy +-- minimum :: [a] -> a +on minimum(xs) + script min + on |λ|(a, x) + if x < a or a is missing value then + x + else + a + end if + end |λ| + end script + + foldl(min, missing value, xs) +end minimum + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + -- Egyptian multiplication - progressively doubling a list, appending -- stages of doubling to an accumulator where needed for binary -- assembly of a target length @@ -153,114 +243,22 @@ on replicate(n, a) return out & dbl end replicate --- List functions +-- transpose :: [[a]] -> [[a]] +on transpose(xss) + script column + on |λ|(_, iCol) + script row + on |λ|(xs) + item iCol of xs + end |λ| + end script --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map - --- foldl :: (a -> b -> a) -> a -> [b] -> a -on foldl(f, startValue, xs) - tell mReturn(f) - set v to startValue - set lng to length of xs - repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) - end repeat - return v - end tell -end foldl - --- zip :: [a] -> [b] -> [(a, b)] -on zip(xs, ys) - script pair - on lambda(x, i) - [x, item i of ys] - end lambda + map(row, xss) + end |λ| end script - map(pair, items 1 thru minimum([length of xs, length of ys]) of xs) -end zip - --- flatten :: Tree a -> [a] -on flatten(t) - if class of t is list then - concatMap(my flatten, t) - else - t - end if -end flatten - --- concatMap :: (a -> [b]) -> [a] -> [b] -on concatMap(f, xs) - script append - on lambda(a, b) - a & b - end lambda - end script - - foldl(append, {}, map(f, xs)) -end concatMap - --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn - --- deleteFirst :: a -> [a] -> [a] -on deleteFirst(x, xs) - script Eq - on lambda(a, b) - a = b - end lambda - end script - - deleteBy(Eq, x, xs) -end deleteFirst - --- minimum :: [a] -> a -on minimum(xs) - script min - on lambda(a, x) - if x < a or a is missing value then - x - else - a - end if - end lambda - end script - - foldl(min, missing value, xs) -end minimum - --- deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a] -on deleteBy(fnEq, x, xs) - if length of xs > 0 then - set {h, t} to uncons(xs) - if lambda(x, h) of mReturn(fnEq) then - t - else - {h} & deleteBy(fnEq, x, t) - end if - else - {} - end if -end deleteBy + map(column, item 1 of xss) +end transpose -- uncons :: [a] -> Maybe (a, [a]) on uncons(xs) @@ -276,15 +274,19 @@ on unwords(xs) intercalate(space, xs) end unwords --- intercalate :: Text -> [Text] -> Text -on intercalate(strText, lstText) - set {dlm, my text item delimiters} to {my text item delimiters, strText} - set strJoined to lstText as text - set my text item delimiters to dlm - return strJoined -end intercalate -- words :: String -> [String] on |words|(s) words of s end |words| + +-- zip :: [a] -> [b] -> [(a, b)] +on zip(xs, ys) + script pair + on |λ|(x, i) + [x, item i of ys] + end |λ| + end script + + map(pair, items 1 thru minimum([length of xs, length of ys]) of xs) +end zip diff --git a/Task/Order-disjoint-list-items/Haskell/order-disjoint-list-items-1.hs b/Task/Order-disjoint-list-items/Haskell/order-disjoint-list-items-1.hs index 540670cd69..05ccc4e981 100644 --- a/Task/Order-disjoint-list-items/Haskell/order-disjoint-list-items-1.hs +++ b/Task/Order-disjoint-list-items/Haskell/order-disjoint-list-items-1.hs @@ -1,16 +1,33 @@ -import Data.List +import Data.List (mapAccumL, sort) -order::Ord a => [[a]] -> [a] -order [ms,ns] = snd.mapAccumL yu ls $ ks +order + :: Ord a + => [[a]] -> [a] +order [ms, ns] = snd . mapAccumL yu ls $ ks where - ks = zip ms [(0::Int)..] - ls = zip ns.sort.snd.foldl go (sort ns,[]).sort $ ks - yu ((u,v):us) (_,y) | v == y = (us,u) - yu ys (x,_) = (ys,x) - go ((u:us),ys) (x,y) | u == x = (us,y:ys) - go ts _ = ts + ks = zip ms [(0 :: Int) ..] + ls = zip ns . sort . snd . foldl go (sort ns, []) . sort $ ks + yu ((u, v):us) (_, y) + | v == y = (us, u) + yu ys (x, _) = (ys, x) + go (u:us, ys) (x, y) + | u == x = (us, y : ys) + go ts _ = ts -task ls@[ms,ns] = do - putStrLn $ "M: " ++ ms ++ " | N: " ++ ns ++ " |> " ++ (unwords.order.map words $ ls) +task :: [String] -> IO () +task ls@[ms, ns] = + putStrLn $ + "M: " ++ ms ++ " | N: " ++ ns ++ " |> " ++ (unwords . order . map words $ ls) -main = mapM_ task [["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"]] +main :: IO () +main = + mapM_ + task + [ ["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"] + ] diff --git a/Task/Order-disjoint-list-items/Haskell/order-disjoint-list-items-2.hs b/Task/Order-disjoint-list-items/Haskell/order-disjoint-list-items-2.hs index 91414608c1..c121821a0b 100644 --- a/Task/Order-disjoint-list-items/Haskell/order-disjoint-list-items-2.hs +++ b/Task/Order-disjoint-list-items/Haskell/order-disjoint-list-items-2.hs @@ -1,44 +1,55 @@ +import Control.Arrow ((***)) import Prelude hiding (unlines, unwords, words, length) import Data.List (delete, transpose) -import Data.Text hiding (concat, zipWith, foldl, transpose, maximum) +import Data.Text + hiding (concat, zipWith, foldl, transpose, maximum) - -disjointOrder :: Eq a => [a] -> [a] -> [a] +disjointOrder + :: Eq a + => [a] -> [a] -> [a] disjointOrder m n = concat $ zipWith (++) ms ns - where - ms = segments m n - ns = ((:[]) <$> n) ++ [[]] -- as list of lists, lengthened by 1 - - segments :: Eq a => [a] -> [a] -> [[a]] - segments m n = _m ++ [_acc] - where - (_m, _, _acc) = foldl split ([], n, []) m - - split :: Eq a => ([[a]],[a],[a]) -> a -> ([[a]],[a],[a]) - split (ms, ns, acc) x - | elem x ns = (ms ++ [acc], delete x ns, []) - | otherwise = (ms, ns, acc ++ [x]) - + where + ms = segments m n + ns = ((: []) <$> n) ++ [[]] -- as list of lists, lengthened by 1 + segments + :: Eq a + => [a] -> [a] -> [[a]] + segments m n = _m ++ [_acc] + where + (_m, _, _acc) = foldl split ([], n, []) m + split + :: Eq a + => ([[a]], [a], [a]) -> a -> ([[a]], [a], [a]) + split (ms, ns, acc) x + | x `elem` ns = (ms ++ [acc], delete x ns, []) + | otherwise = (ms, ns, acc ++ [x]) -- TEST ----------------------------------------------------------- - tests :: [(Text, Text)] -tests = (\(a, b) -> (pack a, pack b)) <$> - [("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")] +tests = + (pack *** pack) <$> + [ ("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") + ] table :: Text -> [[Text]] -> Text -table delim rows = unlines $ (\r -> (intercalate delim r)) - <$> (transpose $ (\col -> - let width = (length $ maximum col) - in (justifyLeft width ' ') <$> col) <$> transpose rows) +table delim rows = + unlines $ + intercalate delim <$> + transpose + ((\col -> + let width = (length $ maximum col) + in justifyLeft width ' ' <$> col) <$> + transpose rows) main :: IO () -main = putStr $ unpack $ table (pack " -> ") $ - (\(m, n) -> [m, n, unwords (disjointOrder (words m) (words n))]) - <$> tests +main = + putStr $ + unpack $ + table (pack " -> ") $ + (\(m, n) -> [m, n, unwords (disjointOrder (words m) (words n))]) <$> tests diff --git a/Task/Order-disjoint-list-items/jq/order-disjoint-list-items-1.jq b/Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-1.jq similarity index 100% rename from Task/Order-disjoint-list-items/jq/order-disjoint-list-items-1.jq rename to Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-1.jq diff --git a/Task/Order-disjoint-list-items/jq/order-disjoint-list-items-2.jq b/Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-2.jq similarity index 100% rename from Task/Order-disjoint-list-items/jq/order-disjoint-list-items-2.jq rename to Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-2.jq diff --git a/Task/Order-disjoint-list-items/jq/order-disjoint-list-items-3.jq b/Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-3.jq similarity index 100% rename from Task/Order-disjoint-list-items/jq/order-disjoint-list-items-3.jq rename to Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-3.jq diff --git a/Task/Order-disjoint-list-items/jq/order-disjoint-list-items-4.jq b/Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-4.jq similarity index 100% rename from Task/Order-disjoint-list-items/jq/order-disjoint-list-items-4.jq rename to Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-4.jq diff --git a/Task/Order-disjoint-list-items/jq/order-disjoint-list-items-5.jq b/Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-5.jq similarity index 100% rename from Task/Order-disjoint-list-items/jq/order-disjoint-list-items-5.jq rename to Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-5.jq diff --git a/Task/Order-disjoint-list-items/jq/order-disjoint-list-items-6.jq b/Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-6.jq similarity index 100% rename from Task/Order-disjoint-list-items/jq/order-disjoint-list-items-6.jq rename to Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-6.jq diff --git a/Task/Order-disjoint-list-items/jq/order-disjoint-list-items-7.jq b/Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-7.jq similarity index 100% rename from Task/Order-disjoint-list-items/jq/order-disjoint-list-items-7.jq rename to Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-7.jq diff --git a/Task/Order-disjoint-list-items/jq/order-disjoint-list-items-8.jq b/Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-8.jq similarity index 100% rename from Task/Order-disjoint-list-items/jq/order-disjoint-list-items-8.jq rename to Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-8.jq diff --git a/Task/Order-disjoint-list-items/jq/order-disjoint-list-items-9.jq b/Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-9.jq similarity index 100% rename from Task/Order-disjoint-list-items/jq/order-disjoint-list-items-9.jq rename to Task/Order-disjoint-list-items/Jq/order-disjoint-list-items-9.jq 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.kotlin new file mode 100644 index 0000000000..d30cf85e1c --- /dev/null +++ b/Task/Order-disjoint-list-items/Kotlin/order-disjoint-list-items.kotlin @@ -0,0 +1,39 @@ +// version 1.0.6 + +const val NULL = "\u0000" + +fun orderDisjointList(m: String, n: String): String { + val nList = n.split(' ') + // first replace the first occurrence of items of 'n' in 'm' with the NULL character + // which we can safely assume won't occur in 'm' naturally + var p = m + for (item in nList) p = p.replaceFirst(item, NULL) + // now successively replace the NULLs with items from nList + val mList = p.split(NULL) + val sb = StringBuilder() + for (i in 0 until nList.size) sb.append(mList[i], nList[i]) + return sb.append(mList.last()).toString() +} + +fun main(args: Array) { + val m = arrayOf( + "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" + ) + val n = arrayOf( + "mat cat", + "cat mat", + "C A C A", + "E A D A", + "B", + "B A", + "B A" + ) + for (i in 0 until m.size) + println("${m[i].padEnd(22)} -> ${n[i].padEnd(7)} -> ${orderDisjointList(m[i], n[i])}") +} diff --git a/Task/Order-disjoint-list-items/REXX/order-disjoint-list-items.rexx b/Task/Order-disjoint-list-items/REXX/order-disjoint-list-items.rexx index a4769d2252..f15e49fee0 100644 --- a/Task/Order-disjoint-list-items/REXX/order-disjoint-list-items.rexx +++ b/Task/Order-disjoint-list-items/REXX/order-disjoint-list-items.rexx @@ -1,4 +1,4 @@ -/*REXX program orders a disjoint list of M items with a list of N items. */ +/*REXX program orders a disjoint list of M items with a list of N items. */ used = '0'x /*indicates that a word has been parsed*/ @. = /*placeholder indicates end─of─array, */ @.1 = " the cat sat on the mat | mat cat " /*a string. */ @@ -17,29 +17,29 @@ used = '0'x /*indicates that a word has bee @.14 = " A B C C B A | A C A C " /*" " */ @.15 = " A B C C B A | C A C A " /*" " */ /* ════════════M═══════════ ════N════ */ - /* [↓] process each input strings. */ - do j=1 while @.j\==''; r.= /*nullify the replacement string [R.] */ + + do j=1 while @.j\=='' /* [↓] process each input string (@.).*/ parse var @.j m '|' n /*parse input string into M and N. */ #=words(m) /*#: number of words in the M list.*/ do i=# for # by -1 /*process list items in reverse order. */ - _=word(m,i); !.i=_; $._=i /*construct the !. and $. arrays.*/ + _=word(m, i); !.i=_; $._=i /*construct the !. and $. arrays.*/ end /*i*/ - - do k=1 for words(n)%2 by 2 /* [↓] process the N array. */ - _=word(n,k); v=word(n,k+1) /*get an order word and the replacement*/ - p1=wordpos(_,m); p2=wordpos(v,m) /*positions of " " " " */ + r.= /*nullify the replacement string [R.] */ + do k=1 by 2 for words(n) % 2 /* [↓] process the N array. */ + _=word(n, k); v=word(n, k+1) /*get an order word and the replacement*/ + p1=wordpos(_, m); p2=wordpos(v, m) /*positions of " " " " */ if p1==0 | p2==0 then iterate /*if either not found, then skip them. */ if $._>>$.v then do; r.p2=!.p1; r.p1=!.p2; end /*switch the words.*/ else do; r.p1=!.p1; r.p2=!.p2; end /*don't switch. */ !.p1=used; !.p2=used /*mark 'em as used.*/ m= - do i=1 for #; m=m !.i; _=word(m,i); !.i=_; $._=i; end /*i*/ + do i=1 for #; m=m !.i; _=word(m, i); !.i=_; $._=i; end /*i*/ end /*k*/ /* [↑] rebuild the !. and $. arrays.*/ mp= /*the MP (aka M') string (so far). */ do q=1 for #; if !.q==used then mp=mp r.q /*use the original.*/ else mp=mp !.q /*use substitute. */ end /*q*/ /* [↑] re─build the (output) string. */ - say @.j '───►' space(mp) /*display new re─ordered text ──► term.*/ + say @.j ' ────► ' space(mp) /*display new re─ordered text ──► term.*/ end /*j*/ /* [↑] end of processing for N words*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Order-disjoint-list-items/Zkl/order-disjoint-list-items-1.zkl b/Task/Order-disjoint-list-items/Zkl/order-disjoint-list-items-1.zkl new file mode 100644 index 0000000000..d7f4853461 --- /dev/null +++ b/Task/Order-disjoint-list-items/Zkl/order-disjoint-list-items-1.zkl @@ -0,0 +1,10 @@ +fcn disOrder(sm,sn){ + M:=sm.split(" "); + N:=sn.split(" "); nc:=Walker.cycle(Utils.Helpers.listUnique(N)); + dn:=Dictionary(); N.pump(Void,'wrap(w){ dn[w] = dn.find(w,0) + 1; }); + M.pump(String,'wrap(w){ + if (Void==(n:=dn.find(w))) return(w); // not replaced + if (n) { dn[w]=n-1; nc.next(); } // swaps left-- + else { nc.next(); w } // exhausted + }, String.fp(" ") )[1,*] // remove leading blank +} diff --git a/Task/Order-disjoint-list-items/Zkl/order-disjoint-list-items-2.zkl b/Task/Order-disjoint-list-items/Zkl/order-disjoint-list-items-2.zkl new file mode 100644 index 0000000000..352ddaa358 --- /dev/null +++ b/Task/Order-disjoint-list-items/Zkl/order-disjoint-list-items-2.zkl @@ -0,0 +1,8 @@ +sets:=T(T("the cat sat on the mat","mat cat"), + T("the cat sat on the mat","cat mat"), + T("A B C A B C A B C","C A C A"), + T("A B C A B D A B E","E A D A"), + T("A B","B"), T("A B","B A"), T("A B B A","B A") ); +foreach m,n in (sets){ + m.println(" / ",n," --> ",disOrder(m,n)); +} diff --git a/Task/Order-two-numerical-lists/Clojure/order-two-numerical-lists.clj b/Task/Order-two-numerical-lists/Clojure/order-two-numerical-lists.clj new file mode 100644 index 0000000000..bc3c64e040 --- /dev/null +++ b/Task/Order-two-numerical-lists/Clojure/order-two-numerical-lists.clj @@ -0,0 +1,2 @@ +(defn lex? [a b] + (compare a b)) diff --git a/Task/Order-two-numerical-lists/jq/order-two-numerical-lists.jq b/Task/Order-two-numerical-lists/Jq/order-two-numerical-lists.jq similarity index 100% rename from Task/Order-two-numerical-lists/jq/order-two-numerical-lists.jq rename to Task/Order-two-numerical-lists/Jq/order-two-numerical-lists.jq 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.kotlin new file mode 100644 index 0000000000..581d019a2c --- /dev/null +++ b/Task/Order-two-numerical-lists/Kotlin/order-two-numerical-lists.kotlin @@ -0,0 +1,28 @@ +// version 1.0.6 + +operator fun List.compareTo(other: List): Int + where T: Comparable, T: Number { + for (i in 0 until this.size) { + if (other.size == i) return 1 + when { + this[i] < other[i] -> return -1 + this[i] > other[i] -> return 1 + } + } + return if (this.size == other.size) 0 else -1 +} + +fun main(args: Array) { + val lists = listOf( + listOf(1, 2, 3, 4, 5), + listOf(1, 2, 1, 5, 2, 2), + listOf(1, 2, 1, 5, 2), + listOf(1, 2, 1, 5, 2), + listOf(1, 2, 1, 3, 2), + listOf(1, 2, 0, 4, 4, 0, 0, 0), + listOf(1, 2, 0, 4, 4, 1, 0, 0) + ) + for (i in 0 until lists.size) println("list${i + 1} : ${lists[i]}") + println() + for (i in 0 until lists.size - 1) println("list${i + 1} > list${i + 2} = ${lists[i] > lists[i + 1]}") +} diff --git a/Task/Order-two-numerical-lists/Phix/order-two-numerical-lists.phix b/Task/Order-two-numerical-lists/Phix/order-two-numerical-lists.phix new file mode 100644 index 0000000000..cf2d4369cf --- /dev/null +++ b/Task/Order-two-numerical-lists/Phix/order-two-numerical-lists.phix @@ -0,0 +1,5 @@ +?{1,2,3}<{1,2,3,4} -- 1 +?{1,2,3,4}<{1,2,3} -- 0 +?{1,2,4}<{1,2,3} -- 0 +?{1,2,3}<{1,2,3} -- 0 +?{1,2,3}<{1,2,4} -- 1 diff --git a/Task/Order-two-numerical-lists/Zkl/order-two-numerical-lists.zkl b/Task/Order-two-numerical-lists/Zkl/order-two-numerical-lists.zkl new file mode 100644 index 0000000000..4ca19758ee --- /dev/null +++ b/Task/Order-two-numerical-lists/Zkl/order-two-numerical-lists.zkl @@ -0,0 +1,5 @@ +fcn listLT(a,b){ + a.walker().zip(b).filter1(fcn([(a,b)]){ a.isMonotonic(): Boolean { + for (i in 1 until this.size) { + if (this[i] < this[i - 1]) return false + } + return true +} + +fun main(args: Array) { + val sizes = args.map { it.toInt() } + println("Partitions for $sizes:\n[") + val totalSize = sizes.sum() + val perm = IntArray(totalSize) { it + 1 } + + do { + val partition = mutableListOf>() + var sum = 0 + var isValid = true + for (size in sizes) { + if (size == 0) { + partition.add(emptyList()) + } + else if (size == 1) { + partition.add(listOf(perm[sum])) + } + else { + val sl = perm.slice(sum until sum + size) + if (!sl.isMonotonic()) { + isValid = false + break + } + partition.add(sl) + } + sum += size + } + if (isValid) println(" $partition") + } + while (nextPerm(perm)) + println("]") +} diff --git a/Task/Ordered-Partitions/Phix/ordered-partitions.phix b/Task/Ordered-Partitions/Phix/ordered-partitions.phix new file mode 100644 index 0000000000..27335758e4 --- /dev/null +++ b/Task/Ordered-Partitions/Phix/ordered-partitions.phix @@ -0,0 +1,29 @@ +function partitions(sequence s) +integer N = sum(s) +sequence set = tagset(N), perm, + results = {}, result, resi + for i=1 to factorial(N) do + perm = permute(i,set) + integer n = 1 + result = {} + for j=1 to length(s) do + resi = {} + for k=1 to s[j] do + resi = append(resi,perm[n]) + n += 1 + end for + result = append(result,sort(resi)) + end for + if not find(result,results) then + results = append(results,result) + end if + end for + return sort(results) +end function + +ppOpt({pp_Nest,1}) +pp(partitions({2,0,2})) +pp(partitions({1,1,1})) +pp(partitions({1,2,0,1})) +pp(partitions({})) +pp(partitions({0,0,0})) diff --git a/Task/Ordered-Partitions/REXX/ordered-partitions.rexx b/Task/Ordered-Partitions/REXX/ordered-partitions.rexx index a5b6a47552..b04b261394 100644 --- a/Task/Ordered-Partitions/REXX/ordered-partitions.rexx +++ b/Task/Ordered-Partitions/REXX/ordered-partitions.rexx @@ -1,48 +1,46 @@ -/*REXX program displays ordered partitions: orderedPartitions(i,j,k,···)*/ -call orderedPartitions 2,0,2 /*Note: 2,,2 will also work*/ -call orderedPartitions 1,1,1 -call orderedPartitions 1,2,0,1 /*Note: 1,2,1 will also work*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ORDEREDPARTITIONS subroutine────────*/ -orderedPartitions: procedure; #=arg(); hdr=; bot.=; top.=; low=; high= -d=123456789 /*handy-dandy literal for digits.*/ -t=0 /*T: is the sum of all arguments.*/ - do i=1 for #; t=t+('0'arg(i)) /*sum all the highest #s in parts*/ - end /*i*/ - /* [↓] process each of arguments*/ - do j=1 for #; _=arg(j) /* _: is the Jth argument.*/ - len.j=max(1,_) /*LEN: length of args, 0=special*/ - bot.j=left(d,_); if _==0 then bot.j=0 /*define the bottom num*/ - top.j=right(left(d,t),_); if _==0 then top.j=0 /* " " top " */ - @.j=left(d,t); if _==0 then @.j=0 /*define VERIFY digits.*/ - hdr=hdr _ /*build display header.*/ - low=low || bot.j; high=high || top.j /*low and high of loop.*/ +/*REXX program displays ordered partitions: orderedPartitions(i, j, k, ···). */ +call orderedPartitions 2,0,2 /*Note: 2,,2 will also work. */ +call orderedPartitions 1,1,1 +call orderedPartitions 1,2,0,1 /*Note: 1,2,1 will also work. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +orderedPartitions: procedure; #=arg(); hdr=; bot.=; top.=; low=; high=; d=123456789 +t=0 /*T: is the sum of all the arguments.*/ + do i=1 for #; t=t + arg(i) /*sum all the highest numbers in parts.*/ + end /*i*/ /* [↑] may have an omitted argument. */ + /* [↓] process each of the arguments. */ + do j=1 for #; _=arg(j) /* _: is the Jth argument. */ + len.j=max(1, _) /*LEN: length of args, 0=special. */ + bot.j=left(d, _); if _==0 then bot.j=0 /*define the bottom number. */ + top.j=right(left(d,t),_); if _==0 then top.j=0 /* " " top " */ + @.j=left(d, t); if _==0 then @.j=0 /*define the digits used for VERIFY. */ + hdr=hdr _ /*build (by appending) display header.*/ + low=low || bot.j; high=high || top.j /*the low and high numbers for DO below*/ end /*j*/ -okD=left(0||d,t+1) /*define legal digits to be used.*/ -say center(' partitions for: ' hdr" ",50,'─'); say - - do g=low to high /* [↑] generate ordered parts. */ - if verify(g,okD)\==0 then iterate /*filter out the unwanted digits.*/ - p=1 /*P: is the position of a digit.*/ - $= /*$: will be the transformed #s.*/ - do k=1 for # /*verify the partitions numbers. */ - /*validate#: dups/ordered/repeats*/ - _=substr(g,p,len.k) /*ordered part num. to be tested.*/ - if verify(_,@.k)\==0 then iterate g /*is digit ¬ valid ? */ - != /* [↓] validate num.*/ - if @.k\==0 then do j=1 for length(_); z=substr(_,j,1) - if pos(z,$)\==0 then iterate g /*prev*/ +okD=left(0 || d, t+1) /*define the legal digits to be used. */ +say center(' partitions for: ' hdr" ", 60, '─') /*display centered title for the output*/ +say + do g=low to high /* [↑] generate the ordered partitions*/ + if verify(g, okD)\==0 then iterate /*filter out unwanted decimal digits. */ + p=1 /*P: is the position of a decimal dig.*/ + $= /*$: will be the transformed numbers. */ + do k=1 for # /*verify the partitions numbers. */ + /*validate number: dups/ordered/repeats*/ + _=substr(g,p,len.k) /*ordered partition number to be tested*/ + if verify(_, @.k)\==0 then iterate g /*is the decimal digit not valid ? */ + != /* [↓] validate the decimal number. */ + if @.k\==0 then do j=1 for length(_); z=substr(_, j, 1) + if pos(z, $)\==0 then iterate g /*previous. */ !=!','z - if j==1 then iterate - if z<=substr(_,j-1,1) then iterate g /*ord.*/ - if pos(z,_,1+pos(z,_))\==0 then iterate g /*dup.*/ + if j==1 then iterate /*is firstt?*/ + if z<=substr(_, j-1, 1) then iterate g /*ordered. */ + if pos(z, _, 1+pos(z,_))\==0 then iterate g /*duplicate.*/ end /*j*/ - p=p+len.k /*point to next #.*/ - $=$ ' {'strip(translate(!,,0),,',')"}" /*dress the # up. */ + p=p + len.k /*point to the next decimal number. */ + $=$ ' {'strip( translate(!, ,0), ,",")'}' /*dress number up by suppressing LZ ···*/ end /*k*/ - - say $ + say ' ' $ /*display numbers in ordered partition.*/ end /*g*/ say return diff --git a/Task/Ordered-Partitions/Sidef/ordered-partitions.sidef b/Task/Ordered-Partitions/Sidef/ordered-partitions.sidef index bc2aaf64a2..cbbc96438c 100644 --- a/Task/Ordered-Partitions/Sidef/ordered-partitions.sidef +++ b/Task/Ordered-Partitions/Sidef/ordered-partitions.sidef @@ -3,7 +3,7 @@ func partitions({.is_empty}) { [[]] } func part(s, args) { gather { - s.combinations(args[0], { |c| + s.combinations(args[0], { |*c| part(s - c, args.ft(1)).each{|r| take([c] + r) } }) } diff --git a/Task/Ordered-Partitions/Zkl/ordered-partitions-1.zkl b/Task/Ordered-Partitions/Zkl/ordered-partitions-1.zkl new file mode 100644 index 0000000000..792d80f06b --- /dev/null +++ b/Task/Ordered-Partitions/Zkl/ordered-partitions-1.zkl @@ -0,0 +1,13 @@ +fcn partitions(args){ + args=vm.arglist; + s:=(1).pump(args.sum(0),List); // (1,2,3,...) + fcn(s,args,p){ + if(not args) return(T(T)); + res:=List(); + foreach c in (Utils.Helpers.pickNFrom(args[0],s)){ + s0:=s.copy().removeEach(c); + foreach r in (self.fcn(s0,args[1,*])){ res.append(T(c).extend(r)) } + } + res + }(s,args) +} diff --git a/Task/Ordered-Partitions/Zkl/ordered-partitions-2.zkl b/Task/Ordered-Partitions/Zkl/ordered-partitions-2.zkl new file mode 100644 index 0000000000..b83651cbd6 --- /dev/null +++ b/Task/Ordered-Partitions/Zkl/ordered-partitions-2.zkl @@ -0,0 +1,4 @@ +args:=vm.arglist.apply("toInt"); // aka argv[1..] +if(not args) args=T(2,0,2); +partitions(args.xplode()).pump(Console.println,Void); +// or: foreach p in (partitions(1,1,1)){ println(p) } diff --git a/Task/Ordered-words/Ada/ordered-words.ada b/Task/Ordered-words/Ada/ordered-words.ada index 18daf458d0..0a8042b0db 100644 --- a/Task/Ordered-words/Ada/ordered-words.ada +++ b/Task/Ordered-words/Ada/ordered-words.ada @@ -1,48 +1,32 @@ -with Ada.Containers.Indefinite_Vectors; -with Ada.Text_IO; +with Ada.Text_IO, Ada.Containers.Indefinite_Vectors; +use Ada.Text_IO; + procedure Ordered_Words is package Word_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); - - function Is_Ordered (The_Word : String) return Boolean is - Highest_Character : Character := 'a'; - begin - for I in The_Word'Range loop - if The_Word(I) not in 'a' .. 'z' then - return False; - end if; - if The_Word(I) < Highest_Character then - return False; - end if; - Highest_Character := The_Word(I); - end loop; - return True; - end Is_Ordered; - - procedure Print_Word (Position : Word_Vectors.Cursor) is - begin - Ada.Text_IO.Put_Line (Word_Vectors.Element (Position)); - end Print_Word; - - File : Ada.Text_IO.File_Type; - Ordered_Words : Word_Vectors.Vector; + use Word_Vectors; + File : File_Type; + Ordered_Words : Vector; Max_Length : Positive := 1; begin - Ada.Text_IO.Open (File, Ada.Text_IO.In_File, "unixdict.txt"); - while not Ada.Text_IO.End_Of_File (File) loop + Open (File, In_File, "unixdict.txt"); + while not End_Of_File (File) loop declare - Next_Word : String := Ada.Text_IO.Get_Line (File); + Word : String := Get_Line (File); begin - if Is_Ordered (Next_Word) then - if Next_Word'Length > Max_Length then - Max_Length := Next_Word'Length; - Word_Vectors.Clear (Ordered_Words); - Word_Vectors.Append (Ordered_Words, Next_Word); - elsif Next_Word'Length = Max_Length then - Word_Vectors.Append (Ordered_Words, Next_Word); + if (for all i in Word'First..Word'Last-1 => Word (i) <= Word(i+1)) then + if Word'Length > Max_Length then + Max_Length := Word'Length; + Ordered_Words.Clear; + Ordered_Words.Append (Word); + elsif Word'Length = Max_Length then + Ordered_Words.Append (Word); end if; end if; end; end loop; - Word_Vectors.Iterate (Ordered_Words, Print_Word'Access); + for Word of Ordered_Words loop + Put_Line (Word); + end loop; + Close (File); end Ordered_Words; diff --git a/Task/Ordered-words/BaCon/ordered-words.bacon b/Task/Ordered-words/BaCon/ordered-words.bacon new file mode 100644 index 0000000000..0693d27efa --- /dev/null +++ b/Task/Ordered-words/BaCon/ordered-words.bacon @@ -0,0 +1,22 @@ +'Ordered words - improved version +OPTION COLLAPSE TRUE + +list$ = LOAD$("unixdict.txt") + +FOR word$ IN list$ STEP NL$ + + SPLIT word$ BY 1 TO letter$ SIZE length + SORT letter$ SIZE length + JOIN letter$ BY "" TO term$ SIZE length + + IF word$ = term$ THEN + IF length > MaxLen THEN + MaxLen = length + result$ = word$ + ELIF length = MaxLen THEN + result$ = APPEND$(result$, 0, word$, NL$) + END IF + END IF +NEXT + +PRINT result$ diff --git a/Task/Ordered-words/Gambas/ordered-words.gambas b/Task/Ordered-words/Gambas/ordered-words.gambas new file mode 100644 index 0000000000..c8e21e272c --- /dev/null +++ b/Task/Ordered-words/Gambas/ordered-words.gambas @@ -0,0 +1,30 @@ +Public Sub Main() +Dim sDict As String = File.Load(User.Home &/ "unixdict.txt") 'Store the 'Dictionary' +Dim sOrdered As New String[] 'To store ordered words +Dim sHold As New String[] 'General store +Dim sTemp As String 'Temp variable +Dim siCount As Short 'Counter + +For Each sTemp In Split(sDict, gb.NewLine) 'For each word in the Dictionary + For siCount = 1 To Len(sTemp) 'Loop for each letter in the word + sHold.Add(Mid(sTemp, siCount, 1)) 'Put each letter in sHold array + Next + sHold.Sort() 'Sort sHold (abbott = abboot, zoom = mooz) + If sTemp = sHold.Join("") Then sOrdered.Add(sTemp) 'If they are the same (abbott(OK) mooz(not OK)) then add to sOrdered + sHold.Clear 'Empty sHold +Next + +siCount = 0 'Reset siCount + +For Each sTemp In sOrdered 'For each of the Ordered words + If Len(sTemp) > siCount Then siCount = Len(sTemp) 'Count the length of the word and keep a record of the longest length +Next + +For Each sTemp In sOrdered 'For each of the Ordered words + If Len(sTemp) = siCount Then sHold.Add(sTemp) 'If it is one of the longest add it to sHold +Next + +sHold.Sort() 'Sort sHold +Print sHold.Join(gb.NewLine) 'Display the result + +End diff --git a/Task/Ordered-words/jq/ordered-words.jq b/Task/Ordered-words/Jq/ordered-words.jq similarity index 100% rename from Task/Ordered-words/jq/ordered-words.jq rename to Task/Ordered-words/Jq/ordered-words.jq diff --git a/Task/Ordered-words/OoRexx/ordered-words.rexx b/Task/Ordered-words/OoRexx/ordered-words.rexx new file mode 100644 index 0000000000..6165beaf53 --- /dev/null +++ b/Task/Ordered-words/OoRexx/ordered-words.rexx @@ -0,0 +1,27 @@ +/*REXX list (the longest) ordered word(s) from a supplied dictionary. */ +iFID= 'UNIXDICT.TXT' +w.='' +mL=0 +Do j=1 While lines(iFID)\==0 + x=linein(iFID) + w=length(x) + If w>=mL Then Do + Parse Upper Var x xU 1 z 2 + Do k=2 To w + _=substr(xU, k, 1) + If \datatype(_, 'U') Then Iterate + If _1) diff --git a/Task/Ordered-words/Python/ordered-words-3.py b/Task/Ordered-words/Python/ordered-words-3.py deleted file mode 100644 index a018f09879..0000000000 --- a/Task/Ordered-words/Python/ordered-words-3.py +++ /dev/null @@ -1,3 +0,0 @@ -from itertools import groupby -o = (w for w in map(str.strip, open("unixdict.txt")) if sorted(w)==list(w)) -print list(next(groupby(sorted(o, key=len, reverse=True), key=len))[1]) diff --git a/Task/Ordered-words/SPL/ordered-words.spl b/Task/Ordered-words/SPL/ordered-words.spl new file mode 100644 index 0000000000..6652d693e5 --- /dev/null +++ b/Task/Ordered-words/SPL/ordered-words.spl @@ -0,0 +1,15 @@ +words = #.split(#.readtext("unixdict.txt","ascii"),#.lf) +max = 0 +> i, 1..#.size(words,1) + word = words[i] + wordb = #.array(word) + wordbc = #.size(wordb,1) + > j, 3..wordbc,2 + << wordb[j]> j!>wordbc|wordbcmax, result = "" + ? wordbc>max, max = wordbc + result += word+#.crlf +< +#.output(result) diff --git a/Task/Ordered-words/Simula/ordered-words.simula b/Task/Ordered-words/Simula/ordered-words.simula new file mode 100644 index 0000000000..0525c080a6 --- /dev/null +++ b/Task/Ordered-words/Simula/ordered-words.simula @@ -0,0 +1,54 @@ +BEGIN + + BOOLEAN PROCEDURE ISORDERED(W); TEXT W; + BEGIN + BOOLEAN B; + B := TRUE; + W.SETPOS(1); + IF W.MORE THEN + BEGIN + CHARACTER CURR, LAST; + CURR := W.GETCHAR; + WHILE W.MORE AND B DO + BEGIN + LAST := CURR; + CURR := W.GETCHAR; + B := LAST <= CURR; + END; + END; + ISORDERED := B; + END; + + REF (INFILE) INF; + INTEGER LONGEST; + TEXT W; + + COMMENT FIND LONGEST LENGTH; + INF :- NEW INFILE("unixdict.txt"); + INF.OPEN(BLANKS(132)); + WHILE NOT INF.LASTITEM DO + BEGIN + W :- COPY(INF.IMAGE).STRIP; + IF ISORDERED(W) THEN + IF W.LENGTH > LONGEST THEN + LONGEST := W.LENGTH; + INF.INIMAGE; + END; + INF.CLOSE; + + COMMENT OUTPUT ORDRERED WORDS OF LONGEST LENGTH; + INF :- NEW INFILE("unixdict.txt"); + INF.OPEN(BLANKS(132)); + WHILE NOT INF.LASTITEM DO + BEGIN + W :- COPY(INF.IMAGE).STRIP; + IF W.LENGTH = LONGEST AND THEN ISORDERED(W) THEN + BEGIN + OUTTEXT(W); + OUTIMAGE; + END; + INF.INIMAGE; + END; + INF.CLOSE; + +END. diff --git a/Task/Ordered-words/Zkl/ordered-words-1.zkl b/Task/Ordered-words/Zkl/ordered-words-1.zkl new file mode 100644 index 0000000000..de0c53d830 --- /dev/null +++ b/Task/Ordered-words/Zkl/ordered-words-1.zkl @@ -0,0 +1,11 @@ +var words=L(), sz=0; // some state +fcn isLex(word){ word.reduce(fcn(p,c){ (p<=c) and c or T(Void.Stop,False) }) } +File("dict.txt").pump(Void,fcn(w){ + w=w.strip(); // get rid of newline + if(isLex(w)){ n:=w.len(); + if(n>sz){ words.clear(w); sz=n } + else if(n==sz) words.append(w) + } +}) +println("Num words: %d, all size %d\n".fmt(words.len(),sz)); +words.pump(Console.println); diff --git a/Task/Ordered-words/Zkl/ordered-words-2.zkl b/Task/Ordered-words/Zkl/ordered-words-2.zkl new file mode 100644 index 0000000000..09bf86f33c --- /dev/null +++ b/Task/Ordered-words/Zkl/ordered-words-2.zkl @@ -0,0 +1,6 @@ +fcn isLex(word){ word.reduce(fcn(p,c){ (p<=c) and c or T(Void.Stop,False) }) } +lwords:=File("dict.txt").readln(*).apply("strip").filter(isLex); +max:=lwords.reduce(fcn(n,w){ w.len()>n and w.len() or n },0); +lwords=lwords.filter(fcn(w,n){ w.len()==n },max); +println("Num words: %d, all size %d\n".fmt(lwords.len(),max)); +words.pump(Console.println); diff --git a/Task/Palindrome-detection/00META.yaml b/Task/Palindrome-detection/00META.yaml index be514df841..7e1befc3ad 100644 --- a/Task/Palindrome-detection/00META.yaml +++ b/Task/Palindrome-detection/00META.yaml @@ -3,4 +3,5 @@ category: - Recursion - String manipulation - Classic CS problems and programs +- Palindromes note: Text processing diff --git a/Task/Palindrome-detection/Ada/palindrome-detection.ada b/Task/Palindrome-detection/Ada/palindrome-detection-1.ada similarity index 100% rename from Task/Palindrome-detection/Ada/palindrome-detection.ada rename to Task/Palindrome-detection/Ada/palindrome-detection-1.ada diff --git a/Task/Palindrome-detection/Ada/palindrome-detection-2.ada b/Task/Palindrome-detection/Ada/palindrome-detection-2.ada new file mode 100644 index 0000000000..a7e943184d --- /dev/null +++ b/Task/Palindrome-detection/Ada/palindrome-detection-2.ada @@ -0,0 +1,2 @@ +function Palindrome (Text : String) return Boolean is +(for all i in Text'Range => Text(i)= Text(Text'Last-i+Text'First)); diff --git a/Task/Palindrome-detection/AppleScript/palindrome-detection.applescript b/Task/Palindrome-detection/AppleScript/palindrome-detection.applescript index 7626ae96c7..8488eb291c 100644 --- a/Task/Palindrome-detection/AppleScript/palindrome-detection.applescript +++ b/Task/Palindrome-detection/AppleScript/palindrome-detection.applescript @@ -1,43 +1,48 @@ use framework "Foundation" +-- CASE-INSENSITIVE PALINDROME, IGNORING SPACES ? ---------------------------- -- isPalindrome :: String -> Bool on isPalindrome(s) s = intercalate("", reverse of characters of s) end isPalindrome +-- toSpaceFreeLower :: String -> String +on spaceFreeToLower(s) + script notSpace + on |λ|(s) + s is not space + end |λ| + end script + + intercalate("", filter(notSpace, characters of toLower(s))) +end spaceFreeToLower --- TEST - +-- TEST ---------------------------------------------------------------------- on run - isPalindrome(lowerCaseNoSpace("In girum imus nocte et consumimur igni")) + isPalindrome(spaceFreeToLower("In girum imus nocte et consumimur igni")) --> true end run --- lowerCaseNoSpace :: String -> String -on lowerCaseNoSpace(s) - script notSpace - on lambda(s) - s is not space - end lambda - end script - intercalate("", filter(notSpace, characters of toLowerCase(s))) -end lowerCaseNoSpace +-- GENERIC FUNCTIONS --------------------------------------------------------- - --- GENERIC LIBRARY FUNCTIONS - --- toLowerCase :: String -> String -on toLowerCase(str) - set ca to current application - ((ca's NSString's stringWithString:(str))'s ¬ - lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text -end toLowerCase +-- filter :: (a -> Bool) -> [a] -> [a] +on filter(f, xs) + tell mReturn(f) + set lst to {} + set lng to length of xs + repeat with i from 1 to lng + set v to item i of xs + if |λ|(v, i, xs) then set end of lst to v + end repeat + return lst + end tell +end filter -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) @@ -47,19 +52,6 @@ on intercalate(strText, lstText) return strJoined end intercalate --- filter :: (a -> Bool) -> [a] -> [a] -on filter(f, xs) - tell mReturn(f) - set lst to {} - set lng to length of xs - repeat with i from 1 to lng - set v to item i of xs - if lambda(v, i, xs) then set end of lst to v - end repeat - return lst - end tell -end filter - -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) @@ -67,7 +59,14 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn + +-- toLower :: String -> String +on toLower(str) + set ca to current application + ((ca's NSString's stringWithString:(str))'s ¬ + lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text +end toLower diff --git a/Task/Palindrome-detection/BASIC/palindrome-detection.basic b/Task/Palindrome-detection/BASIC/palindrome-detection-1.basic similarity index 100% rename from Task/Palindrome-detection/BASIC/palindrome-detection.basic rename to Task/Palindrome-detection/BASIC/palindrome-detection-1.basic diff --git a/Task/Palindrome-detection/BASIC/palindrome-detection-2.basic b/Task/Palindrome-detection/BASIC/palindrome-detection-2.basic new file mode 100644 index 0000000000..d3e6606911 --- /dev/null +++ b/Task/Palindrome-detection/BASIC/palindrome-detection-2.basic @@ -0,0 +1,7 @@ + 10 INPUT S$ + 20 FOR I=1 TO LEN S$/2 + 30 IF S$(I)<>S$(LEN S$-I+1) THEN GOTO 60 + 40 NEXT I + 50 GOTO 70 + 60 PRINT "NOT A "; + 70 PRINT "PALINDROME" diff --git a/Task/Palindrome-detection/BASIC/palindrome-detection-3.basic b/Task/Palindrome-detection/BASIC/palindrome-detection-3.basic new file mode 100644 index 0000000000..c73c02961c --- /dev/null +++ b/Task/Palindrome-detection/BASIC/palindrome-detection-3.basic @@ -0,0 +1,8 @@ + 15 GOSUB 90 + 80 STOP + 90 LET T$="" +100 FOR I=1 TO LEN S$ +110 IF S$(I)>="A" AND S$(I)<="Z" THEN LET T$=T$+S$(I) +120 NEXT I +130 LET S$=T$ +140 RETURN diff --git a/Task/Palindrome-detection/BaCon/palindrome-detection.bacon b/Task/Palindrome-detection/BaCon/palindrome-detection.bacon new file mode 100644 index 0000000000..ddc5e689b5 --- /dev/null +++ b/Task/Palindrome-detection/BaCon/palindrome-detection.bacon @@ -0,0 +1,11 @@ +OPTION COMPARE TRUE + +INPUT "Enter your line... ", word$ + +IF word$ = REVERSE$(word$) THEN + PRINT "This is an exact palindrome!" +ELIF EXTRACT$(word$, "[[:punct:]]|[[:blank:]]", TRUE) = REVERSE$(EXTRACT$(word$, "[[:punct:]]|[[:blank:]]", TRUE)) THEN + PRINT "This is an inexact palindrome!" +ELSE + PRINT "Not a palindrome." +ENDIF diff --git a/Task/Palindrome-detection/CoffeeScript/palindrome-detection-1.coffee b/Task/Palindrome-detection/CoffeeScript/palindrome-detection-1.coffee deleted file mode 100644 index c7f27f6ae1..0000000000 --- a/Task/Palindrome-detection/CoffeeScript/palindrome-detection-1.coffee +++ /dev/null @@ -1,3 +0,0 @@ -isPalindrome = (str) -> - stripped = str.toLowerCase().replace /\W/g, "" - stripped == (stripped.split "").reverse().join "" diff --git a/Task/Palindrome-detection/CoffeeScript/palindrome-detection-2.coffee b/Task/Palindrome-detection/CoffeeScript/palindrome-detection-2.coffee deleted file mode 100644 index 9a32fbb1ad..0000000000 --- a/Task/Palindrome-detection/CoffeeScript/palindrome-detection-2.coffee +++ /dev/null @@ -1,7 +0,0 @@ -strings = [ - "In girum imus nocte et consumimur igni" - "A man, a plan, a canal: Panama!" - "There is no spoon." -] - -console.log "'#{str}' : #{isPalindrome str}" for str in strings diff --git a/Task/Palindrome-detection/FBSL/palindrome-detection-1.fbsl b/Task/Palindrome-detection/FBSL/palindrome-detection-1.fbsl deleted file mode 100644 index e06e6b794e..0000000000 --- a/Task/Palindrome-detection/FBSL/palindrome-detection-1.fbsl +++ /dev/null @@ -1,27 +0,0 @@ -#APPTYPE CONSOLE - -FUNCTION stripNonAlpha(BYVAL s AS STRING) AS STRING - DIM sTemp AS STRING = "" - DIM c AS STRING - FOR DIM i = 1 TO LEN(s) - c = MID(s, i, 1) - IF INSTR("ABCDEFGHIJKLMNOPQRSTUVWXYZ", c, 0, 1) THEN - sTemp = stemp & c - END IF - NEXT - RETURN sTemp -END FUNCTION - -FUNCTION IsPalindrome(BYVAL s AS STRING) AS INTEGER - FOR DIM i = 1 TO STRLEN(s) \ 2 ' only check half of the string, as scanning from both ends - IF s{i} <> s{STRLEN - (i - 1)} THEN RETURN FALSE 'comparison is not case sensitive - NEXT - - RETURN TRUE -END FUNCTION - -PRINT IsPalindrome(stripNonAlpha("A Toyota")) -PRINT IsPalindrome(stripNonAlpha("Madam, I'm Adam")) -PRINT IsPalindrome(stripNonAlpha("the rain in Spain falls mainly on the rooftops")) - -PAUSE diff --git a/Task/Palindrome-detection/FBSL/palindrome-detection-2.fbsl b/Task/Palindrome-detection/FBSL/palindrome-detection-2.fbsl deleted file mode 100644 index ffff75586d..0000000000 --- a/Task/Palindrome-detection/FBSL/palindrome-detection-2.fbsl +++ /dev/null @@ -1 +0,0 @@ -Outputs 1, 1, 0 respectively diff --git a/Task/Palindrome-detection/Forth/palindrome-detection.fth b/Task/Palindrome-detection/Forth/palindrome-detection-1.fth similarity index 100% rename from Task/Palindrome-detection/Forth/palindrome-detection.fth rename to Task/Palindrome-detection/Forth/palindrome-detection-1.fth diff --git a/Task/Palindrome-detection/Forth/palindrome-detection-2.fth b/Task/Palindrome-detection/Forth/palindrome-detection-2.fth new file mode 100644 index 0000000000..0ce7ed47eb --- /dev/null +++ b/Task/Palindrome-detection/Forth/palindrome-detection-2.fth @@ -0,0 +1,31 @@ +variable temp-addr + +: valid-char? ( addr1 u -- f ) ( check for valid character ) + + dup C@ 48 58 within + over C@ 65 91 within or + swap C@ 97 123 within or ; + +: >upper ( c1 -- c2 ) + dup 97 123 within if 32 - then ; + +: strip-input ( addr1 u -- addr2 u ) ( Strip characters, then copy stripped string to temp-addr ) + pad temp-addr ! + temp-addr @ rot rot 0 do dup I 2dup valid-char? if + + C@ >upper temp-addr @ C! 1 temp-addr +! + else 2drop + then loop drop temp-addr @ pad - ; + +: get-phrase ( -- addr1 u ) + ." Type a phrase: " here 1024 accept here swap -trailing cr ; + +: position-phrase ( addr1 u -- addr1 u addr2 u addr1 addr2 u ) + temp-addr @ over 2over 2over drop swap ; + +: reverse-copy ( addr1 addr2 u -- addr1 addr2 ) + 0 do over I' 1- I - + over I + 1 cmove loop 2drop ; + +: palindrome? ( addr1 u1 -- ) + get-phrase strip-input position-phrase reverse-copy compare 0= if + ." << Valid >> Palindrome." + else ." << Not >> a Palindrome." + then cr ; diff --git a/Task/Palindrome-detection/Haskell/palindrome-detection-2.hs b/Task/Palindrome-detection/Haskell/palindrome-detection-2.hs index 32fb6b472c..d472f87f74 100644 --- a/Task/Palindrome-detection/Haskell/palindrome-detection-2.hs +++ b/Task/Palindrome-detection/Haskell/palindrome-detection-2.hs @@ -1,3 +1,19 @@ -is_palindrome_r x | length x <= 1 = True - | head x == last x = is_palindrome_r . tail. init $ x - | otherwise = False +import Data.Char (toLower) + +isPalindrome :: String -> Bool +isPalindrome = (==) <*> reverse + +-- Alternatively, comparing just the first half with the reversed latter half +isPal :: String -> Bool +isPal s = + let (q, r) = quotRem (length s) 2 + in take q s == reverse (drop (q + r) s) + +sample :: String +sample = "In girum imus nocte et consumimur igni" + +prepared :: String -> String +prepared = filter (' ' /=) . fmap toLower + +main :: IO () +main = print $ [isPalindrome, isPal] <*> [prepared sample] diff --git a/Task/Palindrome-detection/Haskell/palindrome-detection-3.hs b/Task/Palindrome-detection/Haskell/palindrome-detection-3.hs new file mode 100644 index 0000000000..32fb6b472c --- /dev/null +++ b/Task/Palindrome-detection/Haskell/palindrome-detection-3.hs @@ -0,0 +1,3 @@ +is_palindrome_r x | length x <= 1 = True + | head x == last x = is_palindrome_r . tail. init $ x + | otherwise = False diff --git a/Task/Palindrome-detection/jq/palindrome-detection.jq b/Task/Palindrome-detection/Jq/palindrome-detection.jq similarity index 100% rename from Task/Palindrome-detection/jq/palindrome-detection.jq rename to Task/Palindrome-detection/Jq/palindrome-detection.jq diff --git a/Task/Palindrome-detection/K/palindrome-detection.k b/Task/Palindrome-detection/K/palindrome-detection.k new file mode 100644 index 0000000000..fe1061a049 --- /dev/null +++ b/Task/Palindrome-detection/K/palindrome-detection.k @@ -0,0 +1 @@ +is_palindrome:{x~|x} diff --git a/Task/Palindrome-detection/Kotlin/palindrome-detection.kotlin b/Task/Palindrome-detection/Kotlin/palindrome-detection.kotlin new file mode 100644 index 0000000000..30391fd527 --- /dev/null +++ b/Task/Palindrome-detection/Kotlin/palindrome-detection.kotlin @@ -0,0 +1,29 @@ +// version 1.1.2 + +/* These functions deal automatically with Unicode as all strings are UTF-16 encoded in Kotlin */ + +fun isExactPalindrome(s: String) = (s == s.reversed()) + +fun isInexactPalindrome(s: String): Boolean { + var t = "" + for (c in s) if (c.isLetterOrDigit()) t += c + t = t.toLowerCase() + return t == t.reversed() +} + +fun main(args: Array) { + val candidates = arrayOf("rotor", "rosetta", "step on no pets", "été") + for (candidate in candidates) { + println("'$candidate' is ${if (isExactPalindrome(candidate)) "an" else "not an"} exact palindrome") + } + println() + val candidates2 = arrayOf( + "In girum imus nocte et consumimur igni", + "Rise to vote, sir", + "A man, a plan, a canal - Panama!", + "Ce repère, Perec" // note: 'è' considered a distinct character from 'e' + ) + for (candidate in candidates2) { + println("'$candidate' is ${if (isInexactPalindrome(candidate)) "an" else "not an"} inexact palindrome") + } +} diff --git a/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection-1.liberty b/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection-1.liberty deleted file mode 100644 index bca4d4cedd..0000000000 --- a/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection-1.liberty +++ /dev/null @@ -1,22 +0,0 @@ -print isPalindrome("In girum imus nocte et consumimur igni") -print isPalindrome(removePunctuation$("In girum imus nocte et consumimur igni", "S")) -print isPalindrome(removePunctuation$("In girum imus nocte et consumimur igni", "SC")) - -function isPalindrome(string$) - isPalindrome = 1 - for i = 1 to int(len(string$)/2) - if mid$(string$, i, 1) <> mid$(string$, len(string$)-i+1, 1) then isPalindrome = 0 : exit function - next i -end function - -function removePunctuation$(string$, remove$) - 'P = remove puctuation. S = remove spaces C = remove case - If instr(upper$(remove$), "C") then string$ = lower$(string$) - If instr(upper$(remove$), "P") then removeCharacters$ = ",.!'()-&*?<>:;~[]{}" - If instr(upper$(remove$), "S") then removeCharacters$ = removeCharacters$;" " - - for i = 1 to len(string$) - if instr(removeCharacters$, mid$(string$, i, 1)) then string$ = left$(string$, i-1);right$(string$, len(string$)-i) : i = i - 1 - next i - removePunctuation$ = string$ -end function diff --git a/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection-2.liberty b/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection-2.liberty deleted file mode 100644 index bb5ee5c21e..0000000000 --- a/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection-2.liberty +++ /dev/null @@ -1,3 +0,0 @@ -0 -0 -1 diff --git a/Task/Palindrome-detection/Phix/palindrome-detection.phix b/Task/Palindrome-detection/Phix/palindrome-detection.phix index 0606f5b298..5890ca68da 100644 --- a/Task/Palindrome-detection/Phix/palindrome-detection.phix +++ b/Task/Palindrome-detection/Phix/palindrome-detection.phix @@ -2,4 +2,23 @@ function is_palindrome(sequence s) return s==reverse(s) end function -?is_palindrome(lower(substitute("In girum imus nocte et consumimur igni"," ",""))) -- prints 1 +?is_palindrome("rotator") -- prints 1 +?is_palindrome("tractor") -- prints 0 + +constant punctuation = " `~!@#$%^&*()-=_+[]{}\\|;:',.<>/?", + nulls = repeat("",length(punctuation)) + +function extra_credit(sequence s) + s = utf8_to_utf32(lower(substitute_all(s,punctuation,nulls))) + return s==reverse(s) +end function + +-- these all print 1 (true) +?extra_credit("Madam, I'm Adam.") +?extra_credit("A man, a plan, a canal: Panama!") +?extra_credit("In girum imus nocte et consumimur igni") +?extra_credit("人人為我,我為人人") +?extra_credit("Я иду с мечем, судия") +?extra_credit("아들딸들아") +?extra_credit("가련하시다 사장집 아들딸들아 집장사 다시 하련가") +?extra_credit("tregða, gón, reiði - er nóg að gert") diff --git a/Task/Palindrome-detection/PowerShell/palindrome-detection-1.psh b/Task/Palindrome-detection/PowerShell/palindrome-detection-1.psh index b27bab275e..21ce687e84 100644 --- a/Task/Palindrome-detection/PowerShell/palindrome-detection-1.psh +++ b/Task/Palindrome-detection/PowerShell/palindrome-detection-1.psh @@ -1,5 +1,5 @@ Function Test-Palindrome( [String] $Text ){ $CharArray = $Text.ToCharArray() [Array]::Reverse($CharArray) - $Text.ToCharArray() -eq $CharArray + $Text -like (-join $CharArray) } diff --git a/Task/Palindrome-detection/Rust/palindrome-detection-1.rust b/Task/Palindrome-detection/Rust/palindrome-detection-1.rust new file mode 100644 index 0000000000..81979f29e2 --- /dev/null +++ b/Task/Palindrome-detection/Rust/palindrome-detection-1.rust @@ -0,0 +1,20 @@ +fn is_palindrome(string: &str) -> bool { + let half_len = string.len()/2; + string.chars().take(half_len).eq(string.chars().take(half_len).rev()) +} + +macro_rules! test { + ( $( $x:tt ),* ) => { $( println!("'{}': {}", $x, is_palindrome($x)); )* }; +} + +fn main() { + test!("", + "a", + "ada", + "adad", + "ingirumimusnocteetconsumimurigni", + "人人為我,我為人人", + "Я иду с мечем, судия", + "아들딸들아", + "The quick brown fox"); +} diff --git a/Task/Palindrome-detection/Rust/palindrome-detection-2.rust b/Task/Palindrome-detection/Rust/palindrome-detection-2.rust new file mode 100644 index 0000000000..2b980a5835 --- /dev/null +++ b/Task/Palindrome-detection/Rust/palindrome-detection-2.rust @@ -0,0 +1,5 @@ +extern crate unicode_segmentation; +use unicode_segmentation::UnicodeSegmentation; +fn is_palindrome(string: &str) -> bool { + string.graphemes(true).eq(string.graphemes(true).rev()) +} diff --git a/Task/Palindrome-detection/Rust/palindrome-detection.rust b/Task/Palindrome-detection/Rust/palindrome-detection.rust deleted file mode 100644 index a483e1dccb..0000000000 --- a/Task/Palindrome-detection/Rust/palindrome-detection.rust +++ /dev/null @@ -1,19 +0,0 @@ -fn is_palindrome(string: &str) -> bool { - string.chars().zip(string.chars().rev()).all(|(x, y)| x == y) -} - -macro_rules! test { - ( $( $x:tt ),* ) => { $( println!("'{}': {}", $x, is_palindrome($x)); )* }; -} - -fn main() { - test!("", - "a", - "ada", - "adad", - "ingirumimusnocteetconsumimurigni", - "人人為我,我為人人", - "Я иду с мечем, судия", - "아들딸들아", - "The quick brown fox"); -} diff --git a/Task/Palindrome-detection/Scala/palindrome-detection-5.scala b/Task/Palindrome-detection/Scala/palindrome-detection-5.scala deleted file mode 100644 index 1a63921a01..0000000000 --- a/Task/Palindrome-detection/Scala/palindrome-detection-5.scala +++ /dev/null @@ -1,4 +0,0 @@ -def isPalindrome(s : String) : Boolean = s match { - case s if s.length > 1 => (s.head == s.last) && isPalindrome(s.slice(1, s.length-1)) - case _ => true -} diff --git a/Task/Palindrome-detection/Scheme/palindrome-detection-2.ss b/Task/Palindrome-detection/Scheme/palindrome-detection-2.ss index 1665831b13..fec2464248 100644 --- a/Task/Palindrome-detection/Scheme/palindrome-detection-2.ss +++ b/Task/Palindrome-detection/Scheme/palindrome-detection-2.ss @@ -13,7 +13,7 @@ (and (char=? (car s) (car r)) (loop (cdr s) (cdr r)))))) -> (palindrome? "ingirumimusnocteetconsumimurigni") +> (palindrome? "ingirumimusnocteetconsumimurigni") #t > (palindrome? "This is not a palindrome") #f diff --git a/Task/Palindrome-detection/Simula/palindrome-detection.simula b/Task/Palindrome-detection/Simula/palindrome-detection.simula new file mode 100644 index 0000000000..4108decfc5 --- /dev/null +++ b/Task/Palindrome-detection/Simula/palindrome-detection.simula @@ -0,0 +1,33 @@ +BEGIN + + BOOLEAN PROCEDURE ISPALINDROME(T); TEXT T; + BEGIN + BOOLEAN RESULT; + INTEGER I, J; + I := 1; + J := T.LENGTH; + RESULT := TRUE; + WHILE RESULT AND I < J DO + BEGIN + CHARACTER L, R; + T.SETPOS(I); L := T.GETCHAR; I := I + 1; + T.SETPOS(J); R := T.GETCHAR; J := J - 1; + RESULT := L = R; + END; + ISPALINDROME := RESULT; + END ISPALINDROME; + + TEXT T; + FOR T :- "", "A", "AA", "ABA", "SALALAS", "MADAMIMADAM", + "AB", "AAB", "ABCBDA" + DO + BEGIN + OUTTEXT(IF ISPALINDROME(T) THEN "IS " ELSE "ISN'T"); + OUTTEXT(" PALINDROME: "); + OUTCHAR('"'); + OUTTEXT(T); + OUTCHAR('"'); + OUTIMAGE; + END; + +END. diff --git a/Task/Palindrome-detection/Standard-ML/palindrome-detection.ml b/Task/Palindrome-detection/Standard-ML/palindrome-detection.ml deleted file mode 100644 index 9694e720d0..0000000000 --- a/Task/Palindrome-detection/Standard-ML/palindrome-detection.ml +++ /dev/null @@ -1,4 +0,0 @@ -fun palindrome s = - let val cs = explode s in - cs = rev cs - end diff --git a/Task/Palindrome-detection/VBScript/palindrome-detection-3.vb b/Task/Palindrome-detection/VBScript/palindrome-detection-3.vb deleted file mode 100644 index 1d208904c3..0000000000 --- a/Task/Palindrome-detection/VBScript/palindrome-detection-3.vb +++ /dev/null @@ -1,4 +0,0 @@ -0 --1 -0 --1 diff --git a/Task/Palindrome-detection/X86-Assembly/palindrome-detection.x86 b/Task/Palindrome-detection/X86-Assembly/palindrome-detection.x86 new file mode 100644 index 0000000000..2d8106f202 --- /dev/null +++ b/Task/Palindrome-detection/X86-Assembly/palindrome-detection.x86 @@ -0,0 +1,35 @@ +; x86_84 Linux nasm +section .text + +isPalindrome: + mov rsi, rax + mov rdi, rax + + get_end: + cmp byte [rsi], 0 + je get_result + inc rsi + jmp get_end + + get_result: + mov rax, 0 + dec rsi + + compare: + mov cl, byte [rdi] + cmp byte [rsi], cl + jne not_palindrome + cmp rsi, rdi + je palindrome + inc rdi + cmp rdi, rsi + je palindrome + dec rsi + jmp compare + + not_palindrome: + mov rax, 0 + ret + palindrome: + mov rax, 1 + ret diff --git a/Task/Palindrome-detection/Zkl/palindrome-detection.zkl b/Task/Palindrome-detection/Zkl/palindrome-detection.zkl new file mode 100644 index 0000000000..2da15058f2 --- /dev/null +++ b/Task/Palindrome-detection/Zkl/palindrome-detection.zkl @@ -0,0 +1,5 @@ +fcn pali(text){ + if (text.len()<2) return(False); + text==text.reverse(); +} +fcn pali2(text){ pali((text - " \t\n.,").toLower()) } // or whatever punctuation is diff --git a/Task/Pangram-checker/ATS/pangram-checker.ats b/Task/Pangram-checker/ATS/pangram-checker.ats new file mode 100644 index 0000000000..733f3b9166 --- /dev/null +++ b/Task/Pangram-checker/ATS/pangram-checker.ats @@ -0,0 +1,45 @@ +(* ****** ****** *) +// +#include +"share/atspre_staload.hats" +#include +"share/HATS/atspre_staload_libats_ML.hats" +// +(* ****** ****** *) +// +fun +letter_check +( +cs: string, c0: char +) : bool = cs.exists()(lam(c) => c0 = c) +// +(* ****** ****** *) + +fun +Pangram_check + (text: string): bool = let +// +val +alphabet = "abcdefghijklmnopqrstuvwxyz" +val +((*void*)) = assertloc(length(alphabet) = 26) +// +in + alphabet.forall()(lam(c) => letter_check(text, c) || letter_check(text, toupper(c))) +end // end of [Pangram_check] + +(* ****** ****** *) + +implement +main0 () = +{ +// +val +text0 = "The quick brown fox jumps over the lazy dog." +// +val-true = Pangram_check(text0) +val-false = Pangram_check("This is not a pangram sentence.") +// +} (* end of [main0] *) + +(* ****** ****** *) diff --git a/Task/Pangram-checker/BASIC/pangram-checker.basic b/Task/Pangram-checker/BASIC/pangram-checker-1.basic similarity index 100% rename from Task/Pangram-checker/BASIC/pangram-checker.basic rename to Task/Pangram-checker/BASIC/pangram-checker-1.basic diff --git a/Task/Pangram-checker/BASIC/pangram-checker-2.basic b/Task/Pangram-checker/BASIC/pangram-checker-2.basic new file mode 100644 index 0000000000..2b9dc57fbc --- /dev/null +++ b/Task/Pangram-checker/BASIC/pangram-checker-2.basic @@ -0,0 +1,18 @@ + 10 LET A$="ABCDEFGHIJKLMNOPQRSTUVWXYZ" + 20 LET L=26 + 30 INPUT P$ + 40 IF LEN P$<26 THEN GOTO 170 + 50 FAST + 60 LET C=1 + 70 IF P$(C)<"A" OR P$(C)>"Z" THEN GOTO 120 + 80 IF A$(CODE P$(C)-37)=" " THEN GOTO 120 + 90 LET A$(CODE P$(C)-37)=" " +100 LET L=L-1 +110 IF L=0 THEN GOTO 150 +120 IF C=LEN P$ THEN GOTO 170 +130 LET C=C+1 +140 GOTO 70 +150 PRINT "PANGRAM" +160 GOTO 180 +170 PRINT "NOT A PANGRAM" +180 SLOW diff --git a/Task/Pangram-checker/jq/pangram-checker.jq b/Task/Pangram-checker/Jq/pangram-checker.jq similarity index 100% rename from Task/Pangram-checker/jq/pangram-checker.jq rename to Task/Pangram-checker/Jq/pangram-checker.jq diff --git a/Task/Pangram-checker/Kotlin/pangram-checker.kotlin b/Task/Pangram-checker/Kotlin/pangram-checker.kotlin new file mode 100644 index 0000000000..cb5a0505ed --- /dev/null +++ b/Task/Pangram-checker/Kotlin/pangram-checker.kotlin @@ -0,0 +1,20 @@ +// version 1.0.6 + +fun isPangram(s: String): Boolean { + if (s.length < 26) return false + val t = s.toLowerCase() + for (c in 'a' .. 'z') + if (c !in t) return false + return true +} + +fun main(args: Array) { + val candidates = arrayOf( + "The quick brown fox jumps over the lazy dog", + "New job: fix Mr. Gluck's hazy TV, PDQ!", + "A very bad quack might jinx zippy fowls", + "A very mad quack might jinx zippy fowls" // no 'b' now! + ) + for (candidate in candidates) + println("'$candidate' is ${if (isPangram(candidate)) "a" else "not a"} pangram") +} diff --git a/Task/Pangram-checker/Phix/pangram-checker.phix b/Task/Pangram-checker/Phix/pangram-checker.phix new file mode 100644 index 0000000000..28bff596ed --- /dev/null +++ b/Task/Pangram-checker/Phix/pangram-checker.phix @@ -0,0 +1,31 @@ +function pangram(string s) +sequence az = repeat(false,26) +integer count = 0 + for i=1 to length(s) do + integer ch = lower(s[i]) + if ch>='a' + and ch<='z' + and not az[ch-96] then + count += 1 + if count=26 then return {true,0} end if + az[ch-96] = true + end if + end for + return {false,find(false,az)+96} +end function + +sequence checks = {"The quick brown fox jumped over the lazy dog", + "The quick brown fox jumps over the lazy dog", + ".!$\"AbCdEfghijklmnoprqstuvwxyz", + "THE FIVE BOXING WIZARDS DUMP QUICKLY.", + "THE FIVE BOXING WIZARDS JUMP QUICKLY.", + "HEAVY BOXES PERFORM WALTZES AND JIGS.", + "PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS.", + "Big fjiords vex quick waltz nymph", + "The quick onyx goblin jumps over the lazy dwarf.", + "no"} +for i=1 to length(checks) do + string ci = checks[i] + integer {r,ch} = pangram(ci) + printf(1,"%-50s - %s\n",{ci,iff(r?"yes":"no "&ch)}) +end for diff --git a/Task/Pangram-checker/Zkl/pangram-checker.zkl b/Task/Pangram-checker/Zkl/pangram-checker.zkl new file mode 100644 index 0000000000..37511a94f5 --- /dev/null +++ b/Task/Pangram-checker/Zkl/pangram-checker.zkl @@ -0,0 +1,2 @@ +var letters=["a".."z"].pump(String); //-->"abcdefghijklmnopqrstuvwxyz" +fcn isPangram(text){(not (letters-text.toLower()))} diff --git a/Task/Paraffins/FreeBASIC/paraffins.freebasic b/Task/Paraffins/FreeBASIC/paraffins.freebasic new file mode 100644 index 0000000000..f3500457c4 --- /dev/null +++ b/Task/Paraffins/FreeBASIC/paraffins.freebasic @@ -0,0 +1,100 @@ +' version 31-12-2016 +' compile with: fbc -s console +' uses gmp, translation from pascal + +#Include Once "gmp.bi" + +Const As Integer max_n = 500, branch = 4 + +Dim Shared As mpz_ptr rooted(), unrooted(), c() +Dim Shared As mpz_ptr cnt, tmp + +Sub tree(br As UInteger, n As UInteger, l As UInteger, sum As UInteger, cnt As mpz_ptr) + + Dim As UInteger b, m + + For b = br +1 To branch + sum = sum + n + If sum > max_n Then Return + + ' prevent unneeded long math + If (l * 2 >= sum) And (b >= branch) Then Return + + If b = (br +1) Then + mpz_mul(c(br), rooted(n), cnt) + Else + mpz_add_ui(tmp, rooted(n), b - br -1) + mpz_mul(c(br), c(br), tmp) + mpz_divexact_ui(c(br), c(br), b - br) + End If + + If l * 2 < sum Then + mpz_add(unrooted(sum), unrooted(sum), c(br)) + End If + If b < branch Then + mpz_add(rooted(sum), rooted(sum), c(br)) + For m = n -1 To 1 Step -1 + tree(b, m, l, sum, c(br)) + Next + End If + Next + +End Sub + +Sub bicenter(s As UInteger) + If (s And 1) = 1 Then Return + mpz_add_ui(tmp, rooted(s \ 2), 1) + mpz_mul(tmp, rooted(s \ 2), tmp) + mpz_tdiv_q_2exp(tmp, tmp, 1) + mpz_add(unrooted(s), unrooted(s), tmp) +End Sub + +' ------=< MAIN >=------ + +Dim As UInteger n, sum +Dim As ZString Ptr ans + +ReDim rooted(max_n), unrooted(max_n) +For n = 0 To max_n + rooted(n) = Allocate(Len(__mpz_struct)) : Mpz_init( rooted(n)) + unrooted(n) = Allocate(Len(__mpz_struct)) : Mpz_init(unrooted(n)) +Next +For n = 0 To 1 + mpz_set_ui( rooted(n), 1) + mpz_set_ui(unrooted(n), 1) +Next + +ReDim c(branch -1) +For n = 0 To branch -1 + c(n) = Allocate(Len(__mpz_struct)) : Mpz_init(c(n)) +Next + +cnt = Allocate(Len(__mpz_struct)) : Mpz_init_set_ui(cnt, 1) +tmp = Allocate(Len(__mpz_struct)) : Mpz_init(tmp) + +sum = 1 +For n = 1 To max_n + tree(0, n, n, sum, cnt) + bicenter(n) + 'gmp_printf("%d: %Zd"+Chr(13)+Chr(10), n, unrooted(n)) + ans = Mpz_get_str (0, 10, unrooted(n)) + Print Using "###: "; n; : Print *ans +Next + +For n = 0 To max_n + mpz_Clear( rooted(n)) + mpz_Clear(unrooted(n)) +Next + +For n = 0 To branch -1 + mpz_clear(c(n)) +Next + +mpz_clear(cnt) +mpz_clear(tmp) + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Paraffins/jq/paraffins-1.jq b/Task/Paraffins/Jq/paraffins-1.jq similarity index 100% rename from Task/Paraffins/jq/paraffins-1.jq rename to Task/Paraffins/Jq/paraffins-1.jq diff --git a/Task/Paraffins/jq/paraffins-2.jq b/Task/Paraffins/Jq/paraffins-2.jq similarity index 100% rename from Task/Paraffins/jq/paraffins-2.jq rename to Task/Paraffins/Jq/paraffins-2.jq diff --git a/Task/Paraffins/Kotlin/paraffins.kotlin b/Task/Paraffins/Kotlin/paraffins.kotlin new file mode 100644 index 0000000000..e9d1ae96b6 --- /dev/null +++ b/Task/Paraffins/Kotlin/paraffins.kotlin @@ -0,0 +1,48 @@ +// version 1.1.4-3 + +import java.math.BigInteger + +const val MAX_N = 250 +const val BRANCHES = 4 + +val rooted = Array(MAX_N + 1) { if (it < 2) BigInteger.ONE else BigInteger.ZERO } +val unrooted = Array(MAX_N + 1) { if (it < 2) BigInteger.ONE else BigInteger.ZERO } +val c = Array(BRANCHES) { BigInteger.ZERO } + +fun tree(br: Int, n: Int, l: Int, s: Int, cnt: BigInteger) { + var sum = s + for (b in (br + 1)..BRANCHES) { + sum += n + if (sum > MAX_N || (l * 2 >= sum && b >= BRANCHES)) return + + var tmp = rooted[n] + if (b == br + 1) { + c[br] = tmp * cnt + } + else { + val diff = (b - br).toLong() + c[br] *= tmp + BigInteger.valueOf(diff - 1L) + c[br] /= BigInteger.valueOf(diff) + } + + if (l * 2 < sum) unrooted[sum] += c[br] + if (b < BRANCHES) rooted[sum] += c[br] + for (m in n - 1 downTo 1) tree(b, m, l, sum, c[br]) + } +} + +fun bicenter(s: Int) { + if ((s and 1) == 0) { + var tmp = rooted[s / 2] + tmp *= tmp + BigInteger.ONE + unrooted[s] += tmp.shiftRight(1) + } +} + +fun main(args: Array) { + for (n in 1..MAX_N) { + tree(0, n, n, 1, BigInteger.ONE) + bicenter(n) + println("$n: ${unrooted[n]}") + } +} diff --git a/Task/Paraffins/PARI-GP/paraffins-1.pari b/Task/Paraffins/PARI-GP/paraffins-1.pari new file mode 100644 index 0000000000..078903f664 --- /dev/null +++ b/Task/Paraffins/PARI-GP/paraffins-1.pari @@ -0,0 +1,15 @@ +paraffin(p) = +{ + local (P = p+1, R, U = R = Vec([1,1], P)); + + for (n = 1, p, + ((B,n,C,S,l=n) -> my(b,c,i,s); + for (b = 1, 4-B, + if ((s = S + b * n) < P, + c = R[n+1] * C * prod(i = 1, b-1, (R[n+1]+i)/(i+1)); + if (l+l < s, U[s+1] += c); + if (B+b < 4, R[s+1] += c; i = n; while (i--, self()(B+b, i, c, s, l))))) + )(0,n,1,1); + if (n % 2,, U[n+1] += R[n/2+1] * (R[n/2+1]+1)/2); + print([n, U[n+1]])) +} diff --git a/Task/Paraffins/PARI-GP/paraffins-2.pari b/Task/Paraffins/PARI-GP/paraffins-2.pari new file mode 100644 index 0000000000..65bc6fb7fd --- /dev/null +++ b/Task/Paraffins/PARI-GP/paraffins-2.pari @@ -0,0 +1,19 @@ +iso(B,n,C,S,l=n) = +{ + my (b,c,i,s); + + for (b = 1, 4-B, + if ((s = S + b * n) < P, + c = R[n+1] * C * prod(i = 1, b-1, (R[n+1]+i)/(i+1)); + if (l+l < s, U[s+1] += c); + if (B+b < 4, R[s+1] += c; i = n; while (i--, iso(B+b, i, c, s, l))))) +} + +paraffin(p) = +{ + local (P = p+1, R, U = R = Vec([1,1], P)); + + for (n = 1, p, iso(0, n, 1, 1); + if (n % 2,, U[n+1] += R[n/2+1] * (R[n/2+1]+1)/2); + print([n, U[n+1]])) +} diff --git a/Task/Paraffins/Zkl/paraffins.zkl b/Task/Paraffins/Zkl/paraffins.zkl new file mode 100644 index 0000000000..556f62d847 --- /dev/null +++ b/Task/Paraffins/Zkl/paraffins.zkl @@ -0,0 +1,35 @@ +var BN=Import("zklBigNum"); + +const nMax=100, nBranches=4; + +var rooted =(nMax+1).pump(List.createLong(nMax+1).write,BN.fp(0)), + unrooted=(nMax+1).pump(List.createLong(nMax+1).write,BN.fp(0)); +rooted[0]=BN(1); rooted[1]=BN(1); unrooted[0]=BN(1); unrooted[1]=BN(1); + +fcn tree(br,n,l,inSum,cnt){ + var c=(nBranches).pump(List().write,0); // happens only once + + sum := inSum; + foreach b in ([br + 1 .. nBranches]){ + sum += n; + if (sum > nMax or (l * 2 >= sum and b >= nBranches)) return(); + if (b == br + 1) c[br] = rooted[n] * cnt; // -->BigInt + else{ + c[br].mul(rooted[n] + b - br - 1); + c[br].div(b - br); + } + if (l * 2 < sum) unrooted[sum].add(c[br]); + if (b < nBranches) rooted[sum].add(c[br]); + foreach m in ([n-1 .. 1,-1]) { tree(b, m, l, sum, c[br]); } + } +} + +fcn bicenter(s){ + if (s.isEven) unrooted[s].add(rooted[s / 2] * (rooted[s / 2] + 1) / 2); +} + +foreach n in ([1 .. nMax]){ + tree(0, n, n, 1, BN(1)); + bicenter(n); + println(n, ": ", unrooted[n]); +} diff --git a/Task/Parallel-calculations/Fortran/parallel-calculations.f b/Task/Parallel-calculations/Fortran/parallel-calculations.f new file mode 100644 index 0000000000..54b9a9072d --- /dev/null +++ b/Task/Parallel-calculations/Fortran/parallel-calculations.f @@ -0,0 +1,54 @@ +program Primes + + use ISO_FORTRAN_ENV + + implicit none + + integer(int64), dimension(7) :: data = (/2099726827, 15780709, 1122725370, 15808973, 576460741, 12878611, 12757923/) + integer(int64), dimension(100) :: outprimes + integer(int64) :: largest_factor = 0, largest = 0, minim = 0, val = 0 + integer(int16) :: count = 0, OMP_GET_THREAD_NUM + + call omp_set_num_threads(4); + !$omp parallel do private(val,outprimes,count) shared(data,largest_factor,largest) + do val = 1, 7 + outprimes = 0 + call find_factors(data(val), outprimes, count) + minim = minval(outprimes(1:count)) + if (minim > largest_factor) then + largest_factor = minim + largest = data(val) + end if + write(*, fmt = '(A7,i0,A2,i12,100i12)') 'Thread ', OMP_GET_THREAD_NUM(), ': ', data(val), outprimes(1:count) + end do + !$omp end parallel do + + write(*, fmt = '(i0,A26,i0)') largest, ' have the Largest factor: ', largest_factor + + return + +contains + + subroutine find_factors(n, d, count) + integer(int64), intent(in) :: n + integer(int64), dimension(:), intent(out) :: d + integer(int16), intent(out) :: count + integer(int16) :: i + integer(int64) :: div, next, rest + + i = 1 + div = 2; next = 3; rest = n + + do while (rest /= 1) + do while (mod(rest, div) == 0) + d(i) = div + i = i + 1 + rest = rest / div + end do + div = next + next = next + 2 + end do + count = i - 1 + end subroutine find_factors + +end program Primes diff --git a/Task/Parallel-calculations/OoRexx/parallel-calculations-1.rexx b/Task/Parallel-calculations/OoRexx/parallel-calculations-1.rexx new file mode 100644 index 0000000000..0dae3d42ae --- /dev/null +++ b/Task/Parallel-calculations/OoRexx/parallel-calculations-1.rexx @@ -0,0 +1,15 @@ +/* Concurrency in ooRexx. Example of early reply */ +object1 = .example~new +object2 = .example~new +say object1~primes(1,11111111111,11111111114) +say object2~primes(2,11111111111,11111111114) +say "Main ended at" time() +exit +::class example +::method primes +use arg which,bot,top +reply "Start primes"which':' time() +Select + When which=1 Then Call pd1 bot top + When which=2 Then Call pd2 bot top + End diff --git a/Task/Parallel-calculations/OoRexx/parallel-calculations-2.rexx b/Task/Parallel-calculations/OoRexx/parallel-calculations-2.rexx new file mode 100644 index 0000000000..a741e30dcc --- /dev/null +++ b/Task/Parallel-calculations/OoRexx/parallel-calculations-2.rexx @@ -0,0 +1,45 @@ +/*PD1 REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/ +Call Time 'R' +numeric digits 1000 /*handle thousand digits for the powers*/ +parse arg bot top step base add /*get optional arguments from the C.L. */ +if bot=='' then do; bot=1; top=100; end /*no BOT given? Then use the default.*/ +if top=='' then top=bot /* " TOP? " " " " " */ +if step=='' then step= 1 /* " STEP? " " " " " */ +if add =='' then add= -1 /* " ADD? " " " " " */ +tell= top>0; top=abs(top) /*if TOP is negative, suppress displays*/ +w=length(top) /*get maximum width for aligned display*/ +if base\=='' then w=length(base**top) /*will be testing powers of two later? */ +commat.=left('', 7); commat.0="{unity}"; commat.1='[prime]' /*some literals: pad; prime (or not).*/ +numeric digits max(9, w+1) /*maybe increase the digits precision. */ +hash=0 /*hash: is the number of primes found. */ + do n=bot to top by step /*process a single number or a range.*/ + ?=n; if base\=='' then ?=base**n + add /*should we perform a "Mercenne" test? */ + pf=factr(?); f=words(pf) /*get prime factors; number of factors.*/ + if f==1 then hash=hash+1 /*Is N prime? Then bump prime counter.*/ + if tell then say right(?,w) right('('f")",9) 'prime factors: ' commat.f pf + end /*n*/ +say +ps= 'primes'; if p==1 then ps= "prime" /*setup for proper English in sentence.*/ +say right(hash, w+9+1) ps 'found.' /*display the number of primes found. */ +Say 'PD1 took' time('E') 'seconds' +exit /*stick a fork in it, we're all done. */ +/*--------------------------------------------------------------------------------------*/ +factr: procedure; parse arg x 1 d,dollar /*set X, D to argument 1; dollar to null.*/ +if x==1 then return '' /*handle the special case of X = 1. */ + do while x//2==0; dollar=dollar 2; x=x%2; end /*append all the 2 factors of new X.*/ + do while x//3==0; dollar=dollar 3; x=x%3; end /* " " " 3 " " " " */ + do while x//5==0; dollar=dollar 5; x=x%5; end /* " " " 5 " " " " */ + do while x//7==0; dollar=dollar 7; x=x%7; end /* " " " 7 " " " " */ + /* ___*/ +q=1; do while q<=x; q=q*4; end /*these two lines compute integer v X */ +r=0; do while q>1; q=q%4; _=d-r-q; r=r%2; if _>=0 then do; d=_; r=r+q; end; end + + do j=11 by 6 to r /*insure that J isn't divisible by 3.*/ + parse var j '' -1 _ /*obtain the last decimal digit of J. */ + if _\==5 then do while x//j==0; dollar=dollar j; x=x%j; end /*maybe reduce by J. */ + if _ ==3 then iterate /*Is next Y is divisible by 5? Skip.*/ + y=j+2; do while x//y==0; dollar=dollar y; x=x%y; end /*maybe reduce by J. */ + end /*j*/ + /* [?] The dollar list has a leading blank.*/ +if x==1 then return dollar /*Is residual=unity? Then don't append.*/ + return dollar x /*return dollar with appended residual. */ diff --git a/Task/Parallel-calculations/OoRexx/parallel-calculations-3.rexx b/Task/Parallel-calculations/OoRexx/parallel-calculations-3.rexx new file mode 100644 index 0000000000..3c4904c904 --- /dev/null +++ b/Task/Parallel-calculations/OoRexx/parallel-calculations-3.rexx @@ -0,0 +1,50 @@ +/*PD2 REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/ +Call time 'R' +numeric digits 1000 /*handle thousand digits for the powers*/ +parse arg bot top step base add /*get optional arguments from the C.L. */ +if bot=='' then do; bot=1; top=100; end /*no BOT given? Then use the default.*/ +if top=='' then top=bot /* " TOP? " " " " " */ +if step=='' then step= 1 /* " STEP? " " " " " */ +if add =='' then add= -1 /* " ADD? " " " " " */ +tell= top>0; top=abs(top) /*if TOP is negative, suppress displays*/ +w=length(top) /*get maximum width for aligned display*/ +if base\=='' then w=length(base**top) /*will be testing powers of two later? */ +commat.=left('', 7); commat.0="{unity}"; commat.1='[prime]' /*some literals: pad; prime (or not).*/ +numeric digits max(9, w+1) /*maybe increase the digits precision. */ +hash=0 /*hash: is the number of primes found. */ + do n=bot to top by step /*process a single number or a range.*/ + ?=n; if base\=='' then ?=base**n + add /*should we perform a "Mercenne" test? */ + pf=factr(?); f=words(pf) /*get prime factors; number of factors.*/ + if f==1 then hash=hash+1 /*Is N prime? Then bump prime counter.*/ + if tell then say right(?,w) right('('f")",9) 'prime factors: ' commat.f pf + end /*n*/ +say +ps= 'primes'; if p==1 then ps= "prime" /*setup for proper English in sentence.*/ +say right(hash, w+9+1) ps 'found.' /*display the number of primes found. */ +Say 'PD2 took' time('E') 'seconds' +exit /*stick a fork in it, we're all done. */ +/*--------------------------------------------------------------------------------------*/ +factr: procedure; parse arg x 1 d,dollar /*set X, D to argument 1; dollar to null.*/ +if x==1 then return '' /*handle the special case of X = 1. */ + do while x// 2==0; dollar=dollar 2; x=x%2; end /*append all the 2 factors of new X.*/ + do while x// 3==0; dollar=dollar 3; x=x%3; end /* " " " 3 " " " " */ + do while x// 5==0; dollar=dollar 5; x=x%5; end /* " " " 5 " " " " */ + do while x// 7==0; dollar=dollar 7; x=x%7; end /* " " " 7 " " " " */ + do while x//11==0; dollar=dollar 11; x=x%11; end /* " " " 11 " " " " */ /* ?¦¦¦¦ added.*/ + do while x//13==0; dollar=dollar 13; x=x%13; end /* " " " 13 " " " " */ /* ?¦¦¦¦ added.*/ + do while x//17==0; dollar=dollar 17; x=x%17; end /* " " " 17 " " " " */ /* ?¦¦¦¦ added.*/ + do while x//19==0; dollar=dollar 19; x=x%19; end /* " " " 19 " " " " */ /* ?¦¦¦¦ added.*/ + do while x//23==0; dollar=dollar 23; x=x%23; end /* " " " 23 " " " " */ /* ?¦¦¦¦ added.*/ + /* ___*/ +q=1; do while q<=x; q=q*4; end /*these two lines compute integer v X */ +r=0; do while q>1; q=q%4; _=d-r-q; r=r%2; if _>=0 then do; d=_; r=r+q; end; end + + do j=29 by 6 to r /*insure that J isn't divisible by 3.*/ /* ?¦¦¦¦ changed.*/ + parse var j '' -1 _ /*obtain the last decimal digit of J. */ + if _\==5 then do while x//j==0; dollar=dollar j; x=x%j; end /*maybe reduce by J. */ + if _ ==3 then iterate /*Is next Y is divisible by 5? Skip.*/ + y=j+2; do while x//y==0; dollar=dollar y; x=x%y; end /*maybe reduce by J. */ + end /*j*/ + /* [?] The dollar list has a leading blank.*/ +if x==1 then return dollar /*Is residual=unity? Then don't append.*/ + return dollar x /*return dollar with appended residual. */ diff --git a/Task/Parallel-calculations/Zkl/parallel-calculations-1.zkl b/Task/Parallel-calculations/Zkl/parallel-calculations-1.zkl new file mode 100644 index 0000000000..6cfa54619f --- /dev/null +++ b/Task/Parallel-calculations/Zkl/parallel-calculations-1.zkl @@ -0,0 +1,8 @@ +fcn factorize(x,y,z,etc){ + xyzs:=vm.arglist; + fs:=xyzs.apply(factors.strand) // queue up factorizing for x,y,... + .apply("noop") // wait for all threads to finish factoring + .apply(fcn{ (0).min(vm.arglist) }); // find minimum factor for x,y... + [0..].zip(fs).filter(fcn([(n,x)],M){ x==M }.fp1((0).max(fs))) // find max of mins + .apply('wrap([(n,_)]){ xyzs[n] }) // and pluck src from arglist +} diff --git a/Task/Parallel-calculations/Zkl/parallel-calculations-2.zkl b/Task/Parallel-calculations/Zkl/parallel-calculations-2.zkl new file mode 100644 index 0000000000..61694ca21c --- /dev/null +++ b/Task/Parallel-calculations/Zkl/parallel-calculations-2.zkl @@ -0,0 +1,3 @@ +factorize(12757923,12878611,12757923,15808973,15780709,197622519).println(); + // do a bunch so I can watch the system monitor +factorize( (0).pump(5000,List,fcn{(1000).random() }).xplode() ).println(); diff --git a/Task/Parallel-calculations/Zkl/parallel-calculations-3.zkl b/Task/Parallel-calculations/Zkl/parallel-calculations-3.zkl new file mode 100644 index 0000000000..24eab06cac --- /dev/null +++ b/Task/Parallel-calculations/Zkl/parallel-calculations-3.zkl @@ -0,0 +1,13 @@ +fcn factors(n){ // Return a list of factors of n + acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum + if(n==1 or k>maxD) acc.close(); + else{ + 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 + if(n!=m) acc.append(n/m); // opps, missed last factor + else acc; +} diff --git a/Task/Parametric-polymorphism/Fortran/parametric-polymorphism-1.f b/Task/Parametric-polymorphism/Fortran/parametric-polymorphism-1.f new file mode 100644 index 0000000000..551ed0e012 --- /dev/null +++ b/Task/Parametric-polymorphism/Fortran/parametric-polymorphism-1.f @@ -0,0 +1,35 @@ + MODULE SORTSEARCH !Genuflect towards Prof. D. Knuth. + + INTERFACE FIND !Binary chop search, not indexed. + MODULE PROCEDURE + 1 FINDI4, !I: of integers. + 2 FINDF4,FINDF8, !F: of numbers. + 3 FINDTTI2,FINDTTI4 !T: of texts. + END INTERFACE FIND + + CONTAINS + INTEGER FUNCTION FINDI4(THIS,NUMB,N) !Binary chopper. Find i such that THIS = NUMB(i) + USE ASSISTANCE !Only for the trace stuff. + INTENT(IN) THIS,NUMB,N !Imply read-only, but definitely no need for any "copy-back". + INTEGER*4 THIS,NUMB(1:*) !Where is THIS in array NUMB(1:N)? + INTEGER N !The count. In other versions, it is supplied by the index. + INTEGER L,R,P !Fingers. +Chop away. + L = 0 !Establish outer bounds. + R = N + 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 !Aha! Nowhere! And THIS follows NUMB(L). + FINDI4 = -L !Having -L rather than 0 (or other code) might be of interest. + RETURN !Finished. + END IF !So much for exhaustion. + P = P + L !Convert from offset to probe point. + IF (THIS - NUMB(P)) 3,4,2 !Compare to the probe point. + 2 L = P !Shift the left bound up: THIS follows NUMB(P). + GO TO 1 !Another chop. + 3 R = P !Shift the right bound down: THIS precedes NUMB(P). + GO TO 1 !Try again. +Caught it! THIS = NUMB(P) + 4 FINDI4 = P !So, THIS is found, here! + END FUNCTION FINDI4 !On success, THIS = NUMB(FINDI4); no fancy index here... + + END MODULE SORTSEARCH diff --git a/Task/Parametric-polymorphism/Fortran/parametric-polymorphism-2.f b/Task/Parametric-polymorphism/Fortran/parametric-polymorphism-2.f new file mode 100644 index 0000000000..972f70a026 --- /dev/null +++ b/Task/Parametric-polymorphism/Fortran/parametric-polymorphism-2.f @@ -0,0 +1,6 @@ + TYPE STUFF + INTEGER CODE !A key number. + CHARACTER*6 NAME !Associated data. + INTEGER THIS !etc. + END TYPE STUFF + TYPE(STUFF) TABLE(600) !An array of such entries. diff --git a/Task/Parametric-polymorphism/Kotlin/parametric-polymorphism.kotlin b/Task/Parametric-polymorphism/Kotlin/parametric-polymorphism.kotlin new file mode 100644 index 0000000000..6a99fcedd5 --- /dev/null +++ b/Task/Parametric-polymorphism/Kotlin/parametric-polymorphism.kotlin @@ -0,0 +1,24 @@ +// version 1.0.6 + +class BinaryTree(var value: T) { + var left : BinaryTree? = null + var right: BinaryTree? = null + + fun map(f: (T) -> U): BinaryTree { + val tree = BinaryTree(f(value)) + if (left != null) tree.left = left?.map(f) + if (right != null) tree.right = right?.map(f) + return tree + } + + fun showTopThree() = "(${left?.value}, $value, ${right?.value})" +} + +fun main(args: Array) { + val b = BinaryTree(6) + b.left = BinaryTree(5) + b.right = BinaryTree(7) + println(b.showTopThree()) + val b2 = b.map { it * 10.0 } + println(b2.showTopThree()) +} diff --git a/Task/Parametric-polymorphism/Phix/parametric-polymorphism-1.phix b/Task/Parametric-polymorphism/Phix/parametric-polymorphism-1.phix new file mode 100644 index 0000000000..a0b3b7835f --- /dev/null +++ b/Task/Parametric-polymorphism/Phix/parametric-polymorphism-1.phix @@ -0,0 +1 @@ +?sort(shuffle({5,"oranges",6,"apples",7})) diff --git a/Task/Parametric-polymorphism/Phix/parametric-polymorphism-2.phix b/Task/Parametric-polymorphism/Phix/parametric-polymorphism-2.phix new file mode 100644 index 0000000000..a1fa3dd88d --- /dev/null +++ b/Task/Parametric-polymorphism/Phix/parametric-polymorphism-2.phix @@ -0,0 +1,39 @@ +enum data, left, right + +function tmap(sequence tree, integer rid) + tree[data] = call_func(rid,{tree[data]}) + if tree[left]!=null then tree[left] = tmap(tree[left],rid) end if + if tree[right]!=null then tree[right] = tmap(tree[right],rid) end if + return tree +end function + +function newnode(object v) + return {v,null,null} +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) + + root[right] = newnode(1.20) + root[right][left] = newnode(1.21) + root[right][right] = newnode(1.22) + + -- Now the tree has seven nodes. + + -- Show the whole tree. + ppOpt({pp_Nest,2}) + pp(root) + + -- Modify the whole tree. + root = tmap(root,routine_id("add10")) + + -- Show the whole tree again. + pp(root) +end procedure +main() diff --git a/Task/Parametric-polymorphism/REXX/parametric-polymorphism.rexx b/Task/Parametric-polymorphism/REXX/parametric-polymorphism.rexx index 7b7940f0bf..bad78b141a 100644 --- a/Task/Parametric-polymorphism/REXX/parametric-polymorphism.rexx +++ b/Task/Parametric-polymorphism/REXX/parametric-polymorphism.rexx @@ -1,35 +1,35 @@ -/*REXX program demonstrates a method of parametric polymorphism in REXX.*/ -call newRoot 1.00, 3 /*new root and indicate 3 stems. */ - /* [↓] no need to label the stems*/ -call addStem 1.10 /*new stem and its initial value.*/ -call addStem 1.11 /* " " " " " " */ -call addStem 1.12 /* " " " " " " */ -call addStem 1.20 /* " " " " " " */ -call addStem 1.21 /* " " " " " " */ -call addStem 1.22 /* " " " " " " */ -call sayNodes /*display nicely formatted values*/ -call modRoot 50 /*MOD will add 50 to all stems. */ -call sayNodes /*display nicely formatted values*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────MODROOT─────────────────────────────*/ -modRoot: do j=1 for nodes /*traipse through all the nodes. */ - do k=1 for stems; _=root.j.k; ?=datatype(_,'N') - if ? then root.j.k=_+arg(1) /*can stem be added to?*/ - end /*k*/ /* [↑] only add if it's numeric.*/ - end /*j*/ -return -/*──────────────────────────────────NEWROOT─────────────────────────────*/ -newRoot: stems=arg(2); nodes=-1; /*set NODES to a kind of "null". */ -call addStem copies('─',9); call addStem arg(1) -return -/*──────────────────────────────────SAYNODES────────────────────────────*/ -sayNodes: say; do j=0 to nodes; _= /*each node gets shown*/ - do k=1 for stems; _=_ right(root.j.k,9); end /*k*/ - say substr(_,2) /*ignore the 1st blank*/ +/*REXX program demonstrates (with displays) a method of parametric polymorphism in REXX.*/ +call newRoot 1.00, 3 /*new root, and also indicate 3 stems.*/ + /* [↓] no need to label the stems. */ +call addStem 1.10 /*a new stem and its initial value. */ +call addStem 1.11 /*" " " " " " " */ +call addStem 1.12 /*" " " " " " " */ +call addStem 1.20 /*" " " " " " " */ +call addStem 1.21 /*" " " " " " " */ +call addStem 1.22 /*" " " " " " " */ + call sayNodes /*display some nicely formatted values.*/ +call modRoot 50 /*modRoot will add fifty to all stems. */ + call sayNodes /*display some nicely formatted values.*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +addStem: nodes=nodes+1; do j=1 for stems; root.nodes.j=arg(1); end; return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +modRoot: do j=1 for nodes /*traipse through all the defined nodes*/ + do k=1 for stems + if datatype(root.j.k, 'N') then root.j.k=root.j.k + arg(1) /*bias.*/ + end /*k*/ /* [↑] only add if numeric stem value.*/ + end /*j*/ + return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +newRoot: stems=arg(2); nodes= -1 /*set NODES to a kind of "null". */ + call addStem copies('═', 9); call addStem arg(1) + return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +sayNodes: say; do j=0 to nodes; _= /*ensure each of the nodes gets shown. */ + do k=1 for stems; _=_ right(root.j.k, 9) + end /*k*/ + say substr(_, 2) /*ignore the first (leading) blank. */ end /*j*/ -say left('', stems*9+stems) || '('nodes" nodes)" /*also show # of nodes*/ -return -/*──────────────────────────────────ADDSTEM─────────────────────────────*/ -addStem: nodes=nodes+1; do j=1 for stems; root.nodes.j=arg(1); end /*j*/ -return + say left('', stems*11) || '('nodes" nodes)" /*also show number of nodes.*/ + return diff --git a/Task/Parametrized-SQL-statement/C/parametrized-sql-statement.c b/Task/Parametrized-SQL-statement/C/parametrized-sql-statement.c new file mode 100644 index 0000000000..14110552c4 --- /dev/null +++ b/Task/Parametrized-SQL-statement/C/parametrized-sql-statement.c @@ -0,0 +1,114 @@ +#include +#include +#include + +static const char* db_file = ":memory:"; // Create an in-memory database. + +void check_error(int result_code, sqlite3 *db); +int select_callback(void* data, int column_count, char** columns, char** column_names); + +int main(void) { + sqlite3 *db; + int result_code; + char *sql; + char *insert_statements[4]; + sqlite3_stmt *compiled_statement; + int i; + + // Open the database. + result_code = sqlite3_open(db_file, &db); + check_error(result_code, db); + + // Create the players table in the database. + sql = "create table players(" + "id integer primary key asc, " + "name text, " + "score real, " + "active integer, " // Store the bool value as integer (see https://sqlite.org/datatype3.html chapter 2.1). + "jerseyNum integer);"; + result_code = sqlite3_exec(db, sql, NULL, NULL, NULL); + check_error(result_code, db); + + // Insert some values into the players table. + insert_statements[0] = "insert into players (name, score, active, jerseyNum) " + "values ('Roethlisberger, Ben', 94.1, 1, 7);"; + insert_statements[1] = "insert into players (name, score, active, jerseyNum) " + "values ('Smith, Alex', 85.3, 1, 11);"; + insert_statements[2] = "insert into players (name, score, active, jerseyNum) " + "values ('Manning, Payton', 96.5, 0, 18);"; + insert_statements[3] = "insert into players (name, score, active, jerseyNum) " + "values ('Doe, John', 15, 0, 99);"; + + for (i=0; i<4; i++) { + result_code = sqlite3_exec(db, insert_statements[i], NULL, NULL, NULL); + check_error(result_code, db); + } + + // Display the contents of the players table. + printf("Before update:\n"); + sql = "select * from players;"; + result_code = sqlite3_exec(db, sql, select_callback, NULL, NULL); + check_error(result_code, db); + + // Prepare the parametrized SQL statement to update player #99. + sql = "update players set name=?, score=?, active=? where jerseyNum=?;"; + result_code = sqlite3_prepare_v2(db, sql, -1, &compiled_statement, NULL); + check_error(result_code, db); + + // Bind the values to the parameters (see https://sqlite.org/c3ref/bind_blob.html). + result_code = sqlite3_bind_text(compiled_statement, 1, "Smith, Steve", -1, NULL); + check_error(result_code, db); + result_code = sqlite3_bind_double(compiled_statement, 2, 42); + check_error(result_code, db); + result_code = sqlite3_bind_int(compiled_statement, 3, 1); + check_error(result_code, db); + result_code = sqlite3_bind_int(compiled_statement, 4, 99); + check_error(result_code, db); + + // Evaluate the prepared SQL statement. + result_code = sqlite3_step(compiled_statement); + if (result_code != SQLITE_DONE) { + printf("Error #%d: %s\n", result_code, sqlite3_errmsg(db)); + sqlite3_close(db); + return result_code; + } + + // Destroy the prepared statement object. + result_code = sqlite3_finalize(compiled_statement); + check_error(result_code, db); + + // Display the contents of the players table. + printf("After update:\n"); + sql = "select * from players;"; + result_code = sqlite3_exec(db, sql, select_callback, NULL, NULL); + check_error(result_code, db); + + // Close the database connection. + sqlite3_close(db); + + return EXIT_SUCCESS; +} + +/* + Checks the result code from an SQLite operation. + If it contains an error code then this function prints the error message, + closes the database and exits. +*/ +void check_error(int result_code, sqlite3 *db) { + if (result_code != SQLITE_OK) { + printf("Error #%d: %s\n", result_code, sqlite3_errmsg(db)); + sqlite3_close(db); + exit(result_code); + } +} + +/* This callback function prints the results of the select statement. */ +int select_callback(void* data, int column_count, char** columns, char** column_names) { + int i; + + for (i=0; i SQLITE_OK then + begin + writeln(format('Error #%d: %s', [ResultCode, sqlite3_errmsg(db)])); + sqlite3_close(DB); + halt(ResultCode); + end; +end; + +{ SelectCallback + + This callback function prints the results of the select statement.} + +function SelectCallback(Data: pointer; ColumnCount: longint; Columns: PPChar; ColumnNames: PPChar):longint; cdecl; +var + i :longint; + col :PPChar; +begin + col := Columns; + for i:=0 to ColumnCount-1 do + begin + write(col^); // Print the current column value. + inc(col); // Advance the pointer. + if i<>ColumnCount-1 then write(' | '); + end; + writeln; +end; + +begin + // Open the database. + ResultCode := sqlite3_open(DB_FILE, @DB); + CheckError(ResultCode, DB); + + // Create the players table in the database. + SQL := 'create table players(' + + 'id integer primary key asc, ' + + 'name text, ' + + 'score real, ' + + 'active integer, ' + // Store the bool value as integer (see https://sqlite.org/datatype3.html chapter 2.1). + 'jerseyNum integer);'; + ResultCode := sqlite3_exec(DB, SQL, nil, nil, nil); + CheckError(ResultCode, DB); + + // Insert some values into the players table. + InsertStatements[1] := 'insert into players (name, score, active, jerseyNum) ' + + 'values (''Roethlisberger, Ben'', 94.1, 1, 7);'; + InsertStatements[2] := 'insert into players (name, score, active, jerseyNum) ' + + 'values (''Smith, Alex'', 85.3, 1, 11);'; + InsertStatements[3] := 'insert into players (name, score, active, jerseyNum) ' + + 'values (''Manning, Payton'', 96.5, 0, 18);'; + InsertStatements[4] := 'insert into players (name, score, active, jerseyNum) ' + + 'values (''Doe, John'', 15, 0, 99);'; + + for i:=1 to 4 do + begin + ResultCode := sqlite3_exec(DB, InsertStatements[i], nil, nil, nil); + CheckError(ResultCode, DB); + end; + + // Display the contents of the players table. + writeln('Before update:'); + SQL := 'select * from players;'; + ResultCode := sqlite3_exec(DB, SQL, @SelectCallback, nil, nil); + CheckError(ResultCode, DB); + + // Prepare the parametrized SQL statement to update player #99. + SQL := 'update players set name=?, score=?, active=? where jerseyNum=?;'; + ResultCode := sqlite3_prepare_v2(DB, SQL, -1, @CompiledStatement, nil); + CheckError(ResultCode, DB); + + // Bind the values to the parameters (see https://sqlite.org/c3ref/bind_blob.html). + ResultCode := sqlite3_bind_text(CompiledStatement, 1, PChar('Smith, Steve'), -1, nil); + CheckError(ResultCode, DB); + ResultCode := sqlite3_bind_double(CompiledStatement, 2, 42); + CheckError(ResultCode, DB); + ResultCode := sqlite3_bind_int(CompiledStatement, 3, 1); + CheckError(ResultCode, DB); + ResultCode := sqlite3_bind_int(CompiledStatement, 4, 99); + CheckError(ResultCode, DB); + + // Evaluate the prepared SQL statement. + ResultCode := sqlite3_step(CompiledStatement); + if ResultCode <> SQLITE_DONE then + begin + writeln(format('Error #%d: %s', [ResultCode, sqlite3_errmsg(db)])); + sqlite3_close(DB); + halt(ResultCode); + end; + + // Destroy the prepared statement object. + ResultCode := sqlite3_finalize(CompiledStatement); + CheckError(ResultCode, DB); + + // Display the contents of the players table. + writeln('After update:'); + SQL := 'select * from players;'; + ResultCode := sqlite3_exec(DB, SQL, @SelectCallback, nil, nil); + CheckError(ResultCode, DB); + + // Close the database connection. + sqlite3_close(db); +end. diff --git a/Task/Parametrized-SQL-statement/SQL/parametrized-sql-statement.sql b/Task/Parametrized-SQL-statement/SQL/parametrized-sql-statement.sql new file mode 100644 index 0000000000..c1dd901e57 --- /dev/null +++ b/Task/Parametrized-SQL-statement/SQL/parametrized-sql-statement.sql @@ -0,0 +1,40 @@ +-- This works in Oracle's SQL*Plus command line utility + +VARIABLE P_NAME VARCHAR2(20); +VARIABLE P_SCORE NUMBER; +VARIABLE P_ACTIVE VARCHAR2(5); +VARIABLE P_JERSEYNUM NUMBER; + +begin + +:P_NAME := 'Smith, Steve'; +:P_SCORE := 42; +:P_ACTIVE := 'TRUE'; +:P_JERSEYNUM := 99; + +end; +/ + +drop table players; + +create table players +( +NAME VARCHAR2(20), +SCORE NUMBER, +ACTIVE VARCHAR2(5), +JERSEYNUM NUMBER +); + +insert into players values ('No name',0,'FALSE',99); + +commit; + +select * from players; + +UPDATE players + SET name = :P_NAME, score = :P_SCORE, active = :P_ACTIVE + WHERE jerseyNum = :P_JERSEYNUM; + +commit; + +select * from players; diff --git a/Task/Parse-an-IP-Address/Kotlin/parse-an-ip-address.kotlin b/Task/Parse-an-IP-Address/Kotlin/parse-an-ip-address.kotlin new file mode 100644 index 0000000000..eba1d53d00 --- /dev/null +++ b/Task/Parse-an-IP-Address/Kotlin/parse-an-ip-address.kotlin @@ -0,0 +1,118 @@ +// version 1.1.3 + +import java.math.BigInteger + +enum class AddressSpace { IPv4, IPv6, Invalid } + +data class IPAddressComponents( + val address: BigInteger, + val addressSpace: AddressSpace, + val port: Int // -1 denotes 'not specified' +) + +val INVALID = IPAddressComponents(BigInteger.ZERO, AddressSpace.Invalid, 0) + +fun ipAddressParse(ipAddress: String): IPAddressComponents { + var addressSpace = AddressSpace.IPv4 + var ipa = ipAddress.toLowerCase() + var port = -1 + var trans = false + + if (ipa.startsWith("::ffff:") && '.' in ipa) { + addressSpace = AddressSpace.IPv6 + trans = true + ipa = ipa.drop(7) + } + else if (ipa.startsWith("[::ffff:") && '.' in ipa) { + addressSpace = AddressSpace.IPv6 + trans = true + ipa = ipa.drop(8).replace("]", "") + } + val octets = ipa.split('.').reversed().toTypedArray() + var address = BigInteger.ZERO + if (octets.size == 4) { + val split = octets[0].split(':') + if (split.size == 2) { + val temp = split[1].toIntOrNull() + if (temp == null || temp !in 0..65535) return INVALID + port = temp + octets[0] = split[0] + } + + for (i in 0..3) { + val num = octets[i].toLongOrNull() + if (num == null || num !in 0..255) return INVALID + val bigNum = BigInteger.valueOf(num) + address = address.or(bigNum.shiftLeft(i * 8)) + } + + if (trans) address += BigInteger("ffff00000000", 16) + } + else if (octets.size == 1) { + addressSpace = AddressSpace.IPv6 + if (ipa[0] == '[') { + ipa = ipa.drop(1) + val split = ipa.split("]:") + if (split.size != 2) return INVALID + val temp = split[1].toIntOrNull() + if (temp == null || temp !in 0..65535) return INVALID + port = temp + ipa = ipa.dropLast(2 + split[1].length) + } + val hextets = ipa.split(':').reversed().toMutableList() + val len = hextets.size + + if (ipa.startsWith("::")) + hextets[len - 1] = "0" + else if (ipa.endsWith("::")) + hextets[0] = "0" + + if (ipa == "::") hextets[1] = "0" + if (len > 8 || (len == 8 && hextets.any { it == "" }) || hextets.count { it == "" } > 1) + return INVALID + if (len < 8) { + var insertions = 8 - len + for (i in 0..7) { + if (hextets[i] == "") { + hextets[i] = "0" + while (insertions-- > 0) hextets.add(i, "0") + break + } + } + } + for (j in 0..7) { + val num = hextets[j].toLongOrNull(16) + if (num == null || num !in 0x0..0xFFFF) return INVALID + val bigNum = BigInteger.valueOf(num) + address = address.or(bigNum.shiftLeft(j * 16)) + } + } + else return INVALID + + return IPAddressComponents(address, addressSpace, port) +} + +fun main(args: Array) { + val ipas = listOf( + "127.0.0.1", + "127.0.0.1:80", + "::1", + "[::1]:80", + "2605:2700:0:3::4713:93e3", + "[2605:2700:0:3::4713:93e3]:80", + "::ffff:192.168.173.22", + "[::ffff:192.168.173.22]:80", + "1::", + "::", + "256.0.0.0", + "::ffff:127.0.0.0.1" + ) + for (ipa in ipas) { + val (address, addressSpace, port) = ipAddressParse(ipa) + println("IP address : $ipa") + println("Address : ${"%X".format(address)}") + println("Address Space : $addressSpace") + println("Port : ${if (port == -1) "not specified" else port.toString()}") + println() + } +} diff --git a/Task/Parse-an-IP-Address/Python/parse-an-ip-address-1.py b/Task/Parse-an-IP-Address/Python/parse-an-ip-address-1.py new file mode 100644 index 0000000000..63ce80b055 --- /dev/null +++ b/Task/Parse-an-IP-Address/Python/parse-an-ip-address-1.py @@ -0,0 +1,27 @@ +from ipaddress import ip_address +from urllib.parse import urlparse + +tests = [ + "127.0.0.1", + "127.0.0.1:80", + "::1", + "[::1]:80", + "::192.168.0.1", + "2605:2700:0:3::4713:93e3", + "[2605:2700:0:3::4713:93e3]:80" ] + +def parse_ip_port(netloc): + try: + ip = ip_address(netloc) + port = None + except ValueError: + parsed = urlparse('//{}'.format(netloc)) + ip = ip_address(parsed.hostname) + port = parsed.port + return ip, port + +for address in tests: + ip, port = parse_ip_port(address) + hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip)) + print("{:39s} {:>32s} IPv{} port={}".format( + str(ip), hex_ip, ip.version, port )) diff --git a/Task/Parse-an-IP-Address/Python/parse-an-ip-address.py b/Task/Parse-an-IP-Address/Python/parse-an-ip-address-2.py similarity index 100% rename from Task/Parse-an-IP-Address/Python/parse-an-ip-address.py rename to Task/Parse-an-IP-Address/Python/parse-an-ip-address-2.py diff --git a/Task/Parse-an-IP-Address/REXX/parse-an-ip-address-1.rexx b/Task/Parse-an-IP-Address/REXX/parse-an-ip-address-1.rexx index 2220692326..edaec90458 100644 --- a/Task/Parse-an-IP-Address/REXX/parse-an-ip-address-1.rexx +++ b/Task/Parse-an-IP-Address/REXX/parse-an-ip-address-1.rexx @@ -1,39 +1,38 @@ -/*REXX program to parse an IP address into ──► IPv4 or IPv6 format, port*/ - say center('input IP address' ,30), - center('hex IP address' ,32), - center('decimal IP address' ,39) 'space port' - _='─' - say copies(_,30) copies(_,32) copies(_,39) copies(_,5) copies(_,5) -call IP_parse 127.0.0.1 /*this IP doesn't need quotes. */ +/*REXX program parses an IP address into ──► IPv4 or IPv6 format, optional pport.*/ +_="_"; say center('input IP address' , 30), + center('hex IP address' , 32), + center('decimal IP address' , 39) 'space port' + say copies(_, 30) copies(_, 32) copies(_, 39) copies(_, 5) copies(_, 5) +call IP_parse 127.0.0.1 /*this simple IP doesn't need quotes.*/ call IP_parse '127.0.0.1:80' call IP_parse '::1' call IP_parse '[::1]:80' call IP_parse '2605:2700:0:3::4713:93e3' call IP_parse '[2605:2700:0:3::4713:93e3]:80' -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────IP_parse subroutine─────────────────*/ -IP_parse: procedure; parse arg a .; hx=; @.=; numeric digits 50 -dot=pos('.',a)\==0 /*see if there is a dot present. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +IP_parse: procedure; parse arg a .; hx=; @.=; numeric digits 50 + dot=pos(.,a)\==0 /*see if there is a dot present in IP. */ -if dot then do; parse var a @.1 '.' @.2 "." @.3 '.' @.4 ":" port - do j=1 for 4; hx=hx || d2x(@.j,2) - end /*j*/ - end /*if dot*/ - else do; parse var a pureA ']:' port - _=space(translate(pureA,,'[]'),0) /*remove brackets*/ - parse var _ x '::' y - do L=1 until x=='' /*get left side.*/ - parse var x @.L ':' x - end /*L*/ - y=reverse(y) - do r=8 by -1 /*get right side.*/ - parse var y z ':' y; if z=='' then leave - @.r=reverse(z) - end /*r*/ + if dot then do; parse var a @.1 '.' @.2 "." @.3 '.' @.4 ":" port + do j=1 for 4; hx=hx || d2x(@.j, 2) + end /*j*/ + end + else do; parse var a pureA ']:' port + _=space( translate( pureA, , '[]'), 0) /*remove brackets.*/ + parse var _ x '::' y + do L=1 until x=='' /*get left side. */ + parse var x @.L ':' x + end /*L*/ + y=reverse(y) + do r=8 by -1 /*get right side. */ + parse var y z ':' y; if z=='' then leave + @.r=reverse(z) + end /*r*/ - do k=1 for 8; hx=hx || right(word(@.k 0, 1), 4, 0) - end /*k*/ - end /*else dot*/ + do k=1 for 8; hx=hx || right( word(@.k 0, 1), 4, 0) + end /*k*/ + end -say left(a,30) right(hx,32) right(x2d(hx),39) ' IPv'||(6-2*dot) right(port,5) -return + say left(a,30) right(hx,32) right(x2d(hx),39) ' IPv' || (6-2*dot) right(port,5) + return diff --git a/Task/Parsing-RPN-calculator-algorithm/Kotlin/parsing-rpn-calculator-algorithm.kotlin b/Task/Parsing-RPN-calculator-algorithm/Kotlin/parsing-rpn-calculator-algorithm.kotlin new file mode 100644 index 0000000000..37941ae934 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Kotlin/parsing-rpn-calculator-algorithm.kotlin @@ -0,0 +1,40 @@ +// version 1.1.2 + +fun rpnCalculate(expr: String) { + if (expr.isEmpty()) throw IllegalArgumentException("Expresssion cannot be empty") + println("For expression = $expr\n") + println("Token Action Stack") + val tokens = expr.split(' ').filter { it != "" } + val stack = mutableListOf() + for (token in tokens) { + val d = token.toDoubleOrNull() + if (d != null) { + stack.add(d) + println(" $d Push num onto top of stack $stack") + } + else if ((token.length > 1) || (token !in "+-*/^")) { + throw IllegalArgumentException("$token is not a valid token") + } + else if (stack.size < 2) { + throw IllegalArgumentException("Stack contains too few operands") + } + else { + val d1 = stack.removeAt(stack.lastIndex) + val d2 = stack.removeAt(stack.lastIndex) + stack.add(when (token) { + "+" -> d2 + d1 + "-" -> d2 - d1 + "*" -> d2 * d1 + "/" -> d2 / d1 + else -> Math.pow(d2, d1) + }) + println(" $token Apply op to top of stack $stack") + } + } + println("\nThe final value is ${stack[0]}") +} + +fun main(args: Array) { + val expr = "3 4 2 * 1 5 - 2 3 ^ ^ / +" + rpnCalculate(expr) +} diff --git a/Task/Parsing-RPN-calculator-algorithm/Lua/parsing-rpn-calculator-algorithm.lua b/Task/Parsing-RPN-calculator-algorithm/Lua/parsing-rpn-calculator-algorithm.lua new file mode 100644 index 0000000000..fe4c77654b --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Lua/parsing-rpn-calculator-algorithm.lua @@ -0,0 +1,52 @@ +local stack = {} +function push( a ) table.insert( stack, 1, a ) end +function pop() + if #stack == 0 then return nil end + return table.remove( stack, 1 ) +end +function writeStack() + for i = #stack, 1, -1 do + io.write( stack[i], " " ) + end + print() +end +function operate( a ) + local s + if a == "+" then + push( pop() + pop() ) + io.write( a .. "\tadd\t" ); writeStack() + elseif a == "-" then + s = pop(); push( pop() - s ) + io.write( a .. "\tsub\t" ); writeStack() + elseif a == "*" then + push( pop() * pop() ) + io.write( a .. "\tmul\t" ); writeStack() + elseif a == "/" then + s = pop(); push( pop() / s ) + io.write( a .. "\tdiv\t" ); writeStack() + elseif a == "^" then + s = pop(); push( pop() ^ s ) + io.write( a .. "\tpow\t" ); writeStack() + elseif a == "%" then + s = pop(); push( pop() % s ) + io.write( a .. "\tmod\t" ); writeStack() + else + push( tonumber( a ) ) + io.write( a .. "\tpush\t" ); writeStack() + end +end +function calc( s ) + local t, a = "", "" + print( "\nINPUT", "OP", "STACK" ) + for i = 1, #s do + a = s:sub( i, i ) + if a == " " then operate( t ); t = "" + else t = t .. a + end + end + if a ~= "" then operate( a ) end + print( string.format( "\nresult: %.13f", pop() ) ) +end +--[[ entry point ]]-- +calc( "3 4 2 * 1 5 - 2 3 ^ ^ / +" ) +calc( "22 11 *" ) diff --git a/Task/Parsing-RPN-calculator-algorithm/OoRexx/parsing-rpn-calculator-algorithm.rexx b/Task/Parsing-RPN-calculator-algorithm/OoRexx/parsing-rpn-calculator-algorithm.rexx new file mode 100644 index 0000000000..fb79704e98 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/OoRexx/parsing-rpn-calculator-algorithm.rexx @@ -0,0 +1,32 @@ +/* ooRexx ************************************************************* +* 10.11.2012 Walter Pachl translated from PL/I via REXX +**********************************************************************/ +fid='rpl.txt' +ex=linein(fid) +Say 'Input:' ex +/* ex=' 3 4 2 * 1 5 - 2 3 ^ ^ / +' */ +Numeric Digits 15 +expr='' +st=.circularqueue~new(100) +Say 'Stack contents:' +do While ex<>'' + Parse Var ex ch +1 ex + expr=expr||ch; + if ch<>' ' then do + If pos(ch,'0123456789')>0 Then /* a digit goes onto stack */ + st~push(ch) + Else Do /* an operator */ + op=st~pull /* get top element */ + select /* and modify the (now) top el*/ + when ch='+' Then st~push(st~pull + op) + when ch='-' Then st~push(st~pull - op) + when ch='*' Then st~push(st~pull * op) + when ch='/' Then st~push(st~pull / op) + when ch='^' Then st~push(st~pull ** op) + end; + Say st~string(' ','L') /* show stack in LIFO order */ + end + end + end +Say 'The reverse polish expression = 'expr +Say 'The evaluated expression = 'st~pull diff --git a/Task/Parsing-RPN-calculator-algorithm/Sidef/parsing-rpn-calculator-algorithm.sidef b/Task/Parsing-RPN-calculator-algorithm/Sidef/parsing-rpn-calculator-algorithm.sidef index f718f32967..0fb10acfae 100644 --- a/Task/Parsing-RPN-calculator-algorithm/Sidef/parsing-rpn-calculator-algorithm.sidef +++ b/Task/Parsing-RPN-calculator-algorithm/Sidef/parsing-rpn-calculator-algorithm.sidef @@ -1,4 +1,4 @@ -var proggie = '3 4 2 * 1 5 - 2 3 ^ ^ / +'; +var proggie = '3 4 2 * 1 5 - 2 3 ^ ^ / +' class RPN(arr=[]) { @@ -10,10 +10,10 @@ class RPN(arr=[]) { method run(p) { p.each_word { |w| - say "#{w} (#{arr})"; + say "#{w} (#{arr})" given (w) { when (/\d/) { - arr << w.to_f + arr << Num(w) } when (<+ - * />) { self.binop(w) @@ -30,4 +30,4 @@ class RPN(arr=[]) { } } -RPN.new.run(proggie); +RPN.new.run(proggie) diff --git a/Task/Parsing-RPN-calculator-algorithm/Sinclair-ZX81-BASIC/parsing-rpn-calculator-algorithm.sinclair b/Task/Parsing-RPN-calculator-algorithm/Sinclair-ZX81-BASIC/parsing-rpn-calculator-algorithm.sinclair new file mode 100644 index 0000000000..3353fec452 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Sinclair-ZX81-BASIC/parsing-rpn-calculator-algorithm.sinclair @@ -0,0 +1,28 @@ + 10 DIM S(5) + 20 LET P=1 + 30 INPUT E$ + 40 LET I=0 + 50 LET I=I+1 + 60 IF E$(I)=" " THEN GOTO 110 + 70 IF I ",stack); + } + println("result: ", stack[0]) +} diff --git a/Task/Parsing-RPN-calculator-algorithm/Zkl/parsing-rpn-calculator-algorithm-2.zkl b/Task/Parsing-RPN-calculator-algorithm/Zkl/parsing-rpn-calculator-algorithm-2.zkl new file mode 100644 index 0000000000..5686946dc3 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Zkl/parsing-rpn-calculator-algorithm-2.zkl @@ -0,0 +1,2 @@ +tests:=T("3 4 2 * 1 5 - 2 3 ^ ^ / +"); +foreach t in (tests) { parseRPN(t) } diff --git a/Task/Parsing-RPN-to-infix-conversion/Python/parsing-rpn-to-infix-conversion.py b/Task/Parsing-RPN-to-infix-conversion/Python/parsing-rpn-to-infix-conversion.py index c6ba5c7acb..80c5641d3c 100644 --- a/Task/Parsing-RPN-to-infix-conversion/Python/parsing-rpn-to-infix-conversion.py +++ b/Task/Parsing-RPN-to-infix-conversion/Python/parsing-rpn-to-infix-conversion.py @@ -1,51 +1,31 @@ -from math import log as ln -from math import sqrt, log, exp, sin, cos, tan, pi, e -from ast import literal_eval - """ >>> # EXAMPLE USAGE ->>> result = rpn_to_infix('3 4 2 * 1 -5 - ln 2 3 ** ** / +', VERBOSE=True) +>>> result = rpn_to_infix('3 4 2 * 1 5 - 2 3 ^ ^ / +', VERBOSE=True) TOKEN STACK 3 ['3'] 4 ['3', '4'] 2 ['3', '4', '2'] * ['3', Node('2','*','4')] 1 ['3', Node('2','*','4'), '1'] --5 ['3', Node('2','*','4'), '1', '-5'] -- ['3', Node('2','*','4'), Node('-5','-','1')] -ln ['3', Node('2','*','4'), Node(Node('-5','-','1'),'ln',None)] -2 ['3', Node('2','*','4'), Node(Node('-5','-','1'),'ln',None), '2'] -3 ['3', Node('2','*','4'), Node(Node('-5','-','1'),'ln',None), '2', '3'] -** ['3', Node('2','*','4'), Node(Node('-5','-','1'),'ln',None), Node('3','**','2')] -** ['3', Node('2','*','4'), Node(Node('3','**','2'),'**',Node(Node('-5','-','1'),'ln',None))] -/ ['3', Node(Node(Node('3','**','2'),'**',Node(Node('-5','-','1'),'ln',None)),'/',Node('2','*','4'))] -+ [Node(Node(Node(Node('3','**','2'),'**',Node(Node('-5','-','1'),'ln',None)),'/',Node('2','*','4')),'+','3')] ->>> result +5 ['3', Node('2','*','4'), '1', '5'] +- ['3', Node('2','*','4'), Node('5','-','1')] +2 ['3', Node('2','*','4'), Node('5','-','1'), '2'] +3 ['3', Node('2','*','4'), Node('5','-','1'), '2', '3'] +^ ['3', Node('2','*','4'), Node('5','-','1'), Node('3','^','2')] +^ ['3', Node('2','*','4'), Node(Node('3','^','2'),'^',Node('5','-','1'))] +/ ['3', Node(Node(Node('3','^','2'),'^',Node('5','-','1')),'/',Node('2','*','4'))] ++ [Node(Node(Node(Node('3','^','2'),'^',Node('5','-','1')),'/',Node('2','*','4')),'+','3')] """ -prec_dict = {'abs':5, 'sqrt':5, 'exp':5, 'log':5, 'ln':5, - 'sin':5, 'cos':5, 'tan':5, - '**':4, '*':3, '/':3, '+':2, '-':2} -assoc_dict = {'abs':0, 'sqrt':0, 'exp':0, 'log':0, 'ln':0, - 'sin':0, 'cos':0, 'tan':0, - '**':1, '*':0, '/':0, '+':0, '-':0} -arity_dict = {'abs':1, 'sqrt':1, 'exp':1, 'log':1, 'ln':1, - 'sin':1, 'cos':1, 'tan':1, - '**':2, '*':2, '/':2, '+':2, '-':2} +prec_dict = {'^':4, '*':3, '/':3, '+':2, '-':2} +assoc_dict = {'^':1, '*':0, '/':0, '+':0, '-':0} class Node: def __init__(self,x,op,y=None): self.precedence = prec_dict[op] self.assocright = assoc_dict[op] - self.arity = arity_dict[op] self.op = op - - if not self.assocright and self > x and \ - isinstance(x, Node) and self.arity == 2: - self.x = x.x - self.y = Node(x.y, x.op, y) - else: - self.x,self.y = x,y + self.x,self.y = x,y def __str__(self): """ @@ -53,7 +33,6 @@ class Node: Building an infix string that looks pretty and evaluates correctly requires more effort. """ - # easy case, Node is unary if self.y == None: return '%s(%s)'%(self.op,str(self.x)) @@ -65,7 +44,6 @@ class Node: (str_y[0] is '-' and self.assocright): str_y = '(%s)'%str_y - # determine right side string and operator str_x = str(self.x) str_op = self.op @@ -80,7 +58,6 @@ class Node: getattr(self.x, 'op', 1) != getattr(self, 'op', 2)): str_x = '(%s)'%str_x - return ' '.join([str_y, str_op, str_x]) def __repr__(self): @@ -100,76 +77,25 @@ class Node: return self.precedence > other.precedence return self.precedence > prec_dict.get(other,9) + def __eq__(self, other): + if isinstance(other, Node): + return self.precedence == other.precedence + return self.precedence > prec_dict.get(other,9) + def rpn_to_infix(s, VERBOSE=False): """ + converts rpn notation to infix notation for string s - "^" are replaced with "**" - - >>> rpn_to_infix('5 4 +') - '5 + 4' - >>> rpn_to_infix('5 -4 +') - '5 - 4' - >>> rpn_to_infix('5 -4 -') - '5 + 4' - >>> rpn_to_infix('5 -4.2 +') - '5 - 4.2' - >>> rpn_to_infix('-4 2 **') - '(-4) ** 2' - >>> rpn_to_infix('x y +') - 'x + y' - >>> rpn_to_infix('x -y +') - 'x - y' - >>> rpn_to_infix('5 4 3 2 ** ** **') - '5 ** 4 ** 3 ** 2' - >>> rpn_to_infix('5 6 ** 7 **') - '(5 ** 6) ** 7' - >>> rpn_to_infix('1 2 3 + -') - '1 - (2 + 3)' - >>> rpn_to_infix('4 3 2 + +') - '4 + 3 + 2' - >>> rpn_to_infix('5 4 3 2 + + +') - '5 + 4 + 3 + 2' - >>> rpn_to_infix('5 4 3 2 * * *') - '5 * 4 * 3 * 2' - >>> rpn_to_infix('5 4 3 2 + - +') - '5 + (4 - (3 + 2))' - >>> rpn_to_infix('3 4 5 * -') - '3 - 4 * 5' - >>> rpn_to_infix('3 4 5 - *') - '(3 - 4) * 5' - >>> rpn_to_infix('4 2 * 1 5 - +') - '4 * 2 + (1 - 5)' - >>> rpn_to_infix('4 2 * 1 5 - 2 ** /') - '4 * 2 / (1 - 5) ** 2' - >>> rpn_to_infix('3 4 2 * 1 5 - 2 3 ** ** / +') - '3 + 4 * 2 / (1 - 5) ** 2 ** 3' - >>> rpn_to_infix('1 2 + 3 4 + ** 5 6 + **') - '((1 + 2) ** (3 + 4)) ** (5 + 6)' - >>> rpn_to_infix('x sin') - 'sin(x)' - >>> rpn_to_infix('5 4 3 2 + sqrt - +') - '5 + (4 - sqrt(3 + 2))' - >>> rpn_to_infix('5 4 3 2 + sqrt ln - +') - '5 + (4 - ln(sqrt(3 + 2)))' - >>> rpn_to_infix('5 sin 4 cos *') - 'sin(5) * cos(4)' - >>> rpn_to_infix('5 4 cos * sin') - 'sin(5 * cos(4))' - >>> rpn_to_infix('3 4 2 * 1 -5 - ln 2 3 ** ** / +') - '3 + 4 * 2 / ln(1 + 5) ** 2 ** 3' """ if VERBOSE : print('TOKEN STACK') stack=[] - for token in s.replace('^','**').split(): + for token in s.replace('^','^').split(): if token in prec_dict: - if arity_dict[token] == 1: - stack.append(Node(stack.pop(),token)) - elif arity_dict[token] == 2: - stack.append(Node(stack.pop(),token,stack.pop())) + stack.append(Node(stack.pop(),token,stack.pop())) else: stack.append(token) @@ -178,36 +104,14 @@ def rpn_to_infix(s, VERBOSE=False): return str(stack[0]) -def rpn_eval(s): - """ - computes the value of an rpn string - - >>> rpn_eval('5 4 +') == eval(rpn_to_infix('5 4 +')) - True - >>> rpn_eval('-4 2 **') == eval(rpn_to_infix('-4 2 **')) - True - >>> round(rpn_eval('3 4 2 * 1 -5 - ln 2 3 ** ** / +'),7) == \ - round(eval(rpn_to_infix('3 4 2 * 1 -5 - ln 2 3 ** ** / +')),7) - True - >>> round(rpn_eval('5 4 3 2 + sqrt ln - +'),7) == \ - round(eval(rpn_to_infix('5 4 3 2 + sqrt ln - +')),7) - True - """ - - stack=[] - for token in s.replace('^','**').split(): - if token in prec_dict: - if arity_dict[token] == 1: - stack.append(literal_eval('%s(%s)'%(token,stack.pop()))) - elif arity_dict[token] == 2: - x,y=stack.pop(),stack.pop() - stack.append(literal_eval('(%s) %s %s'%(y,token,x))) - else: - stack.append(token) - - return stack[0] - -strTest = "3 4 2 * 1 -5 - ln 2 3 ** ** / +" -strResult = rpn_to_infix(strTest) +strTest = "3 4 2 * 1 5 - 2 3 ^ ^ / +" +strResult = rpn_to_infix(strTest, VERBOSE=False) +print ("Input: ",strTest) +print ("Output:",strResult) + +print() + +strTest = "1 2 + 3 4 + ^ 5 6 + ^" +strResult = rpn_to_infix(strTest, VERBOSE=False) print ("Input: ",strTest) print ("Output:",strResult) diff --git a/Task/Parsing-RPN-to-infix-conversion/Sidef/parsing-rpn-to-infix-conversion.sidef b/Task/Parsing-RPN-to-infix-conversion/Sidef/parsing-rpn-to-infix-conversion.sidef index ae74a19d90..b4c6a946cb 100644 --- a/Task/Parsing-RPN-to-infix-conversion/Sidef/parsing-rpn-to-infix-conversion.sidef +++ b/Task/Parsing-RPN-to-infix-conversion/Sidef/parsing-rpn-to-infix-conversion.sidef @@ -1,32 +1,32 @@ func p(pair, prec) { - pair[0] < prec ? "( #{pair[1]} )" : pair[1]; + pair[0] < prec ? "( #{pair[1]} )" : pair[1] } - +  func rpm_to_infix(string) { - say "#{'='*17}\n#{string}"; - var stack = []; + say "#{'='*17}\n#{string}" + var stack = [] string.each_word { |w| if (w ~~ /\d/) { - stack << [9, w.to_f]; + stack << [9, Num(w)] } else { - var y = stack.pop; - var x = stack.pop; + var y = stack.pop + var x = stack.pop given(w) { when ('^') { stack << [4, [p(x,5), w, p(y,4)].join(' ')] } when (<* />) { stack << [3, [p(x,3), w, p(y,3)].join(' ')] } when (<+ ->) { stack << [2, [p(x,2), w, p(y,2)].join(' ')] } } - say stack; + say stack } - }; - '-'*17 -> say; - stack.map{_[1]}; + } + say '-'*17 + stack.map{_[1]} } - +  var tests = [ '3 4 2 * 1 5 - 2 3 ^ ^ / +', '1 2 + 3 4 + ^ 5 6 + ^', -]; - +] +  tests.each { say rpm_to_infix(_).join(' ') } diff --git a/Task/Parsing-RPN-to-infix-conversion/Zkl/parsing-rpn-to-infix-conversion.zkl b/Task/Parsing-RPN-to-infix-conversion/Zkl/parsing-rpn-to-infix-conversion.zkl new file mode 100644 index 0000000000..b5c62547b9 --- /dev/null +++ b/Task/Parsing-RPN-to-infix-conversion/Zkl/parsing-rpn-to-infix-conversion.zkl @@ -0,0 +1,37 @@ +tests:=T("3 4 2 * 1 5 - 2 3 ^ ^ / +","1 2 + 3 4 + ^ 5 6 + ^"); + +var opa=D( + "^",T(4, True), + "*",T(3, False), "/",T(3, False), + "+",T(2, False), "-",T(2, False) ); + +const nPrec = 9; + +foreach t in (tests) { parseRPN(t) } + +fcn parseRPN(e){ + println("\npostfix:", e); + stack:=L(); + foreach tok in (e.split()){ + println("token: ", tok); + opPrec,rAssoc:=opa.find(tok,T(Void,Void)); + if(opPrec){ + rhsPrec,rhsExpr := stack.pop(); + lhsPrec,lhsExpr := stack.pop(); + if(lhsPrec < opPrec or (lhsPrec == opPrec and rAssoc)) + lhsExpr = "(" + lhsExpr + ")"; + lhsExpr += " " + tok + " "; + if(rhsPrec < opPrec or (rhsPrec == opPrec and not rAssoc)){ + lhsExpr += "(" + rhsExpr + ")" + } else + lhsExpr += rhsExpr; + lhsPrec = opPrec; + stack.append(T(lhsPrec,lhsExpr)); + } else + stack.append(T(nPrec, tok)); + foreach f in (stack){ + println(0'| %d "%s"|.fmt(f.xplode())) + } + } + println("infix:", stack[0][1]) +} diff --git a/Task/Parsing-Shunting-yard-algorithm/ALGOL-68/parsing-shunting-yard-algorithm.alg b/Task/Parsing-Shunting-yard-algorithm/ALGOL-68/parsing-shunting-yard-algorithm.alg new file mode 100644 index 0000000000..270c6c270a --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/ALGOL-68/parsing-shunting-yard-algorithm.alg @@ -0,0 +1,78 @@ +BEGIN + # parses s and returns an RPN expression using Dijkstra's "Shunting Yard" algorithm # + # s is expected to contain a valid infix expression containing single-digit numbers and single-character operators # + PROC parse = ( STRING s )STRING: + BEGIN + # add to the output # + PROC output element = ( CHAR c )VOID: + BEGIN + output[ output pos +:= 1 ] := c; + output pos +:= 1 + END # output element # ; + PROC stack op = ( CHAR c )VOID: stack[ stack pos +:= 1 ] := c; + # unstacks and returns the top operator on the stack - stops the program if the stack is empty # + PROC unstack = CHAR: + IF stack pos < 1 THEN + # empty stack # + print( ( "Stack underflow", newline ) ); + stop + ELSE + # still something on the stack to unstack # + CHAR result = stack[ stack pos ]; + stack[ stack pos ] := " "; + stack pos -:= 1; + result + FI # unstack # ; + # returns the priority of the operator o - which must be one of "(", "^", "*", "/", "+" or "-" # + PROC priority of = ( CHAR o )INT: IF o = "(" THEN -1 ELIF o = "^" THEN 4 ELIF o = "*" OR o = "/" THEN 3 ELSE 2 FI; + # returns TRUE if o is a right-associative operator, FALSE otherwise # + PROC right = ( CHAR c )BOOL: c = "^"; + PROC lower or equal priority = ( CHAR c )BOOL: + IF stack pos < 1 THEN FALSE # empty stack # + ELSE priority of( c ) <= priority of( stack[ stack pos ] ) + FI # lower or equal priority # ; + PROC lower priority = ( CHAR c )BOOL: + IF stack pos < 1 THEN FALSE # empty stack # + ELSE priority of( c ) < priority of( stack[ stack pos ] ) + FI # lower priority # ; + # max stack size and output size # + INT max stack = 32; + # stack and output queue # + [ 1 : max stack ]CHAR stack; + [ 1 : max stack ]CHAR output; + FOR c pos TO max stack DO stack[ c pos ] := output[ c pos ] := " " OD; + # stack pointer and output queue pointer # + INT stack pos := 0; + INT output pos := 0; + print( ( "Parsing: ", s, newline ) ); + print( ( "token output stack", newline ) ); + FOR s pos FROM LWB s TO UPB s DO + CHAR c = s[ s pos ]; + IF c /= " " THEN + IF c >= "0" AND c <= "9" THEN output element( c ) + ELIF c = "(" THEN stack op( c ) + ELIF c = ")" THEN + # close bracket - unstack to the matching "(" and unstack the "(" # + WHILE CHAR op char = unstack; + op char /= "(" + DO + output element( op char ) + OD + ELIF right( c ) THEN + # right associative operator # + WHILE lower priority( c ) DO output element( unstack ) OD; + stack op( c ) + ELSE + # must be left associative # + WHILE lower or equal priority( c ) DO output element( unstack ) OD; + stack op( c ) + FI; + print( ( c, " ", output, " ", stack, newline ) ) + FI + OD; + WHILE stack pos >= 1 DO output element( unstack ) OD; + output[ 1 : output pos ] + END # parse # ; + + print( ( "result: ", parse( "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" ), newline ) ) +END diff --git a/Task/Parsing-Shunting-yard-algorithm/C-sharp/parsing-shunting-yard-algorithm.cs b/Task/Parsing-Shunting-yard-algorithm/C-sharp/parsing-shunting-yard-algorithm.cs new file mode 100644 index 0000000000..164827c335 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/C-sharp/parsing-shunting-yard-algorithm.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public class Program +{ + public static void Main() { + string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; + Console.WriteLine(infix.ToPostfix()); + } +} + +public static class ShuntingYard +{ + private static readonly Dictionary operators + = new (string symbol, int precedence, bool rightAssociative) [] { + ("^", 4, true), + ("*", 3, false), + ("/", 3, false), + ("+", 2, false), + ("-", 2, false) + }.ToDictionary(op => op.symbol); + + public static string ToPostfix(this string infix) { + string[] tokens = infix.Split(' '); + var stack = new Stack(); + var output = new List(); + foreach (string token in tokens) { + if (int.TryParse(token, out _)) { + output.Add(token); + Print(token); + } else if (operators.TryGetValue(token, out var op1)) { + while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) { + int c = op1.precedence.CompareTo(op2.precedence); + if (c < 0 || !op1.rightAssociative && c <= 0) { + output.Add(stack.Pop()); + } else { + break; + } + } + stack.Push(token); + Print(token); + } else if (token == "(") { + stack.Push(token); + Print(token); + } else if (token == ")") { + string top = ""; + while (stack.Count > 0 && (top = stack.Pop()) != "(") { + output.Add(top); + } + if (top != "(") throw new ArgumentException("No matching left parenthesis."); + Print(token); + } + } + while (stack.Count > 0) { + var top = stack.Pop(); + if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis."); + output.Add(top); + } + Print("pop"); + return string.Join(" ", output); + + //Yikes! + void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}"); + //A little more readable? + void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]"); + } +} diff --git a/Task/Parsing-Shunting-yard-algorithm/Java/parsing-shunting-yard-algorithm.java b/Task/Parsing-Shunting-yard-algorithm/Java/parsing-shunting-yard-algorithm.java index f7ebb06ee7..52aa4ebda8 100644 --- a/Task/Parsing-Shunting-yard-algorithm/Java/parsing-shunting-yard-algorithm.java +++ b/Task/Parsing-Shunting-yard-algorithm/Java/parsing-shunting-yard-algorithm.java @@ -9,7 +9,11 @@ public class ShuntingYard { } static String infixToPostfix(String infix) { + /* To find out the precedence, we take the index of the + token in the ops string and divide by 2 (rounding down). + This will give us: 0, 0, 1, 1, 2 */ final String ops = "-+/*^"; + StringBuilder sb = new StringBuilder(); Stack s = new Stack<>(); diff --git a/Task/Parsing-Shunting-yard-algorithm/OCaml/parsing-shunting-yard-algorithm.ocaml b/Task/Parsing-Shunting-yard-algorithm/OCaml/parsing-shunting-yard-algorithm.ocaml new file mode 100644 index 0000000000..a8659ede00 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/OCaml/parsing-shunting-yard-algorithm.ocaml @@ -0,0 +1,59 @@ +type associativity = Left | Right;; + + +let prec op = + match op with + | "^" -> 4 + | "*" -> 3 + | "/" -> 3 + | "+" -> 2 + | "-" -> 2 + | _ -> -1;; + + +let assoc op = + match op with + | "^" -> Right + | _ -> Left;; + + +let split_while p = + let rec go ls xs = + match xs with + | x::xs' when p x -> go (x::ls) xs' + | _ -> List.rev ls, xs + in go [];; + + +let rec intercalate sep xs = + match xs with + | [] -> "" + | [x] -> x + | x::xs' -> x ^ sep ^ intercalate sep xs';; + + +let shunting_yard = + let rec pusher stack queue tkns = + match tkns with + | [] -> List.rev queue @ stack + | "("::tkns' -> pusher ("("::stack) queue tkns' + | ")"::tkns' -> + let mv, "("::stack' = split_while ((<>) "(") stack in + pusher stack' (mv @ queue) tkns' + | t::tkns' when prec t < 0 -> pusher stack (t::queue) tkns' + | op::tkns' -> + let mv_to_queue op2 = + (match assoc op with + | Left -> prec op <= prec op2 + | Right -> prec op < prec op2) + in + let mv, stack' = split_while mv_to_queue stack in + pusher (op::stack') (mv @ queue) tkns' + in pusher [] [];; + + +let () = + let inp = read_line () in + let tkns = String.split_on_char ' ' inp in + let postfix = shunting_yard tkns in + print_endline (intercalate " " postfix);; diff --git a/Task/Parsing-Shunting-yard-algorithm/Phix/parsing-shunting-yard-algorithm.phix b/Task/Parsing-Shunting-yard-algorithm/Phix/parsing-shunting-yard-algorithm.phix index 6b847c7ece..2b994e07c9 100644 --- a/Task/Parsing-Shunting-yard-algorithm/Phix/parsing-shunting-yard-algorithm.phix +++ b/Task/Parsing-Shunting-yard-algorithm/Phix/parsing-shunting-yard-algorithm.phix @@ -6,8 +6,7 @@ constant operators = {"^","*","/","+","-"}, procedure shunting_yard(string infix, string rpn) string res = "", sep = "", top sequence stack = {} ---sequence ops = split(infix) -- (only works if () properly spaced) -sequence ops = split(substitute_all(infix,{"(",")"},{" ( "," ) "}),' ',0,1) +sequence ops = split(substitute_all(infix,{"(",")"},{" ( "," ) "}),' ',no_empty:=1,limit:=0) printf(1,"Infix input: %-30s%s", {infix,iff(show_workings?'\n':'\t')}) for i=1 to length(ops) do string op = ops[i] diff --git a/Task/Parsing-Shunting-yard-algorithm/Sidef/parsing-shunting-yard-algorithm.sidef b/Task/Parsing-Shunting-yard-algorithm/Sidef/parsing-shunting-yard-algorithm.sidef index 411d074441..845dfbdb74 100644 --- a/Task/Parsing-Shunting-yard-algorithm/Sidef/parsing-shunting-yard-algorithm.sidef +++ b/Task/Parsing-Shunting-yard-algorithm/Sidef/parsing-shunting-yard-algorithm.sidef @@ -5,7 +5,7 @@ var prec = Hash( '+' => 2, '-' => 2, '(' => 1, -); +) var assoc = Hash( '^' => 'right', @@ -13,38 +13,46 @@ var assoc = Hash( '/' => 'left', '+' => 'left', '-' => 'left', -); +) func shunting_yard(prog) { - var inp = prog.words; - var ops = []; - var res = []; + var inp = prog.words + var ops = [] + var res = [] +  + func report (op) { + printf("%25s  %-7s %10s %s\n", + res.join(' '), ops.join(' '), op, inp.join(' ')) + } - func report (op) { printf("%25s %-7s %10s %s\n", res.join(' '), ops.join(' '), op, inp.join(' ')) } func shift (t) { report( "shift #{t}"); ops << t } func reduce (t) { report("reduce #{t}"); res << t } - +  while (inp) { given(var t = inp.shift) { when (/\d/) { reduce(t) } when ('(') { shift(t) } - when (')') { var x; while (ops && (x = ops.pop) && (x != '(')) { reduce(x) } } + when (')') { + while (ops) { + (var x = ops.pop) == '(' ? break : reduce(x) + } + } default { - var newprec = prec{t}; + var newprec = prec{t} while (ops) { - var oldprec = prec{ops[-1]}; - + var oldprec = prec{ops[-1]} +  break if (newprec > oldprec) break if ((newprec == oldprec) && (assoc{t} == 'right')) - - reduce(ops.pop); +  + reduce(ops.pop) } - shift(t); + shift(t) } } } while (ops) { reduce(ops.pop) } return res } - -say shunting_yard('3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3').join(' '); +  +say shunting_yard('3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3').join(' ') diff --git a/Task/Parsing-Shunting-yard-algorithm/Xojo/parsing-shunting-yard-algorithm.xojo b/Task/Parsing-Shunting-yard-algorithm/Xojo/parsing-shunting-yard-algorithm.xojo new file mode 100644 index 0000000000..e29ad5c994 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Xojo/parsing-shunting-yard-algorithm.xojo @@ -0,0 +1,170 @@ +Function ShuntingYard(strInfix As String) As String + + + Dim i as Integer + Dim token, tokenArray() As String + Dim stack(), queue() As Variant + Dim discard As String + Dim op1, op2 As String + + Dim Left_Brackets, Right_Brackets As Integer + + Dim output As String + Dim dbl_output As Double + + + Left_Brackets = CountFields(strInfix, "(") + Right_Brackets = CountFields(strInfix, ")") + + If Left_Brackets = Right_Brackets Then + + + + 'Get tokens + tokenArray = Split(strInfix," ") + + + + 'Initialize array (removed later) + ReDim stack(1) + ReDim queue(1) + + 'Loop over tokens + For i = 0 to tokenArray.Ubound + + + 'i = i + 1 + If i > UBound(tokenArray) Then + Exit For + Else + token = tokenArray(i ) 'i-1 due to Split returning a Base 0 + End If + If token = "" Then + Exit For + End If + + + + + + + Dim stackString As String + Dim queuString As String + + for m as Integer = 0 to stack.Ubound + stackString = stackString + " " + stack(m) + Next + + for m as Integer = 0 to queue.Ubound + queuString = queuString + " " + queue(m) + Next + + MsgBox(Str(i) + " " + token + " " + stackString + " " + queuString) + + 'Window1.txtQueu.Text = Window1.txtQueu.Text + Str(i) + " " + token + " " + stackString + " " + queuString + EndOfLIne + + + + + ' If-loop over tokens (either brackets, operators, or numbers) + If token = "(" Then + stack.Append(token) + + ElseIf token = ")" Then + While stack(stack.Ubound) <> "(" + queue.Append(stack.pop) + Wend + + discard = stack.Pop 'discard "(" + ElseIf isOperator(token) Then + op1 = token + + + //Do While (isOperator(Peek(stack))) + While isOperator( stack(stack.Ubound) ) = True + op2 = stack(stack.Ubound) + If op2 <> "^" And precedence(op1) = precedence(op2) Then + '"^" is the only right-associative operator + + queue.Append(stack.pop) + + ElseIf precedence(op1) < precedence(op2) Then + queue.Append(stack.Pop) + Else + Exit While + End If + Wend + //Loop + + + stack.Append(op1) + Else 'number + 'actually, wrong operator could end up here, like say % + 'If the token is a number, then add it to the output queue. + queue.Append(CStr(token)) + End If + + + + + Next + + + + for i = 0 to queue.Ubound + output = output +queue(i) + " " + next + + for i = stack.Ubound DownTo 0 + output = output + stack(i)+" " + next + + + + While InStr(output, " ") <> 0 + output = ReplaceAll(output," "," ") + Wend + + + output = Trim(output) + + + Return output + + Else + + MsgBox("Syntax Error!" + EndOfLine + "Count left brackets: " + Str(Left_Brackets) + EndOfLine +"Count right brackets: " + Str(Right_Brackets)) + + End If + +End Function + + +Function isOperator(op As String) As Boolean + + If InStr("+-*/^", op) <> 0 and Len(op) = 1 Then + Return True + End If + +End Function + + +Function precedence(op As String) As Integer + + If isOperator(op) = True Then + + + + If op = "+" or op = "-" Then + Return 2 + ElseIf op = "/" or op = "*" Then + Return 3 + ElseIf op = "^" Then + Return 4 + End If + + + End If + + +End Function diff --git a/Task/Parsing-Shunting-yard-algorithm/Zkl/parsing-shunting-yard-algorithm.zkl b/Task/Parsing-Shunting-yard-algorithm/Zkl/parsing-shunting-yard-algorithm.zkl new file mode 100644 index 0000000000..4898f52197 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Zkl/parsing-shunting-yard-algorithm.zkl @@ -0,0 +1,51 @@ +var input="3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; + +var opa=Dictionary("^",T(4,True), "*",T(3,False), // op:(prec,rAssoc) + "/",T(3,False), "+",T(2,False), "-",T(2,False), +); + +"infix: ".println(input); +"postfix:".println(parseInfix(input)); + +fcn parseInfix(e){ + stack:=List(); // holds operators and left parenthesis + rpn:=""; + foreach tok in (e.split(" ")){ + switch(tok){ + case("("){ stack.append(tok) } // push "(" to stack + case(")"){ + while(True){ // pop item ("(" or operator) from stack + op:=stack.pop(); + if(op=="(") break; // discard "(" + rpn+=" " + op; // add operator to result + } + } + else{ // default + o1:=opa.find(tok); // op or Void + if(o1){ // token is an operator + while(stack){ + // consider top item on stack + op:=stack[-1]; o2:=opa.find(op); + if(not o2 or o1[0]>o2[0] or + (o1[0]==o2[0] and o1[1])) break; + // top item is an operator that needs to come off + stack.pop(); + rpn+=" " + op; // add it to result + } + // push operator (the new one) to stack + stack.append(tok); + }else // token is an operand + rpn+=(rpn and " " or "") + tok; // add operand to result + } + } // switch + display(tok,rpn,stack); + } // foreach + // drain stack to result + rpn + stack.reverse().concat(" "); +} +fcn display(tok,rpn,stack){ + "Token|".println(tok); + "Stack|".println(stack.concat()); + "Queue|".println(rpn); + println(); +} diff --git a/Task/Partial-function-application/AppleScript/partial-function-application.applescript b/Task/Partial-function-application/AppleScript/partial-function-application.applescript new file mode 100644 index 0000000000..d91164a1dd --- /dev/null +++ b/Task/Partial-function-application/AppleScript/partial-function-application.applescript @@ -0,0 +1,62 @@ +-- PARTIAL APPLICATION -------------------------------------------- + +on f1(x) + x * 2 +end f1 + +on f2(x) + x * x +end f2 + +on run + + tell curry(map) + set fsf1 to |λ|(f1) + set fsf2 to |λ|(f2) + end tell + + {fsf1's |λ|({0, 1, 2, 3}), ¬ + fsf2's |λ|({0, 1, 2, 3}), ¬ + fsf1's |λ|({2, 4, 6, 8}), ¬ + fsf2's |λ|({2, 4, 6, 8})} +end run + + +-- GENERIC FUNCTIONS -------------------------------------------- + +-- curry :: (Script|Handler) -> Script +on curry(f) + script + on |λ|(a) + script + on |λ|(b) + |λ|(a, b) of mReturn(f) + end |λ| + end script + end |λ| + end script +end curry + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn diff --git a/Task/Partial-function-application/Bracmat/partial-function-application.bracmat b/Task/Partial-function-application/Bracmat/partial-function-application.bracmat index d16d671c67..d7cdfc4bc7 100644 --- a/Task/Partial-function-application/Bracmat/partial-function-application.bracmat +++ b/Task/Partial-function-application/Bracmat/partial-function-application.bracmat @@ -1,27 +1,11 @@ -( ( fs - = - . '$!arg:?arg - & - ' ( first r - . :?r - & whl - ' ( !arg:%?first ?arg - & !r ($arg)$!first:?r - ) - & !r - ) - ) -& ( partial - = - . !arg:(?f.?g) - & /('(x./('(y.($x)$($y)))$!g))$!f - ) -& (f1=.2*!arg) -& (f2=.!arg^2) -& partial$(fs.f1):(=?fsf1) -& partial$(fs.f2):(=?fsf2) -& out$(fsf1$(0 1 2 3)) -& out$(fsf2$(0 1 2 3)) -& out$(fsf1$(2 4 6 8)) -& out$(fsf2$(2 4 6 8)) +( (fs=/('(x./('(y.map'($x.$y)))))) +& (f1=/('(x.$x*2))) +& (f2=/('(x.$x^2))) +& (partial=/('(x./('(y.($x)$($y)))))) +& (!partial$!fs)$!f1:?fsf1 +& (!partial$!fs)$!f2:?fsf2 +& out$(!fsf1$(0 1 2 3)) +& out$(!fsf2$(0 1 2 3)) +& out$(!fsf1$(2 4 6 8)) +& out$(!fsf2$(2 4 6 8)) ); diff --git a/Task/Partial-function-application/C++/partial-function-application.cpp b/Task/Partial-function-application/C++/partial-function-application.cpp index 80310741b9..793d5c3aaf 100644 --- a/Task/Partial-function-application/C++/partial-function-application.cpp +++ b/Task/Partial-function-application/C++/partial-function-application.cpp @@ -11,7 +11,7 @@ struct PApply F f; Arg arg; - tempalte< class F_, class Arg_ > + template< class F_, class Arg_ > PApply( F_&& f, Arg_&& arg ) : f(std::forward(f)), arg(std::forward(arg)) { diff --git a/Task/Partial-function-application/Elena/partial-function-application.elena b/Task/Partial-function-application/Elena/partial-function-application.elena new file mode 100644 index 0000000000..d576c4f067 --- /dev/null +++ b/Task/Partial-function-application/Elena/partial-function-application.elena @@ -0,0 +1,18 @@ +import system'collections. +import system'routines. +import extensions. + +program = +[ + var partial := (:afs:af)((:s)(afs eval(af, s))). + + var fs := (:f:s)(s selectBy(:x)(f eval:x); summarize(ArrayList new); toArray). + var f1 := (:x)(x * 2). + var f2 := (:x)(x * x). + + var fsf1 := partial eval(fs, f1). + var fsf2 := partial eval(fs, f2). + + console printLine(fsf1 eval:(2,4,6,8)). + console printLine(fsf2 eval:(2,4,6,8)). +]. diff --git a/Task/Partial-function-application/JavaScript/partial-function-application-3.js b/Task/Partial-function-application/JavaScript/partial-function-application-3.js new file mode 100644 index 0000000000..cb9a377db6 --- /dev/null +++ b/Task/Partial-function-application/JavaScript/partial-function-application-3.js @@ -0,0 +1,32 @@ +(() => { + 'use strict'; + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // curry :: ((a, b) -> c) -> a -> b -> c + const curry = f => a => b => f(a, b); + + // map :: (a -> b) -> [a] -> [b] + const map = curry((f, xs) => xs.map(f)); + + + // PARTIAL APPLICATION ---------------------------------------------------- + + const + f1 = x => x * 2, + f2 = x => x * x, + + fs = map, + + fsf1 = fs(f1), + fsf2 = fs(f2); + + // TEST ------------------------------------------------------------------- + return [ + fsf1([0, 1, 2, 3]), + fsf2([0, 1, 2, 3]), + + fsf1([2, 4, 6, 8]), + fsf2([2, 4, 6, 8]) + ]; +})(); diff --git a/Task/Partial-function-application/JavaScript/partial-function-application-4.js b/Task/Partial-function-application/JavaScript/partial-function-application-4.js new file mode 100644 index 0000000000..a74086dcd6 --- /dev/null +++ b/Task/Partial-function-application/JavaScript/partial-function-application-4.js @@ -0,0 +1,37 @@ +(() => { + 'use strict'; + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // 2 or more arguments + // curry :: Function -> Function + const curry = (f, ...args) => { + const go = xs => xs.length >= f.length ? (f.apply(null, xs)) : + function () { + return go(xs.concat(Array.from(arguments))); + }; + return go([].slice.call(args, 1)); + }; + + // map :: (a -> b) -> [a] -> [b] + const map = curry((f, xs) => xs.map(f)); + + // PARTIAL APPLICATION ---------------------------------------------------- + const + f1 = x => x * 2, + f2 = x => x * x, + + fs = map, + + fsf1 = fs(f1), + fsf2 = fs(f2); + + // TEST ------------------------------------------------------------------- + return [ + fsf1([0, 1, 2, 3]), + fsf2([0, 1, 2, 3]), + + fsf1([2, 4, 6, 8]), + fsf2([2, 4, 6, 8]) + ]; +})(); diff --git a/Task/Partial-function-application/Kotlin/partial-function-application.kotlin b/Task/Partial-function-application/Kotlin/partial-function-application.kotlin new file mode 100644 index 0000000000..84c676ea8c --- /dev/null +++ b/Task/Partial-function-application/Kotlin/partial-function-application.kotlin @@ -0,0 +1,28 @@ +// version 1.1.2 + +typealias Func = (Int) -> Int +typealias FuncS = (Func, List) -> List + +fun fs(f: Func, seq: List) = seq.map { f(it) } + +fun partial(fs: FuncS, f: Func) = { seq: List -> fs(f, seq) } + +fun f1(n: Int) = 2 * n + +fun f2(n: Int) = n * n + +fun main(args: Array) { + val fsf1 = partial(::fs, ::f1) + val fsf2 = partial(::fs, ::f2) + val seqs = listOf( + listOf(0, 1, 2, 3), + listOf(2, 4, 6, 8) + ) + for (seq in seqs) { + println(fs(::f1, seq)) // normal + println(fsf1(seq)) // partial + println(fs(::f2, seq)) // normal + println(fsf2(seq)) // partial + println() + } +} diff --git a/Task/Partial-function-application/Lambdatalk/partial-function-application.lambdatalk b/Task/Partial-function-application/Lambdatalk/partial-function-application.lambdatalk new file mode 100644 index 0000000000..4c842277c6 --- /dev/null +++ b/Task/Partial-function-application/Lambdatalk/partial-function-application.lambdatalk @@ -0,0 +1,26 @@ +1) just define function as usual: + {def add {lambda {:a :b :c} {+ :a :b :c}}} -> add + +2) and use it: + {add 1 2 3} -> 6 + {{add 1} 2 3} -> 6 + {{add 1 2} 3} -> 6 + {{{add 1} 2} 3} -> 6 + +3) application: +{def fs {lambda {:f} map :f}} +{def f1 {lambda {:x} {* :x 2}}} +{def f2 {lambda {:x} {pow :x 2}}} +{def fsf1 {fs f1}} +{def fsf2 {fs f2}} + +{{fsf1} 0 1 2 3} +{{fsf2} 0 1 2 3} +{{fsf1} 2 4 6 8} +{{fsf2} 2 4 6 8} + +Output: +0 2 4 6 +0 1 4 9 +4 8 12 16 +4 16 36 64 diff --git a/Task/Partial-function-application/Phix/partial-function-application-1.phix b/Task/Partial-function-application/Phix/partial-function-application-1.phix new file mode 100644 index 0000000000..25a30f696e --- /dev/null +++ b/Task/Partial-function-application/Phix/partial-function-application-1.phix @@ -0,0 +1,24 @@ +function fs(integer rid, sequence s) + for i=1 to length(s) do + s[i] = call_func(rid,{s[i]}) + end for + return s +end function + +function p_apply(sequence f, sequence args) + return call_func(f[1],{f[2],args}) +end function + +function f1(integer i) + return i+i +end function + +function f2(integer i) + return i*i +end function + +constant fsf1 = {routine_id("fs"),routine_id("f1")}, + fsf2 = {routine_id("fs"),routine_id("f2")} + +?p_apply(fsf1,{0,1,2,3}) +?p_apply(fsf2,{2,4,6,8}) diff --git a/Task/Partial-function-application/Phix/partial-function-application-2.phix b/Task/Partial-function-application/Phix/partial-function-application-2.phix new file mode 100644 index 0000000000..2038d7381e --- /dev/null +++ b/Task/Partial-function-application/Phix/partial-function-application-2.phix @@ -0,0 +1,4 @@ +function p_apply(sequence ffsa, sequence extra_args) + object {fa,fx,set_args} = ffsa + return call_func(fa,{fx,set_args&extra_args}) +end function diff --git a/Task/Partial-function-application/Zkl/partial-function-application.zkl b/Task/Partial-function-application/Zkl/partial-function-application.zkl new file mode 100644 index 0000000000..e9aee043cc --- /dev/null +++ b/Task/Partial-function-application/Zkl/partial-function-application.zkl @@ -0,0 +1,4 @@ +fcn fs(f,s){s.apply(f)} fcn f1(n){n*2} fcn f2(n){n*n} +var fsf1=fs.fp(f1), fsf2=fs.fp(f2); +fsf1([0..3]); //-->L(0,2,4,6) +fsf2([2..8,2]); //-->L(4,16,36,64) diff --git a/Task/Pascals-triangle-Puzzle/C/pascals-triangle-puzzle-3.c b/Task/Pascals-triangle-Puzzle/C/pascals-triangle-puzzle-3.c deleted file mode 100644 index bf9df70b5a..0000000000 --- a/Task/Pascals-triangle-Puzzle/C/pascals-triangle-puzzle-3.c +++ /dev/null @@ -1,13 +0,0 @@ -pass 1: 12 -pass 2: 12 -pass 3: 14 -pass 4: 14 -... -pass 113: 4 -pass 114: 7 -pass 115: 0 - 151 - 81 70 - 40 41 29 - 16 24 17 12 - 5 11 13 4 8 diff --git a/Task/Pascals-triangle-Puzzle/Kotlin/pascals-triangle-puzzle.kotlin b/Task/Pascals-triangle-Puzzle/Kotlin/pascals-triangle-puzzle.kotlin new file mode 100644 index 0000000000..803f25bcda --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Kotlin/pascals-triangle-puzzle.kotlin @@ -0,0 +1,22 @@ +// version 1.1.3 + +data class Solution(val x: Int, val y: Int, val z: Int) + +fun Double.isIntegral(tolerance: Double = 0.0) = + (this - Math.floor(this)) <= tolerance || (Math.ceil(this) - this) <= tolerance + +fun pascal(a: Int, b: Int, mid: Int, top: Int): Solution { + val yd = (top - 4 * (a + b)) / 7.0 + if (!yd.isIntegral(0.0001)) return Solution(0, 0, 0) + val y = yd.toInt() + val x = mid - 2 * a - y + return Solution(x, y, y - x) +} + +fun main(args: Array) { + val (x, y, z) = pascal(11, 4, 40, 151) + if (x != 0) + println("Solution is: x = $x, y = $y, z = $z") + else + println("There is no solutuon") +} diff --git a/Task/Pascals-triangle-Puzzle/Nimrod/pascals-triangle-puzzle.nimrod b/Task/Pascals-triangle-Puzzle/Nimrod/pascals-triangle-puzzle.nimrod deleted file mode 100644 index 15f13f8ea1..0000000000 --- a/Task/Pascals-triangle-Puzzle/Nimrod/pascals-triangle-puzzle.nimrod +++ /dev/null @@ -1,66 +0,0 @@ -import math, strutils - -var B_X, B_Y, B_Z : int = 0 - -type - Block_Value = object - Known : int - X, Y, Z : int - -let - X: Block_Value = Block_Value(Known:0, X:1, Y:0, Z:0) - Y: Block_Value = Block_Value(Known:0, X:0, Y:1, Z:0) - Z: Block_Value = Block_Value(Known:0, X:0, Y:0, Z:1) - -proc Add (L : var Block_Value, R : Block_Value) = - # Symbolically adds one block to another - L.Known = L.Known + R.Known - L.X = L.X + R.X - R.Z # Z is excluded as n(Y - X - Z) = 0 - L.Y = L.Y + R.Y + R.Z - -proc Add (L: var Block_Value, R: int) = - # Symbolically adds a value to the block - L.Known = L.Known + R - -proc Image (N : Block_Value): string = - # The block value, when X,Y,Z are known - result = $(N.Known + N.X * B_X + N.Y * B_Y + N.Z * B_Z) - -proc Solve_2x2 (A11: int, A12:int, B1:int, A21:int, A22:int, B2: int) = - # Don't care about things, supposing an integer solution exists - if A22 == 0: - B_X = toInt(B2 / A21) - B_Y = toInt((B1 - (A11*B_X)) / A12) - else: - B_X = toInt((B1*A22 - B2*A12) / (A11*A22 - A21*A12)) - B_Y = toInt((B1 - A11*B_X) / A12) - B_Z = B_Y - B_X - -var B : array [1..5, array[1..5, Block_Value]] # The lower triangle contains blocks - -# The bottom blocks -Add(B[5][1],X) -Add(B[5][2],11) -Add(B[5][3],Y) -Add(B[5][4],4) -Add(B[5][5],Z) - -# Upward run -for Row in countdown(4,1): - for Column in 1 .. Row: - Add (B[Row][Column], B[Row + 1][Column]) - Add (B[Row][Column], B[Row + 1][Column + 1]) - -# Now have known blocks 40=[3][1], 151=[1][1] and Y=X+Z to determine X,Y,Z -Solve_2x2( B[1][1].X, - B[1][1].Y, - 151 - B[1][1].Known, - B[3][1].X, - B[3][1].Y, - 40 - B[3][1].Known) - -#Print the results -for Row in 1..5: - writeln(stdout,"") - for Column in 1..Row: - write(stdout, Image(B[Row][Column]), " ") diff --git a/Task/Pascals-triangle-Puzzle/Python/pascals-triangle-puzzle-3.py b/Task/Pascals-triangle-Puzzle/Python/pascals-triangle-puzzle-3.py deleted file mode 100644 index f44a9f6929..0000000000 --- a/Task/Pascals-triangle-Puzzle/Python/pascals-triangle-puzzle-3.py +++ /dev/null @@ -1 +0,0 @@ -[5, 13, 8] diff --git a/Task/Pascals-triangle-Puzzle/Sidef/pascals-triangle-puzzle.sidef b/Task/Pascals-triangle-Puzzle/Sidef/pascals-triangle-puzzle.sidef index a432d99477..6642a68145 100644 --- a/Task/Pascals-triangle-Puzzle/Sidef/pascals-triangle-puzzle.sidef +++ b/Task/Pascals-triangle-Puzzle/Sidef/pascals-triangle-puzzle.sidef @@ -1,24 +1,24 @@ # set up triangle -var rows = 5; -var tri = rows.of {|i| i.of { Hash(x => 0, z => 0, v => 0, rhs => nil) } } -tri[0][0]{:rhs} = 151; -tri[2][0]{:rhs} = 40; -tri[4][0]{:x} = 1; -tri[4][1]{:v} = 11; -tri[4][2]{:x} = 1; -tri[4][2]{:z} = 1; -tri[4][3]{:v} = 4; -tri[4][4]{:z} = 1; - +var rows = 5 +var tri = rows.of {|i| (i+1).of { Hash(x => 0, z => 0, v => 0, rhs => nil) } } +tri[0][0]{:rhs} = 151 +tri[2][0]{:rhs} = 40 +tri[4][0]{:x} = 1 +tri[4][1]{:v} = 11 +tri[4][2]{:x} = 1 +tri[4][2]{:z} = 1 +tri[4][3]{:v} = 4 +tri[4][4]{:z} = 1 +  # aggregate from bottom to top -for row in (tri.end -> downto(1)) { - for col in (tri[row-1].range) { +for row in (tri.len ^.. 1) { + for col in (^tri[row-1]) { [:x, :z, :v].each { |key| tri[row-1][col]{key} = (tri[row][col]{key} + tri[row][col+1]{key}) } } } - +  # find equations var eqn = gather { for r in tri { @@ -27,21 +27,21 @@ var eqn = gather { } } } - +  # print equations -say "Equations:"; -say " x + z = y"; +say "Equations:" +say " x + z = y" for x,z,y in eqn { say "#{x}x + #{z}z = #{y}" } - +  # solve -var f = (eqn[0][1] / eqn[1][1]); -for i in (0..2) { eqn[0][i] -= (f * eqn[1][i]) } -f = (eqn[1][0] / eqn[0][0]); -for i in (0..2) { eqn[1][i] -= (f * eqn[0][i]) } - +var f = (eqn[0][1] / eqn[1][1]) +{|i| eqn[0][i] -= (f * eqn[1][i]) } << ^3 +f = (eqn[1][0] / eqn[0][0]) +{|i| eqn[1][i] -= (f * eqn[0][i]) } << ^3 +  # print solution -say "Solution:"; -var x = (eqn[0][2] / eqn[0][0]); -var z = (eqn[1][2] / eqn[1][1]); -var y = (x + z); -say "x=#{x}, y=#{y}, z=#{z}"; +say "Solution:" +var x = (eqn[0][2] / eqn[0][0]) +var z = (eqn[1][2] / eqn[1][1]) +var y = (x + z) +say "x=#{x}, y=#{y}, z=#{z}" diff --git a/Task/Pascals-triangle-Puzzle/Zkl/pascals-triangle-puzzle-1.zkl b/Task/Pascals-triangle-Puzzle/Zkl/pascals-triangle-puzzle-1.zkl new file mode 100644 index 0000000000..b9dc1f3241 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Zkl/pascals-triangle-puzzle-1.zkl @@ -0,0 +1,12 @@ +# Pyramid solver +# [151] +# [ ] [ ] +# [ 40] [ ] [ ] +# [ ] [ ] [ ] [ ] +#[ X ] [ 11] [ Y ] [ 4 ] [ Z ] +# Known: X - Y + Z = 0 + +p:=T( L(151), L(Void,Void), L(40,Void,Void), L(Void,Void,Void,Void), + L("X", 11, "Y", 4, "Z") ); +addlConstraint:=Dictionary( "X",1, "Y",-1, "Z",1, "1",0 ); +solvePyramid(p, addlConstraint); diff --git a/Task/Pascals-triangle-Puzzle/Zkl/pascals-triangle-puzzle-2.zkl b/Task/Pascals-triangle-Puzzle/Zkl/pascals-triangle-puzzle-2.zkl new file mode 100644 index 0000000000..54ae783f0d --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Zkl/pascals-triangle-puzzle-2.zkl @@ -0,0 +1,83 @@ +fcn solvePyramid([List]vl,[Dictionary]cnstr){ //ListOfLists,Hash-->zip + vl=vl.reverse(); + constraints:=L(cnstr); + lvls:=vl.len(); + foreach lvln in ([1..lvls-1]){ + lvd:=vl[lvln]; + foreach k in (lvls-lvln){ + sn:=lvd[k]; + ll:=vl[lvln-1]; + vn:=combine(ll[k], ll[k+1]); + if(Void==sn) lvd[k]=vn; + else constraints.append(constrainK(sn,vn)); + } + } + println("Constraint Equations:"); + constraints.pump(Console.println,fcn(hash){ + hash.pump(List,fcn([(k,v)]){"%d*%s".fmt(v,k)}).concat(" + ") + " = 0" + }); + + mtx,vmap:=makeMatrix(constraints); + mtxSolve(mtx); + + d:=vmap.len(); + foreach j in (d){ println(vmap[j]," = ", mtx[j][d]); } +} + +fcn [mixin=Dictionary] constrainK([Int]nsum,[Dictionary]vn){ //-->new hash of old hash, sum K + nn:=vn.copy(); nn["1"]=nn.find("1",0) - nsum; + return(nn.makeReadOnly()); +} + +fcn combine(snl,snr){ //Int|String|Hash *2 --> new Hash + cl:=Dictionary(); + if(snl.isInstanceOf(Int)) cl["1"]=snl; + else if(snl.isInstanceOf(String)) cl[snl]=1; + else cl =snl.copy(); + + if(snr.isInstanceOf(Int)) cl["1"]=cl.find("1",0) + snr; + else if(snr.isInstanceOf(String)) cl[snr]=cl.find(snr,0) + 1; + else{ foreach k,v in (snr){ cl[k] =cl.find(k,0) + v; } } + return(cl.makeReadOnly()) +} + + //-->(listMatrix(row(X,Y,Z,c),row...),List("X","Y","Z")) +fcn makeMatrix([Dictionary]constraints){ + vmap:=Dictionary();// create a sorted list of the variable names in constraints + foreach c in (constraints){ vmap.extend(c) } // no duplicate names + vmap.del("1"); vmap=vmap.keys.sort(); # sort here so output is in sorted order + + mtx:=constraints.pump(List,'wrap(c){ // create list of [writeable] rows + vmap.pump(List, c.find.fp1(0),"toFloat").copy() + .append(-c.find("1",0).toFloat()) + }).copy(); + + nvars:=vmap.len(); + if(constraints.len()==nvars) println("System appears solvable"); + else if(constraints.len() 0 then begin + integer array pascalLine ( 1 :: n ); + pascalLine( 1 ) := 1; + for line := 1 until n do begin + for i := line - 1 step - 1 until 2 do pascalLine( i ) := pascalLine( i - 1 ) + pascalLine( i ); + pascalLine( line ) := 1; + write( s_w := 0, " " ); + for i := line until n do writeon( s_w := 0, " " ); + for i := 1 until line do writeon( i_w := 6, s_w := 0, pascalLine( i ) ) + end for_line ; + end printPascalTriangle ; + + printPascalTriangle( 8 ) + +end. diff --git a/Task/Pascals-triangle/AppleScript/pascals-triangle.applescript b/Task/Pascals-triangle/AppleScript/pascals-triangle.applescript index 5705744436..59f853a5b0 100644 --- a/Task/Pascals-triangle/AppleScript/pascals-triangle.applescript +++ b/Task/Pascals-triangle/AppleScript/pascals-triangle.applescript @@ -1,57 +1,73 @@ +-- PASCAL --------------------------------------------------------------------- + -- pascal :: Int -> [[Int]] on pascal(intRows) script addRow on nextRow(row) script add - on lambda(a, b) + on |λ|(a, b) a + b - end lambda + end |λ| end script zipWith(add, [0] & row, row & [0]) end nextRow - on lambda(xs) + on |λ|(xs) xs & {nextRow(item -1 of xs)} - end lambda + end |λ| end script - foldr(addRow, {{1}}, range(1, intRows - 1)) + foldr(addRow, {{1}}, enumFromTo(1, intRows - 1)) end pascal - --- TEST - +-- TEST ----------------------------------------------------------------------- on run set lstTriangle to pascal(7) script spaced - on lambda(xs) + on |λ|(xs) script rightAlign - on lambda(x) + on |λ|(x) text -4 thru -1 of (" " & x) - end lambda + end |λ| end script intercalate("", map(rightAlign, xs)) - end lambda + end |λ| end script script indented - on lambda(a, x) + on |λ|(a, x) set strIndent to leftSpace of a - {rows:strIndent & x & linefeed & rows of a, leftSpace:leftSpace of a & " "} - end lambda + {rows:¬ + strIndent & x & linefeed & rows of a, leftSpace:¬ + leftSpace of a & " "} ¬ + + end |λ| end script - rows of foldr(indented, {rows:"", leftSpace:""}, map(spaced, lstTriangle)) + rows of foldr(indented, ¬ + {rows:"", leftSpace:""}, map(spaced, lstTriangle)) end run +-- GENERIC FUNCTIONS ---------------------------------------------------------- - --- GENERIC LIBRARY FUNCTIONS +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if n < m then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- foldr :: (a -> b -> a) -> a -> [b] -> a on foldr(f, startValue, xs) @@ -59,51 +75,12 @@ on foldr(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldr --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map - --- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -on zipWith(f, xs, ys) - set nx to length of xs - set ny to length of ys - if nx < 1 or ny < 1 then - {} - else - set lng to cond(nx < ny, nx, ny) - set lst to {} - tell mReturn(f) - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, item i of ys) - end repeat - return lst - end tell - end if -end zipWith - --- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b) -on cond(bool, f, g) - if bool then - f - else - g - end if -end cond - -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} @@ -112,16 +89,26 @@ on intercalate(strText, lstText) return strJoined end intercalate --- range :: Int -> Int -> [Int] -on range(m, n) - set lng to (n - m) + 1 - set base to m - 1 - set lst to {} - repeat with i from 1 to lng - set end of lst to i + base - end repeat - return lst -end range +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- min :: Ord a => a -> a -> a +on min(x, y) + if y < x then + y + else + x + end if +end min -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -130,7 +117,19 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn + +-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] +on zipWith(f, xs, ys) + set lng to min(length of xs, length of ys) + set lst to {} + tell mReturn(f) + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, item i of ys) + end repeat + return lst + end tell +end zipWith diff --git a/Task/Pascals-triangle/Common-Lisp/pascals-triangle-3.lisp b/Task/Pascals-triangle/Common-Lisp/pascals-triangle-3.lisp new file mode 100644 index 0000000000..d628199678 --- /dev/null +++ b/Task/Pascals-triangle/Common-Lisp/pascals-triangle-3.lisp @@ -0,0 +1,11 @@ +(defun next-pascal (l) + `(1 ,@(loop for i from 0 to (- (length l) 2) + collect (+ (nth i l) (nth (1+ i) l))) + 1)) + +(defun pascal-print (r) + (let* ((pasc (loop with p = (list (list 1)) + repeat r do (nconc p (list (apply #'next-pascal (last p)))) + finally (return p))) + (len (length (format nil "~A" (car (last pasc)))))) + (format t (format nil "~~{~~~D:@<~~{~~A ~~}~~>~~%~~}" len) pasc))) diff --git a/Task/Pascals-triangle/Common-Lisp/pascals-triangle-4.lisp b/Task/Pascals-triangle/Common-Lisp/pascals-triangle-4.lisp new file mode 100644 index 0000000000..aa32ca5ee8 --- /dev/null +++ b/Task/Pascals-triangle/Common-Lisp/pascals-triangle-4.lisp @@ -0,0 +1 @@ +(pascal-print 4) diff --git a/Task/Pascals-triangle/Common-Lisp/pascals-triangle-5.lisp b/Task/Pascals-triangle/Common-Lisp/pascals-triangle-5.lisp new file mode 100644 index 0000000000..e5ce3bc4c7 --- /dev/null +++ b/Task/Pascals-triangle/Common-Lisp/pascals-triangle-5.lisp @@ -0,0 +1,5 @@ + 1 + 1 1 + 1 2 1 + 1 3 3 1 +1 4 6 4 1 diff --git a/Task/Pascals-triangle/Common-Lisp/pascals-triangle-6.lisp b/Task/Pascals-triangle/Common-Lisp/pascals-triangle-6.lisp new file mode 100644 index 0000000000..ce72fa9866 --- /dev/null +++ b/Task/Pascals-triangle/Common-Lisp/pascals-triangle-6.lisp @@ -0,0 +1 @@ +(pascal-print 8) diff --git a/Task/Pascals-triangle/Common-Lisp/pascals-triangle-7.lisp b/Task/Pascals-triangle/Common-Lisp/pascals-triangle-7.lisp new file mode 100644 index 0000000000..7be3c934de --- /dev/null +++ b/Task/Pascals-triangle/Common-Lisp/pascals-triangle-7.lisp @@ -0,0 +1,9 @@ + 1 + 1 1 + 1 2 1 + 1 3 3 1 + 1 4 6 4 1 + 1 5 10 10 5 1 + 1 6 15 20 15 6 1 + 1 7 21 35 35 21 7 1 +1 8 28 56 70 56 28 8 1 diff --git a/Task/Pascals-triangle/Component-Pascal/pascals-triangle.component b/Task/Pascals-triangle/Component-Pascal/pascals-triangle.component new file mode 100644 index 0000000000..4d153f7e1b --- /dev/null +++ b/Task/Pascals-triangle/Component-Pascal/pascals-triangle.component @@ -0,0 +1,71 @@ +MODULE PascalTriangle; +IMPORT StdLog, DevCommanders, TextMappers; + +TYPE + Expansion* = POINTER TO ARRAY OF LONGINT; + +PROCEDURE Show*(e: Expansion); +VAR + i: INTEGER; +BEGIN + i := 0; + WHILE (i < LEN(e)) & (e[i] # 0) DO + StdLog.Int(e[i]); + INC(i) + END; + StdLog.Ln +END Show; + +PROCEDURE GenFor*(p: LONGINT): Expansion; +VAR + expA,expB: Expansion; + i,j: LONGINT; + + PROCEDURE Swap(VAR x,y: Expansion); + VAR + swap: Expansion; + BEGIN + swap := x; x := y; y := swap + END Swap; + +BEGIN + ASSERT(p >= 0); + NEW(expA,p + 2);NEW(expB,p + 2); + FOR i := 0 TO p DO + IF i = 0 THEN expA[0] := 1 + ELSE + FOR j := 0 TO i DO + IF j = 0 THEN + expB[j] := expA[j] + ELSE + expB[j] := expA[j - 1] + expA[j] + END + END; + Swap(expA,expB) + END; + END; + expB := NIL; (* for the GC *) + RETURN expA +END GenFor; + + +PROCEDURE Do*; +VAR + s: TextMappers.Scanner; + exp: Expansion; +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.int) THEN + exp := GenFor(s.int); + Show(exp) + END; + s.Scan + END +END Do; + +END PascalTriangle. diff --git a/Task/Pascals-triangle/Dart/pascals-triangle.dart b/Task/Pascals-triangle/Dart/pascals-triangle.dart new file mode 100644 index 0000000000..73d09fa8a5 --- /dev/null +++ b/Task/Pascals-triangle/Dart/pascals-triangle.dart @@ -0,0 +1,39 @@ +import 'dart:io'; + +pascal(n) { + if(n<=0) print("Not defined"); + + else if(n==1) print(1); + + else { + List> matrix = new List>(); + matrix.add(new List()); + matrix.add(new List()); + matrix[0].add(1); + matrix[1].add(1); + matrix[1].add(1); + for (var i = 2; i < n; i++) { + List list = new List(); + list.add(1); + for (var j = 1; j [[Int]] function pascal(n) { - return range(1, n - 1) - .reduce(function (a) { - var lstPreviousRow = a.slice(-1)[0]; - - return a - .concat( - [zipWith( - function (a, b) { - return a + b - }, - [0].concat(lstPreviousRow), - lstPreviousRow.concat(0) - )] - ); - }, [[1]]); - } + return foldl(function (a) { + var xs = a.slice(-1)[0]; // Previous row + return append(a, [zipWith( + function (a, b) { + return a + b; + }, + append([0], xs), + append(xs, [0]) + )]); + }, [ + [1] // Initial seed row + ], enumFromTo(1, n - 1)); + }; + // GENERIC FUNCTIONS ------------------------------------------------------ - // GENERIC FUNCTIONS + // (++) :: [a] -> [a] -> [a] + function append(xs, ys) { + return xs.concat(ys); + }; + + // enumFromTo :: Int -> Int -> [Int] + function enumFromTo(m, n) { + return Array.from({ + length: Math.floor(n - m) + 1 + }, function (_, i) { + return m + i; + }); + }; + + // foldl :: (b -> a -> b) -> b -> [a] -> b + function foldl(f, a, xs) { + return xs.reduce(f, a); + }; + + // foldr (a -> b -> b) -> b -> [a] -> b + function foldr(f, a, xs) { + return xs.reduceRight(f, a); + }; + + // map :: (a -> b) -> [a] -> [b] + function map(f, xs) { + return xs.map(f); + }; + + // min :: Ord a => a -> a -> a + function min(a, b) { + return b < a ? b : a; + }; // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] function zipWith(f, xs, ys) { - return xs.length === ys.length ? ( - xs.map(function (x, i) { - return f(x, ys[i]); - }) - ) : undefined; - } + return Array.from({ + length: min(xs.length, ys.length) + }, function (_, i) { + return f(xs[i], ys[i]); + }); + }; - // range :: Int -> Int -> [Int] - function range(m, n) { - return Array.apply(null, Array(n - m + 1)) - .map(function (x, i) { - return m + i; - }); - } - - // TEST + // TEST and FORMAT -------------------------------------------------------- var lstTriangle = pascal(n); - - // FORMAT OUTPUT AS WIKI TABLE - // [[a]] -> bool -> s -> s function wikiTable(lstRows, blnHeaderRow, strStyle) { - return '{| class="wikitable" ' + ( - strStyle ? 'style="' + strStyle + '"' : '' - ) + lstRows.map(function (lstRow, iRow) { - var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|'); - - return '\n|-\n' + strDelim + ' ' + lstRow.map(function ( - v) { + return '{| class="wikitable" ' + (strStyle ? 'style="' + strStyle + + '"' : '') + lstRows.map(function (lstRow, iRow) { + var strDelim = blnHeaderRow && !iRow ? '!' : '|'; + return '\n|-\n' + strDelim + ' ' + lstRow.map(function (v) { return typeof v === 'undefined' ? ' ' : v; }) .join(' ' + strDelim + strDelim + ' '); @@ -66,29 +82,21 @@ } var lstLastLine = lstTriangle.slice(-1)[0], - lngBase = (lstLastLine.length * 2) - 1, + lngBase = lstLastLine.length * 2 - 1, nWidth = lstLastLine.reduce(function (a, x) { var d = x.toString() .length; return d > a ? d : a; }, 1) * lngBase; - return [ - wikiTable( - lstTriangle.map(function (lst) { - return lst.join(';;') - .split(';'); - }) - .map(function (line, i) { - var lstPad = Array((lngBase - line.length) / 2); - return lstPad.concat(line) - .concat(lstPad); - }), - false, - 'text-align:center;width:' + nWidth + 'em;height:' + nWidth + - 'em;table-layout:fixed;' - ), - - JSON.stringify(lstTriangle) - ].join('\n\n'); + return [wikiTable(lstTriangle.map(function (lst) { + return lst.join(';;') + .split(';'); + }) + .map(function (line, i) { + var lstPad = Array((lngBase - line.length) / 2); + return lstPad.concat(line) + .concat(lstPad); + }), false, 'text-align:center;width:' + nWidth + 'em;height:' + nWidth + + 'em;table-layout:fixed;'), JSON.stringify(lstTriangle)].join('\n\n'); })(7); diff --git a/Task/Pascals-triangle/JavaScript/pascals-triangle-4.js b/Task/Pascals-triangle/JavaScript/pascals-triangle-4.js index 4e1e8b3378..e1f098b118 100644 --- a/Task/Pascals-triangle/JavaScript/pascals-triangle-4.js +++ b/Task/Pascals-triangle/JavaScript/pascals-triangle-4.js @@ -1,50 +1,68 @@ (() => { 'use strict'; + // PASCAL'S TRIANGLE ------------------------------------------------------ + // pascal :: Int -> [[Int]] - let pascal = n => - range(1, n - 1) - .reduce(a => { - let lstPreviousRow = a.slice(-1)[0]; - - return a - .concat([zipWith((a, b) => a + b, - [0].concat(lstPreviousRow), - lstPreviousRow.concat(0) - )]); - }, [ - [1] + const pascal = n => + foldl(a => { + const xs = a.slice(-1)[0]; // Previous row + return append(a, [ + zipWith( + (a, b) => a + b, + append([0], xs), + append(xs, [0]) + ) ]); + }, [ + [1] // Initial seed row + ], enumFromTo(1, n - 1)); - // GENERIC FUNCTIONS - // Int -> Int -> Maybe Int -> [Int] - let range = (m, n, step) => { - let d = (step || 1) * (n >= m ? 1 : -1); - return Array.from({ - length: Math.floor((n - m) / d) + 1 - }, (_, i) => m + (i * d)); - }, + // GENERIC FUNCTIONS ------------------------------------------------------ - // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] - zipWith = (f, xs, ys) => - xs.length === ys.length ? ( - xs.map((x, i) => f(x, ys[i])) - ) : undefined; + // (++) :: [a] -> [a] -> [a] + const append = (xs, ys) => xs.concat(ys); - // TEST - return pascal(7) - .reduceRight((a, x) => { - let strIndent = a.indent; + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + // flip :: (a -> b -> c) -> b -> a -> c + const flip = f => (a, b) => f(b, a); + + // foldl :: (b -> a -> b) -> b -> [a] -> b + const foldl = (f, a, xs) => xs.reduce(f, a); + + // foldr (a -> b -> b) -> b -> [a] -> b + const foldr = (f, a, xs) => xs.reduceRight(flip(f), a); + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // min :: Ord a => a -> a -> a + const min = (a, b) => b < a ? b : a; + + // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] + const zipWith = (f, xs, ys) => + Array.from({ + length: min(xs.length, ys.length) + }, (_, i) => f(xs[i], ys[i])); + + // TEST ------------------------------------------------------------------- + return foldr((x, a) => { + const strIndent = a.indent; return { - rows: strIndent + x - .map(n => (' ' + n).slice(-4)) + rows: strIndent + map(n => (' ' + n) + .slice(-4), x) .join('') + '\n' + a.rows, indent: strIndent + ' ' }; }, { rows: '', indent: '' - }).rows; + }, pascal(7)) + .rows; })(); diff --git a/Task/Pascals-triangle/jq/pascals-triangle-1.jq b/Task/Pascals-triangle/Jq/pascals-triangle-1.jq similarity index 100% rename from Task/Pascals-triangle/jq/pascals-triangle-1.jq rename to Task/Pascals-triangle/Jq/pascals-triangle-1.jq diff --git a/Task/Pascals-triangle/jq/pascals-triangle-2.jq b/Task/Pascals-triangle/Jq/pascals-triangle-2.jq similarity index 100% rename from Task/Pascals-triangle/jq/pascals-triangle-2.jq rename to Task/Pascals-triangle/Jq/pascals-triangle-2.jq diff --git a/Task/Pascals-triangle/jq/pascals-triangle-3.jq b/Task/Pascals-triangle/Jq/pascals-triangle-3.jq similarity index 100% rename from Task/Pascals-triangle/jq/pascals-triangle-3.jq rename to Task/Pascals-triangle/Jq/pascals-triangle-3.jq diff --git a/Task/Pascals-triangle/Julia/pascals-triangle.julia b/Task/Pascals-triangle/Julia/pascals-triangle.julia new file mode 100644 index 0000000000..59a1af3975 --- /dev/null +++ b/Task/Pascals-triangle/Julia/pascals-triangle.julia @@ -0,0 +1,8 @@ +iround(x) = round(Int64, x) + +triangle(n) = iround.(expm(diagm(1:n, -1))) + +function pascal(n) + println.(join.([filter(!iszero, triangle(n)[i,:]) for i in 1:(n+1)], " ")) + return +end diff --git a/Task/Pascals-triangle/Q/pascals-triangle.q b/Task/Pascals-triangle/Q/pascals-triangle.q new file mode 100644 index 0000000000..d1486fbbbd --- /dev/null +++ b/Task/Pascals-triangle/Q/pascals-triangle.q @@ -0,0 +1,7 @@ +pascal:{(x-1){0+':x,0}\1} +pascal 5 +1 +1 1 +1 2 1 +1 3 3 1 +1 4 6 4 1 diff --git a/Task/Pascals-triangle/Racket/pascals-triangle.rkt b/Task/Pascals-triangle/Racket/pascals-triangle.rkt index e898c6f78a..7f9de76cc4 100644 --- a/Task/Pascals-triangle/Racket/pascals-triangle.rkt +++ b/Task/Pascals-triangle/Racket/pascals-triangle.rkt @@ -4,11 +4,7 @@ (define (next-row current-row) (map + (cons 0 current-row) (append current-row '(0)))) - (let-values - ([(previous-rows final-row) - (for/fold ([triangle null] - [row '(1)]) - ([row-number (in-range 1 n)]) - (values (cons row triangle) - (next-row row)))]) - (reverse (cons final-row previous-rows)))) + (reverse + (for/fold ([triangle '((1))]) + ([row (in-range 1 n)]) + (cons (next-row (first triangle)) triangle)))) diff --git a/Task/Pascals-triangle/Sidef/pascals-triangle.sidef b/Task/Pascals-triangle/Sidef/pascals-triangle.sidef index 2796f00d46..a9cec64f3b 100644 --- a/Task/Pascals-triangle/Sidef/pascals-triangle.sidef +++ b/Task/Pascals-triangle/Sidef/pascals-triangle.sidef @@ -1,9 +1,9 @@ func pascal(rows) { - var row = [1]; + var row = [1] { | n| - say row.join(' '); - row = [1, 0..(n-2).map {|i| row[i] + row[i+1] }..., 1]; - } * rows; + say row.join(' ') + row = [1, {|i| row[i] + row[i+1] }.map(0 .. n-2)..., 1] + } << 1..rows } - -pascal(10); +  +pascal(10) diff --git a/Task/Pascals-triangle/Swift/pascals-triangle.swift b/Task/Pascals-triangle/Swift/pascals-triangle.swift new file mode 100644 index 0000000000..84de75d44a --- /dev/null +++ b/Task/Pascals-triangle/Swift/pascals-triangle.swift @@ -0,0 +1,22 @@ +func pascal(n:Int)->[Int]{ + if n==1{ + let a=[1] + print(a) + return a + } + else{ + var a=pascal(n:n-1) + var temp=a + for i in 0.."" + foreach i in (n){ + c := 1; + print(" "*(2*(n-1-i))); + foreach k in (i+1){ + print("%3d ".fmt(c)); + c = c * (i-k)/(k+1); + } + println(); + } +} + +pascalTriangle(8); diff --git a/Task/Pattern-matching/Perl-6/pattern-matching.pl6 b/Task/Pattern-matching/Perl-6/pattern-matching.pl6 index 463b963033..26030a3a34 100644 --- a/Task/Pattern-matching/Perl-6/pattern-matching.pl6 +++ b/Task/Pattern-matching/Perl-6/pattern-matching.pl6 @@ -15,11 +15,11 @@ multi ins( $x, @s [$col, $a, $y, $b] ) { multi ins( $x, Any:U ) { [R, Any, $x, Any] } multi insert( $x, $s ) { - [B, ins($x,$s)[1..3]]; + [B, |ins($x,$s)[1..3]]; } sub MAIN { my $t = Any; $t = insert($_, $t) for (1..10).pick(*); - say $t.perl; + say $t.gist; } diff --git a/Task/Pattern-matching/Rust/pattern-matching.rust b/Task/Pattern-matching/Rust/pattern-matching.rust new file mode 100644 index 0000000000..35aa914bd0 --- /dev/null +++ b/Task/Pattern-matching/Rust/pattern-matching.rust @@ -0,0 +1,43 @@ +#![feature(box_patterns, box_syntax)] +use self::Color::*; +use std::cmp::Ordering::*; + +enum Color {R,B} + +type Link = Option>>; +struct N { + c: Color, + l: Link, + val: T, + r: Link, +} + + +impl N { + fn balance(col: Color, n1: Link, z: T, n2: Link) -> Link { + Some(box + match (col,n1,n2) { + (B, Some(box N {c: R, l: Some(box N {c: R, l: a, val: x, r: b}), val: y, r: c}), d) + | (B, Some(box N {c: R, l: a, val: x, r: Some (box N {c: R, l: b, val: y, r: c})}), d) + => N {c: R, l: Some(box N {c: B, l: a, val: x, r: b}), val: y, r: Some(box N {c: B, l: c, val: z, r: d})}, + (B, a, Some(box N {c: R, l: Some(box N {c: R, l: b, val: y, r: c}), val: v, r: d})) + | (B, a, Some(box N {c: R, l: b, val: y, r: Some(box N {c: R, l: c, val: v, r: d})})) + => N {c: R, l: Some(box N {c: B, l: a, val: z, r: b}), val: y, r: Some(box N {c: B, l: c, val: v, r: d})}, + (col, a, b) => N {c: col, l: a, val: z, r: b}, + }) + } + fn insert(x: T, n: Link) -> Link { + match n { + None => Some(box N { c: R, l: None, val: x, r: None }), + Some(n) => { + let n = *n; + let N {c: col, l: a, val: y, r: b} = n; + match x.cmp(&y) { + Greater => Self::balance(col, a,y,Self::insert(x,b)), + Less => Self::balance(col, Self::insert(x,a),y,b), + Equal => Some(box N {c: col, l: a, val: y, r: b}) + } + } + } + } +} diff --git a/Task/Penneys-game/00DESCRIPTION b/Task/Penneys-game/00DESCRIPTION index f785d1cdd4..867d158b6f 100644 --- a/Task/Penneys-game/00DESCRIPTION +++ b/Task/Penneys-game/00DESCRIPTION @@ -1,31 +1,28 @@ -[[wp:Penney's_game|Penney's game]]   is a game where two players bet on being the first to see a particular sequence of   [[wp:Coin_flipping|heads or tails]]   in consecutive tosses of a   [[wp:Fair_coin|fair coin]]. +[[wp:Penney's_game|Penney's game]] is a game where two players bet on being the first to see a particular sequence of [[wp:Coin_flipping|heads or tails]] in consecutive tosses of a [[wp:Fair_coin|fair coin]]. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: - Heads, Tails, Heads, or - '''HTH''' for short. -The other player on seeing the first players choice will choose his sequence. - -The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins. + Heads, Tails, Heads, or '''HTH''' for short. +The other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins. ;Example: -One player might choose the sequence   '''HHT'''   and the other   '''THT'''.   +One player might choose the sequence '''HHT''' and the other '''THT'''. -Successive coin tosses of   '''HTTHT'''   gives the win to the second player as the last three coin tosses are his sequence. +Successive coin tosses of '''HTTHT''' gives the win to the second player as the last three coin tosses are his sequence. -;Task: +;Task Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent. -:*   Who chooses and shows their sequence of three should be chosen randomly. -:*   If going first, the computer should randomly choose its sequence of three. -:*   If going second, the computer should automatically play [[wp:Penney's_game#Analysis_of_the_three-bit_game|the optimum sequence]]. -:*   Successive coin tosses should be shown. +* Who chooses and shows their sequence of three should be chosen randomly. +* If going first, the computer should randomly choose its sequence of three. +* If going second, the computer should automatically play [[wp:Penney's_game#Analysis_of_the_three-bit_game|the optimum sequence]]. +* Successive coin tosses should be shown.
    Show output of a game where the computer chooses first and a game where the user goes first here on this page. -;See also: -*   [https://www.youtube.com/watch?v=OcYnlSenF04 The Penney Ante Part 1] (Video). -*   [https://www.youtube.com/watch?v=U9wak7g5yQA The Penney Ante Part 2] (Video). +;See also +* [https://www.youtube.com/watch?v=OcYnlSenF04 The Penney Ante Part 1] (Video). +* [https://www.youtube.com/watch?v=U9wak7g5yQA The Penney Ante Part 2] (Video).

    diff --git a/Task/Penneys-game/BASIC/penneys-game.basic b/Task/Penneys-game/BASIC/penneys-game.basic new file mode 100644 index 0000000000..91b73945a6 --- /dev/null +++ b/Task/Penneys-game/BASIC/penneys-game.basic @@ -0,0 +1,31 @@ + 10 IF RND>=.5 THEN GOTO 100 + 20 PRINT "YOU PICK FIRST." + 30 INPUT P$ + 40 PRINT "YOU CHOSE ";P$ + 50 LET C$="H" + 60 IF P$(2)="H" THEN LET C$="T" + 70 LET C$=C$+P$( TO 2) + 80 PRINT "I CHOOSE ";C$ + 90 GOTO 190 +100 PRINT "I PICK FIRST." +110 LET C$="" +120 FOR I=1 TO 3 +130 LET C$=C$+"H" +140 IF RND>=.5 THEN LET C$(I)="T" +150 NEXT I +160 PRINT "I CHOOSE ";C$ +170 INPUT P$ +180 PRINT "YOU CHOSE ";P$ +190 LET G$="" +200 IF RND>=.5 THEN GOTO 230 +210 LET G$=G$+"H" +220 GOTO 240 +230 LET G$=G$+"T" +240 PRINT AT 5,0;G$ +250 IF LEN G$<3 THEN GOTO 200 +260 IF G$(LEN G$-2 TO )=P$ THEN GOTO 290 +270 IF G$(LEN G$-2 TO )=C$ THEN GOTO 310 +280 GOTO 200 +290 PRINT "YOU WIN" +300 STOP +310 PRINT "I WIN" diff --git a/Task/Penneys-game/Clojure/penneys-game.clj b/Task/Penneys-game/Clojure/penneys-game.clj new file mode 100644 index 0000000000..0d37b54d3a --- /dev/null +++ b/Task/Penneys-game/Clojure/penneys-game.clj @@ -0,0 +1,64 @@ +(ns penney.core + (:gen-class)) + +(def heads \H) +(def tails \T) + +(defn flip-coin [] + (let [flip (rand-int 2)] + (if (= flip 0) heads tails))) + +(defn turn [coin] + (if (= coin heads) tails heads)) + +(defn first-index [combo coll] + (some #(if (= (second %) combo) (first %)) coll)) + +(defn find-winner [h c] + (if (< h c) + (do (println "YOU WIN!\n") :human) + (do (println "COMPUTER WINS!\n") :computer))) + +(defn flip-off [human comp] + (let [flips (repeatedly flip-coin) + idx-flips (map-indexed vector (partition 3 1 flips)) + h (first-index (seq human) idx-flips) + c (first-index (seq comp) idx-flips)] + (println (format "Tosses: %s" (apply str (take (+ 3 (min h c)) flips)))) + (find-winner h c))) + +(defn valid? [combo] + (if (empty? combo) true (and (= 3 (count combo)) (every? #(or (= heads %) (= tails %)) combo)))) + +(defn ask-move [] + (println "What sequence of 3 Heads/Tails do you choose?") + (let [input (clojure.string/upper-case (read-line))] + (if-not (valid? input) (recur) input))) + +(defn optimize-against [combo] + (let [mid (nth combo 1) + comp (str (turn mid) (first combo) mid)] + (println (format "Computer chooses %s: " comp)) comp)) + +(defn initial-move [game] + (let [combo (apply str (repeatedly 3 flip-coin))] + (println "--------------") + (println (format "Current score | CPU: %s, You: %s" (:computer game) (:human game))) + (if (= (:first-player game) tails) + (do + (println "Computer goes first and chooses: " combo) + combo) + (println "YOU get to go first.")))) + +(defn play-game [game] + (let [c-move (initial-move game) + h-move (ask-move)] + (if-not (empty? h-move) + (let [winner (flip-off h-move (if (nil? c-move) (optimize-against h-move) c-move))] + (recur (assoc game winner (inc (winner game)) :first-player (flip-coin)))) + (println "Thanks for playing!")))) + +(defn -main [& args] + (println "Penney's Game.") + (play-game {:first-player (flip-coin) + :human 0, :computer 0})) diff --git a/Task/Penneys-game/Go/penneys-game.go b/Task/Penneys-game/Go/penneys-game.go new file mode 100644 index 0000000000..5f07935904 --- /dev/null +++ b/Task/Penneys-game/Go/penneys-game.go @@ -0,0 +1,87 @@ +package main +import "fmt" +import "math/rand" +func main(){ +var a1,a2,a3,y,match,j,k int +var inp string +y=1 +for y==1{ +fmt.Println("Enter your sequence:") +fmt.Scanln(&inp) +var Ai [3] int +var user [3] int +for j=0;j<3;j++{ +if(inp[j]==104){ +user[j]=1 +}else{ +user[j]=0 +} +} +for k=0;k<3;k++{ +Ai[k]=rand.Intn(2) +} +for user[0]==Ai[0]&&user[1]==Ai[1]&&user[2]==Ai[2]{ +for k=0;k<3;k++{ +Ai[k]=rand.Intn(2) +} +} +fmt.Println("You gave the sequence:") +printht(user) +fmt.Println() +fmt.Println("The computer generated sequence is:") +printht(Ai) +fmt.Println() +a1=rand.Intn(2) +a2=rand.Intn(2) +a3=rand.Intn(2) +fmt.Print("The generated sequence is:") +printh(a1) +printh(a2) +printh(a3) +match=0 +for match==0{ +if(matches(user,a1,a2,a3)==1){ +fmt.Println() +fmt.Println("You have won!!!") +match=1 +}else if(matches(Ai,a1,a2,a3)==1){ +fmt.Println() +fmt.Println("You lost!! Computer wins") +match=1 +}else{ +a1=a2 +a2=a3 +a3=rand.Intn(2) +printh(a3) +} +} +fmt.Println("Do you want to continue(0/1):") +fmt.Scanln(&y) +} +} +func printht(a [3] int) int{ +var i int +for i=0;i<3;i++{ +if(a[i]==1){ +fmt.Print("h") +}else{ +fmt.Print("t") +} +} +return 1 +} +func printh(a int) int{ +if(a==1){ +fmt.Print("h") +}else{ +fmt.Print("t") +} +return 1 +} +func matches(a [3] int,p int,q int,r int) int{ +if(a[0]==p&&a[1]==q&&a[2]==r){ +return 1 +}else{ +return 0 +} +} diff --git a/Task/Penneys-game/Lua/penneys-game.lua b/Task/Penneys-game/Lua/penneys-game.lua new file mode 100644 index 0000000000..c6d4ad434c --- /dev/null +++ b/Task/Penneys-game/Lua/penneys-game.lua @@ -0,0 +1,88 @@ +function penny_game() + local player, computer = "", "" + function player_choose() + io.write( "Enter your sequence of three H and/or T: " ) + local t = io.read():upper() + if #t > 3 then t = t:sub( 1, 3 ) + elseif #t < 3 then return "" + end + + for i = 1, 3 do + c = t:sub( i, i ) + if c ~= "T" and c ~= "H" then + print( "Just H's and T's!" ) + return "" + end + end + return t + end + function computer_choose() + local t = "" + if #player > 0 then + if player:sub( 2, 2 ) == "T" then + t = "H" + else + t = "T"; + end + t = t .. player:sub( 1, 2 ) + else + for i = 1, 3 do + if math.random( 2 ) == 1 then + t = t .. "H" + else + t = t .. "T" + end + end + end + return t + end + if math.random( 2 ) == 1 then + computer = computer_choose() + io.write( "My sequence is: " .. computer .. "\n" ) + while( true ) do + player = player_choose() + if player:len() == 3 then break end + end + else + while( true ) do + player = player_choose() + if player:len() == 3 then break end + end + computer = computer_choose() + io.write( "My sequence is: " .. computer .. "\n" ) + end + local coin, i = "", 1 + while( true ) do + if math.random( 2 ) == 1 then + coin = coin .. "T" + io.write( "T" ) + else + coin = coin .. "H" + io.write( "H" ) + end + if #coin > 2 then + local seq = coin:sub( i, i + 2 ) + i = i + 1 + if seq == player then + print( "\nPlayer WINS!!!" ) + return 1 + elseif seq == computer then + print( "\nComputer WINS!!!" ) + return -1 + end + end + end +end +math.randomseed( os.time() ) +local cpu, user = 0, 0 +repeat + r = penny_game() + if r > 0 then + user = user + 1 + else + cpu = cpu + 1 + end + print( "Player: " .. user .. " CPU: " .. cpu ) + io.write( "Play again (Y/N)? " ) + r = io.read() +until( r == "N" or r == "n" ) diff --git a/Task/Penneys-game/Zkl/penneys-game.zkl b/Task/Penneys-game/Zkl/penneys-game.zkl new file mode 100644 index 0000000000..5c9df51613 --- /dev/null +++ b/Task/Penneys-game/Zkl/penneys-game.zkl @@ -0,0 +1,18 @@ +fcn coinToss{ (0).random(2) and "H" or "T" } // (0).random(2) --> 0<=r<2 +reg myBet, yourBet; +if(coinToss()=="H"){ // The toss says I go first + myBet=(3).pump(String,coinToss); + println("I bet ",myBet); + yourBet=ask("Your bet of three (H/T): ")[0,3].toUpper(); +}else{ + yourBet=ask("Your bet of three (H/T): ")[0,3].toUpper(); + myBet=((yourBet[1]=="H") and "T" or "H") + yourBet[0,2]; + println("I bet ",myBet); +} +print("Flipping: "); coins:=""; +while(1){ + print(toss:=coinToss()); coins=coins + toss; + if(Void!=coins.find(yourBet)){ println(" You win!"); break; } + if(Void!=coins.find(myBet)) { println(" I win!"); break; } + // ignore we both won +} diff --git a/Task/Percentage-difference-between-images/Go/percentage-difference-between-images-3.go b/Task/Percentage-difference-between-images/Go/percentage-difference-between-images-3.go deleted file mode 100644 index 601dd08995..0000000000 --- a/Task/Percentage-difference-between-images/Go/percentage-difference-between-images-3.go +++ /dev/null @@ -1,26 +0,0 @@ -import Bitmap -import Bitmap.Netpbm -import Bitmap.RGB - -import Control.Monad -import Control.Monad.ST -import System.Environment (getArgs) - -main = do - [path1, path2] <- getArgs - image1 <- readNetpbm path1 - image2 <- readNetpbm path2 - diff <- stToIO $ imageDiff image1 image2 - putStrLn $ "Difference: " ++ show (100 * diff) ++ "%" - -imageDiff :: Image s RGB -> Image s RGB -> ST s Double -imageDiff image1 image2 = do - i1 <- getPixels image1 - i2 <- getPixels image2 - unless (length i1 == length i2) $ - fail "imageDiff: Images are of different sizes" - return $ - toEnum (sum $ zipWith minus i1 i2) / - toEnum (3 * 255 * length i1) - where (RGB (r1, g1, b1)) `minus` (RGB (r2, g2, b2)) = - abs (r1 - r2) + abs (g1 - g2) + abs (b1 - b2) diff --git a/Task/Percentage-difference-between-images/Swift/percentage-difference-between-images.swift b/Task/Percentage-difference-between-images/Swift/percentage-difference-between-images.swift new file mode 100644 index 0000000000..7d55d61d99 --- /dev/null +++ b/Task/Percentage-difference-between-images/Swift/percentage-difference-between-images.swift @@ -0,0 +1,54 @@ +func pixelValues(fromCGImage imageRef: CGImage?) -> [UInt8]? +{ + var width = 0 + var height = 0 + var pixelValues: [UInt8]? + + if let imageRef = imageRef { + width = imageRef.width + height = imageRef.height + let bitsPerComponent = imageRef.bitsPerComponent + let bytesPerRow = imageRef.bytesPerRow + let totalBytes = height * bytesPerRow + let bitmapInfo = imageRef.bitmapInfo + + let colorSpace = CGColorSpaceCreateDeviceRGB() + var intensities = [UInt8](repeating: 0, count: totalBytes) + + let contextRef = CGContext(data: &intensities, + width: width, + height: height, + bitsPerComponent: bitsPerComponent, + bytesPerRow: bytesPerRow, + space: colorSpace, + bitmapInfo: bitmapInfo.rawValue) + contextRef?.draw(imageRef, in: CGRect(x: 0.0, y: 0.0, width: CGFloat(width), height: CGFloat(height))) + + pixelValues = intensities + } + + return pixelValues +} + +func compareImages(image1: UIImage, image2: UIImage) -> Double? { + guard let data1 = pixelValues(fromCGImage: image1.cgImage), + let data2 = pixelValues(fromCGImage: image2.cgImage), + data1.count == data2.count else { + return nil + } + + let width = Double(image1.size.width) + let height = Double(image1.size.height) + + return zip(data1, data2) + .enumerated() + .reduce(0.0) { + $1.offset % 4 == 3 ? $0 : $0 + abs(Double($1.element.0) - Double($1.element.1)) + } + * 100 / (width * height * 3.0) / 255.0 +} + +let image1 = UIImage(named: "Lenna50") +let image2 = UIImage(named: "Lenna100") + +compareImages(image1: image1, image2: image2) diff --git a/Task/Percentage-difference-between-images/Zkl/percentage-difference-between-images-1.zkl b/Task/Percentage-difference-between-images/Zkl/percentage-difference-between-images-1.zkl new file mode 100644 index 0000000000..6200d07a7b --- /dev/null +++ b/Task/Percentage-difference-between-images/Zkl/percentage-difference-between-images-1.zkl @@ -0,0 +1,7 @@ +fcn imageDiff(img1,img2){ + if(img1.w!=img2.w or img1.h!=img2.h) + throw(Exception.ValueError("width/height of the images must match!")); + img1.data.howza(0).walker().zip(img2.data.howza(0)) // lazy bytes, not strings + .reduce(fcn(totalDiff,[(a,b)]){ totalDiff + (a - b).abs() },0) + .toFloat()/img1.w/img1.h/3/255; // or: .toFloat()/img1.data.len()/255 +} diff --git a/Task/Percentage-difference-between-images/Zkl/percentage-difference-between-images-2.zkl b/Task/Percentage-difference-between-images/Zkl/percentage-difference-between-images-2.zkl new file mode 100644 index 0000000000..e6548f9788 --- /dev/null +++ b/Task/Percentage-difference-between-images/Zkl/percentage-difference-between-images-2.zkl @@ -0,0 +1,6 @@ +fcn readJPG2PPM(fileName){ + p:=System.popen("convert \"%s\" ppm:-".fmt(fileName),"r"); + img:=PPM.readPPM(p); + p.close(); + img +} diff --git a/Task/Percentage-difference-between-images/Zkl/percentage-difference-between-images-3.zkl b/Task/Percentage-difference-between-images/Zkl/percentage-difference-between-images-3.zkl new file mode 100644 index 0000000000..4d4c6b639b --- /dev/null +++ b/Task/Percentage-difference-between-images/Zkl/percentage-difference-between-images-3.zkl @@ -0,0 +1,2 @@ +imageDiff(readJPG2PPM("lenna50.jpg"),readJPG2PPM("lenna100.jpg")) : +"Image difference = %f%%".fmt(_*100).println(); diff --git a/Task/Percentage-difference-between-images/Zkl/percentage-difference-between-images-4.zkl b/Task/Percentage-difference-between-images/Zkl/percentage-difference-between-images-4.zkl new file mode 100644 index 0000000000..5f441a4c92 --- /dev/null +++ b/Task/Percentage-difference-between-images/Zkl/percentage-difference-between-images-4.zkl @@ -0,0 +1,3 @@ +println("Image difference = %f%%".fmt( + imageDiff(readJPG2PPM("lenna50.jpg"),readJPG2PPM("lenna100.jpg")) * 100) +); diff --git a/Task/Percolation-Bond-percolation/Haskell/percolation-bond-percolation.hs b/Task/Percolation-Bond-percolation/Haskell/percolation-bond-percolation.hs new file mode 100644 index 0000000000..0ee0bb07e9 --- /dev/null +++ b/Task/Percolation-Bond-percolation/Haskell/percolation-bond-percolation.hs @@ -0,0 +1,121 @@ +{-# LANGUAGE OverloadedStrings #-} +import Control.Monad +import Control.Monad.Random +import Data.Array.Unboxed +import Data.List +import Formatting + +data Field = Field { f :: UArray (Int, Int) Char + , hWall :: UArray (Int, Int) Bool + , vWall :: UArray (Int, Int) Bool + } + +-- Start percolating some seepage through a field. +-- Recurse to continue percolation with new seepage. +percolateR :: [(Int, Int)] -> Field -> (Field, [(Int,Int)]) +percolateR [] (Field f h v) = (Field f h v, []) +percolateR seep (Field f h v) = + let ((xLo,yLo),(xHi,yHi)) = bounds f + validSeep = filter (\p@(x,y) -> x >= xLo + && x <= xHi + && y >= yLo + && y <= yHi + && f!p == ' ') $ nub $ sort seep + + north (x,y) = if v ! (x ,y ) then [] else [(x ,y-1)] + south (x,y) = if v ! (x ,y+1) then [] else [(x ,y+1)] + west (x,y) = if h ! (x ,y ) then [] else [(x-1,y )] + east (x,y) = if h ! (x+1,y ) then [] else [(x+1,y )] + neighbors (x,y) = north(x,y) ++ south(x,y) ++ west(x,y) ++ east(x,y) + + in percolateR + (concatMap neighbors validSeep) + (Field (f // map (\p -> (p,'.')) validSeep) h v) + +-- Percolate a field; Return the percolated field. +percolate :: Field -> Field +percolate start@(Field f _ _) = + let ((_,_),(xHi,_)) = bounds f + (final, _) = percolateR [(x,0) | x <- [0..xHi]] start + in final + +-- Generate a random field. +initField :: Int -> Int -> Double -> Rand StdGen Field +initField width height threshold = do + let f = listArray ((0,0), (width-1, height-1)) $ repeat ' ' + + hrnd <- fmap ( getRandoms + let h0 = listArray ((0,0),(width, height-1)) hrnd + h1 = h0 // [((0,y), True) | y <- [0..height-1]] -- close left + h2 = h1 // [((width,y), True) | y <- [0..height-1]] -- close right + + vrnd <- fmap ( getRandoms + let v0 = listArray ((0,0),(width-1, height)) vrnd + v1 = v0 // [((x,0), True) | x <- [0..width-1]] -- close top + + return $ Field f h2 v1 + +-- Assess whether or not percolation reached bottom of field. +leaks :: Field -> [Bool] +leaks (Field f _ v) = + let ((xLo,_),(xHi,yHi)) = bounds f + in [f!(x,yHi)=='.' && not (v!(x,yHi+1)) | x <- [xLo..xHi]] + +-- Run test once; Return bool indicating success or failure. +oneTest :: Int -> Int -> Double -> Rand StdGen Bool +oneTest width height threshold = + or.leaks.percolate <$> initField width height threshold + +-- Run test multple times; Return the number of tests that pass. +multiTest :: Int -> Int -> Int -> Double -> Rand StdGen Double +multiTest testCount width height threshold = do + results <- replicateM testCount $ oneTest width height threshold + let leakyCount = length $ filter id results + return $ fromIntegral leakyCount / fromIntegral testCount + +-- Helper function for display +alternate :: [a] -> [a] -> [a] +alternate [] _ = [] +alternate (a:as) bs = a : alternate bs as + +-- Display a field with walls and leaks. +showField :: Field -> IO () +showField field@(Field a h v) = do + let ((xLo,yLo),(xHi,yHi)) = bounds a + fLines = [ [ a!(x,y) | x <- [xLo..xHi]] | y <- [yLo..yHi]] + hLines = [ [ if h!(x,y) then '|' else ' ' | x <- [xLo..xHi+1]] | y <- [yLo..yHi]] + vLines = [ [ if v!(x,y) then '-' else ' ' | x <- [xLo..xHi]] | y <- [yLo..yHi+1]] + lattice = [ [ '+' | x <- [xLo..xHi+1]] | y <- [yLo..yHi+1]] + + hDrawn = zipWith alternate hLines fLines + vDrawn = zipWith alternate lattice vLines + mapM_ putStrLn $ alternate vDrawn hDrawn + + let leakLine = [ if l then '.' else ' ' | l <- leaks field] + putStrLn $ alternate (repeat ' ') leakLine + +main :: IO () +main = do + g <- getStdGen + let threshold = 0.45 + (startField, g2) = runRand (initField 10 10 threshold) g + + putStrLn ("Unpercolated field with " ++ show threshold ++ " threshold.") + putStrLn "" + showField startField + + putStrLn "" + putStrLn "Same field after percolation." + putStrLn "" + showField $ percolate startField + + let testCount = 10000 + densityCount = 10 + putStrLn "" + putStrLn ("Results of running percolation test " ++ show testCount ++ " times with thresholds ranging from 0/" ++ show densityCount ++ " to " ++ show densityCount ++ "/" ++ show densityCount ++ " .") + let densities = [0..densityCount] + let tests = sequence [multiTest testCount 10 10 v + | density <- densities, + let v = fromIntegral density / fromIntegral densityCount ] + let results = zip densities (evalRand tests g2) + mapM_ print [format ("p=" % int % "/" % int % " -> " % fixed 4) density densityCount x | (density,x) <- results] diff --git a/Task/Percolation-Bond-percolation/Perl-6/percolation-bond-percolation.pl6 b/Task/Percolation-Bond-percolation/Perl-6/percolation-bond-percolation.pl6 new file mode 100644 index 0000000000..16feb81f6e --- /dev/null +++ b/Task/Percolation-Bond-percolation/Perl-6/percolation-bond-percolation.pl6 @@ -0,0 +1,72 @@ +my @bond; +my $grid = 10; +my $geom = $grid - 1; +my $water = '▒'; + +enum Direction ; + +say 'Sample percolation at .6'; +percolate .6; +.join.say for @bond; +say "\n"; + +my $tests = 100; +say "Doing $tests trials at each porosity:"; +for .1, .2 ... 1 -> $p { + printf "p = %0.1f: %0.2f\n", $p, (sum percolate($p) xx $tests) / $tests +} + +sub percolate ( $prob ) { + generate $prob; + my @stack; + my $current = [1;0]; + $current.&fill; + + loop { + if my $dir = direction( $current ) { + @stack.push: $current; + $current = move $dir, $current + } + else { + return 0 unless @stack; + $current = @stack.pop + } + return 1 if $current[1] == +@bond - 1 + } + + sub direction( [$x, $y] ) { + ( Down if @bond[$y + 1][$x].contains: ' ' ) || + ( Left if @bond[$y][$x - 1].contains: ' ' ) || + ( Right if @bond[$y][$x + 1].contains: ' ' ) || + ( Up if @bond[$y - 1][$x].defined && @bond[$y - 1][$x].contains: ' ' ) || + DeadEnd + } + + sub move ( $dir, @cur ) { + my ( $x, $y ) = @cur; + given $dir { + when Up { [$x,--$y].&fill xx 2 } + when Down { [$x,++$y].&fill xx 2 } + when Left { [--$x,$y].&fill xx 2 } + when Right { [++$x,$y].&fill xx 2 } + } + [$x, $y] + } + + sub fill ( [$x, $y] ) { @bond[$y;$x].=subst(' ', $water, :g) } +} + +sub generate ( $prob = .5 ) { + @bond = (); + my $sp = ' '; + append @bond, [flat '│', ($sp, ' ') xx $geom, $sp, '│'], + [flat '├', (h(), '┬') xx $geom, h(), '┤']; + append @bond, [flat '│', ($sp, v()) xx $geom, $sp, '│'], + [flat '├', (h(), '┼') xx $geom, h(), '┤'] for ^$geom; + append @bond, [flat '│', ($sp, v()) xx $geom, $sp, '│'], + [flat '├', (h(), '┴') xx $geom, h(), '┤'], + [flat '│', ($sp, ' ') xx $geom, $sp, '│']; + + sub h () { rand < $prob ?? $sp !! '───' } + sub v () { rand < $prob ?? ' ' !! '│' } +} diff --git a/Task/Percolation-Bond-percolation/Zkl/percolation-bond-percolation-1.zkl b/Task/Percolation-Bond-percolation/Zkl/percolation-bond-percolation-1.zkl new file mode 100644 index 0000000000..c397867bc6 --- /dev/null +++ b/Task/Percolation-Bond-percolation/Zkl/percolation-bond-percolation-1.zkl @@ -0,0 +1,46 @@ +// cell states +const FILLED=1; // and odd +const RWALL =2; // right wall +const BWALL =4; // bottom wall +fcn P(p,wall){ (0.0).random(1)
     aleph   1/5.0
    @@ -11,3 +11,7 @@ he      1/9.0
     waw     1/10.0
     zayin   1/11.0
     heth    1759/27720 # adjusted so that probabilities add to 1
    + +;Related task: +* [[Random number generator (device)]] +

    diff --git a/Task/Probabilistic-choice/Haskell/probabilistic-choice.hs b/Task/Probabilistic-choice/Haskell/probabilistic-choice.hs index b0e706deb6..d1e7ba180d 100644 --- a/Task/Probabilistic-choice/Haskell/probabilistic-choice.hs +++ b/Task/Probabilistic-choice/Haskell/probabilistic-choice.hs @@ -1,20 +1,26 @@ -import System.Random -import Data.List -import Control.Monad -import Control.Arrow +import System.Random (newStdGen, randomRs) -labels = ["aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth" ] -piv n = take n . (++ repeat ' ') +dataBinCounts :: [Float] -> [Float] -> [Int] +dataBinCounts thresholds range = + let sampleSize = length range + xs = ((-) sampleSize . length . flip filter range . (<)) <$> thresholds + in zipWith (-) (xs ++ [sampleSize]) (0 : xs) +main :: IO () main = do g <- newStdGen - let rs,ps :: [Float] - rs = take 1000000 $ randomRs(0,1) g - ps = ap (++) (return. (1 -) .sum) $ map recip [5..11] - sps = scanl1 (+) ps - qs = (\xs -> map ((/1000000.0).fromIntegral.length. flip filter xs. (==))sps) - $ map (head . flip dropWhile sps . (>)) rs - putStrLn $ " expected actual" - mapM_ putStrLn $ zipWith3 - (\l s c-> (piv 7 l) ++ (piv 13 $ show $ s) - ++(piv 12 $ show $ c)) labels ps qs + let fractions = recip <$> [5 .. 11] :: [Float] + expected = fractions ++ [1 - sum fractions] + actual = + ((/ 1000000.0) . fromIntegral) <$> + dataBinCounts (scanl1 (+) expected) (take 1000000 (randomRs (0, 1) g)) + + piv n = take n . (++ repeat ' ') + + putStrLn " expected actual" + mapM_ putStrLn $ + zipWith3 + (\l s c -> piv 7 l ++ piv 13 (show s) ++ piv 12 (show c)) + ["aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"] + expected + actual diff --git a/Task/Probabilistic-choice/JavaScript/probabilistic-choice.js b/Task/Probabilistic-choice/JavaScript/probabilistic-choice-1.js similarity index 100% rename from Task/Probabilistic-choice/JavaScript/probabilistic-choice.js rename to Task/Probabilistic-choice/JavaScript/probabilistic-choice-1.js diff --git a/Task/Probabilistic-choice/JavaScript/probabilistic-choice-2.js b/Task/Probabilistic-choice/JavaScript/probabilistic-choice-2.js new file mode 100644 index 0000000000..b39adb627f --- /dev/null +++ b/Task/Probabilistic-choice/JavaScript/probabilistic-choice-2.js @@ -0,0 +1,106 @@ +(() => { + 'use strict'; + + // GENERIC FUNCTIONS ----------------------------------------------------- + + // transpose :: [[a]] -> [[a]] + const transpose = xs => + xs[0].map((_, iCol) => xs.map(row => row[iCol])); + + // justifyLeft :: Int -> Char -> Text -> Text + const justifyLeft = (n, cFiller, strText) => + n > strText.length ? ( + (strText + cFiller.repeat(n)) + .substr(0, n) + ) : strText; + + // 2 or more arguments + // curry :: Function -> Function + const curry = (f, ...args) => { + const go = xs => xs.length >= f.length ? (f.apply(null, xs)) : + function () { + return go(xs.concat([].slice.apply(arguments))); + }; + return go([].slice.call(args, 1)); + }; + + // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] + const zipWith = (f, xs, ys) => { + const ny = ys.length; + return (xs.length <= ny ? xs : xs.slice(0, ny)) + .map((x, i) => f(x, ys[i])); + }; + + // subtract :: (Num a) => a -> a -> a + const subtract = (x, y) => y - x; + + // scanl1 :: (a -> a -> a) -> [a] -> [a] + const scanl1 = (f, xs) => + xs.length > 0 ? scanl(f, xs[0], xs.slice(1)) : []; + + // scanl :: (b -> a -> b) -> b -> [a] -> [b] + const scanl = (f, startValue, xs) => + xs.reduce((a, x) => { + const v = f(a.acc, x); + return { + acc: v, + scan: a.scan.concat(v) + }; + }, { + acc: startValue, + scan: [startValue] + }) + .scan; + + // unwords :: [String] -> String + const unwords = xs => xs.join(' '); + + + // PROBABILISTIC CHOICE -------------------------------------------------- + + // samples :: Int -> Int -> [Float] + const samples = n => + Array.from({ + length: n + }, Math.random); + + // thresholds :: Float + const thresholds = scanl1( + (a, b) => a + b, [5, 6, 7, 8, 9, 10, 11].map(x => 1 / x) + ) + .concat(1); + + // expected :: Float -> Float + const expected = limits => + limits.map((x, i, xs) => i > 0 ? (x - xs[i - 1]) : x); + + // dataBinCounts :: [Float] -> [Float] -> [Int] + const dataBinCounts = (thresholds, samples) => { + const + lng = samples.length, + xs = thresholds + .map(x => lng - samples.filter(v => v > x) + .length); + return zipWith(subtract, [0].concat(xs), xs.concat(lng)); + }; + + // intSamples :: Integer + const intSamples = 1000000; + + // aligned :: a -> String + const aligned = x => justifyLeft(12, ' ', isNaN(x) ? x : x.toFixed(7)); + + return transpose([ + ['', 'Aleph', 'Beit', 'Gimel', 'Dalet', 'He', 'Vav', 'Zayin', 'Chet'] + .map(curry(justifyLeft)(7, ' ')), + + ['Expected'].concat(expected(thresholds)) + .map(aligned), + + ['Observed'].concat(dataBinCounts(thresholds, samples(intSamples)) + .map(x => x / intSamples)) + .map(aligned) + ]) + .map(unwords) + .join('\n'); +})(); diff --git a/Task/Probabilistic-choice/Kotlin/probabilistic-choice.kotlin b/Task/Probabilistic-choice/Kotlin/probabilistic-choice.kotlin new file mode 100644 index 0000000000..f01b9c1ecb --- /dev/null +++ b/Task/Probabilistic-choice/Kotlin/probabilistic-choice.kotlin @@ -0,0 +1,38 @@ +// version 1.0.6 + +fun main(args: Array) { + val letters = arrayOf("aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth") + val actual = IntArray(8) + val probs = doubleArrayOf(1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 0.0) + val cumProbs = DoubleArray(8) + + cumProbs[0] = probs[0] + for (i in 1..6) cumProbs[i] = cumProbs[i - 1] + probs[i] + cumProbs[7] = 1.0 + probs[7] = 1.0 - cumProbs[6] + val n = 1000000 + (1..n).forEach { + val rand = Math.random() + when { + rand <= cumProbs[0] -> actual[0]++ + rand <= cumProbs[1] -> actual[1]++ + rand <= cumProbs[2] -> actual[2]++ + rand <= cumProbs[3] -> actual[3]++ + rand <= cumProbs[4] -> actual[4]++ + rand <= cumProbs[5] -> actual[5]++ + rand <= cumProbs[6] -> actual[6]++ + else -> actual[7]++ + } + } + + var sumActual = 0.0 + println("Letter\t Actual Expected") + println("------\t-------- --------") + for (i in 0..7) { + val generated = actual[i].toDouble() / n + println("${letters[i]}\t${String.format("%8.6f %8.6f", generated, probs[i])}") + sumActual += generated + } + println("\t-------- --------") + println("\t${"%8.6f".format(sumActual)} 1.000000") +} diff --git a/Task/Probabilistic-choice/Nimrod/probabilistic-choice.nimrod b/Task/Probabilistic-choice/Nimrod/probabilistic-choice.nimrod deleted file mode 100644 index 55390813ab..0000000000 --- a/Task/Probabilistic-choice/Nimrod/probabilistic-choice.nimrod +++ /dev/null @@ -1,47 +0,0 @@ -import tables, math, strutils, times - -const - num_trials = 1000000 - precsn = 6 - -var start = cpuTime() - -var probs = initTable[string,float](16) -probs.add("aleph", 1/5.0) -probs.add("beth", 1/6.0) -probs.add("gimel", 1/7.0) -probs.add("daleth", 1/8.0) -probs.add("he", 1/9.0) -probs.add("waw", 1/10.0) -probs.add("zayin", 1/11.0) -probs.add("heth", 1759/27720) - -var samples = initTable[string,int](16) -for i, j in pairs(probs): - samples.add(i,0) - -randomize() -for i in 1 .. num_trials: - var z = random(1.0) - - for j,k in pairs(probs): - if z < probs[j]: - samples[j] = samples[j] + 1 - break - else: - z = z - probs[j] - -var s1, s2: float - -echo("Item ","\t","Target ","\t","Results ","\t","Difference") -echo("==== ","\t","====== ","\t","======= ","\t","==========") -for i, j in pairs(probs): - s1 += samples[i]/num_trials*100.0 - s2 += probs[i]*100.0 - echo( i, - "\t", formatFloat(probs[i],ffDecimal,precsn), - "\t", formatFloat(samples[i]/num_trials,ffDecimal,precsn), - "\t", formatFloat(100.0*(1.0-(samples[i]/num_trials)/probs[i]),ffDecimal,precsn),"%") -echo("======","\t","======= ","\t","======== ") -echo("Total:","\t",formatFloat(s2,ffDecimal,2)," \t",formatFloat(s1,ffDecimal,2)) -echo("\n",formatFloat(cpuTime()-start,ffDecimal,2)," secs") diff --git a/Task/Probabilistic-choice/PowerShell/probabilistic-choice.psh b/Task/Probabilistic-choice/PowerShell/probabilistic-choice.psh new file mode 100644 index 0000000000..5f8093a387 --- /dev/null +++ b/Task/Probabilistic-choice/PowerShell/probabilistic-choice.psh @@ -0,0 +1,46 @@ +$character = [PSCustomObject]@{ + aleph = [PSCustomObject]@{Expected=1/5 ; Alpha="א"} + beth = [PSCustomObject]@{Expected=1/6 ; Alpha="ב"} + gimel = [PSCustomObject]@{Expected=1/7 ; Alpha="ג"} + daleth = [PSCustomObject]@{Expected=1/8 ; Alpha="ד"} + he = [PSCustomObject]@{Expected=1/9 ; Alpha="ה"} + waw = [PSCustomObject]@{Expected=1/10 ; Alpha="ו"} + zayin = [PSCustomObject]@{Expected=1/11 ; Alpha="ז"} + heth = [PSCustomObject]@{Expected=1759/27720; Alpha="ח"} +} + +$sum = 0 +$iterations = 1000000 +$cumulative = [ordered]@{} +$randomly = [ordered]@{} + +foreach ($name in $character.PSObject.Properties.Name) +{ + $sum += $character.$name.Expected + $cumulative.$name = $sum + $randomly.$name = 0 +} + +for ($i = 0; $i -lt $iterations; $i++) +{ + $random = Get-Random -Minimum 0.0 -Maximum 1.0 + + foreach ($name in $cumulative.Keys) + { + if ($random -le $cumulative.$name) + { + $randomly.$name++ + break + } + } +} + +foreach ($name in $character.PSObject.Properties.Name) +{ + [PSCustomObject]@{ + Name = $name + Expected = $character.$name.Expected + Actual = $randomly.$name / $iterations + Character = $character.$name.Alpha + } +} diff --git a/Task/Probabilistic-choice/REXX/probabilistic-choice.rexx b/Task/Probabilistic-choice/REXX/probabilistic-choice.rexx index fdcc53f1d0..88b19523c3 100644 --- a/Task/Probabilistic-choice/REXX/probabilistic-choice.rexx +++ b/Task/Probabilistic-choice/REXX/probabilistic-choice.rexx @@ -1,32 +1,30 @@ /*REXX program displays results of probabilistic choices, gen random #s per probability.*/ -parse arg trials digits seed . /*obtain the optional arguments from CL*/ +parse arg trials digs seed . /*obtain the optional arguments from CL*/ if trials=='' | trials=="," then trials=1000000 /*Not specified? Then use the default.*/ -if digits=='' | digits=="," then digits=15 /* " " " " " " */ -if datatype(seed,'W') then call random ,,seed /*allows repeatability for RANDOM nums.*/ -names= 'aleph beth gimel daleth he waw zayin heth ──totals───►' -cells=words(names) - 1; high=100000; s=0; !.=0 -_=4 - do n=1 for 7; _=_+1; prob.n=1/_; Hprob.n=prob.n*high; s=s+prob.n - end /*n*/ /* [↑] determine the probabilities. */ +if digs=='' | digs=="," then digs=15 /* " " " " " " */ +if datatype(seed, 'W') then call random ,,seed /*allows repeatability for RANDOM nums.*/ +numeric digits digs /*use a specific number of decimal digs*/ +names= 'aleph beth gimel daleth he waw zayin heth ───totals───►' /*names of cells.*/ +#= words(names) - 1; s=0 +HI=100000 + do n=1 for #-1; prob.n=1 / (n+4); Hprob.n=prob.n * HI; s=s + prob.n + end /*n*/ +!.=0 +prob.#=1759/27720; !.9=trials; Hprob.#=prob.# * HI; s=s + prob.# +prob.9=s + do j=1 for trials; r=random(1, HI) /*generate X number of random numbers.*/ + do k=1 for # /*for each cell, compute percentages. */ + if r<=Hprob.k then !.k=!.k + 1 /* " " " range, bump the counter*/ + end /*k*/ + end /*j*/ +@= '═' /*@: a literal used for CENTER BIF pad*/ +w=digs +6 /*W: display width for the percentages*/ +d=4 + max( length(trials), length('count') ) /* [↓] display a formatted top header.*/ +say center('name',15,@) center('count',d,@) center('target %',w,@) center('actual %',w,@) -prob.8=1759/27720; Hprob.8=prob.8*high; s=s+prob.8; prob.9=s; !.9=trials - - do j=1 for trials; r=random(1, high) /*generate X number of random numbers.*/ - do k=1 for cells /*for each cell, compute percentages. */ - if r<=Hprob.k then !.k=!.k+1 /*for each range, bump the counter. */ - end /*k*/ - end /*j*/ - -w=digits+6; d=max(length(trials), length('count')) + 4 -say centr('name',15) centr('count',d) centr('target %') centr('actual %') - /* [↑] display a formatted header line*/ - do i=1 for cells+1 /*show for each of the cells and totals*/ - say ' ' left(word(names,i) , 12), - right(!.i , d-2) " ", - left(format(prob.i *100, d), w-2), - left(format(!.i/trials*100, d), w-2) - if i==8 then say centr(,15) centr(,d) centr() centr() - end /*i*/ -exit /*stick a fork in it, we are all done.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -centr: return center( arg(1), word(arg(2) w, 1), '─') + do i=1 for #+1 /*display each of the cells and totals.*/ + say ' ' left( word(names, i), 13) right(!.i, d-2) " ", + left( format( prob.i * 100, d), w-2), + left( format( !.i/trials * 100, d), w-2) + if i==# then say center(@,15,@) center(@,d,@) center(@,w,@) center(@,w,@) + end /*i*/ /*stick a fork in it, we are all done.*/ diff --git a/Task/Probabilistic-choice/Zkl/probabilistic-choice.zkl b/Task/Probabilistic-choice/Zkl/probabilistic-choice.zkl new file mode 100644 index 0000000000..3ede7b65c1 --- /dev/null +++ b/Task/Probabilistic-choice/Zkl/probabilistic-choice.zkl @@ -0,0 +1,22 @@ +var names=T("aleph", "beth", "gimel", "daleth", + "he", "waw", "zayin", "heth"); +var ptable=T(5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0).apply('/.fp(1.0)); +ptable=ptable.append(1.0-ptable.sum(0.0)); // add last weight to sum to 1.0 +var [const] N=ptable.len(); + +fcn ridx{ i:=0; s:=(0.0).random(1); + while((s-=ptable[i]) > 0) { i+=1 } + i +} + +const M=0d1_000_000; +var r=(0).pump(N,List,T(Ref,0)); // list of references to int 0 +(0).pump(M,Void,fcn{r[ridx()].inc()}); // 1,000,000 weighted random #s + +r=r.apply("value").apply("toFloat"); // (reference to int)-->int-->float + +println(" Name Count Ratio Expected"); +foreach i in (N){ + "%6s%7d %7.4f%% %7.4f%%".fmt(names[i], r[i], r[i]/M*100, + ptable[i]*100).println(); +} diff --git a/Task/Problem-of-Apollonius/jq/problem-of-apollonius-1.jq b/Task/Problem-of-Apollonius/Jq/problem-of-apollonius-1.jq similarity index 100% rename from Task/Problem-of-Apollonius/jq/problem-of-apollonius-1.jq rename to Task/Problem-of-Apollonius/Jq/problem-of-apollonius-1.jq diff --git a/Task/Problem-of-Apollonius/jq/problem-of-apollonius-2.jq b/Task/Problem-of-Apollonius/Jq/problem-of-apollonius-2.jq similarity index 100% rename from Task/Problem-of-Apollonius/jq/problem-of-apollonius-2.jq rename to Task/Problem-of-Apollonius/Jq/problem-of-apollonius-2.jq diff --git a/Task/Problem-of-Apollonius/jq/problem-of-apollonius-3.jq b/Task/Problem-of-Apollonius/Jq/problem-of-apollonius-3.jq similarity index 100% rename from Task/Problem-of-Apollonius/jq/problem-of-apollonius-3.jq rename to Task/Problem-of-Apollonius/Jq/problem-of-apollonius-3.jq diff --git a/Task/Problem-of-Apollonius/Kotlin/problem-of-apollonius.kotlin b/Task/Problem-of-Apollonius/Kotlin/problem-of-apollonius.kotlin new file mode 100644 index 0000000000..973bb57924 --- /dev/null +++ b/Task/Problem-of-Apollonius/Kotlin/problem-of-apollonius.kotlin @@ -0,0 +1,53 @@ +// version 1.1.3 + +data class Circle(val x: Double, val y: Double, val r: Double) + +val Double.sq get() = this * this + +fun solveApollonius(c1: Circle, c2: Circle, c3: Circle, + s1: Int, s2: Int, s3: Int): Circle { + val (x1, y1, r1) = c1 + val (x2, y2, r2) = c2 + val (x3, y3, r3) = c3 + + val v11 = 2 * x2 - 2 * x1 + val v12 = 2 * y2 - 2 * y1 + val v13 = x1.sq - x2.sq + y1.sq - y2.sq - r1.sq + r2.sq + val v14 = 2 * s2 * r2 - 2 * s1 * r1 + + val v21 = 2 * x3 - 2 * x2 + val v22 = 2 * y3 - 2 * y2 + val v23 = x2.sq - x3.sq + y2.sq - y3.sq - r2.sq + r3.sq + val v24 = 2 * s3 * r3 - 2 * s2 * r2 + + val w12 = v12 / v11 + val w13 = v13 / v11 + val w14 = v14 / v11 + + val w22 = v22 / v21 - w12 + val w23 = v23 / v21 - w13 + val w24 = v24 / v21 - w14 + + val p = -w23 / w22 + val q = w24 / w22 + val m = -w12 * p - w13 + val n = w14 - w12 * q + + val a = n.sq + q.sq - 1 + val b = 2 * m * n - 2 * n * x1 + 2 * p * q - 2 * q * y1 + 2 * s1 * r1 + val c = x1.sq + m.sq - 2 * m * x1 + p.sq + y1.sq - 2 * p * y1 - r1.sq + + val d = b.sq - 4 * a * c + val rs = (-b - Math.sqrt(d)) / (2 * a) + val xs = m + n * rs + val ys = p + q * rs + return Circle(xs, ys, rs) +} + +fun main(args: Array) { + val c1 = Circle(0.0, 0.0, 1.0) + val c2 = Circle(4.0, 0.0, 1.0) + val c3 = Circle(2.0, 4.0, 2.0) + println(solveApollonius(c1, c2, c3, 1, 1, 1)) + println(solveApollonius(c1, c2, c3,-1,-1,-1)) +} diff --git a/Task/Problem-of-Apollonius/REXX/problem-of-apollonius.rexx b/Task/Problem-of-Apollonius/REXX/problem-of-apollonius.rexx index a52a2a7647..cd1f0500b9 100644 --- a/Task/Problem-of-Apollonius/REXX/problem-of-apollonius.rexx +++ b/Task/Problem-of-Apollonius/REXX/problem-of-apollonius.rexx @@ -1,37 +1,33 @@ -/*REXX program solves the problem of Apollonius, named after the Greek */ -/*──────────────── Apollonius of Perga [Pergæus] (circa 262 BC ──► 190 BC).*/ -w=20; numeric digits w-5 /*the width used to display the numbers*/ - c1.x=0; c1.y=0; c1.r=1 - c2.x=4; c2.y=0; c2.r=1 - c3.x=2; c3.y=4; c3.r=2 -call tell 'external tangent:', Apollonius( 1, 1, 1) -call tell 'internal tangent:', Apollonius(-1, -1, -1) -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -Apollonius: parse arg s1,s2,s3 /*could be an internal/external tangent*/ - numeric digits digits()*3 /*reduce rounding by using 3 times digs*/ - x1=c1.x; x2=c2.x; x3=c3.x - y1=c1.y; y2=c2.y; y3=c3.y - r1=c1.r; r2=c2.r; r3=c3.r - va=2*x2-2*x1; vb=2*y2-2*y1 - vc=x1*x1-x2*x2+y1*y1-y2*y2-r1*r1+r2*r2 - vd=2*s2*r2-2*s1*r1; ve=2*x3-2*x2; vf=2*y3-2*y2 - vg=x2*x2-x3*x3+y2*y2-y3*y3-r2*r2+r3*r3; vh=2*s3*r3-2*s2*r2 - vj=vb/va; vk=vc/va; vm=vd/va; vn=vf/ve-vj - vp=vg/ve-vk; vr=vh/ve-vm; p=-vp/vn; q =vr/vn - m=-vj*p-vk; n=vm-vj*q; a=n*n+q*q-1 - b=2*m*n-2*n*x1+2*p*q-2*q*y1+2*s1*r1 - c=x1*x1+m*m-2*m*x1+p*p+y1*y1-2*p*y1-r1*r1 - _=b*b-4*a*c; $.r=(-b-sqrt(_))/(a+a); $.x=m+n*$.r; $.y=p+q*$.r - numeric digits digits()%3 /*reset DIGITS to the original.*/ - return $.x $.y $.r /*return with 3 args, normalized.*/ -/*────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 - numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ - numeric digits d; return (g/1)i /*make complex if X < 0.*/ -/*────────────────────────────────────────────────────────────────────────────*/ -tell: parse arg _,a b c; say _ left(a/1,w) left(b/1,w) left(c/1,w); return - /*dividing by 1 normalizes the numbers.*/ +/*REXX program solves the problem of Apollonius, named after the Greek Apollonius of */ +/*────────────────────────────────────── Perga [Pergæus] (circa 262 BCE ──► 190 BCE). */ +numeric digits 15; c1.x=0; c1.y=0; c1.r=1 + c2.x=4; c2.y=0; c2.r=1 + c3.x=2; c3.y=4; c3.r=2 +call tell 'external tangent: ', Apollonius( 1, 1, 1) +call tell 'internal tangent: ', Apollonius(-1, -1, -1) +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +Apollonius: parse arg s1,s2,s3 /*could be internal or external tangent*/ + d=digits(); numeric digits d*3 /*reduce rounding, use thrice digits. */ + x1=c1.x; x2=c2.x; x3=c3.x + y1=c1.y; y2=c2.y; y3=c3.y + r1=c1.r; r2=c2.r; r3=c3.r + va=2*x2 - 2*x1; vb=2*y2 - 2*y1 + vc=x1**2 - x2**2 + y1**2 - y2**2 - r1**2 + r2**2 + vd=2*s2*r2 - 2*s1*r1; ve=2*x3 - 2*x2; vf=2*y3 - 2*y2 + vg=x2**2 - x3**2 + y2**2 - y3**2 - r2**2 + r3**2; vh=2*s3*r3 - 2*s2*r2 + vj=vb/va; vk=vc/va; vm=vd/va; vn=vf/ve - vj + vp=vg/ve - vk; vr=vh/ve - vm; p =-vp/vn; q =vr/vn + m=-vj*p - vk; n=vm - vj*q; a=n**2 + q**2 - 1 + b=2*m*n - 2*n*x1 + 2*p*q - 2*q*y1 + 2*s1*r1 + c=x1**2 + m**2 - 2*m*x1 + p**2 + y1**2 - 2*p*y1 - r1**2 + _=b**2 - 4*a*c; $r=(-b - sqrt(_)) / (a+a); $x=m + n*$r; $y=p + q*$r + numeric digits d; return $x $y $r /*return with three arguments. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h=d+6; numeric digits + m.=9; numeric form; 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 +/*──────────────────────────────────────────────────────────────────────────────────────*/ +tell: parse arg _,a b c; w=digits()+4; say _ left(a/1,w%2) left(b/1,w) left(c/1,w); return diff --git a/Task/Problem-of-Apollonius/Zkl/problem-of-apollonius-1.zkl b/Task/Problem-of-Apollonius/Zkl/problem-of-apollonius-1.zkl new file mode 100644 index 0000000000..7cc2f3806b --- /dev/null +++ b/Task/Problem-of-Apollonius/Zkl/problem-of-apollonius-1.zkl @@ -0,0 +1,42 @@ +class Circle{ + fcn init(xpos,ypos,radius){ + var [const] x=xpos.toFloat(), y=ypos.toFloat(),r=radius.toFloat(); + } + fcn toString{ "Circle(%f,%f,%f)".fmt(x,y,r) } + fcn apollonius(c2,c3,outside=True){ + s1:=s2:=s3:=outside and 1 or -1; + + v11:=2.0*(c2.x - x); + v12:=2.0*(c2.y - y); + v13:=x.pow(2) - c2.x.pow(2) + + y.pow(2) - c2.y.pow(2) - + r.pow(2) + c2.r.pow(2); + v14:=2.0*(s2*c2.r - s1*r); + + v21:=2.0*(c3.x - c2.x); + v22:=2.0*(c3.y - c2.y); + v23:=c2.x.pow(2) - c3.x.pow(2) + + c2.y.pow(2) - c3.y.pow(2) - + c2.r.pow(2) + c3.r.pow(2); + v24:=2.0*(s3*c3.r - s2*c2.r); + + w12,w13,w14:=v12/v11, v13/v11, v14/v11; + w22,w23,w24:=v22/v21 - w12, v23/v21 - w13, v24/v21 - w14; + + P:=-w23/w22; + Q:= w24/w22; + M:=-w12*P - w13; + N:= w14 - w12*Q; + + a:=N*N + Q*Q - 1; + b:=2.0*(M*N - N*x + P*Q - Q*y + s1*r); + c:=x*x + M*M - 2.0*M*x + P*P + y*y - 2.0*P*y - r*r; + + // find a root of a quadratic equation. + // This requires the circle centers not to be e.g. colinear + D:=b*b - 4.0*a*c; + rs:=(-b - D.sqrt())/(2.0*a); + + Circle(M + N*rs, P + Q*rs, rs); + } +} diff --git a/Task/Problem-of-Apollonius/Zkl/problem-of-apollonius-2.zkl b/Task/Problem-of-Apollonius/Zkl/problem-of-apollonius-2.zkl new file mode 100644 index 0000000000..9c79f1f006 --- /dev/null +++ b/Task/Problem-of-Apollonius/Zkl/problem-of-apollonius-2.zkl @@ -0,0 +1,3 @@ +a,b,c:=Circle(0,0,1), Circle(4,0,1), Circle(2,4,2); +a.apollonius(b,c).println(" Outside"); +a.apollonius(b,c,False).println(" Inside"); diff --git a/Task/Program-name/AWK/program-name.awk b/Task/Program-name/AWK/program-name.awk new file mode 100644 index 0000000000..45e2ef905a --- /dev/null +++ b/Task/Program-name/AWK/program-name.awk @@ -0,0 +1,18 @@ +# syntax: TAWK -f PROGRAM_NAME.AWK +# +# GAWK can provide the invoking program name from ARGV[0] but is unable to +# provide the AWK script name that follows -f. Thompson Automation's TAWK +# version 5.0c, last released in 1998 and no longer commercially available, can +# provide the AWK script name that follows -f from the PROGFN built-in +# variable. It should also provide the invoking program name, E.G. TAWK, from +# ARGV[0] but due to a bug it holds the fully qualified -f name instead. +# +# This example is posted here with hopes the TAWK built-in variables PROGFN +# (PROGram File Name) and PROGLN (PROGram Line Number) be added to GAWK by its +# developers. +# +BEGIN { + printf("%s -f %s\n",ARGV[0],PROGFN) + printf("line number %d\n",PROGLN) + exit(0) +} diff --git a/Task/Program-name/Elena/program-name.elena b/Task/Program-name/Elena/program-name.elena index 6e79418102..190cff4bfa 100644 --- a/Task/Program-name/Elena/program-name.elena +++ b/Task/Program-name/Elena/program-name.elena @@ -1,8 +1,6 @@ -#import system. - -#symbol program = +program = [ console writeLine:system'commandLine. // the whole command line - console writeLine:('program'arguments@0). // the program name + console writeLine('program'arguments[0]). // the program name ]. diff --git a/Task/Program-name/Gambas/program-name.gambas b/Task/Program-name/Gambas/program-name.gambas new file mode 100644 index 0000000000..35a41dd459 --- /dev/null +++ b/Task/Program-name/Gambas/program-name.gambas @@ -0,0 +1,10 @@ +Public Sub Main() +Dim sTemp As String + +Print "Command to start the program was ";; + +For Each sTemp In Args.All + Print sTemp;; +Next + +End diff --git a/Task/Program-name/Kotlin/program-name.kotlin b/Task/Program-name/Kotlin/program-name.kotlin new file mode 100644 index 0000000000..792b5242e7 --- /dev/null +++ b/Task/Program-name/Kotlin/program-name.kotlin @@ -0,0 +1,8 @@ +// version 1.0.6 + +// 'progname.kt' packaged as 'progname.jar' + +fun main(args: Array) { + println(System.getProperty("sun.java.command")) // may not exist on all JVMs + println(System.getProperty("java.vm.name")) +} diff --git a/Task/Program-name/NewLISP/program-name.newlisp b/Task/Program-name/NewLISP/program-name.newlisp new file mode 100644 index 0000000000..f434978e03 --- /dev/null +++ b/Task/Program-name/NewLISP/program-name.newlisp @@ -0,0 +1,5 @@ +#!/usr/bin/env newlisp + +(let ((program (main-args 1))) + (println (format "Program: %s" program)) + (exit)) diff --git a/Task/Program-name/Scala/program-name-1.scala b/Task/Program-name/Scala/program-name-1.scala deleted file mode 100644 index 9c69b75372..0000000000 --- a/Task/Program-name/Scala/program-name-1.scala +++ /dev/null @@ -1,19 +0,0 @@ -$ scala ScriptName.scala -Program: ScriptName.scala - -$ scalac ScriptName.scala -$ scala -classpath . ScriptName -Program: ScriptName.scala - -$ scala -Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_26). -Type in expressions to have them evaluated. -Type :help for more information. - -scala> :load ScriptName.scala -Loading ScriptName.scala... -import scala.util.matching.Regex.MatchIterator -defined module ScriptName - -scala> ScriptName.main(Array[String]()) -Program: diff --git a/Task/Program-name/Scala/program-name-2.scala b/Task/Program-name/Scala/program-name-2.scala deleted file mode 100644 index 3dc52e2831..0000000000 --- a/Task/Program-name/Scala/program-name-2.scala +++ /dev/null @@ -1,18 +0,0 @@ -import scala.util.matching.Regex.MatchIterator - -object ScriptName { - val program = { - val filenames = new RuntimeException("").getStackTrace.map { t => t.getFileName } - val scala = filenames.indexOf("NativeMethodAccessorImpl.java") - - if (scala == -1) - "" - else - filenames(scala - 1) - } - - def main(args: Array[String]) { - val prog = program - println("Program: " + prog) - } -} diff --git a/Task/Program-name/TXR/program-name.txr b/Task/Program-name/TXR/program-name.txr index 63d2b6dbdb..fe02ce3401 100644 --- a/Task/Program-name/TXR/program-name.txr +++ b/Task/Program-name/TXR/program-name.txr @@ -1,2 +1,2 @@ #!/usr/local/bin/txr -B -@(bind my-name @*self-path*) +@(bind my-name @self-path) diff --git a/Task/Program-name/VBScript/program-name.vb b/Task/Program-name/VBScript/program-name.vb new file mode 100644 index 0000000000..481a83cd1e --- /dev/null +++ b/Task/Program-name/VBScript/program-name.vb @@ -0,0 +1,5 @@ +Wscript.Echo "FullName:",Wscript.FullName +Wscript.Echo "Name:",Wscript.Name +Wscript.Echo "Path:",Wscript.Path +Wscript.Echo "ScriptFullName:",Wscript.ScriptFullName +Wscript.Echo "ScriptName:",Wscript.ScriptName diff --git a/Task/Program-name/X86-Assembly/program-name-1.x86 b/Task/Program-name/X86-Assembly/program-name-1.x86 new file mode 100644 index 0000000000..b562356f63 --- /dev/null +++ b/Task/Program-name/X86-Assembly/program-name-1.x86 @@ -0,0 +1,19 @@ +FORMAT=-f elf +RUN=./ +BIN=scriptname +OBJ=scriptname.o + +all: test + +test: $(BIN) + $(RUN)$(BIN) + +$(BIN): $(OBJ) + ld -o $(BIN) $(OBJ) + +$(OBJ): scriptname.asm + nasm $(FORMAT) -o $(OBJ) scriptname.asm + +clean: + -rm $(BIN) + -rm $(OBJ) diff --git a/Task/Program-name/X86-Assembly/program-name-2.x86 b/Task/Program-name/X86-Assembly/program-name-2.x86 new file mode 100644 index 0000000000..172761c990 --- /dev/null +++ b/Task/Program-name/X86-Assembly/program-name-2.x86 @@ -0,0 +1,72 @@ +bits 32 + +section .data + +stdout equ 1 + +sys_write equ 4 +sys_exit equ 1 + +kernel equ 0x80 + +program db "Program: ", 0 +programlen equ $-program + +nl db "", 10, 0 +nllen equ $-nl + +section .bss + +scriptname resd 1 +scriptnamelen resd 1 + +section .text + +global _start + +strlen: ; eax: a string ending in 0 + push eax ; cache eax + + .strloop: + mov bl, byte [eax] + cmp bl, 0 + je .strret ; return len if bl == 0 + inc eax ; else eax++ + jmp .strloop + + .strret: + pop ebx ; ebx = cached eax + sub eax, ebx ; eax -= ebx + ret ; eax = len + +_start: + mov eax, esp + add eax, 4 + mov eax, [eax] + mov dword [scriptname], eax + + mov eax, sys_write + mov ebx, stdout + mov ecx, program + mov edx, programlen + int kernel + + mov dword eax, [scriptname] + call strlen + mov dword [scriptnamelen], eax + + mov eax, sys_write + mov ebx, stdout + mov dword ecx, [scriptname] + mov dword edx, [scriptnamelen] + int kernel + + mov eax, sys_write + mov ebx, stdout + mov ecx, nl + mov edx, nllen + int kernel + + mov eax, sys_exit + mov ebx, 0 + int kernel diff --git a/Task/Program-name/X86-Assembly/program-name-3.x86 b/Task/Program-name/X86-Assembly/program-name-3.x86 new file mode 100644 index 0000000000..0c9ab5d072 --- /dev/null +++ b/Task/Program-name/X86-Assembly/program-name-3.x86 @@ -0,0 +1,27 @@ +# FreeBSD defaults + +FORMAT=-f elf +RUN=./ +BIN=scriptname +OBJ=scriptname.o + +# Mac OS X +ifeq ($(shell uname -s),Darwin) + FORMAT=-f macho + MINV=-macosx_version_min 10.6 +endif + +all: test + +test: $(BIN) + $(RUN)$(BIN) + +$(BIN): $(OBJ) + ld -o $(BIN) $(MINV) $(OBJ) + +$(OBJ): scriptname.asm + nasm $(FORMAT) -o $(OBJ) scriptname.asm + +clean: + -rm $(BIN) + -rm $(OBJ) diff --git a/Task/Program-name/X86-Assembly/program-name-4.x86 b/Task/Program-name/X86-Assembly/program-name-4.x86 new file mode 100644 index 0000000000..aadca28b8e --- /dev/null +++ b/Task/Program-name/X86-Assembly/program-name-4.x86 @@ -0,0 +1,79 @@ +bits 32 + +section .data + +stdout equ 1 + +sys_write equ 4 +sys_exit equ 1 + +kernel equ 0x80 + +program db "Program: ", 0 +programlen equ $-program + +nl db "", 10, 0 +nllen equ $-nl + +section .bss + +scriptname resd 1 +scriptnamelen resd 1 + +section .text + +global start + +strlen: ; eax: a string ending in 0 + push eax ; cache eax + + .strloop: + mov bl, byte [eax] + cmp bl, 0 + je .strret ; return len if bl == 0 + inc eax ; else eax++ + jmp .strloop + + .strret: + pop ebx ; ebx = cached eax + sub eax, ebx ; eax -= ebx + ret ; eax = len + +start: + mov eax, esp + add eax, 4 + mov eax, [eax] + mov dword [scriptname], eax + + push programlen + push program + push stdout + mov eax, sys_write + sub esp, 4 + int kernel + add esp, 4 + 4 * 3 + + mov dword eax, [scriptname] + call strlen + mov dword [scriptnamelen], eax + + push dword [scriptnamelen] + push dword [scriptname] + push stdout + mov eax, sys_write + sub esp, 4 + int kernel + add esp, 4 + 4 * 3 + + push nllen + push nl + push stdout + mov eax, sys_write + sub esp, 4 + int kernel + add esp, 4 + 4 * 3 + + push 0 + mov eax, sys_exit + sub esp, 4 + int kernel diff --git a/Task/Program-name/X86-Assembly/program-name-5.x86 b/Task/Program-name/X86-Assembly/program-name-5.x86 new file mode 100644 index 0000000000..b03872a869 --- /dev/null +++ b/Task/Program-name/X86-Assembly/program-name-5.x86 @@ -0,0 +1,19 @@ +FORMAT=-f win32 +BIN=scriptname.exe +OBJ=scriptname.obj +RUN= + +all: test + +test: $(BIN) + $(RUN)$(BIN) + +$(BIN): $(OBJ) + golink /fo $(BIN) $(OBJ) /console kernel32.dll Msvcrt.dll + +$(OBJ): scriptname.asm + nasm $(FORMAT) -o $(OBJ) scriptname.asm + +clean: + -rm $(BIN) + -rm $(OBJ) diff --git a/Task/Program-name/X86-Assembly/program-name-6.x86 b/Task/Program-name/X86-Assembly/program-name-6.x86 new file mode 100644 index 0000000000..350304549f --- /dev/null +++ b/Task/Program-name/X86-Assembly/program-name-6.x86 @@ -0,0 +1,94 @@ +bits 32 + +section .data + +program db "Program: ", 0 +programlen equ $-program + +nl db "", 13, 10, 0 +nllen equ $-nl + +stdouthandle equ -11 + +section .bss + +stdout resd 1 + +charswritten resd 1 + +env resd 1 +argc resd 1 +argv resd 255 + +scriptname resd 1 +scriptnamelen resd 1 + +section .text + +global Start +extern GetStdHandle +extern __getmainargs +extern WriteConsoleA +extern ExitProcess + +strlen: ; eax: a string ending in 0 + push eax ; cache eax + + .strloop: + mov bl, byte [eax] + cmp bl, 0 + je .strret ; return len if bl == 0 + inc eax ; else eax++ + jmp .strloop + + .strret: + pop ebx ; ebx = cached eax + sub eax, ebx ; eax -= ebx + ret ; eax = len + +Start: + push 0 + push env + push argv + push argc + call __getmainargs + mov eax, [argv] + mov eax, [eax] + mov [scriptname], eax + add esp, 4 * 4 + + push stdouthandle + call GetStdHandle + mov [stdout], eax + add esp, 4 * 1 + + push 0 + push charswritten + push programlen + push program + push dword [stdout] + call WriteConsoleA + add esp, 4 * 5 + + mov eax, [scriptname] + call strlen + mov [scriptnamelen], eax + + push 0 + push charswritten + push dword [scriptnamelen] + push dword [scriptname] + push dword [stdout] + call WriteConsoleA + add esp, 4 * 5 + + push 0 + push charswritten + push nllen + push nl + push dword [stdout] + call WriteConsoleA + add esp, 4 * 5 + + push 0 + call ExitProcess diff --git a/Task/Program-name/Zkl/program-name-1.zkl b/Task/Program-name/Zkl/program-name-1.zkl new file mode 100644 index 0000000000..43d923a668 --- /dev/null +++ b/Task/Program-name/Zkl/program-name-1.zkl @@ -0,0 +1,2 @@ +#!/Homer/craigd/Bin/zkl +println(System.argv); diff --git a/Task/Program-name/Zkl/program-name-2.zkl b/Task/Program-name/Zkl/program-name-2.zkl new file mode 100644 index 0000000000..4d70bb3ec1 --- /dev/null +++ b/Task/Program-name/Zkl/program-name-2.zkl @@ -0,0 +1,2 @@ +./bbb.zkl +zkl bbb.zkl diff --git a/Task/Program-name/Zkl/program-name-3.zkl b/Task/Program-name/Zkl/program-name-3.zkl new file mode 100644 index 0000000000..67a04e50bf --- /dev/null +++ b/Task/Program-name/Zkl/program-name-3.zkl @@ -0,0 +1,15 @@ +#!/bin/sh +# A bash script to run zkl if you haven't jumped +# through all the Unix hoops to put the bits in the "right" places +# You can change zklRoot to your build directory, +# change the script name to "zkl" and put it in your bin path. +# You may need to chmod a+x +if [ -z $zklRoot ]; then + zklRoot=$HOME/ZKL + if [ ! -d $zklRoot ]; then + zklRoot=$HOME/Projects/ZKL + fi +fi +export zklRoot +#set -o noglob +LD_LIBRARY_PATH=$zklRoot/Lib $zklRoot/Bin/zkl "$@" diff --git a/Task/Program-termination/ALGOL-W/program-termination.alg b/Task/Program-termination/ALGOL-W/program-termination.alg new file mode 100644 index 0000000000..daefd4b8ff --- /dev/null +++ b/Task/Program-termination/ALGOL-W/program-termination.alg @@ -0,0 +1 @@ +if anErrorOccured then assert( false ); diff --git a/Task/Program-termination/BASIC/program-termination-3.basic b/Task/Program-termination/BASIC/program-termination-3.basic index cd09006ba0..d31d28eace 100644 --- a/Task/Program-termination/BASIC/program-termination-3.basic +++ b/Task/Program-termination/BASIC/program-termination-3.basic @@ -1 +1 @@ -10 IF 1 THEN END +IF TRUE THEN END 42 diff --git a/Task/Program-termination/BASIC/program-termination-4.basic b/Task/Program-termination/BASIC/program-termination-4.basic index e3c19a1a9e..cd09006ba0 100644 --- a/Task/Program-termination/BASIC/program-termination-4.basic +++ b/Task/Program-termination/BASIC/program-termination-4.basic @@ -1,3 +1 @@ -10 LET a = 1: LET b = 1 -20 IF a = b THEN GO TO 9995 -9995 STOP +10 IF 1 THEN END diff --git a/Task/Program-termination/BASIC/program-termination-5.basic b/Task/Program-termination/BASIC/program-termination-5.basic new file mode 100644 index 0000000000..e3c19a1a9e --- /dev/null +++ b/Task/Program-termination/BASIC/program-termination-5.basic @@ -0,0 +1,3 @@ +10 LET a = 1: LET b = 1 +20 IF a = b THEN GO TO 9995 +9995 STOP diff --git a/Task/Program-termination/Gambas/program-termination-1.gambas b/Task/Program-termination/Gambas/program-termination-1.gambas new file mode 100644 index 0000000000..298b5c0095 --- /dev/null +++ b/Task/Program-termination/Gambas/program-termination-1.gambas @@ -0,0 +1,11 @@ +Public Sub Form_Open() +Dim siCount As Short + +Do + If siCount > 1000 Then Break + Inc siCount +Loop + +Me.Close + +End diff --git a/Task/Program-termination/Gambas/program-termination-2.gambas b/Task/Program-termination/Gambas/program-termination-2.gambas new file mode 100644 index 0000000000..fac85907e6 --- /dev/null +++ b/Task/Program-termination/Gambas/program-termination-2.gambas @@ -0,0 +1,11 @@ +Public Sub Main() +Dim siCount As Short + +Do + If siCount > 1000 Then Break + Inc siCount +Loop + +Quit + +End diff --git a/Task/Program-termination/jq/program-termination-1.jq b/Task/Program-termination/Jq/program-termination-1.jq similarity index 100% rename from Task/Program-termination/jq/program-termination-1.jq rename to Task/Program-termination/Jq/program-termination-1.jq diff --git a/Task/Program-termination/jq/program-termination-2.jq b/Task/Program-termination/Jq/program-termination-2.jq similarity index 100% rename from Task/Program-termination/jq/program-termination-2.jq rename to Task/Program-termination/Jq/program-termination-2.jq diff --git a/Task/Program-termination/Kotlin/program-termination.kotlin b/Task/Program-termination/Kotlin/program-termination.kotlin new file mode 100644 index 0000000000..406953e51f --- /dev/null +++ b/Task/Program-termination/Kotlin/program-termination.kotlin @@ -0,0 +1,7 @@ +// version 1.0.6 + +fun main(args: Array) { + val problem = true + if (problem) System.exit(1) // non-zero code passed to OS to indicate a problem + println("Program terminating normally") // this line will not be executed +} diff --git a/Task/Program-termination/Nimrod/program-termination.nimrod b/Task/Program-termination/Nimrod/program-termination.nimrod deleted file mode 100644 index 5cf9eed599..0000000000 --- a/Task/Program-termination/Nimrod/program-termination.nimrod +++ /dev/null @@ -1,2 +0,0 @@ -if problem: - quit(QuitFailure) diff --git a/Task/Program-termination/TI-83-BASIC/program-termination.ti-83 b/Task/Program-termination/TI-83-BASIC/program-termination.ti-83 deleted file mode 100644 index a48896b3ab..0000000000 --- a/Task/Program-termination/TI-83-BASIC/program-termination.ti-83 +++ /dev/null @@ -1 +0,0 @@ - :Stop diff --git a/Task/Program-termination/Zkl/program-termination.zkl b/Task/Program-termination/Zkl/program-termination.zkl new file mode 100644 index 0000000000..f627ecaec0 --- /dev/null +++ b/Task/Program-termination/Zkl/program-termination.zkl @@ -0,0 +1,3 @@ +if (die) System.exit(); +if (die) System.exit(1); +if (die) System.exit("dumping core"); diff --git a/Task/Pythagorean-triples/00DESCRIPTION b/Task/Pythagorean-triples/00DESCRIPTION index 86ac71e812..6de31a73c8 100644 --- a/Task/Pythagorean-triples/00DESCRIPTION +++ b/Task/Pythagorean-triples/00DESCRIPTION @@ -19,4 +19,9 @@ Note: the extra credit is not for you to demonstrate how fast your language is c ;Cf: * [[List comprehensions]] + + +;Related tasks: +*   [[Euler's sum of powers conjecture]]. +*   [[Pythagorean quadruples]].

    diff --git a/Task/Pythagorean-triples/Haskell/pythagorean-triples-1.hs b/Task/Pythagorean-triples/Haskell/pythagorean-triples-1.hs index 608f7c17ba..65156a9c39 100644 --- a/Task/Pythagorean-triples/Haskell/pythagorean-triples-1.hs +++ b/Task/Pythagorean-triples/Haskell/pythagorean-triples-1.hs @@ -1,5 +1,22 @@ -pytr n = filter (\(_, a, b, c) -> a+b+c <= n) [(prim a b c, a, b, c) | a <- [1..n], b <- [1..n], c <- [1..n], a < b && b < c, a^2 + b^2 == c^2] - where prim a b _ = gcd a b == 1 +pytr :: Int -> [(Bool, Int, Int, Int)] +pytr n = + filter + (\(_, a, b, c) -> a + b + c <= n) + [ (prim a b c, a, b, c) + | a <- xs + , b <- drop a xs + , c <- drop b xs + , a ^ 2 + b ^ 2 == c ^ 2 ] + where + xs = [1 .. n] + prim a b _ = gcd a b == 1 -main = putStrLn $ "Up to 100 there are " ++ (show $ length xs) ++ " triples, of which " ++ (show $ length $ filter (\(x,_,_,_) -> x == True) xs) ++ " are primitive." - where xs = pytr 100 +main :: IO () +main = + putStrLn $ + "Up to 100 there are " ++ + show (length xs) ++ + " triples, of which " ++ + show (length $ filter (\(x, _, _, _) -> x) xs) ++ " are primitive." + where + xs = pytr 100 diff --git a/Task/Pythagorean-triples/Haskell/pythagorean-triples-2.hs b/Task/Pythagorean-triples/Haskell/pythagorean-triples-2.hs index 6001ba71e5..34a560e2dd 100644 --- a/Task/Pythagorean-triples/Haskell/pythagorean-triples-2.hs +++ b/Task/Pythagorean-triples/Haskell/pythagorean-triples-2.hs @@ -1,15 +1,22 @@ -triangles :: Int -> [[Int]] -triangles max_peri | max_peri < 12 = [] - | otherwise = concat tiers where - tiers = takeWhile (not.null) $ iterate tier [[3,4,5]] - tier = concatMap (filter ((<=max_peri).sum).tmul) - tmul t = map (map (sum . zipWith (*) t)) - [[[ 1,-2,2],[ 2,-1,2],[ 2,-2,3]], - [[ 1, 2,2],[ 2, 1,2],[ 2, 2,3]], - [[-1, 2,2],[-2, 1,2],[-2, 2,3]]] +pythagoreanTriplesBelow :: Int -> [[Int]] +pythagoreanTriplesBelow n = + let m = quot n 2 + in concatMap + (\x -> + concatMap + (\y -> + concatMap + (\z -> + if x + y + z <= n && x ^ 2 + y ^ 2 == z ^ 2 + then [[x, y, z]] + else []) + [y + 1 .. m]) + [x + 1 .. m]) + [1 .. m] -triangle_count max_p = (length t, sum $ map ((max_p `div`).sum) t) - where t = triangles max_p - -main = mapM_ putStrLn $ - map (\n -> show n ++ " " ++ show (triangle_count n)) $ map (10^) [1..] +-- TEST ------------------------------------------------------------------------- +main :: IO () +main = + mapM_ + (print . length) + ([id, filter (\[x, y, _] -> gcd x y == 1)] <*> [pythagoreanTriplesBelow 100]) diff --git a/Task/Pythagorean-triples/Haskell/pythagorean-triples-3.hs b/Task/Pythagorean-triples/Haskell/pythagorean-triples-3.hs new file mode 100644 index 0000000000..358065aa0c --- /dev/null +++ b/Task/Pythagorean-triples/Haskell/pythagorean-triples-3.hs @@ -0,0 +1,24 @@ +triangles :: Int -> [[Int]] +triangles max_peri + | max_peri < 12 = [] + | otherwise = concat tiers + where + tiers = takeWhile (not . null) $ iterate tier [[3, 4, 5]] + tier = concatMap (filter ((<= max_peri) . sum) . tmul) + tmul t = + map + (map (sum . zipWith (*) t)) + [ [[1, -2, 2], [2, -1, 2], [2, -2, 3]] + , [[1, 2, 2], [2, 1, 2], [2, 2, 3]] + , [[-1, 2, 2], [-2, 1, 2], [-2, 2, 3]] + ] + +triangleCount max_p = (length t, sum $ map ((max_p `div`) . sum) t) + where + t = triangles max_p + +main :: IO () +main = + mapM_ + ((putStrLn . (\n -> show n ++ " " ++ show (triangleCount n))) . (10 ^)) + [1 .. 7] diff --git a/Task/Pythagorean-triples/JavaScript/pythagorean-triples-1.js b/Task/Pythagorean-triples/JavaScript/pythagorean-triples-1.js new file mode 100644 index 0000000000..b1de50ddea --- /dev/null +++ b/Task/Pythagorean-triples/JavaScript/pythagorean-triples-1.js @@ -0,0 +1,43 @@ +(() => { + + // concatMap :: (a -> [b]) -> [a] -> [b] + const concatMap = (f, xs) => [].concat.apply([], xs.map(f)); + + // range :: Int -> Int -> [Int] + const range = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // gcd :: Integral a => a -> a -> a + const gcd = (x, y) => { + const _gcd = (a, b) => (b === 0 ? a : _gcd(b, a % b)), + abs = Math.abs; + return _gcd(abs(x), abs(y)); + } + + // Arguments: predicate, maximum perimeter + // pythTripleCount :: ((Int, Int, Int) -> Bool) -> Int -> Int + const pythTripleCount = (p, maxPerim) => { + const xs = range(1, Math.floor(maxPerim / 2)); + + return concatMap(x => + concatMap(y => + concatMap(z => + ( (x + y + z <= maxPerim ) && + (x * x + y * y === z * z ) && + p(x, y, z) ) ? [ + [x, y, z] + ] : [ ], // concatMap eliminates empty lists + xs.slice(y)), xs.slice(x)), xs + ) + .length; + }; + + return [10, 100, 1000] + .map(n => ({ + maxPerimeter: n, + triples: pythTripleCount(x => true, n), + primitives: pythTripleCount((x, y, _) => gcd(x, y) === 1, n) + })); +})(); diff --git a/Task/Pythagorean-triples/JavaScript/pythagorean-triples-2.js b/Task/Pythagorean-triples/JavaScript/pythagorean-triples-2.js new file mode 100644 index 0000000000..629d0e0bd3 --- /dev/null +++ b/Task/Pythagorean-triples/JavaScript/pythagorean-triples-2.js @@ -0,0 +1,3 @@ +[{"maxPerimeter":10, "triples":0, "primitives":0}, + {"maxPerimeter":100, "triples":17, "primitives":7}, + {"maxPerimeter":1000, "triples":325, "primitives":70}] diff --git a/Task/Pythagorean-triples/jq/pythagorean-triples-1.jq b/Task/Pythagorean-triples/Jq/pythagorean-triples-1.jq similarity index 100% rename from Task/Pythagorean-triples/jq/pythagorean-triples-1.jq rename to Task/Pythagorean-triples/Jq/pythagorean-triples-1.jq diff --git a/Task/Pythagorean-triples/jq/pythagorean-triples-2.jq b/Task/Pythagorean-triples/Jq/pythagorean-triples-2.jq similarity index 100% rename from Task/Pythagorean-triples/jq/pythagorean-triples-2.jq rename to Task/Pythagorean-triples/Jq/pythagorean-triples-2.jq diff --git a/Task/Pythagorean-triples/Kotlin/pythagorean-triples.kotlin b/Task/Pythagorean-triples/Kotlin/pythagorean-triples.kotlin new file mode 100644 index 0000000000..d4abe0e520 --- /dev/null +++ b/Task/Pythagorean-triples/Kotlin/pythagorean-triples.kotlin @@ -0,0 +1,27 @@ +// version 1.1.2 + +var total = 0L +var prim = 0L +var maxPeri = 0L + +fun newTri(s0: Long, s1: Long, s2: Long) { + val p = s0 + s1 + s2 + if (p <= maxPeri) { + prim++ + total += maxPeri / 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) + } +} + +fun main(args: Array) { + maxPeri = 100 + while (maxPeri <= 10_000_000_000L) { + prim = 0 + total = 0 + newTri(3, 4, 5) + println("Up to $maxPeri: $total triples, $prim primatives") + maxPeri *= 10 + } +} diff --git a/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx b/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx index d6d45a5c03..10e5536bea 100644 --- a/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx +++ b/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx @@ -1,29 +1,25 @@ /*REXX program counts the number of Pythagorean triples that exist given a maximum */ /*──────────────────── perimeter of N, and also counts how many of them are primitives.*/ -trips=0; prims=0 /*set the number of triples, primitives*/ parse arg N . /*obtain optional argument from the CL.*/ if N=='' | N=="," then n=100 /*Not specified? Then use the default.*/ - - do a=3 to N%3; aa=a*a /*limit side to 1/3 of the perimeter.*/ - - do b=a+1 /*the triangle can't be isosceles. */ - ab=a + b /*compute a partial perimeter (2 sides)*/ - if ab>=N then iterate a /*is a+b ≥ perimeter? Try different A*/ - aabb=aa + b*b /*compute the sum of a²+b² (shortcut)*/ - - do c=b+1 /*compute the value of the third side. */ - if ab + c > N then iterate a /*is a+b+c > perimeter? Try diff. A.*/ - cc=c*c /*compute the value of C². */ - if cc > aabb then iterate b /*is c² > a²+b² ? Try a different B.*/ - if cc\==aabb then iterate /*is c² ¬= a²+b² ? Try a different C.*/ - trips=trips + 1 /*eureka. We found a Pythagorean triple*/ - prims=prims + (gcd(a,b)==1) /*is this triple a primitive triple? */ - end /*c*/ - end /*b*/ - end /*a*/ - +T=0; P=0 /*set the number of Triples, Primitives*/ + do a=3 to N%3; aa=a*a /*limit side to 1/3 of the perimeter.*/ + do b=a+1 /*the triangle can't be isosceles. */ + ab=a + b /*compute a partial perimeter (2 sides)*/ + if ab>=N then iterate a /*is a+b ≥ perimeter? Try different A*/ + aabb=aa + b*b /*compute the sum of a²+b² (shortcut)*/ + do c=b+1 /*compute the value of the third side. */ + if ab+c > N then iterate a /*is a+b+c > perimeter? Try diff. A.*/ + cc=c*c /*compute the value of C². */ + if cc > aabb then iterate b /*is c² > a²+b² ? Try a different B.*/ + if cc\==aabb then iterate /*is c² ¬= a²+b² ? Try a different C.*/ + T=T + 1 /*eureka. We found a Pythagorean triple*/ + P=P + (gcd(a, b)==1) /*is this triple a primitive triple? */ + end /*c*/ + end /*b*/ + end /*a*/ _=left('', 7) /*for padding the output with 7 blanks.*/ -say 'max perimeter =' N _ "Pythagorean triples =" trips _ 'primitives =' prims +say 'max perimeter =' N _ "Pythagorean triples =" T _ 'primitives =' P exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ gcd: procedure; parse arg x,y; do until y==0; parse value x//y y with y x; end; return x diff --git a/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx b/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx index 5da270027a..5d9da681a0 100644 --- a/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx +++ b/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx @@ -1,36 +1,31 @@ /*REXX program counts the number of Pythagorean triples that exist given a maximum */ /*──────────────────── perimeter of N, and also counts how many of them are primitives.*/ -@.=0; trips=0; prims=0 /*define some REXX variables to zero. */ parse arg N . /*obtain optional argument from the CL.*/ if N=='' | N=="," then n=100 /*Not specified? Then use the default.*/ - - do a=3 to N%3; aa=a*a /*limit side to 1/3 of the perimeter.*/ - aEven= a//2==0 /*set variable to 1 if A is even. */ - - do b=a+1 by 1+aEven /*the triangle can't be isosceles. */ - ab=a + b /*compute a partial perimeter (2 sides)*/ - if ab>=N then iterate a /*is a+b ≥ perimeter? Try different A*/ - aabb=aa + b*b /*compute the sum of a²+b² (shortcut)*/ - - do c=b + 1 /*compute the value of the third side. */ - if aEven then if c//2==0 then iterate - if ab+c>n then iterate a /*a+b+c > perimeter? Try different A.*/ - cc=c*c /*compute the value of C². */ - if cc > aabb then iterate b /*is c² > a²+b² ? Try a different B.*/ - if cc\==aabb then iterate /*is c² ¬= a²+b² ? Try a different C.*/ - if @.a.b.c then iterate /*Is this a duplicate? Then try again.*/ - trips=trips + 1 /*Eureka! We found a Pythagorean triple*/ - prims=prims + 1 /*count this also as a primitive triple*/ - - do m=2; am=a*m; bm=b*m; cm=c*m /*generate non-primitives Pythagoreans.*/ - if am+bm+cm>N then leave /*is this multiple Pythagorean triple? */ - trips=trips+1 /*Eureka! We found a Pythagorean triple*/ - @.am.bm.cm=1 /*mark Pythagorean triangle as a triple*/ - end /*m*/ - end /*c*/ - end /*b*/ - end /*a*/ - +T=0; P=0 /*set the number of Triples, Primitives*/ +@.=0; do a=3 to N%3; aa=a*a /*limit side to 1/3 of the perimeter.*/ + aEven= a//2==0 /*set variable to 1 if A is even. */ + do b=a+1 by 1+aEven /*the triangle can't be isosceles. */ + ab=a + b /*compute a partial perimeter (2 sides)*/ + if ab>=N then iterate a /*is a+b ≥ perimeter? Try different A*/ + aabb=aa + b*b /*compute the sum of a²+b² (shortcut)*/ + do c=b + 1 /*compute the value of the third side. */ + if aEven then if c//2==0 then iterate + if ab+c>n then iterate a /*a+b+c > perimeter? Try different A.*/ + cc=c*c /*compute the value of C². */ + if cc > aabb then iterate b /*is c² > a²+b² ? Try a different B.*/ + if cc\==aabb then iterate /*is c² ¬= a²+b² ? Try a different C.*/ + if @.a.b.c then iterate /*Is this a duplicate? Then try again.*/ + T=T + 1 /*Eureka! We found a Pythagorean triple*/ + P=P + 1 /*count this also as a primitive triple*/ + do m=2 while a*m+b*m+c*m<=N /*generate non-primitives Pythagoreans.*/ + T=T + 1 /*Eureka! We found a Pythagorean triple*/ + am=a*m; bm=b*m; cm=c*m /*create some short-cut variable names.*/ + @.am.bm.cm=1 /*mark Pythagorean triangle as a triple*/ + end /*m*/ + end /*c*/ + end /*b*/ + end /*a*/ _=left('', 7) /*for padding the output with 7 blanks.*/ -say 'max perimeter =' N _ "Pythagorean triples =" trips _ 'primitives =' prims +say 'max perimeter =' N _ "Pythagorean triples =" T _ 'primitives =' P /*stick a fork in it, we're all done. */ diff --git a/Task/Pythagorean-triples/Sidef/pythagorean-triples.sidef b/Task/Pythagorean-triples/Sidef/pythagorean-triples.sidef index b40bbfe08f..279de7a17d 100644 --- a/Task/Pythagorean-triples/Sidef/pythagorean-triples.sidef +++ b/Task/Pythagorean-triples/Sidef/pythagorean-triples.sidef @@ -1,21 +1,21 @@ func triples(limit) { - var primitive = 0; - var civilized = 0; + var primitive = 0 + var civilized = 0 func oyako(a, b, c) { (var perim = a+b+c) > limit || ( - primitive++; - civilized += int(limit / perim); - oyako( a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c); - oyako( a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c); - oyako(-a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c); - ); + primitive++ + civilized += int(limit / perim) + oyako( a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c) + oyako( a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c) + oyako(-a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c) + ) } - oyako(3,4,5); - "#{limit} => (#{primitive} #{civilized})"; + oyako(3,4,5) + "#{limit} => (#{primitive} #{civilized})" } - -Inf.times { |n| - say triples(10**n); +  +for n (1..Inf) { + say triples(10**n) } diff --git a/Task/Pythagorean-triples/Zkl/pythagorean-triples-1.zkl b/Task/Pythagorean-triples/Zkl/pythagorean-triples-1.zkl new file mode 100644 index 0000000000..6660270b35 --- /dev/null +++ b/Task/Pythagorean-triples/Zkl/pythagorean-triples-1.zkl @@ -0,0 +1,9 @@ +fcn tri(lim,a=3,b=4,c=5){ + p:=a + b + c; + if(p>lim) return(0,0); + T(1,lim/p).zipWith('+, + tri(lim, a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c), + tri(lim, a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c), + tri(lim, -a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c) + ); +} diff --git a/Task/Pythagorean-triples/Zkl/pythagorean-triples-2.zkl b/Task/Pythagorean-triples/Zkl/pythagorean-triples-2.zkl new file mode 100644 index 0000000000..59d889d948 --- /dev/null +++ b/Task/Pythagorean-triples/Zkl/pythagorean-triples-2.zkl @@ -0,0 +1 @@ +n:=10; do(10){ println("%,d: %s".fmt(n,tri(n).reverse())); n*=10; } diff --git a/Task/QR-decomposition/C++/qr-decomposition.cpp b/Task/QR-decomposition/C++/qr-decomposition.cpp new file mode 100644 index 0000000000..3f094378d2 --- /dev/null +++ b/Task/QR-decomposition/C++/qr-decomposition.cpp @@ -0,0 +1,395 @@ +/* + * g++ -O3 -Wall --std=c++11 qr_standalone.cpp -o qr_standalone + */ +#include +#include +#include // for memset +#include +#include +#include + +#include + +class Vector; + +class Matrix { + +public: + // default constructor (don't allocate) + Matrix() : m(0), n(0), data(nullptr) {} + + // constructor with memory allocation, initialized to zero + Matrix(int m_, int n_) : Matrix() { + m = m_; + n = n_; + allocate(m_,n_); + } + + // copy constructor + Matrix(const Matrix& mat) : Matrix(mat.m,mat.n) { + + for (int i = 0; i < m; i++) + for (int j = 0; j < n; j++) + (*this)(i,j) = mat(i,j); + } + + // constructor from array + template + Matrix(double (&a)[rows][cols]) : Matrix(rows,cols) { + + for (int i = 0; i < m; i++) + for (int j = 0; j < n; j++) + (*this)(i,j) = a[i][j]; + } + + // destructor + ~Matrix() { + deallocate(); + } + + + // access data operators + double& operator() (int i, int j) { + return data[i+m*j]; } + double operator() (int i, int j) const { + return data[i+m*j]; } + + // operator assignment + Matrix& operator=(const Matrix& source) { + + // self-assignment check + if (this != &source) { + if ( (m*n) != (source.m * source.n) ) { // storage cannot be reused + allocate(source.m,source.n); // re-allocate storage + } + // storage can be used, copy data + std::copy(source.data, source.data + source.m*source.n, data); + } + return *this; + } + + // compute minor + void compute_minor(const Matrix& mat, int d) { + + allocate(mat.m, mat.n); + + for (int i = 0; i < d; i++) + (*this)(i,i) = 1.0; + for (int i = d; i < mat.m; i++) + for (int j = d; j < mat.n; j++) + (*this)(i,j) = mat(i,j); + + } + + // Matrix multiplication + // c = a * b + // c will be re-allocated here + void mult(const Matrix& a, const Matrix& b) { + + if (a.n != b.m) { + std::cerr << "Matrix multiplication not possible, sizes don't match !\n"; + return; + } + + // reallocate ourself if necessary i.e. current Matrix has not valid sizes + if (a.m != m or b.n != n) + allocate(a.m, b.n); + + memset(data,0,m*n*sizeof(double)); + + for (int i = 0; i < a.m; i++) + for (int j = 0; j < b.n; j++) + for (int k = 0; k < a.n; k++) + (*this)(i,j) += a(i,k) * b(k,j); + + } + + void transpose() { + for (int i = 0; i < m; i++) { + for (int j = 0; j < i; j++) { + double t = (*this)(i,j); + (*this)(i,j) = (*this)(j,i); + (*this)(j,i) = t; + } + } + } + + // take c-th column of m, put in v + void extract_column(Vector& v, int c); + + // memory allocation + void allocate(int m_, int n_) { + + // if already allocated, memory is freed + deallocate(); + + // new sizes + m = m_; + n = n_; + + data = new double[m_*n_]; + memset(data,0,m_*n_*sizeof(double)); + + } // allocate + + // memory free + void deallocate() { + + if (data) + delete[] data; + + data = nullptr; + + } + + int m, n; + +private: + double* data; + +}; // struct Matrix + +// column vector +class Vector { + +public: + // default constructor (don't allocate) + Vector() : size(0), data(nullptr) {} + + // constructor with memory allocation, initialized to zero + Vector(int size_) : Vector() { + size = size_; + allocate(size_); + } + + // destructor + ~Vector() { + deallocate(); + } + + // access data operators + double& operator() (int i) { + return data[i]; } + double operator() (int i) const { + return data[i]; } + + // operator assignment + Vector& operator=(const Vector& source) { + + // self-assignment check + if (this != &source) { + if ( size != (source.size) ) { // storage cannot be reused + allocate(source.size); // re-allocate storage + } + // storage can be used, copy data + std::copy(source.data, source.data + source.size, data); + } + return *this; + } + + // memory allocation + void allocate(int size_) { + + deallocate(); + + // new sizes + size = size_; + + data = new double[size_]; + memset(data,0,size_*sizeof(double)); + + } // allocate + + // memory free + void deallocate() { + + if (data) + delete[] data; + + data = nullptr; + + } + + // ||x|| + double norm() { + double sum = 0; + for (int i = 0; i < size; i++) sum += (*this)(i) * (*this)(i); + return sqrt(sum); + } + + // divide data by factor + void rescale(double factor) { + for (int i = 0; i < size; i++) (*this)(i) /= factor; + } + + void rescale_unit() { + double factor = norm(); + rescale(factor); + } + + int size; + +private: + double* data; + +}; // class Vector + +// c = a + b * s +void vmadd(const Vector& a, const Vector& b, double s, Vector& c) +{ + if (c.size != a.size or c.size != b.size) { + std::cerr << "[vmadd]: vector sizes don't match\n"; + return; + } + + for (int i = 0; i < c.size; i++) + c(i) = a(i) + s * b(i); +} + +// mat = I - 2*v*v^T +// !!! m is allocated here !!! +void compute_householder_factor(Matrix& mat, const Vector& v) +{ + + int n = v.size; + mat.allocate(n,n); + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + mat(i,j) = -2 * v(i) * v(j); + for (int i = 0; i < n; i++) + mat(i,i) += 1; +} + +// take c-th column of a matrix, put results in Vector v +void Matrix::extract_column(Vector& v, int c) { + if (m != v.size) { + std::cerr << "[Matrix::extract_column]: Matrix and Vector sizes don't match\n"; + return; + } + + for (int i = 0; i < m; i++) + v(i) = (*this)(i,c); +} + +void matrix_show(const Matrix& m, const std::string& str="") +{ + std::cout << str << "\n"; + for(int i = 0; i < m.m; i++) { + for (int j = 0; j < m.n; j++) { + printf(" %8.3f", m(i,j)); + } + printf("\n"); + } + printf("\n"); +} + +// L2-norm ||A-B||^2 +double matrix_compare(const Matrix& A, const Matrix& B) { + // matrices must have same size + if (A.m != B.m or A.n != B.n) + return std::numeric_limits::max(); + + double res=0; + for(int i = 0; i < A.m; i++) { + for (int j = 0; j < A.n; j++) { + res += (A(i,j)-B(i,j)) * (A(i,j)-B(i,j)); + } + } + + res /= A.m*A.n; + return res; +} + +void householder(Matrix& mat, + Matrix& R, + Matrix& Q) +{ + + int m = mat.m; + int n = mat.n; + + // array of factor Q1, Q2, ... Qm + std::vector qv(m); + + // temp array + Matrix z(mat); + Matrix z1; + + for (int k = 0; k < n && k < m - 1; k++) { + + Vector e(m), x(m); + double a; + + // compute minor + z1.compute_minor(z, k); + + // extract k-th column into x + z1.extract_column(x, k); + + a = x.norm(); + if (mat(k,k) > 0) a = -a; + + for (int i = 0; i < e.size; i++) + e(i) = (i == k) ? 1 : 0; + + // e = x + a*e + vmadd(x, e, a, e); + + // e = e / ||e|| + e.rescale_unit(); + + // qv[k] = I - 2 *e*e^T + compute_householder_factor(qv[k], e); + + // z = qv[k] * z1 + z.mult(qv[k], z1); + + } + + Q = qv[0]; + + // after this loop, we will obtain Q (up to a transpose operation) + for (int i = 1; i < n && i < m - 1; i++) { + + z1.mult(qv[i], Q); + Q = z1; + + } + + R.mult(Q, mat); + Q.transpose(); +} + +double in[][3] = { + { 12, -51, 4}, + { 6, 167, -68}, + { -4, 24, -41}, + { -1, 1, 0}, + { 2, 0, 3}, +}; + +int main() +{ + Matrix A(in); + Matrix Q, R; + + matrix_show(A,"A"); + + // compute QR decompostion + householder(A, R, Q); + + matrix_show(Q,"Q"); + matrix_show(R,"R"); + + // compare Q*R to the original matrix A + Matrix A_check; + A_check.mult(Q, R); + + // compute L2 norm ||A-A_check||^2 + double l2 = matrix_compare(A,A_check); + + // display Q*R + matrix_show(A_check, l2 < 1e-12 ? "A == Q * R ? yes" : "A == Q * R ? no"); + + return EXIT_SUCCESS; +} diff --git a/Task/QR-decomposition/C/qr-decomposition.c b/Task/QR-decomposition/C/qr-decomposition.c index 7ef333e6f7..97aba43826 100644 --- a/Task/QR-decomposition/C/qr-decomposition.c +++ b/Task/QR-decomposition/C/qr-decomposition.c @@ -5,7 +5,7 @@ typedef struct { int m, n; double ** v; -} mat_t, mat; +} mat_t, *mat; mat matrix_new(int m, int n) { @@ -37,7 +37,7 @@ void matrix_transpose(mat m) } } -mat matrix_copy(int n;double a[][n], int m, int n) +mat matrix_copy(int n, double a[][n], int m) { mat x = matrix_new(m, n); for (int i = 0; i < m; i++) @@ -174,7 +174,7 @@ double in[][3] = { int main() { mat R, Q; - mat x = matrix_copy(in, 5, 3); + mat x = matrix_copy(3, in, 5); householder(x, &R, &Q); puts("Q"); matrix_show(Q); diff --git a/Task/QR-decomposition/SequenceL/qr-decomposition.sequencel b/Task/QR-decomposition/SequenceL/qr-decomposition.sequencel new file mode 100644 index 0000000000..23139dec97 --- /dev/null +++ b/Task/QR-decomposition/SequenceL/qr-decomposition.sequencel @@ -0,0 +1,89 @@ +import ; +import ; +import ; + +main := + let + qrTest := [[12.0, -51.0, 4.0], + [ 6.0, 167.0, -68.0], + [-4.0, 24.0, -41.0]]; + + qrResult := qr(qrTest); + + x := 1.0*(0 ... 10); + y := 1.0*[1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]; + + regResult := polyfit(x, y, 2); + in + "q:\n" ++ delimit(delimit(floatToString(qrResult[1], 6), ','), '\n') ++ "\n\n" ++ + "r:\n" ++ delimit(delimit(floatToString(qrResult[2], 1), ','), '\n') ++ "\n\n" ++ + "polyfit:\n" ++ "[" ++ delimit(floatToString(regResult, 1), ',') ++ "]"; + +//---Polynomial Regression--- + +polyfit(x(1), y(1), n) := + let + a[j] := x ^ j foreach j within 0 ... n; + in + lsqr(transpose(a), transpose([y])); + +lsqr(a(2), b(2)) := + let + qrDecomp := qr(a); + prod := mm(transpose(qrDecomp[1]), b); + in + solveUT(qrDecomp[2], prod); + +solveUT(r(2), b(2)) := + let + n := size(r[1]); + in + solveUTHelper(r, b, n, duplicate(0.0, n)); + +solveUTHelper(r(2), b(2), k, x(1)) := + let + n := size(r[1]); + newX := setElementAt(x, k, (b[k][1] - sum(r[k][(k+1) ... n] * x[(k+1) ... n])) / r[k][k]); + in + x when k <= 0 + else + solveUTHelper(r, b, k - 1, newX); + +//---QR Decomposition--- + +qr(A(2)) := qrHelper(A, id(size(A)), 1); + +qrHelper(A(2), Q(2), i) := + let + m := size(A); + n := size(A[1]); + + householder := makeHouseholder(A[i ... m, i]); + + H[j,k] := + householder[j - i + 1][k - i + 1] when j >= i and k >= i + else + 1.0 when j = k else 0.0 + foreach j within 1 ... m, + k within 1 ... m; + in + [Q,A] when i > (n - 1 when m = n else n) + else + qrHelper(mm(H, A), mm(Q, H), i + 1); + + +makeHouseholder(a(1)) := + let + v := [1.0] ++ tail(a / (a[1] + sqrt(sum(a ^ 2)) * sign(a[1]))); + + H := id(size(a)) - (2.0 / mm([v], transpose([v])))[1,1] * mm(transpose([v]), [v]); + in + H; + +//---Utilities--- + +id(n)[i,j] := 1.0 when i = j else 0.0 + foreach i within 1 ... n, + j within 1 ... n; + +mm(A(2), B(2))[i,j] := sum( A[i] * transpose(B)[j] ); diff --git a/Task/QR-decomposition/Stata/qr-decomposition.stata b/Task/QR-decomposition/Stata/qr-decomposition.stata new file mode 100644 index 0000000000..f70935c88e --- /dev/null +++ b/Task/QR-decomposition/Stata/qr-decomposition.stata @@ -0,0 +1,26 @@ +mata +: qrd(a=(12,-51,4\6,167,-68\-4,24,-41),q=.,r=.) + +: a + 1 2 3 + +-------------------+ + 1 | 12 -51 4 | + 2 | 6 167 -68 | + 3 | -4 24 -41 | + +-------------------+ + +: q + 1 2 3 + +----------------------------------------------+ + 1 | -.8571428571 .3942857143 .3314285714 | + 2 | -.4285714286 -.9028571429 -.0342857143 | + 3 | .2857142857 -.1714285714 .9428571429 | + +----------------------------------------------+ + +: r + 1 2 3 + +----------------------+ + 1 | -14 -21 14 | + 2 | 0 -175 70 | + 3 | 0 0 -35 | + +----------------------+ diff --git a/Task/QR-decomposition/Zkl/qr-decomposition.zkl b/Task/QR-decomposition/Zkl/qr-decomposition.zkl new file mode 100644 index 0000000000..0daabd47ba --- /dev/null +++ b/Task/QR-decomposition/Zkl/qr-decomposition.zkl @@ -0,0 +1,8 @@ +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +A:=GSL.Matrix(3,3).set(12.0, -51.0, 4.0, + 6.0, 167.0, -68.0, + 4.0, 24.0, -41.0); +Q,R:=A.QRDecomp(); +println("Q:\n",Q.format()); +println("R:\n",R.format()); +println("Q*R:\n",(Q*R).format()); diff --git a/Task/Quaternion-type/00DESCRIPTION b/Task/Quaternion-type/00DESCRIPTION index d1dc577b74..7c30b92083 100644 --- a/Task/Quaternion-type/00DESCRIPTION +++ b/Task/Quaternion-type/00DESCRIPTION @@ -32,14 +32,11 @@ Given the three quaternions and their components: And a wholly real number   r = 7. -'''Note:''' ''The first formula below is invisible to the majority of browsers, including Chrome, IE/Edge, Safari, Opera etc. It may, subject to the installation of requisite fonts, prove visible in Firefox.'' - - Create functions   (or classes)   to perform simple maths with quaternions including computing: -# The norm of a quaternion:
    = \sqrt{ a^2 + b^2 + c^2 + d^2 } +# The norm of a quaternion:
    = \sqrt{a^2 + b^2 + c^2 + d^2} # The negative of a quaternion:
    = (-a, -b, -c, -d) # The conjugate of a quaternion:
    = ( a, -b, -c, -d) -# Addition of a real number   r   and   a   quaternion   q:
    r + q = q + r = (a+r, b, c, d) +# Addition of a real number   r   and a quaternion   q:
    r + q = q + r = (a+r, b, c, d) # Addition of two quaternions:
    q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) # Multiplication of a real number and a quaternion:
    qr = rq = (ar, br, cr, dr) # Multiplication of two quaternions   q1   and   q2   is given by:
    ( a1a2 − b1b2 − c1c2 − d1d2,
      a1b2 + b1a2 + c1d2 − d1c2,
      a1c2 − b1d2 + c1a2 + d1b2,
      a1d2 + b1c2 − c1b2 + d1a2 )
    diff --git a/Task/Quaternion-type/jq/quaternion-type-1.jq b/Task/Quaternion-type/Jq/quaternion-type-1.jq similarity index 100% rename from Task/Quaternion-type/jq/quaternion-type-1.jq rename to Task/Quaternion-type/Jq/quaternion-type-1.jq diff --git a/Task/Quaternion-type/jq/quaternion-type-2.jq b/Task/Quaternion-type/Jq/quaternion-type-2.jq similarity index 100% rename from Task/Quaternion-type/jq/quaternion-type-2.jq rename to Task/Quaternion-type/Jq/quaternion-type-2.jq diff --git a/Task/Quaternion-type/Kotlin/quaternion-type.kotlin b/Task/Quaternion-type/Kotlin/quaternion-type.kotlin new file mode 100644 index 0000000000..1af8242588 --- /dev/null +++ b/Task/Quaternion-type/Kotlin/quaternion-type.kotlin @@ -0,0 +1,57 @@ +// version 1.1.2 + +data class Quaternion(val a: Double, val b: Double, val c: Double, val d: Double) { + operator fun plus(other: Quaternion): Quaternion { + return Quaternion (this.a + other.a, this.b + other.b, + this.c + other.c, this.d + other.d) + } + + operator fun plus(r: Double) = Quaternion(a + r, b, c, d) + + operator fun times(other: Quaternion): Quaternion { + return Quaternion( + this.a * other.a - this.b * other.b - this.c * other.c - this.d * other.d, + this.a * other.b + this.b * other.a + this.c * other.d - this.d * other.c, + this.a * other.c - this.b * other.d + this.c * other.a + this.d * other.b, + this.a * other.d + this.b * other.c - this.c * other.b + this.d * other.a + ) + } + + operator fun times(r: Double) = Quaternion(a * r, b * r, c * r, d * r) + + operator fun unaryMinus() = Quaternion(-a, -b, -c, -d) + + fun conj() = Quaternion(a, -b, -c, -d) + + fun norm() = Math.sqrt(a * a + b * b + c * c + d * d) + + override fun toString() = "($a, $b, $c, $d)" +} + +// extension functions for Double type +operator fun Double.plus(q: Quaternion) = q + this +operator fun Double.times(q: Quaternion) = q * this + +fun main(args: Array) { + val q = Quaternion(1.0, 2.0, 3.0, 4.0) + val q1 = Quaternion(2.0, 3.0, 4.0, 5.0) + val q2 = Quaternion(3.0, 4.0, 5.0, 6.0) + val r = 7.0 + println("q = $q") + println("q1 = $q1") + println("q2 = $q2") + println("r = $r\n") + println("norm(q) = ${"%f".format(q.norm())}") + println("-q = ${-q}") + println("conj(q) = ${q.conj()}\n") + println("r + q = ${r + q}") + println("q + r = ${q + r}") + println("q1 + q2 = ${q1 + q2}\n") + println("r * q = ${r * q}") + println("q * r = ${q * r}") + val q3 = q1 * q2 + val q4 = q2 * q1 + println("q1 * q2 = $q3") + println("q2 * q1 = $q4\n") + println("q1 * q2 != q2 * q1 = ${q3 != q4}") +} diff --git a/Task/Quaternion-type/OoRexx/quaternion-type.rexx b/Task/Quaternion-type/OoRexx/quaternion-type.rexx new file mode 100644 index 0000000000..ab6a4bdaae --- /dev/null +++ b/Task/Quaternion-type/OoRexx/quaternion-type.rexx @@ -0,0 +1,150 @@ +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/Ruby/quaternion-type-1.rb b/Task/Quaternion-type/Ruby/quaternion-type-1.rb deleted file mode 100644 index 8e9c423b96..0000000000 --- a/Task/Quaternion-type/Ruby/quaternion-type-1.rb +++ /dev/null @@ -1,58 +0,0 @@ -require 'matrix' # For Vector#norm - -class Quaternion - def initialize(*parts) - raise "Invalid number of quaternion parts" unless parts.length == 4 - @parts, @vector = parts, Vector[*parts] - end - - def to_a; @parts; end - def to_s; "Quaternion#{to_a.to_s}" end - def complex_parts; [Complex(*to_a[0..1]), Complex(*to_a[2..3])]; end - def zip(other); to_a.zip(other.to_a); end - - def real; @parts.first; end - def imag; @parts[1..3]; end - def conj; Quaternion.new(real, *imag.map(&:-@)); end - def norm; @vector.norm; end # Or: Math.sqrt(to_a.reduce { |sum, e| sum + e**2 }) # In Rails: Math.sqrt(to_a.sum { e**2 }) - - def ==(other); to_a == other.to_a end - def -@; Quaternion.new(*to_a.map(&:-@)); end - def -(other); self + -other; end - - def +(other) - case other - when Numeric - Quaternion.new(real + other, *imag) - when Quaternion - Quaternion.new(*zip(other).map { |x,y| x + y }) # In Rails: zip(other).map(&:sum) # Or: (vector + other.vector).to_a - end - end - - def *(other) - case other - when Numeric - Quaternion.new(*to_a.map { |x| x * other }) # Or: (vector * other).to_a - when Quaternion - # Multiplication of quaternions in C x C space. See "Cayley-Dickson construction". - a, b, c, d = *complex_parts, *other.complex_parts - x, y = a*c - d.conj*b, a*d + b*c.conj - Quaternion.new(x.real, x.imag, y.real, y.imag) - end - end - - # Coerce is called by Ruby to return a compatible type/receiver when the called method/operation does not accept a Quaternion - def coerce(other) - case other - when Numeric then [Scalar.new(other), self] - else raise TypeError, "#{other.class} can't be coerced into #{self.class}" - end - end - - class Scalar - def initialize(val); @val = val; end - def +(other); other + @val; end - def *(other); other * @val; end - def -(other); Quaternion.new(@val, 0, 0, 0) - other; end - end -end diff --git a/Task/Quaternion-type/Ruby/quaternion-type-2.rb b/Task/Quaternion-type/Ruby/quaternion-type-2.rb deleted file mode 100644 index d99ddb584c..0000000000 --- a/Task/Quaternion-type/Ruby/quaternion-type-2.rb +++ /dev/null @@ -1,38 +0,0 @@ -irb(main):001:0> require 'quaternion' -=> true -irb(main):002:0> q = Quaternion.new(1,2,3,4) -=> Quaternion[1, 2, 3, 4] -irb(main):003:0> q1 = Quaternion.new(2,3,4,5) -=> Quaternion[2, 3, 4, 5] -irb(main):004:0> q2 = Quaternion.new(3,4,5,6) -=> Quaternion[3, 4, 5, 6] -irb(main):005:0> r = 7 -=> 7 -irb(main):006:0> q.norm -=> 5.477225575051661 -irb(main):007:0> q1.norm -=> 7.3484692283495345 -irb(main):008:0> q2.norm -=> 9.273618495495704 -irb(main):009:0> -q -=> Quaternion[-1, -2, -3, -4] -irb(main):010:0> q.conj -=> Quaternion[1, -2, -3, -4] -irb(main):011:0> q1 + q2 -=> Quaternion[5, 7, 9, 11] -irb(main):012:0> q2 + q1 -=> Quaternion[5, 7, 9, 11] -irb(main):013:0> q + r -=> Quaternion[8, 2, 3, 4] -irb(main):014:0> r + q -=> Quaternion[8, 2, 3, 4] -irb(main):015:0> q * r -=> Quaternion[7, 14, 21, 28] -irb(main):016:0> r * q -=> Quaternion[7, 14, 21, 28] -irb(main):017:0> q1 * q2 -=> Quaternion[-56, 16, 24, 26] -irb(main):018:0> q2 * q1 -=> Quaternion[-56, 18, 20, 28] -irb(main):019:0> q1 * q2 != q2 * q1 -=> true diff --git a/Task/Quaternion-type/Zkl/quaternion-type-1.zkl b/Task/Quaternion-type/Zkl/quaternion-type-1.zkl new file mode 100644 index 0000000000..4b0e4706c0 --- /dev/null +++ b/Task/Quaternion-type/Zkl/quaternion-type-1.zkl @@ -0,0 +1,53 @@ +class Quat{ + fcn init(real=0,i1=0,i2=0,i3=0){ + var [const] vector= // Quat(r,i,j,k) or Quat( (r,i,j,k) ) + (if(List.isType(real)) real else vm.arglist).apply("toFloat"); + var r,i,j,k; r,i,j,k=vector; // duplicate data for ease of coding + var [const] // properties: This is one way to do it + norm2=vector.apply("pow",2).sum(0.0), // Norm squared + abs=norm2.sqrt(), // Norm + arg=(r/abs()).acos(), // Theta !!!this may be incorrect... + ; + } + fcn toString { String("[",vector.concat(","),"]") } + var [const proxy] // properties that need calculation (or are recursive) + conj =fcn{ Quat(r,-i,-j,-k) }, // Conjugate + recip =fcn{ n2:=norm2; Quat(r/n2,-i/n2,-j/n2,-k/n2) },// Reciprocal + pureim =fcn{ Quat(0, i, j, k) }, // Pure imagery + versor =fcn{ self / abs; }, // Unit versor + iversor=fcn{ pureim / pureim.abs; }, // Unit versor of imagery part + ; + + fcn __opEQ(z) { r == z.r and i == z.i and j == z.j and k == z.k } + fcn __opNEQ(z){ (not (self==z)) } + + fcn __opNegate{ Quat(-r, -i, -j, -k) } + fcn __opAdd(z){ + if (Quat.isInstanceOf(z)) Quat(vector.zipWith('+,z.vector)); + else Quat(r+z,i,j,k); + } + fcn __opSub(z){ + if (Quat.isInstanceOf(z)) Quat(vector.zipWith('-,z.vector)); + else Quat(r-z,vector.xplode(1)); // same as above + } + fcn __opMul(z){ + if (Quat.isInstanceOf(z)){ + Quat(r*z.r - i*z.i - j*z.j - k*z.k, + r*z.i + i*z.r + j*z.k - k*z.j, + r*z.j - i*z.k + j*z.r + k*z.i, + r*z.k + i*z.j - j*z.i + k*z.r); + } + else Quat(vector.apply('*(z))); + } + fcn __opDiv(z){ + if (Quat.isInstanceOf(z)) self*z.recip; + else Quat(r/z,i/z,j/z,k/z); + } + + fcn pow(r){ exp(r*iversor*arg)*abs.pow(r) } // Power function + fcn log{ iversor*(r / abs).acos() + abs.log() } + fcn exp{ // e^q + inorm:=pureim.abs; + (iversor*inorm.sin() + inorm.cos()) * r.exp(); + } +} diff --git a/Task/Quaternion-type/Zkl/quaternion-type-2.zkl b/Task/Quaternion-type/Zkl/quaternion-type-2.zkl new file mode 100644 index 0000000000..5fcd1058d3 --- /dev/null +++ b/Task/Quaternion-type/Zkl/quaternion-type-2.zkl @@ -0,0 +1,39 @@ + // Demo code +r:=7; +q:=Quat(2,3,4,5); q1:=Quat(2,3,4,5); q2:=Quat(3,4,5,6); + +println("1. norm: q.abs: ", q.abs); +println("2. -q: ", -q); +println("3. conjugate: q.conj: ", q.conj); +println("4. Quat(r) + q: ", Quat(r) + q); +println(" q + r: ", q + r); +println("5. q1 + q2: ", q1 + q2); +println("6. Quat(r) * q: ", Quat(r) * q); +println(" q * r: ", q * r); +println("7. q1 * q2: ", q1 * q2); +println(" q2 * q1: ", q2 * q1); +println("8. q1 * q2 == q2 * q1 ? ", q1 * q2 == q2 * q1); + +i:=Quat(0,1); j:=Quat(0,0,1); k:=Quat(0,0,0,1); +println("9.1 i * i: ", i * i); +println(" J * j: ", j * j); +println(" k * k: ", k * k); +println(" i * j * k: ", i * j * k); + +println("9.2 q1 / q2: ", q1 / q2); +println("9.3 q1 / q2 * q2: ", q1 / q2 * q2); +println(" q2 * q1 / q2: ", q2 * q1 / q2); +println("9.4 (i * pi).exp(): ", (i * (0.0).pi).exp()); +println(" exp(j * pi): ", (j * (0.0).pi).exp()); +println(" exp(k * pi): ", (k * (0.0).pi).exp()); +println(" q.exp(): ", q.exp()); +println(" q.log(): ", q.log()); +println(" q.log().exp(): ", q.log().exp()); +println(" q.exp().log(): ", q.exp().log()); + +s:=q.exp().log(); +println("9.5 let s=q.exp().log(): ", s); +println(" s.exp(): ", s.exp()); +println(" s.log(): ", s.log()); +println(" s.log().exp(): ", s.log().exp()); +println(" s.exp().log(): ", s.exp().log()); diff --git a/Task/Queue-Definition/ALGOL-W/queue-definition.alg b/Task/Queue-Definition/ALGOL-W/queue-definition.alg new file mode 100644 index 0000000000..a851757079 --- /dev/null +++ b/Task/Queue-Definition/ALGOL-W/queue-definition.alg @@ -0,0 +1,51 @@ +begin + % define a Queue type that will hold StringQueueElements % + record StringQueue ( reference(StringQueueElement) front, back ); + % define the StringQueueElement type % + record StringQueueElement ( string(8) element + ; reference(StringQueueElement) next + ); + % we would need separate types for other element types % + % adds s to the end of the StringQueue q % + procedure pushString ( reference(StringQueue) value q + ; string(8) value e + ) ; + begin + reference(StringQueueElement) newElement; + newElement := StringQueueElement( e, null ); + if front(q) = null then begin + % adding to an empty queue % + front(q) := newElement; + back(q) := newElement + end + else begin + % the queue is not empty % + next(back(q)) := newElement; + back(q) := newElement + end + end pushString ; + % removes an element from the front of the StringQueue q % + % asserts the queue is not empty, which will stop the % + % program if it is % + string(8) procedure popString ( reference(StringQueue) value q ) ; + begin + string(8) v; + assert( not isEmptyStringQueue( q ) ); + v := element(front(q)); + front(q) := next(front(q)); + if front(q) = null then % just popped the last element % back(q) := null; + v + end popStringQueue ; + % returns true if the StringQueue q is empty, false otherwise % + logical procedure isEmptyStringQueue ( reference(StringQueue) value q ) ; front(q) = null; + + begin % test the StringQueue operations % + reference(StringQueue) q; + q := StringQueue( null, null ); + pushString( q, "fred" ); + pushString( q, "whilma" ); + pushString( q, "betty" ); + pushString( q, "barney" ); + while not isEmptyStringQueue( q ) do write( popString( q ) ) + end +end. diff --git a/Task/Queue-Definition/CoffeeScript/queue-definition-1.coffee b/Task/Queue-Definition/CoffeeScript/queue-definition-1.coffee deleted file mode 100644 index 46b538ac3c..0000000000 --- a/Task/Queue-Definition/CoffeeScript/queue-definition-1.coffee +++ /dev/null @@ -1,38 +0,0 @@ -# Implement a fifo as an array of arrays, to -# greatly amortize dequeue costs, at some expense of -# memory overhead and insertion time. The speedup -# depends on the underlying JS implementation, but -# it's significant on node.js. -Fifo = -> - max_chunk = 512 - arr = [] # array of arrays - count = 0 - - self = - enqueue: (elem) -> - if count == 0 or arr[arr.length-1].length >= max_chunk - arr.push [] - count += 1 - arr[arr.length-1].push elem - dequeue: (elem) -> - throw Error("queue is empty") if count == 0 - val = arr[0].shift() - count -= 1 - if arr[0].length == 0 - arr.shift() - val - is_empty: (elem) -> - count == 0 - -# test -do -> - max = 5000000 - q = Fifo() - for i in [1..max] - q.enqueue - number: i - - console.log q.dequeue() - while !q.is_empty() - v = q.dequeue() - console.log v diff --git a/Task/Queue-Definition/CoffeeScript/queue-definition-2.coffee b/Task/Queue-Definition/CoffeeScript/queue-definition-2.coffee deleted file mode 100644 index b0629ab927..0000000000 --- a/Task/Queue-Definition/CoffeeScript/queue-definition-2.coffee +++ /dev/null @@ -1,7 +0,0 @@ -> time coffee fifo.coffee -{ number: 1 } -{ number: 5000000 } - -real 0m2.394s -user 0m2.089s -sys 0m0.265s diff --git a/Task/Queue-Definition/FreeBASIC/queue-definition-1.freebasic b/Task/Queue-Definition/FreeBASIC/queue-definition-1.freebasic new file mode 100644 index 0000000000..7bb2479bae --- /dev/null +++ b/Task/Queue-Definition/FreeBASIC/queue-definition-1.freebasic @@ -0,0 +1,89 @@ +' FB 1.05.0 Win64 + +' queue_rosetta.bi +' simple generic Queue type + +#Define Queue(T) Queue_##T + +#Macro Declare_Queue(T) +Type Queue(T) + Public: + Declare Constructor() + Declare Destructor() + Declare Property capacity As Integer + Declare Property count As Integer + Declare Property empty As Boolean + Declare Property front As T + Declare Function pop() As T + Declare Sub push(item As T) + Private: + a(any) As T + count_ As Integer = 0 + Declare Function resize(size As Integer) As Integer +End Type + +Constructor Queue(T)() + Redim a(0 To 0) '' create a default T instance for various purposes +End Constructor + +Destructor Queue(T)() + Erase a +End Destructor + +Property Queue(T).capacity As Integer + Return UBound(a) +End Property + +Property Queue(T).count As Integer + Return count_ +End Property + +Property Queue(T).empty As Boolean + Return count_ = 0 +End Property + +Property Queue(T).front As T + If count_ > 0 Then + Return a(1) + End If + Print "Error: Attempted to access 'front' element of an empty queue" + Return a(0) '' return default element +End Property + +Function Queue(T).pop() As T + If count_ > 0 Then + Dim value As T = a(1) + If count_ > 1 Then '' move remaining elements to fill space vacated + For i As Integer = 2 To count_ + a(i - 1) = a(i) + Next + End If + a(count_) = a(0) '' zero last element + count_ -= 1 + Return value + End If + Print "Error: Attempted to remove 'front' element of an empty queue" + Return a(0) '' return default element +End Function + +Sub Queue(T).push(item As T) + Dim size As Integer = UBound(a) + count_ += 1 + If count_ > size Then + size = resize(size) + Redim Preserve a(0 to size) + End If + a(count_) = item +End Sub + +Function Queue(T).resize(size As Integer) As Integer + If size = 0 Then + size = 4 + ElseIf size <= 32 Then + size = 2 * size + Else + size += 32 + End If + Return size +End Function +#EndMacro diff --git a/Task/Queue-Definition/FreeBASIC/queue-definition-2.freebasic b/Task/Queue-Definition/FreeBASIC/queue-definition-2.freebasic new file mode 100644 index 0000000000..565d002d8f --- /dev/null +++ b/Task/Queue-Definition/FreeBASIC/queue-definition-2.freebasic @@ -0,0 +1,53 @@ +' FB 1.05.0 Win64 + +#Include "queue_rosetta.bi" + +Type Cat + name As String + age As Integer + Declare Constructor + Declare Constructor(name_ As string, age_ As integer) + Declare Operator Cast() As String +end type + +Constructor Cat '' default constructor +End Constructor + +Constructor Cat(name_ As String, age_ As Integer) + name = name_ + age = age_ +End Constructor + +Operator Cat.Cast() As String + Return "[" + name + ", " + Str(age) + "]" +End Operator + +Declare_Queue(Cat) '' expand Queue type for Cat instances + +Dim CatQueue As Queue(Cat) + +Var felix = Cat("Felix", 8) +Var sheba = Cat("Sheba", 4) +Var fluffy = Cat("Fluffy", 2) +With CatQueue '' push these Cat instances into the Queue + .push(felix) + .push(sheba) + .push(fluffy) +End With +Print "Number of Cats in the Queue :" ; CatQueue.count +Print "Capacity of Cat Queue :" ; CatQueue.capacity +Print "Front Cat : "; CatQueue.front +CatQueue.pop() +Print "Front Cat now : "; CatQueue.front +Print "Number of Cats in the Queue :" ; CatQueue.count +CatQueue.pop() +Print "Front Cat now : "; CatQueue.front +Print "Number of Cats in the Queue :" ; CatQueue.count +Print "Is Queue empty now : "; CatQueue.empty +catQueue.pop() +Print "Number of Cats in the Queue :" ; CatQueue.count +Print "Is Queue empty now : "; CatQueue.empty +catQueue.pop() +Print +Print "Press any key to quit" +Sleep diff --git a/Task/Queue-Definition/jq/queue-definition-1.jq b/Task/Queue-Definition/Jq/queue-definition-1.jq similarity index 100% rename from Task/Queue-Definition/jq/queue-definition-1.jq rename to Task/Queue-Definition/Jq/queue-definition-1.jq diff --git a/Task/Queue-Definition/jq/queue-definition-2.jq b/Task/Queue-Definition/Jq/queue-definition-2.jq similarity index 100% rename from Task/Queue-Definition/jq/queue-definition-2.jq rename to Task/Queue-Definition/Jq/queue-definition-2.jq diff --git a/Task/Queue-Definition/Kotlin/queue-definition.kotlin b/Task/Queue-Definition/Kotlin/queue-definition.kotlin new file mode 100644 index 0000000000..d9837ace90 --- /dev/null +++ b/Task/Queue-Definition/Kotlin/queue-definition.kotlin @@ -0,0 +1,47 @@ +// version 1.1.2 + +import java.util.LinkedList + +class Queue { + private val data = LinkedList() + + val size get() = data.size + + val empty get() = size == 0 + + fun push(element: E) = data.add(element) + + fun pop(): E { + if (empty) throw RuntimeException("Can't pop elements from an empty queue") + return data.removeFirst() + } + + val top: E + get() { + if (empty) throw RuntimeException("Empty queue can't have a top element") + return data.first() + } + + fun clear() = data.clear() + + override fun toString() = data.toString() +} + +fun main(args: Array) { + val q = Queue() + (1..5).forEach { q.push(it) } + println(q) + println("Size of queue = ${q.size}") + print("Popping: ") + (1..3).forEach { print("${q.pop()} ") } + println("\nRemaining in queue: $q") + println("Top element is now ${q.top}") + q.clear() + println("After clearing, queue is ${if(q.empty) "empty" else "not empty"}") + try { + q.pop() + } + catch (e: Exception) { + println(e.message) + } +} diff --git a/Task/Queue-Definition/Nimrod/queue-definition.nimrod b/Task/Queue-Definition/Nimrod/queue-definition.nimrod deleted file mode 100644 index 62ca733a77..0000000000 --- a/Task/Queue-Definition/Nimrod/queue-definition.nimrod +++ /dev/null @@ -1,18 +0,0 @@ -import queues - -# defining push & pop (obviously optional) -proc push*[T](q: var TQueue[T]; item: T) = - add(q,item) -proc pop*[T](q: var TQueue[T]): T = - result = dequeue(q) - -var fifo: TQueue[int] = initQueue[int]() - -fifo.push(26) -fifo.push(99) -fifo.push(2) -echo("Fifo size: ", fifo.len()) -echo("Popping: ", fifo.pop()) -echo("Popping: ", fifo.pop()) -echo("Popping: ", fifo.pop()) -#echo("Popping: ", fifo.pop()) # popping an empty stack raises [EAssertionFailed] diff --git a/Task/Queue-Definition/Zkl/queue-definition-1.zkl b/Task/Queue-Definition/Zkl/queue-definition-1.zkl new file mode 100644 index 0000000000..36a10b749d --- /dev/null +++ b/Task/Queue-Definition/Zkl/queue-definition-1.zkl @@ -0,0 +1,6 @@ +class Queue{ + var [const] q=List(); + fcn push { q.append(vm.pasteArgs()) } + fcn pop { q.pop(0) } + fcn empty { q.len()==0 } +} diff --git a/Task/Queue-Definition/Zkl/queue-definition-2.zkl b/Task/Queue-Definition/Zkl/queue-definition-2.zkl new file mode 100644 index 0000000000..9b7309f44b --- /dev/null +++ b/Task/Queue-Definition/Zkl/queue-definition-2.zkl @@ -0,0 +1,5 @@ +q:=Queue(); +q.push(1,2,3); +q.pop(); //-->1 +q.empty(); //-->False +q.pop();q.pop();q.pop() //-->IndexError thrown diff --git a/Task/Queue-Usage/Astro/queue-usage.astro b/Task/Queue-Usage/Astro/queue-usage.astro new file mode 100644 index 0000000000..05f46159e8 --- /dev/null +++ b/Task/Queue-Usage/Astro/queue-usage.astro @@ -0,0 +1,7 @@ +let myQueue = Queue() +myQueue.push 'foo' +myQueue.push 'bar' +myQueue.push 'baz' +print myQueue.pop() # => 'foo' +print myQueue.pop() # => 'bar' +print myQueue.pop() # => 'baz' diff --git a/Task/Queue-Usage/Elena/queue-usage.elena b/Task/Queue-Usage/Elena/queue-usage.elena index 6d1985888d..714398a545 100644 --- a/Task/Queue-Usage/Elena/queue-usage.elena +++ b/Task/Queue-Usage/Elena/queue-usage.elena @@ -1,25 +1,24 @@ -#import system. -#import system'collections. -#import extensions. +import system'collections. +import extensions. -#symbol program = +program = [ // Create a queue and "push" items into it - #var queue := Queue new. + var queue := Queue new. queue push:1. queue push:3. queue push:5. // "Pop" items from the queue in FIFO order - console writeLine:(queue pop). // 1 - console writeLine:(queue pop). // 3 - console writeLine:(queue pop). // 5 + console printLine(queue pop). // 1 + console printLine(queue pop). // 3 + console printLine(queue pop). // 5 // To tell if the queue is empty, we check the count - console writeLine:"queue is ":((queue length == 0) iif:"empty":"nonempty"). + console printLine("queue is ",(queue length == 0) iif("empty","nonempty")). // If we try to pop from an empty queue, an exception // is thrown. - queue pop | if &Error: e [ console writeLine:"Queue empty.". ]. + queue pop | if(:e)[ console writeLine:"Queue empty.". ]. ]. diff --git a/Task/Queue-Usage/Elixir/queue-usage-1.elixir b/Task/Queue-Usage/Elixir/queue-usage-1.elixir new file mode 100644 index 0000000000..a76c0a342d --- /dev/null +++ b/Task/Queue-Usage/Elixir/queue-usage-1.elixir @@ -0,0 +1,10 @@ +defmodule Queue do + def empty?([]), do: true + def empty?(_), do: false + + def pop([h|t]), do: {h,t} + + def push(q,t), do: q ++ [t] + + def front([h|_]), do: h +end diff --git a/Task/Queue-Usage/Elixir/queue-usage-2.elixir b/Task/Queue-Usage/Elixir/queue-usage-2.elixir new file mode 100644 index 0000000000..ddc1274e78 --- /dev/null +++ b/Task/Queue-Usage/Elixir/queue-usage-2.elixir @@ -0,0 +1,14 @@ +iex(2)> q = [1,2,3,4,5] +[1, 2, 3, 4, 5] +iex(3)> Queue.push(q,10) +[1, 2, 3, 4, 5, 10] +iex(4)> front=Queue.front(q) +1 +iex(5)> Queue.empty?(q) +false +iex(6)> Queue.pop(q) +{1, [2, 3, 4, 5]} +iex(7)> l=[] +[] +iex(8)> Queue.empty?(l) +true diff --git a/Task/Queue-Usage/FreeBASIC/queue-usage.freebasic b/Task/Queue-Usage/FreeBASIC/queue-usage.freebasic new file mode 100644 index 0000000000..1a79568dbe --- /dev/null +++ b/Task/Queue-Usage/FreeBASIC/queue-usage.freebasic @@ -0,0 +1,28 @@ +' FB 1.05.0 Win64 + +#Include "queue_rosetta.bi" '' include macro-based generic Queue type used in earlier task + +Declare_Queue(String) '' expand Queue type for Strings + +Dim stringQueue As Queue(String) +With stringQueue '' push some strings into the Queue + .push("first") + .push("second") + .push("third") + .push("fourth") + .push("fifth") +End With +Print "Number of Strings in the Queue :" ; stringQueue.count +Print "Capacity of string Queue :" ; stringQueue.capacity +Print +' now pop them +While Not stringQueue.empty + Print stringQueue.pop(); " popped" +Wend +Print +Print "Number of Strings in the Queue :" ; stringQueue.count +Print "Capacity of string Queue :" ; stringQueue.capacity '' capacity should be unchanged +Print "Is Queue empty now : "; stringQueue.empty +Print +Print "Press any key to quit" +Sleep diff --git a/Task/Queue-Usage/Kotlin/queue-usage.kotlin b/Task/Queue-Usage/Kotlin/queue-usage.kotlin new file mode 100644 index 0000000000..05a3c38b31 --- /dev/null +++ b/Task/Queue-Usage/Kotlin/queue-usage.kotlin @@ -0,0 +1,22 @@ +// version 1.1.2 + +import java.util.* + +fun main(args: Array) { + val q: Queue = ArrayDeque() + (1..5).forEach { q.add(it) } + println(q) + println("Size of queue = ${q.size}") + print("Removing: ") + (1..3).forEach { print("${q.remove()} ") } + println("\nRemaining in queue: $q") + println("Head element is now ${q.element()}") + q.clear() + println("After clearing, queue is ${if(q.isEmpty()) "empty" else "not empty"}") + try { + q.remove() + } + catch (e: NoSuchElementException) { + println("Can't remove elements from an empty queue") + } +} diff --git a/Task/Queue-Usage/Nimrod/queue-usage.nimrod b/Task/Queue-Usage/Nimrod/queue-usage.nimrod deleted file mode 100644 index 3933cebb86..0000000000 --- a/Task/Queue-Usage/Nimrod/queue-usage.nimrod +++ /dev/null @@ -1,12 +0,0 @@ -import queues - -var deq: TQueue[int] = initQueue[int]() - -deq.enqueue(26) -deq.add(99) # same as enqueue() -deq.enqueue(2) -echo("Dequeue size: ", deq.len()) -echo("De-queue: ", deq.dequeue()) -echo("De-queue: ", deq.dequeue()) -echo("De-queue: ", deq.dequeue()) -#echo("De-queue: ", deq.dequeue()) # dequeue an empty dequeue raises [EAssertionFailed] diff --git a/Task/Queue-Usage/OoRexx/queue-usage.rexx b/Task/Queue-Usage/OoRexx/queue-usage.rexx new file mode 100644 index 0000000000..09dbb3c048 --- /dev/null +++ b/Task/Queue-Usage/OoRexx/queue-usage.rexx @@ -0,0 +1,5 @@ +q = .queue~new -- create an instance +q~queue(3) -- adds to the end, but this is at the front +q~push(1) -- push on the front +q~queue(2) -- add to the end +say q~pull q~pull q~pull q~isempty -- should display all and be empty diff --git a/Task/Quickselect-algorithm/ALGOL-68/quickselect-algorithm.alg b/Task/Quickselect-algorithm/ALGOL-68/quickselect-algorithm.alg new file mode 100644 index 0000000000..bc05bcbc02 --- /dev/null +++ b/Task/Quickselect-algorithm/ALGOL-68/quickselect-algorithm.alg @@ -0,0 +1,57 @@ +BEGIN + # returns the kth lowest element of list using the quick select algorithm # + PRIO QSELECT = 1; + OP QSELECT = ( INT k, REF[]INT list )INT: + IF LWB list > UPB list THEN + # empty list # + 0 + ELSE + # non-empty list # + # partitions the subset of list from left to right # + PROC partition = ( REF[]INT list, INT left, right, pivot index )INT: + BEGIN + # swaps elements a and b in list # + PROC swap = ( REF[]INT list, INT a, b )VOID: + BEGIN + INT t = list[ a ]; + list[ a ] := list[ b ]; + list[ b ] := t + END # swap # ; + INT pivot value = list[ pivot index ]; + swap( list, pivot index, right ); + INT store index := left; + FOR i FROM left TO right - 1 DO + IF list[ i ] < pivot value THEN + swap( list, store index, i ); + store index +:= 1 + FI + OD; + swap( list, right, store index ); + store index + END # partition # ; + INT left := LWB list, right := UPB list, result := 0; + BOOL found := FALSE; + WHILE NOT found DO + IF left = right THEN + result := list[ left ]; + found := TRUE + ELSE + INT pivot index = partition( list, left, right, left + ENTIER ( ( random * ( right - left ) + 1 ) ) ); + IF k = pivot index THEN + result := list[ k ]; + found := TRUE + ELIF k < pivot index THEN + right := pivot index - 1 + ELSE + left := pivot index + 1 + FI + FI + OD; + result + FI # QSELECT # ; + # test cases # + FOR i TO 10 DO + [ 1 : 10 ]INT test := []INT( 9, 8, 7, 6, 5, 0, 1, 2, 3, 4 ); + print( ( whole( i, -2 ), ": ", whole( i QSELECT test, -3 ), newline ) ) + OD +END diff --git a/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-1.js b/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-1.js new file mode 100644 index 0000000000..765b950c63 --- /dev/null +++ b/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-1.js @@ -0,0 +1,71 @@ +// this just helps make partition read better +function swap(items, firstIndex, secondIndex) { + var temp = items[firstIndex]; + items[firstIndex] = items[secondIndex]; + items[secondIndex] = temp; +}; + +// many algorithms on this page violate +// the constraint that partition operates in place +function partition(array, from, to) { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random + var pivotIndex = getRandomInt(from, to), + pivot = array[pivotIndex]; + swap(array, pivotIndex, to); + pivotIndex = from; + + for(var i = from; i <= to; i++) { + if(array[i] < pivot) { + swap(array, pivotIndex, i); + pivotIndex++; + } + }; + swap(array, pivotIndex, to); + + return pivotIndex; +}; + +// later versions of JS have TCO so this is safe +function quickselectRecursive(array, from, to, statistic) { + if(array.length === 0 || statistic > array.length - 1) { + return undefined; + }; + + var pivotIndex = partition(array, from, to); + if(pivotIndex === statistic) { + return array[pivotIndex]; + } else if(pivotIndex < statistic) { + return quickselectRecursive(array, pivotIndex, to, statistic); + } else if(pivotIndex > statistic) { + return quickselectRecursive(array, from, pivotIndex, statistic); + } +}; + +function quickselectIterative(array, k) { + if(array.length === 0 || k > array.length - 1) { + return undefined; + }; + + var from = 0, to = array.length, + pivotIndex = partition(array, from, to); + + while(pivotIndex !== k) { + pivotIndex = partition(array, from, to); + if(pivotIndex < k) { + from = pivotIndex; + } else if(pivotIndex > k) { + to = pivotIndex; + } + }; + + return array[pivotIndex]; +}; + +KthElement = { + find: function(array, element) { + var k = element - 1; + return quickselectRecursive(array, 0, array.length, k); + // you can also try out the Iterative version + // return quickselectIterative(array, k); + } +} diff --git a/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-2.js b/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-2.js new file mode 100644 index 0000000000..50795df7ec --- /dev/null +++ b/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-2.js @@ -0,0 +1,3 @@ +var array = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4], + ks = Array.apply(null, {length: 10}).map(Number.call, Number); +ks.map(k => { KthElement.find(array, k) }); diff --git a/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-3.js b/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-3.js new file mode 100644 index 0000000000..6d6ea476d9 --- /dev/null +++ b/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-3.js @@ -0,0 +1 @@ +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; diff --git a/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-4.js b/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-4.js new file mode 100644 index 0000000000..cc7282f447 --- /dev/null +++ b/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-4.js @@ -0,0 +1,52 @@ +(() => { + 'use strict'; + + // QUICKSELECT ------------------------------------------------------------ + + // quickselect :: Ord a => Int -> [a] -> a + const quickSelect = (k, xxs) => { + const + [x, xs] = uncons(xxs), + [ys, zs] = partition(v => v < x, xs), + l = length(ys); + + return (k < l) ? ( + quickSelect(k, ys) + ) : (k > l) ? ( + quickSelect(k - l - 1, zs) + ) : x; + }; + + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // length :: [a] -> Int + const length = xs => xs.length; + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // partition :: Predicate -> List -> (Matches, nonMatches) + // partition :: (a -> Bool) -> [a] -> ([a], [a]) + const partition = (p, xs) => + xs.reduce((a, x) => + p(x) ? [a[0].concat(x), a[1]] : [a[0], a[1].concat(x)], [ + [], + [] + ]); + + // uncons :: [a] -> Maybe (a, [a]) + const uncons = xs => xs.length ? [xs[0], xs.slice(1)] : undefined; + + + // TEST ------------------------------------------------------------------- + const v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]; + + return map(i => quickSelect(i, v), enumFromTo(0, length(v) - 1)); +})(); diff --git a/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-5.js b/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-5.js new file mode 100644 index 0000000000..2fd0bd089c --- /dev/null +++ b/Task/Quickselect-algorithm/JavaScript/quickselect-algorithm-5.js @@ -0,0 +1 @@ +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] diff --git a/Task/Quickselect-algorithm/jq/quickselect-algorithm-1.jq b/Task/Quickselect-algorithm/Jq/quickselect-algorithm-1.jq similarity index 100% rename from Task/Quickselect-algorithm/jq/quickselect-algorithm-1.jq rename to Task/Quickselect-algorithm/Jq/quickselect-algorithm-1.jq diff --git a/Task/Quickselect-algorithm/jq/quickselect-algorithm-2.jq b/Task/Quickselect-algorithm/Jq/quickselect-algorithm-2.jq similarity index 100% rename from Task/Quickselect-algorithm/jq/quickselect-algorithm-2.jq rename to Task/Quickselect-algorithm/Jq/quickselect-algorithm-2.jq diff --git a/Task/Quickselect-algorithm/jq/quickselect-algorithm-3.jq b/Task/Quickselect-algorithm/Jq/quickselect-algorithm-3.jq similarity index 100% rename from Task/Quickselect-algorithm/jq/quickselect-algorithm-3.jq rename to Task/Quickselect-algorithm/Jq/quickselect-algorithm-3.jq diff --git a/Task/Quickselect-algorithm/Kotlin/quickselect-algorithm.kotlin b/Task/Quickselect-algorithm/Kotlin/quickselect-algorithm.kotlin new file mode 100644 index 0000000000..44e2dc6862 --- /dev/null +++ b/Task/Quickselect-algorithm/Kotlin/quickselect-algorithm.kotlin @@ -0,0 +1,45 @@ +// version 1.1.2 + +const val MAX = Int.MAX_VALUE +val rand = java.util.Random() + +fun partition(list:IntArray, left: Int, right:Int, pivotIndex: Int): Int { + val pivotValue = list[pivotIndex] + list[pivotIndex] = list[right] + list[right] = pivotValue + var storeIndex = left + for (i in left until right) { + if (list[i] < pivotValue) { + val tmp = list[storeIndex] + list[storeIndex] = list[i] + list[i] = tmp + storeIndex++ + } + } + val temp = list[right] + list[right] = list[storeIndex] + list[storeIndex] = temp + return storeIndex +} + +tailrec fun quickSelect(list: IntArray, left: Int, right: Int, k: Int): Int { + if (left == right) return list[left] + var pivotIndex = left + Math.floor((rand.nextInt(MAX) % (right - left + 1)).toDouble()).toInt() + pivotIndex = partition(list, left, right, pivotIndex) + if (k == pivotIndex) + return list[k] + else if (k < pivotIndex) + return quickSelect(list, left, pivotIndex - 1, k) + else + return quickSelect(list, pivotIndex + 1, right, k) +} + +fun main(args: Array) { + val list = intArrayOf(9, 8, 7, 6, 5, 0, 1, 2, 3, 4) + val right = list.size - 1 + for (k in 0..9) { + print(quickSelect(list, 0, right, k)) + if (k < 9) print(", ") + } + println() +} diff --git a/Task/Quickselect-algorithm/PicoLisp/quickselect-algorithm.l b/Task/Quickselect-algorithm/PicoLisp/quickselect-algorithm.l new file mode 100644 index 0000000000..b5b568f3aa --- /dev/null +++ b/Task/Quickselect-algorithm/PicoLisp/quickselect-algorithm.l @@ -0,0 +1,30 @@ +(seed (in "/dev/urandom" (rd 8))) +(de swapL (Lst X Y) + (let L (nth Lst Y) + (swap + L + (swap (nth Lst X) (car L)) ) ) ) +(de partition (Lst L R P) + (let V (get Lst P) + (swapL Lst R P) + (for I (range L R) + (and + (> V (get Lst I)) + (swapL Lst L I) + (inc 'L) ) ) + (swapL Lst L R) + L ) ) +(de quick (Lst N L R) + (default L (inc N) R (length Lst)) + (if (= L R) + (get Lst L) + (let P (partition Lst L R (rand L R)) + (cond + ((= N P) (get Lst N)) + ((> P N) (quick Lst N L P)) + (T (quick Lst N P R)) ) ) ) ) +(let Lst (9 8 7 6 5 0 1 2 3 4) + (println + (mapcar + '((N) (quick Lst N)) + (range 0 9) ) ) ) diff --git a/Task/Quickselect-algorithm/REXX/quickselect-algorithm-1.rexx b/Task/Quickselect-algorithm/REXX/quickselect-algorithm-1.rexx index 9de21f9872..671dca4653 100644 --- a/Task/Quickselect-algorithm/REXX/quickselect-algorithm-1.rexx +++ b/Task/Quickselect-algorithm/REXX/quickselect-algorithm-1.rexx @@ -1,10 +1,10 @@ /*REXX program sorts a list (which may be numbers) by using the quick select algorithm. */ parse arg list; if list='' then list=9 8 7 6 5 0 1 2 3 4 /*Not given? Use default.*/ say right('list: ', 22) list +#=words(list) + do i=1 for #; @.i=word(list, i) /*assign all the items ──► @. (array). */ + end /*i*/ /* [↑] #: number of items in the list.*/ say - do #=1 for words(list); @.#=word(list,#) /*assign all the items ──► @. (array). */ - end /*#*/ /* [↑] #: number of items in the list.*/ -#=#-1 /*adjust number of items in the list. */ do j=1 for # /*show 1 ──► # items place and value.*/ say right('item', 20) right(j, length(#))", value: " qSel(1, #, j) end /*j*/ diff --git a/Task/Quickselect-algorithm/REXX/quickselect-algorithm-2.rexx b/Task/Quickselect-algorithm/REXX/quickselect-algorithm-2.rexx index 3bbb74257d..9cfa665f10 100644 --- a/Task/Quickselect-algorithm/REXX/quickselect-algorithm-2.rexx +++ b/Task/Quickselect-algorithm/REXX/quickselect-algorithm-2.rexx @@ -1,10 +1,10 @@ /*REXX program sorts a list (which may be numbers) by using the quick select algorithm. */ parse arg list; if list='' then list=9 8 7 6 5 0 1 2 3 4 /*Not given? Use default.*/ say right('list: ', 22) list +#=words(list) + do i=1 for #; @.i=word(list, i) /*assign all the items ──► @. (array). */ + end /*i*/ /* [↑] #: number of items in the list.*/ say - do #=1 for words(list); @.#=word(list,#) /*assign all the items ──► @. (array). */ - end /*#*/ /* [↑] #: number of items in the list.*/ -#=#-1 /*adjust number of items in the list. */ do j=1 for # /*show 1 ──► # items place and value.*/ say right('item', 20) right(j, length(#))", value: " qSel(1, #, j) end /*j*/ diff --git a/Task/Quickselect-algorithm/Zkl/quickselect-algorithm-1.zkl b/Task/Quickselect-algorithm/Zkl/quickselect-algorithm-1.zkl new file mode 100644 index 0000000000..3e846b4f59 --- /dev/null +++ b/Task/Quickselect-algorithm/Zkl/quickselect-algorithm-1.zkl @@ -0,0 +1,23 @@ +fcn qselect(list,nth){ // in place quick select + fcn(list,left,right,nth){ + if (left==right) return(list[left]); + pivotIndex:=(left+right)/2; // or median of first,middle,last + + // partition + pivot:=list[pivotIndex]; + list.swap(pivotIndex,right); // move pivot to end + pivotIndex := left; + i:=left; do(right-left){ // foreach i in ([left..right-1]) + if (list[i] < pivot){ + list.swap(i,pivotIndex); + pivotIndex += 1; + } + i += 1; + } + list.swap(pivotIndex,right); // move pivot to final place + + if (nth==pivotIndex) return(list[nth]); + if (nth - -void quote(char const* c) -{ - while (*c) - { - switch(*c) - { - case '\\': - std::cout << "\\\\";break; - case '\n': - std::cout << "\\n";break; - case '\"': - std::cout << "\\\"";break; - default: - std::cout << *c; - } - ++c; - } -} - -int main() -{ - char const* parts[] = { - "#include \n\nvoid quote(char const* c)\n{\n while (*c)\n {\n switch(*c)\n {\n case '\\\\':\n std::cout << \"\\\\\\\\\";break;\n case '\\n':\n std::cout << \"\\\\n\";break;\n case '\\\"':\n std::cout << \"\\\\\\\"\";break;\n default:\n std::cout << *c;\n }\n ++c;\n }\n}\n\nint main()\n{\n char const* parts[] = {\n \"", - "\",\n \"", - "\"\n };\n \n std::cout << parts[0];\n quote(parts[0]);\n std::cout << parts[1];\n quote(parts[1]);\n std::cout << parts[1];\n quote(parts[2]);\n std::cout << parts[2];\n\n return 0;\n}\n" - }; - - std::cout << parts[0]; - quote(parts[0]); - std::cout << parts[1]; - quote(parts[1]); - std::cout << parts[1]; - quote(parts[2]); - std::cout << parts[2]; - - return 0; -} +#include +int main(){char n[]=R"(#include +int main(){char n[]=R"(%s%c";printf(n,n,41);})";printf(n,n,41);} diff --git a/Task/Quine/Dc/quine.dc b/Task/Quine/Dc/quine.dc new file mode 100644 index 0000000000..31cdd6f8bf --- /dev/null +++ b/Task/Quine/Dc/quine.dc @@ -0,0 +1 @@ +[91PP93P[dx]P]dx diff --git a/Task/Quine/Kotlin/quine.kotlin b/Task/Quine/Kotlin/quine.kotlin new file mode 100644 index 0000000000..9e95b78e65 --- /dev/null +++ b/Task/Quine/Kotlin/quine.kotlin @@ -0,0 +1,14 @@ +// version 1.1.2 + +const val F = """// version 1.1.2 + +const val F = %c%c%c%s%c%c%c + +fun main(args: Array) { + System.out.printf(F, 34, 34, 34, F, 34, 34, 34) +} +""" + +fun main(args: Array) { + System.out.printf(F, 34, 34, 34, F, 34, 34, 34) +} diff --git a/Task/Quine/M4/quine.m4 b/Task/Quine/M4/quine.m4 index 3835f5f58c..078c217dae 100644 --- a/Task/Quine/M4/quine.m4 +++ b/Task/Quine/M4/quine.m4 @@ -1,3 +1,3 @@ -define(`quine',``$1(`$1')'') -quine(`define(`quine',``$1(`$1')'') +define(`quine',``$1(`$1')'')dnl +quine(`define(`quine',``$1(`$1')'')dnl quine') diff --git a/Task/Quine/Objeck/quine.objeck b/Task/Quine/Objeck/quine.objeck new file mode 100644 index 0000000000..bc44b3ff73 --- /dev/null +++ b/Task/Quine/Objeck/quine.objeck @@ -0,0 +1 @@ +class Program { function : Main(args : String[]) ~ Nil { s := "class Program { function : Main(args : String[]) ~ Nil { s :=; IO.Console->Print(s->SubString(61))->Print(34->As(Char))->Print(s)->Print(34->As(Char))->PrintLine(s->SubString(61, 129)); } }"; IO.Console->Print(s->SubString(61))->Print(34->As(Char))->Print(s)->Print(34->As(Char))->PrintLine(s->SubString(61, 129)); } } diff --git a/Task/Quine/Ol/quine.ol b/Task/Quine/Ol/quine.ol new file mode 100644 index 0000000000..0ed3deb3a6 --- /dev/null +++ b/Task/Quine/Ol/quine.ol @@ -0,0 +1 @@ +((lambda (s) (display (list s (list (quote quote) s)))) (quote (lambda (s) (display (list s (list (quote quote) s)))))) diff --git a/Task/Quine/OoRexx/quine-1.rexx b/Task/Quine/OoRexx/quine-1.rexx new file mode 100644 index 0000000000..21b53095d7 --- /dev/null +++ b/Task/Quine/OoRexx/quine-1.rexx @@ -0,0 +1 @@ +say sourceline(1) diff --git a/Task/Quine/OoRexx/quine-2.rexx b/Task/Quine/OoRexx/quine-2.rexx new file mode 100644 index 0000000000..f6c728eb0f --- /dev/null +++ b/Task/Quine/OoRexx/quine-2.rexx @@ -0,0 +1 @@ +r="say'r='x2c(22)r||22~x2c';interpret r'";interpret r diff --git a/Task/Quine/OoRexx/quine-3.rexx b/Task/Quine/OoRexx/quine-3.rexx new file mode 100644 index 0000000000..ba2833b672 --- /dev/null +++ b/Task/Quine/OoRexx/quine-3.rexx @@ -0,0 +1 @@ +r=";say'r=.'r'.'r~changestr(.,'22'x,2)";say'r="'r'"'r~changestr(.,'22'x,2) diff --git a/Task/Quine/OoRexx/quine-4.rexx b/Task/Quine/OoRexx/quine-4.rexx new file mode 100644 index 0000000000..1f3e40b901 --- /dev/null +++ b/Task/Quine/OoRexx/quine-4.rexx @@ -0,0 +1 @@ +r=";say'r=�'r'�'r~bitor(,' ')";say'r="'r'"'r~bitor(,' ') diff --git a/Task/Quine/Pascal/quine-3.pascal b/Task/Quine/Pascal/quine-3.pascal new file mode 100644 index 0000000000..1b1d7e313b --- /dev/null +++ b/Task/Quine/Pascal/quine-3.pascal @@ -0,0 +1,20 @@ +program main(output);type string=packed array[1..60]of char; +var l:array[1..9]of string; c:array[1..7]of char; i:integer; +lc, a, o, k, n, e, s, t:char; begin +l[1]:='program main(output);type string=packed array[1..60]of char;'; +l[2]:='var l:array[1..9]of string; c:array[1..7]of char; i:integer;'; +l[3]:='lc, a, o, k, n, e, s, t:char; begin '; +l[4]:='for i := 1 to 3 do writeln(l[i]); '; +l[5]:='a:=c[1];t:=c[2];o:=c[3];k:=c[4];n:=c[5];e:=c[6];s:=c[7]; '; +l[6]:='for i := 1 to 9 do writeln(a,o,i:1,k,n,e,lc,l[i],lc,s); '; +l[7]:='writeln(a, t, n, e, lc, lc, lc, lc, s); '; +l[8]:='for i := 1 to 7 do write(t,o,i:1,k,n,e,lc,c[i],lc,s); '; +l[9]:='writeln; for i := 4 to 9 do writeln(l[i]); end. '; +lc:=''''; +c[1]:='l';c[2]:='c';c[3]:='[';c[4]:=']';c[5]:=':';c[6]:='=';c[7]:=';'; +for i := 1 to 3 do writeln(l[i]); +a:=c[1];t:=c[2];o:=c[3];k:=c[4];n:=c[5];e:=c[6];s:=c[7]; +for i := 1 to 9 do writeln(a,o,i:1,k,n,e,lc,l[i],lc,s); +writeln(a, t, n, e, lc, lc, lc, lc, s); +for i := 1 to 7 do write(t,o,i:1,k,n,e,lc,c[i],lc,s); +writeln; for i := 4 to 9 do writeln(l[i]); end. diff --git a/Task/Quine/R/quine-1.r b/Task/Quine/R/quine-1.r index fe0346a5f2..f01e4698c9 100644 --- a/Task/Quine/R/quine-1.r +++ b/Task/Quine/R/quine-1.r @@ -1,2 +1 @@ -(function(){x<-intToUtf8(34);s<-"(functio = 3 TO DATACOUNT - 1" - DATA " PRINT #1, s(nn(){x<-intToUtf8(34);s<-%s%s%s;cat(sprintf(s,x,s,x))})()";cat(sprintf(s,x,s,x))})() +(function(){x<-intToUtf8(34);s<-"(function(){x<-intToUtf8(34);s<-%s%s%s;cat(sprintf(s,x,s,x))})()";cat(sprintf(s,x,s,x))})() diff --git a/Task/Quine/Ruby/quine-5.rb b/Task/Quine/Ruby/quine-5.rb new file mode 100644 index 0000000000..17c08a35cb --- /dev/null +++ b/Task/Quine/Ruby/quine-5.rb @@ -0,0 +1 @@ +p open(__FILE__).read diff --git a/Task/Quine/X86-Assembly/quine-1.x86 b/Task/Quine/X86-Assembly/quine-1.x86 new file mode 100644 index 0000000000..388d2b5623 --- /dev/null +++ b/Task/Quine/X86-Assembly/quine-1.x86 @@ -0,0 +1 @@ +.global _start;_start:mov $p,%rsi;mov $1,%rax;mov $1,%rdi;mov $255,%rdx;syscall;mov $q,%rsi;mov $1,%rax;mov $1,%rdx;syscall;mov $p,%rsi;mov $1,%rax;mov $255,%rdx;syscall;mov $q,%rsi;mov $1,%rax;mov $1,%rdx;syscall;mov $60,%rax;syscall;q:.byte 34;p:.ascii ".global _start;_start:mov $p,%rsi;mov $1,%rax;mov $1,%rdi;mov $255,%rdx;syscall;mov $q,%rsi;mov $1,%rax;mov $1,%rdx;syscall;mov $p,%rsi;mov $1,%rax;mov $255,%rdx;syscall;mov $q,%rsi;mov $1,%rax;mov $1,%rdx;syscall;mov $60,%rax;syscall;q:.byte 34;p:.ascii " diff --git a/Task/Quine/X86-Assembly/quine-2.x86 b/Task/Quine/X86-Assembly/quine-2.x86 new file mode 100644 index 0000000000..a67c3f6ed9 --- /dev/null +++ b/Task/Quine/X86-Assembly/quine-2.x86 @@ -0,0 +1 @@ +.global _start;_start:mov $p,%ecx;mov $4,%eax;mov $1,%ebx;mov $264,%edx;int $0x80;mov $q,%ecx;mov $4,%eax;mov $1,%edx;int $0x80;mov $p,%ecx;mov $4,%eax;mov $264,%edx;int $0x80;mov $q,%ecx;mov $4,%eax;mov $1,%edx;int $0x80;mov $1,%eax;int $0x80;q:.byte 34;p:.ascii ".global _start;_start:mov $p,%ecx;mov $4,%eax;mov $1,%ebx;mov $264,%edx;int $0x80;mov $q,%ecx;mov $4,%eax;mov $1,%edx;int $0x80;mov $p,%ecx;mov $4,%eax;mov $264,%edx;int $0x80;mov $q,%ecx;mov $4,%eax;mov $1,%edx;int $0x80;mov $1,%eax;int $0x80;q:.byte 34;p:.ascii " diff --git a/Task/Quine/X86-Assembly/quine-3.x86 b/Task/Quine/X86-Assembly/quine-3.x86 new file mode 100644 index 0000000000..8e61dd451c --- /dev/null +++ b/Task/Quine/X86-Assembly/quine-3.x86 @@ -0,0 +1 @@ +python -c "from pprint import pprint;prog=open('quine.sx', 'r').read().split(';',24);pprint(prog)" | tr "[]" " " | perl -pe "s/( '|'(,| ))//g" diff --git a/Task/Quine/Zkl/quine-1.zkl b/Task/Quine/Zkl/quine-1.zkl new file mode 100644 index 0000000000..809457c27d --- /dev/null +++ b/Task/Quine/Zkl/quine-1.zkl @@ -0,0 +1,2 @@ +zkl: 123 +123 diff --git a/Task/Quine/Zkl/quine-2.zkl b/Task/Quine/Zkl/quine-2.zkl new file mode 100644 index 0000000000..b95a916ebd --- /dev/null +++ b/Task/Quine/Zkl/quine-2.zkl @@ -0,0 +1 @@ +s:="s:=%c%s%c;print(s.fmt(34,s,34));";print(s.fmt(34,s,34)); diff --git a/Task/Quine/Zkl/quine-3.zkl b/Task/Quine/Zkl/quine-3.zkl new file mode 100644 index 0000000000..9f92e8750e --- /dev/null +++ b/Task/Quine/Zkl/quine-3.zkl @@ -0,0 +1 @@ + a:="a:=;q:=(34).toChar();print(a[0,3]+q+a+q+a[3,*]);";q:=(34).toChar();print(a[0,3]+q+a+q+a[3,*]); diff --git a/Task/Quine/Zkl/quine-4.zkl b/Task/Quine/Zkl/quine-4.zkl new file mode 100644 index 0000000000..cc7d7b73a0 --- /dev/null +++ b/Task/Quine/Zkl/quine-4.zkl @@ -0,0 +1 @@ +reg c=0'|"|,s="reg c=0'|%c|,s=%c%s%c;s.fmt(c,c,s,c).print();";s.fmt(c,c,s,c).print(); diff --git a/Task/Quine/Zkl/quine-5.zkl b/Task/Quine/Zkl/quine-5.zkl new file mode 100644 index 0000000000..f4fb231aef --- /dev/null +++ b/Task/Quine/Zkl/quine-5.zkl @@ -0,0 +1 @@ +File(__FILE__).readln().print() diff --git a/Task/Quine/Zkl/quine-6.zkl b/Task/Quine/Zkl/quine-6.zkl new file mode 100644 index 0000000000..dcb874ca46 --- /dev/null +++ b/Task/Quine/Zkl/quine-6.zkl @@ -0,0 +1,4 @@ +fcn testQuine(quine){ + Compiler.Compiler.compileText(quine).__constructor(); out:=vm.regX; + println("\ndiff>>",quine-out,"<<"); +} diff --git a/Task/RIPEMD-160/FreeBASIC/ripemd-160.freebasic b/Task/RIPEMD-160/FreeBASIC/ripemd-160.freebasic index 12cc18172b..c631b57bfb 100644 --- a/Task/RIPEMD-160/FreeBASIC/ripemd-160.freebasic +++ b/Task/RIPEMD-160/FreeBASIC/ripemd-160.freebasic @@ -9,20 +9,20 @@ Function RIPEMD_160(message As String) As String #Macro f1(x, y, z) (x Xor y Xor z) ' (0 <= j <= 15) - #EndMacro + #Macro f2(x, y, z) ((x And y) Or ((Not x) And z)) ' (16 <= j <= 31) - #EndMacro + #Macro f3(x, y, z) ((x Or (Not y)) Xor z) ''(32 <= j <= 47) - #EndMacro + #Macro f4(x, y, z) ((x And z) Or (y And (Not z))) ''(48 <= j <= 63) - #EndMacro + #Macro f5(x, y, z) (x Xor (y Or (Not z))) ''(64 <= j <= 79) #EndMacro @@ -172,7 +172,6 @@ Dim As String test = "Rosetta Code" Print Print test; " => "; RIPEMD_160(test) - ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" diff --git a/Task/RIPEMD-160/PARI-GP/ripemd-160-3.pari b/Task/RIPEMD-160/PARI-GP/ripemd-160-3.pari new file mode 100644 index 0000000000..f21b069eae --- /dev/null +++ b/Task/RIPEMD-160/PARI-GP/ripemd-160-3.pari @@ -0,0 +1,8 @@ +install(RIPEMD160,"vsLs",,"/usr/lib/x86_64-linux-gnu/libcrypto.so") +ripemd160(a)= +{ + my(b=Strchr(vectorsmall(20,i,32))); + RIPEMD160(a,length(a),b); + Strprintf("%x",fromdigits(Vec(Vecsmall(b)),256)); +} +ripemd160("Rosetta Code") diff --git a/Task/RIPEMD-160/Perl-6/ripemd-160.pl6 b/Task/RIPEMD-160/Perl-6/ripemd-160.pl6 index f7efef4e4b..884513308e 100644 --- a/Task/RIPEMD-160/Perl-6/ripemd-160.pl6 +++ b/Task/RIPEMD-160/Perl-6/ripemd-160.pl6 @@ -42,16 +42,16 @@ constant F = { ($^x +& $^z) +| ($^y +& m^$^z) }, * +^ (* +| m^*), ; -constant K1 = <0x00000000 0x5a827999 0x6ed9eba1 0x8f1bbcdc 0xa953fd4e> »xx» 16; -constant K2 = <0x50a28be6 0x5c4dd124 0x6d703ef3 0x7a6d76e9 0x00000000> »xx» 16; +constant K1 = flat | <0x00000000 0x5a827999 0x6ed9eba1 0x8f1bbcdc 0xa953fd4e> »xx» 16; +constant K2 = flat | <0x50a28be6 0x5c4dd124 0x6d703ef3 0x7a6d76e9 0x00000000> »xx» 16; our proto rmd160($) returns Blob {*} multi rmd160(Str $s) { rmd160 $s.encode: 'ascii' } multi rmd160(Blob $data) { - my @b = $data.list, 0x80; + my @b = | $data, 0x80; push @b, 0 until (8*@b-448) %% 512; my $len = 8 * $data.elems; - push @b, gather for ^8 { take $len % 256; $len div= 256 } + push @b, | gather for ^8 { take $len % 256; $len div= 256 } my @word = gather for @b -> $a, $b, $c, $d { take reduce * *256 + *, $d, $c, $b, $a; @@ -62,17 +62,15 @@ multi rmd160(Blob $data) { my @X = my @Y = @h; for ^80 -> $j { my $T = rotl( - @X[0] m+ F[$j div 16](|@X[1..3]) m+ (@word[$i+r1[$j]] // 0) m+ K1[$j], - s1[$j] + @X[0] m+ F[$j div 16](|@X[1..3]) m+ (@word[$i+r1[$j]] // 0) m+ K1[$j], s1[$j] ) m+ @X[4]; @X = @X[4], $T, @X[1], rotl(@X[2], 10) % 2**32, @X[3]; $T = rotl( - @Y[0] m+ F[(79-$j) div 16](|@Y[1..3]) m+ (@word[$i+r2[$j]] // 0) m+ K2[$j], - s2[$j] + @Y[0] m+ F[(79-$j) div 16](|@Y[1..3]) m+ (@word[$i+r2[$j]] // 0) m+ K2[$j], s2[$j] ) m+ @Y[4]; @Y = @Y[4], $T, @Y[1], rotl(@Y[2], 10) % 2**32, @Y[3]; } - @h = @h[1..4,^1] Z[m+] @X[2..4,^2] Z[m+] @Y[3..4,^3]; + @h = (flat @h[1..4,^1]) Z[m+] (flat @X[2..4,^2]) Z[m+] flat @Y[3..4,^3]; } return Blob.new: gather for @h -> $word is rw { for ^4 { take $word % 256; $word div= 256 } diff --git a/Task/RIPEMD-160/PowerShell/ripemd-160-1.psh b/Task/RIPEMD-160/PowerShell/ripemd-160-1.psh new file mode 100644 index 0000000000..6445975e62 --- /dev/null +++ b/Task/RIPEMD-160/PowerShell/ripemd-160-1.psh @@ -0,0 +1,51 @@ +function Get-Hash +{ + [CmdletBinding(DefaultParameterSetName="String")] + [OutputType([string])] + Param + ( + [Parameter(Mandatory=$true, + ParameterSetName="String", + Position=0)] + [string] + $String, + + [Parameter(Mandatory=$true, + ParameterSetName="FileName", + Position=0)] + [string] + $FileName, + + [Parameter(Mandatory=$false, + Position=1)] + [ValidateSet("MD5", "RIPEMD160", "SHA1", "SHA256", "SHA384", "SHA512")] + [string] + $HashType = "MD5" + ) + + $hashAlgorithm = [System.Security.Cryptography.HashAlgorithm] + $stringBuilder = New-Object -TypeName System.Text.StringBuilder + + switch ($PSCmdlet.ParameterSetName) + { + "String" + { + $hashAlgorithm::Create($HashType).ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String)) | ForEach-Object { + $stringBuilder.Append($_.ToString("x2")) | Out-Null + } + } + "FileName" + { + $fileStream = New-Object -TypeName System.IO.FileStream -ArgumentList $FileName, ([System.IO.FileMode]::Open) + + $hashAlgorithm::Create($HashType).ComputeHash($fileStream) | ForEach-Object { + $stringBuilder.Append($_.ToString("x2")) | Out-Null + } + + $fileStream.Close() + $fileStream.Dispose() + } + } + + $stringBuilder.ToString() +} diff --git a/Task/RIPEMD-160/PowerShell/ripemd-160-2.psh b/Task/RIPEMD-160/PowerShell/ripemd-160-2.psh new file mode 100644 index 0000000000..16e552f941 --- /dev/null +++ b/Task/RIPEMD-160/PowerShell/ripemd-160-2.psh @@ -0,0 +1 @@ +Get-Hash "Rosetta Code" -HashType RIPEMD160 diff --git a/Task/RIPEMD-160/Zkl/ripemd-160.zkl b/Task/RIPEMD-160/Zkl/ripemd-160.zkl new file mode 100644 index 0000000000..db60034163 --- /dev/null +++ b/Task/RIPEMD-160/Zkl/ripemd-160.zkl @@ -0,0 +1,2 @@ +var MsgHash=Import("zklMsgHash"); +MsgHash.RIPEMD160("Rosetta Code") diff --git a/Task/RSA-code/FreeBASIC/rsa-code.freebasic b/Task/RSA-code/FreeBASIC/rsa-code.freebasic new file mode 100644 index 0000000000..6f50998009 --- /dev/null +++ b/Task/RSA-code/FreeBASIC/rsa-code.freebasic @@ -0,0 +1,44 @@ +' version 17-01-2017 +' compile with: fbc -s console + +#Include Once "gmp.bi" + +Dim As Mpz_ptr e, d, n, pt, ct + +e = Allocate(Len(__mpz_struct)) +d = Allocate(Len(__mpz_struct)) +n = Allocate(Len(__mpz_struct)) +pt = Allocate(Len(__mpz_struct)) : mpz_init(pt) +ct = Allocate(Len(__mpz_struct)) : mpz_init(ct) + +mpz_init_set_str(e, "65537", 10) +mpz_init_set_str(d, "5617843187844953170308463622230283376298685", 10) +mpz_init_set_str(n, "9516311845790656153499716760847001433441357", 10) + +Dim As ZString Ptr plaintext : plaintext = Allocate(1000) +Dim As ZString Ptr text : text = Allocate(1000) +*plaintext = "Rosetta Code" + +mpz_import(pt, Len(*plaintext), 1, 1, 0, 0, plaintext) + +If mpz_cmp(pt, n) > 0 Then GoTo clean_up + +mpz_powm(ct, pt, e, n) +gmp_printf(!" Encoded: %Zd\n", ct) + +mpz_powm(pt, ct, d, n) +gmp_printf(!" Decoded: %Zd\n", pt) + +mpz_export(text, NULL, 1, 1, 0, 0, pt) +Print "As string: "; *text + +clean_up: +DeAllocate(plaintext) : DeAllocate(text) +mpz_clear(e) : mpz_clear(d) : mpz_clear(n) +mpz_clear(pt) : mpz_clear(ct) + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/RSA-code/Kotlin/rsa-code.kotlin b/Task/RSA-code/Kotlin/rsa-code.kotlin new file mode 100644 index 0000000000..2c66230de8 --- /dev/null +++ b/Task/RSA-code/Kotlin/rsa-code.kotlin @@ -0,0 +1,28 @@ +// version 1.1.4-3 + +import java.math.BigInteger + +fun main(args: Array) { + val n = BigInteger("9516311845790656153499716760847001433441357") + val e = BigInteger("65537") + val d = BigInteger("5617843187844953170308463622230283376298685") + val c = Charsets.UTF_8 + val plainText = "Rosetta Code" + println("PlainText : $plainText") + val bytes = plainText.toByteArray(c) + val plainNum = BigInteger(bytes) + println("As number : $plainNum") + if (plainNum > n) { + println("Plaintext is too long") + return + } + + val enc = plainNum.modPow(e, n) + println("Encoded : $enc") + + val dec = enc.modPow(d, n) + println("Decoded : $dec") + + val decText = dec.toByteArray().toString(c) + println("As text : $decText") +} diff --git a/Task/RSA-code/Scala/rsa-code.scala b/Task/RSA-code/Scala/rsa-code.scala new file mode 100644 index 0000000000..3a7e2851aa --- /dev/null +++ b/Task/RSA-code/Scala/rsa-code.scala @@ -0,0 +1,32 @@ +object RSA_saket{ + val d = BigInt("5617843187844953170308463622230283376298685") + val n = BigInt("9516311845790656153499716760847001433441357") + val e = 65537 + val text = "Rosetta Code" + val encode = (msg:BigInt) => pow_mod(msg,e,n) + val decode = (msg:BigInt) => pow_mod(msg,d,n) + val getmsg = (txt:String) => BigInt(txt.map(x => "%03d".format(x.toInt)).reduceLeft(_+_)) + def pow_mod(p:BigInt, q:BigInt, n:BigInt):BigInt = { + if(q==0) BigInt(1) + else if(q==1) p + else if(q%2 == 1) pow_mod(p,q-1,n)*p % n + else pow_mod(p*p % n,q/2,n) + } + def gettxt(num:String) = { + if(num.size%3==2) + ("0" + num).grouped(3).toList.foldLeft("")(_ + _.toInt.toChar) + else + num.grouped(3).toList.foldLeft("")(_ + _.toInt.toChar) + } + def main(args: Array[String]): Unit = { + println(f"Original String \t: "+text) + val msg = getmsg(text) + println(f"Converted Signal \t: "+msg) + val enc_sig = encode(msg) + println("Encoded Signal \t\t: "+ enc_sig) + val dec_sig = decode(enc_sig) + println("Decoded String \t\t: "+ dec_sig) + val rec_msg = gettxt(dec_sig.toString) + println("Retrieved Signal \t: "+rec_msg) + } +} diff --git a/Task/RSA-code/Zkl/rsa-code.zkl b/Task/RSA-code/Zkl/rsa-code.zkl new file mode 100644 index 0000000000..1f7c8c89b0 --- /dev/null +++ b/Task/RSA-code/Zkl/rsa-code.zkl @@ -0,0 +1,16 @@ +var BN=Import("zklBigNum"); + +n:=BN("9516311845790656153499716760847001433441357"); +e:=BN("65537"); +d:=BN("5617843187844953170308463622230283376298685"); + +const plaintext="Rossetta Code"; +pt:=BN(Data(Int,0,plaintext)); // convert string (as stream of bytes) to big int +if(pt>n) throw(Exception.ValueError("Message is too large")); + +println("Plain text: ",plaintext); +println("As Int: ",pt); +ct:=pt.powm(e,n); println("Encoded: ",ct); +pt =ct.powm(d,n); println("Decoded: ",pt); +txt:=pt.toData().text; // convert big int to bytes, treat as string +println("As String: ",txt); diff --git a/Task/Random-number-generator--device-/Batch-File/random-number-generator--device-.bat b/Task/Random-number-generator--device-/Batch-File/random-number-generator--device-.bat new file mode 100644 index 0000000000..83661c9a3a --- /dev/null +++ b/Task/Random-number-generator--device-/Batch-File/random-number-generator--device-.bat @@ -0,0 +1 @@ +@echo %random% diff --git a/Task/Random-number-generator--device-/C/random-number-generator--device--6.c b/Task/Random-number-generator--device-/C/random-number-generator--device--6.c deleted file mode 100644 index 80c3924f4f..0000000000 --- a/Task/Random-number-generator--device-/C/random-number-generator--device--6.c +++ /dev/null @@ -1,10 +0,0 @@ -#include -#include - -int main() -{ - std::random_device rd; - std::uniform_int_distribution dist; // long is guaranteed to be 32 bits - - std::cout << "Random Number: " << dist(rd) << std::endl; -} diff --git a/Task/Random-number-generator--device-/Common-Lisp/random-number-generator--device-.lisp b/Task/Random-number-generator--device-/Common-Lisp/random-number-generator--device-.lisp new file mode 100644 index 0000000000..3d8be6797b --- /dev/null +++ b/Task/Random-number-generator--device-/Common-Lisp/random-number-generator--device-.lisp @@ -0,0 +1,3 @@ +(defun random-int32 () + (with-open-file (s "/dev/random" :element-type '(unsigned-byte 32)) + (read-byte s))) diff --git a/Task/Random-number-generator--device-/Jq/random-number-generator--device-.jq b/Task/Random-number-generator--device-/Jq/random-number-generator--device-.jq new file mode 100644 index 0000000000..03bfb42c76 --- /dev/null +++ b/Task/Random-number-generator--device-/Jq/random-number-generator--device-.jq @@ -0,0 +1,11 @@ +# allow both upper and lower-case characters +def hex2integer: + explode + | reverse + | map(if . > 96 then . - 87 elif . > 64 then . - 55 else . - 48 end) + | reduce .[] as $c + # state: [power, ans] + ([1,0]; (.[0] * 16) as $b | [$b, .[1] + (.[0] * $c)]) + | .[1]; + +select(length>0) | hex2integer / pow(16;length) diff --git a/Task/Random-number-generator--device-/Kotlin/random-number-generator--device-.kotlin b/Task/Random-number-generator--device-/Kotlin/random-number-generator--device-.kotlin new file mode 100644 index 0000000000..210721be82 --- /dev/null +++ b/Task/Random-number-generator--device-/Kotlin/random-number-generator--device-.kotlin @@ -0,0 +1,12 @@ +// version 1.1.2 + +import java.security.SecureRandom + +fun main(args: Array) { + val rng = SecureRandom() + val rn1 = rng.nextInt() + val rn2 = rng.nextInt() + val newSeed = rn1.toLong() * rn2 + rng.setSeed(newSeed) // reseed using the previous 2 random numbers + println(rng.nextInt()) // get random 32-bit number and print it +} diff --git a/Task/Random-number-generator--device-/PowerShell/random-number-generator--device--1.psh b/Task/Random-number-generator--device-/PowerShell/random-number-generator--device--1.psh new file mode 100644 index 0000000000..221d02e99b --- /dev/null +++ b/Task/Random-number-generator--device-/PowerShell/random-number-generator--device--1.psh @@ -0,0 +1,31 @@ +function Get-RandomInteger +{ + Param + ( + [Parameter(Mandatory=$false, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true, + Position=0)] + [ValidateScript({$_ -ge 4})] + [int[]] + $InputObject = 64 + ) + + Begin + { + $rng = New-Object -TypeName System.Security.Cryptography.RNGCryptoServiceProvider + } + Process + { + foreach($count in $InputObject) + { + $bytes = New-Object -TypeName Byte[] -Argument $count + $rng.GetBytes($bytes) + [System.BitConverter]::ToInt32($bytes,0) + } + } + End + { + Remove-Variable -Name rng -Scope Local + } +} diff --git a/Task/Random-number-generator--device-/PowerShell/random-number-generator--device--2.psh b/Task/Random-number-generator--device-/PowerShell/random-number-generator--device--2.psh new file mode 100644 index 0000000000..d9a84cc001 --- /dev/null +++ b/Task/Random-number-generator--device-/PowerShell/random-number-generator--device--2.psh @@ -0,0 +1 @@ +4,8,16,32,64,128 | Get-RandomInteger | Format-Wide {$_} -Column 6 -Force diff --git a/Task/Random-number-generator--device-/PowerShell/random-number-generator--device--3.psh b/Task/Random-number-generator--device-/PowerShell/random-number-generator--device--3.psh new file mode 100644 index 0000000000..0526c7cf23 --- /dev/null +++ b/Task/Random-number-generator--device-/PowerShell/random-number-generator--device--3.psh @@ -0,0 +1 @@ +4,8,16,32,64,128 | Get-RandomInteger | Format-Wide {"0x{0:X}" -f $_} -Column 6 -Force diff --git a/Task/Random-number-generator--device-/REXX/random-number-generator--device--1.rexx b/Task/Random-number-generator--device-/REXX/random-number-generator--device--1.rexx index 78a1f6cf90..e21429f519 100644 --- a/Task/Random-number-generator--device-/REXX/random-number-generator--device--1.rexx +++ b/Task/Random-number-generator--device-/REXX/random-number-generator--device--1.rexx @@ -1,9 +1,5 @@ -/*REXX program generates a random 32-bit number using the RANDOM bif.*/ -/*───────── The 32-bit random number is unsigned and constructed from */ -/*───────── two smaller 16-bit numbers, and it's expressed in decimal.*/ -/*───────── Note: the REXX random bif has a maximum range of 100,000.*/ - -numeric digits 10 /*ensure REXX has enough room. */ -_=2**16 /*a handy-dandy constant to have.*/ - -say random(0,_-1)*_+random(0,_-1) /*gen an unsigned 32-bit random #*/ +/*REXX program generates and displays a random 32-bit number using the RANDOM BIF.*/ +numeric digits 10 /*ensure REXX has enough decimal digits*/ +_=2**16 /*a handy─dandy constant to have around*/ +r#= random(0, _-1) * _ + random(0, _-1) /*generate an unsigned 32-bit random #.*/ +say r# /*stick a fork in it, we're all done. */ diff --git a/Task/Random-number-generator--device-/X86-Assembly/random-number-generator--device-.x86 b/Task/Random-number-generator--device-/X86-Assembly/random-number-generator--device-.x86 new file mode 100644 index 0000000000..8400647b60 --- /dev/null +++ b/Task/Random-number-generator--device-/X86-Assembly/random-number-generator--device-.x86 @@ -0,0 +1,2 @@ +L: rdrand eax +jnc L diff --git a/Task/Random-number-generator--device-/Zkl/random-number-generator--device-.zkl b/Task/Random-number-generator--device-/Zkl/random-number-generator--device-.zkl new file mode 100644 index 0000000000..b8f3296381 --- /dev/null +++ b/Task/Random-number-generator--device-/Zkl/random-number-generator--device-.zkl @@ -0,0 +1,5 @@ +const RANDOM_PATH="/dev/urandom"; + +fin,buf:=File(RANDOM_PATH,"r"), fin.read(4); +fin.close(); // GC would also close the file +println(buf.toBigEndian(0,4)); // 4 bytes @ offset 0 diff --git a/Task/Random-number-generator--included-/Common-Lisp/random-number-generator--included-.lisp b/Task/Random-number-generator--included-/Common-Lisp/random-number-generator--included-.lisp new file mode 100644 index 0000000000..01bf69282c --- /dev/null +++ b/Task/Random-number-generator--included-/Common-Lisp/random-number-generator--included-.lisp @@ -0,0 +1,2 @@ +(setf *random-state* (make-random-state t)) +(rand 10) diff --git a/Task/Random-numbers/jq/random-numbers-1.jq b/Task/Random-numbers/Jq/random-numbers-1.jq similarity index 100% rename from Task/Random-numbers/jq/random-numbers-1.jq rename to Task/Random-numbers/Jq/random-numbers-1.jq diff --git a/Task/Random-numbers/jq/random-numbers-2.jq b/Task/Random-numbers/Jq/random-numbers-2.jq similarity index 100% rename from Task/Random-numbers/jq/random-numbers-2.jq rename to Task/Random-numbers/Jq/random-numbers-2.jq diff --git a/Task/Random-numbers/jq/random-numbers-3.jq b/Task/Random-numbers/Jq/random-numbers-3.jq similarity index 100% rename from Task/Random-numbers/jq/random-numbers-3.jq rename to Task/Random-numbers/Jq/random-numbers-3.jq diff --git a/Task/Random-numbers/Kotlin/random-numbers.kotlin b/Task/Random-numbers/Kotlin/random-numbers.kotlin new file mode 100644 index 0000000000..83bb8205bd --- /dev/null +++ b/Task/Random-numbers/Kotlin/random-numbers.kotlin @@ -0,0 +1,14 @@ +// version 1.0.6 + +import java.util.Random + +fun main(args: Array) { + val r = Random() + val da = DoubleArray(1000) + for (i in 0 until 1000) da[i] = 1.0 + 0.5 * r.nextGaussian() + // now check actual mean and SD + val mean = da.average() + val sd = Math.sqrt(da.map { (it - mean) * (it - mean) }.average()) + println("Mean is $mean") + println("S.D. is $sd") +} diff --git a/Task/Random-numbers/Lua/random-numbers.lua b/Task/Random-numbers/Lua/random-numbers.lua new file mode 100644 index 0000000000..5313f3196c --- /dev/null +++ b/Task/Random-numbers/Lua/random-numbers.lua @@ -0,0 +1,4 @@ +local list = {} +for i = 1, 1000 do + list[i] = 1 + math.sqrt(-2 * math.log(math.random())) * math.cos(2 * math.pi * math.random()) / 2 +end diff --git a/Task/Random-numbers/Nimrod/random-numbers.nimrod b/Task/Random-numbers/Nimrod/random-numbers.nimrod deleted file mode 100644 index 31ab2134f7..0000000000 --- a/Task/Random-numbers/Nimrod/random-numbers.nimrod +++ /dev/null @@ -1,14 +0,0 @@ -import math, strutils - -const precisn = 5 -var rs: TRunningStat - -proc normGauss: float {.inline.} = 1 + 0.76 * cos(2*PI*random(1.0)) * sqrt(-2*log10(random(1.0))) - -randomize() - -for j in 0..5: - for i in 0..1000: - rs.push(normGauss()) - echo("mean: ", $formatFloat(rs.mean,ffDecimal,precisn), - " stdDev: ", $formatFloat(rs.standardDeviation(),ffDecimal,precisn)) diff --git a/Task/Random-numbers/OoRexx/random-numbers-1.rexx b/Task/Random-numbers/OoRexx/random-numbers-1.rexx new file mode 100644 index 0000000000..ed68b63275 --- /dev/null +++ b/Task/Random-numbers/OoRexx/random-numbers-1.rexx @@ -0,0 +1,42 @@ +/*REXX pgm gens 1,000 normally distributed #s: mean=1, standard dev.=0.5*/ + pi=RxCalcPi() /* get value of pi */ + Parse Arg n seed . /* allow specification of N & seed*/ + If n==''|n==',' Then + n=1000 /* N is the size of the array. */ + If seed\=='' Then + Call random,,seed /* use seed for repeatable RANDOM#*/ + mean=1 /* desired new mean (arith. avg.) */ + sd=1/2 /* desired new standard deviation.*/ + Do g=1 For n /* generate N uniform random nums.*/ + n.g=random(0,1e5)/1e5 /* REXX gens uniform rand integers*/ + End + + Say ' old mean=' mean() + Say 'old standard deviation=' stddev() + Say + Do j=1 To n-1 By 2 + m=j+1 + /*use Box-Muller method */ + _=sd*RxCalcPower(-2*RxCalcLog(n.j),.5)*RxCalcCos(2*pi*n.m,,'R')+mean + n.m=sd*RxCalcpower(-2*RxCalcLog(n.j),.5)*RxCalcSin(2*pi*n.m,,'R')+, + mean /* rand # must be 0???1. */ + n.j=_ + End /* j */ + Say ' new mean=' mean() + Say 'new standard deviation=' stddev() + Exit +mean: + _=0 + Do k=1 For n + _=_+n.k + End + Return _/n +stddev: + _avg=mean() + _=0 + Do k=1 For n + _=_+(n.k-_avg)**2 + End + Return RxCalcPower(_/n,.5) + +:: requires rxmath library diff --git a/Task/Random-numbers/OoRexx/random-numbers-2.rexx b/Task/Random-numbers/OoRexx/random-numbers-2.rexx new file mode 100644 index 0000000000..ffbcb4c74d --- /dev/null +++ b/Task/Random-numbers/OoRexx/random-numbers-2.rexx @@ -0,0 +1,46 @@ +/*REXX pgm gens 1,000 normally distributed #s: mean=1, standard dev.=0.5*/ + pi=RxCalcPi() /* get value of pi */ + Parse Arg n seed . /* allow specification of N & seed*/ + If n==''|n==',' Then + n=1000 /* N is the size of the array. */ + If seed\=='' Then + Call random,,seed /* use seed for repeatable RANDOM#*/ + mean=1 /* desired new mean (arith. avg.) */ + sd=1/2 /* desired new standard deviation.*/ + Do g=1 For n /* generate N uniform random nums.*/ + n.g=random(0,1e5)/1e5 /* REXX gens uniform rand integers*/ + End + + Say ' old mean=' mean() + Say 'old standard deviation=' stddev() + Say + Do j=1 To n-1 By 2 + m=j+1 + /*use Box-Muller method */ + _=sd*sqrt(-2*ln(n.j))*cos(2*pi*n.m)+mean + n.m=sd*sqrt(-2*ln(n.j))*sin(2*pi*n.m)+mean + n.j=_ + End + Say ' new mean=' mean() + Say 'new standard deviation=' stddev() + Exit +mean: + _=0 + Do k=1 For n + _=_+n.k + End + Return _/n +stddev: + _avg=mean() + _=0 + Do k=1 For n + _=_+(n.k-_avg)**2 + End + Return sqrt(_/n) + +sqrt: Return RxCalcSqrt(arg(1)) +ln: Return RxCalcLog(arg(1)) +cos: Return RxCalcCos(arg(1),,'R') +sin: Return RxCalcSin(arg(1),,'R') + +:: requires rxmath library diff --git a/Task/Random-numbers/Sidef/random-numbers.sidef b/Task/Random-numbers/Sidef/random-numbers.sidef index cef25f9621..bd200713b6 100644 --- a/Task/Random-numbers/Sidef/random-numbers.sidef +++ b/Task/Random-numbers/Sidef/random-numbers.sidef @@ -1,2 +1,2 @@ -var arr = 1000.of { 1 + (0.5 * (-2 * 1.rand.log -> sqrt) * (Number.tau * 1.rand -> cos)) } +var arr = 1000.of { 1 + (0.5 * sqrt(-2 * 1.rand.log) * cos(Num.tau * 1.rand)) } arr.each { .say } diff --git a/Task/Random-numbers/Stata/random-numbers.stata b/Task/Random-numbers/Stata/random-numbers.stata new file mode 100644 index 0000000000..6adc4445bc --- /dev/null +++ b/Task/Random-numbers/Stata/random-numbers.stata @@ -0,0 +1,3 @@ +clear all +set obs 1000 +gen x=rnormal(1,0.5) diff --git a/Task/Random-numbers/Zkl/random-numbers-1.zkl b/Task/Random-numbers/Zkl/random-numbers-1.zkl new file mode 100644 index 0000000000..9379565d03 --- /dev/null +++ b/Task/Random-numbers/Zkl/random-numbers-1.zkl @@ -0,0 +1,5 @@ +fcn mkRand(mean,sd){ //normally distributed random w/mean & standard deviation + pi:=(0.0).pi; // using the Box–Muller transform + rz1:=fcn{1.0-(0.0).random(1)} // from [0,1) to (0,1] + return('wrap(){((-2.0*rz1().log()).sqrt() * (2.0*pi*rz1()).cos())*sd + mean }) +} diff --git a/Task/Random-numbers/Zkl/random-numbers-2.zkl b/Task/Random-numbers/Zkl/random-numbers-2.zkl new file mode 100644 index 0000000000..036e7f1e52 --- /dev/null +++ b/Task/Random-numbers/Zkl/random-numbers-2.zkl @@ -0,0 +1,5 @@ +var g=mkRand(1,0.5); +ns:=(0).pump(1000,List,g); // 1000 rands with mean==1 & sd==1/2 +mean:=(ns.sum(0.0)/1000); //-->1.00379 + // calc sd of list of numbers: +(ns.reduce('wrap(p,n){p+(n-mean).pow(2)},0.0)/1000).sqrt() //-->0.494844 diff --git a/Task/Range-expansion/AppleScript/range-expansion-1.applescript b/Task/Range-expansion/AppleScript/range-expansion-1.applescript index 6917602dac..f39b93ebda 100644 --- a/Task/Range-expansion/AppleScript/range-expansion-1.applescript +++ b/Task/Range-expansion/AppleScript/range-expansion-1.applescript @@ -31,17 +31,17 @@ on expansion(strExpr) end if end signedIntegerAppended - on lambda(strHyphenated) + on |λ|(strHyphenated) tupleRange(foldl(signedIntegerAppended, {}, ¬ splitOn("-", strHyphenated))) - end lambda + end |λ| end script concatMap(signedRange, splitOn(",", strExpr)) end expansion --- TEST +-- TEST ----------------------------------------------------------------------- on run expansion("-6,-3--1,3-5,7-11,14,15,17-20") @@ -50,27 +50,40 @@ on run end run - --- GENERIC LIBRARY FUNCTIONS +-- GENERIC FUNCTIONS ---------------------------------------------------------- -- concatMap :: (a -> [b]) -> [a] -> [b] on concatMap(f, xs) script append - on lambda(a, b) + on |λ|(a, b) a & b - end lambda + end |λ| end script foldl(append, {}, map(f, xs)) end concatMap +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if n < m then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo + -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -82,7 +95,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -95,41 +108,11 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn --- range :: (Int, Int) -> [Int] -on tupleRange(tuple) - if tuple = {} then - {} - else if length of tuple > 1 then - range(item 1 of tuple, item 2 of tuple) - else - item 1 of tuple - end if -end tupleRange - --- range :: Int -> Int -> [Int] -on range(m, n) - set d to cond(n < m, -1, 1) - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range - --- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b) -on cond(bool, f, g) - if bool then - f - else - g - end if -end cond - -- splitOn :: Text -> Text -> [Text] on splitOn(strDelim, strMain) set {dlm, my text item delimiters} to {my text item delimiters, strDelim} @@ -137,3 +120,14 @@ on splitOn(strDelim, strMain) set my text item delimiters to dlm return xs end splitOn + +-- range :: (Int, Int) -> [Int] +on tupleRange(tuple) + if tuple = {} then + {} + else if length of tuple > 1 then + enumFromTo(item 1 of tuple, item 2 of tuple) + else + item 1 of tuple + end if +end tupleRange diff --git a/Task/Range-expansion/jq/range-expansion-1.jq b/Task/Range-expansion/Jq/range-expansion-1.jq similarity index 100% rename from Task/Range-expansion/jq/range-expansion-1.jq rename to Task/Range-expansion/Jq/range-expansion-1.jq diff --git a/Task/Range-expansion/jq/range-expansion-2.jq b/Task/Range-expansion/Jq/range-expansion-2.jq similarity index 100% rename from Task/Range-expansion/jq/range-expansion-2.jq rename to Task/Range-expansion/Jq/range-expansion-2.jq diff --git a/Task/Range-expansion/Kotlin/range-expansion.kotlin b/Task/Range-expansion/Kotlin/range-expansion.kotlin new file mode 100644 index 0000000000..7551fc5ad2 --- /dev/null +++ b/Task/Range-expansion/Kotlin/range-expansion.kotlin @@ -0,0 +1,35 @@ +// version 1.0.6 + +fun expandRange(s: String): MutableList { + val list = mutableListOf() + val items = s.split(',') + var first: Int + var last: Int + for (item in items) { + val count = item.count { it == '-' } + if (count == 0 || (count == 1 && item[0] == '-')) + list.add(item.toInt()) + else { + val items2 = item.split('-') + if (count == 1) { + first = items2[0].toInt() + last = items2[1].toInt() + } + else if (count == 2) { + first = items2[1].toInt() * -1 + last = items2[2].toInt() + } + else { + first = items2[1].toInt() * -1 + last = items2[3].toInt() * -1 + } + for (i in first..last) list.add(i) + } + } + return list +} + +fun main(args: Array) { + val s = "-6,-3--1,3-5,7-11,14,15,17-20" + println(expandRange(s)) +} diff --git a/Task/Range-expansion/Nimrod/range-expansion.nimrod b/Task/Range-expansion/Nimrod/range-expansion.nimrod deleted file mode 100644 index 848195129c..0000000000 --- a/Task/Range-expansion/Nimrod/range-expansion.nimrod +++ /dev/null @@ -1,24 +0,0 @@ -import parseutils, re, strutils - -proc expandRange(input: string): string = - var output: seq[string] = @[] - for range in input.split(','): - var sep = range.find('-', 1) - if sep > 0: # parse range - var first = -1 - if range.substr(0, sep-1).parseInt(first) == 0: - break - var last = -1 - if range.substr(sep+1).parseInt(last) == 0: - break - for i in first..last: - output.add($i) - else: # parse single number - var n = -1 - if range.parseInt(n) > 0: - output.add($n) - else: - break - return output.join(",") - -echo("-6,-3--1,3-5,7-11,14,15,17-20".expandRange) diff --git a/Task/Range-expansion/OoRexx/range-expansion.rexx b/Task/Range-expansion/OoRexx/range-expansion.rexx new file mode 100644 index 0000000000..baf41c5634 --- /dev/null +++ b/Task/Range-expansion/OoRexx/range-expansion.rexx @@ -0,0 +1,30 @@ +list = '-6,-3--1,3-5,7-11,14,15,17-20' +expanded = expandRanges(list) + +say "Original list: ["list"]" +say "Expanded list: ["expanded~tostring("l", ",")"]" + +-- expand a string expression a range of numbers into a list +-- of values for the range. This returns an array +::routine expandRanges + use strict arg list + values = list~makearray(',') + -- build this up using an array first. Make this at least the + -- size of the original value set. + expanded = .array~new(values~items) + + -- now process each element in the range + loop element over values + -- if this is a valid number, it's not a range, so add it directly + if element~datatype('whole') then expanded~append(element) + else do + -- search for the divider, starting from the second position + -- to allow for the starting value to be a minus sign. + split = element~pos('-', 2) + parse var element start =(split) +1 finish + loop i = start to finish + expanded~append(i) + end + end + end + return expanded diff --git a/Task/Range-expansion/Phix/range-expansion.phix b/Task/Range-expansion/Phix/range-expansion.phix new file mode 100644 index 0000000000..5daa5ed261 --- /dev/null +++ b/Task/Range-expansion/Phix/range-expansion.phix @@ -0,0 +1,21 @@ +function range_expansion(string range) +sequence s = split(range,','), + res = {} + for i=1 to length(s) do + string si = s[i] + integer k = find('-',si,2) + if k=0 then + res = append(res,to_number(si)) + else + integer startrange = to_number(si[1..k-1]) + integer endofrange = to_number(si[k+1..$]) + for l=startrange to endofrange do + res = append(res,l) + end for + end if + end for + return res +end function + +?range_expansion("-6,-3-1,3-5,7-11,14,15,17-20") +?range_expansion("-6,-3--1,3-5,7-11,14,15,17-20") diff --git a/Task/Range-expansion/PowerShell/range-expansion.psh b/Task/Range-expansion/PowerShell/range-expansion-1.psh similarity index 100% rename from Task/Range-expansion/PowerShell/range-expansion.psh rename to Task/Range-expansion/PowerShell/range-expansion-1.psh diff --git a/Task/Range-expansion/PowerShell/range-expansion-2.psh b/Task/Range-expansion/PowerShell/range-expansion-2.psh new file mode 100644 index 0000000000..414d2d096a --- /dev/null +++ b/Task/Range-expansion/PowerShell/range-expansion-2.psh @@ -0,0 +1,42 @@ +function Expand-Range +{ + [CmdletBinding()] + [OutputType([int])] + Param + ( + [Parameter(Mandatory=$true, + Position=0)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[0-9,-]*$')] + [string] + $Range + ) + + try + { + if ($Range -match '-,') # I'm not good enough to weed this case out with Regex + { + throw "Input string was not in a correct format." + } + + [int[]]$output = $Range -split ',' | ForEach-Object { + + [int[]]$array = $_ -split '(?<=\d)-' + + if ($array.Count -gt 1) # $array contains one or two elements + { + $array[0]..$array[1] # two elements = start and end of range + } + else + { + $array # one element = an integer + } + } + } + catch + { + throw "Input string was not in a correct format." + } + + $output +} diff --git a/Task/Range-expansion/PowerShell/range-expansion-3.psh b/Task/Range-expansion/PowerShell/range-expansion-3.psh new file mode 100644 index 0000000000..1d7dd9ea5b --- /dev/null +++ b/Task/Range-expansion/PowerShell/range-expansion-3.psh @@ -0,0 +1 @@ +(Expand-Range "-6,-3--1,3-5,7-11,14,15,17-20") -join ", " diff --git a/Task/Range-expansion/Python/range-expansion-3.py b/Task/Range-expansion/Python/range-expansion-3.py deleted file mode 100644 index bfd76ed9cc..0000000000 --- a/Task/Range-expansion/Python/range-expansion-3.py +++ /dev/null @@ -1,6 +0,0 @@ -from functools import reduce -from operator import add - -def rangeexpand(s): - return reduce(add, - map(lambda x: list(range(*map(int, x.split('-')))) if '-' in x else [int(x)], s.split(','))) diff --git a/Task/Range-expansion/R/range-expansion-1.r b/Task/Range-expansion/R/range-expansion-1.r deleted file mode 100644 index 8e16856742..0000000000 --- a/Task/Range-expansion/R/range-expansion-1.r +++ /dev/null @@ -1,9 +0,0 @@ -rangeExpand <- function(text) { - x <- unlist(strsplit(text, ",")) # split the string on commas - x <- gsub("(\\d)-", "\\1:", x) # substitute dashes following a digit with a colon - lst <- list(mode = "list", length = length(x)) # an empty list to hold evaluated elements - for (i in 1:length(x)) { # evaluate each element and add to the list - lst[[i]] <- eval(parse(text = x[i])) - } - unlist(lst, use.names = FALSE) # return the expanded integers -} diff --git a/Task/Range-expansion/R/range-expansion-2.r b/Task/Range-expansion/R/range-expansion-2.r deleted file mode 100644 index 7b9aaf3f5b..0000000000 --- a/Task/Range-expansion/R/range-expansion-2.r +++ /dev/null @@ -1,2 +0,0 @@ -rangeExpand("-6,-3--1,3-5,7-11,14,15,17-20") - [1] -6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20 diff --git a/Task/Range-expansion/Zkl/range-expansion-1.zkl b/Task/Range-expansion/Zkl/range-expansion-1.zkl new file mode 100644 index 0000000000..0379f0df2b --- /dev/null +++ b/Task/Range-expansion/Zkl/range-expansion-1.zkl @@ -0,0 +1,11 @@ +fcn rangex(s){ + fcn(s,re){ + if (re.search(s)){ + a,b:=re.matched[1,*].apply("toInt"); + [a..b].walk(); + } + else s; + } : + s.split(",").pump(List, _.fp1(RegExp(0'|(.*\d+)-(.*\d+)|))) + .flatten().concat(","); +} diff --git a/Task/Range-expansion/Zkl/range-expansion-2.zkl b/Task/Range-expansion/Zkl/range-expansion-2.zkl new file mode 100644 index 0000000000..e7b70d09e1 --- /dev/null +++ b/Task/Range-expansion/Zkl/range-expansion-2.zkl @@ -0,0 +1,5 @@ +ns="-6,-3-1,3-5,7-11,14,15,17-20"; +rangex(ns).println(); + +ns="-6,-3--1,3-5,7-11,14,15,17-20"; +rangex(ns).println(); diff --git a/Task/Range-extraction/AppleScript/range-extraction.applescript b/Task/Range-extraction/AppleScript/range-extraction.applescript index f147431cff..d0d48d3abe 100644 --- a/Task/Range-extraction/AppleScript/range-extraction.applescript +++ b/Task/Range-extraction/AppleScript/range-extraction.applescript @@ -1,111 +1,94 @@ -on run - - rangeString([0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, ¬ - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, ¬ - 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]) - -end run - --- rangeString :: [Int] -> String -on rangeString(xs) - script addNumberOrRange - property iLast : length of xs - - -- [[Int]] -> Int -> Int -> [Int] -> [[Int]] - on lambda(lstAccumulator, x, iPosn, xs) - if iPosn < iLast then - if ((item (iPosn + 1) of xs) - x) > 1 then -- rightward gap > 1 - [[x]] & lstAccumulator --> start of new series - else - -- Prepended to current series - -- (if a series-breaker, or start list, is at left) - if ((iPosn = 1) or (x - (item (iPosn - 1) of xs)) > 1) then - [[x] & (item 1 of lstAccumulator)] & tail(lstAccumulator) - else - lstAccumulator -- Stet - series continues - end if - end if +-- rangeFormat :: [Int] -> String +on rangeFormat(xs) + script rangeString + on |λ|(xs) + if length of xs > 2 then + (item 1 of xs as string) & "-" & (item -1 of xs as string) else - [[x]] + intercalate(",", xs) end if - end lambda + end |λ| end script - interCalate(",", ¬ - map(my delimitedString, ¬ - foldr(addNumberOrRange, [], xs))) -end rangeString + script nonConsec + on |λ|(a, b) + b - a > 1 + end |λ| + end script + + intercalate(",", map(rangeString, splitBy(nonConsec, xs))) +end rangeFormat --- delimitedString :: [Int] -> String -on delimitedString(lstInt) - set intFirst to item 1 of lstInt +--TEST ------------------------------------------------------------------------ +on run + set xs to {0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, ¬ + 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, ¬ + 33, 35, 36, 37, 38, 39} - if length of lstInt > 1 then - set intSecond to item 2 of lstInt - set delta to intSecond - intFirst + rangeFormat(xs) + + --> "0-2,4,6-8,11,12,14-25,27-33,35-39" +end run + + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- splitBy :: (a -> a -> Bool) -> [a] -> [[a]] +on splitBy(f, xs) + set mf to mReturn(f) + + if length of xs < 2 then + {xs} else - set delta to 0 + script p + on |λ|(a, x) + set {acc, active, prev} to a + if mf's |λ|(prev, x) then + {acc & {active}, {x}, x} + else + {acc, active & x, x} + end if + end |λ| + end script + + set h to item 1 of xs + set lstParts to foldl(p, {{}, {h}, h}, items 2 thru -1 of xs) + item 1 of lstParts & {item 2 of lstParts} end if +end splitBy - if delta > 0 then - (intFirst as string) & cond(delta > 1, "-", ",") & intSecond as string - else - intFirst as string - end if -end delimitedString +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl - --- GENERIC LIBRARY FUNCTIONS +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map -- intercalate :: Text -> [Text] -> Text -on interCalate(strText, lstText) +on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined -end interCalate - --- foldr :: (a -> b -> a) -> a -> [b] -> a -on foldr(f, startValue, xs) - set mf to mReturn(f) - - set v to startValue - set lng to length of xs - repeat with i from lng to 1 by -1 - set v to mf's lambda(v, item i of xs, i, xs) - end repeat - return v -end foldr - --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - set mf to mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to mf's lambda(item i of xs, i, xs) - end repeat - return lst -end map - --- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b) -on cond(bool, f, g) - if bool then - f - else - g - end if -end cond - --- tail :: [a] -> [a] -on tail(xs) - if class of xs is list and length of xs > 1 then - items 2 thru -1 of xs - else - {} - end if -end tail +end intercalate -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -114,7 +97,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Range-extraction/C/range-extraction-1.c b/Task/Range-extraction/C/range-extraction-1.c deleted file mode 100644 index 4c0fd09e59..0000000000 --- a/Task/Range-extraction/C/range-extraction-1.c +++ /dev/null @@ -1,36 +0,0 @@ -#include -#include - -size_t rprint(char *s, int *x, int len) -{ -#define sep (a > s ? "," : "") /* use comma except before first output */ -#define ol (s ? 100 : 0) /* print only if not testing for length */ - int i, j; - char *a = s; - for (i = j = 0; i < len; i = ++j) { - for (; j < len - 1 && x[j + 1] == x[j] + 1; j++); - - if (i + 1 < j) - a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]); - else - while (i <= j) - a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]); - } - return a - s; -#undef sep -#undef ol -} - -int main() -{ - int x[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, - 37, 38, 39 }; - - char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1); - rprint(s, x, sizeof(x) / sizeof(int)); - printf("%s\n", s); - - return 0; -} diff --git a/Task/Range-extraction/C/range-extraction-2.c b/Task/Range-extraction/C/range-extraction-2.c deleted file mode 100644 index b8bbe64039..0000000000 --- a/Task/Range-extraction/C/range-extraction-2.c +++ /dev/null @@ -1 +0,0 @@ -0-2,4,6-8,11,12,14-25,27-33,35-39 diff --git a/Task/Range-extraction/Gambas/range-extraction.gambas b/Task/Range-extraction/Gambas/range-extraction.gambas new file mode 100644 index 0000000000..6af2b0574a --- /dev/null +++ b/Task/Range-extraction/Gambas/range-extraction.gambas @@ -0,0 +1,51 @@ +siInput As New Short[] +siInput1 As Short[] = [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39] +siInput2 As Short[] = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20] +sOutput As New String[] +siCount As Short +siNum As Short +'__________________ +Public Sub Main() +Dim siLoop As Short + +For siLoop = 0 To 1 + If siLoop = 0 Then siInput = siInput1.Copy() Else siInput = siInput2.Copy() + siCount = 0 + siNum = 0 + Repeat + If siInput[siCount + 1] = siInput[siCount] + 1 Then + Inc siCount + Else + GetOutput + Endif + Until siCount = siInput.Max + + GetOutput + Print sOutput.join(", ") + sOutput.clear +Next + +End +'__________________ +Public Sub GetOutput() + +If siNum = siCount Then + sOutput.add(siInput[siNum]) + Inc siCount + siNum = siCount +End If + +If siNum <> siCount Then + If siNum = siCount - 1 Then + sOutput.add(siInput[siNum]) + sOutput.add(siInput[siNum + 1]) + siCount += 2 + siNum += 2 + Return + End If + sOutput.Add(siInput[siNum] & "-" & siInput[siCount]) + Inc siCount + siNum = siCount +End If + +End diff --git a/Task/Range-extraction/Haskell/range-extraction-3.hs b/Task/Range-extraction/Haskell/range-extraction-3.hs new file mode 100644 index 0000000000..eceecbbc35 --- /dev/null +++ b/Task/Range-extraction/Haskell/range-extraction-3.hs @@ -0,0 +1,55 @@ +import Data.List (intercalate) +import Data.Function (on) + +-- RANGE FORMAT -------------------------------------------------------------- + +rangeFormat :: [Int] -> String +rangeFormat = intercalate "," . (rangeString <$>) . splitBy ((/=) . succ) + where + rangeString xs + | length xs > 2 = x ++ '-' : last t + | otherwise = intercalate "," ps + where + ps@(x:t) = show <$> xs + + +-- GENERIC FUNCTION ---------------------------------------------------------- + +-- Split wherever a supplied predicate matches the relationship +-- between two consecutive items. + +-- E.G. at boundaries between vowels and consonants: +-- splitBy (on (/=) (flip elem "aeiouAEIOU")) "Constantinople" +-- -> ["C","o","nst","a","nt","i","n","o","pl","e"] + +-- At boundaries between non-successive integers: +-- splitBy ((/=) . succ) [0, 1, 2, 4, 6, 7, 8, 11, 12, 14] +-- -> [[0,1,2],[4],[6,7,8],[11,12],[14]] + +splitBy :: (a -> a -> Bool) -> [a] -> [[a]] +splitBy _ [] = [] +splitBy _ [x] = [[x]] +splitBy f xs@(_:t) = active : acc + where + (active, acc) = + foldr + (\(x, prev) (active, acc) -> + let current = + if null active + then [prev] + else active + in if f x prev + then ([x], current : acc) + else (x : current, acc)) + ([], []) + (zip xs t) + +-- TEST ---------------------------------------------------------------------- +main :: IO () +main = + print $ + rangeFormat + [ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, + 37, 38, 39] diff --git a/Task/Range-extraction/Haskell/range-extraction-4.hs b/Task/Range-extraction/Haskell/range-extraction-4.hs new file mode 100644 index 0000000000..6604ae21bd --- /dev/null +++ b/Task/Range-extraction/Haskell/range-extraction-4.hs @@ -0,0 +1,31 @@ +import Data.List (intercalate, groupBy, isPrefixOf) +import Data.List.Split (chop) + +rangeFormat :: [Int] -> String +rangeFormat xs = + intercalate "," $ + (\x -> head (if_ (length x > 1) (tail x) x)) <$> + groupBy isPrefixOf (rangeString <$> chop succSpan (zip xs (tail xs))) + where + rangeString [] = "" + rangeString xxs@(x:xs) + | null xs = show (snd x) + | otherwise = intercalate "-" (show <$> [fst x, snd (last xs)]) + succSpan [] = ([], []) + succSpan (xxs@(x:xs)) + | null ys = ([x], xs) + | otherwise = (ys, zs) + where + (ys, zs) = span (uncurry ((==) . succ)) xxs + +if_ :: Bool -> a -> a -> a +if_ True x _ = x +if_ False _ y = y + +main :: IO () +main = + putStrLn $ + rangeFormat [ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, + 37, 38, 39 ] diff --git a/Task/Range-extraction/JavaScript/range-extraction-2.js b/Task/Range-extraction/JavaScript/range-extraction-2.js index cd869a464a..b818dd65e3 100644 --- a/Task/Range-extraction/JavaScript/range-extraction-2.js +++ b/Task/Range-extraction/JavaScript/range-extraction-2.js @@ -1,45 +1,64 @@ -(function (lstTest) { +(function () { 'use strict'; - function rangeString(xs) { - var iRightmost = xs.length - 1, + // rangeFormat :: [Int] -> String + var rangeFormat = function (xs) { + return splitBy(function (a, b) { + return b - a > 1; + }, xs) + .map(rangeString) + .join(','); + }; - // Using foldr/reduceRight proves simpler here than foldl/reduce - // (the left end of the list is easier to reach than the tip of the tail) - lstSeries = xs.reduceRight(function (a, x, i, l) { + // rangeString :: [Int] -> String + var rangeString = function (xs) { + return xs.length > 2 ? [head(xs), last(xs)].map(show) + .join('-') : xs.join(','); + }; - return i < iRightmost ? ( + // GENERIC FUNCTIONS - // new series if rightward gap > 1 - l[i + 1] - x > 1 ? ( - [[x]].concat(a) - ) : ( + // Splitting not on a delimiter, but whenever the relationship between + // two consecutive items matches a supplied predicate function - // This value prepended to current series (if a - // series-breaker, or the start of the list, is at left) - (i === 0 || (x - l[i - 1]) > 1) ? ( - [[x].concat(a[0])].concat(a.slice(1)) + // splitBy :: (a -> a -> Bool) -> [a] -> [[a]] + var splitBy = function (f, xs) { + if (xs.length < 2) return [xs]; + var h = head(xs), + lstParts = xs.slice(1) + .reduce(function (a, x) { + var acc = a[0], + active = a[1], + prev = a[2]; - // or, if the series continues to the left, - // just an unmodified copy of the accumulator - ) : a - ) - ) : [[x]]; + return f(prev, x) ? ( + [acc.concat([active]), [x], x] + ) : [acc, active.concat(x), x]; + }, [ + [], + [h], h + ]); + return lstParts[0].concat([lstParts[1]]); + }; - }, []); + // head :: [a] -> a + var head = function (xs) { + return xs.length ? xs[0] : undefined; + }; - return lstSeries.map(function (r) { - var lng = r.length, - d = lng > 1 ? r[1] - r[0] : 0; + // last :: [a] -> a + var last = function (xs) { + return xs.length ? xs.slice(-1)[0] : undefined; + }; - return d ? r[0] + (d > 1 ? '-' : ',') + r[1] : r[0]; + // show :: a -> String + var show = function (x) { + return JSON.stringify(x); + }; - }).join(','); - } - - return rangeString(lstTest); - -})([0, 1, 2, 4, 6, 7, 8, 11, 12, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, - 37, 38, 39]); + // TEST + return rangeFormat([0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, + 33, 35, 36, 37, 38, 39 + ]); +})(); diff --git a/Task/Range-extraction/JavaScript/range-extraction-3.js b/Task/Range-extraction/JavaScript/range-extraction-3.js index 844c5f34ca..9afffdce52 100644 --- a/Task/Range-extraction/JavaScript/range-extraction-3.js +++ b/Task/Range-extraction/JavaScript/range-extraction-3.js @@ -1 +1,55 @@ -"0-2,4,6-8,11,12,14-25,27-33,35-39" +(() => { + 'use strict'; + + // rangeFormat :: [Int] -> String + const rangeFormat = xs => + splitBy((a, b) => b - a > 1, xs) + .map(rangeString) + .join(','); + + // rangeString :: [Int] -> String + const rangeString = xs => + xs.length > 2 ? ( + [head(xs), last(xs)].map(show) + .join('-') + ) : xs.join(',') + + + // GENERIC FUNCTIONS + + // Splitting not on a delimiter, but whenever the relationship between + // two consecutive items matches a supplied predicate function + + // splitBy :: (a -> a -> Bool) -> [a] -> [[a]] + const splitBy = (f, xs) => { + if (xs.length < 2) return [xs]; + const + h = head(xs), + lstParts = xs.slice(1) + .reduce(([acc, active, prev], x) => + f(prev, x) ? ( + [acc.concat([active]), [x], x] + ) : [acc, active.concat(x), x], [ + [], + [h], + h + ]); + return lstParts[0].concat([lstParts[1]]); + }; + + // head :: [a] -> a + const head = xs => xs.length ? xs[0] : undefined; + + // last :: [a] -> a + const last = xs => xs.length ? xs.slice(-1)[0] : undefined; + + // show :: a -> String + const show = x => JSON.stringify(x); + + // TEST + return rangeFormat([0, 1, 2, 4, 6, 7, 8, 11, 12, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, + 37, 38, 39 + ]); +})(); diff --git a/Task/Range-extraction/jq/range-extraction.jq b/Task/Range-extraction/Jq/range-extraction.jq similarity index 100% rename from Task/Range-extraction/jq/range-extraction.jq rename to Task/Range-extraction/Jq/range-extraction.jq diff --git a/Task/Range-extraction/K/range-extraction-1.k b/Task/Range-extraction/K/range-extraction-1.k deleted file mode 100644 index b76c755ed2..0000000000 --- a/Task/Range-extraction/K/range-extraction-1.k +++ /dev/null @@ -1,3 +0,0 @@ -grp : {(&~1=0,-':x)_ x} -fmt : {:[1=#s:$x;s;(*s),:[3>#s;",";"-"],*|s]} -erng: {{x,",",y}/,//'fmt'grp x} diff --git a/Task/Range-extraction/K/range-extraction-2.k b/Task/Range-extraction/K/range-extraction-2.k deleted file mode 100644 index 67acdeeb8c..0000000000 --- a/Task/Range-extraction/K/range-extraction-2.k +++ /dev/null @@ -1,2 +0,0 @@ - erng 0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39 -"0-2,4,6-8,11,12,14-25,27-33,35-39" diff --git a/Task/Range-extraction/Kotlin/range-extraction.kotlin b/Task/Range-extraction/Kotlin/range-extraction.kotlin new file mode 100644 index 0000000000..44d6a57d66 --- /dev/null +++ b/Task/Range-extraction/Kotlin/range-extraction.kotlin @@ -0,0 +1,37 @@ +// version 1.0.6 + +fun extractRange(list: List): String { + if (list.isEmpty()) return "" + val sb = StringBuilder() + var first = list[0] + var prev = first + + fun append(index: Int) { + if (first == prev) sb.append(prev) + else if (first == prev - 1) sb.append(first, ",", prev) + else sb.append(first, "-", prev) + if (index < list.size - 1) sb.append(",") + } + + for (i in 1 until list.size) { + if (list[i] == prev + 1) prev++ + else { + append(i) + first = list[i] + prev = first + } + } + append(list.size - 1) + return sb.toString() +} + +fun main(args: Array) { + val list1 = listOf(-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20) + println(extractRange(list1)) + println() + val list2 = listOf(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, + 37, 38, 39) + println(extractRange(list2)) +} diff --git a/Task/Range-extraction/Nimrod/range-extraction.nimrod b/Task/Range-extraction/Nimrod/range-extraction.nimrod deleted file mode 100644 index 8f300ed0ea..0000000000 --- a/Task/Range-extraction/Nimrod/range-extraction.nimrod +++ /dev/null @@ -1,30 +0,0 @@ -import parseutils, re, strutils - -proc extractRange(input: string): string = - var list = input.replace(re"\s+").split(',').map(parseInt) - var ranges: seq[string] = @[] - var i = 0 - while i < list.len: - var first = list[i] # first element in the current range - var offset = i - while True: # skip ahead to the end of the current range - if i + 1 >= list.len: - # reached end of the list - break - if list[i + 1] - (i + 1) != first - offset: - # next element isn't in the current range - break - i.inc - var last = list[i] # last element in the current range - case last - first - of 0: ranges.add($first) - of 1: ranges.add("$1,$2".format([$first, $last])) - else: ranges.add("$1-$2".format([$first, $last])) - i.inc - return ranges.join(",") - -echo(""" - 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, - 37, 38, 39""".extractRange) diff --git a/Task/Range-extraction/OoRexx/range-extraction.rexx b/Task/Range-extraction/OoRexx/range-extraction.rexx new file mode 100644 index 0000000000..9d43300b82 --- /dev/null +++ b/Task/Range-extraction/OoRexx/range-extraction.rexx @@ -0,0 +1,79 @@ +/* Rexx */ + +parse arg userInput +call runSample userInput +return +exit + +-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ +-- Compact a list of numbers by reducing ranges +compact: +procedure +--trace ?r;nop + parse arg expanded + nums = expanded~changestr(',', ' ')~space -- remove possible commas & clean up the string + rezult = '' + + RANGE = 0 + FIRST = nums~word(1) -- set starting value + loop i_ = 2 to nums~words -- each word in the string is a number to examine + LOCAL = nums~word(i_) + if LOCAL - FIRST - RANGE == 1 then do + -- inside a range + RANGE += 1 + end + else do + -- not inside a range + if RANGE \= 0 then do + -- we have a range of numbers so collect this and reset + rezult = rezult || FIRST || delim(RANGE) || FIRST + RANGE || ',' + RANGE = 0 + end + else do + -- just collect this number + rezult = rezult || FIRST || ',' + end + FIRST = LOCAL -- bump new starting value + end + end i_ + if RANGE \= 0 then do + -- collect terminating value (a range) + rezult = rezult || FIRST || delim(RANGE) || FIRST + RANGE + end + else do + -- collect terminating value (a single number) + rezult = rezult || FIRST + end + + return rezult~space(1, ',') -- format and return result string + +-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ +-- determine if the range delimiter should be a comma or dash +delim: +procedure + parse arg range . + if range == 1 then dlm = ',' + else dlm = '-' + return dlm + +-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ +-- sample driver +runSample: +procedure +parse arg userInput +td. = 0 +if userInput~words > 0 then do + td.0 += 1; r_ = td.0; td.r_ = userInput + end +else do + td.0 += 1; r_ = td.0; td.r_ = '-6 -3 -2 -1 0 1 3 4 5 7 8 9 10 11 14 15 17 18 19 20' + td.0 += 1; r_ = td.0; td.r_ = '0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39' + td.0 += 1; r_ = td.0; td.r_ = '-4, -3, -2, 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39' + end + +loop r_ = 1 to td.0 + say 'Original: ' td.r_~changestr(',', ' ')~space(1, ',') + say 'Compacted:' compact(td.r_) + say + end r_ +return diff --git a/Task/Range-extraction/Oz/range-extraction-1.oz b/Task/Range-extraction/Oz/range-extraction-1.oz deleted file mode 100644 index 47b0006861..0000000000 --- a/Task/Range-extraction/Oz/range-extraction-1.oz +++ /dev/null @@ -1,47 +0,0 @@ -declare - fun {Extract Xs} - {CommaSeparated - {Map {ExtractRanges Xs} RangeToString}} - end - - fun {ExtractRanges Xs} - fun {Loop Ys Start End} - case Ys - of Y|Yr andthen Y == End+1 then {Loop Yr Start Y} - [] Y|Yr then Start#End|{Loop Yr Y Y} - [] nil then [Start#End] - end - end - in - case Xs - of X|Xr then {Loop Xr X X} - [] nil then nil - end - end - - fun {RangeToString S#E} - if E-S >= 2 then - {VirtualString.toString S#"-"#E} - else - {CommaSeparated - {Map {List.number S E 1} Int.toString}} - end - end - - fun {CommaSeparated Xs} - {Flatten {Intersperse "," Xs}} - end - - fun {Intersperse Sep Xs} - case Xs of X|Y|Xr then - X|Sep|{Intersperse Sep Y|Xr} - else - Xs - end - end -in - {System.showInfo - {Extract [ 0 1 2 4 6 7 8 11 12 14 - 15 16 17 18 19 20 21 22 23 24 - 25 27 28 29 30 31 32 33 35 36 - 37 38 39 ]}} diff --git a/Task/Range-extraction/Oz/range-extraction-2.oz b/Task/Range-extraction/Oz/range-extraction-2.oz deleted file mode 100644 index b8bbe64039..0000000000 --- a/Task/Range-extraction/Oz/range-extraction-2.oz +++ /dev/null @@ -1 +0,0 @@ -0-2,4,6-8,11,12,14-25,27-33,35-39 diff --git a/Task/Range-extraction/PL-I/range-extraction-3.pli b/Task/Range-extraction/PL-I/range-extraction-3.pli deleted file mode 100644 index ae893dafc3..0000000000 --- a/Task/Range-extraction/PL-I/range-extraction-3.pli +++ /dev/null @@ -1 +0,0 @@ - 0-2,4,6-8,11,12,14-25,27-33,35-39 diff --git a/Task/Range-extraction/Python/range-extraction-1.py b/Task/Range-extraction/Python/range-extraction-1.py deleted file mode 100644 index 862626e1c7..0000000000 --- a/Task/Range-extraction/Python/range-extraction-1.py +++ /dev/null @@ -1,19 +0,0 @@ -def rangeextract(lst): - lenlst = len(lst) - i, ranges = 0, [] - while i< lenlst: - low = lst[i] - while i = 2 else - ('%i,%i' % (low, hi) if hi - low == 1 else - '%i' % low) ) - i += 1 - return ','.join(ranges) - -lst = [ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, - 37, 38, 39] -print(rangeextract(lst)) diff --git a/Task/Range-extraction/Python/range-extraction-2.py b/Task/Range-extraction/Python/range-extraction-2.py deleted file mode 100644 index 662e67ca8c..0000000000 --- a/Task/Range-extraction/Python/range-extraction-2.py +++ /dev/null @@ -1,26 +0,0 @@ -def grouper(lst): - src = iter(lst) - acc = [ next(src) ] - for i in src: - if i == acc[-1] + 1: acc.append(i) - else: - yield acc - acc = [i] - yield acc - raise StopIteration() - -def rangegrouper(lst): - for g in grouper(lst): - if len(g) == 2: - # satisfy rule that only runs longer than 2 are grouped - a,b = g - yield [a] - yield [b] - else: yield g - raise StopIteration() - -input= [0, 1, 2, 4, 6, 7, 8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39] -print list(rangegrouper(input)) # print groups -as_strings= ['%s%s%s' % ((g[0],'-',g[-1]) if len(g) > 1 else (g[0],'','')) for g in rangegrouper(input)] -print as_strings -print ', '.join(as_strings) diff --git a/Task/Range-extraction/Swift/range-extraction-1.swift b/Task/Range-extraction/Swift/range-extraction-1.swift deleted file mode 100644 index ba97fa52f2..0000000000 --- a/Task/Range-extraction/Swift/range-extraction-1.swift +++ /dev/null @@ -1,47 +0,0 @@ -func rangesFromInts(ints:[Int]) -> [(Int, Int)] { - - var range : (Int, Int)? - var ranges = [(Int, Int)]() - for this in ints { - if let (start, end) = range { - if this == end + 1 { - range = (start, this) - } - else { - ranges.append(range!) - range = (this, this) - } - } - else { range = (this, this) } - } - ranges.append(range!) - - return ranges -} - -func descriptionFromRanges(ranges:[(Int, Int)]) -> String { - var desc = "" - for (start, end) in ranges { - desc += desc.isEmpty ? "" : "," - if start == end { - desc += "\(start)" - } - else if end == start + 1 { - desc += "\(start),\(end)" - } - else { - desc += "\(start)-\(end)" - } - } - return desc -} - - -let ex = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20] -let longer = [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, - 37, 38, 39] - -descriptionFromRanges(rangesFromInts(ex)) -descriptionFromRanges(rangesFromInts(longer)) diff --git a/Task/Range-extraction/Swift/range-extraction-2.swift b/Task/Range-extraction/Swift/range-extraction-2.swift deleted file mode 100644 index b4f287ffb0..0000000000 --- a/Task/Range-extraction/Swift/range-extraction-2.swift +++ /dev/null @@ -1,35 +0,0 @@ -extension NSIndexSet { - - var rangesDescription : String { - var out = "" - indexSet.enumerateRangesUsingBlock { range, _ in - let start = range.location - let end = range.location+range.length-1 - out += out.isEmpty ? "" : "," - if start == end { - out += "\(start)" - } - else if end == start + 1 { - out += "\(start),\(end)" - } - else { - out += "\(start)-\(end)" - } - } - return out - } -} - -let ex = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20] -let longer = [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, - 37, 38, 39] - -var indexSet = NSMutableIndexSet() -ex.map { indexSet.addIndex($0) } -indexSet.rangesDescription - -var indexSet2 = NSMutableIndexSet() -longer.map { indexSet2.addIndex($0) } -indexSet2.rangesDescription diff --git a/Task/Range-extraction/Swift/range-extraction.swift b/Task/Range-extraction/Swift/range-extraction.swift new file mode 100644 index 0000000000..33325e7b8d --- /dev/null +++ b/Task/Range-extraction/Swift/range-extraction.swift @@ -0,0 +1,49 @@ +import Darwin + +func ranges(from ints:[Int]) -> [(Int, Int)] { + + var range : (Int, Int)? + var ranges = [(Int, Int)]() + for this in ints { + if let (start, end) = range { + if this == end + 1 { + range = (start, this) + } + else { + ranges.append(range!) + range = (this, this) + } + } + else { range = (this, this) } + } + ranges.append(range!) + + return ranges +} + +func description(from ranges:[(Int, Int)]) -> String { + var desc = "" + for (start, end) in ranges { + desc += desc.isEmpty ? "" : "," + if start == end { + desc += "\(start)" + } + else if end == start + 1 { + desc += "\(start),\(end)" + } + else { + desc += "\(start)-\(end)" + } + } + return desc +} + + +let ex = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20] +let longer = [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, + 37, 38, 39] + +print(description(from: ranges(from: ex))) +print(description(from: ranges(from: longer))) diff --git a/Task/Range-extraction/TUSCRIPT/range-extraction-1.tu b/Task/Range-extraction/TUSCRIPT/range-extraction-1.tu index 29597e59b7..902a9ef465 100644 --- a/Task/Range-extraction/TUSCRIPT/range-extraction-1.tu +++ b/Task/Range-extraction/TUSCRIPT/range-extraction-1.tu @@ -1,4 +1,4 @@ -$$ MODE TUSCRIPT +$$ MODE TUSCRIPT,{} MODE DATA $$ numbers=* 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, @@ -6,7 +6,7 @@ $$ numbers=* 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 $$ MODE TUSCRIPT -numbers=EXCHANGE (numbers,":,><<> :':") +numbers=EXCHANGE (numbers,":,{0-00} :':") unrangednrs=JOIN (numbers,"") rangednrs=COMBINE (unrangednrs,"") rangednrs=EXCHANGE (rangednrs,":':,:") diff --git a/Task/Range-extraction/Zkl/range-extraction-1.zkl b/Task/Range-extraction/Zkl/range-extraction-1.zkl new file mode 100644 index 0000000000..cc3446d0d9 --- /dev/null +++ b/Task/Range-extraction/Zkl/range-extraction-1.zkl @@ -0,0 +1,10 @@ +fcn range(ns){ + fcn(w){ + if (w.atEnd) return(Void.Stop); + a:=b:=w.next(); n:=0; + while(b+1 == (c:=w.peekN(n))){ n+=1; b=c } + if(n>1){do(n){w.next()}; return("%d-%d".fmt(a,b)); } + a + } : + (0).pump(*,List,_.fp(ns.walker().tweak(Void,Void))).concat(","); +} diff --git a/Task/Range-extraction/Zkl/range-extraction-2.zkl b/Task/Range-extraction/Zkl/range-extraction-2.zkl new file mode 100644 index 0000000000..9cfff0aeb1 --- /dev/null +++ b/Task/Range-extraction/Zkl/range-extraction-2.zkl @@ -0,0 +1,11 @@ +var ns=T(-6,-3,-2,-1,0,1,3,4,5,7,8,9,10,11,14,15,17,18,19,20); +range(ns).println(); + +ns=T( + 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, + 37, 38, 39); +range(ns).println(); + +range([1..100]).println(); diff --git a/Task/Ranking-methods/jq/ranking-methods-1.jq b/Task/Ranking-methods/Jq/ranking-methods-1.jq similarity index 100% rename from Task/Ranking-methods/jq/ranking-methods-1.jq rename to Task/Ranking-methods/Jq/ranking-methods-1.jq diff --git a/Task/Ranking-methods/jq/ranking-methods-2.jq b/Task/Ranking-methods/Jq/ranking-methods-2.jq similarity index 100% rename from Task/Ranking-methods/jq/ranking-methods-2.jq rename to Task/Ranking-methods/Jq/ranking-methods-2.jq diff --git a/Task/Ranking-methods/Kotlin/ranking-methods.kotlin b/Task/Ranking-methods/Kotlin/ranking-methods.kotlin new file mode 100644 index 0000000000..01b2805918 --- /dev/null +++ b/Task/Ranking-methods/Kotlin/ranking-methods.kotlin @@ -0,0 +1,80 @@ +// version 1.0.6 + +/* all ranking functions assume the array of Pairs is non-empty and already sorted by decreasing order of scores + and then, if the scores are equal, by reverse alphabetic order of names +*/ + +fun standardRanking(scores: Array>): IntArray { + val rankings = IntArray(scores.size) + rankings[0] = 1 + for (i in 1 until scores.size) rankings[i] = if (scores[i].first == scores[i - 1].first) rankings[i - 1] else i + 1 + return rankings +} + +fun modifiedRanking(scores: Array>): IntArray { + val rankings = IntArray(scores.size) + rankings[0] = 1 + for (i in 1 until scores.size) { + rankings[i] = i + 1 + val currScore = scores[i].first + for (j in i - 1 downTo 0) { + if (currScore != scores[j].first) break + rankings[j] = i + 1 + } + } + return rankings +} + +fun denseRanking(scores: Array>): IntArray { + val rankings = IntArray(scores.size) + rankings[0] = 1 + var prevRanking = 1 + for (i in 1 until scores.size) rankings[i] = if (scores[i].first == scores[i - 1].first) prevRanking else ++prevRanking + return rankings +} + +fun ordinalRanking(scores: Array>) = IntArray(scores.size) { it + 1 } + +fun fractionalRanking(scores: Array>): DoubleArray { + val rankings = DoubleArray(scores.size) + rankings[0] = 1.0 + for (i in 1 until scores.size) { + var k = i + val currScore = scores[i].first + for (j in i - 1 downTo 0) { + if (currScore != scores[j].first) break + k = j + } + val avg = (k..i).average() + 1.0 + for (m in k..i) rankings[m] = avg + } + return rankings +} + +fun printRankings(title: String, rankings: IntArray, scores: Array>) { + println(title + ":") + for (i in 0 until rankings.size) { + print ("${rankings[i]} ") + println(scores[i].toString().removeSurrounding("(", ")").replace(",", "")) + } + println() +} + +fun printFractionalRankings(title: String, rankings: DoubleArray, scores: Array>) { + println(title + ":") + for (i in 0 until rankings.size) { + print ("${"%3.2f".format(rankings[i])} ") + println(scores[i].toString().removeSurrounding("(", ")").replace(",", "")) + } + println() +} + +fun main(args: Array) { + val scores = arrayOf(44 to "Solomon", 42 to "Jason", 42 to "Errol", 41 to "Garry", + 41 to "Bernard", 41 to "Barry", 39 to "Stephen") + printRankings("Standard ranking", standardRanking(scores), scores) + printRankings("Modified ranking", modifiedRanking(scores), scores) + printRankings("Dense ranking", denseRanking(scores), scores) + printRankings("Ordinal ranking", ordinalRanking(scores), scores) + printFractionalRankings("Fractional ranking", fractionalRanking(scores), scores) +} diff --git a/Task/Ranking-methods/Zkl/ranking-methods-1.zkl b/Task/Ranking-methods/Zkl/ranking-methods-1.zkl new file mode 100644 index 0000000000..0afc601a0f --- /dev/null +++ b/Task/Ranking-methods/Zkl/ranking-methods-1.zkl @@ -0,0 +1,34 @@ +fcn group(scores){ // group like scores into one list --> list of lists + sink:=List(); + scores.reduce('wrap(ps,sn,buf){ + if(sn[0]!=ps){ sink.append(buf.copy()); buf.clear(); } + buf+sn; + sn[0]; + },scores[0][0],buf:=List()); + sink.append(buf); +} +fcn print(list,rank){ + list.apply2('wrap(sn){ "%2s: %s (%d)".fmt(rank,sn[1],sn[0]):println(_); }); +} +fcn rankViaStandard(scores){ + rank:=1; + foreach group in (group(scores)){ print(group,rank); rank+=group.len(); } +} +fcn rankViaModified(scores){ + rank:=0; + foreach group in (group(scores)){ rank+=group.len(); print(group,rank); } +} +fcn rankViaDense(scores){ + rank:=1; + foreach group in (group(scores)){ print(group,rank); rank+=1; } +} +fcn rankViaOrdinal(scores){ + scores.apply2('wrap(sn,rr){ "%2s: %s (%d)".fmt(rr.inc(),sn[1],sn[0]):println(_); },Ref(1)); +} +fcn rankViaFractional(scores){ + rank:=1; + foreach group in (group(scores)){ + n:=group.len(); r:=rank.reduce(n,'+,0.0)/n; rank+=n; + print(group,"%5.2f".fmt(r)); + } +} diff --git a/Task/Ranking-methods/Zkl/ranking-methods-2.zkl b/Task/Ranking-methods/Zkl/ranking-methods-2.zkl new file mode 100644 index 0000000000..5fbd893b0c --- /dev/null +++ b/Task/Ranking-methods/Zkl/ranking-methods-2.zkl @@ -0,0 +1,8 @@ + // these are sorted!?! +scores:=T(T(44,"Solomon"), T(42,"Jason"), T(42,"Errol"), T(41,"Garry"), + T(41,"Bernard"),T(41,"Barry"),T(39,"Stephen"),); +"Standard:" .println(); rankViaStandard(scores); +"Modified:" .println(); rankViaModified(scores); +"Dense:" .println(); rankViaDense(scores); +"Ordinal:" .println(); rankViaOrdinal(scores); +"Fractional:".println(); rankViaFractional(scores); diff --git a/Task/Rate-counter/BaCon/rate-counter.bacon b/Task/Rate-counter/BaCon/rate-counter.bacon new file mode 100644 index 0000000000..46f0d73d1c --- /dev/null +++ b/Task/Rate-counter/BaCon/rate-counter.bacon @@ -0,0 +1,18 @@ +' Rate counter +FOR i = 1 TO 3 + GOSUB timeit +NEXT + +i = 2000 +GOSUB timeit +END + +LABEL timeit + iter = 0 + starter = TIMER + WHILE TRUE DO + INCR iter + IF TIMER >= starter + i THEN BREAK + WEND + PRINT iter, " iterations in ", i, " millisecond", IIF$(i > 1, "s", "") + RETURN diff --git a/Task/Rate-counter/Fortran/rate-counter.f b/Task/Rate-counter/Fortran/rate-counter.f new file mode 100644 index 0000000000..921605a941 --- /dev/null +++ b/Task/Rate-counter/Fortran/rate-counter.f @@ -0,0 +1,4 @@ + DO I = FIRST,LAST + IF (PROGRESSNOTE((I - FIRST)/(LAST - FIRST + 1.0))) WRITE (6,*) "Reached ",I,", towards ",LAST + ...much computation... + END DO diff --git a/Task/Rate-counter/Kotlin/rate-counter.kotlin b/Task/Rate-counter/Kotlin/rate-counter.kotlin new file mode 100644 index 0000000000..2d69987c55 --- /dev/null +++ b/Task/Rate-counter/Kotlin/rate-counter.kotlin @@ -0,0 +1,20 @@ +// version 1.1.3 + +typealias Func = (T) -> T + +fun cube(n: Int) = n * n * n + +fun benchmark(n: Int, func: Func, arg: T): LongArray { + val times = LongArray(n) + for (i in 0 until n) { + val m = System.nanoTime() + func(arg) + times[i] = System.nanoTime() - m + } + return times +} + +fun main(args: Array) { + println("\nTimings (nanoseconds) : ") + for (time in benchmark(10, ::cube, 5)) println(time) +} diff --git a/Task/Rate-counter/Ring/rate-counter.ring b/Task/Rate-counter/Ring/rate-counter.ring new file mode 100644 index 0000000000..f07ac21f5f --- /dev/null +++ b/Task/Rate-counter/Ring/rate-counter.ring @@ -0,0 +1,29 @@ +# Project : Rate counter +# Date : 2017/09/11 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +see "method 1: calculate reciprocal of elapsed time:" + nl +for trial = 1 to 3 + start = clock() + tasktomeasure() + finish = clock() + see "rate = " + 100 / (finish-start) + " per second" + nl +next + +see "method 2: count completed tasks in one second:" + nl +for trial = 1 to 3 + runs = 0 + finish = clock() + 100 + while clock() < finish + tasktomeasure() + if clock() < finish + runs = runs + 1 + ok + end + see "rate = " + runs + " per second" + nl +next + +func tasktomeasure + for i = 1 to 100000 + next diff --git a/Task/Rate-counter/Zkl/rate-counter-1.zkl b/Task/Rate-counter/Zkl/rate-counter-1.zkl new file mode 100644 index 0000000000..c7194ce6e7 --- /dev/null +++ b/Task/Rate-counter/Zkl/rate-counter-1.zkl @@ -0,0 +1,18 @@ +fcn rateCounter(f,timeNRuns,secsToRun=Void){ + now:=Time.Clock.time; + if(secsToRun){ + then:=now + secsToRun; + N:=0; do{ f(); N+=1; }while(Time.Clock.time B.y || + x >= A.x && x >= B.x) { + return false; + } else if (x < A.x && x < B.x) { + return true; + } else { + return (y - A.y) / (x - A.x) > (B.y - A.y) / (B.x - A.x); + } + } else { + return west(B, A, x, y); + } + } +} + +var square = {name: 'square', bounds: [{x: 0, y: 0}, {x: 20, y: 0}, {x: 20, y: 20}, {x: 0, y: 20}]}; +var squareHole = { + name: 'squareHole', + bounds: [{x: 0, y: 0}, {x: 20, y: 0}, {x: 20, y: 20}, {x: 0, y: 20}, {x: 5, y: 5}, {x: 15, y: 5}, {x: 15, y: 15}, {x: 5, y: 15}] +}; +var strange = { + name: 'strange', + bounds: [{x: 0, y: 0}, {x: 5, y: 5}, {x: 0, y: 20}, {x: 5, y: 15}, {x: 15, y: 15}, {x: 20, y: 20}, {x: 20, y: 0}] +}; +var hexagon = { + name: 'hexagon', + bounds: [{x: 6, y: 0}, {x: 14, y: 0}, {x: 20, y: 10}, {x: 14, y: 20}, {x: 6, y: 20}, {x: 0, y: 10}] +}; + +var shapes = [square, squareHole, strange, hexagon]; +var testPoints = [{lng: 10, lat: 10}, {lng: 10, lat: 16}, {lng: -20, lat: 10}, + {lng: 0, lat: 10}, {lng: 20, lat: 10}, {lng: 16, lat: 10}, {lng: 20, lat: 20}]; + +for (var s = 0; s < shapes.length; s++) { + var shape = shapes[s]; + for (var tp = 0; tp < testPoints.length; tp++) { + var testPoint = testPoints[tp]; + console.log(JSON.stringify(testPoint) + '\tin ' + shape.name + '\t' + contains(shape.bounds, testPoint.lat, testPoint.lng)); + } +} diff --git a/Task/Ray-casting-algorithm/Kotlin/ray-casting-algorithm-1.kotlin b/Task/Ray-casting-algorithm/Kotlin/ray-casting-algorithm-1.kotlin index 4dbe9a1df0..1924ade84f 100644 --- a/Task/Ray-casting-algorithm/Kotlin/ray-casting-algorithm-1.kotlin +++ b/Task/Ray-casting-algorithm/Kotlin/ray-casting-algorithm-1.kotlin @@ -1,7 +1,6 @@ -package ray_casting - -import java.lang.Double.* -import java.lang.Math.* +import java.lang.Double.MAX_VALUE +import java.lang.Double.MIN_VALUE +import java.lang.Math.abs data class Point(val x: Double, val y: Double) @@ -9,8 +8,8 @@ data class Edge(val s: Point, val e: Point) { operator fun invoke(p: Point) : Boolean = when { s.y > e.y -> Edge(e, s).invoke(p) p.y == s.y || p.y == e.y -> invoke(Point(p.x, p.y + epsilon)) - p.y > e.y || p.y < s.y || p.x > max(s.x, e.x) -> false - p.x < min(s.x, e.x) -> true + p.y > e.y || p.y < s.y || p.x > Math.max(s.x, e.x) -> false + p.x < Math.min(s.x, e.x) -> true else -> { val blue = if (abs(s.x - p.x) > MIN_VALUE) (p.y - s.y) / (p.x - s.x) else MAX_VALUE val red = if (abs(s.x - e.x) > MIN_VALUE) (e.y - s.y) / (e.x - s.x) else MAX_VALUE diff --git a/Task/Ray-casting-algorithm/Kotlin/ray-casting-algorithm-2.kotlin b/Task/Ray-casting-algorithm/Kotlin/ray-casting-algorithm-2.kotlin index 75d651645a..1b892ff1d1 100644 --- a/Task/Ray-casting-algorithm/Kotlin/ray-casting-algorithm-2.kotlin +++ b/Task/Ray-casting-algorithm/Kotlin/ray-casting-algorithm-2.kotlin @@ -1,5 +1,3 @@ -package ray_casting - fun main(args: Array) { val figures = arrayOf(Figure("Square", arrayOf(Edge(Point(0.0, 0.0), Point(10.0, 0.0)), Edge(Point(10.0, 0.0), Point(10.0, 10.0)), Edge(Point(10.0, 10.0), Point(0.0, 10.0)),Edge(Point(0.0, 10.0), Point(0.0, 0.0)))), diff --git a/Task/Ray-casting-algorithm/Racket/ray-casting-algorithm-1.rkt b/Task/Ray-casting-algorithm/Racket/ray-casting-algorithm-1.rkt deleted file mode 100644 index f7c3e63219..0000000000 --- a/Task/Ray-casting-algorithm/Racket/ray-casting-algorithm-1.rkt +++ /dev/null @@ -1,75 +0,0 @@ -#lang racket - -(module pip racket - (require racket/contract) - - (provide point) - (provide seg) - (provide (contract-out [point-in-polygon? (-> - point? - list? - boolean?)])) - - (struct point (x y) #:transparent) - (struct seg (Ax Ay Bx By)) - (define ε 0.000001) - (define (neq? x y) (not (eq? x y))) - - (define (ray-cross-seg? r s) - (let* ([Ax (seg-Ax s)] [Ay (seg-Ay s)] - [Bx (seg-Bx s)] [By (seg-By s)] - [Px (point-x r)] [Pyo (point-y r)] - [Py (+ Pyo (if (or (eq? Pyo Ay) - (eq? Pyo By)) - ε 0))]) - - (cond [(or (< Py Ay) (> Py By)) #f] - [(> Px (max Ax Bx)) #f] - [(< Px (min Ax Bx)) #t] - [else - (let ([red (if (neq? Ax Px) - (/ (- By Ay) (- Bx Ax)) - +inf.0)] - [blue (if (neq? Ax Px) - (/ (- Py Ax) (- Px Ax)) - +inf.0)]) - (if (>= blue red) #t #f))]))) - - (define (point-in-polygon? point polygon) - (odd? - (for/fold ([c 0]) ([seg polygon]) - (+ c (if (ray-cross-seg? point seg) 1 0)))))) - -(require 'pip) - -(define test-point-list - (list - (point 5.0 5.0) - (point 5.0 8.0) - (point -10.0 5.0) - (point 0.0 5.0) - (point 10.0 5.0) - (point 8.0 5.0) - (point 10.0 10.0))) - -(define square - (list (seg 0.0 0.0 10.0 0.0) - (seg 10.0 0.0 10.0 10.0) - (seg 10.0 10.0 0.0 10.0) - (seg 0.0 0.0 0.0 10.0))) - -(define exagon - (list (seg 3.0 0.0 7.0 0.0) - (seg 7.0 0.0 10.0 5.0) - (seg 10.0 5.0 7.0 10.0) - (seg 7.0 10.0 3.0 10.0) - (seg 0.0 5.0 3.0 10.0) - (seg 3.0 0.0 0.0 5.0))) - -(define (test-figure fig name) - (printf "\ntesting ~a: \n" name) - (for ([p test-point-list]) - (printf "testing ~v: ~a\n" p (point-in-polygon? p fig)))) - -(test-figure square "square") -(test-figure exagon "exagon") diff --git a/Task/Ray-casting-algorithm/Racket/ray-casting-algorithm-2.rkt b/Task/Ray-casting-algorithm/Racket/ray-casting-algorithm-2.rkt deleted file mode 100644 index 3d7177c58c..0000000000 --- a/Task/Ray-casting-algorithm/Racket/ray-casting-algorithm-2.rkt +++ /dev/null @@ -1,17 +0,0 @@ -testing square: -testing (point 5.0 5.0): #t -testing (point 5.0 8.0): #t -testing (point -10.0 5.0): #f -testing (point 0.0 5.0): #f -testing (point 10.0 5.0): #t -testing (point 8.0 5.0): #t -testing (point 10.0 10.0): #f - -testing exagon: -testing (point 5.0 5.0): #t -testing (point 5.0 8.0): #t -testing (point -10.0 5.0): #f -testing (point 0.0 5.0): #f -testing (point 10.0 5.0): #t -testing (point 8.0 5.0): #t -testing (point 10.0 10.0): #f diff --git a/Task/Ray-casting-algorithm/Rust/ray-casting-algorithm.rust b/Task/Ray-casting-algorithm/Rust/ray-casting-algorithm.rust new file mode 100644 index 0000000000..f6f5f85d88 --- /dev/null +++ b/Task/Ray-casting-algorithm/Rust/ray-casting-algorithm.rust @@ -0,0 +1,119 @@ +use std::f64; +use std::clone::Clone; + +const _EPS: f64 = 0.00001; +const _MIN: f64 = f64::MIN_POSITIVE; +const _MAX: f64 = f64::MAX; + +#[derive(Debug, Clone)] +struct Point { + x: f64, + y: f64 +} + +#[derive(Debug, Clone)] +struct Edge { + pt1: Point, + pt2: Point +} + +impl Edge { + fn new(pt1: (f64, f64), pt2: (f64, f64)) -> Edge { + Edge { pt1: Point {x: pt1.0, y: pt1.1}, pt2: Point {x: pt2.0, y: pt2.1} } + } +} + +#[derive(Debug)] +struct Polygon{ + edges: Vec // Polygon has to be created with counter-clockwise coordinates +} + +fn pt_in_polygon(pt: &Point, poly: &Polygon) -> bool { + poly.edges.iter() + .map(|edge| ray_intersect_seg(pt, edge)) + .fold(0u8, |sum, val| sum + (val as u8)) % 2 == 1 +} + +fn ray_intersect_seg(p: &Point, edge: &Edge) -> bool { + let mut pt = p.clone(); + let (mut a, mut b): (&Point, &Point) = (&edge.pt1, &edge.pt2); + if a.y > b.y { + let t = a; a = b; b = t; + } + if pt.y == a.y || pt.y == b.y { + pt = Point {x: pt.x, y: pt.y + _EPS}; + } + if (pt.y > b.y || pt.y < a.y) || pt.x > a.x.max(b.x) { + return false; + } + if pt.x < a.x.min(b.x) { + return true; + } else { + let m_red = if (a.x - b.x).abs() > _MIN { (b.y - a.y) / (b.x - a.x) } else { _MAX }; + let m_blue = if (a.x - pt.x).abs() > _MIN { (pt.y - a.y) / (pt.x - a.x) } else { _MAX }; + return m_blue >= m_red; + } +} + +fn main(){ + let p = |x,y| Point {x: x, y: y}; + let testpoints = vec![p(5.0, 5.0), p(5.0, 8.0), p(-10.0, 5.0), p(0.0, 5.0), p(10.0, 5.0), p(8.0, 5.0), p(10.0, 10.0)]; + let poly_square = Polygon { + edges: vec![ + Edge::new((0.0, 0.0), (10.0, 0.0)), + Edge::new((10.0, 0.0), (10.0, 10.0)), + Edge::new((10.0, 10.0), (0.0, 10.0)), + Edge::new((0.0, 10.0), (0.0, 0.0)) + ] + }; + let poly_square_hole = Polygon { + edges: vec![ + Edge::new((0.0, 0.0), (10.0, 0.0)), + Edge::new((10.0, 0.0), (10.0, 10.0)), + Edge::new((10.0, 10.0), (0.0, 10.0)), + Edge::new((0.0, 10.0), (0.0, 0.0)), + Edge::new((2.5, 2.5), (7.5, 2.5)), + Edge::new((7.5, 2.5), (7.5, 7.5)), + Edge::new((7.5, 7.5), (2.5, 7.5)), + Edge::new((2.5, 7.5), (2.5, 2.5)) + ] + }; + let poly_strange = Polygon { + edges: vec![ + Edge::new((0.0, 0.0), (2.5, 2.5)), + Edge::new((2.5, 2.5), (0.0, 10.0)), + Edge::new((0.0, 10.0), (2.5, 7.5)), + Edge::new((2.5, 7.5), (7.5, 7.5)), + Edge::new((7.5, 7.5), (10.0, 10.0)), + Edge::new((10.0, 10.0), (10.0, 0.0)), + Edge::new((10.0, 0.0), (2.5, 2.5)) + ] + }; + let poly_hexagon = Polygon { + edges: vec![ + Edge::new((3.0, 0.0), (7.0, 0.0)), + Edge::new((7.0, 0.0), (10.0, 5.0)), + Edge::new((10.0, 5.0), (7.0, 10.0)), + Edge::new((7.0, 10.0), (3.0, 10.0)), + Edge::new((3.0, 10.0), (0.0, 5.0)), + Edge::new((0.0, 5.0), (3.0, 0.0)) + ] + }; + print!("\nSquare :"); + for pt in testpoints.iter() { + print!(" {:?}", pt_in_polygon(pt, &poly_square)); + } + print!("\nSquare with hole:"); + for pt in testpoints.iter() { + print!(" {:?}", pt_in_polygon(pt, &poly_square_hole)); + } + print!("\nStrange polygon :"); + for pt in testpoints.iter() { + print!(" {:?}", pt_in_polygon(pt, &poly_strange)); + } + print!("\nHexagon :"); + for pt in testpoints.iter() { + print!(" {:?}", pt_in_polygon(pt, &poly_hexagon)); + } + print!("\n"); +} diff --git a/Task/Ray-casting-algorithm/Zkl/ray-casting-algorithm-1.zkl b/Task/Ray-casting-algorithm/Zkl/ray-casting-algorithm-1.zkl new file mode 100644 index 0000000000..c4947be29a --- /dev/null +++ b/Task/Ray-casting-algorithm/Zkl/ray-casting-algorithm-1.zkl @@ -0,0 +1,17 @@ +const E = 0.0001; + +fcn rayHitsSeg([(Px,Py)],[(Ax,Ay)],[(Bx,By)]){ // --> Bool + if(Py==Ay or Py==By) Py+=E; + if(PyBy or Px>Ax.max(Bx)) False + else if(Px=( (By - Ay)/(Bx - Ax) ) } //blue>=red + catch(MathError){ Px==Ax } // divide by zero == ∞, only blue? +} + +fcn pointInPoly(point, polygon){ // --> Bool, polygon is ( (a,b),(c,d).. ) + polygon.filter('wrap([(ab,cd)]){ a,b:=ab; c,d:=cd; + if(b<=d) rayHitsSeg(point,ab,cd); // left point has smallest y coordinate + else rayHitsSeg(point,cd,ab); + }) + .len().isOdd; // True if crossed an odd number of borders ie inside polygon +} diff --git a/Task/Ray-casting-algorithm/Zkl/ray-casting-algorithm-2.zkl b/Task/Ray-casting-algorithm/Zkl/ray-casting-algorithm-2.zkl new file mode 100644 index 0000000000..dd8831c86f --- /dev/null +++ b/Task/Ray-casting-algorithm/Zkl/ray-casting-algorithm-2.zkl @@ -0,0 +1,50 @@ +polys:=T( //(name,( ((a,b),(c,d)),((a,b),(c,d))... ), ... )==(nm,(ln,ln..) ..) + T("squared", + T(T(T( 0.0, 0.0), T(10.0, 0.0)), + T(T(10.0, 0.0), T(10.0, 10.0)), + T(T(10.0, 10.0), T( 0.0, 10.0)), + T(T( 0.0, 10.0), T( 0.0, 0.0)))), + T("squaredhole", + T(T(T( 0.0, 0.0), T(10.0, 0.0)), + T(T(10.0, 0.0), T(10.0, 10.0)), + T(T(10.0, 10.0), T( 0.0, 10.0)), + T(T( 0.0, 10.0), T( 0.0, 0.0)), + T(T( 2.5, 2.5), T( 7.5, 2.5)), + T(T( 7.5, 2.5), T( 7.5, 7.5)), + T(T( 7.5, 7.5), T( 2.5, 7.5)), + T(T( 2.5, 7.5), T( 2.5, 2.5)))), + T("strange", + T(T(T( 0.0, 0.0), T( 2.5, 2.5)), + T(T( 2.5, 2.5), T( 0.0, 10.0)), + T(T( 0.0, 10.0), T( 2.5, 7.5)), + T(T( 2.5, 7.5), T( 7.5, 7.5)), + T(T( 7.5, 7.5), T(10.0, 10.0)), + T(T(10.0, 10.0), T(10.0, 0.0)), + T(T(10.0, 0.0), T( 2.5, 2.5)), + T(T( 2.5, 2.5), T( 0.0, 0.0)))), # conjecturally close polygon + T("exagon", + T(T(T( 3.0, 0.0), T( 7.0, 0.0)), + T(T( 7.0, 0.0), T(10.0, 5.0)), + T(T(10.0, 5.0), T( 7.0, 10.0)), + T(T( 7.0, 10.0), T( 3.0, 10.0)), + T(T( 3.0, 10.0), T( 0.0, 5.0)), + T(T( 0.0, 5.0), T( 3.0, 0.0)))), +); + +testPoints:=T( + T( 5.0, 5.0), + T( 5.0, 8.0), + T(-10.0, 5.0), + T( 0.0, 5.0), + T( 10.0, 5.0), + T( 8.0, 5.0), + T( 10.0, 10.0) +); + +foreach name,polywanna in (polys){ + name.println(); + foreach testPoint in (testPoints){ + println("\t(%6.1f,%6.1f)\t".fmt(testPoint.xplode()), + pointInPoly(testPoint,polywanna) and "IN" or "OUT"); + } +} diff --git a/Task/Read-a-configuration-file/00DESCRIPTION b/Task/Read-a-configuration-file/00DESCRIPTION index ae216eaf54..6b58c94121 100644 --- a/Task/Read-a-configuration-file/00DESCRIPTION +++ b/Task/Read-a-configuration-file/00DESCRIPTION @@ -32,6 +32,7 @@ For this task, we have a configuration file as follows: OTHERFAMILY Rhu Barber, Harry Barber + For the task we need to set four variables according to the configuration entries as follows: *fullname = Foo Barber @@ -39,11 +40,13 @@ For the task we need to set four variables according to the configuration entrie *needspeeling = true *seedsremoved = false + We also have an option that contains multiple parameters. These may be stored in an array. * otherfamily(1) = Rhu Barber * otherfamily(2) = Harry Barber -'''See also:''' + +;Related tasks * [[Update a configuration file]]

    diff --git a/Task/Read-a-configuration-file/Ada/read-a-configuration-file-1.ada b/Task/Read-a-configuration-file/Ada/read-a-configuration-file-1.ada deleted file mode 100644 index 06232aadaa..0000000000 --- a/Task/Read-a-configuration-file/Ada/read-a-configuration-file-1.ada +++ /dev/null @@ -1,39 +0,0 @@ -with Ada.Strings.Unbounded; -with Config_File_Parser; -pragma Elaborate_All (Config_File_Parser); - -package Config is - - function TUS (S : String) return Ada.Strings.Unbounded.Unbounded_String - renames Ada.Strings.Unbounded.To_Unbounded_String; - -- Convenience rename. TUS is much shorter than To_Unbounded_String. - - type Keys is ( - FULLNAME, - FAVOURITEFRUIT, - NEEDSPEELING, - SEEDSREMOVED, - OTHERFAMILY); - -- These are the valid configuration keys. - - type Defaults_Array is - array (Keys) of Ada.Strings.Unbounded.Unbounded_String; - -- The array type we'll use to hold our default configuration settings. - - Defaults_Conf : Defaults_Array := - (FULLNAME => TUS ("John Doe"), - FAVOURITEFRUIT => TUS ("blackberry"), - NEEDSPEELING => TUS ("False"), - SEEDSREMOVED => TUS ("False"), - OTHERFAMILY => TUS ("Daniel Defoe, Ada Byron")); - -- Default values for the Program object. These can be overwritten by - -- the contents of the rosetta.cfg file(see below). - - package Rosetta_Config is new Config_File_Parser ( - Keys => Keys, - Defaults_Array => Defaults_Array, - Defaults => Defaults_Conf, - Config_File => "rosetta.cfg"); - -- Instantiate the Config configuration object. - -end Config; diff --git a/Task/Read-a-configuration-file/Ada/read-a-configuration-file-2.ada b/Task/Read-a-configuration-file/Ada/read-a-configuration-file-2.ada deleted file mode 100644 index 0bc3b4cb51..0000000000 --- a/Task/Read-a-configuration-file/Ada/read-a-configuration-file-2.ada +++ /dev/null @@ -1,24 +0,0 @@ -with Ada.Text_IO; -with Config; use Config; - -procedure Read_Config is - use Ada.Text_IO; - use Rosetta_Config; - -begin - New_Line; - Put_Line ("Reading Configuration File."); - Put_Line ("Fullname := " & Get (Key => FULLNAME)); - Put_Line ("Favorite Fruit := " & Get (Key => FAVOURITEFRUIT)); - Put_Line ("Other Family := " & Get (Key => OTHERFAMILY)); - if Has_Value (Key => NEEDSPEELING) then - Put_Line ("NEEDSPEELLING := " & Get (Key => NEEDSPEELING)); - else - Put_Line ("NEEDSPEELLING := True"); - end if; - if Has_Value (Key => SEEDSREMOVED) then - Put_Line ("SEEDSREMOVED := " & Get (Key => SEEDSREMOVED)); - else - Put_Line ("SEEDSREMOVED := True"); - end if; -end Read_Config; diff --git a/Task/Read-a-configuration-file/Ada/read-a-configuration-file.ada b/Task/Read-a-configuration-file/Ada/read-a-configuration-file.ada new file mode 100644 index 0000000000..68d8cbf670 --- /dev/null +++ b/Task/Read-a-configuration-file/Ada/read-a-configuration-file.ada @@ -0,0 +1,17 @@ +with Config; use Config; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Rosetta_Read_Cfg is + cfg: Configuration:= Init("rosetta_read.cfg", Case_Sensitive => False, Variable_Terminator => ' '); + fullname : String := cfg.Value_Of("*", "fullname"); + favouritefruit : String := cfg.Value_Of("*", "favouritefruit"); + needspeeling : Boolean := cfg.Is_Set("*", "needspeeling"); + seedsremoved : Boolean := cfg.Is_Set("*", "seedsremoved"); + otherfamily : String := cfg.Value_Of("*", "otherfamily"); +begin + Put_Line("fullname = " & fullname); + Put_Line("favouritefruit = " & favouritefruit); + Put_Line("needspeeling = " & Boolean'Image(needspeeling)); + Put_Line("seedsremoved = " & Boolean'Image(seedsremoved)); + Put_Line("otherfamily = " & otherfamily); +end; diff --git a/Task/Read-a-configuration-file/Aime/read-a-configuration-file.aime b/Task/Read-a-configuration-file/Aime/read-a-configuration-file.aime new file mode 100644 index 0000000000..c77973a49f --- /dev/null +++ b/Task/Read-a-configuration-file/Aime/read-a-configuration-file.aime @@ -0,0 +1,65 @@ +record r, s; +integer c; +file f; +list l; +text an, d, k; + +an = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + +f_affix(f, "tmp/config"); + +while ((c = f_peek(f)) ^ -1) { + integer removed; + + f_side(f, " \t\r"); + c = f_peek(f); + removed = c == ';'; + if (removed) { + f_pick(f); + f_side(f, " \t\r"); + c = f_peek(f); + } + c = index(an, c); + if (-1 < c && c < 52) { + f_near(f, an, k); + if (removed) { + r[k] = "false"; + } else { + data b; + + f_side(f, " \t\r"); + if (f_peek(f) == '=') { + f_pick(f); + f_side(f, " \t\r"); + } + f_ever(f, ",#\n", d); + b = d; + bb_drop(b, " \r\t"); + d = b_string(b); + if (f_peek(f) != ',') { + r[k] = length(d) ? d : "true"; + } else { + f_news(f, l, 0, 0, ","); + lf_push(l, d); + for (c, d in l) { + b = d; + bb_drop(b, " \r\t"); + bf_drop(b, " \r\t"); + l[c] = b_string(b); + } + r_put(s, k, l); + f_seek(f, -1, SEEK_CURRENT); + } + } + } + + f_slip(f); +} + +r_wcall(r, o_, 0, 2, ": ", "\n"); + +for (k, l in s) { + o_(k, ": "); + l_ucall(l, o_, 0, ", "); + o_("\n"); +} diff --git a/Task/Read-a-configuration-file/Gambas/read-a-configuration-file.gambas b/Task/Read-a-configuration-file/Gambas/read-a-configuration-file.gambas new file mode 100644 index 0000000000..f0301dcce1 --- /dev/null +++ b/Task/Read-a-configuration-file/Gambas/read-a-configuration-file.gambas @@ -0,0 +1,16 @@ +Public Sub Form_Open() +Dim fullname As String = Settings["fullname", "Foo Barber"] 'If fullname is empty then use the default "Foo Barber" +Dim favouritefruit As String = Settings["favouritefruit", "banana"] +Dim needspeeling As String = Settings["needspeling", True] +Dim seedsremoved As String = Settings["seedsremoved", False] +Dim otherfamily As String[] = Settings["otherfamily", ["Rhu Barber", "Harry Barber"]] + +Print fullname + +'To save +Settings["fullname"] = "John Smith" +fullname = Settings["fullname"] + +Print fullname + +End diff --git a/Task/Read-a-configuration-file/Jq/read-a-configuration-file.jq b/Task/Read-a-configuration-file/Jq/read-a-configuration-file.jq new file mode 100644 index 0000000000..c3855c51ce --- /dev/null +++ b/Task/Read-a-configuration-file/Jq/read-a-configuration-file.jq @@ -0,0 +1,22 @@ +def parse: + + def uc: .name | ascii_upcase; + + def parse_boolean: + capture( "(?^[^ ] *$)" ) + | { (uc) : true }; + + def parse_var_value: + capture( "(?^[^ ]+)[ =] *(?[^,]+ *$)" ) + | { (uc) : .value }; + + def parse_var_array: + capture( "(?^[^ ]+)[ =] *(?.*)" ) + | { (uc) : (.value | sub(" +$";"") | [splits(", *")]) }; + + reduce inputs as $i ({}; + if $i|length == 0 or test("^[#;]") then . + else . + ($i | ( parse_boolean // parse_var_value // parse_var_array // {} )) + end); + +parse diff --git a/Task/Read-a-configuration-file/Kotlin/read-a-configuration-file.kotlin b/Task/Read-a-configuration-file/Kotlin/read-a-configuration-file.kotlin index fae4fbc98e..11c1b406d9 100644 --- a/Task/Read-a-configuration-file/Kotlin/read-a-configuration-file.kotlin +++ b/Task/Read-a-configuration-file/Kotlin/read-a-configuration-file.kotlin @@ -1,38 +1,37 @@ +import java.nio.charset.StandardCharsets +import java.nio.file.Files +import java.nio.file.Paths + data class Configuration(val map: Map) { - val fullName: String by Delegates.mapVal(map) - val favoriteFruit: String by Delegates.mapVal(map) - val needsPeeling: Boolean by Delegates.mapVal(map) - val otherFamily: List by Delegates.mapVal(map) + val fullName: String by map + val favoriteFruit: String by map + val needsPeeling: Boolean by map + val otherFamily: List by map } fun main(args: Array) { - val configurationPath = Paths.get(args[0])!! + val lines = Files.readAllLines(Paths.get("src/configuration.txt"), StandardCharsets.UTF_8) + val keyValuePairs = lines.map{ it.trim() } + .filterNot { it.isEmpty() } + .filterNot(::commentedOut) + .map(::toKeyValuePair) - val configurables = Files.readAllLines(configurationPath, StandardCharsets.UTF_8) - .map { it.trim() } - .filterNot { it.isEmpty() } - .filterNot(::commentedOut) - .map(::toKeyValuePairs) - - val configurationMap: MutableMap = hashMapOf("needsPeeling" to false) - for (configurable in configurables) { - val (key, value) = configurable + val configurationMap = hashMapOf("needsPeeling" to false) + for (pair in keyValuePairs) { + val (key, value) = pair when (key) { "FULLNAME" -> configurationMap.put("fullName", value) "FAVOURITEFRUIT" -> configurationMap.put("favoriteFruit", value) "NEEDSPEELING" -> configurationMap.put("needsPeeling", true) "OTHERFAMILY" -> configurationMap.put("otherFamily", value.split(" , ").map { it.trim() }) - else -> println("Encountered unexpected key ${key}=${value}") + else -> println("Encountered unexpected key $key=$value") } } - - val configuration = Configuration(configurationMap) + println(Configuration(configurationMap)) } -private fun commentedOut(line: String): Boolean = (line.indexOf("#") == 0 || line.indexOf(";") == 0) +private fun commentedOut(line: String) = line.startsWith("#") || line.startsWith(";") -private fun toKeyValuePairs(line: String): Pair { - return line.split(" ", 2).let { - Pair(it[0], if (it.size == 1) "" else it[1]) - } +private fun toKeyValuePair(line: String) = line.split(Regex(" "), 2).let { + Pair(it[0], if (it.size == 1) "" else it[1]) } diff --git a/Task/Read-a-configuration-file/REXX/read-a-configuration-file-2.rexx b/Task/Read-a-configuration-file/OoRexx/read-a-configuration-file.rexx similarity index 100% rename from Task/Read-a-configuration-file/REXX/read-a-configuration-file-2.rexx rename to Task/Read-a-configuration-file/OoRexx/read-a-configuration-file.rexx diff --git a/Task/Read-a-configuration-file/Phix/read-a-configuration-file.phix b/Task/Read-a-configuration-file/Phix/read-a-configuration-file.phix new file mode 100644 index 0000000000..45b1e283c9 --- /dev/null +++ b/Task/Read-a-configuration-file/Phix/read-a-configuration-file.phix @@ -0,0 +1,31 @@ +integer fn = open("RCTEST.INI","r") +sequence lines = get_text(fn,GT_LF_STRIPPED) +close(fn) +constant dini = new_dict() +for i=1 to length(lines) do + string li = trim(lines[i]) + if length(li) + and not find(li[1],"#;") then + integer k = find(' ',li) + if k!=0 then + string rest = li[k+1..$] + li = li[1..k-1] -- (may want upper()) + if find(',',rest) then + sequence a = split(rest,',') + for j=1 to length(a) do a[j]=trim(a[j]) end for + putd(li,a,dini) + else + putd(li,rest,dini) + end if + else + putd(li,1,dini) -- "" + end if + end if +end for + +function visitor(object key, object data, object /*user_data*/) + ?{key,data} + return 1 +end function +traverse_dict(routine_id("visitor"),0,dini) +?getd("FAVOURITEFRUIT",dini) diff --git a/Task/Read-a-configuration-file/PicoLisp/read-a-configuration-file-1.l b/Task/Read-a-configuration-file/PicoLisp/read-a-configuration-file-1.l deleted file mode 100644 index b1c7dfb9d2..0000000000 --- a/Task/Read-a-configuration-file/PicoLisp/read-a-configuration-file-1.l +++ /dev/null @@ -1,5 +0,0 @@ -(de rdConf (File) - (pipe (in File (while (echo "#" ";") (till "^J"))) - (while (read) - (skip) - (set @ (or (line T) T)) ) ) ) diff --git a/Task/Read-a-configuration-file/PicoLisp/read-a-configuration-file-2.l b/Task/Read-a-configuration-file/PicoLisp/read-a-configuration-file-2.l deleted file mode 100644 index 406723f73c..0000000000 --- a/Task/Read-a-configuration-file/PicoLisp/read-a-configuration-file-2.l +++ /dev/null @@ -1,2 +0,0 @@ -(off FULLNAME FAVOURITEFRUIT NEEDSPEELING SEEDSREMOVED OTHERFAMILY) -(rdConf "conf.txt") diff --git a/Task/Read-a-configuration-file/Protium/read-a-configuration-file.protium b/Task/Read-a-configuration-file/Protium/read-a-configuration-file.protium deleted file mode 100644 index c249509410..0000000000 --- a/Task/Read-a-configuration-file/Protium/read-a-configuration-file.protium +++ /dev/null @@ -1,27 +0,0 @@ -<@ DEFUDRLIT>__ReadConfigurationFile| - <@ LETSCPPNTPARSRC>Data|1<@ OMT> read file into locally scope variable - <@ LETCGDLSTLLOSCP>List|Data<@ OMT> split Data into a list of lines - <@ OMT> Remove comment lines, and blank lines - <@ ACTOVRBEFLSTLIT>List|; - <@ ACTOVRBEFLSTLIT>List|# - <@ ACTRMELST>List - <@ OMT> Iterate over the lines of the list - <@ ITEENULSTLit>List| - <@ LETVARUPTVALLSTLIT>key|...| - <@ LETVARAFTVALLSTLIT>val|...| - <@ OMT> test for an empty key (in the case of a boolean) - <@ TSTVARLIT>key| - <@ IFE><@ LETPNTVARVARLIT>val|__True - <@ ELS> - <@ TSTGT0ATBVARLIT>val|, - <@ IFE><@ ACTEXEEMMCAP><&prot; LETCNDLSTLITLIT>&key;&pipe;&val;&pipe;, - <@ ELS><@ LETPNTVARVARVAR>key|val - - - - -<@ ACTUDRLIT>__ReadConfigurationFile|c:\rosetta.config -<@ SAYVAR>FAVOURITEFRUIT -<@ SAYVAR>FULLNAME -<@ SAYVAR>NEEDSPEELING -<@ SAYDMPLST>OTHERFAMILY diff --git a/Task/Read-a-configuration-file/REXX/read-a-configuration-file-1.rexx b/Task/Read-a-configuration-file/REXX/read-a-configuration-file-1.rexx deleted file mode 100644 index 0b1c588d62..0000000000 --- a/Task/Read-a-configuration-file/REXX/read-a-configuration-file-1.rexx +++ /dev/null @@ -1,47 +0,0 @@ -/*REXX program to read a config file and assign VARs as found within. */ -signal on syntax; signal on novalue /*handle REXX program errors. */ -parse arg cFID _ . /*cFID = config file to be read. */ -if cFID=='' then cFID='CONFIG.DAT' /*Not specified? Use the default*/ -bad= /*this will contain all bad VARs.*/ -varList= /*this will contain all the VARs.*/ -maxLenV=0; blanks=0; hashes=0; semics=0; badVar=0 /*zero 'em.*/ - - do j=0 while lines(cFID)\==0 /*J count's the file's lines. */ - txt=strip(linein(cFID)) /*read a line (record) from file,*/ - /*& strip leading/trailing blanks*/ - if txt ='' then do; blanks=blanks+1; iterate; end - if left(txt,1)=='#' then do; hashes=hashes+1; iterate; end - if left(txt,1)==';' then do; semics=semics+1; iterate; end - eqS=pos('=',txt) /*can't use the TRANSLATE bif. */ - if eqS\==0 then txt=overlay(' ',txt,eqS) /*replace 1st '=' with blank*/ - parse var txt xxx value; upper xxx /*get the variableName and value.*/ - value=strip(value) /*strip leading & trailing blanks*/ - varList=varList xxx /*add it to the list of vARiables*/ - if value='' then value='true' /*if no value, then use "true". */ - if symbol(xxx)=='BAD' then do /*can REXX use the variable name?*/ - badVar=badVar+1; bad=bad xxx; iterate - end - call value xxx,value /*now, use VALUE to set the var. */ - maxLenV=max(maxLenV,length(value)) /*maxLen of varNames, pretty disp*/ - end /*j*/ - -vars=words(varList) - say #(j) 'record's(j) "were read from file: " cFID -if blanks\==0 then say #(blanks) 'blank record's(blanks) "were read." -if hashes\==0 then say #(hashes) 'record's(hashes) "ignored that began with a # (hash)." -if semics\==0 then say #(semics) 'record's(semics) "ignored that began with a ; (semicolon)." -if badVar\==0 then say #(badVar) 'bad variable name's(badVar) 'detected:' bad -say; say 'The list of' vars "variable"s(vars) 'and' s(vars,'their',"it's") "value"s(vars) 'follows:'; say - - do k=1 for vars - v=word(varList,k) - say right(v,maxLenV) '=' value(v) - end /*k*/ -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────error handling subroutines and others.─*/ -s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) -#: return right(arg(1),length(j)+11) /*right justify a number +indent*/ -err: say; say; say center(' error! ', max(40, linesize()%2), "*"); say - do j=1 for arg(); say arg(j); say; end; say; exit 13 -novalue: syntax: call err 'REXX program' condition('C') "error",, - condition('D'),'REXX source statement (line' sigl"):",sourceline(sigl) diff --git a/Task/Read-a-configuration-file/Zkl/read-a-configuration-file-1.zkl b/Task/Read-a-configuration-file/Zkl/read-a-configuration-file-1.zkl new file mode 100644 index 0000000000..ebb3f5d28f --- /dev/null +++ b/Task/Read-a-configuration-file/Zkl/read-a-configuration-file-1.zkl @@ -0,0 +1,19 @@ +fcn readConfigFile(config){ //--> read only dictionary + conf:=Dictionary(); + foreach line in (config){ + line=line.strip(); + if (not line or "#"==line[0] or ";"==line[0]) continue; + line=line.replace("\t"," "); + n:=line.find(" "); + if (Void==n) conf[line.toLower()]=True; // eg NEEDSPEELING + else{ + key:=line[0,n].toLower(); line=line[n,*]; + n=line.find(","); + if (Void!=n) conf[key]=line.split(",").apply("strip").filter(); + else conf[key]=line; + } + } + conf.makeReadOnly(); +} + +conf:=readConfigFile(File("foo.conf")); diff --git a/Task/Read-a-configuration-file/Zkl/read-a-configuration-file-2.zkl b/Task/Read-a-configuration-file/Zkl/read-a-configuration-file-2.zkl new file mode 100644 index 0000000000..dce95bfcf6 --- /dev/null +++ b/Task/Read-a-configuration-file/Zkl/read-a-configuration-file-2.zkl @@ -0,0 +1,2 @@ +foreach k,v in (conf){ println(k," : ",v) } +println("Value of seedsremoved = ",conf.find("seedsremoved",False)); diff --git a/Task/Read-a-configuration-file/Zkl/read-a-configuration-file-3.zkl b/Task/Read-a-configuration-file/Zkl/read-a-configuration-file-3.zkl new file mode 100644 index 0000000000..b8a07dab09 --- /dev/null +++ b/Task/Read-a-configuration-file/Zkl/read-a-configuration-file-3.zkl @@ -0,0 +1,4 @@ +var needspeeling,otherfamily,favouritefruit,fullname,seedsremoved; +foreach k,v in (conf){ try{ setVar(k,v) }catch{} }; +foreach k,v in (vars){ println(k," : ",v) } +println("Value of seedsremoved = ",seedsremoved); diff --git a/Task/Read-a-file-line-by-line/Astro/read-a-file-line-by-line.astro b/Task/Read-a-file-line-by-line/Astro/read-a-file-line-by-line.astro new file mode 100644 index 0000000000..be1ea06913 --- /dev/null +++ b/Task/Read-a-file-line-by-line/Astro/read-a-file-line-by-line.astro @@ -0,0 +1,2 @@ +try f <- open('foobar.txt'): + print line for line in f diff --git a/Task/Read-a-file-line-by-line/BASIC/read-a-file-line-by-line-1.basic b/Task/Read-a-file-line-by-line/BASIC/read-a-file-line-by-line-1.basic index c783f862a8..6a3d900e8b 100644 --- a/Task/Read-a-file-line-by-line/BASIC/read-a-file-line-by-line-1.basic +++ b/Task/Read-a-file-line-by-line/BASIC/read-a-file-line-by-line-1.basic @@ -1,5 +1,10 @@ -10 OPENIN"foo.txt" -20 WHILE NOT EOF -30 LINE INPUT#9,i$ -40 PRINT i$ -50 WEND +' Read a file line by line +filename$ = "readlines.bac" +OPEN filename$ FOR READING AS fh +READLN fl$ FROM fh +WHILE ISFALSE(ENDFILE(fh)) + INCR lines + READLN fl$ FROM fh +WEND +PRINT lines, " lines in ", filename$ +CLOSE FILE fh diff --git a/Task/Read-a-file-line-by-line/BASIC/read-a-file-line-by-line-2.basic b/Task/Read-a-file-line-by-line/BASIC/read-a-file-line-by-line-2.basic index 93090d2f18..c783f862a8 100644 --- a/Task/Read-a-file-line-by-line/BASIC/read-a-file-line-by-line-2.basic +++ b/Task/Read-a-file-line-by-line/BASIC/read-a-file-line-by-line-2.basic @@ -1,7 +1,5 @@ -10 REM open my file for input -20 OPEN #4;"m";1;"MYFILE": REM stream 4 is the first available for general purpose -30 INPUT #4; LINE a$: REM a$ will hold our line from the file -40 REM because we do not know how many lines are in the file, we need an error trap -50 REM to gracefully exit when the file is read. (omitted from this example) -60 REM to prevent an error at end of file, place a handler here -100 GOTO 30 +10 OPENIN"foo.txt" +20 WHILE NOT EOF +30 LINE INPUT#9,i$ +40 PRINT i$ +50 WEND diff --git a/Task/Read-a-file-line-by-line/BASIC/read-a-file-line-by-line-3.basic b/Task/Read-a-file-line-by-line/BASIC/read-a-file-line-by-line-3.basic new file mode 100644 index 0000000000..93090d2f18 --- /dev/null +++ b/Task/Read-a-file-line-by-line/BASIC/read-a-file-line-by-line-3.basic @@ -0,0 +1,7 @@ +10 REM open my file for input +20 OPEN #4;"m";1;"MYFILE": REM stream 4 is the first available for general purpose +30 INPUT #4; LINE a$: REM a$ will hold our line from the file +40 REM because we do not know how many lines are in the file, we need an error trap +50 REM to gracefully exit when the file is read. (omitted from this example) +60 REM to prevent an error at end of file, place a handler here +100 GOTO 30 diff --git a/Task/Read-a-file-line-by-line/Batch-File/read-a-file-line-by-line.bat b/Task/Read-a-file-line-by-line/Batch-File/read-a-file-line-by-line.bat index 10752400df..c81f246d1d 100644 --- a/Task/Read-a-file-line-by-line/Batch-File/read-a-file-line-by-line.bat +++ b/Task/Read-a-file-line-by-line/Batch-File/read-a-file-line-by-line.bat @@ -1,2 +1,9 @@ @echo off -for /f "tokens=* delims=" %%i in (file.txt) do echo %%i +rem delayed expansion must be disabled before the FOR command. +setlocal disabledelayedexpansion +for /f "tokens=1* delims=]" %%A in ('type "File.txt"^|find /v /n ""') do ( + set var=%%B + setlocal enabledelayedexpansion + echo(!var! + endlocal +) diff --git a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c index d7b1e5daab..4e9dd77577 100644 --- a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c +++ b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c @@ -1,14 +1,25 @@ +// From manpage for "getline" + #include #include -int main (void) + +int main(void) { - char buf[256]; - while (fgets (buf, sizeof(buf), stdin)) { - printf("line: %s", buf); - } - if (ferror(stdin)) { - fprintf(stderr,"Oops, error reading stdin\n"); - abort(); - } - return 0; + FILE *stream; + char *line = NULL; + size_t len = 0; + ssize_t read; + + stream = fopen("file.txt", "r"); + if (stream == NULL) + exit(EXIT_FAILURE); + + while ((read = getline(&line, &len, stream)) != -1) { + printf("Retrieved line of length %zu :\n", read); + printf("%s", line); + } + + free(line); + fclose(stream); + exit(EXIT_SUCCESS); } diff --git a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-2.c b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-2.c index c65bf46270..c6c2bacffa 100644 --- a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-2.c +++ b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-2.c @@ -1,35 +1,75 @@ -#include /* err */ -#include /* fopen, fgetln, fputs, fwrite */ +#include +#include +#include +#include +#include +#include +#include +#include -/* - * Read a file line by line. - * http://rosettacode.org/wiki/Read_a_file_line_by_line - */ -int -main() +int read_lines(const char * fname, int (*call_back)(const char*, const char*)) { - FILE *f; - size_t len; - char *line; + int fd = open(fname, O_RDONLY); + struct stat fs; + char *buf, *buf_end; + char *begin, *end, c; - f = fopen("foobar.txt", "r"); - if (f == NULL) - err(1, "foobar.txt"); + if (fd == -1) { + err(1, "open: %s", fname); + return 0; + } - /* - * This loop reads each line. - * Remember that line is not a C string. - * There is no terminating '\0'. - */ - while (line = fgetln(f, &len)) { - /* - * Do something with line. - */ - fputs("LINE: ", stdout); - fwrite(line, len, 1, stdout); - } - if (!feof(f)) - err(1, "fgetln"); + if (fstat(fd, &fs) == -1) { + err(1, "stat: %s", fname); + return 0; + } - return 0; + /* fs.st_size could have been 0 actually */ + buf = mmap(0, fs.st_size, PROT_READ, MAP_SHARED, fd, 0); + if (buf == (void*) -1) { + err(1, "mmap: %s", fname); + close(fd); + return 0; + } + + buf_end = buf + fs.st_size; + + begin = end = buf; + while (1) { + if (! (*end == '\r' || *end == '\n')) { + if (++end < buf_end) continue; + } else if (1 + end < buf_end) { + /* see if we got "\r\n" or "\n\r" here */ + c = *(1 + end); + if ( (c == '\r' || c == '\n') && c != *end) + ++end; + } + + /* call the call back and check error indication. Announce + error here, because we didn't tell call_back the file name */ + if (! call_back(begin, end)) { + err(1, "[callback] %s", fname); + break; + } + + if ((begin = ++end) >= buf_end) + break; + } + + munmap(buf, fs.st_size); + close(fd); + return 1; +} + +int print_line(const char* begin, const char* end) +{ + if (write(fileno(stdout), begin, end - begin + 1) == -1) { + return 0; + } + return 1; +} + +int main() +{ + return read_lines("test.ps", print_line) ? 0 : 1; } diff --git a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-3.c b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-3.c deleted file mode 100644 index 6e36638c56..0000000000 --- a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-3.c +++ /dev/null @@ -1,123 +0,0 @@ -#include /* exit, malloc, realloc, free */ -#include /* fopen, fgetc, fputs, fwrite */ - -struct line_reader { - /* All members are private. */ - FILE *f; - char *buf; - size_t siz; -}; - -/* - * Initializes a line reader _lr_ for the stream _f_. - */ -void -lr_init(struct line_reader *lr, FILE *f) -{ - lr->f = f; - lr->buf = NULL; - lr->siz = 0; -} - -/* - * Reads the next line. If successful, returns a pointer to the line, - * and sets *len to the number of characters, at least 1. The result is - * _not_ a C string; it has no terminating '\0'. The returned pointer - * remains valid until the next call to next_line() or lr_free() with - * the same _lr_. - * - * next_line() returns NULL at end of file, or if there is an error (on - * the stream, or with memory allocation). - */ -char * -next_line(struct line_reader *lr, size_t *len) -{ - size_t newsiz; - int c; - char *newbuf; - - *len = 0; /* Start with empty line. */ - for (;;) { - c = fgetc(lr->f); /* Read next character. */ - if (ferror(lr->f)) - return NULL; - - if (c == EOF) { - /* - * End of file is also end of last line, - ` * unless this last line would be empty. - */ - if (*len == 0) - return NULL; - else - return lr->buf; - } else { - /* Append c to the buffer. */ - if (*len == lr->siz) { - /* Need a bigger buffer! */ - newsiz = lr->siz + 4096; - newbuf = realloc(lr->buf, newsiz); - if (newbuf == NULL) - return NULL; - lr->buf = newbuf; - lr->siz = newsiz; - } - lr->buf[(*len)++] = c; - - /* '\n' is end of line. */ - if (c == '\n') - return lr->buf; - } - } -} - -/* - * Frees internal memory used by _lr_. - */ -void -lr_free(struct line_reader *lr) -{ - free(lr->buf); - lr->buf = NULL; - lr->siz = 0; -} - -/* - * Read a file line by line. - * http://rosettacode.org/wiki/Read_a_file_line_by_line - */ -int -main() -{ - struct line_reader lr; - FILE *f; - size_t len; - char *line; - - f = fopen("foobar.txt", "r"); - if (f == NULL) { - perror("foobar.txt"); - exit(1); - } - - /* - * This loop reads each line. - * Remember that line is not a C string. - * There is no terminating '\0'. - */ - lr_init(&lr, f); - while (line = next_line(&lr, &len)) { - /* - * Do something with line. - */ - fputs("LINE: ", stdout); - fwrite(line, len, 1, stdout); - } - if (!feof(f)) { - perror("next_line"); - exit(1); - } - lr_free(&lr); - - return 0; -} diff --git a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-4.c b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-4.c deleted file mode 100644 index c6c2bacffa..0000000000 --- a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-4.c +++ /dev/null @@ -1,75 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -int read_lines(const char * fname, int (*call_back)(const char*, const char*)) -{ - int fd = open(fname, O_RDONLY); - struct stat fs; - char *buf, *buf_end; - char *begin, *end, c; - - if (fd == -1) { - err(1, "open: %s", fname); - return 0; - } - - if (fstat(fd, &fs) == -1) { - err(1, "stat: %s", fname); - return 0; - } - - /* fs.st_size could have been 0 actually */ - buf = mmap(0, fs.st_size, PROT_READ, MAP_SHARED, fd, 0); - if (buf == (void*) -1) { - err(1, "mmap: %s", fname); - close(fd); - return 0; - } - - buf_end = buf + fs.st_size; - - begin = end = buf; - while (1) { - if (! (*end == '\r' || *end == '\n')) { - if (++end < buf_end) continue; - } else if (1 + end < buf_end) { - /* see if we got "\r\n" or "\n\r" here */ - c = *(1 + end); - if ( (c == '\r' || c == '\n') && c != *end) - ++end; - } - - /* call the call back and check error indication. Announce - error here, because we didn't tell call_back the file name */ - if (! call_back(begin, end)) { - err(1, "[callback] %s", fname); - break; - } - - if ((begin = ++end) >= buf_end) - break; - } - - munmap(buf, fs.st_size); - close(fd); - return 1; -} - -int print_line(const char* begin, const char* end) -{ - if (write(fileno(stdout), begin, end - begin + 1) == -1) { - return 0; - } - return 1; -} - -int main() -{ - return read_lines("test.ps", print_line) ? 0 : 1; -} diff --git a/Task/Read-a-file-line-by-line/Elena/read-a-file-line-by-line.elena b/Task/Read-a-file-line-by-line/Elena/read-a-file-line-by-line.elena index 9f9871c8e9..e575dff333 100644 --- a/Task/Read-a-file-line-by-line/Elena/read-a-file-line-by-line.elena +++ b/Task/Read-a-file-line-by-line/Elena/read-a-file-line-by-line.elena @@ -1,9 +1,8 @@ -#import system. -#import system'io. -#import extensions. -#import extensions'routines. +import system'io. +import extensions. +import extensions'routines. -#symbol program = +program = [ - "file.txt" file_path run &eachLine:printingLn. + File new:"file.txt"; forEachLine:printingLn. ]. diff --git a/Task/Read-a-file-line-by-line/Gambas/read-a-file-line-by-line.gambas b/Task/Read-a-file-line-by-line/Gambas/read-a-file-line-by-line.gambas new file mode 100644 index 0000000000..7edc0ce16b --- /dev/null +++ b/Task/Read-a-file-line-by-line/Gambas/read-a-file-line-by-line.gambas @@ -0,0 +1,12 @@ +Public Sub Main() +Dim hFile As File +Dim sLine As String + +hFile = Open "../InputText.txt" For Input + +While Not Eof(hFile) + Line Input #hFile, sLine + Print sLine +Wend + +End diff --git a/Task/Read-a-file-line-by-line/jq/read-a-file-line-by-line-1.jq b/Task/Read-a-file-line-by-line/Jq/read-a-file-line-by-line-1.jq similarity index 100% rename from Task/Read-a-file-line-by-line/jq/read-a-file-line-by-line-1.jq rename to Task/Read-a-file-line-by-line/Jq/read-a-file-line-by-line-1.jq diff --git a/Task/Read-a-file-line-by-line/jq/read-a-file-line-by-line-2.jq b/Task/Read-a-file-line-by-line/Jq/read-a-file-line-by-line-2.jq similarity index 100% rename from Task/Read-a-file-line-by-line/jq/read-a-file-line-by-line-2.jq rename to Task/Read-a-file-line-by-line/Jq/read-a-file-line-by-line-2.jq diff --git a/Task/Read-a-file-line-by-line/Kotlin/read-a-file-line-by-line.kotlin b/Task/Read-a-file-line-by-line/Kotlin/read-a-file-line-by-line.kotlin new file mode 100644 index 0000000000..0d2c23df5a --- /dev/null +++ b/Task/Read-a-file-line-by-line/Kotlin/read-a-file-line-by-line.kotlin @@ -0,0 +1,7 @@ +// version 1.1.2 + +import java.io.File + +fun main(args: Array) { + File("input.txt").forEachLine { println(it) } +} diff --git a/Task/Read-a-file-line-by-line/Lua/read-a-file-line-by-line.lua b/Task/Read-a-file-line-by-line/Lua/read-a-file-line-by-line-1.lua similarity index 100% rename from Task/Read-a-file-line-by-line/Lua/read-a-file-line-by-line.lua rename to Task/Read-a-file-line-by-line/Lua/read-a-file-line-by-line-1.lua diff --git a/Task/Read-a-file-line-by-line/Lua/read-a-file-line-by-line-2.lua b/Task/Read-a-file-line-by-line/Lua/read-a-file-line-by-line-2.lua new file mode 100644 index 0000000000..68dc9a3888 --- /dev/null +++ b/Task/Read-a-file-line-by-line/Lua/read-a-file-line-by-line-2.lua @@ -0,0 +1,3 @@ +for line in io.lines("input.txt") do + print(line) +end diff --git a/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-3.rexx b/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-3.rexx index 2570873c72..3858910e6e 100644 --- a/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-3.rexx +++ b/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-3.rexx @@ -1,15 +1,14 @@ -/*REXX program reads and displays (with count) a file, 1 line at a time.*/ -parse arg fileID .; if fileID=='' then exit /*No fileID? Then stop.*/ -say 'displaying file: ' fileID /*show what file is being shown. */ -call linein fileID,1,0 /*see comment in the section hdr.*/ -say /* [↓] show the file's contents.*/ - do #=1 while lines(fileID)\==0 /*loop whilst there are records. */ - x=linein(fileID); xLen=length(x) /*read a record; get its length. */ - say /*show a blank for peruseability.*/ - say 'record#=' # " length=" xLen /*show the record number & length*/ - say x /*show the content of the record.*/ - end /*#*/ +/*REXX program reads and displays (with a count) a file, one line at a time. */ +parse arg fID .; if fID=='' then exit /*Was no fileID specified? Then quit. */ +say center(' displaying file: ' fID" ", 79, '═') /*show the name of the file being read.*/ +call linein fID, 1, 0 /*see the comment in the section header*/ +say /* [↓] show a file's contents (lines).*/ + do #=1 while lines(fID)\==0; y=linein(fID) /*loop whilst there are lines in file. */ + say /*show a blank line for peruseability. */ + say 'record#=' # " length=" length(y) /*show the record number and the length*/ + say y /*show the content of the line (record)*/ + end /*#*/ say -say 'file ' fileID " has " #-1 ' records.' /*record count summary.*/ -call lineout fileID /*close input file (most REXXes).*/ - /*stick a fork in it, we're done.*/ +say 'file ' fID " has " #-1 ' records.' /*display the record count summary. */ +call lineout fID /*close the input file (most REXXes). */ + /*stick a fork in it, we're all done. */ diff --git a/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-4.rexx b/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-4.rexx index 13e6ad18ab..2c1978cde0 100644 --- a/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-4.rexx +++ b/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-4.rexx @@ -1,11 +1,12 @@ /* Also works with Regina if you state OPTIONS AREXX_BIFS ; OPTIONS AREXX_SEMANTICS */ filename='file.txt' contents='' -IF Open(filehandle,filename,'READ') THEN DO UNTIL EOF(filehandle) +IF Open(filehandle,filename,'READ') +THEN DO UNTIL EOF(filehandle) line=ReadLn(filehandle) SAY line contents=contents || line || '0a'x END ELSE EXIT 20 -CALL Close(filehandle) +CALL Close filehandle EXIT 0 diff --git a/Task/Read-a-file-line-by-line/SPL/read-a-file-line-by-line.spl b/Task/Read-a-file-line-by-line/SPL/read-a-file-line-by-line.spl new file mode 100644 index 0000000000..2344b07b04 --- /dev/null +++ b/Task/Read-a-file-line-by-line/SPL/read-a-file-line-by-line.spl @@ -0,0 +1,4 @@ +f = "file.txt" +> !#.eof(f) + #.output(#.readline(f)) +< diff --git a/Task/Read-a-file-line-by-line/Zkl/read-a-file-line-by-line-1.zkl b/Task/Read-a-file-line-by-line/Zkl/read-a-file-line-by-line-1.zkl new file mode 100644 index 0000000000..6993659cc8 --- /dev/null +++ b/Task/Read-a-file-line-by-line/Zkl/read-a-file-line-by-line-1.zkl @@ -0,0 +1 @@ +foreach line in (File("foo.zkl")){print(line)} diff --git a/Task/Read-a-file-line-by-line/Zkl/read-a-file-line-by-line-2.zkl b/Task/Read-a-file-line-by-line/Zkl/read-a-file-line-by-line-2.zkl new file mode 100644 index 0000000000..24bc1ba1df --- /dev/null +++ b/Task/Read-a-file-line-by-line/Zkl/read-a-file-line-by-line-2.zkl @@ -0,0 +1 @@ +File("foo.zkl").pump(Console.print) diff --git a/Task/Read-a-file-line-by-line/Zkl/read-a-file-line-by-line-3.zkl b/Task/Read-a-file-line-by-line/Zkl/read-a-file-line-by-line-3.zkl new file mode 100644 index 0000000000..88c586de28 --- /dev/null +++ b/Task/Read-a-file-line-by-line/Zkl/read-a-file-line-by-line-3.zkl @@ -0,0 +1,6 @@ +Utils.zipWith(False,fcn(a,b){"%d: %s".fmt(a,b).print()}, + [0..],File("foo.zkl","r")) +--> +0: var R; n:=GarbageMan.gcCount; +1: ref := GarbageMan.WeakRef(String("the","quick brown fox")); +... diff --git a/Task/Read-a-specific-line-from-a-file/Batch-File/read-a-specific-line-from-a-file.bat b/Task/Read-a-specific-line-from-a-file/Batch-File/read-a-specific-line-from-a-file.bat new file mode 100644 index 0000000000..2cd050c6f2 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Batch-File/read-a-specific-line-from-a-file.bat @@ -0,0 +1,9 @@ +@echo off + +for /f "skip=6 tokens=*" %%i in (file.txt) do ( + set line7=%%i + goto break +) +:break +echo Line 7 is: %line7% +pause>nul diff --git a/Task/Read-a-specific-line-from-a-file/jq/read-a-specific-line-from-a-file-1.jq b/Task/Read-a-specific-line-from-a-file/Jq/read-a-specific-line-from-a-file-1.jq similarity index 100% rename from Task/Read-a-specific-line-from-a-file/jq/read-a-specific-line-from-a-file-1.jq rename to Task/Read-a-specific-line-from-a-file/Jq/read-a-specific-line-from-a-file-1.jq diff --git a/Task/Read-a-specific-line-from-a-file/jq/read-a-specific-line-from-a-file-2.jq b/Task/Read-a-specific-line-from-a-file/Jq/read-a-specific-line-from-a-file-2.jq similarity index 100% rename from Task/Read-a-specific-line-from-a-file/jq/read-a-specific-line-from-a-file-2.jq rename to Task/Read-a-specific-line-from-a-file/Jq/read-a-specific-line-from-a-file-2.jq diff --git a/Task/Read-a-specific-line-from-a-file/jq/read-a-specific-line-from-a-file-3.jq b/Task/Read-a-specific-line-from-a-file/Jq/read-a-specific-line-from-a-file-3.jq similarity index 100% rename from Task/Read-a-specific-line-from-a-file/jq/read-a-specific-line-from-a-file-3.jq rename to Task/Read-a-specific-line-from-a-file/Jq/read-a-specific-line-from-a-file-3.jq diff --git a/Task/Read-a-specific-line-from-a-file/Kotlin/read-a-specific-line-from-a-file.kotlin b/Task/Read-a-specific-line-from-a-file/Kotlin/read-a-specific-line-from-a-file.kotlin new file mode 100644 index 0000000000..cdfd1bea4f --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Kotlin/read-a-specific-line-from-a-file.kotlin @@ -0,0 +1,32 @@ +// version 1.1.2 + +import java.io.File + +fun main(args: Array) { + /* The following code reads the whole file into memory + and so should not be used for large files + which should instead be read line by line until the + desired line is reached */ + + val lines = File("input.txt").readLines() + if (lines.size < 7) + println("There are only ${lines.size} lines in the file") + else { + val line7 = lines[6].trim() + if (line7.isEmpty()) + println("The seventh line is empty") + else + println("The seventh line is : $line7") + } +} + +/* Note that 'input.txt' contains the eight lines: +Line 1 +Line 2 +Line 3 +Line 4 +Line 5 +Line 6 +Line 7 +Line 8 +*/ diff --git a/Task/Read-a-specific-line-from-a-file/Moonscript/read-a-specific-line-from-a-file.moon b/Task/Read-a-specific-line-from-a-file/Moonscript/read-a-specific-line-from-a-file.moon new file mode 100644 index 0000000000..3bbdf205a2 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Moonscript/read-a-specific-line-from-a-file.moon @@ -0,0 +1,5 @@ +iter = io.lines 'test.txt' +for i=0, 5 + error 'Not 7 lines in file' if not iter! + +print iter! diff --git a/Task/Read-a-specific-line-from-a-file/Phix/read-a-specific-line-from-a-file-1.phix b/Task/Read-a-specific-line-from-a-file/Phix/read-a-specific-line-from-a-file-1.phix new file mode 100644 index 0000000000..d581dadbcc --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Phix/read-a-specific-line-from-a-file-1.phix @@ -0,0 +1,8 @@ +integer fn = open("TEST.TXT","r") +sequence lines = get_text(fn,GT_LF_STRIPPED) +close(fn) +if length(lines)>=7 then + ?lines[7] +else + ?"no line 7" +end if diff --git a/Task/Read-a-specific-line-from-a-file/Phix/read-a-specific-line-from-a-file-2.phix b/Task/Read-a-specific-line-from-a-file/Phix/read-a-specific-line-from-a-file-2.phix new file mode 100644 index 0000000000..abea00f212 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Phix/read-a-specific-line-from-a-file-2.phix @@ -0,0 +1,6 @@ +integer fn = open("TEST.TXT","r") +for i=1 to 6 do + {} = gets(fn) +end for +?gets(fn) -- (shows -1 if past eof) +close(fn) diff --git a/Task/Read-a-specific-line-from-a-file/SPL/read-a-specific-line-from-a-file.spl b/Task/Read-a-specific-line-from-a-file/SPL/read-a-specific-line-from-a-file.spl new file mode 100644 index 0000000000..2db6210477 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/SPL/read-a-specific-line-from-a-file.spl @@ -0,0 +1,7 @@ +lines = #.readlines("test.txt") +#.output("Seventh line of text:") +? #.size(lines,1)<7 + #.output("is absent") +! + #.output(lines[7]) +. diff --git a/Task/Read-a-specific-line-from-a-file/Sed/read-a-specific-line-from-a-file-1.sed b/Task/Read-a-specific-line-from-a-file/Sed/read-a-specific-line-from-a-file-1.sed new file mode 100644 index 0000000000..81f97fbbc7 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Sed/read-a-specific-line-from-a-file-1.sed @@ -0,0 +1 @@ +sed -n 7p diff --git a/Task/Read-a-specific-line-from-a-file/Sed/read-a-specific-line-from-a-file-2.sed b/Task/Read-a-specific-line-from-a-file/Sed/read-a-specific-line-from-a-file-2.sed new file mode 100644 index 0000000000..75198dafc4 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Sed/read-a-specific-line-from-a-file-2.sed @@ -0,0 +1 @@ +sed -n '7{p;h;}; ${x;/^$/s/^/Error: no such line/p}' diff --git a/Task/Read-a-specific-line-from-a-file/Stata/read-a-specific-line-from-a-file-1.stata b/Task/Read-a-specific-line-from-a-file/Stata/read-a-specific-line-from-a-file-1.stata new file mode 100644 index 0000000000..8831c8d00a --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Stata/read-a-specific-line-from-a-file-1.stata @@ -0,0 +1,5 @@ +* Read rows 20 to 30 from somedata.dta +. use somedata in 20/30, clear + +* Read rows for which the variable x is positive +. use somedata if x>0, clear diff --git a/Task/Read-a-specific-line-from-a-file/Stata/read-a-specific-line-from-a-file-2.stata b/Task/Read-a-specific-line-from-a-file/Stata/read-a-specific-line-from-a-file-2.stata new file mode 100644 index 0000000000..b386d7012d --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Stata/read-a-specific-line-from-a-file-2.stata @@ -0,0 +1,4 @@ +capture use somedata in 7, clear +if _rc { + display "Too few lines" +} diff --git a/Task/Read-a-specific-line-from-a-file/Zkl/read-a-specific-line-from-a-file-1.zkl b/Task/Read-a-specific-line-from-a-file/Zkl/read-a-specific-line-from-a-file-1.zkl new file mode 100644 index 0000000000..d18b63e802 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Zkl/read-a-specific-line-from-a-file-1.zkl @@ -0,0 +1 @@ +reg line; do(7){line=File.stdin.readln()} println(">>>",line); diff --git a/Task/Read-a-specific-line-from-a-file/Zkl/read-a-specific-line-from-a-file-2.zkl b/Task/Read-a-specific-line-from-a-file/Zkl/read-a-specific-line-from-a-file-2.zkl new file mode 100644 index 0000000000..f3b5210a04 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Zkl/read-a-specific-line-from-a-file-2.zkl @@ -0,0 +1 @@ +lines:=File.stdin.readln(7); println(">>>",line[-1]); diff --git a/Task/Read-entire-file/BASIC/read-entire-file.basic b/Task/Read-entire-file/BASIC/read-entire-file-1.basic similarity index 100% rename from Task/Read-entire-file/BASIC/read-entire-file.basic rename to Task/Read-entire-file/BASIC/read-entire-file-1.basic diff --git a/Task/Read-entire-file/BASIC/read-entire-file-2.basic b/Task/Read-entire-file/BASIC/read-entire-file-2.basic new file mode 100644 index 0000000000..feb8a8f986 --- /dev/null +++ b/Task/Read-entire-file/BASIC/read-entire-file-2.basic @@ -0,0 +1,14 @@ +10 rem load the entire contents of some text file as a single string variable. +20 rem should avoid reading an entire file at once if the file is large +30 rem ================================ +40 print chr$(14) : rem switch to upper+lowercase character set +50 open 4,8,4,"data.txt,seq,read" +60 n=0 +70 for i=0 to 1 +80 get#4,x$ +90 i=st and 64 : rem check for 'end-of-file' +100 if i=0 then a$=a$+x$ : n=n+1 +110 if n=255 then i=1 : rem max string length is 255 only +120 next +130 close 4 +140 end diff --git a/Task/Read-entire-file/BaCon/read-entire-file-1.bacon b/Task/Read-entire-file/BaCon/read-entire-file-1.bacon new file mode 100644 index 0000000000..625341f7ca --- /dev/null +++ b/Task/Read-entire-file/BaCon/read-entire-file-1.bacon @@ -0,0 +1 @@ +content$ = LOAD$(filename$) diff --git a/Task/Read-entire-file/BaCon/read-entire-file-2.bacon b/Task/Read-entire-file/BaCon/read-entire-file-2.bacon new file mode 100644 index 0000000000..be67a6a3b9 --- /dev/null +++ b/Task/Read-entire-file/BaCon/read-entire-file-2.bacon @@ -0,0 +1,3 @@ +binary = BLOAD("somefile.bin") +PRINT "First two bytes are: ", PEEK(binary), " ", PEEK(binary+1) +FREE binary diff --git a/Task/Read-entire-file/Gambas/read-entire-file.gambas b/Task/Read-entire-file/Gambas/read-entire-file.gambas new file mode 100644 index 0000000000..a2a76134a3 --- /dev/null +++ b/Task/Read-entire-file/Gambas/read-entire-file.gambas @@ -0,0 +1,6 @@ +Public Sub Form_Open() +Dim sFile As String + +sFile = File.Load(User.home &/ "file.txt") + +End diff --git a/Task/Read-entire-file/jq/read-entire-file-1.jq b/Task/Read-entire-file/Jq/read-entire-file-1.jq similarity index 100% rename from Task/Read-entire-file/jq/read-entire-file-1.jq rename to Task/Read-entire-file/Jq/read-entire-file-1.jq diff --git a/Task/Read-entire-file/jq/read-entire-file-2.jq b/Task/Read-entire-file/Jq/read-entire-file-2.jq similarity index 100% rename from Task/Read-entire-file/jq/read-entire-file-2.jq rename to Task/Read-entire-file/Jq/read-entire-file-2.jq diff --git a/Task/Read-entire-file/jq/read-entire-file-3.jq b/Task/Read-entire-file/Jq/read-entire-file-3.jq similarity index 100% rename from Task/Read-entire-file/jq/read-entire-file-3.jq rename to Task/Read-entire-file/Jq/read-entire-file-3.jq diff --git a/Task/Read-entire-file/Kotlin/read-entire-file.kotlin b/Task/Read-entire-file/Kotlin/read-entire-file.kotlin index a069cfdc05..f9cfb37f3d 100644 --- a/Task/Read-entire-file/Kotlin/read-entire-file.kotlin +++ b/Task/Read-entire-file/Kotlin/read-entire-file.kotlin @@ -1,3 +1,5 @@ -fun readText() { - val string = File("unixdict.txt").readText(charset = Charsets.UTF_8) +import java.io.File + +fun main(args: Array) { + println(File("unixdict.txt").readText(charset = Charsets.UTF_8)) } diff --git a/Task/Read-entire-file/Nimrod/read-entire-file.nimrod b/Task/Read-entire-file/Nimrod/read-entire-file.nimrod deleted file mode 100644 index 459831b1a0..0000000000 --- a/Task/Read-entire-file/Nimrod/read-entire-file.nimrod +++ /dev/null @@ -1 +0,0 @@ -readFile(filename) diff --git a/Task/Read-entire-file/OoRexx/read-entire-file-1.rexx b/Task/Read-entire-file/OoRexx/read-entire-file-1.rexx new file mode 100644 index 0000000000..52d0d081be --- /dev/null +++ b/Task/Read-entire-file/OoRexx/read-entire-file-1.rexx @@ -0,0 +1,3 @@ +file = 'c:\test.txt' +myStream = .stream~new(file) +myString = myStream~charIn(,myStream~chars) diff --git a/Task/Read-entire-file/OoRexx/read-entire-file-2.rexx b/Task/Read-entire-file/OoRexx/read-entire-file-2.rexx new file mode 100644 index 0000000000..e20079bcee --- /dev/null +++ b/Task/Read-entire-file/OoRexx/read-entire-file-2.rexx @@ -0,0 +1,7 @@ +file = 'c:\test.txt' +myStream = .stream~new(file) +if mystream~open('read') = 'READY:' +then do + myString = myStream~charIn(,myStream~chars) + myStream~close +end diff --git a/Task/Read-entire-file/OoRexx/read-entire-file-3.rexx b/Task/Read-entire-file/OoRexx/read-entire-file-3.rexx new file mode 100644 index 0000000000..0c745d4375 --- /dev/null +++ b/Task/Read-entire-file/OoRexx/read-entire-file-3.rexx @@ -0,0 +1,9 @@ +address hostemu 'execio * diskr "./st.in" (finis stem in.' +Say in.0 'lines in file st.in' +v='' +Do i=1 To in.0 + Say i '>'in.i'<' + v=v||in.i + End +say 'v='v +::requires "hostemu" LIBRARY diff --git a/Task/Read-entire-file/SPL/read-entire-file.spl b/Task/Read-entire-file/SPL/read-entire-file.spl new file mode 100644 index 0000000000..e08e182626 --- /dev/null +++ b/Task/Read-entire-file/SPL/read-entire-file.spl @@ -0,0 +1 @@ +text = #.readtext("filename.txt") diff --git a/Task/Read-entire-file/Stata/read-entire-file.stata b/Task/Read-entire-file/Stata/read-entire-file.stata new file mode 100644 index 0000000000..9973da0583 --- /dev/null +++ b/Task/Read-entire-file/Stata/read-entire-file.stata @@ -0,0 +1,8 @@ +mata +f = fopen("somedata.txt", "r") +fseek(f, 0, 1) +n = ftell(f) +fseek(f, 0, -1) +s = fread(f, n) +fclose(f) +end diff --git a/Task/Read-entire-file/Zkl/read-entire-file.zkl b/Task/Read-entire-file/Zkl/read-entire-file.zkl new file mode 100644 index 0000000000..7437ff78a7 --- /dev/null +++ b/Task/Read-entire-file/Zkl/read-entire-file.zkl @@ -0,0 +1 @@ +data := File("foo.txt","r").read() diff --git a/Task/Real-constants-and-functions/ALGOL-W/real-constants-and-functions.alg b/Task/Real-constants-and-functions/ALGOL-W/real-constants-and-functions.alg new file mode 100644 index 0000000000..94988f744d --- /dev/null +++ b/Task/Real-constants-and-functions/ALGOL-W/real-constants-and-functions.alg @@ -0,0 +1,17 @@ +begin + real t, u; + t := 10; + u := -2.3; + i_w := 4; s_w := 0; r_format := "A"; r_d := 4; r_w := 9; % set output format % + write( " e: ", exp( 1 ) ); % e % + write( " pi: ", pi ); % pi % + write( " root t: ", sqrt( t ) ); % square root % + write( " log t: ", log( t ) ); % log base 10 % + write( " ln t: ", ln( t ) ); % log base e % + write( " exp u: ", exp( u ) ); % exponential % + write( " abs u: ", abs u ); % absolute value % + write( " floor pi: ", entier( pi ) ); % floor % + write( "ceiling pi: ", - entier( - pi ) ); % ceiling % + % the raise-to-the-power operator is "**" - it only allows integers for the power % + write( " pi cubed: ", pi ** 3 ) % use exp( ln( x ) * y ) for general x^y % +end. diff --git a/Task/Real-constants-and-functions/BASIC/real-constants-and-functions.basic b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-1.basic similarity index 100% rename from Task/Real-constants-and-functions/BASIC/real-constants-and-functions.basic rename to Task/Real-constants-and-functions/BASIC/real-constants-and-functions-1.basic diff --git a/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-2.basic b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-2.basic new file mode 100644 index 0000000000..fc13d4dd5f --- /dev/null +++ b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-2.basic @@ -0,0 +1 @@ +EXP 1 diff --git a/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-3.basic b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-3.basic new file mode 100644 index 0000000000..ea3544b889 --- /dev/null +++ b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-3.basic @@ -0,0 +1 @@ +PI diff --git a/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-4.basic b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-4.basic new file mode 100644 index 0000000000..518e404a83 --- /dev/null +++ b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-4.basic @@ -0,0 +1 @@ +SQR X diff --git a/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-5.basic b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-5.basic new file mode 100644 index 0000000000..88a0055ed9 --- /dev/null +++ b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-5.basic @@ -0,0 +1 @@ +LN X diff --git a/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-6.basic b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-6.basic new file mode 100644 index 0000000000..9c69b1670c --- /dev/null +++ b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-6.basic @@ -0,0 +1 @@ +EXP X diff --git a/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-7.basic b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-7.basic new file mode 100644 index 0000000000..c573faa572 --- /dev/null +++ b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-7.basic @@ -0,0 +1 @@ +ABS X diff --git a/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-8.basic b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-8.basic new file mode 100644 index 0000000000..4c37ba68bd --- /dev/null +++ b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-8.basic @@ -0,0 +1 @@ +INT X diff --git a/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-9.basic b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-9.basic new file mode 100644 index 0000000000..e218a5ca8b --- /dev/null +++ b/Task/Real-constants-and-functions/BASIC/real-constants-and-functions-9.basic @@ -0,0 +1 @@ +X**Y diff --git a/Task/Real-constants-and-functions/Bc/real-constants-and-functions-1.bc b/Task/Real-constants-and-functions/Bc/real-constants-and-functions-1.bc new file mode 100644 index 0000000000..f1be032296 --- /dev/null +++ b/Task/Real-constants-and-functions/Bc/real-constants-and-functions-1.bc @@ -0,0 +1,3 @@ +scale = 6 +sqrt(2) /* 1.414213 square root */ +4.3 ^ -2 /* .054083 power (integer exponent) */ diff --git a/Task/Real-constants-and-functions/Bc/real-constants-and-functions-2.bc b/Task/Real-constants-and-functions/Bc/real-constants-and-functions-2.bc new file mode 100644 index 0000000000..33f16195c4 --- /dev/null +++ b/Task/Real-constants-and-functions/Bc/real-constants-and-functions-2.bc @@ -0,0 +1,11 @@ +scale = 6 +l(2) /* .693147 natural logarithm */ +e(2) /* 7.389056 exponential */ + +p = 4 * a(1) +e = e(1) +p /* 3.141592 pi to 6 fractional digits */ +e /* 2.178281 e to 6 fractional digits */ + +e(l(2) * -3.4) /* .094734 2 to the power of -3.4 */ +l(1024) / l(2) /* 10.000001 logarithm base 2 of 1024 */ diff --git a/Task/Real-constants-and-functions/Bc/real-constants-and-functions-3.bc b/Task/Real-constants-and-functions/Bc/real-constants-and-functions-3.bc new file mode 100644 index 0000000000..e7112bded5 --- /dev/null +++ b/Task/Real-constants-and-functions/Bc/real-constants-and-functions-3.bc @@ -0,0 +1,35 @@ +/* absolute value */ +define v(x) { + if (x < 0) return (-x) + return (x) +} + +/* floor */ +define f(x) { + auto s, y + + s = scale + scale = 0 + y = x / 1 + scale = s + + if (y > x) return (y - 1) + return (y) +} + +/* ceiling */ +define g(x) { + auto s, y + + s = scale + scale = 0 + y = x / 1 + scale = s + + if (y < x) return (y + 1) + return (y) +} + +v(-3.4) /* 3.4 absolute value */ +f(-3.4) /* -4 floor */ +g(-3.4) /* -3 ceiling */ diff --git a/Task/Real-constants-and-functions/Elena/real-constants-and-functions.elena b/Task/Real-constants-and-functions/Elena/real-constants-and-functions.elena new file mode 100644 index 0000000000..6971ffadd3 --- /dev/null +++ b/Task/Real-constants-and-functions/Elena/real-constants-and-functions.elena @@ -0,0 +1,16 @@ +import system'math. +import extensions. + +program = +[ + console printLine(e_value). //E + console printLine(pi_value). //PI + console printLine(10 sqrt). //Square Root + console printLine(10 ln). //Logarithm + console printLine(10 log10). // Base 10 Logarithm + console printLine(10 exp). //Exponential + console printLine(10 absolute). //Absolute value + console printLine(10.0r floor). //Floor + console printLine(10.0r ceil). //Ceiling + console printLine(2 power:5). //Exponentiation +]. diff --git a/Task/Real-constants-and-functions/jq/real-constants-and-functions.jq b/Task/Real-constants-and-functions/Jq/real-constants-and-functions.jq similarity index 100% rename from Task/Real-constants-and-functions/jq/real-constants-and-functions.jq rename to Task/Real-constants-and-functions/Jq/real-constants-and-functions.jq diff --git a/Task/Real-constants-and-functions/Kotlin/real-constants-and-functions.kotlin b/Task/Real-constants-and-functions/Kotlin/real-constants-and-functions.kotlin new file mode 100644 index 0000000000..dcb4b05336 --- /dev/null +++ b/Task/Real-constants-and-functions/Kotlin/real-constants-and-functions.kotlin @@ -0,0 +1,14 @@ +// version 1.0.6 + +fun main(args: Array) { + println(Math.E) // e + println(Math.PI) // pi + println(Math.sqrt(2.0)) // square root + println(Math.log(Math.E)) // log to base e + println(Math.log10(10.0)) // log to base 10 + println(Math.exp(1.0)) // exponential + println(Math.abs(-1)) // absolute value + println(Math.floor(-2.5)) // floor + println(Math.ceil(-2.5)) // ceiling + println(Math.pow(2.5, 3.5)) // power +} diff --git a/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions-1.logtalk b/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions-1.logtalk deleted file mode 100644 index b08941a9fa..0000000000 --- a/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions-1.logtalk +++ /dev/null @@ -1,16 +0,0 @@ -:- object(constants_and_functions). - - :- public(show/0). - show :- - write('e = '), E is e, write(E), nl, - write('pi = '), PI is pi, write(PI), nl, - write('sqrt(2) = '), SQRT is sqrt(2), write(SQRT), nl, - % only base e logorithm is avaialable as a standard built-in function - write('log(2) = '), LOG is log(2), write(LOG), nl, - write('exp(2) = '), EXP is exp(2), write(EXP), nl, - write('abs(-1) = '), ABS is abs(-1), write(ABS), nl, - write('floor(-3.4) = '), FLOOR is floor(-3.4), write(FLOOR), nl, - write('ceiling(-3.4) = '), CEILING is ceiling(-3.4), write(CEILING), nl, - write('2 ** -3.4 = '), POWER is 2 ** -3.4, write(POWER), nl. - -:- end_object. diff --git a/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions-2.logtalk b/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions-2.logtalk deleted file mode 100644 index 956ba9091a..0000000000 --- a/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions-2.logtalk +++ /dev/null @@ -1,11 +0,0 @@ -| ?- constants_and_functions::show. -e = 2.718281828459045 -pi = 3.141592653589793 -sqrt(2) = 1.4142135623730951 -log(2) = 0.6931471805599453 -exp(2) = 7.38905609893065 -abs(-1) = 1 -floor(-3.4) = -4 -ceiling(-3.4) = -3 -2 ** -3.4 = 0.09473228540689989 -yes diff --git a/Task/Real-constants-and-functions/OoRexx/real-constants-and-functions.rexx b/Task/Real-constants-and-functions/OoRexx/real-constants-and-functions.rexx new file mode 100644 index 0000000000..8c421aa684 --- /dev/null +++ b/Task/Real-constants-and-functions/OoRexx/real-constants-and-functions.rexx @@ -0,0 +1,58 @@ +/* Rexx */ + +-- MathLoadFuncs & MathDropFuncs are no longer needed and are effectively NOPs +-- but MathLoadFuncs does return its copyright statement when given a string argument +RxMathCopyright = MathLoadFuncs('') +say RxMathCopyright + +numeric digits 16 + +x = 2.5 +y = 3 +pad = 40 +digs = digits() +say +say 'Working with precision' digs +say 'Math constants & functions:' +say (' Euler''s number (e):')~left(pad) RxCalcExp(1, digs) +say (' Pi:')~left(pad) RxCalcPi(digs) +say (' Square root of' x':')~left(pad) RxCalcSqrt(x, digs) +say (' Log(e) of' x':')~left(pad) RxCalcLog(x, digs) +say (' Log(e) of e:')~left(pad) RxCalcLog(RxCalcExp(1, digs), digs) +say (' Log(10) of' x':')~left(pad) RxCalcLog10(x, digs) +say (' Log(10) of 10:')~left(pad) RxCalcLog10(10, digs) +say (' Exponential (e**x) of' x':')~left(pad) RxCalcExp(x, digs) +say (' Exponential (e**x) of log(e)' x':')~left(pad) RxCalcExp(RxCalcLog(x, digs), digs) +say (' ' x 'to the power of' y':')~left(pad) RxCalcPower(x, y, digs) +say (' ' x 'to the power of 1/'y':')~left(pad) RxCalcPower(x, 1 / y, digs) +say (' 10 to the power of log10' x':')~left(pad) RxCalcPower(10, RxCalcLog10(x), digs) + +say +say 'Rexx built-in support for numeric data:' +say (' Abs of' x':')~left(pad) x~abs() +say (' Abs of' (-x)':')~left(pad) (-x)~abs() +say (' Sign of' x':')~left(pad) x~sign() +say (' Sign of' x '-' x':')~left(pad) (x - x)~sign() +say (' Sign of' (-x)':')~left(pad) (-x)~sign() +say (' Max of' (-x) '&' x':')~left(pad) (-x)~max(x) +say (' Min of' (-x) '&' x':')~left(pad) (-x)~min(x) +say (' Truncate' x 'by' y':')~left(pad) x~trunc(y) +say (' Format (with rounding)' x 'by' y':')~left(pad) x~format(y, 0) + +say +say 'Use RYO functions for floor & ceiling:' +say (' Floor of' x':')~left(pad) floor(x) +say (' Floor of' (-x)':')~left(pad) floor((-x)) +say (' Ceiling of' x':')~left(pad) ceiling(x) +say (' Ceiling of' (-x)':')~left(pad) ceiling((-x)) + +return + +-- floor and ceiling functions are not part of ooRexx +floor: procedure + return arg(1)~trunc() - (arg(1) < 0) * (arg(1) \= arg(1)~trunc()) + +ceiling: procedure + return arg(1)~trunc() + (arg(1) > 0) * (arg(1) \= arg(1)~trunc()) + +::requires 'RxMath' library diff --git a/Task/Real-constants-and-functions/Sidef/real-constants-and-functions.sidef b/Task/Real-constants-and-functions/Sidef/real-constants-and-functions.sidef index e134ea527f..1141329c29 100644 --- a/Task/Real-constants-and-functions/Sidef/real-constants-and-functions.sidef +++ b/Task/Real-constants-and-functions/Sidef/real-constants-and-functions.sidef @@ -1,10 +1,10 @@ -Math.e; # e -Math.pi; # pi -x.sqrt; # square root -x.log; # natural logarithm -x.log10; # base 10 logarithm -x.exp; # e raised to the power of x -x.abs; # absolute value -x.floor; # floor -x.ceil; # ceiling -x**y; # exponentiation +Num.e # e +Num.pi # pi +x.sqrt # square root +x.log # natural logarithm +x.log10 # base 10 logarithm +x.exp # e raised to the power of x +x.abs # absolute value +x.floor # floor +x.ceil # ceiling +x**y # exponentiation diff --git a/Task/Real-constants-and-functions/Stata/real-constants-and-functions.stata b/Task/Real-constants-and-functions/Stata/real-constants-and-functions.stata new file mode 100644 index 0000000000..8cb56d62d4 --- /dev/null +++ b/Task/Real-constants-and-functions/Stata/real-constants-and-functions.stata @@ -0,0 +1,13 @@ +scalar x=2 +scalar y=3 +di exp(1) +di _pi +di c(pi) +di sqrt(x) +di log(x) +di log10(x) +di exp(x) +di abs(x) +di floor(x) +di ceil(x) +di x^y diff --git a/Task/Real-constants-and-functions/Zkl/real-constants-and-functions.zkl b/Task/Real-constants-and-functions/Zkl/real-constants-and-functions.zkl new file mode 100644 index 0000000000..4c8d02865a --- /dev/null +++ b/Task/Real-constants-and-functions/Zkl/real-constants-and-functions.zkl @@ -0,0 +1,10 @@ +(0.0).e // Euler's number, a property of all floats +(0.0).e.pi // pi, yep, all floats +(2.0).sqrt() // square root +(2.0).log() // natural (base e) logarithm +(2.0).log10() // log base 10 +(0.0).e.pow(x) // e^x +(-10.0).abs() // absolute value, both floats and ints +x.pow(y) // x raised to the y power +x.ceil() // ceiling +x.floor() // floor diff --git a/Task/Record-sound/Kotlin/record-sound.kotlin b/Task/Record-sound/Kotlin/record-sound.kotlin new file mode 100644 index 0000000000..f001564503 --- /dev/null +++ b/Task/Record-sound/Kotlin/record-sound.kotlin @@ -0,0 +1,45 @@ +// version 1.1.3 + +import java.io.File +import javax.sound.sampled.* + +const val RECORD_TIME = 20000L // twenty seconds say + +fun main(args: Array) { + val wavFile = File("RecordAudio.wav") + val fileType = AudioFileFormat.Type.WAVE + val format = AudioFormat(16000.0f, 16, 2, true, true) + val info = DataLine.Info(TargetDataLine::class.java, format) + val line = AudioSystem.getLine(info) as TargetDataLine + + // Creates a new thread that waits for 'RECORD_TIME' before stopping + Thread(object: Runnable { + override fun run() { + try { + Thread.sleep(RECORD_TIME) + } + catch (ie: InterruptedException) { + println(ie.message) + } + finally { + line.stop() + line.close() + } + println("Finished") + } + }).start() + + // Captures the sound and saves it in a WAV file + try { + if (AudioSystem.isLineSupported(info)) { + line.open(format) + line.start() + println("Recording started") + AudioSystem.write(AudioInputStream(line), fileType, wavFile) + } + else println("Line not supported") + } + catch (lue: LineUnavailableException) { + println(lue.message) + } +} diff --git a/Task/Reduced-row-echelon-form/Aime/reduced-row-echelon-form.aime b/Task/Reduced-row-echelon-form/Aime/reduced-row-echelon-form.aime index 99952d7ca4..4d64f0dddb 100644 --- a/Task/Reduced-row-echelon-form/Aime/reduced-row-echelon-form.aime +++ b/Task/Reduced-row-echelon-form/Aime/reduced-row-echelon-form.aime @@ -1,7 +1,7 @@ void rref(list l, integer rows, integer columns) { - integer e, i, j, lead, r; + integer e, f, i, j, lead, r; list u, v; lead = 0; @@ -12,7 +12,7 @@ rref(list l, integer rows, integer columns) } i = r; - while (!l_q_integer(l_q_list(l, i), lead)) { + while (!l_q_list(l, i)[lead]) { i += 1; if (i == rows) { i = r; @@ -26,31 +26,23 @@ rref(list l, integer rows, integer columns) break; } - u = l_q_list(l, i); + u = l[i]; l_spin(l, i, r); - e = l_q_integer(u, lead); + e = u[lead]; if (e) { - j = 0; - while (j < columns) { - l_r_integer(u, j, l_q_integer(u, j) / e); - j += 1; + for (j, f in u) { + u[j] = f / e; } } - i = 0; - while (i < rows) { + for (i, v in l) { if (i != r) { - v = l_q_list(l, i); - e = l_q_integer(v, lead); - j = 0; - while (j < columns) { - l_r_integer - (v, j, l_q_integer(v, j) - l_q_integer(u, j) * e); - j += 1; + e = v[lead]; + for (j, f in v) { + v[j] = f - l_q_integer(u, j) * e; } } - i += 1; } lead += 1; @@ -62,18 +54,12 @@ rref(list l, integer rows, integer columns) void display_2(list l, integer rows, integer columns) { - integer i, j; + integer i; list u; i = 0; - while (i < rows) { - u = l_q_list(l, i); - j = 0; - while (j < columns) { - o_winteger(4, l_q_integer(u, j)); - j += 1; - } - i += 1; + for (i, u in l) { + l_ucall(u, o_winteger, -1, 4); o_byte('\n'); } } diff --git a/Task/Reduced-row-echelon-form/C++/reduced-row-echelon-form.cpp b/Task/Reduced-row-echelon-form/C++/reduced-row-echelon-form.cpp index df06359217..66b77aba53 100644 --- a/Task/Reduced-row-echelon-form/C++/reduced-row-echelon-form.cpp +++ b/Task/Reduced-row-echelon-form/C++/reduced-row-echelon-form.cpp @@ -5,7 +5,7 @@ // Matrix traits: This describes how a matrix is accessed. By // externalizing this information into a traits class, the same code // can be used both with native arrays and matrix classes. To use the -// dfault implementation of the traits class, a matrix type has to +// default implementation of the traits class, a matrix type has to // provide the following definitions as members: // // * typedef ... index_type; @@ -32,7 +32,7 @@ template struct matrix_traits { typedef typename MatrixType::index_type index_type; - typedef typename MatrixType::value_typ value_type; + typedef typename MatrixType::value_type value_type; static index_type min_row(MatrixType const& A) { return A.min_row(); } static index_type max_row(MatrixType const& A) diff --git a/Task/Reduced-row-echelon-form/Julia/reduced-row-echelon-form.julia b/Task/Reduced-row-echelon-form/Julia/reduced-row-echelon-form.julia deleted file mode 100644 index 15c4f695f1..0000000000 --- a/Task/Reduced-row-echelon-form/Julia/reduced-row-echelon-form.julia +++ /dev/null @@ -1,34 +0,0 @@ -function ToReducedRowEchelonForm(matrix) - lead = 1 - rowCount,columnCount = size(matrix) - - for row = 1:rowCount - if lead > columnCount - return - end - - i = row - while matrix[i,lead] == 0 - i += 1 - if i == rowCount - i = row - lead += 1 - if columnCount == lead - return - end - end - end - - matrix[i,:],matrix[row,:] =matrix[row,:],matrix[i,:] - leadValue = matrix[row,lead] - matrix[row,:] = [ val / leadValue for val in matrix[row,:]] - - for i=1:rowCount - if i != row - leadValue = matrix[i,lead] - matrix[i,:] = [ (ivalue - leadValue*rowvalue) for (rowvalue,ivalue) in zip(matrix[row,:],matrix[i,:])] - end - end - lead += 1 - end -end diff --git a/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx b/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx index e183ed50b1..35d4b53719 100644 --- a/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx +++ b/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx @@ -1,47 +1,46 @@ -/*REXX program performs Reduced Row Echelon Form (RREF) on a matrix). */ -cols=0; w=0; @.=0 /*max cols in a row; max width; matrix.*/ -mat.=; mat.1= ' 1 2 -1 -4 ' - mat.2= ' 2 3 -1 -11 ' - mat.3= ' -2 0 -3 22 ' - do r=1 until mat.r==''; _=mat.r /*build @.row.col from mat.X */ +/*REXX pgm performs Reduced Row Echelon Form (RREF), AKA row canonical form on a matrix)*/ +cols=0; w=0; @.=0 /*max cols in a row; max width; matrix.*/ +mat.=; mat.1= ' 1 2 -1 -4 ' + mat.2= ' 2 3 -1 -11 ' + mat.3= ' -2 0 -3 22 ' + do r=1 until mat.r==''; _=mat.r /*build @.row.col from (matrix) mat.X*/ do c=1 until _=''; parse var _ @.r.c _ - w=max(w, length(@.r.c)) /*get max width of an element.*/ + w=max(w, length(@.r.c) +1) /*find the maximum width of an element.*/ end /*c*/ - cols=max(cols,c) /*remember max number of cols.*/ + cols=max(cols,c) /*remember max number of cols.*/ end /*r*/ -rows=r-1 /*adjust the row count (from DO loop).*/ -w=w+1 /*bump maximum width for a better view.*/ -call showMat 'original matrix' /*display the original matrix to screen*/ -!=1 /*set the working column pointer to 1.*/ - /* ┌───────────────────────────────◄── Reduced Row Echelon Form on matrix.*/ - do r=1 for rows while cols>! /*begin to perform the heavy lifting. */ +rows=r-1 /*adjust the row count (from DO loop).*/ +call showMat 'original matrix' /*display the original matrix to screen*/ +!=1 /*set the working column pointer to 1.*/ + /* ┌─────────────────────────────────────────◄── Reduced Row Echelon Form on matrix.*/ + do r=1 for rows while cols>! /*begin to perform the heavy lifting. */ j=r do while @.j.!==0; j=j+1 if j==rows then do; j=r; !=!+1; if cols==! then leave r; end end /*while*/ - /* [↓] swap rows J,R (but not if same)*/ - do _=1 for cols while j\==r; parse value @.r._ @.j._ with @.j._ @._._; end + /* [↓] swap rows J,R (but not if same)*/ + do _=1 for cols while j\==r; parse value @.r._ @.j._ with @.j._ @._._; end /*_*/ ?=@.r.! - do d=1 for cols while ?\=1; @.r.d=@.r.d/?; end /*d*/ - /* [↑] divide row J by @.r.p ──unless≡1*/ - do k=1 for rows; ?=@.k.! /*subtract (row K) @.r.s from row K.*/ - if k==r | ?=0 then iterate /*skip if row K is the same as row R.*/ - do s=1 for cols; @.k.s=@.k.s - ?*@.r.s; end /*s*/ - end /*k*/ /* [+] for the rest of numbers in row.*/ - !=!+1 /*bump the column pointer. */ + do d=1 for cols while ?\=1; @.r.d=@.r.d/?; end /*d*/ + /* [↑] divide row J by @.r.p ──unless≡1*/ + do k=1 for rows; ?=@.k.! /*subtract (row K) @.r.s from row K.*/ + if k==r | ?=0 then iterate /*skip if row K is the same as row R.*/ + do s=1 for cols; @.k.s=@.k.s - ?*@.r.s; end /*s*/ + end /*k*/ /* [↑] for the rest of numbers in row.*/ + !=!+1 /*bump the column pointer. */ end /*r*/ -call showMat 'matrix RREF' /*display the reduced row echelon form.*/ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -showMat: parse arg title; say; say center(title, 3+(cols+1)*w, '─'); say - do r=1 for rows; _= - do c=1 for cols - if @.r.c=='' then do; say "***error!*** matrix element isn't defined:" - say 'row' row", column" c'.'; exit 13 - end - _=_ right(@.r.c,w) - end /*c*/ - say _ /*display a row of the matrix to screen*/ - end /*r*/ -return +call showMat 'matrix RREF' /*display the reduced row echelon form.*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +showMat: parse arg title; say; say center(title, 3+(cols+1)*w, '─'); say + do r=1 for rows; _= + do c=1 for cols + if @.r.c=='' then do; say "***error*** matrix element isn't defined:" + say 'row' row", column" c'.'; exit 13 + end + _=_ right(@.r.c,w) + end /*c*/ + say _ /*display a row of the matrix to screen*/ + end /*r*/ + return diff --git a/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-1.zkl b/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-1.zkl new file mode 100644 index 0000000000..c02a8bccc8 --- /dev/null +++ b/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-1.zkl @@ -0,0 +1,20 @@ +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); + } + } + M.swapRows(i,r); + if(x:=M[r,lead]) M[r]/=x; + foreach i in (rows){ if(i!=r) M[i]-=M[r]*M[i,lead] } + lead+=1; + } + M +} 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 new file mode 100644 index 0000000000..46bf3423a9 --- /dev/null +++ b/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-2.zkl @@ -0,0 +1,4 @@ +A:=GSL.Matrix(3,4).set( 1, 2, -1, -4, + 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 new file mode 100644 index 0000000000..3e4e3c24a4 --- /dev/null +++ b/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-3.zkl @@ -0,0 +1,22 @@ +fcn toReducedRowEchelonForm(m){ // m is modified, the rows are not + lead,rowCount,columnCount := 0,m.len(),m[1].len(); + foreach r in (rowCount){ + if(columnCount<=lead) break; + i:=r; + while(m[i][lead]==0){ + 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]))) + }//foreach + lead+=1; + }//foreach + m +} 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 new file mode 100644 index 0000000000..2d97f5265e --- /dev/null +++ b/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-4.zkl @@ -0,0 +1,9 @@ +m:=List( T( 1, 2, -1, -4,), // T is read only list + T( 2, 3, -1, -11,), + T(-2, 0, -3, 22,)); +printM(m); +println("-->"); +printM(toReducedRowEchelonForm(m)); + +fcn printM(m){ m.pump(Console.println,rowFmt) } +fcn rowFmt(row){ ("%4d "*row.len()).fmt(row.xplode()) } diff --git a/Task/Regular-expressions/ABAP/regular-expressions.abap b/Task/Regular-expressions/ABAP/regular-expressions.abap index bfa1b7fdc9..66717744d0 100644 --- a/Task/Regular-expressions/ABAP/regular-expressions.abap +++ b/Task/Regular-expressions/ABAP/regular-expressions.abap @@ -8,4 +8,4 @@ ENDIF. REPLACE ALL OCCURRENCES OF REGEX '[t|T]est' IN text WITH 'Regex'. cl_demo_output=>write( text ). -cl_demo_output=>display( +cl_demo_output=>display( ). diff --git a/Task/Regular-expressions/Gambas/regular-expressions.gambas b/Task/Regular-expressions/Gambas/regular-expressions.gambas new file mode 100644 index 0000000000..c1840cd19f --- /dev/null +++ b/Task/Regular-expressions/Gambas/regular-expressions.gambas @@ -0,0 +1,11 @@ +Public Sub Main() +Dim sString As String = "Hello world!" + +If sString Ends "!" Then Print sString & " ends with !" +If sString Begins "Hel" Then Print sString & " begins with 'Hel'" + +sString = Replace(sString, "world", "moon") + +Print sString + +End diff --git a/Task/Regular-expressions/jq/regular-expressions-1.jq b/Task/Regular-expressions/Jq/regular-expressions-1.jq similarity index 100% rename from Task/Regular-expressions/jq/regular-expressions-1.jq rename to Task/Regular-expressions/Jq/regular-expressions-1.jq diff --git a/Task/Regular-expressions/jq/regular-expressions-2.jq b/Task/Regular-expressions/Jq/regular-expressions-2.jq similarity index 100% rename from Task/Regular-expressions/jq/regular-expressions-2.jq rename to Task/Regular-expressions/Jq/regular-expressions-2.jq diff --git a/Task/Regular-expressions/jq/regular-expressions-3.jq b/Task/Regular-expressions/Jq/regular-expressions-3.jq similarity index 100% rename from Task/Regular-expressions/jq/regular-expressions-3.jq rename to Task/Regular-expressions/Jq/regular-expressions-3.jq diff --git a/Task/Regular-expressions/Kotlin/regular-expressions.kotlin b/Task/Regular-expressions/Kotlin/regular-expressions.kotlin new file mode 100644 index 0000000000..bb6509a8fc --- /dev/null +++ b/Task/Regular-expressions/Kotlin/regular-expressions.kotlin @@ -0,0 +1,11 @@ +// version 1.0.6 + +fun main(args: Array) { + val s1 = "I am the original string" + val r1 = Regex("^.*string$") + if (s1.matches(r1)) println("`$s1` matches `$r1`") + val r2 = Regex("original") + val s3 = "replacement" + val s2 = s1.replace(r2, s3) + if (s2 != s1) println("`$s2` replaces `$r2` with `$s3`") +} diff --git a/Task/Regular-expressions/OoRexx/regular-expressions.rexx b/Task/Regular-expressions/OoRexx/regular-expressions.rexx new file mode 100644 index 0000000000..2e277dbc65 --- /dev/null +++ b/Task/Regular-expressions/OoRexx/regular-expressions.rexx @@ -0,0 +1,42 @@ +/* Rexx */ +/* Using the RxRegExp Regular Expression built-in utility class */ + +st1 = 'Fee, fie, foe, fum, I smell the blood of an Englishman' +rx1 = '[Ff]?e' -- unlike most regex engines, RxRegExp uses '?' instead of '.' to match any single character +sbx = 'foo' + +myRE = .RegularExpression~new() +myRE~parse(rx1, MINIMAL) + +mcm = myRE~pos(st1) +say 'String "'st1'"' 'matches pattern "'rx1'":' bool2string(mcm > 0) +say + +-- The RxRegExp package doesn't provide a replace capability so you must roll your own +st0 = st1 +loop label GREP forever + mcp = myRE~pos(st1) + if mcp > 0 then do + mpp = myRE~position + fnd = st1~substr(mcp, mpp - mcp + 1) + stx = st1~changestr(fnd, sbx, 1) + end + else leave GREP + st1 = stx + end GREP +say 'Input string: "'st0'"' +say 'Result string: "'stx'"' +return +exit + +bool2string: +procedure +do + parse arg bv . + if bv then bx = 'true' + else bx = 'false' + return bx +end +exit + +::requires "rxregexp.cls" diff --git a/Task/Regular-expressions/Phix/regular-expressions.phix b/Task/Regular-expressions/Phix/regular-expressions.phix new file mode 100644 index 0000000000..c5ee6987ab --- /dev/null +++ b/Task/Regular-expressions/Phix/regular-expressions.phix @@ -0,0 +1,10 @@ +include builtins\regex.e +string s = "I am a string" +printf(1,"\"%s\" %s with string\n",{s,iff(length(regex(`string$`,s))?"ends":"does not end")}) +printf(1,"\"%s\" %s with You\n",{s,iff(length(regex(`^You`,s))?"starts":"does not start")}) +?gsub(`[A-Z]`,"abCDefG","*") +?gsub(`[A-Z]`,"abCDefGH","(&)") +?gsub(`[A-Z]+`,"abCDefGH","(&)") +?gsub(`string`,s,"replacement") +s = gsub(`\ba\b`,s,"another") ?s +?gsub(`string`,s,"replacement") diff --git a/Task/Regular-expressions/Stata/regular-expressions.stata b/Task/Regular-expressions/Stata/regular-expressions.stata new file mode 100644 index 0000000000..fe8dd2edcf --- /dev/null +++ b/Task/Regular-expressions/Stata/regular-expressions.stata @@ -0,0 +1,7 @@ +scalar s="ars longa vita brevis" + +* is there a vowel? +di regexm(s,"[aeiou]") + +* replace the first vowel with "?" +di regexr(s,"[aeiou]","?") diff --git a/Task/Regular-expressions/Zkl/regular-expressions-1.zkl b/Task/Regular-expressions/Zkl/regular-expressions-1.zkl new file mode 100644 index 0000000000..caea546a5e --- /dev/null +++ b/Task/Regular-expressions/Zkl/regular-expressions-1.zkl @@ -0,0 +1,11 @@ +var re=RegExp(".*string$"); +re.matches("I am a string") //-->True +var s="I am a string thing" +re=RegExp("(string)") // () means group, ie if you see it, save it +re.search(s,True) //-->True, .search(x,True) means search for a match, ie don't need .* +p,n:=re.matched[0] //.matched-->L(L(7,6),"string") +String(s[0,p],"FOO",s[p+n,*]) //-->"I am a FOO thing" + +re.search(s,True); // using .matched clears it +m:=re.matched[1]; +s.replace(m,"FOO"); // -->"I am a FOO thing" diff --git a/Task/Regular-expressions/Zkl/regular-expressions-2.zkl b/Task/Regular-expressions/Zkl/regular-expressions-2.zkl new file mode 100644 index 0000000000..31d074ad0d --- /dev/null +++ b/Task/Regular-expressions/Zkl/regular-expressions-2.zkl @@ -0,0 +1,5 @@ +var s=Data(0,Int,"I am a string thing"); +re.search(s,True); +p,n:=re.matched[0]; +s[p,n]="FOO"; +s.text //-->"I am a FOO thing" diff --git a/Task/Remove-duplicate-elements/Ada/remove-duplicate-elements-1.ada b/Task/Remove-duplicate-elements/Ada/remove-duplicate-elements-1.ada deleted file mode 100644 index c8e014d55b..0000000000 --- a/Task/Remove-duplicate-elements/Ada/remove-duplicate-elements-1.ada +++ /dev/null @@ -1,21 +0,0 @@ -with Ada.Containers.Ordered_Sets; -with Ada.Text_IO; use Ada.Text_IO; - -procedure Unique_Set is - package Int_Sets is new Ada.Containers.Ordered_Sets(Integer); - use Int_Sets; - Nums : array (Natural range <>) of Integer := (1,2,3,4,5,5,6,7,1); - Unique : Set; - Set_Cur : Cursor; - Success : Boolean; -begin - for I in Nums'range loop - Unique.Insert(Nums(I), Set_Cur, Success); - end loop; - Set_Cur := Unique.First; - loop - Put_Line(Item => Integer'Image(Element(Set_Cur))); - exit when Set_Cur = Unique.Last; - Set_Cur := Next(Set_Cur); - end loop; -end Unique_Set; diff --git a/Task/Remove-duplicate-elements/Ada/remove-duplicate-elements-2.ada b/Task/Remove-duplicate-elements/Ada/remove-duplicate-elements-2.ada deleted file mode 100644 index 76fc8b13c5..0000000000 --- a/Task/Remove-duplicate-elements/Ada/remove-duplicate-elements-2.ada +++ /dev/null @@ -1,2 +0,0 @@ -∪ 1 2 3 1 2 3 4 1 -1 2 3 4 diff --git a/Task/Remove-duplicate-elements/Ada/remove-duplicate-elements-3.ada b/Task/Remove-duplicate-elements/Ada/remove-duplicate-elements-3.ada deleted file mode 100644 index 1e01817e31..0000000000 --- a/Task/Remove-duplicate-elements/Ada/remove-duplicate-elements-3.ada +++ /dev/null @@ -1,3 +0,0 @@ -w←1 2 3 1 2 3 4 1 - ((⍳⍨w)=⍳⍴w)/w -1 2 3 4 diff --git a/Task/Remove-duplicate-elements/AppleScript/remove-duplicate-elements-2.applescript b/Task/Remove-duplicate-elements/AppleScript/remove-duplicate-elements-2.applescript index 23c817862c..8b3b7a5836 100644 --- a/Task/Remove-duplicate-elements/AppleScript/remove-duplicate-elements-2.applescript +++ b/Task/Remove-duplicate-elements/AppleScript/remove-duplicate-elements-2.applescript @@ -1,22 +1,22 @@ --- CASE INSENSITIVE VERSION +-- CASE-INSENSITIVE UNIQUE ELEMENTS ------------------------------------------ -- nub :: [a] -> [a] on nub(xs) -- Eq :: a -> a -> Bool script Eq - on lambda(x, y) + on |λ|(x, y) ignoring case x = y end ignoring - end lambda + end |λ| end script nubBy(Eq, xs) end nub --- TEST -on run {} +-- TEST ---------------------------------------------------------------------- +on run {intercalate(space, ¬ nub(splitOn(space, "4 3 2 8 0 1 9 5 1 7 6 3 9 9 4 2 1 5 3 2"))), ¬ intercalate("", ¬ @@ -26,9 +26,40 @@ on run {} end run ---------------------------------------------------------------------------- +-- GENERIC FUNCTIONS --------------------------------------------------------- --- GENERIC FUNCTIONS +-- filter :: (a -> Bool) -> [a] -> [a] +on filter(f, xs) + tell mReturn(f) + set lst to {} + set lng to length of xs + repeat with i from 1 to lng + set v to item i of xs + if |λ|(v, i, xs) then set end of lst to v + end repeat + return lst + end tell +end filter + +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn -- nubBy :: (a -> a -> Bool) -> [a] -> [a] on nubBy(fnEq, xxs) @@ -41,9 +72,9 @@ on nubBy(fnEq, xxs) -- notEq :: a -> Bool script notEq - on lambda(a) - not (p's lambda(a, x)) - end lambda + on |λ|(a) + not (p's |λ|(a, x)) + end |λ| end script {x} & nubBy(fnEq, filter(notEq, xs)) @@ -52,33 +83,6 @@ on nubBy(fnEq, xxs) end if end nubBy --- filter :: (a -> Bool) -> [a] -> [a] -on filter(f, xs) - tell mReturn(f) - set lst to {} - set lng to length of xs - repeat with i from 1 to lng - set v to item i of xs - if lambda(v, i, xs) then set end of lst to v - end repeat - return lst - end tell -end filter - --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn - --- FOR THE TEST - -- splitOn :: Text -> Text -> [Text] on splitOn(strDelim, strMain) set {dlm, my text item delimiters} to {my text item delimiters, strDelim} @@ -86,11 +90,3 @@ on splitOn(strDelim, strMain) set my text item delimiters to dlm return lstParts end splitOn - --- intercalate :: Text -> [Text] -> Text -on intercalate(strText, lstText) - set {dlm, my text item delimiters} to {my text item delimiters, strText} - set strJoined to lstText as text - set my text item delimiters to dlm - return strJoined -end intercalate diff --git a/Task/Remove-duplicate-elements/Forth/remove-duplicate-elements-4.fth b/Task/Remove-duplicate-elements/Forth/remove-duplicate-elements-4.fth deleted file mode 100644 index d8139d8f05..0000000000 --- a/Task/Remove-duplicate-elements/Forth/remove-duplicate-elements-4.fth +++ /dev/null @@ -1 +0,0 @@ -1 2 3 4 5 6 ok diff --git a/Task/Remove-duplicate-elements/jq/remove-duplicate-elements-1.jq b/Task/Remove-duplicate-elements/Jq/remove-duplicate-elements-1.jq similarity index 100% rename from Task/Remove-duplicate-elements/jq/remove-duplicate-elements-1.jq rename to Task/Remove-duplicate-elements/Jq/remove-duplicate-elements-1.jq diff --git a/Task/Remove-duplicate-elements/jq/remove-duplicate-elements-2.jq b/Task/Remove-duplicate-elements/Jq/remove-duplicate-elements-2.jq similarity index 100% rename from Task/Remove-duplicate-elements/jq/remove-duplicate-elements-2.jq rename to Task/Remove-duplicate-elements/Jq/remove-duplicate-elements-2.jq diff --git a/Task/Remove-duplicate-elements/Lua/remove-duplicate-elements.lua b/Task/Remove-duplicate-elements/Lua/remove-duplicate-elements-1.lua similarity index 100% rename from Task/Remove-duplicate-elements/Lua/remove-duplicate-elements.lua rename to Task/Remove-duplicate-elements/Lua/remove-duplicate-elements-1.lua diff --git a/Task/Remove-duplicate-elements/Lua/remove-duplicate-elements-2.lua b/Task/Remove-duplicate-elements/Lua/remove-duplicate-elements-2.lua new file mode 100644 index 0000000000..7a2cc62f4f --- /dev/null +++ b/Task/Remove-duplicate-elements/Lua/remove-duplicate-elements-2.lua @@ -0,0 +1,15 @@ +local items = {1,2,3,4,1,2,3,4,0/0,nil,"bird","cat","dog","dog","bird",0/0} + +function rmdup(t) + local r,dup,c,NaN = {},{},1,{} + for i=1,#t do + local e = t[i] + local k = e~=e and NaN or e + if k~=nil and not dup[k] then + c, r[c], dup[k]= c+1, e, true + end + end + return r +end + +print(table.concat(rmdup(items),' ')) diff --git a/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-3.ocaml b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-3.ocaml index d1581794d3..1bad341dd2 100644 --- a/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-3.ocaml +++ b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-3.ocaml @@ -1 +1,6 @@ -List.sort_uniq compare [1;2;3;2;3;4] +let uniq l = + let rec tail_uniq a l = + match l with + | [] -> a + | hd::tl -> tail_uniq (hd::a) (List.filter (fun x -> x != hd) tl) in + tail_uniq [] l diff --git a/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-4.ocaml b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-4.ocaml new file mode 100644 index 0000000000..d1581794d3 --- /dev/null +++ b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-4.ocaml @@ -0,0 +1 @@ +List.sort_uniq compare [1;2;3;2;3;4] diff --git a/Task/Remove-duplicate-elements/OoRexx/remove-duplicate-elements.rexx b/Task/Remove-duplicate-elements/OoRexx/remove-duplicate-elements.rexx new file mode 100644 index 0000000000..c8e931f005 --- /dev/null +++ b/Task/Remove-duplicate-elements/OoRexx/remove-duplicate-elements.rexx @@ -0,0 +1,8 @@ +data = .array~of(1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d") +uniqueData = .set~new~union(data)~makearray~sort + +say "Unique elements are" +say +do item over uniqueData + say item +end diff --git a/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-1.rexx b/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-1.rexx index 1605f95983..71187449d4 100644 --- a/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-1.rexx +++ b/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-1.rexx @@ -1,12 +1,12 @@ -/*REXX program removes any duplicate elements (items) that are in a list. */ -$= '2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2' +/*REXX program removes any duplicate elements (items) that are in a list (using a hash).*/ +$= '2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2' /*item list.*/ say 'original list:' $ -say right(words($),17,'─') 'words in the original list.'; say -z=; @.= /*initialize the NEW list and index list*/ - do j=1 for words($); y=word($,j) /*process the words (items) in the list.*/ - if @.y=='' then z=z y; @.y=. /*Not duplicated? Add to Z list, @ array*/ - end /*j*/ - -say 'modified list:' space(z) -say right(words(z),17,'─') 'words in the modified list.' - /*stick a fork in it, we're all done. */ +say right( words($), 17, '─') 'words in the original list.' +z=; @.= /*initialize the NEW list & index list.*/ + do j=1 for words($); y=word($,j) /*process the words (items) in the list*/ + if @.y=='' then z=z y; @.y=. /*Not duplicated? Add to Z list,@ array*/ + end /*j*/ +say +say 'modified list:' space(z) +say right( words(z), 17, '─') 'words in the modified list.' + /*stick a fork in it, we're all done. */ diff --git a/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-2.rexx b/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-2.rexx index 7814224902..715f9ea383 100644 --- a/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-2.rexx +++ b/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-2.rexx @@ -1,12 +1,12 @@ -/*REXX program to remove duplicate elements (items) in a list. */ -$= '2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2' +/*REXX program removes any duplicate elements (items) that are in a list (using a list).*/ +$= '2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2' /*item list.*/ say 'original list:' $ -say right(words($),13) ' words in the original list.'; say - - do j=words($) by -1 to 1; y=word($,j) /*process words in the list, */ - _=wordpos(y, $, j+1); if _\==0 then $=delword($, _, 1) /*del if dup.*/ - end /*j*/ - -say 'modified list:' space($) -say right(words($),13) ' words in the modified list.' - /*stick a fork in it, we're done.*/ +say right( words($), 17, '─') 'words in the original list.' +#=words($) /*process all the words in the list. */ + do j=# by -1 for #; y=word($, j) /*get right-to-Left. */ + _=wordpos(y, $, j + 1); if _\==0 then $=delword($,_,1) /*Dup? Then delete it*/ + end /*j*/ +say +say 'modified list:' space($) +say right( words(z), 17, '─') 'words in the modified list.' + /*stick a fork in it, we're all done. */ diff --git a/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-3.rexx b/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-3.rexx index 47a9f05de7..6caa86ec64 100644 --- a/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-3.rexx +++ b/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-3.rexx @@ -1,13 +1,12 @@ -/*REXX program to remove duplicate elements (items) in a list. */ -old= '2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2' -say 'original list:' old -say right(words(old),13) ' words in the original list.'; say -new= /*start with a clean slate. */ - - do j=1 for words(old); _=word(old,j) /*process the words in old list. */ - if wordpos(_,new)==0 then new=new _ /*Doesn't exist? Then add to list*/ - end /*j*/ - +/*REXX program removes any duplicate elements (items) that are in a list (using 2 lists)*/ +old = '2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2' +say 'original list:' old +say right( words(old), 17, '─') 'words in the original list.' +new= /*start with a clean (list) slate. */ + do j=1 for words(old); _=word(old, j) /*process the words in the OLD list. */ + if wordpos(_,new)==0 then new=new _ /*Doesn't exist? Then add word to NEW.*/ + end /*j*/ +say say 'modified list:' space(new) -say right(words(new),13) ' words in the modified list.' - /*stick a fork in it, we're done.*/ +say right( words(new), 17, '─') 'words in the modified list.' + /*stick a fork in it, we're all done. */ diff --git a/Task/Remove-duplicate-elements/SETL/remove-duplicate-elements-4.setl b/Task/Remove-duplicate-elements/SETL/remove-duplicate-elements-4.setl new file mode 100644 index 0000000000..bec776839c --- /dev/null +++ b/Task/Remove-duplicate-elements/SETL/remove-duplicate-elements-4.setl @@ -0,0 +1,4 @@ +proc unique(items); + seen := {}; + return [item: item in items, nps in {#seen} | #(seen with:= item) > nps]; +end proc; diff --git a/Task/Remove-duplicate-elements/SETL/remove-duplicate-elements-5.setl b/Task/Remove-duplicate-elements/SETL/remove-duplicate-elements-5.setl new file mode 100644 index 0000000000..ee52d0cdc5 --- /dev/null +++ b/Task/Remove-duplicate-elements/SETL/remove-duplicate-elements-5.setl @@ -0,0 +1,2 @@ +items := [0,7,6,6,4,9,7,1,2,3,2]; +print(unique(items)); diff --git a/Task/Remove-duplicate-elements/SETL/remove-duplicate-elements-6.setl b/Task/Remove-duplicate-elements/SETL/remove-duplicate-elements-6.setl new file mode 100644 index 0000000000..32a9ca93d0 --- /dev/null +++ b/Task/Remove-duplicate-elements/SETL/remove-duplicate-elements-6.setl @@ -0,0 +1,3 @@ +proc unique(items); + return [item: item in {item: item in items}]; +end proc; diff --git a/Task/Remove-duplicate-elements/Setl4/remove-duplicate-elements.setl4 b/Task/Remove-duplicate-elements/Setl4/remove-duplicate-elements.setl4 new file mode 100644 index 0000000000..991698dcb8 --- /dev/null +++ b/Task/Remove-duplicate-elements/Setl4/remove-duplicate-elements.setl4 @@ -0,0 +1,3 @@ +set = new('set') +* Add all the elements of the array to the set. +add(set,array) diff --git a/Task/Remove-duplicate-elements/Stata/remove-duplicate-elements-1.stata b/Task/Remove-duplicate-elements/Stata/remove-duplicate-elements-1.stata new file mode 100644 index 0000000000..f25a9c1c3c --- /dev/null +++ b/Task/Remove-duplicate-elements/Stata/remove-duplicate-elements-1.stata @@ -0,0 +1,25 @@ +. clear all +. input x y +1 1 +1 1 +1 2 +2 1 +2 2 +1 1 +2 1 +2 1 +1 2 +2 2 +end + +. duplicates drop x y, force +. list + + +-------+ + | x y | + |-------| + 1. | 1 1 | + 2. | 1 2 | + 3. | 2 1 | + 4. | 2 2 | + +-------+ diff --git a/Task/Remove-duplicate-elements/Stata/remove-duplicate-elements-2.stata b/Task/Remove-duplicate-elements/Stata/remove-duplicate-elements-2.stata new file mode 100644 index 0000000000..fa90cb72fc --- /dev/null +++ b/Task/Remove-duplicate-elements/Stata/remove-duplicate-elements-2.stata @@ -0,0 +1,26 @@ +. mata +: a=1,1\1,1\1,2\2,1\2,2\1,1\2,1\2,1\1,2\2,2 + +: a + 1 2 + +---------+ + 1 | 1 1 | + 2 | 1 1 | + 3 | 1 2 | + 4 | 2 1 | + 5 | 2 2 | + 6 | 1 1 | + 7 | 2 1 | + 8 | 2 1 | + 9 | 1 2 | + 10 | 2 2 | + +---------+ + +: uniqrows(a) + 1 2 + +---------+ + 1 | 1 1 | + 2 | 1 2 | + 3 | 2 1 | + 4 | 2 2 | + +---------+ diff --git a/Task/Remove-duplicate-elements/Zkl/remove-duplicate-elements-1.zkl b/Task/Remove-duplicate-elements/Zkl/remove-duplicate-elements-1.zkl new file mode 100644 index 0000000000..ea6ee511a3 --- /dev/null +++ b/Task/Remove-duplicate-elements/Zkl/remove-duplicate-elements-1.zkl @@ -0,0 +1,4 @@ +zkl: Utils.Helpers.listUnique(T(1,3,2,9,1,2,3,8,8,"8",1,0,2,"8")) +L(1,3,2,9,8,"8",0) +zkl: "1,3,2,9,1,2,3,8,8,1,0,2".unique() +,012389 diff --git a/Task/Remove-duplicate-elements/Zkl/remove-duplicate-elements-2.zkl b/Task/Remove-duplicate-elements/Zkl/remove-duplicate-elements-2.zkl new file mode 100644 index 0000000000..55fd0d6c91 --- /dev/null +++ b/Task/Remove-duplicate-elements/Zkl/remove-duplicate-elements-2.zkl @@ -0,0 +1,2 @@ +fcn listUnique(xs){ + xs.reduce(fcn(us,s){us.holds(s) and us or us.append(s)},L()) } 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 new file mode 100644 index 0000000000..e9c6290f3d --- /dev/null +++ b/Task/Remove-lines-from-a-file/ALGOL-68/remove-lines-from-a-file.alg @@ -0,0 +1,121 @@ +# removes the specified number of lines from a file, starting at start line (numbered from 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 + 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 + THEN + # unable to create a temporary output file # + print( ( "Unable to create temporary file", newline ) ); + FALSE + ELIF NOT reset possible( temp file ) + THEN + # rewinding the temporary file is not possible # + # 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 + THEN + # failed to open the file # + print( ( "Unable to open """ + file name + """", newline ) ); + FALSE + 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 + ); + # copy the input file to the temp file # + WHILE STRING line; + get( input file, ( line, newline ) ); + NOT at eof + DO + put( temp file, ( line, newline ) ) + OD; + # copy the temp file back to the input, removing the specified lines # + close( input file ); + IF open( input file, file name, stand out channel ) /= 0 + THEN + # failed to open the original file for output # + print( ( "Unable to open ", file name, " for output", newline ) ); + FALSE + ELSE + # 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 + ); + INT end line = ( start line - 1 ) + number of lines; + INT line number := 0; + WHILE STRING line; + get( temp file, ( line, newline ) ); + NOT at eof + DO + # have another line # + line number +:= 1; + IF line number < start line OR line number > end line + THEN + put( input file, ( line, newline ) ) + FI + OD; + # close the files # + close( input file ); + scratch( temp file ); + 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 ) ); + FALSE + ELIF line number < end line + THEN + # the ending line was not in the file # + print( ( "Final omitted line not in the file ", file name, newline ) ); + FALSE + ELSE + # successful operation # + TRUE + FI + FI + 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 diff --git a/Task/Remove-lines-from-a-file/BASIC/remove-lines-from-a-file.basic b/Task/Remove-lines-from-a-file/BASIC/remove-lines-from-a-file.basic index 9237e5f846..5c99a041ab 100644 --- a/Task/Remove-lines-from-a-file/BASIC/remove-lines-from-a-file.basic +++ b/Task/Remove-lines-from-a-file/BASIC/remove-lines-from-a-file.basic @@ -1,27 +1,35 @@ ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' -' Remove File Lines V1.0 ' +' Remove File Lines V1.1 ' ' ' ' Developed by A. David Garza Marín in VB-DOS for ' ' RosettaCode. November 30, 2016. ' +' ' +' Date | Change ' +'-------------------------------------------------- ' +' 2016/11/30| Original version ' +' 2016/12/30| Added functionality to read parameters' +' | from Command Line ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 'OPTION _EXPLICIT ' For QB45 -'OPTION EXPLICIT ' For VBDOS, PDS 7.1 +OPTION EXPLICIT ' For VBDOS, PDS 7.1 ' SUBs and FUNCTIONs DECLARE FUNCTION DeleteLinesFromFile% (WhichFile AS STRING, Start AS LONG, HowMany AS LONG) DECLARE FUNCTION FileExists% (WhichFile AS STRING) DECLARE FUNCTION GetDummyFile$ (WhichFile AS STRING) +DECLARE FUNCTION getFileName$ (CommandString AS STRING) +DECLARE FUNCTION getHowManyLines& (CommandLine AS STRING) +DECLARE FUNCTION getStartPoint& (CommandLine AS STRING) DECLARE FUNCTION ErrorMessage$ (WhichError AS INTEGER) DECLARE FUNCTION CountLines& (WhichFile AS STRING) -DECLARE FUNCTION YorN$ () ' Var DIM iOk AS INTEGER, iErr AS INTEGER, lStart AS LONG, lHowMany AS LONG, lSize AS LONG -DIM sFile AS STRING +DIM sFile AS STRING, sCommand AS STRING ' Const -CONST ProgramName = "RemFLine (Remove File Lines) Enhanced V1.0" +CONST ProgramName = "RemFLine (Remove File Lines) Enhanced V1.1" ' ----------------------------- Main program cycle -------------------------------- CLS @@ -34,41 +42,59 @@ PRINT "quantity of lines stated to be deleted is beyond the total lines in the t PRINT "file, the process also will be aborted. The program will give you a message" PRINT "if everything ran ok or if any error happened. Includes a function to count" PRINT "how many lines has the intended file." -DO - PRINT - INPUT "Please, type the name of the file"; sFile - sFile = LTRIM$(RTRIM$(sFile)) - IF sFile <> "" THEN - lSize = CountLines&(sFile) - IF lSize > 0 THEN - PRINT "Delete starting on which line (Default=1, Max="; lSize; ")"; - INPUT lStart +' Verifies if parameters are specified +sCommand = COMMAND$ +IF sCommand <> "" THEN + sFile = getFileName$(sCommand) + lSize = CountLines&(sFile) + lStart = getStartPoint&(sCommand) ' Defaults to 1 + lHowMany = getHowManyLines&(sCommand) ' Defaults to 1 +ELSE + PRINT + INPUT "Please, type the name of the file"; sFile + sFile = LTRIM$(RTRIM$(sFile)) + IF sFile <> "" THEN + lSize = CountLines&(sFile) + IF lSize > 0 THEN + PRINT "Delete starting on which line (Default=1, Max="; lSize; ")"; + INPUT lStart - IF lStart = 0 THEN lStart = 1 - IF lStart < lSize THEN - PRINT "How many lines do you want to remove (Default=1, Max="; (lSize - lStart) + 1; ")"; - INPUT lHowMany - IF lHowMany = 0 THEN lHowMany = 1 - IF lHowMany + lStart <= lSize THEN - iOk = DeleteLinesFromFile%(sFile, lStart, lHowMany) - ELSE - iOk = 1 - END IF - ELSE - iOk = 2 - END IF - ELSEIF lSize = -1 THEN - iOk = 3 - ELSE - iOk = 4 ' The file is not a text file + IF lStart = 0 THEN lStart = 1 + IF lStart < lSize THEN + PRINT "How many lines do you want to remove (Default=1, Max="; (lSize - lStart) + 1; ")"; + INPUT lHowMany + IF lHowMany = 0 THEN lHowMany = 1 END IF - ELSE - iOk = 5 ' Null file name not allowed END IF - PRINT - PRINT ErrorMessage$(iOk) - PRINT "Do you want to try again? (Y/N)" -LOOP UNTIL YorN$ = "N" + END IF +END IF + +PRINT +PRINT "Erasing "; lHowMany; "lines from "; sFile; " starting on line"; lStart; "." +IF lSize > 0 THEN + IF lHowMany + lStart <= lSize THEN + iOk = DeleteLinesFromFile%(sFile, lStart, lHowMany) + ELSEIF lHowMany + lStart > lSize THEN + iOk = 1 + ELSEIF lStart > lSize THEN + iOk = 2 + END IF +ELSEIF lSize = -1 THEN + iOk = 3 +END IF + +IF lSize = -1 THEN + iOk = 3 +ELSEIF lSize = 0 THEN + iOk = 4 ' The file is not a text file +END IF + +IF sFile = "" THEN + iOk = 5 ' Null file name not allowed +END IF + +PRINT +PRINT ErrorMessage$(iOk) '----------------End of Main program Cycle ---------------- END @@ -227,16 +253,54 @@ FUNCTION GetDummyFile$ (WhichFile AS STRING) GetDummyFile$ = LEFT$(WhichFile, i - 1) + "$dummyf$.tmp" END FUNCTION -FUNCTION YorN$ () - ' Var - DIM sYorN AS STRING +FUNCTION getFileName$ (CommandString AS STRING) + ' Var + DIM i AS INTEGER + DIM sFileName AS STRING - DO - sYorN = UCASE$(INPUT$(1)) - IF INSTR("YN", sYorN) = 0 THEN - BEEP - END IF - LOOP UNTIL sYorN = "Y" OR sYorN = "N" + i = INSTR(CommandString, ",") + IF i > 0 THEN + sFileName = LEFT$(CommandString, i - 1) + ELSEIF LEN(CommandString) > 0 THEN + sFileName = CommandString + END IF + + getFileName$ = sFileName +END FUNCTION + +FUNCTION getHowManyLines& (CommandLine AS STRING) + ' Var + DIM i AS INTEGER, j AS INTEGER + DIM l AS LONG + + i = INSTR(CommandLine, ",") + IF i > 0 THEN + j = INSTR(i + 1, CommandLine, ",") + IF j = 0 THEN + l = 1 + ELSE + l = CLNG(VAL(MID$(CommandLine, j + 1))) + END IF + END IF + + getHowManyLines& = l + +END FUNCTION + +FUNCTION getStartPoint& (CommandLine AS STRING) + ' Var + DIM i AS INTEGER, j AS INTEGER + DIM l AS LONG + + i = INSTR(CommandLine, ",") + IF i > 0 THEN + j = INSTR(i + 1, CommandLine, ",") + IF j = 0 THEN j = LEN(CommandLine) + l = CLNG(VAL(MID$(CommandLine, i + 1, j - i))) + ELSE + i = 1 + END IF + + getStartPoint& = l - YorN$ = sYorN END FUNCTION diff --git a/Task/Remove-lines-from-a-file/C-sharp/remove-lines-from-a-file.cs b/Task/Remove-lines-from-a-file/C-sharp/remove-lines-from-a-file.cs index e3f429c176..467ff01f07 100644 --- a/Task/Remove-lines-from-a-file/C-sharp/remove-lines-from-a-file.cs +++ b/Task/Remove-lines-from-a-file/C-sharp/remove-lines-from-a-file.cs @@ -3,17 +3,9 @@ using System.IO; public class Rosetta { - /* C# 6 version: public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2); - */ - public static void Main() { - RemoveLines("foobar.txt", start: 1, count: 2); - } - - static void RemoveLines(string filename, int start, int count = 1) { - //Reads and writes one line at a time, so no memory overhead. + static void RemoveLines(string filename, int start, int count = 1) => File.WriteAllLines(filename, File.ReadAllLines(filename) .Where((line, index) => index < start - 1 || index >= start + count - 1)); - } } diff --git a/Task/Remove-lines-from-a-file/Gambas/remove-lines-from-a-file.gambas b/Task/Remove-lines-from-a-file/Gambas/remove-lines-from-a-file.gambas new file mode 100644 index 0000000000..829d80af6a --- /dev/null +++ b/Task/Remove-lines-from-a-file/Gambas/remove-lines-from-a-file.gambas @@ -0,0 +1,45 @@ +sNewFile As String 'Global string for the 'New file' details + +Public Sub Main() +Dim sFileName As String = User.Home &/ "foobar.txt" 'File name + +sNewFile = DeleteLines(sFileName, 1, 2) 'Send the details to the DeleteLine routine 'The parameters should be: foobar.txt, 1, 2' +Print "New file: -" & gb.NewLine & sNewFile 'Print details of the changed file +File.Save(sFileName, sNewFile) 'Save the file with the original name + +End + +Public Sub DeleteLines(sFile As String, siStart As Short, siNum As Short) As String 'DeleteLines routine +Dim sData As New String[] 'To store the existing file data +Dim siCount As Short 'Counter +Dim sTemp, sDel As String 'String variables + +For Each sTemp In Split(File.Load(sFile), gb.NewLine) 'Load the file, split the lines by NewLine + sData.Add(sTemp) 'Add to sData +Next + +Print "Original file: -" 'Print Title + +If siStart + siNum > sData.max Then 'Check an attempt is made to remove lines beyond the end of the file + Print "Not enough lines in file to carry out request" 'An appropriate message should appear if so + Return "" 'Return nothing +Endif + +Dec siStart 'For the purpose of this task, line numbers start at one (Program starts at 0) + +For siCount = siStart To (siStart + siNum) - 1 'Loop through the lines to be deleted + sDel &= Str(siCount) & " " 'Add then to sDel +Next + +siCount = -1 'Reset counter + +For Each sTemp In sData 'For each line in the file.. + Inc siCount 'Increase counter + Print sTemp 'Print the line + If InStr(sDel, Str(siCount) & " ") Then Continue 'If the line number is listed in sDel then jump to the end of the loop + sNewFile &= sTemp & gb.NewLine 'Add the lines not to be removed into sNewFile +Next + +Return sNewFile 'Return the details + +End diff --git a/Task/Remove-lines-from-a-file/jq/remove-lines-from-a-file-1.jq b/Task/Remove-lines-from-a-file/Jq/remove-lines-from-a-file-1.jq similarity index 100% rename from Task/Remove-lines-from-a-file/jq/remove-lines-from-a-file-1.jq rename to Task/Remove-lines-from-a-file/Jq/remove-lines-from-a-file-1.jq diff --git a/Task/Remove-lines-from-a-file/jq/remove-lines-from-a-file-2.jq b/Task/Remove-lines-from-a-file/Jq/remove-lines-from-a-file-2.jq similarity index 100% rename from Task/Remove-lines-from-a-file/jq/remove-lines-from-a-file-2.jq rename to Task/Remove-lines-from-a-file/Jq/remove-lines-from-a-file-2.jq diff --git a/Task/Remove-lines-from-a-file/jq/remove-lines-from-a-file-3.jq b/Task/Remove-lines-from-a-file/Jq/remove-lines-from-a-file-3.jq similarity index 100% rename from Task/Remove-lines-from-a-file/jq/remove-lines-from-a-file-3.jq rename to Task/Remove-lines-from-a-file/Jq/remove-lines-from-a-file-3.jq diff --git a/Task/Remove-lines-from-a-file/jq/remove-lines-from-a-file-4.jq b/Task/Remove-lines-from-a-file/Jq/remove-lines-from-a-file-4.jq similarity index 100% rename from Task/Remove-lines-from-a-file/jq/remove-lines-from-a-file-4.jq rename to Task/Remove-lines-from-a-file/Jq/remove-lines-from-a-file-4.jq 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.kotlin new file mode 100644 index 0000000000..5f5b4bc11c --- /dev/null +++ b/Task/Remove-lines-from-a-file/Kotlin/remove-lines-from-a-file.kotlin @@ -0,0 +1,43 @@ +// version 1.1.2 + +import java.io.File + +fun removeLines(fileName: String, startLine: Int, numLines: Int) { + require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1) + val f = File(fileName) + if (!f.exists()) { + println("$fileName does not exist") + return + } + var lines = f.readLines() + val size = lines.size + if (startLine > size) { + println("The starting line is beyond the length of the file") + return + } + var n = numLines + if (startLine + numLines - 1 > size) { + println("Attempting to remove some lines which are beyond the end of the file") + n = size - startLine + 1 + } + lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1) + val text = lines.joinToString(System.lineSeparator()) + f.writeText(text) +} + +fun printFile(fileName: String, message: String) { + require(!fileName.isEmpty()) + val f = File(fileName) + if (!f.exists()) { + println("$fileName does not exist") + return + } + println("\nContents of $fileName $message:\n") + f.forEachLine { println(it) } +} + +fun main(args: Array) { + printFile("input.txt", "before removal") + removeLines("input.txt", 2, 3) + printFile("input.txt", "after removal of 3 lines starting from the second") +} diff --git a/Task/Remove-lines-from-a-file/Phix/remove-lines-from-a-file.phix b/Task/Remove-lines-from-a-file/Phix/remove-lines-from-a-file.phix new file mode 100644 index 0000000000..935808b347 --- /dev/null +++ b/Task/Remove-lines-from-a-file/Phix/remove-lines-from-a-file.phix @@ -0,0 +1,15 @@ +procedure remove_lines(string filename, integer start, integer n) + integer fn = open(filename,'r') + if fn!=-1 then + sequence lines = get_text(fn,GT_LF_STRIPPED) + close(fn) + end if + if fn=-1 or n<1 or start<1 or length(lines)= start and num > 0 - num -= 1 - else - tmp.write line - end - end - tmp.close - STDERR.puts "Warning: End of file encountered before all lines removed" if num > 0 - FileUtils.copy(tmp.path, filename) - tmp.unlink -end diff --git a/Task/Remove-lines-from-a-file/Ruby/remove-lines-from-a-file-2.rb b/Task/Remove-lines-from-a-file/Ruby/remove-lines-from-a-file-2.rb deleted file mode 100644 index 2cbbd6c7c8..0000000000 --- a/Task/Remove-lines-from-a-file/Ruby/remove-lines-from-a-file-2.rb +++ /dev/null @@ -1,19 +0,0 @@ -def setup(start, remove) - puts "remove #{remove} lines starting at line #{start}" - File.open($filename, "w") {|fh| (1..5).each {|i| fh.puts i}} - puts "before:\n" + File.read($filename) -end - -def teardown - puts "after:\n" + File.read($filename) - puts "" - File.unlink($filename) -end - -$filename = "test.file" -start = 2 -[2, 6].each do |remove| - setup(start, remove) - remove_lines $filename, start, remove - teardown -end diff --git a/Task/Remove-lines-from-a-file/Stata/remove-lines-from-a-file.stata b/Task/Remove-lines-from-a-file/Stata/remove-lines-from-a-file.stata new file mode 100644 index 0000000000..d9fbf26633 --- /dev/null +++ b/Task/Remove-lines-from-a-file/Stata/remove-lines-from-a-file.stata @@ -0,0 +1,5 @@ +* drop lines 20 to 30 +drop in 20/30 + +* keep lines 20 to 30, and remove everything else +keep in 20/30 diff --git a/Task/Remove-lines-from-a-file/UNIX-Shell/remove-lines-from-a-file-3.sh b/Task/Remove-lines-from-a-file/UNIX-Shell/remove-lines-from-a-file-3.sh new file mode 100644 index 0000000000..c24ac9b57e --- /dev/null +++ b/Task/Remove-lines-from-a-file/UNIX-Shell/remove-lines-from-a-file-3.sh @@ -0,0 +1 @@ +sed -i "" "$start,${end}d" "$file" diff --git a/Task/Remove-lines-from-a-file/Zkl/remove-lines-from-a-file-1.zkl b/Task/Remove-lines-from-a-file/Zkl/remove-lines-from-a-file-1.zkl new file mode 100644 index 0000000000..792a2b50a1 --- /dev/null +++ b/Task/Remove-lines-from-a-file/Zkl/remove-lines-from-a-file-1.zkl @@ -0,0 +1,8 @@ +fcn deleteLinesM(fname, start,num){ + blob:=File(fname).read(); // file to memory + n:=blob.seek(Void,start-1); // seek to line and remember it + blob.del(n,blob.seek(Void,num)-n); + + File.stdout.write(blob); +} +deleteLinesM("nn.zkl", 2,5); diff --git a/Task/Remove-lines-from-a-file/Zkl/remove-lines-from-a-file-2.zkl b/Task/Remove-lines-from-a-file/Zkl/remove-lines-from-a-file-2.zkl new file mode 100644 index 0000000000..bb84d7464d --- /dev/null +++ b/Task/Remove-lines-from-a-file/Zkl/remove-lines-from-a-file-2.zkl @@ -0,0 +1,8 @@ +fcn deleteLinesL(fname, start,num){ + if (start < 1) throw(Exception.ValueError); + f:=File(fname); + do(start-1) { File.stdout.write(f.readln()) } + do(num) { f.readln(); } + f.pump(File.stdout.write); +} +deleteLinesL("nn.zkl", 2,5); diff --git a/Task/Rename-a-file/Kotlin/rename-a-file.kotlin b/Task/Rename-a-file/Kotlin/rename-a-file.kotlin new file mode 100644 index 0000000000..f5dbe1a666 --- /dev/null +++ b/Task/Rename-a-file/Kotlin/rename-a-file.kotlin @@ -0,0 +1,21 @@ +// version 1.0.6 + +/* testing on Windows 10 which needs administrative privileges + to rename files in the root */ + +import java.io.File + +fun main(args: Array) { + val oldPaths = arrayOf("input.txt", "docs", "c:\\input.txt", "c:\\docs") + val newPaths = arrayOf("output.txt", "mydocs", "c:\\output.txt", "c:\\mydocs") + var oldFile: File + var newFile: File + for (i in 0 until oldPaths.size) { + oldFile = File(oldPaths[i]) + newFile = File(newPaths[i]) + if (oldFile.renameTo(newFile)) + println("${oldPaths[i]} successfully renamed to ${newPaths[i]}") + else + println("${oldPaths[i]} could not be renamed") + } +} diff --git a/Task/Rename-a-file/Phix/rename-a-file.phix b/Task/Rename-a-file/Phix/rename-a-file.phix new file mode 100644 index 0000000000..ce5f6b0c70 --- /dev/null +++ b/Task/Rename-a-file/Phix/rename-a-file.phix @@ -0,0 +1,4 @@ +?rename_file("input.txt","output.txt") +?rename_file("docs","mydocs") +?rename_file("C:\\Copy.txt","Copy.xxx") +?rename_file("C:\\docs","C:\\mydocs") diff --git a/Task/Rename-a-file/Stata/rename-a-file.stata b/Task/Rename-a-file/Stata/rename-a-file.stata new file mode 100644 index 0000000000..d9fda3b7fa --- /dev/null +++ b/Task/Rename-a-file/Stata/rename-a-file.stata @@ -0,0 +1,2 @@ +!ren input.txt output.txt +!ren docs mydocs diff --git a/Task/Rendezvous/Zkl/rendezvous-1.zkl b/Task/Rendezvous/Zkl/rendezvous-1.zkl new file mode 100644 index 0000000000..c39ee6b8ef --- /dev/null +++ b/Task/Rendezvous/Zkl/rendezvous-1.zkl @@ -0,0 +1,34 @@ +class OutOfInk(Exception.IOError){ + const TEXT="Out of ink"; + text=TEXT; // rename IOError to OutOfInk for this first/mother class + fcn init{ IOError.init(TEXT) } // this renames instances +} +class Printer{ + var id, ink; + fcn init(_id,_ink){ id,ink=vm.arglist } + fcn print(line){ + if(not ink) throw(OutOfInk); + println("%s: %s".fmt(id,line)); + Atomic.sleep((0.0).random(0.01)); // don't let one thread dominate + ink-=1; + } +} +class RendezvousPrinter{ // the choke point between printers and tasks + var printers=Thread.List(); // a thread safe list + fcn init(_printers){ printers.extend(vm.arglist) } + fcn print(line){ // caller waits for print job to finish + var lines=Thread.List(); // fcn local [static] variable, the print queue + lines.write(line); // thread safe, stalls when full + // lines is racy - other threads are modifing it, length is suspect here + while(True){ // this thread can print that threads job + critical{ // creates a [global] mutex, automatically unlocks on exception + if(not printers) throw(OutOfInk); // No more printers to try + if(not lines) break; // only remove jobs in this serialized section + try{ + printers[0].print(lines[0]); // can throw + lines.del(0); // successful print, remove job from queue + }catch(OutOfInk){ printers.del(0) } // Switch to the next printer + } + } + } +} diff --git a/Task/Rendezvous/Zkl/rendezvous-2.zkl b/Task/Rendezvous/Zkl/rendezvous-2.zkl new file mode 100644 index 0000000000..09e0b331cb --- /dev/null +++ b/Task/Rendezvous/Zkl/rendezvous-2.zkl @@ -0,0 +1,20 @@ +fcn printTask(taskNm,rendezvous,lines){ + try{ foreach line in (vm.arglist[2,*]){ rendezvous.print(line); } } + catch{ println(taskNm," caught ",__exception); } // and thread quits trying to print +} +fcn humptyDumptyTask(rendezvous){ // a thread + printTask("humptyDumptyTask",rendezvous, + "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." + ) +} +fcn motherGooseTask(rendezvous){ // a thread + printTask("motherGooseTask",rendezvous, + "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." + ) +} diff --git a/Task/Rendezvous/Zkl/rendezvous-3.zkl b/Task/Rendezvous/Zkl/rendezvous-3.zkl new file mode 100644 index 0000000000..734b3d82a2 --- /dev/null +++ b/Task/Rendezvous/Zkl/rendezvous-3.zkl @@ -0,0 +1,5 @@ +rendezvous:=RendezvousPrinter(Printer("main",5), Printer("reserve",5)); +humptyDumptyTask.launch(rendezvous); +motherGooseTask.launch(rendezvous); + +Atomic.waitFor(fcn{ (not vm.numThreads) }); // wait for threads to finish diff --git a/Task/Rep-string/00DESCRIPTION b/Task/Rep-string/00DESCRIPTION index 26ebb672dc..2fe4d8c5e9 100644 --- a/Task/Rep-string/00DESCRIPTION +++ b/Task/Rep-string/00DESCRIPTION @@ -1,8 +1,8 @@ Given a series of ones and zeroes in a string, define a repeated string or ''rep-string'' as a string which is created by repeating a substring of the ''first'' N characters of the string ''truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original''. -For example, the string     '''10011001100'''     is a rep-string as the leftmost four characters of     '''1001'''     are repeated three times and truncated on the right to give the original string. +For example, the string '''10011001100''' is a rep-string as the leftmost four characters of '''1001''' are repeated three times and truncated on the right to give the original string. -Note that the requirement for having the repeat occur two or more times means that the repeating unit is   ''never''   longer than half the length of the input string. +Note that the requirement for having the repeat occur two or more times means that the repeating unit is ''never'' longer than half the length of the input string. ;Task: diff --git a/Task/Rep-string/AppleScript/rep-string.applescript b/Task/Rep-string/AppleScript/rep-string.applescript new file mode 100644 index 0000000000..aa3d97604c --- /dev/null +++ b/Task/Rep-string/AppleScript/rep-string.applescript @@ -0,0 +1,240 @@ +-- REP-CYCLES ---------------------------------------------------------------- + +-- repCycles :: String -> [String] +on repCycles(xs) + set n to length of xs + + script isCycle + on |λ|(cs) + xs = takeCycle(n, cs) + end |λ| + end script + + filter(isCycle, tail(inits(take(quot(n, 2), xs)))) +end repCycles + +-- cycleReport :: String -> [String] +on cycleReport(xs) + set reps to repCycles(xs) + + if isNull(reps) then + {xs, "(n/a)"} + else + {xs, |last|(reps)} + end if +end cycleReport + + +-- TEST ---------------------------------------------------------------------- +on run + set samples to {"1001110011", "1110111011", "0010010010", ¬ + "1010101010", "1111111111", "0100101101", "0100100", ¬ + "101", "11", "00", "1"} + + unlines(cons("Longest cycle:" & linefeed, ¬ + map(curry(intercalate)'s |λ|(" -> "), ¬ + map(cycleReport, samples)))) + +end run + + +-- GENERIC FUNCTIONS --------------------------------------------------------- + +-- concat :: [[a]] -> [a] | [String] -> String +on concat(xs) + if length of xs > 0 and class of (item 1 of xs) is string then + set acc to "" + else + set acc to {} + end if + repeat with i from 1 to length of xs + set acc to acc & item i of xs + end repeat + acc +end concat + +-- cons :: a -> [a] -> [a] +on cons(x, xs) + {x} & xs +end cons + +-- curry :: (Script|Handler) -> Script +on curry(f) + script + on |λ|(a) + script + on |λ|(b) + |λ|(a, b) of mReturn(f) + end |λ| + end script + end |λ| + end script +end curry + +-- filter :: (a -> Bool) -> [a] -> [a] +on filter(f, xs) + tell mReturn(f) + set lst to {} + set lng to length of xs + repeat with i from 1 to lng + set v to item i of xs + if |λ|(v, i, xs) then set end of lst to v + end repeat + return lst + end tell +end filter + +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl + +-- inits :: [a] -> [[a]] +-- inits :: String -> [String] +on inits(xs) + script elemInit + on |λ|(_, i, xs) + items 1 thru i of xs + end |λ| + end script + + script charInit + on |λ|(_, i, xs) + text 1 thru i of xs + end |λ| + end script + + if class of xs is string then + {""} & map(charInit, xs) + else + {{}} & map(elemInit, xs) + end if +end inits + +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + +-- last :: [a] -> a +on |last|(xs) + if length of xs > 0 then + item -1 of xs + else + missing value + end if +end |last| + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- isNull :: [a] -> Bool +on isNull(xs) + xs = {} +end isNull + +-- min :: Ord a => a -> a -> a +on min(x, y) + if y < x then + y + else + x + end if +end min + +-- quot :: Integral a => a -> a -> a +on quot(n, m) + n div m +end quot + +-- replicate :: Int -> a -> [a] +on replicate(n, a) + set out to {} + if n < 1 then return out + set dbl to {a} + + repeat while (n > 1) + if (n mod 2) > 0 then set out to out & dbl + set n to (n div 2) + set dbl to (dbl & dbl) + end repeat + return out & dbl +end replicate + +-- tail :: [a] -> [a] +on tail(xs) + if length of xs > 1 then + items 2 thru -1 of xs + else + {} + end if +end tail + +-- take :: Int -> [a] -> [a] +on take(n, xs) + if class of xs is string then + if n > 0 then + text 1 thru min(n, length of xs) of xs + else + "" + end if + else + if n > 0 then + items 1 thru min(n, length of xs) of xs + else + {} + end if + end if +end take + +-- takeCycle :: Int -> [a] -> [a] +on takeCycle(n, xs) + set lng to length of xs + if lng ≥ n then + set cycle to xs + else + set cycle to concat(replicate((n div lng) + 1, xs)) + end if + + if class of xs is string then + items 1 thru n of cycle as string + else + items 1 thru n of cycle + end if +end takeCycle + +-- unlines :: [String] -> String +on unlines(xs) + intercalate(linefeed, xs) +end unlines diff --git a/Task/Rep-string/Haskell/rep-string.hs b/Task/Rep-string/Haskell/rep-string-1.hs similarity index 100% rename from Task/Rep-string/Haskell/rep-string.hs rename to Task/Rep-string/Haskell/rep-string-1.hs diff --git a/Task/Rep-string/Haskell/rep-string-2.hs b/Task/Rep-string/Haskell/rep-string-2.hs new file mode 100644 index 0000000000..94338cd1c4 --- /dev/null +++ b/Task/Rep-string/Haskell/rep-string-2.hs @@ -0,0 +1,48 @@ +import Data.List (inits, intercalate, transpose) + +-- REP-CYCLES ----------------------------------------------------------------- +repCycles :: String -> [String] +repCycles cs = + let n = length cs + in filter ((cs ==) . take n . cycle) (tail $ inits (take (quot n 2) cs)) + +cycleReport :: String -> [String] +cycleReport xs = + let reps = repCycles xs + in [ xs + , if not (null reps) + then last reps + else "(n/a)" + ] + +-- TEST ----------------------------------------------------------------------- +main :: IO () +main = do + putStrLn "Longest cycles:\n" + putStrLn $ + unlines $ + table " -> " $ + cycleReport <$> + [ "1001110011" + , "1110111011" + , "0010010010" + , "1010101010" + , "1111111111" + , "0100101101" + , "0100100" + , "101" + , "11" + , "00" + , "1" + ] + +-- GENERIC -------------------------------------------------------------------- +table :: String -> [[String]] -> [String] +table delim rows = + intercalate delim <$> + transpose + ((\col -> + let width = (length $ maximum col) + justifyLeft n c s = take n (s ++ replicate n c) + in justifyLeft width ' ' <$> col) <$> + transpose rows) diff --git a/Task/Rep-string/JavaScript/rep-string.js b/Task/Rep-string/JavaScript/rep-string.js new file mode 100644 index 0000000000..b4a9e1695c --- /dev/null +++ b/Task/Rep-string/JavaScript/rep-string.js @@ -0,0 +1,105 @@ +(() => { + 'use strict'; + + // REP-CYCLES ------------------------------------------------------------- + + // repCycles :: String -> [String] + const repCycles = xs => { + const n = xs.length; + return filter( + cs => xs === takeCycle(n, cs), + map(concat, tail(inits(take(quot(n, 2), xs)))) + ); + }; + + // cycleReport :: String -> [String] + const cycleReport = xs => { + const reps = repCycles(xs); + return [xs, isNull(reps) ? '(n/a)' : last(reps)]; + }; + + + // GENERIC ---------------------------------------------------------------- + + // compose :: (b -> c) -> (a -> b) -> (a -> c) + const compose = (f, g) => x => f(g(x)); + + // concat :: [[a]] -> [a] | [String] -> String + const concat = xs => { + if (xs.length > 0) { + const unit = typeof xs[0] === 'string' ? '' : []; + return unit.concat.apply(unit, xs); + } else return []; + }; + + // cons :: a -> [a] -> [a] + const cons = (x, xs) => [x].concat(xs); + + // curry :: ((a, b) -> c) -> a -> b -> c + const curry = f => a => b => f(a, b); + + // filter :: (a -> Bool) -> [a] -> [a] + const filter = (f, xs) => xs.filter(f); + + // inits :: [a] -> [[a]] + // inits :: String -> [String] + const inits = xs => [ + [] + ] + .concat((typeof xs === 'string' ? xs.split('') : xs) + .map((_, i, lst) => lst.slice(0, i + 1))); + + // intercalate :: String -> [a] -> String + const intercalate = (s, xs) => xs.join(s); + + // last :: [a] -> a + const last = xs => xs.length ? xs.slice(-1)[0] : undefined; + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // isNull :: [a] -> Bool + const isNull = xs => (xs instanceof Array) ? xs.length < 1 : undefined; + + // Integral a => a -> a -> a + const quot = (n, m) => Math.floor(n / m); + + // replicate :: Int -> a -> [a] + const replicate = (n, a) => { + let v = [a], + o = []; + if (n < 1) return o; + while (n > 1) { + if (n & 1) o = o.concat(v); + n >>= 1; + v = v.concat(v); + } + return o.concat(v); + }; + + // tail :: [a] -> [a] + const tail = xs => xs.length ? xs.slice(1) : undefined; + + // take :: Int -> [a] -> [a] + const take = (n, xs) => xs.slice(0, n); + + // First n members of an infinite cycle of xs + // takeCycle :: Int -> [a] -> [a] + const takeCycle = (n, xs) => { + const lng = xs.length; + return concat((lng >= n ? xs : replicate(Math.ceil(n / lng), xs))) + .slice(0, n); + }; + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + + // TEST ------------------------------------------------------------------- + const samples = ["1001110011", "1110111011", "0010010010", "1010101010", + "1111111111", "0100101101", "0100100", "101", "11", "00", "1" + ]; + + return unlines(cons('Longest cycle:\n', + map(compose(curry(intercalate)(' -> '), cycleReport), samples))); +})(); diff --git a/Task/Rep-string/jq/rep-string-1.jq b/Task/Rep-string/Jq/rep-string-1.jq similarity index 100% rename from Task/Rep-string/jq/rep-string-1.jq rename to Task/Rep-string/Jq/rep-string-1.jq diff --git a/Task/Rep-string/jq/rep-string-2.jq b/Task/Rep-string/Jq/rep-string-2.jq similarity index 100% rename from Task/Rep-string/jq/rep-string-2.jq rename to Task/Rep-string/Jq/rep-string-2.jq diff --git a/Task/Rep-string/jq/rep-string-3.jq b/Task/Rep-string/Jq/rep-string-3.jq similarity index 100% rename from Task/Rep-string/jq/rep-string-3.jq rename to Task/Rep-string/Jq/rep-string-3.jq diff --git a/Task/Rep-string/Kotlin/rep-string.kotlin b/Task/Rep-string/Kotlin/rep-string.kotlin new file mode 100644 index 0000000000..fd0bd366d2 --- /dev/null +++ b/Task/Rep-string/Kotlin/rep-string.kotlin @@ -0,0 +1,37 @@ +// version 1.0.6 + +fun repString(s: String): MutableList { + val reps = mutableListOf() + if (s.length < 2) return reps + for (c in s) if (c != '0' && c != '1') throw IllegalArgumentException("Not a binary string") + for (len in 1..s.length / 2) { + val t = s.take(len) + val n = s.length / len + val r = s.length % len + val u = t.repeat(n) + t.take(r) + if (u == s) reps.add(t) + } + return reps +} + +fun main(args: Array) { + val strings = listOf( + "1001110011", + "1110111011", + "0010010010", + "1010101010", + "1111111111", + "0100101101", + "0100100", + "101", + "11", + "00", + "1" + ) + println("The (longest) rep-strings are:\n") + for (s in strings) { + val reps = repString(s) + val size = reps.size + println("${s.padStart(10)} -> ${if (size > 0) reps[size - 1] else "Not a rep-string"}") + } +} diff --git a/Task/Rep-string/Phix/rep-string.phix b/Task/Rep-string/Phix/rep-string.phix new file mode 100644 index 0000000000..88cf4a02b3 --- /dev/null +++ b/Task/Rep-string/Phix/rep-string.phix @@ -0,0 +1,38 @@ +function list_reps(string r) +sequence replist = {} +integer n = length(r) + for m=1 to floor(n/2) do + string s = r[1..m] + if join(repeat(s,floor(n/m)+1),"")[1..n]=r then + replist = append(replist,s) + end if + end for + return replist +end function + +constant tests = {"1001110011", + "1110111011", + "0010010010", + "1010101010", + "1111111111", + "0100101101", + "0100100", + "101", + "11", + "00", + "1"} + +for i=1 to length(tests) do + printf(1,"%s\n",{tests[i]}) + sequence replist = list_reps(tests[i]) + if length(replist)=0 then + printf(1,"not a rep-string.\n") + else + for j=1 to length(replist) do + string rj = replist[j], + pad = repeat(' ',length(rj)) + printf(1,"%s%s\n",{pad,rj}) + end for + end if + printf(1,"\n") +end for diff --git a/Task/Rep-string/PureBasic/rep-string.purebasic b/Task/Rep-string/PureBasic/rep-string.purebasic index 3f87319a1c..49a123d7dc 100644 --- a/Task/Rep-string/PureBasic/rep-string.purebasic +++ b/Task/Rep-string/PureBasic/rep-string.purebasic @@ -2,7 +2,7 @@ a$="1001110011"+#CRLF$+"1110111011"+#CRLF$+"0010010010"+#CRLF$+"1010101010"+#CRL "0100101101"+#CRLF$+"0100100" +#CRLF$+"101" +#CRLF$+"11" +#CRLF$+"00" +#CRLF$+ "1" +#CRLF$ -Define.i : OpenConsole() +OpenConsole() Procedure isRepStr(s1$,s2$) If Int(Len(s1$)/Len(s2$))>=2 : ProcedureReturn isRepStr(s1$,s2$+s2$) : EndIf diff --git a/Task/Rep-string/Zkl/rep-string-1.zkl b/Task/Rep-string/Zkl/rep-string-1.zkl new file mode 100644 index 0000000000..bbda66c33d --- /dev/null +++ b/Task/Rep-string/Zkl/rep-string-1.zkl @@ -0,0 +1,7 @@ +fcn repString(s){ + foreach n in ([s.len()/2+1..1,-1]){ + Walker.cycle(s[0,n]).pump(s.len(),String) : + if(_==s and n*2<=s.len()) return(n); + } + return(False) +} diff --git a/Task/Rep-string/Zkl/rep-string-2.zkl b/Task/Rep-string/Zkl/rep-string-2.zkl new file mode 100644 index 0000000000..9bc475e9cd --- /dev/null +++ b/Task/Rep-string/Zkl/rep-string-2.zkl @@ -0,0 +1,6 @@ +fcn repString(s){ + foreach n in ([s.len()/2..0,-1]){ + if(s.matches(s[n,*] + "*") and n*2<=s.len()) return(n); + } + return(False) +} diff --git a/Task/Rep-string/Zkl/rep-string-3.zkl b/Task/Rep-string/Zkl/rep-string-3.zkl new file mode 100644 index 0000000000..fdcc6f0239 --- /dev/null +++ b/Task/Rep-string/Zkl/rep-string-3.zkl @@ -0,0 +1,7 @@ +words:=("1001110011 1110111011 0010010010 1010101010 " + "1111111111 0100101101 0100100 101 11 00 1").split(" "); +foreach w in (words){ + if(not n:=repString2(w)) "No repeat in ".println(w); + else [0..*,n].tweak('wrap(z){ if(s:=w[z,n]) s else Void.Stop }) + .walk().concat(" ").println(); +} diff --git a/Task/Repeat-a-string/Aime/repeat-a-string.aime b/Task/Repeat-a-string/Aime/repeat-a-string.aime new file mode 100644 index 0000000000..4b45817ed3 --- /dev/null +++ b/Task/Repeat-a-string/Aime/repeat-a-string.aime @@ -0,0 +1 @@ +call_n(5, o_text, "ha"); diff --git a/Task/Repeat-a-string/AppleScript/repeat-a-string-2.applescript b/Task/Repeat-a-string/AppleScript/repeat-a-string-2.applescript index 14509c1f68..9d750e05c9 100644 --- a/Task/Repeat-a-string/AppleScript/repeat-a-string-2.applescript +++ b/Task/Repeat-a-string/AppleScript/repeat-a-string-2.applescript @@ -1,17 +1,20 @@ -on run - nreps("ha", 50000) -end run +replicate(5000, "ha") +-- Repetition by 'Egyptian multiplication' - +-- progressively doubling a list, appending +-- stages of doubling to an accumulator where needed for +-- binary assembly of a target length. --- String -> Int -> String -on nreps(s, n) - set o to "" - if n < 1 then return o +-- replicate :: Int -> String -> String +on replicate(n, s) + set out to "" + if n < 1 then return out + set dbl to s repeat while (n > 1) - if (n mod 2) > 0 then set o to o & s + if (n mod 2) > 0 then set out to out & dbl set n to (n div 2) - set s to (s & s) + set dbl to (dbl & dbl) end repeat - return o & s -end nreps + return out & dbl +end replicate diff --git a/Task/Repeat-a-string/Beeswax/repeat-a-string.beeswax b/Task/Repeat-a-string/Beeswax/repeat-a-string.beeswax new file mode 100644 index 0000000000..b938b8b984 --- /dev/null +++ b/Task/Repeat-a-string/Beeswax/repeat-a-string.beeswax @@ -0,0 +1,3 @@ + p < + p0~1<}~< d@< +_VT@1~>yg~9PKd@M'd; diff --git a/Task/Repeat-a-string/Elena/repeat-a-string.elena b/Task/Repeat-a-string/Elena/repeat-a-string.elena index b029d5ee7b..f1a4f5a11f 100644 --- a/Task/Repeat-a-string/Elena/repeat-a-string.elena +++ b/Task/Repeat-a-string/Elena/repeat-a-string.elena @@ -1,8 +1,7 @@ -#import system. -#import system'routines. -#import extensions. +import system'routines. +import extensions. -#symbol program = +program = [ - #var s := 0 repeat &till:5 &each: n [ "ha" ] summarize:(String new) literal. + var s := 0 till:5 repeat(:n)( "ha" ); summarize(String new); literal. ]. diff --git a/Task/Repeat-a-string/Gambas/repeat-a-string.gambas b/Task/Repeat-a-string/Gambas/repeat-a-string.gambas new file mode 100644 index 0000000000..dd8591384b --- /dev/null +++ b/Task/Repeat-a-string/Gambas/repeat-a-string.gambas @@ -0,0 +1,5 @@ +Public Sub Main() + +Print String$(5, "ha") + +End diff --git a/Task/Repeat-a-string/Haskell/repeat-a-string-6.hs b/Task/Repeat-a-string/Haskell/repeat-a-string-6.hs new file mode 100644 index 0000000000..530bac0aab --- /dev/null +++ b/Task/Repeat-a-string/Haskell/repeat-a-string-6.hs @@ -0,0 +1,9 @@ +repString :: String -> Int -> String +repString s n = + let rep x = xs + where + xs = mappend x xs + in take (n * length s) (rep s) + +main :: IO () +main = print $ repString "ha" 5 diff --git a/Task/Repeat-a-string/Haskell/repeat-a-string-7.hs b/Task/Repeat-a-string/Haskell/repeat-a-string-7.hs new file mode 100644 index 0000000000..cf1cc12ea5 --- /dev/null +++ b/Task/Repeat-a-string/Haskell/repeat-a-string-7.hs @@ -0,0 +1,25 @@ +import Data.Tuple (swap) +import Data.List (unfoldr) +import Control.Monad (join) + +-- BY RHIND PAPYRUS 'EGYPTIAN' OR 'ETHIOPIAN' MULTIPLICATION ------------------ +repString :: Int -> String -> String +repString n s = + foldr + (\(d, x) a -> + if d > 0 -- Is this power of 2 needed for the binary recomposition ? + then mappend a x + else a) + mempty $ + zip + (unfoldr + (\h -> + if h > 0 + then Just $ swap (quotRem h 2) -- Binary decomposition of n + else Nothing) + n) + (iterate (join mappend) s) -- Iterative duplication ( mappend to self ) + +-- TEST ----------------------------------------------------------------------- +main :: IO () +main = print $ repString 500 "ha" diff --git a/Task/Repeat-a-string/Java/repeat-a-string-1.java b/Task/Repeat-a-string/Java/repeat-a-string-1.java index f77d853a7b..dca6fb2866 100644 --- a/Task/Repeat-a-string/Java/repeat-a-string-1.java +++ b/Task/Repeat-a-string/Java/repeat-a-string-1.java @@ -1,9 +1,10 @@ -public static String repeat(String str, int times){ - StringBuilder ret = new StringBuilder(); - for(int i = 0;i < times;i++) ret.append(str); - return ret.toString(); +public static String repeat(String str, int times) { + StringBuilder sb = new StringBuilder(str.length() * times); + for (int i = 0; i < times; i++) + sb.append(str); + return sb.toString(); } -public static void main(String[] args){ - System.out.println(repeat("ha", 5)); +public static void main(String[] args) { + System.out.println(repeat("ha", 5)); } diff --git a/Task/Repeat-a-string/Java/repeat-a-string-2.java b/Task/Repeat-a-string/Java/repeat-a-string-2.java index a843ebc700..c5dd7aa274 100644 --- a/Task/Repeat-a-string/Java/repeat-a-string-2.java +++ b/Task/Repeat-a-string/Java/repeat-a-string-2.java @@ -1,3 +1,3 @@ -public static String repeat(String str, int times){ +public static String repeat(String str, int times) { return new String(new char[times]).replace("\0", str); } diff --git a/Task/Repeat-a-string/JavaScript/repeat-a-string-3.js b/Task/Repeat-a-string/JavaScript/repeat-a-string-3.js index 1a3b1464b6..9874e315e8 100644 --- a/Task/Repeat-a-string/JavaScript/repeat-a-string-3.js +++ b/Task/Repeat-a-string/JavaScript/repeat-a-string-3.js @@ -1,12 +1,19 @@ -function nreps(s, n) { - var o = ''; - if (n < 1) return o; - while (n > 1) { - if (n & 1) o += s; - n >>= 1; - s += s; - } - return o + s; -} +(() => { + 'use strict'; -nreps('ha', 50000); + // replicate :: Int -> String -> String + const replicate = (n, s) => { + let v = [s], + o = []; + if (n < 1) return o; + while (n > 1) { + if (n & 1) o = o + v; + n >>= 1; + v = v + v; + } + return o.concat(v); + }; + + + return replicate(5000, "ha") +})(); diff --git a/Task/Repeat-a-string/JavaScript/repeat-a-string-4.js b/Task/Repeat-a-string/JavaScript/repeat-a-string-4.js new file mode 100644 index 0000000000..c509e96bcc --- /dev/null +++ b/Task/Repeat-a-string/JavaScript/repeat-a-string-4.js @@ -0,0 +1,27 @@ +(() => { + 'use strict'; + + // repeat :: Int -> String -> String + const repeat = (n, s) => + concat(replicate(n, s)); + + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // concat :: [[a]] -> [a] | [String] -> String + const concat = xs => + xs.length > 0 ? (() => { + const unit = typeof xs[0] === 'string' ? '' : []; + return unit.concat.apply(unit, xs); + })() : []; + + // replicate :: Int -> a -> [a] + const replicate = (n, x) => + Array.from({ + length: n + }, () => x); + + + // TEST ------------------------------------------------------------------- + return repeat(5, 'ha'); +})(); diff --git a/Task/Repeat-a-string/jq/repeat-a-string.jq b/Task/Repeat-a-string/Jq/repeat-a-string.jq similarity index 100% rename from Task/Repeat-a-string/jq/repeat-a-string.jq rename to Task/Repeat-a-string/Jq/repeat-a-string.jq diff --git a/Task/Repeat-a-string/Kotlin/repeat-a-string.kotlin b/Task/Repeat-a-string/Kotlin/repeat-a-string-1.kotlin similarity index 100% rename from Task/Repeat-a-string/Kotlin/repeat-a-string.kotlin rename to Task/Repeat-a-string/Kotlin/repeat-a-string-1.kotlin diff --git a/Task/Repeat-a-string/Kotlin/repeat-a-string-2.kotlin b/Task/Repeat-a-string/Kotlin/repeat-a-string-2.kotlin new file mode 100644 index 0000000000..562d9cbe78 --- /dev/null +++ b/Task/Repeat-a-string/Kotlin/repeat-a-string-2.kotlin @@ -0,0 +1,3 @@ +operator fun String.times(n: Int) = this.repeat(n) + +fun main(args: Array) = println("ha" * 5) diff --git a/Task/Repeat-a-string/Nimrod/repeat-a-string.nimrod b/Task/Repeat-a-string/Nimrod/repeat-a-string.nimrod deleted file mode 100644 index 5e600de07c..0000000000 --- a/Task/Repeat-a-string/Nimrod/repeat-a-string.nimrod +++ /dev/null @@ -1,2 +0,0 @@ -import strutils -repeatStr(5, "ha") diff --git a/Task/Repeat-a-string/Pure/repeat-a-string.pure b/Task/Repeat-a-string/Pure/repeat-a-string-1.pure similarity index 100% rename from Task/Repeat-a-string/Pure/repeat-a-string.pure rename to Task/Repeat-a-string/Pure/repeat-a-string-1.pure diff --git a/Task/Repeat-a-string/Pure/repeat-a-string-2.pure b/Task/Repeat-a-string/Pure/repeat-a-string-2.pure new file mode 100644 index 0000000000..9a6b58a395 --- /dev/null +++ b/Task/Repeat-a-string/Pure/repeat-a-string-2.pure @@ -0,0 +1 @@ +str_repeat n::int s::string = string $ take n $ cycle (s:[]); diff --git a/Task/Repeat-a-string/Racket/repeat-a-string-3.rkt b/Task/Repeat-a-string/Racket/repeat-a-string-3.rkt deleted file mode 100644 index bf26460c17..0000000000 --- a/Task/Repeat-a-string/Racket/repeat-a-string-3.rkt +++ /dev/null @@ -1 +0,0 @@ -(make-string 5 #\*) => "*****" diff --git a/Task/Repeat-a-string/Ruby/repeat-a-string-1.rb b/Task/Repeat-a-string/Ruby/repeat-a-string-1.rb deleted file mode 100644 index 0cf142bf02..0000000000 --- a/Task/Repeat-a-string/Ruby/repeat-a-string-1.rb +++ /dev/null @@ -1 +0,0 @@ -"ha" * 5 # ==> "hahahahaha" diff --git a/Task/Repeat-a-string/Ruby/repeat-a-string-2.rb b/Task/Repeat-a-string/Ruby/repeat-a-string-2.rb deleted file mode 100644 index 57ea405b5e..0000000000 --- a/Task/Repeat-a-string/Ruby/repeat-a-string-2.rb +++ /dev/null @@ -1 +0,0 @@ -5 * "ha" # TypeError: String can't be coerced into Fixnum diff --git a/Task/Repeat-a-string/Rust/repeat-a-string.rust b/Task/Repeat-a-string/Rust/repeat-a-string-1.rust similarity index 100% rename from Task/Repeat-a-string/Rust/repeat-a-string.rust rename to Task/Repeat-a-string/Rust/repeat-a-string-1.rust diff --git a/Task/Repeat-a-string/Rust/repeat-a-string-2.rust b/Task/Repeat-a-string/Rust/repeat-a-string-2.rust new file mode 100644 index 0000000000..99e547ec55 --- /dev/null +++ b/Task/Repeat-a-string/Rust/repeat-a-string-2.rust @@ -0,0 +1 @@ +"ha".repeat(5); // ==> "hahahahaha" diff --git a/Task/Repeat-a-string/Sed/repeat-a-string.sed b/Task/Repeat-a-string/Sed/repeat-a-string.sed new file mode 100644 index 0000000000..3e0c79df77 --- /dev/null +++ b/Task/Repeat-a-string/Sed/repeat-a-string.sed @@ -0,0 +1,2 @@ +$ echo ha | sed 's/.*/&&&&&/' +hahahahaha diff --git a/Task/Repeat-a-string/Sinclair-ZX81-BASIC/repeat-a-string.sinclair b/Task/Repeat-a-string/Sinclair-ZX81-BASIC/repeat-a-string.sinclair new file mode 100644 index 0000000000..cb3ea5e8cf --- /dev/null +++ b/Task/Repeat-a-string/Sinclair-ZX81-BASIC/repeat-a-string.sinclair @@ -0,0 +1,10 @@ + 10 LET S$="HA" + 20 LET N=5 + 30 GOSUB 60 + 40 PRINT T$ + 50 STOP + 60 LET T$="" + 70 FOR I=1 TO N + 80 LET T$=T$+S$ + 90 NEXT I +100 RETURN diff --git a/Task/Repeat-a-string/Stata/repeat-a-string.stata b/Task/Repeat-a-string/Stata/repeat-a-string.stata new file mode 100644 index 0000000000..1fcbaf1809 --- /dev/null +++ b/Task/Repeat-a-string/Stata/repeat-a-string.stata @@ -0,0 +1,4 @@ +. scalar a="ha" +. scalar b=a*5 +. display b +hahahahaha diff --git a/Task/Repeat-a-string/Zkl/repeat-a-string.zkl b/Task/Repeat-a-string/Zkl/repeat-a-string.zkl new file mode 100644 index 0000000000..72f92c1d97 --- /dev/null +++ b/Task/Repeat-a-string/Zkl/repeat-a-string.zkl @@ -0,0 +1 @@ +"ha" * 5 # --> "hahahahaha" diff --git a/Task/Resistor-mesh/00DESCRIPTION b/Task/Resistor-mesh/00DESCRIPTION index a81b450dc3..9a8c3326e6 100644 --- a/Task/Resistor-mesh/00DESCRIPTION +++ b/Task/Resistor-mesh/00DESCRIPTION @@ -2,7 +2,7 @@ ;Task: Given   10×10   grid nodes   (as shown in the image)   interconnected by     resistors as shown, -
    find the resistance between point   '''A'''   and   '''B'''. +
    find the resistance between points   '''A'''   and   '''B'''. ;See also: diff --git a/Task/Resistor-mesh/Kotlin/resistor-mesh.kotlin b/Task/Resistor-mesh/Kotlin/resistor-mesh.kotlin new file mode 100644 index 0000000000..41e2ea9192 --- /dev/null +++ b/Task/Resistor-mesh/Kotlin/resistor-mesh.kotlin @@ -0,0 +1,62 @@ +// version 1.1.4-3 + +typealias List2D = List> + +const val S = 10 + +class Node(var v: Double, var fixed: Int) + +fun setBoundary(m: List2D) { + m[1][1].v = 1.0; m[1][1].fixed = 1 + m[6][7].v = -1.0; m[6][7].fixed = -1 +} + +fun calcDiff(m: List2D, d: List2D, w: Int, h: Int): Double { + var total = 0.0 + for (i in 0 until h) { + for (j in 0 until w) { + var v = 0.0 + var n = 0 + if (i > 0) { v += m[i - 1][j].v; n++ } + if (j > 0) { v += m[i][j - 1].v; n++ } + if (i + 1 < h) { v += m[i + 1][j].v; n++ } + if (j + 1 < w) { v += m[i][j + 1].v; n++ } + v = m[i][j].v - v / n + d[i][j].v = v + if (m[i][j].fixed == 0) total += v * v + } + } + return total +} + +fun iter(m: List2D, w: Int, h: Int): Double { + val d = List(h) { List(w) { Node(0.0, 0) } } + val cur = DoubleArray(3) + var diff = 1e10 + + while (diff > 1e-24) { + setBoundary(m) + diff = calcDiff(m, d, w, h) + for (i in 0 until h) { + for (j in 0 until w) m[i][j].v -= d[i][j].v + } + } + + for (i in 0 until h) { + for (j in 0 until w) { + var k = 0 + if (i != 0) k++ + if (j != 0) k++ + if (i < h - 1) k++ + if (j < w - 1) k++ + cur[m[i][j].fixed + 1] += d[i][j].v * k + } + } + return (cur[2] - cur[0]) / 2.0 +} + +fun main(args: Array) { + val mesh = List(S) { List(S) { Node(0.0, 0) } } + val r = 2.0 / iter(mesh, S, S) + println("R = $r") +} diff --git a/Task/Resistor-mesh/REXX/resistor-mesh.rexx b/Task/Resistor-mesh/REXX/resistor-mesh.rexx index c51e51f245..3d3a550d6b 100644 --- a/Task/Resistor-mesh/REXX/resistor-mesh.rexx +++ b/Task/Resistor-mesh/REXX/resistor-mesh.rexx @@ -1,46 +1,45 @@ /*REXX program calculates the resistance between any two points on a resister grid.*/ -numeric digits 20 /*use moderate decimal digs (precision)*/ -minVal = (1'e-' || (digits()*2)) / 1 /*calculate the threshold minimul value*/ -if 1=='f1'x then ohms = 'ohms' /*EBCDIC machine? Then use 'ohms'. */ - else ohms = 'ea'x /* ASCII " " " Greek Ω.*/ -parse arg high wide Arow Acol Brow Bcol . /*obtain optional arguments from the CL*/ +if 2=='f2'x then ohms = "ohms" /*EBCDIC machine? Then use 'ohms'. */ + else ohms = "Ω" /* ASCII " " " Greek Ω.*/ +parse arg high wide Arow Acol Brow Bcol digs . /*obtain optional arguments from the CL*/ if high=='' | high=="," then high=10 /*Not specified? Then use the default.*/ if wide=='' | wide=="," then wide=10 /* " " " " " " */ if Arow=='' | Arow=="," then Arow= 2 /* " " " " " " */ if Acol=='' | Acol=="," then Acol= 2 /* " " " " " " */ if Brow=='' | Brow=="," then Brow= 7 /* " " " " " " */ if Bcol=='' | Bcol=="," then Bcol= 8 /* " " " " " " */ -say ' minimum value = ' translate(format(minVal, , , , 0), "e", 'E'); say -say ' resistor mesh is of size: ' wide "wide, " high 'high' ; say +if digs=='' | digs=="," then digs=20 /* " " " " " " */ +numeric digits digs /*use moderate decimal digs (precision)*/ +minVal = 1'e-' || (digs*2) /*calculate the threshold minimul value*/ +say ' minimum value is ' format(minVal,,,,0) " using " digs ' decimal digits'; say +say ' resistor mesh size is: ' wide "wide, " high 'high' ; say say ' point A is at (row,col): ' Arow"," Acol say ' point B is at (row,col): ' Brow"," Bcol -@.=0; cell.=1 - do until $ <= minVal; v = 0 - @.Arow.Acol = +1 ; cell.Arow.Acol = 0 - @.Brow.Bcol = -1 ; cell.Brow.Bcol = 0 - $=0 - do i=1 for high; im=i - 1; ip=i + 1 - do j=1 for wide; jm=j - 1; jp=j + 1; n=0; v=0 - if i\==1 then do; v=v + @.im.j; n=n + 1; end - if j\==1 then do; v=v + @.i.jm; n=n + 1; end - if i
    diff --git a/Task/Respond-to-an-unknown-method-call/Elena/respond-to-an-unknown-method-call.elena b/Task/Respond-to-an-unknown-method-call/Elena/respond-to-an-unknown-method-call.elena new file mode 100644 index 0000000000..72b69f9965 --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Elena/respond-to-an-unknown-method-call.elena @@ -0,0 +1,28 @@ +import extensions. + +class Example +{ + generic + [ + console printLine($subject," was invoked"). + ] + + generic : x + [ + console printLine($subject,"(",x,") was invoked"). + ] + + generic : x : y + [ + console printLine($subject,"(",x,",",y,") was invoked"). + ] +} + +program = +[ + var o := Example new. + + o foo. + o bar(1). + o someMethod(1,2). +]. diff --git a/Task/Respond-to-an-unknown-method-call/Go/respond-to-an-unknown-method-call-1.go b/Task/Respond-to-an-unknown-method-call/Go/respond-to-an-unknown-method-call-1.go deleted file mode 100644 index 9d3b3b9f14..0000000000 --- a/Task/Respond-to-an-unknown-method-call/Go/respond-to-an-unknown-method-call-1.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "fmt" - "reflect" -) - -type example struct{} - -func (example) Foo() int { - return 42 -} - -// a method to call another method by name -func (e example) CallMethod(n string) int { - if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() { - // it's known. call it. - return int(m.Call(nil)[0].Int()) - } - // otherwise it's unknown. handle as needed. - fmt.Println("Unknown method:", n) - return 0 -} - -func main() { - var e example - fmt.Println(e.CallMethod("Foo")) - fmt.Println(e.CallMethod("Bar")) -} diff --git a/Task/Respond-to-an-unknown-method-call/Go/respond-to-an-unknown-method-call-2.go b/Task/Respond-to-an-unknown-method-call/Go/respond-to-an-unknown-method-call-2.go deleted file mode 100644 index 80eae5408a..0000000000 --- a/Task/Respond-to-an-unknown-method-call/Go/respond-to-an-unknown-method-call-2.go +++ /dev/null @@ -1,16 +0,0 @@ -procedure DynMethod(obj,meth,arglist[]) - local m - - if not (type(obj) ? ( tab(find("__")), ="__state", pos(0))) then - runerr(205,obj) # invalid value - not an object - - if meth == ("initially"|"UndefinedMethod") then fail # avoid protected - - m := obj.__m # get methods list - if fieldnames(m) == meth then # method exists? - return m[meth]!push(copy(arglist),obj) # ... call it - else - if fieldnames(m) == "UndefinedMethod" then # handler exists? - return obj.UndefinedMethod!arglist # ... call it - else runerr(207,obj) # error invalid method (i.e. field) -end diff --git a/Task/Respond-to-an-unknown-method-call/Go/respond-to-an-unknown-method-call-3.go b/Task/Respond-to-an-unknown-method-call/Go/respond-to-an-unknown-method-call-3.go deleted file mode 100644 index 738e8ab7aa..0000000000 --- a/Task/Respond-to-an-unknown-method-call/Go/respond-to-an-unknown-method-call-3.go +++ /dev/null @@ -1,31 +0,0 @@ -procedure main() - x := foo() - y := foo2() - - x.a() # example of normal method call - DynMethod(x,"a") # using DynMethod - DynMethod(x,"simplydoesntexist") # results in error - DynMethod(y,"simplydoesntexist") # catches error - DynMethod(y,"simplydoesntexist",1,2,3,4,5) # with parameters -end - -class foo(A) # sample class and methods - method a(p1) - l1 := p1 - return - end - method b(p2) - l2 := p2 - return - end - initially - i1 := 0 - return -end - -class foo2 : foo (A) - method UndefinedMethod(x[]) # Undefined Method handler - write(&errout,"You called an undefinded method of this object.") - return - end -end diff --git a/Task/Respond-to-an-unknown-method-call/Kotlin/respond-to-an-unknown-method-call.kotlin b/Task/Respond-to-an-unknown-method-call/Kotlin/respond-to-an-unknown-method-call.kotlin new file mode 100644 index 0000000000..38d3c0b6ec --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Kotlin/respond-to-an-unknown-method-call.kotlin @@ -0,0 +1,18 @@ +// Kotlin JS version 1.1.4-3 + +class C // class with no methods + +fun main(args: Array) { + val c: dynamic = C() // 'dynamic' turns off compile time checks + try { + c.foo() // the compiler now allows this call even though foo() is undefined + } + catch (t: Throwable) { + if (t.message == "undefined is not a function") { + println("Class C does not have a method called foo") + } + else { + println(t.message) + } + } +} diff --git a/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call-1.m b/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call-1.m deleted file mode 100644 index a3e25297b6..0000000000 --- a/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call-1.m +++ /dev/null @@ -1,59 +0,0 @@ -#include - -// The methods need to be declared somewhere -@interface Dummy : NSObject { } -- (void)grill; -- (void)ding:(NSString *)s; -@end - -@interface Example : NSObject { } -- (void)foo; -- (void)bar; -@end - -@implementation Example -- (void)foo { - NSLog(@"this is foo"); -} -- (void)bar { - NSLog(@"this is bar"); -} -- (void)forwardInvocation:(NSInvocation *)inv { - NSLog(@"tried to handle unknown method %@", NSStringFromSelector([inv selector])); - unsigned n = [[inv methodSignature] numberOfArguments]; - unsigned i; - for (i = 0; i < n-2; i++) { // first two arguments are the object and selector - id arg; // we assume that all arguments are objects - [inv getArgument:&arg atIndex:i+2]; - NSLog(@"argument #%u: %@", i, arg); - } -} -// forwardInvocation: does not work without methodSignatureForSelector: -- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { - int numArgs = [[NSStringFromSelector(aSelector) componentsSeparatedByString:@":"] count] - 1; - // we assume that all arguments are objects - // The type encoding is "v@:@@@...", where "v" is the return type, void - // "@" is the receiver, object type; ":" is the selector of the current method; - // and each "@" after corresponds to an object argument - return [NSMethodSignature signatureWithObjCTypes: - [[@"v@:" stringByPaddingToLength:numArgs+3 withString:@"@" startingAtIndex:0] UTF8String]]; -} -@end - -int main() -{ - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - id example = [[Example alloc] init]; - - [example foo]; // prints "this is foo" - [example bar]; // prints "this is bar" - [example grill]; // prints "tried to handle unknown method grill" - [example ding:@"dong"]; // prints "tried to handle unknown method ding:" - // prints "argument #0: dong" - [example release]; - - [pool release]; - - return 0; -} diff --git a/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call-2.m b/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call-2.m deleted file mode 100644 index da7ddd2da2..0000000000 --- a/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call-2.m +++ /dev/null @@ -1,57 +0,0 @@ -#include - -// The methods need to be declared somewhere -@interface Dummy : NSObject { } -- (void)grill; -- (void)ding:(NSString *)s; -@end - -@interface Example : NSObject { } -- (void)foo; -- (void)bar; -@end - -@implementation Example -- (void)foo { - NSLog(@"this is foo"); -} -- (void)bar { - NSLog(@"this is bar"); -} -- (void)forwardInvocation:(NSInvocation *)inv { - NSLog(@"tried to handle unknown method %@", NSStringFromSelector([inv selector])); - unsigned n = [[inv methodSignature] numberOfArguments]; - unsigned i; - for (i = 0; i < n-2; i++) { // first two arguments are the object and selector - id __unsafe_unretained arg; // we assume that all arguments are objects - [inv getArgument:&arg atIndex:i+2]; - NSLog(@"argument #%u: %@", i, arg); - } -} -// forwardInvocation: does not work without methodSignatureForSelector: -- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { - int numArgs = [[NSStringFromSelector(aSelector) componentsSeparatedByString:@":"] count] - 1; - // we assume that all arguments are objects - // The type encoding is "v@:@@@...", where "v" is the return type, void - // "@" is the receiver, object type; ":" is the selector of the current method; - // and each "@" after corresponds to an object argument - return [NSMethodSignature signatureWithObjCTypes: - [[@"v@:" stringByPaddingToLength:numArgs+3 withString:@"@" startingAtIndex:0] UTF8String]]; -} -@end - -int main() -{ - @autoreleasepool { - - id example = [[Example alloc] init]; - - [example foo]; // prints "this is foo" - [example bar]; // prints "this is bar" - [example grill]; // prints "tried to handle unknown method grill" - [example ding:@"dong"]; // prints "tried to handle unknown method ding:" - // prints "argument #0: dong" - - } - return 0; -} diff --git a/Task/Respond-to-an-unknown-method-call/OoRexx/respond-to-an-unknown-method-call.rexx b/Task/Respond-to-an-unknown-method-call/OoRexx/respond-to-an-unknown-method-call.rexx new file mode 100644 index 0000000000..de3474b033 --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/OoRexx/respond-to-an-unknown-method-call.rexx @@ -0,0 +1,7 @@ +u = .unknown~new +u~foo(1, 2, 3) + +::class unknown +::method unknown + use arg name, args + say "Unknown method" name "invoked with arguments:" args~tostring('l', ', diff --git a/Task/Respond-to-an-unknown-method-call/Zkl/respond-to-an-unknown-method-call.zkl b/Task/Respond-to-an-unknown-method-call/Zkl/respond-to-an-unknown-method-call.zkl new file mode 100644 index 0000000000..6245d611f4 --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Zkl/respond-to-an-unknown-method-call.zkl @@ -0,0 +1,3 @@ +class C{ fcn __notFound(name){println(name," not in ",self); bar} + fcn bar{vm.arglist.println("***")} +} diff --git a/Task/Return-multiple-values/Agena/return-multiple-values.agena b/Task/Return-multiple-values/Agena/return-multiple-values.agena new file mode 100644 index 0000000000..dcd91148cd --- /dev/null +++ b/Task/Return-multiple-values/Agena/return-multiple-values.agena @@ -0,0 +1,9 @@ +# define a function returning three values +mv := proc() is + return 1, 2, "three" +end ; # mv + +scope # test the mv() proc + local a, b, c := mv(); + print( c, b, a ) +epocs diff --git a/Task/Return-multiple-values/BASIC/return-multiple-values.basic b/Task/Return-multiple-values/BASIC/return-multiple-values.basic new file mode 100644 index 0000000000..e1a4265eae --- /dev/null +++ b/Task/Return-multiple-values/BASIC/return-multiple-values.basic @@ -0,0 +1,19 @@ +' Return multiple values +RECORD multi + LOCAL num + LOCAL s$[2] +END RECORD + +FUNCTION f(n) TYPE multi_type + LOCAL r = { 0 } TYPE multi_type + r.num = n + r.s$[0] = "Hitchhiker's Guide" + r.s$[1] = "Douglas Adams" + RETURN r +END FUNCTION + +DECLARE rec TYPE multi_type +rec = f(42) +PRINT rec.num +PRINT rec.s$[0] +PRINT rec.s$[1] diff --git a/Task/Return-multiple-values/D/return-multiple-values.d b/Task/Return-multiple-values/D/return-multiple-values.d index 904fde8643..5e81920cf9 100644 --- a/Task/Return-multiple-values/D/return-multiple-values.d +++ b/Task/Return-multiple-values/D/return-multiple-values.d @@ -1,14 +1,28 @@ import std.stdio, std.typecons, std.algorithm; + +mixin template ret(string z) { + mixin({ + string res; + + auto r = z.split(" = "); + auto m = r[0].split(", "); + auto s = m.join("_"); + + res ~= "auto " ~ s ~ " = " ~ r[1] ~ ";"; + foreach(i, n; m){ + res ~= "auto " ~ n ~ " = " ~ s ~ "[" ~ i.to!string ~ "];\n"; + } + return res; + }()); +} + auto addSub(T)(T x, T y) { return tuple(x + y, x - y); } -alias _(T...) = T; // костыль - void main() { - int a, b; - _!(a, b) = addSub(33, 12); // _!(a, b) = [33, 12].fold!("a+b","a-b"); + mixin ret!q{ a, b = addSub(33, 12) }; writefln("33 + 12 = %d\n33 - 12 = %d", a, b); } diff --git a/Task/Return-multiple-values/Elena/return-multiple-values.elena b/Task/Return-multiple-values/Elena/return-multiple-values.elena new file mode 100644 index 0000000000..97f4ccb3a3 --- /dev/null +++ b/Task/Return-multiple-values/Elena/return-multiple-values.elena @@ -0,0 +1,24 @@ +import system'routines. +import extensions. + +extension op +{ + MinMax ref:minVal ref:maxVal + [ + var ordered := self ascendant. + + minVal object := ordered firstMember. + maxVal object := ordered lastMember. + ] +} + +program = +[ + var values := (4, 51, 1, -3, 3, 6, 8, 26, 2, 4). + var min := 0. + var max := 0. + + values MinMax ref:min ref:max. + + console printLine("Min: ",min," Max: ",max). +]. diff --git a/Task/Return-multiple-values/FutureBasic/return-multiple-values-4.futurebasic b/Task/Return-multiple-values/FutureBasic/return-multiple-values-4.futurebasic index cd7411ce5e..bf8127abcc 100644 --- a/Task/Return-multiple-values/FutureBasic/return-multiple-values-4.futurebasic +++ b/Task/Return-multiple-values/FutureBasic/return-multiple-values-4.futurebasic @@ -1,7 +1,7 @@ include "ConsoleWindow" begin globals -// An FB container can hold up to 2GB of data, contigent on system memory +// An FB container can hold up to 2GB of data, contingent on system memory dim as container gC1, gC2 end globals diff --git a/Task/Return-multiple-values/jq/return-multiple-values-1.jq b/Task/Return-multiple-values/Jq/return-multiple-values-1.jq similarity index 100% rename from Task/Return-multiple-values/jq/return-multiple-values-1.jq rename to Task/Return-multiple-values/Jq/return-multiple-values-1.jq diff --git a/Task/Return-multiple-values/jq/return-multiple-values-2.jq b/Task/Return-multiple-values/Jq/return-multiple-values-2.jq similarity index 100% rename from Task/Return-multiple-values/jq/return-multiple-values-2.jq rename to Task/Return-multiple-values/Jq/return-multiple-values-2.jq diff --git a/Task/Return-multiple-values/Kotlin/return-multiple-values.kotlin b/Task/Return-multiple-values/Kotlin/return-multiple-values.kotlin new file mode 100644 index 0000000000..838cd6813d --- /dev/null +++ b/Task/Return-multiple-values/Kotlin/return-multiple-values.kotlin @@ -0,0 +1,11 @@ +// version 1.0.6 + +/* implicitly returns a Pair*/ +fun minmax(ia: IntArray) = ia.min() to ia.max() + +fun main(args: Array) { + val ia = intArrayOf(17, 88, 9, 33, 4, 987, -10, 2) + val(min, max) = minmax(ia) // destructuring declaration + println("The smallest number is $min") + println("The largest number is $max") +} diff --git a/Task/Return-multiple-values/OoRexx/return-multiple-values.rexx b/Task/Return-multiple-values/OoRexx/return-multiple-values.rexx new file mode 100644 index 0000000000..1ceb7ff744 --- /dev/null +++ b/Task/Return-multiple-values/OoRexx/return-multiple-values.rexx @@ -0,0 +1,6 @@ +r = addsub(3, 4) +say r[1] r[2] + +::routine addsub + use arg x, y + return .array~of(x + y, x - y) diff --git a/Task/Return-multiple-values/PHP/return-multiple-values-3.php b/Task/Return-multiple-values/PHP/return-multiple-values-3.php index 8e42142995..15bdb6c36d 100644 --- a/Task/Return-multiple-values/PHP/return-multiple-values-3.php +++ b/Task/Return-multiple-values/PHP/return-multiple-values-3.php @@ -1,6 +1,6 @@ function multiples($param1, &$param2) { if ($param1 == 'bob') { - $param2 = 'is your grandmonther'; + $param2 = 'is your grandmother'; return true; } diff --git a/Task/Return-multiple-values/REXX/return-multiple-values.rexx b/Task/Return-multiple-values/REXX/return-multiple-values.rexx index 4a5fa825cc..41b4cdae52 100644 --- a/Task/Return-multiple-values/REXX/return-multiple-values.rexx +++ b/Task/Return-multiple-values/REXX/return-multiple-values.rexx @@ -1,32 +1,21 @@ -/*REXX program shows examples of multiple RETURN values from a function.*/ -numeric digits 70 /*default is: NUMERIC DIGITS 9 */ -arg a b /*get 2 numbers from comand line.*/ -say ' a =' a /*display the first number. */ -say ' b =' b /* " " second " */ -say copies('=',50) /*display a separator line. */ - -z=giveMeBackStuff(a,b) /*call function: giveMeBackStuff */ - -parse var z sum dif mod div idiv prod pow /*get the returned values,*/ - prod=word(z,6) /*obtain an alternate way.*/ -say ' + =' sum -say ' - =' dif -say '// =' mod -say ' / =' div -say ' % =' idiv -say ' * =' prod -say '** =' pow -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────giveMeBackStuff subroutine──────────*/ -giveMeBackStuff: procedure; parse arg x,y - addition = x+y - subtract = x-y - modulus = x//y - divide = x/y - intDiv = x%y - multiply = x*y - power = x**y -return addition subtract modulus divide intDiv multiply power -/*──────────────────────────────────giveMeBackStuff2 subroutine─────────*/ -giveMeBackStuff2: procedure; parse arg x,y -return x+y x-y x//y x/y x%y x*y x**y /*same as version above.*/ +/*REXX program shows and displays examples of multiple RETURN values from a function.*/ +numeric digits 70 /*the default is: NUMERIC DIGITS 9 */ +parse arg a b . /*obtain two numbers from command line.*/ +if a=='' | a=="," then a=82 /*Not specified? Then use the default.*/ +if b=='' | b=="," then b=20 /* " " " " " " */ +say ' a =' a /*display the first number to the term.*/ +say ' b =' b /* " " second " " " " */ +say copies('═', 50) /*display a separator line " " " */ +z= arithmetics(a, b) /*call the function: arithmetics */ +parse var z abut sum diff rem div Idiv prod pow /*obtain the function's returned values*/ +say ' || =' abut /*display abutment to the terminal.*/ +say ' + =' sum /* " sum " " " */ +say ' - =' diff /* " difference " " " */ +say ' // =' rem /* " remainder " " " */ +say ' / =' div /* " quotient " " " */ +say ' % =' Idiv /* " int. quotient " " " */ +say ' * =' prod /* " product " " " */ +say ' ** =' pow /* " power " " " */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +arithmetics: procedure; parse arg x,y; return x||y x+y x-y x//y x/y x%y x*y x**y diff --git a/Task/Return-multiple-values/Scala/return-multiple-values-1.scala b/Task/Return-multiple-values/Scala/return-multiple-values-1.scala index 0b9ee82944..f501e518a1 100644 --- a/Task/Return-multiple-values/Scala/return-multiple-values-1.scala +++ b/Task/Return-multiple-values/Scala/return-multiple-values-1.scala @@ -1 +1 @@ -def addsub(x: Int, y: Int) = (x + y, x - y) +def addSubMult(x: Int, y: Int) = (x + y, x - y, x * y) diff --git a/Task/Return-multiple-values/Scala/return-multiple-values-2.scala b/Task/Return-multiple-values/Scala/return-multiple-values-2.scala index b437978e7f..71be27ddd3 100644 --- a/Task/Return-multiple-values/Scala/return-multiple-values-2.scala +++ b/Task/Return-multiple-values/Scala/return-multiple-values-2.scala @@ -1 +1,4 @@ -val (sum, difference) = addsub(33, 12) +def addSubMult(x: Int, y:Int) : (Int, Int, Int) = { + ... + (x + y, x - y, x * y) +} diff --git a/Task/Return-multiple-values/Scala/return-multiple-values-3.scala b/Task/Return-multiple-values/Scala/return-multiple-values-3.scala new file mode 100644 index 0000000000..b437978e7f --- /dev/null +++ b/Task/Return-multiple-values/Scala/return-multiple-values-3.scala @@ -0,0 +1 @@ +val (sum, difference) = addsub(33, 12) diff --git a/Task/Return-multiple-values/Zkl/return-multiple-values.zkl b/Task/Return-multiple-values/Zkl/return-multiple-values.zkl new file mode 100644 index 0000000000..9cd84e5413 --- /dev/null +++ b/Task/Return-multiple-values/Zkl/return-multiple-values.zkl @@ -0,0 +1,2 @@ +fcn f{return(1,2,"three")} +a,b,c:=f() // a==1, b==2, c=="three" diff --git a/Task/Reverse-a-string/ALGOL-68/reverse-a-string-1.alg b/Task/Reverse-a-string/ALGOL-68/reverse-a-string-1.alg deleted file mode 100644 index b3ee6c60e3..0000000000 --- a/Task/Reverse-a-string/ALGOL-68/reverse-a-string-1.alg +++ /dev/null @@ -1,13 +0,0 @@ -PROC reverse = (REF STRING s)VOID: - FOR i TO UPB s OVER 2 DO - CHAR c = s[i]; - s[i] := s[UPB s - i + 1]; - s[UPB s - i + 1] := c - OD; - -main: -( - STRING text := "Was it a cat I saw"; - reverse(text); - print((text, new line)) -) diff --git a/Task/Reverse-a-string/ALGOL-68/reverse-a-string-2.alg b/Task/Reverse-a-string/ALGOL-68/reverse-a-string-2.alg deleted file mode 100644 index fb792368e4..0000000000 --- a/Task/Reverse-a-string/ALGOL-68/reverse-a-string-2.alg +++ /dev/null @@ -1,2 +0,0 @@ - ⌽'asdf' -fdsa diff --git a/Task/Reverse-a-string/Agda2/reverse-a-string.agda2 b/Task/Reverse-a-string/Agda2/reverse-a-string.agda2 deleted file mode 100644 index 36d529693d..0000000000 --- a/Task/Reverse-a-string/Agda2/reverse-a-string.agda2 +++ /dev/null @@ -1,7 +0,0 @@ -module reverse_string where - -open import Data.String -open import Data.List - -reverse_string : String → String -reverse_string s = fromList (reverse (toList s)) diff --git a/Task/Reverse-a-string/Aime/reverse-a-string.aime b/Task/Reverse-a-string/Aime/reverse-a-string.aime index ff25141035..da2c95421f 100644 --- a/Task/Reverse-a-string/Aime/reverse-a-string.aime +++ b/Task/Reverse-a-string/Aime/reverse-a-string.aime @@ -1,23 +1 @@ -text -reverse(text s) -{ - data b; - integer i; - - i = length(s); - while (i) { - i -= 1; - b_insert(b, -1, s[i]); - } - - return b_string(b); -} - -integer -main(void) -{ - o_text(reverse("Hello, World!")); - o_byte('\n'); - - return 0; -} +o_(b_reverse(b_draft("Hello, World!")), "\n"); diff --git a/Task/Reverse-a-string/AppleScript/reverse-a-string-2.applescript b/Task/Reverse-a-string/AppleScript/reverse-a-string-2.applescript index 842dc6dc49..e189b65120 100644 --- a/Task/Reverse-a-string/AppleScript/reverse-a-string-2.applescript +++ b/Task/Reverse-a-string/AppleScript/reverse-a-string-2.applescript @@ -3,9 +3,9 @@ -- reverse1 :: [a] -> [a] on reverse1(xs) script rev - on lambda(a, x) + on |λ|(a, x) a & x - end lambda + end |λ| end script if class of xs is text then @@ -15,7 +15,6 @@ on reverse1(xs) end if end reverse1 - -- or the built-in reverse method for lists -- reverse2 :: [a] -> [a] @@ -28,22 +27,19 @@ on reverse2(xs) end reverse2 - --- TESTING reverse1 and reverse2 with same string and list +-- TESTING reverse1 and reverse2 with same string and list --------------------------------------------------------------------------- on run script test - on lambda(f) + on |λ|(f) map(f, ["Hello there !", {1, 2, 3, 4, 5}]) - end lambda + end |λ| end script map(test, [reverse1, reverse2]) end run - - --- GENERIC LIBRARY FUNCTIONS +-- GENERIC FUNCTIONS --------------------------------------------------------------------------- -- foldr :: (a -> b -> a) -> a -> [b] -> a on foldr(f, startValue, xs) @@ -51,7 +47,7 @@ on foldr(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -63,7 +59,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -76,7 +72,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Reverse-a-string/BASIC/reverse-a-string.basic b/Task/Reverse-a-string/BASIC/reverse-a-string-1.basic similarity index 100% rename from Task/Reverse-a-string/BASIC/reverse-a-string.basic rename to Task/Reverse-a-string/BASIC/reverse-a-string-1.basic diff --git a/Task/Reverse-a-string/BASIC/reverse-a-string-2.basic b/Task/Reverse-a-string/BASIC/reverse-a-string-2.basic new file mode 100644 index 0000000000..4e06c93d10 --- /dev/null +++ b/Task/Reverse-a-string/BASIC/reverse-a-string-2.basic @@ -0,0 +1,6 @@ +10 INPUT S$ +20 LET T$="" +30 FOR I=LEN S$ TO 1 STEP -1 +40 LET T$=T$+S$(I) +50 NEXT I +60 PRINT T$ diff --git a/Task/Reverse-a-string/BaCon/reverse-a-string.bacon b/Task/Reverse-a-string/BaCon/reverse-a-string.bacon new file mode 100644 index 0000000000..72e2d420c8 --- /dev/null +++ b/Task/Reverse-a-string/BaCon/reverse-a-string.bacon @@ -0,0 +1,3 @@ +OPTION UTF8 TRUE +s$ = "asdf" +PRINT REVERSE$(s$) diff --git a/Task/Reverse-a-string/Crystal/reverse-a-string.crystal b/Task/Reverse-a-string/Crystal/reverse-a-string.crystal new file mode 100644 index 0000000000..159eb2b8f4 --- /dev/null +++ b/Task/Reverse-a-string/Crystal/reverse-a-string.crystal @@ -0,0 +1,6 @@ +# version 0.21.1 + +strings = ["asdf", "as⃝df̅"] +strings.each do |s| + puts "#{s} -> #{s.reverse}" +end diff --git a/Task/Reverse-a-string/Elena/reverse-a-string.elena b/Task/Reverse-a-string/Elena/reverse-a-string.elena index ba293bc10a..fa37200251 100644 --- a/Task/Reverse-a-string/Elena/reverse-a-string.elena +++ b/Task/Reverse-a-string/Elena/reverse-a-string.elena @@ -1,14 +1,13 @@ -#import system. -#import system'routines. -#import extensions. +import system'routines. +import extensions. -#class(extension) extension +extension extension { - #method reversedLiteral - = self toArray reverse summarize:(String new) literal. + reversedLiteral + = self toArray; sequenceReverse; summarize(String new); literal. } -#symbol program = +program = [ - console writeLine:("Hello World" reversedLiteral). + console printLine("Hello World" reversedLiteral). ]. diff --git a/Task/Reverse-a-string/Futhark/reverse-a-string.futhark b/Task/Reverse-a-string/Futhark/reverse-a-string.futhark new file mode 100644 index 0000000000..360470bf96 --- /dev/null +++ b/Task/Reverse-a-string/Futhark/reverse-a-string.futhark @@ -0,0 +1 @@ +fun main(s: []i32) = s[::-1] diff --git a/Task/Reverse-a-string/Gambas/reverse-a-string.gambas b/Task/Reverse-a-string/Gambas/reverse-a-string.gambas new file mode 100644 index 0000000000..5d5427c206 --- /dev/null +++ b/Task/Reverse-a-string/Gambas/reverse-a-string.gambas @@ -0,0 +1,12 @@ +Public Sub Main() +Dim sString As String = "asdf" +Dim sOutput As String +Dim siCount As Short + +For siCount = Len(sString) DownTo 1 + sOutput &= Mid(sString, siCount, 1) +Next + +Print sOutput + +End diff --git a/Task/Reverse-a-string/jq/reverse-a-string.jq b/Task/Reverse-a-string/Jq/reverse-a-string.jq similarity index 100% rename from Task/Reverse-a-string/jq/reverse-a-string.jq rename to Task/Reverse-a-string/Jq/reverse-a-string.jq diff --git a/Task/Reverse-a-string/Nimrod/reverse-a-string.nimrod b/Task/Reverse-a-string/Nimrod/reverse-a-string.nimrod deleted file mode 100644 index 15be271902..0000000000 --- a/Task/Reverse-a-string/Nimrod/reverse-a-string.nimrod +++ /dev/null @@ -1,10 +0,0 @@ -var - str1 = "Reverse This!" - -proc reverse(s: string): string = - result = "" - for i in countdown(high(str1), 0): - result.add str1[i] - -echo "Original string: ", str1, "\nReversed: ", reverse(str1) -echo "Using inbuilt array reversal: ", reverse(str1) diff --git a/Task/Reverse-a-string/PlainTeX/reverse-a-string.tex b/Task/Reverse-a-string/PlainTeX/reverse-a-string.tex new file mode 100644 index 0000000000..43b0badf27 --- /dev/null +++ b/Task/Reverse-a-string/PlainTeX/reverse-a-string.tex @@ -0,0 +1,6 @@ +\def\gobtoA#1\revA{}\def\gobtoB#1\revB{} +\def\reverse#1{\reversei{}#1\revA\revB\revB\revB\revB\revB\revB\revB\revB\revA} +\def\reversei#1#2#3#4#5#6#7#8#9{\gobtoB#9\revend\revB\reversei{#9#8#7#6#5#4#3#2#1}} +\def\revend\revB\reversei#1#2\revA{\gobtoA#1} +\reverse{Rosetta} +\bye diff --git a/Task/Reverse-a-string/Prolog/reverse-a-string-3.pro b/Task/Reverse-a-string/Prolog/reverse-a-string-3.pro deleted file mode 100644 index f27483e3d3..0000000000 --- a/Task/Reverse-a-string/Prolog/reverse-a-string-3.pro +++ /dev/null @@ -1,4 +0,0 @@ -accRev([H|T], A, R) :- accRev(T, [H|A], R). -accRev([], A, A). - -rev(L,R) :- accRev(L,[],R). diff --git a/Task/Reverse-a-string/Protium/reverse-a-string-1.protium b/Task/Reverse-a-string/Protium/reverse-a-string-1.protium deleted file mode 100644 index d267f6da1d..0000000000 --- a/Task/Reverse-a-string/Protium/reverse-a-string-1.protium +++ /dev/null @@ -1 +0,0 @@ -<# 显示 指定 变量 反转顺序 字串>集装箱|猫坐在垫子 diff --git a/Task/Reverse-a-string/Protium/reverse-a-string-2.protium b/Task/Reverse-a-string/Protium/reverse-a-string-2.protium deleted file mode 100644 index 3933f09397..0000000000 --- a/Task/Reverse-a-string/Protium/reverse-a-string-2.protium +++ /dev/null @@ -1 +0,0 @@ -<# 보이십 할당하 변물건 열거꾸 문자그>컨테이너|고양이가 매트 위에 앉아 diff --git a/Task/Reverse-a-string/Protium/reverse-a-string-3.protium b/Task/Reverse-a-string/Protium/reverse-a-string-3.protium deleted file mode 100644 index b7e8cf08b7..0000000000 --- a/Task/Reverse-a-string/Protium/reverse-a-string-3.protium +++ /dev/null @@ -1 +0,0 @@ -<@ SAYLETVARREVLIT>集装箱|猫坐在垫子 diff --git a/Task/Reverse-a-string/Rust/reverse-a-string-1.rust b/Task/Reverse-a-string/Rust/reverse-a-string-1.rust deleted file mode 100644 index 26191bb3e1..0000000000 --- a/Task/Reverse-a-string/Rust/reverse-a-string-1.rust +++ /dev/null @@ -1,3 +0,0 @@ -// rust 0.9 -let s = "一二三四五六七八九十"; -let reversed:~str = s.chars_rev().collect(); diff --git a/Task/Reverse-a-string/Rust/reverse-a-string-2.rust b/Task/Reverse-a-string/Rust/reverse-a-string-2.rust deleted file mode 100644 index 7393f0851e..0000000000 --- a/Task/Reverse-a-string/Rust/reverse-a-string-2.rust +++ /dev/null @@ -1 +0,0 @@ -let reversed:~str = "一二三四五六七八九十".chars_rev().collect(); diff --git a/Task/Reverse-a-string/Stata/reverse-a-string.stata b/Task/Reverse-a-string/Stata/reverse-a-string.stata new file mode 100644 index 0000000000..99210fa631 --- /dev/null +++ b/Task/Reverse-a-string/Stata/reverse-a-string.stata @@ -0,0 +1,6 @@ +. scalar s="ARS LONGA VITA BREVIS" +. di strreverse(s) +SIVERB ATIV AGNOL SRA +. scalar s="Ἐν ἀρχῇ ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν" +. di ustrreverse(s) +νῆγ νὴτ ὶακ νὸναρὐο νὸτ ςὸεθ ὁ νεσηίοπἐ ῇχρἀ νἘ diff --git a/Task/Reverse-words-in-a-string/AppleScript/reverse-words-in-a-string.applescript b/Task/Reverse-words-in-a-string/AppleScript/reverse-words-in-a-string.applescript index 1225dba4b1..910b82ec8c 100644 --- a/Task/Reverse-words-in-a-string/AppleScript/reverse-words-in-a-string.applescript +++ b/Task/Reverse-words-in-a-string/AppleScript/reverse-words-in-a-string.applescript @@ -1,4 +1,4 @@ -on run {} +on run unlines(map(reverseWords, |lines|("---------- Ice and Fire ------------ @@ -13,6 +13,9 @@ Frost Robert -----------------------"))) end run + +-- GENERIC FUNCTIONS --------------------------------------------------------- + -- reverseWords :: String -> String on reverseWords(str) unwords(|reverse|(|words|(str))) @@ -65,13 +68,24 @@ end intercalate -- map :: (a -> b) -> [a] -> [b] on map(f, xs) - script mf - property lambda : f - end script - set lst to {} - set lng to length of xs - repeat with i from 1 to lng - set end of lst to mf's lambda(item i of xs, i, xs) - end repeat - return lst + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to lambda(item i of xs, i, xs) + end repeat + return lst + end tell end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property lambda : f + end script + end if +end mReturn diff --git a/Task/Reverse-words-in-a-string/BaCon/reverse-words-in-a-string.bacon b/Task/Reverse-words-in-a-string/BaCon/reverse-words-in-a-string.bacon new file mode 100644 index 0000000000..d5a8c62178 --- /dev/null +++ b/Task/Reverse-words-in-a-string/BaCon/reverse-words-in-a-string.bacon @@ -0,0 +1,10 @@ +PRINT REV$("---------- Ice and Fire ------------") +PRINT +PRINT REV$("fire, in end will world the say Some") +PRINT REV$("ice. in say Some ") +PRINT REV$("desire of tasted I've what From ") +PRINT REV$("fire. favor who those with hold I ") +PRINT +PRINT REV$("... elided paragraph last ... ") +PRINT +PRINT REV$("Frost Robert -----------------------") diff --git a/Task/Reverse-words-in-a-string/Elena/reverse-words-in-a-string.elena b/Task/Reverse-words-in-a-string/Elena/reverse-words-in-a-string.elena index 0be3a71ffe..7ac1205c01 100644 --- a/Task/Reverse-words-in-a-string/Elena/reverse-words-in-a-string.elena +++ b/Task/Reverse-words-in-a-string/Elena/reverse-words-in-a-string.elena @@ -1,9 +1,9 @@ -#import system. -#import system'routines. +import extensions. +import system'routines. -#symbol program = +program = [ - #var text := ("---------- Ice and Fire ------------", + var text := ("---------- Ice and Fire ------------", "", "fire, in end will world the say Some", "ice. in say Some", @@ -14,11 +14,11 @@ "", "Frost Robert -----------------------"). - text run &each: line + text forEach(:line) [ - line split &by:" " reverse run &each: word + line split by:" "; sequenceReverse; forEach(:word) [ - console write:word write:" ". + console print(word," ") ]. console writeLine. ]. diff --git a/Task/Reverse-words-in-a-string/Gambas/reverse-words-in-a-string.gambas b/Task/Reverse-words-in-a-string/Gambas/reverse-words-in-a-string.gambas new file mode 100644 index 0000000000..43f8b25b8a --- /dev/null +++ b/Task/Reverse-words-in-a-string/Gambas/reverse-words-in-a-string.gambas @@ -0,0 +1,36 @@ +Public Sub Main() +Dim sString As New String[10] 'Array for the input text +Dim sLine As New String[] 'Array of each word in a line +Dim siCount0, siCount1 As Short 'Counters +Dim sOutput, sReverse, sTemp As String 'Strings + +sString[0] = "---------- Ice And Fire ------------" 'Input text +sString[1] = " " +sString[2] = "fire, in end will world the say Some" +sString[3] = "ice. in say Some " +sString[4] = "desire of tasted I've what From " +sString[5] = "fire. favor who those with hold I " +sString[6] = " " +sString[7] = "... elided paragraph last ... " +sString[8] = " " +sString[9] = "Frost Robert -----------------------" + +For siCount0 = 0 To 9 'To work through each line of input text + If Trim(sString[siCount0]) = "" Then sString[siCount0] = " " 'If the line is all spaces then make it 1 space + + For Each sTemp In Split(Trim(sString[siCount0]), " ") 'Split the trimmed line by spaces + sLine.Add(sTemp) 'Add each word to the sLine array + Next + + For siCount1 = sLine.max DownTo 0 'Loop from the last in the sLine array to 0 + sReverse &= sLine[siCount1] & " " 'Fill sReverse with words reversed, adding a space + Next + + sOutput &= Trim(sReverse) & gb.NewLine 'Add the reversed words to sOutput and add a newline + sReverse = "" 'Clear sReverse + sLine.Clear 'Clear sLine array +Next + +Print sOutput 'Print the output + +End diff --git a/Task/Reverse-words-in-a-string/jq/reverse-words-in-a-string-1.jq b/Task/Reverse-words-in-a-string/Jq/reverse-words-in-a-string-1.jq similarity index 100% rename from Task/Reverse-words-in-a-string/jq/reverse-words-in-a-string-1.jq rename to Task/Reverse-words-in-a-string/Jq/reverse-words-in-a-string-1.jq diff --git a/Task/Reverse-words-in-a-string/jq/reverse-words-in-a-string-2.jq b/Task/Reverse-words-in-a-string/Jq/reverse-words-in-a-string-2.jq similarity index 100% rename from Task/Reverse-words-in-a-string/jq/reverse-words-in-a-string-2.jq rename to Task/Reverse-words-in-a-string/Jq/reverse-words-in-a-string-2.jq diff --git a/Task/Reverse-words-in-a-string/Kotlin/reverse-words-in-a-string.kotlin b/Task/Reverse-words-in-a-string/Kotlin/reverse-words-in-a-string.kotlin new file mode 100644 index 0000000000..812468507c --- /dev/null +++ b/Task/Reverse-words-in-a-string/Kotlin/reverse-words-in-a-string.kotlin @@ -0,0 +1,22 @@ +// version 1.0.6 + +fun reversedWords(s: String) = s.split(" ").reversed().joinToString(" ") + +fun main(args: Array) { + val s = "Hey you, Bub!" + println(reversedWords(s)) + println() + val sl = listOf( + " ---------- Ice and Fire ------------ ", + " ", + " fire, in end will world the say Some ", + " ice. in say Some ", + " desire of tasted I've what From ", + " fire. favor who those with hold I ", + " ", + " ... elided paragraph last ... ", + " ", + " Frost Robert ----------------------- " + ) + sl.forEach { println(reversedWords(it).trimStart()) } +} diff --git a/Task/Reverse-words-in-a-string/Zkl/reverse-words-in-a-string.zkl b/Task/Reverse-words-in-a-string/Zkl/reverse-words-in-a-string.zkl new file mode 100644 index 0000000000..6aeba2bcc0 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Zkl/reverse-words-in-a-string.zkl @@ -0,0 +1,17 @@ +text:=Data(0,String, +#<<< +"---------- Ice and Fire ------------ + +fire, in end will world the say Some +ice. in say Some +desire of tasted I've what From +fire. favor who those with hold I + +... elided paragraph last ... + +Frost Robert -----------------------"); +#<<< + +text.pump(11,Data,fcn(s){ // process stripped lines + s.split(" ").reverse().concat(" ") + "\n" }) + .text.print(); diff --git a/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime b/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime index 411cbe6d69..b0bbd9bfe1 100644 --- a/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime +++ b/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime @@ -12,8 +12,8 @@ computer_play(record plays, record beats) if (a < r_q_integer(plays, s)) { break; } - a -= r_q_integer(plays, s); - } while (r_greater(plays, s, s)); + a -= plays[s]; + } while (rsk_greater(plays, s, s)); return r_q_text(beats, s); } @@ -56,7 +56,7 @@ main(void) if (!compare(s, c)) { o_text("Draw\n"); - } elif (!compare(c, r_q_text(beats, s))) { + } elif (!compare(c, beats[s])) { computer += 1; o_text("Computer wins\n"); } else { @@ -64,7 +64,7 @@ main(void) o_text("Human wins\n"); } - r_r_integer(plays, s, r_q_integer(plays, s) + 1); + r_up(plays, s); o_form("Score: Human: ~, Computer: ~\n", human, computer); } diff --git a/Task/Rock-paper-scissors/BASIC/rock-paper-scissors-1.basic b/Task/Rock-paper-scissors/BASIC/rock-paper-scissors-1.basic deleted file mode 100644 index e2f1580179..0000000000 --- a/Task/Rock-paper-scissors/BASIC/rock-paper-scissors-1.basic +++ /dev/null @@ -1,62 +0,0 @@ -DIM pPLchoice(1 TO 3) AS INTEGER, pCMchoice(1 TO 3) AS INTEGER -DIM choices(1 TO 3) AS STRING -DIM playerwins(1 TO 3) AS INTEGER -DIM playerchoice AS INTEGER, compchoice AS INTEGER -DIM playerwon AS INTEGER, compwon AS INTEGER, tie AS INTEGER -DIM tmp AS INTEGER - -' Do it this way for QBasic; FreeBASIC supports direct array assignment. -DATA "rock", "paper", "scissors" -FOR tmp = 1 to 3 - READ choices(tmp) -NEXT -DATA 3, 1, 2 -FOR tmp = 1 to 3 - READ playerwins(tmp) -NEXT - -RANDOMIZE TIMER - -DO - ' Computer chooses first to ensure there's no "cheating". - compchoice = INT(RND * (pPLchoice(1) + pPLchoice(2) + pPLchoice(3) + 3)) - SELECT CASE compchoice - CASE 0 to (pPLchoice(1)) - ' Player past choice: rock; choose paper. - compchoice = 2 - CASE (pPLchoice(1) + 1) TO (pPLchoice(1) + pPLchoice(2) + 1) - ' Player past choice: paper; choose scissors. - compchoice = 3 - CASE (pPLchoice(1) + pPLchoice(2) + 2) TO (pPLchoice(1) + pPLchoice(2) + pPLchoice(3) + 2) - ' Player past choice: scissors; choose rock. - compchoice = 1 - END SELECT - - PRINT "Rock, paper, or scissors "; - DO - PRINT "[1 = rock, 2 = paper, 3 = scissors, 0 to quit]"; - INPUT playerchoice - LOOP WHILE (playerchoice < 0) OR (playerchoice > 3) - - IF 0 = playerchoice THEN EXIT DO - - pCMchoice(compchoice) = pCMchoice(compchoice) + 1 - pPLchoice(playerchoice) = pPLchoice(playerchoice) + 1 - PRINT "You chose "; choices(playerchoice); " and I chose "; choices(compchoice); ". "; - IF (playerchoice) = compchoice THEN - PRINT "Tie!" - tie = tie + 1 - ELSEIF (compchoice) = playerwins(playerchoice) THEN - PRINT "You won!" - playerwon = playerwon + 1 - ELSE - PRINT "I won!" - compwon = compwon + 1 - END IF -LOOP - -PRINT "Some useless statistics:" -PRINT "You won "; STR$(playerwon); " times, and I won "; STR$(compwon); " times; "; STR$(tie); " ties." -PRINT , choices(1), choices(2), choices(3) -PRINT "You chose:", pPLchoice(1), pPLchoice(2), pPLchoice(3) -PRINT " I chose:", pCMchoice(1), pCMchoice(2), pCMchoice(3) diff --git a/Task/Rock-paper-scissors/BASIC/rock-paper-scissors-2.basic b/Task/Rock-paper-scissors/BASIC/rock-paper-scissors-2.basic deleted file mode 100644 index 09750db1ba..0000000000 --- a/Task/Rock-paper-scissors/BASIC/rock-paper-scissors-2.basic +++ /dev/null @@ -1,16 +0,0 @@ - 20 LET P=0: LET Q=0: LET Z=0 - 30 INPUT "Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? ", A - 40 IF A>3 THEN GOTO 400 - 50 IF A=3 THEN LET A=4 - 60 IF A<1 THEN GOTO 400 - 70 CHOOSE C=3 : LET D=4: FOR B=1 TO C+1 : LET D = D+D : NEXT : GOTO (A+D)*10 - 90 Z=Z+1 : PRINT "We both chose 'rock'. It's a draw." : GOTO 30 -100 P=P+1 : PRINT "You chose 'paper', I chose 'rock'. You win.." : GOTO 30 -120 Q=Q+1 : PRINT "You chose 'scissors', I chose 'rock'. I win!" : GOTO 30 -170 Q=Q+1 : PRINT "You chose 'rock', I chose 'paper'. I win!" : GOTO 30 -180 Z=Z+1 : PRINT "We both chose 'paper'. It's a draw." : GOTO 30 -200 P=P+1 : PRINT "You chose 'scissors', I chose 'paper'. You win.." : GOTO 30 -330 P=P+1 : PRINT "You chose 'rock', I chose 'scissors'. You win.." : GOTO 30 -340 Q=Q+1 : PRINT "You chose 'paper', I chose 'scissors'. I win!" : GOTO 30 -360 Z=Z+1 : PRINT "We both chose 'scissors'. It's a draw." : GOTO 30 -400 PRINT "There were ";Z;" draws. I lost ";P;" times, you lost ";Q;" times." : END diff --git a/Task/Rock-paper-scissors/Batch-File/rock-paper-scissors.bat b/Task/Rock-paper-scissors/Batch-File/rock-paper-scissors.bat new file mode 100644 index 0000000000..f40e2ef358 --- /dev/null +++ b/Task/Rock-paper-scissors/Batch-File/rock-paper-scissors.bat @@ -0,0 +1,71 @@ +@echo off +setlocal enabledelayedexpansion + +set choice1=rock +set choice2=paper +set choice3=scissors +set freq1=0 +set freq2=0 +set freq3=0 +set games=0 +set won=0 +set lost=0 +set tie=0 + +:start + +cls +echo Games - %games% : Won - %won% : Lost - %lost% : Ties - %tie% +choice /c RPS /n /m "[R]ock, [P]aper or [S]cissors? " + +set /a choicequant+=1 +set choice=%errorlevel% +set /a rocklimit=100 / %choicequant% * %freq3% +set /a scissorslimit=100 - (100 / %choicequant% * %freq2%) +set /a randchoice=%random% %% 100 + 1 +set compchoice=2 +if %randchoice% geq %scissorslimit% set compchoice=3 +if %randchoice% leq %rocklimit% set compchoice=1 + +cls +echo Player: !choice%choice%! ^|vs^| Computer: !choice%compchoice%! +goto %compchoice% + +:1 + +if %choice%==1 goto tie +if %choice%==2 goto win +if %choice%==3 goto loss + +:2 + +if %choice%==1 goto loss +if %choice%==2 goto tie +if %choice%==3 goto win + +:3 + +if %choice%==1 goto win +if %choice%==2 goto loss +if %choice%==3 goto tie + +:win +set /a won+=1 +echo Player wins^! +goto end + +:loss +set /a lost+=1 +echo Computer Wins^! +goto end + +:tie +set /a tie+=1 +echo Tie^! +goto end + +:end +set /a games+=1 +set /a freq%choice%+=1 +pause +goto start diff --git a/Task/Rock-paper-scissors/D/rock-paper-scissors-1.d b/Task/Rock-paper-scissors/D/rock-paper-scissors-1.d deleted file mode 100644 index a8c893d253..0000000000 --- a/Task/Rock-paper-scissors/D/rock-paper-scissors-1.d +++ /dev/null @@ -1,60 +0,0 @@ -import std.stdio, std.random, std.string, std.array, - std.typecons, std.traits, std.conv, std.algorithm; - -enum Choice { rock, paper, scissors } -immutable order = [EnumMembers!Choice]; - -uint[order.length] choiceFrequency; - -Choice whatBeats(in Choice ch) pure nothrow { - return order[(order.countUntil(ch) + 1) % $]; -} - -Nullable!Choice checkWinner(in Choice a, in Choice b) -pure /*nothrow*/ { - alias TResult = typeof(return); - - if (b == whatBeats(a)) - return TResult(b); - else if (a == whatBeats(b)) - return TResult(a); - return TResult(); -} - -Choice getRandomChoice() /*nothrow*/ { - if (choiceFrequency[].sum == 0) - return uniform!Choice; - return order[choiceFrequency.dice].whatBeats; -} - -void main() { - writeln("Rock-Paper-Scissors Game"); - - while (true) { - write("Your choice (empty to end game): "); - immutable humanChoiceStr = readln.strip.toLower; - if (humanChoiceStr.empty) - break; - - Choice humanChoice; - try { - humanChoice = humanChoiceStr.to!Choice; - } catch (ConvException e) { - writeln("Wrong input: ", humanChoiceStr); - continue; - } - - immutable compChoice = getRandomChoice; - write("Computer picked ", compChoice, ", "); - - // Don't register the player choice until after - // the computer has made its choice. - choiceFrequency[humanChoice]++; - - immutable winner = checkWinner(humanChoice, compChoice); - if (winner.isNull) - writeln("Nobody wins!"); - else - writeln(winner.get, " wins!"); - } -} diff --git a/Task/Rock-paper-scissors/D/rock-paper-scissors-2.d b/Task/Rock-paper-scissors/D/rock-paper-scissors-2.d deleted file mode 100644 index cfd9c80370..0000000000 --- a/Task/Rock-paper-scissors/D/rock-paper-scissors-2.d +++ /dev/null @@ -1,55 +0,0 @@ -import std.stdio, std.random, std.string, std.conv, std.array, - std.typecons; - -enum Choice { rock, paper, scissors } - -bool beats(in Choice c1, in Choice c2) pure nothrow { - return (c1 == Choice.paper && c2 == Choice.rock) || - (c1 == Choice.scissors && c2 == Choice.paper) || - (c1 == Choice.rock && c2 == Choice.scissors); -} - -Choice genMove(in int r, in int p, in int s) { - immutable x = uniform!"[]"(1, r + p + s); - if (x < s) return Choice.rock; - if (x <= s + r) return Choice.paper; - else return Choice.scissors; -} - -Nullable!To maybeTo(To, From)(From x) { - try { - return typeof(return)(x.to!To); - } catch (ConvException e) { - return typeof(return)(); - } -} - -void main() { - int r = 1, p = 1, s = 1; - - while (true) { - write("rock, paper or scissors? "); - immutable hs = readln.strip.toLower; - if (hs.empty) - break; - - immutable h = hs.maybeTo!Choice; - if (h.isNull) { - writeln("Wrong input: ", hs); - continue; - } - - immutable c = genMove(r, p, s); - writeln("Player: ", h, " Computer: ", c); - - if (beats(h, c)) writeln("Player wins\n"); - else if (beats(c, h)) writeln("Player loses\n"); - else writeln("Draw\n"); - - final switch (h.get) { - case Choice.rock: r++; break; - case Choice.paper: p++; break; - case Choice.scissors: s++; break; - } - } -} diff --git a/Task/Rock-paper-scissors/Haskell/rock-paper-scissors.hs b/Task/Rock-paper-scissors/Haskell/rock-paper-scissors.hs index ff9f58ae87..0a5a971867 100644 --- a/Task/Rock-paper-scissors/Haskell/rock-paper-scissors.hs +++ b/Task/Rock-paper-scissors/Haskell/rock-paper-scissors.hs @@ -1,36 +1,59 @@ -import System.Random - -data Choice = Rock | Paper | Scissors - deriving (Show, Eq) +import System.Random (randomRIO) +data Choice + = Rock + | Paper + | Scissors + deriving (Show, Eq) +beats :: Choice -> Choice -> Bool beats Paper Rock = True beats Scissors Paper = True beats Rock Scissors = True beats _ _ = False -genrps (r,p,s) = fmap rps rand - where rps x | x <= s = Rock - | x <= s+r = Paper - | otherwise = Scissors - rand = randomRIO (1,r+p+s) :: IO Int +genrps :: (Int, Int, Int) -> IO Choice +genrps (r, p, s) = rps <$> rand + where + rps x + | x <= s = Rock + | x <= s + r = Paper + | otherwise = Scissors + rand = randomRIO (1, r + p + s) :: IO Int -getrps = fmap rps getLine - where rps "scissors" = Scissors - rps "rock" = Rock - rps "paper" = Paper - rps _ = error "invalid input" +getrps :: IO Choice +getrps = rps <$> getLine + where + rps "scissors" = Scissors + rps "rock" = Rock + rps "paper" = Paper + rps _ = error "invalid input" -game (r,p,s) = do putStrLn "rock, paper or scissors?" - h <- getrps - c <- genrps (r,p,s) - putStrLn ("Player: " ++ show h ++ " Computer: " ++ show c) - putStrLn (if beats h c then "player wins\n" - else if beats c h then "player loses\n" - else "draw\n") - let rr = if h == Rock then r+1 else r - pp = if h == Paper then p+1 else p - ss = if h == Scissors then s+1 else s - game (rr,pp,ss) +game :: (Int, Int, Int) -> IO a +game (r, p, s) = do + putStrLn "rock, paper or scissors?" + h <- getrps + c <- genrps (r, p, s) + putStrLn ("Player: " ++ show h ++ " Computer: " ++ show c) + putStrLn + (if beats h c + then "player wins\n" + else if beats c h + then "player loses\n" + else "draw\n") + let rr = + if h == Rock + then r + 1 + else r + pp = + if h == Paper + then p + 1 + else p + ss = + if h == Scissors + then s + 1 + else s + game (rr, pp, ss) -main = game (1,1,1) +main :: IO a +main = game (1, 1, 1) diff --git a/Task/Rock-paper-scissors/Sidef/rock-paper-scissors.sidef b/Task/Rock-paper-scissors/Sidef/rock-paper-scissors.sidef index 46282796f1..1bf9a1b18b 100644 --- a/Task/Rock-paper-scissors/Sidef/rock-paper-scissors.sidef +++ b/Task/Rock-paper-scissors/Sidef/rock-paper-scissors.sidef @@ -6,7 +6,7 @@ const msg = [ "Scissors cut paper", ] -say <<"EOT"; +say <<"EOT" \n>> Rock Paper Scissors <<\n ** Enter 'r', 'p', or 's' as your play. ** Enter 'q' to exit the game. @@ -17,7 +17,7 @@ var plays = 0 var aScore = 0 var pScore = 0 var pcf = [0,0,0] # pcf = player choice frequency -var aChoice = 3.irand # ai choice for first play is completely random +var aChoice = pick(0..2) # ai choice for first play is completely random loop { var pi = Sys.scanln("Play: ") @@ -34,19 +34,19 @@ loop { ++plays # show result of play - ">> My play: %-8s".printf(rps[aChoice]) + ">> My play: %-8s".printf(rps[aChoice]) given ((aChoice - pChoice + 3) % 3) { when (0) { say "Tie." } - when (1) { "%-*s %s".printlnf(30, msg[aChoice], 'My point'); aScore++ } - when (2) { "%-*s %s".printlnf(30, msg[pChoice], 'Your point'); pScore++ } + when (1) { "%-*s %s".printlnf(30, msg[aChoice], 'My point'); aScore++ } + when (2) { "%-*s %s".printlnf(30, msg[pChoice], 'Your point'); pScore++ } } # show score "%-6s".printf("%d:%d" % (pScore, aScore)) # compute ai choice for next play - given (plays.irand) { |rn| + given (plays.rand.int) { |rn| case (rn < pcf[0]) { aChoice = 1 } case (pcf[0]+pcf[1] > rn) { aChoice = 2 } default { aChoice = 0 } diff --git a/Task/Roman-numerals-Decode/AppleScript/roman-numerals-decode-1.applescript b/Task/Roman-numerals-Decode/AppleScript/roman-numerals-decode-1.applescript index 824414cef3..4ab5c24c3d 100644 --- a/Task/Roman-numerals-Decode/AppleScript/roman-numerals-decode-1.applescript +++ b/Task/Roman-numerals-Decode/AppleScript/roman-numerals-decode-1.applescript @@ -1,9 +1,3 @@ -on run - map(romanValue, {"MCMXC", "MDCLXVI", "MMVIII"}) - - --> {1990, 1666, 2008} -end run - -- romanValue :: String -> Int on romanValue(s) script roman @@ -18,7 +12,7 @@ on romanValue(s) -- If this glyph:value pair matches the head of the list -- return the value and the tail of the list -- transcribe :: (String, Number) -> Maybe (Number, [String]) - on lambda(lstPair) + on |λ|(lstPair) set lstR to characters of (item 1 of lstPair) if isPrefixOf(lstR, xs) then -- Value of this matching glyph, with any remaining glyphs @@ -26,7 +20,7 @@ on romanValue(s) else {} end if - end lambda + end |λ| end script if length of xs > 0 then @@ -41,8 +35,40 @@ on romanValue(s) toArabic(characters of s) of roman end romanValue +-- TEST ----------------------------------------------------------------------- +on run + map(romanValue, {"MCMXC", "MDCLXVI", "MMVIII"}) --- GENERIC LIBRARY FUNCTIONS + --> {1990, 1666, 2008} +end run + + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- concatMap :: (a -> [b]) -> [a] -> [b] +on concatMap(f, xs) + set lst to {} + set lng to length of xs + tell mReturn(f) + repeat with i from 1 to lng + set lst to (lst & |λ|(item i of xs, i, xs)) + end repeat + end tell + return lst +end concatMap + +-- drop :: Int -> a -> a +on drop(n, a) + if n < length of a then + if class of a is text then + text (n + 1) thru -1 of a + else + items (n + 1) thru -1 of a + end if + else + {} + end if +end drop -- isPrefixOf :: [a] -> [a] -> Bool on isPrefixOf(xs, ys) @@ -59,54 +85,30 @@ on isPrefixOf(xs, ys) end if end isPrefixOf --- drop :: Int -> a -> a -on drop(n, a) - if n < length of a then - if class of a is text then - text (n + 1) thru -1 of a - else - items (n + 1) thru -1 of a - end if - else - {} - end if -end drop - --- concatMap :: (a -> [b]) -> [a] -> [b] -on concatMap(f, xs) - script append - on lambda(a, b) - a & b - end lambda - end script - - foldl(append, {}, map(f, xs)) -end concatMap - --- foldl :: (a -> b -> a) -> a -> [b] -> a -on foldl(f, startValue, xs) - tell mReturn(f) - set v to startValue - set lng to length of xs - repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) - end repeat - return v - end tell -end foldl - -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + -- uncons :: [a] -> Maybe (a, [a]) on uncons(xs) if length of xs > 0 then @@ -115,15 +117,3 @@ on uncons(xs) missing value end if end uncons - --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn diff --git a/Task/Roman-numerals-Decode/AppleScript/roman-numerals-decode-3.applescript b/Task/Roman-numerals-Decode/AppleScript/roman-numerals-decode-3.applescript new file mode 100644 index 0000000000..61b288766c --- /dev/null +++ b/Task/Roman-numerals-Decode/AppleScript/roman-numerals-decode-3.applescript @@ -0,0 +1,103 @@ +use framework "Foundation" + +-- INTEGER VALUE OF ROMAN NUMBER STRING --------------------------------------- + +-- fromRoman :: String -> Int +on fromRoman(s) + script subtractIfLower + on |λ|(rn, L) + set {r, n} to rn + if L ≥ r then -- Digit values that increase (right to left), + {L, n + L} -- are added + else + {L, n - L} -- Digit values that go down, are subtracted. + end if + end |λ| + end script + + snd(foldr(subtractIfLower, {0, 0}, map(my charVal, characters of s))) +end fromRoman + +-- charVal :: Char -> Int +on charVal(C) + set V to keyValue({I:1, V:5, X:10, L:50, C:100, D:500, M:1000}, ¬ + toUpper(C)) + if nothing of V then + 0 + else + just of V + end if +end charVal + +-- TEST ----------------------------------------------------------------------- +on run + map(fromRoman, {"MDCLXVI", "MCMXC", "MMVIII", "MMXVI", "MMXVII"}) + + --> {1666, 1990, 2008, 2016, 2017} +end run + + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- foldr :: (a -> b -> a) -> a -> [b] -> a +on foldr(f, startValue, xs) + tell mReturn(f) + set V to startValue + set lng to length of xs + repeat with I from lng to 1 by -1 + set V to |λ|(V, item I of xs, I, xs) + end repeat + return V + end tell +end foldr + +-- keyValue :: Record -> String -> Maybe String +on keyValue(rec, strKey) + set ca to current application + set V to (ca's NSDictionary's dictionaryWithDictionary:rec)'s objectForKey:strKey + if V is not missing value then + {nothing:false, just:item 1 of ((ca's NSArray's arrayWithObject:V) as list)} + else + {nothing:true} + end if +end keyValue + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with I from 1 to lng + set end of lst to |λ|(item I of xs, I, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- snd :: (a, b) -> b +on snd(xs) + if class of xs is list and length of xs = 2 then + item 2 of xs + else + missing value + end if +end snd + +-- toUpper :: String -> String +on toUpper(str) + set ca to current application + ((ca's NSString's stringWithString:(str))'s ¬ + uppercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text +end toUpper diff --git a/Task/Roman-numerals-Decode/AppleScript/roman-numerals-decode-4.applescript b/Task/Roman-numerals-Decode/AppleScript/roman-numerals-decode-4.applescript new file mode 100644 index 0000000000..8c68ea5ae4 --- /dev/null +++ b/Task/Roman-numerals-Decode/AppleScript/roman-numerals-decode-4.applescript @@ -0,0 +1 @@ +{1666, 1990, 2008, 2016, 2017} diff --git a/Task/Roman-numerals-Decode/Gambas/roman-numerals-decode.gambas b/Task/Roman-numerals-Decode/Gambas/roman-numerals-decode.gambas new file mode 100644 index 0000000000..ba353ec1c9 --- /dev/null +++ b/Task/Roman-numerals-Decode/Gambas/roman-numerals-decode.gambas @@ -0,0 +1,72 @@ +'This code will create a GUI Form and Objects and carry out the Roman Numeral convertion as you type +'The input is case insensitive +'A basic check for invalid charaters is made + +hTextBox As TextBox 'To allow the creation of a TextBox +hValueBox As ValueBox 'To allow the creation of a ValueBox + +Public Sub Form_Open() 'Form opens.. + +SetUpForm 'Go to the SetUpForm Routine +hTextBox.text = "MCMXC" 'Put a Roman numeral in the TextBox + +End + +Public Sub TextBoxInput_Change() 'Each time the TextBox text changes.. +Dim cRomanN As Collection = ["M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1] 'Collection of nemerals e.g 'M' = 1000 +Dim cMinus As Collection = ["IV": -2, "IX": -2, "XL": -20, "XC": - 20, "CD": -200, "CM": -200] 'Collection of the 'one less than' numbers e.g. 'IV' = 4 +Dim sClean, sTemp As String 'Various string variables +Dim siCount As Short 'Counter +Dim iTotal As Integer 'Stores the total of the calculation + +hTextBox.Text = UCase(hTextBox.Text) 'Make any text in the TextBox upper case + +For siCount = 1 To Len(hTextBox.Text) 'Loop through each character in the TextBox + If InStr("MDCLXVI", Mid(hTextBox.Text, siCount, 1)) Then 'If a Roman numeral exists then.. + sClean &= Mid(hTextBox.Text, siCount, 1) 'Put it in 'sClean' (Stops input of non Roman numerals) + End If +Next + +hTextBox.Text = sClean 'Put the now clean text in the TextBox + +For siCount = 1 To Len(hTextBox.Text) 'Loop through each character in the TextBox + iTotal += cRomanN[Mid(hTextBox.Text, siCount, 1)] 'Total up all the characters, note 'IX' will = 11 not 9 +Next + +For Each sTemp In cMinus 'Loop through each item in the cMinus Collection + If InStr(sClean, cMinus.Key) > 0 Then iTotal += Val(sTemp) 'If a 'Minus' value is in the string e.g. 'IX' which has been calculated at 11 subtract 2 = 9 +Next + +hValueBox.text = iTotal 'Display the total + +End + +Public Sub SetUpForm() 'Create the Objects for the Form +Dim hLabel1, hLabel2 As Label 'For 2 Labels + +Me.height = 150 'Form Height +Me.Width = 300 'Form Width +Me.Padding = 20 'Form padding (border) +Me.Text = "Roman Numeral converter" 'Text in Form header +Me.Arrangement = Arrange.Vertical 'Form arrangement + +hLabel1 = New Label(Me) 'Create a Label +hLabel1.Height = 21 'Label Height +hLabel1.expand = True 'Expand the Label +hLabel1.Text = "Enter a Roman numeral" 'Put text in the Label + +hTextBox = New TextBox(Me) As "TextBoxInput" 'Set up a TextBox with an Event Label +hTextBox.Height = 21 'TextBox height +hTextBox.expand = True 'Expand the TextBox + +hLabel2 = New Label(Me) 'Create a Label +hLabel2.Height = 21 'Label Height +hLabel2.expand = True 'Expand the Label +hLabel2.Text = "The decimal equivelent is: -" 'Put text in the Label + +hValueBox = New ValueBox(Me) 'Create a ValueBox +hValueBox.Height = 21 'ValuBox Height +hValueBox.expand = True 'Expand the ValueBox +hValueBox.ReadOnly = True 'Set ValueBox to Read Only + +End diff --git a/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-2.hs b/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-2.hs index 242362e131..88e855c3ed 100644 --- a/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-2.hs +++ b/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-2.hs @@ -1,16 +1,29 @@ import Data.List (mapAccumL, isPrefixOf) +import Control.Arrow ((***)) romanValue :: String -> Int -romanValue s = sum . snd $ mapAccumL tr s - [("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), - ("C", 100), ("XC", 90) ,("L", 50), ("XL", 40), - ("X", 10), ("IX", 9), ("V", 5), ("IV", 4), - ("I", 1)] - where - tr s (k, v) = - until (\(s, _) -> not $ isPrefixOf k s) - (\(s, n) -> (drop (length k) s, n + v)) (s, 0) +romanValue = + let tr s (k, v) = + until (not . isPrefixOf k . fst) (drop (length k) *** (v +)) (s, 0) + in sum . + snd . + flip + (mapAccumL tr) + [ ("M", 1000) + , ("CM", 900) + , ("D", 500) + , ("CD", 400) + , ("C", 100) + , ("XC", 90) + , ("L", 50) + , ("XL", 40) + , ("X", 10) + , ("IX", 9) + , ("V", 5) + , ("IV", 4) + , ("I", 1) + ] main :: IO () -main = mapM_ (putStrLn . show . romanValue) - ["MDCLXVI", "MCMXC", "MMVIII", "MMXVI", "MMXVII"] +main = + mapM_ (print . romanValue) ["MDCLXVI", "MCMXC", "MMVIII", "MMXVI", "MMXVII"] diff --git a/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-3.hs b/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-3.hs new file mode 100644 index 0000000000..2f92485652 --- /dev/null +++ b/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-3.hs @@ -0,0 +1,12 @@ +fromRoman :: String -> Int +fromRoman = + sum . + liftM2 (:) fst snd . + mapAccumR + (\l r -> + ( if l <= r + then r + else (-r) + , l)) + 0 . + fmap charVal diff --git a/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-4.hs b/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-4.hs new file mode 100644 index 0000000000..c4e37c5e45 --- /dev/null +++ b/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-4.hs @@ -0,0 +1,31 @@ +import qualified Data.Map.Strict as M + +fromRoman :: String -> Int +fromRoman xs = partialSum + lastDigit + where + (partialSum, lastDigit) = foldl accumulate (0, 0) (evalRomanDigit <$> xs) + accumulate (partial, lastDigit) newDigit + | newDigit <= lastDigit = (partial + lastDigit, newDigit) + | otherwise = (partial - lastDigit, newDigit) + +mapRoman :: M.Map Char Int +mapRoman = + M.fromList + [ ('I', 1) + , ('V', 5) + , ('X', 10) + , ('L', 50) + , ('C', 100) + , ('D', 500) + , ('M', 1000) + ] + +evalRomanDigit :: Char -> Int +evalRomanDigit c = + let mInt = M.lookup c mapRoman + in case mInt of + Just x -> x + _ -> error $ c : " is not a roman digit" + +main :: IO () +main = print $ fromRoman <$> ["MDCLXVI", "MCMXC", "MMVIII", "MMXVI", "MMXVII"] diff --git a/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-5.hs b/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-5.hs new file mode 100644 index 0000000000..22b4c6ed16 --- /dev/null +++ b/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-5.hs @@ -0,0 +1,13 @@ +fromRoman :: String -> Int +fromRoman = + snd . + foldr + (\l (r, n) -> + ( l + , (if l >= r + then (+) + else (-)) + n + l)) + (0, 0) . + fmap evalRomanDigit diff --git a/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-6.hs b/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-6.hs new file mode 100644 index 0000000000..880e71d9f3 --- /dev/null +++ b/Task/Roman-numerals-Decode/Haskell/roman-numerals-decode-6.hs @@ -0,0 +1,39 @@ +import qualified Data.Map.Strict as M (Map, fromList, lookup) +import Data.Maybe (isNothing, isJust, fromJust, catMaybes) +import Data.List (mapAccumL) + +mapRoman :: M.Map String Int +mapRoman = + M.fromList + [ ("M", 1000) + , ("CM", 900) + , ("D", 500) + , ("CD", 400) + , ("C", 100) + , ("XC", 90) + , ("L", 50) + , ("XL", 40) + , ("X", 10) + , ("IX", 9) + , ("V", 5) + , ("IV", 4) + , ("I", 1) + ] + +fromRoman :: String -> Int +fromRoman s = + let value k = M.lookup k mapRoman + in sum . catMaybes . snd $ + mapAccumL + (\mi (l, r, i) -> + let mValue = value [l, r] -- mapRoman lookup of [left, right] Chars + (lastPair, pairValue) + | isJust mValue = (Just i, mValue) -- Pair match: index updated + | isNothing mi || i - fromJust mi > 1 = (mi, value [l]) + | otherwise = (mi, Nothing) -- Left Char was counted in pair + in (lastPair, pairValue)) + Nothing -- Accumulator – maybe Index to last matched Char pair + (zip3 s (tail s ++ " ") [0 ..]) -- Indexed character pairs + +main :: IO () +main = print $ fromRoman <$> ["MDCLXVI", "MCMXC", "MMVIII", "MMXVI", "MMXVII"] diff --git a/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-1.js b/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-1.js index 191cfef352..e334f1cf09 100644 --- a/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-1.js +++ b/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-1.js @@ -1,19 +1,18 @@ var Roman = { - Values: [['M', 1000], ['CM', 900], ['D', 500], ['CD', 400], - ['C', 100], ['XC', 90], ['L', 50], ['XL', 40], - ['X', 10], ['IX', 9], ['V', 5], ['IV', 4], - ['I', 1]], - + Values: [['CM', 900], ['CD', 400], ['XC', 90], ['XL', 40], ['IV', 4], + ['IX', 9], ['V', 5], ['X', 10], ['L', 50], + ['C', 100], ['M', 1000], ['I', 1], ['D', 500]], + UnmappedStr : 'Q', parse: function(str) { var result = 0 for (var i=0; i { + // romanValue :: String -> Int + const romanValue = s => + s.length ? (() => { + const parse = [].concat( + ...glyphs.map(g => 0 === s.indexOf(g) ? ( + [dctTrans[g], s.substr(g.length)] + ) : []) + ); + return parse[0] + romanValue(parse[1]); + })() : 0; + + // dctTrans :: {romanKey: Integer} + const dctTrans = { + M: 1E3, + CM: 900, + D: 500, + CD: 400, + C: 100, + XC: 90, + L: 50, + XL: 40, + X: 10, + IX: 9, + V: 5, + IV: 4, + I: 1 + }; + + // glyphs :: [romanKey] + const glyphs = Object.keys(dctTrans); + + // TEST ------------------------------------------------------------------- + return ["MCMXC", "MDCLXVI", "MMVIII", "MMMM"].map(romanValue); +})(); diff --git a/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-7.js b/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-7.js new file mode 100644 index 0000000000..4c2ed46181 --- /dev/null +++ b/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-7.js @@ -0,0 +1 @@ +[1990,1666,2008,4000] diff --git a/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-8.js b/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-8.js new file mode 100644 index 0000000000..2272259796 --- /dev/null +++ b/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-8.js @@ -0,0 +1,52 @@ +(() => { + + // Folding from right to left, + // lower leftward characters are subtracted, + // others are added. + + // fromRoman :: String -> Int + const fromRoman = s => + snd(foldr( + ([r, n], l) => [l, l >= r ? n + l : n - l], [0, 0], + map(charVal, stringChars(s)) + )); + + // charVal :: Char -> Maybe Int + const charVal = k => { + const v = { + I: 1, + V: 5, + X: 10, + L: 50, + C: 100, + D: 500, + M: 1000 + }[k]; + return v !== undefined ? v : 0; + }; + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // foldr (a -> b -> b) -> b -> [a] -> b + const foldr = (f, a, xs) => xs.reduceRight(f, a); + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // snd :: (a, b) -> b + const snd = tpl => Array.isArray(tpl) ? tpl[1] : undefined; + + // stringChars :: String -> [Char] + const stringChars = s => s.split(''); + + // show :: a -> String + const show = (...x) => + JSON.stringify.apply( + null, x.length > 1 ? [x[1], null, x[0]] : x + ); + + // TEST ------------------------------------------------------------------- + return show( + map(fromRoman, ["MDCLXVI", "MCMXC", "MMVIII", "MMXVI", "MMXVII"]) + ); +})(); diff --git a/Task/Roman-numerals-Decode/jq/roman-numerals-decode-1.jq b/Task/Roman-numerals-Decode/Jq/roman-numerals-decode-1.jq similarity index 100% rename from Task/Roman-numerals-Decode/jq/roman-numerals-decode-1.jq rename to Task/Roman-numerals-Decode/Jq/roman-numerals-decode-1.jq diff --git a/Task/Roman-numerals-Decode/jq/roman-numerals-decode-2.jq b/Task/Roman-numerals-Decode/Jq/roman-numerals-decode-2.jq similarity index 100% rename from Task/Roman-numerals-Decode/jq/roman-numerals-decode-2.jq rename to Task/Roman-numerals-Decode/Jq/roman-numerals-decode-2.jq diff --git a/Task/Roman-numerals-Decode/jq/roman-numerals-decode-3.jq b/Task/Roman-numerals-Decode/Jq/roman-numerals-decode-3.jq similarity index 100% rename from Task/Roman-numerals-Decode/jq/roman-numerals-decode-3.jq rename to Task/Roman-numerals-Decode/Jq/roman-numerals-decode-3.jq diff --git a/Task/Roman-numerals-Decode/Kotlin/roman-numerals-decode.kotlin b/Task/Roman-numerals-Decode/Kotlin/roman-numerals-decode.kotlin new file mode 100644 index 0000000000..74f3fd84dc --- /dev/null +++ b/Task/Roman-numerals-Decode/Kotlin/roman-numerals-decode.kotlin @@ -0,0 +1,25 @@ +// version 1.0.6 + +fun romanDecode(roman: String): Int { + if (roman.isEmpty()) return 0 + var n = 0 + var last = 'O' + for (c in roman) { + when (c) { + 'I' -> n += 1 + 'V' -> if (last == 'I') n += 3 else n += 5 + 'X' -> if (last == 'I') n += 8 else n += 10 + 'L' -> if (last == 'X') n += 30 else n += 50 + 'C' -> if (last == 'X') n += 80 else n += 100 + 'D' -> if (last == 'C') n += 300 else n += 500 + 'M' -> if (last == 'C') n += 800 else n += 1000 + } + last = c + } + return n +} + +fun main(args: Array) { + val romans = arrayOf("I", "III", "IV", "VIII", "XLIX", "CCII", "CDXXXIII", "MCMXC", "MMVIII", "MDCLXVI") + for (roman in romans) println("${roman.padEnd(10)} = ${romanDecode(roman)}") +} diff --git a/Task/Roman-numerals-Decode/SPL/roman-numerals-decode.spl b/Task/Roman-numerals-Decode/SPL/roman-numerals-decode.spl new file mode 100644 index 0000000000..6b10b85630 --- /dev/null +++ b/Task/Roman-numerals-Decode/SPL/roman-numerals-decode.spl @@ -0,0 +1,16 @@ +r2a(r)= + n = [1,5,10,50,100,500,1000] + a,m = 0 + > i, #.size(r)..1, -1 + v,c = n[#.pos("IVXLCDM",#.mid(r,i))] + ? vm, m = c + a += v + < + <= a +. + +t = ["MMXI","MIM","MCMLVI","MDCLXVI","XXCIII","LXXIIX","IIIIX"] +> i, 1..#.size(t,1) + #.output(t[i]," = ",r2a(t[i])) +< diff --git a/Task/Roman-numerals-Decode/Sidef/roman-numerals-decode-1.sidef b/Task/Roman-numerals-Decode/Sidef/roman-numerals-decode-1.sidef index c7f679c17a..36be9bfe6b 100644 --- a/Task/Roman-numerals-Decode/Sidef/roman-numerals-decode-1.sidef +++ b/Task/Roman-numerals-Decode/Sidef/roman-numerals-decode-1.sidef @@ -1,9 +1,9 @@ func roman2arabic(roman) { - - var arabic = 0; - var last_digit = 1000; - - static m = Hash.new( +  + var arabic = 0 + var last_digit = 1000 +  + static m = Hash( I => 1, V => 5, X => 10, @@ -11,18 +11,18 @@ func roman2arabic(roman) { C => 100, D => 500, M => 1000, - ); - - roman.uc.split('').map{m{_} \\ 0}.each { |digit| - last_digit < digit && ( - arabic -= (2 * last_digit); - ); - arabic += (last_digit = digit); + ) +  + roman.uc.chars.map{m{_} \\ 0}.each { |digit| + if (last_digit < digit) { + arabic -= (2 * last_digit) + } + arabic += (last_digit = digit) } - - return arabic; +  + return arabic } - +  %w(MCMXC MMVIII MDCLXVI).each { |roman_digit| - "%-10s == %d\n".printf(roman_digit, roman2arabic(roman_digit)); + "%-10s == %d\n".printf(roman_digit, roman2arabic(roman_digit)) } diff --git a/Task/Roman-numerals-Decode/Sidef/roman-numerals-decode-2.sidef b/Task/Roman-numerals-Decode/Sidef/roman-numerals-decode-2.sidef index da9b32d38f..f790a94393 100644 --- a/Task/Roman-numerals-Decode/Sidef/roman-numerals-decode-2.sidef +++ b/Task/Roman-numerals-Decode/Sidef/roman-numerals-decode-2.sidef @@ -15,7 +15,7 @@ func roman2arabic(digit) { :I: '1+', ]).split('+').map{.to_i}.sum; } - +  %w(MCMXC MMVIII MDCLXVI).each { |roman_num| say "#{roman_num}\t-> #{roman2arabic(roman_num)}"; } diff --git a/Task/Roman-numerals-Decode/Simula/roman-numerals-decode.simula b/Task/Roman-numerals-Decode/Simula/roman-numerals-decode.simula new file mode 100644 index 0000000000..608acf89c1 --- /dev/null +++ b/Task/Roman-numerals-Decode/Simula/roman-numerals-decode.simula @@ -0,0 +1,45 @@ +BEGIN + + INTEGER PROCEDURE FROMROMAN(S); TEXT S; + BEGIN + PROCEDURE P(INTVAL, NUM); INTEGER INTVAL; TEXT NUM; + BEGIN + INTEGER NLEN; + NLEN := NUM.LENGTH; + WHILE INDEX + NLEN - 1 <= SLEN AND THEN + S.SUB(INDEX, NLEN) = NUM DO + BEGIN + RESULT := RESULT + INTVAL; + INDEX := INDEX + NLEN; + END WHILE; + END P; + INTEGER RESULT, INDEX, SLEN; + SLEN := S.LENGTH; + INDEX := 1; + P( 1000, "M" ); + P( 900, "CM" ); + P( 500, "D" ); + P( 400, "CD" ); + P( 100, "C" ); + P( 90, "XC" ); + P( 50, "L" ); + P( 40, "XL" ); + P( 10, "X" ); + P( 9, "IX" ); + P( 5, "V" ); + P( 4, "IV" ); + P( 1, "I" ); + FROMROMAN := RESULT; + END FROMROMAN; + + TEXT T; + FOR T :- "MCMXC", "MMVIII", "MDCLXVI" DO + BEGIN + OUTTEXT("ROMAN """); + OUTTEXT(T); + OUTTEXT(""" => "); + OUTINT(FROMROMAN(T), 0); + OUTIMAGE; + END FOR; + +END PROGRAM; diff --git a/Task/Roman-numerals-Decode/Swift/roman-numerals-decode-3.swift b/Task/Roman-numerals-Decode/Swift/roman-numerals-decode-3.swift new file mode 100644 index 0000000000..ce822418d5 --- /dev/null +++ b/Task/Roman-numerals-Decode/Swift/roman-numerals-decode-3.swift @@ -0,0 +1,34 @@ +func rtoa( str1: String) -> Int { + var str = str1 + var result = 0 + + for (value, letter) in + + [ ( 1000, "M"), + ( 900, "CM"), + ( 500, "D"), + ( 400, "CD"), + ( 100, "C"), + ( 90, "XC"), + ( 50, "L"), + ( 40, "XL"), + ( 10, "X"), + ( 9, "IX"), + ( 5, "V"), + ( 3, "IIV"), + ( 4, "IV"), + ( 1, "I")] + { + while str.hasPrefix(letter) { + + let first = str.startIndex + let count = letter.characters.count + str.removeSubrange(first ..< str.index(first, offsetBy: count)) + result += value + } + } + return result +} + + +print(rtoa("MDCLXVI")) // 1666 diff --git a/Task/Roman-numerals-Decode/TechBASIC/roman-numerals-decode.techbasic b/Task/Roman-numerals-Decode/TechBASIC/roman-numerals-decode.techbasic new file mode 100644 index 0000000000..74ef4b6774 --- /dev/null +++ b/Task/Roman-numerals-Decode/TechBASIC/roman-numerals-decode.techbasic @@ -0,0 +1,48 @@ +Main: +!------------------------------------------------ +! CALLS THE romToDec FUNCTION WITH THE ROMAN +! NUMERALS AND RETURNS ITS DECIMAL EQUIVELENT. +! + + PRINT "MCMXC = "; romToDec("MCMXC") !1990 + PRINT "MMVIII = "; romToDec("MMVIII") !2008 + PRINT "MDCLXVI = "; romToDec("MDCLXVI") !1666 + PRINT:PRINT + PRINT "Here are other solutions not from the TASK:" + PRINT "MCMXCIX = "; romToDec("MCMXCIX") !1999 + PRINT "XXV = "; romToDec("XXV") !25 + PRINT "CMLIV = "; romToDec("CMLIV") !954 + PRINT "MMXI = "; romToDec("MMXI") !2011 + PRINT:PRINT + PRINT "Without error checking, this also is 2011, but is wrong" + PRINT "MMIIIX = "; romToDec("MMIIIX") !INVAID, 2011 + +STOP + + +FUNCTION romToDec(roman AS STRING) AS INTEGER +!------------------------------------------------------ +! FUNCTION THAT CONVERTS ANY ROMAN NUMERAL TO A DECIMAL +! + prenum=0!num=0 + ln=LEN(roman) + FOR i=ln TO 1 STEP -1 + x$=MID(roman,i,1) + n=1000 + SELECT CASE x$ + CASE "M":n=n/1 + CASE "D":n=n/2 + CASE "C":n=n/10 + CASE "L":n=n/20 + CASE "X":n=n/100 + CASE "V":n=n/200 + CASE "I":n=n/n + CASE ELSE:n=0 + END SELECT + IF n < preNum THEN num=num-n ELSE num=num+n + preNum=n + next i + + romToDec=num + +END FUNCTION diff --git a/Task/Roman-numerals-Decode/Zkl/roman-numerals-decode.zkl b/Task/Roman-numerals-Decode/Zkl/roman-numerals-decode.zkl new file mode 100644 index 0000000000..502fb59441 --- /dev/null +++ b/Task/Roman-numerals-Decode/Zkl/roman-numerals-decode.zkl @@ -0,0 +1,16 @@ +var romans = L( + L("M", 1000), L("CM", 900), L("D", 500), L("CD", 400), L("C", 100), + L("XC", 90), L("L", 50), L("XL", 40), L("X", 10), L("IX", 9), + L("V", 5), L("IV", 4), L("I", 1)); +fcn toArabic(romanNumber){ // romanNumber needs to be upper case + if (not RegExp("^[CDILMVX]+$").matches(romanNumber)) + throw(Exception.ValueError("Not a Roman number: %s".fmt(romanNumber))); + reg value = 0; + foreach R,N in (romans){ + while (0 == romanNumber.find(R)){ + value += N; + romanNumber = romanNumber[R.len(),*]; + } + } + return(value); +} diff --git a/Task/Roman-numerals-Encode/AppleScript/roman-numerals-encode.applescript b/Task/Roman-numerals-Encode/AppleScript/roman-numerals-encode.applescript index e22095ff6b..d2a1c30310 100644 --- a/Task/Roman-numerals-Encode/AppleScript/roman-numerals-encode.applescript +++ b/Task/Roman-numerals-Encode/AppleScript/roman-numerals-encode.applescript @@ -1,37 +1,51 @@ +-- ROMAN INTEGER STRINGS ------------------------------------------------------ -- roman :: Int -> String on roman(n) - script romanDigits - on lambda(a, lstPair) - set n to remainder of a - set v to item 1 of lstPair + set kvs to {["M", 1000], ["CM", 900], ["D", 500], ¬ + ["CD", 400], ["C", 100], ["XC", 90], ["L", 50], ["XL", 40], ¬ + ["X", 10], ["IX", 9], ["V", 5], ["IV", 4], ["I", 1]} - if v > n then - a + script stringAddedValueDeducted + on |λ|(balance, kv) + set {k, v} to kv + set {q, r} to quotRem(balance, v) + if q > 0 then + {r, concat(replicate(q, k))} else - {remainder:n mod v, roman:(roman of a) & ¬ - replicate(n div v, item 2 of lstPair)} + {r, ""} end if - end lambda + end |λ| end script - roman of foldl(romanDigits, {remainder:n, roman:""}, ¬ - [[1000, "M"], [900, "CM"], [500, "D"], ¬ - [400, "CD"], [100, "C"], [90, "XC"], [50, "L"], [40, "XL"], ¬ - [10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"]]) + concat(snd(mapAccumL(stringAddedValueDeducted, n, kvs))) end roman - --- TEST - +-- TEST ----------------------------------------------------------------------- on run + map(roman, [2016, 1990, 2008, 2000, 1666]) --> {"MMXVI", "MCMXC", "MMVIII", "MM", "MDCLXVI"} end run +-- GENERIC LIBRARY FUNCTIONS -------------------------------------------------- --- GENERIC LIBRARY FUNCTIONS +-- concat :: [[a]] -> [a] | [String] -> String +on concat(xs) + script append + on |λ|(a, b) + a & b + end |λ| + end script + + if length of xs > 0 and class of (item 1 of xs) is string then + set unit to "" + else + set unit to {} + end if + foldl(append, unit, xs) +end concat -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) @@ -39,7 +53,7 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -51,25 +65,55 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map +-- 'The mapAccumL function behaves like a combination of map and foldl; +-- it applies a function to each element of a list, passing an +-- accumulating parameter from left to right, and returning a final +-- value of this accumulator together with the new list.' (see Hoogle) + +-- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) +on mapAccumL(f, acc, xs) + script + on |λ|(a, x) + tell mReturn(f) to set pair to |λ|(item 1 of a, x) + [item 1 of pair, (item 2 of a) & {item 2 of pair}] + end |λ| + end script + + foldl(result, [acc, {}], xs) +end mapAccumL + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- quotRem :: Integral a => a -> a -> (a, a) +on quotRem(m, n) + {m div n, m mod n} +end quotRem + -- Egyptian multiplication - progressively doubling a list, appending -- stages of doubling to an accumulator where needed for binary -- assembly of a target length -- replicate :: Int -> a -> [a] on replicate(n, a) - if class of a is list then - set out to {} - else - set out to "" - end if + set out to {} if n < 1 then return out - set dbl to a + set dbl to {a} repeat while (n > 1) if (n mod 2) > 0 then set out to out & dbl @@ -79,14 +123,11 @@ on replicate(n, a) return out & dbl end replicate --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f +-- snd :: (a, b) -> b +on snd(xs) + if class of xs is list and length of xs = 2 then + item 2 of xs else - script - property lambda : f - end script + missing value end if -end mReturn +end snd diff --git a/Task/Roman-numerals-Encode/Haskell/roman-numerals-encode-1.hs b/Task/Roman-numerals-Encode/Haskell/roman-numerals-encode-1.hs index 1bb1ed0b84..dfdc914e61 100644 --- a/Task/Roman-numerals-Encode/Haskell/roman-numerals-encode-1.hs +++ b/Task/Roman-numerals-Encode/Haskell/roman-numerals-encode-1.hs @@ -1,13 +1,23 @@ +digit :: Char -> Char -> Char -> Integer -> String digit x y z k = - [[x],[x,x],[x,x,x],[x,y],[y],[y,x],[y,x,x],[y,x,x,x],[x,z]] !! + [[x], [x, x], [x, x, x], [x, y], [y], [y, x], [y, x, x], [y, x, x, x], [x, z]] !! (fromInteger k - 1) toRoman :: Integer -> String toRoman 0 = "" -toRoman x | x < 0 = error "Negative roman numeral" -toRoman x | x >= 1000 = 'M' : toRoman (x - 1000) -toRoman x | x >= 100 = digit 'C' 'D' 'M' q ++ toRoman r where - (q,r) = x `divMod` 100 -toRoman x | x >= 10 = digit 'X' 'L' 'C' q ++ toRoman r where - (q,r) = x `divMod` 10 -toRoman x = digit 'I' 'V' 'X' x +toRoman x + | x < 0 = error "Negative roman numeral" +toRoman x + | x >= 1000 = 'M' : toRoman (x - 1000) +toRoman x + | x >= 100 = digit 'C' 'D' 'M' q ++ toRoman r + where + (q, r) = x `divMod` 100 +toRoman x + | x >= 10 = digit 'X' 'L' 'C' q ++ toRoman r + where + (q, r) = x `divMod` 10 +toRoman x = digit 'I' 'V' 'X' x + +main :: IO () +main = print $ toRoman <$> [1999, 25, 944] diff --git a/Task/Roman-numerals-Encode/Haskell/roman-numerals-encode-2.hs b/Task/Roman-numerals-Encode/Haskell/roman-numerals-encode-2.hs index e5754d187c..8b1c7bea40 100644 --- a/Task/Roman-numerals-Encode/Haskell/roman-numerals-encode-2.hs +++ b/Task/Roman-numerals-Encode/Haskell/roman-numerals-encode-2.hs @@ -1,15 +1,28 @@ import Data.List (mapAccumL) roman :: Int -> String -roman n = concatMap concat . snd $ mapAccumL tr n - [(1000, "M"), (900, "CM"), (500, "D") ,( 400, "CD"), - ( 100, "C"), ( 90, "XC") ,( 50, "L"), ( 40, "XL"), - ( 10, "X"), ( 9, "IX"), ( 5, "V"), ( 4, "IV"), - ( 1, "I")] - where - tr a (m, s) = (r, replicate q s) - where - (q, r) = quotRem a m +roman n = + concat + (snd + (mapAccumL + (\a (m, s) -> + let (q, r) = quotRem a m + in (r, [1 .. q] >> s)) + n + [ (1000, "M") + , (900, "CM") + , (500, "D") + , (400, "CD") + , (100, "C") + , (90, "XC") + , (50, "L") + , (40, "XL") + , (10, "X") + , (9, "IX") + , (5, "V") + , (4, "IV") + , (1, "I") + ])) main :: IO () main = mapM_ (putStrLn . roman) [1666, 1990, 2008, 2016, 2017] diff --git a/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-4.js b/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-4.js index 8f5d7fff24..ea1560407c 100644 --- a/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-4.js +++ b/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-4.js @@ -1,55 +1,71 @@ (() => { - 'use strict'; + // ROMAN INTEGER STRINGS ---------------------------------------------------- // roman :: Int -> String - const roman = n => [ - [1000, "M"], - [900, "CM"], - [500, "D"], - [400, "CD"], - [100,"C"], - [90, "XC"], - [50, "L"], - [40, "XL"], - [10, "X"], - [9,"IX"], - [5, "V"], - [4, "IV"], - [1, "I"] - ] - .reduce((a, lstPair) => { - const m = a.remainder, - v = lstPair[0]; - return (v > m ? a : { - remainder: m % v, - roman: a.roman + Array( - Math.floor(m / v) + 1 - ) - .join(lstPair[1]) - }); - }, { - remainder: n, - roman: '' - }) - .roman; + const roman = n => + concat(snd(mapAccumL((balance, [k, v]) => { + const [q, r] = quotRem(balance, v); + return [r, q > 0 ? concat(replicate(q, k)) : '']; + }, n, [ + ['M', 1000], + ['CM', 900], + ['D', 500], + ['CD', 400], + ['C', 100], + ['XC', 90], + ['L', 50], + ['XL', 40], + ['X', 10], + ['IX', 9], + ['V', 5], + ['IV', 4], + ['I', 1] + ]))); - // TEST + // GENERIC FUNCTIONS ------------------------------------------------------- - // If the input is a decimal string, pass any delimiters through - // romanTranscription :: (Int | String) -> String - const romanTranscription = a => { - if (typeof a === 'string') { - const ps = a.split(/\d+/), - dlm = ps.length > 1 ? ps[1] : undefined; + // concat :: [[a]] -> [a] | [String] -> String + const concat = xs => + xs.length > 0 ? (() => { + const unit = typeof xs[0] === 'string' ? '' : []; + return unit.concat.apply(unit, xs); + })() : []; - return (dlm ? a.split(dlm) - .map(Number) : [a]) - .map(roman) - .join(dlm); - } else return roman(a); - } + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); - // TEST - return [2016, 1990, 2008, "14.09.2015", 2000, 1666] - .map(romanTranscription); + // 'The mapAccumL function behaves like a combination of map and foldl; + // it applies a function to each element of a list, passing an accumulating + // parameter from left to right, and returning a final value of this + // accumulator together with the new list.' (See Hoogle) + + // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) + const mapAccumL = (f, acc, xs) => + xs.reduce((a, x) => { + const pair = f(a[0], x); + return [pair[0], a[1].concat([pair[1]])]; + }, [acc, []]); + + // quotRem :: Integral a => a -> a -> (a, a) + const quotRem = (m, n) => [Math.floor(m / n), m % n]; + + // replicate :: Int -> a -> [a] + const replicate = (n, x) => + Array.from({ + length: n + }, () => x); + + // show :: a -> String + const show = (...x) => + JSON.stringify.apply( + null, x.length > 1 ? [x[0], null, x[1]] : x + ); + + // snd :: (a, b) -> b + const snd = tpl => Array.isArray(tpl) ? tpl[1] : undefined; + + // TEST ------------------------------------------------------------------- + return show( + map(roman, [2016, 1990, 2008, 2000, 1666]) + ); })(); diff --git a/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-5.js b/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-5.js index 76a1730b6e..f672c74d0b 100644 --- a/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-5.js +++ b/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-5.js @@ -1,8 +1 @@ -[ - "MMXVI", - "MCMXC", - "MMVIII", - "XIV.IX.MMXV", - "MM", - "MDCLXVI" -] +["MMXVI","MCMXC","MMVIII","MM","MDCLXVI"] diff --git a/Task/Roman-numerals-Encode/Kotlin/roman-numerals-encode.kotlin b/Task/Roman-numerals-Encode/Kotlin/roman-numerals-encode.kotlin index 6bc5d0aada..3fd94cf31a 100644 --- a/Task/Roman-numerals-Encode/Kotlin/roman-numerals-encode.kotlin +++ b/Task/Roman-numerals-Encode/Kotlin/roman-numerals-encode.kotlin @@ -19,14 +19,14 @@ fun encode(number: Int): String? { return null } var num = number - val buffer = StringBuffer() - for ((multiple, numeral) in romanNumerals) { + var result = "" + for ((multiple, numeral) in romanNumerals.entries) { while (num >= multiple) { num -= multiple - buffer.append(numeral) + result += numeral } } - return buffer.toString() + return result } fun main(args: Array) { diff --git a/Task/Roman-numerals-Encode/Mathematica/roman-numerals-encode-5.math b/Task/Roman-numerals-Encode/Mathematica/roman-numerals-encode-5.math deleted file mode 100644 index 9215a87478..0000000000 --- a/Task/Roman-numerals-Encode/Mathematica/roman-numerals-encode-5.math +++ /dev/null @@ -1,48 +0,0 @@ -:- module roman2. - -:- interface. - -:- import_module io. - -:- pred main(io::di, io::uo) is det. - -:- implementation. - -:- import_module char, int, list, string. - -main(!IO) :- - command_line_arguments(Args, !IO), - filter_map(to_int, Args, CleanArgs), - foldl((pred(Arg::in, !.IO::di, !:IO::uo) is det :- - ( Roman = to_roman(Arg) -> - format("%i => %s", - [i(Arg), s(from_char_list(Roman))], !IO), - nl(!IO) - ; format("%i cannot be converted.", [i(Arg)], !IO), nl(!IO) ) - ), CleanArgs, !IO). - -:- func to_roman(int) = list(char). -:- mode to_roman(in) = out is semidet. -to_roman(N) = ( N >= 1000 -> - ['M'] ++ to_roman(N - 1000) - ;( N >= 100 -> - digit(N / 100, 'C', 'D', 'M') ++ to_roman(N rem 100) - ;( N >= 10 -> - digit(N / 10, 'X', 'L', 'C') ++ to_roman(N rem 10) - ;( N >= 1 -> - digit(N, 'I', 'V', 'X') - ; [] ) ) ) ). - -:- func digit(int, char, char, char) = list(char). -:- mode digit(in, in, in, in) = out is semidet. -digit(1, X, _, _) = [X]. -digit(2, X, _, _) = [X, X]. -digit(3, X, _, _) = [X, X, X]. -digit(4, X, Y, _) = [X, Y]. -digit(5, _, Y, _) = [Y]. -digit(6, X, Y, _) = [Y, X]. -digit(7, X, Y, _) = [Y, X, X]. -digit(8, X, Y, _) = [Y, X, X, X]. -digit(9, X, _, Z) = [X, Z]. - -:- end_module roman2. diff --git a/Task/Roman-numerals-Encode/PlainTeX/roman-numerals-encode.tex b/Task/Roman-numerals-Encode/PlainTeX/roman-numerals-encode.tex new file mode 100644 index 0000000000..acd2042e35 --- /dev/null +++ b/Task/Roman-numerals-Encode/PlainTeX/roman-numerals-encode.tex @@ -0,0 +1,3 @@ +\def\upperroman#1{\uppercase\expandafter{\romannumeral#1}} +Anno Domini \upperroman{\year} +\bye diff --git a/Task/Roman-numerals-Encode/Protium/roman-numerals-encode-1.protium b/Task/Roman-numerals-Encode/Protium/roman-numerals-encode-1.protium deleted file mode 100644 index fe4922fcc7..0000000000 --- a/Task/Roman-numerals-Encode/Protium/roman-numerals-encode-1.protium +++ /dev/null @@ -1,5 +0,0 @@ -<@ DEFUDOLITLIT>_RO|__Transformer|<@ DEFKEYPAR>__NationalNumericID|2<@ LETRESCS%NNMPAR>...|1 - -<@ ENU$$DLSTLITLIT>1990,2008,1,2,64,124,1666,10001|,| -<@ SAYELTLST>... is <@ SAY_ROELTLSTLIT>...|RomanLowerUnicode <@ SAY_ROELTLSTLIT>...|RomanUpperUnicode <@ SAY_ROELTLSTLIT>...|RomanASCII - diff --git a/Task/Roman-numerals-Encode/Protium/roman-numerals-encode-2.protium b/Task/Roman-numerals-Encode/Protium/roman-numerals-encode-2.protium deleted file mode 100644 index 4fb8483617..0000000000 --- a/Task/Roman-numerals-Encode/Protium/roman-numerals-encode-2.protium +++ /dev/null @@ -1,5 +0,0 @@ -<# DEFINE USERDEFINEDOPCODE LITERAL LITERAL>_RO|__Transformer|<# DEFINE KEYWORD PARAMETER>__NationalNumericID|2<# LET RESULT CAST NATIONALNUMBER PARAMETER>...|1 - -<# ENUMERATION LAMBDASPECIFIEDDELMITER LIST LITERAL LITERAL>1990,2008,1,2,64,124,1666,10001|,| -<# SAY ELEMENT LIST>... is <# SAY _RO ELEMENT LIST LITERAL>...|RomanLowerUnicode <# SAY _RO ELEMENT LIST LITERAL>...|RomanUpperUnicode <# SAY _RO ELEMENT LIST LITERAL>...|RomanASCII - diff --git a/Task/Roman-numerals-Encode/SPL/roman-numerals-encode.spl b/Task/Roman-numerals-Encode/SPL/roman-numerals-encode.spl new file mode 100644 index 0000000000..afa44eecd1 --- /dev/null +++ b/Task/Roman-numerals-Encode/SPL/roman-numerals-encode.spl @@ -0,0 +1,16 @@ +a2r(a)= + r = "" + n = [["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"],[1000,900,500,400,100,90,50,40,10,9,5,4,1]] + > i, 1..13 + > a! i, 1..#.size(t,1) + #.output(t[i]," = ",a2r(t[i])) +< diff --git a/Task/Roman-numerals-Encode/Simula/roman-numerals-encode.simula b/Task/Roman-numerals-Encode/Simula/roman-numerals-encode.simula new file mode 100644 index 0000000000..126b74c591 --- /dev/null +++ b/Task/Roman-numerals-Encode/Simula/roman-numerals-encode.simula @@ -0,0 +1,40 @@ +BEGIN + + TEXT PROCEDURE TOROMAN(N); INTEGER N; + BEGIN + PROCEDURE P(WEIGHT,LIT); INTEGER WEIGHT; TEXT LIT; + BEGIN + WHILE N >= WEIGHT DO + BEGIN + T :- T & LIT; + N := N - WEIGHT; + END WHILE; + END P; + TEXT T; T :- NOTEXT; + P( 1000, "M" ); + P( 900, "CM" ); + P( 500, "D" ); + P( 400, "CD" ); + P( 100, "C" ); + P( 90, "XC" ); + P( 50, "L" ); + P( 40, "XL" ); + P( 10, "X" ); + P( 9, "IX" ); + P( 5, "V" ); + P( 4, "IV" ); + P( 1, "I" ); + TOROMAN :- T; + END TOROMAN; + + INTEGER Y; + FOR Y := 1990, 2008, 1666 DO + BEGIN + OUTTEXT("YEAR "); + OUTINT(Y, 4); + OUTTEXT(" => "); + OUTTEXT(TOROMAN(Y)); + OUTIMAGE; + END FOR; + +END PROGRAM; diff --git a/Task/Roman-numerals-Encode/Zkl/roman-numerals-encode.zkl b/Task/Roman-numerals-Encode/Zkl/roman-numerals-encode.zkl new file mode 100644 index 0000000000..a69071fbb8 --- /dev/null +++ b/Task/Roman-numerals-Encode/Zkl/roman-numerals-encode.zkl @@ -0,0 +1,9 @@ +var [const] romans = L( + L("M", 1000), L("CM", 900), L("D", 500), L("CD", 400), L("C", 100), + L("XC", 90), L("L", 50), L("XL", 40), L("X", 10), L("IX", 9), + L("V", 5), L("IV", 4), L("I", 1)); +fcn toRoman(i){ // convert int to a roman number + reg text = ""; + foreach R,N in (romans){ text += R*(i/N); i = i%N; } + return(text); +} diff --git a/Task/Roots-of-a-function/jq/roots-of-a-function-1.jq b/Task/Roots-of-a-function/Jq/roots-of-a-function-1.jq similarity index 100% rename from Task/Roots-of-a-function/jq/roots-of-a-function-1.jq rename to Task/Roots-of-a-function/Jq/roots-of-a-function-1.jq diff --git a/Task/Roots-of-a-function/jq/roots-of-a-function-2.jq b/Task/Roots-of-a-function/Jq/roots-of-a-function-2.jq similarity index 100% rename from Task/Roots-of-a-function/jq/roots-of-a-function-2.jq rename to Task/Roots-of-a-function/Jq/roots-of-a-function-2.jq diff --git a/Task/Roots-of-a-function/Kotlin/roots-of-a-function.kotlin b/Task/Roots-of-a-function/Kotlin/roots-of-a-function.kotlin new file mode 100644 index 0000000000..c0bbaa547d --- /dev/null +++ b/Task/Roots-of-a-function/Kotlin/roots-of-a-function.kotlin @@ -0,0 +1,50 @@ +// version 1.1.2 + +typealias DoubleToDouble = (Double) -> Double + +fun f(x: Double) = x * x * x - 3.0 * x * x + 2.0 * x + +fun secant(x1: Double, x2: Double, f: DoubleToDouble): Double { + val e = 1.0e-12 + val limit = 50 + var xa = x1 + var xb = x2 + var fa = f(xa) + var i = 0 + while (i++ < limit) { + var fb = f(xb) + val d = (xb - xa) / (fb - fa) * fb + if (Math.abs(d) < e) break + xa = xb + fa = fb + xb -= d + } + if (i == limit) { + println("Function is not converging near (${"%7.4f".format(xa)}, ${"%7.4f".format(xb)}).") + return -99.0 + } + return xb +} + +fun main(args: Array) { + val step = 1.0e-2 + val e = 1.0e-12 + var x = -1.032 + var s = f(x) > 0.0 + while (x < 3.0) { + val value = f(x) + if (Math.abs(value) < e) { + println("Root found at x = ${"%12.9f".format(x)}") + s = f(x + 0.0001) > 0.0 + } + else if ((value > 0.0) != s) { + val xx = secant(x - step, x, ::f) + if (xx != -99.0) + println("Root found at x = ${"%12.9f".format(xx)}") + else + println("Root found near x = ${"%7.4f".format(x)}") + s = f(x + 0.0001) > 0.0 + } + x += step + } +} diff --git a/Task/Roots-of-a-function/Phix/roots-of-a-function.phix b/Task/Roots-of-a-function/Phix/roots-of-a-function.phix new file mode 100644 index 0000000000..6e330b3034 --- /dev/null +++ b/Task/Roots-of-a-function/Phix/roots-of-a-function.phix @@ -0,0 +1,32 @@ +procedure print_roots(integer f, atom start, atom stop, atom step) +-- Print approximate roots of f between x=start and x=stop, using +-- sign changes as an indicator that a root has been encountered. +atom x = start, y = 0 + + puts(1,"-----\n") + while x<=stop do + atom last_y = y + y = call_func(f,{x}) + if y=0 + or (last_y<0 and y>0) + or (last_y>0 and y<0) then + printf(1,"Root found %s %.10g\n", {iff(y=0?"at":"near"),x}) + end if + x += step + end while +end procedure + +-- Smaller steps produce more accurate/precise results in general, +-- but for many functions we'll never get exact roots, either due +-- to imperfect binary representation or irrational roots. +constant step = 1/256 + +function f1(atom x) return x*x*x-3*x*x+2*x end function +function f2(atom x) return x*x-4*x+3 end function +function f3(atom x) return x-1.5 end function +function f4(atom x) return x*x-2 end function + +print_roots(routine_id("f1"), -1, 5, step) +print_roots(routine_id("f2"), -1, 5, step) +print_roots(routine_id("f3"), 0, 4, step) +print_roots(routine_id("f4"), -2, 2, step) diff --git a/Task/Roots-of-a-function/REXX/roots-of-a-function-1.rexx b/Task/Roots-of-a-function/REXX/roots-of-a-function-1.rexx index db33bccef1..93f6e66b49 100644 --- a/Task/Roots-of-a-function/REXX/roots-of-a-function-1.rexx +++ b/Task/Roots-of-a-function/REXX/roots-of-a-function-1.rexx @@ -1,18 +1,18 @@ -/*REXX pgm finds roots of a specific function: x^3 -3*x^2 +2*x via bisection.*/ -parse arg bot top inc . /*obtain optional arguments from the CL*/ -if bot=='' | bot==',' then bot= -5 /*Not specified? Then use the default.*/ -if top=='' | top==',' then top= +5 /* " " " " " " */ -if inc=='' | inc==',' then inc= .0001 /* " " " " " " */ -z=f(bot); !=sign(z) /*use these values for initial compare.*/ +/*REXX program finds the roots of a specific function: x^3 - 3*x^2 + 2*x via bisection*/ +parse arg bot top inc . /*obtain optional arguments from the CL*/ +if bot=='' | bot=="," then bot= -5 /*Not specified? Then use the default.*/ +if top=='' | top=="," then top= +5 /* " " " " " " */ +if inc=='' | inc=="," then inc= .0001 /* " " " " " " */ +z=f(bot-inc); !=sign(z) /*use these values for initial compare.*/ - do j=bot to top by inc /*traipse through the specified range. */ - z=f(j); $=sign(z) /*compute the new value and the sign.*/ - if z=0 then say 'found an exact root at' j/1 - else if !\==$ then if !\==0 then say 'passed a root at' j/1 - !=$ /*use the new sign for the next compare*/ - end /*j*/ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -f: parse arg x; return x*(x*(x-3)+2) /* x^3 - 3x^2 + 2x */ - /*with factoring ──► x{ x^2 -3x + 2 } */ - /*more " ──► x{ x( x-3 ) + 2 } */ + do j=bot to top by inc /*traipse through the specified range. */ + z=f(j); $=sign(z) /*compute new value; obtain the sign. */ + if z=0 then say 'found an exact root at' j/1 + else if !\==$ then if !\==0 then say 'passed a root at' j/1 + !=$ /*use the new sign for the next compare*/ + end /*j*/ /*dividing by unity normalizes J [↑] */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +f: parse arg x; return x*(x*(x-3)+2) /*formula used ──► x^3 - 3x^2 + 2x */ + /*with factoring ──► x{ x^2 -3x + 2 } */ + /*more " ──► x{ x( x-3 ) + 2 } */ diff --git a/Task/Roots-of-a-function/REXX/roots-of-a-function-2.rexx b/Task/Roots-of-a-function/REXX/roots-of-a-function-2.rexx index ddee5551c5..177c565e40 100644 --- a/Task/Roots-of-a-function/REXX/roots-of-a-function-2.rexx +++ b/Task/Roots-of-a-function/REXX/roots-of-a-function-2.rexx @@ -1,11 +1,14 @@ -/* REXX */ -Parse Version v; Say v -n=1000000 -Say 'N='n -Call time 'R'; Do i=1 To n; xx=f1(5); End; Say 'f1' xx time('E') -Call time 'R'; Do i=1 To n; xx=f2(5); End; Say 'f2' xx time('E') -Call time 'R'; Do i=1 To n; xx=f3(5); End; Say 'f3' xx time('E') -Exit -f1: procedure; parse arg x; return x**3 - 3 * x**2 + 2 * x -f2: procedure; parse arg x; x2=x*x; return x*x2 - 3*x2 + x+x -f3: Return((arg(1)-3)*arg(1)+2)*arg(1) +/*REXX program finds the roots of a specific function: x^3 - 3*x^2 + 2*x via bisection*/ +parse arg bot top inc . /*obtain optional arguments from the CL*/ +if bot=='' | bot=="," then bot= -5 /*Not specified? Then use the default.*/ +if top=='' | top=="," then top= +5 /* " " " " " " */ +if inc=='' | inc=="," then inc= .0001 /* " " " " " " */ +x=bot-inc /*compute 1st value to start compares. */ +z=x*(x*(x-3)+2) /*formula used ──► x^3 - 3x^2 + 2x */ +!=sign(z) /*obtain the sign of the initial value.*/ + do x=bot to top by inc /*traipse through the specified range. */ + z=x*(x*(x-3)+2); $=sign(z) /*compute new value; obtain the sign. */ + if z=0 then say 'found an exact root at' x/1 + else if !\==$ then if !\==0 then say 'passed a root at' x/1 + !=$ /*use the new sign for the next compare*/ + end /*x*/ /*dividing by unity normalizes X [↑] */ diff --git a/Task/Roots-of-a-function/REXX/roots-of-a-function.rexx b/Task/Roots-of-a-function/REXX/roots-of-a-function.rexx deleted file mode 100644 index 93f6e66b49..0000000000 --- a/Task/Roots-of-a-function/REXX/roots-of-a-function.rexx +++ /dev/null @@ -1,18 +0,0 @@ -/*REXX program finds the roots of a specific function: x^3 - 3*x^2 + 2*x via bisection*/ -parse arg bot top inc . /*obtain optional arguments from the CL*/ -if bot=='' | bot=="," then bot= -5 /*Not specified? Then use the default.*/ -if top=='' | top=="," then top= +5 /* " " " " " " */ -if inc=='' | inc=="," then inc= .0001 /* " " " " " " */ -z=f(bot-inc); !=sign(z) /*use these values for initial compare.*/ - - do j=bot to top by inc /*traipse through the specified range. */ - z=f(j); $=sign(z) /*compute new value; obtain the sign. */ - if z=0 then say 'found an exact root at' j/1 - else if !\==$ then if !\==0 then say 'passed a root at' j/1 - !=$ /*use the new sign for the next compare*/ - end /*j*/ /*dividing by unity normalizes J [↑] */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -f: parse arg x; return x*(x*(x-3)+2) /*formula used ──► x^3 - 3x^2 + 2x */ - /*with factoring ──► x{ x^2 -3x + 2 } */ - /*more " ──► x{ x( x-3 ) + 2 } */ diff --git a/Task/Roots-of-a-function/Sidef/roots-of-a-function.sidef b/Task/Roots-of-a-function/Sidef/roots-of-a-function.sidef index cec1000cca..b09120b15d 100644 --- a/Task/Roots-of-a-function/Sidef/roots-of-a-function.sidef +++ b/Task/Roots-of-a-function/Sidef/roots-of-a-function.sidef @@ -1,20 +1,20 @@ func f(x) { - x*x*x - 3*x*x + 2*x; + x*x*x - 3*x*x + 2*x } - -var step = 0.001; -var start = -1; -var stop = 3; - -range(start+step, stop, step).each { |x| - static sign = false; +  +var step = 0.001 +var start = -1 +var stop = 3 +  +for x in range(start+step, stop, step) { + static sign = false given (var value = f(x)) { when (0) { - say "Root found at #{x}"; + say "Root found at #{x}" } - case (sign && ((value > 0) != sign)) { - say "Root found near #{x}"; + case (sign && ((value > 0) != sign)) { + say "Root found near #{x}" } } - sign = value>0; + sign = value>0 } diff --git a/Task/Roots-of-a-function/Zkl/roots-of-a-function-1.zkl b/Task/Roots-of-a-function/Zkl/roots-of-a-function-1.zkl new file mode 100644 index 0000000000..84f97e45fd --- /dev/null +++ b/Task/Roots-of-a-function/Zkl/roots-of-a-function-1.zkl @@ -0,0 +1,3 @@ +fcn findRoots(f,start,stop,step,eps){ + [start..stop,step].filter('wrap(x){ f(x).closeTo(0.0,eps) }) +} diff --git a/Task/Roots-of-a-function/Zkl/roots-of-a-function-2.zkl b/Task/Roots-of-a-function/Zkl/roots-of-a-function-2.zkl new file mode 100644 index 0000000000..fda8f74212 --- /dev/null +++ b/Task/Roots-of-a-function/Zkl/roots-of-a-function-2.zkl @@ -0,0 +1,2 @@ +fcn f(x){ x*x*x - 3.0*x*x + 2.0*x } +findRoots(f, -1.0, 3.0, 0.0001, 0.00000001).println(); diff --git a/Task/Roots-of-a-function/Zkl/roots-of-a-function-3.zkl b/Task/Roots-of-a-function/Zkl/roots-of-a-function-3.zkl new file mode 100644 index 0000000000..84522f5903 --- /dev/null +++ b/Task/Roots-of-a-function/Zkl/roots-of-a-function-3.zkl @@ -0,0 +1,14 @@ +fcn secant(f,xA,xB){ + reg e=1.0e-12; + + fA:=f(xA); if(fA.closeTo(0.0,e)) return(xA); + + do(50){ + fB:=f(xB); + d:=(xB - xA) / (fB - fA) * fB; + if(d.closeTo(0,e)) break; + xA = xB; fA = fB; xB -= d; + } + if(f(xB).closeTo(0.0,e)) xB + else "Function is not converging near (%7.4f,%7.4f).".fmt(xA,xB); +} diff --git a/Task/Roots-of-a-function/Zkl/roots-of-a-function-4.zkl b/Task/Roots-of-a-function/Zkl/roots-of-a-function-4.zkl new file mode 100644 index 0000000000..bd89129465 --- /dev/null +++ b/Task/Roots-of-a-function/Zkl/roots-of-a-function-4.zkl @@ -0,0 +1,3 @@ +step:=0.1; +xs:=findRoots(f, -1.032, 3.0, step, 0.1); +xs.println(" --> ",xs.apply('wrap(x){ secant(f,x-step,x+step) })); diff --git a/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-5.c b/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-5.c deleted file mode 100644 index 904393f0cc..0000000000 --- a/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-5.c +++ /dev/null @@ -1,15 +0,0 @@ -int main() -{ - complex double x[2]; - - roots_quadratic_eq(1, -1e20, 1, x); - printf("x1 = (%.20le, %.20le)\nx2 = (%.20le, %.20le)\n\n", - creal(x[0]), cimag(x[0]), - creal(x[1]), cimag(x[1])); - roots_quadratic_eq2(1, -1e20, 1, x); - printf("x1 = (%.20le, %.20le)\nx2 = (%.20le, %.20le)\n\n", - creal(x[0]), cimag(x[0]), - creal(x[1]), cimag(x[1])); - - return 0; -} diff --git a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-3.clj b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-3.clj deleted file mode 100644 index 33cc424dbe..0000000000 --- a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-3.clj +++ /dev/null @@ -1,11 +0,0 @@ -; v1.1 if solutions: 0, nil; 1, float; 2, list -(defn quad_func_1_1 [a b c] - (def d - (- (* b b) - (* 4 a c)) ) - (if (< d 0) - nil - (if (> d 0) - (list (quad_func_sign a b d -1) - (quad_func_sign a b d +1)) - (quad_func_sign a b d +1)) )) diff --git a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-4.clj b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-4.clj deleted file mode 100644 index 27b95f21b6..0000000000 --- a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-4.clj +++ /dev/null @@ -1,11 +0,0 @@ -; v1.2 return a list -(defn quad_func [a b c] - (def d - (- (* b b) - (* 4 a c)) ) - (if (< d 0) - (list) - (if (> d 0) - (list (quad_func_sign a b d -1) - (quad_func_sign a b d +1)) - (list (quad_func_sign a b d +1)) )) ) diff --git a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-5.clj b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-5.clj deleted file mode 100644 index d2e6cc0eb3..0000000000 --- a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-5.clj +++ /dev/null @@ -1,6 +0,0 @@ -user=> (quad_func 1.0 1.0 1.0) -() -user=> (quad_func 1.0 2.0 1.0) -(1.0) -user=> (quad_func 1.0 3.0 1.0) -(0.3819660112501051 2.618033988749895) diff --git a/Task/Roots-of-a-quadratic-function/Haskell/roots-of-a-quadratic-function.hs b/Task/Roots-of-a-quadratic-function/Haskell/roots-of-a-quadratic-function.hs index e588ea32b2..1d2bc88726 100644 --- a/Task/Roots-of-a-quadratic-function/Haskell/roots-of-a-quadratic-function.hs +++ b/Task/Roots-of-a-quadratic-function/Haskell/roots-of-a-quadratic-function.hs @@ -1,10 +1,17 @@ -import Data.Complex +import Data.Complex (Complex, realPart) type CD = Complex Double quadraticRoots :: (CD, CD, CD) -> (CD, CD) quadraticRoots (a, b, c) = - if realPart b > 0 - then ((2*c) / (-b - d), (-b - d) / (2*a)) - else ((-b + d) / (2*a), (2*c) / (-b + d)) - where d = sqrt $ b^2 - 4*a*c + if realPart b > 0 + then ((2 * c) / (-b - d), (-b - d) / (2 * a)) + else ((-b + d) / (2 * a), (2 * c) / (-b + d)) + where + d = sqrt $ b ^ 2 - 4 * a * c + +main :: IO () +main = + mapM_ + (print . quadraticRoots) + [(3, 4, 4 / 3), (3, 2, -1), (3, 2, 1), (1, -10e5, 1), (1, -10e9, 1)] diff --git a/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-5.j b/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-5.j deleted file mode 100644 index d345aacb22..0000000000 --- a/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-5.j +++ /dev/null @@ -1,9 +0,0 @@ -q_r =: 3 : 0 -'a b c' =. y -q=. b %~ %: a * c -f=. 0.5 + 0.5*%:(1-4*q*q) -(-b*f%a),(-c%b*f) -) - -q_r 1 _1e6 1 -1e6 1e_6 diff --git a/Task/Roots-of-a-quadratic-function/jq/roots-of-a-quadratic-function-1.jq b/Task/Roots-of-a-quadratic-function/Jq/roots-of-a-quadratic-function-1.jq similarity index 100% rename from Task/Roots-of-a-quadratic-function/jq/roots-of-a-quadratic-function-1.jq rename to Task/Roots-of-a-quadratic-function/Jq/roots-of-a-quadratic-function-1.jq diff --git a/Task/Roots-of-a-quadratic-function/jq/roots-of-a-quadratic-function-2.jq b/Task/Roots-of-a-quadratic-function/Jq/roots-of-a-quadratic-function-2.jq similarity index 100% rename from Task/Roots-of-a-quadratic-function/jq/roots-of-a-quadratic-function-2.jq rename to Task/Roots-of-a-quadratic-function/Jq/roots-of-a-quadratic-function-2.jq diff --git a/Task/Roots-of-a-quadratic-function/jq/roots-of-a-quadratic-function-3.jq b/Task/Roots-of-a-quadratic-function/Jq/roots-of-a-quadratic-function-3.jq similarity index 100% rename from Task/Roots-of-a-quadratic-function/jq/roots-of-a-quadratic-function-3.jq rename to Task/Roots-of-a-quadratic-function/Jq/roots-of-a-quadratic-function-3.jq diff --git a/Task/Roots-of-a-quadratic-function/jq/roots-of-a-quadratic-function-4.jq b/Task/Roots-of-a-quadratic-function/Jq/roots-of-a-quadratic-function-4.jq similarity index 100% rename from Task/Roots-of-a-quadratic-function/jq/roots-of-a-quadratic-function-4.jq rename to Task/Roots-of-a-quadratic-function/Jq/roots-of-a-quadratic-function-4.jq diff --git a/Task/Roots-of-a-quadratic-function/PARI-GP/roots-of-a-quadratic-function-1.pari b/Task/Roots-of-a-quadratic-function/PARI-GP/roots-of-a-quadratic-function-1.pari new file mode 100644 index 0000000000..ff58154d0e --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/PARI-GP/roots-of-a-quadratic-function-1.pari @@ -0,0 +1 @@ +roots(a,b,c)=polrootsreal(Pol([a,b,c])) diff --git a/Task/Roots-of-a-quadratic-function/PARI-GP/roots-of-a-quadratic-function.pari b/Task/Roots-of-a-quadratic-function/PARI-GP/roots-of-a-quadratic-function-2.pari similarity index 100% rename from Task/Roots-of-a-quadratic-function/PARI-GP/roots-of-a-quadratic-function.pari rename to Task/Roots-of-a-quadratic-function/PARI-GP/roots-of-a-quadratic-function-2.pari diff --git a/Task/Roots-of-a-quadratic-function/PARI-GP/roots-of-a-quadratic-function-3.pari b/Task/Roots-of-a-quadratic-function/PARI-GP/roots-of-a-quadratic-function-3.pari new file mode 100644 index 0000000000..b1ef2b836a --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/PARI-GP/roots-of-a-quadratic-function-3.pari @@ -0,0 +1 @@ +roots(1,-1e9,1) diff --git a/Task/Roots-of-a-quadratic-function/Phix/roots-of-a-quadratic-function.phix b/Task/Roots-of-a-quadratic-function/Phix/roots-of-a-quadratic-function.phix new file mode 100644 index 0000000000..6b4ae87364 --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Phix/roots-of-a-quadratic-function.phix @@ -0,0 +1,29 @@ +procedure solve_quadratic(sequence t3) +atom {a,b,c} = t3 +atom 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 + +constant tests = {{1,-1E9,1}, + {1,0,1}, + {2,-1,-6}, + {1,2,-2}, + {0.5,1.4142135,1}, + {1,3,2}, + {3,4,5}} + +for i=1 to length(tests) do + solve_quadratic(tests[i]) +end for diff --git a/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-1.rexx b/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-1.rexx index 466feb3c66..0f24183ebd 100644 --- a/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-1.rexx +++ b/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-1.rexx @@ -15,14 +15,14 @@ exit /*stick a fork in it, we're all done. */ /*────────────────────────────────────────────────────────────────────────────*/ quadratic: parse arg aa,bb,cc /*obtain the specified three arguments.*/ $=sqrt(bb**2-4*aa*cc); L=length($) /*compute SQRT (which may be complex).*/ - rp=1/(aa+aa); c?=right($,1)=='i' /*compute reciprocal of 2*aa; Complex?*/ - if c? then do; n=left($,L-1); r1=-bb*rp; r2=r1; r1j=n*rp; r2j=-r1j; end - else do; r1=(-bb+$)*rp; r2=(-bb-$)*rp; r1j=0; r2j=0; end + r=1/(aa+aa); ?=right($,1)=='i' /*compute reciprocal of 2*aa; Complex?*/ + if ? then do; r1= -bb *r; r2=r1; r1j=left($,L-1)*r; r2j=-r1j; end + else do; r1=(-bb+$)*r; r2=(-bb-$)*r; r1j=0; r2j= 0; end return /*────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 - numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ - numeric digits d; return (g/1)i /*make complex if X < 0.*/ +sqrt: procedure; parse arg x 1 ox; if x=0 then return 0; d=digits(); m.=9 + numeric digits 9; numeric form; h=d+6; x=abs(x) + 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)left('i',ox<0) /*make complex if OX<0.*/ diff --git a/Task/Roots-of-a-quadratic-function/Sidef/roots-of-a-quadratic-function.sidef b/Task/Roots-of-a-quadratic-function/Sidef/roots-of-a-quadratic-function.sidef index 560f83c8ba..d68d80e80f 100644 --- a/Task/Roots-of-a-quadratic-function/Sidef/roots-of-a-quadratic-function.sidef +++ b/Task/Roots-of-a-quadratic-function/Sidef/roots-of-a-quadratic-function.sidef @@ -4,7 +4,7 @@ var sets = [ [1, -2, 1], [1, 0, -4], [1, -1e6, 1], - ]; + ] func quadroots(a, b, c) { var root = sqrt(b**2 - 4*a*c) @@ -15,5 +15,5 @@ func quadroots(a, b, c) { sets.each { |coefficients| say ("Roots for #{coefficients}", - "=> (#{quadroots(coefficients...).join(', ')})"); + "=> (#{quadroots(coefficients...).join(', ')})") } diff --git a/Task/Roots-of-a-quadratic-function/Stata/roots-of-a-quadratic-function.stata b/Task/Roots-of-a-quadratic-function/Stata/roots-of-a-quadratic-function.stata new file mode 100644 index 0000000000..5e99adc51f --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Stata/roots-of-a-quadratic-function.stata @@ -0,0 +1,12 @@ +mata +: polyroots((-2,0,1)) + 1 2 + +-----------------------------+ + 1 | 1.41421356 -1.41421356 | + +-----------------------------+ + +: polyroots((2,0,1)) + 1 2 + +-------------------------------+ + 1 | -1.41421356i 1.41421356i | + +-------------------------------+ diff --git a/Task/Roots-of-a-quadratic-function/Zkl/roots-of-a-quadratic-function-1.zkl b/Task/Roots-of-a-quadratic-function/Zkl/roots-of-a-quadratic-function-1.zkl new file mode 100644 index 0000000000..cff6f53a8e --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Zkl/roots-of-a-quadratic-function-1.zkl @@ -0,0 +1,13 @@ +fcn quadratic(a,b,c){ b=b.toFloat(); + println("Roots of a quadratic function %s, %s, %s".fmt(a,b,c)); + d,a2:=(b*b - 4*a*c), a+a; + if(d>0){ + sd:=d.sqrt(); + println(" the real roots are %s and %s".fmt((-b + sd)/a2,(-b - sd)/a2)); + } + else if(d==0) println(" the single root is ",-b/a2); + else{ + sd:=(-d).sqrt(); + println(" the complex roots are %s and \U00B1;%si".fmt(-b/a2,sd/a2)); + } +} diff --git a/Task/Roots-of-a-quadratic-function/Zkl/roots-of-a-quadratic-function-2.zkl b/Task/Roots-of-a-quadratic-function/Zkl/roots-of-a-quadratic-function-2.zkl new file mode 100644 index 0000000000..c91f582410 --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Zkl/roots-of-a-quadratic-function-2.zkl @@ -0,0 +1,3 @@ +foreach a,b,c in (T( T(1,-2,1), T(1,-3,2), T(1,0,1), T(1,-1.0e10,1), T(1,2,3), T(2,-1,-6)) ){ + quadratic(a,b,c) +} diff --git a/Task/Roots-of-unity/Forth/roots-of-unity.fth b/Task/Roots-of-unity/Forth/roots-of-unity-1.fth similarity index 100% rename from Task/Roots-of-unity/Forth/roots-of-unity.fth rename to Task/Roots-of-unity/Forth/roots-of-unity-1.fth diff --git a/Task/Roots-of-unity/Forth/roots-of-unity-2.fth b/Task/Roots-of-unity/Forth/roots-of-unity-2.fth new file mode 100644 index 0000000000..c8725ed67f --- /dev/null +++ b/Task/Roots-of-unity/Forth/roots-of-unity-2.fth @@ -0,0 +1,18 @@ +require fsl-util.fs +require fsl/complex.fs + +: abs= 1E-12 F~ ; +: clamp-to-0 FDUP 0E0 abs= IF FDROP 0E0 THEN ; +: zclamp-to-0 + clamp-to-0 FSWAP + clamp-to-0 FSWAP ; +: .roots + 1+ 2 DO + I . ." : " + I 0 DO + 1E0 2E0 PI F* I S>F F* J S>F F/ polar> zclamp-to-0 z. SPACE + LOOP + CR + LOOP ; +3 SET-PRECISION +5 .roots diff --git a/Task/Roots-of-unity/Haskell/roots-of-unity-1.hs b/Task/Roots-of-unity/Haskell/roots-of-unity-1.hs index 2cf1710151..443258f2b6 100644 --- a/Task/Roots-of-unity/Haskell/roots-of-unity-1.hs +++ b/Task/Roots-of-unity/Haskell/roots-of-unity-1.hs @@ -1,3 +1,9 @@ -import Data.Complex +import Data.Complex (Complex, cis) -rootsOfUnity n = [cis (2*pi*k/n) | k <- [0..n-1]] +rootsOfUnity :: (Enum a, Floating a) => a -> [Complex a] +rootsOfUnity n = + [ cis (2 * pi * k / n) + | k <- [0 .. n - 1] ] + +main :: IO () +main = mapM_ print $ rootsOfUnity 3 diff --git a/Task/Roots-of-unity/Haskell/roots-of-unity-2.hs b/Task/Roots-of-unity/Haskell/roots-of-unity-2.hs index 5fbd9291e6..31dd60ea6e 100644 --- a/Task/Roots-of-unity/Haskell/roots-of-unity-2.hs +++ b/Task/Roots-of-unity/Haskell/roots-of-unity-2.hs @@ -1,4 +1,3 @@ -*Main> rootsOfUnity 3 -[1.0 :+ 0.0, - (-0.4999999999999998) :+ 0.8660254037844387, - (-0.5000000000000004) :+ (-0.8660254037844384)] +1.0 :+ 0.0 +(-0.4999999999999998) :+ 0.8660254037844388 +(-0.5000000000000004) :+ (-0.8660254037844384) diff --git a/Task/Roots-of-unity/jq/roots-of-unity-1.jq b/Task/Roots-of-unity/Jq/roots-of-unity-1.jq similarity index 100% rename from Task/Roots-of-unity/jq/roots-of-unity-1.jq rename to Task/Roots-of-unity/Jq/roots-of-unity-1.jq diff --git a/Task/Roots-of-unity/jq/roots-of-unity-2.jq b/Task/Roots-of-unity/Jq/roots-of-unity-2.jq similarity index 100% rename from Task/Roots-of-unity/jq/roots-of-unity-2.jq rename to Task/Roots-of-unity/Jq/roots-of-unity-2.jq diff --git a/Task/Roots-of-unity/Phix/roots-of-unity.phix b/Task/Roots-of-unity/Phix/roots-of-unity.phix new file mode 100644 index 0000000000..33f51be74c --- /dev/null +++ b/Task/Roots-of-unity/Phix/roots-of-unity.phix @@ -0,0 +1,9 @@ +for n=2 to 10 do + printf(1,"%2d:",n) + for root=0 to n-1 do + atom real = cos(2*PI*root/n) + atom imag = sin(2*PI*root/n) + printf(1,"%s %6.3f %6.3fi",{iff(root?",":""),real,imag}) + end for + printf(1,"\n") +end for diff --git a/Task/Roots-of-unity/REXX/roots-of-unity.rexx b/Task/Roots-of-unity/REXX/roots-of-unity.rexx index 23cf913f35..49ab0e9d61 100644 --- a/Task/Roots-of-unity/REXX/roots-of-unity.rexx +++ b/Task/Roots-of-unity/REXX/roots-of-unity.rexx @@ -4,37 +4,35 @@ if n=='' | n=="," then n=1 /*Not specified? Then use the if frac='' | frac=="," then frac=5 /* " " " " " " */ start=abs(n) /*assume only one K is wanted. */ if n<0 then start=1 /*Negative? Then use a range of K's. */ -numeric digits length(pi()) - 1 /*use number of decimal digits in pi. */ -pi2=pi*2 /*obtain the value of pi doubled. */ +numeric digits length( pi() ) - 1 /*use number of decimal digits in pi. */ +pi2= pi+pi /*obtain the value of pi doubled. */ /*display unity roots for a range, or */ - do k=start to abs(n) /* just for one K. */ - say right(k 'roots of unity', 40, "─") /*display a pretty separator with title*/ - do angle=0 by pi2/k for k /*compute the angle for each root. */ - rp=adjust(cos(angle)) /*compute real part via COS function.*/ - if left(rp,1)\=='-' then rp=" "rp /*not negative? Then pad with a blank.*/ - ip=adjust(sin(angle)) /*compute imaginary part via SIN funct.*/ - if left(ip,1)\=='-' then ip="+"ip /*Not negative? Then pad with + char.*/ - if ip=0 then say rp /*Only real part? Ignore imaginary part*/ - else say left(rp,frac+4)ip'i' /*display the real and imaginary part. */ - end /*angle*/ - end /*k*/ + do #=start to abs(n) /* just for one K. */ + say right(# 'roots of unity', 40, "─") ' (showing' frac "fractional decimal digits)" + do angle=0 by pi2/# for # /*compute the angle for each root. */ + rp=adjust( cos( angle ) ) /*compute real part via COS function.*/ + if left(rp, 1) \== '-' then rp=" "rp /*not negative? Then pad with a blank.*/ + ip=adjust(sin(angle)) /*compute imaginary part via SIN funct.*/ + if left(ip, 1) \== '-' then ip="+"ip /*Not negative? Then pad with + char.*/ + if ip=0 then say rp /*Only real part? Ignore imaginary part*/ + else say left(rp, frac+4)ip'i' /*display the real and imaginary part. */ + end /*angle*/ + end /*#*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -adjust: parse arg x; near0='1e-' || (digits()-digits()%10) /*compute a tiny number.*/ - if abs(x)=={{header| on each task page. - -Output: - -
    100 doors: 20 examples.
    -99 Bottles of Beer: 29 examples.
    -Abstract type: 10 examples.
    -
    -Total: X examples.
    - -You'll need to use the Media Wiki API, which you can find out about locally, [http://rosettacode.org/mw/api.php here], or in Media Wiki's API documentation at, [http://www.mediawiki.org/wiki/API_Query API:Query] diff --git a/Task/Rosetta-Code-Count-examples/00META.yaml b/Task/Rosetta-Code-Count-examples/00META.yaml deleted file mode 100644 index b392469fa2..0000000000 --- a/Task/Rosetta-Code-Count-examples/00META.yaml +++ /dev/null @@ -1,2 +0,0 @@ ---- -note: Rosetta Code related diff --git a/Task/Rosetta-Code-Count-examples/Ada/rosetta-code-count-examples.ada b/Task/Rosetta-Code-Count-examples/Ada/rosetta-code-count-examples.ada deleted file mode 100644 index 29d0419cb0..0000000000 --- a/Task/Rosetta-Code-Count-examples/Ada/rosetta-code-count-examples.ada +++ /dev/null @@ -1,101 +0,0 @@ -with Aws.Client, Aws.Messages, Aws.Response, Aws.Resources, Aws.Url; -with Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs; -with Input_Sources.Strings, Unicode, Unicode.Ces.Utf8; -with Ada.Strings.Unbounded, Ada.Strings.Fixed, Ada.Text_IO, Ada.Command_Line; -with Ada.Containers.Vectors; - -use Aws.Client, Aws.Messages, Aws.Response, Aws.Resources, Aws.Url; -use Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs; -use Aws, Ada.Strings.Unbounded, Ada.Strings.Fixed, Input_Sources.Strings; -use Ada.Text_IO, Ada.Command_Line; - -procedure Count_Examples is - - package Members_Vectors is new Ada.Containers.Vectors ( - Index_Type => Positive, - Element_Type => Unbounded_String); - use Members_Vectors; - - Exemples : Vector; - Nbr_Lg, Total : Natural := 0; - - procedure Get_Vector (Category : in String; Mbr_Vector : in out Vector) is - Reader : Tree_Reader; - Doc : Document; - List : Node_List; - N : Node; - A : Attr; - Page : Aws.Response.Data; - Uri_Xml : constant String := - "http://rosettacode.org/mw/api.php?action=query&list=categorymembers" - & - "&format=xml&cmlimit=500&cmtitle=Category:"; - begin - Page := Client.Get (Uri_Xml & Category); - if Response.Status_Code (Page) not in Messages.Success then - raise Client.Connection_Error; - end if; - declare - Xml : constant String := Message_Body (Page); - Source : String_Input; - begin - Open - (Xml'Unrestricted_Access, - Unicode.Ces.Utf8.Utf8_Encoding, - Source); - Parse (Reader, Source); - Close (Source); - end; - Doc := Get_Tree (Reader); - List := Get_Elements_By_Tag_Name (Doc, "cm"); - for Index in 1 .. Length (List) loop - N := Item (List, Index - 1); - A := Get_Named_Item (Attributes (N), "title"); - Append (Mbr_Vector, To_Unbounded_String (Value (A))); - end loop; - Free (List); - Free (Reader); - end Get_Vector; - - function Scan_Page (Title : String) return Natural is - Page : Aws.Response.Data; - File : Aws.Resources.File_Type; - Buffer : String (1 .. 1024); - Languages, Position, Last : Natural := 0; - begin - Page := - Client.Get - ("http://rosettacode.org/mw/index.php?title=" & - Aws.Url.Encode (Title) & - "&action=raw"); - Response.Message_Body (Page, File); - while not End_Of_File (File) loop - Resources.Get_Line (File, Buffer, Last); - Position := - Index - (Source => Buffer (Buffer'First .. Last), - Pattern => "=={{header|"); - if Position > 0 then - Languages := Languages + 1; - end if; - end loop; - Close (File); - return Languages; - end Scan_Page; - -begin - Get_Vector ("Programming_Tasks", Exemples); - - for I in First_Index (Exemples) .. Last_Index (Exemples) loop - declare - Title : constant String := - To_String (Members_Vectors.Element (Exemples, I)); - begin - Nbr_Lg := Scan_Page (Title); - Total := Total + Nbr_Lg; - Put_Line (Title & " :" & Integer'Image (Nbr_Lg) & " exemples."); - end; - end loop; - - Put_Line ("Total :" & Integer'Image (Total) & " exemples."); -end Count_Examples; diff --git a/Task/Rosetta-Code-Count-examples/AutoHotkey/rosetta-code-count-examples.ahk b/Task/Rosetta-Code-Count-examples/AutoHotkey/rosetta-code-count-examples.ahk deleted file mode 100644 index 2abaeb18cc..0000000000 --- a/Task/Rosetta-Code-Count-examples/AutoHotkey/rosetta-code-count-examples.ahk +++ /dev/null @@ -1,20 +0,0 @@ -UrlDownloadToFile - , http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml - , tasks.xml -FileRead, tasks, tasks.xml -pos = 0 -quote = " ; " -regtitle := "", i%) - title$ = MID$(a$, i%+7, j%-i%-10) - REM Replace HTML codes: - REPEAT - k% = INSTR(title$, "&") - IF k% THEN - l% = INSTR(title$, ";", k%) - title$ = LEFT$(title$,k%-1) + \ - \ FNhtml(MID$(title$,k%,l%-k%+1)) + MID$(title$,l%+1) - ENDIF - UNTIL k% = 0 - t$ = title$ - REM Substitute characters not allowed in a URL: - FOR s% = 1 TO LEN(special$) - REPEAT - s$ = MID$(special$, s%, 1) - k% = INSTR(t$, s$) - IF k% t$ = LEFT$(t$,k%-1) + "%" + STR$~ASCs$ + MID$(t$,k%+1) - UNTIL k% = 0 - NEXT - url$ = "http://www.rosettacode.org/w/index.php?title=" + t$ + \ - \ "&action=raw" - file$ = @tmp$ + "title.htm" - SYS UDTF, 0, url$, file$, 0, 0 TO fail% - IF fail% ERROR 100, "File download failed " + t$ - examples% = 0 - task% = OPENIN(file$) - WHILE NOT EOF#task% - IF INSTR(GET$#task%, "=={{header|") examples% += 1 - ENDWHILE - CLOSE #task% - Total% += examples% - PRINT title$ ": " ; examples% " examples." - ENDIF - UNTIL i% = 0 - i% = INSTR(a$, "cmcontinue=") - IF i% THEN - CLOSE #file% - j% = INSTR(a$, """", i%+1) - k% = INSTR(a$, """", j%+1) - url$ = "http://www.rosettacode.org/w/api.php?action=query" + \ - \ "&list=categorymembers&cmtitle=Category:Programming_Tasks" + \ - \ "&cmlimit=500&format=xml&cmcontinue=" + MID$(a$,j%+1,k%-j%) - REPEAT - i% = INSTR(url$, "|") - IF i% url$ = LEFT$(url$,i%-1) + "%7C" + MID$(url$,i%+1) - UNTIL i% = 0 - file$ = @tmp$ + "tasks.xml" - SYS UDTF, 0, url$, file$, 0, 0 TO fail% - IF fail% ERROR 100, "File download failed (continue)" - file% = OPENIN(file$) - ENDIF - ENDWHILE - CLOSE #file% - PRINT ' "Total: " ; Total% " examples." - END - - DEF FNhtml(h$) - IF LEFT$(h$,2) = "&#" THEN = CHR$(VALMID$(h$,3)) - CASE h$ OF - WHEN """: = """" - ENDCASE - = h$ diff --git a/Task/Rosetta-Code-Count-examples/Bracmat/rosetta-code-count-examples.bracmat b/Task/Rosetta-Code-Count-examples/Bracmat/rosetta-code-count-examples.bracmat deleted file mode 100644 index d54edcfc06..0000000000 --- a/Task/Rosetta-Code-Count-examples/Bracmat/rosetta-code-count-examples.bracmat +++ /dev/null @@ -1,41 +0,0 @@ -( ( get-page - = - . sys$(str$("wget -q -O wget.out \"" !arg \")) - & get$("wget.out",HT ML) - ) -& get-page$"http://rosettacode.org/wiki/Category:Programming_Tasks" - : ? (table.?) ?tasklist (.table.) ? -& 0:?list -& whl - ' ( !tasklist - : ? - ( a - . (href.@(?:"/wiki/" ?href)) (title.?title) - & get-page$(str$("http://rosettacode.org/wiki/" !href)) - : ?task - & 0:?cnt - & whl - ' ( !task - : ? - ( (span.(class.mw-headline) (id.?)) - ?span - (.span.) - ?task - & !span - : ? - ( a - . (href.@(?:"/wiki/Category:" ?)) - (title.@(?:"Category:" ?)) - ) - @ - (.a.) - ? - ) - & 1+!cnt:?cnt - ) - & (!cnt.!title)+!list:?list - ) - ?tasklist - ) -& lst$(list,taskfreq,NEW) -) diff --git a/Task/Rosetta-Code-Count-examples/Clojure/rosetta-code-count-examples-1.clj b/Task/Rosetta-Code-Count-examples/Clojure/rosetta-code-count-examples-1.clj deleted file mode 100644 index 2a02a00924..0000000000 --- a/Task/Rosetta-Code-Count-examples/Clojure/rosetta-code-count-examples-1.clj +++ /dev/null @@ -1,39 +0,0 @@ -(ns count-examples - (:import [java.net URLEncoder]) - (:use [clojure.contrib.http.agent :only (http-agent string)] - [clojure.contrib.json :only (read-json)] - [clojure.contrib.string :only (join)])) - -(defn url-encode [v] (URLEncoder/encode (str v) "utf-8")) - -(defn rosettacode-get [path params] - (let [param-string (join "&" (for [[n v] params] (str (name n) "=" (url-encode v))))] - (string (http-agent (format "http://www.rosettacode.org/w/%s?%s" path param-string))))) - -(defn rosettacode-query [params] - (read-json (rosettacode-get "api.php" (merge {:action "query" :format "json"} params)))) - -(defn list-cm - ([params] (list-cm params nil)) - ([params continue] - (let [cm-params (merge {:list "categorymembers"} params (or continue {})) - result (rosettacode-query cm-params)] - (concat (-> result (:query) (:categorymembers)) - (if-let [cmcontinue (-> result (:query-continue) (:categorymembers))] - (list-cm params cmcontinue)))))) - -(defn programming-tasks [] - (let [result (list-cm {:cmtitle "Category:Programming_Tasks" :cmlimit 50})] - (map #(:title %) result))) - -(defn task-count [task] - [task (count - (re-seq #"==\{\{header" - (rosettacode-get "index.php" {:action "raw" :title task})))]) - -(defn print-result [] - (let [task-counts (map task-count (programming-tasks))] - (doseq [[task count] task-counts] - (println (str task ":") count) - (flush)) - (println "Total: " (reduce #(+ %1 (second %2)) 0 task-counts)))) diff --git a/Task/Rosetta-Code-Count-examples/Clojure/rosetta-code-count-examples-2.clj b/Task/Rosetta-Code-Count-examples/Clojure/rosetta-code-count-examples-2.clj deleted file mode 100644 index f2a356dbb4..0000000000 --- a/Task/Rosetta-Code-Count-examples/Clojure/rosetta-code-count-examples-2.clj +++ /dev/null @@ -1,16 +0,0 @@ -count-examples> (print-result) -100 doors: 73 -24 game: 18 -24 game/Solve: 14 -99 Bottles of Beer: 89 -Abstract type: 27 -Accumulator factory: 23 -Ackermann function: 73 -Active Directory/Connect: 4 -Active Directory/Search for a user: 3 -Active object: 14 -Add a variable to a class instance at runtime: 21 -Address of a variable: 20 -... -Total: 11216 -nil diff --git a/Task/Rosetta-Code-Count-examples/D/rosetta-code-count-examples.d b/Task/Rosetta-Code-Count-examples/D/rosetta-code-count-examples.d deleted file mode 100644 index a74727fb97..0000000000 --- a/Task/Rosetta-Code-Count-examples/D/rosetta-code-count-examples.d +++ /dev/null @@ -1,48 +0,0 @@ -import tango.io.Stdout; -import tango.net.http.HttpClient; -import tango.net.http.HttpHeaders; -import tango.text.xml.Document; -import tango.text.Util; - -alias HttpHeader.ContentLength CL; - -auto url = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"; -void main() -{ - auto client = new HttpClient (HttpClient.Get, url); - client.open(); - char[] mainData, tmp; - int total, i; - - void cat(void[] content) { tmp ~= cast(char[]) content; } - - if (client.isResponseOK) { - client.read(&cat, client.getResponseHeaders.getInt(CL)); - mainData = tmp; - tmp = null; - - auto doc = new Document!(char); - doc.parse(mainData); - foreach (n; doc.query.descendant("cm").attribute("title")) { - auto subClient = new HttpClient(HttpClient.Get, - "http://www.rosettacode.org/w/index.php?title=" ~ - replace(n.value.dup, ' ', '_') ~ "&action=raw"); - subClient.open(); - if (! subClient.isResponseOK) { - Stderr (client.getResponse); - break; - } - subClient.read(&cat, subClient.getResponseHeaders.getInt(CL)); - foreach (segment; patterns(cast(char[])tmp, "=={{header|")) i++; - --i; - if (i) --i; - Stdout.formatln ("{0,-40} - {}", n.value, i); - total += i; - tmp = null; - i = 0; - } - Stdout("total examples: ", total).newline; - } else { - Stderr (client.getResponse); - } -} diff --git a/Task/Rosetta-Code-Count-examples/EGL/rosetta-code-count-examples-1.egl b/Task/Rosetta-Code-Count-examples/EGL/rosetta-code-count-examples-1.egl deleted file mode 100644 index b9e86896d8..0000000000 --- a/Task/Rosetta-Code-Count-examples/EGL/rosetta-code-count-examples-1.egl +++ /dev/null @@ -1,76 +0,0 @@ -package com.eglexamples.client; - -import org.eclipse.edt.rui.widgets.*; - -handler RosettaCodeHandler type RUIhandler{initialUI =[ui], title = "Rosetta Code Tasks and Counts"} - - ui GridLayout{columns = 3, rows = 4, cellPadding = 4, children = [ b1, dg1, l1, l2, l3, l4 ]}; - - b1 Button{ layoutData = new GridLayoutData{ row = 1, column = 1 }, text = "Go!", onClick ::= b1_onClick }; - l1 TextLabel{ layoutData = new GridLayoutData{ row = 1, column = 2 }, text = "Total Tasks:" }; - l2 TextLabel{ layoutData = new GridLayoutData{ row = 1, column = 3 }, text = "0" }; - - l3 TextLabel{ layoutData = new GridLayoutData{ row = 2, column = 2 }, text = "Total Implementations:" }; - l4 TextLabel{ layoutData = new GridLayoutData{ row = 2, column = 3 }, text = "0" }; - - dg1 DataGrid{ layoutData = new GridLayoutData{ row = 3, column = 1, horizontalSpan = 3 }, - pageSize = 10, showScrollbar = true, - columns = [ new DataGridColumn{name = "title", displayName = "Task", width=220}, - new DataGridColumn{name = "count", displayName = "Count", width=100} ] }; - - cmcontinue string?; - title string?; - allTasks Task[]; - - restBindingTasks IHttp? = new HttpRest{ - restType = eglx.rest.ServiceType.TrueRest, - request.uri = "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=1&format=json"}; - - restBindingPageDetail IHttp? = new HttpRest{ - restType = eglx.rest.ServiceType.TrueRest, - request.uri = "http://rosettacode.org/mw/index.php"}; - - function b1_onClick(event Event in) - call ProxyFunctions.listTasks("") using restBindingTasks - returning to listTasksCallBack onException exceptionHandler; - end - - function listTasksCallBack(retResult RosettaCodeJSON in) - title = retResult.query.categorymembers[1].title; - cmcontinue = retResult.queryContinue.categorymembers.cmcontinue; - - call ProxyFunctions.fetchPageDetail(title) using restBindingPageDetail - returning to pageDetailCallBack onException exceptionHandler; - end - - function pageDetailCallBack(pageResults string in) - count int = countSubstring("=={{header", pageResults); - allTasks.appendElement(new Task { title = title, count = count }); - l2.text = l2.text as int + 1; - l4.text = l4.text as int + count; - - if(cmcontinue != null) - call ProxyFunctions.listTasks(cmcontinue) using restBindingTasks - returning to listTasksCallBack onException exceptionHandler; - else - dg1.data = allTasks as any[]; - end - end - - function countSubstring(substr string in, str string in) returns(int) - if(str.length() > 0 and substr.length() > 0) - return (str.length() - str.replaceStr(subStr, "").length()) / subStr.length(); - else - return 0; - end - end - - function exceptionHandler(exp AnyException in) - end - -end - -record Task - title string; - count int; -end diff --git a/Task/Rosetta-Code-Count-examples/EGL/rosetta-code-count-examples-2.egl b/Task/Rosetta-Code-Count-examples/EGL/rosetta-code-count-examples-2.egl deleted file mode 100644 index c672f8ca00..0000000000 --- a/Task/Rosetta-Code-Count-examples/EGL/rosetta-code-count-examples-2.egl +++ /dev/null @@ -1,37 +0,0 @@ -package com.eglexamples.client; - -library ProxyFunctions - - function listTasks(continueLocation String in) returns (RosettaCodeJSON) { - @Rest{method = _GET, uriTemplate = "&cmcontinue={continueLocation}", - requestFormat = None, responseFormat = JSON} - } - end - - function fetchPageDetail(title String in) returns (String) { - @Rest{method = _GET, uriTemplate = "?title={title}&action=raw", - requestFormat = None, responseFormat = None} - } - end - -end - -record RosettaCodeJSON - query Query; - queryContinue QueryContinue{JSONName = "query-continue"}; -end - -record Query - categorymembers Categorymembers[]; -end - -record Categorymembers - cmcontinue string?; - pageid int?; - ns int?; - title string?; -end - -record QueryContinue - categorymembers Categorymembers; -end diff --git a/Task/Rosetta-Code-Count-examples/Erlang/rosetta-code-count-examples.erl b/Task/Rosetta-Code-Count-examples/Erlang/rosetta-code-count-examples.erl deleted file mode 100644 index 3708959104..0000000000 --- a/Task/Rosetta-Code-Count-examples/Erlang/rosetta-code-count-examples.erl +++ /dev/null @@ -1,62 +0,0 @@ --module(rosseta_examples). --include_lib("xmerl/include/xmerl.hrl"). - --export([main/0]). - -main() -> - application:start(inets), - Titles = read_titles(empty), - Result = lists:foldl(fun(Title,Acc) -> Acc + calculate_one(Title) end, 0, Titles), - io:format("Total: ~p examples.\n",[Result]), - application:stop(inets). - -read_titles(CurrentContinue) -> - URL0 = "http://rosettacode.org/mw/api.php?" ++ - "action=query&list=categorymembers&cmtitle=Category:Programming_Tasks" ++ - "&cmlimit=500&format=xml", - URL = - case CurrentContinue of - empty -> URL0; - _ -> URL0 ++ "&cmcontinue=" ++ CurrentContinue - end, - {ok,Answer} = httpc:request(URL), - {Document,_} = xmerl_scan:string(lists:last(tuple_to_list(Answer))), - Continue = - [Value || #xmlAttribute{value = Value} <- xmerl_xpath:string("//@cmcontinue", Document)], - Titles = - [Value || #xmlAttribute{value = Value} <- xmerl_xpath:string("//@title", Document)], - case Continue of - []-> - Titles; - [ContValue | _] -> - Titles ++ read_titles(ContValue) - end. - -calculate_one(Title0) -> - Title = replace_chars(Title0), - URL = "http://www.rosettacode.org/w/index.php?title=" ++ - Title ++ "&action=raw", - case httpc:request(URL) of - {ok,Result} -> - {match,Found} = - re:run(lists:last(tuple_to_list(Result)), "\n=={{header(|)", [global]), - io:format("~ts: ~p examples.\n",[Title0,length(Found)]), - length(Found); - {error,socket_closed_remotely} -> - io:format("Socket closed remotely. Retry.\n"), - calculate_one(Title0) - end. - -replace_chars(String) -> - replace_chars(String,[]). - -replace_chars([$ | T],Acc) -> - replace_chars(T, [$_| Acc]); -replace_chars([$+| T],Acc) -> - replace_chars(T, lists:reverse("%2B") ++ Acc); -replace_chars([8211| T],Acc) -> - replace_chars(T, lists:reverse("%E2%80%93") ++ Acc); -replace_chars([Other| T],Acc) -> - replace_chars(T, [Other| Acc]); -replace_chars([],Acc) -> - lists:reverse(Acc). diff --git a/Task/Rosetta-Code-Count-examples/Factor/rosetta-code-count-examples.factor b/Task/Rosetta-Code-Count-examples/Factor/rosetta-code-count-examples.factor deleted file mode 100644 index 1d8f4190e2..0000000000 --- a/Task/Rosetta-Code-Count-examples/Factor/rosetta-code-count-examples.factor +++ /dev/null @@ -1,42 +0,0 @@ -USING: arrays assocs concurrency.combinators -concurrency.semaphores formatting hashtables http.client io -json.reader kernel math math.parser sequences splitting -urls.encoding ; -IN: rosetta-code.count-examples - -CONSTANT: list-url "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&cmprop=title&format=json" - -: titles ( query -- titles ) - "query" of "categorymembers" of [ "title" of ] map ; -: continued-url ( query -- url/f ) - "query-continue" of "categorymembers" of - [ assoc>query list-url swap "&" glue ] [ f ] if* ; - -: (all-programming-titles) ( titles url -- titles' url' ) - http-get nip json> [ titles append ] [ continued-url ] bi - [ (all-programming-titles) ] [ f ] if* ; -: all-programming-titles ( -- titles ) { } list-url (all-programming-titles) drop ; - -CONSTANT: content-base-url "http://rosettacode.org/mw/index.php?title=&action=raw" -: content-url ( title -- url ) - " " "_" replace - "title" associate assoc>query - content-base-url swap "&" glue ; - -: occurences ( seq subseq -- n ) split-subseq length 1 - ; -: count-examples ( title -- n ) - content-url http-get nip "=={{header|" occurences ; - -: print-task ( title n -- ) "%s: %d examples.\n" printf ; -: print-total ( assoc -- ) values sum "Total: %d examples.\n" printf ; -: fetch-counts ( titles -- assoc ) - 10 [ - [ dup count-examples 2array ] with-semaphore - ] curry parallel-map ; - -: print-counts ( titles -- ) - [ [ print-task ] assoc-each nl ] [ print-total ] bi ; -: rosetta-examples ( -- ) - all-programming-titles fetch-counts print-counts ; - -MAIN: rosetta-examples diff --git a/Task/Rosetta-Code-Count-examples/Go/rosetta-code-count-examples.go b/Task/Rosetta-Code-Count-examples/Go/rosetta-code-count-examples.go deleted file mode 100644 index a7cceb6e2c..0000000000 --- a/Task/Rosetta-Code-Count-examples/Go/rosetta-code-count-examples.go +++ /dev/null @@ -1,75 +0,0 @@ -package main - -import ( - "bytes" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "strings" -) - -func req(u string, foundCm func(string)) string { - resp, err := http.Get(u) - if err != nil { - fmt.Println(err) // connection or request fail - return "" - } - defer resp.Body.Close() - for p := xml.NewDecoder(resp.Body); ; { - t, err := p.RawToken() - switch s, ok := t.(xml.StartElement); { - case err == io.EOF: - return "" - case err != nil: - fmt.Println(err) - return "" - case !ok: - continue - case s.Name.Local == "cm": - for _, a := range s.Attr { - if a.Name.Local == "title" { - foundCm(a.Value) - } - } - case s.Name.Local == "categorymembers" && len(s.Attr) > 0 && - s.Attr[0].Name.Local == "cmcontinue": - return url.QueryEscape(s.Attr[0].Value) - } - } - return "" -} - -func main() { - taskQuery := "http://rosettacode.org/mw/api.php?action=query" + - "&format=xml&list=categorymembers&cmlimit=500" + - "&cmtitle=Category:Programming_Tasks" - continueAt := req(taskQuery, count) - for continueAt > "" { - continueAt = req(taskQuery+"&cmcontinue="+continueAt, count) - } - fmt.Printf("Total: %d examples.\n", total) -} - -var marker = []byte("=={{header|") -var total int - -func count(cm string) { - taskFmt := "http://rosettacode.org/mw/index.php?title=%s&action=raw" - taskEsc := url.QueryEscape(strings.Replace(cm, " ", "_", -1)) - resp, err := http.Get(fmt.Sprintf(taskFmt, taskEsc)) - var page []byte - if err == nil { - page, err = ioutil.ReadAll(resp.Body) - resp.Body.Close() - } - if err != nil { - fmt.Println(err) - return - } - examples := bytes.Count(page, marker) - fmt.Printf("%s: %d\n", cm, examples) - total += examples -} diff --git a/Task/Rosetta-Code-Count-examples/Haskell/rosetta-code-count-examples-1.hs b/Task/Rosetta-Code-Count-examples/Haskell/rosetta-code-count-examples-1.hs deleted file mode 100644 index d7d1672254..0000000000 --- a/Task/Rosetta-Code-Count-examples/Haskell/rosetta-code-count-examples-1.hs +++ /dev/null @@ -1,37 +0,0 @@ -import Network.Browser -import Network.HTTP -import Network.URI -import Data.List -import Data.Maybe -import Text.XML.Light -import Control.Arrow - -justifyR w = foldl ((.return).(++).tail) (replicate w ' ') -showFormatted t n = t ++ ": " ++ justifyR 4 (show n) - -getRespons url = do - rsp <- Network.Browser.browse $ do - setAllowRedirects True - setOutHandler $ const (return ()) -- quiet - request $ getRequest url - return $ rspBody $ snd rsp - -getNumbOfExampels p = do - let pg = intercalate "_" $ words p - rsp <- getRespons $ "http://www.rosettacode.org/w/index.php?title=" ++ pg ++ "&action=raw" - let taskPage = rsp - countEx = length $ filter (=="=={{header|") $ takeWhile(not.null) $ unfoldr (Just. (take 11 &&& drop 1)) taskPage - return countEx - -progTaskExamples = do - rsp <- getRespons "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" - - let xmls = onlyElems $ parseXML $ rsp - tasks = concatMap (map (fromJust.findAttr (unqual "title")). filterElementsName (== unqual "cm")) xmls - - taskxx <- mapM getNumbOfExampels tasks - let ns = taskxx - tot = sum ns - - mapM_ putStrLn $ zipWith showFormatted tasks ns - putStrLn $ ("Total: " ++) $ show tot diff --git a/Task/Rosetta-Code-Count-examples/Haskell/rosetta-code-count-examples-2.hs b/Task/Rosetta-Code-Count-examples/Haskell/rosetta-code-count-examples-2.hs deleted file mode 100644 index 626e2b9d95..0000000000 --- a/Task/Rosetta-Code-Count-examples/Haskell/rosetta-code-count-examples-2.hs +++ /dev/null @@ -1,10 +0,0 @@ -*Main> progTaskExamples -100 doors: 56 -24 game: 11 -24 game Player: 9 -99 Bottles of Beer: 73 -Abstract type: 23 -Ackermann Function: 61 -Active object: 9 -... -Total: 9156 diff --git a/Task/Rosetta-Code-Count-examples/Haskell/rosetta-code-count-examples-3.hs b/Task/Rosetta-Code-Count-examples/Haskell/rosetta-code-count-examples-3.hs deleted file mode 100644 index 7ea3cd038b..0000000000 --- a/Task/Rosetta-Code-Count-examples/Haskell/rosetta-code-count-examples-3.hs +++ /dev/null @@ -1,82 +0,0 @@ -$define RCINDEX "http://rosettacode.org/mw/api.php?format=xml&action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500" -$define RCTASK "http://rosettacode.org/mw/index.php?action=raw&title=" -$define RCUA "User-Agent: Unicon Rosetta 0.1" -$define RCXUA "X-Unicon: http://unicon.org/" -$define TASKTOT "* Total Tasks *" -$define TOTTOT "* Total Headers*" - -link strings -link hexcvt - -procedure main(A) # simple single threaded read all at once implementation - Tasks := table(0) - every task := taskNames() do { - Tasks[TASKTOT] +:= 1 # count tasks - every lang := languages(task) do { # count languages - Tasks[task] +:= 1 - Tasks[TOTTOT] +:= 1 - } - } - every insert(O := set(),key(Tasks)) # extract & sort keys - O := put(sort(O--set(TOTTOT,TASKTOT)),TASKTOT,TOTTOT) # move totals to end - every write(k := !O, " : ", Tasks[k]," examples.") # report -end - -# Generate task names -procedure taskNames() - continue := "" - while \(txt := ReadURL(RCINDEX||continue)) do { - txt ? { - while tab(find("'\""),3,"0")||";",c) - } - - dxml[1] := u # insert URI as 1st arg - u := replacem!dxml # de-xml it - every (c := "") ||:= tr[!u] # reencode everything - c := replace(c,"%3E","'") # Hack to put single quotes back in - c := replace(c,"%26quot%3B","\"") # Hack to put double quotes back in - return c -end - -procedure ReadURL(url) #: read URL into string - page := open(url,"m",RCUA,RCXUA) | stop("Unable to open ",url) - text := "" - if page["Status-Code"] < 300 then while text ||:= reads(page,-1) - else write(&errout,image(url),": ", - page["Status-Code"]," ",page["Reason-Phrase"]) - close(page) - return text -end diff --git a/Task/Rosetta-Code-Count-examples/J/rosetta-code-count-examples-1.j b/Task/Rosetta-Code-Count-examples/J/rosetta-code-count-examples-1.j deleted file mode 100644 index a47f432cba..0000000000 --- a/Task/Rosetta-Code-Count-examples/J/rosetta-code-count-examples-1.j +++ /dev/null @@ -1,20 +0,0 @@ -require 'web/gethttp' - -getAllTaskSolnCounts=: monad define - tasks=. getCategoryMembers 'Programming_Tasks' - counts=. getTaskSolnCounts &> tasks - tasks;counts -) - -getTaskSolnCounts=: monad define - makeuri=. 'http://www.rosettacode.org/w/index.php?title=' , ,&'&action=raw' - wikidata=. gethttp makeuri urlencode y - ([: +/ '{{header|'&E.) wikidata -) - -formatSolnCounts=: monad define - 'tasks counts'=. y - tasks=. tasks , &.>':' - res=. ;:^:_1 tasks ,. (8!:0 counts) ,. <'examples.' - res , 'Total examples: ' , ": +/counts -) diff --git a/Task/Rosetta-Code-Count-examples/J/rosetta-code-count-examples-2.j b/Task/Rosetta-Code-Count-examples/J/rosetta-code-count-examples-2.j deleted file mode 100644 index c5da0cab6d..0000000000 --- a/Task/Rosetta-Code-Count-examples/J/rosetta-code-count-examples-2.j +++ /dev/null @@ -1,6 +0,0 @@ - formatSolnCounts getAllTaskSolnCounts '' -100 doors: 61 examples. -24 game: 15 examples. -24 game Player: 11 examples. -99 Bottles of Beer: 76 examples. -... diff --git a/Task/Rosetta-Code-Count-examples/Java/rosetta-code-count-examples.java b/Task/Rosetta-Code-Count-examples/Java/rosetta-code-count-examples.java deleted file mode 100644 index 642c7699e5..0000000000 --- a/Task/Rosetta-Code-Count-examples/Java/rosetta-code-count-examples.java +++ /dev/null @@ -1,69 +0,0 @@ -import java.util.ArrayList; -import ScreenScrape; - -public class CountProgramExamples { - private static final String baseURL = "http://rosettacode.org/wiki/"; - private static final String rootURL = "http://www.rosettacode.org/w/" - + "api.php?action=query&list=categorymembers" - + "&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"; - private static final String taskBegin = "title=\""; - private static final String taskEnd = "\""; - private static final String exmplBegin = ""; - private static final String exmplEnd = ""; - private static final String editBegin = ""; - - /** - * @param args - */ - public static void main(String[] args) { - int exTotal = 0; - try { - // Get root query results - ArrayList tasks = new ArrayList(); - ScreenScrape ss = new ScreenScrape(); - String rootPage = ss.read(rootURL); - while (rootPage.contains(taskBegin)) { - rootPage = rootPage.substring(rootPage.indexOf(taskBegin) - + taskBegin.length()); - String title = rootPage.substring(0, rootPage.indexOf(taskEnd)); - if (!title.contains("Category:")) { - tasks.add(title); - } - rootPage = rootPage.substring(rootPage.indexOf(taskEnd)); - } - // Loop through each task and print count - for (String task : tasks) { - String title = task.replaceAll("'", "'"); - String taskPage = ss.read(baseURL + title.replaceAll(" ", "_")); - int exSubTot; - if (taskPage.contains(exmplBegin)) { - int startPos = taskPage.lastIndexOf(exmplBegin) - + exmplBegin.length(); - String countStr = taskPage.substring(startPos, - taskPage.indexOf(exmplEnd, startPos)); - exSubTot = Integer - .parseInt(countStr.contains(".") ? countStr - .substring(0, countStr.indexOf(".")) - : countStr); - } else { - exSubTot = 0; - while (taskPage.contains(editBegin)) { - taskPage = taskPage.substring(taskPage - .indexOf(editBegin) + editBegin.length()); - exSubTot++; - } - } - exTotal += exSubTot; - System.out.println(title + ": " + exSubTot + " examples."); - } - // Print total - System.out.println("\nTotal: " + exTotal + " examples."); - } catch (Exception e) { - System.out.println(title); - System.out.println(startPos + ":" - + taskPage.indexOf(exmplEnd, startPos)); - System.out.println(taskPage); - e.printStackTrace(System.out); - } - } -} diff --git a/Task/Rosetta-Code-Count-examples/MATLAB/rosetta-code-count-examples.m b/Task/Rosetta-Code-Count-examples/MATLAB/rosetta-code-count-examples.m deleted file mode 100644 index 3a93fa9afb..0000000000 --- a/Task/Rosetta-Code-Count-examples/MATLAB/rosetta-code-count-examples.m +++ /dev/null @@ -1,18 +0,0 @@ - function c = count_examples(url) - c = 0; - [s, success] = urlread (url); - if ~success, return; end; - c = length(strfind(s,'

    " "], "\" has ", - Length@Select[Import["http://rosettacode.org/wiki/" <> #, "Data"][[1,2]], - StringFreeQ[#, __ ~~ "Programming Task" | __ ~~ "Omit"]& ], " example(s)"]& - ~Map~ StringReplace[TaskList, " " -> "_"] diff --git a/Task/Rosetta-Code-Count-examples/OCaml/rosetta-code-count-examples.ocaml b/Task/Rosetta-Code-Count-examples/OCaml/rosetta-code-count-examples.ocaml deleted file mode 100644 index e8b9288c6c..0000000000 --- a/Task/Rosetta-Code-Count-examples/OCaml/rosetta-code-count-examples.ocaml +++ /dev/null @@ -1,62 +0,0 @@ -open Http_client.Convenience - - -let repl_quote s = - let reg = Str.regexp_string "'" in - (Str.global_replace reg "%27" s) - -let repl_space s = - let s = String.copy s in - for i = 0 to pred(String.length s) do - if s.[i] = ' ' then s.[i] <- '_' - done; - (s) -(* or in OCaml 4.00+: - let repl_space = String.map (fun c -> if c = ' ' then '_' else c) -*) - -let count_ex s = - let pat = Str.regexp_string "=={{header|" in - let rec aux n p = - try - let p = Str.search_forward pat s p in - aux (n+1) (p+1) - with Not_found -> (n) - in - aux 0 0 - -let get_child child xml = - let child = - List.find - (function Xml.Element (tag,_,_) when tag = child -> true | _ -> false) xml - in - Xml.children child - -let () = - let url = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&\ - cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" in - - let xml = Xml.parse_string (http_get url) in - - let total = ref 0 in - at_exit (fun () -> Printf.printf "\n Total: %d\n" !total); - - let f = function - | Xml.Element ("cm", attrs, _) -> - (try - let _title = List.assoc "title" attrs in - let title = repl_quote (repl_space _title) in - let url = "http://www.rosettacode.org/w/index.php?title="^ title ^"&action=raw" in - let n = count_ex (http_get url) in - Printf.printf "%s: %d\n%!" _title n; - total := n + !total; - with Http_client.Http_error (404, _) -> ()) - | _ -> () - in - - match xml with - | Xml.Element ("api", _, ch) -> - let query = get_child "query" ch in - let catmb = get_child "categorymembers" query in - List.iter f catmb - | _ -> () diff --git a/Task/Rosetta-Code-Count-examples/Objeck/rosetta-code-count-examples.objeck b/Task/Rosetta-Code-Count-examples/Objeck/rosetta-code-count-examples.objeck deleted file mode 100644 index 97704ecfee..0000000000 --- a/Task/Rosetta-Code-Count-examples/Objeck/rosetta-code-count-examples.objeck +++ /dev/null @@ -1,38 +0,0 @@ -use HTTP; -use XML; - -class RosettaCount { - function : Main(args : String[]) ~ Nil { - taks_xml := HttpGet("http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"); - parser := XmlParser->New(taks_xml); - if(parser->Parse()) { - task_names := parser->FindElements("/api/query/categorymembers/cm"); - if(task_names <> Nil) { - each(i : task_names) { - task_name := task_names->Get(i)->As(XmlElement)->GetAttribute("title")->GetValue(); - task_url := "http://rosettacode.org/mw/index.php?title="; - task_url->Append(task_name); - task_url->Append("&action=raw"); - - task := HttpGet(task_url); - counts := task->FindAll("=={{header|"); - if(counts->Size() > 0) { - IO.Console->Print(UrlUtility->Decode(task_name))->Print(": ")->PrintLine(counts->Size()); - }; - }; - }; - }; - } - - function : HttpGet(url : String) ~ String { - xml := ""; - - client := HttpClient->New(); - lines := client->Get(url); - each(i : lines) { - xml->Append(lines->Get(i)->As(String)); - }; - - return xml; - } -} diff --git a/Task/Rosetta-Code-Count-examples/Oz/rosetta-code-count-examples.oz b/Task/Rosetta-Code-Count-examples/Oz/rosetta-code-count-examples.oz deleted file mode 100644 index 789d287782..0000000000 --- a/Task/Rosetta-Code-Count-examples/Oz/rosetta-code-count-examples.oz +++ /dev/null @@ -1,85 +0,0 @@ -declare - [HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']} - [XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']} - [StringX] = {Module.link ['x-oz://system/String.ozf']} - [Regex] = {Module.link ['x-oz://contrib/regex']} - - AllTasksUrl = "http://rosettacode.org/mw/api.php?action=query&list="# - "categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" - - proc {Main} - AllTasks = {Parse {GetPage AllTasksUrl}} - TaskTitles = {GetTitles AllTasks} - Total = {NewCell 0} - in - for Task in TaskTitles do - TaskPage = {GetPage {TaskUrl Task}} - RE = {Regex.compile "{{header\\|" [extended newline icase]} - NumMatches = {Length {Regex.allMatches RE TaskPage}} - in - {System.showInfo Task#": "#NumMatches#" examples."} - Total := @Total + NumMatches - end - {System.showInfo "Total: "#@Total#" examples."} - end - - fun {TaskUrl Task} - "http://rosettacode.org/mw/index.php?"# - "title="#{PercentEncode {StringX.replace Task " " "_"}}# - "&action=raw" - end - - %% GetPage - local - Client = {New HTTPClient.urlGET init(inPrms(toFile:false toStrm:true) _)} - in - fun {GetPage RawUrl} - Url = {VirtualString.toString RawUrl} - OutParams - HttpResponseParams - in - {Client getService(Url ?OutParams ?HttpResponseParams)} - OutParams.sOut - end - end - - %% Parse - local - Parser = {New XMLParser.parser init} - in - fun {Parse Xs} {Parser parseVS(Xs $)} end - end - - fun {GetTitles Doc} - CMs = Doc.2.1.children.1.children.1.children - fun {Attributes element(attributes:As ...)} As end - fun {IsTitle attribute(name:N ...)} N == title end - in - {Map {Filter {Flatten {Map CMs Attributes}} IsTitle} - fun {$ A} {Atom.toString A.value} end} - end - - fun {PercentEncode Xs} - case Xs of nil then nil - [] X|Xr then - if {Char.isDigit X} orelse {Member X [&- &_ &. &~]} - orelse X >= &a andthen X =< &z - orelse X >= &z andthen X =< &Z then - X|{PercentEncode Xr} - else - {Append &%|{ToHex2 X} {PercentEncode Xr}} - end - end - end - - fun {ToHex2 X} - [{ToHex1 X div 16} {ToHex1 X mod 16}] - end - - fun {ToHex1 X} - if X >= 0 andthen X =< 9 then &0 + X - elseif X >= 10 andthen X =< 15 then &A + X - 10 - end - end -in - {Main} diff --git a/Task/Rosetta-Code-Count-examples/Perl-6/rosetta-code-count-examples.pl6 b/Task/Rosetta-Code-Count-examples/Perl-6/rosetta-code-count-examples.pl6 deleted file mode 100644 index c40edbd79d..0000000000 --- a/Task/Rosetta-Code-Count-examples/Perl-6/rosetta-code-count-examples.pl6 +++ /dev/null @@ -1,10 +0,0 @@ -use LWP::Simple; - -my $site = "http://rosettacode.org"; -my $list-url = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"; - -for get("$site$list_url").comb(/'cm' .*? 'title="' <( .*? )> '"'/) { - my $slug = .trans(' ' => '_'); - my $count = +get("$site/wiki/$slug").comb(/'toclevel-1'/); - say "$_: $count examples"; -} diff --git a/Task/Rosetta-Code-Count-examples/Perl/rosetta-code-count-examples-1.pl b/Task/Rosetta-Code-Count-examples/Perl/rosetta-code-count-examples-1.pl deleted file mode 100644 index e204f2a787..0000000000 --- a/Task/Rosetta-Code-Count-examples/Perl/rosetta-code-count-examples-1.pl +++ /dev/null @@ -1,10 +0,0 @@ -use LWP::Simple; - -my $site = "http://rosettacode.org"; -my $list_url = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"; - -for (get("$site$list_url") =~ /cm.*?title="(.*?)"/g) { - (my $slug = $_) =~ tr/ /_/; - my $count = () = get("$site/wiki/$slug") =~ /toclevel-1/g; - print "$_: $count examples\n"; -} diff --git a/Task/Rosetta-Code-Count-examples/Perl/rosetta-code-count-examples-2.pl b/Task/Rosetta-Code-Count-examples/Perl/rosetta-code-count-examples-2.pl deleted file mode 100644 index e0b89bbbf7..0000000000 --- a/Task/Rosetta-Code-Count-examples/Perl/rosetta-code-count-examples-2.pl +++ /dev/null @@ -1,12 +0,0 @@ -use v5.10; -use Mojo::UserAgent; - -my $site = "http://rosettacode.org"; -my $list_url = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"; - -my $ua = Mojo::UserAgent->new; -$ua->get("$site$list_url")->res->dom->find('cm')->each(sub { - (my $slug = $_->{title}) =~ tr/ /_/; - my $count = $ua->get("$site/wiki/$slug")->res->dom->find("#toc .toclevel-1")->size; - say "$_->{title}: $count examples"; -}); diff --git a/Task/Rosetta-Code-Count-examples/PicoLisp/rosetta-code-count-examples.l b/Task/Rosetta-Code-Count-examples/PicoLisp/rosetta-code-count-examples.l deleted file mode 100644 index db55565d40..0000000000 --- a/Task/Rosetta-Code-Count-examples/PicoLisp/rosetta-code-count-examples.l +++ /dev/null @@ -1,12 +0,0 @@ -(load "@lib/http.l") - -(client "rosettacode.org" 80 - "mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" - (while (from " title=\"") - (let Task (till "\"") - (client "rosettacode.org" 80 (pack "wiki/" (replace Task " " "_")) - (let Cnt 0 - (while (from "") - (unless (sub? "." (till "<" T)) - (inc 'Cnt) ) ) - (out NIL (prinl (ht:Pack Task) ": " Cnt)) ) ) ) ) ) diff --git a/Task/Rosetta-Code-Count-examples/PureBasic/rosetta-code-count-examples.purebasic b/Task/Rosetta-Code-Count-examples/PureBasic/rosetta-code-count-examples.purebasic deleted file mode 100644 index fbb34093c2..0000000000 --- a/Task/Rosetta-Code-Count-examples/PureBasic/rosetta-code-count-examples.purebasic +++ /dev/null @@ -1,25 +0,0 @@ -OpenConsole() -URLDownloadToFile_( #Null, "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml", "tasks.xml", 0, #Null) -ReadFile(0, "tasks.xml") - x1$ = ReadString(0) - Repeat - x2 = FindString(x1$, "title=", x2 + 1) - If x2 - title$ = Mid(x1$, x2 + 7, 99) - title$ = Left(title$, FindString(title$, ">", 1) - 4) - URLDownloadToFile_( #Null, "http://www.rosettacode.org/w/index.php?title=" + title$ + "&action=raw", "task.xml", 0, #Null) - ReadFile(1, "task.xml") - While Not Eof(1) - y1$ = ReadString(1) - If FindString(y1$, "=={{header|", 1) - j + 1 - EndIf - Wend - PrintN( title$ +": " + Str(j) + " examples") - k + j - j = 0 - CloseFile(1) - EndIf - Until x2 = 0 - PrintN("Total: " + Str(k) + " examples") - Input() diff --git a/Task/Rosetta-Code-Count-examples/Python/rosetta-code-count-examples.py b/Task/Rosetta-Code-Count-examples/Python/rosetta-code-count-examples.py deleted file mode 100644 index 1c3bf5b90d..0000000000 --- a/Task/Rosetta-Code-Count-examples/Python/rosetta-code-count-examples.py +++ /dev/null @@ -1,12 +0,0 @@ -import urllib, xml.dom.minidom - -x = urllib.urlopen("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml") - -tasks = [] -for i in xml.dom.minidom.parseString(x.read()).getElementsByTagName("cm"): - t = i.getAttribute('title').replace(" ", "_") - y = urllib.urlopen("http://www.rosettacode.org/w/index.php?title=%s&action=raw" % t.encode('utf-8')) - tasks.append( y.read().lower().count("{{header|") ) - print t.replace("_", " ") + ": %d examples." % tasks[-1] - -print "\nTotal: %d examples." % sum(tasks) diff --git a/Task/Rosetta-Code-Count-examples/R/rosetta-code-count-examples.r b/Task/Rosetta-Code-Count-examples/R/rosetta-code-count-examples.r deleted file mode 100644 index 889be021d7..0000000000 --- a/Task/Rosetta-Code-Count-examples/R/rosetta-code-count-examples.r +++ /dev/null @@ -1,14 +0,0 @@ -library(XML) -library(RCurl) -doc <- xmlInternalTreeParse("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml") -nodes <- getNodeSet(doc,"//cm") -titles = as.character( sapply(nodes, xmlGetAttr, "title") ) -headers <- list() -counts <- list() -for (i in 1:length(titles)){ - headers[[i]] <- getURL( paste("http://rosettacode.org/mw/index.php?title=", gsub(" ", "_", titles[i]), "&action=raw", sep="") ) - counts[[i]] <- strsplit(headers[[i]],split=" ")[[1]] - counts[[i]] <- grep("\\{\\{header", counts[[i]]) - cat(titles[i], ":", length(counts[[i]]), "examples\n") -} -cat("Total: ", length(unlist(counts)), "examples\n") diff --git a/Task/Rosetta-Code-Count-examples/README b/Task/Rosetta-Code-Count-examples/README deleted file mode 100644 index cf82a4b320..0000000000 --- a/Task/Rosetta-Code-Count-examples/README +++ /dev/null @@ -1 +0,0 @@ -Data source: http://rosettacode.org/wiki/Rosetta_Code/Count_examples diff --git a/Task/Rosetta-Code-Count-examples/Racket/rosetta-code-count-examples.rkt b/Task/Rosetta-Code-Count-examples/Racket/rosetta-code-count-examples.rkt deleted file mode 100644 index cf888a2d43..0000000000 --- a/Task/Rosetta-Code-Count-examples/Racket/rosetta-code-count-examples.rkt +++ /dev/null @@ -1,25 +0,0 @@ -#lang racket - -(require net/url net/uri-codec json (only-in racket/dict [dict-ref ref])) - -(define (RC-get verb params) - ((compose1 get-pure-port string->url format) - "http://rosettacode.org/mw/~a.php?~a" verb (alist->form-urlencoded params))) - -(define (get-category catname) - (let loop ([c #f]) - (define t - ((compose1 read-json RC-get) 'api - `([action . "query"] [format . "json"] - [list . "categorymembers"] [cmtitle . ,(format "Category:~a" catname)] - [cmcontinue . ,(and c (ref c 'cmcontinue))] [cmlimit . "500"]))) - (define (c-m key) (ref (ref t key '()) 'categorymembers #f)) - (append (for/list ([page (c-m 'query)]) (ref page 'title)) - (cond [(c-m 'query-continue) => loop] [else '()])))) - -(printf "Total: ~a\n" - (for/sum ([task (get-category 'Programming_Tasks)]) - (define s ((compose1 length regexp-match-positions*) - #rx"=={{" (RC-get 'index `([action . "raw"] [title . ,task])))) - (printf "~a: ~a\n" task s) - s)) diff --git a/Task/Rosetta-Code-Count-examples/Ruby/rosetta-code-count-examples-1.rb b/Task/Rosetta-Code-Count-examples/Ruby/rosetta-code-count-examples-1.rb deleted file mode 100644 index 0415f43225..0000000000 --- a/Task/Rosetta-Code-Count-examples/Ruby/rosetta-code-count-examples-1.rb +++ /dev/null @@ -1,51 +0,0 @@ -require 'open-uri' -require 'rexml/document' - -module RosettaCode - - URL_ROOT = "http://rosettacode.org/mw" - - def self.get_url(page, query) - begin - # Ruby 1.9.2 - pstr = URI.encode_www_form_component(page) - qstr = URI.encode_www_form(query) - rescue NoMethodError - require 'cgi' - pstr = CGI.escape(page) - qstr = query.map {|k,v| - "%s=%s" % [CGI.escape(k.to_s), CGI.escape(v.to_s)]}.join("&") - end - url = "#{URL_ROOT}/#{pstr}?#{qstr}" - p url if $DEBUG - url - end - - def self.get_api_url(query) - get_url "api.php", query - end - - def self.category_members(category) - query = { - "action" => "query", - "list" => "categorymembers", - "cmtitle" => "Category:#{category}", - "format" => "xml", - "cmlimit" => 500, - } - while true - url = get_api_url query - doc = REXML::Document.new open(url) - - REXML::XPath.each(doc, "//cm") do |task| - yield task.attribute("title").value - end - - continue = REXML::XPath.first(doc, "//query-continue") - break if continue.nil? - cm = REXML::XPath.first(continue, "categorymembers") - query["cmcontinue"] = cm.attribute("cmcontinue").value - end - end - -end diff --git a/Task/Rosetta-Code-Count-examples/Ruby/rosetta-code-count-examples-2.rb b/Task/Rosetta-Code-Count-examples/Ruby/rosetta-code-count-examples-2.rb deleted file mode 100644 index 3a19cd34f8..0000000000 --- a/Task/Rosetta-Code-Count-examples/Ruby/rosetta-code-count-examples-2.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'rosettacode' - -total_examples = 0 - -RosettaCode.category_members("Programming_Tasks") do |task| - url = RosettaCode.get_url("index.php", {"action" => "raw", "title" => task}) - examples = open(url).read.scan("=={{header").length - puts "#{task}: #{examples}" - total_examples += examples -end - -puts -puts "Total: #{total_examples}" diff --git a/Task/Rosetta-Code-Count-examples/Run-BASIC/rosetta-code-count-examples.run b/Task/Rosetta-Code-Count-examples/Run-BASIC/rosetta-code-count-examples.run deleted file mode 100644 index 98e7e076d8..0000000000 --- a/Task/Rosetta-Code-Count-examples/Run-BASIC/rosetta-code-count-examples.run +++ /dev/null @@ -1,32 +0,0 @@ -html "" - -a$ = httpGet$("http://rosettacode.org/wiki/Category:Programming_Tasks") -a$ = word$(a$,1,"
    NumTaskExamples
    ") -i = instr(a$,"
    0 - count = count + 1 - i = instr(a$,"",i+5) - a1$ = mid$(a$,i+15,j-i) - taskId$ = word$(a1$,1,"""") - task$ = word$(a1$,3,"""") - url$ = "http://rosettacode.org/wiki/";taskId$ - a2$ = httpGet$(url$) - ii = instr(a2$,"") - jj = 0 - while ii > 0 - jj = ii - ii = instr(a2$,"",ii+10) - wend - if jj = 0 then - examp = 0 - else - kk = instr(a2$,"<",jj+24) - examp = int(val(mid$(a2$,jj+24,kk-jj-24))) - end if - html "";count;"";task$;"";examp;"" - totExamp = totExamp + examp -wend -html "**** Total **";totExamp;"" -end diff --git a/Task/Rosetta-Code-Count-examples/Scala/rosetta-code-count-examples.scala b/Task/Rosetta-Code-Count-examples/Scala/rosetta-code-count-examples.scala deleted file mode 100644 index 824096f0f5..0000000000 --- a/Task/Rosetta-Code-Count-examples/Scala/rosetta-code-count-examples.scala +++ /dev/null @@ -1,25 +0,0 @@ -import scala.language.postfixOps - -object TaskCount extends App { - import java.net.{ URL, URLEncoder } - import scala.io.Source.fromURL - - System.setProperty("http.agent", "*") - val allTasksURL = - "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" - val allTasks = xml.parsing.XhtmlParser(fromURL(new URL(allTasksURL))) - - val regexExpr = "(?i)==\\{\\{header\\|".r - - def oneTaskURL(title: String) = { - println(s"Check $title") - "http://www.rosettacode.org/w/index.php?title=%s&action=raw" format URLEncoder.encode(title.replace(' ', '_'), "UTF-8") - } - - def count(title: String) = regexExpr findAllIn fromURL(new URL(oneTaskURL(title)))(io.Codec.UTF8).mkString length - - val counts = for (task <- allTasks \\ "cm" \\ "@title" map (_.text)) yield scala.actors.Futures.future((task, count(task))) - - counts map (_.apply) map Function.tupled("%s: %d examples." format (_, _)) foreach println - println("\nTotal: %d examples." format (counts map (_.apply._2) sum)) -} diff --git a/Task/Rosetta-Code-Count-examples/TUSCRIPT/rosetta-code-count-examples.tu b/Task/Rosetta-Code-Count-examples/TUSCRIPT/rosetta-code-count-examples.tu deleted file mode 100644 index be933b9baf..0000000000 --- a/Task/Rosetta-Code-Count-examples/TUSCRIPT/rosetta-code-count-examples.tu +++ /dev/null @@ -1,39 +0,0 @@ -$$ MODE TUSCRIPT -url="http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" -data=REQUEST (url) - -BUILD S_TABLE beg=* -DATA :title=": -BUILD S_TABLE end=* -DATA :": - -titles=EXTRACT (data,beg|,end,1,0,"~~") -titles=SPLIT (titles,":~~:") -sz_titles=SIZE (titles) - -BUILD R_TABLE header=":==\{\{header|:" -all=* - -ERROR/STOP CREATE ("tasks",seq-e,-std-) - -COMPILE -LOOP title=titles -ask=* -ask =SET_VALUE(ask,"title",title) -ask =SET_VALUE(ask,"action","raw") -ask =ENCODE (ask,cgi) -http ="http://www.rosettacode.org/mw/index.php" -url =CONCAT (http,"?",ask) -data =REQUEST (url) -header =FILTER_INDEX (data,header,-) -sz_header=SIZE(header) -line =CONCAT (title,"=",sz_header," members") -FILE "tasks" = line -all =APPEND(all,sz_header) -ENDLOOP - -ENDCOMPILE -all =JOIN(all),sum=SUM(all),time=time() -line=CONCAT (time,": ", sz_titles, " Programing Tasks: ", sum, " solutions") - -FILE "tasks" = line diff --git a/Task/Rosetta-Code-Count-examples/Tcl/rosetta-code-count-examples.tcl b/Task/Rosetta-Code-Count-examples/Tcl/rosetta-code-count-examples.tcl deleted file mode 100644 index ab23c47ebf..0000000000 --- a/Task/Rosetta-Code-Count-examples/Tcl/rosetta-code-count-examples.tcl +++ /dev/null @@ -1,65 +0,0 @@ -package require Tcl 8.5 -package require http -package require json - -fconfigure stdout -buffering none - -proc get_tasks {category} { - set start [clock milliseconds] - puts -nonewline "getting $category members..." - set base_url http://www.rosettacode.org/w/api.php - set query {action query list categorymembers cmtitle Category:%s format json cmlimit 500} - set this_query [dict create {*}[split [format $query $category]]] - set tasks [list] - - while {1} { - set url [join [list $base_url [http::formatQuery {*}$this_query]] ?] - set response [http::geturl $url] - if {[set s [http::status $response]] ne "ok" || [http::ncode $response] != 200} { - error "Oops: url=$url\nstatus=$s\nhttp code=[http::code $response]" - } - set data [json::json2dict [http::data $response]] - http::cleanup $response - - # add tasks to list - foreach task [dict get $data query categorymembers] { - lappend tasks [dict get [dict create {*}$task] title] - } - - if {[catch {dict get $data query-continue categorymembers cmcontinue} continue_task] != 0} { - # no more continuations, we're done - break - } - dict set this_query cmcontinue $continue_task - } - puts " found [llength $tasks] tasks in [expr {[clock milliseconds] - $start}] milliseconds" - return $tasks -} - -# This proc can be replaced by a single regexp command: -# set count [regexp -all "***=$needle" $haystack] -# However this proc is more efficient -- we're dealing with plain strings only. -proc count_substrings {needle haystack} { - set count 0 - set idx 0 - while {[set idx [string first $needle $haystack $idx]] != -1} { - incr count - incr idx - } - return $count -} - -set total 0 -foreach task [get_tasks Programming_Tasks] { - set url [format "http://www.rosettacode.org/w/index.php?title=%s&action=raw" [string map {{ } _} $task]] - set response [http::geturl $url] - if {[set s [http::status $response]] ne "ok" || [http::ncode $response] != 200} { - error "Oops: url=$url\nstatus=$s\nhttp code=[http::code $response]" - } - set count [count_substrings "\{\{header|" [http::data $response]] - puts [format "%3d examples in %s" $count $task] - http::cleanup $response - incr total $count -} - -puts "\nTotal: $total examples" diff --git a/Task/Rosetta-Code-Find-bare-lang-tags/AutoHotkey/rosetta-code-find-bare-lang-tags.ahk b/Task/Rosetta-Code-Find-bare-lang-tags/AutoHotkey/rosetta-code-find-bare-lang-tags.ahk deleted file mode 100644 index 1757b12e05..0000000000 --- a/Task/Rosetta-Code-Find-bare-lang-tags/AutoHotkey/rosetta-code-find-bare-lang-tags.ahk +++ /dev/null @@ -1 +0,0 @@ -Pseudocode diff --git a/Task/Rosetta-Code-Find-bare-lang-tags/C/rosetta-code-find-bare-lang-tags.c b/Task/Rosetta-Code-Find-bare-lang-tags/C/rosetta-code-find-bare-lang-tags.c deleted file mode 100644 index e84c223938..0000000000 --- a/Task/Rosetta-Code-Find-bare-lang-tags/C/rosetta-code-find-bare-lang-tags.c +++ /dev/null @@ -1 +0,0 @@ -printf("Hello world!\n"); diff --git a/Task/Rosetta-Code-Find-bare-lang-tags/Perl/rosetta-code-find-bare-lang-tags.pl b/Task/Rosetta-Code-Find-bare-lang-tags/Perl/rosetta-code-find-bare-lang-tags.pl deleted file mode 100644 index 053662f327..0000000000 --- a/Task/Rosetta-Code-Find-bare-lang-tags/Perl/rosetta-code-find-bare-lang-tags.pl +++ /dev/null @@ -1 +0,0 @@ -print "Hello world!\n" diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/00DESCRIPTION b/Task/Rosetta-Code-Find-unimplemented-tasks/00DESCRIPTION deleted file mode 100644 index 76b95f1351..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/00DESCRIPTION +++ /dev/null @@ -1,5 +0,0 @@ -Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. - -Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. - -You'll need to use the Media Wiki API, which you can find out about locally, [http://rosettacode.org/mw/api.php here], or in Media Wiki's API documentation at, [http://www.mediawiki.org/wiki/API_Query API:Query] diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/00META.yaml b/Task/Rosetta-Code-Find-unimplemented-tasks/00META.yaml deleted file mode 100644 index b392469fa2..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/00META.yaml +++ /dev/null @@ -1,2 +0,0 @@ ---- -note: Rosetta Code related diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Ada/rosetta-code-find-unimplemented-tasks.ada b/Task/Rosetta-Code-Find-unimplemented-tasks/Ada/rosetta-code-find-unimplemented-tasks.ada deleted file mode 100644 index 402884b167..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Ada/rosetta-code-find-unimplemented-tasks.ada +++ /dev/null @@ -1,123 +0,0 @@ -with Aws.Client, Aws.Messages, Aws.Response, Aws.Resources, Aws.Url; -with Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs; -with Input_Sources.Strings, Unicode, Unicode.Ces.Utf8; -with Ada.Strings.Unbounded, Ada.Text_IO, Ada.Command_Line; -with Ada.Containers.Vectors; - -use Aws.Client, Aws.Messages, Aws.Response, Aws.Resources, Aws.Url; -use Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs; -use Aws, Ada.Strings.Unbounded, Input_Sources.Strings; -use Ada.Text_IO, Ada.Command_Line; - -procedure Not_Coded is - - package Members_Vectors is new Ada.Containers.Vectors ( - Index_Type => Positive, - Element_Type => Unbounded_String); - use Members_Vectors; - - All_Tasks, Language_Members : Vector; - - procedure Get_Vector (Category : in String; Mbr_Vector : in out Vector) is - Reader : Tree_Reader; - Doc : Document; - List : Node_List; - N : Node; - A : Attr; - Page : Aws.Response.Data; - S : Messages.Status_Code; - - -- Query has cmlimit value of 100, so we need 5 calls to - -- retrieve the complete list of Programming_category - Uri_Xml : constant String := - "http://rosettacode.org/mw/api.php?action=query&list=categorymembers" - & - "&format=xml&cmlimit=100&cmtitle=Category:"; - Cmcontinue : Unbounded_String := Null_Unbounded_String; - begin - loop - Page := - Aws.Client.Get (Uri_Xml & Category & (To_String (Cmcontinue))); - S := Response.Status_Code (Page); - if S not in Messages.Success then - Put_Line - ("Unable to retrieve data => Status Code :" & - Image (S) & - " Reason :" & - Reason_Phrase (S)); - raise Connection_Error; - end if; - declare - Xml : constant String := Message_Body (Page); - Source : String_Input; - begin - Open - (Xml'Unrestricted_Access, - Unicode.Ces.Utf8.Utf8_Encoding, - Source); - Parse (Reader, Source); - Close (Source); - end; - Doc := Get_Tree (Reader); - List := Get_Elements_By_Tag_Name (Doc, "cm"); - for Index in 1 .. Length (List) loop - N := Item (List, Index - 1); - A := Get_Named_Item (Attributes (N), "title"); - Members_Vectors.Append - (Mbr_Vector, - To_Unbounded_String (Value (A))); - end loop; - Free (List); - List := Get_Elements_By_Tag_Name (Doc, "query-continue"); - if Length (List) = 0 then - -- we are done - Free (List); - Free (Reader); - exit; - end if; - N := First_Child (Item (List, 0)); - A := Get_Named_Item (Attributes (N), "cmcontinue"); - Cmcontinue := - To_Unbounded_String - ("&cmcontinue=" & Aws.Url.Encode (Value (A))); - Free (List); - Free (Reader); - end loop; - end Get_Vector; - - procedure Quick_Diff (From : in out Vector; Substract : in Vector) is - Beginning, Position : Extended_Index; - begin - -- take adavantage that both lists are already sorted - Beginning := First_Index (From); - for I in First_Index (Substract) .. Last_Index (Substract) loop - Position := - Find_Index - (Container => From, - Item => Members_Vectors.Element (Substract, I), - Index => Beginning); - if not (Position = No_Index) then - Delete (From, Position); - Beginning := Position; - end if; - end loop; - end Quick_Diff; - -begin - if Argument_Count = 0 then - Put_Line ("Can't process : No language given!"); - return; - else - Get_Vector (Argument (1), Language_Members); - end if; - - Get_Vector ("Programming_Tasks", All_Tasks); - Quick_Diff (All_Tasks, Language_Members); - - for I in First_Index (All_Tasks) .. Last_Index (All_Tasks) loop - Put_Line (To_String (Members_Vectors.Element (All_Tasks, I))); - end loop; - Put_Line - ("Numbers of tasks not implemented :=" & - Integer'Image (Last_Index ((All_Tasks)))); -end Not_Coded; diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/AutoHotkey/rosetta-code-find-unimplemented-tasks.ahk b/Task/Rosetta-Code-Find-unimplemented-tasks/AutoHotkey/rosetta-code-find-unimplemented-tasks.ahk deleted file mode 100644 index 97bd6c3de4..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/AutoHotkey/rosetta-code-find-unimplemented-tasks.ahk +++ /dev/null @@ -1,184 +0,0 @@ -#NoEnv ; do not resolve environment variables (speed) -#SingleInstance force ; allow only one instance -SetBatchLines, -1 ; set to highest script speed -SetControlDelay, 0 ; set delay between control commands to lowest - -; additional label, for clarity only -AutoExec: - Gui, Add, DDL, x10 y10 w270 r20 vlngStr ; add drop-down list - Gui, Add, Button, x290 y10 gShowLng, Show Unimplemented ; add button - Gui, Add, ListView, x10 y36 w400 h300 vcatLst gOnLV, Unimplemented ; add listview - Gui, Add, StatusBar, vsbStr, ; add statusbar - Gui, Show, , RosettaCode unimplemented list ; show the gui - allLng := getList("lng") ; get a list of all available languages - selectStr = Select language... ; set selection string for ddl - GuiControl, , LngStr, |%selectStr%||%allLng% ; set the ddl to new contents - SB_SetIcon("user32.dll", 5) ; change statusbar icon - SB_SetText("Done loading languages. Select from menu.") ; change statusbar text -Return ; end of the autoexec section. Script waits for input. - -; subroutine for language list in ddl update -ShowLng: - Gui, Submit, NoHide ; refresh all gui variables - If (lngStr != selectStr) ; if the current selected language is not the selection string - { - SB_SetIcon("user32.dll", 2) ; set statusbar icon to exclamation - SB_SetText("Loading unimplemented tasks... Please wait.") ; set statusbar text - allTsk := getList("tsk") ; get a list of all tasks - allThis := getList(lngStr) ; get a list of all done tasks for this language - Loop, Parse, allTsk, | ; parse the list of all tasks - { - If !InStr(allThis,A_LoopField) ; if the current task is not found in the list of all tasks - notImpl .= A_LoopField . "|" ; add the current field to the notImpl variable - allTskCnt := A_Index ; save the index for final count - } - StringTrimRight, notImpl, notImpl, 1 ; remove last delimiter - LV_Delete() ; emty the listview - GuiControl, -Redraw, catLst ; set the listview to not redraw while adding (speed) - Loop, Parse, notImpl, | ; parse the list of not implemented tasks - { - LV_Add("", A_LoopField) ; add them to the listview, field by field - notImplCnt := A_Index ; save the index for final count - } - GuiControl, +Redraw, catLst ; set the listview back to normal - SB_SetIcon("user32.dll", 5) ; change statusbar icon to information - SB_SetText("There are " . notImplCnt . " of " . allTskCnt - . " tasks unimplemented. Double-click task to open in browser.") ; set the statusbar text - notImpl = ; empty the notImpl variable - notImplCnt = 0 ; set the count back to 0 - } -Return - -; subroutine for action on listview -OnLV: - If (A_GuiEvent = "DoubleClick") ; if the listview was double-clicked - { - LV_GetText(rowTxt, A_EventInfo) ; get the text of the clicked row - rowTxt := Enc_Uri(rowTxt) ; uri-encode the text - StringReplace, rowTxt, rowTxt, `%20, _, All ; replace all space-encodings with underscores - Run % "http://rosettacode.org/wiki/" . rowTxt ; run the resulting link in the default browser - } -Return - -; generic function to gather list -getList(category) -{ - fileName = temp.xml ; set temp-file name - If (category = "lng") ; if the category received is lng - { - category = Programming_Languages ; set the category - fileName = lng.xml ; set temp-file name - IfExist, %fileName% ; if the file already exists - { - FileGetTime, modTime, %fileName% ; get the last modified time - EnvSub, modTime, %A_Now%, days ; get the difference between now and last modified time in days - If (modTime < 3) ; if the result is less than 3 - Goto, GetFileNoDL ; go to function-internal subroutine to parse - } - SB_SetIcon("user32.dll", 2) ; set statusbar icon - SB_SetText("Loading languages... Please wait.") ; set statusbar text - } - If (category = "tsk") ; if the category received is tsk - category = Programming_Tasks ; set the category - - getFile: ; function-internal subroutine for getting a file and parsing it - ; construct the url - url := "http://www.rosettacode.org/w/api.php?action=query&list=" - . "categorymembers&cmtitle=Category:" . category - . "&cmlimit=500&format=xml" . doContinue - UrlDownloadToFile, %url%, %fileName% ; download the url - - getFileNoDL: ; function-internal subroutine for parsing a file - FileRead, data, %fileName% ; read file into variable - pos = 1 ; set while-loop counter - rxp = title="(.*?)" ; set regular expression - While (pos := RegExMatch(data, rxp, title, pos)) ; get the contents of the title fields one-by-one - { - If InStr(title1, "Category:") ; if the contents contain Category: - StringTrimLeft, title1, title1, 9 ; remove that from the contents - StringReplace, title1, title1, |, `|, All ; escape all containing delimiters - title1 := Dec_XML(UTF82Ansi(title1)) ; convert to ansi first and then decode html entities - allTitles .= title1 . "|" ; add this title to list - pos++ ; increment counter - } - rxp = cmcontinue="(.*?)" ; set regular expression - If RegExMatch(data, rxp, next) ; when found - { - doContinue = &cmcontinue=%next1% ; set continuation string to add to url - Goto getFile ; go to function-internal subroutine to redownload and parse - } - StringTrimRight, allTitles, allTitles, 1 ; remove last delimiter from result - Return allTitles ; return result -} - -; function to convert html entities to ansi equivalents -Dec_XML(str) -{ - Loop - If RegexMatch(str, "S)(&#(\d+);)", dec) - StringReplace, str, str, %dec1%, % Chr(dec2), All - Else If RegexMatch(str, "Si)(&#x([\da-f]+);)", hex) - StringReplace, str, str, %hex1%, % Chr("0x" . hex2), All - Else - Break - StringReplace, str, str,  , %A_Space%, All - StringReplace, str, str, ", ", All - StringReplace, str, str, ', ', All - StringReplace, str, str, <, <, All - StringReplace, str, str, >, >, All - StringReplace, str, str, &, &, All - return, str -} - -; function to uri-encode input string -Enc_Uri(str) -{ - f = %A_FormatInteger% - SetFormat, Integer, Hex - If RegExMatch(str, "^\w+:/{0,2}", pr) - StringTrimLeft, str, str, StrLen(pr) - StringReplace, str, str, `%, `%25, All - Loop - If RegExMatch(str, "i)[^\w\.~%/:]", char) - StringReplace, str, str, %char%, % "%" . SubStr(Asc(char),3), All - Else Break - SetFormat, Integer, %f% - Return, pr . str -} - -; function to convert unicode to ansi text -UTF82Ansi(zString) -{ - Ansi2Unicode(zString, wString, 65001) - Unicode2Ansi(wString, sString, 0) - Return sString -} - -; helper function for unicode to ansi function -Ansi2Unicode(ByRef sString, ByRef wString, CP = 0) -{ - nSize := DllCall("MultiByteToWideChar", "Uint", CP - , "Uint", 0, "Uint", &sString, "int", -1 - , "Uint", 0, "int", 0) - VarSetCapacity(wString, nSize * 2) - DllCall("MultiByteToWideChar" - , "Uint", CP, "Uint", 0, "Uint", &sString, "int", -1 - , "Uint", &wString, "int", nSize) -} - -; helper function for unicode to ansi function -Unicode2Ansi(ByRef wString, ByRef sString, CP = 0) -{ - nSize := DllCall("WideCharToMultiByte" - , "Uint", CP, "Uint", 0, "Uint", &wString, "int", -1 - , "Uint", 0, "int", 0, "Uint", 0, "Uint", 0) - VarSetCapacity(sString, nSize) - DllCall("WideCharToMultiByte" - , "Uint", CP, "Uint", 0, "Uint", &wString, "int", -1 - , "str", sString, "int", nSize, "Uint", 0, "Uint", 0) -} - -; subroutine called when user closes the gui -GuiClose: - ExitApp ; exit the script -Return diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Erlang/rosetta-code-find-unimplemented-tasks.erl b/Task/Rosetta-Code-Find-unimplemented-tasks/Erlang/rosetta-code-find-unimplemented-tasks.erl deleted file mode 100644 index a7cd602ed0..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Erlang/rosetta-code-find-unimplemented-tasks.erl +++ /dev/null @@ -1,43 +0,0 @@ --module( find_unimplemented_tasks ). --include_lib( "xmerl/include/xmerl.hrl" ). - --export( [init_http/0, per_language/1, rosetta_code_list_of/1] ). - -init_http() -> - application:start( inets ). - -per_language( Language ) -> - ok = init_http(), - Tasks = rosetta_code_list_of( "Programming_Tasks" ), - Uninplemented = Tasks -- rosetta_code_list_of( Language ), - io:fwrite( "Unimplemented total: ~p~n", [erlang:length(Uninplemented)] ), - [io:fwrite("~p~n", [X]) || X <- Uninplemented]. - -rosetta_code_list_of( Category ) -> - URL = "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmlimit=500&format=xml&cmtitle=Category:" - ++ Category, - title_contents( URL, "", [] ). - - - -title_contents( URL, Continue, Acc ) -> - {ok, {{_HTTP,200,"OK"}, _Headers, Body}} = httpc:request( URL ++ Continue ), - {XML, _} = xmerl_scan:string( Body ), - News = xml_selection( "title", XML ), - New_continue = title_contents_url_continue( xml_selection("cmcontinue", XML) ), - title_contents_continue( URL, New_continue, Acc ++ News ). - -title_contents_continue( _URL, "", Acc ) -> Acc; -title_contents_continue( URL, Continue, Acc ) -> title_contents( URL, Continue, Acc ). - -title_contents_url_continue( [] ) -> ""; -title_contents_url_continue( [Continue | _] ) -> "&cmcontinue=" ++ Continue. - -xml_selection( Selection, XML ) -> - [lists:map( fun xml_8211/1, X) || #xmlAttribute{value=X} <- xmerl_xpath:string("//@" ++ Selection, XML)]. - -xml_8211( 8211 ) -> $-; -xml_8211( 924 ) -> $\s; -xml_8211( 1050 ) -> $\s; -xml_8211( 1052 ) -> $\s; -xml_8211( Character ) -> Character. diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Go/rosetta-code-find-unimplemented-tasks.go b/Task/Rosetta-Code-Find-unimplemented-tasks/Go/rosetta-code-find-unimplemented-tasks.go deleted file mode 100644 index 9740a04683..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Go/rosetta-code-find-unimplemented-tasks.go +++ /dev/null @@ -1,74 +0,0 @@ -package main - -import ( - "encoding/xml" - "fmt" - "io" - "net/http" - "net/url" -) - -const language = "Go" - -var baseQuery = "http://rosettacode.org/mw/api.php?action=query" + - "&format=xml&list=categorymembers&cmlimit=100" - -func req(u string, foundCm func(string)) string { - resp, err := http.Get(u) - if err != nil { - fmt.Println(err) // connection or request fail - return "" - } - defer resp.Body.Close() - for p := xml.NewDecoder(resp.Body); ; { - t, err := p.RawToken() - switch s, ok := t.(xml.StartElement); { - case err == io.EOF: - return "" - case err != nil: - fmt.Println(err) - return "" - case !ok: - continue - case s.Name.Local == "cm": - for _, a := range s.Attr { - if a.Name.Local == "title" { - foundCm(a.Value) - } - } - case s.Name.Local == "categorymembers" && len(s.Attr) > 0 && - s.Attr[0].Name.Local == "cmcontinue": - return url.QueryEscape(s.Attr[0].Value) - } - } - return "" -} - -func main() { - // get language members, store in a map - langMap := make(map[string]bool) - storeLang := func(cm string) { langMap[cm] = true } - languageQuery := baseQuery + "&cmtitle=Category:" + language - continueAt := req(languageQuery, storeLang) - for continueAt > "" { - continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang) - } - - // a quick check to avoid long output - if len(langMap) == 0 { - fmt.Println("no tasks implemented for", language) - return - } - - // get tasks, print as we go along - printUnImp := func(cm string) { - if !langMap[cm] { - fmt.Println(cm) - } - } - taskQuery := baseQuery + "&cmtitle=Category:Programming_Tasks" - continueAt = req(taskQuery, printUnImp) - for continueAt > "" { - continueAt = req(taskQuery+"&cmcontinue="+continueAt, printUnImp) - } -} diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Haskell/rosetta-code-find-unimplemented-tasks.hs b/Task/Rosetta-Code-Find-unimplemented-tasks/Haskell/rosetta-code-find-unimplemented-tasks.hs deleted file mode 100644 index 83c6b67b20..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Haskell/rosetta-code-find-unimplemented-tasks.hs +++ /dev/null @@ -1,27 +0,0 @@ -import Network.Browser -import Network.HTTP -import Network.URI -import Data.List -import Data.Maybe -import Text.XML.Light -import Control.Arrow -import Data.Char - -getRespons url = do - rsp <- Network.Browser.browse $ do - setAllowRedirects True - setOutHandler $ const (return ()) -- quiet - request $ getRequest url - return $ rspBody $ snd rsp - -replaceWithSpace c = (\x -> if c==x then ' ' else x) - -encl = chr 34 - -unimpTasks lang = do - allTasks <- getRespons "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" - impl <- getRespons ( "http://rosettacode.org/json/isb/" ++ lang ++ ".json") - let langxx = map (map(replaceWithSpace '_')) $ filter (/=",") $ words $ map (replaceWithSpace encl ) $ init $ drop 1 impl - xml = onlyElems $ parseXML allTasks - allxx = concatMap (map (fromJust.findAttr (unqual "title")). filterElementsName (== unqual "cm")) xml - mapM_ putStrLn $ sort $ allxx \\ langxx diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Icon/rosetta-code-find-unimplemented-tasks.icon b/Task/Rosetta-Code-Find-unimplemented-tasks/Icon/rosetta-code-find-unimplemented-tasks.icon deleted file mode 100644 index 77efafa3c1..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Icon/rosetta-code-find-unimplemented-tasks.icon +++ /dev/null @@ -1,77 +0,0 @@ -$define RCINDEX "http://rosettacode.org/mw/api.php?format=xml&action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500" -$define RCTASK "http://rosettacode.org/mw/index.php?action=raw&title=" -$define RCUA "User-Agent: Unicon Rosetta 0.1" -$define RCXUA "X-Unicon: http://unicon.org/" -$define TASKTOT "* Total Tasks *" -$define TOTTOT "* Total Headers*" - -link strings -link hexcvt - -procedure main(A) # simple single threaded read all at once implementation - lang := \A[1] | "Unicon" - write("Unimplemented tasks for ",lang," as of ",&date) - every task := taskNames() do { - if lang == languages(task) then next - write(task) - } -end - -# Generate task names -procedure taskNames() - continue := "" - while \(txt := ReadURL(RCINDEX||continue)) do { - txt ? { - while tab(find("'\""),3,"0")||";",c) - } - - dxml[1] := u # insert URI as 1st arg - u := replacem!dxml # de-xml it - every (c := "") ||:= tr[!u] # reencode everything - c := replace(c,"%3E","'") # Hack to put single quotes back in - c := replace(c,"%26quot%3B","\"") # Hack to put double quotes back in - return c -end - -procedure ReadURL(url) #: read URL into string - page := open(url,"m",RCUA,RCXUA) | stop("Unable to open ",url) - text := "" - if page["Status-Code"] < 300 then while text ||:= reads(page,-1) - else write(&errout,image(url),": ", - page["Status-Code"]," ",page["Reason-Phrase"]) - close(page) - return text -end diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/J/rosetta-code-find-unimplemented-tasks-1.j b/Task/Rosetta-Code-Find-unimplemented-tasks/J/rosetta-code-find-unimplemented-tasks-1.j deleted file mode 100644 index ed568389c8..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/J/rosetta-code-find-unimplemented-tasks-1.j +++ /dev/null @@ -1,25 +0,0 @@ -require 'strings web/gethttp' - -findUnimpTasks=: ('Programming_Tasks' -.&getCategoryMembers ,&'/Omit') ([ #~ -.@e.) getCategoryMembers - -getTagContents=: dyad define - 'starttag endtag'=. x - ('\' -.~ endtag&taketo)&.>@(starttag&E. <@((#starttag)&}.);.1 ]) y -) - -NB. RosettaCode Utilities -parseTitles=: ('"title":"';'"')&getTagContents -parseCMcontinue=:('"cmcontinue":"';'"')&getTagContents -getCMcontquery=: ('&cmcontinue=' , urlencode)^:(0 < #)@>@parseCMcontinue - -getCategoryMembers=: monad define - buildqry=. 'action=query&list=categorymembers&cmtitle=Category:' , ,&'&cmlimit=500&format=json' - url=.'http://www.rosettacode.org/w/api.php' - uri=. url ,'?', buildqry urlencode y - catmbrs=. qrycont=. '' - whilst. #qrycont=. getCMcontquery jsondat do. - jsondat=. gethttp uri , qrycont - catmbrs=. catmbrs, parseTitles jsondat - end. - catmbrs -) diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/J/rosetta-code-find-unimplemented-tasks-2.j b/Task/Rosetta-Code-Find-unimplemented-tasks/J/rosetta-code-find-unimplemented-tasks-2.j deleted file mode 100644 index 212cf5c5c7..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/J/rosetta-code-find-unimplemented-tasks-2.j +++ /dev/null @@ -1,4 +0,0 @@ - 4{. findUnimpTasks 'J' NB. get first 4 unimplemented tasks for J -+-------------+--------------+----------------+------------------------------+ -|Active object|Atomic updates|Basic input loop|Call foreign language function| -+-------------+--------------+----------------+------------------------------+ diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica/rosetta-code-find-unimplemented-tasks-1.math b/Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica/rosetta-code-find-unimplemented-tasks-1.math deleted file mode 100644 index ec82be3fcf..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica/rosetta-code-find-unimplemented-tasks-1.math +++ /dev/null @@ -1,21 +0,0 @@ -ClearAll[ImportAll] -ImportAll[lang_String] := - Module[{data, continue, cmcontinue, extra, xml, next}, - data = {}; - continue = True; - cmcontinue = ""; - While[continue, - extra = If[cmcontinue =!= "", "&cmcontinue=" <> cmcontinue, ""]; - xml = Import["http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:" <> lang <> "&cmlimit=500&format=xml" <> extra, "XML"]; - AppendTo[data, Cases[xml, XMLElement["cm", _, {}], \[Infinity]]]; - next = Flatten[Cases[xml, {"cmcontinue" -> _}, \[Infinity]]]; - If[Length[next] > 0, - next = First[next]; - cmcontinue = "cmcontinue" /. next; - , - continue = False; - ]; - ]; - Cases[Flatten[data], HoldPattern["title" -> x_] :> x, \[Infinity]] - ] -Complement[ImportAll["Programming_Tasks"], ImportAll["Mathematica"]] diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica/rosetta-code-find-unimplemented-tasks-2.math b/Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica/rosetta-code-find-unimplemented-tasks-2.math deleted file mode 100644 index eb66f82ff9..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica/rosetta-code-find-unimplemented-tasks-2.math +++ /dev/null @@ -1,13 +0,0 @@ -url = "http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_Mathematica"; -html = Import[url, "XMLObject"]; -pos = Position[html, XMLElement["div", {"class" -> "mw-content-ltr", "dir" -> "ltr", "lang" -> "en"}, ___]]; -pos = First[pos]; -data = Extract[html, pos]; -pos = Position[data, XMLElement["li", {}, {XMLElement["a", {"shape" -> "rect", "href" -> _, "title" -> x_}, {x_}]}]]; -data = Extract[data, pos]; -data = data[[All, -1, -1, 2]]; -data = {"title", "href"} /. # & /@ %; -data[[All, 2]] = "http://rosettacode.org" <> # & /@ data[[All, 2]]; -newb = data[[All, 1]]; -data = Hyperlink @@@ data; -data // Column diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Oz/rosetta-code-find-unimplemented-tasks.oz b/Task/Rosetta-Code-Find-unimplemented-tasks/Oz/rosetta-code-find-unimplemented-tasks.oz deleted file mode 100644 index 976efd5cbe..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Oz/rosetta-code-find-unimplemented-tasks.oz +++ /dev/null @@ -1,127 +0,0 @@ -declare - [HTTPClient] = {Link ['x-ozlib://mesaros/net/HTTPClient.ozf']} - [XMLParser] = {Link ['x-oz://system/xml/Parser.ozf']} - - fun {FindUnimplementedTasks Language} - AllTasks = {FindCategory "Programming Tasks"} - LangTasks = {FindCategory Language} - in - {ListDiff AllTasks LangTasks} - end - - fun {FindCategory Cat} - CatUrl = "http://www.rosettacode.org/mw/api.php?action=query" - #"&list=categorymembers" - #"&cmtitle=Category:"#{PercentEncode Cat} - #"&cmlimit=500&format=xml" - - fun {Loop CMContinue} - [_ Doc] = {Parse {GetPage CatUrl#CMContinue}} - Titles = {XPath Doc - [api query categorymembers cm {Attribute title}]} - in - case {XPath Doc - [api 'query-continue' categorymembers {Attribute cmcontinue}]} - of nil then Titles - [] [NewCMContinueAtom] then - NewCMContinue = {PercentEncode {Atom.toString NewCMContinueAtom}} - in - {Append Titles - {Loop "&cmcontinue="#NewCMContinue}} - end - end - in - {Loop nil} - end - - - %% XPath emulation - fun {XPath Doc Path} - P|Pr = Path - in - Doc.name = P %% assert - {FoldL Pr XPathStep [Doc]} - end - - Nothing = {NewName} - fun {NotNothing X} X \= Nothing end - - fun {XPathStep Elements P} - if {Atom.is P} then - {FilteredChildren Elements P} - elseif {Procedure.is P} then - {Filter {Map Elements P} NotNothing} - end - end - - %% A flat list of all Type-children of all Elements. - fun {FilteredChildren Elements Type} - {Flatten - {Map Elements - fun {$ E} - {Filter E.children - fun {$ X} - case X of element(name:!Type ...) then true - else false - end - end} - end}} - end - - fun {Attribute Attr} - fun {$ Element} - case {Filter Element.attributes fun {$ A} A.name == Attr end} - of [A] then A.value - else Nothing - end - end - end - - - %% GetPage - Client = {New HTTPClient.urlGET init(inPrms(toFile:false toStrm:true) _)} - fun {GetPage RawUrl} - Url = {VirtualString.toString RawUrl} - OutParams - in - {Client getService(Url ?OutParams ?_)} - OutParams.sOut - end - - fun {PercentEncode Xs} - case Xs of nil then nil - [] X|Xr then - if {Char.isDigit X} orelse {Member X [&- &_ &. &~]} - orelse X >= &a andthen X =< &z - orelse X >= &z andthen X =< &Z then - X|{PercentEncode Xr} - else - {Append &%|{ToHex2 X} {PercentEncode Xr}} - end - end - end - - fun {ToHex2 X} - [{ToHex1 X div 16} {ToHex1 X mod 16}] - end - - fun {ToHex1 X} - if X >= 0 andthen X =< 9 then &0 + X - elseif X >= 10 andthen X =< 15 then &A + X - 10 - end - end - - - %% Parse - local - Parser = {New XMLParser.parser init} - in - fun {Parse Xs} {Parser parseVS(Xs $)} end - end - - fun {ListDiff Xs Ys} - {FoldL Ys List.subtract Xs} - end -in - %% show tasks not implemented in Oz - {ForAll {FindUnimplementedTasks "Oz"} System.showInfo} diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Perl-6/rosetta-code-find-unimplemented-tasks.pl6 b/Task/Rosetta-Code-Find-unimplemented-tasks/Perl-6/rosetta-code-find-unimplemented-tasks.pl6 deleted file mode 100644 index ba4bcf7704..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Perl-6/rosetta-code-find-unimplemented-tasks.pl6 +++ /dev/null @@ -1,39 +0,0 @@ -use JSON::Tiny; -sub MAIN ( Str $language = 'Perl_6' ) { - my @done_tasks = set tasks($language); - my @all_tasks = set tasks('Programming_Tasks'); - .say for @all_tasks (-) @done_tasks; -} - -sub url_of ( Str $category, Str $continue? ) { - my $cat = $category.subst( /<-[ A..Z a..z 0..9 . ~ _ - ]>/, - *.ord.fmt('%%%02X'), :g ); - - return 'http://rosettacode.org/mw/api.php?action=query&cmlimit=500' - ~ "&format=json&list=categorymembers&cmtitle=Category:$cat" - ~ ("&cmcontinue=$continue" if $continue); -} - -sub get_mirrored_page ( Str $url, Str $filename ) { - if $filename.IO !~~ :e or (now - $filename.IO.modified) > 3600 { - run('curl', '-sSo', $filename, $url) or die; - } - return slurp $filename; -} - -sub tasks ( Str $category ) { - my $continue = ''; - my @tasks = gather for 1..* -> $page_num { - my $href = from-json get_mirrored_page( - url_of( $category, $continue ), - "{$category}_{$page_num}.json", - ); - - take map *., $href.<query>.<categorymembers>.list; - - $continue = $href.<query-continue>.<categorymembers>.<cmcontinue> - or last; - } or die "Nothing found for category '$category'"; - - return @tasks; -} diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Perl/rosetta-code-find-unimplemented-tasks.pl b/Task/Rosetta-Code-Find-unimplemented-tasks/Perl/rosetta-code-find-unimplemented-tasks.pl deleted file mode 100644 index 8ae140bd22..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Perl/rosetta-code-find-unimplemented-tasks.pl +++ /dev/null @@ -1,24 +0,0 @@ -use LWP::Simple 'get'; - -my $fmt = 'http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:%s&cmlimit=500&format=json'; -my $lang = shift - or die "No language given.\n"; - -sub urlencode - {join '', map {sprintf '%%%02x', ord} split //, shift} -sub tasks - {my $category = urlencode shift; - my @tasks; - my $json = get sprintf $fmt, $category; - for (;;) - {push @tasks, $json =~ /"title":"(.+?)"}/g; - $json =~ /"cmcontinue":"(.+?)"}/ or last; - $json = get sprintf $fmt . '&cmcontinue=%s', - $category, urlencode $1;} - return @tasks;} - -my @all = tasks 'Programming_Tasks'; -my %lang = map {$_, 1} tasks $lang - or die "No such category.\n"; -$lang{$_} or print "$_\n" - foreach @all; diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/PicoLisp/rosetta-code-find-unimplemented-tasks-1.l b/Task/Rosetta-Code-Find-unimplemented-tasks/PicoLisp/rosetta-code-find-unimplemented-tasks-1.l deleted file mode 100644 index 979737798a..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/PicoLisp/rosetta-code-find-unimplemented-tasks-1.l +++ /dev/null @@ -1,24 +0,0 @@ -(load "@lib/http.l" "@lib/xm.l") - -(de rosettaCategory (Cat) - (let (Cont NIL Xml) - (make - (loop - (client "rosettacode.org" 80 - (pack - "mw/api.php?action=query&list=categorymembers&cmtitle=Category:" - Cat - "&cmlimit=200&format=xml" - Cont ) - (while (line)) - (setq Xml (and (xml?) (xml))) ) - (NIL Xml) - (for M (body Xml 'query 'categorymembers) - (link (attr M 'title)) ) - (NIL (attr Xml 'query-continue' categorymembers 'cmcontinue)) - (setq Cont (pack "&cmcontinue=" @)) ) ) ) ) - -(de unimplemented (Task) - (diff - (rosettaCategory "Programming_Tasks") - (rosettaCategory Task) ) ) diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/PicoLisp/rosetta-code-find-unimplemented-tasks-2.l b/Task/Rosetta-Code-Find-unimplemented-tasks/PicoLisp/rosetta-code-find-unimplemented-tasks-2.l deleted file mode 100644 index 54710cf6fa..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/PicoLisp/rosetta-code-find-unimplemented-tasks-2.l +++ /dev/null @@ -1,26 +0,0 @@ -import xml.dom.minidom -import urllib, sys - -def findrc(category): - name = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:%s&cmlimit=500&format=xml" % urllib.quote(category) - cmcontinue, titles = '', [] - while True: - u = urllib.urlopen(name + cmcontinue) - xmldata = u.read() - u.close() - x = xml.dom.minidom.parseString(xmldata) - titles += [i.getAttribute("title") for i in x.getElementsByTagName("cm")] - cmcontinue = filter( None, - (urllib.quote(i.getAttribute("cmcontinue")) - for i in x.getElementsByTagName("categorymembers")) ) - if cmcontinue: - cmcontinue = '&cmcontinue=' + cmcontinue[0] - else: - break - return titles - -alltasks = findrc("Programming_Tasks") -lang = findrc(sys.argv[1]) - -for i in [i for i in alltasks if i not in lang]: - print i diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/R/rosetta-code-find-unimplemented-tasks.r b/Task/Rosetta-Code-Find-unimplemented-tasks/R/rosetta-code-find-unimplemented-tasks.r deleted file mode 100644 index 4ae8289f15..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/R/rosetta-code-find-unimplemented-tasks.r +++ /dev/null @@ -1,16 +0,0 @@ -library(XML) -find.unimplemented.tasks <- function(lang="R"){ - PT <- xmlInternalTreeParse( paste("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml",sep="") ) - PT.nodes <- getNodeSet(PT,"//cm") - PT.titles = as.character( sapply(PT.nodes, xmlGetAttr, "title") ) - language <- xmlInternalTreeParse( paste("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:", - lang, "&cmlimit=500&format=xml",sep="") ) - lang.nodes <- getNodeSet(language,"//cm") - lang.titles = as.character( sapply(lang.nodes, xmlGetAttr, "title") ) - unimplemented <- setdiff(PT.titles, lang.titles) - unimplemented -} -# Usage -find.unimplemented.tasks(lang="Python") -langs <- c("R","python","perl") -sapply(langs, find.unimplemented.tasks) # fetching data for multiple languages diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/README b/Task/Rosetta-Code-Find-unimplemented-tasks/README deleted file mode 100644 index 1909bd4db9..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/README +++ /dev/null @@ -1 +0,0 @@ -Data source: http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Racket/rosetta-code-find-unimplemented-tasks.rkt b/Task/Rosetta-Code-Find-unimplemented-tasks/Racket/rosetta-code-find-unimplemented-tasks.rkt deleted file mode 100644 index 1cdbfabc4c..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Racket/rosetta-code-find-unimplemented-tasks.rkt +++ /dev/null @@ -1,27 +0,0 @@ -#lang racket - -(require net/url net/uri-codec json (only-in racket/dict [dict-ref ref])) - -(define (RC-get verb params) - ((compose1 get-pure-port string->url format) - "http://rosettacode.org/mw/~a.php?~a" verb (alist->form-urlencoded params))) - -(define (get-category catname) - (let loop ([c #f]) - (define t - ((compose1 read-json RC-get) 'api - `([action . "query"] [format . "json"] - [list . "categorymembers"] [cmtitle . ,(format "Category:~a" catname)] - [cmcontinue . ,(and c (ref c 'cmcontinue))] [cmlimit . "500"]))) - (define (c-m key) (ref (ref t key '()) 'categorymembers #f)) - (append (for/list ([page (c-m 'query)]) (ref page 'title)) - (cond [(c-m 'query-continue) => loop] [else '()])))) - -;; The above is the required "library" code, same as the "Rosetta -;; Code/Count" entry - -(define (show-unimplemented lang) - (for-each displayln (remove* (get-category lang) - (get-category 'Programming_Tasks)))) - -(show-unimplemented 'Racket) ; see all of the Racket entries diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Ruby/rosetta-code-find-unimplemented-tasks.rb b/Task/Rosetta-Code-Find-unimplemented-tasks/Ruby/rosetta-code-find-unimplemented-tasks.rb deleted file mode 100644 index 373909a2f0..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Ruby/rosetta-code-find-unimplemented-tasks.rb +++ /dev/null @@ -1,46 +0,0 @@ -require 'rosettacode' -require 'time' - -module RosettaCode - def self.get_unimplemented(lang) - programming_tasks = [] - category_members("Programming_Tasks") {|task| programming_tasks << task} - - lang_tasks = [] - category_members(lang) {|task| lang_tasks << task} - - lang_tasks_omit = [] - category_members("#{lang}/Omit") {|task| lang_tasks_omit << task} - - [programming_tasks - lang_tasks, lang_tasks_omit] - end - - def self.created_time(title) - url = get_api_url({ - "action" => "query", - "titles" => title, - "format" => "xml", - "rvlimit" => 500, - "prop" => "revisions", - "rvprop" => "timestamp" - }) - doc = REXML::Document.new open(url) - REXML::XPath.each(doc, "//rev").collect do |node| - Time.parse( node.attribute("timestamp").value ) - end.min - end - -end - -puts Time.now -lang = ARGV[0] || "Ruby" -unimplemented, omitted = RosettaCode.get_unimplemented(lang) -unimplemented.collect {|title| [title, RosettaCode.created_time(title)]} . - sort_by {|e| e[1]} . - each do |title, date| - puts "%s %6s %s" % [ - date.strftime("%Y-%m-%d"), - omitted.include?(title) ? "[omit]" : "" , - title - ] - end diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Run-BASIC/rosetta-code-find-unimplemented-tasks.run b/Task/Rosetta-Code-Find-unimplemented-tasks/Run-BASIC/rosetta-code-find-unimplemented-tasks.run deleted file mode 100644 index 0e5311174c..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Run-BASIC/rosetta-code-find-unimplemented-tasks.run +++ /dev/null @@ -1,43 +0,0 @@ -WordWrap$ = "style='white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word'" -a$ = httpGet$("http://rosettacode.org/wiki/Category:Programming_Languages") -a$ = word$(a$,2,"mw-subcategories") -a$ = word$(a$,1,"</table>") -i = instr(a$,"/wiki/Category:") -html "<B> Select language from list<BR>" -html "<SELECT name='lang'>" -while i <> 0 - j = instr(a$,""" title=""Category:",i) - lang$ = mid$(a$,i+15,j-i-15) - k = instr(a$,""">",j + 18) - langName$ = mid$(a$,j + 18,k-(j+18)) - count = count + 1 - html "<option value='";lang$;"'>";langName$;"</option>" - i = instr(a$,"/wiki/Category:",k) -wend -html "</select>" -html "<p>Number of Languages:";count;"<BR> " -button #go,"GO", [go] -html " " -button #ex, "Exit", [exit] -wait - -[go] -cls -lang$ = #request get$("lang") -h$ = "http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_";lang$ -a$ = httpGet$(h$) -a$ = word$(a$,3,"mw-content-ltr") -html "<table border=1><tr>" -i = instr(a$,"<a href=""/wiki/") -while i > 0 - i = instr(a$,"title=""",i) - j = instr(a$,""">",i+7) - if c mod 4 = 0 then html "</tr><tr ";WordWrap$;">" - c = c + 1 - html "<td>";mid$(a$,i+7,j-(i+7));"</td>" - i = instr(a$,"<a href=""/wiki/",i+7) -wend -html "</tr></table>" -print "Total unImplemented Tasks:";c -[exit] -end diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Tcl/rosetta-code-find-unimplemented-tasks.tcl b/Task/Rosetta-Code-Find-unimplemented-tasks/Tcl/rosetta-code-find-unimplemented-tasks.tcl deleted file mode 100644 index 1a0c6cfe3c..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Tcl/rosetta-code-find-unimplemented-tasks.tcl +++ /dev/null @@ -1,97 +0,0 @@ -package require Tcl 8.5 -package require http -package require json -package require struct::set - -fconfigure stdout -buffering none - -# Initialize a cache of lookups -array set cache {} -proc log msg { - #puts -nonewline $msg -} - -proc get_tasks {category} { - global cache - if {[info exists cache($category)]} { - return $cache($category) - } - set base_url http://www.rosettacode.org/w/api.php - set query { - action query - list categorymembers - cmtitle Category:%s - format json - cmlimit 500 - } - set query [list {*}$query]; # remove excess whitespace - set this_query [dict create {*}[split [format $query $category]]] - set tasks [list] - - while {1} { - set url [join [list $base_url [http::formatQuery {*}$this_query]] ?] - while 1 { - set response [http::geturl $url] - # Process redirects - if {[http::ncode $response] == 301} { - set newurl [dict get [http::meta $response] Location] - if {[string match http://* $newurl]} { - set url $newurl - } else { - set url [regexp -inline {http://[^/]+} $url] - append url $newurl - } - continue - } - # Check for oopsies! - if { - [set s [http::status $response]] ne "ok" - || [http::ncode $response] != 200 - } then { - error "Oops: url=$url\nstatus=$s\nhttp code=[http::code $response]" - } - break - } - - # Get the data out of the message - set data [json::json2dict [http::data $response]] - http::cleanup $response - - # add tasks to list - foreach task [dict get $data query categorymembers] { - lappend tasks [dict get [dict create {*}$task] title] - } - - if {[catch { - dict get $data query-continue categorymembers cmcontinue - } continue_task]} then { - # no more continuations, we're done - break - } - dict set this_query cmcontinue $continue_task - } - return [set cache($category) $tasks] -} - -proc get_unimplemented {lang} { - set tasks [get_tasks Programming_Tasks] - set collected [get_tasks Collection_Members] - set doneTasks [get_tasks $lang] - set omittedTasks [get_tasks $lang/Omit] - - # Map generic collection task categories to specific ones - set tasks [regsub -all {Category:(\S+)} $tasks "\\1/$lang"] - - set collectOfLang [struct::set intersect $collected $doneTasks] - set ignorable [struct::set union $doneTasks $omittedTasks $collectOfLang] - set unimplemented [struct::set difference $tasks $ignorable] - - puts "\n$lang has [llength $unimplemented] unimplemented programming tasks:" - if {[llength $unimplemented]} { - puts " [join [lsort $unimplemented] "\n "]" - } -} - -foreach lang {Perl Python Ruby Tcl} { - get_unimplemented $lang -} diff --git a/Task/Rosetta-Code-Fix-code-tags/00DESCRIPTION b/Task/Rosetta-Code-Fix-code-tags/00DESCRIPTION deleted file mode 100644 index 7fe1727e83..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/00DESCRIPTION +++ /dev/null @@ -1,10 +0,0 @@ -Fix Rosetta Code deprecated code tags, with these rules: - -<pre>Change <%s> to <lang %s> -Change </%s> to </lang> -Change <code %s> to <lang %s> -Change </code> to </lang></pre> - -Usage: - -<pre>./convert.py < wikisource.txt > converted.txt</pre> diff --git a/Task/Rosetta-Code-Fix-code-tags/00META.yaml b/Task/Rosetta-Code-Fix-code-tags/00META.yaml deleted file mode 100644 index 79419892a3..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/00META.yaml +++ /dev/null @@ -1,4 +0,0 @@ ---- -category: -- Rosetta Code related -note: Text processing diff --git a/Task/Rosetta-Code-Fix-code-tags/AutoHotkey/rosetta-code-fix-code-tags.ahk b/Task/Rosetta-Code-Fix-code-tags/AutoHotkey/rosetta-code-fix-code-tags.ahk deleted file mode 100644 index d4c533fa74..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/AutoHotkey/rosetta-code-fix-code-tags.ahk +++ /dev/null @@ -1,15 +0,0 @@ -; usage: > fixtags.ahk input.txt ouput.txt -FileRead, text, %1% -langs = ada,awk,autohotkey,etc -slang = /lang -slang := "<" . slang . "/>" -Loop, Parse, langs, `, -{ - tag1 = <%A_LoopField%> - tag2 = </%A_LoopField%> - text := RegExReplace(text, tag1, "<lang " . A_LoopField . ">") - text := RegExReplace(text, tag2, slang) - text := RegExReplace(text, "<code (.+?)>(.*?)</code>" - , "<lang $1>$2" . slang) -} -FileAppend, % text, %2% diff --git a/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-1.d b/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-1.d deleted file mode 100644 index 3ccae7f35a..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-1.d +++ /dev/null @@ -1,40 +0,0 @@ -import std.stdio, std.regex, std.string, std.array; - -immutable langs = "_div abap actionscript actionscript3 ada apache -applescript apt_sources asm asp autoit avisynth bash basic4gl bf -blitzbasic bnf boo c c_mac caddcl cadlisp cfdg cfm cil cobol cpp -cpp-qt csharp css d delphi diff dos dot eiffel email fortran -freebasic genero gettext glsl gml gnuplot groovy haskell hq9plus -html4strict idl ini inno intercal io java java5 javascript kixtart -klonec klonecpp latex lisp lolcode lotusformulas lotusscript -lscript lua m68k make matlab mirc modula3 mpasm mxml mysql nsis -objc ocaml ocaml-brief oobas oracle11 oracle8 pascal per perl php -php-brief pic16 pixelbender plsql povray powershell progress -prolog providex python qbasic rails reg robots ruby sas scala -scheme scilab sdlbasic smalltalk smarty sql tcl teraterm text -thinbasic tsql typoscript vb vbnet verilog vhdl vim visualfoxpro -visualprolog whitespace winbatch xml xorg_conf xpp z80".split; - -string fixTags(string text) { - static immutable slang = "/lang"; - static immutable code = "code"; - - foreach (immutable lang; langs) { - text = text.replace("<%s>".format(lang), - "<lang %s>".format(lang)); - text = text.replace("</%s>".format(lang), - "<%s>".format(slang)); - } - - return text.replace("<%s (.+?)>(.*?)</%s>" - .format(code, code).regex("g"), - "<lang $1>$2<%s>".format(slang)); -} - -void main() { - ("lorem ipsum <c>some c code</c>dolor sit amet, <csharp>some " ~ - "csharp code</csharp> consectetur adipisicing elit, <code r>" ~ - " some r code </code>sed do eiusmod tempor incididunt") - .fixTags - .writeln; -} diff --git a/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-2.d b/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-2.d deleted file mode 100644 index 91f9ad9045..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-2.d +++ /dev/null @@ -1 +0,0 @@ -some c code diff --git a/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-3.d b/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-3.d deleted file mode 100644 index cde535ef43..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-3.d +++ /dev/null @@ -1 +0,0 @@ -some csharp code diff --git a/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-4.d b/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-4.d deleted file mode 100644 index eaddfd85bb..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-4.d +++ /dev/null @@ -1 +0,0 @@ - some r code diff --git a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-1.erl b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-1.erl deleted file mode 100644 index 4c5f5f93cd..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-1.erl +++ /dev/null @@ -1,38 +0,0 @@ -#! /usr/bin/env escript --module( fix_code_tags ). --mode( compile ). - -main( _ ) -> - File_lines = loop( io:get_line(""), [] ), - Code_fixed_lines = fix_code_tag( binary:list_to_bin(File_lines) ), -% true = code:add_pathz( "ebin" ), -% ok = find_unimplemented_tasks:init(), -% Dict = dict:from_list( [dict_tuple(X) || X <- rank_languages_by_popularity:rosettacode_languages()], - Dict = dict:from_list( [dict_tuple(X) || X <- ["foo", "bar", "baz"]] ), - {_Dict, All_fixed_lines} = lists:foldl( fun fix_language_tag/2, {Dict, Code_fixed_lines}, dict:fetch_keys(Dict) ), - io:fwrite( "~s", [binary:bin_to_list(All_fixed_lines)] ). - - - -dict_tuple( Language ) -> {binary:list_to_bin(string:to_lower(Language)), binary:list_to_bin(Language)}. - -fix_code_tag( Binary ) -> - Avoid_wiki = binary:list_to_bin( [<<"<">>, <<"lang ">>] ), - Code_fixed_lines = binary:replace( Binary, <<"<code ">>, Avoid_wiki, [global] ), - Avoid_wiki_again = binary:list_to_bin( [<<"</">>, <<"lang ">>] ), - binary:replace( Code_fixed_lines, <<"</code>">>, Avoid_wiki_again, [global] ). - -fix_language_tag( Language_key, {Dict, Binary} ) -> - Language = fix_language_tag_rosettacode_language( Language_key, dict:find(Language_key, Dict) ), - Language_start_old = binary:list_to_bin( [<<"<">>, Language, <<">">>] ), - Language_start_new = binary:list_to_bin( [<<"<">>, <<"lang ">>, Language, <<">">>] ), - Fixed_lines = binary:replace( Binary, Language_start_old, Language_start_new, [global] ), - Language_stop_old = binary:list_to_bin( [<<"</">>, Language, <<">">>] ), - Language_stop_new = binary:list_to_bin( [<<"</">>, <<"lang>">>] ), - {Dict, binary:replace( Fixed_lines, Language_stop_old, Language_stop_new, [global] )}. - -fix_language_tag_rosettacode_language( _Language_key, {ok, Language} ) -> Language; -fix_language_tag_rosettacode_language( Language_key, error ) -> Language_key. - -loop( eof, Acc ) -> lists:reverse( Acc ); -loop( Line, Acc ) -> loop( io:get_line(""), [Line | Acc] ). diff --git a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-2.erl b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-2.erl deleted file mode 100644 index 452afb5cb5..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-2.erl +++ /dev/null @@ -1 +0,0 @@ -saepe audire diff --git a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-3.erl b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-3.erl deleted file mode 100644 index 9a4565775d..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-3.erl +++ /dev/null @@ -1 +0,0 @@ -In sit inermis deleniti percipit diff --git a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-4.erl b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-4.erl deleted file mode 100644 index 08a05fe66e..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-4.erl +++ /dev/null @@ -1 +0,0 @@ -soluta appetere ut mel diff --git a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-5.erl b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-5.erl deleted file mode 100644 index 0fee031400..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-5.erl +++ /dev/null @@ -1 +0,0 @@ -posse nullam lobortis ex usu diff --git a/Task/Rosetta-Code-Fix-code-tags/Go/rosetta-code-fix-code-tags.go b/Task/Rosetta-Code-Fix-code-tags/Go/rosetta-code-fix-code-tags.go deleted file mode 100644 index be3a7983ae..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Go/rosetta-code-fix-code-tags.go +++ /dev/null @@ -1,88 +0,0 @@ -package main - -import "fmt" -import "io/ioutil" -import "log" -import "os" -import "regexp" -import "strings" - -func main() { - err := fix() - if err != nil { - log.Fatalln(err) - } -} - -func fix() (err error) { - buf, err := ioutil.ReadAll(os.Stdin) - if err != nil { - return err - } - out, err := Lang(string(buf)) - if err != nil { - return err - } - fmt.Println(out) - return nil -} - -func Lang(in string) (out string, err error) { - reg := regexp.MustCompile("<[^>]+>") - out = reg.ReplaceAllStringFunc(in, repl) - return out, nil -} - -func repl(in string) (out string) { - if in == "</code>" { - // Change </code> to </ lang> - return "</"+"lang>" - } - - // mid is the content in between '<' and '>'. - mid := in[1 : len(in)-1] - - // thanks, random lua guy - var langs = []string{ - "abap", "actionscript", "actionscript3", "ada", "apache", "applescript", - "apt_sources", "asm", "asp", "autoit", "avisynth", "bash", "basic4gl", - "bf", "blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg", "cfm", - "cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css", "d", "delphi", - "diff", "_div", "dos", "dot", "eiffel", "email", "fortran", "freebasic", - "genero", "gettext", "glsl", "gml", "gnuplot", "go", "groovy", "haskell", - "hq9plus", "html4strict", "idl", "ini", "inno", "intercal", "io", "java", - "java5", "javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp", - "lolcode", "lotusformulas", "lotusscript", "lscript", "lua", "m68k", - "make", "matlab", "mirc", "modula3", "mpasm", "mxml", "mysql", "nsis", - "objc", "ocaml", "ocaml-brief", "oobas", "oracle11", "oracle8", "pascal", - "per", "perl", "php", "php-brief", "pic16", "pixelbender", "plsql", - "povray", "powershell", "progress", "prolog", "providex", "python", - "qbasic", "rails", "reg", "robots", "ruby", "sas", "scala", "scheme", - "scilab", "sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm", - "text", "thinbasic", "tsql", "typoscript", "vb", "vbnet", "verilog", - "vhdl", "vim", "visualfoxpro", "visualprolog", "whitespace", "winbatch", - "xml", "xorg_conf", "xpp", "z80", - } - for _, lang := range langs { - if mid == lang { - // Change <%s> to <lang %s> - return fmt.Sprintf("<lang %s>", lang) - } - - if strings.HasPrefix(mid, "/") { - if mid[len("/"):] == lang { - // Change </%s> to </ lang> - return "</"+"lang>" - } - } - - if strings.HasPrefix(mid, "code ") { - if mid[len("code "):] == lang { - // Change <code %s> to <lang %s> - return fmt.Sprintf("<lang %s>", lang) - } - } - } - - return in -} diff --git a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-1.j b/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-1.j deleted file mode 100644 index 855cb790a2..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-1.j +++ /dev/null @@ -1,6 +0,0 @@ -require 'printf strings files' - -langs=. <;._1 LF -.~ noun define NB. replace with real lang strings - foo bar - baz -) diff --git a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-2.j b/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-2.j deleted file mode 100644 index e083cf4e0f..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-2.j +++ /dev/null @@ -1,2 +0,0 @@ -| -</%s>| diff --git a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-3.j b/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-3.j deleted file mode 100644 index 1c7f21afcd..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-3.j +++ /dev/null @@ -1,2 +0,0 @@ -| -</code>| diff --git a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-4.j b/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-4.j deleted file mode 100644 index ce73763049..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-4.j +++ /dev/null @@ -1 +0,0 @@ -fixCodeTags=: rplc&(, <;._2;._2 &> patterns vbsprintf _5]\ 5#langs) diff --git a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-5.j b/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-5.j deleted file mode 100644 index 452afb5cb5..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-5.j +++ /dev/null @@ -1 +0,0 @@ -saepe audire diff --git a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-6.j b/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-6.j deleted file mode 100644 index 9a4565775d..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-6.j +++ /dev/null @@ -1 +0,0 @@ -In sit inermis deleniti percipit diff --git a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-7.j b/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-7.j deleted file mode 100644 index 08a05fe66e..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-7.j +++ /dev/null @@ -1 +0,0 @@ -soluta appetere ut mel diff --git a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-8.j b/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-8.j deleted file mode 100644 index 0fee031400..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-8.j +++ /dev/null @@ -1 +0,0 @@ -posse nullam lobortis ex usu diff --git a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-9.j b/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-9.j deleted file mode 100644 index 9d96ffbddc..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/J/rosetta-code-fix-code-tags-9.j +++ /dev/null @@ -1 +0,0 @@ - 'converted.txt' fwrite~ fixCodeTags fread 'wikisource.txt' diff --git a/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-1.java b/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-1.java deleted file mode 100644 index 3d124e3dad..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-1.java +++ /dev/null @@ -1,67 +0,0 @@ -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; - -public class FixCodeTags -{ - public static void main(String[] args) - { - String sourcefile=args[0]; - String convertedfile=args[1]; - convert(sourcefile,convertedfile); - } - static String[] languages = {"abap", "actionscript", "actionscript3", - "ada", "apache", "applescript", "apt_sources", "asm", "asp", - "autoit", "avisynth", "bar", "bash", "basic4gl", "bf", - "blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg", - "cfm", "cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css", - "d", "delphi", "diff", "_div", "dos", "dot", "eiffel", "email", - "foo", "fortran", "freebasic", "genero", "gettext", "glsl", "gml", - "gnuplot", "go", "groovy", "haskell", "hq9plus", "html4strict", - "idl", "ini", "inno", "intercal", "io", "java", "java5", - "javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp", - "lolcode", "lotusformulas", "lotusscript", "lscript", "lua", - "m68k", "make", "matlab", "mirc", "modula3", "mpasm", "mxml", - "mysql", "nsis", "objc", "ocaml", "ocaml-brief", "oobas", - "oracle11", "oracle8", "pascal", "per", "perl", "php", "php-brief", - "pic16", "pixelbender", "plsql", "povray", "powershell", - "progress", "prolog", "providex", "python", "qbasic", "rails", - "reg", "robots", "ruby", "sas", "scala", "scheme", "scilab", - "sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm", - "text", "thinbasic", "tsql", "typoscript", "vb", "vbnet", - "verilog", "vhdl", "vim", "visualfoxpro", "visualprolog", - "whitespace", "winbatch", "xml", "xorg_conf", "xpp", "z80"}; - static void convert(String sourcefile,String convertedfile) - { - try - { - BufferedReader br=new BufferedReader(new FileReader(sourcefile)); - //String buffer to store contents of the file - StringBuffer sb=new StringBuffer(""); - String line; - while((line=br.readLine())!=null) - { - for(int i=0;i<languages.length;i++) - { - String lang=languages[i]; - line=line.replaceAll("<"+lang+">", "<lang "+lang+">"); - line=line.replaceAll("</"+lang+">", "</"+lang+">"); - line=line.replaceAll("<code "+lang+">", "<lang "+lang+">"); - line=line.replaceAll("</code>", "</"+"lang>"); - } - sb.append(line); - } - br.close(); - - FileWriter fw=new FileWriter(new File(convertedfile)); - //Write entire string buffer into the file - fw.write(sb.toString()); - fw.close(); - } - catch (Exception e) - { - System.out.println("Something went horribly wrong: "+e.getMessage()); - } - } -} diff --git a/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-2.java b/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-2.java deleted file mode 100644 index 452afb5cb5..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-2.java +++ /dev/null @@ -1 +0,0 @@ -saepe audire diff --git a/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-3.java b/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-3.java deleted file mode 100644 index 06c7c836a7..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-3.java +++ /dev/null @@ -1,4 +0,0 @@ -In sit inermis deleniti percipit</foo>, -ius ex tale civibus omittam. <barf>Vix ut doctus cetero invenire</barf>, his eu -altera electram. Tota adhuc altera te sea, <lang bar>soluta appetere ut mel</bar>. -Quo quis graecis vivendo te, <baz>posse nullam lobortis ex usu diff --git a/Task/Rosetta-Code-Fix-code-tags/JavaScript/rosetta-code-fix-code-tags.js b/Task/Rosetta-Code-Fix-code-tags/JavaScript/rosetta-code-fix-code-tags.js deleted file mode 100644 index b76292285f..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/JavaScript/rosetta-code-fix-code-tags.js +++ /dev/null @@ -1,11 +0,0 @@ -var langs = ['foo', 'bar', 'baz']; // real list of langs goes here -var end_tag = '</'+'lang>'; - -var line; -while (line = readline()) { - line = line.replace(new RegExp('</code>', 'gi'), end_tag); - for (var i = 0; i < langs.length; i++) - line = line.replace(new RegExp('<(?:code )?(' + langs[i] + ')>', 'gi'), '<lang $1>') - .replace(new RegExp('</' + langs[i] + '>', 'gi'), end_tag); - print(line); -} diff --git a/Task/Rosetta-Code-Fix-code-tags/Lua/rosetta-code-fix-code-tags.lua b/Task/Rosetta-Code-Fix-code-tags/Lua/rosetta-code-fix-code-tags.lua deleted file mode 100644 index f33f6e5fe6..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Lua/rosetta-code-fix-code-tags.lua +++ /dev/null @@ -1,29 +0,0 @@ ---thanks, random python guy -langs = {'ada', 'cpp-qt', 'pascal', 'lscript', 'z80', 'visualprolog', -'html4strict', 'cil', 'objc', 'asm', 'progress', 'teraterm', 'hq9plus', -'genero', 'tsql', 'email', 'pic16', 'tcl', 'apt_sources', 'io', 'apache', -'vhdl', 'avisynth', 'winbatch', 'vbnet', 'ini', 'scilab', 'ocaml-brief', -'sas', 'actionscript3', 'qbasic', 'perl', 'bnf', 'cobol', 'powershell', -'php', 'kixtart', 'visualfoxpro', 'mirc', 'make', 'javascript', 'cpp', -'sdlbasic', 'cadlisp', 'php-brief', 'rails', 'verilog', 'xml', 'csharp', -'actionscript', 'nsis', 'bash', 'typoscript', 'freebasic', 'dot', -'applescript', 'haskell', 'dos', 'oracle8', 'cfdg', 'glsl', 'lotusscript', -'mpasm', 'latex', 'sql', 'klonec', 'ruby', 'ocaml', 'smarty', 'python', -'oracle11', 'caddcl', 'robots', 'groovy', 'smalltalk', 'diff', 'fortran', -'cfm', 'lua', 'modula3', 'vb', 'autoit', 'java', 'text', 'scala', -'lotusformulas', 'pixelbender', 'reg', '_div', 'whitespace', 'providex', -'asp', 'css', 'lolcode', 'lisp', 'inno', 'mysql', 'plsql', 'matlab', -'oobas', 'vim', 'delphi', 'xorg_conf', 'gml', 'prolog', 'bf', 'per', -'scheme', 'mxml', 'd', 'basic4gl', 'm68k', 'gnuplot', 'idl', 'abap', -'intercal', 'c_mac', 'thinbasic', 'java5', 'xpp', 'boo', 'klonecpp', -'blitzbasic', 'eiffel', 'povray', 'c', 'gettext'} - -for line in io.lines() do - for i, v in ipairs(langs) do - line = line:gsub("<" .. v .. ">", "<lang " .. v .. ">") - line = line:gsub("<code " .. v .. ">", "<lang " .. v .. ">") - line = line:gsub("</" .. v .. ">", "</" .. "lang>") --the weird concatenation is to prevent the markup from breaking - line = line:gsub("</" .. "code>", "</" .. "lang>") - end - print(line) -end diff --git a/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-1.math b/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-1.math deleted file mode 100644 index 80df0d77a8..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-1.math +++ /dev/null @@ -1,5 +0,0 @@ -"} -]>>"converted.txt" - -->conversion of sample text -Lorem ipsum<lang foo>saepe audire diff --git a/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-2.math b/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-2.math deleted file mode 100644 index 9a4565775d..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-2.math +++ /dev/null @@ -1 +0,0 @@ -In sit inermis deleniti percipit diff --git a/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-3.math b/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-3.math deleted file mode 100644 index 781121b8e3..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-3.math +++ /dev/null @@ -1 +0,0 @@ -Vix ut doctus cetero invenire diff --git a/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-4.math b/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-4.math deleted file mode 100644 index 08a05fe66e..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-4.math +++ /dev/null @@ -1 +0,0 @@ -soluta appetere ut mel diff --git a/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-5.math b/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-5.math deleted file mode 100644 index 0fee031400..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Mathematica/rosetta-code-fix-code-tags-5.math +++ /dev/null @@ -1 +0,0 @@ -posse nullam lobortis ex usu diff --git a/Task/Rosetta-Code-Fix-code-tags/OCaml/rosetta-code-fix-code-tags-1.ocaml b/Task/Rosetta-Code-Fix-code-tags/OCaml/rosetta-code-fix-code-tags-1.ocaml deleted file mode 100644 index 6de4d29bc7..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/OCaml/rosetta-code-fix-code-tags-1.ocaml +++ /dev/null @@ -1,59 +0,0 @@ -#load "str.cma" - -let langs = - Str.split (Str.regexp " ") - "actionscript ada algol68 amigae applescript autohotkey awk bash basic \ - befunge bf c cfm cobol cpp csharp d delphi e eiffel factor false forth \ - fortran fsharp haskell haxe j java javascript lisaac lisp logo lua m4 \ - mathematica maxscript modula3 moo objc ocaml octave oz pascal perl \ - perl6 php pike pop11 powershell prolog python qbasic r rebol ruby \ - scala scheme slate smalltalk tcl ti89b vbnet vedit" - -let read_in ic = - let buf = Buffer.create 16384 - and tmp = String.create 4096 in - let rec aux() = - let bytes = input ic tmp 0 4096 in - if bytes > 0 then begin - Buffer.add_substring buf tmp 0 bytes; - aux() - end - in - (try aux() with End_of_file -> ()); - (Buffer.contents buf) - -let repl pat tpl str = - let reg = Str.regexp_string_case_fold pat in - let str = Str.global_replace reg tpl str in - (str) - -(* change <%s> to <lang %s> *) -let repl1 lang str = - let pat = "<" ^ lang ^ ">" - and tpl = "<lang " ^ lang ^ ">" in - (repl pat tpl str) - -(* change </%s> to </la\ng> *) -let repl2 lang str = - let pat = "</" ^ lang ^ ">" - and tpl = "</lang"^">" in - (repl pat tpl str) - -(* change <code %s> to <lang %s> *) -let repl3 lang str = - let pat = "<code " ^ lang ^ ">" - and tpl = "<lang " ^ lang ^ ">" in - (repl pat tpl str) - -(* change </code> to </la\ng> *) -let repl4 lang str = - let pat = "</code>" - and tpl = "</lang"^">" in - (repl pat tpl str) - - -let () = - print_string ( - List.fold_left (fun str lang -> - (repl4 lang (repl3 lang (repl2 lang (repl1 lang str)))) - ) (read_in stdin) langs) diff --git a/Task/Rosetta-Code-Fix-code-tags/OCaml/rosetta-code-fix-code-tags-2.ocaml b/Task/Rosetta-Code-Fix-code-tags/OCaml/rosetta-code-fix-code-tags-2.ocaml deleted file mode 100644 index 8bf4da2a1f..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/OCaml/rosetta-code-fix-code-tags-2.ocaml +++ /dev/null @@ -1 +0,0 @@ - (repl4 lang (repl3 lang (repl2 lang (repl1 lang str)))) diff --git a/Task/Rosetta-Code-Fix-code-tags/OCaml/rosetta-code-fix-code-tags-3.ocaml b/Task/Rosetta-Code-Fix-code-tags/OCaml/rosetta-code-fix-code-tags-3.ocaml deleted file mode 100644 index 516376f72a..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/OCaml/rosetta-code-fix-code-tags-3.ocaml +++ /dev/null @@ -1 +0,0 @@ - List.fold_right (fun repl -> repl lang) [repl1; repl2; repl3; repl4] str diff --git a/Task/Rosetta-Code-Fix-code-tags/Perl-6/rosetta-code-fix-code-tags.pl6 b/Task/Rosetta-Code-Fix-code-tags/Perl-6/rosetta-code-fix-code-tags.pl6 deleted file mode 100644 index c469d853fd..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Perl-6/rosetta-code-fix-code-tags.pl6 +++ /dev/null @@ -1,26 +0,0 @@ -my @langs = < - abap actionscript actionscript3 ada apache applescript apt_sources - asm asp autoit avisynth bash basic4gl bf blitzbasic bnf boo c caddcl - cadlisp cfdg cfm cil c_mac cobol cpp cpp-qt csharp css d delphi - diff _div dos dot eiffel email fortran freebasic genero gettext - glsl gml gnuplot groovy haskell hq9plus html4strict idl ini inno - intercal io java java5 javascript kixtart klonec klonecpp latex lisp - lolcode lotusformulas lotusscript lscript lua m68k make matlab mirc - modula3 mpasm mxml mysql nsis objc ocaml ocaml-brief oobas oracle11 - oracle8 pascal per perl php php-brief pic16 pixelbender plsql povray - powershell progress prolog providex python qbasic rails reg robots - ruby sas scala scheme scilab sdlbasic smalltalk smarty sql tcl teraterm - text thinbasic tsql typoscript vb vbnet verilog vhdl vim visualfoxpro - visualprolog whitespace winbatch xml xorg_conf xpp z80 ->; - -$_ = slurp; - -for @langs -> $l { - s:g [ '<' $l '>' ] = "<lang $l>"; - s:g [ '</' $l '>' ] = '</' ~ 'lang>'; -} - -s:g [ '<code '(.+?) '>' (.*?) '</code>' ] = "<lang $0>{$1}</"~"lang>"; - -.say; diff --git a/Task/Rosetta-Code-Fix-code-tags/Perl/rosetta-code-fix-code-tags.pl b/Task/Rosetta-Code-Fix-code-tags/Perl/rosetta-code-fix-code-tags.pl deleted file mode 100644 index ff13ad9e0a..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Perl/rosetta-code-fix-code-tags.pl +++ /dev/null @@ -1,26 +0,0 @@ -my @langs = qw(ada cpp-qt pascal lscript z80 visualprolog -html4strict cil objc asm progress teraterm hq9plus genero tsql -email pic16 tcl apt_sources io apache vhdl avisynth winbatch -vbnet ini scilab ocaml-brief sas actionscript3 qbasic perl bnf -cobol powershell php kixtart visualfoxpro mirc make javascript -cpp sdlbasic cadlisp php-brief rails verilog xml csharp -actionscript nsis bash typoscript freebasic dot applescript -haskell dos oracle8 cfdg glsl lotusscript mpasm latex sql klonec -ruby ocaml smarty python oracle11 caddcl robots groovy smalltalk -diff fortran cfm lua modula3 vb autoit java text scala -lotusformulas pixelbender reg _div whitespace providex asp css -lolcode lisp inno mysql plsql matlab oobas vim delphi xorg_conf -gml prolog bf per scheme mxml d basic4gl m68k gnuplot idl abap -intercal c_mac thinbasic java5 xpp boo klonecpp blitzbasic eiffel -povray c gettext); - -my $text = join "", <STDIN>; -my $slang="/lang"; -for (@langs) { - $text =~ s|<$_>|<lang $_>|g; - $text =~ s|</$_>|<$slang>|g; -} - -$text =~ s|<code (.+?)>(.*?)</code>|<lang $1>$2<$slang>|sg; - -print $text; diff --git a/Task/Rosetta-Code-Fix-code-tags/PicoLisp/rosetta-code-fix-code-tags.l b/Task/Rosetta-Code-Fix-code-tags/PicoLisp/rosetta-code-fix-code-tags.l deleted file mode 100644 index 7c3f69050c..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/PicoLisp/rosetta-code-fix-code-tags.l +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/picolisp /usr/lib/picolisp/lib.l - -(let Lang '("ada" "awk" "c" "forth" "prolog" "python" "z80") - (in NIL - (while (echo "<") - (let S (till ">" T) - (cond - ((pre? "code " S) (prin "<lang" (cddddr (chop S)))) - ((member S Lang) (prin "<lang " S)) - ((= S "/code") (prin "</lang")) - ((and (pre? "/" S) (member (pack (cdr (chop S))) Lang)) - (prin "</lang") ) - (T (prin "<" S)) ) ) ) ) ) -(bye) diff --git a/Task/Rosetta-Code-Fix-code-tags/PureBasic/rosetta-code-fix-code-tags.purebasic b/Task/Rosetta-Code-Fix-code-tags/PureBasic/rosetta-code-fix-code-tags.purebasic deleted file mode 100644 index 872459b164..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/PureBasic/rosetta-code-fix-code-tags.purebasic +++ /dev/null @@ -1,40 +0,0 @@ -If Not OpenConsole() - End -ElseIf CountProgramParameters() <> 2 - PrintN("Usage: "+GetFilePart(ProgramFilename())+" InFile OutFile") - End -EndIf - -Define Infile$ =ProgramParameter(), Outfile$=ProgramParameter() -If ReadFile(0,Infile$) - NewList Out$() - Define line$, part$, new$, pos1, pos2 - While Not Eof(0) - line$=ReadString(0): pos2=0 - Repeat - pos1=FindString(line$,"<",pos2) - pos2=FindString(line$,">",pos1) - If pos1 And pos2 - part$=Mid(line$,pos1+1,pos2-pos1-1) - If Mid(part$,1,1)="/" - new$="<"+"/lang>" ; Line split to avoid problem forum coding - ElseIf Mid(part$,1,5)="code " - new$="<lang "+Mid(part$,6)+">" - Else - new$="<lang "+part$+">" - EndIf - line$=ReplaceString(line$,"<"+part$+">",new$) - Else - Break - EndIf - ForEver - AddElement(Out$()): Out$()=line$ - Wend - CloseFile(0) - If CreateFile(1, Outfile$) - ForEach Out$() - WriteStringN(1,Out$()) - Next - CloseFile(1) - EndIf -EndIf diff --git a/Task/Rosetta-Code-Fix-code-tags/Python/rosetta-code-fix-code-tags.py b/Task/Rosetta-Code-Fix-code-tags/Python/rosetta-code-fix-code-tags.py deleted file mode 100644 index 04aa07177a..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Python/rosetta-code-fix-code-tags.py +++ /dev/null @@ -1,36 +0,0 @@ -# coding: utf-8 - -import sys -import re - -langs = ['ada', 'cpp-qt', 'pascal', 'lscript', 'z80', 'visualprolog', -'html4strict', 'cil', 'objc', 'asm', 'progress', 'teraterm', 'hq9plus', -'genero', 'tsql', 'email', 'pic16', 'tcl', 'apt_sources', 'io', 'apache', -'vhdl', 'avisynth', 'winbatch', 'vbnet', 'ini', 'scilab', 'ocaml-brief', -'sas', 'actionscript3', 'qbasic', 'perl', 'bnf', 'cobol', 'powershell', -'php', 'kixtart', 'visualfoxpro', 'mirc', 'make', 'javascript', 'cpp', -'sdlbasic', 'cadlisp', 'php-brief', 'rails', 'verilog', 'xml', 'csharp', -'actionscript', 'nsis', 'bash', 'typoscript', 'freebasic', 'dot', -'applescript', 'haskell', 'dos', 'oracle8', 'cfdg', 'glsl', 'lotusscript', -'mpasm', 'latex', 'sql', 'klonec', 'ruby', 'ocaml', 'smarty', 'python', -'oracle11', 'caddcl', 'robots', 'groovy', 'smalltalk', 'diff', 'fortran', -'cfm', 'lua', 'modula3', 'vb', 'autoit', 'java', 'text', 'scala', -'lotusformulas', 'pixelbender', 'reg', '_div', 'whitespace', 'providex', -'asp', 'css', 'lolcode', 'lisp', 'inno', 'mysql', 'plsql', 'matlab', -'oobas', 'vim', 'delphi', 'xorg_conf', 'gml', 'prolog', 'bf', 'per', -'scheme', 'mxml', 'd', 'basic4gl', 'm68k', 'gnuplot', 'idl', 'abap', -'intercal', 'c_mac', 'thinbasic', 'java5', 'xpp', 'boo', 'klonecpp', -'blitzbasic', 'eiffel', 'povray', 'c', 'gettext'] - -slang = '/lang' -code='code' - -text = sys.stdin.read() - -for i in langs: - text = text.replace("<%s>" % i,"<lang %s>" % i) - text = text.replace("</%s>" % i, "<%s>" % slang) - -text = re.sub("(?s)<%s (.+?)>(.*?)</%s>"%(code,code), r"<lang \1>\2<%s>" % slang, text) - -sys.stdout.write(text) diff --git a/Task/Rosetta-Code-Fix-code-tags/R/rosetta-code-fix-code-tags.r b/Task/Rosetta-Code-Fix-code-tags/R/rosetta-code-fix-code-tags.r deleted file mode 100644 index cbdbb9c332..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/R/rosetta-code-fix-code-tags.r +++ /dev/null @@ -1,14 +0,0 @@ -fixtags <- function(page) -{ - langs <- c("c", "c-sharp", "r") # a complete list is required, obviously - langs <- paste(langs, collapse="|") - page <- gsub(paste("<(", langs, ")>", sep=""), "<lang \\1>", page) - page <- gsub(paste("</(", langs, ")>", sep=""), "</#####lang>", page) - page <- gsub(paste("<code(", langs, ")>", sep=""), "<lang \\1>", page) - page <- gsub(paste("</code>", sep=""), "</#####lang>", page) - page -} - -page <- "lorem ipsum <c>some c code</c>dolor sit amet,<c-sharp>some c-sharp code</c-sharp> -consectetur adipisicing elit,<code r>some r code</code>sed do eiusmod tempor incididunt" -fixtags(page) diff --git a/Task/Rosetta-Code-Fix-code-tags/README b/Task/Rosetta-Code-Fix-code-tags/README deleted file mode 100644 index 3cfa671d2d..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/README +++ /dev/null @@ -1 +0,0 @@ -Data source: http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags diff --git a/Task/Rosetta-Code-Fix-code-tags/REXX/rosetta-code-fix-code-tags-1.rexx b/Task/Rosetta-Code-Fix-code-tags/REXX/rosetta-code-fix-code-tags-1.rexx deleted file mode 100644 index 499c7783a7..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/REXX/rosetta-code-fix-code-tags-1.rexx +++ /dev/null @@ -1,21 +0,0 @@ -/*REXX program fixes (changes) depreciated code tags with newer tags.*/ -@ = '<' /*ensure RC doesn't get confused.*/ -old. = /*define a default value for OLD.*/ -old.1 = @'%s>' ; new.1 = @'lang %s>' -old.2 = @'/%s>' ; new.2 = @'/lang>' -old.3 = @'code %s>' ; new.3 = @'lang %s>' -old.4 = @'/code>' ; new.4 = @'/lang>' - -ifid = 'Wikisource.txt' /* Input File IDentifier. */ -ofid = 'converted.txt' /*Output " " */ - - do while lines(ifid) \== 0 /*keep trunkin' until it's done. */ - _=linein(ifid) /*read a record from input file. */ - - do j=1 while old.j \== '' /*change old ──► new until done. */ - _=changestr(new.j,_,old.j) /*let REXX do the heavy lifting. */ - end /*j*/ - - call lineout ofid,_ /*write the re-formatted record. */ - end /*while lines(ifid...*/ - /*stick a fork in it, we're done.*/ diff --git a/Task/Rosetta-Code-Fix-code-tags/REXX/rosetta-code-fix-code-tags-2.rexx b/Task/Rosetta-Code-Fix-code-tags/REXX/rosetta-code-fix-code-tags-2.rexx deleted file mode 100644 index f1e6eb5a74..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/REXX/rosetta-code-fix-code-tags-2.rexx +++ /dev/null @@ -1,26 +0,0 @@ -/*╔══════════════════════════════╗ CHANGESTR ╔═════════════════════════╗ -╔═╩══════════════════════════════╝ function ╚═════════════════════════╩═╗ -║ new string to be used──────────┐ ┌─────limit of # changes (times)║ -║ original string (haystack)────────┐ │ │ [default: ≈ one billian]║ -║ old string to be changed───┐ │ │ │ ┌───begin at this occurance #.║ -║ {O, H, and N can be null.} │ │ │ │ │ [default: 1st occurrance]║ -╚═╦════════════════════════════╗ │ │ │ │ │ ╔═══════════════════════╦═╝ - ╚════════════════════════════╝ ↓ ↓ ↓ ↓ ↓ ╚═══════════════════════╝*/ -changestr: procedure; parse arg o,h,n,t,b /* T and B are optional.*/ -$='' /*$: the returned string.*/ -t=word(t 999999999 , 1) /*maybe use the default? */ -b=word(b 1 , 1) /* " " " " */ -w=length(o) /*length of OLD string.*/ -if w==0 & t\=0 then return n || h /*changing a null char ? */ -#=0 /*# of changed occurances*/ - do j=1 until # >= t /*keep changing, T times.*/ - parse var h y (o) _ +(w) h /*parse the string ... */ - if _=='' then return $ || y /*no more left, return. */ - if j<b then $=$ || y || o /*didn't meet begin at ? */ - else do - $=$ || y || n /*build new STR from S. */ - #=#+1 /*bump occurance number. */ - end - end /*j*/ - /*Most REXX BIFs only ···*/ -return $ || h /* support three options.*/ diff --git a/Task/Rosetta-Code-Fix-code-tags/REXX/rosetta-code-fix-code-tags.rexx b/Task/Rosetta-Code-Fix-code-tags/REXX/rosetta-code-fix-code-tags.rexx deleted file mode 100644 index 499c7783a7..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/REXX/rosetta-code-fix-code-tags.rexx +++ /dev/null @@ -1,21 +0,0 @@ -/*REXX program fixes (changes) depreciated code tags with newer tags.*/ -@ = '<' /*ensure RC doesn't get confused.*/ -old. = /*define a default value for OLD.*/ -old.1 = @'%s>' ; new.1 = @'lang %s>' -old.2 = @'/%s>' ; new.2 = @'/lang>' -old.3 = @'code %s>' ; new.3 = @'lang %s>' -old.4 = @'/code>' ; new.4 = @'/lang>' - -ifid = 'Wikisource.txt' /* Input File IDentifier. */ -ofid = 'converted.txt' /*Output " " */ - - do while lines(ifid) \== 0 /*keep trunkin' until it's done. */ - _=linein(ifid) /*read a record from input file. */ - - do j=1 while old.j \== '' /*change old ──► new until done. */ - _=changestr(new.j,_,old.j) /*let REXX do the heavy lifting. */ - end /*j*/ - - call lineout ofid,_ /*write the re-formatted record. */ - end /*while lines(ifid...*/ - /*stick a fork in it, we're done.*/ diff --git a/Task/Rosetta-Code-Fix-code-tags/Racket/rosetta-code-fix-code-tags.rkt b/Task/Rosetta-Code-Fix-code-tags/Racket/rosetta-code-fix-code-tags.rkt deleted file mode 100644 index 1f24c83270..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Racket/rosetta-code-fix-code-tags.rkt +++ /dev/null @@ -1,20 +0,0 @@ -#lang racket - -(define lang-names '("X" "Y" "Z")) - -(define rx - (regexp (string-join lang-names "|" - #:before-first "<((/?(?:code)?)(?:( )?(" - #:after-last "))?)>"))) - -(let loop () ; does all in a single scan - (define m (regexp-match rx (current-input-port) 0 #f (current-output-port))) - (when m - (define-values [all pfx space lang] (apply values (cdr m))) - (printf "<~a>" - (cond [(not lang) (if (equal? pfx #"/code") #"/lang" all)] - [space (if (equal? pfx #"code") (bytes-append #"lang " lang) all)] - [(equal? pfx #"") (bytes-append #"lang " lang)] - [(equal? pfx #"/") #"/lang"] - [else all])) - (loop))) diff --git a/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-1.rb b/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-1.rb deleted file mode 100644 index 6c0b5482c8..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-1.rb +++ /dev/null @@ -1,21 +0,0 @@ -# get all stdin in one string -#text = $stdin.read -# for testing, use -text = DATA.read -slash_lang = '/lang' -langs = %w(foo bar baz) # actual list of languages declared here -for lang in langs - text.gsub!(Regexp.new("<(#{lang})>")) {"<lang #$1>"} - text.gsub!(Regexp.new("</#{lang}>"), "<#{slash_lang}>") -end -text.gsub!(/<code (.*?)>/, '<lang \1>') -text.gsub!(/<\/code>/, "<#{slash_lang}>") -print text - -__END__ -Lorem ipsum <code foo>saepe audire</code> elaboraret ne quo, id equidem -atomorum inciderint usu. <foo>In sit inermis deleniti percipit</foo>, -ius ex tale civibus omittam. <barf>Vix ut doctus cetero invenire</barf>, his eu -altera electram. Tota adhuc altera te sea, <code bar>soluta appetere ut mel</bar>. -Quo quis graecis vivendo te, <baz>posse nullam lobortis ex usu</code>. Eam volumus perpetua -constituto id, mea an omittam fierent vituperatoribus. diff --git a/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-2.rb b/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-2.rb deleted file mode 100644 index 452afb5cb5..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-2.rb +++ /dev/null @@ -1 +0,0 @@ -saepe audire diff --git a/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-3.rb b/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-3.rb deleted file mode 100644 index 9a4565775d..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-3.rb +++ /dev/null @@ -1 +0,0 @@ -In sit inermis deleniti percipit diff --git a/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-4.rb b/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-4.rb deleted file mode 100644 index 08a05fe66e..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-4.rb +++ /dev/null @@ -1 +0,0 @@ -soluta appetere ut mel diff --git a/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-5.rb b/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-5.rb deleted file mode 100644 index 0fee031400..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Ruby/rosetta-code-fix-code-tags-5.rb +++ /dev/null @@ -1 +0,0 @@ -posse nullam lobortis ex usu diff --git a/Task/Rosetta-Code-Fix-code-tags/Tcl/rosetta-code-fix-code-tags-1.tcl b/Task/Rosetta-Code-Fix-code-tags/Tcl/rosetta-code-fix-code-tags-1.tcl deleted file mode 100644 index bb6e3b6c56..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Tcl/rosetta-code-fix-code-tags-1.tcl +++ /dev/null @@ -1,20 +0,0 @@ -set langs { - ada cpp-qt pascal lscript z80 visualprolog html4strict cil objc asm progress teraterm - hq9plus genero tsql email pic16 tcl apt_sources io apache vhdl avisynth winbatch vbnet - ini scilab ocaml-brief sas actionscript3 qbasic perl bnf cobol powershell php kixtart - visualfoxpro mirc make javascript cpp sdlbasic cadlisp php-brief rails verilog xml - csharp actionscript nsis bash typoscript freebasic dot applescript haskell dos oracle8 - cfdg glsl lotusscript mpasm latex sql klonec ruby ocaml smarty python oracle11 caddcl - robots groovy smalltalk diff fortran cfm lua modula3 vb autoit java text scala lotusformulas - pixelbender reg _div whitespace providex asp css lolcode lisp inno mysql plsql matlab - oobas vim delphi xorg_conf gml prolog bf per scheme mxml d basic4gl m68k gnuplot idl - abap intercal c_mac thinbasic java5 xpp boo klonecpp blitzbasic eiffel povray c gettext -} - -set text [read stdin] -set slang /lang -foreach lang $langs { - set text [regsub -all "<$lang>" $text "<lang $lang>"] - set text [regsub -all "</$lang>" $text "<$slang>"] -} -set text [regsub -all "<code (.+?)>(.+?)</code>" $text "<lang \\1>\\2<$slang>"] diff --git a/Task/Rosetta-Code-Fix-code-tags/Tcl/rosetta-code-fix-code-tags-2.tcl b/Task/Rosetta-Code-Fix-code-tags/Tcl/rosetta-code-fix-code-tags-2.tcl deleted file mode 100644 index ccc77d56dd..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Tcl/rosetta-code-fix-code-tags-2.tcl +++ /dev/null @@ -1,2 +0,0 @@ -set text [regexp -all "<([join $langs |])>" $text {<lang \1>}] -set text [regexp -all "</(?:[join $langs |])>" $text "<$slang>"] diff --git a/Task/Rosetta-Code-Fix-code-tags/Tcl/rosetta-code-fix-code-tags-3.tcl b/Task/Rosetta-Code-Fix-code-tags/Tcl/rosetta-code-fix-code-tags-3.tcl deleted file mode 100644 index 043b94cd1f..0000000000 --- a/Task/Rosetta-Code-Fix-code-tags/Tcl/rosetta-code-fix-code-tags-3.tcl +++ /dev/null @@ -1,7 +0,0 @@ -set replacements [list </code> <$slang>] -foreach lang $langs { - lappend replacements "<$lang>" "<lang $lang>" - lappend replacements "</$lang>" "<$slang>" - lappend replacements "<code $lang>" "<lang $lang>" -} -set text [string map $replacements $text] diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION b/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION deleted file mode 100644 index a0d8d53879..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION +++ /dev/null @@ -1,50 +0,0 @@ -Sort most popular programming languages based in number of members in Rosetta Code categories -<br>(from http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000) - -Sample output on March 30 2014: - -<pre> 1. 797 - Tcl - 2. 756 - Racket - 3. 750 - Python - 4. 719 - C - 5. 692 - Perl 6 - 6. 678 - D - 7. 677 - J - 8. 668 - Ruby - 9. 638 - Go - 10. 636 - PicoLisp - 11. 630 - Perl - 12. 615 - REXX - 13. 585 - Ada - 14. 578 - Haskell - 15. 567 - Mathematica - 16. 561 - AutoHotkey - 17. 541 - Unicon - 18. 539 - Java - 19. 525 - BBC BASIC - 20. 495 - Icon - 21. 492 - OCaml - 22. 487 - C++ - 23. 473 - Common Lisp - 24. 469 - PureBasic - 25. 446 - C sharp - 26. 444 - Erlang - 27. 411 - Scala - 28. 387 - JavaScript - 29. 385 - Clojure - 30. 359 - Seed7 - 31. 347 - Lua - 32. 341 - Groovy - 33. 340 - R - 34. 340 - F Sharp - 35. 337 - Forth - 36. 335 - PHP - 37. 329 - ALGOL 68 - 38. 328 - Fortran - 39. 319 - Pascal - 40. 307 - Liberty BASIC -...</pre> - -A complete ranked listing of all '''548''' languages (from the REXX example) is included here ──► [[RC_POP.OUT]]. - -Filtering wrong results is optional. You can check against [[Special:MostLinkedCategories]] diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/00META.yaml b/Task/Rosetta-Code-Rank-languages-by-popularity/00META.yaml deleted file mode 100644 index 37dd50820a..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/00META.yaml +++ /dev/null @@ -1,6 +0,0 @@ ---- -category: -- Networking and Web Interaction -- Sorting -- Rosetta Code related -note: Text processing diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/ALGOL-68/rosetta-code-rank-languages-by-popularity.alg b/Task/Rosetta-Code-Rank-languages-by-popularity/ALGOL-68/rosetta-code-rank-languages-by-popularity.alg deleted file mode 100644 index 86d724d2a0..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/ALGOL-68/rosetta-code-rank-languages-by-popularity.alg +++ /dev/null @@ -1,124 +0,0 @@ -PROC good page = (REF STRING page) BOOL: - IF grep in string("^HTTP/[0-9.]* 200", page, NIL, NIL) = 0 - THEN TRUE - ELSE IF INT start, end; - grep in string("^HTTP/[0-9.]* [0-9]+ [a-zA-Z ]*", page, - start, end) = 0 - THEN print (page[start : end]) - ELSE print ("unknown error retrieving page") - FI; - FALSE - FI; - -MODE LISTOFSTRING = STRUCT(REF LINK first, last, INT upb); -MODE LINK = STRUCT(STRING value, REF LINK next); - -PRIO LISTINIT = 1; -OP LISTINIT = (REF LISTOFSTRING new, REF LINK first)REF LISTOFSTRING: ( - new := (first, first, (first IS REF LINK(NIL) | 0 | 1 )); - new -); - -OP +:= = (REF LISTOFSTRING list, []CHAR item)VOID: ( - HEAP LINK new := (STRING(item), REF LINK(NIL)); - IF first OF list IS REF LINK(NIL) THEN - first OF list := new - ELSE - next OF last OF list := new - FI; - last OF list := new; - upb OF list +:= 1 -); - -OP UPB = (LISTOFSTRING list)INT: upb OF list; - -OP ARRAYOFSTRING = (LISTOFSTRING list)[]STRING:( - [UPB list]STRING out; - REF LINK this := first OF list; - FOR i TO UPB list DO out[i] := value OF this; this := next OF this OD; - out -); - -INT match=0, no match=1, out of memory error=2, other error=3; - -PROC re split = (STRING re split, REF STRING beetles)[]STRING:( - LISTOFSTRING out := (NIL, NIL, 0); # LISTINIT REF LINK NIL; # - INT start := 1, pos, end; - WHILE grep in string(re split, beetles[start:], pos, end) = match DO - out +:= beetles[start:start+pos-2]; - out +:= beetles[start+pos-1:start+end-1]; - start +:= end - OD; - IF start > UPB beetles THEN - out +:= beetles[start:] - FI; - ARRAYOFSTRING(out) - ); - - -IF STRING reply; - INT rc = - http content (reply, "www.rosettacode.org", "http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=500", 0); - rc /= 0 OR NOT good page (reply) -THEN print (("Error:",strerror (rc))) -ELSE - STRING # hack: HTML should be parsed by an official HTML parsing library # - re html tag = "<[^>]*>", - re a href category = "^<a href=""/wiki/Category:.*"" title=", - re members = "([1-9][0-9]* members)"; - - MODE STATISTIC = STRUCT(INT members, STRING category); - FLEX[0]STATISTIC stats; - - OP +:= = (REF FLEX[]STATISTIC in out, STATISTIC item)VOID:( - [LWB in out: UPB in out+1]STATISTIC new; - new[LWB in out: UPB in out]:=in out; - new[UPB new]:=item; - in out := new - ); - -# hack: needs to be manually maintained # - STRING re ignore ="Programming Tasks|WikiStubs|Maintenance/OmitCategoriesCreated|"+ - "Unimplemented tasks by language|Programming Languages|"+ - "Solutions by Programming Language|Implementations|"+ - "Solutions by Library|Encyclopedia|Language users|"+ - "Solutions by Programming Task|Basic language learning|"+ - "RCTemplates|Language Implementations"; - - FORMAT category fmt = $"<a href=""/wiki/Category:"g""" title=""Category:"g""""$; - STRING encoded category, category; - FORMAT members fmt = $" ("g" members)"$; - INT members; - - FLEX[0]STRING tokens := re split(re html tag, reply); - FOR token index TO UPB tokens DO - STRING token := tokens[token index]; - FILE file; - IF grep in string(re a href category, token, NIL, NIL) = match THEN - associate(file, token); - make term(file,""""); - getf(file, (category fmt, encoded category, category)); - close(file) - ELIF grep in string(re members, token, NIL, NIL) = match THEN - IF grep in string(re ignore, category, NIL, NIL) /= match THEN - associate(file, token); - getf(file, (members fmt, members)); - stats +:= STATISTIC(members, category); - close(file) - FI - FI - OD; - - OP < = (STATISTIC a,b)BOOL: - members OF a < members OF b; - - MODE SORTSTRUCT = STATISTIC; - PR READ "prelude/sort.a68" PR; - - stats := in place shell sort reverse(stats); - - INT max = 10; - FOR i TO (UPB stats > max | max | UPB stats) DO - printf(($g(-0)". "g(-0)" - "gl$,i,stats[i])) - OD -FI diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/AWK/rosetta-code-rank-languages-by-popularity.awk b/Task/Rosetta-Code-Rank-languages-by-popularity/AWK/rosetta-code-rank-languages-by-popularity.awk deleted file mode 100644 index 77ef666e36..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/AWK/rosetta-code-rank-languages-by-popularity.awk +++ /dev/null @@ -1,93 +0,0 @@ -BEGIN { - for (i = 0; i <= 255; i++) - ord[sprintf("%c", i)] = i -} - -# Encode string with application/x-www-form-urlencoded escapes. -function escape(str, c, len, res) { - len = length(str) - res = "" - for (i = 1; i <= len; i++) { - c = substr(str, i, 1); - if (c ~ /[-._*0-9A-Za-z]/) - res = res c - else if (c == " ") - res = res "+" - else - res = res "%" sprintf("%02X", ord[c]) - } - return res -} - -function nc_open(gcmcontinue, host, path) { - host = "rosettacode.org" - path = "/mw/api.php" \ - "?action=query" \ - "&generator=categorymembers" \ - "&gcmtitle=Category:Programming%20Languages" \ - "&gcmlimit=500" \ - (gcmcontinue "" ? "&gcmcontinue=" escape(gcmcontinue) : "") \ - "&prop=categoryinfo" \ - "&format=txt" - - nc = "printf 'GET %s HTTP/1.1\r\nHost: %s\r\n\r\n' '" \ - path "' '" host "' | nc '" host "' 80" -} - -function nc_next(out) { - # Read each line of the HTTP response. - while (nc | getline > 0) { - # Ignore all lines except - # [gcmcontinue], [title] and [pages]. - if (index($0, "[gcmcontinue]")) { - # " [gcmcontinue] => BEFUNGE|" - sub(/^.*=> */, "") - out["gcmcontinue"] = $0 - } else if (index($0, "[title]")) { - # " [title] => Category:AWK" - sub(/^.*Category:/, "") - out["title"] = $0 - } else if(index($0, "[pages]")) { - # " [pages] => 129" - sub(/^.*=> */, "") - # Ignore " [pages] => Array". - if ($0 !~ /^[0-9]+/) - continue - - # Force conversion to number, so AWK will do - # numeric comparisons, not string comparisons. - out["pages"] = $0 + 0 - - # Return now; [pages] came after [title]. - return 1 - } - } - - if ("gcmcontinue" in out) { - close(nc) - nc_open(out["gcmcontinue"]) - delete out["gcmcontinue"] - return nc_next(out) - } else - return 0 -} - -BEGIN { - nc_open() - while (nc_next(language)) { - title = language["title"] # "AWK" - pages = language["pages"] # 129 - - # Insert "129 - AWK" into rank[]. - i = 1 - while (i <= count && (rank[i] + 0) >= pages) - i++ - for (j = count; j >= i; j--) - rank[j + 1] = rank[j] - rank[i] = pages " - " title - count++ - } - - for (i = 1; i <= count; i++) - print i ". " rank[i] -} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Ada/rosetta-code-rank-languages-by-popularity.ada b/Task/Rosetta-Code-Rank-languages-by-popularity/Ada/rosetta-code-rank-languages-by-popularity.ada deleted file mode 100644 index 470a835d1b..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Ada/rosetta-code-rank-languages-by-popularity.ada +++ /dev/null @@ -1,89 +0,0 @@ -with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; -with Ada.Strings.Fixed; use Ada.Strings.Fixed; -with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; -with Ada.Text_IO; use Ada.Text_IO; - -with Ada.Containers.Ordered_Sets; -with Ada.Strings.Less_Case_Insensitive; - -with AWS.Client; -with AWS.Response; - -procedure Test is - - use Ada.Strings; - - function "+" (S : String) return Unbounded_String renames To_Unbounded_String; - - type A_Language_Count is - record - Count : Integer := 0; - Language : Unbounded_String; - end record; - - function "=" (L, R : A_Language_Count) return Boolean is - begin - return L.Language = R.Language; - end "="; - - function "<" (L, R : A_Language_Count) return Boolean is - begin - -- Sort by 'Count' and then by Language name - return L.Count < R.Count - or else (L.Count = R.Count - and then Less_Case_Insensitive (Left => To_String (L.Language), - Right => To_String (R.Language))); - end "<"; - - package Sets is new Ada.Containers.Ordered_Sets (A_Language_Count); - use Sets; - - Counts : Set; - - procedure Find_Counts (S : String) is - Title_Str : constant String := "title=""Category:"; - End_A_Str : constant String := "</a> ("; - - Title_At : constant Natural := Index (S, Title_Str); - begin - if Title_At /= 0 then - declare - Bracket_At : constant Natural := Index (S (Title_At + Title_Str'Length .. S'Last), ">"); - End_A_At : constant Natural := Index (S (Bracket_At + 1 .. S'Last), End_A_Str); - Space_At : constant Natural := Index (S (End_A_At + End_A_Str'Length .. S'Last), " "); - Count : constant Natural := Natural'Value (S (End_A_At + End_A_Str'Length .. Space_At - 1)); - Language : constant String := S (Title_At + Title_Str'Length .. Bracket_At - 2); - begin - if Bracket_At /= 0 and then End_A_At /= 0 and then Space_At /= 0 then - begin - Counts.Insert (New_Item => (Count, +Language)); - exception - when Constraint_Error => - Put_Line (Standard_Error, "Warning: repeated language: " & Language); - -- Ignore repeated results. - null; - end; - end if; - -- Recursively parse the string for languages and counts - Find_Counts (S (Space_At + 1 .. S'Last)); - end; - end if; - - end Find_Counts; - - Place : Natural := 1; - - procedure Display (C : Cursor) is - begin - Put (Place, Width => 1); Put (". "); - Put (Element (C).Count, Width => 1); Put (" - "); - Put_Line (To_String (Element (C).Language)); - Place := Place + 1; - end Display; - - Http_Source : constant AWS.Response.Data := - AWS.Client.Get ("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"); -begin - Find_Counts (AWS.Response.Message_Body (Http_Source)); - Counts.Reverse_Iterate (Display'Access); -end Test; diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/AutoHotkey/rosetta-code-rank-languages-by-popularity.ahk b/Task/Rosetta-Code-Rank-languages-by-popularity/AutoHotkey/rosetta-code-rank-languages-by-popularity.ahk deleted file mode 100644 index 7eaa25845a..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/AutoHotkey/rosetta-code-rank-languages-by-popularity.ahk +++ /dev/null @@ -1,86 +0,0 @@ -MembsUrl = http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000 -ValidUrl = http://rosettacode.org/wiki/Category:Programming_Languages -WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1") - -; Get the webpages -WebRequest.Open("GET", MembsUrl),WebRequest.Send() -MembsPage := WebRequest.ResponseText -WebRequest.Open("GET", ValidUrl),WebRequest.Send() -ValidPage := WebRequest.ResponseText - -; Replace special characters -StringReplace, MembsPage, MembsPage, ΜC++, µC++, All -StringReplace, MembsPage, MembsPage, МК-61/52, MK-61/52, All -StringReplace, ValidPage, ValidPage, ΜC++, µC++, All -StringReplace, ValidPage, ValidPage, МК-61/52, MK-61/52, All - -ValidREx := "s)href=""([^""]+)"" title=""Category:([^""]+)"">(?=.*</table>)" -MembsREx := "title=""Category:(.+?)"">.+?\((\d+) members?\)" - -; Iterate through all matches for valid languages -ValidLangs := [], FoundPos := 0 -While FoundPos := RegExMatch(ValidPage, ValidREx, Match, FoundPos+1) - ValidLangs[Match2] := Match1 - -; Iterate through all matches for categories with members -MembsLangs := [], Dupes := [], Detected := 0, FoundPos := 0 -While FoundPos := RegExMatch(MembsPage, MembsREx, Match, FoundPos+1) -{ - ; If it isn't a valid language or is a duplicate, skip it - if !ValidLangs.HasKey(Match1) || Dupes.HasKey(Match1) - continue - - Dupes.Insert(Match1, true) - Detected++ - - ; Initialize this member count - if !IsObject(MembsLangs[Match2]) - MembsLangs[Match2] := [Match1] - else - MembsLangs[Match2].Insert(Match1) -} - -; Sort the languages with the highest member count first -Sorted := [] -for Members, Languages in MembsLangs - Sorted.Insert(1, [Members, Languages]) - -; Initialize the GUI -Gui, New, HwndGuiHwnd -Gui, Add, Text, w300 Center, %Detected% languages detected -Gui, Add, Edit, w300 vSearchText gSearch, Filter languages -Gui, Add, ListView, w300 r20 Grid gOpen vMyListView, Rank|Members|Category - -; Populate the list view -LV_ModifyCol(1, "Integer"), LV_ModifyCol(2, "Integer"), LV_ModifyCol(3, 186) -for Rank, Languages in Sorted - for Key, Language in Languages[2] - LV_Add("", Rank, Languages[1], Language) - -Gui, Show,, Rosetta Code -return - -Open: -if (A_GuiEvent == "DoubleClick") -{ - LV_GetText(Language, A_EventInfo, 3) - Run, % "http://rosettacode.org" ValidLangs[Language] -} -return - -Search: -GuiControlGet, SearchText -GuiControl, -Redraw, MyListView - -LV_Delete() -for Rank, Languages in Sorted - for Key, Language in Languages[2] - if InStr(Language, SearchText) - LV_Add("", Rank, Languages[1], Language) - -GuiControl, +Redraw, MyListView -return - -GuiClose: -ExitApp -return diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/BBC-BASIC/rosetta-code-rank-languages-by-popularity.bbc b/Task/Rosetta-Code-Rank-languages-by-popularity/BBC-BASIC/rosetta-code-rank-languages-by-popularity.bbc deleted file mode 100644 index ee91103384..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/BBC-BASIC/rosetta-code-rank-languages-by-popularity.bbc +++ /dev/null @@ -1,90 +0,0 @@ - INSTALL @lib$+"SORTLIB" - SortUp% = FN_sortinit(0,0) : REM Ascending - SortDown% = FN_sortinit(1,0) : REM Descending - - VDU 23,22,640;512;8,16,16,128+8 : REM Enable UTF-8 support - DIM lang$(1000), tasks%(1000) - NORM_IGNORECASE = 1 - - SYS "LoadLibrary", "URLMON.DLL" TO urlmon% - SYS "GetProcAddress", urlmon%, "URLDownloadToFileA" TO UDTF - - PRINT "Downloading languages list..." - url$ = "http://rosettacode.org/wiki/Category:Programming_Languages" - file$ = @tmp$ + "languages.htm" - SYS UDTF, 0, url$, file$, 0, 0 TO fail% - IF fail% ERROR 100, "File download failed (languages)" - - file% = OPENIN(file$) - index% = 0 - WHILE NOT EOF#file% - REPEAT - a$ = GET$#file% - IF INSTR(a$, "<a href=""/wiki/Category") = 0 EXIT REPEAT - i% = INSTR(a$, "</a>") - IF i% = 0 EXIT REPEAT - j% = i% - REPEAT i% -= 1 : UNTIL MID$(a$,i%,1) = ">" OR i% = 0 - IF i% = 0 EXIT REPEAT - lang$(index%) = MID$(a$, i%+1, j%-i%-1) - IF lang$(index%) <> "Languages" index% += 1 - UNTIL TRUE - ENDWHILE - CLOSE #file% - - C% = index% - CALL SortUp%, lang$(0) - - PRINT "Downloading categories list..." - url$ = "http://www.rosettacode.org/w/index.php" - url$ += "?title=Special:Categories&limit=5000" - file$ = @tmp$ + "categories.htm" - SYS UDTF, 0, url$, file$, 0, 0 TO fail% - IF fail% ERROR 100, "File download failed (categories)" - - file% = OPENIN(file$) - WHILE NOT EOF#file% - REPEAT - a$ = GET$#file% - i% = INSTR(a$, "member") - IF i% = 0 EXIT REPEAT - REPEAT i% -= 1 : UNTIL MID$(a$,i%,1) = "(" OR i% = 0 - IF i% = 0 EXIT REPEAT - tasks% = VAL(MID$(a$, i%+1)) - IF tasks% = 0 EXIT REPEAT - REPEAT i% -= 1 : UNTIL MID$(a$,i%,1) = "<" OR i% = 0 - IF i% = 0 EXIT REPEAT - j% = i% - REPEAT i% -= 1 : UNTIL MID$(a$,i%,1) = ">" OR i% = 0 - IF i% = 0 EXIT REPEAT - k% = FNwhere(lang$(), MID$(a$, i%+1, j%-i%-1), index%-1) - IF k% <> -1 tasks%(k%) += tasks% - UNTIL TRUE - ENDWHILE - CLOSE #file% - - CALL SortDown%, tasks%(0), lang$(0) - - VDU 14 - @% = 3 : REM Column width - PRINT "List of languages as of " TIME$ - FOR i% = 0 TO index%-1 - IF tasks%(i%) = 0 EXIT FOR - PRINT i%+1 ". " tasks%(i%) " - " lang$(i%) - NEXT - END - - DEF FNwhere(a$(), S$, T%) - LOCAL B%, C%, H% - H% = 2 - WHILE H%<T% H% *= 2:ENDWHILE - H% /= 2 - REPEAT - IF (B%+H%)<=T% THEN - SYS "CompareString", 0, NORM_IGNORECASE, S$, -1, a$(B%+H%), -1 TO C% - IF C% >= 2 B% += H% - ENDIF - H% /= 2 - UNTIL H%=0 - SYS "CompareString", 0, NORM_IGNORECASE, S$, -1, a$(B%), -1 TO C% - IF C% = 2 THEN = B% ELSE = -1 diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Bracmat/rosetta-code-rank-languages-by-popularity.bracmat b/Task/Rosetta-Code-Rank-languages-by-popularity/Bracmat/rosetta-code-rank-languages-by-popularity.bracmat deleted file mode 100644 index 83bfd932bc..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Bracmat/rosetta-code-rank-languages-by-popularity.bracmat +++ /dev/null @@ -1,91 +0,0 @@ - ( get-page - = url type - . !arg:(?url.?type) - & sys$(str$("wget -q -O wget.out \"" !url \")) - & get$("wget.out",!type) { Type can be JSN, X ML, HT ML or just ML. } - ) -& ( get-langs - = arr lang - . :?arr - & !arg:? (.h2.) ?arg (h2.?) ? { Only analyse part of page between the h2 elements. } - & whl - ' ( !arg - : ? - ( a - . ? - ( title - . @(?:"Category:" ?):?lang - & !lang !arr:?arr - ) - ? - ) - ?arg - ) - & !arr - ) -& ( get-cats - = page langs list count pat li A Z - . !arg:(?page.?langs) - & 0:?list - & whl - ' ( !langs:%?lang ?langs - & { Use macro substitution to create a fast pattern. } - ' ( ? - (a.? (title.$lang) ?) { $lang is replaced by the actual language. } - ? - (.a.) - @(?:? #?count " " ?) - ) - : (=?pat) - & ( !page - : ?A - ( (li.) ?li (.li.) ?Z - & !li:!pat - ) - & !A !Z:?page { Remove found item from page. (Not necessary at all.)} - & !count - | 0 { The language has no examples. } - . - ) - \L !lang { Bracmat normalizes a\Lx+b\Ly+a\Lz to a\L(x*z)+b\Ly, so } - + !list { it's easy to collect categories with the same count. } - : ?list - ) - & !list - ) -& get-cats - $ ( get-page - $ ( "http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000" - . HT,ML - ) - . get-langs - $ ( get-page - $ ( "http://rosettacode.org/wiki/Category:Programming_Languages" - . HT ML - ) - ) - ) - : ?cats -& :?list -& whl - ' ( !cats:(?count.)\L?tiedcats+?cats - & :?ties - & whl - ' ( !tiedcats:@(?:"Category:" ?name)*?tiedcats - & !ties !name:?ties - ) - & (!count.!ties) !list:?list - ) -& 1:?rank -& whl - ' ( !rank:?tiedRank - & !list:(?count.?ties) ?list - & whl - ' ( !ties:%?name ?ties - & @(!tiedRank:? [?len) { We want some padding for the highest ranks. } - & @(" ":? [!len ?sp) { Skip blanks up to the length of the rank. } - & out$(str$(!sp !tiedRank ". " !count " - " !name)) - & 1+!rank:?rank - ) - ) -& ; diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/C++/rosetta-code-rank-languages-by-popularity.cpp b/Task/Rosetta-Code-Rank-languages-by-popularity/C++/rosetta-code-rank-languages-by-popularity.cpp deleted file mode 100644 index 3bb14c22b4..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/C++/rosetta-code-rank-languages-by-popularity.cpp +++ /dev/null @@ -1,78 +0,0 @@ -#include <string> -#include <boost/regex.hpp> -#include <boost/asio.hpp> -#include <vector> -#include <utility> -#include <iostream> -#include <sstream> -#include <cstdlib> -#include <algorithm> -#include <iomanip> - -struct Sort { //sorting programming languages according to frequency - bool operator( ) ( const std::pair<std::string,int> & a , const std::pair<std::string,int> & b ) - const { - return a.second > b.second ; - } -} ; - -int main( ) { - try { - //setting up an io service , with templated subelements for resolver and query - boost::asio::io_service io_service ; - boost::asio::ip::tcp::resolver resolver ( io_service ) ; - boost::asio::ip::tcp::resolver::query query ( "rosettacode.org" , "http" ) ; - boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ; - boost::asio::ip::tcp::resolver::iterator end ; - boost::asio::ip::tcp::socket socket( io_service ) ; - boost::system::error_code error = boost::asio::error::host_not_found ; - //looking for an endpoint the socket will be able to connect to - while ( error && endpoint_iterator != end ) { - socket.close( ) ; - socket.connect( *endpoint_iterator++ , error ) ; - } - if ( error ) - throw boost::system::system_error ( error ) ; - //we send a request - boost::asio::streambuf request ; - std::ostream request_stream( &request ) ; - request_stream << "GET " << "/mw/index.php?title=Special:Categories&limit=5000" << " HTTP/1.0\r\n" ; - request_stream << "Host: " << "rosettacode.org" << "\r\n" ; - request_stream << "Accept: */*\r\n" ; - request_stream << "Connection: close\r\n\r\n" ; - //send the request - boost::asio::write( socket , request ) ; - //we receive the response analyzing every line and storing the programming language - boost::asio::streambuf response ; - std::istream response_stream ( &response ) ; - boost::asio::read_until( socket , response , "\r\n\r\n" ) ; - boost::regex e( "<li><a href=\"[^<>]+?\">([a-zA-Z\\+#1-9]+?)</a>\\s?\\((\\d+) members\\)</li>" ) ; - //using the wrong regex produces incorrect sorting!! - std::ostringstream line ; - std::vector<std::pair<std::string , int> > languages ; //holds language and number of examples - boost::smatch matches ; - while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) { - line << &response ; - if ( boost::regex_search( line.str( ) , matches , e ) ) { - std::string lang( matches[2].first , matches[2].second ) ; - int zahl = atoi ( lang.c_str( ) ) ; - languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ; - } - line.str( "") ;//we have to erase the string buffer for the next read - } - if ( error != boost::asio::error::eof ) - throw boost::system::system_error( error ) ; - //we sort the vector entries , see the struct above - std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ; - int n = 1 ; - for ( std::vector<std::pair<std::string , int> >::const_iterator spi = languages.begin( ) ; - spi != languages.end( ) ; ++spi ) { - std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right << - spi->second << " - " << spi->first << '\n' ; - n++ ; - } - } catch ( std::exception &ex ) { - std::cout << "Exception: " << ex.what( ) << '\n' ; - } - return 0 ; -} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/C/rosetta-code-rank-languages-by-popularity.c b/Task/Rosetta-Code-Rank-languages-by-popularity/C/rosetta-code-rank-languages-by-popularity.c deleted file mode 100644 index c7ebad89b7..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/C/rosetta-code-rank-languages-by-popularity.c +++ /dev/null @@ -1,77 +0,0 @@ -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -const char * lang_url = "http://www.rosettacode.org/w/api.php?action=query&" - "list=categorymembers&cmtitle=Category:Programming_Languages&" - "cmlimit=500&format=json"; -const char * cat_url = "http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000"; - -#define BLOCK 1024 -char *get_page(const char *url) -{ - char cmd[1024]; - char *ptr, *buf; - int bytes_read = 1, len = 0; - sprintf(cmd, "wget -q \"%s\" -O -", url); - FILE *fp = popen(cmd, "r"); - if (!fp) return 0; - for (ptr = buf = 0; bytes_read > 0; ) { - buf = realloc(buf, 1 + (len += BLOCK)); - if (!ptr) ptr = buf; - bytes_read = fread(ptr, 1, BLOCK, fp); - if (bytes_read <= 0) break; - ptr += bytes_read; - } - *++ptr = '\0'; - return buf; -} - -char ** get_langs(char *buf, int *l) -{ - char **arr = 0; - for (*l = 0; (buf = strstr(buf, "Category:")) && (buf += 9); ++*l) - for ( (*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf; - *buf != '"' || (*buf++ = 0); - buf++); - - return arr; -} - -typedef struct { const char *name; int count; } cnt_t; -cnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len) -{ - char str[1024], *found; - cnt_t *list = 0; - int i, llen = 0; - for (i = 0; i < len; i++) { - sprintf(str, "/wiki/Category:%s", langs[i]); - if (!(found = strstr(buf, str))) continue; - buf = found + strlen(str); - - if (!(found = strstr(buf, "</a> ("))) continue; - list = realloc(list, sizeof(cnt_t) * ++llen); - list[llen - 1].name = langs[i]; - list[llen - 1].count = strtol(found + 6, 0, 10); - } - *ret_len = llen; - return list; -} - -int _scmp(const void *a, const void *b) -{ - int x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count; - return x < y ? -1 : x > y; -} - -int main() -{ - int len, clen; - char ** langs = get_langs(get_page(lang_url), &len); - cnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen); - qsort(cats, clen, sizeof(cnt_t), _scmp); - while (--clen >= 0) - printf("%4d %s\n", cats[clen].count, cats[clen].name); - - return 0; -} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Cache-ObjectScript/rosetta-code-rank-languages-by-popularity.cos b/Task/Rosetta-Code-Rank-languages-by-popularity/Cache-ObjectScript/rosetta-code-rank-languages-by-popularity.cos deleted file mode 100644 index 5259479c61..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Cache-ObjectScript/rosetta-code-rank-languages-by-popularity.cos +++ /dev/null @@ -1,80 +0,0 @@ -Class Utils.Net.RosettaCode [ Abstract ] -{ - -ClassMethod GetTopLanguages(pHost As %String = "", pPath As %String = "", pTop As %Integer = 10) As %Status -{ - // check input parameters - If $Match(pHost, "^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$")=0 { - Quit $$$ERROR($$$GeneralError, "Invalid host name.") - } - - // create http request and get page - Set req=##class(%Net.HttpRequest).%New() - Set req.Server=pHost - Do req.Get(pPath) - - // create xml stream with doc type - Set xml=##class(%Stream.GlobalCharacter).%New() - Set sc=xml.WriteLine("<!DOCTYPE doc_type [") - Set sc=xml.WriteLine($Char(9)_"<!ENTITY nbsp ' '>") - Set sc=xml.WriteLine($Char(9)_"<!ENTITY amp '&'>") - Set sc=xml.WriteLine("]>") - - // copy xhtml stream to xml stream - Set xhtml=req.HttpResponse.Data - Set xhtml.LineTerminator=$Char(10) - While 'xhtml.AtEnd { - Set line=xhtml.ReadLine() - If line["!DOCTYPE" Continue - If line["<g:plusone></g:plusone>" { - Continue - Set line="<g:plusone xmlns:g='http://base.google.com/ns/1.0'></g:plusone>" - } - Set sc=xml.WriteLine(line) - } - - // create an instance of an %XML.XPATH.Document - Set sc=##class(%XML.XPATH.Document).CreateFromStream(xml, .xdoc) - If $$$ISERR(sc) Quit sc - - // evaluate following 'XPath' expression - Set sc=xdoc.EvaluateExpression("//div[@id='bodyContent']//li", "a[contains(@href, '/Category:')]/ancestor::li", .res) - - // iterate through list elements - Set array=##class(%ArrayOfDataTypes).%New() - Do { - Set dom=res.GetNext(.key) - If '$IsObject(dom) Quit - - // get language name and members - Set lang="" - While dom.Read() { - If 'dom.HasValue Continue - If lang="" { - If $Locate(dom.Value, "User|Tasks|Omit|attention|operations|Solutions by") Quit - Set lang=dom.Value Continue - } - If dom.Value["members" { - Set members=+$ZStrip(dom.Value, "<>P") - Set list=array.GetAt(members) - Set $List(list, $ListLength(list)+1)=lang - Set sc=array.SetAt(list, members) - Quit - } - } - } While key'="" - If array.Count()=0 Quit $$$ERROR($$$GeneralError, "No languages found.") - - // show top entries - Write "Top "_pTop_" Languages (as at "_$ZDate($HoroLog, 2)_"):", ! - For count=1:1:pTop { - Set members=array.GetPrevious(.key) - If key="" Quit - Write $Justify(count, 3), ". ", key, " - ", $ListToString(members, ", "), ! - } - - // finished - Quit $$$OK -} - -} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/D/rosetta-code-rank-languages-by-popularity.d b/Task/Rosetta-Code-Rank-languages-by-popularity/D/rosetta-code-rank-languages-by-popularity.d deleted file mode 100644 index 840be3d71d..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/D/rosetta-code-rank-languages-by-popularity.d +++ /dev/null @@ -1,20 +0,0 @@ -void main() { - import std.stdio, std.algorithm, std.conv, std.array, std.regex, - std.typecons, std.net.curl; - - immutable r1 = `"title":"Category:([^"]+)"`; - const languages = get("www.rosettacode.org/w/api.php?action=query"~ - "&list=categorymembers&cmtitle=Category:Pro"~ - "gramming_Languages&cmlimit=500&format=json") - .matchAll(r1).map!q{ a[1].dup }.array; - - auto pairs = get("www.rosettacode.org/w/index.php?" ~ - "title=Special:Categories&limit=5000") - .matchAll(`title="Category:([^"]+)">[^<]+` ~ - `</a>[^(]+\((\d+) members\)`) - .filter!(m => languages.canFind(m[1])) - .map!(m => tuple(m[2].to!uint, m[1].dup)); - - foreach (i, res; pairs.array.sort!q{a > b}.release) - writefln("%3d. %3d - %s", i + 1, res[]); -} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Erlang/rosetta-code-rank-languages-by-popularity.erl b/Task/Rosetta-Code-Rank-languages-by-popularity/Erlang/rosetta-code-rank-languages-by-popularity.erl deleted file mode 100644 index 25d240d82c..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Erlang/rosetta-code-rank-languages-by-popularity.erl +++ /dev/null @@ -1,60 +0,0 @@ --module( rank_languages_by_popularity ). - --export( [task/0] ). - --record( print_fold, {place=0, place_step=1, previous_count=0} ). - -task() -> - ok = find_unimplemented_tasks:init(), - Category_programming_languages = find_unimplemented_tasks:rosetta_code_list_of( "Programming_Languages" ), - Programming_languages = [X || "Category:" ++ X <- Category_programming_languages], - {ok, {{_HTTP,200,"OK"}, _Headers, Body}} = httpc:request( "http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000" ), - Count_categories = lists:sort( [{Y, X} || {X, Y} <- category_counts(Body, []), lists:member(X, Programming_languages)] ), - lists:foldr( fun place_count_category_write/2, #print_fold{}, Count_categories ). - - - -category_counts( "", [[] | Acc] ) -> Acc; -category_counts( String, Acc ) -> - {Begin, End} = category_count_begin_end( String ), - {Category_count, String_continuation} = category_count_extract( String, Begin, End ), - category_counts( String_continuation, [Category_count | Acc] ). - -category_count_begin_end( String ) -> - Begin = string:str( String, "/wiki/Category:" ), - End = string:str( string:substr(String, Begin), " member" ), - category_count_begin_end( Begin, End, erlang:length(" member") ). - -category_count_begin_end( _Begin, 0, _End_length ) -> {0, 0}; -category_count_begin_end( Begin, End, End_length ) -> - {Begin, Begin + End + End_length}. - -category_count_extract( _String, 0, _End ) -> {[], ""}; -category_count_extract( String, Begin, End ) -> - Category_count = category_count_extract( string:substr(String, Begin, End - Begin) ), - {Category_count, string:substr( String, End + 1 )}. - -category_count_extract( "/wiki/Category:" ++ T ) -> - Category_member = string:tokens( T, " " ), - Category = category_count_extract_category( Category_member ), - Member = category_count_extract_count( lists:reverse(Category_member) ), - {Category, Member}. - -category_count_extract_category( [Category | _T] ) -> - lists:map( fun category_count_extract_category_map/1, string:strip(Category, right, $") ). - -category_count_extract_category_map( $_ ) -> $\s; -category_count_extract_category_map( Character ) -> Character. - -category_count_extract_count( ["member" ++ _, "(" ++ N | _T] ) -> erlang:list_to_integer( N ); -category_count_extract_count( _T ) -> 0. - -place_count_category_write( {Count, Category}, Acc ) -> - Print_fold = place_count_category_write( Count, Acc ), - io:fwrite("~p. ~p - ~p~n", [Print_fold#print_fold.place, Count, Category] ), - Print_fold; - -place_count_category_write( Count, #print_fold{place_step=Place_step, previous_count=Count}=Print_fold ) -> - Print_fold#print_fold{place_step=Place_step + 1}; -place_count_category_write( Count, #print_fold{place=Place, place_step=Place_step} ) -> - #print_fold{place=Place + Place_step, previous_count=Count}. diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Go/rosetta-code-rank-languages-by-popularity.go b/Task/Rosetta-Code-Rank-languages-by-popularity/Go/rosetta-code-rank-languages-by-popularity.go deleted file mode 100644 index cd56083abe..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Go/rosetta-code-rank-languages-by-popularity.go +++ /dev/null @@ -1,115 +0,0 @@ -package main - -import ( - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "log" - "net/http" - "net/url" - "regexp" - "sort" - "strconv" - "strings" -) - -var baseQuery = "http://rosettacode.org/mw/api.php?action=query" + - "&format=xml&list=categorymembers&cmlimit=500" - -func req(u string, foundCm func(string)) string { - resp, err := http.Get(u) - if err != nil { - log.Fatal(err) // connection or request fail - } - defer resp.Body.Close() - for p := xml.NewDecoder(resp.Body); ; { - t, err := p.RawToken() - switch s, ok := t.(xml.StartElement); { - case err == io.EOF: - return "" - case err != nil: - log.Fatal(err) - case !ok: - continue - case s.Name.Local == "cm": - for _, a := range s.Attr { - if a.Name.Local == "title" { - foundCm(a.Value) - } - } - case s.Name.Local == "categorymembers" && len(s.Attr) > 0 && - s.Attr[0].Name.Local == "cmcontinue": - return url.QueryEscape(s.Attr[0].Value) - } - } - return "" -} - -// satisfy sort interface (reverse sorting) -type pop struct { - string - int -} -type popList []pop - -func (pl popList) Len() int { return len(pl) } -func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] } -func (pl popList) Less(i, j int) bool { - switch d := pl[i].int - pl[j].int; { - case d > 0: - return true - case d < 0: - return false - } - return pl[i].string < pl[j].string -} - -func main() { - // get languages, store in a map - langMap := make(map[string]bool) - storeLang := func(cm string) { - if strings.HasPrefix(cm, "Category:") { - cm = cm[9:] - } - langMap[cm] = true - } - languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages" - continueAt := req(languageQuery, storeLang) - for continueAt != "" { - continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang) - } - // allocate slice for sorting - s := make(popList, 0, len(langMap)) - - // get big list of categories - resp, err := http.Get("http://rosettacode.org/mw/index.php" + - "?title=Special:Categories&limit=5000") - if err != nil { - log.Fatal(err) - } - page, err := ioutil.ReadAll(resp.Body) - resp.Body.Close() - - // split out fields of interest and populate sortable slice - rx := regexp.MustCompile("<li><a.*>(.*)</a>.*[(]([0-9]+) member") - for _, sm := range rx.FindAllSubmatch(page, -1) { - ls := string(sm[1]) - if langMap[ls] { - if n, err := strconv.Atoi(string(sm[2])); err == nil { - s = append(s, pop{ls, n}) - } - } - } - - // output - sort.Sort(s) - lastCnt, lastIdx := -1, 1 - for i, lang := range s { - if lang.int != lastCnt { - lastCnt = lang.int - lastIdx = i + 1 - } - fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string) - } -} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Groovy/rosetta-code-rank-languages-by-popularity.groovy b/Task/Rosetta-Code-Rank-languages-by-popularity/Groovy/rosetta-code-rank-languages-by-popularity.groovy deleted file mode 100644 index 8012045e73..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Groovy/rosetta-code-rank-languages-by-popularity.groovy +++ /dev/null @@ -1,9 +0,0 @@ -def html = new URL('http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000').getText([ - connectTimeout:500, - readTimeout:15000, - requestProperties: [ 'User-Agent': 'Firefox/2.0.0.4']]) -def count = [:] -(html =~ '<li><a[^>]+>([^<]+)</a>[^(]*[(](\\d+) member[s]*[)]</li>').each { match, language, members -> - count[language] = (members as int) -} -count.sort { v1, v2 -> v2.value <=> v1.value }.eachWithIndex { value, index -> println "${index + 1} $value" } diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Haskell/rosetta-code-rank-languages-by-popularity.hs b/Task/Rosetta-Code-Rank-languages-by-popularity/Haskell/rosetta-code-rank-languages-by-popularity.hs deleted file mode 100644 index d6b79802c4..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Haskell/rosetta-code-rank-languages-by-popularity.hs +++ /dev/null @@ -1,35 +0,0 @@ -import Network.Browser -import Network.HTTP -import Network.URI -import Data.List -import Data.Maybe -import Text.XML.Light -import Control.Arrow -import Data.Ord - -getRespons url = do - rsp <- Network.Browser.browse $ do - setAllowRedirects True - setOutHandler $ const (return ()) -- quiet - request $ getRequest url - return $ rspBody $ snd rsp - - -mostPopLang = do - rsp <-getRespons $ "http://www.rosettacode.org/w/api.php?action=query&list=" ++ - "categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=xml" - mbrs <- getRespons "http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000" - let xmls = onlyElems $ parseXML rsp - langs = concatMap (map ((\\"Category:"). fromJust.findAttr (unqual "title")). filterElementsName (== unqual "cm")) xmls - - let catMbr = second (read.takeWhile(/=' '). drop 6). break (=='<'). drop 1. dropWhile(/='>') . drop 5 - catNmbs :: [(String, Int)] - catNmbs = map catMbr $ filter (isPrefixOf "<li>") $ lines mbrs - printFmt (n,(l,m)) = putStrLn $ take 6 (show n ++ ". ") ++ (show m) ++ " " ++ l - toMaybe (a,b) = - case b of - Just x -> Just (a,x) - _ -> Nothing - - mapM_ printFmt $ zip [1..] $ sortBy (flip (comparing snd)) - $ mapMaybe (toMaybe. (id &&& flip lookup catNmbs)) langs diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/HicEst/rosetta-code-rank-languages-by-popularity-1.hicest b/Task/Rosetta-Code-Rank-languages-by-popularity/HicEst/rosetta-code-rank-languages-by-popularity-1.hicest deleted file mode 100644 index d2435ac0e0..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/HicEst/rosetta-code-rank-languages-by-popularity-1.hicest +++ /dev/null @@ -1,33 +0,0 @@ -CHARACTER cats*50000, catlist*50000, sortedCat*50000, sample*100 -DIMENSION RankNr(1) - - READ(ClipBoard) cats - catlist = ' ' - pos = 1 ! find language entries like * 100 doors (2 members) - nr = 0 - ! after next '*' find next "name" = '100 doors' and next "(...)" = '(2 members)' : -1 EDIT(Text=cats, SetPos=pos, Right='*', R, Mark1, R='(', Left, M2, Parse=name, R=2, P=members, GetPos=pos) - IF(pos > 0) THEN - READ(Text=members) count - IF(count > 0) THEN - nr = nr + 1 - WRITE(Text=catlist, Format='i4, 1x, 2a', APPend) count, name, ';' - ENDIF - GOTO 1 ! no WHILE in HicEst - ENDIF ! catlist is now = " 1 ... User ; 2 100 doors ; 3 3D ; 8 4D ; ..." - - ALLOCATE(RankNr, nr) - EDIT(Text=catlist, SePaRators=';', Option=1+4, SorTtoIndex=RankNr) ! case (1) and back (4) - - sortedCat = ' ' ! get the sorted list in the sequence of RankNr: - ok = 0 - DO i = 1, nr - EDIT(Text=catlist, SePaRators=';', ITeM=RankNr(i), CoPyto=sample) - discard = EDIT(Text=sample, LeXicon='user,attention,solutions,tasks,program,language,implementation,') - IF(discard == 0) THEN ! removes many of the non-language entries - ok = ok + 1 - WRITE(Text=sortedCat, APPend, Format='F5.0, 2A') ok, TRIM(sample), $CRLF - ENDIF - ENDDO - DLG(Text=sortedCat, Format=$CRLF) -END diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/HicEst/rosetta-code-rank-languages-by-popularity-2.hicest b/Task/Rosetta-Code-Rank-languages-by-popularity/HicEst/rosetta-code-rank-languages-by-popularity-2.hicest deleted file mode 100644 index aa7f0f9d91..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/HicEst/rosetta-code-rank-languages-by-popularity-2.hicest +++ /dev/null @@ -1,12 +0,0 @@ -2010-04-24 18:31 -Top 10 entries (not all are languages) - 1. 394 Tcl - 2. 363 Python - 3. 346 Ruby - 4. 328 J - 5. 319 C - 6. 317 OCaml - 7. 315 Haskell - 8. 298 Perl - 9. 288 WikiStubs - 10. 281 Common Lisp diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/HicEst/rosetta-code-rank-languages-by-popularity-3.hicest b/Task/Rosetta-Code-Rank-languages-by-popularity/HicEst/rosetta-code-rank-languages-by-popularity-3.hicest deleted file mode 100644 index 5b9eb91212..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/HicEst/rosetta-code-rank-languages-by-popularity-3.hicest +++ /dev/null @@ -1,18 +0,0 @@ -require 'web/gethttp xml/sax/x2j regex' - -x2jclass 'rcPopLang' - -rx =: (<0 1) {:: (2#a:) ,~ rxmatches rxfrom ] - -'Popular Languages' x2jDefn - / := langs : langs =: 0 2 $ a: - html/body/div/div/div/ul/li := langs =: langs ,^:(a:~:{.@[)~ lang ; ' \((\d+) members?\)' rx y - html/body/div/div/div/ul/li/a := lang =: '^\s*((?:.(?!User|Tasks|Omit|attention|operations|by))+)\s*$' rx y -) - -cocurrent'base' - -sortTab =. \: __ ". [: ;:^:_1: {:"1 -formatTab =: [: ;:^:_1: [: (20 A. (<'-') , |. , [: ('.' <"1@:,.~ ":) 1 + 1 i.@,~ 1{$)&.|: sortTab f. - -rcPopLangs =: formatTab@:process_rcPopLang_@:gethttp diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/HicEst/rosetta-code-rank-languages-by-popularity-4.hicest b/Task/Rosetta-Code-Rank-languages-by-popularity/HicEst/rosetta-code-rank-languages-by-popularity-4.hicest deleted file mode 100644 index 1e31405be4..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/HicEst/rosetta-code-rank-languages-by-popularity-4.hicest +++ /dev/null @@ -1,11 +0,0 @@ - 10 {. rcPopLangs 'http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=2000' - 1. 687 - Tcl - 2. 646 - Python - 3. 637 - C - 4. 626 - PicoLisp - 5. 612 - J - 6. 587 - Go - 7. 556 - Ada - 8. 550 - D - 9. 549 - Mathematica - 10. 526 - Perl diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-1.icon b/Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-1.icon deleted file mode 100644 index dbbb6f9781..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-1.icon +++ /dev/null @@ -1,45 +0,0 @@ -$define RCLANGS "http://rosettacode.org/mw/api.php?format=xml&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo" -$define RCUA "User-Agent: Unicon Rosetta 0.1" -$define RCXUA "X-Unicon: http://unicon.org/" - -link strings -link hexcvt - -procedure main() - cnt := create seq() - last := -1 - every pair := !reverse(sort(tallyPages(),2)) do { - n := if last ~=:= pair[2] then @cnt else (@cnt,"") - write(right(n,4),": ",left(pair[1],30,". "),right(pair[2],10,". ")) - } -end - -# Generate page counts for each language -procedure tallyPages(url) - /url := RCLANGS - counts := table() - continue := "" - while \(txt := ReadURL(url||continue)) do { - txt ? { - while tab(find("<page ") & find(s := "title=\"Category:")+*s) do { - lang := tab(upto('"')) - tab(find(s := "pages=\"")+*s) - counts[lang] := numeric(tab(upto('"'))) - } - if tab(find("cmcontinue=")) then { - continue := "&"||tab(upto(' \t')) - } - else return counts - } - } -end - -procedure ReadURL(url) #: read URL into string - page := open(url,"m",RCUA,RCXUA) | stop("Unable to open ",url) - text := "" - if page["Status-Code"] < 300 then while text ||:= reads(page,-1) - else write(&errout,image(url),": ", - page["Status-Code"]," ",page["Reason-Phrase"]) - close(page) - return text -end diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-2.icon b/Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-2.icon deleted file mode 100644 index 5b9eb91212..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-2.icon +++ /dev/null @@ -1,18 +0,0 @@ -require 'web/gethttp xml/sax/x2j regex' - -x2jclass 'rcPopLang' - -rx =: (<0 1) {:: (2#a:) ,~ rxmatches rxfrom ] - -'Popular Languages' x2jDefn - / := langs : langs =: 0 2 $ a: - html/body/div/div/div/ul/li := langs =: langs ,^:(a:~:{.@[)~ lang ; ' \((\d+) members?\)' rx y - html/body/div/div/div/ul/li/a := lang =: '^\s*((?:.(?!User|Tasks|Omit|attention|operations|by))+)\s*$' rx y -) - -cocurrent'base' - -sortTab =. \: __ ". [: ;:^:_1: {:"1 -formatTab =: [: ;:^:_1: [: (20 A. (<'-') , |. , [: ('.' <"1@:,.~ ":) 1 + 1 i.@,~ 1{$)&.|: sortTab f. - -rcPopLangs =: formatTab@:process_rcPopLang_@:gethttp diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-3.icon b/Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-3.icon deleted file mode 100644 index 1e31405be4..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-3.icon +++ /dev/null @@ -1,11 +0,0 @@ - 10 {. rcPopLangs 'http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=2000' - 1. 687 - Tcl - 2. 646 - Python - 3. 637 - C - 4. 626 - PicoLisp - 5. 612 - J - 6. 587 - Go - 7. 556 - Ada - 8. 550 - D - 9. 549 - Mathematica - 10. 526 - Perl diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Mathematica/rosetta-code-rank-languages-by-popularity.math b/Task/Rosetta-Code-Rank-languages-by-popularity/Mathematica/rosetta-code-rank-languages-by-popularity.math deleted file mode 100644 index a8a89b94c5..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Mathematica/rosetta-code-rank-languages-by-popularity.math +++ /dev/null @@ -1,5 +0,0 @@ -Languages = Flatten[Import["http://rosettacode.org/wiki/Category:Programming_Languages","Data"][[1,1]]]; -Languages = Most@StringReplace[Languages, {" " -> "_", "+" -> "%2B"}]; -b = {#, If[# === {}, 0, #[[1]]]&@( StringCases[Import["http://rosettacode.org/wiki/Category:"<>#,"Plaintext"], - "category, out of " ~~ x:NumberString ~~ " total" ->x])} &/@ Languages; -For[i = 1, i < Length@b , i++ , Print[i, ". ", #[[2]], " - ", #[[1]] ]&@ Part[Reverse@SortBy[b, Last], i]] diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Objeck/rosetta-code-rank-languages-by-popularity.objeck b/Task/Rosetta-Code-Rank-languages-by-popularity/Objeck/rosetta-code-rank-languages-by-popularity.objeck deleted file mode 100644 index a13790c030..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Objeck/rosetta-code-rank-languages-by-popularity.objeck +++ /dev/null @@ -1,80 +0,0 @@ -use HTTP; -use RegEx; -use XML; -use Collection; - -class RosettaRank { - function : Main(args : String[]) ~ Nil { - langs_xml := ""; - client := HttpClient->New(); - in := client->Get("http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=5000&format=xml"); - each(i : in) { - langs_xml += in->Get(i)->As(String); - }; - - langs := StringSet->New(); - parser := XmlParser->New(langs_xml); - if(parser->Parse()) { - # get first item - results := parser->FindElements("/api/query/categorymembers/cm"); - each(i : results) { - element := results->Get(i)->As(XmlElement); - name := element->GetAttribute("title")->GetValue(); - offset := name->Find(':'); - if(offset > -1) { - lang := name->SubString(offset + 1, name->Size() - offset - 1); - langs->Insert(lang->ReplaceAll(" ", " ")); - }; - }; - }; - - langs_counts := IntMap->New(); - client := HttpClient->New(); - html := client->Get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"); - each(i : html) { - lines := html->Get(i)->As(String); - html_elements := lines->Split("\n"); - each(j : html_elements) { - element := html_elements[j]; - name : String; count : String; - regex := RegEx->New("<li><a href=\"(\\w|\\s|/|\\?|\\&|;|:|#)+\"\\stitle=\"Category:(\\w|\\s|#)+\">"); - found := regex->FindFirst(element); - if(found <> Nil) { - group1 := found->Size(); - regex := RegEx->New("(\\w|\\s)+"); - found := regex->Match(element, group1); - if(found <> Nil & found->Size() > 0) { - name := found; - # skip over some junk characters - group2 := group1 + found->Size() + 10; - regex := RegEx->New("\\s\\("); - found := regex->Match(element, group2); - if(found <> Nil) { - group3 := group2 + found->Size(); - regex := RegEx->New("\\d+"); - found := regex->Match(element, group3); - if(found <> Nil & found->Size() > 0) { - count := found; - }; - }; - }; - }; - - if(name <> Nil & count <> Nil) { - if(langs->Has(name)) { - langs_counts->Insert(count->ToInt(), name); - }; - name := Nil; count := Nil; - }; - }; - }; - - keys := langs_counts->GetKeys(); - count := 1; - for(i := keys->Size() - 1; i >= 0; i -=1;) { - key := keys->Get(i); - IO.Console->Print(count)->Print(". ")->Print(key)->Print(" - ")->PrintLine(langs_counts->Find(key)->As(String)); - count += 1; - }; - } -} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Oz/rosetta-code-rank-languages-by-popularity.oz b/Task/Rosetta-Code-Rank-languages-by-popularity/Oz/rosetta-code-rank-languages-by-popularity.oz deleted file mode 100644 index 21cedc9ead..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Oz/rosetta-code-rank-languages-by-popularity.oz +++ /dev/null @@ -1,40 +0,0 @@ -declare - [HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']} - [Regex] = {Module.link ['x-oz://contrib/regex']} - - fun {GetPage RawUrl} - Client = {New HTTPClient.urlGET init(inPrms(toFile:false toStrm:true) _)} - Url = {VirtualString.toString RawUrl} - OutParams - HttpResponseParams - in - {Client getService(Url ?OutParams ?HttpResponseParams)} - {Client closeAll(true)} - OutParams.sOut - end - - fun {GetCategories Doc} - {Map {Regex.allMatches "<li><a[^>]+>([^<]+)</a> \\(([0-9]+) member" Doc} - fun {$ Match} - Category = {Regex.group 1 Match Doc} - Count = {String.toInt {ByteString.toString {Regex.group 2 Match Doc}}} - in - Category#Count - end - } - end - - Url = "http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000" - - {System.showInfo "Retrieving..."} - Doc = {GetPage Url} - - {System.showInfo "Parsing..."} - Cs = {GetCategories Doc} -in - for - Cat#Count in {Sort Cs fun {$ _#C1 _#C2} C1 > C2 end} - I in 1..20 - do - {System.showInfo I#". "#Count#" - "#Cat} - end diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Perl-6/rosetta-code-rank-languages-by-popularity.pl6 b/Task/Rosetta-Code-Rank-languages-by-popularity/Perl-6/rosetta-code-rank-languages-by-popularity.pl6 deleted file mode 100644 index 474201cd18..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Perl-6/rosetta-code-rank-languages-by-popularity.pl6 +++ /dev/null @@ -1,22 +0,0 @@ -my $languages = qx{wget -O - 'http://rosettacode.org/wiki/Category:Programming_Languages'}; -my $categories = qx{wget -O - 'http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000'}; - -my @lines = $languages.lines; -shift @lines until @lines[0] ~~ / '<h2>Subcategories</h2>' /; -my \languages = set gather for @lines { - last if / '/bodycontent' /; - take ~$0 if - / '<li><a href="/wiki/Category:' .*? '" title="Category:' .*? '">' (.*?) '</a></li>' /; -} - -@lines = $categories.lines; -my @results = sort -*.[0], gather for @lines { - take [+$1, ~$0] if - / '<li><a href="/wiki/Category:' .*? '" title="Category:' .*? '">' - (.*?) <?{ ~$0 ∈ languages }> - '</a>' .*? '(' (\d+) ' member' /; -} - -for @results.kv -> $i, @l { - printf "%d:\t%3d - %s\n", $i+1, |@l; -} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Perl/rosetta-code-rank-languages-by-popularity.pl b/Task/Rosetta-Code-Rank-languages-by-popularity/Perl/rosetta-code-rank-languages-by-popularity.pl deleted file mode 100644 index c75cf07308..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Perl/rosetta-code-rank-languages-by-popularity.pl +++ /dev/null @@ -1,17 +0,0 @@ -use MediaWiki::API; -my $api = new MediaWiki::API({api_url => 'http://rosettacode.org/mw/api.php'}); - -my @pairs = - sort {$b->[1] <=> $a->[1] or $a->[0] cmp $b->[0]} - map {$_->{title} =~ s/\ACategory://; - [$_->{title}, $_->{categoryinfo}{size} || 0];} - values %{$api->api - ({action => 'query', - generator => 'categorymembers', - gcmtitle => 'Category:Programming Languages', - gcmlimit => 'max', - prop => 'categoryinfo'})->{query}{pages}}; - -for (my $n = 1 ; @pairs ; ++$n) - {my ($lang, $tasks) = @{shift @pairs}; - printf "%3d. %3d - %s\n", $n, $tasks, $lang;} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/PicoLisp/rosetta-code-rank-languages-by-popularity.l b/Task/Rosetta-Code-Rank-languages-by-popularity/PicoLisp/rosetta-code-rank-languages-by-popularity.l deleted file mode 100644 index faa76c92eb..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/PicoLisp/rosetta-code-rank-languages-by-popularity.l +++ /dev/null @@ -1,14 +0,0 @@ -(load "@lib/http.l") - -(for (I . X) - (flip - (sort - (make - (client "rosettacode.org" 80 - "mw/index.php?title=Special:Categories&limit=5000" - (while (from "<li><a href=\"/wiki/Category:") - (let Cat (till "\"") - (from "(") - (when (format (till " " T)) - (link (cons @ (ht:Pack Cat))) ) ) ) ) ) ) ) - (prinl (align 3 I) ". " (car X) " - " (cdr X)) ) diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/PureBasic/rosetta-code-rank-languages-by-popularity.purebasic b/Task/Rosetta-Code-Rank-languages-by-popularity/PureBasic/rosetta-code-rank-languages-by-popularity.purebasic deleted file mode 100644 index 8807f058a5..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/PureBasic/rosetta-code-rank-languages-by-popularity.purebasic +++ /dev/null @@ -1,40 +0,0 @@ -Structure Language - count.i - Name.s -EndStructure - -Dim Row.Language(2000) - -; Lines has been split to fit RC's 80 char preferences -ignore$ = "Basic language learning Encyclopedia Implementations " -ignore$ + "Language Implementations Language users " -ignore$ + "Maintenance/OmitCategoriesCreated Programming Languages " -ignore$ + "Programming Tasks RCTemplates Solutions by Library Solutions by " -ignore$ + "Programming Language Solutions by Programming Task Unimplemented " -ignore$ + "tasks by language WikiStubs Examples needing attention " -ignore$ + "Impl needed" - -URL$="http://www.rosettacode.org/w/index.php?" -URL$+"title=Special:Categories&limit=5000" - -URLDownloadToFile_( #Null, URL$, "special.htm", 0, #Null) -ReadFile(0, "special.htm") -While Not Eof(0) - i + 1 - x1$ = ReadString(0) - x2$ = Mid(x1$, FindString(x1$, "member", 1) - 4 , 3) - Row(i)\count = Val(Trim(RemoveString(x2$, "("))) - - x3$ = Mid(x1$, FindString(x1$, Chr(34) + ">", 1) + 2, 30) - Row(i)\Name = Left(x3$, FindString(x3$, "<", 1) - 1) - If FindString(ignore$, Row(i)\Name, 1) Or Row(i)\Name = "" - Row(i)\count = 0 - EndIf -Wend -offset=OffsetOf(Language\count) -SortStructuredArray(Row(), #PB_Sort_Descending, offset, #PB_Sort_Integer) -OpenConsole() -For i = 0 To 20 - PrintN( Str(i + 1) + ". " + Str(Row(i)\count) + " - " + Row(i)\Name) -Next -Input() diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Python/rosetta-code-rank-languages-by-popularity.py b/Task/Rosetta-Code-Rank-languages-by-popularity/Python/rosetta-code-rank-languages-by-popularity.py deleted file mode 100644 index 7cbbc61509..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Python/rosetta-code-rank-languages-by-popularity.py +++ /dev/null @@ -1,14 +0,0 @@ -import urllib, re - -key1 = lambda x: int(x[1]) - -get1 = urllib.urlopen("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json").read() -get2 = urllib.urlopen("http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000").read() - -langs = re.findall("\"title\":\"Category:(.+?)\"",get1) -qtdmbr = re.findall("title=\"Category:(.+?)\">.+?</a> \((\d+) members\)",get2) - -result = [(x,int(y)) for x,y in qtdmbr if x in langs] - -for n, i in enumerate(sorted(result,key=key1,reverse=True)): - print "%3d. %3d - %s" % (n+1, i[1], i[0]) diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/R/rosetta-code-rank-languages-by-popularity.r b/Task/Rosetta-Code-Rank-languages-by-popularity/R/rosetta-code-rank-languages-by-popularity.r deleted file mode 100644 index 7f981247df..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/R/rosetta-code-rank-languages-by-popularity.r +++ /dev/null @@ -1,15 +0,0 @@ -library(RJSONIO) -langUrl <- "http://rosettacode.org/mw/api.php?action=query&format=json&cmtitle=Category:Solutions_by_Programming_Language&list=categorymembers&cmlimit=500" - -languages <- fromJSON(langUrl)$query$categorymembers -languages <- sapply(languages, function(x) sub("Category:", "", x$title)) - -# fails if there are more than 500 users per language -user <- function (lang) { - userBaseUrl <- "http://rosettacode.org/mw/api.php?action=query&format=json&list=categorymembers&cmlimit=500&cmtitle=Category:" - userUrl <- paste(userBaseUrl, URLencode(paste(lang, " User", sep="")),sep="") - length(fromJSON(userUrl)$query$categorymembers) -} - -users <- sapply(languages, user) -head(sort(users, decreasing=TRUE),15) diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/README b/Task/Rosetta-Code-Rank-languages-by-popularity/README deleted file mode 100644 index 067cecc460..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/README +++ /dev/null @@ -1 +0,0 @@ -Data source: http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/REXX/rosetta-code-rank-languages-by-popularity.rexx b/Task/Rosetta-Code-Rank-languages-by-popularity/REXX/rosetta-code-rank-languages-by-popularity.rexx deleted file mode 100644 index 474daa148f..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/REXX/rosetta-code-rank-languages-by-popularity.rexx +++ /dev/null @@ -1,111 +0,0 @@ -/*REXX pgm reads 2 files, shows a ranked list of Rosetta Code languages.*/ -sep='█'; L.=0; #.=0; u.=0; catHeap=; old.= /*assign variable defaults. */ -parse arg cutoff CinFID LinFID outFID . /*obtain specified options. */ -if cutoff==',' | cutoff=='' then cutoff=0 /*assume no cutoff default. */ -if CinFID=='' then CinFID = 'RC_POP.CAT' /*Not specified? Use default.*/ -if LinFID=='' then LinFID = 'RC_POP.LAN' /* " " " " */ -if outFID=='' then outFID = 'RC_POP.OUT' /* " " " " */ -call tell center('timestamp: ' date() time('Civil'),79,'═'), 2, 1 -call reader 'lang' /*assign to L.ααα */ -call reader 'cat' /*append to the catHeap*/ -#=0 /*number of categories.*/ - do j=1 until catHeap=='' /*process heap of cats.*/ - parse var catHeap cat.j (sep) catHeap /*pick off a category. */ - parse var cat.j cat.j '<' "(" mems . /*untangle the string. */ - cat.j=space(cat.j); _=cat.j; upper _ /*remove excess blanks.*/ - if _=='' | \L._ then iterate /*blank or ¬ a language*/ - if \datatype(mems,'W') then iterate /*"members" ¬ numeric.*/ - #.0=#.0+mems /*bump #members found. */ - if u._\==0 then do /*[↓] handle duplicates*/ - do f=1 for # until _==@u.f - end /*f*/ - #.f=#.f+mems; iterate j - end /* [↑] languages that are in different cases.*/ - u._=u._+1 - #=#+1; #.#=#.#+mems; @.#=cat.j; @u.#=_ /*bump counter, assign.*/ - end /*j=1 until ···*/ -!.= /*array holds indication of TIED.*/ -call tell right(comma(#) ,9) '(total) number of languages detected.' -call tell right(comma(#.0),9) '(total) number of entries detected.', , 1 -call eSort #,0 /*sort the languages along with #*/ -r=0 /*add true rank (tR) ──► entries.*/ -tied=; do j=# by -1 for #; r=r+1; tR=r; !tR.j=r; jp=j+1; jm=j-1 - if tied=='' then pR=r; tied= /*handle if the rank is untied.*/ - if #.j==#.jp | #.j==#.jm then do; !.j='[tied]'; tied=!.j; end - if #.j==#.jp then do; tR=pR; !tR.j=pR; end - else pR=r - end /*j=# by ···*/ - -call eSort #,1 /*sort the languages along with @*/ -listed=0; w=length(#); rank=0 /* [↓] show by ascending rank. */ - - do t=# by -1 for # while #.t>=cutoff; listed=listed+1; rank=rank+1 - call tell right('rank:' right(!tR.t,w),20-1) right(!.t,7), - right('('#.t left("entr"s(#.t,'ies',"y")')', 9),20) @.t - end /*t=# by ···*/ /* [↑] s(···) pluralizes a word*/ - -call tell left('',27) '☼ end-of-list. ☼', 1, 2 -if cutoff==0 then exit /*was there a CUTOFF specified?*/ -call tell ' Listing stopped due to a cutoff of' comma(cutoff)".", 1 -call tell listed 'language's(listed) "found with number of entries ≥" cutoff,1,1 -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ESORT subroutine────────────────────*/ -eSort: procedure expose #. @. !tr.; arg N,p2; h=N /*sort by # entries*/ - do while h>1; h=h%2 /*sort kinda halved*/ - do i=1 for N-h; j=i; k=h+i /*sort this part. */ - if p2 then do while !tR.k==!tR.j & @.k>@.j /*using hard swap ↓*/ - @=@.j; #=!tR.j; @.j=@.k; !tR.j=!tR.k; @.k=@; !tR.k=# - if h>=j then leave; j=j-h; k=k-h - end /*while !tR·k==···*/ - else do while #.k<#.j /*using hard swap ↓*/ - @=@.j; #=#.j; @.j=@.k; #.j=#.k; @.k=@; #.k=# - if h>=j then leave; j=j-h; k=k-h - end /*while #.k<#.j*/ - end /*i*/ - end /*while h>1*/ -return -/*──────────────────────────────────READER subroutine───────────────────*/ -reader: arg which 2; ig_ast=1 /*ARG uppers WHICH, gets 1st char*/ -if which=='L' then inFID=Linfid /*use this fileID for languages. */ -if which=='C' then inFID=Cinfid /* " " " " categories.*/ -old.1='╬£C++' ; new.1= "µC++" /*Unicode ╬£C++ ──►ASCII-8: µC++ */ -old.2='UC++' ; new.2= "µC++" /*old UC++ ──►ASCII-8: µC++ */ -old.3='╨£╨Ü-' ; new.3= "MK-" /*Unicode ╨£╨Ü- ──►ASCII-8: MK- */ -old.4='D├⌐j├á' ; new.4= 'Déjá' /*Unicode ├⌐j├á ──►ASCII-8: Déjá */ -old.5='D├⌐j├á' ; new.4= 'Dëjá' /*Unicode ├½j├á ──►ASCII-8: Dëjá */ -old.6='Cach├⌐' ; new.5= 'Caché' /*Unicode ach├⌐ ──►ASCII-8: Caché*/ -old.7='??-61/52' ; new.6= 'MK-61/52' /*somewhere a mistranslated: MK- */ - - do recs=0 while lines(inFID)\==0 /*read a file, 1 line at a time.*/ - $=translate(linein(inFID),,'9'x) /*handle any stray tab characters*/ - $$=space($); if $$=='' then iterate /*ignore all blank lines. */ - do v=1 while old.v\=='' /*translate Unicode variations. */ - if pos(old.v, $$) \==0 then $$=changestr(old.v, $$, new.v) - end /*v*/ /* [↑] handle different spellings*/ - if ig_ast then do; ig_ast=pos(' * ',$)==0; if ig_ast then iterate; end - $u=$$; upper $u /*get an uppercase version. */ - if pos('RETRIEVED FROM',$u)\==0 then leave /*a pseudo End-Of-Data.*/ - if which=='L' then do - if left($$,1)\=='*' then iterate /*legimate?*/ - parse upper var $$ '*' $$ "<"; $$=space($$) - L.$$=1 /*languages are stored uppercase.*/ - iterate /*iterates the DO WHILE LINES(···*/ - end /*(above) pick off language name.*/ - if left($$,1)=='*' then $$=sep || space(substr($$,2)) - catHeap=catHeap $$ /*append to the (CATegory) heap. */ - end /*while lines···*/ - -call tell right(comma(recs),9) 'records read from file: ' inFID -return -/*──────────────────────────────────TELL subroutine─────────────────────*/ -tell: do '0'arg(2); call lineout outFID,' ' ; say ; end - call lineout outFID,arg(1) ; say arg(1) - do '0'arg(3); call lineout outFID,' ' ; say ; end -return /*show before blanks lines (if any), MSG, show after blank lines*/ -/*──────────────────────────────────one─liner subroutines───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ -comma: procedure; parse arg _,c,p,t; c=pickBlank(c,","); o=p(p 3); p=abs(o); t=p(t 999999999); if \isInt(p) | \isInt(t) | p==0 | arg()>4 then return _; n=_'.9'; #=123456789; k=0; return comma_() -comma_: if o<0 then do; b=verify(_,' '); if b==0 then return _; e=length(_)-verify(reverse(_),' ')+1; end; else do; b=verify(n,#,"M"); e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1; end; do j=e to b by -p while k<t; _=insert(c,_,j); k=k+1;end;return _ -isInt: return datatype(arg(1),'W') -p: return word(arg(1),1) -pickBlank: procedure; parse arg x,y; arg xu; if xu=='BLANK' then return ' '; return p(x y) -s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*plural*/ diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Racket/rosetta-code-rank-languages-by-popularity.rkt b/Task/Rosetta-Code-Rank-languages-by-popularity/Racket/rosetta-code-rank-languages-by-popularity.rkt deleted file mode 100644 index 4fd7e777b4..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Racket/rosetta-code-rank-languages-by-popularity.rkt +++ /dev/null @@ -1,29 +0,0 @@ -#lang racket - -(require net/url) -(require json) - -(define proglangs_url "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json") -(define categories_url "http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000") - -(define (fetch-json urlstring) - (read-json (get-pure-port (string->url urlstring)))) - -(define programming-languages - (for/set ([h (in-list - (hash-ref (hash-ref (fetch-json proglangs_url) 'query) - 'categorymembers))]) - (substring (hash-ref h 'title) 9))) - -(define result '()) -(for ([l (in-port read-line (get-pure-port (string->url categories_url)))]) - (let ([res (regexp-match #px"title=\"Category:(.+?)\".+\\((\\d+) member" l)]) - (when (and res (set-member? programming-languages (cadr res))) - (set! result (cons (cons (cadr res) - (string->number (caddr res))) - result))))) - -(printf "Place\tCount\tName~n") -(for ([lang (in-list (sort result > #:key cdr))] - [place (in-naturals 1)]) - (printf "~a\t~a\t~a~n" place (cdr lang) (car lang))) diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Ruby/rosetta-code-rank-languages-by-popularity.rb b/Task/Rosetta-Code-Rank-languages-by-popularity/Ruby/rosetta-code-rank-languages-by-popularity.rb deleted file mode 100644 index c2d356e1fa..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Ruby/rosetta-code-rank-languages-by-popularity.rb +++ /dev/null @@ -1,30 +0,0 @@ -require 'rosettacode' - -langs = [] -RosettaCode.category_members("Programming Languages") {|lang| langs << lang} - -# API has trouble with long titles= values. -# To prevent skipping languages, use short slices of 20 titles. -langcount = {} -langs.each_slice(20) do |sublist| - url = RosettaCode.get_api_url({ - "action" => "query", - "prop" => "categoryinfo", - "format" => "xml", - "titles" => sublist.join("|"), - }) - - doc = REXML::Document.new open(url) - REXML::XPath.each(doc, "//page") do |page| - lang = page.attribute("title").value - info = REXML::XPath.first(page, "categoryinfo") - langcount[lang] = info.nil? ? 0 : info.attribute("pages").value.to_i - end -end - -puts Time.now -puts "There are #{langcount.length} languages" -puts "the top 25:" -langcount.sort_by {|key,val| val}.reverse[0,25].each_with_index do |(lang, count), i| - puts "#{i+1}. #{count} - #{lang.sub(/Category:/, '')}" -end diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Run-BASIC/rosetta-code-rank-languages-by-popularity.run b/Task/Rosetta-Code-Rank-languages-by-popularity/Run-BASIC/rosetta-code-rank-languages-by-popularity.run deleted file mode 100644 index 7f40df37c1..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Run-BASIC/rosetta-code-rank-languages-by-popularity.run +++ /dev/null @@ -1,28 +0,0 @@ -sqliteconnect #mem, ":memory:" ' make memory DB -#mem execute("CREATE TABLE stats(lang,cnt)") -a$ = httpGet$("http://rosettacode.org/wiki/Category:Programming_Languages") -aa$ = httpGet$("http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000") -i = instr(a$,"/wiki/Category:") -while i > 0 and lang$ <> "Languages" - j = instr(a$,"""",i) - lang$ = mid$(a$,i+15,j - i-15) - ii = instr(aa$,"Category:";lang$;"""") - jj = instr(aa$,"(",ii) - kk = instr(aa$," ",jj+1) - if ii = 0 then cnt = 0 else cnt = val(mid$(aa$,jj+1,kk-jj)) - k = instr(lang$,"%") ' convert hex values to characters - while k > 0 - lang$ = left$(lang$,k-1) + chr$(hexdec(mid$(lang$,k+1,2))) + mid$(lang$,k+3) - k = instr(lang$,"%") - wend - #mem execute("insert into stats values ('";lang$;"',";cnt;")") - i = instr(a$,"/wiki/Category:",i+10) -wend -html "<table border=2>" -#mem execute("SELECT * FROM stats ORDER BY cnt desc") ' order list by count descending -WHILE #mem hasanswer() - #row = #mem #nextrow() - rank = rank + 1 - html "<TR><TD align=right>";rank;"</td><td>";#row lang$();"</td><td align=right>";#row cnt();"</td></tr>" -WEND -html "</table>" diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Scala/rosetta-code-rank-languages-by-popularity.scala b/Task/Rosetta-Code-Rank-languages-by-popularity/Scala/rosetta-code-rank-languages-by-popularity.scala deleted file mode 100644 index 86c1abd347..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Scala/rosetta-code-rank-languages-by-popularity.scala +++ /dev/null @@ -1,137 +0,0 @@ -import akka.actor.{ Actor, ActorSystem, Props } -import scala.collection.immutable.TreeSet -import scala.xml.XML - -// Reports a list with all languages recorded in the Wiki - -private object Acquisition { - val (endPoint, prefix) = ("http://rosettacode.org/mw/api.php", "Category:") - val (maxPlaces, correction) = (50, 2) - - def convertPathArgsToURL(endPoint: String, pathArgs: Map[String, String]) = { - pathArgs.map(argPair => argPair._1 + "=" + argPair._2) - .mkString(endPoint + (if (pathArgs.nonEmpty) "?" else ""), "&", "") - } - - /* The categories include a page for the language and a count of the pages - * linked therein, this count is the data we need to scrape. - * Reports a list with language, count pair recorded in the Wiki - * All strings starts with the prefixes "Category:" - */ - def mineCatos = { - val endPoint = "http://rosettacode.org/mw/index.php" - Concurrent.logInfo("Acquisition of categories started.") - val categories = - (XML.load(convertPathArgsToURL(endPoint, - Map("title" -> "Special:Categories", "limit" -> "5000"))) \\ "ul" \ "li") - .withFilter(p => (p \ "a" \ "@title").text.startsWith(prefix)) - .map // Create a tuple pair, eg. ("Category:Erlang", 195) - { cat => - ((cat \ "a" \ "@title").text, // Takes the sibling of "a" and extracts the number - ("[0-9]+".r.findFirstIn((cat.child.drop(1)).text).getOrElse("0").toInt)) - } - Concurrent.logInfo(s"Got ${categories.size} categories..") - categories - } - - // The languages - // All strings starts with the prefixes "Category:" - def mineLangs = { - Concurrent.logInfo("Acquisition of languages started...") - val languages = ( - TreeSet[String]() ++ (XML.load(convertPathArgsToURL(endPoint, Map("action" -> "query", - "list" -> "categorymembers", - "cmtitle" -> (prefix + "Programming_Languages"), - "cmlimit" -> "505", "format" -> "xml"))) \\ - "categorymembers" \ "cm").map(c => (c \ "@title").text)) - Concurrent.logInfo(s"Got ${languages.size} languages..") - languages - } - - def joinRosettaCodeWithLanguage(catos: Seq[(String, Int)], - langs: TreeSet[String]) = - for { - cato <- catos //Clean up the tuple pairs, eg ("Category:Erlang", 195) becomes ("Erlang", 192) - if langs.exists(_ == cato._1) - } yield (cato._1.drop(prefix.size), cato._2 - correction max 0) // Correct count - - def printScrape(languages: TreeSet[String], category: Seq[(String, Int)]) { - - val join = joinRosettaCodeWithLanguage(category, languages) - val total = join.foldLeft(0)(_ + _._2) - - Concurrent.logInfo("Data processed") - - println(f"\nTop$maxPlaces%3d Rosetta Code Languages by Popularity as ${new java.util.Date}%tF:\n") - (join.groupBy(_._2).toSeq.sortBy(-_._1).take(maxPlaces) :+ (0, Seq(("...", 0)))) - .zipWithIndex // Group the ex aequo - .foreach { - case ((score, languages), rank) => - println(f"${rank + 1}%2d. $score%3d - ${languages.map(_._1).mkString(", ")}") - } - - println(s"\nCross section yields ${join.size} languages, total of $total solutions") - println(s"Resulting average is ${total / join.size} solutions per language") - } - - def printScrape(): Unit = printScrape(mineLangs, mineCatos) -} // object Acquisition - -private object Concurrent extends AppCommons { - var (category: Option[Seq[(String, Int)]], language: Option[TreeSet[String]]) = (None, None) - - class Worker extends Actor { - def receive = { - case 'Catalogue => sender ! Acquisition.mineCatos - case 'Language => sender ! Acquisition.mineLangs - } - } - - class Listener extends Actor { // Create and signal the worker actors - context.actorOf(Props[Worker], "worker0") ! 'Catalogue - context.actorOf(Props[Worker], "worker1") ! 'Language - - def printCompleteScape() = - if (category.isDefined && language.isDefined) { - Acquisition.printScrape(language.get, category.get) - context.system.shutdown - appEnd() - } - - def receive = { - case content: TreeSet[String] => { - language = Some(content) - printCompleteScape() - } - case content: Seq[(String, Int)] => { - category = Some(content) - printCompleteScape() - } - case whatever => logInfo(whatever.toString) - } // def receive - } // class Listener -} // object Concurrent - -trait AppCommons { - val execStart: Long = System.currentTimeMillis() - System.setProperty("http.agent", "*") - - def logInfo(info: String) { - println(f"[Info][${System.currentTimeMillis() - execStart}%5d ms]" + info) - } - - def appEnd() { logInfo("Run succesfully completed") } -} - -// Main entry for sequential version (slower) -object GhettoParserSeq extends App with AppCommons { - Concurrent.logInfo("Sequential version started") - Acquisition.printScrape() - appEnd() -} - -// Entry for parallel version (faster) -object GhettoParserPar extends App { - Concurrent.logInfo("Parallel version started") - ActorSystem("Main").actorOf(Props[Concurrent.Listener]) -} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Seed7/rosetta-code-rank-languages-by-popularity.seed7 b/Task/Rosetta-Code-Rank-languages-by-popularity/Seed7/rosetta-code-rank-languages-by-popularity.seed7 deleted file mode 100644 index 5b9e0f705a..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Seed7/rosetta-code-rank-languages-by-popularity.seed7 +++ /dev/null @@ -1,58 +0,0 @@ -$ include "seed7_05.s7i"; - include "gethttp.s7i"; - include "scanstri.s7i"; - -const type: popularityHash is hash [string] integer; -const type: rankingHash is hash [integer] array string; - -const func array string: getLangs (in string: buffer) is func - result - var array string: langs is 0 times ""; - local - var integer: pos is 0; - begin - pos := pos(buffer, "Category:"); - while pos <> 0 do - pos +:= 9; - langs &:= buffer[pos .. pred(pos(buffer, '"', pos))]; - pos := pos(buffer, "Category:", pos); - end while; - end func; - -const proc: main is func - local - var string: categories is ""; - var popularityHash: popularity is popularityHash.value; - var rankingHash: ranking is rankingHash.value; - var array integer: numList is 0 times 0; - var string: lang is ""; - var integer: pos is 0; - var string: numStri is ""; - var integer: listIdx is 0; - var integer: index is 0; - var integer: place is 1; - begin - categories := getHttp("www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000"); - for lang range getLangs(getHttp("rosettacode.org/mw/api.php?action=query&list=categorymembers&\ - \cmtitle=Category:Programming_Languages&cmlimit=500&format=json")) do - pos := pos(categories, "title=\"Category:" & lang); - if pos <> 0 then - pos := pos(categories, "</a>", succ(pos)); - if pos <> 0 then - pos := pos(categories, "(", succ(pos)); - if pos <> 0 then - numStri := categories[succ(pos) len 10]; - popularity @:= [lang] integer parse getDigits(numStri); - end if; - end if; - end if; - end for; - ranking := flip(popularity); - numList := sort(keys(ranking)); - for listIdx range maxIdx(numList) downto minIdx(numList) do - for key index range ranking[numList[listIdx]] do - writeln(place lpad 3 <& ". " <& numList[listIdx] <& " - " <& ranking[numList[listIdx]][index]); - end for; - place +:= length(ranking[numList[listIdx]]); - end for; - end func; diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/TUSCRIPT/rosetta-code-rank-languages-by-popularity.tu b/Task/Rosetta-Code-Rank-languages-by-popularity/TUSCRIPT/rosetta-code-rank-languages-by-popularity.tu deleted file mode 100644 index 1eacb2afa3..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/TUSCRIPT/rosetta-code-rank-languages-by-popularity.tu +++ /dev/null @@ -1,49 +0,0 @@ -$$ MODE TUSCRIPT -remotedata = REQUEST ("http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000") -allmembers=allnames="" -COMPILE -LOOP d=remotedata -IF (d.sw."<li>") THEN - name=EXTRACT (d,":<<a<><%>>:"|,":<</a>>:") - IF (name.eq."Language users") CYCLE - IF (name.sw."Unimplemented tasks") CYCLE - IF (name.sw."Programming") CYCLE - IF (name.sw."Solutions") CYCLE - IF (name.sw."Garbage") CYCLE - IF (name.sw."Typing") CYCLE - IF (name.sw."BASIC LANG") CYCLE - IF (name.ew."USER") CYCLE - IF (name.ew."tasks") CYCLE - IF (name.ew."attention") CYCLE - IF (name.ew."related") CYCLE - IF (name.ct."*omit*") CYCLE - IF (name.ct.":*Categor*:") CYCLE - IF (name.ct.":WikiSTUBS:") CYCLE - IF (name.ct.":Impl needed:") CYCLE - IF (name.ct.":Implementations:") CYCLE - IF (name.ct.":':") name = EXCHANGE (name,":'::") - members = STRINGS (d,":><1<>>/><<> member:") - IF (members!="") THEN - allmembers=APPEND (allmembers,members) - allnames =APPEND (allnames,name) - ENDIF -ENDIF -ENDLOOP -index = DIGIT_INDEX (allmembers) -index = REVERSE (index) -allmembers = INDEX_SORT (allmembers,index) -allnames = INDEX_SORT (allnames, index) -ERROR/STOP CREATE ("list",SEQ-E,-std-) -time=time(),balt=nalt="" -FILE "list" = time -LOOP n, a=allnames,b=allmembers - IF (b==balt) THEN - nr=nalt - ELSE - nalt=nr=n - ENDIF - content=concat (nr,". ",a," --- ",b) - FILE "list" = CONTENT - balt=b -ENDLOOP -ENDCOMPILE diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Tcl/rosetta-code-rank-languages-by-popularity-1.tcl b/Task/Rosetta-Code-Rank-languages-by-popularity/Tcl/rosetta-code-rank-languages-by-popularity-1.tcl deleted file mode 100644 index 2820a80883..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Tcl/rosetta-code-rank-languages-by-popularity-1.tcl +++ /dev/null @@ -1,36 +0,0 @@ -package require Tcl 8.5 -package require http - -set response [http::geturl http://rosettacode.org/mw/index.php?title=Special:Categories&limit=1000] - -array set ignore { - "Basic language learning" 1 - "Encyclopedia" 1 - "Implementations" 1 - "Language Implementations" 1 - "Language users" 1 - "Maintenance/OmitCategoriesCreated" 1 - "Programming Languages" 1 - "Programming Tasks" 1 - "RCTemplates" 1 - "Solutions by Library" 1 - "Solutions by Programming Language" 1 - "Solutions by Programming Task" 1 - "Unimplemented tasks by language" 1 - "WikiStubs" 1 - "Examples needing attention" 1 - "Impl needed" 1 -} - -foreach line [split [http::data $response] \n] { - if {[regexp {>([^<]+)</a> \((\d+) member} $line -> lang num]} { - if {![info exists ignore($lang)]} { - lappend langs [list $num $lang] - } - } -} - -foreach entry [lsort -integer -index 0 -decreasing $langs] { - lassign $entry num lang - puts [format "%d. %d - %s" [incr i] $num $lang] -} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Tcl/rosetta-code-rank-languages-by-popularity-2.tcl b/Task/Rosetta-Code-Rank-languages-by-popularity/Tcl/rosetta-code-rank-languages-by-popularity-2.tcl deleted file mode 100644 index 32357cc758..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Tcl/rosetta-code-rank-languages-by-popularity-2.tcl +++ /dev/null @@ -1,86 +0,0 @@ -package require Tcl 8.5 -package require http -package require tdom - -namespace eval rc { - ### Utility function that handles the low-level querying ### - proc rcq {q xp vn b} { - upvar 1 $vn v - dict set q action "query" - # Loop to pick up all results out of a category query - while 1 { - set url "http://rosettacode.org/mw/api.php?[http::formatQuery {*}$q]" - puts -nonewline stderr . ;# Indicate query progress... - set token [http::geturl $url] - set doc [dom parse [http::data $token]] - http::cleanup $token - - # Spoon out the DOM nodes that the caller wanted - foreach v [$doc selectNodes $xp] { - uplevel 1 $b - } - - # See if we want to go round the loop again - set next [$doc selectNodes "//query-continue/categorymembers"] - if {![llength $next]} break - dict set q cmcontinue [[lindex $next 0] getAttribute "cmcontinue"] - } - } - - ### API function: Iterate over the members of a category ### - proc members {page varName script} { - upvar 1 $varName var - set query [dict create cmtitle "Category:$page" {*}{ - list "categorymembers" - format "xml" - cmlimit "500" - }] - rcq $query "//cm" item { - # Tell the caller's script about the item - set var [$item getAttribute "title"] - uplevel 1 $script - } - } - - ### API function: Count the members of a list of categories ### - proc count {cats catVar countVar script} { - upvar 1 $catVar cat $countVar count - set query [dict create prop "categoryinfo" format "xml"] - for {set n 0} {$n<[llength $cats]} {incr n 40} { - dict set query titles [join [lrange $cats $n $n+39] |] - rcq $query "//page" item { - # Get title and count - set cat [$item getAttribute "title"] - set info [$item getElementsByTagName "categoryinfo"] - if {[llength $info]} { - set count [[lindex $info 0] getAttribute "pages"] - } else { - set count 0 - } - # Let the caller's script figure out what to do with them - uplevel 1 $script - } - } - } - - ### Assemble the bits into a whole API ### - namespace export members count - namespace ensemble create -} - -# Get the list of programming languages -rc members "Solutions by Programming Language" lang { - lappend langs $lang -} -# Get the count of solutions for each, stripping "Category:" prefix -rc count $langs l c { - lappend count [list [regsub {^Category:} $l {}] $c] -} -puts stderr "" ;# Because of the progress dots... -# Print the output -puts "There are [llength $count] languages" -puts "Here are the top fifteen:" -set count [lsort -index 1 -integer -decreasing $count] -foreach item [lrange $count 0 14] { - puts [format "%1\$3d. %3\$3d - %2\$s" [incr n] {*}$item] -} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/UnixPipes/rosetta-code-rank-languages-by-popularity.unixpipes b/Task/Rosetta-Code-Rank-languages-by-popularity/UnixPipes/rosetta-code-rank-languages-by-popularity.unixpipes deleted file mode 100644 index a594dda861..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/UnixPipes/rosetta-code-rank-languages-by-popularity.unixpipes +++ /dev/null @@ -1,3 +0,0 @@ -curl 'http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000' | -sed -n -e 's|^<li><a href="/wiki/Category:\([^"]*\).* (\([0-9][0-9]*\) members*)<.*|\2 \1|p' | -sort -rn diff --git a/Task/Rot-13/AppleScript/rot-13-4.applescript b/Task/Rot-13/AppleScript/rot-13-4.applescript index e633f57fc3..c17d673f9b 100644 --- a/Task/Rot-13/AppleScript/rot-13-4.applescript +++ b/Task/Rot-13/AppleScript/rot-13-4.applescript @@ -1,7 +1,9 @@ +-- ROT 13 -------------------------------------------------------------------- + -- rot13 :: String -> String on rot13(str) script rt13 - on lambda(x) + on |λ|(x) if (x ≥ "a" and x ≤ "m") or (x ≥ "A" and x ≤ "M") then character id ((id of x) + 13) else if (x ≥ "n" and x ≤ "z") or (x ≥ "N" and x ≤ "Z") then @@ -9,24 +11,22 @@ on rot13(str) else x end if - end lambda + end |λ| end script intercalate("", map(rt13, characters of str)) end rot13 --- TEST +-- TEST ---------------------------------------------------------------------- on run - rot13("nowhere ABJURER") --> "abjurer NOWHERE" - end run --- GENERIC FUNCTIONS +-- GENERIC FUNCTIONS --------------------------------------------------------- -- map :: (a -> b) -> [a] -> [b] on map(f, xs) @@ -34,7 +34,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -55,7 +55,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Rot-13/BaCon/rot-13.bacon b/Task/Rot-13/BaCon/rot-13.bacon new file mode 100644 index 0000000000..a00c701c82 --- /dev/null +++ b/Task/Rot-13/BaCon/rot-13.bacon @@ -0,0 +1,2 @@ +INPUT "String: ", s$ +PRINT "Output: ", REPLACE$(s$, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM", 2) diff --git a/Task/Rot-13/Batch-File/rot-13.bat b/Task/Rot-13/Batch-File/rot-13.bat new file mode 100644 index 0000000000..2e3d0f08c5 --- /dev/null +++ b/Task/Rot-13/Batch-File/rot-13.bat @@ -0,0 +1,47 @@ +@echo off & setlocal enabledelayedexpansion + +:: ROT13 obfuscator Michael Sanders - 2017 +:: +:: example: rot13.cmd Rire abgvpr cflpuvpf arire jva gur ybggrel? + +:setup + + set str=%* + set buf=%str% + set len=0 + +:getlength + + if not defined buf goto :start + set buf=%buf:~1% + set /a len+=1 + goto :getlength + +:start + + if %len% leq 0 (echo rot13: zero length string & exit /b 1) + set abc=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz + set nop=NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm + set r13= + set num=0 + set /a len-=1 + +:rot13 + + for /l %%x in (!num!,1,%len%) do ( + set log=0 + for /l %%y in (0,1,51) do ( + if "!str:~%%x,1!"=="!abc:~%%y,1!" ( + call set r13=!r13!!nop:~%%y,1! + set /a num=%%x+1 + set /a log+=1 + if !num! lss %len% goto :rot13 + ) + ) + if !log!==0 call set r13=!r13!!str:~%%x,1! + ) + +:done + + echo !r13! + endlocal & exit /b 0 diff --git a/Task/Rot-13/C/rot-13-1.c b/Task/Rot-13/C/rot-13-1.c deleted file mode 100644 index a4ffc76630..0000000000 --- a/Task/Rot-13/C/rot-13-1.c +++ /dev/null @@ -1,44 +0,0 @@ -#include<stdio.h> -#include<stdlib.h> -#include<ctype.h> - -#define MAXLINE 1024 - -char *rot13(char *s) -{ - char *p=s; - int upper; - - while(*p) { - upper=toupper(*p); - if(upper>='A' && upper<='M') *p+=13; - else if(upper>='N' && upper<='Z') *p-=13; - ++p; - } - return s; -} - -void rot13file(FILE *fp) -{ - static char line[MAXLINE]; - while(fgets(line, MAXLINE, fp)>0) fputs(rot13(line), stdout); -} - -int main(int argc, char *argv[]) -{ - int n; - FILE *fp; - - if(argc>1) { - for(n=1; n<argc; ++n) { - if(!(fp=fopen(argv[n], "r"))) { - fprintf(stderr, "ERROR: Couldn\'t read %s\n", argv[n]); - exit(EXIT_FAILURE); - } - rot13file(fp); - fclose(fp); - } - } else rot13file(stdin); - - return EXIT_SUCCESS; -} diff --git a/Task/Rot-13/C/rot-13-2.c b/Task/Rot-13/C/rot-13-2.c deleted file mode 100644 index bfda037fb8..0000000000 --- a/Task/Rot-13/C/rot-13-2.c +++ /dev/null @@ -1 +0,0 @@ -cat filename | ./rot13 diff --git a/Task/Rot-13/C/rot-13-3.c b/Task/Rot-13/C/rot-13-3.c deleted file mode 100644 index 57f17179f5..0000000000 --- a/Task/Rot-13/C/rot-13-3.c +++ /dev/null @@ -1,25 +0,0 @@ -#include <stdio.h> -#include <ctype.h> - -char rot13_char(char s); - -int main(int argc, char *argv[]) { - int c; - if (argc != 1) { - fprintf(stderr, "Usage: %s\n", argv[0]); - return 1; - } - while((c = getchar()) != EOF) { - putchar(rot13_char(c)); - } - - return 0; -} - -char rot13_char(char c) { - if (isalpha(c)) { - char alpha = islower(c) ? 'a' : 'A'; - return (c - alpha + 13) % 26 + alpha; - } - return c; -} diff --git a/Task/Rot-13/C/rot-13.c b/Task/Rot-13/C/rot-13.c new file mode 100644 index 0000000000..a283279eb5 --- /dev/null +++ b/Task/Rot-13/C/rot-13.c @@ -0,0 +1,51 @@ +#include <ctype.h> +#include <limits.h> +#include <stdio.h> +#include <stdlib.h> + +static char rot13_table[UCHAR_MAX + 1]; + +static void init_rot13_table(void) { + static const unsigned char upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + static const unsigned char lower[] = "abcdefghijklmnopqrstuvwxyz"; + + for (int ch = '\0'; ch <= UCHAR_MAX; ch++) { + rot13_table[ch] = ch; + } + for (const unsigned char *p = upper; p[13] != '\0'; p++) { + rot13_table[p[0]] = p[13]; + rot13_table[p[13]] = p[0]; + } + for (const unsigned char *p = lower; p[13] != '\0'; p++) { + rot13_table[p[0]] = p[13]; + rot13_table[p[13]] = p[0]; + } +} + +static void rot13_file(FILE *fp) +{ + int ch; + while ((ch = fgetc(fp)) != EOF) { + fputc(rot13_table[ch], stdout); + } +} + +int main(int argc, char *argv[]) +{ + init_rot13_table(); + + if (argc > 1) { + for (int i = 1; i < argc; i++) { + FILE *fp = fopen(argv[i], "r"); + if (fp == NULL) { + perror(argv[i]); + return EXIT_FAILURE; + } + rot13_file(fp); + fclose(fp); + } + } else { + rot13_file(stdin); + } + return EXIT_SUCCESS; +} diff --git a/Task/Rot-13/Clojure/rot-13-1.clj b/Task/Rot-13/Clojure/rot-13-1.clj deleted file mode 100644 index d895b4388e..0000000000 --- a/Task/Rot-13/Clojure/rot-13-1.clj +++ /dev/null @@ -1,12 +0,0 @@ -(defn rot-13 [c] - (let [i (int c)] - (cond - (or (and (>= i (int \a)) (<= i (int \m))) - (and (>= i (int \A)) (<= i (int \M)))) - (char (+ i 13)) - (or (and (>= i (int \n)) (<= i (int \z))) - (and (>= i (int \N)) (<= i (int \Z)))) - (char (- i 13)) - :else c))) - -(apply str (map rot-13 "abcxyzABCXYZ")) ;; output "nopklmNOPKLM" diff --git a/Task/Rot-13/Clojure/rot-13-2.clj b/Task/Rot-13/Clojure/rot-13-2.clj deleted file mode 100644 index 67faccf345..0000000000 --- a/Task/Rot-13/Clojure/rot-13-2.clj +++ /dev/null @@ -1,7 +0,0 @@ -(let [A (into #{} "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") - A-map (zipmap A (take 52 (drop 26 (cycle A))))] - - (defn rot13[in-str] - (reduce str (map #(if (A %1) (A-map %1) %1) in-str)))) - -(rot13 "The Quick Brown Fox Jumped Over The Lazy Dog!") ;; produces "Gur Dhvpx Oebja Sbk Whzcrq Bire Gur Ynml Qbt!" diff --git a/Task/Rot-13/Haskell/rot-13-1.hs b/Task/Rot-13/Haskell/rot-13-1.hs index 47217d21bb..def4dd78fd 100644 --- a/Task/Rot-13/Haskell/rot-13-1.hs +++ b/Task/Rot-13/Haskell/rot-13-1.hs @@ -1,7 +1,14 @@ -import Data.Char +import Data.Char (isAlpha, toLower, chr, ord) rot13 :: Char -> Char rot13 c - | toLower c >= 'a' && toLower c <= 'm' = chr (ord c + 13) - | toLower c >= 'n' && toLower c <= 'z' = chr (ord c - 13) + | isAlpha c = chr (if_ (toLower c <= 'm') (+) (-) (ord c) 13) | otherwise = c + +if_ :: Bool -> a -> a -> a +if_ True x _ = x +if_ False _ y = y + +-- Simple test +main :: IO () +main = print $ rot13 <$> "Abjurer nowhere" diff --git a/Task/Rot-13/Java/rot-13.java b/Task/Rot-13/Java/rot-13.java index 221964086e..998f53c306 100644 --- a/Task/Rot-13/Java/rot-13.java +++ b/Task/Rot-13/Java/rot-13.java @@ -1,49 +1,33 @@ import java.io.*; public class Rot13 { - public static void main(String[] args) { - BufferedReader in; + + public static void main(String[] args) throws IOException { if (args.length >= 1) { for (String file : args) { - try { - in = new BufferedReader(new FileReader(file)); - String line; - while ((line = in.readLine()) != null) { - System.out.println(convert(line)); - } - } catch (IOException e) { - e.printStackTrace(); + try (InputStream in = new BufferedInputStream(new FileInputStream(file))) { + rot13(in, System.out); } } } else { - try { - in = new BufferedReader(new InputStreamReader(System.in)); - String line; - while ((line = in.readLine()) != null) { - System.out.println(convert(line)); - } - } catch (IOException e) { - e.printStackTrace(); - } + rot13(System.in, System.out); } } - public static String convert(String msg) { - StringBuilder retVal = new StringBuilder(); - for (char a : msg.toCharArray()) { - if (a >= 'A' && a <= 'Z') { - a += 13; - if (a > 'Z') { - a -= 26; - } - } else if (a >= 'a' && a <= 'z') { - a += 13; - if (a > 'z') { - a -= 26; - } - } - retVal.append(a); + private static void rot13(InputStream in, OutputStream out) throws IOException { + int ch; + while ((ch = in.read()) != -1) { + out.write(rot13((char) ch)); } - return retVal.toString(); + } + + private static char rot13(char ch) { + if (ch >= 'A' && ch <= 'Z') { + return (char) (((ch - 'A') + 13) % 26 + 'A'); + } + if (ch >= 'a' && ch <= 'z') { + return (char) (((ch - 'a') + 13) % 26 + 'a'); + } + return ch; } } diff --git a/Task/Rot-13/jq/rot-13-1.jq b/Task/Rot-13/Jq/rot-13-1.jq similarity index 100% rename from Task/Rot-13/jq/rot-13-1.jq rename to Task/Rot-13/Jq/rot-13-1.jq diff --git a/Task/Rot-13/jq/rot-13-2.jq b/Task/Rot-13/Jq/rot-13-2.jq similarity index 100% rename from Task/Rot-13/jq/rot-13-2.jq rename to Task/Rot-13/Jq/rot-13-2.jq diff --git a/Task/Rot-13/REXX/rot-13.rexx b/Task/Rot-13/REXX/rot-13.rexx index 2a76035f97..3b4910cf45 100644 --- a/Task/Rot-13/REXX/rot-13.rexx +++ b/Task/Rot-13/REXX/rot-13.rexx @@ -1,13 +1,9 @@ /*REXX program encodes several example text strings using the ROT-13 algorithm. */ -@simple = 'simple text =' -@rot_13 = 'rot-13 text =' - -$= 'foo' ; say @simple $; say @rot_13 rot13($); say -$= 'bar' ; say @simple $; say @rot_13 rot13($); say -$= "Noyr jnf V, 'rer V fnj Ryon." ; say @simple $; say @rot_13 rot13($); say -$= 'abc? ABC!' ; say @simple $; say @rot_13 rot13($); say -$= 'abjurer NOWHERE' ; say @simple $; say @rot_13 rot13($); say - +$='foo' ; say "simple text=" $; say 'rot-13 text=' rot13($); say +$='bar' ; say "simple text=" $; say 'rot-13 text=' rot13($); say +$="Noyr jnf V, 'rer V fnj Ryon."; say "simple text=" $; say 'rot-13 text=' rot13($); say +$='abc? ABC!' ; say "simple text=" $; say 'rot-13 text=' rot13($); say +$='abjurer NOWHERE' ; say "simple text=" $; say 'rot-13 text=' rot13($); say exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ rot13: return translate( arg(1), 'abcdefghijklmABCDEFGHIJKLMnopqrstuvwxyzNOPQRSTUVWXYZ',, diff --git a/Task/Rot-13/Racket/rot-13.rkt b/Task/Rot-13/Racket/rot-13.rkt index a68ff72aa1..4c0d9e93d5 100644 --- a/Task/Rot-13/Racket/rot-13.rkt +++ b/Task/Rot-13/Racket/rot-13.rkt @@ -1,4 +1,4 @@ -#!/bin/env racket +#!/usr/bin/env racket #lang racket/base (define (run i o) diff --git a/Task/Rot-13/Sed/rot-13.sed b/Task/Rot-13/Sed/rot-13.sed new file mode 100644 index 0000000000..e2dd19c6f5 --- /dev/null +++ b/Task/Rot-13/Sed/rot-13.sed @@ -0,0 +1,2 @@ +y/abcdefghijklmnopqrstuvwxyz/nopqrstuvwxyzabcdefghijklm/ +y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/NOPQRSTUVWXYZABCDEFGHIJKLM/ diff --git a/Task/Rot-13/Standard-ML/rot-13.ml b/Task/Rot-13/Standard-ML/rot-13.ml deleted file mode 100644 index c941fccbcc..0000000000 --- a/Task/Rot-13/Standard-ML/rot-13.ml +++ /dev/null @@ -1,9 +0,0 @@ -fun rot13char c = - if c >= #"a" andalso c <= #"m" orelse c >= #"A" andalso c <= #"M" then - chr (ord c + 13) - else if c >= #"n" andalso c <= #"z" orelse c >= #"N" andalso c <= #"Z" then - chr (ord c - 13) - else - c - -val rot13 = String.map rot13char diff --git a/Task/Rot-13/Zkl/rot-13.zkl b/Task/Rot-13/Zkl/rot-13.zkl new file mode 100644 index 0000000000..4c527b07a1 --- /dev/null +++ b/Task/Rot-13/Zkl/rot-13.zkl @@ -0,0 +1,8 @@ +#!/home/craigd/Bin/zkl +fcn rot13(text){ + text.translate("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", + "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"); +} +text:=(vm.arglist or File.stdin); // command line or pipe +text.pump(File.stdout,rot13); // rotate each word and print it +if(text.isType(List)) File.stdout.writeln(); // command line gets ending newline diff --git a/Task/Run-length-encoding/00META.yaml b/Task/Run-length-encoding/00META.yaml index 093819d0be..df654b278f 100644 --- a/Task/Run-length-encoding/00META.yaml +++ b/Task/Run-length-encoding/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Encodings note: Compression diff --git a/Task/Run-length-encoding/Gambas/run-length-encoding.gambas b/Task/Run-length-encoding/Gambas/run-length-encoding.gambas new file mode 100644 index 0000000000..ab5af6d846 --- /dev/null +++ b/Task/Run-length-encoding/Gambas/run-length-encoding.gambas @@ -0,0 +1,23 @@ +Public Sub Main() +Dim sString As String = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" +Dim siCount As Short = 1 +Dim siStart As Short = 1 +Dim sHold As New String[] +Dim sTemp As String + +sString &= " " + +Repeat + sTemp = Mid(sString, siCount, 1) + Do + Inc siCount + If Mid(sString, siCount, 1) <> sTemp Then Break + If siCount = Len(sString) Then Break + Loop + sHold.add(Str(siCount - siStart) & sTemp) + siStart = siCount +Until siCount = Len(sString) + +Print sString & gb.NewLine & sHold.Join(", ") + +End diff --git a/Task/Run-length-encoding/jq/run-length-encoding-1.jq b/Task/Run-length-encoding/Jq/run-length-encoding-1.jq similarity index 100% rename from Task/Run-length-encoding/jq/run-length-encoding-1.jq rename to Task/Run-length-encoding/Jq/run-length-encoding-1.jq diff --git a/Task/Run-length-encoding/jq/run-length-encoding-2.jq b/Task/Run-length-encoding/Jq/run-length-encoding-2.jq similarity index 100% rename from Task/Run-length-encoding/jq/run-length-encoding-2.jq rename to Task/Run-length-encoding/Jq/run-length-encoding-2.jq diff --git a/Task/Run-length-encoding/jq/run-length-encoding-3.jq b/Task/Run-length-encoding/Jq/run-length-encoding-3.jq similarity index 100% rename from Task/Run-length-encoding/jq/run-length-encoding-3.jq rename to Task/Run-length-encoding/Jq/run-length-encoding-3.jq diff --git a/Task/Run-length-encoding/jq/run-length-encoding-4.jq b/Task/Run-length-encoding/Jq/run-length-encoding-4.jq similarity index 100% rename from Task/Run-length-encoding/jq/run-length-encoding-4.jq rename to Task/Run-length-encoding/Jq/run-length-encoding-4.jq diff --git a/Task/Run-length-encoding/Kotlin/run-length-encoding.kotlin b/Task/Run-length-encoding/Kotlin/run-length-encoding.kotlin new file mode 100644 index 0000000000..0e5821ddc8 --- /dev/null +++ b/Task/Run-length-encoding/Kotlin/run-length-encoding.kotlin @@ -0,0 +1,14 @@ +tailrec fun runLengthEncoding(text:String,prev:String=""):String { + if (text.isEmpty()){ + return prev + } + val initialChar = text.get(0) + val count = text.takeWhile{ it==initialChar }.count() + return runLengthEncoding(text.substring(count),prev + "$count$initialChar" ) +} + +fun main(args: Array<String>) { + assert(runLengthEncoding("TTESSST") == "2T1E3S1T") + assert(runLengthEncoding("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") + == "12W1B12W3B24W1B14W") +} diff --git a/Task/Run-length-encoding/Sed/run-length-encoding-1.sed b/Task/Run-length-encoding/Sed/run-length-encoding-1.sed new file mode 100644 index 0000000000..156257f76a --- /dev/null +++ b/Task/Run-length-encoding/Sed/run-length-encoding-1.sed @@ -0,0 +1,26 @@ + /^$/ b +:start + /^[0-9]/ b + s/^/1/ +:loop + h + /^9+([^0-9])\1+/ { + s/^(9+).*/0\1/ + y/09/10/ + G + s/^(.+)\n[0-9]+.(.*)/\1\2/ + b loop } + /^[0-9]*[0-8]([^0-9])\1+/ { + s/^[0-9]*([0-8]).*/\1/ + y/012345678/123456789/ + G + s/^(.)\n([0-9]*)[0-8].(.*)/\2\1\3/ + b loop } + /^[0-9]+9+([^0-9])\1+/ { + s/^[0-9]*([0-8]9+).*/\1/ + y/0123456789/1234567890/ + G + s/^(.+)\n([0-9]*)[0-8]9+.(.*)/\2\1\3/ + b loop } + s/^([0-9]+.)(.*)/\2\1/ + b start diff --git a/Task/Run-length-encoding/Sed/run-length-encoding-2.sed b/Task/Run-length-encoding/Sed/run-length-encoding-2.sed new file mode 100644 index 0000000000..2b227d729c --- /dev/null +++ b/Task/Run-length-encoding/Sed/run-length-encoding-2.sed @@ -0,0 +1,21 @@ + /^$/ b +:start + /^[^0-9]/ b +:loop + /^1[^0-9]/ { + s/^1(.)(\1*)(.*)/\3\1\2/ + b start } + h + /^[0-9]*[1-9][^0-9]/ { + s/^[0-9]*([1-9]).*/\1/ + y/123456789/012345678/ + G + s/^([0-8])\n([0-9]*)[1-9]([^0-9])(.*)/\2\1\3\3\4/ + b loop } + /^[0-9]+0[^0-9]/ { + s/^[0-9]*([1-9]0+)[^0-9].*/\1/ + y/0123456789/9012345678/ + G + s/^([0-9]+)\n([0-9]*)[1-9]0+([^0-9])(.*)/\2\1\3\3\4/ + s/^0+// + b loop } diff --git a/Task/Run-length-encoding/Sed/run-length-encoding-3.sed b/Task/Run-length-encoding/Sed/run-length-encoding-3.sed new file mode 100644 index 0000000000..ad42c7b137 --- /dev/null +++ b/Task/Run-length-encoding/Sed/run-length-encoding-3.sed @@ -0,0 +1,8 @@ +sed -rf encode.sed <<< "foo oops" +# 1f2o1 2o1p1s + +sed -rf decode.sed <<< "1f2o1 2o1p1s" +# foo oops + +(sed -rf decode.sed | sed -rf encode.sed) <<< 1000. +# 1000. diff --git a/Task/Run-length-encoding/Zkl/run-length-encoding-1.zkl b/Task/Run-length-encoding/Zkl/run-length-encoding-1.zkl new file mode 100644 index 0000000000..2bc7731145 --- /dev/null +++ b/Task/Run-length-encoding/Zkl/run-length-encoding-1.zkl @@ -0,0 +1,18 @@ +const MAX_LEN=250, MIN_LEN=3; +fcn compress(text){ // !empty byte/text stream -->Data (byte stream) + sink:=Data(); cnt:=Ref(0); + write:='wrap(c,n){ // helper function + while(n>MAX_LEN){ + sink.write(1); sink.write(MAX_LEN); sink.write(c); + n-=MAX_LEN; + } + if(n>MIN_LEN){ sink.write(1); sink.write(n); sink.write(c); } + else { do(n) { sink.write(c); } } + }; + text.reduce('wrap(a,b){ + if(a==b) cnt.inc(); + else{ write(a,cnt.value); cnt.set(1); } + b + },text[0]) : write(_,cnt.value); + sink; +} diff --git a/Task/Run-length-encoding/Zkl/run-length-encoding-2.zkl b/Task/Run-length-encoding/Zkl/run-length-encoding-2.zkl new file mode 100644 index 0000000000..df0c84a983 --- /dev/null +++ b/Task/Run-length-encoding/Zkl/run-length-encoding-2.zkl @@ -0,0 +1,6 @@ +fcn inflate(data){ //-->String + data.howza(3).pump(String, + fcn(c){ // if c==1, read n,c2 and expand, else write c + if(c=="\x01") return(Void.Read,2) else return(Void.Write,c) }, + fcn(_,n,c){ c*n.toAsc() }) +} diff --git a/Task/Run-length-encoding/Zkl/run-length-encoding-3.zkl b/Task/Run-length-encoding/Zkl/run-length-encoding-3.zkl new file mode 100644 index 0000000000..0c46bec052 --- /dev/null +++ b/Task/Run-length-encoding/Zkl/run-length-encoding-3.zkl @@ -0,0 +1,5 @@ +text:="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"; +d:=compress(text); +d.bytes().println(); +println(text.len()," bytes --> ",d.len()," bytes"); +println(text==inflate(d)); diff --git a/Task/Runge-Kutta-method/00META.yaml b/Task/Runge-Kutta-method/00META.yaml deleted file mode 100644 index 94b4ccfa51..0000000000 --- a/Task/Runge-Kutta-method/00META.yaml +++ /dev/null @@ -1,2 +0,0 @@ ---- -note: Runge-Kutta method diff --git a/Task/Runge-Kutta-method/Groovy/runge-kutta-method.groovy b/Task/Runge-Kutta-method/Groovy/runge-kutta-method.groovy new file mode 100644 index 0000000000..4faa840481 --- /dev/null +++ b/Task/Runge-Kutta-method/Groovy/runge-kutta-method.groovy @@ -0,0 +1,24 @@ +class Runge_Kutta{ +static void main(String[] args){ +def y=1.0,t=0.0,counter=0; +def dy1,dy2,dy3,dy4; +def real; +while(t<=10) +{if(counter%10==0) +{real=(t*t+4)*(t*t+4)/16; +println("y("+t+")="+ y+ " Error:"+ (real-y)); +} + +dy1=dy(dery(y,t)); +dy2=dy(dery(y+dy1/2,t+0.05)); +dy3=dy(dery(y+dy2/2,t+0.05)); +dy4=dy(dery(y+dy3,t+0.1)); + +y=y+(dy1+2*dy2+2*dy3+dy4)/6; +t=t+0.1; +counter++; +} +} +static def dery(def y,def t){return t*(Math.sqrt(y));} +static def dy(def x){return x*0.1;} +} diff --git a/Task/Runge-Kutta-method/jq/runge-kutta-method-1.jq b/Task/Runge-Kutta-method/Jq/runge-kutta-method-1.jq similarity index 100% rename from Task/Runge-Kutta-method/jq/runge-kutta-method-1.jq rename to Task/Runge-Kutta-method/Jq/runge-kutta-method-1.jq diff --git a/Task/Runge-Kutta-method/jq/runge-kutta-method-2.jq b/Task/Runge-Kutta-method/Jq/runge-kutta-method-2.jq similarity index 100% rename from Task/Runge-Kutta-method/jq/runge-kutta-method-2.jq rename to Task/Runge-Kutta-method/Jq/runge-kutta-method-2.jq diff --git a/Task/Runge-Kutta-method/jq/runge-kutta-method-3.jq b/Task/Runge-Kutta-method/Jq/runge-kutta-method-3.jq similarity index 100% rename from Task/Runge-Kutta-method/jq/runge-kutta-method-3.jq rename to Task/Runge-Kutta-method/Jq/runge-kutta-method-3.jq diff --git a/Task/Runge-Kutta-method/jq/runge-kutta-method-4.jq b/Task/Runge-Kutta-method/Jq/runge-kutta-method-4.jq similarity index 100% rename from Task/Runge-Kutta-method/jq/runge-kutta-method-4.jq rename to Task/Runge-Kutta-method/Jq/runge-kutta-method-4.jq diff --git a/Task/Runge-Kutta-method/jq/runge-kutta-method-5.jq b/Task/Runge-Kutta-method/Jq/runge-kutta-method-5.jq similarity index 100% rename from Task/Runge-Kutta-method/jq/runge-kutta-method-5.jq rename to Task/Runge-Kutta-method/Jq/runge-kutta-method-5.jq diff --git a/Task/Runge-Kutta-method/jq/runge-kutta-method-6.jq b/Task/Runge-Kutta-method/Jq/runge-kutta-method-6.jq similarity index 100% rename from Task/Runge-Kutta-method/jq/runge-kutta-method-6.jq rename to Task/Runge-Kutta-method/Jq/runge-kutta-method-6.jq diff --git a/Task/Runge-Kutta-method/jq/runge-kutta-method-7.jq b/Task/Runge-Kutta-method/Jq/runge-kutta-method-7.jq similarity index 100% rename from Task/Runge-Kutta-method/jq/runge-kutta-method-7.jq rename to Task/Runge-Kutta-method/Jq/runge-kutta-method-7.jq diff --git a/Task/Runge-Kutta-method/jq/runge-kutta-method-8.jq b/Task/Runge-Kutta-method/Jq/runge-kutta-method-8.jq similarity index 100% rename from Task/Runge-Kutta-method/jq/runge-kutta-method-8.jq rename to Task/Runge-Kutta-method/Jq/runge-kutta-method-8.jq diff --git a/Task/Runge-Kutta-method/Kotlin/runge-kutta-method.kotlin b/Task/Runge-Kutta-method/Kotlin/runge-kutta-method.kotlin new file mode 100644 index 0000000000..c22252668e --- /dev/null +++ b/Task/Runge-Kutta-method/Kotlin/runge-kutta-method.kotlin @@ -0,0 +1,35 @@ +// version 1.1.2 + +typealias Y = (Double) -> Double +typealias Yd = (Double, Double) -> Double + +fun rungeKutta4(t0: Double, tz: Double, dt: Double, y: Y, yd: Yd) { + var tn = t0 + var yn = y(tn) + val z = ((tz - t0) / dt).toInt() + for (i in 0..z) { + if (i % 10 == 0) { + val exact = y(tn) + val error = yn - exact + println("%4.1f %10f %10f %9f".format(tn, yn, exact, error)) + } + if (i == z) break + val dy1 = dt * yd(tn, yn) + val dy2 = dt * yd(tn + 0.5 * dt, yn + 0.5 * dy1) + val dy3 = dt * yd(tn + 0.5 * dt, yn + 0.5 * dy2) + val dy4 = dt * yd(tn + dt, yn + dy3) + yn += (dy1 + 2.0 * dy2 + 2.0 * dy3 + dy4) / 6.0 + tn += dt + } +} + +fun main(args: Array<String>) { + println(" T RK4 Exact Error") + println("---- ---------- ---------- ---------") + val y = fun(t: Double): Double { + val x = t * t + 4.0 + return x * x / 16.0 + } + val yd = fun(t: Double, yt: Double) = t * Math.sqrt(yt) + rungeKutta4(0.0, 10.0, 0.1, y, yd) +} diff --git a/Task/Runge-Kutta-method/Phix/runge-kutta-method.phix b/Task/Runge-Kutta-method/Phix/runge-kutta-method.phix new file mode 100644 index 0000000000..62024f9e0e --- /dev/null +++ b/Task/Runge-Kutta-method/Phix/runge-kutta-method.phix @@ -0,0 +1,16 @@ +constant dt = 0.1 +atom y = 1.0 +printf(1," x true/actual y calculated y relative error\n") +printf(1," --- ------------- ------------- --------------\n") +for i=0 to 100 do + atom t = i*dt + if integer(t) then + atom act = power(t*t+4,2)/16 + printf(1,"%4.1f %14.9f %14.9f %.9e\n",{t,act,y,abs(y-act)}) + end if + atom k1 = t*sqrt(y), + k2 = (t+dt/2)*sqrt(y+dt/2*k1), + k3 = (t+dt/2)*sqrt(y+dt/2*k2), + k4 = (t+dt)*sqrt(y+dt*k3) + y += dt*(k1+2*(k2+k3)+k4)/6 +end for diff --git a/Task/Runge-Kutta-method/Rust/runge-kutta-method.rust b/Task/Runge-Kutta-method/Rust/runge-kutta-method.rust new file mode 100644 index 0000000000..2fcf694c72 --- /dev/null +++ b/Task/Runge-Kutta-method/Rust/runge-kutta-method.rust @@ -0,0 +1,36 @@ +fn runge_kutta4( fx: &Fn(f64, f64) -> f64, x: f64, y: f64, dx: f64 ) -> f64 { + let k1 = dx * fx( x, y ); + let k2 = dx * fx( x + dx / 2.0, y + k1 / 2.0 ); + let k3 = dx * fx( x + dx / 2.0, y + k2 / 2.0 ); + let k4 = dx * fx( x + dx, y + k3 ); + + y + ( k1 + 2.0 * k2 + 2.0 * k3 + k4 ) / 6.0 +} + +fn f(x: f64, y: f64) -> f64 { + x * y.sqrt() +} + +fn actual(x: f64) -> f64 { + (1.0/16.0) * (x*x+4.0).powi(2) +} + +fn main() { + let mut y = 1.0; + let mut x = 0.0; + let step = 0.1; + let mut steps = 0; + let max_steps = 101; + let sample_every_n = 10; + while steps < max_steps { + if steps % sample_every_n == 0 { + println!("y({}):\t{:.10}\t\t {:E}", x, y, actual(x) - y) + } + + y = runge_kutta4(&f, x, y, step); + + x = ((x * 10.0) + (step * 10.0)) / 10.0; + steps += 1; + + } +} diff --git a/Task/Runge-Kutta-method/Zkl/runge-kutta-method.zkl b/Task/Runge-Kutta-method/Zkl/runge-kutta-method.zkl new file mode 100644 index 0000000000..71efaeaa9c --- /dev/null +++ b/Task/Runge-Kutta-method/Zkl/runge-kutta-method.zkl @@ -0,0 +1,16 @@ +fcn yp(t,y) { t * y.sqrt() } +fcn exact(t){ u:=0.25*t*t + 1.0; u*u } + +fcn rk4_step([(y,t)],h){ + k1:=h * yp(t,y); + k2:=h * yp(t + 0.5*h, y + 0.5*k1); + k3:=h * yp(t + 0.5*h, y + 0.5*k2); + k4:=h * yp(t + h, y + k3); + T(y + (k1+k4)/6.0 + (k2+k3)/3.0, t + h); +} + +fcn loop(h,n,[(y,t)]){ + if(n % 10 == 1) + print("t = %f,\ty = %f,\terr = %g\n".fmt(t,y,(y - exact(t)).abs())); + if(n < 102) return(loop(h,(n+1),rk4_step(T(y,t),h))) //tail recursion +} 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.kotlin new file mode 100644 index 0000000000..c66a13b43c --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Kotlin/runtime-evaluation-in-an-environment.kotlin @@ -0,0 +1,13 @@ +// Kotlin JS version 1.1.4-3 + +fun evalWithX(expr: String, a: Double, b: Double) { + var x = a + val atA = eval(expr) + x = b + val atB = eval(expr) + return atB - atA +} + +fun main(args: Array<String>) { + println(evalWithX("Math.exp(x)", 0.0, 1.0)) +} diff --git a/Task/Runtime-evaluation-In-an-environment/Octave/runtime-evaluation-in-an-environment.octave b/Task/Runtime-evaluation-In-an-environment/Octave/runtime-evaluation-in-an-environment.octave deleted file mode 100644 index 61a735529e..0000000000 --- a/Task/Runtime-evaluation-In-an-environment/Octave/runtime-evaluation-in-an-environment.octave +++ /dev/null @@ -1,10 +0,0 @@ -function r = calcit(f, val1, val2) - x = val1; - a = eval(f); - x = val2; - b = eval(f); - r = b-a; -endfunction - -p = "x .* 2"; -disp(calcit(p, [1:3], [4:6])); diff --git a/Task/Runtime-evaluation-In-an-environment/OoRexx/runtime-evaluation-in-an-environment.rexx b/Task/Runtime-evaluation-In-an-environment/OoRexx/runtime-evaluation-in-an-environment.rexx new file mode 100644 index 0000000000..527ad93fc6 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/OoRexx/runtime-evaluation-in-an-environment.rexx @@ -0,0 +1,8 @@ +say evalWithX("x**2", 2) +say evalWithX("x**2", 3.1415926) + +::routine evalWithX + use arg expression, x + + -- X now has the value of the second argument + interpret "return" expression diff --git a/Task/Runtime-evaluation-In-an-environment/Simula/runtime-evaluation-in-an-environment.simula b/Task/Runtime-evaluation-In-an-environment/Simula/runtime-evaluation-in-an-environment.simula new file mode 100644 index 0000000000..cd1ca334ef --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Simula/runtime-evaluation-in-an-environment.simula @@ -0,0 +1,264 @@ +BEGIN + + CLASS ENV; + BEGIN + + CLASS ITEM(N, X); TEXT N; REAL X; + BEGIN + REF(ITEM) NEXT; NEXT :- HEAD; HEAD :- THIS ITEM; + END ITEM; + + REF(ITEM) HEAD; + + REF(ITEM) PROCEDURE LOOKUP(V); TEXT V; + BEGIN + REF(ITEM) I; BOOLEAN FOUND; I :- HEAD; + WHILE NOT FOUND DO + IF I == NONE OR ELSE I.N = V + THEN FOUND := TRUE + ELSE I :- I.NEXT; + LOOKUP :- I; + END LOOKUP; + + REF(ENV) PROCEDURE SET(V, X); TEXT V; REAL X; + BEGIN + REF(ITEM) I; I :- LOOKUP(V); + IF I == NONE THEN I :- NEW ITEM(V, X) ELSE I.X := X; + SET :- THIS ENV; + END SET; + + REAL PROCEDURE GET(V); TEXT V; + GET := LOOKUP(V).X; + + END ENV; + + CLASS EXPR(EV); REF(ENV) EV; + BEGIN + + + REAL PROCEDURE POP; + BEGIN + IF STACKPOS > 0 THEN + BEGIN STACKPOS := STACKPOS - 1; POP := STACK(STACKPOS); END; + END POP; + + + PROCEDURE PUSH(NEWTOP); REAL NEWTOP; + BEGIN + STACK(STACKPOS) := NEWTOP; + STACKPOS := STACKPOS + 1; + END PUSH; + + + REAL PROCEDURE CALC(OPERATOR, ERR); CHARACTER OPERATOR; LABEL ERR; + BEGIN + REAL X, Y; X := POP; Y := POP; + IF OPERATOR = '+' THEN PUSH(Y + X) + ELSE IF OPERATOR = '-' THEN PUSH(Y - X) + ELSE IF OPERATOR = '*' THEN PUSH(Y * X) + ELSE IF OPERATOR = '/' THEN BEGIN + IF X = 0 THEN + BEGIN + EVALUATEDERR :- "DIV BY ZERO"; + GOTO ERR; + END; + PUSH(Y / X); + END + ELSE IF OPERATOR = '^' THEN PUSH(Y ** X) + ELSE + BEGIN + EVALUATEDERR :- "UNKNOWN OPERATOR"; + GOTO ERR; + END + END CALC; + + + PROCEDURE READCHAR(CH); NAME CH; CHARACTER CH; + BEGIN + IF T.MORE THEN CH := T.GETCHAR ELSE CH := EOT; + END READCHAR; + + + PROCEDURE SKIPWHITESPACE(CH); NAME CH; CHARACTER CH; + BEGIN + WHILE (CH = SPACE) OR (CH = TAB) OR (CH = CR) OR (CH = LF) DO + READCHAR(CH); + END SKIPWHITESPACE; + + + PROCEDURE BUSYBOX(OP, ERR); INTEGER OP; LABEL ERR; + BEGIN + CHARACTER OPERATOR; + REAL NUMBR; + BOOLEAN NEGATIVE; + + SKIPWHITESPACE(CH); + + IF OP = EXPRESSION THEN + BEGIN + + NEGATIVE := FALSE; + WHILE (CH = '+') OR (CH = '-') DO + BEGIN + IF CH = '-' THEN NEGATIVE := NOT NEGATIVE; + READCHAR(CH); + END; + + BUSYBOX(TERM, ERR); + + IF NEGATIVE THEN + BEGIN + NUMBR := POP; PUSH(0 - NUMBR); + END; + + WHILE (CH = '+') OR (CH = '-') DO + BEGIN + OPERATOR := CH; READCHAR(CH); + BUSYBOX(TERM, ERR); CALC(OPERATOR, ERR); + END; + + END + ELSE IF OP = TERM THEN + BEGIN + + BUSYBOX(FACTOR, ERR); + WHILE (CH = '*') OR (CH = '/') DO + BEGIN + OPERATOR := CH; READCHAR(CH); + BUSYBOX(FACTOR, ERR); CALC(OPERATOR, ERR) + END + + END + ELSE IF OP = FACTOR THEN + BEGIN + + BUSYBOX(POWER, ERR); + WHILE CH = '^' DO + BEGIN + OPERATOR := CH; READCHAR(CH); + BUSYBOX(POWER, ERR); CALC(OPERATOR, ERR) + END + + END + ELSE IF OP = POWER THEN + BEGIN + + IF (CH = '+') OR (CH = '-') THEN + BUSYBOX(EXPRESSION, ERR) + ELSE IF (CH >= '0') AND (CH <= '9') THEN + BUSYBOX(NUMBER, ERR) + ELSE IF (CH >= 'A') AND (CH <= 'Z') THEN + BUSYBOX(VARIABLE, ERR) + ELSE IF CH = '(' THEN + BEGIN + READCHAR(CH); + BUSYBOX(EXPRESSION, ERR); + IF CH = ')' THEN READCHAR(CH) ELSE GOTO ERR; + END + ELSE GOTO ERR; + + END + ELSE IF OP = VARIABLE THEN + BEGIN + + TEXT VARNAM; + VARNAM :- BLANKS(32); + WHILE (CH >= 'A') AND (CH <= 'Z') + OR (CH >= '0') AND (CH <= '9') DO + BEGIN + VARNAM.PUTCHAR(CH); + READCHAR(CH); + END; + PUSH(EV.GET(VARNAM.STRIP)); + + END + ELSE IF OP = NUMBER THEN + BEGIN + + NUMBR := 0; + WHILE (CH >= '0') AND (CH <= '9') DO + BEGIN + NUMBR := 10 * NUMBR + RANK(CH) - RANK('0'); READCHAR(CH); + END; + IF CH = '.' THEN + BEGIN + REAL FAKTOR; + READCHAR(CH); + FAKTOR := 10; + WHILE (CH >= '0') AND (CH <= '9') DO + BEGIN + NUMBR := NUMBR + (RANK(CH) - RANK('0')) / FAKTOR; + FAKTOR := 10 * FAKTOR; + READCHAR(CH); + END; + END; + PUSH(NUMBR); + + END; + + SKIPWHITESPACE(CH); + + END BUSYBOX; + + + BOOLEAN PROCEDURE EVAL(INP); TEXT INP; + BEGIN + EVALUATEDERR :- NOTEXT; + STACKPOS := 0; + T :- COPY(INP.STRIP); + READCHAR(CH); + BUSYBOX(EXPRESSION, ERRORLABEL); + IF NOT T.MORE AND STACKPOS = 1 AND CH = EOT THEN + BEGIN + EVALUATED := POP; + EVAL := TRUE; + GOTO NOERRORLABEL; + END; + ERRORLABEL: + EVAL := FALSE; + IF EVALUATEDERR = NOTEXT THEN + EVALUATEDERR :- "INVALID EXPRESSION: " & INP; + NOERRORLABEL: + END EVAL; + + + REAL PROCEDURE RESULT; + RESULT := EVALUATED; + + TEXT PROCEDURE ERR; + ERR :- EVALUATEDERR; + + INTEGER EXPRESSION, TERM, FACTOR, POWER, NUMBER, VARIABLE; + CHARACTER TAB, LF, CR, SPACE, EOT, CH; + REAL ARRAY STACK(0:31); + INTEGER STACKPOS; + REAL EVALUATED; + TEXT EVALUATEDERR, T; + + EXPRESSION := 1; + TERM := 2; + FACTOR := 3; + POWER := 4; + NUMBER := 5; + VARIABLE := 6; + + TAB := CHAR(9); + LF := CHAR(10); + CR := CHAR(13); + SPACE := CHAR(32); + EOT := CHAR(0); + + END EXPR; + + REF(EXPR) EXA, EXB; + EXA :- NEW EXPR(NEW ENV.SET("X", 3)); + EXB :- NEW EXPR(NEW ENV.SET("X", 5)); + IF EXA.EVAL("2 ^ X") THEN + BEGIN + IF EXB.EVAL("2 ^ X") + THEN OUTFIX(EXB.RESULT - EXA.RESULT, 3, 10) + ELSE OUTTEXT(EXB.ERR) + END ELSE OUTTEXT(EXA.ERR); + OUTIMAGE; + +END. diff --git a/Task/Runtime-evaluation-In-an-environment/Zkl/runtime-evaluation-in-an-environment-1.zkl b/Task/Runtime-evaluation-In-an-environment/Zkl/runtime-evaluation-in-an-environment-1.zkl new file mode 100644 index 0000000000..ba1d042d8e --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Zkl/runtime-evaluation-in-an-environment-1.zkl @@ -0,0 +1,8 @@ +fcn evalWithX(text,x) { + f:=Compiler.Compiler.compileText(text); + f.x = x; // set free var in compiled blob + f.__constructor(); // run blob + vm.regX // compiler sets the VMs X register for cases like this +} +const TEXT="var x; x*2"; // variables need to be declared +evalWithX(TEXT,5) - evalWithX(TEXT,3) #--> 4 diff --git a/Task/Runtime-evaluation-In-an-environment/Zkl/runtime-evaluation-in-an-environment-2.zkl b/Task/Runtime-evaluation-In-an-environment/Zkl/runtime-evaluation-in-an-environment-2.zkl new file mode 100644 index 0000000000..8615befa53 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Zkl/runtime-evaluation-in-an-environment-2.zkl @@ -0,0 +1,2 @@ +var klass=Compiler.Compiler.compileText("var x; returnClass(x*2)"); +(klass.__constructor(klass.x=5) - klass.__constructor(klass.x=3)).println(); diff --git a/Task/Runtime-evaluation/OoRexx/runtime-evaluation.rexx b/Task/Runtime-evaluation/OoRexx/runtime-evaluation.rexx new file mode 100644 index 0000000000..7e4a132f1b --- /dev/null +++ b/Task/Runtime-evaluation/OoRexx/runtime-evaluation.rexx @@ -0,0 +1,3 @@ + a = .array~of(1, 2, 3) + ins = "loop num over a; say num; end" + interpret ins diff --git a/Task/Runtime-evaluation/PowerShell/runtime-evaluation-1.psh b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-1.psh new file mode 100644 index 0000000000..3c1448ce23 --- /dev/null +++ b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-1.psh @@ -0,0 +1,2 @@ +$test2plus2 = '2 + 2 -eq 4' +Invoke-Expression $test2plus2 diff --git a/Task/Runtime-evaluation/PowerShell/runtime-evaluation-2.psh b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-2.psh new file mode 100644 index 0000000000..3ffb9b4bd0 --- /dev/null +++ b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-2.psh @@ -0,0 +1,2 @@ +$say = {"Hello, world!"} +& $say diff --git a/Task/Runtime-evaluation/PowerShell/runtime-evaluation-3.psh b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-3.psh new file mode 100644 index 0000000000..b6abd3c858 --- /dev/null +++ b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-3.psh @@ -0,0 +1,2 @@ +$say = {param ([string]$Subject) "Hello, $Subject!"} +& $say -Subject "my friend" diff --git a/Task/Runtime-evaluation/PowerShell/runtime-evaluation-4.psh b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-4.psh new file mode 100644 index 0000000000..b8b3e37f27 --- /dev/null +++ b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-4.psh @@ -0,0 +1,2 @@ +$say = {param ([string]$Exclamation, [string]$Subject) "$Exclamation, $Subject!"} +& $say -Exclamation "Goodbye" -Subject "cruel world" diff --git a/Task/Runtime-evaluation/PowerShell/runtime-evaluation-5.psh b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-5.psh new file mode 100644 index 0000000000..f9b3714964 --- /dev/null +++ b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-5.psh @@ -0,0 +1,6 @@ +$title = "Dong Work For Yuda" +$scriptblock = {$title} +$closedScriptblock = $scriptblock.GetNewClosure() + +& $scriptblock +& $closedScriptblock diff --git a/Task/Runtime-evaluation/PowerShell/runtime-evaluation-6.psh b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-6.psh new file mode 100644 index 0000000000..6cf7147beb --- /dev/null +++ b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-6.psh @@ -0,0 +1,3 @@ +$title = "I'm Too Sexy" +& $scriptblock +& $closedScriptblock diff --git a/Task/Runtime-evaluation/Zkl/runtime-evaluation.zkl b/Task/Runtime-evaluation/Zkl/runtime-evaluation.zkl new file mode 100644 index 0000000000..8587dc4865 --- /dev/null +++ b/Task/Runtime-evaluation/Zkl/runtime-evaluation.zkl @@ -0,0 +1,3 @@ +Compiler.Compiler.compileText( + "fcn f(text){text.len()}").f("foobar") +//-->6 diff --git a/Task/S-Expressions/Ceylon/s-expressions-1.ceylon b/Task/S-Expressions/Ceylon/s-expressions-1.ceylon deleted file mode 100644 index 6790d69227..0000000000 --- a/Task/S-Expressions/Ceylon/s-expressions-1.ceylon +++ /dev/null @@ -1,3 +0,0 @@ -module rosetta "1.0.0" { - import ceylon.collection "1.2.1"; -} diff --git a/Task/S-Expressions/Ceylon/s-expressions-2.ceylon b/Task/S-Expressions/Ceylon/s-expressions-2.ceylon deleted file mode 100644 index 30b7e84f0d..0000000000 --- a/Task/S-Expressions/Ceylon/s-expressions-2.ceylon +++ /dev/null @@ -1,156 +0,0 @@ -import ceylon.collection { - - ArrayList -} - -class Symbol(shared String text) { - string => text; -} - -abstract class Node() of Leaf | Branch {} -class Leaf(shared String|Integer|Float|Symbol data) extends Node() { - string => data.string; -} -class Branch() extends Node() { - shared ArrayList<Node> nodes = ArrayList<Node>(); - string => nodes.string; -} - -shared void run() { - - alias Token => String|Character|Integer|Float|Symbol; - - {Token*} tokenize(String input) { - - class Mode { - shared new neutral {} - shared new symbol {} - shared new quoted {} - shared new integer {} - shared new float {} - shared new escape {} - } - - value tokens = ArrayList<Token>(); - variable value mode = Mode.neutral; - value currentToken = StringBuilder(); - - void completeToken() { - value string = currentToken.string; - if(mode == Mode.symbol) { - tokens.add(Symbol(string)); - } - if(mode == Mode.quoted) { - tokens.add(string); - } - if(mode == Mode.integer) { - assert(exists int = parseInteger(string)); - tokens.add(int); - } - if(mode == Mode.float) { - assert(exists float = parseFloat(string)); - tokens.add(float); - } - mode = Mode.neutral; - currentToken.clear(); - } - - for(char in input) { - switch(char) - case('(' | ')') { - if(mode != Mode.quoted) { - completeToken(); - tokens.add(char); - } else { - currentToken.appendCharacter(char); - } - } - case('\"') { - if(mode == Mode.escape) { - currentToken.appendCharacter(char); - mode = Mode.quoted; - } else if(mode != Mode.quoted) { - mode = Mode.quoted; - } else if(mode == Mode.quoted) { - completeToken(); - } - } - case('\\') { - if(mode == Mode.quoted) { - mode = Mode.escape; - } else { - currentToken.appendCharacter(char); - } - } - case(' ' | '\n' | '\r') { - if(mode != Mode.quoted) { - completeToken(); - } else { - currentToken.append(" "); - } - } - else { - if(mode == Mode.neutral) { - if(char.digit) { - mode = Mode.integer; - } else { - mode = Mode.symbol; - } - } - if(mode == Mode.integer && (char == '.' || char == ',')) { - mode = Mode.float; - } - currentToken.appendCharacter(char); - } - } - completeToken(); - return tokens; - } - - Node readFromTokens(ArrayList<Token> tokens) { - if(exists first = tokens.accept()) { - if(first == '(') { - value branch = Branch(); - while(!tokens.empty) { - if(exists token = tokens.first) { - if(token == ')') { - tokens.accept(); - break; - } else { - branch.nodes.add(readFromTokens(tokens)); - } - } - } - return branch; - } else { - if(is String|Integer|Float|Symbol first) { - return Leaf(first); - } else { - throw Exception("unexpected token ``first``"); - } - } - } else { - return Branch(); - } - } - - void prettyPrint(Node node, Integer indentation = 0) { - - void paddedPrint(String s) => print(" ".repeat(indentation) + s); - - if(is Leaf node) { - paddedPrint(node.string); - } else { - paddedPrint("("); - for(n in node.nodes) { - prettyPrint(n, indentation + 2); - } - paddedPrint(")"); - } - } - - value tokens = tokenize("""((data "quoted data" 123 4.5) - (data (!@# (4.5) "(more" "data)")))"""); - value tree = readFromTokens(ArrayList {*tokens}); - prettyPrint(tree); -} diff --git a/Task/S-Expressions/Ceylon/s-expressions.ceylon b/Task/S-Expressions/Ceylon/s-expressions.ceylon new file mode 100644 index 0000000000..e08aaea324 --- /dev/null +++ b/Task/S-Expressions/Ceylon/s-expressions.ceylon @@ -0,0 +1,168 @@ +class Symbol(symbol) { + shared String symbol; + string => symbol; +} + +abstract class Token() + of DataToken | leftParen | rightParen {} + +abstract class DataToken(data) + of StringToken | IntegerToken | FloatToken | SymbolToken + extends Token() { + + shared String|Integer|Float|Symbol data; + string => data.string; +} + +class StringToken(String data) extends DataToken(data) {} +class IntegerToken(Integer data) extends DataToken(data) {} +class FloatToken(Float data) extends DataToken(data) {} +class SymbolToken(Symbol data) extends DataToken(data) {} + +object leftParen extends Token() { + string => "("; +} +object rightParen extends Token() { + string => ")"; +} + +class Tokens(String input) satisfies {Token*} { + shared actual Iterator<Token> iterator() => object satisfies Iterator<Token> { + + variable value index = 0; + + shared actual Token|Finished next() { + + while(exists nextChar = input[index], nextChar.whitespace) { + index++; + } + + if(index >= input.size) { + return finished; + } + + assert(exists char = input[index]); + + if(char == '(') { + index++; + return leftParen; + } + if(char == ')') { + index++; + return rightParen; + } + + if(char == '"') { + value builder = StringBuilder(); + while(exists nextChar = input[++index]) { + if(nextChar == '"') { + index++; + break; + } + if(nextChar == '\\') { + if(exists nextNextChar = input[++index]) { + switch(nextNextChar) + case('\\') { + builder.append("\\"); + } + case('t') { + builder.append("\t"); + } + case('n') { + builder.append("\n"); + } + case('"') { + builder.append("\""); + } + else { + throw Exception("unknown escaped character"); + } + } else { + throw Exception("unclosed string"); + } + } else { + builder.appendCharacter(nextChar); + } + } + return StringToken(builder.string); + } + + value builder = StringBuilder(); + while(exists nextChar = input[index], !nextChar.whitespace && nextChar != '(' && nextChar != ')') { + builder.appendCharacter(nextChar); + index++; + } + value string = builder.string; + if(is Integer int = Integer.parse(string)) { + return IntegerToken(int); + } else if(is Float float = Float.parse(string)) { + return FloatToken(float); + } else { + return SymbolToken(Symbol(string)); + } + } + }; +} + +abstract class Node() of Atom | Group {} + +class Atom(data) extends Node() { + shared String|Integer|Float|Symbol data; + string => data.string; +} +class Group() extends Node() satisfies {Node*} { + shared variable Node[] nodes = []; + string => nodes.string; + shared actual Iterator<Node> iterator() => nodes.iterator(); + +} + +Node buildTree(Tokens tokens) { + + [Group, Integer] recursivelyBuild(Token[] tokens, variable Integer index = 0) { + value result = Group(); + while(exists token = tokens[index]) { + switch (token) + case (leftParen) { + value [newNode, newIndex] = recursivelyBuild(tokens, index + 1); + index = newIndex; + result.nodes = result.nodes.append([newNode]); + } + case (rightParen) { + return [result, index]; + } + else { + result.nodes = result.nodes.append([Atom(token.data)]); + } + index++; + } + return [result, index]; + } + + value root = recursivelyBuild(tokens.sequence())[0]; + return root.first else Group(); +} + +void prettyPrint(Node node, Integer indentation = 0) { + + void paddedPrint(String s) => print(" ".repeat(indentation) + s); + + if(is Atom node) { + paddedPrint(node.string); + } else { + paddedPrint("("); + for(n in node.nodes) { + prettyPrint(n, indentation + 2); + } + paddedPrint(")"); + } +} + +shared void run() { + value tokens = Tokens("""((data "quoted data" 123 4.5) + (data (!@# (4.5) "(more" "data)")))"""); + print(tokens); + + value tree = buildTree(tokens); + prettyPrint(tree); +} diff --git a/Task/S-Expressions/REXX/s-expressions.rexx b/Task/S-Expressions/REXX/s-expressions.rexx index 25179548fd..9fbf49e434 100644 --- a/Task/S-Expressions/REXX/s-expressions.rexx +++ b/Task/S-Expressions/REXX/s-expressions.rexx @@ -1,64 +1,55 @@ -/*REXX program parses an S-expression and displays the results. */ +/*REXX program parses an S-expression and displays the results to the terminal. */ input= '((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))' -say 'input:'; say input /*display the input data string to term*/ -say copies('═', length(input)) /*also, display a header fence. */ -groupO.= /*default value for grouping symbols. */ -groupO.1 = '{' ; groupC.1 = "}" /*grouping symbols (Open & Close). */ -groupO.2 = '[' ; groupC.2 = "]" /* " " " " " */ -groupO.3 = '(' ; groupC.3 = ")" /* " " " " " */ +say center('input', length(input), "═") /*display the header title to terminal.*/ +say input /* " " input data " " */ +say copies('═', length(input) ) /* " " header sep " " */ +grpO.=; grpO.1 = '{' ; grpC.1 = "}" /*pair of grouping symbol: braces */ + grpO.2 = '[' ; grpC.2 = "]" /* " " " " brackets */ + grpO.3 = '(' ; grpC.3 = ")" /* " " " " parentheses */ + grpO.4 = '«' ; grpC.4 = "»" /* " " " " guillemets */ +q.=; q.1 = "'" ; q.2 = '"' /*1st and 2nd literal string delimiter.*/ # = 0 /*the number of tokens found (so far). */ tabs = 10 /*used for the indenting of the levels.*/ -q.1 = "'" /*literal string delimiter, first. */ -q.2 = '"' /* " " " second. */ -numLits = 2 /*the number of kinds of literals. */ seps = ',;' /*characters used for separation. */ -atoms = ' 'seps /*characters used to separate atoms. */ +atoms = ' 'seps /* " " to separate atoms. */ level = 0 /*the current level being processed. */ -quoted = 0 /*quotation level (when nested). */ -groupu = /*used to go ↑ an expression level. */ -groupd = /* " " " ↓ " " " */ -$.= /*the stem array to hold the tokens. */ - do n=1 while groupO.n\=='' /*handle the number of grouping symbols*/ - atoms =atoms || groupO.n || groupC.n - groupu=groupu || groupO.n - groupd=groupd || groupC.n - end /*n*/ +quoted = 0 /*quotation level (for nested quotes).*/ +grpU = /*used to go up an expression level.*/ +grpD = /* " " " down " " " */ +@.=; do n=1 while grpO.n\=='' + atoms = atoms || grpO.n || grpC.n /*add Open and Closed groups to ATOMS.*/ + grpU = grpU || grpO.n /*add Open groups to GRPU, */ + grpD = grpD || grpC.n /*add Closed groups to GRPD, */ + end /*n*/ /* [↑] handle a bunch of grouping syms*/ literals= - do k=1 for numLits - literals=literals || q.k - end /*k*/ -!= - /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ text parsing ▒▒▒▒▒▒▒▒*/ - do j=1 to length(input); _=substr(input,j,1) /*▒*/ - /*▒*/ - if quoted then do; !=! || _ /*▒*/ - if _==literalStart then quoted=0 /*▒*/ - iterate /*▒*/ - end /*▒*/ - /*▒*/ - if pos(_,literals)\==0 then do; literalStart=_ /*▒*/ - !=! || _ /*▒*/ - quoted=1 /*▒*/ - iterate /*▒*/ - end /*▒*/ - /*▒*/ - if pos(_,atoms)==0 then do; !=! || _ ; iterate; end /*▒*/ - else do; call add!; !=_; end /*▒*/ - /*▒*/ - if pos(_,literals)==0 then do; if pos(_,groupu)\==0 then level=level+1 /*▒*/ - call add! /*▒*/ - if pos(_,groupd)\==0 then level=level-1 /*▒*/ - if level<0 then say 'oops, mismatched' _ /*▒*/ - end /*▒*/ - end /*j*/ /*▒*/ - /*▒*/ -call add! /*handle any residual tokens.*/ /*▒*/ -if level\==0 then say 'oops, mismatched grouping symbol' /*▒*/ -if quoted then say 'oops, no end of quoted literal' literalStart /*▒*/ - /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ + do k=1 while q.k\==''; literals=literals || q.k /*add literal delimiters*/ + end /*k*/ +!=; literalStart= + do j=1 to length(input); $=substr(input, j, 1) /* ◄■■■■■text parsing*/ + /* ◄■■■■■text parsing*/ + if quoted then do; !=! || $; if $==literalStart then quoted=0 /* ◄■■■■■text parsing*/ + iterate /* ◄■■■■■text parsing*/ + end /* [↑] handle running quoted str.*/ /* ◄■■■■■text parsing*/ + /* ◄■■■■■text parsing*/ + if pos($, literals)\==0 then do; literalStart=$; !=! || $; quoted=1 /* ◄■■■■■text parsing*/ + iterate /* ◄■■■■■text parsing*/ + end /* [↑] handle start of quoted str.*/ /* ◄■■■■■text parsing*/ + /* ◄■■■■■text parsing*/ + if pos($, atoms)==0 then do; !=! || $ ; iterate; end /*is an atom?*/ /* ◄■■■■■text parsing*/ + else do; call add!; !=$; end /*isn't an atam?*/ /* ◄■■■■■text parsing*/ + /* ◄■■■■■text parsing*/ + if pos($, literals)==0 then do; if pos($, grpU)\==0 then level=level + 1 /* ◄■■■■■text parsing*/ + call add! /* ◄■■■■■text parsing*/ + if pos($, grpD)\==0 then level=level - 1 /* ◄■■■■■text parsing*/ + if level<0 then say 'error, mismatched' $ /* ◄■■■■■text parsing*/ + end /* ◄■■■■■text parsing*/ + end /*j*/ /* ◄■■■■■text parsing*/ + /* ◄■■■■■text parsing*/ +call add! /*process any residual tokens.*/ /* ◄■■■■■text parsing*/ +if level\==0 then say 'error, mismatched grouping symbol' /* ◄■■■■■text parsing*/ +if quoted then say 'error, no end of quoted literal' literalStart /* ◄■■■■■text parsing*/ - do m=1 for #; say $.m; end /*m*/ /*display the tokens to the terminal. */ + do m=1 for #; say @.m; end /*m*/ /*display the tokens to the terminal. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -add!: if !\='' then do; #=#+1; $.#=left('', max(0, tabs*(level-1)))!; end; != - return +add!: if !='' then return; #=#+1; @.#=left("", max(0, tabs*(level-1)))!; !=; return diff --git a/Task/S-Expressions/TXR/s-expressions-3.txr b/Task/S-Expressions/TXR/s-expressions-3.txr deleted file mode 100644 index e60497e242..0000000000 --- a/Task/S-Expressions/TXR/s-expressions-3.txr +++ /dev/null @@ -1 +0,0 @@ - @/\s*\(\s*/@(coll :vars (e))@(expr e)@/\s*/@(last))@(end) diff --git a/Task/SEDOLs/ALGOL-W/sedols.alg b/Task/SEDOLs/ALGOL-W/sedols.alg new file mode 100644 index 0000000000..7faab3a596 --- /dev/null +++ b/Task/SEDOLs/ALGOL-W/sedols.alg @@ -0,0 +1,43 @@ +begin + % returns the check digit for the specified SEDOL % + string(1) procedure sedolCheckDigit ( string(6) value sedol ) ; + begin + integer checkSum, checkDigit; + checkSum := 0; + for cPos := 0 until 5 do begin + string(1) c; + integer digit; + c := sedol( cPos // 1 ); + if c >= "0" and c <= "9" + then digit := decode( c ) - decode( "0" ) + else digit := 10 + ( decode( c ) - decode( "A" ) ); + checkSum := checkSum + ( ( case cPos + 1 of ( 1, 3, 1, 7, 3, 9 ) ) * digit ) + end for_cPos ; + checkDigit := ( 10 - ( checkSum rem 10 ) ) rem 10; + if checkDigit < 10 + then code( decode( "0" ) + checkDigit ) + else code( decode( "A" ) + ( checkDigit - 10 ) ) + end sedolCheckDigit ; + + % task test cases % + + procedure testCheckDigit ( string(6) value sedol; string(1) value expectedCheckDigit ) ; + begin + string(1) checkDigit; + checkDigit := sedolCheckDigit( sedol ); + write( s_w := 0, sedol, checkDigit ); + if checkDigit not = expectedCheckDigit then writeon( " ?? expected: ", expectedCheckDigit ) + end testCheckDigit ; + + testCheckDigit( "710889", "9" ); + testCheckDigit( "B0YBKJ", "7" ); + testCheckDigit( "406566", "3" ); + testCheckDigit( "B0YBLH", "2" ); + testCheckDigit( "228276", "5" ); + testCheckDigit( "B0YBKL", "9" ); + testCheckDigit( "557910", "7" ); + testCheckDigit( "B0YBKR", "5" ); + testCheckDigit( "585284", "2" ); + testCheckDigit( "B0YBKT", "7" ); + testCheckDigit( "B00030", "0" ) +end. diff --git a/Task/SEDOLs/Cache-ObjectScript/sedols.cos b/Task/SEDOLs/Cache-ObjectScript/sedols.cos new file mode 100644 index 0000000000..b4dcc97051 --- /dev/null +++ b/Task/SEDOLs/Cache-ObjectScript/sedols.cos @@ -0,0 +1,19 @@ +Class Utils.Check [ Abstract ] +{ + +ClassMethod SEDOL(x As %String) As %Boolean +{ + // https://en.wikipedia.org/wiki/SEDOL + IF x'?1(7N,1U5UN1N) QUIT 0 + IF x'=$TRANSLATE(x,"AEIOU") QUIT 0 + SET cd=$EXTRACT(x,*), x=$EXTRACT(x,1,*-1) + SET wgt="1317391", t=0 + FOR i=1:1:$LENGTH(x) { + SET n=$EXTRACT(x,i) + IF n'=+n SET n=$ASCII(n)-55 + SET t=t+(n*$EXTRACT(wgt,i)) + } + QUIT cd=((10-(t#10))#10) +} + +} diff --git a/Task/SEDOLs/Haskell/sedols.hs b/Task/SEDOLs/Haskell/sedols.hs index 7403aea6af..c8f1f52c2c 100644 --- a/Task/SEDOLs/Haskell/sedols.hs +++ b/Task/SEDOLs/Haskell/sedols.hs @@ -1,22 +1,31 @@ -import Data.Char +import Data.Char (isDigit, isAsciiUpper, ord) -char2value c | c `elem` "AEIOU" = error "No vowels." - | c >= '0' && c <= '9' = ord c - ord '0' - | c >= 'A' && c <= 'Z' = ord c - ord 'A' + 10 +checkSum :: String -> String +checkSum = + show . + (`rem` 10) . + (-) 10 . (`rem` 10) . sum . zipWith (*) [1, 3, 1, 7, 3, 9] . (charValue <$>) -sedolweight = [1,3,1,7,3,9] +charValue :: Char -> Int +charValue c + | c `elem` "AEIOU" = error "No vowels." + | isDigit c = ord c - ord '0' + | isAsciiUpper c = ord c - ord 'A' + 10 -checksum sedol = show ((10 - (tmp `mod` 10)) `mod` 10) - where tmp = sum $ zipWith (*) sedolweight $ map char2value sedol - -main = mapM_ (\sedol -> putStrLn $ sedol ++ checksum sedol) - [ "710889", - "B0YBKJ", - "406566", - "B0YBLH", - "228276", - "B0YBKL", - "557910", - "B0YBKR", - "585284", - "B0YBKT" ] +-- TEST ---------------------------------------------------------------------- +main :: IO () +main = + mapM_ + (putStrLn . ((++) <*> checkSum)) + [ "710889" + , "B0YBKJ" + , "406566" + , "B0YBLH" + , "228276" + , "B0YBKL" + , "557910" + , "B0YBKR" + , "585284" + , "B0YBKT" + , "B00030" + ] diff --git a/Task/SEDOLs/jq/sedols.jq b/Task/SEDOLs/Jq/sedols.jq similarity index 100% rename from Task/SEDOLs/jq/sedols.jq rename to Task/SEDOLs/Jq/sedols.jq diff --git a/Task/SEDOLs/Kotlin/sedols.kotlin b/Task/SEDOLs/Kotlin/sedols.kotlin new file mode 100644 index 0000000000..f981b492d0 --- /dev/null +++ b/Task/SEDOLs/Kotlin/sedols.kotlin @@ -0,0 +1,25 @@ +// version 1.1.0 + +val weights = listOf(1, 3, 1, 7, 3, 9, 1) + +fun sedol7(sedol6: String): String { + if (sedol6.length != 6) throw IllegalArgumentException("Length of argument string must be 6") + var sum = 0 + for (i in 0..5) { + val c = sedol6[i] + val v = when (c) { + in '0'..'9' -> c.toInt() - 48 + in 'A'..'Z' -> c.toInt() - 55 + else -> throw IllegalArgumentException("Argument string contains an invalid character") + } + sum += v * weights[i] + } + val check = (10 - (sum % 10)) % 10 + return sedol6 + (check + 48).toChar() +} + +fun main(args: Array<String>) { + val sedol6s = listOf("710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", + "557910", "B0YBKR", "585284", "B0YBKT", "B00030") + for (sedol6 in sedol6s) println("$sedol6 -> ${sedol7(sedol6)}") +} diff --git a/Task/SEDOLs/Zkl/sedols-1.zkl b/Task/SEDOLs/Zkl/sedols-1.zkl new file mode 100644 index 0000000000..8f9d0415eb --- /dev/null +++ b/Task/SEDOLs/Zkl/sedols-1.zkl @@ -0,0 +1,9 @@ +fcn checksum(text){ + ( text.len()!=6 or (text..matches("*[AEIOUaeioua-z]*")) ) and + throw(Exception.ValueError("Invalid SEDOL text: "+text)); + + text + (10 - text.pump(List,'wrap(c){ + if("0"<=c<="9") c.toAsc()-0x30; + else c.toAsc()-55; + }).zipWith('*,T(1,3,1,7,3,9)).sum() % 10) % 10; +} diff --git a/Task/SEDOLs/Zkl/sedols-2.zkl b/Task/SEDOLs/Zkl/sedols-2.zkl new file mode 100644 index 0000000000..83a5e51755 --- /dev/null +++ b/Task/SEDOLs/Zkl/sedols-2.zkl @@ -0,0 +1,3 @@ +T("710889","B0YBKJ","406566","B0YBLH","228276", + "B0YBKL","557910","B0YBKR","585284","B0YBKT","B00030") +.apply(checksum).println(); diff --git a/Task/SHA-1/Astro/sha-1.astro b/Task/SHA-1/Astro/sha-1.astro new file mode 100644 index 0000000000..2cc9f5fc34 --- /dev/null +++ b/Task/SHA-1/Astro/sha-1.astro @@ -0,0 +1,2 @@ +import crypto +let hash = sha1 bytes('Ars longa, vita brevis', encoding:'ascii') diff --git a/Task/SHA-1/Fortran/sha-1.f b/Task/SHA-1/Fortran/sha-1.f index 65022c18e5..229d2312e1 100644 --- a/Task/SHA-1/Fortran/sha-1.f +++ b/Task/SHA-1/Fortran/sha-1.f @@ -85,7 +85,7 @@ program sha1 allocate(character(m) :: name) call get_command_argument(i, name) call sha1hash(name, hash, dwStatus, filesize) - if (dwStatus*0 == 0) then + if (dwStatus == 0) then do j = 1, SHA1LEN write(*, "(Z2.2)", advance="NO") hash(j) end do diff --git a/Task/SHA-1/Halon/sha-1.halon b/Task/SHA-1/Halon/sha-1.halon new file mode 100644 index 0000000000..a18a36f923 --- /dev/null +++ b/Task/SHA-1/Halon/sha-1.halon @@ -0,0 +1,2 @@ +$var = "Rosetta Code"; +echo sha1($var); diff --git a/Task/SHA-1/J/sha-1-4.j b/Task/SHA-1/J/sha-1-4.j deleted file mode 100644 index 7d4c645a0c..0000000000 --- a/Task/SHA-1/J/sha-1-4.j +++ /dev/null @@ -1,8 +0,0 @@ -words2hex=: '0123456789abcdef' {~ (8#16)&#: - - words2hex sha1 text2bits 'Rosetta Code' -48c98f7e -5a6e736d -790ab740 -dfc3f51a -61abe2b5 diff --git a/Task/SHA-1/Kotlin/sha-1.kotlin b/Task/SHA-1/Kotlin/sha-1.kotlin new file mode 100644 index 0000000000..e8780edf5e --- /dev/null +++ b/Task/SHA-1/Kotlin/sha-1.kotlin @@ -0,0 +1,12 @@ +// version 1.0.6 + +import java.security.MessageDigest + +fun main(args: Array<String>) { + val text = "Rosetta Code" + val bytes = text.toByteArray() + val md = MessageDigest.getInstance("SHA-1") + val digest = md.digest(bytes) + for (byte in digest) print("%02x".format(byte)) + println() +} diff --git a/Task/SHA-1/Perl-6/sha-1.pl6 b/Task/SHA-1/Perl-6/sha-1.pl6 index af6c6a910f..fb62c909de 100644 --- a/Task/SHA-1/Perl-6/sha-1.pl6 +++ b/Task/SHA-1/Perl-6/sha-1.pl6 @@ -16,7 +16,7 @@ sub sha1-pad(Blob $msg) flat @padded.map({ :256[$^a,$^b,$^c,$^d] }), (bits +> 32)mod2³², (bits)mod2³²; } -sub sha1-block(@H is rw, @M is copy) +sub sha1-block(@H, @M is copy) { @M.push: S(1, [+^] @M[$_ «-« <3 8 14 16>] ) for 16 .. 79; diff --git a/Task/SHA-1/Zkl/sha-1.zkl b/Task/SHA-1/Zkl/sha-1.zkl new file mode 100644 index 0000000000..1e2e2c7319 --- /dev/null +++ b/Task/SHA-1/Zkl/sha-1.zkl @@ -0,0 +1,15 @@ +$ zkl // run the REPL +zkl: var MsgHash=Import("zklMsgHash") +MsgHash +zkl: MsgHash.SHA1("Rosetta Code") +48c98f7e5a6e736d790ab740dfc3f51a61abe2b5 + +zkl: var hash=MsgHash.SHA1("Rosetta Code",1,False) // hash once, return hash as bytes +Data(20) +zkl: hash.bytes() +L(72,201,143,126,90,110,115,109,121,10,183,64,223,195,245,26,97,171,226,181) +zkl: hash.bytes().apply("toString",16).concat() +48c98f7e5a6e736d79ab740dfc3f51a61abe2b5 + +zkl: MsgHash.SHA1("a"*1000,1000); // hash 1000 a's 1000 times +34aa973cd4c4daa4f61eeb2bdbad27316534016f diff --git a/Task/SHA-256/BaCon/sha-256.bacon b/Task/SHA-256/BaCon/sha-256.bacon new file mode 100644 index 0000000000..0848003707 --- /dev/null +++ b/Task/SHA-256/BaCon/sha-256.bacon @@ -0,0 +1,14 @@ +PRAGMA INCLUDE <openssl/sha.h> +PRAGMA LDFLAGS -lcrypto + +OPTION MEMTYPE unsigned char + +DECLARE result TYPE unsigned char* + +result = SHA256("Rosetta code", 12, 0) + +FOR i = 0 TO SHA256_DIGEST_LENGTH-1 + PRINT PEEK(result+i) FORMAT "%02x" +NEXT + +PRINT diff --git a/Task/SHA-256/C++/sha-256.cpp b/Task/SHA-256/C++/sha-256.cpp new file mode 100644 index 0000000000..0ccc8e6aa7 --- /dev/null +++ b/Task/SHA-256/C++/sha-256.cpp @@ -0,0 +1,19 @@ +#include <iostream> +#include <cryptopp/filters.h> +#include <cryptopp/hex.h> +#include <cryptopp/sha.h> + +int main(int argc, char **argv){ + CryptoPP::SHA256 hash; + std::string digest; + std::string message = "Rosetta code"; + + CryptoPP::StringSource s(message, true, + new CryptoPP::HashFilter(hash, + new CryptoPP::HexEncoder( + new CryptoPP::StringSink(digest)))); + + std::cout << digest << std::endl; + + return 0; +} diff --git a/Task/SHA-256/Fortran/sha-256.f b/Task/SHA-256/Fortran/sha-256.f index cc23a1eb83..1341e65cf5 100644 --- a/Task/SHA-256/Fortran/sha-256.f +++ b/Task/SHA-256/Fortran/sha-256.f @@ -87,7 +87,7 @@ program sha256 allocate(character(m) :: name) call get_command_argument(i, name) call sha256hash(name, hash, dwStatus, filesize) - if (dwStatus*0 == 0) then + if (dwStatus == 0) then do j = 1, SHA256LEN write(*, "(Z2.2)", advance="NO") hash(j) end do diff --git a/Task/SHA-256/Halon/sha-256.halon b/Task/SHA-256/Halon/sha-256.halon new file mode 100644 index 0000000000..5787b50d74 --- /dev/null +++ b/Task/SHA-256/Halon/sha-256.halon @@ -0,0 +1,2 @@ +$var = "Rosetta code"; +echo sha2($var, 256); diff --git a/Task/SHA-256/Julia/sha-256.julia b/Task/SHA-256/Julia/sha-256.julia index b0ca1f726d..6469cb01b8 100644 --- a/Task/SHA-256/Julia/sha-256.julia +++ b/Task/SHA-256/Julia/sha-256.julia @@ -3,7 +3,7 @@ standard = "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf" using SHA -crypt = sha256(clear) +crypt = join(map(hex, sha256("Rosetta code"))) println("Testing Julia's SHA-256:") if crypt == standard diff --git a/Task/SHA-256/Kotlin/sha-256.kotlin b/Task/SHA-256/Kotlin/sha-256.kotlin new file mode 100644 index 0000000000..ba9dac71d4 --- /dev/null +++ b/Task/SHA-256/Kotlin/sha-256.kotlin @@ -0,0 +1,12 @@ +// version 1.0.6 + +import java.security.MessageDigest + +fun main(args: Array<String>) { + val text = "Rosetta code" + val bytes = text.toByteArray() + val md = MessageDigest.getInstance("SHA-256") + val digest = md.digest(bytes) + for (byte in digest) print("%02x".format(byte)) + println() +} diff --git a/Task/SHA-256/PowerShell/sha-256.psh b/Task/SHA-256/PowerShell/sha-256.psh new file mode 100644 index 0000000000..8a8502ad28 --- /dev/null +++ b/Task/SHA-256/PowerShell/sha-256.psh @@ -0,0 +1,2 @@ +Set-Content -Value "Rosetta code" -Path C:\Colors\blue.txt -NoNewline -Force +Get-FileHash -Path C:\Colors\blue.txt -Algorithm SHA256 diff --git a/Task/SHA-256/Zkl/sha-256.zkl b/Task/SHA-256/Zkl/sha-256.zkl new file mode 100644 index 0000000000..cc6de6c8bb --- /dev/null +++ b/Task/SHA-256/Zkl/sha-256.zkl @@ -0,0 +1,2 @@ +var MsgHash=Import("zklMsgHash"); +MsgHash.SHA256("Rosetta code")=="764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf" diff --git a/Task/Safe-addition/Kotlin/safe-addition.kotlin b/Task/Safe-addition/Kotlin/safe-addition.kotlin new file mode 100644 index 0000000000..e7312a2a51 --- /dev/null +++ b/Task/Safe-addition/Kotlin/safe-addition.kotlin @@ -0,0 +1,13 @@ +// version 1.1.2 + +fun stepDown(d: Double) = Math.nextAfter(d, Double.NEGATIVE_INFINITY) + +fun stepUp(d: Double) = Math.nextUp(d) + +fun safeAdd(a: Double, b: Double) = stepDown(a + b).rangeTo(stepUp(a + b)) + +fun main(args: Array<String>) { + val a = 1.2 + val b = 0.03 + println("($a + $b) is in the range ${safeAdd(a, b)}") +} diff --git a/Task/Same-Fringe/Haskell/same-fringe.hs b/Task/Same-Fringe/Haskell/same-fringe.hs index 531ae4dcdc..647318fb2d 100644 --- a/Task/Same-Fringe/Haskell/same-fringe.hs +++ b/Task/Same-Fringe/Haskell/same-fringe.hs @@ -1,24 +1,29 @@ -data Tree a = Leaf a | Node (Tree a) (Tree a) - deriving (Show, Eq) +data Tree a + = Leaf a + | Node (Tree a) + (Tree a) + deriving (Show, Eq) fringe :: Tree a -> [a] fringe (Leaf x) = [x] fringe (Node n1 n2) = fringe n1 ++ fringe n2 -sameFringe :: (Eq a) => Tree a -> Tree a -> Bool +sameFringe + :: (Eq a) + => Tree a -> Tree a -> Bool sameFringe t1 t2 = fringe t1 == fringe t2 +main :: IO () main = do - let a = Node (Leaf 1) (Node (Leaf 2) (Node (Leaf 3) (Node (Leaf 4) (Leaf 5)))) - b = Node (Leaf 1) (Node (Node (Leaf 2) (Leaf 3)) (Node (Leaf 4) (Leaf 5))) - c = Node (Node (Node (Node (Leaf 1) (Leaf 2)) (Leaf 3)) (Leaf 4)) (Leaf 5) - print $ sameFringe a a - print $ sameFringe a b - print $ sameFringe a c - - let x = Node (Leaf 1) (Node (Leaf 2) (Node (Leaf 3) (Node (Leaf 4) (Node (Leaf 5) (Leaf 6))))) - y = Node (Leaf 0) (Node (Node (Leaf 2) (Leaf 3)) (Node (Leaf 4) (Leaf 5))) - z = Node (Leaf 1) (Node (Leaf 2) (Node (Node (Leaf 4) (Leaf 3)) (Leaf 5))) - print $ sameFringe a x - print $ sameFringe a y - print $ sameFringe a z + let a = Node (Leaf 1) (Node (Leaf 2) (Node (Leaf 3) (Node (Leaf 4) (Leaf 5)))) + b = Node (Leaf 1) (Node (Node (Leaf 2) (Leaf 3)) (Node (Leaf 4) (Leaf 5))) + c = Node (Node (Node (Node (Leaf 1) (Leaf 2)) (Leaf 3)) (Leaf 4)) (Leaf 5) + x = + Node + (Leaf 1) + (Node + (Leaf 2) + (Node (Leaf 3) (Node (Leaf 4) (Node (Leaf 5) (Leaf 6))))) + y = Node (Leaf 0) (Node (Node (Leaf 2) (Leaf 3)) (Node (Leaf 4) (Leaf 5))) + z = Node (Leaf 1) (Node (Leaf 2) (Node (Node (Leaf 4) (Leaf 3)) (Leaf 5))) + mapM_ print $ sameFringe a <$> [a, b, c, x, y, z] diff --git a/Task/Same-Fringe/jq/same-fringe-1.jq b/Task/Same-Fringe/Jq/same-fringe-1.jq similarity index 100% rename from Task/Same-Fringe/jq/same-fringe-1.jq rename to Task/Same-Fringe/Jq/same-fringe-1.jq diff --git a/Task/Same-Fringe/jq/same-fringe-2.jq b/Task/Same-Fringe/Jq/same-fringe-2.jq similarity index 100% rename from Task/Same-Fringe/jq/same-fringe-2.jq rename to Task/Same-Fringe/Jq/same-fringe-2.jq diff --git a/Task/Same-Fringe/jq/same-fringe-3.jq b/Task/Same-Fringe/Jq/same-fringe-3.jq similarity index 100% rename from Task/Same-Fringe/jq/same-fringe-3.jq rename to Task/Same-Fringe/Jq/same-fringe-3.jq diff --git a/Task/Same-Fringe/jq/same-fringe-4.jq b/Task/Same-Fringe/Jq/same-fringe-4.jq similarity index 100% rename from Task/Same-Fringe/jq/same-fringe-4.jq rename to Task/Same-Fringe/Jq/same-fringe-4.jq diff --git a/Task/Same-Fringe/Phix/same-fringe.phix b/Task/Same-Fringe/Phix/same-fringe.phix new file mode 100644 index 0000000000..a18cbc1393 --- /dev/null +++ b/Task/Same-Fringe/Phix/same-fringe.phix @@ -0,0 +1,79 @@ +-- +-- demo\rosetta\Same_Fringe.exw +-- ============================ +-- +-- Requires 0.7.5 or later (implementation revealed that task_yield did not +-- have side effects of e_all properly set.) +-- +constant tests = {{0,1,{0,2,0}}, + {{0,1,0},2,0}, + {{0,1,0},2,{0,3,0}}, + } + +sequence tasks +integer res = 0 +sequence sdata = repeat(0,2) + +integer active_tasks +integer show_details = 1 + +procedure scan(sequence tree, integer level, integer tidx) +object {left,data,right} = tree + if res=0 then + if left!=0 then scan(left,level+1,tidx) end if + sdata[tidx] = data + if show_details then + printf(1,"task[%d] sets sdata[%d] to ",tidx) + ?data + end if + if res=0 then + task_suspend(task_self()) + task_yield() + end if + if right!=0 then scan(right,level+1,tidx) end if + end if + if level=1 then + if show_details then + printf(1,"task[%d] ends\n",tidx) + end if + active_tasks -= 1 + tasks[tidx] = 0 + sdata[tidx] = -1 -- (or use a separate flag) + end if +end procedure + +?"started" +procedure test(integer t1, integer t2) + tasks = {task_create(routine_id("scan"),{tests[t1],1,1}), + task_create(routine_id("scan"),{tests[t2],1,2})} + active_tasks = 2 + res = 0 + while active_tasks>0 do + if tasks[1] then + task_schedule(tasks[1],1) + task_yield() + end if + if tasks[2] then + task_schedule(tasks[2],1) + task_yield() + end if + if res=0 then + res = compare(sdata[1],sdata[2]) + if show_details then + ?{res,sdata[1],sdata[2],active_tasks} + end if + end if + end while + printf(1,"test(%d,%d):%d\n",{t1,t2,res}) +end procedure + +test(1,1) +show_details = 0 +test(1,2) +test(1,3) +test(2,1) +test(2,2) +test(2,3) +test(3,1) +test(3,2) +test(3,3) diff --git a/Task/Same-Fringe/Zkl/same-fringe.zkl b/Task/Same-Fringe/Zkl/same-fringe.zkl new file mode 100644 index 0000000000..6584f5d86e --- /dev/null +++ b/Task/Same-Fringe/Zkl/same-fringe.zkl @@ -0,0 +1,27 @@ +var G=Utils.Generator; +//Tree: (node,left,right) or (leaf) or (node,left) ... +aTree := T(1, T(2, T(4, T(7)), T(5)), T(3, T(6, T(8), T(9)))); +bTree := aTree; +println("aTree and bTree ",sameFringe(aTree,bTree) and "have" or "don't have", + " the same leaves."); +cTree := T(1, T(2, T(4, T(7)), T(5)), T(3, T(6, T(8)))); +dTree := T(1, T(2, T(4, T(7)), T(5)), T(3, T(6, T(8), T(9)))); +println("cTree and dTree ",sameFringe(cTree,dTree) and "have"or"don't have", + " the same leaves."); + +fcn sameFringe(a,b){ same(G(genLeaves,a),G(genLeaves,b)) } + +fcn same(g1,g2){ //(Generator,Generator) + foreach n1,n2 in (g1.zip(g2)){ //-->(int,int) ... + if(n1 != n2) return(); // == return(Void) + } + return(not (g2._next() or g2._next())); //-->False if g1 or g2 has leaves +} + +fcn genLeaves(tree){ + switch(tree.len()){ // (), (leaf), (node,left, [right]) + case(1){ vm.yield(tree[0]) } // leaf: int + case(2){ genLeaves(tree[1]); } + else { genLeaves(tree[1]); genLeaves(tree[2]); } + } +} diff --git a/Task/Scope-Function-names-and-labels/Bc/scope-function-names-and-labels.bc b/Task/Scope-Function-names-and-labels/Bc/scope-function-names-and-labels.bc new file mode 100644 index 0000000000..f9c05e30ab --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Bc/scope-function-names-and-labels.bc @@ -0,0 +1,10 @@ +f(1) /* First output line */ +define f(x) { + return(x) +} +f(3) /* Second output line */ + +define f(x) { + return(x - 1) +} +f(3) /* Third output line */ diff --git a/Task/Scope-Function-names-and-labels/C/scope-function-names-and-labels.c b/Task/Scope-Function-names-and-labels/C/scope-function-names-and-labels.c index 72da19ffb9..855816a5bb 100644 --- a/Task/Scope-Function-names-and-labels/C/scope-function-names-and-labels.c +++ b/Task/Scope-Function-names-and-labels/C/scope-function-names-and-labels.c @@ -14,7 +14,7 @@ int main(void) int x; printf("This will demonstrate function and label scopes.\n"); - printf("All output is happening throung printf(), a function declared in the header stdio.h, which is external to this program.\n"); + printf("All output is happening through printf(), a function declared in the header stdio.h, which is external to this program.\n"); printf("Enter a number: "); if (scanf("%d", &x) != 1) return 0; diff --git a/Task/Scope-Function-names-and-labels/Haskell/scope-function-names-and-labels-1.hs b/Task/Scope-Function-names-and-labels/Haskell/scope-function-names-and-labels-1.hs new file mode 100644 index 0000000000..c47b1b7180 --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Haskell/scope-function-names-and-labels-1.hs @@ -0,0 +1,7 @@ +add3 :: Int -> Int-> Int-> Int +add3 x y z = add2 x y + z + +add2 :: Int -> Int -> Int +add2 x y = x + y + +main :: putStrLn(show (add3 5 6 5)) diff --git a/Task/Scope-Function-names-and-labels/Haskell/scope-function-names-and-labels-2.hs b/Task/Scope-Function-names-and-labels/Haskell/scope-function-names-and-labels-2.hs new file mode 100644 index 0000000000..2db474a95f --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Haskell/scope-function-names-and-labels-2.hs @@ -0,0 +1,5 @@ +getSquaredSum :: Int-> Int-> Int +getSquaredSum x y = g x + h y + where + g a = a*a + h b = b*b diff --git a/Task/Scope-Function-names-and-labels/jq/scope-function-names-and-labels-1.jq b/Task/Scope-Function-names-and-labels/Jq/scope-function-names-and-labels-1.jq similarity index 100% rename from Task/Scope-Function-names-and-labels/jq/scope-function-names-and-labels-1.jq rename to Task/Scope-Function-names-and-labels/Jq/scope-function-names-and-labels-1.jq diff --git a/Task/Scope-Function-names-and-labels/jq/scope-function-names-and-labels-2.jq b/Task/Scope-Function-names-and-labels/Jq/scope-function-names-and-labels-2.jq similarity index 100% rename from Task/Scope-Function-names-and-labels/jq/scope-function-names-and-labels-2.jq rename to Task/Scope-Function-names-and-labels/Jq/scope-function-names-and-labels-2.jq diff --git a/Task/Scope-Function-names-and-labels/jq/scope-function-names-and-labels-3.jq b/Task/Scope-Function-names-and-labels/Jq/scope-function-names-and-labels-3.jq similarity index 100% rename from Task/Scope-Function-names-and-labels/jq/scope-function-names-and-labels-3.jq rename to Task/Scope-Function-names-and-labels/Jq/scope-function-names-and-labels-3.jq diff --git a/Task/Scope-Function-names-and-labels/Kotlin/scope-function-names-and-labels.kotlin b/Task/Scope-Function-names-and-labels/Kotlin/scope-function-names-and-labels.kotlin new file mode 100644 index 0000000000..b9975a2c3a --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Kotlin/scope-function-names-and-labels.kotlin @@ -0,0 +1,66 @@ +// version 1.1.2 + +// top level function visible anywhere within the current module +internal fun a() = println("calling a") + +object B { + // object level function visible everywhere, by default + fun f() = println("calling f") +} + +open class C { + // class level function visible everywhere, by default + fun g() = println("calling g") + + // class level function only visible within C + private fun h() = println("calling h") + + // class level function only visible within C and its subclasses + protected fun i() { + println("calling i") + println("calling h") // OK as h within same class + // nested function in scope until end of i + fun j() = println("calling j") + j() + } +} + +class D : C(), E { + // class level function visible anywhere within the same module + fun k() { + println("calling k") + i() // OK as C.i is protected + m() // OK as E.m is public and has a body + } +} + +interface E { + fun m() { + println("calling m") + } +} + +fun main(args: Array<String>) { + a() // OK as a is internal + B.f() // OK as f is public + val c = C() + c.g() // OK as g is public but can't call h or i via c + val d = D() + d.k() // OK as k is public + // labelled lambda expression assigned to variable 'l' + val l = lambda@ { -> + outer@ for (i in 1..3) { + for (j in 1..3) { + if (i == 3) break@outer // jumps out of outer loop + if (j == 2) continue@outer // continues with next iteration of outer loop + println ("i = $i, j = $j") + } + if (i > 1) println ("i = $i") // never executed + } + val n = 1 + if (n == 1) return@lambda // returns from lambda + println("n = $n") // never executed + } + l() // invokes lambda + println("Good-bye!") // will be executed +} diff --git a/Task/Scope-Function-names-and-labels/Ruby/scope-function-names-and-labels.rb b/Task/Scope-Function-names-and-labels/Ruby/scope-function-names-and-labels.rb new file mode 100644 index 0000000000..0df2e1bea6 --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Ruby/scope-function-names-and-labels.rb @@ -0,0 +1,7 @@ +def welcome(name) + puts "hello #{name}" +end +puts "What is your name?" +$name = STDIN.gets +welcome($name) +return diff --git a/Task/Scope-Function-names-and-labels/Zkl/scope-function-names-and-labels.zkl b/Task/Scope-Function-names-and-labels/Zkl/scope-function-names-and-labels.zkl new file mode 100644 index 0000000000..4dc885a547 --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Zkl/scope-function-names-and-labels.zkl @@ -0,0 +1 @@ +class C{ fcn [private] f{} } diff --git a/Task/Scope-modifiers/BBC-BASIC/scope-modifiers.bbc b/Task/Scope-modifiers/BBC-BASIC/scope-modifiers.bbc deleted file mode 100644 index 364fb9a4df..0000000000 --- a/Task/Scope-modifiers/BBC-BASIC/scope-modifiers.bbc +++ /dev/null @@ -1,33 +0,0 @@ - var1$ = "Global1" - var2$ = "Global2" - - PRINT "Before function call:" - PRINT "var1$ = """ var1$ """" - PRINT "var2$ = """ var2$ """" - - PROCtestscope(var1$) - PROCtestscope(var1$) - - PRINT "After function call:" - PRINT "var1$ = """ var1$ """" - PRINT "var2$ = """ var2$ """" - END - - DEF PROCtestscope(var2$) - PRINT "On entry to function:" - PRINT "var1$ = """ var1$ """" - PRINT "var2$ = """ var2$ """" - - LOCAL var1$ - PRIVATE var2$ - PRINT "After LOCAL/PRIVATE:" - PRINT "var1$ = """ var1$ """" - PRINT "var2$ = """ var2$ """" - - var1$ = "Local" - var2$ = "Private" - PRINT "After assignments:" - PRINT "var1$ = """ var1$ """" - PRINT "var2$ = """ var2$ """" - - ENDPROC diff --git a/Task/Scope-modifiers/Bc/scope-modifiers.bc b/Task/Scope-modifiers/Bc/scope-modifiers.bc new file mode 100644 index 0000000000..1225e70e2b --- /dev/null +++ b/Task/Scope-modifiers/Bc/scope-modifiers.bc @@ -0,0 +1,40 @@ +define g(a) { + auto b + + b = 3 + + "Inside g: a = "; a + "Inside g: b = "; b + "Inside g: c = "; c + "Inside g: d = "; d + + a = 3; b = 3; c = 3; d = 3 +} + +define f(a) { + auto b, c + + b = 2; c = 2 + "Inside f (before call): a = "; a + "Inside f (before call): b = "; b + "Inside f (before call): c = "; c + "Inside f (before call): d = "; d + x = g(2) /* Assignment prevents output of the return value */ + "Inside f (after call): a = "; a + "Inside f (after call): b = "; b + "Inside f (after call): c = "; c + "Inside f (after call): d = "; d + + a = 2; b = 2; c = 2; d = 2 +} + +a = 1; b = 1; c = 1; d = 1 +"Global scope (before call): a = "; a +"Global scope (before call): b = "; b +"Global scope (before call): c = "; c +"Global scope (before call): d = "; d +x = f(1) +"Global scope (before call): a = "; a +"Global scope (before call): b = "; b +"Global scope (before call): c = "; c +"Global scope (before call): d = "; d diff --git a/Task/Scope-modifiers/C-sharp/scope-modifiers-1.cs b/Task/Scope-modifiers/C-sharp/scope-modifiers-1.cs new file mode 100644 index 0000000000..957eb45462 --- /dev/null +++ b/Task/Scope-modifiers/C-sharp/scope-modifiers-1.cs @@ -0,0 +1,13 @@ +public //visible to anything. +protected //visible to current class and to derived classes. +internal //visible to anything inside the same assembly (.dll/.exe). +protected internal //visible to anything inside the same assembly and also to derived classes outside the assembly. +private //visible only to the current class. + +//Modifier | Class | Assembly | Subclass | World +//-------------------------------------------------------- +//public | Y | Y | Y | Y +//protected internal | Y | Y | Y | N +//protected | Y | N | Y | N +//internal | Y | Y | N | N +//private | Y | N | N | N diff --git a/Task/Scope-modifiers/C-sharp/scope-modifiers-2.cs b/Task/Scope-modifiers/C-sharp/scope-modifiers-2.cs new file mode 100644 index 0000000000..1a1240d32d --- /dev/null +++ b/Task/Scope-modifiers/C-sharp/scope-modifiers-2.cs @@ -0,0 +1,21 @@ +public interface IPrinter +{ + void Print(); +} + +public class IntPrinter : IPrinter +{ + void IPrinter.Print() { // explicit implementation + Console.WriteLine(123); + } + + public static void Main() { + //====Error==== + IntPrinter p = new IntPrinter(); + p.Print(); + + //====Valid==== + IPrinter p = new IntPrinter(); + p.Print(); + } +} diff --git a/Task/Scope-modifiers/Kotlin/scope-modifiers.kotlin b/Task/Scope-modifiers/Kotlin/scope-modifiers.kotlin new file mode 100644 index 0000000000..328eb19944 --- /dev/null +++ b/Task/Scope-modifiers/Kotlin/scope-modifiers.kotlin @@ -0,0 +1,22 @@ +// version 1.1.2 + +class SomeClass { + val id: Int + + companion object { + private var lastId = 0 + val objectsCreated get() = lastId + } + + init { + id = ++lastId + } +} + +fun main(args: Array<String>) { + val sc1 = SomeClass() + val sc2 = SomeClass() + println(sc1.id) + println(sc2.id) + println(SomeClass.objectsCreated) +} diff --git a/Task/Scope-modifiers/Phix/scope-modifiers-1.phix b/Task/Scope-modifiers/Phix/scope-modifiers-1.phix new file mode 100644 index 0000000000..0789b922f0 --- /dev/null +++ b/Task/Scope-modifiers/Phix/scope-modifiers-1.phix @@ -0,0 +1,10 @@ +forward function localf() -- not normally necesssary, but will not harm +forward global function globalf() -- "" + +function localf() + return 1 +end function + +global function globalf() + return 2 +end function diff --git a/Task/Scope-modifiers/Phix/scope-modifiers-2.phix b/Task/Scope-modifiers/Phix/scope-modifiers-2.phix new file mode 100644 index 0000000000..db93c951ac --- /dev/null +++ b/Task/Scope-modifiers/Phix/scope-modifiers-2.phix @@ -0,0 +1,5 @@ +include somefile.e as xxx +-- alternatively, within somefile.e: +namespace xxx -- (only supported in Phix for compatibility with OpenEuphoria) + +res = xxx:globalf() -- call a global function named globalf, specifically the one declared in somefile.e diff --git a/Task/Search-a-list/Aime/search-a-list.aime b/Task/Search-a-list/Aime/search-a-list.aime index 5e16035484..bd76cdb763 100644 --- a/Task/Search-a-list/Aime/search-a-list.aime +++ b/Task/Search-a-list/Aime/search-a-list.aime @@ -1,42 +1,17 @@ -integer +void search(list l, text s) { integer i; i = 0; - while (i < l_length(l)) { - if (!compare(l_q_text(l, i), s)) { + while (i < ~l) { + if (!compare(l[i], s)) { break; } i += 1; } - if (i == l_length(l)) { - i = -1; - } - - return i; -} - -void -search_for(list l, ...) -{ - integer i; - - i = 1; - while (i < count()) { - integer index; - - index = search(l, $i); - o_text($i); - if (index == -1) { - o_text(" is not in the haystack\n"); - } else { - o_plan(" is at ", index, "\n"); - } - - i += 1; - } + o_(s, " is ", i == ~l ? "not in the haystack" : cat("at ", itoa(i)), "\n"); } integer @@ -46,7 +21,7 @@ main(void) l = l_effect("Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"); - search_for(l, "Bush", "Washington", "Zag"); + __ucall(search, 1, 1, l, "Bush", "Washington", "Zag"); return 0; } diff --git a/Task/Search-a-list/Elena/search-a-list.elena b/Task/Search-a-list/Elena/search-a-list.elena index 5e8e986c1e..a2a628131c 100644 --- a/Task/Search-a-list/Elena/search-a-list.elena +++ b/Task/Search-a-list/Elena/search-a-list.elena @@ -1,17 +1,16 @@ -#import system. -#import system'routines. -#import extensions. +import system'routines. +import extensions. -#symbol program = +program = [ - #var haystack := ("Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"). + var haystack := ("Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"). - ("Washington", "Bush") run &each: needle + ("Washington", "Bush") forEach(:needle) [ - #var index := haystack indexOf:needle. + var index := haystack indexOfElement:needle. - (index == -1) - ? [ console writeLine:needle:" is not in haystack" ] - ! [ console writeLine:index:" ":needle ]. + if (index == -1) + [ console printLine(needle," is not in haystack") ]; + [ console printLine(index," ",needle) ]. ]. ]. diff --git a/Task/Search-a-list/FreeBASIC/search-a-list.freebasic b/Task/Search-a-list/FreeBASIC/search-a-list.freebasic new file mode 100644 index 0000000000..40dca7f901 --- /dev/null +++ b/Task/Search-a-list/FreeBASIC/search-a-list.freebasic @@ -0,0 +1,61 @@ +' FB 1.05.0 Win64 +' Works FB 1.05.0 Linux Mint 64 + +Function tryFindString(s() As String, search As String, ByRef index As Integer) As Boolean + Dim length As Integer = UBound(s) - LBound(s) + 1 + If length = 0 Then + index = LBound(s) - 1 '' outside array + Return False + End If + For i As Integer = LBound(s) To UBound(s) + If s(i) = search Then + index = i '' first occurrence + Return True + End If + Next + index = LBound(s) - 1 '' outside array + Return False +End Function + +Function tryFindLastString(s() As String, search As String, ByRef index As Integer) As Boolean + Dim length As Integer = UBound(s) - LBound(s) + 1 + If length = 0 Then + index = LBound(s) - 1 '' outside array + Return False + End If + Dim maxIndex As Integer = LBound(s) - 1 '' outside array + For i As Integer = LBound(s) To UBound(s) + If s(i) = search Then + maxIndex = i + End If + Next + If maxIndex > LBound(s) - 1 Then + index = maxIndex '' last occurrence + Return True + Else + Return False + End If +End Function + +Dim haystack(1 To 9) As String = {"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"} +Dim needle(1 To 4) As String = {"Zag", "Krusty", "Washington", "Bush"} + +Dim As Integer index +Dim As Boolean found +For i As Integer = 1 To 4 + found = tryFindString(haystack(), needle(i), index) + If found Then + Print needle(i); " found first at index"; index + Else + Print needle(i); " is not present" + End If +Next +found = tryFindLastString(haystack(), needle(4), index) +If found Then + Print needle(4); " found last at index"; index +Else + Print needle(4); " is not present" +End If +Print +Print "Press any key to quit" +Sleep diff --git a/Task/Search-a-list/Gambas/search-a-list.gambas b/Task/Search-a-list/Gambas/search-a-list.gambas new file mode 100644 index 0000000000..19b546772d --- /dev/null +++ b/Task/Search-a-list/Gambas/search-a-list.gambas @@ -0,0 +1,16 @@ +Public Sub Main() +Dim sHaystack As String[] = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"] +Dim sNeedle As String = "Charlie" +Dim sOutput As String = "No needle found!" +Dim siCount As Short + +For siCount = 0 To sHaystack.Max + If sNeedle = sHaystack[siCount] Then + sOutPut = sNeedle & " found at index " & Str(siCount) + Break + End If +Next + +Print sOutput + +End diff --git a/Task/Search-a-list/J/search-a-list-2.j b/Task/Search-a-list/J/search-a-list-2.j index cdee2318ca..3dde01cb73 100644 --- a/Task/Search-a-list/J/search-a-list-2.j +++ b/Task/Search-a-list/J/search-a-list-2.j @@ -1,3 +1,4 @@ - Haystack ;:^:_1@(] ,. [ ((<'is not in haystack')"_)`(#@[ I.@:= ])`(8!:0@])} i.) Needles -Washington is not in haystack -Bush 4 + Needles e. Haystack +0 1 + 1 2 3 4 5 6 7 8 9 e. 2 3 5 60 +0 1 1 0 1 0 0 0 0 diff --git a/Task/Search-a-list/J/search-a-list-3.j b/Task/Search-a-list/J/search-a-list-3.j index 7c93acd3d7..1bca63c90e 100644 --- a/Task/Search-a-list/J/search-a-list-3.j +++ b/Task/Search-a-list/J/search-a-list-3.j @@ -1,8 +1,4 @@ - msg=: (<'is not in haystack')"_ NB. not found message - idxmissing=: #@[ I.@:= ] NB. indices of items not found - fmtdata=: 8!:0@] NB. format atoms as boxed strings - findLastIndex=: ;:inv@(] ,. [ msg`idxmissing`fmtdata} i:) - - Haystack findLastIndex Needles NB. usage -Washington is not in haystack -Bush 7 + 1 2 3 4 5 6 7 8 9 I. 2 3 5 60 6.66 +1 2 4 9 6 + (;:'eight five four nine one seven six three two') I. ;:'two three five sixty' +8 7 1 7 diff --git a/Task/Search-a-list/J/search-a-list-4.j b/Task/Search-a-list/J/search-a-list-4.j new file mode 100644 index 0000000000..cdee2318ca --- /dev/null +++ b/Task/Search-a-list/J/search-a-list-4.j @@ -0,0 +1,3 @@ + Haystack ;:^:_1@(] ,. [ ((<'is not in haystack')"_)`(#@[ I.@:= ])`(8!:0@])} i.) Needles +Washington is not in haystack +Bush 4 diff --git a/Task/Search-a-list/J/search-a-list-5.j b/Task/Search-a-list/J/search-a-list-5.j new file mode 100644 index 0000000000..7c93acd3d7 --- /dev/null +++ b/Task/Search-a-list/J/search-a-list-5.j @@ -0,0 +1,8 @@ + msg=: (<'is not in haystack')"_ NB. not found message + idxmissing=: #@[ I.@:= ] NB. indices of items not found + fmtdata=: 8!:0@] NB. format atoms as boxed strings + findLastIndex=: ;:inv@(] ,. [ msg`idxmissing`fmtdata} i:) + + Haystack findLastIndex Needles NB. usage +Washington is not in haystack +Bush 7 diff --git a/Task/Search-a-list/Jq/search-a-list.jq b/Task/Search-a-list/Jq/search-a-list.jq new file mode 100644 index 0000000000..3cf378cfd1 --- /dev/null +++ b/Task/Search-a-list/Jq/search-a-list.jq @@ -0,0 +1,17 @@ +["a","b","c"] | index("b") +# => 1 + +["a","b","c","b"] | index("b") +# => 1 + +["a","b","c","b"] + | index("x") // error("element not found") +# => jq: error: element not found + +# Extra task - the last element of an array can be retrieved +# using `rindex/` or by using -1 as an index into the array produced by `indices/1`: +["a","b","c","b","d"] | rindex("b") +# => 3 + +["a","b","c","b","d"] | indices("b")[-1] +# => 3 diff --git a/Task/Search-a-list/Kotlin/search-a-list.kotlin b/Task/Search-a-list/Kotlin/search-a-list.kotlin new file mode 100644 index 0000000000..2c48fd562f --- /dev/null +++ b/Task/Search-a-list/Kotlin/search-a-list.kotlin @@ -0,0 +1,14 @@ +// version 1.0.6 (search_list.kt) + +fun main(args: Array<String>) { + val haystack = listOf("Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag") + println(haystack) + var needle = "Zag" + var index = haystack.indexOf(needle) + val index2 = haystack.lastIndexOf(needle) + println("\n'$needle' first occurs at index $index of the list") + println("'$needle' last occurs at index $index2 of the list\n") + needle = "Donald" + index = haystack.indexOf(needle) + if (index == -1) throw Exception("$needle does not occur in the list") +} diff --git a/Task/Search-a-list/Maxima/search-a-list-1.maxima b/Task/Search-a-list/Maxima/search-a-list-1.maxima deleted file mode 100644 index 8a52882fae..0000000000 --- a/Task/Search-a-list/Maxima/search-a-list-1.maxima +++ /dev/null @@ -1,9 +0,0 @@ -haystack: ["Zig","Zag","Wally","Ronald","Bush","Zig","Zag","Krusty","Charlie","Bush","Bozo"]; -needle: "Zag"; - -findneedle(needle, haystack, [opt]):=block([idx], - idx: sublist_indices(haystack, lambda([w], w=needle)), - if emptyp(idx) then throw('notfound), - if emptyp(opt) then return(idx), - opt: first(opt), - if opt='f then first(idx) else if opt='l then last(idx) else throw('unknownmode)); diff --git a/Task/Search-a-list/Maxima/search-a-list-2.maxima b/Task/Search-a-list/Maxima/search-a-list-2.maxima deleted file mode 100644 index 0c0d8e7da1..0000000000 --- a/Task/Search-a-list/Maxima/search-a-list-2.maxima +++ /dev/null @@ -1,12 +0,0 @@ -(%i32) catch(findneedle("Zag", haystack, 'f)); -(%o32) 2 -(%i33) catch(findneedle("Zag", haystack, 'l)); -(%o33) 7 -(%i34) catch(findneedle("Washington", haystack)); -(%o34) notfound -(%i35) catch(findneedle("Bush", haystack, 'f)); -(%o35) 5 -(%i36) catch(findneedle("Zag", haystack)); -(%o36) [2, 7] -(%i37) catch(findneedle("Zag", haystack, 'l)); -(%o37) 7 diff --git a/Task/Search-a-list/Objeck/search-a-list.objeck b/Task/Search-a-list/Objeck/search-a-list.objeck index 6748fdac96..1c1f1bb43c 100644 --- a/Task/Search-a-list/Objeck/search-a-list.objeck +++ b/Task/Search-a-list/Objeck/search-a-list.objeck @@ -1,18 +1,16 @@ -use Structure; +use Collection; -bundle Default { - class Test { - function : Main(args : String[]) ~ Nil { - haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]; - values := CompareVector->New(); - each(i : haystack) { - values->AddBack(haystack[i]->As(Compare)); - }; +class Test { + function : Main(args : String[]) ~ Nil { + haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]; + values := CompareVector->New(); + each(i : haystack) { + values->AddBack(haystack[i]->As(Compare)); + }; - needles := ["Washington", "Bush"]; - each(i : needles) { - values->Has(needles[i]->As(Compare))->PrintLine(); - }; - } + needles := ["Washington", "Bush"]; + each(i : needles) { + values->Has(needles[i]->As(Compare))->PrintLine(); + }; } } diff --git a/Task/Search-a-list/Objective-C/search-a-list-1.m b/Task/Search-a-list/Objective-C/search-a-list-1.m deleted file mode 100644 index 354460710c..0000000000 --- a/Task/Search-a-list/Objective-C/search-a-list-1.m +++ /dev/null @@ -1,8 +0,0 @@ -NSArray *haystack = [NSArray arrayWithObjects:@"Zig",@"Zag",@"Wally",@"Ronald",@"Bush",@"Krusty",@"Charlie",@"Bush",@"Bozo",nil]; -for (id needle in [NSArray arrayWithObjects:@"Washington",@"Bush",nil]) { - int index = [haystack indexOfObject:needle]; - if (index == NSNotFound) - NSLog(@"%@ is not in haystack", needle); - else - NSLog(@"%i %@", index, needle); -} diff --git a/Task/Search-a-list/Objective-C/search-a-list-2.m b/Task/Search-a-list/Objective-C/search-a-list-2.m deleted file mode 100644 index faa40e1d10..0000000000 --- a/Task/Search-a-list/Objective-C/search-a-list-2.m +++ /dev/null @@ -1,10 +0,0 @@ -NSArray *haystack = [NSArray arrayWithObjects:@"Zig",@"Zag",@"Wally",@"Ronald",@"Bush",@"Krusty",@"Charlie",@"Bush",@"Bozo",nil]; -id needle; -NSEnumerator *enm = [[NSArray arrayWithObjects:@"Washington",@"Bush",nil] objectEnumerator]; -while ((needle = [enm nextObject]) != nil) { - int index = [haystack indexOfObject:needle]; - if (index == NSNotFound) - NSLog(@"%@ is not in haystack", needle); - else - NSLog(@"%i %@", index, needle); -} diff --git a/Task/Search-a-list/OoRexx/search-a-list.rexx b/Task/Search-a-list/OoRexx/search-a-list.rexx new file mode 100644 index 0000000000..adce909f46 --- /dev/null +++ b/Task/Search-a-list/OoRexx/search-a-list.rexx @@ -0,0 +1,19 @@ +-- ordered collections always return the first hit +a = .array~of(1,2,3,4,4,5) +say a~index(4) +a2 = .array~new(5,5) -- multidimensional +a2[3,3] = 4 +-- the returned index is an array of values +say a2~index(4)~makestring('line', ',') +-- Note, list indexes are assigned when an item is added and +-- are not tied to relative position +l = .list~of(1,2,3,4,4,5) +say l~index(4) +q = .queue~of(1,2,3,4,4,5) +say q~index(4) +-- directories are unordered, so it is +-- undertermined which one is returned +d = .directory~new +d["foo"] = 4 +d["bar"] = 4 +say d~index(4) diff --git a/Task/Search-a-list/S-lang/search-a-list.slang b/Task/Search-a-list/S-lang/search-a-list.slang new file mode 100644 index 0000000000..b1c2a217a4 --- /dev/null +++ b/Task/Search-a-list/S-lang/search-a-list.slang @@ -0,0 +1,15 @@ +variable haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo","Ronald"]; + +define find(needle) +{ + variable i = where(haystack == needle); + if (length(i)) { + % print(sprintf("%s: first=%d, last=%d", needle, i[0], i[-1])); + return(i[0], i[-1]); + } + else + throw ApplicationError, "an exception"; +} + +($1, $2) = find("Ronald"); % returns 3, 9 +($1, $2) = find("McDonald"); % throws ApplicationError, labelled "an exception" diff --git a/Task/Search-a-list/Zkl/search-a-list-1.zkl b/Task/Search-a-list/Zkl/search-a-list-1.zkl new file mode 100644 index 0000000000..5652a3d110 --- /dev/null +++ b/Task/Search-a-list/Zkl/search-a-list-1.zkl @@ -0,0 +1,2 @@ +L("Krusty","Charlie","Bozo","Bozo").index("Charlie") //--> 1 +L("Krusty","Charlie","Bozo","Bozo").index("fred") //--> throws index error diff --git a/Task/Search-a-list/Zkl/search-a-list-2.zkl b/Task/Search-a-list/Zkl/search-a-list-2.zkl new file mode 100644 index 0000000000..396ed74d3e --- /dev/null +++ b/Task/Search-a-list/Zkl/search-a-list-2.zkl @@ -0,0 +1,3 @@ +haystack:=L("Krusty","Charlie","Bozo","Bozo"); +haystack.filterNs('==("Bozo"))[-1]; // -->3, indexError if not found +haystack.len() - 1 - haystack.reverse().index("Bozo"); // or this diff --git a/Task/Search-a-list/Zkl/search-a-list-3.zkl b/Task/Search-a-list/Zkl/search-a-list-3.zkl new file mode 100644 index 0000000000..46ac033aca --- /dev/null +++ b/Task/Search-a-list/Zkl/search-a-list-3.zkl @@ -0,0 +1,3 @@ +haystack:=Data(0,String,"Krusty","Charlie","Bozo","Bozo"); +if((n:=haystack.findString("Charlie")) != Void) n else throw(Exception.IndexError); +//-->7 diff --git a/Task/Search-a-list/jq/search-a-list.jq b/Task/Search-a-list/jq/search-a-list.jq deleted file mode 100644 index 99496deb7f..0000000000 --- a/Task/Search-a-list/jq/search-a-list.jq +++ /dev/null @@ -1,15 +0,0 @@ -["a","b","c"] | index("b") -# => 1 - -["a","b","c","b"] | index("b") -# => 1 - -["a","b","c","b"] - | index("x") as $ix - | if $ix then $ix else error("element not found") end -# => jq: error: element not found - -# Extra task - the last element of an array can be retrieved -# using -1 as an index: -["a","b","c","b","d"] | indices("b")[-1] -# => 3 diff --git a/Task/Secure-temporary-file/Go/secure-temporary-file-1.go b/Task/Secure-temporary-file/Go/secure-temporary-file-1.go deleted file mode 100644 index aa03714f37..0000000000 --- a/Task/Secure-temporary-file/Go/secure-temporary-file-1.go +++ /dev/null @@ -1,32 +0,0 @@ -package main - -import ( - "fmt" - "io/ioutil" - "log" - "os" -) - -func main() { - f, err := ioutil.TempFile("", "foo") - if err != nil { - log.Fatal(err) - } - defer f.Close() - - // We need to make sure we remove the file - // once it is no longer needed. - defer os.Remove(f.Name()) - - // … use the file via 'f' … - fmt.Fprintln(f, "Using temporary file:", f.Name()) - f.Seek(0, 0) - d, err := ioutil.ReadAll(f) - if err != nil { - log.Fatal(err) - } - fmt.Printf("Wrote and read: %s\n", d) - - // The defer statements above will close and remove the - // temporary file here (or on any return of this function). -} diff --git a/Task/Secure-temporary-file/Go/secure-temporary-file-2.go b/Task/Secure-temporary-file/Go/secure-temporary-file-2.go deleted file mode 100644 index fc4f315d4d..0000000000 --- a/Task/Secure-temporary-file/Go/secure-temporary-file-2.go +++ /dev/null @@ -1,6 +0,0 @@ -def file = File.createTempFile( "xxx", ".txt" ) - -// There is no requirement in the instructions to delete the file. -//file.deleteOnExit() - -println file diff --git a/Task/Secure-temporary-file/Kotlin/secure-temporary-file.kotlin b/Task/Secure-temporary-file/Kotlin/secure-temporary-file.kotlin new file mode 100644 index 0000000000..4c736dfcb6 --- /dev/null +++ b/Task/Secure-temporary-file/Kotlin/secure-temporary-file.kotlin @@ -0,0 +1,14 @@ +// version 1.1.2 + +import java.io.File + +fun main(args: Array<String>) { + try { + val tf = File.createTempFile("temp", ".tmp") + println(tf.absolutePath) + tf.delete() + } + catch (ex: Exception) { + println(ex.message) + } +} diff --git a/Task/Self-describing-numbers/00DESCRIPTION b/Task/Self-describing-numbers/00DESCRIPTION index 8d1f48b27d..8446addc3c 100644 --- a/Task/Self-describing-numbers/00DESCRIPTION +++ b/Task/Self-describing-numbers/00DESCRIPTION @@ -16,4 +16,12 @@ Self-describing numbers < 100.000.000  are:     1210,   2020 ;Task Description # Write a function/routine/method/... that will check whether a given positive integer is self-describing. # As an optional stretch goal - generate and display the set of self-describing numbers. + + +;Related tasks: +*   [[Fours is the number of letters in the ...]] +*   [[Look-and-say sequence]] +*   [[Number names]] +*   [[Self-referential sequence]] +*   [[Spelling of ordinal numbers]] <br><br> diff --git a/Task/Self-describing-numbers/C/self-describing-numbers-1.c b/Task/Self-describing-numbers/C/self-describing-numbers-1.c index ad7c2be178..047679cae1 100644 --- a/Task/Self-describing-numbers/C/self-describing-numbers-1.c +++ b/Task/Self-describing-numbers/C/self-describing-numbers-1.c @@ -1,45 +1,26 @@ #include <stdio.h> -int self_desc(const char *s) +inline int self_desc(unsigned long long xx) { - unsigned char cnt[10] = {0}; - int i; - for (i = 0; s[i] != '\0'; i++) cnt[s[i] - '0']++; - for (i = 0; s[i] != '\0'; i++) if (cnt[i] + '0' != s[i]) return 0; - return 1; -} + register unsigned int d, x; + unsigned char cnt[10] = {0}, dig[10] = {0}; -void gen(int n) -{ - char d[11]; - int one, i; - /* one = 0 may be confusing. 'one' is the number of digit 1s */ - for (one = 0; one <= 2 && one < n - 2; one++) { - for (i = 0; i <= n; d[i++] = 0); + for (d = 0; xx > ~0U; xx /= 10) + cnt[ dig[d++] = xx % 10 ]++; - if ((d[0] = n - 2 - one) != 2) { - d[2] = d[d[0] - 0] = 1; - d[1] = 2; - } else { - d[1] = one ? 1 : 0; - d[2] = 2; - } + for (x = xx; x; x /= 10) + cnt[ dig[d++] = x % 10 ]++; - for (i = 0; i < n; d[i++] += '0'); - if (self_desc(d)) printf("%s\n", d); - } + while(d-- && dig[x++] == cnt[d]); + + return d == -1; } int main() { int i; - const char *nums[] = { "1210", "1337", "2020", "21200", "3211000", "42101000", 0}; + for (i = 1; i < 100000000; i++) /* don't handle 0 */ + if (self_desc(i)) printf("%d\n", i); - for (i = 0; nums[i]; i++) - printf("%s is %sself describing\n", nums[i], - self_desc(nums[i]) ? "" : "not "); - - printf("\nAll autobiograph numbers:\n"); - for (i = 0; i < 11; i++) gen(i); return 0; } diff --git a/Task/Self-describing-numbers/C/self-describing-numbers-2.c b/Task/Self-describing-numbers/C/self-describing-numbers-2.c index 4201b39332..fe98e74c50 100644 --- a/Task/Self-describing-numbers/C/self-describing-numbers-2.c +++ b/Task/Self-describing-numbers/C/self-describing-numbers-2.c @@ -1,15 +1,5 @@ -1210 is self describing -1337 is not self describing -2020 is self describing -21200 is self describing -3211000 is self describing -42101000 is self describing - -All autobiograph numbers: -2020 1210 +2020 21200 3211000 42101000 -521001000 -6210001000 diff --git a/Task/Self-describing-numbers/C/self-describing-numbers-3.c b/Task/Self-describing-numbers/C/self-describing-numbers-3.c index 047679cae1..2e75fa52e5 100644 --- a/Task/Self-describing-numbers/C/self-describing-numbers-3.c +++ b/Task/Self-describing-numbers/C/self-describing-numbers-3.c @@ -1,26 +1,94 @@ #include <stdio.h> +#include <stdlib.h> +#include <string.h> -inline int self_desc(unsigned long long xx) -{ - register unsigned int d, x; - unsigned char cnt[10] = {0}, dig[10] = {0}; +#define BASE_MIN 2 +#define BASE_MAX 94 - for (d = 0; xx > ~0U; xx /= 10) - cnt[ dig[d++] = xx % 10 ]++; +void selfdesc(unsigned long); - for (x = xx; x; x /= 10) - cnt[ dig[d++] = x % 10 ]++; +const char *ref = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; +char *digs; +unsigned long *nums, *inds, inds_sum, inds_val, base; - while(d-- && dig[x++] == cnt[d]); - - return d == -1; +int main(int argc, char *argv[]) { +int used[BASE_MAX]; +unsigned long digs_n, i; + if (argc != 2) { + fprintf(stderr, "Usage is %s <digits>\n", argv[0]); + return EXIT_FAILURE; + } + digs = argv[1]; + digs_n = strlen(digs); + if (digs_n < BASE_MIN || digs_n > BASE_MAX) { + fprintf(stderr, "Invalid number of digits\n"); + return EXIT_FAILURE; + } + for (i = 0; i < BASE_MAX; i++) { + used[i] = 0; + } + for (i = 0; i < digs_n && strchr(ref, digs[i]) && !used[digs[i]-*ref]; i++) { + used[digs[i]-*ref] = 1; + } + if (i < digs_n) { + fprintf(stderr, "Invalid digits\n"); + return EXIT_FAILURE; + } + nums = calloc(digs_n, sizeof(unsigned long)); + if (!nums) { + fprintf(stderr, "Could not allocate memory for nums\n"); + return EXIT_FAILURE; + } + inds = malloc(sizeof(unsigned long)*digs_n); + if (!inds) { + fprintf(stderr, "Could not allocate memory for inds\n"); + free(nums); + return EXIT_FAILURE; + } + inds_sum = 0; + inds_val = 0; + for (base = BASE_MIN; base <= digs_n; base++) { + selfdesc(base); + } + free(inds); + free(nums); + return EXIT_SUCCESS; } -int main() -{ - int i; - for (i = 1; i < 100000000; i++) /* don't handle 0 */ - if (self_desc(i)) printf("%d\n", i); - - return 0; +void selfdesc(unsigned long i) { +unsigned long diff_sum, upper_min, j, lower, upper, k; + if (i) { + diff_sum = base-inds_sum; + upper_min = inds_sum ? diff_sum:base-1; + j = i-1; + if (j) { + lower = 0; + upper = (base-inds_val)/j; + } + else { + lower = diff_sum; + upper = diff_sum; + } + if (upper < upper_min) { + upper_min = upper; + } + for (inds[j] = lower; inds[j] <= upper_min; inds[j]++) { + nums[inds[j]]++; + inds_sum += inds[j]; + inds_val += inds[j]*j; + for (k = base-1; k > j && nums[k] <= inds[k] && inds[k]-nums[k] <= i; k--); + if (k == j) { + selfdesc(i-1); + } + inds_val -= inds[j]*j; + inds_sum -= inds[j]; + nums[inds[j]]--; + } + } + else { + for (j = 0; j < base; j++) { + putchar(digs[inds[j]]); + } + puts(""); + } } diff --git a/Task/Self-describing-numbers/C/self-describing-numbers-4.c b/Task/Self-describing-numbers/C/self-describing-numbers-4.c index fe98e74c50..ba43700dd0 100644 --- a/Task/Self-describing-numbers/C/self-describing-numbers-4.c +++ b/Task/Self-describing-numbers/C/self-describing-numbers-4.c @@ -1,5 +1,38 @@ +$ time ./selfdesc.exe 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 1210 2020 21200 3211000 42101000 +521001000 +6210001000 +72100001000 +821000001000 +9210000001000 +A2100000001000 +B21000000001000 +C210000000001000 +D2100000000001000 +E21000000000001000 +F210000000000001000 +G2100000000000001000 +H21000000000000001000 +I210000000000000001000 +J2100000000000000001000 +K21000000000000000001000 +L210000000000000000001000 +M2100000000000000000001000 +N21000000000000000000001000 +O210000000000000000000001000 +P2100000000000000000000001000 +Q21000000000000000000000001000 +R210000000000000000000000001000 +S2100000000000000000000000001000 +T21000000000000000000000000001000 +U210000000000000000000000000001000 +V2100000000000000000000000000001000 +W21000000000000000000000000000001000 + +real 0m0.094s +user 0m0.046s +sys 0m0.030s diff --git a/Task/Self-describing-numbers/C/self-describing-numbers-5.c b/Task/Self-describing-numbers/C/self-describing-numbers-5.c deleted file mode 100644 index 2e75fa52e5..0000000000 --- a/Task/Self-describing-numbers/C/self-describing-numbers-5.c +++ /dev/null @@ -1,94 +0,0 @@ -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#define BASE_MIN 2 -#define BASE_MAX 94 - -void selfdesc(unsigned long); - -const char *ref = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; -char *digs; -unsigned long *nums, *inds, inds_sum, inds_val, base; - -int main(int argc, char *argv[]) { -int used[BASE_MAX]; -unsigned long digs_n, i; - if (argc != 2) { - fprintf(stderr, "Usage is %s <digits>\n", argv[0]); - return EXIT_FAILURE; - } - digs = argv[1]; - digs_n = strlen(digs); - if (digs_n < BASE_MIN || digs_n > BASE_MAX) { - fprintf(stderr, "Invalid number of digits\n"); - return EXIT_FAILURE; - } - for (i = 0; i < BASE_MAX; i++) { - used[i] = 0; - } - for (i = 0; i < digs_n && strchr(ref, digs[i]) && !used[digs[i]-*ref]; i++) { - used[digs[i]-*ref] = 1; - } - if (i < digs_n) { - fprintf(stderr, "Invalid digits\n"); - return EXIT_FAILURE; - } - nums = calloc(digs_n, sizeof(unsigned long)); - if (!nums) { - fprintf(stderr, "Could not allocate memory for nums\n"); - return EXIT_FAILURE; - } - inds = malloc(sizeof(unsigned long)*digs_n); - if (!inds) { - fprintf(stderr, "Could not allocate memory for inds\n"); - free(nums); - return EXIT_FAILURE; - } - inds_sum = 0; - inds_val = 0; - for (base = BASE_MIN; base <= digs_n; base++) { - selfdesc(base); - } - free(inds); - free(nums); - return EXIT_SUCCESS; -} - -void selfdesc(unsigned long i) { -unsigned long diff_sum, upper_min, j, lower, upper, k; - if (i) { - diff_sum = base-inds_sum; - upper_min = inds_sum ? diff_sum:base-1; - j = i-1; - if (j) { - lower = 0; - upper = (base-inds_val)/j; - } - else { - lower = diff_sum; - upper = diff_sum; - } - if (upper < upper_min) { - upper_min = upper; - } - for (inds[j] = lower; inds[j] <= upper_min; inds[j]++) { - nums[inds[j]]++; - inds_sum += inds[j]; - inds_val += inds[j]*j; - for (k = base-1; k > j && nums[k] <= inds[k] && inds[k]-nums[k] <= i; k--); - if (k == j) { - selfdesc(i-1); - } - inds_val -= inds[j]*j; - inds_sum -= inds[j]; - nums[inds[j]]--; - } - } - else { - for (j = 0; j < base; j++) { - putchar(digs[inds[j]]); - } - puts(""); - } -} diff --git a/Task/Self-describing-numbers/C/self-describing-numbers-6.c b/Task/Self-describing-numbers/C/self-describing-numbers-6.c deleted file mode 100644 index ba43700dd0..0000000000 --- a/Task/Self-describing-numbers/C/self-describing-numbers-6.c +++ /dev/null @@ -1,38 +0,0 @@ -$ time ./selfdesc.exe 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ -1210 -2020 -21200 -3211000 -42101000 -521001000 -6210001000 -72100001000 -821000001000 -9210000001000 -A2100000001000 -B21000000001000 -C210000000001000 -D2100000000001000 -E21000000000001000 -F210000000000001000 -G2100000000000001000 -H21000000000000001000 -I210000000000000001000 -J2100000000000000001000 -K21000000000000000001000 -L210000000000000000001000 -M2100000000000000000001000 -N21000000000000000000001000 -O210000000000000000000001000 -P2100000000000000000000001000 -Q21000000000000000000000001000 -R210000000000000000000000001000 -S2100000000000000000000000001000 -T21000000000000000000000000001000 -U210000000000000000000000000001000 -V2100000000000000000000000000001000 -W21000000000000000000000000000001000 - -real 0m0.094s -user 0m0.046s -sys 0m0.030s diff --git a/Task/Self-describing-numbers/jq/self-describing-numbers-1.jq b/Task/Self-describing-numbers/Jq/self-describing-numbers-1.jq similarity index 100% rename from Task/Self-describing-numbers/jq/self-describing-numbers-1.jq rename to Task/Self-describing-numbers/Jq/self-describing-numbers-1.jq diff --git a/Task/Self-describing-numbers/jq/self-describing-numbers-2.jq b/Task/Self-describing-numbers/Jq/self-describing-numbers-2.jq similarity index 100% rename from Task/Self-describing-numbers/jq/self-describing-numbers-2.jq rename to Task/Self-describing-numbers/Jq/self-describing-numbers-2.jq diff --git a/Task/Self-describing-numbers/jq/self-describing-numbers-3.jq b/Task/Self-describing-numbers/Jq/self-describing-numbers-3.jq similarity index 100% rename from Task/Self-describing-numbers/jq/self-describing-numbers-3.jq rename to Task/Self-describing-numbers/Jq/self-describing-numbers-3.jq diff --git a/Task/Self-describing-numbers/jq/self-describing-numbers-4.jq b/Task/Self-describing-numbers/Jq/self-describing-numbers-4.jq similarity index 100% rename from Task/Self-describing-numbers/jq/self-describing-numbers-4.jq rename to Task/Self-describing-numbers/Jq/self-describing-numbers-4.jq diff --git a/Task/Self-describing-numbers/Kotlin/self-describing-numbers.kotlin b/Task/Self-describing-numbers/Kotlin/self-describing-numbers.kotlin new file mode 100644 index 0000000000..623352cbd8 --- /dev/null +++ b/Task/Self-describing-numbers/Kotlin/self-describing-numbers.kotlin @@ -0,0 +1,21 @@ +// version 1.0.6 + +fun selfDescribing(n: Int): Boolean { + if (n <= 0) return false + val ns = n.toString() + val count = IntArray(10) + var nn = n + while (nn > 0) { + count[nn % 10] += 1 + nn /= 10 + } + for (i in 0 until ns.length) + if( ns[i] - '0' != count[i]) return false + return true +} + +fun main(args: Array<String>) { + println("The self-describing numbers less than 100 million are:") + for (i in 0..99999999) if (selfDescribing(i)) print("$i ") + println() +} diff --git a/Task/Self-describing-numbers/OoRexx/self-describing-numbers.rexx b/Task/Self-describing-numbers/OoRexx/self-describing-numbers.rexx new file mode 100644 index 0000000000..1e9fed98c0 --- /dev/null +++ b/Task/Self-describing-numbers/OoRexx/self-describing-numbers.rexx @@ -0,0 +1,16 @@ +-- REXX program to check if a number (base 10) is self-describing. +parse arg x y . +if x=='' then exit +if y=='' then y=x +-- 10 digits is the maximum size number that works here, so cap it +numeric digits 10 +y=min(y, 9999999999) + +loop number = x to y + loop i = 1 to number~length + digit = number~subchar(i) + -- return on first failure + if digit \= number~countstr(i - 1) then iterate number + end + say number "is a self describing number" +end diff --git a/Task/Self-describing-numbers/Ruby/self-describing-numbers.rb b/Task/Self-describing-numbers/Ruby/self-describing-numbers.rb index 6f6d695f06..0c331ba2f3 100644 --- a/Task/Self-describing-numbers/Ruby/self-describing-numbers.rb +++ b/Task/Self-describing-numbers/Ruby/self-describing-numbers.rb @@ -1,6 +1,6 @@ -def is_self_describing?(n) - digits = n.to_s.chars.map(&:to_i) +def self_describing?(n) + digits = n.digits.reverse digits.each_with_index.all?{|digit, idx| digits.count(idx) == digit} end -3_300_000.times {|n| puts n if is_self_describing?(n)} +3_300_000.times {|n| puts n if self_describing?(n)} diff --git a/Task/Self-describing-numbers/Sidef/self-describing-numbers-1.sidef b/Task/Self-describing-numbers/Sidef/self-describing-numbers-1.sidef index b84ab2115c..699257a0e1 100644 --- a/Task/Self-describing-numbers/Sidef/self-describing-numbers-1.sidef +++ b/Task/Self-describing-numbers/Sidef/self-describing-numbers-1.sidef @@ -1,16 +1,16 @@ -func sdn(n) { - var b = [0]*n.len; - var a = n.chars; +func sdn(Number n) { + var b = [0]*n.len + var a = n.digits a.each { |i| b[i] := 0 ++ } - a.join == b.join; + a == b } -var values = <1210 2020 21200 3211000 -42101000 521001000 6210001000 27 115508>; +var values = [1210, 2020, 21200, 3211000, +42101000, 521001000, 6210001000, 27, 115508] values.each { |test| - say "#{test} is #{sdn(test) ? '' : 'NOT ' }a self describing number."; + say "#{test} is #{sdn(test) ? '' : 'NOT ' }a self describing number." } say "\nSelf-descriptive numbers less than 1e5 (in base 10):" -0.to(1e5).each { |i| say i if sdn(i.to_s) } +^1e5 -> each { |i| say i if sdn(i) } diff --git a/Task/Self-describing-numbers/Sidef/self-describing-numbers-2.sidef b/Task/Self-describing-numbers/Sidef/self-describing-numbers-2.sidef index 61e0993033..08a4c91c88 100644 --- a/Task/Self-describing-numbers/Sidef/self-describing-numbers-2.sidef +++ b/Task/Self-describing-numbers/Sidef/self-describing-numbers-2.sidef @@ -1,4 +1,4 @@ -7.to(36).each { |b| - var n = ((b-4) * b**(b-1) + 2*(b**(b-2)) + b**(b-3) + b**3 -> base(b)); - say "base #{'%2d' % b}: #{n}"; +for b in (7 .. 36) { + var n = ((b-4) * b**(b-1) + 2*(b**(b-2)) + b**(b-3) + b**3 -> base(b)) + say "base #{'%2d' % b}: #{n}" } diff --git a/Task/Self-describing-numbers/Zkl/self-describing-numbers-1.zkl b/Task/Self-describing-numbers/Zkl/self-describing-numbers-1.zkl new file mode 100644 index 0000000000..1d04f19341 --- /dev/null +++ b/Task/Self-describing-numbers/Zkl/self-describing-numbers-1.zkl @@ -0,0 +1,6 @@ +fcn isSelfDescribing(n){ + if (n.bitAnd(1)) return(False); // Wikipedia: last digit must be zero + nu:= n.toString(); + ns:=["0".."9"].pump(String,nu.inCommon,"len"); //"12233".inCommon("2")-->"22" + (nu+"0000000000")[0,10] == ns; //"2020","2020000000" +} diff --git a/Task/Self-describing-numbers/Zkl/self-describing-numbers-2.zkl b/Task/Self-describing-numbers/Zkl/self-describing-numbers-2.zkl new file mode 100644 index 0000000000..26445192b8 --- /dev/null +++ b/Task/Self-describing-numbers/Zkl/self-describing-numbers-2.zkl @@ -0,0 +1,5 @@ +//[1..0x4_000_000].filter(isSelfDescribing).println(); +const N=0d500_000; +[1..0d100_000_000, N] // chunk and thread, 200 in this case + .apply(fcn(n){ n.filter(N,isSelfDescribing) }.future) + .filter().apply("noop").println(); diff --git a/Task/Self-referential-sequence/00DESCRIPTION b/Task/Self-referential-sequence/00DESCRIPTION index 206c2c61d8..aa1e8c3893 100644 --- a/Task/Self-referential-sequence/00DESCRIPTION +++ b/Task/Self-referential-sequence/00DESCRIPTION @@ -14,8 +14,8 @@ Sort the digits largest to smallest. Do not include counts of digits that do not Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.) -<b>Task:</b> +;Task: Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. <pre>Seed Value(s): 9009 9090 9900 @@ -45,4 +45,11 @@ Sequence: (same for all three seeds except for first element) 19281716151413427110 19182716152413228110 </pre> -See also: [[Self-describing numbers]] and [[Look-and-say sequence]] + +;Related tasks: +*   [[Fours is the number of letters in the ...]] +*   [[Look-and-say sequence]] +*   [[Number names]] +*   [[Self-describing numbers]] +*   [[Spelling of ordinal numbers]] +<br><br> diff --git a/Task/Self-referential-sequence/Aime/self-referential-sequence.aime b/Task/Self-referential-sequence/Aime/self-referential-sequence.aime index 0597f871b6..482ba7d272 100644 --- a/Task/Self-referential-sequence/Aime/self-referential-sequence.aime +++ b/Task/Self-referential-sequence/Aime/self-referential-sequence.aime @@ -12,16 +12,15 @@ next(text s, integer show) l -= 1; e = 0; - u = insert("", 0, character(s, l)); - r_g_integer(e, v, u); + u = insert("", 0, s[l]); + r_j_integer(e, v, u); r_f_integer(v, u, e + 1); } if (r_last(v, u)) { do { - b_paste(d, -1, itoa(r_q_integer(v, u))); - b_paste(d, -1, u); - } while (r_less(v, u, u)); + b_plan(d, v[u], u); + } while (rsk_less(v, u, u)); } if (show) { @@ -38,7 +37,7 @@ depth(text s, integer i, record r) integer d; d = 0; - r_g_integer(d, r, s); + r_j_integer(d, r, s); if (d <= 0) { i += 1; if (d) { @@ -48,7 +47,7 @@ depth(text s, integer i, record r) } r_f_integer(r, s, d); i = depth(next(s, 0), i, r); - d = r_q_integer(r, s); + d = r[s]; if (d <= 0) { d = i + 1; r_r_integer(r, s, d); diff --git a/Task/Self-referential-sequence/jq/self-referential-sequence-1.jq b/Task/Self-referential-sequence/Jq/self-referential-sequence-1.jq similarity index 100% rename from Task/Self-referential-sequence/jq/self-referential-sequence-1.jq rename to Task/Self-referential-sequence/Jq/self-referential-sequence-1.jq diff --git a/Task/Self-referential-sequence/jq/self-referential-sequence-2.jq b/Task/Self-referential-sequence/Jq/self-referential-sequence-2.jq similarity index 100% rename from Task/Self-referential-sequence/jq/self-referential-sequence-2.jq rename to Task/Self-referential-sequence/Jq/self-referential-sequence-2.jq diff --git a/Task/Self-referential-sequence/Kotlin/self-referential-sequence.kotlin b/Task/Self-referential-sequence/Kotlin/self-referential-sequence.kotlin new file mode 100644 index 0000000000..d8fc485ee1 --- /dev/null +++ b/Task/Self-referential-sequence/Kotlin/self-referential-sequence.kotlin @@ -0,0 +1,68 @@ +// version 1.1.2 + +const val LIMIT = 1_000_000 + +val sb = StringBuilder() + +fun selfRefSeq(s: String): String { + sb.setLength(0) // faster than using a local StringBuilder object + for (d in '9' downTo '0') { + if (d !in s) continue + val count = s.count { it == d } + sb.append("$count$d") + } + return sb.toString() +} + +fun permute(input: List<Char>): List<List<Char>> { + if (input.size == 1) return listOf(input) + val perms = mutableListOf<List<Char>>() + val toInsert = input[0] + for (perm in permute(input.drop(1))) { + for (i in 0..perm.size) { + val newPerm = perm.toMutableList() + newPerm.add(i, toInsert) + perms.add(newPerm) + } + } + return perms +} + +fun main(args: Array<String>) { + val sieve = IntArray(LIMIT) // all zero by default + val elements = mutableListOf<String>() + for (n in 1 until LIMIT) { + if (sieve[n] > 0) continue + elements.clear() + var next = n.toString() + elements.add(next) + while (true) { + next = selfRefSeq(next) + if (next in elements) { + val size = elements.size + sieve[n] = size + if (n > 9) { + val perms = permute(n.toString().toList()).distinct() + for (perm in perms) { + if (perm[0] == '0') continue + val k = perm.joinToString("").toInt() + sieve[k] = size + } + } + break + } + elements.add(next) + } + } + val maxIterations = sieve.max()!! + for (n in 1 until LIMIT) { + if (sieve[n] < maxIterations) continue + println("$n -> Iterations = $maxIterations") + var next = n.toString() + for (i in 1..maxIterations) { + println(next) + next = selfRefSeq(next) + } + println() + } +} diff --git a/Task/Self-referential-sequence/Phix/self-referential-sequence.phix b/Task/Self-referential-sequence/Phix/self-referential-sequence.phix new file mode 100644 index 0000000000..5ccbffaa08 --- /dev/null +++ b/Task/Self-referential-sequence/Phix/self-referential-sequence.phix @@ -0,0 +1,74 @@ +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 + +sequence res = {}, bestseen +integer maxcycle = 0 + +procedure srs() +sequence seen, this = n +integer cycle = 1 + while length(this)>1 and this[1]='0' do + this = this[2..$] + end while + integer ch = this[1] + for i=2 to length(this) do + if this[i]>ch then return end if + ch = this[i] + end for + seen = {this} + while 1 do + sequence digits = repeat(0,10) + for i=1 to length(this) do + digits[this[i]-'0'+1] += 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) + this = 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 1 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}) diff --git a/Task/Self-referential-sequence/REXX/self-referential-sequence.rexx b/Task/Self-referential-sequence/REXX/self-referential-sequence.rexx index 7cf5e211c0..1313b23a39 100644 --- a/Task/Self-referential-sequence/REXX/self-referential-sequence.rexx +++ b/Task/Self-referential-sequence/REXX/self-referential-sequence.rexx @@ -1,34 +1,34 @@ -/*REXX pgm generates a self-referential sequence and lists the maximums.*/ -parse arg low high .; maxL=0; seeds=; max$$= -if low=='' then low=1 /*no low? Then use the default*/ -if high=='' then high=1000000 /* " high? " " " " */ -/*══════════════════════════════════════════════════traipse through #'s.*/ - do seed=low to high; n=seed; $.=0; $$=n; $.n=1 +/*REXX program generates a self─referential sequence and displays the maximums. */ +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=1000000 - 1 /* " " " " " " */ +max$=; seeds=; maxL=0 /*inialize some defaults and counters. */ - do j=1 until x==n /*generate a self─referential seq*/ - x=n; n= - do k=9 by -1 for 10 /*gen new sequence*/ - _=countstr(k,x); if _\==0 then n=n||_||k - end /*k*/ - if $.n then leave /*sequence been generated before?*/ - $$=$$'-'n; $.n=1 /*add number to sequence & roster*/ - end /*j*/ + do #=LO to HI; n=#; @.=0; @.#=1 /*loop thru seed; define some defaults.*/ + $=n + do c=1 until x==n; x=n /*generate a self─referential sequence.*/ + n=; do k=9 by -1 for 10 /*generate a new sequence (downwards). */ + _=countstr(k, x) /*obtain the number of sequence counts.*/ + if _\==0 then n=n || _ || k /*is count > zero? Then append it to N*/ + end /*k*/ + if @.n then leave /*has sequence been generated before ? */ + $=$'-'n; @.n=1 /*add the number to sequence and roster*/ + end /*c*/ - if j==maxL then do /*sequence equal to max so far ? */ - seeds=seeds seed; maxnums=maxnums n; max$$=max$$ $$ + if c==maxL then do; seeds=seeds # /*is the sequence equal to max so far ?*/ + max$=max$ $ /*append this self─referential # to $ */ end - else if j>maxL then do /*have found a new best sequence.*/ - seeds=seed; maxL=j; maxnums=n; max$$=$$ - end - end /*seed*/ -/*═══════════════════════════════════════════════════display the output.*/ -say 'seeds that had the most iterations =' seeds -hdr=copies('─',30); say 'maximum sequence length =' maxL + else if c>maxL then do; seeds=# /*use the new number as the new seed. */ + maxL=c; max$=$ /*also, set the new maximum L; max seq.*/ + end /* [↑] have we found a new best seq ? */ + end /*#*/ - do j=1 for words(max$$); say - say hdr "iteration sequence for: " word(seeds,j) ' ('maxL "iterations)" - q=translate(word(max$$,j),,'-') - do k=1 for words(q); say word(q,k) +say ' seeds that had the most iterations: ' seeds +say 'the maximum self─referential length: ' maxL + + do j=1 for words(max$) ; say + say copies('─',30) "iteration sequence for: " word(seeds,j) ' ('maxL "iterations)" + q=translate( word( max$, j), ,'-') + do k=1 for words(q); say word(q, k) end /*k*/ - end /*j*/ - /*stick a fork in it, we're done.*/ + end /*j*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Self-referential-sequence/Zkl/self-referential-sequence.zkl b/Task/Self-referential-sequence/Zkl/self-referential-sequence.zkl new file mode 100644 index 0000000000..2ce33007e3 --- /dev/null +++ b/Task/Self-referential-sequence/Zkl/self-referential-sequence.zkl @@ -0,0 +1,32 @@ +N:=0d1_000_001; + +fcn lookAndJustSaying(seed){ // numeric String --> numeric String + "9876543210".pump(String,'wrap(n){ + (s:=seed.inCommon(n)) and String(s.len(),n) or "" + }); +} +fcn sequence(seed){ // numeric string --> sequence until it repeats + seq:=L(); + while(not seq.holds(seed)){ seq.append(seed); seed=lookAndJustSaying(seed); } + seq +} +fcn decending(str) //--> True if digits are in descending (or equal) order + { (not str.walker().zipWith('<,str[1,*]).filter1()) } + +szs:=List.createLong(25); max:=0; +foreach seed in (N){ + z:=seed.toString(); + if(decending(z)){ // 321 generates same sequence as 312,132,123,213 + len:=sequence(z).len(); + if(len>max) szs.clear(); + if(len>=max){ szs.append(seed.toString()); max=len; } + } +} + +// List permutations of longest seeds +// ("9900"-->(((9,0,0,9),...))-->((9,0,0,9),...)-->("9009"...) +// -->remove numbers w/leading zeros-->remove dups +zs:=szs.apply(Utils.Helpers.permute).flatten().apply("concat") + .filter(fcn(s){ s[0]!="0" }) : Utils.Helpers.listUnique(_); +println(max," iterations for ",zs.concat(", ")); +zs.pump(Console.println,sequence,T("concat",", ")); diff --git a/Task/Semiprime/00DESCRIPTION b/Task/Semiprime/00DESCRIPTION index daf1c8c727..3c58910add 100644 --- a/Task/Semiprime/00DESCRIPTION +++ b/Task/Semiprime/00DESCRIPTION @@ -1,6 +1,15 @@ Semiprime numbers are natural numbers that are products of exactly two (possibly equal) [[prime_number|prime numbers]]. +'''Semiprimes'''   are also known as: +:::*   '''semi-primes''' +:::*   '''biprimes''' +:::*   '''bi-primes''' +:::*   ''' ''2-almost'' '''   primes +:::*   or simply:   ''' ''P<sub>2</sub> '' ''' + + + ;Example: <big> 1679 = 23 × 73 </big> @@ -9,4 +18,10 @@ Semiprime numbers are natural numbers that are products of exactly two (possibly ;Task; Write a function determining whether a given number is semiprime. + + +;See also: +* The Wikipedia article:   [http://mathworld.wolfram.com/Semiprime.html semiprime]. +* The Wikipedia article:   [http://mathworld.wolfram.com/AlmostPrime.html almost prime]. +* The OEIS article:   [http://oeis.org/A001358 semiprimes]   which has a shorter definition: ''the product of two primes''. <br><br> diff --git a/Task/Semiprime/360-Assembly/semiprime.360 b/Task/Semiprime/360-Assembly/semiprime.360 new file mode 100644 index 0000000000..5abf21f2d3 --- /dev/null +++ b/Task/Semiprime/360-Assembly/semiprime.360 @@ -0,0 +1,71 @@ +* Semiprime 14/03/2017 +SEMIPRIM CSECT + USING SEMIPRIM,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + LA R10,PG pgi=0 + LA R8,0 m=0 + L R6,=F'2' i=2 + DO WHILE=(C,R6,LE,=F'100') do i=2 to 100 + ST R6,N n=i + LA R9,0 f=0 + LA R7,2 j=2 +LOOPJ EQU * do j=2 while f<2 and j*j<=n + C R9,=F'2' if f<2 + BNL EXITJ then exit do j + LR R5,R7 j + MR R4,R7 *j + C R5,N if j*j<=n + BH EXITJ then exit do j +LOOPK EQU * do while n mod j=0 + L R4,N n + SRDA R4,32 ~ + DR R4,R7 /j + LTR R4,R4 if n mod <>0 + BNZ EXITK then exit do j + ST R5,N n=n/j + LA R9,1(R9) f=f+1 + B LOOPK enddo k +EXITK LA R7,1(R7) j++ + B LOOPJ enddo j +EXITJ L R4,N n + IF C,R4,GT,=F'1' THEN if n>1 then + LA R2,1 g=1 + ELSE , else + LA R2,0 g=0 + ENDIF , endif + AR R2,R9 +f + IF C,R2,EQ,=F'2' THEN if f+(n>1)=2 then + XDECO R6,XDEC edit i + MVC 0(5,R10),XDEC+7 output i + LA R10,5(R10) pgi=pgi+10 + LA R8,1(R8) m=m+1 + LR R4,R8 m + SRDA R4,32 ~ + D R4,=F'16' m/16 + IF LTR,R4,Z,R4 THEN if m mod 16=0 then + XPRNT PG,L'PG print buffer + MVC PG,=CL80' ' clear buffer + LA R10,PG pgi=0 + ENDIF , endif + ENDIF , endif + LA R6,1(R6) i++ + ENDDO , enddo i + XPRNT PG,L'PG print buffer + MVC PG,=CL80'..... semiprimes' init buffer + XDECO R8,XDEC edit m + MVC PG(5),XDEC+7 output m + XPRNT PG,L'PG print buffer + L R13,4(0,R13) restore previous savearea pointer + LM R14,R12,12(R13) restore previous context + XR R15,R15 rc=0 + BR R14 exit +N DS F n +PG DC CL80' ' buffer +XDEC DS CL12 temp + YREGS + END SEMIPRIM diff --git a/Task/Semiprime/Clojure/semiprime.clj b/Task/Semiprime/Clojure/semiprime.clj new file mode 100644 index 0000000000..cb6d828ff2 --- /dev/null +++ b/Task/Semiprime/Clojure/semiprime.clj @@ -0,0 +1,14 @@ +(ns example + (:gen-class)) + +(defn semi-prime? [n] + (loop [a 2 + b 0 + c n] + (cond + (> b 2) false + (<= c 1) (= b 2) + (= 0 (rem c a)) (recur a (inc b) (int (/ c a))) + :else (recur (inc a) b c)))) + +(println (filter semi-prime? (range 1 100))) diff --git a/Task/Semiprime/Kotlin/semiprime.kotlin b/Task/Semiprime/Kotlin/semiprime.kotlin new file mode 100644 index 0000000000..30eb3e6ad7 --- /dev/null +++ b/Task/Semiprime/Kotlin/semiprime.kotlin @@ -0,0 +1,18 @@ +// version 1.1.2 + +fun isSemiPrime(n: Int): Boolean { + var nf = 0 + var nn = n + for (i in 2..nn) + while (nn % i == 0) { + if (nf == 2) return false + nf++ + nn /= i + } + return nf == 2 +} + +fun main(args: Array<String>) { + for (v in 1675..1680) + println("$v ${if (isSemiPrime(v)) "is" else "isn't"} semi-prime") +} diff --git a/Task/Semiprime/Nim/semiprime.nim b/Task/Semiprime/Nim/semiprime.nim new file mode 100644 index 0000000000..fedfba04e4 --- /dev/null +++ b/Task/Semiprime/Nim/semiprime.nim @@ -0,0 +1,18 @@ +proc isSemiPrime(k: int): string = + var + i: int = 2 + compte: int = 0 + x: int = k + while i<=x and compte<3: + if (x mod i)==0: + x = x div i + compte += 1 + else: + i += 1 + if compte==2: + result = "is semi-prime" + else: + result = "isn't semi-prime" + +for k in 1675..1680: + echo k," ",isSemiPrime(k) diff --git a/Task/Semiprime/Perl-6/semiprime.pl6 b/Task/Semiprime/Perl-6/semiprime-1.pl6 similarity index 100% rename from Task/Semiprime/Perl-6/semiprime.pl6 rename to Task/Semiprime/Perl-6/semiprime-1.pl6 diff --git a/Task/Semiprime/Perl-6/semiprime-2.pl6 b/Task/Semiprime/Perl-6/semiprime-2.pl6 new file mode 100644 index 0000000000..aa63ecc0c7 --- /dev/null +++ b/Task/Semiprime/Perl-6/semiprime-2.pl6 @@ -0,0 +1,38 @@ +sub is-semiprime ( Int $n where * > 0 ) { + return False if $n.is-prime; + my $factor = find-factor( $n ); + return True if $factor.is-prime && ( $n div $factor ).is-prime; + False; +} + +sub find-factor ( Int $n, $constant = 1 ) { + my $x = 2; + my $rho = 1; + my $factor = 1; + while $factor == 1 { + $rho *= 2; + my $fixed = $x; + for ^$rho { + $x = ( $x * $x + $constant ) % $n; + $factor = ( $x - $fixed ) gcd $n; + last if 1 < $factor; + } + } + $factor = find-factor( $n, $constant + 1 ) if $n == $factor; + $factor; +} + +INIT my $start = now; + +# Infinite list of semiprimes +constant @semiprimes = 4, 6, 9, -> $p { ($p + 1 ... &is-semiprime).tail } ... *; + +# Show the semiprimes < 100 +say 'Semiprimes less than 100:'; +say @semiprimes[^ @semiprimes.first: * > 100, :k ], "\n"; + +# Check individual integers, or in this case, a range +my $s = 2⁹⁷ - 1; +say "Is $_ semiprime?: ", is-semiprime( $_ ) for $s .. $s + 30; + +say 'elapsed seconds: ', now - $start; diff --git a/Task/Semiprime/Perl/semiprime-1.pl b/Task/Semiprime/Perl/semiprime-1.pl index 863eefa3c8..624d828f9f 100644 --- a/Task/Semiprime/Perl/semiprime-1.pl +++ b/Task/Semiprime/Perl/semiprime-1.pl @@ -1,4 +1,4 @@ -use ntheory "factor"; -print join(" ", grep { scalar factor($_) == 2 } 1..100),"\n"; -print join(" ", grep { scalar factor($_) == 2 } 1675..1681),"\n"; -print join(" ", grep { scalar factor($_) == 2 } (2,4,99,100,1679,5040,32768,1234567,9876543,900660121)),"\n"; +use ntheory "is_semiprime"; +for ([1..100], [1675..1681], [2,4,99,100,1679,5030,32768,1234567,9876543,900660121]) { + print join(" ",grep { is_semiprime($_) } @$_),"\n"; +} diff --git a/Task/Semiprime/Perl/semiprime-2.pl b/Task/Semiprime/Perl/semiprime-2.pl index d00e3dbd8a..7b52801706 100644 --- a/Task/Semiprime/Perl/semiprime-2.pl +++ b/Task/Semiprime/Perl/semiprime-2.pl @@ -1,9 +1,2 @@ -use ntheory qw/factor is_prime trial_factor/; -sub issemi { - my $n = shift; - if ((my @p = trial_factor($n,500)) > 1) { - return 0 if @p > 2; - return !!is_prime($p[1]) if @p == 2; - } - 2 == factor($n); -} +use ntheory "factor"; +print join(" ", grep { scalar factor($_) == 2 } 1..100),"\n"; diff --git a/Task/Semiprime/Perl/semiprime-3.pl b/Task/Semiprime/Perl/semiprime-3.pl new file mode 100644 index 0000000000..d00e3dbd8a --- /dev/null +++ b/Task/Semiprime/Perl/semiprime-3.pl @@ -0,0 +1,9 @@ +use ntheory qw/factor is_prime trial_factor/; +sub issemi { + my $n = shift; + if ((my @p = trial_factor($n,500)) > 1) { + return 0 if @p > 2; + return !!is_prime($p[1]) if @p == 2; + } + 2 == factor($n); +} diff --git a/Task/Semiprime/Phix/semiprime.phix b/Task/Semiprime/Phix/semiprime.phix new file mode 100644 index 0000000000..b2bf1c1c61 --- /dev/null +++ b/Task/Semiprime/Phix/semiprime.phix @@ -0,0 +1,18 @@ +function semiprime(integer n) + sequence f = prime_factors(n) + integer l = length(f) + return (l=2 and n=f[1]*f[2]) or (l=1 and n=power(f[1],2)) +end function + +procedure test(integer start, integer stop) +sequence s = {} + for i=start to stop do + if semiprime(i) then + s &= i + end if + end for + ?s + ?length(s) +end procedure +test(1,100) +test(1675,1680) diff --git a/Task/Semiprime/REXX/semiprime-2.rexx b/Task/Semiprime/REXX/semiprime-2.rexx index 1b2ae9382a..a05a39e14d 100644 --- a/Task/Semiprime/REXX/semiprime-2.rexx +++ b/Task/Semiprime/REXX/semiprime-2.rexx @@ -2,12 +2,16 @@ parse arg bot top . /*obtain optional arguments from the CL*/ if bot=='' | bot=="," then bot=random() /*None given? User wants us to guess.*/ if top=='' | top=="," then top=bot /*maybe define a range of numbers. */ -w=max(length(bot), length(top)) /*obtain the maximum width of numbers. */ +tell= top=>0 | top==bot /*should results be shown to the term? */ +w=max(length(bot), length(top)) + 5 /*obtain the maximum width of numbers. */ numeric digits max(9, w) /*ensure there're enough decimal digits*/ - do n=bot to top /*show results for a range of numbers. */ - if isSemiPrime(n) then say right(n, w) " is semiprime." - else say right(n, w) " isn't semiprime." +#=0 /*initialize number of semiprimes found*/ + do n=bot to abs(top) /*show results for a range of numbers. */ + ?=isSemiPrime(n); #=#+? /*Is N a semiprime?; Maybe bump counter*/ + if tell then say right(n,w) right(word("isn't" 'is', ?+1), 6) 'semiprime.' end /*n*/ +say +if bot\==top then say 'found ' # " semiprimes." exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ isPrime: procedure; parse arg x; if x<2 then return 0 /*number too low?*/ diff --git a/Task/Semiprime/REXX/semiprime-3.rexx b/Task/Semiprime/REXX/semiprime-3.rexx new file mode 100644 index 0000000000..be871d5d54 --- /dev/null +++ b/Task/Semiprime/REXX/semiprime-3.rexx @@ -0,0 +1,41 @@ +/*REXX program determines if any integer (or a range of integers) is/are semiprime. */ +parse arg bot top . /*obtain optional arguments from the CL*/ +if bot=='' | bot=="," then bot=random() /*None given? User wants us to guess.*/ +if top=='' | top=="," then top=bot /*maybe define a range of numbers. */ +tell= bot=>0 & top=>0 /*should results be shown to the term? */ +w=max(length(bot), length(top)) /*obtain the maximum width of numbers. */ +!.=; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1; !.19=1; !.23=1; !.29=1; !.31=1 +numeric digits max(9, w) /*ensure there're enough decimal digits*/ +#=0 /*initialize number of semiprimes found*/ + do n=abs(bot) to abs(top) /*show results for a range of numbers. */ + ?=isSemiPrime(n); #=#+? /*Is N a semiprime?; Maybe bump counter*/ + if tell then say right(n,w) right(word("isn't" 'is', ?+1), 6) 'semiprime.' + end /*n*/ +say +if bot\==top then say 'found ' # " semiprimes." +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +isPrime: procedure expose !.; parse arg x; if x<2 then return 0 /*number too low?*/ + if !.x==1 then return 1 /*a known prime. */ + if x// 2==0 then return 0; if x//3==0 then return 0 /*÷ by 2;÷by 3?*/ + parse var x '' -1 _; if _==5 then return 0 /*last digit a 5?*/ + if x// 7==0 then return 0; if x//11==0 then return 0 /*÷ by 7;÷by 11?*/ + if x//13==0 then return 0; if x//17==0 then return 0 /*÷ by 13;÷by 17?*/ + if x//19==0 then return 0; if x//23==0 then return 0 /*÷ by 19;÷by 23?*/ + do j=29 by 6 until j*j>x; if x//j==0 then return 0 /*not a prime. */ + if x//(j+2)==0 then return 0 /* " " " */ + end /*j*/ + !.x=1; return 1 /*indicate that X is a prime number. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +isSemiPrime: procedure expose !.; parse arg x; if x<4 then return 0 + + do i=2 for 2; if x//i==0 then if isPrime(x%i) then return 1 + else return 0 + end /*i*/ + /* ___ */ + do j=5 by 6 until j*j>x /* > √ x ?*/ + do k=j by 2 for 2; if x//k==0 then if isPrime(x%k) then return 1 + else return 0 + end /*k*/ /* [↑] see if 2nd factor is prime or ¬*/ + end /*j*/ /* [↑] J is never a multiple of three.*/ + return 0 diff --git a/Task/Semiprime/Zkl/semiprime.zkl b/Task/Semiprime/Zkl/semiprime.zkl new file mode 100644 index 0000000000..126a822f59 --- /dev/null +++ b/Task/Semiprime/Zkl/semiprime.zkl @@ -0,0 +1,8 @@ +fcn semiprime(n){ + reg f = 0; + p:=2; while(f < 2 and p*p <= n){ + while(0 == n % p){ n /= p; f+=1; } + p+=1; + } + return(f + (n > 1) == 2); +} diff --git a/Task/Semordnilap/00META.yaml b/Task/Semordnilap/00META.yaml deleted file mode 100644 index 50be2d308f..0000000000 --- a/Task/Semordnilap/00META.yaml +++ /dev/null @@ -1,2 +0,0 @@ ---- -note: Semordnilap diff --git a/Task/Semordnilap/Aime/semordnilap.aime b/Task/Semordnilap/Aime/semordnilap.aime index 3ccd7fa31a..7b423342ec 100644 --- a/Task/Semordnilap/Aime/semordnilap.aime +++ b/Task/Semordnilap/Aime/semordnilap.aime @@ -1,56 +1,28 @@ -text -reverse(text s) -{ - data b; - integer i; +integer p; +record r; +file f; +text s; - i = length(s); - while (i) { - i -= 1; - b_insert(b, -1, s[i]); - } +f_affix(f, "unixdict.txt"); - return b_string(b); +while (f_line(f, s) != -1) { + r[s] = 0; } -integer -main(void) -{ - integer c, p; - record r; - file f; - text s; +p = 0; - f_affix(f, "unixdict.txt"); +for (s in r) { + text t; - while (f_line(f, s) != -1) { - r_p_integer(r, s, 0); - } - - c = 0; - p = 0; - - if (r_first(r, s)) { - do { - text t; - - t = reverse(s); - if (compare(s, t) > 0) { - if (r_key(r, t)) { - p += 1; - if (c < 5) { - c += 1; - o_text(s); - o_byte(' '); - o_text(t); - o_byte('\n'); - } - } + t = b_string(b_reverse(b_draft(s))); + if (s > t) { + if (r_key(r, t)) { + p += 1; + if (p <= 5) { + o_(s, " ", t, "\n"); } - } while (r_greater(r, s, s)); + } } - - o_form("Semordnilap pairs: ~\n", p); - - return 0; } + +o_form("Semordnilap pairs: ~\n", p); diff --git a/Task/Semordnilap/jq/semordnilap.jq b/Task/Semordnilap/Jq/semordnilap.jq similarity index 100% rename from Task/Semordnilap/jq/semordnilap.jq rename to Task/Semordnilap/Jq/semordnilap.jq diff --git a/Task/Semordnilap/Kotlin/semordnilap.kotlin b/Task/Semordnilap/Kotlin/semordnilap.kotlin index 0ad117db5a..1b42e279a3 100644 --- a/Task/Semordnilap/Kotlin/semordnilap.kotlin +++ b/Task/Semordnilap/Kotlin/semordnilap.kotlin @@ -1,7 +1,9 @@ -fun semordnilap() { - val words = File("unixdict.txt").readLines().toSet() - val pairs = words.asSequence().map { it to it.reversed() } // Pair(word, reversed word) - .filter { it.first < it.second && it.second in words }.toList() // avoid dupes+palindromes, find matches - println("Found ${pairs.size()} semordnilap pairs") +import java.io.File + +fun main(args: Array<String>) { + val words = File("/usr/share/dict/words").readLines().toSet() + val pairs = words.map { Pair(it, it.reversed()) } + .filter { it.first < it.second && it.second in words } // avoid dupes+palindromes, find matches + println("Found ${pairs.size} semordnilap pairs") println(pairs.take(5)) } diff --git a/Task/Semordnilap/Zkl/semordnilap.zkl b/Task/Semordnilap/Zkl/semordnilap.zkl new file mode 100644 index 0000000000..ecad6a0585 --- /dev/null +++ b/Task/Semordnilap/Zkl/semordnilap.zkl @@ -0,0 +1,9 @@ +var [const] words= // create hashed unixdict of striped words (word:True, ...) + File("dict.txt").howza(11).pump(Dictionary().howza(8).add.fp1(True)); +ss:=words.pump(List, // push stripped unixdict words through some functions + fcn(w){ words.holds(w.reverse()) }, Void.Filter, // filter palindromes + // create ("word","drow") if "word"<"drow" (ie remove duplicates) + fcn(w){ r:=w.reverse(); if(w<r) T(w,r) else Void.Skip }); + +ss.len().println(); //--> 158 +ss.shuffle()[0,5].println(); diff --git a/Task/Send-an-unknown-method-call/00DESCRIPTION b/Task/Send-an-unknown-method-call/00DESCRIPTION index 8b3db8f765..a51beb1014 100644 --- a/Task/Send-an-unknown-method-call/00DESCRIPTION +++ b/Task/Send-an-unknown-method-call/00DESCRIPTION @@ -1,5 +1,8 @@ +;Task: Invoke an object method where the name of the method to be invoked can be generated at run time. -;Cf: + +;Related tasks: * [[Respond to an unknown method call]]. * [[Runtime evaluation]] +<br><br> 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 9b8471e6a6..4fcd039ed4 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 @@ -1,18 +1,17 @@ -#import system. -#import extensions. +import extensions. -#class Example +class Example { - #method foo : x + foo : x = x + 42. } -#symbol program = +program = [ - #var example := Example new. - #var methodSignature := "foo". + var example := Example new. + var methodSignature := "foo". - #var result := example::(Signature new &literal:methodSignature) eval:5. + var result := example~(Signature new literal:methodSignature) eval:5. - console writeLine:methodSignature:"(":5:") = ":result. + console printLine(methodSignature,"(",5,") = ",result). ]. diff --git a/Task/Send-an-unknown-method-call/Forth/send-an-unknown-method-call.fth b/Task/Send-an-unknown-method-call/Forth/send-an-unknown-method-call.fth index b4956051a7..6f8ad0d7b6 100644 --- a/Task/Send-an-unknown-method-call/Forth/send-an-unknown-method-call.fth +++ b/Task/Send-an-unknown-method-call/Forth/send-an-unknown-method-call.fth @@ -3,10 +3,8 @@ include FMS-SILib.f var x \ instantiate a class var object named x -: test - heap> string locals| s | - '!' s +: ':' s +: \ build the message "!:" into string s - 42 x s @: evaluate \ retrieve the text from s and execute it - x p: ; \ lastly, send the p: message to x to print it +\ Use a standard Forth string and evaluate it. +\ This is equivalent to sending the !: message to object x +42 x s" !:" evaluate -test \ => 42 ok +x p: 42 \ send the print message ( p: ) to x to verify the contents diff --git a/Task/Send-an-unknown-method-call/Go/send-an-unknown-method-call-1.go b/Task/Send-an-unknown-method-call/Go/send-an-unknown-method-call-1.go deleted file mode 100644 index 165aa68ed0..0000000000 --- a/Task/Send-an-unknown-method-call/Go/send-an-unknown-method-call-1.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "fmt" - "reflect" -) - -type example struct{} - -// the method must be exported to be accessed through reflection. -func (example) Foo() int { - return 42 -} - -func main() { - // create an object with a method - var e example - // get the method by name - m := reflect.ValueOf(e).MethodByName("Foo") - // call the method with no argments - r := m.Call(nil) - // interpret first return value as int - fmt.Println(r[0].Int()) // => 42 -} diff --git a/Task/Send-an-unknown-method-call/Go/send-an-unknown-method-call-2.go b/Task/Send-an-unknown-method-call/Go/send-an-unknown-method-call-2.go deleted file mode 100644 index 623167b44a..0000000000 --- a/Task/Send-an-unknown-method-call/Go/send-an-unknown-method-call-2.go +++ /dev/null @@ -1,12 +0,0 @@ -procedure main() - x := foo() # create object - x.m1() # static call of m1 method - # two examples where the method string can be dynamically constructed ... - "foo_m1"(x) # ... need to know class name and method name to construct name - x.__m["m1"] # ... general method (better) -end - -class foo(a,b,c) # define object -method m1(x) -end -end 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.kotlin new file mode 100644 index 0000000000..b093952c0a --- /dev/null +++ b/Task/Send-an-unknown-method-call/Kotlin/send-an-unknown-method-call.kotlin @@ -0,0 +1,13 @@ +// Kotlin JS version 1.1.4-3 + +class C { + fun foo() { + println("foo called") + } +} + +fun main(args: Array<String>) { + val c = C() + val f = "c.foo" + js(f)() // invokes c.foo dynamically +} diff --git a/Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-3.logtalk b/Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-3.logtalk deleted file mode 100644 index 1d034c2129..0000000000 --- a/Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-3.logtalk +++ /dev/null @@ -1,3 +0,0 @@ -| ?- query_foo::query. -Message: bar(X). -Reply: bar(42) diff --git a/Task/Send-an-unknown-method-call/Phix/send-an-unknown-method-call.phix b/Task/Send-an-unknown-method-call/Phix/send-an-unknown-method-call.phix new file mode 100644 index 0000000000..634f77ffa0 --- /dev/null +++ b/Task/Send-an-unknown-method-call/Phix/send-an-unknown-method-call.phix @@ -0,0 +1,10 @@ +procedure Hello() + ?"Hello" +end procedure + +string erm = "Hemmm" +for i=3 to 5 do + erm[i]+=-1+(i=5)*3 +end for + +call_proc(routine_id(erm),{}) 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.psh new file mode 100644 index 0000000000..6274560bca --- /dev/null +++ b/Task/Send-an-unknown-method-call/PowerShell/send-an-unknown-method-call.psh @@ -0,0 +1,10 @@ +$method = ([Math] | Get-Member -MemberType Method -Static | Where-Object {$_.Definition.Split(',').Count -eq 1} | Get-Random).Name +$number = (1..9 | Get-Random) / 10 +$result = [Math]::$method($number) +$output = [PSCustomObject]@{ + Method = $method + Number = $number + Result = $result +} + +$output | Format-List diff --git a/Task/Send-an-unknown-method-call/Zkl/send-an-unknown-method-call.zkl b/Task/Send-an-unknown-method-call/Zkl/send-an-unknown-method-call.zkl new file mode 100644 index 0000000000..4d7bcd489f --- /dev/null +++ b/Task/Send-an-unknown-method-call/Zkl/send-an-unknown-method-call.zkl @@ -0,0 +1 @@ +name:="len"; "this is a test".resolve(name)() //-->14 diff --git a/Task/Send-email/Go/send-email-1.go b/Task/Send-email/Go/send-email-1.go deleted file mode 100644 index 217233450d..0000000000 --- a/Task/Send-email/Go/send-email-1.go +++ /dev/null @@ -1,161 +0,0 @@ -package main - -import ( - "bufio" - "bytes" - "errors" - "flag" - "fmt" - "io/ioutil" - "net/smtp" - "os" - "strings" -) - -type Message struct { - From string - To []string - Cc []string - Subject string - Content string -} - -func (m Message) Bytes() (r []byte) { - to := strings.Join(m.To, ",") - cc := strings.Join(m.Cc, ",") - - r = append(r, []byte("From: "+m.From+"\n")...) - r = append(r, []byte("To: "+to+"\n")...) - r = append(r, []byte("Cc: "+cc+"\n")...) - r = append(r, []byte("Subject: "+m.Subject+"\n\n")...) - r = append(r, []byte(m.Content)...) - - return -} - -func (m Message) Send(host string, port int, user, pass string) (err error) { - err = check(host, user, pass) - if err != nil { - return - } - - err = smtp.SendMail(fmt.Sprintf("%v:%v", host, port), - smtp.PlainAuth("", user, pass, host), - m.From, - m.To, - m.Bytes(), - ) - - return -} - -func check(host, user, pass string) error { - if host == "" { - return errors.New("Bad host") - } - if user == "" { - return errors.New("Bad username") - } - if pass == "" { - return errors.New("Bad password") - } - - return nil -} - -func main() { - var flags struct { - host string - port int - user string - pass string - } - flag.StringVar(&flags.host, "host", "", "SMTP server to connect to") - flag.IntVar(&flags.port, "port", 587, "Port to connect to SMTP server on") - flag.StringVar(&flags.user, "user", "", "Username to authenticate with") - flag.StringVar(&flags.pass, "pass", "", "Password to authenticate with") - flag.Parse() - - err := check(flags.host, flags.user, flags.pass) - if err != nil { - flag.Usage() - os.Exit(1) - } - - bufin := bufio.NewReader(os.Stdin) - - fmt.Printf("From: ") - from, err := bufin.ReadString('\n') - if err != nil { - fmt.Printf("Error: %v\n", err) - os.Exit(1) - } - from = strings.Trim(from, " \t\n\r") - - var to []string - for { - fmt.Printf("To (Blank to finish): ") - tmp, err := bufin.ReadString('\n') - if err != nil { - fmt.Printf("Error: %v\n", err) - os.Exit(1) - } - tmp = strings.Trim(tmp, " \t\n\r") - - if tmp == "" { - break - } - - to = append(to, tmp) - } - - var cc []string - for { - fmt.Printf("Cc (Blank to finish): ") - tmp, err := bufin.ReadString('\n') - if err != nil { - fmt.Printf("Error: %v\n", err) - os.Exit(1) - } - tmp = strings.Trim(tmp, " \t\n\r") - - if tmp == "" { - break - } - - cc = append(cc, tmp) - } - - fmt.Printf("Subject: ") - subject, err := bufin.ReadString('\n') - if err != nil { - fmt.Printf("Error: %v\n", err) - os.Exit(1) - } - subject = strings.Trim(subject, " \t\n\r") - - fmt.Printf("Content (Until EOF):\n") - content, err := ioutil.ReadAll(os.Stdin) - if err != nil { - fmt.Printf("Error: %v\n", err) - os.Exit(1) - } - content = bytes.Trim(content, " \t\n\r") - - m := Message{ - From: from, - To: to, - Cc: cc, - Subject: subject, - Content: string(content), - } - - fmt.Printf("\nSending message...\n") - err = m.Send(flags.host, flags.port, flags.user, flags.pass) - if err != nil { - fmt.Printf("Error: %v\n", err) - os.Exit(1) - } - - fmt.Printf("Message sent.\n") -} diff --git a/Task/Send-email/Go/send-email-2.go b/Task/Send-email/Go/send-email-2.go deleted file mode 100644 index fb1360862f..0000000000 --- a/Task/Send-email/Go/send-email-2.go +++ /dev/null @@ -1,7 +0,0 @@ -procedure main(args) - mail := open("mailto:"||args[1], "m", "Subject : "||args[2], - "X-Note: automatically send by Unicon") | - stop("Cannot send mail to ",args[1]) - every write(mail , !&input) - close (mail) -end diff --git a/Task/Send-email/Kotlin/send-email.kotlin b/Task/Send-email/Kotlin/send-email.kotlin new file mode 100644 index 0000000000..227a2a0c61 --- /dev/null +++ b/Task/Send-email/Kotlin/send-email.kotlin @@ -0,0 +1,51 @@ +// version 1.1.4-3 + +import java.util.Properties +import javax.mail.Authenticator +import javax.mail.PasswordAuthentication +import javax.mail.Session +import javax.mail.internet.MimeMessage +import javax.mail.internet.InternetAddress +import javax.mail.Message.RecipientType +import javax.mail.Transport + +fun sendEmail(user: String, tos: Array<String>, ccs: Array<String>, title: String, + body: String, password: String) { + val props = Properties() + val host = "smtp.gmail.com" + with (props) { + put("mail.smtp.host", host) + put("mail.smtp.port", "587") // for TLS + put("mail.smtp.auth", "true") + put("mail.smtp.starttls.enable", "true") + } + val auth = object: Authenticator() { + protected override fun getPasswordAuthentication() = + PasswordAuthentication(user, password) + } + val session = Session.getInstance(props, auth) + val message = MimeMessage(session) + with (message) { + setFrom(InternetAddress(user)) + for (to in tos) addRecipient(RecipientType.TO, InternetAddress(to)) + for (cc in ccs) addRecipient(RecipientType.TO, InternetAddress(cc)) + setSubject(title) + setText(body) + } + val transport = session.getTransport("smtp") + with (transport) { + connect(host, user, password) + sendMessage(message, message.allRecipients) + close() + } +} + +fun main(args: Array<String>) { + val user = "some.user@gmail.com" + val tos = arrayOf("other.user@otherserver.com") + val ccs = arrayOf<String>() + val title = "Rosetta Code Example" + val body = "This is just a test email" + val password = "secret" + sendEmail(user, tos, ccs, title, body, password) +} diff --git a/Task/Sequence-of-non-squares/CoffeeScript/sequence-of-non-squares-1.coffee b/Task/Sequence-of-non-squares/CoffeeScript/sequence-of-non-squares-1.coffee deleted file mode 100644 index 9290f11d4c..0000000000 --- a/Task/Sequence-of-non-squares/CoffeeScript/sequence-of-non-squares-1.coffee +++ /dev/null @@ -1,19 +0,0 @@ -non_square = (n) -> n + Math.floor(1/2 + Math.sqrt(n)) - -is_square = (n) -> - r = Math.floor(Math.sqrt(n)) - r * r is n - -do -> - first_22_non_squares = (non_square i for i in [1..22]) - console.log first_22_non_squares - - # test is_square has no false negatives: - for i in [1..10000] - throw Error("is_square broken") unless is_square i*i - - # test non_square is valid for first million values of n - for i in [1..1000000] - throw Error("non_square broken") if is_square non_square(i) - - console.log "success" diff --git a/Task/Sequence-of-non-squares/CoffeeScript/sequence-of-non-squares-2.coffee b/Task/Sequence-of-non-squares/CoffeeScript/sequence-of-non-squares-2.coffee deleted file mode 100644 index 3862a52e27..0000000000 --- a/Task/Sequence-of-non-squares/CoffeeScript/sequence-of-non-squares-2.coffee +++ /dev/null @@ -1,3 +0,0 @@ -> coffee foo.coffee -[ 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27 ] -success diff --git a/Task/Sequence-of-non-squares/Haskell/sequence-of-non-squares.hs b/Task/Sequence-of-non-squares/Haskell/sequence-of-non-squares-1.hs similarity index 100% rename from Task/Sequence-of-non-squares/Haskell/sequence-of-non-squares.hs rename to Task/Sequence-of-non-squares/Haskell/sequence-of-non-squares-1.hs diff --git a/Task/Sequence-of-non-squares/Haskell/sequence-of-non-squares-2.hs b/Task/Sequence-of-non-squares/Haskell/sequence-of-non-squares-2.hs new file mode 100644 index 0000000000..c954cc86e8 --- /dev/null +++ b/Task/Sequence-of-non-squares/Haskell/sequence-of-non-squares-2.hs @@ -0,0 +1,21 @@ +import Control.Monad (join) + +root :: Int -> Float +root = sqrt . fromIntegral + +nonSqr :: Int -> Int +nonSqr = (+) <*> (round . root) + +notSquare :: Int -> Bool +notSquare = (/=) <*> (join (*) . floor . root) + +main :: IO () +main = + mapM_ + putStrLn + [ "First 22 members of the series:" + , unwords $ (show . nonSqr) <$> [1 .. 22] + , "" + , "All first 10E6 members non square:" + , show $ all (== True) $ (notSquare . nonSqr) <$> [1 .. 1000000] + ] diff --git a/Task/Sequence-of-non-squares/jq/sequence-of-non-squares-1.jq b/Task/Sequence-of-non-squares/Jq/sequence-of-non-squares-1.jq similarity index 100% rename from Task/Sequence-of-non-squares/jq/sequence-of-non-squares-1.jq rename to Task/Sequence-of-non-squares/Jq/sequence-of-non-squares-1.jq diff --git a/Task/Sequence-of-non-squares/jq/sequence-of-non-squares-2.jq b/Task/Sequence-of-non-squares/Jq/sequence-of-non-squares-2.jq similarity index 100% rename from Task/Sequence-of-non-squares/jq/sequence-of-non-squares-2.jq rename to Task/Sequence-of-non-squares/Jq/sequence-of-non-squares-2.jq 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.kotlin new file mode 100644 index 0000000000..55099db73f --- /dev/null +++ b/Task/Sequence-of-non-squares/Kotlin/sequence-of-non-squares.kotlin @@ -0,0 +1,17 @@ +// version 1.1 + +fun f(n: Int) = n + Math.floor(0.5 + Math.sqrt(n.toDouble())).toInt() + +fun main(args: Array<String>) { + println(" n f") + val squares = mutableListOf<Int>() + for (n in 1 until 1000000) { + val v1 = f(n) + val v2 = Math.sqrt(v1.toDouble()).toInt() + if (v1 == v2 * v2) squares.add(n) + if (n < 23) println("${"%2d".format(n)} : $v1") + } + println() + if (squares.size == 0) println("There are no squares for n less than one million") + else println("Squares are generated for the following values of n: $squares") +} diff --git a/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx b/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx index 788f9c4d36..f5a1d9cd3f 100644 --- a/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx +++ b/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx @@ -3,25 +3,26 @@ parse arg N M . /*obtain optional arguments fro if N=='' | N=="," then N= 22 /*Not specified? Then use the default.*/ if M=='' | M=="," then M= 1000000 /* " " " " " " */ say 'The first ' N " non-square numbers:" /*display a header of what's to come. */ -say +say /* [↑] default for M is one million.*/ +say center('index', 20) center('non-square numbers', 20) +say center('' , 20, "═") center('' , 20, "═") do j=1 for N - say right(j, 6) right(j + floor(1/2 + sqrt(j)), 7) /*could use (.5+ ··· */ + say center(j, 20) center(j +floor(1/2 +sqrt(j)), 20) /*could use (.5+ ···*/ end /*j*/ #oops=0 do k=1 for abs(M-1) /*have it step through a million of 'em*/ - n=k+floor( .5 + sqrt(k)) /*use the specified formula (algorithm)*/ - iRoot=iSqrt(n) /*··· and also use the ISQRT function.*/ - if iRoot*iRoot==n then #oops=#oops+1 /*have we found a mistook? (sic) */ + $= k + floor( .5 + sqrt(k) ) /*use the specified formula (algorithm)*/ + iRoot=iSqrt($) /*··· and also use the ISQRT function.*/ + if iRoot*iRoot==$ then #oops=#oops+1 /*have we found a mistook? (sic) */ end /*k*/ -say -say 'Using the formula: floor[ 1/2 + sqrt(n) ], ' #oops " squares found up to " M'.' +say; if #oops==0 then #oops= 'no' /*use gooder English.*/ +say 'Using the formula: floor[ 1/2 + sqrt(n) ], ' #oops " squares found up to " M'.' /* [↑] display (possible) error count.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -floor: procedure; parse arg x; return trunc( x - (x<0) ) +floor: procedure; parse arg x; return trunc( x - (x<0) ) /*──────────────────────────────────────────────────────────────────────────────────────*/ -iSqrt: procedure; parse arg x; x=trunc(x); r=0; q=1 - do while q<=x; q=q*4; end +iSqrt: procedure; parse arg x; x=trunc(x); r=0; q=1; do while q<=x; q=q*4; end do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do; x=_; r=r+q; end; end return r /*return the integer square root of X.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ diff --git a/Task/Sequence-of-non-squares/Ruby/sequence-of-non-squares.rb b/Task/Sequence-of-non-squares/Ruby/sequence-of-non-squares.rb index 94f95d15cd..9f2cf710f9 100644 --- a/Task/Sequence-of-non-squares/Ruby/sequence-of-non-squares.rb +++ b/Task/Sequence-of-non-squares/Ruby/sequence-of-non-squares.rb @@ -1,9 +1,11 @@ -def f(n); n + (0.5 + Math.sqrt(n)).floor; end +def f(n) + n + (0.5 + Math.sqrt(n)).floor +end -(1..22).each { |n| p "#{n} #{f(n)}" } +(1..22).each { |n| puts "#{n} #{f(n)}" } non_squares = (1..1_000_000).map { |n| f(n) } squares = (1..1001).map { |n| n**2 } # Note: 1001*1001 = 1_002_001 > 1_001_000 = f(1_000_000) (squares & non_squares).each do |n| - fail "Oops, found a square f(#{non_squares.index(n)}) = #{n}" + puts "Oops, found a square f(#{non_squares.index(n)}) = #{n}" end diff --git a/Task/Sequence-of-non-squares/Sidef/sequence-of-non-squares.sidef b/Task/Sequence-of-non-squares/Sidef/sequence-of-non-squares.sidef index 189d4db20f..c3fb9d197f 100644 --- a/Task/Sequence-of-non-squares/Sidef/sequence-of-non-squares.sidef +++ b/Task/Sequence-of-non-squares/Sidef/sequence-of-non-squares.sidef @@ -1,8 +1,8 @@ func nonsqr(n) { 0.5 + n.sqrt -> floor + n } -22.of {|i| nonsqr(i)}.join(' ').say +{|i| nonsqr(i) }.map(1..22).join(' ').say { |i| if (nonsqr(i).is_sqr) { die "Found a square in the sequence: #{i}" } -} * 1e6 +} << 1..1e6 diff --git a/Task/Sequence-of-non-squares/Smalltalk/sequence-of-non-squares.st b/Task/Sequence-of-non-squares/Smalltalk/sequence-of-non-squares.st new file mode 100644 index 0000000000..4409039047 --- /dev/null +++ b/Task/Sequence-of-non-squares/Smalltalk/sequence-of-non-squares.st @@ -0,0 +1,19 @@ +| nonSquare isSquare squaresFound | +nonSquare := [:n | + n + (n sqrt) rounded +]. +isSquare := [:n | + n = (((n sqrt) asInteger) raisedTo: 2) +]. +Transcript show: 'The first few non-squares:'; cr. +1 to: 22 do: [:n | + Transcript show: (nonSquare value: n) asString; cr +]. +squaresFound := 0. +1 to: 1000000 do: [:n | + (isSquare value: (nonSquare value: n)) ifTrue: [ + squaresFound := squaresFound + 1 + ] +]. +Transcript show: 'Squares found for values up to 1,000,000: '; +show: squaresFound asString; cr diff --git a/Task/Sequence-of-non-squares/Zkl/sequence-of-non-squares.zkl b/Task/Sequence-of-non-squares/Zkl/sequence-of-non-squares.zkl new file mode 100644 index 0000000000..099a7a9da0 --- /dev/null +++ b/Task/Sequence-of-non-squares/Zkl/sequence-of-non-squares.zkl @@ -0,0 +1,7 @@ +fcn seq(n){n + (0.5+n.toFloat().sqrt()).floor()} +[1..22].apply(seq).toString(*).println(); + +fcn isSquare(n){n.toFloat().sqrt().modf()[1]==0.0} +isSquare(25) //-->True +isSquare(26) //-->False +[2..0d1_000_000].filter(fcn(n){isSquare(seq(n))}).println(); diff --git a/Task/Sequence-of-primes-by-Trial-Division/00DESCRIPTION b/Task/Sequence-of-primes-by-Trial-Division/00DESCRIPTION index 7812f6e9b2..abda9938cb 100644 --- a/Task/Sequence-of-primes-by-Trial-Division/00DESCRIPTION +++ b/Task/Sequence-of-primes-by-Trial-Division/00DESCRIPTION @@ -14,6 +14,12 @@ If you want to use a ready-made <code>is_prime</code> function, use one from the ;Related tasks: -:*   [[Primality by trial division]] -:*   [[Sieve of Eratosthenes]] +*   [[count in factors]] +*   [[prime decomposition]] +*   [[factors of an integer]] +*   [[Sieve of Eratosthenes]] +*   [[primality by trial division]] +*   [[factors of a Mersenne number]] +*   [[trial factoring of a Mersenne number]] +*   [[partition an integer X into N primes]] <br><br> diff --git a/Task/Sequence-of-primes-by-Trial-Division/ALGOL-W/sequence-of-primes-by-trial-division.alg b/Task/Sequence-of-primes-by-Trial-Division/ALGOL-W/sequence-of-primes-by-trial-division.alg new file mode 100644 index 0000000000..4f3fe9cb62 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/ALGOL-W/sequence-of-primes-by-trial-division.alg @@ -0,0 +1,32 @@ +begin + % use the isPrime procedure from the Primality by Trial Division task % + logical procedure isPrime ( integer value n ) ; algol "isPrime" ; + % sets the elements of p to the first n primes. p must have bounds 1 :: n % + procedure getPrimes ( integer array p ( * ) + ; integer value n + ) ; + if n > 0 then begin + % have room for at least oe prime % + integer pPos, possiblePrime; + p( 1 ) := 2; + pPos := 2; + possiblePrime := 3; + while pPos <= n do begin + if isPrime( possiblePrime ) then begin + p( pPos ) := possiblePrime; + pPos := pPos + 1; + end; + possiblePrime := possiblePrime + 1 + end + end getPrimes ; + + begin % test getPrimes % + integer array p( 1 :: 100 ); + getPrimes( p, 100 ); + for i := 1 until 100 do begin + if i rem 20 = 1 then write( i_w := 4, s_w := 1, p( i ) ) + else writeon( i_w := 4, s_w := 1, p( i ) ) + end for_i + end + +end. diff --git a/Task/Sequence-of-primes-by-Trial-Division/C-sharp/sequence-of-primes-by-trial-division.cs b/Task/Sequence-of-primes-by-Trial-Division/C-sharp/sequence-of-primes-by-trial-division.cs new file mode 100644 index 0000000000..f6af5b3ccf --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/C-sharp/sequence-of-primes-by-trial-division.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public class Program +{ + static void Main() { + Console.WriteLine(string.Join(" ", Primes(100))); + } + + static IEnumerable<int> Primes(int limit) => Enumerable.Range(2, limit-2).Where(IsPrime); + static bool IsPrime(int n) => Enumerable.Range(2, (int)Math.Sqrt(n)-1).All(i => n % i != 0); +} diff --git a/Task/Sequence-of-primes-by-Trial-Division/C/sequence-of-primes-by-trial-division.c b/Task/Sequence-of-primes-by-Trial-Division/C/sequence-of-primes-by-trial-division.c new file mode 100644 index 0000000000..5feafc9f32 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/C/sequence-of-primes-by-trial-division.c @@ -0,0 +1,36 @@ +/*Abhishek Ghosh, 21st September 2017*/ + +#include<stdio.h> + +int isPrime(unsigned int n) +{ + unsigned int num; + + if ( n < 2||!(n & 1)) + return n == 2; + + for (num = 3; num <= n/num; num += 2) + if (!(n % num)) + return 0; + return 1; +} + +int main() +{ + unsigned int l,u,i,sum=0; + + printf("Enter lower and upper bounds: "); + scanf("%ld%ld",&l,&u); + + for(i=l;i<=u;i++){ + if(isPrime(i)==1) + { + printf("\n%ld",i); + sum++; + } + } + + printf("\n\nPrime numbers found in [%ld,%ld] : %ld",l,u,sum); + + return 0; +} diff --git a/Task/Sequence-of-primes-by-Trial-Division/Clojure/sequence-of-primes-by-trial-division.clj b/Task/Sequence-of-primes-by-Trial-Division/Clojure/sequence-of-primes-by-trial-division.clj index 299d13e810..a29ee85ce5 100644 --- a/Task/Sequence-of-primes-by-Trial-Division/Clojure/sequence-of-primes-by-trial-division.clj +++ b/Task/Sequence-of-primes-by-Trial-Division/Clojure/sequence-of-primes-by-trial-division.clj @@ -3,14 +3,17 @@ (defn prime? [a] " Uses trial division to determine if number is prime " - (not (or (< a 2) - (some #(= 0 (mod a %)) - (range 3 (inc (int (Math/ceil (math/sqrt a)))) 2))))) ; 3 to sqrt(n) stepping by 2 + (or (= a 2) + (and (> a 2) + (> (mod a 2) 0) + (not (some #(= 0 (mod a %)) + (range 3 (inc (int (Math/ceil (math/sqrt a)))) 2)))))) + ; 3 to sqrt(a) stepping by 2 (defn primes-below [n] " Finds primes below number n " - (for [q (range 2 (inc n)) - :when (prime? q)] - q)) + (for [a (range 2 (inc n)) + :when (prime? a)] + a)) (println (primes-below 100)) diff --git a/Task/Sequence-of-primes-by-Trial-Division/F-Sharp/sequence-of-primes-by-trial-division-1.fs b/Task/Sequence-of-primes-by-Trial-Division/F-Sharp/sequence-of-primes-by-trial-division-1.fs new file mode 100644 index 0000000000..433e2f2ec5 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/F-Sharp/sequence-of-primes-by-trial-division-1.fs @@ -0,0 +1,8 @@ +(* + Nigel Galloway April 7th., 2017. +*) +let SofE = + let rec fg ng = seq{ + let n = Seq.item 0 ng + yield n; yield! fg (Seq.cache(Seq.filter (fun g->g%n<>0) (Seq.skip 1 ng)))} + fg (Seq.initInfinite(id)|>Seq.skip 2) diff --git a/Task/Sequence-of-primes-by-Trial-Division/F-Sharp/sequence-of-primes-by-trial-division-2.fs b/Task/Sequence-of-primes-by-Trial-Division/F-Sharp/sequence-of-primes-by-trial-division-2.fs new file mode 100644 index 0000000000..f6e32ffc0e --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/F-Sharp/sequence-of-primes-by-trial-division-2.fs @@ -0,0 +1 @@ +[23..42] |> Seq.iter(fun n->printf "%d " (Seq.item n SofE)) diff --git a/Task/Sequence-of-primes-by-Trial-Division/jq/sequence-of-primes-by-trial-division-1.jq b/Task/Sequence-of-primes-by-Trial-Division/Jq/sequence-of-primes-by-trial-division-1.jq similarity index 100% rename from Task/Sequence-of-primes-by-Trial-Division/jq/sequence-of-primes-by-trial-division-1.jq rename to Task/Sequence-of-primes-by-Trial-Division/Jq/sequence-of-primes-by-trial-division-1.jq diff --git a/Task/Sequence-of-primes-by-Trial-Division/jq/sequence-of-primes-by-trial-division-2.jq b/Task/Sequence-of-primes-by-Trial-Division/Jq/sequence-of-primes-by-trial-division-2.jq similarity index 100% rename from Task/Sequence-of-primes-by-Trial-Division/jq/sequence-of-primes-by-trial-division-2.jq rename to Task/Sequence-of-primes-by-Trial-Division/Jq/sequence-of-primes-by-trial-division-2.jq diff --git a/Task/Sequence-of-primes-by-Trial-Division/jq/sequence-of-primes-by-trial-division-3.jq b/Task/Sequence-of-primes-by-Trial-Division/Jq/sequence-of-primes-by-trial-division-3.jq similarity index 100% rename from Task/Sequence-of-primes-by-Trial-Division/jq/sequence-of-primes-by-trial-division-3.jq rename to Task/Sequence-of-primes-by-Trial-Division/Jq/sequence-of-primes-by-trial-division-3.jq diff --git a/Task/Sequence-of-primes-by-Trial-Division/jq/sequence-of-primes-by-trial-division-4.jq b/Task/Sequence-of-primes-by-Trial-Division/Jq/sequence-of-primes-by-trial-division-4.jq similarity index 100% rename from Task/Sequence-of-primes-by-Trial-Division/jq/sequence-of-primes-by-trial-division-4.jq rename to Task/Sequence-of-primes-by-Trial-Division/Jq/sequence-of-primes-by-trial-division-4.jq 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.kotlin new file mode 100644 index 0000000000..d4a74a74a5 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Kotlin/sequence-of-primes-by-trial-division.kotlin @@ -0,0 +1,27 @@ +// version 1.0.6 + +fun isPrime(n: Int): Boolean { + if (n < 2) return false + if (n % 2 == 0) return n == 2 + if (n % 3 == 0) return n == 3 + var d : Int = 5 + while (d * d <= n) { + if (n % d == 0) return false + d += 2 + if (n % d == 0) return false + d += 4 + } + return true +} + +fun main(args: Array<String>) { + // print all primes below 2000 say + var count = 1 + print(" 2") + for (i in 3..1999 step 2) + if (isPrime(i)) { + count++ + print("%5d".format(i)) + if (count % 15 == 0) println() + } +} diff --git a/Task/Sequence-of-primes-by-Trial-Division/Lambdatalk/sequence-of-primes-by-trial-division.lambdatalk b/Task/Sequence-of-primes-by-Trial-Division/Lambdatalk/sequence-of-primes-by-trial-division.lambdatalk new file mode 100644 index 0000000000..4b671e913e --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Lambdatalk/sequence-of-primes-by-trial-division.lambdatalk @@ -0,0 +1,16 @@ +{def prime + {def prime.rec + {lambda {:m :n} + {if {> {* :m :m} :n} + then :n + else {if {= {% :n :m} 0} + then + else {prime.rec {+ :m 1} :n} }}}} + {lambda {:n} + {prime.rec 2 :n} }} + +{map prime {serie 3 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 + +{map prime {serie 9901 10000 2}} +-> 9901 9907 9923 9929 9931 9941 9949 9967 9973 diff --git a/Task/Sequence-of-primes-by-Trial-Division/Phix/sequence-of-primes-by-trial-division.phix b/Task/Sequence-of-primes-by-Trial-Division/Phix/sequence-of-primes-by-trial-division.phix new file mode 100644 index 0000000000..503e8b9712 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Phix/sequence-of-primes-by-trial-division.phix @@ -0,0 +1,5 @@ +sequence s= {} +for i=0 to 100 do + if is_prime(i) then s&=i end if +end for +?s diff --git a/Task/Sequence-of-primes-by-Trial-Division/PureBasic/sequence-of-primes-by-trial-division.purebasic b/Task/Sequence-of-primes-by-Trial-Division/PureBasic/sequence-of-primes-by-trial-division.purebasic new file mode 100644 index 0000000000..713121dd81 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/PureBasic/sequence-of-primes-by-trial-division.purebasic @@ -0,0 +1,49 @@ +EnableExplicit +#SPC=Chr(32) +#TB=~"\t" +#TBLF=~"\t\n" +Define.i a,b,l,n,count=0 +Define *count.Integer=@count + +Procedure.i AddCount(*c.Integer) ; *counter: by Ref + *c\i+1 + ProcedureReturn *c\i +EndProcedure + +Procedure.s FormatStr(tx$,l.i) + Shared *count + If AddCount(*count)%10=0 + ProcedureReturn RSet(tx$,l,#SPC)+#TBLF + Else + ProcedureReturn RSet(tx$,l,#SPC)+#TB + EndIf +EndProcedure + +Procedure.b Trial(n.i) + Define.i i + For i=3 To Int(Sqr(n)) Step 2 + If n%i=0 : ProcedureReturn #False : EndIf + Next + ProcedureReturn #True +EndProcedure + +Procedure.b isPrime(n.i) + If (n>1 And n%2<>0 And Trial(n)) Or n=2 : ProcedureReturn #True : EndIf + ProcedureReturn #False +EndProcedure + +OpenConsole("Sequence of primes by Trial Division") +PrintN("Input (n1<n2 & n1>0)") +Print("n1 : ") : a=Int(Val(Input())) +Print("n2 : ") : b=Int(Val(Input())) +l=Len(Str(b)) +If a<b And a>0 + PrintN(~"\nPrime numbers between "+Str(a)+" and "+Str(b)) + For n=a To b + If isPrime(n) + Print(FormatStr(Str(n),l)) + EndIf + Next + Print(~"\nPrimes= "+Str(*count\i)) + Input() +EndIf diff --git a/Task/Sequence-of-primes-by-Trial-Division/REXX/sequence-of-primes-by-trial-division-2.rexx b/Task/Sequence-of-primes-by-Trial-Division/REXX/sequence-of-primes-by-trial-division-2.rexx index c8c48e9fe3..26351043cd 100644 --- a/Task/Sequence-of-primes-by-Trial-Division/REXX/sequence-of-primes-by-trial-division-2.rexx +++ b/Task/Sequence-of-primes-by-Trial-Division/REXX/sequence-of-primes-by-trial-division-2.rexx @@ -1,23 +1,23 @@ /*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 assume default.*/ -tell= (n>0); n=abs(n) /*N is negative? Then don't display. */ +parse arg N . /*get optional number of primes to find*/ +if N=='' | N=="," then N=26 /*Not specified? Then assume default.*/ +tell= (N>0); N=abs(N) /*N is negative? Then don't display. */ @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; #=5; s=@.#+2 /* [↑] is the number of low primes.*/ - do p=1 for # while p<=n /* [↓] find primes, but don't show 'em*/ - if tell then say right(@.p, 9) /*display some pre-defined 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 /*continue on with the next odd prime. */ - if j// 3 ==0 then iterate /*is this integer a multiple of three? */ + do j=s by 2 while #<N /*continue on with the next odd prime. */ + if j // 3 ==0 then iterate /*is this integer a multiple of three? */ parse var j '' -1 _ /*obtain the last digit of the J var.*/ - if _ ==5 then iterate /*is this integer a multiple of five? */ - if j// 7 ==0 then iterate /* " " " " " " seven? */ - if j//11 ==0 then iterate /* " " " " " " eleven?*/ + if _ ==5 then iterate /*is this integer a multiple of five? */ + if j // 7 ==0 then iterate /* " " " " " " seven? */ + if j //11 ==0 then iterate /* " " " " " " eleven?*/ /* [↓] divide by the primes. ___ */ do k=p to # while !.k<=j /*divide J by other primes ≤ √ J */ - if j//@.k==0 then iterate j /*÷ by prev. prime? ¬prime ___ */ + if j//@.k == 0 then iterate j /*÷ by prev. prime? ¬prime ___ */ end /*k*/ /* [↑] only divide up to √ J */ #=#+1 /*bump the count of number of primes. */ @.#=j; !.#=j*j /*define this prime; define its square.*/ diff --git a/Task/Sequence-of-primes-by-Trial-Division/Zkl/sequence-of-primes-by-trial-division-1.zkl b/Task/Sequence-of-primes-by-Trial-Division/Zkl/sequence-of-primes-by-trial-division-1.zkl new file mode 100644 index 0000000000..25e85d0f6d --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Zkl/sequence-of-primes-by-trial-division-1.zkl @@ -0,0 +1,4 @@ +fcn isPrime(p){ + (p>=2) and (not [2 .. p.toFloat().sqrt()].filter1('wrap(n){ p%n==0 })) +} +fcn primesBelow(n){ [0..n].filter(isPrime) } diff --git a/Task/Sequence-of-primes-by-Trial-Division/Zkl/sequence-of-primes-by-trial-division-2.zkl b/Task/Sequence-of-primes-by-Trial-Division/Zkl/sequence-of-primes-by-trial-division-2.zkl new file mode 100644 index 0000000000..35fdfa361f --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Zkl/sequence-of-primes-by-trial-division-2.zkl @@ -0,0 +1 @@ +primesBelow(100).toString(*).println(); diff --git a/Task/Set-consolidation/Aime/set-consolidation.aime b/Task/Set-consolidation/Aime/set-consolidation.aime index ba0e85afcc..a7d1c4e35e 100644 --- a/Task/Set-consolidation/Aime/set-consolidation.aime +++ b/Task/Set-consolidation/Aime/set-consolidation.aime @@ -2,26 +2,21 @@ void display(list l) { integer i; + record r; text s; - i = -l_length(l); - while (i) { - record r; + for (i, r in l) { text u, v; o_text(s); s = ", "; o_text("{"); - r = l_q_record(l, i); - if (r_first(r, u)) { - do { - o_text(v); - v = ", "; - o_text(u); - } while (r_greater(r, u, u)); + for (u in r) { + o_text(v); + v = ", "; + o_text(u); } o_text("}"); - i += 1; } o_text("\n"); @@ -34,13 +29,11 @@ intersect(record r, record u) text s; a = 0; - if (r_first(r, s)) { - do { - if (r_key(u, s)) { - a = 1; - break; - } - } while (r_greater(r, s, s)); + for (s in r) { + if (r_key(u, s)) { + a = 1; + break; + } } return a; @@ -49,36 +42,28 @@ intersect(record r, record u) void merge(record u, record r) { - text s; - - if (r_first(r, s)) { - do { - r_add(u, s, r_query(r, s)); - } while (r_greater(r, s, s)); - } + r_wcall(r, r_add, 1, 2, u); } list consolidate(list l) { integer i; + record r; - i = -l_length(l); - while (i) { + for (i, r in l) { integer j; - record r; - r = l_q_record(l, i); - i += 1; - j = i; + j = i - ~l + 1; while (j) { record u; - u = l_q_record(l, j); + u = l[j]; j += 1; if (intersect(r, u)) { merge(u, r); - l_delete(l, i - 1); + l_delete(l, i); + i -= 1; break; } } @@ -90,29 +75,15 @@ consolidate(list l) list L(...) { - integer i; - list l; - - i = -count(); - while (i) { - l_link(l, -1, $i); - i += 1; - } - - return l; + return xcall(l_assemble); } record R(...) { - integer i; record r; - i = -count(); - while (i) { - r_p_integer(r, $i, 0); - i += 1; - } + ucall(r_p_integer, 1, r, 0); return r; } diff --git a/Task/Set-consolidation/jq/set-consolidation-1.jq b/Task/Set-consolidation/Jq/set-consolidation-1.jq similarity index 100% rename from Task/Set-consolidation/jq/set-consolidation-1.jq rename to Task/Set-consolidation/Jq/set-consolidation-1.jq diff --git a/Task/Set-consolidation/jq/set-consolidation-2.jq b/Task/Set-consolidation/Jq/set-consolidation-2.jq similarity index 100% rename from Task/Set-consolidation/jq/set-consolidation-2.jq rename to Task/Set-consolidation/Jq/set-consolidation-2.jq diff --git a/Task/Set-consolidation/jq/set-consolidation-3.jq b/Task/Set-consolidation/Jq/set-consolidation-3.jq similarity index 100% rename from Task/Set-consolidation/jq/set-consolidation-3.jq rename to Task/Set-consolidation/Jq/set-consolidation-3.jq diff --git a/Task/Set-consolidation/jq/set-consolidation-4.jq b/Task/Set-consolidation/Jq/set-consolidation-4.jq similarity index 100% rename from Task/Set-consolidation/jq/set-consolidation-4.jq rename to Task/Set-consolidation/Jq/set-consolidation-4.jq diff --git a/Task/Set-consolidation/Kotlin/set-consolidation.kotlin b/Task/Set-consolidation/Kotlin/set-consolidation.kotlin new file mode 100644 index 0000000000..2fd9932993 --- /dev/null +++ b/Task/Set-consolidation/Kotlin/set-consolidation.kotlin @@ -0,0 +1,35 @@ +// version 1.0.6 + +fun<T : Comparable<T>> consolidateSets(sets: Array<Set<T>>): Set<Set<T>> { + val size = sets.size + val consolidated = BooleanArray(size) // all false by default + var i = 0 + while (i < size - 1) { + if (!consolidated[i]) { + while (true) { + var intersects = 0 + for (j in (i + 1) until size) { + if (consolidated[j]) continue + if (sets[i].intersect(sets[j]).isNotEmpty()) { + sets[i] = sets[i].union(sets[j]) + consolidated[j] = true + intersects++ + } + } + if (intersects == 0) break + } + } + i++ + } + return (0 until size).filter { !consolidated[it] }.map { sets[it].toSortedSet() }.toSet() +} + +fun main(args: Array<String>) { + val unconsolidatedSets = arrayOf( + arrayOf(setOf('A', 'B'), setOf('C', 'D')), + arrayOf(setOf('A', 'B'), setOf('B', 'D')), + arrayOf(setOf('A', 'B'), setOf('C', 'D'), setOf('D', 'B')), + arrayOf(setOf('H', 'I', 'K'), setOf('A', 'B'), setOf('C', 'D'), setOf('D', 'B'), setOf('F', 'G', 'H')) + ) + for (sets in unconsolidatedSets) println(consolidateSets(sets)) +} diff --git a/Task/Set-consolidation/OoRexx/set-consolidation.rexx b/Task/Set-consolidation/OoRexx/set-consolidation.rexx new file mode 100644 index 0000000000..fe3639cf99 --- /dev/null +++ b/Task/Set-consolidation/OoRexx/set-consolidation.rexx @@ -0,0 +1,116 @@ +/* REXX *************************************************************** +* 04.08.2013 Walter Pachl using ooRexx features +* (maybe not in the best way -improvements welcome!) +* but trying to demonstrate the algorithm +**********************************************************************/ +s.1=.array~of(.set~of('A','B'),.set~of('C','D')) +s.2=.array~of(.set~of('A','B'),.set~of('B','D')) +s.3=.array~of(.set~of('A','B'),.set~of('C','D'),.set~of('D','B')) +s.4=.array~of(.set~of('H','I','K'),.set~of('A','B'),.set~of('C','D'),, + .set~of('B','D'),.set~of('F','G','H')) +s.5=.array~of(.set~of('snow','ice','slush','frost','fog'),, + .set~of('iceburgs','icecubes'),, + .set~of('rain','fog','sleet')) +s.6=.array~of('one') +s.7=.array~new +s.8=.array~of('') +Do si=1 To 8 /* loop through the test data */ + na=s.si /* an array of sets */ + head='Output(s):' + Say left('Input' si,10) list_as(na) /* show the input */ + Do While na~items()>0 /* while the array ain't empty*/ + na=cons(na) /* consolidate and get back */ + /* array of remaining sets */ + head=' ' + End + Say '====' /* separator line */ + End +Exit + +cons: Procedure Expose head +/********************************************************************** +* consolidate the sets in the given array +**********************************************************************/ + Use Arg a + w=a /* work on a copy */ + n=w~items() /* number of sets in the array*/ + Select + When n=0 Then /* no set in array */ + Return .array~new /* retuns an empty array */ + When n=1 Then Do /* one set in array */ + Say head list(w[1]) /* show its contents */ + Return .array~new /* retuns an empty array */ + End + Otherwise Do /* at least two sets are there*/ + b=.array~new /* use for remaining sets */ + r=w[n] /* start with last set */ + try=1 + Do until changed=0 /* loop until result is stable*/ + changed=0 + new=0 + n=w~items() /* number of sets */ + Do i=1 To n-try /* loop first through n-1 sets*/ + try=0 /* then through all of them */ + is=r~intersection(w[i]) + If is~items>0 Then Do /* any elements in common */ + r=r~union(w[i]) /* result is the union */ + Changed=1 /* and result is now larger */ + End + Else Do /* no elemen in common */ + new=new+1 /* add the set to the array */ + b[new]=w[i] /* of remaining sets */ + End + End + If b~items()=0 Then Do /* no remaining sets */ + w=.array~new + Leave /* we are done */ + End + w=b /* repeat with remaining sets */ + b=.array~new /* prepare for next iteration */ + End + End + Say head list(r) /* show one consolidated set */ + End + Return w /* return array of remaining */ + +list: Procedure +/********************************************************************** +* list elements of given set +**********************************************************************/ + Call trace ?O + Use Arg set + arr=set~makeArray + arr~sort() + ol='(' + Do i=1 To arr~items() + If i=1 Then + ol=ol||arr[i] + Else + ol=ol||','arr[i] + End + Return ol')' + +list_as: Procedure +/********************************************************************** +* List an array of sets +**********************************************************************/ + Call trace ?O + Use Arg a + n=a~items() + If n=0 Then + ol='no element in array' + Else Do + ol='' + Do i=1 To n + ol=ol '(' + arr=a[i]~makeArray + Do j=1 To arr~items() + If j=1 Then + ol=ol||arr[j] + Else + ol=ol','arr[j] + End + ol=ol') ' + End + End + Return strip(ol) diff --git a/Task/Set-consolidation/Zkl/set-consolidation-1.zkl b/Task/Set-consolidation/Zkl/set-consolidation-1.zkl new file mode 100644 index 0000000000..1765c6f37c --- /dev/null +++ b/Task/Set-consolidation/Zkl/set-consolidation-1.zkl @@ -0,0 +1,11 @@ +fcn consolidate(sets){ // set are munged if they are read/write + if(sets.len()<2) return(sets); + r,r0 := List(List()),sets[0]; + foreach x in (consolidate(sets[1,*])){ + i,ni:=x.filter22(r0.holds); //-->(intersection, !intersection) + if(i) r0=r0.extend(ni); + else r.append(x); + } + r[0]=r0; + r +} diff --git a/Task/Set-consolidation/Zkl/set-consolidation-2.zkl b/Task/Set-consolidation/Zkl/set-consolidation-2.zkl new file mode 100644 index 0000000000..dbc227bc2b --- /dev/null +++ b/Task/Set-consolidation/Zkl/set-consolidation-2.zkl @@ -0,0 +1,16 @@ +fcn prettize(sets){ + sets.apply("concat"," ").pump(String,"(%s),".fmt)[0,-1] +} + +foreach sets in (T( + T(L("A","B")), + T(L("A","B"),L("C","D")), + T(L("A","B"),L("B","D")), + T(L("A","B"),L("C","D"),L("D","B")), + T(L("H","I","K"),L("A","B"),L("C","D"),L("D","B"),L("F","G","H")), + T(L("A","H"),L("H","I","K"),L("A","B"),L("C","D"),L("D","B"),L("F","G","H")), + T(L("H","I","K"),L("A","B"),L("C","D"),L("D","B"),L("F","G","H"), L("A","H")), +)){ + prettize(sets).print(" --> "); + consolidate(sets) : prettize(_).println(); +} diff --git a/Task/Set-of-real-numbers/Common-Lisp/set-of-real-numbers.lisp b/Task/Set-of-real-numbers/Common-Lisp/set-of-real-numbers.lisp new file mode 100644 index 0000000000..0d38dfebf1 --- /dev/null +++ b/Task/Set-of-real-numbers/Common-Lisp/set-of-real-numbers.lisp @@ -0,0 +1,29 @@ +(deftype set== (a b) `(real ,a ,b)) +(deftype set<> (a b) `(real (,a) (,b))) +(deftype set=> (a b) `(real ,a (,b))) +(deftype set<= (a b) `(real (,a) ,b)) + +(deftype set-union (s1 s2) `(or ,s1 ,s2)) +(deftype set-intersection (s1 s2) `(and ,s1 ,s2)) +(deftype set-diff (s1 s2) `(and ,s1 (not ,s2))) + +(defun in-set-p (x set) + (typep x set)) + +(defun test () + (let ((set '(set-union (set<= 0 1) (set=> 0 2)))) + (assert (in-set-p 0 set)) + (assert (in-set-p 1 set)) + (assert (not (in-set-p 2 set)))) + (let ((set '(set-intersection (set=> 0 2) (set<= 1 2)))) + (assert (not (in-set-p 0 set))) + (assert (not (in-set-p 1 set))) + (assert (not (in-set-p 2 set)))) + (let ((set '(set-diff (set=> 0 3) (set<> 0 1)))) + (assert (in-set-p 0 set)) + (assert (in-set-p 1 set)) + (assert (in-set-p 2 set))) + (let ((set '(set-diff (set<= 0 3) (set== 0 1)))) + (assert (not (in-set-p 0 set))) + (assert (not (in-set-p 1 set))) + (assert (in-set-p 2 set)))) diff --git a/Task/Set-of-real-numbers/D/set-of-real-numbers-1.d b/Task/Set-of-real-numbers/D/set-of-real-numbers-1.d deleted file mode 100644 index bcdda17e71..0000000000 --- a/Task/Set-of-real-numbers/D/set-of-real-numbers-1.d +++ /dev/null @@ -1,61 +0,0 @@ -struct Set(T) { - const pure nothrow bool delegate(in T) contains; - - bool opIn_r(in T x) const pure nothrow { - return contains(x); - } - - Set opBinary(string op)(in Set set) - const pure nothrow if (op == "+" || op == "-") { - static if (op == "+") - return Set(x => contains(x) || set.contains(x)); - else - return Set(x => contains(x) && !set.contains(x)); - } - - Set intersection(in Set set) const pure nothrow { - return Set(x => contains(x) && set.contains(x)); - } -} - -unittest { // Test union. - alias DSet = Set!double; - const s = DSet(x => 0.0 < x && x <= 1.0) + - DSet(x => 0.0 <= x && x < 2.0); - assert(0.0 in s); - assert(1.0 in s); - assert(2.0 !in s); -} - -unittest { // Test difference. - alias DSet = Set!double; - const s1 = DSet(x => 0.0 <= x && x < 3.0) - - DSet(x => 0.0 < x && x < 1.0); - assert(0.0 in s1); - assert(0.5 !in s1); - assert(1.0 in s1); - assert(2.0 in s1); - - const s2 = DSet(x => 0.0 <= x && x < 3.0) - - DSet(x => 0.0 <= x && x <= 1.0); - assert(0.0 !in s2); - assert(1.0 !in s2); - assert(2.0 in s2); - - const s3 = DSet(x => 0 <= x && x <= double.infinity) - - DSet(x => 1.0 <= x && x <= 2.0); - assert(0.0 in s3); - assert(1.5 !in s3); - assert(3.0 in s3); -} - -unittest { // Test intersection. - alias DSet = Set!double; - const s = DSet(x => 0.0 <= x && x < 2.0).intersection( - DSet(x => 1.0 < x && x <= 2.0)); - assert(0.0 !in s); - assert(1.0 !in s); - assert(2.0 !in s); -} - -void main() {} diff --git a/Task/Set-of-real-numbers/D/set-of-real-numbers-2.d b/Task/Set-of-real-numbers/D/set-of-real-numbers-2.d deleted file mode 100644 index cb318a8e5a..0000000000 --- a/Task/Set-of-real-numbers/D/set-of-real-numbers-2.d +++ /dev/null @@ -1,100 +0,0 @@ -procedure main(A) - s1 := RealSet("(0,1]").union(RealSet("[0,2)")) - s2 := RealSet("[0,2)").intersect(RealSet("(1,2)")) - s3 := RealSet("[0,3)").difference(RealSet("(0,1)")) - s4 := RealSet("[0,3)").difference(RealSet("[0,1]")) - every s := s1|s2|s3|s4 do { - every n := 0 to 2 do - write(s.toString(),if s.contains(n) then " contains " - else " doesn't contain ",n) - write() - } -end - -class Range(a,b,lbnd,rbnd,ltest,rtest) - - method contains(x); return ((ltest(a,x),rtest(x,b)),self); end - method toString(); return lbnd||a||","||b||rbnd; end - method notEmpty(); return (ltest(a,b),rtest(a,b),self); end - method makeLTest(); return proc(if lbnd == "(" then "<" else "<=",2); end - method makeRTest(); return proc(if rbnd == "(" then "<" else "<=",2); end - - method intersect(r) - if a < r.a then (na := r.a, nlb := r.lbnd) - else if a > r.a then (na := a, nlb := lbnd) - else (na := a, nlb := if "(" == (lbnd|r.lbnd) then "(" else "[") - if b < r.b then ( nb := b, nrb := rbnd) - else if b > r.b then (nb := r.b, nrb := r.rbnd) - else (nb := b, nrb := if ")" == (rbnd|r.rbnd) then ")" else "]") - range := Range(nlb||na||","||nb||nrb) - return range - end - - method difference(r) - if /r then return RealSet(toString()) - r1 := lbnd||a||","||min(b,r.a)||map(r.lbnd,"([","])") - r2 := map(r.rbnd,")]","[(")||max(a,r.b)||","||b||rbnd - return RealSet(r1).union(RealSet(r2)) - end - -initially(s) - static lbnds, rbnds - initial (lbnds := '([', rbnds := '])') - if \s then { - s ? { - lbnd := (tab(upto(lbnds)),move(1)) - a := 1(tab(upto(',')),move(1)) - b := tab(upto(rbnds)) - rbnd := move(1) - } - ltest := proc(if lbnd == "(" then "<" else "<=",2) - rtest := proc(if rbnd == ")" then "<" else "<=",2) - } -end - -class RealSet(ranges) - - method contains(x); return ((!ranges).contains(x), self); end - method notEmpty(); return ((!ranges).notEmpty(), self); end - - method toString() - sep := s := "" - every r := (!ranges).toString() do s ||:= .sep || 1(r, sep := " + ") - return s - end - - method clone() - newR := RealSet() - newR.ranges := (copy(\ranges) | []) - return newR - end - - method union(B) - newR := clone() - every put(newR.ranges, (!B.ranges).notEmpty()) - return newR - end - - method intersect(B) - newR := clone() - newR.ranges := [] - every (r1 := !ranges, r2 := !B.ranges) do { - range := r1.intersect(r2) - put(newR.ranges, range.notEmpty()) - } - return newR - end - - method difference(B) - newR := clone() - newR.ranges := [] - every (r1 := !ranges, r2 := !B.ranges) do { - rs := r1.difference(r2) - if rs.notEmpty() then every put(newR.ranges, !rs.ranges) - } - return newR - end - -initially(s) - put(ranges := [],Range(\s).notEmpty()) -end 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 80bc24e392..f8709d20e0 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 @@ -1,38 +1,37 @@ -#import system. -#import extensions. +import extensions. -#class(extension)setOp +extension setOp { - #method union : func - = val [ self eval:val || func eval:val ]. + union : func + = (:val)( self eval:val || func eval:val ). - #method intersection : func - = val [ self eval:val && func eval:val ]. + intersection : func + = (:val)( self eval:val && func eval:val ). - #method difference : func - = val [ self eval:val && func eval:val not ]. + difference : func + = (:val)( self eval:val && func eval:val; not ). } -#symbol program = +program = [ // union - #var set := x [ (x >= 0.0r) && (x <= 1.0r) ] union: x [ (x >= 0.0r) && (x < 2.0r) ]. + var set := (:x)( (x >= 0.0r) && (x <= 1.0r) ) union(:x)( (x >= 0.0r) && (x < 2.0r) ). - set eval:0.0r assert &ifTrue. - set eval:1.0r assert &ifTrue. - set eval:2.0r assert &ifFalse. + set eval:0.0r; assertTrue. + set eval:1.0r; assertTrue. + set eval:2.0r; assertFalse. // intersection - #var set2 := x [ (x >= 0.0r) && (x < 2.0r) ] intersection: x [ (x >= 1.0r) && (x <= 2.0r) ]. + var set2 := (:x)( (x >= 0.0r) && (x < 2.0r) ) intersection(:x)( (x >= 1.0r) && (x <= 2.0r) ). - set2 eval:0.0r assert &ifFalse. - set2 eval:1.0r assert &ifTrue. - set2 eval:2.0r assert &ifFalse. + set2 eval:0.0r; assertFalse. + set2 eval:1.0r; assertTrue. + set2 eval:2.0r; assertFalse. // difference - #var set3 := x [ (x >= 0.0r) && (x < 3.0r) ] difference: x [ (x >= 0.0r) && (x <= 1.0r) ]. + var set3 := (:x)( (x >= 0.0r) && (x < 3.0r) ) difference(:x) ( (x >= 0.0r) && (x <= 1.0r) ). - set3 eval:0.0r assert &ifFalse. - set3 eval:1.0r assert &ifFalse. - set3 eval:2.0r assert &ifTrue. + set3 eval:0.0r; assertFalse. + set3 eval:1.0r; assertFalse. + set3 eval:2.0r; assertTrue. ]. 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.kotlin new file mode 100644 index 0000000000..ec10427f94 --- /dev/null +++ b/Task/Set-of-real-numbers/Kotlin/set-of-real-numbers.kotlin @@ -0,0 +1,77 @@ +// version 1.1.4-3 + +typealias RealPredicate = (Double) -> Boolean + +enum class RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN } + +class RealSet(val low: Double, val high: Double, val predicate: RealPredicate) { + + constructor (start: Double, end: Double, rangeType: RangeType): this(start, end, + when (rangeType) { + RangeType.CLOSED -> fun(d: Double) = d in start..end + RangeType.BOTH_OPEN -> fun(d: Double) = start < d && d < end + RangeType.LEFT_OPEN -> fun(d: Double) = start < d && d <= end + RangeType.RIGHT_OPEN -> fun(d: Double) = start <= d && d < end + } + ) + + fun contains(d: Double) = predicate(d) + + infix fun union(other: RealSet): RealSet { + val low2 = minOf(low, other.low) + val high2 = maxOf(high, other.high) + return RealSet(low2, high2) { predicate(it) || other.predicate(it) } + } + + infix fun intersect(other: RealSet): RealSet { + val low2 = maxOf(low, other.low) + val high2 = minOf(high, other.high) + return RealSet(low2, high2) { predicate(it) && other.predicate(it) } + } + + infix fun subtract(other: RealSet) = RealSet(low, high) { predicate(it) && !other.predicate(it) } + + var interval = 0.00001 + + val length: Double get() { + if (!low.isFinite() || !high.isFinite()) return -1.0 // error value + if (high <= low) return 0.0 + var p = low + var count = 0 + do { + if (predicate(p)) count++ + p += interval + } + while (p < high) + return count * interval + } + + fun isEmpty() = if (high == low) !predicate(low) else length == 0.0 +} + +fun main(args: Array<String>) { + val a = RealSet(0.0, 1.0, RangeType.LEFT_OPEN) + val b = RealSet(0.0, 2.0, RangeType.RIGHT_OPEN) + val c = RealSet(1.0, 2.0, RangeType.LEFT_OPEN) + val d = RealSet(0.0, 3.0, RangeType.RIGHT_OPEN) + val e = RealSet(0.0, 1.0, RangeType.BOTH_OPEN) + val f = RealSet(0.0, 1.0, RangeType.CLOSED) + val g = RealSet(0.0, 0.0, RangeType.CLOSED) + + for (i in 0..2) { + val dd = i.toDouble() + println("(0, 1] ∪ [0, 2) contains $i is ${(a union b).contains(dd)}") + println("[0, 2) ∩ (1, 2] contains $i is ${(b intersect c).contains(dd)}") + println("[0, 3) − (0, 1) contains $i is ${(d subtract e).contains(dd)}") + println("[0, 3) − [0, 1] contains $i is ${(d subtract f).contains(dd)}\n") + } + + println("[0, 0] is empty is ${g.isEmpty()}\n") + + val aa = RealSet(0.0, 10.0) { x -> (0.0 < x && x < 10.0) && + Math.abs(Math.sin(Math.PI * x * x)) > 0.5 } + val bb = RealSet(0.0, 10.0) { x -> (0.0 < x && x < 10.0) && + Math.abs(Math.sin(Math.PI * x)) > 0.5 } + val cc = aa subtract bb + println("Approx length of A - B is ${cc.length}") +} diff --git a/Task/Set-of-real-numbers/PARI-GP/set-of-real-numbers.pari b/Task/Set-of-real-numbers/PARI-GP/set-of-real-numbers.pari new file mode 100644 index 0000000000..6407e8fd93 --- /dev/null +++ b/Task/Set-of-real-numbers/PARI-GP/set-of-real-numbers.pari @@ -0,0 +1,11 @@ +set11(x,a,b)=select(x -> a <= x && x <= b, x); +set01(x,a,b)=select(x -> a < x && x <= b, x); +set10(x,a,b)=select(x -> a <= x && x < b, x); +set00(x,a,b)=select(x -> a < x && x < b, x); + +V = [0, 1, 2]; + + setunion(set01(V, 0, 1), set10(V, 0, 2)) +setintersect(set10(V, 0, 2), set01(V, 1, 2)) + setminus(set10(V, 0, 3), set00(V, 0, 1)) + setminus(set10(V, 0, 3), set11(V, 0, 1)) diff --git a/Task/Set-of-real-numbers/Zkl/set-of-real-numbers-1.zkl b/Task/Set-of-real-numbers/Zkl/set-of-real-numbers-1.zkl new file mode 100644 index 0000000000..56e898f760 --- /dev/null +++ b/Task/Set-of-real-numbers/Zkl/set-of-real-numbers-1.zkl @@ -0,0 +1,7 @@ +class RealSet{ + fcn init(fx){ var [const] contains=fx; } + fcn holds(x){ contains(x) } + fcn __opAdd(rs){ RealSet('wrap(x){ contains(x) or rs.contains(x) }) } + fcn __opSub(rs){ RealSet('wrap(x){ contains(x) and not rs.contains(x) }) } + fcn intersection(rs) { RealSet('wrap(x){ contains(x) and rs.contains(x) }) } +} diff --git a/Task/Set-of-real-numbers/Zkl/set-of-real-numbers-2.zkl b/Task/Set-of-real-numbers/Zkl/set-of-real-numbers-2.zkl new file mode 100644 index 0000000000..99522c89a1 --- /dev/null +++ b/Task/Set-of-real-numbers/Zkl/set-of-real-numbers-2.zkl @@ -0,0 +1,29 @@ +tester := TheVault.Test.UnitTester.UnitTester(); + + // test union +s:=RealSet(fcn(x){ 0.0 < x <= 1.0 }) + + RealSet(fcn(x){ 0.0 <= x < 1.0 }); +tester.testRun(s.holds(0.0),Void,True,__LINE__); +tester.testRun(s.holds(1.0),Void,True,__LINE__); +tester.testRun(s.holds(2.0),Void,False,__LINE__); + + // test difference +s1 := RealSet(fcn(x){ 0.0 <= x < 3.0 }) - + RealSet(fcn(x){ 0.0 < x < 1.0 }); +tester.testRun(s1.holds(0.0),Void,True,__LINE__); +tester.testRun(s1.holds(0.5),Void,False,__LINE__); +tester.testRun(s1.holds(1.0),Void,True,__LINE__); +tester.testRun(s1.holds(2.0),Void,True,__LINE__); + +s2 := RealSet(fcn(x){ 0.0 <= x < 3.0 }) - + RealSet(fcn(x){ 0.0 <= x <= 1.0 }); +tester.testRun(s2.holds(0.0),Void,False,__LINE__); +tester.testRun(s2.holds(1.0),Void,False,__LINE__); +tester.testRun(s2.holds(2.0),Void,True,__LINE__); + + // test intersection +s := RealSet(fcn(x){ 0.0 <= x < 2.0 }).intersection( + RealSet(fcn(x){ 1.0 < x <= 2.0 })); +tester.testRun(s.holds(0.0),Void,False,__LINE__); +tester.testRun(s.holds(1.0),Void,False,__LINE__); +tester.testRun(s.holds(2.0),Void,False,__LINE__); diff --git a/Task/Set-puzzle/Ceylon/set-puzzle.ceylon b/Task/Set-puzzle/Ceylon/set-puzzle.ceylon new file mode 100644 index 0000000000..44922204fb --- /dev/null +++ b/Task/Set-puzzle/Ceylon/set-puzzle.ceylon @@ -0,0 +1,140 @@ +import ceylon.random { + Random, + DefaultRandom +} + +abstract class Feature() of Color | Symbol | NumberOfSymbols | Shading {} + +abstract class Color() + of red | green | purple + extends Feature() {} +object red extends Color() { + string => "red"; +} +object green extends Color() { + string => "green"; +} +object purple extends Color() { + string => "purple"; +} + +abstract class Symbol() + of oval | squiggle | diamond + extends Feature() {} +object oval extends Symbol() { + string => "oval"; +} +object squiggle extends Symbol() { + string => "squiggle"; +} +object diamond extends Symbol() { + string => "diamond"; +} + +abstract class NumberOfSymbols() + of one | two | three + extends Feature() {} +object one extends NumberOfSymbols() { + string => "one"; +} +object two extends NumberOfSymbols() { + string => "two"; +} +object three extends NumberOfSymbols() { + string => "three"; +} + +abstract class Shading() + of solid | open | striped + extends Feature() {} +object solid extends Shading() { + string => "solid"; +} +object open extends Shading() { + string => "open"; +} +object striped extends Shading() { + string => "striped"; +} + +class Card(color, symbol, number, shading) { + shared Color color; + shared Symbol symbol; + shared NumberOfSymbols number; + shared Shading shading; + + value plural => number == one then "" else "s"; + string => "``number`` ``shading`` ``color`` ``symbol````plural``"; +} + +{Card*} deck = { + for(color in `Color`.caseValues) + for(symbol in `Symbol`.caseValues) + for(number in `NumberOfSymbols`.caseValues) + for(shading in `Shading`.caseValues) + Card(color, symbol, number, shading) +}; + +alias CardSet => [Card+]; + +Boolean validSet(CardSet cards) { + + function allOrOne({Feature*} features) => + let(uniques = features.distinct.size) + uniques == 3 || uniques == 1; + + return allOrOne(cards*.color) && + allOrOne(cards*.number) && + allOrOne(cards*.shading) && + allOrOne(cards*.symbol); +} + +{CardSet*} findSets(Card* cards) => + cards + .sequence() + .combinations(3) + .filter(validSet); + +Random random = DefaultRandom(); + +class Mode of basic | advanced { + + shared Integer numberOfCards; + shared Integer numberOfSets; + + shared new basic { + numberOfCards = 9; + numberOfSets = 4; + } + + shared new advanced { + numberOfCards = 12; + numberOfSets = 6; + } +} + +[{Card*}, {CardSet*}] deal(Mode mode) { + value randomStream = random.elements(deck); + while(true) { + value cards = randomStream.distinct.take(mode.numberOfCards).sequence(); + value sets = findSets(*cards); + if(sets.size == mode.numberOfSets) { + return [cards, sets]; + } + } +} + +shared void run() { + value [cards, sets] = deal(Mode.basic); + print("The cards dealt are: + "); + cards.each(print); + print(" + Containing the sets: + "); + for(cardSet in sets) { + cardSet.each(print); + print(""); + } + +} diff --git a/Task/Set-puzzle/Kotlin/set-puzzle.kotlin b/Task/Set-puzzle/Kotlin/set-puzzle.kotlin new file mode 100644 index 0000000000..2804e1f7ac --- /dev/null +++ b/Task/Set-puzzle/Kotlin/set-puzzle.kotlin @@ -0,0 +1,89 @@ +// version 1.1.3 + +import java.util.Collections.shuffle + +enum class Color { RED, GREEN, PURPLE } +enum class Symbol { OVAL, SQUIGGLE, DIAMOND } +enum class Number { ONE, TWO, THREE } +enum class Shading { SOLID, OPEN, STRIPED } +enum class Degree { BASIC, ADVANCED } + +class Card( + val color: Color, + val symbol: Symbol, + val number: Number, + val shading: Shading +) : Comparable<Card> { + + private val value = + color.ordinal * 27 + symbol.ordinal * 9 + number.ordinal * 3 + shading.ordinal + + override fun compareTo(other: Card) = value.compareTo(other.value) + + override fun toString() = ( + color.name.padEnd(8) + + symbol.name.padEnd(10) + + number.name.padEnd(7) + + shading.name.padEnd(7) + ).toLowerCase() + + companion object { + val zero = Card(Color.RED, Symbol.OVAL, Number.ONE, Shading.SOLID) + } +} + +fun createDeck() = + List<Card>(81) { + val col = Color.values() [it / 27] + val sym = Symbol.values() [it / 9 % 3] + val num = Number.values() [it / 3 % 3] + val shd = Shading.values()[it % 3] + Card(col, sym, num, shd) + } + +fun playGame(degree: Degree) { + val deck = createDeck() + val nCards = if (degree == Degree.BASIC) 9 else 12 + val nSets = nCards / 2 + val sets = Array(nSets) { Array(3) { Card.zero } } + var hand: Array<Card> + outer@ while (true) { + shuffle(deck) + hand = deck.take(nCards).toTypedArray() + var count = 0 + for (i in 0 until hand.size - 2) { + for (j in i + 1 until hand.size - 1) { + for (k in j + 1 until hand.size) { + val trio = arrayOf(hand[i], hand[j], hand[k]) + if (isSet(trio)) { + sets[count++] = trio + if (count == nSets) break@outer + } + } + } + } + } + hand.sort() + println("DEALT $nCards CARDS:\n") + println(hand.joinToString("\n")) + println("\nCONTAINING $nSets SETS:\n") + for (s in sets) { + s.sort() + println(s.joinToString("\n")) + println() + } +} + +fun isSet(trio: Array<Card>): Boolean { + val r1 = trio.sumBy { it.color.ordinal } % 3 + val r2 = trio.sumBy { it.symbol.ordinal } % 3 + val r3 = trio.sumBy { it.number.ordinal } % 3 + val r4 = trio.sumBy { it.shading.ordinal } % 3 + return (r1 + r2 + r3 + r4) == 0 +} + +fun main(args: Array<String>) { + playGame(Degree.BASIC) + println() + playGame(Degree.ADVANCED) +} diff --git a/Task/Set-puzzle/Perl-6/set-puzzle.pl6 b/Task/Set-puzzle/Perl-6/set-puzzle.pl6 index 9681dfaeaa..ad091151d9 100644 --- a/Task/Set-puzzle/Perl-6/set-puzzle.pl6 +++ b/Task/Set-puzzle/Perl-6/set-puzzle.pl6 @@ -3,10 +3,10 @@ enum Count (one => 0o100, two => 0o200, three => 0o400); enum Shape (oval => 0o10, squiggle => 0o20, diamond => 0o40); enum Style (solid => 0o1, open => 0o2, striped => 0o4); -my @deck := (Color.enums X Count.enums X Shape.enums X Style.enums).tree; +my @deck = Color.enums X Count.enums X Shape.enums X Style.enums; sub MAIN($DRAW = 9, $GOAL = $DRAW div 2) { - sub show-cards(@c) { printf " %-6s %-5s %-8s %s\n", $_».key for @c } + sub show-cards(@c) { { printf "%9s%7s%10s%9s\n", @c[$_;*]».key } for ^@c } my @combinations = [^$DRAW].combinations(3); diff --git a/Task/Set-puzzle/Phix/set-puzzle.phix b/Task/Set-puzzle/Phix/set-puzzle.phix new file mode 100644 index 0000000000..952b488893 --- /dev/null +++ b/Task/Set-puzzle/Phix/set-puzzle.phix @@ -0,0 +1,66 @@ +function comb(sequence pool, integer needed, sequence res={}, integer done=0, sequence chosen={}) + if needed=0 then -- got a full set + sequence {a,b,c} = chosen + if not find_any({3,5,6},flatten(sq_or_bits(sq_or_bits(a,b),c))) then + res = append(res,chosen) + end if + elsif done+needed<=length(pool) then + -- get all combinations with and without the next item: + done += 1 + res = comb(pool,needed-1,res,done,append(chosen,pool[done])) + res = comb(pool,needed,res,done,chosen) + end if + return res +end function + +constant m124 = {1,2,4} + +function card(integer n) +--returns the nth card (n is 1..81, res is length 4 of 1/2/4) + n -= 1 + sequence res = repeat(0,4) + for i=1 to 4 do + res[i] = m124[remainder(n,3)+1] + n = floor(n/3) + end for + return res +end function + +constant colours = {"red", "green", 0, "purple"}, + symbols = {"oval", "squiggle", 0, "diamond"}, + numbers = {"one", "two", 0, "three"}, + shades = {"solid", "open", 0, "striped"} + +procedure print_cards(sequence hand, sequence cards) + for i=1 to length(cards) do + integer {c,m,n,g} = cards[i], + id = find(cards[i],hand) + printf(1,"%3d: %-7s %-9s %-6s %s\n",{id,colours[c],symbols[m],numbers[n],shades[g]}) + end for + printf(1,"\n") +end procedure + +procedure play(integer cards=9, integer sets=4) + integer deals = 1 + while 1 do + sequence deck = shuffle(tagset(81)) + sequence hand = deck[1..cards] + for i=1 to length(hand) do + hand[i] = card(hand[i]) + end for + sequence res = comb(hand,3) + if length(res)=sets then + printf(1,"dealt %d cards (%d deals)\n",{cards,deals}) + print_cards(hand,hand) + printf(1,"with %d sets\n",{sets}) + for i=1 to sets do + print_cards(hand,res[i]) + end for + exit + end if + deals += 1 + end while +end procedure +play() +--play(12,6) +--play(9,6) diff --git a/Task/Set-puzzle/Zkl/set-puzzle.zkl b/Task/Set-puzzle/Zkl/set-puzzle.zkl new file mode 100644 index 0000000000..eaac300d28 --- /dev/null +++ b/Task/Set-puzzle/Zkl/set-puzzle.zkl @@ -0,0 +1,22 @@ +const nDraw=9, nGoal=(nDraw/2); // Basic +var [const] UH=Utils.Helpers; // baked in stash of goodies +deck:=Walker.cproduct("red green purple".split(), // Cartesian product of 4 lists of lists + "one two three".split(), // T(1,2,3) (ie numbers) also works + "oval squiggle diamond".split(), + "solid open striped".split()).walk(); +reg draw,sets,N=0; +do{ N+=1; + draw=deck.shuffle()[0,nDraw]; // one draw per shuffle + sets=UH.pickNFrom(3,draw) // 84 sets of 3 cards (each with 4 features) + .filter(fcn(set){ // list of 12 items (== 3 cards) + set[0,4].zip(set[4,4],set[8,4]) // -->4 tuples of 3 features + .pump(List,UH.listUnique,"len", // 1,3 (good) or 2 (bad) + '==(2)) // (F,F,F,F)==good + .sum(0) == 0 // all 4 feature sets good + }); +}while(sets.len()!=nGoal); + +println("Dealt %d cards %d times:".fmt(draw.len(),N)); +draw.pump(Void,fcn(card){ println(("%8s "*4).fmt(card.xplode())) }); +println("\nContaining:"); +sets.pump(Void,fcn(card){ println((("%8s "*4 + "\n")*3).fmt(card.xplode())) }); diff --git a/Task/Set/Aime/set.aime b/Task/Set/Aime/set.aime new file mode 100644 index 0000000000..84d6415f8d --- /dev/null +++ b/Task/Set/Aime/set.aime @@ -0,0 +1,81 @@ +record +union(record a, record b) +{ + record c; + r_copy(c, a); + r_wcall(b, r_add, 1, 2, c); + return c; +} + +record +intersection(record a, record b) +{ + record c; + text s; + for (s in a) { + if (r_key(b, s)) { + c[s] = 0; + } + } + return c; +} + +record +difference(record a, record b) +{ + record c; + r_copy(c, a); + r_vcall(b, r_resign, 1, c); + return c; +} + +integer +subset(record a, record b) +{ + integer e; + text s; + e = 1; + for (s in a) { + if (!r_key(b, s)) { + e = 0; + break; + } + } + return e; +} + +integer +equal(record a, record b) +{ + return subset(a, b) && subset(b, a); +} + +integer +main(void) +{ + record a, b; + text s; + + r_fit(a, "apple", 0, "cherry", 0, "grape", 0); + r_fit(b, "banana", 0, "cherry", 0, "date", 0); + + s = "banana"; + + o_(" ", s, " is ", r_key(a, s) ? "" : "not ", "an element of A\n"); + o_(" ", s, " is ", r_key(b, s) ? "" : "not ", "an element of B\n"); + + r_vcall(union(a, b), o_, 1, " "); + o_newline(); + + r_vcall(intersection(a, b), o_, 1, " "); + o_newline(); + + r_vcall(difference(a, b), o_, 1, " "); + o_newline(); + + o_(" ", subset(a, b) ? "yes" : "no", "\n"); + + o_(" ", equal(a, b) ? "yes" : "no", "\n"); + + return 0; +} diff --git a/Task/Set/Ceylon/set.ceylon b/Task/Set/Ceylon/set.ceylon new file mode 100644 index 0000000000..13cae472b5 --- /dev/null +++ b/Task/Set/Ceylon/set.ceylon @@ -0,0 +1,18 @@ +shared void run() { + value a = set {1, 2, 3}; + value b = set {3, 4, 5}; + value union = a | b; + value intersection = a & b; + value difference = a ~ b; + value subset = a.subset(b); + value equality = a == b; + + print("set a: ``a`` + set b: ``b`` + 1 in a? ``1 in a`` + a | b: ``union`` + a & b: ``intersection`` + a ~ b: ``difference`` + a subset of b? ``subset`` + a == b? ``equality``"); +} diff --git a/Task/Set/D/set.d b/Task/Set/D/set.d index 811b877730..493bd41e58 100644 --- a/Task/Set/D/set.d +++ b/Task/Set/D/set.d @@ -1,21 +1,152 @@ -void main() { - import std.stdio, std.algorithm, std.range; +module set; +import std.typecons : Tuple, tuple; +struct Set(V) { // Limited set of V-type elements // here 'this' is named A, s is B, v V-type item - // Not true sets, items can be repeated, but must be sorted. - auto s1 = [1, 2, 3, 4, 5, 6].assumeSorted; - auto s2 = [2, 5, 6, 3, 4, 8].sort(); // [2,3,4,5,6,8]. - auto s3 = [1, 2, 5].assumeSorted; +protected V[] array; - assert(s1.canFind(4)); // Linear search. - assert(s1.contains(4)); // Binary search. - assert(s1.setUnion(s2).equal([1,2,2,3,3,4,4,5,5,6,6,8])); - assert(s1.setIntersection(s2).equal([2, 3, 4, 5, 6])); - assert(s1.setDifference(s2).equal([1])); - assert(s1.setSymmetricDifference(s2).equal([1, 8])); - assert(s3.setDifference(s1).empty); // It's a subset. - assert(!s1.equal(s2)); + this(const Set s) { // construct A by copy of B + array = s.array.dup; + } + + this(V[] arg...){ // construct A with items + foreach(v; arg) if (v.isNotIn(array)) array ~= v; + } + + enum : Set { empty = Set() } // ∅ + + ref Set opAssign()(const Set s) { // A = B + array = s.array.dup; + return this; + } + + bool opBinaryRight(string op : "in")(const V v) const { // v ∈ A + return v.isIn(array); + } + + ref Set opOpAssign(string op)(const V v) if (op == "+" || op == "|") { // A += {v} // + = ∪ = | + if (v.isIn(array)) return this; + array ~= v; + return this; + } + + ref Set opOpAssign(string op)(const Set s) if (op == "+" || op == "|") { // A += B + foreach(x; s.array) if (x.isNotIn(array)) array ~= x; + return this; + } + + Set opBinary(string op)(const V v) const if (op == "+" || op == "|"){ // A + {v} + Set result = this; + result += v; + return result; + } + + Set opBinaryRight(string op)(const V v) const if (op == "+" || op == "|") { // {v} + A + Set result = this; + result += v; + return result; + } + + Set opBinary(string op)(const Set s) const if (op == "+" || op == "|") { // A + B + Set result = this; + result += s; + return result; + } + + Set opBinary(string op : "&")(const Set s) const{ // A ∩ B // ∩ = & + Set result; + foreach(x; array) if(x.isIn(s.array)) result += x; + return result; + } + + ref Set opOpAssign(string op : "&")(const Set s) { // A ∩= B + return this(this & s); + } + + Set opBinary(string op : "^")(const Set s) const { // (A ∪ B) - (A ∩ B) // = A ^ B + Set result; + foreach(x; array) if (x.isNotIn(s.array)) result += x; + foreach(x; s.array) if(x.isNotIn(array)) result += x; + return result; + } + + ref opOpAssign(string op : "^")(const Set s) { + return this = this ^ s; + } + + Set opBinary(string op : "-")(const Set s) const { // A - B + Set r; + foreach(x; array) if(x.isNot(s.array)) r += x; + return r; + } + + ref Set opOpAssign(string op : "-")(const Set s) { // A -= B + return this = this - s; + } + + Set!(Tuple!(V,U)) opBinary(U, string op : "*")(const Set!U s) const { // A × B = { (x, y) | ∀x ∈ A ∧ ∀y ∈ B } + Set!(Tuple!(V, U)) r; + foreach(x; array) foreach(y; s.array) r += tuple(x, y); + return r; + } + + bool isEmpty() const { return !array.length;} // A ≟ ∅ + + bool opBinary(string op : "in")(const Set s) const { // A ⊂ s + foreach(v; array) if(v.isNotIn(s.array)) return false; + return true; + } + + bool opEquals(const Set s) const { // A ≟ B + if (array.length != s.array.length) return false; + return this in s; + } + + T[] array() const @property { return array.dup;} - auto s4 = [[1, 4, 7, 8], [1, 7], [1, 7, 8], [4], [7]]; - const s5 = [1, 1, 1, 4, 4, 7, 7, 7, 7, 8, 8]; - assert(s4.nWayUnion.equal(s5)); +} + +Set!(Tuple!(T, T)) sqr(T)(const Set!T s) { return s * s; } // A² + +auto pow(T, uint n : 0)(const Set!T s) { // A ^ 0 + return Set!T.empty; +} + +auto pow(T, uint n : 1)(const Set!T s) { // A ^ 1 = A + return s; +} + +auto pow(T, uint n : 2)(const Set!T s) { // A ^ 2 (=A²) + return sqr!T(s); +} + +auto pow(T, uint n)(const Set!T s) if(n % 2) { // if n Odd, A^n = A * (A^(n/2))² + return s * sqr!T(pow!(T, n/2)(s)); +} + +auto pow(T, uint n)(const Set!T s) if(!(n % 2)) { // if n Even, A^n = (A^(n/2))² + return sqr!T(pow!(T, n/2)(s)); +} + +size_t Card(T)(const Set!T s) {return s.length; } // Card(A) + +Set!(Set!T) power(T)(Set!T s) { // ∀B ∈ P(A) ⇒ B ⊂ A + Set!(Set!T) ret; + foreach(e; s.array) { + Set!(Set!T) rs; + foreach(x; ret.array) { + x += e; + rs += x; + } + ret += rs; + } + return ret; +} + +bool isIn(T)(T x, T[] array){ + foreach(a; array) if(a == x) return true; + return false; +} +bool isNotIn(T)(T x, T[] array){ + foreachj(a; array) if(a == x) return false; + return true; } diff --git a/Task/Set/jq/set-1.jq b/Task/Set/Jq/set-1.jq similarity index 100% rename from Task/Set/jq/set-1.jq rename to Task/Set/Jq/set-1.jq diff --git a/Task/Set/jq/set-10.jq b/Task/Set/Jq/set-10.jq similarity index 100% rename from Task/Set/jq/set-10.jq rename to Task/Set/Jq/set-10.jq diff --git a/Task/Set/jq/set-11.jq b/Task/Set/Jq/set-11.jq similarity index 100% rename from Task/Set/jq/set-11.jq rename to Task/Set/Jq/set-11.jq diff --git a/Task/Set/jq/set-12.jq b/Task/Set/Jq/set-12.jq similarity index 100% rename from Task/Set/jq/set-12.jq rename to Task/Set/Jq/set-12.jq diff --git a/Task/Set/jq/set-13.jq b/Task/Set/Jq/set-13.jq similarity index 100% rename from Task/Set/jq/set-13.jq rename to Task/Set/Jq/set-13.jq diff --git a/Task/Set/jq/set-2.jq b/Task/Set/Jq/set-2.jq similarity index 100% rename from Task/Set/jq/set-2.jq rename to Task/Set/Jq/set-2.jq diff --git a/Task/Set/jq/set-3.jq b/Task/Set/Jq/set-3.jq similarity index 100% rename from Task/Set/jq/set-3.jq rename to Task/Set/Jq/set-3.jq diff --git a/Task/Set/jq/set-4.jq b/Task/Set/Jq/set-4.jq similarity index 100% rename from Task/Set/jq/set-4.jq rename to Task/Set/Jq/set-4.jq diff --git a/Task/Set/jq/set-5.jq b/Task/Set/Jq/set-5.jq similarity index 100% rename from Task/Set/jq/set-5.jq rename to Task/Set/Jq/set-5.jq diff --git a/Task/Set/jq/set-6.jq b/Task/Set/Jq/set-6.jq similarity index 100% rename from Task/Set/jq/set-6.jq rename to Task/Set/Jq/set-6.jq diff --git a/Task/Set/jq/set-7.jq b/Task/Set/Jq/set-7.jq similarity index 100% rename from Task/Set/jq/set-7.jq rename to Task/Set/Jq/set-7.jq diff --git a/Task/Set/jq/set-8.jq b/Task/Set/Jq/set-8.jq similarity index 100% rename from Task/Set/jq/set-8.jq rename to Task/Set/Jq/set-8.jq diff --git a/Task/Set/jq/set-9.jq b/Task/Set/Jq/set-9.jq similarity index 100% rename from Task/Set/jq/set-9.jq rename to Task/Set/Jq/set-9.jq diff --git a/Task/Set/Kotlin/set.kotlin b/Task/Set/Kotlin/set.kotlin new file mode 100644 index 0000000000..5eb67569a4 --- /dev/null +++ b/Task/Set/Kotlin/set.kotlin @@ -0,0 +1,36 @@ +// version 1.0.6 + +fun main(args: Array<String>) { + val fruits = setOf("apple", "pear", "orange", "banana") + println("fruits : $fruits") + val fruits2 = setOf("melon", "orange", "lemon", "gooseberry") + println("fruits2 : $fruits2\n") + + println("fruits contains 'banana' : ${"banana" in fruits}") + println("fruits2 contains 'elderberry' : ${"elderbury" in fruits2}\n") + + println("Union : ${fruits.union(fruits2)}") + println("Intersection : ${fruits.intersect(fruits2)}") + println("Difference : ${fruits.minus(fruits2)}\n") + + println("fruits2 is a subset of fruits : ${fruits.containsAll(fruits2)}\n") + val fruits3 = fruits + println("fruits3 : $fruits3\n") + var areEqual = fruits.containsAll(fruits2) && fruits3.containsAll(fruits) + println("fruits2 and fruits are equal : $areEqual") + areEqual = fruits.containsAll(fruits3) && fruits3.containsAll(fruits) + println("fruits3 and fruits are equal : $areEqual\n") + + val fruits4 = setOf("apple", "orange") + println("fruits4 : $fruits4\n") + var isProperSubset = fruits.containsAll(fruits3) && !fruits3.containsAll(fruits) + println("fruits3 is a proper subset of fruits : $isProperSubset") + isProperSubset = fruits.containsAll(fruits4) && !fruits4.containsAll(fruits) + println("fruits4 is a proper subset of fruits : $isProperSubset\n") + + val fruits5 = mutableSetOf("cherry", "blueberry", "raspberry") + println("fruits5 : $fruits5\n") + fruits5 += "guava" + println("fruits5 + 'guava' : $fruits5") + println("fruits5 - 'cherry' : ${fruits5 - "cherry"}") +} diff --git a/Task/Set/OoRexx/set.rexx b/Task/Set/OoRexx/set.rexx new file mode 100644 index 0000000000..186a22a641 --- /dev/null +++ b/Task/Set/OoRexx/set.rexx @@ -0,0 +1,32 @@ +-- Set creation +-- Using the OF method +s1 = .set~of(1, 2, 3, 4, 5, 6) +-- Explicit addition of individual items +s2 = .set~new +s2~put(2) +s2~put(4) +s2~put(6) +-- group addition +s3 = .set~new +s3~putall(.array~of(1, 3, 5)) +-- Test m ? S -- "m is an element in set S" +say s1~hasindex(1) s3~hasindex(2) -- "1 0", which is "true" and "false" +-- A ? B -- union; a set of all elements either in set A or in set B. +s4 = s2~union(s3) -- {1, 2, 3, 4, 5, 6} +Call show 's4',s4 +-- A ? B -- intersection; a set of all elements in both set A and set B. +s5 = s1~intersection(s2) -- {2, 4, 6} +Call show 's5',s5 +-- A ? B -- difference; a set of all elements in set A, except those in set B. +s6 = s1~difference(s2) -- {1, 3, 5} +Call show 's6',s6 +-- A ? B -- subset; true if every element in set A is also in set B. +say s1~subset(s2) s2~subset(s1) -- "0 1" +-- A = B -- equality; true if every element of set A is in set B and vice-versa. +-- No direct equivalence method, but the XOR method can be used to determine this +say s1~xor(s4)~isempty -- true +Exit +show: Procedure + Use Arg set_name,set + Say set_name':' set~makearray~makestring((LINE),',') + return diff --git a/Task/Set/Phix/set-1.phix b/Task/Set/Phix/set-1.phix new file mode 100644 index 0000000000..70736f0de8 --- /dev/null +++ b/Task/Set/Phix/set-1.phix @@ -0,0 +1,62 @@ +sequence set1 = {1,2,3}, + set2 = {3,4,5} + +function element(object x, sequence set) + return find(x,set)!=0 +end function + +function union(sequence set1, sequence set2) + for i=1 to length(set2) do + if not element(set2[i],set1) then + set1 = append(set1,set2[i]) + end if + end for + return set1 +end function + +function intersection(sequence set1, sequence set2) +sequence res = {} + for i=1 to length(set1) do + if element(set1[i],set2) then + res = append(res,set1[i]) + end if + end for + return res +end function + +function difference(sequence set1, sequence set2) +sequence res = {} + for i=1 to length(set1) do + if not element(set1[i],set2) then + res = append(res,set1[i]) + end if + end for + return res +end function + +function subset(sequence set1, sequence set2) + for i=1 to length(set1) do + if not element(set1[i],set2) then + return false + end if + end for + return true +end function + +function equality(sequence set1, sequence set2) + if length(set1)!=length(set2) then + return false + end if + return subset(set1,set2) +end function + +--test code: +?element(3,set1) -- 1 +?element(4,set1) -- 0 +?union(set1,set2) -- {1,2,3,4,5} +?intersection(set1,set2) -- {3} +?difference(set1,set2) -- {1,2} +?subset(set1,set2) -- 0 +?subset({1,2},set1) -- 1 +?equality(set1,set2) -- 0 +?equality(set1,{3,1,2}) -- 1 diff --git a/Task/Set/Phix/set-2.phix b/Task/Set/Phix/set-2.phix new file mode 100644 index 0000000000..e1cd070c38 --- /dev/null +++ b/Task/Set/Phix/set-2.phix @@ -0,0 +1,96 @@ +integer set1 = new_dict(), + set2 = new_dict() +setd(3,0,set1) +setd(1,0,set1) +setd(2,0,set1) +setd(5,0,set2) +setd(3,0,set2) +setd(4,0,set2) + +function element(object x, integer set) + return getd_index(x,set)!=0 +end function + +function u_visitor(object key, object data, object user_data) + integer {union_set,set2} = user_data + if set2=0 + or not element(key,union_set) then + setd(key,data,union_set) + end if + return 1 +end function + +function union(integer set1, integer set2) +integer union_set = new_dict() + traverse_dict(routine_id("u_visitor"),{union_set,0},set1) + traverse_dict(routine_id("u_visitor"),{union_set,set2},set2) + return union_set +end function + +function i_visitor(object key, object data, object user_data) + integer {union_set,set2} = user_data + if element(key,set2) then + setd(key,data,union_set) + end if + return 1 +end function + +function intersection(integer set1, integer set2) +integer union_set = new_dict() + traverse_dict(routine_id("i_visitor"),{union_set,set2},set1) + return union_set +end function + +function d_visitor(object key, object data, object user_data) + integer {union_set,set2} = user_data + if not element(key,set2) then + setd(key,data,union_set) + end if + return 1 +end function + +function difference(integer set1, integer set2) +integer union_set = new_dict() + traverse_dict(routine_id("d_visitor"),{union_set,set2},set1) + return union_set +end function + +integer res +function s_visitor(object key, object data, object user_data) + integer set2 = user_data + if not element(key,set2) then + res = 0 + return 0 -- cease traversal + end if + return 1 +end function + +function subset(integer set1, integer set2) + res = 1 + traverse_dict(routine_id("s_visitor"),set2,set1) + return res +end function + +function equality(integer set1, integer set2) + if dict_size(set1)!=dict_size(set2) then + return false + end if + return subset(set1,set2) +end function + +include builtins/map.e -- for keys() + +-- matching test code: +?element(3,set1) -- 1 +?element(4,set1) -- 0 +?keys(union(set1,set2)) -- {1,2,3,4,5} +?keys(intersection(set1,set2)) -- {3} +?keys(difference(set1,set2)) -- {1,2} +?subset(set1,set2) -- 0 +integer set3 = new_dict() +setd(2,0,set3) +setd(1,0,set3) +?subset(set3,set1) -- 1 +?equality(set1,set2) -- 0 +setd(3,0,set3) +?equality(set1,set3) -- 1 diff --git a/Task/Set/PowerShell/set.psh b/Task/Set/PowerShell/set.psh new file mode 100644 index 0000000000..ace34a32c6 --- /dev/null +++ b/Task/Set/PowerShell/set.psh @@ -0,0 +1,17 @@ +[System.Collections.Generic.HashSet[object]]$set1 = 1..4 +[System.Collections.Generic.HashSet[object]]$set2 = 3..6 + +# Operation + Definition + Result +#--------------------------------+---------------------+------------------------- +$set1.UnionWith($set2) # Union $set1 = 1, 2, 3, 4, 5, 6 +$set1.IntersectWith($set2) # Intersection $set1 = 3, 4 +$set1.ExceptWith($set2) # Difference $set1 = 1, 2 +$set1.SymmetricExceptWith($set2) # Symmetric difference $set1 = 1, 2, 6, 5 +$set1.IsSupersetOf($set2) # Test superset False +$set1.IsSubsetOf($set2) # Test subset False +$set1.Equals($set2) # Test equality False +$set1.IsProperSupersetOf($set2) # Test proper superset False +$set1.IsProperSubsetOf($set2) # Test proper subset False + +5 -in $set1 # Test membership False +7 -notin $set1 # Test non-membership True diff --git a/Task/Set/SQL/set.sql b/Task/Set/SQL/set.sql new file mode 100644 index 0000000000..2bd83ff9cf --- /dev/null +++ b/Task/Set/SQL/set.sql @@ -0,0 +1,83 @@ +-- set of numbers is a table +-- create one set with 3 elements + +create table myset1 (element number); + +insert into myset1 values (1); +insert into myset1 values (2); +insert into myset1 values (3); + +commit; + +-- check if 1 is an element + +select 'TRUE' BOOL from dual +where 1 in +(select element from myset1); + +-- create second set with 3 elements + +create table myset2 (element number); + +insert into myset2 values (1); +insert into myset2 values (5); +insert into myset2 values (6); + +commit; + +-- union sets + +select element from myset1 +union +select element from myset2; + +-- intersection + +select element from myset1 +intersect +select element from myset2; + +-- difference + +select element from myset1 +minus +select element from myset2; + +-- subset + +-- change myset2 to only have 1 as element + +delete from myset2 where not element = 1; + +commit; + +-- check if myset2 subset of myset1 + +select 'TRUE' BOOL from dual +where 0 = (select count(*) from +(select element from myset2 +minus +select element from myset1)); + +-- equality + +-- change myset1 to only have 1 as element + +delete from myset1 where not element = 1; + +commit; + + -- check if myset2 subset of myset1 and + -- check if myset1 subset of myset2 and + +select 'TRUE' BOOL from dual +where +0 = (select count(*) from +(select element from myset2 +minus +select element from myset1)) and +0 = +(select count(*) from +(select element from myset1 +minus +select element from myset2)); diff --git a/Task/Set/Simula/set.simula b/Task/Set/Simula/set.simula new file mode 100644 index 0000000000..1af7700e87 --- /dev/null +++ b/Task/Set/Simula/set.simula @@ -0,0 +1,202 @@ +SIMSET +BEGIN + + ! WE DON'T SUBCLASS HEAD BUT USE COMPOSITION FOR CLASS SET ; + CLASS SET; + BEGIN + PROCEDURE ADD(E); REF(ELEMENT) E; + BEGIN + IF NOT ISIN(E, THIS SET) THEN E.CLONE.INTO(H); + END**OF**ADD; + + BOOLEAN PROCEDURE EMPTY; EMPTY := H.EMPTY; + REF(LINK) PROCEDURE FIRST; FIRST :- H.FIRST; + + REF(HEAD) H; + H :- NEW HEAD; + END**OF**SET; + + ! WE SUBCLASS LINK FOR THE ELEMENTS CONTAINED IN THE SET ; + LINK CLASS ELEMENT; + VIRTUAL: + PROCEDURE ISEQUAL IS + BOOLEAN PROCEDURE ISEQUAL(OTHER); REF(ELEMENT) OTHER;; + PROCEDURE REPR IS + TEXT PROCEDURE REPR;; + PROCEDURE REPR IS + REF(ELEMENT) PROCEDURE CLONE;; + BEGIN + END**OF**ELEMENT; + + REF(SET) PROCEDURE UNION(S1, S2); REF(SET) S1, S2; + BEGIN REF(SET) SU, S; + SU :- NEW SET; + FOR S :- S1, S2 DO + BEGIN + IF NOT S.EMPTY THEN + BEGIN REF(ELEMENT) E; + E :- S.FIRST; + WHILE E =/= NONE DO + BEGIN SU.ADD(E); E :- E.SUC; + END; + END; + END; + UNION :- SU; + END**OF**UNION; + + REF(SET) PROCEDURE INTERSECTION(S1, S2); REF(SET) S1, S2; + BEGIN REF(SET) SI; + SI :- NEW SET; + IF NOT S1.EMPTY THEN + BEGIN REF(ELEMENT) E; + E :- S1.FIRST; + WHILE E =/= NONE DO + BEGIN IF ISIN(E, S2) THEN SI.ADD(E); E :- E.SUC; + END; + END; + INTERSECTION :- SI; + END**OF**INTERSECTION; + + REF(SET) PROCEDURE MINUS(S1, S2); REF(SET) S1, S2; + BEGIN REF(SET) SM; + SM :- NEW SET; + IF NOT S1.EMPTY THEN + BEGIN REF(ELEMENT) E; + E :- S1.FIRST; + WHILE E =/= NONE DO + BEGIN IF NOT ISIN(E, S2) THEN SM.ADD(E); E :- E.SUC; + END; + END; + MINUS :- SM; + END**OF**MINUS; + + BOOLEAN PROCEDURE ISSUBSET(S1, S2); REF(SET) S1, S2; + BEGIN BOOLEAN B; + B := TRUE; + IF NOT S1.EMPTY THEN + BEGIN REF(ELEMENT) E; + E :- S1.FIRST; + WHILE B AND E =/= NONE DO + BEGIN + B := ISIN(E, S2); + E :- E.SUC; + END; + END; + ISSUBSET := B; + END**OF**ISSUBSET; + + BOOLEAN PROCEDURE ISEQUAL(S1, S2); REF(SET) S1, S2; + BEGIN + ISEQUAL := ISSUBSET(S1, S2) AND THEN ISSUBSET(S2, S1) + END**OF**ISEQUAL; + + BOOLEAN PROCEDURE ISIN(ELE,S); REF(ELEMENT) ELE; REF(SET) S; + BEGIN + REF(ELEMENT) E; BOOLEAN FOUND; + IF NOT S.EMPTY THEN + BEGIN + E :- S.FIRST; + FOUND := E.ISEQUAL(ELE); + WHILE NOT FOUND AND E =/= NONE DO + BEGIN FOUND := E.ISEQUAL(ELE); E :- E.SUC; + END; + END; + ISIN := FOUND + END**OF**ISIN; + + PROCEDURE OUTSET(S); REF(SET) S; + BEGIN + REF(ELEMENT) E; + OUTCHAR('{'); + IF NOT S.EMPTY THEN + BEGIN + E :- S.FIRST; OUTTEXT(E.REPR); + FOR E :- E.SUC WHILE E =/= NONE DO + BEGIN OUTTEXT(", "); OUTTEXT(E.REPR); + END; + END; + OUTCHAR('}'); + END**OF**OUTSET; + + + COMMENT ============== EXAMPLE USING SETS OF NUMBERS ============== ; + + + ELEMENT CLASS NUMBER(N); INTEGER N; + BEGIN + BOOLEAN PROCEDURE ISEQUAL(OTHER); REF(ELEMENT) OTHER; + ISEQUAL := N = OTHER QUA NUMBER.N; + TEXT PROCEDURE REPR; + BEGIN TEXT T; INTEGER I; + T :- BLANKS(20); T.PUTINT(N); + T.SETPOS(1); + WHILE T.GETCHAR = ' ' DO; + REPR :- T.SUB(T.POS - 1, T.LENGTH - T.POS + 2); + END; + REF(ELEMENT) PROCEDURE CLONE; + CLONE :- NEW NUMBER(N); + END**OF**NUMBER; + + PROCEDURE REPORT(S1, MSG1, S2, MSG2, S3); REF(SET) S1, S2, S3; TEXT MSG1, MSG2; + BEGIN + OUTSET(S1); OUTCHAR(' '); + OUTTEXT(MSG1); OUTCHAR(' '); + OUTSET(S2); OUTCHAR(' '); + OUTTEXT(MSG2); OUTCHAR(' '); + OUTSET(S3); + OUTIMAGE; + END**OF**REPORT; + + PROCEDURE REPORTBOOL(S1, MSG1, S2, MSG2, B); REF(SET) S1, S2; TEXT MSG1, MSG2; BOOLEAN B; + BEGIN + OUTSET(S1); OUTCHAR(' '); + OUTTEXT(MSG1); OUTCHAR(' '); + OUTSET(S2); OUTCHAR(' '); + OUTTEXT(MSG2); OUTCHAR(' '); + OUTTEXT(IF B THEN "T" ELSE "F"); + OUTIMAGE; + END**OF**REPORTBOOL; + + PROCEDURE REPORTNUMBOOL(N1, MSG1, S1, MSG2, B); REF(ELEMENT) N1; REF(SET) S1; TEXT MSG1, MSG2; BOOLEAN B; + BEGIN + OUTTEXT(N1.REPR); OUTCHAR(' '); + OUTTEXT(MSG1); OUTCHAR(' '); + OUTSET(S1); OUTCHAR(' '); + OUTTEXT(MSG2); OUTCHAR(' '); + OUTTEXT(IF B THEN "T" ELSE "F"); + OUTIMAGE; + END**OF**REPORTNUMBOOL; + + REF(SET) S1, S2, S3, S4, S5; + REF(ELEMENT) E; + INTEGER I; + + S1 :- NEW SET; FOR I := 1, 2, 3, 4 DO S1.ADD(NEW NUMBER(I)); + S2 :- NEW SET; FOR I := 3, 4, 5, 6 DO S2.ADD(NEW NUMBER(I)); + S3 :- NEW SET; FOR I := 3, 1 DO S3.ADD(NEW NUMBER(I)); + S4 :- NEW SET; FOR I := 1, 2, 3, 4, 5 DO S4.ADD(NEW NUMBER(I)); + S5 :- NEW SET; FOR I := 4, 3, 2, 1 DO S5.ADD(NEW NUMBER(I)); + + REPORT(S1, "UNION", S2, " = ", UNION(S1, S2)); + + REPORT(S1, "INTERSECTION", S2, " = ", INTERSECTION(S1, S2)); + + REPORT(S1, "MINUS", S2, " = ", MINUS(S1, S2)); + + REPORT(S2, "MINUS", S1, " = ", MINUS(S2, S1)); + + E :- NEW NUMBER(2); + REPORTNUMBOOL(E, "IN", S1, " = ", ISIN(E, S1)); + + E :- NEW NUMBER(10); + REPORTNUMBOOL(E, "NOT IN", S1, " = ", NOT ISIN(E, S1)); + + REPORTBOOL(S1, "IS SUBSET OF", S1, " = ", ISSUBSET(S1, S1)); + REPORTBOOL(S3, "IS SUBSET OF", S1, " = ", ISSUBSET(S3, S1)); + REPORTBOOL(S4, "IS SUPERSET OF", S1, " = ", ISSUBSET(S1, S4)); + + REPORTBOOL(S1, "IS EQUAL TO", S2, " = ", ISEQUAL(S1, S2)); + REPORTBOOL(S2, "IS EQUAL TO", S2, " = ", ISEQUAL(S2, S2)); + REPORTBOOL(S1, "IS EQUAL TO", S5, " = ", ISEQUAL(S1, S5)); + +END. diff --git a/Task/Set/Zkl/set.zkl b/Task/Set/Zkl/set.zkl new file mode 100644 index 0000000000..e1cebb0644 --- /dev/null +++ b/Task/Set/Zkl/set.zkl @@ -0,0 +1,21 @@ +var [const] unique = Utils.Helpers.listUnique; +class Set { + fcn init { var [const] set = (vm.arglist.copy() : unique(_)) } + fcn holds(x) { set.holds(x) } + fcn union(setB) { self(set.xplode(),setB.set.xplode()) } + fcn intersection(setB){ sb:=setB.set; + C:=self(); sc:=C.set; + foreach x in (set){ if (sb.holds(x)) sc.append(x) } + C + } + fcn diff(setB){ C:=self(); C.set.extend(set); + setB.set.pump(Void,C.set.remove); + C + } + fcn isSubset(setB){ sb:=setB.set; + set.pump(Void,'wrap(x){ + if (not sb.holds(x)) return(Void.Stop,False); True + }) + } + fcn __opEQ(setB) { ((set.len() == setB.set.len()) and self.isSubset(setB)) } +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Kotlin/seven-sided-dice-from-five-sided-dice.kotlin b/Task/Seven-sided-dice-from-five-sided-dice/Kotlin/seven-sided-dice-from-five-sided-dice.kotlin new file mode 100644 index 0000000000..333d08377c --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Kotlin/seven-sided-dice-from-five-sided-dice.kotlin @@ -0,0 +1,44 @@ +// version 1.1.3 + +import java.util.Random + +val r = Random() + +fun dice5() = 1 + r.nextInt(5) + +fun dice7(): Int { + while (true) { + val t = (dice5() - 1) * 5 + dice5() - 1 + if (t >= 21) continue + return 1 + t / 3 + } +} + +fun checkDist(gen: () -> Int, nRepeats: Int, tolerance: Double = 0.5) { + val occurs = mutableMapOf<Int, Int>() + for (i in 1..nRepeats) { + val d = gen() + if (occurs.containsKey(d)) + occurs[d] = occurs[d]!! + 1 + else + occurs.put(d, 1) + } + val expected = (nRepeats.toDouble()/ occurs.size).toInt() + val maxError = (expected * tolerance / 100.0).toInt() + println("Repetitions = $nRepeats, Expected = $expected") + println("Tolerance = $tolerance%, Max Error = $maxError\n") + println("Integer Occurrences Error Acceptable") + val f = " %d %5d %5d %s" + var allAcceptable = true + for ((k,v) in occurs.toSortedMap()) { + val error = Math.abs(v - expected) + val acceptable = if (error <= maxError) "Yes" else "No" + if (acceptable == "No") allAcceptable = false + println(f.format(k, v, error, acceptable)) + } + println("\nAcceptable overall: ${if (allAcceptable) "Yes" else "No"}") +} + +fun main(args: Array<String>) { + checkDist(::dice7, 1_400_000) +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/REXX/seven-sided-dice-from-five-sided-dice.rexx b/Task/Seven-sided-dice-from-five-sided-dice/REXX/seven-sided-dice-from-five-sided-dice.rexx index f67322017d..4bc18b697b 100644 --- a/Task/Seven-sided-dice-from-five-sided-dice/REXX/seven-sided-dice-from-five-sided-dice.rexx +++ b/Task/Seven-sided-dice-from-five-sided-dice/REXX/seven-sided-dice-from-five-sided-dice.rexx @@ -1,21 +1,21 @@ -/*REXX program simulate a 7─sided die based on a 5─sided throw. */ -parse arg trials sample . /*obtain optional arguments from the CL*/ -if trials=='' then trials=1 /*Not specified? Then use the default.*/ -if sample=='' then sample=1000000 /* " " " " " " */ - - do t=1 for trials /*performs the number of desired trials*/ - die.=0; k=0 - do until k==sample; r=5*random(1,5) + random(1,5) - 6 - if r>20 then iterate - k=k+1; r=r//7 + 1; die.r=die.r + 1 - end /*until*/ +/*REXX program simulates a 7─sided die based on a 5─sided throw for a number of trials. */ +parse arg trials sample seed . /*obtain optional arguments from the CL*/ +if trials=='' | trials="," then trials= 1 /*Not specified? Then use the default.*/ +if sample=='' | sample="," then sample=1000000 /* " " " " " " */ +if datatype(seed,'W') then call random ,,seed /*Integer? Then use it as a RAND seed.*/ + /* [↑] one million samples to be used.*/ + do #=1 for trials; die.=0 /*performs the number of desired trials*/ + k=0 + do until k==sample; r=5 * random(1, 5) + random(1, 5) - 6 + if r>20 then iterate + k=k+1; r=r // 7 + 1; die.r=die.r + 1 + end /*until*/ + say expect=sample%7 - say - say center('trial:'right(t,4) ' ' sample 'samples, expect='expect,79,'─') - say - do j=1 for 7 - say ' side' j "had " die.j ' occurrences', - ' difference from expected:'right(die.j-expect, length(sample)) - end /*j*/ - end /*t*/ - /*stick a fork in it, we're all done. */ + say center('trial:'right(#, 4) " " sample 'samples, expect='expect, 80, "─") + + do j=1 for 7 + say ' side' j "had " die.j ' occurrences', + ' difference from expected:'right(die.j-expect, length(sample)) + end /*j*/ + end /*#*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Verilog/seven-sided-dice-from-five-sided-dice.v b/Task/Seven-sided-dice-from-five-sided-dice/Verilog/seven-sided-dice-from-five-sided-dice.v new file mode 100644 index 0000000000..b6402db519 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Verilog/seven-sided-dice-from-five-sided-dice.v @@ -0,0 +1,125 @@ +/// @Author: Alexandre Felipe (o.alexandre.felipe@gmail.com) +/// @Date: 2017-May-10 + +/////////////////////////////////////////////////////////////////////////////// +/// seven_sided_dice_tb : (testbench) /// +/// Check the distribution of the output of a seven sided dice circuit /// +/////////////////////////////////////////////////////////////////////////////// +module seven_sided_dice_tb; + reg [31:0] freq[0:6]; + reg clk; + wire [2:0] dice_face; + reg req; + wire valid_roll; + integer i; + initial begin + clk <= 0; + forever begin + #1; + clk <= ~clk; + end + end + initial begin + req <= 1'b1; + for(i = 0; i < 7; i = i + 1) begin + freq[i] <= 32'b0; + end + repeat(10) @(posedge clk); + repeat(7000000) begin + @(posedge clk); + while(~valid_roll) begin + @(posedge clk); + end + freq[dice_face] <= freq[dice_face] + 32'b1; + end + $display("********************************************"); + $display("*** Seven sided dice distribution: "); + $display(" Theoretical distribution is an uniform "); + $display(" distribution with (1/7)-probability "); + $display(" for each possible outcome, "); + $display(" The experimental distribution is: "); + for(i = 0; i < 7; i = i + 1) begin + if(freq[i] < 32'd1_000_000) begin + $display("%d with probability 1/7 - (%d ppm)", i, (32'd1_000_000 - freq[i])/7); + end + else begin + $display("%d with probability 1/7 + (%d ppm)", i, (freq[i] - 32'd1_000_000)/7); + end + end + $finish; + end + + seven_sided_dice DUT( + .clk(clk), + .req(req), + .valid_roll(valid_roll), + .dice_face(dice_face) + ); +endmodule +/////////////////////////////////////////////////////////////////////////////// +/// seven_sided_dice : /// +/// Synthsizeable module that using a 5 sided dice as a black box /// +/// is able to reproduce teh outcomes if a 7-sided dice /// +/////////////////////////////////////////////////////////////////////////////// +module seven_sided_dice( + input wire clk, + input wire req, + output reg valid_roll, + output reg [2:0] dice_face +); + wire [2:0] face1; + wire [2:0] face2; + reg [4:0] combination; + reg req_p1; + reg req_p2; + reg req_p3; + always @(posedge clk) begin + req_p1 <= req; + req_p2 <= req_p1; + end + always @(posedge clk) begin + if(req_p1) begin + combination <= face1 + face2 + {face2, 2'b00}; + end + if(req_p2) begin + case(combination) + 5'd0, 5'd1, 5'd2: {valid_roll, dice_face} <= {1'b1, 3'd0}; + 5'd3, 5'd4, 5'd5: {valid_roll, dice_face} <= {1'b1, 3'd1}; + 5'd6, 5'd7, 5'd8: {valid_roll, dice_face} <= {1'b1, 3'd2}; + 5'd9, 5'd10, 5'd11: {valid_roll, dice_face} <= {1'b1, 3'd3}; + 5'd12, 5'd13, 5'd14: {valid_roll, dice_face} <= {1'b1, 3'd4}; + 5'd15, 5'd16, 5'd17: {valid_roll, dice_face} <= {1'b1, 3'd5}; + 5'd18, 5'd19, 5'd20: {valid_roll, dice_face} <= {1'b1, 3'd6}; + default: valid_roll <= 1'b0; + endcase + end + end + + five_sided_dice dice1( + .clk(clk), + .req(req), + .dice_face(face1) + ); + + five_sided_dice dice2( + .clk(clk), + .req(req), + .dice_face(face2) + ); +endmodule + +/////////////////////////////////////////////////////////////////////////////// +/// five_sided_dice : /// +/// A model of the five sided dice component /// +/////////////////////////////////////////////////////////////////////////////// +module five_sided_dice( + input wire clk, + input wire req, + output reg [2:0] dice_face +); + always @(posedge clk) begin + if(req) begin + dice_face <= $urandom % 5; + end + end +endmodule diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Zkl/seven-sided-dice-from-five-sided-dice.zkl b/Task/Seven-sided-dice-from-five-sided-dice/Zkl/seven-sided-dice-from-five-sided-dice.zkl new file mode 100644 index 0000000000..85c935a8a6 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Zkl/seven-sided-dice-from-five-sided-dice.zkl @@ -0,0 +1,12 @@ +var die5=(1).random.fp(6); // [1..5] +fcn die7{ while((r:=5*die5() + die5())>=27){} r/3-1 } + +fcn rtest(N){ //test spread over [0..9] + dist:=L(0,0,0,0,0,0,0,0,0,0); + do(N){ dist[die7()]+=1 } + sum:=dist.sum(); + dist=dist.apply('wrap(n){ "%.2f%%".fmt(n.toFloat()/sum*100) }).println(); +} + +println("Looking for ",100.0/7,"%"); +rtest(0d1_000_000); diff --git a/Task/Shell-one-liner/Gambas/shell-one-liner.gambas b/Task/Shell-one-liner/Gambas/shell-one-liner.gambas new file mode 100644 index 0000000000..9d801341de --- /dev/null +++ b/Task/Shell-one-liner/Gambas/shell-one-liner.gambas @@ -0,0 +1,5 @@ +Public Sub Main() + +Shell "echo Hello World" + +End diff --git a/Task/Shell-one-liner/jq/shell-one-liner.jq b/Task/Shell-one-liner/Jq/shell-one-liner.jq similarity index 100% rename from Task/Shell-one-liner/jq/shell-one-liner.jq rename to Task/Shell-one-liner/Jq/shell-one-liner.jq diff --git a/Task/Shell-one-liner/OoRexx/shell-one-liner.rexx b/Task/Shell-one-liner/OoRexx/shell-one-liner.rexx new file mode 100644 index 0000000000..a5d07d3f76 --- /dev/null +++ b/Task/Shell-one-liner/OoRexx/shell-one-liner.rexx @@ -0,0 +1 @@ +rexx -e "say 'Goodbye, world.'" diff --git a/Task/Shell-one-liner/Zkl/shell-one-liner.zkl b/Task/Shell-one-liner/Zkl/shell-one-liner.zkl new file mode 100644 index 0000000000..f2d77021c7 --- /dev/null +++ b/Task/Shell-one-liner/Zkl/shell-one-liner.zkl @@ -0,0 +1 @@ +echo 'println("Hello World ",5+6)' | zkl diff --git a/Task/Short-circuit-evaluation/BaCon/short-circuit-evaluation.bacon b/Task/Short-circuit-evaluation/BaCon/short-circuit-evaluation.bacon new file mode 100644 index 0000000000..eaed4bf2e8 --- /dev/null +++ b/Task/Short-circuit-evaluation/BaCon/short-circuit-evaluation.bacon @@ -0,0 +1,26 @@ +' Short-circuit evaluation +FUNCTION a(f) + PRINT "FUNCTION a" + RETURN f +END FUNCTION + +FUNCTION b(f) + PRINT "FUNCTION b" + RETURN f +END FUNCTION + +PRINT "FALSE and TRUE" +x = a(FALSE) AND b(TRUE) +PRINT x + +PRINT "TRUE and TRUE" +x = a(TRUE) AND b(TRUE) +PRINT x + +PRINT "FALSE or FALSE" +y = a(FALSE) OR b(FALSE) +PRINT y + +PRINT "TRUE or FALSE" +y = a(TRUE) OR b(FALSE) +PRINT y diff --git a/Task/Short-circuit-evaluation/Elena/short-circuit-evaluation.elena b/Task/Short-circuit-evaluation/Elena/short-circuit-evaluation.elena index 718984238c..650791ef37 100644 --- a/Task/Short-circuit-evaluation/Elena/short-circuit-evaluation.elena +++ b/Task/Short-circuit-evaluation/Elena/short-circuit-evaluation.elena @@ -1,21 +1,20 @@ -#import system. -#import system'routines. -#import extensions. +import system'routines. +import extensions. -#symbol a = x [ console writeLine:"a". ^ x. ]. +symbol a = (:x)[ console writeLine:"a". ^ x. ]. -#symbol b = x [ console writeLine:"b". ^ x. ]. +symbol b = (:x)[ console writeLine:"b". ^ x. ]. -#symbol program = +program = [ - (false, true) run &each: i + (false, true) forEach(:i) [ - (false, true) run &each: j + (false, true) forEach(:j) [ - console writeLine:i:" and ":j:" = ":(a eval:i and:[ b eval:j ]). + console printLine(i," and ",j," = ",a eval:i && $(b eval:j)). console writeLine. - console writeLine:i:" or ":j:" = ":(a eval:i or:[ b eval:j ]). + console printLine(i," or ",j," = ",a eval:i || $(b eval:j)). console writeLine. ]. ]. diff --git a/Task/Short-circuit-evaluation/JavaScript/short-circuit-evaluation-1.js b/Task/Short-circuit-evaluation/JavaScript/short-circuit-evaluation-1.js deleted file mode 100644 index 3bf5960b01..0000000000 --- a/Task/Short-circuit-evaluation/JavaScript/short-circuit-evaluation-1.js +++ /dev/null @@ -1,14 +0,0 @@ -function a(bool) { - console.log('a -->', bool); - - return bool; -} - -function b(bool) { - console.log('b -->', bool); - - return bool; -} - -var x = a(false) && b(true), - y = a(true) || b(false); diff --git a/Task/Short-circuit-evaluation/JavaScript/short-circuit-evaluation-2.js b/Task/Short-circuit-evaluation/JavaScript/short-circuit-evaluation-2.js deleted file mode 100644 index effde750b2..0000000000 --- a/Task/Short-circuit-evaluation/JavaScript/short-circuit-evaluation-2.js +++ /dev/null @@ -1,2 +0,0 @@ -a --> false -a --> true diff --git a/Task/Short-circuit-evaluation/jq/short-circuit-evaluation-1.jq b/Task/Short-circuit-evaluation/Jq/short-circuit-evaluation-1.jq similarity index 100% rename from Task/Short-circuit-evaluation/jq/short-circuit-evaluation-1.jq rename to Task/Short-circuit-evaluation/Jq/short-circuit-evaluation-1.jq diff --git a/Task/Short-circuit-evaluation/jq/short-circuit-evaluation-2.jq b/Task/Short-circuit-evaluation/Jq/short-circuit-evaluation-2.jq similarity index 100% rename from Task/Short-circuit-evaluation/jq/short-circuit-evaluation-2.jq rename to Task/Short-circuit-evaluation/Jq/short-circuit-evaluation-2.jq diff --git a/Task/Short-circuit-evaluation/Kotlin/short-circuit-evaluation.kotlin b/Task/Short-circuit-evaluation/Kotlin/short-circuit-evaluation.kotlin new file mode 100644 index 0000000000..8bf4b5c062 --- /dev/null +++ b/Task/Short-circuit-evaluation/Kotlin/short-circuit-evaluation.kotlin @@ -0,0 +1,22 @@ +// version 1.1.2 + +fun a(v: Boolean): Boolean { + println("'a' called") + return v +} + +fun b(v: Boolean): Boolean { + println("'b' called") + return v +} + +fun main(args: Array<String>){ + val pairs = arrayOf(Pair(true, true), Pair(true, false), Pair(false, true), Pair(false, false)) + for (pair in pairs) { + val x = a(pair.first) && b(pair.second) + println("${pair.first} && ${pair.second} = $x") + val y = a(pair.first) || b(pair.second) + println("${pair.first} || ${pair.second} = $y") + println() + } +} diff --git a/Task/Short-circuit-evaluation/OoRexx/short-circuit-evaluation.rexx b/Task/Short-circuit-evaluation/OoRexx/short-circuit-evaluation.rexx new file mode 100644 index 0000000000..06ebb6490e --- /dev/null +++ b/Task/Short-circuit-evaluation/OoRexx/short-circuit-evaluation.rexx @@ -0,0 +1,15 @@ +Parse Version v +Say 'Version='v +If a() | b() Then Say 'a and b are true' +If \a() | b() Then Say 'Surprise' + Else Say 'ok' +If a(), b() Then Say 'a is true' +If \a(), b() Then Say 'Surprise' + Else Say 'ok: \a() is false' +Select + When \a(), b() Then Say 'Surprise' + Otherwise Say 'ok: \a() is false (Select)' + End +Exit +a: Say 'a returns .true'; Return .true +b: Say 'b returns 1'; Return 1 diff --git a/Task/Short-circuit-evaluation/Simula/short-circuit-evaluation.simula b/Task/Short-circuit-evaluation/Simula/short-circuit-evaluation.simula new file mode 100644 index 0000000000..90f03b4116 --- /dev/null +++ b/Task/Short-circuit-evaluation/Simula/short-circuit-evaluation.simula @@ -0,0 +1,52 @@ +BEGIN + + BOOLEAN PROCEDURE A(BOOL); BOOLEAN BOOL; + BEGIN OUTCHAR('A'); A := BOOL; + END A; + + BOOLEAN PROCEDURE B(BOOL); BOOLEAN BOOL; + BEGIN OUTCHAR('B'); B := BOOL; + END B; + + PROCEDURE OUTBOOL(BOOL); BOOLEAN BOOL; + OUTCHAR(IF BOOL THEN 'T' ELSE 'F'); + + PROCEDURE TEST; + BEGIN + PROCEDURE ANDTEST; + BEGIN + BOOLEAN X, Y, Z; + FOR X := TRUE, FALSE DO + FOR Y := TRUE, FALSE DO + BEGIN + OUTTEXT("A("); OUTBOOL(X); + OUTTEXT(") AND "); + OUTTEXT("B("); OUTBOOL(Y); + OUTTEXT("): "); + Z := A(X) AND THEN B(Y); + OUTIMAGE; + END; + END ANDTEST; + + PROCEDURE ORTEST; + BEGIN + BOOLEAN X, Y, Z; + FOR X := TRUE, FALSE DO + FOR Y := TRUE, FALSE DO + BEGIN + OUTTEXT("A("); OUTBOOL(X); + OUTTEXT(") OR "); + OUTTEXT("B("); OUTBOOL(Y); + OUTTEXT("): "); + Z := A(X) OR ELSE B(Y); + OUTIMAGE; + END; + END ORTEST; + + ANDTEST; + ORTEST; + + END TEST; + + TEST; +END. diff --git a/Task/Short-circuit-evaluation/Zkl/short-circuit-evaluation.zkl b/Task/Short-circuit-evaluation/Zkl/short-circuit-evaluation.zkl new file mode 100644 index 0000000000..1f483ab7cf --- /dev/null +++ b/Task/Short-circuit-evaluation/Zkl/short-circuit-evaluation.zkl @@ -0,0 +1,2 @@ +fcn a(b){self.fcn.println(b); b} +fcn b(b){self.fcn.println(b); b} diff --git a/Task/Show-the-epoch/jq/show-the-epoch-1.jq b/Task/Show-the-epoch/Jq/show-the-epoch-1.jq similarity index 100% rename from Task/Show-the-epoch/jq/show-the-epoch-1.jq rename to Task/Show-the-epoch/Jq/show-the-epoch-1.jq diff --git a/Task/Show-the-epoch/jq/show-the-epoch-2.jq b/Task/Show-the-epoch/Jq/show-the-epoch-2.jq similarity index 100% rename from Task/Show-the-epoch/jq/show-the-epoch-2.jq rename to Task/Show-the-epoch/Jq/show-the-epoch-2.jq diff --git a/Task/Show-the-epoch/Kotlin/show-the-epoch.kotlin b/Task/Show-the-epoch/Kotlin/show-the-epoch.kotlin new file mode 100644 index 0000000000..75bf5f3ad0 --- /dev/null +++ b/Task/Show-the-epoch/Kotlin/show-the-epoch.kotlin @@ -0,0 +1,12 @@ +// version 1.1.2 + +import java.util.Date +import java.util.TimeZone +import java.text.DateFormat + +fun main( args: Array<String>) { + val epoch = Date(0) + val format = DateFormat.getDateTimeInstance() + format.timeZone = TimeZone.getTimeZone("UTC") + println(format.format(epoch)) +} diff --git a/Task/Show-the-epoch/Phix/show-the-epoch.phix b/Task/Show-the-epoch/Phix/show-the-epoch.phix new file mode 100644 index 0000000000..4ed8a2f7b9 --- /dev/null +++ b/Task/Show-the-epoch/Phix/show-the-epoch.phix @@ -0,0 +1,4 @@ +constant d0 = {0,1,1,0,0,0,1,1} +include builtins\timedate.e +?format_timedate(d0,"YYYY-MM-DD") +?format_timedate(d0,"Dddd, Mmmm d, YYYY") diff --git a/Task/Show-the-epoch/PowerShell/show-the-epoch.psh b/Task/Show-the-epoch/PowerShell/show-the-epoch-1.psh similarity index 100% rename from Task/Show-the-epoch/PowerShell/show-the-epoch.psh rename to Task/Show-the-epoch/PowerShell/show-the-epoch-1.psh diff --git a/Task/Show-the-epoch/PowerShell/show-the-epoch-2.psh b/Task/Show-the-epoch/PowerShell/show-the-epoch-2.psh new file mode 100644 index 0000000000..f09fe7df85 --- /dev/null +++ b/Task/Show-the-epoch/PowerShell/show-the-epoch-2.psh @@ -0,0 +1 @@ +Get-Date -Year 1 -Month 1 -Day 1 -Hour 0 -Minute 0 -Second 0 -Millisecond 0 diff --git a/Task/Show-the-epoch/PowerShell/show-the-epoch-3.psh b/Task/Show-the-epoch/PowerShell/show-the-epoch-3.psh new file mode 100644 index 0000000000..953cc13510 --- /dev/null +++ b/Task/Show-the-epoch/PowerShell/show-the-epoch-3.psh @@ -0,0 +1 @@ +New-Object -TypeName System.DateTime diff --git a/Task/Show-the-epoch/PowerShell/show-the-epoch-4.psh b/Task/Show-the-epoch/PowerShell/show-the-epoch-4.psh new file mode 100644 index 0000000000..eb5224d7a5 --- /dev/null +++ b/Task/Show-the-epoch/PowerShell/show-the-epoch-4.psh @@ -0,0 +1 @@ +New-Object -TypeName System.DateTime -ArgumentList 1, 1, 1, 0, 0, 0, ([DateTimeKind]::Utc) | Format-List diff --git a/Task/Show-the-epoch/Zkl/show-the-epoch.zkl b/Task/Show-the-epoch/Zkl/show-the-epoch.zkl new file mode 100644 index 0000000000..522bb6d2ea --- /dev/null +++ b/Task/Show-the-epoch/Zkl/show-the-epoch.zkl @@ -0,0 +1,2 @@ +zkl: Time.Clock.tickToTock(0,False) +L(1970,1,1,0,0,0) // y,m,d, h,m,s diff --git a/Task/Sierpinski-carpet/AppleScript/sierpinski-carpet.applescript b/Task/Sierpinski-carpet/AppleScript/sierpinski-carpet.applescript index 2ee4ce3fc5..c3825d1dfe 100644 --- a/Task/Sierpinski-carpet/AppleScript/sierpinski-carpet.applescript +++ b/Task/Sierpinski-carpet/AppleScript/sierpinski-carpet.applescript @@ -1,14 +1,15 @@ --- CARPET MODEL +-- CARPET MODEL -------------------------------------------------------------- -- sierpinskiCarpet :: Int -> [[Bool]] on sierpinskiCarpet(n) -- rowStates :: Int -> [Bool] script rowStates - on lambda(x, _, xs) + on |λ|(x, _, xs) -- cellState :: Int -> Bool script cellState + -- inCarpet :: Int -> Int -> Bool on inCarpet(x, y) if (x = 0 or y = 0) then @@ -20,63 +21,74 @@ on sierpinskiCarpet(n) end if end inCarpet - on lambda(y) + on |λ|(y) inCarpet(x, y) - end lambda + end |λ| end script map(cellState, xs) - end lambda + end |λ| end script - map(rowStates, range(0, (3 ^ n) - 1)) + map(rowStates, enumFromTo(0, (3 ^ n) - 1)) end sierpinskiCarpet --- TEST - +-- TEST ---------------------------------------------------------------------- on run -- Carpets of orders 1, 2, 3 set strCarpets to ¬ intercalate(linefeed & linefeed, ¬ - map(showCarpet, range(1, 3))) + map(showCarpet, enumFromTo(1, 3))) set the clipboard to strCarpets return strCarpets end run - --- CARPET DISPLAY +-- CARPET DISPLAY ------------------------------------------------------------ -- showCarpet :: Int -> String on showCarpet(n) + -- showRow :: [Bool] -> String script showRow -- showBool :: Bool -> String script showBool - on lambda(bool) + on |λ|(bool) if bool then character id 9608 else " " end if - end lambda + end |λ| end script - on lambda(xs) + on |λ|(xs) intercalate("", map(my showBool, xs)) - end lambda + end |λ| end script intercalate(linefeed, map(showRow, sierpinskiCarpet(n))) end showCarpet ---------------------------------------------------------------------------- +-- GENERIC FUNCTIONS --------------------------------------------------------- --- GENERIC LIBRARY FUNCTIONS +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- map :: (a -> b) -> [a] -> [b] on map(f, xs) @@ -84,7 +96,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -98,20 +110,6 @@ on intercalate(strText, lstText) return strJoined end intercalate --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then - set d to -1 - else - set d to 1 - end if - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range - -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) @@ -119,7 +117,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Sierpinski-carpet/Gnuplot/sierpinski-carpet-1.gnuplot b/Task/Sierpinski-carpet/Gnuplot/sierpinski-carpet-1.gnuplot new file mode 100644 index 0000000000..ee45945c96 --- /dev/null +++ b/Task/Sierpinski-carpet/Gnuplot/sierpinski-carpet-1.gnuplot @@ -0,0 +1,11 @@ +## SCff.gp 1/14/17 aev +## Plotting Sierpinski carpet fractal. +## dat-files are PARI/GP generated output files: +## http://rosettacode.org/wiki/Sierpinski_carpet#PARI.2FGP +#cd 'C:\gnupData' + +##SC5 +clr = '"green"' +filename = "SC5gp1" +ttl = "Sierpinski carpet fractal, v.#1" +load "plotff.gp" diff --git a/Task/Sierpinski-carpet/Gnuplot/sierpinski-carpet-2.gnuplot b/Task/Sierpinski-carpet/Gnuplot/sierpinski-carpet-2.gnuplot new file mode 100644 index 0000000000..17ea7da8f5 --- /dev/null +++ b/Task/Sierpinski-carpet/Gnuplot/sierpinski-carpet-2.gnuplot @@ -0,0 +1,20 @@ +## plotscf.gp 12/7/16 aev +## Plotting a Sierpinski carpet fractal to the png-file. +## Note: assign variables: ord (order), clr (color), filename and ttl (before using load command). +## ord (order) # a.k.a. level - defines size of fractal (also number of dots). +reset +set terminal png font arial 12 size 640,640 +ofn=filename.".png" +set output ofn +unset border; unset xtics; unset ytics; unset key; +set title ttl font "Arial:Bold,12" +set xrange [0:1]; set yrange [0:1]; +sc(n, x, y, d) = n >= ord ? \ + sprintf('set object rect from %f,%f to %f,%f fc rgb @clr fs solid;', x, y, x+d, y+d) : \ + sc(n+1, x, y, d/3) . sc(n+1, x+d/3, y, d/3) . \ + sc(n+1, x+2*d/3, y, d/3) . sc(n+1, x, y+d/3, d/3) . \ + sc(n+1, x+2*d/3, y+d/3, d/3) . sc(n+1, x, y+2*d/3, d/3) . \ + sc(n+1, x+d/3, y+2*d/3, d/3) . sc(n+1, x+2*d/3, y+2*d /3, d/3); +eval(sc(0, 0.0, 0.0, 1.0)) +plot -100 +set output diff --git a/Task/Sierpinski-carpet/Gnuplot/sierpinski-carpet-3.gnuplot b/Task/Sierpinski-carpet/Gnuplot/sierpinski-carpet-3.gnuplot new file mode 100644 index 0000000000..f857d59422 --- /dev/null +++ b/Task/Sierpinski-carpet/Gnuplot/sierpinski-carpet-3.gnuplot @@ -0,0 +1,27 @@ +## plotscf1.gp 12/7/16 aev +## Plotting a Sierpinski carpet fractal to the png-file. +## Note: assign variables: ord (order, just for title), clr (color), filename and ttl (before using load command). +## In this version order is always 5. +reset +set terminal png font arial 12 size 640,640 +ofn=filename.".png" +set output ofn +unset border; unset xtics; unset ytics; unset key; +set title ttl font "Arial:Bold,12" +o=3 +sqr(x,y) = abs(x + y) + abs(x - y) - o +f(x) = o*abs(x) - o +c0(x,y) = abs(x + y) + abs(x - y) - 1 +c1(x,y) = c0(o*x,f(y)) * c0(f(x),o*y) * c0(f(x),f(y)) +c2(x,y) = c1(o*x,f(y)) * c1(f(x),o*y) * c1(f(x),f(y)) +c3(x,y) = c2(o*x,f(y)) * c2(f(x),o*y) * c2(f(x),f(y)) +c4(x,y) = c3(o*x,f(y)) * c3(f(x),o*y) * c3(f(x),f(y)) +sc(x,y) = sqr(x,y)>0 || c0(x,y)*c1(x,y)*c2(x,y)*c3(x,y)*c4(x,y)<0 ? 0:1 +set xrange [-1.5:1.5]; set yrange [-1.5:1.5]; +set pm3d map; +set palette model RGB defined (0 "white", 1 @clr); +set size ratio -1 +smp=640; set samples smp; set isosamples smp; +unset colorbox +splot sc(x,y) +set output diff --git a/Task/Sierpinski-carpet/Gnuplot/sierpinski-carpet-4.gnuplot b/Task/Sierpinski-carpet/Gnuplot/sierpinski-carpet-4.gnuplot new file mode 100644 index 0000000000..b39433ae68 --- /dev/null +++ b/Task/Sierpinski-carpet/Gnuplot/sierpinski-carpet-4.gnuplot @@ -0,0 +1,20 @@ +## pSCF.gp 12/7/16 aev +## Plotting Sierpinski carpet fractals. +## Note: assign variables: ord (order), clr (color), filename and ttl (before using load command). +## ord (order) # a.k.a. level - defines size of fractal (also number of dots). +#cd 'C:\gnupData' + +##SCF21 +ord=3; clr = '"red"'; +filename = "SCF21gp"; ttl = "Sierpinski carpet fractal #21, ord ".ord; +load "plotscf.gp" + +##SCF22 +ord=5; clr = '"brown"'; +filename = "SCF22gp"; ttl = "Sierpinski carpet fractal #22, ord ".ord; +load "plotscf.gp" + +##SCF31 +ord=5; clr = '"navy"'; +filename = "SCF31gp"; ttl = "Sierpinski carpet fractal #31, ord ".ord; +load "plotscf1.gp" diff --git a/Task/Sierpinski-carpet/jq/sierpinski-carpet-1.jq b/Task/Sierpinski-carpet/Jq/sierpinski-carpet-1.jq similarity index 100% rename from Task/Sierpinski-carpet/jq/sierpinski-carpet-1.jq rename to Task/Sierpinski-carpet/Jq/sierpinski-carpet-1.jq diff --git a/Task/Sierpinski-carpet/jq/sierpinski-carpet-2.jq b/Task/Sierpinski-carpet/Jq/sierpinski-carpet-2.jq similarity index 100% rename from Task/Sierpinski-carpet/jq/sierpinski-carpet-2.jq rename to Task/Sierpinski-carpet/Jq/sierpinski-carpet-2.jq diff --git a/Task/Sierpinski-carpet/Kotlin/sierpinski-carpet-1.kotlin b/Task/Sierpinski-carpet/Kotlin/sierpinski-carpet-1.kotlin new file mode 100644 index 0000000000..b31ac1cb03 --- /dev/null +++ b/Task/Sierpinski-carpet/Kotlin/sierpinski-carpet-1.kotlin @@ -0,0 +1,22 @@ +// version 1.1.2 + +fun inCarpet(x: Int, y: Int): Boolean { + var xx = x + var yy = y + while (xx != 0 && yy != 0) { + if (xx % 3 == 1 && yy % 3 == 1) return false + xx /= 3 + yy /= 3 + } + return true +} + +fun carpet(n: Int) { + val power = Math.pow(3.0, n.toDouble()).toInt() + for(i in 0 until power) { + for(j in 0 until power) print(if (inCarpet(i, j)) "*" else " ") + println() + } +} + +fun main(args: Array<String>) = carpet(3) diff --git a/Task/Sierpinski-carpet/Kotlin/sierpinski-carpet-2.kotlin b/Task/Sierpinski-carpet/Kotlin/sierpinski-carpet-2.kotlin new file mode 100644 index 0000000000..f1cb9c45d5 --- /dev/null +++ b/Task/Sierpinski-carpet/Kotlin/sierpinski-carpet-2.kotlin @@ -0,0 +1,57 @@ +// version 1.1.2 + +import java.awt.* +import javax.swing.* + +public class SierpinskiCarpet : JPanel() { + private val dim = 513 + private val margin = 20 + private var limit = dim + + init { + val size = dim + 2 * margin + preferredSize = Dimension(size, size) + background = Color.blue + foreground = Color.yellow + Timer(2000) { + limit /= 3 + if (limit <= 3) limit = dim + repaint() + }.start() + } + + private fun drawCarpet(g: Graphics2D, x: Int, y: Int, s: Int) { + var size = s + if (s < limit) return + size /= 3 + for (i in 0 until 9) { + if (i == 4) { + g.fillRect(x + size, y + size, size, size) + } + else { + drawCarpet(g, x + (i % 3) * size, y + (i / 3) * size, size) + } + } + } + + override fun paintComponent(gg: Graphics) { + super.paintComponent(gg) + val g = gg as Graphics2D + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + g.translate(margin, margin) + drawCarpet(g, 0, 0, dim) + } +} + +fun main(args: Array<String>) { + SwingUtilities.invokeLater { + val f = JFrame() + f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE + f.title = "Sierpinski Carpet" + f.isResizable = false + f.add(SierpinskiCarpet(), BorderLayout.CENTER) + f.pack() + f.setLocationRelativeTo(null) + f.isVisible = true + } +} diff --git a/Task/Sierpinski-carpet/MATLAB/sierpinski-carpet.m b/Task/Sierpinski-carpet/MATLAB/sierpinski-carpet.m new file mode 100644 index 0000000000..96828e78dd --- /dev/null +++ b/Task/Sierpinski-carpet/MATLAB/sierpinski-carpet.m @@ -0,0 +1,6 @@ +n = 3; +c = string('#'); +for k = 1 : n + c = [c + c + c, c + c.replace('#', ' ') + c, c + c + c]; +end +disp(c.join(char(10))) diff --git a/Task/Sierpinski-carpet/PARI-GP/sierpinski-carpet-1.pari b/Task/Sierpinski-carpet/PARI-GP/sierpinski-carpet-1.pari new file mode 100644 index 0000000000..b447484d6d --- /dev/null +++ b/Task/Sierpinski-carpet/PARI-GP/sierpinski-carpet-1.pari @@ -0,0 +1,31 @@ +\\ Improved simple plotting using matrix mat (color and scaling added). +\\ Matrix should be filled with 0/1. 7/6/16 aev +iPlotmat(mat,clr)={ + my(xz=#mat[1,],yz=#mat[,1],vx=List(),vy=vx,xmin,xmax,ymin,ymax,c=0.625); + for(i=1,yz, for(j=1,xz, if(mat[i,j]==0, next, listput(vx,i); listput(vy,j)))); + xmin=listmin(vx); xmax=listmax(vx); ymin=listmin(vy); ymax=listmax(vy); + plotinit(0); plotcolor(0,clr); + plotscale(0, xmin,xmax,ymin,ymax); + plotpoints(0, Vec(vx)*c,Vec(vy)); + plotdraw([0,xmin,ymin]); + print(" *** matrix: ",xz,"x",yz,", ",#vy," DOTS"); +} +\\ iPlotV2(): Improved plotting from a file written by the wrtmat(). (color added) +\\ Saving possibly huge generation time if re-plotting needed. +iPlotV2(fn, clr)={ + my(F,nf,vx=List(),vy=vx,Vr,xmin,xmax,ymin,ymax,c=0.625); + F=readstr(fn); nf=#F; + print(" *** Plotting from: ", fn, " - ", nf, " DOTS"); + for(i=1,nf, Vr=stok(F[i]," "); listput(vx,eval(Vr[1])); listput(vy,eval(Vr[2]))); + xmin=listmin(vx); xmax=listmax(vx); ymin=listmin(vy); ymax=listmax(vy); + plotinit(0); plotcolor(0,clr); + plotscale(0, xmin,xmax,ymin,ymax); + plotpoints(0, Vec(vx)*c,Vec(vy)); + plotdraw([0,xmin,ymin]); +} +\\ Are x,y inside Sierpinski carpet? (1-yes, 0-no) 6/10/16 aev +inSC(x,y)={ + while(1, if(!x||!y,return(1)); + if(x%3==1&&y%3==1, return(0)); + x\=3; y\=3;);\\wend +} diff --git a/Task/Sierpinski-carpet/PARI-GP/sierpinski-carpet-2.pari b/Task/Sierpinski-carpet/PARI-GP/sierpinski-carpet-2.pari new file mode 100644 index 0000000000..e62e47f2fc --- /dev/null +++ b/Task/Sierpinski-carpet/PARI-GP/sierpinski-carpet-2.pari @@ -0,0 +1,19 @@ +\\ Sierpinski carpet fractal (n - order, clr - color, dfn - data file name) +\\ 6/10/16, upgraded 11/29/16 aev +pSierpinskiC(n, clr=5, dfn="")={ + my(n3=3^n-1,M,pf=n>=5); + if(pf, M=matrix(n3+1,n3+1)); + for(i=0,n3, for(j=0,n3, + if(inSC(i,j), + if(pf, M[i+1,j+1]=1, print1("* ")), if(!pf, print1(" "))); + ); if(!pf, print("")); + );\\fend i + if(!pf, return(0)); + if(dfn=="", c, wrtmat(M, dfn)); +} +{\\ Test: +pSierpinskiC(3); +pSierpinskiC(5,14); \\ SierpC5.png, color - navy +} +{pSierpinskiC(5,,"c:\\pariData\\SC5.dat"); +iPlotV2("c:\\pariData\\SC5.dat",10);} \\ SierpC5a.png, color - dark-green diff --git a/Task/Sierpinski-carpet/PARI-GP/sierpinski-carpet.pari b/Task/Sierpinski-carpet/PARI-GP/sierpinski-carpet.pari deleted file mode 100644 index 0bf8c09c63..0000000000 --- a/Task/Sierpinski-carpet/PARI-GP/sierpinski-carpet.pari +++ /dev/null @@ -1,23 +0,0 @@ -\\ Sierpinski carpet fractal -\\ Note: plotmat() can be found here on -\\ http://rosettacode.org/wiki/Brownian_tree#PARI.2FGP page. -\\ 6/10/16 aev -inSC(x,y)={ -while(1, if(!x||!y,return(1)); - if(x%3==1&&y%3==1, return(0)); - x\=3; y\=3;);\\wend -} -pSierpinskiC(n,pflg=0)={ -my(n3=3^n-1,M); -if(pflg<0||pflg>1, pflg=0); if(pflg, M=matrix(n3+1,n3+1)); -for(i=0,n3, for(j=0,n3, - if(inSC(i,j), - if(pflg, M[i+1,j+1]=1, print1("* ")), if(!pflg, print1(" "))); - ); if(!pflg, print("")); - );\\fend i -if(pflg, plotmat(M)); -} -{\\ Test: -pSierpinskiC(3); -pSierpinskiC(5,1); \\ SierpC5.png -} diff --git a/Task/Sierpinski-carpet/R/sierpinski-carpet-1.r b/Task/Sierpinski-carpet/R/sierpinski-carpet-1.r new file mode 100644 index 0000000000..75be2b91e3 --- /dev/null +++ b/Task/Sierpinski-carpet/R/sierpinski-carpet-1.r @@ -0,0 +1,25 @@ +## Are x,y inside Sierpinski carpet (and where)? (1-yes, 0-no) +inSC <- function(x, y) { + while(TRUE) { + if(!x||!y) {return(1)} + if(x%%3==1&&y%%3==1) {return(0)} + x=x%/%3; y=y%/%3; + } return(0); +} +## Plotting Sierpinski carpet fractal. aev 4/1/17 +## ord - order, fn - file name, ttl - plot title, clr - color +pSierpinskiC <- function(ord, fn="", ttl="", clr="navy") { + m=640; abbr="SCR"; dftt="Sierpinski carpet fractal"; + n=3^ord-1; M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE); + cat(" *** START", abbr, date(), "\n"); + if(fn=="") {pf=paste0(abbr,"o", ord)} else {pf=paste0(fn, ".png")}; + if(ttl!="") {dftt=ttl}; ttl=paste0(dftt,", order ", ord); + cat(" *** Plot file:", pf,".png", "title:", ttl, "\n"); + for(i in 0:n) { + for(j in 0:n) {if(inSC(i,j)) {M[i,j]=1} + }} + plotmat(M, pf, clr, ttl); + cat(" *** END", abbr, date(), "\n"); +} +## Executing: +pSierpinskiC(5); diff --git a/Task/Sierpinski-carpet/R/sierpinski-carpet-2.r b/Task/Sierpinski-carpet/R/sierpinski-carpet-2.r new file mode 100644 index 0000000000..06b697e389 --- /dev/null +++ b/Task/Sierpinski-carpet/R/sierpinski-carpet-2.r @@ -0,0 +1,17 @@ +## Plotting Sierpinski carpet fractal v.2. aev 4/2/17 +## ord - order, fn - file name, ttl - plot title, clr - color +pSierpinskiC2 <- function(ord, fn="", ttl="", clr="brown") { + m=640; abbr="SCR2"; dftt="Sierpinski carpet fractal v.2"; + cat(" *** START", abbr, date(), "\n"); + if(fn=="") {pf=paste0(abbr,"o", ord)} else {pf=paste0(fn, ".png")}; + if(ttl!="") {dftt=ttl}; ttl=paste0(dftt,", order ", ord); + cat(" *** Plot file:", pf,".png", "title:", ttl, "\n"); + S = matrix(1,1,1); + for (i in 1:ord) { + Q = cbind(S,S,S); R = cbind(S,0*S,S); S = rbind(Q,R,Q); + } + plotmat(S, pf, clr, ttl); + cat(" *** END", abbr, date(), "\n"); +} +## Executing: +pSierpinskiC2(5); diff --git a/Task/Sierpinski-carpet/REXX/sierpinski-carpet.rexx b/Task/Sierpinski-carpet/REXX/sierpinski-carpet.rexx index 8c46c0d60b..e383a600f2 100644 --- a/Task/Sierpinski-carpet/REXX/sierpinski-carpet.rexx +++ b/Task/Sierpinski-carpet/REXX/sierpinski-carpet.rexx @@ -5,21 +5,20 @@ if char=='' then char="*" /*use the default of an asteris if length(char)==2 then char=x2c(char) /*it was specified in hexadecimal char.*/ if length(char)==3 then char=d2c(char) /* " " " " decimal character*/ width=linesize() /*the width of the terminal screen. */ -if N>18 then numeric digits 1000 /*just in case the user went ka─razy. */ +if N>18 then numeric digits 100 /*just in case the user went ka─razy. */ nnn=3**N /* [↓] NNN is the cube of N. */ do j=0 for nnn; z= /*Z: is the line to be displayed. */ - do k=0 for nnn; jj=j; kk=k; xChar=char - + do k=0 for nnn; jj=j; kk=k; x=char do while jj\==0 & kk\==0 /*one symbol for a not (¬) is a \ */ - if jj//3==1 & kk//3==1 then do /*in REXX: // ≡ division remainder*/ - xChar=' ' /*use a blank for this display line. */ - leave /*LEAVE terminates this DO WHILE. */ - end + if jj//3==1 then if kk//3==1 then do /*in REXX: // ≡ division remainder*/ + x=' ' /*use a blank for this display line. */ + leave /*LEAVE terminates this DO WHILE. */ + end jj=jj%3; kk=kk%3 /*in REXX: % ≡ integer division. */ end /*while*/ - z=z || xChar /*xChar is either black or white. */ + z=z || x /*xChar is either black or white. */ end /*k*/ /* [↑] " " " " blank. */ if length(z)<width then say z /*display the line if it fits on screen*/ diff --git a/Task/Sierpinski-carpet/Run-BASIC/sierpinski-carpet.run b/Task/Sierpinski-carpet/Run-BASIC/sierpinski-carpet.run deleted file mode 100644 index 069d282d3e..0000000000 --- a/Task/Sierpinski-carpet/Run-BASIC/sierpinski-carpet.run +++ /dev/null @@ -1,16 +0,0 @@ -dim c$(3) -c$(1) = "# # #" -c$(2) = "# #" -c$(3) = "# # #" - -for m = 1 to 6 - print "------ Order ";m;" ------------" - for k = 1 to m - for i = 1 to 3 - for j = 1 to m - print c$(i); - next j - print - next i - next k -next m diff --git a/Task/Sierpinski-carpet/Sinclair-ZX81-BASIC/sierpinski-carpet.sinclair b/Task/Sierpinski-carpet/Sinclair-ZX81-BASIC/sierpinski-carpet.sinclair new file mode 100644 index 0000000000..87d76d80f9 --- /dev/null +++ b/Task/Sierpinski-carpet/Sinclair-ZX81-BASIC/sierpinski-carpet.sinclair @@ -0,0 +1,18 @@ + 10 LET O=3 + 20 LET S=3**O + 30 FOR I=0 TO S-1 + 40 FOR J=0 TO S-1 + 50 LET X=J + 60 LET Y=I + 70 GOSUB 120 + 80 IF C THEN PLOT J,I + 90 NEXT J +100 NEXT I +110 GOTO 190 +120 LET C=0 +130 IF X-INT (X/3)*3=1 AND Y-INT (Y/3)*3=1 THEN RETURN +140 LET X=INT (X/3) +150 LET Y=INT (Y/3) +160 IF X>0 OR Y>0 THEN GOTO 130 +170 LET C=1 +180 RETURN diff --git a/Task/Sierpinski-carpet/Zkl/sierpinski-carpet-1.zkl b/Task/Sierpinski-carpet/Zkl/sierpinski-carpet-1.zkl new file mode 100644 index 0000000000..3d4c6d55b7 --- /dev/null +++ b/Task/Sierpinski-carpet/Zkl/sierpinski-carpet-1.zkl @@ -0,0 +1,8 @@ +fcn drawPat(x0,y0,s,img){ // Draw 3x3 pattern with hole in middle + foreach y,x in (3,3){ + if(x.isEven or y.isEven){ // don't draw middle pattern + if(s>1) self.fcn(x*s + x0, y*s + y0, s/3, img); // recurse + else img[x + x0, y + y0]=0xff0000; // red + } + } +} diff --git a/Task/Sierpinski-carpet/Zkl/sierpinski-carpet-2.zkl b/Task/Sierpinski-carpet/Zkl/sierpinski-carpet-2.zkl new file mode 100644 index 0000000000..7e6a81457a --- /dev/null +++ b/Task/Sierpinski-carpet/Zkl/sierpinski-carpet-2.zkl @@ -0,0 +1,3 @@ +img:=PPM(800,800); +drawPat(0,0,(3).pow(5),img); +img.write(File("foo.ppm","wb")); diff --git a/Task/Sierpinski-triangle-Graphical/Gnuplot/sierpinski-triangle-graphical.gnuplot b/Task/Sierpinski-triangle-Graphical/Gnuplot/sierpinski-triangle-graphical.gnuplot new file mode 100644 index 0000000000..e1dbfe7215 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Gnuplot/sierpinski-triangle-graphical.gnuplot @@ -0,0 +1,17 @@ +# triangle_x(n) and triangle_y(n) return X,Y coordinates for the +# Sierpinski triangle point number n, for integer n. +triangle_x(n) = (n > 0 ? 2*triangle_x(int(n/3)) + digit_to_x(int(n)%3) : 0) +triangle_y(n) = (n > 0 ? 2*triangle_y(int(n/3)) + digit_to_y(int(n)%3) : 0) +digit_to_x(d) = (d==0 ? 0 : d==1 ? -1 : 1) +digit_to_y(d) = (d==0 ? 0 : 1) + +# Plot the Sierpinski triangle to "level" many replications. +# "trange" and "samples" are chosen so the parameter t runs through +# integers t=0 to 3**level-1, inclusive. +# +level=6 +set trange [0:3**level-1] +set samples 3**level +set parametric +set key off +plot triangle_x(t), triangle_y(t) with points diff --git a/Task/Sierpinski-triangle-Graphical/JavaScript/sierpinski-triangle-graphical.js b/Task/Sierpinski-triangle-Graphical/JavaScript/sierpinski-triangle-graphical.js new file mode 100644 index 0000000000..39de0c45c4 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/JavaScript/sierpinski-triangle-graphical.js @@ -0,0 +1,57 @@ +<!-- SierpinskiTriangle.html --> +<html> +<head><title>Sierpinski Triangle Fractal + + + Please click to start and/or change color: +    +

    Sierpinski triangle fractal

    + + + diff --git a/Task/Sierpinski-triangle-Graphical/Kotlin/sierpinski-triangle-graphical.kotlin b/Task/Sierpinski-triangle-Graphical/Kotlin/sierpinski-triangle-graphical.kotlin index 7ca452d4a8..6eada3f21e 100644 --- a/Task/Sierpinski-triangle-Graphical/Kotlin/sierpinski-triangle-graphical.kotlin +++ b/Task/Sierpinski-triangle-Graphical/Kotlin/sierpinski-triangle-graphical.kotlin @@ -1,15 +1,17 @@ -import javax.swing.* import java.awt.* +import javax.swing.JFrame +import javax.swing.JPanel fun main(args: Array) { var i = 8 // Default - if (args.any()) + if (args.any()) { try { i = args.first().toInt() } catch (e: NumberFormatException) { i = 8 println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to $i") } + } object : JFrame("Sierpinsky Triangle - Kotlin") { val panel = object : JPanel() { @@ -21,8 +23,9 @@ fun main(args: Array) { public override fun paintComponent(g: Graphics) { g.color = Color.BLACK - if (g is Graphics2D) + if (g is Graphics2D) { g.drawSierpinskyTriangle(i, 20, 20, size - 40) + } } } diff --git a/Task/Sierpinski-triangle-Graphical/MATLAB/sierpinski-triangle-graphical-1.m b/Task/Sierpinski-triangle-Graphical/MATLAB/sierpinski-triangle-graphical-1.m new file mode 100644 index 0000000000..1478ef123c --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/MATLAB/sierpinski-triangle-graphical-1.m @@ -0,0 +1,5 @@ +[x, x0] = deal(cat(3, [1 0]', [-1 0]', [0 sqrt(3)]')); +for k = 1 : 6 + x = x(:,:) + x0 * 2 ^ k / 2; +end +patch('Faces', reshape(1 : 3 * 3 ^ k, 3, '')', 'Vertices', x(:,:)') diff --git a/Task/Sierpinski-triangle-Graphical/MATLAB/sierpinski-triangle-graphical-2.m b/Task/Sierpinski-triangle-Graphical/MATLAB/sierpinski-triangle-graphical-2.m new file mode 100644 index 0000000000..386a3223f4 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/MATLAB/sierpinski-triangle-graphical-2.m @@ -0,0 +1,2 @@ +t = 0 : 2^16 - 1; +plot(t, bitand(t, bitshift(t, -8)), 'k.') diff --git a/Task/Sierpinski-triangle-Graphical/Phix/sierpinski-triangle-graphical.phix b/Task/Sierpinski-triangle-Graphical/Phix/sierpinski-triangle-graphical.phix new file mode 100644 index 0000000000..b899447c77 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Phix/sierpinski-triangle-graphical.phix @@ -0,0 +1,70 @@ +-- +-- demo\rosetta\SierpinskyTriangle.exw +-- +include pGUI.e + +Ihandle dlg, canvas +cdCanvas cddbuffer, cdcanvas + +procedure SierpinskyTriangle(integer level, atom x, atom y, atom w, atom h) + atom w2 = w/2, w4 = w/4, h2 = h/2 + if level=1 then + cdCanvasBegin(cddbuffer,CD_CLOSED_LINES) + cdCanvasVertex(cddbuffer, x, y) + cdCanvasVertex(cddbuffer, x+w2, y+h) + cdCanvasVertex(cddbuffer, x+w, y) + cdCanvasEnd(cddbuffer) + else + SierpinskyTriangle(level-1, x, y, w2, h2) + SierpinskyTriangle(level-1, x+w4, y+h2, w2, h2) + SierpinskyTriangle(level-1, x+w2, y, w2, h2) + end if +end procedure + +integer level = 7 + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) + integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE") + cdCanvasActivate(cddbuffer) + cdCanvasClear(cddbuffer) + SierpinskyTriangle(level, w*0.05, h*0.05, w*0.9, h*0.9) + cdCanvasFlush(cddbuffer) + IupSetStrAttribute(dlg, "TITLE", "Sierpinsky Triangle (level %d)",{level}) + return IUP_DEFAULT +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + cdCanvasSetBackground(cddbuffer, CD_WHITE) + cdCanvasSetForeground(cddbuffer, CD_GRAY) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + if find(c,"+-") then + level = max(1,min(12,level+','-c)) + IupRedraw(canvas) + end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "640x640") + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", "Sierpinsky Triangle") + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + + IupShow(dlg) + IupSetAttribute(canvas, "RASTERSIZE", NULL) + IupMainLoop() + IupClose() +end procedure +main() diff --git a/Task/Sierpinski-triangle-Graphical/R/sierpinski-triangle-graphical.r b/Task/Sierpinski-triangle-Graphical/R/sierpinski-triangle-graphical.r new file mode 100644 index 0000000000..f3fb3b3eb4 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/R/sierpinski-triangle-graphical.r @@ -0,0 +1,20 @@ +## Plotting Sierpinski triangle. aev 4/1/17 +## ord - order, fn - file name, ttl - plot title, clr - color +pSierpinskiT <- function(ord, fn="", ttl="", clr="navy") { + m=640; abbr="STR"; dftt="Sierpinski triangle"; + n=2^ord; M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE); + cat(" *** START", abbr, date(), "\n"); + if(fn=="") {pf=paste0(abbr,"o", ord)} else {pf=paste0(fn, ".png")}; + if(ttl!="") {dftt=ttl}; ttl=paste0(dftt,", order ", ord); + cat(" *** Plot file:", pf,".png", "title:", ttl, "\n"); + for(y in 1:n) { + for(x in 1:n) { + if(bitwAnd(x, y)==0) {M[x,y]=1} + ##if(bitwAnd(x, y)>0) {M[x,y]=1} ## Try this for "reversed" ST + }} + plotmat(M, pf, clr, ttl); + cat(" *** END", abbr, date(), "\n"); +} +## Executing: +pSierpinskiT(6,,,"red"); +pSierpinskiT(8); diff --git a/Task/Sierpinski-triangle-Graphical/Sidef/sierpinski-triangle-graphical.sidef b/Task/Sierpinski-triangle-Graphical/Sidef/sierpinski-triangle-graphical.sidef index 94ebd65123..121a1d3cb6 100644 --- a/Task/Sierpinski-triangle-Graphical/Sidef/sierpinski-triangle-graphical.sidef +++ b/Task/Sierpinski-triangle-Graphical/Sidef/sierpinski-triangle-graphical.sidef @@ -1,7 +1,7 @@ func sierpinski_triangle(n) -> Array { var triangle = ['*'] { |i| - var sp = (' ' * Math.pow(2, i-1)); + var sp = (' ' * 2**i) triangle = (triangle.map {|x| sp + x + sp} + triangle.map {|x| x + ' ' + x}) } * n diff --git a/Task/Sierpinski-triangle-Graphical/Zkl/sierpinski-triangle-graphical.zkl b/Task/Sierpinski-triangle-Graphical/Zkl/sierpinski-triangle-graphical.zkl new file mode 100644 index 0000000000..a71ff177aa --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Zkl/sierpinski-triangle-graphical.zkl @@ -0,0 +1,4 @@ +const Order=8, Size=(1).shiftLeft(Order); +img:=PPM(300,300); +foreach y,x in (Size,Size){ if(x.bitAnd(y)==0) img[x,y]=0xff0000 } +img.write(File("sierpinskiTriangle.ppm","wb")); diff --git a/Task/Sierpinski-triangle/AppleScript/sierpinski-triangle-1.applescript b/Task/Sierpinski-triangle/AppleScript/sierpinski-triangle-1.applescript new file mode 100644 index 0000000000..c18dc20a41 --- /dev/null +++ b/Task/Sierpinski-triangle/AppleScript/sierpinski-triangle-1.applescript @@ -0,0 +1,103 @@ +-- SIERPINKSI TRIANGLE ------------------------------------------------------- + +-- sierpinski :: Int -> [String] +on sierpinski(n) + if n > 0 then + set previous to sierpinski(n - 1) + set padding to replicate(2 ^ (n - 1), space) + + script alignedCentre + on |λ|(s) + concat(padding & s & padding) + end |λ| + end script + + script adjacentDuplicates + on |λ|(s) + unwords(replicate(2, s)) + end |λ| + end script + + -- Previous triangle block centered, + -- and placed on 2 adjacent duplicates. + map(alignedCentre, previous) & map(adjacentDuplicates, previous) + else + {"*"} + end if +end sierpinski + + +-- TEST ---------------------------------------------------------------------- +on run + unlines(sierpinski(4)) +end run + +-- GENERIC FUNCTIONS --------------------------------------------------------- + +-- concat :: [[a]] -> [a] | [String] -> String +on concat(xs) + if length of xs > 0 and class of (item 1 of xs) is string then + set acc to "" + else + set acc to {} + end if + repeat with i from 1 to length of xs + set acc to acc & item i of xs + end repeat + acc +end concat + +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- replicate :: Int -> a -> [a] +on replicate(n, a) + set out to {} + if n < 1 then return out + set dbl to {a} + + repeat while (n > 1) + if (n mod 2) > 0 then set out to out & dbl + set n to (n div 2) + set dbl to (dbl & dbl) + end repeat + return out & dbl +end replicate + +-- unlines, unwords :: [String] -> String +on unlines(xs) + intercalate(linefeed, xs) +end unlines + +on unwords(xs) + intercalate(space, xs) +end unwords diff --git a/Task/Sierpinski-triangle/AppleScript/sierpinski-triangle-2.applescript b/Task/Sierpinski-triangle/AppleScript/sierpinski-triangle-2.applescript new file mode 100644 index 0000000000..6d389a63f8 --- /dev/null +++ b/Task/Sierpinski-triangle/AppleScript/sierpinski-triangle-2.applescript @@ -0,0 +1,147 @@ +-- SIERPINSKI TRIANGLE BY XOR / RULE 90 -------------------------------------- + +-- sierpinskiTriangle :: Int -> String +on sierpinskiTriangle(intOrder) + + -- A Sierpinski triangle of order N + -- is a Pascal triangle (of N^2 rows) + -- mod 2 + + -- pascalModTwo :: Int -> [[String]] + script pascalModTwo + on |λ|(intRows) + + -- addRow [[Int]] -> [[Int]] + script addRow + + -- nextRow :: [Int] -> [Int] + on nextRow(row) + -- The composition of AsciiBinary . mod two . add + -- is reduced here to a rule from + -- two parent characters above, + -- to the child character below. + + -- Rule 90 also reduces to this XOR relationship + -- between left and right neighbours. + + -- rule :: Character -> Character -> Character + script rule + on |λ|(a, b) + if a = b then + space + else + "*" + end if + end |λ| + end script + + zipWith(rule, {" "} & row, row & {" "}) + end nextRow + + on |λ|(xs) + xs & {nextRow(item -1 of xs)} + end |λ| + end script + + foldr(addRow, {{"*"}}, enumFromTo(1, intRows - 1)) + end |λ| + end script + + -- The centring foldr (fold right) below starts from the end of the list, + -- (the base of the triangle) which has zero indent. + + -- Each preceding row has one more indent space than the row below it. + + script centred + on |λ|(sofar, row) + set strIndent to indent of sofar + + {triangle:strIndent & intercalate(space, row) & linefeed & ¬ + triangle of sofar, indent:strIndent & space} + end |λ| + end script + + triangle of foldr(centred, {triangle:"", indent:""}, ¬ + pascalModTwo's |λ|(intOrder ^ 2)) + +end sierpinskiTriangle + + +-- TEST ---------------------------------------------------------------------- +on run + + set strTriangle to sierpinskiTriangle(4) + + set the clipboard to strTriangle + strTriangle +end run + + +-- GENERIC FUNCTIONS --------------------------------------------------------- + +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo + +-- foldr :: (a -> b -> a) -> a -> [b] -> a +on foldr(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from lng to 1 by -1 + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldr + +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + +-- min :: Ord a => a -> a -> a +on min(x, y) + if y < x then + y + else + x + end if +end min + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] +on zipWith(f, xs, ys) + set lng to min(length of xs, length of ys) + set lst to {} + tell mReturn(f) + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, item i of ys) + end repeat + return lst + end tell +end zipWith diff --git a/Task/Sierpinski-triangle/AppleScript/sierpinski-triangle.applescript b/Task/Sierpinski-triangle/AppleScript/sierpinski-triangle.applescript deleted file mode 100644 index 9364cc72ca..0000000000 --- a/Task/Sierpinski-triangle/AppleScript/sierpinski-triangle.applescript +++ /dev/null @@ -1,149 +0,0 @@ --- sierpinskiTriangle :: Int -> String -on sierpinskiTriangle(intOrder) - - -- A Sierpinski triangle of order N - -- is a Pascal triangle (of N^2 rows) - -- mod 2 - - -- pascalModTwo :: Int -> [[String]] - script pascalModTwo - on lambda(intRows) - - -- addRow [[Int]] -> [[Int]] - script addRow - - -- nextRow :: [Int] -> [Int] - on nextRow(row) - -- The composition of AsciiBinary . mod two . add - -- is reduced here to a rule from - -- two parent characters above, - -- to the child character below. - - -- Rule 90 also reduces to this XOR relationship - -- between left and right neighbours. - - -- rule :: Character -> Character -> Character - script rule - on lambda(a, b) - cond(a = b, space, "*") - end lambda - end script - - zipWith(rule, {" "} & row, row & {" "}) - end nextRow - - on lambda(xs) - xs & {nextRow(item -1 of xs)} - end lambda - end script - - foldr(addRow, {{"*"}}, range(1, intRows - 1)) - end lambda - end script - - -- The centring foldr (fold right) below starts from the end of the list, - -- (the base of the triangle) which has zero indent. - - -- Each preceding row has one more indent space than the row below it. - - script centred - on lambda(sofar, row) - set strIndent to indent of sofar - - {triangle:strIndent & intercalate(space, row) & linefeed & ¬ - triangle of sofar, indent:strIndent & space} - end lambda - end script - - triangle of foldr(centred, {triangle:"", indent:""}, ¬ - pascalModTwo's lambda(intOrder ^ 2)) - -end sierpinskiTriangle - - --- TEST -on run - - set strTriangle to sierpinskiTriangle(4) - - set the clipboard to strTriangle - - strTriangle - -end run - - --- GENERIC LIBRARY FUNCTIONS - --- foldr :: (a -> b -> a) -> a -> [b] -> a -on foldr(f, startValue, xs) - tell mReturn(f) - set v to startValue - set lng to length of xs - repeat with i from lng to 1 by -1 - set v to lambda(v, item i of xs, i, xs) - end repeat - return v - end tell -end foldr - --- intercalate :: Text -> [Text] -> Text -on intercalate(strText, lstText) - set {dlm, my text item delimiters} to {my text item delimiters, strText} - set strJoined to lstText as text - set my text item delimiters to dlm - return strJoined -end intercalate - --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn - --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then - set d to -1 - else - set d to 1 - end if - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range - --- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -on zipWith(f, xs, ys) - set nx to length of xs - set ny to length of ys - if nx < 1 or ny < 1 then - {} - else - set lng to cond(nx < ny, nx, ny) - set lst to {} - tell mReturn(f) - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, item i of ys) - end repeat - return lst - end tell - end if -end zipWith - --- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b) -on cond(bool, f, g) - if bool then - f - else - g - end if -end cond diff --git a/Task/Sierpinski-triangle/Gnuplot/sierpinski-triangle.gnuplot b/Task/Sierpinski-triangle/Gnuplot/sierpinski-triangle.gnuplot new file mode 100644 index 0000000000..2a2bc0a071 --- /dev/null +++ b/Task/Sierpinski-triangle/Gnuplot/sierpinski-triangle.gnuplot @@ -0,0 +1,16 @@ +# Return a string space or star to print at x,y. +# Must have x=0 && ((y+x)%2)==0 && ((y+x)&(y-x))==0 ? "*" : " ") + +# Return a string which is row y of the triangle from character +# position x through to the right hand end x==y, inclusive. +row(x,y) = (x<=y ? char(x,y).row(x+1,y) : "\n") + +# Return a string of stars, spaces and newlines which is the +# Sierpinski triangle from row y to limit, inclusive. +# The first row is y=0. +triangle(y,limit) = (y <= limit ? row(-limit,y).triangle(y+1,limit) : "") + +# Print rows 0 to 15, which is the order 4 triangle per the task. +print triangle(0,15) diff --git a/Task/Sierpinski-triangle/Haskell/sierpinski-triangle-2.hs b/Task/Sierpinski-triangle/Haskell/sierpinski-triangle-2.hs index d71aa7ef5b..1bc5886d36 100644 --- a/Task/Sierpinski-triangle/Haskell/sierpinski-triangle-2.hs +++ b/Task/Sierpinski-triangle/Haskell/sierpinski-triangle-2.hs @@ -1,9 +1,13 @@ -import Data.Bits ((.&.)) +import Data.List (intercalate) -sierpinski n = map row [m, m-1 .. 0] where - m = 2^n - 1 - row y = replicate y ' ' ++ concatMap cell [0..m - y] where - cell x | y .&. x == 0 = " *" - | otherwise = " " +sierpinski :: Int -> [String] +sierpinski 0 = ["▲"] +sierpinski n = + concat $ + (<$> sierpinski (n - 1)) <$> -- Previous triangle, + [ flip intercalate ([replicate (2 ^ (n - 1))] <*> " -") -- centred, + , (++) <*> ('+' :) -- above singly spaced duplicates. + ] +main :: IO () main = mapM_ putStrLn $ sierpinski 4 diff --git a/Task/Sierpinski-triangle/Haskell/sierpinski-triangle-3.hs b/Task/Sierpinski-triangle/Haskell/sierpinski-triangle-3.hs index 44f17c1eb4..d71aa7ef5b 100644 --- a/Task/Sierpinski-triangle/Haskell/sierpinski-triangle-3.hs +++ b/Task/Sierpinski-triangle/Haskell/sierpinski-triangle-3.hs @@ -1,16 +1,9 @@ -import Data.List (intersperse) +import Data.Bits ((.&.)) -sierpinski :: Int -> String -sierpinski n = let +sierpinski n = map row [m, m-1 .. 0] where + m = 2^n - 1 + row y = replicate y ' ' ++ concatMap cell [0..m - y] where + cell x | y .&. x == 0 = " *" + | otherwise = " " - -- Top down, each row after the first is an XOR rewrite - rule90 n = (scanl next ['*'] [1..n-1]) where - next line _ = zipWith xor (" " ++ line) (line ++ " ") - xor l r | l == r = ' ' | otherwise = '*' - - -- Bottom up, each line above the base is indented 1 more space - in fst (foldr spacing ("", "") (rule90 (2^n))) where - spacing x (s, w) = - (concat [w, intersperse ' ' x, "\n", s], w ++ " ") - -main = putStr $ sierpinski 4 +main = mapM_ putStrLn $ sierpinski 4 diff --git a/Task/Sierpinski-triangle/Haskell/sierpinski-triangle-4.hs b/Task/Sierpinski-triangle/Haskell/sierpinski-triangle-4.hs new file mode 100644 index 0000000000..0a1f24fad4 --- /dev/null +++ b/Task/Sierpinski-triangle/Haskell/sierpinski-triangle-4.hs @@ -0,0 +1,17 @@ +import Data.List (intersperse) + +-- Top down, each row after the first is an XOR / Rule90 rewrite. +-- Bottom up, each line above the base is indented 1 more space. +sierpinski :: Int -> String +sierpinski = fst . foldr spacing ([], []) . rule90 . (2 ^) + where + rule90 = scanl next "*" . enumFromTo 1 . subtract 1 + where + next = const . ((zipWith xor . (' ' :)) <*> (++ " ")) + xor l r + | l == r = ' ' + | otherwise = '*' + spacing x (s, w) = (concat [w, intersperse ' ' x, "\n", s], w ++ " ") + +main :: IO () +main = putStr $ sierpinski 4 diff --git a/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle-3.js b/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle-3.js index 0444cef9dc..e7f4fbb682 100644 --- a/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle-3.js +++ b/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle-3.js @@ -1,67 +1,62 @@ -// A Sierpinski triangle of order N, -// constructed as 2^N lines of Pascal's triangle mod 2 -// and mapped to centred {1:asterisk, 0:space} strings +(() => { + 'use strict'; -(order => { + // LINES OF SIERPINSKI TRIANGLE AT LEVEL N ------------------------------- - // sierpinski :: Int -> [Bool] - let sierpinski = intOrder => { + // sierpinski :: Int -> [String] + const sierpTriangle = n => + // Previous triangle centered with left and right padding, + (n > 0) ? concat(ap([ + map(xs => intercalate(xs, ap( + [s => concat(replicate(Math.pow(2, (n - 1)), s))], [' ', '-'] + ))), - // asciiPascalMod2 :: Int -> [[Int]] - let asciiPascalMod2 = nRows => - range(1, nRows - 1) - .reduce(sofar => { - let lstPrev = sofar.slice(-1)[0]; + // above a pair of duplicates, placed one character apart. + map(xs => intercalate('+', [xs, xs])) + ], [sierpTriangle(n - 1)])) : ['▲']; - // The composition of (asciiBinary . mod 2 . add) - // is reduced here to a rule from two parent characters - // to a single child character. - // Rule 90 also reduces to the same XOR - // relationship between left and right neighbours. + // GENERIC FUNCTIONS ----------------------------------------------------- - return sofar - .concat([zipWith( - (left, right) => left === right ? ' ' : '*', - [' '].concat(lstPrev), - lstPrev.concat(' ') - )]); - }, [ - ['*'] // Tip of triangle - ]); - - // Reduce/folding from the last item (base of list) - // which has zero left indent. - - // Each preceding row has one more indent space than the row beneath it - return asciiPascalMod2(Math.pow(2, intOrder)) - .reduceRight((a, x) => { - return { - triangle: a.indent + x.join(' ') + '\n' + a.triangle, - indent: a.indent + ' ' - } - }, { - triangle: '', - indent: '' - }).triangle + // replicate :: Int -> a -> [a] + const replicate = (n, a) => { + let v = [a], + o = []; + if (n < 1) return o; + while (n > 1) { + if (n & 1) o = o.concat(v); + n >>= 1; + v = v.concat(v); + } + return o.concat(v); }; - // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] - let zipWith = (f, xs, ys) => - xs.length === ys.length ? ( - xs.map((x, i) => f(x, ys[i])) - ) : undefined, + // curry :: ((a, b) -> c) -> a -> b -> c + const curry = f => a => b => f(a, b); - // range(intFrom, intTo, optional intStep) - // Int -> Int -> Maybe Int -> [Int] - range = (m, n, step) => { - let d = (step || 1) * (n >= m ? 1 : -1); + // map :: (a -> b) -> [a] -> [b] + const map = curry((f, xs) => xs.map(f)); - return Array.from({ - length: Math.floor((n - m) / d) + 1 - }, (_, i) => m + (i * d)); - }; + // Apply a list of functions to a list of arguments + // <*> :: [(a -> b)] -> [a] -> [b] + const ap = (fs, xs) => // + [].concat.apply([], fs.map(f => // + [].concat.apply([], xs.map(x => [f(x)])))); - return sierpinski(order); + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); -})(4); + // intercalate :: String -> [a] -> String + const intercalate = (s, xs) => xs.join(s); + + // concat :: [[a]] -> [a] || [String] -> String + const concat = xs => { + if (xs.length > 0) { + const unit = typeof xs[0] === 'string' ? '' : []; + return unit.concat.apply(unit, xs); + } else return []; + }; + + // TEST ------------------------------------------------------------------ + return unlines(sierpTriangle(4)); +})(); diff --git a/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle-4.js b/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle-4.js new file mode 100644 index 0000000000..3e8f06ec85 --- /dev/null +++ b/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle-4.js @@ -0,0 +1,62 @@ +(order => { + // sierpinski :: Int -> [Bool] + let sierpinski = intOrder => { + + // asciiPascalMod2 :: Int -> [[Int]] + let asciiPascalMod2 = nRows => + range(1, nRows - 1) + .reduce(sofar => { + let lstPrev = sofar.slice(-1)[0]; + + // The composition of (asciiBinary . mod 2 . add) + // is reduced here to a rule from two parent characters + // to a single child character. + + // Rule 90 also reduces to the same XOR + // relationship between left and right neighbours. + + return sofar + .concat([zipWith( + (left, right) => left === right ? ' ' : '*', + [' '].concat(lstPrev), + lstPrev.concat(' ') + )]); + }, [ + ['*'] // Tip of triangle + ]); + + // Reduce/folding from the last item (base of list) + // which has zero left indent. + + // Each preceding row has one more indent space than the row beneath it + return asciiPascalMod2(Math.pow(2, intOrder)) + .reduceRight((a, x) => { + return { + triangle: a.indent + x.join(' ') + '\n' + a.triangle, + indent: a.indent + ' ' + } + }, { + triangle: '', + indent: '' + }).triangle + }; + + // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] + let zipWith = (f, xs, ys) => + xs.length === ys.length ? ( + xs.map((x, i) => f(x, ys[i])) + ) : undefined, + + // range(intFrom, intTo, optional intStep) + // Int -> Int -> Maybe Int -> [Int] + range = (m, n, step) => { + let d = (step || 1) * (n >= m ? 1 : -1); + + return Array.from({ + length: Math.floor((n - m) / d) + 1 + }, (_, i) => m + (i * d)); + }; + + return sierpinski(order); + +})(4); diff --git a/Task/Sierpinski-triangle/Kotlin/sierpinski-triangle.kotlin b/Task/Sierpinski-triangle/Kotlin/sierpinski-triangle.kotlin new file mode 100644 index 0000000000..0e9d9bd990 --- /dev/null +++ b/Task/Sierpinski-triangle/Kotlin/sierpinski-triangle.kotlin @@ -0,0 +1,12 @@ +// version 1.1.2 + +const val ORDER = 4 +const val SIZE = 1 shl ORDER + +fun main(args: Array) { + for (y in SIZE - 1 downTo 0) { + for (i in 0 until y) print(" ") + for (x in 0 until SIZE - y) print(if ((x and y) != 0) " " else "* ") + println() + } +} diff --git a/Task/Sierpinski-triangle/MATLAB/sierpinski-triangle-1.m b/Task/Sierpinski-triangle/MATLAB/sierpinski-triangle-1.m new file mode 100644 index 0000000000..3f768c22ba --- /dev/null +++ b/Task/Sierpinski-triangle/MATLAB/sierpinski-triangle-1.m @@ -0,0 +1,7 @@ +n = 4; +d = string('*'); +for k = 0 : n - 1 + sp = repelem(' ', 2 ^ k); + d = [sp + d + sp, d + ' ' + d]; +end +disp(d.join(char(10))) diff --git a/Task/Sierpinski-triangle/MATLAB/sierpinski-triangle-2.m b/Task/Sierpinski-triangle/MATLAB/sierpinski-triangle-2.m new file mode 100644 index 0000000000..8bdc220853 --- /dev/null +++ b/Task/Sierpinski-triangle/MATLAB/sierpinski-triangle-2.m @@ -0,0 +1,6 @@ +n = 2 ^ 4 - 1; +tr = + ~(-n : n); +for k = 1:n + tr(k + 1, :) = bitget(90, 1 + filter2([4 2 1], tr(k, :))); +end +char(10 * tr + 32) diff --git a/Task/Sierpinski-triangle/Ring/sierpinski-triangle.ring b/Task/Sierpinski-triangle/Ring/sierpinski-triangle.ring new file mode 100644 index 0000000000..bb9325691b --- /dev/null +++ b/Task/Sierpinski-triangle/Ring/sierpinski-triangle.ring @@ -0,0 +1,25 @@ +# Project : Sierpinski triangle +# Date : 2017/09/20 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +norder=4 +xy = list(40) +for i = 1 to 40 + xy[i] = " " +next +triangle(1, 1, norder) +for i = 1 to 36 + see xy[i] + nl +next + +func triangle(x, y, n) + if n = 0 + xy[y] = left(xy[y],x-1) + "*" + substr(xy[y],x+1) + else + n=n-1 + length=pow(2,n) + triangle(x, y+length, n) + triangle(x+length, y, n) + triangle(x+length*2, y+length, n) + ok diff --git a/Task/Sierpinski-triangle/Sidef/sierpinski-triangle.sidef b/Task/Sierpinski-triangle/Sidef/sierpinski-triangle.sidef index 0730afe8ba..28e4f09a6e 100644 --- a/Task/Sierpinski-triangle/Sidef/sierpinski-triangle.sidef +++ b/Task/Sierpinski-triangle/Sidef/sierpinski-triangle.sidef @@ -1,11 +1,11 @@ func sierpinski_triangle(n) { - var triangle = ['*']; + var triangle = ['*'] { |i| - var sp = (' ' * Math.pow(2, i-1)); + var sp = (' ' * 2**i) triangle = (triangle.map {|x| sp + x + sp} + - triangle.map {|x| x + ' ' + x}); - } * n; - triangle.join("\n"); + triangle.map {|x| x + ' ' + x}) + } * n + triangle.join("\n") } - -say sierpinski_triangle(4); +  +say sierpinski_triangle(4) diff --git a/Task/Sierpinski-triangle/Zkl/sierpinski-triangle.zkl b/Task/Sierpinski-triangle/Zkl/sierpinski-triangle.zkl new file mode 100644 index 0000000000..60a1ef65a0 --- /dev/null +++ b/Task/Sierpinski-triangle/Zkl/sierpinski-triangle.zkl @@ -0,0 +1,7 @@ +level,d := 3,T("*"); +foreach n in (level + 1){ + sp:=" "*(2).pow(n); + d=d.apply('wrap(a){ String(sp,a,sp) }).extend( + d.apply(fcn(a){ String(a," ",a) })); +} +d.concat("\n").println(); diff --git a/Task/Sieve-of-Eratosthenes/00DESCRIPTION b/Task/Sieve-of-Eratosthenes/00DESCRIPTION index abfefe5f14..966d73fefb 100644 --- a/Task/Sieve-of-Eratosthenes/00DESCRIPTION +++ b/Task/Sieve-of-Eratosthenes/00DESCRIPTION @@ -16,9 +16,14 @@ If there's an easy way to add such a wheel based optimization, implement it as a ;Related tasks: -*   [[Primality by trial division]]. -*   [[Sequence of primes by Trial Division]]. -*   [[Prime decomposition]]. -*   [[Extensible prime generator]]. -*   [[Emirp primes]]. +*   [[Emirp primes]] +*   [[count in factors]] +*   [[prime decomposition]] +*   [[factors of an integer]] +*   [[extensible prime generator]] +*   [[primality by trial division]] +*   [[factors of a Mersenne number]] +*   [[trial factoring of a Mersenne number]] +*   [[partition an integer X into N primes]] +*   [[sequence of primes by Trial Division]]

    diff --git a/Task/Sieve-of-Eratosthenes/AWK/sieve-of-eratosthenes.awk b/Task/Sieve-of-Eratosthenes/AWK/sieve-of-eratosthenes-1.awk similarity index 100% rename from Task/Sieve-of-Eratosthenes/AWK/sieve-of-eratosthenes.awk rename to Task/Sieve-of-Eratosthenes/AWK/sieve-of-eratosthenes-1.awk diff --git a/Task/Sieve-of-Eratosthenes/AWK/sieve-of-eratosthenes-2.awk b/Task/Sieve-of-Eratosthenes/AWK/sieve-of-eratosthenes-2.awk new file mode 100644 index 0000000000..28ff8d1ef1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/AWK/sieve-of-eratosthenes-2.awk @@ -0,0 +1,11 @@ +BEGIN { ULIMIT=100 + +for ( n=1 ; (n++) < ULIMIT ; ) + if (n in S) { + p = S[n] + delete S[n] + for ( m = n ; (m += p) in S ; ) { } + S[m] = p + } + else print ( S[(n+n)] = n ) +} diff --git a/Task/Sieve-of-Eratosthenes/ActionScript/sieve-of-eratosthenes.as b/Task/Sieve-of-Eratosthenes/ActionScript/sieve-of-eratosthenes.as new file mode 100644 index 0000000000..b45f88888a --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/ActionScript/sieve-of-eratosthenes.as @@ -0,0 +1,24 @@ +function eratosthenes(limit:int):Array +{ + var primes:Array = new Array(); + if (limit >= 2) { + var sqrtlmt:int = int(Math.sqrt(limit) - 2); + var nums:Array = new Array(); // start with an empty Array... + for (var i:int = 2; i <= limit; i++) // and + nums.push(i); // only initialize the Array once... + for (var j:int = 0; j <= sqrtlmt; j++) { + var p:int = nums[j] + if (p) + for (var t:int = p * p - 2; t < nums.length; t += p) + nums[t] = 0; + } + for (var m:int = 0; m < nums.length; m++) { + var r:int = nums[m]; + if (r) + primes.push(r); + } + } + return primes; +} +var e:Array = eratosthenes(1000); +trace(e); diff --git a/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-5.basic b/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-5.basic index 62e826386b..97c6dcbbaa 100644 --- a/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-5.basic +++ b/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-5.basic @@ -1,12 +1,13 @@ -10 INPUT "Enter number to search to: ";l -20 DIM p(l) -30 FOR n=2 TO SQR l -40 IF p(n)<>0 THEN NEXT n -50 FOR k=n*n TO l STEP n -60 LET p(k)=1 -70 NEXT k -80 NEXT n -90 REM Display the primes -100 FOR n=2 TO l -110 IF p(n)=0 THEN PRINT n;", "; -120 NEXT n + 10 INPUT L + 20 FAST + 30 DIM N(L) + 40 FOR I=2 TO SQR L + 50 IF N(I) THEN GOTO 90 + 60 FOR J=I+I TO L STEP I + 70 LET N(J)=1 + 80 NEXT J + 90 NEXT I +100 SLOW +110 FOR I=2 TO L +120 IF NOT N(I) THEN PRINT I;" "; +130 NEXT I diff --git a/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-6.basic b/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-6.basic new file mode 100644 index 0000000000..62e826386b --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-6.basic @@ -0,0 +1,12 @@ +10 INPUT "Enter number to search to: ";l +20 DIM p(l) +30 FOR n=2 TO SQR l +40 IF p(n)<>0 THEN NEXT n +50 FOR k=n*n TO l STEP n +60 LET p(k)=1 +70 NEXT k +80 NEXT n +90 REM Display the primes +100 FOR n=2 TO l +110 IF p(n)=0 THEN PRINT n;", "; +120 NEXT n diff --git a/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes-1.cmake b/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes-1.cmake deleted file mode 100644 index f393b5d6c1..0000000000 --- a/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes-1.cmake +++ /dev/null @@ -1,35 +0,0 @@ -function(eratosthenes var limit) - # Check for integer overflow. With CMake using 32-bit signed integer, - # this check fails when limit > 46340. - if(NOT limit EQUAL 0) # Avoid division by zero. - math(EXPR i "(${limit} * ${limit}) / ${limit}") - if(NOT limit EQUAL ${i}) - message(FATAL_ERROR "limit is too large, would cause integer overflow") - endif() - endif() - - # Use local variables prime_2, prime_3, ..., prime_${limit} as array. - # Initialize array to y => yes it is prime. - foreach(i RANGE 2 ${limit}) - set(prime_${i} y) - endforeach(i) - - # Gather a list of prime numbers. - set(list) - foreach(i RANGE 2 ${limit}) - if(prime_${i}) - # Append this prime to list. - list(APPEND list ${i}) - - # For each multiple of i, set n => no it is not prime. - # Optimization: start at i squared. - math(EXPR square "${i} * ${i}") - if(NOT square GREATER ${limit}) # Avoid fatal error. - foreach(m RANGE ${square} ${limit} ${i}) - set(prime_${m} n) - endforeach(m) - endif() - endif(prime_${i}) - endforeach(i) - set(${var} ${list} PARENT_SCOPE) -endfunction(eratosthenes) diff --git a/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes-2.cmake b/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes-2.cmake deleted file mode 100644 index 00a57372d4..0000000000 --- a/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes-2.cmake +++ /dev/null @@ -1,3 +0,0 @@ -# Print all prime numbers through 100. -eratosthenes(primes 100) -message(STATUS "${primes}") diff --git a/Task/Sieve-of-Eratosthenes/EC/sieve-of-eratosthenes.ec b/Task/Sieve-of-Eratosthenes/EC/sieve-of-eratosthenes.ec new file mode 100644 index 0000000000..2cb9ec750d --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/EC/sieve-of-eratosthenes.ec @@ -0,0 +1,43 @@ +public class FindPrime +{ + Array primeList { [ 2 ], minAllocSize = 64 }; + int index; + + index = 3; + + bool HasPrimeFactor(int x) + { + int max = (int)floor(sqrt((double)x)); + + for(i : primeList) + { + if(i > max) break; + if(x % i == 0) return true; + } + return false; + } + + public int GetPrime(int x) + { + if(x > primeList.count - 1) + { + for (; primeList.count != x; index += 2) + if(!HasPrimeFactor(index)) + { + if(primeList.count >= primeList.minAllocSize) primeList.minAllocSize *= 2; + primeList.Add(index); + } + } + return primeList[x-1]; + } +} + +class PrimeApp : Application +{ + FindPrime fp { }; + void Main() + { + int num = argc > 1 ? atoi(argv[1]) : 1; + PrintLn(fp.GetPrime(num)); + } +} diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-1.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-1.fs index 6783f1256b..735a8f2eb6 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-1.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-1.fs @@ -1,20 +1,12 @@ -type CIS<'T> = struct val v:'T val cont:unit->CIS<'T> //'Co Inductive Stream for laziness - new (v,cont) = { v = v; cont = cont } end -type Primes = uint32 - -let primesBird() = - let rec (^^) (xs: CIS) (ys: CIS) = // stream merge function - let x = xs.v in let y = ys.v - if x < y then CIS(x, fun() -> xs.cont() ^^ ys) - elif y < x then CIS(y, fun() -> xs ^^ ys.cont()) - else CIS(x, fun() -> xs.cont() ^^ ys.cont()) // no duplications - let pmltpls p = let rec nxt c = CIS(c, fun() -> nxt (c + p)) in nxt (p * p) - let rec allmltps (ps: CIS) = CIS(pmltpls ps.v, fun() -> allmltps (ps.cont())) - let rec cmpsts (css: CIS>) = - CIS(css.v.v, fun() -> (css.v.cont()) ^^ (cmpsts (css.cont()))) - let rec minusat n (cs: CIS) = - if n < cs.v then CIS(n, fun() -> minusat (n + 1u) cs) - else minusat (n + 1u) (cs.cont()) - let rec baseprms() = CIS(2u, fun() -> minusat 3u (cmpsts (allmltps (baseprms())))) - Seq.unfold (fun (ps: CIS) -> Some(ps.v, ps.cont())) - (minusat 2u (cmpsts (allmltps (baseprms())))) +(* + An interesting implementation of The Sieve of Eratosthenes. + Nigel Galloway April 7th., 2017. +*) +let SofE = + let rec fn n g = seq{ match n with + |1 -> yield false; yield! fn g g + |_ -> yield true; yield! fn (n-1) g} + let rec fg ng = seq{ + let g = (Seq.findIndex(id) ng)+2 + yield g; yield! fg (Seq.cache(Seq.map2(&&) ng (fn (g-1) g)))} + fg (Seq.initInfinite(fun x->true)) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-10.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-10.fs index 7093f14210..4c9836434c 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-10.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-10.fs @@ -1,8 +1,9 @@ let primes limit = let lmtb,lmtbsqrt = (limit - 3u) / 2u, (uint32 (sqrt (double limit)) - 3u) / 2u let buf = System.Collections.BitArray(int lmtb + 1, true) - let rec culltest i = if i <= lmtbsqrt then - let p = i + i + 3u in let s = p * (i + 1u) + i in - let rec cullp c = if c <= lmtb then buf.[int c] <- false; cullp (c + p) - (if buf.[int i] then cullp s); culltest (i + 1u) in culltest 0u - seq {yield 2u; for i = 0u to lmtb do if buf.[int i] then yield i + i + 3u } + let cull i = let p = i + i + 3u in let s = p * (i + 1u) + i in + { s .. p .. lmtb } |> Seq.iter (fun c -> buf.[int c] <- false) + { 0u .. lmtbsqrt } |> Seq.iter (fun i -> if buf.[int i] then cull i ) + let oddprms = { 0u .. lmtb } |> Seq.map (fun i -> if buf.[int i] then i + i + 3u else 0u) + |> Seq.filter ((<>) 0u) + seq { yield 2u; yield! oddprms } diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-11.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-11.fs index c1e54606e3..7093f14210 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-11.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-11.fs @@ -1,3 +1,8 @@ - let rec count i acc = - if i > int lmtb then acc else if buf.[i] then count (i + 1) (acc + 1) else count (i + 1) acc - count 0 1 +let primes limit = + let lmtb,lmtbsqrt = (limit - 3u) / 2u, (uint32 (sqrt (double limit)) - 3u) / 2u + let buf = System.Collections.BitArray(int lmtb + 1, true) + let rec culltest i = if i <= lmtbsqrt then + let p = i + i + 3u in let s = p * (i + 1u) + i in + let rec cullp c = if c <= lmtb then buf.[int c] <- false; cullp (c + p) + (if buf.[int i] then cullp s); culltest (i + 1u) in culltest 0u + seq {yield 2u; for i = 0u to lmtb do if buf.[int i] then yield i + i + 3u } diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-12.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-12.fs index b63afd6809..c1e54606e3 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-12.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-12.fs @@ -1,17 +1,3 @@ - let nmrtr() = - let i = ref -2 - let rec nxti() = i:=!i + 1;if !i <= int lmtb && not buf.[!i] then nxti() else !i <= int lmtb - let inline curr() = if !i < 0 then (if !i= -1 then 2u else failwith "Enumeration not started!!!") - else let v = uint32 !i in v + v + 3u - { new System.Collections.Generic.IEnumerator<_> with - member this.Current = curr() - interface System.Collections.IEnumerator with - member this.Current = box (curr()) - member this.MoveNext() = if !i< -1 then i:=!i+1;true else nxti() - member this.Reset() = failwith "IEnumerator.Reset() not implemented!!!"a - interface System.IDisposable with - member this.Dispose() = () } - { new System.Collections.Generic.IEnumerable<_> with - member this.GetEnumerator() = nmrtr() - interface System.Collections.IEnumerable with - member this.GetEnumerator() = nmrtr() :> System.Collections.IEnumerator } + let rec count i acc = + if i > int lmtb then acc else if buf.[i] then count (i + 1) (acc + 1) else count (i + 1) acc + count 0 1 diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-13.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-13.fs index c73f43fa2b..b63afd6809 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-13.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-13.fs @@ -1,26 +1,17 @@ -type Prime = uint32 -let frstprm = 2u -let frstoddprm = 3u -let inc = 2u -let primesDict() = - let dct = System.Collections.Generic.Dictionary() - let rec nxtprm n q (bps: CIS) = - if n >= q then let bp = bps.v in let adv = bp + bp - let nbps = bps.cont() in let nbp = nbps.v - dct.Add(n + adv, adv) - nxtprm (n + inc) (nbp * nbp) nbps - else if dct.ContainsKey(n) then - let adv = dct.[n] - dct.Remove(n) |> ignore -// let mutable nn = n + adv // ugly imperative code -// while dct.ContainsKey(nn) do nn <- nn + adv -// dct.Add(nn, adv) - let rec nxtmt k = // advance to next empty spot - if dct.ContainsKey(k) then nxtmt (k + adv) - else dct.Add(k, adv) in nxtmt (n + adv) - nxtprm (n + inc) q bps - else CIS(n, fun() -> nxtprm (n + inc) q bps) - let rec oddprms() = CIS(frstoddprm, fun() -> - nxtprm (frstoddprm + inc) (frstoddprm * frstoddprm) (oddprms())) - Seq.unfold (fun (cis: CIS) -> Some(cis.v, cis.cont())) - (CIS(frstprm, fun() -> (oddprms()))) + let nmrtr() = + let i = ref -2 + let rec nxti() = i:=!i + 1;if !i <= int lmtb && not buf.[!i] then nxti() else !i <= int lmtb + let inline curr() = if !i < 0 then (if !i= -1 then 2u else failwith "Enumeration not started!!!") + else let v = uint32 !i in v + v + 3u + { new System.Collections.Generic.IEnumerator<_> with + member this.Current = curr() + interface System.Collections.IEnumerator with + member this.Current = box (curr()) + member this.MoveNext() = if !i< -1 then i:=!i+1;true else nxti() + member this.Reset() = failwith "IEnumerator.Reset() not implemented!!!"a + interface System.IDisposable with + member this.Dispose() = () } + { new System.Collections.Generic.IEnumerable<_> with + member this.GetEnumerator() = nmrtr() + interface System.Collections.IEnumerable with + member this.GetEnumerator() = nmrtr() :> System.Collections.IEnumerator } diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-14.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-14.fs index bf9bac2624..c73f43fa2b 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-14.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-14.fs @@ -1,66 +1,26 @@ -let private PGSZBTS = (1 <<< 14) * 8 // sieve buffer size in bits -type private PS = class - val i:int val p:uint64 val cmpsts:uint32[] - new(i,p,c) = { i=i; p=p; cmpsts=c } end -let rec primesPaged(): System.Collections.Generic.IEnumerable<_> = - let lbpse = lazy (primesPaged().GetEnumerator()) // lazy to prevent race - let bpa = ResizeArray() // fills from above sequence as needed - let makePg low = - let nxt = low + (uint64 PGSZBTS <<< 1) - let cmpsts = Array.zeroCreate (PGSZBTS >>> 5) - let inline notprm c = cmpsts.[c >>> 5] &&& (1u <<< c) <> 0u - let rec nxti c = if c < PGSZBTS && notprm c - then nxti (c + 1) else c - let inline mrkc c = let w = c >>> 5 - cmpsts.[w] <- cmpsts.[w] ||| (1u <<< c) - let rec cullf i = - if notprm i then cullf (i + 1) else - let p = 3 + i + i in let sqr = p * p - if uint64 sqr < nxt then - let rec cullp c = if c < PGSZBTS then mrkc c; cullp (c + p) - else cullf (i + 1) in cullp ((sqr - 3) >>> 1) - if low <= 3UL then cullf 0 // special culling for the first page - else // cull rest based on a secondary base prime stream - let bpse = lbpse.Force() - if bpa.Count <= 0 then // move past 2 to 3 - bpse.MoveNext() |> ignore; bpse.MoveNext() |> ignore - let rec fill np = - if np * np >= nxt then - let bpasz = bpa.Count - let rec cull i = - if i < bpasz then - let p = bpa.[i] in let sqr = p * p in let pi = int p - let strt = if sqr >= low then int (sqr - low) >>> 1 - else let r = int (((low - sqr) >>> 1) % p) - if r = 0 then 0 else int p - r - let rec cullp c = if c < PGSZBTS then mrkc c; cullp (c + pi) - cullp strt; cull (i + 1) in cull 0 - else bpa.Add(np); bpse.MoveNext() |> ignore - fill bpse.Current - fill bpse.Current // fill pba as necessary and do cull - let ni = nxti 0 in let np = low + uint64 (ni <<< 1) - PS(ni, np, cmpsts) - let nmrtr() = - let ps = ref (PS(0, 0UL, Array.zeroCreate 0)) - { new System.Collections.Generic.IEnumerator<_> with - member this.Current = (!ps).p - interface System.Collections.IEnumerator with - member this.Current = box ((!ps).p) - member this.MoveNext() = - let drps = !ps in let i = drps.i in let p = drps.p - let cmpsts = drps.cmpsts in let lmt = cmpsts.Length <<< 5 - if p < 3UL then (if p < 2UL then ps := PS(0, 2UL, cmpsts); true - else ps := makePg 3UL; true) else - let inline notprm c = cmpsts.[c >>> 5] &&& (1u <<< c) <> 0u - let rec nxti c = if c < lmt && notprm c - then nxti (c + 1) else c - let ni = nxti (i + 1) in let np = p + uint64 ((ni - i) <<< 1) - if ni < lmt then ps := PS(ni, np, cmpsts); true - else ps := makePg np; true - member this.Reset() = failwith "IEnumerator.Reset() not implemented!!!" - interface System.IDisposable with - member this.Dispose() = () } - { new System.Collections.Generic.IEnumerable<_> with - member this.GetEnumerator() = nmrtr() - interface System.Collections.IEnumerable with - member this.GetEnumerator() = nmrtr() :> System.Collections.IEnumerator } +type Prime = uint32 +let frstprm = 2u +let frstoddprm = 3u +let inc = 2u +let primesDict() = + let dct = System.Collections.Generic.Dictionary() + let rec nxtprm n q (bps: CIS) = + if n >= q then let bp = bps.v in let adv = bp + bp + let nbps = bps.cont() in let nbp = nbps.v + dct.Add(n + adv, adv) + nxtprm (n + inc) (nbp * nbp) nbps + else if dct.ContainsKey(n) then + let adv = dct.[n] + dct.Remove(n) |> ignore +// let mutable nn = n + adv // ugly imperative code +// while dct.ContainsKey(nn) do nn <- nn + adv +// dct.Add(nn, adv) + let rec nxtmt k = // advance to next empty spot + if dct.ContainsKey(k) then nxtmt (k + adv) + else dct.Add(k, adv) in nxtmt (n + adv) + nxtprm (n + inc) q bps + else CIS(n, fun() -> nxtprm (n + inc) q bps) + let rec oddprms() = CIS(frstoddprm, fun() -> + nxtprm (frstoddprm + inc) (frstoddprm * frstoddprm) (oddprms())) + Seq.unfold (fun (cis: CIS) -> Some(cis.v, cis.cont())) + (CIS(frstprm, fun() -> (oddprms()))) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-15.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-15.fs new file mode 100644 index 0000000000..bf9bac2624 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-15.fs @@ -0,0 +1,66 @@ +let private PGSZBTS = (1 <<< 14) * 8 // sieve buffer size in bits +type private PS = class + val i:int val p:uint64 val cmpsts:uint32[] + new(i,p,c) = { i=i; p=p; cmpsts=c } end +let rec primesPaged(): System.Collections.Generic.IEnumerable<_> = + let lbpse = lazy (primesPaged().GetEnumerator()) // lazy to prevent race + let bpa = ResizeArray() // fills from above sequence as needed + let makePg low = + let nxt = low + (uint64 PGSZBTS <<< 1) + let cmpsts = Array.zeroCreate (PGSZBTS >>> 5) + let inline notprm c = cmpsts.[c >>> 5] &&& (1u <<< c) <> 0u + let rec nxti c = if c < PGSZBTS && notprm c + then nxti (c + 1) else c + let inline mrkc c = let w = c >>> 5 + cmpsts.[w] <- cmpsts.[w] ||| (1u <<< c) + let rec cullf i = + if notprm i then cullf (i + 1) else + let p = 3 + i + i in let sqr = p * p + if uint64 sqr < nxt then + let rec cullp c = if c < PGSZBTS then mrkc c; cullp (c + p) + else cullf (i + 1) in cullp ((sqr - 3) >>> 1) + if low <= 3UL then cullf 0 // special culling for the first page + else // cull rest based on a secondary base prime stream + let bpse = lbpse.Force() + if bpa.Count <= 0 then // move past 2 to 3 + bpse.MoveNext() |> ignore; bpse.MoveNext() |> ignore + let rec fill np = + if np * np >= nxt then + let bpasz = bpa.Count + let rec cull i = + if i < bpasz then + let p = bpa.[i] in let sqr = p * p in let pi = int p + let strt = if sqr >= low then int (sqr - low) >>> 1 + else let r = int (((low - sqr) >>> 1) % p) + if r = 0 then 0 else int p - r + let rec cullp c = if c < PGSZBTS then mrkc c; cullp (c + pi) + cullp strt; cull (i + 1) in cull 0 + else bpa.Add(np); bpse.MoveNext() |> ignore + fill bpse.Current + fill bpse.Current // fill pba as necessary and do cull + let ni = nxti 0 in let np = low + uint64 (ni <<< 1) + PS(ni, np, cmpsts) + let nmrtr() = + let ps = ref (PS(0, 0UL, Array.zeroCreate 0)) + { new System.Collections.Generic.IEnumerator<_> with + member this.Current = (!ps).p + interface System.Collections.IEnumerator with + member this.Current = box ((!ps).p) + member this.MoveNext() = + let drps = !ps in let i = drps.i in let p = drps.p + let cmpsts = drps.cmpsts in let lmt = cmpsts.Length <<< 5 + if p < 3UL then (if p < 2UL then ps := PS(0, 2UL, cmpsts); true + else ps := makePg 3UL; true) else + let inline notprm c = cmpsts.[c >>> 5] &&& (1u <<< c) <> 0u + let rec nxti c = if c < lmt && notprm c + then nxti (c + 1) else c + let ni = nxti (i + 1) in let np = p + uint64 ((ni - i) <<< 1) + if ni < lmt then ps := PS(ni, np, cmpsts); true + else ps := makePg np; true + member this.Reset() = failwith "IEnumerator.Reset() not implemented!!!" + interface System.IDisposable with + member this.Dispose() = () } + { new System.Collections.Generic.IEnumerable<_> with + member this.GetEnumerator() = nmrtr() + interface System.Collections.IEnumerable with + member this.GetEnumerator() = nmrtr() :> System.Collections.IEnumerator } diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-2.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-2.fs index 1bc45177cb..f48a7b6938 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-2.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-2.fs @@ -2,20 +2,19 @@ type CIS<'T> = struct val v:'T val cont:unit->CIS<'T> //'Co Inductive Stream for new (v,cont) = { v = v; cont = cont } end type Prime = uint32 -let primesBirdOdds() = +let primesBird() = let rec (^^) (xs: CIS) (ys: CIS) = // stream merge function let x = xs.v in let y = ys.v if x < y then CIS(x, fun() -> xs.cont() ^^ ys) elif y < x then CIS(y, fun() -> xs ^^ ys.cont()) else CIS(x, fun() -> xs.cont() ^^ ys.cont()) // no duplications - let pmltpls p = let adv = p + p - let rec nxt c = CIS(c, fun() -> nxt (c + adv)) in nxt (p * p) + let pmltpls p = let rec nxt c = CIS(c, fun() -> nxt (c + p)) in nxt (p * p) let rec allmltps (ps: CIS) = CIS(pmltpls ps.v, fun() -> allmltps (ps.cont())) let rec cmpsts (css: CIS>) = CIS(css.v.v, fun() -> (css.v.cont()) ^^ (cmpsts (css.cont()))) let rec minusat n (cs: CIS) = - if n < cs.v then CIS(n, fun() -> minusat (n + 2u) cs) - else minusat (n + 2u) (cs.cont()) - let rec oddprms() = CIS(3u, fun() -> minusat 5u (cmpsts (allmltps (oddprms())))) + if n < cs.v then CIS(n, fun() -> minusat (n + 1u) cs) + else minusat (n + 1u) (cs.cont()) + let rec baseprms() = CIS(2u, fun() -> minusat 3u (cmpsts (allmltps (baseprms())))) Seq.unfold (fun (ps: CIS) -> Some(ps.v, ps.cont())) - (CIS(2u, fun() -> minusat 3u (cmpsts (allmltps (oddprms()))))) + (minusat 2u (cmpsts (allmltps (baseprms())))) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-3.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-3.fs index fc4da68ce7..1bc45177cb 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-3.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-3.fs @@ -2,23 +2,20 @@ type CIS<'T> = struct val v:'T val cont:unit->CIS<'T> //'Co Inductive Stream for new (v,cont) = { v = v; cont = cont } end type Prime = uint32 -let primesTreeFold() = - let rec (^^) (xs: CIS) (ys: CIS) = // merge streams; no duplicates +let primesBirdOdds() = + let rec (^^) (xs: CIS) (ys: CIS) = // stream merge function let x = xs.v in let y = ys.v if x < y then CIS(x, fun() -> xs.cont() ^^ ys) elif y < x then CIS(y, fun() -> xs ^^ ys.cont()) - else CIS(x, fun() -> xs.cont() ^^ ys.cont()) + else CIS(x, fun() -> xs.cont() ^^ ys.cont()) // no duplications let pmltpls p = let adv = p + p let rec nxt c = CIS(c, fun() -> nxt (c + adv)) in nxt (p * p) let rec allmltps (ps: CIS) = CIS(pmltpls ps.v, fun() -> allmltps (ps.cont())) - let rec pairs (css: CIS>) = - let ncss = css.cont() - CIS(css.v ^^ ncss.v, fun() -> pairs (ncss.cont())) let rec cmpsts (css: CIS>) = - CIS(css.v.v, fun() -> (css.v.cont()) ^^ (cmpsts << pairs << css.cont)()) + CIS(css.v.v, fun() -> (css.v.cont()) ^^ (cmpsts (css.cont()))) let rec minusat n (cs: CIS) = if n < cs.v then CIS(n, fun() -> minusat (n + 2u) cs) else minusat (n + 2u) (cs.cont()) - let rec oddprms() = CIS(3u, fun() -> (minusat 5u << cmpsts << allmltps) (oddprms())) + let rec oddprms() = CIS(3u, fun() -> minusat 5u (cmpsts (allmltps (oddprms())))) Seq.unfold (fun (ps: CIS) -> Some(ps.v, ps.cont())) - (CIS(2u, fun() -> (minusat 3u << cmpsts << allmltps) (oddprms()))) + (CIS(2u, fun() -> minusat 3u (cmpsts (allmltps (oddprms()))))) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-4.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-4.fs index 9634d42d70..fc4da68ce7 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-4.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-4.fs @@ -1,38 +1,24 @@ -[] -module MinHeap = +type CIS<'T> = struct val v:'T val cont:unit->CIS<'T> //'Co Inductive Stream for laziness + new (v,cont) = { v = v; cont = cont } end +type Prime = uint32 - type HeapEntry<'V> = struct val k:uint32 val v:'V new(k,v) = {k=k;v=v} end - [] - [] - type PQ<'V> = - | Mt - | Br of HeapEntry<'V> * PQ<'V> * PQ<'V> - - let empty = Mt - - let peekMin = function | Br(kv, _, _) -> Some(kv.k, kv.v) - | _ -> None - - let rec push wk wv = - function | Mt -> Br(HeapEntry(wk, wv), Mt, Mt) - | Br(vkv, ll, rr) -> - if wk <= vkv.k then - Br(HeapEntry(wk, wv), push vkv.k vkv.v rr, ll) - else Br(vkv, push wk wv rr, ll) - - let private siftdown wk wv pql pqr = - let rec sift pl pr = - match pl with - | Mt -> Br(HeapEntry(wk, wv), Mt, Mt) - | Br(vkvl, pll, plr) -> - match pr with - | Mt -> if wk <= vkvl.k then Br(HeapEntry(wk, wv), pl, Mt) - else Br(vkvl, Br(HeapEntry(wk, wv), Mt, Mt), Mt) - | Br(vkvr, prl, prr) -> - if wk <= vkvl.k && wk <= vkvr.k then Br(HeapEntry(wk, wv), pl, pr) - elif vkvl.k <= vkvr.k then Br(vkvl, sift pll plr, pr) - else Br(vkvr, pl, sift prl prr) - sift pql pqr - - let replaceMin wk wv = function | Mt -> Mt - | Br(_, ll, rr) -> siftdown wk wv ll rr +let primesTreeFold() = + let rec (^^) (xs: CIS) (ys: CIS) = // merge streams; no duplicates + let x = xs.v in let y = ys.v + if x < y then CIS(x, fun() -> xs.cont() ^^ ys) + elif y < x then CIS(y, fun() -> xs ^^ ys.cont()) + else CIS(x, fun() -> xs.cont() ^^ ys.cont()) + let pmltpls p = let adv = p + p + let rec nxt c = CIS(c, fun() -> nxt (c + adv)) in nxt (p * p) + let rec allmltps (ps: CIS) = CIS(pmltpls ps.v, fun() -> allmltps (ps.cont())) + let rec pairs (css: CIS>) = + let ncss = css.cont() + CIS(css.v ^^ ncss.v, fun() -> pairs (ncss.cont())) + let rec cmpsts (css: CIS>) = + CIS(css.v.v, fun() -> (css.v.cont()) ^^ (cmpsts << pairs << css.cont)()) + let rec minusat n (cs: CIS) = + if n < cs.v then CIS(n, fun() -> minusat (n + 2u) cs) + else minusat (n + 2u) (cs.cont()) + let rec oddprms() = CIS(3u, fun() -> (minusat 5u << cmpsts << allmltps) (oddprms())) + Seq.unfold (fun (ps: CIS) -> Some(ps.v, ps.cont())) + (CIS(2u, fun() -> (minusat 3u << cmpsts << allmltps) (oddprms()))) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-5.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-5.fs index c21cfa0a7d..9634d42d70 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-5.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-5.fs @@ -1,6 +1,38 @@ -type CIS<'T> = struct val v: 'T val cont: unit -> CIS<'T> new(v,cont) = {v=v;cont=cont} end -type Prime = uint32 -let frstprm = 2u -let frstoddprm = 3u -let inc1 = 1u -let inc = 2u +[] +module MinHeap = + + type HeapEntry<'V> = struct val k:uint32 val v:'V new(k,v) = {k=k;v=v} end + [] + [] + type PQ<'V> = + | Mt + | Br of HeapEntry<'V> * PQ<'V> * PQ<'V> + + let empty = Mt + + let peekMin = function | Br(kv, _, _) -> Some(kv.k, kv.v) + | _ -> None + + let rec push wk wv = + function | Mt -> Br(HeapEntry(wk, wv), Mt, Mt) + | Br(vkv, ll, rr) -> + if wk <= vkv.k then + Br(HeapEntry(wk, wv), push vkv.k vkv.v rr, ll) + else Br(vkv, push wk wv rr, ll) + + let private siftdown wk wv pql pqr = + let rec sift pl pr = + match pl with + | Mt -> Br(HeapEntry(wk, wv), Mt, Mt) + | Br(vkvl, pll, plr) -> + match pr with + | Mt -> if wk <= vkvl.k then Br(HeapEntry(wk, wv), pl, Mt) + else Br(vkvl, Br(HeapEntry(wk, wv), Mt, Mt), Mt) + | Br(vkvr, prl, prr) -> + if wk <= vkvl.k && wk <= vkvr.k then Br(HeapEntry(wk, wv), pl, pr) + elif vkvl.k <= vkvr.k then Br(vkvl, sift pll plr, pr) + else Br(vkvr, pl, sift prl prr) + sift pql pqr + + let replaceMin wk wv = function | Mt -> Mt + | Br(_, ll, rr) -> siftdown wk wv ll rr diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-6.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-6.fs index dcca30c0f5..c21cfa0a7d 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-6.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-6.fs @@ -1,31 +1,6 @@ type CIS<'T> = struct val v: 'T val cont: unit -> CIS<'T> new(v,cont) = {v=v;cont=cont} end -type Prime = uint64 -let frstprm = 2UL -let frstoddprm = 3UL -let inc = 2UL - -let primesPQ() = - let pmult p (xs: CIS) = // does map (* p) xs - let rec nxtm (cs: CIS) = - CIS(p * cs.v, fun() -> nxtm (cs.cont())) in nxtm xs - let insertprime p xs table = - MinHeap.push (p * p) (pmult p xs) table - let rec sieve' (ns: CIS) table = - let nextcomposite = match MinHeap.peekMin table with - | None -> ns.v // never happens - | Some (k, _) -> k - let rec adjust table = - let (n, advs) = match MinHeap.peekMin table with - | None -> (ns.v, ns.cont()) // never happens - | Some kv -> kv - if n <= ns.v then adjust (MinHeap.replaceMin advs.v (advs.cont()) table) - else table - if nextcomposite <= ns.v then sieve' (ns.cont()) (adjust table) - else let n = ns.v in CIS(n, fun() -> - let nxtns = ns.cont() in sieve' nxtns (insertprime n nxtns table)) - let rec sieve (ns: CIS) = let n = ns.v in CIS(n, fun() -> - let nxtns = ns.cont() in sieve' nxtns (insertprime n nxtns MinHeap.empty)) - let odds = // is the odds CIS from 3 up - let rec nxto i = CIS(i, fun() -> nxto (i + inc)) in nxto frstoddprm - Seq.unfold (fun (cis: CIS) -> Some(cis.v, cis.cont())) - (CIS(frstprm, fun() -> (sieve odds))) +type Prime = uint32 +let frstprm = 2u +let frstoddprm = 3u +let inc1 = 1u +let inc = 2u diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-7.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-7.fs index 252b9d203e..dcca30c0f5 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-7.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-7.fs @@ -1,20 +1,31 @@ -let primesPQx() = - let rec nxtprm n pq q (bps: CIS) = - if n >= q then let bp = bps.v in let adv = bp + bp - let nbps = bps.cont() in let nbp = nbps.v - nxtprm (n + inc) (MinHeap.push (n + adv) adv pq) (nbp * nbp) nbps - else let ck, cv = match MinHeap.peekMin pq with - | None -> (q, inc) // only happens until first insertion +type CIS<'T> = struct val v: 'T val cont: unit -> CIS<'T> new(v,cont) = {v=v;cont=cont} end +type Prime = uint64 +let frstprm = 2UL +let frstoddprm = 3UL +let inc = 2UL + +let primesPQ() = + let pmult p (xs: CIS) = // does map (* p) xs + let rec nxtm (cs: CIS) = + CIS(p * cs.v, fun() -> nxtm (cs.cont())) in nxtm xs + let insertprime p xs table = + MinHeap.push (p * p) (pmult p xs) table + let rec sieve' (ns: CIS) table = + let nextcomposite = match MinHeap.peekMin table with + | None -> ns.v // never happens + | Some (k, _) -> k + let rec adjust table = + let (n, advs) = match MinHeap.peekMin table with + | None -> (ns.v, ns.cont()) // never happens | Some kv -> kv - if n >= ck then let rec adjpq ck cv pq = - let npq = MinHeap.replaceMin (ck + cv) cv pq - match MinHeap.peekMin npq with - | None -> npq // never happens - | Some(nk, nv) -> if n >= nk then adjpq nk nv npq - else npq - nxtprm (n + inc) (adjpq ck cv pq) q bps - else CIS(n, fun() -> nxtprm (n + inc) pq q bps) - let rec oddprms() = CIS(frstoddprm, fun() -> - nxtprm (frstoddprm + inc) MinHeap.empty (frstoddprm * frstoddprm) (oddprms())) + if n <= ns.v then adjust (MinHeap.replaceMin advs.v (advs.cont()) table) + else table + if nextcomposite <= ns.v then sieve' (ns.cont()) (adjust table) + else let n = ns.v in CIS(n, fun() -> + let nxtns = ns.cont() in sieve' nxtns (insertprime n nxtns table)) + let rec sieve (ns: CIS) = let n = ns.v in CIS(n, fun() -> + let nxtns = ns.cont() in sieve' nxtns (insertprime n nxtns MinHeap.empty)) + let odds = // is the odds CIS from 3 up + let rec nxto i = CIS(i, fun() -> nxto (i + inc)) in nxto frstoddprm Seq.unfold (fun (cis: CIS) -> Some(cis.v, cis.cont())) - (CIS(frstprm, fun() -> (oddprms()))) + (CIS(frstprm, fun() -> (sieve odds))) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-8.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-8.fs index eda1d46ed1..252b9d203e 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-8.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-8.fs @@ -1,11 +1,20 @@ -let primes limit = - let buf = System.Collections.BitArray(int limit + 1, true) - let cull p = { p * p .. p .. limit } |> Seq.iter (fun c -> buf.[int c] <- false) - { 2u .. uint32 (sqrt (double limit)) } |> Seq.iter (fun c -> if buf.[int c] then cull c) - { 2u .. limit } |> Seq.map (fun i -> if buf.[int i] then i else 0u) |> Seq.filter ((<>) 0u) - -[] -let main argv = - if argv = null || argv.Length = 0 then failwith "no command line argument for limit!!!" - printfn "%A" (primes (System.UInt32.Parse argv.[0]) |> Seq.length) - 0 // return an integer exit code +let primesPQx() = + let rec nxtprm n pq q (bps: CIS) = + if n >= q then let bp = bps.v in let adv = bp + bp + let nbps = bps.cont() in let nbp = nbps.v + nxtprm (n + inc) (MinHeap.push (n + adv) adv pq) (nbp * nbp) nbps + else let ck, cv = match MinHeap.peekMin pq with + | None -> (q, inc) // only happens until first insertion + | Some kv -> kv + if n >= ck then let rec adjpq ck cv pq = + let npq = MinHeap.replaceMin (ck + cv) cv pq + match MinHeap.peekMin npq with + | None -> npq // never happens + | Some(nk, nv) -> if n >= nk then adjpq nk nv npq + else npq + nxtprm (n + inc) (adjpq ck cv pq) q bps + else CIS(n, fun() -> nxtprm (n + inc) pq q bps) + let rec oddprms() = CIS(frstoddprm, fun() -> + nxtprm (frstoddprm + inc) MinHeap.empty (frstoddprm * frstoddprm) (oddprms())) + Seq.unfold (fun (cis: CIS) -> Some(cis.v, cis.cont())) + (CIS(frstprm, fun() -> (oddprms()))) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-9.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-9.fs index 4c9836434c..eda1d46ed1 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-9.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-9.fs @@ -1,9 +1,11 @@ let primes limit = - let lmtb,lmtbsqrt = (limit - 3u) / 2u, (uint32 (sqrt (double limit)) - 3u) / 2u - let buf = System.Collections.BitArray(int lmtb + 1, true) - let cull i = let p = i + i + 3u in let s = p * (i + 1u) + i in - { s .. p .. lmtb } |> Seq.iter (fun c -> buf.[int c] <- false) - { 0u .. lmtbsqrt } |> Seq.iter (fun i -> if buf.[int i] then cull i ) - let oddprms = { 0u .. lmtb } |> Seq.map (fun i -> if buf.[int i] then i + i + 3u else 0u) - |> Seq.filter ((<>) 0u) - seq { yield 2u; yield! oddprms } + let buf = System.Collections.BitArray(int limit + 1, true) + let cull p = { p * p .. p .. limit } |> Seq.iter (fun c -> buf.[int c] <- false) + { 2u .. uint32 (sqrt (double limit)) } |> Seq.iter (fun c -> if buf.[int c] then cull c) + { 2u .. limit } |> Seq.map (fun i -> if buf.[int i] then i else 0u) |> Seq.filter ((<>) 0u) + +[] +let main argv = + if argv = null || argv.Length = 0 then failwith "no command line argument for limit!!!" + printfn "%A" (primes (System.UInt32.Parse argv.[0]) |> Seq.length) + 0 // return an integer exit code diff --git a/Task/Sieve-of-Eratosthenes/jq/sieve-of-eratosthenes-1.jq b/Task/Sieve-of-Eratosthenes/Jq/sieve-of-eratosthenes-1.jq similarity index 100% rename from Task/Sieve-of-Eratosthenes/jq/sieve-of-eratosthenes-1.jq rename to Task/Sieve-of-Eratosthenes/Jq/sieve-of-eratosthenes-1.jq diff --git a/Task/Sieve-of-Eratosthenes/jq/sieve-of-eratosthenes-2.jq b/Task/Sieve-of-Eratosthenes/Jq/sieve-of-eratosthenes-2.jq similarity index 100% rename from Task/Sieve-of-Eratosthenes/jq/sieve-of-eratosthenes-2.jq rename to Task/Sieve-of-Eratosthenes/Jq/sieve-of-eratosthenes-2.jq diff --git a/Task/Sieve-of-Eratosthenes/jq/sieve-of-eratosthenes-3.jq b/Task/Sieve-of-Eratosthenes/Jq/sieve-of-eratosthenes-3.jq similarity index 100% rename from Task/Sieve-of-Eratosthenes/jq/sieve-of-eratosthenes-3.jq rename to Task/Sieve-of-Eratosthenes/Jq/sieve-of-eratosthenes-3.jq diff --git a/Task/Sieve-of-Eratosthenes/Kotlin/sieve-of-eratosthenes-2.kotlin b/Task/Sieve-of-Eratosthenes/Kotlin/sieve-of-eratosthenes-2.kotlin index 8863814507..94c2437ed0 100644 --- a/Task/Sieve-of-Eratosthenes/Kotlin/sieve-of-eratosthenes-2.kotlin +++ b/Task/Sieve-of-Eratosthenes/Kotlin/sieve-of-eratosthenes-2.kotlin @@ -3,6 +3,7 @@ fun primesOdds(rng: Int): Iterable { val lstw = topi shr 5 val sqrtndx = (Math.sqrt(rng.toDouble()).toInt() - 3) shr 1 val cmpsts = IntArray(lstw + 1) + tailrec fun testloop(i: Int) { if (i <= sqrtndx) { if (cmpsts[i shr 5] and (1 shl (i and 31)) == 0) { @@ -18,17 +19,25 @@ fun primesOdds(rng: Int): Iterable { testloop(i + 1) } } - testloop(0) - tailrec fun test(i : Int): Int { + + tailrec fun test(i: Int): Int { return if (i <= topi && cmpsts[i shr 5] and (1 shl (i and 31)) != 0) { - test(i + 1) } else { i } + test(i + 1) + } else { + i + } } + + testloop(0) + val iter = object : IntIterator() { var i = -1 override fun nextInt(): Int { - val oi = i; i = test(i + 1) - if (oi < 0) { return 2 } else { return oi + oi + 3 } } - override fun hasNext() = if (i < topi) { true } else { false } + val oi = i + i = test(i + 1) + return if (oi < 0) 2 else oi + oi + 3 + } + override fun hasNext() = i < topi } return Iterable { -> iter } } diff --git a/Task/Sieve-of-Eratosthenes/Kotlin/sieve-of-eratosthenes-3.kotlin b/Task/Sieve-of-Eratosthenes/Kotlin/sieve-of-eratosthenes-3.kotlin index 2509795ec4..0af1628b1a 100644 --- a/Task/Sieve-of-Eratosthenes/Kotlin/sieve-of-eratosthenes-3.kotlin +++ b/Task/Sieve-of-Eratosthenes/Kotlin/sieve-of-eratosthenes-3.kotlin @@ -3,13 +3,11 @@ fun primesOdds(rng: Int): Iterable { val size = topi / 32 + 1 //word size to include index val sqrtndx = (Math.sqrt(rng.toDouble()).toInt() - 3) / 2 val cmpsts = IntArray(size) - fun is_p(i: Int) = if (cmpsts[i shr 5] and (1 shl (i and 0x1F)) == 0) - { true } else { false } - fun cull(i: Int) { cmpsts[i shr 5] = cmpsts[i shr 5] or - (1 shl (i and 0x1F)) } - fun cullp(p: Int) = ((p * p - 3) / 2 .. topi step(p)).forEach { cull(it) } + fun is_p(i: Int) = cmpsts[i shr 5] and (1 shl (i and 0x1F)) == 0 + fun cull(i: Int) { cmpsts[i shr 5] = cmpsts[i shr 5] or (1 shl (i and 0x1F)) } + fun cullp(p: Int) = (((p * p - 3) / 2 .. topi).step(p)).forEach { cull(it) } (0 .. sqrtndx).filter { is_p(it) }.forEach { cullp(it + it + 3) } - fun i2p(i: Int) = if (i < 0) { 2 } else { i + i + 3 } + fun i2p(i: Int) = if (i < 0) 2 else i + i + 3 val orng = (-1 .. topi).filter { it < 0 || is_p(it) }.map { i2p(it) } return Iterable { -> orng.iterator() } } diff --git a/Task/Sieve-of-Eratosthenes/Kotlin/sieve-of-eratosthenes-4.kotlin b/Task/Sieve-of-Eratosthenes/Kotlin/sieve-of-eratosthenes-4.kotlin index 2bbc1adad7..d392258e7b 100644 --- a/Task/Sieve-of-Eratosthenes/Kotlin/sieve-of-eratosthenes-4.kotlin +++ b/Task/Sieve-of-Eratosthenes/Kotlin/sieve-of-eratosthenes-4.kotlin @@ -3,15 +3,13 @@ fun primesOdds(rng: Int): Iterable { val size = topi / 32 + 1 //word size to include index val sqrtndx = (Math.sqrt(rng.toDouble()).toInt() - 3) / 2 val cmpsts = IntArray(size) - fun is_p(i: Int) = if (cmpsts[i shr 5] and (1 shl (i and 0x1F)) == 0) - { true } else { false } - fun cull(i: Int) { cmpsts[i shr 5] = cmpsts[i shr 5] or - (1 shl (i and 0x1F)) } + fun is_p(i: Int) = cmpsts[i shr 5] and (1 shl (i and 0x1F)) == 0 + fun cull(i: Int) { cmpsts[i shr 5] = cmpsts[i shr 5] or (1 shl (i and 0x1F)) } fun iseq(high: Int, low: Int = 0, stp: Int = 1) = Sequence { (low .. high step(stp)).iterator() } fun cullp(p: Int) = iseq(topi, (p * p - 3) / 2, p).forEach { cull(it) } iseq(sqrtndx).filter { is_p(it) }.forEach { cullp(it + it + 3) } - fun i2p(i: Int) = if (i < 0) { 2 } else { i + i + 3 } + fun i2p(i: Int) = if (i < 0) 2 else i + i + 3 val oseq = iseq(topi, -1).filter { it < 0 || is_p(it) }.map { i2p(it) } return Iterable { -> oseq.iterator() } } diff --git a/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-3.m b/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-3.m deleted file mode 100644 index 1ca6ea091c..0000000000 --- a/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-3.m +++ /dev/null @@ -1,9 +0,0 @@ -function P = sieveOfEratosthenes(x) -ISP = [false true(1, x-1)]; % 1 is not prime, but we start off assuming all numbers between 2 and x are -for n = 2:sqrt(x) - if ISP(n) - ISP((2*n):n:x) = false; % Multiples of n that are greater than n are not primes - end -end -% The ISP vector that we have calculated is essentially the output of the ISPRIME function called on 1:x -P = find(ISP); % Convert the ISPRIME output to the values of the primes by finding the locations of the TRUE values in S. diff --git a/Task/Sieve-of-Eratosthenes/Nimrod/sieve-of-eratosthenes.nimrod b/Task/Sieve-of-Eratosthenes/Nimrod/sieve-of-eratosthenes.nimrod deleted file mode 100644 index 73a8793a55..0000000000 --- a/Task/Sieve-of-Eratosthenes/Nimrod/sieve-of-eratosthenes.nimrod +++ /dev/null @@ -1,21 +0,0 @@ -import math, strutils - -var is_prime: seq[Bool] = @[] -is_prime.add(False) -is_prime.add(False) - -iterator iprimes_upto(limit: int): int = - for n in high(is_prime) .. limit+2: is_prime.add(True) - for n in 2 .. limit + 1: - if is_prime[n]: - yield n - for i in countup((n *% n), limit+1, n): # start at ``n`` squared - try: - is_prime[i] = False - except EInvalidIndex: break - - -echo("Primes are:") -for x in iprimes_upto(200): - write(stdout, x, " ") -writeln(stdout,"") diff --git a/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-2.pl6 b/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-2.pl6 index 5155558baa..9c9c713341 100644 --- a/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-2.pl6 +++ b/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-2.pl6 @@ -1,7 +1,7 @@ sub eratsieve($n) { # Requires n(1 - 1/(log(n-1))) storage my $multiples = set(); - lazy gather for 2..$n -> $i { + gather for 2..$n -> $i { unless $i (&) $multiples { # is subset take $i; $multiples (+)= set($i**2, *+$i ... (* > $n)); # union diff --git a/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-3.pl6 b/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-3.pl6 deleted file mode 100644 index f857874e5c..0000000000 --- a/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-3.pl6 +++ /dev/null @@ -1,12 +0,0 @@ -role Filter[Int $factor] { - method next { repeat until $.value % $factor { callsame } } -} - -class Stream { - has Int $.value is rw = 1; - - method next { ++$.value } - method filter { self but Filter[$.value] } -} - -.next, say .value for Stream.new, *.filter ... *; diff --git a/Task/Sieve-of-Eratosthenes/R/sieve-of-eratosthenes.r b/Task/Sieve-of-Eratosthenes/R/sieve-of-eratosthenes.r index ae58dfae5d..3a680a6d35 100644 --- a/Task/Sieve-of-Eratosthenes/R/sieve-of-eratosthenes.r +++ b/Task/Sieve-of-Eratosthenes/R/sieve-of-eratosthenes.r @@ -1,16 +1,14 @@ -sieve <- function(n) -{ - n <- as.integer(n) - if(n > 1e6) stop("n too large") - primes <- rep(TRUE, n) - primes[1] <- FALSE - last.prime <- 2L - for(i in last.prime:floor(sqrt(n))) - { - primes[seq.int(2L*last.prime, n, last.prime)] <- FALSE - last.prime <- last.prime + min(which(primes[(last.prime+1):n])) - } - which(primes) +sieve <- function(n) { + if (n < 2) return(NULL) + a <- rep(T, n) + a[1] <- F + for(i in seq(n)) { + if (a[i]) { + j <- i * i + if (j > n) return(which(a)) + a[seq(j, n, by=i)] <- F + } + } } sieve(1000) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-12.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-12.rkt deleted file mode 100644 index 4de4f01b06..0000000000 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-12.rkt +++ /dev/null @@ -1,21 +0,0 @@ -#lang racket -(require racket/generator) -(define (ints-from i d) - (generator () (let loop ([i i]) (yield i) (loop (+ i d))))) -(define (merge g1 g2) - (generator () - (let loop ([x1 (g1)] [x2 (g2)]) - (cond [(< x1 x2) (yield x1) (loop (g1) x2)] - [(> x1 x2) (yield x2) (loop x1 (g2))] - [else (yield x1) (loop (g1) (g2))])))) -(define (sieve l non-primes) - (generator () - (let loop ([x (l)] [np (non-primes)]) - (cond [(< np x) (loop x (non-primes))] - [(= np x) (loop (l) (non-primes))] - [else (yield x) - (set! non-primes (merge (ints-from (* x x) x) non-primes)) - (loop (l) (non-primes))])))) -(define (cons x l) (generator () (yield x) (let loop () (yield (l)) (loop)))) -(define primes (cons 2 (sieve (ints-from 3 2) (ints-from 2 2)))) -(for/list ([i 25] [x (in-producer primes)]) x) diff --git a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-4.rust b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-4.rust index 2a06aa7591..628e92ad4a 100644 --- a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-4.rust +++ b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-4.rust @@ -77,7 +77,7 @@ fn primes_pages() -> Box)>> { 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); diff --git a/Task/Sieve-of-Eratosthenes/Scilab/sieve-of-eratosthenes.scilab b/Task/Sieve-of-Eratosthenes/Scilab/sieve-of-eratosthenes.scilab index 665d1e6da8..f90772fa31 100644 --- a/Task/Sieve-of-Eratosthenes/Scilab/sieve-of-eratosthenes.scilab +++ b/Task/Sieve-of-Eratosthenes/Scilab/sieve-of-eratosthenes.scilab @@ -1,13 +1,19 @@ - clear - n=99 - sieve=ones(1,n+2) - for i=2:n - if sieve(i) then - for j=i*2:i:n - sieve(j)=0 +function a = sieve(n) + a = ~zeros(n, 1) + a(1) = %f + for i = 1:n + if a(i) + j = i*i + if j > n + return end + a(j:i:n) = %f end end - for i=2:n - if sieve(i) then disp(i); end - end +endfunction + +find(sieve(100)) +// [2 3 5 ... 97] + +sum(sieve(1000)) +// 168, the number of primes below 1000 diff --git a/Task/Sieve-of-Eratosthenes/Sidef/sieve-of-eratosthenes-1.sidef b/Task/Sieve-of-Eratosthenes/Sidef/sieve-of-eratosthenes-1.sidef new file mode 100644 index 0000000000..7a96acf14f --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Sidef/sieve-of-eratosthenes-1.sidef @@ -0,0 +1,15 @@ +func sieve(limit) { + var sieve_arr = [false, false, (limit-1).of(true)...] + gather { + sieve_arr.each_kv { |number, is_prime| + if (is_prime) { + take(number) + for i in (number**2 .. limit `by` number) { + sieve_arr[i] = false + } + } + } + } +} + +say sieve(100).join(",") diff --git a/Task/Sieve-of-Eratosthenes/Sidef/sieve-of-eratosthenes-2.sidef b/Task/Sieve-of-Eratosthenes/Sidef/sieve-of-eratosthenes-2.sidef new file mode 100644 index 0000000000..b571c5ddcf --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Sidef/sieve-of-eratosthenes-2.sidef @@ -0,0 +1,11 @@ +func sieve(limit) { + var composite = [] + for n in (2 .. limit.isqrt) { + for i in (n**2 .. limit `by` n) { + composite[i] = true + } + } + 2..limit -> grep{ !composite[_] } +} + +say sieve(100).join(",") diff --git a/Task/Sieve-of-Eratosthenes/Sidef/sieve-of-eratosthenes.sidef b/Task/Sieve-of-Eratosthenes/Sidef/sieve-of-eratosthenes.sidef deleted file mode 100644 index 8b37f24517..0000000000 --- a/Task/Sieve-of-Eratosthenes/Sidef/sieve-of-eratosthenes.sidef +++ /dev/null @@ -1,15 +0,0 @@ -func sieve(limit) { - var sieve_arr = [false, false, [true]*(limit-1)...] - gather { - sieve_arr.each_kv { |number, is_prime| - if (is_prime) { - take(number) - number.sqr.to(limit).by(number).each { |i| - sieve_arr[i] = false - } - } - } - } -} - -say sieve(100).join(",") diff --git a/Task/Sieve-of-Eratosthenes/Simula/sieve-of-eratosthenes.simula b/Task/Sieve-of-Eratosthenes/Simula/sieve-of-eratosthenes-1.simula similarity index 100% rename from Task/Sieve-of-Eratosthenes/Simula/sieve-of-eratosthenes.simula rename to Task/Sieve-of-Eratosthenes/Simula/sieve-of-eratosthenes-1.simula diff --git a/Task/Sieve-of-Eratosthenes/Simula/sieve-of-eratosthenes-2.simula b/Task/Sieve-of-Eratosthenes/Simula/sieve-of-eratosthenes-2.simula new file mode 100644 index 0000000000..421922d4d7 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Simula/sieve-of-eratosthenes-2.simula @@ -0,0 +1,107 @@ +! A CONCURRENT PRIME SIEVE ; + +BEGIN + +BOOLEAN DEBUG; + +CLASS FILTER(INPUT, OUTPUT, PRIME); REF(FILTER) INPUT, OUTPUT; INTEGER PRIME; +BEGIN + INTEGER NUM; + IF PRIME = 0 AND INPUT == NONE THEN + BEGIN + ! SEND THE SEQUENCE 2, 3, 4, ... TO CHANNEL 'CH'. ; + DETACH; + NUM := 2; + WHILE TRUE DO + BEGIN + IF OUTPUT == NONE THEN + BEGIN + IF DEBUG THEN + BEGIN + OUTTEXT("GENERATE SENDS "); + OUTINT(NUM, 0); + OUTIMAGE; + END; + DETACH; ! SEND 'NUM' ; + END ELSE + BEGIN + IF DEBUG THEN + BEGIN + OUTTEXT("GENERATE SENDS "); + OUTINT(NUM, 0); + OUTTEXT(" TO FILTER("); OUTINT(OUTPUT.PRIME, 0); + OUTTEXT(")"); + OUTIMAGE; + END; + OUTPUT.NUM := NUM; + RESUME(OUTPUT); + END; + NUM := NUM + 1; + END; + END ELSE + BEGIN + ! COPY THE VALUES FROM CHANNEL 'IN' TO CHANNEL 'OUT', ; + ! REMOVING THOSE DIVISIBLE BY 'PRIME'. ; + DETACH; + ! FILTER ; + WHILE TRUE DO + BEGIN + INTEGER I; + RESUME(INPUT); + I := INPUT.NUM; ! RECEIVE VALUE FROM 'INPUT'. ; + IF DEBUG THEN + BEGIN + OUTTEXT("FILTER("); OUTINT(PRIME, 0); OUTTEXT(") RECEIVES "); + OUTINT(I, 0); + OUTIMAGE; + END; + IF NOT MOD(I, PRIME) = 0 THEN + BEGIN + IF OUTPUT == NONE THEN + BEGIN + IF DEBUG THEN + BEGIN + OUTTEXT("FILTER("); OUTINT(PRIME, 0); + OUTTEXT(") SENDS "); + OUTINT(I, 0); + OUTIMAGE; + END; + DETACH; + END ELSE + BEGIN + IF DEBUG THEN + BEGIN + OUTTEXT("FILTER("); OUTINT(PRIME, 0); + OUTTEXT(") SENDS "); + OUTINT(I, 0); + OUTTEXT(" TO FILTER("); OUTINT(OUTPUT.PRIME, 0); + OUTTEXT(")"); + OUTIMAGE; + END; + OUTPUT.NUM := I; ! SEND 'I' TO 'OUT'. ; + RESUME(OUTPUT); + END; + END; + END; + END; +END; + +! THE PRIME SIEVE: DAISY-CHAIN FILTER PROCESSES. ; +! MAIN BLOCK ; + REF(FILTER) CH; + INTEGER I, PRIME; + DEBUG := TRUE; + CH :- NEW FILTER(NONE, NONE, 0); ! LAUNCH GENERATE GOROUTINE. ; + FOR I := 1 STEP 1 UNTIL 5 DO + BEGIN + REF(FILTER) CH1; + RESUME(CH); + PRIME := CH.NUM; + IF DEBUG THEN OUTTEXT("MAIN BLOCK RECEIVES "); + OUTINT(PRIME,0); + OUTIMAGE; + CH1 :- NEW FILTER(CH, NONE, PRIME); + CH.OUTPUT :- CH1; + CH :- CH1; + END; +END; diff --git a/Task/Sieve-of-Eratosthenes/Smalltalk/sieve-of-eratosthenes.st b/Task/Sieve-of-Eratosthenes/Smalltalk/sieve-of-eratosthenes.st new file mode 100644 index 0000000000..22a1c1c760 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Smalltalk/sieve-of-eratosthenes.st @@ -0,0 +1,16 @@ +| potentialPrimes limit | +limit := 100. +potentialPrimes := Array new: limit. +potentialPrimes atAllPut: true. +2 to: limit sqrt do: [:testNumber | + (potentialPrimes at: testNumber) ifTrue: [ + (testNumber * 2) to: limit by: testNumber do: [:nonPrime | + potentialPrimes at: nonPrime put: false + ] + ] +]. +2 to: limit do: [:testNumber | + (potentialPrimes at: testNumber) ifTrue: [ + Transcript show: testNumber asString; cr + ] +] diff --git a/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-1.stata b/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-1.stata new file mode 100644 index 0000000000..f82e0bc338 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-1.stata @@ -0,0 +1,22 @@ +program sieve + clear + quietly set obs `1' + gen long p=_n + gen byte a=_n>1 + local i=2 + while 1 { + if a[`i'] { + local j=`i'*`i' + if `j'>`1' { + continue, break + } + while `j'<=`1' { + quietly replace a=0 in `j' + local j=`j'+`i' + } + } + local ++i + } + quietly keep if a + drop a +end diff --git a/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-2.stata b/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-2.stata new file mode 100644 index 0000000000..4f0bc519e5 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-2.stata @@ -0,0 +1,18 @@ +sieve 100 +list in 1/10 // show only the first ten primes + + +----+ + | p | + |----| + 1. | 2 | + 2. | 3 | + 3. | 5 | + 4. | 7 | + 5. | 11 | + |----| + 6. | 13 | + 7. | 17 | + 8. | 19 | + 9. | 23 | + 10. | 29 | + +----+ diff --git a/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-3.stata b/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-3.stata new file mode 100644 index 0000000000..cffdf1a3a7 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-3.stata @@ -0,0 +1,25 @@ +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 + } + } +} + +sieve(10) + 1 + +-----+ + 1 | 2 | + 2 | 3 | + 3 | 5 | + 4 | 7 | + +-----+ +end diff --git a/Task/Sieve-of-Eratosthenes/Zkl/sieve-of-eratosthenes.zkl b/Task/Sieve-of-Eratosthenes/Zkl/sieve-of-eratosthenes.zkl new file mode 100644 index 0000000000..19b440fa16 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Zkl/sieve-of-eratosthenes.zkl @@ -0,0 +1,8 @@ +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 + '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 +} +sieve(53).println(); diff --git a/Task/Simple-database/Common-Lisp/simple-database.lisp b/Task/Simple-database/Common-Lisp/simple-database.lisp index 5739760805..af1493bc8d 100644 --- a/Task/Simple-database/Common-Lisp/simple-database.lisp +++ b/Task/Simple-database/Common-Lisp/simple-database.lisp @@ -1,396 +1,118 @@ (defvar *db* nil) -(defstruct series description tags episodes) +(defvar *db-cat* (make-hash-table :test 'equal)) -(defstruct (episode (:print-function print-episode-struct)) - series title season episode part date tags) +(defvar *db-file* "db.txt") -(defun format-ymd (date) - (format nil "~{~a.~a.~a~}" date)) +(defstruct item + "this is the unit of data stored/displayed in *db*" + (title " ") + (category "default") + (date (progn (get-universal-time)))) -(defun print-episode-struct (ep stream level) - (let ((*print-pretty* nil)) - (format stream (if *print-escape* - "#s(episode~@{~*~@[ :~1:*~a ~s~]~})" - "~32<~*~a~; ~*~@[~d-~]~*~d~> ~45<~*~@[~a ~]~*~@[(~a) ~]~;~*~@[(~a)~]~>~*~@[ (~{~a~^ ~})~]") - :series (episode-series ep) - :season (episode-season ep) - :episode (episode-episode ep) - :title (episode-title ep) - :part (episode-part ep) - :date (if *print-escape* - (episode-date ep) - (when (episode-date ep) - (format-ymd (episode-date ep)))) - :tags (episode-tags ep)))) +(defun set-category(new-item) + (setf (gethash (item-category new-item) *db-cat*) 't)) -(defun get-value (key alist) - (cdr (assoc key alist))) +(defun find-item-in-db (&optional category) + (if (null category) + (car *db*) + (find category *db* :key #'item-category :test #'string=))) +(defun scan-category () + "scan categories from an existing database -- after reading it from disk" + (dolist (itm *db*) (set-category itm))) -(defun get-latest (database) - (when database - (cons (car (series-episodes (cdar database))) (get-latest (cdr database))))) - -(defun get-all (database) - (when database - (append (series-episodes (cdar database)) (get-all (cdr database))))) - -(defun compare-date (a b) - (cond ((not a) t) - ((not b) nil) - ((= (first a) (first b)) - (compare-date (rest a) (rest b))) - (t (< (first a) (first b))))) - -(defun compare-by-date (a b) - (compare-date (episode-date a) (episode-date b))) - -(defun prompt-read (prompt &optional default) - (format *query-io* "~a~@[ (~a)~]: " prompt default) - (force-output *query-io*) - (let ((answer (read-line *query-io*))) - (if (string= answer "") - default - answer))) - -(defun split (seperator string) - (loop for i = 0 then (1+ j) - as j = (search seperator string :start2 i) - collect (subseq string i j) - while j)) - -(defun get-current-date () +(defun pr-univ-time (utime) (multiple-value-bind - (second minute hour date month year day-of-week dst-p tz) - (get-decoded-time) - (declare (ignore second minute hour day-of-week dst-p tz)) - (list date month year))) + (second minute hour date month year day-of-week dst-p tz) + (decode-universal-time utime) + (declare (ignore day-of-week dst-p tz)) + (format nil "~4,'0d-~2,'0d-~2,'0d ~2,'0d:~2,'0d:~2,'0d" year month date hour minute second))) +(defun pr (&optional (item (find-item-in-db)) (stream t)) + "print an item" + (when item + (format stream "~a: (~a) (~a)~%" + (item-title item) + (item-category item) + (pr-univ-time (item-date item))))) -(defun parse-date (date) - (reverse (mapcar #'parse-integer (split "." date)))) +(defun pr-per-category () + "print the latest item from each category" + (loop for k being the hash-keys in *db-cat* + do (pr (find-item-in-db k)))) -(defun parse-tags (tags) - (when (and tags (string-not-equal "" tags)) - (mapcar #'intern (split " " (string-upcase tags))))) +(defun pr-all () + "print all the items, *db* is sorted by time." + (dolist (itm *db*) (pr itm))) -(defun parse-number (number) - (if (stringp number) - (parse-integer number :junk-allowed t) - number)) +(defun pr-all-categories (&optional (stream t)) + (loop for k being the hash-keys in *db-cat* + do (format stream "(~a) " k))) -(defun prompt-for-episode (&optional last) - (when (not last) - (setf last (make-episode))) - (let* ((series (prompt-read "Series Title" (episode-series last))) - (title (prompt-read "Title")) - (season (parse-number (prompt-read "Season" (episode-season last)))) - (episode (parse-number (prompt-read "Episode" - (if (eq (episode-season last) season) - (1+ (episode-episode last)) - 1)))) - (part (parse-number (prompt-read "Part" - (when (and (episode-part last) - (or (eq (episode-season last) season) - (eq (episode-part last) 1))) - (1+ (episode-part last)))))) - (date (parse-date (prompt-read "Date watched" (format-ymd (get-current-date))))) - (tags (parse-tags (prompt-read "Tags")))) - (make-episode - :series series - :title title - :season season - :episode episode - :part part - :date date - :tags tags))) +(defun insert-item (item) + "insert item into database in a time sorted list. okay for a small list, as per spec." + (let ((first-item (car *db*)) (new-itm item)) + (set-category new-itm) + (push new-itm *db*) + (when (and first-item (>= (item-date new-itm) (item-date first-item))) + (setf *db* (sort *db* #'> :key #'item-date))) + *db*)) -(defun parse-integer-quietly (&rest args) - (ignore-errors (apply #'parse-integer args))) +(defun read-db-from-file (&optional (file *db-file*)) + (with-open-file (in file :if-does-not-exist nil) + (when in + (with-standard-io-syntax (setf *db* (read in))) + (scan-category)))) -(defun get-next-version (basename) - (flet ((parse-version (pathname) - (or (parse-integer-quietly - (string-left-trim (file-namestring basename) - (file-namestring pathname)) - :start 1) 0))) - (let* ((files (directory (format nil "~A,*" (namestring basename)))) - (max (if files - (reduce #'max files :key #'parse-version) - 0))) - (merge-pathnames (format nil "~a,~d" (file-namestring basename) (1+ max)) - basename)))) +(defun save-db-to-file (&optional (file *db-file*)) + (with-open-file (out file :direction :output :if-exists :supersede) + (with-standard-io-syntax + (print *db* out)))) -(defun save-db (dbfile database) - (let ((file (probe-file dbfile))) - (rename-file file (get-next-version file)) - (with-open-file (out file :direction :output) - (with-standard-io-syntax - (let ((*print-case* :downcase)) - (pprint database out)))))) +(defun del-db () + (setf *db* nil) + (save-db-to-file)) -(defun watch-save (dbfile) - (save-db dbfile *db*)) +(defun del-item (itm) + (read-db-from-file) + (setf *db* (remove itm *db* :key #'item-title :test #'string=)) + (save-db-to-file)) -(defun load-db (dbfile) - (with-open-file (in dbfile) - (with-standard-io-syntax - (read in)))) +(defun add-item-to-db (args) + (read-db-from-file) + (insert-item (make-item :title (first args) :category (second args))) + (save-db-to-file)) -(defun get-series (name database) - (cdr (assoc name database :test #'string-equal))) +(defun help-menu () + (format t "clisp db.lisp ~{~15T~a~^~% ~}" + '("delete ------------------- delete an item" + "delete-all --------------------------- delete the database" + "insert --- insert an item with its category" + "show --------------------------------- shows the latest inserted item" + "show-categories ---------------------- show all categories" + "show-all ----------------------------- show all items" + "show-per-category -------------------- show the latest item per category"))) -(defun get-episode-list (series database) - (series-episodes (get-series series database))) +(defun db-cmd-run (args) + (cond ((and (> (length args) 1) (equal (first args) "delete")) + (del-item (second args))) + ((equal (first args) "delete-all") (del-db)) + ((and (> (length args) 2) (equal (first args) "insert")) + (add-item-to-db (rest args))) + ((equal (first args) "show") (read-db-from-file) (pr)) + ((equal (first args) "show-categories") (read-db-from-file) (pr-all-categories)) + ((equal (first args) "show-all") (read-db-from-file) (pr-all)) + ((equal (first args) "show-per-category") (read-db-from-file) (pr-per-category)) + (t (help-menu)))) -(defun print-series (title series) - (format t "~&~30a ~@[ (~{~a~^ ~})~]~%~@[ ~a~%~]" title (series-tags series) - (series-description series)) - (format t "~{~& ~a~%~}" (reverse (series-episodes series)))) - -(defun watch-series (title) - (let ((series (get-series title *db*))) - (when series - (print-series title series)))) - -(defun print-all-series (database) - (loop for (title . series) - in (sort database #'(lambda (a b)(compare-by-date (car (series-episodes (cdr a))) - (car (series-episodes (cdr b)))))) - do (terpri) (print-series title series))) - -(defun watch-all-series () - (print-all-series *db*)) - -(defun watch-latest () - (format t "~{~& ~a~%~}" (sort (get-latest *db*) #'compare-by-date))) - -(defun timeline-all (database) - (let* ((all (get-all database)) - (max (length all)) - (count max) - (all-series-names nil) - (all-series (make-hash-table :test 'equal))) - (loop for episode in (reverse (sort all #'compare-by-date)) - do (unless (gethash (episode-series episode) all-series) - (setf (gethash (episode-series episode) all-series) - (make-array max :initial-element nil)) - (setf all-series-names - (cons (episode-series episode) all-series-names))) - (setf (elt (gethash (episode-series episode) all-series) (decf count)) - episode)) - (values all-series all-series-names max))) - -(defun watch-timeline () - (multiple-value-bind (all-series all-series-names max) (timeline-all *db*) - (loop for series in all-series-names - do (format t "~30a (~{~:[ ~;•~]~})~%" series - (coerce (subseq (gethash series all-series) (- max 60)) 'list))))) - -(defun watch-timelinec () - (multiple-value-bind (all-series all-series-names max) (timeline-all *db*) - (let ((chart (make-array (list (length all-series-names) max) :initial-element nil)) - (newcol 0) - (oldrow -1)) - (loop for oldcol upto (1- max) - do (loop for series in all-series-names - for row from 0 upto (length all-series-names) - do (when (elt (gethash series all-series) oldcol) - (when (<= row oldrow) - (incf newcol)) - (setf (aref chart row newcol) - (elt (gethash series all-series) oldcol)) - (setf oldrow row)))) - (loop for series in all-series-names - for i from 0 upto (length all-series-names) - do (format t "~30a (" series) - (loop for j from (- newcol 60) upto newcol - do (format t "~:[ ~;•~]" (aref chart i j)) - (if (= j newcol) - (format t ")~%"))))))) - -(defun watch-timelinev () - (multiple-value-bind (all-series all-series-names max) (timeline-all *db*) - (loop for series in all-series-names - counting series into count - do (format t "~va ~30a~%" count " " series )) - (loop for i from 0 upto (1- max) - do (let ((episode nil)) - (loop for series in all-series-names - do (format t "~:[ ~;~:*~02a~]" - (when (elt (gethash series all-series) i) - (setf episode (elt (gethash series all-series) i)) - (episode-episode episode)))) - (format t " (~a)~%" (episode-series episode)))))) - -(defun watch-all () - (format t "~{~& ~a~%~}" (sort (get-all *db*) #'compare-by-date))) - -(defun watch-new-series (&key name description tags) - (cdar (push (cons name (make-series :description description :tags tags)) *db*))) - -(defun get-or-add-series (name database) - (or (get-series name database) - (if (y-or-n-p "Add new series? [y/n]: ") - (watch-new-series - :name name - :description (prompt-read "Description" name) - :tags (parse-tags (prompt-read "Tags" "active"))) - nil))) - -(defun watch-add () - (let* ((series (loop thereis (get-or-add-series (prompt-read "Series") *db*))) - (episode (prompt-for-episode (car (series-episodes series))))) - (push episode (series-episodes series)))) - -(defun watch-series-names () - (format T "~{~& ~a~%~}" - (sort (mapcar #'car *db*) - (lambda (series1 series2) - (compare-by-date (car (series-episodes (get-value series1 *db*))) - (car (series-episodes (get-value series2 *db*)))))))) - -(defun exact-match (term text) - (string-equal (format nil "~{~a~^ ~}" term) text)) - -(defun fuzzy-match (term text) - (loop for word in term - when (search word text :test 'string-equal) - collect it)) - -(defun match-tags (term tags) - (intersection (mapcar #'intern term) tags)) - -(defun search-title (term database) - (loop for episode in (get-all database) - when (exact-match term (episode-title episode)) - collect episode)) - -(defun search-tags (term database) - (sort (loop for episode in (get-all database) - for matches = (match-tags term (episode-tags episode)) - when matches collect (list (length matches) episode)) - #'> :key #'car)) - -(defun search-title-fuzzy (term database) - (sort (loop for episode in (get-all database) - for matches = (fuzzy-match term (episode-title episode)) - when matches collect (list (length matches) episode)) - #'> :key #'car)) - -(defun search-all (term database) - (let ((exact-results '()) - (fuzzy-results '()) - (tag-results '())) - (dolist (episode (get-all database)) - (cond ((exact-match term (episode-title episode)) - (push episode exact-results)) - ((fuzzy-match term (episode-title episode)) - (push episode fuzzy-results)) - ((match-tags term (episode-tags episode)) - (push episode tag-results)))) - (append (sort exact-results #'compare-by-date) - (sort tag-results #'compare-by-date) - (sort fuzzy-results #'compare-by-date)))) - -(defun watch-search (term) - (format t "~{~& ~a~%~}" (search-all term *db*))) - -(defun list-all-tags (database) - (let ((tags (make-hash-table :test 'equal))) - (dolist (tag (apply #'append (mapcar #'episode-tags (get-all database)))) - (setf (gethash tag tags) (1+ (or (gethash tag tags) 0)))) - tags)) - -(defun watch-tags () - (maphash #'(lambda (tag count) (format t "~a (~d) " tag count)) - (list-all-tags *db*)) - (terpri)) - -(defun find-series-episode (term database) - (let ((series (get-series (format nil "~{~a~^ ~}" (butlast term)) database))) - (if series - (let* ((season-episode (car (last term))) - (pos (position #\- season-episode)) - (season-str (when pos (subseq season-episode 0 pos))) - (season (or (parse-integer-quietly season-str) season-str)) - (episode-str (if pos - (subseq season-episode (1+ pos)) - season-episode)) - (episode-nr (or (parse-integer-quietly episode-str) episode-str))) - (loop for episode in (series-episodes series) - when (and (equal (episode-episode episode) episode-nr) - (equal (episode-season episode) season)) - collect episode)) - (let ((series (get-series (format nil "~{~a~^ ~}" term) database))) - (if series - (list (car (series-episodes series)))))))) - - -(defun find-episode (term database) - (or (find-series-episode term database) - (search-title term database) - (let* ((res (or (search-tags term database) - (search-title-fuzzy term database))) - (max (caar res))) - (loop for (matches episode) in res when (equal matches max) collect episode)))) - -(defun edit-episode (episode database) - (format t "editing:~%~a~%" episode) - (setf (episode-series episode) - (prompt-read "Series Title" (episode-series episode))) - (setf (episode-title episode) - (prompt-read "Title" (episode-title episode))) - (setf (episode-season episode) - (parse-number (prompt-read "Season" (episode-season episode)))) - (setf (episode-episode episode) - (parse-number (prompt-read "Episode" (episode-episode episode)))) - (setf (episode-part episode) - (parse-number (prompt-read "Part" (episode-part episode)))) - (setf (episode-date episode) - (parse-date (prompt-read "Date watched" (format-ymd (episode-date episode))))) - (setf (episode-tags episode) - (parse-tags (prompt-read "Tags" (format nil "~{~a~^ ~}" (episode-tags episode)))))) - -(defun watch-edit (term) - (let ((episodes (find-episode term *db*))) - (if (> (length episodes) 1) - (format t "found more than one episode, please be more specific:~%~{~& ~a~%~}" episodes) - (edit-episode (car episodes) *db*)))) - -(defun watch-load (dbfile) - (setf *db* (load-db dbfile))) - - -(defun argv () +;; modified https://rosettacode.org/wiki/Command-line_arguments#Common_Lisp +(defun db-argv () (or - #+clisp (ext:argv) - #+sbcl sb-ext:*posix-argv* - #+clozure (ccl::command-line-arguments) - #+gcl si:*command-args* - #+ecl (loop for i from 0 below (si:argc) collect (si:argv i)) - #+cmu extensions:*command-line-strings* - #+allegro (sys:command-line-arguments) - #+lispworks sys:*line-arguments-list* - nil)) + #+clisp ext:*args* + #+sbcl (cdr sb-ext:*posix-argv*) + #+allegro (cdr (sys:command-line-arguments)) + #+lispworks (cdr sys:*line-arguments-list*) + nil)) -(defun main (argv) - (let ((dbfile (make-pathname :name "lwatch" :type nil :defaults *load-pathname*))) - (watch-load dbfile) - (format t "loaded db~%") - (cond ((equal (cadr argv) "add") (watch-add) (watch-save dbfile)) - ((equal (cadr argv) "latest") (watch-latest)) - ((null (cadr argv)) (watch-latest)) - ((equal (cadr argv) "series") (watch-series-names)) - ((and (equal (cadr argv) "all") (equal (caddr argv) "series")) (watch-all-series)) - ((equal (cadr argv) "all") (watch-all)) - ((equal (cadr argv) "tags") (watch-tags)) - ((equal (cadr argv) "search") (watch-search (cddr argv))) - ((equal (cadr argv) "edit") (watch-edit (cddr argv)) (watch-save dbfile)) - ((equal (cadr argv) "timeline") (watch-timeline)) - ((equal (cadr argv) "timelinev") (watch-timelinev)) - ((equal (cadr argv) "timelinec") (watch-timelinec)) - (T (watch-series (format nil "~{~a~^ ~}" (cdr argv))))))) - -(main (argv)) +(db-cmd-run (db-argv)) diff --git a/Task/Simple-windowed-application/Elena/simple-windowed-application.elena b/Task/Simple-windowed-application/Elena/simple-windowed-application.elena index 50cd41e848..84de3b32a8 100644 --- a/Task/Simple-windowed-application/Elena/simple-windowed-application.elena +++ b/Task/Simple-windowed-application/Elena/simple-windowed-application.elena @@ -1,15 +1,16 @@ -#import system. -#import forms. -#import extensions. +import forms. +import extensions. -#class Window +class Window { - #field form. - #field lblClicks. - #field btmClickMe. - #field clicksCount. + object form. + object lblClicks. + object btmClickMe. - #constructor new + //Store how much clicks the user doed + object clicksCount. + + constructor new [ form := SDIDialog new. lblClicks := Label new. @@ -17,30 +18,32 @@ clicksCount := 0. - form controls append:lblClicks. - form controls append:btmClickMe. + form controls; + append:lblClicks; + append:btmClickMe. - form set &caption:"Rosseta Code". - form set &x:100 &y:100. - form set &width:160 &height:80. + form + set caption:"Rosseta Code"; + set x:100 y:100; + set width:160 height:80. - lblClicks set &x:10 &y:2. - lblClicks set &width:160 &height:20. - lblClicks set &caption:"Clicks: 0". + lblClicks + set x:10 y:2; + set width:160 height:20; + set caption:"Clicks: 0". - btmClickMe set &x:7 &y:20. - btmClickMe set &width:140 &height:30. - btmClickMe set &caption:"Click me". - btmClickMe set &onClick:args - - [ $self $onButtonClick. ]. + btmClickMe + set x:7 y:20; + set width:140 height:30; + set caption:"Click me"; + set onClick(:args)[ $self $onButtonClick ] ] - #method $onButtonClick + $onButtonClick [ clicksCount := clicksCount + 1. - lblClicks set &caption:("Clicks: " + clicksCount literal). + lblClicks set caption("Clicks: " + clicksCount literal). ] - #method => form. + dispatch => form. } diff --git a/Task/Simple-windowed-application/Gambas/simple-windowed-application.gambas b/Task/Simple-windowed-application/Gambas/simple-windowed-application.gambas new file mode 100644 index 0000000000..4a072e9b5f --- /dev/null +++ b/Task/Simple-windowed-application/Gambas/simple-windowed-application.gambas @@ -0,0 +1,37 @@ +iCount As Integer 'Counter of clicks! +hLabel As Label 'We need a Label + +Public Sub Form_Open() +Dim hButton As Button 'We need a Button + +With Me 'Set the Form's Properties.. + .height = 75 'Set the Height + .Width = 300 'Set the Width + .Arrangement = Arrange.Vertical 'Arrange items vertically + .Padding = 5 'Border area + .Title = "Click counter!" 'Title displayed on the Form +End With + +hlabel = New Label(Me) 'Add a Label to the form + +With hlabel 'Set the Label's Properties.. + .expand = True 'Expand the Label to fit the Form + .Text = "There have been no clicks yet" 'Add Text to the Label + .Alignment = Align.Center 'Center the Text +End With + +hButton = New Button(Me) As "Button1" 'Add a Button to the form as Event "Button1" + +With hButton 'Set the Button's Properties.. + .Height = 28 'Set the Height + .Text = "&Click me" 'Add Text (The '&' adds a keyboard shortcut) +End With + +End + +Public Sub Button1_Click() 'When the Button is clicked.. + +Inc iCount 'Increase the value of iCount +hLabel.text = "The button has been clicked " & iCount & " times" 'Display the amount of clicks" + +End diff --git a/Task/Simple-windowed-application/Gastona/simple-windowed-application.gastona b/Task/Simple-windowed-application/Gastona/simple-windowed-application.gastona new file mode 100644 index 0000000000..1ae93fe9d2 --- /dev/null +++ b/Task/Simple-windowed-application/Gastona/simple-windowed-application.gastona @@ -0,0 +1,18 @@ +#javaj# + + main, Simple click counter + + + PANEL, X + bClick me, lClicks + +#data# + + 0 + //There have been no clicks yet + +#listix# + + <-- bClick me> + NUM=, NN, NN+1 + -->, lClicks data!,, //@ clicks so far diff --git a/Task/Simple-windowed-application/Kotlin/simple-windowed-application.kotlin b/Task/Simple-windowed-application/Kotlin/simple-windowed-application.kotlin new file mode 100644 index 0000000000..379f45edad --- /dev/null +++ b/Task/Simple-windowed-application/Kotlin/simple-windowed-application.kotlin @@ -0,0 +1,38 @@ +// version 1.0.6 + +import java.awt.BorderLayout +import java.awt.event.ActionEvent +import java.awt.event.ActionListener +import javax.swing.* + +class Clicks : JFrame(), ActionListener { + private var clicks = 0 + private val label: JLabel + private val clicker: JButton + private var text: String + + init { + text = "There have been no clicks yet" + label = JLabel(text) + clicker = JButton("click me") + clicker.addActionListener(this) // listen to the button + layout = BorderLayout() // handles placement of components + add(label, BorderLayout.CENTER) // add the label to the biggest section + add(clicker, BorderLayout.SOUTH) // put the button underneath it + setSize(300, 200) // stretch out the window + defaultCloseOperation = EXIT_ON_CLOSE // stop the program on "X" + isVisible = true // show it + } + + override fun actionPerformed(arg0: ActionEvent) { + if (arg0.source == clicker) { // if they clicked the button + if (clicks == 0) text = "There has been " + (++clicks) + " click" + else text = "There have been " + (++clicks) + " clicks" + label.text = text // change the text + } + } +} + +fun main(args: Array) { + Clicks() // call the constructor where all the magic happens +} diff --git a/Task/Simple-windowed-application/Lambdatalk/simple-windowed-application.lambdatalk b/Task/Simple-windowed-application/Lambdatalk/simple-windowed-application.lambdatalk new file mode 100644 index 0000000000..6985c30460 --- /dev/null +++ b/Task/Simple-windowed-application/Lambdatalk/simple-windowed-application.lambdatalk @@ -0,0 +1,13 @@ +1) the label: {div {@ id="label"} There have been no clicks yet } +2) the button: {input {@ type="button" value="click me" onclick="CLICKAPP.inc()" }} +3) the script: {script °° code °°} where code is a single function: + +var CLICKAPP = (function() { + var counter = 0; + var inc = function() { + counter++; + getId('label').innerHTML = + 'There are ' + counter + ' clicks now'; + }; + return {inc:inc} +})(); diff --git a/Task/Simple-windowed-application/OoRexx/simple-windowed-application.rexx b/Task/Simple-windowed-application/OoRexx/simple-windowed-application.rexx new file mode 100644 index 0000000000..d14ac9bbd2 --- /dev/null +++ b/Task/Simple-windowed-application/OoRexx/simple-windowed-application.rexx @@ -0,0 +1,85 @@ +/* REXX *************************************************************************************** +* 18.06.2014 Walter Pachl shortened from Rony Flatscher's bsf4oorexx (see sourceforge) samples +* Look there for ShowCount.rxj +* bsf4oorexx lets the ooRexx program use Java classes +**********************************************************************************************/ +userData=.directory~new -- a directory which will be passed to Rexx with the event + + -- create a framed Java window, set a title text +win=.bsf~new("java.awt.Frame", "Show Count") + -- Create a Java RexxProxy for controlling the closing of the application +rexxCloseEH =.RexxCloseAppEventHandler~new -- Rexx event handler + -- Create Java RexxProxy for the Rexx event handler +rpCloseEH=BsfCreateRexxProxy(rexxCloseEH,,"java.awt.event.WindowListener" ) +win~addWindowListener(rpCloseEH) -- add RexxProxy event handler + + -- create a Java push button +but=.bsf~new("java.awt.Button","Press me!") + -- Create a RexxProxy for the button Rexx event handler +rp=BsfCreateRexxProxy(.RexxShowCountEventHandler~new,userData,"java.awt.event.ActionListener") +but~addActionListener(rp) -- add RexxProxy event handler + +lab=.bsf~new("java.awt.Label") -- create a Java label,set it to show the text centered +userData~label=lab -- save label object for later use in event handler +lab~setAlignment(lab~center) -- set alignment to center +lab~setText("Button was not yet pressed") -- assign initial text to the label + +win ~~add("Center",lab) ~~add("South",but) -- add the label and the button to the frame +win ~~pack -- now calculate all widget dimensions +call enlargeWidth win,but,120 -- enlarge the width of the frame and the button + +win ~~setVisible(.true) ~~toFront -- make frame visible and move it to the front + +userData~i=0 -- set counter to 0 + +rexxCloseEH~waitForExit -- wait until we are allowed to end the program + +-- if Java was loaded by Rexx,then terminate Java's RexxEngine to inhibit callbacks from Java +call BSF.terminateRexxEngine + +::requires BSF.CLS -- get Java support + + /* enlarge the width of the frame and of the button without using a layout manager */ +::routine enlargeWidth + use arg win,but,addToWidth + winDim=win~getSize -- get frame's dimension + winDim~width+=addToWidth -- increase width + win~setSize(winDim) -- set frame's dimension + +/* ------------------------------------------------------------------------ */ +/* Rexx event handler to set "close app" indicator */ +::class RexxCloseAppEventHandler +::method init -- constructor + expose closeApp + closeApp = .false -- if set to .true, then it is safe to close the app + +::attribute closeApp -- indicates whether app should be closed + +::method unknown -- intercept unhandled events,do nothing + +::method windowClosing -- event method (from WindowListener) + expose closeApp + closeApp=.true -- indicate that the app should close + +::method waitForExit -- method blocks until attribute is set to .true + expose closeApp + guard on when closeApp=.true + +/* ------------------------------------------------------------------------ */ +/* Rexx event handler to process tab changes */ +::class RexxShowCountEventHandler +::method actionPerformed + use arg eventObject,slotDir + call showCount slotDir~userData + +/* ------------------------------------------------------------------------ */ +::routine ShowCount -- increment counter and show text + use arg userData + userData~i+=1 -- increment counter in directory object + Select -- construct text part + When userData~i=1 Then how_often='once' + When userData~i=2 Then how_often='twice' + When userData~i=3 Then how_often='three times' + Otherwise how_often=userData~i 'times' + End + userData~label~setText("Button was pressed" how_often) -- display text diff --git a/Task/Simulate-input-Keyboard/Kotlin/simulate-input-keyboard.kotlin b/Task/Simulate-input-Keyboard/Kotlin/simulate-input-keyboard.kotlin new file mode 100644 index 0000000000..46ca652f15 --- /dev/null +++ b/Task/Simulate-input-Keyboard/Kotlin/simulate-input-keyboard.kotlin @@ -0,0 +1,21 @@ +// version 1.1.2 + +import java.awt.Robot +import java.awt.event.KeyEvent + +fun sendChars(s: String, pressReturn: Boolean = true) { + val r = Robot() + for (c in s) { + val ci = c.toUpperCase().toInt() + r.keyPress(ci) + r.keyRelease(ci) + } + if (pressReturn) { + r.keyPress(KeyEvent.VK_ENTER) + r.keyRelease(KeyEvent.VK_ENTER) + } +} + +fun main(args: Array) { + sendChars("dir") // runs 'dir' command +} diff --git a/Task/Simulate-input-Mouse/Julia/simulate-input-mouse.julia b/Task/Simulate-input-Mouse/Julia/simulate-input-mouse.julia new file mode 100644 index 0000000000..9943ff968a --- /dev/null +++ b/Task/Simulate-input-Mouse/Julia/simulate-input-mouse.julia @@ -0,0 +1,9 @@ +# Wrap win32 API function mouse_event() from the User32 dll. +function mouse_event_wrapper(dwFlags,dx,dy,dwData,dwExtraInfo) + ccall((:mouse_event, "User32"),stdcall,Void,(UInt32,UInt32,UInt32,UInt32,UInt),dwFlags,dx,dy,dwData,dwExtraInfo) +end + +function click() + mouse_event_wrapper(0x2,0,0,0,0) + mouse_event_wrapper(0x4,0,0,0,0) +end diff --git a/Task/Simulate-input-Mouse/Kotlin/simulate-input-mouse.kotlin b/Task/Simulate-input-Mouse/Kotlin/simulate-input-mouse.kotlin new file mode 100644 index 0000000000..ea69569fd5 --- /dev/null +++ b/Task/Simulate-input-Mouse/Kotlin/simulate-input-mouse.kotlin @@ -0,0 +1,14 @@ +// version 1.1.2 + +import java.awt.Robot +import java.awt.event.InputEvent + +fun sendClick(buttons: Int) { + val r = Robot() + r.mousePress(buttons) + r.mouseRelease(buttons) +} + +fun main(args: Array) { + sendClick(InputEvent.BUTTON3_DOWN_MASK) // simulate a click of the mouse's right button +} diff --git a/Task/Singleton/C++/singleton-1.cpp b/Task/Singleton/C++/singleton-1.cpp deleted file mode 100644 index 2a97fe1426..0000000000 --- a/Task/Singleton/C++/singleton-1.cpp +++ /dev/null @@ -1,38 +0,0 @@ -class Singleton -{ -public: - static Singleton* Instance() - { - // We need to ensure that we don't accidentally create two Singletons - HANDLE hMutex = CreateMutex(NULL, FALSE, "MySingletonMutex"); - WaitForSingleObject(hMutex, INFINITE); - - // Create the instance of the class. - // Since it's a static variable, if the class has already been created, - // It won't be created again. - static Singleton myInstance; - - // Release our mutex so that other application threads can use this function - ReleaseMutex( hMutex ); - - // Free the handle - CloseHandle( hMutex ); - - // Return a pointer to our mutex instance. - return &myInstance; - } - - // Any other public methods - -protected: - Singleton() - { - // Constructor code goes here. - } - ~Singleton() - { - // Destructor code goes here. - } - - // And any other protected methods. -} diff --git a/Task/Singleton/C++/singleton-2.cpp b/Task/Singleton/C++/singleton-2.cpp deleted file mode 100644 index ff52ce3270..0000000000 --- a/Task/Singleton/C++/singleton-2.cpp +++ /dev/null @@ -1,27 +0,0 @@ -class Singleton -{ -public: - static Singleton* Instance() - { - // Since it's a static variable, if the class has already been created, - // It won't be created again. - static Singleton myInstance; - - // Return a pointer to our mutex instance. - return &myInstance; - } - - // Any other public methods - -protected: - Singleton() - { - // Constructor code goes here. - } - ~Singleton() - { - // Destructor code goes here. - } - - // And any other protected methods. -} diff --git a/Task/Singleton/C++/singleton-3.cpp b/Task/Singleton/C++/singleton-3.cpp deleted file mode 100644 index a1bc2611cc..0000000000 --- a/Task/Singleton/C++/singleton-3.cpp +++ /dev/null @@ -1,36 +0,0 @@ -class Singleton -{ -public: - static Singleton & Instance() - { - // Since it's a static variable, if the class has already been created, - // It won't be created again. - // And it **is** thread-safe in C++11. - - static Singleton myInstance; - - // Return a reference to our instance. - return myInstance; - } - - // delete copy and move constructors and assign operators - Singleton(Singleton const&) = delete; // Copy construct - Singleton(Singleton&&) = delete; // Move construct - Singleton& operator=(Singleton const&) = delete; // Copy assign - Singleton& operator=(Singleton &&) = delete; // Move assign - - // Any other public methods - -protected: - Singleton() - { - // Constructor code goes here. - } - - ~Singleton() - { - // Destructor code goes here. - } - - // And any other protected methods. -} diff --git a/Task/Singleton/C++/singleton.cpp b/Task/Singleton/C++/singleton.cpp new file mode 100644 index 0000000000..7d7b0bcf6f --- /dev/null +++ b/Task/Singleton/C++/singleton.cpp @@ -0,0 +1,99 @@ +#include + +template +class singleton +{ +protected: + static Self* + sentry; +public: + static Self& + instance() + { + return *sentry; + } + singleton() + { + if(sentry) + throw std::logic_error("Error: attempt to instantiate a singleton over a pre-existing one!"); + sentry = (Self*)this; + } + virtual ~singleton() + { + if(sentry == this) + sentry = 0; + } +}; +template +Self* + singleton::sentry = 0; + +/* + Example usage: +*/ + +#include +#include + +using namespace + std; + +class controller : public singleton +{ +public: + controller(string const& name) + : name(name) + { + trace("begin"); + } + ~controller() + { + trace("end"); + } + void + work() + { + trace("doing stuff"); + } + void + trace(string const& message) + { + cout << name << ": " << message << endl; + } + string + name; +}; +int + main() +{ + controller* + first = new controller("first"); + controller::instance().work(); + delete first; +/* + No problem, our first controller no longer exists... +*/ + controller + second("second"); + controller::instance().work(); + try + { + /* + Never happens... + */ + controller + goner("goner"); + controller::instance().work(); + } + catch(exception const& error) + { + cout << error.what() << endl; + } + controller::instance().work(); +/* + Never happens (and depending on your system this may or may not print a helpful message!) +*/ + controller + goner("goner"); + controller::instance().work(); +} diff --git a/Task/Singleton/Elena/singleton-1.elena b/Task/Singleton/Elena/singleton-1.elena index 096a18c50f..3b2353d64f 100644 --- a/Task/Singleton/Elena/singleton-1.elena +++ b/Task/Singleton/Elena/singleton-1.elena @@ -1,4 +1,4 @@ -#symbol singleton = +class singleton = { // ... }. diff --git a/Task/Singleton/Elena/singleton-2.elena b/Task/Singleton/Elena/singleton-2.elena index a5ac237a25..aa5161fdac 100644 --- a/Task/Singleton/Elena/singleton-2.elena +++ b/Task/Singleton/Elena/singleton-2.elena @@ -1,8 +1,8 @@ -#class $Singleton +class $Singleton { - #field theField. + object theField. // ... } -#static singleton = $Singleton new. +static singleton = $Singleton new. diff --git a/Task/Singleton/Kotlin/singleton.kotlin b/Task/Singleton/Kotlin/singleton.kotlin new file mode 100644 index 0000000000..2b3721496a --- /dev/null +++ b/Task/Singleton/Kotlin/singleton.kotlin @@ -0,0 +1,9 @@ +// version 1.1.2 + +object Singleton { + fun speak() = println("I am a singleton") +} + +fun main(args: Array) { + Singleton.speak() +} diff --git a/Task/Singleton/OoRexx/singleton.rexx b/Task/Singleton/OoRexx/singleton.rexx new file mode 100644 index 0000000000..4b39d31797 --- /dev/null +++ b/Task/Singleton/OoRexx/singleton.rexx @@ -0,0 +1,32 @@ +a = .singleton~new +b = .singleton~new + +a~foo = "Rick" +if a~foo \== b~foo then say "A and B are not the same object" + +::class singleton +-- initialization method for the class +::method init class + expose singleton + -- mark this as unallocated. We could also just allocate + -- the singleton now, but better practice is probably wait + -- until it is requested + singleton = .nil + +-- override the new method. Since this is a guarded +-- method by default, this is thread safe +::method new class + expose singleton + -- first request? Do the real creation now + if singleton == .nil then do + -- forward to the super class. We use this form of + -- FORWARD rather than explicit call ~new:super because + -- this takes care of any arguments passed to NEW as well. + forward class(super) continue + singleton = result + end + return singleton + +-- an attribute that can be used to demonstrate this really is +a singleton. +::attribute foo diff --git a/Task/Singleton/Swift/singleton.swift b/Task/Singleton/Swift/singleton.swift new file mode 100644 index 0000000000..0d30ebfd56 --- /dev/null +++ b/Task/Singleton/Swift/singleton.swift @@ -0,0 +1,11 @@ +class SingletonClass { + +static let sharedInstance = SingletonClass() + + ///Override the init method and make it private + private override init(){ + // User can do additional manipulations here. + } +} +// Usage +let sharedObject = SingletonClass.sharedInstance diff --git a/Task/Singleton/Zkl/singleton.zkl b/Task/Singleton/Zkl/singleton.zkl new file mode 100644 index 0000000000..597fe3a695 --- /dev/null +++ b/Task/Singleton/Zkl/singleton.zkl @@ -0,0 +1,4 @@ +class [static] Borg{ var v } +b1 := Borg; b2 := Borg(); +b1 == b2 //--> True +b1.v=123; b2.v.println(); //--> 123 diff --git a/Task/Singly-linked-list-Element-definition/360-Assembly/singly-linked-list-element-definition.360 b/Task/Singly-linked-list-Element-definition/360-Assembly/singly-linked-list-element-definition.360 new file mode 100644 index 0000000000..a3eed791db --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/360-Assembly/singly-linked-list-element-definition.360 @@ -0,0 +1,87 @@ +* Singly-linked list/Element definition 07/02/2017 +LISTSINA CSECT + USING LISTSINA,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) prolog + ST R13,4(R15) " <- + ST R15,8(R13) " -> + LR R13,R15 " addressability +* Allocate A + GETMAIN RU,LV=12 get storage + USING NODE,R11 make storage addressable + LR R11,R1 " + MVC VAL,=CL8'A' val='A' + MVC NEXT,=A(0) + DROP R11 base no longer needed + ST R11,A A=@A +* Init LIST + ST R11,LIST init LIST with A +* Allocate C + GETMAIN RU,LV=12 get storage + USING NODE,R11 make storage addressable + LR R11,R1 " + MVC VAL,=CL8'C' val='C' + MVC NEXT,=A(0) + DROP R11 base no longer needed + ST R11,C C=@C +* Insert C After A + MVC P1,A + MVC P2,C + LA R1,PARML + BAL R14,INSERTAF +* Allocate B + GETMAIN RU,LV=12 get storage + USING NODE,R11 make storage addressable + LR R11,R1 " + MVC VAL,=CL8'B' val='B' + MVC NEXT,=A(0) + DROP R11 base no longer needed + ST R11,B B=@B +* Insert B After A + MVC P1,A + MVC P2,B + LA R1,PARML + BAL R14,INSERTAF +* List all + L R11,LIST + USING NODE,R11 address node +LOOP C R11,=A(0) + BE ENDLIST + XPRNT VAL,8 + L R11,NEXT + B LOOP +ENDLIST DROP R11 + FREEMAIN A=A,LV=12 free A + FREEMAIN A=B,LV=12 free B + FREEMAIN A=C,LV=12 free C +RETURN L R13,4(0,R13) epilog + LM R14,R12,12(R13) " restore + XR R15,R15 " rc=0 + BR R14 exit +LIST DS A list head +A DS A +B DS A +C DS A +PARML DS 0A +P1 DS A +P2 DS A +INSERTAF CNOP 0,4 + L R2,0(R1) @A + L R3,4(R1) @B + USING NODE,R2 ->A + L R4,NEXT @C + DROP R2 + USING NODE,R3 ->B + ST R4,NEXT B.NEXT=@C + DROP R3 + USING NODE,R2 ->A + ST R3,NEXT A.NEXT=@B + DROP R2 + BR R14 return + LTORG all literals +NODE DSECT node (size=12) +VAL DS CL8 +NEXT DS A + YREGS + END LISTSINA diff --git a/Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition-1.julia b/Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition-1.julia index 00c1a078c0..20c2a6cd86 100644 --- a/Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition-1.julia +++ b/Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition-1.julia @@ -1,12 +1,12 @@ type Node{T} data::T - next::Node{T} + next::Nullable{Node{T}} function Node(data::T) n = new() n.data = data - # mark the end of the list. Julia does not have nil or null. - n.next = n + # To mark the end of the list we use the Nullable{T}() function . + n.next = Nullable{Node{T}}() n end end @@ -16,7 +16,7 @@ function Node(data) return Node{typeof(data)}(data) end -islast(n::Node) = (n == n.next) +islast(n::Node) = (isnull(n.next)) function append{T}(n::Node{T}, data::T) tmp = Node(data) 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.kotlin new file mode 100644 index 0000000000..0460980bd8 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Kotlin/singly-linked-list-element-definition.kotlin @@ -0,0 +1,18 @@ +// version 1.1.2 + +class Node(var data: T, var next: Node? = null) { + override fun toString(): String { + val sb = StringBuilder(this.data.toString()) + var node = this.next + while (node != null) { + sb.append(" -> ", node.data.toString()) + node = node.next + } + return sb.toString() + } +} + +fun main(args: Array) { + val n = Node(1, Node(2, Node(3))) + println(n) +} diff --git a/Task/Singly-linked-list-Element-definition/OoRexx/singly-linked-list-element-definition.rexx b/Task/Singly-linked-list-Element-definition/OoRexx/singly-linked-list-element-definition.rexx new file mode 100644 index 0000000000..54b55b77da --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/OoRexx/singly-linked-list-element-definition.rexx @@ -0,0 +1,133 @@ +list = .linkedlist~new +index = list~insert("abc") -- insert a first item, keeping the index +list~insert("def") -- adds to the end +list~insert("123", .nil) -- adds to the begining +list~insert("456", index) -- inserts between "abc" and "def" +list~remove(index) -- removes "abc" + +say "Manual list traversal" +index = list~first -- demonstrate traversal +loop while index \== .nil + say index~value + index = index~next +end + +say +say "Do ... Over traversal" +do value over list + say value +end + +-- the main list item, holding the anchor to the links. +::class linkedlist +::method init + expose anchor + + -- create this as an empty list + anchor = .nil + +-- return first link element +::method first + expose anchor + return anchor + +-- return last link element +::method last + expose anchor + + current = anchor + loop while current \= .nil + -- found the last one + if current~next == .nil then return current + current = current~next + end + -- empty + return .nil + +-- insert a value into the list, using the convention +-- followed by the built-in list class. If the index item +-- is omitted, add to the end. If the index item is .nil, +-- add to the end. Otherwise, just chain to the provided link. +::method insert + expose anchor + use arg value + + newLink = .link~new(value) + -- adding to the end + if arg() == 1 then do + if anchor == .nil then anchor = newLink + else self~last~insert(newLink) + end + else do + use arg ,index + if index == .nil then do + if anchor \== .nil then newLink~next = anchor + anchor = newLink + end + else index~insert(newLink) + end + -- the link item serves as an "index" + return newLink + +-- remove a link from the chain +::method remove + expose anchor + + use strict arg index + + -- handle the edge case + if index == anchor then anchor = anchor~next + else do + -- no back link, so we need to scan + previous = self~findPrevious(index) + -- invalid index, don't return any item + if previous == .nil then return .nil + previous~next = index~next + end + -- belt-and-braces, remove the link and return the value + index~next = .nil + return index~value + +-- private method to find a link predecessor +::method findPrevious private + expose anchor + use strict arg index + + -- we're our own precessor if this first + if index == anchor then return self + + current = anchor + loop while current \== .nil + if current~next == index then return current + current = current~next + end + -- not found + return .nil + +-- helper method to allow DO ... OVER traversal +::method makearray + expose anchor + array = .array~new + + current = anchor + loop while current \= .nil + array~append(current~value) + current = current~next + end + return array + +::class link +::method init + expose value next + -- by default, initialize both data and next to empty. + use strict arg value = .nil, next = .nil + +-- allow external access to value and next link +::attribute value +::attribute next + +::method insert + expose next + use strict arg newNode + newNode~next = next + next = newNode diff --git a/Task/Singly-linked-list-Element-definition/Phix/singly-linked-list-element-definition.phix b/Task/Singly-linked-list-Element-definition/Phix/singly-linked-list-element-definition.phix new file mode 100644 index 0000000000..24f13334ec --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Phix/singly-linked-list-element-definition.phix @@ -0,0 +1,4 @@ +enum NEXT,DATA +type slnode(object x) + return (sequence(x) and length(x)=DATA and myotherudt(x[DATA]) and integer(x[NEXT]) +end type diff --git a/Task/Singly-linked-list-Element-definition/Swift/singly-linked-list-element-definition.swift b/Task/Singly-linked-list-Element-definition/Swift/singly-linked-list-element-definition.swift new file mode 100644 index 0000000000..f36b5f89ee --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Swift/singly-linked-list-element-definition.swift @@ -0,0 +1,8 @@ +class Node{ + var data:T?=nil + var next:Node?=nil + init(input:T){ + data=input + next=nil + } +} diff --git a/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-1.x86 b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-1.x86 index 412ad6a103..a2c505a637 100644 --- a/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-1.x86 +++ b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-1.x86 @@ -1,4 +1,13 @@ -struct link -.next: resd 1 -.data: resd 1 +; x86_64 Linux NASM +; Linked_List_Definition.asm + +%ifndef LinkedListDefinition +%define LinkedListDefinition + +struc link + value: resd 1 + next: resq 1 + linkSize: endstruc + +%endif diff --git a/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-2.x86 b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-2.x86 index 83e1c1bd5e..412ad6a103 100644 --- a/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-2.x86 +++ b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-2.x86 @@ -1 +1,4 @@ -link resb 16 +struct link +.next: resd 1 +.data: resd 1 +endstruc diff --git a/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-3.x86 b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-3.x86 index 3c3b03702b..83e1c1bd5e 100644 --- a/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-3.x86 +++ b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-3.x86 @@ -1,4 +1 @@ -link struct -next dd ? -data dd ? -link ends +link resb 16 diff --git a/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-4.x86 b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-4.x86 index 14bed8e654..3c3b03702b 100644 --- a/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-4.x86 +++ b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-4.x86 @@ -1,5 +1,4 @@ -struc link next,data -{ - .next dd next - .data dd data -} +link struct +next dd ? +data dd ? +link ends diff --git a/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-5.x86 b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-5.x86 new file mode 100644 index 0000000000..14bed8e654 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-5.x86 @@ -0,0 +1,5 @@ +struc link next,data +{ + .next dd next + .data dd data +} diff --git a/Task/Singly-linked-list-Element-definition/Zkl/singly-linked-list-element-definition.zkl b/Task/Singly-linked-list-Element-definition/Zkl/singly-linked-list-element-definition.zkl new file mode 100644 index 0000000000..416d1c3b51 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Zkl/singly-linked-list-element-definition.zkl @@ -0,0 +1,2 @@ +List(1,"two",3.14); L(1,"two",3.14); +ROList(fcn{"foobar"}); T('+); diff --git a/Task/Singly-linked-list-Element-insertion/00DESCRIPTION b/Task/Singly-linked-list-Element-insertion/00DESCRIPTION index 960192a6f8..e0006fa848 100644 --- a/Task/Singly-linked-list-Element-insertion/00DESCRIPTION +++ b/Task/Singly-linked-list-Element-insertion/00DESCRIPTION @@ -3,3 +3,4 @@ Using the link element defined in [[Singly-Linked List (element)]], define a met Using this method, insert an element C into a list comprised of elements A->B, following element A. {{Template:See also lists}} +

    diff --git a/Task/Singly-linked-list-Element-insertion/360-Assembly/singly-linked-list-element-insertion.360 b/Task/Singly-linked-list-Element-insertion/360-Assembly/singly-linked-list-element-insertion.360 new file mode 100644 index 0000000000..fcdce6b09f --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/360-Assembly/singly-linked-list-element-insertion.360 @@ -0,0 +1,87 @@ +* Singly-linked list - Insert after 01/02/2017 +LISTSINA CSECT + USING LISTSINA,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) prolog + ST R13,4(R15) " <- + ST R15,8(R13) " -> + LR R13,R15 " addressability +* Allocate A + GETMAIN RU,LV=12 get storage + USING NODE,R11 make storage addressable + LR R11,R1 " + MVC VAL,=CL8'A' val='A' + MVC NEXT,=A(0) + DROP R11 base no longer needed + ST R11,A A=@A +* Init LIST + ST R11,LIST init LIST with A +* Allocate C + GETMAIN RU,LV=12 get storage + USING NODE,R11 make storage addressable + LR R11,R1 " + MVC VAL,=CL8'C' val='C' + MVC NEXT,=A(0) + DROP R11 base no longer needed + ST R11,C C=@C +* Insert C After A + MVC P1,A + MVC P2,C + LA R1,PARML + BAL R14,INSERTAF +* Allocate B + GETMAIN RU,LV=12 get storage + USING NODE,R11 make storage addressable + LR R11,R1 " + MVC VAL,=CL8'B' val='B' + MVC NEXT,=A(0) + DROP R11 base no longer needed + ST R11,B B=@B +* Insert B After A + MVC P1,A + MVC P2,B + LA R1,PARML + BAL R14,INSERTAF +* List all + L R11,LIST + USING NODE,R11 address node +LOOP C R11,=A(0) + BE ENDLIST + XPRNT VAL,8 + L R11,NEXT + B LOOP +ENDLIST DROP R11 + FREEMAIN A=A,LV=12 free A + FREEMAIN A=B,LV=12 free B + FREEMAIN A=C,LV=12 free C +RETURN L R13,4(0,R13) epilog + LM R14,R12,12(R13) " restore + XR R15,R15 " rc=0 + BR R14 exit +LIST DS A list head +A DS A +B DS A +C DS A +PARML DS 0A +P1 DS A +P2 DS A +INSERTAF CNOP 0,4 + L R2,0(R1) @A + L R3,4(R1) @B + USING NODE,R2 ->A + L R4,NEXT @C + DROP R2 + USING NODE,R3 ->B + ST R4,NEXT B.NEXT=@C + DROP R3 + USING NODE,R2 ->A + ST R3,NEXT A.NEXT=@B + DROP R2 + BR R14 return + LTORG all literals +NODE DSECT node (size=12) +VAL DS CL8 +NEXT DS A + YREGS + END LISTSINA 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.kotlin new file mode 100644 index 0000000000..fd9cc470da --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Kotlin/singly-linked-list-element-insertion.kotlin @@ -0,0 +1,27 @@ +// version 1.1.2 + +class Node(var data: T, var next: Node? = null) { + override fun toString(): String { + val sb = StringBuilder(this.data.toString()) + var node = this.next + while (node != null) { + sb.append(" -> ", node.data.toString()) + node = node.next + } + return sb.toString() + } +} + +fun insertAfter(prev: Node, new: Node) { + new.next = prev.next + prev.next = new +} + +fun main(args: Array) { + val b = Node(3) + val a = Node(1, b) + println("Before insertion : $a") + val c = Node(2) + insertAfter(a, c) + println("After insertion : $a") +} diff --git a/Task/Singly-linked-list-Element-insertion/OoRexx/singly-linked-list-element-insertion.rexx b/Task/Singly-linked-list-Element-insertion/OoRexx/singly-linked-list-element-insertion.rexx new file mode 100644 index 0000000000..430279f6c4 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/OoRexx/singly-linked-list-element-insertion.rexx @@ -0,0 +1,6 @@ +list = .linkedlist~new +index = list~insert("abc") -- insert a first item, keeping the index +list~insert("def") -- adds to the end +list~insert("123", .nil) -- adds to the begining +list~insert("456", index) -- inserts between "abc" and "def" +list~remove(index) -- removes "abc" diff --git a/Task/Singly-linked-list-Element-insertion/Phix/singly-linked-list-element-insertion.phix b/Task/Singly-linked-list-Element-insertion/Phix/singly-linked-list-element-insertion.phix new file mode 100644 index 0000000000..4fa30c46dc --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Phix/singly-linked-list-element-insertion.phix @@ -0,0 +1,14 @@ +enum NEXT,DATA +constant empty_sll = {{1}} +sequence sll = empty_sll + +procedure insert_after(object data, integer pos=length(sll)) + sll = append(sll,{sll[pos][NEXT],data}) + sll[pos][NEXT] = length(sll) +end procedure + +insert_after("ONE") +insert_after("TWO") +insert_after("THREE") + +?sll diff --git a/Task/Singly-linked-list-Element-insertion/X86-Assembly/singly-linked-list-element-insertion.x86 b/Task/Singly-linked-list-Element-insertion/X86-Assembly/singly-linked-list-element-insertion.x86 new file mode 100644 index 0000000000..198bcfe65d --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/X86-Assembly/singly-linked-list-element-insertion.x86 @@ -0,0 +1,29 @@ +; x86_64 Linux NASM +; Linked_List_Insert.asm + +%ifndef INSERT +%define INSERT + +%include "Linked_List_Definition.asm" ; see LL def task +%include "Heap_Alloc.asm" ; see memory allocation task + +section .text + +; rdi - link to insert after +; rsi - value that the new link will hold +Insert_After: + push rdi + push rsi + mov rdi, linkSize + call alloc + cmp rax, 0 + je Memory_Allocation_Failure_Exception + pop rdi + mov dword [rax + value], edi + pop rdi + mov rsi, qword [rdi + next] + mov qword [rax + next], rsi + mov qword [rdi + next], rax + ret + +%endif diff --git a/Task/Singly-linked-list-Element-insertion/Zkl/singly-linked-list-element-insertion-1.zkl b/Task/Singly-linked-list-Element-insertion/Zkl/singly-linked-list-element-insertion-1.zkl new file mode 100644 index 0000000000..54449654f6 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Zkl/singly-linked-list-element-insertion-1.zkl @@ -0,0 +1,2 @@ +L("a","b","c").insert(1,"foo") //-->L("a","foo","b","c") +a:=L("a","b","c"); a.insert(a.find("b"),"foo") //-->L("a","foo","b","c") diff --git a/Task/Singly-linked-list-Element-insertion/Zkl/singly-linked-list-element-insertion-2.zkl b/Task/Singly-linked-list-Element-insertion/Zkl/singly-linked-list-element-insertion-2.zkl new file mode 100644 index 0000000000..c0a1effa71 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Zkl/singly-linked-list-element-insertion-2.zkl @@ -0,0 +1,2 @@ +a:=ROList("a","b","c"); +n:=a.index("b"); a[0,n].append("foo").extend(a[n,*]) //-->ROList("a","foo","b","c") diff --git a/Task/Singly-linked-list-Traversal/jq/singly-linked-list-traversal.jq b/Task/Singly-linked-list-Traversal/Jq/singly-linked-list-traversal.jq similarity index 100% rename from Task/Singly-linked-list-Traversal/jq/singly-linked-list-traversal.jq rename to Task/Singly-linked-list-Traversal/Jq/singly-linked-list-traversal.jq diff --git a/Task/Singly-linked-list-Traversal/OoRexx/singly-linked-list-traversal.rexx b/Task/Singly-linked-list-Traversal/OoRexx/singly-linked-list-traversal.rexx new file mode 100644 index 0000000000..e5b2605152 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/OoRexx/singly-linked-list-traversal.rexx @@ -0,0 +1,12 @@ +say "Manual list traversal" +index = list~first -- demonstrate traversal +loop while index \== .nil + say index~value + index = index~next +end + +say +say "Do ... Over traversal" +do value over list + say value +end diff --git a/Task/Singly-linked-list-Traversal/Phix/singly-linked-list-traversal.phix b/Task/Singly-linked-list-Traversal/Phix/singly-linked-list-traversal.phix new file mode 100644 index 0000000000..153da9090b --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Phix/singly-linked-list-traversal.phix @@ -0,0 +1,23 @@ +enum NEXT,DATA +constant empty_sll = {{1}} +sequence sll = empty_sll + +procedure insert_after(object data, integer pos=length(sll)) + sll = append(sll,{sll[pos][NEXT],data}) + sll[pos][NEXT] = length(sll) +end procedure + +insert_after("ONE") +insert_after("TWO") +insert_after("THREE") + +?sll + +procedure show() +integer idx = sll[1][NEXT] + while idx!=1 do + ?sll[idx][DATA] + idx = sll[idx][NEXT] + end while +end procedure +show() diff --git a/Task/Singly-linked-list-Traversal/Protium/singly-linked-list-traversal-1.protium b/Task/Singly-linked-list-Traversal/Protium/singly-linked-list-traversal-1.protium deleted file mode 100644 index b003100f7f..0000000000 --- a/Task/Singly-linked-list-Traversal/Protium/singly-linked-list-traversal-1.protium +++ /dev/null @@ -1,9 +0,0 @@ -<@ LETCNSLSTLIT>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕 -<@ OMT>From First to Last -<@ ITEFORSZELSTLIT>public holidays| -<@ SAYLST>...<@ ACTMOVFWDLST>... - -<@ OMT>From Last to First (pointer is still at end of list) -<@ ITEFORSZELSTLIT>public holidays| -<@ SAYLST>...<@ ACTMOVBKWLST>... - diff --git a/Task/Singly-linked-list-Traversal/Protium/singly-linked-list-traversal-2.protium b/Task/Singly-linked-list-Traversal/Protium/singly-linked-list-traversal-2.protium deleted file mode 100644 index ca6946a25b..0000000000 --- a/Task/Singly-linked-list-Traversal/Protium/singly-linked-list-traversal-2.protium +++ /dev/null @@ -1,9 +0,0 @@ -<# 指定构造列表字串>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕 -<# 忽略>From First to Last -<# 迭代迭代次数结构大小列表字串>public holidays| -<# 显示列表>...<# 运行移位指针向前列表>... - -<# 忽略>From Last to First (pointer is still at end of list) -<# 迭代迭代次数结构大小列表字串>public holidays| -<# 显示列表>...<# 运行移位指针向后列表>... - diff --git a/Task/Singly-linked-list-Traversal/Zkl/singly-linked-list-traversal.zkl b/Task/Singly-linked-list-Traversal/Zkl/singly-linked-list-traversal.zkl new file mode 100644 index 0000000000..1c76de393c --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Zkl/singly-linked-list-traversal.zkl @@ -0,0 +1,12 @@ +foreach n in (List(1,2,3) {...} +List(1,2,3).pump(...) // traverse and munge elements, generalized apply/map +List(1,2,3).filter(...) +List(1,2,3).filter22(...) // partition list +List(1,2,3).reduce(...) +List(1,2,3).apply(...) +List(1,2,3).sum() +List(1,2,3).run() // treat each element as f, perform f() +List(1,2,3).enumerate() +List(1,2,3).reverse() +List(1,2,3).concat() +List(1,2,3).shuffle() diff --git a/Task/Sleep/BASIC/sleep-2.basic b/Task/Sleep/BASIC/sleep-2.basic index bb1a6bd5ac..d3331f5dbe 100644 --- a/Task/Sleep/BASIC/sleep-2.basic +++ b/Task/Sleep/BASIC/sleep-2.basic @@ -1,5 +1,6 @@ -10 REM s is the number of seconds -20 LET s = 5 -30 PRINT "Sleeping" -40 PAUSE s * 50 -50 PRINT "Awake" +10 PRINT "HOW LONG SHOULD I SLEEP FOR?" +20 PRINT "(IN TELEVISION FRAMES)" +30 INPUT SLEEPTIME +40 PRINT "SLEEPING... "; +50 PAUSE SLEEPTIME +60 PRINT "AWAKE." diff --git a/Task/Sleep/BASIC/sleep-3.basic b/Task/Sleep/BASIC/sleep-3.basic new file mode 100644 index 0000000000..bb1a6bd5ac --- /dev/null +++ b/Task/Sleep/BASIC/sleep-3.basic @@ -0,0 +1,5 @@ +10 REM s is the number of seconds +20 LET s = 5 +30 PRINT "Sleeping" +40 PAUSE s * 50 +50 PRINT "Awake" diff --git a/Task/Sleep/Kotlin/sleep.kotlin b/Task/Sleep/Kotlin/sleep.kotlin new file mode 100644 index 0000000000..eac4067a03 --- /dev/null +++ b/Task/Sleep/Kotlin/sleep.kotlin @@ -0,0 +1,9 @@ +// version 1.0.6 + +fun main(args: Array) { + print("Enter number of milliseconds to sleep: ") + val ms = readLine()!!.toLong() + println("Sleeping...") + Thread.sleep(ms) + println("Awake!") +} diff --git a/Task/Sleep/Nimrod/sleep.nimrod b/Task/Sleep/Nimrod/sleep.nimrod deleted file mode 100644 index 0d8ac6ff22..0000000000 --- a/Task/Sleep/Nimrod/sleep.nimrod +++ /dev/null @@ -1,7 +0,0 @@ -import os, strutils - -echo("Enter how long I should sleep (in milliseconds):") -var timed = parseInt(readLine(stdin).string) -echo("Sleeping...") -sleep(timed) -echo("Awake!") diff --git a/Task/Sleep/OoRexx/sleep.rexx b/Task/Sleep/OoRexx/sleep.rexx new file mode 100644 index 0000000000..f18e9b3fe3 --- /dev/null +++ b/Task/Sleep/OoRexx/sleep.rexx @@ -0,0 +1,3 @@ +Say time() +Call sysSleep 10 -- wait 10 seconds +Say time() diff --git a/Task/Sleep/Protium/sleep-1.protium b/Task/Sleep/Protium/sleep-1.protium deleted file mode 100644 index dfad53e3de..0000000000 --- a/Task/Sleep/Protium/sleep-1.protium +++ /dev/null @@ -1,4 +0,0 @@ -<@ SAYLIT>Number of seconds: <@ GETVAR>secs -<@ SAYLIT>Sleeping -<@ ACTPAUVAR>secs -<@ SAYLIT>Awake diff --git a/Task/Sleep/Protium/sleep-2.protium b/Task/Sleep/Protium/sleep-2.protium deleted file mode 100644 index 230d2650cd..0000000000 --- a/Task/Sleep/Protium/sleep-2.protium +++ /dev/null @@ -1,4 +0,0 @@ -<# MontrezLittéralement>Number of seconds: <# PrenezUneValeurVariable>secs -<# MontrezLittéralement>Sleeping -<# AgissezFaireUnePauseVariable>secs -<# MontrezLittéralement>Awake diff --git a/Task/Sleep/Protium/sleep-3.protium b/Task/Sleep/Protium/sleep-3.protium deleted file mode 100644 index e4c71629d0..0000000000 --- a/Task/Sleep/Protium/sleep-3.protium +++ /dev/null @@ -1,4 +0,0 @@ -<@ 显示_字串_>Number of seconds: <@ 获取_变量_>secs -<@ 显示_字串_>Sleeping -<@ 运行_暂停动变量_>secs -<@ 显示_字串_>Awake diff --git a/Task/Sleep/Rust/sleep.rust b/Task/Sleep/Rust/sleep.rust new file mode 100644 index 0000000000..e88d814f67 --- /dev/null +++ b/Task/Sleep/Rust/sleep.rust @@ -0,0 +1,19 @@ +use std::{io, time, thread}; + +fn main() { + println!("How long should we sleep in milliseconds?"); + + let mut sleep_string = String::new(); + + io::stdin().read_line(&mut sleep_string) + .expect("Failed to read line"); + + let sleep_timer: u64 = sleep_string.trim() + .parse() + .expect("Not an integer"); + let sleep_duration = time::Duration::from_millis(sleep_timer); + + println!("Sleeping..."); + thread::sleep(sleep_duration); + println!("Awake!"); +} diff --git a/Task/Sleep/Stata/sleep.stata b/Task/Sleep/Stata/sleep.stata new file mode 100644 index 0000000000..aa294a8025 --- /dev/null +++ b/Task/Sleep/Stata/sleep.stata @@ -0,0 +1,8 @@ +program sleep_awake + * pass duration in milliseconds + display "Sleeping..." + sleep `0' + display "Awake!" +end + +sleep_awake 2000 diff --git a/Task/Sleep/X86-Assembly/sleep.x86 b/Task/Sleep/X86-Assembly/sleep.x86 new file mode 100644 index 0000000000..81c76da46a --- /dev/null +++ b/Task/Sleep/X86-Assembly/sleep.x86 @@ -0,0 +1,14 @@ +; x86_64 linux nasm + +section .text + +Sleep: + mov rsi, 0 ; we wont use the second sleep arg, pass null to syscall + sub rsp, 16 + mov qword [rsp], rdi ; number of seconds the caller requested + mov qword [rsp + 8], rsi ; we won't use the nanoseconds + mov rdi, rsp ; pass the struct that's on the stack to + mov rax, 35 ; sys_nanosleep + syscall + add rsp, 16 ; clean up stack + ret diff --git a/Task/Sleep/Zkl/sleep.zkl b/Task/Sleep/Zkl/sleep.zkl new file mode 100644 index 0000000000..8deab8ce26 --- /dev/null +++ b/Task/Sleep/Zkl/sleep.zkl @@ -0,0 +1,4 @@ +seconds:=ask("Seconds to sleep: ").toFloat(); +println("Sleeping..."); +Atomic.sleep(seconds); # float, usually millisecond resolution +println("Awake!"); diff --git a/Task/Sockets/Zkl/sockets.zkl b/Task/Sockets/Zkl/sockets.zkl new file mode 100644 index 0000000000..ea2d221837 --- /dev/null +++ b/Task/Sockets/Zkl/sockets.zkl @@ -0,0 +1,3 @@ +var s=Network.TCPClientSocket.connectTo("localhost",256); +s.write("hello socket world"); //-->18 +s.close(); diff --git a/Task/Solve-a-Hidato-puzzle/00DESCRIPTION b/Task/Solve-a-Hidato-puzzle/00DESCRIPTION index 18230f16ac..b5a32d2dd6 100644 --- a/Task/Solve-a-Hidato-puzzle/00DESCRIPTION +++ b/Task/Solve-a-Hidato-puzzle/00DESCRIPTION @@ -19,10 +19,13 @@ has the following solution, with path marked on it: [[File:HEnd.png|center|Solution to sample Hidato problem]] -Related Tasks: -* [[Solve a Hopido puzzle]] + +;Related tasks: +* [[A* search algorithm]] +* [[N-queens problem]] * [[Solve a Holy Knight's tour]] +* [[Solve a Knight's tour]] +* [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] -* [[Solve the no connection puzzle]] -* [[Knight's tour]] +* [[Solve the no connection puzzle]];

    diff --git a/Task/Solve-a-Hidato-puzzle/Haskell/solve-a-hidato-puzzle-1.hs b/Task/Solve-a-Hidato-puzzle/Haskell/solve-a-hidato-puzzle-1.hs index be5857acbd..4f2b75be23 100644 --- a/Task/Solve-a-Hidato-puzzle/Haskell/solve-a-hidato-puzzle-1.hs +++ b/Task/Solve-a-Hidato-puzzle/Haskell/solve-a-hidato-puzzle-1.hs @@ -1,66 +1,111 @@ {-# LANGUAGE TupleSections #-} {-# LANGUAGE Rank2Types #-} + import qualified Data.IntMap as I import Data.IntMap (IntMap) import Data.List import Data.Maybe import Data.Time.Clock -data BoardProblem = Board { cells :: IntMap (IntMap Int) - , endVal :: Int - , onePos :: (Int,Int) - , givens :: [Int] } deriving (Show,Eq) +data BoardProblem = Board + { cells :: IntMap (IntMap Int) + , endVal :: Int + , onePos :: (Int, Int) + , givens :: [Int] + } deriving (Show, Eq) tupIns x y v m = I.insert x (I.insert y v (I.findWithDefault I.empty x m)) m + tupLookup x y m = I.lookup x m >>= I.lookup y -makeBoard = (\x -> x{givens = dropWhile (<=1) $ sort $ givens x}) - . foldl' f (Board I.empty 0 (0,0) []) . concatMap (zip [0..]) - . zipWith (\y w -> map (y,) $ words w) [0..] - where f bd (x,(y,v)) = if v=="." then bd else - Board (tupIns x y (read v) (cells bd)) - (if read v > endVal bd then read v else endVal bd) - (if v=="1" then (x,y) else onePos bd) - (read v:givens bd) +makeBoard = + (\x -> + x + { givens = dropWhile (<= 1) $ sort $ givens x + }) . + foldl' --' + f + (Board I.empty 0 (0, 0) []) . + concatMap (zip [0 ..]) . zipWith (\y w -> map (y, ) $ words w) [0 ..] + where + f bd (x, (y, v)) = + if v == "." + then bd + else Board + (tupIns x y (read v) (cells bd)) + (if read v > endVal bd + then read v + else endVal bd) + (if v == "1" + then (x, y) + else onePos bd) + (read v : givens bd) -hidato brd = listToMaybe $ h 2 (cells brd) (onePos brd) (givens brd) where - h nval pmap (x,y) gs | nval == endVal brd = [pmap] - | nval == head gs = if null nvalAdj then [] - else h (nval+1) pmap (fst $ head nvalAdj) (tail gs) - | not $ null nvalAdj = h (nval+1) pmap - (fst $ head nvalAdj) gs - | otherwise = hEmptyAdj - where around = [(x-1,y-1),(x,y-1),(x+1,y-1), (x-1,y),(x+1,y) - ,(x-1,y+1),(x,y+1),(x+1,y+1)] - lkdUp = map (\(x,y) -> ((x,y),tupLookup x y pmap)) around - nvalAdj = filter ((==Just nval) . snd) lkdUp - hEmptyAdj = concatMap (\((nx,ny),_) -> h (nval+1) - (tupIns nx ny nval pmap) (nx,ny) gs) - $ filter ((==Just 0) . snd) lkdUp +hidato brd = listToMaybe $ h 2 (cells brd) (onePos brd) (givens brd) + where + h nval pmap (x, y) gs + | nval == endVal brd = [pmap] + | nval == head gs = + if null nvalAdj + then [] + else h (nval + 1) pmap (fst $ head nvalAdj) (tail gs) + | not $ null nvalAdj = h (nval + 1) pmap (fst $ head nvalAdj) gs + | otherwise = hEmptyAdj + where + around = + [ (x - 1, y - 1) + , (x, y - 1) + , (x + 1, y - 1) + , (x - 1, y) + , (x + 1, y) + , (x - 1, y + 1) + , (x, y + 1) + , (x + 1, y + 1) + ] + lkdUp = map (\(x, y) -> ((x, y), tupLookup x y pmap)) around + nvalAdj = filter ((== Just nval) . snd) lkdUp + hEmptyAdj = + concatMap + (\((nx, ny), _) -> h (nval + 1) (tupIns nx ny nval pmap) (nx, ny) gs) $ + filter ((== Just 0) . snd) lkdUp printCellMap cellmap = putStrLn $ concat strings - where maxPos = xyBy I.findMax maximum - minPos = xyBy I.findMin minimum - xyBy :: (forall a. IntMap a -> (Int,a)) -> ([Int] -> Int) -> (Int, Int) - xyBy a b = (fst (a cellmap) - , b $ map (fst . a . snd) $ I.toList cellmap) - strings = map f [(x,y) | y<-[snd minPos..snd maxPos] - , x<-[fst minPos..fst maxPos]] - f (x,y) = let z = if x == fst maxPos then "\n" else " " in - case tupLookup x y cellmap of - Nothing -> " " ++ z - Just n -> (if n<10 then ' ':show n else show n) ++ z + where + maxPos = xyBy I.findMax maximum + minPos = xyBy I.findMin minimum + xyBy :: (forall a. IntMap a -> (Int, a)) -> ([Int] -> Int) -> (Int, Int) + xyBy a b = (fst (a cellmap), b $ map (fst . a . snd) $ I.toList cellmap) + strings = + map + f + [ (x, y) + | y <- [snd minPos .. snd maxPos] + , x <- [fst minPos .. fst maxPos] ] + f (x, y) = + let z = + if x == fst maxPos + then "\n" + else " " + in case tupLookup x y cellmap of + Nothing -> " " ++ z + Just n -> + (if n < 10 + then ' ' : show n + else show n) ++ + z main = do - let sampleBoard = makeBoard sample - printCellMap $ cells sampleBoard - printCellMap $ fromJust $ hidato sampleBoard + let sampleBoard = makeBoard sample + printCellMap $ cells sampleBoard + printCellMap $ fromJust $ hidato sampleBoard -sample = [" 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"] +sample = + [ " 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" + ] diff --git a/Task/Solve-a-Hidato-puzzle/Nimrod/solve-a-hidato-puzzle.nimrod b/Task/Solve-a-Hidato-puzzle/Nimrod/solve-a-hidato-puzzle.nimrod deleted file mode 100644 index 1aa47076a9..0000000000 --- a/Task/Solve-a-Hidato-puzzle/Nimrod/solve-a-hidato-puzzle.nimrod +++ /dev/null @@ -1,80 +0,0 @@ -import strutils, algorithm - -var board: array[0..19, array[0..19, int]] -var given, start: seq[int] = @[] -var rows, cols: int = 0 - -proc setup(s: string) = - var lines = s.splitLines() - cols = lines[0].split().len() - rows = lines.len() - - for i in 0 .. rows + 1: - for j in 0 .. cols + 1: - board[i][j] = -1 - - for r, row in pairs(lines): - for c, cell in pairs(row.split()): - case cell - of "__" : - board[r + 1][c + 1] = 0 - continue - of "." : continue - else : - var val = parseInt(cell) - board[r + 1][c + 1] = val - given.add(val) - if (val == 1): - start.add(r + 1) - start.add(c + 1) - given.sort(cmp[int], Ascending) - -proc solve(r, c, n: int, next: int = 0): Bool = - if n > given[high(given)]: - return True - if board[r][c] < 0: - return False - if (board[r][c] > 0 and board[r][c] != n): - return False - if (board[r][c] == 0 and given[next] == n): - return False - - var back = board[r][c] - board[r][c] = n - for i in -1 .. 1: - for j in -1 .. 1: - if back == n: - if (solve(r + i, c + j, n + 1, next + 1)): return True - else: - if (solve(r + i, c + j, n + 1, next)): return True - board[r][c] = back - result = False - - -proc printBoard() = - for r in 0 .. rows + 1: - for cellid,c in pairs(board[r]): - if cellid > cols + 1: break - if c == -1: - write(stdout, " . ") - elif c == 0: - write(stdout, "__ ") - else: - write(stdout, "$# " % align($c,2)) - writeln(stdout, "") - -var hi: string = """__ 33 35 __ __ . . . -__ __ 24 22 __ . . . -__ __ __ 21 __ __ . . -__ 26 __ 13 40 11 . . -27 __ __ __ 9 __ 1 . -. . __ __ 18 __ __ . -. . . . __ 7 __ __ -. . . . . . 5 __""" - -setup(hi) -printBoard() -echo("") -echo("Found:") -discard solve(start[0], start[1], 1) -printBoard() diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-5.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-5.rb deleted file mode 100644 index 8f45988efa..0000000000 --- a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-5.rb +++ /dev/null @@ -1,11 +0,0 @@ -rows = 3 -cols = 50 -$end = 74 -$zbl = Array.new($end+1,false) -$board = [[Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[]], - [Cell[] ,Cell[1,1,1] ,Cell[1,2,0] ,Cell[1,3,0] ,Cell[] ,Cell[] ,Cell[1,6,0] ,Cell[1,7,0] ,Cell[] ,Cell[] ,Cell[1,10,0] ,Cell[1,11,0] ,Cell[] ,Cell[] ,Cell[1,14,0] ,Cell[1,15,0] ,Cell[] ,Cell[] ,Cell[1,18,0] ,Cell[1,19,0] ,Cell[] ,Cell[] ,Cell[1,22,0] ,Cell[1,23,0] ,Cell[] ,Cell[] ,Cell[1,26,0] ,Cell[1,27,0] ,Cell[] ,Cell[] ,Cell[1,30,0] ,Cell[1,31,0] ,Cell[] ,Cell[] ,Cell[1,34,0] ,Cell[1,35,0] ,Cell[] ,Cell[] ,Cell[1,38,0] ,Cell[1,39,0] ,Cell[] ,Cell[] ,Cell[1,42,0] ,Cell[1,43,0] ,Cell[] ,Cell[] ,Cell[1,46,0] ,Cell[1,47,0] ,Cell[] ,Cell[] ,Cell[1,50,74] ,Cell[]], - [Cell[] ,Cell[] ,Cell[] ,Cell[2,3,0] ,Cell[] ,Cell[2,5,0] ,Cell[] ,Cell[2,7,0] ,Cell[] ,Cell[2,9,0] ,Cell[] ,Cell[2,11,0] ,Cell[] ,Cell[2,13,0] ,Cell[] ,Cell[2,15,0] ,Cell[] ,Cell[2,17,0] ,Cell[] ,Cell[2,19,0] ,Cell[] ,Cell[2,21,0] ,Cell[] ,Cell[2,23,0] ,Cell[] ,Cell[2,25,0] ,Cell[] ,Cell[2,27,0] ,Cell[] ,Cell[2,29,0] ,Cell[] ,Cell[2,31,0] ,Cell[] ,Cell[2,33,0] ,Cell[] ,Cell[2,35,0] ,Cell[] ,Cell[2,37,0] ,Cell[] ,Cell[2,39,0] ,Cell[] ,Cell[2,41,0] ,Cell[] ,Cell[2,43,0] ,Cell[] ,Cell[2,45,0] ,Cell[] ,Cell[2,47,0] ,Cell[] ,Cell[2,49,0] ,Cell[] ,Cell[]], - [Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[3,4,0] ,Cell[3,5,0] ,Cell[] ,Cell[] ,Cell[3,8,0] ,Cell[3,9,0] ,Cell[] ,Cell[] ,Cell[3,12,0] ,Cell[3,13,0] ,Cell[] ,Cell[] ,Cell[3,16,0] ,Cell[3,17,0] ,Cell[] ,Cell[] ,Cell[3,20,0] ,Cell[3,21,0] ,Cell[] ,Cell[] ,Cell[3,24,0] ,Cell[3,25,0] ,Cell[] ,Cell[] ,Cell[3,28,0] ,Cell[3,29,0] ,Cell[] ,Cell[] ,Cell[3,32,0] ,Cell[3,33,0] ,Cell[] ,Cell[] ,Cell[3,36,0] ,Cell[3,37,0] ,Cell[] ,Cell[] ,Cell[3,40,0] ,Cell[3,41,0] ,Cell[] ,Cell[] ,Cell[3,44,0] ,Cell[3,45,0] ,Cell[] ,Cell[] ,Cell[3,48,0] ,Cell[3,49,0] ,Cell[] ,Cell[]], - [Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[]]] - -test(rows, cols, 1, 1) diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-6.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-6.rb deleted file mode 100644 index 0664c6ec52..0000000000 --- a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-6.rb +++ /dev/null @@ -1,40 +0,0 @@ -# Solve a Hidato Puzzle with Warnsdorff like logic applied -# -# Nigel_Galloway -# May 6th., 2012. -class Cell - def self.[](*args) self.new(*args) end - def initialize(row=0, col=0, value=nil) - @adj = [[row-1,col-1],[row,col-1],[row+1,col-1],[row-1,col],[row+1,col],[row-1,col+1],[row,col+1],[row+1,col+1]] - @t = false - $zbl[value] = true unless value.nil? - @value = value - end - def try(value=1) - return false if @value.nil? - return true if value > $end - return false if @t - return false if @value > 0 and @value != value - return false if @value == 0 and $zbl[value] - @t = true - h = Hash.new - @adj.each_with_index do |(x,y), n| - cell = $board[x][y] - h[cell.wdof*10+n] = cell if cell.value - end - h.sort.each do |key, cell| - if (cell.try(value+1)) - @value = value - return true - end - end - @t = false - end - def wdon - (@value.nil? or @value > 0 or @t) ? 0 : 1 - end - def wdof - @adj.inject(0){|res, (x,y)| res += $board[x][y].wdon} - end - attr_reader :value -end diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-7.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-7.rb deleted file mode 100644 index 54ebf377a8..0000000000 --- a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-7.rb +++ /dev/null @@ -1,44 +0,0 @@ -class Cell - def initialize(row=0, col=0, value=nil) - @adj = [[row-1,col-2],[row-2,col-1],[row-2,col+1],[row-1,col+2],[row+1,col+2],[row+2,col+1],[row+2,col-1],[row+1,col-2]] - @t = false - $zbl[value] = false unless value == nil - @value = value - end - def try(value) - return false if @value == nil - return true if value > E - return false if @t - return false if @value > 0 and @value != value - return false if @value == 0 and not $zbl[value] - @t = true - h = Hash.new - n = 0 - @adj.each{|x| - h[Board[x[0]][x[1]].wdof*10+n] = Board[x[0]][x[1]] - n += 1 - } - h.sort.each{|key,cell| - if (cell.try(value+1)) then - @value = value - return true - end - } - @t = false - return false - end - def wdon - return 0 if @value == nil - return 0 if @value > 0 - return 0 if @t - return 1 - end - def wdof - res = 0 - @adj.each{|x| res += Board[x[0]][x[1]].wdon} - return res - end - def value - return @value - end -end diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-8.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-8.rb deleted file mode 100644 index 15ec189f25..0000000000 --- a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-8.rb +++ /dev/null @@ -1,21 +0,0 @@ -Rows = 9 -Cols = 9 -E = 64 -$zbl = Array.new(E+1,true) -Board = [[Cell.new(),Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(),Cell.new()], - [Cell.new(),Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(),Cell.new()], - [Cell.new(),Cell.new(),Cell.new(2,2,0),Cell.new(2,3,0),Cell.new(2,4,0),Cell.new(2,5,0),Cell.new(2,6,0),Cell.new(2,7,0),Cell.new(2,8,0),Cell.new(2,9,0) ,Cell.new(),Cell.new()], - [Cell.new(),Cell.new(),Cell.new(3,2,0),Cell.new(3,3,0),Cell.new(3,4,0),Cell.new(3,5,0),Cell.new(3,6,0),Cell.new(3,7,0),Cell.new(3,8,0),Cell.new(3,9,0) ,Cell.new(),Cell.new()], - [Cell.new(),Cell.new(),Cell.new(4,2,0),Cell.new(4,3,0),Cell.new(4,4,0),Cell.new(4,5,0),Cell.new(4,6,0),Cell.new(4,7,0),Cell.new(4,8,0),Cell.new(4,9,0) ,Cell.new(),Cell.new()], - [Cell.new(),Cell.new(),Cell.new(5,2,0),Cell.new(5,3,1),Cell.new(5,4,0),Cell.new(5,5,0),Cell.new(5,6,0),Cell.new(5,7,0),Cell.new(5,8,0),Cell.new(5,9,0) ,Cell.new(),Cell.new()], - [Cell.new(),Cell.new(),Cell.new(6,2,0),Cell.new(6,3,0),Cell.new(6,4,0),Cell.new(6,5,0),Cell.new(6,6,0),Cell.new(6,7,0),Cell.new(6,8,0),Cell.new(6,9,0) ,Cell.new(),Cell.new()], - [Cell.new(),Cell.new(),Cell.new(7,2,0),Cell.new(7,3,0),Cell.new(7,4,0),Cell.new(7,5,0),Cell.new(7,6,0),Cell.new(7,7,0),Cell.new(7,8,0),Cell.new(7,9,0) ,Cell.new(),Cell.new()], - [Cell.new(),Cell.new(),Cell.new(8,2,0),Cell.new(8,3,0),Cell.new(8,4,0),Cell.new(8,5,0),Cell.new(8,6,0),Cell.new(8,7,0),Cell.new(8,8,0),Cell.new(8,9,0) ,Cell.new(),Cell.new()], - [Cell.new(),Cell.new(),Cell.new(9,2,0),Cell.new(9,3,0),Cell.new(9,4,0),Cell.new(9,5,0),Cell.new(9,6,0),Cell.new(9,7,0),Cell.new(9,8,0),Cell.new(9,9,0),Cell.new(),Cell.new()], - [Cell.new(),Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(),Cell.new()], - [Cell.new(),Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(),Cell.new()]] -require 'benchmark' -puts Benchmark.measure {Board[5][3].try(1)} -(1..Rows).each{|r| - (1..Cols).each{|c| printf("%3s",Board[r][c].value)} - puts ""} diff --git a/Task/Solve-a-Hidato-puzzle/Zkl/solve-a-hidato-puzzle-1.zkl b/Task/Solve-a-Hidato-puzzle/Zkl/solve-a-hidato-puzzle-1.zkl new file mode 100644 index 0000000000..38c36d16b3 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Zkl/solve-a-hidato-puzzle-1.zkl @@ -0,0 +1,17 @@ +hi:= // 0==empty cell, X==not a cell +#<<< + "0 33 35 0 0 X X X + 0 0 24 22 0 X X X + 0 0 0 21 0 0 X X + 0 26 0 13 40 11 X X + 27 0 0 0 9 0 1 X + X X 0 0 18 0 0 X + X X X X 0 7 0 0 + X X X X X X 5 0"; +#<<< + +board,given,start:=setup(hi); +print_board(board); +solve(board,given, start.xplode(), 1); +println(); +print_board(board); diff --git a/Task/Solve-a-Hidato-puzzle/Zkl/solve-a-hidato-puzzle-2.zkl b/Task/Solve-a-Hidato-puzzle/Zkl/solve-a-hidato-puzzle-2.zkl new file mode 100644 index 0000000000..5280aedc7f --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Zkl/solve-a-hidato-puzzle-2.zkl @@ -0,0 +1,37 @@ +fcn print_board(board){ + d:=D(-1," ", 0,"__"); + foreach r in (board[1,-1]){ + r[1,-1].pump(String,'wrap(c){ "%2s ".fmt(d.find(c,c)) }).println(); + } +} +fcn setup(s){ + lines:=s.split("\n"); + ncols,nrows:=lines[0].split().len(),lines.len(); + board:=(nrows+2).pump(List(), (ncols+2).pump(List(),-1).copy); + given,start:=List(),Void; + foreach r,row in (lines.enumerate()){ + foreach c,cell in (row.split().enumerate()){ + if(cell=="X") continue; // X == not in play, leave at -1 + val:=cell.toInt(); + board[r+1][c+1]=val; + given.append(val); + if(val==1) start=T(r+1,c+1); + } + } + return(board,given.filter().sort(),start); +} +fcn solve(board,given, r,c,n, next=0){ + if(n>given[-1]) return(True); + if(board[r][c] and board[r][c]!=n) return(False); + if(board[r][c]==0 and given[next]==n) return(False); + + back:=0; + if(board[r][c]==n){ next+=1; back=n; } + + board[r][c]=n; + foreach i,j in ([-1..1],[-1..1]){ + if(solve(board,given, r+i,c+j,n+1, next)) return(True); + } + board[r][c]=back; + False +} diff --git a/Task/Solve-a-Holy-Knights-tour/00DESCRIPTION b/Task/Solve-a-Holy-Knights-tour/00DESCRIPTION index a290d38af4..13f03aedbb 100644 --- a/Task/Solve-a-Holy-Knights-tour/00DESCRIPTION +++ b/Task/Solve-a-Holy-Knights-tour/00DESCRIPTION @@ -22,8 +22,13 @@ Note that the zeros represent the available squares, not the pennies. Extra credit is available for other interesting examples. + +;Related tasks: +* [[A* search algorithm]] +* [[Knight's tour]] +* [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]] -* [[Knight's tour]] +

    diff --git a/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-1.hs b/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-1.hs index 0b3fd56797..80e5acfd7c 100644 --- a/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-1.hs +++ b/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-1.hs @@ -1,105 +1,115 @@ -import qualified Data.Array as Arr -import qualified Data.Foldable as Fold -import qualified Data.List as List +import Data.Array + (Array, (//), (!), assocs, elems, bounds, listArray) +import Data.Foldable (forM_) +import Data.List (intercalate, transpose) import Data.Maybe type Position = (Int, Int) -type KnightBoard = Arr.Array Position (Maybe Int) + +type KnightBoard = Array Position (Maybe Int) toSlot :: Char -> Maybe Int toSlot '0' = Just 0 toSlot '1' = Just 1 -toSlot _ = Nothing +toSlot _ = Nothing toString :: Maybe Int -> String -toString Nothing = replicate 3 ' ' +toString Nothing = replicate 3 ' ' toString (Just n) = replicate (3 - length nn) ' ' ++ nn where nn = show n chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] -chunksOf n xs = take n xs : (chunksOf n $ drop n xs) +chunksOf n xs = + let (chunk, rest) = splitAt n xs + in chunk : chunksOf n rest showBoard :: KnightBoard -> String showBoard board = - List.intercalate "\n" . map concat . List.transpose - . chunksOf (height + 1) . map toString $ Arr.elems board + intercalate "\n" . map concat . transpose . chunksOf (height + 1) . map toString $ + elems board where - (_, (_, height)) = Arr.bounds board + (_, (_, height)) = bounds board toBoard :: [String] -> KnightBoard toBoard strs = board where height = length strs - width = minimum $ map length strs - board = Arr.listArray ((0, 0), (width - 1, height - 1)) - . map toSlot . concat . List.transpose $ map (take width) strs + width = minimum (length <$> strs) + board = + listArray ((0, 0), (width - 1, height - 1)) . map toSlot . concat . transpose $ + take width <$> strs - -add :: Num a => (a, a) -> (a, a) -> (a, a) +add + :: Num a + => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y) -within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool -within ((a, b), (c, d)) (x, y) = - a <= x && x <= c && - b <= y && y <= d +within + :: Ord a + => ((a, a), (a, a)) -> (a, a) -> Bool +within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d -- Enumerate valid moves given a board and a knight's position. validMoves :: KnightBoard -> Position -> [Position] validMoves board position = filter isValid plausible where - bound = Arr.bounds board - plausible = map (add position) [(1, 2), (2, 1), (2, -1), (-1, 2), - (-2, 1), (1, -2), (-1, -2), (-2, -1)] - isValid pos = within bound pos && maybe False (== 0) (board Arr.! pos) + bound = bounds board + plausible = + add position <$> + [(1, 2), (2, 1), (2, -1), (-1, 2), (-2, 1), (1, -2), (-1, -2), (-2, -1)] + isValid pos = within bound pos && maybe False (== 0) (board ! pos) isSolved :: KnightBoard -> Bool -isSolved = Fold.all (maybe True (/= 0)) +isSolved = all (maybe True (0 /=)) -- Solve the knight's tour with a simple Depth First Search. solveKnightTour :: KnightBoard -> Maybe KnightBoard solveKnightTour board = solve board 1 initPosition where - initPosition = fst $ head $ filter ((== (Just 1)) . snd) $ Arr.assocs board + initPosition = fst $ head $ filter ((== Just 1) . snd) $ assocs board solve boardA depth position = - let boardB = boardA Arr.// [(position, Just depth)] + let boardB = boardA // [(position, Just depth)] in if isSolved boardB - then Just boardB - else listToMaybe $ mapMaybe (solve boardB $ depth + 1) - $ validMoves boardB position + then Just boardB + else listToMaybe $ + mapMaybe (solve boardB $ depth + 1) $ validMoves boardB position tourExA :: [String] tourExA = - [" 000 " - ," 0 00 " - ," 0000000" - ,"000 0 0" - ,"0 0 000" - ,"1000000 " - ," 00 0 " - ," 000 "] + [ " 000 " + , " 0 00 " + , " 0000000" + , "000 0 0" + , "0 0 000" + , "1000000 " + , " 00 0 " + , " 000 " + ] tourExB :: [String] tourExB = - ["-----1-0-----" - ,"-----0-0-----" - ,"----00000----" - ,"-----000-----" - ,"--0--0-0--0--" - ,"00000---00000" - ,"--00-----00--" - ,"00000---00000" - ,"--0--0-0--0--" - ,"-----000-----" - ,"----00000----" - ,"-----0-0-----" - ,"-----0-0-----"] + [ "-----1-0-----" + , "-----0-0-----" + , "----00000----" + , "-----000-----" + , "--0--0-0--0--" + , "00000---00000" + , "--00-----00--" + , "00000---00000" + , "--0--0-0--0--" + , "-----000-----" + , "----00000----" + , "-----0-0-----" + , "-----0-0-----" + ] main :: IO () main = - flip mapM_ [tourExA, tourExB] - (\board -> - case solveKnightTour $ toBoard board of - Nothing -> putStrLn "No solution.\n" - Just solution -> putStrLn $ showBoard solution ++ "\n") + forM_ + [tourExA, tourExB] + (\board -> + case solveKnightTour $ toBoard board of + Nothing -> putStrLn "No solution.\n" + Just solution -> putStrLn $ showBoard solution ++ "\n") diff --git a/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-2.hs b/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-2.hs index 82902128f8..d3f5980509 100644 --- a/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-2.hs +++ b/Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-2.hs @@ -1,31 +1,41 @@ -import Control.Monad.ST -import qualified Data.Array.Base as AB -import qualified Data.Array.ST as AST +{-# LANGUAGE FlexibleContexts #-} + +import Control.Monad (forM_) + import qualified Data.Array.Unboxed as AU -import qualified Data.List as List + +import Control.Monad.ST (ST, runST) + +import Data.Array.Base (unsafeFreeze) + +import Data.List (intercalate, transpose) + +import Data.Array.ST + (STUArray, readArray, writeArray, newListArray) type Position = (Int, Int) + type KnightBoard = AU.UArray Position Int toSlot :: Char -> Int toSlot '0' = 0 toSlot '1' = 1 -toSlot _ = -1 +toSlot _ = -1 toString :: Int -> String toString (-1) = replicate 3 ' ' -toString n = replicate (3 - length nn) ' ' ++ nn +toString n = replicate (3 - length nn) ' ' ++ nn where nn = show n chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] -chunksOf n xs = take n xs : (chunksOf n $ drop n xs) +chunksOf n xs = uncurry ((. chunksOf n) . (:)) (splitAt n xs) showBoard :: KnightBoard -> String showBoard board = - List.intercalate "\n" . map concat . List.transpose - . chunksOf (height + 1) . map toString $ AU.elems board + intercalate "\n" . map concat . transpose . chunksOf (height + 1) . map toString $ + AU.elems board where (_, (_, height)) = AU.bounds board @@ -33,96 +43,104 @@ toBoard :: [String] -> KnightBoard toBoard strs = board where height = length strs - width = minimum $ map length strs - board = AU.listArray ((0, 0), (width - 1, height - 1)) - . map toSlot . concat . List.transpose $ map (take width) strs + width = minimum (length <$> strs) + board = + AU.listArray ((0, 0), (width - 1, height - 1)) . map toSlot . concat . transpose $ + take width <$> strs -add :: Num a => (a, a) -> (a, a) -> (a, a) +add + :: Num a + => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y) -within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool -within ((a, b), (c, d)) (x, y) = - a <= x && x <= c && - b <= y && y <= d +within + :: Ord a + => ((a, a), (a, a)) -> (a, a) -> Bool +within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d -- Solve the knight's tour with a simple Depth First Search. solveKnightTour :: KnightBoard -> Maybe KnightBoard solveKnightTour board = - runST $ do - let - assocs = AU.assocs board - bounds = AU.bounds board - - array <- (AST.newListArray bounds (AU.elems board)) - :: ST s (AST.STUArray s Position Int) - - let - initPosition = fst $ head $ filter ((== 1) . snd) assocs - maxDepth = fromIntegral $ 1 + (length $ filter ((== 0) . snd) assocs) - offsets = - [(1, 2), (2, 1), (2, -1), (-1, 2), - (-2, 1), (1, -2), (-1, -2), (-2, -1)] - - solve depth position = do - if within bounds position - then do - oldValue <- AST.readArray array position - if oldValue == 0 - then do - AST.writeArray array position depth - if depth == maxDepth - then return True - else do - -- This mapM-any combo can be reduced to a string of ||'s - -- with the goal of removing the allocation overhead due to consing - -- which the compiler may not be able to optimize out. - results <- mapM ((solve $ depth + 1) . add position) offsets - if any (== True) results - then return True - else do - AST.writeArray array position oldValue - return False - else return False - else return False - - AST.writeArray array initPosition 0 - result <- solve 1 initPosition - farray <- AB.unsafeFreeze array - return $ if result - then Just farray - else Nothing + runST $ + do let assocs = AU.assocs board + bounds = AU.bounds board + array <- + newListArray bounds (AU.elems board) :: ST s (STUArray s Position Int) + let initPosition = fst $ head $ filter ((== 1) . snd) assocs + maxDepth = fromIntegral $ 1 + length (filter ((== 0) . snd) assocs) + offsets = + [ (1, 2) + , (2, 1) + , (2, -1) + , (-1, 2) + , (-2, 1) + , (1, -2) + , (-1, -2) + , (-2, -1) + ] + solve depth position = + if within bounds position + then do + oldValue <- readArray array position + if oldValue == 0 + then do + writeArray array position depth + if depth == maxDepth + then return True + -- This mapM-any combo can be reduced to a string of ||'s + -- with the goal of removing the allocation overhead due to consing + -- which the compiler may not be able to optimize out. + else do + results <- mapM (solve (depth + 1) . add position) offsets + if or results + then return True + else do + writeArray array position oldValue + return False + else return False + else return False + writeArray array initPosition 0 + result <- solve 1 initPosition + farray <- unsafeFreeze array + return $ + if result + then Just farray + else Nothing tourExA :: [String] tourExA = - [" 000 " - ," 0 00 " - ," 0000000" - ,"000 0 0" - ,"0 0 000" - ,"1000000 " - ," 00 0 " - ," 000 "] + [ " 000 " + , " 0 00 " + , " 0000000" + , "000 0 0" + , "0 0 000" + , "1000000 " + , " 00 0 " + , " 000 " + ] tourExB :: [String] tourExB = - ["-----1-0-----" - ,"-----0-0-----" - ,"----00000----" - ,"-----000-----" - ,"--0--0-0--0--" - ,"00000---00000" - ,"--00-----00--" - ,"00000---00000" - ,"--0--0-0--0--" - ,"-----000-----" - ,"----00000----" - ,"-----0-0-----" - ,"-----0-0-----"] + [ "-----1-0-----" + , "-----0-0-----" + , "----00000----" + , "-----000-----" + , "--0--0-0--0--" + , "00000---00000" + , "--00-----00--" + , "00000---00000" + , "--0--0-0--0--" + , "-----000-----" + , "----00000----" + , "-----0-0-----" + , "-----0-0-----" + ] main :: IO () main = - flip mapM_ [tourExA, tourExB] - (\board -> - case solveKnightTour $ toBoard board of - Nothing -> putStrLn "No solution.\n" - Just solution -> putStrLn $ showBoard solution ++ "\n") + forM_ + [tourExA, tourExB] + (\board -> + case solveKnightTour $ toBoard board of + Nothing -> putStrLn "No solution.\n" + Just solution -> putStrLn $ showBoard solution ++ "\n") diff --git a/Task/Solve-a-Holy-Knights-tour/JavaScript/solve-a-holy-knights-tour.js b/Task/Solve-a-Holy-Knights-tour/JavaScript/solve-a-holy-knights-tour.js new file mode 100644 index 0000000000..2e703a06cc --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/JavaScript/solve-a-holy-knights-tour.js @@ -0,0 +1,411 @@ +(() => { + 'use strict'; + + // problems :: [[String]] + const problems = [ + [ + " 000 " // + , " 0 00 " // + , " 0000000" // + , "000 0 0" // + , "0 0 000" // + , "1000000 " // + , " 00 0 " // + , " 000 " // + ], + [ + "-----1-0-----" // + , "-----0-0-----" // + , "----00000----" // + , "-----000-----" // + , "--0--0-0--0--" // + , "00000---00000" // + , "--00-----00--" // + , "00000---00000" // + , "--0--0-0--0--" // + , "-----000-----" // + , "----00000----" // + , "-----0-0-----" // + , "-----0-0-----" // + ] + ]; + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // comparing :: (a -> b) -> (a -> a -> Ordering) + const comparing = f => + (x, y) => { + const + a = f(x), + b = f(y); + return a < b ? -1 : a > b ? 1 : 0 + }; + + // concat :: [[a]] -> [a] | [String] -> String + const concat = xs => + xs.length > 0 ? (() => { + const unit = typeof xs[0] === 'string' ? '' : []; + return unit.concat.apply(unit, xs); + })() : []; + + // charColRow :: Char -> [String] -> Maybe (Int, Int) + const charColRow = (c, rows) => + foldr((a, xs, iRow) => + a.nothing ? (() => { + const mbiCol = elemIndex(c, xs); + return mbiCol.nothing ? mbiCol : { + just: [mbiCol.just, iRow], + nothing: false + }; + })() : a, { + nothing: true + }, rows); + + // 2 or more arguments + // curry :: Function -> Function + const curry = (f, ...args) => { + const go = xs => xs.length >= f.length ? (f.apply(null, xs)) : + function () { + return go(xs.concat(Array.from(arguments))); + }; + return go([].slice.call(args, 1)); + }; + + // elem :: Eq a => a -> [a] -> Bool + const elem = (x, xs) => xs.indexOf(x) !== -1; + + // elemIndex :: Eq a => a -> [a] -> Maybe Int + const elemIndex = (x, xs) => { + const i = xs.indexOf(x); + return { + nothing: i === -1, + just: i + }; + }; + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // filter :: (a -> Bool) -> [a] -> [a] + const filter = (f, xs) => xs.filter(f); + + // findIndex :: (a -> Bool) -> [a] -> Maybe Int + const findIndex = (f, xs) => { + for (var i = 0, lng = xs.length; i < lng; i++) { + if (f(xs[i])) return { + nothing: false, + just: i + }; + } + return { + nothing: true + }; + }; + + // foldl :: (b -> a -> b) -> b -> [a] -> b + const foldl = (f, a, xs) => xs.reduce(f, a); + + // foldr (a -> b -> b) -> b -> [a] -> b + const foldr = (f, a, xs) => xs.reduceRight(f, a); + + // groupBy :: (a -> a -> Bool) -> [a] -> [[a]] + const groupBy = (f, xs) => { + const dct = xs.slice(1) + .reduce((a, x) => { + const + h = a.active.length > 0 ? a.active[0] : undefined, + blnGroup = h !== undefined && f(h, x); + return { + active: blnGroup ? a.active.concat([x]) : [x], + sofar: blnGroup ? a.sofar : a.sofar.concat([a.active]) + }; + }, { + active: xs.length > 0 ? [xs[0]] : [], + sofar: [] + }); + return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []); + }; + + // intercalate :: String -> [a] -> String + const intercalate = (s, xs) => xs.join(s); + + // intersectBy::(a - > a - > Bool) - > [a] - > [a] - > [a] + const intersectBy = (eq, xs, ys) => + (xs.length > 0 && ys.length > 0) ? + xs.filter(x => ys.some(curry(eq)(x))) : []; + + // justifyRight :: Int -> Char -> Text -> Text + const justifyRight = (n, cFiller, strText) => + n > strText.length ? ( + (cFiller.repeat(n) + strText) + .slice(-n) + ) : strText; + + // length :: [a] -> Int + const length = xs => xs.length; + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // mappendComparing :: [(a -> b)] -> (a -> a -> Ordering) + const mappendComparing = fs => (x, y) => + fs.reduce((ord, f) => { + if (ord !== 0) return ord; + const + a = f(x), + b = f(y); + return a < b ? -1 : a > b ? 1 : 0 + }, 0); + + // maximumBy :: (a -> a -> Ordering) -> [a] -> a + const maximumBy = (f, xs) => + xs.reduce((a, x) => a === undefined ? x : ( + f(x, a) > 0 ? x : a + ), undefined); + + // min :: Ord a => a -> a -> a + const min = (a, b) => b < a ? b : a; + + // replicate :: Int -> a -> [a] + const replicate = (n, a) => { + let v = [a], + o = []; + if (n < 1) return o; + while (n > 1) { + if (n & 1) o = o.concat(v); + n >>= 1; + v = v.concat(v); + } + return o.concat(v); + }; + + // sortBy :: (a -> a -> Ordering) -> [a] -> [a] + const sortBy = (f, xs) => xs.slice() + .sort(f); + + // splitOn :: String -> String -> [String] + const splitOn = (s, xs) => xs.split(s); + + // take :: Int -> [a] -> [a] + const take = (n, xs) => xs.slice(0, n); + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + // until :: (a -> Bool) -> (a -> a) -> a -> a + const until = (p, f, x) => { + let v = x; + while (!p(v)) v = f(v); + return v; + }; + + // zip :: [a] -> [b] -> [(a,b)] + const zip = (xs, ys) => + xs.slice(0, Math.min(xs.length, ys.length)) + .map((x, i) => [x, ys[i]]); + + // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] + const zipWith = (f, xs, ys) => + Array.from({ + length: min(xs.length, ys.length) + }, (_, i) => f(xs[i], ys[i])); + + // HOLY KNIGHT's TOUR FUNCTIONS ------------------------------------------- + + // kmoves :: (Int, Int) -> [(Int, Int)] + const kmoves = ([x, y]) => map( + ([a, b]) => [a + x, b + y], [ + [1, 2], + [1, -2], + [-1, 2], + [-1, -2], + [2, 1], + [2, -1], + [-2, 1], + [-2, -1] + ]); + + // rowPosns :: Int -> String -> [(Int, Int)] + const rowPosns = (iRow, s) => { + return foldl((a, x, i) => (elem(x, ['0', '1']) ? ( + a.concat([ + [i, iRow] + ]) + ) : a), [], splitOn('', s)); + }; + + // hash :: (Int, Int) -> String + const hash = ([col, row]) => col.toString() + '.' + row.toString(); + + // Start node, and degree-sorted cache of moves from each node + // All node references are hash strings (for this cache) + + // problemModel :: [[String]] -> {cache: {nodeKey: [nodeKey], start:String}} + const problemModel = boardLines => { + const + steps = foldl((a, xs, i) => + a.concat(rowPosns(i, xs)), [], boardLines), + courseMoves = (xs, [x, y]) => intersectBy( + ([a, b], [c, d]) => a === c && b === d, kmoves([x, y]), xs + ), + maybeStart = charColRow('1', boardLines); + return { + start: maybeStart.nothing ? '' : hash(maybeStart.just), + boardWidth: boardLines.length > 0 ? boardLines[0].length : 0, + stepCount: steps.length, + cache: (() => { + const moveCache = foldl((a, xy) => ( + a[hash(xy)] = map(hash, courseMoves(steps, xy)), + a + ), {}, steps), + lstMoves = Object.keys(moveCache), + dctDegree = foldl((a, k) => + (a[k] = moveCache[k].length, + a), {}, lstMoves); + + return foldl((a, k) => ( + a[k] = sortBy(comparing(x => dctDegree[x]), moveCache[k]), + a + ), {}, lstMoves); + })() + }; + }; + + // firstSolution :: {nodeKey: [nodeKey]} -> Int -> + // nodeKey -> nodeKey -> [nodeKey] -> + // -> {path::[nodeKey], pathLen::Int, found::Bool} + const firstSolution = (dctMoves, intTarget, strStart, strNodeKey, path) => { + const + intPath = path.length, + moves = dctMoves[strNodeKey]; + + if ((intTarget - intPath) < 2 && elem(strStart, moves)) { + return { + nothing: false, + just: [strStart, strNodeKey].concat(path), + pathLen: intTarget + }; + } + + const + nexts = filter(k => !elem(k, path), moves), + intNexts = nexts.length, + lstFullPath = [strNodeKey].concat(path); + + // Until we find a full path back to start + return until( + x => (x.nothing === false || x.i >= intNexts), + x => { + const + idx = x.i, + dctSoln = firstSolution( + dctMoves, intTarget, strStart, nexts[idx], lstFullPath + ); + return { + i: idx + 1, + nothing: dctSoln.nothing, + just: dctSoln.just, + pathLen: dctSoln.pathLen + }; + }, { + nothing: true, + just: [], + i: 0 + } + ); + }; + + // maybeTour :: [String] -> { + // nothing::Bool, Just::[nodeHash], i::Int: pathLen::Int } + const maybeTour = trackLines => { + const + dctModel = problemModel(trackLines), + strStart = dctModel.start; + return strStart !== '' ? firstSolution( + dctModel.cache, dctModel.stepCount, strStart, strStart, [] + ) : { + nothing: true + }; + }; + + // showLine :: Int -> Int -> String -> Maybe (Int, Int) -> + // [(Int, Int, String)] -> String + const showLine = curry((intCell, strFiller, maybeStart, xs) => { + const + blnSoln = maybeStart.nothing, + [startCol, startRow] = blnSoln ? [0, 0] : maybeStart.just; + return foldl((a, [iCol, iRow, sVal], i, xs) => ({ + col: iCol + 1, + txt: a.txt + + concat(replicate((iCol - a.col) * intCell, strFiller)) + + justifyRight( + intCell, strFiller, + (blnSoln ? sVal : ( + iRow === startRow && + iCol === startCol ? '1' : '0') + ) + ) + }), { + col: 0, + txt: '' + }, + xs + ) + .txt + }); + + // solutionString :: [String] -> Int -> String + const solutionString = (boardLines, iProblem) => { + const + dtePre = Date.now(), + intCols = boardLines.length > 0 ? boardLines[0].length : 0, + soln = maybeTour(boardLines), + intMSeconds = Date.now() - dtePre; + + if (soln.nothing) return 'No solution found …'; + + const + kCol = 0, + kRow = 1, + kSeq = 2, + steps = soln.just, + lstTriples = zipWith((h, n) => { + const [col, row] = map( + x => parseInt(x, 10), splitOn('.', h) + ); + return [col, row, n.toString()]; + }, + steps, + enumFromTo(1, soln.pathLen)), + cellWidth = length(maximumBy( + comparing(x => length(x[kSeq])), lstTriples + )[kSeq]) + 1, + lstGroups = groupBy( + (a, b) => a[kRow] === b[kRow], + sortBy( + mappendComparing([x => x[kRow], x => x[kCol]]), + lstTriples + )), + startXY = take(2, lstTriples[0]), + strMap = 'PROBLEM ' + (parseInt(iProblem, 10) + 1) + '.\n\n' + + unlines(map(showLine(cellWidth, ' ', { + nothing: false, + just: startXY + }), lstGroups)), + strSoln = 'First solution found in c. ' + + intMSeconds + ' milliseconds:\n\n' + + unlines(map(showLine(cellWidth, ' ', { + nothing: true, + just: startXY + }), lstGroups)) + '\n\n'; + + console.log(strSoln); + return strMap + '\n\n' + strSoln; + }; + + // TEST ------------------------------------------------------------------- + return unlines(map(solutionString, problems)); +})(); 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.kotlin new file mode 100644 index 0000000000..4a3adfc0ab --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Kotlin/solve-a-holy-knights-tour.kotlin @@ -0,0 +1,87 @@ +// version 1.1.3 + +val moves = arrayOf( + intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1, 2), intArrayOf(1, 2), + intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf( 2, -1), intArrayOf(2, 1) +) + +val board1 = + " xxx " + + " x xx " + + " xxxxxxx" + + "xxx x x" + + "x x xxx" + + "sxxxxxx " + + " xx x " + + " xxx " + +val 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....." + +fun solve(pz: Array, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean { + if (idx > cnt) return true + for (i in 0 until moves.size) { + val x = sx + moves[i][0] + val y = sy + moves[i][1] + if ((x in 0 until sz) && (y in 0 until sz) && pz[x][y] == 0) { + pz[x][y] = idx + if (solve(pz, sz, x, y, idx + 1, cnt)) return true + pz[x][y] = 0 + } + } + return false +} + +fun findSolution(b: String, sz: Int) { + val pz = Array(sz) { IntArray(sz) { -1 } } + var x = 0 + var y = 0 + var idx = 0 + var cnt = 0 + for (j in 0 until sz) { + for (i in 0 until sz) { + if (b[idx] == 'x') { + pz[i][j] = 0 + cnt++ + } + else if (b[idx] == 's') { + pz[i][j] = 1 + cnt++ + x = i + y = j + } + idx++ + } + } + + if (solve(pz, sz, x, y, 2, cnt)) { + for (j in 0 until sz) { + for (i in 0 until sz) { + if (pz[i][j] != -1) + print("%02d ".format(pz[i][j])) + else + print("-- ") + } + println() + } + } + else println("Cannot solve this puzzle!") +} + +fun main(args: Array) { + findSolution(board1, 8) + println() + findSolution(board2, 13) +} diff --git a/Task/Solve-a-Holy-Knights-tour/Lua/solve-a-holy-knights-tour.lua b/Task/Solve-a-Holy-Knights-tour/Lua/solve-a-holy-knights-tour.lua new file mode 100644 index 0000000000..5159c13b4a --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Lua/solve-a-holy-knights-tour.lua @@ -0,0 +1,57 @@ +local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8 +local p2, p2W = ".....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.....", 13 +local puzzle, movesCnt, wid = {}, 0, 0 +local moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 }, + { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } } + +function isValid( x, y ) + return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 ) +end +function solve( x, y, s ) + if s > movesCnt then return true end + local test, a, b + for i = 1, #moves do + test = false + a = x + moves[i][1]; b = y + moves[i][2] + if isValid( a, b ) then + puzzle[a + b * wid - wid] = s + if solve( a, b, s + 1 ) then return true end + puzzle[a + b * wid - wid] = 0 + end + end + return false +end +function printSolution() + local lp + for j = 1, wid do + for i = 1, wid do + lp = puzzle[i + j * wid - wid] + if lp == -1 then io.write( " " ) + else io.write( string.format( " %.2d", lp ) ) + end + end + print() + end + print( "\n" ) +end +local sx, sy +function fill( pz, w ) + puzzle = {}; wid = w; movesCnt = #pz + local lp + for i = 1, #pz do + lp = pz:sub( i, i ) + if lp == "x" then + table.insert( puzzle, 0 ) + elseif lp == "." then + table.insert( puzzle, -1 ); movesCnt = movesCnt - 1 + else + table.insert( puzzle, 1 ) + sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid ) + end + end +end +-- [[ entry point ]] -- +print( "\n\n" ); fill( p1, p1W ); +if solve( sx, sy, 2 ) then printSolution() end +print( "\n\n" ); fill( p2, p2W ); +if solve( sx, sy, 2 ) then printSolution() end diff --git a/Task/Solve-a-Holy-Knights-tour/Python/solve-a-holy-knights-tour.py b/Task/Solve-a-Holy-Knights-tour/Python/solve-a-holy-knights-tour.py new file mode 100644 index 0000000000..0eb8181dac --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Python/solve-a-holy-knights-tour.py @@ -0,0 +1,54 @@ +from sys import stdout +moves = [ + [-1, -2], [1, -2], [-1, 2], [1, 2], + [-2, -1], [-2, 1], [2, -1], [2, 1] +] + + +def solve(pz, sz, sx, sy, idx, cnt): + if idx > cnt: + return 1 + + for i in range(len(moves)): + x = sx + moves[i][0] + y = sy + moves[i][1] + if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: + pz[x][y] = idx + if 1 == solve(pz, sz, x, y, idx + 1, cnt): + return 1 + pz[x][y] = 0 + + return 0 + + +def find_solution(pz, sz): + p = [[-1 for j in range(sz)] for i in range(sz)] + idx = x = y = cnt = 0 + for j in range(sz): + for i in range(sz): + if pz[idx] == "x": + p[i][j] = 0 + cnt += 1 + elif pz[idx] == "s": + p[i][j] = 1 + cnt += 1 + x = i + y = j + idx += 1 + + if 1 == solve(p, sz, x, y, 2, cnt): + for j in range(sz): + for i in range(sz): + if p[i][j] != -1: + stdout.write(" {:0{}d}".format(p[i][j], 2)) + else: + stdout.write(" ") + print() + else: + print("Cannot solve this puzzle!") + + +# entry point +find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) +print() +find_solution(".....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.....", 13) diff --git a/Task/Solve-a-Holy-Knights-tour/REXX/solve-a-holy-knights-tour.rexx b/Task/Solve-a-Holy-Knights-tour/REXX/solve-a-holy-knights-tour.rexx index f5f7dbd31b..1ab6e6f736 100644 --- a/Task/Solve-a-Holy-Knights-tour/REXX/solve-a-holy-knights-tour.rexx +++ b/Task/Solve-a-Holy-Knights-tour/REXX/solve-a-holy-knights-tour.rexx @@ -1,51 +1,51 @@ /*REXX program solves the holy knight's tour problem for a (general) NxN chessboard.*/ blank=pos('//', space(arg(1), 0))\==0 /*see if the pennies are to be shown. */ parse arg ops '/' cent /*obtain the options and the pennies. */ -parse var ops N sRank sFile . /*boardsize, starting position, pennys*/ +parse var ops N sRank sFile . /*boardsize, starting position, pennys.*/ if N=='' | N=="," then N=8 /*no boardsize specified? Use default.*/ if sRank=='' | sRank=="," then sRank=N /*starting rank given? " " */ if sFile=='' | sFile=="," then sFile=1 /* " file " " " */ NN=N**2; NxN='a ' N"x"N ' chessboard' /*file [↓] [↓] r=rank */ -@.=; do r=1 for N; do f=1 for N; @.r.f=.; end /*f*/; end /*r*/ +@.=; do r=1 for N; do f=1 for N; @.r.f=.; end /*f*/; end /*r*/ /*[↑] create an empty NxN chessboard.*/ -cent=space(translate(cent, , ',')) /*allow use of comma (,) for separater.*/ +cent=space( translate( cent, , ',') ) /*allow use of comma (,) for separater.*/ cents=0 /*number of pennies on the chessboard. */ do while cent\='' /* [↓] possibly place the pennies. */ parse var cent cr cf x '/' cent /*extract where to place the pennies. */ if x='' then x=1 /*if number not specified, use 1 penny.*/ if cr='' then iterate /*support the "blanking" option. */ - do cf=cf for x /*now, place X pennies on chessboard.*/ - @.cr.cf='¢' /*mark chessboard position with a penny*/ - end /*cf*/ /* [↑] places X pennies on chessboard.*/ - end /*while*/ /* [↑] allows of the placing of X ¢s*/ + do cf=cf for x /*now, place X pennies on chessboard.*/ + @.cr.cf= '¢' /*mark chessboard position with a penny*/ + end /*cf*/ /* [↑] places X pennies on chessboard.*/ + end /*while*/ /* [↑] allows of the placing of X ¢s*/ /* [↓] traipse through the chessboard.*/ - do r=1 for N; do f=1 for N; cents=cents+(@.r.f=='¢'); end; end + do r=1 for N; do f=1 for N; cents=cents + (@.r.f=='¢'); end /*f*/; end /*r*/ /* [↑] count the number of pennies. */ -if cents\==0 then say cents 'pennies placed on chessboard.' -target=NN-cents /*use this as the number of moves left.*/ -beg='-1-' /*[↑] create the NxN chessboard. */ - Kr = '2 1 -1 -2 -2 -1 1 2' /*the legal "rank" moves for a knight.*/ - Kf = '1 2 2 1 -1 -2 -2 -1' /* " " "file" " " " " */ +if cents\==0 then say cents 'pennies placed on chessboard.' +target=NN - cents /*use this as the number of moves left.*/ + Kr = '2 1 -1 -2 -2 -1 1 2' /*the legal "rank" moves for a knight.*/ + Kf = '1 2 2 1 -1 -2 -2 -1' /* " " "file" " " " " */ +kr.M=words(Kr) /*number of possible moves for a Knight*/ parse var Kr Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8 /*parse the legal moves by hand.*/ parse var Kf Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8 /* " " " " " " */ -if @.sRank.sFile==. then @.sRank.sFile=beg /*the knight's starting position. */ - +beg= '-1-' /* [↑] create the NxN chessboard. */ +if @.sRank.sFile ==. then @.sRank.sFile=beg /*the knight's starting position. */ if @.sRank.sFile\==beg then do sRank=1 for N /*find starting rank for the knight.*/ do sFile=1 for N /* " " file " " " */ if @.sRank.sFile\==. then iterate @.sRank.sFile=beg /*the knight's starting position. */ leave sRank /*we have a spot, so leave all this.*/ - end /*sRank*/ - end /*sFile*/ -@hkt= "holy knight's tour" /*a handy-dandy literal for the SAYs. */ -if \move(2,sRank,sFile) & \(N==1) then say 'No' @hkt "solution for" NxN'.' - else say 'A solution for the' @hkt "on" NxN':' + end /*sFile*/ + end /*sRank*/ +@hkt= "holy knight's tour" /*a handy─dandy literal for the SAYs. */ +if \move(2,sRank,sFile) & \(N==1) then say 'No' @hkt "solution for" NxN'.' + else say 'A solution for the' @hkt "on" NxN':' - /*show chessboard with moves & pennies.*/ -!=left('', 9*(n<18)) /*used for indentation of chessboard. */ -_=substr(copies("┼───",N),2); say; say ! translate('┌'_"┐", '┬', "┼") - do r=N for N by -1; if r\==N then say ! '├'_"┤"; L=@. - do f=1 for N; ?=@.r.f; if ?==target then ?='end'; L=L'│'center(?,3) /*"end"?*/ + /*show chessboard with moves and coins.*/ +!=left('', 9 * (n<18) ); say /*used for indentation of chessboard. */ +_=substr( copies("┼───", N), 2); say ! translate('┌'_"┐", '┬', "┼") + do r=N for N by -1; if r\==N then say ! '├'_"┤"; L=@. + do f=1 for N; ?=@.r.f; if ?==target then ?='end'; L=L'│'center(?,3) end /*f*/ if blank then L=translate(L,,'¢') /*blank out the pennies on chessboard ?*/ say ! translate(L'│', , .) /*display a rank of the chessboard. */ @@ -54,11 +54,11 @@ say ! translate('└'_"┘", '┴', "┼") /*display the last rank exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ move: procedure expose @. Kr. Kf. target; parse arg #,rank,file /*obtain move,rank,file.*/ - do t=1 for 8; nr=rank+Kr.t; nf=file+Kf.t /*position of the knight*/ - if @.nr.nf==. then do; @.nr.nf=# /*Empty? Knight can move*/ - if #==target then return 1 /*is this the last move?*/ - if move(#+1,nr,nf) then return 1 /* " " " " " */ - @.nr.nf=. /*undo the above move. */ - end /*try different move. */ - end /*t*/ /* [↑] all moves tried.*/ -return 0 /*tour is not possible. */ + do t=1 for Kr.M; nr=rank+Kr.t; nf=file+Kf.t /*position of the knight*/ + if @.nr.nf==. then do; @.nr.nf=# /*Empty? Knight can move*/ + if #==target then return 1 /*is this the last move?*/ + if move(#+1,nr,nf) then return 1 /* " " " " " */ + @.nr.nf=. /*undo the above move. */ + end /*try a different move. */ + end /*t*/ /* [↑] all moves tried.*/ + return 0 /*tour isn't possible. */ diff --git a/Task/Solve-a-Hopido-puzzle/00DESCRIPTION b/Task/Solve-a-Hopido-puzzle/00DESCRIPTION index c69f162fb6..7b303559f9 100644 --- a/Task/Solve-a-Hopido-puzzle/00DESCRIPTION +++ b/Task/Solve-a-Hopido-puzzle/00DESCRIPTION @@ -15,9 +15,14 @@ Example: Extra credits are available for other interesting designs. -Related Tasks: + +;Related tasks: +* [[A* search algorithm]] +* [[Solve a Holy Knight's tour]] +* [[Knight's tour]] +* [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]] -* [[Knight's tour]] +

    diff --git a/Task/Solve-a-Hopido-puzzle/D/solve-a-hopido-puzzle-1.d b/Task/Solve-a-Hopido-puzzle/D/solve-a-hopido-puzzle-1.d deleted file mode 100644 index f1b9bdaf4a..0000000000 --- a/Task/Solve-a-Hopido-puzzle/D/solve-a-hopido-puzzle-1.d +++ /dev/null @@ -1,114 +0,0 @@ -import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons; - - -struct HopidoPuzzle { - private alias InputCellBaseType = char; - private enum InputCell : InputCellBaseType { available = '#', unavailable = '.' } - private alias Cell = uint; - private enum : Cell { unknownCell = 0, unavailableCell = Cell.max } // Special Cell values. - - // Neighbors, [shift row, shift column]. - private static immutable int[2][8] shifts = [[-2, -2], [2, -2], [-2, 2], [2, 2], - [ 0, -3], [0, 3], [-3, 0], [3, 0]]; - - private immutable size_t gridWidth, gridHeight; - private immutable Cell nAvailableCells; - private /*immutable*/ const InputCell[] flatPuzzle; - private Cell[] grid; // Flattened mutable game grid. - - @disable this(); - - - this(in string[] rawPuzzle) pure @safe - in { - assert(!rawPuzzle.empty); - assert(!rawPuzzle[0].empty); - assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); // Is rectangular. - - // Has at least one start point. - assert(rawPuzzle.join.representation.canFind(InputCell.available)); - } body { - //immutable puzzle = rawPuzzle.to!(InputCell[][]); - immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]); - - gridWidth = puzzle[0].length; - gridHeight = puzzle.length; - flatPuzzle = puzzle.join; - nAvailableCells = flatPuzzle.representation.count!(ic => ic == InputCell.available); - - grid = flatPuzzle - .representation - .map!(ic => ic == InputCell.available ? unknownCell : unavailableCell) - .array; - } - - - Nullable!(string[][]) solve() pure /*nothrow*/ @safe - out(result) { - if (!result.isNull) - assert(!grid.canFind(unknownCell)); - } body { - // Try all possible start positions. - foreach (immutable r; 0 .. gridHeight) { - foreach (immutable c; 0 .. gridWidth) { - immutable pos = r * gridWidth + c; - if (grid[pos] == unknownCell) { - immutable Cell startCell = 1; // To lay the first cell value. - grid[pos] = startCell; // Try. - if (search(r, c, startCell + 1)) { - auto result = zip(flatPuzzle, grid) - //.map!({p, c} => ... - .map!(pc => (pc[0] == InputCell.available) ? - pc[1].text : - InputCellBaseType(pc[0]).text) - .array - .chunks(gridWidth) - .array; - return typeof(return)(result); - } - grid[pos] = unknownCell; // Restore. - } - } - } - - return typeof(return)(); - } - - - private bool search(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { - if (cell > nAvailableCells) - return true; // One solution found. - - foreach (immutable sh; shifts) { - immutable r2 = r + sh[0], - c2 = c + sh[1], - pos = r2 * gridWidth + c2; - // No need to test for >= 0 because uint wraps around. - if (c2 < gridWidth && r2 < gridHeight && grid[pos] == unknownCell) { - grid[pos] = cell; // Try. - if (search(r2, c2, cell + 1)) - return true; - grid[pos] = unknownCell; // Restore. - } - } - - return false; - } -} - - -void main() @safe { - // enum HopidoPuzzle to catch malformed puzzles at compile-time. - enum puzzle = ".##.##. - ####### - ####### - .#####. - ..###.. - ...#...".split.HopidoPuzzle; - - immutable solution = puzzle.solve; // Solved at run-time. - if (solution.isNull) - writeln("No solution found."); - else - writefln("One solution:\n%(%-(%2s %)\n%)", solution); -} diff --git a/Task/Solve-a-Hopido-puzzle/D/solve-a-hopido-puzzle-2.d b/Task/Solve-a-Hopido-puzzle/D/solve-a-hopido-puzzle-2.d deleted file mode 100644 index 8b9f27784c..0000000000 --- a/Task/Solve-a-Hopido-puzzle/D/solve-a-hopido-puzzle-2.d +++ /dev/null @@ -1,98 +0,0 @@ -global nCells, cMap, best -record Pos(r,c) - -procedure main(A) - puzzle := showPuzzle("Input",readPuzzle()) - QMouse(puzzle,findStart(puzzle),&null,0) - showPuzzle("Output", solvePuzzle(puzzle)) | write("No solution!") -end - -procedure readPuzzle() - # Start with a reduced puzzle space - p := [[-1],[-1]] - nCells := maxCols := 0 - every line := !&input do { - put(p,[: -1 | -1 | gencells(line) | -1 | -1 :]) - maxCols <:= *p[-1] - } - every put(p, [-1]|[-1]) - # Now normalize all rows to the same length - every i := 1 to *p do p[i] := [: !p[i] | (|-1\(maxCols - *p[i])) :] - return p -end - -procedure gencells(s) - static WS, NWS - initial { - NWS := ~(WS := " \t") - cMap := table() # Map to/from internal model - cMap["#"] := -1; cMap["_"] := 0 - cMap[-1] := " "; cMap[0] := "_" - } - - s ? while not pos(0) do { - w := (tab(many(WS))|"", tab(many(NWS))) | break - w := numeric(\cMap[w]|w) - if -1 ~= w then nCells +:= 1 - suspend w - } -end - -procedure showPuzzle(label, p) - write(label," with ",nCells," cells:") - every r := !p do { - every c := !r do writes(right((\cMap[c]|c),*nCells+1)) - write() - } - return p -end - -procedure findStart(p) - if \p[r := !*p][c := !*p[r]] = 1 then return Pos(r,c) -end - -procedure solvePuzzle(puzzle) - if path := \best then { - repeat { - loc := path.getLoc() - puzzle[loc.r][loc.c] := path.getVal() - path := \path.getParent() | break - } - return puzzle - } -end - -class QMouse(puzzle, loc, parent, val) - - method getVal(); return val; end - method getLoc(); return loc; end - method getParent(); return parent; end - method atEnd(); return nCells = val; end - - method visit(r,c) - if /best & validPos(r,c) then return Pos(r,c) - end - - method validPos(r,c) - v := val+1 - xv := (0 <= puzzle[r][c]) | fail - if xv = (v|0) then { # make sure this path hasn't already gone there - ancestor := self - while xl := (ancestor := \ancestor.getParent()).getLoc() do - if (xl.r = r) & (xl.c = c) then fail - return - } - end - -initially - val := val+1 - if atEnd() then return best := self - QMouse(puzzle, visit(loc.r-3,loc.c), self, val) - QMouse(puzzle, visit(loc.r-2,loc.c-2), self, val) - QMouse(puzzle, visit(loc.r, loc.c-3), self, val) - QMouse(puzzle, visit(loc.r+2,loc.c-2), self, val) - QMouse(puzzle, visit(loc.r+3,loc.c), self, val) - QMouse(puzzle, visit(loc.r+2,loc.c+2), self, val) - QMouse(puzzle, visit(loc.r, loc.c+3), self, val) - QMouse(puzzle, visit(loc.r-2,loc.c+2), self, val) -end diff --git a/Task/Solve-a-Hopido-puzzle/Python/solve-a-hopido-puzzle.py b/Task/Solve-a-Hopido-puzzle/Python/solve-a-hopido-puzzle.py new file mode 100644 index 0000000000..d52f23f55b --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/Python/solve-a-hopido-puzzle.py @@ -0,0 +1,63 @@ +from sys import stdout + +neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] +cnt = 0 +pWid = 0 +pHei = 0 + + +def is_valid(a, b): + return -1 < a < pWid and -1 < b < pHei + + +def iterate(pa, x, y, v): + if v > cnt: + return 1 + + for i in range(len(neighbours)): + a = x + neighbours[i][0] + b = y + neighbours[i][1] + if is_valid(a, b) and pa[a][b] == 0: + pa[a][b] = v + r = iterate(pa, a, b, v + 1) + if r == 1: + return r + pa[a][b] = 0 + return 0 + + +def solve(pz, w, h): + global cnt, pWid, pHei + + pa = [[-1 for j in range(h)] for i in range(w)] + f = 0 + pWid = w + pHei = h + for j in range(h): + for i in range(w): + if pz[f] == "1": + pa[i][j] = 0 + cnt += 1 + f += 1 + + for y in range(h): + for x in range(w): + if pa[x][y] == 0: + pa[x][y] = 1 + if 1 == iterate(pa, x, y, 2): + return 1, pa + pa[x][y] = 0 + + return 0, pa + +r = solve("011011011111111111111011111000111000001000", 7, 6) +if r[0] == 1: + for j in range(6): + for i in range(7): + if r[1][i][j] == -1: + stdout.write(" ") + else: + stdout.write(" {:0{}d}".format(r[1][i][j], 2)) + print() +else: + stdout.write("No solution!") diff --git a/Task/Solve-a-Hopido-puzzle/Zkl/solve-a-hopido-puzzle.zkl b/Task/Solve-a-Hopido-puzzle/Zkl/solve-a-hopido-puzzle.zkl new file mode 100644 index 0000000000..fa09e45caa --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/Zkl/solve-a-hopido-puzzle.zkl @@ -0,0 +1,21 @@ +hi:= // 0==empty cell, X==not a cell +#<<< +" X 0 0 X 0 0 X + 0 0 0 0 0 0 0 + 0 0 0 0 0 0 0 + X 0 0 0 0 0 X + X X 0 0 0 X X + X X X 0 X X X"; +#<<< +adjacent:=T( T(-3,0), + T(-2,-2), T(-2,2), + T(0,-3), T(0,3), + T(2,-2), T(2,2), + T(3,0) ); + +puzzle:=Puzzle(hi,adjacent); +puzzle.print_board(); +puzzle.solve(); +println(); +puzzle.print_board(); +println(); diff --git a/Task/Solve-a-Numbrix-puzzle/00DESCRIPTION b/Task/Solve-a-Numbrix-puzzle/00DESCRIPTION index 8b6ac25cfa..e97f0d2326 100644 --- a/Task/Solve-a-Numbrix-puzzle/00DESCRIPTION +++ b/Task/Solve-a-Numbrix-puzzle/00DESCRIPTION @@ -58,10 +58,14 @@ Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. -Related Tasks: + +;Related tasks: +* [[A* search algorithm]] +* [[Solve a Holy Knight's tour]] +* [[Knight's tour]] +* [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve the no connection puzzle]] -* [[Knight's tour]]

    diff --git a/Task/Solve-a-Numbrix-puzzle/D/solve-a-numbrix-puzzle-1.d b/Task/Solve-a-Numbrix-puzzle/D/solve-a-numbrix-puzzle-1.d deleted file mode 100644 index 473a5bd2fd..0000000000 --- a/Task/Solve-a-Numbrix-puzzle/D/solve-a-numbrix-puzzle-1.d +++ /dev/null @@ -1,209 +0,0 @@ -import std.stdio, std.conv, std.string, std.range, std.array, std.typecons, std.algorithm; - -struct { - alias BitSet8 = ubyte; // A set of 8 bits. - alias Cell = uint; - enum : string { unavailableInCell = "#", availableInCell = "." } - enum : Cell { unavailableCell = Cell.max, availableCell = 0 } - - this(in string inPuzzle) pure @safe { - const rawPuzzle = inPuzzle.splitLines.map!(row => row.split).array; - assert(!rawPuzzle.empty); - assert(!rawPuzzle[0].empty); - assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); // Is rectangular. - - gridWidth = rawPuzzle[0].length; - gridHeight = rawPuzzle.length; - immutable nMaxCells = gridWidth * gridHeight; - grid = new Cell[nMaxCells]; - auto knownMutable = new bool[nMaxCells + 1]; - uint nAvailableMutable = nMaxCells; - bool[Cell] seenCells; // To avoid duplicate input numbers. - - uint i = 0; - foreach (const piece; rawPuzzle.join) { - if (piece == unavailableInCell) { - nAvailableMutable--; - grid[i++] = unavailableCell; - continue; - } else if (piece == availableInCell) { - grid[i] = availableCell; - } else { - immutable cell = piece.to!Cell; - assert(cell > 0 && cell <= nMaxCells); - assert(cell !in seenCells); - seenCells[cell] = true; - knownMutable[cell] = true; - grid[i] = cell; - } - - i++; - } - - known = knownMutable.idup; - nAvailable = nAvailableMutable; - } - - @disable this(); - - - auto solve() pure nothrow @safe @nogc - out(result) { - if (!result.isNull) { - // Can't verify 'result' here because it's const. - // assert(!result.get.join.canFind(availableCell.text)); - - assert(!grid.canFind(availableCell)); - auto values = grid.filter!(c => c != unavailableCell); - auto interval = iota(reduce!min(values.front, values.dropOne), - reduce!max(values.front, values.dropOne) + 1); - assert(values.walkLength == interval.length); - assert(interval.all!(c => values.count(c) == 1)); // Quadratic. - } - } body { - auto result = grid - .map!(c => (c == unavailableCell) ? unavailableInCell : c.text) - .chunks(gridWidth); - alias OutRange = Nullable!(typeof(result)); - - const start = findStart; - if (start.isNull) - return OutRange(); - - search(start.r, start.c, start.cell + 1, 1); - if (start.cell > 1) { - immutable direction = -1; - search(start.r, start.c, start.cell + direction, direction); - } - - if (grid.any!(c => c == availableCell)) - return OutRange(); - else - return OutRange(result); - } - - private: - - - bool search(in uint r, in uint c, in Cell cell, in int direction) - pure nothrow @safe @nogc { - if ((cell > nAvailable && direction > 0) || (cell == 0 && direction < 0) || - (cell == nAvailable && known[cell])) - return true; // One solution found. - - immutable neighbors = getNeighbors(r, c); - - if (known[cell]) { - foreach (immutable i, immutable rc; shifts) { - if (neighbors & (1u << i)) { - immutable c2 = c + rc[0], - r2 = r + rc[1]; - if (grid[r2 * gridWidth + c2] == cell) - if (search(r2, c2, cell + direction, direction)) - return true; - } - } - return false; - } - - foreach (immutable i, immutable rc; shifts) { - if (neighbors & (1u << i)) { - immutable c2 = c + rc[0], - r2 = r + rc[1], - pos = r2 * gridWidth + c2; - if (grid[pos] == availableCell) { - grid[pos] = cell; // Try. - if (search(r2, c2, cell + direction, direction)) - return true; - grid[pos] = availableCell; // Restore. - } - } - } - return false; - } - - - BitSet8 getNeighbors(in uint r, in uint c) const pure nothrow @safe @nogc { - typeof(return) usable = 0; - - foreach (immutable i, immutable rc; shifts) { - immutable c2 = c + rc[0], - r2 = r + rc[1]; - if (c2 >= gridWidth || r2 >= gridHeight) - continue; - if (grid[r2 * gridWidth + c2] != unavailableCell) - usable |= (1u << i); - } - - return usable; - } - - - auto findStart() const pure nothrow @safe @nogc { - alias Triple = Tuple!(uint,"r", uint,"c", Cell,"cell"); - Nullable!Triple result; - - auto cell = Cell.max; - foreach (immutable r; 0 .. gridHeight) { - foreach (immutable c; 0 .. gridWidth) { - immutable pos = gridWidth * r + c; - if (grid[pos] != availableCell && - grid[pos] != unavailableCell && grid[pos] < cell) { - cell = grid[pos]; - result = Triple(r, c, cell); - } - } - } - - return result; - } - - static immutable int[2][4] shifts = [[0, -1], [0, 1], [-1, 0], [1, 0]]; - immutable uint gridWidth, gridHeight; - immutable int nAvailable; - immutable bool[] known; // Given known cells of the puzzle. - Cell[] grid; // Flattened mutable game grid. -} - - -void main() { - // enum NumbrixPuzzle to catch malformed puzzles at compile-time. - enum puzzle1 = ". . . . . . . . . - . . 46 45 . 55 74 . . - . 38 . . 43 . . 78 . - . 35 . . . . . 71 . - . . 33 . . . 59 . . - . 17 . . . . . 67 . - . 18 . . 11 . . 64 . - . . 24 21 . 1 2 . . - . . . . . . . . .".NumbrixPuzzle; - - enum puzzle2 = ". . . . . . . . . - . 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 . - . . . . . . . . .".NumbrixPuzzle; - - enum puzzle3 = "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".NumbrixPuzzle; - - - foreach (puzzle; [puzzle1, puzzle2, puzzle3]) { - auto solution = puzzle.solve; // Solved at run-time. - if (solution.isNull) - writeln("No solution found for puzzle.\n"); - else - writefln("One solution:\n%(%-(%2s %)\n%)\n", solution); - } -} diff --git a/Task/Solve-a-Numbrix-puzzle/D/solve-a-numbrix-puzzle-2.d b/Task/Solve-a-Numbrix-puzzle/D/solve-a-numbrix-puzzle-2.d deleted file mode 100644 index c2e2906849..0000000000 --- a/Task/Solve-a-Numbrix-puzzle/D/solve-a-numbrix-puzzle-2.d +++ /dev/null @@ -1,90 +0,0 @@ -global nCells, cMap, best -record Pos(r,c) - -procedure main(A) - puzzle := showPuzzle("Input",readPuzzle()) - QMouse(puzzle,findStart(puzzle),&null,0) - showPuzzle("Output", solvePuzzle(puzzle)) | write("No solution!") -end - -procedure readPuzzle() - # Start with a reduced puzzle space - p := [] - nCells := maxCols := 0 - every line := !&input do { - put(p,[: gencells(line) :]) - maxCols <:= *p[-1] - } - # Now normalize all rows to the same length - every i := 1 to *p do p[i] := [: !p[i] | (|-1\(maxCols - *p[i])) :] - return p -end - -procedure gencells(s) - static WS, NWS - initial { - NWS := ~(WS := " \t") - cMap := table() # Map to/from internal model - cMap["_"] := 0; cMap[0] := "_" - } - - s ? while not pos(0) do { - w := (tab(many(WS))|"", tab(many(NWS))) | break - w := numeric(\cMap[w]|w) - if -1 ~= w then nCells +:= 1 - suspend w - } -end - -procedure showPuzzle(label, p) - write(label," with ",nCells," cells:") - every r := !p do { - every c := !r do writes(right((\cMap[c]|c),*nCells+1)) - write() - } - return p -end - -procedure findStart(p) - if \p[r := !*p][c := !*p[r]] = 1 then return Pos(r,c) -end - -procedure solvePuzzle(puzzle) - if path := \best then { - repeat { - loc := path.getLoc() - puzzle[loc.r][loc.c] := path.getVal() - path := \path.getParent() | break - } - return puzzle - } -end - -class QMouse(puzzle, loc, parent, val) - - method getVal(); return val; end - method getLoc(); return loc; end - method getParent(); return parent; end - method atEnd(); return (nCells = val, puzzle[loc.r,loc.c] = (val|0)); end - method visit(r,c); return (/best, validPos(r,c), Pos(r,c)); end - - method validPos(r,c) - v := val+1 # number we're looking for - xv := puzzle[r,c] | fail - if (xv ~= 0) & (xv != v) then fail - if xv = (0|v) then { - ancestor := self - while xl := (ancestor := \ancestor.getParent()).getLoc() do - if (xl.r = r) & (xl.c = c) then fail - return - } - end - -initially - val := val+1 - if atEnd() then return best := self - QMouse(puzzle, visit(loc.r-1,loc.c) , self, val) # North - QMouse(puzzle, visit(loc.r, loc.c+1), self, val) # East - QMouse(puzzle, visit(loc.r+1,loc.c), self, val) # South - QMouse(puzzle, visit(loc.r, loc.c-1), self, val) # West -end 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 new file mode 100644 index 0000000000..fdc2e475cb --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Python/solve-a-numbrix-puzzle.py @@ -0,0 +1,98 @@ +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/SystemVerilog/solve-a-numbrix-puzzle.v b/Task/Solve-a-Numbrix-puzzle/SystemVerilog/solve-a-numbrix-puzzle.v new file mode 100644 index 0000000000..753eb37fbd --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/SystemVerilog/solve-a-numbrix-puzzle.v @@ -0,0 +1,129 @@ +/// @Author: Alexandre Felipe (o.alexandre.felipe@gmail.com) +/// @Date: 2017-May-10 +/// + + +////////////////////////////////////////////////////////////////////////////// +/// NumbrixSolver /// +/// Solve the puzzle, by using system verilog randomization engine /// +////////////////////////////////////////////////////////////////////////////// +class NumbrixSolver; + rand int solvedBoard[][]; + int fixedBoard[][]; + int numCells; + //////////////////////////////////////////////////////////////////////////// + /// Dynamically resize the board accordingly to the size of the reference/// + /// board /// + //////////////////////////////////////////////////////////////////////////// + constraint height { + solvedBoard.size == fixedBoard.size; + } + constraint width { + foreach(solvedBoard[i]) solvedBoard[i].size == fixedBoard[i].size; + } + + //////////////////////////////////////////////////////////////////////////// + /// Fix the positions defined in the input board /// + //////////////////////////////////////////////////////////////////////////// + constraint fixed { + foreach(solvedBoard[i]) foreach(solvedBoard[i][j]) + if(fixedBoard[i][j] != 0)solvedBoard[i][j] == fixedBoard[i][j]; + } + //////////////////////////////////////////////////////////////////////////// + /// Ensures that the whole board is filled from the number with numbers /// + /// 1,2,3,...,numCells /// + //////////////////////////////////////////////////////////////////////////// + constraint range { + foreach(solvedBoard[i])foreach(solvedBoard[i][j]) + solvedBoard[i][j] inside {[1:numCells]}; + } + //////////////////////////////////////////////////////////////////////////// + /// Ensures that there is no repeated number, consequently every number /// + /// is present on the board /// + //////////////////////////////////////////////////////////////////////////// + constraint uniqueness { + foreach(solvedBoard[i1]) foreach(solvedBoard[i1][j1]) + foreach(solvedBoard[i2]) foreach(solvedBoard[i2][j2]) + if((i1 != i2) || (j1 != j2)) solvedBoard[i1][j1] != solvedBoard[i2][j2]; + } + + //////////////////////////////////////////////////////////////////////////// + /// Ensures that exists one direction connecting the numbers in /// + /// increasing order /// + //////////////////////////////////////////////////////////////////////////// + constraint f_seq { + foreach(solvedBoard[i])foreach(solvedBoard[i][j]) + (solvedBoard[i][j] == (numCells)) || + (solvedBoard[(i < solvedBoard.size-1) ? (i+1): i][j] == + solvedBoard[i][j]+1) || + (solvedBoard[i][(j < solvedBoard[i].size - 1) ? j+1: j] == + solvedBoard[i][j]+1) || + (solvedBoard[(i > 0) ? i-1: i][j] == + solvedBoard[i][j]+1) || + (solvedBoard[i][(j > 0)? j-1:j] == + solvedBoard[i][j]+1); + } + + + function void pre_randomize(); + // the multiplication is not supported in the constraints + numCells = fixedBoard.size * fixedBoard[0].size; + endfunction + function void printSolvedBoard(); + foreach(solvedBoard[i]) begin + foreach(solvedBoard[j]) begin + $write("%4d", solvedBoard[i][j]); + end + $display(""); + end + endfunction +endclass + + +////////////////////////////////////////////////////////////////////////////// +/// SolveNumBrix: A program demonstrating how to use NumbrixSolver class /// +////////////////////////////////////////////////////////////////////////////// + +program SolveNumbrix; + NumbrixSolver board; + initial begin + board = new; + board.fixedBoard = '{ + '{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}}; + if(board.randomize()) begin + $display("Solution for the Example 1"); + board.printSolvedBoard(); + end + else begin + $display("Failed to solve Example 1"); + end + + board.fixedBoard = '{ + {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}}; + + if(board.randomize()) begin + $display("Solution for the Example 2"); + board.printSolvedBoard(); + end + else begin + $display("Failed to solve Example 2"); + end + $finish; + end +endprogram 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 new file mode 100644 index 0000000000..de12ddf8a7 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-1.zkl @@ -0,0 +1,58 @@ + // Solve Hidato/Hopido/Numbrix puzzles +class Puzzle{ // hold info concerning this puzzle + var board, nrows,ncols, cells, + start, // (r,c) where 1 is located, Void if no 1 + terminated, // if board holds highest numbered cell + given, // all the pre-loaded cells + adj, // a list of (r,c) that are valid next cells + ; + + fcn print_board{ + d:=Dictionary(-1," ", 0,"__"); + foreach r in (board){ + r.pump(String,'wrap(c){ "%2s ".fmt(d.find(c,c)) }).println(); + } + } + fcn init(s,adjacent){ + adj=adjacent; + lines:=s.split("\n"); + ncols,nrows=lines[0].split().len(),lines.len(); + board=nrows.pump(List(), ncols.pump(List(),-1).copy); + 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); + } + } + println("Number of cells = ",cells); + if(not given.holds(cells)){ given.append(cells); terminated=False; } + given=given.filter().sort(); + } + 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); + } + False + } + fcn [private] _solve(r,c,n=1, next=0){ + if(n>given[-1]) return(True); + if(not ( (0<=r 1 || abs(col-c) > 1) + list .= r ":"c "," + if (row<>2) && oGrid[row, col] + list .= oGrid[row, col+1] ? row ":" col+1 "," : oGrid[row, col-1] ? row ":" col-1 "," : "" + return Trim(list, ",") +} diff --git a/Task/Solve-the-no-connection-puzzle/Haskell/solve-the-no-connection-puzzle.hs b/Task/Solve-the-no-connection-puzzle/Haskell/solve-the-no-connection-puzzle.hs index bf10541830..f7c2e12732 100644 --- a/Task/Solve-the-no-connection-puzzle/Haskell/solve-the-no-connection-puzzle.hs +++ b/Task/Solve-the-no-connection-puzzle/Haskell/solve-the-no-connection-puzzle.hs @@ -1,34 +1,37 @@ -import Data.List - -isSolution :: [Int] -> Bool -isSolution (a:b:c:d:e:f:g:h:_) = - all (\v -> abs v > 1) - [a-d, - c-d, - g-d, - e-d, - - a-c, - c-g, - g-e, - e-a, - - b-e, - -- d-e, - h-e, - f-e, - - b-d, - d-h, - h-f, - f-b] +import Data.List (permutations, intercalate) +solution :: [Int] +solution@(a:b:c:d:e:f:g:h:_) = head $ filter isSolution (permutations [1 .. 8]) + where + isSolution :: [Int] -> Bool + isSolution (a:b:c:d:e:f:g:h:_) = + all + ((> 1) . abs) + [ a - d + , c - d + , g - d + , e - d + , a - c + , c - g + , g - e + , e - a + , b - e + , d - e + , h - e + , f - e + , b - d + , d - h + , h - f + , f - b + ] main :: IO () -main = do - let solution@(a:b:c:d:e:f:g:h:_) = head $ filter isSolution (permutations [1..8]) - mapM_ putStrLn $ zipWith (\label val -> [label] ++ " = " ++ show val) ['A'..'H'] solution - putStrLn "" - putStrLn $ " " ++ (show a) ++ " " ++ (show b) - putStrLn $ (show c) ++ " " ++ (show d) ++ " " ++ (show e) ++ " " ++ (show f) - putStrLn $ " " ++ (show g) ++ " " ++ (show h) +main = + mapM_ putStrLn $ + let rightShift s + | length s > 3 = s + | otherwise = " " ++ s + in intercalate + "\n" + (zipWith ((. ((" = " ++) . show)) . (:)) ['A' .. 'H'] solution) : + ((rightShift . unwords . (show <$>)) <$> [[], [a, b], [c, d, e, f], [g, h]]) diff --git a/Task/Solve-the-no-connection-puzzle/JavaScript/solve-the-no-connection-puzzle.js b/Task/Solve-the-no-connection-puzzle/JavaScript/solve-the-no-connection-puzzle.js new file mode 100644 index 0000000000..76899960e1 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/JavaScript/solve-the-no-connection-puzzle.js @@ -0,0 +1,121 @@ +(() => { + 'use strict'; + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // abs :: Num a => a -> a + const abs = Math.abs; + + // all :: (a -> Bool) -> [a] -> Bool + const all = (f, xs) => xs.every(f); + + // concatMap :: (a -> [b]) -> [a] -> [b] + const concatMap = (f, xs) => [].concat.apply([], xs.map(f)); + + // delete_ :: Eq a => a -> [a] -> [a] + const delete_ = (x, xs) => + deleteBy((a, b) => a === b, x, xs); + + // deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a] + const deleteBy = (f, x, xs) => + xs.length > 0 ? ( + f(x, xs[0]) ? ( + xs.slice(1) + ) : [xs[0]].concat(deleteBy(f, x, xs.slice(1))) + ) : []; + + // enumFromTo :: Enum a => a -> a -> [a] + const enumFromTo = (m, n) => { + const [tm, tn] = [typeof m, typeof n]; + return tm !== tn ? undefined : (() => { + const + blnS = (tm === 'string'), + [base, end] = [m, n].map(blnS ? (s => s.codePointAt(0)) : id); + return Array.from({ + length: Math.floor(end - base) + 1 + }, (_, i) => blnS ? String.fromCodePoint(base + i) : m + i); + })(); + }; + + // id :: a -> a + const id = x => x; + + // justifyRight :: Int -> Char -> Text -> Text + const justifyRight = (n, cFiller, strText) => + n > strText.length ? ( + (cFiller.repeat(n) + strText) + .slice(-n) + ) : strText; + + // permutations :: [a] -> [[a]] + const permutations = xs => + xs.length ? concatMap(x => concatMap(ys => [ + [x].concat(ys) + ], + permutations(delete_(x, xs))), xs) : [ + [] + ]; + + // show :: a -> String + const show = x => JSON.stringify(x); + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + // until :: (a -> Bool) -> (a -> a) -> a -> a + const until = (p, f, x) => { + let v = x; + while (!p(v)) v = f(v); + return v; + }; + + // unwords :: [String] -> String + const unwords = xs => xs.join(' '); + + // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] + const zipWith = (f, xs, ys) => { + const ny = ys.length; + return (xs.length <= ny ? xs : xs.slice(0, ny)) + .map((x, i) => f(x, ys[i])); + }; + + + // CONNECTION PUZZLE ------------------------------------------------------ + + // universe :: [[Int]] + const universe = permutations(enumFromTo(1, 8)); + + // isSolution :: [Int] -> Bool + const isSolution = ([a, b, c, d, e, f, g, h]) => + all(x => abs(x) > 1, [a - d, c - d, g - d, e - d, a - c, c - g, g - e, + e - a, b - e, d - e, h - e, f - e, b - d, d - h, h - f, f - b + ]); + + // firstSolution :: [Int] + const firstSolution = universe[until( + i => isSolution(universe[i]), + i => i + 1, + 0 + )]; + + // TEST ------------------------------------------------------------------- + + // [Int] + const [a, b, c, d, e, f, g, h] = firstSolution; + + return unlines( + zipWith( + (a, n) => a + ' = ' + n.toString(), + enumFromTo('A', 'H'), + firstSolution + ) + .concat( + [ + [], + [a, b], + [c, d, e, f], + [g, h] + ].map(xs => justifyRight(5, ' ', unwords(xs.map(show)))) + ) + ); +})(); diff --git a/Task/Solve-the-no-connection-puzzle/jq/solve-the-no-connection-puzzle-1.jq b/Task/Solve-the-no-connection-puzzle/Jq/solve-the-no-connection-puzzle-1.jq similarity index 100% rename from Task/Solve-the-no-connection-puzzle/jq/solve-the-no-connection-puzzle-1.jq rename to Task/Solve-the-no-connection-puzzle/Jq/solve-the-no-connection-puzzle-1.jq diff --git a/Task/Solve-the-no-connection-puzzle/jq/solve-the-no-connection-puzzle-2.jq b/Task/Solve-the-no-connection-puzzle/Jq/solve-the-no-connection-puzzle-2.jq similarity index 100% rename from Task/Solve-the-no-connection-puzzle/jq/solve-the-no-connection-puzzle-2.jq rename to Task/Solve-the-no-connection-puzzle/Jq/solve-the-no-connection-puzzle-2.jq diff --git a/Task/Solve-the-no-connection-puzzle/jq/solve-the-no-connection-puzzle-3.jq b/Task/Solve-the-no-connection-puzzle/Jq/solve-the-no-connection-puzzle-3.jq similarity index 100% rename from Task/Solve-the-no-connection-puzzle/jq/solve-the-no-connection-puzzle-3.jq rename to Task/Solve-the-no-connection-puzzle/Jq/solve-the-no-connection-puzzle-3.jq diff --git a/Task/Solve-the-no-connection-puzzle/jq/solve-the-no-connection-puzzle-4.jq b/Task/Solve-the-no-connection-puzzle/Jq/solve-the-no-connection-puzzle-4.jq similarity index 100% rename from Task/Solve-the-no-connection-puzzle/jq/solve-the-no-connection-puzzle-4.jq rename to Task/Solve-the-no-connection-puzzle/Jq/solve-the-no-connection-puzzle-4.jq diff --git a/Task/Solve-the-no-connection-puzzle/jq/solve-the-no-connection-puzzle-5.jq b/Task/Solve-the-no-connection-puzzle/Jq/solve-the-no-connection-puzzle-5.jq similarity index 100% rename from Task/Solve-the-no-connection-puzzle/jq/solve-the-no-connection-puzzle-5.jq rename to Task/Solve-the-no-connection-puzzle/Jq/solve-the-no-connection-puzzle-5.jq diff --git a/Task/Solve-the-no-connection-puzzle/Perl-6/solve-the-no-connection-puzzle.pl6 b/Task/Solve-the-no-connection-puzzle/Perl-6/solve-the-no-connection-puzzle.pl6 index 08e14b3898..959751fa3c 100644 --- a/Task/Solve-the-no-connection-puzzle/Perl-6/solve-the-no-connection-puzzle.pl6 +++ b/Task/Solve-the-no-connection-puzzle/Perl-6/solve-the-no-connection-puzzle.pl6 @@ -1,11 +1,11 @@ my @adjacent = gather -> $y, $x { take [$y,$x] if abs($x|$y) > 2; -} for -5 .. 5 X -5 .. 5; +} for flat -5 .. 5 X -5 .. 5; solveboard q:to/END/; - . 0 . . 0 . + . _ . . _ . . . . . . . - 0 . 0 1 . 0 + _ . _ 1 . _ . . . . . . - . 0 . . 0 . + . _ . . _ . END diff --git a/Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-1.rexx b/Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-1.rexx index e2cba728c8..cdff328c40 100644 --- a/Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-1.rexx +++ b/Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-1.rexx @@ -8,19 +8,19 @@ if limit=='' | limit=="." then limit=1 /* ║ A B @.3 = 'C A D G' /* ║ C────D────E────F ║ */ @.4 = 'D A B C E G' /* ║ \ │\ /│ / ║ */ @.5 = 'E A B D F H' /* ║ \ │ \/ │ / ║ */ -@.6 = 'F B E G' /* ║ \ │ /\ │ / ║ */ +@.6 = 'F B E H' /* ║ \ │ /\ │ / ║ */ @.7 = 'G C D E' /* ║ \│/ \│/ ║ */ @.8 = 'H D E F' /* ║ G H ║ */ cnt=0 /* ╚═══════════════════════════╝ */ - do nodes=1 while @.nodes\==''; _=word(@.nodes,1) + do pegs=1 while @.pegs\==''; _=word(@.pegs,1) subs=0 - do #=1 for words(@.nodes)-1 /*create list of node paths.*/ - __=word(@.nodes,#+1); if __>_ then iterate - subs=subs + 1; !._.subs=__ + do #=1 for words(@.pegs) -1 /*create list of node paths.*/ + __=word(@.pegs, # + 1); if __>_ then iterate + subs=subs + 1; !._.subs=__ end /*#*/ !._.0=subs /*assign the number of the node paths. */ - end /*nodes*/ -pegs=nodes-1 /*the number of pegs to be seated. */ + end /*pegs*/ +pegs=pegs-1 /*the number of pegs to be seated. */ _=' ' /*_ is used for indenting the output.*/ do a=1 for pegs; if ?('A') then iterate do b=1 for pegs; if ?('B') then iterate @@ -41,13 +41,13 @@ _=' ' /*_ is used for indenting the end /*b*/ end /*a*/ say /*display a blank line to the terminal.*/ -s=left('s',cnt\==1) /*handle the case of plurals (or not).*/ +s= left('s', cnt\==1) /*handle the case of plurals (or not).*/ say 'found ' cnt " solution"s'.' /*display the number of solutions found*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ ?: parse arg node; nn=value(node) nH=nn+1 - do cn=c2d('A') to c2d(node)-1; if value( d2c(cn) )==nn then return 1 + do cn=c2d('A') to c2d(node) - 1; if value( d2c(cn) )==nn then return 1 end /*cn*/ /* [↑] see if there any are duplicates.*/ nL=nn-1 do ch=1 for !.node.0 /* [↓] see if there any ¬= ±1 values.*/ diff --git a/Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-2.rexx b/Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-2.rexx index 2d71ea225f..8c5700fcb5 100644 --- a/Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-2.rexx +++ b/Task/Solve-the-no-connection-puzzle/REXX/solve-the-no-connection-puzzle-2.rexx @@ -9,19 +9,19 @@ oLimit=limit; limit=abs(limit) /* ║ /│\ / @.3 = 'C A D G' /* ║ C────D────E────F ║ */ @.4 = 'D A B C E G' /* ║ \ │\ /│ / ║ */ @.5 = 'E A B D F H' /* ║ \ │ \/ │ / ║ */ -@.6 = 'F B E G' /* ║ \ │ /\ │ / ║ */ +@.6 = 'F B E H' /* ║ \ │ /\ │ / ║ */ @.7 = 'G C D E' /* ║ \│/ \│/ ║ */ @.8 = 'H D E F' /* ║ G H ║ */ cnt=0 /* ╚═══════════════════════════╝ */ - do nodes=1 while @.nodes\==''; _=word(@.nodes,1) + do pegs=1 while @.pegs\==''; _=word(@.pegs, 1) subs=0 - do #=1 for words(@.nodes)-1 /*create list of node paths.*/ - __=word(@.nodes,#+1); if __>_ then iterate - subs=subs + 1; !._.subs=__ + do #=1 for words(@.pegs) -1 /*create list of node paths.*/ + __=word(@.pegs, #+1); if __>_ then iterate + subs=subs + 1; !._.subs=__ end /*#*/ !._.0=subs /*assign the number of the node paths. */ - end /*nodes*/ -pegs=nodes-1 /*the number of pegs to be seated. */ + end /*pegs*/ +pegs=pegs - 1 /*the number of pegs to be seated. */ _=' ' /*_ is used for indenting the output. */ do a=1 for pegs; if ?('A') then iterate do b=1 for pegs; if ?('B') then iterate @@ -42,7 +42,7 @@ _=' ' /*_ is used for indenting the end /*b*/ end /*a*/ say /*display a blank line to the terminal.*/ -s=left('s',cnt\==1) /*handle the case of plurals (or not).*/ +s=left('s', cnt\==1) /*handle the case of plurals (or not).*/ say 'found ' cnt " solution"s'.' /*display the number of solutions found*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ diff --git a/Task/Solve-the-no-connection-puzzle/Zkl/solve-the-no-connection-puzzle.zkl b/Task/Solve-the-no-connection-puzzle/Zkl/solve-the-no-connection-puzzle.zkl new file mode 100644 index 0000000000..c861eb33ac --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Zkl/solve-the-no-connection-puzzle.zkl @@ -0,0 +1,27 @@ +const PegA=0, PegB=1, PegC=2, PegD=3, PegE=4, PegF=5, PegG=6, PegH=7; +connections:=T( + T(PegA, PegC), T(PegA, PegD), T(PegA, PegE), + T(PegB, PegD), T(PegB, PegE), T(PegB, PegF), + T(PegC, PegD), T(PegD, PegE), T(PegE, PegF), + T(PegG, PegC), T(PegG, PegD), T(PegG, PegE), + T(PegH, PegD), T(PegH, PegE), T(PegH, PegF) ); +CZ:=connections.len(); +#<<< // Use "raw" string in a "here doc" so \ isn't a quote char +board:= +0'$ A B + /|\ /|\ + / | X | \ + / |/ \| \ + C - D - E - F + \ |\ /| / + \ | X | / + \|/ \|/ + G H$; +#<<< // end "here doc" + +perm:=T(PegA,PegB,PegC,PegD,PegE,PegF,PegG,PegH); // Peg[8] +foreach p in (Utils.Helpers.permuteW(perm)){ // permutation iterator + if(connections.filter1('wrap([(a,b)]){ (p[a] - p[b]).abs()<=1 })) continue; + board.translate("ABCDEFGH",p.apply('+(1)).concat()).println(); + break; // comment out to see all 16 solutions +} diff --git a/Task/Sort-an-array-of-composite-structures/AppleScript/sort-an-array-of-composite-structures.applescript b/Task/Sort-an-array-of-composite-structures/AppleScript/sort-an-array-of-composite-structures.applescript new file mode 100644 index 0000000000..5c5c331422 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/AppleScript/sort-an-array-of-composite-structures.applescript @@ -0,0 +1,67 @@ +use framework "Foundation" + +-- SORTING COMPOSITE STRUCTURES (BY PRIMARY AND N-ARY KEYS) + +-- List of {strKey, blnAscending} pairs -> list of records -> sorted list of records +-- sortByComparing :: [(String, Bool)] -> [Records] -> [Records] +on sortByComparing(keyDirections, xs) + set ca to current application + + script recDict + on |λ|(x) + ca's NSDictionary's dictionaryWithDictionary:x + end |λ| + end script + set dcts to map(recDict, xs) + + script asDescriptor + on |λ|(kd) + set {k, d} to kd + ca's NSSortDescriptor's sortDescriptorWithKey:k ascending:d selector:dcts + end |λ| + end script + + ((ca's NSArray's arrayWithArray:dcts)'s ¬ + sortedArrayUsingDescriptors:map(asDescriptor, keyDirections)) as list +end sortByComparing + + +-- GENERIC FUNCTIONS --------------------------------------------------------- + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- TEST ---------------------------------------------------------------------- +set xs to [¬ + {city:"Shanghai ", pop:24.2}, ¬ + {city:"Karachi ", pop:23.5}, ¬ + {city:"Beijing ", pop:21.5}, ¬ + {city:"Sao Paulo ", pop:24.2}, ¬ + {city:"Dhaka ", pop:17.0}, ¬ + {city:"Delhi ", pop:16.8}, ¬ + {city:"Lagos ", pop:16.1}] + +-- Boolean true for ascending order, false for descending: + +sortByComparing([{"pop", false}, {"city", true}], xs) 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 56ba283676..deb8b1a7c8 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,21 +1,20 @@ -#import system. -#import system'routines. -#import extensions. +import system'routines. +import extensions. -#symbol program = +program = [ - #var elements := ( - KeyValue new &key:"Krypton" &object:83.798r, - KeyValue new &key:"Beryllium" &object:9.012182r, - KeyValue new &key:"Silicon" &object:28.0855r, - KeyValue new &key:"Cobalt" &object:58.933195r, - KeyValue new &key:"Selenium" &object:78.96r, - KeyValue new &key:"Germanium" &object:72.64r). + var elements := ( + KeyValue new key:"Krypton" value:83.798r, + KeyValue new key:"Beryllium" value:9.012182r, + KeyValue new key:"Silicon" value:28.0855r, + KeyValue new key:"Cobalt" value:58.933195r, + KeyValue new key:"Selenium" value:78.96r, + KeyValue new key:"Germanium" value:72.64r). - #var sorted := elements sort:(:former:later) [ former key < later key ]. + var sorted := elements sort(:former:later)( former key < later key ). - sorted run &each:element + sorted forEach(:element) [ - console writeLine:(element key):" - ":element. + console printLine(element key," - ",element). ]. ]. diff --git a/Task/Sort-an-array-of-composite-structures/FreeBASIC/sort-an-array-of-composite-structures.freebasic b/Task/Sort-an-array-of-composite-structures/FreeBASIC/sort-an-array-of-composite-structures.freebasic new file mode 100644 index 0000000000..5da196f8f6 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/FreeBASIC/sort-an-array-of-composite-structures.freebasic @@ -0,0 +1,53 @@ +' FB 1.05.0 Win64 + +Type Pair + As String name, value + Declare Constructor(name_ As String, value_ As String) + Declare Operator Cast() As String +End Type + +Constructor Pair(name_ As String, value_ As String) + name = name_ + value = value_ +End Constructor + +Operator Pair.Cast() As String + Return "[" + name + ", " + value + "]" +End Operator + +' selection sort, quick enough for sorting small number of pairs +Sub sortPairsByName(p() As Pair) + Dim As Integer i, j, m + For i = LBound(p) To UBound(p) - 1 + m = i + For j = i + 1 To UBound(p) + If p(j).name < p(m).name Then m = j + Next j + If m <> i Then Swap p(i), p(m) + Next i +End Sub + +Dim As Pair pairs(1 To 4) = _ +{ _ + Pair("grass", "green"), _ + Pair("snow", "white" ), _ + Pair("sky", "blue"), _ + Pair("cherry", "red") _ +} + +Print "Before sorting :" +For i As Integer = 1 To 4 + Print Tab(3); pairs(i) +Next + +sortPairsByName pairs() + +Print +Print "After sorting by name :" +For i As Integer = 1 To 4 + Print Tab(3); pairs(i) +Next + +Print +Print "Press any key to quit" +Sleep diff --git a/Task/Sort-an-array-of-composite-structures/Haskell/sort-an-array-of-composite-structures-1.hs b/Task/Sort-an-array-of-composite-structures/Haskell/sort-an-array-of-composite-structures-1.hs new file mode 100644 index 0000000000..9361ef7c5e --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Haskell/sort-an-array-of-composite-structures-1.hs @@ -0,0 +1,26 @@ +import Data.List +import Data.Function (on) + +data Person = + P String + Int + deriving (Eq) + +instance Show Person where + show (P name val) = "Person " ++ name ++ " with value " ++ show val + +instance Ord Person where + compare (P a _) (P b _) = compare a b + +pVal :: Person -> Int +pVal (P _ x) = x + +people :: [Person] +people = [P "Joe" 12, P "Bob" 8, P "Alice" 9, P "Harry" 2] + + +main :: IO () +main = do + mapM_ print $ sort people + putStrLn [] + mapM_ print $ sortBy (on compare pVal) people diff --git a/Task/Sort-an-array-of-composite-structures/Haskell/sort-an-array-of-composite-structures-2.hs b/Task/Sort-an-array-of-composite-structures/Haskell/sort-an-array-of-composite-structures-2.hs new file mode 100644 index 0000000000..33232b31d0 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Haskell/sort-an-array-of-composite-structures-2.hs @@ -0,0 +1,12 @@ +import Data.Ord (comparing) +import Data.List (sortBy) + +xs :: [(String, String, Int)] +xs = + zip3 + (words "Richard John Marvin Alan Maurice James") + (words "Hamming McCarthy Minskey Perlis Wilkes Wilkinson") + [1915, 1927, 1926, 1922, 1913, 1919] + +main :: IO () +main = mapM_ print $ sortBy (comparing (\(_, _, y) -> y)) xs diff --git a/Task/Sort-an-array-of-composite-structures/Haskell/sort-an-array-of-composite-structures.hs b/Task/Sort-an-array-of-composite-structures/Haskell/sort-an-array-of-composite-structures.hs deleted file mode 100644 index f5ff099847..0000000000 --- a/Task/Sort-an-array-of-composite-structures/Haskell/sort-an-array-of-composite-structures.hs +++ /dev/null @@ -1,11 +0,0 @@ -import List - -data Person = P String Int deriving Eq -instance Show Person where - show (P name val) = "Person "++name++" with value "++(show val) -instance Ord Person where - compare (P n1 _) (P n2 _) = compare n1 n2 - -people = [(P "Joe" 12), (P "Bob" 8), (P "Alice" 9), (P "Harry" 2)] -sortedPeople = sort people -sortedPeopleByVal = sortBy (\(P _ v1) (P _ v2)->compare v1 v2) people diff --git a/Task/Sort-an-array-of-composite-structures/JavaScript/sort-an-array-of-composite-structures.js b/Task/Sort-an-array-of-composite-structures/JavaScript/sort-an-array-of-composite-structures-1.js similarity index 100% rename from Task/Sort-an-array-of-composite-structures/JavaScript/sort-an-array-of-composite-structures.js rename to Task/Sort-an-array-of-composite-structures/JavaScript/sort-an-array-of-composite-structures-1.js diff --git a/Task/Sort-an-array-of-composite-structures/JavaScript/sort-an-array-of-composite-structures-2.js b/Task/Sort-an-array-of-composite-structures/JavaScript/sort-an-array-of-composite-structures-2.js new file mode 100644 index 0000000000..f9d5972990 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/JavaScript/sort-an-array-of-composite-structures-2.js @@ -0,0 +1,62 @@ +(() => { + 'use strict'; + + // GENERIC FUNCTIONS FOR COMPARISONS + + // compare :: a -> a -> Ordering + const compare = (a, b) => a < b ? -1 : (a > b ? 1 : 0); + + // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c + const on = (f, g) => (a, b) => f(g(a), g(b)); + + // flip :: (a -> b -> c) -> b -> a -> c + const flip = f => (a, b) => f.apply(null, [b, a]); + + // arrayCopy :: [a] -> [a] + const arrayCopy = (xs) => xs.slice(0); + + // show :: a -> String + const show = x => JSON.stringify(x, null, 2); + + + // TEST + const xs = [{ + name: 'Shanghai', + pop: 24.2 + }, { + name: 'Karachi', + pop: 23.5 + }, { + name: 'Beijing', + pop: 21.5 + }, { + name: 'Sao Paulo', + pop: 24.2 + }, { + name: 'Dhaka', + pop: 17.0 + }, { + name: 'Delhi', + pop: 16.8 + }, { + name: 'Lagos', + pop: 16.1 + }] + + // population :: Dictionary -> Num + const population = x => x.pop; + + // name :: Dictionary -> String + const name = x => x.name; + + return show({ + byPopulation: arrayCopy(xs) + .sort(on(compare, population)), + byDescendingPopulation: arrayCopy(xs) + .sort(on(flip(compare), population)), + byName: arrayCopy(xs) + .sort(on(compare, name)), + byDescendingName: arrayCopy(xs) + .sort(on(flip(compare), name)) + }); +})(); diff --git a/Task/Sort-an-array-of-composite-structures/jq/sort-an-array-of-composite-structures-1.jq b/Task/Sort-an-array-of-composite-structures/Jq/sort-an-array-of-composite-structures-1.jq similarity index 100% rename from Task/Sort-an-array-of-composite-structures/jq/sort-an-array-of-composite-structures-1.jq rename to Task/Sort-an-array-of-composite-structures/Jq/sort-an-array-of-composite-structures-1.jq diff --git a/Task/Sort-an-array-of-composite-structures/jq/sort-an-array-of-composite-structures-2.jq b/Task/Sort-an-array-of-composite-structures/Jq/sort-an-array-of-composite-structures-2.jq similarity index 100% rename from Task/Sort-an-array-of-composite-structures/jq/sort-an-array-of-composite-structures-2.jq rename to Task/Sort-an-array-of-composite-structures/Jq/sort-an-array-of-composite-structures-2.jq diff --git a/Task/Sort-an-array-of-composite-structures/jq/sort-an-array-of-composite-structures-3.jq b/Task/Sort-an-array-of-composite-structures/Jq/sort-an-array-of-composite-structures-3.jq similarity index 100% rename from Task/Sort-an-array-of-composite-structures/jq/sort-an-array-of-composite-structures-3.jq rename to Task/Sort-an-array-of-composite-structures/Jq/sort-an-array-of-composite-structures-3.jq diff --git a/Task/Sort-an-array-of-composite-structures/jq/sort-an-array-of-composite-structures-4.jq b/Task/Sort-an-array-of-composite-structures/Jq/sort-an-array-of-composite-structures-4.jq similarity index 100% rename from Task/Sort-an-array-of-composite-structures/jq/sort-an-array-of-composite-structures-4.jq rename to Task/Sort-an-array-of-composite-structures/Jq/sort-an-array-of-composite-structures-4.jq 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.kotlin new file mode 100644 index 0000000000..b660709da9 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Kotlin/sort-an-array-of-composite-structures.kotlin @@ -0,0 +1,18 @@ +// version 1.1 + +data class Employee(val name: String, var category: String) : Comparable { + override fun compareTo(other: Employee) = this.name.compareTo(other.name) +} + +fun main(args: Array) { + val employees = arrayOf( + Employee("David", "Manager"), + Employee("Alice", "Sales"), + Employee("Joanna", "Director"), + Employee("Henry", "Admin"), + Employee("Tim", "Sales"), + Employee("Juan", "Admin") + ) + employees.sort() + for ((name, category) in employees) println("${name.padEnd(6)} : $category") +} diff --git a/Task/Sort-an-array-of-composite-structures/OoRexx/sort-an-array-of-composite-structures.rexx b/Task/Sort-an-array-of-composite-structures/OoRexx/sort-an-array-of-composite-structures.rexx new file mode 100644 index 0000000000..5448174963 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/OoRexx/sort-an-array-of-composite-structures.rexx @@ -0,0 +1,55 @@ +a = .array~new + +a~append(.pair~new("06-07", "Ducks")) +a~append(.pair~new("00-01", "Avalanche")) +a~append(.pair~new("02-03", "Devils")) +a~append(.pair~new("01-02", "Red Wings")) +a~append(.pair~new("03-04", "Lightning")) +a~append(.pair~new("04-05", "lockout")) +a~append(.pair~new("05-06", "Hurricanes")) +a~append(.pair~new("99-00", "Devils")) +a~append(.pair~new("07-08", "Red Wings")) +a~append(.pair~new("08-09", "Penguins")) + +b = a~copy -- make a copy before sorting +b~sort +say "Sorted using direct comparison" +do pair over b + say pair +end + +c = a~copy +-- this uses a custom comparator instead +c~sortWith(.paircomparator~new) +say +say "Sorted using a comparator (inverted)" +do pair over c + say pair +end + +-- a name/value mapping class that directly support the sort comparisons +::class pair inherit comparable +::method init + expose name value + use strict arg name, value + +::attribute name +::attribute value + +::method string + expose name value + return name "=" value + +-- the compareto method is a requirement brought in +-- by the +::method compareto + expose name + use strict arg other + return name~compareto(other~name) + +-- a comparator that shows an alternate way of sorting +::class pairComparator subclass comparator +::method compare + use strict arg left, right + -- perform the comparison on the names + return -left~name~compareTo(right~name) diff --git a/Task/Sort-an-array-of-composite-structures/Simula/sort-an-array-of-composite-structures.simula b/Task/Sort-an-array-of-composite-structures/Simula/sort-an-array-of-composite-structures.simula new file mode 100644 index 0000000000..77a075b287 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Simula/sort-an-array-of-composite-structures.simula @@ -0,0 +1,69 @@ +BEGIN + + CLASS COMPARABLE;; + + COMPARABLE CLASS PAIR(N,V); TEXT N,V;; + + CLASS COMPARATOR; + VIRTUAL: + PROCEDURE COMPARE IS + INTEGER PROCEDURE COMPARE(A, B); REF(COMPARABLE) A, B;; + BEGIN + END**OF**COMPARATOR; + + COMPARATOR CLASS PAIRBYNAME; + BEGIN + INTEGER PROCEDURE COMPARE(A, B); REF(COMPARABLE) A, B; + BEGIN + COMPARE := IF A QUA PAIR.N < B QUA PAIR.N THEN -1 ELSE + IF A QUA PAIR.N > B QUA PAIR.N THEN +1 ELSE 0; + END; + END**OF**PAIRBYNAME; + + PROCEDURE BUBBLESORT(A, C); NAME A; REF(COMPARABLE) ARRAY A; REF(COMPARATOR) C; + BEGIN + INTEGER LOW, HIGH, I; + BOOLEAN SWAPPED; + + PROCEDURE SWAP(I, J); INTEGER I, J; + BEGIN + REF(COMPARABLE) TEMP; + TEMP :- A(I); A(I) :- A(J); A(J) :- TEMP; + END**OF**SWAP; + + LOW := LOWERBOUND(A, 1); + HIGH := UPPERBOUND(A, 1); + SWAPPED := TRUE; + WHILE SWAPPED DO + BEGIN + SWAPPED := FALSE; + FOR I := LOW + 1 STEP 1 UNTIL HIGH DO + BEGIN + COMMENT IF THIS PAIR IS OUT OF ORDER ; + IF C.COMPARE(A(I - 1), A(I)) > 0 THEN + BEGIN + COMMENT SWAP THEM AND REMEMBER SOMETHING CHANGED ; + SWAP(I - 1, I); + SWAPPED := TRUE; + END; + END; + END; + END**OF**BUBBLESORT; + + COMMENT ** MAIN PROGRAM **; + REF(PAIR) ARRAY A(1:5); + INTEGER I; + + A(1) :- NEW PAIR( "JOE", "5531" ); + A(2) :- NEW PAIR( "ADAM", "2341" ); + A(3) :- NEW PAIR( "BERNIE", "122" ); + A(4) :- NEW PAIR( "WALTER", "1234" ); + A(5) :- NEW PAIR( "DAVID", "19" ); + + BUBBLESORT(A, NEW PAIRBYNAME); + + FOR I:= 1 STEP 1 UNTIL 5 DO + BEGIN OUTTEXT(A(I).N); OUTCHAR(' '); OUTTEXT(A(I).V); OUTIMAGE; END; + OUTIMAGE; + +END. diff --git a/Task/Sort-an-array-of-composite-structures/Zkl/sort-an-array-of-composite-structures.zkl b/Task/Sort-an-array-of-composite-structures/Zkl/sort-an-array-of-composite-structures.zkl new file mode 100644 index 0000000000..967e99a773 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Zkl/sort-an-array-of-composite-structures.zkl @@ -0,0 +1,8 @@ +class P{var name,value; + fcn init(nm,val){name,value=vm.arglist} + fcn __opLT(p){nameL("chris","fred","sam") diff --git a/Task/Sort-an-integer-array/AppleScript/sort-an-integer-array.applescript b/Task/Sort-an-integer-array/AppleScript/sort-an-integer-array.applescript index 22405d5116..056003864c 100644 --- a/Task/Sort-an-integer-array/AppleScript/sort-an-integer-array.applescript +++ b/Task/Sort-an-integer-array/AppleScript/sort-an-integer-array.applescript @@ -1,34 +1,43 @@ use framework "Foundation" -use scripting additions -on sort:lst - tell current application - return ((its (NSArray's arrayWithArray:lst))'s ¬ - sortedArrayUsingDescriptors:{its (NSSortDescriptor's ¬ - sortDescriptorWithKey:"self" ascending:true selector:"compare:")}) as list - end tell -end sort: +-- sort :: [a] -> [a] +on sort(lst) + ((current application's NSArray's arrayWithArray:lst)'s ¬ + sortedArrayUsingSelector:"compare:") as list +end sort +-- TEST ----------------------------------------------------------------------- on run - map(sort_, [[9, 1, 8, 2, 8, 3, 7, 0, 4, 6, 5], ¬ - ["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu"]]) + map(sort, [[9, 1, 8, 2, 8, 3, 7, 0, 4, 6, 5], ¬ + ["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", ¬ + "theta", "iota", "kappa", "lambda", "mu"]]) end run --- GENERIC FUNCTION FOR THE TEST +-- GENERIC FUNCTIONS --------------------------------------------------------- -- map :: (a -> b) -> [a] -> [b] on map(f, xs) - script mf - property lambda : f - end script - - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to mf's lambda(item i of xs, i, xs) - end repeat - return lst + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn diff --git a/Task/Sort-an-integer-array/BaCon/sort-an-integer-array.bacon b/Task/Sort-an-integer-array/BaCon/sort-an-integer-array.bacon new file mode 100644 index 0000000000..4f8e054b1a --- /dev/null +++ b/Task/Sort-an-integer-array/BaCon/sort-an-integer-array.bacon @@ -0,0 +1,14 @@ +' Sort an integer array +DECLARE values[5] TYPE NUMBER +values[0] = 23 +values[1] = 32 +values[2] = 12 +values[3] = 21 +values[4] = 01 + +SORT values + +FOR i = 0 TO 3 + PRINT values[i], ", "; +NEXT +PRINT values[4] 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 8e480bea0c..42a35e8f6f 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,12 +1,9 @@ -#import system. -#import system'routines. -#import extensions. +import system'routines. +import extensions. -#symbol program = +program = [ - #var unsorted := (6, 2, 7, 8, 3, 1, 10, 5, 4, 9). + var unsorted := (6, 2, 7, 8, 3, 1, 10, 5, 4, 9). - unsorted sort:ifOrdered. - - console writeLine:unsorted. + console printLine(unsorted clone; sort:ifOrdered). ]. diff --git a/Task/Sort-an-integer-array/Gambas/sort-an-integer-array.gambas b/Task/Sort-an-integer-array/Gambas/sort-an-integer-array.gambas new file mode 100644 index 0000000000..f3571136f1 --- /dev/null +++ b/Task/Sort-an-integer-array/Gambas/sort-an-integer-array.gambas @@ -0,0 +1,12 @@ +Public Sub Main() +Dim iArray As Integer[] = [8, 2, 5, 9, 1, 3, 6, 7, 4] +Dim iTemp As Integer +Dim sOutput As String + +For Each iTemp In iArray.Sort() + sOutput &= iTemp & ", " +Next + +Print Left(sOutput, -2) + +End diff --git a/Task/Sort-an-integer-array/jq/sort-an-integer-array.jq b/Task/Sort-an-integer-array/Jq/sort-an-integer-array.jq similarity index 100% rename from Task/Sort-an-integer-array/jq/sort-an-integer-array.jq rename to Task/Sort-an-integer-array/Jq/sort-an-integer-array.jq 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.kotlin new file mode 100644 index 0000000000..48c71090eb --- /dev/null +++ b/Task/Sort-an-integer-array/Kotlin/sort-an-integer-array.kotlin @@ -0,0 +1,7 @@ +// version 1.0.6 + +fun main(args: Array) { + val ints = intArrayOf(6, 2, 7, 8, 3, 1, 10, 5, 4, 9) + ints.sort() + println(ints.joinToString(prefix = "[", postfix = "]")) +} diff --git a/Task/Sort-an-integer-array/Nimrod/sort-an-integer-array.nimrod b/Task/Sort-an-integer-array/Nimrod/sort-an-integer-array.nimrod deleted file mode 100644 index e02f5e0991..0000000000 --- a/Task/Sort-an-integer-array/Nimrod/sort-an-integer-array.nimrod +++ /dev/null @@ -1,6 +0,0 @@ -import algorithm - -var a: array[0..8,int] = [2,3,5,8,4,1,6,9,7] -a.sort(system.cmp[int], Ascending) -for x in a: - echo(x) diff --git a/Task/Sort-an-integer-array/OoRexx/sort-an-integer-array.rexx b/Task/Sort-an-integer-array/OoRexx/sort-an-integer-array.rexx new file mode 100644 index 0000000000..0f414a18fd --- /dev/null +++ b/Task/Sort-an-integer-array/OoRexx/sort-an-integer-array.rexx @@ -0,0 +1,3 @@ +a = .array~of(4, 1, 6, -2, 99, -12) +say "The sorted numbers are" +say a~sortWith(.numericComparator~new)~makeString diff --git a/Task/Sort-an-integer-array/Perl-6/sort-an-integer-array-3.pl6 b/Task/Sort-an-integer-array/Perl-6/sort-an-integer-array-3.pl6 deleted file mode 100644 index f748a59c49..0000000000 --- a/Task/Sort-an-integer-array/Perl-6/sort-an-integer-array-3.pl6 +++ /dev/null @@ -1 +0,0 @@ -@a .= sort; diff --git a/Task/Sort-an-integer-array/Protium/sort-an-integer-array-1.protium b/Task/Sort-an-integer-array/Protium/sort-an-integer-array-1.protium deleted file mode 100644 index ac9f23823e..0000000000 --- a/Task/Sort-an-integer-array/Protium/sort-an-integer-array-1.protium +++ /dev/null @@ -1,15 +0,0 @@ -Construct a list of numbers -<@ LETCNSLSTLIT>L|65^84^1^25^77^4^47^2^42^44^41^25^69^3^51^45^4^39^ -Numbers sort as strings -<@ ACTSRTENTLST>L -<@ SAYDMPLST>L -<@ ACTSRTENTLSTLIT>L|__StringDescending -<@ SAYDMPLST>L - -Construct another list of numbers -<@ LETCNSLSTLIT>list|65^84^1^25^77^4^47^2^42^44^41^25^69^3^51^45^4^39^ -Numbers sorted as numbers -<@ ACTSRTENTLSTLIT>list|__Numeric -<@ SAYDMPLST>list -<@ ACTSRTENTLSTLIT>list|__NumericDescending -<@ SAYDMPLST>list diff --git a/Task/Sort-an-integer-array/Protium/sort-an-integer-array-2.protium b/Task/Sort-an-integer-array/Protium/sort-an-integer-array-2.protium deleted file mode 100644 index 84d8078bc9..0000000000 --- a/Task/Sort-an-integer-array/Protium/sort-an-integer-array-2.protium +++ /dev/null @@ -1,15 +0,0 @@ -Construct a list of numbers - -Numbers sort as strings - -1^2^25^25^3^39^4^4^41^42^44^45^47^51^65^69^77^84^ - -84^77^69^65^51^47^45^44^42^41^4^4^39^3^25^25^2^1^ - -Construct another list of numbers - -Numbers sorted as numbers - -1^2^3^4^4^25^25^39^41^42^44^45^47^51^65^69^77^84^ - -84^77^69^65^51^47^45^44^42^41^39^25^25^4^4^3^2^1^ diff --git a/Task/Sort-an-integer-array/Scheme/sort-an-integer-array.ss b/Task/Sort-an-integer-array/Scheme/sort-an-integer-array-1.ss similarity index 100% rename from Task/Sort-an-integer-array/Scheme/sort-an-integer-array.ss rename to Task/Sort-an-integer-array/Scheme/sort-an-integer-array-1.ss 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.ss new file mode 100644 index 0000000000..e06057340d --- /dev/null +++ b/Task/Sort-an-integer-array/Scheme/sort-an-integer-array-2.ss @@ -0,0 +1,6 @@ +> (import (srfi 132)) +> (list-sort < '(9 -2 1 2 8 0 1 2)) +(-2 0 1 1 2 2 8 9) + +> (vector-sort < #(9 -2 1 2 8 0 1 2)) +#(-2 0 1 1 2 2 8 9) 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.ss new file mode 100644 index 0000000000..558e09c4b1 --- /dev/null +++ b/Task/Sort-an-integer-array/Scheme/sort-an-integer-array-3.ss @@ -0,0 +1,5 @@ +> (import (srfi 95)) +> (sort '(9 -2 1 2 8 0 1 2) <) +(-2 0 1 1 2 2 8 9) +> (sort #(9 -2 1 2 8 0 1 2) <) +#(-2 0 1 1 2 2 8 9) diff --git a/Task/Sort-an-integer-array/Stata/sort-an-integer-array.stata b/Task/Sort-an-integer-array/Stata/sort-an-integer-array.stata new file mode 100644 index 0000000000..dc1d830941 --- /dev/null +++ b/Task/Sort-an-integer-array/Stata/sort-an-integer-array.stata @@ -0,0 +1,17 @@ +mata +: a=2\9\4\7\5\3\6\1\8 + +: sort(a,1) + 1 + +-----+ + 1 | 1 | + 2 | 2 | + 3 | 3 | + 4 | 4 | + 5 | 5 | + 6 | 6 | + 7 | 7 | + 8 | 8 | + 9 | 9 | + +-----+ +end diff --git a/Task/Sort-an-integer-array/Zkl/sort-an-integer-array-1.zkl b/Task/Sort-an-integer-array/Zkl/sort-an-integer-array-1.zkl new file mode 100644 index 0000000000..be2b901c93 --- /dev/null +++ b/Task/Sort-an-integer-array/Zkl/sort-an-integer-array-1.zkl @@ -0,0 +1 @@ +a:=L(4,5,2,6); a.sort(); a.println() //--> L(2,4,5,6) diff --git a/Task/Sort-an-integer-array/Zkl/sort-an-integer-array-2.zkl b/Task/Sort-an-integer-array/Zkl/sort-an-integer-array-2.zkl new file mode 100644 index 0000000000..df88698577 --- /dev/null +++ b/Task/Sort-an-integer-array/Zkl/sort-an-integer-array-2.zkl @@ -0,0 +1,3 @@ +a:=T(4,5,2,6); b:=a.sort(); +b.println(); //--> L(2,4,5,6) +a.println(); //--> L(4,5,2,6) diff --git a/Task/Sort-disjoint-sublist/AppleScript/sort-disjoint-sublist-1.applescript b/Task/Sort-disjoint-sublist/AppleScript/sort-disjoint-sublist-1.applescript index 9740101c59..9c54427061 100644 --- a/Task/Sort-disjoint-sublist/AppleScript/sort-disjoint-sublist-1.applescript +++ b/Task/Sort-disjoint-sublist/AppleScript/sort-disjoint-sublist-1.applescript @@ -1,5 +1,7 @@ use framework "Foundation" -- for basic NSArray sort +-- DISJOINT SORT ------------------------------------------------------------- + -- disjointSort :: [a] -> [Int] -> [a] on disjointSort(xs, indices) @@ -8,9 +10,9 @@ on disjointSort(xs, indices) -- valueByIndex :: Int -> a script valueByIndex - on lambda(i) + on |λ|(i) item i of xs - end lambda + end |λ| end script set subsetSorted to ¬ @@ -18,14 +20,14 @@ on disjointSort(xs, indices) -- staticOrSorted :: a -> Int -> a script staticOrSorted - on lambda(x, i) + on |λ|(x, i) set iIndex to elemIndex(i, indicesSorted) if iIndex is missing value then x else item iIndex of subsetSorted end if - end lambda + end |λ| end script -- Sorted subset re-stitched into unsorted remainder of list @@ -33,9 +35,7 @@ on disjointSort(xs, indices) end disjointSort - ---TEST - +-- TEST ---------------------------------------------------------------------- on run -- The indexing of AppleScript lists is 1-based -- so we use {7,2,8} in place of {6,1,7} @@ -43,15 +43,7 @@ on run disjointSort({7, 6, 5, 4, 3, 2, 1, 0}, {7, 2, 8}) end run - - --- GENERIC FUNCTIONS - --- sort :: [a] -> [a] -on sort(lst) - ((current application's NSArray's arrayWithArray:lst)'s ¬ - sortedArrayUsingSelector:"compare:") as list -end sort +-- GENERIC FUNCTIONS --------------------------------------------------------- -- elemIndex :: a -> [a] -> Maybe Int on elemIndex(x, xs) @@ -68,7 +60,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -81,7 +73,13 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn + +-- sort :: [a] -> [a] +on sort(lst) + ((current application's NSArray's arrayWithArray:lst)'s ¬ + sortedArrayUsingSelector:"compare:") as list +end sort diff --git a/Task/Sort-disjoint-sublist/C-sharp/sort-disjoint-sublist.cs b/Task/Sort-disjoint-sublist/C-sharp/sort-disjoint-sublist.cs new file mode 100644 index 0000000000..9390d4f250 --- /dev/null +++ b/Task/Sort-disjoint-sublist/C-sharp/sort-disjoint-sublist.cs @@ -0,0 +1,29 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class Test +{ + public static void Main() + { + var list = new List{ 7, 6, 5, 4, 3, 2, 1, 0 }; + list.SortSublist(6, 1, 7); + Console.WriteLine(string.Join(", ", list)); + } +} + +public static class Extensions +{ + public static void SortSublist(this List list, params int[] indices) + where T : IComparable + { + var sublist = indices.OrderBy(i => i) + .Zip(indices.Select(i => list[i]).OrderBy(v => v), + (Index, Value) => new { Index, Value }); + + foreach (var entry in sublist) { + list[entry.Index] = entry.Value; + } + } + +} diff --git a/Task/Sort-disjoint-sublist/Haskell/sort-disjoint-sublist.hs b/Task/Sort-disjoint-sublist/Haskell/sort-disjoint-sublist-1.hs similarity index 100% rename from Task/Sort-disjoint-sublist/Haskell/sort-disjoint-sublist.hs rename to Task/Sort-disjoint-sublist/Haskell/sort-disjoint-sublist-1.hs diff --git a/Task/Sort-disjoint-sublist/Haskell/sort-disjoint-sublist-2.hs b/Task/Sort-disjoint-sublist/Haskell/sort-disjoint-sublist-2.hs new file mode 100644 index 0000000000..144fa98cae --- /dev/null +++ b/Task/Sort-disjoint-sublist/Haskell/sort-disjoint-sublist-2.hs @@ -0,0 +1,14 @@ +import Data.List (sort, elemIndex) + +disjointSort :: [Int] -> [Int] -> [Int] +disjointSort xs indices = + let indicesSorted = sort indices + subsetSorted = sort $ (xs !!) <$> indicesSorted + in (\(x, i) -> + case elemIndex i indicesSorted of + Nothing -> x + Just iIndex -> subsetSorted !! iIndex) <$> + zip xs [0 ..] + +main :: IO () +main = print $ disjointSort [7, 6, 5, 4, 3, 2, 1, 0] [6, 1, 7] diff --git a/Task/Sort-disjoint-sublist/JavaScript/sort-disjoint-sublist-3.js b/Task/Sort-disjoint-sublist/JavaScript/sort-disjoint-sublist-3.js new file mode 100644 index 0000000000..a023ddc870 --- /dev/null +++ b/Task/Sort-disjoint-sublist/JavaScript/sort-disjoint-sublist-3.js @@ -0,0 +1,23 @@ +(() => { + 'use strict'; + + // disjointSort :: [a] -> [Int] -> [a] + const disjointSort = (xs, indices) => { + + // Sequence of indices discarded + const indicesSorted = indices.sort(), + subsetSorted = indicesSorted + .map(i => xs[i]) + .sort(); + + return xs + .map((x, i) => { + const iIndex = indicesSorted.indexOf(i); + return iIndex !== -1 ? ( + subsetSorted[iIndex] + ) : x; + }); + }; + + return disjointSort([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7]); +})(); diff --git a/Task/Sort-disjoint-sublist/jq/sort-disjoint-sublist-1.jq b/Task/Sort-disjoint-sublist/Jq/sort-disjoint-sublist-1.jq similarity index 100% rename from Task/Sort-disjoint-sublist/jq/sort-disjoint-sublist-1.jq rename to Task/Sort-disjoint-sublist/Jq/sort-disjoint-sublist-1.jq diff --git a/Task/Sort-disjoint-sublist/jq/sort-disjoint-sublist-2.jq b/Task/Sort-disjoint-sublist/Jq/sort-disjoint-sublist-2.jq similarity index 100% rename from Task/Sort-disjoint-sublist/jq/sort-disjoint-sublist-2.jq rename to Task/Sort-disjoint-sublist/Jq/sort-disjoint-sublist-2.jq diff --git a/Task/Sort-disjoint-sublist/OoRexx/sort-disjoint-sublist.rexx b/Task/Sort-disjoint-sublist/OoRexx/sort-disjoint-sublist.rexx new file mode 100644 index 0000000000..df8918c9db --- /dev/null +++ b/Task/Sort-disjoint-sublist/OoRexx/sort-disjoint-sublist.rexx @@ -0,0 +1,37 @@ +data = .array~of(7, 6, 5, 4, 3, 2, 1, 0) +-- this could be a list, array, or queue as well because of polymorphism +-- also, ooRexx arrays are 1-based, so using the alternate index set for the +-- problem. +indexes = .set~of(7, 2, 8) +call disjointSorter data, indexes + +say "Sorted data is: ["data~toString("l", ", ")"]" + +::routine disjointSorter + use arg data, indexes + temp = .array~new(indexes~items) + -- we want to process these in a predictable order, so make an array + tempIndexes = indexes~makearray + -- we can't just assign things back in the same order. The expected + -- result requires the items be inserted back in first-to-last index + -- order, so we need to sort the index values too + tempIndexes~sortWith(.numberComparator~new) + do index over tempIndexes + temp~append(data[index]) + end + -- sort as numbers + temp~sortwith(.numberComparator~new) + + do i = 1 to tempIndexes~items + data[tempIndexes[i]] = temp[i] + end + +-- a custom comparator that sorts strings as numeric values rather than +-- strings +::class numberComparator subclass comparator +::method compare + use strict arg left, right + -- perform the comparison on the names. By subtracting + -- the two and returning the sign, we give the expected + -- results for the compares + return (left - right)~sign diff --git a/Task/Sort-disjoint-sublist/Zkl/sort-disjoint-sublist-1.zkl b/Task/Sort-disjoint-sublist/Zkl/sort-disjoint-sublist-1.zkl new file mode 100644 index 0000000000..66cd276c32 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Zkl/sort-disjoint-sublist-1.zkl @@ -0,0 +1,7 @@ +values :=T(7, 6, 5, 4, 3, 2, 1, 0); +indices:=T(6, 1, 7); + +indices.apply(values.get).sort() // a.get(0) == a[0] + .zip(indices.sort()) //-->(v,i) == L(L(0,1),L(1,6),L(6,7)) + .reduce(fcn(newList,[(v,i)]){ newList[i]=v; newList },values.copy()) + .println(); // new list diff --git a/Task/Sort-disjoint-sublist/Zkl/sort-disjoint-sublist-2.zkl b/Task/Sort-disjoint-sublist/Zkl/sort-disjoint-sublist-2.zkl new file mode 100644 index 0000000000..daa5d0172f --- /dev/null +++ b/Task/Sort-disjoint-sublist/Zkl/sort-disjoint-sublist-2.zkl @@ -0,0 +1,7 @@ +values :=L(7, 6, 5, 4, 3, 2, 1, 0); + +indices.apply(values.get).sort() // a.get(0) == a[0] + .zip(indices.sort()) //-->(v,i) == L(L(0,1),L(1,6),L(6,7)) + .apply2(fcn([(v,i)],list){ list[i]=v },values); + +values.println(); // modified list diff --git a/Task/Sort-stability/Jq/sort-stability.jq b/Task/Sort-stability/Jq/sort-stability.jq new file mode 100644 index 0000000000..ccc0fb258e --- /dev/null +++ b/Task/Sort-stability/Jq/sort-stability.jq @@ -0,0 +1,5 @@ +[["UK", "London"], + ["US", "New York"], + ["US", "Birmingham"], + ["UK", "Birmingham"]] +| sort_by(.[1]) diff --git a/Task/Sort-stability/OoRexx/sort-stability.rexx b/Task/Sort-stability/OoRexx/sort-stability.rexx new file mode 100644 index 0000000000..2d8958bdfc --- /dev/null +++ b/Task/Sort-stability/OoRexx/sort-stability.rexx @@ -0,0 +1,43 @@ +/* Rexx */ +Do + cities = .array~of('UK London', 'US New York', 'US Birmingham', 'UK Birmingham',) + + Say; Say 'Original table' + Call display cities + + Say; Say 'Unstable sort on city' + sorted = cities~copy + sorted~sortWith(.ColumnComparator~new(4, 20)) + Call display sorted + + Say; Say 'Stable sort on city' + sorted = cities~copy + sorted~stableSortWith(.ColumnComparator~new(4, 20)) + Call display sorted + + Say; Say 'Unstable sort on country' + sorted = cities~copy + sorted~sortWith(.ColumnComparator~new(1, 2)) + Call display sorted + + Say; Say 'Stable sort on country' + sorted = cities~copy + sorted~stableSortWith(.ColumnComparator~new(1, 2)) + Call display sorted + + Return +End +Exit + +display: Procedure +Do + Use arg CT + + Say '-'~copies(80) + Loop c_ over CT + Say c_ + End c_ + + Return +End +Exit diff --git a/Task/Sort-stability/Phix/sort-stability.phix b/Task/Sort-stability/Phix/sort-stability.phix new file mode 100644 index 0000000000..589e8e24b2 --- /dev/null +++ b/Task/Sort-stability/Phix/sort-stability.phix @@ -0,0 +1,25 @@ +sequence test = {{"UK","London"}, + {"US","New York"}, + {"US","Birmingham"}, + {"UK","Birmingham"}} + +--------------------- +-- probably stable -- +--------------------- +function cmp(object a, object b) + return compare(a[1],b[1]) +end function +test = custom_sort(routine_id("cmp"),test) +pp(test,{pp_Nest,1}) + +----------------------- +-- guaranteed stable -- +----------------------- +function tag_cmp(integer i, integer j) + return compare({test[i][1],i},{test[j][1],j}) +-- return compare(test[i][1],test[j][1]) +end function +sequence tags = custom_sort(routine_id("tag_cmp"),shuffle(tagset(4))) +for i=1 to length(tags) do + ?test[tags[i]] +end for diff --git a/Task/Sort-stability/Rust/sort-stability.rust b/Task/Sort-stability/Rust/sort-stability.rust new file mode 100644 index 0000000000..a1f2dd77b9 --- /dev/null +++ b/Task/Sort-stability/Rust/sort-stability.rust @@ -0,0 +1,28 @@ +fn main() { + let country_city = vec![("UK", "London"), + ("US", "New York"), + ("US", "Birmingham"), + ("UK", "Birmingham")]; + + let mut city_sorted = country_city.clone(); + city_sorted.sort_by_key(|k| k.1); + + let mut country_sorted = country_city.clone(); + country_sorted.sort_by_key(|k| k.0); + + + println!("Original:"); + for x in &country_city { + println!("{} {}", x.0, x.1); + } + + println!("\nWhen sorted by city:"); + for x in &city_sorted { + println!("{} {}", x.0, x.1); + } + + println!("\nWhen sorted by county:"); + for x in &country_sorted { + println!("{} {}", x.0, x.1); + } +} diff --git a/Task/Sort-stability/Zkl/sort-stability-1.zkl b/Task/Sort-stability/Zkl/sort-stability-1.zkl new file mode 100644 index 0000000000..a6f62da601 --- /dev/null +++ b/Task/Sort-stability/Zkl/sort-stability-1.zkl @@ -0,0 +1,2 @@ +fcn sortByColumn(list,col) + { list.sort('wrap(city1,city2){ city1[col]) of Unbounded_String; - - Strings : StringArrayType := (Null_Unbounded_String, - To_Unbounded_String("this"), - To_Unbounded_String("is"), - To_Unbounded_String("a"), - To_Unbounded_String("set"), - To_Unbounded_String("of"), - To_Unbounded_String("strings"), - To_Unbounded_String("to"), - To_Unbounded_String("sort"), - To_Unbounded_String("This"), - To_Unbounded_String("Is"), - To_Unbounded_String("A"), - To_Unbounded_String("Set"), - To_Unbounded_String("Of"), - To_Unbounded_String("Strings"), - To_Unbounded_String("To"), - To_Unbounded_String("Sort")); - - procedure Move (From, To : in Natural) is - - begin - Strings(To) := Strings(From); - end Move; - - function UpCase (Char : in Character) return Character is - Temp : Character; - begin - if Char >= 'a' and Char <= 'z' then - Temp := Character'Val(Character'Pos(Char) - - Character'Pos('a') - + Character'Pos('A')); - else - Temp := Char; - end if; - return Temp; - end UpCase; - - function Lt (Op1, Op2 : Natural) - return Boolean is - Temp, Len : Natural; - begin - Len := Length(Strings(Op1)); - Temp := Length(Strings(Op2)); - if Len < Temp then - return False; - elsif Len > Temp then - return True; - end if; - - declare - S1, S2 : String(1..Len); - begin - S1 := To_String(Strings(Op1)); - S2 := To_String(Strings(Op2)); - Put("Same size: "); - Put(S1); - Put(" "); - Put(S2); - Put(" "); - for I in S1'Range loop - Put(UpCase(S1(I))); - Put(UpCase(S2(I))); - if UpCase(S1(I)) = UpCase(S2(I)) then - null; - elsif UpCase(S1(I)) < UpCase(S2(I)) then - Put(" LT"); - New_Line; - return True; - else - return False; - end if; - end loop; - Put(" GTE"); - New_Line; - return False; - end; - end Lt; - - procedure Put (Arr : in StringArrayType) is - begin - for I in 1..Arr'Length-1 loop - Put(To_String(Arr(I))); - New_Line; - end loop; - end Put; - - package Heap is new Gnat.Heap_Sort_G(Move, - Lt); - use Heap; - - -begin - Put_Line("Unsorted list:"); - Put(Strings); - New_Line; - Sort(16); - New_Line; - Put_Line("Sorted list:"); - Put(Strings); -end Custom_Compare; diff --git a/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator-2.ada b/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator-2.ada deleted file mode 100644 index 99f5706d8e..0000000000 --- a/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator-2.ada +++ /dev/null @@ -1,35 +0,0 @@ -Unsorted list: -this -is -a -set -of -strings -to -sort -This -Is -A -Set -Of -Strings -To -Sort - -Sorted list: -strings -Strings -sort -Sort -this -This -Set -set -is -Is -Of -of -to -To -a -A diff --git a/Task/Sort-using-a-custom-comparator/AppleScript/sort-using-a-custom-comparator.applescript b/Task/Sort-using-a-custom-comparator/AppleScript/sort-using-a-custom-comparator.applescript new file mode 100644 index 0000000000..40823246bd --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/AppleScript/sort-using-a-custom-comparator.applescript @@ -0,0 +1,97 @@ +use framework "Foundation" + +-- SORTING LISTS OF ATOMIC (NON-RECORD) DATA WITH A CUSTOM SORT FUNCTION + +-- In sortBy, f is a function from () to a tuple of two parts: +-- 1. a function from any value to a record derived from (and containing) that value +-- The base value should be present in the record under the key 'value' +-- additional derivative keys (and optionally the 'value' key) should be included in 2: +-- 2. a list of (record key, boolean) tuples, in the order of sort comparison, +-- where the value *true* selects ascending order for the paired key +-- and the value *false* selects descending order for that key + +-- sortBy :: (() -> ((a -> Record), [(String, Bool)])) -> [a] -> [a] +on sortBy(f, xs) + set {fn, keyBools} to mReturn(f)'s |λ|() + script unWrap + on |λ|(x) + value of x + end |λ| + end script + map(unWrap, sortByComparing(keyBools, map(fn, xs))) +end sortBy + +-- SORTING APPLESCRIPT RECORDS BY PRIMARY AND N-ARY SORT KEYS + +-- sortByComparing :: [(String, Bool)] -> [Records] -> [Records] +on sortByComparing(keyDirections, xs) + set ca to current application + + script recDict + on |λ|(x) + ca's NSDictionary's dictionaryWithDictionary:x + end |λ| + end script + set dcts to map(recDict, xs) + + script asDescriptor + on |λ|(kd) + set {k, d} to kd + ca's NSSortDescriptor's sortDescriptorWithKey:k ascending:d selector:dcts + end |λ| + end script + + ((ca's NSArray's arrayWithArray:dcts)'s ¬ + sortedArrayUsingDescriptors:map(asDescriptor, keyDirections)) as list +end sortByComparing + + +-- GENERIC FUNCTIONS --------------------------------------------------------- +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + + +-- TEST ---------------------------------------------------------------------- +on run + set xs to ["Shanghai", "Karachi", "Beijing", "Sao Paulo", "Dhaka", "Delhi", "Lagos"] + + -- Custom comparator: + + -- Returns a lifting function and a sequence of {key, bool} pairs + + -- Strings in order of descending length, + -- and ascending lexicographic order + script lengthDownAZup + on |λ|() + script + on |λ|(x) + {value:x, n:length of x} + end |λ| + end script + {result, {{"n", false}, {"value", true}}} + end |λ| + end script + + sortBy(lengthDownAZup, xs) +end run diff --git a/Task/Sort-using-a-custom-comparator/Delphi/sort-using-a-custom-comparator.delphi b/Task/Sort-using-a-custom-comparator/Delphi/sort-using-a-custom-comparator.delphi index ba00b6d057..3b63cbbd03 100644 --- a/Task/Sort-using-a-custom-comparator/Delphi/sort-using-a-custom-comparator.delphi +++ b/Task/Sort-using-a-custom-comparator/Delphi/sort-using-a-custom-comparator.delphi @@ -12,6 +12,10 @@ begin TArray.Sort(lArray , TDelegatedComparer.Construct( function(const Left, Right: string): Integer begin - Result := Length(Right) - Length(Left); + //Returns ('Here', 'are', 'be', 'sample', 'some', 'sorted', 'strings', 'to') + //Result := CompareStr(Left, Right); + + //Returns ('are', 'be', 'Here', 'sample', 'some', 'sorted', 'strings', 'to') + Result := CompareText(Left, Right); end)); end. diff --git a/Task/Sort-using-a-custom-comparator/Haskell/sort-using-a-custom-comparator-1.hs b/Task/Sort-using-a-custom-comparator/Haskell/sort-using-a-custom-comparator-1.hs index 4b46448ce4..7e605f7a21 100644 --- a/Task/Sort-using-a-custom-comparator/Haskell/sort-using-a-custom-comparator-1.hs +++ b/Task/Sort-using-a-custom-comparator/Haskell/sort-using-a-custom-comparator-1.hs @@ -1,9 +1,26 @@ -import List -import Char +import Data.List (sortBy) +import Data.Function (on) +import Data.Char (toLower) -mycmp s1 s2 = case compare (length s2) (length s1) of - EQ -> compare (map toLower s1) (map toLower s2) - x -> x +lengthThenAZ :: String -> String -> Ordering +lengthThenAZ a b + | d == EQ = on compare (toLower <$>) a b + | otherwise = d + where + d = on compare length a b -strings = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"] -sorted = sortBy mycmp strings +descLengthThenAZ :: String -> String -> Ordering +descLengthThenAZ a b + | d == EQ = on compare (toLower <$>) a b + | otherwise = d + where + d = on (flip compare) length a b + +xs :: [String] +xs = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"] + +main :: IO () +main = + mapM_ + putStrLn + [unlines $ sortBy lengthThenAZ xs, unlines $ sortBy descLengthThenAZ xs] diff --git a/Task/Sort-using-a-custom-comparator/Haskell/sort-using-a-custom-comparator-2.hs b/Task/Sort-using-a-custom-comparator/Haskell/sort-using-a-custom-comparator-2.hs index bdd1e1e659..259f93bec4 100644 --- a/Task/Sort-using-a-custom-comparator/Haskell/sort-using-a-custom-comparator-2.hs +++ b/Task/Sort-using-a-custom-comparator/Haskell/sort-using-a-custom-comparator-2.hs @@ -1,3 +1,26 @@ +import Data.List (sortBy) +import Data.Char (toLower) +import Data.Ord (comparing) import Data.Monoid -mycmp s1 s2 = mappend (compare (length s2) (length s1)) - (compare (map toLower s1) (map toLower s2)) + +-- the Ordering instance of mappend is defined to yield +-- lexicographical ordering. +-- instance Monoid Ordering where +-- mempty = EQ +-- LT `mappend` _ = LT +-- EQ `mappend` y = y +-- GT `mappend` _ = GT + +xs :: [String] +xs = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"] + +lowerCase :: String -> String +lowerCase = (toLower <$>) + +main :: IO () +main = + mapM_ putStrLn $ + (unlines . flip sortBy xs) <$> + [ comparing length <> comparing lowerCase -- Ascending length + , flip (comparing length) <> comparing lowerCase -- Descending length + ] diff --git a/Task/Sort-using-a-custom-comparator/JavaScript/sort-using-a-custom-comparator.js b/Task/Sort-using-a-custom-comparator/JavaScript/sort-using-a-custom-comparator-1.js similarity index 100% rename from Task/Sort-using-a-custom-comparator/JavaScript/sort-using-a-custom-comparator.js rename to Task/Sort-using-a-custom-comparator/JavaScript/sort-using-a-custom-comparator-1.js diff --git a/Task/Sort-using-a-custom-comparator/JavaScript/sort-using-a-custom-comparator-2.js b/Task/Sort-using-a-custom-comparator/JavaScript/sort-using-a-custom-comparator-2.js new file mode 100644 index 0000000000..d2e7068a1e --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/JavaScript/sort-using-a-custom-comparator-2.js @@ -0,0 +1,121 @@ +(function () { + 'use strict'; + + // GENERIC FUNCTIONS FOR COMPARISONS + + // Ordering :: ( LT | EQ | GT ) | ( -1 | 0 | 1 ) + + // compare :: a -> a -> Ordering + var compare = function (a, b) { + return a < b ? -1 : a > b ? 1 : 0; + }; + + // mappendOrdering :: Ordering -> Ordering -> Ordering + var mappendOrdering = function (a, b) { + return a !== 0 ? a : b; + }; + + // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c + var on = function (f, g) { + return function (a, b) { + return f(g(a), g(b)); + }; + }; + + // flip :: (a -> b -> c) -> b -> a -> c + var flip = function (f) { + return function (a, b) { + return f.apply(null, [b, a]); + }; + }; + + // arrayCopy :: [a] -> [a] + var arrayCopy = function (xs) { + return xs.slice(0); + }; + + // show :: a -> String + var show = function (x) { + return JSON.stringify(x, null, 2); + }; + + // TEST + var xs = ['Shanghai', 'Karachi', 'Beijing', 'Sao Paulo', 'Dhaka', 'Delhi', 'Lagos']; + + var rs = [{ + name: 'Shanghai', + pop: 24.2 + }, { + name: 'Karachi', + pop: 23.5 + }, { + name: 'Beijing', + pop: 21.5 + }, { + name: 'Sao Paulo', + pop: 24.2 + }, { + name: 'Dhaka', + pop: 17.0 + }, { + name: 'Delhi', + pop: 16.8 + }, { + name: 'Lagos', + pop: 16.1 + }]; + + // population :: Dictionary -> Num + var population = function (x) { + return x.pop; + }; + + // length :: [a] -> Int + var length = function (xs) { + return xs.length; + }; + + // toLower :: String -> String + var toLower = function (s) { + return s.toLowerCase(); + }; + + // lengthThenAZ :: String -> String -> ( -1 | 0 | 1) + var lengthThenAZ = function (a, b) { + return mappendOrdering( + on(compare, length)(a, b), + on(compare, toLower)(a, b) + ); + }; + + // descLengthThenAZ :: String -> String -> ( -1 | 0 | 1) + var descLengthThenAZ = function (a, b) { + return mappendOrdering( + on(flip(compare), length)(a, b), + on(compare, toLower)(a, b) + ); + }; + + return show({ + default: arrayCopy(xs) + .sort(compare), + + descendingDefault: arrayCopy(xs) + .sort(flip(compare)), + + byLengthThenAZ: arrayCopy(xs) + .sort(lengthThenAZ), + + byDescendingLengthThenZA: arrayCopy(xs) + .sort(flip(lengthThenAZ)), + + byDescendingLengthThenAZ: arrayCopy(xs) + .sort(descLengthThenAZ), + + byPopulation: arrayCopy(rs) + .sort(on(compare, population)), + + byDescendingPopulation: arrayCopy(rs) + .sort(on(flip(compare), population)) + }); +})(); diff --git a/Task/Sort-using-a-custom-comparator/JavaScript/sort-using-a-custom-comparator-3.js b/Task/Sort-using-a-custom-comparator/JavaScript/sort-using-a-custom-comparator-3.js new file mode 100644 index 0000000000..4e6be4ffcf --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/JavaScript/sort-using-a-custom-comparator-3.js @@ -0,0 +1,97 @@ +(() => { + 'use strict'; + + // GENERIC FUNCTIONS FOR COMPARISONS + + // Ordering :: ( LT | EQ | GT ) | ( -1 | 0 | 1 ) + // compare :: a -> a -> Ordering + const compare = (a, b) => a < b ? -1 : (a > b ? 1 : 0); + + // mappendOrdering :: Ordering -> Ordering -> Ordering + const mappendOrdering = (a, b) => a !== 0 ? a : b; + + // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c + const on = (f, g) => (a, b) => f(g(a), g(b)); + + // flip :: (a -> b -> c) -> b -> a -> c + const flip = f => (a, b) => f.apply(null, [b, a]); + + // arrayCopy :: [a] -> [a] + const arrayCopy = (xs) => xs.slice(0); + + // show :: a -> String + const show = x => JSON.stringify(x, null, 2); + + + // TEST + const xs = ['Shanghai', 'Karachi', 'Beijing', 'Sao Paulo', 'Dhaka', 'Delhi', 'Lagos']; + + const rs = [{ + name: 'Shanghai', + pop: 24.2 + }, { + name: 'Karachi', + pop: 23.5 + }, { + name: 'Beijing', + pop: 21.5 + }, { + name: 'Sao Paulo', + pop: 24.2 + }, { + name: 'Dhaka', + pop: 17.0 + }, { + name: 'Delhi', + pop: 16.8 + }, { + name: 'Lagos', + pop: 16.1 + }] + + // population :: Dictionary -> Num + const population = x => x.pop; + + // length :: [a] -> Int + const length = xs => xs.length; + + // toLower :: String -> String + const toLower = s => s.toLowerCase(); + + // lengthThenAZ :: String -> String -> ( -1 | 0 | 1) + const lengthThenAZ = (a, b) => + mappendOrdering( + on(compare, length)(a, b), + on(compare, toLower)(a, b) + ); + + // descLengthThenAZ :: String -> String -> ( -1 | 0 | 1) + const descLengthThenAZ = (a, b) => + mappendOrdering( + on(flip(compare), length)(a, b), + on(compare, toLower)(a, b) + ); + + return show({ + default: arrayCopy(xs) + .sort(compare), + + descendingDefault: arrayCopy(xs) + .sort(flip(compare)), + + byLengthThenAZ: arrayCopy(xs) + .sort(lengthThenAZ), + + byDescendingLengthThenZA: arrayCopy(xs) + .sort(flip(lengthThenAZ)), + + byDescendingLengthThenAZ: arrayCopy(xs) + .sort(descLengthThenAZ), + + byPopulation: arrayCopy(rs) + .sort(on(compare, population)), + + byDescendingPopulation: arrayCopy(rs) + .sort(on(flip(compare), population)) + }); +})(); diff --git a/Task/Sort-using-a-custom-comparator/jq/sort-using-a-custom-comparator-1.jq b/Task/Sort-using-a-custom-comparator/Jq/sort-using-a-custom-comparator-1.jq similarity index 100% rename from Task/Sort-using-a-custom-comparator/jq/sort-using-a-custom-comparator-1.jq rename to Task/Sort-using-a-custom-comparator/Jq/sort-using-a-custom-comparator-1.jq diff --git a/Task/Sort-using-a-custom-comparator/jq/sort-using-a-custom-comparator-2.jq b/Task/Sort-using-a-custom-comparator/Jq/sort-using-a-custom-comparator-2.jq similarity index 100% rename from Task/Sort-using-a-custom-comparator/jq/sort-using-a-custom-comparator-2.jq rename to Task/Sort-using-a-custom-comparator/Jq/sort-using-a-custom-comparator-2.jq diff --git a/Task/Sort-using-a-custom-comparator/jq/sort-using-a-custom-comparator-3.jq b/Task/Sort-using-a-custom-comparator/Jq/sort-using-a-custom-comparator-3.jq similarity index 100% rename from Task/Sort-using-a-custom-comparator/jq/sort-using-a-custom-comparator-3.jq rename to Task/Sort-using-a-custom-comparator/Jq/sort-using-a-custom-comparator-3.jq diff --git a/Task/Sort-using-a-custom-comparator/Objeck/sort-using-a-custom-comparator.objeck b/Task/Sort-using-a-custom-comparator/Objeck/sort-using-a-custom-comparator.objeck new file mode 100644 index 0000000000..a851b5db5c --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Objeck/sort-using-a-custom-comparator.objeck @@ -0,0 +1,57 @@ +use Collection; + +class Test { + function : Main(args : String[]) ~ Nil { + v := CreateHolders(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]); + "unsorted: "->Print(); Show(v); + v->Sort(); + "sorted: "->Print(); Show(v); + } + + function : CreateHolders(strings : String[]) ~ CompareVector { + vector := CompareVector->New(); + each(i : strings) { + vector->AddBack(StringHolder->New(strings[i])); + }; + + return vector; + } + + function : Show(v : CompareVector) ~ Nil { + each(i : v) { + s := v->Get(i)->As(StringHolder); + s->ToString()->Print(); + if(i + 1 < v->Size()) { + ','->Print(); + }; + }; + '\n'->Print(); + } +} + +class StringHolder implements Compare { + @s : String; + + New(s : String) { + @s := s; + } + + method : public : Compare(c : Compare) ~ Int { + h := c->As(StringHolder); + r := h->ToString(); + size := r->Size() - @s->Size(); + if(size = 0) { + size := @s->ToUpper()->Compare(r->ToUpper()); + }; + + return size; + } + + method : public : HashID() ~ Int { + return @s->HashID(); + } + + method : public : ToString() ~ String { + return @s; + } +} diff --git a/Task/Sort-using-a-custom-comparator/OoRexx/sort-using-a-custom-comparator.rexx b/Task/Sort-using-a-custom-comparator/OoRexx/sort-using-a-custom-comparator.rexx new file mode 100644 index 0000000000..f58496077b --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/OoRexx/sort-using-a-custom-comparator.rexx @@ -0,0 +1,10 @@ +A=.array~of('The seven deadly sins','Pride','avarice','Wrath','envy','gluttony','sloth','Lust') +say 'Sorted in order of descending length, and in ascending lexicographic order' +say A~sortWith(.DescLengthAscLexical~new)~makeString + +::class DescLengthAscLexical mixinclass Comparator +::method compare +use strict arg left, right +if left~length==right~length + then return left~caselessCompareTo(right) + else return right~length-left~length diff --git a/Task/Sort-using-a-custom-comparator/Ring/sort-using-a-custom-comparator.ring b/Task/Sort-using-a-custom-comparator/Ring/sort-using-a-custom-comparator.ring new file mode 100644 index 0000000000..90653b5aeb --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Ring/sort-using-a-custom-comparator.ring @@ -0,0 +1,34 @@ +load "stdlib.ring" + +sList = newlist(8, 2) +aList = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"] +ind = len(aList) + +for n = 1 to ind + sList[n] [1] = aList[n] + sList[n] [2] = len(aList[n]) +next + +nList = sortFirstSecond(sList, 2) +oList = newlist(8, 2) +count = 0 + +for n = len(nList) to 1 step -1 + count = count + 1 + oList[count] [1] = nList[n] [1] + oList[count] [2] = nList[n] [2] +next + +for n = 1 to len(oList) - 1 + temp1 = oList[n] [1] + temp2 = oList[n+1] [1] + if (oList[n] [2] = oList[n+1] [2]) and (strcmp(temp1, temp2) > 0) + temp = oList[n] [1] + oList[n] [1] = oList[n+1] [1] + oList[n+1] [1] = temp + ok +next + +for n = 1 to len(oList) + see oList[n] [1] + nl +next diff --git a/Task/Sort-using-a-custom-comparator/Rust/sort-using-a-custom-comparator.rust b/Task/Sort-using-a-custom-comparator/Rust/sort-using-a-custom-comparator.rust new file mode 100644 index 0000000000..85336390e0 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Rust/sort-using-a-custom-comparator.rust @@ -0,0 +1,9 @@ +fn main() { + let mut words = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]; + words.sort_by(|l, r| if l.len() == r.len() { + l.cmp(&r) + } else { + r.len().cmp(&l.len()) + }); + println!("{:?}", words); +} diff --git a/Task/Sort-using-a-custom-comparator/Scheme/sort-using-a-custom-comparator-1.ss b/Task/Sort-using-a-custom-comparator/Scheme/sort-using-a-custom-comparator-1.ss index e210478a19..6aeb1fad96 100644 --- a/Task/Sort-using-a-custom-comparator/Scheme/sort-using-a-custom-comparator-1.ss +++ b/Task/Sort-using-a-custom-comparator/Scheme/sort-using-a-custom-comparator-1.ss @@ -1,5 +1,5 @@ (use srfi-13);;Syntax for module inclusion depends on implementation, -;;as does the presence of a sort function. +;;a sort function may be predefined, or available through srfi 95 (define (mypred? a b) (let ((len-a (string-length a)) (len-b (string-length b))) diff --git a/Task/Sort-using-a-custom-comparator/Zkl/sort-using-a-custom-comparator.zkl b/Task/Sort-using-a-custom-comparator/Zkl/sort-using-a-custom-comparator.zkl new file mode 100644 index 0000000000..435404ddec --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Zkl/sort-using-a-custom-comparator.zkl @@ -0,0 +1,6 @@ +s:=T("Cat","apple","Adam","zero","Xmas","quit","Level","add","Actor","base","butter"); +r:=s.sort(fcn(a,b){ + an,bn := a.len(),b.len(); + if(an==bn)(a.toLower() < b.toLower()) else (an > bn) + }); +r.pump(Console.println); diff --git a/Task/Sorting-algorithms-Bead-sort/00DESCRIPTION b/Task/Sorting-algorithms-Bead-sort/00DESCRIPTION index aa3b977b24..5419009f67 100644 --- a/Task/Sorting-algorithms-Bead-sort/00DESCRIPTION +++ b/Task/Sorting-algorithms-Bead-sort/00DESCRIPTION @@ -3,6 +3,8 @@ ;Task: Sort an array of positive integers using the [[wp:Bead_sort|Bead Sort Algorithm]]. +A   ''bead sort''   is also known as a   ''gravity sort''. + Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. diff --git a/Task/Sorting-algorithms-Bead-sort/jq/sorting-algorithms-bead-sort-1.jq b/Task/Sorting-algorithms-Bead-sort/Jq/sorting-algorithms-bead-sort-1.jq similarity index 100% rename from Task/Sorting-algorithms-Bead-sort/jq/sorting-algorithms-bead-sort-1.jq rename to Task/Sorting-algorithms-Bead-sort/Jq/sorting-algorithms-bead-sort-1.jq diff --git a/Task/Sorting-algorithms-Bead-sort/jq/sorting-algorithms-bead-sort-2.jq b/Task/Sorting-algorithms-Bead-sort/Jq/sorting-algorithms-bead-sort-2.jq similarity index 100% rename from Task/Sorting-algorithms-Bead-sort/jq/sorting-algorithms-bead-sort-2.jq rename to Task/Sorting-algorithms-Bead-sort/Jq/sorting-algorithms-bead-sort-2.jq diff --git a/Task/Sorting-algorithms-Bead-sort/jq/sorting-algorithms-bead-sort-3.jq b/Task/Sorting-algorithms-Bead-sort/Jq/sorting-algorithms-bead-sort-3.jq similarity index 100% rename from Task/Sorting-algorithms-Bead-sort/jq/sorting-algorithms-bead-sort-3.jq rename to Task/Sorting-algorithms-Bead-sort/Jq/sorting-algorithms-bead-sort-3.jq diff --git a/Task/Sorting-algorithms-Bead-sort/jq/sorting-algorithms-bead-sort-4.jq b/Task/Sorting-algorithms-Bead-sort/Jq/sorting-algorithms-bead-sort-4.jq similarity index 100% rename from Task/Sorting-algorithms-Bead-sort/jq/sorting-algorithms-bead-sort-4.jq rename to Task/Sorting-algorithms-Bead-sort/Jq/sorting-algorithms-bead-sort-4.jq diff --git a/Task/Sorting-algorithms-Bead-sort/jq/sorting-algorithms-bead-sort-5.jq b/Task/Sorting-algorithms-Bead-sort/Jq/sorting-algorithms-bead-sort-5.jq similarity index 100% rename from Task/Sorting-algorithms-Bead-sort/jq/sorting-algorithms-bead-sort-5.jq rename to Task/Sorting-algorithms-Bead-sort/Jq/sorting-algorithms-bead-sort-5.jq 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.kotlin new file mode 100644 index 0000000000..760bd3fd12 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Kotlin/sorting-algorithms-bead-sort.kotlin @@ -0,0 +1,36 @@ +// version 1.1.2 + +fun beadSort(a: IntArray) { + val n = a.size + if (n < 2) return + var max = a.max()!! + val beads = ByteArray(max * n) + /* mark the beads */ + for (i in 0 until n) + for (j in 0 until a[i]) + beads[i * max + j] = 1 + + for (j in 0 until max) { + /* count how many beads are on each post */ + var sum = 0 + for (i in 0 until n) { + sum += beads[i * max + j] + beads[i * max + j] = 0 + } + /* mark bottom sum beads */ + for (i in n - sum until n) beads[i * max + j] = 1 + } + + for (i in 0 until n) { + var j = 0 + while (j < max && beads[i * max + j] == 1.toByte()) j++ + a[i] = j + } +} + +fun main(args: Array) { + val a = intArrayOf(5, 3, 1, 7, 4, 1, 1, 20) + println("Before sorting : ${a.contentToString()}") + beadSort(a) + println("After sorting : ${a.contentToString()}") +} diff --git a/Task/Sorting-algorithms-Bead-sort/OoRexx/sorting-algorithms-bead-sort-1.rexx b/Task/Sorting-algorithms-Bead-sort/OoRexx/sorting-algorithms-bead-sort-1.rexx new file mode 100644 index 0000000000..c235d98a55 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/OoRexx/sorting-algorithms-bead-sort-1.rexx @@ -0,0 +1,47 @@ +in='10 -12 1 0 999 8 2 2 4 4' + Do i=1 To words(in) + z.i=word(in,i) + End + n=i-1 + init=0 + Call minmax + + beads.=0; + Do i=1 To words(in) + z=z.i + beads.z+=1 + End + j=0 + Do i=lo To hi + Do While beads.i>0 + j+=1 + s.j=i + beads.i-=1 + End; + End; + Call show ' Input:',z.,n + Call show 'Sorted:',s.,n + Exit + + minmax: + Do i=1 To n + If init=0 Then Do + init=1 + lo=z.i + hi=z.i + End + Else Do + lo=min(lo,z.i) + hi=max(hi,z.i) + End + End + Return + +show: Procedure Expose n + Use Arg txt,a. + ol=txtg> + Do i=1 To n + ol=ol format(a.i,3) + End + Say ol + Return diff --git a/Task/Sorting-algorithms-Bead-sort/OoRexx/sorting-algorithms-bead-sort-2.rexx b/Task/Sorting-algorithms-Bead-sort/OoRexx/sorting-algorithms-bead-sort-2.rexx new file mode 100644 index 0000000000..8349724e65 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/OoRexx/sorting-algorithms-bead-sort-2.rexx @@ -0,0 +1,82 @@ +/*REXX program sorts a list of integers using a bead sort. */ + + /*get some grassHopper numbers. */ +grasshopper=, +1 4 10 12 22 26 30 46 54 62 66 78 94 110 126 134 138 158 162 186 190 222 254 270 + + + + /*GreeenGrocer numbers are also called hexagonal pyramidal */ + /* numbers. */ +greengrocer=, +0 4 16 40 80 140 224 336 480 660 880 1144 1456 1820 2240 2720 3264 3876 4560 + + + /*get some Bernoulli numerator numbers. */ +bernN='1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617 0 43867 0 -174611 0 854513' + + + /*Psi is also called the Reduced Totient function, and */ + /* is also called Carmichale lambda, or LAMBDA function.*/ +psi=, +1 1 2 2 4 2 6 2 6 4 10 2 12 6 4 4 16 6 18 4 6 10 22 2 20 12 18 6 28 4 30 8 10 16 + + + +list=grasshopper greengrocer bernN psi /*combine the four lists into one*/ + + +call showL 'before sort',list /*show list before sorting. */ +!=beadSort(list) /*invoke the bead sort. */ +call showL ' after sort',! /*show after array elements*/ +exit + + +/*─────────────────────────────────beadSort@ subroutine────────────*/ +beadSort: procedure expose _. + parse arg z + !='' /*this'll be the sorted list*/ + low=999999999; high=-low /*define the low and high #s*/ + _.=0 /*define all beads to zero. */ + + + do j=1 until z=='' /*pick the meat off the bone*/ + parse var z x z + if \datatype(x,'Whole') then + do + say + say '*** error! ***' + say + say 'element' j "in list isn't numeric:" x + say + exit 13 + end + + x=x/1 /*normalize number, it could*/ + /*be: +4 007 5. 2e3 etc.*/ + _.x=_.x+1 /*indicate this bead has a #*/ + low=min(low,x) /*keep track of the lowest #*/ + high=max(high,x) /* " " " " highest#*/ + end j + + /*now, collect the beads and*/ + do m=low to high /*let them fall (to zero). */ + if _.m==0 then iterate /*No bead here? Keep looking*/ + do n=1 for _.m /*let the beads fall to 0. */ + !=! m /*add it to the sorted list.*/ + end n + end m + + return ! + + +/*─────────────────────────────────────SHOW@ subroutine────────────*/ +showL: + widthH=length(words(arg(2))) /*maximum width of the index*/ + + do j=1 for words(arg(2)) + say 'element' right(j,widthH) arg(1)":" right(word(arg(2),j),10) + end j + + say copies('─',80) /*show a separator line. */ + return diff --git a/Task/Sorting-algorithms-Bead-sort/REXX/sorting-algorithms-bead-sort.rexx b/Task/Sorting-algorithms-Bead-sort/REXX/sorting-algorithms-bead-sort.rexx index 43ff05770e..eb26e86d19 100644 --- a/Task/Sorting-algorithms-Bead-sort/REXX/sorting-algorithms-bead-sort.rexx +++ b/Task/Sorting-algorithms-Bead-sort/REXX/sorting-algorithms-bead-sort.rexx @@ -1,44 +1,31 @@ /*REXX program sorts a list of integers using the bead sort algorithm. */ -grasshopper=, /*define two dozen grasshopper numbers.*/ - 1 4 10 12 22 26 30 46 54 62 66 78 94 110 126 134 138 158 162 186 190 222 254 270 - - /*Green Grocer numbers are also called hexagonal pyramidal numbers.*/ + /* [↑] define two dozen grasshopper numbers. */ +gHopper= 1 4 10 12 22 26 30 46 54 62 66 78 94 110 126 134 138 158 162 186 190 222 254 270 + /* [↑] these are also called hexagonal pyramidal #s. */ greenGrocer= 0 4 16 40 80 140 224 336 480 660 880 1144 1456 1820 2240 2720 3264 3876 4560 - - /*define 23 Bernoulli numerator numbers*/ -bernN= '1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617 0 43867 0 -174611 0 854513' - - /*Psi is also called the Reduced Totient function, and is*/ -psi=, /*also called Carmichael lambda, or the LAMBDA function.*/ - 1 1 2 2 4 2 6 2 6 4 10 2 12 6 4 4 16 6 18 4 6 10 22 2 20 12 18 6 28 4 30 8 10 16 - -#= grasshopper greenGrocer bernN psi /*combine the four lists into one list.*/ -call show 'before sort', # /*display the list before sorting. */ -call show ' after sort', beadSort(#) /* " " " after " */ + /*define twenty-three Bernoulli numerator numbers. */ +bernN= '1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617 0 43867 0 -174611 0' + /* [↑] also called the Reduced Totient function, and is*/ + /*also called Carmichael lambda, or the LAMBDA function*/ +psi= 1 1 2 2 4 2 6 2 6 4 10 2 12 6 4 4 16 6 18 4 6 10 22 2 20 12 18 6 28 4 30 8 10 16 +y= gHopper greenGrocer bernN psi /*combine the four lists into one list.*/ +call show 'before sort', y /*display the list before sorting. */ +say copies('░', 75) /*show long separator line before sort.*/ +call show ' after sort', beadSort(y) /*display the list after sorting. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -beadSort: procedure; parse arg low . 1 high . 1 z,$ /*$: the list to be sorted. */ - @.=0 /*set all beads (@.) to zero.*/ - do j=1 until z==''; parse var z x z /*pick the meat off the bone.*/ - if \datatype(x, 'W') then do; say '***error***' - say 'element' j "in list isn't numeric:" x - say; exit 13 - end /* [↑] exit pgm with RC=13. */ - x=x/1 /*normalize: 4. 004 +4 .4e0 */ - @.x=@.x+1 /*indicate this bead has a #.*/ - low=min(low,x); high=max(high,x) /*track lowest and highest #.*/ - end /*j*/ +beadSort: procedure; parse arg low . 1 high . 1 z,$; @.=0 /*$: the list to be sorted. */ + do j=1 until z==''; parse var z x z /*pick the meat off the bone.*/ + x=x/1; @.x=@.x+1 /*normalize X; bump counter.*/ + low=min(low, x); high=max(high, x) /*track lowest and highest #.*/ + end /*j*/ /* [↓] now, collect beads and*/ - do m=low to high /*let them fall (to zero). */ - if @.m\==0 then do n=1 for @.m; $=$ m /*have we found a bead here? */ - end /*n*/ /* [↑] add it to sorted list*/ - end /*m*/ - + do m=low to high; do @.m; $=$ m; end /*let them fall (to zero). */ + end /*m*/ return $ /*──────────────────────────────────────────────────────────────────────────────────────*/ -show: parse arg txt,y; _=left('', 20) - w=length(words(y)); do k=1 for words(y) /* [↑] twenty pad blanks. */ - say _ 'element' right(k, w) txt":" right(word(y, k), 9) - end /*k*/ - say copies('─', 70) /*show a long separator line.*/ +show: parse arg txt,y; w=length( words(y) ) + do k=1 for words(y) /* [↑] twenty pad blanks. */ + say right('element',30) right(k,w) txt":" right(word(y,k),9) + end /*k*/ return diff --git a/Task/Sorting-algorithms-Bead-sort/Zkl/sorting-algorithms-bead-sort-1.zkl b/Task/Sorting-algorithms-Bead-sort/Zkl/sorting-algorithms-bead-sort-1.zkl new file mode 100644 index 0000000000..4879bbe244 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Zkl/sorting-algorithms-bead-sort-1.zkl @@ -0,0 +1,11 @@ +fcn columns(m){ // m is list of lists of zeros/beads, # beads is n, eg (0,0,0)==3 + m + .apply("len") // (0,0,0)-->3 + .reduce("max") // largest bead stack + .walker() // [0..max] + .apply('wrap(i){ m.filter('wrap(s){ s.len() > i }).len().pump(List,0) }); +} + +fcn beadSort(data){ + data.apply("pump",List,0):columns(_):columns(_).apply("len"); +} diff --git a/Task/Sorting-algorithms-Bead-sort/Zkl/sorting-algorithms-bead-sort-2.zkl b/Task/Sorting-algorithms-Bead-sort/Zkl/sorting-algorithms-bead-sort-2.zkl new file mode 100644 index 0000000000..ae38698aa5 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Zkl/sorting-algorithms-bead-sort-2.zkl @@ -0,0 +1,2 @@ +T(5,3,1,7,4,1,1):beadSort(_).println(); +T(4,3,3,2,1):beadSort(_).println(); diff --git a/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort-1.cpp b/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort-1.cpp deleted file mode 100644 index 6ebd033aa0..0000000000 --- a/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort-1.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include -#include - -template - void bogosort(ForwardIterator begin, ForwardIterator end) -{ - typedef std::iterator_traits::value_type value_type; - - // if we find two adjacent values where the first is greater than the second, the sequence isn't sorted. - while (std::adjacent_find(begin, end, std::greater()) != end) - std::random_shuffle(begin, end); -} diff --git a/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort-2.cpp b/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort-2.cpp deleted file mode 100644 index 009708b88a..0000000000 --- a/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort-2.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include -#include - -template - void bogosort(ForwardIterator begin, ForwardIterator end) -{ - while (!__gnu_cxx::is_sorted(begin, end)) - std::random_shuffle(begin, end); -} diff --git a/Task/Sorting-algorithms-Bogosort/Haskell/sorting-algorithms-bogosort.hs b/Task/Sorting-algorithms-Bogosort/Haskell/sorting-algorithms-bogosort.hs index ffcfd7539d..ff827591da 100644 --- a/Task/Sorting-algorithms-Bogosort/Haskell/sorting-algorithms-bogosort.hs +++ b/Task/Sorting-algorithms-Bogosort/Haskell/sorting-algorithms-bogosort.hs @@ -2,9 +2,10 @@ import System.Random import Data.Array.IO import Control.Monad -isSorted :: (Ord a) => [a] -> Bool -isSorted (e1:e2:r) = e1 <= e2 && isSorted (e2:r) -isSorted _ = True +isSortedBy :: (a -> a -> Bool) -> [a] -> Bool +isSortedBy _ [] = True +isSortedBy f xs = all (uncurry f) . (zip <*> tail) $ xs + -- from http://www.haskell.org/haskellwiki/Random_shuffle shuffle :: [a] -> IO [a] @@ -21,6 +22,9 @@ shuffle xs = do newArray :: Int -> [a] -> IO (IOArray Int a) newArray n xs = newListArray (1,n) xs -bogosort :: (Ord a) => [a] -> IO [a] -bogosort li | isSorted li = return li - | otherwise = shuffle li >>= bogosort +bogosortBy :: (a -> a -> Bool) -> [a] -> IO [a] +bogosortBy f xs | isSortedBy f xs = return xs + | otherwise = shuffle xs >>= bogosortBy f + +bogosort :: Ord a => [a] -> IO [a] +bogosort = bogosortBy (<) diff --git a/Task/Sorting-algorithms-Bogosort/Kotlin/sorting-algorithms-bogosort.kotlin b/Task/Sorting-algorithms-Bogosort/Kotlin/sorting-algorithms-bogosort.kotlin new file mode 100644 index 0000000000..09b07655be --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Kotlin/sorting-algorithms-bogosort.kotlin @@ -0,0 +1,36 @@ +// version 1.1.2 + +const val RAND_MAX = 32768 // big enough for this + +val rand = java.util.Random() + +fun isSorted(a: IntArray): Boolean { + val n = a.size + if (n < 2) return true + for (i in 1 until n) { + if (a[i] < a[i - 1]) return false + } + return true +} + +fun shuffle(a: IntArray) { + val n = a.size + if (n < 2) return + for (i in 0 until n) { + val t = a[i] + val r = rand.nextInt(RAND_MAX) % n + a[i] = a[r] + a[r] = t + } +} + +fun bogosort(a: IntArray) { + while (!isSorted(a)) shuffle(a) +} + +fun main(args: Array) { + val a = intArrayOf(1, 10, 9, 7, 3, 0) + println("Before sorting : ${a.contentToString()}") + bogosort(a) + println("After sorting : ${a.contentToString()}") +} diff --git a/Task/Sorting-algorithms-Bogosort/Rust/sorting-algorithms-bogosort.rust b/Task/Sorting-algorithms-Bogosort/Rust/sorting-algorithms-bogosort.rust index 7c58adea57..5007b89ccc 100644 --- a/Task/Sorting-algorithms-Bogosort/Rust/sorting-algorithms-bogosort.rust +++ b/Task/Sorting-algorithms-Bogosort/Rust/sorting-algorithms-bogosort.rust @@ -1,24 +1,27 @@ extern crate rand; +use rand::Rng; -use rand::{thread_rng, Rng}; -use std::vec::Vec; - -fn sorted(curlist: &Vec) -> bool { - let mut sortedlist = curlist.clone(); - sortedlist.sort(); - curlist.iter().eq(sortedlist.iter()) -} - -fn sort(curlist: &Vec) -> Vec { - let mut result = curlist.clone(); - while !sorted(&result) { - let mut rng = thread_rng(); - rng.shuffle(&mut result); +fn bogosort_by(order: F, coll: &mut [T]) + where F: Fn(&T, &T) -> bool +{ + let mut rng = rand::thread_rng(); + while !is_sorted(&order, coll) { + rng.shuffle(coll); } - result } +#[inline] +fn is_sorted_by(order: F, coll: &[T]) -> bool + where F: Fn(&T,&T) -> bool, +{ + coll[..].iter().zip(&coll[1..]).all(|(x,y)| order(x,y)) +} + + fn main() { - let mut testlist = vec![1,55,88,24,990876,312,67,0,854,13,4,7]; - println!("{:?}", sort(&mut testlist)) + let mut testlist = [1,55,88,24,990876,312,67,0,854,13,4,7]; + bogosort_by(|x,y| x < y, &mut testlist); + println!("{:?}", testlist) + bogosort_by(|x,y| x > y, &mut testlist); + println!("{:?}", testlist); } diff --git a/Task/Sorting-algorithms-Bogosort/Zkl/sorting-algorithms-bogosort.zkl b/Task/Sorting-algorithms-Bogosort/Zkl/sorting-algorithms-bogosort.zkl new file mode 100644 index 0000000000..5ba53e63d9 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Zkl/sorting-algorithms-bogosort.zkl @@ -0,0 +1,8 @@ +fcn increasing(list){ + list.len()<2 or + list.reduce(fcn(a,b){ if(b *(a e) | Array a e & < e -bsort array - # (done, array) = sweep 1 True array - = if done array (bsort array) -where - sweep :: !Int !Bool !*(a e) -> (!Bool, !*(a e)) | Array a e & < e - sweep i done array - | i >= size array = (done, array) - # (e1, array) = array![i - 1] - (e2, array) = array![i] - | e1 > e2 = sweep (i + 1) False {array & [i - 1] = e2, [i] = e1} - = sweep (i + 1) done array diff --git a/Task/Sorting-algorithms-Bubble-sort/Clean/sorting-algorithms-bubble-sort-2.clean b/Task/Sorting-algorithms-Bubble-sort/Clean/sorting-algorithms-bubble-sort-2.clean deleted file mode 100644 index d28e355c67..0000000000 --- a/Task/Sorting-algorithms-Bubble-sort/Clean/sorting-algorithms-bubble-sort-2.clean +++ /dev/null @@ -1,2 +0,0 @@ -Start :: {Int} -Start = bsort {x \\ x <- [100,99..1]} diff --git a/Task/Sorting-algorithms-Bubble-sort/Elena/sorting-algorithms-bubble-sort.elena b/Task/Sorting-algorithms-Bubble-sort/Elena/sorting-algorithms-bubble-sort.elena new file mode 100644 index 0000000000..21867f220a --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Elena/sorting-algorithms-bubble-sort.elena @@ -0,0 +1,34 @@ +import system'routines. +import extensions. + +extension $op +{ + bubbleSort + [ + var list := self clone. + + bool madeChanges := true. + int itemCount := list length. + while (madeChanges) + [ + madeChanges := false. + itemCount -= 1. + 0 till:itemCount do(:i) + [ + if (list[i] > list[i + 1]) + [ + list exchange(i,i+1). + madeChanges := true. + ] + ] + ]. + + ^ list + ] +} + +program = +[ + var list := (3, 7, 3, 2, 1, -4, 10, 12, 4). + console printLine(list bubbleSort). +]. diff --git a/Task/Sorting-algorithms-Bubble-sort/jq/sorting-algorithms-bubble-sort-1.jq b/Task/Sorting-algorithms-Bubble-sort/Jq/sorting-algorithms-bubble-sort-1.jq similarity index 100% rename from Task/Sorting-algorithms-Bubble-sort/jq/sorting-algorithms-bubble-sort-1.jq rename to Task/Sorting-algorithms-Bubble-sort/Jq/sorting-algorithms-bubble-sort-1.jq diff --git a/Task/Sorting-algorithms-Bubble-sort/jq/sorting-algorithms-bubble-sort-2.jq b/Task/Sorting-algorithms-Bubble-sort/Jq/sorting-algorithms-bubble-sort-2.jq similarity index 100% rename from Task/Sorting-algorithms-Bubble-sort/jq/sorting-algorithms-bubble-sort-2.jq rename to Task/Sorting-algorithms-Bubble-sort/Jq/sorting-algorithms-bubble-sort-2.jq diff --git a/Task/Sorting-algorithms-Bubble-sort/jq/sorting-algorithms-bubble-sort-3.jq b/Task/Sorting-algorithms-Bubble-sort/Jq/sorting-algorithms-bubble-sort-3.jq similarity index 100% rename from Task/Sorting-algorithms-Bubble-sort/jq/sorting-algorithms-bubble-sort-3.jq rename to Task/Sorting-algorithms-Bubble-sort/Jq/sorting-algorithms-bubble-sort-3.jq diff --git a/Task/Sorting-algorithms-Bubble-sort/Kotlin/sorting-algorithms-bubble-sort.kotlin b/Task/Sorting-algorithms-Bubble-sort/Kotlin/sorting-algorithms-bubble-sort.kotlin index 7b472a63fb..73bb1623ca 100644 --- a/Task/Sorting-algorithms-Bubble-sort/Kotlin/sorting-algorithms-bubble-sort.kotlin +++ b/Task/Sorting-algorithms-Bubble-sort/Kotlin/sorting-algorithms-bubble-sort.kotlin @@ -1,8 +1,10 @@ -fun bubbleSort(a : Array, c: Comparator) { - var changed : Boolean +import java.util.Comparator + +fun bubbleSort(a: Array, c: Comparator) { + var changed: Boolean do { changed = false - for (i in 0 .. a.size - 2) { + for (i in 0..a.size - 2) { if (c.compare(a[i], a[i + 1]) > 0) { val tmp = a[i] a[i] = a[i + 1] diff --git a/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort-1.m b/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort-1.m deleted file mode 100644 index 2598b65718..0000000000 --- a/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort-1.m +++ /dev/null @@ -1,20 +0,0 @@ -function list = bubbleSort(list) - - hasChanged = true; - itemCount = numel(list); - - while(hasChanged) - - hasChanged = false; - itemCount = itemCount - 1; - - for index = (1:itemCount) - - if(list(index) > list(index+1)) - list([index index+1]) = list([index+1 index]); %swap - hasChanged = true; - end %if - - end %for - end %while -end %bubbleSort diff --git a/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort-2.m b/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort-2.m deleted file mode 100644 index 63d5d587e9..0000000000 --- a/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort-2.m +++ /dev/null @@ -1,5 +0,0 @@ -bubbleSort([5 3 8 4 9 7 6 2 1]) - -ans = - - 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Bubble-sort/OoRexx/sorting-algorithms-bubble-sort-1.rexx b/Task/Sorting-algorithms-Bubble-sort/OoRexx/sorting-algorithms-bubble-sort-1.rexx new file mode 100644 index 0000000000..80e9c2b48d --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/OoRexx/sorting-algorithms-bubble-sort-1.rexx @@ -0,0 +1,61 @@ +/* Rexx */ +Do + placesList = sampleData() + call show placesList + say + sortedList = bubbleSort(placesList) + call show sortedList + say + + return +End +Exit + +-- ----------------------------------------------------------------------------- +bubbleSort: +procedure +Do + il = arg(1) + sl = il~copy + + listLen = sl~size + loop i_ = 1 to listLen + loop j_ = i_ + 1 to listLen + cmpi = sl[i_] + cmpj = sl[j_] + if cmpi > cmpj then do + sl[i_] = cmpj + sl[j_] = cmpi + end + end j_ + end i_ + return sl +End +Exit + +-- ----------------------------------------------------------------------------- +show: +procedure +Do + al = arg(1) + + loop e_ over al + say e_ + end e_ + + return +End +Exit + +-- ----------------------------------------------------------------------------- +sampleData: +procedure +Do + placesList = .array~of( , + "UK London", "US New York", "US Boston", "US Washington", , + "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" , + ) + + return placesList +End +Exit diff --git a/Task/Sorting-algorithms-Bubble-sort/OoRexx/sorting-algorithms-bubble-sort-2.rexx b/Task/Sorting-algorithms-Bubble-sort/OoRexx/sorting-algorithms-bubble-sort-2.rexx new file mode 100644 index 0000000000..4377f619eb --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/OoRexx/sorting-algorithms-bubble-sort-2.rexx @@ -0,0 +1,72 @@ +/* Rexx */ +Do + placesList = sampleData() + call show placesList + say + sortedList = bubbleSort(placesList) + call show sortedList + say + + return +End +Exit + +-- ----------------------------------------------------------------------------- +bubbleSort: +procedure +Do + il = arg(1) + sl = il~copy + itemCount = sl~size + + loop label c_ until \hasChanged + hasChanged = isFalse() + itemCount = itemCount - 1 + loop i_ = 1 to itemCount + if sl[i_] > sl[i_ + 1] then do + t_ = sl[i_] + sl[i_] = sl[i_ + 1] + sl[i_ + 1] = t_ + hasChanged = isTrue() + end + end i_ + end c_ + + return sl +End +Exit + +-- ----------------------------------------------------------------------------- +show: +procedure +Do + al = arg(1) + + loop e_ over al + say e_ + end e_ + + return +End +Exit + +-- ----------------------------------------------------------------------------- +sampleData: +procedure +Do + placesList = .array~of( , + "UK London", "US New York", "US Boston", "US Washington", , + "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" , + ) + + return placesList +End +Exit + +-- ----------------------------------------------------------------------------- +isTrue: procedure + return (1 == 1) + +-- ----------------------------------------------------------------------------- +isFalse: procedure + return \isTrue() diff --git a/Task/Sorting-algorithms-Bubble-sort/OoRexx/sorting-algorithms-bubble-sort-3.rexx b/Task/Sorting-algorithms-Bubble-sort/OoRexx/sorting-algorithms-bubble-sort-3.rexx new file mode 100644 index 0000000000..cce649fa26 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/OoRexx/sorting-algorithms-bubble-sort-3.rexx @@ -0,0 +1,61 @@ +/* Rexx */ +Do + placesList. = '' + sortedList. = '' + call sampleData + call bubbleSort + + do i_ = 1 to placesList.0 + say placesList.i_ + end i_ + say + + do i_ = 1 to sortedList.0 + say sortedList.i_ + end i_ + say + + return +End +Exit + +/* -------------------------------------------------------------------------- */ +bubbleSort: +procedure expose sortedList. placesList. +Do + /* Copy list */ + do !_ = 0 to placesList.0 + sortedList.!_ = placesList.!_ + end !_ + + listLen = sortedList.0 + do i_ = 1 to listLen + do j_ = i_ + 1 to listLen + if sortedList.i_ > sortedList.j_ then do + !_ = sortedList.j_ + sortedList.j_ = sortedList.i_ + sortedList.i_ = !_ + end + end j_ + end i_ + return +End +Exit + +/* -------------------------------------------------------------------------- */ +sampleData: +procedure expose placesList. +Do + ! = 0 + ! = ! + 1; placesList.0 = !; placesList.! = "UK London" + ! = ! + 1; placesList.0 = !; placesList.! = "US New York" + ! = ! + 1; placesList.0 = !; placesList.! = "US Boston" + ! = ! + 1; placesList.0 = !; placesList.! = "US Washington" + ! = ! + 1; placesList.0 = !; placesList.! = "UK Washington" + ! = ! + 1; placesList.0 = !; placesList.! = "US Birmingham" + ! = ! + 1; placesList.0 = !; placesList.! = "UK Birmingham" + ! = ! + 1; placesList.0 = !; placesList.! = "UK Boston" + + return +End +Exit diff --git a/Task/Sorting-algorithms-Bubble-sort/PHP/sorting-algorithms-bubble-sort.php b/Task/Sorting-algorithms-Bubble-sort/PHP/sorting-algorithms-bubble-sort.php index caafc1d218..948223b4df 100644 --- a/Task/Sorting-algorithms-Bubble-sort/PHP/sorting-algorithms-bubble-sort.php +++ b/Task/Sorting-algorithms-Bubble-sort/PHP/sorting-algorithms-bubble-sort.php @@ -10,4 +10,5 @@ function bubbleSort(array &$array) { } } } while ($swapped); + return $array; } diff --git a/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort-1.rexx b/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort-1.rexx new file mode 100644 index 0000000000..69a8bc7d1b --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort-1.rexx @@ -0,0 +1,31 @@ +/*REXX program sorts an array (of any kind of items) using the bubble─sort algorithm.*/ +call gen /*generate the array elements (items).*/ +call show 'before sort' /*show the before array elements. */ + say copies('▒', 70) /*show a separator line (before/after).*/ +call bSort # /*invoke the bubble sort with # items.*/ +call show ' after sort' /*show the after array elements. */ +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; k=j+1; if @.j<=@.k then iterate /*elements in order? */ + _=@.j; @.j=@.k; @.k=_; ok=0 /*swap two elements; flag as not done.*/ + end /*j*/ + end /*m*/; return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +gen: @.=; @.1 = '---letters of the Hebrew alphabet---' ; @.13= "kaph [kaf]" + @.2 = '====================================' ; @.14= "lamed" + @.3 = 'aleph [alef]' ; @.15= "mem" + @.4 = 'beth [bet]' ; @.16= "nun" + @.5 = 'gimel' ; @.17= "samekh" + @.6 = 'daleth [dalet]' ; @.18= "ayin" + @.7 = 'he' ; @.19= "pe" + @.8 = 'waw [vav]' ; @.20= "sadhe [tsadi]" + @.9 = 'zayin' ; @.21= "qoph [qof]" + @.10= 'heth [het]' ; @.22= "resh" + @.11= 'teth [tet]' ; @.23= "shin" + @.12= 'yod' ; @.24= "taw [tav]" + do #=1 until @.#==''; end; #=#-1 /*determine #elements in list; adjust #*/ + return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +show: do j=1 for #; say ' element' right(j,length(#)) arg(1)":" @.j; end; return diff --git a/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort-2.rexx b/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort-2.rexx new file mode 100644 index 0000000000..279c369e47 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort-2.rexx @@ -0,0 +1,16 @@ +/*REXX program sorts an array (of any kind of numbers) using the bubble─sort algorithm.*/ +parse arg N .; if N=='' | N=="," then N=30 /*obtain optional size of array from CL*/ +call gen N /*generate the array elements (items). */ +call show 'before sort:' /*show the before array elements. */ +call bSort N /*invoke the bubble sort with N items.*/ +call show ' after sort:' /*show the after array elements. */ +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; k=j+1; if @.j>@.k then parse value @.j @.k 0 with @.k @.j ok + end /*j*/ /* [↑] swap 2 elements, flag as ¬done.*/ + end /*m*/; return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +gen: w=1; do j=1 for N; @.j=random(min(N+N,1e5)); w=max(w,length(@.j)); end; return +show: parse arg $; do k=1 for N; $=$ right(@.k, w); end; say $; return diff --git a/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort-3.rexx b/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort-3.rexx new file mode 100644 index 0000000000..2477685879 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort-3.rexx @@ -0,0 +1,24 @@ +Call random ,,1000 +Do i=1 To 10 + a.i=random(20) + End +a.0=i-1 +Call show 'vorher ' +Call bubble_sort +Call show 'nachher' +Exit +bubble_sort: Procedure Expose a. + Do Until no_more_swaps + no_more_swaps=1 + Do i=1 To a.0-1 + i1=i+1 + if a.i > a.i1 Then Do + temp=a.i; a.i=a.i1; a.i1=temp + no_more_swaps=0 + End + End + End +Return +show: + l=''; Do i=1 To a.0; l=l a.i; End; Say arg(1)':'l + Return diff --git a/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort.rexx b/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort.rexx deleted file mode 100644 index 10651f7809..0000000000 --- a/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort.rexx +++ /dev/null @@ -1,32 +0,0 @@ -/*REXX program sorts an array (of any kind of items) using the bubble─sort algorithm.*/ -call gen /*generate the array elements (items).*/ -call show 'before sort' /*show the before array elements. */ - say copies('─', 79) /*show a separator line (before/after).*/ -call bubbleSort # /*invoke the bubble sort with # items.*/ -call show ' after sort' /*show the after array elements. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -bubbleSort: procedure expose @.; parse arg n; m=n-1 /*N: number of array elements. */ - do m=m for m by -1 until ok; ok=1 /*keep sorting array until done.*/ - do j=1 for m; k=j+1; if @.j<=@.k then iterate /*Not out─of─order?*/ - _=@.j; @.j=@.k; @.k=_; ok=0 /*swap 2 elements; flag as ¬done*/ - end /*j*/ - end /*m*/ - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -gen: @.=; @.1 = '---letters of the Hebrew alphabet---' ; @.13= "kaph [kaf]" - @.2 = '====================================' ; @.14= "lamed" - @.3 = 'aleph [alef]' ; @.15= "mem" - @.4 = 'beth [bet]' ; @.16= "nun" - @.5 = 'gimel' ; @.17= "samekh" - @.6 = 'daleth [dalet]' ; @.18= "ayin" - @.7 = 'he' ; @.19= "pe" - @.8 = 'waw [vav]' ; @.20= "sadhe [tsadi]" - @.9 = 'zayin' ; @.21= "qoph [qof]" - @.10= 'heth [het]' ; @.22= "resh" - @.11= 'teth [tet]' ; @.23= "shin" - @.12= 'yod' ; @.24= "taw [tav]" - do #=1 while @.#\==''; end; #=#-1 /*determine #elements in list; adjust #*/ - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -show: w=length(#); do j=1 for #; say 'element' right(j,w) arg(1)":" @.j; end; return diff --git a/Task/Sorting-algorithms-Bubble-sort/Sidef/sorting-algorithms-bubble-sort.sidef b/Task/Sorting-algorithms-Bubble-sort/Sidef/sorting-algorithms-bubble-sort.sidef index f8f81a0f21..2f244eab70 100644 --- a/Task/Sorting-algorithms-Bubble-sort/Sidef/sorting-algorithms-bubble-sort.sidef +++ b/Task/Sorting-algorithms-Bubble-sort/Sidef/sorting-algorithms-bubble-sort.sidef @@ -2,11 +2,11 @@ func bubble_sort(arr) { loop { var swapped = false { |i| - if (arr[i-1] > arr[i]) { - arr[i-1, i] = arr[i, i-1] + if (arr[i] > arr[i+1]) { + arr[i, i+1] = arr[i+1, i] swapped = true } - } * arr.end + } << ^arr.end swapped || break } return arr diff --git a/Task/Sorting-algorithms-Bubble-sort/Simula/sorting-algorithms-bubble-sort.simula b/Task/Sorting-algorithms-Bubble-sort/Simula/sorting-algorithms-bubble-sort.simula new file mode 100644 index 0000000000..c66043366c --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Simula/sorting-algorithms-bubble-sort.simula @@ -0,0 +1,45 @@ +BEGIN + + PROCEDURE BUBBLESORT(A); NAME A; INTEGER ARRAY A; + BEGIN + INTEGER LOW, HIGH, I; + BOOLEAN SWAPPED; + + PROCEDURE SWAP(I, J); INTEGER I, J; + BEGIN + INTEGER TEMP; + TEMP := A(I); A(I) := A(J); A(J) := TEMP; + END**OF**SWAP; + + LOW := LOWERBOUND(A, 1); + HIGH := UPPERBOUND(A, 1); + SWAPPED := TRUE; + WHILE SWAPPED DO + BEGIN + SWAPPED := FALSE; + FOR I := LOW + 1 STEP 1 UNTIL HIGH DO + BEGIN + COMMENT IF THIS PAIR IS OUT OF ORDER ; + IF A(I - 1) > A(I) THEN + BEGIN + COMMENT SWAP THEM AND REMEMBER SOMETHING CHANGED ; + SWAP(I - 1, I); + SWAPPED := TRUE; + END; + END; + END; + END**OF**BUBBLESORT; + + INTEGER ARRAY A(1:10); + INTEGER I, N; + I := 1; + FOR N := 6, 8, 5, 9, 3, 2, 2, 1, 4, 7 DO + BEGIN + A(I) := N; I := I + 1; + END; + BUBBLESORT(A); + FOR I:= 1 STEP 1 UNTIL 10 DO + OUTINT(A(I), 5); + OUTIMAGE; + +END; diff --git a/Task/Sorting-algorithms-Bubble-sort/Zkl/sorting-algorithms-bubble-sort-1.zkl b/Task/Sorting-algorithms-Bubble-sort/Zkl/sorting-algorithms-bubble-sort-1.zkl new file mode 100644 index 0000000000..565398e317 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Zkl/sorting-algorithms-bubble-sort-1.zkl @@ -0,0 +1,13 @@ +fcn bubbleSort(list){ + itemCount := list.len(); + do{ + hasChanged := False; + foreach index in (itemCount -= 1){ + if (list[index] > list[index + 1]){ + list.swap(index,index + 1); + hasChanged = True; + } + } + }while(hasChanged); + list +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Zkl/sorting-algorithms-bubble-sort-2.zkl b/Task/Sorting-algorithms-Bubble-sort/Zkl/sorting-algorithms-bubble-sort-2.zkl new file mode 100644 index 0000000000..d9363dd925 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Zkl/sorting-algorithms-bubble-sort-2.zkl @@ -0,0 +1,6 @@ +fcn bubbleSort(list){ + foreach n,index in ([list.len()-1..0,-1],n){ + if (list[index] > list[index + 1]) list.swap(index,index + 1); + } + list +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Zkl/sorting-algorithms-bubble-sort-3.zkl b/Task/Sorting-algorithms-Bubble-sort/Zkl/sorting-algorithms-bubble-sort-3.zkl new file mode 100644 index 0000000000..6d49081cdf --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Zkl/sorting-algorithms-bubble-sort-3.zkl @@ -0,0 +1 @@ +bubbleSort("This is a test".split("")).println(); diff --git a/Task/Sorting-algorithms-Cocktail-sort/jq/sorting-algorithms-cocktail-sort-1.jq b/Task/Sorting-algorithms-Cocktail-sort/Jq/sorting-algorithms-cocktail-sort-1.jq similarity index 100% rename from Task/Sorting-algorithms-Cocktail-sort/jq/sorting-algorithms-cocktail-sort-1.jq rename to Task/Sorting-algorithms-Cocktail-sort/Jq/sorting-algorithms-cocktail-sort-1.jq diff --git a/Task/Sorting-algorithms-Cocktail-sort/jq/sorting-algorithms-cocktail-sort-2.jq b/Task/Sorting-algorithms-Cocktail-sort/Jq/sorting-algorithms-cocktail-sort-2.jq similarity index 100% rename from Task/Sorting-algorithms-Cocktail-sort/jq/sorting-algorithms-cocktail-sort-2.jq rename to Task/Sorting-algorithms-Cocktail-sort/Jq/sorting-algorithms-cocktail-sort-2.jq diff --git a/Task/Sorting-algorithms-Cocktail-sort/jq/sorting-algorithms-cocktail-sort-3.jq b/Task/Sorting-algorithms-Cocktail-sort/Jq/sorting-algorithms-cocktail-sort-3.jq similarity index 100% rename from Task/Sorting-algorithms-Cocktail-sort/jq/sorting-algorithms-cocktail-sort-3.jq rename to Task/Sorting-algorithms-Cocktail-sort/Jq/sorting-algorithms-cocktail-sort-3.jq diff --git a/Task/Sorting-algorithms-Cocktail-sort/jq/sorting-algorithms-cocktail-sort-4.jq b/Task/Sorting-algorithms-Cocktail-sort/Jq/sorting-algorithms-cocktail-sort-4.jq similarity index 100% rename from Task/Sorting-algorithms-Cocktail-sort/jq/sorting-algorithms-cocktail-sort-4.jq rename to Task/Sorting-algorithms-Cocktail-sort/Jq/sorting-algorithms-cocktail-sort-4.jq diff --git a/Task/Sorting-algorithms-Cocktail-sort/Kotlin/sorting-algorithms-cocktail-sort.kotlin b/Task/Sorting-algorithms-Cocktail-sort/Kotlin/sorting-algorithms-cocktail-sort.kotlin new file mode 100644 index 0000000000..d2cf7f5487 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Kotlin/sorting-algorithms-cocktail-sort.kotlin @@ -0,0 +1,37 @@ +// version 1.1.0 + +fun cocktailSort(a: IntArray) { + fun swap(i: Int, j: Int) { + val temp = a[i] + a[i] = a[j] + a[j] = temp + } + do { + var swapped = false + for (i in 0 until a.size - 1) + if (a[i] > a[i + 1]) { + swap(i, i + 1) + swapped = true + } + if (!swapped) break + swapped = false + for (i in a.size - 2 downTo 0) + if (a[i] > a[i + 1]) { + swap(i, i + 1) + swapped = true + } + } + while (swapped) +} + +fun main(args: Array) { + val aa = arrayOf( + intArrayOf(100, 2, 56, 200, -52, 3, 99, 33, 177, -199), + intArrayOf(4, 65, 2, -31, 0, 99, 2, 83, 782, 1), + intArrayOf(62, 83, 18, 53, 7, 17, 95, 86, 47, 69, 25, 28) + ) + for (a in aa) { + cocktailSort(a) + println(a.joinToString(", ")) + } +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/OoRexx/sorting-algorithms-cocktail-sort.rexx b/Task/Sorting-algorithms-Cocktail-sort/OoRexx/sorting-algorithms-cocktail-sort.rexx new file mode 100644 index 0000000000..5f81728d2c --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/OoRexx/sorting-algorithms-cocktail-sort.rexx @@ -0,0 +1,51 @@ +/* Rexx */ + +placesList = .array~of( - + "UK London", "US New York" , "US Boston", "US Washington" - + , "UK Washington", "US Birmingham" , "UK Birmingham", "UK Boston" - +) + +sortedList = cocktailSort(placesList~allItems()) + +lists = .array~of(placesList, sortedList) +loop ln = 1 to lists~items() + cl = lists[ln] + loop ct = 1 to cl~items() + say cl[ct] + end ct + say + end ln + +return +exit + +::routine cocktailSort + use arg A + + Alength = A~items() + swapped = .false + loop label swaps until \swapped + swapped = .false + loop i_ = 1 to Alength - 1 + if A[i_] > A[i_ + 1] then do + swap = A[i_ + 1] + A[i_ + 1] = A[i_] + A[i_] = swap + swapped = .true + end + end i_ + if \swapped then do + leave swaps + end + swapped = .false + loop i_ = Alength - 1 to 1 by -1 + if A[i_] > A[i_ + 1] then do + swap = A[i_ + 1] + A[i_ + 1] = A[i_] + A[i_] = swap + swapped = .true + end + end i_ + end swaps + + return A diff --git a/Task/Sorting-algorithms-Cocktail-sort/Scilab/sorting-algorithms-cocktail-sort.scilab b/Task/Sorting-algorithms-Cocktail-sort/Scilab/sorting-algorithms-cocktail-sort.scilab new file mode 100644 index 0000000000..9eea575801 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Scilab/sorting-algorithms-cocktail-sort.scilab @@ -0,0 +1,25 @@ +function varargout=cocktailSort(list_in) + swapped = %T; + while swapped + swapped = %F; + for i = [1:length(list_in)-1] + if list_in(i) > list_in(i+1) then + list_in([i i+1])=list_in([i+1 i]); + swapped = %T; + end + end + if ~swapped + break + end + swapped = %F; + for i = [length(list_in)-1:-1:1] + if list_in(i) > list_in(i+1) + list_in([i i+1]) = list_in([i+1 i]) + swapped = %T; + end + end + end + varargout=list(list_in) +endfunction + +disp(cocktailSort([6 3 7 8 5 1 2 4 9])); diff --git a/Task/Sorting-algorithms-Cocktail-sort/Sidef/sorting-algorithms-cocktail-sort-1.sidef b/Task/Sorting-algorithms-Cocktail-sort/Sidef/sorting-algorithms-cocktail-sort-1.sidef index 7f433c121e..3865eda545 100644 --- a/Task/Sorting-algorithms-Cocktail-sort/Sidef/sorting-algorithms-cocktail-sort-1.sidef +++ b/Task/Sorting-algorithms-Cocktail-sort/Sidef/sorting-algorithms-cocktail-sort-1.sidef @@ -1,16 +1,16 @@ func cocktailsort(a) { - var swapped = false; + var swapped = false func cmpsw(i) { if (a[i] > a[i+1]) { - a[i, i+1] = a[i+1, i]; - swapped = true; + a[i, i+1] = a[i+1, i] + swapped = true } } - var max = a.end; + var max = a.end do { - { |i| cmpsw(i-1) } * max; - swapped.not! && break; - { |i| cmpsw(max-i) } * max; - } while (swapped); - return a; + {|i| cmpsw(i) } << ^max + swapped.not! && break + {|i| cmpsw(max-i) } << 1..max + } while (swapped) + return a } diff --git a/Task/Sorting-algorithms-Cocktail-sort/Sidef/sorting-algorithms-cocktail-sort-2.sidef b/Task/Sorting-algorithms-Cocktail-sort/Sidef/sorting-algorithms-cocktail-sort-2.sidef index c9b44ee617..19671b79d6 100644 --- a/Task/Sorting-algorithms-Cocktail-sort/Sidef/sorting-algorithms-cocktail-sort-2.sidef +++ b/Task/Sorting-algorithms-Cocktail-sort/Sidef/sorting-algorithms-cocktail-sort-2.sidef @@ -1,5 +1,5 @@ -var numbers = [7,6,5,9,8,4,3,1,2,0]; -say cocktailsort(numbers).dump; +var numbers = [7,6,5,9,8,4,3,1,2,0] +say cocktailsort(numbers) -var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"]; -say cocktailsort(strs).dump; +var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"] +say cocktailsort(strs) diff --git a/Task/Sorting-algorithms-Cocktail-sort/Zkl/sorting-algorithms-cocktail-sort-1.zkl b/Task/Sorting-algorithms-Cocktail-sort/Zkl/sorting-algorithms-cocktail-sort-1.zkl new file mode 100644 index 0000000000..f6318fb3d3 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Zkl/sorting-algorithms-cocktail-sort-1.zkl @@ -0,0 +1,15 @@ +fcn cocktailSort(a){ + swapped,begin,end:=False,-1,a.len() - 2; + do{ + swapped,begin=False,begin + 1; + foreach i in ([begin .. end]){ + if(a[i]>a[i+1]){ a.swap(i,i+1); swapped=True; } + } + if(not swapped) break; + swapped,end=False,end - 1; + foreach i in ([end..begin,-1]){ + if(a[i]>a[i+1]){ a.swap(i,i+1); swapped=True; } + } + }while(swapped); + a +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Zkl/sorting-algorithms-cocktail-sort-2.zkl b/Task/Sorting-algorithms-Cocktail-sort/Zkl/sorting-algorithms-cocktail-sort-2.zkl new file mode 100644 index 0000000000..a1fa1081ed --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Zkl/sorting-algorithms-cocktail-sort-2.zkl @@ -0,0 +1,5 @@ +cocktailSort(List(2,1)).println(); +x:=List(5, -1, 101, -4, 0, 1, 8, 6, 2, 3 ); +cocktailSort(x).println(); +x="the lazy fox jumped over the brown dog".split(" ").copy(); +cocktailSort(x).println(); diff --git a/Task/Sorting-algorithms-Comb-sort/Common-Lisp/sorting-algorithms-comb-sort.lisp b/Task/Sorting-algorithms-Comb-sort/Common-Lisp/sorting-algorithms-comb-sort.lisp new file mode 100644 index 0000000000..6e14ade905 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Common-Lisp/sorting-algorithms-comb-sort.lisp @@ -0,0 +1,16 @@ +(defparameter *shrink* 1.3) + +(defun comb-sort (input) + (loop with input-size = (length input) + with gap = input-size + with swapped + do (when (> gap 1) + (setf gap (floor gap *shrink*))) + (setf swapped nil) + (loop for lo from 0 + for hi from gap below input-size + when (> (aref input lo) (aref input hi)) + do (rotatef (aref input lo) (aref input hi)) + (setf swapped t)) + while (or (> gap 1) swapped) + finally (return input))) diff --git a/Task/Sorting-algorithms-Comb-sort/jq/sorting-algorithms-comb-sort.jq b/Task/Sorting-algorithms-Comb-sort/Jq/sorting-algorithms-comb-sort.jq similarity index 100% rename from Task/Sorting-algorithms-Comb-sort/jq/sorting-algorithms-comb-sort.jq rename to Task/Sorting-algorithms-Comb-sort/Jq/sorting-algorithms-comb-sort.jq diff --git a/Task/Sorting-algorithms-Comb-sort/Julia/sorting-algorithms-comb-sort.julia b/Task/Sorting-algorithms-Comb-sort/Julia/sorting-algorithms-comb-sort.julia new file mode 100644 index 0000000000..065a34301a --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Julia/sorting-algorithms-comb-sort.julia @@ -0,0 +1,21 @@ +# v0.6 + +function combsort!(x::Array)::Array + gap, swaps = length(x), true + while gap > 1 || swaps + gap = floor(Int, gap / 1.25) + i, swaps = 0, false + while i + gap < length(x) + if x[i+1] > x[i+1+gap] + x[i+1], x[i+1+gap] = x[i+1+gap], x[i+1] + swaps = true + end + i += 1 + end + end + return x +end + +x = randn(100) +@show x combsort!(x) +@assert issorted(x) diff --git a/Task/Sorting-algorithms-Comb-sort/Kotlin/sorting-algorithms-comb-sort.kotlin b/Task/Sorting-algorithms-Comb-sort/Kotlin/sorting-algorithms-comb-sort.kotlin new file mode 100644 index 0000000000..d53b309597 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Kotlin/sorting-algorithms-comb-sort.kotlin @@ -0,0 +1,34 @@ +// version 1.1.2 + +fun > combSort(input: Array) { + var gap = input.size + if (gap <= 1) return // already sorted + var swaps = false + while (gap > 1 || swaps) { + gap = (gap / 1.247331).toInt() + if (gap < 1) gap = 1 + var i = 0 + swaps = false + while (i + gap < input.size) { + if (input[i] > input[i + gap]) { + val tmp = input[i] + input[i] = input[i + gap] + input[i + gap] = tmp + swaps = true + } + i++ + } + } +} + +fun main(args: Array) { + val ia = arrayOf(28, 44, 46, 24, 19, 2, 17, 11, 25, 4) + println("Unsorted : ${ia.contentToString()}") + combSort(ia) + println("Sorted : ${ia.contentToString()}") + println() + val ca = arrayOf('X', 'B', 'E', 'A', 'Z', 'M', 'S', 'L', 'Y', 'C') + println("Unsorted : ${ca.contentToString()}") + combSort(ca) + println("Sorted : ${ca.contentToString()}") +} diff --git a/Task/Sorting-algorithms-Comb-sort/Zkl/sorting-algorithms-comb-sort-1.zkl b/Task/Sorting-algorithms-Comb-sort/Zkl/sorting-algorithms-comb-sort-1.zkl new file mode 100644 index 0000000000..f46454503c --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Zkl/sorting-algorithms-comb-sort-1.zkl @@ -0,0 +1,13 @@ +fcn combSort(list){ + len,gap,swaps:=list.len(),len,True; + while(gap>1 or swaps){ + gap,swaps=(1).max(gap.toFloat()/1.2473), False; + foreach i in (len - gap){ + if(list[i]>list[i + gap]){ + list.swap(i,i + gap); + swaps=True; + } + } + } + list +} diff --git a/Task/Sorting-algorithms-Comb-sort/Zkl/sorting-algorithms-comb-sort-2.zkl b/Task/Sorting-algorithms-Comb-sort/Zkl/sorting-algorithms-comb-sort-2.zkl new file mode 100644 index 0000000000..9bee6dc0f5 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Zkl/sorting-algorithms-comb-sort-2.zkl @@ -0,0 +1,2 @@ +combSort(List(28, 44, 46, 24, 19, 2, 17, 11, 25, 4)).println(); +combSort("This is a test".toData()).text.println(); diff --git a/Task/Sorting-algorithms-Counting-sort/jq/sorting-algorithms-counting-sort-1.jq b/Task/Sorting-algorithms-Counting-sort/Jq/sorting-algorithms-counting-sort-1.jq similarity index 100% rename from Task/Sorting-algorithms-Counting-sort/jq/sorting-algorithms-counting-sort-1.jq rename to Task/Sorting-algorithms-Counting-sort/Jq/sorting-algorithms-counting-sort-1.jq diff --git a/Task/Sorting-algorithms-Counting-sort/jq/sorting-algorithms-counting-sort-2.jq b/Task/Sorting-algorithms-Counting-sort/Jq/sorting-algorithms-counting-sort-2.jq similarity index 100% rename from Task/Sorting-algorithms-Counting-sort/jq/sorting-algorithms-counting-sort-2.jq rename to Task/Sorting-algorithms-Counting-sort/Jq/sorting-algorithms-counting-sort-2.jq diff --git a/Task/Sorting-algorithms-Counting-sort/jq/sorting-algorithms-counting-sort-3.jq b/Task/Sorting-algorithms-Counting-sort/Jq/sorting-algorithms-counting-sort-3.jq similarity index 100% rename from Task/Sorting-algorithms-Counting-sort/jq/sorting-algorithms-counting-sort-3.jq rename to Task/Sorting-algorithms-Counting-sort/Jq/sorting-algorithms-counting-sort-3.jq diff --git a/Task/Sorting-algorithms-Counting-sort/Kotlin/sorting-algorithms-counting-sort.kotlin b/Task/Sorting-algorithms-Counting-sort/Kotlin/sorting-algorithms-counting-sort.kotlin new file mode 100644 index 0000000000..3d559d76ab --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Kotlin/sorting-algorithms-counting-sort.kotlin @@ -0,0 +1,22 @@ +// version 1.1.0 + +fun countingSort(array: IntArray) { + if (array.isEmpty()) return + val min = array.min()!! + val max = array.max()!! + val count = IntArray(max - min + 1) // all elements zero by default + for (number in array) count[number - min]++ + var z = 0 + for (i in min..max) + while (count[i - min] > 0) { + array[z++] = i + count[i - min]-- + } +} + +fun main(args: Array) { + val array = intArrayOf(4, 65, 2, -31, 0, 99, 2, 83, 782, 1) + println("Original : ${array.asList()}") + countingSort(array) + println("Sorted : ${array.asList()}") +} diff --git a/Task/Sorting-algorithms-Counting-sort/Sidef/sorting-algorithms-counting-sort.sidef b/Task/Sorting-algorithms-Counting-sort/Sidef/sorting-algorithms-counting-sort.sidef index 711daeb2ae..6984e7acdb 100644 --- a/Task/Sorting-algorithms-Counting-sort/Sidef/sorting-algorithms-counting-sort.sidef +++ b/Task/Sorting-algorithms-Counting-sort/Sidef/sorting-algorithms-counting-sort.sidef @@ -1,8 +1,8 @@ func counting_sort(a, min, max) { - var cnt = ([0] * (max - min + 1)); - a.each { |i| cnt[i-min]++ }; - return cnt.map {|i| min++; [min-1] * i}.sum; + var cnt = ([0] * (max - min + 1)) + a.each {|i| cnt[i-min]++ } + cnt.map {|i| [min++] * i }.flat } - -var a = 100.of {100.rand.int}; -say counting_sort(a, 0, 100).dump; +  +var a = 100.of { 100.irand } +say counting_sort(a, 0, 100) diff --git a/Task/Sorting-algorithms-Counting-sort/Zkl/sorting-algorithms-counting-sort-1.zkl b/Task/Sorting-algorithms-Counting-sort/Zkl/sorting-algorithms-counting-sort-1.zkl new file mode 100644 index 0000000000..ef0dc4f543 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Zkl/sorting-algorithms-counting-sort-1.zkl @@ -0,0 +1,11 @@ +fcn countingSort(array, min, max){ // modifies array + count:=(max - min + 1).pump(List().write,0); // array of (max - min + 1) zeros + foreach number in (array){ + count[number - min] += 1; + } + z:=-1; + foreach i in ([min .. max]){ + do(count[i - min]){ array[z += 1] = i } + } + array +} diff --git a/Task/Sorting-algorithms-Counting-sort/Zkl/sorting-algorithms-counting-sort-2.zkl b/Task/Sorting-algorithms-Counting-sort/Zkl/sorting-algorithms-counting-sort-2.zkl new file mode 100644 index 0000000000..8b2935ab06 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Zkl/sorting-algorithms-counting-sort-2.zkl @@ -0,0 +1,2 @@ +array:=List(4, 65, 2, -31, 0, 99, 2, 83, 182, 1); +countingSort(array,(0).min(array), (0).max(array)).println(); diff --git a/Task/Sorting-algorithms-Gnome-sort/jq/sorting-algorithms-gnome-sort-1.jq b/Task/Sorting-algorithms-Gnome-sort/Jq/sorting-algorithms-gnome-sort-1.jq similarity index 100% rename from Task/Sorting-algorithms-Gnome-sort/jq/sorting-algorithms-gnome-sort-1.jq rename to Task/Sorting-algorithms-Gnome-sort/Jq/sorting-algorithms-gnome-sort-1.jq diff --git a/Task/Sorting-algorithms-Gnome-sort/jq/sorting-algorithms-gnome-sort-2.jq b/Task/Sorting-algorithms-Gnome-sort/Jq/sorting-algorithms-gnome-sort-2.jq similarity index 100% rename from Task/Sorting-algorithms-Gnome-sort/jq/sorting-algorithms-gnome-sort-2.jq rename to Task/Sorting-algorithms-Gnome-sort/Jq/sorting-algorithms-gnome-sort-2.jq diff --git a/Task/Sorting-algorithms-Gnome-sort/jq/sorting-algorithms-gnome-sort-3.jq b/Task/Sorting-algorithms-Gnome-sort/Jq/sorting-algorithms-gnome-sort-3.jq similarity index 100% rename from Task/Sorting-algorithms-Gnome-sort/jq/sorting-algorithms-gnome-sort-3.jq rename to Task/Sorting-algorithms-Gnome-sort/Jq/sorting-algorithms-gnome-sort-3.jq diff --git a/Task/Sorting-algorithms-Gnome-sort/Kotlin/sorting-algorithms-gnome-sort.kotlin b/Task/Sorting-algorithms-Gnome-sort/Kotlin/sorting-algorithms-gnome-sort.kotlin new file mode 100644 index 0000000000..6116c7f8b8 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Kotlin/sorting-algorithms-gnome-sort.kotlin @@ -0,0 +1,25 @@ +// version 1.1.0 + +fun > gnomeSort(a: Array, ascending: Boolean = true) { + var i = 1 + var j = 2 + while (i < a.size) + if (ascending && (a[i - 1] <= a[i]) || + !ascending && (a[i - 1] >= a[i])) + i = j++ + else { + val temp = a[i - 1] + a[i - 1] = a[i] + a[i--] = temp + if (i == 0) i = j++ + } +} + +fun main(args: Array) { + val array = arrayOf(100, 2, 56, 200, -52, 3, 99, 33, 177, -199) + println("Original : ${array.asList()}") + gnomeSort(array) + println("Sorted (asc) : ${array.asList()}") + gnomeSort(array, false) + println("Sorted (desc) : ${array.asList()}") +} diff --git a/Task/Sorting-algorithms-Gnome-sort/OoRexx/sorting-algorithms-gnome-sort-1.rexx b/Task/Sorting-algorithms-Gnome-sort/OoRexx/sorting-algorithms-gnome-sort-1.rexx new file mode 100644 index 0000000000..672c215a21 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/OoRexx/sorting-algorithms-gnome-sort-1.rexx @@ -0,0 +1,95 @@ +/* Rexx */ + +call demo +return +exit + +-- ----------------------------------------------------------------------------- +-- Gnome sort implementation +-- ----------------------------------------------------------------------------- +::routine gnomeSort + use arg ra, sAsc = '' + if sAsc = '' then sAsc = isTrue() + + sDsc = \sAsc -- Ascending/descending switches + i_ = 1 + j_ = 2 + loop label i_ while i_ < ra~items() + ctx = (ra~get(i_ - 1))~compareTo(ra~get(i_)) + if (sAsc & ctx <= 0) | (sDsc & ctx >= 0) then do + i_ = j_ + j_ = j_ + 1 + end + else do + swap = ra~get(i_) + ra~set(i_, ra~get(i_ - 1)) + ra~set(i_ - 1, swap) + i_ = i_ - 1 + if i_ = 0 then do + i_ = j_ + j_ = j_ + 1 + end + end + end i_ + + return ra + +-- ----------------------------------------------------------------------------- +-- Demonstrate the implementation +-- ----------------------------------------------------------------------------- +::routine demo + placesList = .nlist~of( - + "UK London", "US New York", "US Boston", "US Washington" - + , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - + ) + + lists = .nlist~of( - + placesList - + , gnomeSort(placesList~copy()) - + ) + + loop ln = 0 to lists~items() - 1 + cl = lists[ln] + loop ct = 0 to cl~items() - 1 + say right(ct + 1, 3)':' cl[ct] + end ct + say + end ln + + i_.0 = 3 + i_.1 = .nlist~of(3, 3, 1, 2, 4, 3, 5, 6) + i_.2 = gnomeSort(i_.1~copy(), isTrue()) + i_.3 = gnomeSort(i_.1~copy(), isFalse()) + loop s_ = 1 to i_.0 + ss = '' + loop x_ = 0 to i_.s_~items() - 1 + ss ||= right(i_.s_~get(x_), 3)' ' + end x_ + say strip(ss, 'T') + end s_ + + return + +-- ----------------------------------------------------------------------------- +::routine isTrue + return 1 == 1 + +-- ----------------------------------------------------------------------------- +::routine isFalse + return \isTrue() + +-- ----------------------------------------------------------------------------- +-- Helper class. Map get and set methods for easier conversion from java.util.List +-- ----------------------------------------------------------------------------- +::class NList mixinclass List public + +-- Map get() to at() +::method get + use arg ix + return self~at(ix) + +-- Map set() to put() +::method set + use arg ix, item + self~put(item, ix) + return diff --git a/Task/Sorting-algorithms-Gnome-sort/OoRexx/sorting-algorithms-gnome-sort-2.rexx b/Task/Sorting-algorithms-Gnome-sort/OoRexx/sorting-algorithms-gnome-sort-2.rexx new file mode 100644 index 0000000000..f38e178950 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/OoRexx/sorting-algorithms-gnome-sort-2.rexx @@ -0,0 +1,40 @@ +/* REXX --------------------------------------------------------------- +* 28.06.2014 Walter Pachl +* 30.06.2014 corrected in sync with REXX version 2 +*--------------------------------------------------------------------*/ + Call gen /* generate the array elements. */ + Call show 'before sort' /* show "before" array elements.*/ + Call gnomeSort x /* invoke the infamous gnome sort.*/ + Call show ' after sort' /* show "after" array elements.*/ + Exit /* done. */ + +gnomesort: Procedure + Use Arg x + n=x~items + k=2 + Do j=3 While k<=n + km=k-1 + If x[km]<=x[k] Then + k=j + Else Do + t=x[km]; x[km]=x[k]; x[k]=t /* swap two entries in the array. */ + k=k-1 + If k==1 Then + k=j + Else + j=j-1 + End + End + Return + +gen: + x=.array~of('---the seven virtues---','=======================',, + 'Faith','Hope','Charity [Love]','Fortitude',' Justice',, + 'Prudence','Temperance') + Return +show: + Say arg(1) + Do i=1 To x~items + Say 'element' right(i,2) x[i] + End + Return diff --git a/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-1.rexx b/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-1.rexx index e2eabebebd..e6642ba552 100644 --- a/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-1.rexx +++ b/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-1.rexx @@ -6,6 +6,11 @@ call gnomeSort # /*invoke the well─known gnom call show ' after sort' /*display the after array elements.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ +gen: @.=; @.1='---the seven virtues---'; @.4="Hope" ; @.7='Justice' + @.2='======================='; @.5="Charity [LOVE]"; @.8='Prudence' + @.3='Faith' ; @.6="Fortitude" ; @.9='Temperance' + do #=1 while @.#\==''; end; #=#-1; w=length(#); return /*find # items.*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ gnomeSort: procedure expose @.; parse arg n; k=2 /*N: is number items. */ do j=3 while k<=n; p=k-1 /*P: is previous item.*/ if @.p<<=@.k then do; k=j; iterate; end /*order is OK so far. */ @@ -14,12 +19,4 @@ gnomeSort: procedure expose @.; parse arg n; k=2 /*N: is number end /*j*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ -gen: @.=; @.1 = '---the seven virtues---' ; @.5 = "Charity [Love]" - @.2 = '=======================' ; @.6 = "Fortitude" - @.3 = 'Faith' ; @.7 = "Justice" - @.4 = 'Hope' ; @.8 = "Prudence" - @.9 = "Temperance" - do #=1 while @.#\==''; end; #=#-1; w=length(#) /*find # of items.*/ - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -show: do j=1 for #; say ' element' right(j,w) arg(1)":" @.j; end; return +show: do j=1 for #; say ' element' right(j,w) arg(1)":" @.j; end; return diff --git a/Task/Sorting-algorithms-Gnome-sort/Zkl/sorting-algorithms-gnome-sort-1.zkl b/Task/Sorting-algorithms-Gnome-sort/Zkl/sorting-algorithms-gnome-sort-1.zkl new file mode 100644 index 0000000000..63cc17f0a6 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Zkl/sorting-algorithms-gnome-sort-1.zkl @@ -0,0 +1,13 @@ +fcn gnomeSort(a){ + i,j,size := 1,2,a.len(); + while(i < size){ + if(a[i-1] > a[i]){ // for descending sort, use < for comparison + a.swap(i-1,i); + i = i - 1; + if(i) continue; + } + i = j; + j = j + 1; + }//while + a +} diff --git a/Task/Sorting-algorithms-Gnome-sort/Zkl/sorting-algorithms-gnome-sort-2.zkl b/Task/Sorting-algorithms-Gnome-sort/Zkl/sorting-algorithms-gnome-sort-2.zkl new file mode 100644 index 0000000000..ccc7179675 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Zkl/sorting-algorithms-gnome-sort-2.zkl @@ -0,0 +1 @@ +gnomeSort("This is a test".split("")).println(); diff --git a/Task/Sorting-algorithms-Heapsort/FreeBASIC/sorting-algorithms-heapsort.freebasic b/Task/Sorting-algorithms-Heapsort/FreeBASIC/sorting-algorithms-heapsort.freebasic index d7e5265222..95bdb9b91c 100644 --- a/Task/Sorting-algorithms-Heapsort/FreeBASIC/sorting-algorithms-heapsort.freebasic +++ b/Task/Sorting-algorithms-Heapsort/FreeBASIC/sorting-algorithms-heapsort.freebasic @@ -2,18 +2,17 @@ ' compile with: fbc -s console ' for boundary checks on array's compile with: fbc -s console -exx -' sort from lower bound to the highter bound +' sort from lower bound to the higher bound ' array's can have subscript range from -2147483648 to +2147483647 -Sub siftdown(hs() As Long, start As ULong , end_ As ULong) - +Sub siftdown(hs() As Long, start As ULong, end_ As ULong) Dim As ULong root = start Dim As Long lb = LBound(hs) - While root * 2 +1 < end_ - Dim As ULong child = root * 2 +1 - If (child +1 < end_) And (hs(lb + child) < hs(lb + child +1)) Then - child = child +1 + While root * 2 + 1 <= end_ + Dim As ULong child = root * 2 + 1 + If (child + 1 <= end_) AndAlso (hs(lb + child) < hs(lb + child + 1)) Then + child = child + 1 End If If hs(lb + root) < hs(lb + child) Then Swap hs(lb + root), hs(lb + child) @@ -22,27 +21,24 @@ Sub siftdown(hs() As Long, start As ULong , end_ As ULong) Return End If Wend - End Sub Sub heapsort(hs() As Long) - Dim As Long lb = LBound(hs) - Dim As ULong count = UBound(hs) - lb - Dim As Long start = (count -2) \ 2 + Dim As ULong count = UBound(hs) - lb + 1 + Dim As Long start = (count - 2) \ 2 + Dim As ULong end_ = count - 1 While start >= 0 - siftdown(hs(), start, count) - start = start -1 + siftdown(hs(), start, end_) + start = start - 1 Wend - Dim As ULong end_ = count While end_ > 0 Swap hs(lb + end_), hs(lb) + end_ = end_ - 1 siftdown(hs(), 0, end_) - end_ = end_ -1 Wend - End Sub ' ------=< MAIN >=------ @@ -53,7 +49,7 @@ Dim As Long i, lb = LBound(array), ub = UBound(array) Randomize Timer For i = lb To ub : array(i) = i : Next For i = lb To ub - Swap array(i), array(Int(Rnd * (ub - lb +1)) + lb) + Swap array(i), array(Int(Rnd * (ub - lb + 1)) + lb) Next Print "Unsorted" diff --git a/Task/Sorting-algorithms-Heapsort/JavaScript/sorting-algorithms-heapsort.js b/Task/Sorting-algorithms-Heapsort/JavaScript/sorting-algorithms-heapsort.js new file mode 100644 index 0000000000..90972168ad --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/JavaScript/sorting-algorithms-heapsort.js @@ -0,0 +1,45 @@ +function swap(data, i, j) { + var tmp = data[i]; + data[i] = data[j]; + data[j] = tmp; +} + + function heap_sort(arr) { + put_array_in_heap_order(arr); + end = arr.length - 1; + while(end > 0) { + swap(arr, 0, end); + sift_element_down_heap(arr, 0, end); + end -= 1 + } +} + +function put_array_in_heap_order(arr) { + var i; + i = arr.length / 2 - 1; + i = Math.floor(i); + while (i >= 0) { + sift_element_down_heap(arr, i, arr.length); + i -= 1; + } +} + +function sift_element_down_heap(heap, i, max) { + var i_big, c1, c2; + while(i < max) { + i_big = i; + c1 = 2*i + 1; + c2 = c1 + 1; + if (c1 < max && heap[c1] > heap[i_big]) + i_big = c1; + if (c2 < max && heap[c2] > heap[i_big]) + i_big = c2; + if (i_big == i) return; + swap(heap,i, i_big); + i = i_big; + } +} + +arr = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8,]; +heap_sort(arr); +alert(arr); diff --git a/Task/Sorting-algorithms-Heapsort/Kotlin/sorting-algorithms-heapsort.kotlin b/Task/Sorting-algorithms-Heapsort/Kotlin/sorting-algorithms-heapsort.kotlin new file mode 100644 index 0000000000..02ebda45f8 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Kotlin/sorting-algorithms-heapsort.kotlin @@ -0,0 +1,48 @@ +// version 1.1.0 + +fun heapSort(a: IntArray) { + heapify(a) + var end = a.size - 1 + while (end > 0) { + val temp = a[end] + a[end] = a[0] + a[0] = temp + end-- + siftDown(a, 0, end) + } +} + +fun heapify(a: IntArray) { + var start = (a.size - 2) / 2 + while (start >= 0) { + siftDown(a, start, a.size - 1) + start-- + } +} + +fun siftDown(a: IntArray, start: Int, end: Int) { + var root = start + while (root * 2 + 1 <= end) { + var child = root * 2 + 1 + if (child + 1 <= end && a[child] < a[child + 1]) child++ + if (a[root] < a[child]) { + val temp = a[root] + a[root] = a[child] + a[child] = temp + root = child + } + else return + } +} + +fun main(args: Array) { + val aa = arrayOf( + intArrayOf(100, 2, 56, 200, -52, 3, 99, 33, 177, -199), + intArrayOf(4, 65, 2, -31, 0, 99, 2, 83, 782, 1), + intArrayOf(12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8) + ) + for (a in aa) { + heapSort(a) + println(a.joinToString(", ")) + } +} diff --git a/Task/Sorting-algorithms-Heapsort/Rust/sorting-algorithms-heapsort-1.rust b/Task/Sorting-algorithms-Heapsort/Rust/sorting-algorithms-heapsort-1.rust new file mode 100644 index 0000000000..ef01998c8c --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Rust/sorting-algorithms-heapsort-1.rust @@ -0,0 +1,39 @@ +fn main() { + let mut v = [4,6,8,1,0,3,2,2,9,5]; + heap_sort(&mut v, |x,y| x < y); + println!("{:?}", v); +} + +fn heap_sort(array: &mut [T], order: F) + where F: Fn(&T,&T) -> bool +{ + let len = array.len(); + // Create heap + for start in (0..len/2).rev() { + sift_down(array,&order,start,len-1) + } + + for end in (1..len).rev() { + array.swap(0,end); + sift_down(array,&order,0,end-1) + } +} + +fn sift_down(array: &mut [T], order: &F, start: usize, end: usize) + where F: Fn(&T,&T) -> bool +{ + let mut root = start; + loop { + let mut child = root * 2 + 1; + if child > end { break; } + if child + 1 <= end && order(&array[child], &array[child + 1]) { + child += 1; + } + if order(&array[root], &array[child]) { + array.swap(root,child); + root = child + } else { + break; + } + } +} diff --git a/Task/Sorting-algorithms-Heapsort/Rust/sorting-algorithms-heapsort-2.rust b/Task/Sorting-algorithms-Heapsort/Rust/sorting-algorithms-heapsort-2.rust new file mode 100644 index 0000000000..f1093f34cd --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Rust/sorting-algorithms-heapsort-2.rust @@ -0,0 +1,7 @@ +use std::collections::BinaryHeap; + +fn main() { + let src = vec![6,2,3,6,1,2,7,8,3,2]; + let sorted= BinaryHeap::from(src).into_sorted_vec(); + println!("{:?}", sorted); +} diff --git a/Task/Sorting-algorithms-Heapsort/SequenceL/sorting-algorithms-heapsort.sequencel b/Task/Sorting-algorithms-Heapsort/SequenceL/sorting-algorithms-heapsort.sequencel new file mode 100644 index 0000000000..b986778695 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/SequenceL/sorting-algorithms-heapsort.sequencel @@ -0,0 +1,32 @@ +import ; + +TUPLE ::= (A: T, B: T); + +heapSort(x(1)) := + let + heapified := heapify(x, (size(x) - 2) / 2 + 1); + in + sortLoop(heapified, size(heapified)); + +heapify(x(1), i) := + x when i <= 0 else + heapify(siftDown(x, i, size(x)), i - 1); + +sortLoop(x(1), i) := + x when i <= 2 else + sortLoop( siftDown(swap(x, 1, i), 1, i - 1), i - 1); + +siftDown(x(1), start, end) := + let + child := start * 2; + child1 := child + 1 when child + 1 <= end and x[child] < x[child + 1] else child; + in + x when child >= end else + x when x[start] >= x[child1] else + siftDown(swap(x, child1, start), child1, end); + +swap(list(1), i, j) := + let + vals := (A: list[i], B: list[j]); + in + setElementAt(setElementAt(list, i, vals.B), j, vals.A); diff --git a/Task/Sorting-algorithms-Heapsort/VBA/sorting-algorithms-heapsort.vba b/Task/Sorting-algorithms-Heapsort/VBA/sorting-algorithms-heapsort.vba new file mode 100644 index 0000000000..84cd796277 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/VBA/sorting-algorithms-heapsort.vba @@ -0,0 +1,47 @@ +Sub SiftDown(list() As Integer, start As Long, eend As Long) + Dim root As Long : root = start + Dim lb As Long : lb = LBound(list) + Dim temp As Integer + + While root * 2 + 1 <= eend + Dim child As Long : child = root * 2 + 1 + If child + 1 <= eend Then + If list(lb + child) < list(lb + child + 1) Then + child = child + 1 + End If + End If + If list(lb + root) < list(lb + child) Then + temp = list(lb + root) + list(lb + root) = list(lb + child) + list(lb + child) = temp + + root = child + Else + Exit Sub + End If + Wend +End Sub + +Sub HeapSort(list() As Integer) + Dim lb As Long : lb = LBound(list) + Dim count As Long : count = UBound(list) - lb + 1 + Dim start As Long : start = (count - 2) \ 2 + Dim eend As Long : eend = count - 1 + + While start >= 0 + SiftDown list(), start, eend + start = start - 1 + Wend + + Dim temp As Integer + + While eend > 0 + temp = list(lb + eend) + list(lb + eend) = list(lb) + list(lb) = temp + + eend = eend - 1 + + SiftDown list(), 0, eend + Wend +End Sub diff --git a/Task/Sorting-algorithms-Heapsort/Zkl/sorting-algorithms-heapsort-1.zkl b/Task/Sorting-algorithms-Heapsort/Zkl/sorting-algorithms-heapsort-1.zkl new file mode 100644 index 0000000000..4084440406 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Zkl/sorting-algorithms-heapsort-1.zkl @@ -0,0 +1,19 @@ +fcn heapSort(a){ // in place + n := a.len(); + foreach start in ([(n-2)/2 .. 0,-1]) + { siftDown(a, start, n-1) } + foreach end in ([n-1 .. 1,-1]){ + a.swap(0, end); + siftDown(a, 0, end-1); + } + a +} + +fcn siftDown(a, start, end){ + while((child := start*2 + 1) <= end){ + if(child < end and a[child]= a[child]) return(); + a.swap(start, child); + start = child; + } +} diff --git a/Task/Sorting-algorithms-Heapsort/Zkl/sorting-algorithms-heapsort-2.zkl b/Task/Sorting-algorithms-Heapsort/Zkl/sorting-algorithms-heapsort-2.zkl new file mode 100644 index 0000000000..325d88a891 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Zkl/sorting-algorithms-heapsort-2.zkl @@ -0,0 +1,2 @@ +heapSort(L(170, 45, 75, -90, -802, 24, 2, 66)).println(); +heapSort("this is a test".split("")).println(); diff --git a/Task/Sorting-algorithms-Insertion-sort/jq/sorting-algorithms-insertion-sort-1.jq b/Task/Sorting-algorithms-Insertion-sort/Jq/sorting-algorithms-insertion-sort-1.jq similarity index 100% rename from Task/Sorting-algorithms-Insertion-sort/jq/sorting-algorithms-insertion-sort-1.jq rename to Task/Sorting-algorithms-Insertion-sort/Jq/sorting-algorithms-insertion-sort-1.jq diff --git a/Task/Sorting-algorithms-Insertion-sort/jq/sorting-algorithms-insertion-sort-2.jq b/Task/Sorting-algorithms-Insertion-sort/Jq/sorting-algorithms-insertion-sort-2.jq similarity index 100% rename from Task/Sorting-algorithms-Insertion-sort/jq/sorting-algorithms-insertion-sort-2.jq rename to Task/Sorting-algorithms-Insertion-sort/Jq/sorting-algorithms-insertion-sort-2.jq diff --git a/Task/Sorting-algorithms-Insertion-sort/jq/sorting-algorithms-insertion-sort-3.jq b/Task/Sorting-algorithms-Insertion-sort/Jq/sorting-algorithms-insertion-sort-3.jq similarity index 100% rename from Task/Sorting-algorithms-Insertion-sort/jq/sorting-algorithms-insertion-sort-3.jq rename to Task/Sorting-algorithms-Insertion-sort/Jq/sorting-algorithms-insertion-sort-3.jq diff --git a/Task/Sorting-algorithms-Insertion-sort/jq/sorting-algorithms-insertion-sort-4.jq b/Task/Sorting-algorithms-Insertion-sort/Jq/sorting-algorithms-insertion-sort-4.jq similarity index 100% rename from Task/Sorting-algorithms-Insertion-sort/jq/sorting-algorithms-insertion-sort-4.jq rename to Task/Sorting-algorithms-Insertion-sort/Jq/sorting-algorithms-insertion-sort-4.jq diff --git a/Task/Sorting-algorithms-Insertion-sort/Julia/sorting-algorithms-insertion-sort.julia b/Task/Sorting-algorithms-Insertion-sort/Julia/sorting-algorithms-insertion-sort.julia new file mode 100644 index 0000000000..14ab13855f --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Julia/sorting-algorithms-insertion-sort.julia @@ -0,0 +1,17 @@ +# v0.6 + +function insertionsort!(A::Array{T}) where T <: Number + for i in 1:length(A)-1 + value = A[i+1] + j = i + while j > 0 && A[j] > value + A[j+1] = A[j] + j -= 1 + end + A[j+1] = value + end + return A +end + +x = randn(5) +@show x insertionsort!(x) diff --git a/Task/Sorting-algorithms-Insertion-sort/OoRexx/sorting-algorithms-insertion-sort.rexx b/Task/Sorting-algorithms-Insertion-sort/OoRexx/sorting-algorithms-insertion-sort.rexx new file mode 100644 index 0000000000..2d9ab6d03e --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/OoRexx/sorting-algorithms-insertion-sort.rexx @@ -0,0 +1,43 @@ +/* REXX program sorts a stemmed array (has characters) */ +/* using the insertion sort algorithm */ + Call gen /* fill the array with test data */ + Call show 'before sort' /* display the elements */ + Say copies('-',79) /* display a separator line */ + Call insertionSort x.0 /* invoke the insertion sort. */ + Call show ' after sort' /* display the elements after sort*/ + Exit +/*--------------------------------------------------------------------*/ +gen: Procedure Expose x. + x.1="---Monday's Child Is Fair of Face (by Mother Goose)---" + x.2="=======================================================" + x.3="Monday's child is fair of face;" + x.4="Tuesday's child is full of grace;" + x.5="Wednesday's child is full of woe;" + x.6="Thursday's child has far to go;" + x.7="Friday's child is loving and giving;" + x.8="Saturday's child works hard for a living;" + x.9="But the child that is born on the Sabbath day" + x.10="Is blithe and bonny, good and gay." + x.0=10 /* number of elements */ + Return +/*--------------------------------------------------------------------*/ +insertionsort: Procedure Expose x. + Parse Arg n + Do i=2 To n + y=x.i + Do j=i-1 By -1 To 1 While x.j>y + z=j+1 + x.z=x.j + /* Say 'set x.'z 'to x.'j '('||x.j||')' */ + End + z=j+1 + x.z=y + /* Say 'set x.'z 'to' y */ + End + Return +/*--------------------------------------------------------------------*/ +show: + Do j=1 To x.0 + Say 'Element' right(j,length(x.0)) arg(1)":" x.j + End + Return diff --git a/Task/Sorting-algorithms-Insertion-sort/Sidef/sorting-algorithms-insertion-sort.sidef b/Task/Sorting-algorithms-Insertion-sort/Sidef/sorting-algorithms-insertion-sort.sidef index 370ad4007a..e51b93f3de 100644 --- a/Task/Sorting-algorithms-Insertion-sort/Sidef/sorting-algorithms-insertion-sort.sidef +++ b/Task/Sorting-algorithms-Insertion-sort/Sidef/sorting-algorithms-insertion-sort.sidef @@ -1,17 +1,17 @@ class Array { method insertion_sort { { |i| - var j = i; - var k = self[i]; - while ((j > 0) && (k < self[j - 1])) { - self[j] = self[j - 1]; - j--; - }; - self[j] = k; - } * self.end; - return self; + var j = i-1 + var k = self[i] + while ((j >= 0) && (k < self[j])) { + self[j+1] = self[j] + j-- + } + self[j+1] = k + } << 1..self.end + return self } } -var a = 10.of {100.rand.int}; -say a.insertion_sort; +var a = 10.of { 100.irand } +say a.insertion_sort diff --git a/Task/Sorting-algorithms-Insertion-sort/Standard-ML/sorting-algorithms-insertion-sort.ml b/Task/Sorting-algorithms-Insertion-sort/Standard-ML/sorting-algorithms-insertion-sort.ml deleted file mode 100644 index 23f3642627..0000000000 --- a/Task/Sorting-algorithms-Insertion-sort/Standard-ML/sorting-algorithms-insertion-sort.ml +++ /dev/null @@ -1,10 +0,0 @@ -fun insertion_sort cmp = let - fun insert (x, []) = [x] - | insert (x, y::ys) = - case cmp (x, y) of GREATER => y :: insert (x, ys) - | _ => x :: y :: ys -in - foldl insert [] -end; - -insertion_sort Int.compare [6,8,5,9,3,2,1,4,7]; diff --git a/Task/Sorting-algorithms-Insertion-sort/Zkl/sorting-algorithms-insertion-sort-1.zkl b/Task/Sorting-algorithms-Insertion-sort/Zkl/sorting-algorithms-insertion-sort-1.zkl new file mode 100644 index 0000000000..04ca42c762 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Zkl/sorting-algorithms-insertion-sort-1.zkl @@ -0,0 +1,8 @@ +fcn insertionSort(list){ + sink:=List(); + foreach x in (list){ + if(False==(n:=sink.filter1n('>(x)))) sink.append(x); // x>all items in sink + else sink.insert(n,x); + } + sink.close(); +} diff --git a/Task/Sorting-algorithms-Insertion-sort/Zkl/sorting-algorithms-insertion-sort-2.zkl b/Task/Sorting-algorithms-Insertion-sort/Zkl/sorting-algorithms-insertion-sort-2.zkl new file mode 100644 index 0000000000..c662bc6354 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Zkl/sorting-algorithms-insertion-sort-2.zkl @@ -0,0 +1,2 @@ +insertionSort(T(4,65,2,-31,0,99,2,83,782,1)).println(); +insertionSort("big fjords vex quick waltz nymph".split()).println(); diff --git a/Task/Sorting-algorithms-Merge-sort/Astro/sorting-algorithms-merge-sort-1.astro b/Task/Sorting-algorithms-Merge-sort/Astro/sorting-algorithms-merge-sort-1.astro new file mode 100644 index 0000000000..24a77e6924 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Astro/sorting-algorithms-merge-sort-1.astro @@ -0,0 +1,15 @@ +fun mergeSort(m): + return m if m.size <= 1 + let middle = m.size / 2 + let left = merge(m[:middle]) + let right = merge(m[middle:]); + +fun merge(left, right): + let result = [] + while |left or right|.!empty: + result ++ (left.shift() if |left <= right|.first ... + else right.shift()) + result ++ left ++ right + +let arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] +print mergeSort arr diff --git a/Task/Sorting-algorithms-Merge-sort/ALGOL-68/sorting-algorithms-merge-sort-3.alg b/Task/Sorting-algorithms-Merge-sort/Astro/sorting-algorithms-merge-sort-2.astro similarity index 100% rename from Task/Sorting-algorithms-Merge-sort/ALGOL-68/sorting-algorithms-merge-sort-3.alg rename to Task/Sorting-algorithms-Merge-sort/Astro/sorting-algorithms-merge-sort-2.astro diff --git a/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort-1.c b/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort-1.c deleted file mode 100644 index 4fb5a2ab7f..0000000000 --- a/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort-1.c +++ /dev/null @@ -1,60 +0,0 @@ -#include -#include -#include - -inline -void merge(int *left, int l_len, int *right, int r_len, int *out) -{ - int i, j, k; - for (i = j = k = 0; i < l_len && j < r_len; ) - out[k++] = left[i] < right[j] ? left[i++] : right[j++]; - - while (i < l_len) out[k++] = left[i++]; - while (j < r_len) out[k++] = right[j++]; -} - -/* inner recursion of merge sort */ -void recur(int *buf, int *tmp, int len) -{ - int l = len / 2; - if (len <= 1) return; - - /* note that buf and tmp are swapped */ - recur(tmp, buf, l); - recur(tmp + l, buf + l, len - l); - - merge(tmp, l, tmp + l, len - l, buf); -} - -/* preparation work before recursion */ -void merge_sort(int *buf, int len) -{ - /* call alloc, copy and free only once */ - int *tmp = malloc(sizeof(int) * len); - memcpy(tmp, buf, sizeof(int) * len); - - recur(buf, tmp, len); - - free(tmp); -} - -int main() -{ -# define LEN 20 - int i, x[LEN]; - - for (i = 0; i < LEN; i++) - x[i] = rand() % LEN; - - puts("before sort:"); - for (i = 0; i < LEN; i++) printf("%d ", x[i]); - putchar('\n'); - - merge_sort(x, LEN); - - puts("after sort:"); - for (i = 0; i < LEN; i++) printf("%d ", x[i]); - putchar('\n'); - - return 0; -} diff --git a/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort-2.c b/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort-2.c deleted file mode 100644 index bd3c52a544..0000000000 --- a/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort-2.c +++ /dev/null @@ -1,70 +0,0 @@ -#include -#include - -typedef struct link_s *link, link_t; -struct link_s { double v; link next; }; - -const link_t fnil = { 0./0., &fnil }; // sentinel -const link const nil = &fnil; - -link list_from_array(double *a, int len) -{ - link p = nil; - while (len--) { - link pp = malloc(sizeof(*pp)); - pp->v = a[len]; - pp->next = p; - p = pp; - } - return p; -} - -void show_list(link a) -{ - for (; a != nil; a = a->next) - printf("%g ", a->v); - putchar('\n'); -} - -link merge(link a, link b) -{ - link head = &(link_t){0, nil}, tail = head; - while (a != nil && b != nil) { - link *p = a->v <= b->v ? &a : &b; - tail->next = *p; - *p = (*p)->next; - tail = tail->next; - } - tail->next = a != nil ? a : b; - return head->next; -} - -link merge_sort(link p) -{ - if (p->next == nil) return p; - - link tail = p, mid = p; - // Seek to the middle of the list. This is O(n) for list - // length, so O(n log n) complexity to overall merge sort - // that an array wouldn't have to deal with. - while (1) { - tail = tail->next->next; - if (tail == nil) break; - mid = mid->next; - } - - tail = mid->next; - mid->next = nil; - - return merge(merge_sort(p), merge_sort(tail)); -} - -int main(void) -{ - double x[] = {5,3,6,1,2,6,2,0,3,5,7,8,2,4,9}; - link p = list_from_array(x, sizeof(x)/sizeof(x[0])); - - puts("list: "); show_list(p); - puts("sort: "); show_list(merge_sort(p)); - return 0; -} diff --git a/Task/Sorting-algorithms-Merge-sort/FreeBASIC/sorting-algorithms-merge-sort.freebasic b/Task/Sorting-algorithms-Merge-sort/FreeBASIC/sorting-algorithms-merge-sort.freebasic new file mode 100644 index 0000000000..2861bfa06c --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/FreeBASIC/sorting-algorithms-merge-sort.freebasic @@ -0,0 +1,74 @@ +' FB 1.05.0 Win64 + +Sub copyArray(a() As Integer, iBegin As Integer, iEnd As Integer, b() As Integer) + Redim b(iBegin To iEnd - 1) As Integer + For k As Integer = iBegin To iEnd - 1 + b(k) = a(k) + Next +End Sub + +' Left source half is a(iBegin To iMiddle-1). +' Right source half is a(iMiddle To iEnd-1). +' Result is b(iBegin To iEnd-1). +Sub topDownMerge(a() As Integer, iBegin As Integer, iMiddle As Integer, iEnd As Integer, b() As Integer) + Dim i As Integer = iBegin + Dim j As Integer = iMiddle + + ' While there are elements in the left or right runs... + For k As Integer = iBegin To iEnd - 1 + ' If left run head exists and is <= existing right run head. + If i < iMiddle AndAlso (j >= iEnd OrElse a(i) <= a(j)) Then + b(k) = a(i) + i += 1 + Else + b(k) = a(j) + j += 1 + End If + Next +End Sub + +' Sort the given run of array a() using array b() as a source. +' iBegin is inclusive; iEnd is exclusive (a(iEnd) is not in the set). +Sub topDownSplitMerge(b() As Integer, iBegin As Integer, iEnd As Integer, a() As Integer) + If (iEnd - iBegin) < 2 Then Return '' If run size = 1, consider it sorted + ' split the run longer than 1 item into halves + Dim iMiddle As Integer = (iEnd + iBegin) \ 2 '' iMiddle = mid point + ' recursively sort both runs from array a() into b() + topDownSplitMerge(a(), iBegin, iMiddle, b()) '' sort the left run + topDownSplitMerge(a(), iMiddle, iEnd, b()) '' sort the right run + ' merge the resulting runs from array b() into a() + topDownMerge(b(), iBegin, iMiddle, iEnd, a()) +End Sub + +' Array a() has the items to sort; array b() is a work array (empty initially). +Sub topDownMergeSort(a() As Integer, b() As Integer, n As Integer) + copyArray(a(), 0, n, b()) '' duplicate array a() into b() + topDownSplitMerge(b(), 0, n, a()) '' sort data from b() into a() +End Sub + +Sub printArray(a() As Integer) + For i As Integer = LBound(a) To UBound(a) + Print Using "####"; a(i); + Next + Print +End Sub + +Dim a(0 To 9) As Integer = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1} + +Dim b() As Integer +Print "Unsorted : "; +printArray(a()) +topDownMergeSort a(), b(), 10 +Print "Sorted : "; +printArray(a()) +Print +Dim a2(0 To 8) As Integer = {7, 5, 2, 6, 1, 4, 2, 6, 3} +Erase b +Print "Unsorted : "; +printArray(a2()) +topDownMergeSort a2(), b(), 9 +Print "Sorted : "; +printArray(a2()) +Print +Print "Press any key to quit" +Sleep diff --git a/Task/Sorting-algorithms-Merge-sort/jq/sorting-algorithms-merge-sort-1.jq b/Task/Sorting-algorithms-Merge-sort/Jq/sorting-algorithms-merge-sort-1.jq similarity index 100% rename from Task/Sorting-algorithms-Merge-sort/jq/sorting-algorithms-merge-sort-1.jq rename to Task/Sorting-algorithms-Merge-sort/Jq/sorting-algorithms-merge-sort-1.jq diff --git a/Task/Sorting-algorithms-Merge-sort/jq/sorting-algorithms-merge-sort-2.jq b/Task/Sorting-algorithms-Merge-sort/Jq/sorting-algorithms-merge-sort-2.jq similarity index 100% rename from Task/Sorting-algorithms-Merge-sort/jq/sorting-algorithms-merge-sort-2.jq rename to Task/Sorting-algorithms-Merge-sort/Jq/sorting-algorithms-merge-sort-2.jq diff --git a/Task/Sorting-algorithms-Merge-sort/Sidef/sorting-algorithms-merge-sort.sidef b/Task/Sorting-algorithms-Merge-sort/Sidef/sorting-algorithms-merge-sort.sidef index eb114abd37..b7b6542014 100644 --- a/Task/Sorting-algorithms-Merge-sort/Sidef/sorting-algorithms-merge-sort.sidef +++ b/Task/Sorting-algorithms-Merge-sort/Sidef/sorting-algorithms-merge-sort.sidef @@ -1,29 +1,27 @@ func merge(left, right) { - var result = []; - while (!left.is_empty && !right.is_empty) { - result.append([right,left][left.first <= right.first].shift); - }; - result + left + right; + var result = [] + while (left && right) { + result << [right,left].min_by{.first}.shift + } + result + left + right }   func mergesort(array) { - var len = array.len; - len < 2 && return array; + var len = array.len + len < 2 && return array   - var mid = (len/2 -> int); - var left = array.ft(0, mid-1); - var right = array.ft(mid); + var (left, right) = array.part(len//2)   - left = __FUNC__(left); - right = __FUNC__(right); + left = __FUNC__(left) + right = __FUNC__(right)   - merge(left, right); + merge(left, right) }   # Numeric sort -var nums = (0..7 -> shuffle); -say mergesort(nums); +var nums = rand(1..100, 10) +say mergesort(nums)   # String sort -var strings = ('a'..'e' -> shuffle); -say mergesort(strings); +var strings = rand('a'..'z', 10) +say mergesort(strings) diff --git a/Task/Sorting-algorithms-Merge-sort/Zkl/sorting-algorithms-merge-sort-1.zkl b/Task/Sorting-algorithms-Merge-sort/Zkl/sorting-algorithms-merge-sort-1.zkl new file mode 100644 index 0000000000..e3b5ee3a84 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Zkl/sorting-algorithms-merge-sort-1.zkl @@ -0,0 +1,13 @@ +fcn _merge(left,right){ + if (not left) return(right); + if (not right) return(left); + l:=left[0]; r:=right[0]; + if (l<=r) return(L(l).extend(self.fcn(left[1,*],right))); + else return(L(r).extend(self.fcn(left,right[1,*]))); +} + +fcn merge_sort(L){ + if (L.len()<2) return(L); + n:=L.len()/2; + return(_merge(self.fcn(L[0,n]), self.fcn(L[n,*]))); +} diff --git a/Task/Sorting-algorithms-Merge-sort/Zkl/sorting-algorithms-merge-sort-2.zkl b/Task/Sorting-algorithms-Merge-sort/Zkl/sorting-algorithms-merge-sort-2.zkl new file mode 100644 index 0000000000..24d8d85d71 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Zkl/sorting-algorithms-merge-sort-2.zkl @@ -0,0 +1,2 @@ +merge_sort(T(1,3,5,7,9,8,6,4,2)).println(); +merge_sort("big fjords vex quick waltz nymph").concat().println(); diff --git a/Task/Sorting-algorithms-Merge-sort/Zkl/sorting-algorithms-merge-sort-3.zkl b/Task/Sorting-algorithms-Merge-sort/Zkl/sorting-algorithms-merge-sort-3.zkl new file mode 100644 index 0000000000..7eb366dde7 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Zkl/sorting-algorithms-merge-sort-3.zkl @@ -0,0 +1,5 @@ +fcn mergeSort(L){ + if (L.len()<2) return(L.copy()); + n:=L.len()/2; + self.fcn(L[0,n]).merge(self.fcn(L[n,*])); +} diff --git a/Task/Sorting-algorithms-Merge-sort/Zkl/sorting-algorithms-merge-sort-4.zkl b/Task/Sorting-algorithms-Merge-sort/Zkl/sorting-algorithms-merge-sort-4.zkl new file mode 100644 index 0000000000..f14428d36a --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Zkl/sorting-algorithms-merge-sort-4.zkl @@ -0,0 +1,2 @@ +mergeSort(T(1,3,5,7,9,8,6,4,2)).println(); +mergeSort("big fjords vex quick waltz nymph".split("")).concat().println(); diff --git a/Task/Sorting-algorithms-Pancake-sort/Batch-File/sorting-algorithms-pancake-sort.bat b/Task/Sorting-algorithms-Pancake-sort/Batch-File/sorting-algorithms-pancake-sort.bat deleted file mode 100644 index 7609b2ae39..0000000000 --- a/Task/Sorting-algorithms-Pancake-sort/Batch-File/sorting-algorithms-pancake-sort.bat +++ /dev/null @@ -1,82 +0,0 @@ -::Pancake Sort -::Batch File Implementation -:: -::Using the "Classic XOR trick" to swap integer values of two variables... -::...IF the variable names are different... - -@echo off -setlocal enabledelayedexpansion - -::Initial Values and Variables -set "range=0" -set "output=" -set "list=-2 0 -1 5 2 7 4 3 6 -1 7 2 1 8" - ::Put the sequence of integers (ONLY) on the list variable. - ::Please do not "play" with the list variable. - ::or else the code will not work or crash. - -for %%l in (!list!) do ( - set num!range!=%%l - set /a range+=1 -) -set /a range-=1 - -::Scramble -for /l %%l in (%range%,-1,1) do ( - set /a n=^(%random% %% %%l^) - set /a num%%l^^^^=num!n! - set /a num!n!^^^^=num%%l - set /a num%%l^^^^=num!n! -) -::/Scramble (Remove this if you do not want to scramble the integers) - -::Display initial condition -for /l %%l in (0,1,%range%) do set "output=!output! !num%%l!" -echo.Initial Sequence: -echo. -echo. ^>^> !output! -echo. -echo Sorting: -echo. - - ::Sort begins! -for /l %%m in (%range%,-1,1) do ( - set n=0 - for /l %%l in (1,1,%%m) do ( - set /a tmp_var1=num!n! - if !tmp_var1! lss !num%%l! set n=%%l - ) - if !n! lss %%m ( - if !n! gtr 0 ( - set /a tmp_var1=!n!/2 - for /l %%l in (0,1,!tmp_var1!) do ( - set /a tmp_var2=!n!-%%l - if !tmp_var2! neq %%l ( - set /a num!tmp_var2!^^^^=num%%l - set /a num%%l^^^^=num!tmp_var2! - set /a num!tmp_var2!^^^^=num%%l - ) - ) - set output= - for /l %%x in (0,1,%range%) do set "output=!output! !num%%x!" - echo. ^>^> !output! - ) - set /a tmp_var3=%%m/2 - for /l %%l in (0,1,!tmp_var3!) do ( - set /a tmp_var4=%%m-%%l - if !tmp_var4! neq %%l ( - set /a num!tmp_var4!^^^^=num%%l - set /a num%%l^^^^=num!tmp_var4! - set /a num!tmp_var4!^^^^=num%%l - ) - ) - set output= - for /l %%x in (0,1,%range%) do set "output=!output! !num%%x!" - echo. ^>^> !output! - ) - ) - -) - ::We are done. - echo DONE^^! - exit /b 0 diff --git a/Task/Sorting-algorithms-Pancake-sort/FreeBASIC/sorting-algorithms-pancake-sort.freebasic b/Task/Sorting-algorithms-Pancake-sort/FreeBASIC/sorting-algorithms-pancake-sort.freebasic new file mode 100644 index 0000000000..624c5a783c --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/FreeBASIC/sorting-algorithms-pancake-sort.freebasic @@ -0,0 +1,104 @@ +' version 11-04-2017 +' compile with: fbc -s console +' for boundry checks on array's compile with: fbc -s console -exx + +' direction = 1, (default) sort ascending +' direction <> 1 sort descending +' show = 0, (default) do not show sorting +' show <> 0, show sorting +Sub pancake_sort(a() As Long,direction As Long = 1, show As Long = 0) + ' array's can have subscript range from -2147483648 to +2147483647 + Dim As Long i, j, n + Dim As Long lb = LBound(a) + Dim As Long ub = UBound(a) + + If show <> 0 Then ' show initial state + For j = lb To ub + Print Using "####"; a(j); + Next + Print + End If + + For i = ub To lb +1 Step -1 + + n = lb + For j = lb +1 To i + If direction = 1 Then + If a(n) < a(j) Then n = j + Else + If a(n) > a(j) Then n = j + End If + Next + + If n < i Then + If n > lb Then + For j = lb To lb + ((n - lb) \ 2) + Swap a(j), a(lb + n - j) + Next + + If show <> 0 Then + For j = lb To ub + Print Using "####"; a(j); + Next + Print + End If + + End If + + For j = lb To lb + ((i - lb) \ 2) + Swap a(j), a(lb + i - j) + Next + + If show <> 0 Then + For j = lb To ub + Print Using "####"; a(j); + Next + Print + End If + + End If + Next + +End Sub + +' ------=< MAIN >=------ + +Dim As Long i, array(-7 To 7) +Dim As Long lb = LBound(array) +Dim As Long ub = UBound(array) + +Randomize Timer +For i = lb To ub : array(i) = i : Next +For i = lb To ub ' little shuffle + Swap array(i), array(Int(Rnd * (ub - lb +1) + lb)) +Next + +Print "unsorted "; +For i = lb To ub + Print Using "####"; array(i); +Next +Print : Print + +pancake_sort(array()) + +Print " sorted "; +For i = lb To ub + Print Using "####"; array(i); +Next + +Print : Print +Dim As Long l(10 To ...) = {0, -30, 20, -10, 0, 10, -20} + +pancake_sort(l(),0,1) ' sort array l, ascending and show process + +Print : Print " sorted l()"; +For i = LBound(l) To UBound(l) + Print Using "####"; l(i); +Next +Print + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Sorting-algorithms-Pancake-sort/jq/sorting-algorithms-pancake-sort-1.jq b/Task/Sorting-algorithms-Pancake-sort/Jq/sorting-algorithms-pancake-sort-1.jq similarity index 100% rename from Task/Sorting-algorithms-Pancake-sort/jq/sorting-algorithms-pancake-sort-1.jq rename to Task/Sorting-algorithms-Pancake-sort/Jq/sorting-algorithms-pancake-sort-1.jq diff --git a/Task/Sorting-algorithms-Pancake-sort/jq/sorting-algorithms-pancake-sort-2.jq b/Task/Sorting-algorithms-Pancake-sort/Jq/sorting-algorithms-pancake-sort-2.jq similarity index 100% rename from Task/Sorting-algorithms-Pancake-sort/jq/sorting-algorithms-pancake-sort-2.jq rename to Task/Sorting-algorithms-Pancake-sort/Jq/sorting-algorithms-pancake-sort-2.jq diff --git a/Task/Sorting-algorithms-Pancake-sort/jq/sorting-algorithms-pancake-sort-3.jq b/Task/Sorting-algorithms-Pancake-sort/Jq/sorting-algorithms-pancake-sort-3.jq similarity index 100% rename from Task/Sorting-algorithms-Pancake-sort/jq/sorting-algorithms-pancake-sort-3.jq rename to Task/Sorting-algorithms-Pancake-sort/Jq/sorting-algorithms-pancake-sort-3.jq diff --git a/Task/Sorting-algorithms-Pancake-sort/Kotlin/sorting-algorithms-pancake-sort.kotlin b/Task/Sorting-algorithms-Pancake-sort/Kotlin/sorting-algorithms-pancake-sort.kotlin new file mode 100644 index 0000000000..7bce326988 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Kotlin/sorting-algorithms-pancake-sort.kotlin @@ -0,0 +1,43 @@ +// version 1.1.2 + +class PancakeSort(private val a: IntArray) { + init { + for (n in a.size downTo 2) { // successively reduce size of array by 1 + val index = indexOfMax(n) // find index of largest + if (index != n - 1) { // if it's not already at the end + if (index > 0) { // if it's not already at the beginning + flip(index) // move largest to beginning + println("${a.contentToString()} after flipping first ${index + 1}") + } + flip(n - 1) // move largest to end + println("${a.contentToString()} after flipping first $n") + } + } + } + + private fun indexOfMax(n: Int): Int { + var index = 0 + for (i in 1 until n) { + if (a[i] > a[index]) index = i + } + return index + } + + private fun flip(index: Int) { + var i = index + var j = 0 + while (j < i) { + val temp = a[j] + a[j] = a[i] + a[i] = temp + j++ + i-- + } + } +} + +fun main(args: Array) { + val a = intArrayOf(7, 6, 9, 2, 4, 8, 1, 3, 5) + println("${a.contentToString()} initially") + PancakeSort(a) +} diff --git a/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx b/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx index 4a3f3e76a9..5113563d4b 100644 --- a/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx +++ b/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx @@ -6,17 +6,18 @@ call pancakeSort # /*invoke the pancake sort. call show ' after sort' /*display the AFTER array elements. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -flip: parse arg y; do i=1 for (y+1)%2; yyy=y-i+1; _=@.i; @.i=@.yyy; @.yyy=_; end - return /*swap: ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ */ +flip: parse arg y; do i=1 for (y+1)%2; yyy=y-i+1; _=@.i; @.i=@.yyy; @.yyy=_; end; return +show: do k=1 for #; say @element right(k,length(#)) arg(1)':' right(@.k,9); end; return /*──────────────────────────────────────────────────────────────────────────────────────*/ gen: fibs= '-55 -21 -1 -8 -8 -21 -55 0 0' /*some non─positive Fibonacci numbers, */ - @element=right('element',21) /* most of which are repeated. - ┌◄─┬──◄─ some paired bread primes which are of the form: (p-3)÷2 and 2∙p+3 - │ │ where p is a prime. Bread primes are related to sandwich & meat primes. - ↓ ↓ ──── ──── ───── ────── ────── ────── ────── ─────── ─────── ─────── ──────*/ + @element= right('element', 21) /* most Fibs of which are repeated.*/ + + /* ┌◄─┬──◄─ some paired bread primes which are of the form: (P-3)÷2 and 2∙P+3 */ + /* │ │ where P is a prime. Bread primes are related to sandwich & meat primes*/ + /* ↓ ↓ ──── ──── ───── ────── ────── ────── ────── ─────── ─────── ─────── ──────*/ bp=2 17 5 29 7 37 13 61 43 181 47 197 67 277 97 397 113 461 137 557 167 677 173 701, 797 1117 307 1237 1597 463 1861 467 - $=bp fibs; #=words($) /*combine the two lists; get # of items*/ + $=bp fibs; #=words($) /*combine the two lists; get # of items*/ do j=1 for #; @.j=word($,j); end /*◄─── obtain a number from the $ list.*/ return /* [↑] populate the @. array with #s*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ @@ -28,5 +29,3 @@ pancakeSort: procedure expose @.; parse arg N call flip ?; call flip N end /*N*/ return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -show: do k=1 for #; say @element right(k,length(#)) arg(1)':' right(@.k,9); end; return diff --git a/Task/Sorting-algorithms-Pancake-sort/Zkl/sorting-algorithms-pancake-sort-1.zkl b/Task/Sorting-algorithms-Pancake-sort/Zkl/sorting-algorithms-pancake-sort-1.zkl new file mode 100644 index 0000000000..a251c0a5d5 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Zkl/sorting-algorithms-pancake-sort-1.zkl @@ -0,0 +1,7 @@ +fcn pancakeSort(a){ + foreach i in ([a.len()-1..1,-1]){ + j := a.index((0).max(a[0,i+1])); // min for decending sort + if(i != j){ a.swap(0,j); a.swap(0,i); } + } + a +} diff --git a/Task/Sorting-algorithms-Pancake-sort/Zkl/sorting-algorithms-pancake-sort-2.zkl b/Task/Sorting-algorithms-Pancake-sort/Zkl/sorting-algorithms-pancake-sort-2.zkl new file mode 100644 index 0000000000..dfd77bd7fb --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Zkl/sorting-algorithms-pancake-sort-2.zkl @@ -0,0 +1 @@ + j := (i+1).reduce('wrap(x,y){ if(a[x]>a[y]) x else y }); diff --git a/Task/Sorting-algorithms-Pancake-sort/Zkl/sorting-algorithms-pancake-sort-3.zkl b/Task/Sorting-algorithms-Pancake-sort/Zkl/sorting-algorithms-pancake-sort-3.zkl new file mode 100644 index 0000000000..d0f7f0c3d3 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Zkl/sorting-algorithms-pancake-sort-3.zkl @@ -0,0 +1 @@ +pancakeSort(List(7,6,9,2,4,8,1,3,5)).println(); diff --git a/Task/Sorting-algorithms-Permutation-sort/FreeBASIC/sorting-algorithms-permutation-sort.freebasic b/Task/Sorting-algorithms-Permutation-sort/FreeBASIC/sorting-algorithms-permutation-sort.freebasic new file mode 100644 index 0000000000..94ba30fe3a --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/FreeBASIC/sorting-algorithms-permutation-sort.freebasic @@ -0,0 +1,59 @@ +' version 07-04-2017 +' compile with: fbc -s console + +' Heap's algorithm non-recursive +Function permutation_sort(a() As ULong) As ULong + + Dim As ULong i, j, count + Dim As ULong lb = LBound(a), ub = UBound(a) + Dim As ULong n = ub - lb +1 + Dim As ULong c(lb To ub) + + While i < n + If c(i) < i Then + If (i And 1) = 0 Then + Swap a(0), a(i) + Else + Swap a(c(i)), a(i) + End If + count += 1 + For j = lb To ub -1 + If a(j) > a(j +1) Then j = 99 + Next + If j < 99 Then Return count + c(i) += 1 + i = 0 + Else + c(i) = 0 + i += 1 + End If + Wend + +End Function + +' ------=< MAIN >=------ + +Dim As ULong k, p, arr(0 To 9) +Randomize Timer + +Print "unsorted array" +For k = LBound(arr) To UBound(arr) + arr(k) = Rnd * 1000 + Print arr(k) & IIf(k = UBound(arr), "", ", "); +Next +Print : Print + +p = permutation_sort(arr()) + +Print "sorted array" +For k = LBound(arr) To UBound(arr) + Print arr(k) & IIf(k = UBound(arr), "", ", "); +Next +Print : Print +Print "sorted array in "; p; " permutations" + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Sorting-algorithms-Permutation-sort/jq/sorting-algorithms-permutation-sort-1.jq b/Task/Sorting-algorithms-Permutation-sort/Jq/sorting-algorithms-permutation-sort-1.jq similarity index 100% rename from Task/Sorting-algorithms-Permutation-sort/jq/sorting-algorithms-permutation-sort-1.jq rename to Task/Sorting-algorithms-Permutation-sort/Jq/sorting-algorithms-permutation-sort-1.jq diff --git a/Task/Sorting-algorithms-Permutation-sort/jq/sorting-algorithms-permutation-sort-2.jq b/Task/Sorting-algorithms-Permutation-sort/Jq/sorting-algorithms-permutation-sort-2.jq similarity index 100% rename from Task/Sorting-algorithms-Permutation-sort/jq/sorting-algorithms-permutation-sort-2.jq rename to Task/Sorting-algorithms-Permutation-sort/Jq/sorting-algorithms-permutation-sort-2.jq diff --git a/Task/Sorting-algorithms-Permutation-sort/jq/sorting-algorithms-permutation-sort-3.jq b/Task/Sorting-algorithms-Permutation-sort/Jq/sorting-algorithms-permutation-sort-3.jq similarity index 100% rename from Task/Sorting-algorithms-Permutation-sort/jq/sorting-algorithms-permutation-sort-3.jq rename to Task/Sorting-algorithms-Permutation-sort/Jq/sorting-algorithms-permutation-sort-3.jq diff --git a/Task/Sorting-algorithms-Permutation-sort/jq/sorting-algorithms-permutation-sort-4.jq b/Task/Sorting-algorithms-Permutation-sort/Jq/sorting-algorithms-permutation-sort-4.jq similarity index 100% rename from Task/Sorting-algorithms-Permutation-sort/jq/sorting-algorithms-permutation-sort-4.jq rename to Task/Sorting-algorithms-Permutation-sort/Jq/sorting-algorithms-permutation-sort-4.jq diff --git a/Task/Sorting-algorithms-Permutation-sort/jq/sorting-algorithms-permutation-sort-5.jq b/Task/Sorting-algorithms-Permutation-sort/Jq/sorting-algorithms-permutation-sort-5.jq similarity index 100% rename from Task/Sorting-algorithms-Permutation-sort/jq/sorting-algorithms-permutation-sort-5.jq rename to Task/Sorting-algorithms-Permutation-sort/Jq/sorting-algorithms-permutation-sort-5.jq diff --git a/Task/Sorting-algorithms-Permutation-sort/jq/sorting-algorithms-permutation-sort-6.jq b/Task/Sorting-algorithms-Permutation-sort/Jq/sorting-algorithms-permutation-sort-6.jq similarity index 100% rename from Task/Sorting-algorithms-Permutation-sort/jq/sorting-algorithms-permutation-sort-6.jq rename to Task/Sorting-algorithms-Permutation-sort/Jq/sorting-algorithms-permutation-sort-6.jq 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.julia new file mode 100644 index 0000000000..61454a6780 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Julia/sorting-algorithms-permutation-sort.julia @@ -0,0 +1,14 @@ +# v0.6 + +using Combinatorics + +function permsort(x::Array) + for perm in permutations(x) + if issorted(perm) + return perm + end + end +end + +x = randn(10) +@show x permsort(x) 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.kotlin new file mode 100644 index 0000000000..2194984cc0 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Kotlin/sorting-algorithms-permutation-sort.kotlin @@ -0,0 +1,49 @@ +// version 1.1.2 + +fun > isSorted(list: List): Boolean { + val size = list.size + if (size < 2) return true + for (i in 1 until size) { + if (list[i] < list[i - 1]) return false + } + return true +} + +fun > permute(input: List): List> { + if (input.size == 1) return listOf(input) + val perms = mutableListOf>() + val toInsert = input[0] + for (perm in permute(input.drop(1))) { + for (i in 0..perm.size) { + val newPerm = perm.toMutableList() + newPerm.add(i, toInsert) + perms.add(newPerm) + } + } + return perms +} + +fun > permutationSort(input: List): List { + if (input.size == 1) return input + val toInsert = input[0] + for (perm in permute(input.drop(1))) { + for (i in 0..perm.size) { + val newPerm = perm.toMutableList() + newPerm.add(i, toInsert) + if (isSorted(newPerm)) return newPerm + } + } + return input +} + +fun main(args: Array) { + val input = listOf('d', 'b', 'e', 'a', 'f', 'c') + println("Before sorting : $input") + val output = permutationSort(input) + println("After sorting : $output") + println() + val input2 = listOf("first", "second", "third", "fourth", "fifth", "sixth") + println("Before sorting : $input2") + val output2 = permutationSort(input2) + println("After sorting : $output2") +} diff --git a/Task/Sorting-algorithms-Permutation-sort/Lua/sorting-algorithms-permutation-sort.lua b/Task/Sorting-algorithms-Permutation-sort/Lua/sorting-algorithms-permutation-sort.lua new file mode 100644 index 0000000000..14a0868065 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Lua/sorting-algorithms-permutation-sort.lua @@ -0,0 +1,30 @@ +-- Return an iterator to produce every permutation of list +function permute (list) + local function perm (list, n) + if n == 0 then coroutine.yield(list) end + for i = 1, n do + list[i], list[n] = list[n], list[i] + perm(list, n - 1) + list[i], list[n] = list[n], list[i] + end + end + return coroutine.wrap(function() perm(list, #list) end) +end + +-- Return true if table t is in ascending order or false if not +function inOrder (t) + for pos = 2, #t do + if t[pos] < t[pos - 1] then + return false + end + end + return true +end + +-- Main procedure +local list = {2,3,1} --\ Written to match task pseudocode, +local nextPermutation = permute(list) --\ more idiomatic would be: +while not inOrder(list) do --\ + list = nextPermutation() --/ for p in permute(list) do +end --/ stuffWith(p) +print(unpack(list)) --/ end diff --git a/Task/Sorting-algorithms-Permutation-sort/REXX/sorting-algorithms-permutation-sort.rexx b/Task/Sorting-algorithms-Permutation-sort/REXX/sorting-algorithms-permutation-sort.rexx index c96cfe7578..a84285bdf3 100644 --- a/Task/Sorting-algorithms-Permutation-sort/REXX/sorting-algorithms-permutation-sort.rexx +++ b/Task/Sorting-algorithms-Permutation-sort/REXX/sorting-algorithms-permutation-sort.rexx @@ -1,53 +1,43 @@ /*REXX program sorts and displays an array using the permutation-sort method. */ -call gen@ /*generate the array elements. */ -call show@ 'before sort' /*show the before array elements. */ -say copies('▒', 70) /*show separator line between displays.*/ -call permsets L /*generate items (!) permutations. */ -call permSort L /*invoke the permutation sort. */ -call show@ ' after sort' /*show the after array elements. */ -say; say 'Permutation sort took' ? "permutations to find the sorted list." +call gen /*generate the array elements. */ +call show 'before sort' /*show the before array elements. */ +say copies('░', 75) /*show separator line between displays.*/ +call pSort L /*invoke the permutation sort. */ +call show ' after sort' /*show the after array elements. */ +say; say 'Permutation sort took ' ? " permutations to find the sorted list." exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -gen@: @.=; @.1= '---Four_horsemen_of_the_Apocalypse---' - @.2= '=====================================' - @.3= 'Famine───black_horse' - @.4= 'Death───pale_horse' - @.5= 'Pestilence_[Slaughter]───red_horse' - @.6= 'Conquest_[War]───white_horse' - /* [↓] also assign to another array. */ - do L=1 while @.L\==''; @@.L=@.L; end /* [↓] find number of entries in array*/ - L=L-1 /*adjust the number of items by one. */ - return +.pAdd: #=#+1; do j=1 for N; #.#=#.# !.j; end; return /*add a permutation.*/ +show: do j=1 for L; say @e right(j,wL) arg(1)":" translate(@.j,,'_'); end; return /*──────────────────────────────────────────────────────────────────────────────────────*/ -inOrder: parse arg q /*see if Q list is in order.*/ - _=word(q,1); do j=2 to words(q); x=word(q,j) - if x<_ then return 0 /*Out of order? Not sorted. */ - _=x - end /*j*/ - do k=1 for #; _=word(#.?,k); @.k=@@._; end /*k*/ - return 1 /*they're all in order finally*/ +gen: @.=; @.1 = '---Four_horsemen_of_the_Apocalypse---' + @.2 = '=====================================' + @.3 = 'Famine───black_horse' + @.4 = 'Death───pale_horse' + @.5 = 'Pestilence_[Slaughter]───red_horse' + @.6 = 'Conquest_[War]───white_horse' + @e=right('element', 15) /*literal used for the display.*/ + do L=1 while @.L\==''; @@.L=@.L; end; L=L-1; wL=length(L); return /*──────────────────────────────────────────────────────────────────────────────────────*/ -.permAdd: #=#+1; do j=1 for N; #.#=#.# !.j; end /*j*/; return +isOrd: parse arg q /*see if Q list is in order. */ + _=word(q, 1); do j=2 to words(q); x=word(q, j); if x<_ then return 0; _=x + end /*j*/ /* [↑] Out of order? ¬sorted*/ + do k=1 for #; _=word(#.?, k); @.k=@@._; end /*k*/; return 1 /*in order.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ -.permNext: procedure expose !.; parse arg n,i; nm=n-1 - do k=nm by -1 for nm; kp=k+1 - if !.kn)return(Void.Stop); cnt.inc(); n }); + if(cnt.value==len) return(ns); + } +}(rns).println(); diff --git a/Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort-1.alg b/Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort.alg similarity index 100% rename from Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort-1.alg rename to Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort.alg diff --git a/Task/Sorting-algorithms-Quicksort/ALGOL-W/sorting-algorithms-quicksort-1.alg b/Task/Sorting-algorithms-Quicksort/ALGOL-W/sorting-algorithms-quicksort-1.alg new file mode 100644 index 0000000000..3006b53b2f --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/ALGOL-W/sorting-algorithms-quicksort-1.alg @@ -0,0 +1,26 @@ +% Quicksorts in-place the array of integers v, from lb to ub % +procedure quicksort ( integer array v( * ) + ; integer value lb, ub + ) ; +if ub > lb then begin + % more than one element, so must sort % + integer left, right, pivot; + left := lb; + right := ub; + % choosing the middle element of the array as the pivot % + pivot := v( left + ( ( right + 1 ) - left ) div 2 ); + while begin + while left <= ub and v( left ) < pivot do left := left + 1; + while right >= lb and v( right ) > pivot do right := right - 1; + left <= right + end do begin + integer swap; + swap := v( left ); + v( left ) := v( right ); + v( right ) := swap; + left := left + 1; + right := right - 1 + end while_left_le_right ; + quicksort( v, lb, right ); + quicksort( v, left, ub ) +end quicksort ; diff --git a/Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort-2.alg b/Task/Sorting-algorithms-Quicksort/ALGOL-W/sorting-algorithms-quicksort-2.alg similarity index 100% rename from Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort-2.alg rename to Task/Sorting-algorithms-Quicksort/ALGOL-W/sorting-algorithms-quicksort-2.alg diff --git a/Task/Sorting-algorithms-Quicksort/AppleScript/sorting-algorithms-quicksort-1.applescript b/Task/Sorting-algorithms-Quicksort/AppleScript/sorting-algorithms-quicksort-1.applescript index a41d0374a2..7209023432 100644 --- a/Task/Sorting-algorithms-Quicksort/AppleScript/sorting-algorithms-quicksort-1.applescript +++ b/Task/Sorting-algorithms-Quicksort/AppleScript/sorting-algorithms-quicksort-1.applescript @@ -5,9 +5,9 @@ on quickSort(xs) -- lessOrEqual :: a -> Bool script lessOrEqual - on lambda(x) + on |λ|(x) x ≤ h - end lambda + end |λ| end script set {less, more} to partition(lessOrEqual, t) @@ -19,7 +19,7 @@ on quickSort(xs) end quickSort --- TEST +-- TEST ----------------------------------------------------------------------- on run quickSort([11.8, 14.1, 21.3, 8.5, 16.7, 5.7]) @@ -29,8 +29,7 @@ on run end run - --- GENERIC FUNCTIONS +-- GENERIC FUNCTIONS ---------------------------------------------------------- -- partition :: predicate -> List -> (Matches, nonMatches) -- partition :: (a -> Bool) -> [a] -> ([a], [a]) @@ -39,7 +38,7 @@ on partition(f, xs) set lst to {{}, {}} repeat with x in xs set v to contents of x - set end of item ((lambda(v) as integer) + 1) of lst to v + set end of item ((|λ|(v) as integer) + 1) of lst to v end repeat return {item 2 of lst, item 1 of lst} end tell @@ -61,7 +60,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort-1.c b/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort-1.c new file mode 100644 index 0000000000..99c4f72429 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort-1.c @@ -0,0 +1,44 @@ +#include + +void quicksort(int *A, int len); + +int main (void) { + int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; + int n = sizeof a / sizeof a[0]; + + int i; + for (i = 0; i < n; i++) { + printf("%d ", a[i]); + } + printf("\n"); + + quicksort(a, n); + + for (i = 0; i < n; i++) { + printf("%d ", a[i]); + } + printf("\n"); + + return 0; +} + +void quicksort(int *A, int len) { + if (len < 2) return; + + int pivot = A[len / 2]; + + int i, j; + for (i = 0, j = len - 1; ; i++, j--) { + while (A[i] < pivot) i++; + while (A[j] > pivot) j--; + + if (i >= j) break; + + int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } + + quicksort(A, i); + quicksort(A + i, len - i); +} diff --git a/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort-2.c b/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort-2.c new file mode 100644 index 0000000000..336f5712da --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort-2.c @@ -0,0 +1,29 @@ +#include // REQ: rand() + +void swap(int *a, int *b) { + int c = *a; + *a = *b; + *b = c; +} + +int partition(int A[], int p, int q) { + swap(&A[p + (rand() % (q - p + 1))], &A[q]); // PIVOT = A[q] + + int i = p - 1; + for(int j = p; j <= q; j++) { + if(A[j] <= A[q]) { + swap(&A[++i], &A[j]); + } + } + + return i; +} + +void quicksort(int A[], int p, int q) { + if(p < q) { + int pivotIndx = partition(A, p, q); + + quicksort(A, p, pivotIndx - 1); + quicksort(A, pivotIndx + 1, q); + } +} diff --git a/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort.c b/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort.c deleted file mode 100644 index 94f3314525..0000000000 --- a/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort.c +++ /dev/null @@ -1,33 +0,0 @@ -#include - -void quick_sort (int *a, int n) { - int i, j, p, t; - if (n < 2) - return; - p = a[n / 2]; - for (i = 0, j = n - 1;; i++, j--) { - while (a[i] < p) - i++; - while (p < a[j]) - j--; - if (i >= j) - break; - t = a[i]; - a[i] = a[j]; - a[j] = t; - } - quick_sort(a, i); - quick_sort(a + i, n - i); -} - -int main (void) { - int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; - int n = sizeof a / sizeof a[0]; - int i; - for (i = 0; i < n; i++) - printf("%d%s", a[i], i == n - 1 ? "\n" : " "); - quick_sort(a, n); - for (i = 0; i < n; i++) - printf("%d%s", a[i], i == n - 1 ? "\n" : " "); - return 0; -} diff --git a/Task/Sorting-algorithms-Quicksort/Elixir/sorting-algorithms-quicksort.elixir b/Task/Sorting-algorithms-Quicksort/Elixir/sorting-algorithms-quicksort.elixir index 17760b5e44..808bf09605 100644 --- a/Task/Sorting-algorithms-Quicksort/Elixir/sorting-algorithms-quicksort.elixir +++ b/Task/Sorting-algorithms-Quicksort/Elixir/sorting-algorithms-quicksort.elixir @@ -1,9 +1,12 @@ defmodule QuickSort do - def qsort([]) do - [] + def qsort([]), do: [] + + def qsort([_|_] = list) do + List.flatten do_qsort(list) end - def qsort([pivot | rest]) do - { left, right } = Enum.partition(rest, fn(x) -> x < pivot end) - qsort(left) ++ [pivot] ++ qsort(right) + + defp do_qsort([pivot | rest]) do + {left, right} = Enum.split_with(rest, &(&1 < pivot)) + [qsort(left), pivot, qsort(right)] end end diff --git a/Task/Sorting-algorithms-Quicksort/Erlang/sorting-algorithms-quicksort-2.erl b/Task/Sorting-algorithms-Quicksort/Erlang/sorting-algorithms-quicksort-2.erl index 30e96cf910..dec8c12ccc 100644 --- a/Task/Sorting-algorithms-Quicksort/Erlang/sorting-algorithms-quicksort-2.erl +++ b/Task/Sorting-algorithms-Quicksort/Erlang/sorting-algorithms-quicksort-2.erl @@ -1,10 +1,10 @@ -quick_sort(L) -> qs(L, erlang:system_info(schedulers)). +quick_sort(L) -> qs(L, trunc(math:log2(erlang:system_info(schedulers)))). qs([],_) -> []; -qs([H|T], N) when N > 1 -> +qs([H|T], N) when N > 0 -> {Parent, Ref} = {self(), make_ref()}, - spawn(fun()-> Parent ! {l1, Ref, qs([E||E<-T, E Parent ! {l2, Ref, qs([E||E<-T, H =< E], N-2)} end), + spawn(fun()-> Parent ! {l1, Ref, qs([E||E<-T, E Parent ! {l2, Ref, qs([E||E<-T, H =< E], N-1)} end), {L1, L2} = receive_results(Ref, undefined, undefined), L1 ++ [H] ++ L2; qs([H|T],_) -> diff --git a/Task/Sorting-algorithms-Quicksort/Haskell/sorting-algorithms-quicksort-2.hs b/Task/Sorting-algorithms-Quicksort/Haskell/sorting-algorithms-quicksort-2.hs index ff105489ed..b4e5491b4d 100644 --- a/Task/Sorting-algorithms-Quicksort/Haskell/sorting-algorithms-quicksort-2.hs +++ b/Task/Sorting-algorithms-Quicksort/Haskell/sorting-algorithms-quicksort-2.hs @@ -1,4 +1,7 @@ -import Data.List +import Data.List (partition) +qsort :: Ord a => [a] -> [a] qsort [] = [] -qsort (x:xs) = qsort ys ++ x : qsort zs where (ys, zs) = partition (< x) xs +qsort (x:xs) = qsort ys ++ x : qsort zs + where + (ys, zs) = partition (< x) xs diff --git a/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-6.js b/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-6.js index 263f2970ce..8d1b84968d 100644 --- a/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-6.js +++ b/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-6.js @@ -1,33 +1,31 @@ -(function () { +(() => { 'use strict'; + // QUICKSORT -------------------------------------------------------------- + // quickSort :: (Ord a) => [a] -> [a] - function quickSort(xs) { - - if (xs.length) { - var h = xs[0], - [less, more] = partition( - x => x <= h, - xs.slice(1) - ); - + const quickSort = xs => + xs.length > 1 ? (() => { + const + h = xs[0], + [less, more] = partition(x => x <= h, xs.slice(1)); return [].concat.apply( [], [quickSort(less), h, quickSort(more)] ); + })() : xs; - } else return []; - } + // GENERIC ---------------------------------------------------------------- // partition :: Predicate -> List -> (Matches, nonMatches) // partition :: (a -> Bool) -> [a] -> ([a], [a]) - function partition(p, xs) { - return xs.reduce((a, x) => ( - a[p(x) ? 0 : 1].push(x), - a - ), [[], []]); - } + const partition = (p, xs) => + xs.reduce((a, x) => + p(x) ? [a[0].concat(x), a[1]] : [a[0], a[1].concat(x)], [ + [], + [] + ]); + // TEST ------------------------------------------------------------------- return quickSort([11.8, 14.1, 21.3, 8.5, 16.7, 5.7]); - })(); diff --git a/Task/Sorting-algorithms-Quicksort/jq/sorting-algorithms-quicksort-1.jq b/Task/Sorting-algorithms-Quicksort/Jq/sorting-algorithms-quicksort-1.jq similarity index 100% rename from Task/Sorting-algorithms-Quicksort/jq/sorting-algorithms-quicksort-1.jq rename to Task/Sorting-algorithms-Quicksort/Jq/sorting-algorithms-quicksort-1.jq diff --git a/Task/Sorting-algorithms-Quicksort/jq/sorting-algorithms-quicksort-2.jq b/Task/Sorting-algorithms-Quicksort/Jq/sorting-algorithms-quicksort-2.jq similarity index 100% rename from Task/Sorting-algorithms-Quicksort/jq/sorting-algorithms-quicksort-2.jq rename to Task/Sorting-algorithms-Quicksort/Jq/sorting-algorithms-quicksort-2.jq diff --git a/Task/Sorting-algorithms-Quicksort/jq/sorting-algorithms-quicksort-3.jq b/Task/Sorting-algorithms-Quicksort/Jq/sorting-algorithms-quicksort-3.jq similarity index 100% rename from Task/Sorting-algorithms-Quicksort/jq/sorting-algorithms-quicksort-3.jq rename to Task/Sorting-algorithms-Quicksort/Jq/sorting-algorithms-quicksort-3.jq diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-8.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-8.k deleted file mode 100644 index 38d72b5d2a..0000000000 --- a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-8.k +++ /dev/null @@ -1 +0,0 @@ - t@ quickSort(a : List, c : Comparator) : ArrayList { - return if (a.size == 0) ArrayList(a) - else { - val boxes = Array>(3, {ArrayList()}) - fun normalise(i : Int) = i / Math.max(1, Math.abs(i)) - a forEach {boxes[normalise(c.compare(it, a[0])) + 1] add(it)} - array(0, 2) forEach {boxes[it] = quickSort(boxes[it], c)} - boxes.flatMapTo(ArrayList()) {it} - } +fun quickSort(a: List, c: Comparator): ArrayList { + if (a.isEmpty()) return ArrayList(a) + + val boxes = Array(3, { ArrayList() }) + fun normalise(i: Int) = i / Math.max(1, Math.abs(i)) + a.forEach { boxes[normalise(c.compare(it, a[0])) + 1].add(it) } + arrayOf(0, 2).forEach { boxes[it] = quickSort(boxes[it], c) } + return boxes.flatMapTo(ArrayList()) { it } } diff --git a/Task/Sorting-algorithms-Quicksort/Kotlin/sorting-algorithms-quicksort-2.kotlin b/Task/Sorting-algorithms-Quicksort/Kotlin/sorting-algorithms-quicksort-2.kotlin index fee3bb609a..afe26e302b 100644 --- a/Task/Sorting-algorithms-Quicksort/Kotlin/sorting-algorithms-quicksort-2.kotlin +++ b/Task/Sorting-algorithms-Quicksort/Kotlin/sorting-algorithms-quicksort-2.kotlin @@ -1,15 +1,13 @@ fun quicksort(list: List): List { - if (list.size == 0) { - return listOf() - } else { - val head = list.first() - val tail = list.takeLast(list.size - 1) + if (list.isEmpty()) return emptyList() - val less = quicksort(tail.filter { it < head }) - val high = quicksort(tail.filter { it >= head }) + val head = list.first() + val tail = list.takeLast(list.size - 1) - return less + head + high - } + val less = quicksort(tail.filter { it < head }) + val high = quicksort(tail.filter { it >= head }) + + return less + head + high } fun main(args: Array) { diff --git a/Task/Sorting-algorithms-Quicksort/Nimrod/sorting-algorithms-quicksort-1.nimrod b/Task/Sorting-algorithms-Quicksort/Nimrod/sorting-algorithms-quicksort-1.nimrod deleted file mode 100644 index f06b9f131b..0000000000 --- a/Task/Sorting-algorithms-Quicksort/Nimrod/sorting-algorithms-quicksort-1.nimrod +++ /dev/null @@ -1,17 +0,0 @@ -proc QuickSort(list: seq[int]): seq[int] = - if len(list) == 0: - return @[] - - var pivot = list[0] - - var left: seq[int] = @[] - var right: seq[int] = @[] - for i in low(list)+1..high(list): - if list[i] <= pivot: - left.add(list[i]) - elif list[i] > pivot: - right.add(list[i]) - - result = QuickSort(left) - result.add(pivot) - result.add(QuickSort(right)) diff --git a/Task/Sorting-algorithms-Quicksort/Nimrod/sorting-algorithms-quicksort-2.nimrod b/Task/Sorting-algorithms-Quicksort/Nimrod/sorting-algorithms-quicksort-2.nimrod deleted file mode 100644 index 76e6fbe37d..0000000000 --- a/Task/Sorting-algorithms-Quicksort/Nimrod/sorting-algorithms-quicksort-2.nimrod +++ /dev/null @@ -1,3 +0,0 @@ -var sorted: seq[int] = QuickSort(@[5,2,1,6,2,3,1,2,123,21,54,6,1]) -for i in items(sorted): - echo(i) diff --git a/Task/Sorting-algorithms-Quicksort/OoRexx/sorting-algorithms-quicksort.rexx b/Task/Sorting-algorithms-Quicksort/OoRexx/sorting-algorithms-quicksort.rexx new file mode 100644 index 0000000000..eaee96c447 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/OoRexx/sorting-algorithms-quicksort.rexx @@ -0,0 +1,27 @@ + a = .array~Of(4, 65, 2, -31, 0, 99, 83, 782, 1) + say 'before:' a~toString( ,', ') + a = quickSort(a) + say ' after:' a~toString( ,', ') + exit + +::routine quickSort + use arg arr -- the array to be sorted + less = .array~new + pivotList = .array~new + more = .array~new + if arr~items <= 1 then + return arr + else do + pivot = arr[1] + do i over arr + if i < pivot then + less~append(i) + else if i > pivot then + more~append(i) + else + pivotList~append(i) + end + less = quickSort(less) + more = quickSort(more) + return less~~appendAll(pivotList)~~appendAll(more) + end diff --git a/Task/Sorting-algorithms-Quicksort/Pascal/sorting-algorithms-quicksort.pascal b/Task/Sorting-algorithms-Quicksort/Pascal/sorting-algorithms-quicksort.pascal index 5912488f96..c33548d6b7 100644 --- a/Task/Sorting-algorithms-Quicksort/Pascal/sorting-algorithms-quicksort.pascal +++ b/Task/Sorting-algorithms-Quicksort/Pascal/sorting-algorithms-quicksort.pascal @@ -1,21 +1,21 @@ { X is array of LongInt } Procedure QuickSort ( Left, Right : LongInt ); Var - i, j : LongInt; + i, j, tmp, pivot : LongInt; { tmp & pivot are the same type as the elements of array } Begin i:=Left; j:=Right; pivot := X[(Left + Right) shr 1]; // pivot := X[(Left + Rigth) div 2] Repeat - While pivot > X[i] Do i:=i+1; - While pivot < X[j] Do j:=j-1; + While pivot > X[i] Do inc(i); // i:=i+1; + While pivot < X[j] Do dec(j); // j:=j-1; If i<=j Then Begin tmp:=X[i]; X[i]:=X[j]; X[j]:=tmp; - j:=j-1; - i:=i+1; + dec(j); // j:=j-1; + inc(i); // i:=i+1; End; Until i>j; If Left@.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 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 tinie-tiny loop.*/ + do j=j while j<=k & @.j<=p; end /*a tinie─tiny loop.*/ do k=k by -1 while j =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*/ + 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@ subroutine──────────────────────────────────────────────────────────────────────────────────────────────────────*/ -gen@: @.=; maxL=0 /*assign default value for array.*/ +/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ +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" @@ -97,10 +97,9 @@ gen@: @.=; maxL=0 /*assign default value for arra @.61 = "Catawba River North Carolina, South Carolina" @.62 = "Blackwater River North Carolina, Virginia" @.63 = "Columbia River Oregon, Washington" - - do #=1 while @.#\=='' /*find how many entries in array, and */ - maxL=max(maxL, length(@.#)) /* also find the maximum width entry.*/ - end /*#*/ + 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. */ diff --git a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-4.rb b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-4.rb deleted file mode 100644 index 9872f7b147..0000000000 --- a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-4.rb +++ /dev/null @@ -1,6 +0,0 @@ -class Array - def quick_sort - h, *t = self - h ? t.partition { |e| e < h }.inject { |l, r| l.quick_sort + [h] + r.quick_sort } : [] - end -end diff --git a/Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort.rust b/Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort.rust index 87b3e0c836..b49452091d 100644 --- a/Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort.rust +++ b/Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort.rust @@ -1,46 +1,39 @@ -// Type alias for function that returns true if arguments should be swapped -type OrderFunc = Fn(&T, &T) -> bool; - fn main() { - // Sort numbers + println!("Sort numbers in descending order"); let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]; println!("Before: {:?}", numbers); - quick_sort(&mut numbers, &is_less); - println!("After: {:?}", numbers); + quick_sort(&mut numbers, &|x,y| x > y); + println!("After: {:?}\n", numbers); - // Sort strings + println!("Sort strings alphabetically"); let mut strings = ["beach", "hotel", "airplane", "car", "house", "art"]; println!("Before: {:?}", strings); - quick_sort(&mut strings, &is_less); - println!("After: {:?}", strings); + quick_sort(&mut strings, &|x,y| x < y); + println!("After: {:?}\n", strings); + + println!("Sort strings by length"); + println!("Before: {:?}", strings); + + quick_sort(&mut strings, &|x,y| x.len() < y.len()); + println!("After: {:?}", strings); } - -// Example OrderFunc which is used to order items from least to greatest -#[inline(always)] -fn is_less(x: &T, y: &T) -> bool { - x < y -} - -fn quick_sort(v: &mut [T], f: &OrderFunc) { - +fn quick_sort(v: &mut [T], f: &F) + where F: Fn(&T,&T) -> bool +{ let len = v.len(); - if len < 2 { - return; + if len >= 2 { + let pivot_index = partition(v, f); + quick_sort(&mut v[0..pivot_index], f); + quick_sort(&mut v[pivot_index + 1..len], f); } - - let pivot_index = partition(v, f); - - // Sort the left side - quick_sort(&mut v[0..pivot_index], f); - - // Sort the right side - quick_sort(&mut v[pivot_index + 1..len], f); } -fn partition(v: &mut [T], f: &OrderFunc) -> usize { +fn partition(v: &mut [T], f: &F) -> usize + where F: Fn(&T,&T) -> bool +{ let len = v.len(); let pivot_index = len / 2; diff --git a/Task/Sorting-algorithms-Quicksort/Simula/sorting-algorithms-quicksort.simula b/Task/Sorting-algorithms-Quicksort/Simula/sorting-algorithms-quicksort.simula new file mode 100644 index 0000000000..dcd83d230e --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Simula/sorting-algorithms-quicksort.simula @@ -0,0 +1,30 @@ +PROCEDURE QUICKSORT(A); REAL ARRAY A; +BEGIN + + PROCEDURE QS(A, FIRST, LAST); REAL ARRAY A; INTEGER FIRST, LAST; + BEGIN + INTEGER LEFT, RIGHT; + LEFT := FIRST; RIGHT := LAST; + IF RIGHT - LEFT + 1 > 1 THEN + BEGIN + REAL PIVOT; + PIVOT := A((LEFT + RIGHT) // 2); + WHILE LEFT <= RIGHT DO + BEGIN + WHILE A(LEFT) < PIVOT DO LEFT := LEFT + 1; + WHILE A(RIGHT) > PIVOT DO RIGHT := RIGHT - 1; + IF LEFT <= RIGHT THEN + BEGIN + REAL SWAP; + SWAP := A(LEFT); A(LEFT) := A(RIGHT); A(RIGHT) := SWAP; + LEFT := LEFT + 1; RIGHT := RIGHT - 1; + END; + END; + QS(A, FIRST, RIGHT); + QS(A, LEFT, LAST); + END; + END QS; + + QS(A, LOWERBOUND(A, 1), UPPERBOUND(A, 1)); + +END QUICKSORT; diff --git a/Task/Sorting-algorithms-Quicksort/Zkl/sorting-algorithms-quicksort-1.zkl b/Task/Sorting-algorithms-Quicksort/Zkl/sorting-algorithms-quicksort-1.zkl new file mode 100644 index 0000000000..10a0ccecd4 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Zkl/sorting-algorithms-quicksort-1.zkl @@ -0,0 +1,8 @@ +fcn qtSort(list,cmp=Op("<")){ // sort immutable lists + fcn(list,cmp,N){ // spendy to keep recreating cmp + reg pivot=list[0], rest=list[1,*]; + left,right:=rest.filter22(cmp,pivot); + N+=1; + T.extend(self.fcn(left,cmp,N),T(pivot),self.fcn(right,cmp,N)); + }(list,cmp,0); +} diff --git a/Task/Sorting-algorithms-Quicksort/Zkl/sorting-algorithms-quicksort-2.zkl b/Task/Sorting-algorithms-Quicksort/Zkl/sorting-algorithms-quicksort-2.zkl new file mode 100644 index 0000000000..0799fb1d4a --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Zkl/sorting-algorithms-quicksort-2.zkl @@ -0,0 +1,24 @@ +fcn qiSort(list,cmp='<){ // in place quick sort + fcn(list,left,right,cmp){ + if (left #include #include +#include -typedef unsigned uint; -#define swap(a, b) { tmp = a; a = b; b = tmp; } -#define each(i, x) for (i = 0; i < x; i++) +// 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)); + +static void swap(unsigned *a, unsigned *b) { + unsigned tmp = *a; + *a = *b; + *b = tmp; +} /* sort unsigned ints */ -static void rad_sort_u(uint *from, uint *to, uint bit) +static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit) { if (!bit || to < from + 1) return; - uint *ll = from, *rr = to - 1, tmp; - while (1) { + unsigned *ll = from, *rr = to - 1; + for (;;) { /* find left most with bit, and right most without bit, swap */ while (ll < rr && !(*ll & bit)) ll++; while (ll < rr && (*rr & bit)) rr--; if (ll >= rr) break; - swap(*ll, *rr); + swap(ll, rr); } if (!(bit & *ll) && ll < to) ll++; @@ -31,27 +39,28 @@ static void rad_sort_u(uint *from, uint *to, uint bit) static void radix_sort(int *a, const size_t len) { size_t i; - uint *x = (uint*) a; + unsigned *x = (unsigned*) a; - each(i, len) x[i] ^= INT_MIN; - rad_sort_u(x, x + len, INT_MIN); - each(i, len) x[i] ^= INT_MIN; -} + for (i = 0; i < len; i++) + x[i] ^= INT_MIN; -static inline void radix_sort_unsigned(uint *a, const size_t len) -{ - rad_sort_u(a, a + len, (uint)INT_MIN); + rad_sort_u(x, x + len, INT_MIN); + + for (i = 0; i < len; i++) + x[i] ^= INT_MIN; } int main(void) { - int len = 16, x[16], i; - size_t len = 16, i; - each(i, len) x[i] = rand() % 512 - 256; - radix_sort(x, len); + srand(time(NULL)); + int x[16]; - each(i, len) printf("%d%c", x[i], i + 1 < len ? ' ' : '\n'); + for (size_t i = 0; i < ARR_LEN(x); i++) + x[i] = RAND_RNG(-128,127) - return 0; + radix_sort(x, ARR_LEN(x)); + + for (size_t i = 0; i < ARR_LEN(x); i++) + printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n'); } 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 new file mode 100644 index 0000000000..ebdf0f22ea --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Fortran/sorting-algorithms-radix-sort.f @@ -0,0 +1,168 @@ +*======================================================================= +* 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) + + 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 + +* IF (N < 2) RETURN ! validate + J = 0 ! find bit size of an integer + J = NOT(J) + ILIM = 0 + DO I = 1, 32767 ! much bigger than exists + J = ISHFT(J, -1) + IF (.NOT. BTEST(J, 0)) THEN + ILIM = I + GO TO 10 + END IF + END DO + 10 CONTINUE + +*======================================================================= +* 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 + + +*********************************************************************** +* test program +*********************************************************************** + PROGRAM t_sort + IMPLICIT NONE + INTEGER I, N + PARAMETER (N = 11) + INTEGER IX(N), IW(N) + LOGICAL OK + + DATA IX / 2, 24, 45, 0, 66, 75, 170, -802, -90, 1066, 666 / + + PRINT *, 'before: ', IX + CALL RSORT (IX, IW, N) + PRINT *, 'after: ', IX + +* 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 diff --git a/Task/Sorting-algorithms-Radix-sort/jq/sorting-algorithms-radix-sort-1.jq b/Task/Sorting-algorithms-Radix-sort/Jq/sorting-algorithms-radix-sort-1.jq similarity index 100% rename from Task/Sorting-algorithms-Radix-sort/jq/sorting-algorithms-radix-sort-1.jq rename to Task/Sorting-algorithms-Radix-sort/Jq/sorting-algorithms-radix-sort-1.jq diff --git a/Task/Sorting-algorithms-Radix-sort/jq/sorting-algorithms-radix-sort-2.jq b/Task/Sorting-algorithms-Radix-sort/Jq/sorting-algorithms-radix-sort-2.jq similarity index 100% rename from Task/Sorting-algorithms-Radix-sort/jq/sorting-algorithms-radix-sort-2.jq rename to Task/Sorting-algorithms-Radix-sort/Jq/sorting-algorithms-radix-sort-2.jq 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.kotlin new file mode 100644 index 0000000000..343f9dad77 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Kotlin/sorting-algorithms-radix-sort.kotlin @@ -0,0 +1,36 @@ +// version 1.1.2 + +fun radixSort(original: IntArray): IntArray { + var old = original // Need this to be mutable + // Loop for every bit in the integers + for (shift in 31 downTo 0) { + val tmp = IntArray(old.size) // The array to put the partially sorted array into + var j = 0 // The number of 0s + // Move the 0s to the new array, and the 1s to the old one + for (i in 0 until old.size) { + // If there is a 1 in the bit we are testing, the number will be negative + val move = (old[i] shl shift) >= 0 + // If this is the last bit, negative numbers are actually lower + val toBeMoved = if (shift == 0) !move else move + if (toBeMoved) + tmp[j++] = old[i] + else { + // It's a 1, so stick it in the old array for now + old[i - j] = old[i] + } + } + // Copy over the 1s from the old array + for (i in j until tmp.size) tmp[i] = old[i - j] + // And now the tmp array gets switched for another round of sorting + old = tmp + } + return old +} + +fun main(args: Array) { + val arrays = arrayOf( + intArrayOf(170, 45, 75, -90, -802, 24, 2, 66), + intArrayOf(-4, 5, -26, 58, -990, 331, 331, 990, -1837, 2028) + ) + for (array in arrays) println(radixSort(array).contentToString()) +} diff --git a/Task/Sorting-algorithms-Radix-sort/REXX/sorting-algorithms-radix-sort.rexx b/Task/Sorting-algorithms-Radix-sort/REXX/sorting-algorithms-radix-sort.rexx index e2b42ad9de..bb76755cd8 100644 --- a/Task/Sorting-algorithms-Radix-sort/REXX/sorting-algorithms-radix-sort.rexx +++ b/Task/Sorting-algorithms-Radix-sort/REXX/sorting-algorithms-radix-sort.rexx @@ -1,63 +1,62 @@ -/*REXX program performs a radix sort on an integer (can be neg/zero/pos) array*/ -ILF='0 2 3 4 5 5 7 6 6 7 11 7 13 9 8 8 17 8 19 9 10 13 23 9 10 15 9 11 29 10 31 10 14 19', - '12 10 37 21 16 11 41 12 43 15 11 25 47 11 14 12 20 17 53 11 16 13 22 31 59 12 61 33', - '13 12 18 16 67 21 26 14 71 12 73 39 13 23 18 18 79 13 12 43 83 14 22 45 32 17 89 13', - '20 27 34 49 24 13 97 16 17 14 101 22 103 19 15 55 107 13 109 18 40 15 113 -42' - /*excluding -42, the abbreviated list (above) is called the integer log function.*/ -n=words(ILF) /* I────── L── F─────── */ -w=0 /*width so far.*/ - do m=1 for n; _=word(ILF,m); @.m=_; w=max(w,length(_)) /*store #s──►@.*/ - end /*m*/ /* ↑ */ - /* └─── is the maximum width of numbers*/ -call radSort n /*invoke the radix sort subroutine. */ - - do j=1 for n; say 'item' right(j,w) "after the radix sort:" right(@.j,w); end -exit /*stick a fork in it, we're all done. */ -/*───────────────────────────────────RADSORT subroutine───────────────────────*/ -radSort: procedure expose @. w; parse arg size; mote=c2d(' '); #=1; !.#._n=size +/*REXX program performs a radix sort on an integer array (can be negative/zero/positive)*/ +call gen /*call subroutine to generate numbers. */ +call radSort n /*invoke the radix sort subroutine. */ + /* [↓] display sorted items ───► term.*/ + do j=1 for n; say 'item' right(j,w) "after the radix sort:" right(@.j,w); end +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +gen: w=0 /*the max width of an number in the ILF*/ + ILF=' 0 2 3 4 5 5 7. 6 6 7 11 7 13 9 8 8 17 8 19 9 10 13 23 9 10 15' , + ' 9 11 29 10 31 10 14 19 12 10 37 21 16 11 41 12 43 15 11 25 47 11 14 12 20 17' , + '53 11 16 13 22 31 59 12 61 33 13 12 18 16 67 21 26 14 71 12 73 39 13 23 18 18' , + '79 13 12 43 83 14 22 45 32 17 89 13 20 27 34 49 24 13 97 16 17 14 101' , + '22 103 19 15 55 107 13 109 18 40 15 113 -42' + /*excluding -42, abbreviated above list is called the integer log function*/ + n=words(ILF) /* I────── L── F───────*/ + do m=1 for n; _=word(ILF,m)+0; @.m=_; w=max(w,length(_)); end + return /* [↑] W: max width of numbers. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +radSort: procedure expose @. w; parse arg size; mote=c2d(' '); #=1; !.#._n=size !.#._b=1; -!.#._i=1; do i=1 for size; y=@.i; @.i=right(abs(y),w,0); if y<0 then @.i='-'@.i - end /*i*/ /* [↓] where the rubber meats the road*/ -/*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ - do while #\==0; ctr.=0; L='ffff'x; low=!.#._b; n=!.#._n; $=!.#._i; H= /*▒*/ - #=#-1 /* [↑] is radix.*/ /*▒*/ - do j=low for n; parse var @.j =($) _ +1; ctr._=ctr._+1 /*▒*/ - if ctr._==1 & _\=='' then do; if _<>H then H=_ /*▒*/ - end /* ↑ */ /*▒*/ - end /*j*/ /* └── << is a strict comparison.*/ /*▒*/ - _= /* ┌── >> " " " " */ /*▒*/ - if L>>H then iterate /*◄─┘ */ /*▒*/ - if L==H & ctr._==0 then do; #=#+1; !.#._b=low; !.#._n=n; !.#._i=$+1; iterate /*▒*/ - end /*▒*/ - L=c2d(L); H=c2d(H); ?=ctr._+low; top._=?; ts=mote /*▒*/ - max=L /*▒*/ - do k=L to H; _=d2c(k,1); cen=ctr._ /*▒*/ - if cen>ts then parse value cen k with ts max /*swap.*/ /*▒*/ - ?=?+cen; top._=? /*▒*/ - end /*k*/ /*▒*/ - piv=low /*set pivot to the low part.*/ /*▒*/ - do while piv=cen then leave; top._=cen; ?=@.cen; @.cen=it; it=? /*▒*/ - end /*forever*/ /*▒*/ - top._=piv /*▒*/ - @.piv=it; piv=piv+ctr._ /*▒*/ - end /*while pivH then i=L; d=ctr._ /*▒*/ - if d<=mote then do; if d>1 then call .radSortP top._,d; iterate; end /*▒*/ - #=#+1; !.#._b=top._; !.#._n=d; !.#._i=$+1 /*▒*/ - end /*until i==max */ /*▒*/ - end /*while #\==0 */ /*▒*/ -/*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ -#=0; do i=size by -1 to 1; if @.i>=0 then iterate; #=#+1; @@.#=@.i; end - do j=1 for size; if @.j>=0 then do; #=#+1; @@.#=@.j; end; @.j=@@.j+0; end -return /* [↑↑↑] combine 2 lists into 1 list. */ -/*───────────────────────────────────.radSortP subroutine─────────────────────*/ -.radSortP: parse arg bb,nn - do k=bb+1 for nn-1; q=@.k - do j=k-1 by -1 to bb while q<<@.j; jp=j+1; @.jp=@.j; end /*j*/ - jp=j+1; @.jp=q - end /*k*/ -return +!.#._i=1; do i=1 for size; y=@.i; @.i=right(abs(y), w, 0); if y<0 then @.i='-'@.i + end /*i*/ /* [↑] negative case*/ + + do while #\==0; ctr.=0; L='ffff'x; low=!.#._b; n=!.#._n; $=!.#._i; H= + #=#-1 /* [↑] is the radix. */ + do j=low for n; parse var @.j =($) _ +1; ctr._=ctr._ + 1 + if ctr._==1 & _\=='' then do; if _<>H then H=_ + end /* ↑↑ */ + end /*j*/ /* └┴─────◄─── << is a strict comparison.*/ + _= /* ┌──◄─── >> " " " " */ + if L>>H then iterate /*◄─────┘ */ + if L==H & ctr._==0 then do; #=#+1; !.#._b=low; !.#._n=n; !.#._i=$ + 1; iterate + end + L=c2d(L); H=c2d(H); ?=ctr._ + low; top._=?; ts=mote + max=L + do k=L to H; _=d2c(k,1); c=ctr._ /* [↓] swap two item radices.*/ + if c>ts then parse value c k with ts max; ?=?+c; top._=? + end /*k*/ + piv=low /*set PIVot to the low part of the sort*/ + do while piv < low+n + it=@.piv + do forever; parse var it =($) _ +1; c=top._ -1 + if piv>=c then leave; top._=c; ?=@.c; @.c=it; it=? + end /*forever*/ + top._=piv; @.piv=it; piv=piv + ctr._ + end /*while pivH then i=L; d=ctr._ + if d<=mote then do; if d<2 then iterate; b=top._ + do k=b+1 for d-1; q=@.k + do j=k-1 by -1 to b while q<<@.j; jp=j+1; @.jp=@.j; end + jp=j+1; @.jp=q + end /*k*/ + iterate + end + #=#+1; !.#._b=top._; !.#._n=d; !.#._i=$+1 + end /*until i==max*/ + end /*while #\==0 */ +#=0 /* [↓↓↓] handle neg. and pos. arrays. */ + do i=size by -1 to 1; if @.i>=0 then iterate; #=#+1; @@.#=@.i; end + do j=1 for size; if @.j>=0 then do; #=#+1; @@.#=@.j; end; @.j=@@.j+0; end +return /* [↑↑↑] combine 2 lists into 1 list. */ diff --git a/Task/Sorting-algorithms-Radix-sort/Sidef/sorting-algorithms-radix-sort.sidef b/Task/Sorting-algorithms-Radix-sort/Sidef/sorting-algorithms-radix-sort.sidef index e200823fa4..a8f4b34487 100644 --- a/Task/Sorting-algorithms-Radix-sort/Sidef/sorting-algorithms-radix-sort.sidef +++ b/Task/Sorting-algorithms-Radix-sort/Sidef/sorting-algorithms-radix-sort.sidef @@ -1,18 +1,18 @@ class Array { method radix_sort(base=10) { - var arr = self.clone; - var rounds = ([arr.minmax].map{.abs}.max -> log(base).floor + 1); - for i in ^rounds { - var buckets = (2*base -> of {[]}); - var base_i = base**i; + var arr = self.clone + var rounds = ([arr.minmax].map{.abs}.max.ilog(base) + 1) + for i in (0..rounds) { + var buckets = (2*base -> of {[]}) + var base_i = base**i for n in arr { - var digit = (n/base_i % base); - digit += base if (0 <= n); - buckets[digit].append(n); + var digit = (n/base_i % base) + digit += base if (0 <= n) + buckets[digit].append(n) } - arr = buckets.flatten; + arr = buckets.flat } - return arr; + return arr } } @@ -22,5 +22,5 @@ for arr in [ [170, 45, 75, 90, 2, 24, -802, -66], [100000, -10000, 400, 23, 10000], ] { - say arr.radix_sort; + say arr.radix_sort } diff --git a/Task/Sorting-algorithms-Radix-sort/Zkl/sorting-algorithms-radix-sort-1.zkl b/Task/Sorting-algorithms-Radix-sort/Zkl/sorting-algorithms-radix-sort-1.zkl new file mode 100644 index 0000000000..71f71f7603 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Zkl/sorting-algorithms-radix-sort-1.zkl @@ -0,0 +1,12 @@ +fcn radixSort(ns){ // ints only, inplace, ns is mutable + b:=(0).pump(20,List,List().copy); // 20 [empty] buckets: -10..10 + z:=ns.reduce(fcn(a,b){ a.abs().max(b.abs()) },0); // |max or min of input| + m:=1; + while(z){ + ns.apply2('wrap(n){ b[(n/m)%10 +10].append(n) }); // sort on right digit + ns.clear(); b.pump(ns.extend); // slam buckets over src + b.apply("clear"); // reset buckets + m*=10; z/=10; // move sort digit left + } + ns +} diff --git a/Task/Sorting-algorithms-Radix-sort/Zkl/sorting-algorithms-radix-sort-2.zkl b/Task/Sorting-algorithms-Radix-sort/Zkl/sorting-algorithms-radix-sort-2.zkl new file mode 100644 index 0000000000..9b4a771d66 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Zkl/sorting-algorithms-radix-sort-2.zkl @@ -0,0 +1,2 @@ +radixSort(T(170, 45, 75, 90, 802, 2, 24, 66)).println(); +radixSort(T(170, 45, 75, -90, -802, 24, 2, 66)).println(); diff --git a/Task/Sorting-algorithms-Selection-sort/Erlang/sorting-algorithms-selection-sort.erl b/Task/Sorting-algorithms-Selection-sort/Erlang/sorting-algorithms-selection-sort.erl new file mode 100644 index 0000000000..c0cf64724b --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Erlang/sorting-algorithms-selection-sort.erl @@ -0,0 +1,16 @@ +-module(solution). +-import(lists,[delete/2,max/1]). +-compile(export_all). +selection_sort([],Sort)-> Sort; +selection_sort(Ar,Sort)-> + M=max(Ar), + Ad=delete(M,Ar), + selection_sort(Ad,[M|Sort]). +print_array([])->ok; +print_array([H|T])-> + io:format("~p~n",[H]), + print_array(T). + +main()-> + Ans=selection_sort([1,5,7,8,4,10],[]), + print_array(Ans). diff --git a/Task/Sorting-algorithms-Selection-sort/jq/sorting-algorithms-selection-sort-1.jq b/Task/Sorting-algorithms-Selection-sort/Jq/sorting-algorithms-selection-sort-1.jq similarity index 100% rename from Task/Sorting-algorithms-Selection-sort/jq/sorting-algorithms-selection-sort-1.jq rename to Task/Sorting-algorithms-Selection-sort/Jq/sorting-algorithms-selection-sort-1.jq diff --git a/Task/Sorting-algorithms-Selection-sort/jq/sorting-algorithms-selection-sort-2.jq b/Task/Sorting-algorithms-Selection-sort/Jq/sorting-algorithms-selection-sort-2.jq similarity index 100% rename from Task/Sorting-algorithms-Selection-sort/jq/sorting-algorithms-selection-sort-2.jq rename to Task/Sorting-algorithms-Selection-sort/Jq/sorting-algorithms-selection-sort-2.jq diff --git a/Task/Sorting-algorithms-Selection-sort/OoRexx/sorting-algorithms-selection-sort.rexx b/Task/Sorting-algorithms-Selection-sort/OoRexx/sorting-algorithms-selection-sort.rexx new file mode 100644 index 0000000000..45eb2c483a --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/OoRexx/sorting-algorithms-selection-sort.rexx @@ -0,0 +1,53 @@ +/*REXX **************************************************************** +* program sorts an array using the selection-sort method. +* derived from REXX solution +* Note that ooRexx can process Elements of the stem argument (Use Arg) +* 06.10.2010 Walter Pachl +**********************************************************************/ +call generate /*generate the array elements. */ +call show 'before sort' /*show the before array elements,*/ +call selectionSort x. /*invoke the selection sort. */ +call show 'after sort' /*show the after array elements.*/ +exit /*stick a fork in it, we're done.*/ + +selectionSort: Procedure + Use Arg s. /* gain access to the argument */ + do j=1 To s.0-1 + t=s.j; + p=j; + do k=j+1 to s.0 + if s.k 0; h = parseInt(h / 2)) { for (var i = h; i < a.length; i++) { var k = a[i]; for (var j = i; j >= h && k < a[j - h]; j -= h) diff --git a/Task/Sorting-algorithms-Shell-sort/jq/sorting-algorithms-shell-sort-1.jq b/Task/Sorting-algorithms-Shell-sort/Jq/sorting-algorithms-shell-sort-1.jq similarity index 100% rename from Task/Sorting-algorithms-Shell-sort/jq/sorting-algorithms-shell-sort-1.jq rename to Task/Sorting-algorithms-Shell-sort/Jq/sorting-algorithms-shell-sort-1.jq diff --git a/Task/Sorting-algorithms-Shell-sort/jq/sorting-algorithms-shell-sort-2.jq b/Task/Sorting-algorithms-Shell-sort/Jq/sorting-algorithms-shell-sort-2.jq similarity index 100% rename from Task/Sorting-algorithms-Shell-sort/jq/sorting-algorithms-shell-sort-2.jq rename to Task/Sorting-algorithms-Shell-sort/Jq/sorting-algorithms-shell-sort-2.jq diff --git a/Task/Sorting-algorithms-Shell-sort/jq/sorting-algorithms-shell-sort-3.jq b/Task/Sorting-algorithms-Shell-sort/Jq/sorting-algorithms-shell-sort-3.jq similarity index 100% rename from Task/Sorting-algorithms-Shell-sort/jq/sorting-algorithms-shell-sort-3.jq rename to Task/Sorting-algorithms-Shell-sort/Jq/sorting-algorithms-shell-sort-3.jq diff --git a/Task/Sorting-algorithms-Shell-sort/Julia/sorting-algorithms-shell-sort.julia b/Task/Sorting-algorithms-Shell-sort/Julia/sorting-algorithms-shell-sort.julia new file mode 100644 index 0000000000..ae1e4ae28d --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Julia/sorting-algorithms-shell-sort.julia @@ -0,0 +1,26 @@ +# v0.6 + +function shellsort!(a::Array{Int})::Array{Int} + incr = div(length(a), 2) + while incr > 0 + for i in incr+1:length(a) + j = i + tmp = a[i] + while j > incr && a[j - incr] > tmp + a[j] = a[j-incr] + j -= incr + end + a[j] = tmp + end + if incr == 2 + incr = 1 + else + incr = floor(Int, incr * 5.0 / 11) + end + end + return a +end + +x = rand(1:10, 10) +@show x shellsort!(x) +@assert issorted(x) diff --git a/Task/Sorting-algorithms-Shell-sort/Kotlin/sorting-algorithms-shell-sort.kotlin b/Task/Sorting-algorithms-Shell-sort/Kotlin/sorting-algorithms-shell-sort.kotlin new file mode 100644 index 0000000000..2c809dde8c --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Kotlin/sorting-algorithms-shell-sort.kotlin @@ -0,0 +1,29 @@ +// version 1.1.0 + +val gaps = listOf(701, 301, 132, 57, 23, 10, 4, 1) // Marcin Ciura's gap sequence + +fun shellSort(a: IntArray) { + for (gap in gaps) { + for (i in gap until a.size) { + val temp = a[i] + var j = i + while (j >= gap && a[j - gap] > temp) { + a[j] = a[j - gap] + j -= gap + } + a[j] = temp + } + } +} + +fun main(args: Array) { + val aa = arrayOf( + intArrayOf(100, 2, 56, 200, -52, 3, 99, 33, 177, -199), + intArrayOf(4, 65, 2, -31, 0, 99, 2, 83, 782, 1), + intArrayOf(62, 83, 18, 53, 7, 17, 95, 86, 47, 69, 25, 28) + ) + for (a in aa) { + shellSort(a) + println(a.joinToString(", ")) + } +} diff --git a/Task/Sorting-algorithms-Shell-sort/OoRexx/sorting-algorithms-shell-sort.rexx b/Task/Sorting-algorithms-Shell-sort/OoRexx/sorting-algorithms-shell-sort.rexx new file mode 100644 index 0000000000..b7ce78b05c --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/OoRexx/sorting-algorithms-shell-sort.rexx @@ -0,0 +1,77 @@ +/* Rexx */ +-- --- Main -------------------------------------------------------------------- +call demo +return +exit + +-- ----------------------------------------------------------------------------- +-- Shell sort implementation +-- ----------------------------------------------------------------------------- +::routine shellSort + use arg ra + + n = ra~items() + inc = format(n / 2.0,, 0) -- rounding + loop label inc while inc > 0 + loop i_ = inc to n - 1 + temp = ra~get(i_) + j_ = i_ + loop label j_ while j_ >= inc + if \(ra~get(j_ - inc) > temp) then leave j_ + ra~set(j_, ra~get(j_ - inc)) + j_ = j_ - inc + end j_ + ra~set(j_, temp) + end i_ + inc = format(inc / 2.2,, 0) -- rounding + end inc + + return ra + +-- ----------------------------------------------------------------------------- +-- Demonstrate the implementation +-- ----------------------------------------------------------------------------- +::routine demo + +placesList = .nlist~of( - + "UK London", "US New York", "US Boston", "US Washington" - + , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - +) + +lists = .array~of( - + placesList - + , shellSort(placesList~copy()) - + ) + +loop ln = 1 to lists~items() + cl = lists[ln] + loop ct = 0 to cl~items() - 1 + say right(ct + 1, 4)':' cl[ct] + end ct + say + end ln + return + +-- ----------------------------------------------------------------------------- +::routine isTrue + return 1 == 1 + +-- ----------------------------------------------------------------------------- +::routine isFalse + return \isTrue() + +-- ----------------------------------------------------------------------------- +-- Helper class. Map get and set methods for easier conversion from java.util.List +-- ----------------------------------------------------------------------------- +::class NList mixinclass List public + +-- Map get() to at() +::method get + use arg ix + return self~at(ix) + +-- Map set() to put() +::method set + use arg ix, item + self~put(item, ix) + return diff --git a/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx b/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx index 0a29a5390a..1fd01115aa 100644 --- a/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx +++ b/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx @@ -31,18 +31,16 @@ gen: @.= /*assign a default value to ste /*──────────────────────────────────────────────────────────────────────────────────────*/ shellSort: procedure expose @.; parse arg N /*obtain the N from the argument list*/ i=N%2 /*% is integer division in REXX. */ - do while i\==0 - do j=i+1 to N; k=j; p=k-i /*P: previous item*/ - _=@.j - do while k>=i+1 & @.p>_; @.k=@.p - k=k-i; p=k-i - end /*while k≥i+1*/ - @.k=_ - end /*j*/ - - if i==2 then i=1 - else i=i*5 % 11 - end /*while i¬==0*/ + do while i\==0 + do j=i+1 to N; k=j; p=k-i /*P: previous item*/ + _=@.j + do while k>=i+1 & @.p>_; @.k=@.p; k=k-i; p=k-i + end /*while k≥i+1*/ + @.k=_ + end /*j*/ + if i==2 then i=1 + else i=i * 5 % 11 + end /*while i¬==0*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ show: do j=1 for #; say 'element' right(j,length(#)) arg(1)": " @.j; end; return diff --git a/Task/Sorting-algorithms-Shell-sort/Zkl/sorting-algorithms-shell-sort.zkl b/Task/Sorting-algorithms-Shell-sort/Zkl/sorting-algorithms-shell-sort.zkl new file mode 100644 index 0000000000..5c63f0fa83 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Zkl/sorting-algorithms-shell-sort.zkl @@ -0,0 +1,19 @@ + // Shell sort a sequence of objects in place + // Requires mutiable list +fcn shellSort(sequence){ + n := sequence.len(); + gap := n / 2; + while (0 < gap){ + i := gap; + while (i < n){ + j := i - gap; + while ((j >= 0) and (sequence[j] > sequence[j + gap])){ + sequence.swap(j,j + gap); + j -= gap; + } + i += 1; + } + gap /= 2; + } + return(sequence); +} diff --git a/Task/Sorting-algorithms-Sleep-sort/C++/sorting-algorithms-sleep-sort.cpp b/Task/Sorting-algorithms-Sleep-sort/C++/sorting-algorithms-sleep-sort.cpp index 9651d32169..3fdc415b29 100644 --- a/Task/Sorting-algorithms-Sleep-sort/C++/sorting-algorithms-sleep-sort.cpp +++ b/Task/Sorting-algorithms-Sleep-sort/C++/sorting-algorithms-sleep-sort.cpp @@ -1,38 +1,20 @@ +#include #include #include #include -#include -using namespace std; +int main(int argc, char* argv[]) { + std::vector threads; -void sortThread( int x ) -{ - usleep( 10000 * x ); - cout << x << " "; -} - -int main() -{ - vector threads; - - srand( ( unsigned )time( NULL ) ); - - cout << "unsorted:" << endl; - for( int x = 0; x < 15; x++ ) - { - int r = rand() % 20 + 5; - cout << r << " "; - thread* t = new thread( sortThread, r ); - threads.push_back( t ); - } - cout << endl << endl << "sorted:" << endl; - - for( vector::iterator t = threads.begin(); t != threads.end(); t++ ) - { - ( *t )->join(); - delete ( *t ); - } - - cout << endl << endl; - return 0; + for (int i = 1; i < argc; ++i) { + threads.emplace_back([i, &argv]() { + int arg = std::stoi(argv[i]); + std::this_thread::sleep_for(std::chrono::seconds(arg)); + std::cout << argv[i] << std::endl; + }); + } + + for (auto& thread : threads) { + thread.join(); + } } diff --git a/Task/Sorting-algorithms-Sleep-sort/Factor/sorting-algorithms-sleep-sort-1.factor b/Task/Sorting-algorithms-Sleep-sort/Factor/sorting-algorithms-sleep-sort-1.factor new file mode 100644 index 0000000000..fd87d6209b --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Factor/sorting-algorithms-sleep-sort-1.factor @@ -0,0 +1,3 @@ +USING: threads calendar concurrency.combinators ; + +: sleep-sort ( seq -- ) [ dup seconds sleep . ] parallel-each ; diff --git a/Task/Sorting-algorithms-Sleep-sort/Factor/sorting-algorithms-sleep-sort-2.factor b/Task/Sorting-algorithms-Sleep-sort/Factor/sorting-algorithms-sleep-sort-2.factor new file mode 100644 index 0000000000..41476d8158 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Factor/sorting-algorithms-sleep-sort-2.factor @@ -0,0 +1 @@ +{ 1 9 2 6 3 4 5 8 7 0 } sleep-sort diff --git a/Task/Sorting-algorithms-Sleep-sort/Fortran/sorting-algorithms-sleep-sort.f b/Task/Sorting-algorithms-Sleep-sort/Fortran/sorting-algorithms-sleep-sort.f new file mode 100644 index 0000000000..ea5cd6ca40 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Fortran/sorting-algorithms-sleep-sort.f @@ -0,0 +1,33 @@ +program sleepSort + use omp_lib + implicit none + integer::nArgs,myid,i,stat + integer,allocatable::intArg(:) + character(len=5)::arg + + !$omp master + nArgs=command_argument_count() + if(nArgs==0)stop ' : No argument is given !' + allocate(intArg(nArgs)) + do i=1,nArgs + call get_command_argument(i, arg) + read(arg,'(I5)',iostat=stat)intArg(i) + if(intArg(i)<0 .or. stat/=0) stop& + &' :Only 0 or positive integer allowed !' + end do + call omp_set_num_threads(nArgs) + !$omp end master + + + !$omp parallel private(myid) + myid =omp_get_thread_num() + call sleepNprint(intArg(myid+1)) + !$omp end parallel + + contains + subroutine sleepNprint(nSeconds) + integer::nSeconds + call sleep(nSeconds) + print*,nSeconds + end subroutine sleepNprint +end program sleepSort diff --git a/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort-1.hs b/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort-1.hs index a05c427547..41932d64bc 100644 --- a/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort-1.hs +++ b/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort-1.hs @@ -4,9 +4,9 @@ import Control.Monad sleepSort :: [Int] -> IO () sleepSort values = do - chan <- newChan - forM_ values (\time -> forkIO (threadDelay (50000 * time) >> writeChan chan time)) - forM_ values (const (readChan chan >>= print)) + chan <- newChan + forM_ values (\time -> forkIO (threadDelay (50000 * time) >> writeChan chan time)) + forM_ values (\_ -> readChan chan >>= print) main :: IO () main = getArgs >>= sleepSort . map read diff --git a/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort-2.hs b/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort-2.hs index 362463413c..15c02e47c6 100644 --- a/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort-2.hs +++ b/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort-2.hs @@ -2,8 +2,8 @@ import System.Environment import Control.Concurrent import Control.Concurrent.Async -sleepSort :: [Int] -> IO [()] -sleepSort = mapConcurrently (\x -> threadDelay (x*10^4) >> print x) +sleepSort :: [Int] -> IO () +sleepSort = (() <$) . mapConcurrently (\x -> threadDelay (x*10^4) >> print x) -main :: IO [()] +main :: IO () main = getArgs >>= sleepSort . map read diff --git a/Task/Sorting-algorithms-Sleep-sort/jq/sorting-algorithms-sleep-sort.jq b/Task/Sorting-algorithms-Sleep-sort/Jq/sorting-algorithms-sleep-sort.jq similarity index 100% rename from Task/Sorting-algorithms-Sleep-sort/jq/sorting-algorithms-sleep-sort.jq rename to Task/Sorting-algorithms-Sleep-sort/Jq/sorting-algorithms-sleep-sort.jq diff --git a/Task/Sorting-algorithms-Sleep-sort/Scala/sorting-algorithms-sleep-sort-1.scala b/Task/Sorting-algorithms-Sleep-sort/Scala/sorting-algorithms-sleep-sort-1.scala new file mode 100644 index 0000000000..2a471f6d8b --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Scala/sorting-algorithms-sleep-sort-1.scala @@ -0,0 +1,17 @@ +object SleepSort { + + def main(args: Array[String]): Unit = { + val nums = args.map(_.toInt) + sort(nums) + Thread.sleep(nums.max * 21) // Keep the JVM alive for the example + } + + def sort(nums: Seq[Int]): Unit = + nums.foreach(i => new Thread { + override def run() { + Thread.sleep(i * 20) // just `i` is unpredictable with small numbers + print(s"$i ") + } + }.start()) + +} diff --git a/Task/Sorting-algorithms-Sleep-sort/Scala/sorting-algorithms-sleep-sort-2.scala b/Task/Sorting-algorithms-Sleep-sort/Scala/sorting-algorithms-sleep-sort-2.scala new file mode 100644 index 0000000000..cd231def47 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Scala/sorting-algorithms-sleep-sort-2.scala @@ -0,0 +1,2 @@ +$ scala SleepSort 1 3 6 0 9 7 4 2 5 8 +0 1 2 3 4 5 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Sleep-sort/Scala/sorting-algorithms-sleep-sort.scala b/Task/Sorting-algorithms-Sleep-sort/Scala/sorting-algorithms-sleep-sort.scala deleted file mode 100644 index d1e337a6e3..0000000000 --- a/Task/Sorting-algorithms-Sleep-sort/Scala/sorting-algorithms-sleep-sort.scala +++ /dev/null @@ -1,12 +0,0 @@ -object SleepSort { - def sort(nums:Seq[Int])=nums foreach {n => - scala.concurrent.ops.spawn{ - Thread.sleep(500*n) - print(n+" ") - } - } - - def main(args:Array[String])={ - sort(args map (_.toInt)) - } -} diff --git a/Task/Sorting-algorithms-Sleep-sort/Simula/sorting-algorithms-sleep-sort.simula b/Task/Sorting-algorithms-Sleep-sort/Simula/sorting-algorithms-sleep-sort.simula new file mode 100644 index 0000000000..979a3171eb --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Simula/sorting-algorithms-sleep-sort.simula @@ -0,0 +1,20 @@ +SIMULATION +BEGIN + + PROCESS CLASS SORTITEM(N); INTEGER N; + BEGIN + HOLD(N); + OUTINT(N, 3); + END; + + INTEGER I; + FOR I := 3, 2, 4, 7, 3, 6, 9, 1 DO + BEGIN + REF(SORTITEM) SI; + SI :- NEW SORTITEM(I); + ACTIVATE SI; + END; + HOLD(100000); + OUTIMAGE; + +END; diff --git a/Task/Sorting-algorithms-Sleep-sort/Zkl/sorting-algorithms-sleep-sort.zkl b/Task/Sorting-algorithms-Sleep-sort/Zkl/sorting-algorithms-sleep-sort.zkl new file mode 100644 index 0000000000..b0e3f7c851 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Zkl/sorting-algorithms-sleep-sort.zkl @@ -0,0 +1,2 @@ +vm.arglist.apply(fcn(n){ Atomic.sleep(n); print(n) }.launch); +Atomic.waitFor(fcn{ vm.numThreads == 1 }); Atomic.sleep(2); println(); diff --git a/Task/Sorting-algorithms-Stooge-sort/Common-Lisp/sorting-algorithms-stooge-sort.lisp b/Task/Sorting-algorithms-Stooge-sort/Common-Lisp/sorting-algorithms-stooge-sort.lisp new file mode 100644 index 0000000000..af64d89222 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Common-Lisp/sorting-algorithms-stooge-sort.lisp @@ -0,0 +1,9 @@ +(defun stooge-sort (vector &optional (i 0) (j (1- (length vector)))) + (when (> (aref vector i) (aref vector j)) + (rotatef (aref vector i) (aref vector j))) + (when (> (- j i) 1) + (let ((third (floor (1+ (- j i)) 3))) + (stooge-sort vector i (- j third)) + (stooge-sort vector (+ i third) j) + (stooge-sort vector i (- j third)))) + vector) diff --git a/Task/Sorting-algorithms-Stooge-sort/jq/sorting-algorithms-stooge-sort-1.jq b/Task/Sorting-algorithms-Stooge-sort/Jq/sorting-algorithms-stooge-sort-1.jq similarity index 100% rename from Task/Sorting-algorithms-Stooge-sort/jq/sorting-algorithms-stooge-sort-1.jq rename to Task/Sorting-algorithms-Stooge-sort/Jq/sorting-algorithms-stooge-sort-1.jq diff --git a/Task/Sorting-algorithms-Stooge-sort/jq/sorting-algorithms-stooge-sort-2.jq b/Task/Sorting-algorithms-Stooge-sort/Jq/sorting-algorithms-stooge-sort-2.jq similarity index 100% rename from Task/Sorting-algorithms-Stooge-sort/jq/sorting-algorithms-stooge-sort-2.jq rename to Task/Sorting-algorithms-Stooge-sort/Jq/sorting-algorithms-stooge-sort-2.jq diff --git a/Task/Sorting-algorithms-Stooge-sort/jq/sorting-algorithms-stooge-sort-3.jq b/Task/Sorting-algorithms-Stooge-sort/Jq/sorting-algorithms-stooge-sort-3.jq similarity index 100% rename from Task/Sorting-algorithms-Stooge-sort/jq/sorting-algorithms-stooge-sort-3.jq rename to Task/Sorting-algorithms-Stooge-sort/Jq/sorting-algorithms-stooge-sort-3.jq diff --git a/Task/Sorting-algorithms-Stooge-sort/Julia/sorting-algorithms-stooge-sort.julia b/Task/Sorting-algorithms-Stooge-sort/Julia/sorting-algorithms-stooge-sort.julia new file mode 100644 index 0000000000..b8e84a9908 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Julia/sorting-algorithms-stooge-sort.julia @@ -0,0 +1,17 @@ +function stoogesort!(a::Array, i::Int=1, j::Int=length(a)) + if a[j] < a[i] + a[[i, j]] = a[[j, i]]; + end + + if (j - i) > 1 + t = round(Int, (j - i + 1) / 3) + a = stoogesort!(a, i, j - t) + a = stoogesort!(a, i + t, j) + a = stoogesort!(a, i, j - t) + end + + return a +end + +x = randn(10) +@show x stoogesort!(x) diff --git a/Task/Sorting-algorithms-Stooge-sort/Kotlin/sorting-algorithms-stooge-sort.kotlin b/Task/Sorting-algorithms-Stooge-sort/Kotlin/sorting-algorithms-stooge-sort.kotlin new file mode 100644 index 0000000000..e1615a6abe --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Kotlin/sorting-algorithms-stooge-sort.kotlin @@ -0,0 +1,22 @@ +// version 1.1.0 + +fun stoogeSort(a: IntArray, i: Int, j: Int) { + if (a[j] < a[i]) { + val temp = a[j] + a[j] = a[i] + a[i] = temp + } + if (j - i > 1) { + val t = (j - i + 1) / 3 + stoogeSort(a, i, j - t) + stoogeSort(a, i + t, j) + stoogeSort(a, i, j - t) + } +} + +fun main(args: Array) { + val a = intArrayOf(100, 2, 56, 200, -52, 3, 99, 33, 177, -199) + println("Original : ${a.asList()}") + stoogeSort(a, 0, a.size - 1) + println("Sorted : ${a.asList()}") +} diff --git a/Task/Sorting-algorithms-Stooge-sort/OoRexx/sorting-algorithms-stooge-sort.rexx b/Task/Sorting-algorithms-Stooge-sort/OoRexx/sorting-algorithms-stooge-sort.rexx new file mode 100644 index 0000000000..07cdf0cd8d --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/OoRexx/sorting-algorithms-stooge-sort.rexx @@ -0,0 +1,80 @@ +/* Rexx */ + +call demo +return +exit + +-- ----------------------------------------------------------------------------- +-- Stooge sort implementation +-- ----------------------------------------------------------------------------- +::routine stoogeSort + use arg rL_, i_ = 0, j_ = .nil + if j_ = .nil then j_ = rL_~items() - 1 + + if rL_~get(j_) < rL_~get(i_) then do + Lt = rL_~get(i_) + rL_~set(i_, rL_~get(j_)) + rL_~set(j_, Lt) + end + if j_ - i_ > 1 then do + t_ = (j_ - i_ + 1) % 3 + rL_ = stoogeSort(rL_, i_, j_ - t_) + rL_ = stoogeSort(rL_, i_ + t_, j_) + rL_ = stoogeSort(rL_, i_, j_ - t_) + end + + return rL_ + +-- ----------------------------------------------------------------------------- +-- Demonstrate the implementation +-- ----------------------------------------------------------------------------- +::routine demo + + iList = .nlist~of(1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7) + sList = iList~copy() + + placesList = .nlist~of( - + "UK London", "US New York", "US Boston", "US Washington" - + , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - + ) + + sList = stoogeSort(sList) + sortedList = stoogeSort(placesList~copy()) + + iLists = .list~of(iList, sList) + loop ln = 0 to iLists~items() - 1 + icl = iLists[ln] + rpt = '' + loop ct = 0 to icl~items() - 1 + rpt = rpt icl[ct] + end ct + say '['rpt~strip()~changestr(' ', ',')']' + end ln + + say + sLists = .list~of(placesList, sortedList) + loop ln = 0 to sLists~items() - 1 + scl = sLists[ln] + loop ct = 0 to scl~items() - 1 + say right(ct + 1, 3)':' scl[ct] + end ct + say + end ln + + return + +-- ----------------------------------------------------------------------------- +-- Helper class. Map get and set methods for easier conversion from java.util.List +-- ----------------------------------------------------------------------------- +::class NList mixinclass List public + +-- Map get() to at() +::method get + use arg ix + return self~at(ix) + +-- Map set() to put() +::method set + use arg ix, item + self~put(item, ix) + return diff --git a/Task/Sorting-algorithms-Stooge-sort/Zkl/sorting-algorithms-stooge-sort-1.zkl b/Task/Sorting-algorithms-Stooge-sort/Zkl/sorting-algorithms-stooge-sort-1.zkl new file mode 100644 index 0000000000..c930a8904f --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Zkl/sorting-algorithms-stooge-sort-1.zkl @@ -0,0 +1,10 @@ +fcn stoogeSort(list,i=0,j=Void){ if(Void==j) j=list.len() - 1; // default parameters set before call + if(list[j]1){ + t:=(j - i + 1)/3; + stoogeSort(list,i , j-t); + stoogeSort(list,i+t, j ); + stoogeSort(list,i , j-t); + } + list +} diff --git a/Task/Sorting-algorithms-Stooge-sort/Zkl/sorting-algorithms-stooge-sort-2.zkl b/Task/Sorting-algorithms-Stooge-sort/Zkl/sorting-algorithms-stooge-sort-2.zkl new file mode 100644 index 0000000000..50e3b45000 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Zkl/sorting-algorithms-stooge-sort-2.zkl @@ -0,0 +1 @@ +stoogeSort(List(67,-201,0,9,9,231,4)).println(); diff --git a/Task/Sorting-algorithms-Strand-sort/jq/sorting-algorithms-strand-sort.jq b/Task/Sorting-algorithms-Strand-sort/Jq/sorting-algorithms-strand-sort.jq similarity index 100% rename from Task/Sorting-algorithms-Strand-sort/jq/sorting-algorithms-strand-sort.jq rename to Task/Sorting-algorithms-Strand-sort/Jq/sorting-algorithms-strand-sort.jq diff --git a/Task/Sorting-algorithms-Strand-sort/Kotlin/sorting-algorithms-strand-sort.kotlin b/Task/Sorting-algorithms-Strand-sort/Kotlin/sorting-algorithms-strand-sort.kotlin new file mode 100644 index 0000000000..c7b57ebf1d --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Kotlin/sorting-algorithms-strand-sort.kotlin @@ -0,0 +1,42 @@ +// version 1.1.2 + +fun > strandSort(l: List): List { + fun merge(left: MutableList, right: MutableList): MutableList { + val res = mutableListOf() + while (!left.isEmpty() && !right.isEmpty()) { + if (left[0] <= right[0]) { + res.add(left[0]) + left.removeAt(0) + } + else { + res.add(right[0]) + right.removeAt(0) + } + } + res.addAll(left) + res.addAll(right) + return res + } + + var list = l.toMutableList() + var result = mutableListOf() + while (!list.isEmpty()) { + val sorted = mutableListOf(list[0]) + list.removeAt(0) + val leftover = mutableListOf() + for (item in list) { + if (sorted.last() <= item) + sorted.add(item) + else + leftover.add(item) + } + result = merge(sorted, result) + list = leftover + } + return result +} + +fun main(args: Array) { + val l = listOf(-2, 0, -2, 5, 5, 3, -1, -3, 5, 5, 0, 2, -4, 4, 2) + println(strandSort(l)) +} diff --git a/Task/Sorting-algorithms-Strand-sort/Zkl/sorting-algorithms-strand-sort-1.zkl b/Task/Sorting-algorithms-Strand-sort/Zkl/sorting-algorithms-strand-sort-1.zkl new file mode 100644 index 0000000000..11cecdc8d7 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Zkl/sorting-algorithms-strand-sort-1.zkl @@ -0,0 +1,11 @@ +fcn strandSort(A){ //--> new list, A is cleared, should add A=A.copy() + sublist:=List.createLong(A.len()); results:=List.createLong(A.len()); + while(A){ + sublist.clear(A.pop(0)); + foreach i in (A.len() - 1){ + if(A[i]>sublist[-1]) sublist.append(A.pop(i)); + } + results.merge(sublist); + } + results +} diff --git a/Task/Sorting-algorithms-Strand-sort/Zkl/sorting-algorithms-strand-sort-2.zkl b/Task/Sorting-algorithms-Strand-sort/Zkl/sorting-algorithms-strand-sort-2.zkl new file mode 100644 index 0000000000..e887dcccc8 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Zkl/sorting-algorithms-strand-sort-2.zkl @@ -0,0 +1,2 @@ +strandSort(L(3,1,5,4,2)).println(); +strandSort("azbfe".split("")).println(); diff --git a/Task/Soundex/360-Assembly/soundex.360 b/Task/Soundex/360-Assembly/soundex.360 new file mode 100644 index 0000000000..28d4aab311 --- /dev/null +++ b/Task/Soundex/360-Assembly/soundex.360 @@ -0,0 +1,81 @@ +* Soundex 02/04/2017 +SOUNDEX CSECT + USING SOUNDEX,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + LA R6,1 i=1 + DO WHILE=(C,R6,LE,=A(NTT)) do i=1 to hbound(tt) + LR R1,R6 i + BCTR R1,0 -1 + MH R1,=AL2(L'TT) *length(tt) + LA R4,TT(R1) @tt(i) + MVC S,0(R4) s=tt(i) + LA R1,S @s + LA R2,L'S length(s) +LOOP OI 0(R1),C' ' loop s[l]=ucase(s[l]) + LA R1,1(R1) @s++ + BCT R2,LOOP endloop + MVC CODE,=C'0000' code='0000' + MVC CODE(1),S code[1]=s[1] + LA R8,1 k=1 + LA R7,1 j=1 + DO WHILE=(C,R7,LE,=A(L'S)) do j=1 to length(s) + LA R4,S-1 @s[0] + AR R4,R7 +j + MVC CCUR,0(R4) ccur=s[j] + TR CCUR,TABLE ccur=translate(ccur,table) + IF C,R7,EQ,=F'1' THEN if j=1 then + MVC CPREV,CCUR cprev=ccur + ELSE , else +* if ccur<>' ' and ccur<>'-' + IF CLI,CCUR,NE,C' ',AND,CLI,CCUR,NE,C'-', * + AND,CLC,CCUR,NE,CPREV THEN and ccur<>cprev then + IF C,R8,LT,=F'4' THEN if k<4 then + LA R8,1(R8) k=k+1 + LA R4,CODE-1(R8) @code[k] + MVC 0(1,R4),CCUR code[k]=ccur + ENDIF , endif + ENDIF , endif + IF CLI,CCUR,NE,C'-' THEN if ccur<>'-' then + MVC CPREV,CCUR cprev=ccur + ENDIF , endif + ENDIF , endif + LA R7,1(R7) j++ + ENDDO , enddo j + XDECO R6,XDEC edit i + MVC PG(2),XDEC+10 i + MVC PG+3(L'S),S s + MVC PG+15(L'CODE),CODE code + XPRNT PG,L'PG print + LA R6,1(R6) i++ + ENDDO , enddo i + L R13,4(0,R13) restore previous savearea pointer + LM R14,R12,12(R13) restore previous context + XR R15,R15 rc=0 + BR R14 exit +TT DC CL12'ashcraft',CL12'ashcroft',CL12'gauss',CL12'ghosh' + DC CL12'hilbert',CL12'heilbronn',CL12'lee',CL12'lloyd' + DC CL12'moses',CL12'pfister',CL12'robert',CL12'rupert' + DC CL12'rubin',CL12'tymczak',CL12'soundex',CL12'example' +TTEND EQU * +NTT EQU (TTEND-TT)/L'TT hbound(tt) +S DS CL12 +CCUR DS CL1 current +CPREV DS CL1 previous +CODE DS CL4 +PG DC CL80' ' +XDEC DS CL12 +TABLE DC CL256' ' translation table + ORG TABLE+C'A' + DC CL9' 123 12- ' ABCDEFGHI + ORG TABLE+C'J' + DC CL9'22455 126' JKLMNOPQR + ORG TABLE+C'S' + DC CL9'23 1-2 2' STUVWXYZ + ORG + YREGS + END SOUNDEX diff --git a/Task/Soundex/Crystal/soundex.crystal b/Task/Soundex/Crystal/soundex.crystal new file mode 100644 index 0000000000..2521ab7c46 --- /dev/null +++ b/Task/Soundex/Crystal/soundex.crystal @@ -0,0 +1,58 @@ +# version 0.21.1 + +def get_code(c : Char) + case c + when 'B', 'F', 'P', 'V' + "1" + when 'C', 'G', 'J', 'K', 'Q', 'S', 'X', 'Z' + "2" + when 'D', 'T' + "3" + when 'L' + "4" + when 'M', 'N' + "5" + when 'R' + "6" + when 'H', 'W' + "-" + else + "" + end +end + +def soundex(s : String) + return "" if s == "" + s = s.upcase + result = s[0,1] + prev = get_code s[0] + s.lchop.each_char {|c| + curr = get_code c + result += curr if curr != "" && curr != "-" && curr != prev + prev = curr unless curr == "-" + } + result.ljust(4, '0')[0, 4] +end + +pairs = [ + ["Ashcraft" , "A261"], + ["Ashcroft" , "A261"], + ["Gauss" , "G200"], + ["Ghosh" , "G200"], + ["Hilbert" , "H416"], + ["Heilbronn" , "H416"], + ["Lee" , "L000"], + ["Lloyd" , "L300"], + ["Moses" , "M220"], + ["Pfister" , "P236"], + ["Robert" , "R163"], + ["Rupert" , "R163"], + ["Rubin" , "R150"], + ["Tymczak" , "T522"], + ["Soundex" , "S532"], + ["Example" , "E251"] + ] + +pairs.each { |pair| + puts "#{pair[0].ljust(9)} -> #{pair[1]} -> #{soundex(pair[0]) == pair[1]}" +} diff --git a/Task/Soundex/Haskell/soundex-1.hs b/Task/Soundex/Haskell/soundex-1.hs deleted file mode 100644 index c09ccf5b28..0000000000 --- a/Task/Soundex/Haskell/soundex-1.hs +++ /dev/null @@ -1,2 +0,0 @@ -import Text.PhoneticCode.Soundex -import Control.Arrow diff --git a/Task/Soundex/Haskell/soundex-2.hs b/Task/Soundex/Haskell/soundex-2.hs deleted file mode 100644 index 51989c7a95..0000000000 --- a/Task/Soundex/Haskell/soundex-2.hs +++ /dev/null @@ -1,5 +0,0 @@ -*Main> mapM_ print $ map (id &&& soundexSimple) ["Soundex", "Example", "Sownteks", "Ekzampul"] -("Soundex","S532") -("Example","E251") -("Sownteks","S532") -("Ekzampul","E251") diff --git a/Task/Soundex/Haskell/soundex.hs b/Task/Soundex/Haskell/soundex.hs new file mode 100644 index 0000000000..28a960c557 --- /dev/null +++ b/Task/Soundex/Haskell/soundex.hs @@ -0,0 +1,6 @@ +import Text.PhoneticCode.Soundex + +main :: IO () +main = + mapM_ print $ + ((,) <*> soundexSimple) <$> ["Soundex", "Example", "Sownteks", "Ekzampul"] diff --git a/Task/Soundex/Java/soundex.java b/Task/Soundex/Java/soundex.java index 1512261393..c37d5656fe 100644 --- a/Task/Soundex/Java/soundex.java +++ b/Task/Soundex/Java/soundex.java @@ -28,7 +28,10 @@ private static String getCode(char c){ public static String soundex(String s){ String code, previous, soundex; code = s.toUpperCase().charAt(0) + ""; - previous = "7"; + + // EDITED : previous = "7"; + previous = getCode(s.toUpperCase().charAt(0)); + for(int i = 1;i < s.length();i++){ String current = getCode(s.toUpperCase().charAt(i)); if(current.length() > 0 && !current.equals(previous)){ diff --git a/Task/Soundex/Kotlin/soundex.kotlin b/Task/Soundex/Kotlin/soundex.kotlin new file mode 100644 index 0000000000..0340a3b8ac --- /dev/null +++ b/Task/Soundex/Kotlin/soundex.kotlin @@ -0,0 +1,48 @@ +// version 1.1.2 + +fun getCode(c: Char) = when (c) { + 'B', 'F', 'P', 'V' -> "1" + 'C', 'G', 'J', 'K', 'Q', 'S', 'X', 'Z' -> "2" + 'D', 'T' -> "3" + 'L' -> "4" + 'M', 'N' -> "5" + 'R' -> "6" + 'H', 'W' -> "-" + else -> "" +} + +fun soundex(s: String): String { + if (s == "") return "" + val sb = StringBuilder().append(s[0].toUpperCase()) + var prev = getCode(sb[0]) + for (i in 1 until s.length) { + val curr = getCode(s[i].toUpperCase()) + if (curr != "" && curr != "-" && curr != prev) sb.append(curr) + if (curr != "-") prev = curr + } + return sb.toString().padEnd(4, '0').take(4) +} + +fun main(args: Array) { + val pairs = arrayOf( + "Ashcraft" to "A261", + "Ashcroft" to "A261", + "Gauss" to "G200", + "Ghosh" to "G200", + "Hilbert" to "H416", + "Heilbronn" to "H416", + "Lee" to "L000", + "Lloyd" to "L300", + "Moses" to "M220", + "Pfister" to "P236", + "Robert" to "R163", + "Rupert" to "R163", + "Rubin" to "R150", + "Tymczak" to "T522", + "Soundex" to "S532", + "Example" to "E251" + ) + for (pair in pairs) { + println("${pair.first.padEnd(9)} -> ${pair.second} -> ${soundex(pair.first) == pair.second}") + } +} diff --git a/Task/Soundex/PicoLisp/soundex.l b/Task/Soundex/PicoLisp/soundex-1.l similarity index 100% rename from Task/Soundex/PicoLisp/soundex.l rename to Task/Soundex/PicoLisp/soundex-1.l diff --git a/Task/Soundex/PicoLisp/soundex-2.l b/Task/Soundex/PicoLisp/soundex-2.l new file mode 100644 index 0000000000..5c5a67ba8c --- /dev/null +++ b/Task/Soundex/PicoLisp/soundex-2.l @@ -0,0 +1,27 @@ +(de soundex (Str) + (let (Str (chop Str) Last) + (pack + (pad + -4 + (cons + (uppc (car Str)) + (head + 3 + (filter + gt0 + (cdr + (mapcar + '((C) + (and + (setq C + (case (uppc C) + (`(chop "AEIOUY") 0) + (`(chop "BFPV") 1) + (`(chop "CGJKQSXZ") 2) + (("D" "T") 3) + ("L" 4) + (("M" "N") 5) + ("R" 6) ) ) + (<> Last C) + (setq Last C) ) ) + Str ) ) ) ) ) ) ) ) ) diff --git a/Task/Soundex/PowerShell/soundex-1.psh b/Task/Soundex/PowerShell/soundex-1.psh new file mode 100644 index 0000000000..53cdc26192 --- /dev/null +++ b/Task/Soundex/PowerShell/soundex-1.psh @@ -0,0 +1,81 @@ +function Get-Soundex +{ + [CmdletBinding()] + [OutputType([PSCustomObject])] + Param + ( + [Parameter(Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true, + Position=0)] + [string[]] + $InputObject + ) + + Begin + { + $characterGroup = [PSCustomObject]@{ + 1 = @('B','F','P','V') + 2 = @('C','G','J','K','Q','S','X','Z') + 3 = @('D','T') + 4 = @('L') + 5 = @('M','N') + 6 = @('R') + } + + function ConvertTo-SoundexDigit ([char]$Character) + { + switch ($Character) + { + {$_ -in $characterGroup.1} {return 1} + {$_ -in $characterGroup.2} {return 2} + {$_ -in $characterGroup.3} {return 3} + {$_ -in $characterGroup.4} {return 4} + {$_ -in $characterGroup.5} {return 5} + {$_ -in $characterGroup.6} {return 6} + Default {return 0} + } + } + } + Process + { + foreach ($String in $InputObject) + { + $originalString = $String + $String = $String.ToUpper() + $isHorWcharacter = $false + $soundex = New-Object -TypeName System.Text.StringBuilder + + $soundex.Append($String[0]) | Out-Null + + for ($i = 1; $i -lt $String.Length; $i++) + { + $currentCharacterDigit = ConvertTo-SoundexDigit $String[$i] + + if ($currentCharacterDigit -ne 0) + { + if ($i -eq (ConvertTo-SoundexDigit $String[$i-1])) + { + continue + } + + if (($i -gt 2) -and ($isHorWcharacter) -and ($currentCharacterDigit -eq (ConvertTo-SoundexDigit $String[$i-2]))) + { + continue + } + + $soundex.Append($currentCharacterDigit) | Out-Null + } + + $isHorWcharacter = $String[$i] -in @('H','W') + } + + $soundexTail = ($soundex.ToString().Substring(1)).TrimStart((ConvertTo-SoundexDigit $String[0]).ToString()) + + [PSCustomObject]@{ + String = $originalString + Soundex = ($soundex[0] + $soundexTail).PadRight(4,"0").Substring(0,4) + } + } + } +} diff --git a/Task/Soundex/PowerShell/soundex-2.psh b/Task/Soundex/PowerShell/soundex-2.psh new file mode 100644 index 0000000000..8742eb8620 --- /dev/null +++ b/Task/Soundex/PowerShell/soundex-2.psh @@ -0,0 +1,2 @@ +"Ashcraft", "Ashcroft", "Gauss", "Ghosh", "Hilbert", "Heilbronn", "Lee", "Lloyd", +"Moses", "Pfister", "Robert", "Rupert", "Rubin", "Tymczak", "Soundex", "Example" | Get-Soundex diff --git a/Task/Soundex/Stata/soundex.stata b/Task/Soundex/Stata/soundex.stata new file mode 100644 index 0000000000..9fac859556 --- /dev/null +++ b/Task/Soundex/Stata/soundex.stata @@ -0,0 +1,5 @@ +. display soundex_nara("Ashcraft") +A261 + +. display soundex_nara("Tymczak") +T522 diff --git a/Task/Soundex/VBScript/soundex.vb b/Task/Soundex/VBScript/soundex.vb index 37f576d4b0..26cab7e98d 100644 --- a/Task/Soundex/VBScript/soundex.vb +++ b/Task/Soundex/VBScript/soundex.vb @@ -1,3 +1,16 @@ +' Soundex + tt=array( _ + "Ashcraft","Ashcroft","Gauss","Ghosh","Hilbert","Heilbronn","Lee","Lloyd", _ + "Moses","Pfister","Robert","Rupert","Rubin","Tymczak","Soundex","Example") + tv=array( _ + "A261","A261","G200","G200","H416","H416","L000","L300", _ + "M220","P236","R163","R163","R150","T522","S532","E251") + For i=lbound(tt) To ubound(tt) + ts=soundex(tt(i)) + If ts<>tv(i) Then ok=" KO "& tv(i) Else ok="" + Wscript.echo right(" "& i ,2) & " " & left( tt(i) &space(12),12) & " " & ts & ok + Next 'i + Function getCode(c) Select Case c Case "B", "F", "P", "V" @@ -12,22 +25,19 @@ Function getCode(c) getCode = "5" Case "R" getCode = "6" + Case "W","H" + getCode = "-" End Select -End Function +End Function 'getCode Function soundex(s) - Dim code, previous + Dim code, previous, i code = UCase(Mid(s, 1, 1)) - previous = 7 - For i = 2 to (Len(s) + 1) + previous = getCode(UCase(Mid(s, 1, 1))) + For i = 2 To Len(s) current = getCode(UCase(Mid(s, i, 1))) - If Len(current) > 0 And current <> previous Then - code = code & current - End If - previous = current - Next - soundex = Mid(code, 1, 4) - If Len(code) < 4 Then - soundex = soundex & String(4 - Len(code), "0") - End If -End Function + If current <> "" And current <> "-" And current <> previous Then code = code & current + If current <> "-" Then previous = current + Next 'i + soundex = Mid(code & "000", 1, 4) +End Function 'soundex diff --git a/Task/Sparkline-in-unicode/AppleScript/sparkline-in-unicode.applescript b/Task/Sparkline-in-unicode/AppleScript/sparkline-in-unicode.applescript index 1fbf56758d..147ef7705c 100644 --- a/Task/Sparkline-in-unicode/AppleScript/sparkline-in-unicode.applescript +++ b/Task/Sparkline-in-unicode/AppleScript/sparkline-in-unicode.applescript @@ -1,4 +1,6 @@ -use framework "Foundation" -- Yosemite onwards – for splitting by regex +use framework "Foundation" -- Yosemite onwards – for splitting by regex + +-- SPARKLINE ----------------------------------------------------------------- -- sparkLine :: [Num] -> String on sparkLine(xs) @@ -8,20 +10,20 @@ on sparkLine(xs) -- scale :: Num -> Num script scale - on lambda(x) + on |λ|(x) ((x - min) * 7) / dataRange - end lambda + end |λ| end script -- bucket :: Num -> String script bucket - on lambda(n) + on |λ|(n) if n ≥ 0 and n < 8 then item (n + 1 as integer) of "▁▂▃▄▅▆▇█" else missing value end if - end lambda + end |λ| end script intercalate("", map(bucket, map(scale, xs))) @@ -41,20 +43,20 @@ on numericOrdering(a, b) end numericOrdering --- TEST +-- TEST ---------------------------------------------------------------------- on run -- splitNumbers :: String -> [Real] script splitNumbers script asReal - on lambda(x) + on |λ|(x) x as real - end lambda + end |λ| end script - on lambda(s) + on |λ|(s) map(asReal, splitRegex("[\\s,]+", s)) - end lambda + end |λ| end script map(sparkLine, map(splitNumbers, ["1 2 3 4 5 6 7 8 7 6 5 4 3 2 1", ¬ @@ -66,9 +68,7 @@ on run end run - - --- GENERIC LIBRARY FUNCTIONS +-- GENERIC LIBRARY FUNCTIONS ------------------------------------------------- -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) @@ -76,19 +76,27 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -98,13 +106,13 @@ end map on maximumBy(f, xs) script max property cmp : f - on lambda(a, b) + on |λ|(a, b) if a is missing value or cmp(a, b) < 0 then b else a end if - end lambda + end |λ| end script foldl(max, missing value, xs) @@ -114,48 +122,29 @@ end maximumBy on minimumBy(f, xs) script min property cmp : f - on lambda(a, b) + on |λ|(a, b) if a is missing value or cmp(a, b) > 0 then b else a end if - end lambda + end |λ| end script foldl(min, missing value, xs) end minimumBy --- splitRegex :: RegexPattern -> String -> [String] -on splitRegex(strRegex, str) - set lstMatches to regexMatches(strRegex, str) - if length of lstMatches > 0 then - script preceding - on lambda(a, x) - set iFrom to start of a - set iLocn to (location of x) - - if iLocn > iFrom then - set strPart to text (iFrom + 1) thru iLocn of str - else - set strPart to "" - end if - {parts:parts of a & strPart, start:iLocn + (length of x) - 1} - end lambda - end script - - set recLast to foldl(preceding, {parts:[], start:0}, lstMatches) - - set iFinal to start of recLast - if iFinal < length of str then - parts of recLast & text (iFinal + 1) thru -1 of str - else - parts of recLast & "" - end if +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f else - {str} + script + property |λ| : f + end script end if -end splitRegex +end mReturn -- regexMatches :: RegexPattern -> String -> [{location:Int, length:Int}] on regexMatches(strRegex, str) @@ -173,22 +162,33 @@ on regexMatches(strRegex, str) lstMatches end regexMatches --- intercalate :: Text -> [Text] -> Text -on intercalate(strText, lstText) - set {dlm, my text item delimiters} to {my text item delimiters, strText} - set strJoined to lstText as text - set my text item delimiters to dlm - return strJoined -end intercalate +-- splitRegex :: RegexPattern -> String -> [String] +on splitRegex(strRegex, str) + set lstMatches to regexMatches(strRegex, str) + if length of lstMatches > 0 then + script preceding + on |λ|(a, x) + set iFrom to start of a + set iLocn to (location of x) --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f + if iLocn > iFrom then + set strPart to text (iFrom + 1) thru iLocn of str + else + set strPart to "" + end if + {parts:parts of a & strPart, start:iLocn + (length of x) - 1} + end |λ| end script + + set recLast to foldl(preceding, {parts:[], start:0}, lstMatches) + + set iFinal to start of recLast + if iFinal < length of str then + parts of recLast & text (iFinal + 1) thru -1 of str + else + parts of recLast & "" + end if + else + {str} end if -end mReturn +end splitRegex diff --git a/Task/Sparkline-in-unicode/Common-Lisp/sparkline-in-unicode.lisp b/Task/Sparkline-in-unicode/Common-Lisp/sparkline-in-unicode.lisp new file mode 100644 index 0000000000..7bed22ed90 --- /dev/null +++ b/Task/Sparkline-in-unicode/Common-Lisp/sparkline-in-unicode.lisp @@ -0,0 +1,43 @@ +(defun buckets (numbers) + (loop with min = (apply #'min numbers) + with max = (apply #'max numbers) + with width = (/ (- max min) 7) + for base from (- min (/ width 2)) by width + repeat 8 + collect (cons base (+ base width)))) + +(defun bucket-for-number (number buckets) + (loop for i from 0 + for (min . max) in buckets + when (and (<= min number) (< number max)) + return i)) + +(defun sparkline (numbers) + (loop with buckets = (buckets numbers) + with sparks = "▁▂▃▄▅▆▇█" + with sparkline = (make-array (length numbers) :element-type 'character) + with min = (apply #'min numbers) + with max = (apply #'max numbers) + for number in numbers + for i from 0 + for bucket = (bucket-for-number number buckets) + do (setf (aref sparkline i) (char sparks bucket)) + finally (format t "Min: ~A, Max: ~A, Range: ~A~%" min max (- max min)) + (write-line sparkline))) + +(defun string->numbers (string) + (flet ((delimiterp (c) + (or (char= c #\Space) (char= c #\,)))) + (loop for prev-end = 0 then end + while prev-end + for start = (position-if-not #'delimiterp string :start prev-end) + for end = (position-if #'delimiterp string :start start) + for number = (read-from-string string t nil :start start :end end) + do (assert (numberp number)) + collect number))) + +(defun string->sparkline (string) + (sparkline (string->numbers string))) + +(string->sparkline "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1") +(string->sparkline "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5") diff --git a/Task/Sparkline-in-unicode/Haskell/sparkline-in-unicode.hs b/Task/Sparkline-in-unicode/Haskell/sparkline-in-unicode-1.hs similarity index 100% rename from Task/Sparkline-in-unicode/Haskell/sparkline-in-unicode.hs rename to Task/Sparkline-in-unicode/Haskell/sparkline-in-unicode-1.hs diff --git a/Task/Sparkline-in-unicode/Haskell/sparkline-in-unicode-2.hs b/Task/Sparkline-in-unicode/Haskell/sparkline-in-unicode-2.hs new file mode 100644 index 0000000000..04999bf486 --- /dev/null +++ b/Task/Sparkline-in-unicode/Haskell/sparkline-in-unicode-2.hs @@ -0,0 +1,22 @@ +import Data.List.Split (splitOneOf) + +sparkLine :: [Float] -> String +sparkLine xs = + (("▁▂▃▄▅▆▇█" !!) . floor . (/ range) . (7 *) . subtract min) <$> xs + where + min = minimum xs + range = maximum xs - min + +parseFloats :: String -> [Float] +parseFloats = (read <$>) . filter (not . null) . splitOneOf " ," + +main :: IO () +main = + mapM_ + putStrLn + ((sparkLine . parseFloats) <$> + [ "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" + , "3 2 1 0 -1 -2 -3 -4 -3 -2 -1 0 1 2 3" + , "-1000 100 1000 500 200 -400 -700 621 -189 3" + ]) diff --git a/Task/Sparkline-in-unicode/J/sparkline-in-unicode-4.j b/Task/Sparkline-in-unicode/J/sparkline-in-unicode-4.j deleted file mode 100644 index fe3a30b470..0000000000 --- a/Task/Sparkline-in-unicode/J/sparkline-in-unicode-4.j +++ /dev/null @@ -1,4 +0,0 @@ - spkln 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 -▁▂▃▄▅▆▇█▇▆▅▄▃▂▁ - spkln 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 -▁▅█▆▅▃▂▇▄▅ diff --git a/Task/Sparkline-in-unicode/jq/sparkline-in-unicode.jq b/Task/Sparkline-in-unicode/Jq/sparkline-in-unicode.jq similarity index 100% rename from Task/Sparkline-in-unicode/jq/sparkline-in-unicode.jq rename to Task/Sparkline-in-unicode/Jq/sparkline-in-unicode.jq diff --git a/Task/Sparkline-in-unicode/Rust/sparkline-in-unicode.rust b/Task/Sparkline-in-unicode/Rust/sparkline-in-unicode.rust new file mode 100644 index 0000000000..1ad05cc52c --- /dev/null +++ b/Task/Sparkline-in-unicode/Rust/sparkline-in-unicode.rust @@ -0,0 +1,17 @@ +const BARS: &'static str = "▁▂▃▄▅▆▇█"; + +fn print_sparkline(s: &str){ + let v = BARS.chars().collect::>(); + let line: String = s.replace(",", " ").split(" ") + .filter(|x| !x.is_empty()) + .map(|x| v[x.parse::().unwrap().ceil() as usize - 1]) + .collect(); + println!("{:?}", line); +} + +fn main(){ + let s1 = "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1"; + print_sparkline(s1); + let s2 = "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"; + print_sparkline(s2); +} diff --git a/Task/Sparkline-in-unicode/S-lang/sparkline-in-unicode.slang b/Task/Sparkline-in-unicode/S-lang/sparkline-in-unicode.slang new file mode 100644 index 0000000000..f669a9efca --- /dev/null +++ b/Task/Sparkline-in-unicode/S-lang/sparkline-in-unicode.slang @@ -0,0 +1,25 @@ +% Just to demonstrate alternate ways of defining unicode: +private variable spchrs = "\u{2581}\u{2582}\u{2583}\u{2584}\u{2585}\u{2586}\u{2587}\u{2588}"; +private variable spchrs_alt = "▁▂▃▄▅▆▇█"; + +define sparkline(arrstr) +{ + variable a = strtok(arrstr, " \t,"), alen = length(a), out = ""; + a = atof(a); + variable amin = min(a), amax = max(a), span = amax - amin, i, d; + + _for i (0, alen-1, 1) + if (span != 0) { + % int() truncates; adding .5 here to round: + d = int((a[i] - amin) * 7.0 / span + 0.5); + out += substr(spchrs, d+1, 1); + } + else + out += substr(spchrs, 4, 1); + + print(out); +} + +if (not _slang_utf8_ok) error("Sorry, UTF8 mode is not on."); +sparkline("1 2 3 4 5 6 7 8 7 6 5 4 3 2 1"); +sparkline("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 "); diff --git a/Task/Sparkline-in-unicode/Zkl/sparkline-in-unicode-1.zkl b/Task/Sparkline-in-unicode/Zkl/sparkline-in-unicode-1.zkl new file mode 100644 index 0000000000..4cbb94930e --- /dev/null +++ b/Task/Sparkline-in-unicode/Zkl/sparkline-in-unicode-1.zkl @@ -0,0 +1,9 @@ +var sparks=[0x2581..0x2588].apply("toString",-8); // int.toString(-8)-->UTF-8 +var sl=(sparks.len()-1); + +fcn sparkLine(xs){ + min:=(0.0).min(xs); max:=(0.0).max(xs); // min/max are float reguardless of xs + range:=max-min; // float + println("Range [",min,"-",max,"]", xs); + xs.pump(String,'wrap(x){ sparks[(x - min)*sl/range] }).println(); +} diff --git a/Task/Sparkline-in-unicode/Zkl/sparkline-in-unicode-2.zkl b/Task/Sparkline-in-unicode/Zkl/sparkline-in-unicode-2.zkl new file mode 100644 index 0000000000..f4904f6c8c --- /dev/null +++ b/Task/Sparkline-in-unicode/Zkl/sparkline-in-unicode-2.zkl @@ -0,0 +1,3 @@ +one:="1 2 3 4 5 6 7 8 7 6 5 4 3 2 1".split(" ").apply("toInt"); +two:=("1.5, 0.5 3.5, 2.5 5.5 4.5 7.5, 6.5" - ",").split(" ").apply("toFloat"); +sparkLine(one); sparkLine(two); diff --git a/Task/Special-characters/jq/special-characters.jq b/Task/Special-characters/Jq/special-characters.jq similarity index 100% rename from Task/Special-characters/jq/special-characters.jq rename to Task/Special-characters/Jq/special-characters.jq diff --git a/Task/Special-characters/Ol/special-characters-1.ol b/Task/Special-characters/Ol/special-characters-1.ol new file mode 100644 index 0000000000..c94b9a2b54 --- /dev/null +++ b/Task/Special-characters/Ol/special-characters-1.ol @@ -0,0 +1,3 @@ +(print #\|) (print #\#) +; ==> 124 +; ==> 35 diff --git a/Task/Special-characters/Ol/special-characters-2.ol b/Task/Special-characters/Ol/special-characters-2.ol new file mode 100644 index 0000000000..1a589c7d8c --- /dev/null +++ b/Task/Special-characters/Ol/special-characters-2.ol @@ -0,0 +1,7 @@ +(define |I'm the ,`stra[]ge symbol :))| 123) + +(print (put #empty '|I'm the ,`stra[]ge symbol :))| 444)) +; ==> #((|I'm the ,`stra[]ge symbol :))| . 444)) + +(print (+ |I'm the ,`stra[]ge symbol :))| 17)) +; ==> 140 diff --git a/Task/Special-variables/ALGOL-W/special-variables.alg b/Task/Special-variables/ALGOL-W/special-variables.alg new file mode 100644 index 0000000000..2d0dd957e0 --- /dev/null +++ b/Task/Special-variables/ALGOL-W/special-variables.alg @@ -0,0 +1,45 @@ +% the Algol W standard environment includes the following standard variables: % + +integer I_W % field width for integer output % +integer R_W % field width for real output % +integer R_D % number of decimal places for real output % +string(1) R_FORMAT % format for real output: + S - "scaled" normalised mantissa with exponent + A - "aligned" fixed point format + F - "free" either scaled or aligned as appropriate + for the value and field width + % +integer S_W % separator width - number of spaces following non-string output items % +integer MAXINTEGER % largest integer value % +real EPSILON % largest positive real number such that 1 + epsilon = 1 % +long real LONGEPSILON % largest positive long real number such that 1 + longepsilon = 1 % +long real MAXREAL % largest real number % +long real PI % approximation to pi % + +% the following reference(EXCEPTION) variables control how errors are handled: + ENDFILE - end-of-file + OVFL - overflow + UNFL - underflow + DIVZERO - division by zero + INTOVFL - integer overflow + INTDIVZERO - integer division by zero or modulo 0 + SQRTERR - invalid SQRT parameter + EXPERR - invalid EXP parameter + LNLOGERR - invalid LN or LOG parameter + SINCOSERR - invalid SIN or COS parameter + +The EXCEPTION record is defined as follows: + +record EXCEPTION( logical XCPNOTED - true if the exception has occurred + ; integer XCPLIMIT - number of times the exception can occur + before the program terminates + , XCPACTION - if the program continues, controls how to + replace the erroneous value + ; logical XCPMARK - true if an error message should be printed + even if the program continues + ; string(64) XCPMSG - message to describe the exception + ) + +if the relevant EXCEPTION variable is null, the exception is ignored, +otherwise it is processed according to the settings of XCPLIMIT etc. +% diff --git a/Task/Special-variables/C/special-variables.c b/Task/Special-variables/C/special-variables.c deleted file mode 100644 index 8bbc712548..0000000000 --- a/Task/Special-variables/C/special-variables.c +++ /dev/null @@ -1 +0,0 @@ -int main(int argc, char **argv){...} diff --git a/Task/Special-variables/Fortran/special-variables.f b/Task/Special-variables/Fortran/special-variables.f new file mode 100644 index 0000000000..e87a8f7032 --- /dev/null +++ b/Task/Special-variables/Fortran/special-variables.f @@ -0,0 +1,4 @@ + INQUIRE(FILE = FILENAME(1:L),EXIST = EXIST, !Here we go. Does the file exist? + 1 ERR = 666,IOSTAT = IOSTAT) !Hopefully, named in good style, etc. + IF (EXIST) THEN !So, does the named file already exist? + ...etc. diff --git a/Task/Special-variables/jq/special-variables.jq b/Task/Special-variables/Jq/special-variables.jq similarity index 100% rename from Task/Special-variables/jq/special-variables.jq rename to Task/Special-variables/Jq/special-variables.jq diff --git a/Task/Special-variables/Kotlin/special-variables.kotlin b/Task/Special-variables/Kotlin/special-variables.kotlin new file mode 100644 index 0000000000..b49ae56547 --- /dev/null +++ b/Task/Special-variables/Kotlin/special-variables.kotlin @@ -0,0 +1,24 @@ +// version 1.0.6 + +class President(val name: String) { + var age: Int = 0 + set(value) { + if (value in 0..125) field = value // assigning to backing field here + else throw IllegalArgumentException("$name's age must be between 0 and 125") + } +} + +fun main(args: Array) { + val pres = President("Donald") + pres.age = 69 + val pres2 = President("Jimmy") + pres2.age = 91 + val presidents = mutableListOf(pres, pres2) + presidents.forEach { + it.age++ // 'it' is implicit sole parameter of lambda expression + println("President ${it.name}'s age is currently ${it.age}") + } + println() + val pres3 = President("Theodore") + pres3.age = 158 +} diff --git a/Task/Special-variables/Tcl/special-variables-1.tcl b/Task/Special-variables/Tcl/special-variables-1.tcl deleted file mode 100644 index 39128cce71..0000000000 --- a/Task/Special-variables/Tcl/special-variables-1.tcl +++ /dev/null @@ -1 +0,0 @@ -__DATE__, __DEBUG__, __FILE__, __LINE__, __NAME__, __TIME__ diff --git a/Task/Spiral-matrix/AppleScript/spiral-matrix.applescript b/Task/Spiral-matrix/AppleScript/spiral-matrix.applescript index d1a7f282ce..77099c55b5 100644 --- a/Task/Spiral-matrix/AppleScript/spiral-matrix.applescript +++ b/Task/Spiral-matrix/AppleScript/spiral-matrix.applescript @@ -1,8 +1,10 @@ --- Int -> Int -> Int -> [[Int]] +-- SPIRAL MATRIX ------------------------------------------------------------- + +-- spiral :: Int -> Int -> Int -> [[Int]] on spiral(lngRows, lngCols, nStart) if lngRows > 0 then - {range(nStart, (nStart + lngCols) - 1)} & ¬ - map(my _reverse, ¬ + {enumFromTo(nStart, (nStart + lngCols) - 1)} & ¬ + map(my |reverse|, ¬ transpose(spiral(lngCols, lngRows - 1, nStart + lngCols))) else {{}} @@ -10,7 +12,7 @@ on spiral(lngRows, lngCols, nStart) end spiral --- TEST +-- TEST ---------------------------------------------------------------------- on run set n to 5 set lstSpiral to spiral(n, n, 0) @@ -24,17 +26,17 @@ on run end run --- WIKI TABLE FORMAT +-- WIKI TABLE FORMAT --------------------------------------------------------- -- wikiTable :: [Text] -> Bool -> Text -> Text on wikiTable(lstRows, blnHdr, strStyle) script fWikiRows - on lambda(lstRow, iRow) + on |λ|(lstRow, iRow) set strDelim to cond(blnHdr and (iRow = 0), "!", "|") set strDbl to strDelim & strDelim linefeed & "|-" & linefeed & strDelim & space & ¬ intercalate(space & strDbl & space, lstRow) - end lambda + end |λ| end script linefeed & "{| class=\"wikitable\" " & ¬ @@ -44,57 +46,20 @@ on wikiTable(lstRows, blnHdr, strStyle) end wikiTable --- GENERIC LIBRARY FUNCTIONS +-- GENERIC FUNCTIONS --------------------------------------------------------- --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map - --- transpose :: [[a]] -> [[a]] -on transpose(xss) - script column - on lambda(_, iCol) - script row - on lambda(xs) - item iCol of xs - end lambda - end script - - map(row, xss) - end lambda - end script - - map(column, item 1 of xss) -end transpose - --- _reverse :: [a] -> [a] -on _reverse(xs) - if class of xs is text then - (reverse of characters of xs) as text +-- cond :: Bool -> a -> a -> a +on cond(bool, x, y) + if bool then + x else - reverse of xs + y end if -end _reverse +end cond --- Text -> [Text] -> Text -on intercalate(strText, lstText) - set {dlm, my text item delimiters} to {my text item delimiters, strText} - set strJoined to lstText as text - set my text item delimiters to dlm - return strJoined -end intercalate - --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then set d to -1 else set d to 1 @@ -104,16 +69,27 @@ on range(m, n) set end of lst to i end repeat return lst -end range +end enumFromTo --- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b) -on cond(bool, f, g) - if bool then - f - else - g - end if -end cond +-- Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -122,7 +98,33 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn + +-- reverse :: [a] -> [a] +on |reverse|(xs) + if class of xs is text then + (reverse of characters of xs) as text + else + reverse of xs + end if +end |reverse| + +-- transpose :: [[a]] -> [[a]] +on transpose(xss) + script column + on |λ|(_, iCol) + script row + on |λ|(xs) + item iCol of xs + end |λ| + end script + + map(row, xss) + end |λ| + end script + + map(column, item 1 of xss) +end transpose diff --git a/Task/Spiral-matrix/Clojure/spiral-matrix-1.clj b/Task/Spiral-matrix/Clojure/spiral-matrix-1.clj new file mode 100644 index 0000000000..87f411da9c --- /dev/null +++ b/Task/Spiral-matrix/Clojure/spiral-matrix-1.clj @@ -0,0 +1,16 @@ +(defn spiral [n] + (let [cyc (cycle [1 n -1 (- n)])] + (->> (range (dec n) 0 -1) + (mapcat #(repeat 2 %)) + (cons n) + (mapcat #(repeat %2 %) cyc) + (reductions +) + (map vector (range 0 (* n n))) + (sort-by second) + (map first))) + +(let [n 5] + (clojure.pprint/cl-format + true + (str " ~{~<~%~," (* n 3) ":;~2d ~>~}~%") + (spiral n))) diff --git a/Task/Spiral-matrix/Clojure/spiral-matrix-2.clj b/Task/Spiral-matrix/Clojure/spiral-matrix-2.clj new file mode 100644 index 0000000000..2581176f82 --- /dev/null +++ b/Task/Spiral-matrix/Clojure/spiral-matrix-2.clj @@ -0,0 +1,8 @@ +(defn spiral-matrix [m n & [start]] + (let [row (list (map #(+ start %) (range m)))] + (if (= 1 n) row + (concat row (map reverse + (apply map list + (spiral-matrix (dec n) m (+ start m)))))))) + +(defn spiral [n m] (spiral-matrix n m 1)) diff --git a/Task/Spiral-matrix/Clojure/spiral-matrix.clj b/Task/Spiral-matrix/Clojure/spiral-matrix.clj deleted file mode 100644 index 23ed0ae869..0000000000 --- a/Task/Spiral-matrix/Clojure/spiral-matrix.clj +++ /dev/null @@ -1,16 +0,0 @@ -(defn spiral [n] - (let [cyc (cycle [1 n -1 (- n)])] - (->> (range (dec n) 0 -1) - (mapcat #(repeat 2 %)) - (cons n) - #(mapcat repeat % cyc) - (reductions +) - (map vector (range 0 (* n n))) - (sort-by second) - (map first))) - -(let [n 5] - (clojure.pprint/cl-format - true - (str " ~{~<~%~," (* n 3) ":;~2d ~>~}~%") - (spiral n))) diff --git a/Task/Spiral-matrix/Haskell/spiral-matrix-4.hs b/Task/Spiral-matrix/Haskell/spiral-matrix-4.hs new file mode 100644 index 0000000000..8690da4a17 --- /dev/null +++ b/Task/Spiral-matrix/Haskell/spiral-matrix-4.hs @@ -0,0 +1,11 @@ +import Data.List (transpose) + +spiral :: Int -> Int -> Int -> [[Int]] +spiral rows cols start = + if rows > 0 + then [start .. start + cols - 1] : + (reverse <$> transpose (spiral cols (rows - 1) (start + cols))) + else [[]] + +main :: IO () +main = mapM_ print $ spiral 5 5 0 diff --git a/Task/Spiral-matrix/jq/spiral-matrix-1.jq b/Task/Spiral-matrix/Jq/spiral-matrix-1.jq similarity index 100% rename from Task/Spiral-matrix/jq/spiral-matrix-1.jq rename to Task/Spiral-matrix/Jq/spiral-matrix-1.jq diff --git a/Task/Spiral-matrix/jq/spiral-matrix-2.jq b/Task/Spiral-matrix/Jq/spiral-matrix-2.jq similarity index 100% rename from Task/Spiral-matrix/jq/spiral-matrix-2.jq rename to Task/Spiral-matrix/Jq/spiral-matrix-2.jq diff --git a/Task/Spiral-matrix/Kotlin/spiral-matrix.kotlin b/Task/Spiral-matrix/Kotlin/spiral-matrix.kotlin new file mode 100644 index 0000000000..f77a6581dc --- /dev/null +++ b/Task/Spiral-matrix/Kotlin/spiral-matrix.kotlin @@ -0,0 +1,40 @@ +// version 1.1.3 + +typealias Vector = IntArray +typealias Matrix = Array + +fun spiralMatrix(n: Int): Matrix { + val result = Matrix(n) { Vector(n) } + var pos = 0 + var count = n + var value = -n + var sum = -1 + do { + value = -value / n + for (i in 0 until count) { + sum += value + result[sum / n][sum % n] = pos++ + } + value *= n + count-- + for (i in 0 until count) { + sum += value + result[sum / n][sum % n] = pos++ + } + } + while (count > 0) + return result +} + +fun printMatrix(m: Matrix) { + for (i in 0 until m.size) { + for (j in 0 until m.size) print("%2d ".format(m[i][j])) + println() + } + println() +} + +fun main(args: Array) { + printMatrix(spiralMatrix(5)) + printMatrix(spiralMatrix(10)) +} diff --git a/Task/Spiral-matrix/OoRexx/spiral-matrix.rexx b/Task/Spiral-matrix/OoRexx/spiral-matrix.rexx new file mode 100644 index 0000000000..56991feda5 --- /dev/null +++ b/Task/Spiral-matrix/OoRexx/spiral-matrix.rexx @@ -0,0 +1,55 @@ +call printArray generateArray(3) +say +call printArray generateArray(4) +say +call printArray generateArray(5) + +::routine generateArray + use arg dimension + -- the output array + array = .array~new(dimension, dimension) + + -- get the number of squares, including the center one if + -- the dimension is odd + squares = dimension % 2 + dimension // 2 + -- length of a side for the current square + sidelength = dimension + current = 0 + loop i = 1 to squares + -- do each side of the current square + -- top side + loop j = 0 to sidelength - 1 + array[i, i + j] = current + current += 1 + end + -- down the right side + loop j = 1 to sidelength - 1 + array[i + j, dimension - i + 1] = current + current += 1 + end + -- across the bottom + loop j = sidelength - 2 to 0 by -1 + array[dimension - i + 1, i + j] = current + current += 1 + end + -- and up the left side + loop j = sidelength - 2 to 1 by -1 + array[i + j, i] = current + current += 1 + end + -- reduce the length of the side by two rows + sidelength -= 2 + end + return array + +::routine printArray + use arg array + dimension = array~dimension(1) + loop i = 1 to dimension + line = "|" + loop j = 1 to dimension + line = line array[i, j]~right(2) + end + line = line "|" + say line + end diff --git a/Task/Spiral-matrix/Perl-6/spiral-matrix-1.pl6 b/Task/Spiral-matrix/Perl-6/spiral-matrix-1.pl6 index 21220b6829..b1956846c4 100644 --- a/Task/Spiral-matrix/Perl-6/spiral-matrix-1.pl6 +++ b/Task/Spiral-matrix/Perl-6/spiral-matrix-1.pl6 @@ -1,47 +1,40 @@ -enum Dir < north northeast east southeast south southwest west northwest >; -my $debug = 0; - class Turtle { - has @.loc = 0,0; - has Dir $.dir = north; - my @dv = [0,-1], [1,-1], [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1]; - my @num-to-dir = Dir.invert.sort».value; - my $points = +Dir; + my $points = 8; # 'compass' points of neighbors on grid: north=0, northeast=1, east=2, etc. - my %world; - my $maxegg; - my $range-x; - my $range-y; + has @.loc = 0,0; + has $.dir = 0; + has %.world; + has $.maxegg; + has $.range-x; + has $.range-y; method turn-left ($angle = 90) { $!dir -= $angle / 45; $!dir %= $points; } method turn-right($angle = 90) { $!dir += $angle / 45; $!dir %= $points; } method lay-egg($egg) { - %world{~@!loc} = $egg; - $maxegg max= $egg; - $range-x minmax= @!loc[0]; - $range-y minmax= @!loc[1]; + %!world{~@!loc} = $egg; + $!maxegg max= $egg; + $!range-x minmax= @!loc[0]; + $!range-y minmax= @!loc[1]; } method look($ahead = 1) { - my $there = @!loc »+« (@dv[$!dir] X* $ahead); - say "looking @num-to-dir[$!dir] to $there" if $debug; - %world{~$there}; + my $there = @!loc »+« @dv[$!dir] »*» $ahead; + %!world{~$there}; } method forward($ahead = 1) { - my $there = @!loc »+« (@dv[$!dir] X* $ahead); - @!loc = @($there); - say " moving @num-to-dir[$!dir] to @!loc[]" if $debug; + my $there = @!loc »+« @dv[$!dir] »*» $ahead; + @!loc = @($there); } method showmap() { - my $form = "%{$maxegg.chars}s"; - my $endx = $range-x.max; - for $range-y.list X $range-x.list -> $y, $x { - print (%world{"$x $y"} // '').fmt($form); - print $x == $endx ?? "\n" !! ' '; - } + my $form = "%{$!maxegg.chars}s"; + my $endx = $!range-x.max; + for $!range-y.list X $!range-x.list -> ($y, $x) { + print (%!world{"$x $y"} // '').fmt($form); + print $x == $endx ?? "\n" !! ' '; + } } } diff --git a/Task/Spiral-matrix/Perl-6/spiral-matrix-2.pl6 b/Task/Spiral-matrix/Perl-6/spiral-matrix-2.pl6 index 8d331f59dd..03867c65d8 100644 --- a/Task/Spiral-matrix/Perl-6/spiral-matrix-2.pl6 +++ b/Task/Spiral-matrix/Perl-6/spiral-matrix-2.pl6 @@ -1,16 +1,16 @@ sub MAIN($size as Int) { - my $t = Turtle.new(dir => east); - my $counter = 0; - $t.forward(-1); - for 0..^ $size -> $ { - $t.forward; - $t.lay-egg($counter++); - } - for $size-1 ... 1 -> $run { - $t.turn-right; - $t.forward, $t.lay-egg($counter++) for 0..^$run; - $t.turn-right; - $t.forward, $t.lay-egg($counter++) for 0..^$run; - } - $t.showmap; +my $t = Turtle.new(dir => 2); +my $counter = 0; +$t.forward(-1); +for 0..^ $size -> $ { + $t.forward; + $t.lay-egg($counter++); +} +for $size-1 ... 1 -> $run { + $t.turn-right; + $t.forward, $t.lay-egg($counter++) for 0..^$run; + $t.turn-right; + $t.forward, $t.lay-egg($counter++) for 0..^$run; +} +$t.showmap; } diff --git a/Task/Spiral-matrix/Perl-6/spiral-matrix-3.pl6 b/Task/Spiral-matrix/Perl-6/spiral-matrix-3.pl6 index 5d5f42f80e..2b1f069102 100644 --- a/Task/Spiral-matrix/Perl-6/spiral-matrix-3.pl6 +++ b/Task/Spiral-matrix/Perl-6/spiral-matrix-3.pl6 @@ -1,11 +1,11 @@ sub MAIN($size as Int) { - my $t = Turtle.new(dir => ($size %% 2 ?? south !! north)); - my $counter = $size * $size; - while $counter { - $t.lay-egg(--$counter); - $t.turn-left; - $t.turn-right if $t.look; - $t.forward; - } - $t.showmap; +my $t = Turtle.new(dir => ($size %% 2 ?? 4 !! 0)); +my $counter = $size * $size; +while $counter { + $t.lay-egg(--$counter); + $t.turn-left; + $t.turn-right if $t.look; + $t.forward; +} +$t.showmap; } diff --git a/Task/Spiral-matrix/REXX/spiral-matrix-1.rexx b/Task/Spiral-matrix/REXX/spiral-matrix-1.rexx index f1779a0a8e..ae6c274e93 100644 --- a/Task/Spiral-matrix/REXX/spiral-matrix-1.rexx +++ b/Task/Spiral-matrix/REXX/spiral-matrix-1.rexx @@ -1,21 +1,22 @@ -/*REXX program displays a spiral in a square array (of any size) from a start number.*/ -parse arg size . /*obtain optional arguments from the CL*/ -if size=='' | size=="," then size=5 /*Not specified? Then use the default.*/ -tot=size**2; L=length(tot) /*total number of elements in spiral. */ +/*REXX program displays a spiral in a square array (of any size) starting at START. */ +parse arg size start . /*obtain optional arguments from the CL*/ +if size =='' | size =="," then size =5 /*Not specified? Then use the default.*/ +if start=='' | start=="," then start=0 /*Not specified? Then use the default.*/ +tot=size**2; L=length(tot + start) /*total number of elements in spiral. */ k=size /*K: is the counter for the spiral. */ -row=1; col=0; start=0 /*start spiral at row 1, column 0. */ +row=1; col=0 /*start spiral at row 1, column 0. */ /* [↓] construct the numbered spiral. */ - do n=start for k; col=col+1; @.col.row=n; end; if k==0 then exit + do n=0 for k; col=col + 1; @.col.row=n + start; end; if k==0 then exit /* [↑] build the first row of spiral. */ do until n>=tot /*spiral matrix.*/ do one=1 to -1 by -2 until n>=tot; k=k-1 /*perform twice.*/ - do n=n for k; row=row+one; @.col.row=n; end /*for the row···*/ - do n=n for k; col=col-one; @.col.row=n; end /* " " col···*/ + do n=n for k; row=row + one; @.col.row=n + start; end /*for the row···*/ + do n=n for k; col=col - one; @.col.row=n + start; end /* " " col···*/ end /*one*/ /* ↑↓ direction.*/ end /*until n≥tot*/ /* [↑] done with the matrix spiral. */ /* [↓] display spiral to the screen. */ - do r=1 for size; _= right(@.1.r, L) /*construct display row by row. */ - do c=2 for size-1; _=_ right(@.c.r, L) /*construct a line for the display. */ + do r=1 for size; _= right(@.1.r, L) /*construct display row by row. */ + do c=2 for size -1; _=_ right(@.c.r, L) /*construct a line for the display. */ end /*col*/ /* [↑] line has an extra leading blank*/ - say _ /*display a line (row) of the sprial. */ + say _ /*display a line (row) of the spiral. */ end /*row*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Spiral-matrix/REXX/spiral-matrix-2.rexx b/Task/Spiral-matrix/REXX/spiral-matrix-2.rexx index f7b5673e23..5badd02510 100644 --- a/Task/Spiral-matrix/REXX/spiral-matrix-2.rexx +++ b/Task/Spiral-matrix/REXX/spiral-matrix-2.rexx @@ -1,16 +1,17 @@ -/*REXX program displays a spiral in a square array (of any size) from a start number.*/ -parse arg size . /*obtain optional arguments from the CL*/ -if size=='' | size=="," then size=5 /*Not specified? Then use the default.*/ -tot=size**2; L=length(tot) /*total number of elements in spiral. */ +/*REXX program displays a spiral in a square array (of any size) starting at START. */ +parse arg size start . /*obtain optional arguments from the CL*/ +if size =='' | size =="," then size =5 /*Not specified? Then use the default.*/ +if start=='' | start=="," then start=0 /*Not specified? Then use the default.*/ +tot=size**2; L=length(tot + start) /*total number of elements in spiral. */ k=size /*K: is the counter for the spiral. */ -row=1; col=0; start=0 /*start spiral at row 1, column 0. */ +row=1; col=0 /*start spiral at row 1, column 0. */ /* [↓] construct the numbered spiral. */ - do n=start for k; col=col+1; @.col.row=n; end; if k==0 then exit + do n=0 for k; col=col + 1; @.col.row=n + start; end; if k==0 then exit /* [↑] build the first row of spiral. */ do until n>=tot /*spiral matrix.*/ - do one=1 to -1 by -2 until n>=tot; k=k-1 /*perform twice.*/ - do n=n for k; row=row+one; @.col.row=n; end /*for the row···*/ - do n=n for k; col=col-one; @.col.row=n; end /* " " col···*/ + do one=1 to -1 by -2 until n>=tot; k=k - 1 /*perform twice.*/ + do n=n for k; row=row + one; @.col.row=n + start; end /*for the row···*/ + do n=n for k; col=col - one; @.col.row=n + start; end /* " " col···*/ end /*one*/ /* ↑↓ direction.*/ end /*until n≥tot*/ /* [↑] done with the matrix spiral. */ !.=0 /* [↓] display spiral to the screen. */ @@ -20,6 +21,6 @@ row=1; col=0; start=0 /*start spiral at row 1, co if two then _=_ right(x, !.c) /*construct a line for the display. */ else !.c=max(!.c, length(x)) /*find the maximum width of the column.*/ end /*c*/ /* [↓] line has an extra leading blank*/ - if two then say substr(_,2) /*this SUBSTR ignores the first blank. */ + if two then say substr(_, 2) /*this SUBSTR ignores the first blank. */ end /*r*/ end /*two*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Spiral-matrix/Sidef/spiral-matrix.sidef b/Task/Spiral-matrix/Sidef/spiral-matrix.sidef index c43d845aa4..f52825a64e 100644 --- a/Task/Spiral-matrix/Sidef/spiral-matrix.sidef +++ b/Task/Spiral-matrix/Sidef/spiral-matrix.sidef @@ -1,20 +1,20 @@ func spiral(n) { - var (x, y, dx, dy, a) = (0, 0, 1, 0, []); + var (x, y, dx, dy, a) = (0, 0, 1, 0, []) { |i| - a[y][x] = i; - var (nx, ny) = (x+dx, y+dy); + a[y][x] = i + var (nx, ny) = (x+dx, y+dy) ( if (dx == 1 && (nx == n || a[ny][nx]!=nil)) { [ 0, 1] } elsif (dy == 1 && (ny == n || a[ny][nx]!=nil)) { [-1, 0] } elsif (dx == -1 && (nx < 0 || a[ny][nx]!=nil)) { [ 0, -1] } elsif (dy == -1 && (ny < 0 || a[ny][nx]!=nil)) { [ 1, 0] } else { [dx, dy] } - ) » (\dx, \dy); - x = x+dx; - y = y+dy; - } * n**2; - return a; + ) » (\dx, \dy) + x = x+dx + y = y+dy + } << (1 .. n**2) + return a } - +  spiral(5).each { |row| - row.map {"%3d" % _}.join(' ').say; + row.map {"%3d" % _}.join(' ').say } diff --git a/Task/Spiral-matrix/Zkl/spiral-matrix-1.zkl b/Task/Spiral-matrix/Zkl/spiral-matrix-1.zkl new file mode 100644 index 0000000000..b253ce6a18 --- /dev/null +++ b/Task/Spiral-matrix/Zkl/spiral-matrix-1.zkl @@ -0,0 +1,9 @@ +fcn spiralMatrix(n){ + sm:=(0).pump(n,List,(0).pump(n,List,False).copy); //L(L(False,False..), L(F,F,..) ...) + drc:=Walker.cycle(T(0,1,0), T(1,0,1), T(0,-1,0), T(-1,0,1)); // deltas + len:=n; r:=0; c:=-1; z:=-1; while(len>0){ //or do(2*n-1){ + dr,dc,dl:=drc.next(); + do(len-=dl){ sm[r+=dr][c+=dc]=(z+=1); } + } + sm +} diff --git a/Task/Spiral-matrix/Zkl/spiral-matrix-2.zkl b/Task/Spiral-matrix/Zkl/spiral-matrix-2.zkl new file mode 100644 index 0000000000..8e2c84befb --- /dev/null +++ b/Task/Spiral-matrix/Zkl/spiral-matrix-2.zkl @@ -0,0 +1,4 @@ +foreach n in (T(5,-1,0,1,2)){ + spiralMatrix(n).pump(Console.println,fcn(r){ r.apply("%4d".fmt).concat() }); + println("---"); +} diff --git a/Task/Stable-marriage-problem/Phix/stable-marriage-problem.phix b/Task/Stable-marriage-problem/Phix/stable-marriage-problem.phix new file mode 100644 index 0000000000..1e8fa91324 --- /dev/null +++ b/Task/Stable-marriage-problem/Phix/stable-marriage-problem.phix @@ -0,0 +1,87 @@ +constant men = {"abe","bob","col","dan","ed","fred","gav","hal","ian","jon"} +enum abe , bob , col , dan , ed , fred , gav , hal , ian , jon +constant hen = {"abi","bea","cath","dee","eve","fay","gay","hope","ivy","jan"} +enum abi , bea , cath , dee , eve , fay , gay , hope , ivy , jan + +-- Given a complete list of ranked preferences, where the most liked is to the left: +sequence mpref = repeat(0,length(men)) + mpref[abe] = {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay} + mpref[bob] = {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay} + mpref[col] = {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan} + mpref[dan] = {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi} + mpref[ed] = {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay} + mpref[fred] = {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay} + mpref[gav] = {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay} + mpref[hal] = {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee} + mpref[ian] = {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve} + mpref[jon] = {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope} + +sequence hpref = repeat(0,length(hen)) + hpref[abi] = {bob, fred, jon, gav, ian, abe, dan, ed, col, hal} + hpref[bea] = {bob, abe, col, fred, gav, dan, ian, ed, jon, hal} + hpref[cath] = {fred, bob, ed, gav, hal, col, ian, abe, dan, jon} + hpref[dee] = {fred, jon, col, abe, ian, hal, gav, dan, bob, ed} + hpref[eve] = {jon, hal, fred, dan, abe, gav, col, ed, ian, bob} + hpref[fay] = {bob, abe, ed, ian, jon, dan, fred, gav, col, hal} + hpref[gay] = {jon, gav, hal, fred, bob, abe, col, ed, dan, ian} + hpref[hope] = {gav, jon, bob, abe, ian, dan, hal, ed, col, fred} + hpref[ivy] = {ian, col, hal, gav, fred, bob, abe, ed, jon, dan} + hpref[jan] = {ed, hal, gav, abe, bob, jon, col, ian, fred, dan} + +sequence engagements := repeat(0,length(hen)) +sequence freemen = tagset(length(men)) +printf(1,"Engagements:\n") + +-- use the Gale Shapley algorithm to find a stable set of engagements: +while length(freemen) do + integer man = freemen[1] + freemen = freemen[2..$] + integer fem, dumpee + -- each male loops through all females in order of his preference until one accepts him + for j=1 to length(mpref[man]) do + fem = mpref[man][j] + dumpee = engagements[fem] + if dumpee=0 + or find(man,hpref[fem])find(j,mpref[man]) + and find(engagements[j],hpref[j])>find(man,hpref[j]) then + if unstable=false then + printf(1,"\nThese couples are not stable.\n") + unstable = true + end if + printf(1,"%s is engaged to %s but would prefer %s and %s is engaged to %s but would prefer %s\n", + {men[man],hen[fem],hen[j],hen[j],men[engagements[j]],men[man]}) + end if + end for + end for + if not unstable then + printf(1,"\nThese couples are stable.\n") + end if +end procedure + +stable() +printf(1,"\nWhat if cath and ivy swap?\n") +engagements[cath]:=abe; engagements[ivy]:=bob +stable() diff --git a/Task/Stable-marriage-problem/Scala/stable-marriage-problem.scala b/Task/Stable-marriage-problem/Scala/stable-marriage-problem.scala index 8cb2dd66c3..4e01fdf7b7 100644 --- a/Task/Stable-marriage-problem/Scala/stable-marriage-problem.scala +++ b/Task/Stable-marriage-problem/Scala/stable-marriage-problem.scala @@ -1,121 +1,107 @@ -import java.util._ -import scala.collection.JavaConversions._ - object SMP extends App { - def run() { - Seq("abe" -> Array("abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"), - "bob" -> Array("cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"), - "col" -> Array("hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"), - "dan" -> Array("ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"), - "ed" -> Array("jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"), - "fred" -> Array("bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"), - "gav" -> Array("gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"), - "hal" -> Array("abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"), - "ian" -> Array("hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"), - "jon" -> Array("abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope")) - .foreach { e => guyPrefers.put(e._1, e._2.toList) } + private def checkMarriages(): Unit = + if (check) + println("Marriages are stable") + else + println("Marriages are unstable") - Seq("abi" -> Array("bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"), - "bea" -> Array("bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"), - "cath" -> Array("fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"), - "dee" -> Array("fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"), - "eve" -> Array("jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"), - "fay" -> Array("bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"), - "gay" -> Array("jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"), - "hope" -> Array("gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"), - "ivy" -> Array("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"), - "jan" -> Array("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan")) - .foreach { e => girlPrefers.put(e._1, e._2.toList) } + private def swap() { + val girl1 = girls.head + val girl2 = girls(1) + val tmp = girl2 -> matches(girl1) + matches += girl1 -> matches(girl2) + matches += tmp + println(girl1 + " and " + girl2 + " have switched partners") + } - val matches = matching(guys, guyPrefers, girlPrefers) - matches.foreach { e => println(s"${e._1} is engaged to ${e._2}") } - if (checkMatches(guys, girls, matches, guyPrefers, girlPrefers)) - println("Marriages are stable") - else - println("Marriages are unstable") + private type TM = scala.collection.mutable.TreeMap[String, String] - val tmp = matches(girls(0)) - matches += girls(0) -> matches(girls(1)) - matches += girls(1) -> tmp - println(girls(0) + " and " + girls(1) + " have switched partners") - if (checkMatches(guys, girls, matches, guyPrefers, girlPrefers)) - println("Marriages are stable") - else - println("Marriages are unstable") - } + private def check: Boolean = { + if (!girls.toSet.subsetOf(matches.keySet) || !guys.toSet.subsetOf(matches.values.toSet)) + return false - private def matching(guys: Iterable[String], - guyPrefers: Map[String, List[String]], - girlPrefers: Map[String, List[String]]): Map[String, String] = { - val engagements = new TreeMap[String, String] - val freeGuys = new LinkedList[String](guys) - while (!freeGuys.isEmpty) { - val guy = freeGuys.remove(0) - val guy_p = guyPrefers(guy) - var break = false - for (girl <- guy_p) - if (!break) - if (!engagements.containsKey(girl)) { - engagements += girl -> guy - break = true - } - else { - val other_guy = engagements(girl) - val girl_p = girlPrefers(girl) - if (girl_p.indexOf(guy) < girl_p.indexOf(other_guy)) { - engagements += girl -> guy - freeGuys += other_guy - break = true + val invertedMatches = new TM + matches foreach { invertedMatches += _.swap } + + for ((k, v) <- matches) { + val shePrefers = girlPrefers(k) + val sheLikesBetter = shePrefers.slice(0, shePrefers.indexOf(v)) + val hePrefers = guyPrefers(v) + val heLikesBetter = hePrefers.slice(0, hePrefers.indexOf(k)) + + for (guy <- sheLikesBetter) { + val fiance = invertedMatches(guy) + val guy_p = guyPrefers(guy) + if (guy_p.indexOf(fiance) > guy_p.indexOf(k)) { + println(s"$k likes $guy better than $v and $guy likes $k better than their current partner") + return false + } } - } + + for (girl <- heLikesBetter) { + val fiance = matches(girl) + val girl_p = girlPrefers(girl) + if (girl_p.indexOf(fiance) > girl_p.indexOf(v)) { + println(s"$v likes $girl better than $k and $girl likes $v better than their current partner") + return false + } + } + } + true } - engagements - } + private val guys = "abe" :: "bob" :: "col" :: "dan" :: "ed" :: "fred" :: "gav" :: "hal" :: "ian" :: "jon" :: Nil + private val girls = "abi" :: "bea" :: "cath" :: "dee" :: "eve" :: "fay" :: "gay" :: "hope" :: "ivy" :: "jan" :: Nil + private val guyPrefers = Map("abe" -> List("abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"), + "bob" -> List("cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"), + "col" -> List("hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"), + "dan" -> List("ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"), + "ed" -> List("jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"), + "fred" -> List("bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"), + "gav" -> List("gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"), + "hal" -> List("abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"), + "ian" -> List("hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"), + "jon" -> List("abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope")) + private val girlPrefers = Map("abi" -> List("bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"), + "bea" -> List("bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"), + "cath" -> List("fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"), + "dee" -> List("fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"), + "eve" -> List("jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"), + "fay" -> List("bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"), + "gay" -> List("jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"), + "hope" -> List("gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"), + "ivy" -> List("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"), + "jan" -> List("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan")) - private def checkMatches(guys: Iterable[String], girls: Iterable[String], - matches: Map[String, String], - guyPrefers: Map[String, List[String]], - girlPrefers: Map[String, List[String]]): Boolean = { - if (!matches.keySet.containsAll(girls) || !matches.values.containsAll(guys)) - return false - - val invertedMatches = new TreeMap[String, String] - matches.foreach { invertedMatches += _.swap } - - for ((k, v) <- matches) { - val shePrefers = girlPrefers(k) - val sheLikesBetter = new LinkedList[String] - sheLikesBetter.addAll(shePrefers.subList(0, shePrefers.indexOf(v))) - val hePrefers = guyPrefers(v) - val heLikesBetter = new LinkedList[String] - heLikesBetter.addAll(hePrefers.subList(0, hePrefers.indexOf(k))) - - for (guy <- sheLikesBetter) { - val fiance = invertedMatches(guy) - val guy_p = guyPrefers(guy) - if (guy_p.indexOf(fiance) > guy_p.indexOf(k)) { - println(s"$k likes $guy better than $v and $guy likes $k better than their current partner") - return false + private lazy val matches = { + val engagements = new TM + val freeGuys = scala.collection.mutable.Queue.empty ++ guys + while (freeGuys.nonEmpty) { + val guy = freeGuys.dequeue() + val guy_p = guyPrefers(guy) + var break = false + for (girl <- guy_p) + if (!break) + if (!engagements.contains(girl)) { + engagements(girl) = guy + break = true + } + else { + val other_guy = engagements(girl) + val girl_p = girlPrefers(girl) + if (girl_p.indexOf(guy) < girl_p.indexOf(other_guy)) { + engagements(girl) = guy + freeGuys += other_guy + break = true + } + } } - } - for (girl <- heLikesBetter) { - val fiance = matches(girl) - val girl_p = girlPrefers(girl) - if (girl_p.indexOf(fiance) > girl_p.indexOf(v)) { - println(s"$v likes $girl better than $k and $girl likes $v better than their current partner") - return false - } - } + engagements foreach { e => println(s"${e._1} is engaged to ${e._2}") } + engagements } - true - } - private val guys = "abe" :: "bob" :: "col" :: "dan" :: "ed" :: "fred" :: "gav" :: "hal" :: "ian" :: "jon" :: Nil - private val girls = "abi" :: "bea" :: "cath" :: "dee" :: "eve" :: "fay" :: "gay" :: "hope" :: "ivy" :: "jan" :: Nil - private val guyPrefers = new HashMap[String, List[String]] - private val girlPrefers = new HashMap[String, List[String]] - - run() + checkMarriages() + swap() + checkMarriages() } diff --git a/Task/Stable-marriage-problem/Zkl/stable-marriage-problem.zkl b/Task/Stable-marriage-problem/Zkl/stable-marriage-problem.zkl new file mode 100644 index 0000000000..58cbb9129a --- /dev/null +++ b/Task/Stable-marriage-problem/Zkl/stable-marriage-problem.zkl @@ -0,0 +1,62 @@ +var + Boys=Dictionary( + "abe", "abi eve cath ivy jan dee fay bea hope gay".split(), + "bob", "cath hope abi dee eve fay bea jan ivy gay".split(), + "col", "hope eve abi dee bea fay ivy gay cath jan".split(), + "dan", "ivy fay dee gay hope eve jan bea cath abi".split(), + "ed", "jan dee bea cath fay eve abi ivy hope gay".split(), + "fred","bea abi dee gay eve ivy cath jan hope fay".split(), + "gav", "gay eve ivy bea cath abi dee hope jan fay".split(), + "hal", "abi eve hope fay ivy cath jan bea gay dee".split(), + "ian", "hope cath dee gay bea abi fay ivy jan eve".split(), + "jon", "abi fay jan gay eve bea dee cath ivy hope".split(), ), + Girls=Dictionary( + "abi", "bob fred jon gav ian abe dan ed col hal".split(), + "bea", "bob abe col fred gav dan ian ed jon hal".split(), + "cath","fred bob ed gav hal col ian abe dan jon".split(), + "dee", "fred jon col abe ian hal gav dan bob ed".split(), + "eve", "jon hal fred dan abe gav col ed ian bob".split(), + "fay", "bob abe ed ian jon dan fred gav col hal".split(), + "gay", "jon gav hal fred bob abe col ed dan ian".split(), + "hope","gav jon bob abe ian dan hal ed col fred".split(), + "ivy", "ian col hal gav fred bob abe ed jon dan".split(), + "jan", "ed hal gav abe bob jon col ian fred dan".split(), ), + Couples=List(); // ( (boy,girl),(boy,girl),...) + +Boyz:=Boys.pump(Dictionary(),fcn([(b,gs)]){ return(b,gs.copy()) }); // make writable copy +while( bgs:=Boyz.filter1( 'wrap([(Boy,gs)]){ // while unattached boy + gs and (not Couples.filter1("holds",Boy)) + }) ) +{ + Boy,Girl:=bgs; Girl=Girl.pop(0); + Pair:=Couples.filter1("holds",Girl); // is Girl part of a couple? + if(not Pair) Couples.append(List(Boy,Girl)); # no, Girl was free + else{ // yes, Girl is engaged to Pair[0] + bsf,nBoy,nB:=Girls[Girl].index, bsf(Boy),bsf(Pair[0]); + if(nBoy) { + myFunc() + println("\nContinuing ... ") +} diff --git a/Task/Stack-traces/Phix/stack-traces-1.phix b/Task/Stack-traces/Phix/stack-traces-1.phix new file mode 100644 index 0000000000..d11a903352 --- /dev/null +++ b/Task/Stack-traces/Phix/stack-traces-1.phix @@ -0,0 +1,56 @@ +constant W = machine_word(), + {RTN,PREVEBP} = iff(W=4?{8,20}:{16,40}) + +procedure show_stack() +sequence symtab, symtabN +integer rtn +atom prev_ebp + + #ilASM{ + [32] + lea edi,[symtab] + call :%opGetST -- [edi]=symtab (ie our local:=the real symtab) + mov edi,[ebp+20] -- prev_ebp + mov eax,[edi+8] -- calling routine no + mov [rtn],eax + mov eax,edi + lea edi,[prev_ebp] + call :%pStoreMint + [64] + lea rdi,[symtab] + call :%opGetST -- [rdi]=symtab (ie our local:=the real symtab) + mov rdi,[rbp+40] -- prev_ebp + mov rax,[rdi+16] -- calling routine no + mov [rtn],rax + mov rax,rdi + lea rdi,[prev_ebp] + call :%pStoreMint + [] + } + while rtn!=21 do -- (T_maintls, main top level routine, always present) + symtabN = symtab[rtn] + ?symtabN[1] + prev_ebp = peekNS(prev_ebp+PREVEBP,W,0) + rtn = peekNS(prev_ebp+RTN,W,0) + end while +end procedure + +procedure three(bool die) + if die then + ?9/0 + else + show_stack() + end if +end procedure + +procedure two(bool die) + three(die) +end procedure + +procedure one(bool die) + two(die) +end procedure + +one(0) +?routine_id("dummy") -- see note below +one(1) diff --git a/Task/Stack-traces/Phix/stack-traces-2.phix b/Task/Stack-traces/Phix/stack-traces-2.phix new file mode 100644 index 0000000000..24f069cc41 --- /dev/null +++ b/Task/Stack-traces/Phix/stack-traces-2.phix @@ -0,0 +1 @@ +trace(1) diff --git a/Task/Stack-traces/REXX/stack-traces-1.rexx b/Task/Stack-traces/REXX/stack-traces-1.rexx new file mode 100644 index 0000000000..93ad81f1dc --- /dev/null +++ b/Task/Stack-traces/REXX/stack-traces-1.rexx @@ -0,0 +1,30 @@ +/* call stack */ +say 'Call A' +call A '123' +say result +exit 0 + +A: +say 'Call B' +call B '456' +say result +return ARG(1) + +B: +say 'Call C' +call C '789' +say result +return ARG(1) + +C: +call callstack +return ARG(1) + +callstack: procedure +getcallstack(cs.) +say 'Dump call stack with' cs.0 'items' +do i = 1 to cs.0 + parse var cs.i line func + say format(line, 3) ':' left(func, 9) ': source "' || sourceline(line) || '"' +end +return cs.0 diff --git a/Task/Stack-traces/REXX/stack-traces-2.rexx b/Task/Stack-traces/REXX/stack-traces-2.rexx new file mode 100644 index 0000000000..90dcde3323 --- /dev/null +++ b/Task/Stack-traces/REXX/stack-traces-2.rexx @@ -0,0 +1,4 @@ +C: +signal noname +call callstack +return ARG(1) diff --git a/Task/Stack-traces/Zkl/stack-traces.zkl b/Task/Stack-traces/Zkl/stack-traces.zkl new file mode 100644 index 0000000000..47c1eea917 --- /dev/null +++ b/Task/Stack-traces/Zkl/stack-traces.zkl @@ -0,0 +1,2 @@ +fcn f{println("F");vm.stackTrace().println()} fcn g{println("G")} +f();g(); diff --git a/Task/Stack/ALGOL-W/stack.alg b/Task/Stack/ALGOL-W/stack.alg new file mode 100644 index 0000000000..79a6ea7385 --- /dev/null +++ b/Task/Stack/ALGOL-W/stack.alg @@ -0,0 +1,51 @@ +begin + % define a Stack type that will hold StringStackElements % + % and the StringStackElement type % + % we would need separate types for other element types % + record StringStack ( reference(StringStackElement) top ); + record StringStackElement ( string(8) element + ; reference(StringStackElement) next + ); + % adds e to the end of the StringStack s % + procedure pushString ( reference(StringStack) value s + ; string(8) value e + ) ; + begin + reference(StringStackElement) newElement; + top(s) := StringStackElement( e, top(s) ) + end pushString ; + % removes and returns the top element from the StringStack s % + % asserts the Stack is not empty, which will stop the % + % program if it is % + string(8) procedure popString ( reference(StringStack) value s ) ; + begin + string(8) v; + assert( not isEmptyStringStack( s ) ); + v := element(top(s)); + top(s):= next(top(s)); + v + end popStringStack ; + % returns the top element of the StringStack s % + % asserts the Stack is not empty, which will stop the % + % program if it is % + string(8) procedure peekStringStack ( reference(StringStack) value s ) ; + begin + assert( not isEmptyStringStack( s ) ); + element(top(s)) + end popStringStack ; + % returns true if the StringStack s is empty, false otherwise % + logical procedure isEmptyStringStack ( reference(StringStack) value s ) ; top(s) = null; + + begin % test the StringStack operations % + reference(StringStack) s; + s := StringStack( null ); + pushString( s, "up" ); + pushString( s, "down" ); + pushString( s, "strange" ); + pushString( s, "charm" ); + while not isEmptyStringStack( s ) do write( popString( s ) + , if isEmptyStringStack( s ) then "(empty)" + else peekStringStack( s ) + ) + end +end. diff --git a/Task/Stack/Elena/stack.elena b/Task/Stack/Elena/stack.elena index 5cbadda7fe..e9d5bffb75 100644 --- a/Task/Stack/Elena/stack.elena +++ b/Task/Stack/Elena/stack.elena @@ -1,9 +1,9 @@ - #var stack := system'collections'Stack new. + var stack := system'collections'Stack new. stack push:2. - #var isEmpty := stack length == 0. + var isEmpty := stack length == 0. - #var item := stack peek. // Peek without Popping. + var item := stack peek. // Peek without Popping. item := stack pop. diff --git a/Task/Stack/FreeBASIC/stack-1.freebasic b/Task/Stack/FreeBASIC/stack-1.freebasic new file mode 100644 index 0000000000..5584a74862 --- /dev/null +++ b/Task/Stack/FreeBASIC/stack-1.freebasic @@ -0,0 +1,85 @@ +' FB 1.05.0 Win64 + +' stack_rosetta.bi +' simple generic Stack type + +#Define Stack(T) Stack_##T + +#Macro Declare_Stack(T) +Type Stack(T) + Public: + Declare Constructor() + Declare Destructor() + Declare Property capacity As Integer + Declare Property count As Integer + Declare Property empty As Boolean + Declare Property top As T + Declare Function pop() As T + Declare Sub push(item As T) + Private: + a(any) As T + count_ As Integer = 0 + Declare Function resize(size As Integer) As Integer +End Type + +Constructor Stack(T)() + Redim a(0 To 0) '' create a default T instance for various purposes +End Constructor + +Destructor Stack(T)() + Erase a +End Destructor + +Property Stack(T).capacity As Integer + Return UBound(a) +End Property + +Property Stack(T).count As Integer + Return count_ +End Property + +Property Stack(T).empty As Boolean + Return count_ = 0 +End Property + +Property Stack(T).top As T + If count_ > 0 Then + Return a(count_) + End If + Print "Error: Attempted to access 'top' element of an empty stack" + Return a(0) '' return default element +End Property + +Function Stack(T).pop() As T + If count_ > 0 Then + Dim value As T = a(count_) + a(count_) = a(0) '' zero element to be removed + count_ -= 1 + Return value + End If + Print "Error: Attempted to remove 'top' element of an empty stack" + Return a(0) '' return default element +End Function + +Sub Stack(T).push(item As T) + Dim size As Integer = UBound(a) + count_ += 1 + If count_ > size Then + size = resize(size) + Redim Preserve a(0 to size) + End If + a(count_) = item +End Sub + +Function Stack(T).resize(size As Integer) As Integer + If size = 0 Then + size = 4 + ElseIf size <= 32 Then + size = 2 * size + Else + size += 32 + End If + Return size +End Function + +#EndMacro diff --git a/Task/Stack/FreeBASIC/stack-2.freebasic b/Task/Stack/FreeBASIC/stack-2.freebasic new file mode 100644 index 0000000000..74ded32ce8 --- /dev/null +++ b/Task/Stack/FreeBASIC/stack-2.freebasic @@ -0,0 +1,49 @@ +' FB 1.05.0 Win64 + +#Include "stack_rosetta.bi" + +Type Dog + name As String + age As Integer + Declare Constructor + Declare Constructor(name_ As string, age_ As integer) + Declare Operator Cast() As String +end type + +Constructor Dog '' default constructor +End Constructor + +Constructor Dog(name_ As String, age_ As Integer) + name = name_ + age = age_ +End Constructor + +Operator Dog.Cast() As String + Return "[" + name + ", " + Str(age) + "]" +End Operator + +Declare_Stack(Dog) '' expand Stack type for Dog instances + +Dim dogStack As Stack(Dog) + +Var cerberus = Dog("Cerberus", 10) +Var rover = Dog("Rover", 3) +Var puppy = Dog("Puppy", 0) +With dogStack '' push these Dog instances onto the stack + .push(cerberus) + .push(rover) + .push(puppy) +End With +Print "Number of dogs on the stack :" ; dogStack.count +Print "Capacity of dog stack :" ; dogStack.capacity +Print "Top dog : "; dogStack.top +dogStack.pop() +Print "Top dog now : "; dogStack.top +Print "Number of dogs on the stack :" ; dogStack.count +dogStack.pop() +Print "Top dog now : "; dogStack.top +Print "Number of dogs on the stack :" ; dogStack.count +Print "Is stack empty now : "; dogStack.empty +Print +Print "Press any key to quit" +Sleep diff --git a/Task/Stack/Kotlin/stack.kotlin b/Task/Stack/Kotlin/stack.kotlin new file mode 100644 index 0000000000..782102ab55 --- /dev/null +++ b/Task/Stack/Kotlin/stack.kotlin @@ -0,0 +1,45 @@ +// version 1.1.2 + +class Stack { + private val data = mutableListOf() + + val size get() = data.size + + val empty get() = size == 0 + + fun push(element: E) = data.add(element) + + fun pop(): E { + if (empty) throw RuntimeException("Can't pop elements from an empty stack") + return data.removeAt(data.lastIndex) + } + + val top: E + get() { + if (empty) throw RuntimeException("Empty stack can't have a top element") + return data.last() + } + + fun clear() = data.clear() + + override fun toString() = data.toString() +} + +fun main(args: Array) { + val s = Stack() + (1..5).forEach { s.push(it) } + println(s) + println("Size of stack = ${s.size}") + print("Popping: ") + (1..3).forEach { print("${s.pop()} ") } + println("\nRemaining on stack: $s") + println("Top element is now ${s.top}") + s.clear() + println("After clearing, stack is ${if(s.empty) "empty" else "not empty"}") + try { + s.pop() + } + catch (e: Exception) { + println(e.message) + } +} diff --git a/Task/Stack/Lang5/stack.lang5 b/Task/Stack/Lang5/stack.lang5 new file mode 100644 index 0000000000..79076d7416 --- /dev/null +++ b/Task/Stack/Lang5/stack.lang5 @@ -0,0 +1,14 @@ +: cr "\n" . ; +: empty? dup execute length if 0 else -1 then swap drop ; +: pop dup execute length 1 - extract swap drop ; +: push dup execute rot append over ; +: s. stack execute . ; + +[] '_ set +: stack '_ ; +stack # local variable + 1 swap push set + 2 swap push set s. cr # [ 1 2 ] + pop . s. cr # 2 [ 1 ] + pop drop + empty? . # -1 diff --git a/Task/Stack/Nimrod/stack.nimrod b/Task/Stack/Nimrod/stack.nimrod deleted file mode 100644 index 372b4abd7d..0000000000 --- a/Task/Stack/Nimrod/stack.nimrod +++ /dev/null @@ -1,73 +0,0 @@ -import math - -type - EStackEmpty = object of E_Base - - TStack* [A] = object - data: seq[A] - count: int - -proc initStack*[A](initialSize = 32): TStack[A] = - assert isPowerOfTwo(initialSize) - result.count = 0 - newSeq(result.data,initialSize) - -proc cap*[A] (s: TStack[A]): int = - result = s.data.len - -proc len*[A](stack: TStack[A]): int = - result = stack.count - -proc push*[A](s: var TStack[A], item: A) = - if s.count == s.data.len: - # not enough room, make container bigger - var d: Seq[A] - newSeq(d,s.len * 2) - for i in 0 .. s.data.len - 1: - shallowCopy(d[i],s.data[i]) - shallowCopy(s.data,d) - s.data[s.count] = item - inc(s.count) - -proc pop*[A](s: var TStack[A]): A {.raises: [EStackEmpty].}= - if s.count == 0: - raise newException(EStackEmpty,"the stack is empty") - dec(s.count) - result = s.data[s.count] - -proc top*[A](s: TStack[A]): A = - result = s.data[s.count - 1] - -proc isEmpty*[A](s: var TStack[A]): bool = - return s.count == 0 - -#Tests -when isMainModule: - var stk: TStack[char] = initStack[char](4) - stk.push('a') - stk.push('b') - stk.push('c') - stk.push('d') - - assert(stk.count == 4) - assert(stk.data.len == 4) - stk.push('e') - assert(stk.cap == 8) - assert(stk.top == 'e') - - - discard stk.pop - discard stk.pop - discard stk.pop - discard stk.pop - assert(stk.isEmpty == false) - discard stk.pop - assert(stk.isEmpty == true) - - try: - discard stk.pop - except: - let - e = getCurrentException() - msg = getCurrentExceptionMsg() - echo "Exception: [[", repr(e), "]] msg: ", msg diff --git a/Task/Stack/OoRexx/stack.rexx b/Task/Stack/OoRexx/stack.rexx new file mode 100644 index 0000000000..9916fb8815 --- /dev/null +++ b/Task/Stack/OoRexx/stack.rexx @@ -0,0 +1,6 @@ +stack = .queue~of(123, 234) -- creates a stack with a couple of items +stack~push("Abc") -- pushing +value = stack~pull -- popping +value = stack~peek -- peeking +-- the is empty test +if stack~isEmpty then say "The stack is empty" diff --git a/Task/Stack/X86-Assembly/stack.x86 b/Task/Stack/X86-Assembly/stack.x86 new file mode 100644 index 0000000000..7812c6fefd --- /dev/null +++ b/Task/Stack/X86-Assembly/stack.x86 @@ -0,0 +1,82 @@ +; x86_64 linux nasm + +struc Stack + maxSize: resb 8 + currentSize: resb 8 + contents: +endStruc + +section .data + +soError: db "Stack Overflow Exception", 10 +seError: db "Stack Empty Error", 10 + + +section .text + +createStack: +; IN: max number of elements (rdi) +; OUT: pointer to new stack (rax) + push rdi + xor rdx, rdx + mov rbx, 8 + mul rbx + mov rcx, rax + mov rax, 12 + mov rdi, 0 + syscall + push rax + mov rdi, rax + add rdi, rcx + mov rax, 12 + syscall + pop rax + pop rbx + mov qword [rax + maxSize], rbx + mov qword [rax + currentSize], 0 + ret + + +push: +; IN: stack to operate on (stack argument), element to push (rdi) +; OUT: void + mov rax, qword [rsp + 8] + mov rbx, qword [rax + currentSize] + cmp rbx, qword [rax + maxSize] + je stackOverflow + lea rsi, [rax + contents + 8*rbx] + mov qword [rsi], rdi + add qword [rax + currentSize], 1 + ret + + +pop: +; pop +; IN: stack to operate on (stack argument) +; OUT: element from stack top + mov rax, qword [rsp + 8] + mov rbx, qword [rax + currentSize] + cmp rbx, 0 + je stackEmpty + sub rbx, 1 + lea rsi, [rax + contents + 8*rbx] + mov qword [rax + currentSize], rbx + mov rax, qword [rsi] + ret + + +; stack operation exceptions +stackOverflow: + mov rsi, soError + mov rdx, 25 + jmp errExit +stackEmpty: + mov rsi, seError + mov rdx, 18 +errExit: + mov rax, 1 + mov rdi, 1 + syscall + mov rax, 60 + mov rdi, 1 + syscall diff --git a/Task/Stack/Zkl/stack.zkl b/Task/Stack/Zkl/stack.zkl new file mode 100644 index 0000000000..c8f75411e4 --- /dev/null +++ b/Task/Stack/Zkl/stack.zkl @@ -0,0 +1,7 @@ +class Stack{ + var [const] stack=L(); + fcn push(x){stack.append(x); self} + fcn pop {stack.pop()} + fcn empty {(not stack.len())} + var [proxy] isEmpty = empty; +} diff --git a/Task/Stair-climbing-puzzle/AWK/stair-climbing-puzzle.awk b/Task/Stair-climbing-puzzle/AWK/stair-climbing-puzzle.awk new file mode 100644 index 0000000000..e64cb1bd6c --- /dev/null +++ b/Task/Stair-climbing-puzzle/AWK/stair-climbing-puzzle.awk @@ -0,0 +1,3 @@ +function step_up() { + while (!step()) { step_up() } +} diff --git a/Task/Stair-climbing-puzzle/Groovy/stair-climbing-puzzle.groovy b/Task/Stair-climbing-puzzle/Groovy/stair-climbing-puzzle.groovy new file mode 100644 index 0000000000..c276740d49 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Groovy/stair-climbing-puzzle.groovy @@ -0,0 +1,10 @@ +class Stair_climbing{ +static void main(String[] args){ +} +static def step_up(){ + while not step(){ + step_up(); + } +} + +} diff --git a/Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-1.jq b/Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-1.jq similarity index 100% rename from Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-1.jq rename to Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-1.jq diff --git a/Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-2.jq b/Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-2.jq similarity index 100% rename from Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-2.jq rename to Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-2.jq diff --git a/Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-3.jq b/Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-3.jq similarity index 100% rename from Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-3.jq rename to Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-3.jq diff --git a/Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-4.jq b/Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-4.jq similarity index 100% rename from Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-4.jq rename to Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-4.jq diff --git a/Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-5.jq b/Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-5.jq similarity index 100% rename from Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-5.jq rename to Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-5.jq diff --git a/Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-6.jq b/Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-6.jq similarity index 100% rename from Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-6.jq rename to Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-6.jq diff --git a/Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-7.jq b/Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-7.jq similarity index 100% rename from Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-7.jq rename to Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-7.jq diff --git a/Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-8.jq b/Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-8.jq similarity index 100% rename from Task/Stair-climbing-puzzle/jq/stair-climbing-puzzle-8.jq rename to Task/Stair-climbing-puzzle/Jq/stair-climbing-puzzle-8.jq diff --git a/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle-1.lua b/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle-1.lua deleted file mode 100644 index e216637294..0000000000 --- a/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle-1.lua +++ /dev/null @@ -1,3 +0,0 @@ -function step_up() - while !step() do step_up() end -end diff --git a/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle-2.lua b/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle-2.lua deleted file mode 100644 index 23ebeb7f70..0000000000 --- a/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle-2.lua +++ /dev/null @@ -1,7 +0,0 @@ --- since lua does not have ! for negation, the example above is wrong. ---Lua uses the ~ instead of the !, but in this case we have to use the not - - -function step_up() - while not step() do step_up() end -end diff --git a/Task/Stair-climbing-puzzle/Zkl/stair-climbing-puzzle-1.zkl b/Task/Stair-climbing-puzzle/Zkl/stair-climbing-puzzle-1.zkl new file mode 100644 index 0000000000..e070b96009 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Zkl/stair-climbing-puzzle-1.zkl @@ -0,0 +1,2 @@ +fcn step{ } // add code to return Bool +fcn stepUp{ while(not step()){ self.fcn() } } diff --git a/Task/Stair-climbing-puzzle/Zkl/stair-climbing-puzzle-2.zkl b/Task/Stair-climbing-puzzle/Zkl/stair-climbing-puzzle-2.zkl new file mode 100644 index 0000000000..4c0b8b5689 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Zkl/stair-climbing-puzzle-2.zkl @@ -0,0 +1,8 @@ +var position=0; +fcn step(){ //-->0|1 + r:=(0).random(2); // 0 or 1 + if(r) println("Climbed up to ",position+=1); + else println("Fell down to ", position-=1); + r +} +stepUp(); diff --git a/Task/Standard-deviation/00DESCRIPTION b/Task/Standard-deviation/00DESCRIPTION deleted file mode 100644 index 066841e733..0000000000 --- a/Task/Standard-deviation/00DESCRIPTION +++ /dev/null @@ -1,8 +0,0 @@ -Write a stateful function, class, generator or coroutine that takes a series of floating point numbers, ''one at a time'', and returns the running [[wp:Standard Deviation|standard deviation]] of the series. -The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task ''must'' state which is being used. Do not apply [[wp:Bessel's correction|Bessel's correction]]; the returned standard deviation should always be computed as if the sample seen so far is the entire population. - -Use this to compute the standard deviation of this demonstration set, \{2, 4, 4, 4, 5, 5, 7, 9\}, which is 2. - -'''See also:''' -* [[Moving Average]] -* [[Random numbers]] diff --git a/Task/Standard-deviation/00META.yaml b/Task/Standard-deviation/00META.yaml deleted file mode 100644 index 29aeacfd2a..0000000000 --- a/Task/Standard-deviation/00META.yaml +++ /dev/null @@ -1,2 +0,0 @@ ---- -note: Probability and statistics diff --git a/Task/Standard-deviation/360-Assembly/standard-deviation.360 b/Task/Standard-deviation/360-Assembly/standard-deviation.360 deleted file mode 100644 index 88237e5df7..0000000000 --- a/Task/Standard-deviation/360-Assembly/standard-deviation.360 +++ /dev/null @@ -1,102 +0,0 @@ -******** Standard deviation of a population -STDDEV CSECT - USING STDDEV,R13 -SAVEAREA B STM-SAVEAREA(R15) - DC 17F'0' - DC CL8'STDDEV' -STM STM R14,R12,12(R13) - ST R13,4(R15) - ST R15,8(R13) - LR R13,R15 - SR R8,R8 s=0 - SR R9,R9 ss=0 - SR R4,R4 i=0 - LA R6,1 - LH R7,N -LOOPI BXH R4,R6,ENDLOOPI - LR R1,R4 i - BCTR R1,0 - SLA R1,1 - LH R5,T(R1) - ST R5,WW ww=t(i) - MH R5,=H'1000' w=ww*1000 - AR R8,R5 s=s+w - LR R15,R5 - MR R14,R5 w*w - AR R9,R15 ss=ss+w*w - LR R14,R8 s - SRDA R14,32 - DR R14,R4 /i - ST R15,AVG avg=s/i - LR R14,R9 ss - SRDA R14,32 - DR R14,R4 ss/i - LR R2,R15 ss/i - LR R15,R8 s - MR R14,R8 s*s - LR R3,R15 - LR R15,R4 i - MR R14,R4 i*i - LR R1,R15 - LA R14,0 - LR R15,R3 - DR R14,R1 (s*s)/(i*i) - SR R2,R15 - LR R10,R2 std=ss/i-(s*s)/(i*i) - LR R11,R10 std - SRA R11,1 x=std/2 - LR R12,R10 px=std -LOOPWHIL EQU * - CR R12,R11 while px<>=x - BE ENDWHILE - LR R12,R11 px=x - LR R15,R10 std - LA R14,0 - DR R14,R12 /px - LR R1,R12 px - AR R1,R15 px+std/px - SRA R1,1 /2 - LR R11,R1 x=(px+std/px)/2 - B LOOPWHIL -ENDWHILE EQU * - LR R10,R11 - CVD R4,P8 i - MVC C17,MASK17 - ED C17,P8 - MVC BUF+2(1),C17+15 - L R1,WW - CVD R1,P8 - MVC C17,MASK17 - ED C17,P8 - MVC BUF+10(1),C17+15 - L R1,AVG - CVD R1,P8 - MVC C18,MASK18 - ED C18,P8 - MVC BUF+17(5),C18+12 - CVD R10,P8 std - MVC C18,MASK18 - ED C18,P8 - MVC BUF+31(5),C18+12 - WTO MF=(E,WTOMSG) - B LOOPI -ENDLOOPI EQU * - L R13,4(0,R13) - LM R14,R12,12(R13) - XR R15,R15 - BR R14 - DS 0D -N DC H'8' -T DC H'2',H'4',H'4',H'4',H'5',H'5',H'7',H'9' -WW DS F -AVG DS F -P8 DS PL8 -MASK17 DC C' ',13X'20',X'2120',C'-' -MASK18 DC C' ',10X'20',X'2120',C'.',3X'20',C'-' -C17 DS CL17 -C18 DS CL18 -WTOMSG DS 0F - DC H'80',XL2'0000' -BUF DC CL80'N=1 ITEM=1 AVG=1.234 STDDEV=1.234 ' - YREGS - END STDDEV diff --git a/Task/Standard-deviation/ALGOL-68/standard-deviation-1.alg b/Task/Standard-deviation/ALGOL-68/standard-deviation-1.alg deleted file mode 100644 index 630300ee2c..0000000000 --- a/Task/Standard-deviation/ALGOL-68/standard-deviation-1.alg +++ /dev/null @@ -1,52 +0,0 @@ -MODE VALUE = STRUCT(CHAR value), - STDDEV = STRUCT(CHAR stddev), - MEAN = STRUCT(CHAR mean), - VAR = STRUCT(CHAR var), - COUNT = STRUCT(CHAR count), - RESET = STRUCT(CHAR reset); - -MODE ACTION = UNION ( VALUE, STDDEV, MEAN, VAR, COUNT, RESET ); - -LONG REAL sum := 0; -LONG REAL sum2 := 0; -INT num := 0; - -PROC stat object = (LONG REAL v, ACTION action)LONG REAL: -( - - LONG REAL m; - - CASE action IN - (VALUE):( - num +:= 1; - sum +:= v; - sum2 +:= v*v; - stat object(0, LOC STDDEV) - ), - (STDDEV): - long sqrt(stat object(0, LOC VAR)), - (MEAN): - IF num>0 THEN sum/LONG REAL(num) ELSE 0 FI, - (VAR):( - m := stat object(0, LOC MEAN); - IF num>0 THEN sum2/LONG REAL(num)-m*m ELSE 0 FI - ), - (COUNT): - num, - (RESET): - sum := sum2 := num := 0 - ESAC -); - -[]LONG REAL v = ( 2,4,4,4,5,5,7,9 ); - -main: -( - LONG REAL sd; - - FOR i FROM LWB v TO UPB v DO - sd := stat object(v[i], LOC VALUE); - printf(($"value: "g(0,6)," standard dev := "g(0,6)l$, v[i], sd)) - OD - -) diff --git a/Task/Standard-deviation/ALGOL-68/standard-deviation-2.alg b/Task/Standard-deviation/ALGOL-68/standard-deviation-2.alg deleted file mode 100644 index d38ca7fad1..0000000000 --- a/Task/Standard-deviation/ALGOL-68/standard-deviation-2.alg +++ /dev/null @@ -1,75 +0,0 @@ -MODE STAT = STRUCT( - LONG REAL sum, - LONG REAL sum2, - INT num -); - -OP INIT = (REF STAT new)REF STAT: - (init OF class stat)(new); - -MODE CLASSSTAT = STRUCT( - PROC (REF STAT, LONG REAL #value#)VOID plusab, - PROC (REF STAT)LONG REAL stddev, mean, variance, count, - PROC (REF STAT)REF STAT init -); - -CLASSSTAT class stat; - -plusab OF class stat := (REF STAT self, LONG REAL value)VOID:( - num OF self +:= 1; - sum OF self +:= value; - sum2 OF self +:= value*value - ); - -OP +:= = (REF STAT lhs, LONG REAL rhs)VOID: # some syntatic sugar # - (plusab OF class stat)(lhs, rhs); - -stddev OF class stat := (REF STAT self)LONG REAL: - long sqrt((variance OF class stat)(self)); - -OP STDDEV = ([]LONG REAL value)LONG REAL: ( # more syntatic sugar # - REF STAT stat = INIT LOC STAT; - FOR i FROM LWB value TO UPB value DO - stat +:= value[i] - OD; - (stddev OF class stat)(stat) -); - -mean OF class stat := (REF STAT self)LONG REAL: - sum OF self/LONG REAL(num OF self); - -variance OF class stat := (REF STAT self)LONG REAL:( - LONG REAL m = (mean OF class stat)(self); - sum2 OF self/LONG REAL(num OF self)-m*m - ); - -count OF class stat := (REF STAT self)LONG REAL: - num OF self; - -init OF class stat := (REF STAT self)REF STAT:( - sum OF self := sum2 OF self := num OF self := 0; - self - ); - -[]LONG REAL value = ( 2,4,4,4,5,5,7,9 ); - -main: -( -# printf(($"standard deviation operator = "g(0,6)l$, STDDEV value)); -# - - REF STAT stat = INIT LOC STAT; - - FOR i FROM LWB value TO UPB value DO - stat +:= value[i]; - printf(($"value: "g(0,6)," standard dev := "g(0,6)l$, value[i], (stddev OF class stat)(stat))) - OD -# -; - printf(($"standard deviation = "g(0,6)l$, (stddev OF class stat)(stat))); - printf(($"mean = "g(0,6)l$, (mean OF class stat)(stat))); - printf(($"variance = "g(0,6)l$, (variance OF class stat)(stat))); - printf(($"count = "g(0,6)l$, (count OF class stat)(stat))) -# - -) diff --git a/Task/Standard-deviation/ALGOL-68/standard-deviation-3.alg b/Task/Standard-deviation/ALGOL-68/standard-deviation-3.alg deleted file mode 100644 index d66a54776d..0000000000 --- a/Task/Standard-deviation/ALGOL-68/standard-deviation-3.alg +++ /dev/null @@ -1,16 +0,0 @@ -LONG REAL sum, sum2; -INT n; - -PROC sd = (LONG REAL x)LONG REAL:( - sum +:= x; - sum2 +:= x*x; - n +:= 1; - IF n = 0 THEN 0 ELSE long sqrt(sum2/n - sum*sum/n/n) FI -); - -sum := sum2 := n := 0; -[]LONG REAL values = (2,4,4,4,5,5,7,9); -FOR i TO UPB values DO - LONG REAL value = values[i]; - printf(($2(xg(0,6))l$, value, sd(value))) -OD diff --git a/Task/Standard-deviation/ALGOL-W/standard-deviation.alg b/Task/Standard-deviation/ALGOL-W/standard-deviation.alg deleted file mode 100644 index 09be0596dc..0000000000 --- a/Task/Standard-deviation/ALGOL-W/standard-deviation.alg +++ /dev/null @@ -1,25 +0,0 @@ -begin - - long real sum, sum2; - integer n; - - long real procedure sd (long real value x) ; - begin - sum := sum + x; - sum2 := sum2 + (x*x); - n := n + 1; - if n = 0 then 0 else longsqrt(sum2/n - sum*sum/n/n) - end sd; - - sum := sum2 := n := 0; - - r_format := "A"; r_w := 14; r_d := 6; % set output to fixed point format % - - for i := 2,4,4,4,5,5,7,9 - do begin - long real val; - val := i; - write(val, sd(val)) - end for_i - -end. diff --git a/Task/Standard-deviation/AWK/standard-deviation.awk b/Task/Standard-deviation/AWK/standard-deviation.awk deleted file mode 100644 index ea97a872d3..0000000000 --- a/Task/Standard-deviation/AWK/standard-deviation.awk +++ /dev/null @@ -1,19 +0,0 @@ -# syntax: GAWK -f STANDARD_DEVIATION.AWK -BEGIN { - n = split("2,4,4,4,5,5,7,9",arr,",") - for (i=1; i<=n; i++) { - temp[i] = arr[i] - printf("%g %g\n",arr[i],stdev(temp)) - } - exit(0) -} -function stdev(arr, i,n,s1,s2,variance,x) { - for (i in arr) { - n++ - x = arr[i] - s1 += x ^ 2 - s2 += x - } - variance = ((n * s1) - (s2 ^ 2)) / (n ^ 2) - return(sqrt(variance)) -} diff --git a/Task/Standard-deviation/Ada/standard-deviation.ada b/Task/Standard-deviation/Ada/standard-deviation.ada deleted file mode 100644 index b6b91eb78e..0000000000 --- a/Task/Standard-deviation/Ada/standard-deviation.ada +++ /dev/null @@ -1,35 +0,0 @@ -with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; -with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Float_Text_IO; use Ada.Float_Text_IO; -with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; - -procedure Test_Deviation is - type Sample is record - N : Natural := 0; - Sum : Float := 0.0; - SumOfSquares : Float := 0.0; - end record; - procedure Add (Data : in out Sample; Point : Float) is - begin - Data.N := Data.N + 1; - Data.Sum := Data.Sum + Point; - Data.SumOfSquares := Data.SumOfSquares + Point ** 2; - end Add; - function Deviation (Data : Sample) return Float is - begin - return Sqrt (Data.SumOfSquares / Float (Data.N) - (Data.Sum / Float (Data.N)) ** 2); - end Deviation; - - Data : Sample; - Test : array (1..8) of Integer := (2, 4, 4, 4, 5, 5, 7, 9); -begin - for Index in Test'Range loop - Add (Data, Float(Test(Index))); - Put("N="); Put(Item => Index, Width => 1); - Put(" ITEM="); Put(Item => Test(Index), Width => 1); - Put(" AVG="); Put(Item => Float(Data.Sum)/Float(Index), Fore => 1, Aft => 3, Exp => 0); - Put(" STDDEV="); Put(Item => Deviation (Data), Fore => 1, Aft => 3, Exp => 0); - New_line; - end loop; -end Test_Deviation; diff --git a/Task/Standard-deviation/AutoHotkey/standard-deviation.ahk b/Task/Standard-deviation/AutoHotkey/standard-deviation.ahk deleted file mode 100644 index 624d017b53..0000000000 --- a/Task/Standard-deviation/AutoHotkey/standard-deviation.ahk +++ /dev/null @@ -1,11 +0,0 @@ -std(2),std(4),std(4),std(4),std(5),std(5),std(7) -MsgBox % std(9) ; 2 - -std(x="") { - Static sum:=0, sqr:=0, n:=0 - If (x="") ; blank parameter: reset - sum := 0, sqr := 0, n := 0 - Else - sum += x, sqr += x*x, n++ ; update state - Return sqrt((sqr-sum*sum/n)/n) -} diff --git a/Task/Standard-deviation/Axiom/standard-deviation-1.axiom b/Task/Standard-deviation/Axiom/standard-deviation-1.axiom deleted file mode 100644 index f14ef43ecf..0000000000 --- a/Task/Standard-deviation/Axiom/standard-deviation-1.axiom +++ /dev/null @@ -1,17 +0,0 @@ -)abbrev package TESTD TestDomain -TestDomain(T : Join(Field,RadicalCategory)): Exports == Implementation where - R ==> Record(n : Integer, sum : T, ssq : T) - Exports == AbelianMonoid with - _+ : (%,T) -> % - _+ : (T,%) -> % - sd : % -> T - Implementation == R add - Rep := R -- similar representation and implementation - obj : % - 0 == [0,0,0] - obj + (obj2:%) == [obj.n + obj2.n, obj.sum + obj2.sum, obj.ssq + obj2.ssq] - obj + (x:T) == obj + [1, x, x*x] - (x:T) + obj == obj + x - sd obj == - mean : T := obj.sum / (obj.n::T) - sqrt(obj.ssq / (obj.n::T) - mean*mean) diff --git a/Task/Standard-deviation/Axiom/standard-deviation-2.axiom b/Task/Standard-deviation/Axiom/standard-deviation-2.axiom deleted file mode 100644 index 67f0b31752..0000000000 --- a/Task/Standard-deviation/Axiom/standard-deviation-2.axiom +++ /dev/null @@ -1,14 +0,0 @@ -T ==> Expression Integer -D ==> TestDomain(T) -items := [2,4,4,4,5,5,7,9+x] :: List T; -map(sd, scan(+, items, 0$D)) - +---------------+ - +-+ +-+ +-+ +-+ | 2 - 2\|2 \|3 2\|6 4\|6 \|7x + 64x + 256 - (1) [0,1,-----,----,-----,1,-----,------------------] - 3 2 5 7 8 - Type: List(Expression(Integer)) -eval subst(last %,x=0) - - (2) 2 - Type: Expression(Integer) diff --git a/Task/Standard-deviation/BBC-BASIC/standard-deviation.bbc b/Task/Standard-deviation/BBC-BASIC/standard-deviation.bbc deleted file mode 100644 index 8d5beb1a04..0000000000 --- a/Task/Standard-deviation/BBC-BASIC/standard-deviation.bbc +++ /dev/null @@ -1,15 +0,0 @@ - MAXITEMS = 100 - FOR i% = 1 TO 8 - READ n - PRINT "Value = "; n ", running SD = " FNrunningsd(n) - NEXT - END - - DATA 2,4,4,4,5,5,7,9 - - DEF FNrunningsd(n) - PRIVATE list(), i% - DIM list(MAXITEMS) - i% += 1 - list(i%) = n - = SQR(MOD(list())^2/i% - (SUM(list())/i%)^2) diff --git a/Task/Standard-deviation/C++/standard-deviation.cpp b/Task/Standard-deviation/C++/standard-deviation.cpp deleted file mode 100644 index d66a4e51cd..0000000000 --- a/Task/Standard-deviation/C++/standard-deviation.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include -#include -#include -#include - -template struct MomentsAccumulator_ -{ - std::vector m_; - MomentsAccumulator_() : m_(N + 1, 0.0) {} - void operator()(double v) - { - double inc = 1.0; - for (auto& mi : m_) - { - mi += inc; - inc *= v; - } - } -}; - -double Stdev(const std::vector& moments) -{ - assert(moments.size() > 2); - assert(moments[0] > 0.0); - const double mean = moments[1] / moments[0]; - const double meanSquare = moments[2] / moments[0]; - return sqrt(meanSquare - mean * mean); -} - -int main(void) -{ - std::vector data({ 2, 4, 4, 4, 5, 5, 7, 9 }); - MomentsAccumulator_<2> accum; - for (auto d : data) - { - accum(d); - std::cout << "Running stdev: " << Stdev(accum.m_) << "\n"; - } -} diff --git a/Task/Standard-deviation/C/standard-deviation-1.c b/Task/Standard-deviation/C/standard-deviation-1.c deleted file mode 100644 index 154a05b54a..0000000000 --- a/Task/Standard-deviation/C/standard-deviation-1.c +++ /dev/null @@ -1,48 +0,0 @@ -#include -#include -#include - -typedef enum Action { STDDEV, MEAN, VAR, COUNT } Action; - -typedef struct stat_obj_struct { - double sum, sum2; - size_t num; - Action action; -} sStatObject, *StatObject; - -StatObject NewStatObject( Action action ) -{ - StatObject so; - - so = malloc(sizeof(sStatObject)); - so->sum = 0.0; - so->sum2 = 0.0; - so->num = 0; - so->action = action; - return so; -} -#define FREE_STAT_OBJECT(so) \ - free(so); so = NULL -double stat_obj_value(StatObject so, Action action) -{ - double num, mean, var, stddev; - - if (so->num == 0.0) return 0.0; - num = so->num; - if (action==COUNT) return num; - mean = so->sum/num; - if (action==MEAN) return mean; - var = so->sum2/num - mean*mean; - if (action==VAR) return var; - stddev = sqrt(var); - if (action==STDDEV) return stddev; - return 0; -} - -double stat_object_add(StatObject so, double v) -{ - so->num++; - so->sum += v; - so->sum2 += v*v; - return stat_obj_value(so, so->action); -} diff --git a/Task/Standard-deviation/C/standard-deviation-2.c b/Task/Standard-deviation/C/standard-deviation-2.c deleted file mode 100644 index 54f1a96935..0000000000 --- a/Task/Standard-deviation/C/standard-deviation-2.c +++ /dev/null @@ -1,13 +0,0 @@ -double v[] = { 2,4,4,4,5,5,7,9 }; - -int main() -{ - int i; - StatObject so = NewStatObject( STDDEV ); - - for(i=0; i < sizeof(v)/sizeof(double) ; i++) - printf("val: %lf std dev: %lf\n", v[i], stat_object_add(so, v[i])); - - FREE_STAT_OBJECT(so); - return 0; -} diff --git a/Task/Standard-deviation/COBOL/standard-deviation-1.cobol b/Task/Standard-deviation/COBOL/standard-deviation-1.cobol deleted file mode 100644 index 88dbe30c94..0000000000 --- a/Task/Standard-deviation/COBOL/standard-deviation-1.cobol +++ /dev/null @@ -1,71 +0,0 @@ -IDENTIFICATION DIVISION. -PROGRAM-ID. run-stddev. -environment division. -input-output section. -file-control. - select input-file assign to "input.txt" - organization is line sequential. -data division. -file section. -fd input-file. - 01 inp-record. - 03 inp-fld pic 9(03). -working-storage section. -01 filler pic 9(01) value 0. - 88 no-more-input value 1. -01 ws-tb-data. - 03 ws-tb-size pic 9(03). - 03 ws-tb-table. - 05 ws-tb-fld pic s9(05)v9999 comp-3 occurs 0 to 100 times - depending on ws-tb-size. -01 ws-stddev pic s9(05)v9999 comp-3. -PROCEDURE DIVISION. - move 0 to ws-tb-size - open input input-file - read input-file - at end - set no-more-input to true - end-read - perform - test after - until no-more-input - add 1 to ws-tb-size - move inp-fld to ws-tb-fld (ws-tb-size) - call 'stddev' using by reference ws-tb-data - ws-stddev - display 'inp=' inp-fld ' stddev=' ws-stddev - read input-file at end set no-more-input to true end-read - end-perform - close input-file - stop run. -end program run-stddev. -IDENTIFICATION DIVISION. -PROGRAM-ID. stddev. -data division. -working-storage section. -01 ws-tbx pic s9(03) comp. -01 ws-tb-work. - 03 ws-sum pic s9(05)v9999 comp-3 value +0. - 03 ws-sumsq pic s9(05)v9999 comp-3 value +0. - 03 ws-avg pic s9(05)v9999 comp-3 value +0. -linkage section. -01 ws-tb-data. - 03 ws-tb-size pic 9(03). - 03 ws-tb-table. - 05 ws-tb-fld pic s9(05)v9999 comp-3 occurs 0 to 100 times - depending on ws-tb-size. -01 ws-stddev pic s9(05)v9999 comp-3. -PROCEDURE DIVISION using ws-tb-data ws-stddev. - compute ws-sum = 0 - perform test before varying ws-tbx from 1 by +1 until ws-tbx > ws-tb-size - compute ws-sum = ws-sum + ws-tb-fld (ws-tbx) - end-perform - compute ws-avg rounded = ws-sum / ws-tb-size - compute ws-sumsq = 0 - perform test before varying ws-tbx from 1 by +1 until ws-tbx > ws-tb-size - compute ws-sumsq = ws-sumsq - + (ws-tb-fld (ws-tbx) - ws-avg) ** 2.0 - end-perform - compute ws-stddev = ( ws-sumsq / ws-tb-size) ** 0.5 - goback. -end program stddev. diff --git a/Task/Standard-deviation/COBOL/standard-deviation-2.cobol b/Task/Standard-deviation/COBOL/standard-deviation-2.cobol deleted file mode 100644 index b52f8d5aaf..0000000000 --- a/Task/Standard-deviation/COBOL/standard-deviation-2.cobol +++ /dev/null @@ -1,9 +0,0 @@ -sample output: -inp=002 stddev=+00000.0000 -inp=004 stddev=+00001.0000 -inp=004 stddev=+00000.9427 -inp=004 stddev=+00000.8660 -inp=005 stddev=+00000.9797 -inp=005 stddev=+00001.0000 -inp=007 stddev=+00001.3996 -inp=009 stddev=+00002.0000 diff --git a/Task/Standard-deviation/COBOL/standard-deviation-3.cobol b/Task/Standard-deviation/COBOL/standard-deviation-3.cobol deleted file mode 100644 index bfe81fa569..0000000000 --- a/Task/Standard-deviation/COBOL/standard-deviation-3.cobol +++ /dev/null @@ -1,55 +0,0 @@ - >>SOURCE FREE -IDENTIFICATION DIVISION. -PROGRAM-ID. std-dev. - -ENVIRONMENT DIVISION. -CONFIGURATION SECTION. -REPOSITORY. - FUNCTION sum-arr - . -DATA DIVISION. -WORKING-STORAGE SECTION. -78 Arr-Len VALUE 8. -01 arr-area VALUE "0204040405050709". - 03 arr PIC 99 OCCURS Arr-Len TIMES. - -01 i PIC 99. - -01 avg PIC 9(3)V99. - -01 std-dev PIC 9(3)V99. - -PROCEDURE DIVISION. - DIVIDE FUNCTION sum-arr(arr-area) BY Arr-Len GIVING avg ROUNDED - - PERFORM VARYING i FROM 1 BY 1 UNTIL i > Arr-Len - COMPUTE arr (i) = (arr (i) - avg) ** 2 - END-PERFORM - - COMPUTE std-dev = FUNCTION SQRT(FUNCTION sum-arr(arr-area) / Arr-Len) - DISPLAY std-dev - . -END PROGRAM std-dev. - - -IDENTIFICATION DIVISION. -FUNCTION-ID. sum-arr. - -DATA DIVISION. -LOCAL-STORAGE SECTION. -01 i PIC 99. - -LINKAGE SECTION. -78 Arr-Len VALUE 8. -01 arr-area. - 03 arr PIC 99 OCCURS Arr-Len TIMES. - -01 arr-sum PIC 99. - -PROCEDURE DIVISION USING arr-area RETURNING arr-sum. - INITIALIZE arr-sum *> Without this, arr-sum is initialised incorrectly. - PERFORM VARYING i FROM 1 BY 1 UNTIL i > Arr-Len - ADD arr (i) TO arr-sum - END-PERFORM - . -END FUNCTION sum-arr. diff --git a/Task/Standard-deviation/Clojure/standard-deviation.clj b/Task/Standard-deviation/Clojure/standard-deviation.clj deleted file mode 100644 index 23463059b5..0000000000 --- a/Task/Standard-deviation/Clojure/standard-deviation.clj +++ /dev/null @@ -1,9 +0,0 @@ -(defn stateful-std-deviation[x] - (letfn [(std-dev[x] - (let [v (deref (find-var (symbol (str *ns* "/v"))))] - (swap! v conj x) - (let [m (/ (reduce + @v) (count @v))] - (Math/sqrt (/ (reduce + (map #(* (- m %) (- m %)) @v)) (count @v))))))] - (when (nil? (resolve 'v)) - (intern *ns* 'v (atom []))) - (std-dev x))) diff --git a/Task/Standard-deviation/CoffeeScript/standard-deviation.coffee b/Task/Standard-deviation/CoffeeScript/standard-deviation.coffee deleted file mode 100644 index 7bbdf453a8..0000000000 --- a/Task/Standard-deviation/CoffeeScript/standard-deviation.coffee +++ /dev/null @@ -1,27 +0,0 @@ -class StandardDeviation - constructor: -> - @sum = 0 - @sumOfSquares = 0 - @values = 0 - @deviation = 0 - - include: ( n ) -> - @values += 1 - @sum += n - @sumOfSquares += n * n - mean = @sum / @values - mean *= mean - @deviation = Math.sqrt @sumOfSquares / @values - mean - -dev = new StandardDeviation -values = [ 2, 4, 4, 4, 5, 5, 7, 9 ] -tmp = [] - -for value in values - tmp.push value - dev.include value - console.log """ - Values: #{ tmp } - Standard deviation: #{ dev.deviation } - - """ diff --git a/Task/Standard-deviation/Common-Lisp/standard-deviation-1.lisp b/Task/Standard-deviation/Common-Lisp/standard-deviation-1.lisp deleted file mode 100644 index a94734f8b8..0000000000 --- a/Task/Standard-deviation/Common-Lisp/standard-deviation-1.lisp +++ /dev/null @@ -1,17 +0,0 @@ -(defun running-stddev () - (let ((sum 0) (sq 0) (n 0)) - (lambda (x) - (incf sum x) (incf sq (* x x)) (incf n) - (/ (sqrt (- (* n sq) (* sum sum))) n)))) - -CL-USER> (loop with f = (running-stddev) for i in '(2 4 4 4 5 5 7 9) do - (format t "~a ~a~%" i (funcall f i))) -NIL -2 0.0 -4 1.0 -4 0.94280905 -4 0.8660254 -5 0.97979593 -5 1.0 -7 1.3997085 -9 2.0 diff --git a/Task/Standard-deviation/Common-Lisp/standard-deviation-2.lisp b/Task/Standard-deviation/Common-Lisp/standard-deviation-2.lisp deleted file mode 100644 index 918d5931c6..0000000000 --- a/Task/Standard-deviation/Common-Lisp/standard-deviation-2.lisp +++ /dev/null @@ -1,18 +0,0 @@ -CL-USER> (setf fn (running-stddev)) -# -CL-USER> (funcall fn 2) -0.0 -CL-USER> (funcall fn 4) -1.0 -CL-USER> (funcall fn 4) -0.94280905 -CL-USER> (funcall fn 4) -0.8660254 -CL-USER> (funcall fn 5) -0.97979593 -CL-USER> (funcall fn 5) -1.0 -CL-USER> (funcall fn 7) -1.3997085 -CL-USER> (funcall fn 9) -2.0 diff --git a/Task/Standard-deviation/Common-Lisp/standard-deviation-3.lisp b/Task/Standard-deviation/Common-Lisp/standard-deviation-3.lisp deleted file mode 100644 index a0d5837503..0000000000 --- a/Task/Standard-deviation/Common-Lisp/standard-deviation-3.lisp +++ /dev/null @@ -1,11 +0,0 @@ -CL-USER> (loop with deviator = (make-deviator) - for i in '(2 4 4 4 5 5 7 9) - collect (list i (funcall deviator i))) ==> -((2 0.0d0) - (4 1.0d0) - (4 0.9428090415820634d0) - (4 0.8660254037844386d0) - (5 0.9797958971132713d0) - (5 1.0d0) - (7 1.3997084244475304d0) - (9 2.0d0)) diff --git a/Task/Standard-deviation/Common-Lisp/standard-deviation-4.lisp b/Task/Standard-deviation/Common-Lisp/standard-deviation-4.lisp deleted file mode 100644 index 760c32cfef..0000000000 --- a/Task/Standard-deviation/Common-Lisp/standard-deviation-4.lisp +++ /dev/null @@ -1,8 +0,0 @@ -(defun running-stddev () - (let ((sum 0) (sq 0) (n 0)) - (lambda (x) - (incf sum x) (incf sq (* x x)) (incf n) - (/ (sqrt (- (* n sq) (* sum sum))) n)))) - -(loop with f = (running-stddev) for i in '(2 4 4 4 5 5 7 9) do - (format t "~a ~a~%" i (funcall f i))) diff --git a/Task/Standard-deviation/Component-Pascal/standard-deviation.component b/Task/Standard-deviation/Component-Pascal/standard-deviation.component deleted file mode 100644 index 03b7783f18..0000000000 --- a/Task/Standard-deviation/Component-Pascal/standard-deviation.component +++ /dev/null @@ -1,43 +0,0 @@ -MODULE StandardDeviation; -IMPORT StdLog, Args,Strings,Math; - -PROCEDURE Mean(x: ARRAY OF REAL; n: INTEGER; OUT mean: REAL); -VAR - i: INTEGER; - total: REAL; -BEGIN - total := 0.0; - FOR i := 0 TO n - 1 DO total := total + x[i] END; - mean := total /n -END Mean; - -PROCEDURE SDeviation(x : ARRAY OF REAL;n: INTEGER): REAL; -VAR - i: INTEGER; - mean,sum: REAL; -BEGIN - Mean(x,n,mean); - sum := 0.0; - FOR i := 0 TO n - 1 DO - sum:= sum + ((x[i] - mean) * (x[i] - mean)); - END; - RETURN Math.Sqrt(sum/n); -END SDeviation; - -PROCEDURE Do*; -VAR - p: Args.Params; - x: POINTER TO ARRAY OF REAL; - i,done: INTEGER; -BEGIN - Args.Get(p); - IF p.argc > 0 THEN - NEW(x,p.argc); - FOR i := 0 TO p.argc - 1 DO x[i] := 0.0 END; - FOR i := 0 TO p.argc - 1 DO - Strings.StringToReal(p.args[i],x[i],done); - StdLog.Int(i + 1);StdLog.String(" :> ");StdLog.Real(SDeviation(x,i + 1));StdLog.Ln - END - END -END Do; -END StandardDeviation. diff --git a/Task/Standard-deviation/D/standard-deviation.d b/Task/Standard-deviation/D/standard-deviation.d deleted file mode 100644 index 8b8caf294b..0000000000 --- a/Task/Standard-deviation/D/standard-deviation.d +++ /dev/null @@ -1,28 +0,0 @@ -import std.stdio, std.math; - -struct StdDev { - real sum = 0.0, sqSum = 0.0; - long nvalues; - - void addNumber(in real input) pure nothrow { - nvalues++; - sum += input; - sqSum += input ^^ 2; - } - - real getStdDev() const pure nothrow { - if (nvalues == 0) - return 0.0; - immutable real mean = sum / nvalues; - return sqrt(sqSum / nvalues - mean ^^ 2); - } -} - -void main() { - StdDev stdev; - - foreach (el; [2.0, 4, 4, 4, 5, 5, 7, 9]) { - stdev.addNumber(el); - writefln("%e", stdev.getStdDev()); - } -} diff --git a/Task/Standard-deviation/Delphi/standard-deviation.delphi b/Task/Standard-deviation/Delphi/standard-deviation.delphi deleted file mode 100644 index 43112d63ca..0000000000 --- a/Task/Standard-deviation/Delphi/standard-deviation.delphi +++ /dev/null @@ -1,11 +0,0 @@ -program StdDevTest; - -{$APPTYPE CONSOLE} - -uses - Math; - -begin - Writeln(PopnStdDev([2,4,4,4,5,5,7,9])); - Readln; -end. diff --git a/Task/Standard-deviation/E/standard-deviation-1.e b/Task/Standard-deviation/E/standard-deviation-1.e deleted file mode 100644 index 4061991bf4..0000000000 --- a/Task/Standard-deviation/E/standard-deviation-1.e +++ /dev/null @@ -1,24 +0,0 @@ -def makeRunningStdDev() { - var sum := 0.0 - var sumSquares := 0.0 - var count := 0.0 - - def insert(v) { - sum += v - sumSquares += v ** 2 - count += 1 - } - - /** Returns the standard deviation of the inputs so far, or null if there - have been no inputs. */ - def stddev() { - if (count > 0) { - def meanSquares := sumSquares/count - def mean := sum/count - def variance := meanSquares - mean**2 - return variance.sqrt() - } - } - - return [insert, stddev] -} diff --git a/Task/Standard-deviation/E/standard-deviation-2.e b/Task/Standard-deviation/E/standard-deviation-2.e deleted file mode 100644 index 722430b6b2..0000000000 --- a/Task/Standard-deviation/E/standard-deviation-2.e +++ /dev/null @@ -1,18 +0,0 @@ -? def [insert, stddev] := makeRunningStdDev() -# value: , - -? [stddev()] -# value: [null] - -? for value in [2,4,4,4,5,5,7,9] { -> insert(value) -> println(stddev()) -> } -0.0 -1.0 -0.9428090415820626 -0.8660254037844386 -0.9797958971132716 -1.0 -1.3997084244475297 -2.0 diff --git a/Task/Standard-deviation/Emacs-Lisp/standard-deviation-1.l b/Task/Standard-deviation/Emacs-Lisp/standard-deviation-1.l deleted file mode 100644 index 262ab6af4f..0000000000 --- a/Task/Standard-deviation/Emacs-Lisp/standard-deviation-1.l +++ /dev/null @@ -1,19 +0,0 @@ -(defun running-std (x) - ; ensure that we have a float to avoid potential integer math errors. - (setq x (float x)) - ; define variables to use - (defvar running-sum 0 "the running sum of all known values") - (defvar running-len 0 "the running number of all known values") - (defvar running-squared-sum 0 "the running squared sum of all known values") - ; and make them local to this buffer - (make-local-variable 'running-sum) - (make-local-variable 'running-len) - (make-local-variable 'running-squared-sum) - ; now process the new value - (setq running-sum (+ running-sum x)) - (setq running-len (1+ running-len)) - (setq running-squared-sum (+ running-squared-sum (* x x))) - ; and calculate the new standard deviation - (sqrt (- (/ running-squared-sum - running-len) (/ (* running-sum running-sum) - (* running-len running-len ))))) diff --git a/Task/Standard-deviation/Emacs-Lisp/standard-deviation-2.l b/Task/Standard-deviation/Emacs-Lisp/standard-deviation-2.l deleted file mode 100644 index 3c3827172b..0000000000 --- a/Task/Standard-deviation/Emacs-Lisp/standard-deviation-2.l +++ /dev/null @@ -1,14 +0,0 @@ -(with-temp-buffer - (loop for i in '(2 4 4 4 5 5 7 9) do - (insert (number-to-string (running-std i))) - (newline)) - (message (buffer-substring (point-min) (1- (point-max))))) - -"0.0 -1.0 -0.9428090415820636 -0.8660254037844386 -0.9797958971132716 -1.0 -1.399708424447531 -2.0" diff --git a/Task/Standard-deviation/Emacs-Lisp/standard-deviation-3.l b/Task/Standard-deviation/Emacs-Lisp/standard-deviation-3.l deleted file mode 100644 index 2e9bff1108..0000000000 --- a/Task/Standard-deviation/Emacs-Lisp/standard-deviation-3.l +++ /dev/null @@ -1,2 +0,0 @@ -(setq x '[2 4 4 4 5 5 7 9]) -(string-to-number (calc-eval (format "sqrt(vpvar(%s))" x))) diff --git a/Task/Standard-deviation/Erlang/standard-deviation.erl b/Task/Standard-deviation/Erlang/standard-deviation.erl deleted file mode 100644 index ebc60aa085..0000000000 --- a/Task/Standard-deviation/Erlang/standard-deviation.erl +++ /dev/null @@ -1,41 +0,0 @@ --module( standard_deviation ). - --export( [add_sample/2, create/0, destroy/1, get/1, task/0] ). - --compile({no_auto_import,[get/1]}). - -add_sample( Pid, N ) -> Pid ! {add, N}. - -create() -> erlang:spawn_link( fun() -> loop( [] ) end ). - -destroy( Pid ) -> Pid ! stop. - -get( Pid ) -> - Pid ! {get, erlang:self()}, - receive - {get, Value, Pid} -> Value - end. - -task() -> - Pid = create(), - [add_print(Pid, X, add_sample(Pid, X)) || X <- [2,4,4,4,5,5,7,9]], - destroy( Pid ). - - - -add_print( Pid, N, _Add ) -> io:fwrite( "Standard deviation ~p when adding ~p~n", [get(Pid), N] ). - -loop( Ns ) -> - receive - {add, N} -> loop( [N | Ns] ); - {get, Pid} -> - Pid ! {get, loop_calculate( Ns ), erlang:self()}, - loop( Ns ); - stop -> ok - end. - -loop_calculate( Ns ) -> - Average = loop_calculate_average( Ns ), - math:sqrt( loop_calculate_average([math:pow(X - Average, 2) || X <- Ns]) ). - -loop_calculate_average( Ns ) -> lists:sum( Ns ) / erlang:length( Ns ). diff --git a/Task/Standard-deviation/Factor/standard-deviation.factor b/Task/Standard-deviation/Factor/standard-deviation.factor deleted file mode 100644 index 54bf02a6e8..0000000000 --- a/Task/Standard-deviation/Factor/standard-deviation.factor +++ /dev/null @@ -1,22 +0,0 @@ -USING: accessors io kernel math math.functions math.parser -sequences ; -IN: standard-deviator - -TUPLE: standard-deviator sum sum^2 n ; - -: ( -- standard-deviator ) - 0.0 0.0 0 standard-deviator boa ; - -: current-std ( standard-deviator -- std ) - [ [ sum^2>> ] [ n>> ] bi / ] - [ [ sum>> ] [ n>> ] bi / sq ] bi - sqrt ; - -: add-value ( value standard-deviator -- ) - [ nip [ 1 + ] change-n drop ] - [ [ + ] change-sum drop ] - [ [ [ sq ] dip + ] change-sum^2 drop ] 2tri ; - -: main ( -- ) - { 2 4 4 4 5 5 7 9 } - [ [ add-value ] curry each ] keep - current-std number>string print ; diff --git a/Task/Standard-deviation/Forth/standard-deviation-1.fth b/Task/Standard-deviation/Forth/standard-deviation-1.fth deleted file mode 100644 index 9cf9aa2954..0000000000 --- a/Task/Standard-deviation/Forth/standard-deviation-1.fth +++ /dev/null @@ -1,23 +0,0 @@ -: f+! ( x addr -- ) dup f@ f+ f! ; - -: st-count ( stats -- n ) f@ ; -: st-sum ( stats -- sum ) float+ f@ ; -: st-sumsq ( stats -- sum*sum ) 2 floats + f@ ; - -: st-mean ( stats -- mean ) - dup st-sum st-count f/ ; - -: st-variance ( stats -- var ) - dup st-sumsq - dup st-mean fdup f* dup st-count f* f- - st-count f/ ; - -: st-stddev ( stats -- stddev ) - st-variance fsqrt ; - -: st-add ( fnum stats -- ) - dup - 1e dup f+! float+ - fdup dup f+! float+ - fdup f* f+! - std-stddev ; diff --git a/Task/Standard-deviation/Forth/standard-deviation-2.fth b/Task/Standard-deviation/Forth/standard-deviation-2.fth deleted file mode 100644 index de7357fe44..0000000000 --- a/Task/Standard-deviation/Forth/standard-deviation-2.fth +++ /dev/null @@ -1,18 +0,0 @@ -: st-count ( stats -- n ) f@ ; -: st-mean ( stats -- mean ) float+ f@ ; -: st-nvar ( stats -- n*var ) 2 floats + f@ ; - -: st-variance ( stats -- var ) dup st-nvar st-count f/ ; -: st-stddev ( stats -- stddev ) st-variance fsqrt ; - -: st-add ( x stats -- ) - dup - 1e dup f+! \ update count - fdup dup st-mean f- fswap - ( delta x ) - fover dup st-count f/ - ( delta x delta/n ) - float+ dup f+! \ update mean - ( delta x ) - dup f@ f- f* float+ f+! \ update nvar - st-stddev ; diff --git a/Task/Standard-deviation/Forth/standard-deviation-3.fth b/Task/Standard-deviation/Forth/standard-deviation-3.fth deleted file mode 100644 index 14462821e2..0000000000 --- a/Task/Standard-deviation/Forth/standard-deviation-3.fth +++ /dev/null @@ -1,10 +0,0 @@ -create stats 0e f, 0e f, 0e f, - -2e stats st-add f. \ 0. -4e stats st-add f. \ 1. -4e stats st-add f. \ 0.942809041582063 -4e stats st-add f. \ 0.866025403784439 -5e stats st-add f. \ 0.979795897113271 -5e stats st-add f. \ 1. -7e stats st-add f. \ 1.39970842444753 -9e stats st-add f. \ 2. diff --git a/Task/Standard-deviation/Fortran/standard-deviation-1.f b/Task/Standard-deviation/Fortran/standard-deviation-1.f deleted file mode 100644 index fbe6b25fc7..0000000000 --- a/Task/Standard-deviation/Fortran/standard-deviation-1.f +++ /dev/null @@ -1,49 +0,0 @@ -program standard_deviation - implicit none - integer(kind=4), parameter :: dp = kind(0.0d0) - - real(kind=dp), dimension(:), allocatable :: vals - integer(kind=4) :: i - - real(kind=dp), dimension(8) :: sample_data = (/ 2, 4, 4, 4, 5, 5, 7, 9 /) - - do i = lbound(sample_data, 1), ubound(sample_data, 1) - call sample_add(vals, sample_data(i)) - write(*, fmt='(''#'',I1,1X,''value = '',F3.1,1X,''stddev ='',1X,F10.8)') & - i, sample_data(i), stddev(vals) - end do - - if (allocated(vals)) deallocate(vals) -contains - ! Adds value :val: to array :population: dynamically resizing array - subroutine sample_add(population, val) - real(kind=dp), dimension(:), allocatable, intent (inout) :: population - real(kind=dp), intent (in) :: val - - real(kind=dp), dimension(:), allocatable :: tmp - integer(kind=4) :: n - - if (.not. allocated(population)) then - allocate(population(1)) - population(1) = val - else - n = size(population) - call move_alloc(population, tmp) - - allocate(population(n + 1)) - population(1:n) = tmp - population(n + 1) = val - endif - end subroutine sample_add - - ! Calculates standard deviation for given set of values - real(kind=dp) function stddev(vals) - real(kind=dp), dimension(:), intent(in) :: vals - real(kind=dp) :: mean - integer(kind=4) :: n - - n = size(vals) - mean = sum(vals)/n - stddev = sqrt(sum((vals - mean)**2)/n) - end function stddev -end program standard_deviation diff --git a/Task/Standard-deviation/Fortran/standard-deviation-2.f b/Task/Standard-deviation/Fortran/standard-deviation-2.f deleted file mode 100644 index 73f2657bbe..0000000000 --- a/Task/Standard-deviation/Fortran/standard-deviation-2.f +++ /dev/null @@ -1,74 +0,0 @@ - REAL FUNCTION STDDEV(X) !Standard deviation for successive values. - REAL X !The latest value. - REAL V !Scratchpad. - INTEGER N !Ongoing: count of the values. - REAL EX,EX2 !Ongoing: sum of X and X**2. - SAVE N,EX,EX2 !Retain values from one invocation to the next. - DATA N,EX,EX2/0,0.0,0.0/ !Initial values. - N = N + 1 !Another value arrives. - EX = X + EX !Augment the total. - EX2 = X**2 + EX2 !Augment the sum of squares. - V = EX2/N - (EX/N)**2 !The variance, but, it might come out negative! - STDDEV = SIGN(SQRT(ABS(V)),V) !Protect the SQRT, but produce a negative result if so. - END FUNCTION STDDEV !For the sequence of received X values. - - REAL FUNCTION STDDEVP(X) !Standard deviation for successive values. - REAL X !The latest value. - INTEGER N !Ongoing: count of the values. - REAL A,V !Ongoing: average, and sum of squared deviations. - SAVE N,A,V !Retain values from one invocation to the next. - DATA N,A,V/0,0.0,0.0/ !Initial values. - N = N + 1 !Another value arrives. - V = (N - 1)*(X - A)**2 /N + V !First, as it requires the existing average. - A = (X - A)/N + A != [x + (n - 1).A)]/n: recover the total from the average. - STDDEVP = SQRT(V/N) !V can never be negative, even with limited precision. - END FUNCTION STDDEVP !For the sequence of received X values. - - REAL FUNCTION STDDEVW(X) !Standard deviation for successive values. - REAL X !The latest value. - REAL V,D !Scratchpads. - INTEGER N !Ongoing: count of the values. - REAL EX,EX2 !Ongoing: sum of X and X**2. - REAL W !Ongoing: working mean. - SAVE N,EX,EX2,W !Retain values from one invocation to the next. - DATA N,EX,EX2/0,0.0,0.0/ !Initial values. - IF (N.LE.0) W = X !Take the first value as the working mean. - N = N + 1 !Another value arrives. - D = X - W !Its deviation from the working mean. - EX = D + EX !Augment the total. - EX2 = D**2 + EX2 !Augment the sum of squares. - V = EX2/N - (EX/N)**2 !The variance, but, it might come out negative! - STDDEVW = SIGN(SQRT(ABS(V)),V) !Protect the SQRT, but produce a negative result if so. - END FUNCTION STDDEVW !For the sequence of received X values. - - REAL FUNCTION STDDEVPW(X) !Standard deviation for successive values. - REAL X !The latest value. - INTEGER N !Ongoing: count of the values. - REAL A,V !Ongoing: average, and sum of squared deviations. - REAL W !Ongoing: working mean. - SAVE N,A,V,W !Retain values from one invocation to the next. - DATA N,A,V/0,0.0,0.0/ !Initial values. - IF (N.LE.0) W = X !Oh for self-modifying code! - N = N + 1 !Another value arrives. - D = X - W !Its deviation from the working mean. - V = (N - 1)*(D - A)**2 /N + V !First, as it requires the existing average. - A = (D - A)/N + A != [x + (n - 1).A)]/n: recover the total from the average. - STDDEVPW = SQRT(V/N) !V can never be negative, even with limited precision. - END FUNCTION STDDEVPW !For the sequence of received X values. - - PROGRAM TEST - INTEGER I !A stepper. - REAL A(8) !The example data. - DATA A/2.0,3*4.0,2*5.0,7.0,9.0/ !Alas, another opportunity to use @ passed over. - REAL B !An offsetting base. - WRITE (6,1) - 1 FORMAT ("Progressive calculation of the standard deviation."/ - 1 " I",7X,"A(I) EX EX2 Av V*N Ed Ed2 wAv V*N") - B = 1000000 !Provoke truncation error. - DO I = 1,8 !Step along the data series, - WRITE (6,2) I,INT(A(I) + B), !No fractional part, so I don't want F11.0. - 1 STDDEV(A(I) + B),STDDEVP(A(I) + B), !Showing progressive values. - 2 STDDEVW(A(I) + B),STDDEVPW(A(I) + B) !These with a working mean. - 2 FORMAT (I2,I11,1X,4F12.6) !Should do for the example. - END DO !On to the next value. - END diff --git a/Task/Standard-deviation/Go/standard-deviation.go b/Task/Standard-deviation/Go/standard-deviation.go deleted file mode 100644 index c45d5a09c6..0000000000 --- a/Task/Standard-deviation/Go/standard-deviation.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "math" -) - -func newRsdv() func(float64) float64 { - var n, a, q float64 - return func(x float64) float64 { - n++ - a1 := a+(x-a)/n - q, a = q+(x-a)*(x-a1), a1 - return math.Sqrt(q/n) - } -} - -func main() { - r := newRsdv() - for _, x := range []float64{2,4,4,4,5,5,7,9} { - fmt.Println(r(x)) - } -} diff --git a/Task/Standard-deviation/Groovy/standard-deviation.groovy b/Task/Standard-deviation/Groovy/standard-deviation.groovy deleted file mode 100644 index 04ebe4ee61..0000000000 --- a/Task/Standard-deviation/Groovy/standard-deviation.groovy +++ /dev/null @@ -1,9 +0,0 @@ -def sum = 0 -def sumSq = 0 -def count = 0 -[2,4,4,4,5,5,7,9].each { - sum += it - sumSq += it*it - count++ - println "running std.dev.: ${(sumSq/count - (sum/count)**2)**0.5}" -} diff --git a/Task/Standard-deviation/Haskell/standard-deviation.hs b/Task/Standard-deviation/Haskell/standard-deviation.hs deleted file mode 100644 index 1db491a4f2..0000000000 --- a/Task/Standard-deviation/Haskell/standard-deviation.hs +++ /dev/null @@ -1,21 +0,0 @@ -import Data.List (genericLength) -import Data.STRef -import Control.Monad.ST - -sd :: RealFloat a => [a] -> a -sd l = sqrt $ sum (map ((^2) . subtract mean) l) / n - where n = genericLength l - mean = sum l / n - -sdAccum :: RealFloat a => ST s (a -> ST s a) -sdAccum = do - accum <- newSTRef [] - return $ \x -> do - modifySTRef accum (x:) - list <- readSTRef accum - return $ sd list - -main = mapM_ print results - where results = runST $ do - runningSD <- sdAccum - mapM runningSD [2, 4, 4, 4, 5, 5, 7, 9] diff --git a/Task/Standard-deviation/Haxe/standard-deviation.haxe b/Task/Standard-deviation/Haxe/standard-deviation.haxe deleted file mode 100644 index 47fe74bf6f..0000000000 --- a/Task/Standard-deviation/Haxe/standard-deviation.haxe +++ /dev/null @@ -1,23 +0,0 @@ -using Lambda; - -class Main { - static function main():Void { - var nums = [2, 4, 4, 4, 5, 5, 7, 9]; - for (i in 1...nums.length+1) - Sys.println(sdev(nums.slice(0, i))); - } - - static function average(nums:Array):Float { - return nums.fold(function(n, t) return n + t, 0) / nums.length; - } - - static function sdev(nums:Array):Float { - var store = []; - var avg = average(nums); - for (n in nums) { - store.push((n - avg) * (n - avg)); - } - - return Math.sqrt(average(store)); - } -} diff --git a/Task/Standard-deviation/HicEst/standard-deviation.hicest b/Task/Standard-deviation/HicEst/standard-deviation.hicest deleted file mode 100644 index 0db9d3d144..0000000000 --- a/Task/Standard-deviation/HicEst/standard-deviation.hicest +++ /dev/null @@ -1,16 +0,0 @@ -REAL :: n=8, set(n), sum=0, sum2=0 - -set = (2,4,4,4,5,5,7,9) - -DO k = 1, n - WRITE() 'Adding ' // set(k) // 'stdev = ' // stdev(set(k)) -ENDDO - -END ! end of "main" - -FUNCTION stdev(x) - USE : sum, sum2, k - sum = sum + x - sum2 = sum2 + x*x - stdev = ( sum2/k - (sum/k)^2) ^ 0.5 - END diff --git a/Task/Standard-deviation/Icon/standard-deviation.icon b/Task/Standard-deviation/Icon/standard-deviation.icon deleted file mode 100644 index 887c0a3fcf..0000000000 --- a/Task/Standard-deviation/Icon/standard-deviation.icon +++ /dev/null @@ -1,22 +0,0 @@ -rocedure main() - -stddev() # reset state / empty -every s := stddev(![2,4,4,4,5,5,7,9]) do - write("stddev (so far) := ",s) - -end - -procedure stddev(x) /: running standard deviation -static X,sumX,sum2X - - if /x then { # reset state - X := [] - sumX := sum2X := 0. - } - else { # accumulate - put(X,x) - sumX +:= x - sum2X +:= x^2 - return sqrt( (sum2X / *X) - (sumX / *X)^2 ) - } -end diff --git a/Task/Standard-deviation/J/standard-deviation-1.j b/Task/Standard-deviation/J/standard-deviation-1.j deleted file mode 100644 index 6e8c9b0503..0000000000 --- a/Task/Standard-deviation/J/standard-deviation-1.j +++ /dev/null @@ -1,9 +0,0 @@ - mean=: +/ % # - dev=: - mean - stddevP=: [: %:@mean *:@dev NB. A) 3 equivalent defs for stddevP - stddevP=: [: mean&.:*: dev NB. B) uses Under (&.:) to apply inverse of *: after mean - stddevP=: %:@(mean@:*: - *:@mean) NB. C) sqrt of ((mean of squares) - (square of mean)) - - - stddevP\ 2 4 4 4 5 5 7 9 -0 1 0.942809 0.866025 0.979796 1 1.39971 2 diff --git a/Task/Standard-deviation/J/standard-deviation-2.j b/Task/Standard-deviation/J/standard-deviation-2.j deleted file mode 100644 index d26e207625..0000000000 --- a/Task/Standard-deviation/J/standard-deviation-2.j +++ /dev/null @@ -1,11 +0,0 @@ - of =: @: - sqrt =: %: - sum =: +/ - squares=: *: - data =: ] - mean =: sum % # - - stddevP=: sqrt of mean of squares of (data-mean) - - stddevP\ 2 4 4 4 5 5 7 9 -0 1 0.942809 0.866025 0.979796 1 1.39971 2 diff --git a/Task/Standard-deviation/J/standard-deviation-3.j b/Task/Standard-deviation/J/standard-deviation-3.j deleted file mode 100644 index 03ff69dd00..0000000000 --- a/Task/Standard-deviation/J/standard-deviation-3.j +++ /dev/null @@ -1,3 +0,0 @@ - require'stats' - (%:@:(%~<:)@:# * stddev)\ 2 4 4 4 5 5 7 9 -0 1 0.942809 0.866025 0.979796 1 1.39971 2 diff --git a/Task/Standard-deviation/Java/standard-deviation.java b/Task/Standard-deviation/Java/standard-deviation.java deleted file mode 100644 index 8b49b32d1e..0000000000 --- a/Task/Standard-deviation/Java/standard-deviation.java +++ /dev/null @@ -1,22 +0,0 @@ -public class StdDev { - int n = 0; - double sum = 0; - double sum2 = 0; - - public double sd(double x) { - n++; - sum += x; - sum2 += x*x; - - return Math.sqrt(sum2/n - sum*sum/n/n); - } - - public static void main(String[] args) { - double[] testData = {2,4,4,4,5,5,7,9}; - StdDev sd = new StdDev(); - - for (double x : testData) { - System.out.println(sd.sd(x)); - } - } -} diff --git a/Task/Standard-deviation/JavaScript/standard-deviation.js b/Task/Standard-deviation/JavaScript/standard-deviation.js deleted file mode 100644 index cb6c72a248..0000000000 --- a/Task/Standard-deviation/JavaScript/standard-deviation.js +++ /dev/null @@ -1,20 +0,0 @@ -function running_stddev() { - var n = 0; - var sum = 0.0; - var sum_sq = 0.0; - return function(num) { - n++; - sum += num; - sum_sq += num*num; - return Math.sqrt( (sum_sq / n) - Math.pow(sum / n, 2) ); - } -} - -var sd = running_stddev(); -var nums = [2,4,4,4,5,5,7,9]; -var stddev = []; -for (var i in nums) - stddev.push( sd(nums[i]) ); - -// using WSH -WScript.Echo(stddev.join(', '); diff --git a/Task/Standard-deviation/Julia/standard-deviation.julia b/Task/Standard-deviation/Julia/standard-deviation.julia deleted file mode 100644 index c026609938..0000000000 --- a/Task/Standard-deviation/Julia/standard-deviation.julia +++ /dev/null @@ -1,22 +0,0 @@ -function makerunningstd() - a = zero(Float64) - b = zero(Float64) - n = zero(Int64) - function runningstd(x) - a += x - b += x^2 - n += 1 - std = sqrt(n*b - a^2)/n - return std - end - return runningstd -end - -test = [2, 4, 4, 4, 5, 5, 7, 9] - -rstd = makerunningstd() - -println("Perform a running standard deviation of ", test) -for i in test - println(i, " => ", rstd(i)) -end diff --git a/Task/Standard-deviation/Liberty-BASIC/standard-deviation.liberty b/Task/Standard-deviation/Liberty-BASIC/standard-deviation.liberty deleted file mode 100644 index 7a23789fb3..0000000000 --- a/Task/Standard-deviation/Liberty-BASIC/standard-deviation.liberty +++ /dev/null @@ -1,26 +0,0 @@ - dim SD.storage$( 100) ' can call up to 100 versions, using ID to identify.. arrays are global. - ' holds (space-separated) number of data items so far, current sum.of.values and current sum.of.squares - - for i =1 to 8 - read x - print "New data "; x; " so S.D. now = "; using( "###.######", standard.deviation( 1, x)) - next i - - end - -function standard.deviation( ID, in) - if SD.storage$( ID) ="" then SD.storage$( ID) ="0 0 0" - num.so.far =val( word$( SD.storage$( ID), 1)) - sum.vals =val( word$( SD.storage$( ID), 2)) - sum.sqs =val( word$( SD.storage$( ID), 3)) - num.so.far =num.so.far +1 - sum.vals =sum.vals +in - sum.sqs =sum.sqs +in^2 - - ' standard deviation = square root of (the average of the squares less the square of the average) - standard.deviation =( ( sum.sqs /num.so.far) - ( sum.vals /num.so.far)^2)^0.5 - - SD.storage$( ID) =str$( num.so.far) +" " +str$( sum.vals) +" " +str$( sum.sqs) -end function - - Data 2, 4, 4, 4, 5, 5, 7, 9 diff --git a/Task/Standard-deviation/Lua/standard-deviation.lua b/Task/Standard-deviation/Lua/standard-deviation.lua deleted file mode 100644 index 088bc0f89a..0000000000 --- a/Task/Standard-deviation/Lua/standard-deviation.lua +++ /dev/null @@ -1,12 +0,0 @@ -function stdev() - local sum, sumsq, k = 0,0,0 - return function(n) - sum, sumsq, k = sum + n, sumsq + n^2, k+1 - return math.sqrt((sumsq / k) - (sum/k)^2) - end -end - -ldev = stdev() -for i, v in ipairs{2,4,4,4,5,5,7,9} do - print(ldev(v)) -end diff --git a/Task/Standard-deviation/MATLAB/standard-deviation-1.m b/Task/Standard-deviation/MATLAB/standard-deviation-1.m deleted file mode 100644 index b5d8951025..0000000000 --- a/Task/Standard-deviation/MATLAB/standard-deviation-1.m +++ /dev/null @@ -1,7 +0,0 @@ - x = [2,4,4,4,5,5,7,9]; - n = length (x); - - m = mean (x); - x2 = mean (x .* x); - dev= sqrt (x2 - m * m) - dev = 2 diff --git a/Task/Standard-deviation/MATLAB/standard-deviation-2.m b/Task/Standard-deviation/MATLAB/standard-deviation-2.m deleted file mode 100644 index 0aedfc26e9..0000000000 --- a/Task/Standard-deviation/MATLAB/standard-deviation-2.m +++ /dev/null @@ -1,6 +0,0 @@ - m = cumsum(x) ./ [1:n]; % running mean - x2= cumsum(x.^2) ./ [1:n]; % running squares - - dev = sqrt(x2 - m .* m) - dev = - 0.00000 1.00000 0.94281 0.86603 0.97980 1.00000 1.39971 2.00000 diff --git a/Task/Standard-deviation/MATLAB/standard-deviation-3.m b/Task/Standard-deviation/MATLAB/standard-deviation-3.m deleted file mode 100644 index 52ba6537f5..0000000000 --- a/Task/Standard-deviation/MATLAB/standard-deviation-3.m +++ /dev/null @@ -1,3 +0,0 @@ -function stdDevEval(n) -disp(sqrt(sum((n-sum(n)/length(n)).^2)/length(n))); -end diff --git a/Task/Standard-deviation/Mathematica/standard-deviation.math b/Task/Standard-deviation/Mathematica/standard-deviation.math deleted file mode 100644 index befff63f36..0000000000 --- a/Task/Standard-deviation/Mathematica/standard-deviation.math +++ /dev/null @@ -1,2 +0,0 @@ -runningSTDDev[n_] := (If[Not[ValueQ[$Data]], $Data = {}]; - StandardDeviation[AppendTo[$Data, n]]) diff --git a/Task/Standard-deviation/OCaml/standard-deviation.ocaml b/Task/Standard-deviation/OCaml/standard-deviation.ocaml deleted file mode 100644 index 190b68203f..0000000000 --- a/Task/Standard-deviation/OCaml/standard-deviation.ocaml +++ /dev/null @@ -1,15 +0,0 @@ -let sqr x = x *. x - -let stddev l = - let n, sx, sx2 = - List.fold_left - (fun (n, sx, sx2) x -> succ n, sx +. x, sx2 +. sqr x) - (0, 0., 0.) l - in - sqrt ((sx2 -. sqr sx /. float n) /. float n) - -let _ = - let l = [ 2.;4.;4.;4.;5.;5.;7.;9. ] in - Printf.printf "List: "; - List.iter (Printf.printf "%g ") l; - Printf.printf "\nStandard deviation: %g\n" (stddev l) diff --git a/Task/Standard-deviation/Objeck/standard-deviation.objeck b/Task/Standard-deviation/Objeck/standard-deviation.objeck deleted file mode 100644 index 156467ce5c..0000000000 --- a/Task/Standard-deviation/Objeck/standard-deviation.objeck +++ /dev/null @@ -1,35 +0,0 @@ -use Structure; - -bundle Default { - class StdDev { - nums : FloatVector; - - New() { - nums := FloatVector->New(); - } - - function : Main(args : String[]) ~ Nil { - sd := StdDev->New(); - test_data := [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]; - each(i : test_data) { - sd->AddNum(test_data[i]); - sd->GetSD()->PrintLine(); - }; - } - - method : public : AddNum(num : Float) ~ Nil { - nums->AddBack(num); - } - - method : public : native : GetSD() ~ Float { - sq_diffs := 0.0; - avg := nums->Average(); - each(i : nums) { - num := nums->Get(i); - sq_diffs += (num - avg) * (num - avg); - }; - - return (sq_diffs / nums->Size())->SquareRoot(); - } - } -} diff --git a/Task/Standard-deviation/Objective-C/standard-deviation-1.m b/Task/Standard-deviation/Objective-C/standard-deviation-1.m deleted file mode 100644 index 37e2c439d2..0000000000 --- a/Task/Standard-deviation/Objective-C/standard-deviation-1.m +++ /dev/null @@ -1,55 +0,0 @@ -#import - -@interface SDAccum : NSObject -{ - double sum, sum2; - unsigned int num; -} --(double)value: (double)v; --(unsigned int)count; --(double)mean; --(double)variance; --(double)stddev; -@end - -@implementation SDAccum --(double)value: (double)v -{ - sum += v; - sum2 += v*v; - num++; - return [self stddev]; -} --(unsigned int)count -{ - return num; -} --(double)mean -{ - return (num>0) ? sum/(double)num : 0.0; -} --(double)variance -{ - double m = [self mean]; - return (num>0) ? (sum2/(double)num - m*m) : 0.0; -} --(double)stddev -{ - return sqrt([self variance]); -} -@end - -int main() -{ - @autoreleasepool { - - double v[] = { 2,4,4,4,5,5,7,9 }; - - SDAccum *sdacc = [[SDAccum alloc] init]; - - for(int i=0; i < sizeof(v)/sizeof(*v) ; i++) - printf("adding %f\tstddev = %f\n", v[i], [sdacc value: v[i]]); - - } - return 0; -} diff --git a/Task/Standard-deviation/Objective-C/standard-deviation-2.m b/Task/Standard-deviation/Objective-C/standard-deviation-2.m deleted file mode 100644 index 39ee4aa1d5..0000000000 --- a/Task/Standard-deviation/Objective-C/standard-deviation-2.m +++ /dev/null @@ -1,30 +0,0 @@ -#import - -typedef double (^Func)(double); // a block that takes a double and returns a double - -Func sdCreator() { - __block int n = 0; - __block double sum = 0; - __block double sum2 = 0; - return ^(double x) { - sum += x; - sum2 += x*x; - n++; - return sqrt(sum2/n - sum*sum/n/n); - }; -} - -int main() -{ - @autoreleasepool { - - double v[] = { 2,4,4,4,5,5,7,9 }; - - Func sdacc = sdCreator(); - - for(int i=0; i < sizeof(v)/sizeof(*v) ; i++) - printf("adding %f\tstddev = %f\n", v[i], sdacc(v[i])); - - } - return 0; -} diff --git a/Task/Standard-deviation/PARI-GP/standard-deviation.pari b/Task/Standard-deviation/PARI-GP/standard-deviation.pari deleted file mode 100644 index f48d01f05f..0000000000 --- a/Task/Standard-deviation/PARI-GP/standard-deviation.pari +++ /dev/null @@ -1,19 +0,0 @@ -newpoint(x)={ - myT=x; - myS=0; - myN=1; - [myT,myS]/myN -}; -addpoint(x)={ - myT+=x; - myN++; - myS+=(myN*x-myT)^2/myN/(myN-1); - [myT,myS]/myN -}; -addpoints(v)={ - print(newpoint(v[1])); - for(i=2,#v,print(addpoint(v[i]))); - print("Mean: ",myT/myN); - print("Standard deviation: ",sqrt(myS/myN)) -}; -addpoints([2,4,4,4,5,5,7,9]) diff --git a/Task/Standard-deviation/PHP/standard-deviation.php b/Task/Standard-deviation/PHP/standard-deviation.php deleted file mode 100644 index e56cdaeb7f..0000000000 --- a/Task/Standard-deviation/PHP/standard-deviation.php +++ /dev/null @@ -1,31 +0,0 @@ -reset(); - } - # callable on an instance - function reset() { - $this->cnt=0; $this->sumup=0; $this->square=0; - } - function add($f) { - $this->cnt++; - $this->sumup += $f; - $this->square += pow($f, 2); - return $this->calc(); - } - function calc() { - if ($this->cnt==0 || $this->sumup==0) { - return 0; - } else { - return sqrt($this->square / $this->cnt - pow(($this->sumup / $this->cnt),2)); - } - } - } - -# start test, adding test data one by one -$c = new sdcalc(); -foreach ([2,4,4,4,5,5,7,9] as $v) { - printf('Adding %g: result %g%s', $v, $c->add($v), PHP_EOL); -} diff --git a/Task/Standard-deviation/PL-I/standard-deviation.pli b/Task/Standard-deviation/PL-I/standard-deviation.pli deleted file mode 100644 index 072d6fc244..0000000000 --- a/Task/Standard-deviation/PL-I/standard-deviation.pli +++ /dev/null @@ -1,25 +0,0 @@ -*process source attributes xref; - stddev: proc options(main); - declare a(10) float init(1,2,3,4,5,6,7,8,9,10); - declare stdev float; - declare i fixed binary; - - stdev=std_dev(a); - put skip list('Standard deviation', stdev); - - std_dev: procedure(a) returns(float); - declare a(*) float, n fixed binary; - n=hbound(a,1); - begin; - declare b(n) float, average float; - declare i fixed binary; - do i=1 to n; - b(i)=a(i); - end; - average=sum(a)/n; - put skip data(average); - return( sqrt(sum(b**2)/n - average**2) ); - end; - end std_dev; - - end; diff --git a/Task/Standard-deviation/Pascal/standard-deviation-1.pascal b/Task/Standard-deviation/Pascal/standard-deviation-1.pascal deleted file mode 100644 index c41d3f5ea6..0000000000 --- a/Task/Standard-deviation/Pascal/standard-deviation-1.pascal +++ /dev/null @@ -1,28 +0,0 @@ -program stddev; -uses math; -const - n=8; -var - arr: array[1..n] of real =(2,4,4,4,5,5,7,9); -function stddev(n: integer): real; -var - i: integer; - s1,s2,variance,x: real; -begin - for i:=1 to n do - begin - x:=arr[i]; - s1:=s1+power(x,2); - s2:=s2+x - end; - variance:=((n*s1)-(power(s2,2)))/(power(n,2)); - stddev:=sqrt(variance) -end; -var - i: integer; -begin - for i:=1 to n do - begin - writeln(i,' item=',arr[i]:2:0,' stddev=',stddev(i):18:15) - end -end. diff --git a/Task/Standard-deviation/Pascal/standard-deviation-2.pascal b/Task/Standard-deviation/Pascal/standard-deviation-2.pascal deleted file mode 100644 index 3dbfb225a3..0000000000 --- a/Task/Standard-deviation/Pascal/standard-deviation-2.pascal +++ /dev/null @@ -1,31 +0,0 @@ -program prj_CalcStdDerv; - -{$APPTYPE CONSOLE} - -uses - Math; - -var Series:Array of Extended; - UserString:String; - - -function AppendAndCalc(NewVal:Extended):Extended; - -begin - setlength(Series,high(Series)+2); - Series[high(Series)] := NewVal; - result := PopnStdDev(Series); -end; - -const data:array[0..7] of Extended = - (2,4,4,4,5,5,7,9); - -var rr: Extended; -begin - setlength(Series,0); - for rr in data do - begin - writeln(rr,' -> ',AppendAndCalc(rr)); - end; - Readln; -end. diff --git a/Task/Standard-deviation/Perl-6/standard-deviation-1.pl6 b/Task/Standard-deviation/Perl-6/standard-deviation-1.pl6 deleted file mode 100644 index a46491d833..0000000000 --- a/Task/Standard-deviation/Perl-6/standard-deviation-1.pl6 +++ /dev/null @@ -1,12 +0,0 @@ -sub sd (@a) { - my $mean = @a R/ [+] @a; - sqrt @a R/ [+] map (* - $mean)**2, @a; -} -  -sub sdaccum { - my @a; - return { push @a, $^x; sd @a; }; -} -  -my &f = sdaccum; -say f $_ for 2, 4, 4, 4, 5, 5, 7, 9; diff --git a/Task/Standard-deviation/Perl-6/standard-deviation-2.pl6 b/Task/Standard-deviation/Perl-6/standard-deviation-2.pl6 deleted file mode 100644 index d94252b6d0..0000000000 --- a/Task/Standard-deviation/Perl-6/standard-deviation-2.pl6 +++ /dev/null @@ -1,9 +0,0 @@ -# remember that <(x-)²> = - ² -sub stddev($x) { - sqrt - (.[2] += $x**2) / ++.[0] - - ((.[1] += $x) / .[0])**2 - given state @; -} - -say stddev $_ for <2 4 4 4 5 5 7 9>; diff --git a/Task/Standard-deviation/Perl/standard-deviation-1.pl b/Task/Standard-deviation/Perl/standard-deviation-1.pl deleted file mode 100644 index c93b958631..0000000000 --- a/Task/Standard-deviation/Perl/standard-deviation-1.pl +++ /dev/null @@ -1,37 +0,0 @@ -{ - package SDAccum; - sub new { - my $class = shift; - my $self = {}; - $self->{sum} = 0.0; - $self->{sum2} = 0.0; - $self->{num} = 0; - bless $self, $class; - return $self; - } - sub count { - my $self = shift; - return $self->{num}; - } - sub mean { - my $self = shift; - return ($self->{num}>0) ? $self->{sum}/$self->{num} : 0.0; - } - sub variance { - my $self = shift; - my $m = $self->mean; - return ($self->{num}>0) ? $self->{sum2}/$self->{num} - $m * $m : 0.0; - } - sub stddev { - my $self = shift; - return sqrt($self->variance); - } - sub value { - my $self = shift; - my $v = shift; - $self->{sum} += $v; - $self->{sum2} += $v * $v; - $self->{num}++; - return $self->stddev; - } -} diff --git a/Task/Standard-deviation/Perl/standard-deviation-2.pl b/Task/Standard-deviation/Perl/standard-deviation-2.pl deleted file mode 100644 index 80301927ec..0000000000 --- a/Task/Standard-deviation/Perl/standard-deviation-2.pl +++ /dev/null @@ -1,7 +0,0 @@ -my $sdacc = SDAccum->new; -my $sd; - -foreach my $v ( 2,4,4,4,5,5,7,9 ) { - $sd = $sdacc->value($v); -} -print "std dev = $sd\n"; diff --git a/Task/Standard-deviation/Perl/standard-deviation-3.pl b/Task/Standard-deviation/Perl/standard-deviation-3.pl deleted file mode 100644 index 26a5694795..0000000000 --- a/Task/Standard-deviation/Perl/standard-deviation-3.pl +++ /dev/null @@ -1,14 +0,0 @@ -# <(x - )²> = - ² -{ - my $num, $sum, $sum2; - sub stddev { - my $x = shift; - $num++; - return sqrt( - ($sum2 += $x**2) / $num - - (($sum += $x) / $num)**2 - ); - } -} - -print stddev($_), "\n" for qw(2 4 4 4 5 5 7 9); diff --git a/Task/Standard-deviation/PicoLisp/standard-deviation.l b/Task/Standard-deviation/PicoLisp/standard-deviation.l deleted file mode 100644 index 16d9b927b2..0000000000 --- a/Task/Standard-deviation/PicoLisp/standard-deviation.l +++ /dev/null @@ -1,18 +0,0 @@ -(scl 2) - -(de stdDev () - (curry ((Data)) (N) - (push 'Data N) - (let (Len (length Data) M (*/ (apply + Data) Len)) - (sqrt - (*/ - (sum - '((N) (*/ (- N M) (- N M) 1.0)) - Data ) - 1.0 - Len ) - T ) ) ) ) - -(let Fun (stdDev) - (for N (2.0 4.0 4.0 4.0 5.0 5.0 7.0 9.0) - (prinl (format N *Scl) " -> " (format (Fun N) *Scl)) ) ) diff --git a/Task/Standard-deviation/PowerShell/standard-deviation.psh b/Task/Standard-deviation/PowerShell/standard-deviation.psh deleted file mode 100644 index b95d6fffc2..0000000000 --- a/Task/Standard-deviation/PowerShell/standard-deviation.psh +++ /dev/null @@ -1,13 +0,0 @@ -function Get-StandardDeviation { - begin { - $avg = 0 - $nums = @() - } - process { - $nums += $_ - $avg = ($nums | Measure-Object -Average).Average - $sum = 0; - $nums | ForEach-Object { $sum += ($avg - $_) * ($avg - $_) } - [Math]::Sqrt($sum / $nums.Length) - } -} diff --git a/Task/Standard-deviation/PureBasic/standard-deviation.purebasic b/Task/Standard-deviation/PureBasic/standard-deviation.purebasic deleted file mode 100644 index 756b97c185..0000000000 --- a/Task/Standard-deviation/PureBasic/standard-deviation.purebasic +++ /dev/null @@ -1,29 +0,0 @@ -;Define our Standard deviation function -Declare.d Standard_deviation(x) - -; Main program -If OpenConsole() - Define i, x - Restore MyList - For i=1 To 8 - Read.i x - PrintN(StrD(Standard_deviation(x))) - Next i - Print(#CRLF$+"Press ENTER to exit"): Input() -EndIf - -;Calculation procedure, with memory -Procedure.d Standard_deviation(In) - Static in_summa, antal - Static in_kvadrater.q - in_summa+in - in_kvadrater+in*in - antal+1 - ProcedureReturn Pow((in_kvadrater/antal)-Pow(in_summa/antal,2),0.50) -EndProcedure - -;data section -DataSection -MyList: - Data.i 2,4,4,4,5,5,7,9 -EndDataSection diff --git a/Task/Standard-deviation/Python/standard-deviation-1.py b/Task/Standard-deviation/Python/standard-deviation-1.py deleted file mode 100644 index be108e4de3..0000000000 --- a/Task/Standard-deviation/Python/standard-deviation-1.py +++ /dev/null @@ -1,22 +0,0 @@ ->>> from math import sqrt ->>> def sd(x): - sd.sum += x - sd.sum2 += x*x - sd.n += 1.0 - sum, sum2, n = sd.sum, sd.sum2, sd.n - return sqrt(sum2/n - sum*sum/n/n) - ->>> sd.sum = sd.sum2 = sd.n = 0 ->>> for value in (2,4,4,4,5,5,7,9): - print (value, sd(value)) - - -(2, 0.0) -(4, 1.0) -(4, 0.94280904158206258) -(4, 0.8660254037844386) -(5, 0.97979589711327075) -(5, 1.0) -(7, 1.3997084244475311) -(9, 2.0) ->>> diff --git a/Task/Standard-deviation/Python/standard-deviation-2.py b/Task/Standard-deviation/Python/standard-deviation-2.py deleted file mode 100644 index b8a8fb9a28..0000000000 --- a/Task/Standard-deviation/Python/standard-deviation-2.py +++ /dev/null @@ -1,13 +0,0 @@ ->>> class SD(object): # Plain () for python 3.x - def __init__(self): - self.sum, self.sum2, self.n = (0,0,0) - def sd(self, x): - self.sum += x - self.sum2 += x*x - self.n += 1.0 - sum, sum2, n = self.sum, self.sum2, self.n - return sqrt(sum2/n - sum*sum/n/n) - ->>> sd_inst = SD() ->>> for value in (2,4,4,4,5,5,7,9): - print (value, sd_inst.sd(value)) diff --git a/Task/Standard-deviation/Python/standard-deviation-3.py b/Task/Standard-deviation/Python/standard-deviation-3.py deleted file mode 100644 index 0812c9b16c..0000000000 --- a/Task/Standard-deviation/Python/standard-deviation-3.py +++ /dev/null @@ -1,25 +0,0 @@ ->>> from math import sqrt ->>> def sdcreator(): - sum = sum2 = n = 0 - def sd(x): - nonlocal sum, sum2, n - - sum += x - sum2 += x*x - n += 1.0 - return sqrt(sum2/n - sum*sum/n/n) - return sd - ->>> sd = sdcreator() ->>> for value in (2,4,4,4,5,5,7,9): - print (value, sd(value)) - - -2 0.0 -4 1.0 -4 0.942809041582 -4 0.866025403784 -5 0.979795897113 -5 1.0 -7 1.39970842445 -9 2.0 diff --git a/Task/Standard-deviation/Python/standard-deviation-4.py b/Task/Standard-deviation/Python/standard-deviation-4.py deleted file mode 100644 index ac0708af6b..0000000000 --- a/Task/Standard-deviation/Python/standard-deviation-4.py +++ /dev/null @@ -1,24 +0,0 @@ ->>> from math import sqrt ->>> def sdcreator(): - sum = sum2 = n = 0 - while True: - x = yield sqrt(sum2/n - sum*sum/n/n) if n else None - - sum += x - sum2 += x*x - n += 1.0 - ->>> sd = sdcreator() ->>> sd.send(None) ->>> for value in (2,4,4,4,5,5,7,9): - print (value, sd.send(value)) - - -2 0.0 -4 1.0 -4 0.942809041582 -4 0.866025403784 -5 0.979795897113 -5 1.0 -7 1.39970842445 -9 2.0 diff --git a/Task/Standard-deviation/Python/standard-deviation-5.py b/Task/Standard-deviation/Python/standard-deviation-5.py deleted file mode 100644 index 9ad200307c..0000000000 --- a/Task/Standard-deviation/Python/standard-deviation-5.py +++ /dev/null @@ -1,5 +0,0 @@ ->>> myMean = lambda MyList : reduce(lambda x, y: x + y, MyList) / float(len(MyList)) ->>> myStd = lambda MyList : (reduce(lambda x,y : x + y , map(lambda x: (x-myMean(MyList))**2 , MyList)) / float(len(MyList)))**.5 - ->>> print myStd([2,4,4,4,5,5,7,9]) -2.0 diff --git a/Task/Standard-deviation/R/standard-deviation-1.r b/Task/Standard-deviation/R/standard-deviation-1.r deleted file mode 100644 index 050ff0c212..0000000000 --- a/Task/Standard-deviation/R/standard-deviation-1.r +++ /dev/null @@ -1,11 +0,0 @@ -#The built-in standard deviation function applies the Bessel correction. To reverse this, we can apply an uncorrection. -#If na.rm is true, missing data points (NA values) are removed. - reverseBesselCorrection <- function(x, na.rm=FALSE) - { - if(na.rm) x <- x[!is.na(x)] - len <- length(x) - if(len < 2) stop("2 or more data points required") - sqrt((len-1)/len) - } - testdata <- c(2,4,4,4,5,5,7,9) - reverseBesselCorrection(testdata)*sd(testdata) #2 diff --git a/Task/Standard-deviation/R/standard-deviation-2.r b/Task/Standard-deviation/R/standard-deviation-2.r deleted file mode 100644 index 5d0229f9b4..0000000000 --- a/Task/Standard-deviation/R/standard-deviation-2.r +++ /dev/null @@ -1,11 +0,0 @@ -#Again, if na.rm is true, missing data points (NA values) are removed. - uncorrectedsd <- function(x, na.rm=FALSE) - { - len <- length(x) - if(len < 2) stop("2 or more data points required") - mu <- mean(x, na.rm=na.rm) - ssq <- sum((x - mu)^2, na.rm=na.rm) - usd <- sqrt(ssq/len) - usd - } - uncorrectedsd(testdata) #2 diff --git a/Task/Standard-deviation/README b/Task/Standard-deviation/README deleted file mode 100644 index 61532c638b..0000000000 --- a/Task/Standard-deviation/README +++ /dev/null @@ -1 +0,0 @@ -Data source: http://rosettacode.org/wiki/Standard_deviation diff --git a/Task/Standard-deviation/REXX/standard-deviation.rexx b/Task/Standard-deviation/REXX/standard-deviation.rexx deleted file mode 100644 index d8f4955e87..0000000000 --- a/Task/Standard-deviation/REXX/standard-deviation.rexx +++ /dev/null @@ -1,17 +0,0 @@ -/*REXX pgm finds & displays the standard deviation of a given set of numbers.*/ -parse arg # /*any optional arguments on the C.L. ? */ -if #='' then # = 2 4 4 4 5 5 7 9 /*None specified? Then use the default*/ -w=words(#); L=length(w); $=0; $$=0 /*# items; item width; couple of sums*/ - /* [↓] process each number in the list*/ - do j=1 for w; _=word(#,j); $=$+_; $$=$$+_**2 - say ' item' right(j,L)":" right(_,4) ' average=' left($/j,12), - ' standard deviation=' left(sqrt( $$/j - ($/j)**2 ), 15) - end /*j*/ /* [↑] prettify output with whitespace*/ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 - numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ - numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Standard-deviation/Racket/standard-deviation.rkt b/Task/Standard-deviation/Racket/standard-deviation.rkt deleted file mode 100644 index 858cc66db6..0000000000 --- a/Task/Standard-deviation/Racket/standard-deviation.rkt +++ /dev/null @@ -1,7 +0,0 @@ -#lang racket -(require math) -(define running-stddev - (let ([ns '()]) - (λ(n) (set! ns (cons n ns)) (stddev ns)))) -;; run it on each number, return the last result -(last (map running-stddev '(2 4 4 4 5 5 7 9))) diff --git a/Task/Standard-deviation/Ruby/standard-deviation-1.rb b/Task/Standard-deviation/Ruby/standard-deviation-1.rb deleted file mode 100644 index 7a25c6e948..0000000000 --- a/Task/Standard-deviation/Ruby/standard-deviation-1.rb +++ /dev/null @@ -1,25 +0,0 @@ -class StdDevAccumulator - def initialize - @n, @sum, @sumofsquares = 0, 0.0, 0.0 - end - - def <<(num) - # return self to make this possible: sd << 1 << 2 << 3 # => 0.816496580927726 - @n += 1 - @sum += num - @sumofsquares += num**2 - self - end - - def stddev - Math.sqrt( (@sumofsquares / @n) - (@sum / @n)**2 ) - end - - def to_s - stddev.to_s - end -end - -sd = StdDevAccumulator.new -i = 0 -[2,4,4,4,5,5,7,9].each {|n| puts "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" } diff --git a/Task/Standard-deviation/Ruby/standard-deviation-2.rb b/Task/Standard-deviation/Ruby/standard-deviation-2.rb deleted file mode 100644 index a465fe5a73..0000000000 --- a/Task/Standard-deviation/Ruby/standard-deviation-2.rb +++ /dev/null @@ -1,12 +0,0 @@ -def sdaccum - n, sum, sum2 = 0, 0.0, 0.0 - lambda do |num| - n += 1 - sum += num - sum2 += num**2 - Math.sqrt( (sum2 / n) - (sum / n)**2 ) - end -end - -sd = sdaccum -[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), ", "} diff --git a/Task/Standard-deviation/Run-BASIC/standard-deviation.run b/Task/Standard-deviation/Run-BASIC/standard-deviation.run deleted file mode 100644 index 629cea3d1f..0000000000 --- a/Task/Standard-deviation/Run-BASIC/standard-deviation.run +++ /dev/null @@ -1,16 +0,0 @@ -dim sdSave$(100) 'can call up to 100 versions - 'holds (space-separated) number of data , sum of values and sum of squares -sd$ = "2,4,4,4,5,5,7,9" - -for num = 1 to 8 - stdData = val(word$(sd$,num,",")) - sumVal = sumVal + stdData - sumSqs = sumSqs + stdData^2 - - ' standard deviation = square root of (the average of the squares less the square of the average) - standDev =((sumSqs / num) - (sumVal /num) ^ 2) ^ 0.5 - - sdSave$(num) = str$(num);" ";str$(sumVal);" ";str$(sumSqs) - print num;" value in = ";stdData; " Stand Dev = "; using("###.######", standDev) - -next num diff --git a/Task/Standard-deviation/SAS/standard-deviation.sas b/Task/Standard-deviation/SAS/standard-deviation.sas deleted file mode 100644 index a55e2ca60b..0000000000 --- a/Task/Standard-deviation/SAS/standard-deviation.sas +++ /dev/null @@ -1,32 +0,0 @@ -*--Load the test data; -data test1; - input x @@; - obs=_n_; -datalines; -2 4 4 4 5 5 7 9 -; -run; - -*--Create a dataset with the cummulative data for each set of data for which the SD should be calculated; -data test2 (drop=i obs); - set test1; - y=x; - do i=1 to n; - set test1 (rename=(obs=setid)) nobs=n point=i; - if obs<=setid then output; - end; -proc sort; - by setid; -run; - -*--Calulate the standards deviation (and mean) using PROC MEANS; -proc means data=test2 vardef=n noprint; *--use vardef=n option to calculate the population SD; - by setid; - var y; - output out=stat1 n=n mean=mean std=sd; -run; - -*--Output the calculated standard deviations; -proc print data=stat1 noobs; - var n sd /*mean*/; -run; diff --git a/Task/Standard-deviation/SQL/standard-deviation.sql b/Task/Standard-deviation/SQL/standard-deviation.sql deleted file mode 100644 index 74b10a02a8..0000000000 --- a/Task/Standard-deviation/SQL/standard-deviation.sql +++ /dev/null @@ -1,34 +0,0 @@ --- the minimal table -create table if not exists teststd (n double precision not null); - --- code modularity with view, we could have used a common table expression instead -create view vteststd as - select count(n) as cnt, - sum(n) as tsum, - sum(power(n,2)) as tsqr -from teststd; - --- you can of course put this code into every query -create or replace function std_dev() returns double precision as $$ - select sqrt(tsqr/cnt - (tsum/cnt)^2) from vteststd; -$$ language sql; - --- test data is: 2,4,4,4,5,5,7,9 -insert into teststd values (2); -select std_dev() as std_deviation; -insert into teststd values (4); -select std_dev() as std_deviation; -insert into teststd values (4); -select std_dev() as std_deviation; -insert into teststd values (4); -select std_dev() as std_deviation; -insert into teststd values (5); -select std_dev() as std_deviation; -insert into teststd values (5); -select std_dev() as std_deviation; -insert into teststd values (7); -select std_dev() as std_deviation; -insert into teststd values (9); -select std_dev() as std_deviation; --- cleanup test data -delete from teststd; diff --git a/Task/Standard-deviation/Scala/standard-deviation.scala b/Task/Standard-deviation/Scala/standard-deviation.scala deleted file mode 100644 index dab352a6e8..0000000000 --- a/Task/Standard-deviation/Scala/standard-deviation.scala +++ /dev/null @@ -1,26 +0,0 @@ -import scala.math.sqrt - -object StddevCalc extends App { - - def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = { - def avg(ts: Iterable[T])(implicit num: Fractional[T]): T = { - num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T - } - - val mean = avg(ts) // Leave val type of T - val stdDev = // Root of mean diffs - sqrt(num.toDouble( - ts.foldLeft(num.zero)((b, a) => - num.plus(b, num.times(num.minus(a, mean), num.minus(a, mean))))) / - ts.size) - (mean, stdDev) - } - - def calcAvgAndStddev(ts: Iterable[BigDecimal]): (Double, Double) = // Overloaded for BigDecimal - calcAvgAndStddev(ts.map(_.toDouble)) - - println(calcAvgAndStddev(List(2.0E0, 4.0, 4, 4, 5, 5, 7, 9))) - println(calcAvgAndStddev(Set(1.0, 2, 3, 4))) - println(calcAvgAndStddev(0.1 to 1.1 by 0.05)) - println(calcAvgAndStddev(List(BigDecimal(120), BigDecimal(1200)))) -} diff --git a/Task/Standard-deviation/Scheme/standard-deviation.ss b/Task/Standard-deviation/Scheme/standard-deviation.ss deleted file mode 100644 index db5d10a333..0000000000 --- a/Task/Standard-deviation/Scheme/standard-deviation.ss +++ /dev/null @@ -1,16 +0,0 @@ -(define (standart-deviation-generator) - (let ((nums '())) - (lambda (x) - (set! nums (cons x nums)) - (let* ((mean (/ (apply + nums) (length nums))) - (mean-sqr (lambda (y) (expt (- y mean) 2))) - (variance (/ (apply + (map mean-sqr nums)) (length nums)))) - (sqrt variance))))) - -(let loop ((f (standart-deviation-generator)) - (input '(2 4 4 4 5 5 7 9))) - (if (not (null? input)) - (begin - (display (f (car input))) - (newline) - (loop f (cdr input))))) diff --git a/Task/Standard-deviation/Scilab/standard-deviation.scilab b/Task/Standard-deviation/Scilab/standard-deviation.scilab deleted file mode 100644 index ac0b36e539..0000000000 --- a/Task/Standard-deviation/Scilab/standard-deviation.scilab +++ /dev/null @@ -1,2 +0,0 @@ -T=[2,4,4,4,5,5,7,9]; -stdev(T)*sqrt((length(T)-1)/length(T)) diff --git a/Task/Standard-deviation/Smalltalk/standard-deviation-1.st b/Task/Standard-deviation/Smalltalk/standard-deviation-1.st deleted file mode 100644 index 1cd4281431..0000000000 --- a/Task/Standard-deviation/Smalltalk/standard-deviation-1.st +++ /dev/null @@ -1,20 +0,0 @@ -Object subclass: SDAccum [ - |sum sum2 num| - SDAccum class >> new [ |o| - o := super basicNew. - ^ o init. - ] - init [ sum := 0. sum2 := 0. num := 0 ] - value: aValue [ - sum := sum + aValue. - sum2 := sum2 + ( aValue * aValue ). - num := num + 1. - ^ self stddev - ] - count [ ^ num ] - mean [ num>0 ifTrue: [^ sum / num] ifFalse: [ ^ 0.0 ] ] - variance [ |m| m := self mean. - num>0 ifTrue: [^ (sum2/num) - (m*m) ] ifFalse: [ ^ 0.0 ] - ] - stddev [ ^ (self variance) sqrt ] -]. diff --git a/Task/Standard-deviation/Smalltalk/standard-deviation-2.st b/Task/Standard-deviation/Smalltalk/standard-deviation-2.st deleted file mode 100644 index 7d85f70b18..0000000000 --- a/Task/Standard-deviation/Smalltalk/standard-deviation-2.st +++ /dev/null @@ -1,5 +0,0 @@ -|sdacc sd| -sdacc := SDAccum new. - -#( 2 4 4 4 5 5 7 9 ) do: [ :v | sd := sdacc value: v ]. -('std dev = %1' % { sd }) displayNl. diff --git a/Task/Standard-deviation/Tcl/standard-deviation-1.tcl b/Task/Standard-deviation/Tcl/standard-deviation-1.tcl deleted file mode 100644 index d09f7b464e..0000000000 --- a/Task/Standard-deviation/Tcl/standard-deviation-1.tcl +++ /dev/null @@ -1,33 +0,0 @@ -oo::class create SDAccum { - variable sum sum2 num - constructor {} { - set sum 0.0 - set sum2 0.0 - set num 0 - } - method value {x} { - set sum2 [expr {$sum2 + $x**2}] - set sum [expr {$sum + $x}] - incr num - return [my stddev] - } - method count {} { - return $num - } - method mean {} { - expr {$sum / $num} - } - method variance {} { - expr {$sum2/$num - [my mean]**2} - } - method stddev {} { - expr {sqrt([my variance])} - } -} - -# Demonstration -set sdacc [SDAccum new] -foreach val {2 4 4 4 5 5 7 9} { - set sd [$sdacc value $val] -} -puts "the standard deviation is: $sd" diff --git a/Task/Standard-deviation/Tcl/standard-deviation-2.tcl b/Task/Standard-deviation/Tcl/standard-deviation-2.tcl deleted file mode 100644 index c64e787067..0000000000 --- a/Task/Standard-deviation/Tcl/standard-deviation-2.tcl +++ /dev/null @@ -1,20 +0,0 @@ -# Make a coroutine out of a lambda application -coroutine sd apply {{} { - set sum 0.0 - set sum2 0.0 - set sd {} - # Keep processing argument values until told not to... - while {[set val [yield $sd]] ne "stop"} { - incr n - set sum [expr {$sum + $val}] - set sum2 [expr {$sum2 + $val**2}] - set sd [expr {sqrt($sum2/$n - ($sum/$n)**2)}] - } -}} - -# Demonstration -foreach val {2 4 4 4 5 5 7 9} { - set sd [sd $val] -} -sd stop -puts "the standard deviation is: $sd" diff --git a/Task/Standard-deviation/VBScript/standard-deviation.vb b/Task/Standard-deviation/VBScript/standard-deviation.vb deleted file mode 100644 index 237a6d559a..0000000000 --- a/Task/Standard-deviation/VBScript/standard-deviation.vb +++ /dev/null @@ -1,21 +0,0 @@ -data = Array(2,4,4,4,5,5,7,9) - -For i = 0 To UBound(data) - WScript.StdOut.Write "value = " & data(i) &_ - " running sd = " & sd(data,i) - WScript.StdOut.WriteLine -Next - -Function sd(arr,n) - mean = 0 - variance = 0 - For j = 0 To n - mean = mean + arr(j) - Next - mean = mean/(n+1) - For k = 0 To n - variance = variance + ((arr(k)-mean)^2) - Next - variance = variance/(n+1) - sd = FormatNumber(Sqr(variance),6) -End Function diff --git a/Task/Standard-deviation/Visual-Basic/standard-deviation.vb b/Task/Standard-deviation/Visual-Basic/standard-deviation.vb deleted file mode 100644 index d6ce338d17..0000000000 --- a/Task/Standard-deviation/Visual-Basic/standard-deviation.vb +++ /dev/null @@ -1,50 +0,0 @@ -Function avg(what() As Variant) As Variant - 'treats non-numeric strings as zero - Dim L0 As Variant, total As Variant - For L0 = LBound(what) To UBound(what) - If IsNumeric(what(L0)) Then total = total + what(L0) - Next - avg = total / (1 + UBound(what) - LBound(what)) -End Function - -Function standardDeviation(fp As Variant) As Variant - Static list() As Variant - Dim av As Variant, tmp As Variant, L0 As Variant - - 'add to sequence if numeric - If IsNumeric(fp) Then - On Error GoTo makeArr 'catch undimensioned list - ReDim Preserve list(UBound(list) + 1) - On Error GoTo 0 - list(UBound(list)) = fp - End If - - 'get average - av = avg(list()) - - 'the actual work - For L0 = 0 To UBound(list) - tmp = tmp + ((list(L0) - av) ^ 2) - Next - tmp = Sqr(tmp / (UBound(list) + 1)) - - standardDeviation = tmp - - Exit Function -makeArr: - If 9 = Err.Number Then - ReDim list(0) - Else - 'something's wrong - Err.Raise Err.Number - End If - Resume Next -End Function - -Sub tester() - Dim x As Variant - x = Array(2, 4, 4, 4, 5, 5, 7, 9) - For L0 = 0 To UBound(x) - Debug.Print standardDeviation(x(L0)) - Next -End Sub diff --git a/Task/Standard-deviation/XPL0/standard-deviation.xpl0 b/Task/Standard-deviation/XPL0/standard-deviation.xpl0 deleted file mode 100644 index 5b9d237da4..0000000000 --- a/Task/Standard-deviation/XPL0/standard-deviation.xpl0 +++ /dev/null @@ -1,13 +0,0 @@ -include c:\cxpl\codes; \intrinsic 'code' declarations -int A, I; -real N, S, S2; -[A:= [2,4,4,4,5,5,7,9]; -N:= 0.0; S:= 0.0; S2:= 0.0; -for I:= 0 to 8-1 do - [N:= N + 1.0; - S:= S + float(A(I)); - S2:= S2 + float(sq(A(I))); - RlOut(0, sqrt((S2/N) - sq(S/N))); - ]; -CrLf(0); -] diff --git a/Task/Start-from-a-main-routine/Ring/start-from-a-main-routine.ring b/Task/Start-from-a-main-routine/Ring/start-from-a-main-routine.ring new file mode 100644 index 0000000000..cdcf03c39e --- /dev/null +++ b/Task/Start-from-a-main-routine/Ring/start-from-a-main-routine.ring @@ -0,0 +1,2 @@ +func Main + see "Hello World!" + nl diff --git a/Task/Start-from-a-main-routine/Sed/start-from-a-main-routine.sed b/Task/Start-from-a-main-routine/Sed/start-from-a-main-routine.sed new file mode 100644 index 0000000000..5ef80db053 --- /dev/null +++ b/Task/Start-from-a-main-routine/Sed/start-from-a-main-routine.sed @@ -0,0 +1,12 @@ +# This code runs only for line 1. +1 { + i\ +Explain-a-lot processed this file and + i\ +replaced every period with three exclamation points!!! + i\ + +} + +# This code runs for each line of input. +s/\./!!!/g diff --git a/Task/Start-from-a-main-routine/Zkl/start-from-a-main-routine.zkl b/Task/Start-from-a-main-routine/Zkl/start-from-a-main-routine.zkl new file mode 100644 index 0000000000..a461db66d7 --- /dev/null +++ b/Task/Start-from-a-main-routine/Zkl/start-from-a-main-routine.zkl @@ -0,0 +1 @@ +"Hello".println() diff --git a/Task/State-name-puzzle/00DESCRIPTION b/Task/State-name-puzzle/00DESCRIPTION index 75ad5caabe..261b057e47 100644 --- a/Task/State-name-puzzle/00DESCRIPTION +++ b/Task/State-name-puzzle/00DESCRIPTION @@ -2,7 +2,10 @@ This task is inspired by [http://drdobbs.com/windows/198701685 Mark Nelson's DDJ Column "Wordplay"] and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [http://www.npr.org/templates/story/story.php?storyId=9264290] and originally attributed to David Edelheit. -The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two ''different'' U.S. States (so that all four state names differ from one another). What states are these? +The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two ''different'' U.S. States (so that all four state names differ from one another). + +What states are these? + The problem was reissued on [https://tapestry.tucson.az.us/twiki/bin/view/Main/StateNamesPuzzle the Unicon Discussion Web] which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to [[wp:Goedel_numbering|Gödel numbering]], [[wp:Equivalence_relation|equivalence relations]], and [[wp:Equivalence_classes|equivalence classes]]. The basic merits of these were discussed in the Unicon Discussion Web. diff --git a/Task/State-name-puzzle/jq/state-name-puzzle-1.jq b/Task/State-name-puzzle/Jq/state-name-puzzle-1.jq similarity index 100% rename from Task/State-name-puzzle/jq/state-name-puzzle-1.jq rename to Task/State-name-puzzle/Jq/state-name-puzzle-1.jq diff --git a/Task/State-name-puzzle/jq/state-name-puzzle-2.jq b/Task/State-name-puzzle/Jq/state-name-puzzle-2.jq similarity index 100% rename from Task/State-name-puzzle/jq/state-name-puzzle-2.jq rename to Task/State-name-puzzle/Jq/state-name-puzzle-2.jq diff --git a/Task/State-name-puzzle/jq/state-name-puzzle-3.jq b/Task/State-name-puzzle/Jq/state-name-puzzle-3.jq similarity index 100% rename from Task/State-name-puzzle/jq/state-name-puzzle-3.jq rename to Task/State-name-puzzle/Jq/state-name-puzzle-3.jq diff --git a/Task/State-name-puzzle/Phix/state-name-puzzle.phix b/Task/State-name-puzzle/Phix/state-name-puzzle.phix new file mode 100644 index 0000000000..fc07a68807 --- /dev/null +++ b/Task/State-name-puzzle/Phix/state-name-puzzle.phix @@ -0,0 +1,50 @@ +constant states = {"Alabama", "Alaska", "Arizona", "Arkansas", + "California", "Colorado", "Connecticut", "Delaware", + "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", + "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", + "Maine", "Maryland", "Massachusetts", "Michigan", + "Minnesota", "Mississippi", "Missouri", "Montana", + "Nebraska", "Nevada", "New Hampshire", "New Jersey", + "New Mexico", "New York", "North Carolina", "North Dakota", + "Ohio", "Oklahoma", "Oregon", "Pennsylvania", + "Rhode Island", "South Carolina", "South Dakota", + "Tennessee", "Texas", "Utah", "Vermont", "Virginia", + "Washington", "West Virginia", "Wisconsin", "Wyoming"}, +-- extras = {"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"} + extras = {"Slender Dragon", "Abalamara"} + +function no_dup(sequence s) + s = sort(s) + for i=length(s) to 2 by -1 do + if s[i]=s[i-1] then + s[i] = s[$] + s = s[1..$-1] + end if + end for + return s +end function + +procedure play(sequence s) + s = no_dup(s) + destroy_dict(1) -- empty dict + for i=1 to length(s)-1 do + for j=i+1 to length(s) do + string key = trim(sort(lower(s[i]&s[j]))) + object data = getd(key) + if data=0 then + putd(key,{{i,j}}) + else + for k=1 to length(data) do + integer {m,n} = data[k] + if m!=i and m!=j and n!=i and n!=j then + ?{s[i],s[j],"<==>",s[m],s[n]} + end if + end for + putd(key,append(data,{i,j})) + end if + end for + end for +end procedure +play(states) +?"===" +play(states&extras) diff --git a/Task/State-name-puzzle/REXX/state-name-puzzle.rexx b/Task/State-name-puzzle/REXX/state-name-puzzle.rexx index 7014d287f7..2147e04ae9 100644 --- a/Task/State-name-puzzle/REXX/state-name-puzzle.rexx +++ b/Task/State-name-puzzle/REXX/state-name-puzzle.rexx @@ -4,68 +4,56 @@ 'Michigan, Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, New Hampshire, New Jersey, New Mexico,', 'New York, North Carolina, North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,', 'South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia, Wisconsin, Wyoming' - parse arg xtra; !=! ',' xtra /*add optional (fictitious) names.*/ -@abcU='ABCDEFGHIJKLMNOPQRSTUVWXYZ'; !=space(!) /*!: the state list, no extra blanks*/ -deads=0; dups=0; L.=0; !orig=!; z=0; @@.= /*initialize some REXX variables. */ - - do de=0 for 2; !=!orig; @.= /*use original state list for each. */ - - do states=0 until !=='' /*parse until the cows come home. */ - parse var ! x ',' !; x=space(x) /*remove all blanks from state name.*/ - if @.x\=='' then do /*was state was already specified? */ - if de then iterate /*don't tell error if doing 2nd pass*/ - dups=dups+1 /*bump the duplicate counter. */ - say 'ignoring the 2nd naming of the state: ' x - iterate - end - @.x=x /*indicate this state name exists. */ - y=space(x,0); upper y; yLen=length(y) /*get upper name with no spaces; Len*/ - - if de then do /*Is the firstt pass? Then process.*/ - do j=1 for yLen /*see if it's a dead─end state name.*/ - _=substr(y,j,1) /* _: is some state name character.*/ - if L._\==1 then iterate /*Count ¬ 1? Then state name is OK.*/ - say 'removing dead─end state [which has the letter ' _"]: " x - deads=deads+1 /*bump number of dead─ends states. */ - iterate states /*go and process another state name.*/ - end /*j*/ - z=z+1 /*bump counter of the state names. */ - #.z=y; ##.z=x /*assign state name; and original. */ - end - else do k=1 for yLen /*inventorize state name's letters. */ - _=substr(y,k,1); L._=L._+1 /*count each letter in state name. */ - end /*k*/ - - end /*states*/ - end /*de*/ - -say; do i=1 for z /*list state names in order given. */ - say right(i,9) ##.i /*show the index number, state name.*/ - end /*i*/ - - say; say z 'state name's(z) "are useable." +@abcU= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; !=space(!) /*!: the state list, no extra blanks*/ +deads=0; dups=0; L.=0; !orig=!; @@.= /*initialize some REXX variables. */ +z=0 /* [↑] elide dend─end (DE) states.*/ + do de=0 for 2; !=!orig /*use original state list for each. */ + @.= + do states=0 by 0 until !=='' /*parse until the cows come home. */ + parse var ! x ',' !; x=space(x) /*remove all blanks from state name.*/ + if @.x\=='' then do /*was state was already specified? */ + if de then iterate /*don't tell error if doing 2nd pass*/ + dups=dups + 1 /*bump the duplicate counter. */ + say 'ignoring the 2nd naming of the state: ' x; iterate + end + @.x=x /*indicate this state name exists. */ + y=space(x,0); upper y; yLen=length(y) /*get upper name with no spaces; Len*/ + if de then do /*Is the firstt pass? Then process.*/ + do j=1 for yLen /*see if it's a dead─end state name.*/ + _=substr(y, j, 1) /* _: is some state name character.*/ + if L._ \== 1 then iterate /*Count ¬ 1? Then state name is OK.*/ + say 'removing dead─end state [which has the letter ' _"]: " x + deads=deads + 1 /*bump number of dead─ends states. */ + iterate states /*go and process another state name.*/ + end /*j*/ + z=z+1 /*bump counter of the state names. */ + #.z=y; ##.z=x /*assign state name; also original.*/ + end + else do k=1 for yLen /*inventorize letters of state name.*/ + _=substr(y,k,1); L._=L._ + 1 /*count each letter in state name. */ + end /*k*/ + end /*states*/ /*the index STATES isn't incremented*/ + end /*de*/ +call list /*list state names in order given. */ + say z 'state name's(z) "are useable." if dups \==0 then say dups 'duplicate of a state's(dups) 'ignored.' if deads\==0 then say deads 'dead─end state's(deads) 'deleted.' -say sols=0 /*number of solutions found (so far)*/ - - do j=1 for z /*◄───────────────────────────────────────────────────────────────┐ */ - /*look for mix and match states. │ */ - do k=j+1 to z /* ◄─── state K, state J ►───────┘ */ +say /*[↑] look for mix and match states*/ + do j=1 for z /* ◄──────────────────────────────────────────────────────────┐ */ + do k=j+1 to z /* ◄─── state K, state J ►─────┘ */ if #.j<<#.k then JK=#.j || #.k /*is the state in the proper order? */ else JK=#.k || #.j /*No, then use the new state name. */ - - do m=1 for z; if m==j | m==k then iterate /*no state overlaps are allowed. */ - if verify(#.m,jk)\==0 then iterate /*is this state name even possible? */ - nJK=elider(JK,#.m) /*a new JK, after eliding #.m chars.*/ - + do m=1 for z; if m==j | m==k then iterate /*no state overlaps are allowed. */ + if verify(#.m, jk) \== 0 then iterate /*is this state name even possible? */ + nJK=elider(JK, #.m) /*a new JK, after eliding #.m chars.*/ do n=m+1 to z; if n==j | n==k then iterate /*no overlaps are allowed. */ - if verify(#.n,nJK)\==0 then iterate /*is it possible? */ - if elider(nJK,#.n)\=='' then iterate /*any leftovers letters? */ + if verify(#.n, nJK) \== 0 then iterate /*is it possible? */ + if elider(nJK, #.n) \== '' then iterate /*any leftovers letters? */ if #.m<<#.n then MN=#.m || #.n /*is it in the proper order?*/ else MN=#.n || #.m /*we found a new state name.*/ - if @@.JK.MN\=='' | @@.MN.JK\=="" then iterate /*was it done before? */ + if @@.JK.MN\=='' | @@.MN.JK\=="" then iterate /*was it done before? */ say 'found: ' ##.j',' ##.k " ───► " ##.m',' ##.n @@.JK.MN=1 /*indicate this solution as being found*/ sols=sols+1 /*bump the number of solutions found. */ @@ -74,13 +62,15 @@ sols=0 /*number of solutions found end /*k*/ end /*j*/ say /*show a blank line for easier reading.*/ -if sols==0 then sols='No' /*use mucher gooder (sic) Englishings. */ -say sols 'solution's(sols) "found." /*display the number of solutions found*/ +if sols==0 then sols= 'No' /*use mucher gooder (sic) Englishings. */ +say sols 'solution's(sols) "found." /*display the number of solutions found*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ elider: parse arg hay,pins /*remove letters (pins) from haystack. */ - do e=1 for length(pins); p=pos(substr(pins,e,1), hay) - if p==0 then iterate ; hay=overlay(' ',hay,p) + do e=1 for length(pins); p=pos( substr( pins, e, 1), hay) + if p==0 then iterate ; hay=overlay(' ', hay, p) end /*e*/ /* [↑] remove a letter from haystack. */ - return space(hay,0) /*remove blanks from the haystack. */ + return space(hay, 0) /*remove blanks from the haystack. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ +list: say; do i=1 for z; say right(i, 9) ##.i; end; say; return +s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) /*pluralizer.*/ diff --git a/Task/State-name-puzzle/Zkl/state-name-puzzle.zkl b/Task/State-name-puzzle/Zkl/state-name-puzzle.zkl new file mode 100644 index 0000000000..db082d4435 --- /dev/null +++ b/Task/State-name-puzzle/Zkl/state-name-puzzle.zkl @@ -0,0 +1,26 @@ +#<<< // here doc +states:=("Alabama, Alaska, Arizona, Arkansas, + California, Colorado, Connecticut, Delaware, Florida, + Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, + Kentucky, Louisiana, Maine, Maryland, Massachusetts, + Michigan, Minnesota, Mississippi, Missouri, Montana, + Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, + New York, North Carolina, North Dakota, Ohio, Oklahoma, + Oregon, Pennsylvania, Rhode Island, South Carolina, + South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, + Washington, West Virginia, Wisconsin, Wyoming" + /* Uncomment the next line for the fake states. */ + # ",New Kory, Wen Kory, York New, Kory New, New Kory" +#<<< +).split(",").apply("strip"); + +smap:=Dictionary(); +Utils.Helpers.pickNFrom(2,states).apply2('wrap(ss){ // 1225 combinations + key:=(ss.concat()).toLower().sort()-" "; + smap[key]=smap.find(key,List()).append(ss.concat(" + ")); +}); + +foreach pairs in (smap.values){ // 1224 keys +// pairs=Utils.Helpers.listUnique(pairs); // eliminate dups + if(pairs.len()>1) + println(pairs.concat(" = ")) } diff --git a/Task/Statistics-Basic/Haskell/statistics-basic.hs b/Task/Statistics-Basic/Haskell/statistics-basic.hs index 326bc0ea17..283349bde9 100644 --- a/Task/Statistics-Basic/Haskell/statistics-basic.hs +++ b/Task/Statistics-Basic/Haskell/statistics-basic.hs @@ -1,48 +1,69 @@ -{-# LANGUAGE BangPatterns #-} - -import Data.Foldable -import System.Random +import Data.Foldable (foldl') --' +import System.Random (randomRs, newStdGen) +import Control.Monad (zipWithM_) import System.Environment (getArgs) -intervals :: [(Double,Double)] -intervals = map conv [0..9] - where xs = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0] - conv s = let { [h,l] = take 2 $ drop s xs } in (h,l) +intervals :: [(Double, Double)] +intervals = map conv [0 .. 9] + where + xs = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] + conv s = + let [h, l] = take 2 $ drop s xs + in (h, l) count :: [Double] -> [Int] -count rands = map (\iv -> foldl' (loop iv) 0 rands) intervals - where loop :: (Double,Double) -> Int -> Double -> Int - loop (lo,hi) n x | lo <= x && x < hi = n+1 - | otherwise = n - -- ^ fuses length and filter within (lo,hi) +count rands = map (\iv -> foldl'' (loop iv) 0 rands) intervals + where + loop :: (Double, Double) -> Int -> Double -> Int + loop (lo, hi) n x + | lo <= x && x < hi = n + 1 + | otherwise = n -data Pair a b = Pair !a !b +-- ^ fuses length and filter within (lo,hi) +data Pair a b = + Pair !a + !b -- accumulate sum and length in one fold sumLen :: [Double] -> Pair Double Double -sumLen = fion2 . foldl' (\(Pair s l) x -> Pair (s+x) (l+1)) (Pair 0.0 0) - where fion2 :: Pair Double Int -> Pair Double Double - fion2 (Pair s l) = Pair s (fromIntegral l) +sumLen = fion2 . foldl'' (\(Pair s l) x -> Pair (s + x) (l + 1)) (Pair 0.0 0) + where + fion2 :: Pair Double Int -> Pair Double Double + fion2 (Pair s l) = Pair s (fromIntegral l) -- safe division on pairs divl :: Pair Double Double -> Double divl (Pair _ 0.0) = 0.0 -divl (Pair s l) = s / l +divl (Pair s l) = s / l -- sumLen and divl are separate for stddev below mean :: [Double] -> Double mean = divl . sumLen stddev :: [Double] -> Double -stddev xs = sqrt $ foldl' (\s x -> s+(x-m)^2) 0 xs / l - where p@(Pair s l) = sumLen xs - m = divl p +stddev xs = sqrt $ foldl'' (\s x -> s + (x - m) ^ 2) 0 xs / l + where + p@(Pair s l) = sumLen xs + m = divl p -main = do nr <- read.head <$> getArgs - rands <- take nr . randomRs (0.0,1.0) <$> newStdGen - putStrLn $ "The mean is " ++ show (mean rands) ++ " !" - putStrLn $ "The standard deviation is " ++ show (stddev rands) ++ " !" - zipWithM_ (\iv fq -> putStrLn $ ivstr iv ++ ": " ++ fqstr fq) intervals (count rands) - where - fqstr i = replicate (if i > 50 then div i (div i 50) else i) '*' - ivstr (lo,hi) = show lo ++ " - " ++ show hi +main = do + nr <- read . head <$> getArgs + -- or in code, e.g. let nr = 1000 + rands <- take nr . randomRs (0.0, 1.0) <$> newStdGen + putStrLn $ "The mean is " ++ show (mean rands) ++ " !" + putStrLn $ "The standard deviation is " ++ show (stddev rands) ++ " !" + zipWithM_ + (\iv fq -> putStrLn $ ivstr iv ++ ": " ++ fqstr fq) + intervals + (count rands) + where + fqstr i = + replicate + (if i > 50 + then div i (div i 50) + else i) + '*' + ivstr (lo, hi) = show lo ++ " - " ++ show hi + +-- To avoid Wiki formatting issue +foldl'' = foldl' diff --git a/Task/Statistics-Basic/Kotlin/statistics-basic.kotlin b/Task/Statistics-Basic/Kotlin/statistics-basic.kotlin new file mode 100644 index 0000000000..4e004c92f3 --- /dev/null +++ b/Task/Statistics-Basic/Kotlin/statistics-basic.kotlin @@ -0,0 +1,49 @@ +// version 1.1.2 + +val rand = java.util.Random() + +fun basicStats(sampleSize: Int) { + if (sampleSize < 1) return + val r = DoubleArray(sampleSize) + val h = IntArray(10) // all zero by default + /* + Generate 'sampleSize' random numbers in the interval [0, 1) + and calculate in which box they will fall when drawing the histogram + */ + for (i in 0 until sampleSize) { + r[i] = rand.nextDouble() + h[(r[i] * 10).toInt()]++ + } + + // adjust one of the h[] values if necessary to ensure they sum to sampleSize + val adj = sampleSize - h.sum() + if (adj != 0) { + for (i in 0..9) { + h[i] += adj + if (h[i] >= 0) break + h[i] -= adj + } + } + + val mean = r.average() + val sd = Math.sqrt(r.map { (it - mean) * (it - mean) }.average()) + + // Draw a histogram of the data with interval 0.1 + var numStars: Int + // If sample size > 500 then normalize histogram to 500 + val scale = if (sampleSize <= 500) 1.0 else 500.0 / sampleSize + println("Sample size $sampleSize\n") + println(" Mean ${"%1.6f".format(mean)} SD ${"%1.6f".format(sd)}\n") + for (i in 0..9) { + print(" %1.2f : ".format(i / 10.0)) + print("%5d ".format(h[i])) + numStars = (h[i] * scale + 0.5).toInt() + println("*".repeat(numStars)) + } + println() +} + +fun main(args: Array) { + val sampleSizes = intArrayOf(100, 1_000, 10_000, 100_000) + for (sampleSize in sampleSizes) basicStats(sampleSize) +} diff --git a/Task/Statistics-Basic/Perl-6/statistics-basic.pl6 b/Task/Statistics-Basic/Perl-6/statistics-basic.pl6 index a4efa94412..3ad93190b2 100644 --- a/Task/Statistics-Basic/Perl-6/statistics-basic.pl6 +++ b/Task/Statistics-Basic/Perl-6/statistics-basic.pl6 @@ -5,6 +5,6 @@ for 100, 1_000, 10_000 -> $N { printf "stddev: %f\n", sqrt $mean**2 R- $N R/ [+] @data »**» 2; printf "%.1f %s\n", .key, '=' x (500 * .value.elems / $N) - for sort *.key, @data.classify: (10 * *).Int / 10; + for sort @data.classify: (10 * *).Int / 10; &say; } diff --git a/Task/Statistics-Basic/Phix/statistics-basic.phix b/Task/Statistics-Basic/Phix/statistics-basic.phix new file mode 100644 index 0000000000..54f78b936e --- /dev/null +++ b/Task/Statistics-Basic/Phix/statistics-basic.phix @@ -0,0 +1,34 @@ +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) + + 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 + +for n=2 to 5 do + display_statistics(generate_statistics(power(10,n+(n=5)))) +end for diff --git a/Task/Statistics-Basic/REXX/statistics-basic.rexx b/Task/Statistics-Basic/REXX/statistics-basic.rexx index fed60dfbf3..bbfd84237f 100644 --- a/Task/Statistics-Basic/REXX/statistics-basic.rexx +++ b/Task/Statistics-Basic/REXX/statistics-basic.rexx @@ -11,12 +11,11 @@ if datatype(seed,'W') then call random ,,seed /*allow a seed for the RANDO #._=#._+1 /* ··· and bump its count. */ end /*j*/ - do k=0 for 10 /*show a histogram of the bins. */ + do k=0 for 10; kp=k+1 /*show a histogram of the bins. */ lr='0.'k ; if k==0 then lr="0 " /*adjust for the low range. */ - hr='0.'||(k+1); if k==9 then hr="1 " /* " " " high range. */ - range=lr"──►"hr' ' /*construct the range. */ + hr='0.'kp ; if k==9 then hr="1 " /* " " " high range. */ barPC=right(strip(left(format(100*#.k/size, , 2), 5)) ,5) /*compute the %. */ - say range barPC copies('─', format(barPC*1, , 0)) /*display histogram*/ + say lr"──►"hr' ' barPC copies('─', format(barPC*1, , 0)) /*display histogram*/ end /*k*/ say say 'sample size = ' size; say diff --git a/Task/Statistics-Basic/Stata/statistics-basic.stata b/Task/Statistics-Basic/Stata/statistics-basic.stata new file mode 100644 index 0000000000..2d346a2de3 --- /dev/null +++ b/Task/Statistics-Basic/Stata/statistics-basic.stata @@ -0,0 +1,10 @@ +. clear all +. set obs 100000 +number of observations (_N) was 0, now 100,000 +. gen x=runiform() +. summarize x + + Variable | Obs Mean Std. Dev. Min Max +-------------+--------------------------------------------------------- + x | 100,000 .4991874 .2885253 1.18e-06 .9999939 +. hist x diff --git a/Task/Statistics-Basic/Zkl/statistics-basic-1.zkl b/Task/Statistics-Basic/Zkl/statistics-basic-1.zkl new file mode 100644 index 0000000000..a02ff1b4ea --- /dev/null +++ b/Task/Statistics-Basic/Zkl/statistics-basic-1.zkl @@ -0,0 +1,4 @@ +fcn mean(ns) { ns.sum(0.0)/ns.len() } +fcn stdDev(ns){ + m:=mean(ns); (ns.reduce('wrap(p,n){ x:=(n-m); p+x*x },0.0)/ns.len()).sqrt() +} diff --git a/Task/Statistics-Basic/Zkl/statistics-basic-2.zkl b/Task/Statistics-Basic/Zkl/statistics-basic-2.zkl new file mode 100644 index 0000000000..5d36f4418c --- /dev/null +++ b/Task/Statistics-Basic/Zkl/statistics-basic-2.zkl @@ -0,0 +1,9 @@ +reg ns; +foreach n in (T(100,1000,10000)){ + ns=(0).pump(n,List,(0.0).random.fp(1.0)); + println("N:%,6d mean:%.5f std dev:%.5f".fmt(n,mean(ns),stdDev(ns))); +} +foreach r in ([0.0 .. 0.9, 0.1]){ // using the last data set (10000 randoms) + n:=ns.filter('wrap(x){ r<=x<(r+0.1) }).len(); + println("%.2f..%.2f:%4d%s".fmt(r,r+0.1,n,"*"*(n/20))); +} diff --git a/Task/Statistics-Basic/Zkl/statistics-basic-3.zkl b/Task/Statistics-Basic/Zkl/statistics-basic-3.zkl new file mode 100644 index 0000000000..450fddffe1 --- /dev/null +++ b/Task/Statistics-Basic/Zkl/statistics-basic-3.zkl @@ -0,0 +1,13 @@ +var pipe=Thread.Pipe(); // used to connect the two threads +fcn{ while(1){ pipe.write((0.0).random(1.0)) } }.launch(); // generator +fcn{ // consumer/calculator + N:=0; M:=SD:=sum:=ssum:=0.0; + while(1){ + x:=pipe.read(); N+=1; sum+=x; ssum+=x*x; + M=sum/N; SD=(ssum/N - M*M).sqrt(); + if(0==N%100000) + println("N:%,10d mean:%.5f std dev:%.5f".fmt(N,M,SD)); + } +}.launch(); + +Atomic.sleep(60*60); // wait because exiting the VM kills the threads diff --git a/Task/Stem-and-leaf-plot/jq/stem-and-leaf-plot-1.jq b/Task/Stem-and-leaf-plot/Jq/stem-and-leaf-plot-1.jq similarity index 100% rename from Task/Stem-and-leaf-plot/jq/stem-and-leaf-plot-1.jq rename to Task/Stem-and-leaf-plot/Jq/stem-and-leaf-plot-1.jq diff --git a/Task/Stem-and-leaf-plot/jq/stem-and-leaf-plot-2.jq b/Task/Stem-and-leaf-plot/Jq/stem-and-leaf-plot-2.jq similarity index 100% rename from Task/Stem-and-leaf-plot/jq/stem-and-leaf-plot-2.jq rename to Task/Stem-and-leaf-plot/Jq/stem-and-leaf-plot-2.jq diff --git a/Task/Stem-and-leaf-plot/jq/stem-and-leaf-plot-3.jq b/Task/Stem-and-leaf-plot/Jq/stem-and-leaf-plot-3.jq similarity index 100% rename from Task/Stem-and-leaf-plot/jq/stem-and-leaf-plot-3.jq rename to Task/Stem-and-leaf-plot/Jq/stem-and-leaf-plot-3.jq diff --git a/Task/Stem-and-leaf-plot/Kotlin/stem-and-leaf-plot.kotlin b/Task/Stem-and-leaf-plot/Kotlin/stem-and-leaf-plot.kotlin new file mode 100644 index 0000000000..d335ee90b8 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Kotlin/stem-and-leaf-plot.kotlin @@ -0,0 +1,27 @@ +// version 1.1.2 + +fun leafPlot(x: IntArray) { + x.sort() + var i = x[0] / 10 - 1 + for (j in 0 until x.size) { + val d = x[j] / 10 + while (d > i) print("%s%3d |".format(if (j != 0) "\n" else "", ++i)) + print(" ${x[j] % 10}") + } + println() +} + +fun main(args: Array) { + val data = intArrayOf( + 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 + ) + leafPlot(data) +} diff --git a/Task/Stem-and-leaf-plot/REXX/stem-and-leaf-plot-1.rexx b/Task/Stem-and-leaf-plot/REXX/stem-and-leaf-plot-1.rexx index 7cde4bb0c4..481b81a605 100644 --- a/Task/Stem-and-leaf-plot/REXX/stem-and-leaf-plot-1.rexx +++ b/Task/Stem-and-leaf-plot/REXX/stem-and-leaf-plot-1.rexx @@ -1,5 +1,5 @@ /*REXX program displays a stem and leaf plot of any non-negative numbers [can include 0]*/ -parse arg @ /* [↑] Not specified? Then use default*/ +parse arg @ /* [↓] Not specified? Then use default*/ if @='' then @=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, diff --git a/Task/Stem-and-leaf-plot/Stata/stem-and-leaf-plot.stata b/Task/Stem-and-leaf-plot/Stata/stem-and-leaf-plot.stata new file mode 100644 index 0000000000..cde86ca50e --- /dev/null +++ b/Task/Stem-and-leaf-plot/Stata/stem-and-leaf-plot.stata @@ -0,0 +1,30 @@ +. clear all +. input x +12 +127 +28 +... +31 +116 +146 +end + +. stem x + +Stem-and-leaf plot for x + + 0* | 77 + 1* | 2388 + 2* | 357777778899 + 3* | 011112345677789 + 4* | 001222233344456788 + 5* | 23788 + 6* | 138 + 7* | 1 + 8* | + 9* | 69 + 10* | 4555567999 + 11* | 13333444555666677778899 + 12* | 00112234445556777788 + 13* | 1239 + 14* | 16 diff --git a/Task/Stem-and-leaf-plot/Zkl/stem-and-leaf-plot.zkl b/Task/Stem-and-leaf-plot/Zkl/stem-and-leaf-plot.zkl new file mode 100644 index 0000000000..acf7df6c46 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Zkl/stem-and-leaf-plot.zkl @@ -0,0 +1,23 @@ +fcn leaf_plot(xs){ + xs=xs.sort(); + i := xs[0] / 10 - 1; + foreach j in (xs.len()){ + d := xs[j] / 10; + while (d > i){ print("%s%3d |".fmt(j and "\n" or "", i+=1)); } + print(" %d".fmt(xs[j] % 10)); + } + println(); +} + +data := T( + 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 ); + +leaf_plot(data); diff --git a/Task/Stern-Brocot-sequence/Common-Lisp/stern-brocot-sequence.lisp b/Task/Stern-Brocot-sequence/Common-Lisp/stern-brocot-sequence.lisp new file mode 100644 index 0000000000..777ed49cd4 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Common-Lisp/stern-brocot-sequence.lisp @@ -0,0 +1,56 @@ +(defun stern-brocot (numbers) + (declare ((or null (vector integer)) numbers)) + (cond ((null numbers) + (setf numbers (make-array 2 :element-type 'integer :adjustable t :fill-pointer t + :initial-element 1))) + ((zerop (length numbers)) + (vector-push-extend 1 numbers) + (vector-push-extend 1 numbers)) + (t + (assert (evenp (length numbers))) + (let* ((considered-index (/ (length numbers) 2)) + (considered (aref numbers considered-index)) + (precedent (aref numbers (1- considered-index)))) + (vector-push-extend (+ considered precedent) numbers) + (vector-push-extend considered numbers)))) + numbers) + +(defun first-15 () + (loop for input = nil then seq + for seq = (stern-brocot input) + while (< (length seq) 15) + finally (format t "First 15: ~{~A~^ ~}~%" (coerce (subseq seq 0 15) 'list)))) + +(defun first-1-to-10 () + (loop with seq = (stern-brocot nil) + for i from 1 to 10 + for index = (loop with start = 0 + for pos = (position i seq :start start) + until pos + do (setf start (length seq) + seq (stern-brocot seq)) + finally (return (1+ pos))) + do (format t "First ~D at ~D~%" i index))) + +(defun first-100 () + (loop for input = nil then seq + for start = (length input) + for seq = (stern-brocot input) + for pos = (position 100 seq :start start) + until pos + finally (format t "First 100 at ~D~%" (1+ pos)))) + +(defun check-gcd () + (loop for input = nil then seq + for seq = (stern-brocot input) + while (< (length seq) 1000) + finally (if (loop for i from 0 below 999 + always (= 1 (gcd (aref seq i) (aref seq (1+ i))))) + (write-line "Correct. The GCDs of all the two consecutive numbers are 1.") + (write-line "Wrong.")))) + +(defun main () + (first-15) + (first-1-to-10) + (first-100) + (check-gcd)) diff --git a/Task/Stern-Brocot-sequence/Haskell/stern-brocot-sequence.hs b/Task/Stern-Brocot-sequence/Haskell/stern-brocot-sequence.hs index d1ba54f1ba..bef5f6d4a9 100644 --- a/Task/Stern-Brocot-sequence/Haskell/stern-brocot-sequence.hs +++ b/Task/Stern-Brocot-sequence/Haskell/stern-brocot-sequence.hs @@ -1,9 +1,14 @@ -import Data.List +import Data.List (elemIndex) -sb = 1:1: f (tail sb) sb where - f (a:aa) (b:bb) = a+b : a : f aa bb +sb :: [Int] +sb = 1 : 1 : f (tail sb) sb + where + f (a:aa) (b:bb) = a + b : a : f aa bb +main :: IO () main = do - print $ take 15 sb - print [(i,1 + (\(Just i)->i) (elemIndex i sb)) | i <- [1..10]++[100]] - print $ all (\(a,b)->1 == gcd a b) $ take 1000 $ zip sb (tail sb) + print $ take 15 sb + print + [ (i, 1 + (\(Just i) -> i) (elemIndex i sb)) + | i <- [1 .. 10] ++ [100] ] + print $ all (\(a, b) -> 1 == gcd a b) $ take 1000 $ zip sb (tail sb) diff --git a/Task/Stern-Brocot-sequence/jq/stern-brocot-sequence-1.jq b/Task/Stern-Brocot-sequence/Jq/stern-brocot-sequence-1.jq similarity index 100% rename from Task/Stern-Brocot-sequence/jq/stern-brocot-sequence-1.jq rename to Task/Stern-Brocot-sequence/Jq/stern-brocot-sequence-1.jq diff --git a/Task/Stern-Brocot-sequence/jq/stern-brocot-sequence-2.jq b/Task/Stern-Brocot-sequence/Jq/stern-brocot-sequence-2.jq similarity index 100% rename from Task/Stern-Brocot-sequence/jq/stern-brocot-sequence-2.jq rename to Task/Stern-Brocot-sequence/Jq/stern-brocot-sequence-2.jq diff --git a/Task/Stern-Brocot-sequence/jq/stern-brocot-sequence-3.jq b/Task/Stern-Brocot-sequence/Jq/stern-brocot-sequence-3.jq similarity index 100% rename from Task/Stern-Brocot-sequence/jq/stern-brocot-sequence-3.jq rename to Task/Stern-Brocot-sequence/Jq/stern-brocot-sequence-3.jq diff --git a/Task/Stern-Brocot-sequence/jq/stern-brocot-sequence-4.jq b/Task/Stern-Brocot-sequence/Jq/stern-brocot-sequence-4.jq similarity index 100% rename from Task/Stern-Brocot-sequence/jq/stern-brocot-sequence-4.jq rename to Task/Stern-Brocot-sequence/Jq/stern-brocot-sequence-4.jq diff --git a/Task/Stern-Brocot-sequence/Julia/stern-brocot-sequence.julia b/Task/Stern-Brocot-sequence/Julia/stern-brocot-sequence.julia new file mode 100644 index 0000000000..bdf1728f9f --- /dev/null +++ b/Task/Stern-Brocot-sequence/Julia/stern-brocot-sequence.julia @@ -0,0 +1,24 @@ +function sternbrocot(f::Function=(x) -> length(x) ≥ 20)::Vector{Int} + rst = Int[1, 1] + i = 3 + while !f(rst) + append!(rst, Int[rst[i-1] + rst[i-2], rst[i-2]]) + i += 1 + end + return rst +end + +println("First 15 elements of Stern-Brocot series:\n", sternbrocot(x -> length(x) ≥ 15)[1:15], "\n") + +for i in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100) + occurr = findfirst(x -> x == i, sternbrocot(x -> i ∈ x)) + @printf("Index of first occurrence of %3i in the series: %4i\n", i, occurr) +end + +print("\nAssertion: the greatest common divisor of all the two\nconsecutive members of the series up to the 1000th member, is always one: ") +sb = sternbrocot(x -> length(x) > 1000) +if all(gcd(prev, this) == 1 for (prev, this) in zip(sb[1:1000], sb[2:1000])) + println("Confirmed.") +else + println("Rejected.") +end diff --git a/Task/Stern-Brocot-sequence/Kotlin/stern-brocot-sequence.kotlin b/Task/Stern-Brocot-sequence/Kotlin/stern-brocot-sequence.kotlin new file mode 100644 index 0000000000..bee0a24999 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Kotlin/stern-brocot-sequence.kotlin @@ -0,0 +1,64 @@ +// version 1.1.0 + +val sbs = mutableListOf(1, 1) + +fun sternBrocot(n: Int, fromStart: Boolean = true) { + if (n < 4 || (n % 2 != 0)) throw IllegalArgumentException("n must be >= 4 and even") + var consider = if (fromStart) 1 else n / 2 - 1 + while (true) { + val sum = sbs[consider] + sbs[consider - 1] + sbs.add(sum) + sbs.add(sbs[consider]) + if (sbs.size == n) break + consider++ + } +} + +fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) + +fun main(args: Array) { + var n = 16 // needs to be even to ensure 'considered' number is added + println("First 15 members of the Stern-Brocot sequence") + sternBrocot(n) + println(sbs.take(15)) + + val firstFind = IntArray(11) // all zero by default + firstFind[0] = -1 // needs to be non-zero for subsequent test + for ((i, v) in sbs.withIndex()) + if (v <= 10 && firstFind[v] == 0) firstFind[v] = i + 1 + loop@ while (true) { + n += 2 + sternBrocot(n, false) + val vv = sbs.takeLast(2) + var m = n - 1 + for (v in vv) { + if (v <= 10 && firstFind[v] == 0) firstFind[v] = m + if (firstFind.all { it != 0 }) break@loop + m++ + } + } + println("\nThe numbers 1 to 10 first appear at the following indices:") + for (i in 1..10) println("${"%2d".format(i)} -> ${firstFind[i]}") + + print("\n100 first appears at index ") + while (true) { + n += 2 + sternBrocot(n, false) + val vv = sbs.takeLast(2) + if (vv[0] == 100) { + println(n - 1); break + } + if (vv[1] == 100) { + println(n); break + } + } + + print("\nThe GCDs of each pair of the series up to the 1000th member are ") + for (p in 0..998 step 2) { + if (gcd(sbs[p], sbs[p + 1]) != 1) { + println("not all one") + return + } + } + println("all one") +} diff --git a/Task/Stern-Brocot-sequence/Perl-6/stern-brocot-sequence.pl6 b/Task/Stern-Brocot-sequence/Perl-6/stern-brocot-sequence.pl6 index 0823bc6893..eb3e9a075c 100644 --- a/Task/Stern-Brocot-sequence/Perl-6/stern-brocot-sequence.pl6 +++ b/Task/Stern-Brocot-sequence/Perl-6/stern-brocot-sequence.pl6 @@ -1,12 +1,11 @@ -constant Stern-Brocot = flat - 1, 1, -> *@a { - @a[$_ - 1] + @a[$_], @a[$_] given ++$; - } ... *; - -say Stern-Brocot[^15]; - -for 1 .. 10, 100 -> $ix { - say "first occurrence of $ix is at index : ", 1 + Stern-Brocot.first($ix, :k); +constant @Stern-Brocot = 1, 1, { + |(@_[$_ - 1] + @_[$_], @_[$_]) given ++$ +} ... *; +  +say @Stern-Brocot[^15]; +  +for (flat 1..10, 100) -> $ix { + say "first occurrence of $ix is at index : ", 1 + @Stern-Brocot.first($ix, :k); } - -say so 1 == all map ^1000: { [gcd] Stern-Brocot[$_, $_ + 1] } +  +say so 1 == all map ^1000: { [gcd] @Stern-Brocot[$_, $_ + 1] } diff --git a/Task/Stern-Brocot-sequence/Phix/stern-brocot-sequence.phix b/Task/Stern-Brocot-sequence/Phix/stern-brocot-sequence.phix new file mode 100644 index 0000000000..23ba2bbcbc --- /dev/null +++ b/Task/Stern-Brocot-sequence/Phix/stern-brocot-sequence.phix @@ -0,0 +1,41 @@ +sequence sb = {1,1} +integer c = 2 + +function stern_brocot(integer n) + while length(sb) map(stern_brocot()).join(' ').say; +say 15.of(stern_brocot()).join(' ') # Show the (1-based) index of where the numbers 1-to-10 first appears # in the sequence, and where the number 100 first appears in the sequence. -[(1..10)..., 100].each { |i| - var index = 1; - var generator = stern_brocot(); - while (generator() != i) { - ++index; +for i (1..10, 100) { + var index = 1 + var generator = stern_brocot() + while (generator() != i) { + ++index } - say "First occurrence of #{i} is at index #{index}"; + say "First occurrence of #{i} is at index #{index}" } # Check that the greatest common divisor of all the two consecutive # members of the series up to the 1000th member, is always one. -var generator = stern_brocot(); -var (a, b) = (generator(), generator()); +var generator = stern_brocot() +var (a, b) = (generator(), generator()) { - assert_eq(Math.gcd(a, b), 1); - a = b; - b = generator(); -} * 1000; + assert_eq(gcd(a, b), 1) + a = b + b = generator() +} * 1000 -say "All GCD's are 1"; +say "All GCD's are 1" diff --git a/Task/Stern-Brocot-sequence/Zkl/stern-brocot-sequence.zkl b/Task/Stern-Brocot-sequence/Zkl/stern-brocot-sequence.zkl new file mode 100644 index 0000000000..761ddb3022 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Zkl/stern-brocot-sequence.zkl @@ -0,0 +1,11 @@ +fcn SB // Stern-Brocot sequence factory --> Walker + { Walker(fcn(sb,n){ a,b:=sb; sb.append(a+b,b); sb.del(0); a }.fp(L(1,1))) } + +SB().walk(15).println(); + +[1..10].zipWith('wrap(n){ [1..].zip(SB()) + .filter(1,fcn(n,sb){ n==sb[1] }.fp(n)) }) + .walk().println(); +[1..].zip(SB()).filter1(fcn(sb){ 100==sb[1] }).println(); + +sb:=SB(); do(500){ if(sb.next().gcd(sb.next())!=1) println("Oops") } diff --git a/Task/String-append/Elena/string-append.elena b/Task/String-append/Elena/string-append.elena index ceb3efa7bd..c30f2a00ab 100644 --- a/Task/String-append/Elena/string-append.elena +++ b/Task/String-append/Elena/string-append.elena @@ -1,9 +1,9 @@ -#import system. +import extensions. -#symbol program = +program = [ - #var s := String new:"Hello". - s += " World". + var s := String new:"Hello". + s append:" World". - console writeLine:s. + console writeLine:s; readChar. ]. diff --git a/Task/String-append/Gambas/string-append.gambas b/Task/String-append/Gambas/string-append.gambas new file mode 100644 index 0000000000..930771cc24 --- /dev/null +++ b/Task/String-append/Gambas/string-append.gambas @@ -0,0 +1,7 @@ +Public Sub Main() +Dim sString As String = "Hello " + +sString &= "World!" +Print sString + +End diff --git a/Task/String-append/Gosu/string-append.gosu b/Task/String-append/Gosu/string-append.gosu new file mode 100644 index 0000000000..405dc2d035 --- /dev/null +++ b/Task/String-append/Gosu/string-append.gosu @@ -0,0 +1,14 @@ +// Example 1 +var s = "a" +s += "b" +s += "c" +print(s) + +// Example 2 +print("a" + "b" + "c") + +// Example 3 +var a = "a" +var b = "b" +var c = "c" +print("${a}${b}${c}") diff --git a/Task/String-append/Groovy/string-append.groovy b/Task/String-append/Groovy/string-append.groovy new file mode 100644 index 0000000000..cc143222f7 --- /dev/null +++ b/Task/String-append/Groovy/string-append.groovy @@ -0,0 +1,8 @@ +class Append{ +static void main(String[] args){ +def c="Hello "; +def d="world"; +def e=c+d; +println(e); +} +} diff --git a/Task/String-append/jq/string-append-1.jq b/Task/String-append/Jq/string-append-1.jq similarity index 100% rename from Task/String-append/jq/string-append-1.jq rename to Task/String-append/Jq/string-append-1.jq diff --git a/Task/String-append/jq/string-append-2.jq b/Task/String-append/Jq/string-append-2.jq similarity index 100% rename from Task/String-append/jq/string-append-2.jq rename to Task/String-append/Jq/string-append-2.jq diff --git a/Task/String-append/PlainTeX/string-append.tex b/Task/String-append/PlainTeX/string-append.tex new file mode 100644 index 0000000000..25a529b311 --- /dev/null +++ b/Task/String-append/PlainTeX/string-append.tex @@ -0,0 +1,7 @@ +\def\addtomacro#1#2{\expandafter\def\expandafter#1\expandafter{#1#2}} +\def\foo{Hello} +Initial: \foo + +\addtomacro\foo{ world!} +Appended: \foo +\bye diff --git a/Task/String-append/Rust/string-append.rust b/Task/String-append/Rust/string-append.rust new file mode 100644 index 0000000000..c77c7fc543 --- /dev/null +++ b/Task/String-append/Rust/string-append.rust @@ -0,0 +1,6 @@ +use std::ops::Add; + +fn main(){ + let hello = String::from("Hello world"); + println!("{}", hello.add("!!!!")); +} diff --git a/Task/String-append/Zkl/string-append.zkl b/Task/String-append/Zkl/string-append.zkl new file mode 100644 index 0000000000..84a9410de3 --- /dev/null +++ b/Task/String-append/Zkl/string-append.zkl @@ -0,0 +1,7 @@ +var s="foo"; +s.append("bar"); //-->new string "foobar", var s unchanged +s+="bar"; //-->new string "foobar", var s modifed to new value + +s=Data(Void,"foo"); // byte blob/character blob/text editor buffer +s.append("bar"); // or s+="bar" +s.text; //-->"foobar" diff --git a/Task/String-case/AppleScript/string-case-1.applescript b/Task/String-case/AppleScript/string-case-1.applescript index 09daa5861b..c75e0baeb2 100644 --- a/Task/String-case/AppleScript/string-case-1.applescript +++ b/Task/String-case/AppleScript/string-case-1.applescript @@ -1,54 +1,52 @@ use framework "Foundation" --- toUpperCase :: Text -> Text -on toUpperCase(str) - set ca to current application - ((ca's NSString's stringWithString:(str))'s ¬ - uppercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text -end toUpperCase - --- toLowerCase :: Text -> Text -on toLowerCase(str) - set ca to current application - ((ca's NSString's stringWithString:(str))'s ¬ - lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text -end toLowerCase - --- toCapitalized :: Text -> Text -on toCapitalized(str) - set ca to current application - ((ca's NSString's stringWithString:(str))'s ¬ - capitalizedStringWithLocale:(ca's NSLocale's currentLocale())) as text -end toCapitalized - - --- TEST +-- TEST ----------------------------------------------------------------------- on run - -- testCase :: Handler -> String - script testCase - on lambda(f) - mReturn(f)'s lambda("alphaBETA αβγδΕΖΗΘ") - end lambda - end script + ap({toLower, toTitle, toUpper}, {"alphaBETA αβγδΕΖΗΘ"}) - map(testCase, {toUpperCase, toLowerCase, toCapitalized}) + --> {"alphabeta αβγδεζηθ", "Alphabeta Αβγδεζηθ", "ALPHABETA ΑΒΓΔΕΖΗΘ"} end run --- GENERIC FUNCTIONS --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- toLower :: String -> String +on toLower(str) + set ca to current application + ((ca's NSString's stringWithString:(str))'s ¬ + lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text +end toLower + +-- toTitle :: String -> String +on toTitle(str) + set ca to current application + ((ca's NSString's stringWithString:(str))'s ¬ + capitalizedStringWithLocale:(ca's NSLocale's currentLocale())) as text +end toTitle + +-- toUpper :: String -> String +on toUpper(str) + set ca to current application + ((ca's NSString's stringWithString:(str))'s ¬ + uppercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text +end toUpper + +-- A list of functions applied to a list of arguments +-- (<*> | ap) :: [(a -> b)] -> [a] -> [b] +on ap(fs, xs) + set {nf, nx} to {length of fs, length of xs} + set lst to {} + repeat with i from 1 to nf + tell mReturn(item i of fs) + repeat with j from 1 to nx + set end of lst to |λ|(contents of (item j of xs)) + end repeat + end tell + end repeat + return lst +end ap -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -57,7 +55,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/String-case/AppleScript/string-case-2.applescript b/Task/String-case/AppleScript/string-case-2.applescript index ffedee28bd..49a7a15707 100644 --- a/Task/String-case/AppleScript/string-case-2.applescript +++ b/Task/String-case/AppleScript/string-case-2.applescript @@ -1 +1 @@ -{"ALPHABETA ΑΒΓΔΕΖΗΘ", "alphabeta αβγδεζηθ", "Alphabeta Αβγδεζηθ"} +{"alphabeta αβγδεζηθ", "Alphabeta Αβγδεζηθ", "ALPHABETA ΑΒΓΔΕΖΗΘ"} diff --git a/Task/String-case/BBC-BASIC/string-case.bbc b/Task/String-case/BBC-BASIC/string-case.bbc deleted file mode 100644 index 6ee5644f87..0000000000 --- a/Task/String-case/BBC-BASIC/string-case.bbc +++ /dev/null @@ -1,7 +0,0 @@ - INSTALL @lib$+"STRINGLIB" - - original$ = "alphaBETA" - PRINT "Original: " original$ - PRINT "Lower case: " FN_lower(original$) - PRINT "Upper case: " FN_upper(original$) - PRINT "Title case: " FN_title(original$) diff --git a/Task/String-case/Elena/string-case.elena b/Task/String-case/Elena/string-case.elena index a6e82ccf1f..736c1db70a 100644 --- a/Task/String-case/Elena/string-case.elena +++ b/Task/String-case/Elena/string-case.elena @@ -1,15 +1,15 @@ -#import system. -#import system'culture. +import system'culture. -#symbol program = +program = [ - #var s1 := "alphaBETA". + var s1 := "alphaBETA". // Alternative 1 - console writeLine:(s1::caseLiteralOp lowerCase). - console writeLine:(s1::caseLiteralOp upperCase). + console writeLine(s1~caseLiteralOp lowerCase). + console writeLine(s1~caseLiteralOp upperCase). // Alternative 2 - console writeLine:(s1 toLower &locale:currentLocale). - console writeLine:(s1 toUpper &locale:currentLocale). + console writeLine(s1 toLower locale:currentLocale). + console writeLine(s1 toUpper locale:currentLocale). + console readChar. ]. diff --git a/Task/String-case/Fortran/string-case-3.f b/Task/String-case/Fortran/string-case-3.f new file mode 100644 index 0000000000..7b01455d41 --- /dev/null +++ b/Task/String-case/Fortran/string-case-3.f @@ -0,0 +1,3 @@ + DO I = 1,LEN(TEXT) + TEXT(I:I) = XLATUC(ICHAR(TEXT(I:I))) + END DO diff --git a/Task/String-case/Gambas/string-case.gambas b/Task/String-case/Gambas/string-case.gambas new file mode 100644 index 0000000000..9ed604afe2 --- /dev/null +++ b/Task/String-case/Gambas/string-case.gambas @@ -0,0 +1,7 @@ +Public Sub Main() +Dim sString As String = "alphaBETA " + +Print UCase(sString) +Print LCase(sString) + +End diff --git a/Task/String-case/jq/string-case-1.jq b/Task/String-case/Jq/string-case-1.jq similarity index 100% rename from Task/String-case/jq/string-case-1.jq rename to Task/String-case/Jq/string-case-1.jq diff --git a/Task/String-case/jq/string-case-2.jq b/Task/String-case/Jq/string-case-2.jq similarity index 100% rename from Task/String-case/jq/string-case-2.jq rename to Task/String-case/Jq/string-case-2.jq diff --git a/Task/String-case/Kotlin/string-case.kotlin b/Task/String-case/Kotlin/string-case.kotlin new file mode 100644 index 0000000000..688c54d3c8 --- /dev/null +++ b/Task/String-case/Kotlin/string-case.kotlin @@ -0,0 +1,9 @@ +// 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/Liberty-BASIC/string-case.liberty b/Task/String-case/Liberty-BASIC/string-case.liberty deleted file mode 100644 index da9027da89..0000000000 --- a/Task/String-case/Liberty-BASIC/string-case.liberty +++ /dev/null @@ -1,7 +0,0 @@ -input$ ="alphaBETA" - -print input$ -print upper$( input$) -print lower$( input$) - -end diff --git a/Task/String-case/MIRC-Scripting-Language/string-case.mirc b/Task/String-case/MIRC-Scripting-Language/string-case.mirc new file mode 100644 index 0000000000..d33c884466 --- /dev/null +++ b/Task/String-case/MIRC-Scripting-Language/string-case.mirc @@ -0,0 +1,2 @@ +echo -ag $upper(alphaBETA) +echo -ag $lower(alphaBETA) diff --git a/Task/String-case/Nimrod/string-case.nimrod b/Task/String-case/Nimrod/string-case.nimrod deleted file mode 100644 index b0344519aa..0000000000 --- a/Task/String-case/Nimrod/string-case.nimrod +++ /dev/null @@ -1,7 +0,0 @@ -import strutils - -var s: string = "alphaBETA_123" -echo s," as upper case: ", toUpper(s) -echo s," as lower case: ", toLower(s) -echo s," as Capitalized: ", capitalize(s) -echo s," as normal case: ", normalize(s) # remove underscores, toLower diff --git a/Task/String-case/OxygenBasic/string-case.oxy b/Task/String-case/OxygenBasic/string-case.oxy deleted file mode 100644 index e4c32a7e33..0000000000 --- a/Task/String-case/OxygenBasic/string-case.oxy +++ /dev/null @@ -1,5 +0,0 @@ -string s="alphaBETA" - -print lcase(s) " "+ - ucase(s) " "+ - ucase(left(s,1))+mid(s,2) 'capitalised diff --git a/Task/String-case/Protium/string-case-1.protium b/Task/String-case/Protium/string-case-1.protium deleted file mode 100644 index 0acddb029d..0000000000 --- a/Task/String-case/Protium/string-case-1.protium +++ /dev/null @@ -1,5 +0,0 @@ -<@ ENU$$$LSTPSTLITLIT>UPP| -[<@ SAYELTLST>...] <@ SAYHLPELTLST>...<@ DEFKEYELTLST>__SuperMacro|... -<@ SAY&&&LIT>alphaBETA - - diff --git a/Task/String-case/Protium/string-case-2.protium b/Task/String-case/Protium/string-case-2.protium deleted file mode 100644 index 6f326a75d5..0000000000 --- a/Task/String-case/Protium/string-case-2.protium +++ /dev/null @@ -1,5 +0,0 @@ -<# ENUMERATION LAMBDA LIST PEERSET LITERAL LITERAL>UPP| -[<# SAY ELEMENT LIST>...] <# SAY HELP ELEMENT LIST>...<# DEFINE KEYWORD ELEMENT LIST>__SuperMacro|... -<# SAY SUPERMACRO LITERAL>alphaBETA - - diff --git a/Task/String-case/PureBasic/string-case.purebasic b/Task/String-case/PureBasic/string-case.purebasic deleted file mode 100644 index c9d40658ff..0000000000 --- a/Task/String-case/PureBasic/string-case.purebasic +++ /dev/null @@ -1,3 +0,0 @@ -s$ = "alphaBETA" -upper$ = UCase(s$) ;uppercase -lower$ = LCase(s$) ;lowercase diff --git a/Task/String-case/Ruby/string-case.rb b/Task/String-case/Ruby/string-case-1.rb similarity index 100% rename from Task/String-case/Ruby/string-case.rb rename to Task/String-case/Ruby/string-case-1.rb diff --git a/Task/String-case/Ruby/string-case-2.rb b/Task/String-case/Ruby/string-case-2.rb new file mode 100644 index 0000000000..45b1b41878 --- /dev/null +++ b/Task/String-case/Ruby/string-case-2.rb @@ -0,0 +1 @@ +'ĥåçýджк'.upcase # => "ĤÅÇÝДЖК" diff --git a/Task/String-case/Run-BASIC/string-case.run b/Task/String-case/Run-BASIC/string-case.run deleted file mode 100644 index 623adb7125..0000000000 --- a/Task/String-case/Run-BASIC/string-case.run +++ /dev/null @@ -1,5 +0,0 @@ -a$ ="alphaBETA" - -print a$ '=> alphaBETA -print upper$(a$) '=> ALPHABETA -print lower$(a$) '=> alphabeta diff --git a/Task/String-case/Rust/string-case-1.rust b/Task/String-case/Rust/string-case-1.rust deleted file mode 100644 index 2a88159a46..0000000000 --- a/Task/String-case/Rust/string-case-1.rust +++ /dev/null @@ -1,5 +0,0 @@ -// Rust 0.9 -use std::ascii::StrAsciiExt; - -"alphaBeta".to_ascii_upper(); -"alphaBeta".to_ascii_lower(); diff --git a/Task/String-case/Rust/string-case-2.rust b/Task/String-case/Rust/string-case-2.rust deleted file mode 100644 index 7c714aebd2..0000000000 --- a/Task/String-case/Rust/string-case-2.rust +++ /dev/null @@ -1,5 +0,0 @@ -// Rust 1.0 Alpha -fn main() { - let s = "jalapeño"; - println!("{}", s.chars().map(|c| c.to_uppercase()).collect::()); -} diff --git a/Task/String-case/Stata/string-case-1.stata b/Task/String-case/Stata/string-case-1.stata new file mode 100644 index 0000000000..231641011a --- /dev/null +++ b/Task/String-case/Stata/string-case-1.stata @@ -0,0 +1,5 @@ +. scalar s="alphaBETA" +. di strupper(s) +ALPHABETA +. di strlower(s) +alphabeta diff --git a/Task/String-case/Stata/string-case-2.stata b/Task/String-case/Stata/string-case-2.stata new file mode 100644 index 0000000000..5d4d74d67d --- /dev/null +++ b/Task/String-case/Stata/string-case-2.stata @@ -0,0 +1,6 @@ +. scalar a="Ἐν ἀρχῇ ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν" +. scalar b=ustrupper(a) +. di b +ἘΝ ἈΡΧΗ͂Ι ἘΠΟΊΗΣΕΝ Ὁ ΘΕῸΣ ΤῸΝ ΟΥ̓ΡΑΝῸΝ ΚΑῚ ΤῊΝ ΓΗ͂Ν +. di ustrlower(b) +ἐν ἀρχῆι ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν diff --git a/Task/String-case/TI-83-BASIC/string-case.ti-83 b/Task/String-case/TI-83-BASIC/string-case.ti-83 deleted file mode 100644 index 7306e81b4b..0000000000 --- a/Task/String-case/TI-83-BASIC/string-case.ti-83 +++ /dev/null @@ -1,18 +0,0 @@ -:"ABCDEFGHIJKLMNOPQRSTUVWXYZ"→Str9 -:"abcdefghijklmnopqrstuvwxyz"→Str0 -:Input ">",Str1 -:":"+Str1+":"→Str1 -:Prompt U -:If U:Then -:For(I,2,length(Str1)) -:If inString(Str0,sub(Str1,I,1)) and sub(Str1,I,1)≠":" -:sub(Str1,1,I-1)+sub(Str9,inString(Str0,sub(Str1,I,1)),1)+sub(Str1,I+1,length(Str1)-I)→Str1 -:End -:Else -:For(I,2,length(Str1)) -:If inString(Str9,sub(Str1,I,1)) and sub(Str1,I,1)≠":" -:sub(Str1,1,I-1)+sub(Str0,inString(Str9,sub(Str1,I,1)),1)+sub(Str1,I+1,length(Str1)-I)→Str1 -:End -:End -:sub(Str1,2,length(Str1)-2)→Str1 -:Pause Str1 diff --git a/Task/String-case/Visual-Basic-.NET/string-case.visual b/Task/String-case/Visual-Basic-.NET/string-case.visual deleted file mode 100644 index 10cde0efea..0000000000 --- a/Task/String-case/Visual-Basic-.NET/string-case.visual +++ /dev/null @@ -1,8 +0,0 @@ -' Define 's' -Dim s AS String = "alphaBETA" - -' Change 's' to Upper Case. -s = s.ToUpper() - -' Change 's' to Lower Case. -s = s.ToLower() diff --git a/Task/String-case/Zkl/string-case.zkl b/Task/String-case/Zkl/string-case.zkl new file mode 100644 index 0000000000..dcd17f3c4f --- /dev/null +++ b/Task/String-case/Zkl/string-case.zkl @@ -0,0 +1,3 @@ +s:="alphaBETA"; +s.toLower(); //--> "alphabeta" +s.toUpper(); //--> "ALPHABETA" diff --git a/Task/String-comparison/Astro/string-comparison.astro b/Task/String-comparison/Astro/string-comparison.astro new file mode 100644 index 0000000000..77c1e29f09 --- /dev/null +++ b/Task/String-comparison/Astro/string-comparison.astro @@ -0,0 +1,14 @@ +fun main(args): ## Array[Str] + let a = "astro" + let b = "astro" + print + ..("Case sensitive comparisons:\n") + ..("astro and astro are equal = $(a == b)") + ..("astro and astro are not equal = $(a != b)") + ..("astro comes before astro = $(a < b)") + ..("astro comes after astro = $(a > b)") + ..("\nCase insensitive comparisons:\n") + ..("astro and astro are equal = $(a == b.lower())") + ..("astro and astro are not equal = $(a != b.lower())") + ..("astro comes before astro = $(a < b.lower())") + ..("astro comes after astro = $(a > b.lower())") diff --git a/Task/String-comparison/Elena/string-comparison.elena b/Task/String-comparison/Elena/string-comparison.elena index 670060fd47..65b9dea0a6 100644 --- a/Task/String-comparison/Elena/string-comparison.elena +++ b/Task/String-comparison/Elena/string-comparison.elena @@ -1,19 +1,20 @@ -#import system. -#import extensions. +import extensions. -#symbol compareStrings = (:val1 :val2) +compareStrings = (:val1 :val2) [ - (val1 == val2)? [ console writeLine:"The strings ":val1:" and ":val2:" are equal". ]. - (val1 != val2)? [ console writeLine:"The strings ":val1:" and ":val2:" are not equal". ]. - (val1 > val2)? [ console writeLine:"The string ":val1:" is lexically after than ":val2. ]. - (val1 < val2)? [ console writeLine:"The string ":val1:" is lexically before than ":val2. ]. - (val1 >= val2)? [ console writeLine:"The string ":val1:" is not lexically before than ":val2. ]. - (val1 <= val2)? [ console writeLine:"The string ":val1:" is not lexically after than ":val2. ]. + 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) ]. ]. -#symbol program = +program = [ - #var s1 := "this". - #var s2 := "that". - compareStrings :s1 :s2. + var s1 := "this". + var s2 := "that". + compareStrings eval(s1,s2). + + console readChar. ]. diff --git a/Task/String-comparison/Fortran/string-comparison.f b/Task/String-comparison/Fortran/string-comparison.f new file mode 100644 index 0000000000..686808370c --- /dev/null +++ b/Task/String-comparison/Fortran/string-comparison.f @@ -0,0 +1,2 @@ + PRINT 42,N + 42 FORMAT (14HThe answer is ,I9) diff --git a/Task/String-comparison/jq/string-comparison-1.jq b/Task/String-comparison/Jq/string-comparison-1.jq similarity index 100% rename from Task/String-comparison/jq/string-comparison-1.jq rename to Task/String-comparison/Jq/string-comparison-1.jq diff --git a/Task/String-comparison/jq/string-comparison-2.jq b/Task/String-comparison/Jq/string-comparison-2.jq similarity index 100% rename from Task/String-comparison/jq/string-comparison-2.jq rename to Task/String-comparison/Jq/string-comparison-2.jq diff --git a/Task/String-comparison/jq/string-comparison-3.jq b/Task/String-comparison/Jq/string-comparison-3.jq similarity index 100% rename from Task/String-comparison/jq/string-comparison-3.jq rename to Task/String-comparison/Jq/string-comparison-3.jq diff --git a/Task/String-comparison/Julia/string-comparison.julia b/Task/String-comparison/Julia/string-comparison.julia new file mode 100644 index 0000000000..5b065dbfda --- /dev/null +++ b/Task/String-comparison/Julia/string-comparison.julia @@ -0,0 +1,17 @@ +function compare(a, b) + println("\n$a is of type $(typeof(a)) and $b is of type $(typeof(b))") + if a < b println("$a is strictly less than $b") end + if a <= b println("$a is less than or equal to $b") end + if a > b println("$a is strictly greater than $b") end + if a >= b println("$a is greater than or equal to $b") end + if a == b println("$a is equal to $b") end + if a != b println("$a is not equal to $b") end + if a === b println("$a has object identity with $b") end + if a !== b println("$a has negated object identity with $b") end +end + +compare("YUP", "YUP") +compare('a', 'z') +compare("24", "123") +compare(24, 123) +compare(5.0, 5) diff --git a/Task/String-comparison/Kotlin/string-comparison.kotlin b/Task/String-comparison/Kotlin/string-comparison.kotlin new file mode 100644 index 0000000000..92322888fb --- /dev/null +++ b/Task/String-comparison/Kotlin/string-comparison.kotlin @@ -0,0 +1,16 @@ +// version 1.0.6 + +fun main(args: Array) { + val k1 = "kotlin" + val k2 = "Kotlin" + println("Case sensitive comparisons:\n") + println("kotlin and Kotlin are equal = ${k1 == k2}") + println("kotlin and Kotlin are not equal = ${k1 != k2}") + println("kotlin comes before Kotlin = ${k1 < k2}") + println("kotlin comes after Kotlin = ${k1 > k2}") + println("\nCase insensitive comparisons:\n") + println("kotlin and Kotlin are equal = ${k1 == k2.toLowerCase()}") + println("kotlin and Kotlin are not equal = ${k1 != k2.toLowerCase()}") + println("kotlin comes before Kotlin = ${k1 < k2.toLowerCase()}") + println("kotlin comes after Kotlin = ${k1 > k2.toLowerCase()}") +} diff --git a/Task/String-comparison/Nimrod/string-comparison.nimrod b/Task/String-comparison/Nimrod/string-comparison.nimrod deleted file mode 100644 index 2ed2dcb4b7..0000000000 --- a/Task/String-comparison/Nimrod/string-comparison.nimrod +++ /dev/null @@ -1,10 +0,0 @@ -import strutils - -var s1: string = "The quick brown" -var s2: string = "The Quick Brown" -echo("== : ", s1 == s2) -echo("!= : ", s1 != s2) -echo("< : ", s1 < s2) -echo("<= : ", s1 <= s2) -echo("> : ", s1 > s2) -echo(">= : ", s1 >= s2) diff --git a/Task/String-comparison/OoRexx/string-comparison.rexx b/Task/String-comparison/OoRexx/string-comparison.rexx new file mode 100644 index 0000000000..080e2efb7f --- /dev/null +++ b/Task/String-comparison/OoRexx/string-comparison.rexx @@ -0,0 +1,5 @@ +a=.array~of('A 1','B 2','a 3','b 3','A 5') +a~sortwith(.caselesscomparator~new) +Do i=1 To 5 + Say a[i] + End diff --git a/Task/String-comparison/Zkl/string-comparison.zkl b/Task/String-comparison/Zkl/string-comparison.zkl new file mode 100644 index 0000000000..084f58b818 --- /dev/null +++ b/Task/String-comparison/Zkl/string-comparison.zkl @@ -0,0 +1,18 @@ +"foo" == "foo" //True +"foo" == "FOO" //False +"foo" == "foobar" //False +Op("==")("foo","foo") //True +Op("==","foo")("foo") //True + +"abc"<"cde" //True +"abc">"cde" //False + +"foo" == "FOO" //False +"abc".toUpper()=="ABC" //True + +123=="123" //False +123=="123".toInt() //True + +123<"123" //False, int on left forces "123".toInt() +123<"1234" //True +2345<"1234" //False diff --git a/Task/String-concatenation/BBC-BASIC/string-concatenation.bbc b/Task/String-concatenation/BBC-BASIC/string-concatenation.bbc deleted file mode 100644 index 43cff30ba9..0000000000 --- a/Task/String-concatenation/BBC-BASIC/string-concatenation.bbc +++ /dev/null @@ -1,4 +0,0 @@ - stringvar1$ = "Hello," - stringvar2$ = stringvar1$ + " world!" - PRINT "Variable 1 is """ stringvar1$ """" - PRINT "Variable 2 is """ stringvar2$ """" diff --git a/Task/String-concatenation/Elena/string-concatenation.elena b/Task/String-concatenation/Elena/string-concatenation.elena index b0e2dbf3f5..83847f64a5 100644 --- a/Task/String-concatenation/Elena/string-concatenation.elena +++ b/Task/String-concatenation/Elena/string-concatenation.elena @@ -1,11 +1,9 @@ -#import system. -#import extensions. - -#symbol program = +program = [ - #var s := "Hello". - #var s2 := s + " literal". + var s := "Hello". + var s2 := s + " literal". console writeLine:s. console writeLine:s2. + console readChar. ]. diff --git a/Task/String-concatenation/Gambas/string-concatenation.gambas b/Task/String-concatenation/Gambas/string-concatenation.gambas index fe1b6b1b05..ba7f4ef5b8 100644 --- a/Task/String-concatenation/Gambas/string-concatenation.gambas +++ b/Task/String-concatenation/Gambas/string-concatenation.gambas @@ -1,4 +1,10 @@ +Public sub main() DIM bestclub AS String DIM myconcat AS String + bestclub = "Liverpool" myconcat = bestclub & " Football Club" + +Print myconcat + +End diff --git a/Task/String-concatenation/Halon/string-concatenation.halon b/Task/String-concatenation/Halon/string-concatenation.halon new file mode 100644 index 0000000000..b199d17bb7 --- /dev/null +++ b/Task/String-concatenation/Halon/string-concatenation.halon @@ -0,0 +1 @@ +echo "Hello" . "World " . 123; diff --git a/Task/String-concatenation/jq/string-concatenation.jq b/Task/String-concatenation/Jq/string-concatenation.jq similarity index 100% rename from Task/String-concatenation/jq/string-concatenation.jq rename to Task/String-concatenation/Jq/string-concatenation.jq diff --git a/Task/String-concatenation/Nimrod/string-concatenation-1.nimrod b/Task/String-concatenation/Nimrod/string-concatenation-1.nimrod deleted file mode 100644 index dc76b28a5f..0000000000 --- a/Task/String-concatenation/Nimrod/string-concatenation-1.nimrod +++ /dev/null @@ -1,6 +0,0 @@ -var str, str1 = "String" -echo(str & " literal.") -str1 = str1 & " literal." -echo(str1) - -# -> String literal. diff --git a/Task/String-concatenation/Nimrod/string-concatenation-2.nimrod b/Task/String-concatenation/Nimrod/string-concatenation-2.nimrod deleted file mode 100644 index 713fd2eb69..0000000000 --- a/Task/String-concatenation/Nimrod/string-concatenation-2.nimrod +++ /dev/null @@ -1,4 +0,0 @@ -var str1 = "String" -echo(join([str1, " literal.", "HelloWorld!"], "~~")) - -# -> String~~ literal.~~HelloWorld! diff --git a/Task/String-concatenation/Nimrod/string-concatenation-3.nimrod b/Task/String-concatenation/Nimrod/string-concatenation-3.nimrod deleted file mode 100644 index d051a2c150..0000000000 --- a/Task/String-concatenation/Nimrod/string-concatenation-3.nimrod +++ /dev/null @@ -1,4 +0,0 @@ -var str1 = "String" -echo "$# $# $#" % [str1, "literal.", "HelloWorld!"] - -# -> String literal. HelloWorld! diff --git a/Task/String-concatenation/ZX-Spectrum-Basic/string-concatenation.zx b/Task/String-concatenation/ZX-Spectrum-Basic/string-concatenation.zx deleted file mode 100644 index e71db46ad2..0000000000 --- a/Task/String-concatenation/ZX-Spectrum-Basic/string-concatenation.zx +++ /dev/null @@ -1,3 +0,0 @@ -10 LET s$="Hello" -20 LET s$=s$+" World!" -30 PRINT s$ diff --git a/Task/String-concatenation/Zkl/string-concatenation.zkl b/Task/String-concatenation/Zkl/string-concatenation.zkl new file mode 100644 index 0000000000..cec5ebbb3a --- /dev/null +++ b/Task/String-concatenation/Zkl/string-concatenation.zkl @@ -0,0 +1,3 @@ +var s="Hello"; +s2:=s+", world!"; s2.println(); //-->Hello, world! +s3:=String(s," ",s2); s3.println(); //-->Hello Hello, world! diff --git a/Task/String-interpolation--included-/Elena/string-interpolation--included-.elena b/Task/String-interpolation--included-/Elena/string-interpolation--included-.elena index a3f061c54e..caa7699aa9 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 system. +import extensions. -#symbol program = +program = [ - #var s := "Mary had a @@x lamb." replace &literal:"@@x" &literal:"little". - console writeLine:s. + var s := "little". + console printLineFormatted("Mary had a {0} lamb.",s); readChar. ]. diff --git a/Task/String-interpolation--included-/Gambas/string-interpolation--included-.gambas b/Task/String-interpolation--included-/Gambas/string-interpolation--included-.gambas new file mode 100644 index 0000000000..be4d36ab7e --- /dev/null +++ b/Task/String-interpolation--included-/Gambas/string-interpolation--included-.gambas @@ -0,0 +1,5 @@ +Public Sub Main() + +Print Subst("Mary had a &1 lamb", "little") + +End diff --git a/Task/String-interpolation--included-/Gastona/string-interpolation--included-.gastona b/Task/String-interpolation--included-/Gastona/string-interpolation--included-.gastona new file mode 100644 index 0000000000..babaa05dea --- /dev/null +++ b/Task/String-interpolation--included-/Gastona/string-interpolation--included-.gastona @@ -0,0 +1,6 @@ +#listix# + + //little + //has a @ lamb + +
    //Mary @ diff --git a/Task/String-interpolation--included-/jq/string-interpolation--included--1.jq b/Task/String-interpolation--included-/Jq/string-interpolation--included--1.jq similarity index 100% rename from Task/String-interpolation--included-/jq/string-interpolation--included--1.jq rename to Task/String-interpolation--included-/Jq/string-interpolation--included--1.jq diff --git a/Task/String-interpolation--included-/jq/string-interpolation--included--2.jq b/Task/String-interpolation--included-/Jq/string-interpolation--included--2.jq similarity index 100% rename from Task/String-interpolation--included-/jq/string-interpolation--included--2.jq rename to Task/String-interpolation--included-/Jq/string-interpolation--included--2.jq diff --git a/Task/String-interpolation--included-/Kotlin/string-interpolation--included-.kotlin b/Task/String-interpolation--included-/Kotlin/string-interpolation--included-.kotlin new file mode 100644 index 0000000000..cf6bf682af --- /dev/null +++ b/Task/String-interpolation--included-/Kotlin/string-interpolation--included-.kotlin @@ -0,0 +1,14 @@ +// version 1.0.6 + +fun main(args: Array) { + val s = "little" + // String interpolation using a simple variable + println("Mary had a $s lamb") + + // String interpolation using an expression (need to wrap it in braces) + println("Mary had a ${s.toUpperCase()} lamb") + + // However if a simple variable is immediately followed by a letter, digit or underscore + // it must be treated as an expression + println("Mary had a ${s}r lamb") // not $sr +} diff --git a/Task/String-interpolation--included-/Nimrod/string-interpolation--included-.nimrod b/Task/String-interpolation--included-/Nimrod/string-interpolation--included-.nimrod deleted file mode 100644 index dcfbe59f1a..0000000000 --- a/Task/String-interpolation--included-/Nimrod/string-interpolation--included-.nimrod +++ /dev/null @@ -1,5 +0,0 @@ -import strutils - -var str = "little" -echo "Mary had a $# lamb" % [str] -# doesn't need an array for one substitution, but use an array for multiple substitutions diff --git a/Task/String-interpolation--included-/Scala/string-interpolation--included--1.scala b/Task/String-interpolation--included-/Scala/string-interpolation--included--1.scala deleted file mode 100644 index 29f25d0f84..0000000000 --- a/Task/String-interpolation--included-/Scala/string-interpolation--included--1.scala +++ /dev/null @@ -1,2 +0,0 @@ -val extra = "little" -val result = s"Mary had a $extra lamb." diff --git a/Task/String-interpolation--included-/Scala/string-interpolation--included--2.scala b/Task/String-interpolation--included-/Scala/string-interpolation--included--2.scala deleted file mode 100644 index 477c3e68fa..0000000000 --- a/Task/String-interpolation--included-/Scala/string-interpolation--included--2.scala +++ /dev/null @@ -1 +0,0 @@ -Mary had a little lamb. diff --git a/Task/String-interpolation--included-/Scala/string-interpolation--included--3.scala b/Task/String-interpolation--included-/Scala/string-interpolation--included--3.scala deleted file mode 100644 index 7a0238fb46..0000000000 --- a/Task/String-interpolation--included-/Scala/string-interpolation--included--3.scala +++ /dev/null @@ -1,3 +0,0 @@ -val original = "Mary had a %s lamb." -val extra = "little" -original format extra diff --git a/Task/String-interpolation--included-/Scala/string-interpolation--included--4.scala b/Task/String-interpolation--included-/Scala/string-interpolation--included--4.scala deleted file mode 100644 index 477c3e68fa..0000000000 --- a/Task/String-interpolation--included-/Scala/string-interpolation--included--4.scala +++ /dev/null @@ -1 +0,0 @@ -Mary had a little lamb. diff --git a/Task/String-interpolation--included-/Zkl/string-interpolation--included-.zkl b/Task/String-interpolation--included-/Zkl/string-interpolation--included-.zkl new file mode 100644 index 0000000000..025b57dd72 --- /dev/null +++ b/Task/String-interpolation--included-/Zkl/string-interpolation--included-.zkl @@ -0,0 +1 @@ +"Mary had a X lamb.".replace("X","big") diff --git a/Task/String-length/BASIC/string-length-3.basic b/Task/String-length/BASIC/string-length-3.basic new file mode 100644 index 0000000000..7c19a50691 --- /dev/null +++ b/Task/String-length/BASIC/string-length-3.basic @@ -0,0 +1,2 @@ +10 INPUT A$ +20 PRINT LEN(A$) diff --git a/Task/String-length/Elena/string-length-1.elena b/Task/String-length/Elena/string-length-1.elena index 731a372b4e..a1eaaa48a8 100644 --- a/Task/String-length/Elena/string-length-1.elena +++ b/Task/String-length/Elena/string-length-1.elena @@ -1,6 +1,11 @@ - #var s := "Hello, world!". // UTF-8 literal - #var ws := "Привет мир!"w. // UTF-16 literal +import extensions. - #var s_length := s length. // Number of UTF-8 characters - #var ws_length := ws length. // Number of UTF-16 characters - #var u_length := ws toArray length. //Number of UTF-32 characters +program = +[ + var s := "Hello, world!". // UTF-8 literal + var ws := "Привет мир!"w. // UTF-16 literal + + var s_length := s length. // Number of UTF-8 characters + var ws_length := ws length. // Number of UTF-16 characters + var u_length := ws toArray; length. //Number of UTF-32 characters +]. diff --git a/Task/String-length/Elena/string-length-2.elena b/Task/String-length/Elena/string-length-2.elena index d64f613219..ff8f490055 100644 --- a/Task/String-length/Elena/string-length-2.elena +++ b/Task/String-length/Elena/string-length-2.elena @@ -1,2 +1,10 @@ - #var s_byte_length := s toByteArray length. // Number of bytes - #var ws_byte_length := ws toByteArray length. // Number of bytes +import extensions. + +program = +[ + var s := "Hello, world!". // UTF-8 literal + var ws := "Привет мир!"w. // UTF-16 literal + + var s_byte_length := s toByteArray; length. // Number of bytes + var ws_byte_length := ws toByteArray; length. // Number of bytes +]. diff --git a/Task/String-length/Java/string-length-5.java b/Task/String-length/Java/string-length-5.java deleted file mode 100644 index a67526ecb5..0000000000 --- a/Task/String-length/Java/string-length-5.java +++ /dev/null @@ -1,19 +0,0 @@ -import java.text.BreakIterator; - -public class Grapheme { - public static void main(String[] args) { - printLength("møøse"); - printLength("𝔘𝔫𝔦𝔠𝔬𝔡𝔢"); - printLength("J̲o̲s̲é̲"); - } - - public static void printLength(String s) { - BreakIterator it = BreakIterator.getCharacterInstance(); - it.setText(s); - int count = 0; - while (it.next() != BreakIterator.DONE) { - count++; - } - System.out.println("Grapheme length: " + count+ " " + s); - } -} diff --git a/Task/String-length/jq/string-length-1.jq b/Task/String-length/Jq/string-length-1.jq similarity index 100% rename from Task/String-length/jq/string-length-1.jq rename to Task/String-length/Jq/string-length-1.jq diff --git a/Task/String-length/jq/string-length-2.jq b/Task/String-length/Jq/string-length-2.jq similarity index 100% rename from Task/String-length/jq/string-length-2.jq rename to Task/String-length/Jq/string-length-2.jq diff --git a/Task/String-length/Kotlin/string-length.kotlin b/Task/String-length/Kotlin/string-length.kotlin new file mode 100644 index 0000000000..e432314fbd --- /dev/null +++ b/Task/String-length/Kotlin/string-length.kotlin @@ -0,0 +1,6 @@ +// version 1.0.6 +fun main(args: Array) { + val s = "José" + println("The char length is ${s.length}") + println("The byte length is ${Character.BYTES * s.length}") +} diff --git a/Task/String-length/MIRC-Scripting-Language/string-length-1.mirc b/Task/String-length/MIRC-Scripting-Language/string-length-1.mirc new file mode 100644 index 0000000000..3a2d5f0fa5 --- /dev/null +++ b/Task/String-length/MIRC-Scripting-Language/string-length-1.mirc @@ -0,0 +1 @@ +alias stringlength { echo -a Your Name is: $len($$?="Whats your name") letters long! } diff --git a/Task/String-length/MIRC-Scripting-Language/string-length-2.mirc b/Task/String-length/MIRC-Scripting-Language/string-length-2.mirc new file mode 100644 index 0000000000..6688226458 --- /dev/null +++ b/Task/String-length/MIRC-Scripting-Language/string-length-2.mirc @@ -0,0 +1,5 @@ +alias utf8len { return $len($utfdecode($1)) } +alias stringlength2 { + var %name = Børje + echo -a %name is: $utf8len(%name) characters long! +} diff --git a/Task/String-length/Nimrod/string-length-1.nimrod b/Task/String-length/Nimrod/string-length-1.nimrod deleted file mode 100644 index 3864d831b7..0000000000 --- a/Task/String-length/Nimrod/string-length-1.nimrod +++ /dev/null @@ -1,4 +0,0 @@ -var s: string = "Hello, world! ☺" -echo '"',s, '"'," has byte length: ", len(s) - -# -> "Hello, world! ☺" has unicode char length: 17 diff --git a/Task/String-length/Nimrod/string-length-2.nimrod b/Task/String-length/Nimrod/string-length-2.nimrod deleted file mode 100644 index 389fdf4490..0000000000 --- a/Task/String-length/Nimrod/string-length-2.nimrod +++ /dev/null @@ -1,6 +0,0 @@ -import unicode - -var s: string = "Hello, world! ☺" -echo '"',s, '"'," has unicode char length: ", runeLen(s) - -# -> "Hello, world! ☺" has unicode char length: 15 diff --git a/Task/String-length/Ol/string-length.ol b/Task/String-length/Ol/string-length.ol new file mode 100644 index 0000000000..9038ec5635 --- /dev/null +++ b/Task/String-length/Ol/string-length.ol @@ -0,0 +1,7 @@ +; Character length +(print (string-length "Hello, wørld!")) +; ==> 13 + +; Byte (utf-8 encoded) length +(print (length (string->bytes "Hello, wørld!"))) +; ==> 14 diff --git a/Task/String-length/PHP/string-length-1.php b/Task/String-length/PHP/string-length-1.php deleted file mode 100644 index fd5a516940..0000000000 --- a/Task/String-length/PHP/string-length-1.php +++ /dev/null @@ -1 +0,0 @@ -$length = strlen('Hello, world!'); diff --git a/Task/String-length/PHP/string-length-2.php b/Task/String-length/PHP/string-length-2.php deleted file mode 100644 index e80055a735..0000000000 --- a/Task/String-length/PHP/string-length-2.php +++ /dev/null @@ -1 +0,0 @@ -$length = mb_strlen('Hello, world!', 'UTF-8'); // or whatever encoding diff --git a/Task/String-length/PHP/string-length-3.php b/Task/String-length/PHP/string-length-3.php deleted file mode 100644 index ab80c16d2d..0000000000 --- a/Task/String-length/PHP/string-length-3.php +++ /dev/null @@ -1 +0,0 @@ -$length = grapheme_strlen('Hello, world!'); // UTF-8 encoding required diff --git a/Task/String-length/Run-BASIC/string-length-1.run b/Task/String-length/Run-BASIC/string-length-1.run deleted file mode 100644 index 16a5f26bfc..0000000000 --- a/Task/String-length/Run-BASIC/string-length-1.run +++ /dev/null @@ -1,2 +0,0 @@ -input a$ -print len(a$) diff --git a/Task/String-length/Run-BASIC/string-length-2.run b/Task/String-length/Run-BASIC/string-length-2.run deleted file mode 100644 index 47fcaa7776..0000000000 --- a/Task/String-length/Run-BASIC/string-length-2.run +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- - -puts "あいうえお".length -# => 5 - -puts "あいうえお".size # alias for length -# => 5 diff --git a/Task/String-length/Run-BASIC/string-length-3.run b/Task/String-length/Run-BASIC/string-length-3.run deleted file mode 100644 index 2a53b6cdfc..0000000000 --- a/Task/String-length/Run-BASIC/string-length-3.run +++ /dev/null @@ -1,4 +0,0 @@ -# -*- coding: iso-8859-1 -*- -s = "møøse" -puts "Byte length: %d" % s.bytesize -puts "Character length: %d" % s.length diff --git a/Task/String-length/Run-BASIC/string-length-4.run b/Task/String-length/Run-BASIC/string-length-4.run deleted file mode 100644 index af1ce7cb7f..0000000000 --- a/Task/String-length/Run-BASIC/string-length-4.run +++ /dev/null @@ -1,4 +0,0 @@ -# -*- coding: utf-8 -*- -s = "møøse" -puts "Byte length: %d" % s.bytesize -puts "Character length: %d" % s.length diff --git a/Task/String-length/Run-BASIC/string-length-5.run b/Task/String-length/Run-BASIC/string-length-5.run deleted file mode 100644 index 108634387d..0000000000 --- a/Task/String-length/Run-BASIC/string-length-5.run +++ /dev/null @@ -1,4 +0,0 @@ -# -*- coding: gb18030 -*- -s = "møøse" -puts "Byte length: %d" % s.bytesize -puts "Character length: %d" % s.length diff --git a/Task/String-length/Run-BASIC/string-length-6.run b/Task/String-length/Run-BASIC/string-length-6.run deleted file mode 100644 index ac153f7564..0000000000 --- a/Task/String-length/Run-BASIC/string-length-6.run +++ /dev/null @@ -1,12 +0,0 @@ -# -*- coding: utf-8 -*- - -class String - # Define String#bytesize for Ruby 1.8.6. - unless method_defined?(:bytesize) - alias bytesize length - end -end - -s = "文字化け" -puts "Byte length: %d" % s.bytesize -puts "Character length: %d" % s.gsub(/./u, ' ').size diff --git a/Task/String-length/Rust/string-length.rust b/Task/String-length/Rust/string-length.rust new file mode 100644 index 0000000000..ab3ce48225 --- /dev/null +++ b/Task/String-length/Rust/string-length.rust @@ -0,0 +1,4 @@ +fn main(){ + let len = String::from("Hello world").len(); + println!("{}", len); +} diff --git a/Task/String-length/SPL/string-length.spl b/Task/String-length/SPL/string-length.spl new file mode 100644 index 0000000000..57d08acab8 --- /dev/null +++ b/Task/String-length/SPL/string-length.spl @@ -0,0 +1,24 @@ +t = ["abc","J̲o̲s̲é̲","møøse","𝔘𝔫𝔦𝔠𝔬𝔡𝔢"] + +> i, 1..#.size(t,1) + ? i>1, #.output() + #.output(#.quot,t[i],#.quot," contains") + + p = #.split(t[i]) + cn = #.size(p,1) + s = #.str(cn,">3>")+" chars: " + > j, 1..cn + ? j>1, s += ", " + s += p[j] + < + #.output(s) + + q = #.array(t[i]) + bn = #.size(q,1) + s = #.str(bn,">3>")+" bytes: " + > j, 1..bn + ? j>1, s += ", " + s += #.str(q[j],"X2")+"h" + < + #.output(s) +< diff --git a/Task/String-length/Simula/string-length-1.simula b/Task/String-length/Simula/string-length-1.simula new file mode 100644 index 0000000000..defe1672a6 --- /dev/null +++ b/Task/String-length/Simula/string-length-1.simula @@ -0,0 +1,14 @@ +BEGIN + TEXT LINE; + WHILE NOT LASTITEM DO + BEGIN + INTEGER L; + LINE :- COPY(SYSIN.IMAGE).STRIP; + OUTCHAR('"'); + OUTTEXT(LINE); + OUTCHAR('"'); + OUTTEXT(" BYTE LENGTH = "); OUTINT(LINE.LENGTH, 0); + OUTIMAGE; + INIMAGE; + END; +END. diff --git a/Task/String-length/Simula/string-length-2.simula b/Task/String-length/Simula/string-length-2.simula new file mode 100644 index 0000000000..721ddae568 --- /dev/null +++ b/Task/String-length/Simula/string-length-2.simula @@ -0,0 +1,46 @@ +BEGIN + + ! NUMBER OF UFT8 CHARACTERS IN STRING ; + INTEGER PROCEDURE UTF8STRLEN(S); TEXT S; + BEGIN + INTEGER R, LEN, BYTES, ALLBYTES; + CHARACTER BYTE; + WHILE S.MORE DO + BEGIN + BYTE := S.GETCHAR; + ALLBYTES := ALLBYTES + 1; + R := RANK(BYTE); + LEN := LEN + 1; + BYTES := + IF R >= 0 AND R <= 127 THEN 1 ELSE ! 0....... ASCII ; + IF R >= 128 AND R <= 191 THEN 0 ELSE ! 10...... CONTINUATION ; + IF R >= 192 AND R <= 223 THEN 2 ELSE ! 110..... 10x ; + IF R >= 224 AND R <= 239 THEN 3 ELSE ! 1110.... 10x 10x ; + IF R >= 240 AND R <= 247 THEN 4 ELSE ! 11110... 10x 10x 10x ; + -1; + IF BYTES = -1 THEN ERROR("ILLEGAL UTF8 STRING"); + WHILE BYTES > 1 DO + BEGIN + BYTE := S.GETCHAR; + ALLBYTES := ALLBYTES + 1; + BYTES := BYTES - 1; + END; + END; + UTF8STRLEN := LEN; + END UTF8STRLEN; + + TEXT LINE; + WHILE NOT LASTITEM DO + BEGIN + INTEGER L; + LINE :- COPY(SYSIN.IMAGE).STRIP; + OUTCHAR('"'); + OUTTEXT(LINE); + OUTCHAR('"'); + L := UTF8STRLEN(LINE); + OUTTEXT(" CHARACTER LENGTH = "); OUTINT(UTF8STRLEN(LINE), 0); + OUTIMAGE; + INIMAGE; + END; + +END. diff --git a/Task/String-length/Stata/string-length.stata b/Task/String-length/Stata/string-length.stata new file mode 100644 index 0000000000..f529728824 --- /dev/null +++ b/Task/String-length/Stata/string-length.stata @@ -0,0 +1,3 @@ +scalar s="Ἐν ἀρχῇ ἐποίησεν ὁ θεὸς τὸν οὐρανὸν καὶ τὴν γῆν" +di strlen(s) +di ustrlen(s) diff --git a/Task/String-length/X86-Assembly/string-length.x86 b/Task/String-length/X86-Assembly/string-length.x86 new file mode 100644 index 0000000000..543369783b --- /dev/null +++ b/Task/String-length/X86-Assembly/string-length.x86 @@ -0,0 +1,24 @@ +.data +string: .asciz "Test" + +.text +.globl main + +main: + pushl %ebp + movl %esp, %ebp + + pushl %edi + xorb %al, %al + movl $-1, %ecx + movl $string, %edi + cld + repne scasb + not %ecx + dec %ecx + popl %edi + + ;; string length is stored in %ecx register + + leave + ret diff --git a/Task/String-length/XTalk/string-length-1.xtalk b/Task/String-length/XTalk/string-length-1.xtalk new file mode 100644 index 0000000000..8582b2b68d --- /dev/null +++ b/Task/String-length/XTalk/string-length-1.xtalk @@ -0,0 +1 @@ +put the length of "Hello World" diff --git a/Task/String-length/XTalk/string-length-2.xtalk b/Task/String-length/XTalk/string-length-2.xtalk new file mode 100644 index 0000000000..63848e4981 --- /dev/null +++ b/Task/String-length/XTalk/string-length-2.xtalk @@ -0,0 +1 @@ +put the number of characters in "Hello World" diff --git a/Task/String-length/XTalk/string-length-3.xtalk b/Task/String-length/XTalk/string-length-3.xtalk new file mode 100644 index 0000000000..8582b2b68d --- /dev/null +++ b/Task/String-length/XTalk/string-length-3.xtalk @@ -0,0 +1 @@ +put the length of "Hello World" diff --git a/Task/String-length/XTalk/string-length-4.xtalk b/Task/String-length/XTalk/string-length-4.xtalk new file mode 100644 index 0000000000..63848e4981 --- /dev/null +++ b/Task/String-length/XTalk/string-length-4.xtalk @@ -0,0 +1 @@ +put the number of characters in "Hello World" diff --git a/Task/String-length/Zkl/string-length-1.zkl b/Task/String-length/Zkl/string-length-1.zkl new file mode 100644 index 0000000000..a999c9c522 --- /dev/null +++ b/Task/String-length/Zkl/string-length-1.zkl @@ -0,0 +1,2 @@ +"abc".len() //-->3 +"\ufeff\u00A2 \u20ac".len() //-->9 "BOM¢ €" diff --git a/Task/String-length/Zkl/string-length-2.zkl b/Task/String-length/Zkl/string-length-2.zkl new file mode 100644 index 0000000000..d640c18f8b --- /dev/null +++ b/Task/String-length/Zkl/string-length-2.zkl @@ -0,0 +1,5 @@ +"abc".len() //-->3 +"\ufeff\u00A2 \u20ac".len() //-->9 +Data(0,Int,"\ufeff\u00A2 \u20ac") //-->Data(9) (bytes) +"J\u0332o\u0332s\u0332e\u0301\u0332".len() //-->14 +"\U1D518;\U1D52B;\U1D526;\U1D520;\U1D52C;\U1D521;\U1D522;".len() //-->28 diff --git a/Task/String-length/Zkl/string-length-3.zkl b/Task/String-length/Zkl/string-length-3.zkl new file mode 100644 index 0000000000..26acedf348 --- /dev/null +++ b/Task/String-length/Zkl/string-length-3.zkl @@ -0,0 +1,6 @@ +"abc".len(8) //-->3 +"\ufeff\u00A2 \u20ac".len(8) //-->4 "BOM¢ €" +"\U1000;".len(8) //-->Exception thrown: ValueError(Invalid UTF-8 string) +"\uD800" //-->SyntaxError : Line 2: Bad Unicode constant (\uD800-\uDFFF) +"J\u0332o\u0332s\u0332e\u0301\u0332".len(8) //-->9 "J̲o̲s̲é̲" +"\U1D518;\U1D52B;\U1D526;\U1D520;\U1D52C;\U1D521;\U1D522;".len(8) //-->7 "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" diff --git a/Task/String-matching/360-Assembly/string-matching.360 b/Task/String-matching/360-Assembly/string-matching.360 new file mode 100644 index 0000000000..9ebb4c4761 --- /dev/null +++ b/Task/String-matching/360-Assembly/string-matching.360 @@ -0,0 +1,34 @@ +* String matching 04/04/2017 +STRMATCH CSECT + USING STRMATCH,R15 + XPRNT SS,L'SS +* + CLC SS(L'S1),S1 + BNE NOT1 + XPRNT =C'-- STARTS WITH',14 + XPRNT S1,L'S1 +NOT1 EQU * +* + CLC SS+L'SS-L'S2(L'S2),S2 + BNE NOT2 + XPRNT =C'-- ENDS WITH',12 + XPRNT S2,L'S2 +NOT2 EQU * +* + LA R0,L'SS-L'S3+1 + LA R1,SS +LOOP CLC 0(L'S3,R1),S3 + BNE NOT3 + XPRNT =C'-- CONTAINS',11 + XPRNT S3,L'S3 +NOT3 LA R1,1(R1) + BCT R0,LOOP +* + BR R14 +SS DC CL6'ABCDEF' +S1 DC CL2'AB' +S2 DC CL2'EF' +S3 DC CL2'CD' +PG DC CL80' ' + YREGS + END STRMATCH diff --git a/Task/String-matching/Elena/string-matching.elena b/Task/String-matching/Elena/string-matching.elena index 11c7eed52c..51551f683f 100644 --- a/Task/String-matching/Elena/string-matching.elena +++ b/Task/String-matching/Elena/string-matching.elena @@ -1,25 +1,24 @@ -#import system. -#import extensions. +import extensions. -#symbol program = +program = [ - #var s := "abcd". + var s := "abcd". - console writeLine:s:" starts with ab: ":(s startingWith:"ab" literal). - console writeLine:s:" starts with cd: ":(s startingWith:"cd" literal). + console printLine(s," starts with ab: ",s startingWith:"ab"). + console printLine(s," starts with cd: ",s startingWith:"cd"). - console writeLine:s:" ends with ab: ":(s endingWith:"ab" literal). - console writeLine:s:" ends with cd: ":(s endingWith:"cd" literal). + console printLine(s," ends with ab: ",s endingWith:"ab"). + console printLine(s," ends with cd: ",s endingWith:"cd"). - console writeLine:s:" contains ab: ":(s containing:"ab" literal). - console writeLine:s:" contains bc: ":(s containing:"bc" literal). - console writeLine:s:" contains cd: ":(s containing:"cd" literal). - console writeLine:s:" contains az: ":(s containing:"az" literal). + console printLine(s," contains ab: ",s containing:"ab"). + console printLine(s," contains bc: ",s containing:"bc"). + console printLine(s," contains cd: ",s containing:"cd"). + console printLine(s," contains az: ",s containing:"az"). - console writeLine:s:" index of az: ":(s indexOf:"az" &at:0 literal). - console writeLine:s:" index of cd: ":(s indexOf:"cd" &at:0 literal). - console writeLine:s:" index of bc: ":(s indexOf:"bc" &at:0 literal). - console writeLine:s:" index of ab: ":(s indexOf:"ab" &at:0 literal). + console printLine(s," index of az: ",s indexOf:"az" at:0). + console printLine(s," index of cd: ",s indexOf:"cd" at:0). + console printLine(s," index of bc: ",s indexOf:"bc" at:0). + console printLine(s," index of ab: ",s indexOf:"ab" at:0). console readChar. ]. diff --git a/Task/String-matching/Gambas/string-matching.gambas b/Task/String-matching/Gambas/string-matching.gambas new file mode 100644 index 0000000000..b19bafb0f0 --- /dev/null +++ b/Task/String-matching/Gambas/string-matching.gambas @@ -0,0 +1,9 @@ +Public Sub Main() +Dim sString1 As String = "Hello world" +Dim sString2 As String = "Hello" + +Print sString1 Begins Left(sString2, 5) 'Determine if the first string starts with second string +If InStr(sString1, sString2) Then Print "True" Else Print "False" 'Determine if the first string contains the second string at any location +Print sString1 Ends Left(sString2, 5) 'Determine if the first string ends with the second string + +End diff --git a/Task/String-matching/jq/string-matching-1.jq b/Task/String-matching/Jq/string-matching-1.jq similarity index 100% rename from Task/String-matching/jq/string-matching-1.jq rename to Task/String-matching/Jq/string-matching-1.jq diff --git a/Task/String-matching/jq/string-matching-2.jq b/Task/String-matching/Jq/string-matching-2.jq similarity index 100% rename from Task/String-matching/jq/string-matching-2.jq rename to Task/String-matching/Jq/string-matching-2.jq diff --git a/Task/String-matching/jq/string-matching-3.jq b/Task/String-matching/Jq/string-matching-3.jq similarity index 100% rename from Task/String-matching/jq/string-matching-3.jq rename to Task/String-matching/Jq/string-matching-3.jq diff --git a/Task/String-matching/jq/string-matching-4.jq b/Task/String-matching/Jq/string-matching-4.jq similarity index 100% rename from Task/String-matching/jq/string-matching-4.jq rename to Task/String-matching/Jq/string-matching-4.jq diff --git a/Task/String-matching/jq/string-matching-5.jq b/Task/String-matching/Jq/string-matching-5.jq similarity index 100% rename from Task/String-matching/jq/string-matching-5.jq rename to Task/String-matching/Jq/string-matching-5.jq diff --git a/Task/String-matching/jq/string-matching-6.jq b/Task/String-matching/Jq/string-matching-6.jq similarity index 100% rename from Task/String-matching/jq/string-matching-6.jq rename to Task/String-matching/Jq/string-matching-6.jq diff --git a/Task/String-matching/Kotlin/string-matching.kotlin b/Task/String-matching/Kotlin/string-matching.kotlin new file mode 100644 index 0000000000..3a3f08cfae --- /dev/null +++ b/Task/String-matching/Kotlin/string-matching.kotlin @@ -0,0 +1,12 @@ +// version 1.0.6 + +fun main(args: Array) { + val s1 = "abracadabra" + val s2 = "abra" + println("$s1 begins with $s2 : ${s1.startsWith(s2)}") + println("$s1 ends with $s2 : ${s1.endsWith(s2)}") + val b = s2 in s1 + print("$s1 contains $s2 : $b") + if (b) println(" at locations ${s1.indexOf(s2) + 1} and ${s1.lastIndexOf(s2) + 1}") + else println() +} diff --git a/Task/String-matching/REXX/string-matching.rexx b/Task/String-matching/REXX/string-matching.rexx index 06ff7ba45f..43761a53f8 100644 --- a/Task/String-matching/REXX/string-matching.rexx +++ b/Task/String-matching/REXX/string-matching.rexx @@ -2,7 +2,7 @@ parse arg A B; LB=length(B) /*obtain A and B from the command line.*/ say 'string A = ' A /*display string A to the terminal.*/ say 'string B = ' B /* " " B " " " */ -say +say copies('░', 70) if left(A, LB)==B then say 'string A starts with string B' else say "string A doesn't start with string B" say /* [↓] another method using COMPARE BIF*/ @@ -17,12 +17,11 @@ say if right(A, LB)==b then say 'string A ends with string B' else say "string A doesn't end with string B" say -$=; p=0; do until p==0; p=pos(B, A, p+1) - if p\==0 then $=$',' p - end /*until ···*/ -$=space(strip($,'L',",")) /*elide extra blanks and leading comma.*/ -#=words($) +$=; p=0; do until p==0; p=pos(B, A, p+1) + if p\==0 then $=$',' p + end /*until*/ +$=space(strip($, 'L', ",")) /*elide extra blanks and leading comma.*/ +#=words($) /*obtain number of words in $ string.*/ if #==0 then say "string A doesn't contain string B" - else say 'string A contains string B ' # " time"left('s', #>1), - "(at position"left('s', #>1) $")" - /*stick a fork in it, we're all done. */ + else say 'string A contains string B ' # " time"left('s', #>1), + "(at position"left('s', #>1) $")" /*stick a fork in it, we're done*/ diff --git a/Task/String-matching/Rust/string-matching.rust b/Task/String-matching/Rust/string-matching-1.rust similarity index 100% rename from Task/String-matching/Rust/string-matching.rust rename to Task/String-matching/Rust/string-matching-1.rust diff --git a/Task/String-matching/Rust/string-matching-2.rust b/Task/String-matching/Rust/string-matching-2.rust new file mode 100644 index 0000000000..6fa37d8f3d --- /dev/null +++ b/Task/String-matching/Rust/string-matching-2.rust @@ -0,0 +1,7 @@ +fn main(){ + let hello = String::from("Hello world"); + println!(" Start with \"he\" {} \n Ends with \"rd\" {}\n Contains \"wi\" {}", + hello.starts_with("He"), + hello.ends_with("ld"), + hello.contains("wi")); +} diff --git a/Task/String-matching/TXR/string-matching-1.txr b/Task/String-matching/TXR/string-matching-1.txr index 2826762e57..34aac218cd 100644 --- a/Task/String-matching/TXR/string-matching-1.txr +++ b/Task/String-matching/TXR/string-matching-1.txr @@ -5,13 +5,12 @@ (put-line `@big is shorter than @small`)) ((str= big small) (put-line `@big and @small are equal`)) - ((match-str big small) + ((starts-with small big) (put-line `@small is a prefix of @big`)) - ((match-str big small -1) + ((ends-with small big) (put-line `@small is a suffix of @big`)) - (t (let ((pos (search-str big small))) - (if pos - (put-line `@small occurs in @big at position @pos`) - (put-line `@small does not occur in @big`)))))) + (t (iflet ((pos (search-str big small))) + (put-line `@small occurs in @big at position @pos`) + (put-line `@small does not occur in @big`))))) (otherwise (put-line `usage: @(ldiff *full-args* *args*) `))) diff --git a/Task/String-matching/Zkl/string-matching-1.zkl b/Task/String-matching/Zkl/string-matching-1.zkl new file mode 100644 index 0000000000..a4cafcb87f --- /dev/null +++ b/Task/String-matching/Zkl/string-matching-1.zkl @@ -0,0 +1,3 @@ +fcn f(text,p){ if(text.find(p)==0)println("Yep") else println("Nope") } +f("foobar","foo") //--> Yep +f("foobar","bar") //--> Nope diff --git a/Task/String-matching/Zkl/string-matching-2.zkl b/Task/String-matching/Zkl/string-matching-2.zkl new file mode 100644 index 0000000000..c64e71027d --- /dev/null +++ b/Task/String-matching/Zkl/string-matching-2.zkl @@ -0,0 +1,3 @@ +fcn f(text,p){ if(Void!=(n:=text.find(p)))println("Contained @",n) else println("Nope") } +f("foobar","ob") //--> Contained @2 +f("foobar","food") //--> Nope diff --git a/Task/String-matching/Zkl/string-matching-3.zkl b/Task/String-matching/Zkl/string-matching-3.zkl new file mode 100644 index 0000000000..70274010be --- /dev/null +++ b/Task/String-matching/Zkl/string-matching-3.zkl @@ -0,0 +1,7 @@ +fcn f(text,p){ + if( Void!=(n:=text.rfind(p)) and n+p.len()==text.len() ) + println("tail gunner") else println("Nope") +} +f("foobar","r"); f("foobar","ar"); //--> tail gunners +f("foobar","ob"); //--> Nope +f("foobarfoobar","bar"); //--> tail gunner diff --git a/Task/String-prepend/ColdFusion/string-prepend-1.cfm b/Task/String-prepend/ColdFusion/string-prepend-1.cfm new file mode 100644 index 0000000000..434f84b18e --- /dev/null +++ b/Task/String-prepend/ColdFusion/string-prepend-1.cfm @@ -0,0 +1,4 @@ + + + #"Hello " & who# + diff --git a/Task/String-prepend/ColdFusion/string-prepend-2.cfm b/Task/String-prepend/ColdFusion/string-prepend-2.cfm new file mode 100644 index 0000000000..f6784d60ee --- /dev/null +++ b/Task/String-prepend/ColdFusion/string-prepend-2.cfm @@ -0,0 +1,5 @@ + + who = "World!"; + greeting = "Hello " & who; + writeOutput( greeting ); + diff --git a/Task/String-prepend/Elena/string-prepend.elena b/Task/String-prepend/Elena/string-prepend.elena index c33704378b..dc3990604b 100644 --- a/Task/String-prepend/Elena/string-prepend.elena +++ b/Task/String-prepend/Elena/string-prepend.elena @@ -1,13 +1,14 @@ -#import system. +import extensions. -#symbol program = +program = [ - #var s := "World". + var s := "World". s := "Hello " + s. console writeLine:s. // Alternative way - #var s2 := String new:"World". - s2 insert:"Hello " &at:0. + var s2 := String new:"World". + s2 insert:"Hello " at:0. console writeLine:s2. + console readChar. ]. diff --git a/Task/String-prepend/Gambas/string-prepend.gambas b/Task/String-prepend/Gambas/string-prepend.gambas new file mode 100644 index 0000000000..96f44558e4 --- /dev/null +++ b/Task/String-prepend/Gambas/string-prepend.gambas @@ -0,0 +1,9 @@ +Public Sub Main() +Dim sString1 As String = "world!" +Dim sString2 As String = "Hello " + +sString1 = sString2 & sString1 + +Print sString1 + +End diff --git a/Task/String-prepend/JavaScript/string-prepend.js b/Task/String-prepend/JavaScript/string-prepend.js new file mode 100644 index 0000000000..5b9d9ed572 --- /dev/null +++ b/Task/String-prepend/JavaScript/string-prepend.js @@ -0,0 +1,4 @@ +// No built-in prepend +var s=", World" +s = "Hello" + s +print(s); diff --git a/Task/String-prepend/jq/string-prepend.jq b/Task/String-prepend/Jq/string-prepend.jq similarity index 100% rename from Task/String-prepend/jq/string-prepend.jq rename to Task/String-prepend/Jq/string-prepend.jq diff --git a/Task/String-prepend/Kotlin/string-prepend.kotlin b/Task/String-prepend/Kotlin/string-prepend.kotlin new file mode 100644 index 0000000000..01a71d9052 --- /dev/null +++ b/Task/String-prepend/Kotlin/string-prepend.kotlin @@ -0,0 +1,13 @@ +// version 1.0.6 + +fun main(args: Array) { + var s = "Obama" + s = "Barack " + s + println(s) + + // It's also possible to use this standard library function + // though this is not what it's really intended for + var t = "Trump" + t = t.prependIndent("Donald ") + println(t) +} diff --git a/Task/String-prepend/Objeck/string-prepend.objeck b/Task/String-prepend/Objeck/string-prepend.objeck new file mode 100644 index 0000000000..9e5133d2df --- /dev/null +++ b/Task/String-prepend/Objeck/string-prepend.objeck @@ -0,0 +1,6 @@ +class Prepend { + function : Main(args : String[]) ~ Nil { + s := "world!"; + "Hello {$s}"->PrintLine(); + } +} diff --git a/Task/String-prepend/Zkl/string-prepend.zkl b/Task/String-prepend/Zkl/string-prepend.zkl new file mode 100644 index 0000000000..df0ca224bf --- /dev/null +++ b/Task/String-prepend/Zkl/string-prepend.zkl @@ -0,0 +1,5 @@ +s:="bar"; s="foo" + s; s.println(); +s:="bar"; s=String("foo",s); s.println(); +s:="bar"; s="%s%s".fmt("foo",s); s.println(); + // a Data is a byte buffer/editor: +s:=Data(Void,"bar").insert(0,"foo").text; s.println(); diff --git a/Task/Strip-a-set-of-characters-from-a-string/AppleScript/strip-a-set-of-characters-from-a-string-2.applescript b/Task/Strip-a-set-of-characters-from-a-string/AppleScript/strip-a-set-of-characters-from-a-string-2.applescript index 26a5e087ff..9324c40157 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/AppleScript/strip-a-set-of-characters-from-a-string-2.applescript +++ b/Task/Strip-a-set-of-characters-from-a-string/AppleScript/strip-a-set-of-characters-from-a-string-2.applescript @@ -1,16 +1,16 @@ -- stripChars :: String -> String -> String on stripChars(strNeedles, strHaystack) script notNeedles - on lambda(x) + on |λ|(x) notElem(x, strNeedles) - end lambda + end |λ| end script intercalate("", filter(notNeedles, strHaystack)) end stripChars --- TEST +-- TEST --------------------------------------------------------------------------- on run stripChars("aei", "She was a soul stripper. She took my heart!") @@ -19,8 +19,7 @@ on run end run - --- GENERIC LIBRARY FUNCTIONS +-- GENERIC FUNCTIONS --------------------------------------------------------------------------- -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) @@ -29,7 +28,7 @@ on filter(f, xs) set lng to length of xs repeat with i from 1 to lng set v to item i of xs - if lambda(v, i, xs) then set end of lst to v + if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell @@ -55,7 +54,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Strip-a-set-of-characters-from-a-string/AppleScript/strip-a-set-of-characters-from-a-string-3.applescript b/Task/Strip-a-set-of-characters-from-a-string/AppleScript/strip-a-set-of-characters-from-a-string-3.applescript index 04651c5aab..9d1c009e1c 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/AppleScript/strip-a-set-of-characters-from-a-string-3.applescript +++ b/Task/Strip-a-set-of-characters-from-a-string/AppleScript/strip-a-set-of-characters-from-a-string-3.applescript @@ -9,7 +9,7 @@ on stripChars(strNeedles, strHaystack) end stripChars --- TEST +-- TEST ------------------------------------------------------------------------ on run stripChars("aei", "She was a soul stripper. She took my heart!") @@ -18,15 +18,14 @@ on run end run - --- GENERIC LIBRARY FUNCTIONS +-- GENERIC FUNCTIONS ----------------------------------------------------------- -- splitRegex :: RegexPattern -> String -> [String] on splitRegex(strRegex, str) set lstMatches to regexMatches(strRegex, str) if length of lstMatches > 0 then script preceding - on lambda(a, x) + on |λ|(a, x) set iFrom to start of a set iLocn to (location of x) @@ -36,7 +35,7 @@ on splitRegex(strRegex, str) set strPart to "" end if {parts:parts of a & strPart, start:iLocn + (length of x) - 1} - end lambda + end |λ| end script set recLast to foldl(preceding, {parts:[], start:0}, lstMatches) @@ -74,7 +73,7 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -95,7 +94,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Strip-a-set-of-characters-from-a-string/BASIC/strip-a-set-of-characters-from-a-string.basic b/Task/Strip-a-set-of-characters-from-a-string/BASIC/strip-a-set-of-characters-from-a-string-1.basic similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/BASIC/strip-a-set-of-characters-from-a-string.basic rename to Task/Strip-a-set-of-characters-from-a-string/BASIC/strip-a-set-of-characters-from-a-string-1.basic diff --git a/Task/Strip-a-set-of-characters-from-a-string/BASIC/strip-a-set-of-characters-from-a-string-2.basic b/Task/Strip-a-set-of-characters-from-a-string/BASIC/strip-a-set-of-characters-from-a-string-2.basic new file mode 100644 index 0000000000..d78760f83d --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/BASIC/strip-a-set-of-characters-from-a-string-2.basic @@ -0,0 +1,14 @@ + 10 LET A$="SHE WAS A SOUL STRIPPER. SHE TOOK MY HEART." + 20 LET B$="AEI" + 30 GOSUB 60 + 40 PRINT C$ + 50 STOP + 60 LET C$="" + 70 FOR I=1 TO LEN A$ + 80 LET J=1 + 90 IF A$(I)=B$(J) THEN GOTO 130 +100 LET J=J+1 +110 IF J<=LEN B$ THEN GOTO 90 +120 LET C$=C$+A$(I) +130 NEXT I +140 RETURN diff --git a/Task/Strip-a-set-of-characters-from-a-string/Common-Lisp/strip-a-set-of-characters-from-a-string.lisp b/Task/Strip-a-set-of-characters-from-a-string/Common-Lisp/strip-a-set-of-characters-from-a-string.lisp index 4b3bf7f639..40dbf8b1ce 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/Common-Lisp/strip-a-set-of-characters-from-a-string.lisp +++ b/Task/Strip-a-set-of-characters-from-a-string/Common-Lisp/strip-a-set-of-characters-from-a-string.lisp @@ -3,3 +3,10 @@ (strip-chars "She was a soul stripper. She took my heart!" "aei") ;; => "Sh ws soul strppr. Sh took my hrt!" + +;; strip whitespace: +(string-trim + '(#\Space #\Newline #\Backspace #\Tab + #\Linefeed #\Page #\Return #\Rubout) + " A string ") +;; => "A string" diff --git a/Task/Strip-a-set-of-characters-from-a-string/Gambas/strip-a-set-of-characters-from-a-string.gambas b/Task/Strip-a-set-of-characters-from-a-string/Gambas/strip-a-set-of-characters-from-a-string.gambas new file mode 100644 index 0000000000..57d05f40a6 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Gambas/strip-a-set-of-characters-from-a-string.gambas @@ -0,0 +1,16 @@ +Public Sub Main() + +Print StripChars("She was a soul stripper. She took my heart!", "aei") + +End +'_____________________________________________________________________ +Public Sub StripChars(sText As String, sRemove As String) As String +Dim siCount As Short + +For siCount = 1 To Len(sRemove) + sText = Replace(sText, Mid(sRemove, siCount, 1), "") +Next + +Return sText + +End diff --git a/Task/Strip-a-set-of-characters-from-a-string/JavaScript/strip-a-set-of-characters-from-a-string.js b/Task/Strip-a-set-of-characters-from-a-string/JavaScript/strip-a-set-of-characters-from-a-string-1.js similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/JavaScript/strip-a-set-of-characters-from-a-string.js rename to Task/Strip-a-set-of-characters-from-a-string/JavaScript/strip-a-set-of-characters-from-a-string-1.js diff --git a/Task/Strip-a-set-of-characters-from-a-string/JavaScript/strip-a-set-of-characters-from-a-string-2.js b/Task/Strip-a-set-of-characters-from-a-string/JavaScript/strip-a-set-of-characters-from-a-string-2.js new file mode 100644 index 0000000000..9854a0c152 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/JavaScript/strip-a-set-of-characters-from-a-string-2.js @@ -0,0 +1,21 @@ +(() => { + 'use strict'; + + // stripChars :: String -> String -> String + const stripChars = (strNeedles, strHayStack) => + strHayStack.replace(RegExp(`[${strNeedles}]`, 'g'), ''); + + // GENERIC FUNCTION + + // curry :: ((a, b) -> c) -> a -> b -> c + const curry = f => a => b => f(a, b); + + // TEST FUNCTION + + const noAEI = curry(stripChars)('aeiAEI'); + + // TEST + return noAEI('She was a soul stripper. She took my heart!'); + + // 'Sh ws soul strppr. Sh took my hrt!' +})(); diff --git a/Task/Strip-a-set-of-characters-from-a-string/JavaScript/strip-a-set-of-characters-from-a-string-3.js b/Task/Strip-a-set-of-characters-from-a-string/JavaScript/strip-a-set-of-characters-from-a-string-3.js new file mode 100644 index 0000000000..6631f0e910 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/JavaScript/strip-a-set-of-characters-from-a-string-3.js @@ -0,0 +1,27 @@ +(() => { + 'use strict'; + + // stripChars :: String -> String -> String + const stripChars = (strNeedles, strHayStack) => + strHayStack.split('') + .filter(x => !elem(x, strNeedles)) + .join(''); + + // GENERIC FUNCTIONS + + // elem :: Eq a => a -> [a] -> Bool + const elem = (x, xs) => xs.indexOf(x) !== -1; + + // curry :: ((a, b) -> c) -> a -> b -> c + const curry = f => a => b => f(a, b); + + // TEST FUNCTION + + const noAEI = curry(stripChars)('aeiAEI'); + + + // TEST + return noAEI('She was a soul stripper. She took my heart!'); + + // 'Sh ws soul strppr. Sh took my hrt!' +})(); diff --git a/Task/Strip-a-set-of-characters-from-a-string/jq/strip-a-set-of-characters-from-a-string-1.jq b/Task/Strip-a-set-of-characters-from-a-string/Jq/strip-a-set-of-characters-from-a-string-1.jq similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/jq/strip-a-set-of-characters-from-a-string-1.jq rename to Task/Strip-a-set-of-characters-from-a-string/Jq/strip-a-set-of-characters-from-a-string-1.jq diff --git a/Task/Strip-a-set-of-characters-from-a-string/jq/strip-a-set-of-characters-from-a-string-2.jq b/Task/Strip-a-set-of-characters-from-a-string/Jq/strip-a-set-of-characters-from-a-string-2.jq similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/jq/strip-a-set-of-characters-from-a-string-2.jq rename to Task/Strip-a-set-of-characters-from-a-string/Jq/strip-a-set-of-characters-from-a-string-2.jq diff --git a/Task/Strip-a-set-of-characters-from-a-string/Kotlin/strip-a-set-of-characters-from-a-string.kotlin b/Task/Strip-a-set-of-characters-from-a-string/Kotlin/strip-a-set-of-characters-from-a-string.kotlin new file mode 100644 index 0000000000..c54051816c --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Kotlin/strip-a-set-of-characters-from-a-string.kotlin @@ -0,0 +1,7 @@ +// version 1.0.6 + +fun stripChars(s: String, r: String) = s.replace(Regex("[$r]"), "") + +fun main(args: Array) { + println(stripChars("She was a soul stripper. She took my heart!", "aei")) +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/Lua/strip-a-set-of-characters-from-a-string.lua b/Task/Strip-a-set-of-characters-from-a-string/Lua/strip-a-set-of-characters-from-a-string.lua index 5d7809b879..232d6322d0 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/Lua/strip-a-set-of-characters-from-a-string.lua +++ b/Task/Strip-a-set-of-characters-from-a-string/Lua/strip-a-set-of-characters-from-a-string.lua @@ -1,6 +1,9 @@ function stripchars(str, chrs) - local s = str:gsub("["..chrs.."]", '') + local s = str:gsub("["..chrs:gsub("%W","%%%1").."]", '') return s end print( stripchars( "She was a soul stripper. She took my heart!", "aei" ) ) +--> Sh ws soul strppr. Sh took my hrt! +print( stripchars( "She was a soul stripper. She took my heart!", "a-z" ) ) +--> She ws soul stripper. She took my hert! diff --git a/Task/Strip-a-set-of-characters-from-a-string/MATLAB/strip-a-set-of-characters-from-a-string.m b/Task/Strip-a-set-of-characters-from-a-string/MATLAB/strip-a-set-of-characters-from-a-string.m index 24427e7f74..4aad40de4b 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/MATLAB/strip-a-set-of-characters-from-a-string.m +++ b/Task/Strip-a-set-of-characters-from-a-string/MATLAB/strip-a-set-of-characters-from-a-string.m @@ -1,6 +1,3 @@ - function str = stripchars(str, charlist) - charlist = unique(charlist); - for k=1:length(charlist) - str(str==charlist(k)) = []; - end; - end; +function str = stripchars(str, charlist) + % MATLAB after 2016b: str = erase(str, charlist); + str(ismember(str, charlist)) = ''; diff --git a/Task/Strip-a-set-of-characters-from-a-string/Nimrod/strip-a-set-of-characters-from-a-string.nimrod b/Task/Strip-a-set-of-characters-from-a-string/Nimrod/strip-a-set-of-characters-from-a-string.nimrod deleted file mode 100644 index cc4c11aca0..0000000000 --- a/Task/Strip-a-set-of-characters-from-a-string/Nimrod/strip-a-set-of-characters-from-a-string.nimrod +++ /dev/null @@ -1,9 +0,0 @@ -import strutils - -proc `$` (x: seq[string]): string = - result = x.join("") - -echo(split("She was a soul stripper. She took my heart!", {'a','e','i'}).join("")) - -# using the above proc to overload the toString operator `$` as an alternative to using join() -echo($split("She was a soul stripper. She took my heart!", {'a','e','i'})) diff --git a/Task/Strip-a-set-of-characters-from-a-string/PowerShell/strip-a-set-of-characters-from-a-string.psh b/Task/Strip-a-set-of-characters-from-a-string/PowerShell/strip-a-set-of-characters-from-a-string.psh new file mode 100644 index 0000000000..d765b358a5 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/PowerShell/strip-a-set-of-characters-from-a-string.psh @@ -0,0 +1,2 @@ +'She was a soul stripper. She took my heart!' -replace '[aei]', '' +Sh ws soul strppr. Sh took my hrt! diff --git a/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-5.rexx b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-5.rexx deleted file mode 100644 index b6b9647afd..0000000000 --- a/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-5.rexx +++ /dev/null @@ -1,9 +0,0 @@ -stripchars: Procedure - Parse Arg i,s /* get input and chars to be removed */ - o='' /* initialize result */ - Do While i\=='' /* loop through input */ - Parse Var i c +1 i /* get one character */ - If pos(c,s)=0 Then /* it's not to be removed */ - o=o||c /* append it to the result */ - End - Return o /* return the result */ diff --git a/Task/Strip-a-set-of-characters-from-a-string/Scheme/strip-a-set-of-characters-from-a-string.ss b/Task/Strip-a-set-of-characters-from-a-string/Scheme/strip-a-set-of-characters-from-a-string.ss new file mode 100644 index 0000000000..a36abcc6c5 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Scheme/strip-a-set-of-characters-from-a-string.ss @@ -0,0 +1,27 @@ +(import (scheme base) + (scheme write) + (only (srfi 13) string-delete) + (only (srfi 14) ->char-set)) + +;; implementation in plain Scheme +(define (strip-chars str chars) + (let ((char-list (string->list chars))) + (define (do-strip str-list result) + (cond ((null? str-list) + (reverse result)) + ((member (car str-list) char-list char=?) + (do-strip (cdr str-list) result)) + (else + (do-strip (cdr str-list) (cons (car str-list) result))))) + (list->string + (do-strip (string->list str) '())))) + +(display (strip-chars "She was a soul stripper. She took my heart!" "aei")) +(newline) + +;; using functions in SRFI 13 and SRFI 14 +(define (strip-chars2 str chars) + (string-delete (->char-set chars) str)) + +(display (strip-chars2 "She was a soul stripper. She took my heart!" "aei")) +(newline) diff --git a/Task/Strip-a-set-of-characters-from-a-string/Zkl/strip-a-set-of-characters-from-a-string.zkl b/Task/Strip-a-set-of-characters-from-a-string/Zkl/strip-a-set-of-characters-from-a-string.zkl new file mode 100644 index 0000000000..e26a0dfca8 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Zkl/strip-a-set-of-characters-from-a-string.zkl @@ -0,0 +1,2 @@ +println("She was a soul stripper. She took my heart!" - "aei") +//-->Sh ws soul strppr. Sh took my hrt! diff --git a/Task/Strip-block-comments/jq/strip-block-comments.jq b/Task/Strip-block-comments/Jq/strip-block-comments.jq similarity index 100% rename from Task/Strip-block-comments/jq/strip-block-comments.jq rename to Task/Strip-block-comments/Jq/strip-block-comments.jq diff --git a/Task/Strip-block-comments/Julia/strip-block-comments.julia b/Task/Strip-block-comments/Julia/strip-block-comments.julia new file mode 100644 index 0000000000..6601a5cfc4 --- /dev/null +++ b/Task/Strip-block-comments/Julia/strip-block-comments.julia @@ -0,0 +1,75 @@ +function _stripcomments(txt::AbstractString, dlm::Tuple{String,String}) + "Strips first nest of block comments" + + dlml, dlmr = dlm + indx = searchindex(txt, dlml) + if indx > 0 + out = IOBuffer() + write(out, txt[1:indx-1]) + txt = txt[indx+length(dlml):end] + txt = _stripcomments(txt, dlm) + indx = searchindex(txt, dlmr) + @assert(indx > 0, "cannot find a closer delimiter \"$dlmr\" in $txt") + write(out, txt[indx+length(dlmr):end]) + else + out = txt + end + return String(out) +end + +function stripcomments(txt::AbstractString, dlm::Tuple{String,String}=("/*", "*/")) + "Strips nests of block comments" + + dlml, dlmr = dlm + while contains(txt, dlml) + txt = _stripcomments(txt, dlm) + end + + return txt +end + +function main() + println("\nNON-NESTED BLOCK COMMENT EXAMPLE:") + smpl = """ +/** +* Some comments +* longer comments here that we can parse. +* +* Rahoo +*/ +function subroutine() { +a = /* inline comment */ b + c ; +} +/*/ <-- tricky comments */ + +/** +* Another comment. +*/ +function something() { +} +""" + println(stripcomments(smpl)) + + println("\nNESTED BLOCK COMMENT EXAMPLE:") + smpl = """ +/** +* Some comments +* longer comments here that we can parse. +* +* Rahoo +*//* +function subroutine() { +a = /* inline comment */ b + c ; +} +/*/ <-- tricky comments */ +*/ +/** +* Another comment. +*/ +function something() { +} +""" + println(stripcomments(smpl)) +end + +main() diff --git a/Task/Strip-block-comments/Kotlin/strip-block-comments.kotlin b/Task/Strip-block-comments/Kotlin/strip-block-comments.kotlin new file mode 100644 index 0000000000..fb82c227e6 --- /dev/null +++ b/Task/Strip-block-comments/Kotlin/strip-block-comments.kotlin @@ -0,0 +1,51 @@ +// version 1.1.4-3 + +val sample = """ +/** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + + /** + * Another comment. + */ + function something() { + } +""" + +val sample2 = """ +``{ + ` Some comments + ` longer comments here that we can parse. + ` + ` Rahoo + ``} + function subroutine2() { + d = ``{ inline comment ``} e + f ; + } + ``{ / <-- tricky comments ``} + + ``{ + ` Another comment. + ``} + function something2() { + } +""" + +fun stripBlockComments(text: String, del1: String = "/*", del2: String = "*/"): String { + val d1 = Regex.escape(del1) + val d2 = Regex.escape(del2) + val r = Regex("""(?s)$d1.*?$d2""") + return text.replace(r, "") +} + +fun main(args: Array) { + println(stripBlockComments(sample)) + println(stripBlockComments(sample2, "``{", "``}")) +} diff --git a/Task/Strip-block-comments/Zkl/strip-block-comments.zkl b/Task/Strip-block-comments/Zkl/strip-block-comments.zkl new file mode 100644 index 0000000000..4dd279eb5c --- /dev/null +++ b/Task/Strip-block-comments/Zkl/strip-block-comments.zkl @@ -0,0 +1,4 @@ +fcn stripper(text, a="/*", b="*/"){ + while(xy:=text.span(a,b,True)){ x,y:=xy; text=text[0,x] + text[x+y,*] } + text +} diff --git a/Task/Strip-comments-from-a-string/jq/strip-comments-from-a-string-1.jq b/Task/Strip-comments-from-a-string/Jq/strip-comments-from-a-string-1.jq similarity index 100% rename from Task/Strip-comments-from-a-string/jq/strip-comments-from-a-string-1.jq rename to Task/Strip-comments-from-a-string/Jq/strip-comments-from-a-string-1.jq diff --git a/Task/Strip-comments-from-a-string/jq/strip-comments-from-a-string-2.jq b/Task/Strip-comments-from-a-string/Jq/strip-comments-from-a-string-2.jq similarity index 100% rename from Task/Strip-comments-from-a-string/jq/strip-comments-from-a-string-2.jq rename to Task/Strip-comments-from-a-string/Jq/strip-comments-from-a-string-2.jq diff --git a/Task/Strip-comments-from-a-string/jq/strip-comments-from-a-string-3.jq b/Task/Strip-comments-from-a-string/Jq/strip-comments-from-a-string-3.jq similarity index 100% rename from Task/Strip-comments-from-a-string/jq/strip-comments-from-a-string-3.jq rename to Task/Strip-comments-from-a-string/Jq/strip-comments-from-a-string-3.jq diff --git a/Task/Strip-comments-from-a-string/jq/strip-comments-from-a-string-4.jq b/Task/Strip-comments-from-a-string/Jq/strip-comments-from-a-string-4.jq similarity index 100% rename from Task/Strip-comments-from-a-string/jq/strip-comments-from-a-string-4.jq rename to Task/Strip-comments-from-a-string/Jq/strip-comments-from-a-string-4.jq diff --git a/Task/Strip-comments-from-a-string/Kotlin/strip-comments-from-a-string.kotlin b/Task/Strip-comments-from-a-string/Kotlin/strip-comments-from-a-string.kotlin new file mode 100644 index 0000000000..014b5d2a84 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Kotlin/strip-comments-from-a-string.kotlin @@ -0,0 +1,15 @@ +// version 1.0.6 + +val r = Regex("""(/\*.*\*/|//.*$)""") + +fun stripComments(s: String) = s.replace(r, "").trim() + +fun main(args: Array) { + val strings = arrayOf( + "apples, pears // and bananas", + " apples, pears /* and bananas */", + "/* oranges */ apples // pears and bananas ", + " \toranges /*apples/*, pears*/*/and bananas" + ) + for (string in strings) println(stripComments(string)) +} diff --git a/Task/Strip-comments-from-a-string/Sed/strip-comments-from-a-string.sed b/Task/Strip-comments-from-a-string/Sed/strip-comments-from-a-string.sed new file mode 100644 index 0000000000..32721d56c1 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Sed/strip-comments-from-a-string.sed @@ -0,0 +1,3 @@ +#!/bin/sh +# Strip comments +echo "$1" | sed 's/ *[#;].*$//g' | sed 's/^ *//' diff --git a/Task/Strip-comments-from-a-string/Zkl/strip-comments-from-a-string-1.zkl b/Task/Strip-comments-from-a-string/Zkl/strip-comments-from-a-string-1.zkl new file mode 100644 index 0000000000..d50b5e0a5e --- /dev/null +++ b/Task/Strip-comments-from-a-string/Zkl/strip-comments-from-a-string-1.zkl @@ -0,0 +1,8 @@ +fcn strip(text,c){ // if c in text, remove it and following text + if (Void!=(n:=text.find(c))) text=text[0,n]; + text.strip() // remove leading and trailing white space +} +fcn stripper(text,a,b,c,etc){ // strip a,b,c,etc from text + foreach c in (vm.arglist[1,*]){ text=strip(text,c) } + text +} diff --git a/Task/Strip-comments-from-a-string/Zkl/strip-comments-from-a-string-2.zkl b/Task/Strip-comments-from-a-string/Zkl/strip-comments-from-a-string-2.zkl new file mode 100644 index 0000000000..557e407578 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Zkl/strip-comments-from-a-string-2.zkl @@ -0,0 +1,6 @@ +fcn stripper(text,a,b,c,etc){ + vm.arglist[1,*].reduce('wrap(text,c){ + if (Void!=(n:=text.find(c))) text[0,n] else text + },text) + .strip() +} diff --git a/Task/Strip-comments-from-a-string/Zkl/strip-comments-from-a-string-3.zkl b/Task/Strip-comments-from-a-string/Zkl/strip-comments-from-a-string-3.zkl new file mode 100644 index 0000000000..baded251fa --- /dev/null +++ b/Task/Strip-comments-from-a-string/Zkl/strip-comments-from-a-string-3.zkl @@ -0,0 +1,2 @@ +String(">", strip(" apples, pears # and bananas","#"), "<").println(); +String(">", stripper(" apples, pears ; and # bananas","#",";"), "<").println(); diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/00DESCRIPTION b/Task/Strip-control-codes-and-extended-characters-from-a-string/00DESCRIPTION index ea29f14b96..4a4e938c52 100644 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/00DESCRIPTION +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/00DESCRIPTION @@ -3,6 +3,8 @@ The task is to strip control codes and extended characters from a string. The so * a string with control codes stripped (but extended characters not stripped) * a string with control codes and extended characters stripped -In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ascii table. + +In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table. On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task. +

    diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Gambas/strip-control-codes-and-extended-characters-from-a-string.gambas b/Task/Strip-control-codes-and-extended-characters-from-a-string/Gambas/strip-control-codes-and-extended-characters-from-a-string.gambas new file mode 100644 index 0000000000..8c43ddc66a --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Gambas/strip-control-codes-and-extended-characters-from-a-string.gambas @@ -0,0 +1,31 @@ +Public Sub Main() +Dim sString As String = "The\t \equick\n \fbrownfox \vcost £125.00 or €145.00 or $160.00 \bto \ncapture ©®" +Dim sStd, sExtend As String +Dim siCount As Short + +For siCount = 32 To 126 + sStd &= Chr(siCount) +Next + +For siCount = 128 To 255 + sExtend &= Chr(siCount) +Next + +Print "Original string: -\t" & sString & gb.NewLine +Print "No extended characters: -\t" & Check(sString, sStd) +sStd &= sExtend +Print "With extended characters: -\t" & Check(sString, sStd) + +End +'________________________________________________________________ +Public Sub Check(sString As String, sCheck As String) As String +Dim siCount As Short +Dim sResult As String + +For siCount = 1 To Len(sString) + If InStr(sCheck, Mid(sString, siCount, 1)) Then sResult &= Mid(sString, siCount, 1) +Next + +Return sResult + +End diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Haskell/strip-control-codes-and-extended-characters-from-a-string.hs b/Task/Strip-control-codes-and-extended-characters-from-a-string/Haskell/strip-control-codes-and-extended-characters-from-a-string.hs index b3940dd955..32cc159c68 100644 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/Haskell/strip-control-codes-and-extended-characters-from-a-string.hs +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Haskell/strip-control-codes-and-extended-characters-from-a-string.hs @@ -1,3 +1,11 @@ -import Data.Char +strip :: String -> String +strip = + filter + (\x -- Though use of Data.Char functions like isAlpha, isDigit etc + -- seems more probable. + -> + let o = fromEnum x + in o > 31 && o < 126) -strip = filter (\x -> ord x > 32 && ord x < 126) +main :: IO () +main = print $ strip "alphabetic 字母 with some less parochial parts" diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/jq/strip-control-codes-and-extended-characters-from-a-string-1.jq b/Task/Strip-control-codes-and-extended-characters-from-a-string/Jq/strip-control-codes-and-extended-characters-from-a-string-1.jq similarity index 100% rename from Task/Strip-control-codes-and-extended-characters-from-a-string/jq/strip-control-codes-and-extended-characters-from-a-string-1.jq rename to Task/Strip-control-codes-and-extended-characters-from-a-string/Jq/strip-control-codes-and-extended-characters-from-a-string-1.jq diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/jq/strip-control-codes-and-extended-characters-from-a-string-2.jq b/Task/Strip-control-codes-and-extended-characters-from-a-string/Jq/strip-control-codes-and-extended-characters-from-a-string-2.jq similarity index 100% rename from Task/Strip-control-codes-and-extended-characters-from-a-string/jq/strip-control-codes-and-extended-characters-from-a-string-2.jq rename to Task/Strip-control-codes-and-extended-characters-from-a-string/Jq/strip-control-codes-and-extended-characters-from-a-string-2.jq diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/jq/strip-control-codes-and-extended-characters-from-a-string-3.jq b/Task/Strip-control-codes-and-extended-characters-from-a-string/Jq/strip-control-codes-and-extended-characters-from-a-string-3.jq similarity index 100% rename from Task/Strip-control-codes-and-extended-characters-from-a-string/jq/strip-control-codes-and-extended-characters-from-a-string-3.jq rename to Task/Strip-control-codes-and-extended-characters-from-a-string/Jq/strip-control-codes-and-extended-characters-from-a-string-3.jq diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Kotlin/strip-control-codes-and-extended-characters-from-a-string.kotlin b/Task/Strip-control-codes-and-extended-characters-from-a-string/Kotlin/strip-control-codes-and-extended-characters-from-a-string.kotlin new file mode 100644 index 0000000000..64fdecfe2e --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Kotlin/strip-control-codes-and-extended-characters-from-a-string.kotlin @@ -0,0 +1,22 @@ +// version 1.1.2 + +fun String.strip(extendedChars: Boolean = false): String { + val sb = StringBuilder() + for (c in this) { + val i = c.toInt() + if (i in 32..126 || (!extendedChars && i >= 128)) sb.append(c) + } + return sb.toString() +} + +fun main(args: Array) { + println("Originally:") + val s = "123\tabc\u0007DEF\u007F+-*/€æŧðłþ" + println("String = $s Length = ${s.length}") + println("\nAfter stripping control characters:") + val t = s.strip() + println("String = $t Length = ${t.length}") + println("\nAfter stripping control and extended characters:") + val u = s.strip(true) + println("String = $u Length = ${u.length}") +} diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-1.psh b/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-1.psh new file mode 100644 index 0000000000..1ef63cb353 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-1.psh @@ -0,0 +1,47 @@ +function Remove-Character +{ + [CmdletBinding(DefaultParameterSetName="Control and Extended")] + [OutputType([string])] + Param + ( + [Parameter(Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true, + Position=0)] + [string] + $String, + + [Parameter(ParameterSetName="Control")] + [switch] + $Control, + + [Parameter(ParameterSetName="Extended")] + [switch] + $Extended + ) + + Begin + { + filter Remove-ControlCharacter + { + $_.ToCharArray() | ForEach-Object -Begin {$out = ""} -Process {if (-not [Char]::IsControl($_)) {$out += $_ }} -End {$out} + } + + filter Remove-ExtendedCharacter + { + $_.ToCharArray() | ForEach-Object -Begin {$out = ""} -Process {if ([int]$_ -lt 127) {$out += $_ }} -End {$out} + } + } + Process + { + foreach ($s in $String) + { + switch ($PSCmdlet.ParameterSetName) + { + "Control" {$s | Remove-ControlCharacter} + "Extended" {$s | Remove-ExtendedCharacter} + Default {$s | Remove-ExtendedCharacter | Remove-ControlCharacter} + } + } + } +} diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-2.psh b/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-2.psh new file mode 100644 index 0000000000..562c68caab --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-2.psh @@ -0,0 +1,6 @@ +$test = "$([char]9)Français." + +"Original string : `"$test`"" +"Control characters stripped : `"$($test | Remove-Character -Control)`"" +"Extended characters stripped : `"$($test | Remove-Character -Extended)`"" +"Control & extended stripped : `"$($test | Remove-Character)`"" diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-3.psh b/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-3.psh new file mode 100644 index 0000000000..e82ec4b553 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-3.psh @@ -0,0 +1 @@ +"Français", "Čeština" | Remove-Character -Extended diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Protium/strip-control-codes-and-extended-characters-from-a-string-1.protium b/Task/Strip-control-codes-and-extended-characters-from-a-string/Protium/strip-control-codes-and-extended-characters-from-a-string-1.protium deleted file mode 100644 index bcdad30b2f..0000000000 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/Protium/strip-control-codes-and-extended-characters-from-a-string-1.protium +++ /dev/null @@ -1,8 +0,0 @@ -Create variable with control characters: <@ SAYLETVARLIT>i|This string has control characters - - - - - - - - -in it -Strip control characters <@ SAYSALVAR>i -Assign infix <@ LETVARSALVAR>j|i <@ SAYVAR>j -Assign prepend <@ LETSALVARVAR>k|i <@ SAYVAR>k -Reflexive assign <@ ACTSALVAR>i <@ SAYVAR>i diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Protium/strip-control-codes-and-extended-characters-from-a-string-2.protium b/Task/Strip-control-codes-and-extended-characters-from-a-string/Protium/strip-control-codes-and-extended-characters-from-a-string-2.protium deleted file mode 100644 index d2b71f8c11..0000000000 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/Protium/strip-control-codes-and-extended-characters-from-a-string-2.protium +++ /dev/null @@ -1,5 +0,0 @@ -Create variable with high and low ANSI: <@ SAYLETVARLIT>i|This string has both low ansi and high ansi characters - il doit d'être prévenu -Strip high ANSI <@ SAYSAHVAR>i -Assign infix <@ LETVARSAHVAR>j|i <@ SAYVAR>j -Assign prepend <@ LETSAHVARVAR>k|i <@ SAYVAR>k -Reflexive assign <@ ACTSAHVAR>i <@ SAYVAR>i diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/REXX/strip-control-codes-and-extended-characters-from-a-string-1.rexx b/Task/Strip-control-codes-and-extended-characters-from-a-string/REXX/strip-control-codes-and-extended-characters-from-a-string-1.rexx index 8447a19895..9964c2d271 100644 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/REXX/strip-control-codes-and-extended-characters-from-a-string-1.rexx +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/REXX/strip-control-codes-and-extended-characters-from-a-string-1.rexx @@ -1,18 +1,10 @@ /*REXX program strips all "control codes" from a character string (ASCII or EBCDIC). */ -xxx= 'string of ☺☻♥♦⌂, may include control characters and other ilk.♫☼§►↔◄' - /*in EBCDIC, the digit 1 is 'f1'x, */ - /* " ASCII, " " " " 31'x. */ -ebcdic= (1=='f1'x) /*is this an EBCDIC computer ? */ - /*generate a string of characters from */ - /*'00'x ──► [1 just before the blank].*/ -ccChars = xrange(,d2c(c2d(' ') -1)) /*generate a range of characters. */ -if \ebcdic then ccChars=ccChars'7f'x /*add the ASCII '7f'X character. */ -say 'hex ccChars =' c2x(ccChars) /*might as well do a display of ccChars*/ -ccCharsX = ccChars'ff'x /*add a "stop" character for ccCharsX*/ +z= 'string of ☺☻♥♦⌂, may include control characters and other ♫☼§►↔◄░▒▓█┌┴┐±÷²¬└┬┘ilk.' +@=' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~' +$= + do j=1 for length(z); _=substr(z, j, 1) /*get a char from X one at a time. */ + if verify(_, @)==0 then $=$ || _ /*Is char in the @ list? Then use it.*/ + end /*j*/ /*stick a fork in it, we're all done. */ -_stop= substr(ccCharsX,verify(ccCharsX, xxx), 1) /*find a "stop" character. */ -yyy = translate(space(translate(xxx, _stop, " "ccChars), 0), , _stop) - -say 'old = »»»'xxx"«««" /*add ««fence»» before & after old text*/ -say 'new = »»»'yyy"«««" /* " " " " " new " */ - /*stick a fork in it, we're all done. */ +say 'old = »»»'z"«««" /*add ««fence»» before & after old text*/ +say 'new = »»»'$"«««" /* " " " " " new " */ diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/REXX/strip-control-codes-and-extended-characters-from-a-string-2.rexx b/Task/Strip-control-codes-and-extended-characters-from-a-string/REXX/strip-control-codes-and-extended-characters-from-a-string-2.rexx index 8b1c8aaa11..f7c58f2aae 100644 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/REXX/strip-control-codes-and-extended-characters-from-a-string-2.rexx +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/REXX/strip-control-codes-and-extended-characters-from-a-string-2.rexx @@ -1,20 +1,11 @@ /*REXX program strips all "control codes" from a character string (ASCII or EBCDIC). */ -xxx= 'string of ☺☻♥♦⌂, may include control characters and other ilk.♫☼§►↔◄' - /*in EBCDIC, the digit 1 is 'f1'x, */ - /* " ASCII, " " " " 31'x. */ -ascii= ('31'x==1) /*is this an ASCII computer? */ - /*generate a string of characters from */ - /*'00'x ──► [1 just before the blank].*/ -ccChars = xrange(, d2c(c2d(' ') -1) ) /*generate a range of characters. */ -if ascii then ccChars=ccChars'7f'x /*add the ASCII '7f'X character. */ -say 'hex ccChars =' c2x(ccChars) /*might as well do a display of ccChars*/ -yyy= /*start with a clean slate. */ - do j=1 for length(xxx) /*build a new string, 1 byte at a time.*/ - _=substr(xxx, j, 1) /*get next character in the old string.*/ - if pos(_, ccChars)\==0 then iterate /*skip this character, it's a no-no. */ - yyy = yyy || _ /*we found a good and decent character.*/ - end +x= 'string of ☺☻♥♦⌂, may include control characters and other ♫☼§►↔◄░▒▓█┌┴┐±÷²¬└┬┘ilk.' +@=' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghij' || , + 'klmnopqrstuvwxyz{|}~' +$=x /*set "new" string to same as the old. */ + do until _=0; _=verify($, @) /*check if any character isn't in @.*/ + if _\==0 then $=delstr($, _, 1) /*Is this a bad char? Then delete it.*/ + end /*until*/ /*stick a fork in it, we're all done. */ -say 'old = »»»'xxx"«««" /*add ««fence»» before & after old text*/ -say 'new = »»»'yyy"«««" /* " " " " " new " */ - /*stick a fork in it, we're all done. */ +say 'old = »»»' || x || "«««" /*add ««fence»» before & after old text*/ +say 'new = »»»' || $ || "«««" /* " " " " " new " */ diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Sidef/strip-control-codes-and-extended-characters-from-a-string.sidef b/Task/Strip-control-codes-and-extended-characters-from-a-string/Sidef/strip-control-codes-and-extended-characters-from-a-string.sidef index 9fba4dd0f0..82d37d3906 100644 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/Sidef/strip-control-codes-and-extended-characters-from-a-string.sidef +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Sidef/strip-control-codes-and-extended-characters-from-a-string.sidef @@ -1,10 +1,10 @@ -var str = "\ba\x00b\n\rc\fd\xc3\x7ffoo"; +var str = "\ba\x00b\n\rc\fd\xc3\x7ffoo" -var letters = str.chars»ord»(); -say letters»chr»().join.dump; +var letters = str.chars.map{.ord} +say letters.map{.chr}.join.dump -var nocontrols = letters.grep{ (_ > 32) && (_ != 127) }; -say nocontrols»chr»().join.dump; +var nocontrols = letters.grep{ (_ > 32) && (_ != 127) } +say nocontrols.map{.chr}.join.dump -var noextended = nocontrols.grep{ _ < 127 }; -say noextended»chr»().join.dump; +var noextended = nocontrols.grep{ _ < 127 } +say noextended.map{.chr}.join.dump diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Zkl/strip-control-codes-and-extended-characters-from-a-string.zkl b/Task/Strip-control-codes-and-extended-characters-from-a-string/Zkl/strip-control-codes-and-extended-characters-from-a-string.zkl new file mode 100644 index 0000000000..685da7fc0b --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Zkl/strip-control-codes-and-extended-characters-from-a-string.zkl @@ -0,0 +1,8 @@ +var ctlCodes=([1..31].pump(String,"toChar") +(127).toChar()); +var extdChars=[127..255].pump(String,"toChar"); + +var test = "string of ☺☻♥♦⌂, control characters(\t\b\e) and other ilk.♫☼§►↔◄"; +test.println("<< test string"); +(test-ctlCodes).println("<< no control chars"); +(test-extdChars).println("<< no extended chars"); +(test-extdChars-ctlCodes).println("<< text"); diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/AppleScript/strip-whitespace-from-a-string-top-and-tail-1.applescript b/Task/Strip-whitespace-from-a-string-Top-and-tail/AppleScript/strip-whitespace-from-a-string-top-and-tail-1.applescript index c00802af58..7256e52580 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/AppleScript/strip-whitespace-from-a-string-top-and-tail-1.applescript +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/AppleScript/strip-whitespace-from-a-string-top-and-tail-1.applescript @@ -1,12 +1,12 @@ use framework "Foundation" -- "OS X" Yosemite onwards, for NSRegularExpression +-- STRIP WHITESPACE ---------------------------------------------------------- -- isSpace :: Char -> Bool on isSpace(c) ((length of c) = 1) and regexTest("\\s", c) end isSpace - -- stripStart :: Text -> Text on stripStart(s) dropWhile(isSpace, s) as text @@ -23,14 +23,14 @@ on strip(s) end strip --- TEST +-- TEST ---------------------------------------------------------------------- on run set strText to " \t\t \n \r Much Ado About Nothing \t \n \r " script arrowed - on lambda(x) + on |λ|(x) "-->" & x & "<--" - end lambda + end |λ| end script map(arrowed, [stripStart(strText), stripEnd(strText), strip(strText)]) @@ -43,15 +43,19 @@ on run end run +-- GENERIC FUNCTIONS --------------------------------------------------------- --- GENERIC FUNCTIONS +-- dropAround :: (Char -> Bool) -> [a] -> [a] +on dropAround(p, xs) + dropWhile(p, dropWhileEnd(p, xs)) +end dropAround -- dropWhile :: (a -> Bool) -> [a] -> [a] on dropWhile(p, xs) tell mReturn(p) set lng to length of xs set i to 1 - repeat while i ≤ lng and lambda(item i of xs) + repeat while i ≤ lng and |λ|(item i of xs) set i to i + 1 end repeat end tell @@ -66,7 +70,7 @@ end dropWhile on dropWhileEnd(p, xs) tell mReturn(p) set i to length of xs - repeat while i > 0 and lambda(item i of xs) + repeat while i > 0 and |λ|(item i of xs) set i to i - 1 end repeat end tell @@ -77,28 +81,13 @@ on dropWhileEnd(p, xs) end if end dropWhileEnd --- dropAround :: (Char -> Bool) -> [a] -> [a] -on dropAround(p, xs) - dropWhile(p, dropWhileEnd(p, xs)) -end dropAround - --- regexTest :: RegexPattern -> String -> Bool -on regexTest(strRegex, str) - set ca to current application - set oString to ca's NSString's stringWithString:str - ((ca's NSRegularExpression's regularExpressionWithPattern:strRegex ¬ - options:((ca's NSRegularExpressionAnchorsMatchLines as integer)) ¬ - |error|:(missing value))'s firstMatchInString:oString options:0 ¬ - range:{location:0, |length|:oString's |length|()}) is not missing value -end regexTest - -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -111,7 +100,17 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn + +-- regexTest :: RegexPattern -> String -> Bool +on regexTest(strRegex, str) + set ca to current application + set oString to ca's NSString's stringWithString:str + ((ca's NSRegularExpression's regularExpressionWithPattern:strRegex ¬ + options:((ca's NSRegularExpressionAnchorsMatchLines as integer)) ¬ + |error|:(missing value))'s firstMatchInString:oString options:0 ¬ + range:{location:0, |length|:oString's |length|()}) is not missing value +end regexTest diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail.cobol b/Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail-1.cobol similarity index 100% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail.cobol rename to Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail-1.cobol diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail-2.cobol b/Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail-2.cobol new file mode 100644 index 0000000000..c138de4d0d --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail-2.cobol @@ -0,0 +1,3 @@ +DISPLAY "'" FUNCTION TRIML(str) "'" +DISPLAY "'" FUNCTION TRIMR(str) "'" +DISPLAY "'" FUNCTION TRIM(str) "'" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Gambas/strip-whitespace-from-a-string-top-and-tail.gambas b/Task/Strip-whitespace-from-a-string-Top-and-tail/Gambas/strip-whitespace-from-a-string-top-and-tail.gambas new file mode 100644 index 0000000000..db36a99967 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Gambas/strip-whitespace-from-a-string-top-and-tail.gambas @@ -0,0 +1,9 @@ +Public Sub Main() +Dim sString As String = " Hello world! " + +Print sString & "\tString length = " & Len(sString) & " - Original string" +Print LTrim(sString) & "\tString length = " & Len(LTrim(sString)) & " - String with leading whitespace removed" +Print RTrim(sString) & "\tString length = " & Len(RTrim(sString)) & " - String with trailing whitespace removed" +Print Trim(sString) & "\t\tString length = " & Len(Trim(sString)) & " - String with both leading and trailing whitespace removed" + +End diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/JavaScript/strip-whitespace-from-a-string-top-and-tail-1.js b/Task/Strip-whitespace-from-a-string-Top-and-tail/JavaScript/strip-whitespace-from-a-string-top-and-tail-1.js new file mode 100644 index 0000000000..866abf11fe --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/JavaScript/strip-whitespace-from-a-string-top-and-tail-1.js @@ -0,0 +1,11 @@ +{ + let s = " \t String with spaces \t "; + // a future version of ECMAScript will have trimStart(). Some current + // implementations have trimLeft(). + console.log("original: '" + s + "'"); + console.log("trimmed left: '" + s.replace(/^\s+/,'') + "'"); + // a future version of ECMAScript will have trimEnd(). Some current + // implementations have trimRight(). + console.log("trimmed right: '" + s.replace(/\s+$/,'') + "'"); + console.log("trimmed both: '" + s.trim() + "'"); + } diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/JavaScript/strip-whitespace-from-a-string-top-and-tail-2.js b/Task/Strip-whitespace-from-a-string-Top-and-tail/JavaScript/strip-whitespace-from-a-string-top-and-tail-2.js new file mode 100644 index 0000000000..b9de63063c --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/JavaScript/strip-whitespace-from-a-string-top-and-tail-2.js @@ -0,0 +1,48 @@ +(() => { + 'use strict'; + + // stripStart :: Text -> Text + let stripStart = s => dropWhile(isSpace, s); + + // stripEnd :: Text -> Text + let stripEnd = s => dropWhileEnd(isSpace, s); + + // strip :: Text -> Text + let strip = s => dropAround(isSpace, s); + // OR: let strip = s => s.trim(); + + + + // GENERIC FUNCTIONS + + // dropAround :: (Char -> Bool) -> Text -> Text + let dropAround = (p, s) => dropWhile(p, dropWhileEnd(p, s)); + + // dropWhile :: (a -> Bool) -> [a] -> [a] + let dropWhile = (p, xs) => { + for (var i = 0, lng = xs.length; + (i < lng) && p(xs[i]); i++) {} + return xs.slice(i); + } + + // dropWhileEnd :: (Char -> Bool) -> Text -> Text + let dropWhileEnd = (p, s) => { + for (var i = s.length; i-- && p(s[i]);) {} + return s.slice(0, i + 1); + } + + // isSpace :: Char -> Bool + let isSpace = c => /\s/.test(c); + + // show :: a -> String + let show = x => JSON.stringify(x, null, 2); + + + // TEST + + let strText = " \t\t \n \r Much Ado About Nothing \t \n \r "; + + return show([stripStart, stripEnd, strip] + .map(f => '-->' + f(strText) + '<--')); + +})(); diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/jq/strip-whitespace-from-a-string-top-and-tail-1.jq b/Task/Strip-whitespace-from-a-string-Top-and-tail/Jq/strip-whitespace-from-a-string-top-and-tail-1.jq similarity index 100% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/jq/strip-whitespace-from-a-string-top-and-tail-1.jq rename to Task/Strip-whitespace-from-a-string-Top-and-tail/Jq/strip-whitespace-from-a-string-top-and-tail-1.jq diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/jq/strip-whitespace-from-a-string-top-and-tail-2.jq b/Task/Strip-whitespace-from-a-string-Top-and-tail/Jq/strip-whitespace-from-a-string-top-and-tail-2.jq similarity index 100% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/jq/strip-whitespace-from-a-string-top-and-tail-2.jq rename to Task/Strip-whitespace-from-a-string-Top-and-tail/Jq/strip-whitespace-from-a-string-top-and-tail-2.jq diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/jq/strip-whitespace-from-a-string-top-and-tail-3.jq b/Task/Strip-whitespace-from-a-string-Top-and-tail/Jq/strip-whitespace-from-a-string-top-and-tail-3.jq similarity index 100% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/jq/strip-whitespace-from-a-string-top-and-tail-3.jq rename to Task/Strip-whitespace-from-a-string-Top-and-tail/Jq/strip-whitespace-from-a-string-top-and-tail-3.jq diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Kotlin/strip-whitespace-from-a-string-top-and-tail.kotlin b/Task/Strip-whitespace-from-a-string-Top-and-tail/Kotlin/strip-whitespace-from-a-string-top-and-tail.kotlin new file mode 100644 index 0000000000..6026dbe11c --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Kotlin/strip-whitespace-from-a-string-top-and-tail.kotlin @@ -0,0 +1,9 @@ +// version 1.0.6 + +fun main(args: Array) { + val s = " \tRosetta Code \r\n" + println("Untrimmed => $s") + println("Left Trimmed => ${s.trimStart()}") + println("Right Trimmed => ${s.trimEnd()}") + println("Fully Trimmed => ${s.trim()}") +} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rust b/Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rust index 90336f9902..f33f00c23c 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rust +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rust @@ -1,9 +1,8 @@ fn main() { - let string = "String without spaces"; - let spaces = " \x0B\t\r\n \u{A0} \u{2000} \u{3000} "; - let string_with_spaces = spaces.to_string() + string + spaces; + let spaces = " \t\n\x0B\x0C\r \u{A0} \u{2000}\u{3000}"; + let string_with_spaces = spaces.to_owned() + "String without spaces" + spaces; - assert_eq!(string_with_spaces.trim(), string); - assert_eq!(string_with_spaces.trim_left().to_string(), string.to_string() + spaces); - assert_eq!(string_with_spaces.trim_right().to_string(), spaces.to_string() + string); + assert_eq!(string_with_spaces.trim(), "String without spaces"); + assert_eq!(string_with_spaces.trim_left(), "String without spaces".to_owned() + spaces); + assert_eq!(string_with_spaces.trim_right(), spaces.to_owned() + "String without spaces"); } diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Zkl/strip-whitespace-from-a-string-top-and-tail-1.zkl b/Task/Strip-whitespace-from-a-string-Top-and-tail/Zkl/strip-whitespace-from-a-string-top-and-tail-1.zkl new file mode 100644 index 0000000000..f7d035c21f --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Zkl/strip-whitespace-from-a-string-top-and-tail-1.zkl @@ -0,0 +1 @@ +"\t\n hoho\n\t\ ".strip() //-->"hoho" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Zkl/strip-whitespace-from-a-string-top-and-tail-2.zkl b/Task/Strip-whitespace-from-a-string-Top-and-tail/Zkl/strip-whitespace-from-a-string-top-and-tail-2.zkl new file mode 100644 index 0000000000..53481b77dd --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Zkl/strip-whitespace-from-a-string-top-and-tail-2.zkl @@ -0,0 +1,5 @@ +fcn removeLeadingWS(s){ n:=0; + try{ while(s[n].isSpace()){ n+=1 } }catch{""}fallthrough{ s[n,*] } +} +removeLeadingWS("\t\n hoho\n\t\ ") //-->"hoho\n\t " +removeLeadingWS("") //-->"" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Zkl/strip-whitespace-from-a-string-top-and-tail-3.zkl b/Task/Strip-whitespace-from-a-string-Top-and-tail/Zkl/strip-whitespace-from-a-string-top-and-tail-3.zkl new file mode 100644 index 0000000000..1c3d999f45 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Zkl/strip-whitespace-from-a-string-top-and-tail-3.zkl @@ -0,0 +1,5 @@ +fcn removeTrailingWS(s){ n:=-1; + try{ while(s[n].isSpace()){ n-=1 } s[0,n+1] }catch{""} +} +removeTrailingWS("\t\n hoho\n\t\ ") //-->"\t\n hoho" +removeTrailingWS("\t\n \n\t\ ") //-->"" diff --git a/Task/Substring-Top-and-tail/360-Assembly/substring-top-and-tail.360 b/Task/Substring-Top-and-tail/360-Assembly/substring-top-and-tail.360 new file mode 100644 index 0000000000..dd70a31b4e --- /dev/null +++ b/Task/Substring-Top-and-tail/360-Assembly/substring-top-and-tail.360 @@ -0,0 +1,27 @@ +* Substring/Top and tail 04/03/2017 +SUBSTRTT CSECT + USING SUBSTRTT,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability +* + XPRNT S8,L'S8 print s8 + MVC S7,S8+1 s7=substr(s8,2,7) + XPRNT S7,L'S7 print s7 + MVC S7,S8 s7=substr(s8,1,7) + XPRNT S7,L'S7 print s7 + MVC S6,S8+1 s6=substr(s8,2,6) + XPRNT S6,L'S6 print s6 +* + L R13,4(0,R13) epilog + LM R14,R12,12(R13) restore previous context + XR R15,R15 rc=0 + BR R14 exit +S8 DC CL8'12345678' +S7 DS CL7 +S6 DS CL6 + YREGS + END SUBSTRTT diff --git a/Task/Substring-Top-and-tail/Ada/substring-top-and-tail.ada b/Task/Substring-Top-and-tail/Ada/substring-top-and-tail-1.ada similarity index 100% rename from Task/Substring-Top-and-tail/Ada/substring-top-and-tail.ada rename to Task/Substring-Top-and-tail/Ada/substring-top-and-tail-1.ada diff --git a/Task/Substring-Top-and-tail/Ada/substring-top-and-tail-2.ada b/Task/Substring-Top-and-tail/Ada/substring-top-and-tail-2.ada new file mode 100644 index 0000000000..88cba96406 --- /dev/null +++ b/Task/Substring-Top-and-tail/Ada/substring-top-and-tail-2.ada @@ -0,0 +1,33 @@ +with Ada.Text_IO; +with Ada.Strings.UTF_Encoding.Wide_Strings; + +procedure Remove_Characters +is + use Ada.Text_IO; + use Ada.Strings.UTF_Encoding; + use Ada.Strings.UTF_Encoding.Wide_Strings; + + S : String := "upraisers"; + U : Wide_String := Decode (UTF_8_String'(S)); + + function To_String (X : Wide_String)return String + is + begin + return String (UTF_8_String'(Encode (X))); + end To_String; + +begin + Put_Line + (To_String + ("Full String: """ & U & """")); + Put_Line + (To_String + ("Without_First: """ & U (U'First + 1 .. U'Last) & """")); + Put_Line + (To_String + ("Without_Last: """ & U (U'First .. U'Last - 1) & """")); + Put_Line + (To_String + ("Without_Both: """ & U (U'First + 1 .. U'Last - 1) & """")); + +end Remove_Characters; diff --git a/Task/Substring-Top-and-tail/BASIC/substring-top-and-tail.basic b/Task/Substring-Top-and-tail/BASIC/substring-top-and-tail-1.basic similarity index 100% rename from Task/Substring-Top-and-tail/BASIC/substring-top-and-tail.basic rename to Task/Substring-Top-and-tail/BASIC/substring-top-and-tail-1.basic diff --git a/Task/Substring-Top-and-tail/BASIC/substring-top-and-tail-2.basic b/Task/Substring-Top-and-tail/BASIC/substring-top-and-tail-2.basic new file mode 100644 index 0000000000..c35df68e26 --- /dev/null +++ b/Task/Substring-Top-and-tail/BASIC/substring-top-and-tail-2.basic @@ -0,0 +1,8 @@ +10 REM STRING SLICING EXAMPLE +20 LET S$="KNIGHTS" +30 REM WITH FIRST CHARACTER REMOVED: +40 PRINT S$(2 TO ) +50 REM WITH LAST CHARACTER REMOVED: +60 PRINT S$( TO LEN S$-1) +70 REM WITH BOTH REMOVED: +80 PRINT S$(2 TO LEN S$-1) diff --git a/Task/Substring-Top-and-tail/Haskell/substring-top-and-tail-3.hs b/Task/Substring-Top-and-tail/Haskell/substring-top-and-tail-3.hs new file mode 100644 index 0000000000..b44d983877 --- /dev/null +++ b/Task/Substring-Top-and-tail/Haskell/substring-top-and-tail-3.hs @@ -0,0 +1,2 @@ +main :: IO () +main = mapM_ print $ [tail, init, init . tail] <*> ["knights"] diff --git a/Task/Substring-Top-and-tail/jq/substring-top-and-tail-1.jq b/Task/Substring-Top-and-tail/Jq/substring-top-and-tail-1.jq similarity index 100% rename from Task/Substring-Top-and-tail/jq/substring-top-and-tail-1.jq rename to Task/Substring-Top-and-tail/Jq/substring-top-and-tail-1.jq diff --git a/Task/Substring-Top-and-tail/jq/substring-top-and-tail-2.jq b/Task/Substring-Top-and-tail/Jq/substring-top-and-tail-2.jq similarity index 100% rename from Task/Substring-Top-and-tail/jq/substring-top-and-tail-2.jq rename to Task/Substring-Top-and-tail/Jq/substring-top-and-tail-2.jq diff --git a/Task/Substring-Top-and-tail/Kotlin/substring-top-and-tail.kotlin b/Task/Substring-Top-and-tail/Kotlin/substring-top-and-tail.kotlin new file mode 100644 index 0000000000..79bddf364e --- /dev/null +++ b/Task/Substring-Top-and-tail/Kotlin/substring-top-and-tail.kotlin @@ -0,0 +1,7 @@ +// version 1.0.6 +fun main(args: Array) { + val s = "Rosetta" + println(s.drop(1)) + println(s.dropLast(1)) + println(s.drop(1).dropLast(1)) +} diff --git a/Task/Substring-Top-and-tail/Nimrod/substring-top-and-tail.nimrod b/Task/Substring-Top-and-tail/Nimrod/substring-top-and-tail.nimrod deleted file mode 100644 index a4673a35d3..0000000000 --- a/Task/Substring-Top-and-tail/Nimrod/substring-top-and-tail.nimrod +++ /dev/null @@ -1,6 +0,0 @@ -var s = "The quick μ brown fox" -echo(s.substr(1)) -echo(s.substr(0,s.len-2)) -echo(s.substr(1,s.len-2)) -# using slices -echo(s[1 .. -2]) diff --git a/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail-1.pl6 b/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail-1.pl6 deleted file mode 100644 index 4f2c696ad4..0000000000 --- a/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail-1.pl6 +++ /dev/null @@ -1,8 +0,0 @@ -say substr('knight', 1); # strip first character - sub -say 'knight'.substr(1); # strip first character - method - -say substr('socks', 0, -1); # strip last character - sub -say 'socks'.substr( 0, -1); # strip last character - method - -say substr('brooms', 1, -1); # strip both first and last characters - sub -say 'brooms'.substr(1, -1); # strip both first and last characters - method diff --git a/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail-2.pl6 b/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail-2.pl6 deleted file mode 100644 index 73c1892179..0000000000 --- a/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail-2.pl6 +++ /dev/null @@ -1,5 +0,0 @@ -my $string = 'ouch'; -say $string.chop; # ouc - does not modify original $string -say $string; # ouch -say $string.p5chop; # h - returns the character chopped off and modifies $string -say $string; # ouc diff --git a/Task/Substring-Top-and-tail/Zkl/substring-top-and-tail.zkl b/Task/Substring-Top-and-tail/Zkl/substring-top-and-tail.zkl new file mode 100644 index 0000000000..1c1f88ecc0 --- /dev/null +++ b/Task/Substring-Top-and-tail/Zkl/substring-top-and-tail.zkl @@ -0,0 +1,3 @@ +"Smiles"[1,*] //-->miles +"Smiles"[0,-1] //-->Smile +"Smiles"[1,-1] //-->mile diff --git a/Task/Substring/AppleScript/substring.applescript b/Task/Substring/AppleScript/substring.applescript index 527df36daf..c9d695c2fa 100644 --- a/Task/Substring/AppleScript/substring.applescript +++ b/Task/Substring/AppleScript/substring.applescript @@ -1,4 +1,4 @@ --- SUBSTRING PRIMITIVES +-- SUBSTRINGS ----------------------------------------------------------------- -- take :: Int -> Text -> Text on take(n, s) @@ -28,8 +28,7 @@ on init(s) end init --- TEST - +-- TEST ----------------------------------------------------------------------- on run set str to "一二三四五六七八九十" @@ -50,9 +49,9 @@ on run script tabulate property strPad : " " - on lambda(l, r) + on |λ|(l, r) l & drop(length of l, strPad) & r - end lambda + end |λ| end script linefeed & intercalate(linefeed, ¬ @@ -60,25 +59,7 @@ on run legends, parts)) & linefeed end run - - --- GENERIC LIBRARY FUNCTIONS – FOR FORMATTING RESULTS - --- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -on zipWith(f, xs, ys) - set lng to length of xs - if lng is not length of ys then - missing value - else - tell mReturn(f) - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, item i of ys) - end repeat - return lst - end tell - end if -end zipWith +-- GENERIC FUNCTIONS FOR TEST ------------------------------------------------- -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) @@ -88,6 +69,15 @@ on intercalate(strText, lstText) return strJoined end intercalate +-- min :: Ord a => a -> a -> a +on min(x, y) + if y < x then + y + else + x + end if +end min + -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) @@ -95,7 +85,19 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn + +-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] +on zipWith(f, xs, ys) + set lng to min(length of xs, length of ys) + set lst to {} + tell mReturn(f) + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, item i of ys) + end repeat + return lst + end tell +end zipWith diff --git a/Task/Substring/BASIC/substring-2.basic b/Task/Substring/BASIC/substring-2.basic index 27521e04fe..8bfee61302 100644 --- a/Task/Substring/BASIC/substring-2.basic +++ b/Task/Substring/BASIC/substring-2.basic @@ -1,13 +1,30 @@ -10 LET A$="abcdefghijklmnopqrstuvwxyz" -15 LET n=10: LET m=7 -20 PRINT A$(n TO n+m-1) -30 PRINT A$(n TO ) -40 PRINT A$( TO LEN (A$)-1) -50 FOR i=1 TO LEN (A$) -60 IF A$(i)="g" THEN PRINT A$(i TO i+m-1): LET i=LEN (A$): GO TO 70 -70 NEXT i -80 LET B$="ijk" -90 FOR i=1 TO LEN (A$)-LEN (B$)+1 -100 IF A$(i TO i+LEN (B$)-1)=B$ THEN PRINT A$(i TO i+m-1): LET i=LEN (A$)-LEN (B$)+1: GO TO 110 -110 NEXT i -120 STOP +10 REM SUBSTRING ... ROSETTACODE.ORG +20 A$ = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG" +30 X$ = "J" : S$ = "FOX" +40 N = 5: M = 11 +50 PRINT "THE STRING:" +60 PRINT A$ +70 PRINT +80 PRINT "SUBSTRING STARTING FROM" N "CHARACTERS IN AND OF" M "LENGTH:" +90 PRINT MID$(A$,N,M) +100 PRINT +110 PRINT "STARTING FROM" N "CHARACTERS IN, UP TO THE END OF THE STRING:" +120 PRINT RIGHT$(A$,LEN(A$)+1-N) +130 PRINT +140 PRINT "WHOLE STRING MINUS LAST CHARACTER:" +150 PRINT LEFT$(A$,LEN(A$)-1) +160 PRINT +170 PRINT "STARTING FROM '";X$;"' AND OF" M "LENGTH:" +180 I = 1 +190 IF MID$(A$,I,1)=X$ THEN 220 +200 I = I+1 +210 GOTO 190 +220 PRINT RIGHT$(A$,LEN(A$)+1-I) +230 PRINT +240 PRINT "STARTING FROM '";S$;"' AND OF" M "LENGTH:" +250 I = 1 +260 IF MID$(A$,I,LEN(S$))=S$ THEN 290 +270 I = I+1 +280 GOTO 260 +290 PRINT RIGHT$(A$,LEN(A$)+1-I) +300 END diff --git a/Task/Substring/BASIC/substring-3.basic b/Task/Substring/BASIC/substring-3.basic index 7132d2c04e..27521e04fe 100644 --- a/Task/Substring/BASIC/substring-3.basic +++ b/Task/Substring/BASIC/substring-3.basic @@ -1,12 +1,13 @@ -10 LET A$="abcdefghijklmnopqrstuvwxyz": LET la=LEN A$ -20 LET n=10: LET m=7 -30 PRINT A$(n TO n+m-1) -40 PRINT A$(n TO ) -50 PRINT A$( TO la-1) -60 FOR i=1 TO la -70 IF A$(i)="g" THEN PRINT A$(i TO i+m-1): LET i=la -80 NEXT i -90 LET B$="ijk": LET lb=LEN b$ -100 FOR i=1 TO la-lb+1 -110 IF A$(i TO i+lb-1)=B$ THEN PRINT A$(i TO i+m-1): LET i=la-lb+1 -120 NEXT i +10 LET A$="abcdefghijklmnopqrstuvwxyz" +15 LET n=10: LET m=7 +20 PRINT A$(n TO n+m-1) +30 PRINT A$(n TO ) +40 PRINT A$( TO LEN (A$)-1) +50 FOR i=1 TO LEN (A$) +60 IF A$(i)="g" THEN PRINT A$(i TO i+m-1): LET i=LEN (A$): GO TO 70 +70 NEXT i +80 LET B$="ijk" +90 FOR i=1 TO LEN (A$)-LEN (B$)+1 +100 IF A$(i TO i+LEN (B$)-1)=B$ THEN PRINT A$(i TO i+m-1): LET i=LEN (A$)-LEN (B$)+1: GO TO 110 +110 NEXT i +120 STOP diff --git a/Task/Substring/BASIC/substring-4.basic b/Task/Substring/BASIC/substring-4.basic new file mode 100644 index 0000000000..7132d2c04e --- /dev/null +++ b/Task/Substring/BASIC/substring-4.basic @@ -0,0 +1,12 @@ +10 LET A$="abcdefghijklmnopqrstuvwxyz": LET la=LEN A$ +20 LET n=10: LET m=7 +30 PRINT A$(n TO n+m-1) +40 PRINT A$(n TO ) +50 PRINT A$( TO la-1) +60 FOR i=1 TO la +70 IF A$(i)="g" THEN PRINT A$(i TO i+m-1): LET i=la +80 NEXT i +90 LET B$="ijk": LET lb=LEN b$ +100 FOR i=1 TO la-lb+1 +110 IF A$(i TO i+lb-1)=B$ THEN PRINT A$(i TO i+m-1): LET i=la-lb+1 +120 NEXT i diff --git a/Task/Substring/C/substring-1.c b/Task/Substring/C/substring-1.c new file mode 100644 index 0000000000..0d877d5e8e --- /dev/null +++ b/Task/Substring/C/substring-1.c @@ -0,0 +1,52 @@ +/* + * RosettaCode: Substring, C89 + * + * In this task display a substring: starting from n characters in and of m + * length; starting from n characters in, up to the end of the string; whole + * string minus last character; starting from a known character within the + * string and of m length; starting from a known substring within the string + * and of m length. + * + * This example program DOES NOT make substrings. The program simply displays + * certain parts of the input string. + * + */ +#define _CRT_SECURE_NO_WARNINGS /* MSVS compilers need this */ +#include +#include +#include + +/* + * Put no more than m characters from string to standard output. + * + * It is worth noting that printf("%*s",width,string) does not limit the number + * of characters to be printed. + * + * @param string null terminated string + * @param m number of characters to display + */ +void putm(char* string, size_t m) +{ + while(*string && m--) + putchar(*string++); +} + +int main(void) +{ + + char string[] = + "Programs for other encodings (such as 8-bit ASCII, or EUC-JP)." + + int n = 3; + int m = 4; + char knownCharacter = '('; + char knownSubstring[] = "encodings"; + + putm(string+n-1, m ); putchar('\n'); + puts(string+n+1); putchar('\n'); + putm(string, strlen(string)-1); putchar('\n'); + putm(strchr(string, knownCharacter), m ); putchar('\n'); + putm(strstr(string, knownSubstring), m ); putchar('\n'); + + return EXIT_SUCCESS; +} diff --git a/Task/Substring/C/substring-2.c b/Task/Substring/C/substring-2.c new file mode 100644 index 0000000000..228173062f --- /dev/null +++ b/Task/Substring/C/substring-2.c @@ -0,0 +1,56 @@ +/* + * RosettaCode: Substring, C89, Unicode + * + * In this task display a substring: starting from n characters in and of m + * length; starting from n characters in, up to the end of the string; whole + * string minus last character; starting from a known character within the + * string and of m length; starting from a known substring within the string + * and of m length. + * + * This example program DOES NOT make substrings. The program simply displays + * certain parts of the input string. + * + */ +#include +#include +#include + +/* + * Put all characters from string to standard output AND write newline. + * BTW, _putws may not be avaliable. + */ +void put(wchar_t* string) +{ + while(*string) + putwchar(*string++); + putwchar(L'\n'); +} + +/* + * Put no more than m characters from string to standard output AND newline. + */ +void putm(wchar_t* string, size_t m) +{ + while(*string && m--) + putwchar(*string++); + putwchar(L'\n'); +} + +int main(void) +{ + wchar_t string[] = + L"Programs for other encodings (such as 8-bit ASCII)."; + + int n = 3; + int m = 4; + wchar_t knownCharacter = L'('; + wchar_t knownSubstring[] = L"encodings"; + + putm(string+n-1,m); + put (string+n+1); + putm(string, wcslen(string)-1); + putm(wcschr(string, knownCharacter), m ); + putm(wcsstr(string, knownSubstring), m ); + + return EXIT_SUCCESS; +} diff --git a/Task/Substring/C/substring.c b/Task/Substring/C/substring-3.c similarity index 100% rename from Task/Substring/C/substring.c rename to Task/Substring/C/substring-3.c diff --git a/Task/Substring/ColdFusion/substring-1.cfm b/Task/Substring/ColdFusion/substring-1.cfm new file mode 100644 index 0000000000..2f99562f99 --- /dev/null +++ b/Task/Substring/ColdFusion/substring-1.cfm @@ -0,0 +1,22 @@ + + + + + + + #mid( str, n, m )# + + + #right( str, countFromRight )# + + + #left( str, allButLast )# + + + #mid( str, startingIndex, m )# + + + #mid( str, startingIndexSubString, m )# + + diff --git a/Task/Substring/ColdFusion/substring-2.cfm b/Task/Substring/ColdFusion/substring-2.cfm new file mode 100644 index 0000000000..03fb91e6c7 --- /dev/null +++ b/Task/Substring/ColdFusion/substring-2.cfm @@ -0,0 +1,21 @@ + + str="abcdefg"; + n = 2; + m = 3; + + // Note: In CF index starts at 1 rather than 0 + // starting from n characters in and of m length + writeOutput( mid( str, n, m ) ); + // starting from n characters in, up to the end of the string + countFromRight = Len( str ) - n + 1; + writeOutput( right( str, countFromRight ) ); + // whole string minus last character + allButLast = Len( str ) - 1; + writeOutput( left( str, allButLast ) ); + // starting from a known character within the string and of m length + startingIndex = find( "b", str ); + writeOutput( mid( str, startingIndex, m ) ); + // starting from a known substring within the string and of m length + startingIndexSubString = find( "bc", str ); + writeOutput( mid( str, startingIndexSubString, m ) ); + diff --git a/Task/Substring/Elena/substring.elena b/Task/Substring/Elena/substring.elena index cf8667b7dd..ee76cc46cb 100644 --- a/Task/Substring/Elena/substring.elena +++ b/Task/Substring/Elena/substring.elena @@ -1,17 +1,16 @@ -#import system. -#import extensions. +import extensions. -#symbol program = +program = [ - #var s := "0123456789". - #var n := 3. - #var m := 2. - #var c := #51. - #var z := "345". + var s := "0123456789". + var n := 3. + var m := 2. + var c := $51. + var z := "345". - console writeLine:(s Substring:m &at:n). - console writeLine:(s Substring:(s length - n) &at:n). - console writeLine:(s Substring:(s length - 1) &at:0). - console writeLine:(s Substring:m &at:(s indexOf:c &at:0)). - console writeLine:(s Substring:m &at:(s indexOf:z &at:0)). + console writeLine(s Substring:m at:n). + console writeLine(s Substring(s length - n) at:n). + console writeLine(s Substring(s length - 1) at:0). + console writeLine(s Substring:m at(s indexOf:c at:0)). + console writeLine(s Substring:m at(s indexOf:z at:0)). ]. diff --git a/Task/Substring/Gambas/substring.gambas b/Task/Substring/Gambas/substring.gambas new file mode 100644 index 0000000000..e7a1655237 --- /dev/null +++ b/Task/Substring/Gambas/substring.gambas @@ -0,0 +1,10 @@ +Public Sub Main() +Dim sString As String = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG" + +Print Mid(sString, 11, 5) 'Starting from n characters in and of m length +Print Mid(sString, 17) 'Starting from n characters in, up to the end of the string +Print Left(sString, -1) 'Whole string minus last character +Print Mid(sString, InStr(sString, "B"), 9) 'Starting from a known character within the string and of m length +Print Mid(sString, InStr(sString, "OVER"), 8) 'Starting from a known substring within the string and of m length + +End diff --git a/Task/Substring/Haskell/substring.hs b/Task/Substring/Haskell/substring-1.hs similarity index 100% rename from Task/Substring/Haskell/substring.hs rename to Task/Substring/Haskell/substring-1.hs diff --git a/Task/Substring/Haskell/substring-2.hs b/Task/Substring/Haskell/substring-2.hs new file mode 100644 index 0000000000..a4f4e6434e --- /dev/null +++ b/Task/Substring/Haskell/substring-2.hs @@ -0,0 +1,30 @@ +import qualified Data.Text as T + (Text, take, drop, init, breakOn, pack, unpack) + +fromNforM :: Int -> Int -> T.Text -> T.Text +fromNforM n m s = T.take m (T.drop n s) + +fromNtoEnd :: Int -> T.Text -> T.Text +fromNtoEnd = T.drop + +allButLast :: T.Text -> T.Text +allButLast = T.init + +fromCharForM :: T.Text -> Int -> T.Text -> T.Text +fromCharForM needle m haystack = T.take m $ snd (T.breakOn needle haystack) + +fromStringForM :: T.Text -> Int -> T.Text -> T.Text +fromStringForM = fromCharForM + +-- TEST ----------------------------------------------------------------------- +main :: IO () +main = + mapM_ + (putStrLn . T.unpack) + ([ fromNforM 9 10 + , fromNtoEnd 20 + , allButLast + , fromCharForM (T.pack "话") 6 + , fromStringForM (T.pack "大势") 6 + ] <*> + [T.pack "天地不仁仁者人也🐒话说天下大势分久必合🍑合久必分🔥"]) diff --git a/Task/Substring/jq/substring-1.jq b/Task/Substring/Jq/substring-1.jq similarity index 100% rename from Task/Substring/jq/substring-1.jq rename to Task/Substring/Jq/substring-1.jq diff --git a/Task/Substring/jq/substring-2.jq b/Task/Substring/Jq/substring-2.jq similarity index 100% rename from Task/Substring/jq/substring-2.jq rename to Task/Substring/Jq/substring-2.jq diff --git a/Task/Substring/jq/substring-3.jq b/Task/Substring/Jq/substring-3.jq similarity index 100% rename from Task/Substring/jq/substring-3.jq rename to Task/Substring/Jq/substring-3.jq diff --git a/Task/Substring/jq/substring-4.jq b/Task/Substring/Jq/substring-4.jq similarity index 100% rename from Task/Substring/jq/substring-4.jq rename to Task/Substring/Jq/substring-4.jq diff --git a/Task/Substring/Kotlin/substring.kotlin b/Task/Substring/Kotlin/substring.kotlin new file mode 100644 index 0000000000..d807d69f74 --- /dev/null +++ b/Task/Substring/Kotlin/substring.kotlin @@ -0,0 +1,17 @@ +// version 1.0.6 + +fun main(args: Array) { + val s = "0123456789" + val n = 3 + val m = 4 + val c = '5' + val z = "12" + var i: Int + println(s.substring(n, n + m)) + println(s.substring(n)) + println(s.dropLast(1)) + i = s.indexOf(c) + println(s.substring(i, i + m)) + i = s.indexOf(z) + println(s.substring(i, i + m)) +} diff --git a/Task/Substring/NewLISP/substring.newlisp b/Task/Substring/NewLISP/substring.newlisp new file mode 100644 index 0000000000..8f1802db4a --- /dev/null +++ b/Task/Substring/NewLISP/substring.newlisp @@ -0,0 +1,17 @@ +> (set 'str "alphabet" 'n 2 'm 4) +4 +> ; starting from n characters in and of m length +> (slice str n m) +"phab" +> ; starting from n characters in, up to the end of the string +> (slice str n) +"phabet" +> ; whole string minus last character +> (chop str) +"alphabe" +> ; starting from a known character within the string and of m length +> (slice str (find "l" str) m) +"lpha" +> ; starting from a known substring within the string and of m length +> (slice str (find "ph" str) m) +"phab" diff --git a/Task/Substring/Zkl/substring.zkl b/Task/Substring/Zkl/substring.zkl new file mode 100644 index 0000000000..8938d65361 --- /dev/null +++ b/Task/Substring/Zkl/substring.zkl @@ -0,0 +1,6 @@ +var str = "abcdefgh", n = 2, m = 3; +str[n,m] //-->"cde" +str[n,*] //-->"cdefgh" +str[0,-1] //-->"abcdefg" +str[str.find("d"),m] //-->"def" +str[str.find("de"),m] //-->"def" diff --git a/Task/Subtractive-generator/Dc/subtractive-generator.dc b/Task/Subtractive-generator/Dc/subtractive-generator.dc new file mode 100644 index 0000000000..4321479400 --- /dev/null +++ b/Task/Subtractive-generator/Dc/subtractive-generator.dc @@ -0,0 +1,52 @@ +[* + * (seed) lsx -- + * Seeds the subtractive generator. + * Uses register R to hold the state. + *]sz +[ + [* Fill ring buffer R[0] to R[54]. *]sz + d 54:R SA [A = R[54] = seed]sz + 1 d 33:R SB [B = R[33] = 1]sz + 12 SC [C = index 12, into array R.]sz + [55 -]SI + [ [Loop until C is 54:]sz + lA lB - d lC:R [R[C] = A - B]sz + lB sA sB [Parallel let A = B and B = A - B]sz + lC 34 + d 55 !>I d sC [C += 34 (mod 55)]sz + 54 !=L + ]d SL x + [* Point R[55] and R[56] into ring buffer. *]sz + 0 55:R [R[55] = index 0, of 55th last number.]sz + 31 56:R [R[56] = index 31, of 24th last number.]sz + [* Stir ring buffer. *]sz + 165 [ [Loop 165 times:]sz + 55;R;R 56;R;R - 55;R:R [Discard a random number.]sz + 55;R 1 + d 55 !>I 55:R [R[55] += 1 (mod 55)]sz + 56;R 1 + d 55 !>I 56:R [R[56] += 1 (mod 55)]sz + 1 - d 0 I 55:R [R[55] += 1 (mod 55)]sz + 56;R 1 + d 55 !>I 56:R [R[56] += 1 (mod 55)]sz + [1000000000 +]sI + 1000000000 % d 0 >I [Random number = it (mod 10^9)]sz + LIsz +]sr + + +[* Seed with 292929 and print first three random numbers. *]sz +292929 lsx +lrx psz +lrx psz +lrx psz diff --git a/Task/Subtractive-generator/Zkl/subtractive-generator-1.zkl b/Task/Subtractive-generator/Zkl/subtractive-generator-1.zkl new file mode 100644 index 0000000000..fa79249e06 --- /dev/null +++ b/Task/Subtractive-generator/Zkl/subtractive-generator-1.zkl @@ -0,0 +1,12 @@ +fcn rand_sub(x){ + var ring=L(),m=(1e9).toInt(); + mod:='wrap(n){ if(n<0) n+m else n }; + if(not ring){ + seed:=L( (if(vm.numArgs) x else m-1), 1); + foreach n in ([2 .. 54]){ seed.append((seed[n-2]-seed[n-1]):mod(_)) } + foreach n in (55){ ring.append(seed[(34*(n+1))%55]) } + do(220-ring.len()){ self.fcn() } // 165 + } + ring.append((ring.pop(0)-ring[-24]):mod(_)); + return(ring[-1]); +} diff --git a/Task/Subtractive-generator/Zkl/subtractive-generator-2.zkl b/Task/Subtractive-generator/Zkl/subtractive-generator-2.zkl new file mode 100644 index 0000000000..31c33ee5e9 --- /dev/null +++ b/Task/Subtractive-generator/Zkl/subtractive-generator-2.zkl @@ -0,0 +1 @@ +do(4){ println(rand_sub(292929)) } //seed ignored after first call diff --git a/Task/Sudoku/JavaScript/sudoku-1.js b/Task/Sudoku/JavaScript/sudoku-1.js new file mode 100644 index 0000000000..166b9ee3b4 --- /dev/null +++ b/Task/Sudoku/JavaScript/sudoku-1.js @@ -0,0 +1,273 @@ +//-------------------------------------------[ Dancing Links and Algorithm X ]-- +/** + * The doubly-doubly circularly linked data object. + * Data object X + */ +class DoX { + /** + * @param {string} V + * @param {!DoX=} H + */ + constructor(V, H) { + this.V = V; + this.L = this; + this.R = this; + this.U = this; + this.D = this; + this.S = 1; + this.H = H || this; + H && (H.S += 1); + } +} + +/** + * Helper function to help build a horizontal doubly linked list. + * @param {!DoX} e An existing node in the list. + * @param {!DoX} n A new node to add to the right of the existing node. + * @return {!DoX} + */ +const addRight = (e, n) => { + n.R = e.R; + n.L = e; + e.R.L = n; + return e.R = n; +}; + +/** + * Helper function to help build a vertical doubly linked list. + * @param {!DoX} e An existing node in the list. + * @param {!DoX} n A new node to add below the existing node. + */ +const addBelow = (e, n) => { + n.D = e.D; + n.U = e; + e.D.U = n; + return e.D = n; +}; + +/** + * Verbatim copy of DK's search algorithm. The meat of the DLX algorithm. + * @param {!DoX} h The root node. + * @param {!Array} s The solution array. + */ +const search = function(h, s) { + if (h.R == h) { + printSol(s); + } else { + let c = chooseColumn(h); + cover(c); + for (let r = c.D; r != c; r = r.D) { + s.push(r); + for (let j = r.R; r !=j; j = j.R) { + cover(j.H); + } + search(h, s); + r = s.pop(); + for (let j = r.R; j != r; j = j.R) { + uncover(j.H); + } + } + uncover(c); + } +}; + +/** + * Verbatim copy of DK's algorithm for choosing the next column object. + * @param {!DoX} h + * @return {!DoX} + */ +const chooseColumn = h => { + let s = Number.POSITIVE_INFINITY; + let c = h; + for(let j = h.R; j != h; j = j.R) { + if (j.S < s) { + c = j; + s = j.S; + } + } + return c; +}; + + +/** + * Verbatim copy of DK's cover algorithm + * @param {!DoX} c + */ +const cover = c => { + c.L.R = c.R; + c.R.L = c.L; + for (let i = c.D; i != c; i = i.D) { + for (let j = i.R; j != i; j = j.R) { + j.U.D = j.D; + j.D.U = j.U; + j.H.S = j.H.S - 1; + } + } +}; + +/** + * Verbatim copy of DK's cover algorithm + * @param {!DoX} c + */ +const uncover = c => { + for (let i = c.U; i != c; i = i.U) { + for (let j = i.L; i != j; j = j.L) { + j.H.S = j.H.S + 1; + j.U.D = j; + j.D.U = j; + } + } + c.L.R = c; + c.R.L = c; +}; + +//-----------------------------------------------------------[ Print Helpers ]-- +/** + * Given the standard string format of a grid, print a formatted view of it. + * @param {!string|!Array} a + */ +const printGrid = function(a) { + + const getChar = c => { + let r = Number(c); + if (isNaN(r)) { return c } + + let o = 48; + if (r > 9 && r < 36) { o = 55 } + if (r >= 36) { o = 61 } + return String.fromCharCode(r + o) + }; + + a = 'string' == typeof a ? a.split('') : a; + + let U = Math.sqrt(a.length); + let N = Math.sqrt(U); + let line = new Array(N).fill('+').reduce((p, c) => { + p.push(... Array.from(new Array(1 + N*2).fill('-'))); + p.push(c); + return p; + }, ['\n+']).join('') + '\n'; + + a = a.reduce(function(p, c, i) { + let d = i && !(i % U), G = i && !(i % N); + i = !(i % (U * N)); + d && !i && (p += '|\n| '); + d && i && (p += '|'); + i && (p = '' + p + line + '| '); + return '' + p + (G && !d ? '| ' : '') + getChar(c) + ' '; + }, '') + '|' + line; + console.log(a); + +}; + +/** + * Given a search solution, print the resultant grid. + * @param {!Array} a An array of data objects + */ +const printSol = a => { + printGrid(a.reduce((p, c) => { + let [i, v] = c.V.split(':'); + p[i * 1] = v; + return p; + }, new Array(a.length).fill('.'))); +}; + +//----------------------------------------------[ Grid to Exact cover Matrix ]-- +/** + * Helper to get some meta about the grid. + * @param {!string} s The standard string representation of a grid. + * @return {!Array} + */ +const gridMeta = s => { + const g = s.split(''); + const cellCount = g.length; + const tokenCount = Math.sqrt(cellCount); + const N = Math.sqrt(tokenCount); + const g2D = g.map(e => isNaN(e * 1) ? + new Array(tokenCount).fill(1).map((_, i) => i + 1) : + [e * 1]); + return [cellCount, N, tokenCount, g2D]; +}; + +/** + * Given a cell grid index, return the row, column and box indexes. + * @param {!number} n The n-value of the grid. 3 for a 9x9 sudoku. + * @return {!function(!number): !Array} + */ +const indexesN = n => i => { + let c = Math.floor(i / (n * n)); + i %= n * n; + return [c, i, Math.floor(c / n) * n + Math.floor(i / n)]; +}; + +/** + * Given a puzzle string, reduce it to an exact-cover matrix and use + * Donald Knuth's DLX algorithm to solve it. + * @param puzString + */ +const reduceGrid = puzString => { + + printGrid(puzString); + const [ + numCells, // The total number of cells in a grid (81 for a 9x9 grid) + N, // the 'n' value of the grid. (3 for a 9x9 grid) + U, // The total number of unique tokens to be placed. + g2D // A 2D array representation of the grid, with each element + // being an array of candidates for a cell. Known cells are + // single element arrays. + ] = gridMeta(puzString); + + const getIndex = indexesN(N); + + /** + * The DLX Header row. + * Its length is 4 times the grid's size. This is to be able to encode + * each of the 4 Sudoku constrains, onto each of the cells of the grid. + * The array is initialised with unlinked DoX nodes, but in the next step + * those nodes are all linked. + * @type {!Array.} + */ + const headRow = new Array(4 * numCells) + .fill('') + .map((_, i) => new DoX(`H${i}`)); + + /** + * The header row root object. This is circularly linked to be to the left + * of the first header object in the header row array. + * It is used as the entry point into the DLX algorithm. + * @type {!DoX} + */ + let H = new DoX('ROOT'); + headRow.reduce((p, c) => addRight(p, c), H); + + /** + * Transposed the sudoku puzzle into a exact cover matrix, so it can be passed + * to the DLX algorithm to solve. + */ + for (let i = 0; i < numCells; i++) { + const [ri, ci, bi] = getIndex(i); + g2D[i].forEach(num => { + let id = `${i}:${num}`; + let candIdx = num - 1; + + // The 4 columns that we will populate. + const A = headRow[i]; + const B = headRow[numCells + candIdx + (ri * U)]; + const C = headRow[(numCells * 2) + candIdx + (ci * U)]; + const D = headRow[(numCells * 3) + candIdx + (bi * U)]; + + // The Row-Column Constraint + let rcc = addBelow(A.U, new DoX(id, A)); + + // The Row-Number Constraint + let rnc = addBelow(B.U, addRight(rcc, new DoX(id, B))); + + // The Column-Number Constraint + let cnc = addBelow(C.U, addRight(rnc, new DoX(id, C))); + + // The Block-Number Constraint + addBelow(D.U, addRight(cnc, new DoX(id, D))); + }); + } + search(H, []); +}; diff --git a/Task/Sudoku/JavaScript/sudoku-2.js b/Task/Sudoku/JavaScript/sudoku-2.js new file mode 100644 index 0000000000..f9baa76dde --- /dev/null +++ b/Task/Sudoku/JavaScript/sudoku-2.js @@ -0,0 +1,25 @@ +[ + '819..5.....2...75..371.4.6.4..59.1..7..3.8..2..3.62..7.5.7.921..64...9.....2..438', + '53..247....2...8..1..7.39.2..8.72.49.2.98..7.79.....8.....3.5.696..1.3...5.69..1.', + '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..', + '394..267....3..4..5..69..2..45...9..6.......7..7...58..1..67..8..9..8....264..735', + '97.3...6..6.75.........8.5.......67.....3.....539..2..7...25.....2.1...8.4...73..', + '4......6.5...8.9..3....1....2.7....1.9.....4.8....3.5....2....7..6.5...8.1......6', + '85...24..72......9..4.........1.7..23.5...9...4...........8..7..17..........36.4.', + '..1..5.7.92.6.......8...6...9..2.4.1.........3.4.8..9...7...3.......7.69.1.8..7..', + '.9...4..7.....79..8........4.58.....3.......2.....97.6........4..35.....2..6...8.', + '12.3....435....1....4........54..2..6...7.........8.9...31..5.......9.7.....6...8', + '9..2..5...4..6..3...3.....6...9..2......5..8...7..4..37.....1...5..2..4...1..6..9', + '1....7.9..3..2...8..96..5....53..9...1..8...26....4...3......1..4......7..7...3..', + '12.4..3..3...1..5...6...1..7...9.....4.6.3.....3..2...5...8.7....7.....5.......98', + '..............3.85..1.2.......5.7.....4...1...9.......5......73..2.1........4...9', + '.......39.....1..5..3.5.8....8.9...6.7...2...1..4.......9.8..5..2....6..4..7.....', + '....839..1......3...4....7..42.3....6.......4....7..1..2........8...92.....25...6', + '..3......4...8..36..8...1...4..6..73...9..........2..5..4.7..686........7..6..5..' +].forEach(reduceGrid); + +// Or of you want to create all the grids of a particular n-size. +// I run out of stack space at n = 9 +let n = 2; +let s = new Array(Math.pow(n, 4)).fill('.').join(''); +reduceGrid(s); diff --git a/Task/Sudoku/Julia/sudoku.julia b/Task/Sudoku/Julia/sudoku.julia new file mode 100644 index 0000000000..75370c57e1 --- /dev/null +++ b/Task/Sudoku/Julia/sudoku.julia @@ -0,0 +1,67 @@ +function check(i, j) + id, im = div(i, 9), mod(i, 9) + jd, jm = div(j, 9), mod(j, 9) + + jd == id && return true + jm == im && return true + + div(id, 3) == div(jd, 3) && + div(jm, 3) == div(im, 3) +end + +const lookup = zeros(Bool, 81, 81) + +for i in 1:81 + for j in 1:81 + lookup[i,j] = check(i-1, j-1) + end +end + +function solve_sudoku(callback::Function, grid::Array{Int64}) + (function solve() + for i in 1:81 + if grid[i] == 0 + t = Dict{Int64, Void}() + + for j in 1:81 + if lookup[i,j] + t[grid[j]] = nothing + end + end + + for k in 1:9 + if !haskey(t, k) + grid[i] = k + solve() + end + end + + grid[i] = 0 + return + end + end + + callback(grid) + end)() +end + +function display(grid) + for i in 1:length(grid) + print(grid[i], " ") + i % 3 == 0 && print(" ") + i % 9 == 0 && print("\n") + i % 27 == 0 && print("\n") + end +end + +grid = Int64[5, 3, 0, 0, 2, 4, 7, 0, 0, + 0, 0, 2, 0, 0, 0, 8, 0, 0, + 1, 0, 0, 7, 0, 3, 9, 0, 2, + 0, 0, 8, 0, 7, 2, 0, 4, 9, + 0, 2, 0, 9, 8, 0, 0, 7, 0, + 7, 9, 0, 0, 0, 0, 0, 8, 0, + 0, 0, 0, 0, 3, 0, 5, 0, 6, + 9, 6, 0, 0, 1, 0, 3, 0, 0, + 0, 5, 0, 6, 9, 0, 0, 1, 0] + +solve_sudoku(display, grid) diff --git a/Task/Sudoku/Scilab/sudoku.scilab b/Task/Sudoku/Scilab/sudoku.scilab new file mode 100644 index 0000000000..48dbe4526b --- /dev/null +++ b/Task/Sudoku/Scilab/sudoku.scilab @@ -0,0 +1,173 @@ +Init_board=[... +5 3 0 0 7 0 0 0 0;... +6 0 0 1 9 5 0 0 0;... +0 9 8 0 0 0 0 6 0;... +8 0 0 0 6 0 0 0 3;... +4 0 0 8 0 3 0 0 1;... +7 0 0 0 2 0 0 0 6;... +0 6 0 0 0 0 2 8 0;... +0 0 0 4 1 9 0 0 5;... +0 0 0 0 8 0 0 7 9]; + +break_point=1.0d5; //if 0 there will be no break + +function []=disp_board(board) + StringBoard=string(board); + for i=1:9 + for j=1:9 + if board(i,j)==0 then + StringBoard(i,j)='×'; + end + end + end + + StringBoard=[StringBoard, string(zeros(9,2))]; + StringBoard=[StringBoard; string(zeros(2,11))]; + + for i=1:9 + StringBoard(i,:)=[StringBoard(i,1:3), '|', StringBoard(i,4:6), '|', StringBoard(i,7:9)] + end + StringBoard(9:11,:)=StringBoard(7:9,:); + StringBoard(8,:)=strsplit('-----------'); + StringBoard(5:7,:)=StringBoard(4:6,:); + StringBoard(4,:)=strsplit('-----------'); + + disp(StringBoard) +endfunction + +function varargout=validate_input(input,position,board) + row=board(position(1),:); + column=board(:,position(2)); + block=zeros(3,3); + if position(1)>=1 & position(1)<=3 then + i=0; + elseif position(1)>=4 & position(1)<=6 then + i=3; + else + i=6; + end + if position(2)>=1 & position(2)<=3 then + j=0; + elseif position(2)>=4 & position(2)<=6 then + j=3; + else + j=6; + end + block=board(i+1:i+3,j+1:j+3) + + valid_input=%F; + valid_row=%F; + valid_col=%F; + valid_block=%F; + + if find(input==row)==[] then + valid_row=%T; + end + if find(input==column)==[] then + valid_col=%T; + end + if find(input==block)==[] then + valid_block=%T; + end + if valid_row & valid_col & valid_block then + valid_input=%T; + end + + varargout=list(valid_input,valid_row,valid_col,valid_block) +endfunction + +function varargout=validate_board(board) + valid_flag1=%T; + for i=1:9 + for j=1:9 + if board(i,j)~= 0 then + check_board=Init_board; + check_board(i,j)=0; + valid_flag1=validate_input(board(i,j),[i j],check_board); + if ~valid_flag1 then + break + end + end + end + if ~valid_flag1 then + break + end + end + + valid_flag2 = (length( find(board) ) >= 17); //enforces rule of minimum of 17 givens + //set it to always %T to ignore this rule + valid_board = (valid_flag1 & valid_flag2); + + varargout=list(valid_board) +endfunction + +disp('Initial board:'); +disp_board(Init_board); + +valid_init_board=validate_board(Init_board); + +if ~valid_init_board then + error('Invalid initial board. Should follow sudoku rules and have at least 17 clues.'); +end + +blank=[]; +for i=1:9 + for j=1:9 + if Init_board(i,j)== 0 then + blank=[blank; i j]; + end + end +end + +Solved_board=Init_board; + +tic(); +i=0; counter=0; breaked=%F; +while i=10 + break + else + valid_value=validate_input(value,pos,Solved_board); + end + end + + if valid_value & value<10 then + Solved_board(pos(1),pos(2))=value + else + Solved_board(pos(1),pos(2))=0; + i=i-2; + end + + if counter==break_point + breaked=%T; + break + end +end + +valid_solved_board=validate_board(Solved_board); +t2=toc(); + +if valid_solved_board & ~breaked then + disp('Solved!'); + disp('Solution:'); + disp_board(Solved_board); + disp('Time: '+string(t2)+'s.'); + disp('Steps: '+string(counter)+'.'); +elseif breaked + disp('Break point reached.'); + disp('Time: '+string(t2)+'s.'); + disp_board(Solved_board); +elseif ~valid_solved_board & ~breaked + disp('Invalid solution found.'); + disp_board(Solved_board); +end diff --git a/Task/Sudoku/Sidef/sudoku.sidef b/Task/Sudoku/Sidef/sudoku.sidef index 1c8893432e..8750eedb6a 100644 --- a/Task/Sudoku/Sidef/sudoku.sidef +++ b/Task/Sudoku/Sidef/sudoku.sidef @@ -5,38 +5,34 @@ func check(i, j) is cached { jd == id && return true jm == im && return true - var id2 = id//3 - var jd2 = jd//3 - - jd2 == id2 || return false - - jm//3 == im//3 + (id//3 == jd//3) && + (jm//3 == im//3) } -func solve(board) { - for i in ^board { - board[i] && next - var *t = board[^board -> grep {|j| check(i, j) }] +func solve(grid) { + for i in ^grid { + grid[i] && next + var t = [grid[{|j| check(i, j) }.grep(^grid)]].freq { |k| - t.contains(k) && next - board[i] = k - solve(board) - } * 9 + t.has_key(k) && next + grid[i] = k + solve(grid) + } << 1..9 - board[i] = 0 + grid[i] = 0 return nil } - for i in ^board { - print "#{board[i]} "; + for i in ^grid { + print "#{grid[i]} " print " " if (3 -> divides(i+1)) print "\n" if (9 -> divides(i+1)) print "\n" if (27 -> divides(i+1)) } } -var board = %i( +var grid = %i( 5 3 0 0 2 4 7 0 0 0 0 2 0 0 0 8 0 0 1 0 0 7 0 3 9 0 2 @@ -50,4 +46,4 @@ var board = %i( 0 5 0 6 9 0 0 1 0 ) -solve(board) +solve(grid) diff --git a/Task/Sudoku/Swift/sudoku-1.swift b/Task/Sudoku/Swift/sudoku-1.swift new file mode 100644 index 0000000000..f456f45841 --- /dev/null +++ b/Task/Sudoku/Swift/sudoku-1.swift @@ -0,0 +1,124 @@ +import Foundation + +typealias SodukuPuzzle = [[Int]] + +class Soduku { + let mBoardSize:Int! + let mBoxSize:Int! + var mBoard:SodukuPuzzle! + var mRowSubset:[[Bool]]! + var mColSubset:[[Bool]]! + var mBoxSubset:[[Bool]]! + + init(board:SodukuPuzzle) { + mBoard = board + mBoardSize = board.count + mBoxSize = Int(sqrt(Double(mBoardSize))) + mRowSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) + mColSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) + mBoxSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) + initSubsets() + } + + func computeBoxNo(i:Int, _ j:Int) -> Int { + let boxRow = i / mBoxSize + let boxCol = j / mBoxSize + + return boxRow * mBoxSize + boxCol + } + + func initSubsets() { + for i in 0.. Bool { + val-- + let isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val] + return !isPresent + } + + func printBoard() { + for i in 0.. Bool { + if i == mBoardSize { + i = 0 + j++ + if j == mBoardSize { + return true + } + } + + if mBoard[i][j] != 0 { + return solve(i + 1, j) + } + + for value in 1...mBoardSize { + if isValid(i, j, value) { + mBoard[i][j] = value + setSubsetValue(i, j, value, true) + + if solve(i + 1, j) { + return true + } + + setSubsetValue(i, j, value, false) + } + } + + mBoard[i][j] = 0 + return false + } +} + +let board = [ + [4, 0, 0, 0, 0, 0, 0, 6, 0], + [5, 0, 0, 0, 8, 0, 9, 0, 0], + [3, 0, 0, 0, 0, 1, 0, 0, 0], + [0, 2, 0, 7, 0, 0, 0, 0, 1], + [0, 9, 0, 0, 0, 0, 0, 4, 0], + [8, 0, 0, 0, 0, 3, 0, 5, 0], + [0, 0, 0, 2, 0, 0, 0, 0, 7], + [0, 0, 6, 0, 5, 0, 0, 0, 8], + [0, 1, 0, 0, 0, 0, 0, 0, 6] +] + +let puzzle = Soduku(board: board) +puzzle.solve() +puzzle.printBoard() diff --git a/Task/Sudoku/Swift/sudoku-2.swift b/Task/Sudoku/Swift/sudoku-2.swift new file mode 100644 index 0000000000..098ff3e4f3 --- /dev/null +++ b/Task/Sudoku/Swift/sudoku-2.swift @@ -0,0 +1,64 @@ +func solving(board: [[Int]]) -> [[Int]] { + var board = board + var isSolved = false + while !isSolved { + for x in 0 ..< 9 { + for y in 0 ..< 9 { + if board[x][y] == 0 { + let known = Set(board.map { $0[y] } + board[x] + subgrid(board, pos: (x, y))) + let possible = Set(Array(1...9)).subtracting(known) + if possible.count == 1 { + board[x][y] = possible.first! + } + } + } + isSolved = 45 == board[x].reduce(0, +) + } + } + return board +} + +func subgrid(_ board: [[Int]], pos: (Int, Int)) -> [Int] { + var r = [Int]() + var (x, y) = pos + x = x / 3 * 3 + y = y / 3 * 3 + for i in x ..< x + 3 { + for j in y ..< y + 3 { + r.append(board[i][j]) + } + } + return r +} + +func print(_ board: [[Int]]) { + for i in board.indices { + if i % 9 == 0 { + print(" -------------------") + } + for j in board.indices { + if j % board.count == 0 { + print("| ", terminator: "") + } + let digit = board[i][j] + print(digit != 0 ? digit : " ", terminator: "") + print(" ", terminator: "") + } + print("|") + } + print(" -------------------") +} + +let puzzle = [ + [0,2,0,4,5,0,7,0,9], + [0,0,0,1,0,9,0,3,0], + [0,0,8,0,0,0,1,0,4], + [0,4,0,0,6,1,0,7,0], + [5,0,6,0,3,0,0,1,0], + [0,3,0,0,0,2,0,9,0], + [3,0,4,0,7,5,0,6,8], + [0,9,0,0,1,0,3,0,7], + [0,0,2,0,0,3,0,0,1] +] + +print(solving(board: puzzle)) diff --git a/Task/Sudoku/Swift/sudoku.swift b/Task/Sudoku/Swift/sudoku.swift deleted file mode 100644 index 543b6e8b3e..0000000000 --- a/Task/Sudoku/Swift/sudoku.swift +++ /dev/null @@ -1,125 +0,0 @@ -import Foundation - -typealias SodukuPuzzle = [[Int]] - -class Soduku { - let mBoardSize:Int! - let mBoxSize:Int! - var mBoard:SodukuPuzzle! - var mRowSubset:[[Bool]]! - var mColSubset:[[Bool]]! - var mBoxSubset:[[Bool]]! - - init(board:SodukuPuzzle) { - mBoard = board - mBoardSize = board.count - mBoxSize = Int(sqrt(Double(mBoardSize))) - mRowSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) - mColSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) - mBoxSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) - initSubsets() - } - - func computeBoxNo(i:Int, _ j:Int) -> Int { - let boxRow = i / mBoxSize - let boxCol = j / mBoxSize - - return boxRow * mBoxSize + boxCol - } - - func initSubsets() { - for i in 0.. Bool { - val-- - let isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val] - return !isPresent - } - - func printBoard() { - for i in 0.. Bool { - if i == mBoardSize { - i = 0 - j++ - if j == mBoardSize { - return true - } - } - - if mBoard[i][j] != 0 { - return solve(i + 1, j) - } - - for value in 1...mBoardSize { - if isValid(i, j, value) { - mBoard[i][j] = value - setSubsetValue(i, j, value, true) - - if solve(i + 1, j) { - return true - } - - setSubsetValue(i, j, value, false) - } - } - - mBoard[i][j] = 0 - return false - } -} - -let board = [ - [4, 0, 0, 0, 0, 0, 0, 6, 0], - [5, 0, 0, 0, 8, 0, 9, 0, 0], - [3, 0, 0, 0, 0, 1, 0, 0, 0], - - [0, 2, 0, 7, 0, 0, 0, 0, 1], - [0, 9, 0, 0, 0, 0, 0, 4, 0], - [8, 0, 0, 0, 0, 3, 0, 5, 0], - [0, 0, 0, 2, 0, 0, 0, 0, 7], - [0, 0, 6, 0, 5, 0, 0, 0, 8], - [0, 1, 0, 0, 0, 0, 0, 0, 6] -] - -let puzzle = Soduku(board: board) -puzzle.solve() -puzzle.printBoard() diff --git a/Task/Sudoku/SystemVerilog/sudoku.v b/Task/Sudoku/SystemVerilog/sudoku.v new file mode 100644 index 0000000000..b66ab77cf4 --- /dev/null +++ b/Task/Sudoku/SystemVerilog/sudoku.v @@ -0,0 +1,132 @@ +/// @Author: Alexandre Felipe (o.alexandre.felipe@gmail.com) +/// @Date: 2017-May-10 +/// + +////////////////////////////////////////////////////////////////////////////// +/// SudokuSolver /// +/// A class that fills up a sudoku board, the initial board is given /// +/// as an array preset_rows, the positions where preset_rows is zero /// +/// are to be determined. Three views of the sudoku board are created /// +/// and the uniqueness of its elements are defined by on constraint for /// +/// each view, one constraint ensures that the values are between 1 and /// +/// 9, and two other constraints are used to ensure that the values in /// +/// all three views agree to each other. /// +/// /// +/// /// +/// A solution using only the "rows" array would be possible, however /// +/// this illustrates better how one can relate different variables in /// +/// SystemVerilog Constrained randomization. /// +////////////////////////////////////////////////////////////////////////////// +class SudokuSolver; + rand int tiles[0:8][0:8]; + rand int rows[0:8][0:8]; + rand int cols[0:8][0:8]; + int preset_rows[0:8][0:8]; + constraint board_input { + foreach(preset_rows[i])foreach(preset_rows[i][j]) + if(preset_rows[i][j] != 0) rows[i][j] == preset_rows[i][j]; + } + constraint range { + foreach(rows[i]) foreach(rows[i][j]) + rows[i][j] inside {[1:9]}; + } + //////////////////////////////////////////////// + /// Every number in a row is unique /// + //////////////////////////////////////////////// + constraint rows_permutation { + foreach(rows[i]) foreach(rows[i][j1]) + foreach(rows[i][j2]) + if(j1 != j2) rows[i][j1] != rows[i][j2]; + } + /////////////////////////////////////////////// + /// Every number in a column is unique /// + /////////////////////////////////////////////// + constraint cols_permutation { + foreach(cols[i]) foreach(cols[i][j1]) + foreach(cols[i][j2]) + if(j1 != j2) cols[i][j1] != cols[i][j2]; + } + ///////////////////////////////////////////////// + /// Every number in a tile (square) is unique /// + ///////////////////////////////////////////////// + constraint tiles_permutation { + foreach(tiles[i]) foreach(tiles[i][j1]) + foreach(tiles[i][j2]) + if(j1 != j2) tiles[i][j1] != tiles[i][j2]; + } + /////////////////////////////////////////////////// + /// Makes sure that sure that the numbers in /// + /// each view agree with other views /// + /////////////////////////////////////////////////// + constraint rows_vs_tiles { + foreach(tiles[i]) foreach(tiles[i][j]) + tiles[i][j] == rows[(i/3) * 3 + (j/3)][3*(i%3)+(j%3)]; + } + constraint rows_vs_cols { + foreach(cols[i]) foreach(cols[i][j]) + cols[i][j] == rows[j][i]; + } + /////////////////////////////////////////////////// + /// Print the current state of the board in the /// + /// standard output /// + /////////////////////////////////////////////////// + function void printBoard; + int i, j; + for(i = 0; i < 9; ++i) begin + if(i % 3 == 0)$display(" -------------"); + $write(" "); + for(j = 0; j < 9; ++j) begin + if(j % 3 == 0) $write("|"); + $write("%c", "0" + rows[i][j]); + end + $display("|"); + end + $display(" -------------"); + endfunction + function void printInitial; + int i, j; + for(i = 0; i < 9; ++i) begin + if(i % 3 == 0)$display("-------------"); + for(j = 0; j < 9; ++j) begin + if(j % 3 == 0) $write("|"); + if(preset_rows[i][j]) begin + $write("%c", "0" + preset_rows[i][j]); + end + else begin + $write("."); + end + end + $display("|"); + end + $display("-------------"); + endfunction + +endclass + +////////////////////////////////////////////////////// +/// Simple program instantiating the sudoku object /// +////////////////////////////////////////////////////// +program SudokuTest; + SudokuSolver board; +initial begin + board = new; + foreach(board.preset_rows[0][i]) board.preset_rows[i][i] = i+1; + $display("Initial Board:"); + board.printInitial(); + // Generate two different solutions for the board + if(board.randomize())begin + $display("One solution:"); + board.printBoard(); + end + else begin + $display("ERROR: Failed to generate first solution"); + end + if(board.randomize())begin + $display("Another solution:"); + board.printBoard(); + end + else begin + $display("ERROR: Failed to generate second solution"); + end +end +endprogram diff --git a/Task/Sudoku/Zkl/sudoku-1.zkl b/Task/Sudoku/Zkl/sudoku-1.zkl new file mode 100644 index 0000000000..db7f271e08 --- /dev/null +++ b/Task/Sudoku/Zkl/sudoku-1.zkl @@ -0,0 +1,22 @@ +fcn trycell(sdku,pos=0){ + row,col:=pos/9, pos%9; + + if(pos==81) return(True); + if(sdku[pos]) return(trycell(sdku, pos + 1)); + + used:=0; + foreach r in (9){ used=used.bitOr((1).shiftLeft(sdku[r*9 + col] - 1)) } + foreach c in (9){ used=used.bitOr((1).shiftLeft(sdku[row*9 + c] - 1)) } + + row,col = row/3*3, col/3*3; + foreach r,c in ([row..row+2], [col..col+2]) + { used=used.bitOr((1).shiftLeft(sdku[r*9 + c] - 1)) } + + sdku[pos]=1; while(sdku[pos]<=9){ + if(used.isEven and trycell(sdku, pos + 1)) return(True); + sdku[pos]+=1; used/=2; + } + + sdku[pos]=0; + return(False); +} diff --git a/Task/Sudoku/Zkl/sudoku-2.zkl b/Task/Sudoku/Zkl/sudoku-2.zkl new file mode 100644 index 0000000000..58baa67008 --- /dev/null +++ b/Task/Sudoku/Zkl/sudoku-2.zkl @@ -0,0 +1,19 @@ +problem:= +#<<< +" 5 3 0 0 7 0 0 0 0 + 6 0 0 1 9 5 0 0 0 + 0 9 8 0 0 0 0 6 0 + 8 0 0 0 6 0 0 0 3 + 4 0 0 8 0 3 0 0 1 + 7 0 0 0 2 0 0 0 6 + 0 6 0 0 0 0 2 8 0 + 0 0 0 4 1 9 0 0 5 + 0 0 0 0 8 0 0 7 9"; +#<<< +s:=problem.split().apply("toInt").copy(); // writable list of 81 ints +trycell(s).println(); +println("+-----+-----+-----+"); +foreach n in (3){ + s[n*27,27].pump(Console.println,T(Void.Read,8),("| " + "%s%s%s | "*3).fmt); // 3 lines + println("+-----+-----+-----+"); +} diff --git a/Task/Sum-and-product-of-an-array/360-Assembly/sum-and-product-of-an-array.360 b/Task/Sum-and-product-of-an-array/360-Assembly/sum-and-product-of-an-array.360 new file mode 100644 index 0000000000..5441803c63 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/360-Assembly/sum-and-product-of-an-array.360 @@ -0,0 +1,21 @@ +* Sum and product of an array 20/04/2017 +SUMPROD CSECT + USING SUMPROD,R15 base register + SR R3,R3 su=0 + LA R5,1 pr=1 + LA R6,1 i=1 + DO WHILE=(CH,R6,LE,=AL2((PG-A)/4)) do i=1 to hbound(a) + LR R1,R6 i + SLA R1,2 *4 + A R3,A-4(R1) su=su+a(i) + M R4,A-4(R1) pr=pr*a(i) + LA R6,1(R6) i++ + ENDDO , enddo i + XDECO R3,PG su + XDECO R5,PG+12 pr + XPRNT PG,L'PG print + BR R14 exit +A DC F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8',F'9',F'10' +PG DS CL24 buffer + YREGS + END SUMPROD diff --git a/Task/Sum-and-product-of-an-array/Aime/sum-and-product-of-an-array.aime b/Task/Sum-and-product-of-an-array/Aime/sum-and-product-of-an-array.aime index cd7cce3a6b..0aef18f529 100644 --- a/Task/Sum-and-product-of-an-array/Aime/sum-and-product-of-an-array.aime +++ b/Task/Sum-and-product-of-an-array/Aime/sum-and-product-of-an-array.aime @@ -8,8 +8,8 @@ compute(integer &s, integer &p, list l) i = l_length(l); while (i) { i -= 1; - s += l_q_integer(l, i); - p *= l_q_integer(l, i); + s += l[i]; + p *= l[i]; } } @@ -20,10 +20,7 @@ main(void) compute(sum, product, l_effect(2, 3, 5, 7, 11, 13, 17, 19)); - o_integer(sum); - o_newline(); - o_integer(product); - o_newline(); + o_form("~\n~\n", sum, product); return 0; } diff --git a/Task/Sum-and-product-of-an-array/AppleScript/sum-and-product-of-an-array-2.applescript b/Task/Sum-and-product-of-an-array/AppleScript/sum-and-product-of-an-array-2.applescript index bb48ef62a4..1210cb47ab 100644 --- a/Task/Sum-and-product-of-an-array/AppleScript/sum-and-product-of-an-array-2.applescript +++ b/Task/Sum-and-product-of-an-array/AppleScript/sum-and-product-of-an-array-2.applescript @@ -1,12 +1,3 @@ -on run - - set lstRange to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} - - {{sum:reduce(summed, 0, lstRange)}, ¬ - {product:reduce(product, 1, lstRange)}} - -end run - on summed(a, b) a + b end summed @@ -15,24 +6,55 @@ on product(a, b) a * b end product +-- TEST ----------------------------------------------------------------------- +on run + set xs to enumFromTo(1, 10) --- GENERIC LIBRARY FUNCTION + {xs, ¬ + {sum:foldl(summed, 0, xs)}, ¬ + {product:foldl(product, 1, xs)}} --- list, function, initial accumulator value --- the arguments available to the function f(a, x, i, l) are --- v: current accumulator value --- x: current item in list --- i: [ 1-based index in list ] optional --- l: [ a reference to the list itself ] optional -on reduce(f, initialValue, xs) - script mf - property lambda : f - end script + --> {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {sum:55}, {product:3628800}} - set v to initialValue - repeat with i from 1 to length of xs - set v to mf's lambda(v, item i of xs, i, xs) +end run + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if n < m then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i end repeat - return v -end reduce + return lst +end enumFromTo + +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn diff --git a/Task/Sum-and-product-of-an-array/AppleScript/sum-and-product-of-an-array-3.applescript b/Task/Sum-and-product-of-an-array/AppleScript/sum-and-product-of-an-array-3.applescript index 482cbb252c..8641618fa3 100644 --- a/Task/Sum-and-product-of-an-array/AppleScript/sum-and-product-of-an-array-3.applescript +++ b/Task/Sum-and-product-of-an-array/AppleScript/sum-and-product-of-an-array-3.applescript @@ -1 +1 @@ -{{sum:55}, {product:3628800}} +{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {sum:55}, {product:3628800}} diff --git a/Task/Sum-and-product-of-an-array/Bc/sum-and-product-of-an-array.bc b/Task/Sum-and-product-of-an-array/Bc/sum-and-product-of-an-array.bc new file mode 100644 index 0000000000..0f42fb5fc6 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Bc/sum-and-product-of-an-array.bc @@ -0,0 +1,14 @@ +a[0] = 3.0 +a[1] = 1 +a[2] = 4.0 +a[3] = 1.0 +a[4] = 5 +a[5] = 9.00 +n = 6 +p = 1 +for (i = 0; i < n; i++) { + s += a[i] + p *= a[i] +} +"Sum: "; s +"Product: "; p diff --git a/Task/Sum-and-product-of-an-array/Dc/sum-and-product-of-an-array.dc b/Task/Sum-and-product-of-an-array/Dc/sum-and-product-of-an-array.dc new file mode 100644 index 0000000000..26dfcec76b --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Dc/sum-and-product-of-an-array.dc @@ -0,0 +1,3 @@ +1 3 5 7 9 11 13 0ss1sp[dls+sslp*spz0!=a]dsax[Sum: ]Plsp[Product: ]Plpp +Sum: 49 +Product: 135135 diff --git a/Task/Sum-and-product-of-an-array/Elena/sum-and-product-of-an-array.elena b/Task/Sum-and-product-of-an-array/Elena/sum-and-product-of-an-array.elena index 3a1d7bad32..683da9e350 100644 --- a/Task/Sum-and-product-of-an-array/Elena/sum-and-product-of-an-array.elena +++ b/Task/Sum-and-product-of-an-array/Elena/sum-and-product-of-an-array.elena @@ -1,11 +1,10 @@ -#import system. -#import system'routines. -#import extensions. +import system'routines. +import extensions. -#symbol program = +program = [ - #var list := (1, 2, 3, 4, 5 ). + var list := (1, 2, 3, 4, 5 ). - #var sum := list summarize:(Integer new). - #var product := list accumulate:(Integer new:1) &with:(:var:val) [ var * val ]. + var sum := list summarize(Integer new). + var product := list accumulate(Integer new:1) with(:var:val)( var * val ). ]. diff --git a/Task/Sum-and-product-of-an-array/Gambas/sum-and-product-of-an-array.gambas b/Task/Sum-and-product-of-an-array/Gambas/sum-and-product-of-an-array.gambas new file mode 100644 index 0000000000..f4d12ffe7b --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Gambas/sum-and-product-of-an-array.gambas @@ -0,0 +1,14 @@ +Public Sub Main() +Dim iList As Integer[] = [1, 2, 3, 4, 5] +Dim iSum, iCount As Integer +Dim iPrd As Integer = 1 + +For iCount = 0 To iList.Max + iSum += iList[iCount] + iPrd *= iList[iCount] +Next + +Print "The Sum =\t" & iSum +Print "The Product =\t" & iPrd + +End diff --git a/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-1.hs b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-1.hs index 711a9a2c9c..395ed02534 100644 --- a/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-1.hs +++ b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-1.hs @@ -3,5 +3,5 @@ values = [1..10] s = sum values -- the easy way p = product values -s' = foldl (+) 0 values -- the hard way -p' = foldl (*) 1 values +s1 = foldl (+) 0 values -- the hard way +p1 = foldl (*) 1 values diff --git a/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-3.hs b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-3.hs new file mode 100644 index 0000000000..5bf978fafe --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-3.hs @@ -0,0 +1,4 @@ +import Data.Array (listArray, elems) + +main :: IO () +main = mapM_ print $ [sum, product] <*> [elems $ listArray (1, 10) [11 .. 20]] diff --git a/Task/Sum-and-product-of-an-array/JavaScript/sum-and-product-of-an-array-3.js b/Task/Sum-and-product-of-an-array/JavaScript/sum-and-product-of-an-array-3.js new file mode 100644 index 0000000000..b8602c9ac7 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/JavaScript/sum-and-product-of-an-array-3.js @@ -0,0 +1,19 @@ +(() => { + 'use strict'; + + // sum :: (Num a) => [a] -> a + const sum = xs => xs.reduce((a, x) => a + x, 0); + + // product :: (Num a) => [a] -> a + const product = xs => xs.reduce((a, x) => a * x, 1); + + + // TEST + // show :: a -> String + const show = x => JSON.stringify(x, null, 2); + + return show( + [sum, product] + .map(f => f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) + ); +})(); diff --git a/Task/Sum-and-product-of-an-array/jq/sum-and-product-of-an-array-1.jq b/Task/Sum-and-product-of-an-array/Jq/sum-and-product-of-an-array-1.jq similarity index 100% rename from Task/Sum-and-product-of-an-array/jq/sum-and-product-of-an-array-1.jq rename to Task/Sum-and-product-of-an-array/Jq/sum-and-product-of-an-array-1.jq diff --git a/Task/Sum-and-product-of-an-array/jq/sum-and-product-of-an-array-2.jq b/Task/Sum-and-product-of-an-array/Jq/sum-and-product-of-an-array-2.jq similarity index 100% rename from Task/Sum-and-product-of-an-array/jq/sum-and-product-of-an-array-2.jq rename to Task/Sum-and-product-of-an-array/Jq/sum-and-product-of-an-array-2.jq diff --git a/Task/Sum-and-product-of-an-array/jq/sum-and-product-of-an-array-3.jq b/Task/Sum-and-product-of-an-array/Jq/sum-and-product-of-an-array-3.jq similarity index 100% rename from Task/Sum-and-product-of-an-array/jq/sum-and-product-of-an-array-3.jq rename to Task/Sum-and-product-of-an-array/Jq/sum-and-product-of-an-array-3.jq diff --git a/Task/Sum-and-product-of-an-array/jq/sum-and-product-of-an-array-4.jq b/Task/Sum-and-product-of-an-array/Jq/sum-and-product-of-an-array-4.jq similarity index 100% rename from Task/Sum-and-product-of-an-array/jq/sum-and-product-of-an-array-4.jq rename to Task/Sum-and-product-of-an-array/Jq/sum-and-product-of-an-array-4.jq diff --git a/Task/Sum-and-product-of-an-array/jq/sum-and-product-of-an-array-5.jq b/Task/Sum-and-product-of-an-array/Jq/sum-and-product-of-an-array-5.jq similarity index 100% rename from Task/Sum-and-product-of-an-array/jq/sum-and-product-of-an-array-5.jq rename to Task/Sum-and-product-of-an-array/Jq/sum-and-product-of-an-array-5.jq diff --git a/Task/Sum-and-product-of-an-array/Kotlin/sum-and-product-of-an-array.kotlin b/Task/Sum-and-product-of-an-array/Kotlin/sum-and-product-of-an-array.kotlin new file mode 100644 index 0000000000..9ffe11d7a0 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Kotlin/sum-and-product-of-an-array.kotlin @@ -0,0 +1,10 @@ +// version 1.1.2 + +fun main(args: Array) { + val a = intArrayOf(1, 5, 8, 11, 15) + println("Array contains : ${a.contentToString()}") + val sum = a.sum() + println("Sum is $sum") + val product = a.fold(1) { acc, i -> acc * i } + println("Product is $product") +} diff --git a/Task/Sum-and-product-of-an-array/OoRexx/sum-and-product-of-an-array.rexx b/Task/Sum-and-product-of-an-array/OoRexx/sum-and-product-of-an-array.rexx new file mode 100644 index 0000000000..8b2608ddcd --- /dev/null +++ b/Task/Sum-and-product-of-an-array/OoRexx/sum-and-product-of-an-array.rexx @@ -0,0 +1,22 @@ +a=.my_array~new(20) +do i=1 To 20 + a[i]=i + End +s=a~makestring((LINE),',') +Say s +Say ' sum='a~sum +Say 'product='a~prod +::class my_array subclass array +::method sum +sum=0 +Do i=1 To self~dimension(1) + sum+=self[i] + End +Return sum +::method prod +Numeric Digits 30 +prod=1 +Do i=1 To self~dimension(1) + prod*=self[i] + End +Return prod diff --git a/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust b/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust index 01be26c8b0..f840e95c52 100644 --- a/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust +++ b/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust @@ -1,7 +1,5 @@ -#![feature(iter_arith)] - fn main() { - let arr: [i32; 9] = [1i32, 2, 3, 4, 5, 6, 7, 8, 9]; + let arr = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; // using fold let sum = arr.iter().fold(0i32, |a, &b| a + b); @@ -9,7 +7,6 @@ fn main() { println!("the sum is {} and the product is {}", sum, product); // or using sum and product - // these are NOT YET STABLE (hence the #![feature(..)] line let sum = arr.iter().sum::(); let product = arr.iter().product::(); println!("the sum is {} and the product is {}", sum, product); diff --git a/Task/Sum-and-product-of-an-array/TI-83-BASIC/sum-and-product-of-an-array.ti-83 b/Task/Sum-and-product-of-an-array/TI-83-BASIC/sum-and-product-of-an-array.ti-83 new file mode 100644 index 0000000000..a6789ec721 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/TI-83-BASIC/sum-and-product-of-an-array.ti-83 @@ -0,0 +1,6 @@ +seq(X,X,1,10,1)→L₁ +{1 2 3 4 5 6 7 8 9 10} +sum(L₁) +55 +prod(L₁) +3628800 diff --git a/Task/Sum-and-product-of-an-array/Zkl/sum-and-product-of-an-array.zkl b/Task/Sum-and-product-of-an-array/Zkl/sum-and-product-of-an-array.zkl new file mode 100644 index 0000000000..47ff4d68e9 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Zkl/sum-and-product-of-an-array.zkl @@ -0,0 +1,2 @@ +fcn sum(vals){vals.reduce('+,0)} +fcn product(vals){vals.reduce('*,1)} diff --git a/Task/Sum-digits-of-an-integer/ALGOL-68/sum-digits-of-an-integer-2.alg b/Task/Sum-digits-of-an-integer/ALGOL-68/sum-digits-of-an-integer-2.alg index 3dadc8c11e..ce54f44600 100644 --- a/Task/Sum-digits-of-an-integer/ALGOL-68/sum-digits-of-an-integer-2.alg +++ b/Task/Sum-digits-of-an-integer/ALGOL-68/sum-digits-of-an-integer-2.alg @@ -1,3 +1,5 @@ +-- INTEGER DIGITS SUMMED ----------------------------------------------------- + -- digitsSummed :: (Int | String) -> Int on digitsSummed(n) @@ -23,33 +25,30 @@ on digitsSummed(n) end if end digitValue - on lambda(accumulator, strDigit) + on |λ|(accumulator, strDigit) accumulator + digitValue(strDigit) - end lambda + end |λ| end script foldl(digitAdded, 0, splitOn("", n as string)) end digitsSummed --- TEST - --- showDigitSum :: Int -> String -on showDigitSum(n) - (n as string) & " -> " & digitsSummed(n) -end showDigitSum - - +-- TEST ---------------------------------------------------------------------- on run + -- showDigitSum :: Int -> String + script showDigitSum + on |λ|(n) + (n as string) & " -> " & digitsSummed(n) + end |λ| + end script intercalate(linefeed, ¬ - map(showDigitSum, [1, 12345, "254", "fe", "f0e", "999ABCXYZ"])) - + map(showDigitSum, [1, 1234, "254", "fe", "f0e", "999ABCXYZ"])) end run - --- GENERIC FUNCTIONS +-- GENERIC FUNCTIONS --------------------------------------------------------- -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) @@ -57,19 +56,27 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -82,7 +89,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn @@ -94,11 +101,3 @@ on splitOn(strDelim, strMain) set my text item delimiters to dlm return xs end splitOn - --- intercalate :: Text -> [Text] -> Text -on intercalate(strText, lstText) - set {dlm, my text item delimiters} to {my text item delimiters, strText} - set strJoined to lstText as text - set my text item delimiters to dlm - return strJoined -end intercalate diff --git a/Task/Sum-digits-of-an-integer/Bc/sum-digits-of-an-integer.bc b/Task/Sum-digits-of-an-integer/Bc/sum-digits-of-an-integer.bc new file mode 100644 index 0000000000..129fe795cf --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Bc/sum-digits-of-an-integer.bc @@ -0,0 +1,20 @@ +define s(n) { + auto i, o, s + + o = scale + scale = 0 + + for (i = n; i > 0; i /= ibase) { + s += i % ibase + } + + scale = o + return(s) +} + +ibase = 10 +s(1) +s(1234) +ibase = 16 +s(FE) +s(F0E) diff --git a/Task/Sum-digits-of-an-integer/Haskell/sum-digits-of-an-integer-1.hs b/Task/Sum-digits-of-an-integer/Haskell/sum-digits-of-an-integer-1.hs new file mode 100644 index 0000000000..3f475cf14b --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Haskell/sum-digits-of-an-integer-1.hs @@ -0,0 +1,12 @@ +digsum + :: Integral a + => a -> a -> a +digsum base = f 0 + where + f a 0 = a + f a n = f (a + r) q + where + (q, r) = n `quotRem` base + +main :: IO () +main = print $ digsum 16 255 -- "FF": 15 + 15 = 30 diff --git a/Task/Sum-digits-of-an-integer/Haskell/sum-digits-of-an-integer-2.hs b/Task/Sum-digits-of-an-integer/Haskell/sum-digits-of-an-integer-2.hs new file mode 100644 index 0000000000..67f90d8aa2 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Haskell/sum-digits-of-an-integer-2.hs @@ -0,0 +1,40 @@ +import Data.Char (digitToInt, intToDigit, isHexDigit) +import Data.List (transpose, intersperse) +import Numeric (showIntAtBase, readInt) + +-- Function of digit string +digitSum :: String -> Int +digitSum = sum . (digitToInt <$>) + +-- Function of base and integer value +intDigitSum :: Int -> Int -> Int +intDigitSum base n = digitSum (showIntAtBase base intToDigit n []) + +-- TEST +main :: IO () +main = + mapM_ putStrLn $ + unwords <$> + transpose + (((<$>) =<< flip justifyRight ' ' . succ . maximum . (length <$>)) <$> + transpose + ([ "Base" + , "Digits" + , "Value" + , "digit string -> sum" + , "integer value -> sum" + ] : + ((\(s, b) -> + let v = readBase b s + in [ show b -- base + , show s -- digits + , show v -- value + , show (digitSum s) -- sum from digit string + , show (intDigitSum b v) -- sum from base and value + ]) <$> + [("1", 10), ("1234", 10), ("fe", 16), ("f0e", 16)]))) + where + justifyRight n c s = drop (length s) (replicate n c ++ s) + readBase b s = + let [(n, _)] = readInt b isHexDigit digitToInt s + in n diff --git a/Task/Sum-digits-of-an-integer/Haskell/sum-digits-of-an-integer.hs b/Task/Sum-digits-of-an-integer/Haskell/sum-digits-of-an-integer.hs deleted file mode 100644 index 79ce63457f..0000000000 --- a/Task/Sum-digits-of-an-integer/Haskell/sum-digits-of-an-integer.hs +++ /dev/null @@ -1,6 +0,0 @@ -digsum base = f 0 where - f a 0 = a - f a n = f (a+r) q where - (q,r) = n `divMod` base - -main = print $ digsum 16 255 -- "FF": 15 + 15 = 30 diff --git a/Task/Sum-digits-of-an-integer/jq/sum-digits-of-an-integer-1.jq b/Task/Sum-digits-of-an-integer/Jq/sum-digits-of-an-integer-1.jq similarity index 100% rename from Task/Sum-digits-of-an-integer/jq/sum-digits-of-an-integer-1.jq rename to Task/Sum-digits-of-an-integer/Jq/sum-digits-of-an-integer-1.jq diff --git a/Task/Sum-digits-of-an-integer/jq/sum-digits-of-an-integer-2.jq b/Task/Sum-digits-of-an-integer/Jq/sum-digits-of-an-integer-2.jq similarity index 100% rename from Task/Sum-digits-of-an-integer/jq/sum-digits-of-an-integer-2.jq rename to Task/Sum-digits-of-an-integer/Jq/sum-digits-of-an-integer-2.jq diff --git a/Task/Sum-digits-of-an-integer/Kotlin/sum-digits-of-an-integer.kotlin b/Task/Sum-digits-of-an-integer/Kotlin/sum-digits-of-an-integer.kotlin new file mode 100644 index 0000000000..060193be13 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Kotlin/sum-digits-of-an-integer.kotlin @@ -0,0 +1,22 @@ +// version 1.1.0 + +const val digits = "0123456789abcdefghijklmnopqrstuvwxyz" + +fun sumDigits(ns: String, base: Int): Int { + val n = ns.toLowerCase().trim() + if (base !in 2..36) throw IllegalArgumentException("Base must be between 2 and 36") + if (n.isEmpty()) throw IllegalArgumentException("Number string can't be blank or empty") + var sum = 0 + for (digit in n) { + val index = digits.indexOf(digit) + if (index == -1 || index >= base) throw IllegalArgumentException("Number string contains an invalid digit") + sum += index + } + return sum +} + +fun main(args: Array) { + val numbers = mapOf("1" to 10, "1234" to 10, "fe" to 16, "f0e" to 16, "1010" to 2, "777" to 8, "16xyz" to 36) + println("The sum of digits is:") + for ((number, base) in numbers) println("$number\tbase $base\t-> ${sumDigits(number, base)}") +} diff --git a/Task/Sum-digits-of-an-integer/PowerShell/sum-digits-of-an-integer.psh b/Task/Sum-digits-of-an-integer/PowerShell/sum-digits-of-an-integer-1.psh similarity index 100% rename from Task/Sum-digits-of-an-integer/PowerShell/sum-digits-of-an-integer.psh rename to Task/Sum-digits-of-an-integer/PowerShell/sum-digits-of-an-integer-1.psh diff --git a/Task/Sum-digits-of-an-integer/PowerShell/sum-digits-of-an-integer-2.psh b/Task/Sum-digits-of-an-integer/PowerShell/sum-digits-of-an-integer-2.psh new file mode 100644 index 0000000000..8d06564f62 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/PowerShell/sum-digits-of-an-integer-2.psh @@ -0,0 +1,4 @@ +function Get-DigitalSum ([string] $number, $base = 10) +{ + Invoke-Expression (($number.ToCharArray() | ForEach-Object {[string][convert]::ToInt16($_, $base)}) -join "+") +} diff --git a/Task/Sum-digits-of-an-integer/Ruby/sum-digits-of-an-integer.rb b/Task/Sum-digits-of-an-integer/Ruby/sum-digits-of-an-integer-1.rb similarity index 100% rename from Task/Sum-digits-of-an-integer/Ruby/sum-digits-of-an-integer.rb rename to Task/Sum-digits-of-an-integer/Ruby/sum-digits-of-an-integer-1.rb diff --git a/Task/Sum-digits-of-an-integer/Ruby/sum-digits-of-an-integer-2.rb b/Task/Sum-digits-of-an-integer/Ruby/sum-digits-of-an-integer-2.rb new file mode 100644 index 0000000000..3aa7b7d6ca --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Ruby/sum-digits-of-an-integer-2.rb @@ -0,0 +1,3 @@ +def sumDigits(num, base = 10) + num.digits(base).sum +end diff --git a/Task/Sum-digits-of-an-integer/Run-BASIC/sum-digits-of-an-integer.run b/Task/Sum-digits-of-an-integer/Run-BASIC/sum-digits-of-an-integer.run deleted file mode 100644 index 72f7135215..0000000000 --- a/Task/Sum-digits-of-an-integer/Run-BASIC/sum-digits-of-an-integer.run +++ /dev/null @@ -1,10 +0,0 @@ -input "Gimme a number:";n - -print "Sum of digits :";n;" is ";sum(n) -end -function sum(n) -n$ = str$(n) -for i = 1 to len(n$) - sum = sum + val(mid$(n$,i,1)) -next i -end function diff --git a/Task/Sum-digits-of-an-integer/Rust/sum-digits-of-an-integer.rust b/Task/Sum-digits-of-an-integer/Rust/sum-digits-of-an-integer.rust new file mode 100644 index 0000000000..e59702eaba --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Rust/sum-digits-of-an-integer.rust @@ -0,0 +1,18 @@ +struct DigitIter(usize, usize); + +impl Iterator for DigitIter { + type Item = usize; + fn next(&mut self) -> Option { + if self.0 == 0 { + None + } else { + let ret = self.0 % self.1; + self.0 /= self.1; + Some(ret) + } + } +} + +fn main() { + println!("{}", DigitIter(1234,10).sum::()); +} diff --git a/Task/Sum-digits-of-an-integer/Scheme/sum-digits-of-an-integer.ss b/Task/Sum-digits-of-an-integer/Scheme/sum-digits-of-an-integer.ss new file mode 100644 index 0000000000..b94b1610eb --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Scheme/sum-digits-of-an-integer.ss @@ -0,0 +1,40 @@ +(import (scheme base) + (scheme write)) + +;; convert number to a list of digits, in desired base +(define (number->list n base) + (let loop ((res '()) + (num n)) + (if (< num base) + (cons num res) + (loop (cons (remainder num base) res) + (quotient num base))))) + +;; return the sum of digits of n in given base +(define (sum-digits n base) + (apply + (number->list n base))) + +;; test cases: +;; -- this displays each number in its original, given-base, for comparison +;; -- target-base is the base in which to consider each number represented, for summing the digits +(define (test-case n given-base target-base) + (display (string-append (number->string n given-base) + " base " + (number->string given-base) + " has decimal value " + (number->string n) + " => sum of digits in base " + (number->string target-base) + " is " + (number->string (sum-digits n target-base)))) + (newline)) + +(test-case 1 10 10) +(test-case 1234 10 10) +(test-case #o1234 8 10) +(test-case #xFE 16 16) +(test-case #xFE 16 10) +(test-case #xF0E 16 16) +(test-case #b1101010101010101010101010101010101 2 2) +(test-case #b1101010101010101010101010101010101 2 10) +(test-case #b1101010101010101010101010101010101 2 1000) diff --git a/Task/Sum-digits-of-an-integer/Zkl/sum-digits-of-an-integer.zkl b/Task/Sum-digits-of-an-integer/Zkl/sum-digits-of-an-integer.zkl new file mode 100644 index 0000000000..24608a96e8 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Zkl/sum-digits-of-an-integer.zkl @@ -0,0 +1,4 @@ +fcn sum(n,b=10){ + if(b==10) n.split().sum(0); // digits to list + else n.toString(b).split("").apply("toInt",b).sum(0); +} diff --git a/Task/Sum-multiples-of-3-and-5/ALGOL-68/sum-multiples-of-3-and-5-3.alg b/Task/Sum-multiples-of-3-and-5/ALGOL-68/sum-multiples-of-3-and-5-3.alg index df3ed962b3..3e19c05e0a 100644 --- a/Task/Sum-multiples-of-3-and-5/ALGOL-68/sum-multiples-of-3-and-5-3.alg +++ b/Task/Sum-multiples-of-3-and-5/ALGOL-68/sum-multiples-of-3-and-5-3.alg @@ -1,37 +1,55 @@ --- sum35 :: Int -> Int -on sum35(n) - sumMults(n, 3) + sumMults(n, 5) - sumMults(n, 15) -end sum35 +-- SUM MULTIPLES OF 3 AND 5 -------------------------------------------------- --- Area under straight line between first multiple and last: +-- sums of all multiples of 3 or 5 below or equal to N +-- for N = 10 to N = 10E8 (limit of AS integers) --- sumMults :: Int -> Int -> Int -on sumMults(n, f) - set n1 to (n - 1) div f +-- sum35Result :: String -> Int -> Int -> String +script sum35Result - f * n1 * (n1 + 1) div 2 -end sumMults + -- sum35 :: Int -> Int + on sum35(n) + sumMults(n, 3) + sumMults(n, 5) - sumMults(n, 15) + end sum35 + + -- Area under straight line between first multiple and last: + + -- sumMults :: Int -> Int -> Int + on sumMults(n, f) + set n1 to (n - 1) div f + + f * n1 * (n1 + 1) div 2 + end sumMults + + on |λ|(a, x, i) + a & "10" & i & " -> " & ¬ + sum35(10 ^ x) & "
    " + end |λ| +end script --- TEST +-- TEST ---------------------------------------------------------------------- on run - -- sums of all multiples of 3 or 5 below or equal to N - -- for N = 10 to N = 10E8 (limit of AS integers) - -- sum35Result :: String -> Int -> Int -> String - script sum35Result - on lambda(a, x, i) - a & "10" & i & " -> " & ¬ - sum35(10 ^ x) & "
    " - end lambda - end script + foldl(sum35Result, "", enumFromTo(1, 8)) - foldl(sum35Result, "", range(1, 8)) end run +-- GENERIC FUNCTIONS --------------------------------------------------------- --- GENERIC LIBRARY FUNCTIONS +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) @@ -39,7 +57,7 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -52,26 +70,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn - --- range :: Int -> Int -> [Int] -on range(m, n) - set d to cond(n < m, -1, 1) - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range - --- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b) -on cond(bool, f, g) - if bool then - f - else - g - end if -end cond diff --git a/Task/Sum-multiples-of-3-and-5/AWK/sum-multiples-of-3-and-5-3.awk b/Task/Sum-multiples-of-3-and-5/AWK/sum-multiples-of-3-and-5-3.awk new file mode 100644 index 0000000000..2a3d0d26a0 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/AWK/sum-multiples-of-3-and-5-3.awk @@ -0,0 +1,10 @@ + 10 INPUT N + 20 FAST + 30 LET SUM=0 + 40 FOR I=3 TO N-1 + 50 IF I/3=INT (I/3) THEN GOTO 70 + 60 IF I/5<>INT (I/5) THEN GOTO 80 + 70 LET SUM=SUM+I + 80 NEXT I + 90 SLOW +100 PRINT SUM diff --git a/Task/Sum-multiples-of-3-and-5/Bc/sum-multiples-of-3-and-5-1.bc b/Task/Sum-multiples-of-3-and-5/Bc/sum-multiples-of-3-and-5-1.bc new file mode 100644 index 0000000000..e1798f3aa5 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Bc/sum-multiples-of-3-and-5-1.bc @@ -0,0 +1,13 @@ +define t(n, f) { + auto m + + m = (n - 1) / f + return(f * m * (m + 1) / 2) +} + +define s(l) { + return(t(l, 3) + t(l, 5) - t(l, 15)) +} + +s(1000) +s(10 ^ 20) diff --git a/Task/Sum-multiples-of-3-and-5/Bc/sum-multiples-of-3-and-5-2.bc b/Task/Sum-multiples-of-3-and-5/Bc/sum-multiples-of-3-and-5-2.bc new file mode 100644 index 0000000000..3113a13035 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Bc/sum-multiples-of-3-and-5-2.bc @@ -0,0 +1,3 @@ +&1-:!#v_:3%#v_ >:># + >+\:v >:5%#v_^ + @.$_^#! < > ^ diff --git a/Task/Sum-multiples-of-3-and-5/Bc/sum-multiples-of-3-and-5-3.bc b/Task/Sum-multiples-of-3-and-5/Bc/sum-multiples-of-3-and-5-3.bc new file mode 100644 index 0000000000..5a924a8e13 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Bc/sum-multiples-of-3-and-5-3.bc @@ -0,0 +1 @@ +&1-::3/:1+*3*2/\5/:1+*5*2/+\96+/:1+*96+*2/-.@ diff --git a/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5-1.e b/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5-1.e deleted file mode 100644 index feeaa57930..0000000000 --- a/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5-1.e +++ /dev/null @@ -1,27 +0,0 @@ -class - SUM_MULTIPLES_OF_THREE_AND_FIVE - -feature - is_multiple(x,y: INTEGER):BOOLEAN - local - do - RESULT:= x\\y=0 - end - - sum_multiples(n: INTEGER): INTEGER - local - i,sum: INTEGER - do - from - i:= 1 - until - i=n - loop - if is_multiple(i,3) or is_multiple(i,5) then - sum:= sum+i - end - i:= i+1 - end - Result:= sum - end -end diff --git a/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5-2.e b/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5-2.e deleted file mode 100644 index 56db06a880..0000000000 --- a/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5-2.e +++ /dev/null @@ -1,15 +0,0 @@ -class - APPLICATION -inherit - ARGUMENTS -create - make -feature {NONE} -- Initialization - make - local - do - create sum - io.put_integer(sum.sum_multiples (1000)) - end - sum: SUM_MULTIPLES_OF_THREE_AND_FIVE -end diff --git a/Task/Sum-multiples-of-3-and-5/Haskell/sum-multiples-of-3-and-5.hs b/Task/Sum-multiples-of-3-and-5/Haskell/sum-multiples-of-3-and-5.hs index 30ae9f0f6b..068c9d99f8 100644 --- a/Task/Sum-multiples-of-3-and-5/Haskell/sum-multiples-of-3-and-5.hs +++ b/Task/Sum-multiples-of-3-and-5/Haskell/sum-multiples-of-3-and-5.hs @@ -1,18 +1,31 @@ import Data.List (nub) -sumMul n f = f * n1 * (n1 + 1) `div` 2 where n1 = (n - 1) `div` f +sum35 :: Integral a => a -> a sum35 n = sumMul n 3 + sumMul n 5 - sumMul n 15 --- below are for variable length inputs +sumMul :: Integral a => a -> a -> a +sumMul n f = f * n1 * (n1 + 1) `div` 2 + where + n1 = (n - 1) `div` f + +-- Functions below are for variable length inputs + +pairLCM :: Integral a => [a] -> [a] pairLCM [] = [] -pairLCM (x:xs) = map (lcm x) xs ++ pairLCM xs +pairLCM (x:xs) = (lcm x <$> xs) ++ pairLCM xs +sumMulS :: Integral a => a -> [a] -> a sumMulS _ [] = 0 -sumMulS n s = sum (map (sumMul n) ss) - sumMulS n (pairLCM ss) - where ss = nub s +sumMulS n s = sum (sumMul n <$> ss) - sumMulS n (pairLCM ss) + where + ss = nub s -main = do - print $ sum35 1000 - print $ sum35 100000000000000000000000000000000 - print $ sumMulS 1000 [3,5] - print $ sumMulS 10000000 [2,3,5,7,11,13] +main :: IO () +main = + mapM_ + print + [ sum35 1000 + , sum35 100000000000000000000000000000000 + , sumMulS 1000 [3, 5] + , sumMulS 10000000 [2, 3, 5, 7, 11, 13] + ] diff --git a/Task/Sum-multiples-of-3-and-5/JavaScript/sum-multiples-of-3-and-5-7.js b/Task/Sum-multiples-of-3-and-5/JavaScript/sum-multiples-of-3-and-5-7.js index 3e55c89901..b342b26c90 100644 --- a/Task/Sum-multiples-of-3-and-5/JavaScript/sum-multiples-of-3-and-5-7.js +++ b/Task/Sum-multiples-of-3-and-5/JavaScript/sum-multiples-of-3-and-5-7.js @@ -1,35 +1,36 @@ (() => { // Area under straight line - // between first multiple and last - let sumMults = (n, factor) => { - let n1 = Math.floor((n - 1) / factor); + // between first multiple and last. - return Math.floor(factor * n1 * (n1 + 1) / 2); - }, + // sumMults :: Int -> Int -> Int + const sumMults = (n, factor) => { + const n1 = quot(n - 1, factor); + return quot(factor * n1 * (n1 + 1), 2); + }; - sum35 = (n) => sumMults(n, 3) + sumMults(n, 5) - sumMults(n, 15); + // sum35 :: Int -> Int + const sum35 = n => sumMults(n, 3) + sumMults(n, 5) - sumMults(n, 15); - // TEST + // GENERIC ---------------------------------------------------------------- - // range(intFrom, intTo, optional intStep) - // Int -> Int -> Maybe Int -> [Int] - let range = (m, n, step) => { - let d = (step || 1) * (n >= m ? 1 : -1); + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); - return Array.from({ - length: Math.floor((n - m) / d) + 1 - }, (_, i) => m + (i * d)); - } + // Integral a => a -> a -> a + const quot = (n, m) => Math.floor(n / m); + + // TEST ------------------------------------------------------------------- // Sums for 10^1 thru 10^8 - - return range(1, 8) + return enumFromTo(1, 8) .map(n => Math.pow(10, n)) .reduce((a, x) => ( a[x.toString()] = sum35(x), a ), {}); - })(); diff --git a/Task/Sum-multiples-of-3-and-5/jq/sum-multiples-of-3-and-5-1.jq b/Task/Sum-multiples-of-3-and-5/Jq/sum-multiples-of-3-and-5-1.jq similarity index 100% rename from Task/Sum-multiples-of-3-and-5/jq/sum-multiples-of-3-and-5-1.jq rename to Task/Sum-multiples-of-3-and-5/Jq/sum-multiples-of-3-and-5-1.jq diff --git a/Task/Sum-multiples-of-3-and-5/jq/sum-multiples-of-3-and-5-2.jq b/Task/Sum-multiples-of-3-and-5/Jq/sum-multiples-of-3-and-5-2.jq similarity index 100% rename from Task/Sum-multiples-of-3-and-5/jq/sum-multiples-of-3-and-5-2.jq rename to Task/Sum-multiples-of-3-and-5/Jq/sum-multiples-of-3-and-5-2.jq diff --git a/Task/Sum-multiples-of-3-and-5/Kotlin/sum-multiples-of-3-and-5.kotlin b/Task/Sum-multiples-of-3-and-5/Kotlin/sum-multiples-of-3-and-5.kotlin new file mode 100644 index 0000000000..96c5822e48 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Kotlin/sum-multiples-of-3-and-5.kotlin @@ -0,0 +1,31 @@ +// version 1.1.2 + +import java.math.BigInteger + +val big2 = BigInteger.valueOf(2) +val big3 = BigInteger.valueOf(3) +val big5 = BigInteger.valueOf(5) +val big15 = big3 * big5 + +fun sum35(n: Int) = (3 until n).filter { it % 3 == 0 || it % 5 == 0}.sum() + +fun sum35(n: BigInteger): BigInteger { + val nn = n - BigInteger.ONE + val num3 = nn / big3 + val end3 = num3 * big3 + val sum3 = (big3 + end3) * num3 / big2 + val num5 = nn / big5 + val end5 = num5 * big5 + val sum5 = (big5 + end5) * num5 / big2 + val num15 = nn / big15 + val end15 = num15 * big15 + val sum15 = (big15 + end15) * num15 / big2 + return sum3 + sum5 - sum15 +} + +fun main(args: Array) { + println("The sum of multiples of 3 or 5 below 1000 is ${sum35(1000)}") + val big100k = BigInteger.valueOf(100_000L) + val e20 = big100k * big100k * big100k * big100k + println("The sum of multiples of 3 or 5 below 1e20 is ${sum35(e20)}") +} diff --git a/Task/Sum-multiples-of-3-and-5/Phix/sum-multiples-of-3-and-5.phix b/Task/Sum-multiples-of-3-and-5/Phix/sum-multiples-of-3-and-5.phix new file mode 100644 index 0000000000..a43733c412 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Phix/sum-multiples-of-3-and-5.phix @@ -0,0 +1,18 @@ +include bigatom.e + +function s(bigatom n, integer d) + bigatom m = ba_idivide(n,d) + m = ba_multiply(m,ba_add(m,1)) + return ba_divide(ba_multiply(d,m),2) +end function + +function sum35(bigatom n) + bigatom n1 = ba_sub(n,1) + return ba_sub(ba_add(s(n1,3),s(n1,5)),s(n1,15)) +end function + +for i=0 to 20 do + string sp = repeat(' ',20-i) + printf(1,sp&"1"&repeat('0',i)&sp) + ba_printf(1," %B\n",sum35(ba_power(10,i))) +end for diff --git a/Task/Sum-multiples-of-3-and-5/Stata/sum-multiples-of-3-and-5-1.stata b/Task/Sum-multiples-of-3-and-5/Stata/sum-multiples-of-3-and-5-1.stata new file mode 100644 index 0000000000..2564bea087 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Stata/sum-multiples-of-3-and-5-1.stata @@ -0,0 +1,4 @@ +clear all +set obs 999 +gen a=_n +tabstat a if mod(a,3)==0 | mod(a,5)==0, statistic(sum) diff --git a/Task/Sum-multiples-of-3-and-5/Stata/sum-multiples-of-3-and-5-2.stata b/Task/Sum-multiples-of-3-and-5/Stata/sum-multiples-of-3-and-5-2.stata new file mode 100644 index 0000000000..f2d0478800 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Stata/sum-multiples-of-3-and-5-2.stata @@ -0,0 +1,3 @@ +mata +a=1..999 +sum(a:*(mod(a,3):==0 :| mod(a,5):==0)) diff --git a/Task/Sum-multiples-of-3-and-5/Swift/sum-multiples-of-3-and-5.swift b/Task/Sum-multiples-of-3-and-5/Swift/sum-multiples-of-3-and-5.swift new file mode 100644 index 0000000000..80017a480b --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Swift/sum-multiples-of-3-and-5.swift @@ -0,0 +1,17 @@ +var n:Int=1000 + +func sum(x:Int)->Int{ + + var s:Int=0 + for i in 0...x{ + if i%3==0 || i%5==0 + { + s=s+i + } + + } + return s +} + +var sumofmult:Int=sum(x:n) +print(sumofmult) diff --git a/Task/Sum-multiples-of-3-and-5/Zkl/sum-multiples-of-3-and-5-1.zkl b/Task/Sum-multiples-of-3-and-5/Zkl/sum-multiples-of-3-and-5-1.zkl new file mode 100644 index 0000000000..2d302a6028 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Zkl/sum-multiples-of-3-and-5-1.zkl @@ -0,0 +1,2 @@ +[3..999,3].reduce('+,0) + [5..999,5].reduce('+,0) - [15..999,15].reduce('+,0) +233168 diff --git a/Task/Sum-multiples-of-3-and-5/Zkl/sum-multiples-of-3-and-5-2.zkl b/Task/Sum-multiples-of-3-and-5/Zkl/sum-multiples-of-3-and-5-2.zkl new file mode 100644 index 0000000000..b999f77c45 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Zkl/sum-multiples-of-3-and-5-2.zkl @@ -0,0 +1,2 @@ +fcn sumMul(N,m){N=(N-1)/m; N*(N+1)*m/2} +fcn sum35(N){sumMul(N,3) + sumMul(N,5) - sumMul(N,15)} diff --git a/Task/Sum-of-a-series/360-Assembly/sum-of-a-series.360 b/Task/Sum-of-a-series/360-Assembly/sum-of-a-series.360 new file mode 100644 index 0000000000..93c702a54c --- /dev/null +++ b/Task/Sum-of-a-series/360-Assembly/sum-of-a-series.360 @@ -0,0 +1,24 @@ +* Sum of a series 30/03/2017 +SUMSER CSECT + USING SUMSER,12 base register + LR 12,15 set addressability + LR 10,14 save r14 + LE 4,=E'0' s=0 + LE 2,=E'1' i=1 + DO WHILE=(CE,2,LE,=E'1000') do i=1 to 1000 + LER 0,2 i + MER 0,2 *i + LE 6,=E'1' 1 + DER 6,0 1/i**2 + AER 4,6 s=s+1/i**2 + AE 2,=E'1' i=i+1 + ENDDO , enddo i + LA 0,4 format F13.4 + LER 0,4 s + BAL 14,FORMATF call formatf + MVC PG(13),0(1) retrieve result + XPRNT PG,80 print buffer + BR 10 exit + COPY FORMATF formatf code +PG DC CL80' ' buffer + END SUMSER diff --git a/Task/Sum-of-a-series/AppleScript/sum-of-a-series-1.applescript b/Task/Sum-of-a-series/AppleScript/sum-of-a-series-1.applescript index 8797288b51..1837681e1d 100644 --- a/Task/Sum-of-a-series/AppleScript/sum-of-a-series-1.applescript +++ b/Task/Sum-of-a-series/AppleScript/sum-of-a-series-1.applescript @@ -1,34 +1,46 @@ --- TEST --------------------------------------------------------- - -on inverseSquare(x) - 1 / (x ^ 2) -end inverseSquare - -on run - - seriesSum(inverseSquare, range(1, 1000)) - - --> 1.643934566682 -end run - - --- SUM OF SERIES ---------------------------------------------- +-- SUM OF SERIES ------------------------------------------------------------- -- seriesSum :: Num a => (a -> a) -> [a] -> a on seriesSum(f, xs) set mf to mReturn(f) script - on lambda(a, x) - a + (mf's lambda(x)) - end lambda + on |λ|(a, x) + a + (mf's |λ|(x)) + end |λ| end script foldl(result, 0, xs) end seriesSum +-- TEST ---------------------------------------------------------------------- --- GENERIC FUNCTIONS ------------------------------------------ +on inverseSquare(x) + 1 / (x ^ 2) +end inverseSquare + +on run + seriesSum(inverseSquare, enumFromTo(1, 1000)) + + --> 1.643934566682 +end run + + +-- GENERIC FUNCTIONS --------------------------------------------------------- + +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) @@ -36,7 +48,7 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -49,21 +61,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn - --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then - set d to -1 - else - set d to 1 - end if - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range diff --git a/Task/Sum-of-a-series/Bc/sum-of-a-series.bc b/Task/Sum-of-a-series/Bc/sum-of-a-series.bc new file mode 100644 index 0000000000..578a3abe76 --- /dev/null +++ b/Task/Sum-of-a-series/Bc/sum-of-a-series.bc @@ -0,0 +1,16 @@ +define f(x) { + return(1 / (x * x)) +} + +define s(n) { + auto i, s + + for (i = 1; i <= n; i++) { + s += f(i) + } + + return(s) +} + +scale = 20 +s(1000) diff --git a/Task/Sum-of-a-series/Elena/sum-of-a-series.elena b/Task/Sum-of-a-series/Elena/sum-of-a-series.elena new file mode 100644 index 0000000000..e10d9d82b5 --- /dev/null +++ b/Task/Sum-of-a-series/Elena/sum-of-a-series.elena @@ -0,0 +1,9 @@ +import system'routines. +import extensions. + +program = +[ + var sum := 1 to:1000 repeat(:x)(1.0r / (x * x)); summarize(Real new). + + console printLine:sum. +]. diff --git a/Task/Sum-of-a-series/Fortran/sum-of-a-series.f b/Task/Sum-of-a-series/Fortran/sum-of-a-series-1.f similarity index 100% rename from Task/Sum-of-a-series/Fortran/sum-of-a-series.f rename to Task/Sum-of-a-series/Fortran/sum-of-a-series-1.f diff --git a/Task/Sum-of-a-series/Fortran/sum-of-a-series-2.f b/Task/Sum-of-a-series/Fortran/sum-of-a-series-2.f new file mode 100644 index 0000000000..865a8b9c61 --- /dev/null +++ b/Task/Sum-of-a-series/Fortran/sum-of-a-series-2.f @@ -0,0 +1,6 @@ + s=0 + do i=1,1000 + s=s+1./i**2 + end do + write (*,*) s + end diff --git a/Task/Sum-of-a-series/Haskell/sum-of-a-series-4.hs b/Task/Sum-of-a-series/Haskell/sum-of-a-series-4.hs index ded8ffa0fa..dfbd6f9e6e 100644 --- a/Task/Sum-of-a-series/Haskell/sum-of-a-series-4.hs +++ b/Task/Sum-of-a-series/Haskell/sum-of-a-series-4.hs @@ -1,8 +1 @@ -import Data.List (foldl') - -seriesSum :: Num a => (a -> a) -> [a] -> a -seriesSum f xs = foldl' (\a x -> a + (f x)) 0 xs - -main :: IO() -main = putStrLn $ show $ - seriesSum (\x -> 1 / x ^ 2) [1..1000] +(sum . map ((1 /) . (^ 2))) [1 .. 1000] diff --git a/Task/Sum-of-a-series/Haskell/sum-of-a-series-5.hs b/Task/Sum-of-a-series/Haskell/sum-of-a-series-5.hs new file mode 100644 index 0000000000..317fb44f05 --- /dev/null +++ b/Task/Sum-of-a-series/Haskell/sum-of-a-series-5.hs @@ -0,0 +1,6 @@ +seriesSum f = foldr ((+) . f) 0 + +inverseSquare = (1 /) . (^ 2) + +main :: IO () +main = print $ seriesSum inverseSquare [1 .. 1000] diff --git a/Task/Sum-of-a-series/JavaScript/sum-of-a-series-4.js b/Task/Sum-of-a-series/JavaScript/sum-of-a-series-4.js index 0bed4ec680..a0b4cd1c9f 100644 --- a/Task/Sum-of-a-series/JavaScript/sum-of-a-series-4.js +++ b/Task/Sum-of-a-series/JavaScript/sum-of-a-series-4.js @@ -1,20 +1,25 @@ (() => { 'use strict'; + // SUM OF A SERIES ------------------------------------------------------- + // seriesSum :: Num a => (a -> a) -> [a] -> a const seriesSum = (f, xs) => - xs.reduce((a, x) => a + f(x), 0); + foldl((a, x) => a + f(x), 0, xs); - // GENERIC ------------------------------------------ + // GENERIC --------------------------------------------------------------- - // range :: Int -> Int -> [Int] - const range = (m, n) => + // enumFromToInt :: Int -> Int -> [Int] + const enumFromTo = (m, n) => Array.from({ length: Math.floor(n - m) + 1 }, (_, i) => m + i); - // TEST ---------------------------------------------- + // foldl :: (b -> a -> b) -> b -> [a] -> b + const foldl = (f, a, xs) => xs.reduce(f, a); - return seriesSum(x => 1 / (x * x), range(1, 1000)); + // TEST ------------------------------------------------------------------ + + return seriesSum(x => 1 / (x * x), enumFromTo(1, 1000)); })(); diff --git a/Task/Sum-of-a-series/jq/sum-of-a-series-1.jq b/Task/Sum-of-a-series/Jq/sum-of-a-series-1.jq similarity index 100% rename from Task/Sum-of-a-series/jq/sum-of-a-series-1.jq rename to Task/Sum-of-a-series/Jq/sum-of-a-series-1.jq diff --git a/Task/Sum-of-a-series/jq/sum-of-a-series-2.jq b/Task/Sum-of-a-series/Jq/sum-of-a-series-2.jq similarity index 100% rename from Task/Sum-of-a-series/jq/sum-of-a-series-2.jq rename to Task/Sum-of-a-series/Jq/sum-of-a-series-2.jq diff --git a/Task/Sum-of-a-series/Kotlin/sum-of-a-series.kotlin b/Task/Sum-of-a-series/Kotlin/sum-of-a-series.kotlin new file mode 100644 index 0000000000..6782d0bc0b --- /dev/null +++ b/Task/Sum-of-a-series/Kotlin/sum-of-a-series.kotlin @@ -0,0 +1,8 @@ +// version 1.0.6 + +fun main(args: Array) { + val n = 1000 + val sum = (1..n).sumByDouble { 1.0 / (it * it) } + println("Actual sum is $sum") + println("zeta(2) is ${Math.PI * Math.PI / 6.0}") +} diff --git a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-5.pl6 b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-5.pl6 index 97d6d0204a..8ecf94d87f 100644 --- a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-5.pl6 +++ b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-5.pl6 @@ -1,2 +1 @@ -constant @x = [\+] 0, { 1 / ++(state $n) ** 2 } ... *; -say @x[1000]; # prints 1.64393456668156 +say [+] (1 / $_**2 for 1..1000); diff --git a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-6.pl6 b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-6.pl6 index 238a7b8dce..97d6d0204a 100644 --- a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-6.pl6 +++ b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-6.pl6 @@ -1,2 +1,2 @@ -constant ζish = [\+] map -> \𝑖 { 1 / 𝑖**2 }, 1..*; -say ζish[1000]; +constant @x = [\+] 0, { 1 / ++(state $n) ** 2 } ... *; +say @x[1000]; # prints 1.64393456668156 diff --git a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 index 05c2bee1c7..238a7b8dce 100644 --- a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 +++ b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 @@ -1,2 +1,2 @@ -sub ζ($s) is cached { [\+] 1..* X** -$s } -say ζ(2)[1000]; +constant ζish = [\+] map -> \𝑖 { 1 / 𝑖**2 }, 1..*; +say ζish[1000]; diff --git a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-8.pl6 b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-8.pl6 index 8ecf94d87f..05c2bee1c7 100644 --- a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-8.pl6 +++ b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-8.pl6 @@ -1 +1,2 @@ -say [+] (1 / $_**2 for 1..1000); +sub ζ($s) is cached { [\+] 1..* X** -$s } +say ζ(2)[1000]; diff --git a/Task/Sum-of-a-series/Standard-ML/sum-of-a-series.ml b/Task/Sum-of-a-series/Standard-ML/sum-of-a-series.ml deleted file mode 100644 index 7ecf618b52..0000000000 --- a/Task/Sum-of-a-series/Standard-ML/sum-of-a-series.ml +++ /dev/null @@ -1,2 +0,0 @@ -(* 1.64393456668 *) -List.foldl op+ 0.0 (List.tabulate(1000, fn x => 1.0 / Math.pow(real(x + 1),2.0))) diff --git a/Task/Sum-of-a-series/TI-83-BASIC/sum-of-a-series.ti-83 b/Task/Sum-of-a-series/TI-83-BASIC/sum-of-a-series.ti-83 new file mode 100644 index 0000000000..c5b3556cd5 --- /dev/null +++ b/Task/Sum-of-a-series/TI-83-BASIC/sum-of-a-series.ti-83 @@ -0,0 +1 @@ +∑(1/X²,X,1,1000) diff --git a/Task/Sum-of-a-series/VBScript/sum-of-a-series.vb b/Task/Sum-of-a-series/VBScript/sum-of-a-series.vb new file mode 100644 index 0000000000..3a57836fd3 --- /dev/null +++ b/Task/Sum-of-a-series/VBScript/sum-of-a-series.vb @@ -0,0 +1,5 @@ +' Sum of a series + for i=1 to 1000 + s=s+1/i^2 + next + wscript.echo s diff --git a/Task/Sum-of-a-series/Visual-Basic-.NET/sum-of-a-series.visual b/Task/Sum-of-a-series/Visual-Basic-.NET/sum-of-a-series.visual new file mode 100644 index 0000000000..0872e012b2 --- /dev/null +++ b/Task/Sum-of-a-series/Visual-Basic-.NET/sum-of-a-series.visual @@ -0,0 +1,9 @@ +' Sum of a series + Sub SumOfaSeries() + Dim s As Double + s = 0 + For i = 1 To 1000 + s = s + 1 / i ^ 2 + Next 'i + Console.WriteLine(s) + End Sub diff --git a/Task/Sum-of-a-series/Zkl/sum-of-a-series.zkl b/Task/Sum-of-a-series/Zkl/sum-of-a-series.zkl new file mode 100644 index 0000000000..308b9a96eb --- /dev/null +++ b/Task/Sum-of-a-series/Zkl/sum-of-a-series.zkl @@ -0,0 +1 @@ +[1.0..1000].reduce(fcn(p,n){ p + 1.0/(n*n) },0.0) //-->1.64394 diff --git a/Task/Sum-of-squares/ALGOL-68/sum-of-squares-3.alg b/Task/Sum-of-squares/ALGOL-68/sum-of-squares-3.alg new file mode 100644 index 0000000000..891f282dcb --- /dev/null +++ b/Task/Sum-of-squares/ALGOL-68/sum-of-squares-3.alg @@ -0,0 +1,44 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +MODE YIELDREAL = PROC(REAL)VOID; +MODE GENREAL = PROC(YIELDREAL)VOID; + +PROC gen real of vector = ([]REAL data, YIELDREAL yield)VOID: + FOR i FROM LWB data TO UPB data DO yield(data[i]) OD; + +PROC real sum sq of gen = (GENREAL gen real)REAL: ( + REAL sum:=0; +# FOR REAL value IN # gen real(#) DO (# + (REAL value)VOID:( + sum+:=value**2 +# OD #)); + sum +); + +PROC real sum map of gen = (PROC(REAL)REAL func, GENREAL gen real)REAL: ( + REAL sum:=0; +# FOR REAL value IN # gen real(#) DO (# + (REAL value)VOID:( + sum+:=func(value) +# OD #)); + sum +); + +OP GEN = ([]REAL array)GENREAL:gen real of vector(array,); + +OP (GENREAL #gen real#)REAL SUMSQ = real sum sq of gen; + +PRIO SUMMAP = 5; +OP (PROC(REAL)REAL #func#, GENREAL #gen real#)REAL SUMMAP = real sum map of gen; + +test:( + []REAL data = (3, 1, 4, 1, 5, 9); +# Permutations of the above routines # + printf(($"real sum sq GEN: "g(0)l$, real sum sq of gen(GEN data))); + printf(($"real sum sq real gen: "g(0)l$, real sum sq of gen(gen real of vector(data,)))); + printf(($"real sum map real gen: "g(0)l$, real sum map of gen(((REAL x)REAL: x*x),gen real of vector(data,)))); + printf(($"SUMSQ real gen: "g(0)l$, SUMSQ gen real of vector(data,))); + printf(($"SUMSQ GEN: "g(0)l$, SUMSQ GEN data)); + printf(($"sq SUMMAP GEN: "g(0)l$, ((REAL x)REAL: x*x)SUMMAP GEN data)) +) diff --git a/Task/Sum-of-squares/AppleScript/sum-of-squares-1.applescript b/Task/Sum-of-squares/AppleScript/sum-of-squares-1.applescript new file mode 100644 index 0000000000..c87baaed40 --- /dev/null +++ b/Task/Sum-of-squares/AppleScript/sum-of-squares-1.applescript @@ -0,0 +1,85 @@ +-- TWO APPROACHES – SUM OVER MAP, AND DIRECT FOLD ---------------------------- + +-- sumOfSquares :: Num a => [a] -> a +on sumOfSquares(xs) + script squared + on |λ|(x) + x ^ 2 + end |λ| + end script + + sum(map(squared, xs)) + +end sumOfSquares + +-- sumOfSquares2 :: Num a => [a] -> a +on sumOfSquares2(xs) + script plusSquare + on |λ|(a, x) + a + x ^ 2 + end |λ| + end script + + foldl(plusSquare, 0, xs) + +end sumOfSquares2 + + +-- TEST ---------------------------------------------------------------------- +on run + set xs to [3, 1, 4, 1, 5, 9] + + {sumOfSquares(xs), sumOfSquares2(xs)} + + -- {133.0, 133.0} +end run + + +-- GENERIC FUNCTIONS --------------------------------------------------------- + +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- sum :: Num a => [a] -> a +on sum(xs) + script add + on |λ|(a, b) + a + b + end |λ| + end script + + foldl(add, 0, xs) +end sum diff --git a/Task/Sum-of-squares/AppleScript/sum-of-squares-2.applescript b/Task/Sum-of-squares/AppleScript/sum-of-squares-2.applescript new file mode 100644 index 0000000000..72f740ce03 --- /dev/null +++ b/Task/Sum-of-squares/AppleScript/sum-of-squares-2.applescript @@ -0,0 +1 @@ +{133.0, 133.0} diff --git a/Task/Sum-of-squares/BASIC/sum-of-squares.basic b/Task/Sum-of-squares/BASIC/sum-of-squares-1.basic similarity index 100% rename from Task/Sum-of-squares/BASIC/sum-of-squares.basic rename to Task/Sum-of-squares/BASIC/sum-of-squares-1.basic diff --git a/Task/Sum-of-squares/BASIC/sum-of-squares-2.basic b/Task/Sum-of-squares/BASIC/sum-of-squares-2.basic new file mode 100644 index 0000000000..f560e13634 --- /dev/null +++ b/Task/Sum-of-squares/BASIC/sum-of-squares-2.basic @@ -0,0 +1,22 @@ +' Sum of squares +FUNCTION ss(int arr[], NUMBER elem) + sum = 0 + FOR i = 0 TO elem - 1 + sum = sum + POW(arr[i], 2) + NEXT + RETURN sum +END FUNCTION + +' 1 to 10 in the test vector, or 1 to -s n +option = CMDLINE("s:") +IF option = ASC("s") THEN + elem = VAL(ARGUMENT$) +ELSE + elem = 10 +END IF + +DECLARE vector TYPE int ARRAY elem +FOR i = 0 TO elem - 1 + vector[i] = i + 1 +NEXT +PRINT ss(vector, elem) diff --git a/Task/Sum-of-squares/Bc/sum-of-squares.bc b/Task/Sum-of-squares/Bc/sum-of-squares.bc new file mode 100644 index 0000000000..afd4bc1730 --- /dev/null +++ b/Task/Sum-of-squares/Bc/sum-of-squares.bc @@ -0,0 +1,9 @@ +define s(a[], n) { + auto i, s + + for (i = 0; i < n; i++) { + s += a[i] * a[i] + } + + return(s) +} diff --git a/Task/Sum-of-squares/Elena/sum-of-squares.elena b/Task/Sum-of-squares/Elena/sum-of-squares.elena new file mode 100644 index 0000000000..d9433bc589 --- /dev/null +++ b/Task/Sum-of-squares/Elena/sum-of-squares.elena @@ -0,0 +1,12 @@ +import system'routines. +import extensions. + +SumOfSquares = + (:list)( list selectBy(:x)(x * x); summarize(Integer new) ). + +program = +[ + console printLine(SumOfSquares eval:(4, 8, 15, 16, 23, 42)). + console printLine(SumOfSquares eval:(1, 2, 3, 4, 5)). + console printLine(SumOfSquares eval(Array min)). +]. diff --git a/Task/Sum-of-squares/Haskell/sum-of-squares.hs b/Task/Sum-of-squares/Haskell/sum-of-squares.hs index 70fe8aedad..061bc22be6 100644 --- a/Task/Sum-of-squares/Haskell/sum-of-squares.hs +++ b/Task/Sum-of-squares/Haskell/sum-of-squares.hs @@ -1,4 +1,8 @@ -sumOfSquares = sum . map (^ 2) - -> sumOfSquares [3,1,4,1,5,9] -133 +main :: IO () +main = + mapM_ print $ + [ sum . fmap (^ 2) -- ver 1 + , sum . ((^ 2) <$>) -- ver 2 + , foldr ((+) . (^ 2)) 0 -- ver 3 + ] <*> + [[3, 1, 4, 1, 5, 9], [1 .. 6], [], [1]] diff --git a/Task/Sum-of-squares/JavaScript/sum-of-squares-5.js b/Task/Sum-of-squares/JavaScript/sum-of-squares-5.js new file mode 100644 index 0000000000..86f115d65e --- /dev/null +++ b/Task/Sum-of-squares/JavaScript/sum-of-squares-5.js @@ -0,0 +1,20 @@ +(() => { + 'use strict'; + + // squared :: Num a => a -> a + const squared = x => Math.pow(x, 2); + + // sum :: (Num a) => [a] -> a + const sum = xs => xs.reduce((a, x) => a + x, 0); + + // sumOfSquares :: Num a => [a] -> a + const sumOfSquares = xs => sum(xs.map(squared)); + + // sumOfSquares2 :: Num a => [a] -> a + const sumOfSquares2 = xs => + xs.reduce((a, x) => a + squared(x), 0); + + return [sumOfSquares, sumOfSquares2] + .map(f => f([3, 1, 4, 1, 5, 9])) + .join('\n'); +})(); diff --git a/Task/Sum-of-squares/jq/sum-of-squares-1.jq b/Task/Sum-of-squares/Jq/sum-of-squares-1.jq similarity index 100% rename from Task/Sum-of-squares/jq/sum-of-squares-1.jq rename to Task/Sum-of-squares/Jq/sum-of-squares-1.jq diff --git a/Task/Sum-of-squares/jq/sum-of-squares-2.jq b/Task/Sum-of-squares/Jq/sum-of-squares-2.jq similarity index 100% rename from Task/Sum-of-squares/jq/sum-of-squares-2.jq rename to Task/Sum-of-squares/Jq/sum-of-squares-2.jq diff --git a/Task/Sum-of-squares/jq/sum-of-squares-3.jq b/Task/Sum-of-squares/Jq/sum-of-squares-3.jq similarity index 100% rename from Task/Sum-of-squares/jq/sum-of-squares-3.jq rename to Task/Sum-of-squares/Jq/sum-of-squares-3.jq diff --git a/Task/Sum-of-squares/jq/sum-of-squares-4.jq b/Task/Sum-of-squares/Jq/sum-of-squares-4.jq similarity index 100% rename from Task/Sum-of-squares/jq/sum-of-squares-4.jq rename to Task/Sum-of-squares/Jq/sum-of-squares-4.jq diff --git a/Task/Sum-of-squares/jq/sum-of-squares-5.jq b/Task/Sum-of-squares/Jq/sum-of-squares-5.jq similarity index 100% rename from Task/Sum-of-squares/jq/sum-of-squares-5.jq rename to Task/Sum-of-squares/Jq/sum-of-squares-5.jq diff --git a/Task/Sum-of-squares/Kotlin/sum-of-squares.kotlin b/Task/Sum-of-squares/Kotlin/sum-of-squares.kotlin new file mode 100644 index 0000000000..2a88760c40 --- /dev/null +++ b/Task/Sum-of-squares/Kotlin/sum-of-squares.kotlin @@ -0,0 +1,8 @@ +// version 1.0.6 + +fun main(args: Array) { + val vector = doubleArrayOf(3.1, 1.0, 4.0, 1.0, 5.0, 9.0) + println(vector.map { it * it }.sum()) + val vector2 = doubleArrayOf() // empty vector + println(vector2.map { it * it }.sum()) +} diff --git a/Task/Sum-of-squares/Ruby/sum-of-squares-2.rb b/Task/Sum-of-squares/Ruby/sum-of-squares-2.rb index 267f9b331c..644c59fc70 100644 --- a/Task/Sum-of-squares/Ruby/sum-of-squares-2.rb +++ b/Task/Sum-of-squares/Ruby/sum-of-squares-2.rb @@ -1 +1 @@ -[3,1,4,1,5,9].map{|x| x*x}.reduce :+ +[3,1,4,1,5,9].map{|x| x*x}.sum(0) diff --git a/Task/Sum-of-squares/Zkl/sum-of-squares.zkl b/Task/Sum-of-squares/Zkl/sum-of-squares.zkl new file mode 100644 index 0000000000..54b13a1f72 --- /dev/null +++ b/Task/Sum-of-squares/Zkl/sum-of-squares.zkl @@ -0,0 +1,3 @@ +T().reduce(fcn(p,n){ p + n*n },0) //-->0 +T(3,1,4,1,5,9).reduce(fcn(p,n){ p + n*n },0.0) //-->133.0 +[1..5].reduce(fcn(p,n){ p + n*n },0) //-->55 diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Kotlin/sutherland-hodgman-polygon-clipping.kotlin b/Task/Sutherland-Hodgman-polygon-clipping/Kotlin/sutherland-hodgman-polygon-clipping.kotlin new file mode 100644 index 0000000000..2292416616 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Kotlin/sutherland-hodgman-polygon-clipping.kotlin @@ -0,0 +1,105 @@ +// version 1.1.2 + +import java.awt.* +import java.awt.geom.Line2D +import javax.swing.* + +class SutherlandHodgman : JPanel() { + private val subject = listOf( + doubleArrayOf( 50.0, 150.0), doubleArrayOf(200.0, 50.0), doubleArrayOf(350.0, 150.0), + doubleArrayOf(350.0, 300.0), doubleArrayOf(250.0, 300.0), doubleArrayOf(200.0, 250.0), + doubleArrayOf(150.0, 350.0), doubleArrayOf(100.0, 250.0), doubleArrayOf(100.0, 200.0) + ) + + private val clipper = listOf( + doubleArrayOf(100.0, 100.0), doubleArrayOf(300.0, 100.0), + doubleArrayOf(300.0, 300.0), doubleArrayOf(100.0, 300.0) + ) + + private var result = subject.toMutableList() + + init { + preferredSize = Dimension(600, 500) + clipPolygon() + } + + private fun clipPolygon() { + val len = clipper.size + for (i in 0 until len) { + val len2 = result.size + val input = result + result = mutableListOf() + val a = clipper[(i + len - 1) % len] + val b = clipper[i] + + for (j in 0 until len2) { + val p = input[(j + len2 - 1) % len2] + val q = input[j] + + if (isInside(a, b, q)) { + if (!isInside(a, b, p)) result.add(intersection(a, b, p, q)) + result.add(q) + } + else if (isInside(a, b, p)) result.add(intersection(a, b, p, q)) + } + } + } + + private fun isInside(a: DoubleArray, b: DoubleArray, c: DoubleArray) = + (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]) + + private fun intersection(a: DoubleArray, b: DoubleArray, + p: DoubleArray, q: DoubleArray): DoubleArray { + val a1 = b[1] - a[1] + val b1 = a[0] - b[0] + val c1 = a1 * a[0] + b1 * a[1] + + val a2 = q[1] - p[1] + val b2 = p[0] - q[0] + val c2 = a2 * p[0] + b2 * p[1] + + val d = a1 * b2 - a2 * b1 + val x = (b2 * c1 - b1 * c2) / d + val y = (a1 * c2 - a2 * c1) / d + + return doubleArrayOf(x, y) + } + + override fun paintComponent(g: Graphics) { + super.paintComponent(g) + val g2 = g as Graphics2D + g2.translate(80, 60) + g2.stroke = BasicStroke(3.0f) + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON) + drawPolygon(g2, subject, Color.blue) + drawPolygon(g2, clipper, Color.red) + drawPolygon(g2, result, Color.green) + } + + private fun drawPolygon(g2: Graphics2D, points: List, color: Color) { + g2.color = color + val len = points.size + val line = Line2D.Double() + for (i in 0 until len) { + val p1 = points[i] + val p2 = points[(i + 1) % len] + line.setLine(p1[0], p1[1], p2[0], p2[1]) + g2.draw(line) + } + } +} + +fun main(args: Array) { + SwingUtilities.invokeLater { + val f = JFrame() + with(f) { + defaultCloseOperation = JFrame.EXIT_ON_CLOSE + add(SutherlandHodgman(), BorderLayout.CENTER) + title = "Sutherland-Hodgman" + pack() + setLocationRelativeTo(null) + isVisible = true + } + } +} diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Phix/sutherland-hodgman-polygon-clipping.phix b/Task/Sutherland-Hodgman-polygon-clipping/Phix/sutherland-hodgman-polygon-clipping.phix new file mode 100644 index 0000000000..d8547af903 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Phix/sutherland-hodgman-polygon-clipping.phix @@ -0,0 +1,109 @@ +-- +-- demo\rosetta\Sutherland_Hodgman_polygon_clipping.exw +-- +enum X,Y + +function inside(sequence cp1, sequence cp2, sequence p) + return (cp2[X]-cp1[X])*(p[Y]-cp1[Y])>(cp2[Y]-cp1[Y])*(p[X]-cp1[X]) +end function + +function intersection(sequence cp1, sequence cp2, sequence s, sequence e) +atom {dcx,dcy} = {cp1[X]-cp2[X],cp1[Y]-cp2[Y]}, + {dpx,dpy} = {s[X]-e[X],s[Y]-e[Y]}, + n1 = cp1[X]*cp2[Y]-cp1[Y]*cp2[X], + n2 = s[X]*e[Y]-s[Y]*e[X], + n3 = 1/(dcx*dpy-dcy*dpx) + return {(n1*dpx-n2*dcx)*n3,(n1*dpy-n2*dcy)*n3} +end function + +function sutherland_hodgman(sequence subjectPolygon, sequence clipPolygon) +sequence cp1, cp2, s, e, inputList, outputList = subjectPolygon + cp1 = clipPolygon[$] + for i=1 to length(clipPolygon) do + cp2 = clipPolygon[i] + inputList = outputList + outputList = {} + s = inputList[$] + for j=1 to length(inputList) do + e = inputList[j] + if inside(cp1,cp2,e) then + if not inside(cp1,cp2,s) then + outputList = append(outputList,intersection(cp1,cp2,s,e)) + end if + outputList = append(outputList,e) + elsif inside(cp1,cp2,s) then + outputList = append(outputList,intersection(cp1,cp2,s,e)) + end if + s = e + end for + cp1 = cp2 + end for + return outputList +end function + +constant subjectPolygon = {{50, 150}, {200, 50}, {350, 150}, {350, 300}, + {250, 300}, {200, 250}, {150, 350}, {100, 250}, + {100, 200}}, + clipPolygon = {{100, 100}, {300, 100}, {300, 300}, {100, 300}} + +sequence clippedPolygon = sutherland_hodgman(subjectPolygon,clipPolygon) + +include pGUI.e + +Ihandle dlg, canvas +cdCanvas cddbuffer, cdcanvas + +procedure draw_poly(sequence poly) + cdCanvasBegin(cddbuffer,CD_FILL) + for i=1 to length(poly) do + atom {x,y} = poly[i] + cdCanvasVertex(cddbuffer,x,y) + end for + cdCanvasEnd(cddbuffer) +end procedure + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) + cdCanvasActivate(cddbuffer) + cdCanvasClear(cddbuffer) + cdCanvasSetForeground(cddbuffer, CD_CYAN) + draw_poly(subjectPolygon) + cdCanvasSetForeground(cddbuffer, CD_MAGENTA) + draw_poly(clipPolygon) + cdCanvasSetForeground(cddbuffer, CD_ORANGE) + draw_poly(clippedPolygon) + cdCanvasFlush(cddbuffer) + return IUP_DEFAULT +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + cdCanvasSetBackground(cddbuffer, CD_WHITE) + cdCanvasSetForeground(cddbuffer, CD_GRAY) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "400x400") + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", "Sutherland-Hodgman polygon clipping") + IupSetAttribute(dlg, "RESIZE", "NO") + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + + IupShow(dlg) + IupMainLoop() + IupClose() +end procedure + +main() diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Rust/sutherland-hodgman-polygon-clipping.rust b/Task/Sutherland-Hodgman-polygon-clipping/Rust/sutherland-hodgman-polygon-clipping.rust new file mode 100644 index 0000000000..404a1228da --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Rust/sutherland-hodgman-polygon-clipping.rust @@ -0,0 +1,58 @@ +#[derive(Debug,Clone)] +struct Point { + x: f64, + y: f64 +} + +#[derive(Debug,Clone)] +struct Polygon(Vec); + +fn is_inside(p: &Point, cp1: &Point, cp2: &Point) -> bool { + (cp2.x - cp1.x) * (p.y - cp1.y) > (cp2.y - cp1.y) * (p.x - cp1.x) +} + +fn compute_intersection(cp1: &Point, cp2: &Point, s: &Point, e: &Point) -> Point { + let dc = Point {x: cp1.x - cp2.x, y: cp1.y - cp2.y}; + let dp = Point {x: s.x - e.x, y: s.y - e.y}; + let n1 = cp1.x * cp2.y - cp1.y * cp2.x; + let n2 = s.x * e.y - s.y * e.x; + let n3 = 1.0 / (dc.x * dp.y - dc.y * dp.x); + Point { + x: (n1 * dp.x - n2 * dc.x) * n3, + y: (n1 * dp.y - n2 * dc.y) * n3 + } +} + +fn sutherland_hodgman_clip(subject_polygon: &Polygon, clip_polygon: &Polygon) -> Polygon { + let mut result_ring = subject_polygon.0.clone(); + let mut cp1 = clip_polygon.0.last().unwrap(); + for cp2 in clip_polygon.0.iter() { + let input = result_ring; + let mut s = input.last().unwrap(); + result_ring = vec![]; + for e in input.iter() { + if is_inside(&e, &cp1, &cp2) { + if !is_inside(&s, &cp1, &cp2){ + result_ring.push(compute_intersection(&cp1, &cp2, &s, &e)); + } + result_ring.push(e.clone()); + } else if is_inside(&s, &cp1, &cp2){ + result_ring.push(compute_intersection(&cp1, &cp2, &s, &e)); + } + s = e; + } + cp1 = cp2; + } + Polygon(result_ring) +} + +fn main(){ + let _p = |x: f64, y: f64| Point {x: x, y: y}; + let subject_polygon = Polygon( + vec![_p(50.0, 150.0), _p(200.0, 50.0), _p(350.0, 150.0), _p(350.0, 300.0), + _p(250.0, 300.0), _p(200.0, 250.0), _p(150.0, 350.0), _p(100.0, 250.0), _p(100.0, 200.0)]); + let clip_polygon = Polygon( + vec![_p(100.0, 100.0), _p(300.0, 100.0), _p(300.0, 300.0), _p(100.0, 300.0)]); + let result = sutherland_hodgman_clip(&subject_polygon, &clip_polygon); + println!("{:?}", result); +} diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Zkl/sutherland-hodgman-polygon-clipping-1.zkl b/Task/Sutherland-Hodgman-polygon-clipping/Zkl/sutherland-hodgman-polygon-clipping-1.zkl new file mode 100644 index 0000000000..b261fb5e6f --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Zkl/sutherland-hodgman-polygon-clipping-1.zkl @@ -0,0 +1,48 @@ +class P{ // point + fcn init(_x,_y){ var [const] x=_x.toFloat(), y=_y.toFloat() } + fcn __opSub(p) { self(x - p.x, y - p.y) } + fcn cross(p) { x*p.y - y*p.x } + fcn toString { "(%7.2f,%7.2f)".fmt(x,y) } + var [const,proxy] ps=fcn{ T(x.toInt(),y.toInt()) }; // property +} +fcn shClipping(clip,polygon){ + inputList,outputList,clipEdge:=List(), polygon.copy(), List(Void,clip[-1]); + foreach p in (clip){ + clipEdge.del(0).append(p); + inputList.clear().extend(outputList); + outputList.clear(); + S:=inputList[-1]; + foreach E in (inputList){ + if(leftOf(clipEdge,E)){ + if(not leftOf(clipEdge,S)) + outputList.append(intersection(S,E,clipEdge)); + outputList.append(E); + } + else if(leftOf(clipEdge,S)) + outputList.append(intersection(S,E,clipEdge)); + S=E; + } + } + outputList +} +fcn leftOf(line,p){ //-->True (p is left of line), direction of line matters + p1,p2:=line; // line is (p1,p2) + (p2-p1).cross(p-p2)>0; +} +fcn intersection(p1,p2, line){ //-->Point of intersection or False + p3,p4:=line; + dx,dy,d:=p2-p1, p3-p4, p1-p3; + // x0 + a dx = y0 + b dy -> + // x0 X dx = y0 X dx + b dy X dx -> + // b = (x0 - y0) X dx / (dy X dx) + dyx:=dy.cross(dx); + if(not dyx) return(False); // parallel lines, could just throw on next line + dyx=d.cross(dx)/dyx; + P(p3.x + dyx*dy.x, p3.y + dyx*dy.y); +} +fcn drawPolygon(ppm,listOfPoints,rgb){ + foreach n in (listOfPoints.len()-1){ + ppm.line(listOfPoints[n].ps.xplode(),listOfPoints[n+1].ps.xplode(),rgb); + } + ppm.line(listOfPoints[0].ps.xplode(),listOfPoints[-1].ps.xplode(),rgb); +} diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Zkl/sutherland-hodgman-polygon-clipping-2.zkl b/Task/Sutherland-Hodgman-polygon-clipping/Zkl/sutherland-hodgman-polygon-clipping-2.zkl new file mode 100644 index 0000000000..6d2f18aec9 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Zkl/sutherland-hodgman-polygon-clipping-2.zkl @@ -0,0 +1,18 @@ +ppm:=PPM(400,400); +clip:=T( P(100,100), P(300,100), P(300,300), P(100,300) ); +polygon:=T( P( 50,150),P(200, 50),P(350,150), + P(350,300),P(250,300),P(200,250), + P(150,350),P(100,250),P(100,200) ); +drawPolygon(ppm,polygon,0x0000ff); // blue: polygon +ppm.flood(200,200,0x000030); +drawPolygon(ppm,clip,0xff0000); // red: clip region + +clipped:=shClipping(clip,polygon); +drawPolygon(ppm,clipped,0x00ff00); // green: clipped polygon +ppm.flood(200,200,0x003000); // which is the clipped region anyway +clipped.apply('wrap(p){ ppm.cross(p.ps.xplode(),0x00ff00) }); // mark vertices + +ppm.writeJPGFile("sutherland_hodgman.zkl.jpg"); + +println("Clipped polygon has ",clipped.len()," points:"); +clipped.pump(Console.println); diff --git a/Task/Symmetric-difference/Aime/symmetric-difference.aime b/Task/Symmetric-difference/Aime/symmetric-difference.aime index ad849f74af..0b116944ac 100644 --- a/Task/Symmetric-difference/Aime/symmetric-difference.aime +++ b/Task/Symmetric-difference/Aime/symmetric-difference.aime @@ -13,14 +13,14 @@ show_sdiff(record u, record x) } else { r_p_integer(r, s, 0); } - } while (r_greater(x, s, s)); + } while (rsk_greater(x, s, s)); } if (r_first(r, s)) { do { o_text(s); o_byte('\n'); - } while (r_greater(r, s, s)); + } while (rsk_greater(r, s, s)); } } diff --git a/Task/Symmetric-difference/AppleScript/symmetric-difference-1.applescript b/Task/Symmetric-difference/AppleScript/symmetric-difference-1.applescript index ed381f5809..1e1c3be9c9 100644 --- a/Task/Symmetric-difference/AppleScript/symmetric-difference-1.applescript +++ b/Task/Symmetric-difference/AppleScript/symmetric-difference-1.applescript @@ -1,44 +1,69 @@ --- UNION AND DIFFERENCE +-- SYMMETRIC DIFFERENCE ------------------------------------------- --- union :: [a] -> [a] -> [a] -on union(xs, ys) - nub(xs & ys) -end union - --- difference :: [a] -> [a] -> [a] -on difference(xs, ys) - script except - on lambda(a, y) - if a contains y then - |delete|(y, a) - else - a - end if - end lambda - end script - - foldl(except, xs, ys) -end difference - - --- TEST +-- symmetricDifference :: [a] -> [a] -> [a] +on symmetricDifference(xs, ys) + union(difference(xs, ys), difference(ys, xs)) +end symmetricDifference +-- TEST ----------------------------------------------------------- on run - set a to ["John", "Serena", "Bob", "Mary", "Serena"] set b to ["Jim", "Mary", "John", "Jim", "Bob"] - - -- 'Symmetric difference' - - union(difference(a, b), difference(b, a)) + symmetricDifference(a, b) --> {"Serena", "Jim"} - end run --- GENERIC LIBRARY FUNCTIONS +-- GENERIC FUNCTIONS ---------------------------------------------- + +-- delete :: Eq a => a -> [a] -> [a] +on |delete|(x, xs) + set mbIndex to elemIndex(x, xs) + set lng to length of xs + + if mbIndex is not missing value then + if lng > 1 then + if mbIndex = 1 then + items 2 thru -1 of xs + else if mbIndex = lng then + items 1 thru -2 of xs + else + tell xs to items 1 thru (mbIndex - 1) & ¬ + items (mbIndex + 1) thru -1 + end if + else + {} + end if + else + xs + end if +end |delete| + +-- difference :: [a] -> [a] -> [a] +on difference(xs, ys) + script + on |λ|(a, y) + if a contains y then + my |delete|(y, a) + else + a + end if + end |λ| + end script + + foldl(result, xs, ys) +end difference + +-- elemIndex :: a -> [a] -> Maybe Int +on elemIndex(x, xs) + set lng to length of xs + repeat with i from 1 to lng + if x = (item i of xs) then return i + end repeat + return missing value +end elemIndex -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) @@ -46,13 +71,24 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl --- unique set of members of xs +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + -- nub :: [a] -> [a] on nub(xs) if (length of xs) > 1 then @@ -63,49 +99,14 @@ on nub(xs) end if end nub --- uncons :: [a] -> Maybe (a, [a]) -on uncons(xs) - if length of xs > 0 then - {item 1 of xs, rest of xs} - else - missing value - end if -end uncons - --- deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a] -on deleteBy(fnEq, x, xs) - if length of xs > 0 then - set {h, t} to uncons(xs) - if lambda(x, h) of mReturn(fnEq) then - t - else - {h} & deleteBy(fnEq, x, t) - end if - else - {} - end if -end deleteBy - --- delete :: a -> [a] -> [a] -on |delete|(x, xs) - script Eq - on lambda(a, b) - a = b - end lambda +-- union :: [a] -> [a] -> [a] +on union(xs, ys) + script flipDelete + on |λ|(xs, x) + my |delete|(x, xs) + end |λ| end script - deleteBy(Eq, x, xs) -end |delete| - - --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn + set sx to nub(xs) + sx & foldl(flipDelete, nub(ys), sx) +end union diff --git a/Task/Symmetric-difference/JavaScript/symmetric-difference-3.js b/Task/Symmetric-difference/JavaScript/symmetric-difference-3.js index b2c3ce7014..01284e294b 100644 --- a/Task/Symmetric-difference/JavaScript/symmetric-difference-3.js +++ b/Task/Symmetric-difference/JavaScript/symmetric-difference-3.js @@ -1,66 +1,64 @@ -((a, b) => { +(() => { 'use strict'; + const symmetricDifference = (xs, ys) => + union(difference(xs, ys), difference(ys, xs)); - let // UNION AND DIFFERENCE + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // First instance of x (if any) removed from xs + // delete_ :: Eq a => a -> [a] -> [a] + const delete_ = (x, xs) => { + const i = xs.indexOf(x); + return i !== -1 ? (xs.slice(0, i) + .concat(xs.slice(i, -1))) : xs; + }; + + // (\\) :: (Eq a) => [a] -> [a] -> [a] + const difference = (xs, ys) => + ys.reduce((a, x) => filter(z => z !== x, a), xs); + + // filter :: (a -> Bool) -> [a] -> [a] + const filter = (f, xs) => xs.filter(f); + + // flip :: (a -> b -> c) -> b -> a -> c + const flip = f => (a, b) => f.apply(null, [b, a]); + + // foldl :: (b -> a -> b) -> b -> [a] -> b + const foldl = (f, a, xs) => xs.reduce(f, a); + + // nub :: [a] -> [a] + const nub = xs => { + const mht = unconsMay(xs); + return mht.nothing ? xs : ( + ([h, t]) => [h].concat(nub(t.filter(s => s !== h))) + )(mht.just); + }; + + // show :: a -> String + const show = x => JSON.stringify(x, null, 2); + + // unconsMay :: [a] -> Maybe (a, [a]) + const unconsMay = xs => xs.length > 0 ? { + just: [xs[0], xs.slice(1)], + nothing: false + } : { + nothing: true + }; // union :: [a] -> [a] -> [a] - union = (xs, ys) => unionBy((a, b) => a === b, xs, ys), + const union = (xs, ys) => { + const sx = nub(xs); + return sx.concat(foldl(flip(delete_), nub(ys), sx)); + }; - // difference :: [a] -> [a] -> [a] - difference = (xs, ys) => - ys.reduce((a, y) => - a.indexOf(y) !== -1 ? ( - delete_(y, a) - ) : a.concat(y), xs), + // TEST ------------------------------------------------------------------- + const + a = ["John", "Serena", "Bob", "Mary", "Serena"], + b = ["Jim", "Mary", "John", "Jim", "Bob"]; - - - // GENERAL PRIMITIVES - - // unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] - unionBy = (f, xs, ys) => { - let sx = nubBy(f, xs), - sy = nubBy(f, ys); - - return sx.concat( - sx - .reduce( - (a, x) => deleteBy(f, x, a), - sy - ) - ) - }, - - // deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a] - deleteBy = (f, x, xs) => - xs.reduce((a, y) => f(x, y) ? a : a.concat(y), []), - - // delete_ :: a -> [a] -> [a] - delete_ = (x, xs) => - deleteBy((a, b) => a === b, x, xs), - - // nubBy :: (a -> a -> Bool) -> [a] -> [a] - nubBy = (f, xs) => { - let x = (xs.length ? xs[0] : undefined); - - return x !== undefined ? [x].concat( - nubBy(f, xs.slice(1) - .filter(y => !f(x, y)) - ) - ) : []; - }; - - - - // 'SYMMETRIC DIFFERENCE' - - return union( - difference(a, b), - difference(b, a) + return show( + symmetricDifference(a, b) ); - -})( - ["John", "Serena", "Bob", "Mary", "Serena"], - ["Jim", "Mary", "John", "Jim", "Bob"] -); +})(); diff --git a/Task/Symmetric-difference/jq/symmetric-difference-1.jq b/Task/Symmetric-difference/Jq/symmetric-difference-1.jq similarity index 100% rename from Task/Symmetric-difference/jq/symmetric-difference-1.jq rename to Task/Symmetric-difference/Jq/symmetric-difference-1.jq diff --git a/Task/Symmetric-difference/jq/symmetric-difference-2.jq b/Task/Symmetric-difference/Jq/symmetric-difference-2.jq similarity index 100% rename from Task/Symmetric-difference/jq/symmetric-difference-2.jq rename to Task/Symmetric-difference/Jq/symmetric-difference-2.jq diff --git a/Task/Symmetric-difference/Kotlin/symmetric-difference.kotlin b/Task/Symmetric-difference/Kotlin/symmetric-difference.kotlin new file mode 100644 index 0000000000..21053cb30b --- /dev/null +++ b/Task/Symmetric-difference/Kotlin/symmetric-difference.kotlin @@ -0,0 +1,14 @@ +// version 1.1.2 + +fun main(args: Array) { + val a = setOf("John", "Bob", "Mary", "Serena") + val b = setOf("Jim", "Mary", "John", "Bob") + println("A = $a") + println("B = $b") + val c = a - b + println("A \\ B = $c") + val d = b - a + println("B \\ A = $d") + val e = c.union(d) + println("A Δ B = $e") +} diff --git a/Task/Symmetric-difference/OoRexx/symmetric-difference.rexx b/Task/Symmetric-difference/OoRexx/symmetric-difference.rexx new file mode 100644 index 0000000000..5b5c49d78e --- /dev/null +++ b/Task/Symmetric-difference/OoRexx/symmetric-difference.rexx @@ -0,0 +1,6 @@ +a = .set~of("John", "Bob", "Mary", "Serena") +b = .set~of("Jim", "Mary", "John", "Bob") +-- the xor operation is a symmetric difference +do item over a~xor(b) + say item +end diff --git a/Task/Symmetric-difference/Pascal/symmetric-difference.pascal b/Task/Symmetric-difference/Pascal/symmetric-difference.pascal new file mode 100644 index 0000000000..c9d845259a --- /dev/null +++ b/Task/Symmetric-difference/Pascal/symmetric-difference.pascal @@ -0,0 +1,28 @@ +PROGRAM Symmetric_difference; + +TYPE + TName = (Bob, Jim, John, Mary, Serena); + TList = SET OF TName; + +PROCEDURE Put(txt : String; ResSet : TList); +VAR + I : TName; + +BEGIN + Write(txt); + FOR I IN ResSet DO Write(I,' '); + WriteLn +END; + +VAR + ListA : TList = [John, Bob, Mary, Serena]; + ListB : TList = [Jim, Mary, John, Bob]; + +BEGIN + Put('ListA -> ', ListA); + Put('ListB -> ', ListB); + Put('ListA >< ListB -> ', ListA >< ListB); + Put('ListA - ListB -> ', ListA - ListB); + Put('ListB - ListA -> ', ListB - ListA); + ReadLn; +END. diff --git a/Task/Symmetric-difference/Phix/symmetric-difference.phix b/Task/Symmetric-difference/Phix/symmetric-difference.phix new file mode 100644 index 0000000000..b4c4412476 --- /dev/null +++ b/Task/Symmetric-difference/Phix/symmetric-difference.phix @@ -0,0 +1,30 @@ +function Union(sequence a, sequence b) + for i=1 to length(a) do + if not find(a[i],b) then + b = append(b,a[i]) + end if + end for + return b +end function + +function Difference(sequence a, sequence b) +sequence res = {} + for i=1 to length(a) do + if not find(a[i],b) + and not find(a[i],res) then + res = append(res,a[i]) + end if + end for + return res +end function + +function Symmetric_Difference(sequence a, sequence b) + return Union(Difference(a, b), Difference(b, a)) +end function + +sequence a = {"John", "Serena", "Bob", "Mary", "Serena"}, + b = {"Jim", "Mary", "John", "Jim", "Bob"} +?Symmetric_Difference(a,a) +?Symmetric_Difference(a,b) +?Symmetric_Difference(b,a) +?Symmetric_Difference(b,b) diff --git a/Task/Symmetric-difference/Ruby/symmetric-difference-3.rb b/Task/Symmetric-difference/Ruby/symmetric-difference-3.rb deleted file mode 100644 index c9ce2f0723..0000000000 --- a/Task/Symmetric-difference/Ruby/symmetric-difference-3.rb +++ /dev/null @@ -1 +0,0 @@ -sym_diff = a ^ b diff --git a/Task/Symmetric-difference/Scheme/symmetric-difference-1.ss b/Task/Symmetric-difference/Scheme/symmetric-difference-1.ss new file mode 100644 index 0000000000..a449909e4c --- /dev/null +++ b/Task/Symmetric-difference/Scheme/symmetric-difference-1.ss @@ -0,0 +1,30 @@ +(import (scheme base) + (scheme write)) + +;; -- given two sets represented as lists, return (A \ B) +(define (a-without-b a b) + (cond ((null? a) + '()) + ((member (car a) (cdr a)) ; drop head of a if it's a duplicate + (a-without-b (cdr a) b)) + ((member (car a) b) ; head of a is in b so drop it + (a-without-b (cdr a) b)) + (else ; head of a not in b, so keep it + (cons (car a) (a-without-b (cdr a) b))))) + +;; -- given two sets represented as lists, return symmetric difference +(define (symmetric-difference a b) + (append (a-without-b a b) + (a-without-b b a))) + +;; -- test case +(define A '(John Bob Mary Serena)) +(define B '(Jim Mary John Bob)) + +(display "A\\B: ") (display (a-without-b A B)) (newline) +(display "B\\A: ") (display (a-without-b B A)) (newline) +(display "Symmetric difference: ") (display (symmetric-difference A B)) (newline) +;; -- extra test as we are using lists +(display "Symmetric difference 2: ") +(display (symmetric-difference '(John Serena Bob Mary Serena) + '(Jim Mary John Jim Bob))) (newline) diff --git a/Task/Symmetric-difference/Scheme/symmetric-difference-2.ss b/Task/Symmetric-difference/Scheme/symmetric-difference-2.ss new file mode 100644 index 0000000000..29dfb840c4 --- /dev/null +++ b/Task/Symmetric-difference/Scheme/symmetric-difference-2.ss @@ -0,0 +1,25 @@ +(import (scheme base) + (scheme write) + (srfi 1)) + +(define (a-without-b a b) + (lset-difference equal? + (delete-duplicates a) + (delete-duplicates b))) + +(define (symmetric-difference a b) + (lset-xor equal? + (delete-duplicates a) + (delete-duplicates b))) + +;; -- test case +(define A '(John Bob Mary Serena)) +(define B '(Jim Mary John Bob)) + +(display "A\\B: ") (display (a-without-b A B)) (newline) +(display "B\\A: ") (display (a-without-b B A)) (newline) +(display "Symmetric difference: ") (display (symmetric-difference A B)) (newline) +;; -- extra test as we are using lists +(display "Symmetric difference 2: ") +(display (symmetric-difference '(John Serena Bob Mary Serena) + '(Jim Mary John Jim Bob))) (newline) diff --git a/Task/Symmetric-difference/Zkl/symmetric-difference-1.zkl b/Task/Symmetric-difference/Zkl/symmetric-difference-1.zkl new file mode 100644 index 0000000000..3a64158433 --- /dev/null +++ b/Task/Symmetric-difference/Zkl/symmetric-difference-1.zkl @@ -0,0 +1,3 @@ +fcn setCommon(list1,list2){ list1.filter(list2.holds); } +fcn sdiff(list1,list2) + { list1.extend(list2).copy().removeEach(setCommon(list1,list2)) } diff --git a/Task/Symmetric-difference/Zkl/symmetric-difference-2.zkl b/Task/Symmetric-difference/Zkl/symmetric-difference-2.zkl new file mode 100644 index 0000000000..d5696df90d --- /dev/null +++ b/Task/Symmetric-difference/Zkl/symmetric-difference-2.zkl @@ -0,0 +1,3 @@ +a:=T("John","Bob","Mary","Serena"); +b:=T("Jim","Mary","John","Bob"); +sdiff(a,b).println(); diff --git a/Task/Symmetric-difference/Zkl/symmetric-difference-3.zkl b/Task/Symmetric-difference/Zkl/symmetric-difference-3.zkl new file mode 100644 index 0000000000..0b8e650c99 --- /dev/null +++ b/Task/Symmetric-difference/Zkl/symmetric-difference-3.zkl @@ -0,0 +1,3 @@ +a:=T("John", "Serena", "Bob", "Mary", "Serena"); +b:=T("Jim", "Mary", "John", "Jim", "Bob"); +sdiff(a,b) : Utils.Helpers.listUnique(_).println(); diff --git a/Task/Synchronous-concurrency/Nim/synchronous-concurrency.nim b/Task/Synchronous-concurrency/Nim/synchronous-concurrency.nim new file mode 100644 index 0000000000..7c386df1a1 --- /dev/null +++ b/Task/Synchronous-concurrency/Nim/synchronous-concurrency.nim @@ -0,0 +1,33 @@ +var msgs: Channel[string] +var count: Channel[int] + +const FILE = "input.txt" + +proc read() {.thread.} = + var file = open(FILE) + for line in file.lines: + msgs.send(line) + msgs.send(nil) + file.close() + echo count.recv() + count.close() + +proc print() {.thread.} = + var n = 0 + while true: + var msg = msgs.recv() + if msg == nil: + break + echo msg + n += 1 + msgs.close() + count.send(n) + +var reader_thread = Thread[void]() +var printer_thread = Thread[void]() + +msgs.open() +count.open() +createThread(reader_thread, read) +createThread(printer_thread, print) +joinThreads(reader_thread, printer_thread) diff --git a/Task/Synchronous-concurrency/OoRexx/synchronous-concurrency.rexx b/Task/Synchronous-concurrency/OoRexx/synchronous-concurrency.rexx new file mode 100644 index 0000000000..7e0ec7dd17 --- /dev/null +++ b/Task/Synchronous-concurrency/OoRexx/synchronous-concurrency.rexx @@ -0,0 +1,85 @@ +queue = .workqueue~new +input = .stream~new("jabberwocky.txt") +output = .output + +reader = .filereader~new(input, queue) +writer = .filewriter~new(output, queue) + +::class workQueue +::method init + expose queue stopped actionpending + queue = .queue~new + stopped = .false + actionPending = .false + +-- add an item to the work queue. This is a +-- guarded method, which means this is a synchronized access +::method addItem guarded + expose queue actionPending + use arg item + -- add the item to the queue + queue~queue(item) + -- indicate there's something new. This is a condition variable + -- that any will wake up any thread that's waiting on access. They'll + -- be able to get access once we exit + actionPending = .true + +-- another method for coordinating access with the other thread. This indicates +-- it is time to shut down +::method stop guarded + expose actionPending stopped + -- indicate this has been stopped and also flip the condition variable to + -- wake up any waiters + stopped = .true + actionPending = .true + +-- read the next item off of the queue. .nil indicates we've reached +-- the last item on the queue. This is also a guarded method, but we'll use +-- the GUARD ON instruction to wait for work if the queue is currently empty +::method nextItem + expose queue stopped actionPending + -- we might need to loop a little to get an item + do forever + -- if there's something on the queue, pull the front item and return + if \queue~isEmpty then return queue~pull + -- if the other thread says it is done sending is stuff, time to shut down + if stopped then return .nil + -- nothing on the queue, not stopped yet, so release the guard and wait until + -- there's something pending to work on. + guard on when actionPending + end + +-- one half of the synchronization effort. This will read lines and +-- add them to the work queue. The thread will terminate once we hit end-of-file +::class filereader +::method init + -- accept a generic stream...the data source need not be a file + use arg stream, queue + + reply -- now multithreaded + + signal on notready + loop forever + queue~addItem(stream~linein) + end + -- we come here on an EOF condition. Indicate we're done and terminate + -- the thread + notready: + queue~stop + +-- the other end of this. This class will read lines from a work queue +-- and write it to a stream +::class filewriter +::method init + -- accept a generic stream...the data source need not be a file + use arg stream, queue + + reply -- now multithreaded + + loop forever + item = queue~nextItem + -- .nil means last item received + if item == .nil then return + -- write to the stream + stream~lineout(item) + end diff --git a/Task/Synchronous-concurrency/Zkl/synchronous-concurrency.zkl b/Task/Synchronous-concurrency/Zkl/synchronous-concurrency.zkl new file mode 100644 index 0000000000..35ed3595a3 --- /dev/null +++ b/Task/Synchronous-concurrency/Zkl/synchronous-concurrency.zkl @@ -0,0 +1,15 @@ +fcn reader(fileName,out){ + n:=0; foreach line in (File(fileName)) { out.write(line); n+=1; } + out.close(); // signal done + Atomic.waitFor(out.Property("isOpen")); // wait for other thread to reopen Pipe + out.write(n); +} +fcn writer(in){ + Utils.zipWith(fcn(n,line){ "%3d: %s".fmt(n,line).print() },[1..],in); + in.open(); // signal other thread to send num lines read + println("Other thread read ",in.read()," lines"); +} + +p:=Thread.Pipe(); // NOT Unix pipes, thread safe channel between threads +reader.launch("input.txt",p); +writer.future(p).noop(); // noop forces eval, ie sleep until writer finished diff --git a/Task/System-time/00DESCRIPTION b/Task/System-time/00DESCRIPTION index 6adb4f1f1c..5be0c681a3 100644 --- a/Task/System-time/00DESCRIPTION +++ b/Task/System-time/00DESCRIPTION @@ -7,7 +7,10 @@ Output the system '''time'''   (any units will do as long as they are noted The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. -;See also: +;Related task: *   [[Date format]] + + +;See also: *   [[wp:System time#Retrieving system time|Retrieving system time (wiki)]]

    diff --git a/Task/System-time/BaCon/system-time.bacon b/Task/System-time/BaCon/system-time.bacon new file mode 100644 index 0000000000..801d5fe07a --- /dev/null +++ b/Task/System-time/BaCon/system-time.bacon @@ -0,0 +1,5 @@ +' BaCon time +n = NOW +PRINT n, " seconds since January 1st, 1970" +PRINT YEAR(n), MONTH(n), DAY(n) FORMAT "%04d/%02d/%02d " +PRINT HOUR(n), MINUTE(n), SECOND(n) FORMAT "%02d:%02d:%02d\n" diff --git a/Task/System-time/ColdFusion/system-time.cfm b/Task/System-time/ColdFusion/system-time.cfm new file mode 100644 index 0000000000..0396df49ce --- /dev/null +++ b/Task/System-time/ColdFusion/system-time.cfm @@ -0,0 +1,11 @@ + + // Date Time + currentTime = Now(); + writeOutput( currentTime ); + + // Epoch + // Credit for Epoch time should go to Ben Nadel + // bennadel.com is his blog + utcDate = dateConvert( "local2utc", currentTime ); + writeOutput( utcDate.getTime() ); + diff --git a/Task/System-time/Excel/system-time-1.excel b/Task/System-time/Excel/system-time-1.excel deleted file mode 100644 index 162ad6ab51..0000000000 --- a/Task/System-time/Excel/system-time-1.excel +++ /dev/null @@ -1 +0,0 @@ -=NOW() diff --git a/Task/System-time/Excel/system-time-2.excel b/Task/System-time/Excel/system-time-2.excel deleted file mode 100644 index 4f35265215..0000000000 --- a/Task/System-time/Excel/system-time-2.excel +++ /dev/null @@ -1 +0,0 @@ -9-8-2013 17:33 diff --git a/Task/System-time/Gambas/system-time.gambas b/Task/System-time/Gambas/system-time.gambas new file mode 100644 index 0000000000..58e97d2267 --- /dev/null +++ b/Task/System-time/Gambas/system-time.gambas @@ -0,0 +1,5 @@ +Public Sub Main() + +Print Format(Now, "dddd dd mmmm yyyy hh:nn:ss") + +End diff --git a/Task/System-time/Haskell/system-time-1.hs b/Task/System-time/Haskell/system-time-1.hs index ad6db90abc..cc7bc224f6 100644 --- a/Task/System-time/Haskell/system-time-1.hs +++ b/Task/System-time/Haskell/system-time-1.hs @@ -1,7 +1,11 @@ import System.Time -import System.Locale + (getClockTime, toCalendarTime, formatCalendarTime) -main = do ct <- getClockTime - print ct -- print default format, or - cal <- toCalendarTime ct - putStrLn $ formatCalendarTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" cal +import System.Locale (defaultTimeLocale) + +main :: IO () +main = do + ct <- getClockTime + print ct -- print default format, or + cal <- toCalendarTime ct + putStrLn $ formatCalendarTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" cal diff --git a/Task/System-time/Haskell/system-time-2.hs b/Task/System-time/Haskell/system-time-2.hs index 31da76c2e4..e6a9b0eac0 100644 --- a/Task/System-time/Haskell/system-time-2.hs +++ b/Task/System-time/Haskell/system-time-2.hs @@ -1,6 +1,7 @@ -import Data.Time -import System.Locale +import Data.Time (getZonedTime, formatTime, defaultTimeLocale) -main = do zt <- getZonedTime - print zt -- print default format, or - putStrLn $ formatTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" zt +main :: IO () +main = do + zt <- getZonedTime + print zt -- print default format, or + putStrLn $ formatTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" zt diff --git a/Task/System-time/Io/system-time-1.io b/Task/System-time/Io/system-time-1.io deleted file mode 100644 index 248ed1b723..0000000000 --- a/Task/System-time/Io/system-time-1.io +++ /dev/null @@ -1 +0,0 @@ -Date now println diff --git a/Task/System-time/Io/system-time-2.io b/Task/System-time/Io/system-time-2.io deleted file mode 100644 index 007fcca316..0000000000 --- a/Task/System-time/Io/system-time-2.io +++ /dev/null @@ -1 +0,0 @@ -2008-08-26 00:15:52 EDT diff --git a/Task/System-time/jq/system-time.jq b/Task/System-time/Jq/system-time.jq similarity index 100% rename from Task/System-time/jq/system-time.jq rename to Task/System-time/Jq/system-time.jq diff --git a/Task/System-time/Kotlin/system-time.kotlin b/Task/System-time/Kotlin/system-time.kotlin new file mode 100644 index 0000000000..cd561b7999 --- /dev/null +++ b/Task/System-time/Kotlin/system-time.kotlin @@ -0,0 +1,5 @@ +// version 1.0.6 + +fun main(args: Array) { + println("%tc".format(System.currentTimeMillis())) +} diff --git a/Task/System-time/Nimrod/system-time.nimrod b/Task/System-time/Nimrod/system-time.nimrod deleted file mode 100644 index d2f8fc09f3..0000000000 --- a/Task/System-time/Nimrod/system-time.nimrod +++ /dev/null @@ -1,5 +0,0 @@ -import times - -echo(getDateStr()) -echo(getClockStr()) -echo(getTime()) diff --git a/Task/System-time/SPL/system-time.spl b/Task/System-time/SPL/system-time.spl new file mode 100644 index 0000000000..f4de3fe444 --- /dev/null +++ b/Task/System-time/SPL/system-time.spl @@ -0,0 +1,5 @@ +hour,min,sec = #.now() +day,month,year = #.today() + +#.output(#.str(hour,"00:"),#.str(min,"00:"),#.str(sec,"00.000")) +#.output(day,".",#.str(month,"00"),".",year) diff --git a/Task/System-time/VBScript/system-time.vb b/Task/System-time/VBScript/system-time.vb new file mode 100644 index 0000000000..97c825da3d --- /dev/null +++ b/Task/System-time/VBScript/system-time.vb @@ -0,0 +1 @@ +WScript.Echo Now diff --git a/Task/System-time/Zkl/system-time.zkl b/Task/System-time/Zkl/system-time.zkl new file mode 100644 index 0000000000..39087f0b7c --- /dev/null +++ b/Task/System-time/Zkl/system-time.zkl @@ -0,0 +1 @@ +Time.Clock.time //-->seconds since the epoch (C/OS defined) diff --git a/Task/Table-creation-Postal-addresses/OoRexx/table-creation-postal-addresses.rexx b/Task/Table-creation-Postal-addresses/OoRexx/table-creation-postal-addresses.rexx new file mode 100644 index 0000000000..c90aa169a8 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/OoRexx/table-creation-postal-addresses.rexx @@ -0,0 +1,41 @@ +/* REXX *************************************************************** +* 17.05.2013 Walter Pachl translated from REXX version 2 +* nice try? improvements are welcome as I am rather unexperienced +* 18.05.2013 the array may contain a variety of objects! +**********************************************************************/ +alist=.array~new +alist[1]=.addr~new('Boston','MA','51 Franklin Street',,'FSF Inc.',, + '02110-1301') +alist[2]='not an address at all' +alist[3]=.addr~new('Washington','DC','The Oval Office',, + '1600 Pennsylvania Avenue NW','The White House',20500) +Do i=1 To alist~items + a=alist[i] + If a~isinstanceof(.addr) Then + a~show + End + +::class addr + ::attribute city + ::attribute state + ::attribute addr + ::attribute addr2 + ::attribute name + ::attribute zip + +::method init + Parse Arg self~city,, + self~state,, + self~addr,, + self~addr2,, + self~name,, + self~zip + +::method show + Say ' name -->' self~name + Say ' addr -->' self~addr + If self~addr2<>'' Then Say ' addr2 -->' self~addr2 + Say ' city -->' self~city + Say ' state -->' self~state + Say ' zip -->' self~zip + Say copies('-',40) diff --git a/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-3.rexx b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-3.rexx deleted file mode 100644 index e33e9020ab..0000000000 --- a/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-3.rexx +++ /dev/null @@ -1,35 +0,0 @@ -/* REXX *************************************************************** -* 17.05.2013 Walter Pachl -* should work with every REXX. -* I use 0xxx for the tail because this can't be modified -**********************************************************************/ -USA.=''; USA.0=0 -Call add_usa 'Boston','MA','51 Franklin Street',,'FSF Inc.',, - '02110-1301' -Call add_usa 'Washington','DC','The Oval Office',, - '1600 Pennsylvania Avenue NW','The White House',20500 -call list_usa -Exit - -add_usa: -z=usa.0+1 -Parse Arg usa.z.0city,, - usa.z.0state,, - usa.z.0addr,, - usa.z.0addr2,, - usa.z.0name,, - usa.z.0zip -usa.0=z -Return - -list_usa: -Do z=1 To usa.0 - Say ' name -->' usa.z.0name - Say ' addr -->' usa.z.0addr - If usa.z.0addr2<>'' Then Say ' addr2 -->' usa.z.0addr2 - Say ' city -->' usa.z.0city - Say ' state -->' usa.z.0state - Say ' zip -->' usa.z.0zip - Say copies('-',40) - End -Return diff --git a/Task/Table-creation-Postal-addresses/Zkl/table-creation-postal-addresses-1.zkl b/Task/Table-creation-Postal-addresses/Zkl/table-creation-postal-addresses-1.zkl new file mode 100644 index 0000000000..6abdd4c35f --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Zkl/table-creation-postal-addresses-1.zkl @@ -0,0 +1,2 @@ +const NM="address.db"; +dbExec(NM,"create table address (street, city, state, zip);"); diff --git a/Task/Table-creation-Postal-addresses/Zkl/table-creation-postal-addresses-2.zkl b/Task/Table-creation-Postal-addresses/Zkl/table-creation-postal-addresses-2.zkl new file mode 100644 index 0000000000..017013efff --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Zkl/table-creation-postal-addresses-2.zkl @@ -0,0 +1,16 @@ +fcn dbExec(db,qry){ dbErrorCheck(dbMakeQuery(db,qry),String(db," : ",qry)) } +fcn dbMakeQuery(db,qry){ + qry=dbEscapeQuery(qry) + ";"; + cmd:=String("echo \"", qry, "\" | sqlite ", db); + reg r; + p:=System.popen(cmd,"r"); + try{ r=p.readln(*) }catch(TheEnd){} // r==Void if sqlite doesn't print + p.close(); + r +} +fcn dbEscapeQuery(qry){ qry.replace(0'|"|, 0'|\"|) } +fcn dbErrorCheck(listOfStrings){ + if(listOfStrings and listOfStrings[-1].holds("SQL error")) + throw(Exception.IOError(listOfStrings.concat().strip())); + True +} diff --git a/Task/Take-notes-on-the-command-line/Common-Lisp/take-notes-on-the-command-line.lisp b/Task/Take-notes-on-the-command-line/Common-Lisp/take-notes-on-the-command-line.lisp new file mode 100644 index 0000000000..9a56bf22b5 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Common-Lisp/take-notes-on-the-command-line.lisp @@ -0,0 +1,22 @@ +(defparameter *notes* "NOTES.TXT") + +(defun format-date-time (stream) + (multiple-value-bind (second minute hour date month year) (get-decoded-time) + (format stream "~D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D" + year month date hour minute second))) + +(defun notes (args) + (if args + (with-open-file (s *notes* :direction :output + :if-exists :append + :if-does-not-exist :create) + (format-date-time s) + (format s "~&~A~{~A~^ ~}~%" #\Tab args)) + (with-open-file (s *notes* :if-does-not-exist nil) + (when s + (loop for line = (read-line s nil) + while line + do (write-line line)))))) + +(defun main () + (notes (uiop:command-line-arguments))) diff --git a/Task/Take-notes-on-the-command-line/Gambas/take-notes-on-the-command-line.gambas b/Task/Take-notes-on-the-command-line/Gambas/take-notes-on-the-command-line.gambas new file mode 100644 index 0000000000..a195c9d4f9 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Gambas/take-notes-on-the-command-line.gambas @@ -0,0 +1,23 @@ +'Note that the 1st item in 'Args' is the file name as on the command line './CLIOnly.gambas' + +Public Sub Main() +Dim sContents As String 'To store the file contents +Dim sArgs As String[] = Args.All 'To store all the Command line Arguments + +If Not Exist(User.home &/ "NOTES.TXT") Then 'If NOTES.TXT doesn't already exist in the current directory then.. + File.Save(User.home &/ "NOTES.TXT", "") 'a new NOTES.TXT file should be created. + Print "New file 'NOTES.TXT' created." 'A meassge +Endif + +sContents = File.Load(User.home &/ "NOTES.TXT") 'Get the contents of the file + +If Args.count < 2 Then 'If NOTES has arguments (other than the file name) + Print sContents 'Print the file contents +Else + sContents &= Format(Now, "dddd dd mmmm, yyyy, hh:nn:ss") & gb.NewLine & 'The current date and time are appended to the local NOTES.TXT followed by a newline and.. + gb.Tab & sArgs.Join(" ") & gb.NewLine 'Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline + Print sContents 'Displays the current contents of the local NOTES.TXT + File.Save(User.home &/ "NOTES.TXT", sContents) 'Write contents to NOTES.TXT +Endif + +End diff --git a/Task/Take-notes-on-the-command-line/Python/take-notes-on-the-command-line.py b/Task/Take-notes-on-the-command-line/Python/take-notes-on-the-command-line.py index dd2b7a4516..d370df2eec 100644 --- a/Task/Take-notes-on-the-command-line/Python/take-notes-on-the-command-line.py +++ b/Task/Take-notes-on-the-command-line/Python/take-notes-on-the-command-line.py @@ -1,15 +1,12 @@ import sys, datetime, shutil -#sys.argv[1:] = 'go for it'.split() if len(sys.argv) == 1: try: - f = open('notes.txt', 'r') - shutil.copyfileobj(f, sys.stdout) - f.close() + with open('notes.txt', 'r') as f: + shutil.copyfileobj(f, sys.stdout) except IOError: pass else: - f = open('notes.txt', 'a') - f.write(datetime.datetime.now().isoformat() + '\n') - f.write("\t%s\n" % ' '.join(sys.argv[1:])) - f.close() + with open('notes.txt', 'a') as f: + f.write(datetime.datetime.now().isoformat() + '\n') + f.write("\t%s\n" % ' '.join(sys.argv[1:])) diff --git a/Task/Take-notes-on-the-command-line/Racket/take-notes-on-the-command-line.rkt b/Task/Take-notes-on-the-command-line/Racket/take-notes-on-the-command-line.rkt index f882a78206..3a56d665bc 100644 --- a/Task/Take-notes-on-the-command-line/Racket/take-notes-on-the-command-line.rkt +++ b/Task/Take-notes-on-the-command-line/Racket/take-notes-on-the-command-line.rkt @@ -1,4 +1,4 @@ -#!/bin/env racket +#!/usr/bin/env racket #lang racket (define file "NOTES.TXT") (require racket/date) diff --git a/Task/Take-notes-on-the-command-line/Sidef/take-notes-on-the-command-line.sidef b/Task/Take-notes-on-the-command-line/Sidef/take-notes-on-the-command-line.sidef index 806f131f01..5abea905fc 100644 --- a/Task/Take-notes-on-the-command-line/Sidef/take-notes-on-the-command-line.sidef +++ b/Task/Take-notes-on-the-command-line/Sidef/take-notes-on-the-command-line.sidef @@ -1,9 +1,10 @@ -var file = %f'notes.txt'; +var file = %f'notes.txt' if (ARGV.len > 0) { - var fh = file.open_a; - fh.say(Time.local.ctime + "\n\t" + ARGV.join(" ")); - fh.close; + var fh = file.open_a + fh.say(Time.local.ctime + "\n\t" + ARGV.join(" ")) + fh.close } else { - file.open_r.each { .print }; + var fh = file.open_r + fh && fh.each { .say } } diff --git a/Task/Take-notes-on-the-command-line/Zkl/take-notes-on-the-command-line.zkl b/Task/Take-notes-on-the-command-line/Zkl/take-notes-on-the-command-line.zkl new file mode 100644 index 0000000000..ea578ca96c --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Zkl/take-notes-on-the-command-line.zkl @@ -0,0 +1,9 @@ +const notesName="NOTES.TXT"; +args:=vm.arglist; +if (not args) + { try{ File(notesName).read(*).text.print(); } catch{println("no file")} } +else{ + f:=File(notesName,"a+"); + f.writeln(Time.Date.ctime(),"\n\t",args.concat(" ")); + f.close(); +} diff --git a/Task/Temperature-conversion/ALGOL-M/temperature-conversion.algol-m b/Task/Temperature-conversion/ALGOL-M/temperature-conversion.algol-m new file mode 100644 index 0000000000..f72e7df80e --- /dev/null +++ b/Task/Temperature-conversion/ALGOL-M/temperature-conversion.algol-m @@ -0,0 +1,12 @@ +BEGIN + DECIMAL K, C, F, R; + WRITE( "Temperature in Kelvin:" ); + READ( K ); + C := K - 273.15; + F := K * 1.8 - 459.67; + R := K * 1.8; + WRITE( K, " Kelvin is equivalent to" ); + WRITE( C, " degrees Celsius" ); + WRITE( F, " degrees Fahrenheit" ); + WRITE( R, " degrees Rankine" ); +END diff --git a/Task/Temperature-conversion/BASIC/temperature-conversion.basic b/Task/Temperature-conversion/BASIC/temperature-conversion-1.basic similarity index 100% rename from Task/Temperature-conversion/BASIC/temperature-conversion.basic rename to Task/Temperature-conversion/BASIC/temperature-conversion-1.basic diff --git a/Task/Temperature-conversion/BASIC/temperature-conversion-2.basic b/Task/Temperature-conversion/BASIC/temperature-conversion-2.basic new file mode 100644 index 0000000000..df0959bff5 --- /dev/null +++ b/Task/Temperature-conversion/BASIC/temperature-conversion-2.basic @@ -0,0 +1,6 @@ +10 PRINT "ENTER A TEMPERATURE IN KELVINS" +20 INPUT K +30 PRINT K;" KELVINS =" +40 PRINT K-273.15;" DEGREES CELSIUS" +50 PRINT K*1.8-459.67;" DEGREES FAHRENHEIT" +60 PRINT K*1.8;" DEGREES RANKINE" diff --git a/Task/Temperature-conversion/Gambas/temperature-conversion.gambas b/Task/Temperature-conversion/Gambas/temperature-conversion.gambas new file mode 100644 index 0000000000..b19490a06c --- /dev/null +++ b/Task/Temperature-conversion/Gambas/temperature-conversion.gambas @@ -0,0 +1,11 @@ +Public Sub Form_Open() +Dim fKelvin As Float + +fKelvin = InputBox("Enter a Kelvin value", "Kelvin converter") + +Print "Kelvin =\t" & Format(Str(fKelvin), "#.00") +Print "Celsius =\t" & Format(Str(fKelvin - 273.15), "#.00") +Print "Fahrenheit =\t" & Format(Str(fKelvin * 1.8 - 459.67), "#.00") +Print "Rankine =\t" & Format(Str(fKelvin * 1.8), "#.00") + +End diff --git a/Task/Temperature-conversion/Groovy/temperature-conversion.groovy b/Task/Temperature-conversion/Groovy/temperature-conversion.groovy new file mode 100644 index 0000000000..c080740333 --- /dev/null +++ b/Task/Temperature-conversion/Groovy/temperature-conversion.groovy @@ -0,0 +1,12 @@ +class Convert{ +static void main(String[] args){ +def c=21.0; +println("K "+c) +println("C "+k_to_c(c)); +println("F "+k_to_f(k_to_c(c))); +println("R "+k_to_r(c)); +} +static def k_to_c(def k=21.0){return k-273.15;} +static def k_to_f(def k=21.0){return ((k*9)/5)+32;} +static def k_to_r(def k=21.0){return k*1.8;} +} diff --git a/Task/Temperature-conversion/jq/temperature-conversion-1.jq b/Task/Temperature-conversion/Jq/temperature-conversion-1.jq similarity index 100% rename from Task/Temperature-conversion/jq/temperature-conversion-1.jq rename to Task/Temperature-conversion/Jq/temperature-conversion-1.jq diff --git a/Task/Temperature-conversion/jq/temperature-conversion-2.jq b/Task/Temperature-conversion/Jq/temperature-conversion-2.jq similarity index 100% rename from Task/Temperature-conversion/jq/temperature-conversion-2.jq rename to Task/Temperature-conversion/Jq/temperature-conversion-2.jq diff --git a/Task/Temperature-conversion/Kotlin/temperature-conversion.kotlin b/Task/Temperature-conversion/Kotlin/temperature-conversion.kotlin new file mode 100644 index 0000000000..c3e9bbe231 --- /dev/null +++ b/Task/Temperature-conversion/Kotlin/temperature-conversion.kotlin @@ -0,0 +1,21 @@ +// version 1.1.2 + +class Kelvin(val degrees: Double) { + fun toCelsius() = degrees - 273.15 + + fun toFahreneit() = (degrees - 273.15) * 1.8 + 32.0 + + fun toRankine() = (degrees - 273.15) * 1.8 + 32.0 + 459.67 +} + +fun main(args: Array) { + print("Enter the temperature in degrees Kelvin : ") + val degrees = readLine()!!.toDouble() + val k = Kelvin(degrees) + val f = "% 1.2f" + println() + println("K ${f.format(k.degrees)}\n") + println("C ${f.format(k.toCelsius())}\n") + println("F ${f.format(k.toFahreneit())}\n") + println("R ${f.format(k.toRankine())}") +} diff --git a/Task/Temperature-conversion/Scheme/temperature-conversion.ss b/Task/Temperature-conversion/Scheme/temperature-conversion.ss new file mode 100644 index 0000000000..b205d703d7 --- /dev/null +++ b/Task/Temperature-conversion/Scheme/temperature-conversion.ss @@ -0,0 +1,19 @@ +(import (scheme base) + (scheme read) + (scheme write)) + +(define (kelvin->celsius k) + (- k 273.15)) + +(define (kelvin->fahrenheit k) + (- (* k 1.8) 459.67)) + +(define (kelvin->rankine k) + (* k 1.8)) + +;; Run the program +(let ((k (begin (display "Kelvin : ") (flush-output-port) (read)))) + (when (number? k) + (display "Celsius : ") (display (kelvin->celsius k)) (newline) + (display "Fahrenheit: ") (display (kelvin->fahrenheit k)) (newline) + (display "Rankine : ") (display (kelvin->rankine k)) (newline))) diff --git a/Task/Temperature-conversion/Swift/temperature-conversion.swift b/Task/Temperature-conversion/Swift/temperature-conversion.swift new file mode 100644 index 0000000000..6a95fa20cc --- /dev/null +++ b/Task/Temperature-conversion/Swift/temperature-conversion.swift @@ -0,0 +1,23 @@ +func KtoC(kelvin : Double)->Double{ + + return kelvin-273.15 +} + +func KtoF(kelvin : Double)->Double{ + + return ((kelvin-273.15)*1.8)+32 +} + +func KtoR(kelvin : Double)->Double{ + + return ((kelvin-273.15)*1.8)+491.67 +} + +var k// input +print("\(k) Kelvin") +var c=KtoC(kelvin : k) +print("\(c) Celsius") +var f=KtoF(kelvin : k) +print("\(f) Fahrenheit") +var r=KtoR(kelvin : k) +print("\(r) Rankine") diff --git a/Task/Temperature-conversion/Zkl/temperature-conversion.zkl b/Task/Temperature-conversion/Zkl/temperature-conversion.zkl new file mode 100644 index 0000000000..402c2c02a6 --- /dev/null +++ b/Task/Temperature-conversion/Zkl/temperature-conversion.zkl @@ -0,0 +1,5 @@ +K:=ask(0,"Kelvin: ").toFloat(); +println("K %.2f".fmt(K)); +println("F %.2f".fmt(K*1.8 - 459.67)); +println("C %.2f".fmt(K - 273.15)); +println("R %.2f".fmt(K*1.8)); diff --git a/Task/Terminal-control-Clear-the-screen/6502-Assembly/terminal-control-clear-the-screen-1.6502 b/Task/Terminal-control-Clear-the-screen/6502-Assembly/terminal-control-clear-the-screen-1.6502 new file mode 100644 index 0000000000..0cb41d374f --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/6502-Assembly/terminal-control-clear-the-screen-1.6502 @@ -0,0 +1,19 @@ +; C64 - Terminal control: Clear the screen + +; *** labels *** + +chrout = $ffd2 + +; *** main *** + + *=$02a8 ; sys 680 + + lda clr ; A = {CLR} + jsr chrout ; Output a character in A to the current + ; output device (default: screen). + rts + +; *** data *** + +clr .byte $93 ; the CLR control code + ; see https://en.wikipedia.org/wiki/PETSCII diff --git a/Task/Terminal-control-Clear-the-screen/6502-Assembly/terminal-control-clear-the-screen-2.6502 b/Task/Terminal-control-Clear-the-screen/6502-Assembly/terminal-control-clear-the-screen-2.6502 new file mode 100644 index 0000000000..3928b7b42d --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/6502-Assembly/terminal-control-clear-the-screen-2.6502 @@ -0,0 +1,31 @@ +; 6502asm.com - Clear the screen + + lda #$00 ; store the start address of the screen ($200) + sta $00 ; at $00 and $01 (high byte in $01) + lda #$02 + sta $01 + + ldy #$00 ; Y = 0 +fillscreen: + lda $fe ; A = random number from $fe + sta ($00),y ; put pixel (random color) to the screen + iny ; Y++ + bne fillscreen ; loop if Y!=0 + inc $01 ; increase address high byte + lda $01 + cmp #$06 ; A==6? (screen ends at $05ff) + bne fillscreen ; no -> loop + +waitforkeypress: + lda $ff ; $ff is 0 if no key has been pressed + beq waitforkeypress + + ldx #$00 + lda #$00 ; black +clearscreen: + sta $0200,x + sta $0300,x + sta $0400,x + sta $0500,x + inx + bne clearscreen diff --git a/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-1.bbc b/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-1.bbc deleted file mode 100644 index 1990de62cc..0000000000 --- a/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-1.bbc +++ /dev/null @@ -1 +0,0 @@ - CLS diff --git a/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-2.bbc b/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-2.bbc deleted file mode 100644 index 747b079d8b..0000000000 --- a/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-2.bbc +++ /dev/null @@ -1 +0,0 @@ - VDU 12 diff --git a/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-3.bbc b/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-3.bbc deleted file mode 100644 index a311bea00d..0000000000 --- a/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-3.bbc +++ /dev/null @@ -1 +0,0 @@ - PRINT CHR$(12); diff --git a/Task/Terminal-control-Clear-the-screen/Beeswax/terminal-control-clear-the-screen.beeswax b/Task/Terminal-control-Clear-the-screen/Beeswax/terminal-control-clear-the-screen.beeswax new file mode 100644 index 0000000000..fd63f74379 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Beeswax/terminal-control-clear-the-screen.beeswax @@ -0,0 +1 @@ +_3F..}`[2J` diff --git a/Task/Terminal-control-Clear-the-screen/GW-BASIC/terminal-control-clear-the-screen.gw-basic b/Task/Terminal-control-Clear-the-screen/GW-BASIC/terminal-control-clear-the-screen.gw-basic deleted file mode 100644 index d8ed2b0aef..0000000000 --- a/Task/Terminal-control-Clear-the-screen/GW-BASIC/terminal-control-clear-the-screen.gw-basic +++ /dev/null @@ -1 +0,0 @@ -10 CLS diff --git a/Task/Terminal-control-Clear-the-screen/jq/terminal-control-clear-the-screen-1.jq b/Task/Terminal-control-Clear-the-screen/Jq/terminal-control-clear-the-screen-1.jq similarity index 100% rename from Task/Terminal-control-Clear-the-screen/jq/terminal-control-clear-the-screen-1.jq rename to Task/Terminal-control-Clear-the-screen/Jq/terminal-control-clear-the-screen-1.jq diff --git a/Task/Terminal-control-Clear-the-screen/jq/terminal-control-clear-the-screen-2.jq b/Task/Terminal-control-Clear-the-screen/Jq/terminal-control-clear-the-screen-2.jq similarity index 100% rename from Task/Terminal-control-Clear-the-screen/jq/terminal-control-clear-the-screen-2.jq rename to Task/Terminal-control-Clear-the-screen/Jq/terminal-control-clear-the-screen-2.jq diff --git a/Task/Terminal-control-Clear-the-screen/Julia/terminal-control-clear-the-screen.julia b/Task/Terminal-control-Clear-the-screen/Julia/terminal-control-clear-the-screen.julia new file mode 100644 index 0000000000..2bedcc86e9 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Julia/terminal-control-clear-the-screen.julia @@ -0,0 +1 @@ +println("\33[2J") diff --git a/Task/Terminal-control-Clear-the-screen/Kotlin/terminal-control-clear-the-screen.kotlin b/Task/Terminal-control-Clear-the-screen/Kotlin/terminal-control-clear-the-screen.kotlin new file mode 100644 index 0000000000..8f0b865d1b --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Kotlin/terminal-control-clear-the-screen.kotlin @@ -0,0 +1,5 @@ +// version 1.1.2 + +fun main(args: Array) { + println("\u001Bc") // Esc + c +} diff --git a/Task/Terminal-control-Clear-the-screen/PureBasic/terminal-control-clear-the-screen.purebasic b/Task/Terminal-control-Clear-the-screen/PureBasic/terminal-control-clear-the-screen.purebasic deleted file mode 100644 index c7e42b6386..0000000000 --- a/Task/Terminal-control-Clear-the-screen/PureBasic/terminal-control-clear-the-screen.purebasic +++ /dev/null @@ -1 +0,0 @@ -ClearConsole() diff --git a/Task/Terminal-control-Clear-the-screen/SPL/terminal-control-clear-the-screen.spl b/Task/Terminal-control-Clear-the-screen/SPL/terminal-control-clear-the-screen.spl new file mode 100644 index 0000000000..acd3a61192 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/SPL/terminal-control-clear-the-screen.spl @@ -0,0 +1 @@ +#.clear() diff --git a/Task/Terminal-control-Clear-the-screen/Zkl/terminal-control-clear-the-screen.zkl b/Task/Terminal-control-Clear-the-screen/Zkl/terminal-control-clear-the-screen.zkl new file mode 100644 index 0000000000..d6671897c2 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Zkl/terminal-control-clear-the-screen.zkl @@ -0,0 +1,2 @@ +System.cmd(System.isWindows and "cls" or "clear"); +// or, for ANSI terminals: print("\e[2J") diff --git a/Task/Terminal-control-Coloured-text/Kotlin/terminal-control-coloured-text.kotlin b/Task/Terminal-control-Coloured-text/Kotlin/terminal-control-coloured-text.kotlin new file mode 100644 index 0000000000..4eb9348a4e --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Kotlin/terminal-control-coloured-text.kotlin @@ -0,0 +1,26 @@ +// version 1.1.2 + +const val ESC = "\u001B" +const val NORMAL = ESC + "[0" +const val BOLD = ESC + "[1" +const val BLINK = ESC + "[5" // not working on my machine +const val BLACK = ESC + "[0;40m" // black background +const val WHITE = ESC + "[0;37m" // normal white foreground + +fun main(args: Array) { + print("${ESC}c") // clear terminal first + print(BLACK) // set background color to black + val foreColors = listOf( + ";31m" to "red", + ";32m" to "green", + ";33m" to "yellow", + ";34m" to "blue", + ";35m" to "magenta", + ";36m" to "cyan", + ";37m" to "white" + ) + for (attr in listOf(NORMAL, BOLD, BLINK)) { + for (color in foreColors) println("$attr${color.first}${color.second}") + } + println(WHITE) // set foreground color to normal white +} diff --git a/Task/Terminal-control-Coloured-text/OoRexx/terminal-control-coloured-text.rexx b/Task/Terminal-control-Coloured-text/OoRexx/terminal-control-coloured-text.rexx new file mode 100644 index 0000000000..6dc566d762 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/OoRexx/terminal-control-coloured-text.rexx @@ -0,0 +1,129 @@ +#!/usr/bin/rexx +/*.----------------------------------------------------------------------.*/ +/*|bashcolours: Display a table showing all of the possible colours that |*/ +/*| can be generated using ANSI escapes in bash in an xterm |*/ +/*| terminal session. |*/ +/*| |*/ +/*|Usage: |*/ +/*| |*/ +/*|>>-bashcolours-.----------.-----------------------------------------><|*/ +/*| |-- -? ----| |*/ +/*| |-- -h ----| |*/ +/*| '- --help -' |*/ +/*| |*/ +/*|where |*/ +/*| -?, -h or --help |*/ +/*| display this documentation. |*/ +/*| |*/ +/*|This program is based on the shell script in the Bash Prompt HowTo at |*/ +/*|http://www.tldp.org/, by Giles Orr. |*/ +/*| |*/ +/*|This program writes the various colour codes to the terminal to |*/ +/*|demonstrate what's available. Each line showshe colour code of one |*/ +/*|forground colour, out of 17 (default + 16 escapes), followed by a test|*/ +/*|use of that colour on all nine background colours (default + 8 |*/ +/*|escapes). Additional highlighting escapes are also demonstrated. |*/ +/*| |*/ +/*|This program uses object-oriented features of Open Object Rexx. |*/ +/*|The lineout method is used instead of say for consistency with use of |*/ +/*|the charout method. |*/ +/*'----------------------------------------------------------------------'*/ + call usage arg(1) + trace normal + +/* See if escapes work on the kind of terminal in use. */ + if value('TERM',,'ENVIRONMENT') = 'LINUX' then + do + say 'The Linux console does not support ANSI escape sequences for', + 'changing text colours or highlighting.' + exit 4 + end + +/* Set up the escape sequences. */ + ! = '1B'x -- ASCII escape + bg = .array~of('[40m','[41m','[42m','[43m','[44m','[45m','[46m','[47m') + fg = .array~of('[0m', '[1m', '[0;30m','[1;30m','[0;31m','[1;31m',, + '[0;32m','[1;32m','[0;33m','[1;33m','[0;34m','[1;34m',, + '[0;35m','[1;35m','[0;36m','[1;36m','[0;37m','[1;37m') + hi = .array~of('[4m','[5m','[7m','[8m') + text = 'gYw' -- The test text + .OUTPUT~lineout(' ') + .OUTPUT~lineout('Foreground | Background Codes') + .OUTPUT~lineout(!'[4mCodes '!'[0m|'||, + !'[4m~[40m ~[41m ~[42m ~[43m ~[44m ~[45m ~[46m ~[47m'!'[0m') + + do f = 1 to fg~size -- write the foreground info. + prefix = '~'fg[f]~left(6)' '!||fg[f]~strip' 'text + .OUTPUT~charout(prefix) + + do b = 1 to bg~size -- write the background info. + segment = !||fg[f]~strip !||bg[b]' 'text' '!||fg[1] + .OUTPUT~charout(segment) + end + + .OUTPUT~lineout(' ') + end + +/* Write the various highlighting escape sequences. */ + prefix = '~[4m'~left(6)' '!||hi[1]'Underlined'!||fg[1] + .OUTPUT~lineout(prefix) + prefix = '~[5m'~left(6)' '!||hi[2]'Blinking'!||fg[1] + .OUTPUT~lineout(prefix) + prefix = '~[7m'~left(6)' '!||hi[3]'Inverted'!||fg[1] + .OUTPUT~lineout(prefix) + prefix = '~[8m'~left(6)' '!||hi[4]'Concealed'!||fg[1], + "(Doesn't seem to work in my xterm; might in Windows?)" + .OUTPUT~lineout(prefix) + .OUTPUT~lineout(' ') + .OUTPUT~lineout("Where ~ denotes the ASCII escape character ('1B'x).") + .OUTPUT~lineout(' ') +exit + +/*.--------------------------------------------------------.*/ +/*|One might expect to be able to use directory collections|*/ +/*|as below instead of array collections, but there is no |*/ +/*|way to guarantee that a directory's indices will be |*/ +/*|iterated over in a consistent sequence, since directory |*/ +/*|objects are not ordered. Oh, well... |*/ +/*'--------------------------------------------------------'*/ + fg = .directory~new + fg[Default] = '[0m'; fg[DefaultBold] = '[1m' + fg[Black] = '[0;30m'; fg[DarkGray] = '[1;30m' + fg[Blue] = '[0;34m'; fg[LightBlue] = '[1;34m' + fg[Green] = '[0;32m'; fg[LightGreen] = '[1;32m' + fg[Cyan] = '[0;36m'; fg[LightCyan] = '[1;36m' + fg[Red] = '[0;31m'; fg[LightRed] = '[1;31m' + fg[Purple] = '[0;35m'; fg[LightPurple] = '[1;35m' + fg[Brown] = '[0;33m'; fg[Yellow] = '[1;33m' + fg[LightGray] = '[0;37m'; fg[White] = '[1;37m' + bg = .directory~new; hi = .directory~new + bg[Black] = '[0;40m'; hi[Underlined] = '[4m' + bg[Blue] = '[0;44m'; hi[Blinking] = '[5m' + bg[Green] = '[0;42m'; hi[Inverted] = '[7m' + bg[Cyan] = '[0;46m'; hi[Concealed] = '[8m' + bg[Red] = '[0;41m' + bg[Purple] = '[0;45m' + bg[Brown] = '[0;43m' + bg[LightGray] = '[0;47m' + +usage: procedure + trace normal + + if arg(1) = '-h', + | arg(1) = '-?', + | arg(1) = '--help' + then + do + line = '/*|' + say + + do l = 3 by 1 while line~left(3) = '/*|' + line = sourceline(l) + parse var line . '/*|' text '|*/' . + .OUTPUT~lineout(text) + end + + say + exit 0 + end +return diff --git a/Task/Terminal-control-Coloured-text/Phix/terminal-control-coloured-text.phix b/Task/Terminal-control-Coloured-text/Phix/terminal-control-coloured-text.phix new file mode 100644 index 0000000000..d0f6c4b206 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Phix/terminal-control-coloured-text.phix @@ -0,0 +1,22 @@ +-- +-- demo\rosetta\Coloured_text.exw +-- ================================ +-- +text_color(GRAY) +bk_color(BLACK) +printf(1,"Background color# 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15\n") +printf(1," -----------------------------------------------\n") +for foreground=0 to 15 do + printf(1,"Foreground color# %02d ",foreground) + for background=0 to 15 do + text_color(foreground) + bk_color(background) + printf(1,"%02d",foreground) + text_color(GRAY) + bk_color(BLACK) + printf(1," ") + end for + printf(1,"\n") +end for +printf(1,"\n\npress enter to exit") +{} = wait_key() diff --git a/Task/Terminal-control-Coloured-text/XPL0/terminal-control-coloured-text-1.xpl0 b/Task/Terminal-control-Coloured-text/XPL0/terminal-control-coloured-text-1.xpl0 deleted file mode 100644 index d30d1a0167..0000000000 --- a/Task/Terminal-control-Coloured-text/XPL0/terminal-control-coloured-text-1.xpl0 +++ /dev/null @@ -1,15 +0,0 @@ -code ChOut=8, Attrib=69; -def Black, Blue, Green, Cyan, Red, Magenta, Brown, White, \attribute colors - Gray, LBlue, LGreen, LCyan, LRed, LMagenta, Yellow, BWhite; \EGA palette -[ChOut(6,^C); \default white on black background -Attrib(Red<<4+White); \white on red -ChOut(6,^o); -Attrib(Green<<4+Red); \red on green -ChOut(6,^l); -Attrib(Blue<<4+LGreen); \light green on blue -ChOut(6,^o); -Attrib(LRed<<4+White); \flashing white on (standard/dim) red -ChOut(6,^u); -Attrib(Cyan<<4+Black); \black on cyan -ChOut(6,^r); -] diff --git a/Task/Terminal-control-Coloured-text/Zkl/terminal-control-coloured-text-1.zkl b/Task/Terminal-control-Coloured-text/Zkl/terminal-control-coloured-text-1.zkl new file mode 100644 index 0000000000..252cce9fbb --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Zkl/terminal-control-coloured-text-1.zkl @@ -0,0 +1,16 @@ +fcn table(title,mode){ + println("\n\e[1m%s\e[m\n bg\t fg".fmt(title)); + foreach b in ([40..48].chain([100..107])){ + print("%3d\t\e[%s%dm".fmt(b,mode,b)); + foreach f in ([30..38].chain([90..97])){ print("\e[%dm%3d ".fmt(f,f)) } + println("\e[m"); + } +} + +table("normal ( ESC[22m or ESC[m )", "22;"); +table("bold ( ESC[1m )", "1;"); +table("faint ( ESC[2m ), not well supported", "2;"); +table("italic ( ESC[3m ), not well supported", "3;"); +table("underline ( ESC[4m ), support varies", "4;"); +table("blink ( ESC[5m )", "5;"); +table("inverted ( ESC[7m )", "7;"); diff --git a/Task/Terminal-control-Coloured-text/XPL0/terminal-control-coloured-text-2.xpl0 b/Task/Terminal-control-Coloured-text/Zkl/terminal-control-coloured-text-2.zkl similarity index 100% rename from Task/Terminal-control-Coloured-text/XPL0/terminal-control-coloured-text-2.xpl0 rename to Task/Terminal-control-Coloured-text/Zkl/terminal-control-coloured-text-2.zkl diff --git a/Task/Terminal-control-Cursor-movement/Kotlin/terminal-control-cursor-movement.kotlin b/Task/Terminal-control-Cursor-movement/Kotlin/terminal-control-cursor-movement.kotlin new file mode 100644 index 0000000000..a09f0b8bb9 --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/Kotlin/terminal-control-cursor-movement.kotlin @@ -0,0 +1,23 @@ +// version 1.1.2 + +const val ESC = "\u001B" // escape code + +fun main(args: Array) { + print("$ESC[2J") // clear terminal first + print("$ESC[10;10H") // move cursor to (10, 10) say + val aecs = arrayOf( + "[1D", // left + "[1C", // right + "[1A", // up + "[1B", // down + "[9D", // line start + "[H", // top left + "[24;79H" // bottom right - assuming 80 x 24 terminal + ) + for (aec in aecs) { + Thread.sleep(3000) // three second display between cursor movements + print("$ESC$aec") + } + Thread.sleep(3000) + println() +} diff --git a/Task/Terminal-control-Cursor-movement/Phix/terminal-control-cursor-movement.phix b/Task/Terminal-control-Cursor-movement/Phix/terminal-control-cursor-movement.phix new file mode 100644 index 0000000000..e62ede9ef2 --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/Phix/terminal-control-cursor-movement.phix @@ -0,0 +1,53 @@ +-- +-- demo\rosetta\Cursor_movement.exw +-- ================================ +-- +-- These may vary by platform/hardware... (this program is ideal for sorting such things out) +-- +constant HOME = 327, + END = 335, + UP = 328, + DOWN = 336, + LEFT = 331, + RIGHT = 333, + PGUP = 329, -- (goto top left) + PGDN = 337 -- (goto bottom right) + +constant {maxl,maxc} = video_config()[VC_SCRNLINES..VC_SCRNCOLS] + +procedure move_cursor(integer dy, integer dx) + integer {l,c} = sq_add(get_position(),{dy,dx}) + if l>=1 and l<=maxl + and c>=1 and c<=maxc then + position(l,c) + end if +end procedure + +procedure move_to(integer ny=-1, integer nx=-1) + integer {l,c} = get_position() + if ny!=-1 then l = ny end if + if nx!=-1 then c = nx end if + position(l,c) +end procedure + +procedure showkey(integer key) + integer {l,c} = get_position() + position(2,maxc-5) + ?key + position(l,c) +end procedure + +while 1 do + integer key = wait_key() + if key=#1B then exit end if -- escape quits + showkey(key) + if key=HOME then move_to(nx:=1) -- home + elsif key=END then move_to(nx:=maxc) -- end + elsif key=UP then move_cursor(-1, 0) -- up + elsif key=DOWN then move_cursor(+1, 0) -- down + elsif key=LEFT then move_cursor( 0,-1) -- left + elsif key=RIGHT then move_cursor( 0,+1) -- right + elsif key=PGUP then move_to(1,1) -- page_up + elsif key=PGDN then move_to(maxl,maxc) -- page_down + end if +end while diff --git a/Task/Terminal-control-Cursor-movement/Zkl/terminal-control-cursor-movement.zkl b/Task/Terminal-control-Cursor-movement/Zkl/terminal-control-cursor-movement.zkl new file mode 100644 index 0000000000..68f71dc828 --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/Zkl/terminal-control-cursor-movement.zkl @@ -0,0 +1,12 @@ +print("\e[2J\e[6;3H"); // clear screen, move to an initial position + Atomic.sleep(1); // pause to let cursor blink +print("\e[D"); // left + Atomic.sleep(1); +print("\e[C"); // right + Atomic.sleep(1); +print("\e[A"); // up + Atomic.sleep(1); +print("\e[B"); // down + Atomic.sleep(1); +print("\e[;H"); // top left + Atomic.sleep(1); diff --git a/Task/Terminal-control-Cursor-positioning/BBC-BASIC/terminal-control-cursor-positioning.bbc b/Task/Terminal-control-Cursor-positioning/BASIC/terminal-control-cursor-positioning-4.basic similarity index 100% rename from Task/Terminal-control-Cursor-positioning/BBC-BASIC/terminal-control-cursor-positioning.bbc rename to Task/Terminal-control-Cursor-positioning/BASIC/terminal-control-cursor-positioning-4.basic diff --git a/Task/Terminal-control-Cursor-positioning/BASIC/terminal-control-cursor-positioning-5.basic b/Task/Terminal-control-Cursor-positioning/BASIC/terminal-control-cursor-positioning-5.basic new file mode 100644 index 0000000000..7f4683d79e --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/BASIC/terminal-control-cursor-positioning-5.basic @@ -0,0 +1,4 @@ + 100 print chr$(19) :rem change to lowercase set + 110 print chr$(14) :rem go to position 1,1 + 120 print:print:print:print + 130 print tab(2) "Hello" diff --git a/Task/Terminal-control-Cursor-positioning/Kotlin/terminal-control-cursor-positioning.kotlin b/Task/Terminal-control-Cursor-positioning/Kotlin/terminal-control-cursor-positioning.kotlin new file mode 100644 index 0000000000..5a9070f34b --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Kotlin/terminal-control-cursor-positioning.kotlin @@ -0,0 +1,6 @@ +// version 1.1.2 + +fun main(args: Array) { + print("\u001Bc") // clear screen first + println("\u001B[6;3HHello") +} diff --git a/Task/Terminal-control-Cursor-positioning/Zkl/terminal-control-cursor-positioning.zkl b/Task/Terminal-control-Cursor-positioning/Zkl/terminal-control-cursor-positioning.zkl new file mode 100644 index 0000000000..e9f7fbf4db --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Zkl/terminal-control-cursor-positioning.zkl @@ -0,0 +1 @@ +print("\e[6;3H" "Hello"); diff --git a/Task/Terminal-control-Dimensions/Kotlin/terminal-control-dimensions.kotlin b/Task/Terminal-control-Dimensions/Kotlin/terminal-control-dimensions.kotlin new file mode 100644 index 0000000000..4c96b22001 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Kotlin/terminal-control-dimensions.kotlin @@ -0,0 +1,13 @@ +// version 1.1.2 + +/* + I needed to execute the terminal command: 'export COLUMNS LINES' + before running this program for it to work (returned 'null' sizes otherwise). +*/ + +fun main(args: Array) { + val lines = System.getenv("LINES") + val columns = System.getenv("COLUMNS") + println("Lines = $lines") + println("Columns = $columns") +} diff --git a/Task/Terminal-control-Dimensions/Zkl/terminal-control-dimensions.zkl b/Task/Terminal-control-Dimensions/Zkl/terminal-control-dimensions.zkl new file mode 100644 index 0000000000..e10be0e626 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Zkl/terminal-control-dimensions.zkl @@ -0,0 +1,2 @@ +h,w:=System.popen("stty size","r").readln().split(); +println(w," x ",h); diff --git a/Task/Terminal-control-Display-an-extended-character/Bc/terminal-control-display-an-extended-character.bc b/Task/Terminal-control-Display-an-extended-character/Bc/terminal-control-display-an-extended-character.bc new file mode 100644 index 0000000000..8822dcef11 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Bc/terminal-control-display-an-extended-character.bc @@ -0,0 +1,3 @@ +"£ +" +quit diff --git a/Task/Terminal-control-Display-an-extended-character/Beeswax/terminal-control-display-an-extended-character.beeswax b/Task/Terminal-control-Display-an-extended-character/Beeswax/terminal-control-display-an-extended-character.beeswax new file mode 100644 index 0000000000..abceb0f28d --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Beeswax/terminal-control-display-an-extended-character.beeswax @@ -0,0 +1 @@ +_4~9P.P.M} diff --git a/Task/Terminal-control-Display-an-extended-character/Kotlin/terminal-control-display-an-extended-character.kotlin b/Task/Terminal-control-Display-an-extended-character/Kotlin/terminal-control-display-an-extended-character.kotlin new file mode 100644 index 0000000000..acde047c47 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Kotlin/terminal-control-display-an-extended-character.kotlin @@ -0,0 +1,3 @@ +// version 1.1.2 + +fun main(args:Array) = println("£") diff --git a/Task/Terminal-control-Display-an-extended-character/Zkl/terminal-control-display-an-extended-character.zkl b/Task/Terminal-control-Display-an-extended-character/Zkl/terminal-control-display-an-extended-character.zkl new file mode 100644 index 0000000000..ba026a819d --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Zkl/terminal-control-display-an-extended-character.zkl @@ -0,0 +1 @@ +"\u00a3 \Ua3;".println() //-->£ £ diff --git a/Task/Terminal-control-Hiding-the-cursor/Kotlin/terminal-control-hiding-the-cursor.kotlin b/Task/Terminal-control-Hiding-the-cursor/Kotlin/terminal-control-hiding-the-cursor.kotlin new file mode 100644 index 0000000000..797eec4d1b --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Kotlin/terminal-control-hiding-the-cursor.kotlin @@ -0,0 +1,8 @@ +// version 1.1.2 + +fun main(args: Array) { + print("\u001B[?25l") // hide cursor + Thread.sleep(2000) // wait 2 seconds before redisplaying cursor + print("\u001B[?25h") // display cursor + Thread.sleep(2000) // wait 2 more seconds before exiting +} diff --git a/Task/Terminal-control-Hiding-the-cursor/PureBasic/terminal-control-hiding-the-cursor.purebasic b/Task/Terminal-control-Hiding-the-cursor/PureBasic/terminal-control-hiding-the-cursor-1.purebasic similarity index 100% rename from Task/Terminal-control-Hiding-the-cursor/PureBasic/terminal-control-hiding-the-cursor.purebasic rename to Task/Terminal-control-Hiding-the-cursor/PureBasic/terminal-control-hiding-the-cursor-1.purebasic diff --git a/Task/Terminal-control-Hiding-the-cursor/PureBasic/terminal-control-hiding-the-cursor-2.purebasic b/Task/Terminal-control-Hiding-the-cursor/PureBasic/terminal-control-hiding-the-cursor-2.purebasic new file mode 100644 index 0000000000..c65c77615e --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/PureBasic/terminal-control-hiding-the-cursor-2.purebasic @@ -0,0 +1,24 @@ +Procedure HideCursor () + ConsoleCursor(0) +EndProcedure + +Procedure ShowCursor (CursorHeight.b = 1) + If CursorHeight > 10 : CursorHeight = 10 : EndIf + If CursorHeight < 1 : CursorHeight = 1 : EndIf + ConsoleCursor(CursorHeight) +EndProcedure + +Procedure NL (NoL.b = 1) + For i = 1 To NoL : PrintN("") : Next +EndProcedure + +If OpenConsole() + EnableGraphicalConsole(1) + Print(" full cursor > ") + ShowCursor(11) : Delay(4000) : NL() + Print(" hidden cursor > ") + HideCursor() : Delay(4000) : NL() + Print("minimal cursor > ") + ShowCursor(-0.5) + Print("press [Enter] to continue ... ") : Input() +EndIf diff --git a/Task/Terminal-control-Hiding-the-cursor/Zkl/terminal-control-hiding-the-cursor.zkl b/Task/Terminal-control-Hiding-the-cursor/Zkl/terminal-control-hiding-the-cursor.zkl new file mode 100644 index 0000000000..a63c581c51 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Zkl/terminal-control-hiding-the-cursor.zkl @@ -0,0 +1,3 @@ +print("\e[?25l"); +Atomic.sleep(3); +print("\e[?25h"); diff --git a/Task/Terminal-control-Inverse-video/6502-Assembly/terminal-control-inverse-video.6502 b/Task/Terminal-control-Inverse-video/6502-Assembly/terminal-control-inverse-video.6502 new file mode 100644 index 0000000000..23e844a6aa --- /dev/null +++ b/Task/Terminal-control-Inverse-video/6502-Assembly/terminal-control-inverse-video.6502 @@ -0,0 +1,22 @@ +; C64 - Terminal control: Inverse Video + +; *** labels *** + +strout = $ab1e + +; *** main *** + + *=$02a8 ; sys 680 + + lda #str ; Address high byte + jsr strout ; Print a null terminated string. + rts + +; *** data *** + +str .byte $12 ; the REVERSE ON control code + ; see https://en.wikipedia.org/wiki/PETSCII + .text "reversed" + .byte $92 ; the REVERSE OFF control code + .null " normal" ; null terminated string diff --git a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-7.basic b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-7.basic index 5df2772b6d..54ff9a1b0a 100644 --- a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-7.basic +++ b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-7.basic @@ -1,4 +1 @@ -10 INVERSE 1 -20 PRINT "FOO"; -30 INVERSE 0 -40 PRINT "BAR" +PRINT "FOOBAR" diff --git a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-8.basic b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-8.basic new file mode 100644 index 0000000000..9de175bf56 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-8.basic @@ -0,0 +1,8 @@ +10 LET S$="FOO" +20 GOSUB 50 +30 PRINT S$;"BAR" +40 STOP +50 FOR I=1 TO LEN S$ +60 LET S$(I)=CHR$ (128+CODE S$(I)) +70 NEXT I +80 RETURN diff --git a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-9.basic b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-9.basic new file mode 100644 index 0000000000..5df2772b6d --- /dev/null +++ b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-9.basic @@ -0,0 +1,4 @@ +10 INVERSE 1 +20 PRINT "FOO"; +30 INVERSE 0 +40 PRINT "BAR" diff --git a/Task/Terminal-control-Inverse-video/BBC-BASIC/terminal-control-inverse-video-1.bbc b/Task/Terminal-control-Inverse-video/BBC-BASIC/terminal-control-inverse-video-1.bbc deleted file mode 100644 index 68cc00506e..0000000000 --- a/Task/Terminal-control-Inverse-video/BBC-BASIC/terminal-control-inverse-video-1.bbc +++ /dev/null @@ -1,6 +0,0 @@ - COLOUR 128 : REM Black background - COLOUR 15 : REM White foreground - PRINT "Inverse"; - COLOUR 128+15 : REM White background - COLOUR 0 : REM Black foreground - PRINT " video" diff --git a/Task/Terminal-control-Inverse-video/BBC-BASIC/terminal-control-inverse-video-2.bbc b/Task/Terminal-control-Inverse-video/BBC-BASIC/terminal-control-inverse-video-2.bbc deleted file mode 100644 index 1b6f4e4bb8..0000000000 --- a/Task/Terminal-control-Inverse-video/BBC-BASIC/terminal-control-inverse-video-2.bbc +++ /dev/null @@ -1,3 +0,0 @@ - inverse$ = CHR$(17)+CHR$(128)+CHR$(17)+CHR$(15) - normal$ = CHR$(17)+CHR$(128+15)+CHR$(17)+CHR$(0) - PRINT inverse$ + "Inverse" + normal$ + " video" diff --git a/Task/Terminal-control-Inverse-video/Kotlin/terminal-control-inverse-video.kotlin b/Task/Terminal-control-Inverse-video/Kotlin/terminal-control-inverse-video.kotlin new file mode 100644 index 0000000000..948d051e14 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Kotlin/terminal-control-inverse-video.kotlin @@ -0,0 +1,5 @@ +// version 1.1.2 + +fun main(args: Array) { + println("\u001B[7mInverse\u001B[m Normal") +} diff --git a/Task/Terminal-control-Inverse-video/Pascal/terminal-control-inverse-video.pascal b/Task/Terminal-control-Inverse-video/Pascal/terminal-control-inverse-video.pascal new file mode 100644 index 0000000000..3349c0892a --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Pascal/terminal-control-inverse-video.pascal @@ -0,0 +1,14 @@ +program InverseVideo; +{$LINKLIB tinfo} +uses + ncurses; +begin + initscr; + attron(A_REVERSE); + printw('reversed'); + attroff(A_REVERSE); + printw(' normal'); + refresh; + getch; + endwin; +end. diff --git a/Task/Terminal-control-Inverse-video/Phix/terminal-control-inverse-video.phix b/Task/Terminal-control-Inverse-video/Phix/terminal-control-inverse-video.phix new file mode 100644 index 0000000000..9201f69848 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Phix/terminal-control-inverse-video.phix @@ -0,0 +1,12 @@ +-- +-- demo\rosetta\Inverse_Video.exw +-- ================================ +-- +text_color(BLACK) +bk_color(WHITE) +printf(1,"Inverse") +text_color(WHITE) +bk_color(BLACK) +printf(1," Video") +printf(1,"\n\npress enter to exit") +{} = wait_key() diff --git a/Task/Terminal-control-Inverse-video/PureBasic/terminal-control-inverse-video.purebasic b/Task/Terminal-control-Inverse-video/PureBasic/terminal-control-inverse-video.purebasic deleted file mode 100644 index f917ae3d6e..0000000000 --- a/Task/Terminal-control-Inverse-video/PureBasic/terminal-control-inverse-video.purebasic +++ /dev/null @@ -1,9 +0,0 @@ -If OpenConsole() - ConsoleColor(0, 15) ;use the colors black (background) and white (forground) - PrintN("Inverse Video") - ConsoleColor(15, 0) ;use the colors white (background) and black (forground) - PrintN("Normal Video") - - Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() - CloseConsole() -EndIf diff --git a/Task/Terminal-control-Inverse-video/Run-BASIC/terminal-control-inverse-video.run b/Task/Terminal-control-Inverse-video/Run-BASIC/terminal-control-inverse-video.run deleted file mode 100644 index 35efdfc74b..0000000000 --- a/Task/Terminal-control-Inverse-video/Run-BASIC/terminal-control-inverse-video.run +++ /dev/null @@ -1,8 +0,0 @@ -' ---------- foo is reverse -------------- -x$ = shell$("tput mr -echo 'foo'") - -' ---------- bar is normal -------------- -x$ = shell$("tput me -echo 'bar'") -wait diff --git a/Task/Terminal-control-Inverse-video/Zkl/terminal-control-inverse-video.zkl b/Task/Terminal-control-Inverse-video/Zkl/terminal-control-inverse-video.zkl new file mode 100644 index 0000000000..25aff83b51 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Zkl/terminal-control-inverse-video.zkl @@ -0,0 +1 @@ +println("\e[7mReversed\e[m Normal"); diff --git a/Task/Terminal-control-Positional-read/Kotlin/terminal-control-positional-read.kotlin b/Task/Terminal-control-Positional-read/Kotlin/terminal-control-positional-read.kotlin new file mode 100644 index 0000000000..1b5b97fce3 --- /dev/null +++ b/Task/Terminal-control-Positional-read/Kotlin/terminal-control-positional-read.kotlin @@ -0,0 +1,25 @@ +// Kotlin Native version 0.3 + +import kotlinx.cinterop.* +import win32.* + +fun main(args: Array) { + for (i in 0 until (80 * 25)) print("A") // fill 80 x 25 console with 'A's + println() + memScoped { + val conOut = GetStdHandle(-11) + val info = alloc() + val pos = alloc() + GetConsoleScreenBufferInfo(conOut, info.ptr) + pos.X = (info.srWindow.Left + 3).toShort() // column number 3 of display window + pos.Y = (info.srWindow.Top + 6).toShort() // row number 6 of display window + val c = alloc() + val len = alloc() + ReadConsoleOutputCharacterW(conOut, c.ptr, 1, pos.readValue(), len.ptr) + if (len.value == 1) { + val ch = c.value.toChar() + println("The character at column 3, row 6 is '$ch'") + } + else println("Something went wrong!") + } +} diff --git a/Task/Terminal-control-Positional-read/Phix/terminal-control-positional-read.phix b/Task/Terminal-control-Positional-read/Phix/terminal-control-positional-read.phix new file mode 100644 index 0000000000..091c6403d9 --- /dev/null +++ b/Task/Terminal-control-Positional-read/Phix/terminal-control-positional-read.phix @@ -0,0 +1,9 @@ +-- +-- demo\rosetta\Positional_read.exw +-- ================================ +-- +position(6,1) -- line 6 column 1 (1-based) +puts(1,"abcdef") +integer {ch,attr} = get_screen_char(6,3) +printf(1,"\n\n=>%c",ch) +{} = wait_key() diff --git a/Task/Terminal-control-Positional-read/TXR/terminal-control-positional-read.txr b/Task/Terminal-control-Positional-read/TXR/terminal-control-positional-read.txr new file mode 100644 index 0000000000..bdf00f3f84 --- /dev/null +++ b/Task/Terminal-control-Positional-read/TXR/terminal-control-positional-read.txr @@ -0,0 +1,72 @@ +;;; Type definitions and constants + +(typedef BOOL (enum BOOL FALSE TRUE)) +(typedef HANDLE cptr) +(typedef WCHAR wchar) +(typedef DWORD uint32) +(typedef WORD uint16) +(typedef SHORT short) + +(typedef COORD + (struct COORD + (X SHORT) + (Y SHORT))) + +(typedef SMALL_RECT + (struct SMALL_RECT + (Left SHORT) + (Top SHORT) + (Right SHORT) + (Bottom SHORT))) + +(typedef CONSOLE_SCREEN_BUFFER_INFO + (struct CONSOLE_SCREEN_BUFFER_INFO + (dwSize COORD) + (dwCursorPosition COORD) + (wAttributes WORD) + (srWindow SMALL_RECT) + (dwMaximumWindowSize COORD))) + +;;; Various constants + +(defvarl STD_INPUT_HANDLE (- #x100000000 10)) +(defvarl STD_OUTPUT_HANDLE (- #x100000000 11)) +(defvarl STD_ERROR_HANDLE (- #x100000000 12)) + +(defvarl NULL cptr-null) +(defvarl INVALID_HANDLE_VALUE (cptr-int -1)) + +;;; Foreign Function Bindings + +(with-dyn-lib "kernel32.dll" + (deffi GetStdHandle "GetStdHandle" HANDLE (DWORD)) + (deffi GetConsoleScreenBufferInfo "GetConsoleScreenBufferInfo" + BOOL (HANDLE (ptr-out CONSOLE_SCREEN_BUFFER_INFO))) + (deffi ReadConsoleOutputCharacter "ReadConsoleOutputCharacterW" + BOOL (HANDLE (ptr-out (array 1 WCHAR)) + DWORD COORD (ptr-out (array 1 DWORD))))) + +;;; Now the character at <2, 5> -- column 3, row 6. + +(let ((console-handle (GetStdHandle STD_OUTPUT_HANDLE))) + (when (equal console-handle INVALID_HANDLE_VALUE) + (error "couldn't get console handle")) + + (let* ((cinfo (new CONSOLE_SCREEN_BUFFER_INFO)) + (getinfo-ok (GetConsoleScreenBufferInfo console-handle cinfo)) + (coord (if getinfo-ok + ^#S(COORD X ,(+ 2 cinfo.srWindow.Left) + Y ,(+ 5 cinfo.srWindow.Top)) + #S(COORD X 0 Y 0))) + (chars (vector 1)) + (nread (vector 1)) + (read-ok (ReadConsoleOutputCharacter console-handle chars + 1 coord nread))) + (when (eq getinfo-ok 'FALSE) + (error "GetConsoleScreenBufferInfo failed")) + (prinl cinfo) + (when (eq read-ok 'FALSE) + (error "ReadConsoleOutputCharacter failed")) + (unless (plusp [nread 0]) + (error "ReadConsoleOutputCharacter read zero characters")) + (format t "character is ~s\n" [chars 0]))) diff --git a/Task/Terminal-control-Preserve-screen/Kotlin/terminal-control-preserve-screen.kotlin b/Task/Terminal-control-Preserve-screen/Kotlin/terminal-control-preserve-screen.kotlin new file mode 100644 index 0000000000..14d979f77b --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Kotlin/terminal-control-preserve-screen.kotlin @@ -0,0 +1,13 @@ +// version 1.1.2 + +const val ESC = "\u001B" + +fun main(args: Array) { + print("$ESC[?1049h$ESC[H") + println("Alternate screen buffer") + for(i in 5 downTo 1) { + print("\rGoing back in $i second${if (i != 1) "s" else ""}...") + Thread.sleep(1000) + } + print("$ESC[?1049l") +} diff --git a/Task/Terminal-control-Preserve-screen/Zkl/terminal-control-preserve-screen.zkl b/Task/Terminal-control-Preserve-screen/Zkl/terminal-control-preserve-screen.zkl new file mode 100644 index 0000000000..769c18cf24 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Zkl/terminal-control-preserve-screen.zkl @@ -0,0 +1,7 @@ +print("\e[?1049h\e[H"); +println("Alternate screen buffer"); +foreach i in ([5..1,-1]){ + print("\rgoing back in %d...".fmt(i)); + Atomic.sleep(1); +} +print("\e[?1049l"); diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Beeswax/terminal-control-ringing-the-terminal-bell.beeswax b/Task/Terminal-control-Ringing-the-terminal-bell/Beeswax/terminal-control-ringing-the-terminal-bell.beeswax new file mode 100644 index 0000000000..8965e754aa --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Beeswax/terminal-control-ringing-the-terminal-bell.beeswax @@ -0,0 +1 @@ +_7} diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Gnuplot/terminal-control-ringing-the-terminal-bell.gnuplot b/Task/Terminal-control-Ringing-the-terminal-bell/Gnuplot/terminal-control-ringing-the-terminal-bell.gnuplot new file mode 100644 index 0000000000..da22fc2d15 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Gnuplot/terminal-control-ringing-the-terminal-bell.gnuplot @@ -0,0 +1 @@ +print "\007" diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Kotlin/terminal-control-ringing-the-terminal-bell.kotlin b/Task/Terminal-control-Ringing-the-terminal-bell/Kotlin/terminal-control-ringing-the-terminal-bell.kotlin new file mode 100644 index 0000000000..840b77a3ae --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Kotlin/terminal-control-ringing-the-terminal-bell.kotlin @@ -0,0 +1,5 @@ +// version 1.1.2 + +fun main(args: Array) { + println("\u0007") +} diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Phix/terminal-control-ringing-the-terminal-bell.phix b/Task/Terminal-control-Ringing-the-terminal-bell/Phix/terminal-control-ringing-the-terminal-bell.phix new file mode 100644 index 0000000000..601a7c9cfe --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Phix/terminal-control-ringing-the-terminal-bell.phix @@ -0,0 +1 @@ +puts(1,"\x07") diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Zkl/terminal-control-ringing-the-terminal-bell.zkl b/Task/Terminal-control-Ringing-the-terminal-bell/Zkl/terminal-control-ringing-the-terminal-bell.zkl new file mode 100644 index 0000000000..d62f0e37d0 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Zkl/terminal-control-ringing-the-terminal-bell.zkl @@ -0,0 +1 @@ +print("\x07"); diff --git a/Task/Terminal-control-Unicode-output/jq/terminal-control-unicode-output.jq b/Task/Terminal-control-Unicode-output/Jq/terminal-control-unicode-output.jq similarity index 100% rename from Task/Terminal-control-Unicode-output/jq/terminal-control-unicode-output.jq rename to Task/Terminal-control-Unicode-output/Jq/terminal-control-unicode-output.jq diff --git a/Task/Terminal-control-Unicode-output/Kotlin/terminal-control-unicode-output.kotlin b/Task/Terminal-control-Unicode-output/Kotlin/terminal-control-unicode-output.kotlin new file mode 100644 index 0000000000..d4945f3325 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/Kotlin/terminal-control-unicode-output.kotlin @@ -0,0 +1,9 @@ +// version 1.1.2 + +fun main(args: Array) { + val supportsUnicode = "UTF" in System.getenv("LANG").toUpperCase() + if (supportsUnicode) + println("This terminal supports unicode and U+25b3 is : \u25b3") + else + println("This terminal does not support unicode") +} diff --git a/Task/Terminal-control-Unicode-output/Zkl/terminal-control-unicode-output.zkl b/Task/Terminal-control-Unicode-output/Zkl/terminal-control-unicode-output.zkl new file mode 100644 index 0000000000..a3171a8ccf --- /dev/null +++ b/Task/Terminal-control-Unicode-output/Zkl/terminal-control-unicode-output.zkl @@ -0,0 +1,4 @@ +if(System.isUnix and T("LC_CTYPE","LC_LANG","LANG").apply(System.getenv) + .filter().filter("holds","UTF")) + println("This terminal supports UTF-8 (\U25B3;)"); +else println("I have doubts about UTF-8 on this terminal."); diff --git a/Task/Ternary-logic/C/ternary-logic-4.c b/Task/Ternary-logic/C/ternary-logic-4.c deleted file mode 100644 index 0a2aba2181..0000000000 --- a/Task/Ternary-logic/C/ternary-logic-4.c +++ /dev/null @@ -1,32 +0,0 @@ -[Not] -F | T -? | ? -T | F - -[And] - F ? T - ------- -F | F F F -? | F ? ? -T | F ? T - -[Or] - F ? T - ------- -F | F ? T -? | ? ? T -T | T T T - -[Equiv] - F ? T - ------- -F | T ? F -? | ? ? ? -T | F ? T - -[Imply] - F ? T - ------- -F | T T T -? | ? ? T -T | F ? T diff --git a/Task/Ternary-logic/C/ternary-logic-5.c b/Task/Ternary-logic/C/ternary-logic-5.c deleted file mode 100644 index 1f006597f3..0000000000 --- a/Task/Ternary-logic/C/ternary-logic-5.c +++ /dev/null @@ -1,55 +0,0 @@ -#include -#include - -typedef double half_truth, maybe; - -inline maybe not3(maybe a) { return 1 - a; } - -inline maybe -and3(maybe a, maybe b) { return a * b; } - -inline maybe -or3(maybe a, maybe b) { return a + b - a * b; } - -inline maybe -eq3(maybe a, maybe b) { return 1 - a - b + 2 * a * b; } - -inline maybe -imply3(maybe a, maybe b) { return or3(not3(a), b); } - -#define true3(x) ((x) * RAND_MAX > rand()) -#define if3(x) if (true3(x)) - -int main() -{ - maybe roses_are_red = 0.25; /* they can be white or black, too */ - maybe violets_are_blue = 1; /* aren't they just */ - int i; - - puts("Verifying flowery truth for 40 times:\n"); - - puts("Rose is NOT red:"); /* chance: .75 */ - for (i = 0; i < 40 || !puts("\n"); i++) - printf( true3( not3(roses_are_red) ) ? "T" : "_"); - - /* pick a rose and a violet; */ - puts("Rose is red AND violet is blue:"); - /* chance of rose being red AND violet being blue is .25 */ - for (i = 0; i < 40 || !puts("\n"); i++) - printf( true3( and3(roses_are_red, violets_are_blue) ) - ? "T" : "_"); - - /* chance of rose being red OR violet being blue is 1 */ - puts("Rose is red OR violet is blue:"); - for (i = 0; i < 40 || !puts("\n"); i++) - printf( true3( or3(roses_are_red, violets_are_blue) ) - ? "T" : "_"); - - /* pick two roses; chance of em being both red or both not red is .625 */ - puts("This rose is as red as that rose:"); - for (i = 0; i < 40 || !puts("\n"); i++) - if3(eq3(roses_are_red, roses_are_red)) putchar('T'); - else putchar('_'); - - return 0; -} diff --git a/Task/Ternary-logic/Common-Lisp/ternary-logic-1.lisp b/Task/Ternary-logic/Common-Lisp/ternary-logic-1.lisp deleted file mode 100644 index f6f438c50a..0000000000 --- a/Task/Ternary-logic/Common-Lisp/ternary-logic-1.lisp +++ /dev/null @@ -1,31 +0,0 @@ -(defun tri-not (x) (- 1 x)) -(defun tri-and (&rest x) (apply #'* x)) -(defun tri-or (&rest x) (tri-not (apply #'* (mapcar #'tri-not x)))) -(defun tri-eq (x y) (+ (tri-and x y) (tri-and (- 1 x) (- 1 y)))) -(defun tri-imply (x y) (tri-or (tri-not x) y)) - -(defun tri-test (x) (< (random 1e0) x)) -(defun tri-string (x) (if (= x 1) "T" (if (= x 0) "F" "?"))) - -;; to say (tri-if (condition) (yes) (no)) -(defmacro tri-if (tri ifcase &optional elsecase) - `(if (tri-test ,tri) ,ifcase ,elsecase)) - -(defun print-table (func header) - (let ((vals '(1 .5 0))) - (format t "~%~a:~%" header) - (format t " ~{~a ~^~}~%---------~%" (mapcar #'tri-string vals)) - (loop for row in vals do - (format t "~a | " (tri-string row)) - (loop for col in vals do - (format t "~a " (tri-string (funcall func row col)))) - (write-line "")))) - -(write-line "NOT:") -(loop for row in '(1 .5 0) do - (format t "~a | ~a~%" (tri-string row) (tri-string (tri-not row)))) - -(print-table #'tri-and "AND") -(print-table #'tri-or "OR") -(print-table #'tri-imply "IMPLY") -(print-table #'tri-eq "EQUAL") diff --git a/Task/Ternary-logic/Common-Lisp/ternary-logic-2.lisp b/Task/Ternary-logic/Common-Lisp/ternary-logic-2.lisp deleted file mode 100644 index d46f97b47f..0000000000 --- a/Task/Ternary-logic/Common-Lisp/ternary-logic-2.lisp +++ /dev/null @@ -1,32 +0,0 @@ -NOT: -T | F -? | ? -F | T - -AND: - T ? F ---------- -T | T ? F -? | ? ? F -F | F F F - -OR: - T ? F ---------- -T | T T T -? | T ? ? -F | T ? F - -IMPLY: - T ? F ---------- -T | T ? F -? | T ? ? -F | T T T - -EQUAL: - T ? F ---------- -T | T ? F -? | ? ? ? -F | F ? T diff --git a/Task/Ternary-logic/jq/ternary-logic.jq b/Task/Ternary-logic/Jq/ternary-logic.jq similarity index 100% rename from Task/Ternary-logic/jq/ternary-logic.jq rename to Task/Ternary-logic/Jq/ternary-logic.jq diff --git a/Task/Ternary-logic/Kotlin/ternary-logic.kotlin b/Task/Ternary-logic/Kotlin/ternary-logic.kotlin new file mode 100644 index 0000000000..11e035b0c3 --- /dev/null +++ b/Task/Ternary-logic/Kotlin/ternary-logic.kotlin @@ -0,0 +1,86 @@ +// version 1.1.2 + +enum class Trit { + TRUE, MAYBE, FALSE; + + operator fun not() = when (this) { + TRUE -> FALSE + MAYBE -> MAYBE + FALSE -> TRUE + } + + infix fun and(other: Trit) = when (this) { + TRUE -> other + MAYBE -> if (other == FALSE) FALSE else MAYBE + FALSE -> FALSE + } + + infix fun or(other: Trit) = when (this) { + TRUE -> TRUE + MAYBE -> if (other == TRUE) TRUE else MAYBE + FALSE -> other + } + + infix fun imp(other: Trit) = when (this) { + TRUE -> other + MAYBE -> if (other == TRUE) TRUE else MAYBE + FALSE -> TRUE + } + + infix fun eqv(other: Trit) = when (this) { + TRUE -> other + MAYBE -> MAYBE + FALSE -> !other + } + + override fun toString() = this.name[0].toString() +} + +fun main(args: Array) { + val ta = arrayOf(Trit.TRUE, Trit.MAYBE, Trit.FALSE) + + // not + println("not") + println("-------") + for (t in ta) println(" $t | ${!t}") + println() + + // and + println("and | T M F") + println("-------------") + for (t in ta) { + print(" $t | ") + for (tt in ta) print("${t and tt} ") + println() + } + println() + + // or + println("or | T M F") + println("-------------") + for (t in ta) { + print(" $t | ") + for (tt in ta) print("${t or tt} ") + println() + } + println() + + // imp + println("imp | T M F") + println("-------------") + for (t in ta) { + print(" $t | ") + for (tt in ta) print("${t imp tt} ") + println() + } + println() + + // eqv + println("eqv | T M F") + println("-------------") + for (t in ta) { + print(" $t | ") + for (tt in ta) print("${t eqv tt} ") + println() + } +} diff --git a/Task/Ternary-logic/OoRexx/ternary-logic.rexx b/Task/Ternary-logic/OoRexx/ternary-logic.rexx new file mode 100644 index 0000000000..82ca393ad1 --- /dev/null +++ b/Task/Ternary-logic/OoRexx/ternary-logic.rexx @@ -0,0 +1,124 @@ +tritValues = .array~of(.trit~true, .trit~false, .trit~maybe) +tab = '09'x + +say "not operation (\)" +loop a over tritValues + say "\"a":" (\a) +end + +say +say "and operation (&)" +loop aa over tritValues + loop bb over tritValues + say (aa" & "bb":" (aa&bb)) + end +end + +say +say "or operation (|)" +loop aa over tritValues + loop bb over tritValues + say (aa" | "bb":" (aa|bb)) + end +end + +say +say "implies operation (&&)" +loop aa over tritValues + loop bb over tritValues + say (aa" && "bb":" (aa&&bb)) + end +end + +say +say "equals operation (=)" +loop aa over tritValues + loop bb over tritValues + say (aa" = "bb":" (aa=bb)) + end +end + +::class trit +-- making this a private method so we can control the creation +-- of these. We only allow 3 instances to exist +::method new class private + forward class(super) + +::method init class + expose true false maybe + -- delayed creation + true = .nil + false = .nil + maybe = .nil + +-- read only attribute access to the instances. +-- these methods create the appropriate singleton on the first call +::attribute true class get + expose true + if true == .nil then true = self~new("True") + return true + +::attribute false class get + expose false + if false == .nil then false = self~new("False") + return false + +::attribute maybe class get + expose maybe + if maybe == .nil then maybe = self~new("Maybe") + return maybe + +-- create an instance +::method init + expose value + use arg value + +-- string method to return the value of the instance +::method string + expose value + return value + +-- "and" method using the operator overload +::method "&" + use strict arg other + if self == .trit~true then return other + else if self == .trit~maybe then do + if other == .trit~false then return .trit~false + else return .trit~maybe + end + else return .trit~false + +-- "or" method using the operator overload +::method "|" + use strict arg other + if self == .trit~true then return .trit~true + else if self == .trit~maybe then do + if other == .trit~true then return .trit~true + else return .trit~maybe + end + else return other + +-- implies method...using the XOR operator for this +::method "&&" + use strict arg other + if self == .trit~true then return other + else if self == .trit~maybe then do + if other == .trit~true then return .trit~true + else return .trit~maybe + end + else return .trit~true + +-- "not" method using the operator overload +::method "\" + if self == .trit~true then return .trit~false + else if self == .trit~maybe then return .trit~maybe + else return .trit~true + +-- "equals" using the "=" override. This makes a distinction between +-- the "==" operator, which is real equality and the "=" operator, which +-- is trinary equality. +::method "=" + use strict arg other + if self == .trit~true then return other + else if self == .trit~maybe then return .trit~maybe + else return \other diff --git a/Task/Test-a-function/jq/test-a-function-1.jq b/Task/Test-a-function/Jq/test-a-function-1.jq similarity index 100% rename from Task/Test-a-function/jq/test-a-function-1.jq rename to Task/Test-a-function/Jq/test-a-function-1.jq diff --git a/Task/Test-a-function/jq/test-a-function-2.jq b/Task/Test-a-function/Jq/test-a-function-2.jq similarity index 100% rename from Task/Test-a-function/jq/test-a-function-2.jq rename to Task/Test-a-function/Jq/test-a-function-2.jq diff --git a/Task/Test-a-function/jq/test-a-function-3.jq b/Task/Test-a-function/Jq/test-a-function-3.jq similarity index 100% rename from Task/Test-a-function/jq/test-a-function-3.jq rename to Task/Test-a-function/Jq/test-a-function-3.jq diff --git a/Task/Test-a-function/jq/test-a-function-4.jq b/Task/Test-a-function/Jq/test-a-function-4.jq similarity index 100% rename from Task/Test-a-function/jq/test-a-function-4.jq rename to Task/Test-a-function/Jq/test-a-function-4.jq diff --git a/Task/Test-a-function/jq/test-a-function-5.jq b/Task/Test-a-function/Jq/test-a-function-5.jq similarity index 100% rename from Task/Test-a-function/jq/test-a-function-5.jq rename to Task/Test-a-function/Jq/test-a-function-5.jq diff --git a/Task/Test-a-function/Kotlin/test-a-function.kotlin b/Task/Test-a-function/Kotlin/test-a-function.kotlin new file mode 100644 index 0000000000..67bbb88b3c --- /dev/null +++ b/Task/Test-a-function/Kotlin/test-a-function.kotlin @@ -0,0 +1,15 @@ +// version 1.1.3 + +fun isPalindrome(s: String) = (s == s.reversed()) + +fun main(args: Array) { + val testCases = listOf("racecar", "alice", "eertree", "david") + for (testCase in testCases) { + try { + assert(isPalindrome(testCase)) { "$testCase is not a palindrome" } + } + catch (ae: AssertionError) { + println(ae.message) + } + } +} diff --git a/Task/Test-a-function/Scheme/test-a-function.ss b/Task/Test-a-function/Scheme/test-a-function.ss new file mode 100644 index 0000000000..1efa80050c --- /dev/null +++ b/Task/Test-a-function/Scheme/test-a-function.ss @@ -0,0 +1,6 @@ +(import (srfi 64)) +(test-begin "palindrome-tests") +(test-assert (palindrome? "ingirumimusnocteetconsumimurigni")) +(test-assert (not (palindrome? "This is not a palindrome"))) +(test-equal #t (palindrome? "ingirumimusnocteetconsumimurigni")) ; another of several test functions +(test-end) diff --git a/Task/Test-a-function/Zkl/test-a-function-1.zkl b/Task/Test-a-function/Zkl/test-a-function-1.zkl new file mode 100644 index 0000000000..8eba111365 --- /dev/null +++ b/Task/Test-a-function/Zkl/test-a-function-1.zkl @@ -0,0 +1,4 @@ +fcn pali(text){ + if (text.len()<2) return(False); + text==text.reverse(); +} diff --git a/Task/Test-a-function/Zkl/test-a-function-2.zkl b/Task/Test-a-function/Zkl/test-a-function-2.zkl new file mode 100644 index 0000000000..3cb70cea5d --- /dev/null +++ b/Task/Test-a-function/Zkl/test-a-function-2.zkl @@ -0,0 +1,3 @@ +tester:=TheVault.Test.UnitTester.UnitTester(__FILE__); + // spaces make this not a palindrome +tester.testRun(pali.fp("red rum sir is murder"), Void,False,__LINE__); diff --git a/Task/Test-a-function/Zkl/test-a-function-3.zkl b/Task/Test-a-function/Zkl/test-a-function-3.zkl new file mode 100644 index 0000000000..d24d8bed58 --- /dev/null +++ b/Task/Test-a-function/Zkl/test-a-function-3.zkl @@ -0,0 +1,11 @@ +tester:=TheVault.Test.UnitTester.UnitTester(__FILE__); +fcn pali(text){ + if (text.len()<2) return(False); + text==text.reverse(); +} +tester.testRun(pali.fp("red rum sir is murder" - " "), Void,True,__LINE__); +tester.testRun(pali.fp("red rum sir is murder"), Void,True,__LINE__); //bad test +tester.testSrc("var R=(1+2)",Void,Void,3,__LINE__); // you can test source too + +tester.stats(); +returnClass(tester); diff --git a/Task/Test-a-function/Zkl/test-a-function-4.zkl b/Task/Test-a-function/Zkl/test-a-function-4.zkl new file mode 100644 index 0000000000..4cea1ee20e --- /dev/null +++ b/Task/Test-a-function/Zkl/test-a-function-4.zkl @@ -0,0 +1 @@ +zkl paliTest.zkl diff --git a/Task/Test-a-function/Zkl/test-a-function-5.zkl b/Task/Test-a-function/Zkl/test-a-function-5.zkl new file mode 100644 index 0000000000..b9cb36e038 --- /dev/null +++ b/Task/Test-a-function/Zkl/test-a-function-5.zkl @@ -0,0 +1 @@ +zkl Test.testThemAll -- paliTest.zkl diff --git a/Task/Text-processing-1/jq/text-processing-1-1.jq b/Task/Text-processing-1/Jq/text-processing-1-1.jq similarity index 100% rename from Task/Text-processing-1/jq/text-processing-1-1.jq rename to Task/Text-processing-1/Jq/text-processing-1-1.jq diff --git a/Task/Text-processing-1/jq/text-processing-1-2.jq b/Task/Text-processing-1/Jq/text-processing-1-2.jq similarity index 100% rename from Task/Text-processing-1/jq/text-processing-1-2.jq rename to Task/Text-processing-1/Jq/text-processing-1-2.jq diff --git a/Task/Text-processing-1/jq/text-processing-1-3.jq b/Task/Text-processing-1/Jq/text-processing-1-3.jq similarity index 100% rename from Task/Text-processing-1/jq/text-processing-1-3.jq rename to Task/Text-processing-1/Jq/text-processing-1-3.jq diff --git a/Task/Text-processing-1/jq/text-processing-1-4.jq b/Task/Text-processing-1/Jq/text-processing-1-4.jq similarity index 100% rename from Task/Text-processing-1/jq/text-processing-1-4.jq rename to Task/Text-processing-1/Jq/text-processing-1-4.jq diff --git a/Task/Text-processing-1/jq/text-processing-1-5.jq b/Task/Text-processing-1/Jq/text-processing-1-5.jq similarity index 100% rename from Task/Text-processing-1/jq/text-processing-1-5.jq rename to Task/Text-processing-1/Jq/text-processing-1-5.jq diff --git a/Task/Text-processing-2/C/text-processing-2-1.c b/Task/Text-processing-2/C/text-processing-2-1.c deleted file mode 100644 index d01d5f98e8..0000000000 --- a/Task/Text-processing-2/C/text-processing-2-1.c +++ /dev/null @@ -1,84 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -typedef struct { const char *s; int ln, bad; } rec_t; -int cmp_rec(const void *aa, const void *bb) -{ - const rec_t *a = aa, *b = bb; - return a->s == b->s ? 0 : !a->s ? 1 : !b->s ? -1 : strncmp(a->s, b->s, 10); -} - -int read_file(const char *fn) -{ - int fd = open(fn, O_RDONLY); - if (fd == -1) return 0; - - struct stat s; - fstat(fd, &s); - - char *txt = malloc(s.st_size); - read(fd, txt, s.st_size); - close(fd); - - int i, j, lines = 0, k, di, bad; - for (i = lines = 0; i < s.st_size; i++) - if (txt[i] == '\n') { - txt[i] = '\0'; - lines++; - } - - rec_t *rec = calloc(sizeof(rec_t), lines); - const char *ptr, *end; - rec[0].s = txt; - rec[0].ln = 1; - for (i = 0; i < lines; i++) { - if (i + 1 < lines) { - rec[i + 1].s = rec[i].s + strlen(rec[i].s) + 1; - rec[i + 1].ln = i + 2; - } - if (sscanf(rec[i].s, "%4d-%2d-%2d", &di, &di, &di) != 3) { - printf("bad line %d: %s\n", i, rec[i].s); - rec[i].s = 0; - continue; - } - ptr = rec[i].s + 10; - - for (j = k = 0; j < 25; j++) { - if (!strtod(ptr, (char**)&end) && end == ptr) break; - k++, ptr = end; - if (!(di = strtol(ptr, (char**)&end, 10)) && end == ptr) break; - k++, ptr = end; - if (di < 1) rec[i].bad = 1; - } - - if (k != 48) { - printf("bad format at line %d: %s\n", i, rec[i].s); - rec[i].s = 0; - } - } - - qsort(rec, lines, sizeof(rec_t), cmp_rec); - for (i = 1, bad = rec[0].bad, j = 0; i < lines && rec[i].s; i++) { - if (rec[i].bad) bad++; - if (strncmp(rec[i].s, rec[j].s, 10)) { - j = i; - } else - printf("dup line %d: %.10s\n", rec[i].ln, rec[i].s); - } - - free(rec); - free(txt); - printf("\n%d out %d lines good\n", lines - bad, lines); - return 0; -} - -int main() -{ - read_file("readings.txt"); - return 0; -} diff --git a/Task/Text-processing-2/C/text-processing-2-2.c b/Task/Text-processing-2/C/text-processing-2-2.c deleted file mode 100644 index 76da1176b6..0000000000 --- a/Task/Text-processing-2/C/text-processing-2-2.c +++ /dev/null @@ -1,7 +0,0 @@ -dup line 85: 1990-03-25 -dup line 456: 1991-03-31 -dup line 820: 1992-03-29 -dup line 1184: 1993-03-28 -dup line 1911: 1995-03-26 - -5017 out 5471 lines good diff --git a/Task/Text-processing-2/jq/text-processing-2-1.jq b/Task/Text-processing-2/Jq/text-processing-2-1.jq similarity index 100% rename from Task/Text-processing-2/jq/text-processing-2-1.jq rename to Task/Text-processing-2/Jq/text-processing-2-1.jq diff --git a/Task/Text-processing-2/jq/text-processing-2-2.jq b/Task/Text-processing-2/Jq/text-processing-2-2.jq similarity index 100% rename from Task/Text-processing-2/jq/text-processing-2-2.jq rename to Task/Text-processing-2/Jq/text-processing-2-2.jq diff --git a/Task/Text-processing-2/jq/text-processing-2-3.jq b/Task/Text-processing-2/Jq/text-processing-2-3.jq similarity index 100% rename from Task/Text-processing-2/jq/text-processing-2-3.jq rename to Task/Text-processing-2/Jq/text-processing-2-3.jq diff --git a/Task/Text-processing-2/jq/text-processing-2-4.jq b/Task/Text-processing-2/Jq/text-processing-2-4.jq similarity index 100% rename from Task/Text-processing-2/jq/text-processing-2-4.jq rename to Task/Text-processing-2/Jq/text-processing-2-4.jq diff --git a/Task/Text-processing-2/jq/text-processing-2-5.jq b/Task/Text-processing-2/Jq/text-processing-2-5.jq similarity index 100% rename from Task/Text-processing-2/jq/text-processing-2-5.jq rename to Task/Text-processing-2/Jq/text-processing-2-5.jq diff --git a/Task/Text-processing-2/jq/text-processing-2-6.jq b/Task/Text-processing-2/Jq/text-processing-2-6.jq similarity index 100% rename from Task/Text-processing-2/jq/text-processing-2-6.jq rename to Task/Text-processing-2/Jq/text-processing-2-6.jq diff --git a/Task/Text-processing-2/jq/text-processing-2-7.jq b/Task/Text-processing-2/Jq/text-processing-2-7.jq similarity index 100% rename from Task/Text-processing-2/jq/text-processing-2-7.jq rename to Task/Text-processing-2/Jq/text-processing-2-7.jq diff --git a/Task/Text-processing-2/jq/text-processing-2-8.jq b/Task/Text-processing-2/Jq/text-processing-2-8.jq similarity index 100% rename from Task/Text-processing-2/jq/text-processing-2-8.jq rename to Task/Text-processing-2/Jq/text-processing-2-8.jq diff --git a/Task/Text-processing-2/Zkl/text-processing-2.zkl b/Task/Text-processing-2/Zkl/text-processing-2.zkl new file mode 100644 index 0000000000..63646a6971 --- /dev/null +++ b/Task/Text-processing-2/Zkl/text-processing-2.zkl @@ -0,0 +1,19 @@ + // the RegExp engine has a low limit on groups so + // I can't use it to select all fields, only verify them +re:=RegExp(0'|^(\d+-\d+-\d+)| + 0'|\s+\d+\.\d+\s+-*\d+| * 24 + ".+$"); +w:=[1..].zip(File("readings.txt")); //-->lazy (line #,line) +reg datep,N, good=0, dd=0; +foreach n,line in (w){ + N=n; // since n is local to this scope + if (not re.search(line)){ println("Line %d: malformed".fmt(n)); continue; } + date:=line[re.matchedNs[1].xplode()]; // I can group the date field + if (datep==date){ dd+=1; println("Line %4d: dup date: %s".fmt(n,date)); } + datep=date; + if (line.replace("\t"," ").split(" ").filter()[1,*] // blow fields apart, drop date + .pump(Void,Void.Read, // get (reading,status) + fcn(_,s){ // stop on first problem status and return True + if(s.strip().toInt()<1) T(Void.Stop,True) else False + })) continue; + good+=1; +} +println("%d records read, %d duplicate dates, %d valid".fmt(N,dd,good)); diff --git a/Task/Text-processing-Max-licenses-in-use/Clojure/text-processing-max-licenses-in-use.clj b/Task/Text-processing-Max-licenses-in-use/Clojure/text-processing-max-licenses-in-use.clj new file mode 100644 index 0000000000..308f35f80e --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Clojure/text-processing-max-licenses-in-use.clj @@ -0,0 +1,16 @@ +(defn delta [entry] + (case (second (re-find #"\ (.*)\ @" entry)) + "IN " -1 + "OUT" 1 + (throw (Exception. (str "Invalid entry:" entry))))) + +(defn t [entry] + (second (re-find #"@\ (.*)\ f" entry))) + +(let [entries (clojure.string/split (slurp "mlijobs.txt") #"\n") + in-use (reductions + (map delta entries)) + m (apply max in-use) + times (map #(nth (map t entries) %) + (keep-indexed #(when (= m %2) %1) in-use))] + (println "Maximum simultaneous license use is" m "at the following times:") + (map println times)) diff --git a/Task/Text-processing-Max-licenses-in-use/jq/text-processing-max-licenses-in-use.jq b/Task/Text-processing-Max-licenses-in-use/Jq/text-processing-max-licenses-in-use.jq similarity index 100% rename from Task/Text-processing-Max-licenses-in-use/jq/text-processing-max-licenses-in-use.jq rename to Task/Text-processing-Max-licenses-in-use/Jq/text-processing-max-licenses-in-use.jq diff --git a/Task/Text-processing-Max-licenses-in-use/Zkl/text-processing-max-licenses-in-use.zkl b/Task/Text-processing-Max-licenses-in-use/Zkl/text-processing-max-licenses-in-use.zkl new file mode 100644 index 0000000000..041e9f0849 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Zkl/text-processing-max-licenses-in-use.zkl @@ -0,0 +1,9 @@ +nOut,maxOut,maxTimes:=0,-1,List(); +foreach job in (File("mlijobs.txt")){ + _,status,_,date:=job.split(); + nOut+=( if(status.toUpper()=="OUT") 1 else -1 ); + if(nOut>maxOut){ maxOut=nOut; maxTimes.clear(); } + if(nOut==maxOut) maxTimes.append(date); +} +println(("Maximum simultaneous license use is %d at" + " the following times:\n %s").fmt(maxOut,maxTimes.concat("\n"))); diff --git a/Task/Textonyms/jq/textonyms-1.jq b/Task/Textonyms/Jq/textonyms-1.jq similarity index 100% rename from Task/Textonyms/jq/textonyms-1.jq rename to Task/Textonyms/Jq/textonyms-1.jq diff --git a/Task/Textonyms/jq/textonyms-2.jq b/Task/Textonyms/Jq/textonyms-2.jq similarity index 100% rename from Task/Textonyms/jq/textonyms-2.jq rename to Task/Textonyms/Jq/textonyms-2.jq diff --git a/Task/Textonyms/Kotlin/textonyms.kotlin b/Task/Textonyms/Kotlin/textonyms.kotlin new file mode 100644 index 0000000000..15027c1faa --- /dev/null +++ b/Task/Textonyms/Kotlin/textonyms.kotlin @@ -0,0 +1,63 @@ +// version 1.1.4-3 + +import java.io.File + +val wordList = "unixdict.txt" +val url = "http://www.puzzlers.org/pub/wordlists/unixdict.txt" + +const val DIGITS = "22233344455566677778889999" + +val map = mutableMapOf>() + +fun processList() { + var countValid = 0 + val f = File(wordList) + val sb = StringBuilder() + + f.forEachLine { word-> + var valid = true + sb.setLength(0) + for (c in word.toLowerCase()) { + if (c !in 'a'..'z') { + valid = false + break + } + sb.append(DIGITS[c - 'a']) + } + if (valid) { + countValid++ + val key = sb.toString() + if (map.containsKey(key)) { + map[key]!!.add(word) + } + else { + map.put(key, mutableListOf(word)) + } + } + } + var textonyms = map.filter { it.value.size > 1 }.toList() + val report = "There are $countValid words in '$url' " + + "which can be represented by the digit key mapping.\n" + + "They require ${map.size} digit combinations to represent them.\n" + + "${textonyms.size} digit combinations represent Textonyms.\n" + println(report) + + val longest = textonyms.sortedByDescending { it.first.length } + val ambiguous = longest.sortedByDescending { it.second.size } + + println("Top 8 in ambiguity:\n") + println("Count Textonym Words") + println("====== ======== =====") + var fmt = "%4d %-8s %s" + for (a in ambiguous.take(8)) println(fmt.format(a.second.size, a.first, a.second)) + + fmt = fmt.replace("8", "14") + println("\nTop 6 in length:\n") + println("Length Textonym Words") + println("====== ============== =====") + for (l in longest.take(6)) println(fmt.format(l.first.length, l.first, l.second)) +} + +fun main(args: Array) { + processList() +} diff --git a/Task/Textonyms/Phix/textonyms.phix b/Task/Textonyms/Phix/textonyms.phix new file mode 100644 index 0000000000..18aaccc396 --- /dev/null +++ b/Task/Textonyms/Phix/textonyms.phix @@ -0,0 +1,63 @@ +sequence digit = repeat(-1,255) + digit['a'..'c'] = '2' + digit['d'..'f'] = '3' + digit['g'..'i'] = '4' + digit['j'..'l'] = '5' + digit['m'..'o'] = '6' + digit['p'..'s'] = '7' + digit['t'..'v'] = '8' + digit['w'..'z'] = '9' + +function digits(string word) + for i=1 to length(word) do + integer ch = word[i] + if ch<'a' or ch>'z' then return "" end if + word[i] = digit[ch] + end for + return word +end function + +sequence words = {}, last="" +object word, keycode +integer keycode_count = 0, textonyms = 0, + this_count = 0, max_count = 0, max_idx + +integer fn = open("demo\\unixdict.txt","r") +while 1 do + word = trim(gets(fn)) + if atom(word) then exit end if + keycode = digits(word) + if length(keycode) then + words = append(words, {keycode, word}) + end if +end while +close(fn) +printf(1,"There are %d words in unixdict.txt which can be represented by the digit key mapping.\n",{length(words)}) + +words = sort(words) +for i=1 to length(words) do + {keycode,word} = words[i] + if keycode=last then + textonyms += this_count=1 + this_count += 1 + if this_count>max_count then + max_count = this_count + max_idx = i + end if + else + keycode_count += 1 + last = keycode + this_count = 1 + end if +end for + +printf(1,"They require %d digit combinations to represent them.\n",{keycode_count}) +printf(1,"%d digit combinations represent Textonyms.\n",{textonyms}) + +sequence dups = {} +for i=max_idx-max_count+1 to max_idx do + dups = append(dups,words[i][2]) +end for + +printf(1,"The maximum number of textonyms for a particular digit key mapping is %d:\n",{max_count}) +printf(1," %s encodes %s\n",{words[max_idx][1],join(dups,"/")}) diff --git a/Task/Textonyms/Zkl/textonyms.zkl b/Task/Textonyms/Zkl/textonyms.zkl new file mode 100644 index 0000000000..2df91e40fb --- /dev/null +++ b/Task/Textonyms/Zkl/textonyms.zkl @@ -0,0 +1,30 @@ +URL:="http://www.puzzlers.org/pub/wordlists/unixdict.txt"; +var ZC=Import("zklCurl"); +var keypad=Dictionary( + "a",2,"b",2,"c",2, "d",3,"e",3,"f",3, "g",4,"h",4,"i",4, + "j",5,"k",5,"l",5, "m",6,"n",6,"o",6, "p",7,"q",7,"r",7,"s",7, + "t",8,"u",8,"v",8, "w",9,"x",9,"y",9,"z",9); +//fcn numerate(word){ word.toLower().apply(keypad.find.fp1("")) } +fcn numerate(word){ word.toLower().apply(keypad.get) } //-->textonym or error +println("criticisms --> ",numerate("criticisms")); + +words:=ZC().get(URL); //--> T(Data,bytes of header, bytes of trailer) +words=words[0].del(0,words[1]); // remove HTTP header +println("Read %d words from %s".fmt(words.len(1),URL)); + +wcnt:=Dictionary(); +foreach word in (words.walker(11)){ // iterate over stripped lines + w2n:=try{ numerate(word) }catch(NotFoundError){ continue }; + wcnt.appendV(w2n,word); // -->[textonym:list of words] +} + +moreThan1Word:=wcnt.reduce(fcn(s,[(k,v)]){ s+=(v.len()>1) },0); +maxWordPerNum:=(0).max(wcnt.values.apply("len")); + +("There are %d words which can be represented by the Textonyms mapping.\n" +"There are %d overlaps.").fmt(wcnt.len(),moreThan1Word).println(); + +println("Max collisions: %d words:".fmt(maxWordPerNum)); +foreach k,v in (wcnt.filter('wrap([(k,v)]){ v.len()==maxWordPerNum })){ + println(" %s is the textonym of: %s".fmt(k,v.concat(", "))); +} diff --git a/Task/The-ISAAC-Cipher/Kotlin/the-isaac-cipher.kotlin b/Task/The-ISAAC-Cipher/Kotlin/the-isaac-cipher.kotlin new file mode 100644 index 0000000000..91fc2297f5 --- /dev/null +++ b/Task/The-ISAAC-Cipher/Kotlin/the-isaac-cipher.kotlin @@ -0,0 +1,163 @@ +// version 1.1.3 + +/* external results */ +val randrsl = IntArray(256) +var randcnt = 0 + +/* internal state */ +val mm = IntArray(256) +var aa = 0 +var bb = 0 +var cc = 0 + +const val GOLDEN_RATIO = 0x9e3779b9.toInt() + +fun isaac() { + cc++ // cc just gets incremented once per 256 results + bb += cc // then combined with bb + for (i in 0..255) { + val x = mm[i] + when (i % 4) { + 0 -> aa = aa xor (aa shl 13) + 1 -> aa = aa xor (aa ushr 6) + 2 -> aa = aa xor (aa shl 2) + 3 -> aa = aa xor (aa ushr 16) + } + aa += mm[(i + 128) % 256] + val y = mm[(x ushr 2) % 256] + aa + bb + mm[i] = y + bb = mm[(y ushr 10) % 256] + x + randrsl[i] = bb + } + randcnt = 0 +} + +/* if (flag == true), then use the contents of randrsl to initialize mm. */ +fun mix(n: IntArray) { + n[0] = n[0] xor (n[1] shl 11); n[3] += n[0]; n[1] += n[2] + n[1] = n[1] xor (n[2] ushr 2); n[4] += n[1]; n[2] += n[3] + n[2] = n[2] xor (n[3] shl 8); n[5] += n[2]; n[3] += n[4] + n[3] = n[3] xor (n[4] ushr 16); n[6] += n[3]; n[4] += n[5] + n[4] = n[4] xor (n[5] shl 10); n[7] += n[4]; n[5] += n[6] + n[5] = n[5] xor (n[6] ushr 4); n[0] += n[5]; n[6] += n[7] + n[6] = n[6] xor (n[7] shl 8); n[1] += n[6]; n[7] += n[0] + n[7] = n[7] xor (n[0] ushr 9); n[2] += n[7]; n[0] += n[1] +} + +fun randinit(flag: Boolean) { + aa = 0 + bb = 0 + cc = 0 + val n = IntArray(8) { GOLDEN_RATIO } + for (i in 0..3) mix(n) // scramble the array + + for (i in 0..255 step 8) { // fill in mm with messy stuff + if (flag) { // use all the information in the seed + for (j in 0..7) n[j] += randrsl[i + j] + } + mix(n) + for (j in 0..7) mm[i + j] = n[j] + } + + if (flag) { + /* do a second pass to make all of the seed affect all of mm */ + for (i in 0..255 step 8) { + for (j in 0..7) n[j] += mm[i + j] + mix(n) + for (j in 0..7) mm[i + j] = n[j] + } + } + + isaac() // fill in the first set of results + randcnt = 0 // prepare to use the first set of results +} + +/* As Kotlin doesn't (yet) support unsigned types, we need to use + Long here to get a random value in the range of a UInt */ +fun iRandom(): Long { + val r = randrsl[randcnt++] + if (randcnt > 255) { + isaac() + randcnt = 0 + } + return r.toLong() and 0xFFFFFFFFL +} + +/* Get a random character (as Int) in printable ASCII range */ +fun iRandA() = (iRandom() % 95 + 32).toInt() + +/* Seed ISAAC with a string */ +fun iSeed(seed: String, flag: Boolean) { + for (i in 0..255) mm[i] = 0 + val m = seed.length + for (i in 0..255) { + /* in case seed has less than 256 elements */ + randrsl[i] = if (i >= m) 0 else seed[i].toInt() + } + /* initialize ISAAC with seed */ + randinit(flag) +} + +/* XOR cipher on random stream. Output: ASCII string */ +fun vernam(msg: String) : String { + val len = msg.length + val v = ByteArray(len) + for (i in 0 until len) { + v[i] = (iRandA() xor msg[i].toInt()).toByte() + } + return v.toString(charset("ASCII")) +} + +/* constants for Caesar */ +const val MOD = 95 +const val START = 32 + +/* cipher modes for Caesar */ +enum class CipherMode { + ENCIPHER, DECIPHER, NONE +} + +/* Caesar-shift a printable character */ +fun caesar(m: CipherMode, ch: Int, shift: Int, modulo: Int, start: Int): Char { + val sh = if (m == CipherMode.DECIPHER) -shift else shift + var n = (ch - start) + sh + n %= modulo + if (n < 0) n += modulo + return (start + n).toChar() +} + +/* Caesar-shift a string on a pseudo-random stream */ +fun caesarStr(m: CipherMode, msg: String, modulo: Int, start: Int): String { + val sb = StringBuilder(msg.length) + /* Caesar-shift message */ + for (c in msg) { + sb.append(caesar(m, c.toInt(), iRandA(), modulo, start)) + } + return sb.toString() +} + +fun String.toHexByteString() = + this.map { "%02X".format(it.toInt()) }.joinToString("") + +fun main(args: Array) { + val msg = "a Top Secret secret" + val key = "this is my secret key" + + // Vernam & Caesar ciphertext + iSeed(key, true) + val vctx = vernam(msg) + val cctx = caesarStr(CipherMode.ENCIPHER, msg, MOD, START) + + // Vernam & Caesar plaintext + iSeed(key, true) + val vptx = vernam(vctx) + val cptx = caesarStr(CipherMode.DECIPHER, cctx, MOD, START) + + // Program output + println("Message : $msg") + println("Key : $key") + println("XOR : ${vctx.toHexByteString()}") + println("XOR dcr : $vptx") + println("MOD : ${cctx.toHexByteString()}") + println("MOD dcr : $cptx") +} diff --git a/Task/The-ISAAC-Cipher/Sidef/the-isaac-cipher.sidef b/Task/The-ISAAC-Cipher/Sidef/the-isaac-cipher.sidef index 51ce1f0ce3..f49ebcbae6 100644 --- a/Task/The-ISAAC-Cipher/Sidef/the-isaac-cipher.sidef +++ b/Task/The-ISAAC-Cipher/Sidef/the-isaac-cipher.sidef @@ -1,20 +1,20 @@ -require('Math::Random::ISAAC'); +require('Math::Random::ISAAC') func xor_isaac(key, msg) { - var rng = %s.new(unpack('C*', key)); + var rng = %O.new(unpack('C*', key)) - msg.chars»ord»() \ - -> »^« 256.of{ rng.irand % 95 + 32 }.last(msg.len).reverse \ - -> «%« '%02X' -> join; + msg.chars»ord()» \ + -> »^« 256.of{ rng.irand % 95 + 32 }.last(msg.len).flip \ + -> «%« '%02X' -> join } -var msg = 'a Top Secret secret'; -var key = 'this is my secret key'; +var msg = 'a Top Secret secret' +var key = 'this is my secret key' -var enc = xor_isaac(key, msg); -var dec = xor_isaac(key, pack('H*', enc)); +var enc = xor_isaac(key, msg) +var dec = xor_isaac(key, pack('H*', enc)) -say "Message: #{msg}"; -say "Key : #{key}"; -say "XOR : #{enc}"; -say "XOR dcr: #{pack('H*', dec)}"; +say "Message: #{msg}" +say "Key : #{key}" +say "XOR : #{enc}" +say "XOR dcr: #{pack('H*', dec)}" diff --git a/Task/The-Twelve-Days-of-Christmas/AppleScript/the-twelve-days-of-christmas-2.applescript b/Task/The-Twelve-Days-of-Christmas/AppleScript/the-twelve-days-of-christmas-2.applescript index 882ee21957..335e94d84d 100644 --- a/Task/The-Twelve-Days-of-Christmas/AppleScript/the-twelve-days-of-christmas-2.applescript +++ b/Task/The-Twelve-Days-of-Christmas/AppleScript/the-twelve-days-of-christmas-2.applescript @@ -8,13 +8,16 @@ property pstrGifts : "A partridge in a pear tree, Two turtle doves, Three French property pstrOrdinals : "first, second, third, fourth, fifth, " & ¬ "sixth, seventh, eighth, ninth, tenth, eleventh, twelfth" +-- DAYS OF XMAS ------------------------------------------------------------ + +-- daysOfXmas :: () -> String on daysOfXmas() -- csv :: String -> [String] script csv - on lambda(str) + on |λ|(str) splitOn(", ", str) - end lambda + end |λ| end script set {gifts, ordinals} to map(csv, [pstrGifts, pstrOrdinals]) @@ -24,37 +27,37 @@ on daysOfXmas() -- dayGift :: Int -> String script dayGift - on lambda(n, i) + on |λ|(n, i) set strGift to item n of gifts if n = 1 then set strFirst to strGift & " !" if i is not 1 then - "And " & toLowerCase(text 1 of strFirst) & text 2 thru -1 of strFirst + "And " & toLower(text 1 of strFirst) & text 2 thru -1 of strFirst else strFirst end if else if n = 5 then - toUpperCase(strGift) + toUpper(strGift) else strGift end if - end lambda + end |λ| end script - on lambda(intDay) + on |λ|(intDay) "On the " & item intDay of ordinals & " day of Xmas, my true love gave to me ..." & ¬ linefeed & intercalate("," & linefeed, ¬ - map(dayGift, range(intDay, 1))) + map(dayGift, enumFromTo(intDay, 1))) - end lambda + end |λ| end script intercalate(linefeed & linefeed, ¬ - map(verseOfTheDay, range(1, length of ordinals))) + map(verseOfTheDay, enumFromTo(1, length of ordinals))) end daysOfXmas --- TEST +-- TEST --------------------------------------------------------------------- on run daysOfXmas() @@ -62,27 +65,21 @@ on run end run --- GENERIC FUNCTIONS +-- GENERIC FUNCTIONS -------------------------------------------------------- --- splitOn :: Text -> Text -> [Text] -on splitOn(strDelim, strMain) - set {dlm, my text item delimiters} to {my text item delimiters, strDelim} - set lstParts to text items of strMain - set my text item delimiters to dlm - return lstParts -end splitOn - --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) @@ -92,30 +89,17 @@ on intercalate(strText, lstText) return strJoined end intercalate --- range :: Int -> Int -> [Int] -on range(m, n) - set d to 1 - if n < m then set d to -1 - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range - --- Text -> Text -on toLowerCase(str) - set ca to current application - ((ca's NSString's stringWithString:(str))'s ¬ - lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text -end toLowerCase - --- Text -> Text -on toUpperCase(str) - set ca to current application - ((ca's NSString's stringWithString:(str))'s ¬ - uppercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text -end toUpperCase +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -124,7 +108,29 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn + +-- splitOn :: Text -> Text -> [Text] +on splitOn(strDelim, strMain) + set {dlm, my text item delimiters} to {my text item delimiters, strDelim} + set lstParts to text items of strMain + set my text item delimiters to dlm + return lstParts +end splitOn + +-- toLower :: String -> String +on toLower(str) + set ca to current application + ((ca's NSString's stringWithString:(str))'s ¬ + lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text +end toLower + +-- toUpper :: String -> String +on toUpper(str) + set ca to current application + ((ca's NSString's stringWithString:(str))'s ¬ + uppercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text +end toUpper diff --git a/Task/The-Twelve-Days-of-Christmas/Batch-File/the-twelve-days-of-christmas.bat b/Task/The-Twelve-Days-of-Christmas/Batch-File/the-twelve-days-of-christmas.bat new file mode 100644 index 0000000000..ed14adfa0e --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Batch-File/the-twelve-days-of-christmas.bat @@ -0,0 +1,50 @@ +:: The Twelve Days of Christmas +:: Batch File Implementation + +@echo off + +::Pseudo-array for Days +set "day1=First" +set "day2=Second" +set "day3=Third" +set "day4=Fourth" +set "day5=Fifth" +set "day6=Sixth" +set "day7=Seventh" +set "day8=Eighth" +set "day9=Nineth" +set "day10=Tenth" +set "day11=Eleventh" +set "day12=Twelveth" + +::Pseudo-array for Gifts +set "gift12=Twelve drummers drumming" +set "gift11=Eleven pipers piping" +set "gift10=Ten loards a-leaping" +set "gift9=Nine ladies dancing" +set "gift8=Eight maids a-milking" +set "gift7=Seven swans a-swimming" +set "gift6=Six geese a-laying" +set "gift5=Five golden rings" +set "gift4=Four calling birds" +set "gift3=Three french hens" +set "gift2=Two turtle doves" +set "gift1=A partridge in a pear tree" + +::Display It! +setlocal enabledelayedexpansion +for /l %%i in (1,1,12) do ( + echo On the !day%%i! day of Christmas + echo My true love gave to me: + + for /l %%j in (%%i,-1,1) do ( + if %%j equ 1 ( + if %%i neq 1 =0;j--) - { - (i==0)?printf("\nA partridge in a pear tree."):printf("\n%s%c",gifts[11-j],(j!=0)?',':' '); - } - } - - return 0; + { + "Twelve drummers drumming", + "Eleven pipers piping", + "Ten lords a-leaping", + "Nine ladies dancing", + "Eight maids a-milking", + "Seven swans a-swimming", + "Six geese a-laying", + "Five golden rings", + "Four calling birds", + "Three french hens", + "Two turtle doves", + "And a partridge in a pear tree." + }; + + for(i=0;i<12;i++) + { + printf("\n\nOn the %s day of Christmas\nMy true love gave to me:",days[i]); + + for(j=i;j>=0;j--) + { + (i==0)?printf("\nA partridge in a pear tree."):printf("\n%s%c",gifts[11-j],(j!=0)?',':' '); + } + } + + return 0; } diff --git a/Task/The-Twelve-Days-of-Christmas/Dc/the-twelve-days-of-christmas.dc b/Task/The-Twelve-Days-of-Christmas/Dc/the-twelve-days-of-christmas.dc new file mode 100644 index 0000000000..a3313f9935 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Dc/the-twelve-days-of-christmas.dc @@ -0,0 +1,66 @@ +0 + +d [first] r :n +d [A partridge in a pear tree.] r :g 1 + + +d [second] r :n +d [Two turtle doves and] r :g 1 + + +d [third] r :n +d [Three French hens,] r :g 1 + + +d [fourth] r :n +d [Four calling birds,] r :g 1 + + +d [fifth] r :n +d [Five gold rings,] r :g 1 + + +d [sixth] r :n +d [Six geese a-laying,] r :g 1 + + +d [seventh] r :n +d [Seven swans a-swimming,] r :g 1 + + +d [eighth] r :n +d [Eight maids a-milking,] r :g 1 + + +d [ninth] r :n +d [Nine ladies dancing,] r :g 1 + + +d [tenth] r :n +d [Ten lords a-leaping,] r :g 1 + + +d [eleventh] r :n +d [Eleven pipers piping,] r :g 1 + + +d [twelfth] r :n + [Twelve drummers drumming,] r :g + +[ + d + ;g n + 10 P +] sp + +[ + d + 0 r !

    1 Then + Print gifts(2); iif(d = 12, "", " and") + End If ' print "A partridge...", on the twelfth day print "And a partrige..." Print " A" & IIf(d = 12, "nd a", "" ) & " partridge in a pear tree" Print diff --git a/Task/The-Twelve-Days-of-Christmas/Go/the-twelve-days-of-christmas.go b/Task/The-Twelve-Days-of-Christmas/Go/the-twelve-days-of-christmas.go index 847d87c44c..f11f846b3c 100644 --- a/Task/The-Twelve-Days-of-Christmas/Go/the-twelve-days-of-christmas.go +++ b/Task/The-Twelve-Days-of-Christmas/Go/the-twelve-days-of-christmas.go @@ -2,32 +2,24 @@ package main import ( "fmt" - "strings" ) func main() { - numbers := []string{"first", "second", "third", "fourth", "fifth", - "sixth", "seventh", "eighth", "ninth", "tenth", - "eleventh", "twelfth"} + days := []string{"first", "second", "third", "fourth", "fifth", "sixth", + "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"} - gifts := []string{"And a partridge in a pear tree", "Two turtle doves", - "Three French hens", "Four calling birds", - "Five gold rings", "Six geese a-laying", - "Seven swans a-swimming", "Eight maids a-miling", - "Nine ladies dancing", "Ten lords a-leaping", - "Eleven pipers piping", "Twelve drummers drumming"} + gifts := []string{"A Patridge in a Pear Tree", "Two Turtle Doves and", "Three French Hens", + "Four Calling Birds", "Five Golden Rings", "Six Geese a Laying", + "Seven Swans a Swimming", "Eight Maids a Milking", "Nine Ladies Dancing", + "Ten Lords a Leaping", "Eleven Pipers Piping", "Twelve Drummers Drumming"} - day := func(n int) { - fmt.Printf("On the %s day of Christams, my true love sent to me\n", numbers[n]) - } + for i := 0; i < 12; i++ { + fmt.Printf("On the %s day of Christmas,\n", days[i]) + fmt.Println("My true love gave to me:") - day(0) - fmt.Println(strings.Replace(gifts[0], "And a", "A", 1)) - for d := 1; d < 12; d++ { - fmt.Println() - day(d) - for g := d; g >= 0; g-- { - fmt.Println(gifts[g]) + for j := i; j >= 0; j-- { + fmt.Println(gifts[j]) } + fmt.Println() } } diff --git a/Task/The-Twelve-Days-of-Christmas/Julia/the-twelve-days-of-christmas.julia b/Task/The-Twelve-Days-of-Christmas/Julia/the-twelve-days-of-christmas.julia new file mode 100644 index 0000000000..01294d8769 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Julia/the-twelve-days-of-christmas.julia @@ -0,0 +1,33 @@ +# v0.6.0 + +function printlyrics() + const gifts = split(""" + A partridge in a pear tree. + Two turtle doves + Three french hens + Four calling birds + Five golden rings + Six geese a-laying + Seven swans a-swimming + Eight maids a-milking + Nine ladies dancing + Ten lords a-leaping + Eleven pipers piping + Twelve drummers drumming + """, '\n') + const days = split(""" + first second third fourth fifth + sixth seventh eighth ninth tenth + eleventh twelfth""") + for (n, day) in enumerate(days) + g = gifts[n:-1:1] + print("\nOn the $day day of Christmas\nMy true love gave to me:\n") + if n == 1 + print(join(g[1:end], '\n'), '\n') + else + print(join(g[1:end-1], '\n'), " and\n", g[end], '\n') + end + end +end + +printlyrics() diff --git a/Task/The-Twelve-Days-of-Christmas/Phix/the-twelve-days-of-christmas.phix b/Task/The-Twelve-Days-of-Christmas/Phix/the-twelve-days-of-christmas.phix new file mode 100644 index 0000000000..5be3211994 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Phix/the-twelve-days-of-christmas.phix @@ -0,0 +1,20 @@ +constant days = {"first", "second", "third", "fourth", "fifth", "sixth", + "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"}, + gifts = {"A partridge in a pear tree.\n", + "Two turtle doves, and\n", + "Three French hens,\n", + "Four calling birds,\n", + "Five gold rings,\n", + "Six geese a-laying,\n", + "Seven swans a-swimming,\n", + "Eight maids a-milking,\n", + "Nine ladies dancing,\n", + "Ten lords a-leaping,\n", + "Eleven pipers piping,\n", + "Twelve drummers drumming,\n"} +for i=1 to 12 do + printf(1,"On the %s day of Christmas,\nmy true love gave to me:\n",{days[i]}) + for j=i to 1 by -1 do + printf(1,gifts[j]) + end for +end for diff --git a/Task/The-Twelve-Days-of-Christmas/Rust/the-twelve-days-of-christmas.rust b/Task/The-Twelve-Days-of-Christmas/Rust/the-twelve-days-of-christmas.rust index eb2924da70..a592ef9fad 100644 --- a/Task/The-Twelve-Days-of-Christmas/Rust/the-twelve-days-of-christmas.rust +++ b/Task/The-Twelve-Days-of-Christmas/Rust/the-twelve-days-of-christmas.rust @@ -1,38 +1,27 @@ -fn showpresents(count : usize) { - let days = ["second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", - "tenth", "eleventh", "twelfth"]; - - let presents = ["Two turtle doves", - "Three french hens", - "Four calling birds", - "Five golden rings", - "Six geese a-laying", - "Seven swans a-swimming", - "Eight maids a-milking", - "Nine ladies dancing", - "Ten lords a-leaping", - "Eleven pipers piping", - "Twelve drummers drumming"]; - - println!("On the {} day of Christmas my true love gave to me {}", days[count-1], presents[count-1]); - if count > 0 { - let mut j = count-1; - while j > 0 { - println!("{}", presents[j-1]); - j -= 1; - - } - } - println!("And a partridge in a pear tree \n"); -} - fn main() { - let mut count = 0; - while count < 12 { - match count { - 0 => println!("On the first day of Christmas my true love gave to me a partridge in a pear tree"), - _ => showpresents(count) - }; - count += 1; + let days = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", + "ninth", "tenth", "eleventh", "twelfth"]; + + let gifts = ["A Patridge in a Pear Tree", + "Two Turtle Doves and", + "Three French Hens", + "Four Calling Birds", + "Five Golden Rings", + "Six Geese a Laying", + "Seven Swans a Swimming", + "Eight Maids a Milking", + "Nine Ladies Dancing", + "Ten Lords a Leaping", + "Eleven Pipers Piping", + "Twelve Drummers Drumming"]; + + for i in 0..12 { + println!("On the {} day of Christmas,", days[i]); + println!("My true love gave to me:"); + + for j in (0..i + 1).rev() { + println!("{}", gifts[j]); + } + println!() } } diff --git a/Task/The-Twelve-Days-of-Christmas/Smart-BASIC/the-twelve-days-of-christmas.smart b/Task/The-Twelve-Days-of-Christmas/Smart-BASIC/the-twelve-days-of-christmas.smart new file mode 100644 index 0000000000..70b839a406 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Smart-BASIC/the-twelve-days-of-christmas.smart @@ -0,0 +1,8 @@ +' by rbytes +dim d$(12),x$(15)!s=15 +for t=0 to 11!read d$(t)!next t +for t=0 to 14!read x$(t)!next t +for u=0 to 11!s-=1 +print x$(0)&d$(u)&x$(1)&chr$(10)&x$(2) +for t=s to 14!print x$(t)!next t +print!next u!data "first","second","third","fourth","fifth","sixth","seventh","eight","ninth","tenth","eleventh","Twelfth","On the "," day of Christmas","My true love gave to me:","Twelve drummers drumming","Eleven pipers piping","Ten lords a-leaping","Nine ladies dancing","Eight maids a-milking","Seven swans a-swimming,","Six geese a-laying","Five golden rings","Four calling birds","Three french hens","Two turtle doves and","A partridge in a pear tree." diff --git a/Task/The-Twelve-Days-of-Christmas/Zkl/the-twelve-days-of-christmas.zkl b/Task/The-Twelve-Days-of-Christmas/Zkl/the-twelve-days-of-christmas.zkl new file mode 100644 index 0000000000..3a620b4643 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Zkl/the-twelve-days-of-christmas.zkl @@ -0,0 +1,17 @@ +gifts:= +#<<< +"A beer, in a tree.; Two turtlenecks; Three french toast; +Four pounds of backbacon; Five golden touques; Six packs of two-four; +Seven packs of smokes; Eight comic books; Nine back up singers; +Ten feet of snow; Eleven hosers hosing; Twelve dozen donuts" +#<<< +.split(";").apply("strip"); + +days:=("first second third fourth fifth sixth seventh eighth ninth tenth " + "eleventh twelfth").split(); + +foreach n,day in (days.enumerate()){ n+=1; + g:=gifts[0,n].reverse(); + println("On the %s day of Christmas\nMy true love gave to me:\n".fmt(day), + g[0,-1].concat("\n"), (n>1) and " and\n" or "", g[-1], "\n"); +} diff --git a/Task/Thieles-interpolation-formula/Haskell/thieles-interpolation-formula.hs b/Task/Thieles-interpolation-formula/Haskell/thieles-interpolation-formula.hs index e589269c24..4bf6dd49d2 100644 --- a/Task/Thieles-interpolation-formula/Haskell/thieles-interpolation-formula.hs +++ b/Task/Thieles-interpolation-formula/Haskell/thieles-interpolation-formula.hs @@ -1,26 +1,32 @@ -thiele xs ys = f rho1 (tail xs) where - f _ [] _ = 1 - f r@(r0:r1:r2:rs) (x:xs) v = r2 - r0 + (v-x) / f (tail r) xs v +thiele :: [Double] -> [Double] -> Double -> Double +thiele xs ys = f rho1 (tail xs) + where + f _ [] _ = 1 + f r@(r0:r1:r2:rs) (x:xs) v = r2 - r0 + (v - x) / f (tail r) xs v + rho1 = ((!! 1) . (++ [0])) <$> rho + rho = [0,0 ..] : [0,0 ..] : ys : rnext (tail rho) xs (tail xs) + where + rnext _ _ [] = [] + rnext r@(r0:r1:rs) x xn = + let z_ = zipWith + in z_ (+) (tail r0) (z_ (/) (z_ (-) x xn) (z_ (-) r1 (tail r1))) : + rnext (tail r) x (tail xn) - rho1 = (map ((!!1).(++[0])) rho) +-- Inverted interpolation function of f +invInterp :: (Double -> Double) -> [Double] -> Double -> Double +invInterp f xs = thiele (map f xs) xs - rho = [0,0..] : [0,0..] : ys : rnext (tail rho) xs (tail xs) where - rnext _ _ [] = [] - rnext r@(r0:r1:rs) x xn = let z_ = zipWith in - (z_ (+) (tail r0) - (z_ (/) (z_ (-) x xn) - (z_ (-) r1 (tail r1)))) - : rnext (tail r) x (tail xn) - --- inverted interpolation function of f -inv_interp f xs = thiele (map f xs) xs - -main = do print $ 3.21 * inv_sin (sin (pi / 3.21)) - print $ pi/1.2345 * inv_cos (cos (1.2345)) - print $ 7 * inv_tan (tan (pi / 7)) - where - inv_sin = inv_interp sin $ div_pi 2 31 - inv_cos = inv_interp cos $ div_pi 2 100 - inv_tan = inv_interp tan $ div_pi 4 1000 -- because we can - -- uniformly take n points from 0 to Pi/d - div_pi d n = map (* (pi / (d * n))) [0..n] +main :: IO () +main = + mapM_ + print + [ 3.21 * inv_sin (sin (pi / 3.21)) + , pi / 1.2345 * inv_cos (cos 1.2345) + , 7 * inv_tan (tan (pi / 7)) + ] + where + [inv_sin, inv_cos, inv_tan] = + uncurry ((. div_pi) . invInterp) <$> + [(sin, (2, 31)), (cos, (2, 100)), (tan, (4, 1000))] + -- N points taken uniformly from 0 to Pi/d + div_pi (d, n) = (* (pi / (d * n))) <$> [0 .. n] diff --git a/Task/Thieles-interpolation-formula/Kotlin/thieles-interpolation-formula.kotlin b/Task/Thieles-interpolation-formula/Kotlin/thieles-interpolation-formula.kotlin new file mode 100644 index 0000000000..c8229d6d97 --- /dev/null +++ b/Task/Thieles-interpolation-formula/Kotlin/thieles-interpolation-formula.kotlin @@ -0,0 +1,43 @@ +// version 1.1.2 + +const val N = 32 +const val N2 = N * (N - 1) / 2 +const val STEP = 0.05 + +val xval = DoubleArray(N) +val tsin = DoubleArray(N) +val tcos = DoubleArray(N) +val ttan = DoubleArray(N) +val rsin = DoubleArray(N2) { Double.NaN } +val rcos = DoubleArray(N2) { Double.NaN } +val rtan = DoubleArray(N2) { Double.NaN } + +fun rho(x: DoubleArray, y: DoubleArray, r: DoubleArray, i: Int, n: Int): Double { + if (n < 0) return 0.0 + if (n == 0) return y[i] + val idx = (N - 1 - n) * (N - n) / 2 + i + if (r[idx].isNaN()) { + r[idx] = (x[i] - x[i + n]) / + (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) + + rho(x, y, r, i + 1, n - 2) + } + return r[idx] +} + +fun thiele(x: DoubleArray, y: DoubleArray, r: DoubleArray, xin: Double, n: Int): Double { + if (n > N - 1) return 1.0 + return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + + (xin - x[n]) / thiele(x, y, r, xin, n + 1) +} + +fun main(args: Array) { + for (i in 0 until N) { + xval[i] = i * STEP + tsin[i] = Math.sin(xval[i]) + tcos[i] = Math.cos(xval[i]) + ttan[i] = tsin[i] / tcos[i] + } + println("%16.14f".format(6 * thiele(tsin, xval, rsin, 0.5, 0))) + println("%16.14f".format(3 * thiele(tcos, xval, rcos, 0.5, 0))) + println("%16.14f".format(4 * thiele(ttan, xval, rtan, 1.0, 0))) +} diff --git a/Task/Thieles-interpolation-formula/Sidef/thieles-interpolation-formula.sidef b/Task/Thieles-interpolation-formula/Sidef/thieles-interpolation-formula.sidef index f722a8c764..6181a17243 100644 --- a/Task/Thieles-interpolation-formula/Sidef/thieles-interpolation-formula.sidef +++ b/Task/Thieles-interpolation-formula/Sidef/thieles-interpolation-formula.sidef @@ -1,38 +1,38 @@ func thiele(x, y) { - var ρ = y.range.map {|i| [y[i]]*(y.len-i) } - + var ρ = {|i| [y[i]]*(y.len-i) }.map(^y) +  for i in ^(ρ.end) { ρ[i][1] = ((x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])) } - for i in range(2, ρ.end) { - for j in range(0, ρ.end - i) { + for i (2 .. ρ.end) { + for j (0 .. ρ.end-i) { ρ[j][i] = (((x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1])) + ρ[j+1][i-2]) } } - +  var ρ0 = ρ[0] - +  func t(xin) { var a = 0 - for i in range(ρ0.end, 2, -1) { + for i (ρ0.len ^.. 2) { a = ((xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)) } y[0] + ((xin-x[0]) / (ρ0[1]+a)) } return t } - +  # task 1: build 32 row trig table -var xVal = range(32).map { |k| k * 0.05 } +var xVal = {|k| k * 0.05 }.map(^32) var tSin = xVal.map { .sin } var tCos = xVal.map { .cos } var tTan = xVal.map { .tan } - +  # task 2: define inverses var iSin = thiele(tSin, xVal) var iCos = thiele(tCos, xVal) var iTan = thiele(tTan, xVal) - +  # task 3: demonstrate identities say 6*iSin(0.5) say 3*iCos(0.5) diff --git a/Task/Thieles-interpolation-formula/Zkl/thieles-interpolation-formula.zkl b/Task/Thieles-interpolation-formula/Zkl/thieles-interpolation-formula.zkl new file mode 100644 index 0000000000..97d283d97d --- /dev/null +++ b/Task/Thieles-interpolation-formula/Zkl/thieles-interpolation-formula.zkl @@ -0,0 +1,40 @@ +const N=32, N2=(N * (N - 1) / 2), STEP=0.05; + +fcn rho(xs,ys,rs, i,n){ + if (n < 0) return(0.0); + if (not n) return(ys[i]); + + idx := (N - 1 - n) * (N - n) / 2 + i; + if (Void==rs[idx]) + rs[idx] = (xs[i] - xs[i + n]) + / (rho(xs, ys, rs, i, n - 1) - rho(xs, ys, rs, i + 1, n - 1)) + + rho(xs, ys, rs, i + 1, n - 2); + return(rs[idx]); +} + +fcn thiele(xs,ys,rs, xin, n){ + if (n > N - 1) return(1.0); + rho(xs, ys, rs, 0, n) - rho(xs, ys, rs, 0, n - 2) + + (xin - xs[n]) / thiele(xs, ys, rs, xin, n + 1); +} + +/////////// + +reg t_sin=L(), t_cos=L(), t_tan=L(), + r_sin=L(), r_cos=L(), r_tan=L(), xval=L(); + +i_sin := thiele.fpM("11101",t_sin, xval, r_sin, 0); +i_cos := thiele.fpM("11101",t_cos, xval, r_cos, 0); +i_tan := thiele.fpM("11101",t_tan, xval, r_tan, 0); + +foreach i in (N){ + xval.append(x:=STEP*i); + t_sin.append(x.sin()); + t_cos.append(x.cos()); + t_tan.append(t_sin[i] / t_cos[i]); +} +foreach i in (N2){ r_sin+Void; r_cos+Void; r_tan+Void; } + +print("%16.14f\n".fmt( 6.0 * i_sin(0.5))); +print("%16.14f\n".fmt( 3.0 * i_cos(0.5))); +print("%16.14f\n".fmt( 4.0 * i_tan(1.0))); diff --git a/Task/Tic-tac-toe/00DESCRIPTION b/Task/Tic-tac-toe/00DESCRIPTION index d6d9a86cfa..601a46bb0d 100644 --- a/Task/Tic-tac-toe/00DESCRIPTION +++ b/Task/Tic-tac-toe/00DESCRIPTION @@ -1,12 +1,9 @@ [[File:Tic_tac_toe.jpg|500px||right]] ;Task: -Play a game of   [[wp:Tic-tac-toe|tic-tac-toe]]. +Play a game of [[wp:Tic-tac-toe|tic-tac-toe]]. Ensure that legal moves are played and that a winning position is notified. -Ensure that legal moves are played and that a winning position is notified. - - -;See: -*   [[http://mathworld.wolfram.com/Tic-Tac-Toe.html Mathworld™, Tic-Tac-Toe game]]. +;See also +* [http://mathworld.wolfram.com/Tic-Tac-Toe.html Mathworld™, Tic-Tac-Toe game].

    diff --git a/Task/Tic-tac-toe/00META.yaml b/Task/Tic-tac-toe/00META.yaml index a2413d963b..327e7d06dc 100644 --- a/Task/Tic-tac-toe/00META.yaml +++ b/Task/Tic-tac-toe/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Games note: Games diff --git a/Task/Tic-tac-toe/MIRC-Scripting-Language/tic-tac-toe.mirc b/Task/Tic-tac-toe/MIRC-Scripting-Language/tic-tac-toe.mirc new file mode 100644 index 0000000000..b4b3178e2d --- /dev/null +++ b/Task/Tic-tac-toe/MIRC-Scripting-Language/tic-tac-toe.mirc @@ -0,0 +1,31 @@ +alias ttt { + if ($2 isin %ttt) || (!%ttt) { + var %ttt~ = $remove($iif(%ttt,%ttt,1 2 3 4 5 6 7 8 9),$2,X,O) + var %ttt~~ = $replace($iif(%ttt,%ttt,1 2 3 4 5 6 7 8 9),$2,X) + set %ttt $replace(%ttt~~,$iif(($regex(%ttt~~,/(?:O . . (?:(?:. O .|O) . . (\d)|(?:. (\d) .|(\d)) . . O)|(\d) . . (?:. O .|O) . . O|. . (?:O . (?:O . (\d)|(\d) . O)|(\d) . O . O) . .)/)) || ($regex(%ttt~~,/^(?:. . . )*(?:O (?:O (\d)|(\d) O)|(\d) O O)(?: . . .)*$/)),$regml(1),$iif(($regex(%ttt~~,/(?:X . . (?:(?:. X .|X) . . (\d)|(?:. (\d) .|(\d)) . . X)|(\d) . . (?:. X .|X) . . X|. . (?:X . (?:X . (\d)|(\d) . X)|(\d) . X . X) . .)/)) || ($regex(%ttt~~,/^(?:. . . )*(?:X (?:X (\d)|(\d) X)|(\d) X X)(?: . . .)*$/)),$regml(1),$iif($remove(%ttt~,2,4,6,8,$chr(32)),$iif((5 isin $remove(%ttt~,2,4,6,8)) && ($rand(0,$numtok($v2,32)) == 0),5,$gettok($remove(%ttt~,2,4,6,8),$rand(1,$numtok($remove(%ttt~,2,4,6,8),32)),32)),$gettok(%ttt~,$rand(1,$numtok(%ttt~,32)),32)))),O) + tokenize 32 %ttt + if ($regex(%ttt,/(?:X . . (?:X|. X .) . . X|. . X . X . X . .)/)) || ($regex(%ttt,/^(?:. . . )*X X X(?: . . .)*$/)) { + echo -ag $me Wins + tokenize 32 %ttt~~ + unset %ttt + } + elseif ($regex(%ttt,/(?:O . . (?:O|. O .) . . O|. . O . O . O . .)/)) || ($regex(%ttt,/^(?:. . . )*O O O(?: . . .)*$/)) { + echo -ag $me Loses + unset %ttt + } + elseif (!$regex(%ttt,/\d/)) { + echo -ag Draw + unset %ttt + } + echo -ag � $+ $iif($1 isnum,$chr(32),$1) $+ $chr(124) $+ $iif($2 isnum,$chr(32),$2) $+ $chr(124) $+ $iif($3 isnum, ,$3) + echo -ag � $+ $iif($4 isnum,$chr(32),$4) $+ $chr(124) $+ $iif($5 isnum,$chr(32),$5) $+ $chr(124) $+ $iif($6 isnum, ,$6) + echo -ag � $+ $iif($7 isnum,$chr(32),$7) $+ $chr(124) $+ $iif($8 isnum,$chr(32),$8) $+ $chr(124) $+ $iif($9 isnum, ,$9) + } + else { + echo -ag Place Taken + tokenize 32 %ttt + echo -ag � $+ $iif($1 isnum,$chr(32),$1) $+ $chr(124) $+ $iif($2 isnum,$chr(32),$2) $+ $chr(124) $+ $iif($3 isnum, ,$3) + echo -ag � $+ $iif($4 isnum,$chr(32),$4) $+ $chr(124) $+ $iif($5 isnum,$chr(32),$5) $+ $chr(124) $+ $iif($6 isnum, ,$6) + echo -ag � $+ $iif($7 isnum,$chr(32),$7) $+ $chr(124) $+ $iif($8 isnum,$chr(32),$8) $+ $chr(124) $+ $iif($9 isnum, ,$9) + } +} diff --git a/Task/Tic-tac-toe/Scilab/tic-tac-toe.scilab b/Task/Tic-tac-toe/Scilab/tic-tac-toe.scilab new file mode 100644 index 0000000000..0cd6bc435d --- /dev/null +++ b/Task/Tic-tac-toe/Scilab/tic-tac-toe.scilab @@ -0,0 +1,379 @@ +function [] = startGame() + //Board size and marks + N = 3; + marks = ["X" "O"]; + + //Creating empty board + board = string(zeros(N,N)); + for i = 1:(N*N) + board(i) = ""; + end + + //Initialising players + clc(); + players= [%F %F]; + players = playerSetup(marks); + + //Console header + header = [strsplit(marks(1)+" is ----")';... + strsplit(marks(2)+" is ----")']; + for i = 1:2 + if players(i) then + header(i,6:10) = strsplit("P"+string(i)+". "); + else + header(i,6:10) = strsplit("COMP."); + end + end + + //Game loop + sleep(1000); + win_flag = %F; + count = 0; + while count0 then + ascii_board(rows,i) = " "; + end + end + + for i = 1:rows + ascii_board(i,cols) = " "; + end + + printf("\n"); + for i = 1:size(ascii_board,'r') + printf("%s\n",strcat(ascii_board(i,:))) + end +endfunction + +function moves_board = availableMoves(board) + //Find empty cells on the board + moves_board = board; + + for i = 1:(size(board,'r')*size(board,'c')) + if board(i) == "" then + moves_board(i) = string(i); + else + moves_board(i) = "_"; + end + end +endfunction + +function varargout = readHumanMove(board) + //Read human input + printf("\nAvailable cells:"); + moves_board = availableMoves(board); + disp(moves_board'); + + x = input("\nEnter a move (0 to quit game): "); + + valid = %F; + pos = 0; + total = size(moves_board,'r') * size(moves_board,'c'); + + //Check if it is a valid move + if x == 0 then + disp("Quit game.") + abort + elseif (x>=1 & x<=total) then + if (moves_board(x) == string(x)) then + valid = %T; + pos = x; + end + end + + varargout = list(pos,valid); +endfunction + +function varargout = updateBoard(board,pos,player) + //Add move to the board + if board(pos) ~= "" then + error('Error: Invalid move.'); + end + + board(pos) = player + + varargout = list(board); +endfunction + +function varargout = detectWin(board) + //Detect if there is a winner or not + win_flag = %F; + winner = ""; + + //Get board marks + marks = ["" ""]; + mark_inds = find(board ~= ""); + marks(1) = board(mark_inds(1)) + mark_inds = find( (board ~= "") & (board ~= marks(1)) ); + marks(2) = board(mark_inds(1)); + + //If there is a minimum number of moves, check if there is a winner + n_moves = find(~(board == "")); + n_moves = length(n_moves) + + if n_moves >= size(board,'r') then + board_X = (board == marks(1)); + board_O = (board == marks(2)); + + for i = 1:size(board,'r') + //Check rows + if find(~board_X(i,:)) == [] then + win_flag = %T; + winner = marks(1); + break + end + if find(~board_O(i,:)) == [] then + win_flag = %T; + winner = marks(2); + break + end + + //Check columns + if find(~board_X(:,i)) == [] then + win_flag = %T; + winner = marks(1); + break + end + if find(~board_O(:,i)) == [] then + win_flag = %T; + winner = marks(2); + break + end + end + + //Check diagonal + if ~win_flag then + if find(~diag(board_X)) == [] then + win_flag = %T; + winner = marks(1); + elseif find(~diag(board_O)) == [] then + win_flag = %T; + winner = marks(2); + end + end + + //Check anti-diagonal + if ~win_flag then + board_X = board_X(:,$:-1:1); + board_O = board_O(:,$:-1:1); + + if find(~diag(board_X)) == [] then + win_flag = %T; + winner = marks(1); + elseif find(~diag(board_O)) == [] then + win_flag = %T; + winner = marks(2); + end + end + end + + varargout = list(win_flag,winner) +endfunction + +function threat_pos = findThreat(board,player) + //Returns a list of moves that can finish the game + + //Available moves + move_inds = find(~( availableMoves(board) == "_" )); + + //If there is a minimum number of moves, check if there is a threat + threat_pos = []; + if (size(board,'r')*size(board,'c')) - length(move_inds) >... + (size(board,'r') - 1) then + for i = 1:length(move_inds) + temp_board = updateBoard(board,move_inds(i),player); + [win_flag,winner] = detectWin(temp_board); + if win_flag & winner == player then + threat_pos = [threat_pos move_inds(i)]; + end + end + end +endfunction + +function varargout = ComputerMove(board,mark,all_marks) + //Atomatically add a move to the board with no human input + + //Find winning moves moves + move_inds = findThreat(board,mark); + + //If there are no winning moves, find opponent's winning moves + //to block opponent's victory + if move_inds == [] then + if mark == all_marks(1) then + opponent = all_marks(2); + elseif mark == all_marks(2) then + opponent = all_marks(1); + end + + move_inds = findThreat(board,opponent); + end + + //If there are no winning moves or threats, find all possible moves + if move_inds == [] then + move_inds = find(~( availableMoves(board) == "_" )); + end + + //Choose a random move among the selected possible moves + pos = grand(1,"prm",move_inds); + pos = pos(1); + + //Update board by adding a new mark + board(pos) = mark; + + varargout = list(board); +endfunction + +startGame() diff --git a/Task/Tic-tac-toe/Swift/tic-tac-toe.swift b/Task/Tic-tac-toe/Swift/tic-tac-toe.swift new file mode 100644 index 0000000000..b4733f65a6 --- /dev/null +++ b/Task/Tic-tac-toe/Swift/tic-tac-toe.swift @@ -0,0 +1,206 @@ +import Darwin + +enum Token : CustomStringConvertible { + case cross, circle + + func matches(tokens: [Token?]) -> Bool { + for token in tokens { + guard let t = token, t == self else { + return false + } + } + return true + } + + func emptyCell(in tokens: [Token?]) -> Int? { + if tokens[0] == nil + && tokens[1] == self + && tokens[2] == self { + return 0 + } else + if tokens[0] == self + && tokens[1] == nil + && tokens[2] == self { + return 1 + } else + if tokens[0] == self + && tokens[1] == self + && tokens[2] == nil { + return 2 + } + return nil + } + + var description: String { + switch self { + case .cross: return "x" + case .circle: return "o" + } + } +} + +struct Board { + var cells: [Token?] = [nil, nil, nil, nil, nil, nil, nil, nil, nil] + + func cells(atCol col: Int) -> [Token?] { + return [cells[col], cells[col + 3], cells[col + 6]] + } + + func cells(atRow row: Int) -> [Token?] { + return [cells[row * 3], cells[row * 3 + 1], cells[row * 3 + 2]] + } + + func cellsTopLeft() -> [Token?] { + return [cells[0], cells[4], cells[8]] + } + + func cellsBottomLeft() -> [Token?] { + return [cells[6], cells[4], cells[2]] + } + + func winner() -> Token? { + let r0 = cells(atRow: 0) + let r1 = cells(atRow: 1) + let r2 = cells(atRow: 2) + let c0 = cells(atCol: 0) + let c1 = cells(atCol: 1) + let c2 = cells(atCol: 2) + let tl = cellsTopLeft() + let bl = cellsBottomLeft() + + if Token.cross.matches(tokens: r0) + || Token.cross.matches(tokens: r1) + || Token.cross.matches(tokens: r2) + || Token.cross.matches(tokens: c0) + || Token.cross.matches(tokens: c1) + || Token.cross.matches(tokens: c2) + || Token.cross.matches(tokens: tl) + || Token.cross.matches(tokens: bl) { + return .cross + } else + if Token.circle.matches(tokens: r0) + || Token.circle.matches(tokens: r1) + || Token.circle.matches(tokens: r2) + || Token.circle.matches(tokens: c0) + || Token.circle.matches(tokens: c1) + || Token.circle.matches(tokens: c2) + || Token.circle.matches(tokens: tl) + || Token.circle.matches(tokens: bl) { + return .circle + } + return nil + } + + func atCapacity() -> Bool { + return cells.filter { $0 == nil }.count == 0 + } + + mutating func play(token: Token, at location: Int) { + cells[location] = token + } + + func findBestLocation(for player: Token) -> Int? { + let r0 = cells(atRow: 0) + let r1 = cells(atRow: 1) + let r2 = cells(atRow: 2) + let c0 = cells(atCol: 0) + let c1 = cells(atCol: 1) + let c2 = cells(atCol: 2) + let tl = cellsTopLeft() + let bl = cellsBottomLeft() + + if let cell = player.emptyCell(in: r0) { + return cell + } else if let cell = player.emptyCell(in: r1) { + return cell + 3 + } else if let cell = player.emptyCell(in: r2) { + return cell + 6 + } else if let cell = player.emptyCell(in: c0) { + return cell * 3 + } else if let cell = player.emptyCell(in: c1) { + return cell * 3 + 1 + } else if let cell = player.emptyCell(in: c2) { + return cell * 3 + 2 + } else if let cell = player.emptyCell(in: tl) { + return cell == 0 ? 0 : (cell == 1 ? 4 : 8) + } else if let cell = player.emptyCell(in: bl) { + return cell == 0 ? 6 : (cell == 1 ? 4 : 2) + } + return nil + } + + func findMove() -> Int { + let empties = cells.enumerated().filter { $0.1 == nil } + let r = Int(arc4random()) % empties.count + return empties[r].0 + } +} + +extension Board : CustomStringConvertible { + var description: String { + var result = "\n---------------\n" + for (idx, cell) in cells.enumerated() { + if let cell = cell { + result += "| \(cell) |" + } else { + result += "| \(idx) |" + } + + if (idx + 1) % 3 == 0 { + result += "\n---------------\n" + } + } + return result + } +} + +while true { + var board = Board() + print("Who do you want to play as ('o' or 'x'): ", separator: "", terminator: "") + let answer = readLine()?.characters.first ?? "x" + + var player: Token = answer == "x" ? .cross : .circle + var pc: Token = player == .cross ? .circle : .cross + + print(board) + + while true { + print("Choose cell to play on: ", separator: "", terminator: "") + var pos = Int(readLine() ?? "0") ?? 0 + while !board.atCapacity() && board.cells[pos] != nil { + print("Invalid move. Choose cell to play on: ", separator: "", terminator: "") + pos = Int(readLine() ?? "0") ?? 0 + } + + if board.atCapacity() { + print("Draw") + break + } + + board.play(token: player, at: pos) + print(board) + + if let winner = board.winner() { + print("winner is \(winner)") + break + } else if board.atCapacity() { + print("Draw") + break + } + + if let win = board.findBestLocation(for: pc) { + board.play(token: pc, at: win) + } else if let def = board.findBestLocation(for: player) { + board.play(token: pc, at: def) + } else { + board.play(token: pc, at: board.findMove()) + } + + print(board) + + if let winner = board.winner() { + print("winner is \(winner)") + break + } + } +} diff --git a/Task/Time-a-function/BaCon/time-a-function.bacon b/Task/Time-a-function/BaCon/time-a-function.bacon new file mode 100644 index 0000000000..2c731ea436 --- /dev/null +++ b/Task/Time-a-function/BaCon/time-a-function.bacon @@ -0,0 +1,9 @@ +' Time a function +SUB timed() + SLEEP 7000 +END SUB + +st = TIMER +timed() +et = TIMER +PRINT st, ", ", et diff --git a/Task/Time-a-function/Halon/time-a-function.halon b/Task/Time-a-function/Halon/time-a-function.halon new file mode 100644 index 0000000000..5bb54766bb --- /dev/null +++ b/Task/Time-a-function/Halon/time-a-function.halon @@ -0,0 +1,5 @@ +$t = uptime(); + +sleep(1); + +echo uptime() - $t; diff --git a/Task/Time-a-function/Haskell/time-a-function.hs b/Task/Time-a-function/Haskell/time-a-function.hs index 1faed29c2a..c6769f744e 100644 --- a/Task/Time-a-function/Haskell/time-a-function.hs +++ b/Task/Time-a-function/Haskell/time-a-function.hs @@ -1,13 +1,13 @@ -import System.CPUTime +import System.CPUTime (getCPUTime) -- We assume the function we are timing is an IO monad computation timeIt :: (Fractional c) => (a -> IO b) -> a -> IO c -timeIt action arg = - do startTime <- getCPUTime - action arg - finishTime <- getCPUTime - return $ fromIntegral (finishTime - startTime) / 1000000000000 +timeIt action arg = do + startTime <- getCPUTime + action arg + finishTime <- getCPUTime + return $ fromIntegral (finishTime - startTime) / 1000000000000 -- Version for use with evaluating regular non-monadic functions -timeIt' :: (Fractional c) => (a -> b) -> a -> IO c -timeIt' f = timeIt (\x -> f x `seq` return ()) +timeIt_ :: (Fractional c) => (a -> b) -> a -> IO c +timeIt_ f = timeIt ((`seq` return ()) . f) diff --git a/Task/Time-a-function/Julia/time-a-function.julia b/Task/Time-a-function/Julia/time-a-function.julia new file mode 100644 index 0000000000..43f3c3bbb4 --- /dev/null +++ b/Task/Time-a-function/Julia/time-a-function.julia @@ -0,0 +1,13 @@ +# v0.6.0 + +function countto(n::Integer) + i = zero(n) + println("Counting...") + while i < n + i += 1 + end + println("Done!") +end + +@time countto(10 ^ 5) +@time countto(10 ^ 10) diff --git a/Task/Time-a-function/Kotlin/time-a-function.kotlin b/Task/Time-a-function/Kotlin/time-a-function.kotlin new file mode 100644 index 0000000000..2ebb336790 --- /dev/null +++ b/Task/Time-a-function/Kotlin/time-a-function.kotlin @@ -0,0 +1,24 @@ +// version 1.1.2 +// need to enable runtime assertions with JVM -ea option + +import java.lang.management.ManagementFactory +import java.lang.management.ThreadMXBean + +fun countTo(x: Int) { + println("Counting..."); + (1..x).forEach {} + println("Done!") +} + +fun main(args: Array) { + val counts = intArrayOf(100_000_000, 1_000_000_000) + val threadMX = ManagementFactory.getThreadMXBean() + assert(threadMX.isCurrentThreadCpuTimeSupported) + threadMX.isThreadCpuTimeEnabled = true + for (count in counts) { + val start = threadMX.currentThreadCpuTime + countTo(count) + val end = threadMX.currentThreadCpuTime + println("Counting to $count takes ${(end-start)/1000000}ms") + } +} diff --git a/Task/Time-a-function/Stata/time-a-function.stata b/Task/Time-a-function/Stata/time-a-function.stata new file mode 100644 index 0000000000..ea62eb2870 --- /dev/null +++ b/Task/Time-a-function/Stata/time-a-function.stata @@ -0,0 +1,10 @@ +program timer_test + timer clear 1 + timer on 1 + sleep `0' + timer off 1 + timer list 1 +end + +. timer_test 1000 + 1: 1.01 / 1 = 1.0140 diff --git a/Task/Time-a-function/Zkl/time-a-function.zkl b/Task/Time-a-function/Zkl/time-a-function.zkl new file mode 100644 index 0000000000..ca62767363 --- /dev/null +++ b/Task/Time-a-function/Zkl/time-a-function.zkl @@ -0,0 +1 @@ +t:=Time.Clock.time; Atomic.sleep(3); (Time.Clock.time - t).println(); diff --git a/Task/Tokenize-a-string/Ada/tokenize-a-string.ada b/Task/Tokenize-a-string/Ada/tokenize-a-string.ada index f79a6de30c..7d375c4c7b 100644 --- a/Task/Tokenize-a-string/Ada/tokenize-a-string.ada +++ b/Task/Tokenize-a-string/Ada/tokenize-a-string.ada @@ -1,18 +1,24 @@ -with Ada.Strings.Fixed; use Ada.Strings.Fixed; -with Ada.Text_Io; use Ada.Text_Io; +with Ada.Text_IO, Ada.Strings.Fixed, Ada.Containers.Indefinite_Vectors; +use Ada.Text_IO, Ada.Strings.Fixed, Ada.Containers; -procedure Parse_Commas is - Source_String : String := "Hello,How,Are,You,Today"; - Index_List : array(Source_String'Range) of Natural; - Next_Index : Natural := Index_List'First; -begin - Index_List(Next_Index) := Source_String'First; - while Index_List(Next_Index) < Source_String'Last loop - Next_Index := Next_Index + 1; - Index_List(Next_Index) := 1 + Index(Source_String(Index_List(Next_Index - 1)..Source_String'Last), ","); - if Index_List(Next_Index) = 1 then - Index_List(Next_Index) := Source_String'Last + 2; +procedure tokenize is + package String_Vector is new Indefinite_Vectors (Natural,String); use String_Vector; + procedure Parse (s : String; v : in out Vector) is + i : Integer := Index (s,","); + begin + if s'Length > 0 then + if i < s'First then + v.Append (s); + else + v.Append (s (s'First..i-1)); + Parse ( s(i+1..s'Last), v); end if; - Put(Source_String(Index_List(Next_Index - 1)..Index_List(Next_Index)-2) & "."); - end loop; -end Parse_Commas; + end if; + end Parse; + v : Vector; +begin + Parse ("Hello,How,Are,You,Today,,",v); + for s of v loop + put(s&"."); + end loop; +end tokenize; diff --git a/Task/Tokenize-a-string/Astro/tokenize-a-string.astro b/Task/Tokenize-a-string/Astro/tokenize-a-string.astro new file mode 100644 index 0000000000..d52871edd1 --- /dev/null +++ b/Task/Tokenize-a-string/Astro/tokenize-a-string.astro @@ -0,0 +1,3 @@ +let text = 'Hello,How,Are,You,Today' +let tokens = text.split /,/ +print join('.', tokens) diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-10.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-10.basic index e6220da699..7c11088ae7 100644 --- a/Task/Tokenize-a-string/BASIC/tokenize-a-string-10.basic +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-10.basic @@ -1,14 +1,5 @@ -Sub Main() - Dim parseMe As String, parsed As Variant - parseMe = "Hello,How,Are,You,Today" - - parsed = Split(parseMe, ",") - - Dim L0 As Long, outP As String - outP = parsed(0) - For L0 = 1 To UBound(parsed) - outP = outP & "." & parsed(L0) - Next - - MsgBox outP -End Sub +text$ = "Hello,How,Are,You,Today" +FOR i = 1 to 5 + textArray$(i) = word$(text$,i,",") + print textArray$(i);" "; +NEXT diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-11.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-11.basic new file mode 100644 index 0000000000..2e5b6a5fa3 --- /dev/null +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-11.basic @@ -0,0 +1 @@ +WScript.Echo Join(Split("Hello,How,Are,You,Today", ","), ".") diff --git a/Task/Tokenize-a-string/Visual-Basic/tokenize-a-string.vb b/Task/Tokenize-a-string/BASIC/tokenize-a-string-12.basic similarity index 100% rename from Task/Tokenize-a-string/Visual-Basic/tokenize-a-string.vb rename to Task/Tokenize-a-string/BASIC/tokenize-a-string-12.basic diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-2.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-2.basic index ed538d7a3d..844b497bc0 100644 --- a/Task/Tokenize-a-string/BASIC/tokenize-a-string-2.basic +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-2.basic @@ -1,8 +1,13 @@ - INSTALL @lib$+"STRINGLIB" +' Tokenize a string +OPTION BASE 1 - text$ = "Hello,How,Are,You,Today" - n% = FN_split(text$, ",", array$()) - FOR i% = 0 TO n%-1 - PRINT array$(i%) "." ; - NEXT - PRINT +READ csv$ +DATA "Hello,How,Are,You,Today" + +SPLIT csv$ BY "," TO elements$ SIZE n + +FOR i = 1 TO n + PRINT elements$[i] FORMAT "%s" + IF i < n THEN PRINT "." FORMAT "%s" +NEXT +PRINT diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-3.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-3.basic index 02fe2206ae..ed538d7a3d 100644 --- a/Task/Tokenize-a-string/BASIC/tokenize-a-string-3.basic +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-3.basic @@ -1,7 +1,8 @@ -'Note that Liberty Basic's array usage can reach element #10 before having to DIM the array -For i = 0 To 4 - array$(i) = Word$("Hello,How,Are,You,Today", (i + 1), ",") - array$ = array$ + array$(i) + "." -Next i + INSTALL @lib$+"STRINGLIB" -Print Left$(array$, (Len(array$) - 1)) + text$ = "Hello,How,Are,You,Today" + n% = FN_split(text$, ",", array$()) + FOR i% = 0 TO n%-1 + PRINT array$(i%) "." ; + NEXT + PRINT diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-4.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-4.basic index 2f5dbd573f..f26264d78f 100644 --- a/Task/Tokenize-a-string/BASIC/tokenize-a-string-4.basic +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-4.basic @@ -1,15 +1,17 @@ -FUNCTION PBMAIN () AS LONG - DIM parseMe AS STRING - parseMe = "Hello,How,Are,You,Today" - - REDIM parsed(PARSECOUNT(parseMe) - 1) AS STRING - PARSE parseMe, parsed() 'comma is default delimiter - - DIM L0 AS LONG, outP AS STRING - outP = parsed(0) - FOR L0 = 1 TO UBOUND(parsed) 'could reuse parsecount instead of ubound - outP = outP & "." & parsed(L0) - NEXT - - MSGBOX outP -END FUNCTION +10 REM TOKENIZE A STRING ... ROSETTACODE.ORG +20 T$ = "HELLO,HOW,ARE,YOU,TODAY" +30 GOSUB 200, TOKENIZE +40 FOR I = 1 TO N +50 PRINT A$(I) "." ; +60 NEXT +70 PRINT +80 END +200 IF N = 0 THEN DIM A$(256) +210 N = 1 +220 A$(N) = "" +230 FOR L = 1 TO LEN(T$) +240 C$ = MID$(T$, L, 1) +250 IF C$<>"," THEN A$(N) = A$(N) + C$: GOTO 270 +260 N = N + 1 +270 NEXT L +280 RETURN diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-5.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-5.basic index 28e4e237da..02fe2206ae 100644 --- a/Task/Tokenize-a-string/BASIC/tokenize-a-string-5.basic +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-5.basic @@ -1,10 +1,7 @@ -NewList MyStrings.s() - -For i=1 To 5 - AddElement(MyStrings()) - MyStrings()=StringField("Hello,How,Are,You,Today",i,",") +'Note that Liberty Basic's array usage can reach element #10 before having to DIM the array +For i = 0 To 4 + array$(i) = Word$("Hello,How,Are,You,Today", (i + 1), ",") + array$ = array$ + array$(i) + "." Next i -ForEach MyStrings() - Print(MyStrings()+".") -Next +Print Left$(array$, (Len(array$) - 1)) diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-6.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-6.basic index c68564a14c..2f5dbd573f 100644 --- a/Task/Tokenize-a-string/BASIC/tokenize-a-string-6.basic +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-6.basic @@ -1 +1,15 @@ -Print(ReplaceString("Hello,How,Are,You,Today",",",".")) +FUNCTION PBMAIN () AS LONG + DIM parseMe AS STRING + parseMe = "Hello,How,Are,You,Today" + + REDIM parsed(PARSECOUNT(parseMe) - 1) AS STRING + PARSE parseMe, parsed() 'comma is default delimiter + + DIM L0 AS LONG, outP AS STRING + outP = parsed(0) + FOR L0 = 1 TO UBOUND(parsed) 'could reuse parsecount instead of ubound + outP = outP & "." & parsed(L0) + NEXT + + MSGBOX outP +END FUNCTION diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-7.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-7.basic index f63022d900..28e4e237da 100644 --- a/Task/Tokenize-a-string/BASIC/tokenize-a-string-7.basic +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-7.basic @@ -1,45 +1,10 @@ -DIM parseMe AS STRING -parseMe = "Hello,How,Are,You,Today" +NewList MyStrings.s() -DIM tmpLng1 AS INTEGER, tmpLng2 AS INTEGER, parsedCount AS INTEGER -tmpLng2 = 1 -parsedCount = -1 +For i=1 To 5 + AddElement(MyStrings()) + MyStrings()=StringField("Hello,How,Are,You,Today",i,",") +Next i -'count number of tokens -DO - tmpLng1 = INSTR(tmpLng2, parseMe, ",") - IF tmpLng1 THEN - parsedCount = parsedCount + 1 - tmpLng2 = tmpLng1 + 1 - ELSE - IF tmpLng2 < (LEN(parseMe) + 1) THEN parsedCount = parsedCount + 1 - EXIT DO - END IF -LOOP - -IF parsedCount > -1 THEN - REDIM parsed(parsedCount) AS STRING - tmpLng2 = 1 - parsedCount = -1 - - 'parse - DO - tmpLng1 = INSTR(tmpLng2, parseMe, ",") - IF tmpLng1 THEN - parsedCount = parsedCount + 1 - parsed(parsedCount) = MID$(parseMe, tmpLng2, tmpLng1 - tmpLng2) - tmpLng2 = tmpLng1 + 1 - ELSE - IF tmpLng2 < (LEN(parseMe) + 1) THEN - parsedCount = parsedCount + 1 - parsed(parsedCount) = MID$(parseMe, tmpLng2) - END IF - EXIT DO - END IF - LOOP - - PRINT parsed(0); - FOR L0 = 1 TO parsedCount - PRINT "."; parsed(L0); - NEXT -END IF +ForEach MyStrings() + Print(MyStrings()+".") +Next diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-8.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-8.basic index 7c11088ae7..c68564a14c 100644 --- a/Task/Tokenize-a-string/BASIC/tokenize-a-string-8.basic +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-8.basic @@ -1,5 +1 @@ -text$ = "Hello,How,Are,You,Today" -FOR i = 1 to 5 - textArray$(i) = word$(text$,i,",") - print textArray$(i);" "; -NEXT +Print(ReplaceString("Hello,How,Are,You,Today",",",".")) diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string-9.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string-9.basic index 2e5b6a5fa3..f63022d900 100644 --- a/Task/Tokenize-a-string/BASIC/tokenize-a-string-9.basic +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string-9.basic @@ -1 +1,45 @@ -WScript.Echo Join(Split("Hello,How,Are,You,Today", ","), ".") +DIM parseMe AS STRING +parseMe = "Hello,How,Are,You,Today" + +DIM tmpLng1 AS INTEGER, tmpLng2 AS INTEGER, parsedCount AS INTEGER +tmpLng2 = 1 +parsedCount = -1 + +'count number of tokens +DO + tmpLng1 = INSTR(tmpLng2, parseMe, ",") + IF tmpLng1 THEN + parsedCount = parsedCount + 1 + tmpLng2 = tmpLng1 + 1 + ELSE + IF tmpLng2 < (LEN(parseMe) + 1) THEN parsedCount = parsedCount + 1 + EXIT DO + END IF +LOOP + +IF parsedCount > -1 THEN + REDIM parsed(parsedCount) AS STRING + tmpLng2 = 1 + parsedCount = -1 + + 'parse + DO + tmpLng1 = INSTR(tmpLng2, parseMe, ",") + IF tmpLng1 THEN + parsedCount = parsedCount + 1 + parsed(parsedCount) = MID$(parseMe, tmpLng2, tmpLng1 - tmpLng2) + tmpLng2 = tmpLng1 + 1 + ELSE + IF tmpLng2 < (LEN(parseMe) + 1) THEN + parsedCount = parsedCount + 1 + parsed(parsedCount) = MID$(parseMe, tmpLng2) + END IF + EXIT DO + END IF + LOOP + + PRINT parsed(0); + FOR L0 = 1 TO parsedCount + PRINT "."; parsed(L0); + NEXT +END IF diff --git a/Task/Tokenize-a-string/BBC-BASIC/tokenize-a-string.bbc b/Task/Tokenize-a-string/BBC-BASIC/tokenize-a-string.bbc deleted file mode 100644 index ed538d7a3d..0000000000 --- a/Task/Tokenize-a-string/BBC-BASIC/tokenize-a-string.bbc +++ /dev/null @@ -1,8 +0,0 @@ - INSTALL @lib$+"STRINGLIB" - - text$ = "Hello,How,Are,You,Today" - n% = FN_split(text$, ",", array$()) - FOR i% = 0 TO n%-1 - PRINT array$(i%) "." ; - NEXT - PRINT diff --git a/Task/Tokenize-a-string/ColdFusion/tokenize-a-string-1.cfm b/Task/Tokenize-a-string/ColdFusion/tokenize-a-string-1.cfm new file mode 100644 index 0000000000..d5f1f15dbb --- /dev/null +++ b/Task/Tokenize-a-string/ColdFusion/tokenize-a-string-1.cfm @@ -0,0 +1,4 @@ + + + #Replace( wordListTag, ",", ".", "all" )# + diff --git a/Task/Tokenize-a-string/ColdFusion/tokenize-a-string-2.cfm b/Task/Tokenize-a-string/ColdFusion/tokenize-a-string-2.cfm new file mode 100644 index 0000000000..c649b55ab8 --- /dev/null +++ b/Task/Tokenize-a-string/ColdFusion/tokenize-a-string-2.cfm @@ -0,0 +1,5 @@ + + wordList = "Hello,How,Are,You,Today"; + splitList = replace( wordList, ",", ".", "all" ); + writeOutput( splitList ); + diff --git a/Task/Tokenize-a-string/Elena/tokenize-a-string.elena b/Task/Tokenize-a-string/Elena/tokenize-a-string.elena index 6a2958ba75..1807214ed4 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. -#import system'routines. +import system'routines. +import extensions. -#symbol program = +program = [ - #var string := "Hello,How,Are,You,Today". + var string := "Hello,How,Are,You,Today". - string split &by:"," run &each:s + string split by:","; forEach(:s) [ - console writeLiteral:(s + "."). - ]. + console print(s,".") + ] ]. diff --git a/Task/Tokenize-a-string/jq/tokenize-a-string-1.jq b/Task/Tokenize-a-string/Jq/tokenize-a-string-1.jq similarity index 100% rename from Task/Tokenize-a-string/jq/tokenize-a-string-1.jq rename to Task/Tokenize-a-string/Jq/tokenize-a-string-1.jq diff --git a/Task/Tokenize-a-string/jq/tokenize-a-string-2.jq b/Task/Tokenize-a-string/Jq/tokenize-a-string-2.jq similarity index 100% rename from Task/Tokenize-a-string/jq/tokenize-a-string-2.jq rename to Task/Tokenize-a-string/Jq/tokenize-a-string-2.jq diff --git a/Task/Tokenize-a-string/Kotlin/tokenize-a-string.kotlin b/Task/Tokenize-a-string/Kotlin/tokenize-a-string.kotlin index 1a38922ae3..26f9ffd1c4 100644 --- a/Task/Tokenize-a-string/Kotlin/tokenize-a-string.kotlin +++ b/Task/Tokenize-a-string/Kotlin/tokenize-a-string.kotlin @@ -1,2 +1,4 @@ -val input = "Hello,How,Are,You,Today" -println(input.split(',').join(".")) +fun main(args: Array) { + val input = "Hello,How,Are,You,Today" + println(input.split(',').joinToString(".")) +} diff --git a/Task/Tokenize-a-string/Liberty-BASIC/tokenize-a-string.liberty b/Task/Tokenize-a-string/Liberty-BASIC/tokenize-a-string.liberty deleted file mode 100644 index 02fe2206ae..0000000000 --- a/Task/Tokenize-a-string/Liberty-BASIC/tokenize-a-string.liberty +++ /dev/null @@ -1,7 +0,0 @@ -'Note that Liberty Basic's array usage can reach element #10 before having to DIM the array -For i = 0 To 4 - array$(i) = Word$("Hello,How,Are,You,Today", (i + 1), ",") - array$ = array$ + array$(i) + "." -Next i - -Print Left$(array$, (Len(array$) - 1)) diff --git a/Task/Tokenize-a-string/Logtalk/tokenize-a-string-1.logtalk b/Task/Tokenize-a-string/Logtalk/tokenize-a-string-1.logtalk deleted file mode 100644 index da0b5f5236..0000000000 --- a/Task/Tokenize-a-string/Logtalk/tokenize-a-string-1.logtalk +++ /dev/null @@ -1,22 +0,0 @@ -:- object(spliting). - - :- public(convert/2). - :- mode(convert(+atom, -atom), one). - - convert(StringIn, StringOut) :- - atom_chars(StringIn, CharactersIn), - phrase(split(',', Tokens), CharactersIn), - phrase(split('.', Tokens), CharactersOut), - atom_chars(StringOut, CharactersOut). - - split(Separator, [t([Character| Characters])| Tokens]) --> - [Character], {Character \== Separator}, split(Separator, [t(Characters)| Tokens]). - split(Separator, [t([])| Tokens]) --> - [Separator], split(Separator, Tokens). - split(_, [t([])]) --> - []. - % the look-ahead in the next rule prevents adding a spurious separator at the end - split(_, []), [Character] --> - [Character]. - -:- end_object. diff --git a/Task/Tokenize-a-string/Logtalk/tokenize-a-string-2.logtalk b/Task/Tokenize-a-string/Logtalk/tokenize-a-string-2.logtalk deleted file mode 100644 index 3ed90b4357..0000000000 --- a/Task/Tokenize-a-string/Logtalk/tokenize-a-string-2.logtalk +++ /dev/null @@ -1,3 +0,0 @@ -| ?- spliting::convert('Hello,How,Are,You,Today', Converted). -Converted = 'Hello.How.Are.You.Today' -yes diff --git a/Task/Tokenize-a-string/Lua/tokenize-a-string-1.lua b/Task/Tokenize-a-string/Lua/tokenize-a-string-1.lua deleted file mode 100644 index 09da94bfc3..0000000000 --- a/Task/Tokenize-a-string/Lua/tokenize-a-string-1.lua +++ /dev/null @@ -1,10 +0,0 @@ -require"re" - -record = re.compile[[ - record <- ( (',' )* ) -> {} (%nl / !.) - field <- / - nonescaped <- { [^,"%nl]* } - escaped <- '"' {~ ([^"] / '""' -> '"')* ~} '"' -]] - -print(unpack(record:match"hello,how,are,you,today")) diff --git a/Task/Tokenize-a-string/Lua/tokenize-a-string-2.lua b/Task/Tokenize-a-string/Lua/tokenize-a-string-2.lua deleted file mode 100644 index 483cbe8a58..0000000000 --- a/Task/Tokenize-a-string/Lua/tokenize-a-string-2.lua +++ /dev/null @@ -1,10 +0,0 @@ -str = "Hello,How,Are,You,Today" - -tokens = {} -for w in string.gmatch( str, "(%a+)" ) do - tokens[#tokens+1] = w -end - -for i = 1, #tokens do - print( tokens[i] ) -end diff --git a/Task/Tokenize-a-string/Lua/tokenize-a-string-3.lua b/Task/Tokenize-a-string/Lua/tokenize-a-string-3.lua deleted file mode 100644 index f778a0a11e..0000000000 --- a/Task/Tokenize-a-string/Lua/tokenize-a-string-3.lua +++ /dev/null @@ -1,11 +0,0 @@ -str = "Hello|How|Are|You||Today" - -tokens = {} -for w in string.gmatch( str, "([^|]*)|?" ) do - tokens[#tokens+1] = w -end -table.remove(tokens)--pops off the last empty value, because without doing |? we lose the last element. - -for i = 1, #tokens do - print( tokens[i] ) -end diff --git a/Task/Tokenize-a-string/MATLAB/tokenize-a-string-1.m b/Task/Tokenize-a-string/MATLAB/tokenize-a-string-1.m deleted file mode 100644 index 48b26ec800..0000000000 --- a/Task/Tokenize-a-string/MATLAB/tokenize-a-string-1.m +++ /dev/null @@ -1,14 +0,0 @@ -function tokenizeString(string,delimeter) - - tokens = {}; - - while not(isempty(string)) - [tokens{end+1},string] = strtok(string,delimeter); - end - - for i = (1:numel(tokens)-1) - fprintf([tokens{i} '.']) - end - - fprintf([tokens{end} '\n']) -end diff --git a/Task/Tokenize-a-string/MATLAB/tokenize-a-string-2.m b/Task/Tokenize-a-string/MATLAB/tokenize-a-string-2.m deleted file mode 100644 index c4257e4e87..0000000000 --- a/Task/Tokenize-a-string/MATLAB/tokenize-a-string-2.m +++ /dev/null @@ -1,2 +0,0 @@ ->> tokenizeString('Hello,How,Are,You,Today',',') -Hello.How.Are.You.Today diff --git a/Task/Tokenize-a-string/OCaml/tokenize-a-string-3.ocaml b/Task/Tokenize-a-string/OCaml/tokenize-a-string-3.ocaml deleted file mode 100644 index 1ddf66f256..0000000000 --- a/Task/Tokenize-a-string/OCaml/tokenize-a-string-3.ocaml +++ /dev/null @@ -1,14 +0,0 @@ -let split_char sep str = - let string_index_from i = - try Some (String.index_from str i sep) - with Not_found -> None - in - let rec aux i acc = match string_index_from i with - | Some i' -> - let w = String.sub str i (i' - i) in - aux (succ i') (w::acc) - | None -> - let w = String.sub str i (String.length str - i) in - List.rev (w::acc) - in - aux 0 [] diff --git a/Task/Tokenize-a-string/OCaml/tokenize-a-string-4.ocaml b/Task/Tokenize-a-string/OCaml/tokenize-a-string-4.ocaml deleted file mode 100644 index 7b58650f99..0000000000 --- a/Task/Tokenize-a-string/OCaml/tokenize-a-string-4.ocaml +++ /dev/null @@ -1,3 +0,0 @@ -#load "str.cma";; -let split_str sep str = - Str.split (Str.regexp_string sep) str diff --git a/Task/Tokenize-a-string/OCaml/tokenize-a-string-5.ocaml b/Task/Tokenize-a-string/OCaml/tokenize-a-string-5.ocaml deleted file mode 100644 index 6689860ed7..0000000000 --- a/Task/Tokenize-a-string/OCaml/tokenize-a-string-5.ocaml +++ /dev/null @@ -1 +0,0 @@ -String.concat sep strings diff --git a/Task/Tokenize-a-string/OoRexx/tokenize-a-string.rexx b/Task/Tokenize-a-string/OoRexx/tokenize-a-string.rexx new file mode 100644 index 0000000000..f7efdd4b94 --- /dev/null +++ b/Task/Tokenize-a-string/OoRexx/tokenize-a-string.rexx @@ -0,0 +1,5 @@ +text='Hello,How,Are,You,Today' +do while text \= '' + parse var text word1 ',' text + call charout 'STDOUT:',word1'.' +end diff --git a/Task/Tokenize-a-string/Phix/tokenize-a-string.phix b/Task/Tokenize-a-string/Phix/tokenize-a-string.phix index 1b5ba8a526..e6ec4ed62d 100644 --- a/Task/Tokenize-a-string/Phix/tokenize-a-string.phix +++ b/Task/Tokenize-a-string/Phix/tokenize-a-string.phix @@ -1 +1 @@ -?split("Hello,How,Are,You,Today",',') +?join(split("Hello,How,Are,You,Today",","),".") diff --git a/Task/Tokenize-a-string/PowerBASIC/tokenize-a-string.powerbasic b/Task/Tokenize-a-string/PowerBASIC/tokenize-a-string.powerbasic deleted file mode 100644 index 2f5dbd573f..0000000000 --- a/Task/Tokenize-a-string/PowerBASIC/tokenize-a-string.powerbasic +++ /dev/null @@ -1,15 +0,0 @@ -FUNCTION PBMAIN () AS LONG - DIM parseMe AS STRING - parseMe = "Hello,How,Are,You,Today" - - REDIM parsed(PARSECOUNT(parseMe) - 1) AS STRING - PARSE parseMe, parsed() 'comma is default delimiter - - DIM L0 AS LONG, outP AS STRING - outP = parsed(0) - FOR L0 = 1 TO UBOUND(parsed) 'could reuse parsecount instead of ubound - outP = outP & "." & parsed(L0) - NEXT - - MSGBOX outP -END FUNCTION diff --git a/Task/Tokenize-a-string/PureBasic/tokenize-a-string-1.purebasic b/Task/Tokenize-a-string/PureBasic/tokenize-a-string-1.purebasic deleted file mode 100644 index 28e4e237da..0000000000 --- a/Task/Tokenize-a-string/PureBasic/tokenize-a-string-1.purebasic +++ /dev/null @@ -1,10 +0,0 @@ -NewList MyStrings.s() - -For i=1 To 5 - AddElement(MyStrings()) - MyStrings()=StringField("Hello,How,Are,You,Today",i,",") -Next i - -ForEach MyStrings() - Print(MyStrings()+".") -Next diff --git a/Task/Tokenize-a-string/PureBasic/tokenize-a-string-2.purebasic b/Task/Tokenize-a-string/PureBasic/tokenize-a-string-2.purebasic deleted file mode 100644 index c68564a14c..0000000000 --- a/Task/Tokenize-a-string/PureBasic/tokenize-a-string-2.purebasic +++ /dev/null @@ -1 +0,0 @@ -Print(ReplaceString("Hello,How,Are,You,Today",",",".")) diff --git a/Task/Tokenize-a-string/Run-BASIC/tokenize-a-string.run b/Task/Tokenize-a-string/Run-BASIC/tokenize-a-string.run deleted file mode 100644 index 7c11088ae7..0000000000 --- a/Task/Tokenize-a-string/Run-BASIC/tokenize-a-string.run +++ /dev/null @@ -1,5 +0,0 @@ -text$ = "Hello,How,Are,You,Today" -FOR i = 1 to 5 - textArray$(i) = word$(text$,i,",") - print textArray$(i);" "; -NEXT diff --git a/Task/Tokenize-a-string/Swift/tokenize-a-string-1.swift b/Task/Tokenize-a-string/Swift/tokenize-a-string-1.swift index 5905e2e184..90cd3e0c87 100644 --- a/Task/Tokenize-a-string/Swift/tokenize-a-string-1.swift +++ b/Task/Tokenize-a-string/Swift/tokenize-a-string-1.swift @@ -1,5 +1,5 @@ let text = "Hello,How,Are,You,Today" -let tokens = text.characters.split(",").map{String($0)} // for single-character separator +let tokens = text.components(separatedBy: ",") // for single or multi-character separator print(tokens) -let result = tokens.joinWithSeparator(".") +let result = tokens.joined(separator: ".") print(result) diff --git a/Task/Tokenize-a-string/Swift/tokenize-a-string-2.swift b/Task/Tokenize-a-string/Swift/tokenize-a-string-2.swift index be3201a174..5905e2e184 100644 --- a/Task/Tokenize-a-string/Swift/tokenize-a-string-2.swift +++ b/Task/Tokenize-a-string/Swift/tokenize-a-string-2.swift @@ -1,5 +1,5 @@ let text = "Hello,How,Are,You,Today" -let tokens = split(text, { $0 == "," }) // for single-character separator -println(tokens) -let result = ".".join(tokens) -println(result) +let tokens = text.characters.split(",").map{String($0)} // for single-character separator +print(tokens) +let result = tokens.joinWithSeparator(".") +print(result) diff --git a/Task/Tokenize-a-string/Swift/tokenize-a-string-3.swift b/Task/Tokenize-a-string/Swift/tokenize-a-string-3.swift index 633cfeae98..be3201a174 100644 --- a/Task/Tokenize-a-string/Swift/tokenize-a-string-3.swift +++ b/Task/Tokenize-a-string/Swift/tokenize-a-string-3.swift @@ -1,5 +1,5 @@ -import Foundation - let text = "Hello,How,Are,You,Today" -let tokens = text.componentsSeparatedByString(",") -print(tokens) +let tokens = split(text, { $0 == "," }) // for single-character separator +println(tokens) +let result = ".".join(tokens) +println(result) diff --git a/Task/Tokenize-a-string/Swift/tokenize-a-string-4.swift b/Task/Tokenize-a-string/Swift/tokenize-a-string-4.swift new file mode 100644 index 0000000000..633cfeae98 --- /dev/null +++ b/Task/Tokenize-a-string/Swift/tokenize-a-string-4.swift @@ -0,0 +1,5 @@ +import Foundation + +let text = "Hello,How,Are,You,Today" +let tokens = text.componentsSeparatedByString(",") +print(tokens) diff --git a/Task/Tokenize-a-string/Zkl/tokenize-a-string.zkl b/Task/Tokenize-a-string/Zkl/tokenize-a-string.zkl new file mode 100644 index 0000000000..aca2dc7287 --- /dev/null +++ b/Task/Tokenize-a-string/Zkl/tokenize-a-string.zkl @@ -0,0 +1,2 @@ +"Hello,How,Are,You,Today".split(",").concat(".").println(); +Hello.How.Are.You.Today diff --git a/Task/Top-rank-per-group/Aime/top-rank-per-group.aime b/Task/Top-rank-per-group/Aime/top-rank-per-group.aime index c205a6d01b..4c9167462c 100644 --- a/Task/Top-rank-per-group/Aime/top-rank-per-group.aime +++ b/Task/Top-rank-per-group/Aime/top-rank-per-group.aime @@ -2,71 +2,54 @@ void Add_Employee(record employees, text name, text id, integer salary, text department) { - l_bill(r_n_list(employees, name), -1, name, id, salary, department); + employees[name] = l_effect(name, id, salary, department); } void collect(record top, record employees) { text name; + list l; - r_first(employees, name); - do { - list department, l; + for (name, l in employees) { + list department; + integer i, salary; - l_set(l, r_q_list(employees, name)); + department = r_v_list(top, l[3]); - if (r_key(top, l_q_text(l, 3))) { - integer i, salary; + salary = l[2]; + i = 0; + while (i < ~department) { + if (__list(department[i])[2] < salary) { + break; + } + i += 1; + } - l_set(department, r_q_list(top, l_q_text(l, 3))); + l_l_list(department, i, l); - salary = l_q_integer(l, 2); - i = 0; - while (i < l_length(department)) { - if (l_q_integer(l_q_list(department, i), 2) < salary) { - break; - } - i += 1; - } - - l_l_list(department, i, l); - - if (l_length(department) == N + 1) { - l_delete(department, N); - } - } else { - l_set(department, r_n_list(top, l_q_text(l, 3))); - l_l_list(department, 0, l); - } - } while (r_greater(employees, name, name)); + if (~department == N + 1) { + l_delete(department, N); + } + } } void print(record top) { text department; + list employees; - r_first(top, department); - do { - list employees; - integer i; + for (department, employees in top) { + integer i; + list l; - o_plan("Department ", department, "\n"); + o_plan("Department ", department, "\n"); - l_set(employees, r_q_list(top, department)); - i = 0; - while (i < l_length(employees)) { - list l; - - l_set(l, l_q_list(employees, i)); - - o_form(" ~ | ~ | ~\n", l_q_text(l, 0), l_q_text(l, 1), - l_q_integer(l, 2)); - - i += 1; - } - } while (r_greater(top, department, department)); + for (i, l in employees) { + o_form(" ~ | ~ | ~\n", l[0], l[1], l[2]); + } + } } integer diff --git a/Task/Top-rank-per-group/E/top-rank-per-group-1.e b/Task/Top-rank-per-group/E/top-rank-per-group-1.e deleted file mode 100644 index ba2eeb2231..0000000000 --- a/Task/Top-rank-per-group/E/top-rank-per-group-1.e +++ /dev/null @@ -1,39 +0,0 @@ -/** Turn a list of arrays into a list of maps with the given keys. */ -def addKeys(keys, rows) { - def res := [].diverge() - for row in rows { res.push(__makeMap.fromColumns(keys, row)) } - return res.snapshot() -} - -def data := addKeys( - ["name", "id", "salary", "dept"], - [["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"]]) - -def topSalaries(n, out) { - var groups := [].asMap() - for row in data { - def [=> salary, => dept] | _ := row - def top := groups.fetch(dept, fn {[]}).with([-salary, row]).sort() - groups with= (dept, top.run(0, top.size().min(n))) - } - for dept => group in groups.sortKeys() { - out.println(`Department $dept`) - out.println(`---------------`) - for [_, row] in group { - out.println(`${row["id"]} $$${row["salary"]} ${row["name"]}`) - } - out.println() - } -} diff --git a/Task/Top-rank-per-group/E/top-rank-per-group-2.e b/Task/Top-rank-per-group/E/top-rank-per-group-2.e deleted file mode 100644 index 5ed6e0c244..0000000000 --- a/Task/Top-rank-per-group/E/top-rank-per-group-2.e +++ /dev/null @@ -1,22 +0,0 @@ -? topSalaries(3, stdout) -Department D050 ---------------- -E21437 $47000 John Rappl -E41298 $21900 Nathan Adams - -Department D101 ---------------- -E00127 $53500 George Woltman -E04242 $41500 David McClellan -E10297 $32000 Tyler Bennett - -Department D190 ---------------- -E10001 $57000 Kim Arlich -E16398 $29900 Timothy Grove - -Department D202 ---------------- -E01234 $49500 Rich Holcomb -E39876 $27800 Claire Buckman -E27002 $19250 David Motsinger 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 ac07bbf953..188ffe0bea 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 @@ -1,18 +1,17 @@ -#import system. -#import system'collections. -#import system'routines. -#import extensions. -#import extensions'routines. -#import extensions'text. +import system'collections. +import system'routines. +import extensions. +import extensions'routines. +import extensions'text. -#class Employee +class Employee { - #field theName. - #field theID. - #field theSalary. - #field theDepartment. + object theName. + object theID. + object theSalary. + object theDepartment. - #constructor new &name:name &id:id &salary:salary &department:department + constructor new name:name id:id salary:salary department:department [ theName := name. theID := id. @@ -20,61 +19,61 @@ theDepartment := department. ] - #method Name = theName. + Name = theName. - #method Salary = theSalary. + Salary = theSalary. - #method Department = theDepartment. + Department = theDepartment. - #method literal - = StringWriter new - write:theName &paddingRight:25 - write:theID &paddingRight:12 - write:theSalary &paddingRight:12 + literal + = StringWriter new; + write:theName paddingRight:25; + write:theID paddingRight:12; + write(theSalary literal) paddingRight:12; write:theDepartment. } -#class(extension)reportOp +extension reportOp { - #method topNPerDepartment &n:n - = self group &by:x [ x Department ] select &each: x + topNPerDepartment:n + = self groupBy(:x)( x Department ); selectBy(:x) [ ^ { Department = x key. Employees - = x order &by:(:f:l)[ f Salary > l Salary ] top:n summarize:(ArrayList new). + = x orderBy(:f:l)( f Salary > l Salary ); top:n; summarize(ArrayList new). }. ]. } -#symbol program = +program = [ - #var employees := + var employees := ( - Employee new &name:"Tyler Bennett" &id:"E10297" &salary:32000 &department:"D101", - Employee new &name:"John Rappl" &id:"E21437" &salary:47000 &department:"D050", - Employee new &name:"George Woltman" &id:"E00127" &salary:53500 &department:"D101", - Employee new &name:"Adam Smith" &id:"E63535" &salary:18000 &department:"D202", - Employee new &name:"Claire Buckman" &id:"E39876" &salary:27800 &department:"D202", - Employee new &name:"David McClellan" &id:"E04242" &salary:41500 &department:"D101", - Employee new &name:"Rich Holcomb" &id:"E01234" &salary:49500 &department:"D202", - Employee new &name:"Nathan Adams" &id:"E41298" &salary:21900 &department:"D050", - Employee new &name:"Richard Potter" &id:"E43128" &salary:15900 &department:"D101", - Employee new &name:"David Motsinger" &id:"E27002" &salary:19250 &department:"D202", - Employee new &name:"Tim Sampair" &id:"E03033" &salary:27000 &department:"D101", - Employee new &name:"Kim Arlich" &id:"E10001" &salary:57000 &department:"D190", - Employee new &name:"Timothy Grove" &id:"E16398" &salary:29900 &department:"D190" + Employee new name:"Tyler Bennett" id:"E10297" salary:32000 department:"D101", + Employee new name:"John Rappl" id:"E21437" salary:47000 department:"D050", + Employee new name:"George Woltman" id:"E00127" salary:53500 department:"D101", + Employee new name:"Adam Smith" id:"E63535" salary:18000 department:"D202", + Employee new name:"Claire Buckman" id:"E39876" salary:27800 department:"D202", + Employee new name:"David McClellan" id:"E04242" salary:41500 department:"D101", + Employee new name:"Rich Holcomb" id:"E01234" salary:49500 department:"D202", + Employee new name:"Nathan Adams" id:"E41298" salary:21900 department:"D050", + Employee new name:"Richard Potter" id:"E43128" salary:15900 department:"D101", + Employee new name:"David Motsinger" id:"E27002" salary:19250 department:"D202", + Employee new name:"Tim Sampair" id:"E03033" salary:27000 department:"D101", + Employee new name:"Kim Arlich" id:"E10001" salary:57000 department:"D190", + Employee new name:"Timothy Grove" id:"E16398" salary:29900 department:"D190" ). - employees topNPerDepartment &n:2 run &each:info + employees topNPerDepartment:2; forEach(:info) [ - console writeLine:"Department: ":(info Department). + console printLine("Department: ",info Department). - info Employees run &each:printingLn. + info Employees; forEach:printingLn. - console writeLine:"---------------------------------------------". + console writeLine:"---------------------------------------------" ]. - console readChar. + console readChar ]. diff --git a/Task/Top-rank-per-group/Fortran/top-rank-per-group-1.f b/Task/Top-rank-per-group/Fortran/top-rank-per-group-1.f new file mode 100644 index 0000000000..4978fdde45 --- /dev/null +++ b/Task/Top-rank-per-group/Fortran/top-rank-per-group-1.f @@ -0,0 +1,4 @@ + DATA EMPLOYEE(1:3)/ + 1 GRIST("Tyler Bennett","E10297",32000,"D101"), + 2 GRIST("John Rappl","E21437",47000,"D050"), + 3 GRIST("George Woltman","E00127",53500,"D101")/ diff --git a/Task/Top-rank-per-group/Fortran/top-rank-per-group-2.f b/Task/Top-rank-per-group/Fortran/top-rank-per-group-2.f new file mode 100644 index 0000000000..ca84145ca6 --- /dev/null +++ b/Task/Top-rank-per-group/Fortran/top-rank-per-group-2.f @@ -0,0 +1,68 @@ + PROGRAM TOP RANK !Just do it. + CHARACTER*28 HEADING(4) !The first line is a header. + TYPE GRIST !But this is the stuff. + CHARACTER*28 NAME !Arbitrary sizes. + CHARACTER*6 ID !Possibly imperfect. + REAL*8 SALARY !Single precision is a bit thin. + CHARACTER*6 DEPARTMENT !Not a number. + END TYPE GRIST !So much for the aggregate. + INTEGER HORDE !Some parameterisation. + PARAMETER (HORDE = 66) !This should suffice. + TYPE(GRIST) EMPLOYEE(HORDE),HIC !An extra for the sort. + LOGICAL CURSE !Possible early completion. + INTEGER I,N,H !Steppers. + INTEGER II,R !Needed for the results. + INTEGER KBD,MSG,IN !I/O unit numbers. + + KBD = 5 !Standard input. + MSG = 6 !Standard output. + IN = 10 !Suitable for an input file. + WRITE (MSG,1) + 1 FORMAT ("Reads a set of employee information from TopRank.csv"/ + 1"Then for each department code, shows the N highest paid.") + OPEN (IN,NAME = "TopRank.csv",FORM = "FORMATTED") + READ (IN,*) HEADING !Column headings: the "Salary" heading is not numeric. +Chug through the input. + N = 0 !None so far. + 10 READ (IN,*,END = 20) EMPLOYEE(N + 1) !Get the next record. + N = N + 1 !We did. Count it in. + IF (N.GT.HORDE) STOP "Too many employee records!" !Ah, suspicion. + GO TO 10 !Perhaps there will be another. +Collate the collection. + 20 CLOSE(IN) !Finished with the input. +Crank up a comb sort, which requires only one comparison statement. Especially good for compound fields. + H = N - 1 !Last - first, and not + 1. + 21 H = MAX(1,H*10/13) !The special feature. + CURSE = .FALSE. !So far, so good. + DO I = N - H,1,-1 !If H = 1, this is a Bubblesort. + IF (EMPLOYEE(I).DEPARTMENT.LT.EMPLOYEE(I + H).DEPARTMENT) CYCLE !In order by department. + IF (EMPLOYEE(I).DEPARTMENT.EQ.EMPLOYEE(I + H).DEPARTMENT !Or, Equal department, + * .AND. EMPLOYEE(I).SALARY.GT.EMPLOYEE(I + H).SALARY) CYCLE !And in decreasing order by salary. + CURSE = .TRUE. !No escape. the elements are in the wrong order. + HIC = EMPLOYEE(I) !So a SWAP statement would be good. But alas. + EMPLOYEE(I) = EMPLOYEE(I + H) !For large data aggregates, an indexed sort would be good. + EMPLOYEE(I + H) = HIC !But, just slog away. + END DO !Consider the next pairing. + IF (CURSE .OR. H.GT.1) GO TO 21 !Work remains? + +Cast forth results. + 30 WRITE (6,31) N !Announce, and solicit a parameter. + 31 FORMAT (I0," employees. How many per dept? ",$) !The $ sez "don't start a new line." + READ (KBD,*) R !The parameter. + IF (R.LE.0) STOP !bah. + WRITE (MSG,32) "Rank",HEADING + 32 FORMAT (/,A6,1X,A28,2X,A12,1X,A10,A) !Compare to FORMAT 33. + HIC.DEPARTMENT = "...Not this" !Different from all departmental codes. + DO I = 1,N !Scan the sorted data. + IF (HIC.DEPARTMENT.EQ.EMPLOYEE(I).DEPARTMENT) THEN !Another? + II = II + 1 !Same department, so count another adherent. + ELSE !But with a change of department code, + II = 1 !Start a fresh count. + HIC.DEPARTMENT = EMPLOYEE(I).DEPARTMENT !And remember the new code. + WRITE (MSG,*) "For ",HIC.DEPARTMENT !Announce the new department's code. + END IF !So much for grouping. + IF (II.LE.R) WRITE (MSG,33) II,EMPLOYEE(I) !Still within the desired rank? + 33 FORMAT (I6,1X,A28,1X,A12,F11.2,1X,A) !Some layout. Includes the repeated departmental code name. + END DO !On to the next. + + END !That was straightforward. diff --git a/Task/Top-rank-per-group/Haskell/top-rank-per-group-1.hs b/Task/Top-rank-per-group/Haskell/top-rank-per-group-1.hs new file mode 100644 index 0000000000..1c8fa6f3c1 --- /dev/null +++ b/Task/Top-rank-per-group/Haskell/top-rank-per-group-1.hs @@ -0,0 +1,79 @@ +import Data.List (sortBy, groupBy) + +import Text.Printf (printf) + +import Data.Ord (comparing) + +import Data.Function (on) + +type ID = Int + +type DEP = String + +type NAME = String + +type SALARY = Double + +data Employee = Employee + { nr :: ID + , dep :: DEP + , name :: NAME + , sal :: SALARY + } + +employees :: [Employee] +employees = + fmap + (\(i, d, n, s) -> Employee i d n s) + [ (1001, "AB", "Janssen A.H.", 41000) + , (101, "KA", "'t Woud B.", 45000) + , (1013, "AB", "de Bont C.A.", 65000) + , (1101, "CC", "Modaal A.M.J.", 30000) + , (1203, "AB", "Anders H.", 50000) + , (100, "KA", "Ezelbips P.J.", 52000) + , (1102, "CC", "Zagt A.", 33000) + , (1103, "CC", "Ternood T.R.", 21000) + , (1104, "CC", "Lageln M.", 23000) + , (1105, "CC", "Amperwat A.", 19000) + , (1106, "CC", "Boon T.J.", 25000) + , (1107, "CC", "Beloop L.O.", 31000) + , (1009, "CD", "Janszoon A.", 38665) + , (1026, "CD", "Janszen H.P.", 41000) + , (1011, "CC", "de Goeij J.", 39000) + , (106, "KA", "Pragtweik J.M.V.", 42300) + , (111, "KA", "Bakeuro S.", 31000) + , (105, "KA", "Clubdrager C.", 39800) + , (104, "KA", "Karendijk F.", 23000) + , (107, "KA", "Centjes R.M.", 34000) + , (119, "KA", "Tegenstroom H.L.", 39000) + , (1111, "CD", "Telmans R.M.", 55500) + , (1093, "AB", "de Slegte S.", 46987) + , (1199, "CC", "Uitlaat G.A.S.", 44500) + ] + +firstN :: Int + -> (Employee -> DEP) + -> (Employee -> SALARY) + -> [Employee] + -> [[Employee]] +firstN n o1 o2 x = + fmap + (take n . sortBy (comparingDown o2)) + (groupBy (groupingOn o1) (sortBy (comparing o1) x)) + +groupingOn + :: Eq a1 + => (a -> a1) -> a -> a -> Bool +groupingOn = ((==) `on`) + +comparingDown + :: Ord a + => (b -> a) -> b -> b -> Ordering +comparingDown = flip . comparing + +main :: IO () +main = do + printf "%-16s %3s %10s\n" "NAME" "DEP" "TIP" + putStrLn $ replicate 31 '=' + mapM_ (traverse ((printf "%-16s %3s %10.2g\n" . name) <*> dep <*> sal)) $ + firstN 3 dep sal employees diff --git a/Task/Top-rank-per-group/Haskell/top-rank-per-group-2.hs b/Task/Top-rank-per-group/Haskell/top-rank-per-group-2.hs new file mode 100644 index 0000000000..c573ffd1c8 --- /dev/null +++ b/Task/Top-rank-per-group/Haskell/top-rank-per-group-2.hs @@ -0,0 +1,80 @@ +import qualified Data.Map as M + +import Data.Ord (comparing) +import Control.Monad (join) +import Data.Maybe (fromJust) +import Data.List (nub, sortBy, sort, intercalate, transpose) + +mapNames, mapDepts :: M.Map Int String +[mapNames, mapDepts] = pure readPairs <*> [nameKV, deptKV] <*> [xs] + +mapSalaries :: M.Map Int Int +mapSalaries = readPairs salaryKV xs + +highSalaryKeys :: Int -> String -> [(Int, Int)] +highSalaryKeys n dept = + take n $ + sortBy ((flip . comparing) snd) $ + (,) <*> (fromJust . flip M.lookup mapSalaries) <$> + M.keys (M.filter (== dept) mapDepts) + +reportLines :: String -> [(Int, Int)] -> [[String]] +reportLines dept = + fmap (\(k, n) -> [fromJust $ M.lookup k mapNames, dept, show n]) + +xs :: [(Int, String, String, Int)] +xs = + [ (1001, "AB", "Janssen A.H.", 41000) + , (101, "KA", "'t Woud B.", 45000) + , (1013, "AB", "de Bont C.A.", 65000) + , (1101, "CC", "Modaal A.M.J.", 30000) + , (1203, "AB", "Anders H.", 50000) + , (100, "KA", "Ezelbips P.J.", 52000) + , (1102, "CC", "Zagt A.", 33000) + , (1103, "CC", "Ternood T.R.", 21000) + , (1104, "CC", "Lageln M.", 23000) + , (1105, "CC", "Amperwat A.", 19000) + , (1106, "CC", "Boon T.J.", 25000) + , (1107, "CC", "Beloop L.O.", 31000) + , (1009, "CD", "Janszoon A.", 38665) + , (1026, "CD", "Janszen H.P.", 41000) + , (1011, "CC", "de Goeij J.", 39000) + , (106, "KA", "Pragtweik J.M.V.", 42300) + , (111, "KA", "Bakeuro S.", 31000) + , (105, "KA", "Clubdrager C.", 39800) + , (104, "KA", "Karendijk F.", 23000) + , (107, "KA", "Centjes R.M.", 34000) + , (119, "KA", "Tegenstroom H.L.", 39000) + , (1111, "CD", "Telmans R.M.", 55500) + , (1093, "AB", "de Slegte S.", 46987) + , (1199, "CC", "Uitlaat G.A.S.", 44500) + ] + +readPairs + :: Ord k + => (a1 -> (k, a)) -> [a1] -> M.Map k a +readPairs f xs = M.fromList $ f <$> xs + +nameKV, deptKV :: (Int, String, String, Int) -> (Int, String) +nameKV (k, _, name, _) = (k, name) + +deptKV (k, dept, _, _) = (k, dept) + +salaryKV :: (Int, String, String, Int) -> (Int, Int) +salaryKV (k, _, _, salary) = (k, salary) + +table :: String -> [[String]] -> [String] +table delim rows = + let justifyLeft c n s = take n (s ++ replicate n c) + justifyRight c n s = drop (length s) (replicate n c ++ s) + in intercalate delim <$> + transpose + ((fmap =<< justifyLeft ' ' . maximum . fmap length) <$> transpose rows) + +main :: IO () +main = + (putStrLn . unlines) + (table + " " + (join + (reportLines <*> highSalaryKeys 3 <$> (sort . nub) (M.elems mapDepts)))) diff --git a/Task/Top-rank-per-group/Haskell/top-rank-per-group.hs b/Task/Top-rank-per-group/Haskell/top-rank-per-group.hs deleted file mode 100644 index 685918d44b..0000000000 --- a/Task/Top-rank-per-group/Haskell/top-rank-per-group.hs +++ /dev/null @@ -1,45 +0,0 @@ -import Data.List -import Control.Monad -import Control.Arrow -import Text.Printf -import Data.Ord -import Data.Function - -groupingOn = ((==) `on`) -comparingDwn = flip . comparing - - -type ID = Int -type DEP = String -type NAME = String -type SALARY = Double -data Employee = Employee {nr :: ID, dep :: DEP, name :: NAME, sal :: SALARY} - -employees :: [Employee] -employees = map (\(i,d,n,s) -> Employee i d n s) - [(1001,"AB","Janssen A.H.",41000), (101,"KA","'t Woud B.",45000), - (1013,"AB","de Bont C.A.",65000), (1101,"CC","Modaal A.M.J.",30000), - (1203,"AB","Anders H.",50000), (100,"KA","Ezelbips P.J.",52000), - (1102,"CC","Zagt A.",33000), (1103,"CC","Ternood T.R.",21000), - (1104,"CC","Lageln M.",23000), (1105,"CC","Amperwat A.",19000), - (1106,"CC","Boon T.J.",25000), (1107,"CC","Beloop L.O.",31000), - (1009,"CD","Janszoon A.",38665), (1026,"CD","Janszen H.P.",41000), - (1011,"CC","de Goeij J.",39000), (106,"KA","Pragtweik J.M.V.",42300), - (111,"KA","Bakeuro S.",31000), (105,"KA","Clubdrager C.",39800), - (104,"KA","Karendijk F.",23000), (107,"KA","Centjes R.M.",34000), - (119,"KA","Tegenstroom H.L.",39000), (1111,"CD","Telmans R.M.",55500), - (1093,"AB","de Slegte S.",46987), (1199,"CC","Uitlaat G.A.S.",44500) - ] - -dorank :: Int -> - (Employee -> DEP) -> - (Employee -> SALARY) -> - [Employee]-> [[Employee]] -dorank n o1 o2 = map (take n. sortBy (comparingDwn o2)) - . groupBy (groupingOn o1) . sortBy (comparing o1) - -toprank :: IO () -toprank = do - printf "%-16s %3s %10s\n" "NAME" "DEP" "TIP" - putStrLn $ replicate 31 '=' - mapM_ (mapM_ (ap (ap (printf "%-16s %3s %10.2g\n" . name) dep) sal)) $ dorank 3 dep sal employees diff --git a/Task/Top-rank-per-group/JavaScript/top-rank-per-group-3.js b/Task/Top-rank-per-group/JavaScript/top-rank-per-group-3.js new file mode 100644 index 0000000000..28ba177e71 --- /dev/null +++ b/Task/Top-rank-per-group/JavaScript/top-rank-per-group-3.js @@ -0,0 +1,158 @@ +(() => { + 'use strict'; + + // topNSalariesPerDept :: Int -> [[String]] -> [String] + const topNSalariesPerDept = (n, records) => + foldl( + (a, k, i) => (a[toLower(k)] = x => x[i], a), + this, + head(records) + ) && map(intercalate(','), + concatMap(take(n), + reverse( + groupBy( + on(same, department), + sortBy( + flip( + mappendComparing([ + department, + salary + ]) + ), + tail(records) + ) + ) + ) + ) + ); + + // GENERIC FUNCTIONS ----------------------------------------------------- + + // comparing :: (a -> b) -> (a -> a -> Ordering) + const comparing = f => + (x, y) => { + const + a = f(x), + b = f(y); + return a < b ? -1 : (a > b ? 1 : 0); + }; + + // concatMap :: (a -> [b]) -> [a] -> [b] + const concatMap = (f, xs) => + xs.length > 0 ? (() => { + const unit = typeof xs[0] === 'string' ? '' : []; + return unit.concat.apply(unit, xs.map(f)); + })() : []; + + // curry :: Function -> Function + const curry = (f, ...args) => { + const go = xs => xs.length >= f.length ? (f.apply(null, xs)) : + function () { + return go(xs.concat(Array.from(arguments))); + }; + return go([].slice.call(args, 1)); + }; + + // flip :: (a -> b -> c) -> b -> a -> c + const flip = f => (a, b) => f.apply(null, [b, a]); + + // foldl :: (b -> a -> b) -> b -> [a] -> b + const foldl = (f, a, xs) => xs.reduce(f, a); + + // groupBy :: (a -> a -> Bool) -> [a] -> [[a]] + const groupBy = (f, xs) => { + const dct = xs.slice(1) + .reduce((a, x) => { + const + h = a.active.length > 0 ? a.active[0] : undefined, + blnGroup = h !== undefined && f(h, x); + return { + active: blnGroup ? a.active.concat([x]) : [x], + sofar: blnGroup ? a.sofar : a.sofar.concat([a.active]) + }; + }, { + active: xs.length > 0 ? [xs[0]] : [], + sofar: [] + }); + return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []); + }; + + // head :: [a] -> a + const head = xs => xs.length ? xs[0] : undefined; + + // intercalate :: String -> [a] -> String + const intercalate = curry((s, xs) => xs.join(s)); + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // mappendComparing :: [(a -> b)] -> (a -> a -> Ordering) + const mappendComparing = fs => (x, y) => + fs.reduce((ord, f) => (ord !== 0) ? ( + ord + ) : (() => { + const + a = f(x), + b = f(y); + return a < b ? -1 : a > b ? 1 : 0 + })(), 0); + + // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c + const on = (f, g) => (a, b) => f(g(a), g(b)); + + // reverse :: [a] -> [a] + const reverse = xs => + typeof xs === 'string' ? ( + xs.split('') + .reverse() + .join('') + ) : xs.slice(0) + .reverse(); + + // same :: a -> a -> Bool + const same = (a, b) => a === b + + // show :: Int -> a -> Indented String + // show :: a -> String + const show = (...x) => + JSON.stringify.apply( + null, x.length > 1 ? [x[1], null, x[0]] : x + ); + + // sortBy :: (a -> a -> Ordering) -> [a] -> [a] + const sortBy = (f, xs) => + xs.slice() + .sort(f); + + // tail :: [a] -> [a] + const tail = xs => xs.length ? xs.slice(1) : undefined; + + // take :: Int -> [a] -> [a] + const take = curry((n, xs) => xs.slice(0, n)); + + // toLower :: Text -> Text + const toLower = s => s.toLowerCase(); + + // TEST ------------------------------------------------------------------ + + const xs = [ + ["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"] + ]; + + return show(2, + topNSalariesPerDept(3, xs) + ); +})(); diff --git a/Task/Top-rank-per-group/jq/top-rank-per-group-1.jq b/Task/Top-rank-per-group/Jq/top-rank-per-group-1.jq similarity index 100% rename from Task/Top-rank-per-group/jq/top-rank-per-group-1.jq rename to Task/Top-rank-per-group/Jq/top-rank-per-group-1.jq diff --git a/Task/Top-rank-per-group/jq/top-rank-per-group-2.jq b/Task/Top-rank-per-group/Jq/top-rank-per-group-2.jq similarity index 100% rename from Task/Top-rank-per-group/jq/top-rank-per-group-2.jq rename to Task/Top-rank-per-group/Jq/top-rank-per-group-2.jq diff --git a/Task/Top-rank-per-group/jq/top-rank-per-group-3.jq b/Task/Top-rank-per-group/Jq/top-rank-per-group-3.jq similarity index 100% rename from Task/Top-rank-per-group/jq/top-rank-per-group-3.jq rename to Task/Top-rank-per-group/Jq/top-rank-per-group-3.jq 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.julia new file mode 100644 index 0000000000..e0e90eaf40 --- /dev/null +++ b/Task/Top-rank-per-group/Julia/top-rank-per-group.julia @@ -0,0 +1,58 @@ +# v0.6.0 + +using DataFrames + +df = DataFrame( +EmployeeName=["Tyler Bennett", "John Rappl", "George Woltman", "Adam Smith", +"Claire Buckman", "David McClellan", "Rich Holcomb", "Nathan Adams", +"Richard Potter", "David Motsinger", "Tim Sampair", "Kim Arlich", "Timothy Grove"], +EmployeeID = ["E10297", "E21437", "E00127", "E63535", "E39876", "E04242", +"E01234", "E41298", "E43128", "E27002", "E03033", "E10001", "E16398"], +Salary = [32000, 47000, 53500, 18000, 27800, 41500, 49500, 21900, 15900, 19250, +27000, 57000, 29900], +Department = ["D101", "D050", "D101", "D202", "D202", "D101", "D202", "D050", +"D101", "D202", "D101", "D190", "D190"]) + +# To get only values +function firstnby(n::Int, y::Array, by::Array) + # Check that each value belong to one and one only class + if length(y) != length(by); error("y and by must have the same length"); end + + # Initialize resulting dictionary + rst = Dict{eltype(by), Array{eltype(y)}}() + + # For each class... + for cl in unique(by) + # ...select the values of that class... + i = find(x -> x == cl, by) + # ...sort them and store them in result... + rst[cl] = sort(y[i]; rev=true) + # ...if length is greater than n select only first n elements + if length(i) > n + rst[cl] = rst[cl][1:n] + end + end + return rst +end + +for (cl, val) in firstnby(3, Array(df[:Salary]), Array(df[:Department])) + println("$cl => $val") +end + +# To get the full row... +function firstnby(n::Int, df::DataFrame, y::Symbol, by::Symbol) + rst = Dict{eltype(df[by]), DataFrame}() + + for cl in unique(df[by]) + i = find(x -> x == cl, df[by]) + rst[cl] = sort(df[i, :]; cols=order(y; rev=true)) + if length(i) > n + rst[cl] = rst[cl][1:n, :] + end + end + return rst +end + +for (cl, data) in firstnby(3, df, :Salary, :Department) + println("\n$cl:\n$data") +end 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.kotlin new file mode 100644 index 0000000000..53f8e69435 --- /dev/null +++ b/Task/Top-rank-per-group/Kotlin/top-rank-per-group.kotlin @@ -0,0 +1,31 @@ +// version 1.1.2 + +data class Employee(val name: String, val id: String, val salary: Int, val dept: String) + +const val N = 2 //say + +fun main(args: Array) { + val employees = listOf( + Employee("Tyler Bennett", "E10297", 32000, "D101"), + Employee("John Rappl", "E21437", 47000, "D050"), + Employee("George Woltman" , "E00127", 53500, "D101"), + Employee("Adam Smith", "E63535", 18000, "D202"), + Employee("Claire Buckman", "E39876", 27800, "D202"), + Employee("David McClellan", "E04242", 41500, "D101"), + Employee("Rich Holcomb", "E01234", 49500, "D202"), + Employee("Nathan Adams", "E41298", 21900, "D050"), + Employee("Richard Potter", "E43128", 15900, "D101"), + Employee("David Motsinger", "E27002", 19250, "D202"), + Employee("Tim Sampair", "E03033", 27000, "D101"), + Employee("Kim Arlich", "E10001", 57000, "D190"), + Employee("Timothy Grove", "E16398", 29900, "D190") + ) + val employeesByDept = employees.sortedBy { it.dept }.groupBy { it.dept } + println("Highest $N salaries by department:\n") + for ((key, value) in employeesByDept) { + val topRanked = value.sortedByDescending { it.salary }.take(N) + println("Dept $key => ") + for (i in 0 until N) with (topRanked[i]) { println("${name.padEnd(15)} $id $salary") } + println() + } +} diff --git a/Task/Top-rank-per-group/Phix/top-rank-per-group.phix b/Task/Top-rank-per-group/Phix/top-rank-per-group.phix new file mode 100644 index 0000000000..9d7a856be2 --- /dev/null +++ b/Task/Top-rank-per-group/Phix/top-rank-per-group.phix @@ -0,0 +1,41 @@ +constant N=3 + +-- Employee Name,Employee ID,Salary,Department +enum /*NAME,*/ /*ID,*/ SAL=3, DEPT=4 +constant employees = {{"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"}} + +function by_dept_sal(integer i, integer j) + return compare(employees[i][DEPT]&-employees[i][SAL], + employees[j][DEPT]&-employees[j][SAL]) +end function + +sequence tags = custom_sort(routine_id("by_dept_sal"),tagset(length(employees))) + +string lastdep = "" +integer dcount = 0 +printf(1,"Top %d salaries by department\n",{N}) +for i=1 to length(employees) do + object emp = employees[tags[i]] + if emp[DEPT]!=lastdep then + lastdep = emp[DEPT] + dcount = 1 + printf(1,"\n") + else + dcount += 1 + end if + if dcount<=N then + ?emp + end if +end for diff --git a/Task/Top-rank-per-group/Sidef/top-rank-per-group.sidef b/Task/Top-rank-per-group/Sidef/top-rank-per-group.sidef index 0cee623b93..289cefadda 100644 --- a/Task/Top-rank-per-group/Sidef/top-rank-per-group.sidef +++ b/Task/Top-rank-per-group/Sidef/top-rank-per-group.sidef @@ -1,4 +1,4 @@ -var data = <<'EOF'.lines.map{ (var h = Hash()){} = .split(',')...; h } +var data = <<'EOF'.lines.map{ ~Z .split(',') -> flat.to_h } Tyler Bennett,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 @@ -14,15 +14,14 @@ Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190 EOF -var n = (ARGV ? ARGV[0].to_i : "usage: #{__MAIN__} [n]\n".die); +var n = (ARGV ? Num(ARGV[0]) : "usage: #{__MAIN__} [n]\n".die) -data.map {|h| h{:dept} }.uniq.sort.each { |d| - var es = data.grep { _{:dept} == d }.sort_by{ _{:salary}.to_num }.reverse; - say d; +for d in (data.map {|h| h{:dept} }.uniq.sort) { + var es = data.grep { _{:dept} == d }.sort_by { -Num(_{:salary}) } + say d n.times { - es || break; - var e = es.shift; - printf("%-15s | %-6s | %5d\n", e{%w(name id salary)}); + es || break + printf("%-15s | %-6s | %5d\n", es.shift(){...}) } - print "\n"; + print "\n" } diff --git a/Task/Top-rank-per-group/Stata/top-rank-per-group.stata b/Task/Top-rank-per-group/Stata/top-rank-per-group.stata new file mode 100644 index 0000000000..547b520670 --- /dev/null +++ b/Task/Top-rank-per-group/Stata/top-rank-per-group.stata @@ -0,0 +1,3 @@ +import delimited employees.csv +local k 2 +bysort department (salary): list salary if _N-_n<`k' diff --git a/Task/Top-rank-per-group/Zkl/top-rank-per-group.zkl b/Task/Top-rank-per-group/Zkl/top-rank-per-group.zkl new file mode 100644 index 0000000000..bdcd1d44c3 --- /dev/null +++ b/Task/Top-rank-per-group/Zkl/top-rank-per-group.zkl @@ -0,0 +1,14 @@ +fcn setAppend(d,[(key,data)]){ d[key]=d.find(key,T).append(data) } //-->(key,(data,data...)) + +fcn topNsalaries(n){ + File("data.txt").pump(setAppend.fp(data:=D()),fcn(line){ //-->Dictionary(dept:salaries) + line=line.strip().split(","); + T(line[-1],line[-2]); //-->(dept,salary) + }); + dss:=data.pump(List,fcn([(dept,ss)],N){ //-->(dept,(salaries), dept...) + T(dept).append(ss.sort()[-N,*].reverse()); + }.fp1(n)).sort(fcn(a,b){a[0] {9, 1.732050807569} +end run + + +-- square :: Num a => a -> a +on square(x) + x * x +end square + +-- squareRoot :: Num a, Float b => a -> b +on squareRoot(x) + x ^ 0.5 +end squareRoot + + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- A list of functions applied to a list of arguments +-- (<*> | ap) :: [(a -> b)] -> [a] -> [b] +on ap(fs, xs) + set intFs to length of fs + set intXs to length of xs + set lst to {} + repeat with i from 1 to intFs + tell mReturn(item i of fs) + repeat with j from 1 to intXs + set end of lst to |λ|(contents of (item j of xs)) + end repeat + end tell + end repeat + return lst +end ap + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn diff --git a/Task/Topic-variable/AppleScript/topic-variable-2.applescript b/Task/Topic-variable/AppleScript/topic-variable-2.applescript new file mode 100644 index 0000000000..e61cabf113 --- /dev/null +++ b/Task/Topic-variable/AppleScript/topic-variable-2.applescript @@ -0,0 +1,51 @@ +on run + script + -- The given function applied to the value 3 + on |λ|(f) + mReturn(f)'s |λ|(3) + end |λ| + end script + + -- Here, 'result' is bound to the script above + map(result, {square, squareRoot}) + + --> {9, 1.732050807569} +end run + + +-- square :: Num a => a -> a +on square(x) + x * x +end square + +-- squareRoot :: Num a, Float b => a -> b +on squareRoot(x) + x ^ 0.5 +end squareRoot + + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn diff --git a/Task/Topic-variable/Haskell/topic-variable.hs b/Task/Topic-variable/Haskell/topic-variable.hs new file mode 100644 index 0000000000..ed39a46029 --- /dev/null +++ b/Task/Topic-variable/Haskell/topic-variable.hs @@ -0,0 +1,4 @@ +Prelude> [1..10] +[1,2,3,4,5,6,7,8,9,10] +Prelude> map (^2) it +[1,4,9,16,25,36,49,64,81,100] diff --git a/Task/Topic-variable/Julia/topic-variable.julia b/Task/Topic-variable/Julia/topic-variable.julia new file mode 100644 index 0000000000..1a409f5f43 --- /dev/null +++ b/Task/Topic-variable/Julia/topic-variable.julia @@ -0,0 +1,4 @@ +julia> 3 +3 +julia> ans * ans, ans - 1 +(9, 2) diff --git a/Task/Topic-variable/Kotlin/topic-variable.kotlin b/Task/Topic-variable/Kotlin/topic-variable.kotlin new file mode 100644 index 0000000000..155104b3c6 --- /dev/null +++ b/Task/Topic-variable/Kotlin/topic-variable.kotlin @@ -0,0 +1,9 @@ +// version 1.1.2 + +fun main(args: Array) { + 3.let { + println(it) + println(it * it) + println(Math.sqrt(it.toDouble())) + } +} diff --git a/Task/Topic-variable/Ring/topic-variable.ring b/Task/Topic-variable/Ring/topic-variable.ring new file mode 100644 index 0000000000..24d6921a64 --- /dev/null +++ b/Task/Topic-variable/Ring/topic-variable.ring @@ -0,0 +1,9 @@ +see "sum1 = " + sum1(1,2) + nl +see "sum2 = " + sum2(2,3) + nl + +func sum1 (x, y) + sum = x + y + return sum + +func sum2 (x, y) + return x + y diff --git a/Task/Topic-variable/Zkl/topic-variable.zkl b/Task/Topic-variable/Zkl/topic-variable.zkl new file mode 100644 index 0000000000..8db3348827 --- /dev/null +++ b/Task/Topic-variable/Zkl/topic-variable.zkl @@ -0,0 +1,5 @@ +a,_,c:=List(1,2,3,4,5,6) //-->a=1, c=3, here _ is used as "ignore" +3.0 : _.sqrt() : println(_) //-->"1.73205", _ (and :) is used to "explode" a computation + // as syntactic sugar +1.0 + 2 : _.sqrt() : _.pow(4) // no variables used, the compiler "implodes" the computation + // --> 9 diff --git a/Task/Topological-sort/C++/topological-sort.cpp b/Task/Topological-sort/C++/topological-sort.cpp index 545a1175f2..ff39745af7 100644 --- a/Task/Topological-sort/C++/topological-sort.cpp +++ b/Task/Topological-sort/C++/topological-sort.cpp @@ -1,93 +1,187 @@ -#include -#include -#include -#include -#include +#include +#include -using namespace std; - -string input = { - "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\n" - "cycle_11 cycle_12\n" - "cycle_12 cycle_11\n" - "cycle_21 dw01 cycle_22 dw02 dw03\n" - "cycle_22 cycle_21 dw01 dw04" }; - -class TopSort { - - public: - TopSort(const string& input){ - stringstream ss(input); - string buf; - - while(getline(ss, buf)){ - stringstream ls(buf); - string target, subtarget; - ls >> target; - - while(ls >> subtarget){ - if(target.compare(subtarget) == 0) - continue; - - dependencies.emplace(subtarget, 0); - parents[subtarget].push_back(target); - ++dependencies[target]; - } - } - } - - void solve(){ - for(const auto& pair : dependencies) - if(pair.second == 0) - sorted.push_back(pair.first); - - for(unsigned int i = 0; i < sorted.size(); ++i){ - string target = sorted[i]; - - for(string& parent : parents[target]) - if(--dependencies[parent] == 0) - sorted.push_back(parent); - } - - for(const auto& pair : dependencies) - if(pair.second != 0) - unorderable.push_back(pair.first); - } - - friend ostream& operator<<(ostream& os, const TopSort& ts) { - for(const string& s : ts.sorted) - os << s << endl; - if(ts.unorderable.size() > 0){ - cout << "Unorderable:" << endl; - for(const string& s : ts.unorderable) - os << s << endl; - } - return os; - } - - private: - - vector sorted; - vector unorderable; - - unordered_map dependencies; - unordered_map> parents; +template +class topological_sorter +{ +protected: + struct relations + { + std::size_t + dependencies; + std::set + dependents; + }; + std::map + map; +public: + void + add_goal(Goal const& goal) + { + map[goal]; + } + void + add_dependency(Goal const& goal, Goal const& dependency) + { + if(dependency == goal) + return; + auto& + dependents = map[dependency].dependents; + if(dependents.find(goal) == dependents.end()) + { + dependents.insert(goal); + ++map[goal].dependencies; + } + } + template + void + add_dependencies(Goal const& goal, Container const& dependencies) + { + for(auto const& dependency : dependencies) + add_dependency(goal, dependency); + } + template + void + destructive_sort(ResultContainer& sorted, CyclicContainer& unsortable) + { + sorted.clear(); + unsortable.clear(); + for(auto const& lookup : map) + { + auto const& + goal = lookup.first, + relations = lookup.second; + if(relations.dependencies == 0) + sorted.push_back(goal); + } + for(std::size_t index = 0; index < sorted.size(); ++index) + for(auto const& goal : map[sorted[index]].dependents) + if(--map[goal].dependencies == 0) + sorted.push_back(goal); + for(auto const& lookup : map) + { + auto const& + goal = lookup.first, + relations = lookup.second; + if(relations.dependencies != 0) + unsortable.push_back(goal); + } + } + template + void + sort(ResultContainer& sorted, CyclicContainer& unsortable) + { + topological_sorter + temporary = *this; + temporary.destructive_sort(sorted, unsortable); + } + void + clear() + { + map.clear(); + } }; -int main () { - TopSort ts(input); - ts.solve(); - cout << ts; +/* + Example usage with text strings +*/ + +#include +#include +#include +#include +#include + +using namespace + std; + +void + display_heading(string const& message) +{ + cout << endl << "~ " << message << " ~" << endl; +} +void + display_results(string const& input) +{ + topological_sorter + sorter; + vector + sorted, + unsortable; + stringstream + lines(input); + string + line; + while(getline(lines, line)) + { + stringstream + buffer(line); + string + goal, + dependency; + buffer >> goal; + sorter.add_goal(goal); + while(buffer >> dependency) + sorter.add_dependency(goal, dependency); + } + sorter.destructive_sort(sorted, unsortable); + if(sorted.size() == 0) + display_heading("Error: no independent variables found!"); + else + { + display_heading("Result"); + for(auto const& goal : sorted) + cout << goal << endl; + } + if(unsortable.size() != 0) + { + display_heading("Error: cyclic dependencies detected!"); + for(auto const& goal : unsortable) + cout << goal << endl; + } +} +int + main(int argc, char** argv) +{ + if(argc == 1) + { + string + example = + "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\n" + "cycle_11 cycle_12\n" + "cycle_12 cycle_11\n" + "cycle_21 dw01 cycle_22 dw02 dw03\n" + "cycle_22 cycle_21 dw01 dw04"; + display_heading("Example: each line starts with a goal followed by it's dependencies"); + cout << example << endl; + display_results(example); + display_heading("Enter lines of data (press enter when finished)"); + string + line, + data; + while(getline(cin, line) && !line.empty()) + data += line + '\n'; + if(!data.empty()) + display_results(data); + } + else while(*(++argv)) + { + ifstream + file(*argv); + typedef istreambuf_iterator + iterator; + display_results(string(iterator(file), iterator())); + } } diff --git a/Task/Topological-sort/JavaScript/topological-sort-1.js b/Task/Topological-sort/JavaScript/topological-sort-1.js new file mode 100644 index 0000000000..d0b95b8b68 --- /dev/null +++ b/Task/Topological-sort/JavaScript/topological-sort-1.js @@ -0,0 +1,57 @@ +const libs = + `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`; + +// A map of the input data, with the keys as the packages, and the values as +// and array of packages on which it depends. +const D = libs + .split('\n') + .map(e => e.split(' ').filter(e => e != '')) + .reduce((p, c) => + p.set(c[0], c.filter((e, i) => i > 0 && e !== c[0] ? e : null)), new Map()); +[].concat(...D.values()).forEach(e => { + D.set(e, D.get(e) || []) +}); + +// The above map rotated so that it represents a DAG of the form +// Map { +// A => [ A, B, C], +// B => [C], +// C => [] +// } +// where each key represents a node, and the array contains the edges. +const G = [...D.keys()].reduce((p, c) => + p.set( + c, + [...D.keys()].filter(e => D.get(e).includes(c))), + new Map() +); + +// An array of leaf nodes; nodes with 0 in degrees. +const Q = [...D.keys()].filter(e => D.get(e).length == 0); + +// The result array. +const S = []; +while (Q.length) { + const u = Q.pop(); + S.push(u); + G.get(u).forEach(v => { + D.set(v, D.get(v).filter(e => e !== u)); + if (D.get(v).length == 0) { + Q.push(v); + } + }); +} + +console.log('Solution:', S); diff --git a/Task/Topological-sort/JavaScript/topological-sort-2.js b/Task/Topological-sort/JavaScript/topological-sort-2.js new file mode 100644 index 0000000000..5e9ab260c3 --- /dev/null +++ b/Task/Topological-sort/JavaScript/topological-sort-2.js @@ -0,0 +1,16 @@ +Solution: [ + 'ieee', + 'std_cell_lib', + 'gtech', + 'dware', + 'dw07', + 'dw06', + 'dw05', + 'dw02', + 'dw01', + 'dw04', + 'std', + 'ramlib', + 'synopsys', + 'dw03', + 'des_system_lib' ] diff --git a/Task/Topological-sort/jq/topological-sort-1.jq b/Task/Topological-sort/Jq/topological-sort-1.jq similarity index 100% rename from Task/Topological-sort/jq/topological-sort-1.jq rename to Task/Topological-sort/Jq/topological-sort-1.jq diff --git a/Task/Topological-sort/jq/topological-sort-2.jq b/Task/Topological-sort/Jq/topological-sort-2.jq similarity index 100% rename from Task/Topological-sort/jq/topological-sort-2.jq rename to Task/Topological-sort/Jq/topological-sort-2.jq diff --git a/Task/Topological-sort/jq/topological-sort-3.jq b/Task/Topological-sort/Jq/topological-sort-3.jq similarity index 100% rename from Task/Topological-sort/jq/topological-sort-3.jq rename to Task/Topological-sort/Jq/topological-sort-3.jq diff --git a/Task/Topological-sort/Perl-6/topological-sort-1.pl6 b/Task/Topological-sort/Perl-6/topological-sort-1.pl6 deleted file mode 100644 index dad1462d24..0000000000 --- a/Task/Topological-sort/Perl-6/topological-sort-1.pl6 +++ /dev/null @@ -1,37 +0,0 @@ -sub print_topo_sort ( %deps ) { - my %ba; - for %deps.kv -> $before, @afters { - for @afters -> $after { - %ba{$before}{$after} = 1 if $before ne $after; - %ba{$after} //= {}; - } - } - - while %ba.grep( not *.value )».key -> @afters { - say ~@afters.sort; - %ba.delete(@afters); - %ba.values».delete(@afters); - } - - say %ba ?? "Cycle found! {%ba.keys.sort}" !! '---'; -} - -my %deps = - 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 => < >; - -print_topo_sort(%deps); -%deps.push: 'dw04'; # Add unresolvable dependency -print_topo_sort(%deps); diff --git a/Task/Topological-sort/Perl-6/topological-sort-2.pl6 b/Task/Topological-sort/Perl-6/topological-sort-2.pl6 deleted file mode 100644 index a71acfeb24..0000000000 --- a/Task/Topological-sort/Perl-6/topological-sort-2.pl6 +++ /dev/null @@ -1,13 +0,0 @@ -sub print_topo_sort ( %deps ) { - my %ba = %deps.kv».map: * => set; - %ba{.key}.=union(set .value) if .key ne .value - for %deps.map: { .key X=> .value } - - while %ba.grep((:!value))».key -> @afters { - say ~@afters.sort; - %ba.delete(@afters); - %ba{*}».=difference(@afters); - } - - say %ba ?? "Cycle found! {%ba.keys.sort}" !! '---'; -} diff --git a/Task/Topological-sort/Zkl/topological-sort-1.zkl b/Task/Topological-sort/Zkl/topological-sort-1.zkl new file mode 100644 index 0000000000..f18e740b51 --- /dev/null +++ b/Task/Topological-sort/Zkl/topological-sort-1.zkl @@ -0,0 +1,15 @@ +fcn topoSort(data){ // data is L( L(root,L(leaves)),...) + allDs:=data.pump(List,fcn(rds){ T(Void.Write,Void.Write,rds[1]) }).copy(); + roots:=Dictionary(data); // dictionary of root:leaves + L:=List(); + S:=data.pump(List,'wrap([(r,_)]){ if(allDs.holds(r)) Void.Skip else r }).copy(); + while(S){ //while S is non-empty do + (n:=S.pop()) : L.append(_); //remove a node n from S, add n to tail of L + foreach m in (ds:=roots.find(n,List)){ //node m with an edge e from n to m + allDs.del(allDs.index(m)); + if (Void==allDs.find(m)) S.append(m); //m has no other incoming edges + } roots.del(n); // remove edge e from the graph + } + if(roots) throw(Exception.ValueError("Cycle: "+roots.keys)); + L +} diff --git a/Task/Topological-sort/Zkl/topological-sort-2.zkl b/Task/Topological-sort/Zkl/topological-sort-2.zkl new file mode 100644 index 0000000000..f4781be302 --- /dev/null +++ b/Task/Topological-sort/Zkl/topological-sort-2.zkl @@ -0,0 +1,19 @@ +data:=T( + "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", "", +); +data=data.pump(List,Void.Read,fcn(r,ds){ + T( r, ds.replace(r,"").strip().split().copy() ) // leaves writable 'cause they will be +}); +topoSort(data).println(); diff --git a/Task/Topswops/Haskell/topswops-2.hs b/Task/Topswops/Haskell/topswops-2.hs index d632338ed6..15f0eab45b 100644 --- a/Task/Topswops/Haskell/topswops-2.hs +++ b/Task/Topswops/Haskell/topswops-2.hs @@ -1,11 +1,21 @@ -import Data.List -import Control.Arrow -import Control.Monad +import Data.List (permutations, inits) -derangements = filter (and . zipWith (/=) [1..] ). permutations -topswop = ((uncurry (++). first reverse).). splitAt -topswopIter = takeWhile((/=1).head). iterate (topswop =<< head) -swops = map (length. topswopIter). derangements +import Control.Arrow (first) + +derangements :: [Int] -> [[Int]] +derangements = (filter . (and .) . zipWith (/=)) <*> permutations + +topswop :: Int -> [a] -> [a] +topswop = ((uncurry (++) . first reverse) .) . splitAt + +topswopIter :: [Int] -> [[Int]] +topswopIter = takeWhile ((/= 1) . head) . iterate (topswop =<< head) + +swops :: [Int] -> [Int] +swops = fmap (length . topswopIter) . derangements topSwops :: [Int] -> [(Int, Int)] -topSwops = zip [1..]. map (maximum. (0:). swops). tail. inits +topSwops = zip [1 ..] . fmap (maximum . (0 :) . swops) . tail . inits + +main :: IO () +main = mapM_ print $ take 10 $ topSwops [1 ..] diff --git a/Task/Topswops/jq/topswops-1.jq b/Task/Topswops/Jq/topswops-1.jq similarity index 100% rename from Task/Topswops/jq/topswops-1.jq rename to Task/Topswops/Jq/topswops-1.jq diff --git a/Task/Topswops/jq/topswops-2.jq b/Task/Topswops/Jq/topswops-2.jq similarity index 100% rename from Task/Topswops/jq/topswops-2.jq rename to Task/Topswops/Jq/topswops-2.jq diff --git a/Task/Topswops/jq/topswops-3.jq b/Task/Topswops/Jq/topswops-3.jq similarity index 100% rename from Task/Topswops/jq/topswops-3.jq rename to Task/Topswops/Jq/topswops-3.jq diff --git a/Task/Topswops/jq/topswops-4.jq b/Task/Topswops/Jq/topswops-4.jq similarity index 100% rename from Task/Topswops/jq/topswops-4.jq rename to Task/Topswops/Jq/topswops-4.jq diff --git a/Task/Topswops/Kotlin/topswops.kotlin b/Task/Topswops/Kotlin/topswops.kotlin new file mode 100644 index 0000000000..880bfd2e1d --- /dev/null +++ b/Task/Topswops/Kotlin/topswops.kotlin @@ -0,0 +1,35 @@ +// version 1.1.2 + +val best = IntArray(32) + +fun trySwaps(deck: IntArray, f: Int, d: Int, n: Int) { + if (d > best[n]) best[n] = d + for (i in n - 1 downTo 0) { + if (deck[i] == -1 || deck[i] == i) break + if (d + best[i] <= best[n]) return + } + val deck2 = deck.copyOf() + for (i in 1 until n) { + val k = 1 shl i + if (deck2[i] == -1) { + if ((f and k) != 0) continue + } + else if (deck2[i] != i) continue + deck2[0] = i + for (j in i - 1 downTo 0) deck2[i - j] = deck[j] + trySwaps(deck2, f or k, d + 1, n) + } +} + +fun topswops(n: Int): Int { + require(n > 0 && n < best.size) + best[n] = 0 + val deck0 = IntArray(n + 1) + for (i in 1 until n) deck0[i] = -1 + trySwaps(deck0, 1, 0, n) + return best[n] +} + +fun main(args: Array) { + for (i in 1..10) println("${"%2d".format(i)} : ${topswops(i)}") +} diff --git a/Task/Topswops/REXX/topswops.rexx b/Task/Topswops/REXX/topswops.rexx index 4a7b0f35e8..e985a00c90 100644 --- a/Task/Topswops/REXX/topswops.rexx +++ b/Task/Topswops/REXX/topswops.rexx @@ -1,41 +1,38 @@ -/*REXX pgm gens N decks of numbered cards and finds the maximum "swops".*/ -parse arg things .; if things=='' then things=10; thingsX= things>9 +/*REXX program generates N decks of numbered cards and finds the maximum "swops". */ +parse arg things .; if things=='' then things=10 - do n=1 for things; #=deckSets(n,n) /*create "decks".*/ - mx= n\==1 /*handle case of a one-card deck.*/ - do i=1 for # - mx=max(mx,swops(!.i)) - end /*i*/ - say '──────── maximum swops for a deck of' right(n,2) ' cards is' right(mx,4) + do n=1 for things; #=decks(n, n) /*create a (things) number of "decks". */ + mx= n\==1 /*handle the case of a one-card deck.*/ + do i=1 for #; p=swops(!.i) /*compute the SWOPS for this iteration.*/ + if p>mx then mx=p /*This a new maximum? Use a new max. */ + end /*i*/ + say '──────── maximum swops for a deck of' right(n,2) ' cards is' right(mx,4) end /*n*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────DECKSETS subroutine─────────────────*/ -deckSets: procedure expose !. /*X things taken Y at a time.*/ -parse arg x,y,,$ @.; #=0; call .deckset 1 /*set $ & @. to null.*/ -return # /*return # permutations (decks).*/ -.deckset: procedure expose @. x y $ # !.; parse arg ? -if ?>y then do; _=@.1; do j=2 to y; _=_ @.j; end /*j*/; #=#+1; !.#=_ - end - else do - ?m=?-1 /*used in the FOR for faster DO.*/ - if ?==1 then qs=2 /*¬ use 1-swops that start with 1*/ - else do - qs=1 - if @.1==? then qs=2 /*skip 1-swops: 3 x 1 x */ - end - do q=qs to x /*build permutation recursively. */ - do k=1 for ?m; if @.k==q then iterate q; end /*k*/ - @.?=q; call .deckset(?+1) - end /*q*/ - end -return -/*──────────────────────────────────SWOPS subroutine────────────────────*/ -swops: parse arg z; do _=1; t=word(z,1) - if word(z,t)==1 then return _ - if thingsX then do h=10 to things - z=changestr(h,z,d2x(h)) - end /*h*/ - z=reverse(subword(z,1,t)) subword(z,t+1) - if thingsX then do d=10 to things - z=changestr(d2x(d),z,d) - end /*_*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +decks: procedure expose !.; parse arg x,y,,$ @. /* X things taken Y at a time. */ + #=0; call .decks 1 /* [↑] initialize $ & @. to null.*/ + return # /*return number of permutations (decks)*/ +.decks: procedure expose !. @. x y $ #; parse arg ? + if ?>y then do; _=@.1; do j=2 for y-1; _=_ @.j; end /*j*/; #=#+1; !.#=_ + end + else do; qm=?-1 + if ?==1 then qs=2 /*don't use 1-swops that start with 1 */ + else if @.1==? then qs=2 /*skip the 1-swops: 3 x 1 x ···*/ + else qs=1 + do q=qs to x /*build the permutations recursively. */ + do k=1 for qm; if @.k==q then iterate q + end /*k*/ + @.?=q; call .decks ? + 1 + end /*q*/ + end + return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +swops: parse arg z; do u=1; parse var z t .; if length(t)==2 then t=x2d(t) + if word(z, t)==1 then return u /*found unity at T. */ + do h=10 to things; if pos(h, z)==0 then iterate + z=changestr(h, z, d2x(h) ) /* [↑] any H's in Z ? */ + /* [↑] hexify decimal H */ + end /*h*/ + z=reverse(subword(z, 1, t)) subword(z, t+1) + end /*u*/ diff --git a/Task/Topswops/Zkl/topswops.zkl b/Task/Topswops/Zkl/topswops.zkl new file mode 100644 index 0000000000..2867490ef4 --- /dev/null +++ b/Task/Topswops/Zkl/topswops.zkl @@ -0,0 +1,10 @@ +fcn topswops(n){ + flip:=fcn(xa){ + if (not xa[0]) return(0); + xa.reverse(0,xa[0]+1); // inplace, ~4x faster than making new lists + return(1 + self.fcn(xa)); + }; + (0).pump(n,List):Utils.Helpers.permute(_).pump(List,"copy",flip).reduce("max"); +} + +foreach n in ([1 .. 10]){ println(n, ": ", topswops(n)) } diff --git a/Task/Total-circles-area/Kotlin/total-circles-area-1.kotlin b/Task/Total-circles-area/Kotlin/total-circles-area-1.kotlin new file mode 100644 index 0000000000..9b0cb078d4 --- /dev/null +++ b/Task/Total-circles-area/Kotlin/total-circles-area-1.kotlin @@ -0,0 +1,53 @@ +// version 1.1.2 + +class Circle(val x: Double, val y: Double, val r: Double) + +val circles = arrayOf( + Circle( 1.6417233788, 1.6121789534, 0.0848270516), + Circle(-1.4944608174, 1.2077959613, 1.1039549836), + Circle( 0.6110294452, -0.6907087527, 0.9089162485), + Circle( 0.3844862411, 0.2923344616, 0.2375743054), + Circle(-0.2495892950, -0.3832854473, 1.0845181219), + Circle( 1.7813504266, 1.6178237031, 0.8162655711), + Circle(-0.1985249206, -0.8343333301, 0.0538864941), + Circle(-1.7011985145, -0.1263820964, 0.4776976918), + Circle(-0.4319462812, 1.4104420482, 0.7886291537), + Circle( 0.2178372997, -0.9499557344, 0.0357871187), + Circle(-0.6294854565, -1.3078893852, 0.7653357688), + Circle( 1.7952608455, 0.6281269104, 0.2727652452), + Circle( 1.4168575317, 1.0683357171, 1.1016025378), + Circle( 1.4637371396, 0.9463877418, 1.1846214562), + Circle(-0.5263668798, 1.7315156631, 1.4428514068), + Circle(-1.2197352481, 0.9144146579, 1.0727263474), + Circle(-0.1389358881, 0.1092805780, 0.7350208828), + Circle( 1.5293954595, 0.0030278255, 1.2472867347), + Circle(-0.5258728625, 1.3782633069, 1.3495508831), + Circle(-0.1403562064, 0.2437382535, 1.3804956588), + Circle( 0.8055826339, -0.0482092025, 0.3327165165), + Circle(-0.6311979224, 0.7184578971, 0.2491045282), + Circle( 1.4685857879, -0.8347049536, 1.3670667538), + Circle(-0.6855727502, 1.6465021616, 1.0593087096), + Circle( 0.0152957411, 0.0638919221, 0.9771215985) +) + +fun Double.sq() = this * this + +fun main(args: Array) { + val xMin = circles.map { it.x - it.r }.min()!! + val xMax = circles.map { it.x + it.r }.max()!! + val yMin = circles.map { it.y - it.r }.min()!! + val yMax = circles.map { it.y + it.r }.max()!! + val boxSide = 5000 + val dx = (xMax - xMin) / boxSide + val dy = (yMax - yMin) / boxSide + var count = 0 + for (r in 0 until boxSide) { + val y = yMin + r * dy + for (c in 0 until boxSide) { + val x = xMin + c * dx + val b = circles.any { (x - it.x).sq() + (y - it.y).sq() <= it.r.sq() } + if (b) count++ + } + } + println("Approximate area = ${count * dx * dy}") +} diff --git a/Task/Total-circles-area/Kotlin/total-circles-area-2.kotlin b/Task/Total-circles-area/Kotlin/total-circles-area-2.kotlin new file mode 100644 index 0000000000..7129f9d680 --- /dev/null +++ b/Task/Total-circles-area/Kotlin/total-circles-area-2.kotlin @@ -0,0 +1,65 @@ +// version 1.1.2 + +class Point(val x: Double, val y: Double) + +class Circle(val x: Double, val y: Double, val r: Double) + +val circles = arrayOf( + Circle( 1.6417233788, 1.6121789534, 0.0848270516), + Circle(-1.4944608174, 1.2077959613, 1.1039549836), + Circle( 0.6110294452, -0.6907087527, 0.9089162485), + Circle( 0.3844862411, 0.2923344616, 0.2375743054), + Circle(-0.2495892950, -0.3832854473, 1.0845181219), + Circle( 1.7813504266, 1.6178237031, 0.8162655711), + Circle(-0.1985249206, -0.8343333301, 0.0538864941), + Circle(-1.7011985145, -0.1263820964, 0.4776976918), + Circle(-0.4319462812, 1.4104420482, 0.7886291537), + Circle( 0.2178372997, -0.9499557344, 0.0357871187), + Circle(-0.6294854565, -1.3078893852, 0.7653357688), + Circle( 1.7952608455, 0.6281269104, 0.2727652452), + Circle( 1.4168575317, 1.0683357171, 1.1016025378), + Circle( 1.4637371396, 0.9463877418, 1.1846214562), + Circle(-0.5263668798, 1.7315156631, 1.4428514068), + Circle(-1.2197352481, 0.9144146579, 1.0727263474), + Circle(-0.1389358881, 0.1092805780, 0.7350208828), + Circle( 1.5293954595, 0.0030278255, 1.2472867347), + Circle(-0.5258728625, 1.3782633069, 1.3495508831), + Circle(-0.1403562064, 0.2437382535, 1.3804956588), + Circle( 0.8055826339, -0.0482092025, 0.3327165165), + Circle(-0.6311979224, 0.7184578971, 0.2491045282), + Circle( 1.4685857879, -0.8347049536, 1.3670667538), + Circle(-0.6855727502, 1.6465021616, 1.0593087096), + Circle( 0.0152957411, 0.0638919221, 0.9771215985) +) + +fun Double.sq() = this * this + +fun areaScan(precision: Double): Double { + fun sect(c: Circle, y: Double): Point { + val dr = Math.sqrt(c.r.sq() - (y - c.y).sq()) + return Point(c.x - dr, c.x + dr) + } + + val ys = circles.map { it.y + it.r } + circles.map { it.y - it.r } + val mins = Math.floor(ys.min()!! / precision).toInt() + val maxs = Math.ceil(ys.max()!! / precision).toInt() + var total = 0.0 + for (x in mins..maxs) { + val y = x * precision + var right = Double.NEGATIVE_INFINITY + val points = circles.filter { Math.abs(y - it.y) < it.r } + .map { sect(it, y) } + .sortedBy { it.x } + for (p in points) { + if (p.y <= right) continue + total += p.y - maxOf(p.x, right) + right = p.y + } + } + return total * precision +} + +fun main(args: Array) { + val p = 1e-6 + println("Approximate area = ${areaScan(p)}") +} diff --git a/Task/Total-circles-area/Perl-6/total-circles-area.pl6 b/Task/Total-circles-area/Perl-6/total-circles-area.pl6 index ee867e8641..13b40afcd8 100644 --- a/Task/Total-circles-area/Perl-6/total-circles-area.pl6 +++ b/Task/Total-circles-area/Perl-6/total-circles-area.pl6 @@ -83,7 +83,7 @@ while @rawcircles { sub set_cbits(Point $p) { my $cbits = 0; - for @circles Z (1,2,4...*) -> $c, $b { + for @circles Z (1,2,4...*) -> ($c, $b) { $cbits += $b if $c.contains($p); } $cbits; diff --git a/Task/Total-circles-area/REXX/total-circles-area-1.rexx b/Task/Total-circles-area/REXX/total-circles-area-1.rexx index eec8950bbc..d7e1490b3d 100644 --- a/Task/Total-circles-area/REXX/total-circles-area-1.rexx +++ b/Task/Total-circles-area/REXX/total-circles-area-1.rexx @@ -2,6 +2,7 @@ parse arg box dig . /*obtain optional argument from the CL.*/ if box=='' | box==',' then box= 500 /*Not specified? Then use the default.*/ if dig=='' | dig==',' then dig= 12 /* " " " " " " */ +numeric digits dig /*have enough decimal digits for points*/ data = ' 1.6417233788 1.6121789534 0.0848270516', '-1.4944608174 1.2077959613 1.1039549836', ' 0.6110294452 -0.6907087527 0.9089162485', diff --git a/Task/Total-circles-area/Zkl/total-circles-area.zkl b/Task/Total-circles-area/Zkl/total-circles-area.zkl new file mode 100644 index 0000000000..9e84257df5 --- /dev/null +++ b/Task/Total-circles-area/Zkl/total-circles-area.zkl @@ -0,0 +1,26 @@ +circles:=File("circles.txt").pump(List,'wrap(line){ + line.split().apply("toFloat") // L(x,y,r) +}); + # compute the bounding box of the circles +x_min:=(0.0).min(circles.apply(fcn([(x,y,r)]){ x - r })); // (0) not used, just the list of numbers +x_max:=(0.0).max(circles.apply(fcn([(x,y,r)]){ x + r })); +y_min:=(0.0).min(circles.apply(fcn([(x,y,r)]){ y - r })); +y_max:=(0.0).max(circles.apply(fcn([(x,y,r)]){ y + r })); + +box_side:=500; +dx:=(x_max - x_min)/box_side; +dy:=(y_max - y_min)/box_side; + +count:=0; +foreach r in (box_side){ + y:=y_min + dy*r; + foreach c in (box_side){ + x:=x_min + dx*c; + count+=circles.filter1('wrap([(cx,cy,cr)]){ + x-=cx; y-=cy; + x*x + y*y <= cr*cr + }).toBool(); // -->False|L(x,y,z), L(x,y,r).toBool()-->True, + } +} + +println("Approximated area: ", dx*dy*count); diff --git a/Task/Towers-of-Hanoi/Euphoria/towers-of-hanoi.euphoria b/Task/Towers-of-Hanoi/Euphoria/towers-of-hanoi.euphoria deleted file mode 100644 index 86a4a5f965..0000000000 --- a/Task/Towers-of-Hanoi/Euphoria/towers-of-hanoi.euphoria +++ /dev/null @@ -1,9 +0,0 @@ -procedure move(integer n, sequence From, sequence To, sequence Via) - if n>0 then - move(n-1, From, Via, To) - printf(1, "Move disk %d from the %s pole to the %s pole\n", {n, From, To}) - move(n-1, Via, To, From) - end if -end procedure - -move(3, "left", "right", "middle") diff --git a/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-4.hs b/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-4.hs new file mode 100644 index 0000000000..6badcd61bf --- /dev/null +++ b/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-4.hs @@ -0,0 +1,18 @@ +import Data.Monoid ((<>), mempty) +import Data.List (intercalate, transpose) + +hanoi :: Int -> t -> t -> t -> [[t]] +hanoi n l r m = + if n > 0 + then hanoi (n - 1) l m r <> [[l, r]] <> hanoi (n - 1) m r l + else mempty + +-- TEST (hanoi 5) ------------------------------------------------------------- +main :: IO () +main = + mapM_ putStrLn $ + intercalate " -> " <$> + transpose + ((justifyLeft 6 ' ' <$>) <$> transpose (hanoi 5 "left" "right" "mid")) + where + justifyLeft n c s = take n (s <> replicate n c) diff --git a/Task/Towers-of-Hanoi/JavaScript/towers-of-hanoi-2.js b/Task/Towers-of-Hanoi/JavaScript/towers-of-hanoi-2.js index 384b0f8609..201b1694bb 100644 --- a/Task/Towers-of-Hanoi/JavaScript/towers-of-hanoi-2.js +++ b/Task/Towers-of-Hanoi/JavaScript/towers-of-hanoi-2.js @@ -1,15 +1,16 @@ (function () { - // hanoi :: n -> s -> s -> s -> [[s, s]] - function hanoi(n, a, b, c) { - return n ? hanoi(n - 1, a, c, b).concat( - [[a, b]] - ).concat(hanoi(n - 1, c, b, a)) : []; - } - - return hanoi(3, 'left', 'right', 'mid') - .map(function (d) { - return d[0] + ' -> ' + d[1]; - }); + // hanoi :: Int -> String -> String -> String -> [[String, String]] + function hanoi(n, a, b, c) { + return n ? hanoi(n - 1, a, c, b) + .concat([ + [a, b] + ]) + .concat(hanoi(n - 1, c, b, a)) : []; + } + return hanoi(3, 'left', 'right', 'mid') + .map(function (d) { + return d[0] + ' -> ' + d[1]; + }); })(); diff --git a/Task/Towers-of-Hanoi/JavaScript/towers-of-hanoi-4.js b/Task/Towers-of-Hanoi/JavaScript/towers-of-hanoi-4.js new file mode 100644 index 0000000000..2974524435 --- /dev/null +++ b/Task/Towers-of-Hanoi/JavaScript/towers-of-hanoi-4.js @@ -0,0 +1,19 @@ +(() => { + 'use strict'; + + // hanoi :: Int -> String -> String -> String -> [[String, String]] + const hanoi = (n, a, b, c) => + n ? hanoi(n - 1, a, c, b) + .concat([ + [a, b] + ]) + .concat(hanoi(n - 1, c, b, a)) : []; + + // show :: a -> String + const show = x => JSON.stringify(x, null, 2); + + return show( + hanoi(3, 'left', 'right', 'mid') + .map(d => d[0] + ' -> ' + d[1]) + ); +})(); diff --git a/Task/Towers-of-Hanoi/jq/towers-of-hanoi.jq b/Task/Towers-of-Hanoi/Jq/towers-of-hanoi.jq similarity index 100% rename from Task/Towers-of-Hanoi/jq/towers-of-hanoi.jq rename to Task/Towers-of-Hanoi/Jq/towers-of-hanoi.jq diff --git a/Task/Towers-of-Hanoi/Julia/towers-of-hanoi.julia b/Task/Towers-of-Hanoi/Julia/towers-of-hanoi.julia new file mode 100644 index 0000000000..bccef76032 --- /dev/null +++ b/Task/Towers-of-Hanoi/Julia/towers-of-hanoi.julia @@ -0,0 +1,11 @@ +function solve(n::Integer, from::Integer, to::Integer, via::Integer) + if n == 1 + println("Move disk from $from to $to") + else + solve(n - 1, from, via, to) + solve(1, from, to, via) + solve(n - 1, via, to, from) + end +end + +solve(4, 1, 2, 3) diff --git a/Task/Towers-of-Hanoi/Kotlin/towers-of-hanoi.kotlin b/Task/Towers-of-Hanoi/Kotlin/towers-of-hanoi.kotlin new file mode 100644 index 0000000000..95669a2935 --- /dev/null +++ b/Task/Towers-of-Hanoi/Kotlin/towers-of-hanoi.kotlin @@ -0,0 +1,25 @@ +// version 1.1.0 + +class Hanoi(disks: Int) { + private var moves = 0 + + init { + println("Towers of Hanoi with $disks disks:\n") + move(disks, 'L', 'C', 'R') + println("\nCompleted in $moves moves\n") + } + + private fun move(n: Int, from: Char, to: Char, via: Char) { + if (n > 0) { + move(n - 1, from, via, to) + moves++ + println("Move disk $n from $from to $to") + move(n - 1, via, to, from) + } + } +} + +fun main(args: Array) { + Hanoi(3) + Hanoi(4) +} diff --git a/Task/Towers-of-Hanoi/Lambdatalk/towers-of-hanoi.lambdatalk b/Task/Towers-of-Hanoi/Lambdatalk/towers-of-hanoi.lambdatalk new file mode 100644 index 0000000000..acdafe437e --- /dev/null +++ b/Task/Towers-of-Hanoi/Lambdatalk/towers-of-hanoi.lambdatalk @@ -0,0 +1,24 @@ +{def move + {lambda {:n :from :to :via} + {if {<= :n 0} + then > + else {move {- :n 1} :from :via :to} + move disk from :from to :to {br} + {move {- :n 1} :via :to :from} }}} +-> move +{move 4 1 2 3} +> move disk from 1 to 3 +> move disk from 1 to 2 +> move disk from 3 to 2 +> move disk from 1 to 3 +> move disk from 2 to 1 +> move disk from 2 to 3 +> move disk from 1 to 3 +> move disk from 1 to 2 +> move disk from 3 to 2 +> move disk from 3 to 1 +> move disk from 2 to 1 +> move disk from 3 to 2 +> move disk from 1 to 3 +> move disk from 1 to 2 +> move disk from 3 to 2 diff --git a/Task/Towers-of-Hanoi/MATLAB/towers-of-hanoi-1.m b/Task/Towers-of-Hanoi/MATLAB/towers-of-hanoi-1.m deleted file mode 100644 index 14a03bd3b8..0000000000 --- a/Task/Towers-of-Hanoi/MATLAB/towers-of-hanoi-1.m +++ /dev/null @@ -1,7 +0,0 @@ -function towerOfHanoi(n,A,C,B) - if (n~=0) - towerOfHanoi(n-1,A,B,C); - disp(sprintf('Move plate %d from tower %d to tower %d',[n A C])); - towerOfHanoi(n-1,B,C,A); - end -end diff --git a/Task/Towers-of-Hanoi/MATLAB/towers-of-hanoi-2.m b/Task/Towers-of-Hanoi/MATLAB/towers-of-hanoi-2.m deleted file mode 100644 index f309d71f6f..0000000000 --- a/Task/Towers-of-Hanoi/MATLAB/towers-of-hanoi-2.m +++ /dev/null @@ -1,8 +0,0 @@ -towerOfHanoi(3,1,3,2) -Move plate 1 from tower 1 to tower 3 -Move plate 2 from tower 1 to tower 2 -Move plate 1 from tower 3 to tower 2 -Move plate 3 from tower 1 to tower 3 -Move plate 1 from tower 2 to tower 1 -Move plate 2 from tower 2 to tower 3 -Move plate 1 from tower 1 to tower 3 diff --git a/Task/Towers-of-Hanoi/Nimrod/towers-of-hanoi.nimrod b/Task/Towers-of-Hanoi/Nimrod/towers-of-hanoi.nimrod deleted file mode 100644 index d80d015f79..0000000000 --- a/Task/Towers-of-Hanoi/Nimrod/towers-of-hanoi.nimrod +++ /dev/null @@ -1,7 +0,0 @@ -proc hanoi(disks: int, fromTower: string, toTower: string, viaTower: string) = - if disks != 0: - hanoi(disks - 1, fromTower, viaTower, toTower) - echo("Move disk ", disks, " from ", fromTower, " to ", toTower) - hanoi(disks - 1, viaTower, toTower, fromTower) - -hanoi(4, "1", "2", "3") diff --git a/Task/Towers-of-Hanoi/Phix/towers-of-hanoi.phix b/Task/Towers-of-Hanoi/Phix/towers-of-hanoi.phix new file mode 100644 index 0000000000..486eab7ec4 --- /dev/null +++ b/Task/Towers-of-Hanoi/Phix/towers-of-hanoi.phix @@ -0,0 +1,33 @@ +constant poles = {"left","middle","right"} +enum left, middle, right + +sequence disks +integer moves +procedure showpegs(integer src, integer dest) +string desc = sprintf("%s to %s:",{poles[src],poles[dest]}) + disks[dest] &= disks[src][$] + disks[src] = disks[src][1..$-1] + for i=1 to length(disks) do + printf(1,"%-16s | %s\n",{desc,join(sq_add(disks[i],'0'),' ')}) + desc = "" + end for + printf(1,"\n") + moves += 1 +end procedure + +procedure hanoir(integer n, src=left, dest=right, via=middle) + if n>0 then + hanoir(n-1, src, via, dest) + showpegs(src,dest) + hanoir(n-1, via, dest, src) + end if +end procedure + +procedure hanoi(integer n) + disks = {reverse(tagset(n)),{},{}} + moves = 0 + hanoir(n) + printf(1,"completed in %d moves\n",{moves}) +end procedure + +hanoi(3) diff --git a/Task/Towers-of-Hanoi/Zkl/towers-of-hanoi.zkl b/Task/Towers-of-Hanoi/Zkl/towers-of-hanoi.zkl new file mode 100644 index 0000000000..540d73c03d --- /dev/null +++ b/Task/Towers-of-Hanoi/Zkl/towers-of-hanoi.zkl @@ -0,0 +1,8 @@ +fcn move(n, from,to,via){ + if (n>0){ + move(n-1, from,via,to); + println("Move disk from pole %d to pole %d".fmt(from, to)); + move(n-1, via,to,from); + } +} +move(3, 1,2,3); diff --git a/Task/Trabb-Pardo-Knuth-algorithm/ALGOL-68/trabb-pardo-knuth-algorithm.alg b/Task/Trabb-Pardo-Knuth-algorithm/ALGOL-68/trabb-pardo-knuth-algorithm.alg new file mode 100644 index 0000000000..63fbb40d2b --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/ALGOL-68/trabb-pardo-knuth-algorithm.alg @@ -0,0 +1,10 @@ +[ 0 : 10 ]REAL a; +PROC f = ( REAL t )REAL: + sqrt(ABS t)+5*t*t*t; +FOR i FROM LWB a TO UPB a DO read( ( a[ i ] ) ) OD; +FOR i FROM UPB a BY -1 TO LWB a DO + REAL y=f(a[i]); + IF y > 400 THEN print( ( "TOO LARGE", newline ) ) + ELSE print( ( fixed( y, -9, 4 ), newline ) ) + FI +OD diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Agena/trabb-pardo-knuth-algorithm.agena b/Task/Trabb-Pardo-Knuth-algorithm/Agena/trabb-pardo-knuth-algorithm.agena new file mode 100644 index 0000000000..51ebfa9269 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Agena/trabb-pardo-knuth-algorithm.agena @@ -0,0 +1,13 @@ +scope # TPK algorithm in Agena + local y; + local a := []; + local f := proc( t :: number ) is return sqrt(abs(t))+5*t*t*t end; + for i from 0 to 10 do a[i] := tonumber( io.read() ) od; + for i from 10 to 0 by - 1 do + y:=f(a[i]); + if y > 400 + then print( "TOO LARGE" ) + else printf( "%10.4f\n", y ) + fi + od +epocs diff --git a/Task/Trabb-Pardo-Knuth-algorithm/FreeBASIC/trabb-pardo-knuth-algorithm.freebasic b/Task/Trabb-Pardo-Knuth-algorithm/FreeBASIC/trabb-pardo-knuth-algorithm.freebasic index f2e4aad455..f661adfa50 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/FreeBASIC/trabb-pardo-knuth-algorithm.freebasic +++ b/Task/Trabb-Pardo-Knuth-algorithm/FreeBASIC/trabb-pardo-knuth-algorithm.freebasic @@ -1,16 +1,16 @@ -' version 22-10-2016 +' version 22-07-2017 ' compile with: fbc -s console Function f(n As Double) As Double - return Sqr(Abs(n)) + 5 * n ^ 5 + return Sqr(Abs(n)) + 5 * n ^ 3 End Function ' ------=< MAIN >=------ -Dim As Double x, s(0 To 10) +Dim As Double x, s(1 To 11) Dim As Long i -For i = 0 To 10 +For i = 1 To 11 Print Str(i); Input " => ", s(i) Next @@ -18,15 +18,17 @@ Next Print Print String(20,"-") -For i = 10 To 0 Step -1 +i -= 1 +Do Print "f(" + Str(s(i)) + ") = "; x = f(s(i)) If x > 400 Then - Print "-=< to large >=-" + Print "-=< overflow >=-" Else Print x End If -Next + i -= 1 +Loop Until i < 1 ' empty keyboard buffer While InKey <> "" : Wend diff --git a/Task/Trabb-Pardo-Knuth-algorithm/jq/trabb-pardo-knuth-algorithm-1.jq b/Task/Trabb-Pardo-Knuth-algorithm/Jq/trabb-pardo-knuth-algorithm-1.jq similarity index 100% rename from Task/Trabb-Pardo-Knuth-algorithm/jq/trabb-pardo-knuth-algorithm-1.jq rename to Task/Trabb-Pardo-Knuth-algorithm/Jq/trabb-pardo-knuth-algorithm-1.jq diff --git a/Task/Trabb-Pardo-Knuth-algorithm/jq/trabb-pardo-knuth-algorithm-2.jq b/Task/Trabb-Pardo-Knuth-algorithm/Jq/trabb-pardo-knuth-algorithm-2.jq similarity index 100% rename from Task/Trabb-Pardo-Knuth-algorithm/jq/trabb-pardo-knuth-algorithm-2.jq rename to Task/Trabb-Pardo-Knuth-algorithm/Jq/trabb-pardo-knuth-algorithm-2.jq diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Kotlin/trabb-pardo-knuth-algorithm.kotlin b/Task/Trabb-Pardo-Knuth-algorithm/Kotlin/trabb-pardo-knuth-algorithm.kotlin new file mode 100644 index 0000000000..1d6acd21e9 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Kotlin/trabb-pardo-knuth-algorithm.kotlin @@ -0,0 +1,29 @@ +// version 1.1.2 + +fun f(x: Double) = Math.sqrt(Math.abs(x)) + 5.0 * x * x * x + +fun main(args: Array) { + val da = DoubleArray(11) + println("Please enter 11 numbers:") + var i = 0 + while (i < 11) { + print(" ${"%2d".format(i + 1)}: ") + val d = readLine()!!.toDoubleOrNull() + if (d == null) + println("Not a valid number, try again") + else + da[i++] = d + } + println("\nThe sequence you just entered in reverse is:") + da.reverse() + println(da.contentToString()) + println("\nProcessing this sequence...") + for (j in 0..10) { + val v = f(da[j]) + print(" ${"%2d".format(j + 1)}: ") + if (v > 400.0) + println("Overflow!") + else + println(v) + } +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Phix/trabb-pardo-knuth-algorithm.phix b/Task/Trabb-Pardo-Knuth-algorithm/Phix/trabb-pardo-knuth-algorithm.phix new file mode 100644 index 0000000000..c906ad229f --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Phix/trabb-pardo-knuth-algorithm.phix @@ -0,0 +1,16 @@ +function f(atom x) + return sqrt(abs(x))+5*power(x,3) +end function + +string s = substitute(prompt_string("Enter 11 numbers:"),","," ") +sequence S = scanf(s,"%f %f %f %f %f %f %f %f %f %f %f") +if length(S)!=1 then puts(1,"not 11 numbers") abort(0) end if +S = reverse(S[1]) +for i=1 to length(S) do + atom result = f(S[i]) + if result>400 then + printf(1,"f(%g):overflow\n",{S[i]}) + else + printf(1,"f(%g):%g\n",{S[i],result}) + end if +end for diff --git a/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-1.psh b/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-1.psh new file mode 100644 index 0000000000..f03504c148 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-1.psh @@ -0,0 +1,49 @@ +function Get-Tpk +{ + [CmdletBinding()] + [OutputType([PSCustomObject])] + Param + ( + [Parameter(Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true, + Position=0)] + [double] + $Number + ) + + Begin + { + function Get-TpkFunction ([double]$Number) + { + [Math]::Pow([Math]::Abs($Number),(0.5)) + 5 * [Math]::Pow($Number,3) + } + + [object[]]$output = @() + } + Process + { + $Number | ForEach-Object { + $n = Get-TpkFunction $_ + + if ($n -le 400) + { + $result = $n + } + else + { + $result = "Overflow" + } + } + + $output += [PSCustomObject]@{ + Number = $Number + Result = $result + } + } + End + { + [Array]::Reverse($output) + $output + } +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-2.psh b/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-2.psh new file mode 100644 index 0000000000..5611d61eb9 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-2.psh @@ -0,0 +1,2 @@ +$tpk = 1..11 | Get-Tpk +$tpk diff --git a/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-3.psh b/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-3.psh new file mode 100644 index 0000000000..7ce6994178 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-3.psh @@ -0,0 +1 @@ +$tpk | where result -ne overflow | sort number diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Sinclair-ZX81-BASIC/trabb-pardo-knuth-algorithm.sinclair b/Task/Trabb-Pardo-Knuth-algorithm/Sinclair-ZX81-BASIC/trabb-pardo-knuth-algorithm.sinclair new file mode 100644 index 0000000000..c56f101e6a --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Sinclair-ZX81-BASIC/trabb-pardo-knuth-algorithm.sinclair @@ -0,0 +1,12 @@ + 10 DIM A(11) + 20 PRINT "ENTER ELEVEN NUMBERS:" + 30 FOR I=1 TO 11 + 40 INPUT A(I) + 50 NEXT I + 60 FOR I=11 TO 1 STEP -1 + 70 LET Y=SQR ABS A(I)+5*A(I)**3 + 80 IF Y<=400 THEN GOTO 110 + 90 PRINT A(I),"TOO LARGE" +100 GOTO 120 +110 PRINT A(I),Y +120 NEXT I diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Zkl/trabb-pardo-knuth-algorithm.zkl b/Task/Trabb-Pardo-Knuth-algorithm/Zkl/trabb-pardo-knuth-algorithm.zkl new file mode 100644 index 0000000000..39d08631bf --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Zkl/trabb-pardo-knuth-algorithm.zkl @@ -0,0 +1,8 @@ +fcn f(x) { x.abs().pow(0.5) + x.pow(3)*5 } +reg ns; do{ + ns=ask("11 numbers seperated by spaces: "); + try{ ns=ns.split(" ").filter().apply("toFloat") } catch{} +}while(not ns.isType(List) or ns.len()!=11); +ns.reverse().apply(fcn(x){ + fx:=f(x); "f(%7.3f)-->%s".fmt(x, if(fx>400)"Overflow" else fx) }) +.pump(Console.println); diff --git a/Task/Tree-traversal/APL/tree-traversal-1.apl b/Task/Tree-traversal/APL/tree-traversal-1.apl new file mode 100644 index 0000000000..f423cb2b0e --- /dev/null +++ b/Task/Tree-traversal/APL/tree-traversal-1.apl @@ -0,0 +1,4 @@ +preorder ← {l r←⍺ ⍵⍵ ⍵ ⋄ (⊃r)∇⍨⍣(×≢r)⊢(⊃l)∇⍨⍣(×≢l)⊢⍺ ⍺⍺ ⍵} +inorder ← {l r←⍺ ⍵⍵ ⍵ ⋄ (⊃r)∇⍨⍣(×≢r)⊢⍵ ⍺⍺⍨(⊃l)∇⍨⍣(×≢l)⊢⍺} +postorder← {l r←⍺ ⍵⍵ ⍵ ⋄ ⍵ ⍺⍺⍨(⊃r)∇⍨⍣(×≢r)⊢(⊃l)∇⍨⍣(×≢l)⊢⍺} +lvlorder ← {0=⍴⍵:⍺ ⋄ (⊃⍺⍺⍨/(⌽⍵),⊂⍺)∇⊃∘(,/)⍣2⊢⍺∘⍵⍵¨⍵} diff --git a/Task/Tree-traversal/APL/tree-traversal-2.apl b/Task/Tree-traversal/APL/tree-traversal-2.apl new file mode 100644 index 0000000000..615f7179f9 --- /dev/null +++ b/Task/Tree-traversal/APL/tree-traversal-2.apl @@ -0,0 +1,3 @@ +tree←1(2(4(7⍬⍬)⍬)(5⍬⍬))(3(6(8⍬⍬)(9⍬⍬))⍬) +visit←{⍺,(×≢⍵)⍴⊃⍵} +children←{⊂¨@(×∘≢¨)1↓⍵} diff --git a/Task/Tree-traversal/AppleScript/tree-traversal-1.applescript b/Task/Tree-traversal/AppleScript/tree-traversal-1.applescript deleted file mode 100644 index aa3c8793c5..0000000000 --- a/Task/Tree-traversal/AppleScript/tree-traversal-1.applescript +++ /dev/null @@ -1,88 +0,0 @@ -on run - set tree to {1, {2, {4, {7}, {}}, {5}}, {3, {6, {8}, {9}}, {}}} - - return {|pre-order|:¬ - traverse("pre-order", tree), |in-order|:¬ - traverse("in-order", tree), |post-order|:¬ - traverse("post-order", tree), |level-order|:¬ - traverse("level-order", tree)} - -end run - --- traverse :: String -> Tree -> [Int] -on traverse(strOrderName, tree) - if strOrderName does not start with "level" then - set {v, l, r} to nodeParts(tree) - - if l is {} then - set lstLeft to [] - else - set lstLeft to traverse(strOrderName, l) - end if - - if r is {} then - set lstRight to [] - else - set lstRight to traverse(strOrderName, r) - end if - - -- PRE-ORDER - if strOrderName begins with "pre" then - v & lstLeft & lstRight - - -- IN-ORDER - else if strOrderName begins with "in" then - lstLeft & v & lstRight - - -- POST-ORDER - else if strOrderName begins with "post" then - lstLeft & lstRight & v - - end if - else - -- LEVEL-ORDER - levelOrder({tree}) - end if -end traverse - - --- levelOrder :: [Tree] -> [Int] -on levelOrder(lstTree) - if length of lstTree > 0 then - set {head, tail} to uncons(lstTree) - - -- Take any value found in the head node - -- deferring any child nodes to the end of the tail - -- before recursing - - if head is not {} then - set {v, l, r} to nodeParts(head) - v & levelOrder(tail & {l, r}) - else - levelOrder(tail) - end if - else - {} - end if -end levelOrder - --- nodeParts :: Tree -> (Int, Tree, Tree) -on nodeParts(tree) - if class of tree is list and length of tree = 3 then - tree - else - {tree} & {{}, {}} - end if -end nodeParts - - --- GENERIC - --- uncons :: [a] -> Maybe (a, [a]) -on uncons(xs) - if length of xs > 0 then - {item 1 of xs, rest of xs} - else - missing value - end if -end uncons diff --git a/Task/Tree-traversal/AppleScript/tree-traversal-2.applescript b/Task/Tree-traversal/AppleScript/tree-traversal-2.applescript deleted file mode 100644 index 5fa83ddfec..0000000000 --- a/Task/Tree-traversal/AppleScript/tree-traversal-2.applescript +++ /dev/null @@ -1,4 +0,0 @@ -{|pre-order|:{1, 2, 4, 7, 5, 3, 6, 8, 9}, -|in-order|:{7, 4, 2, 5, 1, 8, 6, 9, 3}, -|post-order|:{7, 4, 5, 2, 8, 9, 6, 3, 1}, -|level-order|:{1, 2, 3, 4, 5, 6, 7, 8, 9}} diff --git a/Task/Tree-traversal/AppleScript/tree-traversal.applescript b/Task/Tree-traversal/AppleScript/tree-traversal.applescript new file mode 100644 index 0000000000..dc1c40e3d0 --- /dev/null +++ b/Task/Tree-traversal/AppleScript/tree-traversal.applescript @@ -0,0 +1,215 @@ +on run + set tree to {1, {2, {4, {7}, {}}, {5}}, {3, {6, {8}, {9}}, {}}} + + -- asciiTree :: String + set asciiTree to ¬ + unlines({¬ + " 1", ¬ + " / \\", ¬ + " / \\", ¬ + " / \\", ¬ + " 2 3", ¬ + " / \\ /", ¬ + " 4 5 6", ¬ + " / / \\", ¬ + " 7 8 9"}) + + script tabulate + on |λ|(s, xs) + justifyLeft(14, space, s & ":") & unwords(xs) + end |λ| + end script + + set strResult to asciiTree & linefeed & linefeed & ¬ + unlines(zipWith(tabulate, ¬ + ["preorder", "inorder", "postorder", "level-order"], ¬ + ap([preorder, inorder, postorder, levelOrder], [tree]))) + + set the clipboard to strResult + return strResult +end run + +-- TRAVERSAL FUNCTIONS -------------------------------------------------------- + +-- preorder :: Tree Int -> [Int] +on preorder(tree) + set {v, l, r} to nodeParts(tree) + if l is {} then + set lstLeft to [] + else + set lstLeft to preorder(l) + end if + + if r is {} then + set lstRight to [] + else + set lstRight to preorder(r) + end if + v & lstLeft & lstRight +end preorder + +-- inorder :: Tree Int -> [Int] +on inorder(tree) + set {v, l, r} to nodeParts(tree) + if l is {} then + set lstLeft to [] + else + set lstLeft to inorder(l) + end if + + if r is {} then + set lstRight to [] + else + set lstRight to inorder(r) + end if + + lstLeft & v & lstRight +end inorder + +-- postorder :: Tree Int -> [Int] +on postorder(tree) + set {v, l, r} to nodeParts(tree) + if l is {} then + set lstLeft to [] + else + set lstLeft to postorder(l) + end if + + if r is {} then + set lstRight to [] + else + set lstRight to postorder(r) + end if + lstLeft & lstRight & v +end postorder + +-- levelOrder :: Tree Int -> [Int] +on levelOrder(tree) + if length of tree > 0 then + set {head, tail} to uncons(tree) + + -- Take any value found in the head node + -- deferring any child nodes to the end of the tail + -- before recursing + + if head is not {} then + set {v, l, r} to nodeParts(head) + v & levelOrder(tail & {l, r}) + else + levelOrder(tail) + end if + else + {} + end if +end levelOrder + +-- nodeParts :: Tree -> (Int, Tree, Tree) +on nodeParts(tree) + if class of tree is list and length of tree = 3 then + tree + else + {tree} & {{}, {}} + end if +end nodeParts + + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- A list of functions applied to a list of arguments +-- (<*> | ap) :: [(a -> b)] -> [a] -> [b] +on ap(fs, xs) + set lngFs to length of fs + set lngXs to length of xs + set lst to {} + repeat with i from 1 to lngFs + tell mReturn(contents of item i of fs) + repeat with j from 1 to lngXs + set end of lst to |λ|(contents of (item j of xs)) + end repeat + end tell + end repeat + return lst +end ap + +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + +-- justifyLeft :: Int -> Char -> Text -> Text +on justifyLeft(n, cFiller, strText) + if n > length of strText then + text 1 thru n of (strText & replicate(n, cFiller)) + else + strText + end if +end justifyLeft + +-- min :: Ord a => a -> a -> a +on min(x, y) + if y < x then + y + else + x + end if +end min + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- replicate :: Int -> a -> [a] +on replicate(n, a) + set out to {} + if n < 1 then return out + set dbl to {a} + + repeat while (n > 1) + if (n mod 2) > 0 then set out to out & dbl + set n to (n div 2) + set dbl to (dbl & dbl) + end repeat + return out & dbl +end replicate + +-- uncons :: [a] -> Maybe (a, [a]) +on uncons(xs) + if length of xs > 0 then + {item 1 of xs, rest of xs} + else + missing value + end if +end uncons + +-- unlines :: [String] -> String +on unlines(xs) + intercalate(linefeed, xs) +end unlines + +-- unwords :: [String] -> String +on unwords(xs) + intercalate(space, xs) +end unwords + +-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] +on zipWith(f, xs, ys) + set lng to min(length of xs, length of ys) + set lst to {} + tell mReturn(f) + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, item i of ys) + end repeat + return lst + end tell +end zipWith diff --git a/Task/Tree-traversal/Coq/tree-traversal.coq b/Task/Tree-traversal/Coq/tree-traversal.coq new file mode 100644 index 0000000000..323666b937 --- /dev/null +++ b/Task/Tree-traversal/Coq/tree-traversal.coq @@ -0,0 +1,51 @@ +Require Import Utf8. +Require Import List. + +Unset Elimination Schemes. + +(* Rose tree, with numbers on nodes *) +Inductive tree := Tree { value : nat ; children : list tree }. + +Fixpoint height (t: tree) : nat := + 1 + fold_left (λ n t, max n (height t)) (children t) 0. + +Example leaf n : tree := {| value := n ; children := nil |}. + +Example t2 : tree := {| value := 2 ; children := {| value := 4 ; children := leaf 7 :: nil |} :: leaf 5 :: nil |}. + +Example t3 : tree := {| value := 3 ; children := {| value := 6 ; children := leaf 8 :: leaf 9 :: nil |} :: nil |}. + +Example t9 : tree := {| value := 1 ; children := t2 :: t3 :: nil |}. + +Fixpoint preorder (t: tree) : list nat := + let '{| value := n ; children := c |} := t in + n :: flat_map preorder c. + +Fixpoint inorder (t: tree) : list nat := + let '{| value := n ; children := c |} := t in + match c with + | nil => n :: nil + | ℓ :: r => inorder ℓ ++ n :: flat_map inorder r + end. + +Fixpoint postorder (t: tree) : list nat := + let '{| value := n ; children := c |} := t in + flat_map postorder c ++ n :: nil. + +(* Auxiliary function for levelorder, which operates on forests *) +(* Since the recursion is tricky, it relies on a fuel parameter which obviously decreases. *) +Fixpoint levelorder_forest (fuel: nat) (f: list tree) : list nat:= + match fuel with + | O => nil + | S fuel' => + let '(p, f) := fold_right (λ t r, let '(x, f) := r in (value t :: x, children t ++ f) ) (nil, nil) f in + p ++ levelorder_forest fuel' f + end. + +Definition levelorder (t: tree) : list nat := + levelorder_forest (height t) (t :: nil). + +Compute preorder t9. +Compute inorder t9. +Compute postorder t9. +Compute levelorder t9. diff --git a/Task/Tree-traversal/Haskell/tree-traversal.hs b/Task/Tree-traversal/Haskell/tree-traversal.hs index 731787ea54..788691fdad 100644 --- a/Task/Tree-traversal/Haskell/tree-traversal.hs +++ b/Task/Tree-traversal/Haskell/tree-traversal.hs @@ -1,45 +1,55 @@ -data Tree a = Empty - | Node { value :: a, - left :: Tree a, - right :: Tree a } +data Tree a + = Empty + | Node { value :: a + , left :: Tree a + , right :: Tree a} preorder, inorder, postorder, levelorder :: Tree a -> [a] +preorder Empty = [] +preorder (Node v l r) = v : preorder l ++ preorder r -preorder Empty = [] -preorder (Node v l r) = [v] - ++ preorder l - ++ preorder r +inorder Empty = [] +inorder (Node v l r) = inorder l ++ (v : inorder r) -inorder Empty = [] -inorder (Node v l r) = inorder l - ++ [v] - ++ inorder r - -postorder Empty = [] -postorder (Node v l r) = postorder l - ++ postorder r - ++ [v] +postorder Empty = [] +postorder (Node v l r) = postorder l ++ postorder r ++ [v] levelorder x = loop [x] - where loop [] = [] - loop (Empty : xs) = loop xs - loop (Node v l r : xs) = v : loop (xs ++ [l,r]) + where + loop [] = [] + loop (Empty:xs) = loop xs + loop (Node v l r:xs) = v : loop (xs ++ [l, r]) +-- TEST -------------------------------------------------------------- tree :: Tree Int -tree = Node 1 - (Node 2 - (Node 4 - (Node 7 Empty Empty) - Empty) - (Node 5 Empty Empty)) - (Node 3 - (Node 6 - (Node 8 Empty Empty) - (Node 9 Empty Empty)) - Empty) +tree = + Node + 1 + (Node 2 (Node 4 (Node 7 Empty Empty) Empty) (Node 5 Empty Empty)) + (Node 3 (Node 6 (Node 8 Empty Empty) (Node 9 Empty Empty)) Empty) +asciiTree :: String +asciiTree = + unlines + [ " 1" + , " / \\" + , " / \\" + , " / \\" + , " 2 3" + , " / \\ /" + , " 4 5 6" + , " / / \\" + , " 7 8 9" + ] + +-- OUTPUT -------------------------------------------------------------- main :: IO () -main = do print $ preorder tree - print $ inorder tree - print $ postorder tree - print $ levelorder tree +main = do + putStrLn asciiTree + mapM_ putStrLn $ + zipWith + (\s xs -> justifyLeft 14 ' ' (s ++ ":") ++ unwords (show <$> xs)) + ["preorder", "inorder", "postorder", "level-order"] + ([preorder, inorder, postorder, levelorder] <*> [tree]) + where + justifyLeft n c s = take n (s ++ replicate n c) diff --git a/Task/Tree-traversal/Java/tree-traversal.java b/Task/Tree-traversal/Java/tree-traversal.java index ccaf0ac6dc..39cf217ad6 100644 --- a/Task/Tree-traversal/Java/tree-traversal.java +++ b/Task/Tree-traversal/Java/tree-traversal.java @@ -1,105 +1,87 @@ -import java.util.Queue; -import java.util.LinkedList; -public class TreeTraverse -{ - private static class Node - { - public Node left; - public Node right; - public T data; - public Node(T data) - { - this.data = data; - } - public Node getLeft() - { - return this.left; - } - public void setLeft(Node left) - { - this.left = left; - } - public Node getRight() - { - return this.right; - } - public void setRight(Node right) - { - this.right = right; - } - } - public static void preorder(Node n) - { - if (n != null) - { - System.out.print(n.data + " "); - preorder(n.getLeft()); - preorder(n.getRight()); - } - } - public static void inorder(Node n) - { - if (n != null) - { - inorder(n.getLeft()); - System.out.print(n.data + " "); - inorder(n.getRight()); - } - } - public static void postorder(Node n) - { - if (n != null) - { - postorder(n.getLeft()); - postorder(n.getRight()); - System.out.print(n.data + " "); - } - } - public static void levelorder(Node n) - { - Queue> nodequeue = new LinkedList>(); - if (n != null) - nodequeue.add(n); - while (!nodequeue.isEmpty()) - { - Node next = nodequeue.remove(); - System.out.print(next.data + " "); - if (next.getLeft() != null) - { - nodequeue.add(next.getLeft()); - } - if (next.getRight() != null) - { - nodequeue.add(next.getRight()); - } - } - } - public static void main(final String[] args) - { - Node one = new Node(1); - Node two = new Node(2); - Node three = new Node(3); - Node four = new Node(4); - Node five = new Node(5); - Node six = new Node(6); - Node seven = new Node(7); - Node eight = new Node(8); - Node nine = new Node(9); - one.setLeft(two); - one.setRight(three); - two.setLeft(four); - two.setRight(five); - three.setLeft(six); - four.setLeft(seven); - six.setLeft(eight); - six.setRight(nine); - preorder(one); - System.out.println(); - inorder(one); - System.out.println(); - postorder(one); - System.out.println(); - levelorder(one); - System.out.println(); - } +import java.util.*; + +public class TreeTraversal { + + static class Node { + T value; + Node left; + Node right; + + Node(T value) { + this.value = value; + } + + void visit() { + System.out.print(this.value + " "); + } + } + + static enum ORDER { + PREORDER, INORDER, POSTORDER, LEVEL + } + + static void traverse(Node node, ORDER order) { + if (node == null) { + return; + } + switch (order) { + case PREORDER: + node.visit(); + traverse(node.left, order); + traverse(node.right, order); + break; + case INORDER: + traverse(node.left, order); + node.visit(); + traverse(node.right, order); + break; + case POSTORDER: + traverse(node.left, order); + traverse(node.right, order); + node.visit(); + break; + case LEVEL: + Queue> queue = new LinkedList<>(); + queue.add(node); + while(!queue.isEmpty()){ + Node next = queue.remove(); + next.visit(); + if(next.left!=null) + queue.add(next.left); + if(next.right!=null) + queue.add(next.right); + } + } + } + + public static void main(String[] args) { + + Node one = new Node(1); + Node two = new Node(2); + Node three = new Node(3); + Node four = new Node(4); + Node five = new Node(5); + Node six = new Node(6); + Node seven = new Node(7); + Node eight = new Node(8); + Node nine = new Node(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); + System.out.println(); + traverse(one, ORDER.INORDER); + System.out.println(); + traverse(one, ORDER.POSTORDER); + System.out.println(); + traverse(one, ORDER.LEVEL); + + } } diff --git a/Task/Tree-traversal/JavaScript/tree-traversal-6.js b/Task/Tree-traversal/JavaScript/tree-traversal-6.js new file mode 100644 index 0000000000..8666082182 --- /dev/null +++ b/Task/Tree-traversal/JavaScript/tree-traversal-6.js @@ -0,0 +1,99 @@ +(() => { + // TRAVERSALS ------------------------------------------------------------- + + // preorder Tree a -> [a] + const preorder = a => [a[v]] + .concat(a[l] ? preorder(a[l]) : []) + .concat(a[r] ? preorder(a[r]) : []); + + // inorder Tree a -> [a] + const inorder = a => + (a[l] ? inorder(a[l]) : []) + .concat(a[v]) + .concat(a[r] ? inorder(a[r]) : []); + + // postorder Tree a -> [a] + const postorder = a => + (a[l] ? postorder(a[l]) : []) + .concat(a[r] ? postorder(a[r]) : []) + .concat(a[v]); + + // levelorder Tree a -> [a] + const levelorder = a => (function go(x) { + return x.length ? ( + x[0] ? ( + [x[0][v]].concat( + go(x.slice(1) + .concat([x[0][l], x[0][r]]) + ) + ) + ) : go(x.slice(1)) + ) : []; + })([a]); + + + // GENERIC FUNCTIONS ----------------------------------------------------- + + // A list of functions applied to a list of arguments + // <*> :: [(a -> b)] -> [a] -> [b] + const ap = (fs, xs) => // + [].concat.apply([], fs.map(f => // + [].concat.apply([], xs.map(x => [f(x)])))); + + // intercalate :: String -> [a] -> String + const intercalate = (s, xs) => xs.join(s); + + // justifyLeft :: Int -> Char -> Text -> Text + const justifyLeft = (n, cFiller, strText) => + n > strText.length ? ( + (strText + cFiller.repeat(n)) + .substr(0, n) + ) : strText; + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + // unwords :: [String] -> String + const unwords = xs => xs.join(' '); + + // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] + const zipWith = (f, xs, ys) => + Array.from({ + length: Math.min(xs.length, ys.length) + }, (_, i) => f(xs[i], ys[i])); + + // TEST ------------------------------------------------------------------- + // asciiTree :: String + const asciiTree = unlines([ + ' 1', + ' / \\', + ' / \\', + ' / \\', + ' 2 3', + ' / \\ /', + ' 4 5 6', + ' / / \\', + ' 7 8 9' + ]); + + const [v, l, r] = [0, 1, 2], + tree = [1, [2, [4, [7]], + [5] + ], + [3, [6, [8], + [9] + ]] + ], + + // fs :: [(Tree a -> [a])] + fs = [preorder, inorder, postorder, levelorder]; + + return asciiTree + '\n\n' + + intercalate('\n', + zipWith( + (f, xs) => justifyLeft(12, ' ', f.name + ':') + unwords(xs), + fs, + ap(fs, [tree]) + ) + ); +})(); diff --git a/Task/Tree-traversal/JavaScript/tree-traversal-7.js b/Task/Tree-traversal/JavaScript/tree-traversal-7.js new file mode 100644 index 0000000000..c39781545b --- /dev/null +++ b/Task/Tree-traversal/JavaScript/tree-traversal-7.js @@ -0,0 +1,14 @@ + 1 + / \ + / \ + / \ + 2 3 + / \ / + 4 5 6 + / / \ + 7 8 9 + +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 +levelorder: 1 2 3 4 5 6 7 8 9 diff --git a/Task/Tree-traversal/jq/tree-traversal-1.jq b/Task/Tree-traversal/Jq/tree-traversal-1.jq similarity index 100% rename from Task/Tree-traversal/jq/tree-traversal-1.jq rename to Task/Tree-traversal/Jq/tree-traversal-1.jq diff --git a/Task/Tree-traversal/jq/tree-traversal-2.jq b/Task/Tree-traversal/Jq/tree-traversal-2.jq similarity index 100% rename from Task/Tree-traversal/jq/tree-traversal-2.jq rename to Task/Tree-traversal/Jq/tree-traversal-2.jq diff --git a/Task/Tree-traversal/Kotlin/tree-traversal-2.kotlin b/Task/Tree-traversal/Kotlin/tree-traversal-2.kotlin index bfe9b061d3..2eb5f0d3d0 100644 --- a/Task/Tree-traversal/Kotlin/tree-traversal-2.kotlin +++ b/Task/Tree-traversal/Kotlin/tree-traversal-2.kotlin @@ -1,27 +1,27 @@ -data class Node(val v: Int, var left: Node? = null, var right: Node? = null) { - override fun toString() = " $v" - - fun preOrder() { print(this); left?.preOrder(); right?.preOrder() } - fun inorder() { left?.inorder(); print(this); right?.inorder() } - fun postOrder() { left?.postOrder(); right?.postOrder(); print(this) } - - fun levelOrder() = with(mutableListOf(this)) { - do { - val node = removeAt(0) - print(node) - node.left?.let { add(it) } - node.right?.let { add(it) } - } while (any()) - } - - inline fun exec(name: String, f: (Node) -> Unit) { - print(name) - f(this) - println() - } -} - fun main(args: Array) { + data class Node(val v: Int, var left: Node? = null, var right: Node? = null) { + override fun toString() = " $v" + + fun preOrder() { print(this); left?.preOrder(); right?.preOrder() } + fun inorder() { left?.inorder(); print(this); right?.inorder() } + fun postOrder() { left?.postOrder(); right?.postOrder(); print(this) } + + fun levelOrder() = with(mutableListOf(this)) { + do { + val node = removeAt(0) + print(node) + node.left?.let { add(it) } + node.right?.let { add(it) } + } while (any()) + } + + inline fun exec(name: String, f: (Node) -> Unit) { + print(name) + f(this) + println() + } + } + val nodes = Array(10) { Node(it) } nodes[1].left = nodes[2] diff --git a/Task/Tree-traversal/OoRexx/tree-traversal.rexx b/Task/Tree-traversal/OoRexx/tree-traversal.rexx new file mode 100644 index 0000000000..246874b674 --- /dev/null +++ b/Task/Tree-traversal/OoRexx/tree-traversal.rexx @@ -0,0 +1,83 @@ + one = .Node~new(1); + two = .Node~new(2); + three = .Node~new(3); + four = .Node~new(4); + five = .Node~new(5); + six = .Node~new(6); + seven = .Node~new(7); + eight = .Node~new(8); + nine = .Node~new(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 + + out = .array~new + .treetraverser~preorder(one, out); + say "Preorder: " out~toString("l", ", ") + out~empty + .treetraverser~inorder(one, out); + say "Inorder: " out~toString("l", ", ") + out~empty + .treetraverser~postorder(one, out); + say "Postorder: " out~toString("l", ", ") + out~empty + .treetraverser~levelorder(one, out); + say "Levelorder:" out~toString("l", ", ") + + +::class node +::method init + expose left right data + use strict arg data + left = .nil + right = .nil + +::attribute left +::attribute right +::attribute data + +::class treeTraverser +::method preorder class + use arg node, out + if node \== .nil then do + out~append(node~data) + self~preorder(node~left, out) + self~preorder(node~right, out) + end + +::method inorder class + use arg node, out + if node \== .nil then do + self~inorder(node~left, out) + out~append(node~data) + self~inorder(node~right, out) + end + +::method postorder class + use arg node, out + if node \== .nil then do + self~postorder(node~left, out) + self~postorder(node~right, out) + out~append(node~data) + end + +::method levelorder class + use arg node, out + + if node == .nil then return + nodequeue = .queue~new + nodequeue~queue(node) + loop while \nodequeue~isEmpty + next = nodequeue~pull + out~append(next~data) + if next~left \= .nil then + nodequeue~queue(next~left) + if next~right \= .nil then + nodequeue~queue(next~right) + end diff --git a/Task/Tree-traversal/SequenceL/tree-traversal.sequencel b/Task/Tree-traversal/SequenceL/tree-traversal.sequencel new file mode 100644 index 0000000000..44fd254863 --- /dev/null +++ b/Task/Tree-traversal/SequenceL/tree-traversal.sequencel @@ -0,0 +1,42 @@ +main(args(2)) := + "preorder: " ++ toString(preOrder(testTree)) ++ + "\ninoder: " ++ toString(inOrder(testTree)) ++ + "\npostorder: " ++ toString(postOrder(testTree)) ++ + "\nlevel-order: " ++ toString(levelOrder(testTree)); + +Node ::= (value : int, left : Node, right : Node); + +preOrder(n) := [n.value] ++ + (preOrder(n.left) when isDefined(n, left) else []) ++ + (preOrder(n.right) when isDefined(n, right) else []); + +inOrder(n) := (inOrder(n.left) when isDefined(n, left) else []) ++ + [n.value] ++ + (inOrder(n.right) when isDefined(n, right) else []); + +postOrder(n) := (postOrder(n.left) when isDefined(n, left) else []) ++ + (postOrder(n.right) when isDefined(n, right) else []) ++ + [n.value]; + +levelOrder(n) := levelOrderHelper([n]); +levelOrderHelper(ns(1)) := + let + n := head(ns); + in + [] when size(ns) = 0 else + [n.value] ++ levelOrderHelper(tail(ns) ++ + ([n.left] when isDefined(n, left) else []) ++ + ([n.right] when isDefined(n, right) else [])); + +testTree := + (value : 1, + left : (value : 2, + left : (value : 4, + left : (value : 7)), + right : (value : 5)), + right : (value : 3, + left : (value : 6, + left : (value : 8), + right : (value : 9)) + ) + ); diff --git a/Task/Tree-traversal/Zkl/tree-traversal-1.zkl b/Task/Tree-traversal/Zkl/tree-traversal-1.zkl new file mode 100644 index 0000000000..9cadee4dd8 --- /dev/null +++ b/Task/Tree-traversal/Zkl/tree-traversal-1.zkl @@ -0,0 +1,31 @@ +class Node{ var [mixin=Node]left,right; var v; + fcn init(val,[Node]l=Void,[Node]r=Void) { v,left,right=vm.arglist } +} + +class BTree{ var [mixin=Node] root; + fcn init(r){ root=r } + const VISIT=Void, LEFT="left", RIGHT="right"; + fcn preOrder { traverse(VISIT,LEFT, RIGHT) } + fcn inOrder { traverse(LEFT, VISIT,RIGHT) } + fcn postOrder { traverse(LEFT, RIGHT,VISIT) } + fcn [private] traverse(order){ //--> list of Nodes + sink:=List(); + fcn(sink,[Node]n,order){ + if(n){ foreach o in (order){ + if(VISIT==o) sink.write(n); + else self.fcn(sink,n.setVar(o),order); // actually get var, eg n.left + }} + }(sink,root,vm.arglist); + sink + } + fcn levelOrder{ // breadth first + sink:=List(); q:=List(root); + while(q){ + n:=q.pop(0); l:=n.left; r:=n.right; + sink.write(n); + if(l) q.append(l); + if(r) q.append(r); + } + sink + } +} diff --git a/Task/Tree-traversal/Zkl/tree-traversal-2.zkl b/Task/Tree-traversal/Zkl/tree-traversal-2.zkl new file mode 100644 index 0000000000..2c397face1 --- /dev/null +++ b/Task/Tree-traversal/Zkl/tree-traversal-2.zkl @@ -0,0 +1,11 @@ +t:=BTree(Node(1, + Node(2, + Node(4,Node(7)), + Node(5)), + Node(3, + Node(6, Node(8),Node(9))))); + +t.preOrder() .apply("v").println(" preorder"); +t.inOrder() .apply("v").println(" inorder"); +t.postOrder() .apply("v").println(" postorder"); +t.levelOrder().apply("v").println(" level-order"); diff --git a/Task/Trigonometric-functions/BaCon/trigonometric-functions.bacon b/Task/Trigonometric-functions/BaCon/trigonometric-functions.bacon new file mode 100644 index 0000000000..0091a39a9e --- /dev/null +++ b/Task/Trigonometric-functions/BaCon/trigonometric-functions.bacon @@ -0,0 +1,16 @@ +' Trigonometric functions in BaCon use Radians for input values +' The RAD() function converts from degrees to radians + +FOR v$ IN "0, 10, 45, 90, 190.5" + d = VAL(v$) * 1.0 + r = RAD(d) * 1.0 + + PRINT "Sine: ", d, " degrees (or ", r, " radians) is ", SIN(r) + PRINT "Cosine: ", d, " degrees (or ", r, " radians) is ", COS(r) + PRINT "Tangent: ", d, " degrees (or ", r, " radians) is ", TAN(r) + PRINT + PRINT "Arc Sine: ", SIN(r), " is ", DEG(ASIN(SIN(r))), " degrees (or ", ASIN(SIN(r)), " radians)" + PRINT "Arc CoSine: ", COS(r), " is ", DEG(ACOS(COS(r))), " degrees (or ", ACOS(COS(r)), " radians)" + PRINT "Arc Tangent: ", TAN(r), " is ", DEG(ATN(TAN(r))), " degrees (or ", ATN(TAN(r)), " radians)" + PRINT +NEXT diff --git a/Task/Trigonometric-functions/Bc/trigonometric-functions.bc b/Task/Trigonometric-functions/Bc/trigonometric-functions.bc new file mode 100644 index 0000000000..c2d8b8b095 --- /dev/null +++ b/Task/Trigonometric-functions/Bc/trigonometric-functions.bc @@ -0,0 +1,55 @@ +/* t(x) = tangent of x */ +define t(x) { + return s(x) / c(x) +} + +/* y(y) = arcsine of y, domain [-1, 1], range [-pi/2, pi/2] */ +define y(y) { + /* Handle angles with no tangent. */ + if (y == -1) return -2 * a(1) /* -pi/2 */ + if (y == 1) return 2 * a(1) /* pi/2 */ + + /* Tangent of angle is y / x, where x^2 + y^2 = 1. */ + return a(y / sqrt(1 - y * y)) +} + +/* x(x) = arccosine of x, domain [-1, 1], range [0, pi] */ +define x(x) { + auto a + + /* Handle angle with no tangent. */ + if (x == 0) return 2 * a(1) /* pi/2 */ + + /* Tangent of angle is y / x, where x^2 + y^2 = 1. */ + a = a(sqrt(1 - x * x) / x) + if (a < 0) { + return a + 4 * a(1) /* add pi */ + } else { + return a + } +} + + +scale = 50 +p = 4 * a(1) /* pi */ +d = p / 180 /* one degree in radians */ + +"Using radians: +" +" sin(-pi / 6) = "; s(-p / 6) +" cos(3 * pi / 4) = "; c(3 * p / 4) +" tan(pi / 3) = "; t(p / 3) +" asin(-1 / 2) = "; y(-1 / 2) +" acos(-sqrt(2) / 2) = "; x(-sqrt(2) / 2) +" atan(sqrt(3)) = "; a(sqrt(3)) + +"Using degrees: +" +" sin(-30) = "; s(-30 * d) +" cos(135) = "; c(135 * d) +" tan(60) = "; t(60 * d) +" asin(-1 / 2) = "; y(-1 / 2) / d +" acos(-sqrt(2) / 2) = "; x(-sqrt(2) / 2) / d +" atan(sqrt(3)) = "; a(sqrt(3)) / d + +quit diff --git a/Task/Trigonometric-functions/Elena/trigonometric-functions.elena b/Task/Trigonometric-functions/Elena/trigonometric-functions.elena index 45970fe38d..ce75d5f558 100644 --- a/Task/Trigonometric-functions/Elena/trigonometric-functions.elena +++ b/Task/Trigonometric-functions/Elena/trigonometric-functions.elena @@ -1,23 +1,24 @@ -#import system. -#import system'math. -#import extensions. +import system'math. +import extensions. -#symbol program = +program = [ - console writeLine:"Radians:". - console writeLine:"sin(π/3) = ":((pi_value/3) sin). - console writeLine:"cos(π/3) = ":((pi_value/3) cos). - console writeLine:"tan(π/3) = ":((pi_value/3) tan). - console writeLine:"arcsin(1/2) = ":(0.5r arcsin). - console writeLine:"arccos(1/2) = ":(0.5r arccos). - console writeLine:"arctan(1/2) = ":(0.5r arctan). - console writeLine. + 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 writeLine:"Degrees:". - console writeLine:"sin(60º) = ":(60.0r radian sin). - console writeLine:"cos(60º) = ":(60.0r radian cos). - console writeLine:"tan(60º) = ":(60.0r radian tan). - console writeLine:"arcsin(1/2) = ":(0.5r arcsin degree):"º". - console writeLine:"arccos(1/2) = ":(0.5r arccos degree):"º". - console writeLine:"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. ]. diff --git a/Task/Trigonometric-functions/Fortran/trigonometric-functions-2.f b/Task/Trigonometric-functions/Fortran/trigonometric-functions-2.f index fbcdf9e10a..e7253702ce 100644 --- a/Task/Trigonometric-functions/Fortran/trigonometric-functions-2.f +++ b/Task/Trigonometric-functions/Fortran/trigonometric-functions-2.f @@ -1,4 +1,4 @@ -ATAN2(y,x) ! Arctangent(y/x), ''-pi < result <= +pi'' -SINH(x) ! Hyperbolic sine -COSH(x) ! Hyperbolic cosine -TANH(x) ! Hyperbolic tangent + ATAN2(y,x) ! Arctangent(y/x), ''-pi < result <= +pi'' + SINH(x) ! Hyperbolic sine + COSH(x) ! Hyperbolic cosine + TANH(x) ! Hyperbolic tangent diff --git a/Task/Trigonometric-functions/Haskell/trigonometric-functions.hs b/Task/Trigonometric-functions/Haskell/trigonometric-functions.hs index 536ca9dbcf..4772255154 100644 --- a/Task/Trigonometric-functions/Haskell/trigonometric-functions.hs +++ b/Task/Trigonometric-functions/Haskell/trigonometric-functions.hs @@ -1,10 +1,23 @@ +fromDegrees :: Floating a => a -> a fromDegrees deg = deg * pi / 180 -toDegrees rad = rad * 180 / pi -example = [ - sin (pi / 6), sin (fromDegrees 30), - cos (pi / 6), cos (fromDegrees 30), - tan (pi / 6), tan (fromDegrees 30), - asin 0.5, toDegrees (asin 0.5), - acos 0.5, toDegrees (acos 0.5), - atan 0.5, toDegrees (atan 0.5)] +toDegrees :: Floating a => a -> a +toDegrees rad = rad * 180 / pi + +main :: IO () +main = + mapM_ + print + [ sin (pi / 6) + , sin (fromDegrees 30) + , cos (pi / 6) + , cos (fromDegrees 30) + , tan (pi / 6) + , tan (fromDegrees 30) + , asin 0.5 + , toDegrees (asin 0.5) + , acos 0.5 + , toDegrees (acos 0.5) + , atan 0.5 + , toDegrees (atan 0.5) + ] diff --git a/Task/Trigonometric-functions/jq/trigonometric-functions-1.jq b/Task/Trigonometric-functions/Jq/trigonometric-functions-1.jq similarity index 100% rename from Task/Trigonometric-functions/jq/trigonometric-functions-1.jq rename to Task/Trigonometric-functions/Jq/trigonometric-functions-1.jq diff --git a/Task/Trigonometric-functions/jq/trigonometric-functions-2.jq b/Task/Trigonometric-functions/Jq/trigonometric-functions-2.jq similarity index 100% rename from Task/Trigonometric-functions/jq/trigonometric-functions-2.jq rename to Task/Trigonometric-functions/Jq/trigonometric-functions-2.jq diff --git a/Task/Trigonometric-functions/Julia/trigonometric-functions.julia b/Task/Trigonometric-functions/Julia/trigonometric-functions.julia new file mode 100644 index 0000000000..c26068df3b --- /dev/null +++ b/Task/Trigonometric-functions/Julia/trigonometric-functions.julia @@ -0,0 +1,12 @@ +# v0.6.0 + +rad = π / 4 +deg = 45.0 + +@show rad deg +@show sin(rad) sin(deg2rad(deg)) +@show cos(rad) cos(deg2rad(deg)) +@show tan(rad) tan(deg2rad(deg)) +@show asin(sin(rad)) asin(sin(rad)) |> rad2deg +@show acos(cos(rad)) acos(cos(rad)) |> rad2deg +@show atan(tan(rad)) atan(tan(rad)) |> rad2deg diff --git a/Task/Trigonometric-functions/Kotlin/trigonometric-functions.kotlin b/Task/Trigonometric-functions/Kotlin/trigonometric-functions.kotlin new file mode 100644 index 0000000000..c332b97be7 --- /dev/null +++ b/Task/Trigonometric-functions/Kotlin/trigonometric-functions.kotlin @@ -0,0 +1,23 @@ +// version 1.1.2 + +import java.lang.Math.* + +fun main(args: Array) { + val radians = Math.PI / 4.0 + val degrees = 45.0 + val conv = Math.PI / 180.0 + val f = "%1.15f" + var inverse: Double + + println(" Radians Degrees") + println("Angle : ${f.format(radians)}\t ${f.format(degrees)}\n") + println("Sin : ${f.format(sin(radians))}\t ${f.format(sin(degrees * conv))}") + println("Cos : ${f.format(cos(radians))}\t ${f.format(cos(degrees * conv))}") + println("Tan : ${f.format(tan(radians))}\t ${f.format(tan(degrees * conv))}\n") + inverse = asin(sin(radians)) + println("ASin(Sin) : ${f.format(inverse)}\t ${f.format(inverse / conv)}") + inverse = acos(cos(radians)) + println("ACos(Cos) : ${f.format(inverse)}\t ${f.format(inverse / conv)}") + inverse = atan(tan(radians)) + println("ATan(Tan) : ${f.format(inverse)}\t ${f.format(inverse / conv)}") +} diff --git a/Task/Trigonometric-functions/OoRexx/trigonometric-functions-1.rexx b/Task/Trigonometric-functions/OoRexx/trigonometric-functions-1.rexx new file mode 100644 index 0000000000..f61d5a3419 --- /dev/null +++ b/Task/Trigonometric-functions/OoRexx/trigonometric-functions-1.rexx @@ -0,0 +1,18 @@ +/* REXX --------------------------------------------------------------- +* show how the functions can be used +* 03.05.2014 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 'Changed precision:' .locaL~my.rxm~precision() +Say 'Changed type: ' .locaL~my.rxm~type() +Say 'rxmsin(1) ='rxmsin(1) -- 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 new file mode 100644 index 0000000000..f498fc93f9 --- /dev/null +++ b/Task/Trigonometric-functions/OoRexx/trigonometric-functions-2.rexx @@ -0,0 +1,1037 @@ +/******************************************************************** +* Package rxm +* implements the functions available in RxMath with high precision +* by computing the values with significantly increased precision +* and rounding the result to the specified precision. +* This started 10 years ago when Vladimir Zabrodsky published his +* Album of Algorithms http://dhost.info/zabrodskyvlada/aat/ +* Gerard Schildberger suggests on rosettacode.org to use +10 digits +* Rony Flatscher suggested and helped to turn this into an ooRexx class +* Rick McGuire advised on using Use STRICT Arg for argument checking +* Alexander Seik creates this documentation +* Horst Wegscheider helped with reviewing and some improvements +* 12.04.2014 Walter Pachl +* Documentation: see rxmath.pdf in the ooRexx distribution +* and rxm.doc (here) +* 13.04.2014 WP arcsin and arctan commentary corrected (courtesy Horst) +* 13.04.2014 WP improve arctan performance +* 20.04.2014 WP towards completion +* 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 +**********************************************************************/ +.local~my.rxm=.rxm~new(16,"D") + +::Class rxm Public + +::Method init + Expose precision type + Use Arg precision=(digits()),type='D' + +::attribute precision set + Expose precision + Use Strict Arg precision=(digits()) + +::attribute precision get + +::attribute type set + Expose type + Use Strict Arg type='R' + +::attribute type get + +::Method arccos +/*********************************************************************** +* 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) + iprec=xprec+10 + Numeric Digits iprec + If x=1 Then + r=0 + Else Do + r=self~arcsin(x,iprec,'R') + If r='nan' Then + Return r + r=self~pi(iprec)/2 - r + End + Select + When xtype='D' Then + r=r*180/self~pi(iprec) + When xtype='G' Then + r=r*200/self~pi(iprec) + Otherwise + Nop + End + Numeric Digits xprec + Return (r+0) + +::Method arcsin +/*********************************************************************** +* 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) + iprec=xprec+10 + Numeric Digits iprec + sign=sign(x) + If x<0 Then + x=abs(x) + Select + When abs(x)>1 Then + Return 'nan' + When x=0 Then + r=0 + When x=1 Then + r=rxmpi(iprec)/2 + When x<0.8 Then Do + o=x + u=1 + r=x + Do i=3 By 2 Until ra=r + ra=r + o=o*x*x*(i-2) + u=u*(i-1)*i/(i-2) + r=r+(o/u) + If r=ra Then + r=r+(o/u)/2 /* final touch */ + End + End + Otherwise Do + z=x + r=x + o=x + s=x*x + do j=2 by 2; + o=o*s*(j-1)/j; + z=z+o/(j+1); + if z=r then + leave + r=z; + end + /*********************** + y=(1-x*x)/4 + n=0.5-self~sqrt(y,iprec) + z=self~sqrt(n,iprec) + r=2*self~arcsin(z,xprec) + ***********************/ + End + End + Select + When xtype='D' Then + r=r*180/self~pi(iprec) + When xtype='G' Then + r=r*200/self~pi(iprec) + Otherwise + Nop + End + Numeric Digits xprec + Return sign*(r+0) + +::Method arctan +/*********************************************************************** +* Return arctan(x,precision,type) -- with specified precision +* x=0 -> arctan(x) = 0 +* If x>0 Then +* x<1 -> arctan(x) = arcsin(x/sqrt(x**2+1)) +* x=1 -> arctan(x) = pi/4 +* x>1 -> arctan(x) = pi/2-arcsin((1/x)/sqrt((1/x)**2+1)) +* Else +* adjust as necessary +***********************************************************************/ + Expose precision type + Use Strict Arg x,xprec=(precision),xtype=(type) + iprec=xprec+10 + Numeric Digits iprec + Select + When abs(x)<1 Then + r=self~arcsin(x/self~sqrt(1+x**2,iprec),iprec,'R') + When abs(x)=1 Then + r=self~pi(iprec)/4*sign(x) + Otherwise Do + xr=1/abs(x) + r=self~arcsin(xr/self~sqrt(1+xr**2,iprec),iprec,'R') + If x>0 Then + r=self~pi(iprec)/2-r + Else + r=-self~pi(iprec)/2+r + End + End + Select + When xtype='D' Then + r=r*180/self~pi(iprec) + When xtype='G' Then + r=r*200/self~pi(iprec) + Otherwise + Nop + End + Numeric Digits xprec + Return (r+0) + +::Method arsinh +/*********************************************************************** +* Return arsinh(x,precision,type) -- with specified precision +* arsinh(x) = ln(x+sqrt(x**2+1)) +***********************************************************************/ + Expose precision + Use Strict Arg x,xprec=(precision) + iprec=xprec+10 + Numeric Digits iprec + x2p1=x**2+1 + r=self~log(x+self~sqrt(x2p1,iprec),iprec) + Numeric Digits xprec + Return (r+0) + +::Method cos +/* 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) + iprec=xprec+10 + Numeric Digits iprec + Select + When xtype='R' Then xa=x+self~pi(iprec)/2 + When xtype='D' Then xa=x+90 + When xtype='G' Then xa=x+100 + End + r=self~sin(xa,iprec,xtype) + Numeric Digits xprec + Return (r+0) + +::Method cosh +/* REXX **************************************************************** +* Return cosh(x,precision,type) -- with specified precision +* cosh(x) = 1+(x**2/2!)+(x**4/4!)+(x**6/6!)+-... +***********************************************************************/ + Expose precision + Use Strict Arg x,xprec=(precision) + iprec=xprec+10 + Numeric Digits iprec + o=1 + u=1 + r=1 + Do i=2 By 2 Until ra=r + ra=r + o=o*x*x + u=u*i*(i-1) + r=r+(o/u) + End + Numeric Digits xprec + Return (r+0) + +::Method cotan +/* 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) + iprec=xprec+10 + Numeric Digits iprec + s=self~sin(x,iprec,xtype) + c=self~cos(x,iprec,xtype) + If s=0 Then + Return '+infinity' + r=c/s + Numeric Digits xprec + Return (r+0) + +::Method exp +/*********************************************************************** +* exp(x,precision) returns e**x -- with specified precision +* exp(x,precision,base) returns base**x -- with specified precision +***********************************************************************/ + Expose precision + Use Strict Arg x,xprec=(precision),xbase='' + iprec=xprec+10 + Numeric Digits iprec + Numeric Fuzz 3 + If xbase<>'' Then Do + Select + When xbase=0 Then Do + Select + When x<0 Then Return '+infinity' + When x=0 Then Return 'nan' + Otherwise Return 0 + End + End + When xbase=1 Then Return 1 + When xbase<0 Then Do + Select + When x=0 Then Return 1 + When datatype(x,'W')=0 Then Return 'nan' + Otherwise Do + r=xbase**x + Numeric Digits xprec + Return r+0 + End + End + End + Otherwise + x=x*self~log(xbase,iprec) + End + End + o=1 + u=1 + r=1 + Do i=1 By 1 Until ra=r + ra=r + o=o*x + u=u*i + r=r+(o/u) + End + Numeric Digits xprec + Return (r+0) + +::Method log +/*********************************************************************** +* log(x,precision) -- returns ln(x) with specified precision +* log(x,precision,base) -- returns blog(x) with specified precision +* Three different series are used for ln(x): x in range 0 to 0.5 +* 0.5 to 1.5 +* 1.5 to infinity +***********************************************************************/ + Expose precision + Use Strict Arg x,xprec=(precision),xbase='' + iprec=xprec+100 + Numeric Digits iprec + Select + When x=0 Then Return '-infinity' + When x<0 Then Return 'nan' + When x<1 Then r= -self~Log(1/X,xprec) + Otherwise Do + do M = 0 until (2 ** M) > X; end + M = M - 1 + Z = X / (2 ** M) + Zeta = (1 - Z) / (1 + Z) + N = Zeta; Ln = Zeta; Zetasup2 = Zeta * Zeta + do J = 1 + N = N * Zetasup2; NewLn = Ln + N / (2 * J + 1) + if NewLn = Ln then Do + r= M * self~LN2P(xprec) - 2 * Ln + Leave + End + Ln = NewLn + end + End + End + If x>0 Then Do + If xbase>'' Then + r=r/self~log(xbase,iprec) + Numeric Digits xprec + r=r+0 + End + Return r + +::Method ln2p + Parse Arg p + Numeric Digits p+10 + If p<=1000 Then + Return self~ln2() + n=1/3 + ln=n + zetasup2=1/9 + Do j=1 + n=n*zetasup2 + newln=ln+n/(2*j+1) + If newln=ln Then + Return 2*ln + ln=newln + End + +::Method LN2 + 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 +v=v||7156058633269964186875420014810205706857 +v=v||3368552023575813055703267075163507596193 +v=v||0727570828371435190307038623891673471123 +v=v||3501153644979552391204751726815749320651 +v=v||5552473413952588295045300709532636664265 +v=v||4104239157814952043740430385500801944170 +v=v||6416715186447128399681717845469570262716 +v=v||3106454615025720740248163777338963855069 +v=v||5260668341137273873722928956493547025762 +v=v||6520988596932019650585547647033067936544 +v=v||3254763274495125040606943814710468994650 +v=v||6220167720424524529612687946546193165174 +v=v||6813926725041038025462596568691441928716 +v=v||0829380317271436778265487756648508567407 +v=v||7648451464439940461422603193096735402574 +v=v||4460703080960850474866385231381816767514 +v=v||3866747664789088143714198549423151997354 +v=v||8803751658612753529166100071053558249879 +v=v||4147295092931138971559982056543928717000 +v=v||7218085761025236889213244971389320378439 +v=v||3530887748259701715591070882368362758984 +v=v||2589185353024363421436706118923678919237 +v=v||231467232172053401649256872747782344535348 + + return V + +::Method log10 +/*********************************************************************** +* Return log10(x,prec) specified precision +***********************************************************************/ + Expose precision + Use Strict Arg x,xprec=(precision) + iprec=xprec+10 + r=self~log(x,iprec,10) + Numeric Digits xprec + Return (r+0) + +::Method pi +/* REXX ************************************************************* +* Return pi with the specified precision +********************************************************************/ + Expose precision + Use Strict Arg xprec=(precision) + p='3.141592653589793238462643383279502884197169399375'||, + '10582097494459230781640628620899862803482534211706'||, + '79821480865132823066470938446095505822317253594081'||, + '28481117450284102701938521105559644622948954930381'||, + '96442881097566593344612847564823378678316527120190'||, + '91456485669234603486104543266482133936072602491412'||, + '73724587006606315588174881520920962829254091715364'||, + '36789259036001133053054882046652138414695194151160'||, + '94330572703657595919530921861173819326117931051185'||, + '48074462379962749567351885752724891227938183011949'||, + '12983367336244065664308602139494639522473719070217'||, + '98609437027705392171762931767523846748184676694051'||, + '32000568127145263560827785771342757789609173637178'||, + '72146844090122495343014654958537105079227968925892'||, + '35420199561121290219608640344181598136297747713099'||, + '60518707211349999998372978049951059731732816096318'||, + '59502445945534690830264252230825334468503526193118'||, + '81710100031378387528865875332083814206171776691473'||, + '03598253490428755468731159562863882353787593751957'||, + '781857780532171226806613001927876611195909216420199' + If xprec>1000 Then Do /* more than 1000 digits wanted */ + iprec=xprec+10 /* internal precision */ + Numeric Digits iprec + new=1 + a=sqrt(2,iprec) + b=0 + p=2+a + Do i=1 By 1 Until p=pi + pi=p + y=self~sqrt(a,iprec) + a1=(y+1/y)/2 + b1=y*(b+1)/(b+a) + p=pi*b1*(1+a1)/(1+b1) + a=a1 + b=b1 + End + End + Numeric Digits xprec + Return (p+0) + +::Method power +/*********************************************************************** +* power(base,exponent,precision) returns base**exponent +* -- with specified precision +***********************************************************************/ + Expose precision + Use Strict Arg b,c,xprec=(precision) + Numeric Digits xprec + rsign=1 + If b<0 Then Do /* negative base */ + If datatype(c,'W') Then Do /* Exponent is an integer */ + If c//2=1 Then /* .. an odd number */ + rsign=-1 /* Resuld will be negative */ + b=abs(b) /* proceed with positive base */ + End + Else Do /* Exponent is not an integer */ +-- Say 'for a negative base ('||b')', + 'exponent ('c') must be an integer' + Return 'nan' /* Return not a number */ + End + End + If c=0 Then Do + If b>=0 Then + r=1 + End + Else + r=self~exp(c,xprec,b) + If datatype(r)<>'NUM' Then + Return r + Return rsign*r + +::Method sqrt +/* REXX ************************************************************* +* Return sqrt(x,precision) -- with the specified precision +********************************************************************/ + Expose precision type + Use Strict Arg x,xprec=(precision) + If x<0 Then Do + Return 'nan' + End + iprec=xprec+10 + Numeric Digits iprec + r0= x + r = 1 + Do i=1 By 1 Until r=r0 | (abs(r*r-x)<10**-iprec) + r0 = r + r = (r + x/r) / 2 + End + Numeric Digits xprec + Return (r+0) + +::Method sin +/* REXX ************************************************************* +* Return sin(x,precision,type) -- with the specified precision +* xtype = 'R' (radians, default) 'D' (degrees) 'G' (grades) +* sin(x) = x-(x**3/3!)+(x**5/5!)-(x**7/7!)+-... +********************************************************************/ + Expose precision type + Use Strict Arg x,xprec=(precision),xtype=(type) + iprec=xprec+10 /* internal precision */ + Numeric Digits iprec + /* first use pi constant or compute it if necessary */ + pi=self~pi(iprec) + /* normalize x to be between 0 and 2*pi (or equivalent) */ + /* and convert degrees or grades to radians */ + xx=x + Select + When xtype='R' Then Do + Do While xx>=pi*2; xx=xx-pi*2; End + Do While xx<0; xx=xx+pi*2; End + End + When xtype='D' Then Do + Do While xx>=360; xx=xx-360; End + Do While xx<0; xx=xx+360; End + xx=xx*pi/180 + End + When xtype='G' Then Do + Do While xx>=400; xx=xx-400; End + Do While xx<0; xx=xx+400; End + xx=xx*pi/200 + End + End + /* normalize xx to be between 0 and pi/2 */ + sign=1 + Select + When xx<=pi/2 Then Nop + When xx<=pi Then xx=pi-xx + When xx<=3*pi/2 Then Do; sign=-1; xx=xx-pi; End + Otherwise Do; sign=-1; xx=2*pi-xx; End + End + /* now compute the Taylor series for the normalized xx */ + o=xx + u=1 + r=xx + If abs(xx)<10**(-iprec) Then + r=0 + Else Do + Do i=3 By 2 Until ra=r + ra=r + o=-o*xx*xx + u=u*i*(i-1) + r=r+(o/u) + End + End + Numeric Digits xprec + Return sign*(r+0) + +::Method sinh +/* REXX **************************************************************** +* Return sinh(x,precision) -- with specified precision +* sinh(x) = x+(x**3/3!)+(x**5/5!)+(x**7/7!)+-... +* 920903 Walter Pachl +***********************************************************************/ + Expose precision + Use Strict Arg x,xprec=(precision) + iprec=xprec+10 + Numeric Digits iprec + o=x + u=1 + r=x + Do i=3 By 2 Until ra=r + ra=r + o=o*x*x + u=u*i*(i-1) + r=r+(o/u) + End + Numeric Digits xprec + Return (r+0) + +::Method tan +/* 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) + iprec=xprec+10 + Numeric Digits iprec + s=self~sin(x,iprec,xtype) + c=self~cos(x,iprec,xtype) + If c=0 Then + Return '+infinity' + t=s/c + Numeric Digits xprec + Return (t+0) + +::Method tanh +/*********************************************************************** +* Return tanh(x,precision) -- with specified precision +* tanh(x) = sinh(x)/cosh(x) +***********************************************************************/ + Expose precision + Use Strict Arg x,xprec=(precision) + iprec=xprec+10 + Numeric Digits iprec + r=self~sinh(x,iprec)/self~cosh(x,iprec) + Numeric Digits xprec + Return (r+0) + +::routine rxmarccos public + Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type) + + If datatype(x,'NUM')=0 Then Do +-- Say 'Argument 1 must be a number' + Raise Syntax 88.902 array(1,x) + End + + If datatype(xprec,'W')=0 Then Do +-- Say 'Argument 2 must be a positive whole number' + Raise Syntax 88.905 array(2,xprec) + End + + If xprec<1 | 999999'' Then Do +-- Say 'Argument 3 must be omitted or a number' + Raise Syntax 88.902 array(3,xbase) + End + + Select + When x<0 Then Do + iprec=xprec+10 + Numeric Digits iprec + z=.my.rxm~exp(abs(x),iprec,xbase) + Select + When z=0 Then Return '+infinity' + When datatype(z)<>'NUM' Then Return z + Otherwise r=1/z + End + Numeric Digits xprec + return r+0 + End + When x=0 Then Do + If xbase=0 Then + Return 'nan' + Else + Return 1 + End + Otherwise + return .my.rxm~exp(x,xprec,xbase) + End + +::routine rxmlog public + Use Strict Arg x,xprec=(.my.rxm~precision),xbase='' + + If datatype(x,'NUM')=0 Then Do +-- Say 'Argument 1 must be a number' + Raise Syntax 88.902 array(1,x) + End + + If datatype(xprec,'W')=0 Then Do +-- Say 'Argument 2 must be a whole number between 1 and 999999' + Raise Syntax 88.905 array(2,xprec) + End + + If xprec<1 | 999999'' &, + datatype(xbase,'NUM')=0 Then Do +-- Say 'Argument 3 must be a number' + Raise Syntax 88.902 array(3,xbase) + End + + If x=0 Then + Return '-infinity' + + If x<0 Then + Return 'nan' + + return .my.rxm~log(x,xprec,xbase) + +::routine rxmlog10 public + Use Strict Arg x,xprec=(.my.rxm~precision) + + If datatype(x,'NUM')=0 Then Do +-- Say 'Argument 1 must be a number' + Raise Syntax 88.902 array(1,x) + End + + If datatype(xprec,'W')=0 Then Do +-- Say 'Argument 2 must be a whole number between 1 and 999999' + Raise Syntax 88.905 array(2,xprec) + End + + If xprec<1 | 9999990.5 +(60.0).toRad().cos() //-->0.5 +(45.0).toRad().tan() //-->1 +(0.523599).sin() //-->0.5 +etc + +(0.5).asin() //-->0.523599 +(0.5).acos() //-->1.0472 +(1.0).atan() //-->0.785398 +(1.0).atan().toDeg() //-->45 +etc diff --git a/Task/Truncatable-primes/00DESCRIPTION b/Task/Truncatable-primes/00DESCRIPTION index ac054c6ab8..65e69320cc 100644 --- a/Task/Truncatable-primes/00DESCRIPTION +++ b/Task/Truncatable-primes/00DESCRIPTION @@ -5,10 +5,13 @@ A truncatable prime is a prime number that when you successively remove digits f The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied). -;C.f: +;Related tasks: * [[Find largest left truncatable prime in a given base]] * [[Sieve of Eratosthenes]] -* [http://mathworld.wolfram.com/TruncatablePrime.html Truncatable Prime] from Mathworld. + + +;See also: +* [http://mathworld.wolfram.com/TruncatablePrime.html Truncatable Prime] from MathWorld.
    [[:Category: Prime_Numbers]] diff --git a/Task/Truncatable-primes/Elena/truncatable-primes.elena b/Task/Truncatable-primes/Elena/truncatable-primes.elena index 6bc504b9c1..6e9e20ecf6 100644 --- a/Task/Truncatable-primes/Elena/truncatable-primes.elena +++ b/Task/Truncatable-primes/Elena/truncatable-primes.elena @@ -1,78 +1,95 @@ -#import system. -#import extensions. +import system'calendar. +import extensions. -#symbol MAXN = 1000000. +const MAXN = 1000000. -#class(extension)mathOp +extension mathOp { - #method is &prime + isPrime [ - #var(type:int)n := self int. + int n := self int. - (n < 2) ? [ ^ false. ]. - (n < 4) ? [ ^ true. ]. - (n mod:2 == 0) ? [ ^ false. ]. - (n < 9) ? [ ^ true. ]. - (n mod:3 == 0) ? [ ^ false. ]. + if (n < 2) [ ^ false. ]. + if (n < 4) [ ^ true. ]. + if (n mod:2 == 0) [ ^ false. ]. + if (n < 9) [ ^ true. ]. + if (n mod:3 == 0) [ ^ false. ]. - #var(type:int)r := n sqrt. - #var(type:int)f := 5. - #loop (f <= r)? + int r := n sqrt. + int f := 5. + while (f <= r) [ - ((n mod:f == 0) || (n mod:(f + 2) == 0)) - ? [ ^ false. ]. - f := f + 6. + if ((n mod:f == 0) || (n mod:(f + 2) == 0)) + [ ^ false ]. + + f := f + 6 ]. + + ^ true + ] + + isRightTruncatable + [ + int n := self. + + while (n != 0) + [ + ifnot (n isPrime) + [ ^ false ]. + + n := n / 10 + ]. + ^ true. ] - #method is &rightTruncatable + isLeftTruncatable [ - #var(type:int)n := self int. - #loop (n != 0)? - [ - (n is &prime) - ! [ ^ false. ]. - n := n / 10. - ]. - ^ true. - ] + int n := self. + int tens := 1. - #method is &leftTruncatable - [ - #var(type:int)n := self int. - #var(type:int)tens := 1. - #loop (tens < n) - ? [ tens := tens * 10. ]. + while (tens < n) + [ tens := tens * 10. ]. - #loop (n != 0)? + while (n != 0) [ - (n is &prime) - ! [ ^ false. ]. + ifnot (n isPrime) + [ ^ false ]. + tens := tens / 10. - n := n - (n / tens * tens). + n := n - (n / tens * tens) ]. - ^ true. + + ^ true ] } -#symbol program = +program = [ - #var n := MAXN. - #var max_lt := 0. - #var max_rt := 0. - #loop ((max_lt == 0) || (max_rt == 0))? + var n := MAXN. + var max_lt := 0. + var max_rt := 0. + + while ((max_lt == 0) || (max_rt == 0)) [ - (n literal indexOf:"0" == -1) ? + if(n literal; indexOf:"0" == -1) [ - ((max_lt == 0) and:[ n is &leftTruncatable ]) - ? [ max_lt := n. ]. - ((max_rt == 0) and:[ n is &rightTruncatable ]) - ? [ max_rt := n. ]. + if ((max_lt == 0) && $(n isLeftTruncatable)) + [ + max_lt := n. + ]. + + if ((max_rt == 0) && $(n isRightTruncatable)) + [ + max_rt := n. + ]. ]. + n := n - 1. ]. - console writeLine:"Largest truncable left is ":max_lt. - console writeLine:"Largest truncable right is ":max_rt. + console printLine("Largest truncable left is ",max_lt). + console printLine("Largest truncable right is ",max_rt). + + console readChar. ]. diff --git a/Task/Truncatable-primes/FreeBASIC/truncatable-primes-1.freebasic b/Task/Truncatable-primes/FreeBASIC/truncatable-primes-1.freebasic new file mode 100644 index 0000000000..174ab3995e --- /dev/null +++ b/Task/Truncatable-primes/FreeBASIC/truncatable-primes-1.freebasic @@ -0,0 +1,56 @@ +' FB 1.05.0 Win64 + +Function isPrime(n As Integer) As Boolean + If n Mod 2 = 0 Then Return n = 2 + If n Mod 3 = 0 Then Return n = 3 + Dim d As Integer = 5 + While d * d <= n + If n Mod d = 0 Then Return False + d += 2 + If n Mod d = 0 Then Return False + d += 4 + Wend + Return True +End Function + +Dim As UInteger i, j, p, pow, lMax = 2, rMax = 2 +Dim s As String + +' largest left truncatable prime less than 1000000 +' It can't end with 1, 4, 6, 8 or 9 as these numbers are not prime +' Nor can it end in 2 if it has more than one digit as such a number would divide by 2 +For i = 3 To 999997 Step 2 + s = Str(i) + If Instr(s, "0") > 1 Then Continue For '' cannot contain 0 + j = s[Len(s) - 1] - 48 + If j = 1 OrElse j = 9 Then Continue For + p = i + pow = 10 ^ (Len(s) - 1) + While pow > 1 + If Not isPrime(p) Then Continue For + p Mod= pow + pow \= 10 + Wend + lMax = i +Next + +' largest right truncatable prime less than 1000000 +' It can't begin with 1, 4, 6, 8 or 9 as these numbers are not prime +For i = 3 To 799999 Step 2 + s = Str(i) + If Instr(s, "0") > 1 Then Continue For '' cannot contain 0 + j = s[0] - 48 + If j = 1 OrElse j = 4 OrElse j = 6 Then Continue For + p = i + While p > 0 + If Not isPrime(p) Then Continue For + p \= 10 + Wend + rMax = i +Next + +Print "Largest left truncatable prime : "; lMax +Print "Largest right truncatable prime : "; rMax +Print +Print "Press any key to quit" +Sleep diff --git a/Task/Truncatable-primes/FreeBASIC/truncatable-primes-2.freebasic b/Task/Truncatable-primes/FreeBASIC/truncatable-primes-2.freebasic new file mode 100644 index 0000000000..832953f726 --- /dev/null +++ b/Task/Truncatable-primes/FreeBASIC/truncatable-primes-2.freebasic @@ -0,0 +1,83 @@ +' version 10-12-2016 +' compile with: fbc -s console + +Dim Shared As Byte isPrime() + +Sub sieve(m As UInteger) + + Dim As Integer i, j + ReDim isPrime(m) + + For i = 4 To m Step 2 + isPrime(i) = 1 + Next + + For i = 3 To Sqr(m) Step 2 + If isPrime(i) = 0 Then + For j = i * i To m Step i * 2 + isPrime(j) = 1 + Next + End If + Next + +End Sub + +' ------=< MAIN >=------ + +#Define max 1000000 'upto 2^30 max for 32bit OS + +Dim As UInteger a(), lt_prime(5000), rt_prime(100) +Dim As UInteger i, j, j1, p1, p2, left_max, right_max + +sieve(max) + +' left truncatable primes +' if odd and ends with 3 or 7, never ends 1 or 9 (no prime +' never ends on a 2 or 5 and starts with 1 to 9 +lt_prime(1) = 3 : lt_prime(2) = 7 +p1 = 1 : p2 = 2 + +Do + For i = 1 To 9 + j = Val( Str(i) + Str(lt_prime(p1)) ) + If j > max Then Exit Do + If isPrime(j) = 0 Then ' if prime then add to the list + p2 += 1 + lt_prime(p2) = j + If Left_max < j Then left_max = j + End If + Next + p1 += 1 +Loop Until p1 > p2 ' no more numbers to process + +' right truncatable prime +' start with 2, 3, 5 or 7 and end with 1, 3, 7 or 9 +rt_prime(1) = 2 : rt_prime(2) = 3 : rt_prime(3) = 5 : rt_prime(4) = 7 +p1 = 1 : p2 = 4 +Dim As UInteger end_num(1 To 4) => {1, 3, 7, 9} + +Do + j1 = rt_prime(p1) * 10 + If j1 > max Then Exit Do + For i = 1 To 4 + j = j1 + End_num(i) + If isprime(j) = 0 Then ' if prime then add to the list + p2 += 1 + rt_prime(p2) = j + ' If right_max < j Then right_max = j + End If + Next + p1 += 1 +Loop Until p1 > p2 ' no more numbers to process +' the last one added is the biggest +right_max = rt_prime(p2) + +Print +Print "The biggest left truncatable prime below"; max; " is "; left_max +Print "The biggest right truncatable prime below"; max; " is "; right_max + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Truncatable-primes/Kotlin/truncatable-primes.kotlin b/Task/Truncatable-primes/Kotlin/truncatable-primes.kotlin new file mode 100644 index 0000000000..a65b6a04bc --- /dev/null +++ b/Task/Truncatable-primes/Kotlin/truncatable-primes.kotlin @@ -0,0 +1,58 @@ +// version 1.0.5-2 + +fun isPrime(n: Int) : Boolean { + if (n < 2) return false + if (n % 2 == 0) return n == 2 + if (n % 3 == 0) return n == 3 + var d : Int = 5 + while (d * d <= n) { + if (n % d == 0) return false + d += 2 + if (n % d == 0) return false + d += 4 + } + return true +} + +fun main(args: Array) { + var j: Char + var p: Int + var pow: Int + var lMax: Int = 2 + var rMax: Int = 2 + var s: String + + // calculate maximum left truncatable prime less than 1 million + loop@ for( i in 3..999997 step 2) { + s = i.toString() + if ('0' in s) continue + j = s[s.length - 1] + if (j == '1' || j == '9') continue + p = i + pow = 1 + for (k in 1..s.length - 1) pow *= 10 + while(pow > 1) { + if (!isPrime(p)) continue@loop + p %= pow + pow /= 10 + } + lMax = i + } + + // calculate maximum right truncatable prime less than 1 million + loop@ for( i in 3..799999 step 2) { + s = i.toString() + if ('0' in s) continue + j = s[0] + if (j == '1' || j == '4' || j == '6') continue + p = i + while(p > 0) { + if (!isPrime(p)) continue@loop + p /= 10 + } + rMax = i + } + + println("Largest left truncatable prime : " + lMax.toString()) + println("Largest right truncatable prime : " + rMax.toString()) +} diff --git a/Task/Truncatable-primes/Nim/truncatable-primes.nim b/Task/Truncatable-primes/Nim/truncatable-primes.nim index d64ccc4a48..ff436da097 100644 --- a/Task/Truncatable-primes/Nim/truncatable-primes.nim +++ b/Task/Truncatable-primes/Nim/truncatable-primes.nim @@ -1,6 +1,6 @@ import sets, strutils, algorithm -proc primes(n): seq[int64] = +proc primes(n: int64): seq[int64] = result = @[] var multiples = initSet[int64]() for i in 2..n: @@ -9,7 +9,7 @@ proc primes(n): seq[int64] = for j in countup(i*i, n, i.int): multiples.incl j -proc truncatablePrime(n): tuple[left: int64, right: int64] = +proc truncatablePrime(n: int64): tuple[left: int64, right: int64] = var primelist: seq[string] = @[] for x in primes(n): @@ -18,14 +18,14 @@ proc truncatablePrime(n): tuple[left: int64, right: int64] = var primeset = toSet primelist for n in primelist: var alltruncs = initSet[string]() - for i in 0..n.len: - alltruncs.incl n[1..n.high] + for i in 0..n.len-1: + alltruncs.incl n[i..n.high] if alltruncs <= primeset: result.left = parseInt(n) break for n in primelist: var alltruncs = initSet[string]() - for i in 0..n.len: + for i in 0..n.len-1: alltruncs.incl n[0..i] if alltruncs <= primeset: result.right = parseInt(n) diff --git a/Task/Truncatable-primes/OoRexx/truncatable-primes.rexx b/Task/Truncatable-primes/OoRexx/truncatable-primes.rexx new file mode 100644 index 0000000000..7aa55da616 --- /dev/null +++ b/Task/Truncatable-primes/OoRexx/truncatable-primes.rexx @@ -0,0 +1,64 @@ +-- find largest left- & right-truncatable primes < 1 million. +-- an initial set of primes (not, at this time, we leave out 2 because +-- we'll automatically skip the even numbers. No point in doing a needless +-- test each time through +primes = .array~of(3, 5, 7, 11) + +-- check all of the odd numbers up to 1,000,000 +loop j = 13 by 2 to 1000000 + loop i = 1 to primes~size + prime = primes[i] + -- found an even prime divisor + if j // prime == 0 then iterate j + -- only check up to the square root + if prime*prime > j then leave + end + -- we only get here if we don't find a divisor + primes~append(j) +end + +-- get a set of the primes that we can test more efficiently +primeSet = .set~of(2) +primeSet~putall(primes) + + +say 'The last prime is' primes[primes~last] "("primeSet~items 'primes under one million).' +say copies('-',66) + +lastLeft = 0 + +-- we're going to use the array version to do these in order. We're still +-- missing "2", but that's not going to be the largest +loop prime over primes + + -- values containing 0 can never work + if prime~pos(0) \= 0 then iterate + -- now start the truncations, checking against our set of + -- known primes + loop i = 1 for prime~length - 1 + subprime = prime~right(i) + -- not in our known set, this can't work + if \primeset~hasIndex(subprime) then iterate prime + end + -- this, by definition, with be the largest left-trunc prime + lastLeft = prime +end +-- now look for right-trunc primes +lastRight = 0 +loop prime over primes + + -- values containing 0 can never work + if prime~pos(0) \= 0 then iterate + -- now start the truncations, checking against our set of + -- known primes + loop i = 1 for prime~length - 1 + subprime = prime~left(i) + -- not in our known set, this can't work + if \primeset~hasIndex(subprime) then iterate prime + end + -- this, by definition, with be the largest left-trunc prime + lastRight = prime +end + +say 'The largest left-truncatable prime is' lastLeft '(under one million).' +say 'The largest right-truncatable prime is' lastRight '(under one million).' diff --git a/Task/Truncatable-primes/Phix/truncatable-primes.phix b/Task/Truncatable-primes/Phix/truncatable-primes.phix new file mode 100644 index 0000000000..f37d6e80ce --- /dev/null +++ b/Task/Truncatable-primes/Phix/truncatable-primes.phix @@ -0,0 +1,38 @@ +constant N = 6, limit = power(10,N) +-- standard sieve: +enum L,R -- (with primes[i] as mini bit-field) +sequence primes = repeat(L+R, limit) +primes[1] = 0 +for i=2 to floor(sqrt(limit)) do + if primes[i] then + for k=i*i to limit by i do + primes[k] = 0 + end for + end if +end for + +-- propagate non-truncateables up the prime table: +for p=1 to N-1 do + integer p10 = power(10,p) -- ie 10, 100, .. 100_000 + for i=p10+1 to p10*10-1 by 2 do -- to 99, 999, .. 999_999 + if primes[i] then + integer l = remainder(i,p10), + r = floor(i/10) + integer pi = and_bits(primes[l],L)+and_bits(primes[r],R) + if pi and find('0',sprint(i)) then pi = 0 end if + primes[i] = pi + end if + end for +end for + +integer maxl=0, maxr=0 + +for i=limit-1 to 1 by -2 do + integer pi = primes[i] + if pi then + if maxl=0 and and_bits(pi,L) then maxl = i end if + if maxr=0 and and_bits(pi,R) then maxr = i end if + if maxl!=0 and maxr!=0 then exit end if + end if +end for +?{maxl,maxr} diff --git a/Task/Truncatable-primes/REXX/truncatable-primes.rexx b/Task/Truncatable-primes/REXX/truncatable-primes.rexx index 19579c8ba5..aac8122c92 100644 --- a/Task/Truncatable-primes/REXX/truncatable-primes.rexx +++ b/Task/Truncatable-primes/REXX/truncatable-primes.rexx @@ -5,7 +5,7 @@ parse arg high .; if high=='' then high=1000000 /*Not specified? The !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1 /*set some low prime flags. */ #=7; s.#=@.#**2 /*number of primes so far; prime². */ /* [↓] generate more primes ≤ high.*/ - do j=@.#+2 by 2 to high /*only find odd primes from here on out*/ + do j=@.#+2 by 2 for max(0, high%2-@.#%2-1) /*only find odd primes from here on out*/ if j// 3==0 then iterate /*is J divisible by three? */ parse var j '' -1 _; if _==5 then iterate /* " " " " five? (right digit)*/ if j// 7==0 then iterate /* " " " " seven? */ @@ -13,8 +13,8 @@ parse arg high .; if high=='' then high=1000000 /*Not specified? The if j//13==0 then iterate /* " " " " thirteen? */ /* [↑] the above five lines saves time*/ do k=7 while s.k<=j /* [↓] divide by the known odd primes.*/ - if j//@.k==0 then iterate j /*Is J divisible by X? Then not prime.*/ - end /*k*/ + if j//@.k==0 then iterate j /*Is J ÷ X? Then not prime. ___ */ + end /*k*/ /* [↑] only process up to the √ J */ #=#+1 /*bump the number of primes found. */ @.#=j; s.#=j*j; !.j=1 /*assign next prime; prime²; prime #.*/ end /*j*/ diff --git a/Task/Truncatable-primes/Zkl/truncatable-primes-1.zkl b/Task/Truncatable-primes/Zkl/truncatable-primes-1.zkl new file mode 100644 index 0000000000..abdfcf8780 --- /dev/null +++ b/Task/Truncatable-primes/Zkl/truncatable-primes-1.zkl @@ -0,0 +1,15 @@ +const million=0d1_000_000; + +var pTable=Data(million+1,Int).fill(0); // actually bytes, all zero +primes:=Utils.Generator(Import("sieve").postponed_sieve); +while((p:=primes.next()) 0) { + fnr++ + } + close(filename) + if (fnr == 0) { + msg = "file not found" + } + if (fnr > 1) { + msg = "choose a different RecordSeparator" + } + if (msg == "") { # no errors + system(cmd) # optional: show filesize before truncation + if (length(rec) > size) { + rec = substr(rec,1,size) + } + printf("%s",rec) >filename + close(filename) + system(cmd) # optional: show filesize after truncation + } + BINMODE = old_BINMODE + RS = old_RS + return(msg) +} diff --git a/Task/Truncate-a-file/C++/truncate-a-file.cpp b/Task/Truncate-a-file/C++/truncate-a-file.cpp new file mode 100644 index 0000000000..725c646e92 --- /dev/null +++ b/Task/Truncate-a-file/C++/truncate-a-file.cpp @@ -0,0 +1,20 @@ +#include +#include + +using namespace std; + +void truncateFile(string filename, int max_size) { + std::ifstream input( filename, std::ios::binary ); + char buffer; + string outfile = filename + ".trunc"; + ofstream appendFile(outfile, ios_base::out); + for(int i=0; i= fc.size()) + println("Requested file size isn't less than existing size") + else + fc.truncate(newSize) + } + catch (ex: Exception) { + println(ex.message) + } + finally { + fc!!.close() + } +} + +fun main(args: Array) { + truncateFile("test.txt", 10) +} diff --git a/Task/Truncate-a-file/PowerShell/truncate-a-file.psh b/Task/Truncate-a-file/PowerShell/truncate-a-file.psh new file mode 100644 index 0000000000..cb8913973a --- /dev/null +++ b/Task/Truncate-a-file/PowerShell/truncate-a-file.psh @@ -0,0 +1,3 @@ +Function Truncate-File(fname) { + $null | Set-Content -Path "$fname" +} diff --git a/Task/Truncate-a-file/Python/truncate-a-file.py b/Task/Truncate-a-file/Python/truncate-a-file.py index b21f5ef2be..42d57decf7 100644 --- a/Task/Truncate-a-file/Python/truncate-a-file.py +++ b/Task/Truncate-a-file/Python/truncate-a-file.py @@ -5,5 +5,4 @@ def truncate_file(name, length): return False with open(name, 'ab') as f: f.truncate(length) - f.close() - return True + return True diff --git a/Task/Twelve-statements/Elena/twelve-statements.elena b/Task/Twelve-statements/Elena/twelve-statements.elena index 1176804f92..a4966e0645 100644 --- a/Task/Twelve-statements/Elena/twelve-statements.elena +++ b/Task/Twelve-statements/Elena/twelve-statements.elena @@ -1,58 +1,60 @@ -#import system. -#import system'routines. -#import extensions. +import system'routines. +import extensions. -#class(extension)op +extension op { - #method printSolution : bits - = self zip:bits &into: - (:s:b) [ s iif:"T":"F" + (s xor:b) iif:"* ":" " ] summarize:(String new). + printSolution : bits + = self zip:bits by + (:s:b)( s iif("T","F") + (s xor:b) iif("* "," ") ); summarize(String new). + + toBit + = self iif(1,0). } -#symbol puzzle = +puzzle = ( - bits [ bits length == 12 ], + (:bits)( bits length == 12 ), - bits [ bits last:6 select &each:x [ x iif:1:0 ] summarize == 3 ], + (:bits)( bits last:6; selectBy(:x)( x toBit ); summarize == 3 ), - bits [ bits zip:(RangeEnumerator new &from:1 &to:12) - &into:(:x:i) [ (i int is &even)and:x iif:1:0 ] summarize == 2 ], + (:bits)( bits zip(RangeEnumerator new from:1 to:12) + by(:x:i)( (i int; isEven)and:x; toBit ); summarize == 2 ), - bits [ bits@4 iif:(bits@5 && bits@6):true ], + (:bits)( bits[4] iif(bits[5] && bits[6],true) ), - bits [ (bits@1 || bits@2 || bits@3) not ], + (:bits)( (bits[1] || bits[2] || bits[3]) not ), - bits [ bits zip:(RangeEnumerator new &from:1 &to:12) - &into:(:x:i) [ (i int is &odd)and:x iif:1:0 ] summarize == 4 ], + (:bits)( bits zip(RangeEnumerator new from:1 to:12) + by(:x:i)( (i int; isOdd)and:x; toBit ); summarize == 4 ), - bits [ (bits@1) xor:(bits@2) ], + (:bits)( bits[1] xor(bits[2]) ), - bits [ bits@6 iif:(bits@5 && bits@4):true ], + (:bits)( bits[6] iif(bits[5] && bits[4],true) ), - bits [ bits top:6 select &each:x [ x iif:1:0 ] summarize == 3 ], + (:bits)( bits top:6; selectBy(:x)( x toBit ); summarize == 3 ), - bits [ bits@10 && bits@11 ], + (:bits)( bits[10] && bits[11] ), - bits [ ((bits@6) iif:1:0 + (bits@7) iif:1:0 + (bits@8) iif:1:0)==1 ], + (:bits)( (bits[6] toBit + bits[7] toBit + bits[8] toBit)==1 ), - bits [ bits top:11 select &each:x [ x iif:1:0 ] summarize == 4 ] + (:bits)( bits top:11; selectBy(:x)( x toBit ); summarize == 4 ) ). -#symbol program = +program = [ console writeLine:"". - 0 till:(2 power &int:12) &doEach:n + 0 till(2 power int:12) do(:n) [ - #var bits := BitArray32 new:n top:12 toArray. - #var results := puzzle select &each: r [ r eval:bits ] toArray. + var bits := BitArray32 new:n; top:12; toArray. + var results := puzzle selectBy(:r)( r eval:bits ); toArray. - #var counts := bits zip:results &into:(:b:r) [ b xor:r iif:1:0 ] summarize. + var counts := bits zip:results by(:b:r)( b xor:r; toBit ); summarize. counts => - 0 ? [ console writeLine:"Total hit :":(results printSolution:bits). ] - 1 ? [ console writeLine:"Near miss :":(results printSolution:bits). ] - 12 ? [ console writeLine:"Total miss:":(results printSolution:bits). ]. + 0 [ console printLine("Total hit :",results printSolution:bits) ]; + 1 [ console printLine("Near miss :",results printSolution:bits) ]; + 12 [ console printLine("Total miss:",results printSolution:bits) ]. ]. console readChar. diff --git a/Task/Twelve-statements/jq/twelve-statements.jq b/Task/Twelve-statements/Jq/twelve-statements.jq similarity index 100% rename from Task/Twelve-statements/jq/twelve-statements.jq rename to Task/Twelve-statements/Jq/twelve-statements.jq diff --git a/Task/Twelve-statements/Kotlin/twelve-statements.kotlin b/Task/Twelve-statements/Kotlin/twelve-statements.kotlin new file mode 100644 index 0000000000..e1e1dba3b8 --- /dev/null +++ b/Task/Twelve-statements/Kotlin/twelve-statements.kotlin @@ -0,0 +1,45 @@ +// version 1.1.3 + +typealias Predicate = (String) -> Boolean + +val predicates = listOf( + { it.length == 13 }, // indexing starts at 0 but first bit ignored + { (7..12).count { i -> it[i] == '1' } == 3 }, + { (2..12 step 2).count { i -> it[i] == '1' } == 2 }, + { it[5] == '0' || (it[6] == '1' && it[7] == '1') }, + { it[2] == '0' && it[3] == '0' && it[4] == '0' }, + { (1..11 step 2).count { i -> it[i] == '1' } == 4 }, + { (it[2] == '1') xor (it[3] == '1') }, + { it[7] == '0' || (it[5] == '1' && it[6] == '1') }, + { (1..6).count { i -> it[i] == '1' } == 3 }, + { it[11] == '1' && it[12] == '1' }, + { (7..9).count { i -> it[i] == '1' } == 1 }, + { (1..11).count { i -> it[i] == '1' } == 4 } +) + +fun show(s: String, indent: Boolean) { + if (indent) print(" ") + for (i in s.indices) if (s[i] == '1') print("$i ") + println() +} + +fun main(args: Array) { + println("Exact hits:") + for (i in 0..4095) { + val s = i.toString(2).padStart(13, '0') + var j = 1 + if (predicates.all { it(s) == (s[j++] == '1') }) show(s, true) + } + + println("\nNear misses:") + for (i in 0..4095) { + val s = i.toString(2).padStart(13, '0') + var j = 1 + if (predicates.count { it(s) == (s[j++] == '1') } == 11) { + var k = 1 + val iof = predicates.indexOfFirst { it(s) != (s[k++] == '1') } + 1 + print(" (Fails at statement ${"%2d".format(iof)}) ") + show(s, false) + } + } +} diff --git a/Task/Twelve-statements/Sidef/twelve-statements.sidef b/Task/Twelve-statements/Sidef/twelve-statements.sidef new file mode 100644 index 0000000000..600ab7d515 --- /dev/null +++ b/Task/Twelve-statements/Sidef/twelve-statements.sidef @@ -0,0 +1,26 @@ +var conditions = [ + { false }, + {|a| a.len == 13 }, + {|a| Math.sum(a[7..12]) == 3 }, + {|a| Math.sum(a[2..12 `by` 2]) == 2 }, + {|a| a[5] ? (a[6] && a[7]) : true }, + {|a| !a[2] && !a[3] && !a[4] }, + {|a| Math.sum(a[1..11 `by` 2]) == 4 }, + {|a| a[2] == true^a[3] }, + {|a| a[7] ? (a[5] && a[6]) : true }, + {|a| Math.sum(a[1..6]) == 3 }, + {|a| Math.sum(a[11,12]) == 2 }, + {|a| Math.sum(a[7..9]) == 1 }, + {|a| Math.sum(a[1..11]) == 4 }, +] + +func miss(args) { + 1..12 -> grep {|i| conditions[i](args) != args[i] } +} + +for k in (^(1<<12)) { + var t = ("0%012b" % k -> chars.map {|bit| bit == '1' ? true : false }) + var no = miss(t) + no.len == 0 && say "Solution: true statements are #{1..12->grep{t[_]}.join(' ')}" + no.len == 1 && say "1 miss (#{no[0]}): true statements are #{1..12->grep{t[_]}.join(' ')}" +} diff --git a/Task/Twelve-statements/Zkl/twelve-statements.zkl b/Task/Twelve-statements/Zkl/twelve-statements.zkl new file mode 100644 index 0000000000..a2adffdfa5 --- /dev/null +++ b/Task/Twelve-statements/Zkl/twelve-statements.zkl @@ -0,0 +1,30 @@ +var statements; // list of 13 Bools, statements[0] is garbage to make 1 based +fcn s0 { False } // dummy for padding +fcn s1 { True } +fcn s2 { statements[-6,*].filter().len()==3 } +fcn s3 { [2..12,2].apply(statements.get).filter().len()==2 } +fcn s4 { if(statements[5]) statements[6]==statements[7]==True else True } +fcn s5 { statements[2,3].filter().len()==0 } +fcn s6 { [1..12,2].apply(statements.get).filter().len()==4 } +fcn s7 { statements[2]!=statements[3] } +fcn s8 { if(statements[7]) statements[5]==statements[6]==True else True } +fcn s9 { statements[1,6].filter().len()==3 } +fcn s10{ statements[11]==statements[12]==True } +fcn s11{ statements[7,3].filter().len()==1 } +fcn s12{ statements[1,11].filter().len()==4 } + +filters:=T(s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12); +foreach n in ((2).pow(12)){ // 4k + // 5-->"0000000000101"-->("0","0"..."1")-->(F,F,...T) + statements="%013.2B".fmt(n).split("").apply('==("1")); + r:=filters.run(True); // and return list of results + if(r==statements) print("<<<<<<<<<<<<<<<= (length string) (+ start 3)) + (multiple-value-bind (code pos) + (parse-integer string :start (1+ start) :end (+ start 3) :radix 16 :junk-allowed t) + (if (= pos (+ start 3)) + (values (code-char code) pos) + (values #\% (1+ start)))) + (values #\% (1+ start)))) + +(defun url-decode (url) + (loop with start = 0 + for pos = (position #\% url :start start) + collect (subseq url start pos) into chunks + when pos + collect (multiple-value-bind (decoded next) (decode url :start pos) + (setf start next) + (string decoded)) + into chunks + while pos + finally (return (apply #'concatenate 'string chunks)))) + +(url-decode "http%3A%2F%2Ffoo%20bar%2F") diff --git a/Task/URL-decoding/Haskell/url-decoding.hs b/Task/URL-decoding/Haskell/url-decoding-1.hs similarity index 100% rename from Task/URL-decoding/Haskell/url-decoding.hs rename to Task/URL-decoding/Haskell/url-decoding-1.hs diff --git a/Task/URL-decoding/Haskell/url-decoding-2.hs b/Task/URL-decoding/Haskell/url-decoding-2.hs new file mode 100644 index 0000000000..e4b0c0ba0f --- /dev/null +++ b/Task/URL-decoding/Haskell/url-decoding-2.hs @@ -0,0 +1,13 @@ +import Data.Char (chr) +import Data.List.Split (splitOn) + +deCode :: String -> String +deCode url = + let ps = splitOn "%" url + in concat $ + head ps : + ((\(a, b) -> (chr . read) (mappend "0x" a) : b) <$> (splitAt 2 <$> tail ps)) + +-- TEST ------------------------------------------------------------------------ +main :: IO () +main = putStrLn $ deCode "http%3A%2F%2Ffoo%20bar%2F" diff --git a/Task/URL-decoding/jq/url-decoding-1.jq b/Task/URL-decoding/Jq/url-decoding-1.jq similarity index 100% rename from Task/URL-decoding/jq/url-decoding-1.jq rename to Task/URL-decoding/Jq/url-decoding-1.jq diff --git a/Task/URL-decoding/jq/url-decoding-2.jq b/Task/URL-decoding/Jq/url-decoding-2.jq similarity index 100% rename from Task/URL-decoding/jq/url-decoding-2.jq rename to Task/URL-decoding/Jq/url-decoding-2.jq diff --git a/Task/URL-decoding/jq/url-decoding-3.jq b/Task/URL-decoding/Jq/url-decoding-3.jq similarity index 100% rename from Task/URL-decoding/jq/url-decoding-3.jq rename to Task/URL-decoding/Jq/url-decoding-3.jq diff --git a/Task/URL-decoding/Kotlin/url-decoding.kotlin b/Task/URL-decoding/Kotlin/url-decoding.kotlin new file mode 100644 index 0000000000..df364a3b8e --- /dev/null +++ b/Task/URL-decoding/Kotlin/url-decoding.kotlin @@ -0,0 +1,8 @@ +// version 1.1.2 + +import java.net.URLDecoder + +fun main(args: Array) { + val encoded = arrayOf("http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1") + for (e in encoded) println(URLDecoder.decode(e, "UTF-8")) +} diff --git a/Task/URL-decoding/Lua/url-decoding.lua b/Task/URL-decoding/Lua/url-decoding.lua new file mode 100644 index 0000000000..1c0f1877e4 --- /dev/null +++ b/Task/URL-decoding/Lua/url-decoding.lua @@ -0,0 +1,11 @@ +function decodeChar(hex) + return string.char(tonumber(hex,16)) +end + +function decodeString(str) + local output, t = string.gsub(str,"%%(%x%x)",decodeChar) + return output +end + +-- will print "http://foo bar/" +print(decodeString("http%3A%2F%2Ffoo%20bar%2F")) diff --git a/Task/URL-decoding/Phix/url-decoding.phix b/Task/URL-decoding/Phix/url-decoding.phix new file mode 100644 index 0000000000..605fefd094 --- /dev/null +++ b/Task/URL-decoding/Phix/url-decoding.phix @@ -0,0 +1,33 @@ +-- +-- demo\rosetta\decode_url.exw +-- =========================== +-- +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")}) diff --git a/Task/URL-decoding/REXX/url-decoding-3.rexx b/Task/URL-decoding/REXX/url-decoding-3.rexx index d48e970597..a591339507 100644 --- a/Task/URL-decoding/REXX/url-decoding-3.rexx +++ b/Task/URL-decoding/REXX/url-decoding-3.rexx @@ -1,21 +1,21 @@ -/*REXX program converts an URL─encoded string ──► its original unencoded form.*/ +/*REXX program converts & displays an URL─encoded string ──► its original unencoded form*/ url.1='http%3A%2F%2Ffoo%20bar%2F' url.2='mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E' url.3='%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E' URLs=3 - do j=1 for URLs; say /*process each URL; display blank line.*/ - say url.j /*display the original URL. */ - say URLdecode(url.j) /* " " decoded " */ + do j=1 for URLs; say /*process each URL; display blank line.*/ + say url.j /*display the original URL. */ + say URLdecode(url.j) /* " " decoded " */ end /*j*/ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -URLdecode: procedure; parse arg yyy /*get encoded URL from argument list. */ -yyy=translate(yyy,,'+') /*a special case for an encoded blank. */ -URL= - do until yyy='' - parse var yyy plain '%' +1 code +2 yyy - URL=URL || plain - if datatype(code,'X') then URL=URL || x2c(code) - else URL=URL'%'code - end /*until*/ -return URL +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +URLdecode: procedure; parse arg yyy /*get encoded URL from argument list. */ + yyy=translate(yyy, , '+') /*a special case for an encoded blank. */ + URL= + do until yyy='' + parse var yyy plain '%' +1 code +2 yyy + URL=URL || plain + if datatype(code, 'X') then URL=URL || x2c(code) + else URL=URL'%'code + end /*until*/ + return URL diff --git a/Task/URL-decoding/Zkl/url-decoding-1.zkl b/Task/URL-decoding/Zkl/url-decoding-1.zkl new file mode 100644 index 0000000000..44846328e7 --- /dev/null +++ b/Task/URL-decoding/Zkl/url-decoding-1.zkl @@ -0,0 +1,3 @@ +"http%3A%2F%2Ffoo%20bar%2F".pump(String, // push each char through these fcns: + fcn(c){ if(c=="%") return(Void.Read,2); return(Void.Skip,c) },// %-->read 2 chars else pass through + fcn(_,b,c){ (b+c).toInt(16).toChar() }) // "%" (ignored) "3"+"1"-->0x31-->"1" diff --git a/Task/URL-decoding/Zkl/url-decoding-2.zkl b/Task/URL-decoding/Zkl/url-decoding-2.zkl new file mode 100644 index 0000000000..a8662dc1ac --- /dev/null +++ b/Task/URL-decoding/Zkl/url-decoding-2.zkl @@ -0,0 +1,2 @@ +var Curl=Import("zklCurl"); +Curl.urlDecode("http%3A%2F%2Ffoo%20bar%2F"); diff --git a/Task/URL-encoding/00META.yaml b/Task/URL-encoding/00META.yaml index 12b5b405fb..0a7aacb5eb 100644 --- a/Task/URL-encoding/00META.yaml +++ b/Task/URL-encoding/00META.yaml @@ -1,3 +1,4 @@ --- category: - String manipulation +- Encodings diff --git a/Task/URL-encoding/Common-Lisp/url-encoding.lisp b/Task/URL-encoding/Common-Lisp/url-encoding.lisp new file mode 100644 index 0000000000..fc3b95a2ca --- /dev/null +++ b/Task/URL-encoding/Common-Lisp/url-encoding.lisp @@ -0,0 +1,15 @@ +(defun needs-encoding-p (char) + (not (digit-char-p char 36))) + +(defun encode-char (char) + (format nil "%~2,'0X" (char-code char))) + +(defun url-encode (url) + (apply #'concatenate 'string + (map 'list (lambda (char) + (if (needs-encoding-p char) + (encode-char char) + (string char))) + url))) + +(url-encode "http://foo bar/") diff --git a/Task/URL-encoding/jq/url-encoding-1.jq b/Task/URL-encoding/Jq/url-encoding-1.jq similarity index 100% rename from Task/URL-encoding/jq/url-encoding-1.jq rename to Task/URL-encoding/Jq/url-encoding-1.jq diff --git a/Task/URL-encoding/jq/url-encoding-2.jq b/Task/URL-encoding/Jq/url-encoding-2.jq similarity index 100% rename from Task/URL-encoding/jq/url-encoding-2.jq rename to Task/URL-encoding/Jq/url-encoding-2.jq diff --git a/Task/URL-encoding/jq/url-encoding-3.jq b/Task/URL-encoding/Jq/url-encoding-3.jq similarity index 100% rename from Task/URL-encoding/jq/url-encoding-3.jq rename to Task/URL-encoding/Jq/url-encoding-3.jq diff --git a/Task/URL-encoding/jq/url-encoding-4.jq b/Task/URL-encoding/Jq/url-encoding-4.jq similarity index 100% rename from Task/URL-encoding/jq/url-encoding-4.jq rename to Task/URL-encoding/Jq/url-encoding-4.jq diff --git a/Task/URL-encoding/jq/url-encoding-5.jq b/Task/URL-encoding/Jq/url-encoding-5.jq similarity index 100% rename from Task/URL-encoding/jq/url-encoding-5.jq rename to Task/URL-encoding/Jq/url-encoding-5.jq diff --git a/Task/URL-encoding/jq/url-encoding-6.jq b/Task/URL-encoding/Jq/url-encoding-6.jq similarity index 100% rename from Task/URL-encoding/jq/url-encoding-6.jq rename to Task/URL-encoding/Jq/url-encoding-6.jq diff --git a/Task/URL-encoding/Kotlin/url-encoding.kotlin b/Task/URL-encoding/Kotlin/url-encoding.kotlin new file mode 100644 index 0000000000..a1c953653c --- /dev/null +++ b/Task/URL-encoding/Kotlin/url-encoding.kotlin @@ -0,0 +1,8 @@ +// version 1.1.2 + +import java.net.URLEncoder + +fun main(args: Array) { + val url = "http://foo bar/" + println(URLEncoder.encode(url, "utf-8")) // note: encodes space to + not %20 +} diff --git a/Task/URL-encoding/Lua/url-encoding.lua b/Task/URL-encoding/Lua/url-encoding.lua new file mode 100644 index 0000000000..5034399a5c --- /dev/null +++ b/Task/URL-encoding/Lua/url-encoding.lua @@ -0,0 +1,11 @@ +function encodeChar(chr) + return string.format("%%%X",string.byte(chr)) +end + +function encodeString(str) + local output, t = string.gsub(str,"[^%w]",encodeChar) + return output +end + +-- will print "http%3A%2F%2Ffoo%20bar%2F" +print(encodeString("http://foo bar/")) diff --git a/Task/URL-encoding/Phix/url-encoding.phix b/Task/URL-encoding/Phix/url-encoding.phix new file mode 100644 index 0000000000..1ad9f6e994 --- /dev/null +++ b/Task/URL-encoding/Phix/url-encoding.phix @@ -0,0 +1,29 @@ +-- +-- demo\rosetta\encode_url.exw +-- =========================== +-- +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 + +printf(1,"%s\n",{encode_url("http://foo bar/")}) diff --git a/Task/URL-encoding/PowerShell/url-encoding.psh b/Task/URL-encoding/PowerShell/url-encoding.psh new file mode 100644 index 0000000000..1f003d80e7 --- /dev/null +++ b/Task/URL-encoding/PowerShell/url-encoding.psh @@ -0,0 +1,3 @@ +[uri]::EscapeDataString('http://foo bar/') + +http%3A%2F%2Ffoo%20bar%2F diff --git a/Task/URL-encoding/REXX/url-encoding-2.rexx b/Task/URL-encoding/REXX/url-encoding-2.rexx index f773aceff4..8a3b422d88 100644 --- a/Task/URL-encoding/REXX/url-encoding-2.rexx +++ b/Task/URL-encoding/REXX/url-encoding-2.rexx @@ -1,31 +1,28 @@ -/*REXX pgm encodes an URL text, blanks──►+, preserves -._* and -._~ */ -url.1 = 'http://foo bar/' -url.2 = 'mailto:"Ivan Aim" ' -url.3 = 'mailto:"Irma User" ' -url.4 = 'http://foo.bar.com/~user-name/_subdir/*~.html' -URLs = 4 - do j=1 for URLs; say - say url.j - say URLencode(url.j) - end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────URLENCODE subroutine────────────────*/ -URLencode: procedure; parse arg yyy; t1= '-._~' ; skip=0 - t2= '-._*' ; z='' - - do k=1 for length(yyy); _=substr(yyy,k,1) /*pickoff 1char*/ - if skip\==0 then do /*skip t1 | t2?*/ - skip=skip-1 /*skip a char. */ - iterate - end - select - when datatype(_,'A') then z=z || _ /*alphanumeric?*/ - when _==' ' then z=z'+' /*is a blank ? */ - when substr(yyy,k,4)==t1 |, /*t1 or t2 ? */ - substr(yyy,k,4)==t2 then do; skip=3 /*skip 3 chars.*/ - z=z || substr(yyy,k,4) - end - otherwise z=z'%'c2x(_) /*special char.*/ - end /*select*/ - end /*k*/ -return z +/*REXX program encodes a URL text, blanks ──► +, preserves -._* and -._~ */ +url.=; url.1= 'http://foo bar/' + url.2= 'mailto:"Ivan Aim" ' + url.3= 'mailto:"Irma User" ' + url.4= 'http://foo.bar.com/~user-name/_subdir/*~.html' + do j=1 while url.j\==''; say + say ' original: ' url.j + say ' encoded: ' URLencode(url.j) + end /*j*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +URLencode: procedure; parse arg $,,z; t1= '-._~' /*get args, null Z.*/ + skip=0; t2= '-._*' + do k=1 for length($); _=substr($, k, 1) /*get a character. */ + if skip\==0 then do; skip=skip-1 /*skip t1 or t2 ? */ + iterate /*skip a character.*/ + end + select + when datatype(_, 'A') then z=z || _ /*is alphanumeric ?*/ + when _==' ' then z=z'+' /*is it a blank ?*/ + when substr($, k, 4)==t1 |, /*is it t1 or t2 ?*/ + substr($, k, 4)==t2 then do; skip=3 /*skip 3 characters*/ + z=z || substr($, k, 4) + end + otherwise z=z'%'c2x(_) /*special character*/ + end /*select*/ + end /*k*/ + return z diff --git a/Task/URL-encoding/Zkl/url-encoding.zkl b/Task/URL-encoding/Zkl/url-encoding.zkl new file mode 100644 index 0000000000..35dfe68f50 --- /dev/null +++ b/Task/URL-encoding/Zkl/url-encoding.zkl @@ -0,0 +1,2 @@ +var CURL=Import("zklCurl"); +CURL.urlEncode("http://foo bar/") //--> "http%3A%2F%2Ffoo%20bar%2F" 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-.kotlin index e90fd33998..b080101dcb 100644 --- a/Task/Ulam-spiral--for-primes-/Kotlin/ulam-spiral--for-primes-.kotlin +++ b/Task/Ulam-spiral--for-primes-/Kotlin/ulam-spiral--for-primes-.kotlin @@ -1,5 +1,3 @@ -package ulam - object Ulam { fun generate(n: Int, i: Int = 1, c: Char = '*') { require(n > 1) diff --git a/Task/Ulam-spiral--for-primes-/R/ulam-spiral--for-primes-.r b/Task/Ulam-spiral--for-primes-/R/ulam-spiral--for-primes-.r new file mode 100644 index 0000000000..7c9b3fd2a1 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/R/ulam-spiral--for-primes-.r @@ -0,0 +1,30 @@ +## Plotting Ulam spiral (for primes) 2/12/17 aev +## plotulamspirR(n, clr, fn, ttl, psz=600), where: n - initial size; +## clr - color; fn - file name; ttl - plot title; psz - picture size. +## +require(numbers); +plotulamspirR <- function(n, clr, fn, ttl, psz=600) { + cat(" *** START:", date(), "n=",n, "clr=",clr, "psz=", psz, "\n"); + if (n%%2==0) {n=n+1}; n2=n*n; + x=y=floor(n/2); xmx=ymx=cnt=1; dir="R"; + ttl= paste(c(ttl, n,"x",n," matrix."), sep="", collapse=""); + cat(" ***", ttl, "\n"); + M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE); + for (i in 1:n2) { + if(isPrime(i)) {M[x,y]=1}; + if(dir=="R") {if(xmx>0) {x=x+1;xmx=xmx-1} + else {dir="U";ymx=cnt;y=y-1;ymx=ymx-1}; next}; + if(dir=="U") {if(ymx>0) {y=y-1;ymx=ymx-1} + else {dir="L";cnt=cnt+1;xmx=cnt;x=x-1;xmx=xmx-1}; next}; + if(dir=="L") {if(xmx>0) {x=x-1;xmx=xmx-1} + else {dir="D";ymx=cnt;y=y+1;ymx=ymx-1}; next}; + if(dir=="D") {if(ymx>0) {y=y+1;ymx=ymx-1} + else {dir="R";cnt=cnt+1;xmx=cnt;x=x+1;xmx=xmx-1}; next}; + }; + plotmat(M, fn, clr, ttl,,psz); + cat(" *** END:",date(),"\n"); +} + +## Executing: +plotulamspirR(100, "red", "UlamSpiralR1", "Ulam Spiral: "); +plotulamspirR(200, "red", "UlamSpiralR2", "Ulam Spiral: ",1240); diff --git a/Task/Ulam-spiral--for-primes-/Sidef/ulam-spiral--for-primes-.sidef b/Task/Ulam-spiral--for-primes-/Sidef/ulam-spiral--for-primes-.sidef index fe121a8f6a..92d89b2d63 100644 --- a/Task/Ulam-spiral--for-primes-/Sidef/ulam-spiral--for-primes-.sidef +++ b/Task/Ulam-spiral--for-primes-/Sidef/ulam-spiral--for-primes-.sidef @@ -1,27 +1,26 @@ -require('Imager'); +require('Imager')   -var (n=512, start=1, file='ulam.png') = ARGV»to_i»()...; +var (n=512, start=1, file='ulam.png') = ARGV.map{.to_i}...   func cell(n, x, y, start) { - y -= (n >> 1); - x -= (n-1 >> 1); - var l = 2*(x.abs > y.abs ? x.abs : y.abs); - var d = (y > x  ? (l*3 + x + y) : (l - x - y)); - (l-1)**2 + d + start - 1; + y -= (n >> 1) + x -= (n-1 >> 1) + var l = 2*(x.abs > y.abs ? x.abs : y.abs) + var d = (y > x  ? (l*3 + x + y) : (l - x - y)) + (l-1)**2 + d + start - 1 }   -var black = %s'Imager::Color'.new('#000000'); -var white = %s'Imager::Color'.new('#FFFFFF'); +var black = %s'Imager::Color'.new('#000000') +var white = %s'Imager::Color'.new('#FFFFFF')   -var img = %s'Imager'.new(xsize => n, ysize => n, channels => 1); -img.box(filled => 1, color => white); +var img = %s'Imager'.new(xsize => n, ysize => n, channels => 1) +img.box(filled => 1, color => white)   -for y in ^n { - for x in ^n { - var v = cell(n, x, y, start); - v.is_prime && - img.setpixel(x => x, y => y, color => black); +for y,x in (^n ~X ^n) { + var v = cell(n, x, y, start) + if (v.is_prime) { + img.setpixel(x => x, y => y, color => black) } }   -img.write(file => file); +img.write(file => file) diff --git a/Task/Ulam-spiral--for-primes-/Zkl/ulam-spiral--for-primes-.zkl b/Task/Ulam-spiral--for-primes-/Zkl/ulam-spiral--for-primes-.zkl new file mode 100644 index 0000000000..27bb140c8f --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Zkl/ulam-spiral--for-primes-.zkl @@ -0,0 +1,22 @@ +var primes =Utils.Generator(Import("sieve.zkl").postponed_sieve); // lazy +var offsets=Utils.cycle( T(0,1),T(-1,0),T(0,-1),T(1,0) ); // (N,E,S,W), lazy +const BLACK=0, WHITE=0xff|ff|ff, GREEN=0x00|ff|00, EMPTY=0x080|80|80; +fcn uspiral(N){ + if((M:=N).isEven) M+=1; // need odd width, height + img,p := PPM(M,M,EMPTY), primes.next(); // 2 .. 250,007: 22,045 primes + x,y,n := N/2,x,2; img[x,y]=GREEN; x+=1; // start on 2 facing "north" + while(True){ + ox,oy:=offsets.next(); leftx,lefty:=offsets.peek(); // set direction + while(True){ + img[x,y]=( if(n==p){ p=primes.next(); WHITE } else BLACK ); + if(n==N*N) break(2); // all done + n+=1; + if(img[x+leftx,y+lefty]==EMPTY) // nothing to my left, turn left + { x+=leftx; y+=lefty; break; } + x+=ox; y+=oy; // move in a straight line + } + } + img +} + +uspiral(500).write(File("ulamSpiral.ppm","wb")); diff --git a/Task/Unbias-a-random-generator/Kotlin/unbias-a-random-generator.kotlin b/Task/Unbias-a-random-generator/Kotlin/unbias-a-random-generator.kotlin new file mode 100644 index 0000000000..e3c6811573 --- /dev/null +++ b/Task/Unbias-a-random-generator/Kotlin/unbias-a-random-generator.kotlin @@ -0,0 +1,28 @@ +// version 1.1.2 + +fun biased(n: Int) = Math.random() < 1.0 / n + +fun unbiased(n: Int): Boolean { + var a: Boolean + var b: Boolean + do { + a = biased(n) + b = biased(n) + } + while (a == b) + return a +} + +fun main(args: Array) { + val m = 50_000 + val f = "%d: %2.2f%% %2.2f%%" + for (n in 3..6) { + var c1 = 0 + var c2 = 0 + for (i in 0 until m) { + if (biased(n)) c1++ + if (unbiased(n)) c2++ + } + println(f.format(n, 100.0 * c1 / m, 100.0 * c2 / m)) + } +} diff --git a/Task/Unbias-a-random-generator/Nim/unbias-a-random-generator.nim b/Task/Unbias-a-random-generator/Nim/unbias-a-random-generator.nim index e964bbef99..3f17d34f47 100644 --- a/Task/Unbias-a-random-generator/Nim/unbias-a-random-generator.nim +++ b/Task/Unbias-a-random-generator/Nim/unbias-a-random-generator.nim @@ -3,20 +3,18 @@ randomize() template newSeqWith(len: int, init: expr): expr = var result {.gensym.} = newSeq[type(init)](len) - for i in 0 .. ) { + val soc = SomeOtherClass() + + try { + soc.printSomething() + } + catch (ex: Exception) { + println(ex) + } + + try { + soc.someFunc() + } + catch (e: Error) { + println(e) + } +} diff --git a/Task/Undefined-values/Zkl/undefined-values.zkl b/Task/Undefined-values/Zkl/undefined-values.zkl new file mode 100644 index 0000000000..8d7ae16e1b --- /dev/null +++ b/Task/Undefined-values/Zkl/undefined-values.zkl @@ -0,0 +1,3 @@ +println(Void); +1+Void +if(Void){} else { 23 } diff --git a/Task/Unicode-strings/Elena/unicode-strings.elena b/Task/Unicode-strings/Elena/unicode-strings.elena index 2ed7a05ca3..9d1428706b 100644 --- a/Task/Unicode-strings/Elena/unicode-strings.elena +++ b/Task/Unicode-strings/Elena/unicode-strings.elena @@ -1,9 +1,7 @@ -#import system. - -#symbol program = +program = [ - #var 四十二 := "♥♦♣♠". // UTF8 string - #var строка := "Привет"w. // UTF16 string + var 四十二 := "♥♦♣♠". // UTF8 string + var строка := "Привет"w. // UTF16 string console writeLine:строка. console writeLine:四十二. diff --git a/Task/Unicode-strings/Kotlin/unicode-strings.kotlin b/Task/Unicode-strings/Kotlin/unicode-strings.kotlin new file mode 100644 index 0000000000..513ba95287 --- /dev/null +++ b/Task/Unicode-strings/Kotlin/unicode-strings.kotlin @@ -0,0 +1,6 @@ +// version 1.1.2 + +fun main(args: Array) { + val åäö = "as⃝df̅ ♥♦♣♠ 頰" + println(åäö) +} diff --git a/Task/Unicode-variable-names/Elena/unicode-variable-names.elena b/Task/Unicode-variable-names/Elena/unicode-variable-names.elena index 888d14c087..cc5bdbea1d 100644 --- a/Task/Unicode-variable-names/Elena/unicode-variable-names.elena +++ b/Task/Unicode-variable-names/Elena/unicode-variable-names.elena @@ -1,8 +1,6 @@ -#import system. - -#symbol program = +program = [ - #var Δ := 1. + var Δ := 1. Δ := Δ + 1. console writeLine:Δ. diff --git a/Task/Unicode-variable-names/Frink/unicode-variable-names.frink b/Task/Unicode-variable-names/Frink/unicode-variable-names.frink new file mode 100644 index 0000000000..9c3eeefd0b --- /dev/null +++ b/Task/Unicode-variable-names/Frink/unicode-variable-names.frink @@ -0,0 +1,3 @@ +Δ = 1 +Δ = Δ + 1 +println[Δ] diff --git a/Task/Unicode-variable-names/Jq/unicode-variable-names-1.jq b/Task/Unicode-variable-names/Jq/unicode-variable-names-1.jq new file mode 100644 index 0000000000..e93439eead --- /dev/null +++ b/Task/Unicode-variable-names/Jq/unicode-variable-names-1.jq @@ -0,0 +1 @@ +{ "Δ": 1 } | .["Δ"] diff --git a/Task/Unicode-variable-names/Jq/unicode-variable-names-2.jq b/Task/Unicode-variable-names/Jq/unicode-variable-names-2.jq new file mode 100644 index 0000000000..2b53ee11ff --- /dev/null +++ b/Task/Unicode-variable-names/Jq/unicode-variable-names-2.jq @@ -0,0 +1 @@ +.["Δ"] diff --git a/Task/Unicode-variable-names/Jq/unicode-variable-names-3.jq b/Task/Unicode-variable-names/Jq/unicode-variable-names-3.jq new file mode 100644 index 0000000000..ec86c9946f --- /dev/null +++ b/Task/Unicode-variable-names/Jq/unicode-variable-names-3.jq @@ -0,0 +1 @@ +."Δ" diff --git a/Task/Unicode-variable-names/Jq/unicode-variable-names-4.jq b/Task/Unicode-variable-names/Jq/unicode-variable-names-4.jq new file mode 100644 index 0000000000..8243e08e7f --- /dev/null +++ b/Task/Unicode-variable-names/Jq/unicode-variable-names-4.jq @@ -0,0 +1,3 @@ +{ "Δ": 1 } # initialization +| .["Δ"] += 1 # increment by 1 +| .["Δ"] # emit the incremented value diff --git a/Task/Unicode-variable-names/Kotlin/unicode-variable-names.kotlin b/Task/Unicode-variable-names/Kotlin/unicode-variable-names.kotlin new file mode 100644 index 0000000000..101c8a6445 --- /dev/null +++ b/Task/Unicode-variable-names/Kotlin/unicode-variable-names.kotlin @@ -0,0 +1,5 @@ +fun main(args: Array) { + var Δ = 1 + Δ++ + print(Δ) +} diff --git a/Task/Unicode-variable-names/Lua/unicode-variable-names.lua b/Task/Unicode-variable-names/Lua/unicode-variable-names.lua index a5b2309910..2082489675 100644 --- a/Task/Unicode-variable-names/Lua/unicode-variable-names.lua +++ b/Task/Unicode-variable-names/Lua/unicode-variable-names.lua @@ -1,9 +1,3 @@ -local unicode = {} -unicode["Für"] = "for" -print(unicode["Für"]) - -unicode["garçon"] = "boy" -print(unicode["garçon"]) - -unicode["∆"]=1 -print(unicode["∆"]) +∆ = 1 +∆ = ∆ + 1 +print(∆) diff --git a/Task/Unicode-variable-names/Nimrod/unicode-variable-names.nimrod b/Task/Unicode-variable-names/Nimrod/unicode-variable-names.nimrod deleted file mode 100644 index 90f18dc334..0000000000 --- a/Task/Unicode-variable-names/Nimrod/unicode-variable-names.nimrod +++ /dev/null @@ -1,3 +0,0 @@ -var Δ = 1 -Δ.inc() -echo(Δ) diff --git a/Task/Unicode-variable-names/Protium/unicode-variable-names-1.protium b/Task/Unicode-variable-names/Protium/unicode-variable-names-1.protium deleted file mode 100644 index 20b99e6665..0000000000 --- a/Task/Unicode-variable-names/Protium/unicode-variable-names-1.protium +++ /dev/null @@ -1,3 +0,0 @@ -<@ LETVARLIT>Δ|1 -<@ ACTICRVAR>Δ -<@ SAYVAR>Δ diff --git a/Task/Unicode-variable-names/Protium/unicode-variable-names-2.protium b/Task/Unicode-variable-names/Protium/unicode-variable-names-2.protium deleted file mode 100644 index 504503f553..0000000000 --- a/Task/Unicode-variable-names/Protium/unicode-variable-names-2.protium +++ /dev/null @@ -1,3 +0,0 @@ -<@ LETVARLIT>三角洲|1 -<@ ACTICRVAR>三角洲 -<@ SAYVAR>三角洲 diff --git a/Task/Unicode-variable-names/Ring/unicode-variable-names.ring b/Task/Unicode-variable-names/Ring/unicode-variable-names.ring new file mode 100644 index 0000000000..e516a2e9c9 --- /dev/null +++ b/Task/Unicode-variable-names/Ring/unicode-variable-names.ring @@ -0,0 +1,7 @@ +# Project : Unicode variable names +# Date : 2017/09/20 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +Δ = "Ring Programming Language" +see Δ + nl diff --git a/Task/Unicode-variable-names/Ruby/unicode-variable-names-1.rb b/Task/Unicode-variable-names/Ruby/unicode-variable-names-1.rb deleted file mode 100644 index 274d8a154e..0000000000 --- a/Task/Unicode-variable-names/Ruby/unicode-variable-names-1.rb +++ /dev/null @@ -1,4 +0,0 @@ -# -*- coding: big5 -*- -Δ = 1 -Δ += 1 -puts Δ diff --git a/Task/Unicode-variable-names/Ruby/unicode-variable-names-2.rb b/Task/Unicode-variable-names/Ruby/unicode-variable-names-2.rb deleted file mode 100644 index b7d1f69264..0000000000 --- a/Task/Unicode-variable-names/Ruby/unicode-variable-names-2.rb +++ /dev/null @@ -1,13 +0,0 @@ -# -*- coding: euc-jp -*- - -class Numeric - def ≦(♯♭♪) - self <= ♯♭♪ - end -end - -∞ = Float::INFINITY -±5 = [-5, 5] -p [(±5.first.≦ ∞), - (±5.last.≦ ∞), - (∞.≦ ∞)] diff --git a/Task/Unicode-variable-names/Rust/unicode-variable-names.rust b/Task/Unicode-variable-names/Rust/unicode-variable-names.rust index 0f96c3d8a4..55c6fc4c1e 100644 --- a/Task/Unicode-variable-names/Rust/unicode-variable-names.rust +++ b/Task/Unicode-variable-names/Rust/unicode-variable-names.rust @@ -1,4 +1,5 @@ #![feature(non_ascii_idents)] +#![allow(non_snake_case)] fn main() { let mut Δ: i32 = 1; diff --git a/Task/Unicode-variable-names/S-lang/unicode-variable-names.slang b/Task/Unicode-variable-names/S-lang/unicode-variable-names.slang new file mode 100644 index 0000000000..72b9cfd7ad --- /dev/null +++ b/Task/Unicode-variable-names/S-lang/unicode-variable-names.slang @@ -0,0 +1,11 @@ +define ∆increment(∆ref) { + @∆ref++; +} +variable foo∆bar = 1; +foo∆bar++; +variable ∆bar = 1; +∆bar++; +∆increment(&∆bar); +% foo∆bar should be 2 and ∆bar should be 3. +print(foo∆bar); +print(∆bar); diff --git a/Task/Unicode-variable-names/Zkl/unicode-variable-names.zkl b/Task/Unicode-variable-names/Zkl/unicode-variable-names.zkl new file mode 100644 index 0000000000..6ce6568518 --- /dev/null +++ b/Task/Unicode-variable-names/Zkl/unicode-variable-names.zkl @@ -0,0 +1,9 @@ +delta:="\U0394;"; // UTF-8 delta +klass:= // embryo(names, numFcns, numClasses, numParents, ...) + self.embryo(L("","",delta),0,0,0).cook(); +klass.setVar(0,Ref(1)); // indirect set since delta not valid var name +klass.vars.println(); + +dv:=klass.setVar(0); // which actually gets the var, go figure +dv.inc(); // ie (*ptr)++ +dv.value.println(); diff --git a/Task/Universal-Turing-machine/BASIC/universal-turing-machine-1.basic b/Task/Universal-Turing-machine/BASIC/universal-turing-machine-1.basic new file mode 100644 index 0000000000..eedda66847 --- /dev/null +++ b/Task/Universal-Turing-machine/BASIC/universal-turing-machine-1.basic @@ -0,0 +1,18 @@ +1000 PRINT AT 0,0;T$ +1010 LET P=1 +1020 IF P>LEN T$ THEN LET T$=T$+B$ +1030 PRINT AT INT (P/32),P-(32*INT (P/32)+1);CHR$ (CODE T$(P)+128) +1040 LET R=1 +1050 IF R$(R,1)=S$ AND R$(R,2)=T$(P) THEN GOTO 1080 +1060 LET R=R+1 +1070 GOTO 1050 +1080 LET T$(P)=R$(R,3) +1090 PRINT AT INT (P/32),P-(32*INT (P/32)+1);T$(P) +1100 IF R$(R,4)="L" THEN LET P=P-1 +1110 IF R$(R,4)="R" THEN LET P=P+1 +1120 LET S$=R$(R,5) +1130 IF S$=H$ THEN STOP +1140 IF P=0 THEN GOTO 1160 +1150 GOTO 1020 +1160 LET T$=B$+T$ +1170 GOTO 1000 diff --git a/Task/Universal-Turing-machine/BASIC/universal-turing-machine-2.basic b/Task/Universal-Turing-machine/BASIC/universal-turing-machine-2.basic new file mode 100644 index 0000000000..408938ea8f --- /dev/null +++ b/Task/Universal-Turing-machine/BASIC/universal-turing-machine-2.basic @@ -0,0 +1,7 @@ +10 DIM R$(2,5) +20 LET S$=CHR$ (CODE "Q"+CODE "0") +30 LET H$=CHR$ (CODE "Q"+CODE "F") +40 LET R$(1)=S$+"11R"+S$ +50 LET R$(2)=S$+"B1S"+H$ +60 LET B$="B" +70 LET T$="111" diff --git a/Task/Universal-Turing-machine/BASIC/universal-turing-machine-3.basic b/Task/Universal-Turing-machine/BASIC/universal-turing-machine-3.basic new file mode 100644 index 0000000000..b4b7b71364 --- /dev/null +++ b/Task/Universal-Turing-machine/BASIC/universal-turing-machine-3.basic @@ -0,0 +1,11 @@ + 10 DIM R$(6,5) + 20 LET R$(1)="A01RB" + 30 LET R$(2)="A11LC" + 40 LET R$(3)="B01LA" + 50 LET R$(4)="B11RB" + 60 LET R$(5)="C01LB" + 70 LET R$(6)="C11SH" + 80 LET T$="" + 90 LET S$="A" +100 LET B$="0" +110 LET H$="H" diff --git a/Task/Universal-Turing-machine/JavaScript/universal-turing-machine.js b/Task/Universal-Turing-machine/JavaScript/universal-turing-machine.js index f7ef54afcf..3963509e5f 100644 --- a/Task/Universal-Turing-machine/JavaScript/universal-turing-machine.js +++ b/Task/Universal-Turing-machine/JavaScript/universal-turing-machine.js @@ -1,6 +1,7 @@ function tm(d,s,e,i,b,t,... r) { document.write(d, '
    ') if (i<0||i>=t.length) return + var re=new RegExp(b,'g') write('*',s,i,t=t.split('')) var p={}; r.forEach(e=>((s,r,w,m,n)=>{p[s+'.'+r]={w,n,m:[0,1,-1][1+'RL'.indexOf(m)]}})(... e.split(/[ .:,]+/))) for (var n=1; s!=e; n+=1) { @@ -13,7 +14,7 @@ function tm(d,s,e,i,b,t,... r) { function write(n, s, i, t) { t = t.join('') t = t.substring(0,i) + '' + t.charAt(i) + '' + t.substr(i+1) - document.write((' '+n).slice(-3).replace(/ /g,' '), ': ', s, ' [', t.replace(b,' ','g'), ']', '
    ') + document.write((' '+n).slice(-3).replace(/ /g,' '), ': ', s, ' [', t.replace(re,' '), ']', '
    ') } } @@ -24,16 +25,14 @@ tm( 'Unary incrementer', 'a.1: 1, L, a', 'a.B: 1, S, h' ) - + tm( 'Unary adder', 1, 0, 0, '0', '1110111', '1.1: 0, R, 2', // write 0 rigth goto 2 - '2.0: 0, S, 0', // if (0) halt - '2.1: 0, R, 3', // write 0 rigth goto 3 - '3.1: 1, R, 3', // while (1) rigth - '3.0: 1, S, 0', // write 1 halt + '2.1: 1, R, 2', // while (1) rigth + '2.0: 1, S, 0' // write 1 stay halt ) - + tm( 'Three-state busy beaver', 1, 0, 0, '0', '0', '1.0: 1, R, 2', diff --git a/Task/Universal-Turing-machine/Phix/universal-turing-machine.phix b/Task/Universal-Turing-machine/Phix/universal-turing-machine.phix new file mode 100644 index 0000000000..92c6ebb07d --- /dev/null +++ b/Task/Universal-Turing-machine/Phix/universal-turing-machine.phix @@ -0,0 +1,93 @@ +enum name, initState, endState, blank, rules + +-- Machine definitions +constant incrementer = { + /*name =*/ "Simple incrementer", + /*initState =*/ "q0", + /*endState =*/ "qf", + /*blank =*/ "B", + /*rules =*/ { + {"q0", "1", "1", "right", "q0"}, + {"q0", "B", "1", "stay", "qf"} + } +} + +constant threeStateBB = { + /*name =*/ "Three-state busy beaver", + /*initState =*/ "a", + /*endState =*/ "halt", + /*blank =*/ "0", + /*rules =*/ { + {"a", "0", "1", "right", "b"}, + {"a", "1", "1", "left", "c"}, + {"b", "0", "1", "left", "a"}, + {"b", "1", "1", "right", "b"}, + {"c", "0", "1", "left", "b"}, + {"c", "1", "1", "stay", "halt"} + } +} + +constant fiveStateBB = { + /*name =*/ "Five-state busy beaver", + /*initState =*/ "A", + /*endState =*/ "H", + /*blank =*/ "0", + /*rules =*/ { + {"A", "0", "1", "right", "B"}, + {"A", "1", "1", "left", "C"}, + {"B", "0", "1", "right", "C"}, + {"B", "1", "1", "right", "B"}, + {"C", "0", "1", "right", "D"}, + {"C", "1", "0", "left", "E"}, + {"D", "0", "1", "left", "A"}, + {"D", "1", "1", "left", "D"}, + {"E", "0", "1", "stay", "H"}, + {"E", "1", "0", "left", "A"} + } +} + +procedure show(string state, integer headpos, sequence tape) + printf(1," %-6s | ",{state}) + for p=1 to length(tape) do + printf(1,iff(p=headpos?"[%s]":" %s "),{tape[p]}) + end for + printf(1,"\n") +end procedure + +-- a universal turing machine +procedure UTM(sequence machine, sequence tape, integer countOnly=0) +string state = machine[initState] +integer headpos = 1, counter = 0 + printf(1,"\n\n%s\n%s\n",{machine[name],repeat('=',length(machine[name]))}) + if not countOnly then printf(1," State | Tape [head]\n---------------------\n") end if + while 1 do + if headpos>length(tape) then + tape = append(tape,machine[blank]) + elsif headpos<1 then + tape = prepend(tape,machine[blank]) + headpos = 1 + end if + if not countOnly then show(state, headpos, tape) end if + for i=1 to length(machine[rules]) do + sequence rule = machine[rules][i] + if rule[1]=state and rule[2]=tape[headpos] then + tape[headpos] = rule[3] + if rule[4] == "left" then headpos -= 1 end if + if rule[4] == "right" then headpos += 1 end if + state = rule[5] + exit + end if + end for + counter += 1 + if state=machine[endState] then exit end if + end while + if countOnly then + printf(1,"Steps taken: %d\n",{counter}) + else + show(state, headPos, tape) + end if +end procedure + +UTM(incrementer, {"1", "1", "1"}) +UTM(threeStateBB, {}) +UTM(fiveStateBB, {}, countOnly:=1) diff --git a/Task/Universal-Turing-machine/REXX/universal-turing-machine-1.rexx b/Task/Universal-Turing-machine/REXX/universal-turing-machine-1.rexx index dc78bbdb8e..029386d5e7 100644 --- a/Task/Universal-Turing-machine/REXX/universal-turing-machine-1.rexx +++ b/Task/Universal-Turing-machine/REXX/universal-turing-machine-1.rexx @@ -18,8 +18,7 @@ TM: !=1; bot=1; top=1; @er= '***error***' /*start at the tape location if rMove== 'left' then !=!-1 /*Are we moving left? Then subtract 1*/ if rMove=='right' then !=!+1 /* " " " right? " add 1*/ bot=min(bot, !); top=max(top, !) /*find the tape bottom and top. */ - state=rNext /*use this for the next state. */ - iterate cycle /*go process another TM instruction. */ + state=rNext; iterate cycle /*use this for the next state; and */ end /*k*/ say @er 'unknown state:' state; leave /*oops, we have an unknown state error.*/ end /*cycle*/ @@ -27,8 +26,8 @@ TM: !=1; bot=1; top=1; @er= '***error***' /*start at the tape location do t=bot to top; _=@.t if _==blank then _=' ' /*do we need to translate a true blank?*/ $=$ || pad || _ /*construct char by char, maybe pad it.*/ - end /*t*/ /* [↑] construct the tape's contents.*/ - L=length($) + end /*t*/ /* [↑] construct the tape's contents*/ + L=length($) /*obtain length of " " " */ if L==0 then $= "[tape is blank.]" /*make an empty tape visible to user.*/ if L>1000 then $=left($, 1000) ... /*truncate tape to 1k bytes, append ···*/ say "tape's contents:" $ /*show the tape's contents (or 1st 1k).*/ diff --git a/Task/Universal-Turing-machine/Standard-ML/universal-turing-machine.ml b/Task/Universal-Turing-machine/Standard-ML/universal-turing-machine.ml new file mode 100644 index 0000000000..614c722a1f --- /dev/null +++ b/Task/Universal-Turing-machine/Standard-ML/universal-turing-machine.ml @@ -0,0 +1,331 @@ +(*** Signatures ***) + +signature TAPE = sig + datatype move = Left | Right | Stay + + type ''a tape + val empty : ''a tape + val moveLeft : ''a tape -> ''a tape + val moveRight : ''a tape -> ''a tape + val move : ''a tape -> move -> ''a tape + val getSymbol : ''a tape -> ''a option + val write : ''a option -> ''a tape -> ''a tape + val leftOf : ''a tape -> ''a option list (* Symbols left of the head in reverse order *) + val rightOf : ''a tape -> ''a option list (* Symbols right of of the head *) +end + +signature MACHINE = sig + structure Tape : TAPE + + type state = int + + (* ''a is band alphabet type *) + type ''a transitions = (state * ''a option Vector.vector) -> + (state * (Tape.move * ''a option) Vector.vector) + + type ''a configuration = { state : state, tapes : ''a Tape.tape Vector.vector } + + type ''a machine = { + alphabet : ''a Vector.vector, (* (not used) *) + states : state Vector.vector, (* (not used) *) + start : state, (* element of stats *) + final : state, (* element of stats *) + transitions : ''a transitions, (* transitions *) + tapes : ''a Tape.tape Vector.vector (* vector of the initial tapes *) + } +end + + + +signature UNIVERSALMACHINE = sig + structure Machine : MACHINE + + val start : ''a Machine.machine -> ''a Machine.configuration + + (* Find a holding configuration (limited by n steps) + * Execute the handler for each step *) + val simulate : (''a Machine.configuration -> unit) -> ''a Machine.machine -> int option -> ''a Machine.configuration option +end + + +(*** Implementation ***) + +structure Tape :> TAPE = struct + + (* + * NONE => blank field + * SOME a => written field + *) + type ''a symbol = ''a option + + datatype move = Left | Right | Stay + + (* + * Four cases: + * 1 The tape is complete empty. + * 2 The head is in the written area. + * On the right and on the left handside are symbols, + * On the head is a symbol. + * 3/4 The head is (n-1) fields over the right/left edge of the written area. + * There is at least one entry and a rest list of entries. + *) + datatype ''a tape = + Empty + | Middle of ''a symbol list * ''a symbol * ''a symbol list + | LeftOf of ''a symbol * ''a symbol list * int + | RightOf of ''a symbol * ''a symbol list * int + + val empty = Empty + + fun rep a 0 = nil + | rep a n = a :: rep a (n-1) + + fun leftOf (Empty) = nil + | leftOf (Middle (ls, _, _)) = ls + | leftOf (RightOf (r, rs, i)) = rep NONE i @ r :: rs + | leftOf (LeftOf _) = nil + + fun rightOf (Empty) = nil + | rightOf (Middle (_, _, rs)) = rs + | rightOf (RightOf _) = nil + | rightOf (LeftOf (l, ls, i)) = rep NONE i @ l :: ls + + fun write (NONE) t = t (* Cannot write a blank field! *) + | write a t = Middle (leftOf t, a, rightOf t) + + fun getSymbol (Middle (_, m, _)) = m + | getSymbol _ = NONE (* blank *) + + + fun moveRight (Empty) = Empty + | moveRight (Middle (ls, m, nil)) = RightOf (m, ls, 0) + | moveRight (Middle (ls, m, r::rs)) = Middle (m::ls, r, rs) + | moveRight (RightOf (l, ls, n)) = RightOf (l, ls, n+1) + | moveRight (LeftOf (r, rs, 0)) = Middle (nil, r, rs) + | moveRight (LeftOf (r, rs, n)) = LeftOf (r, rs, n-1) + + + fun moveLeft (Empty) = Empty + | moveLeft (Middle (nil, m, rs)) = LeftOf (m, rs, 0) + | moveLeft (Middle (l::ls, m, rs)) = Middle (ls, l, m::rs) + | moveLeft (RightOf (l, ls, 0)) = Middle (ls, l, nil) + | moveLeft (RightOf (l, ls, n)) = RightOf (l, ls, n-1) + | moveLeft (LeftOf (r, rs, n)) = LeftOf (r, rs, n+1) + + + fun move tape Stay = tape + | move tape Right = moveRight tape + | move tape Left = moveLeft tape + + (* Test *) + local + val tape : int tape = empty (* [] *) + val tape = moveRight tape (* [] *) + val NONE = getSymbol tape + val tape = write (SOME 42) tape (* [42] *) + val (SOME 42) = getSymbol tape + val tape = moveRight tape (* 42, [] *) + val tape = moveRight tape (* 42, , [] *) + val NONE = getSymbol tape + val tape = moveLeft tape (* 42, [] *) + val NONE = getSymbol tape + val tape = moveLeft tape (* [42] *) + val (SOME 42) = getSymbol tape + val tape = write NONE tape (* [42] *) (* !!! *) + val (SOME 42) = getSymbol tape + val tape = moveLeft tape (* [], 42 *) + val tape = moveLeft tape (* [], , 42 *) + val tape = write (SOME 47) tape (* [47], , 42 *) + val (SOME 47) = getSymbol tape + val tape = moveRight tape (* 47, [], 42 *) + val NONE = getSymbol tape + val tape = moveRight tape (* 47, , [42] *) + val (SOME 42) = getSymbol tape + in end +end + +structure Machine :> MACHINE = struct + structure Tape = Tape + + type state = int + + (* ''a is band alphabet type *) + type ''a transitions = (state * ''a option Vector.vector) -> + (state * (Tape.move * ''a option) Vector.vector) + + type ''a configuration = { state : state, tapes : ''a Tape.tape Vector.vector } + + type ''a machine = { + alphabet : ''a Vector.vector, + states : state Vector.vector, + start : state, + final : state, + transitions : ''a transitions, + tapes : ''a Tape.tape Vector.vector + } +end + +structure UniversalMachine :> UNIVERSALMACHINE = struct + + structure Machine = Machine + + fun start ({ start, tapes, ... } : ''a Machine.machine) : ''a Machine.configuration = { + state = start, + tapes = tapes + } + + fun doTransition ({ state, tapes } : ''a Machine.configuration) + ((state', actions) : (Machine.state * (Machine.Tape.move * ''a option) Vector.vector)) + : ''a Machine.configuration = { + state = state', + tapes = Vector.mapi (fn (i, tape) => + let val (move, write) = Vector.sub (actions, i) + val tape' = Machine.Tape.write write tape + val tape'' = Machine.Tape.move tape' move + in tape'' end) tapes + } + + fun getSymbols ({ tapes, ... } : ''a Machine.configuration) : ''a option Vector.vector = + Vector.map (Machine.Tape.getSymbol) tapes + + fun step ({ transitions, ... } : ''a Machine.machine) (conf : ''a Machine.configuration) : ''a Machine.configuration = + doTransition conf (transitions (#state conf, getSymbols conf)) + + fun isFinal ({final, ...} : ''a Machine.machine) ({state, ...} : ''a Machine.configuration) : bool = + final = state + + fun iter term (SOME 0) f s = NONE + | iter term (SOME n) f s = if term s then SOME s else iter term (SOME (n-1)) f (f s) + | iter term NONE f s = if term s then SOME s else iter term NONE f (f s) + + + fun simulate handler (machine : ''a Machine.machine) optcount = + let val endconf = iter (isFinal machine) optcount (fn conf => (handler conf; step machine conf)) (start machine) + in case endconf of NONE => NONE | SOME conf => (handler conf; endconf) end + +end + + +structure ExampleMachines = struct + + structure Machine = UniversalMachine.Machine + + (* Tranform the 5-Tuple notation into the vector function *) + fun makeTransitions nil : ''a Machine.transitions = (fn (t, vec) => (print (Int.toString t); raise Subscript)) + | makeTransitions ((s : Machine.state, + read : ''a option, + write : ''a option, + move : Machine.Tape.move, + s' : Machine.state) :: ts) = + fn (t, vec) => + if s=t andalso vec=(Vector.fromList [read]) + then (s', Vector.fromList [(move, write)]) + else makeTransitions ts (t, vec) + + (* `createTape xs` creates an tape initialized by xs, where the head stands on the first element of xs *) + fun createTape' nil = Machine.Tape.empty + | createTape' (x::xs) = Machine.Tape.moveLeft (Machine.Tape.write x (createTape' xs)) + + fun createTape xs = Machine.Tape.moveRight (createTape' (rev xs)) + + + (* Convert a tape into a string to print it. It needs a function that converts each symbol to string *) + fun tapeToStr (symStr : ''a -> string) (tape : ''a Machine.Tape.tape) : string = + let val left : ''a option list = rev (Machine.Tape.leftOf tape) + val right : ''a option list = Machine.Tape.rightOf tape + val current : ''a option = Machine.Tape.getSymbol tape + val symToStr : ''a option -> string = (fn (NONE) => "#" | (SOME a) => symStr a) + in + String.concatWith " " ((map symToStr left) @ [ "|" ^ symToStr current ^ "|" ] @ (map symToStr right)) + end + + (* Convert a vector to a list *) + fun vectToList vect = List.tabulate (Vector.length vect, fn i => Vector.sub (vect, i)) + + + (* Do this before every step and after the last step. *) + fun handler (symToStr : ''a -> string) ({state, tapes} : ''a Machine.configuration) : unit = + let + val str = "State " ^ Int.toString state ^ "\n" ^ + String.concat (vectToList (Vector.mapi (fn (i, tape) => "Tape #" ^ Int.toString i ^ ": " ^ + tapeToStr symToStr tape ^ "\n") tapes)) + in + print str + end + + + (* Simulate and make result into string *) + fun simulate (symToStr : ''a -> string) (machine : ''a Machine.machine) + (optcount : int option) : string = + case (UniversalMachine.simulate (handler symToStr) machine optcount) of + NONE => "Did not terminate." + | SOME ({state, tapes} : ''a Machine.configuration) => "Terminated." + + + + (* Now finaly the machines! *) + + val incrementer : unit Machine.machine = { + alphabet = Vector.fromList [()], + states = Vector.fromList [0, 1], + start = 0, + final = 1, + tapes = Vector.fromList [createTape (map SOME [(), (), (), ()])], + transitions = makeTransitions [ + (0, SOME (), SOME (), Machine.Tape.Right, 0), + (0, NONE, SOME (), Machine.Tape.Stay, 1)] + } + + val busybeaver : unit Machine.machine = { + alphabet = Vector.fromList [()], + states = Vector.fromList [0, 1, 2, 3], + start = 0, + final = 3, + tapes = Vector.fromList [Machine.Tape.empty], + transitions = makeTransitions [ + (0, NONE, SOME (), Machine.Tape.Right, 1), + (0, SOME (), SOME (), Machine.Tape.Left, 2), + (1, NONE, SOME (), Machine.Tape.Left, 0), + (1, SOME (), SOME (), Machine.Tape.Right, 1), + (2, NONE, SOME (), Machine.Tape.Left, 1), + (2, SOME (), SOME (), Machine.Tape.Stay, 3)] + } + + val sorting : int Machine.machine = { + alphabet = Vector.fromList [1,2,3], + states = Vector.fromList [0,1,2,3,4,5], + start = 1, + final = 0, + tapes = Vector.fromList [createTape (map SOME [2, 1, 2, 2, 1, 1])], + transitions = makeTransitions [ + (1, SOME 1, SOME 1, Machine.Tape.Right, 1), + (1, SOME 2, SOME 3, Machine.Tape.Right, 2), + (1, NONE, NONE, Machine.Tape.Left, 5), + (2, SOME 1, SOME 1, Machine.Tape.Right, 2), + (2, SOME 2, SOME 2, Machine.Tape.Right, 2), + (2, NONE, NONE, Machine.Tape.Left, 3), + (3, SOME 1, SOME 2, Machine.Tape.Left, 3), + (3, SOME 2, SOME 2, Machine.Tape.Left, 3), + (3, SOME 3, SOME 2, Machine.Tape.Left, 5), + (4, SOME 1, SOME 1, Machine.Tape.Left, 4), + (4, SOME 2, SOME 2, Machine.Tape.Left, 4), + (4, SOME 3, SOME 1, Machine.Tape.Right, 1), + (5, SOME 1, SOME 1, Machine.Tape.Left, 5), + (5, NONE, NONE, Machine.Tape.Right, 0)] + } +end + +(** Invoke Simulations **) +local + open ExampleMachines + val unitToString = (fn () => "()") + fun simulate_unit machine optcount = print (simulate unitToString machine optcount ^ "\n") + fun simulate_int machine optcount = print (simulate Int.toString machine optcount ^ "\n") +in + val () = print "Simulate incrementer...\n\n" + val () = simulate_unit incrementer NONE + val () = print "\nSimulate Busy Beaver...\n\n" + val () = simulate_unit busybeaver NONE + val () = print "\nSimulate Sorting...\n\n" + val () = simulate_int sorting NONE +end diff --git a/Task/Universal-Turing-machine/Zkl/universal-turing-machine-1.zkl b/Task/Universal-Turing-machine/Zkl/universal-turing-machine-1.zkl new file mode 100644 index 0000000000..0294baa28e --- /dev/null +++ b/Task/Universal-Turing-machine/Zkl/universal-turing-machine-1.zkl @@ -0,0 +1,20 @@ +var [const] D=Dictionary; // short cut +// blank symbol and terminating state(s) are Void +var Lt=-1, Sy=0, Rt=1; // Left, Stay, Right + +fcn printTape(tape,pos){ + tape.keys.apply("toInt").sort() + .pump(String,'wrap(i){ ((pos==i) and "(%s)" or " %s ").fmt(tape[i]) }) + .println(); +} +fcn turing(state,[D]tape,[Int]pos,[D]rules,verbose=True,n=0){ + if(not state){ + print("%d steps. Length %d. Tape: ".fmt(n,tape.len())); + printTape(tape,Void); + return(tape); + } + r:=rules[state][tape[pos] = tape.find(pos)]; + if(verbose) printTape(tape,pos); + tape[pos]=r[0]; + return(self.fcn(r[2],tape,pos+r[1],rules,verbose,n+1)); +} diff --git a/Task/Universal-Turing-machine/Zkl/universal-turing-machine-2.zkl b/Task/Universal-Turing-machine/Zkl/universal-turing-machine-2.zkl new file mode 100644 index 0000000000..ad0b21ae0a --- /dev/null +++ b/Task/Universal-Turing-machine/Zkl/universal-turing-machine-2.zkl @@ -0,0 +1,25 @@ +println("Simple incrementer"); +turing("q0",D(0,Rt, 1,Rt, 2,Rt),0, // Incrementer + D("q0",D(1,T(1,Rt,"q0"), Void,T(1,Sy,Void)) ) ); + +println("\nThree-state busy beaver"); +turing("a",D(),0, // Three-state busy beaver + SD("a",D(Void,T(1,Rt,"b"), 1,T(1,Lt,"c")), + "b",D(Void,T(1,Lt,"a"), 1,T(1,Rt,"b")), + "c",D(Void,T(1,Lt,"b"), 1,T(1,Sy,Void)) ) ); + +println("\nSort"); +turing("A",D(T(2,2,2,1,2,2,1,2,1,2,1,2,1,2).enumerate()),0, + SD("A",D(1,T(1,Rt,"A"), 2,T(3,Rt,"B"), Void,T(Void,Lt,"E")), + "B",D(1,T(1,Rt,"B"), 2,T(2,Rt,"B"), Void,T(Void,Lt,"C")), + "C",D(1,T(2,Lt,"D"), 2,T(2,Lt,"C"), 3, T(2, Lt,"E")), + "D",D(1,T(1,Lt,"D"), 2,T(2,Lt,"D"), 3, T(1, Rt,"A")), + "E",D(1,T(1,Lt,"E"), Void,T(Void,Rt,Void)) ) ,False); + +println("\nFive-state busy beaver"); +turing("A",D(),0, + SD("A",D(Void,T(1,Rt,"B"), 1,T(1, Lt,"C")), + "B",D(Void,T(1,Rt,"C"), 1,T(1, Rt,"B")), + "C",D(Void,T(1,Rt,"D"), 1,T(Void,Lt,"E")), + "D",D(Void,T(1,Lt,"A"), 1,T(1, Lt,"D")), + "E",D(Void,T(1,Sy,Void), 1,T(Void,Lt,"A")) ) ,False); diff --git a/Task/Unix-ls/BaCon/unix-ls.bacon b/Task/Unix-ls/BaCon/unix-ls.bacon new file mode 100644 index 0000000000..fe224f2b13 --- /dev/null +++ b/Task/Unix-ls/BaCon/unix-ls.bacon @@ -0,0 +1,18 @@ +' Emulate ls +cnt% = 0 +files$ = "" +OPEN CURDIR$ FOR DIRECTORY AS mydir +GETFILE myfile$ FROM mydir +WHILE ISTRUE(LEN(myfile$)) + IF LEFT$(myfile$, 1) != "." THEN + INCR cnt% + files$ = APPEND$(files$, cnt%, UNFLATTEN$(myfile$)) + ENDIF + GETFILE myfile$ FROM mydir +WEND +CLOSE DIRECTORY mydir +IF cnt% > 0 THEN + FOR f$ IN SORT$(files$) + PRINT FLATTEN$(f$) + NEXT +ENDIF diff --git a/Task/Unix-ls/Gambas/unix-ls.gambas b/Task/Unix-ls/Gambas/unix-ls.gambas new file mode 100644 index 0000000000..5339bd739f --- /dev/null +++ b/Task/Unix-ls/Gambas/unix-ls.gambas @@ -0,0 +1,6 @@ +Public Sub Main() +Dim sDir As String[] = Dir(User.Home &/ "test").Sort() + +Print sDir.Join(gb.NewLine) + +End diff --git a/Task/Unix-ls/Java/unix-ls.java b/Task/Unix-ls/Java/unix-ls.java new file mode 100644 index 0000000000..8a69a80ab8 --- /dev/null +++ b/Task/Unix-ls/Java/unix-ls.java @@ -0,0 +1,22 @@ +package rosetta; + +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class UnixLS { + + public static void main(String[] args) throws IOException { + UnixLS ls = new UnixLS(); + ls.list(System.out); + } + + private void list(PrintStream out) throws IOException { + try (DirectoryStream stream = Files.newDirectoryStream(Paths.get("."))) { + stream.forEach((path) -> out.println(path.getFileName())); + } + } +} diff --git a/Task/Unix-ls/JavaScript/unix-ls.js b/Task/Unix-ls/JavaScript/unix-ls.js new file mode 100644 index 0000000000..79a83ec6c4 --- /dev/null +++ b/Task/Unix-ls/JavaScript/unix-ls.js @@ -0,0 +1,2 @@ +const fs = require('fs'); +fs.readdir('.', (err, names) => names.sort().map( name => console.log(name) )); diff --git a/Task/Unix-ls/Julia/unix-ls.julia b/Task/Unix-ls/Julia/unix-ls.julia new file mode 100644 index 0000000000..b2f553aa62 --- /dev/null +++ b/Task/Unix-ls/Julia/unix-ls.julia @@ -0,0 +1,9 @@ +# v0.6.0 + +for e in readdir() # Current directory + println(e) +end + +# Same for... +readdir("~") # Read home directory +readdir("~/documents") diff --git a/Task/Unix-ls/Phix/unix-ls.phix b/Task/Unix-ls/Phix/unix-ls.phix new file mode 100644 index 0000000000..39be2cf7b4 --- /dev/null +++ b/Task/Unix-ls/Phix/unix-ls.phix @@ -0,0 +1 @@ +pp(dir("."),{pp_Nest,1}) diff --git a/Task/Unix-ls/Stata/unix-ls.stata b/Task/Unix-ls/Stata/unix-ls.stata new file mode 100644 index 0000000000..dcc3aefa37 --- /dev/null +++ b/Task/Unix-ls/Stata/unix-ls.stata @@ -0,0 +1,4 @@ +. dir *.dta + 6.3k 6/12/17 14:26 auto.dta + 2.3k 8/10/17 7:34 titanium.dta + 6.0k 8/12/17 9:28 trend.dta diff --git a/Task/Unix-ls/Zkl/unix-ls-1.zkl b/Task/Unix-ls/Zkl/unix-ls-1.zkl new file mode 100644 index 0000000000..a87ce12617 --- /dev/null +++ b/Task/Unix-ls/Zkl/unix-ls-1.zkl @@ -0,0 +1 @@ +File.glob("*").sort() diff --git a/Task/Unix-ls/Zkl/unix-ls-2.zkl b/Task/Unix-ls/Zkl/unix-ls-2.zkl new file mode 100644 index 0000000000..500e982016 --- /dev/null +++ b/Task/Unix-ls/Zkl/unix-ls-2.zkl @@ -0,0 +1 @@ +File.glob("*",0x8).sort() diff --git a/Task/Unix-ls/Zkl/unix-ls-3.zkl b/Task/Unix-ls/Zkl/unix-ls-3.zkl new file mode 100644 index 0000000000..adf77a48e7 --- /dev/null +++ b/Task/Unix-ls/Zkl/unix-ls-3.zkl @@ -0,0 +1 @@ +File.globular("Src",*,True,0x10,List).sort().concat("\n") diff --git a/Task/Update-a-configuration-file/Phix/update-a-configuration-file.phix b/Task/Update-a-configuration-file/Phix/update-a-configuration-file.phix new file mode 100644 index 0000000000..e5bf5573ba --- /dev/null +++ b/Task/Update-a-configuration-file/Phix/update-a-configuration-file.phix @@ -0,0 +1,62 @@ +integer fn = open("RCTEST.INI","r") +sequence lines = get_text(fn,GT_LF_STRIPPED) +close(fn) +constant dini = new_dict() +for i=1 to length(lines) do + string li = trim(lines[i]) + if length(li) + and not find(li[1],"#;") then + integer k = find(' ',li) + if k!=0 then + string rest = li[k+1..$] + li = upper(li[1..k-1]) + putd(li,rest,dini) + else + putd(upper(li),1,dini) + end if + end if +end for + +deld("NEEDSPEELING",dini) +setd("SEEDSREMOVED",1,dini) +setd("NUMBEROFBANANAS",1024,dini) +setd("NUMBEROFSTRAWBERRIES",62000,dini) + +for i=1 to length(lines) do + string li = trim(lines[i]) + if length(li) + and li[1]!='#' then + if li[1]=';' then + li = trim(li[2..$]) + end if + integer k = find(' ',li) + if k!=0 then + string rest = li[k+1..$] + li = upper(li[1..k-1]) + k = getd_index(li,dini) + if k=0 then + lines[i] = "; "&li&" "&rest + else + object o = getd_by_index(k,dini) + if not string(o) then o = sprint(o) end if + lines[i] = li&" "&o + deld(li,dini) + end if + else + if getd(li,dini) then + lines[i] = li + deld(li,dini) + else + lines[i] = "; "&li + end if + end if + end if +end for +function visitor(object key, object data, object /*user_data*/) + lines = append(lines,key&" "&sprint(data)) + return 1 +end function +traverse_dict(routine_id("visitor"),0,dini) +fn = open("RCTEST.INI","w") +puts(fn,join(lines,"\n")) +close(fn) diff --git a/Task/Use-another-language-to-call-a-function/C++/use-another-language-to-call-a-function-1.cpp b/Task/Use-another-language-to-call-a-function/C++/use-another-language-to-call-a-function-1.cpp new file mode 100644 index 0000000000..0a4597b247 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/C++/use-another-language-to-call-a-function-1.cpp @@ -0,0 +1,17 @@ +#include +using std::string; + +// C++ functions with extern "C" can get called from C. +extern "C" int +Query (char *Data, size_t *Length) +{ + const string Message = "Here am I"; + + // Check that Message fits in Data. + if (*Length < Message.length()) + return false; // C++ converts bool to int. + + *Length = Message.length(); + Message.copy(Data, *Length); + return true; +} diff --git a/Task/Use-another-language-to-call-a-function/C++/use-another-language-to-call-a-function-2.cpp b/Task/Use-another-language-to-call-a-function/C++/use-another-language-to-call-a-function-2.cpp new file mode 100644 index 0000000000..692e27e987 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/C++/use-another-language-to-call-a-function-2.cpp @@ -0,0 +1,5 @@ +$ gcc -c main.c +$ g++ -c query.cpp +$ g++ -o main main.o query.o +$ ./main +Here am I diff --git a/Task/Use-another-language-to-call-a-function/Java/use-another-language-to-call-a-function-1.java b/Task/Use-another-language-to-call-a-function/Java/use-another-language-to-call-a-function-1.java new file mode 100644 index 0000000000..b5c2af4215 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Java/use-another-language-to-call-a-function-1.java @@ -0,0 +1,14 @@ +/* Query.java */ +public class Query { + public static boolean call(byte[] data, int[] length) + throws java.io.UnsupportedEncodingException + { + String message = "Here am I"; + byte[] mb = message.getBytes("utf-8"); + if (length[0] < mb.length) + return false; + length[0] = mb.length; + System.arraycopy(mb, 0, data, 0, mb.length); + return true; + } +} diff --git a/Task/Use-another-language-to-call-a-function/Java/use-another-language-to-call-a-function-2.java b/Task/Use-another-language-to-call-a-function/Java/use-another-language-to-call-a-function-2.java new file mode 100644 index 0000000000..cc75e3fb0e --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Java/use-another-language-to-call-a-function-2.java @@ -0,0 +1,105 @@ +/* query-jni.c */ +#include +#include +#include + +static JavaVM *jvm = NULL; +static JNIEnv *jenv = NULL; + +static void die(const char *message) { + fprintf(stderr, "%s\n", message); + exit(1); +} + +static void oom(void) { + die("Query: out of memory"); +} + +static void except(void) { + if ((*jenv)->ExceptionCheck(jenv)) + die("Query: unexpected Java exception"); +} + +static void do_at_exit(void) { + (*jvm)->DestroyJavaVM(jvm); +} + +static void require_jvm(void) { + JavaVMInitArgs args; + + if (jvm) + return; + + args.version = JNI_VERSION_1_4; + args.nOptions = 0; + args.options = NULL; + args.ignoreUnrecognized = JNI_FALSE; + if (JNI_CreateJavaVM(&jvm, (void **)&jenv, &args) != JNI_OK) + die("Query: can't create Java VM"); + atexit(do_at_exit); +} + +int Query(char *data, size_t *length) { + jclass cQuery; + jmethodID mcall; + jintArray jlength; + jint jlength0; + jbyteArray jdata; + jboolean result; + + jlength0 = (jint)length[0]; + if ((size_t)jlength0 != length[0]) + die("Query: length is too large for Java array"); + + require_jvm(); + + /* Create a local frame for references to Java objects. */ + if ((*jenv)->PushLocalFrame(jenv, 16)) + oom(); + + /* Look for class Query, static boolean call(byte[], int[]) */ + cQuery = (*jenv)->FindClass(jenv, "Query"); + if (cQuery == NULL) + die("Query: can't find Query.class"); + mcall = (*jenv)->GetStaticMethodID(jenv, cQuery, "call", "([B[I)Z"); + if (mcall == NULL) + die("Query: missing call() method"); + + /* + * Make arguments to Query.call(). We can't pass data[] and + * length[] to Java, so we make new Java arrays jdata[] and + * jlength[]. + */ + jdata = (*jenv)->NewByteArray(jenv, (jsize)jlength0); + if (jdata == NULL) + oom(); + jlength = (*jenv)->NewIntArray(jenv, 1); + if (jlength == NULL) + oom(); + + /* Set jlength[0] = length[0]. */ + (*jenv)->SetIntArrayRegion(jenv, jlength, 0, 1, &jlength0); + except(); + + /* + * Call our Java method. + */ + result = (*jenv)->CallStaticBooleanMethod + (jenv, cQuery, mcall, jdata, jlength); + except(); + + /* + * Set length[0] = jlength[0]. + * Copy length[0] bytes from jdata[] to data[]. + */ + (*jenv)->GetIntArrayRegion(jenv, jlength, 0, 1, &jlength0); + except(); + length[0] = (size_t)jlength0; + (*jenv)->GetByteArrayRegion + (jenv, jdata, 0, (jsize)jlength0, (jbyte *)data); + + /* Drop our local frame and its references. */ + (*jenv)->PopLocalFrame(jenv, NULL); + + return (int)result; +} diff --git a/Task/Use-another-language-to-call-a-function/Java/use-another-language-to-call-a-function-3.java b/Task/Use-another-language-to-call-a-function/Java/use-another-language-to-call-a-function-3.java new file mode 100644 index 0000000000..94c9f555b7 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Java/use-another-language-to-call-a-function-3.java @@ -0,0 +1,22 @@ +# Makefile + +# Edit these lines to match your JDK. +JAVA_HOME = /Library/Java/Home +CPPFLAGS = -I$(JAVA_HOME)/include +LIBS = -framework JavaVM +JAVAC = $(JAVA_HOME)/bin/javac +CC = cc + +all: calljava Query.class + +calljava: main.o query-jni.o + $(CC) -o calljava main.o query-jni.o $(LIBS) + +.SUFFIXES: .c .class .java .o +.c.o: + $(CC) $(CPPFLAGS) -c $< +.java.class: + $(JAVAC) $< + +clean: + rm -f calljava main.o query-jni.o Query.class diff --git a/Task/Use-another-language-to-call-a-function/Ruby/use-another-language-to-call-a-function-1.rb b/Task/Use-another-language-to-call-a-function/Ruby/use-another-language-to-call-a-function-1.rb new file mode 100644 index 0000000000..81b0a5fb32 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Ruby/use-another-language-to-call-a-function-1.rb @@ -0,0 +1,37 @@ +# query.rb +require 'fiddle' + +# Look for a C variable named QueryPointer. +# Raise an error if it is missing. +c_var = Fiddle.dlopen(nil)['QueryPointer'] + +int = Fiddle::TYPE_INT +voidp = Fiddle::TYPE_VOIDP +sz_voidp = Fiddle::SIZEOF_VOIDP + +# Implement the C function +# int Query(void *data, size_t *length) +# in Ruby code. Store it in a global constant in Ruby (named Query) +# to protect it from Ruby's garbage collector. +# +Query = Fiddle::Closure::BlockCaller + .new(int, [voidp, voidp]) do |datap, lengthp| + message = "Here am I" + + # We got datap and lengthp as Fiddle::Pointer objects. + # Read length, assuming sizeof(size_t) == sizeof(void *). + length = lengthp[0, sz_voidp].unpack('J').first + + # Does the message fit in length bytes? + if length < message.bytesize + 0 # failure + else + length = message.bytesize + datap[0, length] = message # Copy the message. + lengthp[0, sz_voidp] = [length].pack('J') # Update the length. + 1 # success + end +end + +# Set the C variable to our Query. +Fiddle::Pointer.new(c_var)[0, sz_voidp] = [Query.to_i].pack('J') diff --git a/Task/Use-another-language-to-call-a-function/Ruby/use-another-language-to-call-a-function-2.rb b/Task/Use-another-language-to-call-a-function/Ruby/use-another-language-to-call-a-function-2.rb new file mode 100644 index 0000000000..ff55e35edc --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Ruby/use-another-language-to-call-a-function-2.rb @@ -0,0 +1,81 @@ +/* query-rb.c */ +#include +#include + +/* + * QueryPointer() uses Ruby and may raise a Ruby error. Query() is a + * C wrapper around QueryPointer() that loads Ruby, sets QueryPointer, + * and protects against Ruby errors. + */ +int (*QueryPointer)(char *, size_t *) = NULL; + +static int in_bad_exit = 0; + +static void +do_at_exit(void) +{ + RUBY_INIT_STACK; + + if (!in_bad_exit) + ruby_cleanup(0); +} + +static void +bad_exit(int state) +{ + in_bad_exit = 1; + ruby_stop(state); /* Clean up Ruby and exit the process. */ +} + +static void +require_query(void) +{ + static int done = 0; + int state; + + if (done) + return; + done = 1; + + ruby_init(); + atexit(do_at_exit); + ruby_init_loadpath(); /* needed to require 'fiddle' */ + + /* Require query.rb in current directory. */ + rb_eval_string_protect("require_relative 'query'", &state); + if (!state && !QueryPointer) + rb_eval_string_protect("fail 'missing QueryPointer'", &state); + if (state) + bad_exit(state); /* Ruby will report the error. */ +} + +struct args { + char *data; + size_t *length; + int result; +}; + +static VALUE +Query1(VALUE v) { + struct args *a = (struct args *)v; + a->result = QueryPointer(a->data, a->length); + return Qnil; +} + +int +Query(char *data, size_t *length) +{ + struct args a; + int state; + RUBY_INIT_STACK; + + require_query(); + + /* Call QueryPointer(), protect against errors. */ + a.data = data; + a.length = length; + rb_protect(Query1, (VALUE)&a, &state); + if (state) + bad_exit(state); + return a.result; +} diff --git a/Task/Use-another-language-to-call-a-function/Ruby/use-another-language-to-call-a-function-3.rb b/Task/Use-another-language-to-call-a-function/Ruby/use-another-language-to-call-a-function-3.rb new file mode 100644 index 0000000000..1c408be7bd --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Ruby/use-another-language-to-call-a-function-3.rb @@ -0,0 +1,27 @@ +# Rakefile + +# To build and run: +# $ rake +# $ ./callruby + +# Must link with cc -Wl,-E so query.c exports QueryPointer. +CC = ENV.fetch('CC', 'cc') +LDFLAGS = '-Wl,-E' +CPPFLAGS = RbConfig.expand('-I$(rubyarchhdrdir) -I$(rubyhdrdir)') +LIBS = RbConfig.expand('$(LIBRUBYARG) $(LIBS)') + +task 'default' => 'callruby' + +desc 'compiles callruby' +file 'callruby' => %w[main.o query-rb.o] do |t| + sh "#{CC} #{LDFLAGS} -o #{t.name} #{t.sources.join(' ')} #{LIBS}" +end + +rule '.o' => %w[.c] do |t| + sh "#{CC} #{CPPFLAGS} -o #{t.name} -c #{t.source}" +end + +desc 'removes callruby and .o files' +task 'clean' do + rm_f %w[callruby main.o query-rb.o] +end diff --git a/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-1.txr b/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-1.txr new file mode 100644 index 0000000000..0b801efb4e --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-1.txr @@ -0,0 +1,17 @@ +#include + +int query(int (*callback)(char *, size_t *)) +{ + char buffer[1024]; + size_t size = sizeof buffer; + + if (callback(buffer, &size) == 0) { + puts("query: callback failed"); + } else { + char *ptr = buffer; + + while (size-- > 0) + putchar (*ptr++); + putchar('\n'); + } +} diff --git a/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-2.txr b/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-2.txr new file mode 100644 index 0000000000..dbf018c73a --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-2.txr @@ -0,0 +1,2 @@ +gcc -g -fPIC query.c -c +gcc -g --shared query.c -o query.c diff --git a/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-3.txr b/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-3.txr new file mode 100644 index 0000000000..6305d9307d --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-3.txr @@ -0,0 +1,14 @@ +(with-dyn-lib "./query.so" + (deffi query "query" void (closure))) + +(deffi-cb query-cb int ((carray char) (ptr (array 1 size-t)))) + +(query (query-cb (lambda (buf sizeptr) + (symacrolet ((size [sizeptr 0])) + (let* ((s "Here am I") + (l (length s))) + (cond + ((> l size) 0) + (t (carray-set-length buf size) + (carray-put buf s) + (set size l)))))))) diff --git a/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-4.txr b/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-4.txr new file mode 100644 index 0000000000..fe0d3858ea --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-4.txr @@ -0,0 +1,16 @@ +(with-dyn-lib "./query.so" + (deffi query "query" void (closure))) + +(with-dyn-lib nil + (deffi memcpy "memcpy" cptr (cptr str size-t))) + +(deffi-cb query-cb int (cptr (ptr (array 1 size-t)))) + +(query (query-cb (lambda (buf sizeptr) ; int lambda(void *buf, siz + (symacrolet ((size [sizeptr 0])) ; { #define size sizeptr[0] + (let* ((s "Here am I") ; char *s = "Here am I"; + (l (length s))) ; size_t l = strlen(s); + (cond ; if (length > size) + ((> l size) 0) ; { return 0; } else + (t (memcpy buf s l) ; { memcpy(buf, s, l); + (set size l)))))))) ; return size = l; } } diff --git a/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-5.txr b/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-5.txr new file mode 100644 index 0000000000..77089032ae --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/TXR/use-another-language-to-call-a-function-5.txr @@ -0,0 +1 @@ +(deffi-cb query-cb int (cptr (ptr (array 1 size-t))) -1) diff --git a/Task/Use-another-language-to-call-a-function/Zkl/use-another-language-to-call-a-function-1.zkl b/Task/Use-another-language-to-call-a-function/Zkl/use-another-language-to-call-a-function-1.zkl new file mode 100644 index 0000000000..5fecef9803 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Zkl/use-another-language-to-call-a-function-1.zkl @@ -0,0 +1,47 @@ +// query.c +// export zklRoot=/home/ZKL +// clang query.c -I $zklRoot/VM -L $zklRoot/Lib -lzkl -pthread -lncurses -o query +// LD_LIBRARY_PATH=$zklRoot/Lib ./query + +#include +#include + +#include "zklObject.h" +#include "zklImports.h" +#include "zklClass.h" +#include "zklFcn.h" +#include "zklString.h" + +int query(char *buf, size_t *sz) +{ + Instance *r; + pVM vm; + MLIST(mlist,10); + + // Bad practice: not protecting things from the garbage collector + + // build the call parameters: ("query.zkl",False,False,True) + mlistBuild(mlist,stringCreate("query.zkl",I_OWNED,NoVM), + BoolFalse,BoolFalse,BoolTrue,ZNIL); + // Import is in the Vault, a store of useful stuff + // We want to call TheVault.Import.import("query.zkl",False,False,True) + // which will load/compile/run query.zkl + r = fcnRunith("Import","import",(Instance *)mlist,NoVM); + // query.zkl is a class with a var that has the query result + r = classFindVar(r,"query",0,NoVM); // -->the var contents + strcpy(buf,stringText(r)); // decode the string into a char * + *sz = strlen(buf); // screw overflow checking + return 1; +} + +int main(int argc, char* argv[]) +{ + char buf[100]; + size_t sz = sizeof(buf); + + zklConstruct(argc,argv); // initialize the zkl shared library + query(buf,&sz); + printf("Query() --> \"%s\"\n",buf); + + return 0; +} diff --git a/Task/Use-another-language-to-call-a-function/Zkl/use-another-language-to-call-a-function-2.zkl b/Task/Use-another-language-to-call-a-function/Zkl/use-another-language-to-call-a-function-2.zkl new file mode 100644 index 0000000000..17587490c7 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Zkl/use-another-language-to-call-a-function-2.zkl @@ -0,0 +1,2 @@ +// query.zkl +var query="Here am I"; diff --git a/Task/User-input-Graphical/Gambas/user-input-graphical.gambas b/Task/User-input-Graphical/Gambas/user-input-graphical.gambas new file mode 100644 index 0000000000..fc79ba7b6b --- /dev/null +++ b/Task/User-input-Graphical/Gambas/user-input-graphical.gambas @@ -0,0 +1,36 @@ +hTextBox As TextBox +hValueBox As ValueBox +hLabel As Label + +Public Sub Form_Open() + +With Me + .Height = 100 + .Width = 300 + .padding = 5 + .Arrangement = Arrange.Vertical + .Title = "User input/Graphical" +End With + +hTextBox = New TextBox(Me) As "TextBox1" +hTextBox.Expand = True + +hValueBox = New ValueBox(Me) As "ValueBox1" +hValueBox.Expand = True + +hLabel = New Label(Me) +hLabel.expand = True + +End + +Public Sub TextBox1_Change() + +hLabel.text = hTextBox.Text & " - " & Str(hValueBox.value) + +End + +Public Sub valueBox1_Change() + +TextBox1_Change + +End diff --git a/Task/User-input-Graphical/Kotlin/user-input-graphical.kotlin b/Task/User-input-Graphical/Kotlin/user-input-graphical.kotlin new file mode 100644 index 0000000000..ba1b350c74 --- /dev/null +++ b/Task/User-input-Graphical/Kotlin/user-input-graphical.kotlin @@ -0,0 +1,9 @@ +// version 1.1 + +import javax.swing.JOptionPane + +fun main(args: Array) { + do { + val number = JOptionPane.showInputDialog("Enter 75000").toInt() + } while (number != 75000) +} diff --git a/Task/User-input-Graphical/Phix/user-input-graphical.phix b/Task/User-input-Graphical/Phix/user-input-graphical.phix index ea78a2c136..a3e5365eab 100644 --- a/Task/User-input-Graphical/Phix/user-input-graphical.phix +++ b/Task/User-input-Graphical/Phix/user-input-graphical.phix @@ -1,3 +1,6 @@ +-- +-- demo\rosetta\User_Input_Graphical.exw +-- include pGUI.e Ihandle dlg, label1, input1, label2, input2, OK, Cancel @@ -17,7 +20,7 @@ function esc_close(Ihandle /*ih*/, atom c) return iff(c=K_ESC?IUP_CLOSE:IUP_CONTINUE) end function -IupOpen("demo/pGUI/") +IupOpen() label1 = IupLabel("Please enter a string") input1 = IupText("VALUE=\"a string\", EXPAND=HORIZONTAL") label2 = IupLabel("and the number 75000") diff --git a/Task/User-input-Text/ALGOL-W/user-input-text.alg b/Task/User-input-Text/ALGOL-W/user-input-text.alg new file mode 100644 index 0000000000..c6a771d2ed --- /dev/null +++ b/Task/User-input-Text/ALGOL-W/user-input-text.alg @@ -0,0 +1,8 @@ +begin + string(80) s; + integer n; + write( "Enter a string > " ); + read( s ); + write( "Enter an integer> " ); + read( n ) +end. diff --git a/Task/User-input-Text/BASIC/user-input-text-3.basic b/Task/User-input-Text/BASIC/user-input-text-3.basic new file mode 100644 index 0000000000..ecfb50cc1c --- /dev/null +++ b/Task/User-input-Text/BASIC/user-input-text-3.basic @@ -0,0 +1,8 @@ +10 PRINT "ENTER A STRING" +20 INPUT S$ +30 PRINT "YOU ENTERED: ";S$ +40 PRINT "NOW ENTER THE NUMBER 75000" +50 INPUT N +60 IF N=75000 THEN STOP +70 PRINT "NO, "; +80 GOTO 40 diff --git a/Task/User-input-Text/Elena/user-input-text.elena b/Task/User-input-Text/Elena/user-input-text.elena index 6711fe7947..6e29d52ad6 100644 --- a/Task/User-input-Text/Elena/user-input-text.elena +++ b/Task/User-input-Text/Elena/user-input-text.elena @@ -1,8 +1,9 @@ -#import system. -#import extensions. +import extensions. -#symbol program = +program = [ - #var num := console write:"Enter an integer: " readLine:(Integer new). - #var word := console write:"Enter a String: " readLine. + var num := Integer new. + console write:"Enter an integer: "; readLine:num. + + var word := console write:"Enter a String: "; readLine. ]. diff --git a/Task/User-input-Text/Elixir/user-input-text.elixir b/Task/User-input-Text/Elixir/user-input-text.elixir index b36d48427e..1ccb1ba3b8 100644 --- a/Task/User-input-Text/Elixir/user-input-text.elixir +++ b/Task/User-input-Text/Elixir/user-input-text.elixir @@ -1,4 +1,6 @@ -a = IO.gets("Enter a string: ") |> String.strip -b = IO.gets("Enter an integer: ") |> String.strip |> String.to_integer() +a = IO.gets("Enter a string: ") |> String.strip +b = IO.gets("Enter an integer: ") |> String.strip |> String.to_integer +f = IO.gets("Enter a real number: ") |> String.strip |> String.to_float IO.puts "String = #{a}" IO.puts "Integer = #{b}" +IO.puts "Float = #{f}" diff --git a/Task/User-input-Text/jq/user-input-text-1.jq b/Task/User-input-Text/Jq/user-input-text-1.jq similarity index 100% rename from Task/User-input-Text/jq/user-input-text-1.jq rename to Task/User-input-Text/Jq/user-input-text-1.jq diff --git a/Task/User-input-Text/jq/user-input-text-2.jq b/Task/User-input-Text/Jq/user-input-text-2.jq similarity index 100% rename from Task/User-input-Text/jq/user-input-text-2.jq rename to Task/User-input-Text/Jq/user-input-text-2.jq diff --git a/Task/User-input-Text/Kotlin/user-input-text.kotlin b/Task/User-input-Text/Kotlin/user-input-text.kotlin new file mode 100644 index 0000000000..234656a2c5 --- /dev/null +++ b/Task/User-input-Text/Kotlin/user-input-text.kotlin @@ -0,0 +1,11 @@ +// version 1.1 + +fun main(args: Array) { + print("Enter a string : ") + val s = readLine()!! + println(s) + do { + print("Enter 75000 : ") + val number = readLine()!!.toInt() + } while (number != 75000) +} diff --git a/Task/User-input-Text/MIRC-Scripting-Language/user-input-text.mirc b/Task/User-input-Text/MIRC-Scripting-Language/user-input-text.mirc new file mode 100644 index 0000000000..c2fb2fe103 --- /dev/null +++ b/Task/User-input-Text/MIRC-Scripting-Language/user-input-text.mirc @@ -0,0 +1,3 @@ +alias askmesomething { + echo -a You answered: $input(What's your name?, e) +} diff --git a/Task/User-input-Text/NewLISP/user-input-text.newlisp b/Task/User-input-Text/NewLISP/user-input-text.newlisp new file mode 100644 index 0000000000..7dba6d4ad1 --- /dev/null +++ b/Task/User-input-Text/NewLISP/user-input-text.newlisp @@ -0,0 +1,4 @@ +(print "Enter an integer: ") +(set 'x (read-line)) +(print "Enter a string: ") +(set 'y (read-line)) diff --git a/Task/User-input-Text/Ruby/user-input-text.rb b/Task/User-input-Text/Ruby/user-input-text.rb index af62ca7b47..3624800f5a 100644 --- a/Task/User-input-Text/Ruby/user-input-text.rb +++ b/Task/User-input-Text/Ruby/user-input-text.rb @@ -1,6 +1,9 @@ print "Enter a string: " s = gets -print "Enter an integer: " +printf "Enter an integer: " i = gets.to_i # If string entered, will return zero +printf "Enter a real number: " +f = Float(gets) rescue nil # converts a floating point number or returns nil puts "String = #{s}" puts "Integer = #{i}" +puts "Float = #{f}" diff --git a/Task/User-input-Text/SPL/user-input-text.spl b/Task/User-input-Text/SPL/user-input-text.spl new file mode 100644 index 0000000000..45fd8729cc --- /dev/null +++ b/Task/User-input-Text/SPL/user-input-text.spl @@ -0,0 +1,2 @@ +text = #.input("Input a string") +number = #.val(#.input("Input a number")) diff --git a/Task/User-input-Text/Smart-BASIC/user-input-text.smart b/Task/User-input-Text/Smart-BASIC/user-input-text.smart new file mode 100644 index 0000000000..854a894e18 --- /dev/null +++ b/Task/User-input-Text/Smart-BASIC/user-input-text.smart @@ -0,0 +1,2 @@ +INPUT "Enter a string.":a$ +INPUT "Enter the value 75000.":n diff --git a/Task/User-input-Text/UNIX-Shell/user-input-text.sh b/Task/User-input-Text/UNIX-Shell/user-input-text.sh index 8960b2da15..d237aa97da 100644 --- a/Task/User-input-Text/UNIX-Shell/user-input-text.sh +++ b/Task/User-input-Text/UNIX-Shell/user-input-text.sh @@ -1,4 +1,6 @@ #!/bin/sh -read STRING -read INTEGER +read string +read integer +read -p 'Enter a number: ' number +echo "The number is $number" diff --git a/Task/User-input-Text/XLISP/user-input-text.xlisp b/Task/User-input-Text/XLISP/user-input-text.xlisp new file mode 100644 index 0000000000..cfebda495c --- /dev/null +++ b/Task/User-input-Text/XLISP/user-input-text.xlisp @@ -0,0 +1,16 @@ +(display "Enter a string: ") +(define s (read-line)) +(display "Yes, ") +(write s) +(display " is a string.") ;; no need to verify, because READ-LINE has to return a string +(newline) +(display "Now enter the integer 75000: ") +(define n (read)) +(display + (cond + ((not (integerp n)) + "That's not even an integer." ) + ((/= n 75000) + "That is not the integer 75000." ) + (t + "Yes, that is the integer 75000." ) ) ) diff --git a/Task/User-input-Text/Zkl/user-input-text.zkl b/Task/User-input-Text/Zkl/user-input-text.zkl new file mode 100644 index 0000000000..696cd9db06 --- /dev/null +++ b/Task/User-input-Text/Zkl/user-input-text.zkl @@ -0,0 +1,2 @@ +str:=ask("Gimmie a string: "); +n:=ask("Type 75000: ").toInt(); diff --git a/Task/Vampire-number/Haskell/vampire-number.hs b/Task/Vampire-number/Haskell/vampire-number.hs index b88b285bb8..a9f5f2b7a7 100644 --- a/Task/Vampire-number/Haskell/vampire-number.hs +++ b/Task/Vampire-number/Haskell/vampire-number.hs @@ -1,41 +1,49 @@ import Data.List (sort) +import Control.Arrow ((&&&)) -primes = 2:filter isPrime [3,5..] where - isPrime n = f n primes where - f n (p:ps) - | p*p > n = True - | n`mod`p == 0 = False - | otherwise = f n ps - -primeFactors n = f n primes where - f n (p:ps) - | p*p > n = if n == 1 then [] else [(n,1)] - | n`mod`p == 0 = (p,e):f res ps - | otherwise = f n ps - where (e,res) = ppower (n`div`p) p 1 - ppower n p e - | n`mod`p /= 0 = (e,n) - | otherwise = ppower (n`div`p) p (e+1) - -factors n = comb (primeFactors n) where - comb [] = [1] - comb ((p,e):others) = [a*b | b<-map (p^) [0 .. e], a<-comb others] - -ndigit 0 = 0 -ndigit n = 1 + ndigit (n`div`10) +-- VAMPIRE NUMBERS ------------------------------------------------------------ +vampires :: [Int] +vampires = filter ((0 <) . length . fangs) [1 ..] +fangs :: Int -> [(Int, Int)] fangs n - | odd w = [] - | otherwise = map (\x->(x,n`div`x)) $ filter isfang (factors n) where - isfang x = x > xmin && x < y && y < ymax && -- same length - ((x`div`10)/=0 || (y`div`10)/=0) && -- not zero-ended - sort (show n) == sort ((show x) ++ (show y)) -- same digits - where y = n`div`x - w = ndigit n - xmin = 10^(w`div`2-1) - ymax = 10^(w`div`2) + | odd w = [] + | otherwise = ((,) <*> quot n) <$> filter isfang (integerFactors n) + where + ndigit :: Int -> Int + ndigit 0 = 0 + ndigit n = 1 + ndigit (quot n 10) + w = ndigit n + xmin = 10 ^ (quot w 2 - 1) + xmax = xmin * 10 + isfang x = + x > xmin && + x < y && + y < xmax && -- same length + (quot x 10 /= 0 || quot y 10 /= 0) && -- not zero-ended + sort (show n) == sort (show x ++ show y) + where + y = quot n x -vampires = filter ((0<).length.fangs) [1..] +-- FACTORS -------------------------------------------------------------------- +integerFactors :: Int -> [Int] +integerFactors n + | n < 1 = [] + | otherwise = + lows ++ + (quot n <$> + (if intSquared == n -- A perfect square, + then tail -- and cofactor of square root would be redundant. + else id) + (reverse lows)) + where + (intSquared, lows) = + (^ 2) &&& (filter ((0 ==) . rem n) . enumFromTo 1) $ + floor (sqrt $ fromIntegral n) -main = mapM (\n->print (n,fangs n)) $ - ((take 25 vampires) ++ [16758243290880, 24959017348650, 14593825548650]) +-- TEST ----------------------------------------------------------------------- +main :: IO [()] +main = + mapM + (print . ((,) <*>) fangs) + (take 25 vampires ++ [16758243290880, 24959017348650, 14593825548650]) diff --git a/Task/Vampire-number/Kotlin/vampire-number.kotlin b/Task/Vampire-number/Kotlin/vampire-number.kotlin new file mode 100644 index 0000000000..06278b25ad --- /dev/null +++ b/Task/Vampire-number/Kotlin/vampire-number.kotlin @@ -0,0 +1,96 @@ +// version 1.1 + +data class Fangs(val fang1: Long = 0L, val fang2: Long = 0L) + +fun pow10(n: Int): Long = when { + n < 0 -> throw IllegalArgumentException("Can't be negative") + else -> { + var pow = 1L + for (i in 1..n) pow *= 10L + pow + } +} + +fun countDigits(n: Long): Int = when { + n < 0L -> throw IllegalArgumentException("Can't be negative") + n == 0L -> 1 + else -> { + var count = 0 + var nn = n + while (nn > 0L) { + count++ + nn /= 10L + } + count + } +} + +fun hasTrailingZero(n: Long): Boolean = when { + n < 0L -> throw IllegalArgumentException("Can't be negative") + else -> n % 10L == 0L +} + +fun sortedString(s: String): String { + val ca = s.toCharArray() + ca.sort() + return String(ca) +} + +fun isVampiric(n: Long, fl: MutableList): Boolean { + if (n < 0L) return false + val len = countDigits(n) + if (len % 2L == 1L) return false + val hlen = len / 2 + val first = pow10(hlen - 1) + val last = 10L * first + var j: Long + var cd: Int + val ss = sortedString(n.toString()) + for (i in first until last) { + if (n % i != 0L) continue + j = n / i + if (j < i) return fl.size > 0 + cd = countDigits(j) + if (cd > hlen) continue + if (cd < hlen) return fl.size > 0 + if (ss != sortedString(i.toString() + j.toString())) continue + if (!(hasTrailingZero(i) && hasTrailingZero(j))) { + fl.add(Fangs(i, j)) + } + } + return fl.size > 0 +} + +fun showFangs(fangsList: MutableList): String { + var s = "" + for ((fang1, fang2) in fangsList) { + s += " = $fang1 x $fang2" + } + return s +} + +fun main(args: Array) { + println("The first 25 vampire numbers and their fangs are:") + var count = 0 + var n: Long = 0 + val fl = mutableListOf() + while (true) { + if (isVampiric(n, fl)) { + count++ + println("${"%2d".format(count)} : $n\t${showFangs(fl)}") + fl.clear() + if (count == 25) break + } + n++ + } + println() + val va = longArrayOf(16758243290880L, 24959017348650L, 14593825548650L) + for (v in va) { + if (isVampiric(v, fl)) { + println("$v\t${showFangs(fl)}") + fl.clear() + } else { + println("$v\t = not vampiric") + } + } +} diff --git a/Task/Vampire-number/PureBasic/vampire-number.purebasic b/Task/Vampire-number/PureBasic/vampire-number.purebasic new file mode 100644 index 0000000000..1f601a7847 --- /dev/null +++ b/Task/Vampire-number/PureBasic/vampire-number.purebasic @@ -0,0 +1,62 @@ +EnableExplicit +DisableDebugger + +Macro CheckVamp(CheckNum) + c=0 : i=CheckNum : Print(~"\nCheck number: "+Str(i)+~"\n") + Gosub VampireLoop : If c=0 : Print(Str(i)+" is not vampiric.") : EndIf : PrintN("") +EndMacro + +Procedure.i Factor(number.i,counter.i) + If number>0 And number>=counter*counter And number%counter=0 + ProcedureReturn counter + EndIf + ProcedureReturn 0 +EndProcedure + +Procedure.b IsVampire(f1.i,f2.i) + Define a.s=Str(f1*f2), + b.s=Str(f1), + c.s=Str(f2), + d.s=b+c, + i.i + If Len(a)=Len(d) And Len(b)=Len(c) + While Len(a) + i=FindString(d,Left(a,1)) + If i + a=Mid(a,2) + d=RemoveString(d,Mid(d,i,1),#PB_String_NoCase,i,1) + Else + ProcedureReturn #False + EndIf + Wend + ProcedureReturn Bool(Len(d)=0) + EndIf + ProcedureReturn #False +EndProcedure + +OpenConsole("Vampire number") +Define i.i, + j.i, + m.i, + c.i=0 + +PrintN("The first 25 Vampire numbers...") +While c<25 : i+1 : Gosub VampireLoop : Wend +PrintN("") +CheckVamp(16758243290880) : CheckVamp(24959017348650) : CheckVamp(14593825548650) +Input() +End + +VampireLoop: + For j=1 To Int(Sqr(i)) + If Factor(i,j)>0 + m=i/j + Else + Continue + EndIf + If IsVampire(m,j) + c+1 + PrintN(RSet(Str(c),3," ")+". "+RSet(Str(i),10," ")+": ["+Str(j)+", "+Str(m)+"]") + EndIf + Next +Return diff --git a/Task/Vampire-number/REXX/vampire-number.rexx b/Task/Vampire-number/REXX/vampire-number.rexx index 02589cab34..0fc1125f9e 100644 --- a/Task/Vampire-number/REXX/vampire-number.rexx +++ b/Task/Vampire-number/REXX/vampire-number.rexx @@ -1,46 +1,42 @@ -/*REXX pgm displays N vampire numbers, or verifies if a # is vampiric.*/ -numeric digits 20 /*be able to handle large numbers*/ -parse arg N .; if N=='' then N=25 /*No arg? Then use the default. */ -!.0=1260; !.1=11453481; !.2=115672; !.3=124483; !.4=105264 /*lowest#,dig*/ -!.5=1395; !.6=126846; !.7=1827; !.8=110758; !.9=156289 /*lowest#,dig*/ -#=0 /*number of vampire numbers found*/ -if N>0 then do j=1260 until # >= N /*search until N vampire #s found*/ - if length(j)//2 then do; j=j*10-1; iterate; end /*adjust J*/ - _=right(j,1) /*obtain the right-most J digit.*/ - if j0 then do j=1260 until # >= N /*search until N vampire numbers found.*/ + if length(j) // 2 then do; j=j*10 - 1; iterate; end /*adjust J*/ + _=right(J,1); if jq then iterate - if q*d//9\==(q+d)//9 then iterate /*modulo 9 congruence.*/ - if verify(q,?)\==0 then iterate - if right(q,1)==0 then if right(d,1)==0 then iterate - if length(q)\==w then iterate - dq=d || q; t=? - do i=1 for L; p=pos(substr(dq,i,1), t) - if p==0 then iterate d; t=delstr(t,p,1) - end /*i*/ - !!=!! '['d"∙"q']' - end /*d*/ -return !! +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +vampire: procedure; parse arg ?,, $. !! bot; L=length(?); if L//2 then return !! + w=L%2 /* [↑] L an odd length? Then ¬vampire*/ + do k=1 for L; _=substr(?,k,1); $._=$._ || _; end /*k*/ + do m=0 for 10; bot=bot || $.m; end /*m*/ + top=left( reverse(bot), w); bot=left(bot, w) /*determine limits of search*/ + inc=?//2 + 1 /*? is odd? INC=2. No? INC=1*/ + start=max(bot, 10**(w-1)); if inc=2 then if start//2==0 then start=start+1 + /* [↑] odd START if odd INC*/ + do d=start to min(top, 10**w-1) by inc + if ?//d\==0 then iterate + if verify(d, ?) \==0 then iterate + q=?%d; if d>q then iterate + if q*d//9\==(q+d)//9 then iterate /*modulo 9 congruence test. */ + if verify(q, ?) \==0 then iterate + if right(q, 1) ==0 then if right(d, 1)==0 then iterate + if length(q)\==w then iterate + dq=d || q; t=? + do i=1 for L; p=pos( substr(dq, i, 1), t) + if p==0 then iterate d; t=delstr(t, p, 1) + end /*i*/ + !!=!! '['d"∙"q']' + end /*d*/ + return !! diff --git a/Task/Vampire-number/Zkl/vampire-number-1.zkl b/Task/Vampire-number/Zkl/vampire-number-1.zkl new file mode 100644 index 0000000000..7d4f1bf4eb --- /dev/null +++ b/Task/Vampire-number/Zkl/vampire-number-1.zkl @@ -0,0 +1,13 @@ +fcn fangs(N){ //-->if Vampire number: (N,(a,b,c,...)), where a*x==N + var [const] tens=[0 .. 18].pump(List,(10.0).pow,"toInt"); + + (half:=N.numDigits) : if (_.isOdd) return(T);; + half/=2; digits:=N.toString().sort(); + lo:=tens[half-1].max((N+tens[half])/(tens[half])); + hi:=(N/lo).min(N.toFloat().sqrt()); + fs:=[lo .. hi].filter('wrap(n){ + N%n==0 and (n%10!=0 or (N/n)%10!=0) and + (n.toString()+(N/n).toString()).sort()==digits + }); + fs and T(N,fs) or T; +} diff --git a/Task/Vampire-number/Zkl/vampire-number-2.zkl b/Task/Vampire-number/Zkl/vampire-number-2.zkl new file mode 100644 index 0000000000..ce4adb5c6d --- /dev/null +++ b/Task/Vampire-number/Zkl/vampire-number-2.zkl @@ -0,0 +1,9 @@ +fcn vampiric(fangs,n=Void){ + if(not fangs) return(n,"Not a Vampire number"); + v:=fangs[0]; T(v,fangs[1].apply('wrap(n){T(n,v/n)})) } + +T(16758243290880, 24959017348650, 14593825548650) +.pump(Console.println,fcn(n){"%d: %s".fmt(vampiric(fangs(n),n).xplode())}); + +(0).walker(*).tweak(fangs).filter(26) +.pump(Console.println,vampiric); diff --git a/Task/Van-der-Corput-sequence/360-Assembly/van-der-corput-sequence.360 b/Task/Van-der-Corput-sequence/360-Assembly/van-der-corput-sequence.360 new file mode 100644 index 0000000000..b745515796 --- /dev/null +++ b/Task/Van-der-Corput-sequence/360-Assembly/van-der-corput-sequence.360 @@ -0,0 +1,58 @@ +* Van der Corput sequence 31/01/2017 +VDCS CSECT + USING VDCS,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) prolog + ST R13,4(R15) " <- + ST R15,8(R13) " -> + LR R13,R15 " addressability + ZAP B,=P'2' b=2 (base) + ZAP M,=P'-1' m=-1 + SR R6,R6 i=0 +LOOPI CH R6,=H'10' do i=0 to 10 + BH ELOOPI + AP M,=P'1' w=m+1 + ZAP V,=P'0' v=0 + ZAP S,=P'1' s=1 + ZAP N,M n=m +WHILE CP N,=P'0' do while n<>0 + BE EWHILE + MP S,B s=s*b + ZAP PL16,N n + DP PL16,B n/b + ZAP W,PL16+8(8) w=n mod b + MP W,=P'100000' *100000 + ZAP PL16,W w + DP PL16,S w/s + ZAP W,PL16(8) w=w/s + AP V,W v=v+(n mod b)*100000/s + ZAP PL16,N n + DP PL16,B n/b + ZAP N,PL16(8) n=n/b + B WHILE +EWHILE XDECO R6,XDEC edit i + MVC PG+0(3),XDEC+9 output i + MVC PG+3(3),=C' 0.' + UNPK Z,V unpack v + OI Z+L'Z-1,X'F0' edit v + MVC PG+6(5),Z+11 output v (v/100000) + XPRNT PG,L'PG print buffer + LA R6,1(R6) i=i+1 + B LOOPI +ELOOPI L R13,4(0,R13) epilog + LM R14,R12,12(R13) " restore + XR R15,R15 " rc=0 + BR R14 exit +B DS PL8 +M DS PL8 +V DS PL8 +S DS PL8 +N DS PL8 +W DS PL8 packed +Z DS ZL16 zoned +PL16 DS PL16 packed max +PG DC CL80' ' buffer +XDEC DS CL12 work area for xdeco + YREGS + END VDCS diff --git a/Task/Van-der-Corput-sequence/Bc/van-der-corput-sequence.bc b/Task/Van-der-Corput-sequence/Bc/van-der-corput-sequence.bc new file mode 100644 index 0000000000..dcecc194e8 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Bc/van-der-corput-sequence.bc @@ -0,0 +1,39 @@ +/* + * Return the _n_th term of the van der Corput sequence. + * Uses the current _ibase_. + */ +define v(n) { + auto c, r, s + + s = scale + scale = 0 /* to use integer division */ + + /* + * c = count digits of n + * r = reverse the digits of n + */ + for (0; n != 0; n /= 10) { + c += 1 + r = (10 * r) + (n % 10) + } + + /* move radix point to left of digits */ + scale = length(r) + 6 + r /= 10 ^ c + + scale = s + return r +} + +t = 10 +for (b = 2; b <= 4; b++) { + "base "; b + obase = b + for (i = 0; i < 10; i++) { + ibase = b + " "; v(i) + ibase = t + } + obase = t +} +quit diff --git a/Task/Van-der-Corput-sequence/C/van-der-corput-sequence-1.c b/Task/Van-der-Corput-sequence/C/van-der-corput-sequence-1.c deleted file mode 100644 index 4281b56813..0000000000 --- a/Task/Van-der-Corput-sequence/C/van-der-corput-sequence-1.c +++ /dev/null @@ -1,35 +0,0 @@ -#include - -void vc(int n, int base, int *num, int *denom) -{ - int p = 0, q = 1; - - while (n) { - p = p * base + (n % base); - q *= base; - n /= base; - } - - *num = p; - *denom = q; - - while (p) { n = p; p = q % p; q = n; } - *num /= q; - *denom /= q; -} - -int main() -{ - int d, n, i, b; - for (b = 2; b < 6; b++) { - printf("base %d:", b); - for (i = 0; i < 10; i++) { - vc(i, b, &n, &d); - if (n) printf(" %d/%d", n, d); - else printf(" 0"); - } - printf("\n"); - } - - return 0; -} diff --git a/Task/Van-der-Corput-sequence/C/van-der-corput-sequence-2.c b/Task/Van-der-Corput-sequence/C/van-der-corput-sequence-2.c deleted file mode 100644 index 7911ed15f4..0000000000 --- a/Task/Van-der-Corput-sequence/C/van-der-corput-sequence-2.c +++ /dev/null @@ -1,4 +0,0 @@ -base 2: 0 1/2 1/4 3/4 1/8 5/8 3/8 7/8 1/16 9/16 -base 3: 0 1/3 2/3 1/9 4/9 7/9 2/9 5/9 8/9 1/27 -base 4: 0 1/4 1/2 3/4 1/16 5/16 9/16 13/16 1/8 3/8 -base 5: 0 1/5 2/5 3/5 4/5 1/25 6/25 11/25 16/25 21/25 diff --git a/Task/Van-der-Corput-sequence/Clojure/van-der-corput-sequence-1.clj b/Task/Van-der-Corput-sequence/Clojure/van-der-corput-sequence-1.clj deleted file mode 100644 index bb00e96510..0000000000 --- a/Task/Van-der-Corput-sequence/Clojure/van-der-corput-sequence-1.clj +++ /dev/null @@ -1,25 +0,0 @@ -(defn van-der-corput - "Get the nth element of the van der Corput sequence." - ([n] - ;; Default base = 2 - (van-der-corput n 2)) - ([n base] - (let [s (/ 1 base)] ;; A multiplicand to shift to the right of the decimal. - ;; We essentially want to reverse the digits of n and put them after the - ;; decimal point. So, we repeatedly pull off the lowest digit of n, scale - ;; it to the right of the decimal point, and accumulate that. - (loop [sum 0 - n n - scale s] - (if (zero? n) - sum ;; Base case: no digits left, so we're done. - (recur (+ sum (* (rem n base) scale)) ;; Accumulate the least digit - (quot n base) ;; Drop a digit of n - (* scale s))))))) ;; Move farther past the decimal - -(clojure.pprint/print-table - (cons :base (range 10)) ;; column headings - (for [base (range 2 6)] ;; rows - (into {:base base} - (for [n (range 10)] ;; table entries - [n (van-der-corput n base)])))) diff --git a/Task/Van-der-Corput-sequence/Clojure/van-der-corput-sequence-2.clj b/Task/Van-der-Corput-sequence/Clojure/van-der-corput-sequence-2.clj deleted file mode 100644 index 5663c98b59..0000000000 --- a/Task/Van-der-Corput-sequence/Clojure/van-der-corput-sequence-2.clj +++ /dev/null @@ -1,6 +0,0 @@ -| :base | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -|-------+---+-----+-----+-----+------+------+------+-------+-------+-------| -| 2 | 0 | 1/2 | 1/4 | 3/4 | 1/8 | 5/8 | 3/8 | 7/8 | 1/16 | 9/16 | -| 3 | 0 | 1/3 | 2/3 | 1/9 | 4/9 | 7/9 | 2/9 | 5/9 | 8/9 | 1/27 | -| 4 | 0 | 1/4 | 1/2 | 3/4 | 1/16 | 5/16 | 9/16 | 13/16 | 1/8 | 3/8 | -| 5 | 0 | 1/5 | 2/5 | 3/5 | 4/5 | 1/25 | 6/25 | 11/25 | 16/25 | 21/25 | diff --git a/Task/Van-der-Corput-sequence/Common-Lisp/van-der-corput-sequence-1.lisp b/Task/Van-der-Corput-sequence/Common-Lisp/van-der-corput-sequence-1.lisp deleted file mode 100644 index ae1a6f5a5c..0000000000 --- a/Task/Van-der-Corput-sequence/Common-Lisp/van-der-corput-sequence-1.lisp +++ /dev/null @@ -1,11 +0,0 @@ -(defun van-der-Corput (n base) - (loop for d = 1 then (* d base) while (<= d n) - finally - (return (/ (parse-integer - (reverse (write-to-string n :base base)) - :radix base) - d)))) - -(loop for base from 2 to 5 do - (format t "Base ~a: ~{~6a~^~}~%" base - (loop for i to 10 collect (van-der-Corput i base)))) diff --git a/Task/Van-der-Corput-sequence/Common-Lisp/van-der-corput-sequence-2.lisp b/Task/Van-der-Corput-sequence/Common-Lisp/van-der-corput-sequence-2.lisp deleted file mode 100644 index 0c3a4c0974..0000000000 --- a/Task/Van-der-Corput-sequence/Common-Lisp/van-der-corput-sequence-2.lisp +++ /dev/null @@ -1,4 +0,0 @@ -Base 2: 0 1/2 1/4 3/4 1/8 5/8 3/8 7/8 1/16 9/16 5/16 -Base 3: 0 1/3 2/3 1/9 4/9 7/9 2/9 5/9 8/9 1/27 10/27 -Base 4: 0 1/4 1/2 3/4 1/16 5/16 9/16 13/16 1/8 3/8 5/8 -Base 5: 0 1/5 2/5 3/5 4/5 1/25 6/25 11/25 16/25 21/25 2/25 diff --git a/Task/Van-der-Corput-sequence/Fortran/van-der-corput-sequence.f b/Task/Van-der-Corput-sequence/Fortran/van-der-corput-sequence.f new file mode 100644 index 0000000000..2b535922f0 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Fortran/van-der-corput-sequence.f @@ -0,0 +1,35 @@ + FUNCTION VDC(N,BASE) !Calculates a Van der Corput number... +Converts 1234 in decimal to 4321 in V, and P = 10000. + INTEGER N !For this integer, + INTEGER BASE !In this base. + INTEGER I !A copy of N that can be damaged. + INTEGER P !Successive powers of BASE. + INTEGER V !Accumulates digits. + P = 1 ! = BASE**0 + V = 0 !Start with no digits, as if N = 0. + I = N !Here we go. + DO WHILE (I .NE. 0) !While something remains, + V = V*BASE + MOD(I,BASE) !Extract its low-order digit. + I = I/BASE !Reduce it by a power. + P = P*BASE !And track the power. + END DO !Thus extract the digits in reverse order: right-to-left. + VDC = V/FLOAT(P) !The power is one above the highest digit. + END FUNCTION VDC !Numerology is weird. + + PROGRAM POKE + INTEGER FIRST,LAST !Might as well document some constants. + PARAMETER (FIRST = 0,LAST = 9) !Thus, the first ten values. + INTEGER I,BASE !Steppers. + REAL VDC !Stop the compiler moaning about undeclared items. + + WRITE (6,1) FIRST,LAST,(I, I = FIRST,LAST) !Announce. + 1 FORMAT ("Calculates values ",I0," to ",I0," of the ", + 1 "Van der Corput sequence, in various bases."/ + 2 "Base",666I9) + + DO BASE = 2,13 !A selection of bases. + WRITE (6,2) BASE,(VDC(I,BASE), I = FIRST,LAST) !Show the specified span. + 2 FORMAT (I4,666F9.6) !Aligns with FORMAT 1. + END DO !On to the next base. + + END diff --git a/Task/Van-der-Corput-sequence/jq/van-der-corput-sequence-1.jq b/Task/Van-der-Corput-sequence/Jq/van-der-corput-sequence-1.jq similarity index 100% rename from Task/Van-der-Corput-sequence/jq/van-der-corput-sequence-1.jq rename to Task/Van-der-Corput-sequence/Jq/van-der-corput-sequence-1.jq diff --git a/Task/Van-der-Corput-sequence/jq/van-der-corput-sequence-2.jq b/Task/Van-der-Corput-sequence/Jq/van-der-corput-sequence-2.jq similarity index 100% rename from Task/Van-der-Corput-sequence/jq/van-der-corput-sequence-2.jq rename to Task/Van-der-Corput-sequence/Jq/van-der-corput-sequence-2.jq diff --git a/Task/Van-der-Corput-sequence/jq/van-der-corput-sequence-3.jq b/Task/Van-der-Corput-sequence/Jq/van-der-corput-sequence-3.jq similarity index 100% rename from Task/Van-der-Corput-sequence/jq/van-der-corput-sequence-3.jq rename to Task/Van-der-Corput-sequence/Jq/van-der-corput-sequence-3.jq 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.kotlin new file mode 100644 index 0000000000..c6cd4b7f57 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Kotlin/van-der-corput-sequence.kotlin @@ -0,0 +1,34 @@ +// version 1.1.2 + +data class Rational(val num: Int, val denom: Int) + +fun vdc(n: Int, base: Int): Rational { + var p = 0 + var q = 1 + var nn = n + while (nn != 0) { + p = p * base + nn % base + q *= base + nn /= base + } + val num = p + val denom = q + while (p != 0) { + nn = p + p = q % p + q = nn + } + return Rational(num / q, denom / q) +} + +fun main(args: Array) { + for (b in 2..5) { + print("base $b:") + for (i in 0..9) { + val(num, denom) = vdc(i, b) + if (num != 0) print(" $num/$denom") + else print(" 0") + } + println() + } +} diff --git a/Task/Van-der-Corput-sequence/PureBasic/van-der-corput-sequence.purebasic b/Task/Van-der-Corput-sequence/PureBasic/van-der-corput-sequence.purebasic new file mode 100644 index 0000000000..126cceac37 --- /dev/null +++ b/Task/Van-der-Corput-sequence/PureBasic/van-der-corput-sequence.purebasic @@ -0,0 +1,20 @@ +Procedure.d nBase(n.i,b.i) + Define r.d,s.i=1 + While n + s*b + r+(Mod(n,b)/s) + n=Int(n/b) + Wend + ProcedureReturn r +EndProcedure + +Define.i b,c +OpenConsole("van der Corput - Sequence") +For b=2 To 5 + Print("Base "+Str(b)+": ") + For c=0 To 9 + Print(StrD(nBase(c,b),5)+~"\t") + Next + PrintN("") +Next +Input() diff --git a/Task/Van-der-Corput-sequence/Ruby/van-der-corput-sequence-1.rb b/Task/Van-der-Corput-sequence/Ruby/van-der-corput-sequence-1.rb deleted file mode 100644 index ab99246947..0000000000 --- a/Task/Van-der-Corput-sequence/Ruby/van-der-corput-sequence-1.rb +++ /dev/null @@ -1,4 +0,0 @@ -def vdc(n, base=2) - str = n.to_s(base).reverse - str.to_i(base).quo(base ** str.length) -end diff --git a/Task/Van-der-Corput-sequence/Ruby/van-der-corput-sequence-2.rb b/Task/Van-der-Corput-sequence/Ruby/van-der-corput-sequence-2.rb deleted file mode 100644 index e74a339a5e..0000000000 --- a/Task/Van-der-Corput-sequence/Ruby/van-der-corput-sequence-2.rb +++ /dev/null @@ -1,2 +0,0 @@ -> Array.new(10){|i| vdc(i,3)} -=> [Rational(0, 1), Rational(1, 3), Rational(2, 3), Rational(1, 9), Rational(4, 9), Rational(7, 9), Rational(2, 9), Rational(5, 9), Rational(8, 9), Rational(1, 27)] diff --git a/Task/Van-der-Corput-sequence/Scala/van-der-corput-sequence.scala b/Task/Van-der-Corput-sequence/Scala/van-der-corput-sequence.scala new file mode 100644 index 0000000000..7a7a4489db --- /dev/null +++ b/Task/Van-der-Corput-sequence/Scala/van-der-corput-sequence.scala @@ -0,0 +1,12 @@ +object VanDerCorput extends App { + def compute(n: Int, base: Int = 2) = + Iterator.from(0). + scanLeft(1)((a, _) => a * base). + map(b => (n - 1) / b -> b). + takeWhile(_._1 != 0). + foldLeft(0d)((a, b) => a + (b._1 % base).toDouble / b._2 / base) + + val n = scala.io.StdIn.readInt + val b = scala.io.StdIn.readInt + (1 to n).foreach(x => println(compute(x, b))) +} diff --git a/Task/Van-der-Corput-sequence/Sidef/van-der-corput-sequence.sidef b/Task/Van-der-Corput-sequence/Sidef/van-der-corput-sequence.sidef index a331362b7e..9f385360b9 100644 --- a/Task/Van-der-Corput-sequence/Sidef/van-der-corput-sequence.sidef +++ b/Task/Van-der-Corput-sequence/Sidef/van-der-corput-sequence.sidef @@ -1,15 +1,15 @@ func vdc(value, base=2) { while (value[-1] > 0) { - value.append(value[-1] / base -> int); + value.append(value[-1] / base -> int) } - var (x, sum) = (1, 0); + var (x, sum) = (1, 0) value.each { |i| - sum += ((i % base) / (x *= base)); + sum += ((i % base) / (x *= base)) } - return sum; + return sum } - -2.to(5).each { |base| - var seq = (10.range.map {|i| vdc([i], base) }); - "base %d: %s\n".printf(base, seq.map{|n| "%.4f" % n}.join(', ')); +  +for base in (2..5) { + var seq = 10.of {|i| vdc([i], base) } + "base %d: %s\n".printf(base, seq.map{|n| "%.4f" % n}.join(', ')) } diff --git a/Task/Van-der-Corput-sequence/Stata/van-der-corput-sequence-1.stata b/Task/Van-der-Corput-sequence/Stata/van-der-corput-sequence-1.stata new file mode 100644 index 0000000000..e68b50241d --- /dev/null +++ b/Task/Van-der-Corput-sequence/Stata/van-der-corput-sequence-1.stata @@ -0,0 +1,38 @@ +mata +// 5th term of Van der Corput sequence +halton(1,1,5) + .625 + +// the first 10 terms of Van der Corput sequence +halton(10,1) + 1 + +---------+ + 1 | .5 | + 2 | .25 | + 3 | .75 | + 4 | .125 | + 5 | .625 | + 6 | .375 | + 7 | .875 | + 8 | .0625 | + 9 | .5625 | + 10 | .3125 | + +---------+ + +// the first 10 terms of Van der Corput sequence in base 3 +ghalton(10,3,0) + 1 + +---------------+ + 1 | .3333333333 | + 2 | .6666666667 | + 3 | .1111111111 | + 4 | .4444444444 | + 5 | .7777777778 | + 6 | .2222222222 | + 7 | .5555555556 | + 8 | .8888888889 | + 9 | .037037037 | + 10 | .3703703704 | + +---------------+ + +end diff --git a/Task/Van-der-Corput-sequence/Stata/van-der-corput-sequence-2.stata b/Task/Van-der-Corput-sequence/Stata/van-der-corput-sequence-2.stata new file mode 100644 index 0000000000..81a440f061 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Stata/van-der-corput-sequence-2.stata @@ -0,0 +1,13 @@ +clear +mata +st_addobs(2500) +st_addvar("double","x") +st_addvar("double","y") +st_addvar("double","z") +k=1::2500 +st_store(k,1,k) +st_store(k,2,0.5*runiform(2500,1)) +st_store(k,3,0.5:+0.5*halton(2500,1)) +end +twoway scatter y x, msize(tiny) color(blue) /// + || scatter z x, msize(tiny) color(green) diff --git a/Task/Van-der-Corput-sequence/Zkl/van-der-corput-sequence-1.zkl b/Task/Van-der-Corput-sequence/Zkl/van-der-corput-sequence-1.zkl new file mode 100644 index 0000000000..ef0e414a24 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Zkl/van-der-corput-sequence-1.zkl @@ -0,0 +1,9 @@ +fcn vdc(n,base=2){ + vdc:=0.0; denom:=1; + while(n){ reg remainder; + denom *= base; + n, remainder = n.divr(base); + vdc += (remainder.toFloat() / denom); + } + vdc +} diff --git a/Task/Van-der-Corput-sequence/Zkl/van-der-corput-sequence-2.zkl b/Task/Van-der-Corput-sequence/Zkl/van-der-corput-sequence-2.zkl new file mode 100644 index 0000000000..c8be39c485 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Zkl/van-der-corput-sequence-2.zkl @@ -0,0 +1,4 @@ +fcn vdc(n,base=2){ + str:=n.toString(base).reverse(); + str.toInt(base).toFloat()/(base.toFloat().pow(str.len())) +} diff --git a/Task/Variable-length-quantity/Haskell/variable-length-quantity-1.hs b/Task/Variable-length-quantity/Haskell/variable-length-quantity-1.hs index 42f8adb079..d6f7d2bfb2 100644 --- a/Task/Variable-length-quantity/Haskell/variable-length-quantity-1.hs +++ b/Task/Variable-length-quantity/Haskell/variable-length-quantity-1.hs @@ -1,10 +1,15 @@ -import Numeric +import Numeric (readOct, showOct) +import Data.List (intercalate) +to :: Int -> String to = flip showOct "" +from :: String -> Int from = fst . head . readOct -main = do - fancy 2097152 - fancy 2097151 - where fancy i = putStrLn $ to i ++ " <-> " ++ show (from $ to i) +main :: IO () +main = + mapM_ + (putStrLn . + intercalate " <-> " . (pure (:) <*> to <*> (return . show . from . to))) + [2097152, 2097151] diff --git a/Task/Variable-length-quantity/Haskell/variable-length-quantity-2.hs b/Task/Variable-length-quantity/Haskell/variable-length-quantity-2.hs index a64c7b50a3..a347c2973b 100644 --- a/Task/Variable-length-quantity/Haskell/variable-length-quantity-2.hs +++ b/Task/Variable-length-quantity/Haskell/variable-length-quantity-2.hs @@ -1,11 +1,19 @@ +import Data.List (intercalate) + +base :: Int base = 8 +to :: Int -> [Int] to 0 = [] to i = to (div i base) ++ [mod i base] -from = foldl1 (\x y -> x*base + y) +from :: [Int] -> Int +from = foldl1 ((+) . (base *)) -main = do - fancy 2097152 - fancy 2097151 - where fancy i = putStrLn $ concatMap show (to i) ++ " <-> " ++ show (from $ to i) +main :: IO () +main = + mapM_ + (putStrLn . + intercalate " <-> " . + (((:) . concatMap show . to) <*> (return . show . from . to))) + [2097152, 2097151] diff --git a/Task/Variable-length-quantity/Kotlin/variable-length-quantity.kotlin b/Task/Variable-length-quantity/Kotlin/variable-length-quantity.kotlin new file mode 100644 index 0000000000..c5464dd90f --- /dev/null +++ b/Task/Variable-length-quantity/Kotlin/variable-length-quantity.kotlin @@ -0,0 +1,31 @@ +// version 1.0.6 + +fun Int.toOctets(): ByteArray { + var s = Integer.toBinaryString(this) + val r = s.length % 7 + var z = s.length / 7 + if (r > 0) { + z++ + s = s.padStart(z * 7, '0') + } + s = Array(z) { "1" + s.slice(it * 7 until (it + 1) * 7) }.joinToString("") + s = s.take(s.length - 8) + "0" + s.takeLast(7) + return ByteArray(z) { Integer.parseInt(s.slice(it * 8 until (it + 1) * 8), 2).toByte() } +} + +fun ByteArray.fromOctets(): Int { + var s = "" + for (b in this) s += Integer.toBinaryString(b.toInt()).padStart(7, '0').takeLast(7) + return Integer.parseInt(s, 2) +} + +fun main(args: Array) { + val tests = intArrayOf(0x7f, 0x3fff, 0x200000, 0x1fffff) + for (test in tests) { + val ba = test.toOctets() + print("${"0x%x".format(test).padEnd(8)} -> ") + var s = "" + ba.forEach { s += "0x%02x ".format(it) } + println("${s.padEnd(20)} <- ${"0x%x".format(ba.fromOctets())}") + } +} diff --git a/Task/Variable-length-quantity/REXX/variable-length-quantity.rexx b/Task/Variable-length-quantity/REXX/variable-length-quantity.rexx index bd8f9f7e2c..a3fbeb69d8 100644 --- a/Task/Variable-length-quantity/REXX/variable-length-quantity.rexx +++ b/Task/Variable-length-quantity/REXX/variable-length-quantity.rexx @@ -1,26 +1,24 @@ -/*REXX program to display (and also test/verify) some numbers as octets.*/ +/*REXX program displays (and also tests/verifies) some numbers as octets. */ nums = x2d(200000) x2d(1fffff) 2097172 2097151 #=words(nums) -say ' number hex octet original' -say '═════════ ═════════ ═════════ ═════════' +say ' number hex octet original' +say '══════════ ══════════ ══════════ ══════════' ok=1 - do j=1 for #; @.j=word(nums,j) + do j=1 for #; @.j= word(nums,j) onum.j=octet(@.j) - orig.j=x2d(space(onum.j,0)) - - say show(@.j) show(d2x(@.j)) show(onum.j) show(orig.j) + orig.j= x2d( space(onum.j, 0) ) + w=10 + say center(@.j, w) center(d2x(@.j), w) center(onum.j, w) center(orig.j, w) if @.j\==orig.j then ok=0 end /*j*/ say -if ok then say 'All' # "numbers are OK." /*all numbers good*/ - else say 'Trouble right here in River City.' /*some number ¬good*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────OCTET subroutine────────────────────*/ -octet: procedure; parse arg a,_ /*obtain A from the passed arg. */ -x=d2x(a) /*convert A to hexadecimal octet.*/ - do j=length(x) by -2 to 1 /*process the "little" end first.*/ - _=substr(x,j-1,2,0) _ /*pad odd hexcharacters with ··· */ - end /*j*/ /* ··· a zero on the left. */ -return _ -/*──────────────────────────────────SHOW subroutine─────────────────────*/ -show: return center(arg(1),9) /*justify via centering the text.*/ +if ok then say 'All ' # " numbers are OK." /*all of the numbers are good. */ + else say "Some numbers are not OK." /*some of the numbers are ¬good. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +octet: procedure; parse arg z,$ /*obtain Z from the passed arguments.*/ + x=d2x(z) /*convert Z to a hexadecimal octet. */ + do j=length(x) by -2 to 1 /*process the "little" end first. */ + $= substr(x, j-1, 2, 0) $ /*pad odd hexadecimal characters with */ + end /*j*/ /* ··· a zero on the left. */ + return strip($) diff --git a/Task/Variable-length-quantity/Sidef/variable-length-quantity.sidef b/Task/Variable-length-quantity/Sidef/variable-length-quantity.sidef new file mode 100644 index 0000000000..497ac12558 --- /dev/null +++ b/Task/Variable-length-quantity/Sidef/variable-length-quantity.sidef @@ -0,0 +1,27 @@ +func vlq_encode(num) { + var t = (0x7F & num) + var str = t.chr + while (num >>= 7) { + t = (0x7F & num) + str += chr(0x80 | t) + } + str.reverse +} + +func vlq_decode(str) { + var num = '' + str.each_byte { |b| + num += ('%07b' % (b & 0x7F)) + } + Num(num, 2) +} + +var tests = [0, 0xa, 123, 254, 255, 256, + 257, 65534, 65535, 65536, 65537, 0x1fffff, + 0x200000] + +tests.each { |t| + var vlq = vlq_encode(t) + printf("%8s %12s %8s\n", t, + vlq.bytes.join(':', { "%02X" % _ }), vlq_decode(vlq)) +} diff --git a/Task/Variable-length-quantity/TXR/variable-length-quantity.txr b/Task/Variable-length-quantity/TXR/variable-length-quantity.txr deleted file mode 100644 index 44ed910759..0000000000 --- a/Task/Variable-length-quantity/TXR/variable-length-quantity.txr +++ /dev/null @@ -1,20 +0,0 @@ -;; show the utf8 bytes from byte stream as hex -(defun put-utf8 (str : stream) - (set stream (or stream *stdout*)) - (for ((s (make-string-byte-input-stream str)) byte) - ((set byte (get-byte s))) - ((format stream "\\x~,02x" byte)))) - -;; print -(put-utf8 (tostring 0)) -(put-line "") -(put-utf8 (tostring 42)) -(put-line "") -(put-utf8 (tostring #x200000)) -(put-line "") -(put-utf8 (tostring #x1fffff)) -(put-line "") - -;; print to string and recover -(format t "~a\n" (read (tostring #x200000))) -(format t "~a\n" (read (tostring #x1f0000))) diff --git a/Task/Variable-length-quantity/Zkl/variable-length-quantity-1.zkl b/Task/Variable-length-quantity/Zkl/variable-length-quantity-1.zkl new file mode 100644 index 0000000000..3b5d6c3c54 --- /dev/null +++ b/Task/Variable-length-quantity/Zkl/variable-length-quantity-1.zkl @@ -0,0 +1,8 @@ +fcn to_seq(x){ //--> list of ints + z:=(x.log2()/7); + (0).pump(z+1,List,'wrap(j){ + x.shiftRight((z-j)*7).bitAnd(0x7f).bitOr((j!=z) and 0x80 or 0) + }); +} + +fcn from_seq(in){ in.reduce(fcn(p,n){ p.shiftLeft(7).bitOr(n.bitAnd(0x7f)) },0) } diff --git a/Task/Variable-length-quantity/Zkl/variable-length-quantity-2.zkl b/Task/Variable-length-quantity/Zkl/variable-length-quantity-2.zkl new file mode 100644 index 0000000000..7a434a6f64 --- /dev/null +++ b/Task/Variable-length-quantity/Zkl/variable-length-quantity-2.zkl @@ -0,0 +1,5 @@ +ns:=T(0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413); +ms:=ns.apply(to_seq); +ns.zipWith(fcn{"%8,x --> %s --> %,x".fmt(vm.arglist.xplode()).println()}, + ms.apply("apply","%,x".fmt), + ms.apply(from_seq)); diff --git a/Task/Variable-size-Get/Gambas/variable-size-get.gambas b/Task/Variable-size-Get/Gambas/variable-size-get.gambas new file mode 100644 index 0000000000..63485c4c65 --- /dev/null +++ b/Task/Variable-size-Get/Gambas/variable-size-get.gambas @@ -0,0 +1,16 @@ +Public Sub Main() + +Print "Boolean =\t " & SizeOf(gb.Boolean) +Print "Byte =\t\t " & SizeOf(gb.Byte) +Print "Short =\t\t " & SizeOf(gb.Short) +Print "Integer =\t " & SizeOf(gb.Integer) +Print "Single =\t " & SizeOf(gb.Single) +Print "Long =\t\t " & SizeOf(gb.Long) +Print "Float =\t\t " & SizeOf(gb.Float) +Print "Date =\t\t " & SizeOf(gb.Date) +Print "String =\t " & SizeOf(gb.String) +Print "Object =\t " & SizeOf(gb.Object) +Print "Pointer =\t " & SizeOf(gb.Pointer) +Print "Variant =\t " & SizeOf(gb.Variant) + +End diff --git a/Task/Variable-size-Get/Kotlin/variable-size-get.kotlin b/Task/Variable-size-Get/Kotlin/variable-size-get.kotlin new file mode 100644 index 0000000000..ba2d92ab20 --- /dev/null +++ b/Task/Variable-size-Get/Kotlin/variable-size-get.kotlin @@ -0,0 +1,12 @@ +// version 1.1.2 + +fun main(args: Array) { + /* sizes for variables of the primitive types (except Boolean which is JVM dependent) */ + println("A Byte variable occupies: ${java.lang.Byte.SIZE / 8} byte") + println("A Short variable occupies: ${java.lang.Short.SIZE / 8} bytes") + println("An Int variable occupies: ${java.lang.Integer.SIZE / 8} bytes") + println("A Long variable occupies: ${java.lang.Long.SIZE / 8} bytes") + println("A Float variable occupies: ${java.lang.Float.SIZE / 8} bytes") + println("A Double variable occupies: ${java.lang.Double.SIZE / 8} bytes") + println("A Char variable occupies: ${java.lang.Character.SIZE / 8} bytes") +} diff --git a/Task/Variable-size-Get/Phix/variable-size-get.phix b/Task/Variable-size-Get/Phix/variable-size-get.phix new file mode 100644 index 0000000000..972f5d20a7 --- /dev/null +++ b/Task/Variable-size-Get/Phix/variable-size-get.phix @@ -0,0 +1 @@ +printf(1,"An integer contains %d bytes.\n", machine_word()) diff --git a/Task/Variable-size-Get/TXR/variable-size-get.txr b/Task/Variable-size-Get/TXR/variable-size-get.txr new file mode 100644 index 0000000000..012e6d46e4 --- /dev/null +++ b/Task/Variable-size-Get/TXR/variable-size-get.txr @@ -0,0 +1,5 @@ +struct foo { + uint32_t x : 17; + uint8_t y : 3; + char z[16]; +}; diff --git a/Task/Variable-size-Get/Zkl/variable-size-get.zkl b/Task/Variable-size-Get/Zkl/variable-size-get.zkl new file mode 100644 index 0000000000..4f6f1783cf --- /dev/null +++ b/Task/Variable-size-Get/Zkl/variable-size-get.zkl @@ -0,0 +1,8 @@ +(123).len() //-->1 (byte) +(0).MAX.len() //-->8 (bytes), ie the max number of bytes in an int +(1.0).MAX.len() //-->8 (bytes), ie the max number of bytes in an float +"this is a test".len() //-->14 +L(1,2,3,4).len() //-->4 +Dictionary("1",1, "2",2).len() //-->2 (keys) +Data(0,Int,1,2,3,4).len() //-->4 (bytes) +Data(0,String,"1","2","3","4").len() //-->8 bytes (ASCIIZ) diff --git a/Task/Variable-size-Set/C/variable-size-set.c b/Task/Variable-size-Set/C/variable-size-set-1.c similarity index 100% rename from Task/Variable-size-Set/C/variable-size-set.c rename to Task/Variable-size-Set/C/variable-size-set-1.c diff --git a/Task/Variable-size-Set/C/variable-size-set-2.c b/Task/Variable-size-Set/C/variable-size-set-2.c new file mode 100644 index 0000000000..88f36d785b --- /dev/null +++ b/Task/Variable-size-Set/C/variable-size-set-2.c @@ -0,0 +1,6 @@ +union u { + int i; + long l; + double d; + /* ... */ +}; diff --git a/Task/Variable-size-Set/C/variable-size-set-3.c b/Task/Variable-size-Set/C/variable-size-set-3.c new file mode 100644 index 0000000000..bbcea54b58 --- /dev/null +++ b/Task/Variable-size-Set/C/variable-size-set-3.c @@ -0,0 +1,4 @@ +union must_be_at_least_512_bytes { + int interesting_datum; + char padding[512]; +}; diff --git a/Task/Variable-size-Set/Kotlin/variable-size-set.kotlin b/Task/Variable-size-Set/Kotlin/variable-size-set.kotlin new file mode 100644 index 0000000000..4dc8aeec65 --- /dev/null +++ b/Task/Variable-size-Set/Kotlin/variable-size-set.kotlin @@ -0,0 +1,11 @@ +// version 1.0.6 + +fun main(args: Array) { + /* ranges for variables of the primitive numeric types */ + println("A Byte variable has a range of : ${Byte.MIN_VALUE} to ${Byte.MAX_VALUE}") + println("A Short variable has a range of : ${Short.MIN_VALUE} to ${Short.MAX_VALUE}") + println("An Int variable has a range of : ${Int.MIN_VALUE} to ${Int.MAX_VALUE}") + println("A Long variable has a range of : ${Long.MIN_VALUE} to ${Long.MAX_VALUE}") + println("A Float variable has a range of : ${Float.MIN_VALUE} to ${Float.MAX_VALUE}") + println("A Double variable has a range of : ${Double.MIN_VALUE} to ${Double.MAX_VALUE}") +} diff --git a/Task/Variable-size-Set/TXR/variable-size-set.txr b/Task/Variable-size-Set/TXR/variable-size-set.txr new file mode 100644 index 0000000000..013cafbed2 --- /dev/null +++ b/Task/Variable-size-Set/TXR/variable-size-set.txr @@ -0,0 +1 @@ +(make-buf 8 0 4096) diff --git a/Task/Variables/DM/variables-1.dm b/Task/Variables/DM/variables-1.dm new file mode 100644 index 0000000000..edfcd38fd1 --- /dev/null +++ b/Task/Variables/DM/variables-1.dm @@ -0,0 +1,12 @@ +// Both of the following declarations can be seen as a tree, +// var -> +var/x +var y + +// They can also be defined like this. +// This is once again a tree structure, but this time the "var" only appears once, and the x and y are children. +var + x + y +// And like this, still a tree structure. +var/x, y diff --git a/Task/Variables/DM/variables-2.dm b/Task/Variables/DM/variables-2.dm new file mode 100644 index 0000000000..1bfccf4df4 --- /dev/null +++ b/Task/Variables/DM/variables-2.dm @@ -0,0 +1,12 @@ +// Here, "/obj" is the type, a /obj being a simple game object. +var/obj/x +// It can also be defined like this, because of the tree structure: +var + obj + x +// Or this +var/obj + x + +// ... +// You get the idea diff --git a/Task/Variables/DM/variables-3.dm b/Task/Variables/DM/variables-3.dm new file mode 100644 index 0000000000..085418d9da --- /dev/null +++ b/Task/Variables/DM/variables-3.dm @@ -0,0 +1,4 @@ +var/x = 0 +x = 10 +var/y +y = "hi!" diff --git a/Task/Variables/Elena/variables.elena b/Task/Variables/Elena/variables.elena index 59ebd9bed2..55074d5485 100644 --- a/Task/Variables/Elena/variables.elena +++ b/Task/Variables/Elena/variables.elena @@ -1,8 +1,8 @@ -#symbol program = +program = [ - #var c. // declaring variable. default value is $nil - #var a := 3. // declaring and initializing variables - #var b := "my string" length. + var c := $nil. // declaring variable. + var a := 3. // declaring and initializing variables + var b := "my string" length. c := b + a. // assigning variable ]. diff --git a/Task/Variables/jq/variables-1.jq b/Task/Variables/Jq/variables-1.jq similarity index 100% rename from Task/Variables/jq/variables-1.jq rename to Task/Variables/Jq/variables-1.jq diff --git a/Task/Variables/jq/variables-2.jq b/Task/Variables/Jq/variables-2.jq similarity index 100% rename from Task/Variables/jq/variables-2.jq rename to Task/Variables/Jq/variables-2.jq diff --git a/Task/Variables/jq/variables-3.jq b/Task/Variables/Jq/variables-3.jq similarity index 100% rename from Task/Variables/jq/variables-3.jq rename to Task/Variables/Jq/variables-3.jq diff --git a/Task/Variables/jq/variables-4.jq b/Task/Variables/Jq/variables-4.jq similarity index 100% rename from Task/Variables/jq/variables-4.jq rename to Task/Variables/Jq/variables-4.jq diff --git a/Task/Variables/Kotlin/variables.kotlin b/Task/Variables/Kotlin/variables.kotlin new file mode 100644 index 0000000000..a467a01271 --- /dev/null +++ b/Task/Variables/Kotlin/variables.kotlin @@ -0,0 +1,26 @@ +// version 1.0.6 + +fun main(args: Array) { + /* read-only variables */ + val i = 3 // type inferred to be Int + val d = 2.4 // type inferred to be double + val sh: Short = 2 // type specified as Short + val ch = 'A' // type inferred to be Char + val bt: Byte = 1 // type specified as Byte + + /* mutable variables */ + var s = "Hey" // type inferred to be String + var l = 4L // type inferred to be Long + var b: Boolean // type specified as Boolean, not initialized immediately + var f = 4.4f // type inferred to be Float + + b = true // now initialized + println("$i, $d, $sh, $ch, $bt, $s, $l, $b, $f") + + s = "Bye" // OK as mutable + l = 5L // OK as mutable + b = false // OK as mutable + f = 5.6f // OK as mutable + + println("$i, $d, $sh, $ch, $bt, $s, $l, $b, $f") +} diff --git a/Task/Variables/OoRexx/variables.rexx b/Task/Variables/OoRexx/variables.rexx new file mode 100644 index 0000000000..15141abd4b --- /dev/null +++ b/Task/Variables/OoRexx/variables.rexx @@ -0,0 +1,9 @@ +a.=4711 +Say 'before sub a.3='a.3 +Call sub a. +Say ' after sub a.3='a.3 +Exit +sub: Procedure +use Arg a. +a.3=3 +Return diff --git a/Task/Variables/SPL/variables-1.spl b/Task/Variables/SPL/variables-1.spl new file mode 100644 index 0000000000..2b9e13a48a --- /dev/null +++ b/Task/Variables/SPL/variables-1.spl @@ -0,0 +1 @@ +a += 1 diff --git a/Task/Variables/SPL/variables-2.spl b/Task/Variables/SPL/variables-2.spl new file mode 100644 index 0000000000..5d33dec7ec --- /dev/null +++ b/Task/Variables/SPL/variables-2.spl @@ -0,0 +1 @@ +a = a+1 diff --git a/Task/Variables/SPL/variables-3.spl b/Task/Variables/SPL/variables-3.spl new file mode 100644 index 0000000000..63a2f8b59c --- /dev/null +++ b/Task/Variables/SPL/variables-3.spl @@ -0,0 +1,2 @@ +a = 1 +b,c,d = 0 diff --git a/Task/Variables/SPL/variables-4.spl b/Task/Variables/SPL/variables-4.spl new file mode 100644 index 0000000000..43c75833e9 --- /dev/null +++ b/Task/Variables/SPL/variables-4.spl @@ -0,0 +1,5 @@ +r = ~a +a = 3 +#.output(r) +r = 5 +#.output(a) diff --git a/Task/Variables/Smart-BASIC/variables-1.smart b/Task/Variables/Smart-BASIC/variables-1.smart new file mode 100644 index 0000000000..9c398a11f8 --- /dev/null +++ b/Task/Variables/Smart-BASIC/variables-1.smart @@ -0,0 +1,3 @@ +x = 14 +y = 0.4E3 +z = 3-2i diff --git a/Task/Variables/Smart-BASIC/variables-2.smart b/Task/Variables/Smart-BASIC/variables-2.smart new file mode 100644 index 0000000000..0b045152de --- /dev/null +++ b/Task/Variables/Smart-BASIC/variables-2.smart @@ -0,0 +1 @@ +t$ = "Name" diff --git a/Task/Variables/Smart-BASIC/variables-3.smart b/Task/Variables/Smart-BASIC/variables-3.smart new file mode 100644 index 0000000000..c8371cf71e --- /dev/null +++ b/Task/Variables/Smart-BASIC/variables-3.smart @@ -0,0 +1 @@ +n$ = """This is a quoted text""" diff --git a/Task/Variables/Smart-BASIC/variables-4.smart b/Task/Variables/Smart-BASIC/variables-4.smart new file mode 100644 index 0000000000..77a60c90ba --- /dev/null +++ b/Task/Variables/Smart-BASIC/variables-4.smart @@ -0,0 +1,3 @@ +n = 4 +a$ = "6 feet" +PRINT n * a$ diff --git a/Task/Variables/Smart-BASIC/variables-5.smart b/Task/Variables/Smart-BASIC/variables-5.smart new file mode 100644 index 0000000000..e291d44dcc --- /dev/null +++ b/Task/Variables/Smart-BASIC/variables-5.smart @@ -0,0 +1 @@ +DIM name$(100) diff --git a/Task/Variables/Smart-BASIC/variables-6.smart b/Task/Variables/Smart-BASIC/variables-6.smart new file mode 100644 index 0000000000..97a6fbfff9 --- /dev/null +++ b/Task/Variables/Smart-BASIC/variables-6.smart @@ -0,0 +1,5 @@ +DEF MyFunction(x) +MyF2 = x^2 +MyF3 = x^3 +MyFunction = MyF2 + MyF3 +END DEF diff --git a/Task/Variables/Smart-BASIC/variables-7.smart b/Task/Variables/Smart-BASIC/variables-7.smart new file mode 100644 index 0000000000..ca8022841b --- /dev/null +++ b/Task/Variables/Smart-BASIC/variables-7.smart @@ -0,0 +1,2 @@ +x = MyFunction(3) +PRINT x; MyFunction.MyF2; MyFunction.MyF3 diff --git a/Task/Variables/Smart-BASIC/variables-8.smart b/Task/Variables/Smart-BASIC/variables-8.smart new file mode 100644 index 0000000000..87fb220597 --- /dev/null +++ b/Task/Variables/Smart-BASIC/variables-8.smart @@ -0,0 +1 @@ +DEF num=123 diff --git a/Task/Variables/SuperCollider/variables.supercollider b/Task/Variables/SuperCollider/variables.supercollider new file mode 100644 index 0000000000..66705de1d3 --- /dev/null +++ b/Task/Variables/SuperCollider/variables.supercollider @@ -0,0 +1,69 @@ +// variable declaration +var table, chair; + +// assignment +var table = 10, chair = -10; + +// multiple assignment to the same value +table = chair = 0; + +// multiple assignment to an array +( +var table, chair; +#table, chair = [10, -10]; +#table ... chair = [10, -10, 2, 3]; // with ellipsis: now chair is [-10, 2, 3] +) + +// the letters a-z are predeclared in the interpreter for interactive programming +a = 10; x = a - 8; + +// variables are type-neutral and mutable: reassign to different objects +a = 10; a = [1, 2, 3]; a = nil; + +// immutable variables (only in class definitions) +const z = 42; + +// lexical scope +// the closures g and h refer to different values of their c +( +f = { + var c = 0; + { c = c + 1 } +}; +g = f.value; +h = f.value; +c = 100; // this doesn't change it. +) + +// dynamic scope: environments +f = { ~table = ~table + 1 }; +Environment.use { ~table = 100; f.value }; // 101. +Environment.use { ~table = -1; f.value }; // 0. + +// there is a default environment +~table = 7; +f.value; + +// lexical scope in environments: +( +Environment.use { + ~table = 100; + f = { ~table = ~table + 1 }.inEnvir; +}; +) +f.value; // 101. + +// because objects keep reference to other objects, references are not needed: +// objects can take the role of variables. But there is a Ref object, that just holds a value + +a = Ref([1, 2, 3]); // a reference to an array, can also be written as a quote `[1, 2, 3]; +f = { |x| x.value = x.value.squared }; // a function that operates on a ref +f.(a); // `[ 1, 4, 9 ] + +// proxy objects serve as delegators in environments. This can be called line by line: +ProxySpace.push; +~z // returns a NodeProxy +~z.play; // play a silent sound +~z = ~x + ~y; // make it the sum of two silent sounds +~x = { PinkNoise.ar(0.1) }; // … which now are noise, +~y = { SinOsc.ar(440, 0, 0.1) }; // and a sine tone diff --git a/Task/Variables/Zkl/variables.zkl b/Task/Variables/Zkl/variables.zkl new file mode 100644 index 0000000000..43ff3651b5 --- /dev/null +++ b/Task/Variables/Zkl/variables.zkl @@ -0,0 +1,14 @@ +var v; // global to the class that encloses this file +class C{ var v } // global to class C, each instance gets a new v +class C{fcn f{var v=123;}} // v can only be seen by f, initialized when C is +class C{fcn init{var [const] v=5;}} // init is part of the constructor, + so vars are promoted yo class scope. This allows const vars to be created at + construction time +var v=123; v="hoho"; //not typed +class C{var v} // C.v OK, but just v is not found +class C{var[const]v=4} // C.v=3 illegal (compile or run time, depending) +class C{var[mixin]v=4} // the compiler treats v as an int for type checking +class C{var[proxy]v=f; fcn f{println("my name is ",self.fcn.name)} } + v acts like a property to run f so C.v is the same as C.f() +class C{reg r} // C.r is compile time error +r:=5; // := syntax is same as "reg r=5", convenience diff --git a/Task/Variadic-function/00DESCRIPTION b/Task/Variadic-function/00DESCRIPTION index a0883648ae..27dd42e45c 100644 --- a/Task/Variadic-function/00DESCRIPTION +++ b/Task/Variadic-function/00DESCRIPTION @@ -4,7 +4,7 @@ Create a function which takes in a variable number of arguments and prints each Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. -Functions of this type are also known as   [[wp:Variadic_function|Variadic Functions]]. +Functions of this type are also known as [[wp:Variadic_function|Variadic Functions]]. ;Related task: diff --git a/Task/Variadic-function/AppleScript/variadic-function.applescript b/Task/Variadic-function/AppleScript/variadic-function.applescript index c9f37f6b4e..b664653fab 100644 --- a/Task/Variadic-function/AppleScript/variadic-function.applescript +++ b/Task/Variadic-function/AppleScript/variadic-function.applescript @@ -10,9 +10,9 @@ end positionalArgs -- namedArgs :: Record -> String on namedArgs(rec) script showKVpair - on lambda(k) + on |λ|(k) my putStrLn(k & " -> " & keyValue(rec, k)) - end lambda + end |λ| end script -- follow each argument name and value with line feed @@ -52,7 +52,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -89,7 +89,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Variadic-function/BaCon/variadic-function.bacon b/Task/Variadic-function/BaCon/variadic-function.bacon new file mode 100644 index 0000000000..7105d96071 --- /dev/null +++ b/Task/Variadic-function/BaCon/variadic-function.bacon @@ -0,0 +1,16 @@ +' Variadic functions +OPTION BASE 1 +SUB demo (VAR arg$ SIZE argc) + LOCAL x + PRINT "Amount of incoming arguments: ", argc + FOR x = 1 TO argc + PRINT arg$[x] + NEXT +END SUB + +' No argument +demo(0) +' One argument +demo("abc") +' Three arguments +demo("123", "456", "789") diff --git a/Task/Variadic-function/Bc/variadic-function.bc b/Task/Variadic-function/Bc/variadic-function.bc new file mode 100644 index 0000000000..15be3329fe --- /dev/null +++ b/Task/Variadic-function/Bc/variadic-function.bc @@ -0,0 +1,18 @@ +/* Version a */ +define f(a[], l) { + auto i + for (i = 0; i < l; i++) a[i] +} + +/* Version b */ +define g(a[]) { + auto i + for (i = 0; a[i] != -1; i++) a[i] +} + +/* Version c */ +define h(a[]) { + auto i + + for (i = 1; i <= a[0]; i++) a[i] +} diff --git a/Task/Variadic-function/Elena/variadic-function.elena b/Task/Variadic-function/Elena/variadic-function.elena new file mode 100644 index 0000000000..6d27a5043a --- /dev/null +++ b/Task/Variadic-function/Elena/variadic-function.elena @@ -0,0 +1,18 @@ +import system'routines. +import extensions. + +extension variadicOp +{ + generic printAll args:list + [ + list forEach(:v) + [ + self printLine:v + ] + ] +} + +program = +[ + console printAll("test", "rosetta code", 123, 5.6r). +]. diff --git a/Task/Variadic-function/JavaScript/variadic-function-4.js b/Task/Variadic-function/JavaScript/variadic-function-4.js new file mode 100644 index 0000000000..8f0bd7bbdd --- /dev/null +++ b/Task/Variadic-function/JavaScript/variadic-function-4.js @@ -0,0 +1,12 @@ +(() => { + 'use strict'; + + // show :: a -> String + const show = x => JSON.stringify(x, null, 2); + + // printAll [any] -> String + const printAll = (...a) => a.map(show) + .join('\n'); + + return printAll(1, 2, 3, 2 + 2, "five", 6); +})(); diff --git a/Task/Variadic-function/jq/variadic-function-1.jq b/Task/Variadic-function/Jq/variadic-function-1.jq similarity index 100% rename from Task/Variadic-function/jq/variadic-function-1.jq rename to Task/Variadic-function/Jq/variadic-function-1.jq diff --git a/Task/Variadic-function/jq/variadic-function-2.jq b/Task/Variadic-function/Jq/variadic-function-2.jq similarity index 100% rename from Task/Variadic-function/jq/variadic-function-2.jq rename to Task/Variadic-function/Jq/variadic-function-2.jq diff --git a/Task/Variadic-function/jq/variadic-function-3.jq b/Task/Variadic-function/Jq/variadic-function-3.jq similarity index 100% rename from Task/Variadic-function/jq/variadic-function-3.jq rename to Task/Variadic-function/Jq/variadic-function-3.jq diff --git a/Task/Variadic-function/jq/variadic-function-4.jq b/Task/Variadic-function/Jq/variadic-function-4.jq similarity index 100% rename from Task/Variadic-function/jq/variadic-function-4.jq rename to Task/Variadic-function/Jq/variadic-function-4.jq diff --git a/Task/Variadic-function/jq/variadic-function-5.jq b/Task/Variadic-function/Jq/variadic-function-5.jq similarity index 100% rename from Task/Variadic-function/jq/variadic-function-5.jq rename to Task/Variadic-function/Jq/variadic-function-5.jq diff --git a/Task/Variadic-function/jq/variadic-function-6.jq b/Task/Variadic-function/Jq/variadic-function-6.jq similarity index 100% rename from Task/Variadic-function/jq/variadic-function-6.jq rename to Task/Variadic-function/Jq/variadic-function-6.jq diff --git a/Task/Variadic-function/Julia/variadic-function-3.julia b/Task/Variadic-function/Julia/variadic-function-3.julia deleted file mode 100644 index 74e3a313d1..0000000000 --- a/Task/Variadic-function/Julia/variadic-function-3.julia +++ /dev/null @@ -1,5 +0,0 @@ -julia> x = (3,4) -(3,4) - -julia> bar(1,2,x...) -(1,2,(3,4)) diff --git a/Task/Variadic-function/Julia/variadic-function-4.julia b/Task/Variadic-function/Julia/variadic-function-4.julia deleted file mode 100644 index 8e165f017a..0000000000 --- a/Task/Variadic-function/Julia/variadic-function-4.julia +++ /dev/null @@ -1,11 +0,0 @@ -julia> x = (2,3,4) -(2,3,4) - -julia> bar(1,x...) -(1,2,(3,4)) - -julia> x = (1,2,3,4) -(1,2,3,4) - -julia> bar(x...) -(1,2,(3,4)) diff --git a/Task/Variadic-function/Julia/variadic-function-5.julia b/Task/Variadic-function/Julia/variadic-function-5.julia deleted file mode 100644 index 623a7dd0b0..0000000000 --- a/Task/Variadic-function/Julia/variadic-function-5.julia +++ /dev/null @@ -1,17 +0,0 @@ -julia> x = [3,4] -2-element Int64 Array: - 3 - 4 - -julia> bar(1,2,x...) -(1,2,(3,4)) - -julia> x = [1,2,3,4] -4-element Int64 Array: - 1 - 2 - 3 - 4 - -julia> bar(x...) -(1,2,(3,4)) diff --git a/Task/Variadic-function/Julia/variadic-function-6.julia b/Task/Variadic-function/Julia/variadic-function-6.julia deleted file mode 100644 index 9a5c08759e..0000000000 --- a/Task/Variadic-function/Julia/variadic-function-6.julia +++ /dev/null @@ -1,17 +0,0 @@ -baz(a,b) = a + b - -julia> args = [1,2] -2-element Int64 Array: - 1 - 2 - -julia> baz(args...) -3 - -julia> args = [1,2,3] -3-element Int64 Array: - 1 - 2 - 3 - -julia> baz(args...) diff --git a/Task/Variadic-function/Kotlin/variadic-function.kotlin b/Task/Variadic-function/Kotlin/variadic-function.kotlin new file mode 100644 index 0000000000..b8a65c1104 --- /dev/null +++ b/Task/Variadic-function/Kotlin/variadic-function.kotlin @@ -0,0 +1,17 @@ +// version 1.1 + +fun variadic(vararg va: String) { + for (v in va) println(v) +} + +fun main(args: Array) { + variadic("First", "Second", "Third") + println("\nEnter four strings for the function to print:") + val va = Array(4) { "" } + for (i in 1..4) { + print("String $i = ") + va[i - 1] = readLine()!! + } + println() + variadic(*va) +} diff --git a/Task/Variadic-function/Ruby/variadic-function-1.rb b/Task/Variadic-function/Ruby/variadic-function-1.rb index 405888f815..e52f640780 100644 --- a/Task/Variadic-function/Ruby/variadic-function-1.rb +++ b/Task/Variadic-function/Ruby/variadic-function-1.rb @@ -1,3 +1,3 @@ def print_all(*things) - things.each { |x| puts x } + puts things end diff --git a/Task/Variadic-function/Zkl/variadic-function-1.zkl b/Task/Variadic-function/Zkl/variadic-function-1.zkl new file mode 100644 index 0000000000..cc35d8813c --- /dev/null +++ b/Task/Variadic-function/Zkl/variadic-function-1.zkl @@ -0,0 +1,2 @@ +fcn f{vm.arglist.apply2("println")} +f("Mary","had","a","little"); diff --git a/Task/Variadic-function/Zkl/variadic-function-2.zkl b/Task/Variadic-function/Zkl/variadic-function-2.zkl new file mode 100644 index 0000000000..fa483f7612 --- /dev/null +++ b/Task/Variadic-function/Zkl/variadic-function-2.zkl @@ -0,0 +1,2 @@ +a:="This is a test".split(); //-->L("This","is","a","test") +f(a.xplode()); // xplode takes a list and blows it apart into call args diff --git a/Task/Variadic-function/Zkl/variadic-function-3.zkl b/Task/Variadic-function/Zkl/variadic-function-3.zkl new file mode 100644 index 0000000000..4ee0a825b5 --- /dev/null +++ b/Task/Variadic-function/Zkl/variadic-function-3.zkl @@ -0,0 +1,2 @@ +fcn g{f(vm.pasteArgs(2)} +g(a.xplode()); diff --git a/Task/Vector-products/00DESCRIPTION b/Task/Vector-products/00DESCRIPTION index f1fd9689c2..2bda317626 100644 --- a/Task/Vector-products/00DESCRIPTION +++ b/Task/Vector-products/00DESCRIPTION @@ -28,8 +28,8 @@ Given the three vectors: # Optionally create a function to compute the vector triple product of three vectors. # Compute and display: a • b # Compute and display: a x b -# Compute and display: a • b x c, the scalar triple product. -# Compute and display: a x b x c, the vector triple product. +# Compute and display: a • (b x c), the scalar triple product. +# Compute and display: a x (b x c), the vector triple product. ;References: diff --git a/Task/Vector-products/Erlang/vector-products.erl b/Task/Vector-products/Erlang/vector-products.erl new file mode 100644 index 0000000000..064b144615 --- /dev/null +++ b/Task/Vector-products/Erlang/vector-products.erl @@ -0,0 +1,21 @@ +-module(vector). +-export([main/0]). +vector_product(X,Y)-> +[X1,X2,X3]=X, +[Y1,Y2,Y3]=Y, +Ans=[X2*Y3-X3*Y2,X3*Y1-X1*Y3,X1*Y2-X2*Y1], +Ans. +dot_product(X,Y)-> +[X1,X2,X3]=X, +[Y1,Y2,Y3]=Y, +Ans=X1*Y1+X2*Y2+X3*Y3, +io:fwrite("~p~n",[Ans]). +main()-> +{ok, A} = io:fread("Enter vector A : ", "~d ~d ~d"), +{ok, B} = io:fread("Enter vector B : ", "~d ~d ~d"), +{ok, C} = io:fread("Enter vector C : ", "~d ~d ~d"), +dot_product(A,B), +Ans=vector_product(A,B), +io:fwrite("~p,~p,~p~n",Ans), +dot_product(C,vector_product(A,B)), +io:fwrite("~p,~p,~p~n",vector_product(C,vector_product(A,B))). diff --git a/Task/Vector-products/Forth/vector-products.fth b/Task/Vector-products/Forth/vector-products-1.fth similarity index 100% rename from Task/Vector-products/Forth/vector-products.fth rename to Task/Vector-products/Forth/vector-products-1.fth diff --git a/Task/Vector-products/Forth/vector-products-2.fth b/Task/Vector-products/Forth/vector-products-2.fth new file mode 100644 index 0000000000..5936a0720b --- /dev/null +++ b/Task/Vector-products/Forth/vector-products-2.fth @@ -0,0 +1,13 @@ +S" fsl-util.fs" REQUIRED +: 3f! 3 SWAP }fput ; +: vector + CREATE + HERE 3 DUP FLOAT DUP , * ALLOT SWAP CELL+ }fput + DOES> + CELL+ ; +: >fx@ 0 } F@ ; +: >fy@ 1 } F@ ; +: >fz@ 2 } F@ ; +: .Vector 3 SWAP }fprint ; + 0e 0e 0e vector pad \ NB: your system will be non-standard after this line +\ From here on is identical to the above example diff --git a/Task/Vector-products/Haskell/vector-products.hs b/Task/Vector-products/Haskell/vector-products.hs index 2af1123876..514031acde 100644 --- a/Task/Vector-products/Haskell/vector-products.hs +++ b/Task/Vector-products/Haskell/vector-products.hs @@ -1,32 +1,53 @@ +import Data.Monoid ((<>)) + type Vector a = [a] + type Scalar a = a -a,b,c,d :: Vector Int -a = [ 3, 4, 5 ] -b = [ 4, 3, 5 ] -c = [-5,-12,-13 ] -d = [ 3, 4, 5, 6 ] +a, b, c, d :: Vector Int +a = [3, 4, 5] -dot :: (Num t) => Vector t -> Vector t -> Scalar t -dot u v | length u == length v = sum $ zipWith (*) u v - | otherwise = error "Dotted Vectors must be of equal dimension." +b = [4, 3, 5] -cross :: (Num t) => Vector t -> Vector t -> Vector t -cross u v | length u == 3 && length v == 3 = - [u !! 1 * v !! 2 - u !! 2 * v !! 1, - u !! 2 * v !! 0 - u !! 0 * v !! 2, - u !! 0 * v !! 1 - u !! 1 * v !! 0] - | otherwise = error "Crossed Vectors must both be three dimensional." +c = [-5, -12, -13] -scalarTriple :: (Num t) => Vector t -> Vector t -> Vector t -> Scalar t +d = [3, 4, 5, 6] + +dot + :: (Num t) + => Vector t -> Vector t -> Scalar t +dot u v + | length u == length v = sum $ zipWith (*) u v + | otherwise = error "Dotted Vectors must be of equal dimension." + +cross + :: (Num t) + => Vector t -> Vector t -> Vector t +cross u v + | length u == 3 && length v == 3 = + [ u !! 1 * v !! 2 - u !! 2 * v !! 1 + , u !! 2 * head v - head u * v !! 2 + , head u * v !! 1 - u !! 1 * head v + ] + | otherwise = error "Crossed Vectors must both be three dimensional." + +scalarTriple + :: (Num t) + => Vector t -> Vector t -> Vector t -> Scalar t scalarTriple q r s = dot q $ cross r s -vectorTriple :: (Num t) => Vector t -> Vector t -> Vector t -> Vector t +vectorTriple + :: (Num t) + => Vector t -> Vector t -> Vector t -> Vector t vectorTriple q r s = cross q $ cross r s -main = do - mapM_ putStrLn [ "a . b = " ++ (show $ dot a b) - , "a x b = " ++ (show $ cross a b) - , "a . b x c = " ++ (show $ scalarTriple a b c) - , "a x b x c = " ++ (show $ vectorTriple a b c) - , "a . d = " ++ (show $ dot a d) ] +main :: IO () +main = + mapM_ + putStrLn + [ "a . b = " <> show (dot a b) + , "a x b = " <> show (cross a b) + , "a . b x c = " <> show (scalarTriple a b c) + , "a x b x c = " <> show (vectorTriple a b c) + , "a . d = " <> show (dot a d) + ] diff --git a/Task/Vector-products/jq/vector-products-1.jq b/Task/Vector-products/Jq/vector-products-1.jq similarity index 100% rename from Task/Vector-products/jq/vector-products-1.jq rename to Task/Vector-products/Jq/vector-products-1.jq diff --git a/Task/Vector-products/jq/vector-products-2.jq b/Task/Vector-products/Jq/vector-products-2.jq similarity index 100% rename from Task/Vector-products/jq/vector-products-2.jq rename to Task/Vector-products/Jq/vector-products-2.jq diff --git a/Task/Vector-products/Kotlin/vector-products.kotlin b/Task/Vector-products/Kotlin/vector-products.kotlin new file mode 100644 index 0000000000..7abbf1988b --- /dev/null +++ b/Task/Vector-products/Kotlin/vector-products.kotlin @@ -0,0 +1,28 @@ +// version 1.1.2 + +class Vector3D(val x: Double, val y: Double, val z: Double) { + infix fun dot(v: Vector3D) = x * v.x + y * v.y + z * v.z + + infix fun cross(v: Vector3D) = + Vector3D(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x) + + fun scalarTriple(v: Vector3D, w: Vector3D) = this dot (v cross w) + + fun vectorTriple(v: Vector3D, w: Vector3D) = this cross (v cross w) + + override fun toString() = "($x, $y, $z)" +} + +fun main(args: Array) { + val a = Vector3D(3.0, 4.0, 5.0) + val b = Vector3D(4.0, 3.0, 5.0) + val c = Vector3D(-5.0, -12.0, -13.0) + println("a = $a") + println("b = $b") + println("c = $c") + println() + println("a . b = ${a dot b}") + println("a x b = ${a cross b}") + println("a . b x c = ${a.scalarTriple(b, c)}") + println("a x b x c = ${a.vectorTriple(b, c)}") +} diff --git a/Task/Vector-products/OoRexx/vector-products.rexx b/Task/Vector-products/OoRexx/vector-products.rexx new file mode 100644 index 0000000000..3e67acd1bf --- /dev/null +++ b/Task/Vector-products/OoRexx/vector-products.rexx @@ -0,0 +1,49 @@ +a = .vector~new(3, 4, 5); +b = .vector~new(4, 3, 5); +c = .vector~new(-5, -12, -13); + +say a~dot(b) +say a~cross(b) +say a~scalarTriple(b, c) +say a~vectorTriple(b, c) + + +::class vector +::method init + expose x y z + use arg x, y, z + +::attribute x get +::attribute y get +::attribute z get + +-- dot product operation +::method dot + expose x y z + use strict arg other + + return x * other~x + y * other~y + z * other~z + +-- cross product operation +::method cross + expose x y z + use strict arg other + + newX = y * other~z - z * other~y + newY = z * other~x - x * other~z + newZ = x * other~y - y * other~x + return self~class~new(newX, newY, newZ) + +-- scalar triple product +::method scalarTriple + use strict arg vectorB, vectorC + return self~dot(vectorB~cross(vectorC)) + +-- vector triple product +::method vectorTriple + use strict arg vectorB, vectorC + return self~cross(vectorB~cross(vectorC)) + +::method string + expose x y z + return "<"||x", "y", "z">" diff --git a/Task/Vector-products/REXX/vector-products.rexx b/Task/Vector-products/REXX/vector-products.rexx index d35eb32d33..ea892e69c0 100644 --- a/Task/Vector-products/REXX/vector-products.rexx +++ b/Task/Vector-products/REXX/vector-products.rexx @@ -1,7 +1,7 @@ /*REXX program computes the products: dot, cross, scalar triple, and vector triple.*/ - a= 3 4 5 - b= 4 3 5 /*positive numbers don't need quotes. */ - c= "-5 -12 -13" + a= 3 4 5 + b= 4 3 5 /*(positive numbers don't need quotes.)*/ + c= "-5 -12 -13" call tellV 'vector A =', a /*show the A vector, aligned numbers.*/ call tellV 'vector B =', b /* " " B " " " */ call tellV 'vector C =', c /* " " C " " " */ @@ -12,13 +12,10 @@ call tellV 'scalar triple product [A∙(BxC)] =', dot(a, cross(b, c) ) call tellV 'vector triple product [Ax(BxC)] =', cross(a, cross(b, c) ) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -cross: procedure; parse arg x1 x2 x3,y1 y2 y3 /*the CROSS product.*/ - return x2*y3-x3*y2 x3*y1-x1*y3 x1*y2-x2*y1 /*a vector quantity. */ +cross: procedure; arg $1 $2 $3,@1 @2 @3; return $2*@3 -$3*@2 $3*@1 -$1*@3 $1*@2 -$2*@1 +dot: procedure; arg $1 $2 $3,@1 @2 @3; return $1*@1 + $2*@2 + $3*@3 /*──────────────────────────────────────────────────────────────────────────────────────*/ -dot: procedure; parse arg x1 x2 x3,y1 y2 y3 /*the DOT product.*/ - return x1*y1 + x2*y2 + x3*y3 /*a scalar quantity. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -tellV: procedure; parse arg name,x y z /*display the vector. */ - w=max(4, length(x), length(y), length(z)) /*max width of numbers*/ - say right(name, 40) right(x,w) right(y,w) right(z,w) /*enforce alignment. */ - return +tellV: procedure; parse arg name,x y z /*obtain name, values.*/ + w=max(4, length(x), length(y), length(z) ) /*max width of numbers*/ + say right(name, 40) right(x,w) right(y,w) right(z,w) /*enforce # alignment.*/ + return /* [↑] display vector*/ diff --git a/Task/Vector-products/Ring/vector-products.ring b/Task/Vector-products/Ring/vector-products.ring new file mode 100644 index 0000000000..a7c1025b6e --- /dev/null +++ b/Task/Vector-products/Ring/vector-products.ring @@ -0,0 +1,35 @@ +# Project : Vector products +# Date : 2017/09/21 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +d = list(3) +e = list(3) +a = [3, 4, 5] +b = [4, 3, 5] +c = [-5, -12, -13] + +see "a . b = " + dot(a,b) + nl +cross(a,b,d) +see "a x b = (" + d[1] + ", " + d[2] + ", " + d[3] + ")" + nl +see "a . (b x c) = " + scalartriple(a,b,c) + nl +vectortriple(a,b,c,d) + +def dot(a,b) + sum = 0 + for n=1 to len(a) + sum = sum + a[n]*b[n] + next + return sum + +func cross(a,b,d) + d = [a[2]*b[3]-a[3]*b[2], a[3]*b[1]-a[1]*b[3], a[1]*b[2]-a[2]*b[1]] + +func scalartriple(a,b,c) + cross(b,c,d) + return dot(a,d) + +func vectortriple(a,b,c,d) + cross(b,c,d) + cross(a,d,e) + see "a x (b x c) = (" + e[1] + ", " +e[2] + ", " + e[3] + ")" diff --git a/Task/Vector-products/Rust/vector-products.rust b/Task/Vector-products/Rust/vector-products.rust new file mode 100644 index 0000000000..3b2062a645 --- /dev/null +++ b/Task/Vector-products/Rust/vector-products.rust @@ -0,0 +1,45 @@ +#[derive(Debug)] +struct Vector { + x: f64, + y: f64, + z: f64, +} + +impl Vector { + fn new(x: f64, y: f64, z: f64) -> Self { + Vector { + x: x, + y: y, + z: z, + } + } + + fn dot_product(&self, other: &Vector) -> f64 { + (self.x * other.x) + (self.y * other.y) + (self.z * other.z) + } + + fn cross_product(&self, other: &Vector) -> Vector { + Vector::new(self.y * other.z - self.z * other.y, + self.z * other.x - self.x * other.z, + self.x * other.y - self.y * other.x) + } + + fn scalar_triple_product(&self, b: &Vector, c: &Vector) -> f64 { + self.dot_product(&b.cross_product(&c)) + } + + fn vector_triple_product(&self, b: &Vector, c: &Vector) -> Vector { + self.cross_product(&b.cross_product(&c)) + } +} + +fn main(){ + let a = Vector::new(3.0, 4.0, 5.0); + let b = Vector::new(4.0, 3.0, 5.0); + let c = Vector::new(-5.0, -12.0, -13.0); + + println!("a . b = {}", a.dot_product(&b)); + println!("a x b = {:?}", a.cross_product(&b)); + println!("a . (b x c) = {}", a.scalar_triple_product(&b, &c)); + println!("a x (b x c) = {:?}", a.vector_triple_product(&b, &c)); +} diff --git a/Task/Vector-products/Stata/vector-products.stata b/Task/Vector-products/Stata/vector-products.stata new file mode 100644 index 0000000000..a87193cfec --- /dev/null +++ b/Task/Vector-products/Stata/vector-products.stata @@ -0,0 +1,43 @@ +mata +real scalar sprod(real colvector u, real colvector v) { + return(u[1]*v[1] + u[2]*v[2] + u[3]*v[3]) +} + +real colvector vprod(real colvector u, real colvector v) { + return(u[2]*v[3]-u[3]*v[2]\u[3]*v[1]-u[1]*v[3]\u[1]*v[2]-u[2]*v[1]) +} + +real scalar striple(real colvector u, real colvector v, real colvector w) { + return(sprod(u, vprod(v, w))) +} + +real colvector vtriple(real colvector u, real colvector v, real colvector w) { + return(vprod(u, vprod(v, w))) +} + +a = 3\4\5 +b = 4\3\5 +c = -5\-12\-13 + +sprod(a, b) + 49 + +vprod(a, b) + 1 + +------+ + 1 | 5 | + 2 | 5 | + 3 | -7 | + +------+ + +striple(a, b, c) + 6 + +vtriple(a, b, c) + 1 + +--------+ + 1 | -267 | + 2 | 204 | + 3 | -3 | + +--------+ +end diff --git a/Task/Vector-products/Zkl/vector-products-1.zkl b/Task/Vector-products/Zkl/vector-products-1.zkl new file mode 100644 index 0000000000..f1ea982b65 --- /dev/null +++ b/Task/Vector-products/Zkl/vector-products-1.zkl @@ -0,0 +1,3 @@ +fcn dotp(a,b){ a.zipWith('*,b).sum() } //1 slow but concise +fcn crossp([(a1,a2,a3)],[(b1,b2,b3)]) //2 + { return(a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1) } diff --git a/Task/Vector-products/Zkl/vector-products-2.zkl b/Task/Vector-products/Zkl/vector-products-2.zkl new file mode 100644 index 0000000000..7b182d00d7 --- /dev/null +++ b/Task/Vector-products/Zkl/vector-products-2.zkl @@ -0,0 +1,5 @@ +a,b,c := T(3,4,5), T(4,3,5), T(-5,-12,-13); +dotp(a,b).println(); //5 --> 49 +crossp(a,b).println(); //6 --> (5,5,-7) +dotp(a, crossp(b,c)).println(); //7 --> 6 +crossp(a, crossp(b,c)).println(); //8 --> (-267,204,-3) diff --git a/Task/Vector-products/Zkl/vector-products-3.zkl b/Task/Vector-products/Zkl/vector-products-3.zkl new file mode 100644 index 0000000000..fcebbd6494 --- /dev/null +++ b/Task/Vector-products/Zkl/vector-products-3.zkl @@ -0,0 +1,11 @@ +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +a:=GSL.VectorFromData( 3, 4, 5); +b:=GSL.VectorFromData( 4, 3, 5); +c:=GSL.VectorFromData(-5,-12,-13); + +(a*b).println(); // 49, dot product +a.copy().crossProduct(b) // (5,5,-7) cross product, in place + .format().println(); +(a*(b.copy().crossProduct(c))).println(); // 6 scalar triple product +(a.crossProduct(b.crossProduct(c))) // (-267,204,-3) vector triple product, in place + .format().println(); diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Julia/verify-distribution-uniformity-chi-squared-test.julia b/Task/Verify-distribution-uniformity-Chi-squared-test/Julia/verify-distribution-uniformity-chi-squared-test.julia new file mode 100644 index 0000000000..3add14625c --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Julia/verify-distribution-uniformity-chi-squared-test.julia @@ -0,0 +1,19 @@ +# v0.6 + +using Distributions + +function eqdist(data::Vector{T}, α::Float64=0.05)::Bool where T <: Real + if ! (0 ≤ α ≤ 1); error("α must be in [0, 1]") end + exp = mean(data) + chisqval = sum((x - exp) ^ 2 for x in data) / exp + pval = ccdf(Chisq(2), chisqval) + return pval > α +end + +data1 = [199809, 200665, 199607, 200270, 199649] +data2 = [522573, 244456, 139979, 71531, 21461] + +for data in (data1, data2) + println("Data:\n$data") + println("Hypothesis test: the original population is ", (eqdist(data) ? "" : "not "), "uniform.\n") +end diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Zkl/verify-distribution-uniformity-chi-squared-test-1.zkl b/Task/Verify-distribution-uniformity-Chi-squared-test/Zkl/verify-distribution-uniformity-chi-squared-test-1.zkl new file mode 100644 index 0000000000..67e4ab59de --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Zkl/verify-distribution-uniformity-chi-squared-test-1.zkl @@ -0,0 +1,37 @@ +/* Numerical integration method */ +fcn Simpson3_8(f,a,b,N){ // fcn,double,double,Int --> double + h,h1:=(b - a)/N, h/3.0; + h*[1..3*N - 1].reduce('wrap(sum,j){ + l1:=(if(j%3) 3.0 else 2.0); + sum + l1*f(a + h1*j); + },f(a) + f(b))/8.0; +} + +const A=12; +fcn Gamma_Spouge(z){ // double --> double + var coefs=fcn{ // this runs only once, at construction time + a,coefs:=A.toFloat(),(A).pump(List(),0.0); + k1_factrl:=1.0; + coefs[0]=(2.0*(0.0).pi).sqrt(); + foreach k in ([1.0..A-1]){ + coefs[k]=(a - k).exp() * (a - k).pow(k - 0.5) / k1_factrl; + k1_factrl*=-k; + } + coefs + }(); + + ( [1..A-1].reduce('wrap(accum,k){ accum + coefs[k]/(z + k) },coefs[0]) + * (-(z + A)).exp()*(z + A).pow(z + 0.5) ) + / z; +} + +fcn f0(t,aa1){ t.pow(aa1)*(-t).exp() } + +fcn GammaIncomplete_Q(a,x){ // double,double --> double + h:=1.5e-2; /* approximate integration step size */ + /* this cuts off the tail of the integration to speed things up */ + y:=a - 1; f:=f0.fp1(y); + while((f(y)*(x - y)>2.0e-8) and (yx) y=x; + 1.0 - Simpson3_8(f,0.0,y,(y/h).toInt())/Gamma_Spouge(a); +} diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Zkl/verify-distribution-uniformity-chi-squared-test-2.zkl b/Task/Verify-distribution-uniformity-Chi-squared-test/Zkl/verify-distribution-uniformity-chi-squared-test-2.zkl new file mode 100644 index 0000000000..21806d82e3 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Zkl/verify-distribution-uniformity-chi-squared-test-2.zkl @@ -0,0 +1,12 @@ +fcn chi2UniformDistance(ds){ // --> double + dslen :=ds.len(); + expected:=dslen.reduce('wrap(sum,k){ sum + ds[k] },0.0)/dslen; + sum := dslen.reduce('wrap(sum,k){ x:=ds[k] - expected; sum + x*x },0.0); + sum/expected +} + +fcn chi2Probability(dof,distance){ GammaIncomplete_Q(0.5*dof, 0.5*distance) } + +fcn chiIsUniform(dset,significance=0.05){ + significance < chi2Probability(-1.0 + dset.len(),chi2UniformDistance(dset)) +} diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Zkl/verify-distribution-uniformity-chi-squared-test-3.zkl b/Task/Verify-distribution-uniformity-Chi-squared-test/Zkl/verify-distribution-uniformity-chi-squared-test-3.zkl new file mode 100644 index 0000000000..20fe1dbb10 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Zkl/verify-distribution-uniformity-chi-squared-test-3.zkl @@ -0,0 +1,12 @@ +datasets:=T( T(199809.0, 200665.0, 199607.0, 200270.0, 199649.0), + T(522573.0, 244456.0, 139979.0, 71531.0, 21461.0) ); +println(" %4s %12s %12s %8s %s".fmt( + "dof", "distance", "probability", "Uniform?", "dataset")); +foreach ds in (datasets){ + dof :=ds.len() - 1; + dist:=chi2UniformDistance(ds); + prob:=chi2Probability(dof,dist); + println("%4d %12.3f %12.8f %5s %6s".fmt( + dof, dist, prob, chiIsUniform(ds) and "YES" or "NO", + ds.concat(","))); +} diff --git a/Task/Verify-distribution-uniformity-Naive/00DESCRIPTION b/Task/Verify-distribution-uniformity-Naive/00DESCRIPTION index 98626dbc20..88aaf25597 100644 --- a/Task/Verify-distribution-uniformity-Naive/00DESCRIPTION +++ b/Task/Verify-distribution-uniformity-Naive/00DESCRIPTION @@ -1,7 +1,7 @@ This task is an adjunct to [[Seven-sided dice from five-sided dice]]. -;Ttask: +;Task: Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. @@ -10,12 +10,15 @@ The function should take as arguments: * The number of times to call the integer generator. * A 'delta' value of some sort that indicates how close to a flat distribution is close enough. + The function should produce: * Some indication of the distribution achieved. * An 'error' if the distribution is not flat enough. + Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from [[Seven-sided dice from five-sided dice]]). + See also: *[[Verify distribution uniformity/Chi-squared test]]

    diff --git a/Task/Verify-distribution-uniformity-Naive/Kotlin/verify-distribution-uniformity-naive.kotlin b/Task/Verify-distribution-uniformity-Naive/Kotlin/verify-distribution-uniformity-naive.kotlin new file mode 100644 index 0000000000..d91350d569 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Kotlin/verify-distribution-uniformity-naive.kotlin @@ -0,0 +1,38 @@ +// version 1.1.3 + +import java.util.Random + +val r = Random() + +fun dice5() = 1 + r.nextInt(5) + +fun checkDist(gen: () -> Int, nRepeats: Int, tolerance: Double = 0.5) { + val occurs = mutableMapOf() + for (i in 1..nRepeats) { + val d = gen() + if (occurs.containsKey(d)) + occurs[d] = occurs[d]!! + 1 + else + occurs.put(d, 1) + } + val expected = (nRepeats.toDouble()/ occurs.size).toInt() + val maxError = (expected * tolerance / 100.0).toInt() + println("Repetitions = $nRepeats, Expected = $expected") + println("Tolerance = $tolerance%, Max Error = $maxError\n") + println("Integer Occurrences Error Acceptable") + val f = " %d %5d %5d %s" + var allAcceptable = true + for ((k,v) in occurs.toSortedMap()) { + val error = Math.abs(v - expected) + val acceptable = if (error <= maxError) "Yes" else "No" + if (acceptable == "No") allAcceptable = false + println(f.format(k, v, error, acceptable)) + } + println("\nAcceptable overall: ${if (allAcceptable) "Yes" else "No"}") +} + +fun main(args: Array) { + checkDist(::dice5, 1_000_000) + println() + checkDist(::dice5, 100_000) +} diff --git a/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx b/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx index 161b3a0a80..9f1c8d8790 100644 --- a/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx +++ b/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx @@ -1,33 +1,34 @@ /*REXX program simulates a number of trials of a random digit and show it's skew %. */ -parse arg f t d s . /*obtain arguments (options) from C.L. */ -if f=='' | f=="," then f='RANDOM' /*function not specified? Use default.*/ -if t=='' | t=="," then t=1000000 /*times " " " " */ -if d=='' | d=="," then d=1/2 /*delta% " " " " */ -if s\=='' then call random ,,s /*use some RAND seed for repeatability.*/ +parse arg func times delta seed . /*obtain arguments (options) from C.L. */ +if func=='' | func=="," then func= 'RANDOM' /*function not specified? Use default.*/ +if times=='' | times=="," then times= 1000000 /*times " " " " */ +if delta=='' | delta=="," then delta= 1/2 /*delta% " " " " */ +if datatype(seed, 'W') then call random ,,seed /*use some RAND seed for repeatability.*/ highDig=9 /*use this var for the highest digit. */ !.=0 /*initialize all possible random trials*/ - do t /* [↓] perform a bunch of trials. */ - if f=='RANDOM' then ?=random(0,highDig) /*use the RANDOM BIF function.*/ - else interpret '?='f"(0,"highDig')' /*use the (specified) " */ - !.?=!.?+1 /*bump the invocation counter.*/ - end /*t*/ /* [↑] store trials ───► pigeonholes. */ + do times /* [↓] perform a bunch of trials. */ + if func=='RANDOM' then ?=random(highDig) /*use RANDOM function.*/ + else interpret '?='func"(0,"highDig')' /* " specified " */ + !.?=!.? + 1 /*bump the invocation counter.*/ + end /*times*/ /* [↑] store trials ───► pigeonholes. */ /* [↓] compute the digit's skewness. */ -g=t / (1+highDig) /*calculate number of each digit throw.*/ -OK?= 'OK skewed' /*words to show "skewed" or if "OK".*/ -w=max(8, length(t)) /*maximum length of number of trials.*/ +g=times / (1 + highDig) /*calculate number of each digit throw.*/ +w=max(9, length( commas(times) ) ) /*maximum length of number of trials.*/ pad=left('', 9) /*this is used for output indentation. */ -say pad 'digit' center("hits",w) ' skew ' "skew%" 'result' /*header. */ -say pad '─────' center('',w,'─') '──────' "─────" '──────' /*separator.*/ +say pad 'digit' center(" hits", w) ' skew ' "skew %" 'result' /*header. */ +say pad '─────' center('', w, '─') '──────' "──────" '──────' /*separator*/ /** [↑] show header and the separator.*/ do k=0 to highDig /*process each of the possible digits. */ - skew=g-!.k /*calculate the skew for the digit. */ + skew=g - !.k /*calculate the skew for the digit. */ skewPC=(1- (g-abs(skew)) / g) * 100 /* " " " percentage for dig*/ - ok=center(word(ok?, 1 + (skewPC>d)), 6) /*it's gotta be one of skewed or xx%*/ - say pad center(k,5) right(!.k,w) right(skew,6) format(skewPC,,3) ok + say pad center(k, 5) right( commas(!.k), w) right(skew, 6) , + right( format(skewPC, , 3), 6) center( word('ok skewed', 1+(skewPC>delta)), 6) end /*k*/ -say pad '─────' center('',w,'─') '──────' "─────" '──────' /*separator. */ +say pad '─────' center('', w, '─') '──────' "─────" '──────' /*separator. */ y=5+1+w+1+6+1+6+1+6 /*the width. */ -say pad center(" (with " t ' trials)',y) /*# trials. */ -say pad center(" (skewed when exceeds " d'%)',y) /*skewed note.*/ - /*stick a fork in it, we're all done. */ +say pad center(" (with " commas(times) ' trials)' , y) /*# trials. */ +say pad center(" (skewed when exceeds " delta'%)' , y) /*skewed note.*/ +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 _ diff --git a/Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive-1.rkt b/Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive-1.rkt deleted file mode 100644 index a26eb964f9..0000000000 --- a/Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive-1.rkt +++ /dev/null @@ -1,41 +0,0 @@ -#lang racket -(require - racket/flonum (planet williams/science:4:5/science) - (only-in (planet williams/science/unsafe-ops-utils) real->float)) - -; (chi^2-goodness-of-fit-test observed expected df) -; Given: observed, a sequence of observed frequencies -; expected, a sequence of expected frequencies -; df, the degrees of freedom -; Result: P-value = 1-chi^2cdf(X^2,df) , the p-value -(define (chi^2-goodness-of-fit-test observed expected df) - (define X^2 (for/sum ([o observed] [e expected]) - (/ (sqr (- o e)) e))) - (- 1.0 (chi-squared-cdf X^2 df))) - - -(define (is-uniform? rand n α) - ; Use significance level α to test whether - ; n small random numbers generated by rand - ; have a uniform distribution. - - ; Observed values: - (define o (make-vector 10 0)) - ; generate n random integers from 0 to 9. - (for ([_ (+ n 1)]) - (define r (rand 10)) - (vector-set! o r (+ (vector-ref o r) 1))) - ; Expected values: - (define ex (make-vector 10 (/ n 10))) - - ; Calculate the P-value: - (define P (chi^2-goodness-of-fit-test o ex (- n 1))) - - ; If the P-value is larger than α we accept the - ; hypothesis that the numbers are distributed uniformly. - (> P α)) - -; Test whether the builtin generator is uniform: -(is-uniform? random 1000 0.05) -; Test whether the constant generator fails: -(is-uniform? (λ(_) 5) 1000 0.05) diff --git a/Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive-2.rkt b/Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive-2.rkt deleted file mode 100644 index 39b423189b..0000000000 --- a/Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive-2.rkt +++ /dev/null @@ -1,2 +0,0 @@ -#t -#f diff --git a/Task/Verify-distribution-uniformity-Naive/Ring/verify-distribution-uniformity-naive.ring b/Task/Verify-distribution-uniformity-Naive/Ring/verify-distribution-uniformity-naive.ring new file mode 100644 index 0000000000..fd1a3b0c88 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Ring/verify-distribution-uniformity-naive.ring @@ -0,0 +1,33 @@ +# Project : Verify distribution uniformity/Naive +# Date : 2017/09/21 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +maxrnd = 7 +for r = 2 to 5 + check = distcheck(pow(10,r), 0.05) + see "over " + pow(10,r) + " runs dice5 " + nl + if check + see "failed distribution check with " + check + " bin(s) out of range" + nl + else + see "passed distribution check" + nl + ok +next + +func distcheck(repet, delta) +m = 1 +s = 0 +bins = list(maxrnd) +for i = 1 to repet + r = dice5() + 1 + bins[r] = bins[r] + 1 + if r>m m = r ok +next +for i = 1 to m + if bins[i]/(repet/m) > 1+delta s = s + 1 ok + if bins[i]/(repet/m) < 1-delta s = s + 1 ok +next +return s + +func dice5 + return random(5) diff --git a/Task/Verify-distribution-uniformity-Naive/Zkl/verify-distribution-uniformity-naive.zkl b/Task/Verify-distribution-uniformity-Naive/Zkl/verify-distribution-uniformity-naive.zkl new file mode 100644 index 0000000000..50efcb6ddf --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Zkl/verify-distribution-uniformity-naive.zkl @@ -0,0 +1,12 @@ +fcn rtest(N){ + dist:=L(0,0,0,0,0,0,0,0,0,0); + do(N){n:=(0).random(10); dist[n]=dist[n]+1} + sum:=dist.sum(); + dist=dist.apply('wrap(n){n.toFloat()/sum*100}); + if (dist.filter((10.0).closeTo.fp1(0.1)).len() == 10) + { "Good enough at %,d: %s".fmt(N,dist).println(); return(True); } + False +} + +n:=10; +while(not rtest(n)) {n*=2} diff --git a/Task/Video-display-modes/Ring/video-display-modes.ring b/Task/Video-display-modes/Ring/video-display-modes.ring new file mode 100644 index 0000000000..6291842630 --- /dev/null +++ b/Task/Video-display-modes/Ring/video-display-modes.ring @@ -0,0 +1 @@ +system("mode 40, 25") diff --git a/Task/Video-display-modes/Smart-BASIC/video-display-modes.smart b/Task/Video-display-modes/Smart-BASIC/video-display-modes.smart new file mode 100644 index 0000000000..3711106c41 --- /dev/null +++ b/Task/Video-display-modes/Smart-BASIC/video-display-modes.smart @@ -0,0 +1,4 @@ +GRAPHICS +FILL RECT 50,50 SIZE 50 +GRAPHICS MODE CLEAR +FILL RECT 50,50 SIZE 25 diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Haskell/vigen-re-cipher-cryptanalysis-1.hs b/Task/Vigen-re-cipher-Cryptanalysis/Haskell/vigen-re-cipher-cryptanalysis-1.hs new file mode 100644 index 0000000000..71ad6ffa3a --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Haskell/vigen-re-cipher-cryptanalysis-1.hs @@ -0,0 +1,93 @@ +import Data.List(transpose, nub, sort, maximumBy) +import Data.Ord (comparing) +import Data.Char (ord) + +average :: Fractional a => [a] -> a +average as = sum as / fromIntegral (length as) + +-- Count the occurrence of a char in a string. +countChar :: Eq a => [a] -> a -> Int +countChar s c = length $ filter (==c) s + +-- Break a string up into substrings of n chars. +breakup :: Int -> [a] -> [[a]] +breakup _ [] = [] +breakup n as = + let (h, r) = splitAt n as + in h:breakup n r + +-- Dole out elements of a string over a n element distribution. +distribute :: [a] -> Int -> [[a]] +distribute as n = transpose $ breakup n as + +-- The probability that members of a pair of characters taken randomly +-- from a given string are equal. +coincidence :: (Ord a, Fractional b) => [a] -> b +coincidence str = + let charCounts = fmap (countChar str) (nub $ sort str) + strln = length str + d = fromIntegral $ strln * (strln - 1) + n = fromIntegral $ sum $ fmap (\cc -> cc * (cc-1)) charCounts + in n / d + +-- Use the average probablity of coincidence for all the members of +-- a distribution to rate the distribution - the higher the better. +-- The correlation increases artificially for smaller +-- pieces/longer keys, so weigh against them a little +rate :: (Ord a, Fractional b) => [[a]] -> b +rate d = average (fmap coincidence d) - fromIntegral (length d) / 3000.0 + +-- Multiply elements of lists together and add up the results. +dot :: Num a => [a] -> [a] -> a +dot v0 v1 = sum $ zipWith (*) v0 v1 + +-- Given two lists of floats, rotate one of them by the number of +-- characters indicated by letter and then 'dot' them together. +rotateAndDot :: Num a => [a] -> [a] -> Char -> a +rotateAndDot v0 v1 letter = dot v0 (drop (ord letter - ord 'A') (cycle v1)) + +-- Find decoding offset that results in best match +-- between actual char frequencies and expected frequencies. +getKeyChar :: RealFrac a => [a] -> String -> Char +getKeyChar expected sample = + let actual = fmap (fromIntegral . countChar sample) ['A'..'Z'] + in maximumBy (comparing $ rotateAndDot expected actual) ['A'..'Z'] + +main = do + let cr = filter (/=' ') crypt + -- Assume that if there are less than 20 characters + -- per column, the key's too long to guess + distributions = fmap (distribute cr) [1..length cr `div` 20] + bestDistribution = maximumBy (comparing rate) distributions + key = fmap (getKeyChar englishFrequencies) bestDistribution + alphaSum a b = ['A'..'Z'] !! ((ord b - ord a) `mod` 26) + mapM_ putStrLn ["Key: " ++ key, "Decrypted Text: " ++ zipWith alphaSum (cycle key) cr] + +englishFrequencies = + [ 0.08167, 0.01492, 0.02782, 0.04253, + 0.12702, 0.02228, 0.02015, 0.06094, + 0.06966, 0.00153, 0.00772, 0.04025, + 0.02406, 0.06749, 0.07507, 0.01929, + 0.00095, 0.05987, 0.06327, 0.09056, + 0.02758, 0.00978, 0.02360, 0.00150, + 0.01974, 0.00074 ] + +crypt = "\ + \MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\ + \VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\ + \ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\ + \FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\ + \ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\ + \ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\ + \JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\ + \LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\ + \MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\ + \QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\ + \RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\ + \TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\ + \SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\ + \ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\ + \BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\ + \BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\ + \FWAML ZZRXJ EKAHV FASMU LVVUT TGK\ + \" diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Haskell/vigen-re-cipher-cryptanalysis-2.hs b/Task/Vigen-re-cipher-Cryptanalysis/Haskell/vigen-re-cipher-cryptanalysis-2.hs new file mode 100644 index 0000000000..51bc21ee85 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Haskell/vigen-re-cipher-cryptanalysis-2.hs @@ -0,0 +1,4 @@ +import Data.Map (fromListWith, toList) + +main = + mapM_ print (toList (fromListWith (+) (flip (,) 1 <$> filter (' ' /=) crypt))) diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Kotlin/vigen-re-cipher-cryptanalysis.kotlin b/Task/Vigen-re-cipher-Cryptanalysis/Kotlin/vigen-re-cipher-cryptanalysis.kotlin new file mode 100644 index 0000000000..bd40aa3473 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Kotlin/vigen-re-cipher-cryptanalysis.kotlin @@ -0,0 +1,102 @@ +// version 1.1.3 + +val encoded = + "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" + + "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" + + "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" + + "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" + + "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" + + "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" + + "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" + + "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" + + "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" + + "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" + + "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" + + "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" + + "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" + + "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" + + "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" + + "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" + + "FWAML ZZRXJ EKAHV FASMU LVVUT TGK" + +val freq = doubleArrayOf( + 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, + 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, + 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, + 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 +) + +fun bestMatch(a: DoubleArray): Int { + val sum = a.sum() + var bestFit = 1e100 + var bestRotate = 0 + for (rotate in 0..25) { + var fit = 0.0 + for (i in 0..25) { + val d = a[(i + rotate) % 26] / sum - freq[i] + fit += d * d / freq[i] + } + if (fit < bestFit) { + bestFit = fit + bestRotate = rotate + } + } + return bestRotate +} + +fun freqEveryNth(msg: IntArray, key: CharArray): Double { + val len = msg.size + val interval = key.size + val out = DoubleArray(26) + val accu = DoubleArray(26) + for (j in 0 until interval) { + out.fill(0.0) + for (i in j until len step interval) out[msg[i]]++ + val rot = bestMatch(out) + key[j] = (rot + 65).toChar() + for (i in 0..25) accu[i] += out[(i + rot) % 26] + } + val sum = accu.sum() + var ret = 0.0 + for (i in 0..25) { + val d = accu[i] / sum - freq[i] + ret += d * d / freq[i] + } + return ret +} + +fun decrypt(text: String, key: String): String { + val sb = StringBuilder() + var ki = 0 + for (c in text) { + if (c !in 'A'..'Z') continue + val ci = (c.toInt() - key[ki].toInt() + 26) % 26 + sb.append((ci + 65).toChar()) + ki = (ki + 1) % key.length + } + return sb.toString() +} + +fun main(args: Array) { + val enc = encoded.replace(" ", "") + val txt = IntArray(enc.length) { enc[it] - 'A' } + var bestFit = 1e100 + var bestKey = "" + val f = "%f %2d %s" + println(" Fit Length Key") + for (j in 1..26) { + val key = CharArray(j) + val fit = freqEveryNth(txt, key) + val sKey = key.joinToString("") + print(f.format(fit, j, sKey)) + if (fit < bestFit) { + bestFit = fit + bestKey = sKey + print(" <--- best so far") + } + println() + } + println() + println("Best key : $bestKey") + println("\nDecrypted text:\n${decrypt(enc, bestKey)}") +} diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Phix/vigen-re-cipher-cryptanalysis.phix b/Task/Vigen-re-cipher-Cryptanalysis/Phix/vigen-re-cipher-cryptanalysis.phix new file mode 100644 index 0000000000..ef12f0b714 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Phix/vigen-re-cipher-cryptanalysis.phix @@ -0,0 +1,208 @@ +-- +-- demo\rosetta\Cryptanalysis.exw +-- +atom t0 = time() +constant ciphertext = substitute_all(""" +MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH +VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD +ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS +FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG +ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ +ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS +JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT +LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST +MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH +QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV +RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW +TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO +SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR +ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX +BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB +BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA +FWAML ZZRXJ EKAHV FASMU LVVUT TGK""",{" ","\n"},{"",""}) + +constant letters = new_dict( + {{'E',12.702}, + {'T',9.056}, + {'A',8.167}, + {'O',7.507}, + {'I',6.966}, + {'N',6.749}, + {'S',6.327}, + {'H',6.094}, + {'R',5.987}, + {'D',4.253}, + {'L',4.025}, + {'C',2.782}, + {'U',2.758}, + {'M',2.406}, + {'W',2.361}, + {'F',2.228}, + {'G',2.015}, + {'Y',1.974}, + {'P',1.929}, + {'B',1.492}, + {'V',0.978}, + {'K',0.772}, + {'J',0.153}, + {'X',0.150}, + {'Q',0.095}, + {'Z',0.074}}) +constant digraphs = new_dict( + {{"TH",15.2}, + {"HE",12.8}, + {"IN",9.4}, + {"ER",9.4}, + {"AN",8.2}, + {"RE",6.8}, + {"ND",6.3}, + {"AT",5.9}, + {"ON",5.7}, + {"NT",5.6}, + {"HA",5.6}, + {"ES",5.6}, + {"ST",5.5}, + {"EN",5.5}, + {"ED",5.3}, + {"TO",5.2}, + {"IT",5.0}, + {"OU",5.0}, + {"EA",4.7}, + {"HI",4.6}, + {"IS",4.6}, + {"OR",4.3}, + {"TI",3.4}, + {"AS",3.3}, + {"TE",2.7}, + {"ET",1.9}, + {"NG",1.8}, + {"OF",1.6}, + {"AL",0.9}, + {"DE",0.9}, + {"SE",0.8}, + {"LE",0.8}, + {"SA",0.6}, + {"SI",0.5}, + {"AR",0.4}, + {"VE",0.4}, + {"RA",0.4}, + {"LD",0.2}, + {"UR",0.2}}) +constant trigraphs = new_dict( + {{"THE",18.1}, + {"AND",7.3}, + {"ING",7.2}, + {"ION",4.2}, + {"ENT",4.2}, + {"HER",3.6}, + {"FOR",3.4}, + {"THA",3.3}, + {"NTH",3.3}, + {"INT",3.2}, + {"TIO",3.1}, + {"ERE",3.1}, + {"TER",3.0}, + {"EST",2.8}, + {"ERS",2.8}, + {"HAT",2.6}, + {"ATI",2.6}, + {"ATE",2.5}, + {"ALL",2.5}, + {"VER",2.4}, + {"HIS",2.4}, + {"HES",2.4}, + {"ETH",2.4}, + {"OFT",2.2}, + {"STH",2.1}, + {"RES",2.1}, + {"OTH",2.1}, + {"ITH",2.1}, + {"FTH",2.1}, + {"ONT",2.0}}) + +function decrypt(string enc, string key) +integer keylen = length(key), k = 1 + string msg = repeat(' ', length(enc)) + for i=1 to length(enc) do + msg[i] = mod(enc[i]-key[k]+26,26)+'A' + k = mod(k,keylen)+1 + end for + return msg +end function + +function cryptanalyze(string enc, integer maxkeylen=20) + integer enclen = length(enc) + string maxkey = "", + maxdec = "", + k1 = " " + atom maxscore = 0.0 + + for keylen=1 to maxkeylen do + string key = repeat(' ',keylen) + sequence idx = {} + for i=1 to enclen do + if mod(i,keylen)=0 then + idx &= i-keylen+1 + end if + end for + + for i=1 to keylen do + atom maxsubscore = 0.0 + + for j='A' to 'Z' do + atom subscore = 0.0 + + k1[1] = j + string encidx = "" + for ii=1 to length(idx) do + encidx &= enc[idx[ii]] + end for + string dec = decrypt(encidx,k1) + for di=1 to length(dec) do + subscore += getd(dec[di],letters) + end for + + if subscore > maxsubscore then + maxsubscore = subscore + key[i] = j + end if + end for + + idx = sq_add(idx,1) + end for + + string dec = decrypt(enc, key) + atom score = 0.0 + + for i=1 to length(dec) do + score += getd(dec[i],letters) + end for + + for i=1 to enclen - 2 do + string digraph = dec[i..i+1] + string trigraph = dec[i..i + 2] + score += 2 * getd(digraph,digraphs) + score += 3 * getd(trigraph,trigraphs) + end for + + if score > maxscore then + maxscore = score + maxkey = key + maxdec = dec + end if + end for + + return {maxkey,maxdec} +end function + +function fold(string s, integer w) + for i=w to length(s) by w do + s[i..i-1] = "\n" + end for + return s +end function + +string {key, dec} = cryptanalyze(ciphertext) +printf(1,"key: %s\n\n%s\n\n", {key, fold(dec,80)}) + +printf(1,"elapsed time: %3.2f seconds",{time()-t0}) diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Zkl/vigen-re-cipher-cryptanalysis-1.zkl b/Task/Vigen-re-cipher-Cryptanalysis/Zkl/vigen-re-cipher-cryptanalysis-1.zkl new file mode 100644 index 0000000000..dbd56e2348 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Zkl/vigen-re-cipher-cryptanalysis-1.zkl @@ -0,0 +1,62 @@ +var[const] uppercase=["A".."Z"].pump(String), + english_frequences=T( // A..Z + 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, + 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, + 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, + 0.00978, 0.02360, 0.00150, 0.01974, 0.00074); + +fcn vigenere_decrypt(target_freqs, input){ // ( (float,...), string) + nchars,ordA :=uppercase.len(),"A".toAsc(); + sorted_targets:=target_freqs.sort(); + + frequency:='wrap(input){ // (n,n,n,n,...), n is ASCII index ("A"==65) + result:=uppercase.pump(List(),List.fp1(0)); // ( ("A",0),("B",0) ...) + foreach c in (input){ result[c - ordA][1] += 1 } + result // --> mutable list of mutable lists ( ("A",Int)...("Z",Int) ) + }; + correlation:='wrap(input){ // (n,n,n,n,...), n is ASCII index ("A"==65) + result,freq:=0.0, frequency(input); + freq.sort(fcn([(_,a)],[(_,b)]){ aFloat + }; + + cleaned:=input.toUpper().pump(List,uppercase.holds,Void.Filter,"toAsc"); + + best_len,best_corr := 0,-100.0; + # Assume that if there are less than 20 characters + # per column, the key's too long to guess + foreach i in ([2..cleaned.len()/20]){ + pieces:=(i).pump(List,List.copy); // ( (),() ... ) + foreach c in (cleaned){ pieces[__cWalker.idx%i].append(c) } + + # The correlation seems to increase for smaller + # pieces/longer keys, so weigh against them a little + corr:=-0.5*i + pieces.apply(correlation).sum(0.0); + if(corr>best_corr) best_len,best_corr=i,corr; + } + if(best_len==0) return("Text is too short to analyze", ""); + + pieces:=best_len.pump(List,List.copy); + foreach c in (cleaned){ pieces[__cWalker.idx%best_len].append(c) } + + key,freqs := "",pieces.apply(frequency); + foreach fr in (freqs){ + fr.sort(fcn([(_,a)],[(_,b)]){ a>b }); // reverse sort by freq + m,max_corr := 0,0.0; + foreach j in (nchars){ + corr,c := 0.0,ordA + j; + foreach frc in (fr){ + d:=(frc[0].toAsc() - c + nchars) % nchars; + corr+=target_freqs[d]*frc[1]; + if(corr>max_corr) m,max_corr=j,corr; + } + } + key+=(m + ordA).toChar(); + } + + cleaned.enumerate().apply('wrap([(i,c])){ + ( (c - (key[i%best_len]).toAsc() + nchars)%nchars + ordA ).toChar() + }).concat() : + T(key,_); +} diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Zkl/vigen-re-cipher-cryptanalysis-2.zkl b/Task/Vigen-re-cipher-Cryptanalysis/Zkl/vigen-re-cipher-cryptanalysis-2.zkl new file mode 100644 index 0000000000..b49ddf4057 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Zkl/vigen-re-cipher-cryptanalysis-2.zkl @@ -0,0 +1,23 @@ +encryptedText:= +#<<< +"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH +VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD +ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS +FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG +ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ +ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS +JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT +LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST +MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH +QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV +RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW +TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO +SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR +ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX +BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB +BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA +FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; +#<<< +key,decoded:=vigenere_decrypt(english_frequences,encryptedText); +println("Key:", key); +println("Decoded text:", decoded); diff --git a/Task/Vigen-re-cipher/C/vigen-re-cipher-1.c b/Task/Vigen-re-cipher/C/vigen-re-cipher-1.c deleted file mode 100644 index 36760f589e..0000000000 --- a/Task/Vigen-re-cipher/C/vigen-re-cipher-1.c +++ /dev/null @@ -1,56 +0,0 @@ -#include -#include -#include -#include - -void upper_case(char *src) -{ - while (*src != '\0') { - if (islower(*src)) *src &= ~0x20; - src++; - } -} - -char* encipher(const char *src, char *key, int is_encode) -{ - int i, klen, slen; - char *dest; - - dest = strdup(src); - upper_case(dest); - upper_case(key); - - /* strip out non-letters */ - for (i = 0, slen = 0; dest[slen] != '\0'; slen++) - if (isupper(dest[slen])) - dest[i++] = dest[slen]; - - dest[slen = i] = '\0'; /* null pad it, make it safe to use */ - - klen = strlen(key); - for (i = 0; i < slen; i++) { - if (!isupper(dest[i])) continue; - dest[i] = 'A' + (is_encode - ? dest[i] - 'A' + key[i % klen] - 'A' - : dest[i] - key[i % klen] + 26) % 26; - } - - return dest; -} - -int main() -{ - const char *str = "Beware the Jabberwock, my son! The jaws that bite, " - "the claws that catch!"; - const char *cod, *dec; - char key[] = "VIGENERECIPHER"; - - printf("Text: %s\n", str); - printf("key: %s\n", key); - - cod = encipher(str, key, 1); printf("Code: %s\n", cod); - dec = encipher(cod, key, 0); printf("Back: %s\n", dec); - - /* free(dec); free(cod); */ /* nah */ - return 0; -} diff --git a/Task/Vigen-re-cipher/C/vigen-re-cipher-2.c b/Task/Vigen-re-cipher/C/vigen-re-cipher-2.c deleted file mode 100644 index 98b82cf348..0000000000 --- a/Task/Vigen-re-cipher/C/vigen-re-cipher-2.c +++ /dev/null @@ -1,4 +0,0 @@ -Text: Beware the Jabberwock, my son! The jaws that bite, the claws that catch! -key: VIGENERECIPHER -Code: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY -Back: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH diff --git a/Task/Vigen-re-cipher/Common-Lisp/vigen-re-cipher-1.lisp b/Task/Vigen-re-cipher/Common-Lisp/vigen-re-cipher-1.lisp deleted file mode 100644 index bae0b77dba..0000000000 --- a/Task/Vigen-re-cipher/Common-Lisp/vigen-re-cipher-1.lisp +++ /dev/null @@ -1,26 +0,0 @@ -(defun strip (s) - (remove-if-not - (lambda (c) (char<= #\A c #\Z)) - (string-upcase s))) - -(defun vigenère (s key &key decipher - &aux (A (char-code #\A)) - (op (if decipher #'- #'+))) - (labels - ((to-char (c) (code-char (+ c A))) - (to-code (c) (- (char-code c) A))) - (let ((k (map 'list #'to-code (strip key)))) - (setf (cdr (last k)) k) - (map 'string - (lambda (c) - (prog1 - (to-char - (mod (funcall op (to-code c) (car k)) 26)) - (setf k (cdr k)))) - (strip s))))) - -(let* ((msg "Beware the Jabberwock... The jaws that... the claws that catch!") - (key "vigenere cipher") - (enc (vigenère msg key)) - (dec (vigenère enc key :decipher t))) - (format t "msg: ~a~%enc: ~a~%dec: ~a~%" msg enc dec)) diff --git a/Task/Vigen-re-cipher/Common-Lisp/vigen-re-cipher-2.lisp b/Task/Vigen-re-cipher/Common-Lisp/vigen-re-cipher-2.lisp deleted file mode 100644 index 42b5098c24..0000000000 --- a/Task/Vigen-re-cipher/Common-Lisp/vigen-re-cipher-2.lisp +++ /dev/null @@ -1,3 +0,0 @@ -msg: Beware the Jabberwock... The jaws that... the claws that catch! -enc: WMCEEIKLGRPIFVMEUGXXYILILZXYVBZLRGCEYAIOEKXIZGU -dec: BEWARETHEJABBERWOCKTHEJAWSTHATTHECLAWSTHATCATCH diff --git a/Task/Vigen-re-cipher/Kotlin/vigen-re-cipher.kotlin b/Task/Vigen-re-cipher/Kotlin/vigen-re-cipher.kotlin new file mode 100644 index 0000000000..bf1386f1ba --- /dev/null +++ b/Task/Vigen-re-cipher/Kotlin/vigen-re-cipher.kotlin @@ -0,0 +1,26 @@ +// version 1.1.3 + +fun vigenere(text: String, key: String, encrypt: Boolean = true): String { + val t = if (encrypt) text.toUpperCase() else text + val sb = StringBuilder() + var ki = 0 + for (c in t) { + if (c !in 'A'..'Z') continue + val ci = if (encrypt) + (c.toInt() + key[ki].toInt() - 130) % 26 + else + (c.toInt() - key[ki].toInt() + 26) % 26 + sb.append((ci + 65).toChar()) + ki = (ki + 1) % key.length + } + return sb.toString() +} + +fun main(args: Array) { + val key = "VIGENERECIPHER" + val text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" + val encoded = vigenere(text, key) + println(encoded) + val decoded = vigenere(encoded, key, false) + println(decoded) +} diff --git a/Task/Vigen-re-cipher/OoRexx/vigen-re-cipher.rexx b/Task/Vigen-re-cipher/OoRexx/vigen-re-cipher.rexx new file mode 100644 index 0000000000..57a9594e30 --- /dev/null +++ b/Task/Vigen-re-cipher/OoRexx/vigen-re-cipher.rexx @@ -0,0 +1,194 @@ +/* Rexx */ +Do + alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + key = 'LEMON' + + pt = 'Attack at dawn!' + Call test key, pt + + key = 'N' + Call test key, pt + + key = 'B' + Call test key, pt + + pt = alpha + key = 'A' + Call test key, pt + + pt = sampledata() + key = 'Hamlet; Prince of Denmark' + Call test key, pt + + Return +End +Exit + +vigenere: +Procedure Expose alpha +Do + Parse upper Arg meth, key, text + + Select + When 'ENCIPHER'~abbrev(meth, 1) = 1 then df = 1 + When 'DECIPHER'~abbrev(meth, 1) = 1 then df = -1 + Otherwise Do + Say meth 'invalid. Must be "ENCIPHER" or "DECIPHER"' + Exit + End + End + + text = stringscrubber(text) + key = stringscrubber(key) + code = '' + + Do l_ = 1 to text~length() + M = alpha~pos(text~substr(l_, 1)) - 1 + k_ = (l_ - 1) // key~length() + K = alpha~pos(key~substr(k_ + 1, 1)) - 1 + C = mod((M + K * df), alpha~length()) + C = alpha~substr(C + 1, 1) + code = code || C + End l_ + + Return code + + Return +End +Exit + +vigenere_encipher: +Procedure Expose alpha +Do + Parse upper Arg key, plaintext + + Return vigenere('ENCIPHER', key, plaintext) +End +Exit + +vigenere_decipher: +Procedure Expose alpha +Do + Parse upper Arg key, ciphertext + + Return vigenere('DECIPHER', key, ciphertext) +End +Exit + +mod: +Procedure +Do + Parse Arg N, D + + Return (D + (N // D)) // D +End +Exit + +stringscrubber: +Procedure Expose alpha +Do + Parse upper Arg cleanup + + cleanup = cleanup~space(0) + Do label f_ forever + x_ = cleanup~verify(alpha) + If x_ = 0 then Leave f_ + cleanup = cleanup~changestr(cleanup~substr(x_, 1), '') + end f_ + + Return cleanup +End +Exit + +test: +Procedure Expose alpha +Do + Parse Arg key, pt + + ct = vigenere_encipher(key, pt) + Call display ct + dt = vigenere_decipher(key, ct) + Call display dt + + Return +End +Exit + +display: +Procedure +Do + Parse Arg text + + line = '' + o_ = 0 + Do c_ = 1 to text~length() + b_ = o_ // 5 + o_ = o_ + 1 + If b_ = 0 then line = line' ' + line = line || text~substr(c_, 1) + End c_ + + Say '....+....|'~copies(8) + Do label l_ forever + Parse Var line w1 w2 w3 w4 w5 w6 W7 w8 w9 w10 w11 w12 line + pline = w1 w2 w3 w4 w5 w6 w7 w8 w9 w10 w11 w12 + Say pline~strip() + If line~strip()~length() = 0 then Leave l_ + End l_ + Say + + Return +End +Exit + +sampledata: +Procedure +Do + + NL = '0a'x + X = 0 + antic_disposition. = '' + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "To be, or not to be--that is the question:" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Whether 'tis nobler in the mind to suffer" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "The slings and arrows of outrageous fortune" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Or to take arms against a sea of troubles" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "And by opposing end them. To die, to sleep--" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "No more--and by a sleep to say we end" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "The heartache, and the thousand natural shocks" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "That flesh is heir to. 'Tis a consummation" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Devoutly to be wished. To die, to sleep--" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "To sleep--perchance to dream: ay, there's the rub," + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "For in that sleep of death what dreams may come" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "When we have shuffled off this mortal coil," + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Must give us pause. There's the respect" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "That makes calamity of so long life." + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "For who would bear the whips and scorns of time," + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Th' oppressor's wrong, the proud man's contumely" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "The pangs of despised love, the law's delay," + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "The insolence of office, and the spurns" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "That patient merit of th' unworthy takes," + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "When he himself might his quietus make" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "With a bare bodkin? Who would fardels bear," + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "To grunt and sweat under a weary life," + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "But that the dread of something after death," + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "The undiscovered country, from whose bourn" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "No traveller returns, puzzles the will," + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "And makes us rather bear those ills we have" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Than fly to others that we know not of?" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Thus conscience does make cowards of us all," + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "And thus the native hue of resolution" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Is sicklied o'er with the pale cast of thought," + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "And enterprise of great pith and moment" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "With this regard their currents turn awry" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "And lose the name of action. -- Soft you now," + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "The fair Ophelia! -- Nymph, in thy orisons" + X = X + 1; antic_disposition.0 = X; antic_disposition.X = "Be all my sins remembered." + + melancholy_dane = '' + Do l_ = 1 for antic_disposition.0 + melancholy_dane = melancholy_dane || antic_disposition.l_ || NL + End l_ + + Return melancholy_dane +End +Exit diff --git a/Task/Vigen-re-cipher/Phix/vigen-re-cipher.phix b/Task/Vigen-re-cipher/Phix/vigen-re-cipher.phix new file mode 100644 index 0000000000..e978a67b9b --- /dev/null +++ b/Task/Vigen-re-cipher/Phix/vigen-re-cipher.phix @@ -0,0 +1,22 @@ +enum type mode ENCRYPT = +1, DECRYPT = -1 end type + +function Vigenere(string s, string key, mode m) +string res = "" +integer k = 1, ch + s = upper(s) + for i=1 to length(s) do + ch = s[i] + if ch>='A' and ch<='Z' then + res &= 'A'+mod(ch+m*(key[k]+26),26) + k = mod(k,length(key))+1 + end if + end for + return res +end function + +constant key = "LEMON", + s = "ATTACK AT DAWN", + e = Vigenere(s,key,ENCRYPT), + d = Vigenere(e,key,DECRYPT) + +printf(1,"Original: %s\nEncrypted: %s\nDecrypted: %s\n",{s,e,d}) diff --git a/Task/Vigen-re-cipher/Sidef/vigen-re-cipher.sidef b/Task/Vigen-re-cipher/Sidef/vigen-re-cipher.sidef index c3428624ed..b5d7cf5610 100644 --- a/Task/Vigen-re-cipher/Sidef/vigen-re-cipher.sidef +++ b/Task/Vigen-re-cipher/Sidef/vigen-re-cipher.sidef @@ -1,12 +1,12 @@ -func s2v(s) { s.uc.scan(/[A-Z]/)»ord»() »-» 65 }; -func v2s(v) { (v »%» 26 »+» 65)»chr»().join }; - -func blacken (red, key) { v2s(s2v(red) »+« s2v(key)) }; -func redden (blk, key) { v2s(s2v(blk) »-« s2v(key)) }; - -var red = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; -var key = "Vigenere Cipher!!!"; - -say red; -say (var black = blacken(red, key)); -say redden(black, key); +func s2v(s) { s.uc.scan(/[A-Z]/).map{.ord} »-» 65 } +func v2s(v) { v »%» 26 »+» 65 -> map{.chr}.join } +  +func blacken (red, key) { v2s(s2v(red) »+« s2v(key)) } +func redden (blk, key) { v2s(s2v(blk) »-« s2v(key)) } +  +var red = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" +var key = "Vigenere Cipher!!!" +  +say red +say (var black = blacken(red, key)) +say redden(black, key) diff --git a/Task/Vigen-re-cipher/Zkl/vigen-re-cipher-1.zkl b/Task/Vigen-re-cipher/Zkl/vigen-re-cipher-1.zkl new file mode 100644 index 0000000000..428d5f4447 --- /dev/null +++ b/Task/Vigen-re-cipher/Zkl/vigen-re-cipher-1.zkl @@ -0,0 +1,12 @@ +fcn encipher(src,key,is_encode){ + upperCase:=["A".."Z"].pump(String); + src=src.toUpper().inCommon(upperCase); // only uppercase + key=key.toUpper().inCommon(upperCase).pump(List,"toAsc"); + + const A="A".toAsc(); + klen:=Walker.cycle(key.len()); // 0,1,2,3,..,keyLen-1,0,1,2,3, ... + src.pump(String,'wrap(c){ i:=klen.next(); c=c.toAsc(); + (A + ( if(is_encode) c - A + key[i] - A; + else c - key[i] + 26 ) % 26).toChar() + }); +} diff --git a/Task/Vigen-re-cipher/Zkl/vigen-re-cipher-2.zkl b/Task/Vigen-re-cipher/Zkl/vigen-re-cipher-2.zkl new file mode 100644 index 0000000000..7b4fa6824e --- /dev/null +++ b/Task/Vigen-re-cipher/Zkl/vigen-re-cipher-2.zkl @@ -0,0 +1,9 @@ +str := "Beware the Jabberwock, my son! The jaws that bite, " + "the claws that catch!"; +key := "Vigenere Cipher"; + +println("Text: ", str); +println("key: ", key); + +cod := encipher(str, key, True); println("Code: ", cod); +dec := encipher(cod, key, False); println("Back: ", dec); diff --git a/Task/Visualize-a-tree/Elena/visualize-a-tree.elena b/Task/Visualize-a-tree/Elena/visualize-a-tree.elena index d8a2158d2d..1169d1b473 100644 --- a/Task/Visualize-a-tree/Elena/visualize-a-tree.elena +++ b/Task/Visualize-a-tree/Elena/visualize-a-tree.elena @@ -1,62 +1,67 @@ -#import system. -#import system'routines. -#import extensions. +import system'routines. +import extensions. -#class Node +class Node { - #field theValue. - #field theChildren. + object theValue. + object theChildren. - #constructor new : value &children:children + constructor new : value children:children [ theValue := value. + theChildren := children toArray. ] - #constructor new : value - <= new:value &children:nil. + constructor new : value + <= new:value children:nil. - #constructor new &children:children - <= new:emptyLiteralValue &children:children. + constructor new children:children + <= new:emptyLiteralValue children:children. - #constructor new : value &child:child - <= new:value &children:(Array new &object:child). + constructor new : value child:child + <= new:value children(Array new object:child). - #method get = theValue. + get = theValue. - #method children = theChildren. + children = theChildren. } -#class(extension)treeOp +extension treeOp { - #method writeTree:node:prefix &subject:childrenProp + writeTree : node : prefix : childrenProp [ - #var children := node::childrenProp get. - #var length := children length. - children zip:(RangeEnumerator new &from:1 &to:length) &eachPair:(:child:index) - [ - self writeLine:prefix:"|". - self writeLine:prefix:"+---":(child get). - #var nodeLine := prefix + (index==length)iif:" ":"| ". + var children := node~childrenProp get. + var length := children length. - self writeTree:child:nodeLine &subject:childrenProp. + children zip(RangeEnumerator new from:1 to:length) forEach(:child:index) + [ + self printLine(prefix,"|"). + self printLine(prefix,"+---",child get). + + var nodeLine := prefix + (index==length)iif(" ","| "). + + self writeTree(child,nodeLine,childrenProp). ]. + ^ self. ] - #method writeTree:node &subject:childrenProp - = self writeTree:node:"" &subject:childrenProp. + writeTree : node : childrenProp + = self~treeOp writeTree(node,"",childrenProp). } -#symbol program = +program = [ - #var tree := Node new &children: + var tree := Node new children: ( - Node new:"a" &children: + Node new:"a" children: ( - Node new:"c" &child:(Node new:"d"), + Node new:"b" child:(Node new:"c"), Node new:"d" ), - Node new:"b"). - console writeTree:tree &subject:%children. + Node new:"e" + ). + + console writeTree(tree, %children); readChar. ]. diff --git a/Task/Visualize-a-tree/Perl-6/visualize-a-tree.pl6 b/Task/Visualize-a-tree/Perl-6/visualize-a-tree.pl6 index f51f768d09..f9690634e7 100644 --- a/Task/Visualize-a-tree/Perl-6/visualize-a-tree.pl6 +++ b/Task/Visualize-a-tree/Perl-6/visualize-a-tree.pl6 @@ -4,7 +4,7 @@ sub visualize-tree($tree, &label, &children, :@end = ('└─', ' '), ) { sub visit($node, *@pre) { - gather { + | gather { take @pre[0] ~ label($node); my @children := children($node); my $end = @children.end; diff --git a/Task/Visualize-a-tree/Zkl/visualize-a-tree.zkl b/Task/Visualize-a-tree/Zkl/visualize-a-tree.zkl new file mode 100644 index 0000000000..cfec7f5dc7 --- /dev/null +++ b/Task/Visualize-a-tree/Zkl/visualize-a-tree.zkl @@ -0,0 +1,20 @@ +fcn vaultDir(out=Console){ + const INDENT=" "; + space:=""; lastPath:=L(); + foreach fullname in (TheVault.BaseClass.contents.sort()){ + path:=fullname.split("."); name:=path.pop(); + if(lastPath==path) out.writeln(space,name); + else{ + n:=0; p:=path.copy(); + try{ + while(path[0]==lastPath[0]) + { n+=1; path.pop(0); lastPath.pop(0); } + }catch{} + space=INDENT*n; + foreach dir in (path){ out.writeln(space,dir); space+=INDENT; } + out.writeln(space,name); + lastPath=p; + } + } + "" // so startup has something to display +} diff --git a/Task/Vogels-approximation-method/Kotlin/vogels-approximation-method.kotlin b/Task/Vogels-approximation-method/Kotlin/vogels-approximation-method.kotlin new file mode 100644 index 0000000000..988ac5017e --- /dev/null +++ b/Task/Vogels-approximation-method/Kotlin/vogels-approximation-method.kotlin @@ -0,0 +1,90 @@ +// version 1.1.3 + +val supply = intArrayOf(50, 60, 50, 50) +val demand = intArrayOf(30, 20, 70, 30, 60) + +val costs = arrayOf( + intArrayOf(16, 16, 13, 22, 17), + intArrayOf(14, 14, 13, 19, 15), + intArrayOf(19, 19, 20, 23, 50), + intArrayOf(50, 12, 50, 15, 11) +) + +val nRows = supply.size +val nCols = demand.size + +val rowDone = BooleanArray(nRows) +val colDone = BooleanArray(nCols) +val results = Array(nRows) { IntArray(nCols) } + +fun nextCell(): IntArray { + val res1 = maxPenalty(nRows, nCols, true) + val res2 = maxPenalty(nCols, nRows, false) + if (res1[3] == res2[3]) + return if (res1[2] < res2[2]) res1 else res2 + return if (res1[3] > res2[3]) res2 else res1 +} + +fun diff(j: Int, len: Int, isRow: Boolean): IntArray { + var min1 = Int.MAX_VALUE + var min2 = min1 + var minP = -1 + for (i in 0 until len) { + val done = if (isRow) colDone[i] else rowDone[i] + if (done) continue + val c = if (isRow) costs[j][i] else costs[i][j] + if (c < min1) { + min2 = min1 + min1 = c + minP = i + } + else if (c < min2) min2 = c + } + return intArrayOf(min2 - min1, min1, minP) +} + +fun maxPenalty(len1: Int, len2: Int, isRow: Boolean): IntArray { + var md = Int.MIN_VALUE + var pc = -1 + var pm = -1 + var mc = -1 + for (i in 0 until len1) { + val done = if (isRow) rowDone[i] else colDone[i] + if (done) continue + val 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 if (isRow) intArrayOf(pm, pc, mc, md) else + intArrayOf(pc, pm, mc, md) +} + +fun main(args: Array) { + var supplyLeft = supply.sum() + var totalCost = 0 + while (supplyLeft > 0) { + val cell = nextCell() + val r = cell[0] + val c = cell[1] + val q = minOf(demand[c], supply[r]) + demand[c] -= q + if (demand[c] == 0) colDone[c] = true + supply[r] -= q + if (supply[r] == 0) rowDone[r] = true + results[r][c] = q + supplyLeft -= q + totalCost += q * costs[r][c] + } + + println(" A B C D E") + for ((i, result) in results.withIndex()) { + print(('W'.toInt() + i).toChar()) + for (item in result) print(" %2d".format(item)) + println() + } + println("\nTotal Cost = $totalCost") +} diff --git a/Task/Vogels-approximation-method/Zkl/vogels-approximation-method-1.zkl b/Task/Vogels-approximation-method/Zkl/vogels-approximation-method-1.zkl new file mode 100644 index 0000000000..b87b6e80ec --- /dev/null +++ b/Task/Vogels-approximation-method/Zkl/vogels-approximation-method-1.zkl @@ -0,0 +1,7 @@ +costs:=Dictionary( + "W",Dictionary("A",16, "B",16, "C",13, "D",22, "E",17), + "X",Dictionary("A",14, "B",14, "C",13, "D",19, "E",15), + "Y",Dictionary("A",19, "B",19, "C",20, "D",23, "E",50), + "Z",Dictionary("A",50, "B",12, "C",50, "D",15, "E",11)).makeReadOnly(); +demand:=Dictionary("A",30, "B",20, "C",70, "D",30, "E",60); // gonna be modified +supply:=Dictionary("W",50, "X",60, "Y",50, "Z",50); // gonna be modified diff --git a/Task/Vogels-approximation-method/Zkl/vogels-approximation-method-2.zkl b/Task/Vogels-approximation-method/Zkl/vogels-approximation-method-2.zkl new file mode 100644 index 0000000000..72f6eae549 --- /dev/null +++ b/Task/Vogels-approximation-method/Zkl/vogels-approximation-method-2.zkl @@ -0,0 +1,14 @@ +cols:=demand.keys.sort(); +res :=vogel(costs,supply,demand); +cost:=0; +println("\t",cols.concat("\t")); +foreach g in (costs.keys.sort()){ + print(g,"\t"); + foreach n in (cols){ + y:=res[g].find(n); + if(y){ y=y[0]; print(y); cost+=y*costs[g][n]; } + print("\t"); + } + println(); +} +println("\nTotal Cost = ",cost); diff --git a/Task/Vogels-approximation-method/Zkl/vogels-approximation-method-3.zkl b/Task/Vogels-approximation-method/Zkl/vogels-approximation-method-3.zkl new file mode 100644 index 0000000000..a1a55a1fad --- /dev/null +++ b/Task/Vogels-approximation-method/Zkl/vogels-approximation-method-3.zkl @@ -0,0 +1,30 @@ +fcn vogel(costs,supply,demand){ + // a Dictionary can be created via a list of (k,v) pairs + res:= Dictionary(costs.pump(List,fcn([(k,_)]){ return(k,D()) })); + g := Dictionary(); // cross index costs and make writable + supply.pump(Void,'wrap([(k,_)]){ g[k] = + costs[k].keys.sort('wrap(a,b){ costs[k][a]s[t]) T(f,g[f][0]) else T(g[t][0],t)); + v:=supply[f].min(demand[t]); + res[f].appendV(t,v); // create t:(v) or append v to t:(...) + if(0 == (demand[t]-=v)){ + supply.pump(Void,'wrap([(k,n)]){ if(n!=0) g[k].remove(t) }); + g.del(t); demand.del(t); + } + if(0 == (supply[f]-=v)){ + demand.pump(Void,'wrap([(k,n)]){ if(n!=0) g[k].remove(f) }); + g.del(f); supply.del(f); + } + }//while + res +} diff --git a/Task/Voronoi-diagram/JavaScript/voronoi-diagram.js b/Task/Voronoi-diagram/JavaScript/voronoi-diagram.js new file mode 100644 index 0000000000..86fe31f537 --- /dev/null +++ b/Task/Voronoi-diagram/JavaScript/voronoi-diagram.js @@ -0,0 +1,62 @@ + + +Voronoi diagram + + + Please input number of sites: +    + Metric: +   +    +

    Voronoi diagram

    + + + diff --git a/Task/Voronoi-diagram/Kotlin/voronoi-diagram.kotlin b/Task/Voronoi-diagram/Kotlin/voronoi-diagram.kotlin new file mode 100644 index 0000000000..3d8b0d777c --- /dev/null +++ b/Task/Voronoi-diagram/Kotlin/voronoi-diagram.kotlin @@ -0,0 +1,51 @@ +// version 1.1.3 + +import java.awt.Color +import java.awt.Graphics +import java.awt.Graphics2D +import java.awt.geom.Ellipse2D +import java.awt.image.BufferedImage +import java.util.Random +import javax.swing.JFrame + +fun distSq(x1: Int, x2: Int, y1: Int, y2: Int): Int { + val x = x1 - x2 + val y = y1 - y2 + return x * x + y * y +} + +class Voronoi(val cells: Int, val size: Int) : JFrame("Voronoi Diagram") { + val bi: BufferedImage + + init { + setBounds(0, 0, size, size) + defaultCloseOperation = EXIT_ON_CLOSE + val r = Random() + bi = BufferedImage(size, size, BufferedImage.TYPE_INT_RGB) + val px = IntArray(cells) { r.nextInt(size) } + val py = IntArray(cells) { r.nextInt(size) } + val cl = IntArray(cells) { r.nextInt(16777215) } + for (x in 0 until size) { + for (y in 0 until size) { + var n = 0 + for (i in 0 until cells) { + if (distSq(px[i], x, py[i], y) < distSq(px[n], x, py[n], y)) n = i + } + bi.setRGB(x, y, cl[n]) + } + } + val g = bi.createGraphics() + g.color = Color.BLACK + for (i in 0 until cells) { + g.fill(Ellipse2D.Double(px[i] - 2.5, py[i] - 2.5, 5.0, 5.0)) + } + } + + override fun paint(g: Graphics) { + g.drawImage(bi, 0, 0, this) + } +} + +fun main(args: Array) { + Voronoi(70, 700).isVisible = true +} diff --git a/Task/Voronoi-diagram/Phix/voronoi-diagram.phix b/Task/Voronoi-diagram/Phix/voronoi-diagram.phix new file mode 100644 index 0000000000..8a28d34031 --- /dev/null +++ b/Task/Voronoi-diagram/Phix/voronoi-diagram.phix @@ -0,0 +1,195 @@ +-- +-- demo\rosetta\VoronoiDiagram.exw +-- +include pGUI.e + +Ihandle dlg, canvas, timer +cdCanvas cddbuffer, cdcanvas + +-- Stop any current drawing process before starting a new one: +-- Without this it /is/ going to crash, if it tries to finish +-- drawing all 100 sites, when there are now only 50, for eg. +integer timer_active = 0 + +integer nsites = 200 +integer last_width = -1, last_height +sequence siteX, siteY, siteC + +enum EUCLID, MANHATTAN, MINKOWSKI + +constant dmodes = {"Euclid", "Manhattan", "Minkowski"} + +integer dmode = EUCLID, + drawn = 0 -- (last dmode actually shown) + +function distance(integer x1,y1, x2,y2) +atom d + x1 -= x2 + y1 -= y2 + switch dmode do + case EUCLID: d = x1*x1+y1*y1 -- (no need for sqrt) + case MANHATTAN: d = abs(x1)+abs(y1) + case MINKOWSKI: d = power(abs(x1),3)+power(abs(y1),3) -- ("" power(d,1/3)) + end switch + return d +end function + +sequence nearestIndex, dist + +function checkRow(integer site, integer x, integer height) +bool res = false +atom dxSquared + integer x1 = siteX[site]-x + switch dmode do + case EUCLID: dxSquared = x1*x1 + case MANHATTAN: dxSquared = abs(x1) + case MINKOWSKI: dxSquared = power(abs(x1),3) + end switch + for y=1 to height do +-- atom dSquared = distance(siteX[site],siteY[site],x,y) -- (sub-optimal..) + atom dSquared + integer y1 = siteY[site]-y + switch dmode do + case EUCLID: dSquared = dxSquared + y1*y1 + case MANHATTAN: dSquared = dxSquared + abs(y1) + case MINKOWSKI: dSquared = dxSquared + power(abs(y1),3) + end switch + if dSquared<=dist[x,y] then + dist[x,y] = dSquared + nearestIndex[x,y] = site + res = true + end if + end for + return res +end function + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) +integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") + if width!=last_width + or height!=last_height + or nsites!=length(siteX) then + if nsites<1 then nsites = 1 end if + siteX = sq_rand(repeat(width,nsites)) + siteY = sq_rand(repeat(height,nsites)) + siteC = sq_rand(repeat(#FFFFFF,nsites)) + last_width = width + last_height = height + drawn = 0 + end if + if drawn!=dmode -- (prevent double-draw, and) + and not timer_active then -- (drawing when rug moved..) + drawn = dmode + cdCanvasActivate(cddbuffer) + atom t0 = time(), t1 + t1 = time()+0.25 + nearestIndex = repeat(repeat(1,height),width) + dist = repeat(repeat(0,height),width) + -- fill distance table with distances from the first site + integer x1 = siteX[1], y1 = siteY[1] + for x=1 to width do + for y=1 to height do + dist[x,y] = distance(x1,y1,x,y) + end for + if timer_active then exit end if + end for + --for other towns + for i=2 to nsites do + -- look left + for x=siteX[i] to 1 by -1 do + if not checkRow(i, x, height) then exit end if + end for + -- look right + for x=siteX[i]+1 to width do + if not checkRow(i, x, height) then exit end if + end for + if timer_active then exit end if + if time()>t1 then + IupSetStrAttribute(dlg, "TITLE", "Voronoi diagram (generating - %3.2f%%)",{100*i/nsites}) + IupFlush() + t1 = time()+0.25 + end if + end for + t1 = time() + for y=1 to height do + integer nearest = nearestIndex[1,y] + integer s = 1 + for x=2 to width do + if nearestIndex[x,y]<>nearest then + cdCanvasSetForeground(cddbuffer, siteC[nearest]) + cdCanvasLine(cddbuffer, s-1, y-1, x-2, y-1) + nearest = nearestIndex[x,y] + s = x + end if + end for + if timer_active then exit end if + cdCanvasSetForeground(cddbuffer, siteC[nearest]) + cdCanvasLine(cddbuffer, s-1, y-1, width-1, y-1) + end for + if not timer_active then + cdCanvasSetForeground(cddbuffer, CD_BLACK) + for i=1 to nsites do + cdCanvasSector(cddbuffer, siteX[i], siteY[i], 2, 2, 0, 360) + end for + cdCanvasFlush(cddbuffer) + IupSetStrAttribute(dlg, "TITLE", "Voronoi diagram - %s, %dx%d, %d sites, %3.2fs",{dmodes[dmode],width,height,nsites,time()-t0}) + end if + end if + return IUP_DEFAULT +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + cdCanvasSetBackground(cddbuffer, CD_WHITE) + cdCanvasSetForeground(cddbuffer, CD_BLACK) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + integer wasdmode = dmode + switch c do + case '+': nsites *= 2 + case '-': nsites = max(floor(nsites/2),1) + case 'E','e': dmode = EUCLID + case 'M','m': dmode = MANHATTAN + case 'W','w': dmode = MINKOWSKI + end switch + if dmode!=wasdmode + or nsites!=length(siteX) then + -- give any current drawing process 0.1s to abandon: + timer_active = 1 + IupStoreAttribute(timer, "RUN", "YES") +-- IupUpdate(canvas) + end if + return IUP_CONTINUE +end function + +function timer_cb(Ihandle /*ih*/) + timer_active = 0 + IupStoreAttribute(timer, "RUN", "NO") + IupUpdate(canvas) + return IUP_IGNORE +end function + +procedure main() + IupOpen() + + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "600x400") -- initial size + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + + timer = IupTimer(Icallback("timer_cb"), 100, 0) -- (inactive) + + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", "Voronoi diagram") + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + + IupMap(dlg) + IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation + IupShowXY(dlg,IUP_CENTER,IUP_CENTER) + IupMainLoop() + IupClose() +end procedure +main() diff --git a/Task/Voronoi-diagram/R/voronoi-diagram.r b/Task/Voronoi-diagram/R/voronoi-diagram.r new file mode 100644 index 0000000000..e79c7a0cae --- /dev/null +++ b/Task/Voronoi-diagram/R/voronoi-diagram.r @@ -0,0 +1,51 @@ +## HF#1 Random Hex color +randHclr <- function() { + m=255;r=g=b=0; + r <- sample(0:m, 1, replace=TRUE); + g <- sample(0:m, 1, replace=TRUE); + b <- sample(0:m, 1, replace=TRUE); + return(rgb(r,g,b,maxColorValue=m)); +} +## HF#2 Metrics: Euclidean, Manhattan and Minkovski +Metric <- function(x, y, mt) { + if(mt==1) {return(sqrt(x*x + y*y))} + if(mt==2) {return(abs(x) + abs(y))} + if(mt==3) {return((abs(x)^3 + abs(y)^3)^0.33333)} +} + +## Plotting Voronoi diagram. aev 3/12/17 +## ns - number of sites, fn - file name, ttl - plot title. +## mt - type of metric: 1 - Euclidean, 2 - Manhattan, 3 - Minkovski. +pVoronoiD <- function(ns, fn="", ttl="",mt=1) { + cat(" *** START VD:", date(), "\n"); + if(mt<1||mt>3) {mt=1}; mts=""; if(mt>1) {mts=paste0(", mt - ",mt)}; + m=640; i=j=k=m1=m-2; x=y=d=dm=0; + if(fn=="") {pf=paste0("VDR", mt, ns, ".png")} else {pf=paste0(fn, ".png")}; + if(ttl=="") {ttl=paste0("Voronoi diagram, sites - ", ns, mts)}; + cat(" *** Plot file -", pf, "title:", ttl, "\n"); + plot(NA, xlim=c(0,m), ylim=c(0,m), xlab="", ylab="", main=ttl); + X=numeric(ns); Y=numeric(ns); C=numeric(ns); + for(i in 1:ns) { + X[i]=sample(0:m1, 1, replace=TRUE); + Y[i]=sample(0:m1, 1, replace=TRUE); + C[i]=randHclr(); + } + for(i in 0:m1) { + for(j in 0:m1) { + dm=Metric(m1,m1,mt); k=-1; + for(n in 1:ns) { + d=Metric(X[n]-j,Y[n]-i, mt); + if(d { + val d = File(dirPath) + require(d.exists() && d.isDirectory()) + return d.list().filter { it.matches(pattern) } +} + +fun main(args: Array) { + val r = Regex("""^a.*\.h$""") // get all C header files beginning with 'a' + val files = walkDirectory("/usr/include", r) + for (file in files) println(file) +} diff --git a/Task/Walk-a-directory-Non-recursively/Ring/walk-a-directory-non-recursively.ring b/Task/Walk-a-directory-Non-recursively/Ring/walk-a-directory-non-recursively.ring new file mode 100644 index 0000000000..8f29e565a2 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Ring/walk-a-directory-non-recursively.ring @@ -0,0 +1,88 @@ +###--------------------------------------- +### Directory Tree Walk +### Look for FileType for Music and Video + +fileType = [".avi", ".mp4", ".mpg", ".mkv", ".mp3", ".wmv" ] + +dirList = [] +musicList = [] + +###--------------------------------------- +### Main + + ###----------------------------------- + ### Start at this directory + + searchVideoMusic("C:\Users\Umberto\") + + see nl +"Number of Music and Videos files: " +len(musicList) +nl +nl + see musicList + See nl +"Finished" +nl + +###======================================= +### Search for Video and Music files + +Func searchVideoMusic(startDir) + + ChDir(startDir + "Music") ### <<<== add Music subpath C:\Users\Umberto\Music + listDir( CurrentDir() ) + + ChDir(startDir + "Videos") ### <<<== add Videos subpath C:\Users\Umberto\Videos + listDir( CurrentDir() ) + + for searchDir in dirList ### Search Directory List for Music and Videos files + listDir(searchDir) + next + + +###============================== +### Find Files in Directory + +Func listDir(dirName) + + ChDir(dirName) + Try + ###------------------------------------- + ### Get SubDirectories + + myListSub = Dir( CurrentDir() ) + Catch + ###------------------------------------- + ### Error, Couldn't open the directory + + See "ListDir Catch! " + CurrentDir() +" --- "+ cCatchError +nl + return + Done + + for x in myListSub + if x[2] + thisDir = x[1] + + if thisDir[1] = "." + ### Do Nothing. Ignore dot.name + + else + see nl +"Dir: " + CurrentDir() +"\"+ thisDir + nl + + ###---------------------------------------- + ### Directory Walk add to directory list + + Add( dirList, (CurrentDir() +"\"+ thisDir)) + ok + else + thisFile = x[1] + + ###------------------------------- + ### Add Music or Video file type + + for thisType in fileType + if ( substr(thisFile, thisType) ) ### <<<== Type of File from List + see " File: " + thisFile + nl + Add(musicList, (CurrentDir() +"\"+ thisFile)) + ok + next + ok + next +return + +###=============================================== diff --git a/Task/Walk-a-directory-Non-recursively/Sidef/walk-a-directory-non-recursively-1.sidef b/Task/Walk-a-directory-Non-recursively/Sidef/walk-a-directory-non-recursively-1.sidef index fc55e7616a..d1e6e93718 100644 --- a/Task/Walk-a-directory-Non-recursively/Sidef/walk-a-directory-non-recursively-1.sidef +++ b/Task/Walk-a-directory-Non-recursively/Sidef/walk-a-directory-non-recursively-1.sidef @@ -1 +1 @@ -'*.p[lm]'.glob.each { |file| say file }; # Perl files under this directory +'*.p[lm]'.glob.each { |file| say file } # Perl files under this directory diff --git a/Task/Walk-a-directory-Non-recursively/Sidef/walk-a-directory-non-recursively-2.sidef b/Task/Walk-a-directory-Non-recursively/Sidef/walk-a-directory-non-recursively-2.sidef index 5d342f85b5..064da9b64a 100644 --- a/Task/Walk-a-directory-Non-recursively/Sidef/walk-a-directory-non-recursively-2.sidef +++ b/Task/Walk-a-directory-Non-recursively/Sidef/walk-a-directory-non-recursively-2.sidef @@ -1,16 +1,16 @@ func file_match(Block callback, pattern=/\.txt\z/, path=Dir.cwd) { - path.open(\var dir_h) || return; + path.open(\var dir_h) || return nil dir_h.entries.each { |entry| if (entry.basename ~~ pattern) { - callback(entry); + callback(entry) } } } - +  file_match( path: %d'/tmp', pattern: /\.p[lm]\z/i, callback: { |file| say file; } -); +) diff --git a/Task/Walk-a-directory-Non-recursively/TXR/walk-a-directory-non-recursively-1.txr b/Task/Walk-a-directory-Non-recursively/TXR/walk-a-directory-non-recursively-1.txr new file mode 100644 index 0000000000..f87c232b64 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/TXR/walk-a-directory-non-recursively-1.txr @@ -0,0 +1 @@ +(glob "/etc/*.conf") diff --git a/Task/Walk-a-directory-Non-recursively/TXR/walk-a-directory-non-recursively-2.txr b/Task/Walk-a-directory-Non-recursively/TXR/walk-a-directory-non-recursively-2.txr new file mode 100644 index 0000000000..01dcfc636c --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/TXR/walk-a-directory-non-recursively-2.txr @@ -0,0 +1,11 @@ +("/etc/adduser.conf" "/etc/apg.conf" "/etc/blkid.conf" "/etc/brltty.conf" + "/etc/ca-certificates.conf" "/etc/colord.conf" "/etc/ddclient.conf" + "/etc/debconf.conf" "/etc/deluser.conf" "/etc/dnsmasq.conf" "/etc/ffserver.conf" + "/etc/fuse.conf" "/etc/gai.conf" "/etc/hdparm.conf" "/etc/host.conf" + "/etc/insserv.conf" "/etc/irssi.conf" "/etc/kernel-img.conf" + "/etc/kerneloops.conf" "/etc/knockd.conf" "/etc/ld.so.conf" "/etc/lftp.conf" + "/etc/logrotate.conf" "/etc/ltrace.conf" "/etc/mke2fs.conf" "/etc/mtools.conf" + "/etc/netscsid.conf" "/etc/nsswitch.conf" "/etc/ntp.conf" "/etc/pam.conf" + "/etc/pnm2ppa.conf" "/etc/popularity-contest.conf" "/etc/resolv.conf" + "/etc/rsyslog.conf" "/etc/sensors3.conf" "/etc/sysctl.conf" "/etc/ucf.conf" + "/etc/updatedb.conf" "/etc/usb_modeswitch.conf" "/etc/wodim.conf") diff --git a/Task/Walk-a-directory-Non-recursively/TXR/walk-a-directory-non-recursively-3.txr b/Task/Walk-a-directory-Non-recursively/TXR/walk-a-directory-non-recursively-3.txr new file mode 100644 index 0000000000..61ecf99128 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/TXR/walk-a-directory-non-recursively-3.txr @@ -0,0 +1 @@ +(mappend [iff (op ends-with ".conf") list] (get-lines (open-directory "/etc"))) diff --git a/Task/Walk-a-directory-Non-recursively/TXR/walk-a-directory-non-recursively-4.txr b/Task/Walk-a-directory-Non-recursively/TXR/walk-a-directory-non-recursively-4.txr new file mode 100644 index 0000000000..0348d4d65b --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/TXR/walk-a-directory-non-recursively-4.txr @@ -0,0 +1,9 @@ +("ddclient.conf" "gai.conf" "ucf.conf" "kernel-img.conf" "ltrace.conf" + "debconf.conf" "apg.conf" "adduser.conf" "mke2fs.conf" "colord.conf" + "kerneloops.conf" "fuse.conf" "hdparm.conf" "irssi.conf" "host.conf" + "ffserver.conf" "pam.conf" "sysctl.conf" "ld.so.conf" "dnsmasq.conf" + "insserv.conf" "brltty.conf" "deluser.conf" "netscsid.conf" "nsswitch.conf" + "mtools.conf" "wodim.conf" "updatedb.conf" "popularity-contest.conf" + "knockd.conf" "ntp.conf" "sensors3.conf" "resolv.conf" "blkid.conf" + "lftp.conf" "ca-certificates.conf" "usb_modeswitch.conf" "logrotate.conf" + "rsyslog.conf" "pnm2ppa.conf") diff --git a/Task/Walk-a-directory-Non-recursively/Zkl/walk-a-directory-non-recursively.zkl b/Task/Walk-a-directory-Non-recursively/Zkl/walk-a-directory-non-recursively.zkl new file mode 100644 index 0000000000..a28206fe96 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Zkl/walk-a-directory-non-recursively.zkl @@ -0,0 +1 @@ +File.glob("*.zkl") //--> list of matches diff --git a/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively-1.d b/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively-1.d deleted file mode 100644 index 4d51ab8754..0000000000 --- a/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively-1.d +++ /dev/null @@ -1,18 +0,0 @@ -import std.stdio; -import std.file; -import std.regexp; - -void main(string[] args) { - auto path = args.length > 1 ? args[1] : "." ; // default current - auto pattern = args.length > 2 ? args[2] : "*.*"; // default all file - bool useRegExp = (args.length > 3 && args[3] == "-re") ; // pattern matching method - - if (args.length > 3 && args[3] == "-re") - // use Regular Expression - foreach (d; listdir(path, RegExp(pattern))) - writefln(d); - else - // use unix shell style pattern matching - foreach (d; listdir(path, pattern)) - writefln(d); - } diff --git a/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively-2.d b/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively-2.d deleted file mode 100644 index 63c2e960ea..0000000000 --- a/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively-2.d +++ /dev/null @@ -1,29 +0,0 @@ -import std.stdio; -import std.file; -import std.regexp; -import std.path ; - -void main(string[] args) { - auto path = args.length > 1 ? args[1] : "." ; // default current - auto pattern = args.length > 2 ? args[2] : "*.*"; // default all file - bool useRegExp = (args.length > 3 && args[3] == "-re") ; // pattern matching method - bool recursive = (args.length <= 4 || args[4] != "-nr") ; // recursive? - - bool matchNPrint(DirEntry* de) { - bool bPrint = false ; - if(!de.isdir) { - if(useRegExp){ - if(search(de.name, pattern)) // this _search_ from regexp module - writefln(de.name) ; - }else{ - if(fnmatch(de.name, pattern)) // this _fnmatch_ from path module - writefln(de.name) ; - } - } else - if(recursive) - listdir(de.name, &matchNPrint) ; // recursive sub dir - return true ; // continue - } - - listdir(path, &matchNPrint) ; -} diff --git a/Task/Walk-a-directory-Recursively/Gambas/walk-a-directory-recursively.gambas b/Task/Walk-a-directory-Recursively/Gambas/walk-a-directory-recursively.gambas new file mode 100644 index 0000000000..3e6cb87537 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Gambas/walk-a-directory-recursively.gambas @@ -0,0 +1,8 @@ +Public Sub Main() +Dim sTemp As String + +For Each sTemp In RDir("/etc", "*.d") + Print sTemp +Next + +End diff --git a/Task/Walk-a-directory-Recursively/IDL/walk-a-directory-recursively-1.idl b/Task/Walk-a-directory-Recursively/IDL/walk-a-directory-recursively-1.idl deleted file mode 100644 index 965dac6580..0000000000 --- a/Task/Walk-a-directory-Recursively/IDL/walk-a-directory-recursively-1.idl +++ /dev/null @@ -1 +0,0 @@ -result = file_search( directory, '*.txt', count=cc ) diff --git a/Task/Walk-a-directory-Recursively/IDL/walk-a-directory-recursively-2.idl b/Task/Walk-a-directory-Recursively/IDL/walk-a-directory-recursively-2.idl deleted file mode 100644 index 77e5c0865b..0000000000 --- a/Task/Walk-a-directory-Recursively/IDL/walk-a-directory-recursively-2.idl +++ /dev/null @@ -1,73 +0,0 @@ -########################### -# A sequential solution # -########################### - -procedure main() -every write(!getdirs(".")) # writes out all directories from the current directory down -end - -procedure getdirs(s) #: return a list of directories beneath the directory 's' -local D,d,f - -if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then { - D := [s] - while f := read(d) do - if not ( ".." ? =f ) then # skip . and .. - D |||:= getdirs(s || "/" ||f) - close(d) - return D - } -end - -######################### -# A threaded solution # -######################### - -import threads - -global n, # number of the concurrently running threads - maxT, # Max number of concurrent threads ("soft limit") - tot_threads # the total number of threads created in the program - -procedure main(argv) - target := argv[1] | stop("Usage: tdir [dir name] [#threads]. #threads default to 2* the number of cores in the machine.") - tot_threads := n := 1 - maxT := ( integer(argv[2])| - (&features? if ="CPU cores " then cores := integer(tab(0)) * 2) | # available cores * 2 - 4) # default to 4 threads - t := milliseconds() - L := getdirs(target) # writes out all directories from the current directory down - write((*\L)| 0, " directories in ", milliseconds() - t, - " ms using ", maxT, "-concurrent/", tot_threads, "-total threads" ) -end - -procedure getdirs(s) # return a list of directories beneath the directory 's' -local D,d,f, thrd - -if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then { - D := [s] - while f := read(d) do - if not ( ".." ? =f ) then # skip . and .. - if n>=maxT then # max thread count reached - D |||:= getdirs(s || "/" ||f) - else # spawn a new thread for this directory - {/thrd:=[]; n +:= 1; put(thrd, thread getdirs(s || "/" ||f))} - - close(d) - - if \thrd then{ # If I have threads, collect their results - tot_threads +:= *thrd - n -:= 1 # allow new threads to be spawned while I'm waiting/collecting results - every wait(th := !thrd) do { # wait for the thread to finish - n -:= 1 - D |||:= <@th # If the thread produced a result, it is going to be - # stored in its "outbox", <@th in this case serves as - # a deferred return since the thread was created by - # thread getdirs(s || "/" ||f) - # this is similar to co-expression activation semantics - } - n +:= 1 - } - return D - } -end diff --git a/Task/Walk-a-directory-Recursively/OoRexx/walk-a-directory-recursively-1.rexx b/Task/Walk-a-directory-Recursively/OoRexx/walk-a-directory-recursively-1.rexx new file mode 100644 index 0000000000..7a8ab3e80a --- /dev/null +++ b/Task/Walk-a-directory-Recursively/OoRexx/walk-a-directory-recursively-1.rexx @@ -0,0 +1,10 @@ +/* REXX --------------------------------------------------------------- +* List all file names on my disk D: that contain the string TTTT +*--------------------------------------------------------------------*/ +call SysFileTree "d:\*.*", "file", "FS" -- F get all Files + -- S search subdirectories +Say file.0 'files on disk' +do i=1 to file.0 + If pos('TTTT',translate(file.i))>0 Then + say file.i + end diff --git a/Task/Walk-a-directory-Recursively/OoRexx/walk-a-directory-recursively-2.rexx b/Task/Walk-a-directory-Recursively/OoRexx/walk-a-directory-recursively-2.rexx new file mode 100644 index 0000000000..69ee55dccd --- /dev/null +++ b/Task/Walk-a-directory-Recursively/OoRexx/walk-a-directory-recursively-2.rexx @@ -0,0 +1,10 @@ +/* REXX --------------------------------------------------------------- +* List all file names on my disk D: that contain the string TTTT +*--------------------------------------------------------------------*/ +call SysFileTree "*TTTT*.*", "file", "FS" -- F get all Files + -- S search subdirectories +Say file.0 'files found' +do i=1 to file.0 + If pos('TTTT',translate(file.i))>0 Then + say file.i + end diff --git a/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-1.scala b/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-1.scala deleted file mode 100644 index d0ffa5cf23..0000000000 --- a/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-1.scala +++ /dev/null @@ -1,21 +0,0 @@ -package io.utils - -import scala.language.implicitConversions -import java.io.File - -/** A wrapper around file, allowing iteration either on direct children - or on directory tree */ -class RichFile(file: File) { - - def children = new Iterable[File] { - def iterator = if (file.isDirectory) file.listFiles.iterator else Iterator.empty - } - - def andTree : Iterable[File] = - Seq(file) ++ children.flatMap(child => new RichFile(child).andTree) -} - -/** implicitely enrich java.io.File with methods of RichFile */ -object RichFile { - implicit def toRichFile(file: File) = new RichFile(file) -} diff --git a/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-2.scala b/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-2.scala deleted file mode 100644 index 1daba8a29d..0000000000 --- a/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-2.scala +++ /dev/null @@ -1,12 +0,0 @@ -package test.io.utils - -import io.utils.RichFile.toRichFile // this makes implicit toRichFile active -import java.io.File - -object Test extends App { - val root = new File("/home/user") - for(f <- root.andTree) Console.println(f) - - // filtering comes for free - for(f <- root.andTree; if f.getName.endsWith(".mp3")) Console.println(f) -} diff --git a/Task/Walk-a-directory-Recursively/Sidef/walk-a-directory-recursively.sidef b/Task/Walk-a-directory-Recursively/Sidef/walk-a-directory-recursively.sidef index 5e7f7f9e04..7b2bff4cfd 100644 --- a/Task/Walk-a-directory-Recursively/Sidef/walk-a-directory-recursively.sidef +++ b/Task/Walk-a-directory-Recursively/Sidef/walk-a-directory-recursively.sidef @@ -1,22 +1,22 @@ func traverse(Block callback, Dir dir) { - dir.open(\var dir_h) || return; - + dir.open(\var dir_h) || return nil +  dir_h.entries.each { |entry| if (entry.is_a(Dir)) { - traverse(callback, entry); + traverse(callback, entry) } else { - callback(entry); + callback(entry) } } } - -var dir = Dir.cwd; -var pattern = /foo/; # display files that contain 'foo' - +  +var dir = Dir.cwd +var pattern = /foo/ # display files that contain 'foo' +  traverse( { |file| if (file.basename ~~ pattern) { - say file; + say file } } => dir -); +) diff --git a/Task/Walk-a-directory-Recursively/TXR/walk-a-directory-recursively-1.txr b/Task/Walk-a-directory-Recursively/TXR/walk-a-directory-recursively-1.txr new file mode 100644 index 0000000000..246d4b8412 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/TXR/walk-a-directory-recursively-1.txr @@ -0,0 +1,3 @@ +(build (ftw "." (lambda (path type stat level base) + (if (ends-with ".tl" path) + (add path))))) diff --git a/Task/Walk-a-directory-Recursively/TXR/walk-a-directory-recursively-2.txr b/Task/Walk-a-directory-Recursively/TXR/walk-a-directory-recursively-2.txr new file mode 100644 index 0000000000..96d4a809f2 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/TXR/walk-a-directory-recursively-2.txr @@ -0,0 +1,18 @@ +("./tests/016/arith.tl" "./tests/014/dgram-stream.tl" "./tests/014/socket-basic.tl" + "./tests/sock-common.tl" "./tests/012/ifa.tl" "./tests/012/except.tl" + "./tests/012/fini.tl" "./tests/012/oop.tl" "./tests/012/circ.tl" + "./tests/012/cont.tl" "./tests/012/aseq.tl" "./tests/012/quasi.tl" + "./tests/012/struct.tl" "./tests/012/man-or-boy.tl" "./tests/017/glob-carray.tl" + "./tests/017/glob-zarray.tl" "./tests/017/realpath.tl" "./tests/017/qsort.tl" + "./tests/015/split.tl" "./tests/013/maze.tl" "./tests/common.tl" + "./tests/011/special-1.tl" "./share/txr/stdlib/ifa.tl" "./share/txr/stdlib/with-stream.tl" + "./share/txr/stdlib/pmac.tl" "./share/txr/stdlib/except.tl" "./share/txr/stdlib/awk.tl" + "./share/txr/stdlib/package.tl" "./share/txr/stdlib/place.tl" + "./share/txr/stdlib/trace.tl" "./share/txr/stdlib/type.tl" "./share/txr/stdlib/keyparams.tl" + "./share/txr/stdlib/ffi.tl" "./share/txr/stdlib/ver.tl" "./share/txr/stdlib/build.tl" + "./share/txr/stdlib/cadr.tl" "./share/txr/stdlib/hash.tl" "./share/txr/stdlib/error.tl" + "./share/txr/stdlib/txr-case.tl" "./share/txr/stdlib/tagbody.tl" + "./share/txr/stdlib/getopts.tl" "./share/txr/stdlib/socket.tl" + "./share/txr/stdlib/struct.tl" "./share/txr/stdlib/getput.tl" + "./share/txr/stdlib/path-test.tl" "./share/txr/stdlib/with-resources.tl" + "./share/txr/stdlib/yield.tl" "./share/txr/stdlib/conv.tl" "./share/txr/stdlib/termios.tl") diff --git a/Task/Walk-a-directory-Recursively/Zkl/walk-a-directory-recursively-1.zkl b/Task/Walk-a-directory-Recursively/Zkl/walk-a-directory-recursively-1.zkl new file mode 100644 index 0000000000..b302503a4b --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Zkl/walk-a-directory-recursively-1.zkl @@ -0,0 +1 @@ +d:=File.globular("..","s*.zkl") diff --git a/Task/Walk-a-directory-Recursively/Zkl/walk-a-directory-recursively-2.zkl b/Task/Walk-a-directory-Recursively/Zkl/walk-a-directory-recursively-2.zkl new file mode 100644 index 0000000000..2fc92ef676 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Zkl/walk-a-directory-recursively-2.zkl @@ -0,0 +1 @@ +File.globular("..","s*.zkl",True,0,Console.println) diff --git a/Task/Web-scraping/CoffeeScript/web-scraping-1.coffee b/Task/Web-scraping/CoffeeScript/web-scraping-1.coffee deleted file mode 100644 index 6f15191051..0000000000 --- a/Task/Web-scraping/CoffeeScript/web-scraping-1.coffee +++ /dev/null @@ -1,39 +0,0 @@ -http = require 'http' - -CONFIG = - host: 'tycho.usno.navy.mil' - path: '/cgi-bin/timer.pl' - -# Web scraping code tends to be brittle, and this is no exception. -# The tycho time page does not use highly structured markup, so -# we do a real dirty scrape. -scrape_tycho_ust_time = (text) -> - for line in text.split '\n' - matches = line.match /(.*:\d\d UTC)/ - if matches - console.log matches[0].replace '
    ', '' - return - throw Error("unscrapable page!") - -# This is low-level-ish code to get data from a URL. It's -# pretty general purpose, so you'd normally tuck this away -# in a library (or use somebody else's library). -wget = (host, path, cb) -> - options = - host: host - path: path - headers: - "Cache-Control": "max-age=0" - - req = http.request options, (res) -> - s = '' - res.on 'data', (chunk) -> - s += chunk - res.on 'end', -> - cb s - req.end() - -# Do our web scrape -do -> - wget CONFIG.host, CONFIG.path, (data) -> - scrape_tycho_ust_time data diff --git a/Task/Web-scraping/CoffeeScript/web-scraping-2.coffee b/Task/Web-scraping/CoffeeScript/web-scraping-2.coffee deleted file mode 100644 index 4a8550d2fa..0000000000 --- a/Task/Web-scraping/CoffeeScript/web-scraping-2.coffee +++ /dev/null @@ -1,2 +0,0 @@ -> coffee web_scrape.coffee -Jan. 09, 19:19:07 UTC diff --git a/Task/Web-scraping/Gambas/web-scraping.gambas b/Task/Web-scraping/Gambas/web-scraping.gambas new file mode 100644 index 0000000000..c793d6ef3b --- /dev/null +++ b/Task/Web-scraping/Gambas/web-scraping.gambas @@ -0,0 +1,17 @@ +Public Sub Main() +Dim sWeb, sTemp, sOutput As String 'Variables + +Shell "wget -O /tmp/web http://tycho.usno.navy.mil/cgi-bin/timer.pl" Wait 'Use 'wget' to save the web file in /tmp/ + +sWeb = File.Load("/tmp/web") 'Open file and store in sWeb + +For Each sTemp In Split(sWeb, gb.NewLine) 'Split the file by NewLines.. + If InStr(sTemp, "UTC") Then 'If the line contains "UTC" then.. + sOutPut = sTemp 'Extract the line into sOutput + Break 'Get out of here + End If +Next + +Print Mid(sOutput, 5) 'Print the result without the '
    ' tag + +End diff --git a/Task/Web-scraping/jq/web-scraping-1.jq b/Task/Web-scraping/Jq/web-scraping-1.jq similarity index 100% rename from Task/Web-scraping/jq/web-scraping-1.jq rename to Task/Web-scraping/Jq/web-scraping-1.jq diff --git a/Task/Web-scraping/jq/web-scraping-2.jq b/Task/Web-scraping/Jq/web-scraping-2.jq similarity index 100% rename from Task/Web-scraping/jq/web-scraping-2.jq rename to Task/Web-scraping/Jq/web-scraping-2.jq diff --git a/Task/Web-scraping/Kotlin/web-scraping.kotlin b/Task/Web-scraping/Kotlin/web-scraping.kotlin new file mode 100644 index 0000000000..efd9b93a29 --- /dev/null +++ b/Task/Web-scraping/Kotlin/web-scraping.kotlin @@ -0,0 +1,19 @@ +// version 1.1.3 + +import java.net.URL +import java.io.InputStreamReader +import java.util.Scanner + +fun main(args: Array) { + val url = URL("http://tycho.usno.navy.mil/cgi-bin/timer.pl") + val isr = InputStreamReader(url.openStream()) + val sc = Scanner(isr) + while (sc.hasNextLine()) { + val line = sc.nextLine() + if ("UTC" in line) { + println(line.drop(4).take(17)) + break + } + } + sc.close() +} diff --git a/Task/Web-scraping/MIRC-Scripting-Language/web-scraping.mirc b/Task/Web-scraping/MIRC-Scripting-Language/web-scraping.mirc new file mode 100644 index 0000000000..b1f7bbb519 --- /dev/null +++ b/Task/Web-scraping/MIRC-Scripting-Language/web-scraping.mirc @@ -0,0 +1,23 @@ +alias utc { + sockclose UTC + sockopen UTC tycho.usno.navy.mil 80 +} + +on *:SOCKOPEN:UTC: { + sockwrite -n UTC GET /cgi-bin/timer.pl HTTP/1.1 + sockwrite -n UTC Host: tycho.usno.navy.mil + sockwrite UTC $crlf +} + +on *:SOCKREAD:UTC: { + sockread %UTC + while ($sockbr) { + if (
    *Universal Time iswm %UTC) { + echo -ag $remove(%UTC,
    ,$chr(9),Universal Time) + unset %UTC + sockclose UTC + return + } + sockread %UTC + } +} diff --git a/Task/Web-scraping/OoRexx/web-scraping.rexx b/Task/Web-scraping/OoRexx/web-scraping.rexx new file mode 100644 index 0000000000..061ad46458 --- /dev/null +++ b/Task/Web-scraping/OoRexx/web-scraping.rexx @@ -0,0 +1,23 @@ +/* load the RexxcURL library */ +Call RxFuncAdd 'CurlLoadFuncs', 'rexxcurl', 'CurlLoadFuncs' +Call CurlLoadFuncs + +url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl" + +/* get a curl session */ +curl = CurlInit() +if curl \= '' +then do + call CurlSetopt curl, 'URL', Url + if curlerror.intcode \= 0 then exit + call curlSetopt curl, 'OUTSTEM', 'stem.' + if curlerror.intcode \= 0 then exit + call CurlPerform curl + + /* content is in a stem - lets get it all in a string */ + content = stem.~allItems~makestring('l') + /* now parse out utc time */ + parse var content content 'Universal Time' . + utcTime = content~substr(content~lastpos('
    ') + 4) + say utcTime +end diff --git a/Task/Web-scraping/PowerShell/web-scraping.psh b/Task/Web-scraping/PowerShell/web-scraping-1.psh similarity index 100% rename from Task/Web-scraping/PowerShell/web-scraping.psh rename to Task/Web-scraping/PowerShell/web-scraping-1.psh diff --git a/Task/Web-scraping/PowerShell/web-scraping-2.psh b/Task/Web-scraping/PowerShell/web-scraping-2.psh new file mode 100644 index 0000000000..8562941d22 --- /dev/null +++ b/Task/Web-scraping/PowerShell/web-scraping-2.psh @@ -0,0 +1 @@ +[System.DateTime]::UtcNow diff --git a/Task/Web-scraping/PowerShell/web-scraping-3.psh b/Task/Web-scraping/PowerShell/web-scraping-3.psh new file mode 100644 index 0000000000..90bbbe6bb0 --- /dev/null +++ b/Task/Web-scraping/PowerShell/web-scraping-3.psh @@ -0,0 +1 @@ +[System.DateTime]::Now diff --git a/Task/Web-scraping/Protium/web-scraping-1.protium b/Task/Web-scraping/Protium/web-scraping-1.protium deleted file mode 100644 index c30bf0931c..0000000000 --- a/Task/Web-scraping/Protium/web-scraping-1.protium +++ /dev/null @@ -1,5 +0,0 @@ -<@ DEFAREPRS>Rexx Parse -<@ DEFPRSLIT>Rexx Parse|'
    ' UTCtime 'UTC' -<@ LETVARURL>timer|http://tycho.usno.navy.mil/cgi-bin/timer.pl -<@ ACTRPNPRSVAR>Rexx Parse|timer -<@ SAYVAR>UTCtime diff --git a/Task/Web-scraping/Protium/web-scraping-2.protium b/Task/Web-scraping/Protium/web-scraping-2.protium deleted file mode 100644 index c92515ee74..0000000000 --- a/Task/Web-scraping/Protium/web-scraping-2.protium +++ /dev/null @@ -1,5 +0,0 @@ -<# DEFINE WORKAREA PARSEVALUES>Rexx Parse -<# DEFINE PARSEVALUES LITERAL>Rexx Parse|'
    ' UTCtime 'UTC' -<# LET VARIABLE URLSOURCE>timer|http://tycho.usno.navy.mil/cgi-bin/timer.pl -<# ACT REPLACEBYPATTERN PARSEVALUES VARIABLE>Rexx Parse|timer -<# SAY VARIABLE>UTCtime diff --git a/Task/Web-scraping/Protium/web-scraping-3.protium b/Task/Web-scraping/Protium/web-scraping-3.protium deleted file mode 100644 index cb8fdb898f..0000000000 --- a/Task/Web-scraping/Protium/web-scraping-3.protium +++ /dev/null @@ -1 +0,0 @@ -<@ SAY AFT BEF URL LIT LIT LIT >http://tycho.usno.navy.mil/cgi-bin/timer.pl| UTC|
    diff --git a/Task/Web-scraping/Zkl/web-scraping.zkl b/Task/Web-scraping/Zkl/web-scraping.zkl new file mode 100644 index 0000000000..2b4993951a --- /dev/null +++ b/Task/Web-scraping/Zkl/web-scraping.zkl @@ -0,0 +1,14 @@ +const HOST="tycho.usno.navy.mil", PORT=80, dir="/cgi-bin/timer.pl"; +get:="GET %s HTTP/1.0\r\nHost: %s:%s\r\n\r\n".fmt(dir,HOST,PORT); +server:=Network.TCPClientSocket.connectTo(HOST,PORT); +server.write(get); // send request to web serer +data:=server.read(True); // read data from web server + +data.seek(data.find("UTC")); // middle of line +c:=data.seek(Void,0); // start of line +line:=data[c,data.seek(Void,1)-c].text; +line.print(); // the HTML UTC line + +re:=RegExp(0'|.*(\d\d:\d\d:\d\d)|); // get time +re.search(line); +re.matched[1].println(); diff --git a/Task/Window-creation-X11/Kotlin/window-creation-x11.kotlin b/Task/Window-creation-X11/Kotlin/window-creation-x11.kotlin new file mode 100644 index 0000000000..a125050eb9 --- /dev/null +++ b/Task/Window-creation-X11/Kotlin/window-creation-x11.kotlin @@ -0,0 +1,32 @@ +// Kotlin Native v0.3 + +import kotlinx.cinterop.* +import Xlib.* + +fun main(args: Array) { + val msg = "Hello, World!" + val d = XOpenDisplay(null) + if (d == null) { + println("Cannot open display") + return + } + + val s = XDefaultScreen(d) + val w = XCreateSimpleWindow(d, XRootWindow(d, s), 10, 10, 160, 160, 1, + XBlackPixel(d, s), XWhitePixel(d, s)) + XSelectInput(d, w, ExposureMask or KeyPressMask) + XMapWindow(d, w) + val e = nativeHeap.alloc() + + while (true) { + XNextEvent(d, e.ptr) + if (e.type == Expose) { + XFillRectangle(d, w, XDefaultGC(d, s), 55, 40, 50, 50) + XDrawString(d, w, XDefaultGC(d, s), 45, 120, msg, msg.length) + } + else if (e.type == KeyPress) break + } + + XCloseDisplay(d) + nativeHeap.free(e) +} diff --git a/Task/Window-creation/BaCon/window-creation.bacon b/Task/Window-creation/BaCon/window-creation.bacon new file mode 100644 index 0000000000..91301fdd4a --- /dev/null +++ b/Task/Window-creation/BaCon/window-creation.bacon @@ -0,0 +1,7 @@ +REM empty window +INCLUDE "hug.bac" + +mainwin = WINDOW("Rosetta Code empty", 400, 300) + +REM start gtk event loop... +DISPLAY diff --git a/Task/Window-creation/Gambas/window-creation.gambas b/Task/Window-creation/Gambas/window-creation.gambas new file mode 100644 index 0000000000..e169a5cac8 --- /dev/null +++ b/Task/Window-creation/Gambas/window-creation.gambas @@ -0,0 +1,3 @@ +Public Sub Form_Open() + +End diff --git a/Task/Window-creation/Julia/window-creation.julia b/Task/Window-creation/Julia/window-creation.julia new file mode 100644 index 0000000000..bd6a459240 --- /dev/null +++ b/Task/Window-creation/Julia/window-creation.julia @@ -0,0 +1,5 @@ +# v0.6 + +using Tk + +w = Toplevel("Example") diff --git a/Task/Window-creation/Nimrod/window-creation-1.nimrod b/Task/Window-creation/Nimrod/window-creation-1.nimrod deleted file mode 100644 index 1beb2ad1de..0000000000 --- a/Task/Window-creation/Nimrod/window-creation-1.nimrod +++ /dev/null @@ -1,52 +0,0 @@ -import - gdk2, glib2, gtk2 - -proc thisDestroy(widget: pWidget, data: pgpointer){.cdecl.} = - main_quit() - -const - Inside: cstring = "Mouse is over label" - OutSide: cstring = "Mouse is not over label" - -var - OverButton: bool - -nimrod_init() -var window = window_new(gtk2.WINDOW_TOPLEVEL) -var stackbox = vbox_new(TRUE, 10) -var button1 = button_new("Move mouse over button") -var buttonstyle = copy(get_style(Button1)) -ButtonStyle.bg[STATE_PRELIGHT].pixel = 0 -ButtonStyle.bg[STATE_PRELIGHT].red = -1'i16 -ButtonStyle.bg[STATE_PRELIGHT].blue = 0'i16 -ButtonStyle.bg[STATE_PRELIGHT].green = 0'i16 -set_style(button1, buttonstyle) -var button2 = button_new() -var ALabel = label_new(Outside) -var button3 = button_new("Quit") - - -proc ChangeLabel(P: PWidget, Event: gdk2.PEventCrossing, - Data: var bool){.cdecl.} = - if Not Data: set_text(ALabel, Inside) - else: set_text(ALabel, Outside) - Data = Not Data - - -add(button2, ALAbel) -pack_start(stackbox, button1, TRUE, TRUE, 0) -pack_start(stackbox, button2, TRUE, TRUE, 0) -pack_start(stackbox, button3, TRUE, TRUE, 0) -set_border_width(Window, 5) -add(window, stackbox) -discard signal_connect(window, "destroy", - SIGNAL_FUNC(thisDestroy), nil) -overbutton = False -discard signal_connect(button1, "enter_notify_event", - SIGNAL_FUNC(ChangeLabel), addr(OverButton)) -discard signal_connect(button1, "leave_notify_event", - SIGNAL_FUNC(ChangeLabel), addr(OverButton)) -discard signal_connect(button3, "clicked", - SIGNAL_FUNC(thisDestroy), nil) -show_all(window) -main() diff --git a/Task/Window-creation/Nimrod/window-creation-2.nimrod b/Task/Window-creation/Nimrod/window-creation-2.nimrod deleted file mode 100644 index 4a9da4c7cd..0000000000 --- a/Task/Window-creation/Nimrod/window-creation-2.nimrod +++ /dev/null @@ -1,48 +0,0 @@ -import - sdl, sdl_image, colors - -var - screen, greeting: PSurface - r: TRect - event: TEvent - bgColor = colChocolate.int32 - -if init(INIT_VIDEO) != 0: - quit "SDL failed to initialize!" - -screen = SetVideoMode(640, 480, 16, SWSURFACE or ANYFORMAT) -if screen.isNil: - quit($sdl.getError()) - -greeting = IMG_load("tux.png") -if greeting.isNil: - echo "Failed to load tux.png" -else: - ## convert the image to alpha and free the old one - var s = greeting.displayFormatAlpha() - swap(greeting, s) - s.freeSurface() - -r.x = 0 -r.y = 0 - -block game_loop: - while true: - - while pollEvent(addr event) > 0: - case event.kind - of QUITEV: - break game_loop - of KEYDOWN: - if EvKeyboard(addr event).keysym.sym == K_ESCAPE: - break game_loop - else: - discard - - discard fillRect(screen, nil, bgColor) - discard blitSurface(greeting, nil, screen, addr r) - discard flip(screen) - -greeting.freeSurface() -screen.freeSurface() -sdl.Quit() diff --git a/Task/Window-creation/Nimrod/window-creation-3.nimrod b/Task/Window-creation/Nimrod/window-creation-3.nimrod deleted file mode 100644 index 05cc09c7cd..0000000000 --- a/Task/Window-creation/Nimrod/window-creation-3.nimrod +++ /dev/null @@ -1,73 +0,0 @@ -import xlib, xutil, x, keysym - -const - WINDOW_WIDTH = 400 - WINDOW_HEIGHT = 300 - -var - width, height: cuint - display: PDisplay - screen: cint - depth: int - win: TWindow - sizeHints: TXSizeHints - -proc create_window = - width = WINDOW_WIDTH - height = WINDOW_HEIGHT - - display = XOpenDisplay(nil) - if display == nil: - echo("Verbindung zum X-Server fehlgeschlagen") - quit(1) - - screen = XDefaultScreen(display) - depth = XDefaultDepth(display, screen) - var rootwin = XRootWindow(display, screen) - win = XCreateSimpleWindow(display, rootwin, 100, 10, - width, height, 5, - XBlackPixel(display, screen), - XWhitePixel(display, screen)) - size_hints.flags = PSize or PMinSize or PMaxSize - size_hints.min_width = width.cint - size_hints.max_width = width.cint - size_hints.min_height = height.cint - size_hints.max_height = height.cint - discard XSetStandardProperties(display, win, "Simple Window", "window", - 0, nil, 0, addr(size_hints)) - discard XSelectInput(display, win, ButtonPressMask or KeyPressMask or - PointerMotionMask) - discard XMapWindow(display, win) - -proc close_window = - discard XDestroyWindow(display, win) - discard XCloseDisplay(display) - -var - xev: TXEvent - -proc process_event = - var key: TKeySym - case int(xev.theType) - of KeyPress: - key = XLookupKeysym(cast[ptr TXKeyEvent](addr(xev)), 0) - if key.int != 0: - echo("keyboard event",$key.int) - if key.int == 65307: # - quit(1) - of ButtonPressMask, PointerMotionMask: - Echo("Mouse event") - else: nil - -proc eventloop = - discard XFlush(display) - var num_events = int(XPending(display)) - while num_events != 0: - dec(num_events) - discard XNextEvent(display, addr(xev)) - process_event() - -create_window() -while true: - eventloop() -close_window() diff --git a/Task/Window-creation/Nimrod/window-creation-4.nimrod b/Task/Window-creation/Nimrod/window-creation-4.nimrod deleted file mode 100644 index 1ce702e918..0000000000 --- a/Task/Window-creation/Nimrod/window-creation-4.nimrod +++ /dev/null @@ -1,13 +0,0 @@ -import glut - -var win: int = 0 - -proc myOnKeyPress(c: int8, v1, v2: cint) {.cdecl.} = - echo(c) - if c == 27: - glutDestroyWindow(win) - -glutInit() -win = glutCreateWindow("Goodbye, World!") -glutKeyboardFunc(TGlut1Char2IntCallback(myOnKeyPress)) -glutMainLoop() diff --git a/Task/Window-creation/Nimrod/window-creation-5.nimrod b/Task/Window-creation/Nimrod/window-creation-5.nimrod deleted file mode 100644 index c77a142622..0000000000 --- a/Task/Window-creation/Nimrod/window-creation-5.nimrod +++ /dev/null @@ -1,9 +0,0 @@ -# test a Windows GUI application - -import - windows, shellapi, nb30, mmsystem, shfolder - -#proc MessageBox(hWnd: int, lpText, lpCaption: CString, uType: uint): int -# {stdcall, import: "MessageBox", header: ""} - -discard MessageBox(0, "Hello World!", "Nimrod GUI Application", 0) diff --git a/Task/Window-creation/Phix/window-creation.phix b/Task/Window-creation/Phix/window-creation.phix index 321277d7a9..74df758665 100644 --- a/Task/Window-creation/Phix/window-creation.phix +++ b/Task/Window-creation/Phix/window-creation.phix @@ -1,13 +1,16 @@ +-- +-- demo\rosetta\Window_creation.exw +-- include pGUI.e function esc_close(Ihandle /*ih*/, atom c) return iff(c=K_ESC?IUP_CLOSE:IUP_CONTINUE) end function - IupOpen("../pGUI/") - Ihandle dlg = IupDialog(IupVbox({IupLabel("hello")},"MARGIN=200x200")) - IupSetAttribute(dlg,"TITLE","Hello") - IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) - IupShow(dlg) - IupMainLoop() - IupClose() +IupOpen() +Ihandle dlg = IupDialog(IupVbox({IupLabel("hello")},"MARGIN=200x200")) +IupSetAttribute(dlg,"TITLE","Hello") +IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) +IupShow(dlg) +IupMainLoop() +IupClose() diff --git a/Task/Window-creation/TXR/window-creation-1.txr b/Task/Window-creation/TXR/window-creation-1.txr new file mode 100644 index 0000000000..58ef134bd7 --- /dev/null +++ b/Task/Window-creation/TXR/window-creation-1.txr @@ -0,0 +1,34 @@ +(defvarl SDL_INIT_VIDEO #x00000020) +(defvarl SDL_SWSURFACE #x00000000) +(defvarl SDL_HWPALETTE #x20000000) + +(typedef SDL_Surface (cptr SDL_Surface)) + +(typedef SDL_EventType (enumed uint8 SDL_EventType + (SDL_KEYUP 3) + (SDL_QUIT 12))) + +(typedef SDL_Event (union SD_Event + (type SDL_EventType) + (pad (array 8 uint32)))) + + +(with-dyn-lib "libSDL.so" + (deffi SDL_Init "SDL_Init" int (uint32)) + (deffi SDL_SetVideoMode "SDL_SetVideoMode" + SDL_Surface (int int int uint32)) + (deffi SDL_GetError "SDL_GetError" str ()) + (deffi SDL_WaitEvent "SDL_WaitEvent" int ((ptr-out SDL_Event))) + (deffi SDL_Quit "SDL_Quit" void ())) + +(when (neql 0 (SDL_Init SDL_INIT_VIDEO)) + (put-string `unable to initialize SDL: @(SDL_GetError)`) + (exit nil)) + +(unwind-protect + (progn + (SDL_SetVideoMode 800 600 16 (logior SDL_SWSURFACE SDL_HWPALETTE)) + (let ((e (make-union (ffi SDL_Event)))) + (until* (memql (union-get e 'type) '(SDL_KEYUP SDL_QUIT)) + (SDL_WaitEvent e)))) + (SDL_Quit)) diff --git a/Task/Window-creation/TXR/window-creation-2.txr b/Task/Window-creation/TXR/window-creation-2.txr new file mode 100644 index 0000000000..aa81b90f7e --- /dev/null +++ b/Task/Window-creation/TXR/window-creation-2.txr @@ -0,0 +1,66 @@ +(typedef XID uint32) + +(typedef Window XID) + +(typedef Drawable XID) + +(typedef Display (cptr Display)) + +(typedef GC (cptr GC)) + +(typedef XEventType (enum _XEventType + (KeyPress 2) + (Expose 12))) + +(defvarl KeyPressMask (ash 1 0)) +(defvarl ExposureMask (ash 1 15)) + +(typedef XEvent (union _XEvent + (type XEventType) + (pad (array 24 long)))) + +(defvarl NULL cptr-null) + +(with-dyn-lib "libX11.so" + (deffi XOpenDisplay "XOpenDisplay" Display (bstr)) + (deffi XCloseDisplay "XCloseDisplay" int (Display)) + (deffi XDefaultScreen "XDefaultScreen" int (Display)) + (deffi XRootWindow "XRootWindow" Window (Display int)) + (deffi XBlackPixel "XBlackPixel" ulong (Display int)) + (deffi XWhitePixel "XWhitePixel" ulong (Display int)) + (deffi XCreateSimpleWindow "XCreateSimpleWindow" Window (Display + Window + int int + uint uint uint + ulong ulong)) + (deffi XSelectInput "XSelectInput" int (Display Window long)) + (deffi XMapWindow "XMapWindow" int (Display Window)) + (deffi XNextEvent "XNextEvent" int (Display (ptr-out XEvent))) + (deffi XDefaultGC "XDefaultGC" GC (Display int)) + (deffi XFillRectangle "XFillRectangle" int (Display Drawable GC + int int uint uint)) + (deffi XDrawString "XDrawString" int (Display Drawable GC + int int bstr int))) + +(let* ((msg "Hello, world!") + (d (XOpenDisplay nil))) + (when (equal d NULL) + (put-line "Cannot-open-display" *stderr*) + (exit 1)) + + (let* ((s (XDefaultScreen d)) + (w (XCreateSimpleWindow d (XRootWindow d s) 10 10 100 100 1 + (XBlackPixel d s) (XWhitePixel d s)))) + (XSelectInput d w (logior ExposureMask KeyPressMask)) + (XMapWindow d w) + + (while t + (let ((e (make-union (ffi XEvent)))) + (XNextEvent d e) + (caseq (union-get e 'type) + (Expose + (XFillRectangle d w (XDefaultGC d s) 20 20 10 10) + (XDrawString d w (XDefaultGC d s) 10 50 msg (length msg))) + (KeyPress (return))))) + + (XCloseDisplay d))) diff --git a/Task/Window-creation/TXR/window-creation-3.txr b/Task/Window-creation/TXR/window-creation-3.txr new file mode 100644 index 0000000000..00dceeb3fe --- /dev/null +++ b/Task/Window-creation/TXR/window-creation-3.txr @@ -0,0 +1,31 @@ +(typedef GtkObject* (cptr GtkObject)) +(typedef GtkWidget* (cptr GtkWidget)) + +(typedef GtkWidget* (cptr GtkWidget)) + +(typedef GtkWindowType (enum GtkWindowType + GTK_WINDOW_TOPLEVEL + GTK_WINDOW_POPUP)) + +(with-dyn-lib "libgtk-x11-2.0.so.0" + (deffi gtk_init "gtk_init" void ((ptr int) (ptr (ptr (zarray str))))) + (deffi gtk_window_new "gtk_window_new" GtkWidget* (GtkWindowType)) + (deffi gtk_signal_connect_full "gtk_signal_connect_full" + ulong (GtkObject* str closure closure val closure int int)) + (deffi gtk_widget_show "gtk_widget_show" void (GtkWidget*)) + (deffi gtk_main "gtk_main" void ()) + (deffi-sym gtk_main_quit "gtk_main_quit")) + +(defmacro GTK_OBJECT (cptr) + ^(cptr-cast 'GtkObject ,cptr)) + +(defmacro gtk_signal_connect (object name func func-data) + ^(gtk_signal_connect_full ,object ,name ,func cptr-null + ,func-data cptr-null 0 0)) + +(gtk_init (length *args*) (vec-list *args*)) + +(let ((window (gtk_window_new 'GTK_WINDOW_TOPLEVEL))) + (gtk_signal_connect (GTK_OBJECT window) "destroy" gtk_main_quit nil) + (gtk_widget_show window) + (gtk_main)) diff --git a/Task/Window-creation/TXR/window-creation-4.txr b/Task/Window-creation/TXR/window-creation-4.txr new file mode 100644 index 0000000000..b1f9617564 --- /dev/null +++ b/Task/Window-creation/TXR/window-creation-4.txr @@ -0,0 +1,130 @@ +(typedef LRESULT int-ptr-t) +(typedef LPARAM int-ptr-t) +(typedef WPARAM uint-ptr-t) + +(typedef UINT uint32) +(typedef LONG int32) +(typedef WORD uint16) +(typedef DWORD uint32) +(typedef LPVOID cptr) +(typedef BOOL (bool int32)) +(typedef BYTE uint8) + +(typedef HWND (cptr HWND)) +(typedef HINSTANCE (cptr HINSTANCE)) +(typedef HICON (cptr HICON)) +(typedef HCURSOR (cptr HCURSOR)) +(typedef HBRUSH (cptr HBRUSH)) +(typedef HMENU (cptr HMENU)) +(typedef HDC (cptr HDC)) + +(typedef ATOM WORD) +(typedef LPCTSTR wstr) + +(defvarl NULL cptr-null) + +(typedef WNDCLASS (struct WNDCLASS + (style UINT) + (lpfnWndProc closure) + (cbClsExtra int) + (cbWndExtra int) + (hInstance HINSTANCE) + (hIcon HICON) + (hCursor HCURSOR) + (hbrBackground HBRUSH) + (lpszMenuName LPCTSTR) + (lpszClassName LPCTSTR))) + +(defmeth WNDCLASS :init (me) + (zero-fill (ffi WNDCLASS) me)) + +(typedef POINT (struct POINT + (x LONG) + (y LONG))) + +(typedef MSG (struct MSG + (hwnd HWND) + (message UINT) + (wParam WPARAM) + (lParam LPARAM) + (time DWORD) + (pt POINT))) + +(typedef RECT (struct RECT + (left LONG) + (top LONG) + (right LONG) + (bottom LONG))) + +(typedef PAINTSTRUCT (struct PAINTSTRUCT + (hdc HDC) + (fErase BOOL) + (rcPaint RECT) + (fRestore BOOL) + (fIncUpdate BOOL) + (rgbReserved (array 32 BYTE)))) + +(defvarl CW_USEDEFAULT #x-80000000) +(defvarl WS_OVERLAPPEDWINDOW #x00cf0000) + +(defvarl SW_SHOWDEFAULT 5) + +(defvarl WM_DESTROY 2) +(defvarl WM_PAINT 15) + +(defvarl COLOR_WINDOW 5) + +(deffi-cb wndproc-fn LRESULT (HWND UINT LPARAM WPARAM)) + +(with-dyn-lib "kernel32.dll" + (deffi GetModuleHandle "GetModuleHandleW" HINSTANCE (wstr))) + +(with-dyn-lib "user32.dll" + (deffi RegisterClass "RegisterClassW" ATOM ((ptr-in WNDCLASS))) + (deffi CreateWindowEx "CreateWindowExW" HWND (DWORD + LPCTSTR LPCTSTR + DWORD + int int int int + HWND HMENU HINSTANCE + LPVOID)) + (deffi ShowWindow "ShowWindow" BOOL (HWND int)) + (deffi GetMessage "GetMessageW" BOOL ((ptr-out MSG) HWND UINT UINT)) + (deffi TranslateMessage "TranslateMessage" BOOL ((ptr-in MSG))) + (deffi DispatchMessage "DispatchMessageW" LRESULT ((ptr-in MSG))) + (deffi PostQuitMessage "PostQuitMessage" void (int)) + (deffi DefWindowProc "DefWindowProcW" LRESULT (HWND UINT LPARAM WPARAM)) + (deffi BeginPaint "BeginPaint" HDC (HWND (ptr-out PAINTSTRUCT))) + (deffi EndPaint "EndPaint" BOOL (HWND (ptr-in PAINTSTRUCT))) + (deffi FillRect "FillRect" int (HDC (ptr-in RECT) HBRUSH))) + +(defun WindowProc (hwnd uMsg wParam lParam) + (caseql* uMsg + (WM_DESTROY + (PostQuitMessage 0) + 0) + (WM_PAINT + (let* ((ps (new PAINTSTRUCT)) + (hdc (BeginPaint hwnd ps))) + (FillRect hdc ps.rcPaint (cptr-int (succ COLOR_WINDOW) 'HBRUSH)) + (EndPaint hwnd ps) + 0)) + (t (DefWindowProc hwnd uMsg wParam lParam)))) + +(let* ((hInstance (GetModuleHandle nil)) + (wc (new WNDCLASS + lpfnWndProc [wndproc-fn WindowProc] + hInstance hInstance + lpszClassName "Sample Window Class"))) + (RegisterClass wc) + (let ((hwnd (CreateWindowEx 0 wc.lpszClassName "Learn to Program Windows" + WS_OVERLAPPEDWINDOW + CW_USEDEFAULT CW_USEDEFAULT + CW_USEDEFAULT CW_USEDEFAULT + NULL NULL hInstance NULL))) + (unless (equal hwnd NULL) + (ShowWindow hwnd SW_SHOWDEFAULT) + + (let ((msg (new MSG))) + (while (GetMessage msg NULL 0 0) + (TranslateMessage msg) + (DispatchMessage msg)))))) diff --git a/Task/Window-management/Nimrod/window-management.nimrod b/Task/Window-management/Nimrod/window-management.nimrod deleted file mode 100644 index ea13320d31..0000000000 --- a/Task/Window-management/Nimrod/window-management.nimrod +++ /dev/null @@ -1,79 +0,0 @@ -import - gdk2, glib2, gtk2, - os - -proc thisDestroy(widget: pWidget, data: pgpointer){.cdecl.} = - main_quit() -proc thisMax(widget: pWidget, data: pgpointer){.cdecl.} = - maximize(get_parent_window(widget)) -proc thisUnmax(widget: pWidget, data: pgpointer){.cdecl.} = - unmaximize(get_parent_window(widget)) -proc thisIcon(widget: pWidget, data: pgpointer){.cdecl.} = - iconify(get_parent_window(widget)) -proc thisDeicon(widget: pWidget, data: pgpointer){.cdecl.} = - deiconify(get_parent_window(widget)) -proc thisHide(widget: pWidget, data: pgpointer){.cdecl.} = - hide(get_parent_window(widget)) - sleep(5) - show(get_parent_window(widget)) - -proc thisShow(widget: pWidget, data: pgpointer){.cdecl.} = - show(get_parent_window(widget)) - -var isshifted: bool = false - -proc thisMove(widget: pWidget, data: pgpointer){.cdecl.} = - var w, h: gint - get_size(get_parent_window(widget), Addr(w), Addr(h)) - if isshifted: - move(get_parent_window(widget), w-10, h-10) - else: - move(get_parent_window(widget), w+10, h+10) - isshifted = not isshifted - - -nimrod_init() -var window = window_new(gtk2.WINDOW_TOPLEVEL) -discard allow_grow(window) -set_title(window,"Window management") -var stackbox = vbox_new(TRUE, 10) -var bmax = button_new("maximize") -var bunmax = button_new("unmaximize") -var bicon = button_new("iconize") -var bdeicon = button_new("deiconize") -var bhide = button_new("hide") -var bshow = button_new("show") -var bmove = button_new("move") -var bquit = button_new("Quit") - -pack_start(stackbox, bmax, TRUE, TRUE, 0) -pack_start(stackbox, bunmax, TRUE, TRUE, 0) -pack_start(stackbox, bicon, TRUE, TRUE, 0) -pack_start(stackbox, bdeicon, TRUE, TRUE, 0) -pack_start(stackbox, bhide, TRUE, TRUE, 0) -pack_start(stackbox, bshow, TRUE, TRUE, 0) -pack_start(stackbox, bmove, TRUE, TRUE, 0) -pack_start(stackbox, bquit, TRUE, TRUE, 0) -set_border_width(Window, 5) -add(window, stackbox) -discard signal_connect(window, "destroy", - SIGNAL_FUNC(thisDestroy), nil) - -discard signal_connect(bicon, "clicked", - SIGNAL_FUNC(thisIcon), nil) -discard signal_connect(bdeicon, "clicked", - SIGNAL_FUNC(thisDeicon), nil) -discard signal_connect(bmax, "clicked", - SIGNAL_FUNC(thisMax), nil) -discard signal_connect(bunmax, "clicked", - SIGNAL_FUNC(thisUnmax), nil) -discard signal_connect(bhide, "clicked", - SIGNAL_FUNC(thisHide), nil) -discard signal_connect(bshow, "clicked", - SIGNAL_FUNC(thisShow), nil) -discard signal_connect(bmove, "clicked", - SIGNAL_FUNC(thismove), nil) -discard signal_connect(bquit, "clicked", - SIGNAL_FUNC(thisDestroy), nil) -show_all(window) -main() diff --git a/Task/Window-management/Phix/window-management.phix b/Task/Window-management/Phix/window-management.phix index b5338f1bae..1bace44919 100644 --- a/Task/Window-management/Phix/window-management.phix +++ b/Task/Window-management/Phix/window-management.phix @@ -1,3 +1,6 @@ +-- +-- demo\rosetta\Window_management.exw +-- include pGUI.e Ihandle dlg @@ -47,7 +50,7 @@ function doMove(Ihandle /*ih*/) end function procedure main() - IupOpen("../pGUI/") + IupOpen() Ihandle hbox = IupHbox({IupButton("restore", Icallback("doRestore")), IupButton("full screen",Icallback("doFull")), diff --git a/Task/Wireworld/Ceylon/wireworld.ceylon b/Task/Wireworld/Ceylon/wireworld.ceylon new file mode 100644 index 0000000000..2966e3e985 --- /dev/null +++ b/Task/Wireworld/Ceylon/wireworld.ceylon @@ -0,0 +1,101 @@ +abstract class Cell(shared Character char) of emptyCell | head | tail | conductor { + + shared Cell output({Cell*} neighbors) => + switch (this) + case (emptyCell) emptyCell + case (head) tail + case (tail) conductor + case (conductor) (neighbors.count(head.equals) in 1..2 then head else conductor); + + string => char.string; +} + +object emptyCell extends Cell(' ') {} + +object head extends Cell('H') {} + +object tail extends Cell('t') {} + +object conductor extends Cell('.') {} + +Map cellsByChar = map { for (cell in `Cell`.caseValues) cell.char->cell }; + +class Wireworld(String data) { + + value lines = data.lines; + + value width = max(lines*.size); + value height = lines.size; + + function toIndex(Integer x, Integer y) => x + y * width; + + variable value currentState = Array.ofSize(width * height, emptyCell); + variable value nextState = Array.ofSize(width * height, emptyCell); + + for (j->line in lines.indexed) { + for (i->char in line.indexed) { + currentState[toIndex(i, j)] = cellsByChar[char] else emptyCell; + } + } + + value emptyGrid = Array.ofSize(width * height, emptyCell); + void clear(Array cells) => emptyGrid.copyTo(cells); + + shared void update() { + clear(nextState); + for(j in 0:height) { + for(i in 0:width) { + if(exists cell = currentState[toIndex(i, j)]) { + value nextCell = cell.output(neighborhood(currentState, i, j)); + nextState[toIndex(i, j)] = nextCell; + } + } + } + value temp = currentState; + currentState = nextState; + nextState = temp; + } + + shared void display() { + for (row in currentState.partition(width)) { + print("".join(row)); + } + } + + shared {Cell*} neighborhood(Array grid, Integer x, Integer y) => { + for (j in y - 1..y + 1) + for (i in x - 1..x + 1) + if(i in 0:width && j in 0:height) + grid[toIndex(i, j)] + }.coalesced; + +} + +shared void run() { + value data = "tH......... + . . + ... + . . + Ht.. ......"; + + value world = Wireworld(data); + + variable value generation = 0; + + void display() { + print("generation: ``generation``"); + world.display(); + } + + display(); + + while (true) { + if (exists input = process.readLine(), input.lowercased == "q") { + return; + } + world.update(); + generation++; + display(); + + } +} diff --git a/Task/Wireworld/JavaScript/wireworld.js b/Task/Wireworld/JavaScript/wireworld.js new file mode 100644 index 0000000000..d78cf62846 --- /dev/null +++ b/Task/Wireworld/JavaScript/wireworld.js @@ -0,0 +1,88 @@ +var ctx, sizeW, sizeH, scl = 10, map, tmp; +function getNeighbour( i, j ) { + var ii, jj, c = 0; + for( var b = -1; b < 2; b++ ) { + for( var a = -1; a < 2; a++ ) { + ii = i + a; jj = j + b; + if( ii < 0 || ii >= sizeW || jj < 0 || jj >= sizeH ) continue; + if( map[ii][jj] == 1 ) c++; + } + } + return ( c == 1 || c == 2 ); +} +function simulate() { + drawWorld(); + for( var j = 0; j < sizeH; j++ ) { + for( var i = 0; i < sizeW; i++ ) { + switch( map[i][j] ) { + case 0: tmp[i][j] = 0; break; + case 1: tmp[i][j] = 2; break; + case 2: tmp[i][j] = 3; break; + case 3: + if( getNeighbour( i, j ) ) tmp[i][j] = 1; + else tmp[i][j] = 3; + break; + } + } + } + [tmp, map] = [map, tmp]; + setTimeout( simulate, 200 ); +} +function drawWorld() { + ctx.fillStyle = "#000"; ctx.fillRect( 0, 0, sizeW * scl, sizeH * scl ); + for( var j = 0; j < sizeH; j++ ) { + for( var i = 0; i < sizeW; i++ ) { + switch( map[i][j] ) { + case 0: continue; + case 1: ctx.fillStyle = "#03f"; break; + case 2: ctx.fillStyle = "#f30"; break; + case 3: ctx.fillStyle = "#ff3"; break; + } + ctx.fillRect( i, j, 1, 1 ); + } + } +} +function openFile( event ) { + var input = event.target; + var reader = new FileReader(); + reader.onload = function() { + createWorld( reader.result ); + }; + reader.readAsText(input.files[0]); +} +function createWorld( txt ) { + var l = txt.split( "\n" ); + sizeW = parseInt( l[0] ); + sizeH = parseInt( l[1] ); + map = new Array( sizeW ); + tmp = new Array( sizeW ); + for( var i = 0; i < sizeW; i++ ) { + map[i] = new Array( sizeH ); + tmp[i] = new Array( sizeH ); + for( var j = 0; j < sizeH; j++ ) { + map[i][j] = tmp[i][j] = 0; + } + } + var t; + for( var j = 0; j < sizeH; j++ ) { + for( var i = 0; i < sizeW; i++ ) { + switch( l[j + 2][i] ) { + case " ": t = 0; break; + case "H": t = 1; break; + case "t": t = 2; break; + case ".": t = 3; break; + } + map[i][j] = t; + } + } + init(); +} +function init() { + var canvas = document.createElement( "canvas" ); + canvas.width = sizeW * scl; + canvas.height = sizeH * scl; + ctx = canvas.getContext( "2d" ); + ctx.scale( scl, scl ); + document.body.appendChild( canvas ); + simulate(); +} diff --git a/Task/Wireworld/jq/wireworld-1.jq b/Task/Wireworld/Jq/wireworld-1.jq similarity index 100% rename from Task/Wireworld/jq/wireworld-1.jq rename to Task/Wireworld/Jq/wireworld-1.jq diff --git a/Task/Wireworld/jq/wireworld-2.jq b/Task/Wireworld/Jq/wireworld-2.jq similarity index 100% rename from Task/Wireworld/jq/wireworld-2.jq rename to Task/Wireworld/Jq/wireworld-2.jq diff --git a/Task/Wireworld/jq/wireworld-3.jq b/Task/Wireworld/Jq/wireworld-3.jq similarity index 100% rename from Task/Wireworld/jq/wireworld-3.jq rename to Task/Wireworld/Jq/wireworld-3.jq diff --git a/Task/Wireworld/jq/wireworld-4.jq b/Task/Wireworld/Jq/wireworld-4.jq similarity index 100% rename from Task/Wireworld/jq/wireworld-4.jq rename to Task/Wireworld/Jq/wireworld-4.jq diff --git a/Task/Wireworld/jq/wireworld-5.jq b/Task/Wireworld/Jq/wireworld-5.jq similarity index 100% rename from Task/Wireworld/jq/wireworld-5.jq rename to Task/Wireworld/Jq/wireworld-5.jq diff --git a/Task/Wireworld/Lua/wireworld.lua b/Task/Wireworld/Lua/wireworld.lua new file mode 100644 index 0000000000..d3e066b359 --- /dev/null +++ b/Task/Wireworld/Lua/wireworld.lua @@ -0,0 +1,69 @@ +local map = {{'t', 'H', '.', '.', '.', '.', '.', '.', '.', '.', '.'}, + {'.', ' ', ' ', ' ', '.'}, + {' ', ' ', ' ', '.', '.', '.'}, + {'.', ' ', ' ', ' ', '.'}, + {'H', 't', '.', '.', ' ', '.', '.', '.', '.', '.', '.'}} + +function step(map) + local next = {} + for i = 1, #map do + next[i] = {} + for j = 1, #map[i] do + next[i][j] = map[i][j] + if map[i][j] == "H" then + next[i][j] = "t" + elseif map[i][j] == "t" then + next[i][j] = "." + elseif map[i][j] == "." then + local count = ((map[i-1] or {})[j-1] == "H" and 1 or 0) + + ((map[i-1] or {})[j] == "H" and 1 or 0) + + ((map[i-1] or {})[j+1] == "H" and 1 or 0) + + ((map[i] or {})[j-1] == "H" and 1 or 0) + + ((map[i] or {})[j+1] == "H" and 1 or 0) + + ((map[i+1] or {})[j-1] == "H" and 1 or 0) + + ((map[i+1] or {})[j] == "H" and 1 or 0) + + ((map[i+1] or {})[j+1] == "H" and 1 or 0) + if count == 1 or count == 2 then + next[i][j] = "H" + else + next[i][j] = "." + end + end + end + end + return next +end + +if not not love then + local time, frameTime, size = 0, 0.25, 20 + local colors = {["."] = {255, 200, 0}, + ["t"] = {255, 0, 0}, + ["H"] = {0, 0, 255}} + function love.update(dt) + time = time + dt + if time > frameTime then + time = time - frameTime + map = step(map) + end + end + + function love.draw() + for i = 1, #map do + for j = 1, #map[i] do + love.graphics.setColor(colors[map[i][j]] or {0, 0, 0}) + love.graphics.rectangle("fill", j*size, i*size, size, size) + end + end + end +else + for iter = 1, 10 do + print("\nstep "..iter.."\n") + for i = 1, #map do + for j = 1, #map[i] do + io.write(map[i][j]) + end + io.write("\n") + end + map = step(map) + end +end diff --git a/Task/Wireworld/Phix/wireworld.phix b/Task/Wireworld/Phix/wireworld.phix new file mode 100644 index 0000000000..0ce34be504 --- /dev/null +++ b/Task/Wireworld/Phix/wireworld.phix @@ -0,0 +1,167 @@ +-- +-- demo\rosetta\Wireworld.exw +-- ========================== +-- +-- Invoke with file to read or let it read the one below (if compiled assumes source is in the same directory) +-- +-- Note that tabs in description files are not supported - where necessary spaces can be replaced with _ chars. +-- (tab chars in text files should technically always represent (to-next) 8 spaces, but not many editors respect +-- that, and instead assume the file will only ever be read by the same program/with matching settings. ) +-- (see also demo\edix\src\tabs.e\ExpandTabs() for what you'd need if you knew what tab chars really meant.) +-- +/* -- default description: +tH......... +.___. +___... +.___. +Ht.. ...... +*/ +sequence lines, counts +integer longest + +function valid_line(string line, integer l=0) + if length(line)=0 then return 0 end if + for i=1 to length(line) do + integer ch = line[i] + if not find(ch," _.tH") then + if l and ch='\t' then + -- as above + printf(1,"error: tab char on line %d\n",{l}) + {} = wait_key() + abort(0) + end if + return 0 + end if + end for + return 1 +end function + +procedure load_desc() + string filename = substitute(command_line()[$],".exe",".exw") + integer fn = open(filename,"r") + if fn=-1 then + printf(1,"error opening %s\n",{filename}) + {} = wait_key() + abort(0) + end if + sequence text = get_text(fn,GT_LF_STRIPPED) + close(fn) + lines = {} + for i=1 to length(text) do + string line = text[i] + if valid_line(line) then + lines = {line} + longest = length(line) + for j=i+1 to length(text) do + line = text[j] + if not valid_line(line,j) then exit end if + lines = append(lines,line) + if longest=1 and cy<=length(lines) + and cx>=1 and cx<=length(lines[cy]) + and lines[cy][cx]='H' then + count += 1 + end if + end for + counts[y][x] = (count=1 or count=2) + end if + end for + end for +end procedure + +include pGUI.e + +Ihandle dlg, canvas, timer +cdCanvas cddbuffer, cdcanvas + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) + integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE") + integer dx = floor(w/(longest+2)) + integer dy = floor(h/(length(lines)+2)) + cdCanvasActivate(cddbuffer) + cdCanvasClear(cddbuffer) + set_counts() + for y=1 to length(lines) do + for x=1 to length(lines[y]) do + integer c = lines[y][x], colour + if find(c," _") then + colour = CD_BLACK + elsif c='.' then + colour = CD_YELLOW + if counts[y][x] then + lines[y][x] = 'H' + end if + elsif c='H' then + colour = CD_BLUE + lines[y][x] = 't' + elsif c='t' then + colour = CD_RED + lines[y][x] = '.' + end if + cdCanvasSetForeground(cddbuffer, colour) + cdCanvasBox(cddbuffer,x*dx,x*dx+dx,h-y*dy,h-(y*dy+dy)) + end for + end for + cdCanvasFlush(cddbuffer) + return IUP_DEFAULT +end function + +function timer_cb(Ihandle /*ih*/) + IupUpdate(canvas) + return IUP_IGNORE +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + cdCanvasSetBackground(cddbuffer, CD_BLACK) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +procedure main() + load_desc() + IupOpen() + + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "300x180") + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + + timer = IupTimer(Icallback("timer_cb"), 500) + + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", "Wireworld") + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + + IupShow(dlg) + IupSetAttribute(canvas, "RASTERSIZE", NULL) + IupMainLoop() + IupClose() +end procedure + +main() diff --git a/Task/Wireworld/REXX/wireworld.rexx b/Task/Wireworld/REXX/wireworld.rexx index ab2becd027..c05733f94f 100644 --- a/Task/Wireworld/REXX/wireworld.rexx +++ b/Task/Wireworld/REXX/wireworld.rexx @@ -1,37 +1,36 @@ -/*REXX program displays a wire world Cartesian grid of four─state cells. */ +/*REXX program displays a wire world Cartesian grid of four─state cells. */ signal on halt /*handle any cell growth interruptus. */ parse arg iFID . '(' generations rows cols bare head tail wire clearScreen reps -if iFID=='' then iFID="WIREWORLD.TXT" /*should default input file be used? */ - blank = 'BLANK' /*the "name" for a blank. */ +if iFID=='' then iFID= "WIREWORLD.TXT" /*should default input file be used? */ + bla = 'BLANK' /*the "name" for a blank. */ generations = p(generations 100 ) /*number generations that are allowed. */ rows = p(rows 3 ) /*the number of cell rows. */ cols = p(cols 3 ) /* " " " " columns. */ - bare = pickChar(bare blank ) /*an empty cell character. */ + bare = pickChar(bare bla ) /*an empty cell character. */ clearScreen = p(clearScreen 0 ) /*1 means to clear the screen. */ head = pickChar(head 'H' ) /*pick the character for the head. */ - tail = pickChar(wire . ) /* " " " " " wire. */ + tail = pickChar(tail 't' ) /* " " " " " tail. */ + wire = pickChar(wire . ) /* " " " " " wire. */ reps = p(reps 2 ) /*stop program if there are 2 repeats.*/ -fents=max(linesize()-1,cols) /*the fence width used after displaying*/ +fents=max(cols, linesize() - 1) /*the fence width used after displaying*/ #reps=0; $.=bare /*at start, universe is new and barren.*/ gens=abs(generations) /*use for convenience (and short name).*/ /* [↓] read the input file. */ do r=1 while lines(iFID)\==0 /*keep reading until the End─Of─File. */ - q=strip(linein(iFID), 'T') /*get single line from the input file. */ - _=length(q) /*obtain the length of this (input) row*/ - cols=max(cols, _) /*calculate the maximum number of cols.*/ - do c=1 for _; $.r.c=substr(q, c, 1); end /*assign the row cells.*/ + q=strip(linein(iFID),'T'); L=length(q) /*get a line from input file; get len.*/ + cols=max(cols, L) /*calculate maximum number of columns. */ + do c=1 for L; $.r.c=substr(q, c, 1); end /*c*/ /*assign the row cells.*/ end /*r*/ rows=r-1 /*adjust the row number (from DO loop).*/ -life=0; !.=0; call showCells /*display initial state of the cells. */ +life=0; !.=0; call showCells /*display initial state of the cells. */ /*watch cells evolve, 4 possible states*/ - do life=1 for gens; @.=bare /*perform for the number of generations*/ - + do life=1 for gens; @.=bare /*perform for the number of generations*/ do r=1 for rows /*process each of the rows. */ do c=1 for cols; ?=$.r.c; ??=? /* " " " " columns. */ select /*determine the type of cell. */ when ?==head then ??=tail when ?==tail then ??=wire - when ?==wire then do; n=hood(); if n==1 | n==2 then ??=head; end + when ?==wire then do; #=hood(); if #==1 | #==2 then ??=head; end otherwise nop end /*select*/ @.r.c=?? @@ -44,21 +43,20 @@ life=0; !.=0; call showCells /*display initial state of the /*stop watching the universe (or life).*/ halt: if life-1\==gens then say 'The ~~~Wireworld~~~ program was interrupted.' done: exit /*stick a fork in it, we are all done.*/ +/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ +$: parse arg _row,_col; return $._row._col==head +assign$: do r=1 for rows; do c=1 for cols; $.r.c=@.r.c; end; end; return +hood: return $(r-1,c-1) + $(r-1,c) + $(r-1,c+1) + $(r,c-1) + $(r,c+1) + $(r+1,c-1) + $(r+1,c) + $(r+1,c+1) +p: return word(arg(1), 1) /*pick the 1st word in list.*/ +pickChar: _=p(arg(1));L=length(_);if translate(_)==bla then _=' ';if L==3 then _=d2c(_);if L==2 then _=x2c(_);return _ +showRows: _=; do r=1 for rows; z=; do c=1 for cols; z=z||$.r.c; end; z=strip(z,'T'); say z; _=_||z; end; return /*──────────────────────────────────────────────────────────────────────────────────────*/ showCells: if clearScreen then 'CLS' /*◄──change this for the OS.*/ call showRows /*show rows in proper order.*/ - say right(copies('═',fents)life,fents) /*display a bunch of cells. */ - if _=='' then signal done /*No life? Then stop run. */ - if !._ then #reps=#reps+1 /*detected repeated pattern.*/ - !._=1 /*it is now existence state.*/ + say right( copies('═', fents)life, fents) /*display a bunch of cells. */ + if _=='' then signal done /*No life? Then stop run. */ + if !._ then #reps=#reps+1 /*detected repeated pattern.*/ + !._=1 /*it's now existence state. */ if reps\==0 & #reps<=reps then return /*so far, so good, no reps. */ - say '"Wireworld" repeated itself' reps "times, program is stopping." - signal done /*exit program, we're done. */ -/*─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ -$: parse arg _row,_col; return ($._row._col==head) -assign$: do r=1 for rows; do c=1 for cols; $.r.c=@.r.c; end; end; return -err: say; say center(' error! ',max(40,linesize()%2),"*"); say; do j=1 for arg(); say arg(j); say; end; say; exit 13 -hood: return $(r-1,c-1) + $(r-1,c) + $(r-1,c+1) + $(r,c-1) + $(r,c+1) + $(r+1,c-1) + $(r+1,c) + $(r+1,c+1) -p: return word(arg(1), 1) -pickChar: _=p(arg(1));if translate(_)==blank then _=' ';if length(_)==3 then _=d2c(_);if length(_)==2 then _=x2c(_);return _ -showRows: _=; do r=1 for rows; z=; do c=1 for cols; z=z || $.r.c; end; z=strip(z,'T'); say z; _=_ || z; end; return + say '"Wireworld" repeated itself' reps "times, program is stopping." + signal done /*jump to this pgm's "exit".*/ diff --git a/Task/Word-wrap/360-Assembly/word-wrap.360 b/Task/Word-wrap/360-Assembly/word-wrap.360 new file mode 100644 index 0000000000..3fa6184a44 --- /dev/null +++ b/Task/Word-wrap/360-Assembly/word-wrap.360 @@ -0,0 +1,223 @@ +* Word wrap 29/01/2017 +WORDWRAP CSECT + USING WORDWRAP,R13 + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) prolog + ST R13,4(R15) " <- + ST R15,8(R13) " -> + LR R13,R15 " addressability + MVC S2,=CL96' ' s2='' + SR R0,R0 + STH R0,LENS2 lens2=0 + LA R8,1 i=1 +LOOPI CH R8,=AL2(NTS) do i=1 to hbound(ts) + BH ELOOPI -- + LH R4,LENS2 + LTR R4,R4 if lens2=0 + BNZ IFLENS2 then + LR R1,R8 i + MH R1,=H'48' + LA R14,TS-48(R1) + MVC S(48),0(R14) s=ts(i) + MVC S+48(48),=CL48' ' + LA R12,L'TS jmax=length(ts) + B EIFLENS2 else +IFLENS2 MVC S,=CL96' ' s='' + LA R6,S @s + LH R7,LENS2 + LA R4,S2 @s2 + LH R5,LENS2 + MVCL R6,R4 substr(s,1,lens2)=substr(s2,1,lens2) + LH R2,LENS2 + LA R2,1(R2) lens2+1 + LR R1,R8 i + MH R1,=H'48' + LA R14,TS-48(R1) @ts(i) + LA R15,S-1 + AR R15,R2 + MVC 0(48,R15),0(R14) substr(s,lens2+1,48)=ts(i) + LA R12,L'S jmax=length(s) +EIFLENS2 MVI OKS2,X'01' oks2=true +WHILEOK CLI OKS2,X'01' do while(oks2) + BNE EWHILEOK -- + LR R9,R12 j=jmax /*loop1*/ +LOOPJ1 CH R9,=H'1' do j=jmax to 1 by -1 + BL ELOOPJ1 -- + LA R14,S-1 @s-1 + AR R14,R9 j + MVC CJ(1),0(R14) cj=substr(s,j,1) + CLI CJ,C' ' if cj^=' ' + BNE ELOOPJ1 then leave j + BCTR R9,0 j=j-1 + B LOOPJ1 end do j +ELOOPJ1 STH R9,LENS lens=j {length of s} + MVI OKJ,X'00' okj=false /*loop2*/ + LH R11,W js=w + LH R4,W + CH R4,LENS if w>lens + BNH IFWLENS + LH R11,LENS js=lens +IFWLENS LR R9,R11 j=js +LOOPJ2 CH R9,=H'1' do j=js to 1 by -1 + BL ELOOPJ2 -- + LA R14,S-1 @s-1 + AR R14,R9 +j + MVC CJ(1),0(R14) cj=substr(s,j,1) + CLI CJ,C' ' if cj=' ' + BNE ITERJ2 then + MVI OKJ,X'01' okj=true + B ELOOPJ2 leave j +ITERJ2 BCTR R9,0 j=j-1 + B LOOPJ2 end do j +ELOOPJ2 CLI OKJ,X'00' if ^okj + BNE ELOOPK + MVI OKK,X'00' okk=false /*loop3*/ + LH R10,W k=w +LOOPK CH R10,LENS do k=w to lens + BH ELOOPK -- + LA R14,S-1 @s-1 + AR R14,R10 +k + MVC CK(1),0(R14) ck=substr(s,k,1) + CLI CK,C' ' if ck=' ' + BNE ITERK then + MVI OKK,X'01' okk=true + B ELOOPK leave k +ITERK LA R10,1(R10) k=k+1 + B LOOPK end do k +ELOOPK MVC S2,=CL96' ' s2=' ' + SR R0,R0 + STH R0,LENS2 lens2=0 + MVI CAS,X'01' cas=true + LH R1,LENS + CH R1,W lens0 + BNP ELJLENS2 then + LA R6,S2 + LH R7,LENS2 + LA R4,S(R9) @s(j+1) + LR R5,R7 + MVCL R6,R4 s2=substr(s,j+1,lens2) + B EFJLENS2 +ELJLENS2 SR R0,R0 else + STH R0,LENS2 lens2=0 +EFJLENS2 B IFNOTCAS +NOKJ CLI OKK,X'01' else if okk + BNE NOTOKK + STH R10,LENS1 lens1=k + LH R2,LENS + SR R2,R10 -k + LA R2,1(R2) + STH R2,LENS2 lens2=lens-k+1 + LA R6,S1 + LR R7,R10 k + LA R4,S + LR R5,R7 + MVCL R6,R4 s1=substr(s,1,k) + LH R4,LENS2 + LTR R4,R4 if lens2>0 + BNP ELKLENS2 then + LA R6,S2 + LH R7,LENS2 + LA R4,S(R10) @s(k+1) + LR R5,R7 + MVCL R6,R4 s2=substr(s,k+1,lens2) + B EFKLENS2 else +ELKLENS2 SR R0,R0 + STH R0,LENS2 lens2=0 +EFKLENS2 B IFNOTCAS else +NOTOKK LH R0,LENS + STH R0,LENS1 lens1=lens + MVC S1,S s1=s +IFNOTCAS CLI CAS,X'01' if cas + BNE ELCAS then + LH R7,LENS + LA R7,1(R7) + LA R6,S2 + LA R4,S + LR R5,R7 + MVCL R6,R4 s2=substr(s,1,lens+1) + LH R2,LENS + LA R2,1(R2) + STH R2,LENS2 lens2=lens+1 + B EFCAS else +ELCAS LA R6,PG + LA R7,L'PG + LA R4,S1 + LH R5,LENS1 + ICM R5,B'1000',=C' ' padding + MVCL R6,R4 pg=substr(s1,1,lens1) + XPRNT PG,L'PG put skip list(pg) +EFCAS MVI OKS2,X'00' oks2=false + LH R4,LENS2 + CH R4,W if lens2>w + BNH EFWLENS2 then + MVI OKS2,X'01' oks2=true + LH R0,LENS2 + STH R0,LENS lens=lens2 + MVC S,S2 s=s2 +EFWLENS2 B WHILEOK end while +EWHILEOK LA R8,1(R8) i=i+1 + B LOOPI end do i +ELOOPI LH R4,LENS2 + LTR R4,R4 if lens2^=0 + BZ EFLENS2N then + LA R6,PG + LA R7,L'PG + LA R4,S2 + LH R5,LENS2 + ICM R5,B'1000',=C' ' padding + MVCL R6,R4 pg=substr(s2,1,lens2) + XPRNT PG,L'PG put skip list(pg) +EFLENS2N L R13,4(0,R13) epilog + LM R14,R12,12(R13) " restore + XR R15,R15 " rc=0 + BR R14 exit +TS DC CL48'In olden times when wishing still helped one,' + DC CL48'there lived a king whose daughters were all,' + DC CL48'beautiful, but the youngest was so beautiful' + DC CL48'that the sun itself, which has seen so much,' + DC CL48'was astonished whenever it shone in her face.' + DC CL48'Close by the king''s castle lay a great dark' + DC CL48'forest, and under an old lime tree in the' + DC CL48'forest was a well, and when the day was very' + DC CL48'warm, the king''s child went out into the forest' + DC CL48'and sat down by the side of the cool fountain,' + DC CL48'and when she was bored she took a golden ball,' + DC CL48'and threw it up on high and caught it, and this' + DC CL48'ball was her favorite plaything.' +TSE DC 0C +NTS EQU (TSE-TS)/L'TS +W DC H'36' <-- input width 12<=w<=80 +LENS DS H +S DS CL96 +LENS1 DS H +S1 DS CL96 +LENS2 DS H +S2 DS CL96 +OKJ DS X +OKK DS X +OKS2 DS X +CAS DS X +CJ DS CL1 +CK DS CL1 +PG DS CL80 + YREGS + END WORDWRAP diff --git a/Task/Word-wrap/BaCon/word-wrap.bacon b/Task/Word-wrap/BaCon/word-wrap.bacon new file mode 100644 index 0000000000..6565b7ae40 --- /dev/null +++ b/Task/Word-wrap/BaCon/word-wrap.bacon @@ -0,0 +1,13 @@ +paragraph$ = "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." + +PRINT ALIGN$(paragraph$, 72, 0) +PRINT ALIGN$(paragraph$, 90, 0) diff --git a/Task/Word-wrap/Batch-File/word-wrap.bat b/Task/Word-wrap/Batch-File/word-wrap.bat new file mode 100644 index 0000000000..ee95e50c4f --- /dev/null +++ b/Task/Word-wrap/Batch-File/word-wrap.bat @@ -0,0 +1,40 @@ +@echo off + +set "input=Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur!" +rem call the function (the second parameter is the line width) +call :wrap "%input%" 40 +echo( +call :wrap "%input%" 70 +pause>nul +exit /b 0 + +:: The procedure +:wrap +set "line=" +set "tmp_str=%~1" +set /a "width=%2", "width-=1" + +:proc_loop +rem check if we are done already +if "%tmp_str%"=="" ( + setlocal enabledelayedexpansion + if defined line echo(!line! + endlocal & goto :EOF +) + +rem not yet done, so take a word and process it +for /f "tokens=1,* delims= " %%A in ("%tmp_str%") do ( + set "word=%%A" + set "tmp_str=%%B" + + setlocal enabledelayedexpansion + if "!line!"=="" (set "testline=!word!") else (set "testline=!line! !word!") + if "!testline:~%width%,1!" == "" ( + set "line=!testline!" + ) else ( + echo(!line! + set "line=!word!" + ) +) +endlocal & set "line=%line%" +goto proc_loop diff --git a/Task/Word-wrap/Clojure/word-wrap-2.clj b/Task/Word-wrap/Clojure/word-wrap-2.clj index 53e55693ca..cb566bd4f9 100644 --- a/Task/Word-wrap/Clojure/word-wrap-2.clj +++ b/Task/Word-wrap/Clojure/word-wrap-2.clj @@ -1,4 +1,4 @@ ;; Wrap line base on regular expression (defn wrap-line [size text] - (re-seq (re-pattern (str ".{0," size "}\\s")) + (re-seq (re-pattern (str ".{1," size "}\\s|.{1," size "}")) (clojure.string/replace text #"\n" " "))) diff --git a/Task/Word-wrap/Clojure/word-wrap-3.clj b/Task/Word-wrap/Clojure/word-wrap-3.clj index 44a0c79ae0..97f5ac5a40 100644 --- a/Task/Word-wrap/Clojure/word-wrap-3.clj +++ b/Task/Word-wrap/Clojure/word-wrap-3.clj @@ -1,12 +1,3 @@ -(def text "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.") - -(doseq [line (wrap-line 72 text)] - (println line)) +;; cl-format based version +(defn wrap-line [size text] + (clojure.pprint/cl-format nil (str "~{~<~%~1," size ":;~A~> ~}") (clojure.string/split text #" "))) diff --git a/Task/Word-wrap/Clojure/word-wrap-4.clj b/Task/Word-wrap/Clojure/word-wrap-4.clj new file mode 100644 index 0000000000..44a0c79ae0 --- /dev/null +++ b/Task/Word-wrap/Clojure/word-wrap-4.clj @@ -0,0 +1,12 @@ +(def text "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.") + +(doseq [line (wrap-line 72 text)] + (println line)) diff --git a/Task/Word-wrap/Elena/word-wrap.elena b/Task/Word-wrap/Elena/word-wrap.elena new file mode 100644 index 0000000000..983ef3f35c --- /dev/null +++ b/Task/Word-wrap/Elena/word-wrap.elena @@ -0,0 +1,50 @@ +import extensions. +import system'routines. +import extensions. +import extensions'text. + +literal text = + "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.". + +extension wrapOp +{ + wrap(IntNumber lineWidth) + [ + int currentWidth := 0. + + ^ TokenEnumerator + new(self); + selectBy(:word) + [ + currentWidth += word length. + if (currentWidth > lineWidth) + [ + currentWidth := word length + 1. + + ^ 'newLine + word + " " + ]; + [ + currentWidth += 1. + + ^ word + " " + ] + ]; + summarize(String new). + ] +} + +program = +[ + console printLine(String new; write:"-" length:72). + console printLine(text wrap(72)). + console printLine(String new; write:"-" length:80). + console printLine(text wrap(80)). +]. diff --git a/Task/Word-wrap/Groovy/word-wrap-3.groovy b/Task/Word-wrap/Groovy/word-wrap-3.groovy new file mode 100644 index 0000000000..8437abdff7 --- /dev/null +++ b/Task/Word-wrap/Groovy/word-wrap-3.groovy @@ -0,0 +1,6 @@ +String wordWrap(str, width=80) { + str.tokenize(' ').inject([[]]) { rows, word -> + if (rows.last().join(' ').length() + word.length() <= width) rows.last() << word else rows << [word] + rows + }.collect { it.join(' ') }.join('\n') +} diff --git a/Task/Word-wrap/Groovy/word-wrap-4.groovy b/Task/Word-wrap/Groovy/word-wrap-4.groovy new file mode 100644 index 0000000000..bc76787e70 --- /dev/null +++ b/Task/Word-wrap/Groovy/word-wrap-4.groovy @@ -0,0 +1,8 @@ +import groovy.transform.TailRecursive +import static java.lang.Math.min + +@TailRecursive +String wordWrap(str, w, i=w, b=''<<'', len=str.length()-1, x=0) { + b.setCharAt(x = (b << str[b.length()..i]).lastIndexOf(' '), '\n' as char) + b.length()+w >= len ? b << str[i..-1] : wordWrap(str, w, min(x+w+1, len), b, len, 0) +} diff --git a/Task/Word-wrap/Groovy/word-wrap-5.groovy b/Task/Word-wrap/Groovy/word-wrap-5.groovy new file mode 100644 index 0000000000..4c9e571580 --- /dev/null +++ b/Task/Word-wrap/Groovy/word-wrap-5.groovy @@ -0,0 +1,2 @@ +def a = new StringBuilder() +def a = '' << '' diff --git a/Task/Word-wrap/Haskell/word-wrap-1.hs b/Task/Word-wrap/Haskell/word-wrap-1.hs index a94bfdaa5c..e2f5840bae 100644 --- a/Task/Word-wrap/Haskell/word-wrap-1.hs +++ b/Task/Word-wrap/Haskell/word-wrap-1.hs @@ -1,23 +1,25 @@ -ss = "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." +ss = + concat + [ "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." + ] -wordwrap maxlen = (wrap_ 0) . words where - wrap_ _ [] = "\n" - wrap_ pos (w:ws) - -- at line start: put down the word no matter what - | pos == 0 = w ++ wrap_ (pos + lw) ws - | pos + lw + 1 > maxlen = '\n':wrap_ 0 (w:ws) - | otherwise = " " ++ w ++ wrap_ (pos + lw + 1) ws - where lw = length w +wordwrap maxlen = wrap_ 0 . words + where + wrap_ _ [] = "\n" + wrap_ pos (w:ws) + -- at line start: put down the word no matter what + | pos == 0 = w ++ wrap_ (pos + lw) ws + | pos + lw + 1 > maxlen = '\n' : wrap_ 0 (w : ws) + | otherwise = ' ' : w ++ wrap_ (pos + lw + 1) ws + where + lw = length w -main = do - putStr $ wordwrap 72 ss - putStr "\n" - putStr $ wordwrap 32 ss +main = mapM_ putStr [wordwrap 72 ss, "\n", wordwrap 32 ss] diff --git a/Task/Word-wrap/Haskell/word-wrap-2.hs b/Task/Word-wrap/Haskell/word-wrap-2.hs index d73811cd54..f0f75c128d 100644 --- a/Task/Word-wrap/Haskell/word-wrap-2.hs +++ b/Task/Word-wrap/Haskell/word-wrap-2.hs @@ -1,21 +1,24 @@ -import Data.List +import Data.List (inits, tails, tail) -teststring = "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." +testString = + concat + [ "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." + ] -wwrap'' _ [] = [] -wwrap'' i ss = (\(a,b) -> a : wwrap'' i b) - $ last . filter ((<=i) . length . unwords . fst) - $ zip (inits ss) (tails ss) +wWrap'' _ [] = [] +wWrap'' i ss = + (\(a, b) -> a : wWrap'' i b) $ + last . filter ((<= i) . length . unwords . fst) $ zip (inits ss) (tails ss) -wwrap :: Int -> String -> String -wwrap i = unlines . map unwords . wwrap'' i . words . concat . lines +wWrap :: Int -> String -> String +wWrap i = unlines . map unwords . wWrap'' i . words . concat . lines -main = putStrLn $ wwrap 80 teststring +main = putStrLn $ wWrap 80 testString diff --git a/Task/Word-wrap/jq/word-wrap-1.jq b/Task/Word-wrap/Jq/word-wrap-1.jq similarity index 100% rename from Task/Word-wrap/jq/word-wrap-1.jq rename to Task/Word-wrap/Jq/word-wrap-1.jq diff --git a/Task/Word-wrap/jq/word-wrap-2.jq b/Task/Word-wrap/Jq/word-wrap-2.jq similarity index 100% rename from Task/Word-wrap/jq/word-wrap-2.jq rename to Task/Word-wrap/Jq/word-wrap-2.jq diff --git a/Task/Word-wrap/jq/word-wrap-3.jq b/Task/Word-wrap/Jq/word-wrap-3.jq similarity index 100% rename from Task/Word-wrap/jq/word-wrap-3.jq rename to Task/Word-wrap/Jq/word-wrap-3.jq diff --git a/Task/Word-wrap/jq/word-wrap-4.jq b/Task/Word-wrap/Jq/word-wrap-4.jq similarity index 100% rename from Task/Word-wrap/jq/word-wrap-4.jq rename to Task/Word-wrap/Jq/word-wrap-4.jq diff --git a/Task/Word-wrap/jq/word-wrap-5.jq b/Task/Word-wrap/Jq/word-wrap-5.jq similarity index 100% rename from Task/Word-wrap/jq/word-wrap-5.jq rename to Task/Word-wrap/Jq/word-wrap-5.jq diff --git a/Task/Word-wrap/Kotlin/word-wrap.kotlin b/Task/Word-wrap/Kotlin/word-wrap.kotlin new file mode 100644 index 0000000000..836e8202ab --- /dev/null +++ b/Task/Word-wrap/Kotlin/word-wrap.kotlin @@ -0,0 +1,37 @@ +// version 1.1.3 + +val text = + "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." + +fun greedyWordwrap(text: String, lineWidth: Int): String { + val words = text.split(' ') + val sb = StringBuilder(words[0]) + var spaceLeft = lineWidth - words[0].length + for (word in words.drop(1)) { + val len = word.length + if (len + 1 > spaceLeft) { + sb.append("\n").append(word) + spaceLeft = lineWidth - len + } + else { + sb.append(" ").append(word) + spaceLeft -= (len + 1) + } + } + return sb.toString() +} + +fun main(args: Array) { + println("Greedy algorithm - wrapped at 72:") + println(greedyWordwrap(text, 72)) + println("\nGreedy algorithm - wrapped at 80:") + println(greedyWordwrap(text, 80)) +} diff --git a/Task/Word-wrap/Ol/word-wrap.ol b/Task/Word-wrap/Ol/word-wrap.ol new file mode 100644 index 0000000000..f73e38b61b --- /dev/null +++ b/Task/Word-wrap/Ol/word-wrap.ol @@ -0,0 +1,35 @@ +(define (get-one-word start) +(let loop ((chars #null) (end start)) + (let ((char (car end))) + (if (has? (list #\space #\newline) char) + (values (reverse chars) (force (cdr end))) + (loop (cons char chars) (force (cdr end))))))) + +(define (get-all-words string) +(let loop ((words #null) (start (str-iter string))) + (let* ((word next (get-one-word start))) + (if (null? next) + (reverse words) + (loop (cons (runes->string word) words) next))))) + +(define (get-one-line words n) +(let loop ((line #null) (words words) (i 0)) + (let*((word (car words)) + (len (string-length word))) + (if (null? (cdr words)) + (values (reverse (cons word line)) #null) + (if (> (+ i len) n 1) + (values (reverse line) words) + (loop (cons word line) (cdr words) (+ i len 1))))))) + +(define (get-all-lines words n) +(let loop ((lines #null) (words words)) + (let* ((line words (get-one-line words n))) + (if (null? words) + (reverse (cons line lines)) + (loop (cons line lines) words))))) + +(define (hyphenation width string) +(let*((words (get-all-words string)) + (lines (get-all-lines words width))) + lines)) diff --git a/Task/Word-wrap/Phix/word-wrap.phix b/Task/Word-wrap/Phix/word-wrap.phix new file mode 100644 index 0000000000..2e3dc9e471 --- /dev/null +++ b/Task/Word-wrap/Phix/word-wrap.phix @@ -0,0 +1,25 @@ +string s = substitute("""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.""","\n"," ") + +procedure word_wrap(string s, integer maxwidth) + sequence words = split(s) + string line = words[1] + for i=2 to length(words) do + string word = words[i] + if length(line)+length(word)+1>maxwidth then + puts(1,line&"\n") + line = word + else + line &= " "&word + end if + end for + puts(1,line&"\n") +end procedure + +word_wrap(s,72) +word_wrap(s,80) diff --git a/Task/Word-wrap/Python/word-wrap.py b/Task/Word-wrap/Python/word-wrap.py new file mode 100644 index 0000000000..724498fcd0 --- /dev/null +++ b/Task/Word-wrap/Python/word-wrap.py @@ -0,0 +1,40 @@ +>>> import textwrap +>>> help(textwrap.fill) +Help on function fill in module textwrap: + +fill(text, width=70, **kwargs) + Fill a single paragraph of text, returning a new string. + + Reformat the single paragraph in 'text' to fit in lines of no more + than 'width' columns, and return a new string containing the entire + wrapped paragraph. As with wrap(), tabs are expanded and other + whitespace characters converted to space. See TextWrapper class for + available keyword args to customize wrapping behaviour. + +>>> txt = '''\ +Reformat the single paragraph in 'text' to fit in lines of no more +than 'width' columns, and return a new string containing the entire +wrapped paragraph. As with wrap(), tabs are expanded and other +whitespace characters converted to space. See TextWrapper class for +available keyword args to customize wrapping behaviour.''' +>>> print(textwrap.fill(txt, width=75)) +Reformat the single paragraph in 'text' to fit in lines of no more than +'width' columns, and return a new string containing the entire wrapped +paragraph. As with wrap(), tabs are expanded and other whitespace +characters converted to space. See TextWrapper class for available keyword +args to customize wrapping behaviour. +>>> print(textwrap.fill(txt, width=45)) +Reformat the single paragraph in 'text' to +fit in lines of no more than 'width' columns, +and return a new string containing the entire +wrapped paragraph. As with wrap(), tabs are +expanded and other whitespace characters +converted to space. See TextWrapper class +for available keyword args to customize +wrapping behaviour. +>>> print(textwrap.fill(txt, width=85)) +Reformat the single paragraph in 'text' to fit in lines of no more than 'width' +columns, and return a new string containing the entire wrapped paragraph. As with +wrap(), tabs are expanded and other whitespace characters converted to space. See +TextWrapper class for available keyword args to customize wrapping behaviour. +>>> diff --git a/Task/Word-wrap/Scheme/word-wrap.ss b/Task/Word-wrap/Scheme/word-wrap.ss new file mode 100644 index 0000000000..05d31b74eb --- /dev/null +++ b/Task/Word-wrap/Scheme/word-wrap.ss @@ -0,0 +1,39 @@ +(import (scheme base) + (scheme write) + (only (srfi 13) string-join string-tokenize)) + +;; word wrap, using greedy algorithm with minimum lines +(define (simple-word-wrap str width) + (let loop ((words (string-tokenize str)) + (line-length 0) + (line '()) + (lines '())) + (cond ((null? words) + (reverse (cons (reverse line) lines))) + ((> (+ line-length (string-length (car words))) + width) + (if (null? line) + (loop (cdr words) ; case where word exceeds line length + 0 + '() + (cons (list (car words)) lines)) + (loop words ; word must go to next line, so finish current line + 0 + '() + (cons (reverse line) lines)))) + (else + (loop (cdr words) ; else, add word to current line + (+ 1 line-length (string-length (car words))) + (cons (car words) line) + lines))))) + +;; run examples - text from RnRS report +(define *text* "Programming languages should be designed not by piling feature on top of feature, but by removing the weaknesses and restrictions that make additional features appear necessary. Scheme demonstrates that a very small number of rules for forming expressions, with no restrictions on how they are composed, suffice to form a practical and efficient programming language that is flexible enough to support most of the major programming paradigms in use today.") + +(define (show-para algorithm width) + (display (make-string width #\-)) (newline) + (for-each (lambda (line) (display (string-join line " ")) (newline)) + (algorithm *text* width))) + +(show-para simple-word-wrap 50) +(show-para simple-word-wrap 60) diff --git a/Task/Word-wrap/Zkl/word-wrap-1.zkl b/Task/Word-wrap/Zkl/word-wrap-1.zkl new file mode 100644 index 0000000000..f781896d19 --- /dev/null +++ b/Task/Word-wrap/Zkl/word-wrap-1.zkl @@ -0,0 +1,37 @@ +fcn formatText(text, // text can be String,Data,File, -->Data + length=72, calcIndents=True){ + sink:=Data(); + getIndents:='wrap(w){ // look at first two lines to indent paragraph + reg lines=L(), len=0, prefix="", one=True; + do(2){ + if(w._next()){ + lines.append(line:=w.value); + word:=line.split(Void,1)[0,1]; // get first word, if line !blank + if(word){ + p:=line[0,line.find(word[0]]); + if(one){ sink.write(p); len=p.len(); one=False; } + else prefix=p; + } + } + } + w.push(lines.xplode()); // put first two lines back to be formated + return(len,prefix); + }; + + reg len=0, prefix="", w=text.walker(1); // lines + if(calcIndents) len,prefix=getIndents(w); + foreach line in (w){ + if(not line.strip()){ // blank line + sink.write("\n",line); // blank line redux + if(calcIndents) len,prefix=getIndents(w); + else len=0; // restart formating + }else + len=line.split().reduce('wrap(len,word){ + n:=word.len(); + if(len==0) { sink.write(word); return(n); } + nn:=n+1+len; if(nn<=length) { sink.write(" ",word); return(nn); } + sink.write("\n",prefix,word); return(prefix.len()+word.len()); + },len); + } + sink +} diff --git a/Task/Word-wrap/Zkl/word-wrap-2.zkl b/Task/Word-wrap/Zkl/word-wrap-2.zkl new file mode 100644 index 0000000000..2d9f21c6bd --- /dev/null +++ b/Task/Word-wrap/Zkl/word-wrap-2.zkl @@ -0,0 +1 @@ +formatText(File("frog.txt")).text.println(); diff --git a/Task/Word-wrap/Zkl/word-wrap-3.zkl b/Task/Word-wrap/Zkl/word-wrap-3.zkl new file mode 100644 index 0000000000..7393573266 --- /dev/null +++ b/Task/Word-wrap/Zkl/word-wrap-3.zkl @@ -0,0 +1,2 @@ +[1..].zipWith("%2d: %s".fmt,formatText(File("frog.txt")).walker(1)) +.pump(String).println(); diff --git a/Task/Word-wrap/Zkl/word-wrap-4.zkl b/Task/Word-wrap/Zkl/word-wrap-4.zkl new file mode 100644 index 0000000000..c9f7c394fe --- /dev/null +++ b/Task/Word-wrap/Zkl/word-wrap-4.zkl @@ -0,0 +1 @@ +formatText("this\n is a test foo bar\n\ngreen eggs and spam",10).text.println(); 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.kotlin new file mode 100644 index 0000000000..7db9cb75c9 --- /dev/null +++ b/Task/World-Cup-group-stage/Kotlin/world-cup-group-stage.kotlin @@ -0,0 +1,36 @@ +// version 1.1.2 + +val games = arrayOf("12", "13", "14", "23", "24", "34") +var results = "000000" + +fun nextResult(): Boolean { + if (results == "222222") return false + val res = results.toInt(3) + 1 + results = res.toString(3).padStart(6, '0') + return true +} + +fun main(args: Array) { + val points = Array(4) { IntArray(10) } + do { + val records = IntArray(4) + for (i in 0..5) { + when (results[i]) { + '2' -> records[games[i][0] - '1'] += 3 + '1' -> { records[games[i][0] - '1']++ ; records[games[i][1] - '1']++ } + '0' -> records[games[i][1] - '1'] += 3 + } + } + records.sort() + for (i in 0..3) points[i][records[i]]++ + } + while(nextResult()) + println("POINTS 0 1 2 3 4 5 6 7 8 9") + println("-------------------------------------------------------------") + val places = arrayOf("1st", "2nd", "3rd", "4th") + for (i in 0..3) { + print("${places[i]} place ") + points[3 - i].forEach { print("%-5d".format(it)) } + println() + } +} diff --git a/Task/World-Cup-group-stage/Perl-6/world-cup-group-stage.pl6 b/Task/World-Cup-group-stage/Perl-6/world-cup-group-stage.pl6 index e42d2ecd7c..7ef1bbdfec 100644 --- a/Task/World-Cup-group-stage/Perl-6/world-cup-group-stage.pl6 +++ b/Task/World-Cup-group-stage/Perl-6/world-cup-group-stage.pl6 @@ -1,18 +1,15 @@ constant scoring = 0, 1, 3; -constant r = 0..2; my @histo = [0 xx 10] xx 4; -for ([X] r,r,r,r,r,r).tree -> @results { +for [X] ^3 xx 6 -> @results { my @s; - for @results Z (^4).combinations(2) - -> $r, @g { + for @results Z (^4).combinations(2) -> ($r, @g) { @s[@g[0]] += scoring[$r]; @s[@g[1]] += scoring[2 - $r]; } - for @histo Z @s.sort - -> @h, $v { + for @histo Z @s.sort -> (@h, $v) { ++@h[$v]; } } diff --git a/Task/World-Cup-group-stage/Zkl/world-cup-group-stage.zkl b/Task/World-Cup-group-stage/Zkl/world-cup-group-stage.zkl new file mode 100644 index 0000000000..da2789ca2b --- /dev/null +++ b/Task/World-Cup-group-stage/Zkl/world-cup-group-stage.zkl @@ -0,0 +1,14 @@ +combos :=Utils.Helpers.pickNFrom(2,T(0,1,2,3)); // ( (0,1),(0,2) ... ) +scoring:=T(0,1,3); +histo :=(0).pump(4,List().write,(0).pump(10,List().write,0).copy); //[4][10] of zeros + +foreach r0,r1,r2,r3,r4,r5 in ([0..2],[0..2],[0..2],[0..2],[0..2],[0..2]){ + s:=L(0,0,0,0); + foreach i,r in (T(r0,r1,r2,r3,r4,r5).enumerate()){ + g:=combos[i]; + s[g[0]]+=scoring[r]; + s[g[1]]+=scoring[2 - r]; + } + foreach h,v in (histo.zip(s.sort())){ h[v]+=1; } +} +foreach h in (histo.reverse()){ println(h.apply("%3d ".fmt).concat()) } diff --git a/Task/Write-float-arrays-to-a-text-file/jq/write-float-arrays-to-a-text-file-1.jq b/Task/Write-float-arrays-to-a-text-file/Jq/write-float-arrays-to-a-text-file-1.jq similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/jq/write-float-arrays-to-a-text-file-1.jq rename to Task/Write-float-arrays-to-a-text-file/Jq/write-float-arrays-to-a-text-file-1.jq diff --git a/Task/Write-float-arrays-to-a-text-file/jq/write-float-arrays-to-a-text-file-2.jq b/Task/Write-float-arrays-to-a-text-file/Jq/write-float-arrays-to-a-text-file-2.jq similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/jq/write-float-arrays-to-a-text-file-2.jq rename to Task/Write-float-arrays-to-a-text-file/Jq/write-float-arrays-to-a-text-file-2.jq 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.julia index a04d92f1bc..51447fccfb 100644 --- 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.julia @@ -1,5 +1,5 @@ xprecision = 3 yprecision = 5 -x = round([1, 2, 3, 1e11],xprecision) -y = round([1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791],yprecision) +x = round.([1, 2, 3, 1e11],xprecision) +y = round.([1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791],yprecision) writedlm("filename", [x y], '\t') 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.kotlin new file mode 100644 index 0000000000..5884aa3d8c --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Kotlin/write-float-arrays-to-a-text-file.kotlin @@ -0,0 +1,18 @@ +// version 1.1.2 + +import java.io.File + +fun main(args: Array) { + val x = doubleArrayOf(1.0, 2.0, 3.0, 1e11) + val y = doubleArrayOf(1.0, 1.4142135623730951, 1.7320508075688772, 316227.76601683791) + val xp = 3 + val yp = 5 + val f = "%.${xp}g\t%.${yp}g\n" + val writer = File("output.txt").writer() + writer.use { + for (i in 0 until x.size) { + val s = f.format(x[i], y[i]) + writer.write(s) + } + } +} diff --git a/Task/Write-float-arrays-to-a-text-file/Nimrod/write-float-arrays-to-a-text-file.nimrod b/Task/Write-float-arrays-to-a-text-file/Nimrod/write-float-arrays-to-a-text-file.nimrod deleted file mode 100644 index 34e7d96351..0000000000 --- a/Task/Write-float-arrays-to-a-text-file/Nimrod/write-float-arrays-to-a-text-file.nimrod +++ /dev/null @@ -1,21 +0,0 @@ -import strutils, math, sequtils - -const - outFileName = "floatarr2file.txt" - -proc sqrt*(x: int64): float {.importc: "sqrt", header: "".} - -const - xprecision = 3 - yprecision = 5 - -var a: seq[int64] = @[int64(1), 2, 3, 100_000_000_000] -var b: seq[float] = @[sqrt(a[0]), sqrt(a[1]), sqrt(a[2]), sqrt(a[3])] -var c = zip(a,b) -var res: string = "" -for t in c: - res.add($formatFloat(float(t.a),ffDefault,xprecision) & "\t" & $formatFloat(t.b,ffDefault,yprecision) & "\n") - -writeFile(outFileName,res) -var res2 = readFile(outFileName) -echo(res2) diff --git a/Task/Write-float-arrays-to-a-text-file/SPL/write-float-arrays-to-a-text-file.spl b/Task/Write-float-arrays-to-a-text-file/SPL/write-float-arrays-to-a-text-file.spl new file mode 100644 index 0000000000..722bf58f28 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/SPL/write-float-arrays-to-a-text-file.spl @@ -0,0 +1,9 @@ +x = [1, 2, 3, 10^11] +y = [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791] +xprecision = 3 +yprecision = 5 +> i, 1..4 + s1 = #.str(x[i],"g"+xprecision) + s2 = #.str(y[i],"g"+yprecision) + #.writeline("file.txt",s1+#.tab+s2) +< diff --git a/Task/Write-float-arrays-to-a-text-file/Sidef/write-float-arrays-to-a-text-file.sidef b/Task/Write-float-arrays-to-a-text-file/Sidef/write-float-arrays-to-a-text-file.sidef index 6b1d6c9ff4..3f24af354b 100644 --- a/Task/Write-float-arrays-to-a-text-file/Sidef/write-float-arrays-to-a-text-file.sidef +++ b/Task/Write-float-arrays-to-a-text-file/Sidef/write-float-arrays-to-a-text-file.sidef @@ -1,14 +1,14 @@ func writedat(filename, x, y, x_precision=3, y_precision=5) { - var fh = File.new(filename).open_w; - - MultiArray.new(x, y).each { |x, y| - fh.printf("%.*g\t%.*g\n", x_precision, x, y_precision, y); + var fh = File(filename).open_w +  + for a,b in (x ~Z y) { + fh.printf("%.*g\t%.*g\n", x_precision, a, y_precision, b) } - - fh.close; +  + fh.close } - -var x = [1, 2, 3, 1e11]; -var y = x»sqrt»(); - -writedat('sqrt.dat', x, y); +  +var x = [1, 2, 3, 1e11] +var y = x.map{.sqrt} +  +writedat('sqrt.dat', x, y) diff --git a/Task/Write-float-arrays-to-a-text-file/Zkl/write-float-arrays-to-a-text-file.zkl b/Task/Write-float-arrays-to-a-text-file/Zkl/write-float-arrays-to-a-text-file.zkl new file mode 100644 index 0000000000..635973439a --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Zkl/write-float-arrays-to-a-text-file.zkl @@ -0,0 +1,10 @@ +fcn writeFloatArraysToFile(filename, xs,xprecision, ys,yprecision){ + f :=File(filename,"w"); + fmt:="%%.%dg\t%%.%dg".fmt(xprecision,yprecision).fmt; // "%.3g\t%.5g".fmt + foreach x,y in (xs.zip(ys)){ f.writeln(fmt(x,y)); } + f.close(); +} + +xs,ys := T(1.0, 2.0, 3.0, 1e11), xs.apply("sqrt"); +xprecision,yprecision := 3,5; +writeFloatArraysToFile("floatArray.txt", xs,xprecision, ys,yprecision); diff --git a/Task/Write-language-name-in-3D-ASCII/00DESCRIPTION b/Task/Write-language-name-in-3D-ASCII/00DESCRIPTION index c24b48a033..709a385cec 100644 --- a/Task/Write-language-name-in-3D-ASCII/00DESCRIPTION +++ b/Task/Write-language-name-in-3D-ASCII/00DESCRIPTION @@ -8,4 +8,9 @@ Write/display a language's name in '''3D''' ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) + + +;Related tasks: +* [[Draw_a_rotating_cube|draw a rotating cube]] +* [[Draw_a_cuboid|draw a cuboid]]

    diff --git a/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-7.basic b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-7.basic index ec0c10912b..43f9efea60 100644 --- a/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-7.basic +++ b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-7.basic @@ -1,46 +1,35 @@ -10 LET s$="BASIC": REM our language name -20 DIM b(5,5):REM our bigmap characters -30 FOR l = 1 TO 5: REM 5 characters -40 FOR m = 1 TO 5: REM 5 rows -50 READ b(l,m) -60 NEXT m -70 NEXT l - -100 PAPER 0: REM black background -110 INK 2: REM our shadow will be red -120 CLS -130 LET r=9: REM shadow will start on row 5 -140 LET c=2: REM shadow will start at column 2 -150 GO SUB 2000: REM draw shadow -160 INK 6: REM our forground will be yellow -170 LET r=10: REM foreground will start on row 6 -180 LET c=3: REM foreground will start on column 3 -190 GO SUB 2000: REM display the language name - -999 STOP - + 10 DIM b(5,5): REM our bigmap characters + 20 FOR l=1 TO 5: REM 5 characters + 30 FOR m=1 TO 5: REM 5 rows + 40 READ b(m,l) + 50 NEXT m + 60 NEXT l + 70 PAPER 0: BORDER 0: REM black background and border + 80 INK 2: REM our shadow will be red + 90 CLS + 100 LET r=8: REM shadow will start on row 8 + 110 LET c=1: REM shadow will start at column 1 + 120 GO SUB 2000: REM draw shadow + 130 INK 6: REM our foreground will be yellow + 140 LET r=9: REM foreground will start on row 9 + 150 LET c=2: REM foreground will start on column 2 + 160 GO SUB 2000: REM display the language name + 999 STOP 1000 REM convert to binary bigmap -1010 LET t=n: REM temporary variable -1020 LET g$="": REM this will contain our 5 character binary bigmap -1040 FOR z=5 TO 0 STEP -1 -1050 LET d$=" ": REM assume next digit is zero (draw a space) -1060 IF t>=(2^z) THEN LET d$=CHR$(143): LET t=t-(2^z): LET sf=1: REM 143 is a block -1070 LET g$=g$+d$ -1080 NEXT z -1090 RETURN - +1010 LET z=16 +1020 IF t>=z THEN PRINT AT r+l-1,c+c1;CHR$ (143);: LET t=t-z: REM 143 is a block +1040 LET c1=c1+1: LET z=z/2 +1050 IF z>=1 THEN GO TO 1020 +1060 RETURN 2000 REM display the big letters -2010 FOR l=1 TO 5: REM our 5 rows -2020 PRINT AT r+l-1,c; +2010 FOR l=1 TO 5: LET c1=0: REM our 5 rows 2030 FOR m=1 TO 5: REM bigmap for each character -2040 LET n=b(l,m) +2040 LET t=b(l,m) 2050 GO SUB 1000 -2060 PRINT g$;: REM 5 character bigmap -2070 PRINT " ";: REM space between each letter -2080 NEXT m -2090 NEXT l -2100 RETURN - +2060 LET c1=c1+1: REM PRINT " ";: REM space between each letter +2070 NEXT m +2080 NEXT l +2090 RETURN 9000 DATA 30,17,30,17,30: REM B 9010 DATA 14,17,31,17,17: REM A 9020 DATA 15,16,14,1,30: REM S diff --git a/Task/Write-language-name-in-3D-ASCII/BBC-BASIC/write-language-name-in-3d-ascii.bbc b/Task/Write-language-name-in-3D-ASCII/BBC-BASIC/write-language-name-in-3d-ascii.bbc deleted file mode 100644 index 9c416d07cd..0000000000 --- a/Task/Write-language-name-in-3D-ASCII/BBC-BASIC/write-language-name-in-3d-ascii.bbc +++ /dev/null @@ -1,22 +0,0 @@ - PROC3dname("BBC BASIC") - END - - DEF PROC3dname(name$) - LOCAL A%, X%, Y%, char%, row%, patt%, bit% - DIM X% 8 : A% = 10 : Y% = X% DIV 256 - FOR row% = 1 TO 8 - FOR char% = 1 TO LEN(name$) - ?X% = ASCMID$(name$,char%) - CALL &FFF1 - patt% = X%?row% - FOR bit% = 7 TO 0 STEP -1 - CASE TRUE OF - WHEN (patt% AND 2^bit%) <> 0 : PRINT "#"; - WHEN GET$(POS-1,VPOS-1) = "#": PRINT "\"; - OTHERWISE: PRINT " "; - ENDCASE - NEXT - NEXT char% - PRINT - NEXT row% - ENDPROC diff --git a/Task/Write-language-name-in-3D-ASCII/Dart/write-language-name-in-3d-ascii.dart b/Task/Write-language-name-in-3D-ASCII/Dart/write-language-name-in-3d-ascii.dart new file mode 100644 index 0000000000..bcd7cc90ad --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Dart/write-language-name-in-3d-ascii.dart @@ -0,0 +1,9 @@ +void main(){ + print(""" + + XXX XX XXX XXXX + X X X X X X X + X X XXXX XXX X + XXX X X X X X + """.replaceAll('X','_/')); +} diff --git a/Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii.erl b/Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii-1.erl similarity index 100% rename from Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii.erl rename to Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii-1.erl diff --git a/Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii-2.erl b/Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii-2.erl new file mode 100644 index 0000000000..db5661a987 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii-2.erl @@ -0,0 +1,9 @@ +-module(ascii3d). +-export([decode/1]). + +decode(Str) -> + Splited = re:split(Str, "(\\d+)(\\D+)", [{return,list},group,trim]), + Fun = fun([_,N,S]) -> {Num,_} = string:to_integer(N), lists:duplicate(Num, S) end, + Joined = string:join(lists:flatmap(Fun, Splited), ""), + Lines = binary:replace(binary:list_to_bin(Joined), <<"B">>, <<"\\">>, [global]), + io:format("~s~n", [Lines]). diff --git a/Task/Write-language-name-in-3D-ASCII/Kotlin/write-language-name-in-3d-ascii.kotlin b/Task/Write-language-name-in-3D-ASCII/Kotlin/write-language-name-in-3d-ascii.kotlin new file mode 100644 index 0000000000..82eecd06cd --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Kotlin/write-language-name-in-3d-ascii.kotlin @@ -0,0 +1,97 @@ +// version 1.1 + +class Ascii3D(s: String) { + val z = charArrayOf(' ', ' ', '_', '/') + + val f = arrayOf( + longArrayOf(87381, 87381, 87381, 87381, 87381, 87381, 87381), + longArrayOf(349525, 375733, 742837, 742837, 375733, 349525, 349525), + longArrayOf(742741, 768853, 742837, 742837, 768853, 349525, 349525), + longArrayOf(349525, 375733, 742741, 742741, 375733, 349525, 349525), + longArrayOf(349621, 375733, 742837, 742837, 375733, 349525, 349525), + longArrayOf(349525, 375637, 768949, 742741, 375733, 349525, 349525), + longArrayOf(351157, 374101, 768949, 374101, 374101, 349525, 349525), + longArrayOf(349525, 375733, 742837, 742837, 375733, 349621, 351157), + longArrayOf(742741, 768853, 742837, 742837, 742837, 349525, 349525), + longArrayOf(181, 85, 181, 181, 181, 85, 85), + longArrayOf(1461, 1365, 1461, 1461, 1461, 1461, 2901), + longArrayOf(742741, 744277, 767317, 744277, 742837, 349525, 349525), + longArrayOf(181, 181, 181, 181, 181, 85, 85), + longArrayOf(1431655765, 3149249365L, 3042661813L, 3042661813L, 3042661813L, 1431655765, 1431655765), + longArrayOf(349525, 768853, 742837, 742837, 742837, 349525, 349525), + longArrayOf(349525, 375637, 742837, 742837, 375637, 349525, 349525), + longArrayOf(349525, 768853, 742837, 742837, 768853, 742741, 742741), + longArrayOf(349525, 375733, 742837, 742837, 375733, 349621, 349621), + longArrayOf(349525, 744373, 767317, 742741, 742741, 349525, 349525), + longArrayOf(349525, 375733, 767317, 351157, 768853, 349525, 349525), + longArrayOf(374101, 768949, 374101, 374101, 351157, 349525, 349525), + longArrayOf(349525, 742837, 742837, 742837, 375733, 349525, 349525), + longArrayOf(5592405, 11883957, 11883957, 5987157, 5616981, 5592405, 5592405), + longArrayOf(366503875925L, 778827027893L, 778827027893L, 392374737749L, 368114513237L, 366503875925L, 366503875925L), + longArrayOf(349525, 742837, 375637, 742837, 742837, 349525, 349525), + longArrayOf(349525, 742837, 742837, 742837, 375733, 349621, 375637), + longArrayOf(349525, 768949, 351061, 374101, 768949, 349525, 349525), + longArrayOf(375637, 742837, 768949, 742837, 742837, 349525, 349525), + longArrayOf(768853, 742837, 768853, 742837, 768853, 349525, 349525), + longArrayOf(375733, 742741, 742741, 742741, 375733, 349525, 349525), + longArrayOf(192213, 185709, 185709, 185709, 192213, 87381, 87381), + longArrayOf(1817525, 1791317, 1817429, 1791317, 1817525, 1398101, 1398101), + longArrayOf(768949, 742741, 768853, 742741, 742741, 349525, 349525), + longArrayOf(375733, 742741, 744373, 742837, 375733, 349525, 349525), + longArrayOf(742837, 742837, 768949, 742837, 742837, 349525, 349525), + longArrayOf(48053, 23381, 23381, 23381, 48053, 21845, 21845), + longArrayOf(349621, 349621, 349621, 742837, 375637, 349525, 349525), + longArrayOf(742837, 744277, 767317, 744277, 742837, 349525, 349525), + longArrayOf(742741, 742741, 742741, 742741, 768949, 349525, 349525), + longArrayOf(11883957, 12278709, 11908533, 11883957, 11883957, 5592405, 5592405), + longArrayOf(11883957, 12277173, 11908533, 11885493, 11883957, 5592405, 5592405), + longArrayOf(375637, 742837, 742837, 742837, 375637, 349525, 349525), + longArrayOf(768853, 742837, 768853, 742741, 742741, 349525, 349525), + longArrayOf(6010197, 11885397, 11909973, 11885397, 6010293, 5592405, 5592405), + longArrayOf(768853, 742837, 768853, 742837, 742837, 349525, 349525), + longArrayOf(375733, 742741, 375637, 349621, 768853, 349525, 349525), + longArrayOf(12303285, 5616981, 5616981, 5616981, 5616981, 5592405, 5592405), + longArrayOf(742837, 742837, 742837, 742837, 375637, 349525, 349525), + longArrayOf(11883957, 11883957, 11883957, 5987157, 5616981, 5592405, 5592405), + longArrayOf(3042268597L, 3042268597L, 3042661813L, 1532713813, 1437971797, 1431655765, 1431655765), + longArrayOf(11883957, 5987157, 5616981, 5987157, 11883957, 5592405, 5592405), + longArrayOf(11883957, 5987157, 5616981, 5616981, 5616981, 5592405, 5592405), + longArrayOf(12303285, 5593941, 5616981, 5985621, 12303285, 5592405, 5592405) + ) + + init { + val o = Array(7) { StringBuilder() } + for (i in 0 until s.length) { + var c = s[i].toInt() + if (c in 65..90) { + c -= 39 + } else if (c in 97..122) { + c -= 97 + } else { + c = -1 + } + val d = f[++c] + for (j in 0 until 7) { + val b = StringBuilder() + var v = d[j] + while (v > 0) { + b.append(z[(v and 3).toInt()]) + v = v shr 2 + } + o[j].append(b.reverse().toString()) + } + } + for (i in 0 until 7) { + for (j in 0 until 7 - i) print(' ') + println(o[i]) + } + } +} + +fun main(args: Array) { + Ascii3D("KOTLIN") + Ascii3D("with thanks") + Ascii3D("to the author") + Ascii3D("of the") + Ascii3D("Java entry") +} diff --git a/Task/Write-language-name-in-3D-ASCII/Locomotive-Basic/write-language-name-in-3d-ascii.locomotive b/Task/Write-language-name-in-3D-ASCII/Locomotive-Basic/write-language-name-in-3d-ascii.locomotive deleted file mode 100644 index 10ef5ca043..0000000000 --- a/Task/Write-language-name-in-3D-ASCII/Locomotive-Basic/write-language-name-in-3d-ascii.locomotive +++ /dev/null @@ -1,25 +0,0 @@ -10 mode 2:defint a-z -20 locate 1,25 -30 print "Basic"; -40 ' add some kerning so the characters will fit in 80 columns: -50 off(2)=1:off(4)=-2:off(5)=-4 -60 for c=0 to 4 -70 for y=7 to 0 step -1 -80 for x=0 to 7 -90 v=test(x+8*c,2*y) -100 plot x+8*c,2*y,0 -110 if v>0 then gosub 180 -120 next x -130 next y -140 next c -150 call &bb06 ' wait for key press -160 end -170 ' print pixel -180 xp=16*c+2*x+1+y+off(c+1) -190 yp=8-y -200 if xp>77 then return -210 locate xp,yp -220 print "//\"; -230 locate xp,yp+1 -240 print "\\/"; -250 return diff --git a/Task/Write-language-name-in-3D-ASCII/Nim/write-language-name-in-3d-ascii.nim b/Task/Write-language-name-in-3D-ASCII/Nim/write-language-name-in-3d-ascii.nim index c7774b4d9b..84a9bc6190 100644 --- a/Task/Write-language-name-in-3D-ASCII/Nim/write-language-name-in-3d-ascii.nim +++ b/Task/Write-language-name-in-3D-ASCII/Nim/write-language-name-in-3d-ascii.nim @@ -1,13 +1,13 @@ import strutils const nim = """ - # # ##### # # #### #### #### - ## # # ## ## # # # # # # - # # # # # ## # # # # # # # - # # # # # # #### # # # # - # ## # # # # # # # # # - # # ##### # # # # #### ####""" + # # ##### # # + ## # # ## ## + # # # # # ## # + # # # # # # + # ## # # # + # # ##### # #""" let lines = nim.replace("#", "<<<").replace(" ", "X").replace("X", " ").replace("\n", " Y").replace("< ", "<>").split('Y') -for i, l in lines: - echo repeatChar((lines.len - i) * 3), l +for i, line in lines: + echo spaces((lines.len - i) * 3), line diff --git a/Task/Write-language-name-in-3D-ASCII/OCaml/write-language-name-in-3d-ascii.ocaml b/Task/Write-language-name-in-3D-ASCII/OCaml/write-language-name-in-3d-ascii.ocaml new file mode 100644 index 0000000000..1cc1f8c3df --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/OCaml/write-language-name-in-3d-ascii.ocaml @@ -0,0 +1,7 @@ + print_string " + _|_|_| _|_|_| _|_| _|_| _|_| _| + _| _| _| _| _| _| _| _| _| _| + _| _| _| _|_|_| _| _| _| _| _| + _| _| _| _| _| _| _| _| + _|_|_| _|_|_| _| _| _| _| _|_|_|_|_| + " diff --git a/Task/Write-language-name-in-3D-ASCII/UNIX-Shell/write-language-name-in-3d-ascii.sh b/Task/Write-language-name-in-3D-ASCII/UNIX-Shell/write-language-name-in-3d-ascii.sh new file mode 100644 index 0000000000..67b098b524 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/UNIX-Shell/write-language-name-in-3d-ascii.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +mapfile -t name <=(2^z) THEN LET d$=CHR$(143): LET t=t-(2^z): LET sf=1: REM 143 is a block -1070 LET g$=g$+d$ -1080 NEXT z -1090 RETURN - -2000 REM display the big letters -2010 FOR l=1 TO 5: REM our 5 rows -2020 PRINT AT r+l-1,c; -2030 FOR m=1 TO 5: REM bigmap for each character -2040 LET n=b(l,m) -2050 GO SUB 1000 -2060 PRINT g$;: REM 5 character bigmap -2070 PRINT " ";: REM space between each letter -2080 NEXT m -2090 NEXT l -2100 RETURN - -9000 DATA 30,17,30,17,30: REM B -9010 DATA 14,17,31,17,17: REM A -9020 DATA 15,16,14,1,30: REM S -9030 DATA 31,4,4,4,31: REM I -9040 DATA 14,17,16,17,14: REM C diff --git a/Task/Write-language-name-in-3D-ASCII/Zkl/write-language-name-in-3d-ascii.zkl b/Task/Write-language-name-in-3D-ASCII/Zkl/write-language-name-in-3d-ascii.zkl new file mode 100644 index 0000000000..1b03b74895 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Zkl/write-language-name-in-3d-ascii.zkl @@ -0,0 +1,10 @@ +#<<< +" +xxxxxx x x x + x x x x + x x x x +x x x x +xxxxx x x xxxx +" +#<<<< +.replace(" "," ").replace("x","_/").println(); diff --git a/Task/Write-to-Windows-event-log/Kotlin/write-to-windows-event-log.kotlin b/Task/Write-to-Windows-event-log/Kotlin/write-to-windows-event-log.kotlin new file mode 100644 index 0000000000..9e4dc9d66b --- /dev/null +++ b/Task/Write-to-Windows-event-log/Kotlin/write-to-windows-event-log.kotlin @@ -0,0 +1,12 @@ +// version 1.1.4-3 + +fun main(args: Array) { + val command = "EventCreate" + + " /t INFORMATION" + + " /id 123" + + " /l APPLICATION" + + " /so Kotlin" + + " /d \"Rosetta Code Example\"" + + Runtime.getRuntime().exec(command) +} diff --git a/Task/Write-to-Windows-event-log/REXX/write-to-windows-event-log-1.rexx b/Task/Write-to-Windows-event-log/REXX/write-to-windows-event-log-1.rexx new file mode 100644 index 0000000000..4277f58b6f --- /dev/null +++ b/Task/Write-to-Windows-event-log/REXX/write-to-windows-event-log-1.rexx @@ -0,0 +1,13 @@ +/*REXX program writes a "record" (event) to the (Microsoft) Windows event log. */ + + eCMD = 'EVENTCREATE' /*name of the command that'll be used. */ + type = 'INFORMATION' /*one of: ERROR WARNING INFORMATION */ + id = 234 /*in range: 1 ───► 1000 (inclusive).*/ + logName = 'APPLICATION' /*information about what this is. */ + source = 'REXX' /* " " who's doing this. */ + desc = 'attempting to add an entry for a Rosetta Code demonstration.' + desc = '"' || desc || '"' /*enclose description in double quotes.*/ + +eCMD '/T' type "/ID" id '/L' logName "/SO" source '/D' desc + + /*stick a fork in it, we're all done. */ diff --git a/Task/Write-to-Windows-event-log/REXX/write-to-windows-event-log-2.rexx b/Task/Write-to-Windows-event-log/REXX/write-to-windows-event-log-2.rexx new file mode 100644 index 0000000000..338edfafe7 --- /dev/null +++ b/Task/Write-to-Windows-event-log/REXX/write-to-windows-event-log-2.rexx @@ -0,0 +1,7 @@ +/*REXX program writes a "record" (event) to the (Microsoft) Windows event log. */ + /* [↓] cmd options have extra spacing.*/ + +'EVENTCREATE /T INFORMATION /ID 234 /L APPLICATION /SO REXX' , + '/D "attempting to add an entry for a Rosetta Code demonstration."' + + /*stick a fork in it, we're all done. */ diff --git a/Task/Write-to-Windows-event-log/REXX/write-to-windows-event-log.rexx b/Task/Write-to-Windows-event-log/REXX/write-to-windows-event-log.rexx deleted file mode 100644 index 76701de5b2..0000000000 --- a/Task/Write-to-Windows-event-log/REXX/write-to-windows-event-log.rexx +++ /dev/null @@ -1,13 +0,0 @@ -/*REXX program writes a "record" (event) to the (MS) Windows event log.*/ - - eCMD = 'EVENTCREATE' - type = 'INFORMATION' /*one of: ERROR WARNING INFORMATION */ - id = 234 /*in range: 1 ───► 1000 (inclusive).*/ - logName = 'APPLICATION' - source = 'REXX' - desc = 'attempting to add an entry for Rosetta Code demonstration.' - desc = '"' || desc '"' /*enclose DESCription in double quotes.*/ - -eCMD '/T' type "/ID" id '/L' logName "/SO" source '/D' desc - - /*stick a fork in it honey, we're done.*/ diff --git a/Task/Write-to-Windows-event-log/Zkl/write-to-windows-event-log.zkl b/Task/Write-to-Windows-event-log/Zkl/write-to-windows-event-log.zkl new file mode 100644 index 0000000000..7b9d421cf6 --- /dev/null +++ b/Task/Write-to-Windows-event-log/Zkl/write-to-windows-event-log.zkl @@ -0,0 +1 @@ +zkl: System.cmd(0'|eventcreate "/T" "INFORMATION" "/ID" "123" "/D" "Rosetta Code example"|) diff --git a/Task/XML-DOM-serialization/Kotlin/xml-dom-serialization.kotlin b/Task/XML-DOM-serialization/Kotlin/xml-dom-serialization.kotlin new file mode 100644 index 0000000000..1aa5f5f800 --- /dev/null +++ b/Task/XML-DOM-serialization/Kotlin/xml-dom-serialization.kotlin @@ -0,0 +1,31 @@ +// version 1.1.3 + +import javax.xml.parsers.DocumentBuilderFactory +import javax.xml.transform.dom.DOMSource +import java.io.StringWriter +import javax.xml.transform.stream.StreamResult +import javax.xml.transform.TransformerFactory + +fun main(args: Array) { + val dbFactory = DocumentBuilderFactory.newInstance() + val dBuilder = dbFactory.newDocumentBuilder() + val doc = dBuilder.newDocument() + val root = doc.createElement("root") // create root node + doc.appendChild(root) + val element = doc.createElement("element") // create element node + val text = doc.createTextNode("Some text here") // create text node + element.appendChild(text) + root.appendChild(element) + + // serialize + val source = DOMSource(doc) + val sw = StringWriter() + val result = StreamResult(sw) + val tFactory = TransformerFactory.newInstance() + tFactory.newTransformer().apply { + setOutputProperty("indent", "yes") + setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4") + transform(source, result) + } + println(sw) +} diff --git a/Task/XML-Input/Kotlin/xml-input.kotlin b/Task/XML-Input/Kotlin/xml-input.kotlin new file mode 100644 index 0000000000..8ebfd503aa --- /dev/null +++ b/Task/XML-Input/Kotlin/xml-input.kotlin @@ -0,0 +1,36 @@ +// version 1.1.3 + +import javax.xml.parsers.DocumentBuilderFactory +import org.xml.sax.InputSource +import java.io.StringReader +import org.w3c.dom.Node +import org.w3c.dom.Element + +val xml = +""" + + + + + + + + + +""" + +fun main(args: Array) { + val dbFactory = DocumentBuilderFactory.newInstance() + val dBuilder = dbFactory.newDocumentBuilder() + val xmlInput = InputSource(StringReader(xml)) + val doc = dBuilder.parse(xmlInput) + val nList = doc.getElementsByTagName("Student") + for (i in 0 until nList.length) { + val node = nList.item(i) + if (node.nodeType == Node.ELEMENT_NODE) { + val element = node as Element + val name = element.getAttribute("Name") + println(name) + } + } +} diff --git a/Task/XML-Input/NewLISP/xml-input.newlisp b/Task/XML-Input/NewLISP/xml-input.newlisp new file mode 100644 index 0000000000..d85fcc742c --- /dev/null +++ b/Task/XML-Input/NewLISP/xml-input.newlisp @@ -0,0 +1,15 @@ +(set 'xml-input " + + + + + + + +") + +(set 'sexp (xml-parse xml-input)) + +(dolist (x (ref-all "Name" sexp)) + (if (= (length x) 6) + (println (last (sexp (chop x)))))) diff --git a/Task/XML-Input/REXX/xml-input-3.rexx b/Task/XML-Input/REXX/xml-input-3.rexx deleted file mode 100644 index fe08e878ac..0000000000 --- a/Task/XML-Input/REXX/xml-input-3.rexx +++ /dev/null @@ -1,85 +0,0 @@ -/*REXX program to extract student names from an XML string(s). */ -g.= -g.1=' ' -g.2=' ' -g.3=' ' -g.4=' ' -g.5=' ' -g.6=' ' -g.7=' ' -g.8=' ' -g.9=' ' - - do j=1 while g.j\=='' - g.j=space(g.j) - parse var g.j 'Name="' studname '"' - if studname=='' then iterate - if pos('&',studname)\==0 then studname=xmlTranE(studname) - say studname - end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────XML_ subroutine─────────────────────*/ -xml_: parse arg ,_ /*tran an XML entity (&xxxx;) */ -xmlEntity! = '&'_";" -if pos(xmlEntity!,x)\==0 then x=changestr(xmlEntity!,x,arg(1)) -if left(_,2)=='#x' then do - xmlEntity!='&'left(_,3)translate(substr(_,4))";" - x=changestr(xmlEntity!,x,arg(1)) - end -return x -/*──────────────────────────────────XMLTRANE subroutine─────────────────*/ -xmlTranE: procedure; parse arg x /*Following are most of the chars in*/ - /*the DOS (under Windows) codepage. */ -x=XML_('♥',"hearts") ; x=XML_('â',"ETH") ; x=XML_('ƒ',"fnof") ; x=XML_('═',"boxH") -x=XML_('♦',"diams") ; x=XML_('â','#x00e2') ; x=XML_('á',"aacute"); x=XML_('╬',"boxVH") -x=XML_('♣',"clubs") ; x=XML_('â','#x00e9') ; x=XML_('á','#x00e1'); x=XML_('╧',"boxHu") -x=XML_('♠',"spades") ; x=XML_('ä',"auml") ; x=XML_('í',"iacute"); x=XML_('╨',"boxhU") -x=XML_('♂',"male") ; x=XML_('ä','#x00e4') ; x=XML_('í','#x00ed'); x=XML_('╤',"boxHd") -x=XML_('♀',"female") ; x=XML_('à',"agrave") ; x=XML_('ó',"oacute"); x=XML_('╥',"boxhD") -x=XML_('☼',"#x263c") ; x=XML_('à','#x00e0') ; x=XML_('ó','#x00f3'); x=XML_('╙',"boxUr") -x=XML_('↕',"UpDownArrow") ; x=XML_('å',"aring") ; x=XML_('ú',"uacute"); x=XML_('╘',"boxuR") -x=XML_('¶',"para") ; x=XML_('å','#x00e5') ; x=XML_('ú','#x00fa'); x=XML_('╒',"boxdR") -x=XML_('§',"sect") ; x=XML_('ç',"ccedil") ; x=XML_('ñ',"ntilde"); x=XML_('╓',"boxDr") -x=XML_('↑',"uarr") ; x=XML_('ç','#x00e7') ; x=XML_('ñ','#x00f1'); x=XML_('╫',"boxVh") -x=XML_('↑',"uparrow") ; x=XML_('ê',"ecirc") ; x=XML_('Ñ',"Ntilde"); x=XML_('╪',"boxvH") -x=XML_('↑',"ShortUpArrow") ; x=XML_('ê','#x00ea') ; x=XML_('Ñ','#x00d1'); x=XML_('┘',"boxul") -x=XML_('↓',"darr") ; x=XML_('ë',"euml") ; x=XML_('¿',"iquest"); x=XML_('┌',"boxdr") -x=XML_('↓',"downarrow") ; x=XML_('ë','#x00eb') ; x=XML_('⌐',"bnot") ; x=XML_('█',"block") -x=XML_('↓',"ShortDownArrow") ; x=XML_('è',"egrave") ; x=XML_('¬',"not") ; x=XML_('▄',"lhblk") -x=XML_('←',"larr") ; x=XML_('è','#x00e8') ; x=XML_('½',"frac12"); x=XML_('▀',"uhblk") -x=XML_('←',"leftarrow") ; x=XML_('ï',"iuml") ; x=XML_('½',"half") ; x=XML_('α',"alpha") -x=XML_('←',"ShortLeftArrow") ; x=XML_('ï','#x00ef') ; x=XML_('¼',"frac14"); x=XML_('ß',"beta") -x=XML_('1c'x,"rarr") ; x=XML_('î',"icirc") ; x=XML_('¡',"iexcl") ; x=XML_('ß',"szlig") -x=XML_('1c'x,"rightarrow") ; x=XML_('î','#x00ee') ; x=XML_('«',"laqru") ; x=XML_('ß','#x00df') -x=XML_('1c'x,"ShortRightArrow"); x=XML_('ì',"igrave") ; x=XML_('»',"raqru") ; x=XML_('Γ',"Gamma") -x=XML_('!',"excl") ; x=XML_('ì','#x00ec') ; x=XML_('░',"blk12") ; x=XML_('π',"pi") -x=XML_('"',"apos") ; x=XML_('Ä',"Auml") ; x=XML_('▒',"blk14") ; x=XML_('Σ',"Sigma") -x=XML_('$',"dollar") ; x=XML_('Ä','#x00c4') ; x=XML_('▓',"blk34") ; x=XML_('σ',"sigma") -x=XML_("'","quot") ; x=XML_('Å',"Aring") ; x=XML_('│',"boxv") ; x=XML_('µ',"mu") -x=XML_('*',"ast") ; x=XML_('Å','#x00c5') ; x=XML_('┤',"boxvl") ; x=XML_('τ',"tau") -x=XML_('/',"sol") ; x=XML_('É',"Eacute") ; x=XML_('╡',"boxvL") ; x=XML_('Φ',"phi") -x=XML_(':',"colon") ; x=XML_('É','#x00c9') ; x=XML_('╢',"boxVl") ; x=XML_('Θ',"Theta") -x=XML_('<',"lt") ; x=XML_('æ',"aelig") ; x=XML_('╖',"boxDl") ; x=XML_('δ',"delta") -x=XML_('=',"equals") ; x=XML_('æ','#x00e6') ; x=XML_('╕',"boxdL") ; x=XML_('∞',"infin") -x=XML_('>',"gt") ; x=XML_('Æ',"AElig") ; x=XML_('╣',"boxVL") ; x=XML_('φ',"Phi") -x=XML_('?',"quest") ; x=XML_('Æ','#x00c6') ; x=XML_('║',"boxV") ; x=XML_('ε',"epsilon") -x=XML_('@',"commat") ; x=XML_('ô',"ocirc") ; x=XML_('╗',"boxDL") ; x=XML_('∩',"cap") -x=XML_('[',"lbrack") ; x=XML_('ô','#x00f4') ; x=XML_('╝',"boxUL") ; x=XML_('≡',"equiv") -x=XML_('\',"bsol") ; x=XML_('ö',"ouml") ; x=XML_('╜',"boxUl") ; x=XML_('±',"plusmn") -x=XML_(']',"rbrack") ; x=XML_('ö','#x00f6') ; x=XML_('╛',"boxuL") ; x=XML_('±',"pm") -x=XML_('^',"Hat") ; x=XML_('ò',"ograve") ; x=XML_('┐',"boxdl") ; x=XML_('±',"PlusMinus") -x=XML_('`',"grave") ; x=XML_('ò','#x00f2') ; x=XML_('└',"boxur") ; x=XML_('≥',"ge") -x=XML_('{',"lbrace") ; x=XML_('û',"ucirc") ; x=XML_('┴',"bottom"); x=XML_('≤',"le") -x=XML_('{',"lcub") ; x=XML_('û','#x00fb') ; x=XML_('┴',"boxhu") ; x=XML_('÷',"div") -x=XML_('|',"vert") ; x=XML_('ù',"ugrave") ; x=XML_('┬',"boxhd") ; x=XML_('÷',"divide") -x=XML_('|',"verbar") ; x=XML_('ù','#x00f9') ; x=XML_('├',"boxvr") ; x=XML_('≈',"approx") -x=XML_('}',"rbrace") ; x=XML_('ÿ',"yuml") ; x=XML_('─',"boxh") ; x=XML_('∙',"bull") -x=XML_('}',"rcub") ; x=XML_('ÿ','#x00ff') ; x=XML_('┼',"boxvh") ; x=XML_('°',"deg") -x=XML_('Ç',"Ccedil") ; x=XML_('Ö',"Ouml") ; x=XML_('╞',"boxvR") ; x=XML_('·',"middot") -x=XML_('Ç','#x00c7') ; x=XML_('Ö','#x00d6') ; x=XML_('╟',"boxVr") ; x=XML_('·',"middledot") -x=XML_('ü',"uuml") ; x=XML_('Ü',"Uuml") ; x=XML_('╚',"boxUR") ; x=XML_('·',"centerdot") -x=XML_('ü','#x00fc') ; x=XML_('Ü','#x00dc') ; x=XML_('╔',"boxDR") ; x=XML_('·',"CenterDot") -x=XML_('é',"eacute") ; x=XML_('¢',"cent") ; x=XML_('╩',"boxHU") ; x=XML_('√',"radic") -x=XML_('é','#x00e9') ; x=XML_('£',"pound") ; x=XML_('╦',"boxHD") ; x=XML_('²',"sup2") -x=XML_('â',"acirc") ; x=XML_('¥',"yen") ; x=XML_('╠',"boxVR") ; x=XML_('■',"squart ") -return x diff --git a/Task/XML-Input/Zkl/xml-input.zkl b/Task/XML-Input/Zkl/xml-input.zkl new file mode 100644 index 0000000000..256ed51617 --- /dev/null +++ b/Task/XML-Input/Zkl/xml-input.zkl @@ -0,0 +1,18 @@ +student:=RegExp(0'|.*"):?c) - ?arg - ) - & !a - "&" - ( !c:"<"< - | !c:"&"& - | gt - ) - ";" - PCDATAentities$!arg - | !arg - ) - & ( doAttributes - = a v - . !arg:(?a.?v) ?arg - & " " - PCDATAentities$!a - "=\"" - attributeValueEntities$!v - \" - doAttributes$!arg - | - ) - & ( doAll - = xml first A B C att XML - . !arg:?xml - & :?XML - & whl - ' ( !xml:%?first ?xml - & ( !first:(?A.?B) - & ( !B:(?att,?C) - & !XML - ( !C: - & "<" !A doAttributes$!att " />\n" - | "<" - !A - doAttributes$!att - ">" - doAll$!C - "\n" - ) - : ?XML - | !A - : ( "!"&!XML "":?XML - | "!--" - & !XML "":?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/Bracmat/xml-output-2.bracmat b/Task/XML-Output/Bracmat/xml-output-2.bracmat deleted file mode 100644 index b718d519d4..0000000000 --- a/Task/XML-Output/Bracmat/xml-output-2.bracmat +++ /dev/null @@ -1,5 +0,0 @@ - -Bubbly: I'm > Tam and <= Emily -Burns: "When chapman billies leave the street ..." -Short & shrift - diff --git a/Task/XML-Output/Euphoria/xml-output-1.euphoria b/Task/XML-Output/Euphoria/xml-output-1.euphoria deleted file mode 100644 index 6e3674c064..0000000000 --- a/Task/XML-Output/Euphoria/xml-output-1.euphoria +++ /dev/null @@ -1,34 +0,0 @@ -function xmlquote(sequence s) - sequence r - r = "" - for i = 1 to length(s) do - if s[i] = '<' then - r &= "<" - elsif s[i] = '>' then - r &= ">" - elsif s[i] = '&' then - r &= "&" - elsif s[i] = '"' then - r &= """ - elsif s[i] = '\'' then - r &= "'" - else - r &= s[i] - end if - end for - return r -end function - -constant CharacterRemarks = { - {"April", "Bubbly: I'm > Tam and <= Emily"}, - {"Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""}, - {"Emily", "Short & shrift"} -} - -puts(1,"\n") -for i = 1 to length(CharacterRemarks) do - printf(1," ",{xmlquote(CharacterRemarks[i][1])}) - puts(1,xmlquote(CharacterRemarks[i][2])) - puts(1,"\n") -end for -puts(1,"\n") diff --git a/Task/XML-Output/Euphoria/xml-output-2.euphoria b/Task/XML-Output/Euphoria/xml-output-2.euphoria deleted file mode 100644 index d9384feb46..0000000000 --- a/Task/XML-Output/Euphoria/xml-output-2.euphoria +++ /dev/null @@ -1,5 +0,0 @@ - - Bubbly: I'm > Tam and <= Emily - Burns: "When chapman billies leave the street ..." - Short & shrift - diff --git a/Task/XML-Output/Kotlin/xml-output-1.kotlin b/Task/XML-Output/Kotlin/xml-output-1.kotlin new file mode 100644 index 0000000000..f0f420453e --- /dev/null +++ b/Task/XML-Output/Kotlin/xml-output-1.kotlin @@ -0,0 +1,44 @@ +// version 1.1.3 + +import javax.xml.parsers.DocumentBuilderFactory +import javax.xml.transform.dom.DOMSource +import java.io.StringWriter +import javax.xml.transform.stream.StreamResult +import javax.xml.transform.TransformerFactory + +fun main(args: Array) { + val names = listOf("April", "Tam O'Shanter", "Emily") + + val remarks = listOf( + "Bubbly: I'm > Tam and <= Emily", + "Burns: \"When chapman billies leave the street ...\"", + "Short & shrift" + ) + + val dbFactory = DocumentBuilderFactory.newInstance() + val dBuilder = dbFactory.newDocumentBuilder() + val doc = dBuilder.newDocument() + val root = doc.createElement("CharacterRemarks") // create root node + doc.appendChild(root) + + // now create Character elements + for (i in 0 until names.size) { + val character = doc.createElement("Character") + character.setAttribute("name", names[i]) + val remark = doc.createTextNode(remarks[i]) + character.appendChild(remark) + root.appendChild(character) + } + + val source = DOMSource(doc) + val sw = StringWriter() + val result = StreamResult(sw) + val tFactory = TransformerFactory.newInstance() + tFactory.newTransformer().apply { + setOutputProperty("omit-xml-declaration", "yes") + setOutputProperty("indent", "yes") + setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4") + transform(source, result) + } + println(sw) +} diff --git a/Task/XML-Output/Kotlin/xml-output-2.kotlin b/Task/XML-Output/Kotlin/xml-output-2.kotlin new file mode 100644 index 0000000000..8bc6fb934d --- /dev/null +++ b/Task/XML-Output/Kotlin/xml-output-2.kotlin @@ -0,0 +1,5 @@ + + Bubbly: I'm > Tam and <= Emily + Burns: "When chapman billies leave the street ..." + Short & shrift + diff --git a/Task/XML-Output/Zkl/xml-output.zkl b/Task/XML-Output/Zkl/xml-output.zkl new file mode 100644 index 0000000000..aef7416bb3 --- /dev/null +++ b/Task/XML-Output/Zkl/xml-output.zkl @@ -0,0 +1,18 @@ +fcn xmlEscape(text){ + text.replace(" &"," &") .replace(" \""," "") + .replace(" '"," '") .replace(" <"," <") .replace(" >"," >") +} +fcn toXML(as,bs){ + xml:=Sink("\n"); + as.zipWith('wrap(a,b){ + xml.write(" ", + xmlEscape(b),"\n"); + },bs); + xml.write("\n").close(); +} + +toXML(T("April", "Tam O'Shanter", "Emily"), + T("Bubbly: I'm > Tam and <= Emily", + 0'|Burns: "When chapman billies leave the street ..."|, + "Short & shrift")) +.print(); diff --git a/Task/XML-XPath/Gastona/xml-xpath.gastona b/Task/XML-XPath/Gastona/xml-xpath.gastona new file mode 100644 index 0000000000..58124e47bf --- /dev/null +++ b/Task/XML-XPath/Gastona/xml-xpath.gastona @@ -0,0 +1,78 @@ +#javaj# + + oSal, XML Path sample, 300, 400 + +#data# + + + // + //
    + // + // 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 + // + //
    + //
    + + + DEEP DB, SELECT, xmelon_data + ,, path pathStr + ,, tag tagStr + ,, patCnt + ,, dataPlace + ,, value + +#listix# + +
    + //parsing xml data ... + GEN, :mem datos, xml + XMELON, FILE2DB, :mem datos + // + //first item ... + // + // + LOOP, SQL,, //SELECT patCnt AS patITEM1 FROM (@) WHERE path_pathStr == '/inventory/section/item' LIMIT 1 + ,HEAD, //) WHERE patCnt == @ AND dataPlace == 'A' + ,, , LINK, "" + ,, ,, // @="@" + ,, //> + ,, // + ,, LOOP, SQL,, //SELECT * FROM (@) WHERE patCnt == @ AND dataPlace != 'A' + ,, ,, // <@>@> + ,TAIL, // + ,TAIL, // + // + // + //report prices ... + // + LOOP, SQL,, //SELECT value FROM (@) WHERE tag_tagStr == 'price' + , LINK, ", " + ,, @ + // + //put names into a variable + // + VAR=, tabnames, "name" + LOOP, SQL,, //SELECT value FROM (@) WHERE tag_tagStr == 'name' + , LINK, "" + ,, VAR+, tabnames, @ + DUMP, data,, tabnames diff --git a/Task/XML-XPath/Kotlin/xml-xpath.kotlin b/Task/XML-XPath/Kotlin/xml-xpath.kotlin new file mode 100644 index 0000000000..f4a852ef5c --- /dev/null +++ b/Task/XML-XPath/Kotlin/xml-xpath.kotlin @@ -0,0 +1,63 @@ +// version 1.1.3 + +import javax.xml.parsers.DocumentBuilderFactory +import org.xml.sax.InputSource +import java.io.StringReader +import javax.xml.xpath.XPathFactory +import javax.xml.xpath.XPathConstants +import org.w3c.dom.Node +import org.w3c.dom.NodeList + +val 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 + +
    +
    +""" + +fun main(args: Array) { + val dbFactory = DocumentBuilderFactory.newInstance() + val dBuilder = dbFactory.newDocumentBuilder() + val xmlInput = InputSource(StringReader(xml)) + val doc = dBuilder.parse(xmlInput) + val xpFactory = XPathFactory.newInstance() + val xPath = xpFactory.newXPath() + + val qNode = xPath.evaluate("/inventory/section/item[1]", doc, XPathConstants.NODE) as Node + val upc = qNode.attributes.getNamedItem("upc") + val stock = qNode.attributes.getNamedItem("stock") + println("For the first item : upc = ${upc.textContent} and stock = ${stock.textContent}") + + val qNodes = xPath.evaluate("/inventory/section/item/price", doc, XPathConstants.NODESET) as NodeList + print("\nThe prices of each item are : ") + for (i in 0 until qNodes.length) print("${qNodes.item(i).textContent} ") + println() + + val qNodes2 = xPath.evaluate("/inventory/section/item/name", doc, XPathConstants.NODESET) as NodeList + val names = Array(qNodes2.length) { qNodes2.item(it).textContent } + println("\nThe names of each item are as follows :") + println(" ${names.joinToString("\n ")}") +} 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.kotlin new file mode 100644 index 0000000000..cf455382ca --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/Kotlin/xiaolin-wus-line-algorithm.kotlin @@ -0,0 +1,101 @@ +// version 1.1.2 + +import java.awt.* +import javax.swing.* + +class XiaolinWu: JPanel() { + init { + preferredSize = Dimension(640, 640) + background = Color.white + } + + private fun plot(g: Graphics2D, x: Double, y: Double, c: Double) { + g.color = Color(0f, 0f, 0f, c.toFloat()) + g.fillOval(x.toInt(), y.toInt(), 2, 2) + } + + private fun ipart(x: Double) = x.toInt() + + private fun fpart(x: Double) = x - Math.floor(x) + + private fun rfpart(x: Double) = 1.0 - fpart(x) + + private fun drawLine(g: Graphics2D, x0: Double, y0: Double, x1: Double, y1: Double) { + val steep = Math.abs(y1 - y0) > Math.abs(x1 - x0) + if (steep) drawLine(g, y0, x0, y1, x1) + if (x0 > x1) drawLine(g, x1, y1, x0, y0) + + val dx = x1 - x0 + val dy = y1 - y0 + val gradient = dy / dx + + // handle first endpoint + var xend = Math.round(x0).toDouble() + var yend = y0 + gradient * (xend - x0) + var xgap = rfpart(x0 + 0.5) + val xpxl1 = xend // this will be used in the main loop + val ypxl1 = ipart(yend).toDouble() + + if (steep) { + plot(g, ypxl1, xpxl1, rfpart(yend) * xgap) + plot(g, ypxl1 + 1.0, xpxl1, fpart(yend) * xgap) + } + else { + plot(g, xpxl1, ypxl1, rfpart(yend) * xgap) + plot(g, xpxl1, ypxl1 + 1.0, fpart(yend) * xgap) + } + + // first y-intersection for the main loop + var intery = yend + gradient + + // handle second endpoint + xend = Math.round(x1).toDouble() + yend = y1 + gradient * (xend - x1) + xgap = fpart(x1 + 0.5) + val xpxl2 = xend // this will be used in the main loop + val ypxl2 = ipart(yend).toDouble() + + if (steep) { + plot(g, ypxl2, xpxl2, rfpart(yend) * xgap) + plot(g, ypxl2 + 1.0, xpxl2, fpart(yend) * xgap) + } + else { + plot(g, xpxl2, ypxl2, rfpart(yend) * xgap) + plot(g, xpxl2, ypxl2 + 1.0, fpart(yend) * xgap) + } + + // main loop + var x = xpxl1 + 1.0 + while (x <= xpxl2 - 1) { + if (steep) { + plot(g, ipart(intery).toDouble(), x, rfpart(intery)) + plot(g, ipart(intery).toDouble() + 1.0, x, fpart(intery)) + } + else { + plot(g, x, ipart(intery).toDouble(), rfpart(intery)) + plot(g, x, ipart(intery).toDouble() + 1.0, fpart(intery)) + } + intery += gradient + x++ + } + } + + override protected fun paintComponent(gg: Graphics) { + super.paintComponent(gg) + val g = gg as Graphics2D + drawLine(g, 550.0, 170.0, 50.0, 435.0) + } +} + +fun main(args: Array) { + SwingUtilities.invokeLater { + val f = JFrame() + f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE + f.title = "Xiaolin Wu's line algorithm" + f.isResizable = false + f.add(XiaolinWu(), BorderLayout.CENTER) + f.pack() + f.setLocationRelativeTo(null) + f.isVisible = true + } +} diff --git a/Task/Xiaolin-Wus-line-algorithm/Perl-6/xiaolin-wus-line-algorithm.pl6 b/Task/Xiaolin-Wus-line-algorithm/Perl-6/xiaolin-wus-line-algorithm.pl6 index fe44f497e8..85c0e88ae9 100644 --- a/Task/Xiaolin-Wus-line-algorithm/Perl-6/xiaolin-wus-line-algorithm.pl6 +++ b/Task/Xiaolin-Wus-line-algorithm/Perl-6/xiaolin-wus-line-algorithm.pl6 @@ -47,7 +47,7 @@ sub draw-line(@a is copy, @b is copy) { for (x-pxl1 + 1 .. x-pxl2 - 1) Z (intery, intery + gradient ... *) - -> \x,\y { + -> (\x,\y) { my \c = fpart(y); $plot(x, floor(y) , 1 - c) unless c == 1; $plot(x, floor(y) + 1, c ) unless c == 0; diff --git a/Task/Xiaolin-Wus-line-algorithm/Phix/xiaolin-wus-line-algorithm.phix b/Task/Xiaolin-Wus-line-algorithm/Phix/xiaolin-wus-line-algorithm.phix new file mode 100644 index 0000000000..cfad8e5e3f --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/Phix/xiaolin-wus-line-algorithm.phix @@ -0,0 +1,120 @@ +-- +-- demo\rosetta\XiaolinWuLine.exw +-- ============================== +-- +constant TITLE = "Xiaolin Wu's line algorithm" + +bool bresline = false -- space toggles, for comparison + +include pGUI.e + +Ihandle dlg, canvas +cdCanvas cddbuffer, cdcanvas + +constant BACK = CD_PARCHMENT, + LINE = CD_BLUE, + rB = red(BACK), gB = green(BACK), bB = blue(BACK), + rL = red(LINE), gL = green(LINE), bL = blue(LINE) + +procedure plot(atom x, atom y, atom c, bool steep=false) +-- plot the pixel at (x, y) with brightness c (where 0 <= c <= 1) + if steep then {x,y} = {y,x} end if + atom C = 1-c + c = rgb(rL*c+rB*C,gL*c+gB*C,bL*c+bB*C) + cdCanvasPixel(cddbuffer, x, y, c) +end procedure + +procedure plot2(atom x, atom y, atom f, atom xgap, bool steep) + plot(x,y,(1-f)*xgap,steep) + plot(x,y+1,f*xgap,steep) +end procedure + +function fpart(atom x) + return x - floor(x) -- fractional part of x +end function + +procedure draw_line(atom x0,y0,x1,y1) + if bresline then + cdCanvasLine(cddbuffer, x0, y0, x1, y1) + return + end if + bool steep := abs(y1 - y0) > abs(x1 - x0) + if steep then + {x0, y0, x1, y1} = {y0, x0, y1, x1} + end if + if x0>x1 then + {x0, x1, y0, y1} = {x1, x0, y1, y0} + end if + + atom dx := x1 - x0, + dy := y1 - y0, + gradient := iff(dx=0? 1 : dy / dx) + + -- handle first endpoint + atom xend := round(x0), + yend := y0 + gradient * (xend - x0), + xgap := 1-fpart(x0 + 0.5), + xpxl1 := xend, -- this will be used in the main loop + ypxl1 := floor(yend) + plot2(xpxl1, ypxl1, fpart(yend), xgap, steep) + atom intery := yend + gradient -- first y-intersection for the main loop + + -- handle second endpoint + xend := round(x1) + yend := y1 + gradient * (xend - x1) + xgap := fpart(x1 + 0.5) + atom xpxl2 := xend, -- this will be used in the main loop + ypxl2 := floor(yend) + plot2(xpxl2, ypxl2, fpart(yend), xgap, steep) + + -- main loop + for x = xpxl1+1 to xpxl2-1 do + plot2(x, floor(intery), fpart(intery), 1, steep) + intery += gradient + end for +end procedure + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) + integer {w, h} = sq_sub(IupGetIntInt(canvas, "DRAWSIZE"),10) + cdCanvasActivate(cddbuffer) + cdCanvasClear(cddbuffer) + draw_line(0,0,200,200) + draw_line(w,0,200,200) + draw_line(0,h,200,200) + draw_line(w,h,200,200) + cdCanvasFlush(cddbuffer) + return IUP_DEFAULT +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + cdCanvasSetBackground(cddbuffer, BACK) + cdCanvasSetForeground(cddbuffer, LINE) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + if c=' ' then + bresline = not bresline + IupRedraw(canvas) + end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "640x480") + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", TITLE) + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + IupShow(dlg) + IupSetAttribute(canvas, "RASTERSIZE", NULL) + IupMainLoop() + IupClose() +end procedure +main() diff --git a/Task/Xiaolin-Wus-line-algorithm/REXX/xiaolin-wus-line-algorithm.rexx b/Task/Xiaolin-Wus-line-algorithm/REXX/xiaolin-wus-line-algorithm.rexx index 3e519b3e65..5be0e1e5ac 100644 --- a/Task/Xiaolin-Wus-line-algorithm/REXX/xiaolin-wus-line-algorithm.rexx +++ b/Task/Xiaolin-Wus-line-algorithm/REXX/xiaolin-wus-line-algorithm.rexx @@ -1,63 +1,60 @@ -/*REXX program plots/draws a line using the Xiaolin Wu line algorithm. */ -background='·' /*background character: a middle-dot. */ - image.=background /*fill the array with middle-dots. */ - plotC='░▒▓█' /*characters used for plotting points. */ - EoE=1000 /*EOE = End Of Earth, er, ··· graph. */ - do j=-EoE to +EoE /*define the graph: lowest ──► highest.*/ - image.j.0='─' /*define the graph's horizontal axis. */ - image.0.j='│' /* " " " verical " */ - end /*j*/ - image.0.0='┼' /*define the graph's axis origin (char)*/ -parse arg xi yi xf yf . /*allow specifying the line-end points.*/ -if xi=='' | xi=="," then xi= 1 /*Not specified? Then use the default.*/ -if yi=='' | yi=="," then yi= 2 /* " " " " " " */ -if xf=='' | xf=="," then xf=11 /* " " " " " " */ -if yf=='' | yf=="," then yf=12 /* " " " " " " */ -minX=0; minY=0 /*use these as the limits for plotting.*/ -maxX=0; maxY=0 /* " " " " " " " */ -call drawLine xi, yi, xf, yf /*invoke subroutine and graph the line.*/ -border=2 /*allow additional space (plot border).*/ -minX=minX-border*2; maxX=maxX+border*2 /* *2 preserves screen's aspect ratio.*/ -minY=minY-border ; maxY=maxY+border - do y=maxY by -1 to minY; _= /*build a row.*/ - do x=minX to maxX; _=_ || image.x.y; end /*x*/ - say _ /*display row.*/ - end /*y*/ /*graph is cropped by the MINs and MAXs*/ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ +/*REXX program plots/draws (ASCII) a line using the Xiaolin Wu line algorithm. */ +background= '·' /*background character: a middle-dot. */ + image.= background /*fill the array with middle-dots. */ + plotC= '░▒▓█' /*characters used for plotting points. */ + EoE= 3000 /*EOE = End Of Earth, er, ··· graph. */ + do j=-EoE to +EoE /*define the graph: lowest ──► highest.*/ + image.j.0= '─' /*define the graph's horizontal axis. */ + image.0.j= '│' /* " " " verical " */ + end /*j*/ + image.0.0= '┼' /*define the graph's axis origin (char)*/ +parse arg xi yi xf yf . /*allow specifying the line-end points.*/ +if xi=='' | xi=="," then xi= 1 /*Not specified? Then use the default.*/ +if yi=='' | yi=="," then yi= 2 /* " " " " " " */ +if xf=='' | xf=="," then xf=11 /* " " " " " " */ +if yf=='' | yf=="," then yf=12 /* " " " " " " */ +minX=0; minY=0 /*use these as the limits for plotting.*/ +maxX=0; maxY=0 /* " " " " " " " */ +call drawLine xi, yi, xf, yf /*invoke subroutine and graph the line.*/ +border=2 /*allow additional space (plot border).*/ +minX=minX - border * 2; maxX=maxX+border * 2 /*preserve screen's aspect ratio {*2}.*/ +minY=minY - border ; maxY=maxY+border + do y=maxY to minY by -1; _= /*construct a row.*/ + do x=minX to maxX; _=_ || image.x.y; end /*x*/ + say _ /*display the constructed row to term. */ + end /*y*/ /*graph is cropped by the MINs and MAXs*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ drawLine: parse arg x1,y1,x2,y2; switchXY=0; dx=x2-x1 dy=y2-y1 - if abs(dx) < abs(dy) then parse value x1 y1 x2 y2 dx dy with, - y1 x2 y2 x2 dy dx - if x2= 0 && idx < self.bitmap.count { + self.bitmap[idx] = self.blendColors(bot: self.bitmap[idx], top: color) + } +} + +// return the fractional part of a Double +func fpart(_ x: Double) -> Double { + return modf(x).1 +} + +// reciprocal of the fractional part of a Double +func rfpart(_ x: Double) -> Double { + return 1 - fpart(x) +} + +// draw a 1px wide line using Xiolin Wu's antialiased line algorithm +public func smoothLine(_ p0: Point, _ p1: Point) { + var x0 = p0.x, x1 = p1.x, y0 = p0.y, y1 = p1.y //swapable ptrs + let steep = abs(y1 - y0) > abs(x1 - x0) + if steep { + swap(&x0, &y0) + swap(&x1, &y1) + } + if x0 > x1 { + swap(&x0, &x1) + swap(&y0, &y1) + } + let dX = x1 - x0 + let dY = y1 - y0 + + var gradient: Double + if dX == 0.0 { + gradient = 1.0 + } + else { + gradient = dY / dX + } + + // handle endpoint 1 + var xend = round(x0) + var yend = y0 + gradient * (xend - x0) + var xgap = self.rfpart(x0 + 0.5) + let xpxl1 = Int(xend) + let ypxl1 = Int(yend) + + // first y-intersection for the main loop + var intery = yend + gradient + + if steep { + self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: ypxl1, y: xpxl1) + self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: ypxl1 + 1, y: xpxl1) + } + else { + self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: xpxl1, y: ypxl1) + self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: xpxl1, y: ypxl1 + 1) + } + + xend = round(x1) + yend = y1 + gradient * (xend - x1) + xgap = self.fpart(x1 + 0.5) + let xpxl2 = Int(xend) + let ypxl2 = Int(yend) + + // handle second endpoint + if steep { + self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: ypxl2, y: xpxl2) + self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: ypxl2 + 1, y: xpxl2) + } + else { + self.pixel(color: self.strokeColor.colorWithAlpha(self.rfpart(yend) * xgap), x: xpxl2, y: ypxl2) + self.pixel(color: self.strokeColor.colorWithAlpha(self.fpart(yend) * xgap), x: xpxl2, y: ypxl2 + 1) + } + + // main loop + if steep { + for x in xpxl1+1.. a +) : lazy(a) = $delay(f(myfix(f))) +// +val +fact = +myfix{int-int} +( +lam(ff) => lam(x) => if x > 0 then x * !ff(x-1) else 1 +) +(* ****** ****** *) +// +implement main0 () = println! ("fact(10) = ", !fact(10)) +// +(* ****** ****** *) diff --git a/Task/Y-combinator/AppleScript/y-combinator-1.applescript b/Task/Y-combinator/AppleScript/y-combinator-1.applescript index 87fe15d7f2..9018fce5cd 100644 --- a/Task/Y-combinator/AppleScript/y-combinator-1.applescript +++ b/Task/Y-combinator/AppleScript/y-combinator-1.applescript @@ -1,64 +1,62 @@ --- Y COMBINATOR +-- Y COMBINATOR --------------------------------------------------------------- on |Y|(f) script - on lambda(y) + on |λ|(y) script - on lambda(arg) - y's lambda(y)'s lambda(arg) - end lambda + on |λ|(x) + y's |λ|(y)'s |λ|(x) + end |λ| end script - f's lambda(result) - - end lambda + f's |λ|(result) + end |λ| end script - result's lambda(result) + result's |λ|(result) end |Y| --- TEST +-- TEST ----------------------------------------------------------------------- on run -- Factorial script fact - on lambda(f) + on |λ|(f) script - on lambda(n) + on |λ|(n) if n = 0 then return 1 - n * (f's lambda(n - 1)) - end lambda + n * (f's |λ|(n - 1)) + end |λ| end script - end lambda + end |λ| end script -- Fibonacci script fib - on lambda(f) + on |λ|(f) script - on lambda(n) + on |λ|(n) if n = 0 then return 0 if n = 1 then return 1 - (f's lambda(n - 2)) + (f's lambda(n - 1)) - end lambda + (f's |λ|(n - 2)) + (f's |λ|(n - 1)) + end |λ| end script - end lambda + end |λ| end script - {facts:map(|Y|(fact), range(0, 11)), fibs:map(|Y|(fib), range(0, 20))} + {facts:map(|Y|(fact), enumFromTo(0, 11)), fibs:map(|Y|(fib), enumFromTo(0, 20))} --> {facts:{1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800}, - --> fibs:{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765}} + + --> fibs:{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, + -- 1597, 2584, 4181, 6765}} end run ---------------------------------------------------------------------------- - - --- GENERIC FUNCTIONS (FOR TEST) +-- GENERIC FUNCTIONS FOR TEST ------------------------------------------------- -- map :: (a -> b) -> [a] -> [b] on map(f, xs) @@ -66,14 +64,14 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map --- range :: Int -> Int -> [Int] -on range(m, n) +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) if n < m then set d to -1 else @@ -84,7 +82,7 @@ on range(m, n) set end of lst to i end repeat return lst -end range +end enumFromTo -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -93,7 +91,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Y-combinator/C/y-combinator.c b/Task/Y-combinator/C/y-combinator.c index 4422a8fafd..377df60855 100644 --- a/Task/Y-combinator/C/y-combinator.c +++ b/Task/Y-combinator/C/y-combinator.c @@ -6,27 +6,25 @@ a potential parameter, to simulate closure */ typedef struct func_t *func; typedef struct func_t { - func (*func) (func, func), _; + func (*fn) (func, func); + func _; int num; } func_t; func new(func(*f)(func, func), func _) { func x = malloc(sizeof(func_t)); - x->func = f; + x->fn = f; x->_ = _; /* closure, sort of */ x->num = 0; return x; } -func call(func f, func g) { - return f->func(f, g); +func call(func f, func n) { + return f->fn(f, n); } func Y(func(*f)(func, func)) { - func _(func x, func y) { return call(x->_, y); } - func_t __ = { _ }; - - func g = call(new(f, 0), &__); + func g = new(f, 0); g->_ = g; return g; } @@ -37,26 +35,19 @@ func num(int n) { return x; } -func fac(func f, func _null) { - func _(func self, func n) { - int nn = n->num; - return nn > 1 ? num(nn * call(self->_, num(nn - 1))->num) - : num(1); - } - return new(_, f); +func fac(func self, func n) { + int nn = n->num; + return nn > 1 ? num(nn * call(self->_, num(nn - 1))->num) + : num(1); } -func fib(func f, func _null) { - func _(func self, func n) { - int nn = n->num; - return nn > 1 - ? num( call(self->_, num(nn - 1))->num + - call(self->_, num(nn - 2))->num ) - : num(1); - } - - return new(_, f); +func fib(func self, func n) { + int nn = n->num; + return nn > 1 + ? num( call(self->_, num(nn - 1))->num + + call(self->_, num(nn - 2))->num ) + : num(1); } void show(func n) { printf(" %d", n->num); } diff --git a/Task/Y-combinator/Elena/y-combinator.elena b/Task/Y-combinator/Elena/y-combinator.elena new file mode 100644 index 0000000000..bad9d303b9 --- /dev/null +++ b/Task/Y-combinator/Elena/y-combinator.elena @@ -0,0 +1,16 @@ +import extensions. + +singleton YCombinator +{ + fix : func + = (:f)[(:x)[ x eval:x ] eval(:g)[ f eval(:x)[(g eval:g) eval:x] ]] eval:func. +} + +program = +[ + var fib := YCombinator fix(:f)((:i)( (i <= 1) ifTrue:[^i] ifFalse:[^f eval(i-1) + f eval(i-2) ] )). + var fact := YCombinator fix(:f)((:i)((i == 0) ifTrue:[^1] ifFalse:[^f eval(i-1) * i] )). + + console printLine("fib(10)=",fib eval(10)). + console printLine("fact(10)=",fact eval(10)). +]. diff --git a/Task/Y-combinator/Haskell/y-combinator-1.hs b/Task/Y-combinator/Haskell/y-combinator-1.hs index 166f51aebb..3958793430 100644 --- a/Task/Y-combinator/Haskell/y-combinator-1.hs +++ b/Task/Y-combinator/Haskell/y-combinator-1.hs @@ -1,15 +1,27 @@ -newtype Mu a = Roll { unroll :: Mu a -> a } +newtype Mu a = Roll + { unroll :: Mu a -> a } fix :: (a -> a) -> a -fix = \f -> (\x -> f (unroll x x)) $ Roll (\x -> f (unroll x x)) +fix = g <*> (Roll . g) + where + g = (. (>>= id) unroll) fac :: Integer -> Integer -fac = fix $ \f n -> if (n <= 0) then 1 else n * f (n-1) +fac = + fix $ + \f n -> + (if n <= 0 + then 1 + else n * f (n - 1)) fibs :: [Integer] -fibs = fix $ \fbs -> 0 : 1 : fix zipP fbs (tail fbs) - where zipP f (x:xs) (y:ys) = x+y : f xs ys +fibs = + fix $ (0 :) . (1 :) . (fix (\f (x:xs) (y:ys) -> x + y : f xs ys) <*> tail) -main = do - print $ map fac [1 .. 20] - print $ take 20 fibs +main :: IO () +main = + mapM_ + print + [ map fac [1 .. 20] + , take 20 fibs + ] diff --git a/Task/Y-combinator/Haskell/y-combinator-2.hs b/Task/Y-combinator/Haskell/y-combinator-2.hs index 18b74b9f80..6fd1eb6ba2 100644 --- a/Task/Y-combinator/Haskell/y-combinator-2.hs +++ b/Task/Y-combinator/Haskell/y-combinator-2.hs @@ -1,28 +1,36 @@ fix :: (a -> a) -> a -fix f = f (fix f) -- _not_ the {fix f = x where x = f x} +fix f = f (fix f) -- _not_ the {fix f = x where x = f x} fac :: Integer -> Integer -fac_ f n | n <= 0 = 1 - | otherwise = n * f (n-1) -fac = fix fac_ -- fac_ (fac_ . fac_ . fac_ . fac_ . ...) +fac_ f n + | n <= 0 = 1 + | otherwise = n * f (n - 1) + +fac = fix fac_ -- fac_ (fac_ . fac_ . fac_ . fac_ . ...) -- a simple but wasteful exponential time definition: fib :: Integer -> Integer fib_ f 0 = 0 fib_ f 1 = 1 -fib_ f n = f (n-1) + f (n-2) +fib_ f n = f (n - 1) + f (n - 2) + fib = fix fib_ -- Or for far more efficiency, compute a lazy infinite list. This is -- a Y-combinator version of: fibs = 0:1:zipWith (+) fibs (tail fibs) fibs :: [Integer] -fibs_ a = 0:1:(fix zipP a (tail a)) - where - zipP f (x:xs) (y:ys) = x+y : f xs ys +fibs_ a = 0 : 1 : fix zipP a (tail a) + where + zipP f (x:xs) (y:ys) = x + y : f xs ys + fibs = fix fibs_ -- This code shows how the functions can be used: -main = do - print $ map fac [1 .. 20] - print $ map fib [0 .. 19] - print $ take 20 fibs +main : IO () +main = + mapM_ + print + [ map fac [1 .. 20] + , map fib [0 .. 19] + , take 20 fibs + ] diff --git a/Task/Y-combinator/J/y-combinator-1.j b/Task/Y-combinator/J/y-combinator-1.j index 757cded197..c88bb44baf 100644 --- a/Task/Y-combinator/J/y-combinator-1.j +++ b/Task/Y-combinator/J/y-combinator-1.j @@ -1 +1 @@ -Y=. ((((&>)/)(1 : '(5!:5)<''x'''))(&([ 128!:2 ,&<)))f. +Y=. ((((&>)/)((((^:_1)b.)(`(<'0';_1)))(`:6)))(&([ 128!:2 ,&<))) diff --git a/Task/Y-combinator/J/y-combinator-2.j b/Task/Y-combinator/J/y-combinator-2.j index fe0b2408ac..c700edddd5 100644 --- a/Task/Y-combinator/J/y-combinator-2.j +++ b/Task/Y-combinator/J/y-combinator-2.j @@ -1,11 +1,11 @@ u=. [ NB. Function (left) n=. ] NB. Argument (right) - sr=. [ 128!:2 ,&< NB. Self referring + sr=. [ apply f. ,&< NB. Self referring - fac=. (1:`(n * u sr n - 1:)) @. (0: < n) + fac=. (1:`(n * u sr n - 1:)) @. (0 < n) fac f. Y 10 3628800 - Fib=. ((u sr n - 2:) + u sr n - 1:) ^: (1: < n) + Fib=. ((u sr n - 2:) + u sr n - 1:) ^: (1 < n) Fib f. Y 10 55 diff --git a/Task/Y-combinator/J/y-combinator-3.j b/Task/Y-combinator/J/y-combinator-3.j index 8690a20540..130c6b34bb 100644 --- a/Task/Y-combinator/J/y-combinator-3.j +++ b/Task/Y-combinator/J/y-combinator-3.j @@ -1,9 +1,12 @@ fac f. Y NB. Showing the stateless recursive factorial function... -'1:`(] * [ ([ 128!:2 ,&<) ] - 1:)@.(0: < ])&>/'&([ 128!:2 ,&<) +'1:`(] * [ ([ 128!:2 ,&<) ] - 1:)@.(0 < ])&>/'&([ 128!:2 ,&<) + fac f. NB. Showing the stateless factorial step... -1:`(] * [ ([ 128!:2 ,&<) ] - 1:)@.(0: < ]) +1:`(] * [ ([ 128!:2 ,&<) ] - 1:)@.(0 < ]) + Fib f. Y NB. Showing the stateless recursive Fibonacci function... -'(([ ([ 128!:2 ,&<) ] - 2:) + [ ([ 128!:2 ,&<) ] - 1:)^:(1: < ])&>/'&([ 128!:2 ,&<) +'(([ ([ 128!:2 ,&<) ] - 2:) + [ ([ 128!:2 ,&<) ] - 1:)^:(1 < ])&>/'&([ 128!:2 ,&<) + Fib f. NB. Showing the stateless Fibonacci step... -(([ ([ 128!:2 ,&<) ] - 2:) + [ ([ 128!:2 ,&<) ] - 1:)^:(1: < ]) +(([ ([ 128!:2 ,&<) ] - 2:) + [ ([ 128!:2 ,&<) ] - 1:)^:(1 < ]) diff --git a/Task/Y-combinator/J/y-combinator-4.j b/Task/Y-combinator/J/y-combinator-4.j index f6d6b60d3d..ed3d9d709b 100644 --- a/Task/Y-combinator/J/y-combinator-4.j +++ b/Task/Y-combinator/J/y-combinator-4.j @@ -1,4 +1,4 @@ -sr=. [ 128!:2 ,&< NB. Self referring -lw=. '(5!:5)<''x''' (1 :) NB. Linear representation of a word -Y=. (&>)/lw(&sr) f. -Y=. 'Y'f. NB. Fixing it + sr=. [ apply f.,&< NB. Self referring + lv=. (((^:_1)b.)(`(<'0';_1)))(`:6) NB. Linear representation of a verb argument + Y=. (&>)/lv(&sr) f. NB. Y combinator + Y=. 'Y'f. NB. Fixing it diff --git a/Task/Y-combinator/Kotlin/y-combinator.kotlin b/Task/Y-combinator/Kotlin/y-combinator.kotlin new file mode 100644 index 0000000000..b9102398aa --- /dev/null +++ b/Task/Y-combinator/Kotlin/y-combinator.kotlin @@ -0,0 +1,22 @@ +// version 1.1.2 + +typealias Func = (T) -> R + +class RecursiveFunc(val p: (RecursiveFunc) -> Func) + +fun y(f: (Func) -> Func): Func { + val rec = RecursiveFunc { r -> f { r.p(r)(it) } } + return rec.p(rec) +} + +fun fac(f: Func) = { x: Int -> if (x <= 1) 1 else x * f(x - 1) } + +fun fib(f: Func) = { x: Int -> if (x <= 2) 1 else f(x - 1) + f(x - 2) } + +fun main(args: Array) { + print("Factorial(1..10) : ") + for (i in 1..10) print("${y(::fac)(i)} ") + print("\nFibonacci(1..10) : ") + for (i in 1..10) print("${y(::fib)(i)} ") + println() +} diff --git a/Task/Y-combinator/Lambdatalk/y-combinator.lambdatalk b/Task/Y-combinator/Lambdatalk/y-combinator.lambdatalk new file mode 100644 index 0000000000..9fb1565df5 --- /dev/null +++ b/Task/Y-combinator/Lambdatalk/y-combinator.lambdatalk @@ -0,0 +1,42 @@ +1) defining the Ycombinator +{def Y + {lambda {:f :n} + {:f :f :n}}} + +2) defining non recursive functions +2.1) factorial +{def almost-fac + {lambda {:f :n} + {if {= :n 1} + then 1 + else {* :n {:f :f {- :n 1}}}}}} + +2.2) fibonacci +{def almost-fibo + {lambda {:f :n} + {if {< :n 2} + then 1 + else {+ {:f :f {- :n 1}} {:f :f {- :n 2}}}}}} + +3) testing +{Y almost-fac 6} +-> 720 +{Y almost-fibo 8} +-> 34 + +We could also forget the Ycombinator and names: + +1) fac: +{{lambda {:f :n} {:f :f :n}} + {lambda {:f :n} + {if {= :n 1} + then 1 + else {* :n {:f :f {- :n 1}}}}} 6} +-> 720 + +2) fibo: +{{lambda {:f :n} {:f :f :n}} + {{lambda {:f :n} + {if {< :n 2} then 1 + else {+ {:f :f {- :n 1}} {:f :f {- :n 2}}}}}} 8} +-> 34 diff --git a/Task/Y-combinator/Rust/y-combinator.rust b/Task/Y-combinator/Rust/y-combinator.rust index f9eb38f374..b098980cb3 100644 --- a/Task/Y-combinator/Rust/y-combinator.rust +++ b/Task/Y-combinator/Rust/y-combinator.rust @@ -1,49 +1,71 @@ -use std::sync::Arc; +//! A simple implementation of the Y Combinator +// λf.(λx.xx)(λx.f(xx)) +// <=> λf.(λx.f(xx))(λx.f(xx)) -//Arc> -macro_rules! abc { - ($x:expr) => (Arc::new(Box::new($x))); +// CREDITS: A better version of the previous code that was posted here, with detailed explanation. +// See and also . + +// A function type that takes its own type as an input is an infinite recursive type. +// We introduce a trait that will allow us to have an input with the same type as self, and break the recursion. +// The input is going to be a trait object that implements the desired function in the interface. +// NOTE: We will be coercing a reference to a closure into this trait object. +trait Apply { + fn apply( &self, &Apply, T ) -> R; } -#[derive(Clone)] -enum Mu { - Roll(Arc)->T>>), -} +impl Apply for F where F: Fn( &Apply, T ) -> R { + fn apply( &self, f: &Apply, t: T ) -> R { + self( f, t ) -fn unroll(Mu::Roll(f): Mu) -> Arc)->T>> {f.clone()} - -pub type Func
    = ArcA>>; -pub type RecFunc = Arc) -> Func>>; - -pub fn y(f: RecFunc) -> Func { - let g: Arc>)->Func>> = abc!(move |x : Mu>| -> Func { - let f = f.clone(); - abc!(move |a:A| -> A { - let f = f.clone(); - f(unroll(x.clone())(x.clone()))(a) - }) - }); - g(Mu::Roll(g.clone())) -} - -#[macro_export] -macro_rules! y { - (|$name:ident| $fun:tt) => { - y(abc!(|$name| abc!($fun))) + // If we were to pass in self as f, we get - + // NOTE: Each letter is an individual symbol. + // λf.λt.sft + // => λs.λt.sst [s/f] + // => λs.ss } } -fn fac(n: u32) -> u32 { - let fn_: Func = y!(|f| (move |x| if x == 0 { 1 } else { f(x-1) * x })); - fn_(n) +// Here you take a reference to the function you want to recurse, AND the input, and return the result. +// But, you are NOT a recursive version of the given function... +// You CAN, of course, wrap this in a closure. +fn y_apply( f: &F, t: T ) -> R where F: Fn( &Fn( T ) -> R, T ) -> R { + ( &|x: &Apply, y| x.apply( x, y ) ) + .apply( &|x: &Apply, y| f( &|z| x.apply( x, z ), y ), t ) + + // NOTE: Each letter is an individual symbol. + // (λx.(λy.xxy))(λx.(λy.f(λz.xxz)y))t + // => (λx.xx)(λx.f(xx))t + // => (Yf)t } -fn fib(n: u32) -> u32 { - let fn_: Func = y!(|f| (move |x| if x < 2 { x } else { f(x-1) + f(x-2) })); - fn_(n) +// The static lifetime bounds on the type parameters 'T' and 'R' guarantee that those types will not - +// - contain any references that will have a lifetime less than 'static. +// If the types are allowed to have references that have a lifetime shorter than 'static, those references - +// - may become invalid while you still you have the returned value. +// You need to have the lifetimes be 'static, because, unlike before, you RETURN a recursive version of the function... +fn y( f: Box R, T ) -> R> ) -> Box R> { + Box::new( move |t: T| ( &|x: &Apply, y| x.apply( x, y ) ) + .apply( &|x: &Apply, y| f( &|z| x.apply( x, z ), y ), t ) ) + + // NOTE: Each letter is an individual symbol. + // (λt(λx.(λy.xxy))(λx.(λy.f(λz.xxz)y)))t + // => (λx.xx)(λx.f(xx)) + // => Yf +} + +fn fac( n: usize ) -> usize { + let almost_fac = Box::new( |f: &Fn( usize ) -> usize, x| if x == 0 { 1 } else { x * f( x - 1 ) } ); + let fac = y( almost_fac ); + fac( n ) +} + +fn fib( n: usize ) -> usize { + let almost_fib = Box::new( |f: &Fn( usize ) -> usize, x| if x < 2 { x } else { f( x - 2 ) + f( x - 1 ) } ); + let fib = y( almost_fib ); + fib( n ) } fn main() { - println!("{}", fac(10)); - println!("{}", fib(10)) + println!( "{}", fac( 10 ) ); + println!( "{}", fib( 10 ) ); } diff --git a/Task/Y-combinator/Shen/y-combinator.shen b/Task/Y-combinator/Shen/y-combinator.shen new file mode 100644 index 0000000000..f1ac1f1baa --- /dev/null +++ b/Task/Y-combinator/Shen/y-combinator.shen @@ -0,0 +1,11 @@ +(define y + F -> ((/. X (X X)) + (/. X (F (/. Z ((X X) Z)))))) + +(let Fac (y (/. F N (if (= 0 N) + 1 + (* N (F (- N 1)))))) + (output "~A~%~A~%~A~%" + (Fac 0) + (Fac 5) + (Fac 10))) diff --git a/Task/Y-combinator/Sidef/y-combinator.sidef b/Task/Y-combinator/Sidef/y-combinator.sidef index c88e2050fc..fa48b66cff 100644 --- a/Task/Y-combinator/Sidef/y-combinator.sidef +++ b/Task/Y-combinator/Sidef/y-combinator.sidef @@ -1,7 +1,7 @@ -var y = ->(f) {->(g) {g(g)}(->(g) { f(->(*args) {g(g)(args...)})})}; +var y = ->(f) {->(g) {g(g)}(->(g) { f(->(*args) {g(g)(args...)})})} -var fac = ->(f) { ->(n) { n < 2 ? 1 : (n * f(n-1)) } }; -say 10.of { |i| y(fac)(i) }; +var fac = ->(f) { ->(n) { n < 2 ? 1 : (n * f(n-1)) } } +say 10.of { |i| y(fac)(i) } -var fib = ->(f) { ->(n) { n < 2 ? n : (f(n-2) + f(n-1)) } }; -say 10.of { |i| y(fib)(i) }; +var fib = ->(f) { ->(n) { n < 2 ? n : (f(n-2) + f(n-1)) } } +say 10.of { |i| y(fib)(i) } diff --git a/Task/Y-combinator/SuperCollider/y-combinator.supercollider b/Task/Y-combinator/SuperCollider/y-combinator.supercollider new file mode 100644 index 0000000000..1ea3e0bd5a --- /dev/null +++ b/Task/Y-combinator/SuperCollider/y-combinator.supercollider @@ -0,0 +1,39 @@ +// z-combinator +( +z = { |f| + { |x| x.(x) }.( + { |y| + f.({ |args| y.(y).(args) }) + } + ) +}; +) + + +// factorial +k = { |f| { |x| if(x < 2, 1, { x * f.(x - 1) }) } }; + +g = z.(k); + +g.(5) // 120 + +(1..10).collect(g) // [ 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800 ] + + + +// fibonacci + +k = { |f| { |x| if(x <= 2, 1, { f.(x - 1) + f.(x - 2) }) } }; + +g = z.(k); + +g.(3) + +(1..10).collect(g) // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ] + +// a shorter form + +( +r = { |x| x.(x) }; +z = { |f| r.({ |y| f.(r.(y).(_)) }) }; +) diff --git a/Task/Y-combinator/Vim-Script/y-combinator.vim b/Task/Y-combinator/Vim-Script/y-combinator-1.vim similarity index 100% rename from Task/Y-combinator/Vim-Script/y-combinator.vim rename to Task/Y-combinator/Vim-Script/y-combinator-1.vim diff --git a/Task/Y-combinator/Vim-Script/y-combinator-2.vim b/Task/Y-combinator/Vim-Script/y-combinator-2.vim new file mode 100644 index 0000000000..aab07ceac8 --- /dev/null +++ b/Task/Y-combinator/Vim-Script/y-combinator-2.vim @@ -0,0 +1,9 @@ +if !has("lambda") + echoerr 'Lambda feature required' + finish +endif +let Y = {f -> {x -> x(x)}({y -> f({... -> call(y(y), a:000)})})} +let Fac = {f -> {n -> n<2 ? 1 : n * f(n-1)}} + +echo Y(Fac)(5) +echo map(range(10), 'Y(Fac)(v:val)') diff --git a/Task/Y-combinator/Wart/y-combinator.wart b/Task/Y-combinator/Wart/y-combinator.wart index 2146e9601e..24b222fa23 100644 --- a/Task/Y-combinator/Wart/y-combinator.wart +++ b/Task/Y-combinator/Wart/y-combinator.wart @@ -1,3 +1,4 @@ +# Better names due to Jim Weirich: http://vimeo.com/45140590 def (Y improver) ((fn(gen) gen.gen) (fn(gen) diff --git a/Task/Y-combinator/Zkl/y-combinator-1.zkl b/Task/Y-combinator/Zkl/y-combinator-1.zkl new file mode 100644 index 0000000000..51418b8101 --- /dev/null +++ b/Task/Y-combinator/Zkl/y-combinator-1.zkl @@ -0,0 +1 @@ +fcn Y(f){ fcn(g){ g(g) }( 'wrap(h){ f( 'wrap(a){ h(h)(a) }) }) } diff --git a/Task/Y-combinator/Zkl/y-combinator-2.zkl b/Task/Y-combinator/Zkl/y-combinator-2.zkl new file mode 100644 index 0000000000..e7076ae736 --- /dev/null +++ b/Task/Y-combinator/Zkl/y-combinator-2.zkl @@ -0,0 +1,3 @@ +fcn almost_factorial(f){ fcn(n,f){ if(n<=1) 1 else n*f(n-1) }.fp1(f) } +Y(almost_factorial)(6).println(); +[0..10].apply(Y(almost_factorial)).println(); diff --git a/Task/Y-combinator/Zkl/y-combinator-3.zkl b/Task/Y-combinator/Zkl/y-combinator-3.zkl new file mode 100644 index 0000000000..2d4f879627 --- /dev/null +++ b/Task/Y-combinator/Zkl/y-combinator-3.zkl @@ -0,0 +1,3 @@ +fcn almost_fib(f){ fcn(n,f){ if(n<2) 1 else f(n-1)+f(n-2) }.fp1(f) } +Y(almost_fib)(9).println(); +[0..10].apply(Y(almost_fib)).println(); diff --git a/Task/Yahoo--search-interface/Gambas/yahoo--search-interface.gambas b/Task/Yahoo--search-interface/Gambas/yahoo--search-interface.gambas new file mode 100644 index 0000000000..7d4b8782ea --- /dev/null +++ b/Task/Yahoo--search-interface/Gambas/yahoo--search-interface.gambas @@ -0,0 +1,12 @@ +Public Sub Form_Open() +Dim hWebView As WebView + +Me.Arrangement = Arrange.Fill +Me.Maximized = True +Me.Title = "Yahoo! search interface" + +hWebView = New WebView(Me) +hWebView.Expand = True +hWebView.URL = "https://www.yahoo.com" + +End diff --git a/Task/Yin-and-yang/Batch-File/yin-and-yang.bat b/Task/Yin-and-yang/Batch-File/yin-and-yang.bat deleted file mode 100644 index e20bb36b07..0000000000 --- a/Task/Yin-and-yang/Batch-File/yin-and-yang.bat +++ /dev/null @@ -1,34 +0,0 @@ -@echo off - - %== Set the dimension of the SVG 'image' that will be created ==% -set pic_width=30 -set pic_height=30 - - %== Redirect the SVG stdout to 'YINYANG.SVG' in the same directory ==% - -echo.^>YINYANG.SVG -echo.^>YINYANG.SVG -echo. 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'^>>>YINYANG.SVG -echo.^>YINYANG.SVG -echo. xmlns:xlink='http://www.w3.org/1999/xlink'>>YINYANG.SVG -echo. width='%pic_width%' height='%pic_height%'^>>>YINYANG.SVG -echo. ^^>>YINYANG.SVG -echo. ^>YINYANG.SVG -echo. fill='white' stroke-width='1'/^>>>YINYANG.SVG -echo. ^>>YINYANG.SVG -echo. ^>>YINYANG.SVG -echo. ^>>YINYANG.SVG -echo. ^^>>YINYANG.SVG - - %== Create the yin-yang symbol ==% -call :draw_yinyang 20 0.05 -call :draw_yinyang 8 0.02 - -echo.^>>YINYANG.SVG -exit /b 0 - -:draw_yinyang -echo.^>>YINYANG.SVG -goto :EOF diff --git a/Task/Yin-and-yang/Gambas/yin-and-yang.gambas b/Task/Yin-and-yang/Gambas/yin-and-yang.gambas new file mode 100644 index 0000000000..56ac4c4838 --- /dev/null +++ b/Task/Yin-and-yang/Gambas/yin-and-yang.gambas @@ -0,0 +1,23 @@ +Public Sub Form_Open() +Dim hPictureBox As PictureBox +Dim siCount As Short + +With Me + .Title = "Yin and yang" + .Padding = 5 + .Height = 210 + .Width = 310 + .Arrangement = Arrange.Row +End With + +For siCount = 2 DownTo 1 + hPictureBox = New PictureBox(Me) + With hPictureBox + .Height = siCount * 100 + .Width = siCount * 100 + .Picture = Picture.Load("../yinyang.png") + .Stretch = True + End With +Next + +End diff --git a/Task/Yin-and-yang/jq/yin-and-yang-1.jq b/Task/Yin-and-yang/Jq/yin-and-yang-1.jq similarity index 100% rename from Task/Yin-and-yang/jq/yin-and-yang-1.jq rename to Task/Yin-and-yang/Jq/yin-and-yang-1.jq diff --git a/Task/Yin-and-yang/jq/yin-and-yang-2.jq b/Task/Yin-and-yang/Jq/yin-and-yang-2.jq similarity index 100% rename from Task/Yin-and-yang/jq/yin-and-yang-2.jq rename to Task/Yin-and-yang/Jq/yin-and-yang-2.jq diff --git a/Task/Yin-and-yang/Kotlin/yin-and-yang.kotlin b/Task/Yin-and-yang/Kotlin/yin-and-yang.kotlin new file mode 100644 index 0000000000..76d362d819 --- /dev/null +++ b/Task/Yin-and-yang/Kotlin/yin-and-yang.kotlin @@ -0,0 +1,73 @@ +// version 1.1.2 + +import java.awt.Color +import java.awt.Graphics +import java.awt.Image +import java.awt.image.BufferedImage +import javax.swing.ImageIcon +import javax.swing.JFrame +import javax.swing.JPanel +import javax.swing.JLabel + +class YinYangGenerator { + private fun drawYinYang(size: Int, g: Graphics) { + with(g) { + // Preserve the color for the caller + val colorSave = color + color = Color.WHITE + + // Use fillOval to draw a filled in circle + fillOval(0, 0, size - 1, size - 1) + color = Color.BLACK + + // Use fillArc to draw part of a filled in circle + fillArc(0, 0, size - 1, size - 1, 270, 180) + fillOval(size / 4, size / 2, size / 2, size / 2) + color = Color.WHITE + fillOval(size / 4, 0, size / 2, size / 2) + fillOval(7 * size / 16, 11 * size / 16, size /8, size / 8) + color = Color.BLACK + fillOval(7 * size / 16, 3 * size / 16, size / 8, size / 8) + + // Use drawOval to draw an empty circle for the outside border + drawOval(0, 0, size - 1, size - 1) + + // Restore the color for the caller + color = colorSave + } + } + + fun createImage(size: Int, bg: Color): Image { + // A BufferedImage creates the image in memory + val image = BufferedImage(size, size, BufferedImage.TYPE_INT_RGB) + + // Get the graphics object for the image + val g = image.graphics + + // Color in the background of the image + g.color = bg + g.fillRect(0, 0, size, size) + drawYinYang(size, g) + return image + } +} + +fun main(args: Array) { + val gen = YinYangGenerator() + val size = 400 // say + val p = JPanel() + val yinYang = gen.createImage(size, p.background) + p.add(JLabel(ImageIcon(yinYang))) + + val size2 = size / 2 // say + val yinYang2 = gen.createImage(size2, p.background) + p.add(JLabel(ImageIcon(yinYang2))) + + val f = JFrame("Big and Small Yin Yang") + with (f) { + defaultCloseOperation = JFrame.EXIT_ON_CLOSE + add(p) + pack() + isVisible = true + } +} diff --git a/Task/Yin-and-yang/Phix/yin-and-yang.phix b/Task/Yin-and-yang/Phix/yin-and-yang.phix new file mode 100644 index 0000000000..4cbf29dc4c --- /dev/null +++ b/Task/Yin-and-yang/Phix/yin-and-yang.phix @@ -0,0 +1,80 @@ +-- +-- demo\rosetta\Yin_and_yang.exw +-- +include pGUI.e + +Ihandle dlg, canvas +cdCanvas cd_canvas + +procedure cdCanvasSecArc(cdCanvas hCdCanvas, atom xc, atom yc, atom w, atom h, atom angle1, atom angle2) +-- cdCanvasSector does not draw anti-aliased edges, but cdCanvasArc does, so over-draw... + cdCanvasSector(hCdCanvas, xc, yc, w, h, angle1, angle2) + cdCanvasArc (hCdCanvas, xc, yc, w, h, angle1, angle2) +end procedure + +procedure yinyang(atom cx, cy, r) + cdCanvasArc(cd_canvas, cx, cy, r, r, 0, 360) + cdCanvasSecArc(cd_canvas, cx, cy, r, r, 270, 90) + cdCanvasSecArc(cd_canvas, cx, cy-r/4, r/2-1, r/2-1, 0, 360) + cdCanvasSetForeground(cd_canvas, CD_WHITE) + cdCanvasSecArc(cd_canvas, cx, cy+r/4, r/2-1, r/2-1, 0, 360) + cdCanvasSecArc(cd_canvas, cx, cy-r/4, r/8, r/8, 0, 360) + cdCanvasSetForeground(cd_canvas, CD_BLACK) + cdCanvasSecArc(cd_canvas, cx, cy+r/4, r/8, r/8, 0, 360) +end procedure + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) +integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") +integer r = min(width,height)-40 +integer cx = floor(width/2) +integer cy = floor(height/2) + cdCanvasActivate(cd_canvas) + cdCanvasClear(cd_canvas) + yinyang(cx-r*.43,cy+r*.43,r/6) + yinyang(cx,cy,r) + cdCanvasFlush(cd_canvas) + return IUP_DEFAULT +end function + +function map_cb(Ihandle ih) + atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 + IupGLMakeCurrent(canvas) + cd_canvas = cdCreateCanvas(CD_GL, "10x10 %g", {res}) + cdCanvasSetBackground(cd_canvas, CD_WHITE) + cdCanvasSetForeground(cd_canvas, CD_BLACK) + return IUP_DEFAULT +end function + +function canvas_resize_cb(Ihandle /*canvas*/) + integer {canvas_width, canvas_height} = IupGetIntInt(canvas, "DRAWSIZE") + atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 + cdCanvasSetAttribute(cd_canvas, "SIZE", "%dx%d %g", {canvas_width, canvas_height, res}) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + + canvas = IupGLCanvas() + IupSetAttribute(canvas, "RASTERSIZE", "340x340") -- initial size + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + IupSetCallback(canvas, "RESIZE_CB", Icallback("canvas_resize_cb")) + + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", "Yin and Yang") + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + + IupMap(dlg) + IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation + IupShowXY(dlg,IUP_CENTER,IUP_CENTER) + IupMainLoop() + IupClose() +end procedure + +main() diff --git a/Task/Yin-and-yang/REXX/yin-and-yang.rexx b/Task/Yin-and-yang/REXX/yin-and-yang.rexx index 0afc9f9c45..c485bc2b30 100644 --- a/Task/Yin-and-yang/REXX/yin-and-yang.rexx +++ b/Task/Yin-and-yang/REXX/yin-and-yang.rexx @@ -1,31 +1,25 @@ -/*REXX program creates and displays an ASCII art version of the Yin-Yang symbol.*/ +/*REXX program creates and displays an ASCII art version of the Yin─Yang symbol.*/ parse arg s1 s2 . /*obtain optional arguments from the CL*/ if s1=='' | s1=="," then s1=17 /*Not defined? Then use the default. */ -if s2=='' | s2=="," then s2= 8 /* " " " " " " */ -if s1>0 then call YinYang s1 /*create and display the 1st Yin-Yang. */ -if s2>0 then call YinYang s2 /* " " " " 2nd " */ +if s2=='' | s2=="," then s2=s1 % 2 /* " " " " " " */ +if s1>0 then call Yin_Yang s1 /*create & display 1st Yin-Yang symbol.*/ +if s2>0 then call Yin_Yang s2 /* " " " 2nd " " */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -in@: procedure; parse arg cy,r,x,y; return x**2 + (y-cy)**2 <= r**2 -big@: /*in big circle.*/ return in@( 0, r, x, y ) -semi@: /*in semi circle.*/ return in@( r/2, r/2, x, y ) -sBK@: /*in small black circle.*/ return in@( r/2, r/6, x, y ) -sWH@: /*in small white circle.*/ return in@( 0-r/2, r/6, x, y ) -BK_semi@: /*in black semi circle.*/ return in@( 0-r/2, r/2, x, y ) +in@: procedure; parse arg cy,r,x,y; return x**2 + (y-cy)**2 <= r**2 +big@: /*in big circle. */ return in@( 0 , r , x, y ) +semi@: /*in semi circle. */ return in@( r/2, r/2, x, y ) +sB@: /*in small black circle. */ return in@( r/2, r/6, x, y ) +sW@: /*in small white circle. */ return in@(-r/2, r/6, x, y ) +Bsemi@: /*in black semi circle. */ return in@(-r/2, r/2, x, y ) /*──────────────────────────────────────────────────────────────────────────────────────*/ -YinYang: procedure; parse arg r; mY=1; mX=2 /*scale multiplier for the X, Y axis.*/ - WH='·'; BL="Θ"; zz=' ' /*define some symbol shading (glyphs). */ - - do sy=+r*mY by -1 while sy >= -r*mY; $= /*$: is the output line.*/ - do sx=-r*mX by +1 while sx <= +r*mX; x=sx/mX; y=sy/mY - if big@() then if semi@() then if sBK@() then $=$||BL - else $=$||WH - else if BK_semi@() then if sWH@() then $=$||WH - else $=$||BL - else if x<0 then $=$||WH - else $=$||BL - else $=$ || zz - end /*sy*/ - say $ /*display a single line of the symbol. */ - end /*sx*/ - return +Yin_Yang: procedure; parse arg r; mY=1; mX=2 /*aspect multiplier for the X,Y axis.*/ + do sy= r*mY to -r*mY by -1; $= /*$ ≡ an output line*/ + do sx=-r*mX to r*mX; x=sx/mX; y=sy/mY /*apply aspect ratio*/ + if big@() then if semi@() then if sB@() then $=$'Θ'; else $=$'°' + else if Bsemi@() then if sW@() then $=$'°'; else $=$'Θ' + else if x<0 then $=$'°'; else $=$'Θ' + else $=$' ' + end /*sy*/ + say strip($, 'T') /*display one line of a Yin─Yang symbol*/ + end /*sx*/; return diff --git a/Task/Yin-and-yang/Scilab/yin-and-yang.scilab b/Task/Yin-and-yang/Scilab/yin-and-yang.scilab new file mode 100644 index 0000000000..71371c50a7 --- /dev/null +++ b/Task/Yin-and-yang/Scilab/yin-and-yang.scilab @@ -0,0 +1,89 @@ +R = 1; //outer radius of first image +scale = 0.5; //scale of the second image + +scf(0); clf(); +set(gca(),'isoview','on'); +xname('Yin and Yang'); + +//First one +n_p = 100; //number of points per arc +angles = []; //angles for each arc +angles = linspace(%pi/2, 3*%pi/2, n_p); +Arcs = zeros(7,n_p); + + Arcs(1,:) = R * exp(%i * angles); + plot2d(real(Arcs(1,:)),imag(Arcs(1,:))); + line = gce(); + set(line.children,'polyline_style',5); + set(line.children,'foreground',8); + + Arcs(2,:) = -%i*R/2 + R/2 * exp(%i * angles); + plot2d(real(Arcs(2,:)),imag(Arcs(2,:))); + line = gce(); + set(line.children,'polyline_style',5); + +angles = []; +angles = linspace(-%pi/2, %pi/2, n_p); + + Arcs(3,:) = R * exp(%i * angles); + plot2d(real(Arcs(3,:)), imag(Arcs(3,:))); + line = gce(); + set(line.children,'polyline_style',5); + + Arcs(4,:) = %i*R/2 + R/2 * exp(%i * angles); + plot2d(real(Arcs(4,:)),imag(Arcs(4,:))); + line = gce(); + set(line.children,'polyline_style',5); + set(line.children,'foreground',8); + +angles = []; +angles = linspace(0, 2*%pi, n_p); + + Arcs(5,:) = %i*R/2 + R/8 * exp(%i * angles); + plot2d(real(Arcs(5,:)),imag(Arcs(5,:))); + line = gce(); + set(line.children,'polyline_style',5); + + Arcs(6,:) = -%i*R/2 + R/8 * exp(%i * angles); + plot2d(real(Arcs(6,:)),imag(Arcs(6,:))); + line = gce(); + set(line.children,'polyline_style',5); + set(line.children,'foreground',8); + + Arcs(7,:) = R * exp(%i * angles); + plot2d(real(Arcs(7,:)),imag(Arcs(7,:))); + set(gca(),'axes_visible',['off','off','off']); + +//Scaling +new_pos = R + 2*R*scale; +Arcs = new_pos + Arcs .* scale; + + plot2d(real(Arcs(1,:)),imag(Arcs(1,:))); + line = gce(); + set(line.children,'polyline_style',5); + set(line.children,'foreground',8); + + plot2d(real(Arcs(2,:)),imag(Arcs(2,:))); + line = gce(); + set(line.children,'polyline_style',5); + + plot2d(real(Arcs(3,:)), imag(Arcs(3,:))); + line = gce(); + set(line.children,'polyline_style',5); + + plot2d(real(Arcs(4,:)),imag(Arcs(4,:))); + line = gce(); + set(line.children,'polyline_style',5); + set(line.children,'foreground',8); + + plot2d(real(Arcs(5,:)),imag(Arcs(5,:))); + line = gce(); + set(line.children,'polyline_style',5); + + plot2d(real(Arcs(6,:)),imag(Arcs(6,:))); + line = gce(); + set(line.children,'polyline_style',5); + set(line.children,'foreground',8); + + plot2d(real(Arcs(7,:)),imag(Arcs(7,:))); + set(gca(),'axes_visible',['off','off','off']); diff --git a/Task/Yin-and-yang/Zkl/yin-and-yang.zkl b/Task/Yin-and-yang/Zkl/yin-and-yang.zkl new file mode 100644 index 0000000000..2edecf41d9 --- /dev/null +++ b/Task/Yin-and-yang/Zkl/yin-and-yang.zkl @@ -0,0 +1,25 @@ +fcn draw_yinyang(trans,scale){ + 0'|| + .fmt(trans,trans,scale).print(); +} + +print( +"\n" +"\n" +"\n" +" \n" +" \n" +" \n" +" \n" +" \n" +" \n"); + +draw_yinyang(20, 0.05); +draw_yinyang( 8, 0.02); +print(""); diff --git a/Task/Zebra-puzzle/00DESCRIPTION b/Task/Zebra-puzzle/00DESCRIPTION index b8719bd8a9..f61e183da1 100644 --- a/Task/Zebra-puzzle/00DESCRIPTION +++ b/Task/Zebra-puzzle/00DESCRIPTION @@ -1,5 +1,3 @@ -[[File:zebra.png|550px||right]] - The [[wp:Zebra puzzle|Zebra puzzle]], a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically.
    It has several variants, one of them this: diff --git a/Task/Zebra-puzzle/00META.yaml b/Task/Zebra-puzzle/00META.yaml index 920313c0b5..54f399b2d1 100644 --- a/Task/Zebra-puzzle/00META.yaml +++ b/Task/Zebra-puzzle/00META.yaml @@ -1,4 +1,5 @@ --- category: - Constraint Handling Rules +- Puzzles note: Puzzles diff --git a/Task/Zebra-puzzle/Haskell/zebra-puzzle-1.hs b/Task/Zebra-puzzle/Haskell/zebra-puzzle-1.hs index 4705c950fc..e957ba84bc 100644 --- a/Task/Zebra-puzzle/Haskell/zebra-puzzle-1.hs +++ b/Task/Zebra-puzzle/Haskell/zebra-puzzle-1.hs @@ -1,10 +1,12 @@ +module Main where + import Control.Applicative ((<$>), (<*>)) import Control.Monad (foldM, forM_) -import Data.List ((\\), isInfixOf) +import Data.List ((\\)) -- types data House = House - { color :: Color + { color :: Color -- :: House -> , man :: Man , pet :: Pet , drink :: Drink @@ -27,51 +29,55 @@ data Drink = Coffee | Tea | Milk | Beer | Water data Smoke = PallMall | Dunhill | Blend | BlueMaster | Prince deriving (Eq, Show, Enum, Bounded) +type Solution = [House] main :: IO () main = do - forM_ solutions $ \x -> mapM_ print (reverse x) - >> putStrLn "----" + forM_ solutions $ \sol -> mapM_ print sol + >> putStrLn "----" putStrLn "No More Solutions" -solutions :: [[House]] -solutions = filter (and . postChecks) $ foldM next [] [1..5] +solutions :: [Solution] +solutions = filter finalCheck . map reverse $ foldM next [] [1..5] where - next xs pos = [x:xs | x <- iterHouse xs, and $ checks pos x] + -- NOTE: list of houses is generated in reversed order + next :: Solution -> Int -> [Solution] + next sol pos = [h:sol | h <- newHouses sol, consistent h pos] -iterHouse :: [House] -> [House] -iterHouse xs = +newHouses :: Solution -> Solution +newHouses sol = -- all combinations of traits not yet used House <$> new color <*> new man <*> new pet <*> new drink <*> new smoke where - new getter = [minBound ..] \\ map getter xs + new trait = [minBound ..] \\ map trait sol -- :: [] --- immediate checks -checks :: Int -> House -> [Bool] -checks pos house = - [ man `is` Eng <=> color `is` Red -- 2 - , man `is` Swe <=> pet `is` Dog -- 3 - , man `is` Dan <=> drink `is` Tea -- 4 - , color `is` Green <=> drink `is` Coffee -- 6 - , pet `is` Birds <=> smoke `is` PallMall -- 7 - , color `is` Yellow <=> smoke `is` Dunhill -- 8 - , const (pos == 3) <=> drink `is` Milk -- 9 - , const (pos == 1) <=> man `is` Nor -- 10 - , drink `is` Beer <=> smoke `is` BlueMaster -- 13 - , man `is` Ger <=> smoke `is` Prince -- 14 +consistent :: House -> Int -> Bool +consistent house pos = and -- consistent with the rules: + [ man `is` Eng <=> color `is` Red -- 2 + , man `is` Swe <=> pet `is` Dog -- 3 + , man `is` Dan <=> drink `is` Tea -- 4 + , color `is` Green <=> drink `is` Coffee -- 6 + , pet `is` Birds <=> smoke `is` PallMall -- 7 + , color `is` Yellow <=> smoke `is` Dunhill -- 8 + , const (pos == 3) <=> drink `is` Milk -- 9 + , const (pos == 1) <=> man `is` Nor -- 10 + , drink `is` Beer <=> smoke `is` BlueMaster -- 13 + , man `is` Ger <=> smoke `is` Prince -- 14 ] where infix 4 <=> - p <=> q = p house == q house -- both True or both False + p <=> q = p house == q house -- both True or both False --- final checks -postChecks :: [House] -> [Bool] -postChecks houses = - -- NOTE: list of houses is generated in reversed order - [ [White, Green] `isInfixOf` map color houses -- 5 +is :: Eq a => (House -> a) -> a -> House -> Bool +(trait `is` value) house = trait house == value + + +finalCheck :: [House] -> Bool +finalCheck solution = and -- fulfills the rules: + [ (color `is` Green) `leftOf` (color `is` White) -- 5 , (smoke `is` Blend ) `nextTo` (pet `is` Cats ) -- 11 , (smoke `is` Dunhill) `nextTo` (pet `is` Horse) -- 12 , (color `is` Blue ) `nextTo` (man `is` Nor ) -- 15 @@ -79,12 +85,7 @@ postChecks houses = ] where nextTo :: (House -> Bool) -> (House -> Bool) -> Bool - nextTo p q - | (_:x:_) <- dropWhile (not . match) houses = match x - | otherwise = False - where - match x = p x || q x - - -is :: Eq a => (House -> a) -> a -> House -> Bool -getter `is` value = (== value) . getter + nextTo p q = leftOf p q || leftOf q p + leftOf p q + | (_:h:_) <- dropWhile (not . p) solution = q h + | otherwise = False diff --git a/Task/Zebra-puzzle/jq/zebra-puzzle-1.jq b/Task/Zebra-puzzle/Jq/zebra-puzzle-1.jq similarity index 100% rename from Task/Zebra-puzzle/jq/zebra-puzzle-1.jq rename to Task/Zebra-puzzle/Jq/zebra-puzzle-1.jq diff --git a/Task/Zebra-puzzle/jq/zebra-puzzle-2.jq b/Task/Zebra-puzzle/Jq/zebra-puzzle-2.jq similarity index 100% rename from Task/Zebra-puzzle/jq/zebra-puzzle-2.jq rename to Task/Zebra-puzzle/Jq/zebra-puzzle-2.jq diff --git a/Task/Zebra-puzzle/jq/zebra-puzzle-3.jq b/Task/Zebra-puzzle/Jq/zebra-puzzle-3.jq similarity index 100% rename from Task/Zebra-puzzle/jq/zebra-puzzle-3.jq rename to Task/Zebra-puzzle/Jq/zebra-puzzle-3.jq diff --git a/Task/Zebra-puzzle/Kotlin/zebra-puzzle.kotlin b/Task/Zebra-puzzle/Kotlin/zebra-puzzle.kotlin new file mode 100644 index 0000000000..e477bab82f --- /dev/null +++ b/Task/Zebra-puzzle/Kotlin/zebra-puzzle.kotlin @@ -0,0 +1,114 @@ +// version 1.1.3 + +fun nextPerm(perm: IntArray): Boolean { + val size = perm.size + var k = -1 + for (i in size - 2 downTo 0) { + if (perm[i] < perm[i + 1]) { + k = i + break + } + } + if (k == -1) return false // last permutation + for (l in size - 1 downTo k) { + if (perm[k] < perm[l]) { + val temp = perm[k] + perm[k] = perm[l] + perm[l] = temp + var m = k + 1 + var n = size - 1 + while (m < n) { + val temp2 = perm[m] + perm[m++] = perm[n] + perm[n--] = temp2 + } + break + } + } + return true +} + +fun check(a1: Int, a2: Int, v1: Int, v2: Int): Boolean { + for (i in 0..4) + if (p[a1][i] == v1) return p[a2][i] == v2 + return false +} + +fun checkLeft(a1: Int, a2: Int, v1: Int, v2: Int): Boolean { + for (i in 0..3) + if (p[a1][i] == v1) return p[a2][i + 1] == v2 + return false +} + +fun checkRight(a1: Int, a2: Int, v1: Int, v2: Int): Boolean { + for (i in 1..4) + if (p[a1][i] == v1) return p[a2][i - 1] == v2 + return false +} + +fun checkAdjacent(a1: Int, a2: Int, v1: Int, v2: Int): Boolean { + return checkLeft(a1, a2, v1, v2) || checkRight(a1, a2, v1, v2) +} + +val colors = listOf("Red", "Green", "White", "Yellow", "Blue") +val nations = listOf("English", "Swede", "Danish", "Norwegian", "German") +val animals = listOf("Dog", "Birds", "Cats", "Horse", "Zebra") +val drinks = listOf("Tea", "Coffee", "Milk", "Beer", "Water") +val smokes = listOf("Pall Mall", "Dunhill", "Blend", "Blue Master", "Prince") + +val p = Array(120) { IntArray(5) { -1 } } // stores all permutations of numbers 0..4 + +fun fillHouses(): Int { + var solutions = 0 + for (c in 0..119) { + if (!checkLeft(c, c, 1, 2)) continue // C5 : Green left of white + for (n in 0..119) { + if (p[n][0] != 3) continue // C10: Norwegian in First + if (!check(n, c, 0, 0)) continue // C2 : English in Red + if (!checkAdjacent(n, c, 3, 4)) continue // C15: Norwegian next to Blue + for (a in 0..119) { + if (!check(a, n, 0, 1)) continue // C3 : Swede has Dog + for (d in 0..119) { + if (p[d][2] != 2) continue // C9 : Middle drinks Milk + if (!check(d, n, 0, 2)) continue // C4 : Dane drinks Tea + if (!check(d, c, 1, 1)) continue // C6 : Green drinks Coffee + for (s in 0..119) { + if (!check(s, a, 0, 1)) continue // C7 : Pall Mall has Birds + if (!check(s, c, 1, 3)) continue // C8 : Yellow smokes Dunhill + if (!check(s, d, 3, 3)) continue // C13: Blue Master drinks Beer + if (!check(s, n, 4, 4)) continue // C14: German smokes Prince + if (!checkAdjacent(s, a, 2, 2)) continue // C11: Blend next to Cats + if (!checkAdjacent(s, a, 1, 3)) continue // C12: Dunhill next to Horse + if (!checkAdjacent(s, d, 2, 4)) continue // C16: Blend next to Water + solutions++ + printHouses(c, n, a, d, s) + } + } + } + } + } + return solutions +} + +fun printHouses(c: Int, n: Int, a: Int, d: Int, s: Int) { + var owner: String = "" + println("House Color Nation Animal Drink Smokes") + println("===== ====== ========= ====== ====== ===========") + for (i in 0..4) { + val f = "%3d %-6s %-9s %-6s %-6s %-11s\n" + System.out.printf(f, i + 1, colors[p[c][i]], nations[p[n][i]], animals[p[a][i]], drinks[p[d][i]], smokes[p[s][i]]) + if (animals[p[a][i]] == "Zebra") owner = nations[p[n][i]] + } + println("\nThe $owner owns the Zebra\n") +} + +fun main(args: Array) { + val perm = IntArray(5) { it } + for (i in 0..119) { + for (j in 0..4) p[i][j] = perm[j] + nextPerm(perm) + } + val solutions = fillHouses() + val plural = if (solutions == 1) "" else "s" + println("$solutions solution$plural found") +} diff --git a/Task/Zebra-puzzle/Prolog/zebra-puzzle-2.pro b/Task/Zebra-puzzle/Prolog/zebra-puzzle-2.pro index 5f891cf12c..7040fc5c1a 100644 --- a/Task/Zebra-puzzle/Prolog/zebra-puzzle-2.pro +++ b/Task/Zebra-puzzle/Prolog/zebra-puzzle-2.pro @@ -1,32 +1,30 @@ -zebra( Z, HS):- - length( HS, 5), - member( H1, HS), nation(H1, eng), color(H1, red), - member( H2, HS), nation(H2, swe), owns( H2, dog), - member( H3, HS), nation(H3, dane), drink(H3, tea), - left_of(A,B, HS), color( A, green), color( B, white), - member( H4, HS), drink( H4, coffee), color(H4, green), - member( H5, HS), smoke( H5, palmal), owns( H5, birds), - member( H6, HS), color( H6, yellow), smoke(H6, dunhill), - middle( C, HS), drink( C, milk), - first( D, HS), nation( D, norweg), - next_to(E,F, HS), smoke( E, blend), owns( F, cats), - next_to(G,H, HS), owns( G, horse), smoke( H, dunhill), - member( H7, HS), smoke( H7, bluemas), drink(H7, beer), - member( H8, HS), nation(H8, german), smoke(H8, prince), - next_to(I,J, HS), nation( I, norweg), color( J, blue), - next_to(V,W, HS), drink( W, water), smoke( V, blend), - member( X, HS), owns( X, zebra), nation(X, Z). +% register unique attribute names from rules +attrs(H,[N-V|R]):- memberchk( N-X, H), X=V, (R=[] -> true ; attrs(H,R)). -left_of( A, B, HS):- append( _, [A,B|_], HS). -next_to( A, B, HS):- left_of( A, B, HS) ; left_of( B, A, HS). -middle( A, [_,_,A,_,_]). -first( A, [A|_]). +in(HS,Attrs) :- member(H,HS), attrs(H,Attrs). +in(HS,G,AttrsL):- call(G,Args,HS), maplist(attrs,Args,AttrsL). -attr( House, Name-Value):- - memberchk( Name-X, House), % unique attribute names - X = Value. % set, validate, or reject -nation(H, V):- attr( H, nation-V). -owns( H, V):- attr( H, owns-V). % select an attribute -smoke( H, V):- attr( H, smoke-V). % from an extensible record -color( H, V):- attr( H, color-V). % of house attributes -drink( H, V):- attr( H, drink-V). % which *is* a house +left_of([A,B],HS):- append(_,[A,B|_],HS). +next_to([A,B],HS):- left_of([A,B],HS) ; left_of([B,A],HS). + +zebra(Owner,Houses):- + Houses = [A,_,C,_,_], % 1 + maplist( in(Houses), [ [ nation-englishman, color-red ] % 2 + , [ nation-swede, owns -dog ] % 3 + , [ nation-dane, drink-tea ] % 4 + , [ drink -coffee, color-green ] % 6 + , [ smoke -'Pall Mall', owns -birds ] % 7 + , [ color -yellow, smoke-'Dunhill' ] % 8 + , [ drink -beer, smoke-'Blue Master'] % 13 + , [ nation-german, smoke-'Prince' ] % 14 + ] ), + in(Houses, left_of, [[color -green ], [color -white ]]), % 5 + maplist( attrs, [C,A], [[drink -milk ], % 9 + [nation-norwegian]]), % 10 + maplist( in(Houses, next_to), + [ [[smoke -'Blend' ], [owns -cats ]] % 11 + , [[owns -horse ], [smoke-'Dunhill' ]] % 12 + , [[nation-norwegian], [color-blue ]] % 15 + , [[drink -water ], [smoke-'Blend' ]] % 16 + ] ), + in(Houses, [owns-zebra, nation-Owner]). diff --git a/Task/Zebra-puzzle/Prolog/zebra-puzzle-3.pro b/Task/Zebra-puzzle/Prolog/zebra-puzzle-3.pro index 3c7db79546..baee4f540f 100644 --- a/Task/Zebra-puzzle/Prolog/zebra-puzzle-3.pro +++ b/Task/Zebra-puzzle/Prolog/zebra-puzzle-3.pro @@ -1,32 +1,12 @@ -attrs( R, [N-V|T]):- % extensible record, attribute specs - memberchk( N-X, R), % unique attribute names - X = V, % set, validate, or reject - ( T = [] -> true ; attrs( R, T) ). +?- time(( zebra(Z,HS), (maplist(length,HS,_) -> maplist(sort,HS,S), + maplist(writeln,S),nl,writeln(Z)), false ; writeln('No More Solutions'))). -specs( P, Hs, [Spec1]) :- call(P, A, Hs), attrs(A, Spec1). -specs( P, Hs, [Spec1, Spec2]) :- call(P, A, B, Hs), attrs(A, Spec1), attrs(B, Spec2). +[color-yellow,drink-water, nation-norwegian, owns-cats, smoke-Dunhill ] +[color-blue, drink-tea, nation-dane, owns-horse, smoke-Blend ] +[color-red, drink-milk, nation-englishman,owns-birds, smoke-Pall Mall ] +[color-green, drink-coffee,nation-german, owns-zebra, smoke-Prince ] +[color-white, drink-beer, nation-swede, owns-dog, smoke-Blue Master] -left_of( A, B, HS):- append( _, [A,B|_], HS). -next_to( A, B, HS):- left_of( A, B, HS) ; left_of( B, A, HS). - -zebra( Zebra, Houses):- % a house *is* a collection of attributes - Houses = [A,_,C,_,_], % 1 - maplist( specs( member, Houses), - [ [[ nation-englishman, color-red ]] % 2 - , [[ nation-swede, owns -dog ]] % 3 - , [[ nation-dane, drink-tea ]] % 4 - , [[ drink -coffee, color-green ]] % 6 - , [[ smoke -'Pall Mall', owns -birds ]] % 7 - , [[ color -yellow, smoke-'Dunhill' ]] % 8 - , [[ drink -beer, smoke-'Blue Master']] % 13 - , [[ nation-german, smoke-'Prince' ]] % 14 - ] ), - specs( left_of, Houses, [[color -green ], [color-white ]]), % 5 - maplist( attrs, [A, C], [[nation-norwegian], [drink-milk ]]), % 10, 9 - maplist( specs( next_to, Houses), - [ [[smoke -'Blend' ], [owns -cats ]] % 11 - , [[owns -horse ], [smoke-'Dunhill' ]] % 12 - , [[nation-norwegian], [color-blue ]] % 15 - , [[drink -water ], [smoke-'Blend' ]] % 16 - ] ), - specs( member, Houses, [[ owns-zebra, nation-Zebra]]). +german +No More Solutions +% 250,927 inferences, 0.027 CPU in 0.027 seconds (100% CPU, 9240311 Lips) diff --git a/Task/Zebra-puzzle/Prolog/zebra-puzzle-4.pro b/Task/Zebra-puzzle/Prolog/zebra-puzzle-4.pro index 8b55242fa7..f2ea4cc460 100644 --- a/Task/Zebra-puzzle/Prolog/zebra-puzzle-4.pro +++ b/Task/Zebra-puzzle/Prolog/zebra-puzzle-4.pro @@ -1,12 +1,45 @@ -?- time(( zebra(Z,HS), ( maplist(length,HS,_) -> maplist(sort,HS,S), - maplist(writeln,S), nl, writeln(Z) ), false ; true)). +:- initialization(main). -[color-yellow,drink-water, nation-norwegian, owns-cats, smoke-Dunhill ] -[color-blue, drink-tea, nation-dane, owns-horse, smoke-Blend ] -[color-red, drink-milk, nation-englishman,owns-birds, smoke-Pall Mall ] -[color-green, drink-coffee,nation-german, owns-zebra, smoke-Prince ] -[color-white, drink-beer, nation-swede, owns-dog, smoke-Blue Master] -german -% 202,730 inferences, 0.031 CPU in 0.031 seconds (100% CPU, 6497715 Lips) -true. +zebra(X) :- + houses(Hs), member(h(_,X,zebra,_,_), Hs) + , findall(_, (member(H,Hs), write(H), nl), _), nl + , write('the one who keeps zebra: '), write(X), nl + . + + +houses(Hs) :- + Hs = [_,_,_,_,_] % 1 + , H3 = h(_,_,_,milk,_), Hs = [_,_,H3,_,_] % 9 + , H1 = h(_,nvg,_,_,_ ), Hs = [H1|_] % 10 + + , maplist( flip(member,Hs), + [ h(red,eng,_,_,_) % 2 + , h(_,swe,dog,_,_) % 3 + , h(_,dan,_,tea,_) % 4 + , h(green,_,_,coffe,_) % 6 + , h(_,_,birds,_,pm) % 7 + , h(yellow,_,_,_,dh) % 8 + , h(_,_,_,beer,bm) % 13 + , h(_,ger,_,_,pri) % 14 + ]) + + , infix([ h(green,_,_,_,_) + , h(white,_,_,_,_) ], Hs) % 5 + + , maplist( flip(nextto,Hs), + [ [h(_,_,_,_,bl ), h(_,_,cats,_,_)] % 11 + , [h(_,_,horse,_,_), h(_,_,_,_,dh )] % 12 + , [h(_,nvg,_,_,_ ), h(blue,_,_,_,_)] % 15 + , [h(_,_,_,water,_), h(_,_,_,_,bl )] % 16 + ]) + . + + +flip(F,X,Y) :- call(F,Y,X). + +infix(Xs,Ys) :- append(Xs,_,Zs) , append(_,Zs,Ys). +nextto(P,Xs) :- permutation(P,R), infix(R,Xs). + + +main :- findall(_, (zebra(_), nl), _), halt. diff --git a/Task/Zebra-puzzle/Prolog/zebra-puzzle-5.pro b/Task/Zebra-puzzle/Prolog/zebra-puzzle-5.pro deleted file mode 100644 index f2ea4cc460..0000000000 --- a/Task/Zebra-puzzle/Prolog/zebra-puzzle-5.pro +++ /dev/null @@ -1,45 +0,0 @@ -:- initialization(main). - - -zebra(X) :- - houses(Hs), member(h(_,X,zebra,_,_), Hs) - , findall(_, (member(H,Hs), write(H), nl), _), nl - , write('the one who keeps zebra: '), write(X), nl - . - - -houses(Hs) :- - Hs = [_,_,_,_,_] % 1 - , H3 = h(_,_,_,milk,_), Hs = [_,_,H3,_,_] % 9 - , H1 = h(_,nvg,_,_,_ ), Hs = [H1|_] % 10 - - , maplist( flip(member,Hs), - [ h(red,eng,_,_,_) % 2 - , h(_,swe,dog,_,_) % 3 - , h(_,dan,_,tea,_) % 4 - , h(green,_,_,coffe,_) % 6 - , h(_,_,birds,_,pm) % 7 - , h(yellow,_,_,_,dh) % 8 - , h(_,_,_,beer,bm) % 13 - , h(_,ger,_,_,pri) % 14 - ]) - - , infix([ h(green,_,_,_,_) - , h(white,_,_,_,_) ], Hs) % 5 - - , maplist( flip(nextto,Hs), - [ [h(_,_,_,_,bl ), h(_,_,cats,_,_)] % 11 - , [h(_,_,horse,_,_), h(_,_,_,_,dh )] % 12 - , [h(_,nvg,_,_,_ ), h(blue,_,_,_,_)] % 15 - , [h(_,_,_,water,_), h(_,_,_,_,bl )] % 16 - ]) - . - - -flip(F,X,Y) :- call(F,Y,X). - -infix(Xs,Ys) :- append(Xs,_,Zs) , append(_,Zs,Ys). -nextto(P,Xs) :- permutation(P,R), infix(R,Xs). - - -main :- findall(_, (zebra(_), nl), _), halt. diff --git a/Task/Zebra-puzzle/Scala/zebra-puzzle-2.scala b/Task/Zebra-puzzle/Scala/zebra-puzzle-2.scala index f7141da1a1..9118407dbb 100644 --- a/Task/Zebra-puzzle/Scala/zebra-puzzle-2.scala +++ b/Task/Zebra-puzzle/Scala/zebra-puzzle-2.scala @@ -67,7 +67,7 @@ object Einstein extends App { // There *should* be just one solution... solutions.foreach { solution => - // so we can pretty-print, find out the maximum strength length of all cells + // so we can pretty-print, find out the maximum string length of all cells val maxLen = solution.flatten.map(_.length).max def pretty(str: String): String = str + (" " * (maxLen - str.length + 1)) diff --git a/Task/Zebra-puzzle/Sidef/zebra-puzzle.sidef b/Task/Zebra-puzzle/Sidef/zebra-puzzle.sidef index adf87ef48f..286e5ad3a7 100644 --- a/Task/Zebra-puzzle/Sidef/zebra-puzzle.sidef +++ b/Task/Zebra-puzzle/Sidef/zebra-puzzle.sidef @@ -20,19 +20,19 @@ func coincident(n,i,g,e) { } func solve { - CONTENT{:Nationality}.permutations{|nation| + CONTENT{:Nationality}.permutations{|*nation| nation.first == :Norwegian -> - && CONTENT{:Colour}.permutations {|colour| + && CONTENT{:Colour}.permutations {|*colour| leftof(colour,:Green,colour,:White) -> && coincident(nation,:English,colour,:Red) -> && adjacent(nation,:Norwegian,colour,:Blue) -> - && CONTENT{:Pet}.permutations {|pet| + && CONTENT{:Pet}.permutations {|*pet| coincident(nation,:Swedish,pet,:Dog) -> - && CONTENT{:Drink}.permutations {|drink| + && CONTENT{:Drink}.permutations {|*drink| drink[2] == :Milk -> && coincident(nation,:Danish,drink,:Tea) -> && coincident(colour,:Green,drink,:Coffee) -> - && CONTENT{:Smoke}.permutations {|smoke| + && CONTENT{:Smoke}.permutations {|*smoke| coincident(smoke,:PallMall,pet,:Birds) -> && coincident(smoke,:Dunhill,colour,:Yellow) -> && coincident(smoke,:BlueMaster,drink,:Beer) -> diff --git a/Task/Zebra-puzzle/Zkl/zebra-puzzle.zkl b/Task/Zebra-puzzle/Zkl/zebra-puzzle.zkl new file mode 100644 index 0000000000..4ce4e00ff3 --- /dev/null +++ b/Task/Zebra-puzzle/Zkl/zebra-puzzle.zkl @@ -0,0 +1,61 @@ +var people,drinks,houses,smokes,pets; // lists treated as associated arrays +fcn c2 { people.find(English)==houses.find(Red) } +fcn c3 { people.find(Swede)==pets.find(Dog) } +fcn c4 { people.find(Dane)==drinks.find(Tea) } +fcn c5 { (houses.find(Green) + 1)==houses.find(White) } +fcn c5a{ houses.find(Green)!=4 } // deduced constraint (from c5) +fcn c5b{ houses.find(White)!=0 } // deduced constraint (from c5) +fcn c6 { drinks.find(Coffee)==houses.find(Green) } +fcn c7 { smokes.find(PallMall)==pets.find(Bird) } +fcn c8 { houses.find(Yellow)==smokes.find(Dunhill) } +fcn c9 { drinks[2]==Milk } // 0,1,2,3,4 +fcn c10{ people[0]==Norwegian } +fcn c11{ (smokes.find(Blend) - pets.find(Cat)).abs()==1 } +fcn c12{ (pets.find(Horse) - smokes.find(Dunhill)).abs()==1 } +fcn c13{ smokes.find(BlueMaster)==drinks.find(Beer) } +fcn c14{ people.find(German)==smokes.find(Prince) } +fcn c15{ (people.find(Norwegian) - houses.find(Blue)).abs()==1 } +fcn c16{ (drinks.find(Water) - smokes.find(Blend)).abs()==1 } +#<<<#////////////////////////////////////////////////////////////////////// +Showing a solution to c2,c5,c10,c15: + |0 1 2 3 4 +--------+------------------------------------------- +houses: |Yellow Blue Red Green White +people: |Norwegian Dane English German Swede +#<<<#////////////////////////////////////////////////////////////////////// + +const Blue =0,Green =1,Red =2,White =3,Yellow=4, + Dane =0,English =1,German =2,Norwegian=3,Swede =4, + Beer =0,Coffee =1,Milk =2,Tea =3,Water =4, + Blend=0,BlueMaster=1,Dunhill=2,PallMall =3,Prince=4, + Bird =0,Cat =1,Dog =2,Horse =3,Zebra =4; +perm5:=T(0,1,2,3,4) : Utils.Helpers.permute(_); // 120 sets + +constraints:=T(c2,c3,c4,c5,c5a,c5b,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16); +constraints1:=T(c2,c5,c10,c15); // houses,people: 12 solutions +constraints2:=T(c4,c6,c9); // houses,people,drinks: down to 8 solutions +foreach _houses,_people in (perm5,perm5){ houses,people=_houses,_people; + if(not constraints1.runNFilter(False)){ // all constraints are True + foreach _drinks in (perm5){ drinks=_drinks; + if(not constraints2.runNFilter(False)){ + foreach _smokes,_pets in (perm5,perm5){ smokes,pets=_smokes,_pets; + if(not constraints.runNFilter(False)) printSolution(); + }// smokes,pets + } + } // drinks + } // houses,people +} +fcn printSolution{ + var titles=T("Houses:","People:","Drinks:","Smokes:","Pets:"), + names=T( + T("Blue", "Green", "Red", "White", "Yellow",), + T("Dane", "English", "German", "Norwegian","Swede",), + T("Beer", "Coffee", "Milk", "Tea", "Water",), + T("Blend","Blue Master","Dunhill","Pall Mall","Prince",), + T("Bird", "Cat", "Dog", "Horse", "Zebra",) ), + ; + fmt:=("%-7s " + "%-11s "*5).fmt; + foreach list,title,names in (T(houses,people,drinks,smokes,pets) + .zip(titles,names)) + { println(list.apply(names.get):fmt(title,_.xplode())) } +} diff --git a/Task/Zeckendorf-arithmetic/Elena/zeckendorf-arithmetic.elena b/Task/Zeckendorf-arithmetic/Elena/zeckendorf-arithmetic.elena new file mode 100644 index 0000000000..955a468c25 --- /dev/null +++ b/Task/Zeckendorf-arithmetic/Elena/zeckendorf-arithmetic.elena @@ -0,0 +1,239 @@ +import extensions. + +const dig = ("00","01","10"). +const dig1 = ("","1","10"). + +sealed struct ZeckendorfNumber :: BaseNumber +{ + int dVal. + int dLen. + + clone + = ZeckendorfNumber $new(dVal,dLen). + + stacksafe explicit n(LiteralValue s) + [ + int i := s length - 1. + int q := 1. + + dLen := i / 2. + dVal := 0. + + while (i >= 0) + [ + dVal += ((intConvertor convert(s[i]) - 48) * q). + q *= 2. + + i -= 1. + ]. + ] + + stacksafe $readContent vint:val vint:len + [ + val int := dVal. + len int := dLen. + ] + + sealed $a(IntNumber n) + [ + int i := n. + + while (true) + [ + if (dLen < i) + [ + dLen := i. + ]. + + ((dVal >> (i * 2)) && 3) => + 0 [ ^ $self ]; + 1 [ ^ $self ]; + 2 [ + ifnot ((dVal >> ((i + 1) * 2)) allMask:1) + [ + ^ $self. + ]. + + dVal += (1 << (i*2 + 1)). + ^ $self. + ]; + 3 [ + dVal := dVal && ((3 << i*2) inverted). + + $self $b((i+1)*2). + ]. + + i += 1. + ]. + ] + + inc + [ + dVal += 1. + $self $a(0). + ] + + $b(IntNumber pos) + [ + if (pos == 0) [ ^ $self inc ]. + + ifnot((dVal >> pos) allMask:1) + [ + dVal += (1 << pos). + $self $a(pos / 2). + if (pos > 1) [ $self $a((pos / 2) - 1) ] + ]; + [ + dVal := dVal && (1 << pos) inverted. + $self $b(pos + 1). + $self $b(pos - (pos > 1) iif(2,1)). + ]. + ] + + $c(IntNumber pos) + [ + if ((dVal >> pos) allMask:1) + [ + dVal := dVal && (1 << pos) inverted. + + ^ $self + ]. + + $self $c(pos + 1). + + if (pos > 0) + [ + $self $b(pos - 1). + ]; + [ + $self inc. + ] + ] + + constructor $sum(ZeckendorfNumber n, ZeckendorfNumber m) + [ + int mVal := 0. + int mLen := 0. + + n $readContent vint:dVal vint:dLen. + m $readContent vint:mVal vint:mLen. + + 0 till((mLen + 1) * 2) do(:GN) + [ + if (mVal shiftRight:GN; allMask:1) + [ + $self $b(GN). + ]. + ]. + ] + + constructor $difference(ZeckendorfNumber n, ZeckendorfNumber m) + [ + int mVal := 0. + int mLen := 0. + + n $readContent vint:dVal vint:dLen. + m $readContent vint:mVal vint:mLen. + + 0 till((mLen + 1) * 2) do(:GN) + [ + if (mVal shiftRight:GN; allMask:1) + [ + $self $c(GN). + ]. + ]. + + while ((((dVal >> (dLen*2)) && 3) == 0) || (dLen == 0)) + [ + dLen -= 1. + ]. + ] + + constructor $product(ZeckendorfNumber n, ZeckendorfNumber m) + [ + n $readContent vint:dVal vint:dLen. + + var Na := m. + var Nb := m. + var Nr := 0n. + var Nt := 0n. + + 0 to((dLen + 1) * 2) do(:i) + [ + if (((dVal shiftRight:i) && 1) > 0) + [ + Nr += Nb + ]. + Nt := Nb. + Nb += Na. + Na := Nt. + ]. + + Nr $readContent vint:dVal vint:dLen. + ] + + constructor $new(IntNumber v, IntNumber l) + [ + dVal := v. + dLen := l. + ] + + literal + [ + if (dVal == 0) + [ ^ "0". ]. + + literal s := dig1[(dVal >> (dLen * 2)) && 3]. + int i := dLen - 1. + while (i >= 0) + [ + s := s + dig[(dVal >> (i * 2)) && 3]. + + i-=1 + ]. + + ^ s. + ] + + add(ZeckendorfNumber n) + = ZeckendorfNumber $sum($self, n). + + subtract(ZeckendorfNumber n) + = ZeckendorfNumber $difference($self, n). + + multiply(ZeckendorfNumber n) + = ZeckendorfNumber $product($self, n). +} + +program = +[ + console printLine("Addition:"). + var n := 10n. + + n += 10n. + console printLine(n). + n += 10n. + console printLine(n). + n += 1001n. + console printLine(n). + n += 1000n. + console printLine(n). + n += 10101n. + console printLine(n). + + console printLine("Subtraction:"). + n := 1000n. + n -= 101n. + console printLine(n). + n := 10101010n. + n -= 1010101n. + console printLine(n). + + console printLine("Multiplication:"). + n := 1001n. + n *= 101n. + console printLine(n). + n := 101010n. + n += 101n. + console printLine(n). +]. diff --git a/Task/Zeckendorf-number-representation/360-Assembly/zeckendorf-number-representation.360 b/Task/Zeckendorf-number-representation/360-Assembly/zeckendorf-number-representation.360 new file mode 100644 index 0000000000..a31f51078f --- /dev/null +++ b/Task/Zeckendorf-number-representation/360-Assembly/zeckendorf-number-representation.360 @@ -0,0 +1,67 @@ +* Zeckendorf number representation 04/04/2017 +ZECKEN CSECT + USING ZECKEN,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + LA R6,0 i=0 + DO WHILE=(C,R6,LE,=A(20)) do i=0 to 20 + MVC PG,=CL80'xx : ' init buffer + LA R10,PG pgi=0 + XDECO R6,XDEC i + MVC 0(2,R10),XDEC+10 output i + LA R10,5(R10) pgi+=5 + MVC FIB,=A(1) fib(1)=1 + MVC FIB+4,=A(2) fib(2)=2 + LA R7,2 j=2 + LR R1,R7 j + SLA R1,2 @fib(j) + DO WHILE=(C,R6,GT,FIB-4(R1) do while fib(j) Bool) -> (a -> a) -> a -> a on |until|(p, f, x) set mp to mReturn(p) - set mf to mReturn(f) + set v to x - script - property p : mp's lambda - property f : mf's lambda - - on lambda(v) - repeat until p(v) - set v to f(v) - end repeat - return v - end lambda - end script - - result's lambda(x) + tell mReturn(f) + repeat until mp's lambda(v) + set v to lambda(v) + end repeat + end tell + return v end |until| -- map :: (a -> b) -> [a] -> [b] diff --git a/Task/Zeckendorf-number-representation/Elena/zeckendorf-number-representation.elena b/Task/Zeckendorf-number-representation/Elena/zeckendorf-number-representation.elena new file mode 100644 index 0000000000..6d7c44ceae --- /dev/null +++ b/Task/Zeckendorf-number-representation/Elena/zeckendorf-number-representation.elena @@ -0,0 +1,64 @@ +import system'routines. +import system'collections. +import system'text. +import extensions. + +extension op +{ + fibonacci + [ + if (self < 2) + [ + ^ self + ]; + [ + ^ (self - 1) fibonacci + (self - 2) fibonacci. + ]. + ] + + zeckendorf + [ + var fibonacciNumbers := list(10). + + int num := self. + int fibPosition := 2. + int currentFibonaciNum := fibPosition fibonacci. + + while (currentFibonaciNum <= num) + [ + fibonacciNumbers append:currentFibonaciNum. + + fibPosition := fibPosition + 1. + currentFibonaciNum := fibPosition fibonacci. + ]. + + textbuffer output := TextBuilder new. + int temp := num. + + fibonacciNumbers sequenceReverse; forEach(:item) + [ + if (item <= temp) + [ + output << "1". + temp := temp - item. + ]; + [ + output << "0". + ]. + ]. + + ^ output literal. + ] +} + +program = +[ + 1 to:20 do(:i) + [ + var zeckendorfRepresentation := i zeckendorf. + + console printFormatted("{0} : {1}",i,i zeckendorf); writeLine. + ]. + + console readChar. +]. diff --git a/Task/Zeckendorf-number-representation/Fortran/zeckendorf-number-representation-1.f b/Task/Zeckendorf-number-representation/Fortran/zeckendorf-number-representation-1.f new file mode 100644 index 0000000000..cc478ba96f --- /dev/null +++ b/Task/Zeckendorf-number-representation/Fortran/zeckendorf-number-representation-1.f @@ -0,0 +1 @@ +F(N) = ((1 + SQRT(5))**N - (1 - SQRT(5))**N)/(SQRT(5)*2**N) diff --git a/Task/Zeckendorf-number-representation/Fortran/zeckendorf-number-representation-2.f b/Task/Zeckendorf-number-representation/Fortran/zeckendorf-number-representation-2.f new file mode 100644 index 0000000000..03b690afd2 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Fortran/zeckendorf-number-representation-2.f @@ -0,0 +1,86 @@ + MODULE ZECKENDORF ARITHMETIC !Using the Fibonacci series, rather than powers of some base. + INTEGER ZLAST !The standard 32-bit two's complement integers + PARAMETER (ZLAST = 45) !only get so far, just as there's a limit to the highest power. + INTEGER F1B(ZLAST) !I want the Fibonacci series, and, starting with its second one. +c PARAMETER (F1B = (/1,2, !But alas, the compiler doesn't allow +c 3 F1B(1) + F1B(2), !for this sort of carpet-unrolling +c 4 F1B(2) + F1B(3), !initialisation sequence. + INTEGER,PRIVATE:: F01,F02,F03,F04,F05,F06,F07,F08,F09,F10, !So, not bothering with F00, + 1 F11,F12,F13,F14,F15,F16,F17,F18,F19,F20, !Prepare a horde of simple names, + 2 F21,F22,F23,F24,F25,F26,F27,F28,F29,F30, !which can be initialised + 3 F31,F32,F33,F34,F35,F36,F37,F38,F39,F40, !in a certain way, + 4 F41,F42,F43,F44,F45 !without scaring the compiler. + PARAMETER (F01 = 1, F02 = 2, F03 = F02 + F01, F04 = F03 + F02, !Thusly. + 1 F05=F04+F03,F06=F05+F04,F07=F06+F05,F08=F07+F06,F09=F08+F07, !Typing all this + 2 F10=F09+F08,F11=F10+F09,F12=F11+F10,F13=F12+F11,F14=F13+F12, !is an invitation + 3 F15=F14+F13,F16=F15+F14,F17=F16+F15,F18=F17+F16,F19=F18+F17, !for mistypes. + 4 F20=F19+F18,F21=F20+F19,F22=F21+F20,F23=F22+F21,F24=F23+F22, !So a regular layout + 5 F25=F24+F23,F26=F25+F24,F27=F26+F25,F28=F27+F26,F29=F28+F27, !helps a little. + 6 F30=F29+F28,F31=F30+F29,F32=F31+F30,F33=F32+F31,F34=F33+F32, !Otherwise, + 7 F35=F34+F33,F36=F35+F34,F37=F36+F35,F38=F37+F36,F39=F38+F37, !devise a prog. + 8 F40=F39+F38,F41=F40+F39,F42=F41+F40,F43=F42+F41,F44=F43+F42, !to generate these texts... + 9 F45=F44+F43) !The next is 2971215073. Too big for 32-bit two's complement integers. + PARAMETER (F1B = (/F01,F02,F03,F04,F05,F06,F07,F08,F09,F10, !And now, + 1 F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, !Here is the desired + 2 F21, F22, F23, F24, F25, F26, F27, F28, F29, F30, !array of constants. + 3 F31, F32, F33, F34, F35, F36, F37, F38, F39, F40, !And as such, possibly + 4 F41, F42, F43, F44, F45/)) !protected from alteration. + CONTAINS !After all that, here we go. + SUBROUTINE ZECK(N,D) !Convert N to a "Zeckendorf" digit sequence. +Counts upwards from digit one. D(i) ~ F1B(i). D(0) fingers the high-order digit. + INTEGER N !The normal number, in the computer's base. + INTEGER D(0:) !The digits, to be determined. + INTEGER R !The remnant. + INTEGER L !A finger, similar to the power of the base. + IF (N.LT.0) STOP "ZECK! No negative numbers!" !I'm not thinking about them. + R = N !Grab a copy that I can mess with. + D = 0 !Scrub the lot in one go. + L = ZLAST !As if starting with BASE**MAX, rather than BASE**0. + 10 IF (R.GE.F1B(L)) THEN !Has the remnant sufficient for this digit? + R = R - F1B(L) !Yes! Remove that amount. + IF (D(0).EQ.0) THEN !Is this the first non-zero digit? + IF (L.GT.UBOUND(D,DIM=1)) STOP "ZECK! Not enough digits!" !Yes. + D(0) = L !Remember the location of the high-order digit. + END IF !Two loops instead, to avoid repeated testing? + D(L) = 1 !Place the digit, knowing a place awaits. + L = L - 1 !Never need a ...11... sequence because F1B(i) + F1B(i+1) = F1B(i+2). + END IF !So much for that digit "power". + L = L - 1 !Down a digit. + IF (L.GT.0 .AND. R.GT.0) GO TO 10 !Are we there yet? + IF (N.EQ.0) D(0) = 1 !Zero has one digit. + END SUBROUTINE ZECK !That was fun. + + INTEGER FUNCTION ZECKN(D) !Converts a "Zeckendorf" digit sequence to a number. + INTEGER D(0:) !The digits. D(0) fingers the high-order digit. + IF (D(0).LE.0) STOP "ZECKN! Empty number!" !General paranoia. + IF (D(0).GT.ZLAST) STOP "ZECKN! Oversize number!" !I hate array bound hiccoughs. + ZECKN = SUM(D(1:D(0))*F1B(1:D(0))) !This is what positional notation means. + IF (ZECKN.LT.0) STOP "ZECKN! Integer overflow!" !Oh for IF OVERFLOW as in First Fortran. + END FUNCTION ZECKN !Overflows by a small amount will produce a negative number. + END MODULE ZECKENDORF ARITHMETIC !Odd stuff. + + PROGRAM POKE + USE ZECKENDORF ARITHMETIC !Please. + INTEGER ZD(0:ZLAST) !A scratchpad. + INTEGER I,J,W + CHARACTER*1 DIGIT(0:1) !Assistance for the output. + PARAMETER (DIGIT = (/"0","1"/), W = 6) !This field width suffices. +c WRITE (6,*) F1B +c WRITE (6,*) INT8(F1B(44)) + INT8(F1B(45)) + WRITE (6,1) F1B(1:4),ZLAST,ZLAST,F1B(ZLAST),HUGE(I) !Show some provenance. + 1 FORMAT ("Converts integers to their Zeckendorf digit string " + 1 "using the Fib1nacci sequence (",4(I0,","), + 2 " ...) as the equivalent of powers."/ + 3 "At most, ",I0," digits because Fib1nacci(",I0,") = ",I0, + 4 " and the integer limit is ",I0,".",//," N ZN") !Ends with a heading. + + DO I = 0,20 !Step through the specified range. + CALL ZECK(I,ZD) !Convert I to ZD. +c WRITE (6,2) I,ZD(ZD(0):1:-1) !Show digits from high-order to low. +c 2 FORMAT (I3,1X,66I1) !Or, WRITE (6,2) I,(ZD(J), J = ZD(0),1,-1) + WRITE (6,3) I,(" ",J = ZD(0) + 1,W),DIGIT(ZD(ZD(0):1:-1)) !Right-aligned in field width W. + 3 FORMAT (I3,1X,66A1) !The digits appear as characters. + IF (I.NE.ZECKN(ZD)) STOP "Huh?" !Should never happen... + END DO !On to the next. + + END diff --git a/Task/Zeckendorf-number-representation/jq/zeckendorf-number-representation-1.jq b/Task/Zeckendorf-number-representation/Jq/zeckendorf-number-representation-1.jq similarity index 100% rename from Task/Zeckendorf-number-representation/jq/zeckendorf-number-representation-1.jq rename to Task/Zeckendorf-number-representation/Jq/zeckendorf-number-representation-1.jq diff --git a/Task/Zeckendorf-number-representation/jq/zeckendorf-number-representation-2.jq b/Task/Zeckendorf-number-representation/Jq/zeckendorf-number-representation-2.jq similarity index 100% rename from Task/Zeckendorf-number-representation/jq/zeckendorf-number-representation-2.jq rename to Task/Zeckendorf-number-representation/Jq/zeckendorf-number-representation-2.jq diff --git a/Task/Zeckendorf-number-representation/jq/zeckendorf-number-representation-3.jq b/Task/Zeckendorf-number-representation/Jq/zeckendorf-number-representation-3.jq similarity index 100% rename from Task/Zeckendorf-number-representation/jq/zeckendorf-number-representation-3.jq rename to Task/Zeckendorf-number-representation/Jq/zeckendorf-number-representation-3.jq diff --git a/Task/Zeckendorf-number-representation/Kotlin/zeckendorf-number-representation.kotlin b/Task/Zeckendorf-number-representation/Kotlin/zeckendorf-number-representation.kotlin new file mode 100644 index 0000000000..bde3cb690d --- /dev/null +++ b/Task/Zeckendorf-number-representation/Kotlin/zeckendorf-number-representation.kotlin @@ -0,0 +1,39 @@ +// version 1.0.6 + +const val LIMIT = 46 // to stay within range of signed 32 bit integer +val fibs = fibonacci(LIMIT) + +fun fibonacci(n: Int): IntArray { + if (n !in 2..LIMIT) throw IllegalArgumentException("n must be between 2 and $LIMIT") + val fibs = IntArray(n) + fibs[0] = 1 + fibs[1] = 1 + for (i in 2 until n) fibs[i] = fibs[i - 1] + fibs[i - 2] + return fibs +} + +fun zeckendorf(n: Int): String { + if (n < 0) throw IllegalArgumentException("n must be non-negative") + if (n < 2) return n.toString() + var lastFibIndex = 1 + for (i in 2..LIMIT) + if (fibs[i] > n) { + lastFibIndex = i - 1 + break + } + var nn = n - fibs[lastFibIndex--] + val zr = StringBuilder("1") + for (i in lastFibIndex downTo 1) + if (fibs[i] <= nn) { + zr.append('1') + nn -= fibs[i] + } else { + zr.append('0') + } + return zr.toString() +} + +fun main(args: Array) { + println(" n z") + for (i in 0..20) println("${"%2d".format(i)} : ${zeckendorf(i)}") +} diff --git a/Task/Zeckendorf-number-representation/Phix/zeckendorf-number-representation.phix b/Task/Zeckendorf-number-representation/Phix/zeckendorf-number-representation.phix new file mode 100644 index 0000000000..ed6affb3c5 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Phix/zeckendorf-number-representation.phix @@ -0,0 +1,17 @@ +function zeckendorf(integer n) +integer r = 0, c +sequence fib = {1,1} + while fib[$]=fib[i] + r += r+c + n -= c*fib[i] + end for + return r +end function + +for i=0 to 20 do + printf(1,"%2d: %7b\n",{i,zeckendorf(i)}) +end for diff --git a/Task/Zeckendorf-number-representation/PlainTeX/zeckendorf-number-representation.tex b/Task/Zeckendorf-number-representation/PlainTeX/zeckendorf-number-representation.tex new file mode 100644 index 0000000000..af573d99fe --- /dev/null +++ b/Task/Zeckendorf-number-representation/PlainTeX/zeckendorf-number-representation.tex @@ -0,0 +1,37 @@ +\def\genfibolist#1{% #creates the fibo list which sum>=#1 + \let\fibolist\empty\def\targetsum{#1}\def\fibosum{0}% + \genfibolistaux1,1\relax +} +\def\genfibolistaux#1,#2\relax{% + \ifnum\fibosum<\targetsum\relax + \edef\fibosum{\number\numexpr\fibosum+#2}% + \edef\fibolist{#2,\fibolist}% + \edef\tempfibo{\noexpand\genfibolistaux#2,\number\numexpr#1+#2\relax\relax}% + \expandafter\tempfibo + \fi +} +\def\zeckendorf#1{\expandafter\zeckendorfaux\fibolist,\relax#1\relax\relax0} +\def\zeckendorfaux#1,#2\relax#3\relax#4\relax#5{% + \ifx\relax#2\relax + #4% + \else + \ifnum#3<#1 + \edef\temp{#2\relax#3\relax#4\ifnum#5=1 0\fi\relax#5}% + \else + \edef\temp{#2\relax\number\numexpr#3-#1\relax\relax#41\relax1}% + \fi + \expandafter\expandafter\expandafter\zeckendorfaux\expandafter\temp + \fi +} +\newcount\ii +\def\listzeckendorf#1{% + \genfibolist{#1}% + \ii=0 + \loop + \ifnum\ii<#1 + \advance\ii1 + \number\ii: \zeckendorf\ii\endgraf + \repeat +} +\listzeckendorf{20}% any integer accepted +\bye diff --git a/Task/Zeckendorf-number-representation/PureBasic/zeckendorf-number-representation.purebasic b/Task/Zeckendorf-number-representation/PureBasic/zeckendorf-number-representation.purebasic new file mode 100644 index 0000000000..fb02e0007c --- /dev/null +++ b/Task/Zeckendorf-number-representation/PureBasic/zeckendorf-number-representation.purebasic @@ -0,0 +1,26 @@ +Procedure.s zeck(n.i) + Dim f.i(1) : Define i.i=1, o$ + f(0)=1 : f(1)=1 + While f(i)=f(i) : o$+"1" : n-f(i) : Else : o$+"0" : EndIf + Next + If Len(o$)>1 : o$=LTrim(o$,"0") : EndIf + ProcedureReturn o$ +EndProcedure + +Define n.i, t$ +OpenConsole("Zeckendorf number representation") +PrintN(~"\tNr.\tZeckendorf") +For n=0 To 20 + t$=zeck(n) + If FindString(t$,"11") + PrintN("Error: n= "+Str(n)+~"\tZeckendorf= "+t$) + Break + Else + PrintN(~"\t"+RSet(Str(n),3," ")+~"\t"+RSet(t$,7," ")) + EndIf +Next +Input() diff --git a/Task/Zeckendorf-number-representation/Sidef/zeckendorf-number-representation.sidef b/Task/Zeckendorf-number-representation/Sidef/zeckendorf-number-representation.sidef index 1b7d32ec2f..8945d907d1 100644 --- a/Task/Zeckendorf-number-representation/Sidef/zeckendorf-number-representation.sidef +++ b/Task/Zeckendorf-number-representation/Sidef/zeckendorf-number-representation.sidef @@ -1,21 +1,21 @@ func fib(n) is cached { - n < 2 ? 1 - : (fib(n-1) + fib(n-2)); + n < 2 ? 1 +  : (fib(n-1) + fib(n-2)) } func zeckendorf(n) { - n == 0 && return '0'; - var i = 1; - ++i while (fib(i) <= n); + n == 0 && return '0' + var i = 1 + ++i while (fib(i) <= n) gather { while (--i > 0) { - var f = fib(i); - f > n ? (take '0') - : (take '1'; n -= f); + var f = fib(i) + f > n ? (take '0') +  : (take '1'; n -= f) } - }.join(''); + }.join } -range(0, 20).each { |n| - printf("%4d: %8s\n", n, zeckendorf(n)) +for n (0..20) { + printf("%4d: %8s\n", n, zeckendorf(n)) } diff --git a/Task/Zeckendorf-number-representation/Sinclair-ZX81-BASIC/zeckendorf-number-representation.sinclair b/Task/Zeckendorf-number-representation/Sinclair-ZX81-BASIC/zeckendorf-number-representation.sinclair new file mode 100644 index 0000000000..015cec89f1 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Sinclair-ZX81-BASIC/zeckendorf-number-representation.sinclair @@ -0,0 +1,23 @@ + 10 DIM F(6) + 20 LET F(1)=1 + 30 LET F(2)=2 + 40 FOR I=3 TO 6 + 50 LET F(I)=F(I-2)+F(I-1) + 60 NEXT I + 70 FOR I=0 TO 20 + 80 LET Z$="" + 90 LET S$=" " +100 LET Z=I +110 FOR J=6 TO 1 STEP -1 +120 IF J=1 THEN LET S$="0" +130 IF ZString of 1s & 0s, no consecutive 1's + if(n<=0) return("0"); + fibs:=fcn(ab){ ab.append(ab.sum()).pop(0) }.fp(L(1,2)); + (0).pump(*,List,fibs,'wrap(fib){ if(fib>n)Void.Stop else fib }) + .reverse() + .pump(String,fcn(fib,rn){ + if(fib>rn.value)"0" else { rn.set(rn.value-fib); "1" } }.fp1(Ref(n))) +} diff --git a/Task/Zeckendorf-number-representation/Zkl/zeckendorf-number-representation-2.zkl b/Task/Zeckendorf-number-representation/Zkl/zeckendorf-number-representation-2.zkl new file mode 100644 index 0000000000..0f80810f2a --- /dev/null +++ b/Task/Zeckendorf-number-representation/Zkl/zeckendorf-number-representation-2.zkl @@ -0,0 +1 @@ +[0..20].pump(Console.println,fcn(n){ "%2d: %8s".fmt(n,zeckendorf(n)) }); diff --git a/Task/Zero-to-the-zero-power/BaCon/zero-to-the-zero-power.bacon b/Task/Zero-to-the-zero-power/BaCon/zero-to-the-zero-power.bacon new file mode 100644 index 0000000000..3a89906a10 --- /dev/null +++ b/Task/Zero-to-the-zero-power/BaCon/zero-to-the-zero-power.bacon @@ -0,0 +1 @@ +PRINT POW(0, 0) diff --git a/Task/Zero-to-the-zero-power/ColdFusion/zero-to-the-zero-power-1.cfm b/Task/Zero-to-the-zero-power/ColdFusion/zero-to-the-zero-power-1.cfm new file mode 100644 index 0000000000..b4304806ee --- /dev/null +++ b/Task/Zero-to-the-zero-power/ColdFusion/zero-to-the-zero-power-1.cfm @@ -0,0 +1,2 @@ + +"#zeroPowerTag#" diff --git a/Task/Zero-to-the-zero-power/ColdFusion/zero-to-the-zero-power-2.cfm b/Task/Zero-to-the-zero-power/ColdFusion/zero-to-the-zero-power-2.cfm new file mode 100644 index 0000000000..3e61d4a4ab --- /dev/null +++ b/Task/Zero-to-the-zero-power/ColdFusion/zero-to-the-zero-power-2.cfm @@ -0,0 +1,4 @@ + + zeroPower = 0^0; + writeOutput( zeroPower ); + diff --git a/Task/Zero-to-the-zero-power/Elena/zero-to-the-zero-power.elena b/Task/Zero-to-the-zero-power/Elena/zero-to-the-zero-power.elena new file mode 100644 index 0000000000..71bf8744dd --- /dev/null +++ b/Task/Zero-to-the-zero-power/Elena/zero-to-the-zero-power.elena @@ -0,0 +1,6 @@ +import extensions. + +program = +[ + console printLine("0^0 is ",0 power:0). +]. diff --git a/Task/Zero-to-the-zero-power/Gambas/zero-to-the-zero-power.gambas b/Task/Zero-to-the-zero-power/Gambas/zero-to-the-zero-power.gambas new file mode 100644 index 0000000000..2c9e5d913a --- /dev/null +++ b/Task/Zero-to-the-zero-power/Gambas/zero-to-the-zero-power.gambas @@ -0,0 +1,5 @@ +Public Sub Main() + +Print 0 ^ 0 + +End diff --git a/Task/Zero-to-the-zero-power/jq/zero-to-the-zero-power.jq b/Task/Zero-to-the-zero-power/Jq/zero-to-the-zero-power.jq similarity index 100% rename from Task/Zero-to-the-zero-power/jq/zero-to-the-zero-power.jq rename to Task/Zero-to-the-zero-power/Jq/zero-to-the-zero-power.jq diff --git a/Task/Zero-to-the-zero-power/Kotlin/zero-to-the-zero-power.kotlin b/Task/Zero-to-the-zero-power/Kotlin/zero-to-the-zero-power.kotlin new file mode 100644 index 0000000000..7552f0f51d --- /dev/null +++ b/Task/Zero-to-the-zero-power/Kotlin/zero-to-the-zero-power.kotlin @@ -0,0 +1,5 @@ +// version 1.0.6 + +fun main(args: Array) { + println("0 ^ 0 = ${Math.pow(0.0, 0.0)}") +} diff --git a/Task/Zero-to-the-zero-power/MATLAB/zero-to-the-zero-power.m b/Task/Zero-to-the-zero-power/MATLAB/zero-to-the-zero-power.m index b906ee0d2d..6578f4ac7d 100644 --- a/Task/Zero-to-the-zero-power/MATLAB/zero-to-the-zero-power.m +++ b/Task/Zero-to-the-zero-power/MATLAB/zero-to-the-zero-power.m @@ -1 +1,2 @@ 0^0 +complex(0,0)^0 diff --git a/Task/Zero-to-the-zero-power/OoRexx/zero-to-the-zero-power.rexx b/Task/Zero-to-the-zero-power/OoRexx/zero-to-the-zero-power.rexx new file mode 100644 index 0000000000..7c8c5b7f56 --- /dev/null +++ b/Task/Zero-to-the-zero-power/OoRexx/zero-to-the-zero-power.rexx @@ -0,0 +1,6 @@ +/********************************************************************** +* 21.04.2014 Walter Pachl +**********************************************************************/ +Say 'rxCalcpower(0,0) ->' rxCalcpower(0,0) +Say '0**0 ->' 0**0 +::requires rxmath library diff --git a/Task/Zero-to-the-zero-power/Sidef/zero-to-the-zero-power-1.sidef b/Task/Zero-to-the-zero-power/Sidef/zero-to-the-zero-power-1.sidef index 25295b1c59..6385f534ef 100644 --- a/Task/Zero-to-the-zero-power/Sidef/zero-to-the-zero-power-1.sidef +++ b/Task/Zero-to-the-zero-power/Sidef/zero-to-the-zero-power-1.sidef @@ -1,6 +1,3 @@ [0, Complex(0, 0)].each {|n| - say n**n; - say n.pow(n); - say pow(n, n); - say Math.pow(n, n); + say n**n } diff --git a/Task/Zero-to-the-zero-power/Sidef/zero-to-the-zero-power-2.sidef b/Task/Zero-to-the-zero-power/Sidef/zero-to-the-zero-power-2.sidef index d6c347c223..cb49503fcb 100644 --- a/Task/Zero-to-the-zero-power/Sidef/zero-to-the-zero-power-2.sidef +++ b/Task/Zero-to-the-zero-power/Sidef/zero-to-the-zero-power-2.sidef @@ -1,2 +1,2 @@ -say 0.root(0).pow(0); # => 1 -say ((0**(1/0))**0); # => 1 +say 0.root(0).pow(0) # => 1 +say ((0**(1/0))**0) # => 1 diff --git a/Task/Zero-to-the-zero-power/Sinclair-ZX81-BASIC/zero-to-the-zero-power.sinclair b/Task/Zero-to-the-zero-power/Sinclair-ZX81-BASIC/zero-to-the-zero-power.sinclair new file mode 100644 index 0000000000..c154b79710 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Sinclair-ZX81-BASIC/zero-to-the-zero-power.sinclair @@ -0,0 +1 @@ +PRINT 0**0 diff --git a/Task/Zero-to-the-zero-power/Smart-BASIC/zero-to-the-zero-power.smart b/Task/Zero-to-the-zero-power/Smart-BASIC/zero-to-the-zero-power.smart new file mode 100644 index 0000000000..5769450edb --- /dev/null +++ b/Task/Zero-to-the-zero-power/Smart-BASIC/zero-to-the-zero-power.smart @@ -0,0 +1 @@ +PRINT 0^0 diff --git a/Task/Zero-to-the-zero-power/Stata/zero-to-the-zero-power.stata b/Task/Zero-to-the-zero-power/Stata/zero-to-the-zero-power.stata new file mode 100644 index 0000000000..bde8e6c7bc --- /dev/null +++ b/Task/Zero-to-the-zero-power/Stata/zero-to-the-zero-power.stata @@ -0,0 +1,2 @@ +. display 0^0 +1 diff --git a/Task/Zero-to-the-zero-power/Zkl/zero-to-the-zero-power.zkl b/Task/Zero-to-the-zero-power/Zkl/zero-to-the-zero-power.zkl new file mode 100644 index 0000000000..b0f2fd644d --- /dev/null +++ b/Task/Zero-to-the-zero-power/Zkl/zero-to-the-zero-power.zkl @@ -0,0 +1,3 @@ +(0.0).pow(0) //--> 1.0 +var BN=Import("zklBigNum"); // big ints +BN(0).pow(0) //--> 1 diff --git a/Task/Zhang-Suen-thinning-algorithm/Elena/zhang-suen-thinning-algorithm.elena b/Task/Zhang-Suen-thinning-algorithm/Elena/zhang-suen-thinning-algorithm.elena new file mode 100644 index 0000000000..a20e13d799 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Elena/zhang-suen-thinning-algorithm.elena @@ -0,0 +1,164 @@ +import system'collections. +import system'routines. +import extensions. +import extensions'routines. + +type charmatrix = matrix. + +const image = ( + " ", + " ################# ############# ", + " ################## ################ ", + " ################### ################## ", + " ######## ####### ################### ", + " ###### ####### ####### ###### ", + " ###### ####### ####### ", + " ################# ####### ", + " ################ ####### ", + " ################# ####### ", + " ###### ####### ####### ", + " ###### ####### ####### ", + " ###### ####### ####### ###### ", + " ######## ####### ################### ", + " ######## ####### ###### ################## ###### ", + " ######## ####### ###### ################ ###### ", + " ######## ####### ###### ############# ###### ", + " "). + +nbrs = ((0, -1), (1, -1), (1, 0), (1, 1), (0, 1), + (-1, 1), (-1, 0), (-1, -1), (0, -1)). + +nbrGroups = (((0, 2, 4), (2, 4, 6)), ((0, 2, 6), + (0, 4, 6))). + +charmatrix extension zhangsuenOp +{ + $proceed : r : c : toWhite : firstStep + [ + if (self[r][c] != $35) + [ ^ false ]. + + int nn := self numNeighbors(r,c). + + if ((nn < 2) || (nn > 6)) + [ ^ false ]. + + if(self numTransitions(r,c) != 1) + [ ^ false ]. + + ifnot (self atLeastOneIsWhite(r,c,firstStep iif(0,1))) + [ ^ false ]. + + toWhite append:{ x = c. y = r. }. + + ^ true. + ] + + numNeighbors :r : c + [ + int count := 0. + + 0 till(nbrs length - 1) do(:i) + [ + if (self[r + nbrs[i][1]][c + nbrs[i][0]] == $35) + [ count := count + 1. ]. + ]. + + ^ count. + ] + + numTransitions : r : c + [ + int count := 0. + + 0 till(nbrs length - 1) do(:i) + [ + if (self[r + nbrs[i][1]][c + nbrs[i][0]] == $32) + [ + if (self[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == $35) + [ + count := count + 1. + ]. + ]. + ]. + + ^ count. + ] + + atLeastOneIsWhite : r : c : step + [ + int count := 0. + var group := nbrGroups[step]. + 0 till:2 do(:i) + [ + 0 till(group[i] length) seek(:j) + [ + var nbr := nbrs[group[i][j]]. + + if (self[r + nbr[1]][c + nbr[0]] == $32) + [ count := count + 1. ^ true ]. + + ^ false. + ]. + ]. + + ^ count > 1. + ] + + thinImage + [ + bool firstStep := false. + bool hasChanged := true. + var toWhite := List new. + + while (hasChanged || firstStep) + [ + hasChanged := false. + firstStep := firstStep not. + + 1 till(self rows - 1) do(:r) + [ + 1 till(self columns - 1) do(:c) + [ + if(self~zhangsuenOp $proceed(r,c,toWhite,firstStep)) + [ hasChanged := true ]. + ]. + ]. + + toWhite forEach(:p)[ self[p y][p x] := $32. ]. + toWhite clear. + ]. + ] + + print + [ + var it := self enumerator. + + it forEach(:ch) [ console print(ch," ") ]. + while (it next) + [ + console writeLine. + + it forEach(:ch) [ console print(ch," ") ]. + ]. + ] +} + +program = +[ + charmatrix grid := MatrixSpace:: + { + rows = image length. + + columns = image[0] length. + + getAt int:i int:j + = image[i][j]. + }. + + grid thinImage. + + grid print. + + console readChar. +]. diff --git a/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-1.f b/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-1.f new file mode 100644 index 0000000000..6616567bfc --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-1.f @@ -0,0 +1 @@ +FOR ALL (i = 2:n - 1) A(i) = (A(i - 1) + A(i) + A(i + 1))/3 diff --git a/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-2.f b/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-2.f new file mode 100644 index 0000000000..c87a9d71c6 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-2.f @@ -0,0 +1 @@ +A(2:N - 1) = (A(1:N - 2) + A(2:N - 1) + A(3:N))/3 diff --git a/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-3.f b/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-3.f new file mode 100644 index 0000000000..61693effd8 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-3.f @@ -0,0 +1,2 @@ + FOR ALL (I = 2:N - 1, J = 2:M - 1) + WHERE(DOT(I,J) .NE. 0) DOT(I,J) = ADJUST(DOT,I,J) diff --git a/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-4.f b/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-4.f new file mode 100644 index 0000000000..a06e86f126 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-4.f @@ -0,0 +1 @@ + DOT(WHACK(1:WHACKCOUNT).I,WHACK(1:WHACKCOUNT).J) = 0 diff --git a/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-5.f b/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-5.f new file mode 100644 index 0000000000..f6f9b3242b --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Fortran/zhang-suen-thinning-algorithm-5.f @@ -0,0 +1,106 @@ + MODULE ZhangSuenThinning !Image manipulation. + CONTAINS + SUBROUTINE ZST(DOT) !Attempts to thin out thick lines. + INTEGER DOT(:,:) !The image in an array, rows down the page. + TYPE PLACE !This records an array location. + INTEGER I !Via its + INTEGER J !Indices. + END TYPE PLACE !A lot of baggage. + TYPE(PLACE) WHACK(UBOUND(DOT,DIM = 1)*UBOUND(DOT,DIM = 2)) !Allow a whack for every dot. + INTEGER WHACKCOUNT !Counts up those to be wiped out. + LOGICAL WHACKED !Notes if any have been. + INTEGER STEP,I,N,J,M !Assistants. + INTEGER D9(9) !Holds a 3x3 portion. + INTEGER HIT1(3,2),HIT2(3,2) !Lists of elements to inspect for certain tests. + PARAMETER (HIT1 = (/2,6,8, 4,2,6/)) !Two stages. + PARAMETER (HIT2 = (/4,8,6, 2,4,8/)) !Each with two hit lists. + N = UBOUND(DOT,DIM = 1) !Number of rows. + M = UBOUND(DOT,DIM = 2) !Number of columns. +Commence a pass. + 10 WHACKED = .FALSE. !No damage so far. + DO STEP = 1,2 !Each pass is in two stages. + WHACKCOUNT = 0 !No dots have been selected for whitewashing. + DO I = 2,N - 1 !Scan down the rows. + DO J = 2,M - 1 !And the columns. Interior dots only. + IF (DOT(I,J).NE.0) THEN !Rule 0: Is the dot black? Eight neighbours are present due to loop control. + D9(1:3) = DOT(I - 1,J - 1:J + 1) !Yes. Form a 3x3 mesh. 1 2 3 not 9 2 3 + D9(4:6) = DOT(I ,J - 1:J + 1) !As a 1-D array. 4 5 6 8 1 4 + D9(7:9) = DOT(I + 1,J - 1:J + 1) !For eased access. 7 8 9 7 6 5 + CALL INSPECT(D9,HIT1(1,STEP),HIT2(1,STEP)) !Apply rules one to four, as specified. + END IF !So much for a black dot. + END DO !On to the next column. + END DO !On to the next row. + IF (WHACKCOUNT.GT.0) THEN !Are any to be wiped out? + DO I = 1,WHACKCOUNT !Yes! + DOT(WHACK(I).I,WHACK(I).J) = 0 !One by one. + END DO !On to the next victim. +Can't use DOT(WHACK(1:WHACKCOUNT).I,WHACK(1:WHACKCOUNT).J) = 0 + WHACKED = .TRUE. !There has been a change. + END IF !So much for changes. + END DO !On to the second stage. + IF (WHACKED) GO TO 10 !If there had been changes, perhaps there will be more. + CONTAINS !Some helpers. + SUBROUTINE INSPECT(BLOB,HIT1,HIT2) !Inspect a 3x3 piece according to the four levels of tests as specified. + INTEGER BLOB(9) !The piece. BLOB(5) is DOT(I,J), and is expected to be 1. + INTEGER HIT1(3),HIT2(3) !Two hit lists. + INTEGER TWIRL(9) !traces the periphery of the piece. + PARAMETER (TWIRL = (/2,3,6,9,8,7,4,1,2/)) !Cycle around the periphery. + INTEGER B !A counter. !Rule: + B = SUM(BLOB) - BLOB(5) !1: Count the neighbours having one, not zero. + IF (2 <= B .AND. B <= 6) THEN ! The test. Can't have 2 <= B <= 6, alas. + IF (COUNT(BLOB(TWIRL(1:8)) !2: Counting transitions. + * .LT.BLOB(TWIRL(2:9))) .EQ.1) THEN ! The test of 0 --> positive. + IF (ANY(BLOB(HIT1).EQ.0)) THEN !3: At least one must be white. + IF (ANY(BLOB(HIT2).EQ.0)) THEN !4: Of two sets of three. + WHACKCOUNT = WHACKCOUNT + 1 !Another one down! + WHACK(WHACKCOUNT) = PLACE(I,J) !This is the place. + END IF !Now back out of the nested IF-statements. + END IF !Since the tests must all be passed + END IF !Rather than say three out of four. + END IF !For the given method. + END SUBROUTINE INSPECT!That was weird. + END SUBROUTINE ZST !But so it goes. + + SUBROUTINE SHOW(A) !Display an image array on the standard output. + INTEGER A(:,:) !Values are expected to be zero and one. + CHARACTER*1 HIC(0:1) !But I don't want to look at wads of digits. + PARAMETER (HIC = (/".","#"/)) !These offer better contrast. + INTEGER I !A stepper. + DO I = 1,UBOUND(A,DIM = 1) !Work down the given number of rows. + WRITE (6,"(666A1)") HIC(A(I,:)) !Roll a translated line. + END DO !Hopefully, no more than 666 to a line. + END SUBROUTINE SHOW !That was straightforward. + END MODULE ZhangSuenThinning + + PROGRAM POKE !Just set up the example. + USE ZhangSuenThinning + INTEGER N,M !Parameters for the example. + PARAMETER (N = 10,M = 32) !Rows and columns. + CHARACTER*(M) CANVAS(N) !Rather than some monster DATA statement, + PARAMETER (CANVAS = (/ !It is easier to prepare a worksheet. + 1 " ", + 2 " 111111111 11111111 ", + 3 " 111 1111 1111 1111 ", + 4 " 111 111 111 111 ", + 5 " 111 1111 111 ", + 6 " 111111111 111 ", + 7 " 111 1111 111 111 ", + 8 " 111 1111 111 1111 1111 111 ", + 9 " 111 1111 111 11111111 111 ", + o " "/)) + INTEGER IMAGE(N,M) !The image array. Exactly the required size. + INTEGER I !A stepper. + + DO I = 1,N !Read the rows. + READ (CANVAS(I),"(666I1)") IMAGE(I,:) !Presumably, 666 will suffice. + END DO !A blank is taken as a zero with formatted input. + + WRITE (6,*) "The initial image..." + CALL SHOW(IMAGE) + WRITE (6,*) + + CALL ZST(IMAGE) + WRITE (6,*) "And after 'thinning'..." + CALL SHOW(IMAGE) + + END PROGRAM POKE diff --git a/Task/Zhang-Suen-thinning-algorithm/JavaScript/zhang-suen-thinning-algorithm.js b/Task/Zhang-Suen-thinning-algorithm/JavaScript/zhang-suen-thinning-algorithm.js new file mode 100644 index 0000000000..0e01d448ce --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/JavaScript/zhang-suen-thinning-algorithm.js @@ -0,0 +1,106 @@ +function Point(x, y) { + this.x = x; + this.y = y; +} +var ZhangSuen = (function () { + function ZhangSuen() { + } + ZhangSuen.image = + [" ", + " ################# ############# ", + " ################## ################ ", + " ################### ################## ", + " ######## ####### ################### ", + " ###### ####### ####### ###### ", + " ###### ####### ####### ", + " ################# ####### ", + " ################ ####### ", + " ################# ####### ", + " ###### ####### ####### ", + " ###### ####### ####### ", + " ###### ####### ####### ###### ", + " ######## ####### ################### ", + " ######## ####### ###### ################## ###### ", + " ######## ####### ###### ################ ###### ", + " ######## ####### ###### ############# ###### ", + " "]; + + ZhangSuen.nbrs = [[0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1]]; + + ZhangSuen.nbrGroups = [[[0, 2, 4], [2, 4, 6]], [[0, 2, 6], [0, 4, 6]]]; + + ZhangSuen.toWhite = new Array(); + ; + ZhangSuen.main = function (args) { + ZhangSuen.grid = new Array(ZhangSuen.image.length); + for (var r = 0; r < ZhangSuen.image.length; r++) + ZhangSuen.grid[r] = (ZhangSuen.image[r]).split(''); + ZhangSuen.thinImage(); + }; + ZhangSuen.thinImage = function () { + var firstStep = false; + var hasChanged; + do { + hasChanged = false; + firstStep = !firstStep; + for (var r = 1; r < ZhangSuen.grid.length - 1; r++) { + for (var c = 1; c < ZhangSuen.grid[0].length - 1; c++) { + if (ZhangSuen.grid[r][c] !== '#') + continue; + var nn = ZhangSuen.numNeighbors(r, c); + if (nn < 2 || nn > 6) + continue; + if (ZhangSuen.numTransitions(r, c) !== 1) + continue; + if (!ZhangSuen.atLeastOneIsWhite(r, c, firstStep ? 0 : 1)) + continue; + ZhangSuen.toWhite.push(new Point(c, r)); + hasChanged = true; + } + } + for (let i = 0; i < ZhangSuen.toWhite.length; i++) { + var p = ZhangSuen.toWhite[i]; + ZhangSuen.grid[p.y][p.x] = ' '; + } + ZhangSuen.toWhite = new Array(); + } while ((firstStep || hasChanged)); + ZhangSuen.printResult(); + }; + ZhangSuen.numNeighbors = function (r, c) { + var count = 0; + for (var i = 0; i < ZhangSuen.nbrs.length - 1; i++) + if (ZhangSuen.grid[r + ZhangSuen.nbrs[i][1]][c + ZhangSuen.nbrs[i][0]] === '#') + count++; + return count; + }; + ZhangSuen.numTransitions = function (r, c) { + var count = 0; + for (var i = 0; i < ZhangSuen.nbrs.length - 1; i++) + if (ZhangSuen.grid[r + ZhangSuen.nbrs[i][1]][c + ZhangSuen.nbrs[i][0]] === ' ') { + if (ZhangSuen.grid[r + ZhangSuen.nbrs[i + 1][1]][c + ZhangSuen.nbrs[i + 1][0]] === '#') + count++; + } + return count; + }; + ZhangSuen.atLeastOneIsWhite = function (r, c, step) { + var count = 0; + var group = ZhangSuen.nbrGroups[step]; + for (var i = 0; i < 2; i++) + for (var j = 0; j < group[i].length; j++) { + var nbr = ZhangSuen.nbrs[group[i][j]]; + if (ZhangSuen.grid[r + nbr[1]][c + nbr[0]] === ' ') { + count++; + break; + } + } + return count > 1; + }; + ZhangSuen.printResult = function () { + for (var i = 0; i < ZhangSuen.grid.length; i++) { + var row = ZhangSuen.grid[i]; + console.log(row.join('')); + } + }; + return ZhangSuen; +}()); +ZhangSuen.main(null); diff --git a/Task/Zhang-Suen-thinning-algorithm/Kotlin/zhang-suen-thinning-algorithm.kotlin b/Task/Zhang-Suen-thinning-algorithm/Kotlin/zhang-suen-thinning-algorithm.kotlin new file mode 100644 index 0000000000..a30dcd6203 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Kotlin/zhang-suen-thinning-algorithm.kotlin @@ -0,0 +1,100 @@ +// version 1.1.2 + +class Point(val x: Int, val y: Int) + +val image = arrayOf( + " ", + " ################# ############# ", + " ################## ################ ", + " ################### ################## ", + " ######## ####### ################### ", + " ###### ####### ####### ###### ", + " ###### ####### ####### ", + " ################# ####### ", + " ################ ####### ", + " ################# ####### ", + " ###### ####### ####### ", + " ###### ####### ####### ", + " ###### ####### ####### ###### ", + " ######## ####### ################### ", + " ######## ####### ###### ################## ###### ", + " ######## ####### ###### ################ ###### ", + " ######## ####### ###### ############# ###### ", + " " +) + +val nbrs = arrayOf( + intArrayOf( 0, -1), intArrayOf( 1, -1), intArrayOf( 1, 0), + intArrayOf( 1, 1), intArrayOf( 0, 1), intArrayOf(-1, 1), + intArrayOf(-1, 0), intArrayOf(-1, -1), intArrayOf( 0, -1) +) + +val nbrGroups = arrayOf( + arrayOf(intArrayOf(0, 2, 4), intArrayOf(2, 4, 6)), + arrayOf(intArrayOf(0, 2, 6), intArrayOf(0, 4, 6)) +) + +val toWhite = mutableListOf() +val grid = Array(image.size) { image[it].toCharArray() } + +fun thinImage() { + var firstStep = false + var hasChanged: Boolean + do { + hasChanged = false + firstStep = !firstStep + for (r in 1 until grid.size - 1) { + for (c in 1 until grid[0].size - 1) { + if (grid[r][c] != '#') continue + val nn = numNeighbors(r, c) + if (nn !in 2..6) continue + if (numTransitions(r, c) != 1) continue + val step = if (firstStep) 0 else 1 + if (!atLeastOneIsWhite(r, c, step)) continue + toWhite.add(Point(c, r)) + hasChanged = true + } + } + for (p in toWhite) grid[p.y][p.x] = ' ' + toWhite.clear() + } + while (firstStep || hasChanged) + for (row in grid) println(row) +} + +fun numNeighbors(r: Int, c: Int): Int { + var count = 0 + for (i in 0 until nbrs.size - 1) { + if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#') count++ + } + return count +} + +fun numTransitions(r: Int, c: Int): Int { + var count = 0 + for (i in 0 until nbrs.size - 1) { + if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') { + if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#') count++ + } + } + return count +} + +fun atLeastOneIsWhite(r: Int, c: Int, step: Int): Boolean { + var count = 0; + val group = nbrGroups[step] + for (i in 0..1) { + for (j in 0 until group[i].size) { + val nbr = nbrs[group[i][j]] + if (grid[r + nbr[1]][c + nbr[0]] == ' ') { + count++ + break + } + } + } + return count > 1 +} + +fun main(args: Array) { + thinImage() +} diff --git a/Task/Zhang-Suen-thinning-algorithm/Perl-6/zhang-suen-thinning-algorithm.pl6 b/Task/Zhang-Suen-thinning-algorithm/Perl-6/zhang-suen-thinning-algorithm.pl6 index f59008b3be..74f1cbbce4 100644 --- a/Task/Zhang-Suen-thinning-algorithm/Perl-6/zhang-suen-thinning-algorithm.pl6 +++ b/Task/Zhang-Suen-thinning-algorithm/Perl-6/zhang-suen-thinning-algorithm.pl6 @@ -3,7 +3,7 @@ constant DEBUG = 1; my @lines = ([.ords X+& 1] for lines); # The low bits Just Work. my \v = +@lines; my \h = +@lines[0]; -my @black = @lines.map: *.values; # Flatten to 1-dimensional. +my @black = flat @lines.map: *.values; # Flatten to 1-dimensional. my \p8 = [-h-1, -h+0, -h+1, # Flatland distances to 8 neighbors. 0-1, 0+1, @@ -11,7 +11,7 @@ my \p8 = [-h-1, -h+0, -h+1, # Flatland distances to 8 neighbors. # Candidates have 8 neighbors and are known black my @cand = grep { @black[$_] }, do - for 1..v-2 X 1..h-2 -> \y,\x { y*h + x } + for 1..v-2 X 1..h-2 -> (\y,\x) { y*h + x } repeat while my @goners1 or my @goners2 { sub seewhite (\w1,\w2) { diff --git a/Task/Zhang-Suen-thinning-algorithm/Sidef/zhang-suen-thinning-algorithm.sidef b/Task/Zhang-Suen-thinning-algorithm/Sidef/zhang-suen-thinning-algorithm.sidef index fa543dfebf..288177cd92 100644 --- a/Task/Zhang-Suen-thinning-algorithm/Sidef/zhang-suen-thinning-algorithm.sidef +++ b/Task/Zhang-Suen-thinning-algorithm/Sidef/zhang-suen-thinning-algorithm.sidef @@ -2,37 +2,37 @@ class ZhangSuen(str, black="1") { const NEIGHBOURS = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]] # 8 neighbors const CIRCULARS = (NEIGHBOURS + [NEIGHBOURS.first]) # P2, ... P9, P2 - has r = 0; - has image = [[]]; + has r = 0 + has image = [[]] method init { var s1 = str.lines.map{|line| line.chars.map{|c| c==black ? 1 : 0 }} var s2 = s1.len.of { s1[0].len.of(0) } - var xr = RangeNum(1, s1.end-1) - var yr = RangeNum(1, s1[0].end-1) + var xr = range(1, s1.end-1) + var yr = range(1, s1[0].end-1) do { - r = 0; + r = 0 xr.each{|x| yr.each{|y| s2[x][y] = (s1[x][y] - self.zs(s1,x,y,1)) }} # Step 1 xr.each{|x| yr.each{|y| s1[x][y] = (s2[x][y] - self.zs(s2,x,y,0)) }} # Step 2 - } while !r.is_zero; - image = s1; + } while !r.is_zero + image = s1 } method zs(ng,x,y,g) { (ng[x][y] == 0) -> || (ng[x-1][y] + ng[x][y+1] + ng[x+g][y+g - 1] == 3) -> || (ng[x+g - 1][y+g] + ng[x+1][y] + ng[x][y-1] == 3) -> - && return 0; + && return 0 - var bp1 = NEIGHBOURS.map {|p| ng[x+p[0]][y+p[1]] }.sum(0); # B(P1) - return 0 if ((bp1 < 2) || (6 < bp1)); + var bp1 = NEIGHBOURS.map {|p| ng[x+p[0]][y+p[1]] }.sum # B(P1) + return 0 if ((bp1 < 2) || (6 < bp1)) - var ap1 = 0; - CIRCULARS.map {|p| ng[x+p[0]][y+p[1]] }.each_cons(2, {|p| - ++ap1 if (p[0] < p[1]) # A(P1) + var ap1 = 0 + CIRCULARS.map {|p| ng[x+p[0]][y+p[1]] }.each_cons(2, {|a,b| + ++ap1 if (a < b) # A(P1) }) - return 0 if (ap1 != 1); + return 0 if (ap1 != 1) r = 1 } diff --git a/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-3.applescript b/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-3.applescript index cdfcf95fbb..1efa8d20fa 100644 --- a/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-3.applescript +++ b/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-3.applescript @@ -3,7 +3,7 @@ on zigzagMatrix(n) -- diagonals :: n -> [[n]] script diagonals - on lambda(n) + on |λ|(n) script mf on diags(xs, iCol, iRow) if (iCol < length of xs) then @@ -21,35 +21,25 @@ on zigzagMatrix(n) end diags end script - diags(range(0, n * n - 1), 1, 1) of mf - end lambda + diags(enumFromTo(0, n * n - 1), 1, 1) of mf + end |λ| end script -- oddReversed :: [a] -> Int -> [a] script oddReversed - on lambda(lst, i) + on |λ|(lst, i) if i mod 2 = 0 then lst else reverse of lst end if - end lambda + end |λ| end script - rowsFromDiagonals(n, map(oddReversed, lambda(n) of diagonals)) + rowsFromDiagonals(n, map(oddReversed, |λ|(n) of diagonals)) end zigzagMatrix - --- TEST -on run - - zigzagMatrix(5) - -end run - - - -- Rows of given length from list of diagonals -- rowsFromDiagonals :: Int -> [[a]] -> [[a]] on rowsFromDiagonals(n, lst) @@ -57,9 +47,9 @@ on rowsFromDiagonals(n, lst) -- lengthOverOne :: [a] -> Bool script lengthOverOne - on lambda(lst) + on |λ|(lst) length of lst > 1 - end lambda + end |λ| end script set {edge, residue} to splitAt(n, lst) @@ -69,14 +59,34 @@ on rowsFromDiagonals(n, lst) map(my tail, ¬ filter(lengthOverOne, edge)) & residue) else - [] + {} end if end rowsFromDiagonals ---------------------------------------------------------------------------- +-- TEST ----------------------------------------------------------------------- +on run --- GENERIC FUNCTIONS + zigzagMatrix(5) + +end run + + +-- GENERIC FUNCTIONS ---------------------------------------------------------- + +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if n < m then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) @@ -85,24 +95,45 @@ on filter(f, xs) set lng to length of xs repeat with i from 1 to lng set v to item i of xs - if lambda(v, i, xs) then set end of lst to v + if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell end filter +-- head :: [a] -> a +on head(xs) + if length of xs > 0 then + item 1 of xs + else + missing value + end if +end head + -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + -- splitAt:: n -> list -> {n items from start of list, rest of list} -- splitAt :: Int -> [a] -> ([a], [a]) on splitAt(n, xs) @@ -117,15 +148,6 @@ on splitAt(n, xs) end if end splitAt --- head :: [a] -> a -on head(xs) - if length of xs > 0 then - item 1 of xs - else - missing value - end if -end head - -- tail :: [a] -> [a] on tail(xs) if length of xs > 1 then @@ -134,26 +156,3 @@ on tail(xs) {} end if end tail - --- range :: Int -> Int -> [Int] -on range(m, n) - set d to 1 - if n < m then set d to -1 - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range - --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn diff --git a/Task/Zig-zag-matrix/C/zig-zag-matrix-1.c b/Task/Zig-zag-matrix/C/zig-zag-matrix-1.c deleted file mode 100644 index ebe9d6ef1d..0000000000 --- a/Task/Zig-zag-matrix/C/zig-zag-matrix-1.c +++ /dev/null @@ -1,23 +0,0 @@ -#include -#include - -int main(int c, char **v) -{ - int i, j, m, n, *s; - - /* default size: 5 */ - if (c < 2 || ((m = atoi(v[1]))) <= 0) m = 5; - - /* 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 = 0; i < m * m; putchar((++i % m) ? ' ':'\n')) - printf("%3d", s[i]); - - /* free(s) */ - return 0; -} diff --git a/Task/Zig-zag-matrix/C/zig-zag-matrix-2.c b/Task/Zig-zag-matrix/C/zig-zag-matrix-2.c deleted file mode 100644 index 44b1c1944a..0000000000 --- a/Task/Zig-zag-matrix/C/zig-zag-matrix-2.c +++ /dev/null @@ -1,8 +0,0 @@ -% ./a.out 7 - 0 1 5 6 14 15 27 - 2 4 7 13 16 26 28 - 3 8 12 17 25 29 38 - 9 11 18 24 30 37 39 - 10 19 23 31 36 40 45 - 20 22 32 35 41 44 46 - 21 33 34 42 43 47 48 diff --git a/Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix-1.coffee b/Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix-1.coffee deleted file mode 100644 index 8f7565fa58..0000000000 --- a/Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix-1.coffee +++ /dev/null @@ -1,41 +0,0 @@ -# Calculate a zig-zag pattern of numbers like so: -# 0 1 5 -# 2 4 6 -# 3 7 8 -# -# There are many interesting ways to solve this; we -# try for an algebraic approach, calculating triangle -# areas, so that me minimize space requirements. - -zig_zag_value = (x, y, n) -> - - upper_triangle_zig_zag = (x, y) -> - # calculate the area of the triangle from the prior - # diagonals - diag = x + y - triangle_area = diag * (diag+1) / 2 - # then add the offset along the diagonal - if diag % 2 == 0 - triangle_area + y - else - triangle_area + x - - if x + y < n - upper_triangle_zig_zag x, y - else - # For the bottom right part of the matrix, we essentially - # use reflection to count backward. - bottom_right_cell = n * n - 1 - n -= 1 - v = upper_triangle_zig_zag(n-x, n-y) - bottom_right_cell - v - -zig_zag_matrix = (n) -> - row = (i) -> (zig_zag_value i, j, n for j in [0...n]) - (row i for i in [0...n]) - -do -> - for n in [4..6] - console.log "---- n=#{n}" - console.log zig_zag_matrix(n) - console.log "\n" diff --git a/Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix-2.coffee b/Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix-2.coffee deleted file mode 100644 index 973d2c6d0e..0000000000 --- a/Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix-2.coffee +++ /dev/null @@ -1,23 +0,0 @@ -> coffee zigzag.coffee ----- n=4 -[ [ 0, 1, 5, 6 ], - [ 2, 4, 7, 12 ], - [ 3, 8, 11, 13 ], - [ 9, 10, 14, 15 ] ] - - ----- n=5 -[ [ 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 ] ] - - ----- n=6 -[ [ 0, 1, 5, 6, 14, 15 ], - [ 2, 4, 7, 13, 16, 25 ], - [ 3, 8, 12, 17, 24, 26 ], - [ 9, 11, 18, 23, 27, 32 ], - [ 10, 19, 22, 28, 31, 33 ], - [ 20, 21, 29, 30, 34, 35 ] ] diff --git a/Task/Zig-zag-matrix/Elena/zig-zag-matrix.elena b/Task/Zig-zag-matrix/Elena/zig-zag-matrix.elena new file mode 100644 index 0000000000..8947d7eee4 --- /dev/null +++ b/Task/Zig-zag-matrix/Elena/zig-zag-matrix.elena @@ -0,0 +1,46 @@ +import extensions. + +extension op +{ + zigzagMatrix + [ + intmatrix result := IntMatrix new int:self int:self. + + int i := 0. + int j := 0. + int d := -1. + int start := 0. + int end := self*self - 1. + + while (start < end) + [ + result write int:i int:j int:start. start := start + 1. + result write int(self - i - 1) int(self - j - 1) int:end. end := end - 1. + + i := i + d. + j := j - d. + if (i < 0) + [ + i:=i+1. d := d negative + ]; + [ + if (j < 0) + [ + j := j + 1. d := d negative + ] + ] + ]. + + if (start == end) + [ + result write int:i int:j int:start. + ]. + + ^ result + ] +} + +program = +[ + console printLine(5 zigzagMatrix); readChar. +]. diff --git a/Task/Zig-zag-matrix/Haskell/zig-zag-matrix-3.hs b/Task/Zig-zag-matrix/Haskell/zig-zag-matrix-3.hs new file mode 100644 index 0000000000..a805928893 --- /dev/null +++ b/Task/Zig-zag-matrix/Haskell/zig-zag-matrix-3.hs @@ -0,0 +1,37 @@ +import Data.List (mapAccumL) +import Data.Text (justifyRight, pack, unpack) + +zigZag :: Int -> [[Int]] +zigZag n = horizontals n (diagonals n) + where + + diagonals :: Int -> [[Int]] + diagonals n = + snd $ + mapAccumL + (\xs h -> + let (grp, rst) = splitAt h xs + in ( rst + , (if mod h 2 /= 0 + then reverse + else id) + grp)) + [0 .. (n * n) - 1] + (slope ++ [n] ++ reverse slope) + where + slope = [1 .. n - 1] + + horizontals :: Int -> [[Int]] -> [[Int]] + horizontals n xss = + if not (null xss) + then let (edge, rst) = splitAt n xss + in (head <$> edge) : + horizontals n (dropWhile null (tail <$> edge) ++ rst) + else [] + +main :: IO () +main = + putStrLn $ + unlines $ + (concat . (unpack <$>)) . ((justifyRight 3 ' ' . pack . show) <$>) <$> + zigZag 5 diff --git a/Task/Zig-zag-matrix/jq/zig-zag-matrix-1.jq b/Task/Zig-zag-matrix/Jq/zig-zag-matrix-1.jq similarity index 100% rename from Task/Zig-zag-matrix/jq/zig-zag-matrix-1.jq rename to Task/Zig-zag-matrix/Jq/zig-zag-matrix-1.jq diff --git a/Task/Zig-zag-matrix/jq/zig-zag-matrix-2.jq b/Task/Zig-zag-matrix/Jq/zig-zag-matrix-2.jq similarity index 100% rename from Task/Zig-zag-matrix/jq/zig-zag-matrix-2.jq rename to Task/Zig-zag-matrix/Jq/zig-zag-matrix-2.jq diff --git a/Task/Zig-zag-matrix/Jq/zig-zag-matrix-3.jq b/Task/Zig-zag-matrix/Jq/zig-zag-matrix-3.jq new file mode 100644 index 0000000000..cdd39cf02b --- /dev/null +++ b/Task/Zig-zag-matrix/Jq/zig-zag-matrix-3.jq @@ -0,0 +1,65 @@ +#!/usr/bin/env jq -Mnrc -f +# +# solve zigzag matrix by constructing list of 2n+1 column "runs" +# and then shifting them into final form. +# +# e.g. for n=3 initial runs are [[0],[1,2],[3,4,5],[6,7],[8]] +# runs below are shown as columns: +# +# initial column runs 0 1 3 6 8 +# 2 4 7 +# 5 +# +# reverse cols 0,2,4 0 1 5 6 8 +# 2 4 7 +# 3 +# +# shift cols 3,4 down 0 1 5 +# 2 4 6 +# 3 7 8 +# +# shift rows left 0 1 5 +# to get final zigzag 2 4 6 +# 3 7 8 + + def N: $n ; # size of matrix + def NR: 2*N - 1; # number of runs + def abs: if .<0 then -. else . end ; # absolute value + def runlen: N-(N-.|abs) ; # length of run + def makeruns: [ + foreach range(1;NR+1) as $r ( # for each run + {c:0} # state counter + ; .l = ($r|runlen) # length of this run + | .r = [range(.c;.c+.l)] # values in this run + | .c += .l # increment counter + ; .r # produce run + ) ] ; # collect into array + def even: .%2==0 ; # is input even? + def reverseruns: # reverse alternate runs + .[keys|map(select(even))[]] |= reverse ; + def zeros: [range(.|N-length)|0] ; # array of padding zeros + def shiftdown: + def pad($r): # pad run with zeros + if $r < N # determine where zeros go + then . = . + zeros # at back for left runs + else . = zeros + . # at front for right runs + end ; + reduce keys[] as $r (.;.[$r] |= pad($r)); # shift rows down with pad + def shiftleft: [ + range(N) as $r + | [ range($r;$r+N) as $c + | .[$c][$r] + ] + ] ; + def width: [.[][]]|max|tostring|1+length; # width of largest value + def justify($w): (($w-length)*" ") + . ; # leading spaces + def format: + width as $w # compute width + | map(map(tostring | justify($w)))[] # justify values + | join(" ") + ; + makeruns # create column runs + | reverseruns # reverse alternate runs + | shiftdown # shift right runs down + | shiftleft # shift rows left + | format # format final result diff --git a/Task/Zig-zag-matrix/Kotlin/zig-zag-matrix.kotlin b/Task/Zig-zag-matrix/Kotlin/zig-zag-matrix.kotlin new file mode 100644 index 0000000000..bcc5535c98 --- /dev/null +++ b/Task/Zig-zag-matrix/Kotlin/zig-zag-matrix.kotlin @@ -0,0 +1,37 @@ +// version 1.1.3 + +typealias Vector = IntArray +typealias Matrix = Array + +fun zigzagMatrix(n: Int): Matrix { + val result = Matrix(n) { Vector(n) } + var down = false + var count = 0 + for (col in 0 until n) { + if (down) + for (row in 0..col) result[row][col - row] = count++ + else + for (row in col downTo 0) result[row][col - row] = count++ + down = !down + } + for (row in 1 until n) { + if (down) + for (col in n - 1 downTo row) result[row + n - 1 - col][col] = count++ + else + for (col in row until n) result[row + n - 1 - col][col] = count++ + down = !down + } + return result +} +fun printMatrix(m: Matrix) { + for (i in 0 until m.size) { + for (j in 0 until m.size) print("%2d ".format(m[i][j])) + println() + } + println() +} + +fun main(args: Array) { + printMatrix(zigzagMatrix(5)) + printMatrix(zigzagMatrix(10)) +} diff --git a/Task/Zig-zag-matrix/MATLAB/zig-zag-matrix-1.m b/Task/Zig-zag-matrix/MATLAB/zig-zag-matrix-1.m deleted file mode 100644 index 7120658c08..0000000000 --- a/Task/Zig-zag-matrix/MATLAB/zig-zag-matrix-1.m +++ /dev/null @@ -1,64 +0,0 @@ -function matrix = zigZag(n) - - %This is very unintiutive. This algorithm parameterizes the - %zig-zagging movement along the matrix indicies. The easiest way to see - %what this algorithm does is to go through line-by-line and write out - %what the algorithm does on a peace of paper. - - matrix = zeros(n); - counter = 1; - flipCol = true; - flipRow = false; - - %This for loop does the top-diagonal of the matrix - for i = (2:n) - row = (1:i); - column = (1:i); - - %Causes the zig-zagging. Without these conditionals, you would end - %up with a diagonal matrix. To see what happens comment these conditionals out. - if flipCol - column = fliplr(column); - flipRow = true; - flipCol = false; - elseif flipRow - row = fliplr(row); - flipRow = false; - flipCol = true; - end - - %Selects a diagonal of the zig-zag matrix and places the correct - %integer value in each index along that diagonal - for j = (1:numel(row)) - matrix(row(j),column(j)) = counter; - counter = counter + 1; - end - end - - %This for loop does the bottom-diagonal of the matrix - for i = (2:n) - row = (i:n); - column = (i:n); - - %Causes the zig-zagging. Without these conditionals, you would end - %up with a diagonal matrix. To see what happens comment these conditionals out. - if flipCol - column = fliplr(column); - flipRow = true; - flipCol = false; - elseif flipRow - row = fliplr(row); - flipRow = false; - flipCol = true; - end - - %Selects a diagonal of the zig-zag matrix and places the correct - %integer value in each index along that diagonal - for j = (1:numel(row)) - matrix(row(j),column(j)) = counter; - counter = counter + 1; - end - end - - -end diff --git a/Task/Zig-zag-matrix/MATLAB/zig-zag-matrix-2.m b/Task/Zig-zag-matrix/MATLAB/zig-zag-matrix-2.m deleted file mode 100644 index 50618a0307..0000000000 --- a/Task/Zig-zag-matrix/MATLAB/zig-zag-matrix-2.m +++ /dev/null @@ -1,9 +0,0 @@ ->> zigZag(5) - -ans = - - 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 diff --git a/Task/Zig-zag-matrix/OoRexx/zig-zag-matrix.rexx b/Task/Zig-zag-matrix/OoRexx/zig-zag-matrix.rexx new file mode 100644 index 0000000000..7f878c5fef --- /dev/null +++ b/Task/Zig-zag-matrix/OoRexx/zig-zag-matrix.rexx @@ -0,0 +1,42 @@ +call printArray zigzag(3) +say +call printArray zigzag(4) +say +call printArray zigzag(5) + +::routine zigzag + use strict arg size + + data = .array~new(size, size) + row = 1 + col = 1 + + loop element = 0 to (size * size) - 1 + data[row, col] = element + -- even stripes + if (row + col) // 2 = 0 then do + if col < size then col += 1 + else row += 2 + if row > 1 then row -= 1 + end + -- odd rows + else do + if row < size then row += 1 + else col += 2 + if col > 1 then col -= 1 + end + end + + return data + +::routine printArray + use arg array + dimension = array~dimension(1) + loop i = 1 to dimension + line = "|" + loop j = 1 to dimension + line = line array[i, j]~right(2) + end + line = line "|" + say line + end diff --git a/Task/Zig-zag-matrix/Perl-6/zig-zag-matrix.pl6 b/Task/Zig-zag-matrix/Perl-6/zig-zag-matrix.pl6 index eba875b43b..f70ed524a7 100644 --- a/Task/Zig-zag-matrix/Perl-6/zig-zag-matrix.pl6 +++ b/Task/Zig-zag-matrix/Perl-6/zig-zag-matrix.pl6 @@ -1,5 +1,5 @@ sub MAIN($size as Int) { - my $t = Turtle.new(dir => northeast); + my $t = Turtle.new(dir => 1); my $counter = 0; for 1 ..^ $size -> $run { for ^$run { diff --git a/Task/Zig-zag-matrix/PowerShell/zig-zag-matrix.psh b/Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-1.psh similarity index 100% rename from Task/Zig-zag-matrix/PowerShell/zig-zag-matrix.psh rename to Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-1.psh diff --git a/Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-2.psh b/Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-2.psh new file mode 100644 index 0000000000..969f0cfa6a --- /dev/null +++ b/Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-2.psh @@ -0,0 +1 @@ +zigzag 5 | Format-Wide {"{0,2}" -f $_} -Column 5 -Force diff --git a/Task/Zig-zag-matrix/Scala/zig-zag-matrix-1.scala b/Task/Zig-zag-matrix/Scala/zig-zag-matrix-1.scala index 7e5d1c0c25..52d81c4ee4 100644 --- a/Task/Zig-zag-matrix/Scala/zig-zag-matrix-1.scala +++ b/Task/Zig-zag-matrix/Scala/zig-zag-matrix-1.scala @@ -1,10 +1,19 @@ -def zigzag(n:int) = { - var l = List[Tuple2[int,int]]() - (0 until n*n) foreach {i=>l = l + (i%n,i/n)} - l = l.sort{case ((x,y),(u,v)) => if (x+y == u+v) - if ((x+y) % 2 == 0) x a(y)(x) = i} - a -} + def zigzag(n: Int): Array[Array[Int]] = { + val l = for (i <- 0 until n*n) yield (i%n, i/n) + val lSorted = l.sortWith { + case ((x,y), (u,v)) => + if (x+y == u+v) + if ((x+y) % 2 == 0) x res(y)(x) = i + } + res + } + + zigzag(5).foreach{ + ar => ar.foreach(x => print("%3d".format(x))) + println + } diff --git a/Task/Zig-zag-matrix/Scala/zig-zag-matrix-2.scala b/Task/Zig-zag-matrix/Scala/zig-zag-matrix-2.scala index b087b071d6..88ba0b6165 100644 --- a/Task/Zig-zag-matrix/Scala/zig-zag-matrix-2.scala +++ b/Task/Zig-zag-matrix/Scala/zig-zag-matrix-2.scala @@ -1,10 +1,5 @@ -def zigzag(n:int) = { - var indices = List[Tuple2[Int,Int]]() - var array = new Array[Array[Int]](n,n) - - (0 until n*n).foldLeft(indices)((l,i) => l + (i%n,i/n)). - sort{case ((x,y),(u,v)) => if (x+y == u+v) - if ((x+y) % 2 == 0) x a(y)(x) = i; a} -} + 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 diff --git a/Task/Zig-zag-matrix/Sidef/zig-zag-matrix.sidef b/Task/Zig-zag-matrix/Sidef/zig-zag-matrix.sidef index d7eca2a07f..8fde43fb09 100644 --- a/Task/Zig-zag-matrix/Sidef/zig-zag-matrix.sidef +++ b/Task/Zig-zag-matrix/Sidef/zig-zag-matrix.sidef @@ -1,24 +1,21 @@ func zig_zag(w, h) { - var r = []; - var n = 0; + var r = [] + var n = 0 h.of { |e| w.of { |f| - [e-1, f-1] + [e, f] } - } \ - -> reduce('+') \ - -> sort { |a, b| + }.reduce('+').sort { |a, b| (a[0]+a[1] <=> b[0]+b[1]) || (a[0]+a[1] -> is_even ? a[0]<=>b[0] : a[1]<=>b[1]) - } \ - -> each { |a| - r[a[1]][a[0]] = n++; + }.each { |a| + r[a[1]][a[0]] = n++ } - return r; + return r } -zig_zag(5, 5).each {say .join('', {|i| "%4i" % i})}; +zig_zag(5, 5).each { say .join('', {|i| "%4i" % i}) } diff --git a/Task/Zig-zag-matrix/Zkl/zig-zag-matrix-1.zkl b/Task/Zig-zag-matrix/Zkl/zig-zag-matrix-1.zkl new file mode 100644 index 0000000000..d40500ccbc --- /dev/null +++ b/Task/Zig-zag-matrix/Zkl/zig-zag-matrix-1.zkl @@ -0,0 +1,11 @@ +fcn zz(n){ + grid := (0).pump(n,List, (0).pump(n,List).copy).copy(); + ri := Ref(0); + foreach d in ([1..n*2]){ + x:=(0).max(d - n); y:=(n - 1).min(d - 1); + (0).pump(d.min(n*2 - d),Void,'wrap(it){ + grid[if(d%2)y-it else x+it][if(d%2)x+it else y-it] = ri.inc(); + }); + } + grid.pump(String,'wrap(r){("%3s"*n+"\n").fmt(r.xplode())}); +} diff --git a/Task/Zig-zag-matrix/Zkl/zig-zag-matrix-2.zkl b/Task/Zig-zag-matrix/Zkl/zig-zag-matrix-2.zkl new file mode 100644 index 0000000000..018108d71d --- /dev/null +++ b/Task/Zig-zag-matrix/Zkl/zig-zag-matrix-2.zkl @@ -0,0 +1,7 @@ +fcn ceg(m){ + s := (0).pump(m*m,List).copy(); // copy to make writable + rn := Ref(0); + [[(i,j); [0..m*2-1]; '{[(0).max(i-m+1) .. i.min(m-1)]}; + '{ s[ if(i.isOdd) j*(m-1)+i else (i-j)*m+j ] = rn.inc(); }]]; + s.pump(String,T(Void.Read,m-1), ("%3s"*m+"\n").fmt); +} diff --git a/Task/Zig-zag-matrix/Zkl/zig-zag-matrix-3.zkl b/Task/Zig-zag-matrix/Zkl/zig-zag-matrix-3.zkl new file mode 100644 index 0000000000..c19d532a78 --- /dev/null +++ b/Task/Zig-zag-matrix/Zkl/zig-zag-matrix-3.zkl @@ -0,0 +1,7 @@ +fcn ceg2(m){ + rn := Ref(0); + [[(i,j); [0..m*2-1]; '{[(0).max(i-m+1) .. i.min(m-1)]}; + '{ T( if(i.isOdd) j*(m-1)+i else (i-j)*m+j;, rn.inc() ) }]] + .sort(fcn([(a,_)], [(b,_)]){ a

    =grid.len()) return(True); // success: reached bottom row + return(( not grid[x] .bitAnd(BWALL) and fill(grid,x + m,m) ) or // down + ( not grid[x] .bitAnd(RWALL) and fill(grid,x + 1,m) ) or // right + ( not grid[x - 1].bitAnd(RWALL) and fill(grid,x - 1,m) ) or // left + ( not grid[x - m].bitAnd(BWALL) and fill(grid,x - m,m) )); // up +} +fcn percolate(grid,m){ + i:=0; while(i; + +my $𝘒 = perctest(15); +.fmt("%-2s").say for @perc; +say "𝘱 = 0.5, 𝘕 = 15, 𝘒 = $𝘒\n"; + +my $trials = 5; +for 10, 30, 100, 300, 1000 -> $𝘕 { + my $𝘒 = ( [+] perctest($𝘕) xx $trials ) / $trials; + say "𝘱 = 0.5, trials = $trials, 𝘕 = $𝘕, 𝘒 = $𝘒"; +} + +sub infix: ( $a, $b ) { $a.defined && ($a eq $b) } + +sub perctest ( $grid ) { + generate $grid; + my $block = 1; + for ^$grid X ^$grid -> ($y, $x) { + fill( [$x, $y], $block++ ) if @perc[$y; $x] eq $fill + } + ($block - 1) / $grid²; +} + +sub generate ( $grid ) { + @perc = (); + @perc.push: [ ( rand < .5 ?? '.' !! $fill ) xx $grid ] for ^$grid; +} + +sub fill ( @cur, $block ) { + @perc[@cur[1]; @cur[0]] = $block; + my @stack; + my $current = @cur; + + loop { + if my $dir = direction( $current ) { + @stack.push: $current; + $current = move $dir, $current, $block + } + else { + return unless @stack; + $current = @stack.pop + } + } + + sub direction( [$x, $y] ) { + ( Down if @perc[$y + 1][$x] deq $fill ) || + ( Left if @perc[$y][$x - 1] deq $fill ) || + ( Right if @perc[$y][$x + 1] deq $fill ) || + ( Up if @perc[$y - 1][$x] deq $fill ) || + DeadEnd + } + + sub move ( $dir, @cur, $block ) { + my ( $x, $y ) = @cur; + given $dir { + when Up { @perc[--$y; $x] = $block } + when Down { @perc[++$y; $x] = $block } + when Left { @perc[$y; --$x] = $block } + when Right { @perc[$y; ++$x] = $block } + } + [$x, $y] + } +} diff --git a/Task/Percolation-Mean-cluster-density/Zkl/percolation-mean-cluster-density-1.zkl b/Task/Percolation-Mean-cluster-density/Zkl/percolation-mean-cluster-density-1.zkl new file mode 100644 index 0000000000..5c990de6c3 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/Zkl/percolation-mean-cluster-density-1.zkl @@ -0,0 +1,29 @@ +const X=-1; // the sentinal that marks an untouched cell +var C,N,NN,P; +fcn createC(n,p){ + N,P=n,p; NN=N*N; + C=NN.pump(List.createLong(NN),0); // vector of ints + foreach n in (NN){ C[n]=X*(Float.random(1)<=P) } // X is the sentinal +} +fcn showCluster{ + alpha:="-ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; + foreach n in ([0..NN,N]){ C[n,N].pump(String,alpha.get).println() } +} +fcn countClusters{ + clusters:=0; + foreach n in (NN){ + if(X!=C[n]) continue; + fcn(n,v){ + if((0<=n Field -> (Field, [(Int,Int)]) percolateR [] f = (f, []) -percolateR seep f = percolateR - (concat $ fmap neighbors validSeep) - (f // map (\p -> (p,'.')) validSeep) where - neighbors p@(r,c) = [(r-1,c), (r+1,c), (r, c-1), (r, c+1)] - ((rLo,cLo),(rHi,cHi)) = bounds f - validSeep = filter (\p@(r,c) -> r >= rLo && - r <= rHi && - c >= cLo && - c <= cHi && - f!p == ' ') $ nub $ sort seep +percolateR seep f = + let ((xLo,yLo),(xHi,yHi)) = bounds f + validSeep = filter (\p@(x,y) -> x >= xLo + && x <= xHi + && y >= yLo + && y <= yHi + && f!p == ' ') $ nub $ sort seep --- Percolate a field; Return the percolated field. + neighbors (x,y) = [(x,y-1), (x,y+1), (x-1,y), (x+1,y)] + + in percolateR + (concatMap neighbors validSeep) + (f // map (\p -> (p,'.')) validSeep) + +-- Percolate a field. Return the percolated field. percolate :: Field -> Field percolate start = - let ((_,_),(_,cHi)) = bounds start - (final, _) = percolateR [(0,c) | c <- [0..cHi]] start + let ((_,_),(xHi,_)) = bounds start + (final, _) = percolateR [(x,0) | x <- [0..xHi]] start in final -- Generate a random field. -randomField :: Int -> Int -> Double -> Rand StdGen Field -randomField rows cols threshold = do - rnd <- replicateM rows (replicateM cols $ getRandomR (0.0, 1.0)) - return $ array ((0,0), (rows-1, cols-1)) - [((r,c), if rnd !! r !! c < threshold then ' ' - else '#') - | r <- [0..rows-1], c <- [0..cols-1] ] +initField :: Int -> Int -> Double -> Rand StdGen Field +initField w h threshold = do + frnd <- fmap (\rv -> if rv getRandoms + return $ listArray ((0,0), (w-1, h-1)) frnd --- Assess whether or not percolation reached bottom of field. -leaky :: Field -> Bool -leaky f = '.' `elem` [f!(rHi,c) | c <- [cLo..cHi]] where - ((_,cLo),(rHi,cHi)) = bounds f +-- Get a list of "leaks" from the bottom of a field. +leaks :: Field -> [Bool] +leaks f = + let ((xLo,_),(xHi,yHi)) = bounds f + in [f!(x,yHi)=='.'| x <- [xLo..xHi]] -- Run test once; Return bool indicating success or failure. oneTest :: Int -> Int -> Double -> Rand StdGen Bool -oneTest rows cols threshold = - leaky <$> percolate <$> randomField rows cols threshold +oneTest w h threshold = + or.leaks.percolate <$> initField w h threshold --- Run test multple times; Return the number of tests that pass +-- Run test multple times; Return the number of tests that pass. multiTest :: Int -> Int -> Int -> Double -> Rand StdGen Double -multiTest repeats rows cols threshold = do - x <- replicateM repeats $ oneTest rows cols threshold - let leakyCount = length $ filter (==True) x - return $ fromIntegral leakyCount / fromIntegral repeats +multiTest testCount w h threshold = do + results <- replicateM testCount $ oneTest w h threshold + let leakyCount = length $ filter id results + return $ fromIntegral leakyCount / fromIntegral testCount +-- Display a field with walls and leaks. showField :: Field -> IO () -showField a = mapM_ print [ [ a!(r,c) | c <- [cLo..cHi]] | r <- [rLo..rHi]] - where ((rLo,cLo),(rHi,cHi)) = bounds a +showField a = do + let ((xLo,yLo),(xHi,yHi)) = bounds a + mapM_ print [ [ a!(x,y) | x <- [xLo..xHi]] | y <- [yLo..yHi]] main :: IO () main = do g <- getStdGen - let (startField, g2) = runRand (randomField 15 15 0.6) g - putStrLn "Unpercolated field with 0.6 threshold." + let w = 15 + h = 15 + threshold = 0.6 + (startField, g2) = runRand (initField w h threshold) g + + putStrLn ("Unpercolated field with " ++ show threshold ++ " threshold.") putStrLn "" showField startField @@ -72,12 +79,17 @@ main = do putStrLn "" showField $ percolate startField + let testCount = 10000 + densityCount = 10 + putStrLn "" - putStrLn "Results of running percolation test 10000 times with thresholds ranging from 0.0 to 1.0 ." - let d = 10 - let ns = [0..10] - let tests = sequence [multiTest 10000 15 15 v - | n <- ns, - let v = fromIntegral n / fromIntegral d ] - let results = zip ns (evalRand tests g2) - mapM_ print [format ("p=" % int % "/" % int % " -> " % fixed 4) n d r | (n,r) <- results] + putStrLn ( "Results of running percolation test " ++ show testCount + ++ " times with thresholds ranging from 0/" ++ show densityCount + ++ " to " ++ show densityCount ++ "/" ++ show densityCount ++ " .") + + let densities = [0..densityCount] + tests = sequence [multiTest testCount w h v + | density <- densities, + let v = fromIntegral density / fromIntegral densityCount ] + results = zip densities (evalRand tests g2) + mapM_ print [format ("p=" % int % "/" % int % " -> " % fixed 4) density densityCount x | (density,x) <- results] diff --git a/Task/Percolation-Site-percolation/Perl-6/percolation-site-percolation.pl6 b/Task/Percolation-Site-percolation/Perl-6/percolation-site-percolation.pl6 new file mode 100644 index 0000000000..510f3b88ae --- /dev/null +++ b/Task/Percolation-Site-percolation/Perl-6/percolation-site-percolation.pl6 @@ -0,0 +1,64 @@ +my $block = '▒'; +my $water = '+'; +my $pore = ' '; +my $grid = 15; +my @site; + +enum Direction ; + +say 'Sample percolation at .6'; +percolate(.6); +.join.say for @site; +say "\n"; + +my $tests = 1000; +say "Doing $tests trials at each porosity:"; +for .1, .2 ... 1 -> $p { + printf "p = %0.1f: %0.3f\n", $p, (sum percolate($p) xx $tests) / $tests +} + +sub infix: ( $a, $b ) { $a.defined && ($a eq $b) } + +sub percolate ( $prob = .6 ) { + @site[0] = [$pore xx $grid]; + @site[$grid + 1] = [$pore xx $grid]; + + for ^$grid X 1..$grid -> ($x, $y) { + @site[$y;$x] = rand < $prob ?? $pore !! $block + } + @site[0;0] = $water; + + my @stack; + my $current = [0;0]; + + loop { + if my $dir = direction( $current ) { + @stack.push: $current; + $current = move( $dir, $current ) + } + else { + return 0 unless @stack; + $current = @stack.pop + } + return 1 if $current[1] > $grid + } + + sub direction( [$x, $y] ) { + (Down if @site[$y + 1][$x] deq $pore) || + (Left if @site[$y][$x - 1] deq $pore) || + (Right if @site[$y][$x + 1] deq $pore) || + (Up if @site[$y - 1][$x] deq $pore) || + DeadEnd + } + + sub move ( $dir, @cur ) { + my ( $x, $y ) = @cur; + given $dir { + when Up { @site[--$y][$x] = $water } + when Down { @site[++$y][$x] = $water } + when Left { @site[$y][--$x] = $water } + when Right { @site[$y][++$x] = $water } + } + [$x, $y] + } +} diff --git a/Task/Percolation-Site-percolation/Zkl/percolation-site-percolation.zkl b/Task/Percolation-Site-percolation/Zkl/percolation-site-percolation.zkl new file mode 100644 index 0000000000..5fc9e3a3e0 --- /dev/null +++ b/Task/Percolation-Site-percolation/Zkl/percolation-site-percolation.zkl @@ -0,0 +1,29 @@ +fcn makeGrid(m,n,p){ + grid:=Data((m+1)*(n+1)); // first row and right edges are buffers + grid.write(" "*m); grid.write("\r"); + do(n){ + do(m){ grid.write(((0.0).random(1)=grid.len() or + ff(grid,x+m,m) or ff(grid,x+1,m) or ff(grid,x-1,m) or ff(grid,x-m,m)); +} +fcn percolate(grid,m){ + x:=m+1; i:=0; while(i bool on perfect(n) -- isFactor :: integer -> bool script isFactor - on lambda(x) + on |λ|(x) n mod x = 0 - end lambda + end |λ| end script -- quotient :: number -> number script quotient - on lambda(x) + on |λ|(x) n / x - end lambda + end |λ| end script -- sum :: number -> number -> number script sum - on lambda(a, b) + on |λ|(a, b) a + b - end lambda + end |λ| end script -- Integer factors of n below the square root - set lows to filter(isFactor, range(1, (n ^ (1 / 2)) as integer)) + set lows to filter(isFactor, enumFromTo(1, (n ^ (1 / 2)) as integer)) -- low and high factors (quotients of low factors) tested for perfection (n > 1) and (foldl(sum, 0, (lows & map(quotient, lows))) / 2 = n) end perfect --- TEST - +-- TEST ---------------------------------------------------------------------- on run - filter(perfect, range(1, 10000)) + filter(perfect, enumFromTo(1, 10000)) --> {6, 28, 496, 8128} end run +-- GENERIC FUNCTIONS --------------------------------------------------------- --- GENERIC LIBRARY FUNCTIONS +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) @@ -51,7 +65,7 @@ on filter(f, xs) set lng to length of xs repeat with i from 1 to lng set v to item i of xs - if lambda(v, i, xs) then set end of lst to v + if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell @@ -63,7 +77,7 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -75,26 +89,12 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then - set d to -1 - else - set d to 1 - end if - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range - -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) @@ -102,7 +102,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Perfect-numbers/BASIC/perfect-numbers.basic b/Task/Perfect-numbers/BASIC/perfect-numbers-1.basic similarity index 100% rename from Task/Perfect-numbers/BASIC/perfect-numbers.basic rename to Task/Perfect-numbers/BASIC/perfect-numbers-1.basic diff --git a/Task/Perfect-numbers/BASIC/perfect-numbers-2.basic b/Task/Perfect-numbers/BASIC/perfect-numbers-2.basic new file mode 100644 index 0000000000..796e3fdf30 --- /dev/null +++ b/Task/Perfect-numbers/BASIC/perfect-numbers-2.basic @@ -0,0 +1,6 @@ +2000 LET SUM=0 +2010 FOR F=1 TO N-1 +2020 IF N/F=INT (N/F) THEN LET SUM=SUM+F +2030 NEXT F +2040 LET PERFECT=SUM=N +2050 RETURN diff --git a/Task/Perfect-numbers/Eiffel/perfect-numbers-1.e b/Task/Perfect-numbers/Eiffel/perfect-numbers-1.e deleted file mode 100644 index aa0d2b2ec6..0000000000 --- a/Task/Perfect-numbers/Eiffel/perfect-numbers-1.e +++ /dev/null @@ -1,24 +0,0 @@ -class - PERFECT_NUMBERS -feature - perfect(n:INTEGER):BOOLEAN - require - n_positive: n>0 - local - sum, i: INTEGER - do - from - i:=1 - until - i=n - loop - if n\\i=0 then - sum:=sum+i - end - i:= i+1 - end - if sum= n then - RESULT:= TRUE - end - end -end diff --git a/Task/Perfect-numbers/Eiffel/perfect-numbers-2.e b/Task/Perfect-numbers/Eiffel/perfect-numbers-2.e deleted file mode 100644 index 36573e74bf..0000000000 --- a/Task/Perfect-numbers/Eiffel/perfect-numbers-2.e +++ /dev/null @@ -1,20 +0,0 @@ -class - APPLICATION -inherit - ARGUMENTS -create - make -feature - make - do - create perfect - io.put_string ("%N 6 is perfect...%T") - io.put_boolean (perfect.perfect (6)) - io.put_string ("%N77 is perfect...%T") - io.put_boolean (perfect.perfect (77)) - io.put_string ("%N496 is perfect...%T") - io.put_boolean (perfect.perfect (496)) - - end - perfect: PERFECT_NUMBERS -end diff --git a/Task/Perfect-numbers/Elena/perfect-numbers.elena b/Task/Perfect-numbers/Elena/perfect-numbers.elena index e1e69bc556..62b4580105 100644 --- a/Task/Perfect-numbers/Elena/perfect-numbers.elena +++ b/Task/Perfect-numbers/Elena/perfect-numbers.elena @@ -1,20 +1,19 @@ -#import system. -#import system'routines. -#import system'math. -#import extensions. +import system'routines. +import system'math. +import extensions. -#class(extension)extension +extension extension { - #method is &perfect - = 1 repeat &till:self &each: n [ (self mod:n == 0) iif:n:0 ] summarize:(Integer new) == self. + isPerfect + = 1 till:self repeat(:n)( (self mod:n == 0) iif(n,0) ); summarize(Integer new) == self. } -#symbol program = +program = [ - 1 till:10000 &doEach: n + 1 till:10000 do(:n) [ - (n is &perfect) - ? [ console writeLine:n:" is perfect". ]. + if(n isPerfect) + [ console printLine(n," is perfect") ] ]. console readChar. diff --git a/Task/Perfect-numbers/Haskell/perfect-numbers-2.hs b/Task/Perfect-numbers/Haskell/perfect-numbers-2.hs index df87da5507..cc72b7a288 100644 --- a/Task/Perfect-numbers/Haskell/perfect-numbers-2.hs +++ b/Task/Perfect-numbers/Haskell/perfect-numbers-2.hs @@ -1,15 +1,19 @@ -perfect = map (\x -> (2^x - 1) * (2^(x - 1))) $ - filter (\x -> isPrime x && isPrime (2^x - 1)) maybe_prime where - maybe_prime = scanl1 (+) (2:1:cycle [2,2,4,2,4,2,4,6]) - isPrime n = all ((/=0).(n`mod`)) $ - takeWhile (\x -> x*x <= n) maybe_prime +perfect = + (\x -> (2 ^ x - 1) * (2 ^ (x - 1))) <$> + filter (\x -> isPrime x && isPrime (2 ^ x - 1)) maybe_prime + where + maybe_prime = scanl1 (+) (2 : 1 : cycle [2, 2, 4, 2, 4, 2, 4, 6]) + isPrime n = all ((/= 0) . (n `mod`)) $ takeWhile (\x -> x * x <= n) maybe_prime -isPerfect n = f n perfect where - f n (p:ps) = case compare n p of - EQ -> True - LT -> False - GT -> f n ps +isPerfect n = f n perfect + where + f n (p:ps) = + case compare n p of + EQ -> True + LT -> False + GT -> f n ps +main :: IO () main = do - mapM_ print $ take 10 perfect - mapM_ print $ map (\x -> (x, isPerfect x)) [6,27,28,29,496,8128,8129] + mapM_ print $ take 10 perfect + mapM_ (print . (\x -> (x, isPerfect x))) [6, 27, 28, 29, 496, 8128, 8129] diff --git a/Task/Perfect-numbers/jq/perfect-numbers.jq b/Task/Perfect-numbers/Jq/perfect-numbers.jq similarity index 100% rename from Task/Perfect-numbers/jq/perfect-numbers.jq rename to Task/Perfect-numbers/Jq/perfect-numbers.jq diff --git a/Task/Perfect-numbers/Kotlin/perfect-numbers.kotlin b/Task/Perfect-numbers/Kotlin/perfect-numbers.kotlin new file mode 100644 index 0000000000..c1ce0964d1 --- /dev/null +++ b/Task/Perfect-numbers/Kotlin/perfect-numbers.kotlin @@ -0,0 +1,24 @@ +// version 1.0.6 + +fun isPerfect(n: Int): Boolean = when { + n < 2 -> false + n % 2 == 1 -> false // there are no known odd perfect numbers + else -> { + var tot = 1 + var q: Int + for (i in 2 .. Math.sqrt(n.toDouble()).toInt()) { + if (n % i == 0) { + tot += i + q = n / i + if (q > i) tot += q + } + } + n == tot + } + } + +fun main(args: Array) { + // expect a run time of about 6 minutes on a typical laptop + println("The first five perfect numbers are:") + for (i in 2 .. 33550336) if (isPerfect(i)) print("$i ") +} diff --git a/Task/Perfect-numbers/Nimrod/perfect-numbers.nimrod b/Task/Perfect-numbers/Nimrod/perfect-numbers.nimrod deleted file mode 100644 index bed6c11f8a..0000000000 --- a/Task/Perfect-numbers/Nimrod/perfect-numbers.nimrod +++ /dev/null @@ -1,14 +0,0 @@ -import math - -proc isperfect(n: int): bool = - let max: int = (sqrt(n.toFloat)).toInt - var sum: int = 1 - for i in 2..max: - if n mod i == 0: - let q: int = n div i - sum += (i + q) - return (n == sum) - -for i in 2..10_000: - if isperfect(i): - echo(i) diff --git a/Task/Perfect-numbers/OoRexx/perfect-numbers.rexx b/Task/Perfect-numbers/OoRexx/perfect-numbers.rexx new file mode 100644 index 0000000000..d089f93832 --- /dev/null +++ b/Task/Perfect-numbers/OoRexx/perfect-numbers.rexx @@ -0,0 +1,17 @@ +-- first perfect number over 10000 is 33550336...let's not be crazy +loop i = 1 to 10000 + if perfectNumber(i) then say i "is a perfect number" +end + +::routine perfectNumber + use strict arg n + + sum = 0 + + -- the largest possible factor is n % 2, so no point in + -- going higher than that + loop i = 1 to n % 2 + if n // i == 0 then sum += i + end + + return sum = n diff --git a/Task/Perfect-numbers/Perl/perfect-numbers-7.pl b/Task/Perfect-numbers/Perl/perfect-numbers-7.pl index 0f6893d989..44607163b3 100644 --- a/Task/Perfect-numbers/Perl/perfect-numbers-7.pl +++ b/Task/Perfect-numbers/Perl/perfect-numbers-7.pl @@ -1,13 +1,10 @@ -use ntheory qw(is_mersenne_prime valuation hammingweight is_power sqrtint); +use ntheory qw(is_mersenne_prime valuation); sub is_even_perfect { my ($n) = @_; - - $n % 2 == 0 || return; - - my $square = 8 * $n + 1; - is_power($square, 2) || return; - - my $k = (sqrtint($square) + 1) / 2; - hammingweight($k) == 1 && is_mersenne_prime(valuation($k, 2)); + my $v = valuation($n, 2) || return; + my $m = ($n >> $v); + ($m & ($m + 1)) && return; + ($m >> $v) == 1 || return; + is_mersenne_prime($v + 1); } diff --git a/Task/Perfect-numbers/Rust/perfect-numbers.rust b/Task/Perfect-numbers/Rust/perfect-numbers.rust new file mode 100644 index 0000000000..a6971bfead --- /dev/null +++ b/Task/Perfect-numbers/Rust/perfect-numbers.rust @@ -0,0 +1,21 @@ +fn main ( ) { + fn factor_sum(n: i32) -> i32 { + let mut v = Vec::new(); //create new empty array + for x in 1..n-1 { //test vaules 1 to n-1 + if n%x == 0 { //if current x is a factor of n + v.push(x); //add x to the array + } + } + let mut sum = v.iter().sum(); //iterate over array and sum it up + return sum; + } + + fn perfect_nums(n: i32) { + for x in 2..n { //test numbers from 1-n + if factor_sum(x) == x {//call factor_sum on each value of x, if return value is = x + println!("{} is a perfect number.", x); //print value of x + } + } + } + perfect_nums(10000); +} diff --git a/Task/Perfect-numbers/Zkl/perfect-numbers.zkl b/Task/Perfect-numbers/Zkl/perfect-numbers.zkl new file mode 100644 index 0000000000..158a214c6f --- /dev/null +++ b/Task/Perfect-numbers/Zkl/perfect-numbers.zkl @@ -0,0 +1,2 @@ +fcn isPerfectNumber1(n) + { n == [1..n-1].filter('wrap(i){ n % i == 0 }).sum(); } diff --git a/Task/Permutation-test/jq/permutation-test-1.jq b/Task/Permutation-test/Jq/permutation-test-1.jq similarity index 100% rename from Task/Permutation-test/jq/permutation-test-1.jq rename to Task/Permutation-test/Jq/permutation-test-1.jq diff --git a/Task/Permutation-test/jq/permutation-test-2.jq b/Task/Permutation-test/Jq/permutation-test-2.jq similarity index 100% rename from Task/Permutation-test/jq/permutation-test-2.jq rename to Task/Permutation-test/Jq/permutation-test-2.jq diff --git a/Task/Permutation-test/jq/permutation-test-3.jq b/Task/Permutation-test/Jq/permutation-test-3.jq similarity index 100% rename from Task/Permutation-test/jq/permutation-test-3.jq rename to Task/Permutation-test/Jq/permutation-test-3.jq diff --git a/Task/Permutation-test/Kotlin/permutation-test.kotlin b/Task/Permutation-test/Kotlin/permutation-test.kotlin new file mode 100644 index 0000000000..ffd4181578 --- /dev/null +++ b/Task/Permutation-test/Kotlin/permutation-test.kotlin @@ -0,0 +1,24 @@ +// version 1.1.2 + +val data = intArrayOf( + 85, 88, 75, 66, 25, 29, 83, 39, 97, + 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 +) + +fun pick(at: Int, remain: Int, accu: Int, treat: Int): Int { + if (remain == 0) return if (accu > treat) 1 else 0 + return pick(at - 1, remain - 1, accu + data[at - 1], treat) + + if (at > remain) pick(at - 1, remain, accu, treat) else 0 +} + +fun main(args: Array) { + var treat = 0 + var total = 1.0 + for (i in 0..8) treat += data[i] + for (i in 19 downTo 11) total *= i + for (i in 9 downTo 1) total /= i + val gt = pick(19, 9, 0, treat) + val le = (total - gt).toInt() + System.out.printf("<= : %f%% %d\n", 100.0 * le / total, le) + System.out.printf(" > : %f%% %d\n", 100.0 * gt / total, gt) +} diff --git a/Task/Permutation-test/Phix/permutation-test.phix b/Task/Permutation-test/Phix/permutation-test.phix new file mode 100644 index 0000000000..07c42b307d --- /dev/null +++ b/Task/Permutation-test/Phix/permutation-test.phix @@ -0,0 +1,20 @@ +constant data = {85, 88, 75, 66, 25, 29, 83, 39, 97, + 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 } + +function pick(int at, int remain, int accu, int treat) + if remain=0 then return iff(accu>treat?1:0) end if + return pick(at-1, remain-1, accu+data[at], treat) + + iff(at>remain?pick(at-1, remain, accu, treat):0) +end function + +int treat = 0, le, gt +atom total = 1; +for i=1 to 9 do treat += data[i] end for +for i=19 to 11 by -1 do total *= i end for +for i=9 to 1 by -1 do total /= i end for + +gt = pick(19, 9, 0, treat) +le = total - gt; + +printf(1,"<= : %f%% %d\n > : %f%% %d\n", + {100*le/total, le, 100*gt/total, gt}) diff --git a/Task/Permutation-test/REXX/permutation-test.rexx b/Task/Permutation-test/REXX/permutation-test.rexx index 6701427568..9c293018b9 100644 --- a/Task/Permutation-test/REXX/permutation-test.rexx +++ b/Task/Permutation-test/REXX/permutation-test.rexx @@ -1,30 +1,32 @@ -/*REXX program performs a permutation test on N + M subjects (volunteers): */ - /* ↑ ↑ */ - /* │ │ */ - /* │ └─────control population. */ - /* └────────treatment population. */ +/*REXX program performs a permutation test on N + M subjects (volunteers): */ + /* ↑ ↑ */ + /* │ │ */ + /* │ └─────control population. */ + /* └────────treatment population. */ n=9 -data=85 88 75 66 25 29 83 39 97 68 41 10 49 16 65 32 92 28 98 -w=words(data); m=w-n -say 'volunteer population given treatment:' right(n,length(w)) -say ' control population given a placebo:' right(m,length(w)) +data= 85 88 75 66 25 29 83 39 97 68 41 10 49 16 65 32 92 28 98 +w=words(data); m=w-n +say 'w=' w +say 'volunteer population given treatment:' right(n, length(w) ) +say ' control population given a placebo:' right(m, length(w) ) say -say 'treatment population efficacy % (percentages):' subword(data,1,n) -say ' control population placebo % (percentages):' subword(data,n+1) +say 'treatment population efficacy % (percentages):' subword(data, 1, n) +say ' control population placebo % (percentages):' subword(data, n+1 ) say - do v= 0 for w ; #.v=word(data,v+1) ; end -treat=0; do i= 0 to n-1 ; treat=treat+#.i ; end - tot=1; do j=19 to m+1 by -1 ; tot=tot*j ; end - do k= 9 to 1 by -1 ; tot=tot/k ; end -gt=picker(n+m, n, 0) -le=tot-gt -say "<= " format(100*le/tot,,3)'%' le /*display number with 3 decimal places.*/ -say " > " format(100*gt/tot,,3)'%' gt /* " " " " " " */ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -picker: procedure expose #. treat; parse arg it,rest,eff - if rest==0 then return eff>treat - if it>rest then q=picker(it-1, rest, eff) + do v= 0 for w ; #.v=word(data, v+1) ; end +treat=0; do i= 0 to n-1 ; treat=treat + #.i ; end + tot=1; do j= w to m+1 by -1 ; tot=tot * j ; end + do k=w%2 to 1 by -1 ; tot=tot / k ; end + +GT=picker(n+m, n, 0) /*compute the GT value from PICKER func*/ +LE=tot - GT /* " " LE " via subtraction.*/ +say "<= " format(100 * LE / tot, ,3)'%' LE /*display number with 3 decimal places.*/ +say " > " format(100 * GT / tot, ,3)'%' GT /* " " " " " " */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +picker: procedure expose #. treat; parse arg it,rest,eff /*get args.*/ + if rest==0 then return eff > treat /*Zero ? */ + if it>rest then q=picker(it-1, rest, eff) /*recurse. */ else q=0 - itP=it-1 - return picker(itP, rest-1, eff+#.itP) + q + itP=it - 1 /*temp var.*/ + return picker(itP, rest - 1, eff+#.itP) + q /*recurse. */ diff --git a/Task/Permutation-test/Sidef/permutation-test.sidef b/Task/Permutation-test/Sidef/permutation-test.sidef index 13072c3856..2767896ce4 100644 --- a/Task/Permutation-test/Sidef/permutation-test.sidef +++ b/Task/Permutation-test/Sidef/permutation-test.sidef @@ -1,20 +1,20 @@ func statistic(ab, a) { - var(sumab, suma) = (ab.sum, a.sum); + var(sumab, suma) = (ab.sum, a.sum) suma/a.size - ((sumab-suma) / (ab.size-a.size)) } func permutationTest(a, b) { - var ab = (a + b); - var tobs = statistic(ab, a); - var under = (var count = 0); - ab.combinations(a.len).each { |perm| - statistic(ab, perm) <= tobs && (under += 1); - count += 1; - }; - under * 100 / count; + var ab = (a + b) + var tobs = statistic(ab, a) + var under = (var count = 0) + ab.combinations(a.len, {|*perm| + statistic(ab, perm) <= tobs && (under += 1) + count += 1 + }) + under * 100 / count } -var treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]; -var controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]; -var under = permutationTest(treatmentGroup, controlGroup); -say ("under=%.2f%%, over=%.2f%%" % (under, 100 - under)); +var treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97] +var controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98] +var under = permutationTest(treatmentGroup, controlGroup) +say ("under=%.2f%%, over=%.2f%%" % (under, 100 - under)) diff --git a/Task/Permutation-test/Zkl/permutation-test.zkl b/Task/Permutation-test/Zkl/permutation-test.zkl new file mode 100644 index 0000000000..7262b87679 --- /dev/null +++ b/Task/Permutation-test/Zkl/permutation-test.zkl @@ -0,0 +1,12 @@ +fcn permutationTest(a,b){ + ab := a.extend(b); + tObs := a.sum(0); + combs := Utils.Helpers.pickNFrom(a.len(),ab); // 92,378 + under := combs.reduce('wrap(sum,perm){ sum+(perm.sum(0) <= tObs) },0); + 100.0 * under / combs.len(); +} + +treatmentGroup := T(85, 88, 75, 66, 25, 29, 83, 39, 97); +controlGroup := T(68, 41, 10, 49, 16, 65, 32, 92, 28, 98); +under := permutationTest(treatmentGroup, controlGroup); +println("Under =%6.2f%%\nOver =%6.2f%%".fmt(under, 100.0 - under)); diff --git a/Task/Permutations-Derangements/360-Assembly/permutations-derangements.360 b/Task/Permutations-Derangements/360-Assembly/permutations-derangements.360 new file mode 100644 index 0000000000..030c0cb60f --- /dev/null +++ b/Task/Permutations-Derangements/360-Assembly/permutations-derangements.360 @@ -0,0 +1,252 @@ +* Permutations/Derangements 01/04/2017 +DERANGE CSECT + USING DERANGE,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + XPRNT PG1,L'PG1 print title + LA R1,4 4 + LA R2,1 1 : combinations print + BAL R14,DERGEN call dergen + STH R0,COUNT count=dergen(4,1) + XPRNT PG2,L'PG2 print table headings + XPRNT PG3,L'PG3 print hyphens + SR R4,R4 + STH R4,II ii=0 + DO WHILE=(CH,R4,LE,=H'9') do ii=0 to 9 + MVC PG,=CL80' ' clear buffer + XDECO R4,PG edit ii + LR R1,R4 ii + LA R2,0 0 : no combination print + BAL R14,DERGEN dergen(ii,0) + XDECO R0,PG+12 edit + LH R1,II ii + BAL R14,SUBFACT subfact(ii) + XDECO R0,PG+24 edit + XPRNT PG,L'PG print + LH R4,II ii + LA R4,1(R4) i+1 + STH R4,II i=i+1 + ENDDO , enddo i + LA R0,12 12 + STH R0,II ii=12 + MVC PG,=CL16'!xx=' init buffer + XDECO R0,XDEC edit ii + MVC PG+1(2),XDEC+10 output + LH R1,II ii + BAL R14,SUBFACT subfact(ii) + XDECO R0,PG+4 edit subfact(ii) + XPRNT PG,16 print + L R13,4(0,R13) restore previous savearea pointer + LM R14,R12,12(R13) restore previous context + XR R15,R15 rc=0 + BR R14 exit +*------- ---- ------------------------------------------- +DERGEN EQU * dergen(n,fprt) + ST R14,SAVEDG + ST R1,N n + ST R2,FPRT fprt + IF LTR,R1,Z,R1 THEN if n=0 then + LA R0,1 1 + B RETDG return(1) + ENDIF , endif + MVC C,=F'0' c=0 + LA R6,1 i=1 + DO WHILE=(C,R6,LE,N) do i=1 to 2 + LR R1,R6 i + SLA R1,1 + STH R6,A-2(R1) a(i)=i + STH R6,AO-2(R1) ao(i)=i + LA R6,1(R6) i++ + ENDDO , enddo i + L R1,N n + BAL R14,FACT + ST R0,FACTNM1 fact(n)-1 + SR R6,R6 i=0 + DO WHILE=(C,R6,LE,FACTNM1) do i=0 to fact(n)-1 + L R1,N n + BAL R14,NEXTPER call nextper(n) + MVI D,X'01' d=true + LA R7,1 + DO WHILE=(C,R7,LE,N) do j=1 to n + LR R1,R7 j + SLA R1,1 + LH R2,A-2(R1) a(j) + LH R3,AO-2(R1) ao(j) + IF CR,R2,EQ,R3 THEN if a(j)=ao(j) then + MVI D,X'00' d=false + ENDIF , endif + LA R7,1(R7) j++ + ENDDO , enddo j + IF CLI,D,EQ,X'01' THEN if d then + L R2,C c + LA R2,1(R2) c+1 + ST R2,C c=c+1 + IF CLI,FPRT+3,EQ,X'01' THEN if fprt=1 then + MVC PG,=CL80' ' clear buffer + LA R10,PG pgi=0 + LA R7,1 j=1 + DO WHILE=(C,R7,LE,N) do j=1 to n + LR R1,R7 j + SLA R1,1 + LH R2,A-2(R1) a(j) + XDECO R2,XDEC edit + MVC 0(1,R10),XDEC+11 output + LA R10,2(R10) pgi=pgi+2 + LA R7,1(R7) j++ + ENDDO , enddo j + XPRNT PG,L'PG print + ENDIF , endif + ENDIF , endif + LA R6,1(R6) i++ + ENDDO , enddo i + L R0,C c + B RETDG return(c) +RETDG L R14,SAVEDG + BR R14 +SAVEDG DS A +*------- ---- ------------------------------------------- +NEXTPER EQU * nextper(nk) + ST R14,SAVENP + ST R1,NK nk + BCTR R1,0 nk-1 + ST R1,NELEM nelem=nk-1 + IF C,R1,LT,=F'1' THEN if nelem<1 then + LA R0,0 return(0) + B RETNP + ENDIF , endif + L R8,NELEM nelem + BCTR R8,0 pos=nelem-1 +LOOPW1 EQU * while a(pos+1)>=a(pos+2) + LR R1,R8 pos + SLA R1,1 + LH R2,A(R1) a(pos+1) + CH R2,A+2(R1) if a(pos+1)a(pos+1) + BH ELOOPW2 then exit while + BCTR R9,0 last=last-1 + B LOOPW2 endwhile +ELOOPW2 LR R1,R8 pos + SLA R1,1 *2 + LA R2,A(R1) @a(pos+1) + LR R1,R9 last + SLA R1,1 + LA R3,A(R1) @a(last+1) + LH R0,0(R2) w=a(pos+1) + MVC 0(2,R2),0(R3) a(pos+1)=a(last+1) + STH R0,0(R3) a(last+1)=w + LA R1,1(R8) pos+1 + L R2,NELEM nelem + BAL R14,PERMREV call permrev(pos+1,nelem) +RETNP L R14,SAVENP + BR R14 +SAVENP DS A +*------- ---- ------------------------------------------- +PERMREV EQU * permrev(firstix,lastix) + LR R4,R1 xfirst + LR R5,R2 xlast + DO WHILE=(CR,R4,LT,R5) do while(xfirst= A%(pos+1) - pos -= 1 - IF pos < 0 THEN - PROC_Permutation_Reverse(A%(), 0, elementcount) - ENDPROC - ENDIF - ENDWHILE - last = elementcount - WHILE A%(last) <= A%(pos) - last -= 1 - ENDWHILE - SWAP A%(pos), A%(last) - PROC_Permutation_Reverse(A%(), pos+1, elementcount) - ENDPROC - - DEF PROC_Permutation_Reverse(A%(), firstindex, lastindex) - LOCAL first, last - first = firstindex - last = lastindex - WHILE first < last - SWAP A%(first), A%(last) - first += 1 - last -= 1 - ENDWHILE - ENDPROC - - DEF FN_Factorial(N) : IF (N = 1) OR (N = 0) THEN =1 ELSE = N * FN_Factorial(N-1) - - DEF FN_SubFactorial(N) : IF N=0 THEN =1 ELSE =N*FN_SubFactorial(N-1)+-1^N - - REM Or you could use: - REM DEF FN_SubFactorial(N) : IF N<1 THEN =1 ELSE =(N-1)*(FN_SubFactorial(N-1)+FN_SubFactorial(N-2)) diff --git a/Task/Permutations-Derangements/BBC-BASIC/permutations-derangements-2.bbc b/Task/Permutations-Derangements/BBC-BASIC/permutations-derangements-2.bbc deleted file mode 100644 index af47ed865d..0000000000 --- a/Task/Permutations-Derangements/BBC-BASIC/permutations-derangements-2.bbc +++ /dev/null @@ -1,26 +0,0 @@ -Derangements for the numbers 0,1,2,3 are: -1 0 3 2 -1 2 3 0 -1 3 0 2 -2 0 3 1 -2 3 0 1 -2 3 1 0 -3 0 1 2 -3 2 0 1 -3 2 1 0 - -Table of n, counted derangements, calculated derangements : - 0 1 1 - 1 0 0 - 2 1 1 - 3 2 2 - 4 9 9 - 5 44 44 - 6 265 265 - 7 1854 1854 - 8 14833 14833 - 9 133496 133496 - -There is no long int in BBC BASIC! -!20 = 8.95014632E17 -> diff --git a/Task/Permutations-Derangements/FreeBASIC/permutations-derangements.freebasic b/Task/Permutations-Derangements/FreeBASIC/permutations-derangements.freebasic new file mode 100644 index 0000000000..f390fa5b65 --- /dev/null +++ b/Task/Permutations-Derangements/FreeBASIC/permutations-derangements.freebasic @@ -0,0 +1,94 @@ +' version 08-04-2017 +' compile with: fbc -s console + +Sub Subfactorial(a() As ULongInt) + + Dim As ULong i + Dim As ULongInt num + + For i = 0 To UBound(a) + num = num * i + If (i And 1) = 1 Then + num -= 1 + Else + num += 1 + End If + a(i) = num + Next + +End Sub + +' Heap's algorithm non-recursive +Function perms_derange(n As ULong, flag As Long = 0) As ULongInt + ' fast upto n < 12 + If n = 0 Then Return 1 + + Dim As ULong i, j, c1, count + Dim As ULong a(0 To n -1), c(0 To n -1) + + For j = 0 To n -1 + a(j) = j + Next + + While i < n + If c(i) < i Then + If (i And 1) = 0 Then + Swap a(0), a(i) + Else + Swap a(c(i)), a(i) + End If + For j = 0 To n -1 + If a(j) = j Then j = 99 + Next + If j < 99 Then + count += 1 + If flag = 0 Then + c1 += 1 + For j = 0 To n -1 + Print a(j); + Next + If c1 > 12 Then + Print : c1 = 0 + Else + Print " "; + End If + End If + End If + c(i) += 1 + i = 0 + Else + c(i) = 0 + i += 1 + End If + Wend + If flag = 0 AndAlso c1 <> 0 Then Print + Return count + +End Function + +' ------=< MAIN >=------ + +Dim As ULong i, n = 4 +Dim As ULongInt subfac(20) + +Subfactorial(subfac()) + +Print "permutations derangements for n = "; n +i = perms_derange(n) +Print "count returned = "; i; " , !"; n; " calculated = "; subfac(n) + +Print +Print "count counted subfactorial" +Print "---------------------------" +For i = 0 To 9 + Print Using " ###: ######## ########"; i; perms_derange(i, 1); subfac(i) +Next +For i = 10 To 20 + Print Using " ###: ###################"; i; subfac(i) +Next + +' empty keyboard buffer +While InKey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Permutations-Derangements/Haskell/permutations-derangements-1.hs b/Task/Permutations-Derangements/Haskell/permutations-derangements-1.hs index de84bec584..30d7b21626 100644 --- a/Task/Permutations-Derangements/Haskell/permutations-derangements-1.hs +++ b/Task/Permutations-Derangements/Haskell/permutations-derangements-1.hs @@ -1,24 +1,33 @@ -import Control.Monad -import Data.List +import Control.Monad (forM_) + +import Data.List (permutations) -- Compute all derangements of a list -derangements xs = filter (and . zipWith (/=) xs) $ permutations xs +derangements + :: Eq a + => [a] -> [[a]] +derangements = (\x -> filter (and . zipWith (/=) x)) <*> permutations -- Compute the number of derangements of n elements +subfactorial + :: (Eq a, Num a) + => a -> a subfactorial 0 = 1 subfactorial 1 = 0 -subfactorial n = (n-1) * (subfactorial (n-1) + subfactorial (n-2)) +subfactorial n = (n - 1) * (subfactorial (n - 1) + subfactorial (n - 2)) -main = do - -- Generate and show all the derangements of four integers - print $ derangements [1..4] +main :: IO () +main +-- Generate and show all the derangements of four integers + = do + print $ derangements [1 .. 4] putStrLn "" - -- Print the count of derangements vs subfactorial - forM_ [1..9] $ \i -> - putStrLn $ show (length (derangements [1..i])) ++ " " ++ - show (subfactorial i) + forM_ [1 .. 9] $ + \i -> + putStrLn $ + mconcat + [show (length (derangements [1 .. i])), " ", show (subfactorial i)] putStrLn "" - -- Print the number of derangements in a list of 20 items print $ subfactorial 20 diff --git a/Task/Permutations-Derangements/jq/permutations-derangements-1.jq b/Task/Permutations-Derangements/Jq/permutations-derangements-1.jq similarity index 100% rename from Task/Permutations-Derangements/jq/permutations-derangements-1.jq rename to Task/Permutations-Derangements/Jq/permutations-derangements-1.jq diff --git a/Task/Permutations-Derangements/jq/permutations-derangements-2.jq b/Task/Permutations-Derangements/Jq/permutations-derangements-2.jq similarity index 100% rename from Task/Permutations-Derangements/jq/permutations-derangements-2.jq rename to Task/Permutations-Derangements/Jq/permutations-derangements-2.jq diff --git a/Task/Permutations-Derangements/jq/permutations-derangements-3.jq b/Task/Permutations-Derangements/Jq/permutations-derangements-3.jq similarity index 100% rename from Task/Permutations-Derangements/jq/permutations-derangements-3.jq rename to Task/Permutations-Derangements/Jq/permutations-derangements-3.jq diff --git a/Task/Permutations-Derangements/Julia/permutations-derangements.julia b/Task/Permutations-Derangements/Julia/permutations-derangements.julia new file mode 100644 index 0000000000..cd9391f4fe --- /dev/null +++ b/Task/Permutations-Derangements/Julia/permutations-derangements.julia @@ -0,0 +1,34 @@ +# v0.6 + +using Combinatorics + +derangements(n::Int) = (perm for perm in permutations(1:n) + if all(indx != p for (indx, p) in enumerate(perm))) + +function subfact(n::Integer)::Integer + if n in (0, 2) + return 1 + elseif n == 1 + return 0 + elseif 1 ≤ n ≤ 18 + return round(Int, factorial(n) / e) + elseif n > 0 + return (n - 1) * ( subfact(n - 1) + subfact(n - 2) ) + else + error() + end +end + +println("Derangements of [1, 2, 3, 4]") +for perm in derangements(4) + println(perm) +end + +@printf("\n%5s%13s%13s\n", "n", "derangements", "!n") +for n in 1:10 + ders = derangements(n) + subf = subfact(n) + @printf("%5i%13i%13i\n", n, length(collect(ders)), subf) +end + +println("\n!20 = ", subfact(20)) diff --git a/Task/Permutations-Derangements/Kotlin/permutations-derangements.kotlin b/Task/Permutations-Derangements/Kotlin/permutations-derangements.kotlin new file mode 100644 index 0000000000..35bcd5843b --- /dev/null +++ b/Task/Permutations-Derangements/Kotlin/permutations-derangements.kotlin @@ -0,0 +1,46 @@ +// version 1.1.2 + +fun permute(input: List): List> { + if (input.size == 1) return listOf(input) + val perms = mutableListOf>() + val toInsert = input[0] + for (perm in permute(input.drop(1))) { + for (i in 0..perm.size) { + val newPerm = perm.toMutableList() + newPerm.add(i, toInsert) + perms.add(newPerm) + } + } + return perms +} + +fun derange(input: List): List> { + if (input.isEmpty()) return listOf(input) + return permute(input).filter { permutation -> + permutation.filterIndexed { i, index -> i == index }.none() + } +} + +fun subFactorial(n: Int): Long = + when (n) { + 0 -> 1 + 1 -> 0 + else -> (n - 1) * (subFactorial(n - 1) + subFactorial(n - 2)) + } + +fun main(args: Array) { + val input = listOf(0, 1, 2, 3) + + val derangements = derange(input) + println("There are ${derangements.size} derangements of $input, namely:\n") + derangements.forEach(::println) + + println("\nN Counted Calculated") + println("- ------- ----------") + for (n in 0..9) { + val list = List(n) { it } + val counted = derange(list).size + println("%d %-9d %-9d".format(n, counted, subFactorial(n))) + } + println("\n!20 = ${subFactorial(20)}") +} diff --git a/Task/Permutations-Derangements/Phix/permutations-derangements.phix b/Task/Permutations-Derangements/Phix/permutations-derangements.phix new file mode 100644 index 0000000000..c1c251bb70 --- /dev/null +++ b/Task/Permutations-Derangements/Phix/permutations-derangements.phix @@ -0,0 +1,37 @@ +function deranged(sequence s1, sequence s2) + for i=1 to length(s1) do + if s1[i]==s2[i] then return 0 end if + end for + return 1 +end function + +function derangements(integer n) + sequence ts = tagset(n) + sequence res = {} + for i=1 to factorial(n) do + sequence s = permute(i,ts) + if deranged(s,ts) then + res = append(res,s) + end if + end for + return res +end function + +function subfactorial(integer n) + if n<=0 then return 1 end if + if n=1 then return 0 end if + return (n-1)*(subfactorial(n-1)+subfactorial(n-2)) +end function + +?derangements(4) +for n=0 to 9 do + printf(1,"%d: counted:%d, calculated:%d\n",{n,length(derangements(n)),subfactorial(n)}) +end for +printf(1,"!20=%d (incorrect!)\n",{subfactorial(20)}) +include builtins\bigatom.e +function ba_subfactorial(integer n) + if n<=0 then return 1 end if + if n=1 then return 0 end if + return ba_multiply(n-1,ba_add(ba_subfactorial(n-1),ba_subfactorial(n-2))) +end function +ba_printf(1,"!20=%B (bigatom)\n",ba_subfactorial(20)) diff --git a/Task/Permutations-Derangements/Zkl/permutations-derangements-1.zkl b/Task/Permutations-Derangements/Zkl/permutations-derangements-1.zkl new file mode 100644 index 0000000000..c0197ab7af --- /dev/null +++ b/Task/Permutations-Derangements/Zkl/permutations-derangements-1.zkl @@ -0,0 +1,19 @@ +fcn subFact(n){ + if(n==0) return(1); + if(n==1) return(0); + (n-1)*(self.fcn(n-1) + self.fcn(n-2)); +} + +fcn derangements(n){ + // All deranged permutations of the integers 0..n-1 inclusive + enum:=[0..n-1].pump(List); + Utils.Helpers.permuteW(enum).filter('wrap(perm){ + perm.zipWith('==,enum).sum(0) == 0 + }); +} +fcn derangers(n){ // just count # of derangements + enum:=[0..n-1].pump(List); + Utils.Helpers.permuteW(enum).reduce('wrap(sum,perm){ + sum + (perm.zipWith('==,enum).sum(0) == 0) + },0); +} diff --git a/Task/Permutations-Derangements/Zkl/permutations-derangements-2.zkl b/Task/Permutations-Derangements/Zkl/permutations-derangements-2.zkl new file mode 100644 index 0000000000..bfc651fbbd --- /dev/null +++ b/Task/Permutations-Derangements/Zkl/permutations-derangements-2.zkl @@ -0,0 +1,7 @@ +println("Derangements of 0,1,2,3:\n",derangements(4)); +println("\nTable of n vs counted vs calculated derangements:"); +foreach n in (10){ + println("%2d %-6d %-6d".fmt(n, derangers(n), subFact(n))); +} + +n:=20; println("\n!%d = %d".fmt(n, subFact(n))); diff --git a/Task/Permutations-Derangements/Zkl/permutations-derangements-3.zkl b/Task/Permutations-Derangements/Zkl/permutations-derangements-3.zkl new file mode 100644 index 0000000000..59443f13bd --- /dev/null +++ b/Task/Permutations-Derangements/Zkl/permutations-derangements-3.zkl @@ -0,0 +1,10 @@ +fcn derangements(n){ //-->Walker + enum:=[0..n-1].pump(List); + Utils.Helpers.permuteW(enum).tweak('wrap(perm){ + if(perm.zipWith('==,enum).sum(0)) Void.Skip + else perm + }); +} +fcn derangers(n){ // just count # of derangements, w/o saving them + derangements(n).reduce('+.fpM("10-",1),0); // ignore perm --> '+(1,sum)... +} diff --git a/Task/Permutations-Derangements/Zkl/permutations-derangements-4.zkl b/Task/Permutations-Derangements/Zkl/permutations-derangements-4.zkl new file mode 100644 index 0000000000..d5d6bf4836 --- /dev/null +++ b/Task/Permutations-Derangements/Zkl/permutations-derangements-4.zkl @@ -0,0 +1,2 @@ +foreach d in (derangements(4)){ println(d) } +//rest of test code remains the same diff --git a/Task/Permutations-Rank-of-a-permutation/FreeBASIC/permutations-rank-of-a-permutation-1.freebasic b/Task/Permutations-Rank-of-a-permutation/FreeBASIC/permutations-rank-of-a-permutation-1.freebasic new file mode 100644 index 0000000000..77f444d1ac --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/FreeBASIC/permutations-rank-of-a-permutation-1.freebasic @@ -0,0 +1,150 @@ +' version 31-03-2017 +' compile with: fbc -s console + +' Myrvold and Ruskey +' only for up to 20 elements, 21! > 2^64 -1 +Function Factorial(n As Integer) As ULongInt + + Dim As ULongInt tmp = 1 + + For i As ULong = 2 To n + tmp *= i + Next + + Return tmp + +End Function + +Sub unrank1(n As ULong, r As ULongInt , pi() As UByte) + + If n > 0 Then + Swap pi(n -1), pi(r Mod n) + unrank1(n -1, (r \ n), pi()) + End If + +End Sub + +Function rank1(n As ULongInt, pi() As UByte, pi_inv() As UByte) As ULongInt + + If n = 1 Then Return 0 + + Dim As UByte s = pi(n -1) + + Swap pi(n -1), pi(pi_inv(n -1)) + Swap pi_inv(s), pi_inv(n -1) + + Return (s + n * rank1(n -1, pi(), pi_inv())) + +End Function + +Sub unrank2(n As ULong, r As ULongInt, pi() As ubyte) + + If n > 0 Then + Dim As ULongInt fac = Factorial(n - 1) + Dim As ULongint s = r \ fac + Swap pi(n -1), pi(s) + unrank2(n -1, r - s * fac, pi()) + End If + +End Sub + +Function rank2(n As ULong, pi() As UByte, pi_inv() As UByte) As ULongInt + + If n = 1 Then Return 0 + Dim As UByte s = pi(n -1) + Swap pi(n -1), pi(pi_inv(n -1)) + Swap pi_inv(s), pi_inv(n -1) + Return (s * Factorial(n -1) + rank2(n -1, pi(), pi_inv())) + +End Function + +' ------=< MAIN >=------ + +Dim As ULongInt i, i1, j, n, n1 +Dim As UByte pi(), pi_inv() +Dim As String frmt1, frmt2 +Randomize timer + +n = 3 : n1 = Factorial(n) +ReDim pi(n -1), pi_inv(n - 1) +frmt1 = " ###" +frmt2 = "##" + +Print "Rank: unrank1 rank1" + +For i = 0 To n1 -1 + For j = 0 To n -1 + pi(j) = j + Next + Print Using frmt1 & ": --> "; i; + unrank1(n, i, pi()) + For j = 0 To n -1 + Print Using frmt2; pi(j); + pi_inv(pi(j))= j + Next + + Print Using " -->" & frmt1; rank1(n, pi(), pi_inv()) + +Next + +n = 12 : n1 = Factorial(n) +ReDim pi(n -1), pi_inv(n - 1) +frmt1 = "###########" +frmt2 = "###" +Print : Print "4 random samples of permutations from 12 objects" +Print " Rank: unrank1 rank1" + +For i = 1 To 4 + i1 = Int(Rnd * n1) + For j = 0 To n -1 : pi(j) = j : Next + Print Using frmt1 & ": --> "; i1; : unrank1(n, i1, pi()) + For j = 0 To n -1 : Print Using frmt2; pi(j); + pi_inv(pi(j))= j : Next + Print Using " -->" & frmt1; rank1(n, pi(), pi_inv()) +Next + +Print : Print String(69,"-") : Print +Print "Rank: unrank2 rank2" + +n = 3 : n1 = Factorial(n) +ReDim pi(n -1), pi_inv(n - 1) +frmt1 = " ###" +frmt2 = "##" + + +For i = 0 To n1 -1 + For j = 0 To n -1 + pi(j) = j + Next + Print Using frmt1 & ": --> "; i; + unrank2(n, i, pi()) + For j = 0 To n -1 + Print Using frmt2; pi(j); + pi_inv(pi(j))= j + Next + + Print Using " -->" & frmt1; rank2(n, pi(), pi_inv()) + +Next + +n = 12 : n1 = Factorial(n) +ReDim pi(n -1), pi_inv(n - 1) +frmt1 = "###########" +frmt2 = "###" +Print : Print "4 random samples of permutations from 12 objects" +Print " Rank: unrank2 rank2" + +For i = 1 To 4 + i1 = Int(Rnd * n1) + For j = 0 To n -1 : pi(j) = j : Next + Print Using frmt1 & ": --> "; i1; : unrank2(n, i1, pi()) + For j = 0 To n -1 : Print Using frmt2; pi(j); + pi_inv(pi(j))= j : Next + Print Using " -->" & frmt1; rank2(n, pi(), pi_inv()) +Next + +' empty keyboard buffer +While InKey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Permutations-Rank-of-a-permutation/FreeBASIC/permutations-rank-of-a-permutation-2.freebasic b/Task/Permutations-Rank-of-a-permutation/FreeBASIC/permutations-rank-of-a-permutation-2.freebasic new file mode 100644 index 0000000000..3ca9b0bd4b --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/FreeBASIC/permutations-rank-of-a-permutation-2.freebasic @@ -0,0 +1,117 @@ +' version 31-03-2017 +' compile with: fbc -s console + +' Myrvold and Ruskey +#Include Once "gmp.bi" +' next two gmp integer are made shared to make things a little easier +Dim Shared As Mpz_ptr _tmp1_, _tmp2_ +_tmp1_ = Allocate(Len( __mpz_struct)) : Mpz_init(_tmp1_) +_tmp2_ = Allocate(Len( __mpz_struct)) : Mpz_init(_tmp2_) + +Sub unrank1(n As ULong, rank As Mpz_ptr, pi As String) + + If n > 0 Then + ' _tmp1_ = quotient, _tmp2_ = remainder + Mpz_fdiv_qr_ui(_tmp1_, _tmp2_, rank, n) + Dim As UInteger r = Mpz_get_ui(_tmp2_) + Swap pi[n -1], pi[r] + unrank1(n -1, _tmp1_, pi) + End If + +End Sub + +Function rank1(n As ULong, pi As String, pi_inv As String) As Mpz_ptr + + Dim As Mpz_ptr ret_val = Allocate( Len( __mpz_struct)) : Mpz_init(ret_val) + + If n = 1 Then Return ret_val ' ret_val = 0 + + Dim As UByte s = pi[n -1] + + Swap pi[n -1], pi[pi_inv[n -1]] + Swap pi_inv[s], pi_inv[n -1] + + _tmp1_ = rank1(n -1, pi, pi_inv) + Mpz_mul_ui(_tmp1_, _tmp1_, n) + Mpz_add_ui(_tmp1_, _tmp1_, s) + + Return _tmp1_ + +End Function + +' ------=< MAIN >=------ +Dim As Mpz_ptr rank_nr = Allocate( Len( __mpz_struct)) : Mpz_init(rank_nr) +Dim As Mpz_ptr max_nr = Allocate( Len( __mpz_struct)) : Mpz_init(max_nr) + +Dim As ULong i, j, n = 144 +Dim As String tmp, pi_start, pi = Space(144), pi_inv = pi +Dim As ZString Ptr gmp_str : gmp_str = Allocate(1000) + +Mpz_fac_ui(max_nr, n) + +Randomize Timer +Dim Shared As __gmp_randstate_struct rnd_ +Gmp_randinit_mt(@rnd_) ' Mersenne Twister + +For i = 0 To 200 ' create seed + tmp += Str(Int(Rnd * 10)) +Next + +Mpz_set_str(_tmp1_, tmp, 10) +Gmp_randseed(@rnd_, _tmp1_) ' seed the random generator + +' set random generator give number from 0 to max_nr -1 +Mpz_fac_ui(max_nr, n) + +' setup the starting position +For j = 0 To n -1 + pi[j] = j +Next + +pi_start = pi + +For i = 1 To 4 + + pi = pi_start + + Mpz_urandomm(rank_nr, @rnd_, max_nr) + ' comment out the next 2 lines if you don't want the rank number + gmp_str = Mpz_get_str(0, 10, rank_nr) + Print *gmp_str + + unrank1(n, rank_nr, pi) + For j = 0 To n -1 + Print pi[j]; " "; + Next + Print : Print + +Next + +' test rank1 +For j = 0 To n -1 + pi_inv[pi[j]] = j +Next + +Print "Calculate rank from last return of unrank1" : Print + +_tmp2_ = rank1(n, pi, pi_inv) +gmp_str = Mpz_get_str(0, 10, _tmp2_) +Print *gmp_str + +Print +If Mpz_cmp(rank_nr, _tmp2_) = 0 Then + Print "Both numbers are equal" +Else + Print "Oh no, they are different" +End If + +' clean up +Gmp_randclear(@rnd_): DeAllocate(gmp_str) +Mpz_clear(_tmp1_) : Mpz_clear(_tmp2_) +Mpz_clear(rank_nr) : Mpz_clear(max_nr) + +' empty keyboard buffer +While InKey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Permutations-Rank-of-a-permutation/Kotlin/permutations-rank-of-a-permutation.kotlin b/Task/Permutations-Rank-of-a-permutation/Kotlin/permutations-rank-of-a-permutation.kotlin new file mode 100644 index 0000000000..2a0f10d043 --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Kotlin/permutations-rank-of-a-permutation.kotlin @@ -0,0 +1,65 @@ +// version 1.1.2 + +import java.util.Random + +fun IntArray.swap(i: Int, j: Int) { + val temp = this[i] + this[i] = this[j] + this[j] = temp +} + +tailrec fun mrUnrank1(rank: Int, n: Int, vec: IntArray) { + if (n < 1) return + val q = rank / n + val r = rank % n + vec.swap(r, n - 1) + mrUnrank1(q, n - 1, vec) +} + +fun mrRank1(n: Int, vec: IntArray, inv: IntArray): Int { + if (n < 2) return 0 + val s = vec[n - 1] + vec.swap(n - 1, inv[n - 1]) + inv.swap(s, n - 1) + return s + n * mrRank1(n - 1, vec, inv) +} + +fun getPermutation(rank: Int, n: Int, vec: IntArray) { + for (i in 0 until n) vec[i] = i + mrUnrank1(rank, n, vec) +} + +fun getRank(n: Int, vec: IntArray): Int { + val v = IntArray(n) + val inv = IntArray(n) + for (i in 0 until n) { + v[i] = vec[i] + inv[vec[i]] = i + } + return mrRank1(n, v, inv) +} + +fun main(args: Array) { + var tv = IntArray(3) + for (r in 0..5) { + getPermutation(r, 3, tv) + System.out.printf("%2d -> %s -> %d\n", r, tv.contentToString(), getRank(3, tv)) + } + println() + tv = IntArray(4) + for (r in 0..23) { + getPermutation(r, 4, tv) + System.out.printf("%2d -> %s -> %d\n", r, tv.contentToString(), getRank(4, tv)) + } + + println() + tv = IntArray(12) + val a = IntArray(4) + val rand = Random() + val fact12 = (2..12).fold(1) { acc, i -> acc * i } + for (i in 0..3) a[i] = rand.nextInt(fact12) + for (r in a) { + getPermutation(r, 12, tv) + System.out.printf("%9d -> %s -> %d\n", r, tv.contentToString(), getRank(12, tv)) + } +} diff --git a/Task/Permutations-Rank-of-a-permutation/Zkl/permutations-rank-of-a-permutation-1.zkl b/Task/Permutations-Rank-of-a-permutation/Zkl/permutations-rank-of-a-permutation-1.zkl new file mode 100644 index 0000000000..93e92ed253 --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Zkl/permutations-rank-of-a-permutation-1.zkl @@ -0,0 +1,8 @@ +fcn computePermutation(items,rank){ // in place permutation of items + foreach n in ([items.len()..1,-1]){ + r:=rank%n; + rank/=n; + items.swap(r,n-1); + } + items +} diff --git a/Task/Permutations-Rank-of-a-permutation/Zkl/permutations-rank-of-a-permutation-2.zkl b/Task/Permutations-Rank-of-a-permutation/Zkl/permutations-rank-of-a-permutation-2.zkl new file mode 100644 index 0000000000..19570cee70 --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Zkl/permutations-rank-of-a-permutation-2.zkl @@ -0,0 +1,12 @@ + /// Return the rank of a permutation. +fcn computeRank(perm){ + N,p2,inv := perm.len(), perm.copy(), List.createLong(N,0); + foreach n in (N){ inv[perm[n]] = n; } + fcn(n,p2,inv){ + if(n<2) return(0); + i,s:= n-1, p2[i]; + p2.swap(i,inv[i]); + inv.swap(s,i); + s + n*self.fcn(i,p2,inv); + }(N,p2,inv); +} diff --git a/Task/Permutations-Rank-of-a-permutation/Zkl/permutations-rank-of-a-permutation-3.zkl b/Task/Permutations-Rank-of-a-permutation/Zkl/permutations-rank-of-a-permutation-3.zkl new file mode 100644 index 0000000000..9be85199d1 --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Zkl/permutations-rank-of-a-permutation-3.zkl @@ -0,0 +1,15 @@ + // do some random permutations of 4 +fcn factorial(n){ (1).reduce(n,'*) } +items,max:=(4).toList(),factorial(items.len()); // (0,1,2,3), read only +foreach rank in ((5).pump(List,(0).random.fp(max)).sort()){ + p:=computePermutation(items.copy(),rank); + println("%3d: %s = %d".fmt(rank, p, computeRank(p))); +} +println(); + + // Permutations of 12 to compare to other solutions +items:=(12).toList(); // (0,1,2,3,..11) +foreach rank in (T(340494881,469128647,460982459,432900481)){ + p:=computePermutation(items.copy(),rank); + println("%12d: %s = %d".fmt(rank,p,computeRank(p))); +} diff --git a/Task/Permutations-Rank-of-a-permutation/Zkl/permutations-rank-of-a-permutation-4.zkl b/Task/Permutations-Rank-of-a-permutation/Zkl/permutations-rank-of-a-permutation-4.zkl new file mode 100644 index 0000000000..28e39ab73f --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/Zkl/permutations-rank-of-a-permutation-4.zkl @@ -0,0 +1,6 @@ +var [const] BN=Import("zklBigNum"); // libGMP +one44Bang:=BN(144).factorial(); // 250 digits +// Needed: random number [0,one44Bang) +do(0d1_000_000){ + p:=computePermutation((144).toList().copy(),(0).random((0).MAX)); +} diff --git a/Task/Permutations-by-swapping/00DESCRIPTION b/Task/Permutations-by-swapping/00DESCRIPTION index ebd28d1bd0..e72104ddbb 100644 --- a/Task/Permutations-by-swapping/00DESCRIPTION +++ b/Task/Permutations-by-swapping/00DESCRIPTION @@ -14,8 +14,10 @@ Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutati * [[wp:Steinhaus–Johnson–Trotter algorithm|Steinhaus–Johnson–Trotter algorithm]] * [http://www.cut-the-knot.org/Curriculum/Combinatorics/JohnsonTrotter.shtml Johnson-Trotter Algorithm Listing All Permutations] * [http://stackoverflow.com/a/29044942/10562 Correction to] Heap's algorithm as presented in Wikipedia and widely distributed. +* [http://www.gutenberg.org/files/18567/18567-h/18567-h.htm#ch7] Tintinnalogia ;Related task: *   [[Matrix arithmetic]] +*   [[Gray code]]

    diff --git a/Task/Permutations-by-swapping/Common-Lisp/permutations-by-swapping.lisp b/Task/Permutations-by-swapping/Common-Lisp/permutations-by-swapping.lisp new file mode 100644 index 0000000000..69f76d1237 --- /dev/null +++ b/Task/Permutations-by-swapping/Common-Lisp/permutations-by-swapping.lisp @@ -0,0 +1,59 @@ +(defstruct (directed-number (:conc-name dn-)) + (number nil :type integer) + (direction nil :type (member :left :right))) + +(defmethod print-object ((dn directed-number) stream) + (ecase (dn-direction dn) + (:left (format stream "<~D" (dn-number dn))) + (:right (format stream "~D>" (dn-number dn))))) + +(defun dn> (dn1 dn2) + (declare (directed-number dn1 dn2)) + (> (dn-number dn1) (dn-number dn2))) + +(defun dn-reverse-direction (dn) + (declare (directed-number dn)) + (setf (dn-direction dn) (ecase (dn-direction dn) + (:left :right) + (:right :left)))) + +(defun make-directed-numbers-upto (upto) + (let ((numbers (make-array upto :element-type 'integer))) + (dotimes (n upto numbers) + (setf (aref numbers n) (make-directed-number :number (1+ n) :direction :left))))) + +(defun max-mobile-pos (numbers) + (declare ((vector directed-number) numbers)) + (loop with pos-limit = (1- (length numbers)) + with max-value and max-pos + for num across numbers + for pos from 0 + do (ecase (dn-direction num) + (:left (when (and (plusp pos) (dn> num (aref numbers (1- pos))) + (or (null max-value) (dn> num max-value))) + (setf max-value num + max-pos pos))) + (:right (when (and (< pos pos-limit) (dn> num (aref numbers (1+ pos))) + (or (null max-value) (dn> num max-value))) + (setf max-value num + max-pos pos)))) + finally (return max-pos))) + +(defun permutations (upto) + (loop with numbers = (make-directed-numbers-upto upto) + for max-mobile-pos = (max-mobile-pos numbers) + for sign = 1 then (- sign) + do (format t "~A sign: ~:[~;+~]~D~%" numbers (plusp sign) sign) + while max-mobile-pos + do (let ((max-mobile-number (aref numbers max-mobile-pos))) + (ecase (dn-direction max-mobile-number) + (:left (rotatef (aref numbers (1- max-mobile-pos)) + (aref numbers max-mobile-pos))) + (:right (rotatef (aref numbers max-mobile-pos) + (aref numbers (1+ max-mobile-pos))))) + (loop for n across numbers + when (dn> n max-mobile-number) + do (dn-reverse-direction n))))) + +(permutations 3) +(permutations 4) diff --git a/Task/Permutations-by-swapping/Forth/permutations-by-swapping.fth b/Task/Permutations-by-swapping/Forth/permutations-by-swapping.fth new file mode 100644 index 0000000000..d3bf2de02b --- /dev/null +++ b/Task/Permutations-by-swapping/Forth/permutations-by-swapping.fth @@ -0,0 +1,67 @@ +S" fsl-util.fs" REQUIRED +S" fsl/dynmem.seq" REQUIRED + +cell darray p{ + +: sgn + DUP 0 > IF + DROP 1 + ELSE 0 < IF + -1 + ELSE + 0 + THEN THEN ; +: arr-swap {: addr1 addr2 | tmp -- :} + addr1 @ TO tmp + addr2 @ addr1 ! + tmp addr2 ! ; +: perms {: n xt | my-i k s -- :} + & p{ n 1+ }malloc malloc-fail? ABORT" perms :: out of memory" + 0 p{ 0 } ! + n 1+ 1 DO + I NEGATE p{ I } ! + LOOP + 1 TO s + BEGIN + 1 n 1+ DO + p{ I } @ ABS + -1 +LOOP + n 1+ s xt EXECUTE + 0 TO k + n 1+ 2 DO + p{ I } @ 0 < ( flag ) + p{ I } @ ABS p{ I 1- } @ ABS > ( flag flag ) + p{ I } @ ABS p{ k } @ ABS > ( flag flag flag ) + AND AND IF + I TO k + THEN + LOOP + n 1 DO + p{ I } @ 0 > ( flag ) + p{ I } @ ABS p{ I 1+ } @ ABS > ( flag flag ) + p{ I } @ ABS p{ k } @ ABS > ( flag flag flag ) + AND AND IF + I TO k + THEN + LOOP + k IF + n 1+ 1 DO + p{ I } @ ABS p{ k } @ ABS > IF + p{ I } @ NEGATE p{ I } ! + THEN + LOOP + p{ k } @ sgn k + TO my-i + p{ k } p{ my-i } arr-swap + s NEGATE TO s + THEN + k 0 = UNTIL ; +: .perm ( p0 p1 p2 ... pn n s ) + >R + ." Perm: [ " + 1 DO + . SPACE + LOOP + R> ." ] Sign: " . CR ; + +3 ' .perm perms CR +4 ' .perm perms diff --git a/Task/Permutations-by-swapping/FreeBASIC/permutations-by-swapping.freebasic b/Task/Permutations-by-swapping/FreeBASIC/permutations-by-swapping.freebasic new file mode 100644 index 0000000000..45dbe2ae44 --- /dev/null +++ b/Task/Permutations-by-swapping/FreeBASIC/permutations-by-swapping.freebasic @@ -0,0 +1,59 @@ +' version 31-03-2017 +' compile with: fbc -s console + +Sub perms(n As ULong) + + Dim As Long p(n), i, k, s = 1 + + For i = 1 To n + p(i) = -i + Next + + Do + Print "Perm: [ "; + For i = 1 To n + Print Abs(p(i)); " "; + Next + Print "] Sign: "; s + + k = 0 + For i = 2 To n + If p(i) < 0 Then + If Abs(p(i)) > Abs(p(i -1)) Then + If Abs(p(i)) > Abs(p(k)) Then k = i + End If + End If + Next + + For i = 1 To n -1 + If p(i) > 0 Then + If Abs(p(i)) > Abs(p(i +1)) Then + If Abs(p(i)) > Abs(p(k)) Then k = i + End If + End If + Next + + If k Then + For i = 1 To n + If Abs(p(i)) > Abs(p(k)) Then p(i) = -p(i) + Next + i = k + Sgn(p(k)) + Swap p(k), p(i) + s = -s + End If + + Loop Until k = 0 + +End Sub + +' ------=< MAIN >=------ + +perms(3) +print +perms(4) + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Permutations-by-swapping/Haskell/permutations-by-swapping.hs b/Task/Permutations-by-swapping/Haskell/permutations-by-swapping.hs index 811aac66a5..c068dcd46e 100644 --- a/Task/Permutations-by-swapping/Haskell/permutations-by-swapping.hs +++ b/Task/Permutations-by-swapping/Haskell/permutations-by-swapping.hs @@ -1,14 +1,15 @@ -s_permutations :: [a] -> [([a], Int)] -s_permutations = flip zip (cycle [1, -1]) . (foldl aux [[]]) - where aux items x = do - (f,item) <- zip (cycle [reverse,id]) items - f (insertEv x item) - insertEv x [] = [[x]] - insertEv x l@(y:ys) = (x:l) : map (y:) (insertEv x ys) +sPermutations :: [a] -> [([a], Int)] +sPermutations = flip zip (cycle [-1, 1]) . foldr aux [[]] + where + aux x items = do + (f, item) <- zip (repeat id) items + f (insertEv x item) + insertEv x [] = [[x]] + insertEv x l@(y:ys) = (x : l) : ((y :) <$> insertEv x ys) main :: IO () main = do putStrLn "3 items:" - mapM_ print $ s_permutations [0..2] - putStrLn "4 items:" - mapM_ print $ s_permutations [0..3] + mapM_ print $ sPermutations [1 .. 3] + putStrLn "\n4 items:" + mapM_ print $ sPermutations [1 .. 4] diff --git a/Task/Permutations-by-swapping/Java/permutations-by-swapping.java b/Task/Permutations-by-swapping/Java/permutations-by-swapping.java new file mode 100644 index 0000000000..98ad3b878d --- /dev/null +++ b/Task/Permutations-by-swapping/Java/permutations-by-swapping.java @@ -0,0 +1,68 @@ +package org.rosettacode.java; + +import java.util.Arrays; +import java.util.stream.IntStream; + +public class HeapsAlgorithm { + + public static void main(String[] args) { + Object[] array = IntStream.range(0, 4) + .boxed() + .toArray(); + HeapsAlgorithm algorithm = new HeapsAlgorithm(); + algorithm.recursive(array); + System.out.println(); + algorithm.loop(array); + } + + void recursive(Object[] array) { + recursive(array, array.length, true); + } + + void recursive(Object[] array, int n, boolean plus) { + if (n == 1) { + output(array, plus); + } else { + for (int i = 0; i < n; i++) { + recursive(array, n - 1, i == 0); + swap(array, n % 2 == 0 ? i : 0, n - 1); + } + } + } + + void output(Object[] array, boolean plus) { + System.out.println(Arrays.toString(array) + (plus ? " +1" : " -1")); + } + + void swap(Object[] array, int a, int b) { + Object o = array[a]; + array[a] = array[b]; + array[b] = o; + } + + void loop(Object[] array) { + loop(array, array.length); + } + + void loop(Object[] array, int n) { + int[] c = new int[n]; + output(array, true); + boolean plus = false; + for (int i = 0; i < n; ) { + if (c[i] < i) { + if (i % 2 == 0) { + swap(array, 0, i); + } else { + swap(array, c[i], i); + } + output(array, plus); + plus = !plus; + c[i]++; + i = 0; + } else { + c[i] = 0; + i++; + } + } + } +} diff --git a/Task/Permutations-by-swapping/jq/permutations-by-swapping-1.jq b/Task/Permutations-by-swapping/Jq/permutations-by-swapping-1.jq similarity index 100% rename from Task/Permutations-by-swapping/jq/permutations-by-swapping-1.jq rename to Task/Permutations-by-swapping/Jq/permutations-by-swapping-1.jq diff --git a/Task/Permutations-by-swapping/jq/permutations-by-swapping-2.jq b/Task/Permutations-by-swapping/Jq/permutations-by-swapping-2.jq similarity index 100% rename from Task/Permutations-by-swapping/jq/permutations-by-swapping-2.jq rename to Task/Permutations-by-swapping/Jq/permutations-by-swapping-2.jq diff --git a/Task/Permutations-by-swapping/jq/permutations-by-swapping-3.jq b/Task/Permutations-by-swapping/Jq/permutations-by-swapping-3.jq similarity index 100% rename from Task/Permutations-by-swapping/jq/permutations-by-swapping-3.jq rename to Task/Permutations-by-swapping/Jq/permutations-by-swapping-3.jq diff --git a/Task/Permutations-by-swapping/Kotlin/permutations-by-swapping.kotlin b/Task/Permutations-by-swapping/Kotlin/permutations-by-swapping.kotlin new file mode 100644 index 0000000000..5a6c362707 --- /dev/null +++ b/Task/Permutations-by-swapping/Kotlin/permutations-by-swapping.kotlin @@ -0,0 +1,46 @@ +// version 1.1.2 + +fun johnsonTrotter(n: Int): Pair, List> { + val p = IntArray(n) { it } // permutation + val q = IntArray(n) { it } // inverse permutation + val d = IntArray(n) { -1 } // direction = 1 or -1 + var sign = 1 + val perms = mutableListOf() + val signs = mutableListOf() + + fun permute(k: Int) { + if (k >= n) { + perms.add(p.copyOf()) + signs.add(sign) + sign *= -1 + return + } + permute(k + 1) + for (i in 0 until k) { + val z = p[q[k] + d[k]] + p[q[k]] = z + p[q[k] + d[k]] = k + q[z] = q[k] + q[k] += d[k] + permute(k + 1) + } + d[k] *= -1 + } + + permute(0) + return perms to signs +} + +fun printPermsAndSigns(perms: List, signs: List) { + for ((i, perm) in perms.withIndex()) { + println("${perm.contentToString()} -> sign = ${signs[i]}") + } +} + +fun main(args: Array) { + val (perms, signs) = johnsonTrotter(3) + printPermsAndSigns(perms, signs) + println() + val (perms2, signs2) = johnsonTrotter(4) + printPermsAndSigns(perms2, signs2) +} diff --git a/Task/Permutations-by-swapping/Phix/permutations-by-swapping.phix b/Task/Permutations-by-swapping/Phix/permutations-by-swapping.phix new file mode 100644 index 0000000000..8505220096 --- /dev/null +++ b/Task/Permutations-by-swapping/Phix/permutations-by-swapping.phix @@ -0,0 +1,23 @@ +function spermutations(integer p, integer i) +-- generate the i'th permutation of [1..p]: +-- first obtain the appropriate permutation of [1..p-1], +-- then insert p/move it down k(=0..p-1) places from the end. + integer k = mod(i-1,2*p) + if k>=p then k=2*p-1-k end if + sequence res + integer parity + if p>1 then + {res,parity} = spermutations(p-1,floor((i-1)/p)+1) + res = res[1..length(res)-k]&p&res[length(res)-k+1..$] + else + res = {1} + end if + return {res,iff(and_bits(i,1)?1:-1)} +end function + +for p=1 to 4 do + printf(1,"==%d==\n",p) + for i=1 to factorial(p) do + ?{i,spermutations(p,i)} + end for +end for diff --git a/Task/Permutations-by-swapping/Sidef/permutations-by-swapping.sidef b/Task/Permutations-by-swapping/Sidef/permutations-by-swapping.sidef index e9272b2aa8..d2385bf1f6 100644 --- a/Task/Permutations-by-swapping/Sidef/permutations-by-swapping.sidef +++ b/Task/Permutations-by-swapping/Sidef/permutations-by-swapping.sidef @@ -1,20 +1,20 @@ func perms(n) { var perms = [[+1]] - n.times { |x| - var sign = -1; + for x in (1..n) { + var sign = -1 perms = gather { for s,*p in perms { - var r = (0 .. p.len); + var r = (0 .. p.len) take((s < 0 ? r : r.flip).map {|i| - [sign *= -1, p[0..i-1], x, p[i..p.end]] + [sign *= -1, p[^i], x, p[i..p.end]] }...) } } } - perms; + perms } -var n = 4; +var n = 4 for p in perms(n) { var s = p.shift s > 0 && (s = '+1') diff --git a/Task/Permutations-by-swapping/Zkl/permutations-by-swapping-1.zkl b/Task/Permutations-by-swapping/Zkl/permutations-by-swapping-1.zkl new file mode 100644 index 0000000000..4f022f2659 --- /dev/null +++ b/Task/Permutations-by-swapping/Zkl/permutations-by-swapping-1.zkl @@ -0,0 +1,13 @@ +fcn permute(seq) +{ + insertEverywhere := fcn(x,list){ //(x,(a,b))-->((x,a,b),(a,x,b),(a,b,x)) + (0).pump(list.len()+1,List,'wrap(n){list[0,n].extend(x,list[n,*]) })}; + insertEverywhereB := fcn(x,t){ //--> insertEverywhere().reverse() + [t.len()..-1,-1].pump(t.len()+1,List,'wrap(n){t[0,n].extend(x,t[n,*])})}; + + seq.reduce('wrap(items,x){ + f := Utils.Helpers.cycle(insertEverywhereB,insertEverywhere); + items.pump(List,'wrap(item){f.next()(x,item)}, + T.fp(Void.Write,Void.Write)); + },T(T)); +} diff --git a/Task/Permutations-by-swapping/Zkl/permutations-by-swapping-2.zkl b/Task/Permutations-by-swapping/Zkl/permutations-by-swapping-2.zkl new file mode 100644 index 0000000000..eae741cf2e --- /dev/null +++ b/Task/Permutations-by-swapping/Zkl/permutations-by-swapping-2.zkl @@ -0,0 +1,6 @@ +p := permute(T(1,2,3)); +p.println(); + +p := permute([1..4]); +p.len().println(); +p.toString(*).println() diff --git a/Task/Permutations-by-swapping/Zkl/permutations-by-swapping-3.zkl b/Task/Permutations-by-swapping/Zkl/permutations-by-swapping-3.zkl new file mode 100644 index 0000000000..bd50aaea54 --- /dev/null +++ b/Task/Permutations-by-swapping/Zkl/permutations-by-swapping-3.zkl @@ -0,0 +1,21 @@ + fcn [private] _permuteW(seq){ // lazy version + N:=seq.len(); NM1:=N-1; + ds:=(0).pump(N,List,T(Void,-1)).copy(); ds[0]=0; // direction to move e: -1,0,1 + es:=(0).pump(N,List).copy(); // enumerate seq + + while(1) { + vm.yield(es.pump(List,seq.__sGet)); + + // find biggest e with d!=0 + reg i=Void, c=-1; + foreach n in (N){ if(ds[n] and es[n]>c) { c=es[n]; i=n; } } + if(Void==i) return(); + + d:=ds[i]; j:=i+d; + es.swap(i,j); ds.swap(i,j); // d tracks e + if(j==NM1 or j==0 or es[j+d]>c) ds[j]=0; + foreach e in (N){ if(es[e]>c) ds[e]=(i-e).sign } + } +} + +fcn permuteW(seq) { Utils.Generator(_permuteW,seq) } diff --git a/Task/Permutations-by-swapping/Zkl/permutations-by-swapping-4.zkl b/Task/Permutations-by-swapping/Zkl/permutations-by-swapping-4.zkl new file mode 100644 index 0000000000..f882171d99 --- /dev/null +++ b/Task/Permutations-by-swapping/Zkl/permutations-by-swapping-4.zkl @@ -0,0 +1 @@ +foreach p in (permuteW(T("a","b","c"))){ println(p) } diff --git a/Task/Permutations/AppleScript/permutations-1.applescript b/Task/Permutations/AppleScript/permutations-1.applescript new file mode 100644 index 0000000000..1cda85642f --- /dev/null +++ b/Task/Permutations/AppleScript/permutations-1.applescript @@ -0,0 +1,92 @@ +-- PERMUTATIONS -------------------------------------------------------------- + +-- permutations :: [a] -> [[a]] +on permutations(xs) + script firstElement + on |λ|(x) + script tailElements + on |λ|(ys) + {{x} & ys} + end |λ| + end script + + concatMap(tailElements, permutations(|delete|(x, xs))) + end |λ| + end script + + if length of xs > 0 then + concatMap(firstElement, xs) + else + {{}} + end if +end permutations + + +-- TEST ---------------------------------------------------------------------- +on run + + permutations({"aardvarks", "eat", "ants"}) + +end run + + +-- GENERIC FUNCTIONS --------------------------------------------------------- + +-- concatMap :: (a -> [b]) -> [a] -> [b] +on concatMap(f, xs) + set lst to {} + set lng to length of xs + tell mReturn(f) + repeat with i from 1 to lng + set lst to (lst & |λ|(contents of item i of xs, i, xs)) + end repeat + end tell + return lst +end concatMap + +-- delete :: a -> [a] -> [a] +on |delete|(x, xs) + if length of xs > 0 then + set {h, t} to uncons(xs) + if x = h then + t + else + {h} & |delete|(x, t) + end if + else + {} + end if +end |delete| + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- uncons :: [a] -> Maybe (a, [a]) +on uncons(xs) + if length of xs > 0 then + {item 1 of xs, rest of xs} + else + missing value + end if +end uncons diff --git a/Task/Permutations/AppleScript/permutations-2.applescript b/Task/Permutations/AppleScript/permutations-2.applescript new file mode 100644 index 0000000000..a4c4a8afe8 --- /dev/null +++ b/Task/Permutations/AppleScript/permutations-2.applescript @@ -0,0 +1,43 @@ +to DoPermutations(aList, n) + --> Heaps's algorithm (Permutation by interchanging pairs) AppleScript by Jean.O.matiC + if n = 1 then + tell (a reference to Permlist) to copy aList to its end + -- or: copy aList as text (for concatenated results) + else + repeat with i from 1 to n + DoPermutations(aList, n - 1) + if n mod 2 = 0 then -- n is even + tell aList to set [item i, item n] to [item n, item i] -- swaps items i and n of aList + else + tell aList to set [item 1, item n] to [item n, item 1] -- swaps items 1 and n of aList + end if + set i to i + 1 + end repeat + end if + return (a reference to Permlist) as list +end DoPermutations + +--> Example 1 (list of words) +set [SourceList, Permlist] to [{"Good", "Johnny", "Be"}, {}] +DoPermutations(SourceList, SourceList's length) +--> result (value of Permlist) +{{"Good", "Johnny", "Be"}, {"Johnny", "Good", "Be"}, {"Be", "Good", "Johnny"}, ¬ + {"Good", "Be", "Johnny"}, {"Johnny", "Be", "Good"}, {"Be", "Johnny", "Good"}} + +--> Example 2 (characters with concatenated results) +set [SourceList, Permlist] to [{"X", "Y", "Z"}, {}] +DoPermutations(SourceList, SourceList's length) +--> result (value of Permlist) +{"XYZ", "YXZ", "ZXY", "XZY", "YZX", "ZYX"} + +--> Example 3 (Integers) +set [SourceList, Permlist] to [{1, 2, 3}, {}] +DoPermutations(SourceList, SourceList's length) +--> result (value of Permlist) +{{1, 2, 3}, {2, 1, 3}, {3, 1, 2}, {1, 3, 2}, {2, 3, 1}, {3, 2, 1}} + +--> Example 4 (Integers with concatenated results) +set [SourceList, Permlist] to [{1, 2, 3}, {}] +DoPermutations(SourceList, SourceList's length) +--> result (value of Permlist) +{"123", "213", "312", "132", "231", "321"} diff --git a/Task/Permutations/AppleScript/permutations.applescript b/Task/Permutations/AppleScript/permutations.applescript deleted file mode 100644 index 55160d0128..0000000000 --- a/Task/Permutations/AppleScript/permutations.applescript +++ /dev/null @@ -1,114 +0,0 @@ --- permutations :: [a] -> [[a]] -on permutations(xs) - script firstElement - on lambda(x) - script tailElements - on lambda(ys) - {x & ys} - end lambda - end script - - concatMap(tailElements, permutations(|delete|(x, xs))) - end lambda - end script - - if length of xs > 0 then - concatMap(firstElement, xs) - else - {{}} - end if -end permutations - - --- TEST -on run - - return permutations({1, 2, 3}) - permutations({"aardvarks", "eat", "ants"}) - -end run - - - --- GENERIC LIBRARY FUNCTIONS - --- concatMap :: (a -> [b]) -> [a] -> [b] -on concatMap(f, xs) - script append - on lambda(a, b) - a & b - end lambda - end script - - foldl(append, {}, map(f, xs)) -end concatMap - --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map - --- foldl :: (a -> b -> a) -> a -> [b] -> a -on foldl(f, startValue, xs) - tell mReturn(f) - set v to startValue - set lng to length of xs - repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) - end repeat - return v - end tell -end foldl - --- delete :: a -> [a] -> [a] -on |delete|(x, xs) - script Eq - on lambda(a, b) - a = b - end lambda - end script - - deleteBy(Eq, x, xs) -end |delete| - --- deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a] -on deleteBy(fnEq, x, xs) - if length of xs > 0 then - set {h, t} to uncons(xs) - if lambda(x, h) of mReturn(fnEq) then - t - else - {h} & deleteBy(fnEq, x, t) - end if - else - {} - end if -end deleteBy - --- uncons :: [a] -> Maybe (a, [a]) -on uncons(xs) - if length of xs > 0 then - {item 1 of xs, rest of xs} - else - missing value - end if -end uncons - --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn diff --git a/Task/Permutations/FreeBASIC/permutations.freebasic b/Task/Permutations/FreeBASIC/permutations.freebasic new file mode 100644 index 0000000000..b10a9ab806 --- /dev/null +++ b/Task/Permutations/FreeBASIC/permutations.freebasic @@ -0,0 +1,52 @@ +' version 07-04-2017 +' compile with: fbc -s console + +' Heap's algorithm non-recursive +Sub perms(n As Long) + + Dim As ULong i, j, count = 1 + Dim As ULong a(0 To n -1), c(0 To n -1) + + For j = 0 To n -1 + a(j) = j +1 + Print a(j); + Next + Print " "; + + i = 0 + While i < n + If c(i) < i Then + If (i And 1) = 0 Then + Swap a(0), a(i) + Else + Swap a(c(i)), a(i) + End If + For j = 0 To n -1 + Print a(j); + Next + count += 1 + If count = 12 Then + Print + count = 0 + Else + Print " "; + End If + c(i) += 1 + i = 0 + Else + c(i) = 0 + i += 1 + End If + Wend + +End Sub + +' ------=< MAIN >=------ + +perms(4) + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Permutations/Glee/permutations-1.glee b/Task/Permutations/Glee/permutations-1.glee new file mode 100644 index 0000000000..2a3c565163 --- /dev/null +++ b/Task/Permutations/Glee/permutations-1.glee @@ -0,0 +1,7 @@ +$$ n !! k dyadic: Permutations for k out of n elements (in this case k = n) +$$ #s monadic: number of elements in s +$$ ,, monadic: expose with space-lf separators +$$ s[n] index n of s + +'Hello' 123 7.9 '•'=>s; +s[s# !! (s#)],, diff --git a/Task/Permutations/Glee/permutations-2.glee b/Task/Permutations/Glee/permutations-2.glee new file mode 100644 index 0000000000..952f49188b --- /dev/null +++ b/Task/Permutations/Glee/permutations-2.glee @@ -0,0 +1,24 @@ +Hello 123 7.9 • +Hello 123 • 7.9 +Hello 7.9 123 • +Hello 7.9 • 123 +Hello • 123 7.9 +Hello • 7.9 123 +123 Hello 7.9 • +123 Hello • 7.9 +123 7.9 Hello • +123 7.9 • Hello +123 • Hello 7.9 +123 • 7.9 Hello +7.9 Hello 123 • +7.9 Hello • 123 +7.9 123 Hello • +7.9 123 • Hello +7.9 • Hello 123 +7.9 • 123 Hello +• Hello 123 7.9 +• Hello 7.9 123 +• 123 Hello 7.9 +• 123 7.9 Hello +• 7.9 Hello 123 +• 7.9 123 Hello diff --git a/Task/Permutations/JavaScript/permutations-4.js b/Task/Permutations/JavaScript/permutations-4.js index 7c49b8445f..cf85a75731 100644 --- a/Task/Permutations/JavaScript/permutations-4.js +++ b/Task/Permutations/JavaScript/permutations-4.js @@ -1,39 +1,35 @@ (function () { + 'use strict'; // permutations :: [a] -> [[a]] - function permutations(xs) { - return xs.length ? (concatMap( - function (x) { - return concatMap( - function (ys) { - return ([[x].concat(ys)]); - }, permutations(delete1(x, xs))) - }, xs)) : [[]] - } + var permutations = function (xs) { + return xs.length ? concatMap(function (x) { + return concatMap(function (ys) { + return [[x].concat(ys)]; + }, permutations(delete_(x, xs))); + }, xs) : [[]]; + }; - - // GENERIC LIBRARY FUNCTIONS + // GENERIC FUNCTIONS // concatMap :: (a -> [b]) -> [a] -> [b] - function concatMap(f, xs) { + var concatMap = function (f, xs) { return [].concat.apply([], xs.map(f)); - } + }; - // delete first instance of a in [a] - // delete1 :: a -> [a] -> [a] - function delete1(x, xs) { + // delete :: Eq a => a -> [a] -> [a] + var delete_ = function (x, xs) { return deleteBy(function (a, b) { return a === b; }, x, xs); - } + }; // deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a] - function deleteBy(fnEq, x, xs) { - return xs.length ? fnEq(x, xs[0]) ? xs.slice(1) : [xs[0]] - .concat(deleteBy(fnEq, x, xs.slice(1))) : []; - } - - - return permutations(['Aardvarks', 'eat', 'ants']) + var deleteBy = function (f, x, xs) { + return xs.length > 0 ? f(x, xs[0]) ? xs.slice(1) : + [xs[0]].concat(deleteBy(f, x, xs.slice(1))) : []; + }; + // TEST + return permutations(['Aardvarks', 'eat', 'ants']); })(); diff --git a/Task/Permutations/JavaScript/permutations-6.js b/Task/Permutations/JavaScript/permutations-6.js index 5052af34c7..72b229a793 100644 --- a/Task/Permutations/JavaScript/permutations-6.js +++ b/Task/Permutations/JavaScript/permutations-6.js @@ -1,19 +1,38 @@ -(function (lst) { +(() => { 'use strict'; - const permutations = (xs) => xs.length ? ( - flatMap((x) => flatMap((xs) => [[x].concat(xs)], - permutations(del(x, xs))), xs) - ) : [[]], + // permutations :: [a] -> [[a]] + const permutations = xs => + xs.length ? concatMap(x => concatMap(ys => [ + [x].concat(ys) + ], + permutations(delete_(x, xs))), xs) : [ + [] + ]; - flatMap = (f, xs) => [].concat.apply([], xs.map(f)), + // GENERIC FUNCTIONS - del = (x, xs) => xs.length ? x === xs[0] ? ( - xs.slice(1) - ) : [xs[0]].concat(del(x, xs.slice(1)) + // concatMap :: (a -> [b]) -> [a] -> [b] + const concatMap = (f, xs) => [].concat.apply([], xs.map(f)); + // + // // delete :: Eq a => a -> [a] -> [a] + // const delete_ = (x, xs) => + // deleteBy((a, b) => a === b, x, xs); + + // delete_ :: Eq a => a -> [a] -> [a] + const delete_ = (x, xs) => + xs.length > 0 ? ( + (x === xs[0]) ? ( + xs.slice(1) + ) : [xs[0]].concat(delete_(x, xs.slice(1))) ) : []; + // range :: Int -> Int -> [Int] + const range = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); - return permutations(lst); - -})(["Aardvarks", "eat", "ants"]); + // TEST + return permutations(['Aardvarks', 'eat', 'ants']); +})(); diff --git a/Task/Permutations/jq/permutations.jq b/Task/Permutations/Jq/permutations.jq similarity index 100% rename from Task/Permutations/jq/permutations.jq rename to Task/Permutations/Jq/permutations.jq diff --git a/Task/Permutations/Kotlin/permutations.kotlin b/Task/Permutations/Kotlin/permutations.kotlin new file mode 100644 index 0000000000..c553fbcd5f --- /dev/null +++ b/Task/Permutations/Kotlin/permutations.kotlin @@ -0,0 +1,22 @@ +// version 1.1.2 + +fun permute(input: List): List> { + if (input.size == 1) return listOf(input) + val perms = mutableListOf>() + val toInsert = input[0] + for (perm in permute(input.drop(1))) { + for (i in 0..perm.size) { + val newPerm = perm.toMutableList() + newPerm.add(i, toInsert) + perms.add(newPerm) + } + } + return perms +} + +fun main(args: Array) { + val input = listOf('a', 'b', 'c', 'd') + val perms = permute(input) + println("There are ${perms.size} permutations of $input, namely:\n") + for (perm in perms) println(perm) +} diff --git a/Task/Permutations/PHP/permutations.php b/Task/Permutations/PHP/permutations.php index 919cf79e82..ba2dfc3bbe 100644 --- a/Task/Permutations/PHP/permutations.php +++ b/Task/Permutations/PHP/permutations.php @@ -1,4 +1,3 @@ -//Author Gavryushin Ivan @dcc0 permutation(letters[1:3]) +[[1]] +[1] "c" "b" "a" + +[[2]] +[1] "b" "c" "a" + +[[3]] +[1] "b" "a" "c" + +[[4]] +[1] "c" "a" "b" + +[[5]] +[1] "a" "c" "b" + +[[6]] +[1] "a" "b" "c" diff --git a/Task/Permutations/Ruby/permutations-2.rb b/Task/Permutations/Ruby/permutations-2.rb deleted file mode 100644 index 78d60efec9..0000000000 --- a/Task/Permutations/Ruby/permutations-2.rb +++ /dev/null @@ -1,37 +0,0 @@ -class Array - # Yields distinct permutations of _self_ to the block. - # This method requires that all array elements be Comparable. - def distinct_permutation # :yields: _ary_ - # If no block, return an enumerator. Works with Ruby 1.8.7. - block_given? or return enum_for(:distinct_permutation) - - copy = self.sort - yield copy.dup - return if size < 2 - - while true - # from: "The Art of Computer Programming" by Donald Knuth - j = size - 2; - j -= 1 while j > 0 && copy[j] >= copy[j+1] - if copy[j] < copy[j+1] - l = size - 1 - l -= 1 while copy[j] >= copy[l] - copy[j] , copy[l] = copy[l] , copy[j] - copy[j+1..-1] = copy[j+1..-1].reverse - yield copy.dup - else - break - end - end - end -end - -permutations = [] -[1,1,2].distinct_permutation do |p| permutations << p end -p permutations -# => [[1, 1, 2], [1, 2, 1], [2, 1, 1]] - -if RUBY_VERSION >= "1.8.7" - p [1,1,2].distinct_permutation.to_a - # => [[1, 1, 2], [1, 2, 1], [2, 1, 1]] -end diff --git a/Task/Permutations/Ruby/permutations-1.rb b/Task/Permutations/Ruby/permutations.rb similarity index 100% rename from Task/Permutations/Ruby/permutations-1.rb rename to Task/Permutations/Ruby/permutations.rb diff --git a/Task/Permutations/Rust/permutations-1.rust b/Task/Permutations/Rust/permutations-1.rust new file mode 100644 index 0000000000..b7a7432add --- /dev/null +++ b/Task/Permutations/Rust/permutations-1.rust @@ -0,0 +1,34 @@ +struct QuickPerm { + idxs: Vec, + elems: Vec, + idx: usize, +} + +impl QuickPerm { + fn new(elems: Vec) -> Self { + QuickPerm { idxs: (0..elems.len()+1).collect(), elems: elems, idx: 1 } + } +} + +impl Iterator for QuickPerm { + type Item = Vec; + fn next(&mut self) -> Option { + if self.idx == self.elems.len() { return None; } + + self.idxs[self.idx] -= 1; + let other = if self.idx % 2 == 1 { self.idxs[self.idx] } else { 0 }; + self.elems.swap(self.idx, other); + self.idx = 1; + while self.idxs[self.idx] == 0 { + self.idxs[self.idx] = self.idx; + self.idx += 1; + } + Some(self.elems.clone()) + } +} + +fn main() { + for perm in QuickPerm::new(vec![1,2,3]) { + println!("{:?}", perm); + } +} diff --git a/Task/Permutations/Rust/permutations-2.rust b/Task/Permutations/Rust/permutations-2.rust new file mode 100644 index 0000000000..ce7f859b9e --- /dev/null +++ b/Task/Permutations/Rust/permutations-2.rust @@ -0,0 +1,25 @@ +use std::collections::VecDeque; +fn permute(used: &mut Vec, unused: &mut VecDeque, action: &F) { + if unused.is_empty() { + action(used); + } else { + for _ in 0..unused.len() { + used.push(unused.pop_front().unwrap()); + permute(used, unused, action); + unused.push_back(used.pop().unwrap()); + } + } +} + +// Same as the vec! macro, but for VecDeques as well +macro_rules! vec_deque { + ($($item:expr),*) => {{ + let mut deque = ::std::collections::VecDeque::new(); + $(deque.push_back($item);)* + deque + }} +} + +fn main() { + permute(&mut Vec::new(), &mut vec_deque![1,2,3], &|perm| println!("{:?}", perm)); +} diff --git a/Task/Permutations/Stata/permutations-1.stata b/Task/Permutations/Stata/permutations-1.stata new file mode 100644 index 0000000000..a0ccbc3d59 --- /dev/null +++ b/Task/Permutations/Stata/permutations-1.stata @@ -0,0 +1 @@ +perm 4 diff --git a/Task/Permutations/Stata/permutations-2.stata b/Task/Permutations/Stata/permutations-2.stata new file mode 100644 index 0000000000..9aaec3a281 --- /dev/null +++ b/Task/Permutations/Stata/permutations-2.stata @@ -0,0 +1,49 @@ +program perm + local n=`1' + local r=1 + forv i=1/`n' { + local r=`r'*`i' + } + clear + qui set obs `r' + forv i=1/`n' { + gen p`i'=0 + } + mata: genperm() +end + +mata +void genperm() { + real scalar n, i, j, k, s, p + real rowvector u + st_view(a=., ., .) + n = cols(a) + u = 1..n + p = 1 + do { + a[p++, .] = u + i = n + for (i = n; i > 1; i--) { + if (u[i-1] < u[i]) break + } + if (i > 1) { + j = i + k = n + while (j < k) { + s = u[j] + u[j] = u[k] + u[k] = s + j++ + k-- + } + + s = u[i-1] + j = i + for (j = i; u[j] < s; j++) { + } + u[i-1] = u[j] + u[j] = s + } + } while (i > 1) +} +end diff --git a/Task/Permutations/Zkl/permutations.zkl b/Task/Permutations/Zkl/permutations.zkl new file mode 100644 index 0000000000..3000189a84 --- /dev/null +++ b/Task/Permutations/Zkl/permutations.zkl @@ -0,0 +1,8 @@ +zkl: Utils.Helpers.permute("rose").apply("concat") +L("rose","roes","reos","eros","erso","reso","rseo","rsoe","sroe","sreo",...) + +zkl: Utils.Helpers.permute("rose").len() +24 + +zkl: Utils.Helpers.permute(T(1,2,3,4)) +L(L(1,2,3,4),L(1,2,4,3),L(1,4,2,3),L(4,1,2,3),L(4,1,3,2),L(1,4,3,2),L(1,3,4,2),L(1,3,2,4),...) diff --git a/Task/Pernicious-numbers/00DESCRIPTION b/Task/Pernicious-numbers/00DESCRIPTION index 36a04510dd..d473a4dfbd 100644 --- a/Task/Pernicious-numbers/00DESCRIPTION +++ b/Task/Pernicious-numbers/00DESCRIPTION @@ -1,17 +1,14 @@ -A   ''[[wp:Pernicious number|pernicious number]]''   is a positive integer whose   [[population count]]   is a prime. - -The   ''population count''   (also known as ''pop count'')   is the number of 1's  (ones) in the binary representation of a non-negative integer. +A   [[wp:Pernicious number|pernicious number]]   is a positive integer whose   [[population count]]   is a prime.   The population count is the number of ones in the binary representation of a non-negative integer. -;Example: -'''22'''   (which is   '''10110'''   in binary)   has a population count of   '''3'''   (which is prime),   and therefore -
    '''22'''   is a pernicious number. +;Example +'''22'''   (which is   '''10110'''   in binary)   has a population count of   '''3''',   which is prime, and therefore   '''22'''   is a pernicious number. -'''Task requirements''' -:* display the first   25   pernicious numbers. -:* display all pernicious numbers between   888,888,877   and   888,888,888   (inclusive). -:* display each list of integers on one line (which may or may not include a title).
    +;Task +* display the first   '''25'''   pernicious numbers. +* display all pernicious numbers between   '''888,888,877'''   and   '''888,888,888'''   (inclusive). +* display each list of integers on one line   (which may or may not include a title). ;See also diff --git a/Task/Pernicious-numbers/Groovy/pernicious-numbers.groovy b/Task/Pernicious-numbers/Groovy/pernicious-numbers.groovy new file mode 100644 index 0000000000..1f7cff4d27 --- /dev/null +++ b/Task/Pernicious-numbers/Groovy/pernicious-numbers.groovy @@ -0,0 +1,24 @@ +class example{ +static void main(String[] args){ +def n=0; +def counter=0; +while(counter<25){ +if(print(n)){ +counter++;} +n=n+1; +} +println(); +def x=888888877; +while(x<888888889){ +print(x); +x++;} +} +static def print(def a){ +def primes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]; +def c=Integer.toBinaryString(a); +String d=c; +def e=0; +for(i in d){if(i=='1'){e++;}} +if(e in primes){printf(a+" ");return 1;} +} +} diff --git a/Task/Pernicious-numbers/jq/pernicious-numbers.jq b/Task/Pernicious-numbers/Jq/pernicious-numbers.jq similarity index 100% rename from Task/Pernicious-numbers/jq/pernicious-numbers.jq rename to Task/Pernicious-numbers/Jq/pernicious-numbers.jq diff --git a/Task/Pernicious-numbers/Kotlin/pernicious-numbers.kotlin b/Task/Pernicious-numbers/Kotlin/pernicious-numbers.kotlin new file mode 100644 index 0000000000..ecf26fb118 --- /dev/null +++ b/Task/Pernicious-numbers/Kotlin/pernicious-numbers.kotlin @@ -0,0 +1,47 @@ +// version 1.0.5-2 + +fun isPrime(n: Int): Boolean { + if (n < 2) return false + if (n % 2 == 0) return n == 2 + if (n % 3 == 0) return n == 3 + var d : Int = 5 + while (d * d <= n) { + if (n % d == 0) return false + d += 2 + if (n % d == 0) return false + d += 4 + } + return true +} + +fun getPopulationCount(n: Int): Int { + if (n <= 0) return 0 + var nn = n + var sum = 0 + while (nn > 0) { + sum += nn % 2 + nn /= 2 + } + return sum +} + +fun isPernicious(n: Int): Boolean = isPrime(getPopulationCount(n)) + +fun main(args: Array) { + var n = 1 + var count = 0 + println("The first 25 pernicious numbers are:\n") + do { + if (isPernicious(n)) { + print("$n ") + count++ + } + n++ + } + while (count < 25) + println("\n") + println("The pernicious numbers between 888,888,877 and 888,888,888 inclusive are:\n") + for (i in 888888877..888888888) { + if (isPernicious(i)) print("$i ") + } +} diff --git a/Task/Pernicious-numbers/Phix/pernicious-numbers.phix b/Task/Pernicious-numbers/Phix/pernicious-numbers.phix new file mode 100644 index 0000000000..4356550494 --- /dev/null +++ b/Task/Pernicious-numbers/Phix/pernicious-numbers.phix @@ -0,0 +1,28 @@ +function is_prime(atom n) + if n<2 then return false end if + for i=2 to floor(sqrt(n)) do + if mod(n,i)=0 then return false end if + end for + return true +end function + +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 +?s +s = {} +for i=888_888_877 to 888_888_888 do + if pernicious(i) then + s &= i + end if +end for +?s diff --git a/Task/Pernicious-numbers/PowerShell/pernicious-numbers.psh b/Task/Pernicious-numbers/PowerShell/pernicious-numbers-1.psh similarity index 100% rename from Task/Pernicious-numbers/PowerShell/pernicious-numbers.psh rename to Task/Pernicious-numbers/PowerShell/pernicious-numbers-1.psh diff --git a/Task/Pernicious-numbers/PowerShell/pernicious-numbers-2.psh b/Task/Pernicious-numbers/PowerShell/pernicious-numbers-2.psh new file mode 100644 index 0000000000..9773cde041 --- /dev/null +++ b/Task/Pernicious-numbers/PowerShell/pernicious-numbers-2.psh @@ -0,0 +1,44 @@ +function Select-PerniciousNumber +{ + [CmdletBinding()] + [OutputType([int])] + Param + ( + [Parameter(Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true, + Position=0)] + $InputObject + ) + + Begin + { + function Test-Prime ([int]$n) + { + $n = [Math]::Abs($n) + + if ($n -eq 0 -or $n -eq 1) {return $false} + + for ($m = 2; $m -le [Math]::Sqrt($n); $m++) + { + if (($n % $m) -eq 0) {return $false} + } + + return $true + } + + [scriptblock]$popCount = {(([Convert]::ToString($this, 2)).ToCharArray() | Where-Object {$_ -eq '1'}).Count} + } + Process + { + foreach ($object in $InputObject) + { + $object | Add-Member -MemberType ScriptProperty -Name PopCount -Value $popCount -Force -PassThru | ForEach-Object { + if (Test-Prime $_.PopCount) + { + $_ + } + } + } + } +} diff --git a/Task/Pernicious-numbers/PowerShell/pernicious-numbers-3.psh b/Task/Pernicious-numbers/PowerShell/pernicious-numbers-3.psh new file mode 100644 index 0000000000..0b14b48494 --- /dev/null +++ b/Task/Pernicious-numbers/PowerShell/pernicious-numbers-3.psh @@ -0,0 +1,9 @@ +$start, $end = 0, 999999 +$range1 = $start..$end | Select-PerniciousNumber | Select-Object -First 25 + +"First {0} pernicious numbers:`n{1}`n" -f $range1.Count, ($range1 -join ", ") + +$start, $end = 888888877, 888888888 +$range2 = $start..$end | Select-PerniciousNumber + +"Pernicious numbers between {0} and {1}:`n{2}`n" -f $start, $end, ($range2 -join ", ") diff --git a/Task/Pernicious-numbers/Ruby/pernicious-numbers.rb b/Task/Pernicious-numbers/Ruby/pernicious-numbers.rb index 43f33d7d70..376c68d4da 100644 --- a/Task/Pernicious-numbers/Ruby/pernicious-numbers.rb +++ b/Task/Pernicious-numbers/Ruby/pernicious-numbers.rb @@ -3,7 +3,7 @@ require "prime" class Integer def popcount - to_s(2).count("1") + to_s(2).count("1") #Ruby 2.4: digits(2).count(1) end def pernicious? diff --git a/Task/Pernicious-numbers/S-lang/pernicious-numbers.slang b/Task/Pernicious-numbers/S-lang/pernicious-numbers.slang new file mode 100644 index 0000000000..6c575d7be3 --- /dev/null +++ b/Task/Pernicious-numbers/S-lang/pernicious-numbers.slang @@ -0,0 +1,46 @@ +% Simplistic prime-test from prime-by-trial-division: +define is_prime(n) +{ + if (n <= 1) return(0); + if (n == 2) return(1); + if ((n & 1) == 0) return(0); + + variable mx = int(sqrt(n)), i; + + _for i (3, mx, 1) { + if ((n mod i) == 0) + return(0); + } + return(1); +} + +define population(n) +{ + variable pc = 0; + do { + if (n & 1) pc++; + n /= 2; + } + while (n); + return(pc); +} + +define is_pernicious(n) +{ + return(is_prime(population(n))); +} + +variable plist = {}, n = 0; +while (length(plist) < 25) { + n++; + if (is_pernicious(n)) + list_append(plist, string(n)); +} +print(strjoin(list_to_array(plist), " ")); + +plist = {}; +_for n (888888877, 888888888, 1) { + if (is_pernicious(n)) + list_append(plist, string(n)); +} +print(strjoin(list_to_array(plist), " ")); diff --git a/Task/Pernicious-numbers/Zkl/pernicious-numbers-1.zkl b/Task/Pernicious-numbers/Zkl/pernicious-numbers-1.zkl new file mode 100644 index 0000000000..f299093fe0 --- /dev/null +++ b/Task/Pernicious-numbers/Zkl/pernicious-numbers-1.zkl @@ -0,0 +1,10 @@ +primes:=T(2,3,5,7,11,13,17,19,23,29,31,37,41); +N:=0; foreach n in ([2..]){ + if(n.num1s : primes.holds(_)){ + print(n," "); + if((N+=1)==25) break; + } +} +foreach n in ([0d888888877..888888888]){ + if (n.num1s : primes.holds(_)) "%,d; ".fmt(n).print(); +} diff --git a/Task/Pernicious-numbers/Zkl/pernicious-numbers-2.zkl b/Task/Pernicious-numbers/Zkl/pernicious-numbers-2.zkl new file mode 100644 index 0000000000..956bb2a64e --- /dev/null +++ b/Task/Pernicious-numbers/Zkl/pernicious-numbers-2.zkl @@ -0,0 +1,5 @@ +primes:=T(2,3,5,7,11,13,17,19,23,29,31,37,41); +p:='wrap(n){ primes.holds(n.num1s) }; + +[1..].filter(25,p).toString(*).println(); +[0d888888877..888888888].filter(p).println(); diff --git a/Task/Phrase-reversals/AppleScript/phrase-reversals.applescript b/Task/Phrase-reversals/AppleScript/phrase-reversals.applescript index 8cf6c567bb..c4fd1a8993 100644 --- a/Task/Phrase-reversals/AppleScript/phrase-reversals.applescript +++ b/Task/Phrase-reversals/AppleScript/phrase-reversals.applescript @@ -1,39 +1,71 @@ --- _reverse :: [a] -> [a] -on _reverse(xs) - if class of xs is text then - (reverse of characters of xs) as text - else - reverse of xs - end if -end _reverse +-- REVERSED PHRASES, COMPONENT WORDS, AND WORD ORDER --------------------- + +-- reverseString, reverseEachWord, reverseWordOrder :: String -> String +on stringReverse(s) + |reverse|(s) +end stringReverse + +on reverseEachWord(s) + wordLevel(curry(my map)'s |λ|(my |reverse|))'s |λ|(s) +end reverseEachWord + +on reverseWordOrder(s) + wordLevel(my |reverse|)'s |λ|(s) +end reverseWordOrder --- TEST +-- wordLevel :: ([String] -> [String]) -> String -> String +on wordLevel(f) + script + on |λ|(x) + unwords(mReturn(f)'s |λ|(|words|(x))) + end |λ| + end script +end wordLevel -on run {} - set phrase to "rosetta code phrase reversal" - unlines({¬ - _reverse(phrase), ¬ - unwords(map(_reverse, _words(phrase))), ¬ - unwords(_reverse(_words(phrase)))}) +-- TEST ---------------------------------------------------------------------- +on run + unlines(|<*>|({stringReverse, reverseEachWord, reverseWordOrder}, ¬ + {"rosetta code phrase reversal"})) + + --> + + -- "lasrever esarhp edoc attesor + -- attesor edoc esarhp lasrever + -- reversal phrase code rosetta" end run +-- GENERIC FUNCTIONS --------------------------------------------------------- --- GENERIC FUNCTIONS +-- A list of functions applied to a list of arguments +-- (<*> | ap) :: [(a -> b)] -> [a] -> [b] +on |<*>|(fs, xs) + set {nf, nx} to {length of fs, length of xs} + set acc to {} + repeat with i from 1 to nf + tell mReturn(item i of fs) + repeat with j from 1 to nx + set end of acc to |λ|(contents of (item j of xs)) + end repeat + end tell + end repeat + return acc +end |<*>| --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map +-- curry :: (Script|Handler) -> Script +on curry(f) + script + on |λ|(a) + script + on |λ|(b) + |λ|(a, b) of mReturn(f) + end |λ| + end script + end |λ| + end script +end curry -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) @@ -43,10 +75,43 @@ on intercalate(strText, lstText) return strJoined end intercalate --- _words :: String -> [String] -on _words(str) - words of str -end _words +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- reverse :: [a] -> [a] +on |reverse|(xs) + if class of xs is text then + (reverse of characters of xs) as text + else + reverse of xs + end if +end |reverse| + +-- words :: String -> [String] +on |words|(s) + words of s +end |words| -- unlines :: [String] -> String on unlines(lstLines) @@ -57,15 +122,3 @@ end unlines on unwords(lstWords) intercalate(space, lstWords) end unwords - --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn diff --git a/Task/Phrase-reversals/BaCon/phrase-reversals.bacon b/Task/Phrase-reversals/BaCon/phrase-reversals.bacon new file mode 100644 index 0000000000..dfdf2eb0a3 --- /dev/null +++ b/Task/Phrase-reversals/BaCon/phrase-reversals.bacon @@ -0,0 +1,7 @@ +phrase$ = "rosetta code phrase reversal" + +PRINT REVERSE$(phrase$) + +PRINT REV$(REVERSE$(phrase$)) + +PRINT REV$(phrase$) diff --git a/Task/Phrase-reversals/Gambas/phrase-reversals.gambas b/Task/Phrase-reversals/Gambas/phrase-reversals.gambas new file mode 100644 index 0000000000..5f4dce85b3 --- /dev/null +++ b/Task/Phrase-reversals/Gambas/phrase-reversals.gambas @@ -0,0 +1,36 @@ +Public Sub Main() +Dim sString As String = "rosetta code phrase reversal" 'The string +Dim sNewString, sTemp As String 'String variables +Dim siCount As Short 'Counter +Dim sWord As New String[] 'Word store + +For siCount = Len(sString) DownTo 1 'Loop backwards through the string + sNewString &= Mid(sString, sicount, 1) 'Add each character to the new string +Next + +Print "Original string = \t" & sString & "\n" & 'Print the original string + "Reversed string = \t" & sNewString 'Print the reversed string + +sNewString = "" 'Reset sNewString + +For Each sTemp In Split(sString, " ") 'Split the original string by the spaces + sWord.Add(sTemp) 'Add each word to sWord array +Next + +For siCount = sWord.max DownTo 0 'Loop backward through each word in sWord + sNewString &= sWord[siCount] & " " 'Add each word to to sNewString +Next + +Print "Reversed word order = \t" & sNewString 'Print reversed word order + +sNewString = "" 'Reset sNewString +For Each sTemp In sWord 'For each word in sWord + For siCount = Len(sTemp) DownTo 1 'Loop backward through the word + sNewString &= Mid(sTemp, siCount, 1) 'Add the characters to sNewString + Next + sNewString &= " " 'Add a space at the end of each word +Next + +Print "Words reversed = \t" & sNewString 'Print words reversed + +End diff --git a/Task/Phrase-reversals/Haskell/phrase-reversals.hs b/Task/Phrase-reversals/Haskell/phrase-reversals.hs index 7e028929ea..3773197f03 100644 --- a/Task/Phrase-reversals/Haskell/phrase-reversals.hs +++ b/Task/Phrase-reversals/Haskell/phrase-reversals.hs @@ -1,6 +1,15 @@ -phrase = "rosetta code phrase reversal" +reverseString, reverseEachWord, reverseWordOrder :: String -> String +reverseString = reverse -main = do - putStrLn $ reverse phrase - putStrLn $ unwords . map reverse . words $ phrase - putStrLn $ unwords . reverse . words $ phrase +reverseEachWord = wordLevel (fmap reverse) + +reverseWordOrder = wordLevel reverse + +wordLevel :: ([String] -> [String]) -> String -> String +wordLevel f = unwords . f . words + +main :: IO () +main = + (putStrLn . unlines) $ + [reverseString, reverseEachWord, reverseWordOrder] <*> + ["rosetta code phrase reversal"] diff --git a/Task/Phrase-reversals/JavaScript/phrase-reversals.js b/Task/Phrase-reversals/JavaScript/phrase-reversals-1.js similarity index 100% rename from Task/Phrase-reversals/JavaScript/phrase-reversals.js rename to Task/Phrase-reversals/JavaScript/phrase-reversals-1.js diff --git a/Task/Phrase-reversals/JavaScript/phrase-reversals-2.js b/Task/Phrase-reversals/JavaScript/phrase-reversals-2.js new file mode 100644 index 0000000000..a43f807fa4 --- /dev/null +++ b/Task/Phrase-reversals/JavaScript/phrase-reversals-2.js @@ -0,0 +1,65 @@ +(() => { + 'use strict' + + // reverseString, reverseEachWord, reverseWordOrder :: String -> String + const + reverseString = s => reverse(s), + + reverseEachWord = s => wordLevel(map(reverse))(s), + + reverseWordOrder = s => wordLevel(reverse)(s); + + // wordLevel :: ([String] -> [String]) -> String -> String + const wordLevel = f => + x => unwords(f(words(x))); + + + // GENERIC FUNCTIONS ----------------------------------------------------- + + // A list of functions applied to a list of arguments + // <*> :: [(a -> b)] -> [a] -> [b] + const ap = (fs, xs) => // + [].concat.apply([], fs.map(f => // + [].concat.apply([], xs.map(x => [f(x)])))); + + // 2 or more arguments + // curry :: Function -> Function + const curry = (f, ...args) => { + const go = xs => xs.length >= f.length ? (f.apply(null, xs)) : + function () { + return go(xs.concat(Array.from(arguments))); + }; + return go([].slice.call(args, 1)); + }; + + // map :: (a -> b) -> [a] -> [b] + const map = curry((f, xs) => xs.map(f)); + + // reverse :: [a] -> [a] + const reverse = curry(xs => + typeof xs === 'string' ? ( + xs.split('') + .reverse() + .join('') + ) : xs.slice(0) + .reverse()); + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + // unwords :: [String] -> String + const unwords = xs => xs.join(' '); + + // words :: String -> [String] + const words = s => s.split(/\s+/); + + + // TEST ------------------------------------------------------------------ + return unlines( + ap([ + reverseString, + reverseEachWord, + reverseWordOrder + ], ["rosetta code phrase reversal"]) + ); +})(); diff --git a/Task/Phrase-reversals/jq/phrase-reversals.jq b/Task/Phrase-reversals/Jq/phrase-reversals.jq similarity index 100% rename from Task/Phrase-reversals/jq/phrase-reversals.jq rename to Task/Phrase-reversals/Jq/phrase-reversals.jq diff --git a/Task/Phrase-reversals/Kotlin/phrase-reversals.kotlin b/Task/Phrase-reversals/Kotlin/phrase-reversals.kotlin new file mode 100644 index 0000000000..79cf46ff11 --- /dev/null +++ b/Task/Phrase-reversals/Kotlin/phrase-reversals.kotlin @@ -0,0 +1,12 @@ +// version 1.0.6 + +fun reverseEachWord(s: String) = s.split(" ").map { it.reversed() }.joinToString(" ") + +fun main(args: Array) { + val original = "rosetta code phrase reversal" + val reversed = original.reversed() + println("Original string => $original") + println("Reversed string => $reversed") + println("Reversed words => ${reverseEachWord(original)}") + println("Reversed order => ${reverseEachWord(reversed)}") +} diff --git a/Task/Phrase-reversals/PlainTeX/phrase-reversals.tex b/Task/Phrase-reversals/PlainTeX/phrase-reversals.tex new file mode 100644 index 0000000000..4f07a6e36f --- /dev/null +++ b/Task/Phrase-reversals/PlainTeX/phrase-reversals.tex @@ -0,0 +1,39 @@ +\def\afterfi#1#2\fi{#2\fi#1} +\def\RevSingleWord#1{\RevSingleWordi{}#1\RSWA\RSWB\RSWB\RSWB\RSWB\RSWB\RSWB\RSWB\RSWB\RSWA} +\def\RevSingleWordi#1#2#3#4#5#6#7#8#9{\RSWgobtoB#9\RSWend\RSWB\RevSingleWordi{#9#8#7#6#5#4#3#2#1}} +\def\RSWend\RSWB\RevSingleWordi#1#2\RSWA{\RSWgobtoA#1} +\def\RSWgobtoA#1\RSWA{}\def\RSWgobtoB#1\RSWB{} +%--- +\def\firstchartonil#1#2\nil{#1} +\def\RevOrderSameWords#1{\RevOrderSameWordsi{}#1 \. \* \* \* \* \* \* \* \* \.} +\def\RevOrderSameWordsi#1#2 #3 #4 #5 #6 #7 #8 #9 {% + \expandafter\ifx\expandafter\*\firstchartonil#9\nil + \expandafter\ROSWend\else\expandafter\RevOrderSameWordsi\fi{#9 #8 #7 #6 #5 #4 #3 #2#1}% +} +\def\ROSWend#1#2\.{\ROSWendi#1} +\def\ROSWendi#1\.{\romannumeral-`\-} +%--- +\def\ROWquark{\ROWquark} +\def\RevOnlyWords#1{\edef\ROWtemp{\noexpand\RevOnlyWordsi{}#1 \noexpand\ROWquark\space}\ROWtemp} +\def\RevOnlyWordsi#1#2 {% + \ifx\ROWquark#2\afterfi{\ROWgoblastspace#1\nil}% + \else\afterfi{\RevOnlyWordsi{#1\RevSingleWord{#2} }}% + \fi +} +\def\ROWgoblastspace#1 \nil{#1} +%--- +\def\RevAll#1{\RevAlli{}#1 \. \* \* \* \* \* \* \* \* \.\:} +\def\RevAlli#1#2 #3 #4 #5 #6 #7 #8 #9 {% + \expandafter\ifx\expandafter\*\firstchartonil#9\nil + \expandafter\RAWend\else\expandafter\RevAlli\fi{#9 #8 #7 #6 #5 #4 #3 #2#1}% +} +\def\RAWend#1#2\.{\RAWendi#1} +\def\RAWendi#1\.{\expandafter\RAWendii\romannumeral-`\-} +\def\RAWendii#1\:{\RevOnlyWords{#1}} +%-- +\halign{#\hfil: &#\cr +Initial&rosetta code phrase reversal\cr +Reverse all&\RevAll{rosetta code phrase reversal}\cr +Reverse order, same words&\RevOrderSameWords{rosetta code phrase reversal}\cr +Reverse only words&\RevOnlyWords{rosetta code phrase reversal}\cr\crcr} +\bye diff --git a/Task/Phrase-reversals/PureBasic/phrase-reversals.purebasic b/Task/Phrase-reversals/PureBasic/phrase-reversals.purebasic new file mode 100644 index 0000000000..68ceddb6e7 --- /dev/null +++ b/Task/Phrase-reversals/PureBasic/phrase-reversals.purebasic @@ -0,0 +1,31 @@ +#TEXT="rosetta code phrase reversal" + +If OpenConsole("rosetta code phrase reversal") + Define idx.i=1, txt.s="" + + Print(~"Original:\t\t") + PrintN(#TEXT) + + Print(~"Reversed:\t\t") + PrintN(ReverseString(#TEXT)) + + Print(~"Reversed words:\t\t") + txt=StringField(#TEXT,idx," ") + While Len(txt) + Print(ReverseString(txt)+" ") + idx+1 + txt=StringField(#TEXT,idx," ") + Wend + PrintN("") + + Print(~"Reversed order:\t\t") + idx-1 + txt=StringField(#TEXT,idx," ") + While Len(txt) + Print(txt+" ") + If idx>1 : idx-1 : Else : Break : EndIf + txt=StringField(#TEXT,idx," ") + Wend + + Input() +EndIf diff --git a/Task/Phrase-reversals/Python/phrase-reversals.py b/Task/Phrase-reversals/Python/phrase-reversals.py index ec89d1e698..f2929c67ed 100644 --- a/Task/Phrase-reversals/Python/phrase-reversals.py +++ b/Task/Phrase-reversals/Python/phrase-reversals.py @@ -3,6 +3,6 @@ 'lasrever esarhp edoc attesor' >>> ' '.join(word[::-1] for word in phrase.split()) # Words reversed. 'attesor edoc esarhp lasrever' ->>> ' '.join(word for word in phrase.split()[::-1]) # Word order reversed. +>>> ' '.join(phrase.split()[::-1]) # Word order reversed. 'reversal phrase code rosetta' >>> diff --git a/Task/Phrase-reversals/Scala/phrase-reversals.scala b/Task/Phrase-reversals/Scala/phrase-reversals.scala new file mode 100644 index 0000000000..f1bb4c8666 --- /dev/null +++ b/Task/Phrase-reversals/Scala/phrase-reversals.scala @@ -0,0 +1,6 @@ +object PhraseReversals extends App { + val phrase = scala.io.StdIn.readLine + println(phrase.reverse) + println(phrase.split(' ').map(_.reverse).mkString(" ")) + println(phrase.split(' ').reverse.mkString(" ")) +} diff --git a/Task/Phrase-reversals/Swift/phrase-reversals.swift b/Task/Phrase-reversals/Swift/phrase-reversals.swift new file mode 100644 index 0000000000..156533a89a --- /dev/null +++ b/Task/Phrase-reversals/Swift/phrase-reversals.swift @@ -0,0 +1,38 @@ +func reverseString(s:String)->String{ + var temp = [Character]() + for i in s.characters{ + temp.append(i) + } + var j=s.characters.count-1 + for i in s.characters{ + temp[j]=i + j-=1 + } + return String(temp) +} + +func reverseWord(s:String)->String{ + var temp = [Character]() + var result:String="" + for i in s.characters{ + if i==" "{ + result += "\(reverseString(s:String(temp))) " + temp=[Character]() + } + else { + temp.append(i) + } + if i==s[s.index(before: s.endIndex)]{ + result += (reverseString(s:String(temp))) + } + } + return result +} + +func flipString(s:String)->String{ + return reverseWord(s:reverseString(s:s)) +} +print(str) +print(reverseString(s:str)) +print(reverseWord(s:str)) +print(flipString(s:str)) diff --git a/Task/Phrase-reversals/Zkl/phrase-reversals.zkl b/Task/Phrase-reversals/Zkl/phrase-reversals.zkl new file mode 100644 index 0000000000..4d40dc42c6 --- /dev/null +++ b/Task/Phrase-reversals/Zkl/phrase-reversals.zkl @@ -0,0 +1,11 @@ +zkl: var str="rosetta code phrase reversal" +rosetta code phrase reversal + +zkl: str.reverse() #1 +lasrever esarhp edoc attesor + +zkl: str.split().apply("reverse").concat(" ") #2 string to list to string +attesor edoc esarhp lasrever + +zkl: str.split().reverse().concat(" ") #3 +reversal phrase code rosetta diff --git a/Task/Pi/Bc/pi.bc b/Task/Pi/Bc/pi.bc new file mode 100644 index 0000000000..0b6aa90782 --- /dev/null +++ b/Task/Pi/Bc/pi.bc @@ -0,0 +1,30 @@ +#!/usr/bin/bc -l + +scaleinc= 20 + +define zeropad ( n ) { + auto m + for ( m= scaleinc - 1; m > 0; --m ) { + if ( n < 10^m ) { + print "0" + } + } + return ( n ) +} + +wantscale= scaleinc - 2 +scale= wantscale + 2 +oldpi= 4*a(1) +scale= wantscale +oldpi= oldpi / 1 +oldpi +while( 1 ) { + wantscale= wantscale + scaleinc + scale= wantscale + 2 + pi= 4*a(1) + scale= 0 + digits= ((pi - oldpi) * 10^wantscale) / 1 + zeropad( digits ) + scale= wantscale + oldpi= pi / 1 +} diff --git a/Task/Pi/C++/pi.cpp b/Task/Pi/C++/pi.cpp deleted file mode 100644 index dc4b46fa5d..0000000000 --- a/Task/Pi/C++/pi.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include "gmp.h" - -void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) { - mpf_add (out1, in1, in2); - mpf_div_ui (out1, out1, 2); - mpf_mul (out2, in1, in2); - mpf_sqrt (out2, out2); -} - -int main (void) { - mpf_set_default_prec (300000); - mpf_t x0, y0, resA, resB, Z, var; - - mpf_init_set_ui (x0, 1); - mpf_init_set_d (y0, 0.5); - mpf_sqrt (y0, y0); - mpf_init (resA); - mpf_init (resB); - mpf_init_set_d (Z, 0.25); - mpf_init (var); - - int n = 1; - for(int i=0; i<8; i++){ - agm(x0, y0, resA, resB); - mpf_sub(var, resA, x0); - mpf_mul(var, var, var); - mpf_mul_ui(var, var, n); - mpf_sub(Z, Z, var); - n += n; - agm(resA, resB, x0, y0); - mpf_sub(var, x0, resA); - mpf_mul(var, var, var); - mpf_mul_ui(var, var, n); - mpf_sub(Z, Z, var); - n += n; - } - mpf_mul(x0, x0, x0); - mpf_div(x0, x0, Z); - gmp_printf ("%.100000Ff\n", x0); - return 0; -} diff --git a/Task/Pi/Crystal/pi.crystal b/Task/Pi/Crystal/pi.crystal new file mode 100644 index 0000000000..b58d3db89b --- /dev/null +++ b/Task/Pi/Crystal/pi.crystal @@ -0,0 +1,30 @@ +require "big_int" + +def pi + q, r, t, k, n, l = [1, 0, 1, 1, 3, 3].map { |n| BigInt.new(n) } + dot_written = false + loop do + if 4*q + r - t < n*t + yield n + unless dot_written + yield '.' + dot_written = true + end + nr = 10*(r - n*t) + n = ((10*(3*q + r)) / t) - 10*n + q *= 10 + r = nr + else + nr = (2*q + r) * l + nn = (q*(7*k + 2) + r*l) / (t*l) + q *= k + t *= l + l += 2 + k += 1 + n = nn + r = nr + end + end +end + +pi { |digit_or_dot| print digit_or_dot; STDOUT.flush } diff --git a/Task/Pi/Haskell/pi-1.hs b/Task/Pi/Haskell/pi-1.hs index 9bd5c10c39..3295ae2004 100644 --- a/Task/Pi/Haskell/pi-1.hs +++ b/Task/Pi/Haskell/pi-1.hs @@ -1,5 +1,19 @@ -pi_ = g(1,0,1,1,3,3) where - g (q,r,t,k,n,l) = - if 4*q+r-t < n*t - then n : g (10*q, 10*(r-n*t), t, k, div (10*(3*q+r)) t - 10*n, l) - else g (q*k, (2*q+r)*l, t*l, k+1, div (q*(7*k+2)+r*l) (t*l), l+2) +pi_ = g (1, 0, 1, 1, 3, 3) + where + g (q, r, t, k, n, l) = + if 4 * q + r - t < n * t + then n : + g + ( 10 * q + , 10 * (r - n * t) + , t + , k + , div (10 * (3 * q + r)) t - 10 * n + , l) + else g + ( q * k + , (2 * q + r) * l + , t * l + , k + 1 + , div (q * (7 * k + 2) + r * l) (t * l) + , l + 2) diff --git a/Task/Pi/jq/pi-1.jq b/Task/Pi/Jq/pi-1.jq similarity index 100% rename from Task/Pi/jq/pi-1.jq rename to Task/Pi/Jq/pi-1.jq diff --git a/Task/Pi/jq/pi-2.jq b/Task/Pi/Jq/pi-2.jq similarity index 100% rename from Task/Pi/jq/pi-2.jq rename to Task/Pi/Jq/pi-2.jq diff --git a/Task/Pi/Julia/pi.julia b/Task/Pi/Julia/pi.julia index d1a5ce69bc..370ce3e203 100644 --- a/Task/Pi/Julia/pi.julia +++ b/Task/Pi/Julia/pi.julia @@ -1,10 +1,10 @@ -prec = get_bigfloat_precision() +prec = precision(BigFloat) spi = "" digit = 1 while true if digit > length(spi) - 6 prec *= 2 - set_bigfloat_precision(prec) + setprecision(prec) spi = string(big(π)) end print(spi[digit]) diff --git a/Task/Pi/Kotlin/pi.kotlin b/Task/Pi/Kotlin/pi.kotlin new file mode 100644 index 0000000000..2ed9537361 --- /dev/null +++ b/Task/Pi/Kotlin/pi.kotlin @@ -0,0 +1,45 @@ +// version 1.1.2 + +import java.math.BigInteger + +val ZERO = BigInteger.ZERO +val ONE = BigInteger.ONE +val TWO = BigInteger.valueOf(2L) +val THREE = BigInteger.valueOf(3L) +val FOUR = BigInteger.valueOf(4L) +val SEVEN = BigInteger.valueOf(7L) +val TEN = BigInteger.TEN + +fun calcPi() { + var nn: BigInteger + var nr: BigInteger + var q = ONE + var r = ZERO + var t = ONE + var k = ONE + var n = THREE + var l = THREE + var first = true + while (true) { + if (FOUR * q + r - t < n * t) { + print(n) + if (first) { print ("."); first = false } + nr = TEN * (r - n * t) + n = TEN * (THREE * q + r) / t - TEN * n + q *= TEN + r = nr + } + else { + nr = (TWO * q + r) * l + nn = (q * SEVEN * k + TWO + r * l) / (t * l) + q *= k + t *= l + l += TWO + k += ONE + n = nn + r = nr + } + } +} + +fun main(args: Array) = calcPi() diff --git a/Task/Pi/PowerShell/pi-1.psh b/Task/Pi/PowerShell/pi-1.psh new file mode 100644 index 0000000000..7ce129d03b --- /dev/null +++ b/Task/Pi/PowerShell/pi-1.psh @@ -0,0 +1,57 @@ +Function Get-Pi ( $Digits ) + { + $Big = [bigint[]](0..10) + + $ndigits = 0 + $Output = "" + + $q = $t = $k = $Big[1] + $r = $Big[0] + $l = $n = $Big[3] + # Calculate first digit + $nr = ( $Big[2] * $q + $r ) * $l + $nn = ( $q * ( $Big[7] * $k + $Big[2] ) + $r * $l ) / ( $t * $l ) + $q *= $k + $t *= $l + $l += $Big[2] + $k = $k + $Big[1] + $n = $nn + $r = $nr + + $Output += [string]$n + '.' + $ndigits++ + + $nr = $Big[10] * ( $r - $n * $t ) + $n = ( ( $Big[10] * ( 3 * $q + $r ) ) / $t ) - 10 * $n + $q *= $Big[10] + $r = $nr + + While ( $ndigits -lt $Digits ) + { + While ( $ndigits % 100 -ne 0 -or -not $Output ) + { + If ( $Big[4] * $q + $r - $t -lt $n * $t ) + { + $Output += [string]$n + $ndigits++ + $nr = $Big[10] * ( $r - $n * $t ) + $n = ( ( $Big[10] * ( 3 * $q + $r ) ) / $t ) - 10 * $n + $q *= $Big[10] + $r = $nr + } + Else + { + $nr = ( $Big[2] * $q + $r ) * $l + $nn = ( $q * ( $Big[7] * $k + $Big[2] ) + $r * $l ) / ( $t * $l ) + $q *= $k + $t *= $l + $l += $Big[2] + $k = $k + $Big[1] + $n = $nn + $r = $nr + } + } + $Output + $Output = "" + } + } diff --git a/Task/Pi/PowerShell/pi-2.psh b/Task/Pi/PowerShell/pi-2.psh new file mode 100644 index 0000000000..2702b3f1ad --- /dev/null +++ b/Task/Pi/PowerShell/pi-2.psh @@ -0,0 +1 @@ +[math]::pi diff --git a/Task/Pi/PowerShell/pi-3.psh b/Task/Pi/PowerShell/pi-3.psh new file mode 100644 index 0000000000..79df1ba6db --- /dev/null +++ b/Task/Pi/PowerShell/pi-3.psh @@ -0,0 +1,2 @@ +.Net digits of pi +3.14159265358979 diff --git a/Task/Pi/REXX/pi.rexx b/Task/Pi/REXX/pi-1.rexx similarity index 100% rename from Task/Pi/REXX/pi.rexx rename to Task/Pi/REXX/pi-1.rexx diff --git a/Task/Pi/REXX/pi-2.rexx b/Task/Pi/REXX/pi-2.rexx new file mode 100644 index 0000000000..f01d307255 --- /dev/null +++ b/Task/Pi/REXX/pi-2.rexx @@ -0,0 +1,32 @@ +/*REXX program spits out decimal digits of pi (one digit at a time) until Ctrl-Break.*/ +signal on halt +parse arg digs oFID . /*obtain optional argument from the CL.*/ +if digs=='' | digs=="," then digs= 300 /*Not specified? Then use the default.*/ +if oFID=='' | oFID=="," then oFID='PI_SPIT2.OUT' /*" " " " " " */ +numeric digits digs /*with bigger digs, spitting is slower.*/ +q=1; r=0; t=1; k=1; n=3; L=3; z=0 /*define some REXX variables. */ +dot=1 /*DOT≡a flag when a dot in pi is shown.*/ + do until z==digs; qq= q+q /* qq is a fast version of: q*2 */ + tn= t*n /* t*n is used twice (below). */ + if qq+qq+r-t < tn then do; z= z+1 /* qq+qq is faster than qq*2 */ + call charout , n + call charout oFID, n + if dot then do; dot=0; call charout , . + call charout oFID, . + end + nr= (r - tn) * 10 + n = ((( (qq+q+r) * 10) / t) - n*10) %1 + q = q*10 + end + else do; nr= (qq+r) * L + tL= t*L + n = (q * (k*7 + 2) + r*L) / tL %1 + q = q*k + t = tL + L = L+2 + k = k+1 + end /* %1≡fast way doing TRUNC of a number.*/ + r=nr + end /*forever*/ +exit +halt: say; say 'PI_SPIT2 halted via use of Ctrl-Break.'; exit diff --git a/Task/Pi/Ruby/pi-1.rb b/Task/Pi/Ruby/pi-1.rb deleted file mode 100644 index ae9e30ba4c..0000000000 --- a/Task/Pi/Ruby/pi-1.rb +++ /dev/null @@ -1,20 +0,0 @@ -# Calculate Pi using the Arithmetic Geometric Mean of 1 and 1/sqrt(2) -# -# -# Nigel_Galloway -# March 8th., 2012. -# -require 'flt' -Flt::BinNum.Context.precision = 8192 -a = n = 1 -g = 1 / Flt::BinNum(2).sqrt -z = 0.25 -(0..17).each{ - x = [(a + g) * 0.5, (a * g).sqrt] - var = x[0] - a - z -= var * var * n - n += n - a = x[0] - g = x[1] -} -puts a * a / z diff --git a/Task/Pi/Ruby/pi-2.rb b/Task/Pi/Ruby/pi-2.rb deleted file mode 100644 index be243ea97d..0000000000 --- a/Task/Pi/Ruby/pi-2.rb +++ /dev/null @@ -1,28 +0,0 @@ -def pi - q, r, t, k, n, l = 1, 0, 1, 1, 3, 3 - dot = nil - loop do - if 4*q+r-t < n*t - yield n - if dot.nil? - yield '.' - dot = '.' - end - nr = 10*(r-n*t) - n = ((10*(3*q+r)) / t) - 10*n - q *= 10 - r = nr - else - nr = (2*q+r) * l - nn = (q*(7*k+2)+r*l) / (t*l) - q *= k - t *= l - l += 2 - k += 1 - n = nn - r = nr - end - end -end - -pi {|digit| print digit; $stdout.flush} diff --git a/Task/Pi/Sidef/pi.sidef b/Task/Pi/Sidef/pi.sidef index 04e7e0a169..cb27c578ec 100644 --- a/Task/Pi/Sidef/pi.sidef +++ b/Task/Pi/Sidef/pi.sidef @@ -1,26 +1,26 @@ func pi(callback) { - var (q, r, t, k, n, l) = (1, 0, 1, 1, 3, 3); + var (q, r, t, k, n, l) = (1, 0, 1, 1, 3, 3) loop { if ((4*q + r - t) < n*t) { - callback(n); - static _dot = callback('.'); - var nr = 10*(r-n*t); - n = (int((10*(3*q + r)) / t) - 10*n); - q *= 10; - r = nr; + callback(n) + static _dot = callback('.') + var nr = 10*(r - n*t) + n = ((10*(3*q + r)) // t - 10*n) + q *= 10 + r = nr } else { - var nr = ((2*q + r) * l); - var nn = int((q*(7*k + 2) + r*l) / (t*l)); - q *= k; - t *= l; - l += 2; - k += 1; - n = nn; - r = nr; + var nr = ((2*q + r) * l) + var nn = ((q*(7*k + 2) + r*l) // (t*l)) + q *= k + t *= l + l += 2 + k += 1 + n = nn + r = nr } } } - -STDOUT.autoflush(1); -pi(func(digit){ print digit }); +  +STDOUT.autoflush(true) +pi(func(digit){ print digit }) diff --git a/Task/Pi/Zkl/pi.zkl b/Task/Pi/Zkl/pi.zkl new file mode 100644 index 0000000000..362169f7e3 --- /dev/null +++ b/Task/Pi/Zkl/pi.zkl @@ -0,0 +1,24 @@ +var [const] BN=Import("zklBigNum"), + one=BN(1), two=BN(2), three=BN(3), four=BN(4), seven=BN(7), ten=BN(10); + +fcn calcPiDigits{ + reg q=BN(1), r=BN(0), t=BN(1), k=BN(1), n=BN(3), l=BN(3); + first:=True; N:=0; + while(True){ if((N+=1)==1000){ GarbageMan.collect(); N=0; } // take a deep breath ... + if(four*q + r - t < n*t){ + n.print(); if(first){ print("."); first=False; } + nr:=(r - n*t).mul(ten); // 10 * (r - n * t); + n=(three*q).add(r).mul(ten) // ((10*(3*q + r))/t) - 10*n; + .div(t).sub(ten*n); + q.mul(ten); // q *= 10; + r=nr; + }else{ + nr:=(two*q).add(r).mul(l); // (2*q + r)*l; + nn:=(q*seven).mul(k).add(two) // (q*(7*k + 2) + r*l)/(t*l); + .add(r*l).div(t*l); + q.mul(k); t.mul(l); // q*=k; t*=l; + l.add(two); k.add(one); // l+=2; k++; + n=nn; r=nr; + } + } +}(); diff --git a/Task/Pick-random-element/Aime/pick-random-element.aime b/Task/Pick-random-element/Aime/pick-random-element.aime index d9bfdd1380..519a921f81 100644 --- a/Task/Pick-random-element/Aime/pick-random-element.aime +++ b/Task/Pick-random-element/Aime/pick-random-element.aime @@ -7,5 +7,5 @@ l_append(l, 'd'); l_append(l, 'e'); l_append(l, 'f'); -o_byte(l_query(l, drand(5))); +o_byte(l[drand(5)]); o_byte('\n'); diff --git a/Task/Pick-random-element/BaCon/pick-random-element.bacon b/Task/Pick-random-element/BaCon/pick-random-element.bacon new file mode 100644 index 0000000000..133e0dc4f1 --- /dev/null +++ b/Task/Pick-random-element/BaCon/pick-random-element.bacon @@ -0,0 +1,8 @@ +' Pick random element +OPTION BASE 1 +DECLARE words$[6] +FOR i = 1 TO 6 : READ words$[i] : NEXT +DATA "Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta" + +element = RANDOM(6) + 1 +PRINT "Chose ", element, ": ", words$[element] diff --git a/Task/Pick-random-element/C/pick-random-element.c b/Task/Pick-random-element/C/pick-random-element.c index e0d130354b..a1a9a3a329 100644 --- a/Task/Pick-random-element/C/pick-random-element.c +++ b/Task/Pick-random-element/C/pick-random-element.c @@ -1,13 +1,18 @@ +/*Corrected by Abhishek Ghosh, Mahalaya (19th September) 2017*/ + #include #include #include int main(){ - char array[] = { 'a', 'b', 'c' }; + char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' }; + int i; + time_t t; + srand((unsigned)time(&t)); - srand( time( 0 ) ); + for(i=0;i<30;i++){ + printf("%c\n", array[rand()%10]); + } - printf( "%c\n", array[ rand() % 3 ] ); - - return 0; + return 0; } diff --git a/Task/Pick-random-element/Elena/pick-random-element.elena b/Task/Pick-random-element/Elena/pick-random-element.elena index 94068179ce..7ef562da89 100644 --- a/Task/Pick-random-element/Elena/pick-random-element.elena +++ b/Task/Pick-random-element/Elena/pick-random-element.elena @@ -1,15 +1,14 @@ -#import system. -#import extensions. +import extensions. -#class(extension)listOp +extension listOp { - #method randomItem - = self @ (randomGenerator eval:(self length)). + randomItem + = self[randomGenerator eval(self length)]. } -#symbol program = +program = [ - #var item := (0, 1, 2, 3, 4, 5, 6, 7, 8, 9). + var item := (0, 1, 2, 3, 4, 5, 6, 7, 8, 9). - console writeLine:"I picked element ":(item randomItem). + console printLine("I picked element ",item randomItem). ]. diff --git a/Task/Pick-random-element/Gambas/pick-random-element.gambas b/Task/Pick-random-element/Gambas/pick-random-element.gambas new file mode 100644 index 0000000000..3d77ea6613 --- /dev/null +++ b/Task/Pick-random-element/Gambas/pick-random-element.gambas @@ -0,0 +1,6 @@ +Public Sub Main() +Dim sList As String[] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + +Print sList[Rand(0, 11)] + +End diff --git a/Task/Pick-random-element/Kotlin/pick-random-element.kotlin b/Task/Pick-random-element/Kotlin/pick-random-element.kotlin new file mode 100644 index 0000000000..2666869a4c --- /dev/null +++ b/Task/Pick-random-element/Kotlin/pick-random-element.kotlin @@ -0,0 +1,13 @@ +// version 1.0.6 + +fun main(args: Array) { + val list = listOf(1, 16, 3, 7, 17, 24, 34, 23, 11, 2) + println("The list consists of the following numbers:") + println(list) + val chosen = mutableSetOf() + println("\nFive elements chosen at random without duplication are:") + while (chosen.size < 5) { + val r = list[(Math.random() * list.size).toInt()] + if (chosen.add(r)) println(r) + } +} diff --git a/Task/Pick-random-element/PowerShell/pick-random-element.psh b/Task/Pick-random-element/PowerShell/pick-random-element.psh new file mode 100644 index 0000000000..a865a8f12d --- /dev/null +++ b/Task/Pick-random-element/PowerShell/pick-random-element.psh @@ -0,0 +1 @@ +1..100 | Get-Random -Count 3 diff --git a/Task/Pick-random-element/PureBasic/pick-random-element-2.purebasic b/Task/Pick-random-element/PureBasic/pick-random-element-2.purebasic index 463a724b2e..b1119df34e 100644 --- a/Task/Pick-random-element/PureBasic/pick-random-element-2.purebasic +++ b/Task/Pick-random-element/PureBasic/pick-random-element-2.purebasic @@ -1,4 +1,3 @@ -Define.i OpenConsole() a$="One" +#TAB$+ "Two" +#TAB$+ "Three" +#TAB$+ "Four" +#TAB$+ "Five" +#TAB$+ diff --git a/Task/Pick-random-element/REXX/pick-random-element-1.rexx b/Task/Pick-random-element/REXX/pick-random-element-1.rexx index 62bf330ee9..e3adaf962b 100644 --- a/Task/Pick-random-element/REXX/pick-random-element-1.rexx +++ b/Task/Pick-random-element/REXX/pick-random-element-1.rexx @@ -1,21 +1,17 @@ -/*REXX program to pick a random element from a list (tongue in cheek). */ +/*REXX program picks a random element from a list (tongue in cheek, a visual pun).*/ +_= 'hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium' +_=_ 'magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calcium' +_=_ 'scandium titanium vanadium chromium manganese iron cobalt nickel copper zinc gallium' +_=_ 'germanium arsenic selenium bromine krypton rubidium strontium yttrium zirconium' +_=_ 'niobium molybdenum technetium ruthenium rhodium palladium silver cadmium indium tin' +_=_ 'antimony tellurium iodine xenon cesium barium lanthanum cerium praseodymium' +_=_ 'neodymium promethium samarium europium gadolinium terbium dysprosium holmium erbium' +_=_ 'thulium ytterbium lutetium hafnium tantalum tungsten rhenium osmium iridium platinum' +_=_ 'gold mercury thallium lead bismuth polonium astatine radon francium radium actinium' +_=_ 'thorium protactinium uranium neptunium plutonium americium curium berkelium' +_=_ 'californium einsteinium fermium mendelevium nobelium lawrencium rutherfordium dubnium' +_=_ 'seaborgium bohrium hassium meitnerium darmstadtium roentgenium copernicium Ununtrium' -_= 'hydrogen helium lithium beryllium boron carbon nitrogen oxygen' -_=_ 'fluorine neon sodium magnesium aluminum silicon phosphorous sulfur' -_=_ 'chlorine argon potassium calcium scandium titanium vanadium chromium' -_=_ 'manganese iron cobalt nickel copper zinc gallium germanium arsenic' -_=_ 'selenium bromine krypton rubidium strontium yttrium zirconium' -_=_ 'niobium molybdenum technetium ruthenium rhodium palladium silver' -_=_ 'cadmium indium tin antimony tellurium iodine xenon cesium barium' -_=_ 'lanthanum cerium praseodymium neodymium promethium samarium europium' -_=_ 'gadolinium terbium dysprosium holmium erbium thulium ytterbium' -_=_ 'lutetium hafnium tantalum tungsten rhenium osmium irdium platinum' -_=_ 'gold mercury thallium lead bismuth polonium astatine radon francium' -_=_ 'radium actinium thorium protactinium uranium neptunium plutonium' -_=_ 'americium curium berkelium californium einsteinum fermium mendelevium' -_=_ 'nobelium lawrencium rutherfordium dubnium seaborgium bohrium hassium' -_=_ 'meitnerium darmstadtium roentgenium copernicium Ununtrium' - -w=words(_) -say 'random element =' word(_,random(1,w)) - /*stick a fork in it, we're done.*/ +#=words(_) /*obtain the number of words in list. */ +item=subword(_, random(1, #), 1) /*obtain random word (element) in list.*/ +say 'random element: ' item /*stick a fork in it, we're all done. */ diff --git a/Task/Pick-random-element/Ruby/pick-random-element-1.rb b/Task/Pick-random-element/Ruby/pick-random-element-1.rb deleted file mode 100644 index ccab5f1694..0000000000 --- a/Task/Pick-random-element/Ruby/pick-random-element-1.rb +++ /dev/null @@ -1,4 +0,0 @@ -irb(main):001:0> %w(north east south west).sample -=> "west" -irb(main):002:0> (1..100).to_a.sample(2) -=> [17, 79] diff --git a/Task/Pick-random-element/Ruby/pick-random-element-2.rb b/Task/Pick-random-element/Ruby/pick-random-element-2.rb deleted file mode 100644 index b8c1285213..0000000000 --- a/Task/Pick-random-element/Ruby/pick-random-element-2.rb +++ /dev/null @@ -1,2 +0,0 @@ -irb(main):001:0> %w(north east south west).choice -=> "south" diff --git a/Task/Pick-random-element/Rust/pick-random-element.rust b/Task/Pick-random-element/Rust/pick-random-element.rust new file mode 100644 index 0000000000..1e958ef156 --- /dev/null +++ b/Task/Pick-random-element/Rust/pick-random-element.rust @@ -0,0 +1,6 @@ +extern crate rand; +use rand::Rng; +fn main() { + let array = [5,1,2,5,6,7,8,1,2,4,5]; + println!("{}", rand::thread_rng().choose(&array).unwrap()); +} diff --git a/Task/Pick-random-element/SuperCollider/pick-random-element.supercollider b/Task/Pick-random-element/SuperCollider/pick-random-element.supercollider new file mode 100644 index 0000000000..d1c4fe17fa --- /dev/null +++ b/Task/Pick-random-element/SuperCollider/pick-random-element.supercollider @@ -0,0 +1 @@ +[1, 2, 3].choose diff --git a/Task/Pick-random-element/Zkl/pick-random-element.zkl b/Task/Pick-random-element/Zkl/pick-random-element.zkl new file mode 100644 index 0000000000..252d2f591b --- /dev/null +++ b/Task/Pick-random-element/Zkl/pick-random-element.zkl @@ -0,0 +1,2 @@ +list:=T("hydrogen", "helium", "lithium", "beryllium", "boron"); +list[(0).random(list.len())] diff --git a/Task/Pig-the-dice-game-Player/Ruby/pig-the-dice-game-player.rb b/Task/Pig-the-dice-game-Player/Ruby/pig-the-dice-game-player.rb new file mode 100644 index 0000000000..982e1ff96c --- /dev/null +++ b/Task/Pig-the-dice-game-Player/Ruby/pig-the-dice-game-player.rb @@ -0,0 +1,41 @@ +def player1(sum,sm) +for i in 1..100 +puts "player1 rolled" +a=gets.chomp().to_i +if (a>1 && a<7) + sum+=a + if sum>=100 + puts "player1 wins" + break + end +else + +goto player2(sum,sm) +end +i+=1 +end +end + +def player2(sum,sm) +for j in 1..100 +puts "player2 rolled" +b=gets.chomp().to_i +if(b>1 && b<7) + sm+=b + if sm>=100 + puts "player2 wins" + break + end +else + +player1(sum,sm) +end +j+=1 +end +end +i=0 +j=0 +sum=0 +sm=0 +player1(sum,sm) +return diff --git a/Task/Pig-the-dice-game/Clojure/pig-the-dice-game.clj b/Task/Pig-the-dice-game/Clojure/pig-the-dice-game.clj new file mode 100644 index 0000000000..cbe47ccc98 --- /dev/null +++ b/Task/Pig-the-dice-game/Clojure/pig-the-dice-game.clj @@ -0,0 +1,41 @@ +(def max 100) + +(defn roll-dice [] + (let [roll (inc (rand-int 6))] + (println "Rolled:" roll) roll)) + +(defn switch [player] + (if (= player :player1) :player2 :player1)) + +(defn find-winner [game] + (cond + (>= (:player1 game) max) :player1 + (>= (:player2 game) max) :player2 + :else nil)) + +(defn bust [] + (println "Busted!") 0) + +(defn hold [points] + (println "Sticking with" points) points) + +(defn play-round [game player temp-points] + (println (format "%s: (%s, %s). Want to Roll? (y/n) " (name player) (player game) temp-points)) + (let [input (clojure.string/upper-case (read-line))] + (if (.equals input "Y") + (let [roll (roll-dice)] + (if (= 1 roll) + (bust) + (play-round game player (+ roll temp-points)))) + (hold temp-points)))) + +(defn play-game [game player] + (let [winner (find-winner game)] + (if (nil? winner) + (let [points (play-round game player 0)] + (recur (assoc game player (+ points (player game))) (switch player))) + (println (name winner) "wins!")))) + +(defn -main [& args] + (println "Pig the Dice Game.") + (play-game {:player1 0, :player2 0} :player1)) diff --git a/Task/Pig-the-dice-game/Go/pig-the-dice-game.go b/Task/Pig-the-dice-game/Go/pig-the-dice-game.go index 69472d1dac..c898a18117 100644 --- a/Task/Pig-the-dice-game/Go/pig-the-dice-game.go +++ b/Task/Pig-the-dice-game/Go/pig-the-dice-game.go @@ -27,7 +27,7 @@ func main() { playerScores[player] += currentScore fmt.Printf(" Player %v now has a score of %v.\n\n", player, playerScores[player]) - if playerScores[player] >= 10 { + if playerScores[player] >= 100 { fmt.Printf(" Player %v wins!!!\n", player) return } diff --git a/Task/Pig-the-dice-game/Kotlin/pig-the-dice-game.kotlin b/Task/Pig-the-dice-game/Kotlin/pig-the-dice-game.kotlin new file mode 100644 index 0000000000..14f615467e --- /dev/null +++ b/Task/Pig-the-dice-game/Kotlin/pig-the-dice-game.kotlin @@ -0,0 +1,45 @@ +// version 1.1.2 + +fun main(Args: Array) { + print("Player 1 - Enter your name : ") + val name1 = readLine()!!.trim().let { if (it == "") "PLAYER 1" else it.toUpperCase() } + print("Player 2 - Enter your name : ") + val name2 = readLine()!!.trim().let { if (it == "") "PLAYER 2" else it.toUpperCase() } + val names = listOf(name1, name2) + val r = java.util.Random() + val totals = intArrayOf(0, 0) + var player = 0 + while (true) { + println("\n${names[player]}") + println(" Your total score is currently ${totals[player]}") + var score = 0 + while (true) { + print(" Roll or Hold r/h : ") + val rh = readLine()!![0].toLowerCase() + if (rh == 'h') { + totals[player] += score + println(" Your total score is now ${totals[player]}") + if (totals[player] >= 100) { + println(" So, ${names[player]}, YOU'VE WON!") + return + } + player = if (player == 0) 1 else 0 + break + } + if (rh != 'r') { + println(" Must be 'r'or 'h', try again") + continue + } + val dice = 1 + r.nextInt(6) + println(" You have thrown a $dice") + if (dice == 1) { + println(" Sorry, your score for this round is now 0") + println(" Your total score remains at ${totals[player]}") + player = if (player == 0) 1 else 0 + break + } + score += dice + println(" Your score for the round is now $score") + } + } +} diff --git a/Task/Pig-the-dice-game/REXX/pig-the-dice-game.rexx b/Task/Pig-the-dice-game/REXX/pig-the-dice-game.rexx index 14f1ba4dac..f47a6394e0 100644 --- a/Task/Pig-the-dice-game/REXX/pig-the-dice-game.rexx +++ b/Task/Pig-the-dice-game/REXX/pig-the-dice-game.rexx @@ -1,97 +1,101 @@ -/*REXX program plays pig the dice game (any # of CBLFs and/or silicons).*/ -signal on syntax; signal on novalue /*handle REXX program errors. */ -sw=linesize()-1 /*get the width of the terminal. */ -parse arg hp cp win die _ . '(' names ")" /*obtain optional arguments.*/ - /*names with blanks should use _ */ +/*REXX program plays "pig the dice game" (any number of CBLFs and/or silicons or HALs).*/ +sw=linesize() - 1 /*get the width of the terminal screen,*/ +parse arg hp cp win die _ . '(' names ")" /*obtain optional arguments from the CL*/ + /*names with blanks should use an _ */ if _\=='' then call err 'too many arguments were specified: ' _ -@nhp = 'number of human players' ; hp =scrutinize( hp,@nhp , 0, 0, 0) -@ncp = 'number of computer players'; cp =scrutinize( cp,@ncp , 0, 0, 2) -@sn2w = 'score needed to win' ; win=scrutinize(win,@sn2w, 1,1e6,60) -@nsid = 'number of sides in die' ; die=scrutinize(die,@nsid, 2,999, 6) -if hp==0 & cp==0 then cp=2 /*if both counts are zero, 2 HALs*/ -if hp==1 & cp==0 then cp=1 /*if one human, then use 1 HAL.*/ -name.= /*nullify all names (to a blank).*/ -L=0 /*maximum length of a player name*/ - do i=1 for hp+cp /*get the player's names, maybe. */ - if i>hp then @='HAL_'i"_the_computer" /*use this for default.*/ - else @='player_'i /* " " " " */ +@nhp = 'number of human players' ; hp =scrutinize( hp, @nhp , 0, 0, 0) +@ncp = 'number of computer players'; cp =scrutinize( cp, @ncp , 0, 0, 2) +@sn2w = 'score needed to win' ; win=scrutinize(win, @sn2w, 1, 1e6, 60) +@nsid = 'number of sides in die' ; die=scrutinize(die, @nsid, 2, 999, 6) +if hp==0 & cp==0 then cp=2 /*if both counts are zero, two HALs. */ +if hp==1 & cp==0 then cp=1 /*if one human, then use one HAL. */ +name.= /*nullify all names (to a blank). */ +L=0 /*maximum length of a player name. */ + do i=1 for hp+cp /*get the player's names, ... maybe. */ + if i>hp then @= 'HAL_'i"_the_computer" /*use this for default name. */ + else @= 'player_'i /* " " " " " */ name.i = translate( word( strip( word(names,i)) @, 1),,'_') - L=max(L, length(name.i)) /*use L for nice name formatting.*/ - end /*i*/ /*underscores are changed─►blanks*/ + L=max(L, length(name.i)) /*use L for nice name formatting. */ + end /*i*/ /*underscores are changed ──► blanks. */ + +hpn=hp; if hpn==0 then hpn='no' /*use normal English for the display. */ +cpn=cp; if cpn==0 then cpn="no" /* " " " " " " */ + +say 'Pig (the dice game) is being played with:' /*the introduction to pig-the-dice-game*/ -hpn=hp; if hpn==0 then hpn='no' /*use normal English for display.*/ -cpn=cp; if cpn==0 then cpn="no" /* " " " " " */ -say 'Pig (the dice game) is being played with:' /*introduction to pig.*/ if cpn\==0 then say right(cpn,9) 'computer player's(cp) if hpn\==0 then say right(hpn,9) 'human player's(hp) -say 'and the' @sn2w "is: " win ' (or greater).' -!.=; dieNames='ace deuce trey square nickle boxcar' /*die face names.*/ - /*note: snake eyes is for 2 aces.*/ -!w=0; do i=1 for die; !.i=' ['word(dieNames,i)"]" - !w=max(!w, length(!.i)) /*!w ──► maximum length die name.*/ +!.= +say 'and the' @sn2w "is: " win ' (or greater).' +dieNames= 'ace deuce trey square nickle boxcar' /*some slangy vernacular die─face names*/ + /*note: snake eyes is for two aces. */ +!w=0; do i=1 for die /*assign the vernacular die─face names.*/ + !.i=' ['word(dieNames,i)"]" /*pick a word from die─face name lists.*/ + !w=max(!w, length(!.i)) /*!w ──► maximum length die─face name. */ end /*i*/ -s.=0 /*set all player's scores to zero*/ -!w=!w+length(die)+3 /*pad the die number and die name*/ -@=copies('─',9) /*an eyecatcher (for prompting). */ -@jra='just rolled a '; @ati='and the inning' /*nice literals to have.*/ -/*──────────────────────────────────────────────────let's play some pig.*/ - do game=1; in.=0 /*set each inning's score to zero*/ - say; say copies('█',sw) /*display a fence for da eyeballs*/ +s.=0 /*set all player's scores to zero. */ +!w=!w+length(die)+3 /*pad the die number and die names. */ +@=copies('─',9) /*eyecatcher (for the prompting text). */ +@jra= 'just rolled a ' /*a nice literal to have laying 'round.*/ +@ati= 'and the inning' /*" " " " " " " */ - do k=1 for hp+cp /*display the scores (as a recap)*/ - say 'The score for ' left(name.k,L) " is " right(s.k,length(win))'.' - end /*k*/ + /*════════════════════════════════════════════════════════════let's play some pig.*/ + do game=1; in.=0 /*set each inning's score to zero. */ + call score /*display the current score. */ - say copies('█',sw) /*display a fence for da eyeballs*/ - - do j=1 for hp+cp /*let each player roll their dice*/ - say; say copies('─',sw); /*display a fence for da eyeballs*/ + do j=1 for hp+cp /*let each player roll their dice. */ + say; say copies('─', sw) /*display a fence for da ole eyeballs. */ it=name.j - say it', your total score (so far) in this pig game is: ' s.j"." + say it', your total score (so far) in this pig game is: ' s.j"." - do until stopped /*keep prompting/rolling 'til not*/ - r=random(1,die) /*get a random die face (number).*/ - !=left(space(r !.r','), !w) /*for color, use a die-face name.*/ - in.j=in.j+r /*add die-face number to inning. */ - if r==1 then do; say it @jra ! || @ati "is a bust."; leave; end + do until stopped /*keep prompting/rolling 'til stopped. */ + r=random(1, die) /*get a random die face (number). */ + !=left(space(r !.r','), !w) /*for color, use a die─face name. */ + in.j=in.j + r /*add die─face number to the inning. */ + + if r==1 then do; say it @jra ! || @ati "is a bust."; leave; end say it @jra ! || @ati "total is: " in.j - stopped=what2do(j) /*determine|ask to stop rolling.*/ - if j>hp & stopped then say ' and' name.j "elected to stop rolling." + + stopped=what2do(j) /*determine or ask to stop rolling. */ + if j>hp & stopped then say ' and' name.j "elected to stop rolling." end /*until stopped*/ - if r\==1 then s.j=s.j+in.j /*if not a bust, then add inning.*/ - if s.j>=win then leave game /*we have a winner, so game ends.*/ - end /*j*/ /*that's the end of the players. */ + if r\==1 then s.j=s.j + in.j /*if not a bust, then add to the inning*/ + if s.j>=win then leave game /*we have a winner, so the game ends. */ + end /*j*/ /*that's the end of the players. */ end /*game*/ +call score say; say; say; say; say center(''name.j "won! ",sw,'═'); say; say; exit -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────S subroutine────────────────────────*/ -s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*plural?*/ -/*──────────────────────────────────SCRUTINIZE subroutine───────────────*/ -scrutinize: parse arg ?,what,min,max /*? is the number, or maybe not. */ -if ?=='' | ?==',' then return arg(5) -if \datatype(?,'N') then call err what "isn't numeric: " ?; ?=?/1 -if \datatype(?,'W') then call err what "isn't an integer: " ? -if ?==0 & min>0 then call err what "can't be zero." -if ?0 then call err what "can't be zero." -if ?>max & max\==0 then call err what "can't be greater than" max': ' ? -return ? -/*──────────────────────────────────what2do subroutine──────────────────*/ -what2do: parse arg who /*"who" is a human or a computer.*/ -if j>hp & s.j+in.j>=win then return 1 /*an easy choice for HAL.*/ -if j>hp & in.j>=win%4 then return 1 /*a simple stategy for HAL.*/ -if j>hp then return 0 /*HAL says, keep truckin'! */ -say @ name.who', what do you want to do? (a QUIT will stop the game),' -say @ 'press ENTER to roll again, or anything else to STOP rolling.' -pull action; action=space(action) /*remove any superfluous blanks. */ -if \abbrev('QUIT',action,1) then return action\=='' -say; say; say; say center(' quitting. ',sw,'─'); say; say; say; exit -/*───────────────────────────────error handling subroutines and others.─*/ -err: say; say; say center(' error! ',max(40,linesize()%2),"*"); say - do j=1 for arg(); say arg(j); say; end; say; exit 13 - -novalue: syntax: call err 'REXX program' condition('C') "error",, - condition('D'),'REXX source statement (line' sigl"):",, - sourceline(sigl) +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +score: say; say copies('█', sw) /*display a fence for da ole eyeballs. */ + do k=1 for hp+cp /*display the scores (as a recap). */ + say 'The score for ' left(name.k, L) " is " right(s.k, length(win) )'.' + end /*k*/ + say copies('█', sw); return /*display a fence for da ole eyeballs. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +scrutinize: parse arg ?,what,min,max /*? is the number, ... or maybe not. */ + if ?=='' | ?==',' then return arg(5) + if \datatype(?, 'N') then call err what "isn't numeric: " ?; ?=?/1 + if \datatype(?, 'W') then call err what "isn't an integer: " ? + if ?==0 & min>0 then call err what "can't be zero." + if ?0 then call err what "can't be zero." + if ?>max & max\==0 then call err what "can't be greater than" max': ' ? + return ? +/*──────────────────────────────────────────────────────────────────────────────────────*/ +what2do: parse arg who /*"who" is a human or a computer.*/ + if j>hp & s.j+in.j>=win then return 1 /*an easy choice for HAL. */ + if j>hp & in.j>=win%4 then return 1 /*a simple strategy for HAL. */ + if j>hp then return 0 /*HAL says, keep truckin'! */ + say @ name.who', what do you want to do? (a QUIT will stop the game),' + say @ 'press ENTER to roll again, or anything else to STOP rolling.' + pull action; action=space(action) /*remove any superfluous blanks. */ + if \abbrev('QUIT', action, 1) then return action\=='' + say; say; say center(' quitting. ',sw,'─'); say; say; exit +/*──────────────────────────────────────────────────────────────────────────────────────*/ +err: say; say; say center(' error! ', max(40, linesize() % 2), "*"); say + do j=1 for arg(); say arg(j); say; end; say; exit 13 diff --git a/Task/Pig-the-dice-game/Zkl/pig-the-dice-game.zkl b/Task/Pig-the-dice-game/Zkl/pig-the-dice-game.zkl new file mode 100644 index 0000000000..73be4c2ee7 --- /dev/null +++ b/Task/Pig-the-dice-game/Zkl/pig-the-dice-game.zkl @@ -0,0 +1,24 @@ +const WIN=100, PLAYERS=2; +players,safeScores:=Walker.cycle([0..PLAYERS-1]), PLAYERS.pump(List(),0); +rollDie:=(1).random.fp(7); +yes,player,score,S:=T("","y"),players.next(),0,0; +tally:='wrap(player,score){ w:=safeScores[player]+=score; (w>=WIN) }; + +while(True){ + print("Player %d: (%d, %d). Rolling? (y/n) ".fmt(player+1,S,score)); + if(yes.holds(ask().strip().toLower())){ + rolled:=rollDie(); println(" Rolled a %d".fmt(rolled)); + if(rolled==1){ + println(" Bust! You lose %d but keep %d\n".fmt(score,S)); + }else{ + score+=rolled; + if(score + S>=WIN){ tally(player,score); break; } + continue; + } + }else{ + if(tally(player,score)) break; + println(" Sticking with %d\n".fmt(safeScores[player])); + } + player,score,S=players.next(),0,safeScores[player]; +} +println("\n\nPlayer %d wins with a score of %d".fmt(player+1, safeScores[player])); diff --git a/Task/Pinstripe-Display/FreeBASIC/pinstripe-display.freebasic b/Task/Pinstripe-Display/FreeBASIC/pinstripe-display.freebasic new file mode 100644 index 0000000000..f48b11b24e --- /dev/null +++ b/Task/Pinstripe-Display/FreeBASIC/pinstripe-display.freebasic @@ -0,0 +1,27 @@ +' version 14-03-2017 +' compile with: fbc -s console +' or compile with: fbc -s gui + +Dim As UInteger ps, col, h, w, x, y1, y2 +ScreenInfo w, h + +' create display size window, 8bit color (palette), no frame +ScreenRes w, h, 8,, 8 +' vga palette black = 0 and white = 15 + +h = h \ 4 : y2 = h -1 + +For ps = 1 To 4 + col = 0 + For x = 0 To (w - ps -1) Step ps + Line (x, y1) - (x + ps -1, y2), col, bf + col = 15 - col ' col alternate between 0 (black) and 15 (white) + Next + y1 += h : y2 += h +Next + +' empty keyboard buffer +While InKey <> "" : Wend +'Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Pinstripe-Display/Gambas/pinstripe-display.gambas b/Task/Pinstripe-Display/Gambas/pinstripe-display.gambas new file mode 100644 index 0000000000..a1fc8f8a0a --- /dev/null +++ b/Task/Pinstripe-Display/Gambas/pinstripe-display.gambas @@ -0,0 +1,28 @@ +'WARNING this takes a time to display +'Use the 'gb.qt4' component + +Public Sub Form_Open() +Dim iColour As Integer[] = [Color.Black, Color.white] +Dim hPanel As Panel +Dim siCount, siCounter, siSet As Short + +With Me + .Arrangement = Arrange.Row + .Border = False + .Height = Desktop.Height + .Width = Desktop.Width + .Fullscreen = True +End With + +For siCounter = 1 To 4 + For siCount = 1 To Desktop.Width Step siCounter + hpanel = New Panel(Me) + hpanel.Width = siCounter + hpanel.Height = Desktop.Height / 4 + HPanel.Background = iColour[siSet] + Inc siSet + If siSet > 1 Then siSet = 0 + Next +Next + +End diff --git a/Task/Pinstripe-Display/Kotlin/pinstripe-display.kotlin b/Task/Pinstripe-Display/Kotlin/pinstripe-display.kotlin new file mode 100644 index 0000000000..160f670fe4 --- /dev/null +++ b/Task/Pinstripe-Display/Kotlin/pinstripe-display.kotlin @@ -0,0 +1,41 @@ +// version 1.1.0 + +import java.awt.* +import javax.swing.* + +class ColourPinstripeDisplay(): JPanel() { + private companion object { + val palette = arrayOf(Color.white, Color.black) + } + + private val bands = 4 + + init { + preferredSize = Dimension(900, 600) + } + + protected override fun paintComponent(g: Graphics) { + super.paintComponent(g) + for (b in 1..bands) { + var colIndex = 0 + val h = height / bands + for (x in 0 until width step b) { + g.color = palette[colIndex % palette.size] + g.fillRect(x, (b - 1) * h, b, h) + colIndex++ + } + } + } +} + +fun main(args: Array) { + SwingUtilities.invokeLater { + val f = JFrame() + f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE + f.title = "PinstripeDisplay" + f.add(ColourPinstripeDisplay(), BorderLayout.CENTER) + f.pack() + f.setLocationRelativeTo(null) + f.setVisible(true) + } +} diff --git a/Task/Pinstripe-Display/Perl-6/pinstripe-display.pl6 b/Task/Pinstripe-Display/Perl-6/pinstripe-display.pl6 index 673d394ffe..9b38d319d2 100644 --- a/Task/Pinstripe-Display/Perl-6/pinstripe-display.pl6 +++ b/Task/Pinstripe-Display/Perl-6/pinstripe-display.pl6 @@ -3,20 +3,20 @@ my $VERT = 720; my @colors = 0, 1; -my $PPM = open "pinstripes.pgm", :w, :bin or die "Can't create pinstripes.ppm: $!"; - -$PPM.print: qq:to/EOH/; +spurt "pinstripes.pgm", qq:to/EOH/; P5 # pinstripes.pgm $HOR $VERT 1 EOH +my $PGM = open "pinstripes.pgm", :a, :bin or die "Can't append to pinstripes.pgm: $!"; + my $vzones = $VERT div 4; for 1..4 -> $w { my $hzones = ceiling $HOR / $w / +@colors; my $line = Buf.new: (flat((@colors Xxx $w) xx $hzones).Array).splice(0,$HOR); - $PPM.write: $line for ^$vzones; + $PGM.write: $line for ^$vzones; } -$PPM.close; +$PGM.close; diff --git a/Task/Playing-cards/ATS/playing-cards.ats b/Task/Playing-cards/ATS/playing-cards.ats new file mode 100644 index 0000000000..2c835fae6f --- /dev/null +++ b/Task/Playing-cards/ATS/playing-cards.ats @@ -0,0 +1,440 @@ +(* ****** ****** *) +// +#include +"share/atspre_staload.hats" +#include +"share/HATS/atspre_staload_libats_ML.hats" +// +(* ****** ****** *) +// +abst@ype +pip_type = int +abst@ype +suit_type = int +// +abst@ype +card_type = int +// +(* ****** ****** *) + +typedef pip = pip_type +typedef suit = suit_type + +(* ****** ****** *) + +typedef card = card_type + +(* ****** ****** *) +// +extern +fun +pip_make: natLt(13) -> pip +extern +fun +pip_get_name: pip -> string +extern +fun +pip_get_value: pip -> intBtwe(1, 13) +// +extern +fun +suit_make: natLt(4) -> suit +extern +fun +suit_get_name: suit -> string +extern +fun +suit_get_value: suit -> intBtwe(1, 4) +// +overload .name with pip_get_name +overload .name with suit_get_name +overload .value with pip_get_value +overload .value with suit_get_value +// +(* ****** ****** *) +// +(* + | Two | Three | Four | Five + | Six | Seven | Eight | Nine + | Ten | Jack | Queen | King | Ace +*) +// +(* + | Spade | Heart | Diamond | Club +*) +// +(* ****** ****** *) + +local + +assume +pip_type = natLt(13) + +in (* in-of-local *) + +implement +pip_make(x) = x +implement +pip_get_value(x) = x + 1 + +end // end of [local] + +(* ****** ****** *) + +local + +assume +suit_type = natLt(4) + +in (* in-of-local *) + +implement +suit_make(x) = x +implement +suit_get_value(x) = x + 1 + +end // end of [local] + +(* ****** ****** *) + +implement +pip_get_name + (x) = +( +case+ +x.value() +of // case+ +| 1 => "Ace" +| 2 => "Two" +| 3 => "Three" +| 4 => "Four" +| 5 => "Five" +| 6 => "Six" +| 7 => "Seven" +| 8 => "Eight" +| 9 => "Nine" +| 10 => "Ten" +| 11 => "Jack" +| 12 => "Queen" +| 13 => "King" +) + +(* ****** ****** *) +// +implement +suit_get_name + (x) = +( +case+ +x.value() +of // case+ +| 1 => "S" | 2 => "H" | 3 => "D" | 4 => "C" +) (* end of [suit_get_name] *) +// +(* ****** ****** *) +// +extern +fun +card_get_pip: card -> pip +extern +fun +card_get_suit: card -> suit +// +extern +fun +card_make: natLt(52) -> card +extern +fun +card_make_suit_pip: (suit, pip) -> card +// +(* ****** ****** *) + +extern +fun +fprint_pip : fprint_type(pip) +extern +fun +fprint_suit : fprint_type(suit) +extern +fun +fprint_card : fprint_type(card) + +(* ****** ****** *) + +overload .pip with card_get_pip +overload .suit with card_get_suit + +(* ****** ****** *) + +implement +fprint_val = fprint_card + +(* ****** ****** *) + +overload fprint with fprint_pip +overload fprint with fprint_suit +overload fprint with fprint_card + +(* ****** ****** *) + +local + +assume +card_type = natLt(52) + +in (* in-of-local *) +// +implement +card_get_pip + (x) = pip_make(nmod(x, 13)) +implement +card_get_suit + (x) = suit_make(ndiv(x, 13)) +// +implement +card_make(xy) = xy +// +implement +card_make_suit_pip(x, y) = + (x.value()-1) * 13 + (y.value()-1) +// +end // end of [local] + +(* ****** ****** *) +// +implement +fprint_pip(out, x) = + fprint!(out, x.name()) +implement +fprint_suit(out, x) = + fprint!(out, x.name()) +// +implement +fprint_card(out, c) = + fprint!(out, c.suit(), "(", c.pip(), ")") +// +(* ****** ****** *) +// +absvtype +deck_vtype(n:int) = ptr +// +vtypedef deck(n:int) = deck_vtype(n) +// +(* ****** ****** *) +// +extern +fun +deck_get_size + {n:nat}(!deck(n)): int(n) +// +extern +fun +deck_is_empty + {n:nat}(!deck(n)): bool(n==0) +// +overload iseqz with deck_is_empty +// +(* ****** ****** *) +// +extern +fun +deck_free{n:int}(deck(n)): void +// +overload .free with deck_free +// +(* ****** ****** *) +// +extern +fun +deck_make_full((*void*)): deck(52) +// +(* ****** ****** *) +// +extern +fun +fprint_deck + {n:nat}(FILEref, !deck(n)): void +// +overload fprint with fprint_deck +// +(* ****** ****** *) +// +extern +fun +deck_shuffle + {n:nat}(!deck(n) >> _): void +// +overload .shuffle with deck_shuffle +// +(* ****** ****** *) +// +extern +fun +deck_takeout_top + {n:pos}(!deck(n) >> deck(n-1)): card +// +(* ****** ****** *) + +local +// +datavtype +deck(int) = +| {n:nat} + Deck(n) of + ( + int(n) + , list_vt(card, n) + ) // end of [Deck] +// +assume +deck_vtype(n:int) = deck(n) +// +in (* in-of-local *) + +implement +deck_get_size + (deck) = +( +let val+Deck(n, _) = deck in n end +) + +implement +deck_is_empty + (deck) = +( +let val+Deck(n, _) = deck in n = 0 end +) + +(* ****** ****** *) +// +implement +deck_free(deck) = +( +let val+~Deck(n, xs) = deck in free(xs) end +) (* end of [deck_free] *) +// +(* ****** ****** *) + +implement +deck_make_full + ((*void*)) = let +// +val xys = +list_make_intrange(0, 52) +// +val cards = +list_vt_mapfree_fun(xys, lam xy => card_make(xy)) +// +in + Deck(52, cards) +end // end of [deck_make_full] + +(* ****** ****** *) + +implement +fprint_deck + (out, deck) = let +// +val+Deck(n, xs) = deck +// +in +// +fprint_list_vt(out, xs) +// +end // end of [fprint_deck] + +(* ****** ****** *) + +implement +deck_shuffle + (deck) = + fold@(deck) where +{ +// +val+@Deck(n, xs) = deck +// +implement +list_vt_permute$randint<> + (n) = randint(n) +// +val ((*void*)) = + (xs := list_vt_permute(xs)) +// +} (* end of [deck_shuffle] *) + +(* ****** ****** *) + +implement +deck_takeout_top + (deck) = let +// +val+@Deck(n, xs) = deck +// +val+ +~list_vt_cons(x0, xs_tl) = xs +// +val ((*void*)) = n := n - 1 +val ((*void*)) = (xs := xs_tl) +// +in + fold@(deck); x0(*top*) +end // end of [deck_takeout_top] + +end // end of [local] + +(* ****** ****** *) + +implement +main0((*void*)) = +{ +// +val () = +println! +( +"Hello from [Playing_cards]!" +) (* println! *) +// +val out = stdout_ref +// +val theDeck = + deck_make_full((*void*)) +// +val ((*void*)) = + fprintln!(out, "theDeck = ", theDeck) +// +val ((*void*)) = + theDeck.shuffle((*void*)) +// +val ((*void*)) = + fprintln!(out, "theDeck = ", theDeck) +// +val ((*void*)) = + loop_deal(theDeck) where +{ +// +fun +loop_deal{n:nat} +( + deck: !deck(n) >> deck(0) +) : void = +( + if ( + iseqz(deck) + ) then ((*void*)) + else + let + val card = + deck_takeout_top(deck) + in + fprintln!(out, card); loop_deal(deck) + end // end of [let] + // end of [else] +) +// +} (* end of [val] *) +// +val ((*freed*)) = theDeck.free() +// +} (* end of [main0] *) + +(* ****** ****** *) diff --git a/Task/Playing-cards/AutoHotkey/playing-cards-1.ahk b/Task/Playing-cards/AutoHotkey/playing-cards-1.ahk deleted file mode 100644 index b6a33d1ddd..0000000000 --- a/Task/Playing-cards/AutoHotkey/playing-cards-1.ahk +++ /dev/null @@ -1,30 +0,0 @@ -Loop, 52 -{ - Random, card%A_Index%, 1, 52 - While card%A_Index% - Random, card%A_Index%, 1, 52 - card%A_Index% := Mod(card%A_Index%, 12) . " of " . ((card%A_Index% <= 12) - ? "diamonds" : ((card%A_Index%) <= 24) - ? "hearts" : ((card%A_Index% <= 36) - ? "clubs" - : "spades")) - allcards .= card%A_Index% . "`n" -} -currentcard = 1 -Gui, Add, Text, vcard w500 -Gui, Add, Button, w500 gNew, New Deck (Shuffle) -Gui, Add, Button, w500 gDeal, Deal Next Card -Gui, Add, Button, w500 gReveal, Reveal Entire Deck -Gui, Show,, Playing Cards -Return -New: -Reload -GuiClose: -ExitApp -Deal: -GuiControl,, card, % card%currentcard% -currentcard++ -Return -Reveal: -GuiControl,, card, % allcards -Return diff --git a/Task/Playing-cards/AutoHotkey/playing-cards-2.ahk b/Task/Playing-cards/AutoHotkey/playing-cards-2.ahk deleted file mode 100644 index 8e0f9533c4..0000000000 --- a/Task/Playing-cards/AutoHotkey/playing-cards-2.ahk +++ /dev/null @@ -1,44 +0,0 @@ -Deck:=new Deck -Deck.Shuffle() -msgbox % Deck.Show() -loop, 2 - msgbox % Deck.Deal().Show() -msgbox % Deck.Show() -Return ;------------------------------------------------------------------- - -class Card -{ - __New(Pip, Suit) { - this.Pip:=Pip, this.Suit:=Suit - } - Show() { - Return this.Pip . this.Suit - } -} - -class Deck -{ - Suits:={1:"♣",2:"♦",3:"♠",4:"♥"} - Pips:={13:"A",1:"2",2:"3",3:"4",4:"5",5:"6",6:"7",7:"8",8:"9",9:"T",10:"J",11:"Q",12:"K"} - - __New() { - this.Deck:=[] - For i, Pip in this.Pips - For j, Suit in this.Suits - this.Deck.Insert(new Card(Pip,Suit)) - } - Shuffle() { ; Knuth Shuffle from http://rosettacode.org/wiki/Knuth_Shuffle#AutoHotkey - Loop % this.Deck.MaxIndex()-1 { - Random, i, A_Index, this.Deck.MaxIndex() ; swap item 1,2... with a random item to the right of it - temp := this.Deck[i], this.Deck[i] := this.Deck[A_Index], this.Deck[A_Index] := temp - } - } - Deal() { - Return this.Deck.Remove() ; to deal from bottom, use Remove(1) - } - Show() { - For i, Card in this.Deck - s .= Card.Show() " " - Return s - } -} diff --git a/Task/Playing-cards/Kotlin/playing-cards.kotlin b/Task/Playing-cards/Kotlin/playing-cards.kotlin new file mode 100644 index 0000000000..9b8c358c3d --- /dev/null +++ b/Task/Playing-cards/Kotlin/playing-cards.kotlin @@ -0,0 +1,51 @@ +// version 1.1.2 + +import java.util.Random + +const val FACES = "23456789tjqka" +const val SUITS = "shdc" + +val r = Random() + +fun createDeck(): List { + val cards = mutableListOf() + for (suit in SUITS) { + for (face in FACES) cards.add("$face$suit") + } + return cards +} + +fun shuffleDeck(deck: List): List { + val shuffled = mutableListOf() + do { + val card = deck[r.nextInt(52)] + if (card !in shuffled) shuffled.add(card) + } while (shuffled.size < 52) + return shuffled +} + +fun dealTopDeck(deck: List, n: Int) = deck.take(n) + +fun dealBottomDeck(deck: List, n: Int) = deck.takeLast(n).reversed() + +fun printDeck(deck: List) { + for (i in 0 until deck.size) { + print("${deck[i]} ") + if ((i + 1) % 13 == 0 || i == deck.size - 1) println() + } +} + +fun main(args: Array) { + var deck = createDeck() + println("After creation, deck consists of:") + printDeck(deck) + deck = shuffleDeck(deck) + println("\nAfter shuffling, deck consists of:") + printDeck(deck) + val dealtTop = dealTopDeck(deck, 10) + println("\nThe 10 cards dealt from the top of the deck are:") + printDeck(dealtTop) + val dealtBottom = dealBottomDeck(deck, 10) + println("\nThe 10 cards dealt from the bottom of the deck are:") + printDeck(dealtBottom) +} diff --git a/Task/Playing-cards/OCaml/playing-cards.ocaml b/Task/Playing-cards/OCaml/playing-cards.ocaml index 31a7ce7e1e..0809b9fd78 100644 --- a/Task/Playing-cards/OCaml/playing-cards.ocaml +++ b/Task/Playing-cards/OCaml/playing-cards.ocaml @@ -2,19 +2,13 @@ type pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace let pips = [Two; Three; Four; Five; Six; Seven; Eight; Nine; Ten; Jack; Queen; King; Ace] - type suit = Diamonds | Spades | Hearts | Clubs let suits = [Diamonds; Spades; Hearts; Clubs] - type card = pip * suit - let full_deck = Array.of_list (List.concat (List.map (fun pip -> List.map (fun suit -> (pip, suit)) suits) pips)) - -(* Fisher-Yates shuffle *) let shuffle deck = for i = Array.length deck - 1 downto 1 do let j = Random.int (i+1) in - (* swap deck.(i) and deck.(j) *) let temp = deck.(i) in deck.(i) <- deck.(j); deck.(j) <- temp diff --git a/Task/Playing-cards/Phix/playing-cards.phix b/Task/Playing-cards/Phix/playing-cards.phix new file mode 100644 index 0000000000..6cc2053fb2 --- /dev/null +++ b/Task/Playing-cards/Phix/playing-cards.phix @@ -0,0 +1,74 @@ +-- +-- demo\rosetta\Playing_cards.exw +-- +function deal(sequence deck, integer nhands, integer ncards) +sequence hands = repeat({},nhands) + for n=1 to ncards do + for h=1 to nhands do + hands[h] &= deck[1] + deck = deck[2..$] + end for + end for + return {deck,hands} +end function + +--console: +procedure show_cards(sequence s) + for i=1 to length(s) do + integer c = s[i]-1 + string sep = iff(mod(i,13)=0 or i=length(s)?"\n":" ") + puts(1,"23456789TJQKA"[mod(c,13)+1]&"SHDC"[floor(c/13)+1]&sep) + end for +end procedure + +sequence deck, hands + +procedure console_show() + for i=1 to length(hands) do + printf(1,"hand%d:\n",{i}) + show_cards(sort(hands[i])) + end for + printf(1,"remaining cards(%d):\n",{length(deck)}) + show_cards(deck) +end procedure + +--GUI: +function cards_to_utf8(sequence s) +sequence utf32 = {} + for i=1 to length(s) do + integer c = s[i] + integer pip = mod(c,13) + utf32 &= 0x1F0A1 + pip+(pip>10) + floor((c-1)/13)*#10 + end for + return utf32_to_utf8(utf32) +end function + +include pGUI.e + +constant FONT = sprintf("FONT=\"Arial, %d\"",{92}) + +procedure gui_show() + IupOpen() + IupSetGlobal("UTF8MODE","YES") + + Ihandles lh = {} + for i=1 to length(hands) do + Ihandle l = IupLabel(sprintf("hand%d:",{i})) + Ihandle h = IupLabel(cards_to_utf8(sort(hands[i])),FONT) + lh &= l&h + end for + lh &= IupLabel("remaining cards:") + lh &= IupLabel(cards_to_utf8(deck),FONT) + + Ihandle dlg = IupDialog(IupVbox(lh)) + IupShow(dlg) + IupMainLoop() + IupClose() +end procedure + +constant DECKSIZE=52 +deck = shuffle(tagset(DECKSIZE)) +show_cards(deck) +{deck,hands} = deal(deck,4,7) +console_show() +gui_show() diff --git a/Task/Playing-cards/Zkl/playing-cards-1.zkl b/Task/Playing-cards/Zkl/playing-cards-1.zkl new file mode 100644 index 0000000000..2e5df5e820 --- /dev/null +++ b/Task/Playing-cards/Zkl/playing-cards-1.zkl @@ -0,0 +1,25 @@ +const Diamonds=1, Spades=3, Clubs=0, Hearts=2, Ace=1; // informational +var suits=T(0x1F0D1,0x1F0C1,0x1F0B1,0x1F0A1); //unicode 🃑,🃁,🂱,🂡 + +class Card{ + fcn init(pip,suit){ // or 0..51 + reg p,s; + if(vm.numArgs==1){ s=pip/13; p=pip%13; } else { p=pip; s=suit } + var [const] _pip=p, _suit=s; + } + fcn toString{ + p:=_pip + (_pip>=11); + (suits[_suit]+p).toString(8); // int-->UTF-8 + } +} + +class Deck{ //--> 52 shuffled Cards + var [const] deck=L(); + fcn init{ + (0).pump(52,deck.clear().write,Card); + shuffle(); + } + fcn shuffle{ deck.shuffle() } + fcn deal(cards=5){ deck.pop(0,cards); } + fcn toString{ deck.pump(String,"toString"); } +} diff --git a/Task/Playing-cards/Zkl/playing-cards-2.zkl b/Task/Playing-cards/Zkl/playing-cards-2.zkl new file mode 100644 index 0000000000..35b0281ed9 --- /dev/null +++ b/Task/Playing-cards/Zkl/playing-cards-2.zkl @@ -0,0 +1,4 @@ +d:=Deck(); +d.println(d.deck.len()); +d.deal().println(); +d.println(); diff --git a/Task/Plot-coordinate-pairs/Gnuplot/plot-coordinate-pairs.gnuplot b/Task/Plot-coordinate-pairs/Gnuplot/plot-coordinate-pairs.gnuplot new file mode 100644 index 0000000000..e94c7836e1 --- /dev/null +++ b/Task/Plot-coordinate-pairs/Gnuplot/plot-coordinate-pairs.gnuplot @@ -0,0 +1,14 @@ +unset key # Only one data set, so the key is uninformative + +plot '-' # '-' can be replaced with a filename, to read data from that file. + 0 2.7 + 1 2.8 + 2 31.4 + 3 38.1 + 4 68.0 + 5 76.2 + 6 100.5 + 7 130.0 + 8 149.3 + 9 180.0 +e diff --git a/Task/Plot-coordinate-pairs/jq/plot-coordinate-pairs-1.jq b/Task/Plot-coordinate-pairs/Jq/plot-coordinate-pairs-1.jq similarity index 100% rename from Task/Plot-coordinate-pairs/jq/plot-coordinate-pairs-1.jq rename to Task/Plot-coordinate-pairs/Jq/plot-coordinate-pairs-1.jq diff --git a/Task/Plot-coordinate-pairs/jq/plot-coordinate-pairs-2.jq b/Task/Plot-coordinate-pairs/Jq/plot-coordinate-pairs-2.jq similarity index 100% rename from Task/Plot-coordinate-pairs/jq/plot-coordinate-pairs-2.jq rename to Task/Plot-coordinate-pairs/Jq/plot-coordinate-pairs-2.jq diff --git a/Task/Plot-coordinate-pairs/jq/plot-coordinate-pairs-3.jq b/Task/Plot-coordinate-pairs/Jq/plot-coordinate-pairs-3.jq similarity index 100% rename from Task/Plot-coordinate-pairs/jq/plot-coordinate-pairs-3.jq rename to Task/Plot-coordinate-pairs/Jq/plot-coordinate-pairs-3.jq diff --git a/Task/Plot-coordinate-pairs/Phix/plot-coordinate-pairs.phix b/Task/Plot-coordinate-pairs/Phix/plot-coordinate-pairs.phix new file mode 100644 index 0000000000..3b15e664e5 --- /dev/null +++ b/Task/Plot-coordinate-pairs/Phix/plot-coordinate-pairs.phix @@ -0,0 +1,75 @@ +-- +-- demo\rosetta\Plot_coordinate_pairs.exw +-- +include pGUI.e + +Ihandle dlg, canvas +cdCanvas cddbuffer, cdcanvas + +constant 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} + +function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) +integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") +atom cx,cy,nx,ny +atom {w,h} = {(width-60)/9,(height-60)/180} + cdCanvasActivate(cddbuffer) + cx = 30+x[1]*w + cy = 30+y[1]*h + for i=2 to length(x) do + cdCanvasSetForeground(cddbuffer, CD_BLACK) + nx = 30+(i-1)*w + ny = 30+(i-1)*20*h + {} = cdCanvasTextAlignment(cddbuffer, CD_NORTH) + cdCanvasText(cddbuffer, nx, 25, sprintf("%d",(i-1))) + {} = cdCanvasTextAlignment(cddbuffer, CD_EAST) + cdCanvasText(cddbuffer, 25, ny, sprintf("%3d",(i-1)*20)) + cdCanvasSetForeground(cddbuffer, CD_GRAY) + cdCanvasLine(cddbuffer,30,ny,width-30,ny) + cdCanvasLine(cddbuffer,nx,30,nx,height-30) + cdCanvasSetForeground(cddbuffer, CD_BLUE) + nx = 30+floor(x[i]*w) + ny = 30+floor(y[i]*h) + cdCanvasLine(cddbuffer,cx,cy,nx,ny) + cx = nx + cy = ny + end for + cdCanvasSetForeground(cddbuffer, CD_BLACK) + cdCanvasLine(cddbuffer,30,30,width-30,30) + cdCanvasLine(cddbuffer,30,30,30,height-30) + cdCanvasFlush(cddbuffer) + return IUP_DEFAULT +end function + +function map_cb(Ihandle ih) + cdcanvas = cdCreateCanvas(CD_IUP, ih) + cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) + cdCanvasSetBackground(cddbuffer, CD_WHITE) + return IUP_DEFAULT +end function + +function esc_close(Ihandle /*ih*/, atom c) + if c=K_ESC then return IUP_CLOSE end if + return IUP_CONTINUE +end function + +procedure main() + IupOpen() + + canvas = IupCanvas(NULL) + IupSetAttribute(canvas, "RASTERSIZE", "340x340") -- initial size + IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) + + dlg = IupDialog(canvas) + IupSetAttribute(dlg, "TITLE", "Plot coordinate pairs") + IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) + IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) + + IupMap(dlg) + IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation + IupShowXY(dlg,IUP_CENTER,IUP_CENTER) + IupMainLoop() + IupClose() +end procedure + +main() diff --git a/Task/Plot-coordinate-pairs/REXX/plot-coordinate-pairs-1.rexx b/Task/Plot-coordinate-pairs/REXX/plot-coordinate-pairs-1.rexx new file mode 100644 index 0000000000..baa0a811e4 --- /dev/null +++ b/Task/Plot-coordinate-pairs/REXX/plot-coordinate-pairs-1.rexx @@ -0,0 +1,9 @@ +/*REXX program plots X,Y coördinate pairs of numbers with plain (ASCII) characters.*/ +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 +$= + do j=1 for words(x) /*build a list suitable for $PLOT subr.*/ + $=$ word(x, j)','word(y, j) /*add this X,Y coördinate to the $ list*/ + end /*j*/ /*$≡ 0,2.7 1,2.8 2,31.4 3,38.1 ··· */ +call '$PLOT' $ /*invoke the REXX program: $PLOT */ +exit rc /*stick a fork in it, we're all done. */ diff --git a/Task/Plot-coordinate-pairs/REXX/plot-coordinate-pairs-2.rexx b/Task/Plot-coordinate-pairs/REXX/plot-coordinate-pairs-2.rexx new file mode 100644 index 0000000000..c4fe0c85e2 --- /dev/null +++ b/Task/Plot-coordinate-pairs/REXX/plot-coordinate-pairs-2.rexx @@ -0,0 +1,9 @@ +/*REXX program plots X,Y coördinate pairs of numbers with plain (ASCII) characters.*/ +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 +$= + do j=1 for words(x) /*build a list suitable for $PLOT subr.*/ + $=$ word(x, j)','word(y, j) /*add this X,Y coördinate to the $ list*/ + end /*j*/ /*$≡ 0,2.7 1,2.8 2,31.4 3,38.1 ··· */ +call '$PLOT' $ '(LABELDatapoints' /*invoke the REXX program: $PLOT */ +exit rc /*stick a fork in it, we're all done. */ diff --git a/Task/Plot-coordinate-pairs/REXX/plot-coordinate-pairs.rexx b/Task/Plot-coordinate-pairs/REXX/plot-coordinate-pairs.rexx deleted file mode 100644 index 7a0cc5acef..0000000000 --- a/Task/Plot-coordinate-pairs/REXX/plot-coordinate-pairs.rexx +++ /dev/null @@ -1,9 +0,0 @@ -/*REXX program plots coördinate pairs of numbers with plain characters. */ -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 -$= - do j=1 for words(x) /*build a list suitable for $PLOT*/ - $=$ word(x,j)','word(y,j) - end /*j*/ /*$≡ 0,2.7 1,2.8 2,31.4 ···*/ -call '$PLOT' $ /*invoke the REXX program: $PLOT.*/ -exit rc /*stick a fork in it, we're done.*/ diff --git a/Task/Plot-coordinate-pairs/Racket/plot-coordinate-pairs-2.rkt b/Task/Plot-coordinate-pairs/Racket/plot-coordinate-pairs-2.rkt index beafa1624a..cdedd05a4e 100644 --- a/Task/Plot-coordinate-pairs/Racket/plot-coordinate-pairs-2.rkt +++ b/Task/Plot-coordinate-pairs/Racket/plot-coordinate-pairs-2.rkt @@ -5,4 +5,4 @@ (define y (list 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0)) (plot-new-window? #t) -(plot (points (map vector x y))) +(plot (lines (map vector x y))) diff --git a/Task/Plot-coordinate-pairs/Scilab/plot-coordinate-pairs.scilab b/Task/Plot-coordinate-pairs/Scilab/plot-coordinate-pairs.scilab new file mode 100644 index 0000000000..e0835d2f04 --- /dev/null +++ b/Task/Plot-coordinate-pairs/Scilab/plot-coordinate-pairs.scilab @@ -0,0 +1,3 @@ +--> 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]; +--> plot2d(x,y) diff --git a/Task/Plot-coordinate-pairs/Stata/plot-coordinate-pairs.stata b/Task/Plot-coordinate-pairs/Stata/plot-coordinate-pairs.stata new file mode 100644 index 0000000000..ca29a6335c --- /dev/null +++ b/Task/Plot-coordinate-pairs/Stata/plot-coordinate-pairs.stata @@ -0,0 +1,16 @@ +clear +input x y +0 2.7 +1 2.8 +2 31.4 +3 38.1 +4 58.0 +5 76.2 +6 100.5 +7 130.0 +8 149.3 +9 180.0 +end + +lines y x +graph export image.png diff --git a/Task/Plot-coordinate-pairs/Zkl/plot-coordinate-pairs.zkl b/Task/Plot-coordinate-pairs/Zkl/plot-coordinate-pairs.zkl new file mode 100644 index 0000000000..0361fecb9f --- /dev/null +++ b/Task/Plot-coordinate-pairs/Zkl/plot-coordinate-pairs.zkl @@ -0,0 +1,23 @@ +#<<< +cmd:=0'| +#set term wxt # X11 +unset key # Only one data set, so the key is uninformative + +plot '-' # '-' can be replaced with a filename, to read data from that file. + 0 2.7 + 1 2.8 + 2 31.4 + 3 38.1 + 4 68.0 + 5 76.2 + 6 100.5 + 7 130.0 + 8 149.3 + 9 180.0 +e +|; +#<<< + +gnuplot:=System.popen("gnuplot","w"); +gnuplot.write(cmd); gnuplot.flush(); +ask("Hit return to finish"); gnuplot.close(); diff --git a/Task/Pointers-and-references/D/pointers-and-references-1.d b/Task/Pointers-and-references/D/pointers-and-references-1.d deleted file mode 100644 index dddc372490..0000000000 --- a/Task/Pointers-and-references/D/pointers-and-references-1.d +++ /dev/null @@ -1,2 +0,0 @@ -int var; -int* ptr = &var; diff --git a/Task/Pointers-and-references/D/pointers-and-references-2.d b/Task/Pointers-and-references/D/pointers-and-references-2.d deleted file mode 100644 index f6b639e38c..0000000000 --- a/Task/Pointers-and-references/D/pointers-and-references-2.d +++ /dev/null @@ -1,9 +0,0 @@ -struct S{} -class C{} - -void foo(S s){} // pass by value -void foo(C c){} // pass by reference -void foo(int i){} // pass by value -void foo(int[4] i){} // pass by value -void foo(int[] i){} // pass by reference -void foo(ref T t){} // pass by reference regardless of what type T really is diff --git a/Task/Pointers-and-references/Kotlin/pointers-and-references.kotlin b/Task/Pointers-and-references/Kotlin/pointers-and-references.kotlin new file mode 100644 index 0000000000..9ee07e39bb --- /dev/null +++ b/Task/Pointers-and-references/Kotlin/pointers-and-references.kotlin @@ -0,0 +1,39 @@ +// Kotlin Native v0.3 + +import kotlinx.cinterop.* + +fun main(args: Array) { + // allocate space for an 'int' on the native heap and wrap a pointer to it in an IntVar object + val intVar: IntVar = nativeHeap.alloc() + intVar.value = 3 // set its value + println(intVar.value) // print it + println(intVar.ptr) // corresponding CPointer object + println(intVar.rawPtr) // the actual address wrapped by the CPointer + + // change the value and print that + intVar.value = 333 + println() + println(intVar.value) + println(intVar.ptr) // same as before, of course + + // implicitly convert to an opaque pointer which is the supertype of all pointer types + val op: COpaquePointer = intVar.ptr + + // cast opaque pointer to a pointer to ByteVar + println() + var bytePtr: CPointer = op.reinterpret() + println(bytePtr.pointed.value) // value of first byte i.e. 333 - 256 = 77 on Linux + bytePtr = (bytePtr + 1)!! // increment pointer + println(bytePtr.pointed.value) // value of second byte i.e. 1 on Linux + println(bytePtr) // one byte more than before + bytePtr = (bytePtr + (-1))!! // decrement pointer + println(bytePtr) // back to original value + nativeHeap.free(intVar) // free native memory + + // allocate space for an array of 3 'int's on the native heap + println() + var intArray: CPointer = nativeHeap.allocArray(3) + for (i in 0..2) intArray[i] = i // set them + println(intArray[2]) // print the last element + nativeHeap.free(intArray) // free native memory +} diff --git a/Task/Pointers-and-references/Lua/pointers-and-references.lua b/Task/Pointers-and-references/Lua/pointers-and-references.lua new file mode 100644 index 0000000000..065d19ddb9 --- /dev/null +++ b/Task/Pointers-and-references/Lua/pointers-and-references.lua @@ -0,0 +1,4 @@ +local table1 = {1,2,3} +local table2 = table1 +table2[3] = 4 +print(unpack(table1)) diff --git a/Task/Pointers-and-references/OoRexx/pointers-and-references-1.rexx b/Task/Pointers-and-references/OoRexx/pointers-and-references-1.rexx new file mode 100644 index 0000000000..32faf17a85 --- /dev/null +++ b/Task/Pointers-and-references/OoRexx/pointers-and-references-1.rexx @@ -0,0 +1,11 @@ + ::class Foo + ::method init + expose x + x = 0 + ::attribute x + + ::routine somefunction + a = .Foo~new -- assigns a to point to a new Foo object + b = a -- b and a now point to the same object + a~x = 5 -- modifies the X variable inside the object pointer to by a + say b~x -- displays "5" because b points to the same object as a diff --git a/Task/Pointers-and-references/OoRexx/pointers-and-references-2.rexx b/Task/Pointers-and-references/OoRexx/pointers-and-references-2.rexx new file mode 100644 index 0000000000..dfa56f0013 --- /dev/null +++ b/Task/Pointers-and-references/OoRexx/pointers-and-references-2.rexx @@ -0,0 +1,20 @@ +a.='not set' +a.3=3 +Say 'Before Call sub: a.3='a.3 +Call sub a. +Say ' After Call sub: a.3='a.3 +Call sub2 a. +Say ' After Call sub2: a.3='a.3 +Exit + +sub: Procedure +Use Arg a. -- this established access to the caller's object +a.3=27 +Return + +sub2: Procedure +Parse Arg a. -- this gets the value of the caller's object +a.3=9 +Say 'in sub2: a.='a. +Say 'in sub2: a.3='a.3 -- this changes the local a. +Return diff --git a/Task/Pointers-and-references/PL-I/pointers-and-references.pli b/Task/Pointers-and-references/PL-I/pointers-and-references.pli new file mode 100644 index 0000000000..772c8b19ae --- /dev/null +++ b/Task/Pointers-and-references/PL-I/pointers-and-references.pli @@ -0,0 +1,22 @@ +dcl i fixed bin(31); +dcl p pointer; +dcl j fixed bin(31) based; +i=5; +p=addr(i); +p->j=p->j+1; /an other way to say i=i+1 */ +put skip edit(i)(F(5)); /* -> 6 */ + +/* second form */ +dcl i fixed bin(31); +dcl j fixed bin(31) based(p); +i=5; +p=addr(i); +j=j+1; /* an other way to say i=i+1 */ +put skip edit(i)(F(5)); /* -> 6 */ + +/* cascading pointers */ +dcl (p,q,s,t) pointer; +dcl (j,k) fixed bin(31) based; +dcl (i1,i2) fixed bin(31); +p=addr(i1); t=addr(i2), q=addr(p); s=addr(t); +q->p->j = s->t->k + 3; /* to say i1=i2+3 */ diff --git a/Task/Pointers-and-references/Phix/pointers-and-references-1.phix b/Task/Pointers-and-references/Phix/pointers-and-references-1.phix new file mode 100644 index 0000000000..e8c6783df1 --- /dev/null +++ b/Task/Pointers-and-references/Phix/pointers-and-references-1.phix @@ -0,0 +1,5 @@ +atom addr = allocate(8) -- (assumes 32 bit) +poke4(addr,{NULL,SOME_CONSTANT}) +c_proc(xSome_External_Routine,{addr,addr+4}) +?peek4s({addr,2}) -- prints {x,y} +free(addr) diff --git a/Task/Pointers-and-references/Phix/pointers-and-references-2.phix b/Task/Pointers-and-references/Phix/pointers-and-references-2.phix new file mode 100644 index 0000000000..2d2791361e --- /dev/null +++ b/Task/Pointers-and-references/Phix/pointers-and-references-2.phix @@ -0,0 +1,9 @@ +atom mypi +#ilASM{ + fldpi + [32] + lea edi,[mypi] + [64] + lea rdi,[mypi] + [] + call :%pStoreFlt } diff --git a/Task/Pointers-and-references/Phix/pointers-and-references-3.phix b/Task/Pointers-and-references/Phix/pointers-and-references-3.phix new file mode 100644 index 0000000000..9c58665958 --- /dev/null +++ b/Task/Pointers-and-references/Phix/pointers-and-references-3.phix @@ -0,0 +1,10 @@ +string mystring = "mystring" +#ilASM{ + [32] + mov esi,[mystring] + lea esi,[ebx+esi*4] -- byte[esi] is 'm' + [64] + mov rsi,[mystring] + lea rsi,[rbx+rsi*4] -- byte[rsi] is 'm' + [] + } diff --git a/Task/Pointers-and-references/Phix/pointers-and-references-4.phix b/Task/Pointers-and-references/Phix/pointers-and-references-4.phix new file mode 100644 index 0000000000..ac6a49a9a0 --- /dev/null +++ b/Task/Pointers-and-references/Phix/pointers-and-references-4.phix @@ -0,0 +1,2 @@ +sequence s + s = myfunc(s) diff --git a/Task/Pointers-and-references/Zkl/pointers-and-references-1.zkl b/Task/Pointers-and-references/Zkl/pointers-and-references-1.zkl new file mode 100644 index 0000000000..d8eab4ba87 --- /dev/null +++ b/Task/Pointers-and-references/Zkl/pointers-and-references-1.zkl @@ -0,0 +1 @@ +fcn f(r){r.inc()} r:= Ref(1); f(r); r.value; //-->2 diff --git a/Task/Pointers-and-references/Zkl/pointers-and-references-2.zkl b/Task/Pointers-and-references/Zkl/pointers-and-references-2.zkl new file mode 100644 index 0000000000..17cce8a63a --- /dev/null +++ b/Task/Pointers-and-references/Zkl/pointers-and-references-2.zkl @@ -0,0 +1 @@ +fcn f(lst){lst.append(5)} f(L()); //-->L(5) diff --git a/Task/Polymorphic-copy/Kotlin/polymorphic-copy.kotlin b/Task/Polymorphic-copy/Kotlin/polymorphic-copy.kotlin new file mode 100644 index 0000000000..464b45fa84 --- /dev/null +++ b/Task/Polymorphic-copy/Kotlin/polymorphic-copy.kotlin @@ -0,0 +1,21 @@ +// version 1.1.2 + +open class Animal(val name: String, var age: Int) { + open fun copy() = Animal(name, age) + + override fun toString() = "Name: $name, Age: $age" +} + +class Dog(name: String, age: Int, val breed: String) : Animal(name, age) { + override fun copy() = Dog(name, age, breed) + + override fun toString() = super.toString() + ", Breed: $breed" +} + +fun main(args: Array) { + val a: Animal = Dog("Rover", 3, "Terrier") + val b: Animal = a.copy() // calls Dog.copy() because runtime type of 'a' is Dog + println("Dog 'a' = $a") // implicitly calls Dog.toString() + println("Dog 'b' = $b") // ditto + println("Dog 'a' is ${if (a === b) "" else "not"} the same object as Dog 'b'") +} diff --git a/Task/Polymorphic-copy/OoRexx/polymorphic-copy.rexx b/Task/Polymorphic-copy/OoRexx/polymorphic-copy.rexx new file mode 100644 index 0000000000..12620bed0a --- /dev/null +++ b/Task/Polymorphic-copy/OoRexx/polymorphic-copy.rexx @@ -0,0 +1,12 @@ +s = .s~new +s2 = s~copy -- makes a copy of the first +if s == s2 then say "copy didn't work!" +if s2~name == "S" then say "polymorphic copy worked" + +::class t +::method name + return "T" + +::class s subclass t +::method name + return "S" diff --git a/Task/Polymorphic-copy/Phix/polymorphic-copy.phix b/Task/Polymorphic-copy/Phix/polymorphic-copy.phix new file mode 100644 index 0000000000..2c95a5c009 --- /dev/null +++ b/Task/Polymorphic-copy/Phix/polymorphic-copy.phix @@ -0,0 +1,27 @@ +enum NAME, METHOD + +procedure me_t() + puts(1,"I is a T\n") +end procedure +constant r_t = routine_id("me_t") + +procedure me_s() + puts(1,"I is an S\n") +end procedure +constant r_s = routine_id("me_s") + +type T(object o) + -- as o[METHOD] can be overidden, don't verify it! + return sequence(o) and length(o)=2 and string(o[NAME]) and integer(o[METHOD]) +end type + +type S(T t) + return t[METHOD] = r_s +end type + +S this = {"S",r_s} +T that = {"T",r_t} + +call_proc(that[METHOD],{}) +that = this +call_proc(that[METHOD],{}) diff --git a/Task/Polymorphism/Ceylon/polymorphism.ceylon b/Task/Polymorphism/Ceylon/polymorphism.ceylon new file mode 100644 index 0000000000..43cf929208 --- /dev/null +++ b/Task/Polymorphism/Ceylon/polymorphism.ceylon @@ -0,0 +1,52 @@ +import ceylon.language { + consolePrint = print +} + +shared void run() { + + class Point { + + shared variable Integer x; + shared variable Integer y; + + shared new(Integer x = 0, Integer y = 0) { + this.x = x; + this.y = y; + } + + shared new copy(Point p) { + this.x = p.x; + this.y = p.y; + } + + shared default void print() { + consolePrint("[Point ``x`` ``y``]"); + } + } + + class Circle extends Point { + + shared variable Integer r; + + shared new(Integer x = 0, Integer y = 0, Integer r = 0) extends Point(x, y) { + this.r = r; + } + + shared new copy(Circle c) extends Point.copy(c){ + this.r = c.r; + } + + shared actual void print() { + consolePrint("[Circle ``x`` ``y`` ``r``]"); + } + } + + value shapes = [ + Point(), Point(1), Point(1, 2), Point {y = 3;}, Point.copy(Point(4, 5)), + Circle(), Circle(1), Circle(2, 3), Circle(4, 5, 6), Circle {y = 7; r = 8;}, Circle.copy(Circle(9, 10, 11)) + ]; + + for(shape in shapes) { + shape.print(); + } +} diff --git a/Task/Polymorphism/Eiffel/polymorphism-4.e b/Task/Polymorphism/Eiffel/polymorphism-4.e deleted file mode 100644 index 52e7954a8e..0000000000 --- a/Task/Polymorphism/Eiffel/polymorphism-4.e +++ /dev/null @@ -1,6 +0,0 @@ -Point: x = 0 y = 0 -Circle: x = 0 y = 0 r = 0 -Point: x = 10 y = 15 -Circle: x = 20 y = 25 r = 5 -Circle: x = 30 y = 35 r = 10 -Circle: x = 20 y = 25 r = 35 diff --git a/Task/Polymorphism/Jq/polymorphism-1.jq b/Task/Polymorphism/Jq/polymorphism-1.jq new file mode 100644 index 0000000000..f1e6a3eec1 --- /dev/null +++ b/Task/Polymorphism/Jq/polymorphism-1.jq @@ -0,0 +1,14 @@ +def Point(x;y): {"type": "Point", "x": x, "y": y}; +def Point(x): Point(x;0); +def Point: Point(0); + +def Circle(x;y;r): {"type": "Circle", "x": x, "y": y, "r": r}; +def Circle(x;y): Circle(x;y;0); +def Circle(x): Circle(x;0); +def Circle: Circle(0); + +def print: + if .type == "Circle" then "\(.type)(\(.x); \(.y); \(.r))" + elif .type == "Point" then "\(.type)(\(.x); \(.y))" + else empty + end; diff --git a/Task/Polymorphism/Jq/polymorphism-2.jq b/Task/Polymorphism/Jq/polymorphism-2.jq new file mode 100644 index 0000000000..40b097338b --- /dev/null +++ b/Task/Polymorphism/Jq/polymorphism-2.jq @@ -0,0 +1,5 @@ +# keyname should be (or evaluate to) a string +def set(keyname; value): + if type == "object" and .type and has(keyname) then .[keyname] = value + else error("set: invalid type: \(.)") + end; diff --git a/Task/Polymorphism/Jq/polymorphism-3.jq b/Task/Polymorphism/Jq/polymorphism-3.jq new file mode 100644 index 0000000000..cc243d1893 --- /dev/null +++ b/Task/Polymorphism/Jq/polymorphism-3.jq @@ -0,0 +1 @@ +Circle(0;1;2) | .x = 1 | print diff --git a/Task/Polymorphism/Kotlin/polymorphism.kotlin b/Task/Polymorphism/Kotlin/polymorphism.kotlin new file mode 100644 index 0000000000..2ca96cf938 --- /dev/null +++ b/Task/Polymorphism/Kotlin/polymorphism.kotlin @@ -0,0 +1,56 @@ +// version 1.1.2 + +open class Point(var x: Int, var y: Int) { + constructor(): this(0, 0) + + constructor(x: Int) : this(x, 0) + + constructor(p: Point) : this(p.x, p.y) + + open protected fun finalize() = println("Finalizing $this...") + + override fun toString() = "Point at ($x, $y)" + + open fun print() = println(this) +} + +class Circle(x: Int, y: Int, var r: Int) : Point(x, y) { + constructor(): this(0, 0, 0) + + constructor(x: Int) : this(x, 0, 0) + + constructor(x: Int, r: Int) : this(x, 0, r) + + constructor(c: Circle) : this(c.x, c.y, c.r) + + // for simplicity not calling super.finalize() below though this would normally be done in practice + override protected fun finalize() = println("Finalizing $this...") + + override fun toString() = "Circle at center ($x, $y), radius $r" + + override fun print() = println(this) +} + +fun createObjects() { + val points = listOf(Point(), Point(1), Point(2, 3), Point(Point(3, 4))) + for (point in points) point.print() + val circles = listOf(Circle(), Circle(1), Circle(2, 3), Circle(4, 5, 6), Circle(Circle(7, 8, 9))) + for (circle in circles) circle.print() + println() +} + +fun main(args: Array) { + createObjects() + System.gc() // try and force garbage collection + Thread.sleep(2000) // allow time for finalizers to run + println() + val p = Point(5, 6) + p.print() + p.y = 7 // change y coordinate + p.print() + val c = Circle(5, 6, 7) + c.print() + c.r = 8 + c.print() // change radius + /* note that finalizers for p and c are not called */ +} diff --git a/Task/Polymorphism/OoRexx/polymorphism-1.rexx b/Task/Polymorphism/OoRexx/polymorphism-1.rexx new file mode 100644 index 0000000000..2fd1229e19 --- /dev/null +++ b/Task/Polymorphism/OoRexx/polymorphism-1.rexx @@ -0,0 +1,29 @@ +p = .point~new(3,2) +c = .circle~new(,2,6) + +p~print +c~print + +::class point +::method init + expose x y + use strict arg x = 0, y = 0 -- defaults to 0 for any non-specified coordinates + +::attribute x +::attribute y + +::method print + expose x y + say "A point at location ("||x","y")" + +::class circle subclass point +::method init + expose radius + use strict arg x = 0, y = 0, radius = 0 + self~init:super(x, y) -- call superclass constructor + +::attribute radius + +::method print + expose radius + say "A circle of radius" radius "centered at location ("||self~x","self~y")" diff --git a/Task/Polymorphism/OoRexx/polymorphism-2.rexx b/Task/Polymorphism/OoRexx/polymorphism-2.rexx new file mode 100644 index 0000000000..fb69b055ec --- /dev/null +++ b/Task/Polymorphism/OoRexx/polymorphism-2.rexx @@ -0,0 +1,30 @@ +p = .point~new(3,2) +c = .circle~new(,2,6) + +p~print +c~print + +::class point +::method init + expose x y + use strict arg x = 0, y = 0 -- defaults to 0 for any non-specified coordinates + +::attribute x +::attribute y + +::method print + expose x y + say "A point at location ("||x","y")" + +::class circle +::method init + expose x y radius + use strict arg x = 0, y = 0, radius = 0 + +::attribute radius +::attribute x +::attribute y + +::method print + expose radius x y + say "A circle of radius" radius "centered at location ("||x","y")" diff --git a/Task/Polymorphism/Phix/polymorphism.phix b/Task/Polymorphism/Phix/polymorphism.phix index a5523960a3..7624786dff 100644 --- a/Task/Polymorphism/Phix/polymorphism.phix +++ b/Task/Polymorphism/Phix/polymorphism.phix @@ -15,10 +15,12 @@ function new_circle(object x=0, atom y=0, atom r=0) r = y -- assume r got passed in y return {x,r} -- {point,r} end if - return {{x,y},r} + return {{x,y},r} -- {point,r} + -- (or {new_point(x,y),r} if you prefer) end function point p = new_point(4,5) -circle c = new_circle(p,6) -?p -?c +circle c1 = new_circle(p,6), + c2 = new_circle(4,5,6} +?c1 +?c2 diff --git a/Task/Polymorphism/Zkl/polymorphism.zkl b/Task/Polymorphism/Zkl/polymorphism.zkl new file mode 100644 index 0000000000..6df4fe1f8b --- /dev/null +++ b/Task/Polymorphism/Zkl/polymorphism.zkl @@ -0,0 +1,27 @@ +class Point{var x,y; + fcn init(xyOrPoint=0,_=0){ + if(Point.isInstanceOf(xyOrPoint)) set(xyOrPoint); + else x,y=vm.arglist.apply("toFloat")} + fcn set(p){x=p.x;y=p.y} + fcn toString{"(%d,%d)".fmt(x,y)} +} +class Circle{var center, radius; + fcn init(a=0.0,b=0.0,r=1.0){ + switch [arglist]{ + case(Circle){ center=Point(a.center); radius=a.radius } + case(Point) { center=Point(a); radius=b.toFloat(); } + else { center=Point(a,b); radius=r.toFloat(); } + } + } + fcn copy{self(self)} + fcn toString{"(%s,%d)".fmt(center.toString(),radius)} +} + // see if various constructors work +Point(); Point(1); Point(1,2), Point(Point()); +Circle(); Circle(1); Circle(1,2); Circle(1,2,3); +Circle(Point()); Circle(Point(),1); +Circle(Circle()); + +c:=Circle(1,2,3); +c.println(); c.center.println(); +c.copy().println(); diff --git a/Task/Polynomial-long-division/SPAD/polynomial-long-division.spad b/Task/Polynomial-long-division/SPAD/polynomial-long-division.spad new file mode 100644 index 0000000000..f7a819c30e --- /dev/null +++ b/Task/Polynomial-long-division/SPAD/polynomial-long-division.spad @@ -0,0 +1,6 @@ +(1) -> monicDivide(x^3-12*x^2-42,x-3,'x) + + 2 + (1) [quotient = x - 9x - 27,remainder = - 123] + + Type: Record(quotient: Polynomial(Integer),remainder: Polynomial(Integer)) diff --git a/Task/Polynomial-long-division/Sidef/polynomial-long-division-1.sidef b/Task/Polynomial-long-division/Sidef/polynomial-long-division-1.sidef index 9a4b655323..e9e935d862 100644 --- a/Task/Polynomial-long-division/Sidef/polynomial-long-division-1.sidef +++ b/Task/Polynomial-long-division/Sidef/polynomial-long-division-1.sidef @@ -1,20 +1,20 @@ func poly_long_div(rn, rd) { - +  var n = rn.map{_} var gd = rd.len - +  if (n.len >= gd) { return(gather { while (n.len >= gd) { var piv = n[0]/rd[0] take(piv) - 0.to(n.len.min(gd)-1).each { |i| + { |i| n[i] -= (rd[i] * piv) - } + } << ^(n.len `min` gd) n.shift } }, n) } - +  return([0], rn) } diff --git a/Task/Polynomial-long-division/Zkl/polynomial-long-division-1.zkl b/Task/Polynomial-long-division/Zkl/polynomial-long-division-1.zkl new file mode 100644 index 0000000000..4e74bd8349 --- /dev/null +++ b/Task/Polynomial-long-division/Zkl/polynomial-long-division-1.zkl @@ -0,0 +1,22 @@ +fcn polyLongDivision(a,b){ // (a0 + a1x + a2x^2 + a3x^3 ...) + _assert_(degree(b)>=0,"degree(%s) < 0".fmt(b)); + q:=List.createLong(a.len(),0.0); + while((ad:=degree(a)) >= (bd:=degree(b))){ + z,d,m := ad-bd, List.createLong(z,0.0).extend(b), a[ad]/b[bd];; + q[z]=m; + d,a = d.apply('*(m)), a.zipWith('-,d); + } + return(q,a); // may have trailing zero elements +} +fcn degree(v){ // -1,0,..len(v)-1, -1 if v==0 + v.len() - v.copy().reverse().filter1n('!=(0)) - 1; +} +fcn polyString(terms){ // (a0,a1,a2...)-->"a0 + a1x + a2x^2 ..." + str:=[0..].zipWith('wrap(n,a){ if(a) "+ %sx^%s ".fmt(a,n) else "" },terms) + .pump(String) + .replace("x^0 "," ").replace(" 1x"," x").replace("x^1 ","x ") + .replace("+ -", "- "); + if(not str) return(" "); // all zeros + if(str[0]=="+") str[1,*]; // leave leading space + else String("-",str[2,*]); +} diff --git a/Task/Polynomial-long-division/Zkl/polynomial-long-division-2.zkl b/Task/Polynomial-long-division/Zkl/polynomial-long-division-2.zkl new file mode 100644 index 0000000000..fa719cb70b --- /dev/null +++ b/Task/Polynomial-long-division/Zkl/polynomial-long-division-2.zkl @@ -0,0 +1,3 @@ +q,r:=polyLongDivision(T(-42.0, 0.0, -12.0, 1.0),T(-3.0, 1.0)); +println("Quotient = ",polyString(q)); +println("Remainder = ",polyString(r)); diff --git a/Task/Polynomial-regression/Gnuplot/polynomial-regression.gnuplot b/Task/Polynomial-regression/Gnuplot/polynomial-regression.gnuplot new file mode 100644 index 0000000000..5627ad8180 --- /dev/null +++ b/Task/Polynomial-regression/Gnuplot/polynomial-regression.gnuplot @@ -0,0 +1,24 @@ +# The polynomial approximation +f(x) = a*x**2 + b*x + c + +# Initial values for parameters +a = 0.1 +b = 0.1 +c = 0.1 + +# Fit f to the following data by modifying the variables a, b, c +fit f(x) '-' via a, b, c + 0 1 + 1 6 + 2 17 + 3 34 + 4 57 + 5 86 + 6 121 + 7 162 + 8 209 + 9 262 + 10 321 +e + +print sprintf("\n --- \n Polynomial fit: %.4f x^2 + %.4f x + %.4f\n", a, b, c) diff --git a/Task/Polynomial-regression/Go/polynomial-regression-1.go b/Task/Polynomial-regression/Go/polynomial-regression-1.go index f88f93ccef..f5dfefd8a5 100644 --- a/Task/Polynomial-regression/Go/polynomial-regression-1.go +++ b/Task/Polynomial-regression/Go/polynomial-regression-1.go @@ -14,9 +14,9 @@ var ( ) func main() { - a := Vandermonde(x, 2) - b := mat64.NewDense(11, 1, y) - c := mat64.NewDense(3, 1, nil) + a := Vandermonde(x, degree) + b := mat64.NewDense(len(y), 1, y) + c := mat64.NewDense(degree+1, 1, nil) qr := new(mat64.QR) qr.Factorize(a) diff --git a/Task/Polynomial-regression/HicEst/polynomial-regression-1.hicest b/Task/Polynomial-regression/HicEst/polynomial-regression-1.hicest deleted file mode 100644 index e31c893157..0000000000 --- a/Task/Polynomial-regression/HicEst/polynomial-regression-1.hicest +++ /dev/null @@ -1,15 +0,0 @@ -REAL :: n=10, x(n), y(n), m=3, p(m) - - x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) - y = (1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321) - - p = 2 ! initial guess for the polynom's coefficients - - SOLVE(NUL=Theory()-y(nr), Unknown=p, DataIdx=nr, Iters=iterations) - - WRITE(ClipBoard, Name) p, iterations - -FUNCTION Theory() - ! called by the solver of the SOLVE function. All variables are global - Theory = p(1)*x(nr)^2 + p(2)*x(nr) + p(3) - END diff --git a/Task/Polynomial-regression/HicEst/polynomial-regression-2.hicest b/Task/Polynomial-regression/HicEst/polynomial-regression-2.hicest deleted file mode 100644 index f52ff606fd..0000000000 --- a/Task/Polynomial-regression/HicEst/polynomial-regression-2.hicest +++ /dev/null @@ -1,2 +0,0 @@ -SOLVE performs a (nonlinear) least-square fit (Levenberg-Marquardt): -p(1)=2.997135145; p(2)=2.011348347; p(3)=0.9906627242; iterations=19; diff --git a/Task/Polynomial-regression/Julia/polynomial-regression-1.julia b/Task/Polynomial-regression/Julia/polynomial-regression-1.julia deleted file mode 100644 index b397000990..0000000000 --- a/Task/Polynomial-regression/Julia/polynomial-regression-1.julia +++ /dev/null @@ -1,4 +0,0 @@ -function polyfit(x, y, n) - A = [ float(x[i])^p for i = 1:length(x), p = 0:n ] - A \ y -end diff --git a/Task/Polynomial-regression/Julia/polynomial-regression-2.julia b/Task/Polynomial-regression/Julia/polynomial-regression-2.julia deleted file mode 100644 index 973047c0c5..0000000000 --- a/Task/Polynomial-regression/Julia/polynomial-regression-2.julia +++ /dev/null @@ -1,7 +0,0 @@ -julia> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] -julia> y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321] -julia> polyfit(x, y, 2) -3-element Array{Float64,1}: - 1.0 - 2.0 - 3.0 diff --git a/Task/Polynomial-regression/PARI-GP/polynomial-regression-2.pari b/Task/Polynomial-regression/PARI-GP/polynomial-regression-2.pari index 3e764b0e14..d111bb28f4 100644 --- a/Task/Polynomial-regression/PARI-GP/polynomial-regression-2.pari +++ b/Task/Polynomial-regression/PARI-GP/polynomial-regression-2.pari @@ -1,2 +1 @@ -V=[1,6,17,34,57,86,121,162,209,262,321]~; -M=matrix(#V,3,i,j,(i-1)^(j-1));Polrev(matsolve(M~*M,M~*V)) +polinterpolate([0..10],[1,6,17,34,57,86,121,162,209,262,321]) diff --git a/Task/Polynomial-regression/PARI-GP/polynomial-regression-3.pari b/Task/Polynomial-regression/PARI-GP/polynomial-regression-3.pari index 15c8d681f3..3e764b0e14 100644 --- a/Task/Polynomial-regression/PARI-GP/polynomial-regression-3.pari +++ b/Task/Polynomial-regression/PARI-GP/polynomial-regression-3.pari @@ -1,2 +1,2 @@ -lsf(X,Y,n)=my(M=matrix(#X,n+1,i,j,X[i]^(j-1))); Polrev(matsolve(M~*M,M~*Y~)) -lsf([0..10], [1,6,17,34,57,86,121,162,209,262,321], 2) +V=[1,6,17,34,57,86,121,162,209,262,321]~; +M=matrix(#V,3,i,j,(i-1)^(j-1));Polrev(matsolve(M~*M,M~*V)) diff --git a/Task/Polynomial-regression/PARI-GP/polynomial-regression-4.pari b/Task/Polynomial-regression/PARI-GP/polynomial-regression-4.pari new file mode 100644 index 0000000000..15c8d681f3 --- /dev/null +++ b/Task/Polynomial-regression/PARI-GP/polynomial-regression-4.pari @@ -0,0 +1,2 @@ +lsf(X,Y,n)=my(M=matrix(#X,n+1,i,j,X[i]^(j-1))); Polrev(matsolve(M~*M,M~*Y~)) +lsf([0..10], [1,6,17,34,57,86,121,162,209,262,321], 2) diff --git a/Task/Polynomial-regression/Phix/polynomial-regression-1.phix b/Task/Polynomial-regression/Phix/polynomial-regression-1.phix new file mode 100644 index 0000000000..4be7041eba --- /dev/null +++ b/Task/Polynomial-regression/Phix/polynomial-regression-1.phix @@ -0,0 +1,46 @@ +constant x = {0,1,2,3,4,5,6,7,8,9,10} +constant y = {1,6,17,34,57,86,121,162,209,262,321} +constant n = length(x) + +function regression() +atom {xm, ym, x2m, x3m, x4m, xym, x2ym} @= 0 + for i=1 to n do + atom xi = x[i], + yi = y[i] + xm += xi + ym += yi + x2m += power(xi,2) + x3m += power(xi,3) + x4m += power(xi,4) + xym += xi*yi + x2ym += power(xi,2)*yi + end for + xm /= n + ym /= n + x2m /= n + x3m /= n + x4m /= n + xym /= n + x2ym /= n + atom Sxx = x2m-power(xm,2), + Sxy = xym-xm*ym, + Sxx2 = x3m-xm*x2m, + Sx2x2 = x4m-power(x2m,2), + Sx2y = x2ym-x2m*ym, + B = (Sxy*Sx2x2-Sx2y*Sxx2)/(Sxx*Sx2x2-power(Sxx2,2)), + C = (Sx2y*Sxx-Sxy*Sxx2)/(Sxx*Sx2x2-power(Sxx2,2)), + A = ym-B*xm-C*x2m + return {C,B,A} +end function + +atom {a,b,c} = regression() + +function f(atom x) + return a*x*x+b*x+c +end function + +printf(1,"y=%gx^2+%gx+%g\n",{a,b,c}) +printf(1,"\n x y f(x)\n") +for i=1 to n do + printf(1," %2d %3d %3g\n",{x[i],y[i],f(x[i])}) +end for diff --git a/Task/Polynomial-regression/Phix/polynomial-regression-2.phix b/Task/Polynomial-regression/Phix/polynomial-regression-2.phix new file mode 100644 index 0000000000..a860d14829 --- /dev/null +++ b/Task/Polynomial-regression/Phix/polynomial-regression-2.phix @@ -0,0 +1,22 @@ +include pGUI.e + +constant x = {0,1,2,3,4,5,6,7,8,9,10} +constant y = {1,6,17,34,57,86,121,162,209,262,321} + +IupOpen() + +Ihandle plot = IupPlot("GRID=YES, MARGINLEFT=50, MARGINBOTTOM=40") + -- (just add ", AXS_YSCALE=LOG10" for a nice log scale) +IupPlotBegin(plot, 0) +for i=1 to length(x) do + IupPlotAdd(plot, x[i], y[i]) +end for +{} = IupPlotEnd(plot) + +Ihandle dlg = IupDialog(plot) +IupSetAttributes(dlg, "RASTERSIZE=%dx%d", {640, 480}) +IupSetAttribute(dlg, "TITLE", "simple plot") +IupShow(dlg) + +IupMainLoop() +IupClose() diff --git a/Task/Polynomial-regression/R/polynomial-regression-2.r b/Task/Polynomial-regression/R/polynomial-regression-2.r index b26e1fc746..c837fd8b2d 100644 --- a/Task/Polynomial-regression/R/polynomial-regression-2.r +++ b/Task/Polynomial-regression/R/polynomial-regression-2.r @@ -1,2 +1 @@ -(Intercept) x I(x^2) - 1 2 3 +coef(lm(y ~ poly(x, 2, raw=T))) diff --git a/Task/Polynomial-regression/R/polynomial-regression.r b/Task/Polynomial-regression/R/polynomial-regression.r deleted file mode 100644 index 2a646e259f..0000000000 --- a/Task/Polynomial-regression/R/polynomial-regression.r +++ /dev/null @@ -1,3 +0,0 @@ -x <- c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) -y <- c(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321) -coef(lm(y ~ x + I(x^2))) diff --git a/Task/Polynomial-regression/REXX/polynomial-regression.rexx b/Task/Polynomial-regression/REXX/polynomial-regression.rexx new file mode 100644 index 0000000000..7169eca634 --- /dev/null +++ b/Task/Polynomial-regression/REXX/polynomial-regression.rexx @@ -0,0 +1,51 @@ +/* REXX --------------------------------------------------------------- +* Implementation of http://keisan.casio.com/exec/system/14059932254941 +*--------------------------------------------------------------------*/ +xl='0 1 2 3 4 5 6 7 8 9 10' +yl='1 6 17 34 57 86 121 162 209 262 321' +n=11 +Do i=1 To n + Parse Var xl x.i xl + Parse Var yl y.i yl + End +xm=0 +ym=0 +x2m=0 +x3m=0 +x4m=0 +xym=0 +x2ym=0 +Do i=1 To n + xm=xm+x.i + ym=ym+y.i + x2m=x2m+x.i**2 + x3m=x3m+x.i**3 + x4m=x4m+x.i**4 + xym=xym+x.i*y.i + x2ym=x2ym+(x.i**2)*y.i + End +xm =xm /n +ym =ym /n +x2m=x2m/n +x3m=x3m/n +x4m=x4m/n +xym=xym/n +x2ym=x2ym/n +Sxx=x2m-xm**2 +Sxy=xym-xm*ym +Sxx2=x3m-xm*x2m +Sx2x2=x4m-x2m**2 +Sx2y=x2ym-x2m*ym +B=(Sxy*Sx2x2-Sx2y*Sxx2)/(Sxx*Sx2x2-Sxx2**2) +C=(Sx2y*Sxx-Sxy*Sxx2)/(Sxx*Sx2x2-Sxx2**2) +A=ym-B*xm-C*x2m +Say 'y='a'+'||b'*x+'c'*x**2' +Say ' Input "Approximation"' +Say ' x y y1' +Do i=1 To 11 + Say right(x.i,2) right(y.i,3) format(fun(x.i),5,3) + End +Exit +fun: + Parse Arg x + Return a+b*x+c*x**2 diff --git a/Task/Polynomial-regression/Sidef/polynomial-regression.sidef b/Task/Polynomial-regression/Sidef/polynomial-regression.sidef index 7a1a6bbd25..9db8154ba6 100644 --- a/Task/Polynomial-regression/Sidef/polynomial-regression.sidef +++ b/Task/Polynomial-regression/Sidef/polynomial-regression.sidef @@ -1,18 +1,18 @@ -var Matrix = require('Math::Matrix'); +var Matrix = require('Math::Matrix') func regress(x, y, degree) { - var x_data = x.map { |xi| (0..degree).map { |pow| (xi**pow).to_f } }; + var x_data = x.map {|xi| (0..degree).map {|pow| xi**pow } } - var mx = Matrix.new(x_data...); - var my = Matrix.new(y.map{[_]}...); + var mx = Matrix.new(x_data...) + var my = Matrix.new(y.map{[_]}...) - mx.transpose.multiply(mx).invert.multiply(mx.transpose).multiply(my).transpose; + mx.transpose.multiply(mx).invert.multiply(mx.transpose).multiply(my).transpose } var betas = regress( [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321], 2 -); +) -betas.print; +betas.print diff --git a/Task/Polynomial-regression/Stata/polynomial-regression.stata b/Task/Polynomial-regression/Stata/polynomial-regression.stata new file mode 100644 index 0000000000..71a6398b1a --- /dev/null +++ b/Task/Polynomial-regression/Stata/polynomial-regression.stata @@ -0,0 +1,33 @@ +. clear +. input x y +0 1 +1 6 +2 17 +3 34 +4 57 +5 86 +6 121 +7 162 +8 209 +9 262 +10 321 +end + +. regress y c.x##c.x + + Source | SS df MS Number of obs = 11 +-------------+---------------------------------- F(2, 8) = . + Model | 120362 2 60181 Prob > F = . + Residual | 0 8 0 R-squared = 1.0000 +-------------+---------------------------------- Adj R-squared = 1.0000 + Total | 120362 10 12036.2 Root MSE = 0 + +------------------------------------------------------------------------------ + y | Coef. Std. Err. t P>|t| [95% Conf. Interval] +-------------+---------------------------------------------------------------- + x | 2 . . . . . + | + c.x#c.x | 3 . . . . . + | + _cons | 1 . . . . . +------------------------------------------------------------------------------ diff --git a/Task/Polynomial-regression/Zkl/polynomial-regression-1.zkl b/Task/Polynomial-regression/Zkl/polynomial-regression-1.zkl new file mode 100644 index 0000000000..ea85d8c9e4 --- /dev/null +++ b/Task/Polynomial-regression/Zkl/polynomial-regression-1.zkl @@ -0,0 +1,7 @@ +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +xs:=GSL.VectorFromData(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); +ys:=GSL.VectorFromData(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321); +v :=GSL.polyFit(xs,ys,2); +v.format().println(); +GSL.Helpers.polyString(v).println(); +GSL.Helpers.polyEval(v,xs).format().println(); diff --git a/Task/Polynomial-regression/Zkl/polynomial-regression-2.zkl b/Task/Polynomial-regression/Zkl/polynomial-regression-2.zkl new file mode 100644 index 0000000000..06722d584c --- /dev/null +++ b/Task/Polynomial-regression/Zkl/polynomial-regression-2.zkl @@ -0,0 +1,3 @@ +polyfit(T(T(0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0)), + T(T(1.0,6.0,17.0,34.0,57.0,86.0,121.0,162.0,209.0,262.0,321.0)), 2) +.flatten().println(); diff --git a/Task/Power-set/Ada/power-set-1.ada b/Task/Power-set/Ada/power-set-1.ada deleted file mode 100644 index 22f8156055..0000000000 --- a/Task/Power-set/Ada/power-set-1.ada +++ /dev/null @@ -1,10 +0,0 @@ -package Power_Set is - - type Set is array (Positive range <>) of Positive; - Empty_Set: Set(1 .. 0); - - generic - with procedure Visit(S: Set); - procedure All_Subsets(S: Set); -- calles Visit once for each subset of S - -end Power_Set; diff --git a/Task/Power-set/Ada/power-set-2.ada b/Task/Power-set/Ada/power-set-2.ada deleted file mode 100644 index 951f255bd9..0000000000 --- a/Task/Power-set/Ada/power-set-2.ada +++ /dev/null @@ -1,20 +0,0 @@ -package body Power_Set is - - procedure All_Subsets(S: Set) is - - procedure Visit_Sets(Unmarked: Set; Marked: Set) is - Tail: Set := Unmarked(Unmarked'First+1 .. Unmarked'Last); - begin - if Unmarked = Empty_Set then - Visit(Marked); - else - Visit_Sets(Tail, Marked & Unmarked(Unmarked'First)); - Visit_Sets(Tail, Marked); - end if; - end Visit_Sets; - - begin - Visit_Sets(S, Empty_Set); - end All_Subsets; - -end Power_Set; diff --git a/Task/Power-set/Ada/power-set-3.ada b/Task/Power-set/Ada/power-set-3.ada deleted file mode 100644 index 8fb42043e1..0000000000 --- a/Task/Power-set/Ada/power-set-3.ada +++ /dev/null @@ -1,28 +0,0 @@ -with Ada.Text_IO, Ada.Command_Line, Power_Set; - -procedure Print_Power_Set is - - procedure Print_Set(Items: Power_Set.Set) is - First: Boolean := True; - begin - Ada.Text_IO.Put("{ "); - for Item of Items loop - if First then - First := False; -- no comma needed - else - Ada.Text_IO.Put(", "); -- comma, to separate the items - end if; - Ada.Text_IO.Put(Ada.Command_Line.Argument(Item)); - end loop; - Ada.Text_IO.Put_Line(" }"); - end Print_Set; - - procedure Print_All_Subsets is new Power_Set.All_Subsets(Print_Set); - - Set: Power_Set.Set(1 .. Ada.Command_Line.Argument_Count); -begin - for I in Set'Range loop -- initialize set - Set(I) := I; - end loop; - Print_All_Subsets(Set); -- do the work -end; diff --git a/Task/Power-set/Ada/power-set.ada b/Task/Power-set/Ada/power-set.ada new file mode 100644 index 0000000000..53a9bb00a3 --- /dev/null +++ b/Task/Power-set/Ada/power-set.ada @@ -0,0 +1,28 @@ +with Ada.Text_IO, Ada.Command_Line; +use Ada.Text_IO, Ada.Command_Line; + +procedure powerset is + procedure print_subset (set : natural) is +-- each i'th binary digit of "set" indicates if the i'th integer belongs to "set" or not. + k : natural := set; + first : boolean := true; + begin + Put ("{"); + for i in 1..Argument_Count loop + if k mod 2 = 1 then + if first then + first := false; + else + Put (","); + end if; + Put (Argument (i)); + end if; + k := k / 2; -- we go to the next bit of "set" + end loop; + Put_Line("}"); + end print_subset; +begin + for i in 0..2**Argument_Count-1 loop + print_subset (i); + end loop; +end powerset; diff --git a/Task/Power-set/AppleScript/power-set-1.applescript b/Task/Power-set/AppleScript/power-set-1.applescript index 1e83709750..0d8dd6b31f 100644 --- a/Task/Power-set/AppleScript/power-set-1.applescript +++ b/Task/Power-set/AppleScript/power-set-1.applescript @@ -1,29 +1,30 @@ +-- POWER SET ----------------------------------------------------------------- + -- powerset :: [a] -> [[a]] on powerset(xs) script subSet - on lambda(acc, x) - script consX - on lambda(y) + on |λ|(acc, x) + script cons + on |λ|(y) {x} & y - end lambda + end |λ| end script - acc & map(consX, acc) - end lambda + acc & map(cons, acc) + end |λ| end script foldr(subSet, {{}}, xs) end powerset --------------------------------------------------------------------------------------- --- TEST +-- TEST ---------------------------------------------------------------------- on run script test - on lambda(x) + on |λ|(x) set {setName, setMembers} to x {setName, powerset(setMembers)} - end lambda + end |λ| end script map(test, [¬ @@ -34,11 +35,9 @@ on run --> {{"Set [1,2,3]", {{}, {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}}}, --> {"Empty set", {{}}}, --> {"Set containing only empty set", {{}, {{}}}}} - end run - --- GENERIC FUNCTIONS --------------------------------------------------------------- +-- GENERIC FUNCTIONS --------------------------------------------------------- -- foldr :: (a -> b -> a) -> a -> [b] -> a on foldr(f, startValue, xs) @@ -46,7 +45,7 @@ on foldr(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -58,7 +57,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -71,7 +70,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Power-set/C/power-set-1.c b/Task/Power-set/C/power-set-1.c deleted file mode 100644 index 10dabb8cb5..0000000000 --- a/Task/Power-set/C/power-set-1.c +++ /dev/null @@ -1,28 +0,0 @@ -#include -#include -#include - -static void powerset(int argc, char** argv) -{ - unsigned int i, j, bits, i_max = 1U << argc; - - if (argc >= sizeof(i) * CHAR_BIT) { - fprintf(stderr, "Error: set too large\n"); - exit(1); - } - - for (i = 0; i < i_max ; ++i) { - printf("{"); - for (bits = i, j = 0; bits; bits >>= 1, ++j) { - if (bits & 1) - printf(bits > 1 ? "%s, " : "%s", argv[j]); - } - printf("}\n"); - } -} - -int main(int argc, char* argv[]) -{ - powerset(argc - 1, argv + 1); - return 0; -} diff --git a/Task/Power-set/C/power-set-2.c b/Task/Power-set/C/power-set-2.c deleted file mode 100644 index 17c01ecac3..0000000000 --- a/Task/Power-set/C/power-set-2.c +++ /dev/null @@ -1,17 +0,0 @@ -% ./a.out 1 2 3 4 -{} -{1} -{2} -{1, 2} -{3} -{1, 3} -{2, 3} -{1, 2, 3} -{4} -{1, 4} -{2, 4} -{1, 2, 4} -{3, 4} -{1, 3, 4} -{2, 3, 4} -{1, 2, 3, 4} diff --git a/Task/Power-set/Haskell/power-set-3.hs b/Task/Power-set/Haskell/power-set-3.hs index 4ed8ea3c0a..d1a0f176f3 100644 --- a/Task/Power-set/Haskell/power-set-3.hs +++ b/Task/Power-set/Haskell/power-set-3.hs @@ -1,2 +1,2 @@ powerSet :: [a] -> [[a]] -powerset = foldr (\x acc -> acc ++ map (x:) acc) [[]] +powerSet = foldr (\x acc -> acc ++ map (x:) acc) [[]] diff --git a/Task/Power-set/Haskell/power-set-4.hs b/Task/Power-set/Haskell/power-set-4.hs index e4c027f567..795caa6865 100644 --- a/Task/Power-set/Haskell/power-set-4.hs +++ b/Task/Power-set/Haskell/power-set-4.hs @@ -1,15 +1,2 @@ -import qualified Data.Set as Set -type Set=Set.Set -unionAll :: (Ord a) => Set (Set a) -> Set a -unionAll = Set.fold Set.union Set.empty - ---slift is the analogue of liftA2 for sets. -slift :: (Ord a, Ord b, Ord c) => (a->b->c) -> Set a -> Set b -> Set c -slift f s0 s1 = unionAll (Set.map (\e->Set.map (f e) s1) s0) - ---a -> {{},{a}} -makeSet :: (Ord a) => a -> Set (Set a) -makeSet = (Set.insert Set.empty) . Set.singleton.Set.singleton - -powerSet :: (Ord a) => Set a -> Set (Set a) -powerSet = (Set.fold (slift Set.union) (Set.singleton Set.empty)) . Set.map makeSet +powerSet :: [a] -> [[a]] +powerSet = foldr ((mappend <*>) . fmap . (:)) (pure []) diff --git a/Task/Power-set/Haskell/power-set-5.hs b/Task/Power-set/Haskell/power-set-5.hs index c34a0f14a8..e4c027f567 100644 --- a/Task/Power-set/Haskell/power-set-5.hs +++ b/Task/Power-set/Haskell/power-set-5.hs @@ -1,2 +1,15 @@ -Prelude Data.Set> powerSet fromList [1,2,3] -fromList [fromList [], fromList [1], fromList [1,2], fromList [1,2,3], fromList [1,3], fromList [2], fromList [2,3], fromList [3]] +import qualified Data.Set as Set +type Set=Set.Set +unionAll :: (Ord a) => Set (Set a) -> Set a +unionAll = Set.fold Set.union Set.empty + +--slift is the analogue of liftA2 for sets. +slift :: (Ord a, Ord b, Ord c) => (a->b->c) -> Set a -> Set b -> Set c +slift f s0 s1 = unionAll (Set.map (\e->Set.map (f e) s1) s0) + +--a -> {{},{a}} +makeSet :: (Ord a) => a -> Set (Set a) +makeSet = (Set.insert Set.empty) . Set.singleton.Set.singleton + +powerSet :: (Ord a) => Set a -> Set (Set a) +powerSet = (Set.fold (slift Set.union) (Set.singleton Set.empty)) . Set.map makeSet diff --git a/Task/Power-set/Haskell/power-set-6.hs b/Task/Power-set/Haskell/power-set-6.hs new file mode 100644 index 0000000000..c34a0f14a8 --- /dev/null +++ b/Task/Power-set/Haskell/power-set-6.hs @@ -0,0 +1,2 @@ +Prelude Data.Set> powerSet fromList [1,2,3] +fromList [fromList [], fromList [1], fromList [1,2], fromList [1,2,3], fromList [1,3], fromList [2], fromList [2,3], fromList [3]] diff --git a/Task/Power-set/jq/power-set-1.jq b/Task/Power-set/Jq/power-set-1.jq similarity index 100% rename from Task/Power-set/jq/power-set-1.jq rename to Task/Power-set/Jq/power-set-1.jq diff --git a/Task/Power-set/jq/power-set-2.jq b/Task/Power-set/Jq/power-set-2.jq similarity index 100% rename from Task/Power-set/jq/power-set-2.jq rename to Task/Power-set/Jq/power-set-2.jq diff --git a/Task/Power-set/jq/power-set-3.jq b/Task/Power-set/Jq/power-set-3.jq similarity index 100% rename from Task/Power-set/jq/power-set-3.jq rename to Task/Power-set/Jq/power-set-3.jq diff --git a/Task/Power-set/Kotlin/power-set.kotlin b/Task/Power-set/Kotlin/power-set.kotlin new file mode 100644 index 0000000000..4604b4e532 --- /dev/null +++ b/Task/Power-set/Kotlin/power-set.kotlin @@ -0,0 +1,38 @@ +// version 1.1.3 + +class PowerSet(val items: List) { + private lateinit var combination: IntArray + + init { + println("Power set of $items comprises:") + for (m in 0..items.size) { + combination = IntArray(m) + generate(0, m) + } + } + + private fun generate(k: Int, m: Int) { + if (k >= m) { + println(combination.map { items[it] }) + } + else { + for (j in 0 until items.size) + if (k == 0 || j > combination[k - 1]) { + combination[k] = j + generate(k + 1, m) + } + } + } +} + +fun main(args: Array) { + val itemsList = listOf( + listOf(1, 2, 3, 4), + emptyList(), + listOf(emptyList()) + ) + for (items in itemsList) { + PowerSet(items) + println() + } +} diff --git a/Task/Power-set/Phix/power-set.phix b/Task/Power-set/Phix/power-set.phix new file mode 100644 index 0000000000..daf963793c --- /dev/null +++ b/Task/Power-set/Phix/power-set.phix @@ -0,0 +1,33 @@ +sequence powerset +integer step = 1 + +function pst(object key, object /*data*/, object /*user_data*/) + integer k = 1 + while k 0 THEN OUTTEXT(","); + OUTINT(V_LI.N, 0); + V_LI :- V_LI.SUC; + I := I+1; + END; + END; + OUTTEXT("]"); + END PRINT_LIST; + + PROCEDURE PRINT_LIST_LIST(P_LLI); REF(HEAD) P_LLI; + BEGIN + OUTTEXT("["); + IF NOT P_LLI.EMPTY THEN BEGIN + INTEGER I; + REF(LOF_LOF_INT) V_LLI; + I := 0; + V_LLI :- P_LLI.FIRST QUA LOF_LOF_INT; + WHILE V_LLI =/= NONE DO BEGIN + IF I > 0 THEN BEGIN + OUTTEXT(","); + ! OUTIMAGE; + END; + PRINT_LIST(V_LLI.H); + V_LLI :- V_LLI.SUC; + I := I+1; + END; + END; + OUTTEXT("]"); + OUTIMAGE; + END PRINT_LIST_LIST; + + INTEGER N; + REF(HEAD) V_RANGE; + REF(HEAD) V_LISTS; + + V_RANGE :- NEW HEAD; + V_LISTS :- SUBSETS(V_RANGE); + PRINT_LIST_LIST(V_LISTS); + OUTIMAGE; + FOR N := 1 STEP 1 UNTIL 4 DO BEGIN + NEW LOF_INT(N).INTO(V_RANGE); + V_LISTS :- SUBSETS(V_RANGE); + PRINT_LIST_LIST(V_LISTS); + OUTIMAGE; + END; +END. diff --git a/Task/Power-set/Zkl/power-set.zkl b/Task/Power-set/Zkl/power-set.zkl new file mode 100644 index 0000000000..35963b7aa1 --- /dev/null +++ b/Task/Power-set/Zkl/power-set.zkl @@ -0,0 +1,4 @@ +fcn pwerSet(list){ + (0).pump(list.len(),List, Utils.Helpers.pickNFrom.fp1(list), + T(Void.Write,Void.Write) ) .append(list) +} diff --git a/Task/Pragmatic-directives/Kotlin/pragmatic-directives.kotlin b/Task/Pragmatic-directives/Kotlin/pragmatic-directives.kotlin new file mode 100644 index 0000000000..66406f11de --- /dev/null +++ b/Task/Pragmatic-directives/Kotlin/pragmatic-directives.kotlin @@ -0,0 +1,7 @@ +// version 1.0.6 + +@Suppress("UNUSED_VARIABLE") + +fun main(args: Array) { + val s = "To be suppressed" +} diff --git a/Task/Price-fraction/Common-Lisp/price-fraction.lisp b/Task/Price-fraction/Common-Lisp/price-fraction.lisp new file mode 100644 index 0000000000..af7c70e595 --- /dev/null +++ b/Task/Price-fraction/Common-Lisp/price-fraction.lisp @@ -0,0 +1,23 @@ +(defun scale (value) + (cond ((minusp value) (error "invalid value: ~A" value)) + ((< value 0.06) 0.10) + ((< value 0.11) 0.18) + ((< value 0.16) 0.26) + ((< value 0.21) 0.32) + ((< value 0.26) 0.38) + ((< value 0.31) 0.44) + ((< value 0.36) 0.50) + ((< value 0.41) 0.54) + ((< value 0.46) 0.58) + ((< value 0.51) 0.62) + ((< value 0.56) 0.66) + ((< value 0.61) 0.70) + ((< value 0.66) 0.74) + ((< value 0.71) 0.78) + ((< value 0.76) 0.82) + ((< value 0.81) 0.86) + ((< value 0.86) 0.90) + ((< value 0.91) 0.94) + ((< value 0.96) 0.98) + ((< value 1.01) 1.00) + (t (error "invalid value: ~A" value)))) diff --git a/Task/Price-fraction/jq/price-fraction-1.jq b/Task/Price-fraction/Jq/price-fraction-1.jq similarity index 100% rename from Task/Price-fraction/jq/price-fraction-1.jq rename to Task/Price-fraction/Jq/price-fraction-1.jq diff --git a/Task/Price-fraction/jq/price-fraction-2.jq b/Task/Price-fraction/Jq/price-fraction-2.jq similarity index 100% rename from Task/Price-fraction/jq/price-fraction-2.jq rename to Task/Price-fraction/Jq/price-fraction-2.jq diff --git a/Task/Price-fraction/K/price-fraction-1.k b/Task/Price-fraction/K/price-fraction-1.k deleted file mode 100644 index 68bf835d28..0000000000 --- a/Task/Price-fraction/K/price-fraction-1.k +++ /dev/null @@ -1,4 +0,0 @@ -le:- 0.96 0.91 0.86 0.81 0.76 0.71 0.66 0.61 0.56 0.51 0.46 0.41 0.36 0.31 0.26 0.21 0.16 0.11 0.06 0.0 -out: 1.00 0.98 0.94 0.90 0.86 0.82 0.78 0.74 0.70 0.66 0.62 0.58 0.54 0.50 0.44 0.38 0.32 0.26 0.18 0.1 - -pf:{out@_bin[le;-x]}' diff --git a/Task/Price-fraction/K/price-fraction-2.k b/Task/Price-fraction/K/price-fraction-2.k deleted file mode 100644 index 44d66b2ddf..0000000000 --- a/Task/Price-fraction/K/price-fraction-2.k +++ /dev/null @@ -1,2 +0,0 @@ - pf 0.6094701 0.5003597 0.8512954 0.08951883 0.6868076 -0.7 0.62 0.9 0.18 0.78 diff --git a/Task/Price-fraction/Kotlin/price-fraction.kotlin b/Task/Price-fraction/Kotlin/price-fraction.kotlin new file mode 100644 index 0000000000..31a01aa049 --- /dev/null +++ b/Task/Price-fraction/Kotlin/price-fraction.kotlin @@ -0,0 +1,34 @@ +// version 1.0.6 + +fun rescale(price: Double): Double = + when { + price < 0.06 -> 0.10 + price < 0.11 -> 0.18 + price < 0.16 -> 0.26 + price < 0.21 -> 0.32 + price < 0.26 -> 0.38 + price < 0.31 -> 0.44 + price < 0.36 -> 0.50 + price < 0.41 -> 0.54 + price < 0.46 -> 0.58 + price < 0.51 -> 0.62 + price < 0.56 -> 0.66 + price < 0.61 -> 0.70 + price < 0.66 -> 0.74 + price < 0.71 -> 0.78 + price < 0.76 -> 0.82 + price < 0.81 -> 0.86 + price < 0.86 -> 0.90 + price < 0.91 -> 0.94 + price < 0.96 -> 0.98 + else -> 1.00 + } + +fun main(args: Array) { + var d: Double + for (i in 1..100) { + d = i / 100.0 + print(String.format("%4.2f -> %4.2f ", d, rescale(d))) + if (i % 5 == 0) println() + } +} diff --git a/Task/Price-fraction/Nimrod/price-fraction.nimrod b/Task/Price-fraction/Nimrod/price-fraction.nimrod deleted file mode 100644 index 0bbfe319b7..0000000000 --- a/Task/Price-fraction/Nimrod/price-fraction.nimrod +++ /dev/null @@ -1,32 +0,0 @@ -import strutils, math - -const - pricemap: array[0 .. 19, int] = [10,18,26,32,38,44,50,54,58,62,66,70,74,78,82,86,90,94,98,100] - -# outputs an int (=>float*100) -proc floatToPrice100(f: float): int = - # indx: 0.1-0.05->0, 0.06-0.10->1, 0.11-0.15->2, ..... - var valu: int = toInt(f*100) - if valu == 0: - result = 10 - else: - dec(valu) - # inc indx every 5 of valu, so value of 1..100 translates to indx of 0..19 - var indx: int = 2*int(valu/10)+int((valu%%10)/5) - result = pricemap[indx] - -# str representation of an int (that is a representation of a float price) -proc price100ToStr(p: int): string = - if p < 10: - result = "0.0" & $p - if p < 100: - result = "0." & $p - else: - result = "1.00" - -randomize() -var i: int = 0 - -for x in 0 .. 10: - i = random(101) - echo("Price for ", i.price100ToStr(), ", is: ", float(i/100).floatToPrice100().price100ToStr()) diff --git a/Task/Price-fraction/PowerShell/price-fraction-1.psh b/Task/Price-fraction/PowerShell/price-fraction-1.psh new file mode 100644 index 0000000000..05a1b5a551 --- /dev/null +++ b/Task/Price-fraction/PowerShell/price-fraction-1.psh @@ -0,0 +1,45 @@ +function Convert-PriceFraction +{ + [CmdletBinding()] + [OutputType([double])] + Param + ( + [Parameter(Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true, + Position=0)] + [ValidateScript({$_ -ge 0.0 -and $_ -le 1.0})] + [double] + $InputObject + ) + + Process + { + foreach ($fraction in $InputObject) + { + switch ($fraction) + { + {$_ -lt 0.06} {0.10; break} + {$_ -lt 0.11} {0.18; break} + {$_ -lt 0.16} {0.26; break} + {$_ -lt 0.21} {0.32; break} + {$_ -lt 0.26} {0.38; break} + {$_ -lt 0.31} {0.44; break} + {$_ -lt 0.36} {0.50; break} + {$_ -lt 0.41} {0.54; break} + {$_ -lt 0.46} {0.58; break} + {$_ -lt 0.51} {0.62; break} + {$_ -lt 0.56} {0.66; break} + {$_ -lt 0.61} {0.70; break} + {$_ -lt 0.66} {0.74; break} + {$_ -lt 0.71} {0.78; break} + {$_ -lt 0.76} {0.82; break} + {$_ -lt 0.81} {0.86; break} + {$_ -lt 0.86} {0.90; break} + {$_ -lt 0.91} {0.94; break} + {$_ -lt 0.96} {0.98; break} + Default {1.00} + } + } + } +} diff --git a/Task/Price-fraction/PowerShell/price-fraction-2.psh b/Task/Price-fraction/PowerShell/price-fraction-2.psh new file mode 100644 index 0000000000..9e5d01c4a7 --- /dev/null +++ b/Task/Price-fraction/PowerShell/price-fraction-2.psh @@ -0,0 +1 @@ +.7388727, .8593103, .826687, .3444635, .0491907 | Convert-PriceFraction | ForEach-Object {"{0:C}" -f $_} diff --git a/Task/Price-fraction/Zkl/price-fraction-1.zkl b/Task/Price-fraction/Zkl/price-fraction-1.zkl new file mode 100644 index 0000000000..411eafee8a --- /dev/null +++ b/Task/Price-fraction/Zkl/price-fraction-1.zkl @@ -0,0 +1,11 @@ +fcn convert(price){ // float --> float + // < -->, increments of 0.05 but tables are easier to update + var vert=T( T(0.06, 0.10), T(0.11, 0.18), T(0.16, 0.26), + T(0.21, 0.32), T(0.26, 0.38), T(0.31, 0.44), + T(0.36, 0.50), T(0.41, 0.54), T(0.46, 0.58), + T(0.51, 0.62), T(0.56, 0.66), T(0.61, 0.70), + T(0.66, 0.74), T(0.71, 0.78), T(0.76, 0.82), + T(0.81, 0.86), T(0.86, 0.90), T(0.91, 0.94), + T(0.96, 0.98), T(1.01, 1.00), ); + vert.filter1('wrap([(a,_)]){ price

    diff --git a/Task/Primality-by-trial-division/360-Assembly/primality-by-trial-division.360 b/Task/Primality-by-trial-division/360-Assembly/primality-by-trial-division.360 new file mode 100644 index 0000000000..91e33eb8f5 --- /dev/null +++ b/Task/Primality-by-trial-division/360-Assembly/primality-by-trial-division.360 @@ -0,0 +1,63 @@ +* Primality by trial division 26/03/2017 +PRIMEDIV CSECT + USING PRIMEDIV,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + STM R14,R12,12(R13) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + LA R10,PG pgi=0 + LA R6,1 i=1 + DO WHILE=(C,R6,LE,=F'50') do i=1 to 50 + LR R1,R6 i + BAL R14,ISPRIME call isprime(i) + IF C,R0,EQ,=F'1' THEN if isprime(i) then + XDECO R6,XDEC edit i + MVC 0(4,R10),XDEC+8 output i + LA R10,4(R10) pgi+=4 + ENDIF , endif + LA R6,1(R6) i++ + ENDDO , enddo i + XPRNT PG,L'PG print buffer + L R13,4(0,R13) restore previous savearea pointer + LM R14,R12,12(R13) restore previous context + XR R15,R15 rc=0 + BR R14 exit +*------- ---- ---------------------------------------- +ISPRIME EQU * function isprime(n) + IF C,R1,LE,=F'1' THEN if n<=1 then + LA R0,0 return(0) + BR R14 return + ENDIF , endif + IF C,R1,EQ,=F'2' THEN if n=2 then + LA R0,1 return(1) + BR R14 return + ENDIF , endif + LR R4,R1 n + N R4,=X'00000001' n and 1 + IF LTR,R4,Z,R4 THEN if mod(n,2)=0 then + LA R0,0 return(0) + BR R14 return + ENDIF , endif + LA R7,3 j=3 + LA R5,9 r5=j*j + DO WHILE=(CR,R5,LE,R1) do j=3 by 2 while j*j<=n + LR R4,R1 n + SRDA R4,32 ~ + DR R4,R7 /j + IF LTR,R4,Z,R4 THEN if mod(n,j)=0 then + LA R0,0 return(0) + BR R14 return + ENDIF , endif + LA R7,2(R7) j+=2 + LR R5,R7 j + MR R4,R7 r5=j*j + ENDDO , enddo j + LA R0,1 return(1) + BR R14 return +*------- ---- ---------------------------------------- +PG DC CL80' ' buffer +XDEC DS CL12 temp for xdeco + YREGS + END PRIMEDIV diff --git a/Task/Primality-by-trial-division/ALGOL-W/primality-by-trial-division-1.alg b/Task/Primality-by-trial-division/ALGOL-W/primality-by-trial-division-1.alg new file mode 100644 index 0000000000..2aa28ef763 --- /dev/null +++ b/Task/Primality-by-trial-division/ALGOL-W/primality-by-trial-division-1.alg @@ -0,0 +1,17 @@ +% returns true if n is prime, false otherwise % +% uses trial division % +logical procedure isPrime ( integer value n ) ; + if n < 3 or not odd( n ) then n = 2 + else begin + % odd number > 2 % + integer f, rootN; + logical havePrime; + f := 3; + rootN := entier( sqrt( n ) ); + havePrime := true; + while f <= rootN and havePrime do begin + havePrime := ( n rem f ) not = 0; + f := f + 2 + end; + havePrime + end isPrime ; diff --git a/Task/Primality-by-trial-division/ALGOL-W/primality-by-trial-division-2.alg b/Task/Primality-by-trial-division/ALGOL-W/primality-by-trial-division-2.alg new file mode 100644 index 0000000000..1a7924a50d --- /dev/null +++ b/Task/Primality-by-trial-division/ALGOL-W/primality-by-trial-division-2.alg @@ -0,0 +1,4 @@ +begin + logical procedure isPrime ( integer value n ) ; algol "isPrime" ; + for i := 0 until 32 do if isPrime( i ) then writeon( i_w := 1,s_w := 1, i ) +end. diff --git a/Task/Primality-by-trial-division/ATS/primality-by-trial-division.ats b/Task/Primality-by-trial-division/ATS/primality-by-trial-division.ats new file mode 100644 index 0000000000..5088d0adf2 --- /dev/null +++ b/Task/Primality-by-trial-division/ATS/primality-by-trial-division.ats @@ -0,0 +1,32 @@ +(* ****** ****** *) +// +#include +"share/atspre_staload.hats" +#include +"share/HATS/atspre_staload_libats_ML.hats" +// +#staload M = "libats/libc/SATS/math.sats" +// +(* ****** ****** *) +// +fun +isqrt(n: intGte(0)): intGte(0) = + $UNSAFE.cast($M.sqrt_double(g0i2f(n))) +// +fun +is_prime +( +n : intGte(2) +) : bool = +( +if +(n = 2) +then true +else ( + if n % 2 = 0 + then false + else (1, (isqrt(n)+1)/2).forall()(lam i => n % (2*i+1) != 0) +) (* else *) +) (* end of [is_prime] *) +// +(* ****** ****** *) diff --git a/Task/Primality-by-trial-division/Bc/primality-by-trial-division.bc b/Task/Primality-by-trial-division/Bc/primality-by-trial-division.bc new file mode 100644 index 0000000000..93ab2b52ec --- /dev/null +++ b/Task/Primality-by-trial-division/Bc/primality-by-trial-division.bc @@ -0,0 +1,12 @@ +/* Return 1 if n is prime, 0 otherwise */ +define p(n) { + auto i + + if (n < 2) return(0) + if (n == 2) return(1) + if (n % 2 == 0) return(0) + for (i = 3; i * i <= n; i += 2) { + if (n % i == 0) return(0) + } + return(1) +} diff --git a/Task/Primality-by-trial-division/COBOL/primality-by-trial-division-1.cobol b/Task/Primality-by-trial-division/COBOL/primality-by-trial-division-1.cobol deleted file mode 100644 index 80dfb488f2..0000000000 --- a/Task/Primality-by-trial-division/COBOL/primality-by-trial-division-1.cobol +++ /dev/null @@ -1,54 +0,0 @@ - >>source format is free -identification division. -program-id. prime-div. - -data division. -working-storage section. - -*> The number for which we are testing primality. -01 num pic 9(6) value 1. -01 out-num pic z(6). - -*> Division-related stuff. -01 div pic 9(6). -01 div-lim pic 9(6). -01 rem pic 9(6). - 88 not-prime value 0. - -procedure division. -main. - perform until num = 0 - perform get-a-num - perform is-prime - move num to out-num - if not-prime - display out-num " is not prime." - else - display out-num " is prime." - end-if - end-perform - - stop run - . - -is-prime. - if num = 1 - move 0 to rem - else if num < 4 - move 1 to rem - else - compute div-lim = function sqrt(num) + 1 - perform with test after varying div from 2 by 1 - until (div = div-lim) or not-prime - compute rem = function mod(num, div) - end-perform - end-if - . - -get-a-num. - display "Enter a possible prime number (0 to stop): " with no advancing - accept num - if num = 0 - stop run - end-if - . diff --git a/Task/Primality-by-trial-division/COBOL/primality-by-trial-division-2.cobol b/Task/Primality-by-trial-division/COBOL/primality-by-trial-division-2.cobol deleted file mode 100644 index b4b0d6d163..0000000000 --- a/Task/Primality-by-trial-division/COBOL/primality-by-trial-division-2.cobol +++ /dev/null @@ -1,22 +0,0 @@ -Identification division. -Program-id. prime-by-div-main. - -Data division. -Working-storage section. -01 num-out pic z(10). -01 num pic 9(10). -01 ans pic x. - 88 is-prime value "y". - -Procedure division. -Main. -Perform until 1 = 2 - display "Number: " with no advancing - accept num - move num to num-out - if num = 0 stop run end-if - call "prime-by-div-subr" using num by reference ans - if ans = "Y" display num-out " is prime." - else display num-out " is not prime." -end-perform. -Stop run. diff --git a/Task/Primality-by-trial-division/COBOL/primality-by-trial-division-3.cobol b/Task/Primality-by-trial-division/COBOL/primality-by-trial-division-3.cobol deleted file mode 100644 index f2ba131963..0000000000 --- a/Task/Primality-by-trial-division/COBOL/primality-by-trial-division-3.cobol +++ /dev/null @@ -1,27 +0,0 @@ -Identification division. -Program-id. prime-by-div-subr. - -Data division. -Working-storage section. -01 div pic 9(10). -01 lim pic 9(10). -01 rem pic 9(10). - 88 is-not-prime value 0. - -Linkage section. -01 the-num pic 9(10). -01 the-ans pic x. - -Procedure division using the-num, the-ans. -Main. -Move "Y" to the-ans. -If the-num < 4 exit program. -Compute lim = Function sqrt(the-num) + 1. -Perform - with test after - varying div from 2 by 1 - until div > lim or is-not-prime - compute rem = function mod(the-num, div) -end-perform. -If is-not-prime move "N" to the-ans. -Exit program. diff --git a/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-1.clj b/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-1.clj new file mode 100644 index 0000000000..b3fe41231a --- /dev/null +++ b/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-1.clj @@ -0,0 +1 @@ +(defn divides? [k n] (zero? (mod k n))) diff --git a/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-2.clj b/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-2.clj new file mode 100644 index 0000000000..1c04af6669 --- /dev/null +++ b/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-2.clj @@ -0,0 +1,7 @@ +(defn prime? [x] + (or (= 2 x) + (= 3 x) + (and (< 1 x) + (odd? x) + (not-any? (partial divides? x) + (range 3 (math/sqrt x) 2))))) diff --git a/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-3.clj b/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-3.clj new file mode 100644 index 0000000000..42f41ae18b --- /dev/null +++ b/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-3.clj @@ -0,0 +1,10 @@ +(declare prime?) + +(def primes (filter prime? (range))) + +(defn prime? [x] + (or (= 2 x) + (and (integer? x) + (< 1 x) + (not-any? (partial divides? x) + (take-while (partial > (math/sqrt x)) primes))))) diff --git a/Task/Primality-by-trial-division/Clojure/primality-by-trial-division.clj b/Task/Primality-by-trial-division/Clojure/primality-by-trial-division.clj deleted file mode 100644 index 6547389e2f..0000000000 --- a/Task/Primality-by-trial-division/Clojure/primality-by-trial-division.clj +++ /dev/null @@ -1,6 +0,0 @@ -(defn divides? [k n] (= (rem n k) 0)) - -(defn prime? [n] - (if (< n 2) - false - (empty? (filter #(divides? % n) (take-while #(<= (* % %) n) (range 2 n)))))) diff --git a/Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division-1.lisp b/Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division-1.lisp deleted file mode 100644 index 54e14f34d9..0000000000 --- a/Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division-1.lisp +++ /dev/null @@ -1,7 +0,0 @@ - (defun primep (a) - (cond ((= a 2) T) - ((or (<= a 1) (= (mod a 2) 0)) nil) - ((loop for i from 3 to (sqrt a) by 2 do - (if (= (mod a i) 0) - (return nil))) nil) - (T T))) diff --git a/Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division-2.lisp b/Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division-2.lisp deleted file mode 100644 index 55b2ea2dcc..0000000000 --- a/Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division-2.lisp +++ /dev/null @@ -1,6 +0,0 @@ -(defun primep (n) - "Is N prime?" - (and (> n 1) - (or (= n 2) (oddp n)) - (loop for i from 3 to (isqrt n) by 2 - never (zerop (rem n i))))) diff --git a/Task/Primality-by-trial-division/Gambas/primality-by-trial-division.gambas b/Task/Primality-by-trial-division/Gambas/primality-by-trial-division.gambas new file mode 100644 index 0000000000..02b597ce00 --- /dev/null +++ b/Task/Primality-by-trial-division/Gambas/primality-by-trial-division.gambas @@ -0,0 +1,26 @@ +'Reworked from the BBC Basic example + +Public Sub Main() +Dim iNum As Integer + +For iNum = 1 To 100 + If FNisprime(iNum) Then Print iNum & " is prime" +Next + +End +'___________________________________________________ +Public Sub FNisprime(iNum As Integer) As Boolean +Dim iLoop As Integer +Dim bReturn As Boolean = True + +If iNum <= 1 Then bReturn = False +If iNum <= 3 Then bReturn = True +If (iNum And 1) = 0 Then bReturn = False + +For iLoop = 3 To Sqr(iNum) Step 2 + If iNum Mod iLoop = 0 Then bReturn = False +Next + +Return bReturn + +End diff --git a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-5.hs b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-5.hs deleted file mode 100644 index 848478cd2c..0000000000 --- a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-5.hs +++ /dev/null @@ -1,3 +0,0 @@ -import Data.List (nubBy) - -primes = nubBy (\p x -> x `mod` p == 0) [2..] diff --git a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-6.hs b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-6.hs deleted file mode 100644 index 50a2967ae8..0000000000 --- a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-6.hs +++ /dev/null @@ -1,3 +0,0 @@ -import Data.List (nubBy) - -primes = nubBy (((>1).).gcd) [2..] diff --git a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-7.hs b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-7.hs deleted file mode 100644 index ea72d1b44c..0000000000 --- a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-7.hs +++ /dev/null @@ -1,3 +0,0 @@ -primesTo m = 2 : sieve [3,5..m] where - sieve (p:xs) | p*p > m = p : xs - | otherwise = p : sieve [x | x <- xs, x `mod` p /= 0] diff --git a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-8.hs b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-8.hs deleted file mode 100644 index decfe6cdea..0000000000 --- a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-8.hs +++ /dev/null @@ -1,3 +0,0 @@ -primesT = 2 : 3 : sieve [5,7..] 9 (tail primesT) where - sieve (x:xs) q ps@(p:t) | x < q = x : sieve xs q ps - | otherwise = sieve [x | x <- xs, x `mod` p /= 0] (head t^2) t diff --git a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-9.hs b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-9.hs deleted file mode 100644 index 4cd513df69..0000000000 --- a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-9.hs +++ /dev/null @@ -1,4 +0,0 @@ -primesST = 2 : 3 : sieve 5 9 (drop 2 primesST) 0 where - sieve x q ps k = let fs = take k (tail primesST) in - filter (\x-> all ((/=0).mod x) fs) [x,x+2..q-2] - ++ sieve (q+2) (head ps^2) (tail ps) (k+1) diff --git a/Task/Primality-by-trial-division/Kotlin/primality-by-trial-division.kotlin b/Task/Primality-by-trial-division/Kotlin/primality-by-trial-division.kotlin new file mode 100644 index 0000000000..fd74342a22 --- /dev/null +++ b/Task/Primality-by-trial-division/Kotlin/primality-by-trial-division.kotlin @@ -0,0 +1,12 @@ +// version 1.1.2 +fun isPrime(n: Int): Boolean { + if (n < 2) return false + if (n % 2 == 0) return n == 2 + val limit = Math.sqrt(n.toDouble()).toInt() + return (3..limit step 2).none { n % it == 0 } +} + +fun main(args: Array) { + // test by printing all primes below 100 say + (2..99).filter { isPrime(it) }.forEach { print("$it ") } +} diff --git a/Task/Primality-by-trial-division/MAXScript/primality-by-trial-division.max b/Task/Primality-by-trial-division/MAXScript/primality-by-trial-division.max deleted file mode 100644 index 60d8f13231..0000000000 --- a/Task/Primality-by-trial-division/MAXScript/primality-by-trial-division.max +++ /dev/null @@ -1,17 +0,0 @@ - fn isPrime n = - ( - if n == 2 then - ( - return true - ) - else if (n <= 1) OR (mod n 2 == 0) then - ( - return false - ) - - for i in 3 to (sqrt n) by 2 do - ( - if mod n i == 0 then return false - ) - true - ) diff --git a/Task/Primality-by-trial-division/Perl-6/primality-by-trial-division-3.pl6 b/Task/Primality-by-trial-division/Perl-6/primality-by-trial-division-3.pl6 deleted file mode 100644 index ca4be43225..0000000000 --- a/Task/Primality-by-trial-division/Perl-6/primality-by-trial-division-3.pl6 +++ /dev/null @@ -1 +0,0 @@ -say "$_ is{ "n't" x !prime($_) } prime." for 1 .. 100; diff --git a/Task/Primality-by-trial-division/S-lang/primality-by-trial-division.slang b/Task/Primality-by-trial-division/S-lang/primality-by-trial-division.slang new file mode 100644 index 0000000000..3eed7fdad4 --- /dev/null +++ b/Task/Primality-by-trial-division/S-lang/primality-by-trial-division.slang @@ -0,0 +1,25 @@ +define is_prime(n) +{ + if (n == 2) return(1); + if (n <= 1) return(0); + if ((n & 1) == 0) return(0); + + variable mx = int(sqrt(n)), i; + + _for i (3, mx, 1) { + if ((n mod i) == 0) + return(0); + } + return(1); +} + +define ptest() +{ + variable lst = {}; + + _for $1 (1, 64, 1) + if (is_prime($1)) + list_append(lst, string($1)); + print(strjoin(list_to_array(lst), ", ")); +} +ptest(); diff --git a/Task/Primality-by-trial-division/Smalltalk/primality-by-trial-division.st b/Task/Primality-by-trial-division/Smalltalk/primality-by-trial-division.st new file mode 100644 index 0000000000..e132b843a7 --- /dev/null +++ b/Task/Primality-by-trial-division/Smalltalk/primality-by-trial-division.st @@ -0,0 +1,10 @@ +| isPrime | +isPrime := [:n | + n even ifTrue: [ ^n=2 ] + ifFalse: [ + 3 to: n sqrt do: [:i | + (n \\ i = 0) ifTrue: [ ^false ] + ]. + ^true + ] +] diff --git a/Task/Primality-by-trial-division/Zkl/primality-by-trial-division.zkl b/Task/Primality-by-trial-division/Zkl/primality-by-trial-division.zkl new file mode 100644 index 0000000000..aec50bc08c --- /dev/null +++ b/Task/Primality-by-trial-division/Zkl/primality-by-trial-division.zkl @@ -0,0 +1,4 @@ +fcn isPrime(n){ + if(n.isEven or n<2) return(n==2); + (not [3..n.toFloat().sqrt().toInt(),2].filter1('wrap(m){n%m==0})) +} diff --git a/Task/Prime-decomposition/00DESCRIPTION b/Task/Prime-decomposition/00DESCRIPTION index aa4226b773..25f26f32e2 100644 --- a/Task/Prime-decomposition/00DESCRIPTION +++ b/Task/Prime-decomposition/00DESCRIPTION @@ -21,7 +21,12 @@ Note: The program must not be limited by the word size of your computer or some ;Related tasks: -*   [[Factors of an integer]] -*   [[Primality by trial division]] +*   [[count in factors]] +*   [[factors of an integer]] *   [[Sieve of Eratosthenes]] +*   [[primality by trial division]] +*   [[factors of a Mersenne number]] +*   [[trial factoring of a Mersenne number]] +*   [[partition an integer X into N primes]] +*   [[sequence of primes by Trial Division]]

    diff --git a/Task/Prime-decomposition/Batch-File/prime-decomposition.bat b/Task/Prime-decomposition/Batch-File/prime-decomposition.bat new file mode 100644 index 0000000000..d1b2f250b3 --- /dev/null +++ b/Task/Prime-decomposition/Batch-File/prime-decomposition.bat @@ -0,0 +1,25 @@ +@echo off +::usage: cmd /k primefactor.cmd number +setlocal enabledelayedexpansion + +set /a compo=%1 +if "%compo%"=="" goto:eof +set list=%compo%= ( + +set /a div=2 & call :loopdiv +set /a div=3 & call :loopdiv +set /a div=5,inc=2 + +:looptest +call :loopdiv +set /a div+=inc,inc=6-inc,div2=div*div +if %div2% lss %compo% goto looptest +if %compo% neq 1 set list= %list% %compo% +echo %list%) & goto:eof + +:loopdiv +set /a "res=compo%%div +if %res% neq 0 goto:eof +set list=%list% %div%, +set/a compo/=div +goto:loopdiv diff --git a/Task/Prime-decomposition/jq/prime-decomposition-1.jq b/Task/Prime-decomposition/Jq/prime-decomposition-1.jq similarity index 100% rename from Task/Prime-decomposition/jq/prime-decomposition-1.jq rename to Task/Prime-decomposition/Jq/prime-decomposition-1.jq diff --git a/Task/Prime-decomposition/jq/prime-decomposition-2.jq b/Task/Prime-decomposition/Jq/prime-decomposition-2.jq similarity index 100% rename from Task/Prime-decomposition/jq/prime-decomposition-2.jq rename to Task/Prime-decomposition/Jq/prime-decomposition-2.jq diff --git a/Task/Prime-decomposition/Julia/prime-decomposition.julia b/Task/Prime-decomposition/Julia/prime-decomposition.julia index c6c4b5afbf..1d09dc828a 100644 --- a/Task/Prime-decomposition/Julia/prime-decomposition.julia +++ b/Task/Prime-decomposition/Julia/prime-decomposition.julia @@ -1,2 +1,3 @@ +julia> Pkg.add("Primes") julia> factor(8796093022207) [9719=>1,431=>1,2099863=>1] diff --git a/Task/Prime-decomposition/Kotlin/prime-decomposition.kotlin b/Task/Prime-decomposition/Kotlin/prime-decomposition.kotlin new file mode 100644 index 0000000000..c2cae2b51e --- /dev/null +++ b/Task/Prime-decomposition/Kotlin/prime-decomposition.kotlin @@ -0,0 +1,35 @@ +// version 1.0.6 + +import java.math.BigInteger + +val bigTwo = BigInteger.valueOf(2L) +val bigThree = BigInteger.valueOf(3L) + +fun getPrimeFactors(n: BigInteger): MutableList { + val factors = mutableListOf() + if (n < bigTwo) return factors + if (n.isProbablePrime(20)) { + factors.add(n) + return factors + } + var factor = bigTwo + var nn = n + while (true) { + if (nn % factor == BigInteger.ZERO) { + factors.add(factor) + nn /= factor + if (nn == BigInteger.ONE) return factors + if (nn.isProbablePrime(20)) factor = nn + } + else if (factor >= bigThree) factor += bigTwo + else factor = bigThree + } +} + +fun main(args: Array) { + val primes = intArrayOf(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) + for (prime in primes) { + val bigPow2 = bigTwo.pow(prime) - BigInteger.ONE + println("2^${"%2d".format(prime)} - 1 = ${bigPow2.toString().padEnd(30)} => ${getPrimeFactors(bigPow2)}") + } +} diff --git a/Task/Prime-decomposition/Nimrod/prime-decomposition.nimrod b/Task/Prime-decomposition/Nimrod/prime-decomposition.nimrod deleted file mode 100644 index 6c407c1f2a..0000000000 --- a/Task/Prime-decomposition/Nimrod/prime-decomposition.nimrod +++ /dev/null @@ -1,47 +0,0 @@ -import strutils, math, sequtils, times - -proc getStep(n: int64) : int64 {.inline.} = - result = 1 + n*4 - int64(n /% 2)*2 - -proc primeFac(n: int64): seq[int64] = - var res: seq[int64] = @[] - var maxq = int64(floor(sqrt(float(n)))) - var d = 1 - var q: int64 = (n %% 2) and 2 or 3 # either 2 or 3, alternating - while (q <= maxq) and ((n %% q) != 0): - q = getStep(d) - d += 1 - if q <= maxq: - var q1: seq[int64] = primeFac(n /% q) - var q2: seq[int64] = primeFac(q) - res = concat(q2, q1, res) - else: - res.add(n) - result = res - -var is_prime: seq[Bool] = @[] -is_prime.add(False) -is_prime.add(False) - -iterator primes(limit: int): int = - for n in high(is_prime) .. limit+2: is_prime.add(True) - for n in 2 .. limit + 1: - if is_prime[n]: - yield n - for i in countup((n *% n), limit+1, n): # start at ``n`` squared - try: - is_prime[i] = False - except EInvalidIndex: break - -# Example: calculate factors of Mersenne numbers to M59 # - -for m in primes(59): - var p = int64(pow(2.0,float(m)) - 1) - write(stdout,"2**$1-1 = $2, with factors: " % [$m, $p] ) - var start = cpuTime() - var f = primeFac(p) - for factor in f: - write(stdout, factor) - write(stdout, ", ") - FlushFile(stdout) - writeln(stdout, "=> $#ms" % $int(1000*(cpuTime()-start)) ) diff --git a/Task/Prime-decomposition/Phix/prime-decomposition.phix b/Task/Prime-decomposition/Phix/prime-decomposition.phix new file mode 100644 index 0000000000..821f4b79a8 --- /dev/null +++ b/Task/Prime-decomposition/Phix/prime-decomposition.phix @@ -0,0 +1,31 @@ +atom t0 = time() +include builtins\bigatom.e +constant zero = ba_new(0) + +function ba_factorise(bigatom n) +sequence res = {} +bigatom p = ba_new(2), + lim = ba_floor(ba_sqrt(n)) +integer step = 1 + + while ba_compare(p,lim)<=0 do + while ba_remainder(n,p)=zero do + res = append(res,ba_sprint(p)) + n = ba_divide(n,p) + if ba_compare(n,p)=0 then exit end if + lim = ba_floor(ba_sqrt(n)) + end while + p = ba_add(p,step) + step = 2 + end while + res = append(res,ba_sprint(n)) + return res +end function + +sequence primes = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47}--,53,59} + +for i=1 to length(primes) do + ?ba_factorise(ba_sub(ba_power(2,primes[i]),1)) +end for +?ba_factorise(ba_new("600851475143")) +?time()-t0 diff --git a/Task/Prime-decomposition/Python/prime-decomposition-3.py b/Task/Prime-decomposition/Python/prime-decomposition-3.py deleted file mode 100644 index d91a529cb5..0000000000 --- a/Task/Prime-decomposition/Python/prime-decomposition-3.py +++ /dev/null @@ -1,21 +0,0 @@ -def fac(n): - step = lambda x: 1 + x*4 - (x/2)*2 - maxq = long(math.floor(math.sqrt(n))) - d = 1 - q = n % 2 == 0 and 2 or 3 - while q <= maxq and n % q != 0: - q = step(d) - d += 1 - res = [] - if q <= maxq: - res.extend(fac(n//q)) - res.extend(fac(q)) - else: res=[n] - return res - -if __name__ == '__main__': - import time - start = time.time() - tocalc = 2**59-1 - print "%s = %s" % (tocalc, fac(tocalc)) - print "Needed %ss" % (time.time() - start) diff --git a/Task/Prime-decomposition/Ruby/prime-decomposition-5.rb b/Task/Prime-decomposition/Ruby/prime-decomposition-5.rb deleted file mode 100644 index edf0dedb33..0000000000 --- a/Task/Prime-decomposition/Ruby/prime-decomposition-5.rb +++ /dev/null @@ -1,10 +0,0 @@ -require 'benchmark' -require 'mathn' -Benchmark.bm(24) do |x| - [2**25 - 6, 2**35 - 7].each do |i| - puts "#{i} = #{prime_factors_faster(i).join(' * ')}" - x.report(" prime_factors") { prime_factors(i) } - x.report(" prime_factors_faster") { prime_factors_faster(i) } - x.report(" Integer#prime_division") { i.prime_division } - end -end diff --git a/Task/Prime-decomposition/Scala/prime-decomposition-4.scala b/Task/Prime-decomposition/Scala/prime-decomposition-4.scala deleted file mode 100644 index 459c6411ac..0000000000 --- a/Task/Prime-decomposition/Scala/prime-decomposition-4.scala +++ /dev/null @@ -1,11 +0,0 @@ -// A test -decompose(423) // Results: List(3,3,47) -decompose(423).product // Results: 423 - -// A BigInt test -decompose(BigInt("2535301200456458802993406410752")) - // Results: a list of (2)s -decompose(BigInt("2535301200456458802993406410752")).length - // Results: 101 -decompose(BigInt("2535301200456458802993406410752")).product - // Results: 2535301200456458802993406410752 diff --git a/Task/Prime-decomposition/Tcl/prime-decomposition-1.tcl b/Task/Prime-decomposition/Tcl/prime-decomposition-1.tcl index e3047bbbff..6f1beede56 100644 --- a/Task/Prime-decomposition/Tcl/prime-decomposition-1.tcl +++ b/Task/Prime-decomposition/Tcl/prime-decomposition-1.tcl @@ -1,93 +1,16 @@ -namespace eval primes {} - -proc primes::reset {} { - variable list [list] - variable current_index end -} - -namespace eval primes {reset} - -proc primes::restart {} { - variable list - variable current_index - if {[llength $list] > 0} { - set current_index 0 - } -} - -proc primes::is_prime {candidate} { - variable list - - if {$candidate in $list} {return true} - foreach prime $list { - if {$candidate % $prime == 0} { - return false - } - if {$prime * $prime > $candidate} { - return true - } - } - while true { - set largest [get_next_prime] - if {$largest * $largest >= $candidate} { - return [is_prime $candidate] - } - } -} - -proc primes::get_next_prime {} { - variable list - variable current_index - - if {$current_index ne "end"} { - set p [lindex $list $current_index] - if {[incr current_index] == [llength $list]} { - set current_index end - } - return $p - } - - switch -exact -- [llength $list] { - 0 {set candidate 2} - 1 {set candidate 3} - default { - set candidate [lindex $list end] - while true { - incr candidate 2 - if {[is_prime $candidate]} break - } - } - } - lappend list $candidate - return $candidate -} - -# return the prime factors of a number in a dictionary. -# The keys will be the factors, the value will be the number -# of times the factor divides the given number -# -# example: 120 = 2**3 * 3 * 5, so -# [primes::factors 120] returns 2 3 3 1 5 1 -# so: set prod 1 -# dict for {p e} [primes::factors 120] { -# set prod [expr {$prod * $p**$e}] -# } -# expr {$prod == 120} ;# ==> true -# -proc primes::factors {num} { - restart - set factors [dict create] - for {set i [get_next_prime]} {$i <= $num} {} { - if {$num % $i == 0} { - dict incr factors $i - set num [expr {$num / $i}] - continue - } elseif {$i*$i > $num} { - dict incr factors $num - break - } else { - set i [get_next_prime] - } - } - return $factors +proc factors {x} { + # list the prime factors of x in ascending order + set result [list] + while {$x % 2 == 0} { + lappend result 2 + set x [expr {$x / 2}] + } + for {set i 3} {$i*$i <= $x} {incr i 2} { + while {$x % $i == 0} { + lappend result $i + set x [expr {$x / $i}] + } + } + if {$x != 1} {lappend result $x} + return $result } diff --git a/Task/Prime-decomposition/Tcl/prime-decomposition-2.tcl b/Task/Prime-decomposition/Tcl/prime-decomposition-2.tcl index 9dc3f7aacb..e210e88c52 100644 --- a/Task/Prime-decomposition/Tcl/prime-decomposition-2.tcl +++ b/Task/Prime-decomposition/Tcl/prime-decomposition-2.tcl @@ -1,8 +1,5 @@ -primes::reset foreach m {2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59} { set n [expr {2**$m - 1}] - catch {time {set f [dict create {*}[primes::factors $n]]} 1} tm - set primes [list] - dict for {p e} $f {lappend primes {*}[lrepeat $e $p]} + catch {time {set primes [factors $n]} 1} tm puts [format "2**%02d-1 = %-18s = %-22s => %s" $m $n [join $primes *] $tm] } diff --git a/Task/Prime-decomposition/Zkl/prime-decomposition-1.zkl b/Task/Prime-decomposition/Zkl/prime-decomposition-1.zkl new file mode 100644 index 0000000000..cdbcad76c6 --- /dev/null +++ b/Task/Prime-decomposition/Zkl/prime-decomposition-1.zkl @@ -0,0 +1,13 @@ +fcn primeFactors(n){ // Return a list of factors of n + acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum + if(n==1 or k>maxD) acc.close(); + else{ + 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 + if(n!=m) acc.append(n/m); // opps, missed last factor + else acc; +} diff --git a/Task/Prime-decomposition/Zkl/prime-decomposition-2.zkl b/Task/Prime-decomposition/Zkl/prime-decomposition-2.zkl new file mode 100644 index 0000000000..4fc9b1a66c --- /dev/null +++ b/Task/Prime-decomposition/Zkl/prime-decomposition-2.zkl @@ -0,0 +1,4 @@ +foreach n in (T(5,12, 2147483648, 2199023255551, 8796093022207, + 9007199254740991, 576460752303423487)){ + println(n,": ",primeFactors(n).concat(", ")) +} diff --git a/Task/Prime-decomposition/Zkl/prime-decomposition-3.zkl b/Task/Prime-decomposition/Zkl/prime-decomposition-3.zkl new file mode 100644 index 0000000000..7d201118af --- /dev/null +++ b/Task/Prime-decomposition/Zkl/prime-decomposition-3.zkl @@ -0,0 +1,13 @@ +fcn factorsBI(n){ // Return a list of factors of n + acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum + if(n==1 or k>maxD) acc.close(); + else{ + q,r:=n.div2(k); // divr-->(quotient,remainder) + if(r==0) return(self.fcn(q,k,acc.write(k),q.root(2))); + return(self.fcn(n,k+1+k.isOdd,acc,maxD)) + } + }(n,2,Sink(List),n.root(2)); + m:=acc.reduce('*,BN(1)); // mulitply factors + if(n!=m) acc.append(n/m); // opps, missed last factor + else acc; +} diff --git a/Task/Prime-decomposition/Zkl/prime-decomposition-4.zkl b/Task/Prime-decomposition/Zkl/prime-decomposition-4.zkl new file mode 100644 index 0000000000..5a4fe6c230 --- /dev/null +++ b/Task/Prime-decomposition/Zkl/prime-decomposition-4.zkl @@ -0,0 +1,5 @@ +var BN=Import("zklBigNum"); +foreach n in (T(BN("12"), + BN("340282366920938463463374607431768211455"))){ + println(n,": ",factorsBI(n).concat(", ")) +} diff --git a/Task/Priority-queue/Axiom/priority-queue-3.axiom b/Task/Priority-queue/Axiom/priority-queue-3.axiom deleted file mode 100644 index 393f5b6c37..0000000000 --- a/Task/Priority-queue/Axiom/priority-queue-3.axiom +++ /dev/null @@ -1,3 +0,0 @@ - [[5,"Make tea"], [4,"Feed cat"], [3,"Clear drains"], [2,"Tax return"], - [1,"Solve RC tasks"]] - Type: List(OrderedKeyEntry(Integer,String)) diff --git a/Task/Priority-queue/C/priority-queue-1.c b/Task/Priority-queue/C/priority-queue-1.c deleted file mode 100644 index 29ffba4151..0000000000 --- a/Task/Priority-queue/C/priority-queue-1.c +++ /dev/null @@ -1,131 +0,0 @@ -#include -#include - -typedef struct { void * data; int pri; } q_elem_t; -typedef struct { q_elem_t *buf; int n, alloc; } pri_queue_t, *pri_queue; - -#define priq_purge(q) (q)->n = 1 -#define priq_size(q) ((q)->n - 1) -/* first element in array not used to simplify indices */ -pri_queue priq_new(int size) -{ - if (size < 4) size = 4; - - pri_queue q = malloc(sizeof(pri_queue_t)); - q->buf = malloc(sizeof(q_elem_t) * size); - q->alloc = size; - q->n = 1; - - return q; -} - -void priq_push(pri_queue q, void *data, int pri) -{ - q_elem_t *b; - int n, m; - - if (q->n >= q->alloc) { - q->alloc *= 2; - b = q->buf = realloc(q->buf, sizeof(q_elem_t) * q->alloc); - } else - b = q->buf; - - n = q->n++; - /* append at end, then up heap */ - while ((m = n / 2) && pri < b[m].pri) { - b[n] = b[m]; - n = m; - } - b[n].data = data; - b[n].pri = pri; -} - -/* remove top item. returns 0 if empty. *pri can be null. */ -void * priq_pop(pri_queue q, int *pri) -{ - void *out; - if (q->n == 1) return 0; - - q_elem_t *b = q->buf; - - out = b[1].data; - if (pri) *pri = b[1].pri; - - /* pull last item to top, then down heap. */ - --q->n; - - int n = 1, m; - while ((m = n * 2) < q->n) { - if (m + 1 < q->n && b[m].pri > b[m + 1].pri) m++; - - if (b[q->n].pri <= b[m].pri) break; - b[n] = b[m]; - n = m; - } - - b[n] = b[q->n]; - if (q->n < q->alloc / 2 && q->n >= 16) - q->buf = realloc(q->buf, (q->alloc /= 2) * sizeof(b[0])); - - return out; -} - -/* get the top element without removing it from queue */ -void* priq_top(pri_queue q, int *pri) -{ - if (q->n == 1) return 0; - if (pri) *pri = q->buf[1].pri; - return q->buf[1].data; -} - -/* this is O(n log n), but probably not the best */ -void priq_combine(pri_queue q, pri_queue q2) -{ - int i; - q_elem_t *e = q2->buf + 1; - - for (i = q2->n - 1; i >= 1; i--, e++) - priq_push(q, e->data, e->pri); - priq_purge(q2); -} - -int main() -{ - int i, p; - const char *c, *tasks[] ={ - "Clear drains", "Feed cat", "Make tea", "Solve RC tasks", "Tax return" }; - int pri[] = { 3, 4, 5, 1, 2 }; - - /* make two queues */ - pri_queue q = priq_new(0), q2 = priq_new(0); - - /* push all 5 tasks into q */ - for (i = 0; i < 5; i++) - priq_push(q, tasks[i], pri[i]); - - /* pop them and print one by one */ - while ((c = priq_pop(q, &p))) - printf("%d: %s\n", p, c); - - /* put a million random tasks in each queue */ - for (i = 0; i < 1 << 20; i++) { - p = rand() / ( RAND_MAX / 5 ); - priq_push(q, tasks[p], pri[p]); - - p = rand() / ( RAND_MAX / 5 ); - priq_push(q2, tasks[p], pri[p]); - } - - printf("\nq has %d items, q2 has %d items\n", priq_size(q), priq_size(q2)); - - /* merge q2 into q; q2 is empty */ - priq_combine(q, q2); - printf("After merge, q has %d items, q2 has %d items\n", - priq_size(q), priq_size(q2)); - - /* pop q until it's empty */ - for (i = 0; (c = priq_pop(q, 0)); i++); - printf("Popped %d items out of q\n", i); - - return 0; -} diff --git a/Task/Priority-queue/C/priority-queue-2.c b/Task/Priority-queue/C/priority-queue-2.c deleted file mode 100644 index 61c2df986c..0000000000 --- a/Task/Priority-queue/C/priority-queue-2.c +++ /dev/null @@ -1,9 +0,0 @@ -1: Solve RC tasks -2: Tax return -3: Clear drains -4: Feed cat -5: Make tea - -q has 1048576 items, q2 has 1048576 items -After merge, q has 2097152 items, q2 has 0 items -Popped 2097152 items out of q diff --git a/Task/Priority-queue/jq/priority-queue-1.jq b/Task/Priority-queue/Jq/priority-queue-1.jq similarity index 100% rename from Task/Priority-queue/jq/priority-queue-1.jq rename to Task/Priority-queue/Jq/priority-queue-1.jq diff --git a/Task/Priority-queue/jq/priority-queue-2.jq b/Task/Priority-queue/Jq/priority-queue-2.jq similarity index 100% rename from Task/Priority-queue/jq/priority-queue-2.jq rename to Task/Priority-queue/Jq/priority-queue-2.jq diff --git a/Task/Priority-queue/Phix/priority-queue.phix b/Task/Priority-queue/Phix/priority-queue.phix new file mode 100644 index 0000000000..477d4a5816 --- /dev/null +++ b/Task/Priority-queue/Phix/priority-queue.phix @@ -0,0 +1,54 @@ +integer tasklist = new_dict() + +procedure add_task(integer priority, string desc) + integer k = getd_index(priority,tasklist) + if k=0 then + putd(priority,{desc},tasklist) + else + sequence descs = getd_by_index(k,tasklist) + putd(priority,append(descs,desc),tasklist) + end if +end procedure + +function list_task_visitor(integer priority, sequence descs, integer /*user_data*/) + ?{priority,descs} + return 1 +end function + +procedure list_tasks() + traverse_dict(routine_id("list_task_visitor"), 0, tasklist,true) +end procedure + +function pop_task_visitor(integer priority, sequence descs, integer rid) + string desc = descs[1] + descs = descs[2..$] + if length(descs)=0 then + deld(priority,tasklist) + else + putd(priority,descs,tasklist) + end if + call_proc(rid,{priority,desc}) + return 0 +end function + +procedure pop_task(integer rid) + if dict_size(tasklist)!=0 then + traverse_dict(routine_id("pop_task_visitor"), rid, tasklist,true) + end if +end procedure + +add_task(3,"Clear drains") +add_task(4,"Feed cat") +add_task(5,"Make tea") +add_task(1,"Solve RC tasks") +add_task(2,"Tax return") + +procedure do_task(integer priority, string desc) + ?{priority,desc} +end procedure + +list_tasks() +?"===" +pop_task(routine_id("do_task")) +?"===" +list_tasks() diff --git a/Task/Priority-queue/Zkl/priority-queue-1.zkl b/Task/Priority-queue/Zkl/priority-queue-1.zkl new file mode 100644 index 0000000000..6cf0375f75 --- /dev/null +++ b/Task/Priority-queue/Zkl/priority-queue-1.zkl @@ -0,0 +1,20 @@ +class PQ{ + fcn init(numLevels=10){ // 0..numLevels, bigger # == lower priorty + var [const] queue=(1).pump(numLevels+1,List.createLong(numLevels).write,L().copy); + } + fcn add(item,priorty){ queue[priorty].append(item); } + fcn peek{ if(q:=queue.filter1()) return(q[-1]); Void }// -->Void if empty + fcn pop { if(q:=queue.filter1()) return(q.pop()); Void }// -->Void if empty + var [private] state=L(); + fcn [private] next{ // iterate + qi,ii:=state; + foreach n in ([qi..queue.len()-1]){ + q:=queue[n]; + if(ii>=q.len()) ii=0; + else{ state.clear().append(n,ii+1); return(q[ii]) } + } + Void.Stop + } + fcn walker{ state.clear().append(0,0); Walker(next) } // iterator front end + fcn toString{ "PQ(%d) items".fmt(queue.reduce(fcn(sum,q){ sum+q.len() },0)) } +} diff --git a/Task/Priority-queue/Zkl/priority-queue-2.zkl b/Task/Priority-queue/Zkl/priority-queue-2.zkl new file mode 100644 index 0000000000..55bef69824 --- /dev/null +++ b/Task/Priority-queue/Zkl/priority-queue-2.zkl @@ -0,0 +1,13 @@ +pq:=PQ(); +foreach x in + (T("Clear drains",3, "Feed cat",4, "Make tea",5, "Solve RC tasks",1, "Tax return",2, + "Clean room",10,"Wash cat",10)){ + pq.add(x,__xWalker.next()) +} +pq.println(); +println("Number 1 thing to do: ",pq.peek()); +println("Top 2 things to do: ",pq.walker().walk(2)); +println("Do this next year: ",pq.walker().walk()[-1]); +println("ToDo list:"); +foreach item in (pq){ item.println() } +pq.println(); diff --git a/Task/Probabilistic-choice/00DESCRIPTION b/Task/Probabilistic-choice/00DESCRIPTION index 66e4a3748a..9da4bdb01a 100644 --- a/Task/Probabilistic-choice/00DESCRIPTION +++ b/Task/Probabilistic-choice/00DESCRIPTION @@ -1,6 +1,6 @@ Given a mapping between items and their required probability of occurrence, generate a million items ''randomly'' subject to the given probabilities and compare the target probability of occurrence versus the generated values. -The total of all the probabilities should equal one. (Because floating point arithmetic is involved this is subject to rounding errors). +The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors). Use the following mapping to test your programs: